@memberjunction/ai-agents 6.2.0 → 6.3.0-edge.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/README.md +21 -1
  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 +5 -1
  7. package/dist/AgentDataPreloader.d.ts.map +1 -1
  8. package/dist/AgentDataPreloader.js +13 -7
  9. package/dist/AgentDataPreloader.js.map +1 -1
  10. package/dist/AgentFeedbackCoordinator.d.ts +169 -0
  11. package/dist/AgentFeedbackCoordinator.d.ts.map +1 -0
  12. package/dist/AgentFeedbackCoordinator.js +593 -0
  13. package/dist/AgentFeedbackCoordinator.js.map +1 -0
  14. package/dist/AgentStepDispatcher.d.ts +211 -0
  15. package/dist/AgentStepDispatcher.d.ts.map +1 -0
  16. package/dist/AgentStepDispatcher.js +729 -0
  17. package/dist/AgentStepDispatcher.js.map +1 -0
  18. package/dist/AgentTreeBudgetTracker.d.ts +163 -0
  19. package/dist/AgentTreeBudgetTracker.d.ts.map +1 -0
  20. package/dist/AgentTreeBudgetTracker.js +415 -0
  21. package/dist/AgentTreeBudgetTracker.js.map +1 -0
  22. package/dist/AgentWakeTriggerService.d.ts +41 -1
  23. package/dist/AgentWakeTriggerService.d.ts.map +1 -1
  24. package/dist/AgentWakeTriggerService.js +154 -8
  25. package/dist/AgentWakeTriggerService.js.map +1 -1
  26. package/dist/MJAIAgentRequestEntityServer.d.ts +32 -1
  27. package/dist/MJAIAgentRequestEntityServer.d.ts.map +1 -1
  28. package/dist/MJAIAgentRequestEntityServer.js +105 -3
  29. package/dist/MJAIAgentRequestEntityServer.js.map +1 -1
  30. package/dist/PayloadManager.d.ts.map +1 -1
  31. package/dist/PayloadManager.js +14 -1
  32. package/dist/PayloadManager.js.map +1 -1
  33. package/dist/SkillMarkdownConverter.d.ts +1 -1
  34. package/dist/SkillMarkdownConverter.d.ts.map +1 -1
  35. package/dist/SkillMarkdownConverter.js +4 -4
  36. package/dist/SkillMarkdownConverter.js.map +1 -1
  37. package/dist/agent-pre-execution-rag.d.ts +5 -0
  38. package/dist/agent-pre-execution-rag.d.ts.map +1 -1
  39. package/dist/agent-pre-execution-rag.js +5 -0
  40. package/dist/agent-pre-execution-rag.js.map +1 -1
  41. package/dist/agent-types/base-agent-type.d.ts.map +1 -1
  42. package/dist/agent-types/base-agent-type.js +8 -1
  43. package/dist/agent-types/base-agent-type.js.map +1 -1
  44. package/dist/agent-types/loop-agent-prompt-params.d.ts +18 -0
  45. package/dist/agent-types/loop-agent-prompt-params.d.ts.map +1 -1
  46. package/dist/agent-types/loop-agent-prompt-params.js +2 -0
  47. package/dist/agent-types/loop-agent-prompt-params.js.map +1 -1
  48. package/dist/base-agent.d.ts +105 -133
  49. package/dist/base-agent.d.ts.map +1 -1
  50. package/dist/base-agent.js +395 -1472
  51. package/dist/base-agent.js.map +1 -1
  52. package/dist/catalog-narrowing.d.ts +112 -5
  53. package/dist/catalog-narrowing.d.ts.map +1 -1
  54. package/dist/catalog-narrowing.js +181 -6
  55. package/dist/catalog-narrowing.js.map +1 -1
  56. package/dist/index.d.ts +6 -1
  57. package/dist/index.d.ts.map +1 -1
  58. package/dist/index.js +6 -1
  59. package/dist/index.js.map +1 -1
  60. package/dist/pipeline/operators.d.ts.map +1 -1
  61. package/dist/pipeline/operators.js +1 -1
  62. package/dist/pipeline/operators.js.map +1 -1
  63. package/dist/pipeline/pipeline-executor.d.ts +29 -1
  64. package/dist/pipeline/pipeline-executor.d.ts.map +1 -1
  65. package/dist/pipeline/pipeline-executor.js +159 -2
  66. package/dist/pipeline/pipeline-executor.js.map +1 -1
  67. package/dist/pipeline/pipeline.types.d.ts +19 -1
  68. package/dist/pipeline/pipeline.types.d.ts.map +1 -1
  69. package/dist/pipeline/template.d.ts +11 -0
  70. package/dist/pipeline/template.d.ts.map +1 -1
  71. package/dist/pipeline/template.js +56 -6
  72. package/dist/pipeline/template.js.map +1 -1
  73. package/dist/realtime/bridge-room-transcript-sink.d.ts.map +1 -1
  74. package/dist/realtime/bridge-room-transcript-sink.js +28 -1
  75. package/dist/realtime/bridge-room-transcript-sink.js.map +1 -1
  76. package/dist/realtime/media-channel-server.js +1 -1
  77. package/dist/realtime/media-channel-server.js.map +1 -1
  78. package/dist/realtime/realtime-client-session-service.d.ts +122 -2
  79. package/dist/realtime/realtime-client-session-service.d.ts.map +1 -1
  80. package/dist/realtime/realtime-client-session-service.js +413 -4
  81. package/dist/realtime/realtime-client-session-service.js.map +1 -1
  82. package/dist/realtime/realtime-coagent-config.d.ts +4 -2
  83. package/dist/realtime/realtime-coagent-config.d.ts.map +1 -1
  84. package/dist/realtime/realtime-coagent-config.js +27 -38
  85. package/dist/realtime/realtime-coagent-config.js.map +1 -1
  86. package/dist/realtime/realtime-delegation-narrator.js +1 -1
  87. package/dist/realtime/realtime-delegation-narrator.js.map +1 -1
  88. package/dist/realtime/realtime-session-runner.d.ts +2 -0
  89. package/dist/realtime/realtime-session-runner.d.ts.map +1 -1
  90. package/dist/realtime/realtime-session-runner.js +24 -3
  91. package/dist/realtime/realtime-session-runner.js.map +1 -1
  92. package/dist/unsafe-object-keys.d.ts +20 -0
  93. package/dist/unsafe-object-keys.d.ts.map +1 -0
  94. package/dist/unsafe-object-keys.js +42 -0
  95. package/dist/unsafe-object-keys.js.map +1 -0
  96. package/package.json +20 -20
