@memberjunction/ai-agents 6.2.2 → 6.3.0-edge.1

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 (250) hide show
  1. package/README.md +29 -6
  2. package/dist/AgentContextAssembler.d.ts +127 -0
  3. package/dist/AgentContextAssembler.d.ts.map +1 -0
  4. package/dist/AgentContextAssembler.js +482 -0
  5. package/dist/AgentContextAssembler.js.map +1 -0
  6. package/dist/AgentDataPreloader.d.ts +14 -3
  7. package/dist/AgentDataPreloader.d.ts.map +1 -1
  8. package/dist/AgentDataPreloader.js +147 -22
  9. package/dist/AgentDataPreloader.js.map +1 -1
  10. package/dist/AgentDecisionService.d.ts +10 -1
  11. package/dist/AgentDecisionService.d.ts.map +1 -1
  12. package/dist/AgentDecisionService.js +28 -13
  13. package/dist/AgentDecisionService.js.map +1 -1
  14. package/dist/AgentFeedbackCoordinator.d.ts +169 -0
  15. package/dist/AgentFeedbackCoordinator.d.ts.map +1 -0
  16. package/dist/AgentFeedbackCoordinator.js +593 -0
  17. package/dist/AgentFeedbackCoordinator.js.map +1 -0
  18. package/dist/AgentRunner.d.ts +57 -15
  19. package/dist/AgentRunner.d.ts.map +1 -1
  20. package/dist/AgentRunner.js +692 -101
  21. package/dist/AgentRunner.js.map +1 -1
  22. package/dist/AgentStepDispatcher.d.ts +211 -0
  23. package/dist/AgentStepDispatcher.d.ts.map +1 -0
  24. package/dist/AgentStepDispatcher.js +729 -0
  25. package/dist/AgentStepDispatcher.js.map +1 -0
  26. package/dist/AgentTreeBudgetTracker.d.ts +163 -0
  27. package/dist/AgentTreeBudgetTracker.d.ts.map +1 -0
  28. package/dist/AgentTreeBudgetTracker.js +415 -0
  29. package/dist/AgentTreeBudgetTracker.js.map +1 -0
  30. package/dist/AgentWakeTriggerService.d.ts +41 -1
  31. package/dist/AgentWakeTriggerService.d.ts.map +1 -1
  32. package/dist/AgentWakeTriggerService.js +154 -8
  33. package/dist/AgentWakeTriggerService.js.map +1 -1
  34. package/dist/ArtifactToolManager.d.ts +134 -39
  35. package/dist/ArtifactToolManager.d.ts.map +1 -1
  36. package/dist/ArtifactToolManager.js +2761 -321
  37. package/dist/ArtifactToolManager.js.map +1 -1
  38. package/dist/GovernedArtifactService.d.ts +367 -0
  39. package/dist/GovernedArtifactService.d.ts.map +1 -0
  40. package/dist/GovernedArtifactService.js +2569 -0
  41. package/dist/GovernedArtifactService.js.map +1 -0
  42. package/dist/MJAIAgentRequestEntityServer.d.ts +32 -1
  43. package/dist/MJAIAgentRequestEntityServer.d.ts.map +1 -1
  44. package/dist/MJAIAgentRequestEntityServer.js +105 -3
  45. package/dist/MJAIAgentRequestEntityServer.js.map +1 -1
  46. package/dist/SkillMarkdownConverter.d.ts +1 -1
  47. package/dist/SkillMarkdownConverter.d.ts.map +1 -1
  48. package/dist/SkillMarkdownConverter.js +8 -6
  49. package/dist/SkillMarkdownConverter.js.map +1 -1
  50. package/dist/agent-context-injector.d.ts +2 -25
  51. package/dist/agent-context-injector.d.ts.map +1 -1
  52. package/dist/agent-context-injector.js +38 -153
  53. package/dist/agent-context-injector.js.map +1 -1
  54. package/dist/agent-instance.d.ts +28 -0
  55. package/dist/agent-instance.d.ts.map +1 -0
  56. package/dist/agent-instance.js +39 -0
  57. package/dist/agent-instance.js.map +1 -0
  58. package/dist/agent-memory-context-builder.d.ts.map +1 -1
  59. package/dist/agent-memory-context-builder.js +46 -42
  60. package/dist/agent-memory-context-builder.js.map +1 -1
  61. package/dist/agent-pre-execution-rag.d.ts +5 -0
  62. package/dist/agent-pre-execution-rag.d.ts.map +1 -1
  63. package/dist/agent-pre-execution-rag.js +10 -0
  64. package/dist/agent-pre-execution-rag.js.map +1 -1
  65. package/dist/agent-run-watchdog.d.ts +38 -6
  66. package/dist/agent-run-watchdog.d.ts.map +1 -1
  67. package/dist/agent-run-watchdog.js +75 -13
  68. package/dist/agent-run-watchdog.js.map +1 -1
  69. package/dist/agent-types/flow-agent-type.d.ts +6 -1
  70. package/dist/agent-types/flow-agent-type.d.ts.map +1 -1
  71. package/dist/agent-types/flow-agent-type.js +30 -7
  72. package/dist/agent-types/flow-agent-type.js.map +1 -1
  73. package/dist/agent-types/loop-agent-prompt-params.d.ts +18 -0
  74. package/dist/agent-types/loop-agent-prompt-params.d.ts.map +1 -1
  75. package/dist/agent-types/loop-agent-prompt-params.js +2 -0
  76. package/dist/agent-types/loop-agent-prompt-params.js.map +1 -1
  77. package/dist/agent-types/loop-agent-type.d.ts +4 -0
  78. package/dist/agent-types/loop-agent-type.d.ts.map +1 -1
  79. package/dist/agent-types/loop-agent-type.js +29 -0
  80. package/dist/agent-types/loop-agent-type.js.map +1 -1
  81. package/dist/artifact-presence-locator.d.ts +132 -0
  82. package/dist/artifact-presence-locator.d.ts.map +1 -0
  83. package/dist/artifact-presence-locator.js +472 -0
  84. package/dist/artifact-presence-locator.js.map +1 -0
  85. package/dist/artifact-tools/CSVToolLibrary.d.ts +2 -2
  86. package/dist/artifact-tools/CSVToolLibrary.d.ts.map +1 -1
  87. package/dist/artifact-tools/CSVToolLibrary.js +41 -14
  88. package/dist/artifact-tools/CSVToolLibrary.js.map +1 -1
  89. package/dist/artifact-tools/DataSnapshotToolLibrary.d.ts +2 -2
  90. package/dist/artifact-tools/DataSnapshotToolLibrary.d.ts.map +1 -1
  91. package/dist/artifact-tools/DataSnapshotToolLibrary.js +53 -21
  92. package/dist/artifact-tools/DataSnapshotToolLibrary.js.map +1 -1
  93. package/dist/artifact-tools/DocumentToolLibrary.d.ts +101 -0
  94. package/dist/artifact-tools/DocumentToolLibrary.d.ts.map +1 -0
  95. package/dist/artifact-tools/DocumentToolLibrary.js +1846 -0
  96. package/dist/artifact-tools/DocumentToolLibrary.js.map +1 -0
  97. package/dist/artifact-tools/DocxToolLibrary.d.ts +2 -4
  98. package/dist/artifact-tools/DocxToolLibrary.d.ts.map +1 -1
  99. package/dist/artifact-tools/DocxToolLibrary.js +42 -30
  100. package/dist/artifact-tools/DocxToolLibrary.js.map +1 -1
  101. package/dist/artifact-tools/ExcelToolLibrary.d.ts +2 -3
  102. package/dist/artifact-tools/ExcelToolLibrary.d.ts.map +1 -1
  103. package/dist/artifact-tools/ExcelToolLibrary.js +105 -49
  104. package/dist/artifact-tools/ExcelToolLibrary.js.map +1 -1
  105. package/dist/artifact-tools/GenericBinaryToolLibrary.d.ts +2 -2
  106. package/dist/artifact-tools/GenericBinaryToolLibrary.d.ts.map +1 -1
  107. package/dist/artifact-tools/GenericBinaryToolLibrary.js +3 -2
  108. package/dist/artifact-tools/GenericBinaryToolLibrary.js.map +1 -1
  109. package/dist/artifact-tools/JSONToolLibrary.d.ts +4 -4
  110. package/dist/artifact-tools/JSONToolLibrary.d.ts.map +1 -1
  111. package/dist/artifact-tools/JSONToolLibrary.js +32 -11
  112. package/dist/artifact-tools/JSONToolLibrary.js.map +1 -1
  113. package/dist/artifact-tools/PDFToolLibrary.d.ts +27 -3
  114. package/dist/artifact-tools/PDFToolLibrary.d.ts.map +1 -1
  115. package/dist/artifact-tools/PDFToolLibrary.js +36 -21
  116. package/dist/artifact-tools/PDFToolLibrary.js.map +1 -1
  117. package/dist/artifact-tools/SearchResultSetToolLibrary.d.ts +2 -2
  118. package/dist/artifact-tools/SearchResultSetToolLibrary.d.ts.map +1 -1
  119. package/dist/artifact-tools/SearchResultSetToolLibrary.js +83 -24
  120. package/dist/artifact-tools/SearchResultSetToolLibrary.js.map +1 -1
  121. package/dist/artifact-tools/SlideDeckToolLibrary.d.ts +50 -0
  122. package/dist/artifact-tools/SlideDeckToolLibrary.d.ts.map +1 -0
  123. package/dist/artifact-tools/SlideDeckToolLibrary.js +1617 -0
  124. package/dist/artifact-tools/SlideDeckToolLibrary.js.map +1 -0
  125. package/dist/artifact-tools/SpreadsheetToolLibrary.d.ts +87 -0
  126. package/dist/artifact-tools/SpreadsheetToolLibrary.d.ts.map +1 -0
  127. package/dist/artifact-tools/SpreadsheetToolLibrary.js +3351 -0
  128. package/dist/artifact-tools/SpreadsheetToolLibrary.js.map +1 -0
  129. package/dist/artifact-tools/TextToolLibrary.d.ts +3 -3
  130. package/dist/artifact-tools/TextToolLibrary.d.ts.map +1 -1
  131. package/dist/artifact-tools/TextToolLibrary.js +34 -24
  132. package/dist/artifact-tools/TextToolLibrary.js.map +1 -1
  133. package/dist/artifact-tools/WhiteboardToolLibrary.d.ts +69 -0
  134. package/dist/artifact-tools/WhiteboardToolLibrary.d.ts.map +1 -0
  135. package/dist/artifact-tools/WhiteboardToolLibrary.js +555 -0
  136. package/dist/artifact-tools/WhiteboardToolLibrary.js.map +1 -0
  137. package/dist/artifact-tools/artifact-comment-suggestion-helper.d.ts +98 -0
  138. package/dist/artifact-tools/artifact-comment-suggestion-helper.d.ts.map +1 -0
  139. package/dist/artifact-tools/artifact-comment-suggestion-helper.js +851 -0
  140. package/dist/artifact-tools/artifact-comment-suggestion-helper.js.map +1 -0
  141. package/dist/artifact-tools/artifact-tool-helpers.d.ts +21 -0
  142. package/dist/artifact-tools/artifact-tool-helpers.d.ts.map +1 -0
  143. package/dist/artifact-tools/artifact-tool-helpers.js +74 -0
  144. package/dist/artifact-tools/artifact-tool-helpers.js.map +1 -0
  145. package/dist/artifact-tools/grepHelper.d.ts +27 -0
  146. package/dist/artifact-tools/grepHelper.d.ts.map +1 -0
  147. package/dist/artifact-tools/grepHelper.js +229 -0
  148. package/dist/artifact-tools/grepHelper.js.map +1 -0
  149. package/dist/artifact-tools/node-vm-safe-regex.d.ts +10 -0
  150. package/dist/artifact-tools/node-vm-safe-regex.d.ts.map +1 -0
  151. package/dist/artifact-tools/node-vm-safe-regex.js +148 -0
  152. package/dist/artifact-tools/node-vm-safe-regex.js.map +1 -0
  153. package/dist/base-agent.d.ts +151 -137
  154. package/dist/base-agent.d.ts.map +1 -1
  155. package/dist/base-agent.js +727 -1550
  156. package/dist/base-agent.js.map +1 -1
  157. package/dist/catalog-narrowing.d.ts +112 -5
  158. package/dist/catalog-narrowing.d.ts.map +1 -1
  159. package/dist/catalog-narrowing.js +181 -6
  160. package/dist/catalog-narrowing.js.map +1 -1
  161. package/dist/decision-discovery.d.ts +42 -15
  162. package/dist/decision-discovery.d.ts.map +1 -1
  163. package/dist/decision-discovery.js +90 -20
  164. package/dist/decision-discovery.js.map +1 -1
  165. package/dist/index.d.ts +17 -2
  166. package/dist/index.d.ts.map +1 -1
  167. package/dist/index.js +17 -3
  168. package/dist/index.js.map +1 -1
  169. package/dist/memory-decision-uses.d.ts +206 -0
  170. package/dist/memory-decision-uses.d.ts.map +1 -0
  171. package/dist/memory-decision-uses.js +259 -0
  172. package/dist/memory-decision-uses.js.map +1 -0
  173. package/dist/memory-manager-agent.d.ts +66 -6
  174. package/dist/memory-manager-agent.d.ts.map +1 -1
  175. package/dist/memory-manager-agent.js +184 -31
  176. package/dist/memory-manager-agent.js.map +1 -1
  177. package/dist/memory-note-gate.d.ts +12 -9
  178. package/dist/memory-note-gate.d.ts.map +1 -1
  179. package/dist/memory-note-gate.js +16 -11
  180. package/dist/memory-note-gate.js.map +1 -1
  181. package/dist/native-tools/control-tools.d.ts +8 -1
  182. package/dist/native-tools/control-tools.d.ts.map +1 -1
  183. package/dist/native-tools/control-tools.js +38 -5
  184. package/dist/native-tools/control-tools.js.map +1 -1
  185. package/dist/native-tools/framework-tools.d.ts +3 -3
  186. package/dist/native-tools/framework-tools.d.ts.map +1 -1
  187. package/dist/native-tools/framework-tools.js +20 -8
  188. package/dist/native-tools/framework-tools.js.map +1 -1
  189. package/dist/pipeline/operators.d.ts.map +1 -1
  190. package/dist/pipeline/operators.js +1 -1
  191. package/dist/pipeline/operators.js.map +1 -1
  192. package/dist/pipeline/pipeline-executor.d.ts +29 -1
  193. package/dist/pipeline/pipeline-executor.d.ts.map +1 -1
  194. package/dist/pipeline/pipeline-executor.js +159 -2
  195. package/dist/pipeline/pipeline-executor.js.map +1 -1
  196. package/dist/pipeline/pipeline.types.d.ts +19 -1
  197. package/dist/pipeline/pipeline.types.d.ts.map +1 -1
  198. package/dist/pipeline/template.d.ts +16 -0
  199. package/dist/pipeline/template.d.ts.map +1 -1
  200. package/dist/pipeline/template.js +55 -6
  201. package/dist/pipeline/template.js.map +1 -1
  202. package/dist/realtime/artifact-workspace-channel-server.d.ts +27 -0
  203. package/dist/realtime/artifact-workspace-channel-server.d.ts.map +1 -0
  204. package/dist/realtime/artifact-workspace-channel-server.js +43 -0
  205. package/dist/realtime/artifact-workspace-channel-server.js.map +1 -0
  206. package/dist/realtime/bridge-realtime-session-factory.d.ts +2 -2
  207. package/dist/realtime/bridge-realtime-session-factory.d.ts.map +1 -1
  208. package/dist/realtime/bridge-realtime-session-factory.js +7 -56
  209. package/dist/realtime/bridge-realtime-session-factory.js.map +1 -1
  210. package/dist/realtime/bridge-room-transcript-sink.d.ts.map +1 -1
  211. package/dist/realtime/bridge-room-transcript-sink.js +28 -1
  212. package/dist/realtime/bridge-room-transcript-sink.js.map +1 -1
  213. package/dist/realtime/media-channel-server.js +1 -1
  214. package/dist/realtime/media-channel-server.js.map +1 -1
  215. package/dist/realtime/realtime-artifact-helpers.d.ts +37 -0
  216. package/dist/realtime/realtime-artifact-helpers.d.ts.map +1 -0
  217. package/dist/realtime/realtime-artifact-helpers.js +150 -0
  218. package/dist/realtime/realtime-artifact-helpers.js.map +1 -0
  219. package/dist/realtime/realtime-client-session-service.d.ts +209 -19
  220. package/dist/realtime/realtime-client-session-service.d.ts.map +1 -1
  221. package/dist/realtime/realtime-client-session-service.js +670 -41
  222. package/dist/realtime/realtime-client-session-service.js.map +1 -1
  223. package/dist/realtime/realtime-coagent-config.d.ts +26 -9
  224. package/dist/realtime/realtime-coagent-config.d.ts.map +1 -1
  225. package/dist/realtime/realtime-coagent-config.js +47 -60
  226. package/dist/realtime/realtime-coagent-config.js.map +1 -1
  227. package/dist/realtime/realtime-delegation-narrator.js +1 -1
  228. package/dist/realtime/realtime-delegation-narrator.js.map +1 -1
  229. package/dist/realtime/realtime-moderator-decision.d.ts +86 -0
  230. package/dist/realtime/realtime-moderator-decision.d.ts.map +1 -0
  231. package/dist/realtime/realtime-moderator-decision.js +131 -0
  232. package/dist/realtime/realtime-moderator-decision.js.map +1 -0
  233. package/dist/realtime/realtime-session-runner.d.ts +2 -0
  234. package/dist/realtime/realtime-session-runner.d.ts.map +1 -1
  235. package/dist/realtime/realtime-session-runner.js +24 -3
  236. package/dist/realtime/realtime-session-runner.js.map +1 -1
  237. package/dist/realtime/realtime-tool-broker.d.ts +6 -0
  238. package/dist/realtime/realtime-tool-broker.d.ts.map +1 -1
  239. package/dist/realtime/realtime-tool-broker.js +4 -2
  240. package/dist/realtime/realtime-tool-broker.js.map +1 -1
  241. package/dist/realtime/realtime-turn-moderator.d.ts +20 -0
  242. package/dist/realtime/realtime-turn-moderator.d.ts.map +1 -1
  243. package/dist/realtime/realtime-turn-moderator.js +63 -8
  244. package/dist/realtime/realtime-turn-moderator.js.map +1 -1
  245. package/dist/repeated-failing-step.d.ts +50 -0
  246. package/dist/repeated-failing-step.d.ts.map +1 -0
  247. package/dist/repeated-failing-step.js +130 -0
  248. package/dist/repeated-failing-step.js.map +1 -0
  249. package/dist/tsconfig.tsbuildinfo +1 -0
  250. package/package.json +20 -20
