@memberjunction/ai-bridge-server 0.0.1 → 5.41.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 +505 -0
  3. package/dist/ai-bridge-engine.d.ts.map +1 -0
  4. package/dist/ai-bridge-engine.js +833 -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,833 @@
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, } 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
+ * A default {@link IHostInstanceIdentity} for standalone use (and a sane fallback when the host
18
+ * application does not inject one). Generates a stable `unknown-host:pid:bootId` identity at module
19
+ * load. Production hosts (MJServer) inject the real `HostInstance` helper so the janitor's host
20
+ * affinity matches across the whole deployment.
21
+ */
22
+ export class DefaultHostInstanceIdentity {
23
+ constructor() {
24
+ const pid = typeof process !== 'undefined' && process.pid ? process.pid : 0;
25
+ // A cheap, dependency-free random boot id; good enough for the fallback path.
26
+ const bootId = Math.random().toString(36).slice(2) + Date.now().toString(36);
27
+ this.hostName = 'unknown-host';
28
+ this.instanceId = `${this.hostName}:${pid}:${bootId}`;
29
+ }
30
+ /** @inheritdoc */
31
+ GetHostInstanceID() {
32
+ return this.instanceId;
33
+ }
34
+ /** @inheritdoc */
35
+ GetHostNamePrefix() {
36
+ return `${this.hostName}:`;
37
+ }
38
+ }
39
+ /**
40
+ * Server-tier engine for the Realtime Bridge plane — **coordination + execution**.
41
+ *
42
+ * `AIBridgeEngine` **composes** {@link AIBridgeEngineBase} (the metadata-only cache of providers /
43
+ * identities / provider-channels) rather than extending it — exactly mirroring how the server
44
+ * `AIEngine` builds on `AIEngineBase` via containment. The base is itself a `BaseEngine` singleton
45
+ * keyed by class name, so *inheriting* from it would make the startup manager instantiate **two**
46
+ * separate engines (the base AND this subclass), each loading and event-subscribing its own copy of
47
+ * the same caches. Composition keeps exactly **one** `BaseEngine` cache — {@link AIBridgeEngineBase.Instance}
48
+ * — which this engine warms once via {@link HandleStartup} and reads through the delegating accessors
49
+ * below. This server engine then adds everything that actually *runs* a bridged session:
50
+ *
51
+ * - **The transport seam** (Phase 0, the deferred unification): {@link wireTransportSeam} connects
52
+ * the driver's media plane to the realtime session — inbound `OnMedia` → `SendInput`, outbound
53
+ * `OnOutput` → `SendMedia`. This is the "no client-facing pipe" gap the realtime guide flagged;
54
+ * the bridge IS that pipe.
55
+ * - **Bot-session lifecycle** — {@link StartBridgeSession} / {@link StopBridgeSession} drive the
56
+ * `AIAgentSessionBridge` status state machine (Pending → Connecting → Connected → Disconnected),
57
+ * stamp `HostInstanceID` for node affinity, and resolve the driver via the `ClassFactory`.
58
+ * - **Participant tracking** — subscribes the driver's roster events (when supported) and upserts
59
+ * `AIAgentSessionBridgeParticipant` rows.
60
+ * - **Turn-taking integration** — holds a {@link TurnTakingPolicy} per session and feeds diarized
61
+ * transcript segments through it, acting on the decision (Speak / PostToChat / Silent).
62
+ * - **Janitor scaffold** — {@link ReconcileOrphans} force-closes Connected bridges left by a dead
63
+ * host, following the `SessionJanitor` shape.
64
+ *
65
+ * The engine never constructs the realtime model: the {@link IRealtimeSession} is injected via
66
+ * {@link StartBridgeSessionParams}, keeping the only coupling the transport seam itself and making
67
+ * the whole engine unit-testable with a mock session + the {@link LoopbackBridge}.
68
+ *
69
+ * @see `/plans/realtime/realtime-bridges-architecture.md` §2 (layer cake), §7 (lifecycle), §10 (security/janitor).
70
+ */
71
+ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
72
+ constructor() {
73
+ super(...arguments);
74
+ /** In-memory registry of bridged sessions this process currently hosts, keyed by bridge id (lowercased). */
75
+ this.activeSessions = new Map();
76
+ /** Host-instance identity provider; injected by the host application or defaulted for standalone use. */
77
+ this.hostIdentity = new DefaultHostInstanceIdentity();
78
+ /**
79
+ * Coordinates speaking discipline when MULTIPLE agent bridge sessions share one room (§4c —
80
+ * "1+ agents in a shared room"). Single-agent sessions never touch it; it is engaged only via the
81
+ * additive {@link RegisterRoomParticipant} / {@link UnregisterRoomParticipant} hooks, so the default
82
+ * single-agent path is wholly unaffected.
83
+ */
84
+ this.roomCoordinator = new MultiAgentRoomCoordinator();
85
+ }
86
+ /**
87
+ * The singleton accessor. Keyed by THIS class's name in the Global Object Store (via
88
+ * {@link BaseSingleton}), distinct from {@link AIBridgeEngineBase.Instance} — which this engine
89
+ * composes rather than inherits.
90
+ */
91
+ static get Instance() {
92
+ return super.getInstance();
93
+ }
94
+ // ──────────────────────────────────────────────────────────────────────────────
95
+ // Composed base — the ONE BaseEngine cache. All metadata is read through this.
96
+ // ──────────────────────────────────────────────────────────────────────────────
97
+ /**
98
+ * The single underlying {@link AIBridgeEngineBase} instance whose `BaseEngine` cache holds the
99
+ * bridge registry (providers / identities / provider-channels). Composed (not inherited) so the
100
+ * startup manager warms exactly one cache. All metadata reads on this engine delegate here.
101
+ */
102
+ get Base() {
103
+ return AIBridgeEngineBase.Instance;
104
+ }
105
+ /**
106
+ * Deferred-startup entry point (per {@link IStartupSink}). Warms the ONE composed base cache by
107
+ * delegating to {@link AIBridgeEngineBase.Config}; mirrors `AIEngine.HandleStartup`. No double
108
+ * load — there is only the base's cache to warm.
109
+ *
110
+ * @param contextUser The boot/system user context.
111
+ * @param provider Optional metadata provider override (multi-provider scenarios).
112
+ */
113
+ async HandleStartup(contextUser, provider) {
114
+ await this.Config(false, contextUser, provider);
115
+ }
116
+ /**
117
+ * Loads (or refreshes) the composed base's bridge metadata cache. Delegates to
118
+ * {@link AIBridgeEngineBase.Config} so the warming path matches `AIEngine`'s shape and there is
119
+ * never a second cache to load. Idempotent — a no-op when already loaded unless `forceRefresh`.
120
+ *
121
+ * @param forceRefresh When `true`, reloads even if already loaded.
122
+ * @param contextUser Required server-side for proper data isolation.
123
+ * @param provider Optional explicit metadata provider (multi-provider scenarios).
124
+ */
125
+ async Config(forceRefresh, contextUser, provider) {
126
+ await this.Base.Config(forceRefresh, contextUser, provider);
127
+ }
128
+ /** Returns `true` once the composed base cache is loaded. */
129
+ get Loaded() {
130
+ return this.Base.Loaded;
131
+ }
132
+ // ── Delegated metadata surface (reads the ONE base cache) ──────────────────────
133
+ /** All cached `MJ: AI Bridge Providers` rows. @see AIBridgeEngineBase.Providers */
134
+ get Providers() {
135
+ return this.Base.Providers;
136
+ }
137
+ /** All cached `MJ: AI Bridge Agent Identities` rows. @see AIBridgeEngineBase.AgentIdentities */
138
+ get AgentIdentities() {
139
+ return this.Base.AgentIdentities;
140
+ }
141
+ /** All cached `MJ: AI Bridge Provider Channels` rows. @see AIBridgeEngineBase.ProviderChannels */
142
+ get ProviderChannels() {
143
+ return this.Base.ProviderChannels;
144
+ }
145
+ /** Resolves a provider by display name. @see AIBridgeEngineBase.ProviderByName */
146
+ ProviderByName(name) {
147
+ return this.Base.ProviderByName(name);
148
+ }
149
+ /** Resolves a provider by `DriverClass`. @see AIBridgeEngineBase.ProviderByDriverClass */
150
+ ProviderByDriverClass(driverClass) {
151
+ return this.Base.ProviderByDriverClass(driverClass);
152
+ }
153
+ /** Resolves an agent identity by its address value. @see AIBridgeEngineBase.IdentityByValue */
154
+ IdentityByValue(identityValue, providerId) {
155
+ return this.Base.IdentityByValue(identityValue, providerId);
156
+ }
157
+ /** Returns the active identities for an agent. @see AIBridgeEngineBase.IdentitiesForAgent */
158
+ IdentitiesForAgent(agentId, providerId) {
159
+ return this.Base.IdentitiesForAgent(agentId, providerId);
160
+ }
161
+ /** Returns a provider's channels ordered by sequence. @see AIBridgeEngineBase.ChannelsForProvider */
162
+ ChannelsForProvider(providerId) {
163
+ return this.Base.ChannelsForProvider(providerId);
164
+ }
165
+ /** Returns a provider's auto-attach (default) channels. @see AIBridgeEngineBase.DefaultChannelsForProvider */
166
+ DefaultChannelsForProvider(providerId) {
167
+ return this.Base.DefaultChannelsForProvider(providerId);
168
+ }
169
+ /**
170
+ * Injects the host-instance identity provider used for `HostInstanceID` stamping and janitor
171
+ * affinity. Production hosts (MJServer) call this once at boot with the real `HostInstance`
172
+ * helper; standalone callers can rely on the {@link DefaultHostInstanceIdentity}.
173
+ *
174
+ * @param identity The identity provider to use.
175
+ */
176
+ SetHostInstanceIdentity(identity) {
177
+ this.hostIdentity = identity;
178
+ }
179
+ /**
180
+ * The bridged sessions this process currently hosts (read-only snapshot).
181
+ */
182
+ get ActiveSessions() {
183
+ return Array.from(this.activeSessions.values());
184
+ }
185
+ // ──────────────────────────────────────────────────────────────────────────────
186
+ // Multi-party — shared-room coordination (§4c). Additive; single-agent unaffected.
187
+ // ──────────────────────────────────────────────────────────────────────────────
188
+ /**
189
+ * The {@link MultiAgentRoomCoordinator} this engine uses for inter-agent floor arbitration when
190
+ * multiple agent bridge sessions share one room. Exposed so the runner-constructing layer can run
191
+ * `CanTakeFloor` / `TakeFloor` / `ReleaseFloor` around an agent's generation in a multi-agent room.
192
+ */
193
+ get RoomCoordinator() {
194
+ return this.roomCoordinator;
195
+ }
196
+ /**
197
+ * Ties a bridge session into the multi-agent room coordinator when it joins a SHARED room (§4c). Call
198
+ * this for an agent session whose bridge connects into a room that other agent sessions may also
199
+ * inhabit — keyed by the shared external room id (the driver's `ExternalConnectionID` / the
200
+ * ConversationID). Once 2+ agents are registered on the same room, floor arbitration keeps exactly one
201
+ * agent speaking at a time across agents; combined with passive turn-taking, two agents are loop-safe.
202
+ *
203
+ * **Additive and opt-in.** A normal single-agent bridge never calls this and is wholly unaffected —
204
+ * the coordinator only matters once two sessions name the same room. Designating `isFacilitator`
205
+ * marks the agent (typically the one running the Meeting Controls channel) as the room's arbiter,
206
+ * which may override the floor to call on a specific agent.
207
+ *
208
+ * @param roomId The shared external room id all co-located agents key on.
209
+ * @param agentSessionId The agent session joining the room.
210
+ * @param isFacilitator Whether this agent is the room's facilitator (may override the floor).
211
+ */
212
+ RegisterRoomParticipant(roomId, agentSessionId, isFacilitator = false) {
213
+ this.roomCoordinator.RegisterRoomParticipant(roomId, agentSessionId, isFacilitator);
214
+ LogStatus(`[AIBridgeEngine] Agent session ${agentSessionId} registered in shared room ${roomId}` +
215
+ `${isFacilitator ? ' (facilitator)' : ''}; multi-agent=${this.roomCoordinator.IsMultiAgentRoom(roomId)}.`);
216
+ }
217
+ /**
218
+ * Removes a bridge session from the multi-agent room coordinator (its bridge stopped / it left the
219
+ * room). Releases the floor if the leaving agent held it and clears the facilitator slot if it was
220
+ * the facilitator. Safe to call unconditionally on teardown — a no-op for sessions that were never
221
+ * registered as room participants.
222
+ *
223
+ * @param roomId The shared room the agent is leaving.
224
+ * @param agentSessionId The agent session leaving.
225
+ */
226
+ UnregisterRoomParticipant(roomId, agentSessionId) {
227
+ this.roomCoordinator.UnregisterRoomParticipant(roomId, agentSessionId);
228
+ }
229
+ // ──────────────────────────────────────────────────────────────────────────────
230
+ // Lifecycle — start / stop a bridged session.
231
+ // ──────────────────────────────────────────────────────────────────────────────
232
+ /**
233
+ * Starts a bridged session: resolves + connects the driver, drives the bridge row through its
234
+ * status state machine, and **wires the transport seam** between the driver and the injected
235
+ * realtime session.
236
+ *
237
+ * Flow (mirrors the §7 state machine):
238
+ * 1. Create the `AIAgentSessionBridge` row as `Pending`, stamped with this host.
239
+ * 2. Resolve the driver via `ClassFactory.CreateInstance(BaseRealtimeBridge, provider.DriverClass)`.
240
+ * 3. Transition to `Connecting`, build the {@link RealtimeBridgeContext}, call `driver.Connect`.
241
+ * 4. On success: persist the platform handles, transition to `Connected`, wire the transport seam,
242
+ * wire participant tracking + turn-taking, register the live session.
243
+ * 5. On failure: transition to `Failed` and rethrow.
244
+ *
245
+ * @param params The session parameters (including the injected {@link IRealtimeSession}).
246
+ * @returns The live {@link ActiveBridgeSession} handle.
247
+ * @throws When the driver cannot be resolved or `Connect` fails (the row is stamped `Failed`).
248
+ */
249
+ async StartBridgeSession(params) {
250
+ const bridgeRow = await this.createBridgeRow(params);
251
+ try {
252
+ // Resolve the driver inside the try so a resolution failure still stamps the row Failed
253
+ // (the row already exists at this point — it must not be left dangling as Pending).
254
+ const driver = this.resolveDriver(params.Provider);
255
+ await this.transitionStatus(bridgeRow, 'Connecting', params);
256
+ const ctx = this.buildBridgeContext(params);
257
+ const result = await driver.Connect(ctx);
258
+ bridgeRow.ExternalConnectionID = result.ExternalConnectionId;
259
+ bridgeRow.BotParticipantID = result.BotParticipantId;
260
+ bridgeRow.ConnectedAt = new Date();
261
+ await this.transitionStatus(bridgeRow, 'Connected', params);
262
+ const turnPolicy = this.buildTurnPolicy(params);
263
+ const active = {
264
+ SessionBridgeID: bridgeRow.ID,
265
+ AgentSessionID: params.AgentSessionID,
266
+ Bridge: driver,
267
+ RealtimeSession: params.RealtimeSession,
268
+ TurnPolicy: turnPolicy,
269
+ Provider: params.Provider,
270
+ ContextUser: params.ContextUser,
271
+ MetadataProvider: params.MetadataProvider,
272
+ ChannelHost: params.ChannelHost,
273
+ ServerChannelTools: [],
274
+ };
275
+ this.wireTransportSeam(active);
276
+ this.wireParticipantTracking(active);
277
+ this.wireTurnTaking(active);
278
+ await this.wireChannelPlane(active);
279
+ this.activeSessions.set(bridgeRow.ID.toLowerCase(), active);
280
+ LogStatus(`[AIBridgeEngine] Bridge session ${bridgeRow.ID} connected via ${params.Provider.Name}`);
281
+ return active;
282
+ }
283
+ catch (err) {
284
+ await this.failBridgeRow(bridgeRow, params, err);
285
+ throw err;
286
+ }
287
+ }
288
+ /**
289
+ * Stops a bridged session: disconnects the driver, tears down the wired listeners, and transitions
290
+ * the bridge row to `Disconnected` with the supplied `CloseReason`. Idempotent — stopping a
291
+ * session this process no longer holds still attempts to reconcile the durable row.
292
+ *
293
+ * @param sessionBridgeID The `AIAgentSessionBridge` row id to stop.
294
+ * @param reason Why the bridge is closing (mirrors `CloseReason`).
295
+ * @param contextUser Required server-side for the durable-row write when the live session is gone.
296
+ * @param provider Required metadata provider when the live session is gone.
297
+ * @returns `true` when the durable row reached a `Disconnected` state.
298
+ */
299
+ async StopBridgeSession(sessionBridgeID, reason, contextUser, provider) {
300
+ const key = sessionBridgeID.toLowerCase();
301
+ const active = this.activeSessions.get(key);
302
+ if (active) {
303
+ await this.disconnectDriver(active, reason);
304
+ this.activeSessions.delete(key);
305
+ return this.markBridgeDisconnected(sessionBridgeID, reason, active.ContextUser ?? contextUser, active.MetadataProvider ?? provider);
306
+ }
307
+ // Not held by this process — still reconcile the durable row (janitor / cross-host close).
308
+ return this.markBridgeDisconnected(sessionBridgeID, reason, contextUser, provider);
309
+ }
310
+ // ──────────────────────────────────────────────────────────────────────────────
311
+ // THE TRANSPORT SEAM — the deferred "unified-transport track" completed here.
312
+ // ──────────────────────────────────────────────────────────────────────────────
313
+ /**
314
+ * Wires the bidirectional media transport seam between a bridge driver and a realtime session —
315
+ * the single piece of code that completes the realtime engine's deferred server-bridged media
316
+ * transport (the guide's "`SendInput`/`OnOutput` have no client-facing pipe" gap). The bridge IS
317
+ * that pipe.
318
+ *
319
+ * Two hooks, one per direction:
320
+ * - **Inbound** (`bridge.OnMedia` → `session.SendInput`): what the agent HEARS. Each inbound
321
+ * {@link BridgeMediaFrame} from the endpoint is unwrapped to its raw `ArrayBuffer` payload and
322
+ * streamed straight to the model.
323
+ * - **Outbound** (`session.OnOutput` → `bridge.SendMedia`): what the agent SAYS. Each model
324
+ * output `ArrayBuffer` is wrapped in an outbound audio {@link BridgeMediaFrame} and sent into
325
+ * the meeting/call.
326
+ *
327
+ * Audio is the first track lit up, so the outbound direction is wired as `audio-out`; video/screen
328
+ * tracks ride the same `SendMedia` method once the model emits them.
329
+ *
330
+ * @param active The live bridged session whose driver and realtime session are wired together.
331
+ */
332
+ wireTransportSeam(active) {
333
+ const { Bridge, RealtimeSession } = active;
334
+ // Inbound: endpoint media → the agent hears it.
335
+ Bridge.OnMedia((frame) => {
336
+ const chunk = this.frameToArrayBuffer(frame);
337
+ if (chunk) {
338
+ RealtimeSession.SendInput(chunk);
339
+ }
340
+ });
341
+ // Outbound: the agent speaks → into the meeting/call.
342
+ RealtimeSession.OnOutput((chunk) => {
343
+ const track = 'audio-out';
344
+ Bridge.SendMedia(track, this.arrayBufferToFrame(chunk, track));
345
+ });
346
+ }
347
+ /**
348
+ * Unwraps a {@link BridgeMediaFrame} to the raw `ArrayBuffer` the realtime session consumes,
349
+ * preferring the binary `Bytes` payload and decoding `Base64` when only that is present. Returns
350
+ * `undefined` when the frame carries no payload (defensive — never forwards an empty frame).
351
+ *
352
+ * @param frame The inbound media frame.
353
+ * @returns The raw frame bytes, or `undefined` when the frame has no payload.
354
+ */
355
+ frameToArrayBuffer(frame) {
356
+ if (frame.Bytes) {
357
+ return frame.Bytes;
358
+ }
359
+ if (frame.Base64) {
360
+ return this.decodeBase64(frame.Base64);
361
+ }
362
+ return undefined;
363
+ }
364
+ /**
365
+ * Wraps a raw model-output `ArrayBuffer` in an outbound {@link BridgeMediaFrame} on the given
366
+ * track, using the fast binary payload path.
367
+ *
368
+ * @param chunk The raw output frame from the model.
369
+ * @param track The outbound track to stamp on the frame.
370
+ * @returns The outbound media frame.
371
+ */
372
+ arrayBufferToFrame(chunk, track) {
373
+ return { Track: track, Bytes: chunk, TimestampMs: Date.now() };
374
+ }
375
+ /**
376
+ * Decodes a base64 string into an `ArrayBuffer`. Uses Node's `Buffer` when available (the
377
+ * server tier) and falls back to `atob` otherwise so the seam stays environment-agnostic.
378
+ *
379
+ * @param base64 The base64-encoded payload.
380
+ * @returns The decoded `ArrayBuffer`.
381
+ */
382
+ decodeBase64(base64) {
383
+ if (typeof Buffer !== 'undefined') {
384
+ const buf = Buffer.from(base64, 'base64');
385
+ // Copy into a fresh ArrayBuffer (Buffer.buffer is ArrayBufferLike under newer @types/node).
386
+ const out = new Uint8Array(buf.byteLength);
387
+ out.set(buf);
388
+ return out.buffer;
389
+ }
390
+ const binary = atob(base64);
391
+ const bytes = new Uint8Array(binary.length);
392
+ for (let i = 0; i < binary.length; i++) {
393
+ bytes[i] = binary.charCodeAt(i);
394
+ }
395
+ return bytes.buffer;
396
+ }
397
+ // ──────────────────────────────────────────────────────────────────────────────
398
+ // Participant tracking.
399
+ // ──────────────────────────────────────────────────────────────────────────────
400
+ /**
401
+ * Subscribes the driver's roster-change stream (when the provider supports diarization/roster)
402
+ * and upserts `AIAgentSessionBridgeParticipant` rows on each change. Capability-gated: a driver
403
+ * without roster support throws from `OnParticipantChange`, which is caught and treated as
404
+ * "no participant tracking for this provider" rather than failing the session.
405
+ *
406
+ * @param active The live bridged session to track participants for.
407
+ */
408
+ wireParticipantTracking(active) {
409
+ if (active.Provider.SupportedFeaturesObject?.SpeakerDiarization !== true) {
410
+ return; // provider metadata says no roster — never call the driver (defense-in-depth gate).
411
+ }
412
+ try {
413
+ active.Bridge.OnParticipantChange((participants) => {
414
+ void this.upsertParticipants(active, participants);
415
+ });
416
+ }
417
+ catch (err) {
418
+ // The driver did not actually implement roster despite the flag — log and continue.
419
+ LogError(`[AIBridgeEngine] Participant tracking unavailable for bridge ${active.SessionBridgeID}: ` +
420
+ `${err instanceof Error ? err.message : String(err)}`);
421
+ }
422
+ }
423
+ /**
424
+ * Upserts the supplied participants onto the bridge as `AIAgentSessionBridgeParticipant` rows,
425
+ * matching existing rows by `ExternalParticipantID`. Best-effort: a failed write is logged and
426
+ * never propagates to the live media plane.
427
+ *
428
+ * @param active The live bridged session the participants belong to.
429
+ * @param participants The current roster from the driver.
430
+ */
431
+ async upsertParticipants(active, participants) {
432
+ const provider = active.MetadataProvider;
433
+ if (!provider) {
434
+ return;
435
+ }
436
+ try {
437
+ const existing = await this.loadParticipants(active, provider);
438
+ for (const p of participants) {
439
+ await this.upsertOneParticipant(active, p, existing, provider);
440
+ }
441
+ }
442
+ catch (err) {
443
+ LogError(`[AIBridgeEngine] upsertParticipants failed for bridge ${active.SessionBridgeID}: ` +
444
+ `${err instanceof Error ? err.message : String(err)}`);
445
+ }
446
+ }
447
+ /** Loads the existing participant rows for a bridge, keyed (lowercased) by `ExternalParticipantID`. */
448
+ async loadParticipants(active, provider) {
449
+ const rv = RunView.FromMetadataProvider(provider);
450
+ const result = await rv.RunView({
451
+ EntityName: SESSION_BRIDGE_PARTICIPANT_ENTITY,
452
+ ExtraFilter: `SessionBridgeID='${active.SessionBridgeID}'`,
453
+ ResultType: 'entity_object',
454
+ }, active.ContextUser);
455
+ const map = new Map();
456
+ if (result.Success) {
457
+ for (const row of result.Results) {
458
+ if (row.ExternalParticipantID) {
459
+ map.set(row.ExternalParticipantID.toLowerCase(), row);
460
+ }
461
+ }
462
+ }
463
+ return map;
464
+ }
465
+ /** Inserts a new participant row or updates the matched existing one in place. */
466
+ async upsertOneParticipant(active, p, existing, provider) {
467
+ const key = p.ExternalId.toLowerCase();
468
+ let row = existing.get(key);
469
+ if (!row) {
470
+ row = await provider.GetEntityObject(SESSION_BRIDGE_PARTICIPANT_ENTITY, active.ContextUser);
471
+ row.NewRecord();
472
+ row.SessionBridgeID = active.SessionBridgeID;
473
+ row.ExternalParticipantID = p.ExternalId;
474
+ row.JoinedAt = new Date();
475
+ existing.set(key, row);
476
+ }
477
+ row.DisplayName = p.DisplayName ?? null;
478
+ row.Role = p.Role;
479
+ row.IsAgent = p.IsAgent;
480
+ const saved = await row.Save();
481
+ if (!saved) {
482
+ LogError(`[AIBridgeEngine] participant upsert save failed: ${row.LatestResult?.CompleteMessage ?? 'unknown error'}`);
483
+ }
484
+ }
485
+ // ──────────────────────────────────────────────────────────────────────────────
486
+ // Turn-taking integration.
487
+ // ──────────────────────────────────────────────────────────────────────────────
488
+ /**
489
+ * Wires the session's turn-taking policy to its inbound transcript stream. Each diarized
490
+ * transcript segment is fed to {@link TurnTakingPolicy.EvaluateTurn} and the decision is acted
491
+ * on: `Speak` lets the realtime session take the floor (via {@link IRealtimeSession.RequestSpokenUpdate}
492
+ * when available, else a context note), `PostToChat` is delegated to the bridge chat path
493
+ * (currently a documented hook), and `Silent` does nothing.
494
+ *
495
+ * Only the realtime session's *user* transcripts drive turn-taking — assistant transcripts are
496
+ * the agent's own speech and would otherwise self-trigger.
497
+ *
498
+ * @param active The live bridged session.
499
+ */
500
+ wireTurnTaking(active) {
501
+ active.RealtimeSession.OnTranscript((t) => {
502
+ if (t.Role !== 'user' || !t.IsFinal) {
503
+ return; // act only on a completed human turn
504
+ }
505
+ const segment = {
506
+ Text: t.Text,
507
+ IsAgent: false,
508
+ EndMs: Date.now(),
509
+ };
510
+ const decision = active.TurnPolicy.EvaluateTurn({ Segment: segment });
511
+ this.applyTurnDecision(active, decision.Action);
512
+ });
513
+ }
514
+ /**
515
+ * Acts on a turn-taking decision. Kept behind the injected {@link IRealtimeSession} interface so
516
+ * the actual model trigger stays the session's concern and the engine remains testable.
517
+ *
518
+ * @param active The live bridged session.
519
+ * @param action The decided action (`Speak` / `PostToChat` / `Silent`).
520
+ */
521
+ applyTurnDecision(active, action) {
522
+ switch (action) {
523
+ case 'Speak':
524
+ // Let the session respond. Prefer an instructed spoken update when the provider
525
+ // supports it; otherwise the inbound media already reached the model and it will
526
+ // respond on its own turn — nothing further to force.
527
+ if (active.RealtimeSession.RequestSpokenUpdate) {
528
+ active.RealtimeSession.RequestSpokenUpdate('Respond to the participant who just addressed you.');
529
+ }
530
+ break;
531
+ case 'PostToChat':
532
+ // Bridge chat is a Phase 2 channel surface; the hook is here so the wiring is complete.
533
+ // A chat-capable driver/channel will consume this once the server-side channel plane lands.
534
+ LogStatus(`[AIBridgeEngine] Turn decision PostToChat for bridge ${active.SessionBridgeID} (chat hook).`);
535
+ break;
536
+ case 'Silent':
537
+ default:
538
+ break;
539
+ }
540
+ }
541
+ /**
542
+ * Builds the per-session {@link TurnTakingPolicy} from the start params.
543
+ *
544
+ * @param params The session parameters.
545
+ * @returns The configured turn-taking policy.
546
+ */
547
+ buildTurnPolicy(params) {
548
+ const config = {
549
+ Mode: params.TurnMode ?? 'Passive',
550
+ Matcher: params.TurnMatcher,
551
+ Scorer: params.TurnScorer,
552
+ ...(params.TurnTuning ?? {}),
553
+ };
554
+ return new TurnTakingPolicy(config);
555
+ }
556
+ // ──────────────────────────────────────────────────────────────────────────────
557
+ // THE CHANNEL PLANE — Part A: generic wiring of the Phase 2 server-side channels.
558
+ // ──────────────────────────────────────────────────────────────────────────────
559
+ /**
560
+ * Wires the session's server-side channel plane (Phase 2's `RealtimeChannelServerHost` +
561
+ * `MeetingControlsChannelServer`) to this bridged session — the generic, platform-agnostic
562
+ * integration the Phase 2 agent flagged as the bridge-server follow-up.
563
+ *
564
+ * When a {@link IBridgeChannelHost} was supplied, this:
565
+ * 1. Resolves the driver's optional Meeting Controls event source
566
+ * ({@link BaseRealtimeBridge.GetMeetingControlsEventSource}) — non-null only for drivers that
567
+ * contribute a facilitator surface.
568
+ * 2. Captures the realtime session's `SendContextNote` perception sink (when the provider supports
569
+ * mid-session context injection) so channel perception reaches the model.
570
+ * 3. Calls {@link IBridgeChannelHost.StartSessionChannels} to register the session's channels and
571
+ * construct + bind the Meeting Controls channel to the event source.
572
+ * 4. Reads the contributed server-channel tools and binds the per-session executor onto the
573
+ * {@link ActiveBridgeSession}, so the runner-constructing layer registers them as
574
+ * `RealtimeSessionRunner.ServerChannelTools` and routes `ExecuteServerChannelTool` here.
575
+ *
576
+ * Failure posture mirrors the channel plane itself: a channel-host error is logged and never
577
+ * propagates — the live media plane (the call/meeting) must not break because a channel failed.
578
+ *
579
+ * @param active The live bridged session to wire channels for.
580
+ */
581
+ async wireChannelPlane(active) {
582
+ const host = active.ChannelHost;
583
+ if (!host) {
584
+ return; // IRealtimeSession-only caller — no channel plane to wire (back-compat).
585
+ }
586
+ try {
587
+ const meetingControls = active.Bridge.GetMeetingControlsEventSource();
588
+ // The model perceives channel events via SendContextNote when the provider supports it.
589
+ const sink = active.RealtimeSession.SendContextNote
590
+ ? (text) => active.RealtimeSession.SendContextNote?.(text)
591
+ : undefined;
592
+ await host.StartSessionChannels(active.AgentSessionID, meetingControls, sink);
593
+ active.ServerChannelTools = host.GetSessionServerTools(active.AgentSessionID) ?? [];
594
+ active.ExecuteServerChannelTool = (toolName, argsJson) => host.ExecuteSessionServerTool(active.AgentSessionID, toolName, argsJson);
595
+ LogStatus(`[AIBridgeEngine] Channel plane wired for bridge ${active.SessionBridgeID}: ` +
596
+ `${active.ServerChannelTools.length} server-channel tool(s)` +
597
+ `${meetingControls ? ' (incl. Meeting Controls)' : ''}.`);
598
+ }
599
+ catch (err) {
600
+ LogError(`[AIBridgeEngine] Channel-plane wiring failed for bridge ${active.SessionBridgeID} ` +
601
+ `(media plane unaffected): ${err instanceof Error ? err.message : String(err)}`);
602
+ }
603
+ }
604
+ /**
605
+ * Closes the session's server-side channels through the channel host (best-effort; teardown must
606
+ * never throw). Invoked from {@link disconnectDriver} so every stop path — explicit, janitor,
607
+ * shutdown — releases the channel plane.
608
+ *
609
+ * @param active The live bridged session whose channels to close.
610
+ */
611
+ async closeChannelPlane(active) {
612
+ if (!active.ChannelHost) {
613
+ return;
614
+ }
615
+ try {
616
+ await active.ChannelHost.CloseSessionChannels(active.AgentSessionID);
617
+ }
618
+ catch (err) {
619
+ LogError(`[AIBridgeEngine] Channel-plane close failed for bridge ${active.SessionBridgeID}: ` +
620
+ `${err instanceof Error ? err.message : String(err)}`);
621
+ }
622
+ }
623
+ // ──────────────────────────────────────────────────────────────────────────────
624
+ // Janitor — orphan reconciliation (scaffold; scheduling is a host-provided hook).
625
+ // ──────────────────────────────────────────────────────────────────────────────
626
+ /**
627
+ * Force-closes `Connected`/`Connecting` bridges left behind by a **previous boot of this host**
628
+ * (matching hostname prefix, differing instance id), stamping `CloseReason = 'Janitor'`. Mirrors
629
+ * `SessionJanitor.RunStartupRecovery`: a crash/redeploy vaporizes the in-memory driver sockets
630
+ * but leaves the durable rows reading `Connected` forever; this reconciles them.
631
+ *
632
+ * The actual *scheduling* (run once at boot + periodic sweep) is intentionally left to the host
633
+ * application (MJServer's startup + janitor timer) so this engine package carries no timer/IO of
634
+ * its own; call this method from that scheduler.
635
+ *
636
+ * @param contextUser The system user the reconciliation writes run as.
637
+ * @param provider The metadata provider for the reconciliation reads/writes.
638
+ * @returns The number of orphaned bridges closed.
639
+ */
640
+ async ReconcileOrphans(contextUser, provider) {
641
+ const prefix = this.escapeSql(this.hostIdentity.GetHostNamePrefix());
642
+ const current = this.escapeSql(this.hostIdentity.GetHostInstanceID());
643
+ const filter = `Status IN ('Connecting','Connected') ` +
644
+ `AND HostInstanceID LIKE '${prefix}%' ` +
645
+ `AND HostInstanceID <> '${current}'`;
646
+ const rows = await this.loadOrphanRows(filter, contextUser, provider);
647
+ let closed = 0;
648
+ for (const row of rows) {
649
+ const ok = await this.markBridgeDisconnected(row.ID, 'Janitor', contextUser, provider);
650
+ if (ok) {
651
+ closed++;
652
+ }
653
+ }
654
+ if (closed > 0) {
655
+ LogStatus(`[AIBridgeEngine] Janitor reconciled ${closed} orphaned bridge(s) from a prior boot of this host`);
656
+ }
657
+ return closed;
658
+ }
659
+ /** Loads the orphaned bridge rows matching the janitor filter. */
660
+ async loadOrphanRows(filter, contextUser, provider) {
661
+ const rv = RunView.FromMetadataProvider(provider);
662
+ const result = await rv.RunView({
663
+ EntityName: SESSION_BRIDGE_ENTITY,
664
+ ExtraFilter: filter,
665
+ ResultType: 'entity_object',
666
+ }, contextUser);
667
+ if (!result.Success) {
668
+ LogError(`[AIBridgeEngine] ReconcileOrphans load failed: ${result.ErrorMessage}`);
669
+ return [];
670
+ }
671
+ return result.Results;
672
+ }
673
+ // ──────────────────────────────────────────────────────────────────────────────
674
+ // Driver resolution + bridge-row persistence.
675
+ // ──────────────────────────────────────────────────────────────────────────────
676
+ /**
677
+ * Resolves the concrete bridge driver for a provider via the MJ `ClassFactory`, keyed by the
678
+ * provider's `DriverClass`.
679
+ *
680
+ * @param provider The provider whose `DriverClass` selects the driver.
681
+ * @returns The instantiated driver.
682
+ * @throws When no driver is registered under the provider's `DriverClass`.
683
+ */
684
+ resolveDriver(provider) {
685
+ const driverClass = provider.DriverClass;
686
+ // ClassFactory.CreateInstance FALLS BACK to the (abstract) base class when no driver is
687
+ // registered under the key — it never returns null for a non-null base. So we must verify a
688
+ // concrete registration exists first, otherwise we'd return an unusable abstract instance and
689
+ // fail later with an opaque "Connect is not a function".
690
+ const registration = MJGlobal.Instance.ClassFactory.GetRegistration(BaseRealtimeBridge, driverClass);
691
+ if (!registration) {
692
+ throw new Error(`No bridge driver registered for DriverClass '${driverClass}' (provider '${provider.Name}').`);
693
+ }
694
+ const driver = MJGlobal.Instance.ClassFactory.CreateInstance(BaseRealtimeBridge, driverClass);
695
+ if (!driver) {
696
+ throw new Error(`Failed to instantiate bridge driver '${driverClass}' (provider '${provider.Name}').`);
697
+ }
698
+ return driver;
699
+ }
700
+ /**
701
+ * Builds the {@link RealtimeBridgeContext} handed to the driver's `Connect` from the start params
702
+ * and the provider's typed `SupportedFeatures`.
703
+ *
704
+ * @param params The session parameters.
705
+ * @returns The bridge context.
706
+ */
707
+ buildBridgeContext(params) {
708
+ return {
709
+ Features: params.Provider.SupportedFeaturesObject ?? {},
710
+ ProviderName: params.Provider.Name,
711
+ Address: params.Address,
712
+ Configuration: params.Configuration,
713
+ ContextUser: params.ContextUser,
714
+ };
715
+ }
716
+ /**
717
+ * Creates the `AIAgentSessionBridge` row as `Pending`, stamped with the host instance for affinity.
718
+ *
719
+ * @param params The session parameters.
720
+ * @returns The saved bridge row.
721
+ * @throws When the row cannot be created (no metadata provider, or save failure).
722
+ */
723
+ async createBridgeRow(params) {
724
+ const provider = params.MetadataProvider;
725
+ if (!provider) {
726
+ throw new Error('AIBridgeEngine.StartBridgeSession requires a MetadataProvider.');
727
+ }
728
+ const row = await provider.GetEntityObject(SESSION_BRIDGE_ENTITY, params.ContextUser);
729
+ row.NewRecord();
730
+ row.AgentSessionID = params.AgentSessionID;
731
+ row.ProviderID = params.Provider.ID;
732
+ row.Direction = params.Direction ?? 'Outbound';
733
+ row.JoinMethod = params.JoinMethod ?? 'OnDemand';
734
+ row.TurnMode = params.TurnMode ?? 'Passive';
735
+ row.Address = params.Address;
736
+ row.Status = 'Pending';
737
+ row.HostInstanceID = this.hostIdentity.GetHostInstanceID();
738
+ const saved = await row.Save();
739
+ if (!saved) {
740
+ throw new Error(`Failed to create AIAgentSessionBridge: ${row.LatestResult?.CompleteMessage ?? 'unknown error'}`);
741
+ }
742
+ return row;
743
+ }
744
+ /**
745
+ * Transitions a bridge row to a new `Status` and persists it.
746
+ *
747
+ * @param row The bridge row to transition.
748
+ * @param status The target status.
749
+ * @param params The session parameters (carry the context user for the save).
750
+ */
751
+ async transitionStatus(row, status, params) {
752
+ row.Status = status;
753
+ const saved = await row.Save();
754
+ if (!saved) {
755
+ throw new Error(`Failed to transition bridge ${row.ID} to '${status}': ` +
756
+ `${row.LatestResult?.CompleteMessage ?? 'unknown error'} (user ${params.ContextUser?.Email ?? 'n/a'})`);
757
+ }
758
+ }
759
+ /** Stamps a bridge row `Failed` (best-effort) after a connect failure, logging the cause. */
760
+ async failBridgeRow(row, params, cause) {
761
+ LogError(`[AIBridgeEngine] Bridge ${row.ID} failed to connect via ${params.Provider.Name}: ` +
762
+ `${cause instanceof Error ? cause.message : String(cause)}`);
763
+ try {
764
+ row.Status = 'Failed';
765
+ row.CloseReason = 'Error';
766
+ row.DisconnectedAt = new Date();
767
+ await row.Save();
768
+ }
769
+ catch (err) {
770
+ LogError(`[AIBridgeEngine] failed to stamp bridge ${row.ID} as Failed: ${err instanceof Error ? err.message : String(err)}`);
771
+ }
772
+ }
773
+ /** Disconnects the driver of a live session, tolerant of driver teardown errors, and closes its channels. */
774
+ async disconnectDriver(active, reason) {
775
+ // Close the channel plane first so its post-close hooks see the session still mid-teardown,
776
+ // then release the driver's media plane.
777
+ await this.closeChannelPlane(active);
778
+ try {
779
+ await active.Bridge.Disconnect(reason);
780
+ }
781
+ catch (err) {
782
+ LogError(`[AIBridgeEngine] driver Disconnect failed for bridge ${active.SessionBridgeID}: ` +
783
+ `${err instanceof Error ? err.message : String(err)}`);
784
+ }
785
+ }
786
+ /**
787
+ * Loads a bridge row and transitions it to `Disconnected` with the supplied `CloseReason`,
788
+ * stamping `DisconnectedAt`. Idempotent — an already-`Disconnected`/`Failed` row is left untouched
789
+ * and reported as success.
790
+ *
791
+ * @param sessionBridgeID The bridge row id.
792
+ * @param reason The close reason to stamp.
793
+ * @param contextUser The user the write runs as.
794
+ * @param provider The metadata provider for the load/save.
795
+ * @returns `true` when the row is (or already was) in a terminal disconnected state.
796
+ */
797
+ async markBridgeDisconnected(sessionBridgeID, reason, contextUser, provider) {
798
+ if (!provider) {
799
+ LogError(`[AIBridgeEngine] markBridgeDisconnected requires a metadata provider (bridge ${sessionBridgeID}).`);
800
+ return false;
801
+ }
802
+ const row = await provider.GetEntityObject(SESSION_BRIDGE_ENTITY, contextUser);
803
+ const loaded = await row.Load(sessionBridgeID);
804
+ if (!loaded) {
805
+ return false;
806
+ }
807
+ if (row.Status === 'Disconnected' || row.Status === 'Failed') {
808
+ return true; // idempotent — already terminal, keep the original reason.
809
+ }
810
+ row.Status = 'Disconnected';
811
+ row.CloseReason = reason;
812
+ row.DisconnectedAt = new Date();
813
+ const saved = await row.Save();
814
+ if (!saved) {
815
+ LogError(`[AIBridgeEngine] markBridgeDisconnected save failed for ${sessionBridgeID}: ` +
816
+ `${row.LatestResult?.CompleteMessage ?? 'unknown error'}`);
817
+ }
818
+ return saved;
819
+ }
820
+ /** Escapes single quotes for safe embedding inside an `ExtraFilter` literal. */
821
+ escapeSql(value) {
822
+ return value.replace(/'/g, "''");
823
+ }
824
+ };
825
+ AIBridgeEngine = __decorate([
826
+ RegisterForStartup({
827
+ deferred: true,
828
+ deferredDelay: 15000,
829
+ description: 'Server-side AI Bridge Engine (realtime bridge coordination + transport seam)',
830
+ })
831
+ ], AIBridgeEngine);
832
+ export { AIBridgeEngine };
833
+ //# sourceMappingURL=ai-bridge-engine.js.map