@memberjunction/realtime-runtime 0.0.0 → 6.2.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.
@@ -0,0 +1,2585 @@
1
+ import { BehaviorSubject, Subject } from 'rxjs';
2
+ import { Metadata } from '@memberjunction/core';
3
+ import { UserInfoEngine } from '@memberjunction/core-entities';
4
+ import { AIEngineBase } from '@memberjunction/ai-engine-base';
5
+ import { MJGlobal } from '@memberjunction/global';
6
+ import { DEFAULT_REALTIME_AUDIO_TRACKS } from '@memberjunction/ai';
7
+ import { BaseRealtimeClient, LoadAssemblyAIRealtimeClient, LoadElevenLabsRealtimeClient, LoadGeminiRealtimeClient, LoadHuggingFaceRealtimeClient, LoadOpenAIRealtimeClient, LoadxAIRealtimeClient } from '@memberjunction/ai-realtime-client';
8
+ import { BuildNarrationInstructions } from '../narration/narration-template.js';
9
+ import { ParseDelegationResultJson, FormatToolName } from './delegation-result-parser.js';
10
+ import { BaseRealtimeChannelClient } from '../channels/base-realtime-channel-client.js';
11
+ /**
12
+ * `MJ: User Settings` key for the per-user "record this voice call" consent toggle. Stored as
13
+ * the literal string `'true'`/`'false'` (read with `=== 'true'`), cross-device via
14
+ * {@link UserInfoEngine}. The pre-call picker writes it; the session service reads it as the
15
+ * default when the caller doesn't pass an explicit consent value.
16
+ */
17
+ export const REALTIME_RECORDING_CONSENT_KEY = 'mj.realtimeVoice.recordingConsent.v1';
18
+ // Tree-shaking prevention: the OpenAI client is resolved dynamically through the
19
+ // ClassFactory (by the server-reported Provider key), so this static call is what keeps
20
+ // its @RegisterClass side effect from being eliminated by the bundler.
21
+ // NOTE: the interactive-channel plugins (resolved dynamically from the `MJ: AI Agent
22
+ // Channels` registry by ClientPluginClass key) get the same treatment, but their Load
23
+ // calls live in `conversations.module.ts` — plugins carry Angular surface COMPONENTS,
24
+ // and this service stays component-free (it must stay importable in plain-node tests).
25
+ LoadOpenAIRealtimeClient();
26
+ LoadGeminiRealtimeClient();
27
+ LoadElevenLabsRealtimeClient();
28
+ LoadAssemblyAIRealtimeClient();
29
+ LoadxAIRealtimeClient();
30
+ LoadHuggingFaceRealtimeClient();
31
+ /**
32
+ * Converts a {@link RealtimeTrackDescriptor} to its JSON form for the session-config bag.
33
+ *
34
+ * Every field's VALUE is already JSON-safe; the interface simply is not assignable to `JSONValue`
35
+ * because it declares no index signature and `UsageBasis` is `readonly`. Written out field by field
36
+ * rather than asserted, so adding a descriptor field is a compile error here instead of a field that
37
+ * silently stops reaching the driver.
38
+ */
39
+ function trackDescriptorToJSON(track) {
40
+ const json = { Modality: track.Modality, Direction: track.Direction };
41
+ if (track.Encoding !== undefined) {
42
+ json['Encoding'] = track.Encoding;
43
+ }
44
+ if (track.Rate !== undefined) {
45
+ json['Rate'] = track.Rate;
46
+ }
47
+ if (track.UsageBasis !== undefined) {
48
+ json['UsageBasis'] = [...track.UsageBasis];
49
+ }
50
+ if (track.RequiresConsent !== undefined) {
51
+ json['RequiresConsent'] = track.RequiresConsent;
52
+ }
53
+ return json;
54
+ }
55
+ /**
56
+ * Reads the `Direction:Modality` dedupe key off an already-JSON track entry, or `null` when the
57
+ * entry is not a track-shaped object. Used for tracks the mint supplied, which arrive as raw JSON.
58
+ */
59
+ function trackKeyFromJSON(raw) {
60
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {
61
+ return null;
62
+ }
63
+ const direction = raw['Direction'];
64
+ const modality = raw['Modality'];
65
+ if (typeof direction !== 'string' || typeof modality !== 'string') {
66
+ return null;
67
+ }
68
+ return `${direction}:${modality}`;
69
+ }
70
+ /**
71
+ * Drives a **client-direct** real-time voice session: the browser mints an ephemeral
72
+ * token from the MJ server, then connects DIRECTLY to the realtime provider. Audio
73
+ * frames never transit the MJ server (low latency); only tool calls and final
74
+ * transcripts are relayed back to MJ over GraphQL.
75
+ *
76
+ * This service is PROVIDER-AGNOSTIC policy/orchestration. All provider wire concerns
77
+ * (transport, event translation, the response state machine, narration-kind tagging,
78
+ * playback tracking) live in a {@link BaseRealtimeClient} driver resolved through the
79
+ * MJ ClassFactory by the server-reported `Provider` key (e.g. `'openai'` →
80
+ * `OpenAIRealtimeClient`). Future providers (Gemini Live, …) snap in by registering a
81
+ * new driver — this service does not change.
82
+ *
83
+ * The Realtime Co-Agent (server-side) fronts the conversation's current agent — the server
84
+ * bakes the companion instructions + tool set into `SessionConfigJson`, which the client
85
+ * driver applies verbatim.
86
+ *
87
+ * Lifecycle: {@link StartRealtimeSession} → live duplex → {@link EndRealtimeSession}. A start is
88
+ * two halves — MINT (the `StartRealtimeClientSession` mutation) and RUN (everything above) — and a
89
+ * host that must mint through its own server surface enters at the second half via
90
+ * {@link StartRealtimeSessionFromResult}; there is one implementation of the run half either way.
91
+ */
92
+ export class RealtimeSessionRuntime {
93
+ /**
94
+ * @param mediaHost the platform's media capabilities. The runtime never touches `navigator`,
95
+ * `Blob` or `FileReader` itself — microphone acquisition and audio recording
96
+ * are the host's, because both are platform-specific product decisions
97
+ * (permission UX, container format, where the bytes live).
98
+ */
99
+ constructor(mediaHost) {
100
+ this.mediaHost = mediaHost;
101
+ // ── Reactive UI state ──────────────────────────────────────────────────────
102
+ this._connectionState$ = new BehaviorSubject('closed');
103
+ this._captions$ = new BehaviorSubject([]);
104
+ this._active$ = new BehaviorSubject(false);
105
+ this._delegationProgress$ = new Subject();
106
+ this._delegationResult$ = new Subject();
107
+ this._delegationNarration$ = new Subject();
108
+ this._thoughtNarration$ = new Subject();
109
+ this._agentName$ = new BehaviorSubject('Sage');
110
+ this._modelName$ = new BehaviorSubject(null);
111
+ this._minimized$ = new BehaviorSubject(false);
112
+ this._activeChannels$ = new BehaviorSubject([]);
113
+ this._channelFocus$ = new Subject();
114
+ // ─── Generic session-lifecycle events (consumed by RealtimeSessionsAdapter to
115
+ // bridge into @memberjunction/conversations-runtime's framework-agnostic
116
+ // SessionsObserver). Why not derive from Active$ + agentSessionId? Because
117
+ // Active$ flips true before mintSession resolves and sets agentSessionId —
118
+ // a naive Active$ subscription would emit session-started with sessionId === null.
119
+ // Emitting explicitly avoids the race entirely. ───
120
+ this._sessionStarted$ = new Subject();
121
+ this._sessionEnded$ = new Subject();
122
+ this._channelActivity$ = new Subject();
123
+ /** Current connection / turn state. */
124
+ this.ConnectionState$ = this._connectionState$.asObservable();
125
+ /** Live captions for both sides of the conversation. */
126
+ this.Captions$ = this._captions$.asObservable();
127
+ /** True while a session is open (mic button active, overlay shown). */
128
+ this.Active$ = this._active$.asObservable();
129
+ /**
130
+ * Progress updates from a delegated agent run (e.g. Sage) while the realtime model waits on it.
131
+ * The future overlay subscribes to render a "working" card; the model also narrates these aloud.
132
+ */
133
+ this.DelegationProgress$ = this._delegationProgress$.asObservable();
134
+ /** Terminal result of a delegation, so the overlay can complete the working card with real content. */
135
+ this.DelegationResult$ = this._delegationResult$.asObservable();
136
+ /**
137
+ * EPHEMERAL spoken progress narrations (see {@link RealtimeDelegationNarration}). These are
138
+ * deliberately kept OUT of {@link Captions$} and never relayed/persisted — the overlay
139
+ * renders them as a transient "live note" near the active working card.
140
+ */
141
+ this.DelegationNarration$ = this._delegationNarration$.asObservable();
142
+ /**
143
+ * Model-authored thought / reasoning narrations (see {@link RealtimeThoughtNarration}). These are
144
+ * reasoning summaries author-emitted during extended thinking, separate from spoken progress updates.
145
+ */
146
+ this.ThoughtNarration$ = this._thoughtNarration$.asObservable();
147
+ /** Display name of the agent the active session fronts (set at session start). */
148
+ this.AgentName$ = this._agentName$.asObservable();
149
+ /**
150
+ * Display name of the realtime MODEL the active session runs on (server-reported at session
151
+ * start, e.g. "GPT Realtime 2"). `null` before a session starts / when the server didn't report
152
+ * one. The overlay banner shows it subtly next to the agent identity.
153
+ */
154
+ this.ModelName$ = this._modelName$.asObservable();
155
+ /**
156
+ * True while the active call overlay is MINIMIZED to the host's floating "on call" pill
157
+ * (e.g. after a dev link navigated away). The mic and session stay fully live — this is
158
+ * pure presentation state, reset to `false` at session start and teardown.
159
+ */
160
+ this.Minimized$ = this._minimized$.asObservable();
161
+ /**
162
+ * The session's ACTIVE interactive-channel plugins, resolved from the `MJ: AI Agent
163
+ * Channels` registry at session start (one instance per session, per channel). Emits
164
+ * `[]` before a session starts and after teardown. The overlay subscribes to register
165
+ * one surface tab per plugin — it never knows any concrete channel type.
166
+ */
167
+ this.ActiveChannels$ = this._activeChannels$.asObservable();
168
+ /**
169
+ * Channel requests to enter / leave the FOCUS layout (see
170
+ * {@link RealtimeChannelFocusEvent}). Fired when a plugin calls its host context's
171
+ * `SetFocusMode` — e.g. the whiteboard's "Focus board" toggle.
172
+ */
173
+ this.ChannelFocus$ = this._channelFocus$.asObservable();
174
+ /**
175
+ * Fired EXACTLY ONCE per session after both `agentSessionId` is set AND the
176
+ * realtime client is connected. Carries the server-issued `sessionId` and the
177
+ * `ChannelName` of each plugin resolved at session mint. Consumed by
178
+ * `RealtimeSessionsAdapter` (in this package) to feed
179
+ * `@memberjunction/conversations-runtime`'s `SessionsObserver`.
180
+ *
181
+ * **Why this exists separately from `Active$`:** `Active$` flips `true` BEFORE
182
+ * `mintSession` resolves, so `agentSessionId` is still `null` at that moment.
183
+ * Subscribers correlating `(Active$, agentSessionId)` would race; this event
184
+ * removes the race.
185
+ */
186
+ this.SessionStarted$ = this._sessionStarted$.asObservable();
187
+ /**
188
+ * Fired EXACTLY ONCE per session as teardown begins, with the prior
189
+ * `agentSessionId` (so subscribers can correlate against `SessionStarted$`'s
190
+ * sessionId) and the client-distinguishable reason — `'explicit'` when the
191
+ * user called `EndRealtimeSession`, `'error'` when teardown ran from a catch
192
+ * block. Server-side close paths (janitor, shutdown) do NOT propagate here —
193
+ * they happen out-of-process and have no client push channel today.
194
+ */
195
+ this.SessionEnded$ = this._sessionEnded$.asObservable();
196
+ /**
197
+ * Fires with the channel PLUGIN every time the agent ACTS on that channel (a tool call
198
+ * was routed to its local executor — e.g. the agent drew on the whiteboard). The overlay
199
+ * uses the FIRST emission per channel to auto-reveal + focus the channel's surface tab,
200
+ * so the user discovers the surface the moment the agent starts using it. Finer-grained
201
+ * than {@link SessionStarted$}/{@link SessionEnded$} (per tool call, not per session).
202
+ */
203
+ this.ChannelActivity$ = this._channelActivity$.asObservable();
204
+ /**
205
+ * ID of the active server-side agent session (`MJ: AI Agent Sessions`), or `null` when no
206
+ * session is open / the session hasn't been minted yet. Powers the overlay's gear-gated
207
+ * "Open session" dev link.
208
+ */
209
+ /** Conversation id the SERVER created for this session (null when the host supplied one). */
210
+ this.createdConversationId = null;
211
+ /** The session's conversation id (supplied or server-created). */
212
+ this.sessionConversationId = null;
213
+ /** First final user utterance of the live session (the naming seed). */
214
+ this.firstUserTranscript = null;
215
+ /** Buffer accumulating streaming user interim deltas into a single in-progress bubble. */
216
+ this.pendingUserCaption = '';
217
+ /** Whether an in-place interim user caption is currently placed in `_captions$`. */
218
+ this.hasActiveInterimUserCaption = false;
219
+ // ── Session internals ──────────────────────────────────────────────────────
220
+ /** The provider-direct realtime client driving the live session (ClassFactory-resolved). */
221
+ this.client = null;
222
+ /** The mic capture stream — acquired here (permission UX) and handed to the client. */
223
+ this.localStream = null;
224
+ this.agentSessionId = null;
225
+ /**
226
+ * The application the active session runs in (sources the server-side app config cascade +
227
+ * RelevantAgents → allowed-agent union, and the default-agent chain). `null` when no app context
228
+ * was supplied. Set at {@link StartRealtimeSession}; sent to the mint mutation.
229
+ */
230
+ this.applicationId = null;
231
+ /**
232
+ * The live app-context snapshot (where the user is, what they see, the capability manifest),
233
+ * pushed by the host (Explorer) at session start and on subsequent changes via
234
+ * {@link UpdateAppContext}. The headless {@link import('../components/realtime/channels/client-context-channel').ClientContextChannel}
235
+ * subscribes to {@link AppContext$} and streams deltas to the model via `SendContextNote`.
236
+ */
237
+ this._appContext$ = new BehaviorSubject(null);
238
+ /** Observable of the live app-context snapshot (see {@link _appContext$}). */
239
+ this.AppContext$ = this._appContext$.asObservable();
240
+ /**
241
+ * The DB-driven narration instruction template (server-resolved at session start, containing a
242
+ * `{{ progressMessage }}` placeholder). `null` when the deployment hasn't synced the narration
243
+ * prompt — {@link buildNarrationInstructions} then falls back to the built-in wording.
244
+ */
245
+ this.narrationTemplate = null;
246
+ // ── Browser-side call recording ────────────────────────────────────────────
247
+ /**
248
+ * The active session's audio recorder (mic + agent mix), or `null` when the user didn't
249
+ * consent or the browser can't record. Created after the client connects; stopped + uploaded
250
+ * at teardown.
251
+ */
252
+ this.recorder = null;
253
+ /** ISO timestamp of when recording started — sent to the server on session start. */
254
+ this.recordingStartedAtIso = null;
255
+ /** Interval that flushes ~15s crash-recovery shards to the server during a recording. */
256
+ this.segmentTimer = null;
257
+ /** 0-based index of the next recording shard to upload. */
258
+ this.segmentIndex = 0;
259
+ // ── Server-side liveness ───────────────────────────────────────────────────
260
+ /**
261
+ * Interval that tells the server this session is still in use, or `null` when no session is
262
+ * running. See {@link startLivenessPulse} for why the server cannot work this out itself.
263
+ */
264
+ this.livenessTimer = null;
265
+ /**
266
+ * Recording-relative ms offset at which the IN-FLIGHT (not-yet-finalized) turn's audio
267
+ * actually BEGAN — captured the moment that turn's audio/text starts flowing (its first
268
+ * interim transcript), NOT inherited from the previous turn's end. `null` before the first
269
+ * turn / between turns (until the next turn's audio starts). Sent as `utteranceStartMs` on
270
+ * the turn's final transcript so per-turn timing lines up with the recording even when a
271
+ * tool-call / silence gap sits between turns (the inherit-previous-end model mis-stamped
272
+ * the post-gap turn at the pre-gap offset). See {@link markTurnAudioStart}.
273
+ */
274
+ this.currentTurnStartMs = null;
275
+ /**
276
+ * Wall-anchor of the SESSION clock (#3832): `performance.now()` at the moment the call went
277
+ * live, or `null` before any call has. Read only through {@link nowTurnOffsetMs}.
278
+ */
279
+ this.sessionClockStartMs = null;
280
+ /**
281
+ * Per-turn guard for {@link markTurnAudioStart}: `true` once the in-flight turn's audio-start
282
+ * offset has been captured, so mid-turn interim deltas don't overwrite it. Reset to `false`
283
+ * at each finalization so the NEXT turn re-stamps from where ITS audio begins.
284
+ */
285
+ this.turnAudioStartCaptured = false;
286
+ /**
287
+ * Aggregation buffer: distinct progress messages since the last spoken update (oldest
288
+ * first, capped at {@link RealtimeSessionRuntime.MaxDigestMessages}). A flood of small
289
+ * updates becomes ONE digest; the buffer is discarded when the result lands first.
290
+ */
291
+ this.pendingNarrationMessages = [];
292
+ /**
293
+ * Tool calls currently executing on the server. Progress events ride PubSub and can
294
+ * lag the (fast) mutation result — any progress for a call NOT in this set is stale
295
+ * (already completed) and is dropped, so we never narrate "starting up" after the
296
+ * answer was already spoken.
297
+ */
298
+ this.inFlightCallIds = new Set();
299
+ /** Timer for the deferred narration; cancelled when the delegation result lands first. */
300
+ this.narrationTimer = null;
301
+ /**
302
+ * Call ids the USER explicitly cancelled via {@link CancelDelegation} /
303
+ * {@link CancelInFlightDelegations}. Their cards were already flipped to the
304
+ * "Cancelled by user" failed result, so when the original tool mutation later resolves
305
+ * with the aborted run's outcome, {@link emitDelegationResult} skips the duplicate card
306
+ * emission (the model still receives the tool result). Cleared at teardown.
307
+ */
308
+ this.cancelledCallIds = new Set();
309
+ /** Accumulated input-token delta since the last flush. */
310
+ this.pendingUsageInput = 0;
311
+ /** Accumulated output-token delta since the last flush. */
312
+ this.pendingUsageOutput = 0;
313
+ /** Pending debounced usage flush; also force-flushed at teardown. */
314
+ this.usageFlushTimer = null;
315
+ /** Active push-status subscription that feeds delegation progress; cleared on teardown. */
316
+ this.delegationProgressSub = null;
317
+ /** Timestamp (ms) of the last narration we triggered; 0 = never. */
318
+ this.lastDelegationNarrationAt = 0;
319
+ /** When the current delegation burst began (first in-flight call); anchors the 5s first update. */
320
+ this.delegationBurstStartedAt = 0;
321
+ /** Spoken updates so far in this burst (1-based numbering for the instructions). */
322
+ this.narrationCount = 0;
323
+ /** What the model actually SAID for prior updates this burst — chained in so it never repeats itself. */
324
+ this.spokenNarrations = [];
325
+ /** Tail message of the last digest, so an identical trailing progress event isn't re-buffered. */
326
+ this.lastNarratedTail = '';
327
+ /**
328
+ * Registry of CLIENT-EXECUTED UI tool handlers, keyed by tool-name prefix (e.g.
329
+ * `'Whiteboard_'`). Tool calls whose name matches a registered prefix run LOCALLY through the
330
+ * handler (never relayed to the server); everything else takes the standard server-relay path.
331
+ * Cleared at teardown.
332
+ */
333
+ this.clientToolHandlers = new Map();
334
+ /**
335
+ * Monotonic id for the current start attempt, bumped by every {@link teardown}.
336
+ *
337
+ * A session start is a multi-await sequence — mint, acquire the microphone, connect — and a host
338
+ * can end the session part-way through it (the user taps back while the mint is still in flight).
339
+ * Teardown at that moment has nothing to tear down: the stream and the client do not exist yet.
340
+ * Without this, the in-flight start then proceeds to open a microphone and a provider connection
341
+ * nobody is watching. Each start captures the generation it began under and abandons itself the
342
+ * moment it no longer matches.
343
+ */
344
+ this.startGeneration = 0;
345
+ /**
346
+ * The teardown currently running, so a second call awaits it rather than racing it.
347
+ *
348
+ * Ending a session commonly fires twice — an explicit stop followed by the host unmounting — and
349
+ * `teardown` flips `_active$` only at the end, so the second call passes the `IsActive` guard and
350
+ * runs concurrently with the first: two `Disconnect()` calls, two `CloseAgentSession` mutations,
351
+ * two `SessionEnded$` emissions for one session.
352
+ */
353
+ this.teardownInFlight = null;
354
+ /**
355
+ * Why the last session start failed, or `null` when none has.
356
+ *
357
+ * The runtime reports failure as `'error'` on {@link ConnectionState$}, which is enough to show
358
+ * *that* something went wrong but not *what* — and the difference matters at exactly one point:
359
+ * microphone permission. A host that cannot tell "you denied the mic" from "the provider is
360
+ * down" has to show the same unhelpful copy for both. `AcquireMicrophone` rejects inside the
361
+ * runtime's own try/catch, so the host never sees that rejection itself.
362
+ */
363
+ this.lastStartError = null;
364
+ /**
365
+ * Pending DEBOUNCED channel-state saves, keyed by channel name. Each entry keeps the
366
+ * LATEST serialized state plus the session id captured while the session was live —
367
+ * the teardown flush runs as the live id is being torn down, so the capture guarantees
368
+ * the final save still lands on the just-closed session.
369
+ */
370
+ this.pendingChannelSaves = new Map();
371
+ /**
372
+ * `ChannelName`s the agent has ACTED ON at least once this session (the channel's first
373
+ * tool call routed to its local executor). The overlay reads this to decide which channel
374
+ * surface tabs to register: a channel earns its tab only once it's been used (the
375
+ * whiteboard is the sole exception — it tabs immediately, since a user may draw first).
376
+ * Reset at session start via {@link resetState}.
377
+ */
378
+ this.usedChannelNames = new Set();
379
+ this._provider = null;
380
+ /**
381
+ * Host registry of surface CLIENT TOOLS (Name → handler), fed by the host (Explorer) from the
382
+ * active surface's `SetAgentClientTools`. The headless ClientContextChannel's `ContextTool` proxy
383
+ * executes against this via {@link executeAppClientTool}. Keys are lower-cased for case-insensitive
384
+ * model-supplied action names.
385
+ */
386
+ this.appClientToolHandlers = new Map();
387
+ }
388
+ /** Synchronous access to the session's active interactive-channel plugins. */
389
+ get ActiveChannels() {
390
+ return this._activeChannels$.value;
391
+ }
392
+ /**
393
+ * The `ChannelName`s the agent has used (acted on) at least once this session. The overlay
394
+ * uses this to register a channel's surface tab only after it has come into play. A fresh
395
+ * Set snapshot so callers can't mutate the service's tracking.
396
+ */
397
+ get UsedChannelNames() {
398
+ return new Set(this.usedChannelNames);
399
+ }
400
+ /** Whether the agent has used (acted on) the named channel at least once this session. */
401
+ HasChannelBeenUsed(channelName) {
402
+ return this.usedChannelNames.has(channelName);
403
+ }
404
+ /** Synchronous access to the display name of the agent the active session fronts. */
405
+ get CurrentAgentName() {
406
+ return this._agentName$.value;
407
+ }
408
+ /**
409
+ * When the active/last session CREATED its conversation (started without one), the new
410
+ * conversation's id — the host uses it to refresh the cached list, conditionally select
411
+ * it on close, and auto-name it. Null when the session joined an existing conversation.
412
+ */
413
+ get SessionCreatedConversationId() {
414
+ return this.createdConversationId;
415
+ }
416
+ /** The first final user utterance of the session (naming seed); null before the user speaks. */
417
+ get FirstUserTranscript() {
418
+ return this.firstUserTranscript;
419
+ }
420
+ get CurrentAgentSessionId() {
421
+ return this.agentSessionId;
422
+ }
423
+ /** Synchronous access to the minimized presentation state. */
424
+ get IsMinimized() {
425
+ return this._minimized$.value;
426
+ }
427
+ /**
428
+ * Minimizes / restores the active call overlay (host renders the floating pill while
429
+ * minimized). Presentation-only — the live audio session is untouched.
430
+ */
431
+ SetMinimized(minimized) {
432
+ if (this._minimized$.value !== minimized) {
433
+ this._minimized$.next(minimized);
434
+ }
435
+ }
436
+ /**
437
+ * Push an updated app-context snapshot mid-session (the continuous-streaming half of client-context
438
+ * delivery). The host (Explorer) calls this when the user navigates / the active surface's state or
439
+ * capability manifest changes; the ClientContextChannel turns the delta into a `SendContextNote`.
440
+ * No-op semantics when no session is live — the channel simply re-reads on next start.
441
+ *
442
+ * @param snapshot The latest app-context snapshot (or null to clear).
443
+ */
444
+ UpdateAppContext(snapshot) {
445
+ this._appContext$.next(snapshot);
446
+ }
447
+ /** How often crash-recovery shards are flushed during a recording. */
448
+ static { this.SegmentFlushMs = 15000; }
449
+ /**
450
+ * How often the client asserts liveness. Comfortably under `SessionJanitor`'s
451
+ * `closeThresholdMinutes` (15 by default) so several pulses must be missed in a row before a
452
+ * live session is reaped, and well above `SessionManager`'s heartbeat write-coalescing window
453
+ * so the DB sees at most a trickle of writes per session.
454
+ */
455
+ static { this.LivenessPulseMs = 60000; }
456
+ // ── Delegated-run progress streaming ───────────────────────────────────────
457
+ /** First spoken update fires no earlier than this long after delegated work starts. */
458
+ static { this.FirstNarrationDelayMs = 5000; }
459
+ /** Minimum gap between SUBSEQUENT spoken updates (the 7–10s band; floods aggregate). */
460
+ static { this.NarrationIntervalMs = 8000; }
461
+ /** Retry delay when the fire moment finds the model busy / audio still playing. */
462
+ static { this.NarrationBusyRetryMs = 1500; }
463
+ /** Max progress messages aggregated into one spoken digest. */
464
+ static { this.MaxDigestMessages = 4; }
465
+ /** Max prior spoken narrations chained into the instructions (anti-repetition). */
466
+ static { this.MaxPriorNarrations = 3; }
467
+ // ── Usage telemetry relay (B7) ─────────────────────────────────────────────
468
+ /** Debounce window for relaying accumulated usage deltas to the server. */
469
+ static { this.UsageFlushDebounceMs = 10000; }
470
+ // ── Interactive channels (registry-resolved plugins) ───────────────────────
471
+ /** Debounce window for persisting a channel's state of record after a change burst. */
472
+ static { this.ChannelSaveDebounceMs = 3000; }
473
+ /**
474
+ * Metadata provider used for the GraphQL relay mutations. Falls back to the
475
+ * global default when unset (single-provider apps see no change).
476
+ */
477
+ get Provider() {
478
+ return this._provider ?? Metadata.Provider;
479
+ }
480
+ set Provider(value) {
481
+ this._provider = value;
482
+ }
483
+ /** True when a session is currently open. */
484
+ get IsActive() {
485
+ return this._active$.value;
486
+ }
487
+ /**
488
+ * Start a client-direct voice session fronting `targetAgentId`.
489
+ *
490
+ * @param targetAgentId The agent the Realtime Co-Agent voices on behalf of.
491
+ * @param conversationId Optional existing conversation to bind + seed context from.
492
+ * @param lastSessionId Optional prior session to chain to (resume / continuation).
493
+ * @param agentName Optional display name of the target agent — resolved by the caller
494
+ * (which knows the conversation's routing context) and surfaced on {@link AgentName$}
495
+ * so ANY host (composer trigger, chat-area overlay) can render it without re-resolving.
496
+ * @param preferredModelId Optional EXPLICIT realtime model choice (`MJ: AI Models.ID`). When
497
+ * set, the server uses exactly that model and FAILS with a clear reason if it can't (no
498
+ * silent fallback). Omit for the server's automatic (highest-PowerRank) selection.
499
+ * @param clientTools Optional EXTRA client-executed UI tool declarations to expose to the
500
+ * realtime model alongside the server's stable tool set and the interactive-channel
501
+ * tools (which are aggregated automatically from the registry-resolved plugins — see
502
+ * {@link ActiveChannels$}). The server only DECLARES these — execution stays in the
503
+ * browser via handlers registered with {@link RegisterClientToolHandler}. This is an
504
+ * extension point for hosts with bespoke (non-channel) UI tools; most callers omit it.
505
+ * @param coAgentId Optional EXPLICIT co-agent choice (`MJ: AI Agents.ID` of an Active,
506
+ * Realtime-type agent) — the highest-precedence step of the server's co-agent resolution
507
+ * chain. When set, the server uses exactly that co-agent and FAILS with a clear reason if
508
+ * it can't (no silent fallback). Omit to let server metadata drive the choice: the target
509
+ * agent's `DefaultCoAgentID`, then the type-level `AIAgentCoAgent` default row, then the global Realtime Co-Agent.
510
+ * @param configOverridesJson Optional JSON payload of SESSION CONFIG overrides (e.g.
511
+ * `{"realtime":{"modelPreference":"<modelId>"}}`), forwarded verbatim on the mint
512
+ * mutation. The server enforces the `Realtime: Advanced Session Controls`
513
+ * authorization on any overrides — hosts only populate this from authorization-gated
514
+ * pickers, and never synthesize overrides beyond what the user explicitly chose.
515
+ * Omit/`null` for the server's defaults (today's behavior).
516
+ * @param recordingConsent Optional EXPLICIT "record this call" consent for THIS session. When
517
+ * `true`, the browser records a mic + agent-audio mix and uploads it at session end. When
518
+ * omitted/`null`, the per-user persisted preference (`mj.realtimeVoice.recordingConsent.v1`
519
+ * via {@link UserInfoEngine}) is read as the default. `false` never records.
520
+ * @param mediaCollectionId Optional per-session media-kit override (`MJ: Collections.ID`). When set,
521
+ * the server-side Media channel resolves THIS collection as the agent's media kit for the session,
522
+ * taking precedence over the agent's `DefaultMediaCollectionID`. The server UUID-validates it
523
+ * (malformed ⇒ ignored, the agent default applies). Omit/`null` to use the agent default kit.
524
+ */
525
+ async StartRealtimeSession(targetAgentId, conversationId, lastSessionId, agentName, preferredModelId, clientTools, coAgentId, configOverridesJson, recordingConsent, mediaCollectionId, applicationId, appContext) {
526
+ if (this.IsActive) {
527
+ return; // a session is already running — ignore duplicate starts
528
+ }
529
+ const consent = this.beginSessionStart({ agentName, recordingConsent, applicationId, appContext });
530
+ // Captured BEFORE startChannels so the mint carries exactly the snapshot the prologue
531
+ // resolved, whatever a channel plugin may push in the meantime.
532
+ const effectiveAppContext = this._appContext$.value;
533
+ let session;
534
+ try {
535
+ // Resolve + initialize the interactive-channel plugins FIRST: their client-executed
536
+ // tool sets must be declared to the realtime model at session mint.
537
+ const allClientTools = [...(clientTools ?? []), ...(await this.startChannels())];
538
+ session = await this.mintSession(targetAgentId, conversationId, lastSessionId, preferredModelId, allClientTools, coAgentId, configOverridesJson, consent, this.recordingStartedAtIso, mediaCollectionId, this.applicationId, effectiveAppContext);
539
+ }
540
+ catch (error) {
541
+ await this.failSessionStart(error);
542
+ return;
543
+ }
544
+ if (!this.hostCanUseProvider(session.Provider)) {
545
+ await this.abortUnusableSession(session);
546
+ return;
547
+ }
548
+ await this.runMintedSession(session, conversationId ?? null, consent);
549
+ }
550
+ /**
551
+ * Declares which provider keys this host can actually carry audio for.
552
+ *
553
+ * The server resolves a realtime model by rank across every configured vendor, so it can
554
+ * legitimately return a provider whose client driver this host cannot run. A browser can run all
555
+ * of them; React Native can run the WebRTC ones but not those needing a Web Audio PCM plane.
556
+ * Connecting anyway gets as far as constructing the driver's playback engine and then throws —
557
+ * a crash, where the honest answer is "this workspace's voice provider is not one this app can
558
+ * use".
559
+ *
560
+ * The default accepts everything, so existing hosts are unaffected. Override to narrow it.
561
+ *
562
+ * @param provider The `Provider` key the server stamped on the minted session.
563
+ */
564
+ hostCanUseProvider(_provider) {
565
+ return true;
566
+ }
567
+ /**
568
+ * Closes a session that was minted but will never be connected, and reports why.
569
+ *
570
+ * Minting creates a durable `MJ: AI Agent Sessions` row server-side, so declining to connect
571
+ * still has to close it — otherwise every rejected attempt leaks an `Active` session for the
572
+ * janitor to reconcile fifteen minutes later.
573
+ */
574
+ async abortUnusableSession(session) {
575
+ const reason = `[RealtimeSession] This host cannot carry provider '${session.Provider}' ` +
576
+ `(model '${session.ModelName ?? session.Model}'); closing the minted session without connecting.`;
577
+ console.error(reason);
578
+ this.lastStartError = new Error(reason);
579
+ // Adopt the session id so the shared teardown closes it — and so this path unwinds through
580
+ // exactly one implementation. The prologue has already initialized the channel plugins and
581
+ // published them on ActiveChannels$; skipping teardown would leave them undisposed, their tool
582
+ // handlers registered, and their subscriptions live until the next start replaced them.
583
+ this.agentSessionId = session.AgentSessionId ?? this.agentSessionId;
584
+ this._connectionState$.next('error');
585
+ await this.teardown(true);
586
+ }
587
+ /**
588
+ * Run a session the HOST has already minted itself — the second half of
589
+ * {@link StartRealtimeSession}, without the `StartRealtimeClientSession` mutation.
590
+ *
591
+ * For hosts that must mint through their own server surface because they attach per-session
592
+ * context the stock mutation cannot carry (e.g. an interview persona baked into the companion
593
+ * prompt). They call their own mutation, shape the reply into a
594
+ * {@link StartRealtimeClientSessionResult}, and hand it here: driver resolution, the ephemeral-token
595
+ * connect, tool/transcript relays, recording, connection state and teardown are all identical to
596
+ * the all-in-one path — there is exactly one implementation of the run half.
597
+ *
598
+ * NOTE: the interactive-channel plugins are NOT started on this path. Their tool sets must be
599
+ * declared to the model AT MINT, which happened on the host's side — so a host that wants channels
600
+ * owns that half too.
601
+ *
602
+ * @param result The minted session — the same ten fields the `StartRealtimeClientSession`
603
+ * mutation returns. `EphemeralToken` and `Provider` are what actually open the call.
604
+ * @param options Host-side inputs the result cannot carry; see {@link RealtimeSessionRunOptions}.
605
+ * Every field defaults exactly as its {@link StartRealtimeSession} counterpart does.
606
+ */
607
+ async StartRealtimeSessionFromResult(result, options) {
608
+ if (this.IsActive) {
609
+ return; // a session is already running — ignore duplicate starts
610
+ }
611
+ const effectiveOptions = options ?? {};
612
+ if (!this.hostCanUseProvider(result.Provider)) {
613
+ await this.abortUnusableSession(result);
614
+ return;
615
+ }
616
+ const consent = this.beginSessionStart(effectiveOptions);
617
+ await this.runMintedSession(result, effectiveOptions.conversationId ?? null, consent);
618
+ }
619
+ /**
620
+ * Start prologue shared by both entry points: bind the app layer, publish the agent name, reset
621
+ * per-session state, and flip the session live (which is ALSO what makes the `IsActive` guard
622
+ * suppress duplicate starts while the mint is still in flight — hence it runs before minting, not
623
+ * after). Returns the resolved recording consent, which the mint half reports to the server and
624
+ * the run half uses to decide whether to record.
625
+ */
626
+ beginSessionStart(options) {
627
+ // App awareness (Move 1/3/4): the application the session runs in (sources the app config
628
+ // cascade + RelevantAgents → allowed-agent union) and the live app-context snapshot injected
629
+ // into the companion prompt at mint. Stored so the ClientContextChannel can stream subsequent
630
+ // deltas. Absent ⇒ no app layer / no mint-time context (the pre-app behavior).
631
+ this.applicationId = options.applicationId ?? null;
632
+ // Prefer the explicit param, but fall back to the snapshot the host has ALREADY pushed via
633
+ // UpdateAppContext (explorer-app streams the live snapshot continuously). The overlay's
634
+ // [appContext] binding can still read null at the instant the mic is clicked — without this
635
+ // fallback, StartRealtimeSession(null) would clobber a perfectly good snapshot and mint the
636
+ // companion prompt with no app context (no NavigableApps / no tool schemas → the co-agent guesses
637
+ // parameter names and navigation fails). Never overwrite a good value with null.
638
+ this._appContext$.next(options.appContext ?? this._appContext$.value);
639
+ if (options.agentName) {
640
+ this._agentName$.next(options.agentName);
641
+ }
642
+ this.resetState();
643
+ this._active$.next(true);
644
+ this._connectionState$.next('connecting');
645
+ // Resolve recording consent for this session: explicit value wins, else the per-user
646
+ // persisted preference. Computed before mint so it can be reported to the server.
647
+ const consent = options.recordingConsent ?? this.readPersistedRecordingConsent();
648
+ this.recordingStartedAtIso = consent ? new Date().toISOString() : null;
649
+ return consent;
650
+ }
651
+ /**
652
+ * The RUN half of a session start, shared by both entry points: consume the minted result, open
653
+ * the provider connection, and go live. `inputConversationId` is the conversation the START asked
654
+ * for (null ⇒ "server, make me one") — the result alone can't distinguish the two.
655
+ */
656
+ async runMintedSession(session, inputConversationId, consent) {
657
+ // Captured up front: every await below is a window in which the host can end the session.
658
+ const generation = this.startGeneration;
659
+ try {
660
+ this.agentSessionId = session.AgentSessionId;
661
+ // A null input conversationId means the SERVER created a fresh conversation for
662
+ // this session — track it so the host can fold it into the cached list, select
663
+ // it on close, and auto-name it (via the shared naming helper).
664
+ this.createdConversationId = !inputConversationId && session.ConversationId ? session.ConversationId : null;
665
+ this.sessionConversationId = session.ConversationId ?? inputConversationId ?? null;
666
+ this.firstUserTranscript = null;
667
+ this.narrationTemplate = session.NarrationInstructionsTemplate ?? null;
668
+ this._modelName$.next(session.ModelName ?? null);
669
+ // Resume continuity: rehydrate channel plugins from the PRIOR session's saved states
670
+ // (e.g. the whiteboard) BEFORE any surface binds — tolerant, never blocks the start.
671
+ this.applyPriorChannelStates(session.PriorChannelStatesJson);
672
+ const client = this.createRealtimeClient(session.Provider);
673
+ this.client = client;
674
+ this.wireClientHandlers(client);
675
+ // Everything past here awaits on hardware and the network, during which the host may end the
676
+ // session. Each await is followed by a staleness check so an abandoned start releases what it
677
+ // just acquired instead of leaving a live microphone and a live call behind it.
678
+ this.localStream = await this.mediaHost.AcquireMicrophone();
679
+ if (this.startGeneration !== generation) {
680
+ await this.unwindAbandonedStart(session, client);
681
+ return;
682
+ }
683
+ await client.Connect(this.buildClientConfig(session), this.localStream);
684
+ if (this.startGeneration !== generation) {
685
+ await this.unwindAbandonedStart(session, client);
686
+ return;
687
+ }
688
+ // Notify active channels that the session client is connected and tracks are established
689
+ for (const channel of this._activeChannels$.value) {
690
+ try {
691
+ channel.OnSessionStarted?.();
692
+ }
693
+ catch (err) {
694
+ console.error(`[RealtimeSession] Error in channel '${channel.ChannelName}' OnSessionStarted:`, err);
695
+ }
696
+ }
697
+ // Start browser-side recording (mic + agent mix) when consented. Best-effort: an
698
+ // unsupported browser / missing remote stream degrades gracefully (mic-only or off)
699
+ // and never blocks the call. The remote stream may still be null here (the WebRTC
700
+ // ontrack can land slightly after Connect resolves) — the recorder mixes the mic now
701
+ // and the agent audio rides through whenever its track is already attached.
702
+ // The SESSION clock (#3832): anchored the moment the call goes live, whether or not a
703
+ // recording exists. When the recorder runs, per-turn timings use ITS clock (offsets into a
704
+ // seekable file); when it does not — every unconsented and every relay-captured session,
705
+ // which is 100% of turns measured across two databases — this is the fallback that stops
706
+ // `UtteranceStartMs`/`UtteranceEndMs` being categorically null. An offset into a session
707
+ // with no audio is not seekable, but it is orderable and displayable ("3:42 into the
708
+ // interview"), and it is stamped when the SPEECH happened rather than when the relay
709
+ // mutation landed — which no server-side backfill can ever recover.
710
+ this.sessionClockStartMs = performance.now();
711
+ if (consent) {
712
+ this.startRecording(client);
713
+ }
714
+ this.subscribeDelegationProgress();
715
+ // State advances to 'listening' once the provider control channel opens
716
+ // (driven by the client's OnStateChange events).
717
+ // Surface a generic session-started event for the conversations runtime
718
+ // SessionsObserver bridge. Emitting AFTER Connect() guarantees both that
719
+ // agentSessionId is set (line ~468) AND the realtime client is connected,
720
+ // so consumers can act on it without re-checking either condition.
721
+ this._sessionStarted$.next({
722
+ sessionId: this.agentSessionId,
723
+ channelNames: this._activeChannels$.value.map(c => c.ChannelName),
724
+ });
725
+ // Same place, same reason: the session is connected and its id is known, which is exactly
726
+ // the window in which the server needs to be told it is alive.
727
+ this.startLivenessPulse();
728
+ }
729
+ catch (error) {
730
+ await this.failSessionStart(error);
731
+ }
732
+ }
733
+ /**
734
+ * Releases everything a start acquired after the host had already ended the session.
735
+ *
736
+ * Reached only when {@link teardown} ran while this start was awaiting the microphone or the
737
+ * provider connection. Teardown found nothing to release because nothing existed yet, so this
738
+ * start owns the cleanup: stop the microphone, close the provider connection, and close the
739
+ * server-side session row that the mint created.
740
+ */
741
+ async unwindAbandonedStart(session, client) {
742
+ console.warn('[RealtimeSession] Session was ended while starting — releasing the partial session.');
743
+ this.localStream?.getTracks().forEach(t => t.stop());
744
+ this.localStream = null;
745
+ try {
746
+ await client.Disconnect();
747
+ }
748
+ catch (error) {
749
+ console.error('[RealtimeSession] Disconnect of an abandoned start failed:', error);
750
+ }
751
+ // Only clear the shared slots when they still point at THIS attempt — a newer start may
752
+ // already have replaced them.
753
+ if (this.client === client) {
754
+ this.client = null;
755
+ }
756
+ // Close the server session only if teardown has NOT already done so. It nulls `agentSessionId`
757
+ // after closing, so a still-matching id means this attempt still owns the row; a cleared one
758
+ // means the teardown that invalidated this start already closed it, and closing again would
759
+ // send a second `CloseAgentSession` for one session.
760
+ if (session.AgentSessionId && this.agentSessionId === session.AgentSessionId) {
761
+ this.agentSessionId = null;
762
+ await this.closeServerSession(session.AgentSessionId);
763
+ }
764
+ }
765
+ /**
766
+ * Why the last session start failed, or `null` when the last start succeeded or none has run.
767
+ *
768
+ * Read it when {@link ConnectionState$} reports `'error'`, to tell a denied microphone apart from
769
+ * a provider or backend failure and show copy the user can act on. Cleared at the start of every
770
+ * session.
771
+ */
772
+ get LastStartError() {
773
+ return this.lastStartError;
774
+ }
775
+ /**
776
+ * The single failure path for a session start (mint half or run half): report it, latch the
777
+ * overlay into 'error', and unwind whatever the half-built session already opened.
778
+ */
779
+ async failSessionStart(error) {
780
+ console.error('[RealtimeSession] Failed to start session:', error);
781
+ this.lastStartError = error instanceof Error ? error : new Error(String(error));
782
+ this._connectionState$.next('error');
783
+ await this.teardown(false);
784
+ }
785
+ /**
786
+ * End the active session: stop the mic, tear down the provider connection, and close
787
+ * the server-side agent session. Safe to call when no session is active.
788
+ */
789
+ async EndRealtimeSession() {
790
+ if (!this.IsActive && !this.agentSessionId) {
791
+ return;
792
+ }
793
+ await this.teardown(true);
794
+ }
795
+ /**
796
+ * Inject a typed message into the live session as a user turn.
797
+ *
798
+ * Decomposed into two steps, each mirroring an existing voice path so the typed
799
+ * turn behaves identically to a spoken one:
800
+ * 1. {@link BaseRealtimeClient.SendText} injects the text as user input and triggers a
801
+ * reply through the SAME collision-safe path tool results use — so it queues behind
802
+ * any in-flight response (progress narration / prior turn) instead of colliding.
803
+ * 2. Relay the turn through the same caption + transcript paths user speech uses
804
+ * ({@link onUserTranscript}) so it shows in the live thread AND persists to MJ.
805
+ *
806
+ * No-op when no session is open / the control channel isn't ready, or when the text is empty.
807
+ */
808
+ SendText(text) {
809
+ const trimmed = text?.trim() ?? '';
810
+ if (trimmed.length === 0) {
811
+ return;
812
+ }
813
+ const client = this.client;
814
+ if (!client || !this.isSessionLive()) {
815
+ return;
816
+ }
817
+ client.SendText(trimmed);
818
+ // Relay as a user turn — same path spoken input uses (caption + persisted transcript).
819
+ void this.onUserTranscript(trimmed);
820
+ }
821
+ /** Mute / unmute the local microphone track. Returns the new muted state. */
822
+ ToggleMute() {
823
+ const tracks = this.localStream?.getAudioTracks() ?? [];
824
+ if (tracks.length === 0) {
825
+ return false;
826
+ }
827
+ const muted = tracks[0].enabled; // currently enabled → becomes muted
828
+ this.client?.SetMuted(muted);
829
+ return muted;
830
+ }
831
+ // ── Client-executed UI tools ───────────────────────────────────────────────
832
+ /**
833
+ * Registers a handler for CLIENT-EXECUTED UI tools whose names start with `toolNamePrefix`
834
+ * (e.g. `'Whiteboard_'` → all `Whiteboard_*` calls). Matching tool calls execute LOCALLY via
835
+ * the handler — they are never relayed to the server — and the handler's result JSON is sent
836
+ * back to the model as the `tool_response`. Re-registering the same prefix replaces the
837
+ * handler. The registry is cleared at session teardown.
838
+ */
839
+ RegisterClientToolHandler(toolNamePrefix, handler) {
840
+ this.clientToolHandlers.set(toolNamePrefix, handler);
841
+ }
842
+ /** Removes the handler registered for `toolNamePrefix` (no-op when none is registered). */
843
+ UnregisterClientToolHandler(toolNamePrefix) {
844
+ this.clientToolHandlers.delete(toolNamePrefix);
845
+ }
846
+ /**
847
+ * Feeds a background context note into the live model (no spoken reply is requested) — the
848
+ * perception channel interactive surfaces use (e.g. the whiteboard's coalesced scene deltas).
849
+ * No-op when no session is live.
850
+ */
851
+ SendContextNote(text) {
852
+ const trimmed = text?.trim() ?? '';
853
+ if (trimmed.length === 0 || !this.client || !this.isSessionLive()) {
854
+ return;
855
+ }
856
+ this.client.SendContextNote(trimmed);
857
+ }
858
+ /**
859
+ * Asks the live model to SPEAK FIRST — before the human has said anything.
860
+ *
861
+ * Every other path into the model's voice reacts to something: the human spoke, or a channel
862
+ * reported input. A host that needs the agent to open the conversation (an interviewer greeting
863
+ * a candidate, a guide introducing a task) had no way to ask for that, so the session connected
864
+ * and both sides waited for the other. The instructions are what to say, in the host's words —
865
+ * the model still speaks in its own voice and persona.
866
+ *
867
+ * Returns whether the request was DELIVERED, which is the one way this deliberately differs from
868
+ * {@link SendContextNote} beside it. A context note that is dropped costs the model a little
869
+ * perception; an opening line that is dropped is a session that sits in silence, and the host
870
+ * needs to be able to tell the two apart. `false` means no session was live (or the instructions
871
+ * were empty) — usually a host that asked before the connection reached a speaking state, which
872
+ * it can then retry.
873
+ */
874
+ RequestSpokenOpening(instructions) {
875
+ const trimmed = instructions?.trim() ?? '';
876
+ if (trimmed.length === 0 || !this.client || !this.isSessionLive()) {
877
+ return false;
878
+ }
879
+ this.requestChannelSpokenResponse(trimmed);
880
+ return true;
881
+ }
882
+ /**
883
+ * The active client's current audio activity (per-direction RMS levels + spectrum
884
+ * bins), or `null` when no session is live or the driver attached no audio meters.
885
+ * Sampled by the overlay's animation-frame loop to drive the audio-reactive orb/EQ —
886
+ * a cheap analyser read, never provider traffic.
887
+ */
888
+ GetAudioActivity() {
889
+ return this.client?.GetAudioActivity() ?? null;
890
+ }
891
+ /**
892
+ * The active {@link BaseRealtimeClient} driving the media plane, or null when not connected.
893
+ */
894
+ get Client() {
895
+ return this.client;
896
+ }
897
+ /**
898
+ * Relays a video frame to the underlying realtime client if active.
899
+ */
900
+ SendVideoFrame(base64Image, mimeType) {
901
+ if (!this.client || !this.isSessionLive()) {
902
+ return;
903
+ }
904
+ this.client.SendVideoFrame?.(base64Image, mimeType);
905
+ }
906
+ /**
907
+ * Checks whether a media track is established on the active realtime client.
908
+ */
909
+ IsTrackEstablished(modality, direction) {
910
+ return this.client?.IsTrackEstablished(modality, direction) ?? false;
911
+ }
912
+ // ── Browser-side call recording ────────────────────────────────────────────
913
+ /**
914
+ * Reads the per-user recording-consent preference from `MJ: User Settings` (via
915
+ * {@link UserInfoEngine}'s synchronous cache). Defensive: any failure resolves to `false`
916
+ * (don't record) so a settings hiccup can never opt a user into recording.
917
+ */
918
+ readPersistedRecordingConsent() {
919
+ try {
920
+ return UserInfoEngine.Instance.GetSetting(REALTIME_RECORDING_CONSENT_KEY) === 'true';
921
+ }
922
+ catch {
923
+ return false;
924
+ }
925
+ }
926
+ /**
927
+ * Starts the browser-side recorder (mic + agent-audio mix). Best-effort — any failure is
928
+ * contained so it never disturbs the live call; an unsupported browser simply records
929
+ * nothing (the recorder disables itself).
930
+ */
931
+ startRecording(client) {
932
+ try {
933
+ if (!this.localStream) {
934
+ return;
935
+ }
936
+ const remoteStream = client.GetRemoteMediaStream?.() ?? null;
937
+ const recorder = this.mediaHost.CreateRecorder?.() ?? null;
938
+ if (!recorder) {
939
+ return;
940
+ }
941
+ recorder.Start(this.localStream, remoteStream);
942
+ this.recorder = recorder.IsRecording ? recorder : null;
943
+ // First turn's audio starts at ~0 (recording begins right as the call goes live). Seed it
944
+ // here so the very first turn has a sane start even if its first interim is missed; later
945
+ // turns re-stamp from where THEIR audio begins via markTurnAudioStart (handles tool gaps).
946
+ // Seeded even though the session clock may already have stamped a start: the clocks have
947
+ // different zeros, and a session-clock start carried into recorder-clock offsets would put
948
+ // turn one's cue wherever the clocks happen to differ.
949
+ this.currentTurnStartMs = recorder.IsRecording ? 0 : null;
950
+ this.turnAudioStartCaptured = false;
951
+ if (this.recorder) {
952
+ // The agent's WebRTC audio track usually lands AFTER Connect() resolves, so `remoteStream`
953
+ // above is typically null and we'd capture mic-only. Attach the agent stream whenever it
954
+ // arrives (fires immediately if already present) so the recording includes the agent voice.
955
+ client.OnRemoteMediaStream?.((stream) => this.recorder?.AttachRemoteStream(stream));
956
+ this.startSegmentFlushing();
957
+ }
958
+ }
959
+ catch (error) {
960
+ console.warn('[RealtimeSession] Failed to start call recording:', error);
961
+ this.recorder = null;
962
+ }
963
+ }
964
+ /** Begins flushing ~15s crash-recovery shards to the server for the duration of the recording. */
965
+ startSegmentFlushing() {
966
+ this.segmentIndex = 0;
967
+ this.segmentTimer = setInterval(() => { void this.flushRecordingSegment(); }, RealtimeSessionRuntime.SegmentFlushMs);
968
+ }
969
+ /** Stops the periodic crash-recovery shard flush. */
970
+ stopSegmentFlushing() {
971
+ if (this.segmentTimer) {
972
+ clearInterval(this.segmentTimer);
973
+ this.segmentTimer = null;
974
+ }
975
+ }
976
+ /**
977
+ * Starts telling the server this session is still in use (#3533).
978
+ *
979
+ * **Why the server cannot work this out on its own.** In the client-direct topology the audio
980
+ * goes browser → provider over WebRTC. The server sees the mint, a few channel actions in the
981
+ * first seconds, and then nothing at all — so `SessionManager.RecordActivity` stops being
982
+ * reached while the conversation is still going. `LastActiveAt` freezes ~45 seconds in, and
983
+ * `SessionJanitor` — which cannot distinguish an active call from an abandoned one — force-closes
984
+ * it at `closeThresholdMinutes`, mid-sentence, taking the user's surfaces with it. A session
985
+ * whose channels are all client-side (whiteboard, media) goes quiet from the server's point of
986
+ * view almost immediately.
987
+ *
988
+ * The browser is the only participant that knows the call is alive, so it is the one that has to
989
+ * say so. Raising `closeThresholdMinutes` is not the fix — it just makes the janitor slower at
990
+ * its real job (reaping rows orphaned by a crash) without making liveness observable.
991
+ *
992
+ * The pulse is best-effort by design: a failed beat is logged and skipped, never surfaced to the
993
+ * user and never allowed to end the session. Losing one beat costs nothing because the threshold
994
+ * is many beats wide; turning a transient network blip into a visible error would be a worse
995
+ * failure than the one this fixes. Write amplification is bounded on the server side too, where
996
+ * `SessionManager.Heartbeat` coalesces persisted writes.
997
+ */
998
+ startLivenessPulse() {
999
+ this.stopLivenessPulse();
1000
+ this.livenessTimer = setInterval(() => { void this.pulseLiveness(); }, RealtimeSessionRuntime.LivenessPulseMs);
1001
+ }
1002
+ /** Stops the liveness pulse. Idempotent — safe on a session that never started one. */
1003
+ stopLivenessPulse() {
1004
+ if (this.livenessTimer) {
1005
+ clearInterval(this.livenessTimer);
1006
+ this.livenessTimer = null;
1007
+ }
1008
+ }
1009
+ /**
1010
+ * One liveness beat. Reads the session id at fire time rather than closing over it, so a beat
1011
+ * that fires during teardown finds `null` and does nothing instead of resurrecting a closed row.
1012
+ */
1013
+ async pulseLiveness() {
1014
+ const agentSessionId = this.agentSessionId;
1015
+ if (!agentSessionId) {
1016
+ return;
1017
+ }
1018
+ const mutation = `
1019
+ mutation AgentSessionHeartbeat($agentSessionId: String!) {
1020
+ AgentSessionHeartbeat(agentSessionId: $agentSessionId)
1021
+ }
1022
+ `;
1023
+ try {
1024
+ await this.gql().ExecuteGQL(mutation, { agentSessionId });
1025
+ }
1026
+ catch (error) {
1027
+ // Best-effort: the next beat is 60s away and the janitor threshold is many beats wide.
1028
+ console.warn('[RealtimeSession] Liveness pulse failed (session continues):', error);
1029
+ }
1030
+ }
1031
+ /**
1032
+ * Uploads the chunks captured since the last flush as one crash-recovery shard (durability only;
1033
+ * the canonical file is still the full upload at teardown). Best-effort — never disturbs the call.
1034
+ */
1035
+ async flushRecordingSegment() {
1036
+ const recorder = this.recorder;
1037
+ const agentSessionId = this.agentSessionId;
1038
+ if (!recorder || !agentSessionId) {
1039
+ return;
1040
+ }
1041
+ try {
1042
+ const audioBase64 = await recorder.SnapshotNewSegmentBase64();
1043
+ if (!audioBase64) {
1044
+ return;
1045
+ }
1046
+ const index = this.segmentIndex++;
1047
+ const mutation = `
1048
+ mutation UploadRealtimeRecordingSegment($agentSessionId: String!, $segmentIndex: Int!, $audioBase64: String!, $mimeType: String!) {
1049
+ UploadRealtimeRecordingSegment(agentSessionId: $agentSessionId, segmentIndex: $segmentIndex, audioBase64: $audioBase64, mimeType: $mimeType)
1050
+ }
1051
+ `;
1052
+ // Shards are HEADER-LESS raw little-endian PCM16 (mime audio/L16 with the capture sample rate),
1053
+ // NOT individually-playable WAV — recovery is concatenate-in-order then WAV-wrap. The canonical
1054
+ // seekable WAV is the consolidated end-of-call upload below.
1055
+ const shardMime = `audio/L16;rate=${recorder.SampleRate}`;
1056
+ await this.gql().ExecuteGQL(mutation, { agentSessionId, segmentIndex: index, audioBase64, mimeType: shardMime });
1057
+ }
1058
+ catch (error) {
1059
+ console.warn('[RealtimeSession] Failed to flush recording shard:', error);
1060
+ }
1061
+ }
1062
+ /**
1063
+ * Stops the active recorder and uploads the captured audio via `UploadRealtimeRecording`.
1064
+ * Fully best-effort and wrapped in try/catch — recording upload must NEVER block teardown.
1065
+ * No-op when nothing was recorded or there's no session id to attach the file to.
1066
+ */
1067
+ async stopAndUploadRecording(agentSessionId) {
1068
+ this.stopSegmentFlushing();
1069
+ const recorder = this.recorder;
1070
+ this.recorder = null;
1071
+ this.currentTurnStartMs = null;
1072
+ this.turnAudioStartCaptured = false;
1073
+ if (!recorder) {
1074
+ return;
1075
+ }
1076
+ try {
1077
+ // Capture the recorder MIME (now 'audio/wav') BEFORE Stop() — the getter reads '' once stopped.
1078
+ const mimeType = recorder.MimeType;
1079
+ const audioBase64 = await recorder.StopAndEncode();
1080
+ // Read the real waveform peaks computed during capture (survives the stop via the snapshot).
1081
+ const peaks = recorder.GetPeaks();
1082
+ if (!audioBase64 || !agentSessionId) {
1083
+ console.warn('[RealtimeSession] ⚠️ recording NOT uploaded — empty recording or no session id.');
1084
+ return;
1085
+ }
1086
+ await this.uploadRecording(agentSessionId, audioBase64, mimeType, peaks);
1087
+ }
1088
+ catch (error) {
1089
+ console.warn('[RealtimeSession] Failed to stop/upload call recording:', error);
1090
+ }
1091
+ }
1092
+ /**
1093
+ * Runs the `UploadRealtimeRecording` mutation; failures are logged, never thrown. Sends the
1094
+ * capture-time waveform `peaks` (max-abs per bucket, normalized 0..1) so the server can persist a
1095
+ * `peaks.json` sidecar for fast waveform rendering without re-decoding the audio.
1096
+ */
1097
+ async uploadRecording(agentSessionId, audioBase64, mimeType, peaks) {
1098
+ const mutation = `
1099
+ mutation UploadRealtimeRecording($agentSessionId: String!, $audioBase64: String!, $mimeType: String!, $consent: Boolean, $peaks: [Float!]) {
1100
+ UploadRealtimeRecording(agentSessionId: $agentSessionId, audioBase64: $audioBase64, mimeType: $mimeType, consent: $consent, peaks: $peaks) {
1101
+ Success
1102
+ FileID
1103
+ ErrorMessage
1104
+ }
1105
+ }
1106
+ `;
1107
+ const result = await this.gql().ExecuteGQL(mutation, {
1108
+ agentSessionId,
1109
+ audioBase64,
1110
+ mimeType,
1111
+ consent: true,
1112
+ peaks
1113
+ });
1114
+ const payload = result?.UploadRealtimeRecording;
1115
+ if (!payload?.Success) {
1116
+ console.warn(`[RealtimeSession] ❌ recording upload reported failure: ${payload?.ErrorMessage ?? 'unknown error'} (full result: ${JSON.stringify(result)})`);
1117
+ }
1118
+ }
1119
+ // ── Interactive channels (registry-driven plugins) ─────────────────────────
1120
+ /**
1121
+ * Resolves, instantiates and initializes the session's interactive-channel plugins from
1122
+ * the `MJ: AI Agent Channels` registry, publishes them on {@link ActiveChannels$}, and
1123
+ * returns their aggregated client-executed tool declarations for the session mint.
1124
+ * Tolerant by design: registry/resolution failures degrade to "no channels" — the voice
1125
+ * session itself always proceeds.
1126
+ */
1127
+ async startChannels() {
1128
+ const channels = await this.loadActiveChannels();
1129
+ for (const plugin of channels) {
1130
+ this.initializeChannel(plugin);
1131
+ }
1132
+ this._activeChannels$.next(channels);
1133
+ return channels.flatMap(plugin => plugin.GetToolDefinitions());
1134
+ }
1135
+ /**
1136
+ * Loads the ACTIVE channel definitions from the registry and resolves each row's
1137
+ * `ClientPluginClass` through the MJ ClassFactory into a per-session plugin instance —
1138
+ * the client-side mirror of how realtime-model drivers resolve from `BaseRealtimeModel`
1139
+ * / `BaseRealtimeClient`. Rows whose plugin class isn't registered are skipped (logged),
1140
+ * never fatal.
1141
+ */
1142
+ async loadActiveChannels() {
1143
+ const rows = await this.fetchChannelDefinitions();
1144
+ const channels = [];
1145
+ for (const row of rows) {
1146
+ const plugin = this.resolveChannelPlugin(row);
1147
+ if (plugin) {
1148
+ channels.push(plugin);
1149
+ }
1150
+ }
1151
+ return channels;
1152
+ }
1153
+ /**
1154
+ * Reads the ACTIVE `MJ: AI Agent Channels` rows from {@link AIEngineBase}'s cached
1155
+ * `AgentChannels` (provider-scoped engine instance, lazy `Config` — no RunView
1156
+ * round-trip; the engine's BaseEntity-event reactivity keeps the registry fresh).
1157
+ * Failures are logged and degrade to an empty list — channel availability must
1158
+ * never block the voice session.
1159
+ */
1160
+ async fetchChannelDefinitions() {
1161
+ try {
1162
+ const engine = AIEngineBase.GetProviderInstance(this.Provider, AIEngineBase);
1163
+ await engine.Config(false, undefined, this.Provider);
1164
+ return (engine.AgentChannels ?? [])
1165
+ .filter(c => c.IsActive)
1166
+ .map(c => ({ ID: c.ID, Name: c.Name, ClientPluginClass: c.ClientPluginClass }));
1167
+ }
1168
+ catch (error) {
1169
+ console.warn('[RealtimeSession] Channel registry unavailable — starting with no channels:', error);
1170
+ return [];
1171
+ }
1172
+ }
1173
+ /**
1174
+ * Resolves one registry row's `ClientPluginClass` via the ClassFactory (registration
1175
+ * checked first, exactly like the realtime-client drivers) and instantiates a fresh
1176
+ * per-session plugin. Returns `null` (logged) when no plugin is registered for the key
1177
+ * — e.g. its Load function was never called or the package isn't included client-side.
1178
+ */
1179
+ resolveChannelPlugin(row) {
1180
+ const key = row.ClientPluginClass?.trim();
1181
+ if (!key) {
1182
+ console.warn(`[RealtimeSession] Channel '${row.Name}' has no ClientPluginClass — skipping.`);
1183
+ return null;
1184
+ }
1185
+ const registration = MJGlobal.Instance.ClassFactory.GetRegistration(BaseRealtimeChannelClient, key);
1186
+ if (!registration) {
1187
+ console.warn(`[RealtimeSession] No client plugin registered for channel '${row.Name}' (key '${key}') — skipping.`);
1188
+ return null;
1189
+ }
1190
+ const plugin = MJGlobal.Instance.ClassFactory.CreateInstance(BaseRealtimeChannelClient, key);
1191
+ if (!plugin) {
1192
+ console.warn(`[RealtimeSession] Failed to instantiate client plugin for channel '${row.Name}' (key '${key}').`);
1193
+ return null;
1194
+ }
1195
+ return plugin;
1196
+ }
1197
+ /**
1198
+ * Wires one plugin into the session: hands it its host context and registers its
1199
+ * prefix-routed local tool executor (so `<ToolNamePrefix>*` calls run in the browser
1200
+ * through {@link BaseRealtimeChannelClient.ApplyAgentTool}, never the server relay).
1201
+ */
1202
+ initializeChannel(plugin) {
1203
+ plugin.Initialize(this.buildChannelContext(plugin));
1204
+ this.RegisterClientToolHandler(plugin.ToolNamePrefix, (toolName, argsJson) => {
1205
+ // The agent is ACTING on this channel — surface-discovery signal for the overlay
1206
+ // (first activity registers + auto-reveals + focuses the channel tab) before the
1207
+ // tool applies. Record the channel as USED so the overlay tabs it (channels other
1208
+ // than the whiteboard are tab-less until they're first used).
1209
+ this.usedChannelNames.add(plugin.ChannelName);
1210
+ this._channelActivity$.next(plugin);
1211
+ return plugin.ApplyAgentTool(toolName, argsJson);
1212
+ });
1213
+ }
1214
+ /** Builds the host-services context one channel plugin sees (its only line to the session). */
1215
+ buildChannelContext(plugin) {
1216
+ // Capture the service in a local so the AgentSessionID getter reads the SERVICE's live
1217
+ // field (not the object literal's `this`) every time it's accessed.
1218
+ const service = this;
1219
+ return {
1220
+ AgentName: this.CurrentAgentName,
1221
+ // The live session's provider — threaded by channels into MJ-backed surfaces (e.g. the Media
1222
+ // channel's mj-storage-media-player / CreateMediaAccessToken). `get` so it stays current.
1223
+ get Provider() {
1224
+ return service.Provider;
1225
+ },
1226
+ SendContextNote: (text) => this.SendContextNote(text),
1227
+ RequestSpokenResponse: (instructions) => this.requestChannelSpokenResponse(instructions),
1228
+ RequestSave: (stateJson) => this.scheduleChannelSave(plugin.ChannelName, stateJson),
1229
+ SaveAsArtifact: (name, contentJson) => this.saveChannelArtifact(plugin.ChannelName, name, contentJson),
1230
+ SetFocusMode: (on) => this._channelFocus$.next({ Channel: plugin, Focused: on }),
1231
+ // Live session id + GraphQL escape hatch for SERVER-BACKED channels (e.g. Remote
1232
+ // Browser). `get` so a channel always reads the CURRENT id — it's null at Initialize
1233
+ // (the plugin is built before mintSession resolves) and set once the session is live.
1234
+ get AgentSessionID() {
1235
+ return service.agentSessionId;
1236
+ },
1237
+ ExecuteServerAction: (query, variables) => this.executeChannelServerAction(query, variables),
1238
+ // App-context stream + client-tool execution for the headless ClientContextChannel. The host
1239
+ // (Explorer) feeds both; absent on hosts that supply no app context / register no client tools.
1240
+ AppContext$: this.AppContext$,
1241
+ ExecuteClientTool: (name, params) => this.executeAppClientTool(name, params),
1242
+ get Client() {
1243
+ return service.client;
1244
+ },
1245
+ SendVideoFrame: (base64Image, mimeType) => this.SendVideoFrame(base64Image, mimeType),
1246
+ IsTrackEstablished: (modality, direction) => this.IsTrackEstablished(modality, direction)
1247
+ };
1248
+ }
1249
+ /**
1250
+ * Replaces the set of host-registered surface client tools the realtime ContextTool can execute.
1251
+ * The host calls this at session start and whenever the active surface's tool set changes (the
1252
+ * continuous-capability half of client-context delivery). Passing `[]` clears them.
1253
+ *
1254
+ * @param tools The current surface client tools (name + handler). Descriptions/schemas ride the
1255
+ * app-context manifest separately; only the executable handler is needed here.
1256
+ */
1257
+ RegisterAppClientTools(tools) {
1258
+ this.appClientToolHandlers.clear();
1259
+ for (const tool of tools) {
1260
+ if (tool?.Name && typeof tool.Handler === 'function') {
1261
+ this.appClientToolHandlers.set(tool.Name.trim().toLowerCase(), tool.Handler);
1262
+ }
1263
+ }
1264
+ }
1265
+ /**
1266
+ * Executes a host-registered surface client tool by name (the {@link RealtimeChannelContext.ExecuteClientTool}
1267
+ * implementation). Tolerant: an unknown tool or a thrown handler resolves to a structured
1268
+ * `Success: false` result the channel narrates — never throws.
1269
+ *
1270
+ * @param name The tool name (the model's `action`).
1271
+ * @param params The tool parameters.
1272
+ * @returns A structured result for the channel to serialize back to the model.
1273
+ */
1274
+ async executeAppClientTool(name, params) {
1275
+ const handler = this.appClientToolHandlers.get((name ?? '').trim().toLowerCase());
1276
+ if (!handler) {
1277
+ const available = Array.from(this.appClientToolHandlers.keys()).join(', ');
1278
+ return {
1279
+ Success: false,
1280
+ ErrorMessage: `No client tool named "${name}" is available on this surface. Available: ${available || '(none)'}.`
1281
+ };
1282
+ }
1283
+ try {
1284
+ const result = await handler(params ?? {});
1285
+ return { Success: true, Result: result };
1286
+ }
1287
+ catch (error) {
1288
+ return { Success: false, ErrorMessage: error instanceof Error ? error.message : String(error) };
1289
+ }
1290
+ }
1291
+ /**
1292
+ * Runs a channel-specific GraphQL operation through the live session's provider (the
1293
+ * {@link RealtimeChannelContext.ExecuteServerAction} implementation). Best-effort: any
1294
+ * transport/server error is logged and resolves to `null` so the calling channel can map
1295
+ * the failure to a model-readable result string without `try/catch`.
1296
+ */
1297
+ async executeChannelServerAction(query, variables) {
1298
+ try {
1299
+ const result = await this.gql().ExecuteGQL(query, variables);
1300
+ return result ?? null;
1301
+ }
1302
+ catch (error) {
1303
+ console.error('[RealtimeSession] Channel server action failed:', error);
1304
+ return null;
1305
+ }
1306
+ }
1307
+ /**
1308
+ * A channel asked the live model to SPEAK in reaction to channel input (e.g. a widget
1309
+ * submission) — routed through the client's spoken-update channel. No-op when the
1310
+ * session isn't live; empty instructions are dropped.
1311
+ */
1312
+ requestChannelSpokenResponse(instructions) {
1313
+ const trimmed = instructions?.trim() ?? '';
1314
+ if (trimmed.length === 0 || !this.client || !this.isSessionLive()) {
1315
+ return;
1316
+ }
1317
+ this.client.RequestSpokenUpdate(trimmed);
1318
+ }
1319
+ /**
1320
+ * Applies the PRIOR session's saved channel states (resume continuity): parses the
1321
+ * server-supplied map and offers each entry to the matching active plugin via
1322
+ * {@link BaseRealtimeChannelClient.RestoreState}. Fully tolerant — malformed payloads,
1323
+ * unknown channels, and plugin rejections are logged and skipped; the session start is
1324
+ * never affected.
1325
+ */
1326
+ applyPriorChannelStates(statesJson) {
1327
+ if (!statesJson) {
1328
+ return;
1329
+ }
1330
+ let states;
1331
+ try {
1332
+ const parsed = JSON.parse(statesJson);
1333
+ if (parsed === null || typeof parsed !== 'object') {
1334
+ return;
1335
+ }
1336
+ states = parsed;
1337
+ }
1338
+ catch {
1339
+ console.warn('[RealtimeSession] PriorChannelStatesJson was malformed — starting channels fresh');
1340
+ return;
1341
+ }
1342
+ for (const plugin of this._activeChannels$.value) {
1343
+ const state = states[plugin.ChannelName];
1344
+ if (typeof state === 'string' && state.length > 0) {
1345
+ try {
1346
+ const restored = plugin.RestoreState(state);
1347
+ if (!restored) {
1348
+ console.warn(`[RealtimeSession] Channel '${plugin.ChannelName}' declined its prior-session state — starting fresh`);
1349
+ }
1350
+ }
1351
+ catch (error) {
1352
+ console.warn(`[RealtimeSession] Channel '${plugin.ChannelName}' restore threw — starting fresh`, error);
1353
+ }
1354
+ }
1355
+ }
1356
+ }
1357
+ /**
1358
+ * Persists a channel's state as a first-class versioned artifact (`MJ: Artifacts`) via the
1359
+ * `SaveSessionChannelArtifact` mutation — the channel-context capability behind e.g. the
1360
+ * whiteboard's "Save to artifacts". Best-effort: returns the created Artifact ID, or null
1361
+ * on any failure (logged, never thrown). Uses the live session id, falling back to the
1362
+ * teardown-captured one so "save my board" works right after the call ends.
1363
+ */
1364
+ async saveChannelArtifact(channelName, name, contentJson) {
1365
+ const sessionId = this.agentSessionId ?? this.lastKnownSessionIdForSaves();
1366
+ if (!sessionId || !name.trim() || !contentJson) {
1367
+ return null;
1368
+ }
1369
+ try {
1370
+ const result = await this.gql().ExecuteGQL(`mutation SaveSessionChannelArtifact($agentSessionId: String!, $channelName: String!, $name: String!, $contentJson: String!) {
1371
+ SaveSessionChannelArtifact(agentSessionId: $agentSessionId, channelName: $channelName, name: $name, contentJson: $contentJson) {
1372
+ Success
1373
+ ErrorMessage
1374
+ ArtifactID
1375
+ ArtifactVersionID
1376
+ }
1377
+ }`, { agentSessionId: sessionId, channelName, name: name.trim(), contentJson });
1378
+ const payload = result?.SaveSessionChannelArtifact;
1379
+ if (!payload?.Success) {
1380
+ console.warn(`[RealtimeSession] Save-as-artifact failed for '${channelName}': ${payload?.ErrorMessage ?? 'unknown error'}`);
1381
+ return null;
1382
+ }
1383
+ return payload.ArtifactID ?? null;
1384
+ }
1385
+ catch (error) {
1386
+ console.warn(`[RealtimeSession] Save-as-artifact errored for '${channelName}':`, error);
1387
+ return null;
1388
+ }
1389
+ }
1390
+ /** Most recent session id captured by the save pipeline (post-teardown saves). */
1391
+ lastKnownSessionIdForSaves() {
1392
+ for (const pending of this.pendingChannelSaves.values()) {
1393
+ if (pending.SessionID) {
1394
+ return pending.SessionID;
1395
+ }
1396
+ }
1397
+ return null;
1398
+ }
1399
+ /**
1400
+ * Schedules the DEBOUNCED state-of-record save for a channel: each request replaces the
1401
+ * pending payload (latest state wins) and re-arms the timer; the session id is captured
1402
+ * while live so the teardown flush can persist onto the just-closed session.
1403
+ */
1404
+ scheduleChannelSave(channelName, stateJson) {
1405
+ const pending = this.pendingChannelSaves.get(channelName);
1406
+ if (pending) {
1407
+ clearTimeout(pending.Timer);
1408
+ }
1409
+ this.pendingChannelSaves.set(channelName, {
1410
+ Timer: setTimeout(() => this.flushChannelSave(channelName), RealtimeSessionRuntime.ChannelSaveDebounceMs),
1411
+ StateJson: stateJson,
1412
+ SessionID: this.agentSessionId ?? pending?.SessionID ?? null
1413
+ });
1414
+ }
1415
+ /** Fires one pending channel save (best-effort; {@link SaveChannelState} logs failures). */
1416
+ flushChannelSave(channelName) {
1417
+ const pending = this.pendingChannelSaves.get(channelName);
1418
+ if (!pending) {
1419
+ return;
1420
+ }
1421
+ this.pendingChannelSaves.delete(channelName);
1422
+ clearTimeout(pending.Timer);
1423
+ void this.SaveChannelState(channelName, pending.StateJson, pending.SessionID);
1424
+ }
1425
+ /** Final teardown flush: persist every channel's unsaved state immediately. */
1426
+ flushAllChannelSaves() {
1427
+ for (const channelName of [...this.pendingChannelSaves.keys()]) {
1428
+ this.flushChannelSave(channelName);
1429
+ }
1430
+ }
1431
+ /** Disposes all channel plugins (errors contained per plugin) and clears the live set. */
1432
+ disposeChannels() {
1433
+ for (const plugin of this._activeChannels$.value) {
1434
+ try {
1435
+ plugin.Dispose();
1436
+ }
1437
+ catch (error) {
1438
+ console.error(`[RealtimeSession] Channel '${plugin.ChannelName}' Dispose failed:`, error);
1439
+ }
1440
+ }
1441
+ if (this._activeChannels$.value.length > 0) {
1442
+ this._activeChannels$.next([]);
1443
+ }
1444
+ this.usedChannelNames.clear();
1445
+ }
1446
+ // ── Realtime client resolution + wiring ────────────────────────────────────
1447
+ /**
1448
+ * Resolves the provider-direct realtime client for `provider` through the MJ
1449
+ * ClassFactory — the client-side mirror of how server drivers are resolved from
1450
+ * `BaseRealtimeModel`. Throws a clear error when no driver is registered for the
1451
+ * provider (e.g. its Load function was never called).
1452
+ */
1453
+ createRealtimeClient(provider) {
1454
+ const registration = MJGlobal.Instance.ClassFactory.GetRegistration(BaseRealtimeClient, provider);
1455
+ if (!registration) {
1456
+ throw new Error(`No realtime client registered for provider '${provider}'. ` +
1457
+ `Ensure the provider's client driver package is imported and its Load function called.`);
1458
+ }
1459
+ const client = MJGlobal.Instance.ClassFactory.CreateInstance(BaseRealtimeClient, provider);
1460
+ if (!client) {
1461
+ throw new Error(`Failed to instantiate the realtime client for provider '${provider}'`);
1462
+ }
1463
+ return client;
1464
+ }
1465
+ /**
1466
+ * Builds the client-direct session config the realtime client connects with.
1467
+ * Aggregates tracks sourced by active channels into `requestedTracks` so the driver
1468
+ * can negotiate them (e.g., establishing inbound video streaming for Whiteboard / RemoteBrowser).
1469
+ */
1470
+ buildClientConfig(session) {
1471
+ const sessionConfig = this.parseSessionConfig(session.SessionConfigJson);
1472
+ const channelTracks = this._activeChannels$.value.flatMap((c) => c.GetSourcedTracks());
1473
+ if (channelTracks.length > 0) {
1474
+ // `requestedTracks` crosses a JSON boundary — the driver reads it back out of the session
1475
+ // config bag (`GeminiRealtimeClient.parseSessionConfig`). A `RealtimeTrackDescriptor` is NOT
1476
+ // structurally a `JSONValue`: it has no index signature and `UsageBasis` is readonly, so the
1477
+ // conversion is written out rather than asserted. Dedupe key and precedence are unchanged —
1478
+ // audio floor first, then anything the mint supplied, then the channels' own tracks.
1479
+ const existing = Array.isArray(sessionConfig['requestedTracks'])
1480
+ ? sessionConfig['requestedTracks']
1481
+ : [];
1482
+ const trackMap = new Map();
1483
+ for (const t of DEFAULT_REALTIME_AUDIO_TRACKS) {
1484
+ trackMap.set(`${t.Direction}:${t.Modality}`, trackDescriptorToJSON(t));
1485
+ }
1486
+ for (const raw of existing) {
1487
+ const key = trackKeyFromJSON(raw);
1488
+ if (key) {
1489
+ trackMap.set(key, raw);
1490
+ }
1491
+ }
1492
+ for (const t of channelTracks) {
1493
+ trackMap.set(`${t.Direction}:${t.Modality}`, trackDescriptorToJSON(t));
1494
+ }
1495
+ sessionConfig['requestedTracks'] = Array.from(trackMap.values());
1496
+ }
1497
+ return {
1498
+ Provider: session.Provider,
1499
+ Model: session.Model,
1500
+ EphemeralToken: session.EphemeralToken,
1501
+ ExpiresAt: session.ExpiresAt,
1502
+ SessionConfig: sessionConfig
1503
+ };
1504
+ }
1505
+ /**
1506
+ * Parses the server-built session config JSON. On failure, logs and returns an empty
1507
+ * object — the client treats an empty config as "nothing to apply", so the session
1508
+ * still opens (mirroring the prior behavior of skipping the config update).
1509
+ */
1510
+ parseSessionConfig(sessionConfigJson) {
1511
+ if (!sessionConfigJson) {
1512
+ return {};
1513
+ }
1514
+ try {
1515
+ return JSON.parse(sessionConfigJson);
1516
+ }
1517
+ catch (error) {
1518
+ console.error('[RealtimeSession] Failed to parse/apply SessionConfigJson:', error);
1519
+ return {};
1520
+ }
1521
+ }
1522
+ /** Subscribes this service's policy handlers to the realtime client's events. */
1523
+ wireClientHandlers(client) {
1524
+ client.OnStateChange((state) => this.onClientStateChange(state));
1525
+ client.OnTranscript((transcript) => {
1526
+ void this.onClientTranscript(transcript);
1527
+ });
1528
+ client.OnToolCall((call) => {
1529
+ void this.handleToolCall(call);
1530
+ });
1531
+ client.OnError((error) => {
1532
+ console.error('[RealtimeSession] Provider error event:', JSON.stringify(error), error);
1533
+ });
1534
+ // Usage telemetry: accumulate the driver's per-response token DELTAS and relay them to
1535
+ // the server (onto the co-agent AIPromptRun) debounced + once at teardown. Providers
1536
+ // without usage events simply never emit — registering is always safe.
1537
+ client.OnUsage((usage) => this.onUsageDelta(usage));
1538
+ // TRUE BARGE-IN (user input cut off active model output — the driver already stopped
1539
+ // the speech): the user took the floor, so any pending/queued progress narration is
1540
+ // stale — cancel it; the next progress event re-schedules at the session-global pace.
1541
+ // HOST POLICY (deliberate): barge-in does NOT abort in-flight delegated runs — the
1542
+ // narration design EXPECTS the user to keep talking while delegated work runs, so
1543
+ // killing the work on speech would cancel exactly the jobs the user asked for.
1544
+ // Explicit cancellation is a separate, intentional act: the overlay's per-card ✕
1545
+ // calls {@link CancelDelegation} (server cancel channel) instead.
1546
+ client.OnInterruption(() => {
1547
+ this.cancelPendingNarration();
1548
+ });
1549
+ }
1550
+ /** Maps a client state event onto the UI connection state. */
1551
+ onClientStateChange(state) {
1552
+ const mapped = this.mapClientState(state);
1553
+ if (mapped) {
1554
+ this._connectionState$.next(mapped);
1555
+ }
1556
+ }
1557
+ /**
1558
+ * Translates {@link RealtimeClientState} into {@link RealtimeConnectionState}. `'connected'`
1559
+ * is suppressed (the UI stays 'connecting' until the control channel opens → 'listening'),
1560
+ * and `'closed'` never overwrites a terminal 'error' the service itself recorded.
1561
+ */
1562
+ mapClientState(state) {
1563
+ switch (state) {
1564
+ case 'connecting':
1565
+ return 'connecting';
1566
+ case 'connected':
1567
+ return null;
1568
+ case 'listening':
1569
+ return 'listening';
1570
+ case 'speaking':
1571
+ return 'speaking';
1572
+ case 'error':
1573
+ return 'error';
1574
+ case 'closed':
1575
+ return this._connectionState$.value === 'error' ? null : 'closed';
1576
+ }
1577
+ }
1578
+ /** True when the live control channel is usable (open and not torn down / failed). */
1579
+ isSessionLive() {
1580
+ const state = this._connectionState$.value;
1581
+ return state === 'listening' || state === 'speaking' || state === 'thinking';
1582
+ }
1583
+ // ── Transcript policy ──────────────────────────────────────────────────────
1584
+ /**
1585
+ * Applies transcript policy to client transcript events. Interim deltas don't become
1586
+ * captions/turns (the client already drives the speaking state) but DO mark this turn's
1587
+ * audio-start offset against the recording (the first interim fires as the audio/text
1588
+ * starts flowing — see {@link markTurnAudioStart}). Final NORMAL assistant turns become
1589
+ * captions + persisted transcripts; final NARRATION turns are EPHEMERAL by product
1590
+ * decision — emitted on {@link DelegationNarration$} only, never a caption, never
1591
+ * relayed/persisted. User turns ride the caption + relay path.
1592
+ */
1593
+ async onClientTranscript(transcript) {
1594
+ if (!transcript.IsFinal) {
1595
+ // First interim of a NEW turn = that turn's audio is starting NOW. Stamp the
1596
+ // recording-relative start here so a turn whose audio begins AFTER a tool-call /
1597
+ // silence gap is timed where its audio really is — not inherited from the prior
1598
+ // turn's end. Narration interims are ephemeral and excluded (Kind guard inside).
1599
+ this.markTurnAudioStart(transcript.Kind);
1600
+ if (transcript.Role === 'User') {
1601
+ if (!this.hasActiveInterimUserCaption) {
1602
+ if (transcript.Text.trim().length === 0) {
1603
+ return;
1604
+ }
1605
+ this.hasActiveInterimUserCaption = true;
1606
+ this.pendingUserCaption = transcript.Text;
1607
+ this.appendCaption({ Role: 'User', Text: this.pendingUserCaption });
1608
+ }
1609
+ else {
1610
+ this.pendingUserCaption += transcript.Text;
1611
+ this.replaceLastCaption('User', this.pendingUserCaption);
1612
+ }
1613
+ }
1614
+ return;
1615
+ }
1616
+ if (transcript.Role === 'Assistant') {
1617
+ this.hasActiveInterimUserCaption = false;
1618
+ this.pendingUserCaption = '';
1619
+ if (transcript.Kind === 'narration') {
1620
+ if (transcript.IsThought) {
1621
+ this._thoughtNarration$.next({
1622
+ CallID: 'thought-session',
1623
+ Text: transcript.Text,
1624
+ IsFinal: transcript.IsFinal ?? true,
1625
+ });
1626
+ }
1627
+ else {
1628
+ this._delegationNarration$.next({ Text: transcript.Text });
1629
+ // Remember what was actually SAID so later updates build on it instead of repeating.
1630
+ this.spokenNarrations.push(transcript.Text);
1631
+ if (this.spokenNarrations.length > RealtimeSessionRuntime.MaxPriorNarrations) {
1632
+ this.spokenNarrations.shift();
1633
+ }
1634
+ }
1635
+ }
1636
+ else if (transcript.ReplacesPrevious) {
1637
+ // CORRECTION (e.g. ElevenLabs post-barge-in re-finalization): this final
1638
+ // SUPERSEDES the previous final assistant turn — replace the caption in place
1639
+ // and tell the server to update the persisted turn instead of appending.
1640
+ this.replaceLastCaption('Assistant', transcript.Text);
1641
+ await this.relayTranscript('assistant', transcript.Text, true);
1642
+ }
1643
+ else {
1644
+ this.appendCaption({ Role: 'Assistant', Text: transcript.Text });
1645
+ await this.relayTranscript('assistant', transcript.Text);
1646
+ }
1647
+ }
1648
+ else if (this.hasActiveInterimUserCaption) {
1649
+ this.hasActiveInterimUserCaption = false;
1650
+ this.pendingUserCaption = '';
1651
+ if (transcript.Text.trim().length === 0) {
1652
+ return;
1653
+ }
1654
+ this.replaceLastCaption('User', transcript.Text);
1655
+ if (this.firstUserTranscript === null) {
1656
+ this.firstUserTranscript = transcript.Text;
1657
+ }
1658
+ await this.relayTranscript('user', transcript.Text);
1659
+ }
1660
+ else if (transcript.ReplacesPrevious) {
1661
+ // STREAMING user transcription: providers like Grok and OpenAI Live emit the growing utterance as repeated
1662
+ // events (each the full text so far), flagging all but the first ReplacesPrevious. Update the
1663
+ // in-place User caption + persisted turn instead of stacking a new bubble per increment — the
1664
+ // same correction semantics the assistant branch uses. (Classic OpenAI Realtime sends one final → the else path.)
1665
+ if (transcript.Text.trim().length === 0) {
1666
+ return;
1667
+ }
1668
+ this.replaceLastCaption('User', transcript.Text);
1669
+ await this.relayTranscript('user', transcript.Text, true);
1670
+ }
1671
+ else {
1672
+ await this.onUserTranscript(transcript.Text);
1673
+ }
1674
+ }
1675
+ /**
1676
+ * Stamps the recording-relative offset at which the IN-FLIGHT turn's audio actually began,
1677
+ * the moment that turn's audio/text first starts flowing (its FIRST interim transcript).
1678
+ *
1679
+ * This is the fix for transcript cues drifting out of sync with the audio when a tool-call /
1680
+ * silence gap sits between turns: the old model inherited the next turn's start from the
1681
+ * PREVIOUS turn's end (assumes contiguous turns), so a post-gap turn's cue pointed ~gap-length
1682
+ * too early. Capturing the start where the audio truly begins keeps the cue aligned.
1683
+ *
1684
+ * Guards:
1685
+ * - only when recording ({@link recorder} present),
1686
+ * - only ONCE per turn ({@link turnAudioStartCaptured}) so mid-turn interim deltas don't move it,
1687
+ * - NORMAL turns only — NARRATION interims are ephemeral and never persisted, so they must not
1688
+ * claim the next real turn's start slot.
1689
+ *
1690
+ * Works for any role whose driver surfaces interim deltas (all drivers for the assistant; the
1691
+ * relevant case here — the post-tool-gap assistant answer — and user-interim drivers like
1692
+ * Gemini/AssemblyAI). For final-only user turns (OpenAI/xAI/ElevenLabs) no interim arrives, so
1693
+ * {@link relayTranscript} falls back to the seeded/prior start — the gap case that drifts is the
1694
+ * assistant answer, which always has interims.
1695
+ */
1696
+ markTurnAudioStart(kind) {
1697
+ if (this.turnAudioStartCaptured || kind === 'narration') {
1698
+ return;
1699
+ }
1700
+ const offset = this.nowTurnOffsetMs();
1701
+ if (offset === null) {
1702
+ return;
1703
+ }
1704
+ this.currentTurnStartMs = offset;
1705
+ this.turnAudioStartCaptured = true;
1706
+ }
1707
+ /**
1708
+ * The current per-turn offset in ms — the RECORDER's clock when one runs (an offset into a
1709
+ * seekable file), else the SESSION clock (#3832: orderable and displayable, not seekable),
1710
+ * else `null` before any call is live. One function so the two stamp sites cannot disagree
1711
+ * about which clock a session is on.
1712
+ */
1713
+ nowTurnOffsetMs() {
1714
+ if (this.recorder) {
1715
+ return this.recorder.NowOffsetMs();
1716
+ }
1717
+ if (this.sessionClockStartMs !== null) {
1718
+ return Math.max(0, Math.round(performance.now() - this.sessionClockStartMs));
1719
+ }
1720
+ return null;
1721
+ }
1722
+ /**
1723
+ * Replaces the LAST caption of `role` in place (correction semantics); falls back to a
1724
+ * plain append when no such caption exists yet (e.g. the superseded turn predates this
1725
+ * client's caption window).
1726
+ */
1727
+ replaceLastCaption(role, text) {
1728
+ const captions = this._captions$.value;
1729
+ for (let i = captions.length - 1; i >= 0; i--) {
1730
+ if (captions[i].Role === role) {
1731
+ const next = [...captions];
1732
+ next[i] = { Role: role, Text: text };
1733
+ this._captions$.next(next);
1734
+ return;
1735
+ }
1736
+ }
1737
+ this.appendCaption({ Role: role, Text: text });
1738
+ }
1739
+ /** Finalizes the user turn: push a caption + relay the final transcript. */
1740
+ async onUserTranscript(transcript) {
1741
+ if (transcript.trim().length === 0) {
1742
+ return;
1743
+ }
1744
+ if (this.firstUserTranscript === null) {
1745
+ // First spoken user utterance — the naming seed for a session-created conversation.
1746
+ this.firstUserTranscript = transcript;
1747
+ }
1748
+ this.appendCaption({ Role: 'User', Text: transcript });
1749
+ await this.relayTranscript('user', transcript);
1750
+ }
1751
+ // ── Tool calling ───────────────────────────────────────────────────────────
1752
+ /**
1753
+ * Routes a provider tool call: names matching a registered client-tool prefix execute
1754
+ * LOCALLY (UI tools — see {@link RegisterClientToolHandler}); everything else executes on
1755
+ * the MJ server. Either way the result feeds back to the model via
1756
+ * {@link BaseRealtimeClient.SendToolResult} so it speaks the outcome.
1757
+ */
1758
+ async handleToolCall(call) {
1759
+ const clientHandler = this.findClientToolHandler(call.ToolName);
1760
+ if (clientHandler) {
1761
+ // Local UI tool: no server relay, no 'thinking' turn-state / narration burst, and intentionally
1762
+ // NO thread card — these are fast, in-browser surface mutations (e.g. drawing on the whiteboard)
1763
+ // whose visual effects are immediately visible on the dedicated canvas/surface.
1764
+ const resultJson = await this.executeClientTool(clientHandler, call);
1765
+ this.client?.SendToolResult(call.CallID, resultJson);
1766
+ // Observability: record the channel tool call on the co-agent's run (run-only — NOT a chat
1767
+ // turn). Without this the run shows speech but never the browser_/Whiteboard_ actions the
1768
+ // co-agent took. Fire-and-forget; never disturbs the live surface mutation.
1769
+ void this.relayToolTurn(call.ToolName, call.ArgumentsJson, resultJson);
1770
+ return;
1771
+ }
1772
+ this._connectionState$.next('thinking');
1773
+ if (this.inFlightCallIds.size === 0) {
1774
+ // A fresh delegation burst: anchor the first-update delay and clear the digest
1775
+ // buffer. Deliberately NOT reset: lastDelegationNarrationAt (the 8s spacing floor
1776
+ // is SESSION-global — sequential tool calls seconds apart must not re-arm the
1777
+ // faster first-update path, which read as "no debounce") and spokenNarrations
1778
+ // (so the story never repeats across closely-spaced calls).
1779
+ this.delegationBurstStartedAt = Date.now();
1780
+ this.narrationCount = 0;
1781
+ this.pendingNarrationMessages = [];
1782
+ this.lastNarratedTail = '';
1783
+ }
1784
+ this.inFlightCallIds.add(call.CallID);
1785
+ if (call.ToolName !== 'invoke-target-agent') {
1786
+ // Direct action: emit synthetic progress immediately so the conversation thread
1787
+ // and activity rail render an active "working" action card while the tool executes.
1788
+ this._delegationProgress$.next({
1789
+ CallID: call.CallID,
1790
+ ToolName: call.ToolName,
1791
+ Step: 'direct_action',
1792
+ Message: `Executing ${FormatToolName(call.ToolName)}`
1793
+ });
1794
+ }
1795
+ try {
1796
+ const resultJson = await this.executeSessionTool(call.CallID, call.ToolName, call.ArgumentsJson);
1797
+ this.emitDelegationResult(call.CallID, resultJson, call.ToolName);
1798
+ this.client?.SendToolResult(call.CallID, resultJson);
1799
+ }
1800
+ catch (error) {
1801
+ console.error('[RealtimeSession] Tool execution failed:', error);
1802
+ // Feed the error back so the model can narrate it rather than going silent.
1803
+ // success:false matters: ParseDelegationResultJson treats anything else as
1804
+ // success, which would flip the overlay's working card to a SUCCESS card
1805
+ // carrying the error text (matches the server broker's failure shape).
1806
+ const errorJson = JSON.stringify({
1807
+ success: false,
1808
+ error: error instanceof Error ? error.message : String(error)
1809
+ });
1810
+ this.emitDelegationResult(call.CallID, errorJson, call.ToolName);
1811
+ this.client?.SendToolResult(call.CallID, errorJson);
1812
+ }
1813
+ }
1814
+ /** Finds the registered client-tool handler whose prefix matches `toolName`, or `null`. */
1815
+ findClientToolHandler(toolName) {
1816
+ for (const [prefix, handler] of this.clientToolHandlers) {
1817
+ if (toolName.startsWith(prefix)) {
1818
+ return handler;
1819
+ }
1820
+ }
1821
+ return null;
1822
+ }
1823
+ /**
1824
+ * Executes one client-tool call through its handler, wrapping any thrown error into a
1825
+ * `{ success: false, error }` JSON payload so the model can narrate the failure instead of
1826
+ * the call going silent.
1827
+ */
1828
+ async executeClientTool(handler, call) {
1829
+ try {
1830
+ return await handler(call.ToolName, call.ArgumentsJson);
1831
+ }
1832
+ catch (error) {
1833
+ console.error('[RealtimeSession] Client tool execution failed:', error);
1834
+ return JSON.stringify({
1835
+ success: false,
1836
+ error: error instanceof Error ? error.message : String(error)
1837
+ });
1838
+ }
1839
+ }
1840
+ /**
1841
+ * Emits a delegation result so the overlay's "working" card flips to a result card with real
1842
+ * content. Parses the broker's `{success, output, runId}` | `{success:false, error}` shape via
1843
+ * {@link ParseDelegationResultJson}; if it isn't JSON, surfaces the raw string. The `runId`
1844
+ * (the delegated `MJ: AI Agent Runs` record) rides along as {@link RealtimeDelegationResult.RunID}
1845
+ * for the overlay's dev links, and any `artifacts` ride along as {@link RealtimeDelegationResult.Artifacts}
1846
+ * for the surface panel's artifact tabs.
1847
+ */
1848
+ emitDelegationResult(callId, resultJson, toolName) {
1849
+ // The result will be spoken next — a deferred interim update is now pointless
1850
+ // (this is what keeps fast agents like Sage from narrating over their own answer),
1851
+ // and any progress still in the PubSub pipe for this call is stale.
1852
+ this.inFlightCallIds.delete(callId);
1853
+ this.cancelPendingNarration();
1854
+ if (this.cancelledCallIds.delete(callId)) {
1855
+ // The user explicitly cancelled this call: its card already flipped to the
1856
+ // "Cancelled by user" failed result, so the aborted run's late outcome must not
1857
+ // overwrite it. (The tool result still flows back to the model via the caller.)
1858
+ return;
1859
+ }
1860
+ const parsed = ParseDelegationResultJson(resultJson);
1861
+ this._delegationResult$.next({
1862
+ CallID: callId,
1863
+ ToolName: toolName,
1864
+ Success: parsed.Success,
1865
+ Output: parsed.Output,
1866
+ RunID: parsed.RunID,
1867
+ Artifacts: parsed.Artifacts
1868
+ });
1869
+ }
1870
+ // ── Explicit delegation cancellation (server cancel channel) ───────────────
1871
+ /**
1872
+ * Cancels ONE in-flight delegated tool call — the overlay's per-card ✕ affordance.
1873
+ *
1874
+ * EXPLICIT USER INTENT ONLY (deliberate host policy): true barge-in never aborts
1875
+ * delegations — the narration design expects the user to talk while delegated work runs.
1876
+ * Calls the `CancelRealtimeSessionTool` mutation (ownership-gated server-side); when the
1877
+ * server reports it aborted the run, the card is flipped immediately to a FAILED
1878
+ * "Cancelled by user" result and the eventual late result from the aborted run is
1879
+ * suppressed (see {@link emitDelegationResult}).
1880
+ *
1881
+ * @returns `true` when the server aborted the in-flight run; `false` when there was
1882
+ * nothing to cancel (the work finished first — its real result is already racing in)
1883
+ * or the mutation failed (logged, never thrown).
1884
+ */
1885
+ async CancelDelegation(callId) {
1886
+ if (!this.agentSessionId || !this.inFlightCallIds.has(callId)) {
1887
+ return false;
1888
+ }
1889
+ const aborted = await this.cancelSessionTool(callId);
1890
+ if (aborted <= 0) {
1891
+ return false; // finished first / nothing in flight server-side — let the real result land
1892
+ }
1893
+ this.surfaceUserCancellation(callId);
1894
+ return true;
1895
+ }
1896
+ /**
1897
+ * Cancels EVERY in-flight delegated tool call for the active session (callId-less form of
1898
+ * the `CancelRealtimeSessionTool` mutation). Exposed for host policies that need a
1899
+ * sweep-cancel (e.g. an explicit "stop everything" affordance) — NOT wired to barge-in,
1900
+ * by the same deliberate policy as {@link CancelDelegation}.
1901
+ *
1902
+ * @returns The number of in-flight runs the server aborted (0 when nothing was tracked
1903
+ * in flight client-side, nothing was in flight server-side, or the mutation failed).
1904
+ */
1905
+ async CancelInFlightDelegations() {
1906
+ if (!this.agentSessionId || this.inFlightCallIds.size === 0) {
1907
+ return 0;
1908
+ }
1909
+ const aborted = await this.cancelSessionTool(null);
1910
+ if (aborted <= 0) {
1911
+ return 0;
1912
+ }
1913
+ for (const callId of [...this.inFlightCallIds]) {
1914
+ this.surfaceUserCancellation(callId);
1915
+ }
1916
+ return aborted;
1917
+ }
1918
+ /** Flips a cancelled call's card to the failed "Cancelled by user" result and suppresses the late real result. */
1919
+ surfaceUserCancellation(callId) {
1920
+ this.inFlightCallIds.delete(callId);
1921
+ this.cancelledCallIds.add(callId);
1922
+ this.cancelPendingNarration();
1923
+ this._delegationResult$.next({
1924
+ CallID: callId,
1925
+ Success: false,
1926
+ Output: 'Cancelled by user'
1927
+ });
1928
+ }
1929
+ /**
1930
+ * Calls the `CancelRealtimeSessionTool` mutation and unwraps its structured
1931
+ * `{ AbortedCount, Success, ErrorMessage }` result. Returns the aborted count —
1932
+ * 0 on a structured failure or a thrown transport error (both logged, never thrown).
1933
+ */
1934
+ async cancelSessionTool(callId) {
1935
+ try {
1936
+ const mutation = `
1937
+ mutation CancelRealtimeSessionTool($agentSessionId: String!, $callId: String) {
1938
+ CancelRealtimeSessionTool(agentSessionId: $agentSessionId, callId: $callId) {
1939
+ AbortedCount
1940
+ Success
1941
+ ErrorMessage
1942
+ }
1943
+ }
1944
+ `;
1945
+ const result = await this.gql().ExecuteGQL(mutation, { agentSessionId: this.agentSessionId, callId });
1946
+ const payload = result?.CancelRealtimeSessionTool;
1947
+ if (!payload?.Success) {
1948
+ console.warn(`[RealtimeSession] Cancel reported failure: ${payload?.ErrorMessage ?? 'unknown error'}`);
1949
+ return 0;
1950
+ }
1951
+ return typeof payload.AbortedCount === 'number' ? payload.AbortedCount : 0;
1952
+ }
1953
+ catch (error) {
1954
+ console.error('[RealtimeSession] Failed to cancel in-flight delegation(s):', error);
1955
+ return 0;
1956
+ }
1957
+ }
1958
+ // ── Session minting (GraphQL) ──────────────────────────────────────────────
1959
+ /** Calls the `StartRealtimeClientSession` mutation to obtain an ephemeral token + config. */
1960
+ async mintSession(targetAgentId, conversationId, lastSessionId, preferredModelId, clientTools, coAgentId, configOverridesJson, recordingConsent, recordingStartedAt, mediaCollectionId, applicationId, appContext) {
1961
+ const mutation = `
1962
+ mutation StartRealtimeClientSession($targetAgentId: String!, $conversationId: String, $lastSessionId: String, $preferredModelId: String, $clientToolsJson: String, $coAgentId: String, $configOverridesJson: String, $recordingConsent: Boolean, $recordingStartedAt: String, $mediaCollectionId: String, $applicationId: String, $appContextJson: String) {
1963
+ StartRealtimeClientSession(targetAgentId: $targetAgentId, conversationId: $conversationId, lastSessionId: $lastSessionId, preferredModelId: $preferredModelId, clientToolsJson: $clientToolsJson, coAgentId: $coAgentId, configOverridesJson: $configOverridesJson, recordingConsent: $recordingConsent, recordingStartedAt: $recordingStartedAt, mediaCollectionId: $mediaCollectionId, applicationId: $applicationId, appContextJson: $appContextJson) {
1964
+ AgentSessionId
1965
+ ConversationId
1966
+ Provider
1967
+ Model
1968
+ EphemeralToken
1969
+ ExpiresAt
1970
+ SessionConfigJson
1971
+ ModelName
1972
+ NarrationInstructionsTemplate
1973
+ PriorChannelStatesJson
1974
+ }
1975
+ }
1976
+ `;
1977
+ const variables = {
1978
+ targetAgentId,
1979
+ conversationId: conversationId ?? null,
1980
+ lastSessionId: lastSessionId ?? null,
1981
+ preferredModelId: preferredModelId ?? null,
1982
+ clientToolsJson: clientTools && clientTools.length > 0 ? JSON.stringify(clientTools) : null,
1983
+ coAgentId: coAgentId ?? null,
1984
+ configOverridesJson: configOverridesJson ?? null,
1985
+ recordingConsent: recordingConsent ?? false,
1986
+ recordingStartedAt: recordingStartedAt ?? null,
1987
+ mediaCollectionId: mediaCollectionId ?? null,
1988
+ applicationId: applicationId ?? null,
1989
+ appContextJson: appContext ? JSON.stringify(appContext) : null
1990
+ };
1991
+ const result = await this.gql().ExecuteGQL(mutation, variables);
1992
+ const payload = result?.StartRealtimeClientSession;
1993
+ if (!payload?.EphemeralToken) {
1994
+ throw new Error('StartRealtimeClientSession returned no ephemeral token');
1995
+ }
1996
+ return payload;
1997
+ }
1998
+ /** Calls the `ExecuteRealtimeSessionTool` mutation; returns the ResultJson string. */
1999
+ async executeSessionTool(callId, toolName, argsJson) {
2000
+ if (!this.agentSessionId) {
2001
+ throw new Error('No active agent session for tool execution');
2002
+ }
2003
+ const mutation = `
2004
+ mutation ExecuteRealtimeSessionTool($agentSessionId: String!, $callId: String!, $toolName: String!, $argsJson: String!) {
2005
+ ExecuteRealtimeSessionTool(agentSessionId: $agentSessionId, callId: $callId, toolName: $toolName, argsJson: $argsJson)
2006
+ }
2007
+ `;
2008
+ const result = await this.gql().ExecuteGQL(mutation, {
2009
+ agentSessionId: this.agentSessionId,
2010
+ callId,
2011
+ toolName,
2012
+ argsJson
2013
+ });
2014
+ return result?.ExecuteRealtimeSessionTool ?? '{}';
2015
+ }
2016
+ /**
2017
+ * Persists an interactive channel's state of record (e.g. the whiteboard's serialized scene)
2018
+ * onto the session's `MJ: AI Agent Session Channels` row via `SaveSessionChannelState`.
2019
+ *
2020
+ * @param channelName The channel definition name (e.g. `'Whiteboard'`).
2021
+ * @param stateJson The serialized channel state.
2022
+ * @param agentSessionId Optional EXPLICIT session id. The debounced channel-save pipeline
2023
+ * captures the id while the session is live and passes it here, so the final teardown
2024
+ * flush still lands on the just-closed session. Falls back to the active session's id;
2025
+ * returns `false` when neither is available.
2026
+ * @returns Whether the server persisted the state. Failures are logged, never thrown — channel
2027
+ * persistence is best-effort and must not disturb the live call.
2028
+ */
2029
+ async SaveChannelState(channelName, stateJson, agentSessionId) {
2030
+ const sessionId = agentSessionId ?? this.agentSessionId;
2031
+ if (!sessionId) {
2032
+ return false;
2033
+ }
2034
+ try {
2035
+ const mutation = `
2036
+ mutation SaveSessionChannelState($agentSessionId: String!, $channelName: String!, $stateJson: String!) {
2037
+ SaveSessionChannelState(agentSessionId: $agentSessionId, channelName: $channelName, stateJson: $stateJson)
2038
+ }
2039
+ `;
2040
+ const result = await this.gql().ExecuteGQL(mutation, { agentSessionId: sessionId, channelName, stateJson });
2041
+ return result?.SaveSessionChannelState ?? false;
2042
+ }
2043
+ catch (error) {
2044
+ console.error('[RealtimeSession] Failed to save channel state:', error);
2045
+ return false;
2046
+ }
2047
+ }
2048
+ // ── Transcript relay (GraphQL) ─────────────────────────────────────────────
2049
+ /**
2050
+ * Relays a final transcript turn to MJ via `RelayRealtimeTranscript`.
2051
+ *
2052
+ * When the session is being recorded, per-turn timing rides along: `utteranceEndMs` is the
2053
+ * recording-relative offset at finalization, and `utteranceStartMs` is the offset captured by
2054
+ * {@link markTurnAudioStart} when THIS turn's audio actually began (its first interim) — NOT
2055
+ * inherited from the previous turn's end. That distinction is the timing fix: when a tool-call
2056
+ * / silence gap sits between turns, the post-gap turn's audio starts much later, so inheriting
2057
+ * the prior turn's end stamped the cue ~gap-length too early. Both are omitted (left `null`)
2058
+ * when the session isn't being recorded.
2059
+ *
2060
+ * A correction (`replacesPrevious`) doesn't open a new turn, so it carries no start and doesn't
2061
+ * reset the per-turn start guard. After a normal finalization the guard is cleared so the NEXT
2062
+ * turn re-stamps its start from where ITS audio begins.
2063
+ *
2064
+ * @param replacesPrevious CORRECTION semantics: the server updates the session's most
2065
+ * recent persisted turn of this role IN PLACE instead of appending (e.g. ElevenLabs'
2066
+ * post-barge-in `agent_response_correction`).
2067
+ */
2068
+ async relayTranscript(role, text, replacesPrevious = false) {
2069
+ if (!this.agentSessionId) {
2070
+ return;
2071
+ }
2072
+ // Per-turn timing against whichever clock the session is on (#3832): the recorder's when one
2073
+ // runs, else the session clock. `utteranceStartMs` is where this turn's audio actually began
2074
+ // (captured by markTurnAudioStart on the first interim); the `?? 0` fallback covers a turn
2075
+ // whose interim was missed / a final-only first turn.
2076
+ const utteranceEndMs = this.nowTurnOffsetMs();
2077
+ const utteranceStartMs = utteranceEndMs !== null && !replacesPrevious ? (this.currentTurnStartMs ?? 0) : null;
2078
+ if (utteranceEndMs !== null && !replacesPrevious) {
2079
+ // This turn is finalized — arm the NEXT turn to re-stamp its start from its own first
2080
+ // interim (handles a tool-call gap before the next turn). Stop inheriting this end as the
2081
+ // next start. `null` means "not yet captured"; relay falls back to `?? 0` if no interim fires.
2082
+ this.currentTurnStartMs = null;
2083
+ this.turnAudioStartCaptured = false;
2084
+ }
2085
+ try {
2086
+ const mutation = `
2087
+ mutation RelayRealtimeTranscript($agentSessionId: String!, $role: String!, $text: String!, $replacesPrevious: Boolean, $utteranceStartMs: Int, $utteranceEndMs: Int) {
2088
+ RelayRealtimeTranscript(agentSessionId: $agentSessionId, role: $role, text: $text, replacesPrevious: $replacesPrevious, utteranceStartMs: $utteranceStartMs, utteranceEndMs: $utteranceEndMs)
2089
+ }
2090
+ `;
2091
+ await this.gql().ExecuteGQL(mutation, {
2092
+ agentSessionId: this.agentSessionId,
2093
+ role,
2094
+ text,
2095
+ replacesPrevious,
2096
+ utteranceStartMs,
2097
+ utteranceEndMs
2098
+ });
2099
+ }
2100
+ catch (error) {
2101
+ console.error('[RealtimeSession] Failed to relay transcript:', error);
2102
+ }
2103
+ }
2104
+ /**
2105
+ * Relays a co-agent CHANNEL tool-call turn (browser_ / Whiteboard_ etc.) to the session's run for
2106
+ * observability via `RelayRealtimeToolTurn` — so the co-agent's AIPromptRun shows what it DID, not
2107
+ * just what it said. Run-only by design: deliberately NOT a `ConversationDetail` turn, so the chat
2108
+ * thread stays speech-only. Best-effort — a failed relay never disturbs the live call.
2109
+ */
2110
+ async relayToolTurn(toolName, argsJson, resultJson) {
2111
+ if (!this.agentSessionId) {
2112
+ return;
2113
+ }
2114
+ try {
2115
+ const mutation = `
2116
+ mutation RelayRealtimeToolTurn($agentSessionId: String!, $toolName: String!, $argsJson: String, $resultJson: String) {
2117
+ RelayRealtimeToolTurn(agentSessionId: $agentSessionId, toolName: $toolName, argsJson: $argsJson, resultJson: $resultJson)
2118
+ }
2119
+ `;
2120
+ await this.gql().ExecuteGQL(mutation, {
2121
+ agentSessionId: this.agentSessionId,
2122
+ toolName,
2123
+ argsJson,
2124
+ resultJson
2125
+ });
2126
+ }
2127
+ catch (error) {
2128
+ console.error('[RealtimeSession] Failed to relay tool turn:', error);
2129
+ }
2130
+ }
2131
+ // ── Usage telemetry relay (B7) ─────────────────────────────────────────────
2132
+ /**
2133
+ * Accumulates one usage DELTA from the realtime client (per-response token counts —
2134
+ * the `OnUsage` contract shape) and schedules the debounced relay. Negative / non-finite
2135
+ * values are clamped to 0; an all-zero delta is dropped without arming the timer.
2136
+ */
2137
+ onUsageDelta(usage) {
2138
+ const input = this.clampUsageDelta(usage.InputTokens);
2139
+ const output = this.clampUsageDelta(usage.OutputTokens);
2140
+ if (input === 0 && output === 0) {
2141
+ return;
2142
+ }
2143
+ this.pendingUsageInput += input;
2144
+ this.pendingUsageOutput += output;
2145
+ if (!this.usageFlushTimer) {
2146
+ this.usageFlushTimer = setTimeout(() => {
2147
+ this.usageFlushTimer = null;
2148
+ void this.flushPendingUsage();
2149
+ }, RealtimeSessionRuntime.UsageFlushDebounceMs);
2150
+ }
2151
+ }
2152
+ /** Clamps a driver-reported token delta: undefined / negative / non-finite become 0. */
2153
+ clampUsageDelta(value) {
2154
+ return typeof value === 'number' && Number.isFinite(value) && value > 0 ? Math.floor(value) : 0;
2155
+ }
2156
+ /**
2157
+ * Relays the accumulated usage deltas to the server via `RelayRealtimeUsage` (which
2158
+ * accumulates them onto the co-agent `AIPromptRun`). Best-effort: a failed relay
2159
+ * re-accumulates the captured deltas so the next debounce / teardown flush retries —
2160
+ * usage telemetry must never disturb the live call.
2161
+ *
2162
+ * @param agentSessionId Optional EXPLICIT session id (the teardown flush runs while the
2163
+ * live id is still set, but accepts it as a parameter for symmetry with channel saves).
2164
+ */
2165
+ async flushPendingUsage(agentSessionId) {
2166
+ const sessionId = agentSessionId ?? this.agentSessionId;
2167
+ const input = this.pendingUsageInput;
2168
+ const output = this.pendingUsageOutput;
2169
+ if (!sessionId || (input === 0 && output === 0)) {
2170
+ return;
2171
+ }
2172
+ this.pendingUsageInput = 0;
2173
+ this.pendingUsageOutput = 0;
2174
+ try {
2175
+ const mutation = `
2176
+ mutation RelayRealtimeUsage($agentSessionId: String!, $inputTokens: Int!, $outputTokens: Int!) {
2177
+ RelayRealtimeUsage(agentSessionId: $agentSessionId, inputTokens: $inputTokens, outputTokens: $outputTokens)
2178
+ }
2179
+ `;
2180
+ await this.gql().ExecuteGQL(mutation, { agentSessionId: sessionId, inputTokens: input, outputTokens: output });
2181
+ }
2182
+ catch (error) {
2183
+ console.error('[RealtimeSession] Failed to relay usage telemetry:', error);
2184
+ // Re-accumulate so a later debounce / the teardown flush retries the same deltas.
2185
+ this.pendingUsageInput += input;
2186
+ this.pendingUsageOutput += output;
2187
+ }
2188
+ }
2189
+ /** Cancels the pending debounced usage flush and zeroes the accumulators (teardown tail). */
2190
+ resetUsageRelay() {
2191
+ if (this.usageFlushTimer) {
2192
+ clearTimeout(this.usageFlushTimer);
2193
+ this.usageFlushTimer = null;
2194
+ }
2195
+ this.pendingUsageInput = 0;
2196
+ this.pendingUsageOutput = 0;
2197
+ }
2198
+ // ── Delegated-run progress streaming ───────────────────────────────────────
2199
+ /**
2200
+ * Subscribes to the server's push-status topic (scoped by the GraphQL transport
2201
+ * sessionId) to receive delegated-run progress for the active voice session.
2202
+ * Each matching event is surfaced on {@link DelegationProgress$} and narrated.
2203
+ */
2204
+ subscribeDelegationProgress() {
2205
+ if (this.delegationProgressSub) {
2206
+ return; // already subscribed for this session
2207
+ }
2208
+ const transportSessionId = this.gql().sessionId;
2209
+ this.lastDelegationNarrationAt = 0;
2210
+ this.delegationProgressSub = this.gql()
2211
+ .PushStatusUpdates(transportSessionId)
2212
+ .subscribe({
2213
+ next: (raw) => this.onDelegationStatusMessage(raw),
2214
+ error: (err) => console.error('[RealtimeSession] Delegation progress stream error:', err)
2215
+ });
2216
+ }
2217
+ /**
2218
+ * Parses one push-status message and routes it: a Remote Browser screencast frame goes to the active
2219
+ * Remote Browser channel's canvas; a delegation-progress event is dispatched + narrated. Other shapes
2220
+ * (normal agent-run streams) are ignored. Screencast frames are checked FIRST and short-circuit, so the
2221
+ * delegation path is untouched.
2222
+ */
2223
+ onDelegationStatusMessage(raw) {
2224
+ const frame = this.parseScreencastFrame(raw);
2225
+ if (frame) {
2226
+ this.routeScreencastFrame(frame);
2227
+ return;
2228
+ }
2229
+ const audio = this.parseAudioChunk(raw);
2230
+ if (audio) {
2231
+ this.routeAudioChunk(audio);
2232
+ return;
2233
+ }
2234
+ const progress = this.parseProgress(raw);
2235
+ if (progress) {
2236
+ this.dispatchProgress(progress);
2237
+ }
2238
+ }
2239
+ /**
2240
+ * Parses a push-status message and returns it only when it's a Remote Browser screencast frame for the
2241
+ * active session — otherwise `null` (ignored, so delegation progress falls through). Matched by
2242
+ * `resolver` + `type`, then scoped to THIS session by `agentSessionID`.
2243
+ */
2244
+ parseScreencastFrame(raw) {
2245
+ let payload;
2246
+ try {
2247
+ payload = JSON.parse(raw);
2248
+ }
2249
+ catch {
2250
+ return null;
2251
+ }
2252
+ const matches = payload?.resolver === 'RemoteBrowserActionResolver' &&
2253
+ payload?.type === 'RemoteBrowserScreencastFrame' &&
2254
+ payload?.agentSessionID === this.agentSessionId &&
2255
+ typeof payload?.dataBase64 === 'string';
2256
+ return matches ? payload : null;
2257
+ }
2258
+ /**
2259
+ * Forwards a screencast frame to the active Remote Browser channel plugin so it paints the frame on its
2260
+ * surface canvas. The plugin is found among the session's active channels by its `ChannelName`; located
2261
+ * via a structural guard so the service stays decoupled from the concrete channel class.
2262
+ */
2263
+ routeScreencastFrame(frame) {
2264
+ for (const channel of this._activeChannels$.value) {
2265
+ if (channel.ChannelName === 'Remote Browser' && this.hasOnScreencastFrame(channel)) {
2266
+ // The URL rides along so the channel can notice a page change nobody on this side caused —
2267
+ // under streaming the snapshot poll is stopped, and frames were pure pixels (#3496).
2268
+ channel.OnScreencastFrame(frame.dataBase64, frame.currentUrl ?? null);
2269
+ return;
2270
+ }
2271
+ }
2272
+ }
2273
+ /** Structural guard: true when the channel exposes an `OnScreencastFrame(dataBase64)` method. */
2274
+ hasOnScreencastFrame(channel) {
2275
+ return typeof channel.OnScreencastFrame === 'function';
2276
+ }
2277
+ /**
2278
+ * Parses a push-status message and returns it only when it's a Remote Browser audio chunk for the active
2279
+ * session — otherwise `null` (ignored). Matched by `resolver` + `type`, then scoped to THIS session by
2280
+ * `agentSessionID`.
2281
+ */
2282
+ parseAudioChunk(raw) {
2283
+ let payload;
2284
+ try {
2285
+ payload = JSON.parse(raw);
2286
+ }
2287
+ catch {
2288
+ return null;
2289
+ }
2290
+ const matches = payload?.resolver === 'RemoteBrowserActionResolver' &&
2291
+ payload?.type === 'RemoteBrowserAudioChunk' &&
2292
+ payload?.agentSessionID === this.agentSessionId &&
2293
+ typeof payload?.dataBase64 === 'string';
2294
+ return matches ? payload : null;
2295
+ }
2296
+ /**
2297
+ * Forwards an audio chunk to the active Remote Browser channel plugin so it plays the chunk through its
2298
+ * client-side audio player. The plugin is found among the session's active channels by its `ChannelName`;
2299
+ * located via a structural guard so the service stays decoupled from the concrete channel class.
2300
+ */
2301
+ routeAudioChunk(chunk) {
2302
+ for (const channel of this._activeChannels$.value) {
2303
+ if (channel.ChannelName === 'Remote Browser' && this.hasOnAudioChunk(channel)) {
2304
+ channel.OnAudioChunk({
2305
+ dataBase64: chunk.dataBase64,
2306
+ codec: chunk.codec,
2307
+ sampleRate: chunk.sampleRate,
2308
+ channels: chunk.channels,
2309
+ seq: chunk.seq,
2310
+ });
2311
+ return;
2312
+ }
2313
+ }
2314
+ }
2315
+ /** Structural guard: true when the channel exposes an `OnAudioChunk(chunk)` method. */
2316
+ hasOnAudioChunk(channel) {
2317
+ return typeof channel.OnAudioChunk === 'function';
2318
+ }
2319
+ /**
2320
+ * Parses a push-status message and returns it only when it's a delegation
2321
+ * progress event for the active voice session — otherwise `null` (ignored).
2322
+ */
2323
+ parseProgress(raw) {
2324
+ let payload;
2325
+ try {
2326
+ payload = JSON.parse(raw);
2327
+ }
2328
+ catch {
2329
+ return null; // non-JSON or unrelated frame
2330
+ }
2331
+ const matches = payload?.resolver === 'RealtimeClientSessionResolver' &&
2332
+ payload?.type === 'RealtimeDelegationProgress' &&
2333
+ payload?.agentSessionID === this.agentSessionId;
2334
+ if (!matches) {
2335
+ return null;
2336
+ }
2337
+ return {
2338
+ CallID: payload.callID,
2339
+ Step: payload.step,
2340
+ Message: payload.message,
2341
+ Percentage: payload.percentage
2342
+ };
2343
+ }
2344
+ /** Emits the progress to the UI observable and feeds it to the realtime model. */
2345
+ dispatchProgress(progress) {
2346
+ // Drop stale progress: PubSub delivery can lag the mutation result, so events for a
2347
+ // call that already completed (or was never seen) must not update cards or narrate.
2348
+ if (!this.inFlightCallIds.has(progress.CallID)) {
2349
+ return;
2350
+ }
2351
+ this._delegationProgress$.next(progress);
2352
+ this.narrateProgress(progress);
2353
+ }
2354
+ /**
2355
+ * Injects the progress into the model's context as a background note every time,
2356
+ * then (throttled) asks the model to briefly voice a reassuring update so the
2357
+ * background work doesn't sit in silence — without chattering or interrupting.
2358
+ */
2359
+ narrateProgress(progress) {
2360
+ const client = this.client;
2361
+ if (!client) {
2362
+ return;
2363
+ }
2364
+ client.SendContextNote(`[delegated-agent progress] ${progress.Message}`);
2365
+ // Floods of small updates AGGREGATE: each distinct message joins the digest buffer,
2366
+ // and ONE spoken update fires per window (first at ~5s into the burst, then every
2367
+ // ~8s). The buffer is discarded if the final result lands first.
2368
+ this.bufferNarrationMessage(progress.Message);
2369
+ if (this.pendingNarrationMessages.length > 0 && !this.narrationTimer) {
2370
+ this.narrationTimer = setTimeout(() => this.fireDeferredNarration(), this.nextNarrationDelayMs());
2371
+ }
2372
+ }
2373
+ /** Adds a progress message to the digest buffer (deduped, capped, oldest-first). */
2374
+ bufferNarrationMessage(message) {
2375
+ if (message === this.lastNarratedTail || this.pendingNarrationMessages.includes(message)) {
2376
+ return;
2377
+ }
2378
+ this.pendingNarrationMessages.push(message);
2379
+ if (this.pendingNarrationMessages.length > RealtimeSessionRuntime.MaxDigestMessages) {
2380
+ this.pendingNarrationMessages.shift();
2381
+ }
2382
+ }
2383
+ /**
2384
+ * ms until the next spoken update is allowed. Two constraints, BOTH enforced:
2385
+ * - first update of a burst: no earlier than ~5s after the burst started;
2386
+ * - ~8s since the last spoken update, SESSION-global — so sequential tool calls
2387
+ * that reset the burst can never narrate faster than the interval.
2388
+ */
2389
+ nextNarrationDelayMs() {
2390
+ const now = Date.now();
2391
+ const firstAnchor = this.narrationCount === 0
2392
+ ? this.delegationBurstStartedAt + RealtimeSessionRuntime.FirstNarrationDelayMs
2393
+ : 0;
2394
+ const spacingFloor = this.lastDelegationNarrationAt > 0
2395
+ ? this.lastDelegationNarrationAt + RealtimeSessionRuntime.NarrationIntervalMs
2396
+ : 0;
2397
+ return Math.max(250, Math.max(firstAnchor, spacingFloor) - now);
2398
+ }
2399
+ /**
2400
+ * Speaks the aggregated progress digest — unless the work already finished (buffer
2401
+ * cancelled) or the model is busy / audio is still playing, in which case it retries
2402
+ * shortly with the buffer intact (work is still running, so the update stays relevant).
2403
+ */
2404
+ fireDeferredNarration() {
2405
+ this.narrationTimer = null;
2406
+ const client = this.client;
2407
+ if (this.pendingNarrationMessages.length === 0 || !client || this.inFlightCallIds.size === 0) {
2408
+ this.pendingNarrationMessages = [];
2409
+ return;
2410
+ }
2411
+ if (client.IsBusy || client.IsAudioPlaying) {
2412
+ this.narrationTimer = setTimeout(() => this.fireDeferredNarration(), RealtimeSessionRuntime.NarrationBusyRetryMs);
2413
+ return;
2414
+ }
2415
+ const digest = this.pendingNarrationMessages.join(' → ');
2416
+ this.lastNarratedTail = this.pendingNarrationMessages[this.pendingNarrationMessages.length - 1];
2417
+ this.pendingNarrationMessages = [];
2418
+ this.narrationCount++;
2419
+ this.lastDelegationNarrationAt = Date.now();
2420
+ client.RequestSpokenUpdate(this.buildNarrationInstructions(digest));
2421
+ }
2422
+ /** Cancels any deferred narration — the result is about to be spoken, so it's moot. */
2423
+ cancelPendingNarration() {
2424
+ if (this.narrationTimer) {
2425
+ clearTimeout(this.narrationTimer);
2426
+ this.narrationTimer = null;
2427
+ }
2428
+ this.pendingNarrationMessages = [];
2429
+ }
2430
+ /**
2431
+ * Builds the one-off instructions for a short spoken update that conveys THIS specific
2432
+ * progress message naturally — strictly first person, since the co-agent owns the work.
2433
+ * The wording is DB-driven: the server-resolved `Realtime Co-Agent - Progress Narration`
2434
+ * template (substituting `{{ progressMessage }}`) when present, otherwise the built-in
2435
+ * fallback so deployments that haven't synced the prompt behave exactly as before.
2436
+ * The client tags the resulting turn as narration, keeping it EPHEMERAL — surfaced on
2437
+ * {@link DelegationNarration$} instead of becoming a caption / persisted ConversationDetail.
2438
+ */
2439
+ buildNarrationInstructions(digest) {
2440
+ return BuildNarrationInstructions(this.narrationTemplate, digest, {
2441
+ PriorNarrations: this.spokenNarrations.slice(-RealtimeSessionRuntime.MaxPriorNarrations),
2442
+ UpdateNumber: this.narrationCount
2443
+ });
2444
+ }
2445
+ /** Tears down the delegation progress subscription and resets the narration throttle. */
2446
+ teardownDelegationProgress() {
2447
+ if (this.delegationProgressSub) {
2448
+ this.delegationProgressSub.unsubscribe();
2449
+ this.delegationProgressSub = null;
2450
+ }
2451
+ this.cancelPendingNarration();
2452
+ this.inFlightCallIds.clear();
2453
+ this.cancelledCallIds.clear();
2454
+ this.lastDelegationNarrationAt = 0;
2455
+ this.delegationBurstStartedAt = 0;
2456
+ this.narrationCount = 0;
2457
+ this.spokenNarrations = [];
2458
+ this.lastNarratedTail = '';
2459
+ }
2460
+ // ── Teardown ───────────────────────────────────────────────────────────────
2461
+ /**
2462
+ * Tears down all client resources and (optionally) closes the server session.
2463
+ * @param closeServerSession when true, calls `CloseAgentSession` on the server.
2464
+ */
2465
+ async teardown(closeServerSession) {
2466
+ // Invalidate any start still in flight BEFORE anything else, so it abandons itself at its next
2467
+ // await rather than opening a microphone behind a session that is being ended.
2468
+ this.startGeneration++;
2469
+ // Coalesce concurrent teardowns onto one run. Callers still get a promise that resolves when
2470
+ // teardown is actually complete.
2471
+ if (this.teardownInFlight) {
2472
+ await this.teardownInFlight;
2473
+ return;
2474
+ }
2475
+ this.teardownInFlight = this.runTeardown(closeServerSession).finally(() => {
2476
+ this.teardownInFlight = null;
2477
+ });
2478
+ await this.teardownInFlight;
2479
+ }
2480
+ /** The body of {@link teardown}; never called concurrently with itself. */
2481
+ async runTeardown(closeServerSession) {
2482
+ // First: stop asserting liveness. A pulse racing the close would re-stamp LastActiveAt on a
2483
+ // session we are deliberately ending, leaving an Idle row the janitor then has to age out.
2484
+ this.stopLivenessPulse();
2485
+ this.teardownDelegationProgress();
2486
+ // Channels first: flush any unsaved channel state WHILE the live session id is still
2487
+ // set (the captured per-save id covers the race anyway), then dispose the plugins.
2488
+ this.flushAllChannelSaves();
2489
+ this.disposeChannels();
2490
+ // Defensive: stop the mic even when Connect never ran (the client also stops the
2491
+ // tracks it was handed — track.stop() is idempotent).
2492
+ this.localStream?.getTracks().forEach(t => t.stop());
2493
+ this.localStream = null;
2494
+ // Hand the platform back whatever acquiring the microphone changed. Stopping the tracks is not
2495
+ // the same thing: iOS, for instance, is put into a record-and-play audio category for the call,
2496
+ // and leaving it there changes the route and volume behaviour of every sound the app makes
2497
+ // afterwards. Best-effort by contract — a failure here must never block ending a call.
2498
+ try {
2499
+ await this.mediaHost.ReleaseMicrophone?.();
2500
+ }
2501
+ catch (error) {
2502
+ console.error('[RealtimeSession] Media host failed to release the microphone:', error);
2503
+ }
2504
+ if (this.client) {
2505
+ await this.client.Disconnect();
2506
+ this.client = null;
2507
+ }
2508
+ // Stop + upload the call recording WHILE the live session id is still set (the file is
2509
+ // attached to it). Best-effort and never blocks teardown — stopAndUploadRecording swallows
2510
+ // its own errors. No-op when nothing was recorded.
2511
+ await this.stopAndUploadRecording(this.agentSessionId);
2512
+ this.recordingStartedAtIso = null;
2513
+ // Final usage flush WHILE the live session id is still set (the relay mutation also
2514
+ // accepts a Closed session, so ordering vs. CloseAgentSession is belt-and-braces).
2515
+ if (this.usageFlushTimer) {
2516
+ clearTimeout(this.usageFlushTimer);
2517
+ this.usageFlushTimer = null;
2518
+ }
2519
+ await this.flushPendingUsage(this.agentSessionId);
2520
+ this.resetUsageRelay();
2521
+ if (closeServerSession && this.agentSessionId) {
2522
+ await this.closeServerSession(this.agentSessionId);
2523
+ }
2524
+ // Capture the session id BEFORE we null it so the lifecycle emit carries it.
2525
+ // Skip emitting when there was no live session (defensive — teardown is safe
2526
+ // to call without an active session).
2527
+ const closedSessionId = this.agentSessionId;
2528
+ this.agentSessionId = null;
2529
+ this.narrationTemplate = null;
2530
+ this.clientToolHandlers.clear();
2531
+ this._modelName$.next(null);
2532
+ this.SetMinimized(false);
2533
+ this._active$.next(false);
2534
+ if (this._connectionState$.value !== 'error') {
2535
+ this._connectionState$.next('closed');
2536
+ }
2537
+ // Surface generic session-ended for the conversations runtime bridge.
2538
+ // `closeServerSession=true` means the user explicitly called EndRealtimeSession;
2539
+ // `false` means teardown ran from a catch block (start path error path).
2540
+ if (closedSessionId) {
2541
+ this._sessionEnded$.next({
2542
+ sessionId: closedSessionId,
2543
+ reason: closeServerSession ? 'explicit' : 'error',
2544
+ });
2545
+ }
2546
+ }
2547
+ /** Calls the `CloseAgentSession` mutation (provisioned in P4b). */
2548
+ async closeServerSession(agentSessionId) {
2549
+ try {
2550
+ const mutation = `
2551
+ mutation CloseAgentSession($agentSessionId: String!) {
2552
+ CloseAgentSession(agentSessionId: $agentSessionId)
2553
+ }
2554
+ `;
2555
+ await this.gql().ExecuteGQL(mutation, { agentSessionId });
2556
+ }
2557
+ catch (error) {
2558
+ console.error('[RealtimeSession] Failed to close server session:', error);
2559
+ }
2560
+ }
2561
+ // ── Helpers ────────────────────────────────────────────────────────────────
2562
+ /** Pushes a caption onto the live list (immutable update for change detection). */
2563
+ appendCaption(caption) {
2564
+ this._captions$.next([...this._captions$.value, caption]);
2565
+ }
2566
+ /** Resets reactive + internal state at the start of a session. */
2567
+ resetState() {
2568
+ this._captions$.next([]);
2569
+ this.pendingUserCaption = '';
2570
+ this.hasActiveInterimUserCaption = false;
2571
+ this.SetMinimized(false);
2572
+ this.stopSegmentFlushing();
2573
+ this.segmentIndex = 0;
2574
+ this.recorder = null;
2575
+ this.recordingStartedAtIso = null;
2576
+ this.currentTurnStartMs = null;
2577
+ this.turnAudioStartCaptured = false;
2578
+ this.usedChannelNames.clear();
2579
+ }
2580
+ /** The GraphQL provider used for relay mutations. */
2581
+ gql() {
2582
+ return this.Provider;
2583
+ }
2584
+ }
2585
+ //# sourceMappingURL=RealtimeSessionRuntime.js.map