@@ -30,20 +30,22 @@
30
30
  * @author MemberJunction.com
31
31
  */
32
32
  import { LogError, LogStatus, RunView, DatabaseProviderBase } from '@memberjunction/core';
33
- import { MJGlobal, MJLruCache, UUIDsEqual, EscapeSQLString, NormalizeUUID } from '@memberjunction/global';
33
+ import { BaseSingleton, 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, IsZeroDataRetention } from '@memberjunction/ai';
37
- import { FormatAppContextNote, ResolvePromptRunUserID, ClientToolMetadataFromDefinition, ParseAgentSettings, ResolveAppClientToolMetadata, ResolveClientTools } from '@memberjunction/ai-core-plus';
36
+ import { BaseRealtimeModel, BuildRealtimeRelayUrl, GetAIAPIKey, CredentialScopeAllows, IsZeroDataRetention, REALTIME_RELAY_MAX_CONNECTIONS, REALTIME_RELAY_PATH, REALTIME_RELAY_SESSION_LIFETIME_SECONDS, RealtimeProxyRegistry, ResolveRealtimeProxyBaseWsUrl, ResolveRealtimeTiming } from '@memberjunction/ai';
37
+ import { AgentUserPolicyEngine, FormatAppContextNote, ResolvePromptRunUserID, ClientToolMetadataFromDefinition, ParseAgentSettings, ResolveAppClientToolMetadata, ResolveClientTools } from '@memberjunction/ai-core-plus';
38
38
  import { AIEngine } from '@memberjunction/aiengine';
