@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,505 @@
1
+ import { IMetadataProvider, IStartupSink, UserInfo } from '@memberjunction/core';
2
+ import { BaseSingleton } from '@memberjunction/global';
3
+ import { IRealtimeSession } from '@memberjunction/ai';
4
+ import { MJAIBridgeProviderEntity, MJAIBridgeAgentIdentityEntity, MJAIBridgeProviderChannelEntity } from '@memberjunction/core-entities';
5
+ import { AIBridgeEngineBase, BaseRealtimeBridge, BridgeDisconnectReason, TurnTakingPolicy, TurnTakingPolicyConfig, BridgeTurnMode, IAddressedMatcher, IWorthSayingScorer, IBridgeChannelHost, BridgeChannelToolDefinition, BridgeChannelToolResult } from '@memberjunction/ai-bridge-base';
6
+ import { MultiAgentRoomCoordinator } from './multi-agent-room-coordinator.js';
7
+ /**
8
+ * The host-instance identity provider the engine uses to stamp `HostInstanceID` for node affinity
9
+ * and orphan reconciliation. Mirrors `@memberjunction/server`'s `HostInstance` helper but is
10
+ * **injected** so this server-tier engine has no hard dependency on MJServer (which would create a
11
+ * layering inversion) and so tests can supply a deterministic identity.
12
+ *
13
+ * @see `/plans/realtime/realtime-bridges-architecture.md` §10 (host affinity + janitor).
14
+ */
15
+ export interface IHostInstanceIdentity {
16
+ /** Returns this process's stable host-instance identity (`hostname:pid:bootId`). */
17
+ GetHostInstanceID(): string;
18
+ /** Returns the host-name prefix (`hostname:`) matching ANY boot of this OS host. */
19
+ GetHostNamePrefix(): string;
20
+ }
21
+ /**
22
+ * A default {@link IHostInstanceIdentity} for standalone use (and a sane fallback when the host
23
+ * application does not inject one). Generates a stable `unknown-host:pid:bootId` identity at module
24
+ * load. Production hosts (MJServer) inject the real `HostInstance` helper so the janitor's host
25
+ * affinity matches across the whole deployment.
26
+ */
27
+ export declare class DefaultHostInstanceIdentity implements IHostInstanceIdentity {
28
+ private readonly hostName;
29
+ private readonly instanceId;
30
+ constructor();
31
+ /** @inheritdoc */
32
+ GetHostInstanceID(): string;
33
+ /** @inheritdoc */
34
+ GetHostNamePrefix(): string;
35
+ }
36
+ /**
37
+ * Parameters for {@link AIBridgeEngine.StartBridgeSession}.
38
+ *
39
+ * The engine does NOT construct the realtime model — the caller injects the already-open
40
+ * {@link IRealtimeSession} (or a session factory) so the engine stays testable without a real
41
+ * provider and so the realtime model's lifecycle stays owned by the agent/session layer above.
42
+ */
43
+ export interface StartBridgeSessionParams {
44
+ /** The `MJ: AI Agent Sessions` row this bridge attaches to (the session IS the existing session). */
45
+ AgentSessionID: string;
46
+ /** The bridge provider to transport through (resolved to its `DriverClass` for ClassFactory). */
47
+ Provider: MJAIBridgeProviderEntity;
48
+ /**
49
+ * The live realtime session the bridge media plane wires to. Injected (not constructed here) so
50
+ * the engine never depends on a concrete realtime provider — the transport seam is the only
51
+ * coupling, and it is to the {@link IRealtimeSession} interface.
52
+ */
53
+ RealtimeSession: IRealtimeSession;
54
+ /**
55
+ * The endpoint address — a meeting join URL/ID (meetings) or a phone number (telephony).
56
+ */
57
+ Address: string;
58
+ /** Connection direction. Defaults to `'Outbound'`. */
59
+ Direction?: 'Inbound' | 'Outbound';
60
+ /** How the agent connected. Defaults to `'OnDemand'`. */
61
+ JoinMethod?: 'InMeetingCommand' | 'InboundRoute' | 'Invite' | 'NativeInvite' | 'OnDemand' | 'Scheduled';
62
+ /**
63
+ * Turn-taking mode for the session. Defaults to `'Passive'` (speak only when addressed). The
64
+ * engine builds a {@link TurnTakingPolicy} from this and {@link StartBridgeSessionParams.TurnMatcher}/
65
+ * {@link StartBridgeSessionParams.TurnScorer}.
66
+ */
67
+ TurnMode?: BridgeTurnMode;
68
+ /**
69
+ * The addressed-matcher for Passive/Hybrid turn-taking (e.g. a {@link RegexAddressedMatcher}
70
+ * built from the agent's name + aliases). Required for Passive/Hybrid to ever speak.
71
+ */
72
+ TurnMatcher?: IAddressedMatcher;
73
+ /** The "worth saying" scorer for Active/Hybrid turn-taking. */
74
+ TurnScorer?: IWorthSayingScorer;
75
+ /** Optional extra turn-taking tuning (silence window, throttle, score threshold, clock). */
76
+ TurnTuning?: Partial<Omit<TurnTakingPolicyConfig, 'Mode' | 'Matcher' | 'Scorer'>>;
77
+ /** Per-session bridge configuration (resolved credential refs, region, …) passed to the driver. */
78
+ Configuration?: Record<string, unknown>;
79
+ /**
80
+ * Optional server-side channel-plane host (Part A — the generic channel wiring). When supplied,
81
+ * the engine starts the session's channels through it at connect, constructs a Meeting Controls
82
+ * channel from the driver's {@link BaseRealtimeBridge.GetMeetingControlsEventSource} (when the
83
+ * driver contributes one), feeds the realtime session's `SendContextNote` perception sink into the
84
+ * channel context, and surfaces the contributed server tools + executor onto the returned
85
+ * {@link ActiveBridgeSession} so the runner-constructing layer binds them to
86
+ * `RealtimeSessionRunner.ServerChannelTools` / `ExecuteServerChannelTool`.
87
+ *
88
+ * Additive and optional: `IRealtimeSession`-only callers (no channel plane) keep working untouched.
89
+ * In production this is an adapter (in `@memberjunction/ai-agents`, which owns `RealtimeChannelServerHost`)
90
+ * over the channel host; here the engine depends only on the {@link IBridgeChannelHost} interface so
91
+ * it takes no heavy dependency on the agents package.
92
+ */
93
+ ChannelHost?: IBridgeChannelHost;
94
+ /** The MJ user the bridge session runs as; every session is owned + audited by a user. */
95
+ ContextUser?: UserInfo;
96
+ /** The request-scoped metadata provider for all entity operations (multi-provider safe). */
97
+ MetadataProvider?: IMetadataProvider;
98
+ }
99
+ /**
100
+ * The live, in-memory handle for one running bridged session held by the engine. Carries the driver,
101
+ * the wired realtime session, the per-session turn-taking policy, and the persisted bridge row id so
102
+ * teardown can reach all of them.
103
+ */
104
+ export interface ActiveBridgeSession {
105
+ /** The `AIAgentSessionBridge` row id (the durable record). */
106
+ SessionBridgeID: string;
107
+ /** The `MJ: AI Agent Sessions` row id the bridge is attached to. */
108
+ AgentSessionID: string;
109
+ /** The concrete driver instance transporting media. */
110
+ Bridge: BaseRealtimeBridge;
111
+ /** The realtime session the driver's media plane is wired to. */
112
+ RealtimeSession: IRealtimeSession;
113
+ /** The per-session turn-taking policy gating generation. */
114
+ TurnPolicy: TurnTakingPolicy;
115
+ /** The provider row backing this session. */
116
+ Provider: MJAIBridgeProviderEntity;
117
+ /** The context user the session runs as (for participant upserts / teardown writes). */
118
+ ContextUser?: UserInfo;
119
+ /** The metadata provider bound to this session's entity operations. */
120
+ MetadataProvider?: IMetadataProvider;
121
+ /**
122
+ * The server-side channel host wired for this session (Part A), or `undefined` when the caller
123
+ * supplied none. Held so teardown can close the session's channels.
124
+ */
125
+ ChannelHost?: IBridgeChannelHost;
126
+ /**
127
+ * The server-executed tool definitions the session's channels contributed at connect (e.g. the
128
+ * Meeting Controls facilitator tools). Empty when no channel host / no contributing channels. The
129
+ * runner-constructing layer registers these as `RealtimeSessionRunner.ServerChannelTools`.
130
+ */
131
+ ServerChannelTools: BridgeChannelToolDefinition[];
132
+ /**
133
+ * Executes ONE server-channel tool call for this session, routed through the channel host. Bound by
134
+ * the runner-constructing layer to `RealtimeSessionRunner.ExecuteServerChannelTool`. `undefined`
135
+ * when no channel host was supplied. Never throws — resolves to a structured failure.
136
+ */
137
+ ExecuteServerChannelTool?: (toolName: string, argsJson: string) => Promise<BridgeChannelToolResult>;
138
+ }
139
+ /**
140
+ * Server-tier engine for the Realtime Bridge plane — **coordination + execution**.
141
+ *
142
+ * `AIBridgeEngine` **composes** {@link AIBridgeEngineBase} (the metadata-only cache of providers /
143
+ * identities / provider-channels) rather than extending it — exactly mirroring how the server
144
+ * `AIEngine` builds on `AIEngineBase` via containment. The base is itself a `BaseEngine` singleton
145
+ * keyed by class name, so *inheriting* from it would make the startup manager instantiate **two**
146
+ * separate engines (the base AND this subclass), each loading and event-subscribing its own copy of
147
+ * the same caches. Composition keeps exactly **one** `BaseEngine` cache — {@link AIBridgeEngineBase.Instance}
148
+ * — which this engine warms once via {@link HandleStartup} and reads through the delegating accessors
149
+ * below. This server engine then adds everything that actually *runs* a bridged session:
150
+ *
151
+ * - **The transport seam** (Phase 0, the deferred unification): {@link wireTransportSeam} connects
152
+ * the driver's media plane to the realtime session — inbound `OnMedia` → `SendInput`, outbound
153
+ * `OnOutput` → `SendMedia`. This is the "no client-facing pipe" gap the realtime guide flagged;
154
+ * the bridge IS that pipe.
155
+ * - **Bot-session lifecycle** — {@link StartBridgeSession} / {@link StopBridgeSession} drive the
156
+ * `AIAgentSessionBridge` status state machine (Pending → Connecting → Connected → Disconnected),
157
+ * stamp `HostInstanceID` for node affinity, and resolve the driver via the `ClassFactory`.
158
+ * - **Participant tracking** — subscribes the driver's roster events (when supported) and upserts
159
+ * `AIAgentSessionBridgeParticipant` rows.
160
+ * - **Turn-taking integration** — holds a {@link TurnTakingPolicy} per session and feeds diarized
161
+ * transcript segments through it, acting on the decision (Speak / PostToChat / Silent).
162
+ * - **Janitor scaffold** — {@link ReconcileOrphans} force-closes Connected bridges left by a dead
163
+ * host, following the `SessionJanitor` shape.
164
+ *
165
+ * The engine never constructs the realtime model: the {@link IRealtimeSession} is injected via
166
+ * {@link StartBridgeSessionParams}, keeping the only coupling the transport seam itself and making
167
+ * the whole engine unit-testable with a mock session + the {@link LoopbackBridge}.
168
+ *
169
+ * @see `/plans/realtime/realtime-bridges-architecture.md` §2 (layer cake), §7 (lifecycle), §10 (security/janitor).
170
+ */
171
+ export declare class AIBridgeEngine extends BaseSingleton<AIBridgeEngine> implements IStartupSink {
172
+ /** In-memory registry of bridged sessions this process currently hosts, keyed by bridge id (lowercased). */
173
+ private activeSessions;
174
+ /** Host-instance identity provider; injected by the host application or defaulted for standalone use. */
175
+ private hostIdentity;
176
+ /**
177
+ * Coordinates speaking discipline when MULTIPLE agent bridge sessions share one room (§4c —
178
+ * "1+ agents in a shared room"). Single-agent sessions never touch it; it is engaged only via the
179
+ * additive {@link RegisterRoomParticipant} / {@link UnregisterRoomParticipant} hooks, so the default
180
+ * single-agent path is wholly unaffected.
181
+ */
182
+ private readonly roomCoordinator;
183
+ /**
184
+ * The singleton accessor. Keyed by THIS class's name in the Global Object Store (via
185
+ * {@link BaseSingleton}), distinct from {@link AIBridgeEngineBase.Instance} — which this engine
186
+ * composes rather than inherits.
187
+ */
188
+ static get Instance(): AIBridgeEngine;
189
+ /**
190
+ * The single underlying {@link AIBridgeEngineBase} instance whose `BaseEngine` cache holds the
191
+ * bridge registry (providers / identities / provider-channels). Composed (not inherited) so the
192
+ * startup manager warms exactly one cache. All metadata reads on this engine delegate here.
193
+ */
194
+ protected get Base(): AIBridgeEngineBase;
195
+ /**
196
+ * Deferred-startup entry point (per {@link IStartupSink}). Warms the ONE composed base cache by
197
+ * delegating to {@link AIBridgeEngineBase.Config}; mirrors `AIEngine.HandleStartup`. No double
198
+ * load — there is only the base's cache to warm.
199
+ *
200
+ * @param contextUser The boot/system user context.
201
+ * @param provider Optional metadata provider override (multi-provider scenarios).
202
+ */
203
+ HandleStartup(contextUser?: UserInfo, provider?: IMetadataProvider): Promise<void>;
204
+ /**
205
+ * Loads (or refreshes) the composed base's bridge metadata cache. Delegates to
206
+ * {@link AIBridgeEngineBase.Config} so the warming path matches `AIEngine`'s shape and there is
207
+ * never a second cache to load. Idempotent — a no-op when already loaded unless `forceRefresh`.
208
+ *
209
+ * @param forceRefresh When `true`, reloads even if already loaded.
210
+ * @param contextUser Required server-side for proper data isolation.
211
+ * @param provider Optional explicit metadata provider (multi-provider scenarios).
212
+ */
213
+ Config(forceRefresh?: boolean, contextUser?: UserInfo, provider?: IMetadataProvider): Promise<void>;
214
+ /** Returns `true` once the composed base cache is loaded. */
215
+ get Loaded(): boolean;
216
+ /** All cached `MJ: AI Bridge Providers` rows. @see AIBridgeEngineBase.Providers */
217
+ get Providers(): MJAIBridgeProviderEntity[];
218
+ /** All cached `MJ: AI Bridge Agent Identities` rows. @see AIBridgeEngineBase.AgentIdentities */
219
+ get AgentIdentities(): MJAIBridgeAgentIdentityEntity[];
220
+ /** All cached `MJ: AI Bridge Provider Channels` rows. @see AIBridgeEngineBase.ProviderChannels */
221
+ get ProviderChannels(): MJAIBridgeProviderChannelEntity[];
222
+ /** Resolves a provider by display name. @see AIBridgeEngineBase.ProviderByName */
223
+ ProviderByName(name: string): MJAIBridgeProviderEntity | undefined;
224
+ /** Resolves a provider by `DriverClass`. @see AIBridgeEngineBase.ProviderByDriverClass */
225
+ ProviderByDriverClass(driverClass: string): MJAIBridgeProviderEntity | undefined;
226
+ /** Resolves an agent identity by its address value. @see AIBridgeEngineBase.IdentityByValue */
227
+ IdentityByValue(identityValue: string, providerId?: string): MJAIBridgeAgentIdentityEntity | undefined;
228
+ /** Returns the active identities for an agent. @see AIBridgeEngineBase.IdentitiesForAgent */
229
+ IdentitiesForAgent(agentId: string, providerId?: string): MJAIBridgeAgentIdentityEntity[];
230
+ /** Returns a provider's channels ordered by sequence. @see AIBridgeEngineBase.ChannelsForProvider */
231
+ ChannelsForProvider(providerId: string): MJAIBridgeProviderChannelEntity[];
232
+ /** Returns a provider's auto-attach (default) channels. @see AIBridgeEngineBase.DefaultChannelsForProvider */
233
+ DefaultChannelsForProvider(providerId: string): MJAIBridgeProviderChannelEntity[];
234
+ /**
235
+ * Injects the host-instance identity provider used for `HostInstanceID` stamping and janitor
236
+ * affinity. Production hosts (MJServer) call this once at boot with the real `HostInstance`
237
+ * helper; standalone callers can rely on the {@link DefaultHostInstanceIdentity}.
238
+ *
239
+ * @param identity The identity provider to use.
240
+ */
241
+ SetHostInstanceIdentity(identity: IHostInstanceIdentity): void;
242
+ /**
243
+ * The bridged sessions this process currently hosts (read-only snapshot).
244
+ */
245
+ get ActiveSessions(): ReadonlyArray<ActiveBridgeSession>;
246
+ /**
247
+ * The {@link MultiAgentRoomCoordinator} this engine uses for inter-agent floor arbitration when
248
+ * multiple agent bridge sessions share one room. Exposed so the runner-constructing layer can run
249
+ * `CanTakeFloor` / `TakeFloor` / `ReleaseFloor` around an agent's generation in a multi-agent room.
250
+ */
251
+ get RoomCoordinator(): MultiAgentRoomCoordinator;
252
+ /**
253
+ * Ties a bridge session into the multi-agent room coordinator when it joins a SHARED room (§4c). Call
254
+ * this for an agent session whose bridge connects into a room that other agent sessions may also
255
+ * inhabit — keyed by the shared external room id (the driver's `ExternalConnectionID` / the
256
+ * ConversationID). Once 2+ agents are registered on the same room, floor arbitration keeps exactly one
257
+ * agent speaking at a time across agents; combined with passive turn-taking, two agents are loop-safe.
258
+ *
259
+ * **Additive and opt-in.** A normal single-agent bridge never calls this and is wholly unaffected —
260
+ * the coordinator only matters once two sessions name the same room. Designating `isFacilitator`
261
+ * marks the agent (typically the one running the Meeting Controls channel) as the room's arbiter,
262
+ * which may override the floor to call on a specific agent.
263
+ *
264
+ * @param roomId The shared external room id all co-located agents key on.
265
+ * @param agentSessionId The agent session joining the room.
266
+ * @param isFacilitator Whether this agent is the room's facilitator (may override the floor).
267
+ */
268
+ RegisterRoomParticipant(roomId: string, agentSessionId: string, isFacilitator?: boolean): void;
269
+ /**
270
+ * Removes a bridge session from the multi-agent room coordinator (its bridge stopped / it left the
271
+ * room). Releases the floor if the leaving agent held it and clears the facilitator slot if it was
272
+ * the facilitator. Safe to call unconditionally on teardown — a no-op for sessions that were never
273
+ * registered as room participants.
274
+ *
275
+ * @param roomId The shared room the agent is leaving.
276
+ * @param agentSessionId The agent session leaving.
277
+ */
278
+ UnregisterRoomParticipant(roomId: string, agentSessionId: string): void;
279
+ /**
280
+ * Starts a bridged session: resolves + connects the driver, drives the bridge row through its
281
+ * status state machine, and **wires the transport seam** between the driver and the injected
282
+ * realtime session.
283
+ *
284
+ * Flow (mirrors the §7 state machine):
285
+ * 1. Create the `AIAgentSessionBridge` row as `Pending`, stamped with this host.
286
+ * 2. Resolve the driver via `ClassFactory.CreateInstance(BaseRealtimeBridge, provider.DriverClass)`.
287
+ * 3. Transition to `Connecting`, build the {@link RealtimeBridgeContext}, call `driver.Connect`.
288
+ * 4. On success: persist the platform handles, transition to `Connected`, wire the transport seam,
289
+ * wire participant tracking + turn-taking, register the live session.
290
+ * 5. On failure: transition to `Failed` and rethrow.
291
+ *
292
+ * @param params The session parameters (including the injected {@link IRealtimeSession}).
293
+ * @returns The live {@link ActiveBridgeSession} handle.
294
+ * @throws When the driver cannot be resolved or `Connect` fails (the row is stamped `Failed`).
295
+ */
296
+ StartBridgeSession(params: StartBridgeSessionParams): Promise<ActiveBridgeSession>;
297
+ /**
298
+ * Stops a bridged session: disconnects the driver, tears down the wired listeners, and transitions
299
+ * the bridge row to `Disconnected` with the supplied `CloseReason`. Idempotent — stopping a
300
+ * session this process no longer holds still attempts to reconcile the durable row.
301
+ *
302
+ * @param sessionBridgeID The `AIAgentSessionBridge` row id to stop.
303
+ * @param reason Why the bridge is closing (mirrors `CloseReason`).
304
+ * @param contextUser Required server-side for the durable-row write when the live session is gone.
305
+ * @param provider Required metadata provider when the live session is gone.
306
+ * @returns `true` when the durable row reached a `Disconnected` state.
307
+ */
308
+ StopBridgeSession(sessionBridgeID: string, reason: BridgeDisconnectReason, contextUser?: UserInfo, provider?: IMetadataProvider): Promise<boolean>;
309
+ /**
310
+ * Wires the bidirectional media transport seam between a bridge driver and a realtime session —
311
+ * the single piece of code that completes the realtime engine's deferred server-bridged media
312
+ * transport (the guide's "`SendInput`/`OnOutput` have no client-facing pipe" gap). The bridge IS
313
+ * that pipe.
314
+ *
315
+ * Two hooks, one per direction:
316
+ * - **Inbound** (`bridge.OnMedia` → `session.SendInput`): what the agent HEARS. Each inbound
317
+ * {@link BridgeMediaFrame} from the endpoint is unwrapped to its raw `ArrayBuffer` payload and
318
+ * streamed straight to the model.
319
+ * - **Outbound** (`session.OnOutput` → `bridge.SendMedia`): what the agent SAYS. Each model
320
+ * output `ArrayBuffer` is wrapped in an outbound audio {@link BridgeMediaFrame} and sent into
321
+ * the meeting/call.
322
+ *
323
+ * Audio is the first track lit up, so the outbound direction is wired as `audio-out`; video/screen
324
+ * tracks ride the same `SendMedia` method once the model emits them.
325
+ *
326
+ * @param active The live bridged session whose driver and realtime session are wired together.
327
+ */
328
+ private wireTransportSeam;
329
+ /**
330
+ * Unwraps a {@link BridgeMediaFrame} to the raw `ArrayBuffer` the realtime session consumes,
331
+ * preferring the binary `Bytes` payload and decoding `Base64` when only that is present. Returns
332
+ * `undefined` when the frame carries no payload (defensive — never forwards an empty frame).
333
+ *
334
+ * @param frame The inbound media frame.
335
+ * @returns The raw frame bytes, or `undefined` when the frame has no payload.
336
+ */
337
+ private frameToArrayBuffer;
338
+ /**
339
+ * Wraps a raw model-output `ArrayBuffer` in an outbound {@link BridgeMediaFrame} on the given
340
+ * track, using the fast binary payload path.
341
+ *
342
+ * @param chunk The raw output frame from the model.
343
+ * @param track The outbound track to stamp on the frame.
344
+ * @returns The outbound media frame.
345
+ */
346
+ private arrayBufferToFrame;
347
+ /**
348
+ * Decodes a base64 string into an `ArrayBuffer`. Uses Node's `Buffer` when available (the
349
+ * server tier) and falls back to `atob` otherwise so the seam stays environment-agnostic.
350
+ *
351
+ * @param base64 The base64-encoded payload.
352
+ * @returns The decoded `ArrayBuffer`.
353
+ */
354
+ private decodeBase64;
355
+ /**
356
+ * Subscribes the driver's roster-change stream (when the provider supports diarization/roster)
357
+ * and upserts `AIAgentSessionBridgeParticipant` rows on each change. Capability-gated: a driver
358
+ * without roster support throws from `OnParticipantChange`, which is caught and treated as
359
+ * "no participant tracking for this provider" rather than failing the session.
360
+ *
361
+ * @param active The live bridged session to track participants for.
362
+ */
363
+ private wireParticipantTracking;
364
+ /**
365
+ * Upserts the supplied participants onto the bridge as `AIAgentSessionBridgeParticipant` rows,
366
+ * matching existing rows by `ExternalParticipantID`. Best-effort: a failed write is logged and
367
+ * never propagates to the live media plane.
368
+ *
369
+ * @param active The live bridged session the participants belong to.
370
+ * @param participants The current roster from the driver.
371
+ */
372
+ private upsertParticipants;
373
+ /** Loads the existing participant rows for a bridge, keyed (lowercased) by `ExternalParticipantID`. */
374
+ private loadParticipants;
375
+ /** Inserts a new participant row or updates the matched existing one in place. */
376
+ private upsertOneParticipant;
377
+ /**
378
+ * Wires the session's turn-taking policy to its inbound transcript stream. Each diarized
379
+ * transcript segment is fed to {@link TurnTakingPolicy.EvaluateTurn} and the decision is acted
380
+ * on: `Speak` lets the realtime session take the floor (via {@link IRealtimeSession.RequestSpokenUpdate}
381
+ * when available, else a context note), `PostToChat` is delegated to the bridge chat path
382
+ * (currently a documented hook), and `Silent` does nothing.
383
+ *
384
+ * Only the realtime session's *user* transcripts drive turn-taking — assistant transcripts are
385
+ * the agent's own speech and would otherwise self-trigger.
386
+ *
387
+ * @param active The live bridged session.
388
+ */
389
+ private wireTurnTaking;
390
+ /**
391
+ * Acts on a turn-taking decision. Kept behind the injected {@link IRealtimeSession} interface so
392
+ * the actual model trigger stays the session's concern and the engine remains testable.
393
+ *
394
+ * @param active The live bridged session.
395
+ * @param action The decided action (`Speak` / `PostToChat` / `Silent`).
396
+ */
397
+ private applyTurnDecision;
398
+ /**
399
+ * Builds the per-session {@link TurnTakingPolicy} from the start params.
400
+ *
401
+ * @param params The session parameters.
402
+ * @returns The configured turn-taking policy.
403
+ */
404
+ private buildTurnPolicy;
405
+ /**
406
+ * Wires the session's server-side channel plane (Phase 2's `RealtimeChannelServerHost` +
407
+ * `MeetingControlsChannelServer`) to this bridged session — the generic, platform-agnostic
408
+ * integration the Phase 2 agent flagged as the bridge-server follow-up.
409
+ *
410
+ * When a {@link IBridgeChannelHost} was supplied, this:
411
+ * 1. Resolves the driver's optional Meeting Controls event source
412
+ * ({@link BaseRealtimeBridge.GetMeetingControlsEventSource}) — non-null only for drivers that
413
+ * contribute a facilitator surface.
414
+ * 2. Captures the realtime session's `SendContextNote` perception sink (when the provider supports
415
+ * mid-session context injection) so channel perception reaches the model.
416
+ * 3. Calls {@link IBridgeChannelHost.StartSessionChannels} to register the session's channels and
417
+ * construct + bind the Meeting Controls channel to the event source.
418
+ * 4. Reads the contributed server-channel tools and binds the per-session executor onto the
419
+ * {@link ActiveBridgeSession}, so the runner-constructing layer registers them as
420
+ * `RealtimeSessionRunner.ServerChannelTools` and routes `ExecuteServerChannelTool` here.
421
+ *
422
+ * Failure posture mirrors the channel plane itself: a channel-host error is logged and never
423
+ * propagates — the live media plane (the call/meeting) must not break because a channel failed.
424
+ *
425
+ * @param active The live bridged session to wire channels for.
426
+ */
427
+ private wireChannelPlane;
428
+ /**
429
+ * Closes the session's server-side channels through the channel host (best-effort; teardown must
430
+ * never throw). Invoked from {@link disconnectDriver} so every stop path — explicit, janitor,
431
+ * shutdown — releases the channel plane.
432
+ *
433
+ * @param active The live bridged session whose channels to close.
434
+ */
435
+ private closeChannelPlane;
436
+ /**
437
+ * Force-closes `Connected`/`Connecting` bridges left behind by a **previous boot of this host**
438
+ * (matching hostname prefix, differing instance id), stamping `CloseReason = 'Janitor'`. Mirrors
439
+ * `SessionJanitor.RunStartupRecovery`: a crash/redeploy vaporizes the in-memory driver sockets
440
+ * but leaves the durable rows reading `Connected` forever; this reconciles them.
441
+ *
442
+ * The actual *scheduling* (run once at boot + periodic sweep) is intentionally left to the host
443
+ * application (MJServer's startup + janitor timer) so this engine package carries no timer/IO of
444
+ * its own; call this method from that scheduler.
445
+ *
446
+ * @param contextUser The system user the reconciliation writes run as.
447
+ * @param provider The metadata provider for the reconciliation reads/writes.
448
+ * @returns The number of orphaned bridges closed.
449
+ */
450
+ ReconcileOrphans(contextUser: UserInfo, provider: IMetadataProvider): Promise<number>;
451
+ /** Loads the orphaned bridge rows matching the janitor filter. */
452
+ private loadOrphanRows;
453
+ /**
454
+ * Resolves the concrete bridge driver for a provider via the MJ `ClassFactory`, keyed by the
455
+ * provider's `DriverClass`.
456
+ *
457
+ * @param provider The provider whose `DriverClass` selects the driver.
458
+ * @returns The instantiated driver.
459
+ * @throws When no driver is registered under the provider's `DriverClass`.
460
+ */
461
+ private resolveDriver;
462
+ /**
463
+ * Builds the {@link RealtimeBridgeContext} handed to the driver's `Connect` from the start params
464
+ * and the provider's typed `SupportedFeatures`.
465
+ *
466
+ * @param params The session parameters.
467
+ * @returns The bridge context.
468
+ */
469
+ private buildBridgeContext;
470
+ /**
471
+ * Creates the `AIAgentSessionBridge` row as `Pending`, stamped with the host instance for affinity.
472
+ *
473
+ * @param params The session parameters.
474
+ * @returns The saved bridge row.
475
+ * @throws When the row cannot be created (no metadata provider, or save failure).
476
+ */
477
+ private createBridgeRow;
478
+ /**
479
+ * Transitions a bridge row to a new `Status` and persists it.
480
+ *
481
+ * @param row The bridge row to transition.
482
+ * @param status The target status.
483
+ * @param params The session parameters (carry the context user for the save).
484
+ */
485
+ private transitionStatus;
486
+ /** Stamps a bridge row `Failed` (best-effort) after a connect failure, logging the cause. */
487
+ private failBridgeRow;
488
+ /** Disconnects the driver of a live session, tolerant of driver teardown errors, and closes its channels. */
489
+ private disconnectDriver;
490
+ /**
491
+ * Loads a bridge row and transitions it to `Disconnected` with the supplied `CloseReason`,
492
+ * stamping `DisconnectedAt`. Idempotent — an already-`Disconnected`/`Failed` row is left untouched
493
+ * and reported as success.
494
+ *
495
+ * @param sessionBridgeID The bridge row id.
496
+ * @param reason The close reason to stamp.
497
+ * @param contextUser The user the write runs as.
498
+ * @param provider The metadata provider for the load/save.
499
+ * @returns `true` when the row is (or already was) in a terminal disconnected state.
500
+ */
501
+ private markBridgeDisconnected;
502
+ /** Escapes single quotes for safe embedding inside an `ExtraFilter` literal. */
503
+ private escapeSql;
504
+ }
505
+ //# sourceMappingURL=ai-bridge-engine.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ai-bridge-engine.d.ts","sourceRoot":"","sources":["../src/ai-bridge-engine.ts"],"names":[],"mappings":"AAAA,OAAO,EACH,iBAAiB,EACjB,YAAY,EACZ,QAAQ,EAKX,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,aAAa,EAAY,MAAM,wBAAwB,CAAC;AACjE,OAAO,EACH,gBAAgB,EAEnB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EACH,wBAAwB,EACxB,6BAA6B,EAC7B,+BAA+B,EAGlC,MAAM,+BAA+B,CAAC;AACvC,OAAO,EACH,kBAAkB,EAClB,kBAAkB,EAIlB,sBAAsB,EAEtB,gBAAgB,EAChB,sBAAsB,E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