@memberjunction/ai-agents 6.2.0-edge.3 → 6.2.0-edge.5

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 (182) hide show
  1. package/README.md +100 -7
  2. package/dist/AgentRunner.d.ts +55 -5
  3. package/dist/AgentRunner.d.ts.map +1 -1
  4. package/dist/AgentRunner.js +277 -59
  5. package/dist/AgentRunner.js.map +1 -1
  6. package/dist/ArtifactToolManager.d.ts +11 -3
  7. package/dist/ArtifactToolManager.d.ts.map +1 -1
  8. package/dist/ArtifactToolManager.js +72 -6
  9. package/dist/ArtifactToolManager.js.map +1 -1
  10. package/dist/ClientToolRequestManager.d.ts +11 -1
  11. package/dist/ClientToolRequestManager.d.ts.map +1 -1
  12. package/dist/ClientToolRequestManager.js +19 -6
  13. package/dist/ClientToolRequestManager.js.map +1 -1
  14. package/dist/ConversationCompactionManager.d.ts +2 -0
  15. package/dist/ConversationCompactionManager.d.ts.map +1 -1
  16. package/dist/ConversationCompactionManager.js +2 -2
  17. package/dist/ConversationCompactionManager.js.map +1 -1
  18. package/dist/ConversationToolManager.d.ts +13 -2
  19. package/dist/ConversationToolManager.d.ts.map +1 -1
  20. package/dist/ConversationToolManager.js +19 -3
  21. package/dist/ConversationToolManager.js.map +1 -1
  22. package/dist/KnowledgeAgent.d.ts.map +1 -1
  23. package/dist/KnowledgeAgent.js +6 -1
  24. package/dist/KnowledgeAgent.js.map +1 -1
  25. package/dist/MJAIAgentRequestEntityServer.d.ts +6 -0
  26. package/dist/MJAIAgentRequestEntityServer.d.ts.map +1 -1
  27. package/dist/MJAIAgentRequestEntityServer.js +26 -1
  28. package/dist/MJAIAgentRequestEntityServer.js.map +1 -1
  29. package/dist/PayloadChangeAnalyzer.d.ts.map +1 -1
  30. package/dist/PayloadChangeAnalyzer.js +53 -30
  31. package/dist/PayloadChangeAnalyzer.js.map +1 -1
  32. package/dist/PayloadManager.d.ts +35 -2
  33. package/dist/PayloadManager.d.ts.map +1 -1
  34. package/dist/PayloadManager.js +250 -149
  35. package/dist/PayloadManager.js.map +1 -1
  36. package/dist/ScratchpadManager.d.ts +18 -0
  37. package/dist/ScratchpadManager.d.ts.map +1 -1
  38. package/dist/ScratchpadManager.js +61 -0
  39. package/dist/ScratchpadManager.js.map +1 -1
  40. package/dist/agent-audience.d.ts +38 -0
  41. package/dist/agent-audience.d.ts.map +1 -0
  42. package/dist/agent-audience.js +99 -0
  43. package/dist/agent-audience.js.map +1 -0
  44. package/dist/agent-context-injector.d.ts +17 -2
  45. package/dist/agent-context-injector.d.ts.map +1 -1
  46. package/dist/agent-context-injector.js +23 -7
  47. package/dist/agent-context-injector.js.map +1 -1
  48. package/dist/agent-memory-context-builder.d.ts +7 -2
  49. package/dist/agent-memory-context-builder.d.ts.map +1 -1
  50. package/dist/agent-memory-context-builder.js +12 -3
  51. package/dist/agent-memory-context-builder.js.map +1 -1
  52. package/dist/agent-pre-execution-rag.d.ts +101 -9
  53. package/dist/agent-pre-execution-rag.d.ts.map +1 -1
  54. package/dist/agent-pre-execution-rag.js +224 -23
  55. package/dist/agent-pre-execution-rag.js.map +1 -1
  56. package/dist/agent-run-watchdog.d.ts +65 -5
  57. package/dist/agent-run-watchdog.d.ts.map +1 -1
  58. package/dist/agent-run-watchdog.js +143 -28
  59. package/dist/agent-run-watchdog.js.map +1 -1
  60. package/dist/agent-types/flow-agent-type.d.ts +8 -0
  61. package/dist/agent-types/flow-agent-type.d.ts.map +1 -1
  62. package/dist/agent-types/flow-agent-type.js +48 -6
  63. package/dist/agent-types/flow-agent-type.js.map +1 -1
  64. package/dist/agent-types/loop-agent-prompt-params.d.ts +7 -0
  65. package/dist/agent-types/loop-agent-prompt-params.d.ts.map +1 -1
  66. package/dist/agent-types/loop-agent-prompt-params.js +1 -0
  67. package/dist/agent-types/loop-agent-prompt-params.js.map +1 -1
  68. package/dist/agent-types/loop-agent-response-type.d.ts +8 -2
  69. package/dist/agent-types/loop-agent-response-type.d.ts.map +1 -1
  70. package/dist/agent-types/loop-agent-response-type.js.map +1 -1
  71. package/dist/agent-types/loop-agent-type.d.ts +9 -2
  72. package/dist/agent-types/loop-agent-type.d.ts.map +1 -1
  73. package/dist/agent-types/loop-agent-type.js +60 -16
  74. package/dist/agent-types/loop-agent-type.js.map +1 -1
  75. package/dist/artifact-tools/SearchResultSetToolLibrary.js +4 -4
  76. package/dist/artifact-tools/SearchResultSetToolLibrary.js.map +1 -1
  77. package/dist/base-agent.d.ts +837 -43
  78. package/dist/base-agent.d.ts.map +1 -1
  79. package/dist/base-agent.js +3081 -663
  80. package/dist/base-agent.js.map +1 -1
  81. package/dist/client-tool-results.d.ts +45 -0
  82. package/dist/client-tool-results.d.ts.map +1 -0
  83. package/dist/client-tool-results.js +94 -0
  84. package/dist/client-tool-results.js.map +1 -0
  85. package/dist/index.d.ts +9 -0
  86. package/dist/index.d.ts.map +1 -1
  87. package/dist/index.js +9 -0
  88. package/dist/index.js.map +1 -1
  89. package/dist/memory-manager-agent.d.ts.map +1 -1
  90. package/dist/memory-manager-agent.js +46 -34
  91. package/dist/memory-manager-agent.js.map +1 -1
  92. package/dist/native-tools/action-param-schema.d.ts +57 -0
  93. package/dist/native-tools/action-param-schema.d.ts.map +1 -0
  94. package/dist/native-tools/action-param-schema.js +238 -0
  95. package/dist/native-tools/action-param-schema.js.map +1 -0
  96. package/dist/native-tools/action-tool-builder.d.ts +5 -4
  97. package/dist/native-tools/action-tool-builder.d.ts.map +1 -1
  98. package/dist/native-tools/action-tool-builder.js +29 -71
  99. package/dist/native-tools/action-tool-builder.js.map +1 -1
  100. package/dist/native-tools/json-argument.d.ts +41 -0
  101. package/dist/native-tools/json-argument.d.ts.map +1 -0
  102. package/dist/native-tools/json-argument.js +79 -0
  103. package/dist/native-tools/json-argument.js.map +1 -0
  104. package/dist/prior-turn-tool-result-cache.d.ts +31 -12
  105. package/dist/prior-turn-tool-result-cache.d.ts.map +1 -1
  106. package/dist/prior-turn-tool-result-cache.js +59 -16
  107. package/dist/prior-turn-tool-result-cache.js.map +1 -1
  108. package/dist/query-builder-agent.d.ts +13 -4
  109. package/dist/query-builder-agent.d.ts.map +1 -1
  110. package/dist/query-builder-agent.js +102 -27
  111. package/dist/query-builder-agent.js.map +1 -1
  112. package/dist/realtime/bridge-realtime-session-factory.d.ts +44 -2
  113. package/dist/realtime/bridge-realtime-session-factory.d.ts.map +1 -1
  114. package/dist/realtime/bridge-realtime-session-factory.js +68 -20
  115. package/dist/realtime/bridge-realtime-session-factory.js.map +1 -1
  116. package/dist/realtime/bridge-realtime-usage-recorder.d.ts +81 -0
  117. package/dist/realtime/bridge-realtime-usage-recorder.d.ts.map +1 -0
  118. package/dist/realtime/bridge-realtime-usage-recorder.js +194 -0
  119. package/dist/realtime/bridge-realtime-usage-recorder.js.map +1 -0
  120. package/dist/realtime/client-only-channel-server.d.ts +83 -0
  121. package/dist/realtime/client-only-channel-server.d.ts.map +1 -0
  122. package/dist/realtime/client-only-channel-server.js +107 -0
  123. package/dist/realtime/client-only-channel-server.js.map +1 -0
  124. package/dist/realtime/identity-verification-channel-server.d.ts +50 -0
  125. package/dist/realtime/identity-verification-channel-server.d.ts.map +1 -0
  126. package/dist/realtime/identity-verification-channel-server.js +66 -0
  127. package/dist/realtime/identity-verification-channel-server.js.map +1 -0
  128. package/dist/realtime/interactive-component-channel-server.d.ts +39 -0
  129. package/dist/realtime/interactive-component-channel-server.d.ts.map +1 -0
  130. package/dist/realtime/interactive-component-channel-server.js +55 -0
  131. package/dist/realtime/interactive-component-channel-server.js.map +1 -0
  132. package/dist/realtime/realtime-avatar-resolution.d.ts +194 -0
  133. package/dist/realtime/realtime-avatar-resolution.d.ts.map +1 -0
  134. package/dist/realtime/realtime-avatar-resolution.js +208 -0
  135. package/dist/realtime/realtime-avatar-resolution.js.map +1 -0
  136. package/dist/realtime/realtime-channel-policy.d.ts +81 -0
  137. package/dist/realtime/realtime-channel-policy.d.ts.map +1 -0
  138. package/dist/realtime/realtime-channel-policy.js +91 -0
  139. package/dist/realtime/realtime-channel-policy.js.map +1 -0
  140. package/dist/realtime/realtime-channel-server-host.d.ts +14 -0
  141. package/dist/realtime/realtime-channel-server-host.d.ts.map +1 -1
  142. package/dist/realtime/realtime-channel-server-host.js +35 -0
  143. package/dist/realtime/realtime-channel-server-host.js.map +1 -1
  144. package/dist/realtime/realtime-client-session-service.d.ts +435 -34
  145. package/dist/realtime/realtime-client-session-service.d.ts.map +1 -1
  146. package/dist/realtime/realtime-client-session-service.js +806 -139
  147. package/dist/realtime/realtime-client-session-service.js.map +1 -1
  148. package/dist/realtime/realtime-coagent-config.d.ts +102 -16
  149. package/dist/realtime/realtime-coagent-config.d.ts.map +1 -1
  150. package/dist/realtime/realtime-coagent-config.js +126 -5
  151. package/dist/realtime/realtime-coagent-config.js.map +1 -1
  152. package/dist/realtime/realtime-recording-ledger.d.ts +130 -0
  153. package/dist/realtime/realtime-recording-ledger.d.ts.map +1 -0
  154. package/dist/realtime/realtime-recording-ledger.js +190 -0
  155. package/dist/realtime/realtime-recording-ledger.js.map +1 -0
  156. package/dist/realtime/realtime-recording-opus-assembly.d.ts +211 -0
  157. package/dist/realtime/realtime-recording-opus-assembly.d.ts.map +1 -0
  158. package/dist/realtime/realtime-recording-opus-assembly.js +706 -0
  159. package/dist/realtime/realtime-recording-opus-assembly.js.map +1 -0
  160. package/dist/realtime/realtime-recording-store.d.ts +174 -17
  161. package/dist/realtime/realtime-recording-store.d.ts.map +1 -1
  162. package/dist/realtime/realtime-recording-store.js +552 -58
  163. package/dist/realtime/realtime-recording-store.js.map +1 -1
  164. package/dist/realtime/realtime-session-runner.js +4 -4
  165. package/dist/realtime/realtime-session-runner.js.map +1 -1
  166. package/dist/realtime/realtime-turn-moderator.d.ts +2 -1
  167. package/dist/realtime/realtime-turn-moderator.d.ts.map +1 -1
  168. package/dist/realtime/realtime-turn-moderator.js +7 -1
  169. package/dist/realtime/realtime-turn-moderator.js.map +1 -1
  170. package/dist/realtime/realtime-vendor-resolution.d.ts +9 -0
  171. package/dist/realtime/realtime-vendor-resolution.d.ts.map +1 -1
  172. package/dist/realtime/realtime-vendor-resolution.js +16 -5
  173. package/dist/realtime/realtime-vendor-resolution.js.map +1 -1
  174. package/dist/realtime/realtime-video-output-gate.d.ts +83 -0
  175. package/dist/realtime/realtime-video-output-gate.d.ts.map +1 -0
  176. package/dist/realtime/realtime-video-output-gate.js +79 -0
  177. package/dist/realtime/realtime-video-output-gate.js.map +1 -0
  178. package/dist/tool-result-format.d.ts +14 -0
  179. package/dist/tool-result-format.d.ts.map +1 -1
  180. package/dist/tool-result-format.js.map +1 -1
  181. package/dist/volatile-child-prompt.js +3 -3
  182. package/package.json +21 -19
@@ -29,21 +29,50 @@
29
29
  * @module @memberjunction/ai-agents
30
30
  * @author MemberJunction.com
31
31
  */
32
- import { LogError, LogStatus, RunView } from '@memberjunction/core';
33
- import { MJGlobal, MJLruCache, UUIDsEqual, EscapeSQLString } from '@memberjunction/global';
32
+ import { LogError, LogStatus, RunView, DatabaseProviderBase } from '@memberjunction/core';
33
+ import { MJGlobal, MJLruCache, UUIDsEqual, EscapeSQLString, NormalizeUUID } from '@memberjunction/global';
34
34
  import { ActionEngineServer } from '@memberjunction/actions';