39
39
  import { RealtimeSessionCanShowAvatar, ResolveBridgedAvatarStatus, ResolveRealtimeAvatar, ResolveRealtimeAvatarStatus, WithoutUnseenAvatar, } from './realtime-avatar-resolution.js';
40
40
  import { ChooseRealtimeVendorForAvatar, ReadRealtimeVideoOutputRow, RealtimeModelShowsAvatar } from './realtime-video-output-gate.js';
41
41
  import { AgentMemoryContextBuilder } from '../agent-memory-context-builder.js';
42
42
  import { AgentRunner } from '../AgentRunner.js';
43
+ import { GovernedArtifactService } from '../GovernedArtifactService.js';
43
44
  import { AgentRunWatchdog } from '../agent-run-watchdog.js';
44
45
  import { DelegationNarrator } from './realtime-delegation-narrator.js';
45
46
  import { FilterAllowedAgentsByCanRun } from './realtime-coagent-resolution.js';
46
47
  import { BridgeRealtimeUsageRecorder } from './bridge-realtime-usage-recorder.js';
48
+ import { CollectDelegatedRunArtifacts, ExtractDirectActionArtifacts, } from './realtime-artifact-helpers.js';
47
49
  import { RealtimeToolBroker, INVOKE_TARGET_AGENT_TOOL_NAME, INVOKE_TARGET_AGENT_DESCRIPTION, BuildRealtimeAgentFraming } from './realtime-tool-broker.js';
48
50
  import { NARRATION_PROMPT_NAME, LEGACY_NARRATION_PROMPT_NAME, ResolveNarrationInstructionsTemplate } from './realtime-narration.js';
49
51
  import { BuildVoiceMannerSection, BuildAppRealtimeOverridesJson, DeepMergeConfigs, FindDeprecatedRealtimeVideoKeys, GetModelCatalogSessionSettings, GetDisclosureForTarget, GetNarrationPaceMs, GetProviderVoiceSettings, GetSessionTuningSettings, GetWatchesMeetingVideo, ResolveEffectiveRealtimeConfig, MatchProviderVoiceSettings, GetDirectActionsConfig, IsActionAllowedForDirectInvocation } from './realtime-coagent-config.js';
@@ -74,6 +76,99 @@ const deprecatedVideoKeysLogged = new Set();
74
76
  * price prices them. Raise it for a model that counts more.
75
77
  */
76
78
  const VIDEO_TOKENS_PER_SECOND = 6192;
79
+ const MINT_SNAPSHOT_MAX_ENTRIES = 2000;
80
+ const MINT_SNAPSHOT_TTL_MS = 4 * 60 * 60 * 1000;
81
+ /**
82
+ * Process-wide singleton registry of mint snapshots for active client-direct realtime sessions,
83
+ * backed by `BaseSingleton` (`GetGlobalObjectStore()`) with bounded LRU/TTL eviction.
84
+ */
85
+ export class RealtimeMintSnapshotRegistry extends BaseSingleton {
86
+ constructor() {
87
+ super();
88
+ this._snapshots = new MJLruCache({
89
+ maxSize: MINT_SNAPSHOT_MAX_ENTRIES,
90
+ ttlMs: MINT_SNAPSHOT_TTL_MS,
91
+ });
92
+ }
93
+ static get Instance() {
94
+ return super.getInstance();
95
+ }
96
+ Set(agentSessionID, snapshot) {
97
+ const key = NormalizeUUID(agentSessionID);
98
+ if (!key) {
99
+ return;
100
+ }
101
+ this._snapshots.Set(key, snapshot);
102
+ }
103
+ Get(agentSessionID) {
104
+ const key = NormalizeUUID(agentSessionID);
105
+ return key ? this._snapshots.Get(key) : undefined;
106
+ }
107
+ Delete(agentSessionID) {
108
+ const key = NormalizeUUID(agentSessionID);
109
+ if (key) {
110
+ this._snapshots.Delete(key);
111
+ }
112
+ }
113
+ Clear() {
114
+ this._snapshots.Clear();
115
+ }
116
+ }
117
+ /**
118
+ * The copy of a mint snapshot the transport layer persists on the owner-readable session row
119
+ * ({@link PersistedRealtimeMintSnapshot}):
120
+ * - A relay session keeps its session params on this instance only. Its browser is deliberately given no system
121
+ * prompt, tools or upstream configuration, so the owner must not read them from the row either. Its relay lives in
122
+ * this process: another instance could only open a new relay and re-seed the call, from exactly those params, so a
123
+ * refresh there fails and says why.
124
+ * - A direct session keeps its params: its browser was handed the prompt and tools in the provider config it applies,
125
+ * and another instance needs them to mint an equivalent credential. The minted provider config is kept only when the
126
+ * driver's refresh reads it (ElevenLabs reuses its managed agent); the base refresh ignores it.
127
+ */
128
+ function toPersistedMintSnapshot(snapshot, model) {
129
+ const routing = {
130
+ coAgentID: snapshot.coAgentID,
131
+ targetAgentID: snapshot.targetAgentID,
132
+ modelID: snapshot.modelID,
133
+ vendorID: snapshot.vendorID,
134
+ modelVendorID: snapshot.modelVendorID,
135
+ driverClass: snapshot.driverClass,
136
+ credentialScope: snapshot.credentialScope,
137
+ connectionMaxSeconds: snapshot.connectionMaxSeconds,
138
+ };
139
+ if (snapshot.transport === 'relay') {
140
+ return { ...routing, transport: 'relay' };
141
+ }
142
+ const refreshReadsSessionConfig = model.RefreshClientSessionCredential !== BaseRealtimeModel.prototype.RefreshClientSessionCredential;
143
+ return {
144
+ ...routing,
145
+ sessionParams: snapshot.sessionParams,
146
+ ...(refreshReadsSessionConfig && snapshot.existingSessionConfig ? { existingSessionConfig: snapshot.existingSessionConfig } : {}),
147
+ };
148
+ }
149
+ /** Whether a persisted mint snapshot is a relay session's, whose session params only its minting instance holds. */
150
+ function isRelayMintSnapshot(candidate) {
151
+ return typeof candidate === 'object' && candidate !== null && candidate.transport === 'relay';
152
+ }
153
+ function extractRelayTicketId(relayUrl) {
154
+ if (!relayUrl) {
155
+ return undefined;
156
+ }
157
+ const marker = `${REALTIME_RELAY_PATH}/`;
158
+ const idx = relayUrl.indexOf(marker);
159
+ if (idx < 0) {
160
+ return undefined;
161
+ }
162
+ const tail = relayUrl.slice(idx + marker.length);
163
+ const slash = tail.indexOf('/');
164
+ const raw = slash >= 0 ? tail.slice(0, slash) : tail;
165
+ try {
166
+ return decodeURIComponent(raw) || undefined;
167
+ }
168
+ catch {
169
+ return raw || undefined;
170
+ }
171
+ }
77
172
  /** Runtime handles by their realtime session, so the layer that only holds the session can reach its runtime. */
78
173
  const bridgeRuntimes = new WeakMap();
