@memberjunction/ai-bridge-server 0.0.1 → 5.42.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/README.md +120 -42
  2. package/dist/ai-bridge-engine.d.ts +663 -0
  3. package/dist/ai-bridge-engine.d.ts.map +1 -0
  4. package/dist/ai-bridge-engine.js +1085 -0
  5. package/dist/ai-bridge-engine.js.map +1 -0
  6. package/dist/calendar-source.d.ts +142 -0
  7. package/dist/calendar-source.d.ts.map +1 -0
  8. package/dist/calendar-source.js +63 -0
  9. package/dist/calendar-source.js.map +1 -0
  10. package/dist/calendar-watcher.d.ts +174 -0
  11. package/dist/calendar-watcher.d.ts.map +1 -0
  12. package/dist/calendar-watcher.js +248 -0
  13. package/dist/calendar-watcher.js.map +1 -0
  14. package/dist/identity-provisioner.d.ts +109 -0
  15. package/dist/identity-provisioner.d.ts.map +1 -0
  16. package/dist/identity-provisioner.js +71 -0
  17. package/dist/identity-provisioner.js.map +1 -0
  18. package/dist/index.d.ts +9 -0
  19. package/dist/index.d.ts.map +1 -0
  20. package/dist/index.js +9 -0
  21. package/dist/index.js.map +1 -0
  22. package/dist/join-url-resolver.d.ts +37 -0
  23. package/dist/join-url-resolver.d.ts.map +1 -0
  24. package/dist/join-url-resolver.js +102 -0
  25. package/dist/join-url-resolver.js.map +1 -0
  26. package/dist/loopback-bridge.d.ts +165 -0
  27. package/dist/loopback-bridge.d.ts.map +1 -0
  28. package/dist/loopback-bridge.js +255 -0
  29. package/dist/loopback-bridge.js.map +1 -0
  30. package/dist/multi-agent-room-coordinator.d.ts +198 -0
  31. package/dist/multi-agent-room-coordinator.d.ts.map +1 -0
  32. package/dist/multi-agent-room-coordinator.js +296 -0
  33. package/dist/multi-agent-room-coordinator.js.map +1 -0
  34. package/dist/scheduled-bridge-runner.d.ts +126 -0
  35. package/dist/scheduled-bridge-runner.d.ts.map +1 -0
  36. package/dist/scheduled-bridge-runner.js +140 -0
  37. package/dist/scheduled-bridge-runner.js.map +1 -0
  38. package/package.json +34 -7
