-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchatOrchestrator.ts
More file actions
348 lines (330 loc) · 13.3 KB
/
chatOrchestrator.ts
File metadata and controls
348 lines (330 loc) · 13.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
/**
* @description: Orchestrates universal chat requests across web and Discord surfaces.
* @footnote-scope: core
* @footnote-module: ChatOrchestrator
* @footnote-risk: high - Routing mistakes here can send the wrong action or break chat across surfaces.
* @footnote-ethics: high - This is the canonical action-selection boundary for user-facing chat behavior.
*/
import type {
PostChatRequest,
PostChatResponse,
ChatConversationMessage,
} from '@footnote/contracts/web';
import { renderConversationPromptLayers } from './prompts/conversationPromptLayers.js';
import {
createChatService,
type CreateChatServiceOptions,
} from './chatService.js';
import { createChatPlanner, type ChatPlan } from './chatPlanner.js';
import type { ChatGenerationPlan } from './chatGenerationTypes.js';
import { normalizeDiscordConversation } from './chatConversationNormalization.js';
import {
resolveActiveProfileOverlayPrompt,
resolveBotProfileDisplayName,
} from './chatProfileOverlay.js';
import { coercePlanForSurface } from './chatSurfacePolicy.js';
import { createModelProfileResolver } from './modelProfileResolver.js';
import { runtimeConfig } from '../config.js';
import { logger } from '../utils/logger.js';
type CreateChatOrchestratorOptions = CreateChatServiceOptions;
/**
* Packs the normalized planner decision into one structured system payload.
*
* JSON keeps this payload machine-stable so generation can treat planner output
* as data, not as ambiguous free-form text.
*/
const buildPlannerPayload = (
plan: ChatPlan,
surfacePolicy?: { coercedFrom: ChatPlan['action'] }
): string =>
JSON.stringify({
action: plan.action,
modality: plan.modality,
profileId: plan.profileId,
reaction: plan.reaction,
imageRequest: plan.imageRequest,
riskTier: plan.riskTier,
reasoning: plan.reasoning,
generation: plan.generation,
...(surfacePolicy && { surfacePolicy }),
});
/**
* The orchestrator keeps surface-specific policy in one place while reusing the
* shared message-generation service for any branch that ends in text output.
*/
export const createChatOrchestrator = ({
generationRuntime,
storeTrace,
buildResponseMetadata,
defaultModel = runtimeConfig.modelProfiles.defaultProfileId,
recordUsage,
}: CreateChatOrchestratorOptions) => {
const chatOrchestratorLogger =
typeof logger.child === 'function'
? logger.child({ module: 'chatOrchestrator' })
: logger;
const catalogProfiles = runtimeConfig.modelProfiles.catalog;
const enabledProfiles = catalogProfiles.filter(
(profile) => profile.enabled
);
const enabledProfilesById = new Map(
enabledProfiles.map((profile) => [profile.id, profile])
);
// Resolver remains authoritative for all profile-id/tier/raw selector
// resolution and fail-open behavior.
const modelProfileResolver = createModelProfileResolver({
catalog: catalogProfiles,
defaultProfileId: runtimeConfig.modelProfiles.defaultProfileId,
legacyDefaultModel: runtimeConfig.openai.defaultModel,
warn: chatOrchestratorLogger,
});
const plannerProfile = modelProfileResolver.resolve(
runtimeConfig.modelProfiles.plannerProfileId
);
// Startup fallback profile for end-user response generation.
// Planner may override this per-request with one catalog profile id.
const defaultResponseProfile = modelProfileResolver.resolve(defaultModel);
// Bounded profile payload sent to planner prompt context.
// Description is trimmed to keep planner context predictable.
const plannerProfileOptions = enabledProfiles.map((profile) => ({
id: profile.id,
description: profile.description.slice(0, 180),
costClass: profile.costClass,
latencyClass: profile.latencyClass,
capabilities: {
canUseSearch: profile.capabilities.canUseSearch,
},
}));
// TODO(phase-5-provider-tool-registry): Add deterministic fallback ranking
// metadata for planner/executor handoff (for example, preferred
// search-capable backup profile ids by policy).
// ChatService handles final message generation and trace/cost wiring.
const chatService = createChatService({
generationRuntime,
storeTrace,
buildResponseMetadata,
defaultModel: defaultResponseProfile.providerModel,
defaultProvider: defaultResponseProfile.provider,
defaultCapabilities: defaultResponseProfile.capabilities,
recordUsage,
});
const chatPlanner = createChatPlanner({
availableProfiles: plannerProfileOptions,
executePlanner: async ({
messages,
model,
maxOutputTokens,
reasoningEffort,
verbosity,
}) => {
// Planner calls go through the same runtime seam so model usage and
// behavior stay aligned with normal generation calls.
const plannerResult = await generationRuntime.generate({
messages,
model,
provider: plannerProfile.provider,
capabilities: plannerProfile.capabilities,
maxOutputTokens,
reasoningEffort,
verbosity,
});
return {
text: plannerResult.text,
model: plannerResult.model,
usage: plannerResult.usage,
};
},
defaultModel: plannerProfile.providerModel,
recordUsage,
});
/**
* Runs one chat request end-to-end:
* 1) normalize conversation shape by surface
* 2) plan action/modality
* 3) apply surface policy guardrails
* 4) execute message generation when action requires text output
*/
const runChat = async (
request: PostChatRequest
): Promise<PostChatResponse> => {
const normalizedConversation =
request.surface === 'discord'
? normalizeDiscordConversation(request, chatOrchestratorLogger)
: request.conversation.map(
(message: PostChatRequest['conversation'][number]) => ({
role: message.role,
content: message.content,
})
);
const normalizedRequest: PostChatRequest = {
...request,
conversation: normalizedConversation,
};
// Planner and generation both consume this normalized request shape.
const botProfileDisplayName = resolveBotProfileDisplayName();
const planned = await chatPlanner.planChat(normalizedRequest);
const { plan, surfacePolicy } = coercePlanForSurface(
normalizedRequest,
planned,
chatOrchestratorLogger
);
// Planner-selected profile is advisory.
// Runtime resolution here is authoritative and fail-open.
let selectedResponseProfile = defaultResponseProfile;
if (plan.profileId) {
const selectedProfile = enabledProfilesById.get(plan.profileId);
if (selectedProfile) {
selectedResponseProfile = selectedProfile;
} else {
chatOrchestratorLogger.warn(
'planner selected invalid or disabled profile id; falling back to default profile',
{
selectedProfileId: plan.profileId,
defaultProfileId: defaultResponseProfile.id,
surface: normalizedRequest.surface,
}
);
}
}
// Keep selected profile, but drop search when profile capabilities do
// not allow it. This avoids silently forcing a different model.
let generationForExecution: ChatGenerationPlan = plan.generation;
if (
generationForExecution.search &&
!selectedResponseProfile.capabilities.canUseSearch
) {
// TODO: Before dropping search, attempt rerouting to a search-capable profile. Emit structured fields for observability, maybe:
// - searchFallbackApplied
// - originalProfileId
// - effectiveProfileId
generationForExecution = {
...generationForExecution,
search: undefined,
};
chatOrchestratorLogger.warn(
'planner requested search but selected profile does not support search; running without search',
{
selectedProfileId: selectedResponseProfile.id,
surface: normalizedRequest.surface,
}
);
}
// Persist the effective profile id in planner payload/snapshot so traces
// reflect what was actually executed.
const executionPlan: ChatPlan = {
...plan,
generation: generationForExecution,
profileId: selectedResponseProfile.id,
};
// Non-message actions return early and skip model generation.
if (executionPlan.action === 'ignore') {
return {
action: 'ignore',
metadata: null,
};
}
if (executionPlan.action === 'react') {
return {
action: 'react',
reaction: executionPlan.reaction ?? '👍',
metadata: null,
};
}
if (executionPlan.action === 'image' && executionPlan.imageRequest) {
return {
action: 'image',
imageRequest: executionPlan.imageRequest,
metadata: null,
};
}
if (executionPlan.action === 'image' && !executionPlan.imageRequest) {
// Invalid image action should not block response flow.
chatOrchestratorLogger.warn(
`Chat planner returned image without imageRequest; falling back to ignore. surface=${normalizedRequest.surface} trigger=${normalizedRequest.trigger.kind} latestUserInputLength=${normalizedRequest.latestUserInput.length}`
);
return {
action: 'ignore',
metadata: null,
};
}
const promptLayers = renderConversationPromptLayers(
normalizedRequest.surface === 'discord'
? 'discord-chat'
: 'web-chat',
{
botProfileDisplayName,
}
);
const backendOwnedProfileOverlay =
normalizedRequest.surface === 'discord'
? resolveActiveProfileOverlayPrompt(
normalizedRequest,
chatOrchestratorLogger
)
: null;
// Discord can inject backend-owned runtime overlay text.
// Web keeps default prompt persona layers.
const personaPrompt =
backendOwnedProfileOverlay ?? promptLayers.personaPrompt;
// Planner output is injected as a final system message so generation
// can follow one backend-owned decision payload.
const conversationMessages: Array<
Pick<ChatConversationMessage, 'role' | 'content'>
> = [
{
role: 'system',
content: promptLayers.systemPrompt,
},
{
role: 'system',
content: personaPrompt,
},
...normalizedConversation,
{
role: 'system',
content: [
'// ==========',
'// BEGIN Planner Output',
'// This planner decision was made by the backend and should be treated as authoritative for this response.',
'// ==========',
buildPlannerPayload(executionPlan, surfacePolicy),
'// ==========',
'// END Planner Output',
'// ==========',
].join('\n'),
},
];
// Generation receives resolved provider/capabilities from the active
// default model profile instead of relying on provider-name checks.
const response = await chatService.runChatMessages({
messages: conversationMessages,
conversationSnapshot: JSON.stringify({
request: normalizedRequest,
planner: {
action: executionPlan.action,
modality: executionPlan.modality,
profileId: executionPlan.profileId,
riskTier: executionPlan.riskTier,
generation: executionPlan.generation,
...(surfacePolicy && { surfacePolicy }),
},
}),
plannerTemperament: executionPlan.generation.temperament,
riskTier: executionPlan.riskTier,
model: selectedResponseProfile.providerModel,
provider: selectedResponseProfile.provider,
capabilities: selectedResponseProfile.capabilities,
generation: executionPlan.generation,
});
// Message action is the only branch that returns provenance metadata.
return {
action: 'message',
message: response.message,
modality: executionPlan.modality,
metadata: response.metadata,
};
};
return {
runChat,
};
};