79
174
  /**
@@ -207,6 +302,16 @@ export class RealtimeClientSessionService {
207
302
  maxSize: 5_000,
208
303
  ttlMs: 4 * 60 * 60 * 1000,
209
304
  });
305
+ /** Maps session id -> live accumulated artifacts touched, created, or seeded during the voice session. */
306
+ this.sessionArtifacts = new MJLruCache({
307
+ maxSize: 5_000,
308
+ ttlMs: 4 * 60 * 60 * 1000,
309
+ });
310
+ /** Maps session id -> associated ConversationID recorded during session prep. */
311
+ this.sessionConversationIds = new MJLruCache({
312
+ maxSize: 5_000,
313
+ ttlMs: 4 * 60 * 60 * 1000,
314
+ });
210
315
  /**
211
316
  * IN-FLIGHT DELEGATION REGISTRY — the server half of the client-direct CANCEL channel.
212
317
  *
@@ -245,6 +350,59 @@ export class RealtimeClientSessionService {
245
350
  ttlMs: 4 * 60 * 60 * 1000, // 4h backstop — generous vs. any realistic session duration
246
351
  });
247
352
  }
353
+ /** Records/merges artifacts into the live session ledger, deduplicating by normalized ArtifactID. */
354
+ RecordSessionArtifacts(agentSessionID, items) {
355
+ const key = agentSessionID?.trim();
356
+ if (!key) {
357
+ return [];
358
+ }
359
+ const existing = this.sessionArtifacts.Get(key) ?? [];
360
+ const byNormId = new Map();
361
+ for (const item of existing) {
362
+ const norm = NormalizeUUID((item.ArtifactID ?? '').trim());
363
+ if (norm) {
364
+ byNormId.set(norm, item);
365
+ }
366
+ }
367
+ for (const item of items ?? []) {
368
+ const rawId = (item.ArtifactID ?? '').trim();
369
+ const norm = NormalizeUUID(rawId);
370
+ if (!norm) {
371
+ continue;
372
+ }
373
+ const prior = byNormId.get(norm);
374
+ const isSummary = 'LatestVersionID' in item || 'LatestVersionNumber' in item || 'Type' in item;
375
+ const summaryItem = isSummary ? item : undefined;
376
+ const delegatedItem = !isSummary ? item : undefined;
377
+ const hasNewerPriorVersion = prior?.LatestVersionNumber !== undefined &&
378
+ (summaryItem?.LatestVersionNumber === undefined
379
+ ? isSummary
380
+ : summaryItem.LatestVersionNumber < prior.LatestVersionNumber);
381
+ const merged = {
382
+ ArtifactID: rawId,
383
+ Name: item.Name?.trim() || prior?.Name || 'Untitled Artifact',
384
+ Type: summaryItem?.Type ?? delegatedItem?.ArtifactTypeName ?? prior?.Type,
385
+ LatestVersionID: hasNewerPriorVersion
386
+ ? prior?.LatestVersionID
387
+ : summaryItem?.LatestVersionID ?? (delegatedItem?.ArtifactVersionID || undefined) ?? prior?.LatestVersionID,
388
+ LatestVersionNumber: hasNewerPriorVersion
389
+ ? prior?.LatestVersionNumber
390
+ : summaryItem?.LatestVersionNumber ?? prior?.LatestVersionNumber,
391
+ };
392
+ byNormId.set(norm, merged);
393
+ }
394
+ const mergedList = Array.from(byNormId.values());
395
+ this.sessionArtifacts.Set(key, mergedList);
396
+ return mergedList;
397
+ }
398
+ /** Returns the live deduplicated artifact ledger for the given voice session. */
399
+ GetSessionArtifacts(agentSessionID) {
400
+ const key = agentSessionID?.trim();
401
+ if (!key) {
402
+ return [];
403
+ }
404
+ return [...(this.sessionArtifacts.Get(key) ?? [])];
405
+ }
248
406
  /**
249
407
  * Builds a wire-name to action map from candidate actions, sanitizing each
250
408
  * action's name and deduplicating collisions (first action wins).
@@ -335,7 +493,12 @@ export class RealtimeClientSessionService {
335
493
  const message = error instanceof Error ? error.message : String(error);
336
494
  return { Success: false, ErrorMessage: `Failed to mint client realtime session: ${message}` };
337
495
  }
496
+ this.stampClientConfigTiming(clientConfig, sessionParams, resolution.Model);
338
497
  const avatarStatus = this.resolveMintedAvatarStatus(prep, clientConfig);
498
+ const mintSnapshot = this.buildMintSnapshot(input, coAgent.ID, resolution, sessionParams, clientConfig);
499
+ if (input.AgentSessionID?.trim()) {
500
+ RealtimeMintSnapshotRegistry.Instance.Set(input.AgentSessionID, mintSnapshot);
501
+ }
339
502
  // Best-effort observability: create a server-side co-agent run (+ prompt run) so the voice
340
503
  // session is visible in the agent-run timeline and delegated runs can nest under it. A
341
504
  // failure here never fails the prepare — we just omit the ids.
@@ -357,8 +520,318 @@ export class RealtimeClientSessionService {
357
520
  ClientPolicy: clientPolicy,
358
521
  NarrationPaceMs: GetNarrationPaceMs(effectiveConfig) ?? undefined,
359
522
  ...(avatarStatus ? { AvatarStatus: avatarStatus } : {}),
523
+ MintSnapshot: toPersistedMintSnapshot(mintSnapshot, resolution.Model),
524
+ };
525
+ }
526
+ /** The full mint snapshot this instance keeps for a session: what a refresh needs to re-mint it or extend its relay. */
527
+ buildMintSnapshot(input, coAgentID, resolution, sessionParams, clientConfig) {
528
+ const sessionConfig = clientConfig.SessionConfig;
529
+ const relayTicketId = extractRelayTicketId(clientConfig.RelayUrl);
530
+ return {
531
+ coAgentID,
532
+ targetAgentID: input.TargetAgentID,
533
+ modelID: resolution.ModelID,
534
+ vendorID: resolution.VendorID,
535
+ modelVendorID: resolution.ModelVendorID,
536
+ driverClass: resolution.DriverClass ?? resolution.Model.constructor.name,
537
+ credentialScope: input.CredentialScope ?? 'Any',
538
+ ...(clientConfig.ConnectionMaxSeconds !== undefined ? { connectionMaxSeconds: clientConfig.ConnectionMaxSeconds } : {}),
539
+ ...(clientConfig.Transport === 'relay' ? { transport: 'relay' } : {}),
540
+ sessionParams,
541
+ ...(sessionConfig && typeof sessionConfig === 'object' && !Array.isArray(sessionConfig)
542
+ ? { existingSessionConfig: { ...sessionConfig } }
543
+ : {}),
544
+ ...(relayTicketId ? { relayTicketId } : {}),
545
+ ...(clientConfig.RelayUrl ? { relayUrl: clientConfig.RelayUrl } : {}),
360
546
  };
361
547
  }
