@memberjunction/ai-bridge-server 5.42.0 → 5.44.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.
@@ -4,7 +4,7 @@ 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
9
  import { AIBridgeEngineBase, BaseRealtimeBridge, TurnTakingPolicy, BridgeNativeSdkRegistry, } from '@memberjunction/ai-bridge-base';
10
10
  import { MultiAgentRoomCoordinator } from './multi-agent-room-coordinator.js';
@@ -19,6 +19,42 @@ const SESSION_BRIDGE_PARTICIPANT_ENTITY = 'MJ: AI Agent Session Bridge Participa
19
19
  * room frees its model session + finalizes its run promptly. See {@link AIBridgeEngine.evaluateRoomOccupancy}.
20
20
  */
21
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.';
22
58
  /**
23
59
  * A default {@link IHostInstanceIdentity} for standalone use (and a sane fallback when the host
24
60
  * application does not inject one). Generates a stable `unknown-host:pid:bootId` identity at module
@@ -77,6 +113,11 @@ export class DefaultHostInstanceIdentity {
77
113
  let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
78
114
  constructor() {
79
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;
80
121
  /** roomKey (lowercased) → the bridge id of that room's current transcript scribe. Election dedup. */
81
122
  this.roomScribes = new Map();
82
123
  /** Diagnostic: session ids that have already logged their first inbound / outbound media frame. */
@@ -84,6 +125,18 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
84
125
  this.diagOutbound = new Set();
85
126
  /** In-memory registry of bridged sessions this process currently hosts, keyed by bridge id (lowercased). */
86
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();
87
140
  /** Host-instance identity provider; injected by the host application or defaulted for standalone use. */
88
141
  this.hostIdentity = new DefaultHostInstanceIdentity();
89
142
  /**
@@ -123,6 +176,9 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
123
176
  */
124
177
  async HandleStartup(contextUser, provider) {
125
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();
126
182
  }
127
183
  /**
128
184
  * Loads (or refreshes) the composed base's bridge metadata cache. Delegates to
@@ -175,6 +231,27 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
175
231
  SetSessionRunFinalizer(finalizer) {
176
232
  this.runFinalizer = finalizer;
177
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
+ }
178
255
  /**
179
256
  * Registers the {@link BridgeTranscriptSink} that persists the unified per-room transcript. The engine
180
257
  * elects one scribe per room and feeds its final transcript lines here; the sink owns *where* they land
@@ -186,6 +263,16 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
186
263
  SetTranscriptSink(sink) {
187
264
  this.transcriptSink = sink;
188
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
+ }
189
276
  /** Returns the active identities for an agent. @see AIBridgeEngineBase.IdentitiesForAgent */
190
277
  IdentitiesForAgent(agentId, providerId) {
191
278
  return this.Base.IdentitiesForAgent(agentId, providerId);
@@ -309,6 +396,14 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
309
396
  RoomKey: result.ExternalConnectionId,
310
397
  BotParticipantID: result.BotParticipantId,
311
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,
312
407
  Provider: params.Provider,
313
408
  ContextUser: params.ContextUser,
314
409
  MetadataProvider: params.MetadataProvider,
@@ -316,6 +411,12 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
316
411
  ServerChannelTools: [],
317
412
  };
318
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
+ }
319
420
  this.wireTransportSeam(active);
320
421
  this.wireParticipantTracking(active);
321
422
  this.wireTurnTaking(active);
@@ -378,11 +479,18 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
378
479
  // Inbound: endpoint media → the agent hears (and, for a video model, SEES) it. The frame's
379
480
  // Track tags the plane, so a human's camera (`video-in`) reaches the model as a `video` frame.
380
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
+ }
381
489
  const chunk = this.frameToArrayBuffer(frame);
382
490
  if (chunk) {
383
491
  if (!this.diagInbound.has(active.SessionBridgeID)) {
384
492
  this.diagInbound.add(active.SessionBridgeID);
385
- LogStatus(`[AIBridgeEngine][diag] FIRST inbound media frame reached the agent (bridge ${active.SessionBridgeID}, track=${frame.Track}). The agent is HEARING you.`);
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 });
386
494
  }
387
495
  RealtimeSession.SendInput(chunk, frame.Track === 'video-in' ? 'video' : 'audio');
388
496
  }
@@ -391,7 +499,7 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
391
499
  RealtimeSession.OnOutput((chunk) => {
392
500
  if (!this.diagOutbound.has(active.SessionBridgeID)) {
393
501
  this.diagOutbound.add(active.SessionBridgeID);
394
- LogStatus(`[AIBridgeEngine][diag] FIRST outbound audio from the agent (bridge ${active.SessionBridgeID}). The agent is SPEAKING into the room.`);
502
+ LogStatusEx({ message: `[AIBridgeEngine][diag] FIRST outbound audio from the agent (bridge ${active.SessionBridgeID}). The agent is SPEAKING into the room.`, verboseOnly: true });
395
503
  }
396
504
  const track = 'audio-out';
397
505
  Bridge.SendMedia(track, this.arrayBufferToFrame(chunk, track));
@@ -408,9 +516,17 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
408
516
  // agent goes quiet immediately. Without this, interruption "doesn't work" on the bridge surface.
409
517
  RealtimeSession.OnInterruption(() => {
410
518
  if (this.diagOutbound.has(active.SessionBridgeID)) {
411
- LogStatus(`[AIBridgeEngine][diag] barge-in — flushing the agent's queued audio (bridge ${active.SessionBridgeID}).`);
519
+ LogStatusEx({ message: `[AIBridgeEngine][diag] barge-in — flushing the agent's queued audio (bridge ${active.SessionBridgeID}).`, verboseOnly: true });
412
520
  }
413
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
+ }
414
530
  });
415
531
  }