@@ -0,0 +1,1085 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ import { LogError, LogStatus, RunView, RegisterForStartup, } from '@memberjunction/core';
8
+ import { BaseSingleton, MJGlobal } from '@memberjunction/global';
9
+ import { AIBridgeEngineBase, BaseRealtimeBridge, TurnTakingPolicy, BridgeNativeSdkRegistry, } from '@memberjunction/ai-bridge-base';
10
+ import { MultiAgentRoomCoordinator } from './multi-agent-room-coordinator.js';
11
+ /**
12
+ * Entity names — centralised so the `MJ:`-prefix convention is applied in exactly one place.
13
+ */
14
+ const SESSION_BRIDGE_ENTITY = 'MJ: AI Agent Session Bridges';
15
+ const SESSION_BRIDGE_PARTICIPANT_ENTITY = 'MJ: AI Agent Session Bridge Participants';
16
+ /**
17
+ * Grace window after the last human leaves a room before the bot auto-leaves. Long enough that a page
18
+ * refresh (participant briefly drops + rejoins) does NOT kill the agent, short enough that an abandoned
19
+ * room frees its model session + finalizes its run promptly. See {@link AIBridgeEngine.evaluateRoomOccupancy}.
20
+ */
21
+ const ROOM_EMPTY_GRACE_MS = 15000;
22
+ /**
23
+ * A default {@link IHostInstanceIdentity} for standalone use (and a sane fallback when the host
24
+ * application does not inject one). Generates a stable `unknown-host:pid:bootId` identity at module
25
+ * load. Production hosts (MJServer) inject the real `HostInstance` helper so the janitor's host
26
+ * affinity matches across the whole deployment.
27
+ */
28
+ export class DefaultHostInstanceIdentity {
29
+ constructor() {
30
+ const pid = typeof process !== 'undefined' && process.pid ? process.pid : 0;
31
+ // A cheap, dependency-free random boot id; good enough for the fallback path.
32
+ const bootId = Math.random().toString(36).slice(2) + Date.now().toString(36);
33
+ this.hostName = 'unknown-host';
34
+ this.instanceId = `${this.hostName}:${pid}:${bootId}`;
35
+ }
36
+ /** @inheritdoc */
37
+ GetHostInstanceID() {
38
+ return this.instanceId;
39
+ }
40
+ /** @inheritdoc */
41
+ GetHostNamePrefix() {
42
+ return `${this.hostName}:`;
43
+ }
44
+ }
45
+ /**
46
+ * Server-tier engine for the Realtime Bridge plane — **coordination + execution**.
47
+ *
48
+ * `AIBridgeEngine` **composes** {@link AIBridgeEngineBase} (the metadata-only cache of providers /
49
+ * identities / provider-channels) rather than extending it — exactly mirroring how the server
50
+ * `AIEngine` builds on `AIEngineBase` via containment. The base is itself a `BaseEngine` singleton
51
+ * keyed by class name, so *inheriting* from it would make the startup manager instantiate **two**
52
+ * separate engines (the base AND this subclass), each loading and event-subscribing its own copy of
53
+ * the same caches. Composition keeps exactly **one** `BaseEngine` cache — {@link AIBridgeEngineBase.Instance}
54
+ * — which this engine warms once via {@link HandleStartup} and reads through the delegating accessors
55
+ * below. This server engine then adds everything that actually *runs* a bridged session:
56
+ *
57
+ * - **The transport seam** (Phase 0, the deferred unification): {@link wireTransportSeam} connects
58
+ * the driver's media plane to the realtime session — inbound `OnMedia` → `SendInput`, outbound
59
+ * `OnOutput` → `SendMedia`. This is the "no client-facing pipe" gap the realtime guide flagged;
60
+ * the bridge IS that pipe.
61
+ * - **Bot-session lifecycle** — {@link StartBridgeSession} / {@link StopBridgeSession} drive the
62
+ * `AIAgentSessionBridge` status state machine (Pending → Connecting → Connected → Disconnected),
63
+ * stamp `HostInstanceID` for node affinity, and resolve the driver via the `ClassFactory`.
64
+ * - **Participant tracking** — subscribes the driver's roster events (when supported) and upserts
65
+ * `AIAgentSessionBridgeParticipant` rows.
66
+ * - **Turn-taking integration** — holds a {@link TurnTakingPolicy} per session and feeds diarized
67
+ * transcript segments through it, acting on the decision (Speak / PostToChat / Silent).
68
+ * - **Janitor scaffold** — {@link ReconcileOrphans} force-closes Connected bridges left by a dead
69
+ * host, following the `SessionJanitor` shape.
70
+ *
71
+ * The engine never constructs the realtime model: the {@link IRealtimeSession} is injected via
72
+ * {@link StartBridgeSessionParams}, keeping the only coupling the transport seam itself and making
73
+ * the whole engine unit-testable with a mock session + the {@link LoopbackBridge}.
74
+ *
75
+ * @see `/plans/realtime/realtime-bridges-architecture.md` §2 (layer cake), §7 (lifecycle), §10 (security/janitor).
76
+ */
77
+ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
78
+ constructor() {
79
+ super(...arguments);
80
+ /** roomKey (lowercased) → the bridge id of that room's current transcript scribe. Election dedup. */
81
+ this.roomScribes = new Map();
82
+ /** Diagnostic: session ids that have already logged their first inbound / outbound media frame. */
83
+ this.diagInbound = new Set();
84
+ this.diagOutbound = new Set();
85
+ /** In-memory registry of bridged sessions this process currently hosts, keyed by bridge id (lowercased). */
86
+ this.activeSessions = new Map();
87
+ /** Host-instance identity provider; injected by the host application or defaulted for standalone use. */
88
+ this.hostIdentity = new DefaultHostInstanceIdentity();
89
+ /**
90
+ * Coordinates speaking discipline when MULTIPLE agent bridge sessions share one room (§4c —
91
+ * "1+ agents in a shared room"). Single-agent sessions never touch it; it is engaged only via the
92
+ * additive {@link RegisterRoomParticipant} / {@link UnregisterRoomParticipant} hooks, so the default
93
+ * single-agent path is wholly unaffected.
94
+ */
95
+ this.roomCoordinator = new MultiAgentRoomCoordinator();
96
+ }
97
+ /**
98
+ * The singleton accessor. Keyed by THIS class's name in the Global Object Store (via
99
+ * {@link BaseSingleton}), distinct from {@link AIBridgeEngineBase.Instance} — which this engine
100
+ * composes rather than inherits.
101
+ */
102
+ static get Instance() {
103
+ return super.getInstance();
104
+ }
105
+ // ──────────────────────────────────────────────────────────────────────────────
106
+ // Composed base — the ONE BaseEngine cache. All metadata is read through this.
107
+ // ──────────────────────────────────────────────────────────────────────────────
108
+ /**
109
+ * The single underlying {@link AIBridgeEngineBase} instance whose `BaseEngine` cache holds the
110
+ * bridge registry (providers / identities / provider-channels). Composed (not inherited) so the
111
+ * startup manager warms exactly one cache. All metadata reads on this engine delegate here.
112
+ */
113
+ get Base() {
114
+ return AIBridgeEngineBase.Instance;
115
+ }
116
+ /**
117
+ * Deferred-startup entry point (per {@link IStartupSink}). Warms the ONE composed base cache by
118
+ * delegating to {@link AIBridgeEngineBase.Config}; mirrors `AIEngine.HandleStartup`. No double
119
+ * load — there is only the base's cache to warm.
120
+ *
121
+ * @param contextUser The boot/system user context.
122
+ * @param provider Optional metadata provider override (multi-provider scenarios).
123
+ */
124
+ async HandleStartup(contextUser, provider) {
125
+ await this.Config(false, contextUser, provider);
126
+ }
127
+ /**
128
+ * Loads (or refreshes) the composed base's bridge metadata cache. Delegates to
129
+ * {@link AIBridgeEngineBase.Config} so the warming path matches `AIEngine`'s shape and there is
130
+ * never a second cache to load. Idempotent — a no-op when already loaded unless `forceRefresh`.
131
+ *
132
+ * @param forceRefresh When `true`, reloads even if already loaded.
133
+ * @param contextUser Required server-side for proper data isolation.
134
+ * @param provider Optional explicit metadata provider (multi-provider scenarios).
135
+ */
136
+ async Config(forceRefresh, contextUser, provider) {
137
+ await this.Base.Config(forceRefresh, contextUser, provider);
138
+ }
139
+ /** Returns `true` once the composed base cache is loaded. */
140
+ get Loaded() {
141
+ return this.Base.Loaded;
142
+ }
143
+ // ── Delegated metadata surface (reads the ONE base cache) ──────────────────────
144
+ /** All cached `MJ: AI Bridge Providers` rows. @see AIBridgeEngineBase.Providers */
145
+ get Providers() {
146
+ return this.Base.Providers;
147
+ }
148
+ /** All cached `MJ: AI Bridge Agent Identities` rows. @see AIBridgeEngineBase.AgentIdentities */
149
+ get AgentIdentities() {
150
+ return this.Base.AgentIdentities;
151
+ }
152
+ /** All cached `MJ: AI Bridge Provider Channels` rows. @see AIBridgeEngineBase.ProviderChannels */
153
+ get ProviderChannels() {
154
+ return this.Base.ProviderChannels;
155
+ }
156
+ /** Resolves a provider by display name. @see AIBridgeEngineBase.ProviderByName */
157
+ ProviderByName(name) {
158
+ return this.Base.ProviderByName(name);
159
+ }
160
+ /** Resolves a provider by `DriverClass`. @see AIBridgeEngineBase.ProviderByDriverClass */
161
+ ProviderByDriverClass(driverClass) {
162
+ return this.Base.ProviderByDriverClass(driverClass);
163
+ }
164
+ /** Resolves an agent identity by its address value. @see AIBridgeEngineBase.IdentityByValue */
165
+ IdentityByValue(identityValue, providerId) {
166
+ return this.Base.IdentityByValue(identityValue, providerId);
167
+ }
168
+ /**
169
+ * Registers the {@link BridgeSessionRunFinalizer} this engine calls when a bridge is marked disconnected
170
+ * without a live in-memory session (orphan/cross-host reap) — so the co-agent run finalizes there too,
171
+ * not only on the same-process `Close()` path. Bound once at startup by the agent layer. Idempotent.
172
+ *
173
+ * @param finalizer The finalizer (from `@memberjunction/ai-agents`).
174
+ */
175
+ SetSessionRunFinalizer(finalizer) {
176
+ this.runFinalizer = finalizer;
177
+ }
178
+ /**
179
+ * Registers the {@link BridgeTranscriptSink} that persists the unified per-room transcript. The engine
180
+ * elects one scribe per room and feeds its final transcript lines here; the sink owns *where* they land
181
+ * (e.g. an `MJ: Conversations` "Meeting Room"). Bound once at startup by the app layer. Without it, no
182
+ * transcript is persisted (the engine still elects a scribe but emits nothing).
183
+ *
184
+ * @param sink The transcript sink (from the app layer).
185
+ */
186
+ SetTranscriptSink(sink) {
187
+ this.transcriptSink = sink;
188
+ }
189
+ /** Returns the active identities for an agent. @see AIBridgeEngineBase.IdentitiesForAgent */
190
+ IdentitiesForAgent(agentId, providerId) {
191
+ return this.Base.IdentitiesForAgent(agentId, providerId);
192
+ }
193
+ /** Returns a provider's channels ordered by sequence. @see AIBridgeEngineBase.ChannelsForProvider */
194
+ ChannelsForProvider(providerId) {
195
+ return this.Base.ChannelsForProvider(providerId);
196
+ }
197
+ /** Returns a provider's auto-attach (default) channels. @see AIBridgeEngineBase.DefaultChannelsForProvider */
198
+ DefaultChannelsForProvider(providerId) {
199
+ return this.Base.DefaultChannelsForProvider(providerId);
200
+ }
201
+ /**
202
+ * Injects the host-instance identity provider used for `HostInstanceID` stamping and janitor
203
+ * affinity. Production hosts (MJServer) call this once at boot with the real `HostInstance`
204
+ * helper; standalone callers can rely on the {@link DefaultHostInstanceIdentity}.
205
+ *
206
+ * @param identity The identity provider to use.
207
+ */
208
+ SetHostInstanceIdentity(identity) {
209
+ this.hostIdentity = identity;
210
+ }
211
+ /**
212
+ * The bridged sessions this process currently hosts (read-only snapshot).
213
+ */
214
+ get ActiveSessions() {
215
+ return Array.from(this.activeSessions.values());
216
+ }
217
+ // ──────────────────────────────────────────────────────────────────────────────
218
+ // Multi-party — shared-room coordination (§4c). Additive; single-agent unaffected.
219
+ // ──────────────────────────────────────────────────────────────────────────────
220
+ /**
221
+ * The {@link MultiAgentRoomCoordinator} this engine uses for inter-agent floor arbitration when
222
+ * multiple agent bridge sessions share one room. Exposed so the runner-constructing layer can run
223
+ * `CanTakeFloor` / `TakeFloor` / `ReleaseFloor` around an agent's generation in a multi-agent room.
224
+ */
225
+ get RoomCoordinator() {
226
+ return this.roomCoordinator;
227
+ }
228
+ /**
229
+ * Ties a bridge session into the multi-agent room coordinator when it joins a SHARED room (§4c). Call
230
+ * this for an agent session whose bridge connects into a room that other agent sessions may also
231
+ * inhabit — keyed by the shared external room id (the driver's `ExternalConnectionID` / the
232
+ * ConversationID). Once 2+ agents are registered on the same room, floor arbitration keeps exactly one
233
+ * agent speaking at a time across agents; combined with passive turn-taking, two agents are loop-safe.
234
+ *
235
+ * **Additive and opt-in.** A normal single-agent bridge never calls this and is wholly unaffected —
236
+ * the coordinator only matters once two sessions name the same room. Designating `isFacilitator`
237
+ * marks the agent (typically the one running the Meeting Controls channel) as the room's arbiter,
238
+ * which may override the floor to call on a specific agent.
239
+ *
240
+ * @param roomId The shared external room id all co-located agents key on.
241
+ * @param agentSessionId The agent session joining the room.
242
+ * @param isFacilitator Whether this agent is the room's facilitator (may override the floor).
243
+ */
244
+ RegisterRoomParticipant(roomId, agentSessionId, isFacilitator = false) {
245
+ this.roomCoordinator.RegisterRoomParticipant(roomId, agentSessionId, isFacilitator);
246
+ LogStatus(`[AIBridgeEngine] Agent session ${agentSessionId} registered in shared room ${roomId}` +
247
+ `${isFacilitator ? ' (facilitator)' : ''}; multi-agent=${this.roomCoordinator.IsMultiAgentRoom(roomId)}.`);
248
+ }
249
+ /**
250
+ * Removes a bridge session from the multi-agent room coordinator (its bridge stopped / it left the
251
+ * room). Releases the floor if the leaving agent held it and clears the facilitator slot if it was
252
+ * the facilitator. Safe to call unconditionally on teardown — a no-op for sessions that were never
253
+ * registered as room participants.
254
+ *
255
+ * @param roomId The shared room the agent is leaving.
256
+ * @param agentSessionId The agent session leaving.
257
+ */
258
+ UnregisterRoomParticipant(roomId, agentSessionId) {
259
+ this.roomCoordinator.UnregisterRoomParticipant(roomId, agentSessionId);
260
+ }
261
+ // ──────────────────────────────────────────────────────────────────────────────
262
+ // Lifecycle — start / stop a bridged session.
263
+ // ──────────────────────────────────────────────────────────────────────────────
264
+ /**
265
+ * Starts a bridged session: resolves + connects the driver, drives the bridge row through its
266
+ * status state machine, and **wires the transport seam** between the driver and the injected
267
+ * realtime session.
268
+ *
269
+ * Flow (mirrors the §7 state machine):
270
+ * 1. Create the `AIAgentSessionBridge` row as `Pending`, stamped with this host.
271
+ * 2. Resolve the driver via `ClassFactory.CreateInstance(BaseRealtimeBridge, provider.DriverClass)`.
272
+ * 3. Transition to `Connecting`, build the {@link RealtimeBridgeContext}, call `driver.Connect`.
273
+ * 4. On success: persist the platform handles, transition to `Connected`, wire the transport seam,
274
+ * wire participant tracking + turn-taking, register the live session.
275
+ * 5. On failure: transition to `Failed` and rethrow.
276
+ *
277
+ * @param params The session parameters (including the injected {@link IRealtimeSession}).
278
+ * @returns The live {@link ActiveBridgeSession} handle.
279
+ * @throws When the driver cannot be resolved or `Connect` fails (the row is stamped `Failed`).
280
+ */
281
+ async StartBridgeSession(params) {
282
+ const bridgeRow = await this.createBridgeRow(params);
283
+ try {
284
+ // Resolve the driver inside the try so a resolution failure still stamps the row Failed
285
+ // (the row already exists at this point — it must not be left dangling as Pending).
286
+ const driver = this.resolveDriver(params.Provider);
287
+ // Bind the driver's SDK factory BEFORE Connect (Connect constructs the SDK from it). A
288
+ // per-session BindSdk override wins; otherwise apply the provider's registered native binding.
289
+ // Resolved drivers start with a default factory that throws "no SDK bound", so this is what
290
+ // makes a real provider session actually connect.
291
+ this.bindDriverSdk(params, driver);
292
+ await this.transitionStatus(bridgeRow, 'Connecting', params);
293
+ const ctx = this.buildBridgeContext(params);
294
+ const result = await driver.Connect(ctx);
295
+ bridgeRow.ExternalConnectionID = result.ExternalConnectionId;
296
+ bridgeRow.BotParticipantID = result.BotParticipantId;
297
+ bridgeRow.ConnectedAt = new Date();
298
+ await this.transitionStatus(bridgeRow, 'Connected', params);
299
+ const turnPolicy = this.buildTurnPolicy(params);
300
+ const active = {
301
+ SessionBridgeID: bridgeRow.ID,
302
+ AgentSessionID: params.AgentSessionID,
303
+ AgentID: params.AgentID,
304
+ Bridge: driver,
305
+ RealtimeSession: params.RealtimeSession,
306
+ TurnPolicy: turnPolicy,
307
+ DisableAutoResponse: params.DisableAutoResponse === true,
308
+ HasSeenHuman: false,
309
+ RoomKey: result.ExternalConnectionId,
310
+ BotParticipantID: result.BotParticipantId,
311
+ IsTranscriptScribe: false,
312
+ Provider: params.Provider,
313
+ ContextUser: params.ContextUser,
314
+ MetadataProvider: params.MetadataProvider,
315
+ ChannelHost: params.ChannelHost,
316
+ ServerChannelTools: [],
317
+ };
318
+ this.electTranscriptScribe(active);
319
+ this.wireTransportSeam(active);
320
+ this.wireParticipantTracking(active);
321
+ this.wireTurnTaking(active);
322
+ await this.wireChannelPlane(active);
323
+ this.activeSessions.set(bridgeRow.ID.toLowerCase(), active);
324
+ LogStatus(`[AIBridgeEngine] Bridge session ${bridgeRow.ID} connected via ${params.Provider.Name}`);
325
+ return active;
326
+ }
327
+ catch (err) {
328
+ await this.failBridgeRow(bridgeRow, params, err);
329
+ throw err;
330
+ }
331
+ }
332
+ /**
333
+ * Stops a bridged session: disconnects the driver, tears down the wired listeners, and transitions
334
+ * the bridge row to `Disconnected` with the supplied `CloseReason`. Idempotent — stopping a
335
+ * session this process no longer holds still attempts to reconcile the durable row.
336
+ *
337
+ * @param sessionBridgeID The `AIAgentSessionBridge` row id to stop.
338
+ * @param reason Why the bridge is closing (mirrors `CloseReason`).
339
+ * @param contextUser Required server-side for the durable-row write when the live session is gone.
340
+ * @param provider Required metadata provider when the live session is gone.
341
+ * @returns `true` when the durable row reached a `Disconnected` state.
342
+ */
343
+ async StopBridgeSession(sessionBridgeID, reason, contextUser, provider) {
344
+ const key = sessionBridgeID.toLowerCase();
345
+ const active = this.activeSessions.get(key);
346
+ if (active) {
347
+ await this.disconnectDriver(active, reason);
348
+ this.activeSessions.delete(key);
349
+ return this.markBridgeDisconnected(sessionBridgeID, reason, active.ContextUser ?? contextUser, active.MetadataProvider ?? provider);
350
+ }
351
+ // Not held by this process — still reconcile the durable row (janitor / cross-host close).
352
+ return this.markBridgeDisconnected(sessionBridgeID, reason, contextUser, provider);
353
+ }
354
+ // ──────────────────────────────────────────────────────────────────────────────
355
+ // THE TRANSPORT SEAM — the deferred "unified-transport track" completed here.
356
+ // ──────────────────────────────────────────────────────────────────────────────
357
+ /**
358
+ * Wires the bidirectional media transport seam between a bridge driver and a realtime session —
359
+ * the single piece of code that completes the realtime engine's deferred server-bridged media
360
+ * transport (the guide's "`SendInput`/`OnOutput` have no client-facing pipe" gap). The bridge IS
361
+ * that pipe.
362
+ *
363
+ * Two hooks, one per direction:
364
+ * - **Inbound** (`bridge.OnMedia` → `session.SendInput`): what the agent HEARS. Each inbound
365
+ * {@link BridgeMediaFrame} from the endpoint is unwrapped to its raw `ArrayBuffer` payload and
366
+ * streamed straight to the model.
367
+ * - **Outbound** (`session.OnOutput` → `bridge.SendMedia`): what the agent SAYS. Each model
368
+ * output `ArrayBuffer` is wrapped in an outbound audio {@link BridgeMediaFrame} and sent into
369
+ * the meeting/call.
370
+ *
371
+ * Audio is the first track lit up, so the outbound direction is wired as `audio-out`; video/screen
372
+ * tracks ride the same `SendMedia` method once the model emits them.
373
+ *
374
+ * @param active The live bridged session whose driver and realtime session are wired together.
375
+ */
376
+ wireTransportSeam(active) {
377
+ const { Bridge, RealtimeSession } = active;
378
+ // Inbound: endpoint media → the agent hears (and, for a video model, SEES) it. The frame's
379
+ // Track tags the plane, so a human's camera (`video-in`) reaches the model as a `video` frame.
380
+ Bridge.OnMedia((frame) => {
381
+ const chunk = this.frameToArrayBuffer(frame);
382
+ if (chunk) {
383
+ if (!this.diagInbound.has(active.SessionBridgeID)) {
384
+ this.diagInbound.add(active.SessionBridgeID);
385
+ LogStatus(`[AIBridgeEngine][diag] FIRST inbound media frame reached the agent (bridge ${active.SessionBridgeID}, track=${frame.Track}). The agent is HEARING you.`);
386
+ }
387
+ RealtimeSession.SendInput(chunk, frame.Track === 'video-in' ? 'video' : 'audio');
388
+ }
389
+ });
390
+ // Outbound: the agent speaks → into the meeting/call.
391
+ RealtimeSession.OnOutput((chunk) => {
392
+ if (!this.diagOutbound.has(active.SessionBridgeID)) {
393
+ this.diagOutbound.add(active.SessionBridgeID);
394
+ LogStatus(`[AIBridgeEngine][diag] FIRST outbound audio from the agent (bridge ${active.SessionBridgeID}). The agent is SPEAKING into the room.`);
395
+ }
396
+ const track = 'audio-out';
397
+ Bridge.SendMedia(track, this.arrayBufferToFrame(chunk, track));
398
+ });
399
+ // Outbound VIDEO: a video-capable session ALSO emits a synced avatar/video track. Optional —
400
+ // audio-only sessions don't implement OnVideoOutput, so call it null-safely. The bridge driver
401
+ // gates the actual publish on its `VideoOut` capability.
402
+ RealtimeSession.OnVideoOutput?.((chunk) => {
403
+ const track = 'video-out';
404
+ Bridge.SendMedia(track, this.arrayBufferToFrame(chunk, track));
405
+ });
406
+ // Barge-in: on a TRUE interruption (the user speaks over the agent), the model stops generating —
407
+ // but the driver may still hold queued outbound audio that would keep playing. Flush it so the
408
+ // agent goes quiet immediately. Without this, interruption "doesn't work" on the bridge surface.
409
+ RealtimeSession.OnInterruption(() => {
410
+ if (this.diagOutbound.has(active.SessionBridgeID)) {
411
+ LogStatus(`[AIBridgeEngine][diag] barge-in — flushing the agent's queued audio (bridge ${active.SessionBridgeID}).`);
412
+ }
413
+ Bridge.FlushOutboundMedia();
414
+ });
415
+ }
416
+ /**
417
+ * Unwraps a {@link BridgeMediaFrame} to the raw `ArrayBuffer` the realtime session consumes,
418
+ * preferring the binary `Bytes` payload and decoding `Base64` when only that is present. Returns
419
+ * `undefined` when the frame carries no payload (defensive — never forwards an empty frame).
420
+ *
421
+ * @param frame The inbound media frame.
422
+ * @returns The raw frame bytes, or `undefined` when the frame has no payload.
423
+ */
424
+ frameToArrayBuffer(frame) {
425
+ if (frame.Bytes) {
426
+ return frame.Bytes;
427
+ }
428
+ if (frame.Base64) {
429
+ return this.decodeBase64(frame.Base64);
430
+ }
431
+ return undefined;
432
+ }
433
+ /**
434
+ * Wraps a raw model-output `ArrayBuffer` in an outbound {@link BridgeMediaFrame} on the given
435
+ * track, using the fast binary payload path.
436
+ *
437
+ * @param chunk The raw output frame from the model.
438
+ * @param track The outbound track to stamp on the frame.
439
+ * @returns The outbound media frame.
440
+ */
441
+ arrayBufferToFrame(chunk, track) {
442
+ return { Track: track, Bytes: chunk, TimestampMs: Date.now() };
443
+ }
444
+ /**
445
+ * Decodes a base64 string into an `ArrayBuffer`. Uses Node's `Buffer` when available (the
446
+ * server tier) and falls back to `atob` otherwise so the seam stays environment-agnostic.
447
+ *
448
+ * @param base64 The base64-encoded payload.
449
+ * @returns The decoded `ArrayBuffer`.
450
+ */
451
+ decodeBase64(base64) {
452
+ if (typeof Buffer !== 'undefined') {
453
+ const buf = Buffer.from(base64, 'base64');
454
+ // Copy into a fresh ArrayBuffer (Buffer.buffer is ArrayBufferLike under newer @types/node).
455
+ const out = new Uint8Array(buf.byteLength);
456
+ out.set(buf);
457
+ return out.buffer;
458
+ }
459
+ const binary = atob(base64);
460
+ const bytes = new Uint8Array(binary.length);
461
+ for (let i = 0; i < binary.length; i++) {
462
+ bytes[i] = binary.charCodeAt(i);
463
+ }
464
+ return bytes.buffer;
465
+ }
466
+ // ──────────────────────────────────────────────────────────────────────────────
467
+ // Participant tracking.
468
+ // ──────────────────────────────────────────────────────────────────────────────
469
+ /**
470
+ * Subscribes the driver's roster-change stream (when the provider supports diarization/roster)
471
+ * and upserts `AIAgentSessionBridgeParticipant` rows on each change. Capability-gated: a driver
472
+ * without roster support throws from `OnParticipantChange`, which is caught and treated as
473
+ * "no participant tracking for this provider" rather than failing the session.
474
+ *
475
+ * @param active The live bridged session to track participants for.
476
+ */
477
+ wireParticipantTracking(active) {
478
+ if (active.Provider.SupportedFeaturesObject?.SpeakerDiarization !== true) {
479
+ return; // provider metadata says no roster — never call the driver (defense-in-depth gate).
480
+ }
481
+ try {
482
+ active.Bridge.OnParticipantChange((participants) => {
483
+ void this.upsertParticipants(active, participants);
484
+ // Auto-leave an emptied room: the dominant teardown path (the user just closes the tab never
485
+ // calls StopBridgeSession), so without this the bot lingers Connected and its co-agent run
486
+ // dangles in Running forever. Routed through the normal stop, so the run finalizes cleanly.
487
+ this.evaluateRoomOccupancy(active, participants);
488
+ });
489
+ }
490
+ catch (err) {
491
+ // The driver did not actually implement roster despite the flag — log and continue.
492
+ LogError(`[AIBridgeEngine] Participant tracking unavailable for bridge ${active.SessionBridgeID}: ` +
493
+ `${err instanceof Error ? err.message : String(err)}`);
494
+ }
495
+ }
496
+ /**
497
+ * Decides whether an emptied room should auto-leave. Marks {@link ActiveBridgeSession.HasSeenHuman}
498
+ * once any human is present; when a human WAS present and the roster drops to agents-only, it arms a
499
+ * grace timer ({@link ROOM_EMPTY_GRACE_MS}) that stops the session (so a page-refresh re-join cancels
500
+ * it). The stop routes through {@link StopBridgeSession} → driver disconnect → realtime `Close()`, which
501
+ * finalizes the co-agent run — so a closed tab no longer leaves a `Connected` bridge + `Running` run.
502
+ *
503
+ * Only providers with a roster (diarization) reach here; rosterless transports rely on the host janitor.
504
+ *
505
+ * @param active The live bridged session.
506
+ * @param participants The current roster from the driver.
507
+ */
508
+ evaluateRoomOccupancy(active, participants) {
509
+ const humanPresent = participants.some(p => !p.IsAgent);
510
+ if (humanPresent) {
511
+ active.HasSeenHuman = true;
512
+ if (active.LeaveGraceTimer) {
513
+ clearTimeout(active.LeaveGraceTimer);
514
+ active.LeaveGraceTimer = undefined;
515
+ }
516
+ return;
517
+ }
518
+ // Agents-only roster. Never reaped unless a human was actually here first (so a bot that joins ahead
519
+ // of anyone isn't killed), and only one countdown at a time.
520
+ if (!active.HasSeenHuman || active.LeaveGraceTimer) {
521
+ return;
522
+ }
523
+ active.LeaveGraceTimer = setTimeout(() => {
524
+ active.LeaveGraceTimer = undefined;
525
+ // A re-join cleared this timer; a prior stop removed the session. Only act if it's still live.
526
+ if (this.activeSessions.has(active.SessionBridgeID.toLowerCase())) {
527
+ LogStatus(`[AIBridgeEngine] All humans left bridge ${active.SessionBridgeID}; auto-leaving (grace elapsed).`);
528
+ void this.StopBridgeSession(active.SessionBridgeID, 'HostEnded', active.ContextUser, active.MetadataProvider);
529
+ }
530
+ }, ROOM_EMPTY_GRACE_MS);
531
+ }
532
+ /**
533
+ * Upserts the supplied participants onto the bridge as `AIAgentSessionBridgeParticipant` rows,
534
+ * matching existing rows by `ExternalParticipantID`. Best-effort: a failed write is logged and
535
+ * never propagates to the live media plane.
536
+ *
537
+ * @param active The live bridged session the participants belong to.
538
+ * @param participants The current roster from the driver.
539
+ */
540
+ async upsertParticipants(active, participants) {
541
+ const provider = active.MetadataProvider;
542
+ if (!provider) {
543
+ return;
544
+ }
545
+ try {
546
+ const existing = await this.loadParticipants(active, provider);
547
+ for (const p of participants) {
548
+ await this.upsertOneParticipant(active, p, existing, provider);
549
+ }
550
+ }
551
+ catch (err) {
552
+ LogError(`[AIBridgeEngine] upsertParticipants failed for bridge ${active.SessionBridgeID}: ` +
553
+ `${err instanceof Error ? err.message : String(err)}`);
554
+ }
555
+ }
556
+ /** Loads the existing participant rows for a bridge, keyed (lowercased) by `ExternalParticipantID`. */
557
+ async loadParticipants(active, provider) {
558
+ const rv = RunView.FromMetadataProvider(provider);
559
+ const result = await rv.RunView({
560
+ EntityName: SESSION_BRIDGE_PARTICIPANT_ENTITY,
561
+ ExtraFilter: `SessionBridgeID='${active.SessionBridgeID}'`,
562
+ ResultType: 'entity_object',
563
+ }, active.ContextUser);
564
+ const map = new Map();
565
+ if (result.Success) {
566
+ for (const row of result.Results) {
567
+ if (row.ExternalParticipantID) {
568
+ map.set(row.ExternalParticipantID.toLowerCase(), row);
569
+ }
570
+ }
571
+ }
572
+ return map;
573
+ }
574
+ /** Inserts a new participant row or updates the matched existing one in place. */
575
+ async upsertOneParticipant(active, p, existing, provider) {
576
+ const key = p.ExternalId.toLowerCase();
577
+ let row = existing.get(key);
578
+ if (!row) {
579
+ row = await provider.GetEntityObject(SESSION_BRIDGE_PARTICIPANT_ENTITY, active.ContextUser);
580
+ row.NewRecord();
581
+ row.SessionBridgeID = active.SessionBridgeID;
582
+ row.ExternalParticipantID = p.ExternalId;
583
+ row.JoinedAt = new Date();
584
+ existing.set(key, row);
585
+ }
586
+ row.DisplayName = p.DisplayName ?? null;
587
+ row.Role = p.Role;
588
+ row.IsAgent = p.IsAgent;
589
+ const saved = await row.Save();
590
+ if (!saved) {
591
+ LogError(`[AIBridgeEngine] participant upsert save failed: ${row.LatestResult?.CompleteMessage ?? 'unknown error'}`);
592
+ }
593
+ }
594
+ // ──────────────────────────────────────────────────────────────────────────────
595
+ // Turn-taking integration.
596
+ // ──────────────────────────────────────────────────────────────────────────────
597
+ /**
598
+ * Wires the session's turn-taking policy to its inbound transcript stream. Each diarized
599
+ * transcript segment is fed to {@link TurnTakingPolicy.EvaluateTurn} and the decision is acted
600
+ * on: `Speak` lets the realtime session take the floor (via {@link IRealtimeSession.RequestSpokenUpdate}
601
+ * when available, else a context note), `PostToChat` is delegated to the bridge chat path
602
+ * (currently a documented hook), and `Silent` does nothing.
603
+ *
604
+ * Only the realtime session's *user* transcripts drive turn-taking — assistant transcripts are
605
+ * the agent's own speech and would otherwise self-trigger.
606
+ *
607
+ * @param active The live bridged session.
608
+ */
609
+ wireTurnTaking(active) {
610
+ active.RealtimeSession.OnTranscript((t) => {
611
+ if (t.IsFinal) {
612
+ // Only log FINAL transcripts — partials fire per-word and flood the log.
613
+ LogStatus(`[AIBridgeEngine][diag] transcript(final): role=${t.Role} text="${(t.Text ?? '').slice(0, 80)}" (bridge ${active.SessionBridgeID})`);
614
+ // Persist the unified room transcript (scribe only — emits both roles).
615
+ this.emitTranscriptLine(active, t);
616
+ }
617
+ if (t.Role !== 'user' || !t.IsFinal) {
618
+ return; // act only on a completed human turn
619
+ }
620
+ const segment = {
621
+ Text: t.Text,
622
+ IsAgent: false,
623
+ EndMs: Date.now(),
624
+ };
625
+ const decision = active.TurnPolicy.EvaluateTurn({ Segment: segment });
626
+ LogStatus(`[AIBridgeEngine][diag] turn decision=${decision.Action} for user turn "${(t.Text ?? '').slice(0, 60)}" (bridge ${active.SessionBridgeID})`);
627
+ this.applyTurnDecision(active, decision.Action);
628
+ });
629
+ }
630
+ /**
631
+ * Acts on a turn-taking decision. Kept behind the injected {@link IRealtimeSession} interface so
632
+ * the actual model trigger stays the session's concern and the engine remains testable.
633
+ *
634
+ * @param active The live bridged session.
635
+ * @param action The decided action (`Speak` / `PostToChat` / `Silent`).
636
+ */
637
+ applyTurnDecision(active, action) {
638
+ switch (action) {
639
+ case 'Speak':
640
+ if (active.DisableAutoResponse) {
641
+ // MEETING MODE: the model's blind auto-response is OFF (the agent layer opened the
642
+ // session with `disableAutoResponse`), so the bridge is the SOLE speech trigger. The
643
+ // turn policy already gated this to an ADDRESSED turn, so issue exactly one response.
644
+ // This is what lets several agents share a room without all answering every utterance.
645
+ active.RealtimeSession.RequestSpokenUpdate?.('');
646
+ }
647
+ else {
648
+ // 1:1 CALL: the model has server-VAD auto-response on (same as the browser client-direct
649
+ // path), so it ALREADY answered this turn — one clean stream. Forcing a second
650
+ // `RequestSpokenUpdate` here would race the auto-response (double-answer + overlap/chop).
651
+ // Rely on auto-response.
652
+ }
653
+ break;
654
+ case 'PostToChat':
655
+ // Bridge chat is a Phase 2 channel surface; the hook is here so the wiring is complete.
656
+ // A chat-capable driver/channel will consume this once the server-side channel plane lands.
657
+ LogStatus(`[AIBridgeEngine] Turn decision PostToChat for bridge ${active.SessionBridgeID} (chat hook).`);
658
+ break;
659
+ case 'Silent':
660
+ default:
661
+ break;
662
+ }
663
+ }
664
+ /**
665
+ * Builds the per-session {@link TurnTakingPolicy} from the start params.
666
+ *
667
+ * @param params The session parameters.
668
+ * @returns The configured turn-taking policy.
669
+ */
670
+ buildTurnPolicy(params) {
671
+ const config = {
672
+ Mode: params.TurnMode ?? 'Passive',
673
+ Matcher: params.TurnMatcher,
674
+ Scorer: params.TurnScorer,
675
+ ...(params.TurnTuning ?? {}),
676
+ };
677
+ return new TurnTakingPolicy(config);
678
+ }
679
+ /**
680
+ * Elects this session as its room's transcript **scribe** iff a transcript sink is registered, the
681
+ * session has a room key, and no scribe exists for that room yet. Exactly one scribe per room writes the
682
+ * unified transcript, so a multi-agent room records one copy (the scribe hears everyone), not N.
683
+ *
684
+ * @param active The freshly connected session.
685
+ */
686
+ electTranscriptScribe(active) {
687
+ if (!this.transcriptSink || !active.RoomKey) {
688
+ return;
689
+ }
690
+ const roomKey = active.RoomKey.toLowerCase();
691
+ if (!this.roomScribes.has(roomKey)) {
692
+ this.roomScribes.set(roomKey, active.SessionBridgeID);
693
+ active.IsTranscriptScribe = true;
694
+ LogStatus(`[AIBridgeEngine] Bridge ${active.SessionBridgeID} is the transcript scribe for its room.`);
695
+ }
696
+ }
697
+ /**
698
+ * Releases this session's scribe role on teardown and HANDS OFF to another live session in the same
699
+ * room (so the transcript continues when the original scribe leaves a still-occupied room). No-op when
700
+ * the session wasn't the scribe. Called during disconnect while the session is still in the active map.
701
+ *
702
+ * @param active The session being torn down.
703
+ */
704
+ releaseTranscriptScribe(active) {
705
+ if (!active.RoomKey) {
706
+ return;
707
+ }
708
+ const roomKey = active.RoomKey.toLowerCase();
709
+ if (this.roomScribes.get(roomKey) !== active.SessionBridgeID) {
710
+ return; // not the scribe
711
+ }
712
+ this.roomScribes.delete(roomKey);
713
+ active.IsTranscriptScribe = false;
714
+ for (const other of this.activeSessions.values()) {
715
+ if (other !== active && other.RoomKey?.toLowerCase() === roomKey) {
716
+ this.roomScribes.set(roomKey, other.SessionBridgeID);
717
+ other.IsTranscriptScribe = true;
718
+ LogStatus(`[AIBridgeEngine] Transcript scribe handed to bridge ${other.SessionBridgeID} (prior scribe left).`);
719
+ return;
720
+ }
721
+ }
722
+ }
723
+ /**
724
+ * Emits one FINAL transcript line to the registered sink — only from the room's scribe, so the room
725
+ * gets a single unified transcript. The scribe's OWN speech (`assistant`) is attributed to it; everything
726
+ * it hears (`user`) is recorded as heard. Best-effort: a sink failure is logged, never fatal to media.
727
+ *
728
+ * @param active The scribe session.
729
+ * @param t The final transcript line.
730
+ */
731
+ emitTranscriptLine(active, t) {
732
+ if (!active.IsTranscriptScribe || !this.transcriptSink || !active.RoomKey) {
733
+ return;
734
+ }
735
+ const text = (t.Text ?? '').trim();
736
+ if (!text) {
737
+ return;
738
+ }
739
+ const isAgentSpeech = t.Role === 'assistant';
740
+ void Promise.resolve(this.transcriptSink({
741
+ RoomKey: active.RoomKey,
742
+ AgentSessionID: active.AgentSessionID,
743
+ AgentID: active.AgentID,
744
+ IsAgentSpeech: isAgentSpeech,
745
+ SpeakerParticipantID: isAgentSpeech ? active.BotParticipantID : undefined,
746
+ Text: text,
747
+ }, active.ContextUser, active.MetadataProvider)).catch((err) => LogError(`[AIBridgeEngine] transcript sink failed for bridge ${active.SessionBridgeID}: ` +
748
+ `${err instanceof Error ? err.message : String(err)}`));
749
+ }
750
+ // ──────────────────────────────────────────────────────────────────────────────
751
+ // THE CHANNEL PLANE — Part A: generic wiring of the Phase 2 server-side channels.
752
+ // ──────────────────────────────────────────────────────────────────────────────
753
+ /**
754
+ * Wires the session's server-side channel plane (Phase 2's `RealtimeChannelServerHost` +
755
+ * `MeetingControlsChannelServer`) to this bridged session — the generic, platform-agnostic
756
+ * integration the Phase 2 agent flagged as the bridge-server follow-up.
757
+ *
758
+ * When a {@link IBridgeChannelHost} was supplied, this:
759
+ * 1. Resolves the driver's optional Meeting Controls event source
760
+ * ({@link BaseRealtimeBridge.GetMeetingControlsEventSource}) — non-null only for drivers that
761
+ * contribute a facilitator surface.
762
+ * 2. Captures the realtime session's `SendContextNote` perception sink (when the provider supports
763
+ * mid-session context injection) so channel perception reaches the model.
764
+ * 3. Calls {@link IBridgeChannelHost.StartSessionChannels} to register the session's channels and
765
+ * construct + bind the Meeting Controls channel to the event source.
766
+ * 4. Reads the contributed server-channel tools and binds the per-session executor onto the
767
+ * {@link ActiveBridgeSession}, so the runner-constructing layer registers them as
768
+ * `RealtimeSessionRunner.ServerChannelTools` and routes `ExecuteServerChannelTool` here.
769
+ *
770
+ * Failure posture mirrors the channel plane itself: a channel-host error is logged and never
771
+ * propagates — the live media plane (the call/meeting) must not break because a channel failed.
772
+ *
773
+ * @param active The live bridged session to wire channels for.
774
+ */
775
+ async wireChannelPlane(active) {
776
+ const host = active.ChannelHost;
777
+ if (!host) {
778
+ return; // IRealtimeSession-only caller — no channel plane to wire (back-compat).
779
+ }
780
+ try {
781
+ const meetingControls = active.Bridge.GetMeetingControlsEventSource();
782
+ // The model perceives channel events via SendContextNote when the provider supports it.
783
+ const sink = active.RealtimeSession.SendContextNote
784
+ ? (text) => active.RealtimeSession.SendContextNote?.(text)
785
+ : undefined;
786
+ await host.StartSessionChannels(active.AgentSessionID, meetingControls, sink);
787
+ active.ServerChannelTools = host.GetSessionServerTools(active.AgentSessionID) ?? [];
788
+ active.ExecuteServerChannelTool = (toolName, argsJson) => host.ExecuteSessionServerTool(active.AgentSessionID, toolName, argsJson);
789
+ LogStatus(`[AIBridgeEngine] Channel plane wired for bridge ${active.SessionBridgeID}: ` +
790
+ `${active.ServerChannelTools.length} server-channel tool(s)` +
791
+ `${meetingControls ? ' (incl. Meeting Controls)' : ''}.`);
792
+ }
793
+ catch (err) {
794
+ LogError(`[AIBridgeEngine] Channel-plane wiring failed for bridge ${active.SessionBridgeID} ` +
795
+ `(media plane unaffected): ${err instanceof Error ? err.message : String(err)}`);
796
+ }
797
+ }
798
+ /**
799
+ * Closes the session's server-side channels through the channel host (best-effort; teardown must
800
+ * never throw). Invoked from {@link disconnectDriver} so every stop path — explicit, janitor,
801
+ * shutdown — releases the channel plane.
802
+ *
803
+ * @param active The live bridged session whose channels to close.
804
+ */
805
+ async closeChannelPlane(active) {
806
+ if (!active.ChannelHost) {
807
+ return;
808
+ }
809
+ try {
810
+ await active.ChannelHost.CloseSessionChannels(active.AgentSessionID);
811
+ }
812
+ catch (err) {
813
+ LogError(`[AIBridgeEngine] Channel-plane close failed for bridge ${active.SessionBridgeID}: ` +
814
+ `${err instanceof Error ? err.message : String(err)}`);
815
+ }
816
+ }
817
+ // ──────────────────────────────────────────────────────────────────────────────
818
+ // Janitor — orphan reconciliation (scaffold; scheduling is a host-provided hook).
819
+ // ──────────────────────────────────────────────────────────────────────────────
820
+ /**
821
+ * Force-closes `Connected`/`Connecting` bridges left behind by a **previous boot of this host**
822
+ * (matching hostname prefix, differing instance id), stamping `CloseReason = 'Janitor'`. Mirrors
823
+ * `SessionJanitor.RunStartupRecovery`: a crash/redeploy vaporizes the in-memory driver sockets
824
+ * but leaves the durable rows reading `Connected` forever; this reconciles them.
825
+ *
826
+ * The actual *scheduling* (run once at boot + periodic sweep) is intentionally left to the host
827
+ * application (MJServer's startup + janitor timer) so this engine package carries no timer/IO of
828
+ * its own; call this method from that scheduler.
829
+ *
830
+ * @param contextUser The system user the reconciliation writes run as.
831
+ * @param provider The metadata provider for the reconciliation reads/writes.
832
+ * @returns The number of orphaned bridges closed.
833
+ */
834
+ async ReconcileOrphans(contextUser, provider) {
835
+ const prefix = this.escapeSql(this.hostIdentity.GetHostNamePrefix());
836
+ const current = this.escapeSql(this.hostIdentity.GetHostInstanceID());
837
+ const filter = `Status IN ('Connecting','Connected') ` +
838
+ `AND HostInstanceID LIKE '${prefix}%' ` +
839
+ `AND HostInstanceID <> '${current}'`;
840
+ const rows = await this.loadOrphanRows(filter, contextUser, provider);
841
+ let closed = 0;
842
+ for (const row of rows) {
843
+ const ok = await this.markBridgeDisconnected(row.ID, 'Janitor', contextUser, provider);
844
+ if (ok) {
845
+ closed++;
846
+ }
847
+ }
848
+ if (closed > 0) {
849
+ LogStatus(`[AIBridgeEngine] Janitor reconciled ${closed} orphaned bridge(s) from a prior boot of this host`);
850
+ }
851
+ return closed;
852
+ }
853
+ /** Loads the orphaned bridge rows matching the janitor filter. */
854
+ async loadOrphanRows(filter, contextUser, provider) {
855
+ const rv = RunView.FromMetadataProvider(provider);
856
+ const result = await rv.RunView({
857
+ EntityName: SESSION_BRIDGE_ENTITY,
858
+ ExtraFilter: filter,
859
+ ResultType: 'entity_object',
860
+ }, contextUser);
861
+ if (!result.Success) {
862
+ LogError(`[AIBridgeEngine] ReconcileOrphans load failed: ${result.ErrorMessage}`);
863
+ return [];
864
+ }
865
+ return result.Results;
866
+ }
867
+ // ──────────────────────────────────────────────────────────────────────────────
868
+ // Driver resolution + bridge-row persistence.
869
+ // ──────────────────────────────────────────────────────────────────────────────
870
+ /**
871
+ * Binds the SDK factory onto a resolved driver before `Connect`. Precedence: a per-session
872
+ * {@link StartBridgeSessionParams.BindSdk} override wins; otherwise the provider's registered native
873
+ * binding from the {@link BridgeNativeSdkRegistry} is applied. When neither exists the driver keeps its
874
+ * default factory (which fails loudly at connect if it actually needs an SDK — e.g. LoopbackBridge has
875
+ * no SDK and needs no binding, so this is a harmless no-op for it).
876
+ *
877
+ * @param params The start params (its `BindSdk` is the override).
878
+ * @param driver The resolved driver to bind onto.
879
+ */
880
+ bindDriverSdk(params, driver) {
881
+ const override = params.BindSdk;
882
+ if (override) {
883
+ override(driver);
884
+ return;
885
+ }
886
+ BridgeNativeSdkRegistry.Instance.Apply(params.Provider.DriverClass, driver);
887
+ }
888
+ /**
889
+ * Resolves the concrete bridge driver for a provider via the MJ `ClassFactory`, keyed by the
890
+ * provider's `DriverClass`.
891
+ *
892
+ * @param provider The provider whose `DriverClass` selects the driver.
893
+ * @returns The instantiated driver.
894
+ * @throws When no driver is registered under the provider's `DriverClass`.
895
+ */
896
+ resolveDriver(provider) {
897
+ const driverClass = provider.DriverClass;
898
+ // ClassFactory.CreateInstance FALLS BACK to the (abstract) base class when no driver is
899
+ // registered under the key — it never returns null for a non-null base. So we must verify a
900
+ // concrete registration exists first, otherwise we'd return an unusable abstract instance and
901
+ // fail later with an opaque "Connect is not a function".
902
+ const registration = MJGlobal.Instance.ClassFactory.GetRegistration(BaseRealtimeBridge, driverClass);
903
+ if (!registration) {
904
+ throw new Error(`No bridge driver registered for DriverClass '${driverClass}' (provider '${provider.Name}').`);
905
+ }
906
+ const driver = MJGlobal.Instance.ClassFactory.CreateInstance(BaseRealtimeBridge, driverClass);
907
+ if (!driver) {
908
+ throw new Error(`Failed to instantiate bridge driver '${driverClass}' (provider '${provider.Name}').`);
909
+ }
910
+ return driver;
911
+ }
912
+ /**
913
+ * Builds the {@link RealtimeBridgeContext} handed to the driver's `Connect` from the start params
914
+ * and the provider's typed `SupportedFeatures`.
915
+ *
916
+ * @param params The session parameters.
917
+ * @returns The bridge context.
918
+ */
919
+ buildBridgeContext(params) {
920
+ // Carry the realtime model's audio format down to the media-transport driver so it resamples to the
921
+ // rate the model actually consumes/emits (OpenAI 24 kHz; Gemini Live 16 kHz IN). Without this a
922
+ // bridge feeds e.g. Gemini 24 kHz audio it can't parse and the agent never responds. Defaults keep
923
+ // every existing driver/model on 24 kHz. See plans/realtime/realtime-core-host-convergence.md.
924
+ return {
925
+ Features: params.Provider.SupportedFeaturesObject ?? {},
926
+ ProviderName: params.Provider.Name,
927
+ Address: params.Address,
928
+ Configuration: {
929
+ ...params.Configuration,
930
+ InboundSampleRate: params.RealtimeSession.InputSampleRate ?? 24000,
931
+ OutboundSampleRate: params.RealtimeSession.OutputSampleRate ?? 24000,
932
+ },
933
+ ContextUser: params.ContextUser,
934
+ };
935
+ }
936
+ /**
937
+ * Creates the `AIAgentSessionBridge` row as `Pending`, stamped with the host instance for affinity.
938
+ *
939
+ * @param params The session parameters.
940
+ * @returns The saved bridge row.
941
+ * @throws When the row cannot be created (no metadata provider, or save failure).
942
+ */
943
+ async createBridgeRow(params) {
944
+ const provider = params.MetadataProvider;
945
+ if (!provider) {
946
+ throw new Error('AIBridgeEngine.StartBridgeSession requires a MetadataProvider.');
947
+ }
948
+ const row = await provider.GetEntityObject(SESSION_BRIDGE_ENTITY, params.ContextUser);
949
+ row.NewRecord();
950
+ row.AgentSessionID = params.AgentSessionID;
951
+ row.ProviderID = params.Provider.ID;
952
+ row.Direction = params.Direction ?? 'Outbound';
953
+ row.JoinMethod = params.JoinMethod ?? 'OnDemand';
954
+ row.TurnMode = params.TurnMode ?? 'Passive';
955
+ row.Address = params.Address;
956
+ row.Status = 'Pending';
957
+ row.HostInstanceID = this.hostIdentity.GetHostInstanceID();
958
+ const saved = await row.Save();
959
+ if (!saved) {
960
+ throw new Error(`Failed to create AIAgentSessionBridge: ${row.LatestResult?.CompleteMessage ?? 'unknown error'}`);
961
+ }
962
+ return row;
963
+ }
964
+ /**
965
+ * Transitions a bridge row to a new `Status` and persists it.
966
+ *
967
+ * @param row The bridge row to transition.
968
+ * @param status The target status.
969
+ * @param params The session parameters (carry the context user for the save).
970
+ */
971
+ async transitionStatus(row, status, params) {
972
+ row.Status = status;
973
+ const saved = await row.Save();
974
+ if (!saved) {
975
+ throw new Error(`Failed to transition bridge ${row.ID} to '${status}': ` +
976
+ `${row.LatestResult?.CompleteMessage ?? 'unknown error'} (user ${params.ContextUser?.Email ?? 'n/a'})`);
977
+ }
978
+ }
979
+ /** Stamps a bridge row `Failed` (best-effort) after a connect failure, logging the cause. */
980
+ async failBridgeRow(row, params, cause) {
981
+ LogError(`[AIBridgeEngine] Bridge ${row.ID} failed to connect via ${params.Provider.Name}: ` +
982
+ `${cause instanceof Error ? cause.message : String(cause)}`);
983
+ try {
984
+ row.Status = 'Failed';
985
+ row.CloseReason = 'Error';
986
+ row.DisconnectedAt = new Date();
987
+ await row.Save();
988
+ }
989
+ catch (err) {
990
+ LogError(`[AIBridgeEngine] failed to stamp bridge ${row.ID} as Failed: ${err instanceof Error ? err.message : String(err)}`);
991
+ }
992
+ }
993
+ /** Disconnects the driver of a live session, tolerant of driver teardown errors, and closes its channels. */
994
+ async disconnectDriver(active, reason) {
995
+ // Cancel any pending auto-leave timer so it can't fire against an already-torn-down session.
996
+ if (active.LeaveGraceTimer) {
997
+ clearTimeout(active.LeaveGraceTimer);
998
+ active.LeaveGraceTimer = undefined;
999
+ }
1000
+ // Hand the transcript scribe role to another live session in the room (if this was the scribe), so a
1001
+ // multi-agent room keeps recording after the first agent leaves. Done before the active map removal.
1002
+ this.releaseTranscriptScribe(active);
1003
+ // Close the channel plane first so its post-close hooks see the session still mid-teardown,
1004
+ // then release the driver's media plane.
1005
+ await this.closeChannelPlane(active);
1006
+ try {
1007
+ await active.Bridge.Disconnect(reason);
1008
+ }
1009
+ catch (err) {
1010
+ LogError(`[AIBridgeEngine] driver Disconnect failed for bridge ${active.SessionBridgeID}: ` +
1011
+ `${err instanceof Error ? err.message : String(err)}`);
1012
+ }
1013
+ // Close the realtime model session too — releases the provider connection AND triggers the
1014
+ // co-agent run/prompt-run finalizer the agent layer wrapped onto Close() (otherwise the run dangles
1015
+ // in `Running` and the model socket leaks). Tolerant: a provider Close error must not block teardown.
1016
+ try {
1017
+ await active.RealtimeSession.Close();
1018
+ }
1019
+ catch (err) {
1020
+ LogError(`[AIBridgeEngine] realtime session Close failed for bridge ${active.SessionBridgeID}: ` +
1021
+ `${err instanceof Error ? err.message : String(err)}`);
1022
+ }
1023
+ }
1024
+ /**
1025
+ * Loads a bridge row and transitions it to `Disconnected` with the supplied `CloseReason`,
1026
+ * stamping `DisconnectedAt`. Idempotent — an already-`Disconnected`/`Failed` row is left untouched
1027
+ * and reported as success.
1028
+ *
1029
+ * @param sessionBridgeID The bridge row id.
1030
+ * @param reason The close reason to stamp.
1031
+ * @param contextUser The user the write runs as.
1032
+ * @param provider The metadata provider for the load/save.
1033
+ * @returns `true` when the row is (or already was) in a terminal disconnected state.
1034
+ */
1035
+ async markBridgeDisconnected(sessionBridgeID, reason, contextUser, provider) {
1036
+ if (!provider) {
1037
+ LogError(`[AIBridgeEngine] markBridgeDisconnected requires a metadata provider (bridge ${sessionBridgeID}).`);
1038
+ return false;
1039
+ }
1040
+ const row = await provider.GetEntityObject(SESSION_BRIDGE_ENTITY, contextUser);
1041
+ const loaded = await row.Load(sessionBridgeID);
1042
+ if (!loaded) {
1043
+ return false;
1044
+ }
1045
+ if (row.Status === 'Disconnected' || row.Status === 'Failed') {
1046
+ return true; // idempotent — already terminal, keep the original reason.
1047
+ }
1048
+ const agentSessionID = row.AgentSessionID;
1049
+ row.Status = 'Disconnected';
1050
+ row.CloseReason = reason;
1051
+ row.DisconnectedAt = new Date();
1052
+ const saved = await row.Save();
1053
+ if (!saved) {
1054
+ LogError(`[AIBridgeEngine] markBridgeDisconnected save failed for ${sessionBridgeID}: ` +
1055
+ `${row.LatestResult?.CompleteMessage ?? 'unknown error'}`);
1056
+ }
1057
+ // Finalize the co-agent run(s) for this session on EVERY teardown path. The same-process `Close()`
1058
+ // already finalized them (so this is a no-op there), but the orphan/cross-host reaps reach here
1059
+ // WITHOUT a live session — this is the only place their dangling `Running` co-agent run gets closed.
1060
+ // Tolerant: a finalizer failure must never block the disconnect bookkeeping.
1061
+ if (saved && this.runFinalizer && agentSessionID) {
1062
+ try {
1063
+ await this.runFinalizer(agentSessionID, reason !== 'Error', contextUser, provider);
1064
+ }
1065
+ catch (err) {
1066
+ LogError(`[AIBridgeEngine] session run finalizer failed for ${sessionBridgeID}: ` +
1067
+ `${err instanceof Error ? err.message : String(err)}`);
1068
+ }
1069
+ }
1070
+ return saved;
1071
+ }
1072
+ /** Escapes single quotes for safe embedding inside an `ExtraFilter` literal. */
1073
+ escapeSql(value) {
1074
+ return value.replace(/'/g, "''");
1075
+ }
1076
+ };
1077
+ AIBridgeEngine = __decorate([
1078
+ RegisterForStartup({
1079
+ deferred: true,
1080
+ deferredDelay: 15000,
1081
+ description: 'Server-side AI Bridge Engine (realtime bridge coordination + transport seam)',
1082
+ })
1083
+ ], AIBridgeEngine);
1084
+ export { AIBridgeEngine };
1085
+ //# sourceMappingURL=ai-bridge-engine.js.map