548
+ /**
549
+ * Stamps `ConnectionMaxSeconds`, `SessionMaxSeconds`, `ReconnectBufferSeconds`, and
550
+ * `TrustNativeResumption` onto the typed `ClientRealtimeSessionConfig` fields using
551
+ * {@link ResolveRealtimeTiming} and {@link BaseRealtimeModel.ClientSessionTrustsNativeResumption}.
552
+ * Never writes framework keys into `clientConfig.SessionConfig`, so provider payloads remain clean.
553
+ */
554
+ stampClientConfigTiming(clientConfig, sessionParams, model) {
555
+ const timing = ResolveRealtimeTiming({
556
+ Config: sessionParams.Config,
557
+ DriverDefaultConnectionSeconds: clientConfig.ConnectionMaxSeconds ?? model.DefaultCallDurationSeconds,
558
+ DefaultTrustNativeResumption: clientConfig.TrustNativeResumption ??
559
+ model.ClientSessionTrustsNativeResumption(clientConfig.Transport ?? 'direct'),
560
+ });
561
+ if (timing.ConnectionMaxSeconds !== undefined) {
562
+ clientConfig.ConnectionMaxSeconds =
563
+ clientConfig.ConnectionMaxSeconds !== undefined
564
+ ? Math.min(clientConfig.ConnectionMaxSeconds, timing.ConnectionMaxSeconds)
565
+ : timing.ConnectionMaxSeconds;
566
+ }
567
+ if (timing.SessionMaxSeconds !== undefined && clientConfig.SessionMaxSeconds === undefined) {
568
+ clientConfig.SessionMaxSeconds = timing.SessionMaxSeconds;
569
+ }
570
+ if (clientConfig.ReconnectBufferSeconds === undefined) {
571
+ clientConfig.ReconnectBufferSeconds = timing.ReconnectBufferSeconds;
572
+ }
573
+ if (sessionParams.ZeroDataRetention === true) {
574
+ clientConfig.TrustNativeResumption = false;
575
+ }
576
+ else if (clientConfig.TrustNativeResumption === undefined) {
577
+ clientConfig.TrustNativeResumption = timing.TrustNativeResumption;
578
+ }
579
+ }
580
+ /**
581
+ * Refreshes the browser-facing credential for an active client-direct realtime session without
582
+ * re-running the companion prompt / memory / tool cascade.
583
+ *
584
+ * - If the session is a relay session whose ticket is still live in `RealtimeProxyRegistry`,
585
+ * extends the relay session in place (`ExtendRelaySession`) so existing forwarded resumption
586
+ * handles remain valid, and returns `Kind: 'relay'`.
587
+ * - Otherwise re-mints via `Model.RefreshClientSessionCredential(clampedParams, snapshot.existingSessionConfig)`
588
+ * using the mint snapshot from `RealtimeMintSnapshotRegistry` (falling back to the server-protected
589
+ * `realtimeMintSnapshot` on `MJ: AI Agent Sessions.Config_` for cross-instance failover of a direct session).
590
+ */
591
+ async RefreshClientSessionCredential(input, contextUser, provider) {
592
+ await this.configureEngine(contextUser, provider);
593
+ const sessionID = input.AgentSessionID?.trim();
594
+ if (!sessionID) {
595
+ return { Success: false, ErrorMessage: 'AgentSessionID is required to refresh a client realtime session credential.' };
596
+ }
597
+ const found = await this.findMintSnapshot(sessionID, input, contextUser, provider);
598
+ if (!found.Snapshot) {
599
+ return { Success: false, ErrorMessage: found.ErrorMessage };
600
+ }
601
+ const snapshot = found.Snapshot;
602
+ const clampedParams = {
603
+ ...snapshot.sessionParams,
604
+ ...(input.RemainingSessionSeconds !== undefined
605
+ ? {
606
+ MaxSessionSeconds: snapshot.sessionParams.MaxSessionSeconds !== undefined
607
+ ? Math.min(snapshot.sessionParams.MaxSessionSeconds, input.RemainingSessionSeconds)
608
+ : input.RemainingSessionSeconds,
609
+ }
610
+ : {}),
611
+ };
612
+ if (snapshot.relayTicketId) {
613
+ const additionalSeconds = clampedParams.MaxSessionSeconds ?? REALTIME_RELAY_SESSION_LIFETIME_SECONDS;
614
+ const extended = RealtimeProxyRegistry.Instance.ExtendRelaySession(snapshot.relayTicketId, additionalSeconds, REALTIME_RELAY_MAX_CONNECTIONS, { AllowFreshReopen: input.AllowFreshReopen === true });
615
+ if (extended) {
616
+ // Stored again so the registry's TTL counts from this refresh: a relay session lives only here.
617
+ RealtimeMintSnapshotRegistry.Instance.Set(sessionID, snapshot);
618
+ const baseWs = ResolveRealtimeProxyBaseWsUrl(clampedParams);
619
+ const relayUrl = snapshot.relayUrl ?? BuildRealtimeRelayUrl(baseWs, snapshot.relayTicketId);
620
+ return {
621
+ Success: true,
622
+ Kind: 'relay',
623
+ Credential: {
624
+ Kind: 'relay',
625
+ ExpiresAt: extended.ExpiresAt,
626
+ RelayUrl: relayUrl,
627
+ },
628
+ ExpiresAt: extended.ExpiresAt,
629
+ RelayUrl: relayUrl,
630
+ };
631
+ }
632
+ }
633
+ const coAgent = this.resolveCoAgent({
634
+ CoAgent: input.CoAgent,
635
+ CoAgentID: input.CoAgentID ?? snapshot.coAgentID,
636
+ TargetAgentID: '',
637
+ AgentSessionID: sessionID,
638
+ });
639
+ if (!coAgent) {
640
+ return {
641
+ Success: false,
642
+ ErrorMessage: `Co-agent '${input.CoAgentID ?? snapshot.coAgentID ?? 'unknown'}' could not be resolved for credential refresh.`,
643
+ };
644
+ }
645
+ const resolution = await this.resolveModelFromSnapshot(snapshot, coAgent, input.APIKeys, contextUser);
646
+ if (!resolution) {
647
+ return {
648
+ Success: false,
649
+ ErrorMessage: `Could not resolve realtime model '${snapshot.modelID}' (${snapshot.driverClass}) for credential refresh.`,
650
+ };
651
+ }
652
+ try {
653
+ const clientConfig = await resolution.Model.RefreshClientSessionCredential(clampedParams, snapshot.existingSessionConfig);
654
+ this.stampClientConfigTiming(clientConfig, clampedParams, resolution.Model);
655
+ const newRelayTicketId = extractRelayTicketId(clientConfig.RelayUrl);
656
+ if (newRelayTicketId) {
657
+ snapshot.relayTicketId = newRelayTicketId;
658
+ snapshot.relayUrl = clientConfig.RelayUrl;
659
+ }
660
+ RealtimeMintSnapshotRegistry.Instance.Set(sessionID, snapshot);
661
+ const isRelay = clientConfig.Transport === 'relay' || Boolean(clientConfig.RelayUrl && !clientConfig.EphemeralToken);
662
+ const credential = isRelay
663
+ ? {
664
+ Kind: 'relay',
665
+ ExpiresAt: clientConfig.ExpiresAt,
666
+ RelayUrl: clientConfig.RelayUrl,
667
+ }
668
+ : {
669
+ Kind: 'token',
670
+ EphemeralToken: clientConfig.EphemeralToken,
671
+ ExpiresAt: clientConfig.ExpiresAt,
672
+ };
673
+ return {
674
+ Success: true,
675
+ Kind: credential.Kind,
676
+ Credential: credential,
677
+ EphemeralToken: clientConfig.EphemeralToken,
678
+ ExpiresAt: clientConfig.ExpiresAt,
679
+ RelayUrl: clientConfig.RelayUrl,
680
+ SessionConfigJson: JSON.stringify(clientConfig.SessionConfig),
681
+ ConnectionMaxSeconds: clientConfig.ConnectionMaxSeconds,
682
+ SessionMaxSeconds: clientConfig.SessionMaxSeconds,
683
+ ReconnectBufferSeconds: clientConfig.ReconnectBufferSeconds,
684
+ TrustNativeResumption: clientConfig.TrustNativeResumption,
685
+ };
686
+ }
687
+ catch (error) {
688
+ const message = error instanceof Error ? error.message : String(error);
689
+ return { Success: false, ErrorMessage: `Failed to refresh client realtime session credential: ${message}` };
690
+ }
691
+ }
692
+ async resolveModelFromSnapshot(snapshot, coAgent, apiKeys, contextUser) {
693
+ if (snapshot.credentialScope !== 'Any' && snapshot.credentialScope !== 'RuntimeOnly') {
694
+ LogError(`RealtimeClientSessionService.resolveModelFromSnapshot refused invalid credentialScope '${String(snapshot.credentialScope)}'.`);
695
+ return null;
696
+ }
697
+ const scope = snapshot.credentialScope;
698
+ const resolveRunKey = this.buildRunKeyResolver(apiKeys);
699
+ const platform = await this.resolvePlatformCredentials(scope, coAgent, snapshot.modelID, contextUser);
700
+ const resolveKey = this.buildKeyChain(resolveRunKey, scope, platform, snapshot.modelID);
701
+ const cachedModels = AIEngine.Instance.Models ?? [];
702
+ if (cachedModels.length > 0) {
703
+ const model = this.findModelByID(snapshot.modelID);
704
+ if (!model || !model.IsActive || !this.isRealtimeModel(model)) {
705
+ LogError(`RealtimeClientSessionService.resolveModelFromSnapshot refused inactive or non-realtime model '${snapshot.modelID}'.`);
706
+ return null;
707
+ }
708
+ const vendors = ListRealtimeVendorsForModel(model.ID);
709
+ if (vendors.length > 0) {
710
+ const matchedVendor = vendors.find((v) => v.DriverClass === snapshot.driverClass &&
711
+ (!snapshot.modelVendorID || UUIDsEqual(v.ModelVendorID, snapshot.modelVendorID)));
712
+ if (!matchedVendor) {
713
+ LogError(`RealtimeClientSessionService.resolveModelFromSnapshot refused driver '${snapshot.driverClass}' not bound to model '${model.Name}'.`);
714
+ return null;
715
+ }
716
+ return this.instantiateRealtimeVendor(model, matchedVendor, resolveKey);
717
+ }
718
+ const apiKey = resolveKey(snapshot.driverClass);
719
+ if (apiKey) {
720
+ const instance = this.createModelInstance(snapshot.driverClass, apiKey);
721
+ if (instance) {
722
+ return {
723
+ Model: instance,
724
+ ModelID: model.ID,
725
+ VendorID: snapshot.vendorID ?? '',
726
+ ModelVendorID: snapshot.modelVendorID,
727
+ APIName: snapshot.sessionParams.Model,
728
+ ModelName: model.Name,
729
+ DriverClass: snapshot.driverClass,
730
+ };
731
+ }
732
+ }
733
+ return null;
734
+ }
735
+ const apiKey = resolveKey(snapshot.driverClass);
736
+ if (apiKey) {
737
+ const instance = this.createModelInstance(snapshot.driverClass, apiKey);
738
+ if (instance) {
739
+ return {
740
+ Model: instance,
741
+ ModelID: snapshot.modelID,
742
+ VendorID: snapshot.vendorID ?? '',
743
+ ModelVendorID: snapshot.modelVendorID,
744
+ APIName: snapshot.sessionParams.Model,
745
+ DriverClass: snapshot.driverClass,
746
+ };
747
+ }
748
+ }
749
+ const fallback = await this.resolveRealtimeModel(coAgent, resolveRunKey, scope, false, platform);
750
+ if (fallback && (UUIDsEqual(fallback.ModelID, snapshot.modelID) || !fallback.DriverClass || fallback.DriverClass === snapshot.driverClass)) {
751
+ return fallback;
752
+ }
753
+ return null;
754
+ }
755
+ validatePersistedMintSnapshot(candidate, expectedCoAgentID) {
756
+ if (!candidate || typeof candidate !== 'object' || Array.isArray(candidate)) {
757
+ return null;
758
+ }
759
+ const parsed = candidate;
760
+ if (typeof parsed.modelID !== 'string' ||
761
+ parsed.modelID.trim().length === 0 ||
762
+ typeof parsed.driverClass !== 'string' ||
763
+ parsed.driverClass.trim().length === 0 ||
764
+ (parsed.credentialScope !== 'Any' && parsed.credentialScope !== 'RuntimeOnly') ||
765
+ !parsed.sessionParams ||
766
+ typeof parsed.sessionParams !== 'object' ||
767
+ Array.isArray(parsed.sessionParams) ||
768
+ typeof parsed.sessionParams.Model !== 'string') {
769
+ return null;
770
+ }
771
+ if (expectedCoAgentID &&
772
+ typeof parsed.coAgentID === 'string' &&
773
+ parsed.coAgentID.trim().length > 0 &&
774
+ !UUIDsEqual(parsed.coAgentID, expectedCoAgentID)) {
775
+ LogError(`RealtimeClientSessionService.validatePersistedMintSnapshot refused snapshot whose coAgentID '${parsed.coAgentID}' does not match session coAgentID '${expectedCoAgentID}'.`);
776
+ return null;
777
+ }
778
+ return {
779
+ coAgentID: typeof parsed.coAgentID === 'string' ? parsed.coAgentID : expectedCoAgentID,
780
+ ...(typeof parsed.targetAgentID === 'string' ? { targetAgentID: parsed.targetAgentID } : {}),
781
+ modelID: parsed.modelID,
782
+ vendorID: typeof parsed.vendorID === 'string' ? parsed.vendorID : undefined,
783
+ modelVendorID: typeof parsed.modelVendorID === 'string' ? parsed.modelVendorID : undefined,
784
+ driverClass: parsed.driverClass,
785
+ credentialScope: parsed.credentialScope,
786
+ ...(typeof parsed.connectionMaxSeconds === 'number' ? { connectionMaxSeconds: parsed.connectionMaxSeconds } : {}),
787
+ sessionParams: parsed.sessionParams,
788
+ ...(parsed.existingSessionConfig && typeof parsed.existingSessionConfig === 'object' && !Array.isArray(parsed.existingSessionConfig)
789
+ ? { existingSessionConfig: parsed.existingSessionConfig }
790
+ : {}),
791
+ };
792
+ }
793
+ /**
794
+ * The session's mint snapshot: this instance's copy, else the persisted copy (the one the caller passed, else the one
795
+ * read from the session row), validated and then kept here. A relay session's persisted copy holds no session params,
796
+ * so on any instance but the one that minted it the lookup fails with a reason the caller can show.
797
+ */
798
+ async findMintSnapshot(sessionID, input, contextUser, provider) {
799
+ const cached = RealtimeMintSnapshotRegistry.Instance.Get(sessionID);
800
+ if (cached) {
801
+ return { Snapshot: cached };
802
+ }
803
+ let snapshot = this.validatePersistedMintSnapshot(input.PersistedMintSnapshot, input.CoAgentID);
804
+ let relayCopy = isRelayMintSnapshot(input.PersistedMintSnapshot);
805
+ if (!snapshot && !relayCopy) {
806
+ const stored = await this.loadPersistedMintSnapshot(sessionID, contextUser, provider);
807
+ relayCopy = isRelayMintSnapshot(stored?.Snapshot);
808
+ snapshot = stored ? this.validatePersistedMintSnapshot(stored.Snapshot, input.CoAgentID ?? stored.AgentID) : null;
809
+ }
810
+ if (!snapshot) {
811
+ return {
812
+ ErrorMessage: relayCopy
813
+ ? `Realtime session '${sessionID}' is a relay session: only the MJAPI instance that minted it can refresh its credential.`
814
+ : `No valid mint snapshot found for realtime session '${sessionID}'.`,
815
+ };
816
+ }
817
+ RealtimeMintSnapshotRegistry.Instance.Set(sessionID, snapshot);
818
+ return { Snapshot: snapshot };
819
+ }
820
+ /** The `realtimeMintSnapshot` stored on the session row, not yet validated, with the row's co-agent; null when absent. */
821
+ async loadPersistedMintSnapshot(agentSessionID, contextUser, provider) {
822
+ try {
823
+ const session = await provider.GetEntityObject('MJ: AI Agent Sessions', contextUser);
824
+ if (!(await session.Load(agentSessionID)) || !session.Config_) {
825
+ return null;
826
+ }
827
+ const configObj = JSON.parse(session.Config_);
828
+ return { Snapshot: configObj.realtimeMintSnapshot, AgentID: session.AgentID };
829
+ }
830
+ catch (error) {
831
+ LogError(`RealtimeClientSessionService.loadPersistedMintSnapshot failed: ${error instanceof Error ? error.message : String(error)}`);
832
+ return null;
833
+ }
834
+ }
362
835
  /**
363
836
  * The call's avatar status once the driver has minted the session (see {@link ResolveRealtimeAvatarStatus}), with one
364
837
  * log line saying whether the avatar shows. `undefined`, and no line, when the session asked for no avatar.
@@ -530,6 +1003,9 @@ export class RealtimeClientSessionService {
530
1003
  TargetAgentID: wiring.Input.TargetAgentID,
531
1004
  AllowedAgents: wiring.AllowedAgents,
532
1005
  DirectActions: wiring.Prep.EffectiveConfig?.realtime?.directActions,
1006
+ // The preparing run's scope and skills, from the server-built prep input.
1007
+ RunScope: wiring.Input.RunScope,
1008
+ ActiveSkillIDs: wiring.Input.ActiveSkillIDs,
533
1009
  OnProgress: (progress) => wiring.Narrator.HandleProgress(progress),
534
1010
  Call: call,
535
1011
  }, wiring.ContextUser, wiring.Provider))).ResultJson;
@@ -611,6 +1087,15 @@ export class RealtimeClientSessionService {
611
1087
  */