35
35
  import { RunActionParams } from '@memberjunction/actions-base';
36
- import { BaseRealtimeModel, GetAIAPIKey, CredentialScopeAllows } from '@memberjunction/ai';
37
- import { FormatAppContextNote, ResolvePromptRunUserID } from '@memberjunction/ai-core-plus';
36
+ import { BaseRealtimeModel, GetAIAPIKey, CredentialScopeAllows, IsZeroDataRetention } from '@memberjunction/ai';
37
+ import { FormatAppContextNote, ResolvePromptRunUserID, ClientToolMetadataFromDefinition, ParseAgentSettings, ResolveAppClientToolMetadata, ResolveClientTools } from '@memberjunction/ai-core-plus';
38
38
  import { AIEngine } from '@memberjunction/aiengine';
39
+ import { RealtimeSessionCanShowAvatar, ResolveBridgedAvatarStatus, ResolveRealtimeAvatar, ResolveRealtimeAvatarStatus, WithoutUnseenAvatar, } from './realtime-avatar-resolution.js';
40
+ import { ChooseRealtimeVendorForAvatar, ReadRealtimeVideoOutputRow, RealtimeModelShowsAvatar } from './realtime-video-output-gate.js';
39
41
  import { AgentMemoryContextBuilder } from '../agent-memory-context-builder.js';
40
42
  import { AgentRunner } from '../AgentRunner.js';
43
+ import { AgentRunWatchdog } from '../agent-run-watchdog.js';
41
44
  import { DelegationNarrator } from './realtime-delegation-narrator.js';
42
45
  import { FilterAllowedAgentsByCanRun } from './realtime-coagent-resolution.js';
46
+ import { BridgeRealtimeUsageRecorder } from './bridge-realtime-usage-recorder.js';
43
47
  import { RealtimeToolBroker, INVOKE_TARGET_AGENT_TOOL_NAME, INVOKE_TARGET_AGENT_DESCRIPTION, BuildRealtimeAgentFraming } from './realtime-tool-broker.js';
44
48
  import { NARRATION_PROMPT_NAME, LEGACY_NARRATION_PROMPT_NAME, ResolveNarrationInstructionsTemplate } from './realtime-narration.js';
45
- import { BuildVoiceMannerSection, BuildAppRealtimeOverridesJson, DeepMergeConfigs, GetModelCatalogSessionSettings, GetDisclosureForTarget, GetNarrationPaceMs, GetProviderVoiceSettings, GetSessionTuningSettings, ResolveEffectiveRealtimeConfig, MatchProviderVoiceSettings, GetDirectActionsConfig, IsActionAllowedForDirectInvocation } from './realtime-coagent-config.js';
46
- import { SelectRealtimeVendorForModel } from './realtime-vendor-resolution.js';
49
+ import { BuildVoiceMannerSection, BuildAppRealtimeOverridesJson, DeepMergeConfigs, FindDeprecatedRealtimeVideoKeys, GetModelCatalogSessionSettings, GetDisclosureForTarget, GetNarrationPaceMs, GetProviderVoiceSettings, GetSessionTuningSettings, GetWatchesMeetingVideo, ResolveEffectiveRealtimeConfig, MatchProviderVoiceSettings, GetDirectActionsConfig, IsActionAllowedForDirectInvocation } from './realtime-coagent-config.js';
50
+ import { ListRealtimeVendorsForModel, SelectRealtimeVendorForModel } from './realtime-vendor-resolution.js';
51
+ import { AIEngineBase, MergeRealtimeUsageRecord } from '@memberjunction/ai-engine-base';
52
+ import { BuildSessionChannelPolicy } from './realtime-channel-policy.js';
53
+ /**
54
+ * How many seconds of avatar video a run may store beyond its elapsed time: usage is client-reported, so the stored
55
+ * output video seconds are capped at the run's elapsed time plus this grace (relays land a few seconds late).
56
+ */
57
+ const VIDEO_SECONDS_GRACE = 30;
58
+ /**
59
+ * How long closing a bridged (server-held) session waits for its model session to close before the session's runs are
60
+ * finalized anyway, in milliseconds. A model session reports its last usage while it closes (a Gemini avatar session,
61
+ * the seconds of video it has not reported yet), and the runs are priced from what was stored when they are finalized.
62
+ */
63
+ export const BRIDGE_SESSION_CLOSE_WAIT_MS = 5_000;
64
+ /**
65
+ * The co-agent and target pairs already named in the deprecated `realtime.video` keys line, so the line is logged once
66
+ * per pair per process rather than on every session.
67
+ */
68
+ const deprecatedVideoKeysLogged = new Set();
69
+ /**
70
+ * How many output video tokens one second of avatar video counts: Gemini counts 258 tokens a frame at 24 frames a
71
+ * second, the rate the per-minute avatar price is derived from. The stored output video tokens are capped at the
72
+ * seconds cap at this rate, because pricing uses them: they leave the cost row's output bucket, and a per-token avatar
73
+ * price prices them. Raise it for a model that counts more.
74
+ */
75
+ const VIDEO_TOKENS_PER_SECOND = 6192;
47
76
  /** Runtime handles by their realtime session, so the layer that only holds the session can reach its runtime. */
48
77
  const bridgeRuntimes = new WeakMap();
49
78
  /**
@@ -55,6 +84,34 @@ const bridgeRuntimes = new WeakMap();
55
84
  export function GetBridgeRealtimeRuntime(session) {
56
85
  return bridgeRuntimes.get(session);
57
86
  }
87
+ /**
88
+ * Closes a bridged model session, waiting for it up to `waitMs`. Resolves when the close finishes or the wait runs out;
89
+ * rejects when the close fails within the wait. A close still running when the wait runs out is logged (what the
90
+ * session reports from then on is not stored), and so is its failure, should it fail later.
91
+ *
92
+ * @param close The session's own `Close()`.
93
+ * @param waitMs How long to wait for it.
94
+ * @param label Names the session in the log lines (its co-agent prompt run).
95
+ */
96
+ async function closeBridgedSessionWithin(close, waitMs, label) {
97
+ const closing = Promise.resolve(close());
98
+ let timer;
99
+ const waitRanOut = new Promise((resolve) => {
100
+ timer = setTimeout(() => resolve(true), waitMs);
101
+ timer.unref?.();
102
+ });
103
+ try {
104
+ const ranOut = await Promise.race([closing.then(() => false), waitRanOut]);
105
+ if (ranOut) {
106
+ LogError(`[Bridged usage] ${label}: the model session took more than ${waitMs} ms to close; its runs are finalized ` +
107
+ `without waiting, so usage it reports while closing is not stored.`);
108
+ closing.catch((error) => LogError(`[Bridged usage] ${label}: closing the model session failed: ${error instanceof Error ? error.message : String(error)}`));
109
+ }
110
+ }
111
+ finally {
112
+ clearTimeout(timer);
113
+ }
114
+ }
58
115
  /**
59
116
  * Logs when a configuration authored per-provider voice settings but NONE matched the vendor that
60
117
  * actually ran — those settings are dropped, and pre-#3530 that happened with no trace at all: the
@@ -262,7 +319,7 @@ export class RealtimeClientSessionService {
262
319
  if (!prep.Success || !prep.CoAgent || !prep.Resolution || !prep.SessionParams || !prep.EffectiveConfig) {
263
320
  return { Success: false, ErrorMessage: prep.ErrorMessage };
264
321
  }
265
- const { CoAgent: coAgent, Resolution: resolution, SessionParams: sessionParams, EffectiveConfig: effectiveConfig } = prep;
322
+ const { CoAgent: coAgent, Resolution: resolution, SessionParams: sessionParams, EffectiveConfig: effectiveConfig, ClientPolicy: clientPolicy } = prep;
266
323
  if (!resolution.Model.SupportsClientDirect) {
267
324
  return {
268
325
  Success: false,
@@ -277,6 +334,7 @@ export class RealtimeClientSessionService {
277
334
  const message = error instanceof Error ? error.message : String(error);
278
335
  return { Success: false, ErrorMessage: `Failed to mint client realtime session: ${message}` };
279
336
  }
337
+ const avatarStatus = this.resolveMintedAvatarStatus(prep, clientConfig);
280
338
  // Best-effort observability: create a server-side co-agent run (+ prompt run) so the voice
281
339
  // session is visible in the agent-run timeline and delegated runs can nest under it. A
282
340
  // failure here never fails the prepare — we just omit the ids.
@@ -294,9 +352,30 @@ export class RealtimeClientSessionService {
294
352
  DriverClass: resolution.DriverClass,
295
353
  NarrationInstructionsTemplate: this.resolveNarrationInstructionsTemplate() ?? undefined,
296
354
  EffectiveConfig: effectiveConfig,
355
+ ClientPolicy: clientPolicy,
297
356
  NarrationPaceMs: GetNarrationPaceMs(effectiveConfig) ?? undefined,
357
+ ...(avatarStatus ? { AvatarStatus: avatarStatus } : {}),
298
358
  };
299
359
  }
360
+ /**
361
+ * The call's avatar status once the driver has minted the session (see {@link ResolveRealtimeAvatarStatus}), with one
362
+ * log line saying whether the avatar shows. `undefined`, and no line, when the session asked for no avatar.
363
+ */
364
+ resolveMintedAvatarStatus(prep, clientConfig) {
365
+ const resolution = prep.Resolution;
366
+ const apiName = resolution?.APIName ?? clientConfig.Model;
367
+ const status = ResolveRealtimeAvatarStatus({
368
+ Resolution: prep.AvatarResolution ?? {},
369
+ ModelSupportsAvatarOutput: resolution
370
+ ? RealtimeModelShowsAvatar({ ModelID: resolution.ModelID, APIName: apiName, Model: resolution.Model }, AIEngine.Instance)
371
+ : false,
372
+ DriverStatus: clientConfig.AvatarStatus,
373
+ });
374
+ if (status) {
375
+ console.log(`[RealtimeCoAgent] mint avatar model=${apiName} shown=${status.Granted} reason=${status.Reason ?? 'none'}`);
376
+ }
377
+ return status;
378
+ }
300
379
  /**
301
380
  * Wires a **server long-lived (bridged)** realtime session onto the SAME core machinery the
302
381
  * client-direct path uses — so a LiveKit (or future Zoom/Teams) agent does real work and is tracked
@@ -307,12 +386,22 @@ export class RealtimeClientSessionService {
307
386
  * under the co-agent run, supports barge-in cancel + paused-run resume — all of it, for free).
308
387
  *
309
388
  * Responsibilities, in order:
389
+ * 0. Report the avatar status the driver had nothing to say about: a prep that asked the driver for no avatar (a
390
+ * phone call, no face for the model's vendor, an unknown avatar, a Video/Output row that turns video off) leaves
391
+ * the driver nothing to report, and a driver that renders no avatar ignores a request, so the session's
392
+ * `AvatarStatus` says why instead of saying nothing ({@link ResolveBridgedAvatarStatus}).
310
393
  * 1. Create the co-agent observability run (+ prompt run + step) so the voice session shows up in the
311
394
  * agent-run timeline and delegated runs nest under it (best-effort; a failure just omits the ids).
312
- * 2. Wire `session.OnToolCall` → `ExecuteRelayedTool` → `session.SendToolResult`.
313
- * 3. Guarantee finalize-once: wrap `session.Close()` and listen for an unexpected drop (`OnClose`), both
395
+ * 2. Record the session's usage on the co-agent prompt run, as client-direct calls do: `session.OnUsage` →
396
+ * {@link BridgeRealtimeUsageRecorder} → {@link AccumulatePromptRunUsage}, every 10 s and once more at finalize.
397
+ * 3. Wire `session.OnToolCall` → `ExecuteRelayedTool` → `session.SendToolResult`.
398
+ * 4. Guarantee finalize-once: wrap `session.Close()` and listen for an unexpected drop (`OnClose`), both
314
399
  * routed through one idempotent finalizer. The bridge teardown calls `Close()`, so the run finalizes
315
- * on graceful end; a dropped socket finalizes via `OnClose`.
400
+ * on graceful end; a dropped socket finalizes via `OnClose`, and a `Close()` after it waits for that
401
+ * finalize. The wrapped `Close()` closes the model session first (waiting up to
402
+ * {@link BRIDGE_SESSION_CLOSE_WAIT_MS}), so the usage it reports while closing is recorded; the
403
+ * finalizer then writes the session's last usage before it finalizes the runs, so the prompt run is
404
+ * priced from its final counts.
316
405
  *
317
406
  * @param session The live realtime session the bridge owns (from `model.StartSession`).
318
407
  * @param input The same prep input used to build the session (carries AgentSessionID, TargetAgentID, …).
@@ -322,6 +411,7 @@ export class RealtimeClientSessionService {
322
411
  * @returns A {@link BridgeRealtimeRuntime} the bridge holds for the session lifetime.
323
412
  */