@@ -30,11 +30,11 @@
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';
@@ -74,6 +74,99 @@ const deprecatedVideoKeysLogged = new Set();
74
74
  * price prices them. Raise it for a model that counts more.
75
75
  */
76
76
  const VIDEO_TOKENS_PER_SECOND = 6192;
77
+ const MINT_SNAPSHOT_MAX_ENTRIES = 2000;
78
+ const MINT_SNAPSHOT_TTL_MS = 4 * 60 * 60 * 1000;
79
+ /**
80
+ * Process-wide singleton registry of mint snapshots for active client-direct realtime sessions,
81
+ * backed by `BaseSingleton` (`GetGlobalObjectStore()`) with bounded LRU/TTL eviction.
82
+ */
83
+ export class RealtimeMintSnapshotRegistry extends BaseSingleton {
84
+ constructor() {
85
+ super();
86
+ this._snapshots = new MJLruCache({
87
+ maxSize: MINT_SNAPSHOT_MAX_ENTRIES,
88
+ ttlMs: MINT_SNAPSHOT_TTL_MS,
89
+ });
90
+ }
91
+ static get Instance() {
92
+ return super.getInstance();
93
+ }
94
+ Set(agentSessionID, snapshot) {
95
+ const key = NormalizeUUID(agentSessionID);
96
+ if (!key) {
97
+ return;
98
+ }
99
+ this._snapshots.Set(key, snapshot);
100
+ }
101
+ Get(agentSessionID) {
102
+ const key = NormalizeUUID(agentSessionID);
103
+ return key ? this._snapshots.Get(key) : undefined;
104
+ }
105
+ Delete(agentSessionID) {
106
+ const key = NormalizeUUID(agentSessionID);
107
+ if (key) {
108
+ this._snapshots.Delete(key);
109
+ }
110
+ }
111
+ Clear() {
112
+ this._snapshots.Clear();
113
+ }
114
+ }
115
+ /**
116
+ * The copy of a mint snapshot the transport layer persists on the owner-readable session row
117
+ * ({@link PersistedRealtimeMintSnapshot}):
118
+ * - A relay session keeps its session params on this instance only. Its browser is deliberately given no system
119
+ * prompt, tools or upstream configuration, so the owner must not read them from the row either. Its relay lives in
120
+ * this process: another instance could only open a new relay and re-seed the call, from exactly those params, so a
121
+ * refresh there fails and says why.
122
+ * - A direct session keeps its params: its browser was handed the prompt and tools in the provider config it applies,
123
+ * and another instance needs them to mint an equivalent credential. The minted provider config is kept only when the
124
+ * driver's refresh reads it (ElevenLabs reuses its managed agent); the base refresh ignores it.
125
+ */
126
+ function toPersistedMintSnapshot(snapshot, model) {
127
+ const routing = {
128
+ coAgentID: snapshot.coAgentID,
129
+ targetAgentID: snapshot.targetAgentID,
130
+ modelID: snapshot.modelID,
131
+ vendorID: snapshot.vendorID,
132
+ modelVendorID: snapshot.modelVendorID,
133
+ driverClass: snapshot.driverClass,
134
+ credentialScope: snapshot.credentialScope,
135
+ connectionMaxSeconds: snapshot.connectionMaxSeconds,
136
+ };
137
+ if (snapshot.transport === 'relay') {
138
+ return { ...routing, transport: 'relay' };
139
+ }
140
+ const refreshReadsSessionConfig = model.RefreshClientSessionCredential !== BaseRealtimeModel.prototype.RefreshClientSessionCredential;
141
+ return {
142
+ ...routing,
143
+ sessionParams: snapshot.sessionParams,
144
+ ...(refreshReadsSessionConfig && snapshot.existingSessionConfig ? { existingSessionConfig: snapshot.existingSessionConfig } : {}),
145
+ };
146
+ }
147
+ /** Whether a persisted mint snapshot is a relay session's, whose session params only its minting instance holds. */
148
+ function isRelayMintSnapshot(candidate) {
149
+ return typeof candidate === 'object' && candidate !== null && candidate.transport === 'relay';
150
+ }
151
+ function extractRelayTicketId(relayUrl) {
152
+ if (!relayUrl) {
153
+ return undefined;
154
+ }
155
+ const marker = `${REALTIME_RELAY_PATH}/`;
156
+ const idx = relayUrl.indexOf(marker);
157
+ if (idx < 0) {
158
+ return undefined;
159
+ }
160
+ const tail = relayUrl.slice(idx + marker.length);
161
+ const slash = tail.indexOf('/');
162
+ const raw = slash >= 0 ? tail.slice(0, slash) : tail;
163
+ try {
164
+ return decodeURIComponent(raw) || undefined;
165
+ }
166
+ catch {
167
+ return raw || undefined;
168
+ }
169
+ }
77
170
  /** Runtime handles by their realtime session, so the layer that only holds the session can reach its runtime. */
