@memberjunction/ai-bridge-server 5.41.0 → 5.43.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.
package/dist/ai-bridge-engine.js
CHANGED
|
@@ -4,15 +4,57 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
|
|
|
4
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
5
|
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
6
|
};
|
|
7
|
-
import { LogError, LogStatus, RunView, RegisterForStartup, } from '@memberjunction/core';
|
|
7
|
+
import { LogError, LogStatus, LogStatusEx, RunView, RegisterForStartup, } from '@memberjunction/core';
|
|
8
8
|
import { BaseSingleton, MJGlobal } from '@memberjunction/global';
|
|
9
|
-
import { AIBridgeEngineBase, BaseRealtimeBridge, TurnTakingPolicy, } from '@memberjunction/ai-bridge-base';
|
|
9
|
+
import { AIBridgeEngineBase, BaseRealtimeBridge, TurnTakingPolicy, BridgeNativeSdkRegistry, } from '@memberjunction/ai-bridge-base';
|
|
10
10
|
import { MultiAgentRoomCoordinator } from './multi-agent-room-coordinator.js';
|
|
11
11
|
/**
|
|
12
12
|
* Entity names — centralised so the `MJ:`-prefix convention is applied in exactly one place.
|
|
13
13
|
*/
|
|
14
14
|
const SESSION_BRIDGE_ENTITY = 'MJ: AI Agent Session Bridges';
|
|
15
15
|
const SESSION_BRIDGE_PARTICIPANT_ENTITY = 'MJ: AI Agent Session Bridge Participants';
|
|
16
|
+
/**
|
|
17
|
+
* Grace window after the last human leaves a room before the bot auto-leaves. Long enough that a page
|
|
18
|
+
* refresh (participant briefly drops + rejoins) does NOT kill the agent, short enough that an abandoned
|
|
19
|
+
* room frees its model session + finalizes its run promptly. See {@link AIBridgeEngine.evaluateRoomOccupancy}.
|
|
20
|
+
*/
|
|
21
|
+
const ROOM_EMPTY_GRACE_MS = 15000;
|
|
22
|
+
/**
|
|
23
|
+
* Max time a meeting agent may hold the speaking floor before the engine force-releases it — a safety
|
|
24
|
+
* valve so a missed end-of-speech signal can't wedge a multi-agent room's floor closed. The normal release
|
|
25
|
+
* (the agent's own final transcript) fires well within this. See {@link AIBridgeEngine.releaseRoomFloor}.
|
|
26
|
+
*/
|
|
27
|
+
const FLOOR_MAX_HOLD_MS = 20000;
|
|
28
|
+
/**
|
|
29
|
+
* Window for collapsing duplicate transcriptions of the SAME user utterance across a room's agents. When
|
|
30
|
+
* several agents transcribe the user (slightly apart), only the first dispatch within this window drives the
|
|
31
|
+
* room's addressing gate; later identical-text dispatches are dropped. See {@link AIBridgeEngine.dispatchUserTurn}.
|
|
32
|
+
*/
|
|
33
|
+
const ROOM_TURN_DEDUP_MS = 2500;
|
|
34
|
+
/** Upper bound on the per-room diarized lookback the engine retains in memory (the moderator narrows this further). */
|
|
35
|
+
const ROOM_LOOKBACK_MAX_TURNS = 50;
|
|
36
|
+
/** Hard cap on chars stored per lookback turn (memory bound; the moderator clips again to its configured budget). */
|
|
37
|
+
const ROOM_LOOKBACK_MAX_CHARS = 600;
|
|
38
|
+
/**
|
|
39
|
+
* Runaway breaker: max consecutive agent-only turns (no human between) before the engine pauses agent↔agent
|
|
40
|
+
* continuation regardless of the configurable {@link RealtimeModeratorConfig.maxConsecutiveAgentOnlyTurns}
|
|
41
|
+
* (which defaults to no cap). Set high — real discussions don't approach it — purely to stop a pathological loop.
|
|
42
|
+
*/
|
|
43
|
+
const ROOM_AGENT_TURN_HARD_CEILING = 30;
|
|
44
|
+
/**
|
|
45
|
+
* Stale-session sweep thresholds (the SAME-process complement to {@link AIBridgeEngine.ReconcileOrphans},
|
|
46
|
+
* which handles prior-boot orphans). A live session is reaped when it has been **idle** (no inbound
|
|
47
|
+
* transcript) for longer than the idle TTL, OR has simply run past the absolute max duration — covering a
|
|
48
|
+
* missed leave event, a rosterless transport with no occupancy signal, and "the bot joined a scheduled
|
|
49
|
+
* meeting but nobody ever came." The reap routes through the normal stop, so the co-agent run finalizes.
|
|
50
|
+
*/
|
|
51
|
+
const SESSION_IDLE_TTL_MS = 10 * 60 * 1000; // 10 min with no transcript activity
|
|
52
|
+
const SESSION_MAX_DURATION_MS = 4 * 60 * 60 * 1000; // 4 h absolute cap
|
|
53
|
+
const STALE_SWEEP_INTERVAL_MS = 60 * 1000; // sweep cadence when self-scheduled
|
|
54
|
+
/** Context note injected into a re-gated agent so it knows it's now in a meeting (its prompt predates it). */
|
|
55
|
+
const MEETING_REGATE_CONTEXT_NOTE = 'You are now in a multi-party meeting with other people and agents. Stop responding to everything you ' +
|
|
56
|
+
'hear — listen, and speak only when you are addressed by name or the conversation clearly needs your ' +
|
|
57
|
+
'expertise. Never talk over others, and keep your replies brief.';
|
|
16
58
|
/**
|
|
17
59
|
* A default {@link IHostInstanceIdentity} for standalone use (and a sane fallback when the host
|
|
18
60
|
* application does not inject one). Generates a stable `unknown-host:pid:bootId` identity at module
|
|
@@ -71,8 +113,30 @@ export class DefaultHostInstanceIdentity {
|
|
|
71
113
|
let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
72
114
|
constructor() {
|
|
73
115
|
super(...arguments);
|
|
116
|
+
// Session timing thresholds (defaults from the module consts; overridable via {@link ConfigureSessionTimings}).
|
|
117
|
+
this.idleTtlMs = SESSION_IDLE_TTL_MS;
|
|
118
|
+
this.maxDurationMs = SESSION_MAX_DURATION_MS;
|
|
119
|
+
this.emptyGraceMs = ROOM_EMPTY_GRACE_MS;
|
|
120
|
+
this.floorMaxHoldMs = FLOOR_MAX_HOLD_MS;
|
|
121
|
+
/** roomKey (lowercased) → the bridge id of that room's current transcript scribe. Election dedup. */
|
|
122
|
+
this.roomScribes = new Map();
|
|
123
|
+
/** Diagnostic: session ids that have already logged their first inbound / outbound media frame. */
|
|
124
|
+
this.diagInbound = new Set();
|
|
125
|
+
this.diagOutbound = new Set();
|
|
74
126
|
/** In-memory registry of bridged sessions this process currently hosts, keyed by bridge id (lowercased). */
|
|
75
127
|
this.activeSessions = new Map();
|
|
128
|
+
/** Per-room, per-utterance-text last-dispatch timestamps — collapses duplicate transcriptions (see {@link ROOM_TURN_DEDUP_MS}). */
|
|
129
|
+
this.recentRoomTurnDispatch = new Map();
|
|
130
|
+
/** Per-room rolling diarized lookback the moderator reads. Bounded to {@link ROOM_LOOKBACK_MAX_TURNS}. */
|
|
131
|
+
this.roomLookback = new Map();
|
|
132
|
+
/** Per-room ordered queue of `AgentSessionID`s the moderator decided should speak, drained serially via the floor. */
|
|
133
|
+
this.roomSpeakerQueue = new Map();
|
|
134
|
+
/** Per-room count of consecutive agent-only turns since the last human turn (optional ping-pong backstop). */
|
|
135
|
+
this.roomConsecutiveAgentTurns = new Map();
|
|
136
|
+
/** Rooms with a moderator decision in flight — prevents overlapping moderator calls for one room. */
|
|
137
|
+
this.roomModeratorBusy = new Set();
|
|
138
|
+
/** Per-room latest turn that arrived while the moderator was busy — run once the in-flight call finishes (no turn lost). */
|
|
139
|
+
this.roomPendingTurn = new Map();
|
|
76
140
|
/** Host-instance identity provider; injected by the host application or defaulted for standalone use. */
|
|
77
141
|
this.hostIdentity = new DefaultHostInstanceIdentity();
|
|
78
142
|
/**
|
|
@@ -112,6 +176,9 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
112
176
|
*/
|
|
113
177
|
async HandleStartup(contextUser, provider) {
|
|
114
178
|
await this.Config(false, contextUser, provider);
|
|
179
|
+
// Begin reaping stale live sessions (idle / over-duration) — the same-process backstop to the
|
|
180
|
+
// occupancy auto-leave + the prior-boot orphan reconcile. Idempotent.
|
|
181
|
+
this.StartStaleSessionSweep();
|
|
115
182
|
}
|
|
116
183
|
/**
|
|
117
184
|
* Loads (or refreshes) the composed base's bridge metadata cache. Delegates to
|
|
@@ -154,6 +221,58 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
154
221
|
IdentityByValue(identityValue, providerId) {
|
|
155
222
|
return this.Base.IdentityByValue(identityValue, providerId);
|
|
156
223
|
}
|
|
224
|
+
/**
|
|
225
|
+
* Registers the {@link BridgeSessionRunFinalizer} this engine calls when a bridge is marked disconnected
|
|
226
|
+
* without a live in-memory session (orphan/cross-host reap) — so the co-agent run finalizes there too,
|
|
227
|
+
* not only on the same-process `Close()` path. Bound once at startup by the agent layer. Idempotent.
|
|
228
|
+
*
|
|
229
|
+
* @param finalizer The finalizer (from `@memberjunction/ai-agents`).
|
|
230
|
+
*/
|
|
231
|
+
SetSessionRunFinalizer(finalizer) {
|
|
232
|
+
this.runFinalizer = finalizer;
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* Overrides the session timing thresholds (the idle/max-duration sweep caps, the empty-room auto-leave
|
|
236
|
+
* grace, and the floor max-hold). Any omitted value keeps its default. Call once at startup to tune for a
|
|
237
|
+
* deployment (e.g. shorter idle TTL for a high-churn telephony host).
|
|
238
|
+
*
|
|
239
|
+
* @param timings The thresholds to override (ms).
|
|
240
|
+
*/
|
|
241
|
+
ConfigureSessionTimings(timings) {
|
|
242
|
+
if (timings.IdleTtlMs != null) {
|
|
243
|
+
this.idleTtlMs = timings.IdleTtlMs;
|
|
244
|
+
}
|
|
245
|
+
if (timings.MaxDurationMs != null) {
|
|
246
|
+
this.maxDurationMs = timings.MaxDurationMs;
|
|
247
|
+
}
|
|
248
|
+
if (timings.EmptyGraceMs != null) {
|
|
249
|
+
this.emptyGraceMs = timings.EmptyGraceMs;
|
|
250
|
+
}
|
|
251
|
+
if (timings.FloorMaxHoldMs != null) {
|
|
252
|
+
this.floorMaxHoldMs = timings.FloorMaxHoldMs;
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
/**
|
|
256
|
+
* Registers the {@link BridgeTranscriptSink} that persists the unified per-room transcript. The engine
|
|
257
|
+
* elects one scribe per room and feeds its final transcript lines here; the sink owns *where* they land
|
|
258
|
+
* (e.g. an `MJ: Conversations` "Meeting Room"). Bound once at startup by the app layer. Without it, no
|
|
259
|
+
* transcript is persisted (the engine still elects a scribe but emits nothing).
|
|
260
|
+
*
|
|
261
|
+
* @param sink The transcript sink (from the app layer).
|
|
262
|
+
*/
|
|
263
|
+
SetTranscriptSink(sink) {
|
|
264
|
+
this.transcriptSink = sink;
|
|
265
|
+
}
|
|
266
|
+
/**
|
|
267
|
+
* Injects the room turn {@link TurnModerator} (the LLM router). When set, a MULTI-agent room routes each
|
|
268
|
+
* turn through it (who speaks next, serialized via the floor) instead of evaluating per-agent matchers.
|
|
269
|
+
* Single-agent rooms and the no-moderator case are unaffected (they keep using the matcher path).
|
|
270
|
+
*
|
|
271
|
+
* @param moderator The moderator function, or `undefined` to clear it.
|
|
272
|
+
*/
|
|
273
|
+
SetTurnModerator(moderator) {
|
|
274
|
+
this.turnModerator = moderator;
|
|
275
|
+
}
|
|
157
276
|
/** Returns the active identities for an agent. @see AIBridgeEngineBase.IdentitiesForAgent */
|
|
158
277
|
IdentitiesForAgent(agentId, providerId) {
|
|
159
278
|
return this.Base.IdentitiesForAgent(agentId, providerId);
|
|
@@ -252,6 +371,11 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
252
371
|
// Resolve the driver inside the try so a resolution failure still stamps the row Failed
|
|
253
372
|
// (the row already exists at this point — it must not be left dangling as Pending).
|
|
254
373
|
const driver = this.resolveDriver(params.Provider);
|
|
374
|
+
// Bind the driver's SDK factory BEFORE Connect (Connect constructs the SDK from it). A
|
|
375
|
+
// per-session BindSdk override wins; otherwise apply the provider's registered native binding.
|
|
376
|
+
// Resolved drivers start with a default factory that throws "no SDK bound", so this is what
|
|
377
|
+
// makes a real provider session actually connect.
|
|
378
|
+
this.bindDriverSdk(params, driver);
|
|
255
379
|
await this.transitionStatus(bridgeRow, 'Connecting', params);
|
|
256
380
|
const ctx = this.buildBridgeContext(params);
|
|
257
381
|
const result = await driver.Connect(ctx);
|
|
@@ -263,15 +387,36 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
263
387
|
const active = {
|
|
264
388
|
SessionBridgeID: bridgeRow.ID,
|
|
265
389
|
AgentSessionID: params.AgentSessionID,
|
|
390
|
+
AgentID: params.AgentID,
|
|
266
391
|
Bridge: driver,
|
|
267
392
|
RealtimeSession: params.RealtimeSession,
|
|
268
393
|
TurnPolicy: turnPolicy,
|
|
394
|
+
DisableAutoResponse: params.DisableAutoResponse === true,
|
|
395
|
+
HasSeenHuman: false,
|
|
396
|
+
RoomKey: result.ExternalConnectionId,
|
|
397
|
+
BotParticipantID: result.BotParticipantId,
|
|
398
|
+
IsTranscriptScribe: false,
|
|
399
|
+
HoldsFloor: false,
|
|
400
|
+
ConnectedAtMs: Date.now(),
|
|
401
|
+
LastActivityMs: Date.now(),
|
|
402
|
+
ParticipationMode: params.ParticipationMode ?? 'proactive',
|
|
403
|
+
AgentNames: params.AgentNames ?? [],
|
|
404
|
+
AgentRole: params.AgentRole,
|
|
405
|
+
AgentRunID: params.AgentRunID,
|
|
406
|
+
TargetAgentID: params.TargetAgentID,
|
|
269
407
|
Provider: params.Provider,
|
|
270
408
|
ContextUser: params.ContextUser,
|
|
271
409
|
MetadataProvider: params.MetadataProvider,
|
|
272
410
|
ChannelHost: params.ChannelHost,
|
|
273
411
|
ServerChannelTools: [],
|
|
274
412
|
};
|
|
413
|
+
this.electTranscriptScribe(active);
|
|
414
|
+
// Join the room's floor-control roster (keyed on the shared room). For a single-agent room this
|
|
415
|
+
// is a 1-member room where the floor is always free — so floor control is a no-op until a 2nd
|
|
416
|
+
// agent joins, at which point they take turns. Unregistered on teardown.
|
|
417
|
+
if (active.RoomKey) {
|
|
418
|
+
this.roomCoordinator.RegisterRoomParticipant(active.RoomKey, active.AgentSessionID);
|
|
419
|
+
}
|
|
275
420
|
this.wireTransportSeam(active);
|
|
276
421
|
this.wireParticipantTracking(active);
|
|
277
422
|
this.wireTurnTaking(active);
|
|
@@ -331,18 +476,58 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
331
476
|
*/
|
|
332
477
|
wireTransportSeam(active) {
|
|
333
478
|
const { Bridge, RealtimeSession } = active;
|
|
334
|
-
// Inbound: endpoint media → the agent hears it.
|
|
479
|
+
// Inbound: endpoint media → the agent hears (and, for a video model, SEES) it. The frame's
|
|
480
|
+
// Track tags the plane, so a human's camera (`video-in`) reaches the model as a `video` frame.
|
|
335
481
|
Bridge.OnMedia((frame) => {
|
|
482
|
+
// DIARIZATION: the inbound frame carries the speaking participant's identity (when the provider
|
|
483
|
+
// supports it). The realtime model's transcript has no speaker label, so we remember the
|
|
484
|
+
// most-recent inbound audio speaker here and attribute the next 'user' transcript to them — a
|
|
485
|
+
// single-speaker-at-a-time approximation that's right for the common case. See emitTranscriptLine.
|
|
486
|
+
if (frame.Track === 'audio-in' && frame.SpeakerLabel) {
|
|
487
|
+
active.LastInboundSpeaker = frame.SpeakerLabel;
|
|
488
|
+
}
|
|
336
489
|
const chunk = this.frameToArrayBuffer(frame);
|
|
337
490
|
if (chunk) {
|
|
338
|
-
|
|
491
|
+
if (!this.diagInbound.has(active.SessionBridgeID)) {
|
|
492
|
+
this.diagInbound.add(active.SessionBridgeID);
|
|
493
|
+
LogStatusEx({ message: `[AIBridgeEngine][diag] FIRST inbound media frame reached the agent (bridge ${active.SessionBridgeID}, track=${frame.Track}). The agent is HEARING you.`, verboseOnly: true });
|
|
494
|
+
}
|
|
495
|
+
RealtimeSession.SendInput(chunk, frame.Track === 'video-in' ? 'video' : 'audio');
|
|
339
496
|
}
|
|
340
497
|
});
|
|
341
498
|
// Outbound: the agent speaks → into the meeting/call.
|
|
342
499
|
RealtimeSession.OnOutput((chunk) => {
|
|
500
|
+
if (!this.diagOutbound.has(active.SessionBridgeID)) {
|
|
501
|
+
this.diagOutbound.add(active.SessionBridgeID);
|
|
502
|
+
LogStatusEx({ message: `[AIBridgeEngine][diag] FIRST outbound audio from the agent (bridge ${active.SessionBridgeID}). The agent is SPEAKING into the room.`, verboseOnly: true });
|
|
503
|
+
}
|
|
343
504
|
const track = 'audio-out';
|
|
344
505
|
Bridge.SendMedia(track, this.arrayBufferToFrame(chunk, track));
|
|
345
506
|
});
|
|
507
|
+
// Outbound VIDEO: a video-capable session ALSO emits a synced avatar/video track. Optional —
|
|
508
|
+
// audio-only sessions don't implement OnVideoOutput, so call it null-safely. The bridge driver
|
|
509
|
+
// gates the actual publish on its `VideoOut` capability.
|
|
510
|
+
RealtimeSession.OnVideoOutput?.((chunk) => {
|
|
511
|
+
const track = 'video-out';
|
|
512
|
+
Bridge.SendMedia(track, this.arrayBufferToFrame(chunk, track));
|
|
513
|
+
});
|
|
514
|
+
// Barge-in: on a TRUE interruption (the user speaks over the agent), the model stops generating —
|
|
515
|
+
// but the driver may still hold queued outbound audio that would keep playing. Flush it so the
|
|
516
|
+
// agent goes quiet immediately. Without this, interruption "doesn't work" on the bridge surface.
|
|
517
|
+
RealtimeSession.OnInterruption(() => {
|
|
518
|
+
if (this.diagOutbound.has(active.SessionBridgeID)) {
|
|
519
|
+
LogStatusEx({ message: `[AIBridgeEngine][diag] barge-in — flushing the agent's queued audio (bridge ${active.SessionBridgeID}).`, verboseOnly: true });
|
|
520
|
+
}
|
|
521
|
+
Bridge.FlushOutboundMedia();
|
|
522
|
+
// A human cut in → any moderator decision staged for the prior turn is now stale. Drop the queued
|
|
523
|
+
// speakers (the human's new turn will drive a fresh decision); also free the floor this agent held.
|
|
524
|
+
if (active.RoomKey) {
|
|
525
|
+
this.clearRoomModeratorState(active.RoomKey, false);
|
|
526
|
+
if (active.HoldsFloor) {
|
|
527
|
+
this.releaseRoomFloor(active);
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
});
|
|
346
531
|
}
|
|
347
532
|
/**
|
|
348
533
|
* Unwraps a {@link BridgeMediaFrame} to the raw `ArrayBuffer` the realtime session consumes,
|
|
@@ -412,6 +597,10 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
412
597
|
try {
|
|
413
598
|
active.Bridge.OnParticipantChange((participants) => {
|
|
414
599
|
void this.upsertParticipants(active, participants);
|
|
600
|
+
// Auto-leave an emptied room: the dominant teardown path (the user just closes the tab never
|
|
601
|
+
// calls StopBridgeSession), so without this the bot lingers Connected and its co-agent run
|
|
602
|
+
// dangles in Running forever. Routed through the normal stop, so the run finalizes cleanly.
|
|
603
|
+
this.evaluateRoomOccupancy(active, participants);
|
|
415
604
|
});
|
|
416
605
|
}
|
|
417
606
|
catch (err) {
|
|
@@ -420,6 +609,42 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
420
609
|
`${err instanceof Error ? err.message : String(err)}`);
|
|
421
610
|
}
|
|
422
611
|
}
|
|
612
|
+
/**
|
|
613
|
+
* Decides whether an emptied room should auto-leave. Marks {@link ActiveBridgeSession.HasSeenHuman}
|
|
614
|
+
* once any human is present; when a human WAS present and the roster drops to agents-only, it arms a
|
|
615
|
+
* grace timer ({@link ROOM_EMPTY_GRACE_MS}) that stops the session (so a page-refresh re-join cancels
|
|
616
|
+
* it). The stop routes through {@link StopBridgeSession} → driver disconnect → realtime `Close()`, which
|
|
617
|
+
* finalizes the co-agent run — so a closed tab no longer leaves a `Connected` bridge + `Running` run.
|
|
618
|
+
*
|
|
619
|
+
* Only providers with a roster (diarization) reach here; rosterless transports rely on the host janitor.
|
|
620
|
+
*
|
|
621
|
+
* @param active The live bridged session.
|
|
622
|
+
* @param participants The current roster from the driver.
|
|
623
|
+
*/
|
|
624
|
+
evaluateRoomOccupancy(active, participants) {
|
|
625
|
+
const humanPresent = participants.some(p => !p.IsAgent);
|
|
626
|
+
if (humanPresent) {
|
|
627
|
+
active.HasSeenHuman = true;
|
|
628
|
+
if (active.LeaveGraceTimer) {
|
|
629
|
+
clearTimeout(active.LeaveGraceTimer);
|
|
630
|
+
active.LeaveGraceTimer = undefined;
|
|
631
|
+
}
|
|
632
|
+
return;
|
|
633
|
+
}
|
|
634
|
+
// Agents-only roster. Never reaped unless a human was actually here first (so a bot that joins ahead
|
|
635
|
+
// of anyone isn't killed), and only one countdown at a time.
|
|
636
|
+
if (!active.HasSeenHuman || active.LeaveGraceTimer) {
|
|
637
|
+
return;
|
|
638
|
+
}
|
|
639
|
+
active.LeaveGraceTimer = setTimeout(() => {
|
|
640
|
+
active.LeaveGraceTimer = undefined;
|
|
641
|
+
// A re-join cleared this timer; a prior stop removed the session. Only act if it's still live.
|
|
642
|
+
if (this.activeSessions.has(active.SessionBridgeID.toLowerCase())) {
|
|
643
|
+
LogStatus(`[AIBridgeEngine] All humans left bridge ${active.SessionBridgeID}; auto-leaving (grace elapsed).`);
|
|
644
|
+
void this.StopBridgeSession(active.SessionBridgeID, 'HostEnded', active.ContextUser, active.MetadataProvider);
|
|
645
|
+
}
|
|
646
|
+
}, this.emptyGraceMs);
|
|
647
|
+
}
|
|
423
648
|
/**
|
|
424
649
|
* Upserts the supplied participants onto the bridge as `AIAgentSessionBridgeParticipant` rows,
|
|
425
650
|
* matching existing rows by `ExternalParticipantID`. Best-effort: a failed write is logged and
|
|
@@ -476,7 +701,13 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
476
701
|
}
|
|
477
702
|
row.DisplayName = p.DisplayName ?? null;
|
|
478
703
|
row.Role = p.Role;
|
|
479
|
-
|
|
704
|
+
// Persist IsAgent ONLY for THIS bridge's own bot — the row-level invariant is "one bot per bridge".
|
|
705
|
+
// In a multi-agent room the live roster (driver-side `p.IsAgent`) flags OTHER agents too (turn-taking
|
|
706
|
+
// + occupancy need that), but on THIS bridge's persisted roster they are remote participants, not its
|
|
707
|
+
// bot. Diarization still resolves them: each agent's OWN bridge marks itself, and the transcript
|
|
708
|
+
// viewer OR-reduces IsAgent per identity across all of the room's bridges.
|
|
709
|
+
row.IsAgent =
|
|
710
|
+
active.BotParticipantID != null && p.ExternalId.toLowerCase() === active.BotParticipantID.toLowerCase();
|
|
480
711
|
const saved = await row.Save();
|
|
481
712
|
if (!saved) {
|
|
482
713
|
LogError(`[AIBridgeEngine] participant upsert save failed: ${row.LatestResult?.CompleteMessage ?? 'unknown error'}`);
|
|
@@ -499,17 +730,335 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
499
730
|
*/
|
|
500
731
|
wireTurnTaking(active) {
|
|
501
732
|
active.RealtimeSession.OnTranscript((t) => {
|
|
502
|
-
|
|
503
|
-
|
|
733
|
+
active.LastActivityMs = Date.now(); // any transcript = the session is alive (drives the idle sweep)
|
|
734
|
+
if (!t.IsFinal) {
|
|
735
|
+
return; // partials fire per-word — act only on a completed turn (and don't flood the log)
|
|
504
736
|
}
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
737
|
+
LogStatusEx({ message: `[AIBridgeEngine][diag] transcript(final): role=${t.Role} text="${(t.Text ?? '').slice(0, 80)}" (bridge ${active.SessionBridgeID})`, verboseOnly: true });
|
|
738
|
+
// Persist the unified room transcript (scribe only — emits both roles).
|
|
739
|
+
this.emitTranscriptLine(active, t);
|
|
740
|
+
// Record into the room's diarized lookback so the moderator (and observability) see the full thread.
|
|
741
|
+
this.recordRoomTurn(active, t);
|
|
742
|
+
if (t.Role === 'assistant') {
|
|
743
|
+
// The agent finished its own turn → release the room floor so the next can speak. Then advance:
|
|
744
|
+
// run the moderator for "who responds to this agent?" (the agent↔agent + pre-stage path) — this
|
|
745
|
+
// executes while the agent's audio is still playing out, hiding the moderator latency.
|
|
746
|
+
if (active.HoldsFloor) {
|
|
747
|
+
this.releaseRoomFloor(active);
|
|
748
|
+
}
|
|
749
|
+
this.onAgentTurnCompleted(active, t.Text ?? '');
|
|
750
|
+
return;
|
|
751
|
+
}
|
|
752
|
+
if (t.Role === 'user') {
|
|
753
|
+
this.dispatchUserTurn(active, t.Text ?? '');
|
|
754
|
+
}
|
|
755
|
+
});
|
|
756
|
+
}
|
|
757
|
+
/**
|
|
758
|
+
* Routes a completed human turn to the addressing gate(s). In a **single-agent** room (or 1:1) only the
|
|
759
|
+
* source agent evaluates. In a **multi-agent** room the user's utterance is the SAME for everyone, so we
|
|
760
|
+
* broadcast it to EVERY agent's `TurnPolicy` — each independently decides "was I addressed?". This is the
|
|
761
|
+
* fix for agents whose own model can't transcribe in meeting mode (e.g. Gemini with automatic activity
|
|
762
|
+
* detection disabled): whichever agent CAN transcribe the room (e.g. the GPT agent, or the scribe) drives
|
|
763
|
+
* the addressing decision for all of them. The audio plane is untouched — every agent already hears the
|
|
764
|
+
* raw audio; this only decides WHEN each is triggered to commit + speak.
|
|
765
|
+
*
|
|
766
|
+
* Dedup: the same utterance may be transcribed by several agents (slightly apart). A per-room, per-text
|
|
767
|
+
* time window collapses those re-transcriptions so each real utterance dispatches to the room once.
|
|
768
|
+
*
|
|
769
|
+
* @param source The bridge whose session produced the transcript.
|
|
770
|
+
* @param text The final user-turn text.
|
|
771
|
+
*/
|
|
772
|
+
dispatchUserTurn(source, text) {
|
|
773
|
+
const peers = source.RoomKey ? this.roomAgents(source.RoomKey) : [source];
|
|
774
|
+
// Only a REAL human turn counts as presence. In a multi-agent room every agent transcribes its peers'
|
|
775
|
+
// speech as a 'user' turn (it has no other role to assign overheard audio); if those counted as a human,
|
|
776
|
+
// an agents-only room would keep cancelling its own auto-leave and babble forever after the humans left —
|
|
777
|
+
// burning realtime tokens at full cost. The diarized inbound speaker tells us: an `agent-…` identity is a
|
|
778
|
+
// peer agent, NOT a human, so it must NOT keep the room alive.
|
|
779
|
+
const overheardAgent = source.LastInboundSpeaker?.toLowerCase().startsWith('agent-') === true;
|
|
780
|
+
if (!overheardAgent) {
|
|
781
|
+
// A real human just spoke → definitive presence for EVERY agent in the room. Cancel any pending
|
|
782
|
+
// empty-room auto-leave + reset the consecutive-agent-only counter.
|
|
783
|
+
for (const peer of peers) {
|
|
784
|
+
this.noteHumanPresence(peer);
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
if (source.RoomKey) {
|
|
788
|
+
this.roomConsecutiveAgentTurns.set(source.RoomKey.toLowerCase(), 0);
|
|
789
|
+
}
|
|
790
|
+
if (peers.length <= 1) {
|
|
791
|
+
this.evaluateUserTurnForAgent(source, text); // 1:1 / solo room — no broadcast, no dedup
|
|
792
|
+
return;
|
|
793
|
+
}
|
|
794
|
+
const now = Date.now();
|
|
795
|
+
const dedupKey = `${source.RoomKey.toLowerCase()}\n${text.trim().toLowerCase()}`;
|
|
796
|
+
if (now - (this.recentRoomTurnDispatch.get(dedupKey) ?? 0) < ROOM_TURN_DEDUP_MS) {
|
|
797
|
+
return; // a peer already dispatched this same utterance to the room
|
|
798
|
+
}
|
|
799
|
+
this.recentRoomTurnDispatch.set(dedupKey, now);
|
|
800
|
+
if (this.recentRoomTurnDispatch.size > 512) {
|
|
801
|
+
this.recentRoomTurnDispatch.clear(); // bounded — dedup only needs the last few seconds
|
|
802
|
+
}
|
|
803
|
+
// MODERATOR PATH: one LLM decision routes the turn to 0+ agents (serialized via the floor). FALLBACK
|
|
804
|
+
// (no moderator configured): each agent independently evaluates its own addressed-matcher (broadcast).
|
|
805
|
+
if (this.turnModerator) {
|
|
806
|
+
void this.runRoomModerator(source.RoomKey, { Speaker: this.speakerLabel(source, false), IsAgent: false, Text: text });
|
|
807
|
+
return;
|
|
808
|
+
}
|
|
809
|
+
LogStatusEx({ message: `[AIBridgeEngine][diag] broadcasting user turn "${text.slice(0, 60)}" to ${peers.length} room agents for addressing (source bridge ${source.SessionBridgeID})`, verboseOnly: true });
|
|
810
|
+
for (const peer of peers) {
|
|
811
|
+
this.evaluateUserTurnForAgent(peer, text);
|
|
812
|
+
}
|
|
813
|
+
}
|
|
814
|
+
/** Marks a human as present on a session: remembers it + cancels any pending empty-room auto-leave. */
|
|
815
|
+
noteHumanPresence(active) {
|
|
816
|
+
active.HasSeenHuman = true;
|
|
817
|
+
if (active.LeaveGraceTimer) {
|
|
818
|
+
clearTimeout(active.LeaveGraceTimer);
|
|
819
|
+
active.LeaveGraceTimer = undefined;
|
|
820
|
+
LogStatusEx({ message: `[AIBridgeEngine][diag] cancelled pending auto-leave for bridge ${active.SessionBridgeID} — a human is actively speaking`, verboseOnly: true });
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
/** Evaluates ONE agent's addressed-matcher against a user utterance and acts on the decision (fallback path). */
|
|
824
|
+
evaluateUserTurnForAgent(active, text) {
|
|
825
|
+
const segment = { Text: text, IsAgent: false, EndMs: Date.now() };
|
|
826
|
+
const decision = active.TurnPolicy.EvaluateTurn({ Segment: segment });
|
|
827
|
+
LogStatusEx({ message: `[AIBridgeEngine][diag] turn decision=${decision.Action} for user turn "${(text ?? '').slice(0, 60)}" (bridge ${active.SessionBridgeID})`, verboseOnly: true });
|
|
828
|
+
this.applyTurnDecision(active, decision.Action);
|
|
829
|
+
}
|
|
830
|
+
/** All active bridged sessions sharing a room (by external room key), case-insensitive. */
|
|
831
|
+
roomAgents(roomKey) {
|
|
832
|
+
const key = roomKey.toLowerCase();
|
|
833
|
+
const out = [];
|
|
834
|
+
for (const s of this.activeSessions.values()) {
|
|
835
|
+
if (s.RoomKey && s.RoomKey.toLowerCase() === key) {
|
|
836
|
+
out.push(s);
|
|
837
|
+
}
|
|
838
|
+
}
|
|
839
|
+
return out;
|
|
840
|
+
}
|
|
841
|
+
// ── Room turn moderator (LLM router) — the multi-agent path used when SetTurnModerator is wired ─────────
|
|
842
|
+
/** A diarized speaker label for a session (the agent's first name, or a generic human label). */
|
|
843
|
+
speakerLabel(active, isAgent) {
|
|
844
|
+
if (isAgent) {
|
|
845
|
+
return active.AgentNames[0] ?? 'Agent';
|
|
846
|
+
}
|
|
847
|
+
return active.LastInboundSpeaker ?? 'Participant';
|
|
848
|
+
}
|
|
849
|
+
/**
|
|
850
|
+
* Appends one final turn to the room's bounded, clipped diarized lookback (oldest→newest). Sourcing rules
|
|
851
|
+
* keep the thread clean in a multi-agent room (where EVERY agent's session independently transcribes what
|
|
852
|
+
* it hears):
|
|
853
|
+
* - **Agent (assistant) turns** are recorded from the speaking agent's OWN bridge (correct, no duplication).
|
|
854
|
+
* - **Human (user) turns** are recorded ONLY by the room **scribe** (one canonical hearer → no N-fold
|
|
855
|
+
* duplication), and ONLY when the diarized inbound speaker is a human — a `user` transcript whose speaker
|
|
856
|
+
* is another AGENT (the scribe overhearing a peer agent) is dropped here, since that agent's own bridge
|
|
857
|
+
* already recorded it as its assistant turn.
|
|
858
|
+
*/
|
|
859
|
+
recordRoomTurn(active, t) {
|
|
860
|
+
if (!active.RoomKey) {
|
|
861
|
+
return;
|
|
862
|
+
}
|
|
863
|
+
const isAgent = t.Role === 'assistant';
|
|
864
|
+
if (!isAgent) {
|
|
865
|
+
if (!active.IsTranscriptScribe) {
|
|
866
|
+
return; // only the scribe records human turns (avoids one copy per transcribing agent)
|
|
867
|
+
}
|
|
868
|
+
if (active.LastInboundSpeaker?.toLowerCase().startsWith('agent-')) {
|
|
869
|
+
return; // the scribe is overhearing another agent — that agent's own bridge records it
|
|
870
|
+
}
|
|
871
|
+
}
|
|
872
|
+
const key = active.RoomKey.toLowerCase();
|
|
873
|
+
const buf = this.roomLookback.get(key) ?? [];
|
|
874
|
+
buf.push({
|
|
875
|
+
Speaker: this.speakerLabel(active, isAgent),
|
|
876
|
+
IsAgent: isAgent,
|
|
877
|
+
AgentID: isAgent ? active.AgentID : undefined,
|
|
878
|
+
Text: (t.Text ?? '').slice(0, ROOM_LOOKBACK_MAX_CHARS),
|
|
512
879
|
});
|
|
880
|
+
while (buf.length > ROOM_LOOKBACK_MAX_TURNS) {
|
|
881
|
+
buf.shift();
|
|
882
|
+
}
|
|
883
|
+
this.roomLookback.set(key, buf);
|
|
884
|
+
}
|
|
885
|
+
/**
|
|
886
|
+
* Called when an agent finishes a turn. Advances a multi-agent room: increments the consecutive-agent-only
|
|
887
|
+
* counter and — if a moderator is wired and the room's speaker queue is empty — runs the moderator to decide
|
|
888
|
+
* whether (and who) continues the discussion. Because this fires on the agent's FINAL TEXT (its audio is
|
|
889
|
+
* still playing out), the moderator's latency is hidden behind playback. No-op for single-agent rooms.
|
|
890
|
+
*/
|
|
891
|
+
onAgentTurnCompleted(active, text) {
|
|
892
|
+
if (!active.RoomKey || !this.turnModerator || this.roomAgents(active.RoomKey).length <= 1) {
|
|
893
|
+
return;
|
|
894
|
+
}
|
|
895
|
+
const key = active.RoomKey.toLowerCase();
|
|
896
|
+
const consecutive = (this.roomConsecutiveAgentTurns.get(key) ?? 0) + 1;
|
|
897
|
+
this.roomConsecutiveAgentTurns.set(key, consecutive);
|
|
898
|
+
// Runaway breaker: even with the configurable cap left null (the user wants free-flowing agent↔agent
|
|
899
|
+
// discussion), a hard ceiling stops a pathological loop from burning tokens forever with no human. Real
|
|
900
|
+
// discussions don't run this many agent turns without a human; a human turn resets the counter.
|
|
901
|
+
if (consecutive >= ROOM_AGENT_TURN_HARD_CEILING) {
|
|
902
|
+
LogStatus(`[AIBridgeEngine] room ${active.RoomKey} hit the agent-turn hard ceiling (${ROOM_AGENT_TURN_HARD_CEILING}) — pausing agent↔agent continuation until a human speaks`);
|
|
903
|
+
return;
|
|
904
|
+
}
|
|
905
|
+
// Run the continuation ONLY when the room is fully idle: no more queued speakers AND nobody currently
|
|
906
|
+
// holds the floor. This handler fires AFTER `releaseRoomFloor` has already drained the next queued
|
|
907
|
+
// speaker (which now holds the floor), so without the floor check we'd re-route to an agent that's
|
|
908
|
+
// mid-response — double-speaking. The continuation then fires once, when the last speaker finishes.
|
|
909
|
+
if ((this.roomSpeakerQueue.get(key)?.length ?? 0) > 0 || this.roomAgents(active.RoomKey).some((a) => a.HoldsFloor)) {
|
|
910
|
+
return;
|
|
911
|
+
}
|
|
912
|
+
void this.runRoomModerator(active.RoomKey, { Speaker: this.speakerLabel(active, true), IsAgent: true, AgentID: active.AgentID, Text: text }, true);
|
|
913
|
+
}
|
|
914
|
+
/**
|
|
915
|
+
* Runs the room turn moderator for one decision: builds the context, calls the injected moderator, sets the
|
|
916
|
+
* room's ordered speaker queue to its result, and drains it (serialized via the floor). Guards against
|
|
917
|
+
* overlapping calls per room and against an unproductive agent-only loop via the optional consecutive cap.
|
|
918
|
+
*
|
|
919
|
+
* @param roomKey The external room key.
|
|
920
|
+
* @param latest The turn that triggered this decision.
|
|
921
|
+
* @param isContinuation True when triggered by an agent turn (vs a fresh human turn).
|
|
922
|
+
*/
|
|
923
|
+
async runRoomModerator(roomKey, latest, isContinuation = false) {
|
|
924
|
+
const key = roomKey.toLowerCase();
|
|
925
|
+
if (!this.turnModerator) {
|
|
926
|
+
return;
|
|
927
|
+
}
|
|
928
|
+
if (this.roomModeratorBusy.has(key)) {
|
|
929
|
+
// A decision is already in flight for this room → remember the LATEST turn so it isn't dropped
|
|
930
|
+
// (e.g. a human speaks while a continuation is mid-call); it runs as soon as the current one finishes.
|
|
931
|
+
this.roomPendingTurn.set(key, latest);
|
|
932
|
+
return;
|
|
933
|
+
}
|
|
934
|
+
const ctx = this.buildModeratorContext(roomKey, latest);
|
|
935
|
+
if (ctx.Roster.length <= 1) {
|
|
936
|
+
return; // not a multi-agent room
|
|
937
|
+
}
|
|
938
|
+
this.roomModeratorBusy.add(key);
|
|
939
|
+
try {
|
|
940
|
+
const sessionIds = await this.turnModerator(ctx);
|
|
941
|
+
const valid = sessionIds.filter((id) => ctx.Roster.some((r) => r.AgentSessionID.toLowerCase() === id.toLowerCase()));
|
|
942
|
+
LogStatusEx({ message: `[AIBridgeEngine][diag] moderator${isContinuation ? '(continuation)' : ''} routed turn "${latest.Text.slice(0, 50)}" → [${valid.map((id) => this.agentSessionLabel(id)).join(', ') || 'nobody'}]`, verboseOnly: true });
|
|
943
|
+
// Moderator chose to go quiet → the (possible) agent↔agent exchange ended; reset the consecutive
|
|
944
|
+
// counter so a later resumption starts fresh rather than near the hard ceiling.
|
|
945
|
+
if (valid.length === 0) {
|
|
946
|
+
this.roomConsecutiveAgentTurns.set(key, 0);
|
|
947
|
+
}
|
|
948
|
+
this.roomSpeakerQueue.set(key, valid);
|
|
949
|
+
this.drainSpeakerQueue(roomKey);
|
|
950
|
+
}
|
|
951
|
+
catch (err) {
|
|
952
|
+
LogError(`[AIBridgeEngine] turn moderator failed for room ${roomKey}: ${err instanceof Error ? err.message : String(err)}`);
|
|
953
|
+
}
|
|
954
|
+
finally {
|
|
955
|
+
this.roomModeratorBusy.delete(key);
|
|
956
|
+
// Process the latest turn that arrived while we were busy (if any) so no turn is lost.
|
|
957
|
+
const pending = this.roomPendingTurn.get(key);
|
|
958
|
+
if (pending) {
|
|
959
|
+
this.roomPendingTurn.delete(key);
|
|
960
|
+
void this.runRoomModerator(roomKey, pending, pending.IsAgent);
|
|
961
|
+
}
|
|
962
|
+
}
|
|
963
|
+
}
|
|
964
|
+
/** Builds the {@link TurnModeratorContext} for a room from the live roster + diarized lookback. */
|
|
965
|
+
buildModeratorContext(roomKey, latest) {
|
|
966
|
+
const key = roomKey.toLowerCase();
|
|
967
|
+
const agents = this.roomAgents(roomKey);
|
|
968
|
+
const roster = agents.map((a) => ({
|
|
969
|
+
AgentSessionID: a.AgentSessionID,
|
|
970
|
+
AgentID: a.AgentID,
|
|
971
|
+
TargetAgentID: a.TargetAgentID,
|
|
972
|
+
Names: a.AgentNames,
|
|
973
|
+
Role: a.AgentRole,
|
|
974
|
+
Mode: a.ParticipationMode,
|
|
975
|
+
}));
|
|
976
|
+
// A representative session for observability/provider context (the scribe if we have it, else the first).
|
|
977
|
+
const rep = agents.find((a) => a.IsTranscriptScribe) ?? agents[0];
|
|
978
|
+
return {
|
|
979
|
+
RoomKey: roomKey,
|
|
980
|
+
Roster: roster,
|
|
981
|
+
Lookback: this.roomLookback.get(key) ?? [latest],
|
|
982
|
+
LatestTurn: latest,
|
|
983
|
+
ConsecutiveAgentOnlyTurns: this.roomConsecutiveAgentTurns.get(key) ?? 0,
|
|
984
|
+
AgentRunID: rep?.AgentRunID,
|
|
985
|
+
RepAgentSessionID: rep?.AgentSessionID,
|
|
986
|
+
ContextUser: rep?.ContextUser,
|
|
987
|
+
Provider: rep?.MetadataProvider,
|
|
988
|
+
};
|
|
989
|
+
}
|
|
990
|
+
/** Triggers the next queued speaker for a room (serialized — only when the floor is free). */
|
|
991
|
+
drainSpeakerQueue(roomKey) {
|
|
992
|
+
const key = roomKey.toLowerCase();
|
|
993
|
+
const queue = this.roomSpeakerQueue.get(key);
|
|
994
|
+
if (!queue || queue.length === 0) {
|
|
995
|
+
return;
|
|
996
|
+
}
|
|
997
|
+
// Don't start the next speaker while someone in the room still holds the floor.
|
|
998
|
+
if (this.roomAgents(roomKey).some((a) => a.HoldsFloor)) {
|
|
999
|
+
return;
|
|
1000
|
+
}
|
|
1001
|
+
const nextSessionId = queue.shift();
|
|
1002
|
+
this.roomSpeakerQueue.set(key, queue);
|
|
1003
|
+
const next = this.roomAgents(roomKey).find((a) => a.AgentSessionID.toLowerCase() === nextSessionId.toLowerCase());
|
|
1004
|
+
if (!next) {
|
|
1005
|
+
this.drainSpeakerQueue(roomKey); // session gone — skip to the next
|
|
1006
|
+
return;
|
|
1007
|
+
}
|
|
1008
|
+
// If the trigger didn't actually start a turn (driver skipped → floor already freed by
|
|
1009
|
+
// triggerMeetingSpeak), advance to the next queued speaker rather than stalling the queue. A floor
|
|
1010
|
+
// DENIAL re-enters here too, but the holds-floor guard above makes the recursion a safe no-op (it waits
|
|
1011
|
+
// for the holder's release to drive the next drain).
|
|
1012
|
+
if (!this.triggerMeetingSpeak(next)) {
|
|
1013
|
+
this.drainSpeakerQueue(roomKey);
|
|
1014
|
+
}
|
|
1015
|
+
}
|
|
1016
|
+
/**
|
|
1017
|
+
* Claims the room floor and triggers the model to speak exactly one turn (meeting mode). Returns `false`
|
|
1018
|
+
* (stays silent) when another agent holds the floor. Shared by the matcher path and the moderator drainer.
|
|
1019
|
+
*/
|
|
1020
|
+
triggerMeetingSpeak(active) {
|
|
1021
|
+
if (active.RoomKey) {
|
|
1022
|
+
const floor = this.roomCoordinator.TakeFloor(active.RoomKey, active.AgentSessionID);
|
|
1023
|
+
if (!floor.Granted) {
|
|
1024
|
+
LogStatus(`[AIBridgeEngine] floor denied (${floor.Reason}) for bridge ${active.SessionBridgeID} — staying silent`);
|
|
1025
|
+
return false;
|
|
1026
|
+
}
|
|
1027
|
+
LogStatusEx({ message: `[AIBridgeEngine][diag] floor GRANTED to bridge ${active.SessionBridgeID} — triggering the model to speak`, verboseOnly: true });
|
|
1028
|
+
this.armFloorHold(active);
|
|
1029
|
+
}
|
|
1030
|
+
LogStatusEx({ message: `[AIBridgeEngine][diag] meeting trigger → RequestSpokenUpdate for bridge ${active.SessionBridgeID}`, verboseOnly: true });
|
|
1031
|
+
// The trigger can be SKIPPED by the driver (a response already in flight) or commit nothing — in which
|
|
1032
|
+
// case no assistant transcript will ever arrive to release the floor. If the driver reports "not sent"
|
|
1033
|
+
// (explicit `false`), release the floor immediately so the room doesn't wedge until the safety timer,
|
|
1034
|
+
// and advance the queue. `undefined`/`true` ⇒ a turn was triggered, so hold the floor as normal.
|
|
1035
|
+
const sent = active.RealtimeSession.RequestSpokenUpdate?.('');
|
|
1036
|
+
if (sent === false) {
|
|
1037
|
+
LogStatusEx({ message: `[AIBridgeEngine][diag] trigger NOT sent (driver skipped) for bridge ${active.SessionBridgeID} — releasing floor + advancing`, verboseOnly: true });
|
|
1038
|
+
this.releaseRoomFloor(active, /*skipDrain*/ true); // the drainSpeakerQueue caller advances the queue
|
|
1039
|
+
return false;
|
|
1040
|
+
}
|
|
1041
|
+
return true;
|
|
1042
|
+
}
|
|
1043
|
+
/** A short label for an `AgentSessionID` (the agent's first name) for diagnostics. */
|
|
1044
|
+
agentSessionLabel(sessionId) {
|
|
1045
|
+
for (const s of this.activeSessions.values()) {
|
|
1046
|
+
if (s.AgentSessionID.toLowerCase() === sessionId.toLowerCase()) {
|
|
1047
|
+
return s.AgentNames[0] ?? s.AgentSessionID.slice(0, 8);
|
|
1048
|
+
}
|
|
1049
|
+
}
|
|
1050
|
+
return sessionId.slice(0, 8);
|
|
1051
|
+
}
|
|
1052
|
+
/** Clears a room's moderator state (lookback, queue, counter) — on barge-in (queue only) or teardown (all). */
|
|
1053
|
+
clearRoomModeratorState(roomKey, full) {
|
|
1054
|
+
const key = roomKey.toLowerCase();
|
|
1055
|
+
this.roomSpeakerQueue.delete(key);
|
|
1056
|
+
this.roomPendingTurn.delete(key); // a barge-in/teardown invalidates any turn staged behind an in-flight call
|
|
1057
|
+
if (full) {
|
|
1058
|
+
this.roomLookback.delete(key);
|
|
1059
|
+
this.roomConsecutiveAgentTurns.delete(key);
|
|
1060
|
+
this.roomModeratorBusy.delete(key);
|
|
1061
|
+
}
|
|
513
1062
|
}
|
|
514
1063
|
/**
|
|
515
1064
|
* Acts on a turn-taking decision. Kept behind the injected {@link IRealtimeSession} interface so
|
|
@@ -521,11 +1070,14 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
521
1070
|
applyTurnDecision(active, action) {
|
|
522
1071
|
switch (action) {
|
|
523
1072
|
case 'Speak':
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
1073
|
+
if (active.DisableAutoResponse) {
|
|
1074
|
+
this.triggerMeetingSpeak(active);
|
|
1075
|
+
}
|
|
1076
|
+
else {
|
|
1077
|
+
// 1:1 CALL: the model has server-VAD auto-response on (same as the browser client-direct
|
|
1078
|
+
// path), so it ALREADY answered this turn — one clean stream. Forcing a second
|
|
1079
|
+
// `RequestSpokenUpdate` here would race the auto-response (double-answer + overlap/chop).
|
|
1080
|
+
// Rely on auto-response.
|
|
529
1081
|
}
|
|
530
1082
|
break;
|
|
531
1083
|
case 'PostToChat':
|
|
@@ -553,6 +1105,164 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
553
1105
|
};
|
|
554
1106
|
return new TurnTakingPolicy(config);
|
|
555
1107
|
}
|
|
1108
|
+
/**
|
|
1109
|
+
* Retroactively switches an already-running session into **meeting mode** (auto-response off +
|
|
1110
|
+
* addressed-only) — used when a room becomes multi-agent and the first (1:1) agent must stop
|
|
1111
|
+
* auto-responding. **Capability-gated**: only sessions whose provider reports
|
|
1112
|
+
* {@link RealtimeSessionCapabilities.CanReconfigureTurnMode} can change turn mode on a live socket;
|
|
1113
|
+
* others (e.g. Gemini, fixed at connect) are left in their start mode — no dead-method call. Idempotent.
|
|
1114
|
+
*
|
|
1115
|
+
* @param sessionBridgeID The bridge to re-gate.
|
|
1116
|
+
* @param matcher The addressed-matcher (the agent's names) the re-gated session should speak on.
|
|
1117
|
+
* @returns `true` if now in meeting mode (or already was); `false` if the session is unknown or the
|
|
1118
|
+
* provider can't reconfigure mid-session.
|
|
1119
|
+
*/
|
|
1120
|
+
ReconfigureSessionToMeeting(sessionBridgeID, matcher) {
|
|
1121
|
+
const active = this.activeSessions.get(sessionBridgeID.toLowerCase());
|
|
1122
|
+
if (!active) {
|
|
1123
|
+
return false;
|
|
1124
|
+
}
|
|
1125
|
+
if (active.DisableAutoResponse) {
|
|
1126
|
+
return true; // already meeting mode — nothing to do
|
|
1127
|
+
}
|
|
1128
|
+
if (active.RealtimeSession.Capabilities?.CanReconfigureTurnMode !== true) {
|
|
1129
|
+
// LOUD: this agent was the FIRST in the room (1:1 auto-response) and its provider can't switch a
|
|
1130
|
+
// live socket to meeting mode (e.g. Gemini). It will keep auto-responding to ALL room audio,
|
|
1131
|
+
// bypassing the turn moderator and likely talking over the other agents. The robust fix is to
|
|
1132
|
+
// reconnect it in meeting mode; until then, prefer a re-configurable provider (OpenAI) as the FIRST
|
|
1133
|
+
// agent in a room that will become multi-agent. See the Bridges guide §9.
|
|
1134
|
+
LogError(`[AIBridgeEngine] ⚠️ bridge ${sessionBridgeID} CANNOT re-gate to meeting mode mid-session ` +
|
|
1135
|
+
`(provider config fixed at connect, e.g. Gemini). It stays in 1:1 auto-response and will ` +
|
|
1136
|
+
`respond to ALL room audio, bypassing the moderator — use an OpenAI-realtime agent as the ` +
|
|
1137
|
+
`first agent in multi-agent rooms.`);
|
|
1138
|
+
return false;
|
|
1139
|
+
}
|
|
1140
|
+
active.RealtimeSession.Reconfigure?.({ DisableAutoResponse: true });
|
|
1141
|
+
active.DisableAutoResponse = true;
|
|
1142
|
+
active.TurnPolicy = new TurnTakingPolicy({ Mode: 'Passive', Matcher: matcher });
|
|
1143
|
+
// The agent started 1:1, so its system prompt has no meeting-discipline clause. The Reconfigure flips
|
|
1144
|
+
// the ENFORCEMENT (auto-response off + addressed gate), but tell the agent too so its replies are
|
|
1145
|
+
// meeting-appropriate. A context note is additive (doesn't clobber the prompt) — no-op if unsupported.
|
|
1146
|
+
active.RealtimeSession.SendContextNote?.(MEETING_REGATE_CONTEXT_NOTE);
|
|
1147
|
+
LogStatus(`[AIBridgeEngine] re-gated bridge ${sessionBridgeID} to meeting mode (room became multi-agent)`);
|
|
1148
|
+
return true;
|
|
1149
|
+
}
|
|
1150
|
+
/**
|
|
1151
|
+
* Marks the session as holding the room floor and arms the safety release timer (so a missed
|
|
1152
|
+
* end-of-speech can't wedge the floor closed). Called right after a granted {@link TakeFloor}.
|
|
1153
|
+
*
|
|
1154
|
+
* @param active The session that just claimed the floor.
|
|
1155
|
+
*/
|
|
1156
|
+
armFloorHold(active) {
|
|
1157
|
+
active.HoldsFloor = true;
|
|
1158
|
+
if (active.FloorReleaseTimer) {
|
|
1159
|
+
clearTimeout(active.FloorReleaseTimer);
|
|
1160
|
+
}
|
|
1161
|
+
LogStatusEx({ message: `[AIBridgeEngine][diag] floor HELD by bridge ${active.SessionBridgeID} (agentSession ${active.AgentSessionID}) — safety release in ${this.floorMaxHoldMs}ms if no assistant transcript`, verboseOnly: true });
|
|
1162
|
+
active.FloorReleaseTimer = setTimeout(() => {
|
|
1163
|
+
LogStatusEx({ message: `[AIBridgeEngine][diag] floor SAFETY-RELEASE fired for bridge ${active.SessionBridgeID} — it held the floor for ${this.floorMaxHoldMs}ms without producing a reply (the triggered turn never yielded audio)`, verboseOnly: true });
|
|
1164
|
+
this.releaseRoomFloor(active);
|
|
1165
|
+
}, this.floorMaxHoldMs);
|
|
1166
|
+
}
|
|
1167
|
+
/**
|
|
1168
|
+
* Releases the room floor this session holds (if any) and clears the safety timer. Idempotent and safe
|
|
1169
|
+
* for non-room / single-agent sessions (a no-op when the session never held the floor). Called on the
|
|
1170
|
+
* agent's own final transcript, the safety timeout, and teardown.
|
|
1171
|
+
*
|
|
1172
|
+
* @param active The session to release the floor for.
|
|
1173
|
+
*/
|
|
1174
|
+
releaseRoomFloor(active, skipDrain = false) {
|
|
1175
|
+
if (active.FloorReleaseTimer) {
|
|
1176
|
+
clearTimeout(active.FloorReleaseTimer);
|
|
1177
|
+
active.FloorReleaseTimer = undefined;
|
|
1178
|
+
}
|
|
1179
|
+
const held = active.HoldsFloor;
|
|
1180
|
+
if (active.RoomKey && held) {
|
|
1181
|
+
this.roomCoordinator.ReleaseFloor(active.RoomKey, active.AgentSessionID);
|
|
1182
|
+
LogStatusEx({ message: `[AIBridgeEngine][diag] floor RELEASED by bridge ${active.SessionBridgeID} (agentSession ${active.AgentSessionID}) — next addressed agent can now take it`, verboseOnly: true });
|
|
1183
|
+
}
|
|
1184
|
+
active.HoldsFloor = false;
|
|
1185
|
+
// Floor freed → trigger the next agent the moderator queued for this turn (serialized speaking). Skipped
|
|
1186
|
+
// when the caller (a skipped trigger inside drainSpeakerQueue) will itself advance the queue — avoids a
|
|
1187
|
+
// double drain.
|
|
1188
|
+
if (active.RoomKey && held && !skipDrain) {
|
|
1189
|
+
this.drainSpeakerQueue(active.RoomKey);
|
|
1190
|
+
}
|
|
1191
|
+
}
|
|
1192
|
+
/**
|
|
1193
|
+
* Elects this session as its room's transcript **scribe** iff a transcript sink is registered, the
|
|
1194
|
+
* session has a room key, and no scribe exists for that room yet. Exactly one scribe per room writes the
|
|
1195
|
+
* unified transcript, so a multi-agent room records one copy (the scribe hears everyone), not N.
|
|
1196
|
+
*
|
|
1197
|
+
* @param active The freshly connected session.
|
|
1198
|
+
*/
|
|
1199
|
+
electTranscriptScribe(active) {
|
|
1200
|
+
if (!this.transcriptSink || !active.RoomKey) {
|
|
1201
|
+
return;
|
|
1202
|
+
}
|
|
1203
|
+
const roomKey = active.RoomKey.toLowerCase();
|
|
1204
|
+
if (!this.roomScribes.has(roomKey)) {
|
|
1205
|
+
this.roomScribes.set(roomKey, active.SessionBridgeID);
|
|
1206
|
+
active.IsTranscriptScribe = true;
|
|
1207
|
+
LogStatus(`[AIBridgeEngine] Bridge ${active.SessionBridgeID} is the transcript scribe for its room.`);
|
|
1208
|
+
}
|
|
1209
|
+
}
|
|
1210
|
+
/**
|
|
1211
|
+
* Releases this session's scribe role on teardown and HANDS OFF to another live session in the same
|
|
1212
|
+
* room (so the transcript continues when the original scribe leaves a still-occupied room). No-op when
|
|
1213
|
+
* the session wasn't the scribe. Called during disconnect while the session is still in the active map.
|
|
1214
|
+
*
|
|
1215
|
+
* @param active The session being torn down.
|
|
1216
|
+
*/
|
|
1217
|
+
releaseTranscriptScribe(active) {
|
|
1218
|
+
if (!active.RoomKey) {
|
|
1219
|
+
return;
|
|
1220
|
+
}
|
|
1221
|
+
const roomKey = active.RoomKey.toLowerCase();
|
|
1222
|
+
if (this.roomScribes.get(roomKey) !== active.SessionBridgeID) {
|
|
1223
|
+
return; // not the scribe
|
|
1224
|
+
}
|
|
1225
|
+
this.roomScribes.delete(roomKey);
|
|
1226
|
+
active.IsTranscriptScribe = false;
|
|
1227
|
+
for (const other of this.activeSessions.values()) {
|
|
1228
|
+
if (other !== active && other.RoomKey?.toLowerCase() === roomKey) {
|
|
1229
|
+
this.roomScribes.set(roomKey, other.SessionBridgeID);
|
|
1230
|
+
other.IsTranscriptScribe = true;
|
|
1231
|
+
LogStatus(`[AIBridgeEngine] Transcript scribe handed to bridge ${other.SessionBridgeID} (prior scribe left).`);
|
|
1232
|
+
return;
|
|
1233
|
+
}
|
|
1234
|
+
}
|
|
1235
|
+
}
|
|
1236
|
+
/**
|
|
1237
|
+
* Emits one FINAL transcript line to the registered sink — only from the room's scribe, so the room
|
|
1238
|
+
* gets a single unified transcript. The scribe's OWN speech (`assistant`) is attributed to it; everything
|
|
1239
|
+
* it hears (`user`) is recorded as heard. Best-effort: a sink failure is logged, never fatal to media.
|
|
1240
|
+
*
|
|
1241
|
+
* @param active The scribe session.
|
|
1242
|
+
* @param t The final transcript line.
|
|
1243
|
+
*/
|
|
1244
|
+
emitTranscriptLine(active, t) {
|
|
1245
|
+
if (!active.IsTranscriptScribe || !this.transcriptSink || !active.RoomKey) {
|
|
1246
|
+
return;
|
|
1247
|
+
}
|
|
1248
|
+
const text = (t.Text ?? '').trim();
|
|
1249
|
+
if (!text) {
|
|
1250
|
+
return;
|
|
1251
|
+
}
|
|
1252
|
+
const isAgentSpeech = t.Role === 'assistant';
|
|
1253
|
+
void Promise.resolve(this.transcriptSink({
|
|
1254
|
+
RoomKey: active.RoomKey,
|
|
1255
|
+
AgentSessionID: active.AgentSessionID,
|
|
1256
|
+
AgentID: active.AgentID,
|
|
1257
|
+
IsAgentSpeech: isAgentSpeech,
|
|
1258
|
+
// The bot's own speech is labeled with its participant id; a 'user' line is attributed to
|
|
1259
|
+
// the last inbound speaker (diarization) so the transcript records WHO said it, not just
|
|
1260
|
+
// "a user". Falls back to undefined when the provider doesn't diarize.
|
|
1261
|
+
SpeakerParticipantID: isAgentSpeech ? active.BotParticipantID : active.LastInboundSpeaker,
|
|
1262
|
+
Text: text,
|
|
1263
|
+
}, active.ContextUser, active.MetadataProvider)).catch((err) => LogError(`[AIBridgeEngine] transcript sink failed for bridge ${active.SessionBridgeID}: ` +
|
|
1264
|
+
`${err instanceof Error ? err.message : String(err)}`));
|
|
1265
|
+
}
|
|
556
1266
|
// ──────────────────────────────────────────────────────────────────────────────
|
|
557
1267
|
// THE CHANNEL PLANE — Part A: generic wiring of the Phase 2 server-side channels.
|
|
558
1268
|
// ──────────────────────────────────────────────────────────────────────────────
|
|
@@ -621,8 +1331,60 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
621
1331
|
}
|
|
622
1332
|
}
|
|
623
1333
|
// ──────────────────────────────────────────────────────────────────────────────
|
|
624
|
-
// Janitor — orphan reconciliation
|
|
1334
|
+
// Janitor — orphan reconciliation + stale-session sweep.
|
|
625
1335
|
// ──────────────────────────────────────────────────────────────────────────────
|
|
1336
|
+
/**
|
|
1337
|
+
* Reaps **live, same-process** sessions that have gone stale — idle past {@link SESSION_IDLE_TTL_MS}
|
|
1338
|
+
* (no inbound transcript) or running past {@link SESSION_MAX_DURATION_MS}. This is the same-process
|
|
1339
|
+
* complement to {@link ReconcileOrphans} (prior-boot orphans): it covers a missed leave event, a
|
|
1340
|
+
* rosterless transport with no occupancy signal, and "the bot joined but nobody came." Each reap routes
|
|
1341
|
+
* through {@link StopBridgeSession} using the session's own user/provider, so the co-agent run finalizes.
|
|
1342
|
+
*
|
|
1343
|
+
* Tolerant: a single failed stop is logged and the sweep continues. Safe to call on any cadence.
|
|
1344
|
+
*
|
|
1345
|
+
* @param nowMs Current epoch-ms (injectable for tests; defaults to `Date.now()`).
|
|
1346
|
+
* @returns The number of stale sessions reaped.
|
|
1347
|
+
*/
|
|
1348
|
+
async SweepStaleSessions(nowMs = Date.now()) {
|
|
1349
|
+
const stale = [...this.activeSessions.values()].filter((s) => nowMs - s.LastActivityMs > this.idleTtlMs || nowMs - s.ConnectedAtMs > this.maxDurationMs);
|
|
1350
|
+
let reaped = 0;
|
|
1351
|
+
for (const active of stale) {
|
|
1352
|
+
const idle = nowMs - active.LastActivityMs > this.idleTtlMs;
|
|
1353
|
+
LogStatus(`[AIBridgeEngine] Stale sweep reaping bridge ${active.SessionBridgeID} ` +
|
|
1354
|
+
`(${idle ? 'idle' : 'max-duration'}) — auto-leaving.`);
|
|
1355
|
+
try {
|
|
1356
|
+
await this.StopBridgeSession(active.SessionBridgeID, 'HostEnded', active.ContextUser, active.MetadataProvider);
|
|
1357
|
+
reaped++;
|
|
1358
|
+
}
|
|
1359
|
+
catch (err) {
|
|
1360
|
+
LogError(`[AIBridgeEngine] stale sweep stop failed for ${active.SessionBridgeID}: ` +
|
|
1361
|
+
`${err instanceof Error ? err.message : String(err)}`);
|
|
1362
|
+
}
|
|
1363
|
+
}
|
|
1364
|
+
return reaped;
|
|
1365
|
+
}
|
|
1366
|
+
/**
|
|
1367
|
+
* Starts the self-scheduled stale-session sweep ({@link SweepStaleSessions} every
|
|
1368
|
+
* {@link STALE_SWEEP_INTERVAL_MS}). Idempotent — calling again is a no-op while a sweep is scheduled.
|
|
1369
|
+
* The host opts in once at startup; {@link StopStaleSessionSweep} cancels it (e.g. for tests/shutdown).
|
|
1370
|
+
*/
|
|
1371
|
+
StartStaleSessionSweep(intervalMs = STALE_SWEEP_INTERVAL_MS) {
|
|
1372
|
+
if (this.staleSweepTimer) {
|
|
1373
|
+
return;
|
|
1374
|
+
}
|
|
1375
|
+
this.staleSweepTimer = setInterval(() => {
|
|
1376
|
+
void this.SweepStaleSessions().catch((err) => LogError(`[AIBridgeEngine] stale sweep tick failed: ${err instanceof Error ? err.message : String(err)}`));
|
|
1377
|
+
}, intervalMs);
|
|
1378
|
+
// Don't keep the process alive solely for the sweep (Node-only; guarded for non-Node hosts).
|
|
1379
|
+
this.staleSweepTimer?.unref?.();
|
|
1380
|
+
}
|
|
1381
|
+
/** Cancels the self-scheduled stale-session sweep, if running. */
|
|
1382
|
+
StopStaleSessionSweep() {
|
|
1383
|
+
if (this.staleSweepTimer) {
|
|
1384
|
+
clearInterval(this.staleSweepTimer);
|
|
1385
|
+
this.staleSweepTimer = undefined;
|
|
1386
|
+
}
|
|
1387
|
+
}
|
|
626
1388
|
/**
|
|
627
1389
|
* Force-closes `Connected`/`Connecting` bridges left behind by a **previous boot of this host**
|
|
628
1390
|
* (matching hostname prefix, differing instance id), stamping `CloseReason = 'Janitor'`. Mirrors
|
|
@@ -673,6 +1435,24 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
673
1435
|
// ──────────────────────────────────────────────────────────────────────────────
|
|
674
1436
|
// Driver resolution + bridge-row persistence.
|
|
675
1437
|
// ──────────────────────────────────────────────────────────────────────────────
|
|
1438
|
+
/**
|
|
1439
|
+
* Binds the SDK factory onto a resolved driver before `Connect`. Precedence: a per-session
|
|
1440
|
+
* {@link StartBridgeSessionParams.BindSdk} override wins; otherwise the provider's registered native
|
|
1441
|
+
* binding from the {@link BridgeNativeSdkRegistry} is applied. When neither exists the driver keeps its
|
|
1442
|
+
* default factory (which fails loudly at connect if it actually needs an SDK — e.g. LoopbackBridge has
|
|
1443
|
+
* no SDK and needs no binding, so this is a harmless no-op for it).
|
|
1444
|
+
*
|
|
1445
|
+
* @param params The start params (its `BindSdk` is the override).
|
|
1446
|
+
* @param driver The resolved driver to bind onto.
|
|
1447
|
+
*/
|
|
1448
|
+
bindDriverSdk(params, driver) {
|
|
1449
|
+
const override = params.BindSdk;
|
|
1450
|
+
if (override) {
|
|
1451
|
+
override(driver);
|
|
1452
|
+
return;
|
|
1453
|
+
}
|
|
1454
|
+
BridgeNativeSdkRegistry.Instance.Apply(params.Provider.DriverClass, driver);
|
|
1455
|
+
}
|
|
676
1456
|
/**
|
|
677
1457
|
* Resolves the concrete bridge driver for a provider via the MJ `ClassFactory`, keyed by the
|
|
678
1458
|
* provider's `DriverClass`.
|
|
@@ -705,11 +1485,19 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
705
1485
|
* @returns The bridge context.
|
|
706
1486
|
*/
|
|
707
1487
|
buildBridgeContext(params) {
|
|
1488
|
+
// Carry the realtime model's audio format down to the media-transport driver so it resamples to the
|
|
1489
|
+
// rate the model actually consumes/emits (OpenAI 24 kHz; Gemini Live 16 kHz IN). Without this a
|
|
1490
|
+
// bridge feeds e.g. Gemini 24 kHz audio it can't parse and the agent never responds. Defaults keep
|
|
1491
|
+
// every existing driver/model on 24 kHz. See plans/realtime/realtime-core-host-convergence.md.
|
|
708
1492
|
return {
|
|
709
1493
|
Features: params.Provider.SupportedFeaturesObject ?? {},
|
|
710
1494
|
ProviderName: params.Provider.Name,
|
|
711
1495
|
Address: params.Address,
|
|
712
|
-
Configuration:
|
|
1496
|
+
Configuration: {
|
|
1497
|
+
...params.Configuration,
|
|
1498
|
+
InboundSampleRate: params.RealtimeSession.InputSampleRate ?? 24000,
|
|
1499
|
+
OutboundSampleRate: params.RealtimeSession.OutputSampleRate ?? 24000,
|
|
1500
|
+
},
|
|
713
1501
|
ContextUser: params.ContextUser,
|
|
714
1502
|
};
|
|
715
1503
|
}
|
|
@@ -772,6 +1560,25 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
772
1560
|
}
|
|
773
1561
|
/** Disconnects the driver of a live session, tolerant of driver teardown errors, and closes its channels. */
|
|
774
1562
|
async disconnectDriver(active, reason) {
|
|
1563
|
+
// Cancel any pending auto-leave timer so it can't fire against an already-torn-down session.
|
|
1564
|
+
if (active.LeaveGraceTimer) {
|
|
1565
|
+
clearTimeout(active.LeaveGraceTimer);
|
|
1566
|
+
active.LeaveGraceTimer = undefined;
|
|
1567
|
+
}
|
|
1568
|
+
// Hand the transcript scribe role to another live session in the room (if this was the scribe), so a
|
|
1569
|
+
// multi-agent room keeps recording after the first agent leaves. Done before the active map removal.
|
|
1570
|
+
this.releaseTranscriptScribe(active);
|
|
1571
|
+
// Drop out of the floor-control roster: release the floor if held (so a remaining agent isn't
|
|
1572
|
+
// blocked) and unregister so the room's membership count stays accurate.
|
|
1573
|
+
this.releaseRoomFloor(active);
|
|
1574
|
+
if (active.RoomKey) {
|
|
1575
|
+
this.roomCoordinator.UnregisterRoomParticipant(active.RoomKey, active.AgentSessionID);
|
|
1576
|
+
// Last agent out → drop the room's moderator state (lookback/queue/counter). A still-occupied room
|
|
1577
|
+
// keeps its lookback so the conversation thread survives one agent leaving.
|
|
1578
|
+
if (this.roomAgents(active.RoomKey).filter((a) => a.SessionBridgeID !== active.SessionBridgeID).length === 0) {
|
|
1579
|
+
this.clearRoomModeratorState(active.RoomKey, true);
|
|
1580
|
+
}
|
|
1581
|
+
}
|
|
775
1582
|
// Close the channel plane first so its post-close hooks see the session still mid-teardown,
|
|
776
1583
|
// then release the driver's media plane.
|
|
777
1584
|
await this.closeChannelPlane(active);
|
|
@@ -782,6 +1589,16 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
782
1589
|
LogError(`[AIBridgeEngine] driver Disconnect failed for bridge ${active.SessionBridgeID}: ` +
|
|
783
1590
|
`${err instanceof Error ? err.message : String(err)}`);
|
|
784
1591
|
}
|
|
1592
|
+
// Close the realtime model session too — releases the provider connection AND triggers the
|
|
1593
|
+
// co-agent run/prompt-run finalizer the agent layer wrapped onto Close() (otherwise the run dangles
|
|
1594
|
+
// in `Running` and the model socket leaks). Tolerant: a provider Close error must not block teardown.
|
|
1595
|
+
try {
|
|
1596
|
+
await active.RealtimeSession.Close();
|
|
1597
|
+
}
|
|
1598
|
+
catch (err) {
|
|
1599
|
+
LogError(`[AIBridgeEngine] realtime session Close failed for bridge ${active.SessionBridgeID}: ` +
|
|
1600
|
+
`${err instanceof Error ? err.message : String(err)}`);
|
|
1601
|
+
}
|
|
785
1602
|
}
|
|
786
1603
|
/**
|
|
787
1604
|
* Loads a bridge row and transitions it to `Disconnected` with the supplied `CloseReason`,
|
|
@@ -807,6 +1624,7 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
807
1624
|
if (row.Status === 'Disconnected' || row.Status === 'Failed') {
|
|
808
1625
|
return true; // idempotent — already terminal, keep the original reason.
|
|
809
1626
|
}
|
|
1627
|
+
const agentSessionID = row.AgentSessionID;
|
|
810
1628
|
row.Status = 'Disconnected';
|
|
811
1629
|
row.CloseReason = reason;
|
|
812
1630
|
row.DisconnectedAt = new Date();
|
|
@@ -815,6 +1633,19 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
815
1633
|
LogError(`[AIBridgeEngine] markBridgeDisconnected save failed for ${sessionBridgeID}: ` +
|
|
816
1634
|
`${row.LatestResult?.CompleteMessage ?? 'unknown error'}`);
|
|
817
1635
|
}
|
|
1636
|
+
// Finalize the co-agent run(s) for this session on EVERY teardown path. The same-process `Close()`
|
|
1637
|
+
// already finalized them (so this is a no-op there), but the orphan/cross-host reaps reach here
|
|
1638
|
+
// WITHOUT a live session — this is the only place their dangling `Running` co-agent run gets closed.
|
|
1639
|
+
// Tolerant: a finalizer failure must never block the disconnect bookkeeping.
|
|
1640
|
+
if (saved && this.runFinalizer && agentSessionID) {
|
|
1641
|
+
try {
|
|
1642
|
+
await this.runFinalizer(agentSessionID, reason !== 'Error', contextUser, provider);
|
|
1643
|
+
}
|
|
1644
|
+
catch (err) {
|
|
1645
|
+
LogError(`[AIBridgeEngine] session run finalizer failed for ${sessionBridgeID}: ` +
|
|
1646
|
+
`${err instanceof Error ? err.message : String(err)}`);
|
|
1647
|
+
}
|
|
1648
|
+
}
|
|
818
1649
|
return saved;
|
|
819
1650
|
}
|
|
820
1651
|
/** Escapes single quotes for safe embedding inside an `ExtraFilter` literal. */
|