612
1088
  async PrepareRealtimeSessionParams(input, contextUser, provider) {
613
1089
  await this.configureEngine(contextUser, provider);
1090
+ const sessionKey = input.AgentSessionID?.trim();
1091
+ if (sessionKey) {
1092
+ if (input.ConversationID?.trim()) {
1093
+ this.sessionConversationIds.Set(sessionKey, input.ConversationID.trim());
1094
+ }
1095
+ if (input.ConversationArtifacts?.length) {
1096
+ this.RecordSessionArtifacts(sessionKey, input.ConversationArtifacts);
1097
+ }
1098
+ }
614
1099
  const coAgent = this.resolveCoAgent(input);
615
1100
  if (!coAgent) {
616
1101
  return { Success: false, ErrorMessage: 'The Realtime Co-Agent could not be resolved from the supplied id or entity.' };
@@ -2156,8 +2641,9 @@ export class RealtimeClientSessionService {
2156
2641
  const appContextSection = this.buildAppContextSection(input.AppContext);
2157
2642
  const priorTranscript = this.formatPriorTranscript(input.PriorTranscript);
2158
2643
  const history = this.formatConversationHistory(input.ConversationMessages);
2644
+ const artifacts = this.formatConversationArtifacts(input.ConversationArtifacts);
2159
2645
  const memory = memoryContext ?? await this.assembleMemoryContext(input, coAgent, contextUser, provider);
2160
- return [framing, meetingFraming, hostFraming, coAgentPrompt, voiceManner, targetIdentity, appContextSection, priorTranscript, history, memory]
2646
+ return [framing, meetingFraming, hostFraming, coAgentPrompt, voiceManner, targetIdentity, appContextSection, priorTranscript, history, artifacts, memory]
2161
2647
  .filter(part => part && part.trim().length > 0)
2162
2648
  .join('\n\n');
2163
2649
  }
@@ -2279,9 +2765,15 @@ export class RealtimeClientSessionService {
2279
2765
  `Knowledge Hub" → ContextTool with action 'NavigateToApp'; "open this record"; "switch to the X tab"). ` +
2280
2766
  `Do NOT route in-app navigation/actions through '${INVOKE_TARGET_AGENT_TOOL_NAME}', and NEVER say you ` +
2281
2767
  `need an active session id or a screen snapshot to do them — calling 'ContextTool' is all that's ` +
2282
- `needed. Reserve '${INVOKE_TARGET_AGENT_TOOL_NAME}' for actual analysis / data work, not navigation. ` +
2768
+ `needed. Reserve '${INVOKE_TARGET_AGENT_TOOL_NAME}' for actual analysis / data / artifact creation work, not navigation. ` +
2283
2769
  `When a channel note lists interactive channels you can use, 'ContextTool' also addresses ONE of ` +
2284
- `them: add "target": { "channel": "<channel name>" } and use that channel's action names.`;
2770
+ `them: add "target": { "channel": "<channel name>" } and use that channel's action names (for example, ` +
2771
+ `in 'ArtifactWorkspace' call ContextTool with action 'open' and params { "artifactId": "<id>" } or ` +
2772
+ `{ "name": "<title>" }; call action 'navigate_to_anchor' with params { "artifactId"?: "<id>", ` +
2773
+ `"sheet"?: "<sheet>", "range"?: "<A1:D10>", "heading"?: "<section>", "blockId"?: "<id>", ` +
2774
+ `"slideNumber"?: <1-based n>, "elementId"?: "<id>", "highlightMs"?: <ms> } to jump the user's viewer straight to a cell, section, slide, ` +
2775
+ `or element; and call action 'set_view_mode' with params { "artifactId"?: "<id>", "mode": "edit" | "suggest" | "diff" | "present" } to ` +
2776
+ `switch viewer mode. Watch 'selection_changed' context events to see what the user highlighted).`;
2285
2777
  }
2286
2778
  return clause;
2287
2779
  }
@@ -2377,6 +2869,35 @@ export class RealtimeClientSessionService {
2377
2869
  .filter(line => line.length > 0);
2378
2870
  return lines.length > 0 ? `Conversation so far:\n${lines.join('\n')}` : '';
2379
2871
  }
2872
+ /**
2873
+ * Formats artifacts already created or attached in the conversation before this call started
2874
+ * so the co-agent can open or revise them by ID rather than duplicating them.
2875
+ *
2876
+ * @param artifacts The deduplicated conversation artifact summaries, or undefined.
2877
+ * @returns The formatted section, or empty string when none exist.
2878
+ */
2879
+ formatConversationArtifacts(artifacts) {
2880
+ if (!artifacts || artifacts.length === 0) {
2881
+ return '';
2882
+ }
2883
+ const lines = artifacts
2884
+ .filter(a => a.ArtifactID && a.Name)
2885
+ .map(a => {
2886
+ const typePart = a.Type ? `, Type: ${a.Type}` : '';
2887
+ const verPart = typeof a.LatestVersionNumber === 'number' ? `, LatestVersion: v${a.LatestVersionNumber}` : '';
2888
+ return `- "${a.Name}" (ArtifactID: ${a.ArtifactID}${typePart}${verPart})`;
2889
+ });
2890
+ if (lines.length === 0) {
2891
+ return '';
2892
+ }
2893
+ return ('Artifacts already in this conversation (to display a Doc, Spreadsheet, or Presentation in the workspace use ContextTool with ' +
2894
+ 'target={ "channel": "ArtifactWorkspace" }, action="open", params={ "artifactId": "<ArtifactID>" }; ' +
2895
+ 'to jump the viewer to a specific section, cell range, or slide use action="navigate_to_anchor" with ' +
2896
+ 'params={ "artifactId"?: "<ArtifactID>", "sheet"?: "<sheet>", "range"?: "<A1:D10>", "heading"?: "<heading>", "blockId"?: "<id>", "slideNumber"?: <1-based n>, "elementId"?: "<id>", "highlightMs"?: <ms> }; ' +
2897
+ 'to change mode use action="set_view_mode" with params={ "artifactId"?: "<ArtifactID>", "mode": "edit" | "suggest" | "diff" | "present" }; ' +
2898
+ 'to revise an existing artifact via invoke-target-agent, include its ArtifactID so the agent updates it instead of creating a duplicate):\n' +
2899
+ lines.join('\n'));
2900
+ }
2380
2901
  /**
2381
2902
  * Assembles the same memory/context block a loop agent injects, reusing
2382
2903
  * {@link AgentMemoryContextBuilder} so there is no duplicated retrieval logic. The builder
@@ -2512,7 +3033,7 @@ export class RealtimeClientSessionService {
2512
3033
  buildToolBroker(input, contextUser, provider) {
2513
3034
  const deps = {
2514
3035
  DelegateToTarget: (request) => this.delegateToTarget(input, request, contextUser, provider),
2515
- ExecuteTool: (call) => this.executeNonTargetTool(call, input, contextUser)
3036
+ ExecuteTool: (call) => this.executeNonTargetTool(call, input, contextUser, provider)
2516
3037
  };
2517
3038
  return new RealtimeToolBroker(deps);
2518
3039
  }
@@ -2542,6 +3063,9 @@ export class RealtimeClientSessionService {
2542
3063
  try {
2543
3064
  const result = await this.runDelegatedAgent(input, request, resolution.Agent, contextUser, provider);
2544
3065
  const artifacts = await this.createDelegatedRunArtifacts(result, contextUser, provider);
3066
+ if (artifacts?.length && input.AgentSessionID?.trim()) {
3067
+ this.RecordSessionArtifacts(input.AgentSessionID, artifacts);
3068
+ }
2545
3069
  return this.buildDelegatedResult(request.CallID, result, artifacts);
2546
3070
  }
2547
3071
  catch (error) {
@@ -2641,8 +3165,9 @@ export class RealtimeClientSessionService {
2641
3165
  async createDelegatedRunArtifacts(result, contextUser, provider) {
2642
3166
  const paused = result.agentRun?.Status === 'AwaitingFeedback';
2643
3167
  const payload = result.payload;
2644
- const hasPayload = payload != null && Object.keys(payload).length > 0;
2645
- if (!result.success || paused || !hasPayload) {
3168
+ const hasPayload = payload != null && typeof payload === 'object' && Object.keys(payload).length > 0;
3169
+ const hasTouched = (result.touchedArtifacts?.length ?? 0) > 0;
3170
+ if (!hasTouched && (!result.success || paused || !hasPayload)) {
2646
3171
  return undefined;
2647
3172
  }
2648
3173
  try {
@@ -2655,35 +3180,25 @@ export class RealtimeClientSessionService {
2655
3180
  }
2656
3181
  }
2657
3182
  /**
2658
- * The DB-backed artifact-creation seam: runs `AgentRunner.ProcessAgentArtifacts` WITHOUT a
2659
- * conversation detail (the voice path has none — the artifact + version are created and the
2660
- * junction link is skipped), then loads the artifact header for its display name.
2661
- *
2662
- * Artifacts whose Visibility resolved to `System Only` (the agent's ArtifactCreationMode) are
2663
- * created but NOT surfaced to the overlay — matching how chat hides them from users.
2664
- *
2665
- * **Overridable seam** so tests can exercise {@link createDelegatedRunArtifacts}' eligibility
2666
- * guards without a DB.
2667
- *
2668
- * @param result The delegated agent execution result (payload + agentRun).
2669
- * @param contextUser The calling user.
2670
- * @param provider The request-scoped metadata provider.
2671
- * @returns The produced artifact descriptor(s), or `undefined`.
3183
+ * The DB-backed artifact-creation seam: surfaces collaborative artifacts touched during the run
3184
+ * (`result.touchedArtifacts`) plus any payload artifact created by `AgentRunner.ProcessAgentArtifacts`
3185
+ * (without a conversation detail on voice paths). Payload artifacts are created only on completed,
3186
+ * successful runs (paused/failed runs still surface touched governed artifacts).
2672
3187
  */
2673
3188
  async processRunArtifacts(result, contextUser, provider) {
3189
+ const paused = result.agentRun?.Status === 'AwaitingFeedback';
3190
+ const canProcessPayload = result.success && !paused;
2674
3191
  const runner = new AgentRunner(provider);
2675
- const info = await runner.ProcessAgentArtifacts(result, undefined, undefined, contextUser, provider);
2676
- if (!info) {
2677
- return undefined;
2678
- }
2679
- const artifact = await provider.GetEntityObject('MJ: Artifacts', contextUser);
2680
- if (!(await artifact.Load(info.artifactId))) {
2681
- return undefined;
2682
- }
2683
- if (artifact.Visibility === 'System Only') {
2684
- return undefined; // created for system purposes, never user-surfaced
2685
- }
2686
- return [{ ArtifactID: info.artifactId, ArtifactVersionID: info.versionId, Name: artifact.Name }];
3192
+ return CollectDelegatedRunArtifacts({
3193
+ Result: result,
3194
+ ContextUser: contextUser,
3195
+ Provider: provider,
3196
+ ...(canProcessPayload
3197
+ ? {
3198
+ ProcessPayloadArtifacts: (r) => runner.ProcessAgentArtifacts(r, undefined, undefined, contextUser, provider),
3199
+ }
3200
+ : {}),
3201
+ });
2687
3202
  }
2688
3203
  /**
2689
3204
  * Runs (or resumes) the target agent for a delegation. Threads the combined abort signal, parent
@@ -2706,6 +3221,41 @@ export class RealtimeClientSessionService {
2706
3221
  const parentRun = await this.loadParentRun(input.ParentRunID, contextUser, provider);
2707
3222
  const runner = new AgentRunner(provider);
2708
3223
  const combined = this.combineSignals(request.AbortSignal, input.AbortSignal);
3224
+ const sessionKey = input.AgentSessionID?.trim();
3225
+ const sessionSummaries = sessionKey
3226
+ ? this.RecordSessionArtifacts(sessionKey, input.ConversationArtifacts)
3227
+ : (input.ConversationArtifacts ?? []);
3228
+ const effectiveConversationId = input.ConversationID?.trim() || (sessionKey ? this.sessionConversationIds.Get(sessionKey) : undefined);
3229
+ const resolvedInputArtifacts = [];
3230
+ for (const summary of sessionSummaries) {
3231
+ try {
3232
+ const loaded = await GovernedArtifactService.Instance.LoadReadableArtifactState(provider, contextUser, summary.ArtifactID);
3233
+ if (loaded.state) {
3234
+ const st = loaded.state;
3235
+ resolvedInputArtifacts.push({
3236
+ name: st.name,
3237
+ typeName: st.typeName,
3238
+ content: st.content,
3239
+ artifactId: st.artifactId,
3240
+ ...(st.versionId ? { versionId: st.versionId } : {}),
3241
+ versionNumber: st.versionNumber,
3242
+ ...(st.description ? { description: st.description } : {}),
3243
+ ...(st.mimeType ? { mimeType: st.mimeType } : {}),
3244
+ ...(st.toolLibraryClass ? { toolLibraryClass: st.toolLibraryClass } : {}),
3245
+ });
3246
+ }
3247
+ }
3248
+ catch {
3249
+ // Non-fatal: individual unreadable/evicted artifact does not abort delegated run
3250
+ }
3251
+ }
3252
+ const runData = {};
3253
+ if (input.AppContext) {
3254
+ runData.appContext = input.AppContext;
3255
+ }
3256
+ if (sessionSummaries.length > 0) {
3257
+ runData.conversationArtifacts = sessionSummaries;
3258
+ }
2709
3259
  try {
2710
3260
  return await runner.RunAgent({
2711
3261
  agent: target,
@@ -2720,16 +3270,35 @@ export class RealtimeClientSessionService {
2720
3270
  parentRun: parentRun ?? undefined,
2721
3271
  agentSessionID: input.AgentSessionID,
2722
3272
  sessionID: input.BrowserSessionID,
2723
- data: input.AppContext ? { appContext: input.AppContext } : undefined,
3273
+ ...(effectiveConversationId ? { conversationId: effectiveConversationId } : {}),
3274
+ ...(resolvedInputArtifacts.length > 0 ? { inputArtifacts: resolvedInputArtifacts } : {}),
3275
+ data: Object.keys(runData).length > 0 ? runData : undefined,
2724
3276
  onProgress: input.OnProgress,
2725
3277
  lastRunId: input.ResumeRunID,
2726
- autoPopulateLastRunPayload: input.ResumeRunID ? true : undefined
3278
+ autoPopulateLastRunPayload: input.ResumeRunID ? true : undefined,
3279
+ // The session's run scope and active skills (#5624), as BaseAgent hands a sub-agent its own.
3280
+ ...this.delegatedRunScope(input)
2727
3281
  });
2728
3282
  }
2729
3283
  finally {
2730
3284
  combined.Dispose();
2731
3285
  }
2732
3286
  }
3287
+ /**
3288
+ * The scope a delegated target-agent run starts with: the session's ({@link ExecuteRelayedToolInput.RunScope}) and
3289
+ * its active skills, in the `ExecuteAgentParams` fields BaseAgent propagates to a sub-agent. Nothing for a session
3290
+ * with no scope, so the delegated run is unscoped, as before.
3291
+ */
3292
+ delegatedRunScope(input) {
3293
+ const scope = input.RunScope;
3294
+ return {
3295
+ ...(scope?.PrimaryScopeEntityName ? { PrimaryScopeEntityName: scope.PrimaryScopeEntityName } : {}),
3296
+ ...(scope?.PrimaryScopeRecordID ? { PrimaryScopeRecordID: scope.PrimaryScopeRecordID } : {}),
3297
+ ...(scope?.SecondaryScopes ? { SecondaryScopes: { ...scope.SecondaryScopes } } : {}),
3298
+ ...(scope?.SearchScopeIDs?.length ? { SearchScopeIDs: [...scope.SearchScopeIDs] } : {}),
3299
+ ...(input.ActiveSkillIDs?.length ? { parentActivatedSkillIDs: [...input.ActiveSkillIDs] } : {}),
3300
+ };
3301
+ }
2733
3302
  /**
2734
3303
  * Maps an {@link ExecuteAgentResult} onto the broker's {@link DelegatedResult}, special-casing a
2735
3304
  * run that paused awaiting feedback. An `AwaitingFeedback` run is a valid intermediate outcome,
@@ -2752,7 +3321,8 @@ export class RealtimeClientSessionService {
2752
3321
  Success: true,
2753
3322
  Output: `You need an answer from the user before you can continue this work. Ask them, in your own first-person voice: ${question}`,
2754
3323
  PausedRunID: result.agentRun.ID,
2755
- RunID: result.agentRun.ID
3324
+ RunID: result.agentRun.ID,
3325
+ ...(artifacts ? { Artifacts: artifacts } : {}),
2756
3326
  };
2757
3327
  }
2758
3328
  return {
@@ -2907,6 +3477,32 @@ export class RealtimeClientSessionService {
2907
3477
  type: schemaType,
2908
3478
  description: p.Description || p.Name
2909
3479
  };
3480
+ if (p.IsArray) {
3481
+ const lowerName = p.Name.trim().toLowerCase();
3482
+ if (lowerName === 'operations' || lowerName === 'initialoperations') {
3483
+ propSchema.items = {
3484
+ type: 'object',
3485
+ description: 'Single governed artifact tool invocation inside the array.',
3486
+ properties: {
3487
+ tool: {
3488
+ type: 'string',
3489
+ description: 'Exact artifact tool name, e.g. "write_cells", "insert_block_after", "add_slide".'
3490
+ },
3491
+ input: {
3492
+ type: 'object',
3493
+ description: 'JSON arguments object matching the selected tool\'s inputSchema.'
3494
+ }
3495
+ },
3496
+ required: ['tool']
3497
+ };
3498
+ }
3499
+ else if (p.ValueType === 'Simple Object' || p.ValueType === 'BaseEntity Sub-Class') {
3500
+ propSchema.items = { type: 'object' };
3501
+ }
3502
+ else {
3503
+ propSchema.items = { type: 'string' };
3504
+ }
3505
+ }
2910
3506
  properties[p.Name] = propSchema;
2911
3507
  if (p.IsRequired) {
2912
3508
  required.push(p.Name);
@@ -2941,7 +3537,7 @@ export class RealtimeClientSessionService {
2941
3537
  * @param contextUser The calling user context.
2942
3538
  * @returns A {@link ToolExecutionResult} for the model's tool_response.
2943
3539
  */
2944
- async executeNonTargetTool(call, input, contextUser) {
3540
+ async executeNonTargetTool(call, input, contextUser, provider) {
2945
3541
  if (!input?.TargetAgentID) {
2946
3542
  return {
2947
3543
  CallID: call.CallID,
@@ -2998,6 +3594,19 @@ export class RealtimeClientSessionService {
2998
3594
  runParams.ContextUser = executingUser;
2999
3595
  runParams.Params = actionParams;
3000
3596
  runParams.Filters = [];
3597
+ if (provider) {
3598
+ runParams.Provider = provider;
3599
+ }
3600
+ // The session's run scope and active skills, as BaseAgent stamps them on every action call in a run
3601
+ // (#5624). The arguments are model-written, so without them a Scoped Search here runs as a direct call
3602
+ // and searches whatever tenant and skill the model names.
3603
+ runParams.RunScope = this.directToolRunScope(input);
3604
+ runParams.Context = {
3605
+ AgentID: target.ID,
3606
+ AgentName: target.Name,
3607
+ ...(input.ParentRunID ? { AgentRunID: input.ParentRunID } : {}),
3608
+ ActiveSkillIDs: [...(input.ActiveSkillIDs ?? [])]
3609
+ };
3001
3610
  let timerHandle;
3002
3611
  const timeoutPromise = new Promise((_, reject) => {
3003
3612
  timerHandle = setTimeout(() => {
@@ -3008,7 +3617,7 @@ export class RealtimeClientSessionService {
3008
3617
  }
3009
3618
  });
3010
3619
  const result = await Promise.race([
3011
- ActionEngineServer.Instance.RunAction(runParams),
3620
+ AgentUserPolicyEngine.Instance.RunWithExecutingAgentContext(target.ID, () => ActionEngineServer.Instance.RunAction(runParams)),
3012
3621
  timeoutPromise
3013
3622
  ]).finally(() => {
3014
3623
  if (timerHandle) {
@@ -3016,10 +3625,15 @@ export class RealtimeClientSessionService {
3016
3625
  }
3017
3626
  });
3018
3627
  const outputText = result.Message || (result.Success ? 'Action completed successfully.' : 'Action failed.');
3628
+ const actionArtifacts = ExtractDirectActionArtifacts(action.Name, result.Success, result.Params);
3629
+ if (actionArtifacts?.length && input.AgentSessionID?.trim()) {
3630
+ this.RecordSessionArtifacts(input.AgentSessionID, actionArtifacts);
3631
+ }
3019
3632
  return {
3020
3633
  CallID: call.CallID,
3021
3634
  Success: result.Success,
3022
- Output: outputText
3635
+ Output: outputText,
3636
+ ...(actionArtifacts ? { Artifacts: actionArtifacts } : {})
3023
3637
  };
3024
3638
  }
3025
3639
  catch (error) {
@@ -3031,6 +3645,21 @@ export class RealtimeClientSessionService {
3031
3645
  };
3032
3646
  }
3033
3647
  }
3648
+ /**
3649
+ * The `RunScope` a direct tool call carries: the session's ({@link ExecuteRelayedToolInput.RunScope}), copied so
3650
+ * an action cannot change what the next call sees, or an unscoped run's (every field null) when the session has
3651
+ * none. Never absent: an absent `RunScope` tells an action it is called outside any run.
3652
+ */
3653
+ directToolRunScope(input) {
3654
+ const scope = input.RunScope;
3655
+ if (!scope) {
3656
+ return { PrimaryScopeEntityName: null, PrimaryScopeRecordID: null, SecondaryScopes: null };
3657
+ }
3658
+ const secondary = scope.SecondaryScopes
3659
+ ? Object.fromEntries(Object.entries(scope.SecondaryScopes).map(([key, value]) => [key, Array.isArray(value) ? [...value] : value]))
3660
+ : null;
3661
+ return { ...scope, SecondaryScopes: secondary, ...(scope.SearchScopeIDs ? { SearchScopeIDs: [...scope.SearchScopeIDs] } : {}) };
3662
+ }
3034
3663
  /**
3035
3664
  * Finds the action a relayed tool name refers to: the exact wire name first, then a
3036
3665
  * case-insensitive match.