@memberjunction/ai-agents 5.40.1 → 5.41.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/README.md +45 -0
  2. package/dist/AgentRunner.d.ts +5 -2
  3. package/dist/AgentRunner.d.ts.map +1 -1
  4. package/dist/AgentRunner.js +14 -4
  5. package/dist/AgentRunner.js.map +1 -1
  6. package/dist/MemoryWriteManager.d.ts +188 -0
  7. package/dist/MemoryWriteManager.d.ts.map +1 -0
  8. package/dist/MemoryWriteManager.js +299 -0
  9. package/dist/MemoryWriteManager.js.map +1 -0
  10. package/dist/agent-context-injector.d.ts +29 -0
  11. package/dist/agent-context-injector.d.ts.map +1 -1
  12. package/dist/agent-context-injector.js +90 -32
  13. package/dist/agent-context-injector.js.map +1 -1
  14. package/dist/agent-memory-context-builder.d.ts +100 -0
  15. package/dist/agent-memory-context-builder.d.ts.map +1 -0
  16. package/dist/agent-memory-context-builder.js +172 -0
  17. package/dist/agent-memory-context-builder.js.map +1 -0
  18. package/dist/agent-types/index.d.ts +1 -0
  19. package/dist/agent-types/index.d.ts.map +1 -1
  20. package/dist/agent-types/index.js +1 -0
  21. package/dist/agent-types/index.js.map +1 -1
  22. package/dist/agent-types/loop-agent-response-type.d.ts +12 -1
  23. package/dist/agent-types/loop-agent-response-type.d.ts.map +1 -1
  24. package/dist/agent-types/loop-agent-response-type.js.map +1 -1
  25. package/dist/agent-types/loop-agent-type.d.ts.map +1 -1
  26. package/dist/agent-types/loop-agent-type.js +4 -0
  27. package/dist/agent-types/loop-agent-type.js.map +1 -1
  28. package/dist/agent-types/realtime-agent-type.d.ts +146 -0
  29. package/dist/agent-types/realtime-agent-type.d.ts.map +1 -0
  30. package/dist/agent-types/realtime-agent-type.js +176 -0
  31. package/dist/agent-types/realtime-agent-type.js.map +1 -0
  32. package/dist/base-agent.d.ts +365 -24
  33. package/dist/base-agent.d.ts.map +1 -1
  34. package/dist/base-agent.js +995 -175
  35. package/dist/base-agent.js.map +1 -1
  36. package/dist/index.d.ts +11 -0
  37. package/dist/index.d.ts.map +1 -1
  38. package/dist/index.js +15 -0
  39. package/dist/index.js.map +1 -1
  40. package/dist/memory-manager-agent.d.ts +55 -2
  41. package/dist/memory-manager-agent.d.ts.map +1 -1
  42. package/dist/memory-manager-agent.js +261 -62
  43. package/dist/memory-manager-agent.js.map +1 -1
  44. package/dist/realtime/meeting-controls-channel-server.d.ts +198 -0
  45. package/dist/realtime/meeting-controls-channel-server.d.ts.map +1 -0
  46. package/dist/realtime/meeting-controls-channel-server.js +319 -0
  47. package/dist/realtime/meeting-controls-channel-server.js.map +1 -0
  48. package/dist/realtime/meeting-controls-state.d.ts +191 -0
  49. package/dist/realtime/meeting-controls-state.d.ts.map +1 -0
  50. package/dist/realtime/meeting-controls-state.js +219 -0
  51. package/dist/realtime/meeting-controls-state.js.map +1 -0
  52. package/dist/realtime/realtime-channel-server-host.d.ts +166 -0
  53. package/dist/realtime/realtime-channel-server-host.d.ts.map +1 -0
  54. package/dist/realtime/realtime-channel-server-host.js +378 -0
  55. package/dist/realtime/realtime-channel-server-host.js.map +1 -0
  56. package/dist/realtime/realtime-client-session-service.d.ts +884 -0
  57. package/dist/realtime/realtime-client-session-service.d.ts.map +1 -0
  58. package/dist/realtime/realtime-client-session-service.js +1401 -0
  59. package/dist/realtime/realtime-client-session-service.js.map +1 -0
  60. package/dist/realtime/realtime-coagent-config.d.ts +202 -0
  61. package/dist/realtime/realtime-coagent-config.d.ts.map +1 -0
  62. package/dist/realtime/realtime-coagent-config.js +334 -0
  63. package/dist/realtime/realtime-coagent-config.js.map +1 -0
  64. package/dist/realtime/realtime-narration.d.ts +67 -0
  65. package/dist/realtime/realtime-narration.d.ts.map +1 -0
  66. package/dist/realtime/realtime-narration.js +127 -0
  67. package/dist/realtime/realtime-narration.js.map +1 -0
  68. package/dist/realtime/realtime-session-runner.d.ts +383 -0
  69. package/dist/realtime/realtime-session-runner.d.ts.map +1 -0
  70. package/dist/realtime/realtime-session-runner.js +532 -0
  71. package/dist/realtime/realtime-session-runner.js.map +1 -0
  72. package/dist/realtime/realtime-tool-broker.d.ts +279 -0
  73. package/dist/realtime/realtime-tool-broker.d.ts.map +1 -0
  74. package/dist/realtime/realtime-tool-broker.js +184 -0
  75. package/dist/realtime/realtime-tool-broker.js.map +1 -0
  76. package/dist/realtime/whiteboard-channel-server.d.ts +50 -0
  77. package/dist/realtime/whiteboard-channel-server.d.ts.map +1 -0
  78. package/dist/realtime/whiteboard-channel-server.js +85 -0
  79. package/dist/realtime/whiteboard-channel-server.js.map +1 -0
  80. package/package.json +17 -17