416
532
  /**
@@ -527,7 +643,7 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
527
643
  LogStatus(`[AIBridgeEngine] All humans left bridge ${active.SessionBridgeID}; auto-leaving (grace elapsed).`);
528
644
  void this.StopBridgeSession(active.SessionBridgeID, 'HostEnded', active.ContextUser, active.MetadataProvider);
529
645
  }
530
- }, ROOM_EMPTY_GRACE_MS);
646
+ }, this.emptyGraceMs);
531
647
  }
532
648
  /**
533
649
  * Upserts the supplied participants onto the bridge as `AIAgentSessionBridgeParticipant` rows,
@@ -585,7 +701,13 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
585
701
  }
586
702
  row.DisplayName = p.DisplayName ?? null;
587
703
  row.Role = p.Role;
588
- row.IsAgent = p.IsAgent;
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();
589
711
  const saved = await row.Save();
590
712
  if (!saved) {
591
713
  LogError(`[AIBridgeEngine] participant upsert save failed: ${row.LatestResult?.CompleteMessage ?? 'unknown error'}`);
@@ -608,25 +730,336 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
608
730
  */
609
731
  wireTurnTaking(active) {
610
732
  active.RealtimeSession.OnTranscript((t) => {
611
- if (t.IsFinal) {
612
- // Only log FINAL transcripts — partials fire per-word and flood the log.
613
- LogStatus(`[AIBridgeEngine][diag] transcript(final): role=${t.Role} text="${(t.Text ?? '').slice(0, 80)}" (bridge ${active.SessionBridgeID})`);
614
- // Persist the unified room transcript (scribe only — emits both roles).
615
- this.emitTranscriptLine(active, t);
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)
736
+ }
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;
616
751
  }
617
- if (t.Role !== 'user' || !t.IsFinal) {
618
- return; // act only on a completed human turn
752
+ if (t.Role === 'user') {
753
+ this.dispatchUserTurn(active, t.Text ?? '');
619
754
  }
620
- const segment = {
621
- Text: t.Text,
622
- IsAgent: false,
623
- EndMs: Date.now(),
624
- };
625
- const decision = active.TurnPolicy.EvaluateTurn({ Segment: segment });
626
- LogStatus(`[AIBridgeEngine][diag] turn decision=${decision.Action} for user turn "${(t.Text ?? '').slice(0, 60)}" (bridge ${active.SessionBridgeID})`);
627
- this.applyTurnDecision(active, decision.Action);
628
755
  });
629
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),
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
+ }
1062
+ }
630
1063
  /**
631
1064
  * Acts on a turn-taking decision. Kept behind the injected {@link IRealtimeSession} interface so
632
1065
  * the actual model trigger stays the session's concern and the engine remains testable.
@@ -638,11 +1071,7 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
638
1071
  switch (action) {
639
1072
  case 'Speak':
640
1073
  if (active.DisableAutoResponse) {
641
- // MEETING MODE: the model's blind auto-response is OFF (the agent layer opened the
642
- // session with `disableAutoResponse`), so the bridge is the SOLE speech trigger. The
643
- // turn policy already gated this to an ADDRESSED turn, so issue exactly one response.
644
- // This is what lets several agents share a room without all answering every utterance.
645
- active.RealtimeSession.RequestSpokenUpdate?.('');
1074
+ this.triggerMeetingSpeak(active);
646
1075
  }
647
1076
  else {
648
1077
  // 1:1 CALL: the model has server-VAD auto-response on (same as the browser client-direct
@@ -676,6 +1105,90 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
676
1105
  };
677
1106
  return new TurnTakingPolicy(config);
678
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
+ }
679
1192
  /**
680
1193
  * Elects this session as its room's transcript **scribe** iff a transcript sink is registered, the
681
1194
  * session has a room key, and no scribe exists for that room yet. Exactly one scribe per room writes the
@@ -742,7 +1255,10 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
742
1255
  AgentSessionID: active.AgentSessionID,
743
1256
  AgentID: active.AgentID,
744
1257
  IsAgentSpeech: isAgentSpeech,
745
- SpeakerParticipantID: isAgentSpeech ? active.BotParticipantID : undefined,
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,
746
1262
  Text: text,
747
1263
  }, active.ContextUser, active.MetadataProvider)).catch((err) => LogError(`[AIBridgeEngine] transcript sink failed for bridge ${active.SessionBridgeID}: ` +
748
1264
  `${err instanceof Error ? err.message : String(err)}`));
@@ -815,8 +1331,60 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
815
1331
  }
816
1332
  }
817
1333
  // ──────────────────────────────────────────────────────────────────────────────
818
- // Janitor — orphan reconciliation (scaffold; scheduling is a host-provided hook).
1334
+ // Janitor — orphan reconciliation + stale-session sweep.
819
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
+ }
820
1388
  /**
821
1389
  * Force-closes `Connected`/`Connecting` bridges left behind by a **previous boot of this host**
822
1390
  * (matching hostname prefix, differing instance id), stamping `CloseReason = 'Janitor'`. Mirrors
@@ -1000,6 +1568,17 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
1000
1568
  // Hand the transcript scribe role to another live session in the room (if this was the scribe), so a
1001
1569
  // multi-agent room keeps recording after the first agent leaves. Done before the active map removal.
1002
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
+ }
1003
1582
  // Close the channel plane first so its post-close hooks see the session still mid-teardown,
1004
1583
  // then release the driver's media plane.
1005
1584
  await this.closeChannelPlane(active);