@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,663 @@
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, BridgeNativeSdkBinding } from '@memberjunction/ai-bridge-base';
6
+ import { MultiAgentRoomCoordinator } from './multi-agent-room-coordinator.js';
7
+ /**
8
+ * Finalizes the co-agent observability run(s) for an agent session when a bridge is torn down WITHOUT a
9
+ * live in-memory session — a prior-boot orphan or a cross-host reap, where the agent layer's `Close()`-wrapped
10
+ * finalizer can't run, so the co-agent `AIAgentRun` would otherwise dangle in `Running` forever. The agent
11
+ * layer registers it via {@link AIBridgeEngine.SetSessionRunFinalizer} at startup (it lives in
12
+ * `@memberjunction/ai-agents`, not reachable from this package). **Idempotent**: for a clean same-process
13
+ * teardown the run is already `Completed`, so this is a harmless no-op.
14
+ */
15
+ export type BridgeSessionRunFinalizer = (agentSessionID: string, success: boolean, contextUser?: UserInfo, provider?: IMetadataProvider) => Promise<void>;
16
+ /**
17
+ * One final transcript line from a room's **scribe** session (the single elected per-room writer). The
18
+ * engine knows the room topology + owns the transcript tap; the SINK owns *where* it persists (e.g. an
19
+ * `MJ: Conversations` "Meeting Room" + `MJ: Conversation Details`). Keeping the Conversations/app specifics
20
+ * out of the engine — the engine only emits these neutral lines. See `plans/realtime/...followups.md` §5.
21
+ */
22
+ export interface BridgeTranscriptLine {
23
+ /** The room grouping (driver `ExternalConnectionId`) — one room = one unified transcript. */
24
+ RoomKey: string;
25
+ /** The scribe's agent-session id (stamped on the scribe's OWN speech lines). */
26
+ AgentSessionID: string;
27
+ /** The scribe's agent id, when known (attribution for its own speech). */
28
+ AgentID?: string;
29
+ /** `true` for the scribe's OWN speech (`assistant`), `false` for anything it heard (`user`). */
30
+ IsAgentSpeech: boolean;
31
+ /** The speaker's participant id — the scribe's own bot id for its speech; absent for heard speech. */
32
+ SpeakerParticipantID?: string;
33
+ /** The final transcript text for the turn. */
34
+ Text: string;
35
+ }
36
+ /**
37
+ * Registered by the app layer to persist the unified room transcript. The engine calls it for each FINAL
38
+ * transcript line from a room's scribe, passing the scribe session's `contextUser` + `provider` so the sink
39
+ * can write entities under the right identity. Bound once at startup (see `AIBridgeEngine.SetTranscriptSink`).
40
+ */
41
+ export type BridgeTranscriptSink = (line: BridgeTranscriptLine, contextUser?: UserInfo, provider?: IMetadataProvider) => void | Promise<void>;
42
+ /**
43
+ * The host-instance identity provider the engine uses to stamp `HostInstanceID` for node affinity
44
+ * and orphan reconciliation. Mirrors `@memberjunction/server`'s `HostInstance` helper but is
45
+ * **injected** so this server-tier engine has no hard dependency on MJServer (which would create a
46
+ * layering inversion) and so tests can supply a deterministic identity.
47
+ *
48
+ * @see `/plans/realtime/realtime-bridges-architecture.md` §10 (host affinity + janitor).
49
+ */
50
+ export interface IHostInstanceIdentity {
51
+ /** Returns this process's stable host-instance identity (`hostname:pid:bootId`). */
52
+ GetHostInstanceID(): string;
53
+ /** Returns the host-name prefix (`hostname:`) matching ANY boot of this OS host. */
54
+ GetHostNamePrefix(): string;
55
+ }
56
+ /**
57
+ * A default {@link IHostInstanceIdentity} for standalone use (and a sane fallback when the host
58
+ * application does not inject one). Generates a stable `unknown-host:pid:bootId` identity at module
59
+ * load. Production hosts (MJServer) inject the real `HostInstance` helper so the janitor's host
60
+ * affinity matches across the whole deployment.
61
+ */
62
+ export declare class DefaultHostInstanceIdentity implements IHostInstanceIdentity {
63
+ private readonly hostName;
64
+ private readonly instanceId;
65
+ constructor();
66
+ /** @inheritdoc */
67
+ GetHostInstanceID(): string;
68
+ /** @inheritdoc */
69
+ GetHostNamePrefix(): string;
70
+ }
71
+ /**
72
+ * Parameters for {@link AIBridgeEngine.StartBridgeSession}.
73
+ *
74
+ * The engine does NOT construct the realtime model — the caller injects the already-open
75
+ * {@link IRealtimeSession} (or a session factory) so the engine stays testable without a real
76
+ * provider and so the realtime model's lifecycle stays owned by the agent/session layer above.
77
+ */
78
+ export interface StartBridgeSessionParams {
79
+ /** The `MJ: AI Agent Sessions` row this bridge attaches to (the session IS the existing session). */
80
+ AgentSessionID: string;
81
+ /** The voicing agent's `MJ: AI Agents` id — used only to attribute this agent's transcript lines. */
82
+ AgentID?: string;
83
+ /** The bridge provider to transport through (resolved to its `DriverClass` for ClassFactory). */
84
+ Provider: MJAIBridgeProviderEntity;
85
+ /**
86
+ * The live realtime session the bridge media plane wires to. Injected (not constructed here) so
87
+ * the engine never depends on a concrete realtime provider — the transport seam is the only
88
+ * coupling, and it is to the {@link IRealtimeSession} interface.
89
+ */
90
+ RealtimeSession: IRealtimeSession;
91
+ /**
92
+ * The endpoint address — a meeting join URL/ID (meetings) or a phone number (telephony).
93
+ */
94
+ Address: string;
95
+ /** Connection direction. Defaults to `'Outbound'`. */
96
+ Direction?: 'Inbound' | 'Outbound';
97
+ /** How the agent connected. Defaults to `'OnDemand'`. */
98
+ JoinMethod?: 'InMeetingCommand' | 'InboundRoute' | 'Invite' | 'NativeInvite' | 'OnDemand' | 'Scheduled';
99
+ /**
100
+ * Turn-taking mode for the session. Defaults to `'Passive'` (speak only when addressed). The
101
+ * engine builds a {@link TurnTakingPolicy} from this and {@link StartBridgeSessionParams.TurnMatcher}/
102
+ * {@link StartBridgeSessionParams.TurnScorer}.
103
+ */
104
+ TurnMode?: BridgeTurnMode;
105
+ /**
106
+ * The addressed-matcher for Passive/Hybrid turn-taking (e.g. a {@link RegexAddressedMatcher}
107
+ * built from the agent's name + aliases). Required for Passive/Hybrid to ever speak.
108
+ */
109
+ TurnMatcher?: IAddressedMatcher;
110
+ /** The "worth saying" scorer for Active/Hybrid turn-taking. */
111
+ TurnScorer?: IWorthSayingScorer;
112
+ /** Optional extra turn-taking tuning (silence window, throttle, score threshold, clock). */
113
+ TurnTuning?: Partial<Omit<TurnTakingPolicyConfig, 'Mode' | 'Matcher' | 'Scorer'>>;
114
+ /**
115
+ * **Multi-agent meeting mode.** When `true`, the realtime model's blind auto-response was disabled at
116
+ * session start (the agent layer set `disableAutoResponse` on the model session), so the BRIDGE is the
117
+ * sole speech trigger: on a `Speak` turn decision the engine issues exactly one `RequestSpokenUpdate`.
118
+ * When `false`/absent the model auto-responds and the engine must NOT also trigger (it would double-fire).
119
+ * Must agree with what the session was opened with. See `plans/realtime/multi-agent-meeting-turn-taking.md`.
120
+ */
121
+ DisableAutoResponse?: boolean;
122
+ /** Per-session bridge configuration (resolved credential refs, region, …) passed to the driver. */
123
+ Configuration?: Record<string, unknown>;
124
+ /**
125
+ * Optional server-side channel-plane host (Part A — the generic channel wiring). When supplied,
126
+ * the engine starts the session's channels through it at connect, constructs a Meeting Controls
127
+ * channel from the driver's {@link BaseRealtimeBridge.GetMeetingControlsEventSource} (when the
128
+ * driver contributes one), feeds the realtime session's `SendContextNote` perception sink into the
129
+ * channel context, and surfaces the contributed server tools + executor onto the returned
130
+ * {@link ActiveBridgeSession} so the runner-constructing layer binds them to
131
+ * `RealtimeSessionRunner.ServerChannelTools` / `ExecuteServerChannelTool`.
132
+ *
133
+ * Additive and optional: `IRealtimeSession`-only callers (no channel plane) keep working untouched.
134
+ * In production this is an adapter (in `@memberjunction/ai-agents`, which owns `RealtimeChannelServerHost`)
135
+ * over the channel host; here the engine depends only on the {@link IBridgeChannelHost} interface so
136
+ * it takes no heavy dependency on the agents package.
137
+ */
138
+ ChannelHost?: IBridgeChannelHost;
139
+ /** The MJ user the bridge session runs as; every session is owned + audited by a user. */
140
+ ContextUser?: UserInfo;
141
+ /** The request-scoped metadata provider for all entity operations (multi-provider safe). */
142
+ MetadataProvider?: IMetadataProvider;
143
+ /**
144
+ * Optional per-session override for binding the driver's SDK factory, applied to the resolved driver
145
+ * just before `Connect`. When supplied it takes precedence over the {@link BridgeNativeSdkRegistry}
146
+ * default — use it to choose a non-default binding for a provider that has more than one (e.g. Zoom's
147
+ * RTMS receive-only binding instead of the native two-way default) or to inject a fake in a test.
148
+ * When omitted, the engine applies the provider's registered native binding (if any).
149
+ */
150
+ BindSdk?: BridgeNativeSdkBinding;
151
+ }
152
+ /**
153
+ * The live, in-memory handle for one running bridged session held by the engine. Carries the driver,
154
+ * the wired realtime session, the per-session turn-taking policy, and the persisted bridge row id so
155
+ * teardown can reach all of them.
156
+ */
157
+ export interface ActiveBridgeSession {
158
+ /** The `AIAgentSessionBridge` row id (the durable record). */
159
+ SessionBridgeID: string;
160
+ /** The `MJ: AI Agent Sessions` row id the bridge is attached to. */
161
+ AgentSessionID: string;
162
+ /** The voicing agent's `MJ: AI Agents` id — stamped on this agent's transcript lines for attribution. */
163
+ AgentID?: string;
164
+ /** The concrete driver instance transporting media. */
165
+ Bridge: BaseRealtimeBridge;
166
+ /** The realtime session the driver's media plane is wired to. */
167
+ RealtimeSession: IRealtimeSession;
168
+ /** The per-session turn-taking policy gating generation. */
169
+ TurnPolicy: TurnTakingPolicy;
170
+ /**
171
+ * Whether the model's blind auto-response is OFF for this session (multi-agent meeting). When `true`
172
+ * the bridge is the sole speech trigger — a `Speak` decision issues one `RequestSpokenUpdate`. When
173
+ * `false` the model auto-responds and the engine stays hands-off (forcing would double-fire).
174
+ */
175
+ DisableAutoResponse: boolean;
176
+ /**
177
+ * Whether at least one HUMAN participant has been seen in the room. Auto-leave only fires after a human
178
+ * was present and then all humans left — so a bot that joins ahead of anyone (or a momentarily bot-only
179
+ * roster at startup) is never reaped prematurely. Set by the occupancy check off the driver roster.
180
+ */
181
+ HasSeenHuman: boolean;
182
+ /**
183
+ * Pending grace timer started when the last human leaves. If a human rejoins within the grace window
184
+ * (e.g. a page refresh) it is cleared; otherwise it fires {@link AIBridgeEngine.StopBridgeSession} so the
185
+ * bot leaves the empty room and its co-agent run finalizes. Cleared on any teardown.
186
+ */
187
+ LeaveGraceTimer?: ReturnType<typeof setTimeout>;
188
+ /** The room key (driver `ExternalConnectionId`) this session is in — the unified-transcript room grouping. */
189
+ RoomKey?: string;
190
+ /** This session's own bot participant id on the endpoint — the speaker label on its own transcript lines. */
191
+ BotParticipantID?: string;
192
+ /**
193
+ * Whether THIS session is the room's transcript **scribe**. Exactly one session per room writes the
194
+ * unified meeting transcript (its own speech + everything it hears), so a multi-agent room records one
195
+ * copy, not N. Elected at connect (first session in the room); re-elected if the scribe leaves.
196
+ */
197
+ IsTranscriptScribe: boolean;
198
+ /** The provider row backing this session. */
199
+ Provider: MJAIBridgeProviderEntity;
200
+ /** The context user the session runs as (for participant upserts / teardown writes). */
201
+ ContextUser?: UserInfo;
202
+ /** The metadata provider bound to this session's entity operations. */
203
+ MetadataProvider?: IMetadataProvider;
204
+ /**
205
+ * The server-side channel host wired for this session (Part A), or `undefined` when the caller
206
+ * supplied none. Held so teardown can close the session's channels.
207
+ */
208
+ ChannelHost?: IBridgeChannelHost;
209
+ /**
210
+ * The server-executed tool definitions the session's channels contributed at connect (e.g. the
211
+ * Meeting Controls facilitator tools). Empty when no channel host / no contributing channels. The
212
+ * runner-constructing layer registers these as `RealtimeSessionRunner.ServerChannelTools`.
213
+ */
214
+ ServerChannelTools: BridgeChannelToolDefinition[];
215
+ /**
216
+ * Executes ONE server-channel tool call for this session, routed through the channel host. Bound by
217
+ * the runner-constructing layer to `RealtimeSessionRunner.ExecuteServerChannelTool`. `undefined`
218
+ * when no channel host was supplied. Never throws — resolves to a structured failure.
219
+ */
220
+ ExecuteServerChannelTool?: (toolName: string, argsJson: string) => Promise<BridgeChannelToolResult>;
221
+ }
222
+ /**
223
+ * Server-tier engine for the Realtime Bridge plane — **coordination + execution**.
224
+ *
225
+ * `AIBridgeEngine` **composes** {@link AIBridgeEngineBase} (the metadata-only cache of providers /
226
+ * identities / provider-channels) rather than extending it — exactly mirroring how the server
227
+ * `AIEngine` builds on `AIEngineBase` via containment. The base is itself a `BaseEngine` singleton
228
+ * keyed by class name, so *inheriting* from it would make the startup manager instantiate **two**
229
+ * separate engines (the base AND this subclass), each loading and event-subscribing its own copy of
230
+ * the same caches. Composition keeps exactly **one** `BaseEngine` cache — {@link AIBridgeEngineBase.Instance}
231
+ * — which this engine warms once via {@link HandleStartup} and reads through the delegating accessors
232
+ * below. This server engine then adds everything that actually *runs* a bridged session:
233
+ *
234
+ * - **The transport seam** (Phase 0, the deferred unification): {@link wireTransportSeam} connects
235
+ * the driver's media plane to the realtime session — inbound `OnMedia` → `SendInput`, outbound
236
+ * `OnOutput` → `SendMedia`. This is the "no client-facing pipe" gap the realtime guide flagged;
237
+ * the bridge IS that pipe.
238
+ * - **Bot-session lifecycle** — {@link StartBridgeSession} / {@link StopBridgeSession} drive the
239
+ * `AIAgentSessionBridge` status state machine (Pending → Connecting → Connected → Disconnected),
240
+ * stamp `HostInstanceID` for node affinity, and resolve the driver via the `ClassFactory`.
241
+ * - **Participant tracking** — subscribes the driver's roster events (when supported) and upserts
242
+ * `AIAgentSessionBridgeParticipant` rows.
243
+ * - **Turn-taking integration** — holds a {@link TurnTakingPolicy} per session and feeds diarized
244
+ * transcript segments through it, acting on the decision (Speak / PostToChat / Silent).
245
+ * - **Janitor scaffold** — {@link ReconcileOrphans} force-closes Connected bridges left by a dead
246
+ * host, following the `SessionJanitor` shape.
247
+ *
248
+ * The engine never constructs the realtime model: the {@link IRealtimeSession} is injected via
249
+ * {@link StartBridgeSessionParams}, keeping the only coupling the transport seam itself and making
250
+ * the whole engine unit-testable with a mock session + the {@link LoopbackBridge}.
251
+ *
252
+ * @see `/plans/realtime/realtime-bridges-architecture.md` §2 (layer cake), §7 (lifecycle), §10 (security/janitor).
253
+ */
254
+ export declare class AIBridgeEngine extends BaseSingleton<AIBridgeEngine> implements IStartupSink {
255
+ /** Registered by the agent layer; finalizes dangling co-agent runs on orphan/cross-host teardown. */
256
+ private runFinalizer?;
257
+ /** Registered by the app layer; persists the unified per-room transcript from the elected scribe. */
258
+ private transcriptSink?;
259
+ /** roomKey (lowercased) → the bridge id of that room's current transcript scribe. Election dedup. */
260
+ private readonly roomScribes;
261
+ /** Diagnostic: session ids that have already logged their first inbound / outbound media frame. */
262
+ private diagInbound;
263
+ private diagOutbound;
264
+ /** In-memory registry of bridged sessions this process currently hosts, keyed by bridge id (lowercased). */
265
+ private activeSessions;
266
+ /** Host-instance identity provider; injected by the host application or defaulted for standalone use. */
267
+ private hostIdentity;
268
+ /**
269
+ * Coordinates speaking discipline when MULTIPLE agent bridge sessions share one room (§4c —
270
+ * "1+ agents in a shared room"). Single-agent sessions never touch it; it is engaged only via the
271
+ * additive {@link RegisterRoomParticipant} / {@link UnregisterRoomParticipant} hooks, so the default
272
+ * single-agent path is wholly unaffected.
273
+ */
274
+ private readonly roomCoordinator;
275
+ /**
276
+ * The singleton accessor. Keyed by THIS class's name in the Global Object Store (via
277
+ * {@link BaseSingleton}), distinct from {@link AIBridgeEngineBase.Instance} — which this engine
278
+ * composes rather than inherits.
279
+ */
280
+ static get Instance(): AIBridgeEngine;
281
+ /**
282
+ * The single underlying {@link AIBridgeEngineBase} instance whose `BaseEngine` cache holds the
283
+ * bridge registry (providers / identities / provider-channels). Composed (not inherited) so the
284
+ * startup manager warms exactly one cache. All metadata reads on this engine delegate here.
285
+ */
286
+ protected get Base(): AIBridgeEngineBase;
287
+ /**
288
+ * Deferred-startup entry point (per {@link IStartupSink}). Warms the ONE composed base cache by
289
+ * delegating to {@link AIBridgeEngineBase.Config}; mirrors `AIEngine.HandleStartup`. No double
290
+ * load — there is only the base's cache to warm.
291
+ *
292
+ * @param contextUser The boot/system user context.
293
+ * @param provider Optional metadata provider override (multi-provider scenarios).
294
+ */
295
+ HandleStartup(contextUser?: UserInfo, provider?: IMetadataProvider): Promise<void>;
296
+ /**
297
+ * Loads (or refreshes) the composed base's bridge metadata cache. Delegates to
298
+ * {@link AIBridgeEngineBase.Config} so the warming path matches `AIEngine`'s shape and there is
299
+ * never a second cache to load. Idempotent — a no-op when already loaded unless `forceRefresh`.
300
+ *
301
+ * @param forceRefresh When `true`, reloads even if already loaded.
302
+ * @param contextUser Required server-side for proper data isolation.
303
+ * @param provider Optional explicit metadata provider (multi-provider scenarios).
304
+ */
305
+ Config(forceRefresh?: boolean, contextUser?: UserInfo, provider?: IMetadataProvider): Promise<void>;
306
+ /** Returns `true` once the composed base cache is loaded. */
307
+ get Loaded(): boolean;
308
+ /** All cached `MJ: AI Bridge Providers` rows. @see AIBridgeEngineBase.Providers */
309
+ get Providers(): MJAIBridgeProviderEntity[];
310
+ /** All cached `MJ: AI Bridge Agent Identities` rows. @see AIBridgeEngineBase.AgentIdentities */
311
+ get AgentIdentities(): MJAIBridgeAgentIdentityEntity[];
312
+ /** All cached `MJ: AI Bridge Provider Channels` rows. @see AIBridgeEngineBase.ProviderChannels */
313
+ get ProviderChannels(): MJAIBridgeProviderChannelEntity[];
314
+ /** Resolves a provider by display name. @see AIBridgeEngineBase.ProviderByName */
315
+ ProviderByName(name: string): MJAIBridgeProviderEntity | undefined;
316
+ /** Resolves a provider by `DriverClass`. @see AIBridgeEngineBase.ProviderByDriverClass */
317
+ ProviderByDriverClass(driverClass: string): MJAIBridgeProviderEntity | undefined;
318
+ /** Resolves an agent identity by its address value. @see AIBridgeEngineBase.IdentityByValue */
319
+ IdentityByValue(identityValue: string, providerId?: string): MJAIBridgeAgentIdentityEntity | undefined;
320
+ /**
321
+ * Registers the {@link BridgeSessionRunFinalizer} this engine calls when a bridge is marked disconnected
322
+ * without a live in-memory session (orphan/cross-host reap) — so the co-agent run finalizes there too,
323
+ * not only on the same-process `Close()` path. Bound once at startup by the agent layer. Idempotent.
324
+ *
325
+ * @param finalizer The finalizer (from `@memberjunction/ai-agents`).
326
+ */
327
+ SetSessionRunFinalizer(finalizer: BridgeSessionRunFinalizer): void;
328
+ /**
329
+ * Registers the {@link BridgeTranscriptSink} that persists the unified per-room transcript. The engine
330
+ * elects one scribe per room and feeds its final transcript lines here; the sink owns *where* they land
331
+ * (e.g. an `MJ: Conversations` "Meeting Room"). Bound once at startup by the app layer. Without it, no
332
+ * transcript is persisted (the engine still elects a scribe but emits nothing).
333
+ *
334
+ * @param sink The transcript sink (from the app layer).
335
+ */
336
+ SetTranscriptSink(sink: BridgeTranscriptSink): void;
337
+ /** Returns the active identities for an agent. @see AIBridgeEngineBase.IdentitiesForAgent */
338
+ IdentitiesForAgent(agentId: string, providerId?: string): MJAIBridgeAgentIdentityEntity[];
339
+ /** Returns a provider's channels ordered by sequence. @see AIBridgeEngineBase.ChannelsForProvider */
340
+ ChannelsForProvider(providerId: string): MJAIBridgeProviderChannelEntity[];
341
+ /** Returns a provider's auto-attach (default) channels. @see AIBridgeEngineBase.DefaultChannelsForProvider */
342
+ DefaultChannelsForProvider(providerId: string): MJAIBridgeProviderChannelEntity[];
343
+ /**
344
+ * Injects the host-instance identity provider used for `HostInstanceID` stamping and janitor
345
+ * affinity. Production hosts (MJServer) call this once at boot with the real `HostInstance`
346
+ * helper; standalone callers can rely on the {@link DefaultHostInstanceIdentity}.
347
+ *
348
+ * @param identity The identity provider to use.
349
+ */
350
+ SetHostInstanceIdentity(identity: IHostInstanceIdentity): void;
351
+ /**
352
+ * The bridged sessions this process currently hosts (read-only snapshot).
353
+ */
354
+ get ActiveSessions(): ReadonlyArray<ActiveBridgeSession>;
355
+ /**
356
+ * The {@link MultiAgentRoomCoordinator} this engine uses for inter-agent floor arbitration when
357
+ * multiple agent bridge sessions share one room. Exposed so the runner-constructing layer can run
358
+ * `CanTakeFloor` / `TakeFloor` / `ReleaseFloor` around an agent's generation in a multi-agent room.
359
+ */
360
+ get RoomCoordinator(): MultiAgentRoomCoordinator;
361
+ /**
362
+ * Ties a bridge session into the multi-agent room coordinator when it joins a SHARED room (§4c). Call
363
+ * this for an agent session whose bridge connects into a room that other agent sessions may also
364
+ * inhabit — keyed by the shared external room id (the driver's `ExternalConnectionID` / the
365
+ * ConversationID). Once 2+ agents are registered on the same room, floor arbitration keeps exactly one
366
+ * agent speaking at a time across agents; combined with passive turn-taking, two agents are loop-safe.
367
+ *
368
+ * **Additive and opt-in.** A normal single-agent bridge never calls this and is wholly unaffected —
369
+ * the coordinator only matters once two sessions name the same room. Designating `isFacilitator`
370
+ * marks the agent (typically the one running the Meeting Controls channel) as the room's arbiter,
371
+ * which may override the floor to call on a specific agent.
372
+ *
373
+ * @param roomId The shared external room id all co-located agents key on.
374
+ * @param agentSessionId The agent session joining the room.
375
+ * @param isFacilitator Whether this agent is the room's facilitator (may override the floor).
376
+ */
377
+ RegisterRoomParticipant(roomId: string, agentSessionId: string, isFacilitator?: boolean): void;
378
+ /**
379
+ * Removes a bridge session from the multi-agent room coordinator (its bridge stopped / it left the
380
+ * room). Releases the floor if the leaving agent held it and clears the facilitator slot if it was
381
+ * the facilitator. Safe to call unconditionally on teardown — a no-op for sessions that were never
382
+ * registered as room participants.
383
+ *
384
+ * @param roomId The shared room the agent is leaving.
385
+ * @param agentSessionId The agent session leaving.
386
+ */
387
+ UnregisterRoomParticipant(roomId: string, agentSessionId: string): void;
388
+ /**
389
+ * Starts a bridged session: resolves + connects the driver, drives the bridge row through its
390
+ * status state machine, and **wires the transport seam** between the driver and the injected
391
+ * realtime session.
392
+ *
393
+ * Flow (mirrors the §7 state machine):
394
+ * 1. Create the `AIAgentSessionBridge` row as `Pending`, stamped with this host.
395
+ * 2. Resolve the driver via `ClassFactory.CreateInstance(BaseRealtimeBridge, provider.DriverClass)`.
396
+ * 3. Transition to `Connecting`, build the {@link RealtimeBridgeContext}, call `driver.Connect`.
397
+ * 4. On success: persist the platform handles, transition to `Connected`, wire the transport seam,
398
+ * wire participant tracking + turn-taking, register the live session.
399
+ * 5. On failure: transition to `Failed` and rethrow.
400
+ *
401
+ * @param params The session parameters (including the injected {@link IRealtimeSession}).
402
+ * @returns The live {@link ActiveBridgeSession} handle.
403
+ * @throws When the driver cannot be resolved or `Connect` fails (the row is stamped `Failed`).
404
+ */
405
+ StartBridgeSession(params: StartBridgeSessionParams): Promise<ActiveBridgeSession>;
406
+ /**
407
+ * Stops a bridged session: disconnects the driver, tears down the wired listeners, and transitions
408
+ * the bridge row to `Disconnected` with the supplied `CloseReason`. Idempotent — stopping a
409
+ * session this process no longer holds still attempts to reconcile the durable row.
410
+ *
411
+ * @param sessionBridgeID The `AIAgentSessionBridge` row id to stop.
412
+ * @param reason Why the bridge is closing (mirrors `CloseReason`).
413
+ * @param contextUser Required server-side for the durable-row write when the live session is gone.
414
+ * @param provider Required metadata provider when the live session is gone.
415
+ * @returns `true` when the durable row reached a `Disconnected` state.
416
+ */
417
+ StopBridgeSession(sessionBridgeID: string, reason: BridgeDisconnectReason, contextUser?: UserInfo, provider?: IMetadataProvider): Promise<boolean>;
418
+ /**
419
+ * Wires the bidirectional media transport seam between a bridge driver and a realtime session —
420
+ * the single piece of code that completes the realtime engine's deferred server-bridged media
421
+ * transport (the guide's "`SendInput`/`OnOutput` have no client-facing pipe" gap). The bridge IS
422
+ * that pipe.
423
+ *
424
+ * Two hooks, one per direction:
425
+ * - **Inbound** (`bridge.OnMedia` → `session.SendInput`): what the agent HEARS. Each inbound
426
+ * {@link BridgeMediaFrame} from the endpoint is unwrapped to its raw `ArrayBuffer` payload and
427
+ * streamed straight to the model.
428
+ * - **Outbound** (`session.OnOutput` → `bridge.SendMedia`): what the agent SAYS. Each model
429
+ * output `ArrayBuffer` is wrapped in an outbound audio {@link BridgeMediaFrame} and sent into
430
+ * the meeting/call.
431
+ *
432
+ * Audio is the first track lit up, so the outbound direction is wired as `audio-out`; video/screen
433
+ * tracks ride the same `SendMedia` method once the model emits them.
434
+ *
435
+ * @param active The live bridged session whose driver and realtime session are wired together.
436
+ */
437
+ private wireTransportSeam;
438
+ /**
439
+ * Unwraps a {@link BridgeMediaFrame} to the raw `ArrayBuffer` the realtime session consumes,
440
+ * preferring the binary `Bytes` payload and decoding `Base64` when only that is present. Returns
441
+ * `undefined` when the frame carries no payload (defensive — never forwards an empty frame).
442
+ *
443
+ * @param frame The inbound media frame.
444
+ * @returns The raw frame bytes, or `undefined` when the frame has no payload.
445
+ */
446
+ private frameToArrayBuffer;
447
+ /**
448
+ * Wraps a raw model-output `ArrayBuffer` in an outbound {@link BridgeMediaFrame} on the given
449
+ * track, using the fast binary payload path.
450
+ *
451
+ * @param chunk The raw output frame from the model.
452
+ * @param track The outbound track to stamp on the frame.
453
+ * @returns The outbound media frame.
454
+ */
455
+ private arrayBufferToFrame;
456
+ /**
457
+ * Decodes a base64 string into an `ArrayBuffer`. Uses Node's `Buffer` when available (the
458
+ * server tier) and falls back to `atob` otherwise so the seam stays environment-agnostic.
459
+ *
460
+ * @param base64 The base64-encoded payload.
461
+ * @returns The decoded `ArrayBuffer`.
462
+ */
463
+ private decodeBase64;
464
+ /**
465
+ * Subscribes the driver's roster-change stream (when the provider supports diarization/roster)
466
+ * and upserts `AIAgentSessionBridgeParticipant` rows on each change. Capability-gated: a driver
467
+ * without roster support throws from `OnParticipantChange`, which is caught and treated as
468
+ * "no participant tracking for this provider" rather than failing the session.
469
+ *
470
+ * @param active The live bridged session to track participants for.
471
+ */
472
+ private wireParticipantTracking;
473
+ /**
474
+ * Decides whether an emptied room should auto-leave. Marks {@link ActiveBridgeSession.HasSeenHuman}
475
+ * once any human is present; when a human WAS present and the roster drops to agents-only, it arms a
476
+ * grace timer ({@link ROOM_EMPTY_GRACE_MS}) that stops the session (so a page-refresh re-join cancels
477
+ * it). The stop routes through {@link StopBridgeSession} → driver disconnect → realtime `Close()`, which
478
+ * finalizes the co-agent run — so a closed tab no longer leaves a `Connected` bridge + `Running` run.
479
+ *
480
+ * Only providers with a roster (diarization) reach here; rosterless transports rely on the host janitor.
481
+ *
482
+ * @param active The live bridged session.
483
+ * @param participants The current roster from the driver.
484
+ */
485
+ private evaluateRoomOccupancy;
486
+ /**
487
+ * Upserts the supplied participants onto the bridge as `AIAgentSessionBridgeParticipant` rows,
488
+ * matching existing rows by `ExternalParticipantID`. Best-effort: a failed write is logged and
489
+ * never propagates to the live media plane.
490
+ *
491
+ * @param active The live bridged session the participants belong to.
492
+ * @param participants The current roster from the driver.
493
+ */
494
+ private upsertParticipants;
495
+ /** Loads the existing participant rows for a bridge, keyed (lowercased) by `ExternalParticipantID`. */
496
+ private loadParticipants;
497
+ /** Inserts a new participant row or updates the matched existing one in place. */
498
+ private upsertOneParticipant;
499
+ /**
500
+ * Wires the session's turn-taking policy to its inbound transcript stream. Each diarized
501
+ * transcript segment is fed to {@link TurnTakingPolicy.EvaluateTurn} and the decision is acted
502
+ * on: `Speak` lets the realtime session take the floor (via {@link IRealtimeSession.RequestSpokenUpdate}
503
+ * when available, else a context note), `PostToChat` is delegated to the bridge chat path
504
+ * (currently a documented hook), and `Silent` does nothing.
505
+ *
506
+ * Only the realtime session's *user* transcripts drive turn-taking — assistant transcripts are
507
+ * the agent's own speech and would otherwise self-trigger.
508
+ *
509
+ * @param active The live bridged session.
510
+ */
511
+ private wireTurnTaking;
512
+ /**
513
+ * Acts on a turn-taking decision. Kept behind the injected {@link IRealtimeSession} interface so
514
+ * the actual model trigger stays the session's concern and the engine remains testable.
515
+ *
516
+ * @param active The live bridged session.
517
+ * @param action The decided action (`Speak` / `PostToChat` / `Silent`).
518
+ */
519
+ private applyTurnDecision;
520
+ /**
521
+ * Builds the per-session {@link TurnTakingPolicy} from the start params.
522
+ *
523
+ * @param params The session parameters.
524
+ * @returns The configured turn-taking policy.
525
+ */
526
+ private buildTurnPolicy;
527
+ /**
528
+ * Elects this session as its room's transcript **scribe** iff a transcript sink is registered, the
529
+ * session has a room key, and no scribe exists for that room yet. Exactly one scribe per room writes the
530
+ * unified transcript, so a multi-agent room records one copy (the scribe hears everyone), not N.
531
+ *
532
+ * @param active The freshly connected session.
533
+ */
534
+ private electTranscriptScribe;
535
+ /**
536
+ * Releases this session's scribe role on teardown and HANDS OFF to another live session in the same
537
+ * room (so the transcript continues when the original scribe leaves a still-occupied room). No-op when
538
+ * the session wasn't the scribe. Called during disconnect while the session is still in the active map.
539
+ *
540
+ * @param active The session being torn down.
541
+ */
542
+ private releaseTranscriptScribe;
543
+ /**
544
+ * Emits one FINAL transcript line to the registered sink — only from the room's scribe, so the room
545
+ * gets a single unified transcript. The scribe's OWN speech (`assistant`) is attributed to it; everything
546
+ * it hears (`user`) is recorded as heard. Best-effort: a sink failure is logged, never fatal to media.
547
+ *
548
+ * @param active The scribe session.
549
+ * @param t The final transcript line.
550
+ */
551
+ private emitTranscriptLine;
552
+ /**
553
+ * Wires the session's server-side channel plane (Phase 2's `RealtimeChannelServerHost` +
554
+ * `MeetingControlsChannelServer`) to this bridged session — the generic, platform-agnostic
555
+ * integration the Phase 2 agent flagged as the bridge-server follow-up.
556
+ *
557
+ * When a {@link IBridgeChannelHost} was supplied, this:
558
+ * 1. Resolves the driver's optional Meeting Controls event source
559
+ * ({@link BaseRealtimeBridge.GetMeetingControlsEventSource}) — non-null only for drivers that
560
+ * contribute a facilitator surface.
561
+ * 2. Captures the realtime session's `SendContextNote` perception sink (when the provider supports
562
+ * mid-session context injection) so channel perception reaches the model.
563
+ * 3. Calls {@link IBridgeChannelHost.StartSessionChannels} to register the session's channels and
564
+ * construct + bind the Meeting Controls channel to the event source.
565
+ * 4. Reads the contributed server-channel tools and binds the per-session executor onto the
566
+ * {@link ActiveBridgeSession}, so the runner-constructing layer registers them as
567
+ * `RealtimeSessionRunner.ServerChannelTools` and routes `ExecuteServerChannelTool` here.
568
+ *
569
+ * Failure posture mirrors the channel plane itself: a channel-host error is logged and never
570
+ * propagates — the live media plane (the call/meeting) must not break because a channel failed.
571
+ *
572
+ * @param active The live bridged session to wire channels for.
573
+ */
574
+ private wireChannelPlane;
575
+ /**
576
+ * Closes the session's server-side channels through the channel host (best-effort; teardown must
577
+ * never throw). Invoked from {@link disconnectDriver} so every stop path — explicit, janitor,
578
+ * shutdown — releases the channel plane.
579
+ *
580
+ * @param active The live bridged session whose channels to close.
581
+ */
582
+ private closeChannelPlane;
583
+ /**
584
+ * Force-closes `Connected`/`Connecting` bridges left behind by a **previous boot of this host**
585
+ * (matching hostname prefix, differing instance id), stamping `CloseReason = 'Janitor'`. Mirrors
586
+ * `SessionJanitor.RunStartupRecovery`: a crash/redeploy vaporizes the in-memory driver sockets
587
+ * but leaves the durable rows reading `Connected` forever; this reconciles them.
588
+ *
589
+ * The actual *scheduling* (run once at boot + periodic sweep) is intentionally left to the host
590
+ * application (MJServer's startup + janitor timer) so this engine package carries no timer/IO of
591
+ * its own; call this method from that scheduler.
592
+ *
593
+ * @param contextUser The system user the reconciliation writes run as.
594
+ * @param provider The metadata provider for the reconciliation reads/writes.
595
+ * @returns The number of orphaned bridges closed.
596
+ */
597
+ ReconcileOrphans(contextUser: UserInfo, provider: IMetadataProvider): Promise<number>;
598
+ /** Loads the orphaned bridge rows matching the janitor filter. */
599
+ private loadOrphanRows;
600
+ /**
601
+ * Binds the SDK factory onto a resolved driver before `Connect`. Precedence: a per-session
602
+ * {@link StartBridgeSessionParams.BindSdk} override wins; otherwise the provider's registered native
603
+ * binding from the {@link BridgeNativeSdkRegistry} is applied. When neither exists the driver keeps its
604
+ * default factory (which fails loudly at connect if it actually needs an SDK — e.g. LoopbackBridge has
605
+ * no SDK and needs no binding, so this is a harmless no-op for it).
606
+ *
607
+ * @param params The start params (its `BindSdk` is the override).
608
+ * @param driver The resolved driver to bind onto.
609
+ */
610
+ private bindDriverSdk;
611
+ /**
612
+ * Resolves the concrete bridge driver for a provider via the MJ `ClassFactory`, keyed by the
613
+ * provider's `DriverClass`.
614
+ *
615
+ * @param provider The provider whose `DriverClass` selects the driver.
616
+ * @returns The instantiated driver.
617
+ * @throws When no driver is registered under the provider's `DriverClass`.
618
+ */
619
+ private resolveDriver;
620
+ /**
621
+ * Builds the {@link RealtimeBridgeContext} handed to the driver's `Connect` from the start params
622
+ * and the provider's typed `SupportedFeatures`.
623
+ *
624
+ * @param params The session parameters.
625
+ * @returns The bridge context.
626
+ */
627
+ private buildBridgeContext;
628
+ /**
629
+ * Creates the `AIAgentSessionBridge` row as `Pending`, stamped with the host instance for affinity.
630
+ *
631
+ * @param params The session parameters.
632
+ * @returns The saved bridge row.
633
+ * @throws When the row cannot be created (no metadata provider, or save failure).
634
+ */
635
+ private createBridgeRow;
636
+ /**
637
+ * Transitions a bridge row to a new `Status` and persists it.
638
+ *
639
+ * @param row The bridge row to transition.
640
+ * @param status The target status.
641
+ * @param params The session parameters (carry the context user for the save).
642
+ */
643
+ private transitionStatus;
644
+ /** Stamps a bridge row `Failed` (best-effort) after a connect failure, logging the cause. */
645
+ private failBridgeRow;
646
+ /** Disconnects the driver of a live session, tolerant of driver teardown errors, and closes its channels. */
647
+ private disconnectDriver;
648
+ /**
649
+ * Loads a bridge row and transitions it to `Disconnected` with the supplied `CloseReason`,
650
+ * stamping `DisconnectedAt`. Idempotent — an already-`Disconnected`/`Failed` row is left untouched
651
+ * and reported as success.
652
+ *
653
+ * @param sessionBridgeID The bridge row id.
654
+ * @param reason The close reason to stamp.
655
+ * @param contextUser The user the write runs as.
656
+ * @param provider The metadata provider for the load/save.
657
+ * @returns `true` when the row is (or already was) in a terminal disconnected state.
658
+ */
659
+ private markBridgeDisconnected;
660
+ /** Escapes single quotes for safe embedding inside an `ExtraFilter` literal. */
661
+ private escapeSql;
662
+ }
663
+ //# sourceMappingURL=ai-bridge-engine.d.ts.map