@@ -0,0 +1,1401 @@
1
+ /**
2
+ * @fileoverview Server-agnostic preparer + tool relay for a CLIENT-DIRECT realtime session
3
+ * (the Realtime Co-Agent dual-topology design).
4
+ *
5
+ * In the client-direct topology the browser opens its OWN provider socket (e.g. WebRTC) using a
6
+ * server-minted ephemeral token, but the **server** still owns the system prompt and tool set and
7
+ * **executes** every tool call the browser relays back. This service is the server-side half of
8
+ * that contract. It does two things:
9
+ *
10
+ * 1. {@link RealtimeClientSessionService.PrepareClientSession} — resolves the Realtime model,
11
+ * assembles the companion system prompt (co-agent prompt + target identity + history + memory),
12
+ * builds the stable, target-independent tool set (always including `invoke-target-agent`), and
13
+ * asks the model to mint a {@link ClientRealtimeSessionConfig} (ephemeral token + provider
14
+ * session config) the browser applies verbatim.
15
+ * 2. {@link RealtimeClientSessionService.ExecuteRelayedTool} — executes a single tool call the
16
+ * browser relayed, routing it through the shared {@link RealtimeToolBroker} so the result is
17
+ * byte-for-byte identical to the server-bridged path. `invoke-target-agent` delegates to the
18
+ * target agent via {@link AgentRunner.RunAgent}; every other tool returns a structured
19
+ * "not available" result for now (action wiring is a later phase).
20
+ *
21
+ * **Why this duplicates BaseAgent.** The private helpers in `BaseAgent.executeRealtimeSession`
22
+ * (model resolution, companion-prompt assembly, target-agent resolution, delegation) are the
23
+ * server-bridged equivalents of the logic here, but they are `private` to `BaseAgent` and bound to
24
+ * an in-flight `AIAgentRun`/`StartSession` lifecycle. This service mirrors that logic for the
25
+ * client-direct topology, which has no server-side session loop. **A future refactor should extract
26
+ * a shared `RealtimeSessionPreparer`** that both `BaseAgent` and this service consume, eliminating
27
+ * the duplication. Until then, keep the two in sync intentionally.
28
+ *
29
+ * @module @memberjunction/ai-agents
30
+ * @author MemberJunction.com
31
+ */
32
+ import { LogError, LogStatus } from '@memberjunction/core';
33
+ import { MJGlobal, UUIDsEqual } from '@memberjunction/global';
34
+ import { BaseRealtimeModel, GetAIAPIKey } from '@memberjunction/ai';
35
+ import { AIEngine } from '@memberjunction/aiengine';
36
+ import { AgentMemoryContextBuilder } from '../agent-memory-context-builder.js';
37
+ import { AgentRunner } from '../AgentRunner.js';
38
+ import { RealtimeToolBroker, INVOKE_TARGET_AGENT_TOOL_NAME } from './realtime-tool-broker.js';
39
+ import { NARRATION_PROMPT_NAME, LEGACY_NARRATION_PROMPT_NAME, ResolveNarrationInstructionsTemplate } from './realtime-narration.js';
40
+ import { BuildVoiceMannerSection, DeepMergeConfigs, GetNarrationPaceMs, GetProviderVoiceSettings, ResolveEffectiveRealtimeConfig } from './realtime-coagent-config.js';
41
+ /**
42
+ * Server-agnostic service that prepares a client-direct realtime session and executes the tool
43
+ * calls the browser relays back. Constructed per-request (a normal injectable service — NOT a
44
+ * singleton) so the {@link UserInfo} and {@link IMetadataProvider} are always request-scoped.
45
+ *
46
+ * Every public method takes the `contextUser` and `provider` explicitly — this service never
47
+ * reaches for the global default provider, so it is safe in multi-provider/multi-tenant servers.
48
+ */
49
+ export class RealtimeClientSessionService {
50
+ constructor() {
51
+ /**
52
+ * IN-FLIGHT DELEGATION REGISTRY — the server half of the client-direct CANCEL channel.
53
+ *
54
+ * Every relayed tool call registers an {@link AbortController} under
55
+ * `(agentSessionID, callID)` for the duration of {@link ExecuteRelayedTool}; the
56
+ * `CancelRealtimeSessionTool` mutation aborts entries via
57
+ * {@link CancelInFlightDelegations} so an explicit user cancel (the overlay's per-card ✕)
58
+ * kills the delegated target-agent run mid-flight. Entries are removed on completion
59
+ * (success, failure, or abort), so the registry only ever holds truly in-flight calls.
60
+ *
61
+ * Keys are normalized (trimmed, lowercased) so SQL Server's uppercase UUIDs and
62
+ * PostgreSQL's lowercase UUIDs address the same entry.
63
+ *
64
+ * NOTE: this registry is per-service-instance state (the resolver holds ONE shared service
65
+ * per server process), not per-request state — it deliberately spans requests so the cancel
66
+ * mutation can reach the execute mutation's in-flight controller.
67
+ */
68
+ this.inFlightDelegations = new Map();
69
+ /**
70
+ * Per-`AIPromptRun` write serialization. Both the high-frequency usage checkpoint
71
+ * ({@link AccumulatePromptRunUsage}) and the per-turn message append ({@link AppendPromptRunMessage})
72
+ * do load-modify-save on the SAME run row. Run concurrently, the frequent usage save would rewrite the
73
+ * whole row — including the STALE `Messages` it loaded — and perpetually clobber freshly-appended turns
74
+ * back to an empty snapshot (the "transcript never persists" bug). Funnelling every write for a given
75
+ * run through a single promise chain makes each load happen AFTER the prior save committed, so no writer
76
+ * overwrites another's field. Keyed by promptRunID; the entry is dropped on {@link finalizePromptRun}.
77
+ */
78
+ this.promptRunWriteChains = new Map();
79
+ }
80
+ /**
81
+ * The seeded name of the `MJ: AI Prompts` row whose `TemplateText` carries the first-person
82
+ * progress-narration instructions (with a `{{ progressMessage }}` placeholder). Resolved at
83
+ * session prepare time so the browser narrates with DB-driven, product-tunable wording.
84
+ * Canonical value lives in `realtime-narration.ts` (shared with the server-bridged runner path).
85
+ */
86
+ static { this.NarrationPromptName = NARRATION_PROMPT_NAME; }
87
+ /**
88
+ * DEPRECATED legacy name of the narration prompt, from before the co-agent's rename from
89
+ * "Voice Co-Agent" to "Realtime Co-Agent". Deployments that have not re-synced the prompt seed
90
+ * still carry this name, so {@link resolveNarrationInstructionsTemplate} falls back to it
91
+ * (with a deprecation log) when {@link RealtimeClientSessionService.NarrationPromptName} is absent.
92
+ */
93
+ static { this.LegacyNarrationPromptName = LEGACY_NARRATION_PROMPT_NAME; }
94
+ /**
95
+ * Serializes `task` against all other writes to the same `AIPromptRun` (see {@link promptRunWriteChains}).
96
+ * Tasks run in call order; a failing task never breaks the chain for the next one. Returns the task's result.
97
+ */
98
+ serializePromptRunWrite(promptRunID, task) {
99
+ const prior = this.promptRunWriteChains.get(promptRunID) ?? Promise.resolve();
100
+ const run = prior.then(task, task);
101
+ // Store an error-swallowing tail so one failed write doesn't reject every queued write behind it.
102
+ this.promptRunWriteChains.set(promptRunID, run.then(() => undefined, () => undefined));
103
+ return run;
104
+ }
105
+ /**
106
+ * Prepares a client-direct realtime session: resolves the model, assembles the companion
107
+ * system prompt + stable tool set, and mints the {@link ClientRealtimeSessionConfig}.
108
+ *
109
+ * Returns a failure result (never throws) when no Realtime model/key resolves or the provider
110
+ * cannot mint a client-direct session.
111
+ *
112
+ * @param input The co-agent/target/session inputs.
113
+ * @param contextUser The calling user (threaded to metadata + memory retrieval).
114
+ * @param provider The request-scoped metadata provider.
115
+ * @returns The prep result (Success + ClientConfig/SessionParams, or Success: false + ErrorMessage).
116
+ */
117
+ async PrepareClientSession(input, contextUser, provider) {
118
+ await this.configureEngine(contextUser, provider);
119
+ const coAgent = this.resolveCoAgent(input);
120
+ if (!coAgent) {
121
+ return { Success: false, ErrorMessage: 'The Realtime Co-Agent could not be resolved from the supplied id or entity.' };
122
+ }
123
+ // Effective config: type DefaultConfiguration ← agent TypeConfiguration ← runtime
124
+ // overrides (already authorization-gated upstream). Drives model preference, voice
125
+ // persona/provider settings, and narration pacing below.
126
+ const effectiveConfig = this.resolveEffectiveConfig(coAgent, input.ConfigOverridesJson);
127
+ const outcome = await this.resolveModelForSession(input, coAgent, effectiveConfig);
128
+ if (!outcome.Resolution) {
129
+ return { Success: false, ErrorMessage: outcome.ErrorMessage ?? this.noModelMessage() };
130
+ }
131
+ const resolution = outcome.Resolution;
132
+ if (!resolution.Model.SupportsClientDirect) {
133
+ return {
134
+ Success: false,
135
+ ErrorMessage: `The resolved realtime model '${resolution.APIName}' does not support client-direct sessions.`
136
+ };
137
+ }
138
+ const sessionParams = await this.buildSessionParams(input, coAgent, resolution.APIName, contextUser, provider, effectiveConfig, resolution.DriverClass);
139
+ let clientConfig;
140
+ try {
141
+ clientConfig = await resolution.Model.CreateClientSession(sessionParams);
142
+ }
143
+ catch (error) {
144
+ const message = error instanceof Error ? error.message : String(error);
145
+ return { Success: false, ErrorMessage: `Failed to mint client realtime session: ${message}` };
146
+ }
147
+ // Best-effort observability: create a server-side co-agent run (+ prompt run) so the voice
148
+ // session is visible in the agent-run timeline and delegated runs can nest under it. A
149
+ // failure here never fails the prepare — we just omit the ids.
150
+ const promptID = this.resolveCoAgentSystemPrompt(coAgent).PromptID;
151
+ const obs = await this.createCoAgentObservabilityRun(coAgent, promptID, resolution.ModelID, resolution.VendorID, input.UserID || contextUser?.ID, input.AgentSessionID, contextUser, provider, input.ConversationID);
152
+ return {
153
+ Success: true,
154
+ ClientConfig: clientConfig,
155
+ SessionParams: sessionParams,
156
+ CoAgentRunID: obs?.CoAgentRunID,
157
+ PromptRunID: obs?.PromptRunID,
158
+ CoAgentRunStepID: obs?.CoAgentRunStepID,
159
+ ModelID: resolution.ModelID,
160
+ ModelName: resolution.ModelName,
161
+ NarrationInstructionsTemplate: this.resolveNarrationInstructionsTemplate() ?? undefined,
162
+ EffectiveConfig: effectiveConfig,
163
+ NarrationPaceMs: GetNarrationPaceMs(effectiveConfig) ?? undefined,
164
+ };
165
+ }
166
+ /**
167
+ * Resolves the EFFECTIVE realtime configuration for a co-agent: the agent TYPE's
168
+ * `DefaultConfiguration` (base) ← the agent's `TypeConfiguration` ← the (pre-authorized)
169
+ * runtime overrides — deep-merged per key and normalized. Tolerant end-to-end: malformed
170
+ * layers contribute nothing and an unloaded metadata cache yields no type defaults.
171
+ *
172
+ * @param coAgent The resolved co-agent.
173
+ * @param overridesJson The pre-authorized runtime override layer, when present.
174
+ * @returns The normalized effective configuration (possibly empty, never `null`).
175
+ */
176
+ resolveEffectiveConfig(coAgent, overridesJson) {
177
+ return ResolveEffectiveRealtimeConfig(this.getAgentTypeDefaultConfiguration(coAgent), coAgent.TypeConfiguration ?? null, overridesJson ?? null);
178
+ }
179
+ /**
180
+ * Reads the co-agent's TYPE-level `DefaultConfiguration` from {@link AIEngine}'s cached agent
181
+ * types. **Overridable seam**; tolerant — an absent type or unloaded cache returns `null`.
182
+ */
183
+ getAgentTypeDefaultConfiguration(coAgent) {
184
+ try {
185
+ if (!coAgent.TypeID) {
186
+ return null;
187
+ }
188
+ const type = (AIEngine.Instance.AgentTypes ?? []).find(t => UUIDsEqual(t.ID, coAgent.TypeID));
189
+ return type?.DefaultConfiguration ?? null;
190
+ }
191
+ catch {
192
+ return null;
193
+ }
194
+ }
195
+ /**
196
+ * Creates the server-side co-agent observability runs for a voice session: an `AIAgentRun`
197
+ * (Status `Running`), and — when a co-agent system prompt resolved — a linked `AIPromptRun`
198
+ * (Status `Running`, `AgentRunID` = the co-agent run, `AgentID` = the co-agent) plus a single
199
+ * `MJ: AI Agent Run Steps` row (StepType `Prompt`) so the co-agent run's Timeline is non-empty.
200
+ * Delegated target-agent runs nest under the returned `CoAgentRunID` via `ParentRunID`.
201
+ *
202
+ * Best-effort: returns `null` (and logs) when the co-agent run cannot be saved, so callers can
203
+ * continue without observability rather than failing the whole prepare. A failed prompt-run or
204
+ * run-step save just omits that id.
205
+ *
206
+ * @param coAgent The resolved co-agent (its id stamps `AgentID` on both runs).
207
+ * @param promptID The co-agent system prompt id, or `null` to skip the prompt run + run step.
208
+ * @param modelID The resolved realtime model id (stamps the prompt run's `ModelID`).
209
+ * @param userID Optional owning user id for the agent run.
210
+ * @param agentSessionID The session id grouping this voice session's runs.
211
+ * @param contextUser The calling user.
212
+ * @param provider The request-scoped metadata provider.
213
+ * @returns The `{ CoAgentRunID, PromptRunID, CoAgentRunStepID }` ids, or `null` when the agent run failed.
214
+ */
215
+ async createCoAgentObservabilityRun(coAgent, promptID, modelID, vendorID, userID, agentSessionID, contextUser, provider, conversationID) {
216
+ const coAgentRunID = await this.createCoAgentRun(coAgent, userID, agentSessionID, conversationID, contextUser, provider);
217
+ if (!coAgentRunID) {
218
+ return null;
219
+ }
220
+ const promptRunID = await this.createCoAgentPromptRun(coAgent, promptID, modelID, vendorID, coAgentRunID, contextUser, provider);
221
+ const runStepID = await this.createCoAgentRunStep(coAgentRunID, promptID, promptRunID, contextUser, provider);
222
+ return { CoAgentRunID: coAgentRunID, PromptRunID: promptRunID ?? undefined, CoAgentRunStepID: runStepID ?? undefined };
223
+ }
224
+ /**
225
+ * Creates the co-agent `AIAgentRun` row (Status `Running`). Returns its id, or `null` (logging
226
+ * `CompleteMessage`) when the save fails.
227
+ */
228
+ async createCoAgentRun(coAgent, userID, agentSessionID, conversationID, contextUser, provider) {
229
+ const run = await provider.GetEntityObject('MJ: AI Agent Runs', contextUser);
230
+ run.NewRecord();
231
+ run.AgentID = coAgent.ID;
232
+ run.Status = 'Running';
233
+ run.StartedAt = new Date();
234
+ run.AgentSessionID = agentSessionID;
235
+ if (conversationID) {
236
+ run.ConversationID = conversationID;
237
+ }
238
+ if (userID) {
239
+ run.UserID = userID;
240
+ }
241
+ if (await run.Save()) {
242
+ return run.ID;
243
+ }
244
+ LogError(`RealtimeClientSessionService.createCoAgentRun save failed: ${run.LatestResult?.CompleteMessage ?? 'unknown error'}`);
245
+ return null;
246
+ }
247
+ /**
248
+ * Creates the co-agent `AIPromptRun` row (Status `Running`) linked to the co-agent run via
249
+ * `AgentRunID` AND to the co-agent itself via `AgentID` — so the run shows up both on the
250
+ * prompt's run history (`PromptID`) and in agent-scoped prompt-run views. Returns its id, or
251
+ * `null` when `promptID` is absent (skipped) or the save fails (logged).
252
+ */
253
+ async createCoAgentPromptRun(coAgent, promptID, modelID, vendorID, coAgentRunID, contextUser, provider) {
254
+ if (!promptID) {
255
+ return null;
256
+ }
257
+ const promptRun = await provider.GetEntityObject('MJ: AI Prompt Runs', contextUser);
258
+ promptRun.NewRecord();
259
+ promptRun.PromptID = promptID;
260
+ promptRun.ModelID = modelID;
261
+ // VendorID is required on AIPromptRun ("Vendor cannot be null") — without it the prompt run
262
+ // save fails and the whole co-agent observability chain (transcript/tool-turn/usage) is dropped.
263
+ if (vendorID) {
264
+ promptRun.VendorID = vendorID;
265
+ }
266
+ promptRun.AgentID = coAgent.ID;
267
+ promptRun.RunAt = new Date();
268
+ promptRun.RunType = 'Single';
269
+ promptRun.Status = 'Running';
270
+ promptRun.AgentRunID = coAgentRunID;
271
+ if (await promptRun.Save()) {
272
+ return promptRun.ID;
273
+ }
274
+ LogError(`RealtimeClientSessionService.createCoAgentPromptRun save failed: ${promptRun.LatestResult?.CompleteMessage ?? 'unknown error'}`);
275
+ return null;
276
+ }
277
+ /**
278
+ * Creates the single `MJ: AI Agent Run Steps` row for the co-agent observability run — the
279
+ * realtime session has no iterative loop, so its Timeline carries exactly one step
280
+ * representing the session's system prompt (StepNumber 1, StepType `Prompt`, Status `Running`,
281
+ * `TargetID` = the system `AIPrompt`, `TargetLogID` = the linked `AIPromptRun` when one was
282
+ * created). Skipped (returns `null`) when no system prompt resolved. Best-effort: a save
283
+ * failure is logged and returns `null` — it never breaks the session.
284
+ */
285
+ async createCoAgentRunStep(coAgentRunID, promptID, promptRunID, contextUser, provider) {
286
+ if (!promptID) {
287
+ return null;
288
+ }
289
+ try {
290
+ const step = await provider.GetEntityObject('MJ: AI Agent Run Steps', contextUser);
291
+ step.NewRecord();
292
+ step.AgentRunID = coAgentRunID;
293
+ step.StepNumber = 1;
294
+ step.StepType = 'Prompt';
295
+ step.StepName = 'Realtime session system prompt';
296
+ step.TargetID = promptID;
297
+ step.TargetLogID = promptRunID;
298
+ step.Status = 'Running';
299
+ step.StartedAt = new Date();
300
+ if (await step.Save()) {
301
+ return step.ID;
302
+ }
303
+ LogError(`RealtimeClientSessionService.createCoAgentRunStep save failed: ${step.LatestResult?.CompleteMessage ?? 'unknown error'}`);
304
+ return null;
305
+ }
306
+ catch (error) {
307
+ LogError(`RealtimeClientSessionService.createCoAgentRunStep failed: ${error instanceof Error ? error.message : String(error)}`);
308
+ return null;
309
+ }
310
+ }
311
+ /**
312
+ * Finalizes the server-side co-agent observability records when a voice session ends. Loads
313
+ * each (when its id is supplied) and, **only if it is still `Running`**, sets it to `Completed`
314
+ * (or `Failed` when `success` is false) with a `CompletedAt` + `Success` stamp. Idempotent and
315
+ * tolerant: a missing/already-finalized record is a no-op; a load/save failure is logged,
316
+ * never thrown.
317
+ *
318
+ * @param coAgentRunID The co-agent run id, or `null` to skip.
319
+ * @param promptRunID The co-agent prompt run id, or `null` to skip.
320
+ * @param contextUser The calling user.
321
+ * @param provider The request-scoped metadata provider.
322
+ * @param success Whether the session ended successfully (controls Completed vs Failed).
323
+ * @param coAgentRunStepID The co-agent run's single `MJ: AI Agent Run Steps` row id, or `null` to skip.
324
+ */
325
+ async FinalizeCoAgentRun(coAgentRunID, promptRunID, contextUser, provider, success = true, coAgentRunStepID = null) {
326
+ await this.finalizeAgentRun(coAgentRunID, contextUser, provider, success);
327
+ await this.finalizePromptRun(promptRunID, contextUser, provider, success);
328
+ await this.finalizeRunStep(coAgentRunStepID, contextUser, provider, success);
329
+ }
330
+ /** Loads + finalizes the co-agent `AIAgentRun` if still `Running`. Tolerant: logs, never throws. */
331
+ async finalizeAgentRun(coAgentRunID, contextUser, provider, success) {
332
+ if (!coAgentRunID) {
333
+ return;
334
+ }
335
+ const run = await provider.GetEntityObject('MJ: AI Agent Runs', contextUser);
336
+ if (!(await run.Load(coAgentRunID)) || run.Status !== 'Running') {
337
+ return;
338
+ }
339
+ run.Status = success ? 'Completed' : 'Failed';
340
+ run.CompletedAt = new Date();
341
+ run.Success = success;
342
+ if (!(await run.Save())) {
343
+ LogError(`RealtimeClientSessionService.finalizeAgentRun save failed: ${run.LatestResult?.CompleteMessage ?? 'unknown error'}`);
344
+ }
345
+ }
346
+ /**
347
+ * Loads + finalizes the co-agent run's single system-prompt `MJ: AI Agent Run Steps` row if
348
+ * still `Running` (Status `Completed`/`Failed`, `CompletedAt`, `Success`). Tolerant: a
349
+ * missing/already-finalized step is a no-op; a load/save failure is logged, never thrown.
350
+ */
351
+ async finalizeRunStep(coAgentRunStepID, contextUser, provider, success) {
352
+ if (!coAgentRunStepID) {
353
+ return;
354
+ }
355
+ try {
356
+ const step = await provider.GetEntityObject('MJ: AI Agent Run Steps', contextUser);
357
+ if (!(await step.Load(coAgentRunStepID)) || step.Status !== 'Running') {
358
+ return;
359
+ }
360
+ step.Status = success ? 'Completed' : 'Failed';
361
+ step.CompletedAt = new Date();
362
+ step.Success = success;
363
+ if (!success) {
364
+ step.ErrorMessage = 'The realtime session ended in an error state.';
365
+ }
366
+ if (!(await step.Save())) {
367
+ LogError(`RealtimeClientSessionService.finalizeRunStep save failed: ${step.LatestResult?.CompleteMessage ?? 'unknown error'}`);
368
+ }
369
+ }
370
+ catch (error) {
371
+ LogError(`RealtimeClientSessionService.finalizeRunStep failed: ${error instanceof Error ? error.message : String(error)}`);
372
+ }
373
+ }
374
+ /** Loads + finalizes the co-agent `AIPromptRun` if still `Running`. Tolerant: logs, never throws. */
375
+ async finalizePromptRun(promptRunID, contextUser, provider, success) {
376
+ if (!promptRunID) {
377
+ return;
378
+ }
379
+ // Serialize the finalize against any in-flight message/usage writes so it can't race them — and so a
380
+ // late usage flush queued behind it sees the run already Completed.
381
+ await this.serializePromptRunWrite(promptRunID, async () => {
382
+ const run = await provider.GetEntityObject('MJ: AI Prompt Runs', contextUser);
383
+ if (!(await run.Load(promptRunID)) || run.Status !== 'Running') {
384
+ return false;
385
+ }
386
+ run.Status = success ? 'Completed' : 'Failed';
387
+ run.CompletedAt = new Date();
388
+ run.Success = success;
389
+ if (!(await run.Save())) {
390
+ LogError(`RealtimeClientSessionService.finalizePromptRun save failed: ${run.LatestResult?.CompleteMessage ?? 'unknown error'}`);
391
+ }
392
+ return true;
393
+ });
394
+ // Drop the per-run lock chain — no further writes are expected after finalize.
395
+ this.promptRunWriteChains.delete(promptRunID);
396
+ }
397
+ /**
398
+ * Appends (or replaces) one transcript turn onto the co-agent's long-lived `AIPromptRun.Messages`,
399
+ * so the realtime co-agent's conversation is captured on its run exactly like every other MJ agent
400
+ * run — closing the observability gap where the run held only token totals, never the turns. The
401
+ * run viewer can then show what the co-agent heard and said. Mirrors {@link accumulatePromptRunUsage}'s
402
+ * load/append/save pattern; best-effort and tolerant (logs, never throws).
403
+ *
404
+ * `replacePrevious` swaps the last same-role message instead of appending — the streaming-correction
405
+ * case (an interim assistant turn finalized into its full text). The stored shape is the standard
406
+ * chat-message array (`[{ role, content }, …]`) the rest of MJ already reads from `Messages`.
407
+ *
408
+ * NOTE: load-append-save carries the same benign race as usage accumulation; realtime turns are
409
+ * sequential per session so collisions are rare. A dedicated child turn-row entity would remove the
410
+ * race (and the blob rewrite) entirely — a future increment. Tool-call turns (the browser_ and
411
+ * Whiteboard_ channel tools) are a separate increment that requires the client to relay them.
412
+ *
413
+ * @returns `true` when the turn was persisted onto the prompt run.
414
+ */
415
+ async AppendPromptRunMessage(promptRunID, role, content, replacePrevious, contextUser, provider) {
416
+ // Serialized against usage checkpoints on the same run so a concurrent usage save can't clobber
417
+ // the Messages we write here (and vice-versa). See promptRunWriteChains.
418
+ return this.serializePromptRunWrite(promptRunID, async () => {
419
+ try {
420
+ const promptRun = await provider.GetEntityObject('MJ: AI Prompt Runs', contextUser);
421
+ if (!(await promptRun.Load(promptRunID))) {
422
+ LogError(`AppendPromptRunMessage: co-agent prompt run ${promptRunID} not found — transcript turn dropped.`);
423
+ return false;
424
+ }
425
+ const messages = this.parsePromptRunMessages(promptRun.Messages);
426
+ const last = messages[messages.length - 1];
427
+ if (replacePrevious && last && last.role === role) {
428
+ last.content = content;
429
+ }
430
+ else {
431
+ messages.push({ role, content });
432
+ }
433
+ promptRun.Messages = JSON.stringify(messages);
434
+ if (!(await promptRun.Save())) {
435
+ LogError(`AppendPromptRunMessage: prompt run ${promptRunID} save failed: ${promptRun.LatestResult?.CompleteMessage ?? 'unknown error'}`);
436
+ return false;
437
+ }
438
+ return true;
439
+ }
440
+ catch (error) {
441
+ LogError(`AppendPromptRunMessage: append failed for prompt run ${promptRunID}: ${error.message}`);
442
+ return false;
443
+ }
444
+ });
445
+ }
446
+ /**
447
+ * Accumulates relayed usage DELTAS onto the co-agent `AIPromptRun`'s `TokensPrompt` / `TokensCompletion`
448
+ * (recomputing `TokensUsed`). Serialized against {@link AppendPromptRunMessage} on the same run so the
449
+ * high-frequency usage checkpoint never overwrites freshly-appended transcript turns (and vice-versa).
450
+ * Best-effort: load/save failures log and return `false`, never throw.
451
+ *
452
+ * @param promptRunID The co-agent observability prompt run.
453
+ * @param inputDelta Input-token delta to add (caller clamps to >= 0).
454
+ * @param outputDelta Output-token delta to add (caller clamps to >= 0).
455
+ * @returns `true` when the accumulated usage was persisted.
456
+ */
457
+ async AccumulatePromptRunUsage(promptRunID, inputDelta, outputDelta, contextUser, provider) {
458
+ return this.serializePromptRunWrite(promptRunID, async () => {
459
+ try {
460
+ const promptRun = await provider.GetEntityObject('MJ: AI Prompt Runs', contextUser);
461
+ if (!(await promptRun.Load(promptRunID))) {
462
+ LogError(`AccumulatePromptRunUsage: co-agent prompt run ${promptRunID} not found — usage delta dropped.`);
463
+ return false;
464
+ }
465
+ promptRun.TokensPrompt = (promptRun.TokensPrompt ?? 0) + inputDelta;
466
+ promptRun.TokensCompletion = (promptRun.TokensCompletion ?? 0) + outputDelta;
467
+ promptRun.TokensUsed = (promptRun.TokensPrompt ?? 0) + (promptRun.TokensCompletion ?? 0);
468
+ if (!(await promptRun.Save())) {
469
+ LogError(`AccumulatePromptRunUsage: prompt run ${promptRunID} save failed: ${promptRun.LatestResult?.CompleteMessage ?? 'unknown error'}`);
470
+ return false;
471
+ }
472
+ return true;
473
+ }
474
+ catch (error) {
475
+ LogError(`AccumulatePromptRunUsage: usage accumulation failed for prompt run ${promptRunID}: ${error.message}`);
476
+ return false;
477
+ }
478
+ });
479
+ }
480
+ /** Parses the prompt run's `Messages` JSON into a mutable chat-message array (tolerant: `[]` on empty/malformed). */
481
+ parsePromptRunMessages(raw) {
482
+ if (!raw || !raw.trim()) {
483
+ return [];
484
+ }
485
+ try {
486
+ const parsed = JSON.parse(raw);
487
+ return Array.isArray(parsed) ? parsed : [];
488
+ }
489
+ catch {
490
+ return [];
491
+ }
492
+ }
493
+ /**
494
+ * Executes a single tool call relayed from the browser and returns its serialized result.
495
+ *
496
+ * Builds a {@link RealtimeToolBroker} whose `DelegateToTarget` runs the target agent (threading
497
+ * the abort signal, parent run, and session id) and whose `ExecuteTool` returns a structured
498
+ * "not available" result for non-target tools (action wiring is a later phase). The broker
499
+ * routes the call and always resolves with structured JSON — failures become `tool_response`
500
+ * errors the model can narrate rather than thrown exceptions.
501
+ *
502
+ * @param input The relayed tool call plus delegation linkage.
503
+ * @param contextUser The calling user (threaded into the delegated agent run).
504
+ * @param provider The request-scoped metadata provider (threaded into the delegated agent run).
505
+ * @returns `{ ResultJson, Success, PausedRunID?, Artifacts? }` — the serialized tool result for
506
+ * the browser to relay back, the paused run id when the delegated target agent paused awaiting
507
+ * feedback (so the resolver can persist it and resume that run on the next answer), and the
508
+ * artifacts the delegated run produced (so the resolver can junction-link them into the
509
+ * session's conversation history — the same info is embedded in `ResultJson` for the client).
510
+ */
511
+ async ExecuteRelayedTool(input, contextUser, provider) {
512
+ // Register this call in the in-flight registry so CancelInFlightDelegations (the
513
+ // CancelRealtimeSessionTool mutation) can abort it mid-flight. The registry controller's
514
+ // signal is combined with any caller-supplied signal — either source cancels the run.
515
+ const controller = this.registerInFlightDelegation(input.AgentSessionID, input.Call.CallID);
516
+ const effectiveInput = {
517
+ ...input,
518
+ AbortSignal: input.AbortSignal ? this.combineSignals(controller.signal, input.AbortSignal) : controller.signal
519
+ };
520
+ try {
521
+ const broker = this.buildToolBroker(effectiveInput, contextUser, provider);
522
+ const result = await broker.ExecuteToolCall(effectiveInput.Call);
523
+ return { ResultJson: result.ResultJson, Success: result.Success, PausedRunID: result.PausedRunID, Artifacts: result.Artifacts };
524
+ }
525
+ finally {
526
+ this.unregisterInFlightDelegation(input.AgentSessionID, input.Call.CallID, controller);
527
+ }
528
+ }
529
+ /**
530
+ * Aborts in-flight relayed delegations for a session — the server half of the client-direct
531
+ * CANCEL channel (see the registry note on {@link inFlightDelegations}).
532
+ *
533
+ * @param agentSessionID The session whose in-flight delegations to abort.
534
+ * @param callID When supplied, only the delegation for this specific call is aborted; when
535
+ * omitted, EVERY in-flight delegation for the session is aborted.
536
+ * @returns The number of in-flight delegations aborted. **Tolerant by design**: an unknown
537
+ * session, an unknown call id, or a session with nothing in flight returns `0` — never throws
538
+ * (the call the user wanted dead may simply have finished already, which is a fine outcome).
539
+ */
540
+ CancelInFlightDelegations(agentSessionID, callID) {
541
+ const sessionKey = this.registryKey(agentSessionID);
542
+ const sessionMap = this.inFlightDelegations.get(sessionKey);
543
+ if (!sessionMap || sessionMap.size === 0) {
544
+ return 0;
545
+ }
546
+ let aborted = 0;
547
+ if (callID != null && callID.trim().length > 0) {
548
+ const callKey = this.registryKey(callID);
549
+ const controller = sessionMap.get(callKey);
550
+ if (controller) {
551
+ controller.abort();
552
+ sessionMap.delete(callKey);
553
+ aborted = 1;
554
+ }
555
+ }
556
+ else {
557
+ for (const controller of sessionMap.values()) {
558
+ controller.abort();
559
+ aborted++;
560
+ }
561
+ sessionMap.clear();
562
+ }
563
+ if (sessionMap.size === 0) {
564
+ this.inFlightDelegations.delete(sessionKey);
565
+ }
566
+ if (aborted > 0) {
567
+ LogStatus(`RealtimeClientSessionService: aborted ${aborted} in-flight delegation(s) for session ${agentSessionID}.`);
568
+ }
569
+ return aborted;
570
+ }
571
+ /** Normalized (trim + lowercase) registry key so UUID casing differences can't split entries. */
572
+ registryKey(id) {
573
+ return id.trim().toLowerCase();
574
+ }
575
+ /** Creates + registers the abort controller for one in-flight relayed call. */
576
+ registerInFlightDelegation(agentSessionID, callID) {
577
+ const sessionKey = this.registryKey(agentSessionID);
578
+ let sessionMap = this.inFlightDelegations.get(sessionKey);
579
+ if (!sessionMap) {
580
+ sessionMap = new Map();
581
+ this.inFlightDelegations.set(sessionKey, sessionMap);
582
+ }
583
+ const controller = new AbortController();
584
+ sessionMap.set(this.registryKey(callID), controller);
585
+ return controller;
586
+ }
587
+ /**
588
+ * Removes one call's registry entry on completion — but only when the stored controller is
589
+ * STILL the one this execution registered (a cancel may already have removed it, and a
590
+ * same-callID retry may have replaced it).
591
+ */
592
+ unregisterInFlightDelegation(agentSessionID, callID, controller) {
593
+ const sessionKey = this.registryKey(agentSessionID);
594
+ const sessionMap = this.inFlightDelegations.get(sessionKey);
595
+ if (!sessionMap) {
596
+ return;
597
+ }
598
+ const callKey = this.registryKey(callID);
599
+ if (sessionMap.get(callKey) === controller) {
600
+ sessionMap.delete(callKey);
601
+ }
602
+ if (sessionMap.size === 0) {
603
+ this.inFlightDelegations.delete(sessionKey);
604
+ }
605
+ }
606
+ /**
607
+ * Ensures {@link AIEngine} metadata is loaded before resolution. **Overridable seam** so tests
608
+ * can skip the DB-backed config load.
609
+ *
610
+ * @param contextUser The calling user.
611
+ * @param provider The request-scoped metadata provider.
612
+ */
613
+ async configureEngine(contextUser, provider) {
614
+ await AIEngine.Instance.Config(false, contextUser, provider);
615
+ }
616
+ /**
617
+ * Resolves the co-agent from either the supplied entity or its id (from cached metadata).
618
+ *
619
+ * @param input The prepare-session input.
620
+ * @returns The co-agent entity, or `null` when neither form resolves.
621
+ */
622
+ resolveCoAgent(input) {
623
+ if (input.CoAgent) {
624
+ return input.CoAgent;
625
+ }
626
+ if (input.CoAgentID) {
627
+ return (AIEngine.Instance.Agents ?? []).find(a => UUIDsEqual(a.ID, input.CoAgentID)) ?? null;
628
+ }
629
+ return null;
630
+ }
631
+ /**
632
+ * Resolves the realtime model for a session, honoring an explicit user choice when present.
633
+ *
634
+ * - With {@link PrepareClientSessionInput.PreferredModelID}: resolve THAT model strictly via
635
+ * {@link resolvePreferredRealtimeModel} — failures return a specific reason and never fall
636
+ * back to another model (the user explicitly chose). (The transport layer has already
637
+ * authorization-gated a deviating explicit choice.)
638
+ * - Else, with an effective-config `realtime.modelPreference` (name or id): resolve it via
639
+ * {@link resolveConfiguredModelPreference}. METADATA preferences degrade gracefully — an
640
+ * unsatisfiable preference logs and FALLS THROUGH to the default (mirroring the co-agent
641
+ * resolution chain's tolerant metadata steps), it never breaks calls.
642
+ * - Without either: the existing default behavior via {@link resolveRealtimeModel}
643
+ * (highest-PowerRank active Realtime model), with the generic {@link noModelMessage} on failure.
644
+ *
645
+ * @param input The prepare-session input (carries the optional preferred model id).
646
+ * @param coAgent The resolved co-agent (threaded to the default-resolution seam).
647
+ * @param effectiveConfig The resolved effective configuration (carries `modelPreference`).
648
+ * @returns The resolution outcome (resolution or failure reason).
649
+ */
650
+ async resolveModelForSession(input, coAgent, effectiveConfig) {
651
+ if (input.PreferredModelID) {
652
+ return this.resolvePreferredRealtimeModel(input.PreferredModelID);
653
+ }
654
+ const fromConfig = this.resolveConfiguredModelPreference(effectiveConfig);
655
+ if (fromConfig) {
656
+ return { Resolution: fromConfig };
657
+ }
658
+ const resolution = await this.resolveRealtimeModel(coAgent);
659
+ return resolution ? { Resolution: resolution } : { ErrorMessage: this.noModelMessage() };
660
+ }
661
+ /**
662
+ * Resolves the effective config's `realtime.modelPreference` (an `MJ: AI Models` Name OR ID)
663
+ * into a usable realtime model. TOLERANT by design — this is a METADATA preference, so any
664
+ * failure (unknown model, inactive, wrong type, no vendor/key) logs a warning and returns
665
+ * `null`, falling through to the default highest-PowerRank resolution. Contrast with the
666
+ * explicit runtime choice ({@link resolvePreferredRealtimeModel}), which fails loud.
667
+ *
668
+ * @param effectiveConfig The resolved effective configuration.
669
+ * @returns The resolution, or `null` when no preference is configured or it can't be satisfied.
670
+ */
671
+ resolveConfiguredModelPreference(effectiveConfig) {
672
+ const preference = effectiveConfig?.realtime?.modelPreference;
673
+ if (!preference) {
674
+ return null;
675
+ }
676
+ const model = this.findModelByIDOrName(preference);
677
+ if (!model) {
678
+ LogError(`RealtimeClientSessionService: configured realtime model preference '${preference}' matches no model in ` +
679
+ 'AI model metadata — falling through to default realtime model resolution.');
680
+ return null;
681
+ }
682
+ if (!model.IsActive || !this.isRealtimeModel(model)) {
683
+ LogError(`RealtimeClientSessionService: configured realtime model preference '${preference}' resolved to ` +
684
+ `'${model.Name}' but it is not an Active Realtime model — falling through to default resolution.`);
685
+ return null;
686
+ }
687
+ const resolution = this.resolveVendorAndInstantiate(model);
688
+ if (!resolution) {
689
+ LogError(`RealtimeClientSessionService: configured realtime model preference '${model.Name}' has no usable ` +
690
+ 'vendor DriverClass/API key — falling through to default resolution.');
691
+ }
692
+ return resolution;
693
+ }
694
+ /**
695
+ * Looks up a model by ID (UUID-insensitive) or, failing that, by case/whitespace-insensitive
696
+ * Name in {@link AIEngine}'s cached models. **Overridable seam**; tolerant of an unloaded cache.
697
+ *
698
+ * @param preference The `MJ: AI Models` ID or Name.
699
+ * @returns The model entity, or `null`.
700
+ */
701
+ findModelByIDOrName(preference) {
702
+ try {
703
+ const models = AIEngine.Instance.Models ?? [];
704
+ const wanted = preference.trim().toLowerCase();
705
+ return (models.find(m => UUIDsEqual(m.ID, preference)) ??
706
+ models.find(m => m.Name?.trim().toLowerCase() === wanted) ??
707
+ null);
708
+ }
709
+ catch {
710
+ return null;
711
+ }
712
+ }
713
+ /**
714
+ * Strictly resolves an EXPLICITLY requested realtime model. Each precondition failure returns
715
+ * a clear, user-facing reason naming the model — there is NO fallback to another model, because
716
+ * the caller's user explicitly chose this one.
717
+ *
718
+ * @param preferredModelID The `MJ: AI Models.ID` the user chose.
719
+ * @returns The resolution outcome (resolution or a specific failure reason).
720
+ */
721
+ resolvePreferredRealtimeModel(preferredModelID) {
722
+ const model = this.findModelByID(preferredModelID);
723
+ if (!model) {
724
+ return { ErrorMessage: `The requested realtime model (id '${preferredModelID}') was not found in AI model metadata.` };
725
+ }
726
+ if (!model.IsActive) {
727
+ return { ErrorMessage: `The requested model '${model.Name}' is not active and cannot be used for a voice session.` };
728
+ }
729
+ if (!this.isRealtimeModel(model)) {
730
+ return { ErrorMessage: `The requested model '${model.Name}' is not a Realtime model (its type is '${model.AIModelType}').` };
731
+ }
732
+ const resolution = this.resolveVendorAndInstantiate(model);
733
+ if (!resolution) {
734
+ return {
735
+ ErrorMessage: `The requested model '${model.Name}' has no active vendor with a usable DriverClass/API key ` +
736
+ '(e.g. AI_VENDOR_API_KEY__<driver>), so the voice session could not be started with it.'
737
+ };
738
+ }
739
+ return { Resolution: resolution };
740
+ }
741
+ /**
742
+ * Looks up a model by id in {@link AIEngine}'s cached models. **Overridable seam** for tests.
743
+ *
744
+ * @param modelID The `MJ: AI Models.ID` to find.
745
+ * @returns The model entity, or `null` when not present.
746
+ */
747
+ findModelByID(modelID) {
748
+ return (AIEngine.Instance.Models ?? []).find(m => UUIDsEqual(m.ID, modelID)) ?? null;
749
+ }
750
+ /** True when the model's denormalized `AIModelType` name is `Realtime` (case/whitespace-insensitive). */
751
+ isRealtimeModel(model) {
752
+ return typeof model.AIModelType === 'string' && model.AIModelType.trim().toLowerCase() === 'realtime';
753
+ }
754
+ /**
755
+ * Resolves the Realtime model + vendor driver + API key, mirroring `BaseAgent`'s server-bridged
756
+ * resolution: highest-power active model of AIModelType `Realtime`; highest-priority active
757
+ * vendor whose `DriverClass` has a resolvable API key; instantiated via the `ClassFactory`.
758
+ *
759
+ * **Overridable seam.** Test subclasses override this to return a mock model so the service can
760
+ * be exercised without provider SDKs or DB metadata. Returns `null` (never throws) when any
761
+ * step can't be satisfied.
762
+ *
763
+ * @param coAgent The co-agent being voiced (reserved for future per-agent model preference).
764
+ * @returns The resolved model + identifiers, or `null`.
765
+ */
766
+ async resolveRealtimeModel(coAgent) {
767
+ // Walk candidates in descending PowerRank, returning the FIRST that fully resolves to a usable
768
+ // client-direct driver (active vendor + API key + ClassFactory driver + SupportsClientDirect).
769
+ // Single-pick dead-ended whenever the highest-power model lacked a key or client-direct support
770
+ // — e.g. a newly-seeded provider (Grok/Inworld) with no env key outranking GPT Realtime — and
771
+ // surfaced "No usable Realtime model" instead of falling through to a model that works.
772
+ const candidates = this.selectRealtimeModelCandidates(coAgent);
773
+ for (const model of candidates) {
774
+ const resolution = this.resolveVendorAndInstantiate(model);
775
+ if (resolution && resolution.Model.SupportsClientDirect) {
776
+ return resolution;
777
+ }
778
+ }
779
+ return null;
780
+ }
781
+ /**
782
+ * Shared tail of model resolution: picks the vendor (with a usable API key) for an
783
+ * already-chosen model entity and instantiates its realtime driver.
784
+ *
785
+ * @param model The chosen model entity.
786
+ * @returns The full resolution, or `null` when no vendor/key/driver can be satisfied.
787
+ */
788
+ resolveVendorAndInstantiate(model) {
789
+ const vendor = this.selectRealtimeVendor(model.ID);
790
+ if (!vendor) {
791
+ return null;
792
+ }
793
+ const apiKey = this.getAPIKeyForDriver(vendor.DriverClass);
794
+ if (!apiKey) {
795
+ return null;
796
+ }
797
+ const instance = this.createModelInstance(vendor.DriverClass, apiKey);
798
+ if (!instance) {
799
+ return null;
800
+ }
801
+ return {
802
+ Model: instance,
803
+ ModelID: model.ID,
804
+ VendorID: vendor.VendorID,
805
+ APIName: vendor.APIName,
806
+ ModelName: model.Name,
807
+ DriverClass: vendor.DriverClass
808
+ };
809
+ }
810
+ /**
811
+ * Resolves the API key for a vendor driver class. **Overridable seam** (wraps the module-level
812
+ * {@link GetAIAPIKey}) so tests can simulate present/absent keys without environment setup.
813
+ *
814
+ * @param driverClass The vendor's `DriverClass`.
815
+ * @returns The API key, or a falsy value when none is configured.
816
+ */
817
+ getAPIKeyForDriver(driverClass) {
818
+ return GetAIAPIKey(driverClass) || undefined;
819
+ }
820
+ /**
821
+ * Instantiates the realtime driver for a vendor driver class via the ClassFactory.
822
+ * **Overridable seam** so tests can return a mock driver.
823
+ *
824
+ * @param driverClass The vendor's `DriverClass` (the ClassFactory key).
825
+ * @param apiKey The resolved API key (constructor argument).
826
+ * @returns The driver instance, or `null` when the factory cannot create one.
827
+ */
828
+ createModelInstance(driverClass, apiKey) {
829
+ return MJGlobal.Instance.ClassFactory.CreateInstance(BaseRealtimeModel, driverClass, apiKey) ?? null;
830
+ }
831
+ /**
832
+ * The active models of AIModelType `Realtime`, sorted highest-PowerRank first — the candidate
833
+ * list {@link resolveRealtimeModel} walks until one yields a usable client-direct driver.
834
+ * Returns ALL candidates (not just the top pick) so a keyless or non-client-direct top model
835
+ * falls through to the next usable one instead of dead-ending the whole resolution.
836
+ *
837
+ * @param coAgent The co-agent (reserved for future per-agent model preference).
838
+ * @returns The candidate models in resolution order (empty array when none are active).
839
+ */
840
+ selectRealtimeModelCandidates(coAgent) {
841
+ return AIEngine.Instance.Models
842
+ .filter(m => m.IsActive && this.isRealtimeModel(m))
843
+ .sort((a, b) => (b.PowerRank ?? 0) - (a.PowerRank ?? 0));
844
+ }
845
+ /**
846
+ * Selects the highest-priority active vendor for a model whose `DriverClass` has a resolvable
847
+ * API key. Mirrors `BaseAgent.selectRealtimeVendor`.
848
+ *
849
+ * @param modelID The chosen model's id.
850
+ * @returns The vendor driver/api identifiers, or `null` when none has a usable key.
851
+ */
852
+ selectRealtimeVendor(modelID) {
853
+ const vendors = AIEngine.Instance.ModelVendors
854
+ .filter(mv => UUIDsEqual(mv.ModelID, modelID) && mv.Status === 'Active' && mv.DriverClass != null)
855
+ .sort((a, b) => (b.Priority ?? 0) - (a.Priority ?? 0));
856
+ for (const v of vendors) {
857
+ if (this.getAPIKeyForDriver(v.DriverClass)) {
858
+ return { VendorID: v.VendorID ?? '', DriverClass: v.DriverClass, APIName: v.APIName ?? '' };
859
+ }
860
+ }
861
+ return null;
862
+ }
863
+ /**
864
+ * Resolves the DB-driven progress-narration instruction template: the Active `MJ: AI Prompts`
865
+ * row named {@link RealtimeClientSessionService.NarrationPromptName}, read from
866
+ * {@link AIEngine}'s cached prompts. When the current name is absent, falls back to the
867
+ * DEPRECATED {@link RealtimeClientSessionService.LegacyNarrationPromptName} (pre-rename seed)
868
+ * with a deprecation log. **Tolerant**: returns `null` (never throws) when neither prompt is
869
+ * present, the text is empty, or the engine cache is unavailable — clients fall back to their
870
+ * built-in narration instruction text.
871
+ *
872
+ * @returns The template text (containing a `{{ progressMessage }}` placeholder), or `null`.
873
+ */
874
+ resolveNarrationInstructionsTemplate() {
875
+ return ResolveNarrationInstructionsTemplate();
876
+ }
877
+ /**
878
+ * Builds the {@link RealtimeSessionParams} for the client-direct session: the companion system
879
+ * prompt plus the stable, target-independent tool set.
880
+ *
881
+ * @param input The prepare-session input.
882
+ * @param coAgent The resolved co-agent.
883
+ * @param modelApiName The vendor API name of the resolved realtime model.
884
+ * @param contextUser The calling user.
885
+ * @param provider The request-scoped metadata provider.
886
+ * @param effectiveConfig The resolved effective configuration (voice persona + provider settings).
887
+ * @param driverClass The resolved vendor's DriverClass — matches per-provider voice settings.
888
+ * @returns The assembled session params.
889
+ */
890
+ async buildSessionParams(input, coAgent, modelApiName, contextUser, provider, effectiveConfig, driverClass) {
891
+ const systemPrompt = await this.buildCompanionSystemPrompt(input, coAgent, contextUser, provider, effectiveConfig);
892
+ const memoryContext = await this.assembleMemoryContext(input, coAgent, contextUser);
893
+ const tools = this.buildStableToolSet(input.ExtraTools);
894
+ // One line per mint: confirms which tools + whether the channel-direct framing actually reach
895
+ // the model — settles "why does the co-agent delegate instead of calling browser_*" without
896
+ // runtime guesswork (channelExceptionInPrompt=false ⇒ stale build; browser_* missing from
897
+ // tools ⇒ the channel's tools never reached the mint).
898
+ console.log(`[RealtimeCoAgent] mint model=${modelApiName} ` +
899
+ `tools=[${tools.map(t => t.Name).join(', ')}] ` +
900
+ `channelExceptionInPrompt=${systemPrompt.includes('interactive-surface')}`);
901
+ return {
902
+ Model: modelApiName,
903
+ SystemPrompt: systemPrompt,
904
+ Tools: tools,
905
+ InitialContext: memoryContext || undefined,
906
+ Config: this.buildSessionConfigBag(input, effectiveConfig, driverClass)
907
+ };
908
+ }
909
+ /**
910
+ * Builds the provider-pact `Config` bag for the session: the effective config's matching
911
+ * per-provider voice settings (`realtime.voice.providers.<provider>`) merged UNDER any
912
+ * caller-supplied {@link PrepareClientSessionInput.Config} (the runtime bag wins per key).
913
+ * The settings objects are OPAQUE driver pacts — each server driver consumes its own keys
914
+ * exactly as it consumes any other entry of the open config bag (OpenAI spreads it into
915
+ * `session.update`, AssemblyAI reads `voice`, Gemini merges it last). Returns the original
916
+ * `input.Config` (possibly `undefined`) when no provider settings match, preserving the
917
+ * pre-config behavior byte-for-byte.
918
+ *
919
+ * @param input The prepare-session input (carries the runtime config bag).
920
+ * @param effectiveConfig The resolved effective configuration.
921
+ * @param driverClass The resolved vendor's DriverClass.
922
+ * @returns The merged config bag, or `undefined` when nothing contributes.
923
+ */
924
+ buildSessionConfigBag(input, effectiveConfig, driverClass) {
925
+ const providerVoice = GetProviderVoiceSettings(effectiveConfig, driverClass ?? null);
926
+ if (!providerVoice) {
927
+ return input.Config;
928
+ }
929
+ const merged = DeepMergeConfigs(providerVoice, input.Config);
930
+ return merged;
931
+ }
932
+ /**
933
+ * Assembles the companion system prompt: the framing ("you are the voice for the target"), the
934
+ * co-agent's own system prompt text, the TARGET agent's identity/capabilities (Name +
935
+ * Description), the conversation history, and the same memory/context a loop agent assembles.
936
+ *
937
+ * When the effective configuration carries a voice persona (`realtime.voice.default`), a
938
+ * short "Voice & manner" section (tone / speaking style) is appended after the co-agent's
939
+ * own prompt so the model speaks in the configured manner.
940
+ *
941
+ * @param input The prepare-session input.
942
+ * @param coAgent The resolved co-agent.
943
+ * @param contextUser The calling user.
944
+ * @param provider The request-scoped metadata provider.
945
+ * @param effectiveConfig The resolved effective configuration (voice persona source).
946
+ * @returns The concatenated system prompt (never empty — the framing is always present).
947
+ */
948
+ async buildCompanionSystemPrompt(input, coAgent, contextUser, provider, effectiveConfig) {
949
+ const target = this.resolveTargetAgent(input.TargetAgentID);
950
+ const targetName = target?.Name ?? 'the configured target agent';
951
+ const framing = `You are the real-time voice for the agent "${targetName}". Hold a natural, low-latency ` +
952
+ `conversation with the user, always speaking in the FIRST PERSON as ${targetName} — own the work ` +
953
+ `("I'm pulling that up", "I found three matches"); never refer to ${targetName} or the work in the ` +
954
+ `third person. When actual work is required, call the '${INVOKE_TARGET_AGENT_TOOL_NAME}' ` +
955
+ `tool and narrate progress while it runs — do not attempt to do the work yourself.` +
956
+ this.buildInteractiveSurfaceFraming(input.ExtraTools);
957
+ const coAgentPrompt = this.getCoAgentSystemPromptText(coAgent);
958
+ const voiceManner = BuildVoiceMannerSection(effectiveConfig);
959
+ const targetIdentity = this.formatTargetIdentity(target);
960
+ const priorTranscript = this.formatPriorTranscript(input.PriorTranscript);
961
+ const history = this.formatConversationHistory(input.ConversationMessages);
962
+ const memoryContext = await this.assembleMemoryContext(input, coAgent, contextUser);
963
+ return [framing, coAgentPrompt, voiceManner, targetIdentity, priorTranscript, history, memoryContext]
964
+ .filter(part => part && part.trim().length > 0)
965
+ .join('\n\n');
966
+ }
967
+ /**
968
+ * Builds the "interactive-surface tools" exception clause appended to the co-agent framing when
969
+ * the client supplied channel tools (browser_*, Whiteboard_*, …) as ExtraTools. Without it the
970
+ * co-agent — told to route ALL work through invoke-target-agent — delegates browser/whiteboard
971
+ * requests to the target agent (which has no live channel of its own) instead of driving the
972
+ * surface itself, then hallucinates a "missing session id". The tools ARE already in its set
973
+ * ({@link buildStableToolSet} merges `[invokeTarget, ...extraTools]`); this clause tells the model
974
+ * to USE them directly. Returns empty for pure-voice sessions (no ExtraTools), keeping that
975
+ * framing untouched. Generic by design — it names browser_ and Whiteboard_ tools only as
976
+ * examples, so any future client channel is covered automatically.
977
+ *
978
+ * @param extraTools The client-supplied channel tools, when any.
979
+ * @returns The exception clause (leading space included), or '' when there are no extra tools.
980
+ */
981
+ buildInteractiveSurfaceFraming(extraTools) {
982
+ if (!extraTools || extraTools.length === 0) {
983
+ return '';
984
+ }
985
+ return ` ONE EXCEPTION: besides '${INVOKE_TARGET_AGENT_TOOL_NAME}' you have been given ` +
986
+ `interactive-surface tools (for example 'browser_*' to drive a LIVE web browser the user can ` +
987
+ `watch, or 'Whiteboard_*' to draw on a shared board). Those surfaces are operated by YOU, ` +
988
+ `directly — when the user asks to use one (e.g. "open/show a browser", "go to a site", "add ` +
989
+ `to the whiteboard"), call the matching tool yourself immediately and narrate what you're ` +
990
+ `doing. NEVER route an interactive-surface request through '${INVOKE_TARGET_AGENT_TOOL_NAME}', ` +
991
+ `and never claim you lack a session — calling the tool is all that's needed.`;
992
+ }
993
+ /**
994
+ * Frames the prior-leg transcript (when a session resumes via `lastSessionId`) as a clearly
995
+ * labeled PRIOR-CONVERSATION section of the system prompt, so the model REMEMBERS the last
996
+ * live session rather than greeting the user cold. The transport layer supplies the
997
+ * already-capped, role-tagged lines (see {@link PrepareClientSessionInput.PriorTranscript});
998
+ * this method only adds the framing. Empty/whitespace input yields an empty section.
999
+ *
1000
+ * @param priorTranscript The role-tagged transcript lines, or undefined.
1001
+ * @returns The framed section, or empty string when there is nothing to frame.
1002
+ */
1003
+ formatPriorTranscript(priorTranscript) {
1004
+ const text = priorTranscript?.trim() ?? '';
1005
+ if (text.length === 0) {
1006
+ return '';
1007
+ }
1008
+ return ('Earlier in this conversation (a previous live session that you are now resuming), ' +
1009
+ 'you and the user discussed the following. Treat it as shared context you both remember:\n' +
1010
+ text);
1011
+ }
1012
+ /**
1013
+ * Resolves the target agent entity from cached metadata.
1014
+ *
1015
+ * @param targetAgentID The target agent id.
1016
+ * @returns The target agent entity, or `null` when not found.
1017
+ */
1018
+ resolveTargetAgent(targetAgentID) {
1019
+ if (!targetAgentID) {
1020
+ return null;
1021
+ }
1022
+ return (AIEngine.Instance.Agents ?? []).find(a => UUIDsEqual(a.ID, targetAgentID)) ?? null;
1023
+ }
1024
+ /**
1025
+ * Reads the co-agent's own system prompt text from its highest-priority active agent prompt,
1026
+ * mirroring `BaseAgent.loadAgentConfiguration`'s child-prompt resolution.
1027
+ *
1028
+ * @param coAgent The resolved co-agent.
1029
+ * @returns The co-agent's system prompt template text, or empty string when none is configured.
1030
+ */
1031
+ getCoAgentSystemPromptText(coAgent) {
1032
+ return this.resolveCoAgentSystemPrompt(coAgent).Text;
1033
+ }
1034
+ /**
1035
+ * Resolves the co-agent's highest-priority active system prompt, returning both its template
1036
+ * text and its prompt id. The id is surfaced so {@link PrepareClientSession} can create a linked
1037
+ * co-agent `AIPromptRun` for observability. Mirrors `BaseAgent.loadAgentConfiguration`'s
1038
+ * child-prompt resolution.
1039
+ *
1040
+ * @param coAgent The resolved co-agent.
1041
+ * @returns The prompt text + id, or `{ Text: '', PromptID: null }` when none is configured.
1042
+ */
1043
+ resolveCoAgentSystemPrompt(coAgent) {
1044
+ const engine = AIEngine.Instance;
1045
+ const agentPrompt = (engine.AgentPrompts ?? [])
1046
+ .filter(ap => UUIDsEqual(ap.AgentID, coAgent.ID) && ap.Status === 'Active')
1047
+ .sort((a, b) => a.ExecutionOrder - b.ExecutionOrder)[0];
1048
+ if (!agentPrompt) {
1049
+ return { Text: '', PromptID: null };
1050
+ }
1051
+ const prompt = (engine.Prompts ?? []).find(p => UUIDsEqual(p.ID, agentPrompt.PromptID));
1052
+ return { Text: prompt?.TemplateText ?? '', PromptID: prompt?.ID ?? null };
1053
+ }
1054
+ /**
1055
+ * Formats the target agent's identity + capabilities block for the system prompt.
1056
+ *
1057
+ * @param target The target agent, or `null`.
1058
+ * @returns The formatted block, or empty string when no target resolved.
1059
+ */
1060
+ formatTargetIdentity(target) {
1061
+ if (!target) {
1062
+ return '';
1063
+ }
1064
+ const description = target.Description?.trim() ? target.Description.trim() : 'No description provided.';
1065
+ return `Target agent you are voicing for:\nName: ${target.Name}\nCapabilities: ${description}`;
1066
+ }
1067
+ /**
1068
+ * Formats prior conversation history as a plain-text block for the system prompt.
1069
+ *
1070
+ * @param messages The conversation messages, or undefined.
1071
+ * @returns The formatted history block, or empty string when there is none.
1072
+ */
1073
+ formatConversationHistory(messages) {
1074
+ if (!messages || messages.length === 0) {
1075
+ return '';
1076
+ }
1077
+ const lines = messages
1078
+ .map(m => {
1079
+ const text = typeof m.content === 'string' ? m.content : '';
1080
+ return text.trim().length > 0 ? `${m.role}: ${text}` : '';
1081
+ })
1082
+ .filter(line => line.length > 0);
1083
+ return lines.length > 0 ? `Conversation so far:\n${lines.join('\n')}` : '';
1084
+ }
1085
+ /**
1086
+ * Assembles the same memory/context block a loop agent injects, reusing
1087
+ * {@link AgentMemoryContextBuilder} so there is no duplicated retrieval logic. The builder
1088
+ * unshifts a system message onto a throwaway array, which we pull back out as plain text.
1089
+ *
1090
+ * @param input The prepare-session input.
1091
+ * @param coAgent The resolved co-agent.
1092
+ * @param contextUser The calling user.
1093
+ * @returns The concatenated context text (empty string when nothing was injected).
1094
+ */
1095
+ async assembleMemoryContext(input, coAgent, contextUser) {
1096
+ const lastUserMessage = (input.ConversationMessages ?? []).filter(m => m.role === 'user').pop();
1097
+ const inputText = typeof lastUserMessage?.content === 'string' ? lastUserMessage.content : '';
1098
+ const scratch = [];
1099
+ const builder = new AgentMemoryContextBuilder();
1100
+ await builder.InjectContextMemory(inputText, coAgent, input.UserID || contextUser?.ID, input.CompanyID, contextUser, scratch, undefined, undefined, undefined, null);
1101
+ return scratch
1102
+ .map(m => (typeof m.content === 'string' ? m.content : ''))
1103
+ .filter(c => c.length > 0)
1104
+ .join('\n\n');
1105
+ }
1106
+ /**
1107
+ * Builds the stable, target-independent tool set every voice session exposes: the single
1108
+ * `invoke-target-agent` tool plus any caller-supplied extra tools. The target is a runtime
1109
+ * argument *inside* the call, never a per-target tool — this keeps the provider contract
1110
+ * identical across targets.
1111
+ *
1112
+ * @param extraTools Optional additional target-independent tools.
1113
+ * @returns The tools to register at session start.
1114
+ */
1115
+ buildStableToolSet(extraTools) {
1116
+ const invokeTarget = {
1117
+ Name: INVOKE_TARGET_AGENT_TOOL_NAME,
1118
+ Description: 'Hand the user\'s request to the target agent to perform the actual work. Call this whenever ' +
1119
+ 'real work (data lookup, analysis, actions) is required, then narrate progress while it runs.',
1120
+ ParametersSchema: {
1121
+ type: 'object',
1122
+ properties: {
1123
+ request: {
1124
+ type: 'string',
1125
+ description: 'The natural-language request to hand to the target agent.'
1126
+ }
1127
+ },
1128
+ required: ['request']
1129
+ }
1130
+ };
1131
+ return extraTools && extraTools.length > 0 ? [invokeTarget, ...extraTools] : [invokeTarget];
1132
+ }
1133
+ /**
1134
+ * Builds the {@link RealtimeToolBroker} for a relayed tool call, wiring `DelegateToTarget` to a
1135
+ * target-agent run and `ExecuteTool` to a structured "not available" placeholder.
1136
+ *
1137
+ * @param input The relayed tool input.
1138
+ * @param contextUser The calling user.
1139
+ * @param provider The request-scoped metadata provider.
1140
+ * @returns The constructed broker.
1141
+ */
1142
+ buildToolBroker(input, contextUser, provider) {
1143
+ const deps = {
1144
+ DelegateToTarget: (request) => this.delegateToTarget(input, request, contextUser, provider),
1145
+ ExecuteTool: (call) => this.executeNonTargetTool(call)
1146
+ };
1147
+ return new RealtimeToolBroker(deps);
1148
+ }
1149
+ /**
1150
+ * Delegates an `invoke-target-agent` call to the target agent via {@link AgentRunner.RunAgent}.
1151
+ *
1152
+ * Threads the broker-owned abort signal (combined with any caller signal) into the child run's
1153
+ * `cancellationToken`, links the child run to the co-agent run via `parentRunID`, and propagates
1154
+ * `agentSessionID` so both runs group under the same session. Mirrors
1155
+ * `BaseAgent.delegateRealtimeToTarget`.
1156
+ *
1157
+ * @param input The relayed tool input (target id + linkage).
1158
+ * @param request The broker's delegation request (call id + arguments + abort signal).
1159
+ * @param contextUser The calling user.
1160
+ * @param provider The request-scoped metadata provider.
1161
+ * @returns The delegated result for the model's tool_response.
1162
+ */
1163
+ async delegateToTarget(input, request, contextUser, provider) {
1164
+ const target = this.resolveTargetAgent(input.TargetAgentID);
1165
+ if (!target) {
1166
+ return {
1167
+ CallID: request.CallID,
1168
+ Success: false,
1169
+ Output: 'No target agent is configured for this voice session, so the request could not be performed.'
1170
+ };
1171
+ }
1172
+ try {
1173
+ const result = await this.runDelegatedAgent(input, request, target, contextUser, provider);
1174
+ const artifacts = await this.createDelegatedRunArtifacts(result, contextUser, provider);
1175
+ return this.buildDelegatedResult(request.CallID, result, artifacts);
1176
+ }
1177
+ catch (error) {
1178
+ const message = error instanceof Error ? error.message : String(error);
1179
+ return { CallID: request.CallID, Success: false, Output: `Delegation failed: ${message}` };
1180
+ }
1181
+ }
1182
+ /**
1183
+ * Creates artifact(s) from a completed delegated run's payload — the voice-path equivalent of
1184
+ * the chat path's artifact step in `AgentRunner.RunAgentInConversation`. Delegated voice runs
1185
+ * execute via `AgentRunner.RunAgent` directly (no conversation detail), so without this step
1186
+ * they would never produce artifacts at all.
1187
+ *
1188
+ * Eligibility guards (all must hold, mirroring the chat path's `processArtifacts`):
1189
+ * - the run succeeded and did NOT pause awaiting feedback (a paused run has no deliverable yet);
1190
+ * - the run returned a non-empty payload.
1191
+ *
1192
+ * The DB work is delegated to {@link processRunArtifacts} (an overridable seam), which reuses
1193
+ * `AgentRunner.ProcessAgentArtifacts` — so ArtifactCreationMode, DefaultArtifactTypeID,
1194
+ * name extraction, and duplicate-version dedup all behave exactly as in chat. **Best-effort:**
1195
+ * any failure is logged and returns `undefined`; artifact surfacing never fails the delegation.
1196
+ *
1197
+ * @param result The delegated agent execution result.
1198
+ * @param contextUser The calling user.
1199
+ * @param provider The request-scoped metadata provider.
1200
+ * @returns The produced artifact descriptor(s), or `undefined` when none were created.
1201
+ */
1202
+ async createDelegatedRunArtifacts(result, contextUser, provider) {
1203
+ const paused = result.agentRun?.Status === 'AwaitingFeedback';
1204
+ const payload = result.payload;
1205
+ const hasPayload = payload != null && Object.keys(payload).length > 0;
1206
+ if (!result.success || paused || !hasPayload) {
1207
+ return undefined;
1208
+ }
1209
+ try {
1210
+ return await this.processRunArtifacts(result, contextUser, provider);
1211
+ }
1212
+ catch (error) {
1213
+ const message = error instanceof Error ? error.message : String(error);
1214
+ LogError(`RealtimeClientSessionService.createDelegatedRunArtifacts failed (delegation continues): ${message}`);
1215
+ return undefined;
1216
+ }
1217
+ }
1218
+ /**
1219
+ * The DB-backed artifact-creation seam: runs `AgentRunner.ProcessAgentArtifacts` WITHOUT a
1220
+ * conversation detail (the voice path has none — the artifact + version are created and the
1221
+ * junction link is skipped), then loads the artifact header for its display name.
1222
+ *
1223
+ * Artifacts whose Visibility resolved to `System Only` (the agent's ArtifactCreationMode) are
1224
+ * created but NOT surfaced to the overlay — matching how chat hides them from users.
1225
+ *
1226
+ * **Overridable seam** so tests can exercise {@link createDelegatedRunArtifacts}' eligibility
1227
+ * guards without a DB.
1228
+ *
1229
+ * @param result The delegated agent execution result (payload + agentRun).
1230
+ * @param contextUser The calling user.
1231
+ * @param provider The request-scoped metadata provider.
1232
+ * @returns The produced artifact descriptor(s), or `undefined`.
1233
+ */
1234
+ async processRunArtifacts(result, contextUser, provider) {
1235
+ const runner = new AgentRunner(provider);
1236
+ const info = await runner.ProcessAgentArtifacts(result, undefined, undefined, contextUser, provider);
1237
+ if (!info) {
1238
+ return undefined;
1239
+ }
1240
+ const artifact = await provider.GetEntityObject('MJ: Artifacts', contextUser);
1241
+ if (!(await artifact.Load(info.artifactId))) {
1242
+ return undefined;
1243
+ }
1244
+ if (artifact.Visibility === 'System Only') {
1245
+ return undefined; // created for system purposes, never user-surfaced
1246
+ }
1247
+ return [{ ArtifactID: info.artifactId, ArtifactVersionID: info.versionId, Name: artifact.Name }];
1248
+ }
1249
+ /**
1250
+ * Runs (or resumes) the target agent for a delegation. Threads the combined abort signal, parent
1251
+ * run linkage, session id, and the `OnProgress` callback so the resolver can stream progress.
1252
+ * When {@link ExecuteRelayedToolInput.ResumeRunID} is set, resumes that paused run via
1253
+ * `lastRunId` + `autoPopulateLastRunPayload` (the user's answer continues the same interactive
1254
+ * run) instead of starting fresh.
1255
+ *
1256
+ * @param input The relayed tool input (linkage, progress callback, optional resume id).
1257
+ * @param request The broker's delegation request (call id + arguments + abort signal).
1258
+ * @param target The resolved target agent.
1259
+ * @param contextUser The calling user.
1260
+ * @param provider The request-scoped metadata provider.
1261
+ * @returns The agent execution result.
1262
+ */
1263
+ async runDelegatedAgent(input, request, target, contextUser, provider) {
1264
+ const requestText = this.parseDelegateRequestText(request.Arguments);
1265
+ const parentRun = await this.loadParentRun(input.ParentRunID, contextUser, provider);
1266
+ const runner = new AgentRunner(provider);
1267
+ return runner.RunAgent({
1268
+ agent: target,
1269
+ conversationMessages: [{ role: 'user', content: requestText }],
1270
+ contextUser,
1271
+ provider,
1272
+ cancellationToken: this.combineSignals(request.AbortSignal, input.AbortSignal),
1273
+ parentRun: parentRun ?? undefined,
1274
+ agentSessionID: input.AgentSessionID,
1275
+ onProgress: input.OnProgress,
1276
+ lastRunId: input.ResumeRunID,
1277
+ autoPopulateLastRunPayload: input.ResumeRunID ? true : undefined
1278
+ });
1279
+ }
1280
+ /**
1281
+ * Maps an {@link ExecuteAgentResult} onto the broker's {@link DelegatedResult}, special-casing a
1282
+ * run that paused awaiting feedback. An `AwaitingFeedback` run is a valid intermediate outcome,
1283
+ * not an error: we return its clarifying QUESTION (the run's `Message`) as the tool Output —
1284
+ * phrased so the realtime model relays it as a question to the user — set `Success: true`, and
1285
+ * surface the paused run id so the resolver can resume that run on the user's next answer.
1286
+ *
1287
+ * @param callID The provider call id this result corresponds to.
1288
+ * @param result The agent execution result.
1289
+ * @param artifacts Artifacts the run produced (from {@link createDelegatedRunArtifacts}),
1290
+ * threaded into the result so the broker serializes them for the call overlay.
1291
+ * @returns The delegated result for the model's tool_response.
1292
+ */
1293
+ buildDelegatedResult(callID, result, artifacts) {
1294
+ if (result.agentRun?.Status === 'AwaitingFeedback') {
1295
+ const question = result.agentRun.Message?.trim()
1296
+ || 'The target agent needs more information to continue.';
1297
+ return {
1298
+ CallID: callID,
1299
+ Success: true,
1300
+ Output: `You need an answer from the user before you can continue this work. Ask them, in your own first-person voice: ${question}`,
1301
+ PausedRunID: result.agentRun.ID,
1302
+ RunID: result.agentRun.ID
1303
+ };
1304
+ }
1305
+ return {
1306
+ CallID: callID,
1307
+ Success: result.success,
1308
+ Output: result.success
1309
+ ? (result.agentRun?.Message || 'The delegated work is complete. Share the outcome with the user in your own first-person voice.')
1310
+ : (result.agentRun?.ErrorMessage || 'The work could not be completed. Tell the user, in first person, that you hit a problem and offer a next step.'),
1311
+ RunID: result.agentRun?.ID,
1312
+ Artifacts: artifacts
1313
+ };
1314
+ }
1315
+ /**
1316
+ * Loads the co-agent run entity behind {@link ExecuteRelayedToolInput.ParentRunID} so the
1317
+ * delegated run can link to it via `parentRun` (→ `ParentRunID`). Returns `null` when no id was
1318
+ * supplied or the run cannot be loaded (delegation proceeds without parent linkage rather than
1319
+ * failing the whole call).
1320
+ *
1321
+ * @param parentRunID The co-agent run id, or undefined.
1322
+ * @param contextUser The calling user.
1323
+ * @param provider The request-scoped metadata provider.
1324
+ * @returns The loaded parent run entity, or `null`.
1325
+ */
1326
+ async loadParentRun(parentRunID, contextUser, provider) {
1327
+ if (!parentRunID) {
1328
+ return null;
1329
+ }
1330
+ const run = await provider.GetEntityObject('MJ: AI Agent Runs', contextUser);
1331
+ return (await run.Load(parentRunID)) ? run : null;
1332
+ }
1333
+ /**
1334
+ * Routes a non-target tool call. For now this returns a structured "not available" result —
1335
+ * the richer client/UI/action routing is wired in a later phase. Documented minimal seam.
1336
+ *
1337
+ * @param call The non-target tool call.
1338
+ * @returns A failed {@link ToolExecutionResult} the model can narrate.
1339
+ */
1340
+ async executeNonTargetTool(call) {
1341
+ return {
1342
+ CallID: call.CallID,
1343
+ Success: false,
1344
+ Output: `Tool '${call.ToolName}' is not available in this voice session.`
1345
+ };
1346
+ }
1347
+ /**
1348
+ * Parses the natural-language request text out of an `invoke-target-agent` call's arguments.
1349
+ * Falls back to the raw argument string when it is not the expected `{ request: string }` JSON.
1350
+ *
1351
+ * @param argumentsJson The raw arguments string emitted by the model.
1352
+ * @returns The request text to hand to the target agent.
1353
+ */
1354
+ parseDelegateRequestText(argumentsJson) {
1355
+ try {
1356
+ const parsed = JSON.parse(argumentsJson);
1357
+ if (typeof parsed.request === 'string') {
1358
+ return parsed.request;
1359
+ }
1360
+ }
1361
+ catch {
1362
+ /* not JSON — fall through to raw */
1363
+ }
1364
+ return argumentsJson;
1365
+ }
1366
+ /**
1367
+ * Combines the broker's per-call abort signal with an optional caller-supplied signal so either
1368
+ * source can cancel the delegated run. Returns the broker signal alone when no caller signal is
1369
+ * present (the common case), avoiding an unnecessary controller.
1370
+ *
1371
+ * @param brokerSignal The broker-owned per-call abort signal (always present).
1372
+ * @param callerSignal An optional caller signal (e.g. a request-scoped barge-in).
1373
+ * @returns A single abort signal that fires when either source aborts.
1374
+ */
1375
+ combineSignals(brokerSignal, callerSignal) {
1376
+ if (!callerSignal) {
1377
+ return brokerSignal;
1378
+ }
1379
+ const controller = new AbortController();
1380
+ const abort = () => controller.abort();
1381
+ if (brokerSignal.aborted || callerSignal.aborted) {
1382
+ controller.abort();
1383
+ }
1384
+ else {
1385
+ brokerSignal.addEventListener('abort', abort, { once: true });
1386
+ callerSignal.addEventListener('abort', abort, { once: true });
1387
+ }
1388
+ return controller.signal;
1389
+ }
1390
+ /**
1391
+ * The clear, actionable message returned when no usable Realtime model can be resolved.
1392
+ *
1393
+ * @returns The failure message.
1394
+ */
1395
+ noModelMessage() {
1396
+ return ('No usable Realtime model could be resolved for the Realtime Co-Agent. Configure a model of ' +
1397
+ "AIModelType 'Realtime' with an active vendor DriverClass and a valid API key " +
1398
+ '(e.g. AI_VENDOR_API_KEY__<driver>).');
1399
+ }
1400
+ }
1401
+ //# sourceMappingURL=realtime-client-session-service.js.map