324
413
  async WireBridgeRealtimeSession(session, input, prep, contextUser, provider) {
414
+ this.reportBridgedAvatarStatus(session, input, prep);
325
415
  const coAgent = prep.CoAgent;
326
416
  const resolution = prep.Resolution;
327
417
  if (!coAgent || !resolution) {
@@ -340,28 +430,106 @@ export class RealtimeClientSessionService {
340
430
  let localToolHandler;
341
431
  const promptID = this.resolveCoAgentSystemPrompt(coAgent).PromptID;
342
432
  const obs = await this.createCoAgentObservabilityRun(coAgent, promptID, resolution.ModelID, resolution.VendorID, input.UserID || contextUser?.ID, input.AgentSessionID, contextUser, provider, input.ConversationID);
343
- let finalized = false;
344
- const finalize = async (success) => {
345
- if (finalized) {
346
- return;
347
- }
348
- finalized = true;
349
- await this.FinalizeCoAgentRun(obs?.CoAgentRunID ?? null, obs?.PromptRunID ?? null, contextUser, provider, success, obs?.CoAgentRunStepID ?? null);
433
+ const usage = this.wireBridgeUsage(session, obs?.PromptRunID, contextUser, provider);
434
+ const finalize = this.createBridgeFinalizer(obs, usage, contextUser, provider);
435
+ this.wireBridgeToolCalls(session, {
436
+ Input: input,
437
+ Prep: prep,
438
+ ParentRunID: obs?.CoAgentRunID,
439
+ AllowedAgents: allowedAgents,
440
+ Narrator: narrator,
441
+ LocalToolHandler: () => localToolHandler,
442
+ ContextUser: contextUser,
443
+ Provider: provider,
444
+ });
445
+ this.finalizeOnBridgeClose(session, narrator, finalize, obs?.PromptRunID);
446
+ const runtime = {
447
+ CoAgentRunID: obs?.CoAgentRunID,
448
+ PromptRunID: obs?.PromptRunID,
449
+ Finalize: finalize,
450
+ CancelInFlightDelegations: () => {
451
+ narrator.Cancel(); // a stale "still working on it" line must not be spoken over the caller
452
+ return this.CancelInFlightDelegations(input.AgentSessionID);
453
+ },
454
+ CancelPendingNarration: () => narrator.Cancel(),
455
+ SetLocalToolHandler: (handler) => { localToolHandler = handler; },
456
+ WatchesMeetingVideo: GetWatchesMeetingVideo(prep.EffectiveConfig),
350
457
  };
351
- // Tool calls → the shared delegation entry point, then hand the serialized result back to the model.
458
+ bridgeRuntimes.set(session, runtime);
459
+ return runtime;
460
+ }
461
+ /**
462
+ * Gives a bridged session the avatar status its driver had nothing to say about ({@link ResolveBridgedAvatarStatus}),
463
+ * with one log line: a prep that asked the driver for no avatar (a phone call, no face for the model's vendor, an
464
+ * unknown avatar, a Video/Output row that turns video off) leaves the driver nothing to report, and a driver that
465
+ * renders no avatar ignores a request and reports nothing. A host reads it like any driver's status (the LiveKit room
466
+ * puts it on the agent's bot, so the room shows its notice). A status the driver reported stands.
467
+ */
468
+ reportBridgedAvatarStatus(session, input, prep) {
469
+ const model = prep.Resolution;
470
+ const status = ResolveBridgedAvatarStatus({
471
+ Resolution: prep.AvatarResolution,
472
+ RoomDelivery: input.AvatarDelivery === 'room',
473
+ ModelShowsAvatar: () => (model ? RealtimeModelShowsAvatar(model, AIEngine.Instance) : false),
474
+ DriverStatus: session.AvatarStatus,
475
+ });
476
+ if (!status || status === session.AvatarStatus) {
477
+ return;
478
+ }
479
+ session.AvatarStatus = status;
480
+ const asked = prep.AvatarResolution?.Reason ? 'the driver was asked for none' : 'the driver was asked for one and reported nothing';
481
+ LogStatus(`[RealtimeCoAgent] bridged session avatar: audio only (${status.Reason}); ${asked}.`);
482
+ }
483
+ /**
484
+ * Records a bridged session's usage on its co-agent prompt run. The recorder is the session's only `OnUsage`
485
+ * subscriber: drivers keep one usage handler. Without a prompt run there is nowhere to record, so nothing subscribes
486
+ * and one line is logged, as the client-direct relay logs a dropped delta.
487
+ */
488
+ wireBridgeUsage(session, promptRunID, contextUser, provider) {
489
+ if (!promptRunID) {
490
+ LogStatus('WireBridgeRealtimeSession: the session has no co-agent prompt run, so its usage is not recorded.');
491
+ return undefined;
492
+ }
493
+ const recorder = new BridgeRealtimeUsageRecorder((write) => this.AccumulatePromptRunUsage(promptRunID, write.InputTokens, write.OutputTokens, contextUser, provider, write.Details), `prompt run ${promptRunID}`);
494
+ session.OnUsage((usage) => recorder.Add(usage));
495
+ return recorder;
496
+ }
497
+ /**
498
+ * The bridged session's finalizer. It closes the usage recorder first (no more updates; the unwritten usage is
499
+ * written), so the prompt run's cost, computed when finalize stamps `CompletedAt`, covers the whole session. On a
500
+ * graceful close it runs after the model session closed (see `finalizeOnBridgeClose`).
501
+ *
502
+ * It runs once, and every call returns the first call's promise: whichever path calls second (a `Close()` after a
503
+ * dropped connection's `OnClose` started the finalize) resolves only once the runs are finalized and priced. The
504
+ * first call decides the outcome (see {@link BridgeRealtimeRuntime.Finalize}).
505
+ */
506
+ createBridgeFinalizer(obs, usage, contextUser, provider) {
507
+ let finalizing;
508
+ const finalizeRuns = async (success, errorMessage) => {
509
+ await usage?.Close();
510
+ await this.FinalizeCoAgentRun(obs?.CoAgentRunID ?? null, obs?.PromptRunID ?? null, contextUser, provider, success, obs?.CoAgentRunStepID ?? null, errorMessage);
511
+ };
512
+ return (success, errorMessage) => {
513
+ finalizing ??= finalizeRuns(success, errorMessage);
514
+ return finalizing;
515
+ };
516
+ }
517
+ /** Tool calls → the host's local handler or the shared delegation entry point, then the result back to the model. */
518
+ wireBridgeToolCalls(session, wiring) {
352
519
  session.OnToolCall(async (call) => {
353
520
  try {
354
- const resultJson = localToolHandler?.Handles(call.ToolName)
355
- ? await localToolHandler.Execute(call)
356
- : (await narrator.Track(() => this.ExecuteRelayedTool({
357
- AgentSessionID: input.AgentSessionID,
358
- ParentRunID: obs?.CoAgentRunID,
359
- TargetAgentID: input.TargetAgentID,
360
- AllowedAgents: allowedAgents,
361
- DirectActions: prep.EffectiveConfig?.realtime?.directActions,
362
- OnProgress: (progress) => narrator.HandleProgress(progress),
521
+ const localHandler = wiring.LocalToolHandler();
522
+ const resultJson = localHandler?.Handles(call.ToolName)
523
+ ? await localHandler.Execute(call)
524
+ : (await wiring.Narrator.Track(() => this.ExecuteRelayedTool({
525
+ AgentSessionID: wiring.Input.AgentSessionID,
526
+ ParentRunID: wiring.ParentRunID,
527
+ TargetAgentID: wiring.Input.TargetAgentID,
528
+ AllowedAgents: wiring.AllowedAgents,
529
+ DirectActions: wiring.Prep.EffectiveConfig?.realtime?.directActions,
530
+ OnProgress: (progress) => wiring.Narrator.HandleProgress(progress),
363
531
  Call: call,
364
- }, contextUser, provider))).ResultJson;
532
+ }, wiring.ContextUser, wiring.Provider))).ResultJson;
365
533
  await session.SendToolResult(call.CallID, resultJson);
366
534
  }
367
535
  catch (error) {
@@ -370,28 +538,34 @@ export class RealtimeClientSessionService {
370
538
  await session.SendToolResult(call.CallID, JSON.stringify({ success: false, error: message }));
371
539
  }
372
540
  });
373
- // Finalize on graceful teardown (the bridge calls Close()) and on an unexpected drop. Both routed
374
- // through the idempotent finalizer, so double-fire is harmless.
541
+ }
542
+ /**
543
+ * Finalizes on graceful teardown (the bridge calls `Close()`) and on an unexpected drop. Both go through the one
544
+ * finalizer, which runs once: a double fire finalizes once, and a `Close()` after a drop waits for the finalize the
545
+ * drop started, so it resolves only once the runs are finalized. Both finalize as completed: a host whose bridge
546
+ * start failed calls {@link BridgeRealtimeRuntime.Finalize} with `false` and the start's error before it closes the
547
+ * session.
548
+ *
549
+ * `Close()` closes the model session before it finalizes: a session reports its last usage while it closes (a
550
+ * Gemini avatar session, the seconds of video not reported yet), and the finalizer stores only what was reported
551
+ * before it ran. The close is waited for up to {@link BRIDGE_SESSION_CLOSE_WAIT_MS}. The runs are finalized whether
552
+ * the close finished, failed or is still running; a failed close still rejects, after the finalize.
553
+ *
554
+ * @param promptRunID The session's co-agent prompt run, which names the session in a log line.
555
+ */
556
+ finalizeOnBridgeClose(session, narrator, finalize, promptRunID) {
375
557
  const originalClose = session.Close.bind(session);
558
+ const label = promptRunID ? `prompt run ${promptRunID}` : 'a session with no co-agent prompt run';
376
559
  session.Close = async () => {
377
- narrator.Cancel();
378
- await finalize(true);
379
- await originalClose();
560
+ narrator.Cancel(); // nothing more is spoken on a session that is closing
561
+ try {
562
+ await closeBridgedSessionWithin(originalClose, BRIDGE_SESSION_CLOSE_WAIT_MS, label);
563
+ }
564
+ finally {
565
+ await finalize(true);
566
+ }
380
567
  };
381
568
  session.OnClose?.(() => { void finalize(true); });
382
- const runtime = {
383
- CoAgentRunID: obs?.CoAgentRunID,
384
- PromptRunID: obs?.PromptRunID,
385
- Finalize: finalize,
386
- CancelInFlightDelegations: () => {
387
- narrator.Cancel(); // a stale "still working on it" line must not be spoken over the caller
388
- return this.CancelInFlightDelegations(input.AgentSessionID);
389
- },
390
- CancelPendingNarration: () => narrator.Cancel(),
391
- SetLocalToolHandler: (handler) => { localToolHandler = handler; },
392
- };
393
- bridgeRuntimes.set(session, runtime);
394
- return runtime;
395
569
  }
396
570
  /**
397
571
  * Degenerate {@link BridgeRealtimeRuntime} for the rare case wiring is attempted without a resolved
@@ -407,6 +581,7 @@ export class RealtimeClientSessionService {
407
581
  CancelInFlightDelegations: () => 0,
408
582
  CancelPendingNarration: () => { },
409
583
  SetLocalToolHandler: () => { },
584
+ WatchesMeetingVideo: false,
410
585
  };
411
586
  bridgeRuntimes.set(session, runtime);
412
587
  return runtime;
@@ -443,13 +618,157 @@ export class RealtimeClientSessionService {
443
618
  const targetAgent = this.resolveTargetAgent(input.TargetAgentID);
444
619
  const appSettingsJson = await this.resolveAppRealtimeOverrides(input.ApplicationID, contextUser, provider);
445
620
  const effectiveConfig = this.resolveEffectiveConfig(coAgent, input.ConfigOverridesJson, targetAgent, appSettingsJson);
621
+ this.logDeprecatedVideoKeys(effectiveConfig, coAgent, targetAgent);
446
622
  const outcome = await this.resolveModelForSession(input, coAgent, effectiveConfig);
447
623
  if (!outcome.Resolution) {
448
624
  return { Success: false, ErrorMessage: outcome.ErrorMessage ?? this.noModelMessage() };
449
625
  }
450
626
  const resolution = outcome.Resolution;
451
- const sessionParams = await this.buildSessionParams(input, coAgent, resolution.APIName, contextUser, provider, effectiveConfig, resolution.DriverClass, resolution.ModelID, resolution.ModelVendorID);
452
- return { Success: true, CoAgent: coAgent, Resolution: resolution, EffectiveConfig: effectiveConfig, SessionParams: sessionParams };
627
+ let hostTools = input.HostTools;
628
+ if (input.ResolveHostTools) {
629
+ const dynamicHostTools = input.ResolveHostTools({
630
+ ModelID: resolution.ModelID,
631
+ ModelVendorID: resolution.ModelVendorID,
632
+ DriverClass: resolution.DriverClass,
633
+ });
634
+ if (dynamicHostTools !== undefined) {
635
+ hostTools = dynamicHostTools;
636
+ }
637
+ }
638
+ const effectiveInput = hostTools !== input.HostTools ? { ...input, HostTools: hostTools } : input;
639
+ // One answer for the whole session: it lowers channel exposure here and keeps the driver from
640
+ // turning on provider features that store session data (Gemini session resumption).
641
+ const zeroDataRetention = this.modelHasZeroDataRetention(resolution.ModelID, resolution.ModelVendorID);
642
+ // Channel scoping + client-tool tiers: narrows the declared tools to the scope's decision and
643
+ // folds the app tier into the capability manifest the prompt renders. The scoped input is what
644
+ // the prompt/tool builders see, so a vetoed channel is absent from the framing as well as the tools.
645
+ const scoped = await this.scopeSessionInput(effectiveInput, effectiveConfig, contextUser, provider, zeroDataRetention);
646
+ // A session nobody would see an avatar in (a phone call, an app without agent video) asks the driver for none
647
+ // and keeps the persona's voice.
648
+ const avatar = WithoutUnseenAvatar(this.ResolveSessionAvatar(scoped.Input, coAgent, effectiveConfig, resolution.ModelID, resolution.ModelVendorID), scoped.Input);
649
+ const sessionParams = {
650
+ ...(await this.buildSessionParams(scoped.Input, coAgent, resolution.APIName, contextUser, provider, effectiveConfig, resolution.DriverClass, resolution.ModelID, resolution.ModelVendorID, avatar)),
651
+ ZeroDataRetention: zeroDataRetention,
652
+ };
653
+ return {
654
+ Success: true, CoAgent: coAgent, Resolution: resolution, EffectiveConfig: effectiveConfig, SessionParams: sessionParams,
655
+ ClientPolicy: scoped.ClientPolicy, AvatarResolution: avatar,
656
+ };
657
+ }
658
+ /**
659
+ * Applies channel scoping and the client-tool tiers to a prepare input.
660
+ *
661
+ * - **App tier into the prompt.** `Application.AgentSettings.ClientTools` is resolved to metadata
662
+ * and layered, through the unified {@link ResolveClientTools}, beneath the live surface's own
663
+ * manifest in the app-context snapshot — so the co-agent is told about tools the app declares
664
+ * even when the active surface did not republish them. (Only the HOST can run them; the browser
665
+ * reports "declared but not registered" for one it has no handler for.) The agent's static
666
+ * junction tools are deliberately NOT added to the voice prompt — voice prompts are
667
+ * token-sensitive and a tool with no browser handler is noise — but they ride the returned policy
668
+ * so the browser can describe them.
669
+ * - **Channel scoping.** When the browser reported candidates, they are scoped against the
670
+ * registry and the cascade's `channels` section, and the declared tools narrowed to match
671
+ * ({@link BuildSessionChannelPolicy}).
672
+ *
673
+ * @returns The (possibly adjusted) input, and the policy to hand back when candidates were reported.
674
+ */
675
+ async scopeSessionInput(input, effectiveConfig, contextUser, provider, modelHasZeroDataRetention = false) {
676
+ const tiers = await this.resolveSessionClientToolTiers(input.ApplicationID, input.TargetAgentID, contextUser);
677
+ const appContext = this.withAppToolTier(input.AppContext, tiers.App, input.TargetAgentID);
678
+ const candidates = input.ChannelCandidates ?? [];
679
+ if (candidates.length === 0) {
680
+ return { Input: appContext === input.AppContext ? input : { ...input, AppContext: appContext } };
681
+ }
682
+ const outcome = BuildSessionChannelPolicy({
683
+ Candidates: candidates,
684
+ ChannelsConfig: effectiveConfig.realtime?.channels ?? null,
685
+ Registry: this.readChannelRegistry(provider),
686
+ ClientTools: input.ExtraTools,
687
+ ClientToolTiers: tiers,
688
+ ModelHasZeroDataRetention: modelHasZeroDataRetention,
689
+ });
690
+ return {
691
+ Input: { ...input, ExtraTools: outcome.ClientTools, AppContext: appContext },
692
+ ClientPolicy: outcome.Policy,
693
+ };
694
+ }
695
+ /**
696
+ * Whether the session model's effective catalog configuration (type < model < vendor < model-vendor)
697
+ * declares `Privacy.ZeroDataRetention: true`. Fails closed: a model or vendor row that cannot be
698
+ * resolved, or a catalog lookup that throws, reads as "not declared", so an agent that REQUIRES zero
699
+ * data retention loses exposure rather than gaining it. Overridable seam.
700
+ *
701
+ * @param modelID The resolved `MJ: AI Models` id.
702
+ * @param modelVendorID The resolved model-vendor row id (the cascade's most specific layer).
703
+ */
704
+ modelHasZeroDataRetention(modelID, modelVendorID) {
705
+ if (!modelID) {
706
+ return false;
707
+ }
708
+ try {
709
+ return IsZeroDataRetention(AIEngine.Instance.GetEffectiveModelConfiguration(modelID, modelVendorID));
710
+ }
711
+ catch (error) {
712
+ LogError(`RealtimeClientSessionService.modelHasZeroDataRetention failed for model '${modelID}': ${error instanceof Error ? error.message : String(error)}`);
713
+ return false;
714
+ }
715
+ }
716
+ /**
717
+ * Layers the app's client tools beneath the surface's manifest in the app-context snapshot, through
718
+ * the unified resolver (`session > app`, first match by name wins). Returns the SAME snapshot object
719
+ * when nothing changes, so callers can detect "no change" by identity.
720
+ */
721
+ withAppToolTier(appContext, appTools, targetAgentId) {
722
+ if (!appContext || !appTools || appTools.length === 0) {
723
+ return appContext;
724
+ }
725
+ const surfaceTools = appContext.Capabilities?.Tools;
726
+ const tools = ResolveClientTools({ agentId: targetAgentId, sessionTools: surfaceTools, appTools: [...appTools] });
727
+ if (surfaceTools && tools.length === surfaceTools.length) {
728
+ return appContext; // the surface already covered every app tool
729
+ }
730
+ return { ...appContext, Capabilities: { ...appContext.Capabilities, Tools: tools } };
731
+ }
732
+ /**
733
+ * The server's view of the channel registry (`MJ: AI Agent Channels`), read from the request
734
+ * provider's cached {@link AIEngineBase} rows (already configured by the prepare). Overridable seam.
735
+ * Tolerant: an unloaded cache yields an empty registry (every candidate then reads as having no
736
+ * row), never a throw.
737
+ */
738
+ readChannelRegistry(provider) {
739
+ try {
740
+ const engine = AIEngineBase.GetProviderInstance(provider, AIEngineBase);
741
+ return (engine.AgentChannels ?? []).map(c => ({ Name: c.Name, IsActive: c.IsActive }));
742
+ }
743
+ catch (error) {
744
+ LogError(`RealtimeClientSessionService.readChannelRegistry failed: ${error instanceof Error ? error.message : String(error)}`);
745
+ return [];
746
+ }
747
+ }
748
+ /**
749
+ * Resolves the client-tool tiers the browser is told about at mint: the APP tier
750
+ * (`Application.AgentSettings.ClientTools` resolved against the tool-definition catalog) and the
751
+ * STATIC tier (the target agent's `MJ: AI Agent Client Tools` junction). Overridable seam; tolerant —
752
+ * any failure yields empty tiers and never fails the mint.
753
+ */
754
+ async resolveSessionClientToolTiers(applicationId, targetAgentId, contextUser) {
755
+ const tiers = {};
756
+ try {
757
+ const settings = await this.loadAppAgentSettings(applicationId, contextUser);
758
+ const definitions = AIEngine.Instance.ClientToolDefinitions ?? [];
759
+ const app = ResolveAppClientToolMetadata(settings?.ClientTools, definitions, ref => LogStatus(`RealtimeClientSessionService: the app's client tool '${ref.Name ?? ref.ClientToolDefinitionID}' matches no tool definition — skipping it.`));
760
+ if (app.length > 0) {
761
+ tiers.App = app;
762
+ }
763
+ const stat = targetAgentId ? AIEngine.Instance.GetClientToolsForAgent(targetAgentId).map(ClientToolMetadataFromDefinition) : [];
764
+ if (stat.length > 0) {
765
+ tiers.Static = stat;
766
+ }
767
+ }
768
+ catch (error) {
769
+ LogError(`RealtimeClientSessionService.resolveSessionClientToolTiers failed: ${error instanceof Error ? error.message : String(error)}`);
770
+ }
771
+ return tiers;
453
772
  }
454
773
  /**
455
774
  * Resolves the EFFECTIVE realtime configuration via the surface-agnostic precedence cascade:
@@ -468,6 +787,27 @@ export class RealtimeClientSessionService {
468
787
  resolveEffectiveConfig(coAgent, overridesJson, targetAgent, appSettingsJson) {
469
788
  return ResolveEffectiveRealtimeConfig(this.getAgentTypeDefaultConfiguration(coAgent), coAgent.TypeConfiguration ?? null, overridesJson ?? null, targetAgent?.TypeConfiguration ?? null, appSettingsJson ?? null);
470
789
  }
790
+ /**
791
+ * Logs one line, once per co-agent and target pair per process, when the effective configuration sets
792
+ * `realtime.video.provider` or `realtime.video.providers`. Both are deprecated and nothing reads them, so an author
793
+ * who set them would otherwise get nothing and no word of it.
794
+ *
795
+ * @param config The effective configuration.
796
+ * @param coAgent The co-agent.
797
+ * @param targetAgent The voiced agent, when there is one.
798
+ */
799
+ logDeprecatedVideoKeys(config, coAgent, targetAgent) {
800
+ const keys = FindDeprecatedRealtimeVideoKeys(config);
801
+ const pair = `${NormalizeUUID(coAgent.ID)}|${NormalizeUUID(targetAgent?.ID)}`;
802
+ if (keys.length === 0 || deprecatedVideoKeysLogged.has(pair)) {
803
+ return;
804
+ }
805
+ deprecatedVideoKeysLogged.add(pair);
806
+ const voiced = targetAgent && !UUIDsEqual(targetAgent.ID, coAgent.ID) ? `'${targetAgent.Name}' (co-agent '${coAgent.Name}')` : `'${coAgent.Name}'`;
807
+ const what = keys.length === 1 ? `${keys[0]}, which is deprecated and does nothing` : `${keys.join(' and ')}, which are deprecated and do nothing`;
808
+ LogStatus(`[RealtimeCoAgent] The realtime configuration for ${voiced} sets ${what}. Choose the model with ` +
809
+ "realtime.modelPreference, and set an avatar's settings on its persona's Video binding (VendorSettings.Avatar).");
810
+ }
471
811
  /**
472
812
  * Resolves the APP cascade layer JSON from `Application.AgentSettings`: the `Realtime` overrides
473
813
  * (persona/disclosure/model) plus `RelevantAgents` mapped to the union-accumulated allowed-agent
@@ -484,6 +824,30 @@ export class RealtimeClientSessionService {
484
824
  async resolveAppRealtimeOverrides(applicationId, contextUser,
485
825
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
486
826
  provider) {
827
+ const settings = await this.loadAppAgentSettings(applicationId, contextUser);
828
+ if (!settings) {
829
+ return null;
830
+ }
831
+ const relevantAgents = (settings.RelevantAgents ?? []).map(r => {
832
+ const entry = { agentId: r.AgentID };
833
+ if (r.Label) {
834
+ entry.label = r.Label;
835
+ }
836
+ if (r.Disclosure === 'silent' || r.Disclosure === 'mention' || r.Disclosure === 'hand-voice') {
837
+ entry.disclosure = r.Disclosure;
838
+ }
839
+ return entry;
840
+ });
841
+ return BuildAppRealtimeOverridesJson(settings.Realtime ?? null, relevantAgents);
842
+ }
843
+ /**
844
+ * Reads and parses an application's `AgentSettings` (one tiny by-ID read, served from the provider's
845
+ * RunView cache on repeat). The RAW column is parsed with {@link ParseAgentSettings} rather than read
846
+ * through the CodeGen-generated `AgentSettingsObject` accessor, so a field added to the settings
847
+ * interface works the moment the code reading it ships, before CodeGen next refreshes the copy.
848
+ * Tolerant — a blank id, a failed read, a missing app, or an app with no usable settings returns `null`.
849
+ */
850
+ async loadAppAgentSettings(applicationId, contextUser) {
487
851
  const appId = applicationId?.trim();
488
852
  if (!appId) {
489
853
  return null;
@@ -499,24 +863,10 @@ export class RealtimeClientSessionService {
499
863
  if (!result.Success || !result.Results || result.Results.length === 0) {
500
864
  return null;
501
865
  }
502
- const settings = result.Results[0].AgentSettingsObject;
503
- if (!settings) {
504
- return null;
505
- }
506
- const relevantAgents = (settings.RelevantAgents ?? []).map(r => {
507
- const entry = { agentId: r.AgentID };
508
- if (r.Label) {
509
- entry.label = r.Label;
510
- }
511
- if (r.Disclosure === 'silent' || r.Disclosure === 'mention' || r.Disclosure === 'hand-voice') {
512
- entry.disclosure = r.Disclosure;
513
- }
514
- return entry;
515
- });
516
- return BuildAppRealtimeOverridesJson(settings.Realtime ?? null, relevantAgents);
866
+ return ParseAgentSettings(result.Results[0].AgentSettings);
517
867
  }
518
868
  catch (error) {
519
- LogError(`RealtimeClientSessionService.resolveAppRealtimeOverrides failed for app '${appId}': ${error instanceof Error ? error.message : String(error)}`);
869
+ LogError(`RealtimeClientSessionService.loadAppAgentSettings failed for app '${appId}': ${error instanceof Error ? error.message : String(error)}`);
520
870
  return null;
521
871
  }
522
872
  }
@@ -590,11 +940,30 @@ export class RealtimeClientSessionService {
590
940
  run.UserID = userID;
591
941
  }
592
942
  if (await run.Save()) {
943
+ this.KeepCoAgentRunAlive(run.ID, provider, contextUser);
593
944
  return run.ID;
594
945
  }
595
946
  LogError(`RealtimeClientSessionService.createCoAgentRun save failed: ${run.LatestResult?.CompleteMessage ?? 'unknown error'}`);
596
947
  return null;
597
948
  }
949
+ /**
950
+ * Keeps a voice session's co-agent run alive as far as the {@link AgentRunWatchdog} is concerned. The
951
+ * run spans the whole call, but no agent loop owns it, so nothing stamped its heartbeat: the watchdog
952
+ * force-failed every call that ran past ~5 minutes ("no liveness heartbeat … owning process presumed
953
+ * dead") while the call carried on. Called when the run is created and again on each persisted
954
+ * session heartbeat (`SessionManager`), so whichever server instance the session is talking to keeps
955
+ * it fresh; the watchdog drops it once it is finalized. Only a database provider can stamp heartbeats —
956
+ * any other provider is a no-op, as for every agent run.
957
+ *
958
+ * @param coAgentRunID The session's co-agent run id (from its `Config`), or nothing.
959
+ * @param provider The request-scoped metadata provider.
960
+ * @param contextUser The user the heartbeat writes run as.
961
+ */
962
+ KeepCoAgentRunAlive(coAgentRunID, provider, contextUser) {
963
+ if (coAgentRunID && provider instanceof DatabaseProviderBase) {
964
+ AgentRunWatchdog.Instance.Track(coAgentRunID, provider, contextUser);
965
+ }
966
+ }
598
967
  /**
599
968
  * Creates the co-agent `AIPromptRun` row (Status `Running`) linked to the co-agent run via
600
969
  * `AgentRunID` AND to the co-agent itself via `AgentID` — so the run shows up both on the
@@ -672,11 +1041,59 @@ export class RealtimeClientSessionService {
672
1041
  * @param provider The request-scoped metadata provider.
673
1042
  * @param success Whether the session ended successfully (controls Completed vs Failed).
674
1043
  * @param coAgentRunStepID The co-agent run's single `MJ: AI Agent Run Steps` row id, or `null` to skip.
1044
+ * @param errorMessage Why the session failed (for example the bridge start's error), stamped as `ErrorMessage` on each
1045
+ * record it fails. Ignored when `success` is true. Without it the step gets a generic line and the runs none.
675
1046
  */
676
- async FinalizeCoAgentRun(coAgentRunID, promptRunID, contextUser, provider, success = true, coAgentRunStepID = null) {
677
- await this.finalizeAgentRun(coAgentRunID, contextUser, provider, success);
678
- await this.finalizePromptRun(promptRunID, contextUser, provider, success);
679
- await this.finalizeRunStep(coAgentRunStepID, contextUser, provider, success);
1047
+ async FinalizeCoAgentRun(coAgentRunID, promptRunID, contextUser, provider, success = true, coAgentRunStepID = null, errorMessage) {
1048
+ const failure = success ? undefined : errorMessage?.trim() || undefined;
1049
+ try {
1050
+ await this.finalizeAgentRun(coAgentRunID, contextUser, provider, success, failure);
1051
+ await this.finalizePromptRun(promptRunID, contextUser, provider, success, failure);
1052
+ await this.finalizeRunStep(coAgentRunStepID, contextUser, provider, success, failure);
1053
+ }
1054
+ finally {
1055
+ // Even when a finalize step throws, the run still owes its cost, and the watchdog must stop
1056
+ // treating it as alive — or a run stuck at Running would be kept fresh indefinitely.
1057
+ await this.rollUpCoAgentRunUsage(coAgentRunID, promptRunID, contextUser, provider);
1058
+ if (coAgentRunID) {
1059
+ AgentRunWatchdog.Instance.Untrack(coAgentRunID);
1060
+ }
1061
+ }
1062
+ }
1063
+ /**
1064
+ * Copies the co-agent prompt run's tokens and cost onto the co-agent run. The realtime model's usage
1065
+ * accumulates on the prompt run ({@link AccumulatePromptRunUsage}), which prices itself; the run's
1066
+ * own `TotalCost` / `Total*TokensUsed` stayed 0, so everything that sums agent runs — the realtime
1067
+ * analytics dashboard's per-session cost among them — left out the voice model entirely and showed
1068
+ * only the delegated runs. Mirrors how an agent loop derives its run totals from its prompt runs.
1069
+ *
1070
+ * Applied whatever the run's status: a run the watchdog already failed, or one a shutdown cancelled,
1071
+ * still owes its cost. Runs after {@link finalizePromptRun}, which waits for in-flight usage writes,
1072
+ * so the copy sees the final counts. Tolerant: logs, never throws.
1073
+ */
1074
+ async rollUpCoAgentRunUsage(coAgentRunID, promptRunID, contextUser, provider) {
1075
+ if (!coAgentRunID || !promptRunID) {
1076
+ return;
1077
+ }
1078
+ try {
1079
+ const promptRun = await provider.GetEntityObject('MJ: AI Prompt Runs', contextUser);
1080
+ const run = await provider.GetEntityObject('MJ: AI Agent Runs', contextUser);
1081
+ if (!(await promptRun.Load(promptRunID)) || !(await run.Load(coAgentRunID))) {
1082
+ return;
1083
+ }
1084
+ const promptTokens = promptRun.TokensPrompt ?? 0;
1085
+ const completionTokens = promptRun.TokensCompletion ?? 0;
1086
+ run.TotalPromptTokensUsed = promptTokens;
1087
+ run.TotalCompletionTokensUsed = completionTokens;
1088
+ run.TotalTokensUsed = promptRun.TokensUsed ?? promptTokens + completionTokens;
1089
+ run.TotalCost = promptRun.TotalCost ?? promptRun.Cost ?? 0;
1090
+ if (run.Dirty && !(await run.Save())) {
1091
+ LogError(`RealtimeClientSessionService.rollUpCoAgentRunUsage save failed: ${run.LatestResult?.CompleteMessage ?? 'unknown error'}`);
1092
+ }
1093
+ }
1094
+ catch (error) {
1095
+ LogError(`RealtimeClientSessionService.rollUpCoAgentRunUsage failed: ${error instanceof Error ? error.message : String(error)}`);
1096
+ }
680
1097
  }
681
1098
  /**
682
1099
  * Finalizes the **co-agent observability run(s)** for an agent session that were left `Running` because
@@ -763,8 +1180,11 @@ export class RealtimeClientSessionService {
763
1180
  }
764
1181
  return { PromptRunID: promptRuns.Results[0]?.ID ?? null, StepID: stepID };
765
1182
  }
766
- /** Loads + finalizes the co-agent `AIAgentRun` if still `Running`. Tolerant: logs, never throws. */
767
- async finalizeAgentRun(coAgentRunID, contextUser, provider, success) {
1183
+ /**
1184
+ * Loads + finalizes the co-agent `AIAgentRun` if still `Running`, with `failure` as its `ErrorMessage` when it fails.
1185
+ * Tolerant: logs, never throws.
1186
+ */
1187
+ async finalizeAgentRun(coAgentRunID, contextUser, provider, success, failure) {
768
1188
  if (!coAgentRunID) {
769
1189
  return;
770
1190
  }
@@ -775,16 +1195,20 @@ export class RealtimeClientSessionService {
775
1195
  run.Status = success ? 'Completed' : 'Failed';
776
1196
  run.CompletedAt = new Date();
777
1197
  run.Success = success;
1198
+ if (failure) {
1199
+ run.ErrorMessage = failure;
1200
+ }
778
1201
  if (!(await run.Save())) {
779
1202
  LogError(`RealtimeClientSessionService.finalizeAgentRun save failed: ${run.LatestResult?.CompleteMessage ?? 'unknown error'}`);
780
1203
  }
781
1204
  }
782
1205
  /**
783
1206
  * Loads + finalizes the co-agent run's single system-prompt `MJ: AI Agent Run Steps` row if
784
- * still `Running` (Status `Completed`/`Failed`, `CompletedAt`, `Success`). Tolerant: a
785
- * missing/already-finalized step is a no-op; a load/save failure is logged, never thrown.
1207
+ * still `Running` (Status `Completed`/`Failed`, `CompletedAt`, `Success`; a failed step's `ErrorMessage` is
1208
+ * `failure`, or a generic line without one). Tolerant: a missing/already-finalized step is a no-op; a
1209
+ * load/save failure is logged, never thrown.
786
1210
  */
787
- async finalizeRunStep(coAgentRunStepID, contextUser, provider, success) {
1211
+ async finalizeRunStep(coAgentRunStepID, contextUser, provider, success, failure) {
788
1212
  if (!coAgentRunStepID) {
789
1213
  return;
790
1214
  }
@@ -797,7 +1221,7 @@ export class RealtimeClientSessionService {
797
1221
  step.CompletedAt = new Date();
798
1222
  step.Success = success;
799
1223
  if (!success) {
800
- step.ErrorMessage = 'The realtime session ended in an error state.';
1224
+ step.ErrorMessage = failure ?? 'The realtime session ended in an error state.';
801
1225
  }
802
1226
  if (!(await step.Save())) {
803
1227
  LogError(`RealtimeClientSessionService.finalizeRunStep save failed: ${step.LatestResult?.CompleteMessage ?? 'unknown error'}`);
@@ -807,8 +1231,11 @@ export class RealtimeClientSessionService {
807
1231
  LogError(`RealtimeClientSessionService.finalizeRunStep failed: ${error instanceof Error ? error.message : String(error)}`);
808
1232
  }
809
1233
  }
810
- /** Loads + finalizes the co-agent `AIPromptRun` if still `Running`. Tolerant: logs, never throws. */
811
- async finalizePromptRun(promptRunID, contextUser, provider, success) {
1234
+ /**
1235
+ * Loads + finalizes the co-agent `AIPromptRun` if still `Running`, with `failure` as its `ErrorMessage` when it fails.
1236
+ * Tolerant: logs, never throws.
1237
+ */
1238
+ async finalizePromptRun(promptRunID, contextUser, provider, success, failure) {
812
1239
  if (!promptRunID) {
813
1240
  return;
814
1241
  }
@@ -822,6 +1249,9 @@ export class RealtimeClientSessionService {
822
1249
  run.Status = success ? 'Completed' : 'Failed';
823
1250
  run.CompletedAt = new Date();
824
1251
  run.Success = success;
1252
+ if (failure) {
1253
+ run.ErrorMessage = failure;
1254
+ }
825
1255
  if (!(await run.Save())) {
826
1256
  LogError(`RealtimeClientSessionService.finalizePromptRun save failed: ${run.LatestResult?.CompleteMessage ?? 'unknown error'}`);
827
1257
  }
@@ -885,12 +1315,19 @@ export class RealtimeClientSessionService {
885
1315
  * high-frequency usage checkpoint never overwrites freshly-appended transcript turns (and vice-versa).
886
1316
  * Best-effort: load/save failures log and return `false`, never throw.
887
1317
  *
1318
+ * The per-modality details add into the usage record the run keeps in `ModelSpecificResponseDetails`
1319
+ * (`RealtimeUsage.Input` / `.Output`, which pricing reads at finalize); every other key there is kept. The
1320
+ * stored output video seconds never exceed the run's elapsed time plus 30 seconds, and the stored output video
1321
+ * tokens never exceed 6,192 a second of that: usage is client-reported, and avatar video carries a price, per
1322
+ * minute or per token.
1323
+ *
888
1324
  * @param promptRunID The co-agent observability prompt run.
889
1325
  * @param inputDelta Input-token delta to add (caller clamps to >= 0).
890
1326
  * @param outputDelta Output-token delta to add (caller clamps to >= 0).
1327
+ * @param details Per-modality usage to add (input and output blocks, avatar video seconds included).
891
1328
  * @returns `true` when the accumulated usage was persisted.
892
1329
  */
893
- async AccumulatePromptRunUsage(promptRunID, inputDelta, outputDelta, contextUser, provider) {
1330
+ async AccumulatePromptRunUsage(promptRunID, inputDelta, outputDelta, contextUser, provider, details) {
894
1331
  return this.serializePromptRunWrite(promptRunID, async () => {
895
1332
  try {
896
1333
  const promptRun = await provider.GetEntityObject('MJ: AI Prompt Runs', contextUser);
@@ -901,6 +1338,9 @@ export class RealtimeClientSessionService {
901
1338
  promptRun.TokensPrompt = (promptRun.TokensPrompt ?? 0) + inputDelta;
902
1339
  promptRun.TokensCompletion = (promptRun.TokensCompletion ?? 0) + outputDelta;
903
1340
  promptRun.TokensUsed = (promptRun.TokensPrompt ?? 0) + (promptRun.TokensCompletion ?? 0);
1341
+ if (details) {
1342
+ this.mergeUsageDetails(promptRun, details);
1343
+ }
904
1344
  if (!(await promptRun.Save())) {
905
1345
  LogError(`AccumulatePromptRunUsage: prompt run ${promptRunID} save failed: ${promptRun.LatestResult?.CompleteMessage ?? 'unknown error'}`);
906
1346
  return false;
@@ -913,6 +1353,37 @@ export class RealtimeClientSessionService {
913
1353
  }
914
1354
  });
915
1355
  }
1356
+ /**
1357
+ * Adds relayed per-modality usage into the run's usage record, with the output video seconds capped at the run's
1358
+ * elapsed time plus {@link VIDEO_SECONDS_GRACE}, and the output video tokens at that many seconds of
1359
+ * {@link VIDEO_TOKENS_PER_SECOND}. Details that are not a JSON object are left alone (logged).
1360
+ */
1361
+ mergeUsageDetails(promptRun, details) {
1362
+ const runAt = promptRun.RunAt ? new Date(promptRun.RunAt).getTime() : Number.NaN;
1363
+ const elapsedSeconds = Math.max(0, (Date.now() - runAt) / 1000);
1364
+ const maxVideoSeconds = Number.isFinite(elapsedSeconds) ? elapsedSeconds + VIDEO_SECONDS_GRACE : undefined;
1365
+ const merged = MergeRealtimeUsageRecord(promptRun.ModelSpecificResponseDetails, details, {
1366
+ MaxOutputVideoSeconds: maxVideoSeconds,
1367
+ MaxOutputVideoTokens: maxVideoSeconds === undefined ? undefined : maxVideoSeconds * VIDEO_TOKENS_PER_SECOND,
1368
+ });
1369
+ if (!merged) {
1370
+ LogError(`AccumulatePromptRunUsage: prompt run ${promptRun.ID} has details that are not a JSON object — usage details dropped.`);
1371
+ return;
1372
+ }
1373
+ this.logClampedVideo(promptRun.ID, merged);
1374
+ promptRun.ModelSpecificResponseDetails = merged.Details;
1375
+ }
1376
+ /** One log line for each output video quantity the merge capped. */
1377
+ logClampedVideo(promptRunID, merged) {
1378
+ if (merged.ClampedVideoSeconds > 0) {
1379
+ LogStatus(`AccumulatePromptRunUsage: prompt run ${promptRunID} reported ${merged.ClampedVideoSeconds} s more avatar video than ` +
1380
+ `the run's elapsed time plus ${VIDEO_SECONDS_GRACE} s allows; the stored seconds are capped.`);
1381
+ }
1382
+ if (merged.ClampedVideoTokens > 0) {
1383
+ LogStatus(`AccumulatePromptRunUsage: prompt run ${promptRunID} reported ${merged.ClampedVideoTokens} more avatar video tokens than ` +
1384
+ `${VIDEO_TOKENS_PER_SECOND} a second of the run's elapsed time plus ${VIDEO_SECONDS_GRACE} s allows; the stored tokens are capped.`);
1385
+ }
1386
+ }
916
1387
  /** Parses the prompt run's `Messages` JSON into a mutable chat-message array (tolerant: `[]` on empty/malformed). */
917
1388
  parsePromptRunMessages(raw) {
918
1389
  if (!raw || !raw.trim()) {
@@ -949,9 +1420,10 @@ export class RealtimeClientSessionService {
949
1420
  // CancelRealtimeSessionTool mutation) can abort it mid-flight. The registry controller's
950
1421
  // signal is combined with any caller-supplied signal — either source cancels the run.
951
1422
  const controller = this.registerInFlightDelegation(input.AgentSessionID, input.Call.CallID);
1423
+ const combined = this.combineSignals(controller.signal, input.AbortSignal);
952
1424
  const effectiveInput = {
953
1425
  ...input,
954
- AbortSignal: input.AbortSignal ? this.combineSignals(controller.signal, input.AbortSignal) : controller.signal
1426
+ AbortSignal: combined.Signal
955
1427
  };
956
1428
  try {
957
1429
  const broker = this.buildToolBroker(effectiveInput, contextUser, provider);
@@ -959,6 +1431,7 @@ export class RealtimeClientSessionService {
959
1431
  return { ResultJson: result.ResultJson, Success: result.Success, PausedRunID: result.PausedRunID, Artifacts: result.Artifacts };
960
1432
  }
961
1433
  finally {
1434
+ combined.Dispose();
962
1435
  this.unregisterInFlightDelegation(input.AgentSessionID, input.Call.CallID, controller);
963
1436
  }
964
1437
  }
@@ -1076,12 +1549,19 @@ export class RealtimeClientSessionService {
1076
1549
  * {@link resolveConfiguredModelPreference}. METADATA preferences degrade gracefully — an
1077
1550
  * unsatisfiable preference logs and FALLS THROUGH to the default (mirroring the co-agent
1078
1551
  * resolution chain's tolerant metadata steps), it never breaks calls.
1079
- * - Without either: the existing default behavior via {@link resolveRealtimeModel}
1080
- * (highest-PowerRank active Realtime model), with the generic {@link noModelMessage} on failure.
1552
+ * - Without either: the default walk ({@link resolveDefaultRealtimeModel}): for a co-agent with video on, in a session
1553
+ * that could show an avatar (a browser session, or a server-side one with {@link PrepareClientSessionInput.AvatarDelivery}
1554
+ * `'room'`), the first candidate that shows one ({@link ResolveAvatarRealtimeModel}); else the existing default via
1555
+ * {@link resolveRealtimeModel} (highest-PowerRank active Realtime model), with the generic
1556
+ * {@link noModelMessage} on failure. The two explicit choices above win over the video preference.
1557
+ *
1558
+ * On every path the chosen model's vendor follows whether the session will show an avatar (the video setting is on
1559
+ * and the session could show one): among the model's keyed vendors, one that renders avatars (Vertex AI for Gemini
1560
+ * 3.8 Live) only when it will, else one that renders none; see {@link resolveVendorAndInstantiate}.
1081
1561
  *
1082
1562
  * @param input The prepare-session input (carries the optional preferred model id).
1083
1563
  * @param coAgent The resolved co-agent (threaded to the default-resolution seam).
1084
- * @param effectiveConfig The resolved effective configuration (carries `modelPreference`).
1564
+ * @param effectiveConfig The resolved effective configuration (carries `modelPreference` and the video setting).
1085
1565
  * @returns The resolution outcome (resolution or failure reason).
1086
1566
  */
1087
1567
  async resolveModelForSession(input, coAgent, effectiveConfig) {
@@ -1093,16 +1573,61 @@ export class RealtimeClientSessionService {
1093
1573
  // subclass that overrides the seam would lose to AI_VENDOR_API_KEY__<driver>.
1094
1574
  const resolveRunKey = this.buildRunKeyResolver(input.APIKeys);
1095
1575
  const scope = input.CredentialScope ?? 'Any';
1576
+ const preferAvatar = effectiveConfig?.realtime?.video?.enabled === true && RealtimeSessionCanShowAvatar(input);
1096
1577
  if (input.PreferredModelID) {
1097
- return this.resolvePreferredRealtimeModel(input.PreferredModelID, resolveRunKey, scope);
1578
+ return this.resolvePreferredRealtimeModel(input.PreferredModelID, resolveRunKey, scope, preferAvatar);
1098
1579
  }
1099
- const fromConfig = this.resolveConfiguredModelPreference(effectiveConfig, resolveRunKey, scope);
1580
+ const fromConfig = this.resolveConfiguredModelPreference(effectiveConfig, resolveRunKey, scope, preferAvatar);
1100
1581
  if (fromConfig) {
1101
1582
  return { Resolution: fromConfig };
1102
1583
  }
1103
- const resolution = await this.resolveRealtimeModel(coAgent, resolveRunKey, scope);
1584
+ const resolution = await this.resolveDefaultRealtimeModel(coAgent, preferAvatar, resolveRunKey, scope);
1104
1585
  return resolution ? { Resolution: resolution } : { ErrorMessage: this.noModelMessage() };
1105
1586
  }
1587
+ /**
1588
+ * The default walk. With `preferAvatar` (the co-agent's video setting is on and the session could show an avatar),
1589
+ * it takes the first candidate that shows one ({@link ResolveAvatarRealtimeModel}). When none does, or without it, it
1590
+ * takes {@link resolveRealtimeModel}'s choice; when one was preferred, one log line says the call stays audio only.
1591
+ */
1592
+ async resolveDefaultRealtimeModel(coAgent, preferAvatar, resolve, credentialScope) {
1593
+ const withAvatar = preferAvatar ? this.ResolveAvatarRealtimeModel(coAgent, resolve, credentialScope) : null;
1594
+ if (withAvatar) {
1595
+ return withAvatar;
1596
+ }
1597
+ const resolution = await this.resolveRealtimeModel(coAgent, resolve, credentialScope, preferAvatar);
1598
+ if (preferAvatar && resolution) {
1599
+ LogStatus('[RealtimeCoAgent] Video is on, but no realtime model with a usable key shows an avatar (its Video/Output row ' +
1600
+ `and its endpoint): using '${resolution.ModelName ?? resolution.APIName}' on ${resolution.DriverClass ?? 'its driver'}, audio only.`);
1601
+ }
1602
+ return resolution;
1603
+ }
1604
+ /**
1605
+ * For a co-agent with video on: the first candidate that shows an avatar and supports client-direct sessions, in the
1606
+ * default walk's order (highest PowerRank first; a model's Active vendor rows by Priority, each with a usable key).
1607
+ * A candidate shows an avatar when its model's Video/Output row allows video or it has none, and its driver renders
1608
+ * avatars for the vendor's API name on its endpoint ({@link RealtimeModelShowsAvatar}). Every keyed vendor of a model
1609
+ * is tried, not only the first. **Overridable seam.**
1610
+ *
1611
+ * @param coAgent The co-agent (reserved for future per-agent model preference).
1612
+ * @param resolve The session's run-scoped key resolver (run keys only; see {@link resolveVendorAndInstantiate}).
1613
+ * @param credentialScope The session's credential scope; see {@link resolveVendorAndInstantiate}.
1614
+ * @returns The resolution, or `null` when no candidate shows an avatar.
1615
+ */
1616
+ ResolveAvatarRealtimeModel(coAgent, resolve, credentialScope = 'Any') {
1617
+ const resolveKey = this.buildKeyChain(resolve, credentialScope);
1618
+ for (const model of this.selectRealtimeModelCandidates(coAgent)) {
1619
+ if (ReadRealtimeVideoOutputRow(model.ID, AIEngine.Instance) === 'unsupported') {
1620
+ continue;
1621
+ }
1622
+ for (const vendor of ListRealtimeVendorsForModel(model.ID)) {
1623
+ const resolution = this.instantiateRealtimeVendor(model, vendor, resolveKey);
1624
+ if (resolution?.Model.SupportsClientDirect && RealtimeModelShowsAvatar(resolution, AIEngine.Instance)) {
1625
+ return resolution;
1626
+ }
1627
+ }
1628
+ }
1629
+ return null;
1630
+ }
1106
1631
  /**
1107
1632
  * The session's run-scoped keys as a resolver: the key for a driver class when the run carries
1108
1633
  * one, else `undefined` — no platform fallback. The fallback belongs to
@@ -1125,9 +1650,10 @@ export class RealtimeClientSessionService {
1125
1650
  * @param effectiveConfig The resolved effective configuration.
1126
1651
  * @param resolve The session's run-scoped key resolver (run keys only; see {@link resolveVendorAndInstantiate}).
1127
1652
  * @param credentialScope The session's credential scope; see {@link resolveVendorAndInstantiate}.
1653
+ * @param showsAvatar Whether the session will show an avatar; see {@link resolveVendorAndInstantiate}.
1128
1654
  * @returns The resolution, or `null` when no preference is configured or it can't be satisfied.
1129
1655
  */
1130
- resolveConfiguredModelPreference(effectiveConfig, resolve, credentialScope = 'Any') {
1656
+ resolveConfiguredModelPreference(effectiveConfig, resolve, credentialScope = 'Any', showsAvatar = false) {
1131
1657
  const preference = effectiveConfig?.realtime?.modelPreference;
1132
1658
  if (!preference) {
1133
1659
  return null;
@@ -1143,7 +1669,7 @@ export class RealtimeClientSessionService {
1143
1669
  `'${model.Name}' but it is not an Active Realtime model — falling through to default resolution.`);
1144
1670
  return null;
1145
1671
  }
1146
- const resolution = this.resolveVendorAndInstantiate(model, resolve, credentialScope);
1672
+ const resolution = this.resolveVendorAndInstantiate(model, resolve, credentialScope, showsAvatar);
1147
1673
  if (!resolution) {
1148
1674
  LogError(`RealtimeClientSessionService: configured realtime model preference '${model.Name}' has no usable ` +
1149
1675
  'vendor DriverClass/API key — falling through to default resolution.');
@@ -1177,9 +1703,10 @@ export class RealtimeClientSessionService {
1177
1703
  * @param preferredModelID The `MJ: AI Models.ID` the user chose.
1178
1704
  * @param resolve The session's run-scoped key resolver (run keys only; see {@link resolveVendorAndInstantiate}).
1179
1705
  * @param credentialScope The session's credential scope; see {@link resolveVendorAndInstantiate}.
1706
+ * @param showsAvatar Whether the session will show an avatar; see {@link resolveVendorAndInstantiate}.
1180
1707
  * @returns The resolution outcome (resolution or a specific failure reason).
1181
1708
  */
1182
- resolvePreferredRealtimeModel(preferredModelID, resolve, credentialScope = 'Any') {
1709
+ resolvePreferredRealtimeModel(preferredModelID, resolve, credentialScope = 'Any', showsAvatar = false) {
1183
1710
  const model = this.findModelByID(preferredModelID);
1184
1711
  if (!model) {
1185
1712
  return { ErrorMessage: `The requested realtime model (id '${preferredModelID}') was not found in AI model metadata.` };
@@ -1190,7 +1717,7 @@ export class RealtimeClientSessionService {
1190
1717
  if (!this.isRealtimeModel(model)) {
1191
1718
  return { ErrorMessage: `The requested model '${model.Name}' is not a Realtime model (its type is '${model.AIModelType}').` };
1192
1719
  }
1193
- const resolution = this.resolveVendorAndInstantiate(model, resolve, credentialScope);
1720
+ const resolution = this.resolveVendorAndInstantiate(model, resolve, credentialScope, showsAvatar);
1194
1721
  if (!resolution) {
1195
1722
  return {
1196
1723
  ErrorMessage: `The requested model '${model.Name}' has no active vendor with a usable DriverClass/API key ` +
@@ -1224,9 +1751,10 @@ export class RealtimeClientSessionService {
1224
1751
  * @param coAgent The co-agent being voiced (reserved for future per-agent model preference).
1225
1752
  * @param resolve The session's run-scoped key resolver (run keys only; see {@link resolveVendorAndInstantiate}).
1226
1753
  * @param credentialScope The session's credential scope; see {@link resolveVendorAndInstantiate}.
1754
+ * @param showsAvatar Whether the session will show an avatar; see {@link resolveVendorAndInstantiate}.
1227
1755
  * @returns The resolved model + identifiers, or `null`.
1228
1756
  */
1229
- async resolveRealtimeModel(coAgent, resolve, credentialScope = 'Any') {
1757
+ async resolveRealtimeModel(coAgent, resolve, credentialScope = 'Any', showsAvatar = false) {
1230
1758
  // Walk candidates in descending PowerRank, returning the FIRST that fully resolves to a usable
1231
1759
  // client-direct driver (active vendor + API key + ClassFactory driver + SupportsClientDirect).
1232
1760
  // Single-pick dead-ended whenever the highest-power model lacked a key or client-direct support
@@ -1234,7 +1762,7 @@ export class RealtimeClientSessionService {
1234
1762
  // surfaced "No usable Realtime model" instead of falling through to a model that works.
1235
1763
  const candidates = this.selectRealtimeModelCandidates(coAgent);
1236
1764
  for (const model of candidates) {
1237
- const resolution = this.resolveVendorAndInstantiate(model, resolve, credentialScope);
1765
+ const resolution = this.resolveVendorAndInstantiate(model, resolve, credentialScope, showsAvatar);
1238
1766
  if (resolution && resolution.Model.SupportsClientDirect) {
1239
1767
  return resolution;
1240
1768
  }
@@ -1256,19 +1784,40 @@ export class RealtimeClientSessionService {
1256
1784
  * @param credentialScope A scope that rules out the `'Environment'` source (`'RuntimeOnly'`) drops the
1257
1785
  * {@link getAPIKeyForDriver} seam: the run's keys are the whole chain, so a vendor they do not key
1258
1786
  * is never selected on the platform's key.
1787
+ * @param showsAvatar Whether the session will show an avatar. The highest-Priority keyed vendor stands when it
1788
+ * renders avatars ({@link RealtimeModelShowsAvatar}) exactly when the session will show one; otherwise the first
1789
+ * other keyed vendor that does is taken, when there is one. So a vendor that renders avatars (Vertex AI for Gemini
1790
+ * 3.8 Live, with its own billing and limits) takes a session only when it will show an avatar, or when it is the
1791
+ * only keyed vendor; and a session that will show one goes to such a vendor whatever the Priority order.
1259
1792
  * @returns The full resolution, or `null` when no vendor/key/driver can be satisfied.
1260
1793
  */
1261
- resolveVendorAndInstantiate(model, resolve, credentialScope = 'Any') {
1262
- // The run's keys first, then this service's own seam (which subclasses and tests override) —
1263
- // so a run-scoped credential wins without taking that seam away from anyone who replaced it.
1264
- // A scope that rules out the environment has no second step: the seam's default is the platform key.
1265
- const resolveKey = CredentialScopeAllows(credentialScope, 'Environment')
1794
+ resolveVendorAndInstantiate(model, resolve, credentialScope = 'Any', showsAvatar = false) {
1795
+ const resolveKey = this.buildKeyChain(resolve, credentialScope);
1796
+ const vendor = this.selectRealtimeVendor(model.ID, resolveKey);
1797
+ const first = vendor ? this.instantiateRealtimeVendor(model, vendor, resolveKey) : null;
1798
+ if (!vendor || !first) {
1799
+ return first;
1800
+ }
1801
+ return ChooseRealtimeVendorForAvatar(vendor, first, ListRealtimeVendorsForModel(model.ID), showsAvatar, {
1802
+ Instantiate: (other) => this.instantiateRealtimeVendor(model, other, resolveKey),
1803
+ RendersAvatar: (resolution) => RealtimeModelShowsAvatar(resolution, AIEngine.Instance),
1804
+ // A stand-in does client-direct sessions when the first one does.
1805
+ Accepts: (resolution) => resolution.Model.SupportsClientDirect || !first.Model.SupportsClientDirect,
1806
+ });
1807
+ }
1808
+ /**
1809
+ * The session's complete key chain for vendor selection and the mint (see {@link resolveVendorAndInstantiate}): the
1810
+ * run's keys first, then this service's own seam (which subclasses and tests override), so a run-scoped credential
1811
+ * wins without taking that seam away from anyone who replaced it. A scope that rules out the environment has no second
1812
+ * step: the seam's default is the platform key.
1813
+ */
1814
+ buildKeyChain(resolve, credentialScope) {
1815
+ return CredentialScopeAllows(credentialScope, 'Environment')
1266
1816
  ? (driverClass) => resolve?.(driverClass) ?? this.getAPIKeyForDriver(driverClass)
1267
1817
  : (driverClass) => resolve?.(driverClass);
1268
- const vendor = this.selectRealtimeVendor(model.ID, resolveKey);
1269
- if (!vendor) {
1270
- return null;
1271
- }
1818
+ }
1819
+ /** Instantiates a vendor's realtime driver with its key from the chain; `null` when the key or the driver is missing. */
1820
+ instantiateRealtimeVendor(model, vendor, resolveKey) {
1272
1821
  const apiKey = resolveKey(vendor.DriverClass);
1273
1822
  if (!apiKey) {
1274
1823
  return null;
@@ -1313,7 +1862,9 @@ export class RealtimeClientSessionService {
1313
1862
  }
1314
1863
  /**
1315
1864
  * The active models of AIModelType `Realtime`, sorted highest-PowerRank first — the candidate
1316
- * list {@link resolveRealtimeModel} walks until one yields a usable client-direct driver.
1865
+ * list {@link resolveRealtimeModel} walks until one yields a usable client-direct driver, and
1866
+ * {@link ResolveAvatarRealtimeModel} walks first for a co-agent with video on. Equal PowerRanks
1867
+ * keep the engine's cached order (a stable sort).
1317
1868
  * Returns ALL candidates (not just the top pick) so a keyless or non-client-direct top model
1318
1869
  * falls through to the next usable one instead of dead-ending the whole resolution.
1319
1870
  *
@@ -1364,10 +1915,11 @@ export class RealtimeClientSessionService {
1364
1915
  * @param driverClass The resolved vendor's DriverClass — matches per-provider voice settings.
1365
1916
  * @param modelID The resolved `MJ: AI Models` id — keys the model-catalog `ModelConfiguration` cascade.
1366
1917
  * @param modelVendorID The resolved `MJ: AI Model Vendors` ROW id — the cascade's most-specific layer.
1918
+ * @param resolvedAvatar The session's avatar resolution, when the caller already made it; resolved here otherwise.
1367
1919
  * @returns The assembled session params.
1368
1920
  */
1369
- async buildSessionParams(input, coAgent, modelApiName, contextUser, provider, effectiveConfig, driverClass, modelID, modelVendorID) {
1370
- const directTools = this.BuildDirectActionTools(input.TargetAgentID, effectiveConfig, driverClass, input.AgentSessionID);
1921
+ async buildSessionParams(input, coAgent, modelApiName, contextUser, provider, effectiveConfig, driverClass, modelID, modelVendorID, resolvedAvatar) {
1922
+ const directTools = this.projectDirectActions(input, effectiveConfig, driverClass);
1371
1923
  const hasDirectTools = directTools.length > 0 || (input.ExtraTools != null && input.ExtraTools.length > 0);
1372
1924
  const systemPrompt = await this.buildCompanionSystemPrompt(input, coAgent, contextUser, provider, effectiveConfig, hasDirectTools);
1373
1925
  const memoryContext = await this.assembleMemoryContext(input, coAgent, contextUser, provider);
@@ -1376,8 +1928,11 @@ export class RealtimeClientSessionService {
1376
1928
  : input.ExtraTools;
1377
1929
  const tools = this.appendHostTools(this.buildStableToolSet(combinedExtra), input.HostTools);
1378
1930
  // Hoisted (rather than built inline at the return) so the mint log below can report the voice
1379
- // that ACTUALLY reached the driver — see the `voice=` field. Same bag, built once.
1380
- const configBag = this.buildSessionConfigBag(input, effectiveConfig, driverClass, modelID, modelVendorID);
1931
+ // that ACTUALLY reached the driver — see the `voice=` field. Same bag, built once. A phone call, or
1932
+ // an app without agent video, carries no avatar request whoever resolved it (WithoutUnseenAvatar is
1933
+ // idempotent).
1934
+ const avatar = WithoutUnseenAvatar(resolvedAvatar ?? this.ResolveSessionAvatar(input, coAgent, effectiveConfig, modelID, modelVendorID), input);
1935
+ const configBag = this.withAvatarVoice(this.buildSessionConfigBag(input, effectiveConfig, driverClass, modelID, modelVendorID), avatar, input);
1381
1936
  WarnOnUnmatchedProviderVoice(effectiveConfig, driverClass, 'RealtimeClientSessionService');
1382
1937
  // One line per mint: confirms which tools + whether the channel-direct framing actually reach
1383
1938
  // the model — settles "why does the co-agent delegate instead of calling browser_*" without
@@ -1386,6 +1941,7 @@ export class RealtimeClientSessionService {
1386
1941
  // actually reached the driver legible — the whole failure mode in #3530 was that it was not.
1387
1942
  console.log(`[RealtimeCoAgent] mint model=${modelApiName} driver=${driverClass ?? 'unknown'} ` +
1388
1943
  `voice=${typeof configBag?.['voice'] === 'string' ? configBag['voice'] : 'none'} ` +
1944
+ `avatar=${avatar.Avatar ? avatar.Avatar.AvatarID : avatar.Reason ? `none(${avatar.Reason})` : 'none'} ` +
1389
1945
  `tools=[${tools.map(t => t.Name).join(', ')}] ` +
1390
1946
  `channelExceptionInPrompt=${systemPrompt.includes('interactive-surface')}`);
1391
1947
  return {
@@ -1400,8 +1956,58 @@ export class RealtimeClientSessionService {
1400
1956
  MaxSessionSeconds: input.MaxSessionSeconds,
1401
1957
  UserID: contextUser?.ID,
1402
1958
  HasToolFraming: true,
1959
+ ...(avatar.Avatar ? { Avatar: input.AvatarDelivery ? { ...avatar.Avatar, Delivery: input.AvatarDelivery } : avatar.Avatar } : {}),
1403
1960
  };
1404
1961
  }
1962
+ /**
1963
+ * The live avatar this session asks for, if any: from the voiced agent's persona, or `realtime.video.avatarId`,
1964
+ * when the agent's video setting is on (see `ResolveRealtimeAvatar`). A call that picked an avatar (its runtime
1965
+ * override names `realtime.video.avatarId`) while that setting is off asks for none, with reason `video-off`. A model
1966
+ * whose `MJ: AI Model Modalities`
1967
+ * Video/Output row turns video off asks for none (reason `endpoint`, one log line); otherwise whether the session can
1968
+ * render it is the driver's call. A seam so tests can supply a resolution without the engine's persona metadata.
1969
+ *
1970
+ * @param input The prepare-session input (the voiced agent).
1971
+ * @param coAgent The co-agent.
1972
+ * @param effectiveConfig The effective configuration.
1973
+ * @param modelID The resolved model.
1974
+ * @param modelVendorID The resolved model-vendor row; its vendor scopes the persona bindings.
1975
+ */
1976
+ ResolveSessionAvatar(input, coAgent, effectiveConfig, modelID, modelVendorID) {
1977
+ const videoOn = effectiveConfig?.realtime?.video?.enabled === true;
1978
+ const avatarPicked = !!ResolveEffectiveRealtimeConfig(null, null, input.ConfigOverridesJson).realtime?.video?.avatarId;
1979
+ if (!modelID || (!videoOn && !avatarPicked)) {
1980
+ return {};
1981
+ }
1982
+ const vendorID = modelVendorID ? AIEngine.Instance.ModelVendors.find((mv) => UUIDsEqual(mv.ID, modelVendorID))?.VendorID : undefined;
1983
+ const videoOutputRow = ReadRealtimeVideoOutputRow(modelID, AIEngine.Instance);
1984
+ if (videoOn && videoOutputRow === 'unsupported') {
1985
+ LogStatus(`[RealtimeCoAgent] No avatar asked for: the Video/Output modality row of '${this.findModelByID(modelID)?.Name ?? modelID}' ` +
1986
+ 'turns video off (IsSupported false). The call is audio only. Reason: endpoint.');
1987
+ }
1988
+ return ResolveRealtimeAvatar({
1989
+ EffectiveConfig: effectiveConfig,
1990
+ TargetAgentID: input.TargetAgentID,
1991
+ CoAgentID: coAgent.ID,
1992
+ ModelID: modelID,
1993
+ VendorID: vendorID,
1994
+ VideoOutputRow: videoOutputRow,
1995
+ AvatarPicked: avatarPicked,
1996
+ }, AIEngine.Instance);
1997
+ }
1998
+ /**
1999
+ * The config bag with the avatar persona's voice, so the face and the voice match, unless a voice was picked in this
2000
+ * call (a runtime override's `realtime.voice.default.voice`), which wins. A session nobody would see the avatar in (a
2001
+ * phone call, an app without agent video) keeps the voice without the face, so the agent sounds the same as in a call
2002
+ * that shows it.
2003
+ */
2004
+ withAvatarVoice(bag, avatar, input) {
2005
+ if (!avatar.Voice) {
2006
+ return bag;
2007
+ }
2008
+ const picked = ResolveEffectiveRealtimeConfig(null, null, input.ConfigOverridesJson).realtime?.voice?.default?.voice;
2009
+ return picked ? bag : { ...(bag ?? {}), voice: avatar.Voice };
2010
+ }
1405
2011
  /**
1406
2012
  * Builds the provider-pact `Config` bag for the session: the effective config's resolved voice
1407
2013
  * settings (per {@link GetProviderVoiceSettings} — the persona's agnostic wire-level slots
@@ -1599,7 +2205,9 @@ export class RealtimeClientSessionService {
1599
2205
  `Knowledge Hub" → ContextTool with action 'NavigateToApp'; "open this record"; "switch to the X tab"). ` +
1600
2206
  `Do NOT route in-app navigation/actions through '${INVOKE_TARGET_AGENT_TOOL_NAME}', and NEVER say you ` +
1601
2207
  `need an active session id or a screen snapshot to do them — calling 'ContextTool' is all that's ` +
1602
- `needed. Reserve '${INVOKE_TARGET_AGENT_TOOL_NAME}' for actual analysis / data work, not navigation.`;
2208
+ `needed. Reserve '${INVOKE_TARGET_AGENT_TOOL_NAME}' for actual analysis / data work, not navigation. ` +
2209
+ `When a channel note lists interactive channels you can use, 'ContextTool' also addresses ONE of ` +
2210
+ `them: add "target": { "channel": "<channel name>" } and use that channel's action names.`;
1603
2211
  }
1604
2212
  return clause;
1605
2213
  }
@@ -2006,11 +2614,13 @@ export class RealtimeClientSessionService {
2006
2614
  /**
2007
2615
  * Runs (or resumes) the target agent for a delegation. Threads the combined abort signal, parent
2008
2616
  * run linkage, session id, and the `OnProgress` callback so the resolver can stream progress.
2617
+ * The browser session id becomes the run's `sessionID` (client-tool channel) and the app-context
2618
+ * snapshot rides `data.appContext` (prompt context and surface tools); both are optional.
2009
2619
  * When {@link ExecuteRelayedToolInput.ResumeRunID} is set, resumes that paused run via
2010
2620
  * `lastRunId` + `autoPopulateLastRunPayload` (the user's answer continues the same interactive
2011
2621
  * run) instead of starting fresh.
2012
2622
  *
2013
- * @param input The relayed tool input (linkage, progress callback, optional resume id).
2623
+ * @param input The relayed tool input (linkage, progress callback, optional resume id, browser session, app context).
2014
2624
  * @param request The broker's delegation request (call id + arguments + abort signal).
2015
2625
  * @param target The resolved target agent.
2016
2626
  * @param contextUser The calling user.
@@ -2021,22 +2631,30 @@ export class RealtimeClientSessionService {
2021
2631
  const requestText = this.parseDelegateRequestText(request.Arguments);
2022
2632
  const parentRun = await this.loadParentRun(input.ParentRunID, contextUser, provider);
2023
2633
  const runner = new AgentRunner(provider);
2024
- return runner.RunAgent({
2025
- agent: target,
2026
- conversationMessages: [{ role: 'user', content: requestText }],
2027
- contextUser,
2028
- // Attribution and context-memory scope follow the PERSON, not the executing principal —
2029
- // see `ExecuteRelayedToolInput.AttributionUserID`. Undefined ⇒ base-agent falls back to
2030
- // `contextUser.ID`, preserving today's behavior for every non-elevated caller.
2031
- userId: input.AttributionUserID,
2032
- provider,
2033
- cancellationToken: this.combineSignals(request.AbortSignal, input.AbortSignal),
2034
- parentRun: parentRun ?? undefined,
2035
- agentSessionID: input.AgentSessionID,
2036
- onProgress: input.OnProgress,
2037
- lastRunId: input.ResumeRunID,
2038
- autoPopulateLastRunPayload: input.ResumeRunID ? true : undefined
2039
- });
2634
+ const combined = this.combineSignals(request.AbortSignal, input.AbortSignal);
2635
+ try {
2636
+ return await runner.RunAgent({
2637
+ agent: target,
2638
+ conversationMessages: [{ role: 'user', content: requestText }],
2639
+ contextUser,
2640
+ // Attribution and context-memory scope follow the PERSON, not the executing principal —
2641
+ // see `ExecuteRelayedToolInput.AttributionUserID`. Undefined ⇒ base-agent falls back to
2642
+ // `contextUser.ID`, preserving today's behavior for every non-elevated caller.
2643
+ userId: input.AttributionUserID,
2644
+ provider,
2645
+ cancellationToken: combined.Signal,
2646
+ parentRun: parentRun ?? undefined,
2647
+ agentSessionID: input.AgentSessionID,
2648
+ sessionID: input.BrowserSessionID,
2649
+ data: input.AppContext ? { appContext: input.AppContext } : undefined,
2650
+ onProgress: input.OnProgress,
2651
+ lastRunId: input.ResumeRunID,
2652
+ autoPopulateLastRunPayload: input.ResumeRunID ? true : undefined
2653
+ });
2654
+ }
2655
+ finally {
2656
+ combined.Dispose();
2657
+ }
2040
2658
  }
2041
2659
  /**
2042
2660
  * Maps an {@link ExecuteAgentResult} onto the broker's {@link DelegatedResult}, special-casing a
@@ -2118,11 +2736,25 @@ export class RealtimeClientSessionService {
2118
2736
  const agentActions = (AIEngine.Instance.AgentActions ?? []).filter(aa => UUIDsEqual(aa.AgentID, targetAgentID) && aa.Status === 'Active');
2119
2737
  return (ActionEngineServer.Instance.Actions ?? []).filter(a => agentActions.some(aa => UUIDsEqual(aa.ActionID, a.ID)) && a.Status === 'Active');
2120
2738
  }
2739
+ /**
2740
+ * The session's direct-action tools. When the input excludes direct actions, none, and the empty
2741
+ * projection is recorded so the session's relays run none.
2742
+ */
2743
+ projectDirectActions(input, effectiveConfig, driverClass) {
2744
+ if (input.ExcludeDirectActions) {
2745
+ this.recordEmptyProjection(input.AgentSessionID);
2746
+ return [];
2747
+ }
2748
+ return this.BuildDirectActionTools(input.TargetAgentID, effectiveConfig, driverClass, input.AgentSessionID);
2749
+ }
2121
2750
  /**
2122
2751
  * Builds the projected direct action tool definitions for a target agent if supported by the driver.
2123
2752
  * Gated by driver capability (`SupportsDynamicToolSet`) and explicit configuration opt-in
2124
2753
  * (`Configuration.realtime.directActions.enabled = true`).
2125
2754
  *
2755
+ * With `agentSessionID`, the projection is recorded for the session, even when it is empty: relayed
2756
+ * direct-action calls for the session may run only the projected actions.
2757
+ *
2126
2758
  * @param targetAgentID The target agent ID being voiced.
2127
2759
  * @param effectiveConfig The resolved effective configuration.
2128
2760
  * @param driverClass The resolved vendor's DriverClass.
@@ -2130,10 +2762,12 @@ export class RealtimeClientSessionService {
2130
2762
  */
2131
2763
  BuildDirectActionTools(targetAgentID, effectiveConfig, driverClass, agentSessionID) {
2132
2764
  if (!targetAgentID || !this.driverSupportsDynamicToolSet(driverClass)) {
2765
+ this.recordEmptyProjection(agentSessionID);
2133
2766
  return [];
2134
2767
  }
2135
2768
  const directConfig = GetDirectActionsConfig(effectiveConfig);
2136
2769
  if (!directConfig || !directConfig.enabled) {
2770
+ this.recordEmptyProjection(agentSessionID);
2137
2771
  return [];
2138
2772
  }
2139
2773
  const candidateActions = this.getTargetAgentActions(targetAgentID);
@@ -2152,6 +2786,12 @@ export class RealtimeClientSessionService {
2152
2786
  }
2153
2787
  return tools;
2154
2788
  }
2789
+ /** Records that a session projected no direct actions, so its relays run none. */
2790
+ recordEmptyProjection(agentSessionID) {
2791
+ if (agentSessionID) {
2792
+ this.sessionWireActionMaps.Set(agentSessionID, new Map());
2793
+ }
2794
+ }
2155
2795
  /** @deprecated Use {@link BuildDirectActionTools}. */
2156
2796
  buildDirectActionTools(targetAgentID, effectiveConfig, driverClass, agentSessionID) {
2157
2797
  return this.BuildDirectActionTools(targetAgentID, effectiveConfig, driverClass, agentSessionID);
@@ -2207,6 +2847,13 @@ export class RealtimeClientSessionService {
2207
2847
  * configured timeout. If the tool is unrecognized, disallowed, or target resolution fails,
2208
2848
  * returns a structured "not available" result.
2209
2849
  *
2850
+ * When this service holds the session's start-time projection, only the projected actions may
2851
+ * run, whatever target the input names. When it holds none, the target agent's own metadata
2852
+ * decides: another process prepared the session, the entry was evicted or lost on a restart, or
2853
+ * the session was never started through this service (for example a row created through the
2854
+ * entity API). That fallback skips the driver-capability gate but is still limited to the
2855
+ * target's own direct-actions allowlist.
2856
+ *
2210
2857
  * @param call The non-target tool call.
2211
2858
  * @param input The optional relayed tool input context.
2212
2859
  * @param contextUser The calling user context.
@@ -2228,11 +2875,9 @@ export class RealtimeClientSessionService {
2228
2875
  Output: `Target agent is not available to execute '${call.ToolName}'.`
2229
2876
  };
2230
2877
  }
2231
- const candidateActions = this.getTargetAgentActions(target.ID);
2232
- const candidateWireMap = this.BuildWireActionMap(candidateActions);
2233
- const action = (input?.AgentSessionID ? this.sessionWireActionMaps.Get(input.AgentSessionID)?.get(call.ToolName) : undefined)
2234
- ?? candidateWireMap.get(call.ToolName)
2235
- ?? Array.from(candidateWireMap.entries()).find(([w]) => w.toLowerCase() === call.ToolName.trim().toLowerCase())?.[1];
2878
+ const projection = input?.AgentSessionID ? this.sessionWireActionMaps.Get(input.AgentSessionID) : undefined;
2879
+ const candidateWireMap = this.BuildWireActionMap(this.getTargetAgentActions(target.ID));
2880
+ const action = this.findWireAction(projection, call.ToolName) ?? this.findWireAction(candidateWireMap, call.ToolName);
2236
2881
  if (!action) {
2237
2882
  return {
2238
2883
  CallID: call.CallID,
@@ -2243,7 +2888,7 @@ export class RealtimeClientSessionService {
2243
2888
  const directConfig = input?.DirectActions
2244
2889
  ?? (input?.AgentSessionID ? this.sessionDirectConfigs.Get(input.AgentSessionID) : undefined)
2245
2890
  ?? GetDirectActionsConfig(this.resolveEffectiveConfig(target, undefined, target));
2246
- if (!IsActionAllowedForDirectInvocation(action.Name, directConfig)) {
2891
+ if (!this.isInProjection(projection, action) || !IsActionAllowedForDirectInvocation(action.Name, directConfig)) {
2247
2892
  return {
2248
2893
  CallID: call.CallID,
2249
2894
  Success: false,
@@ -2304,6 +2949,24 @@ export class RealtimeClientSessionService {
2304
2949
  };
2305
2950
  }
2306
2951
  }
2952
+ /**
2953
+ * Finds the action a relayed tool name refers to: the exact wire name first, then a
2954
+ * case-insensitive match.
2955
+ */
2956
+ findWireAction(wireMap, toolName) {
2957
+ if (!wireMap) {
2958
+ return undefined;
2959
+ }
2960
+ const wanted = toolName.trim().toLowerCase();
2961
+ return wireMap.get(toolName) ?? Array.from(wireMap.entries()).find(([wireName]) => wireName.toLowerCase() === wanted)?.[1];
2962
+ }
2963
+ /**
2964
+ * True when the action is in the session's start-time projection, or when this service holds no
2965
+ * projection for the session (see {@link executeNonTargetTool} for when that happens).
2966
+ */
2967
+ isInProjection(projection, action) {
2968
+ return !projection || Array.from(projection.values()).some(projected => UUIDsEqual(projected.ID, action.ID));
2969
+ }
2307
2970
  /**
2308
2971
  * Parses JSON arguments string into a key-value record of parameters.
2309
2972
  * Distinguishes "no arguments" (valid for zero-param action) from "unparseable JSON".
@@ -2350,27 +3013,31 @@ export class RealtimeClientSessionService {
2350
3013
  }
2351
3014
  /**
2352
3015
  * Combines the broker's per-call abort signal with an optional caller-supplied signal so either
2353
- * source can cancel the delegated run. Returns the broker signal alone when no caller signal is
2354
- * present (the common case), avoiding an unnecessary controller.
3016
+ * source can cancel the delegated run, paired with a `Dispose` callback that removes the
3017
+ * forwarding listeners when the call finishes so a long-lived caller signal does not retain one
3018
+ * closure per relayed tool call. Short-circuits when no distinct caller signal is present.
2355
3019
  *
2356
3020
  * @param brokerSignal The broker-owned per-call abort signal (always present).
2357
- * @param callerSignal An optional caller signal (e.g. a request-scoped barge-in).
2358
- * @returns A single abort signal that fires when either source aborts.
3021
+ * @param callerSignal An optional caller signal (e.g. a request-scoped or session-scoped barge-in).
3022
+ * @returns The combined abort signal and a disposer that removes its forwarding listeners.
2359
3023
  */
2360
3024
  combineSignals(brokerSignal, callerSignal) {
2361
- if (!callerSignal) {
2362
- return brokerSignal;
3025
+ if (!callerSignal || callerSignal === brokerSignal) {
3026
+ return { Signal: brokerSignal, Dispose: () => undefined };
2363
3027
  }
2364
3028
  const controller = new AbortController();
2365
3029
  const abort = () => controller.abort();
2366
3030
  if (brokerSignal.aborted || callerSignal.aborted) {
2367
3031
  controller.abort();
3032
+ return { Signal: controller.signal, Dispose: () => undefined };
2368
3033
  }
2369
- else {
2370
- brokerSignal.addEventListener('abort', abort, { once: true });
2371
- callerSignal.addEventListener('abort', abort, { once: true });
2372
- }
2373
- return controller.signal;
3034
+ brokerSignal.addEventListener('abort', abort, { once: true });
3035
+ callerSignal.addEventListener('abort', abort, { once: true });
3036
+ const dispose = () => {
3037
+ brokerSignal.removeEventListener('abort', abort);
3038
+ callerSignal.removeEventListener('abort', abort);
3039
+ };
3040
+ return { Signal: controller.signal, Dispose: dispose };
2374
3041
  }
2375
3042
  /**
2376
3043
  * The clear, actionable message returned when no usable Realtime model can be resolved.