78
171
  const bridgeRuntimes = new WeakMap();
79
172
  /**
@@ -335,7 +428,12 @@ export class RealtimeClientSessionService {
335
428
  const message = error instanceof Error ? error.message : String(error);
336
429
  return { Success: false, ErrorMessage: `Failed to mint client realtime session: ${message}` };
337
430
  }
431
+ this.stampClientConfigTiming(clientConfig, sessionParams, resolution.Model);
338
432
  const avatarStatus = this.resolveMintedAvatarStatus(prep, clientConfig);
433
+ const mintSnapshot = this.buildMintSnapshot(input, coAgent.ID, resolution, sessionParams, clientConfig);
434
+ if (input.AgentSessionID?.trim()) {
435
+ RealtimeMintSnapshotRegistry.Instance.Set(input.AgentSessionID, mintSnapshot);
436
+ }
339
437
  // Best-effort observability: create a server-side co-agent run (+ prompt run) so the voice
340
438
  // session is visible in the agent-run timeline and delegated runs can nest under it. A
341
439
  // failure here never fails the prepare — we just omit the ids.
@@ -357,7 +455,317 @@ export class RealtimeClientSessionService {
357
455
  ClientPolicy: clientPolicy,
358
456
  NarrationPaceMs: GetNarrationPaceMs(effectiveConfig) ?? undefined,
359
457
  ...(avatarStatus ? { AvatarStatus: avatarStatus } : {}),
458
+ MintSnapshot: toPersistedMintSnapshot(mintSnapshot, resolution.Model),
459
+ };
460
+ }
461
+ /** The full mint snapshot this instance keeps for a session: what a refresh needs to re-mint it or extend its relay. */
462
+ buildMintSnapshot(input, coAgentID, resolution, sessionParams, clientConfig) {
463
+ const sessionConfig = clientConfig.SessionConfig;
464
+ const relayTicketId = extractRelayTicketId(clientConfig.RelayUrl);
465
+ return {
466
+ coAgentID,
467
+ targetAgentID: input.TargetAgentID,
468
+ modelID: resolution.ModelID,
469
+ vendorID: resolution.VendorID,
470
+ modelVendorID: resolution.ModelVendorID,
471
+ driverClass: resolution.DriverClass ?? resolution.Model.constructor.name,
472
+ credentialScope: input.CredentialScope ?? 'Any',
473
+ ...(clientConfig.ConnectionMaxSeconds !== undefined ? { connectionMaxSeconds: clientConfig.ConnectionMaxSeconds } : {}),
474
+ ...(clientConfig.Transport === 'relay' ? { transport: 'relay' } : {}),
475
+ sessionParams,
476
+ ...(sessionConfig && typeof sessionConfig === 'object' && !Array.isArray(sessionConfig)
477
+ ? { existingSessionConfig: { ...sessionConfig } }
478
+ : {}),
479
+ ...(relayTicketId ? { relayTicketId } : {}),
480
+ ...(clientConfig.RelayUrl ? { relayUrl: clientConfig.RelayUrl } : {}),
481
+ };
482
+ }
483
+ /**
484
+ * Stamps `ConnectionMaxSeconds`, `SessionMaxSeconds`, `ReconnectBufferSeconds`, and
485
+ * `TrustNativeResumption` onto the typed `ClientRealtimeSessionConfig` fields using
486
+ * {@link ResolveRealtimeTiming} and {@link BaseRealtimeModel.ClientSessionTrustsNativeResumption}.
487
+ * Never writes framework keys into `clientConfig.SessionConfig`, so provider payloads remain clean.
488
+ */
489
+ stampClientConfigTiming(clientConfig, sessionParams, model) {
490
+ const timing = ResolveRealtimeTiming({
491
+ Config: sessionParams.Config,
492
+ DriverDefaultConnectionSeconds: clientConfig.ConnectionMaxSeconds ?? model.DefaultCallDurationSeconds,
493
+ DefaultTrustNativeResumption: clientConfig.TrustNativeResumption ??
494
+ model.ClientSessionTrustsNativeResumption(clientConfig.Transport ?? 'direct'),
495
+ });
496
+ if (timing.ConnectionMaxSeconds !== undefined) {
497
+ clientConfig.ConnectionMaxSeconds =
498
+ clientConfig.ConnectionMaxSeconds !== undefined
499
+ ? Math.min(clientConfig.ConnectionMaxSeconds, timing.ConnectionMaxSeconds)
500
+ : timing.ConnectionMaxSeconds;
501
+ }
502
+ if (timing.SessionMaxSeconds !== undefined && clientConfig.SessionMaxSeconds === undefined) {
503
+ clientConfig.SessionMaxSeconds = timing.SessionMaxSeconds;
504
+ }
505
+ if (clientConfig.ReconnectBufferSeconds === undefined) {
506
+ clientConfig.ReconnectBufferSeconds = timing.ReconnectBufferSeconds;
507
+ }
508
+ if (sessionParams.ZeroDataRetention === true) {
509
+ clientConfig.TrustNativeResumption = false;
510
+ }
511
+ else if (clientConfig.TrustNativeResumption === undefined) {
512
+ clientConfig.TrustNativeResumption = timing.TrustNativeResumption;
513
+ }
514
+ }
515
+ /**
516
+ * Refreshes the browser-facing credential for an active client-direct realtime session without
517
+ * re-running the companion prompt / memory / tool cascade.
518
+ *
519
+ * - If the session is a relay session whose ticket is still live in `RealtimeProxyRegistry`,
520
+ * extends the relay session in place (`ExtendRelaySession`) so existing forwarded resumption
521
+ * handles remain valid, and returns `Kind: 'relay'`.
522
+ * - Otherwise re-mints via `Model.RefreshClientSessionCredential(clampedParams, snapshot.existingSessionConfig)`
523
+ * using the mint snapshot from `RealtimeMintSnapshotRegistry` (falling back to the server-protected
524
+ * `realtimeMintSnapshot` on `MJ: AI Agent Sessions.Config_` for cross-instance failover of a direct session).
525
+ */
526
+ async RefreshClientSessionCredential(input, contextUser, provider) {
527
+ await this.configureEngine(contextUser, provider);
528
+ const sessionID = input.AgentSessionID?.trim();
529
+ if (!sessionID) {
530
+ return { Success: false, ErrorMessage: 'AgentSessionID is required to refresh a client realtime session credential.' };
531
+ }
532
+ const found = await this.findMintSnapshot(sessionID, input, contextUser, provider);
533
+ if (!found.Snapshot) {
534
+ return { Success: false, ErrorMessage: found.ErrorMessage };
535
+ }
536
+ const snapshot = found.Snapshot;
537
+ const clampedParams = {
538
+ ...snapshot.sessionParams,
539
+ ...(input.RemainingSessionSeconds !== undefined
540
+ ? {
541
+ MaxSessionSeconds: snapshot.sessionParams.MaxSessionSeconds !== undefined
542
+ ? Math.min(snapshot.sessionParams.MaxSessionSeconds, input.RemainingSessionSeconds)
543
+ : input.RemainingSessionSeconds,
544
+ }
545
+ : {}),
360
546
  };
547
+ if (snapshot.relayTicketId) {
548
+ const additionalSeconds = clampedParams.MaxSessionSeconds ?? REALTIME_RELAY_SESSION_LIFETIME_SECONDS;
549
+ const extended = RealtimeProxyRegistry.Instance.ExtendRelaySession(snapshot.relayTicketId, additionalSeconds, REALTIME_RELAY_MAX_CONNECTIONS, { AllowFreshReopen: input.AllowFreshReopen === true });
550
+ if (extended) {
551
+ // Stored again so the registry's TTL counts from this refresh: a relay session lives only here.
552
+ RealtimeMintSnapshotRegistry.Instance.Set(sessionID, snapshot);
553
+ const baseWs = ResolveRealtimeProxyBaseWsUrl(clampedParams);
554
+ const relayUrl = snapshot.relayUrl ?? BuildRealtimeRelayUrl(baseWs, snapshot.relayTicketId);
555
+ return {
556
+ Success: true,
557
+ Kind: 'relay',
558
+ Credential: {
559
+ Kind: 'relay',
560
+ ExpiresAt: extended.ExpiresAt,
561
+ RelayUrl: relayUrl,
562
+ },
563
+ ExpiresAt: extended.ExpiresAt,
564
+ RelayUrl: relayUrl,
565
+ };
566
+ }
567
+ }
568
+ const coAgent = this.resolveCoAgent({
569
+ CoAgent: input.CoAgent,
570
+ CoAgentID: input.CoAgentID ?? snapshot.coAgentID,
571
+ TargetAgentID: '',
572
+ AgentSessionID: sessionID,
573
+ });
574
+ if (!coAgent) {
575
+ return {
576
+ Success: false,
577
+ ErrorMessage: `Co-agent '${input.CoAgentID ?? snapshot.coAgentID ?? 'unknown'}' could not be resolved for credential refresh.`,
578
+ };
579
+ }
580
+ const resolution = await this.resolveModelFromSnapshot(snapshot, coAgent, input.APIKeys, contextUser);
581
+ if (!resolution) {
582
+ return {
583
+ Success: false,
584
+ ErrorMessage: `Could not resolve realtime model '${snapshot.modelID}' (${snapshot.driverClass}) for credential refresh.`,
585
+ };
586
+ }
587
+ try {
588
+ const clientConfig = await resolution.Model.RefreshClientSessionCredential(clampedParams, snapshot.existingSessionConfig);
589
+ this.stampClientConfigTiming(clientConfig, clampedParams, resolution.Model);
590
+ const newRelayTicketId = extractRelayTicketId(clientConfig.RelayUrl);
591
+ if (newRelayTicketId) {
592
+ snapshot.relayTicketId = newRelayTicketId;
593
+ snapshot.relayUrl = clientConfig.RelayUrl;
594
+ }
595
+ RealtimeMintSnapshotRegistry.Instance.Set(sessionID, snapshot);
596
+ const isRelay = clientConfig.Transport === 'relay' || Boolean(clientConfig.RelayUrl && !clientConfig.EphemeralToken);
597
+ const credential = isRelay
598
+ ? {
599
+ Kind: 'relay',
600
+ ExpiresAt: clientConfig.ExpiresAt,
601
+ RelayUrl: clientConfig.RelayUrl,
602
+ }
603
+ : {
604
+ Kind: 'token',
605
+ EphemeralToken: clientConfig.EphemeralToken,
606
+ ExpiresAt: clientConfig.ExpiresAt,
607
+ };
608
+ return {
609
+ Success: true,
610
+ Kind: credential.Kind,
611
+ Credential: credential,
612
+ EphemeralToken: clientConfig.EphemeralToken,
613
+ ExpiresAt: clientConfig.ExpiresAt,
614
+ RelayUrl: clientConfig.RelayUrl,
615
+ SessionConfigJson: JSON.stringify(clientConfig.SessionConfig),
616
+ ConnectionMaxSeconds: clientConfig.ConnectionMaxSeconds,
617
+ SessionMaxSeconds: clientConfig.SessionMaxSeconds,
618
+ ReconnectBufferSeconds: clientConfig.ReconnectBufferSeconds,
619
+ TrustNativeResumption: clientConfig.TrustNativeResumption,
620
+ };
621
+ }
622
+ catch (error) {
623
+ const message = error instanceof Error ? error.message : String(error);
624
+ return { Success: false, ErrorMessage: `Failed to refresh client realtime session credential: ${message}` };
625
+ }
626
+ }
627
+ async resolveModelFromSnapshot(snapshot, coAgent, apiKeys, contextUser) {
628
+ if (snapshot.credentialScope !== 'Any' && snapshot.credentialScope !== 'RuntimeOnly') {
629
+ LogError(`RealtimeClientSessionService.resolveModelFromSnapshot refused invalid credentialScope '${String(snapshot.credentialScope)}'.`);
630
+ return null;
631
+ }
632
+ const scope = snapshot.credentialScope;
633
+ const resolveRunKey = this.buildRunKeyResolver(apiKeys);
634
+ const platform = await this.resolvePlatformCredentials(scope, coAgent, snapshot.modelID, contextUser);
635
+ const resolveKey = this.buildKeyChain(resolveRunKey, scope, platform, snapshot.modelID);
636
+ const cachedModels = AIEngine.Instance.Models ?? [];
637
+ if (cachedModels.length > 0) {
638
+ const model = this.findModelByID(snapshot.modelID);
639
+ if (!model || !model.IsActive || !this.isRealtimeModel(model)) {
640
+ LogError(`RealtimeClientSessionService.resolveModelFromSnapshot refused inactive or non-realtime model '${snapshot.modelID}'.`);
641
+ return null;
642
+ }
643
+ const vendors = ListRealtimeVendorsForModel(model.ID);
644
+ if (vendors.length > 0) {
645
+ const matchedVendor = vendors.find((v) => v.DriverClass === snapshot.driverClass &&
646
+ (!snapshot.modelVendorID || UUIDsEqual(v.ModelVendorID, snapshot.modelVendorID)));
647
+ if (!matchedVendor) {
648
+ LogError(`RealtimeClientSessionService.resolveModelFromSnapshot refused driver '${snapshot.driverClass}' not bound to model '${model.Name}'.`);
649
+ return null;
650
+ }
651
+ return this.instantiateRealtimeVendor(model, matchedVendor, resolveKey);
652
+ }
653
+ const apiKey = resolveKey(snapshot.driverClass);
654
+ if (apiKey) {
655
+ const instance = this.createModelInstance(snapshot.driverClass, apiKey);
656
+ if (instance) {
657
+ return {
658
+ Model: instance,
659
+ ModelID: model.ID,
660
+ VendorID: snapshot.vendorID ?? '',
661
+ ModelVendorID: snapshot.modelVendorID,
662
+ APIName: snapshot.sessionParams.Model,
663
+ ModelName: model.Name,
664
+ DriverClass: snapshot.driverClass,
665
+ };
666
+ }
667
+ }
668
+ return null;
669
+ }
670
+ const apiKey = resolveKey(snapshot.driverClass);
671
+ if (apiKey) {
672
+ const instance = this.createModelInstance(snapshot.driverClass, apiKey);
673
+ if (instance) {
674
+ return {
675
+ Model: instance,
676
+ ModelID: snapshot.modelID,
677
+ VendorID: snapshot.vendorID ?? '',
678
+ ModelVendorID: snapshot.modelVendorID,
679
+ APIName: snapshot.sessionParams.Model,
680
+ DriverClass: snapshot.driverClass,
681
+ };
682
+ }
683
+ }
684
+ const fallback = await this.resolveRealtimeModel(coAgent, resolveRunKey, scope, false, platform);
685
+ if (fallback && (UUIDsEqual(fallback.ModelID, snapshot.modelID) || !fallback.DriverClass || fallback.DriverClass === snapshot.driverClass)) {
686
+ return fallback;
687
+ }
688
+ return null;
689
+ }
690
+ validatePersistedMintSnapshot(candidate, expectedCoAgentID) {
691
+ if (!candidate || typeof candidate !== 'object' || Array.isArray(candidate)) {
692
+ return null;
693
+ }
694
+ const parsed = candidate;
695
+ if (typeof parsed.modelID !== 'string' ||
696
+ parsed.modelID.trim().length === 0 ||
697
+ typeof parsed.driverClass !== 'string' ||
698
+ parsed.driverClass.trim().length === 0 ||
699
+ (parsed.credentialScope !== 'Any' && parsed.credentialScope !== 'RuntimeOnly') ||
700
+ !parsed.sessionParams ||
701
+ typeof parsed.sessionParams !== 'object' ||
702
+ Array.isArray(parsed.sessionParams) ||
703
+ typeof parsed.sessionParams.Model !== 'string') {
704
+ return null;
705
+ }
706
+ if (expectedCoAgentID &&
707
+ typeof parsed.coAgentID === 'string' &&
708
+ parsed.coAgentID.trim().length > 0 &&
709
+ !UUIDsEqual(parsed.coAgentID, expectedCoAgentID)) {
710
+ LogError(`RealtimeClientSessionService.validatePersistedMintSnapshot refused snapshot whose coAgentID '${parsed.coAgentID}' does not match session coAgentID '${expectedCoAgentID}'.`);
711
+ return null;
712
+ }
713
+ return {
714
+ coAgentID: typeof parsed.coAgentID === 'string' ? parsed.coAgentID : expectedCoAgentID,
715
+ ...(typeof parsed.targetAgentID === 'string' ? { targetAgentID: parsed.targetAgentID } : {}),
716
+ modelID: parsed.modelID,
717
+ vendorID: typeof parsed.vendorID === 'string' ? parsed.vendorID : undefined,
718
+ modelVendorID: typeof parsed.modelVendorID === 'string' ? parsed.modelVendorID : undefined,
719
+ driverClass: parsed.driverClass,
720
+ credentialScope: parsed.credentialScope,
721
+ ...(typeof parsed.connectionMaxSeconds === 'number' ? { connectionMaxSeconds: parsed.connectionMaxSeconds } : {}),
722
+ sessionParams: parsed.sessionParams,
723
+ ...(parsed.existingSessionConfig && typeof parsed.existingSessionConfig === 'object' && !Array.isArray(parsed.existingSessionConfig)
724
+ ? { existingSessionConfig: parsed.existingSessionConfig }
725
+ : {}),
726
+ };
727
+ }
728
+ /**
729
+ * The session's mint snapshot: this instance's copy, else the persisted copy (the one the caller passed, else the one
730
+ * read from the session row), validated and then kept here. A relay session's persisted copy holds no session params,
731
+ * so on any instance but the one that minted it the lookup fails with a reason the caller can show.
732
+ */
733
+ async findMintSnapshot(sessionID, input, contextUser, provider) {
734
+ const cached = RealtimeMintSnapshotRegistry.Instance.Get(sessionID);
735
+ if (cached) {
736
+ return { Snapshot: cached };
737
+ }
738
+ let snapshot = this.validatePersistedMintSnapshot(input.PersistedMintSnapshot, input.CoAgentID);
739
+ let relayCopy = isRelayMintSnapshot(input.PersistedMintSnapshot);
740
+ if (!snapshot && !relayCopy) {
741
+ const stored = await this.loadPersistedMintSnapshot(sessionID, contextUser, provider);
742
+ relayCopy = isRelayMintSnapshot(stored?.Snapshot);
743
+ snapshot = stored ? this.validatePersistedMintSnapshot(stored.Snapshot, input.CoAgentID ?? stored.AgentID) : null;
744
+ }
745
+ if (!snapshot) {
746
+ return {
747
+ ErrorMessage: relayCopy
748
+ ? `Realtime session '${sessionID}' is a relay session: only the MJAPI instance that minted it can refresh its credential.`
749
+ : `No valid mint snapshot found for realtime session '${sessionID}'.`,
750
+ };
751
+ }
752
+ RealtimeMintSnapshotRegistry.Instance.Set(sessionID, snapshot);
753
+ return { Snapshot: snapshot };
754
+ }
755
+ /** The `realtimeMintSnapshot` stored on the session row, not yet validated, with the row's co-agent; null when absent. */
756
+ async loadPersistedMintSnapshot(agentSessionID, contextUser, provider) {
757
+ try {
758
+ const session = await provider.GetEntityObject('MJ: AI Agent Sessions', contextUser);
759
+ if (!(await session.Load(agentSessionID)) || !session.Config_) {
760
+ return null;
761
+ }
762
+ const configObj = JSON.parse(session.Config_);
763
+ return { Snapshot: configObj['realtimeMintSnapshot'], AgentID: session.AgentID };
764
+ }
765
+ catch (error) {
766
+ LogError(`RealtimeClientSessionService.loadPersistedMintSnapshot failed: ${error instanceof Error ? error.message : String(error)}`);
767
+ return null;
768
+ }
361
769
  }
362
770
  /**
363
771
  * The call's avatar status once the driver has minted the session (see {@link ResolveRealtimeAvatarStatus}), with one
@@ -2998,6 +3406,7 @@ export class RealtimeClientSessionService {
2998
3406
  runParams.ContextUser = executingUser;
2999
3407
  runParams.Params = actionParams;
3000
3408
  runParams.Filters = [];
3409
+ runParams.Context = { AgentID: target.ID };
3001
3410
  let timerHandle;
3002
3411
  const timeoutPromise = new Promise((_, reject) => {
3003
3412
  timerHandle = setTimeout(() => {
@@ -3008,7 +3417,7 @@ export class RealtimeClientSessionService {
3008
3417
  }
3009
3418
  });
3010
3419
  const result = await Promise.race([
3011
- ActionEngineServer.Instance.RunAction(runParams),
3420
+ AgentUserPolicyEngine.Instance.RunWithExecutingAgentContext(target.ID, () => ActionEngineServer.Instance.RunAction(runParams)),
3012
3421
  timeoutPromise
3013
3422
  ]).finally(() => {
3014
3423
  if (timerHandle) {