@memberjunction/ai-bridge-server 6.2.0-edge.1 → 6.2.0-edge.3

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.
@@ -6,8 +6,11 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
6
6
  };
7
7
  import { LogError, LogStatus, LogStatusEx, RunView, RegisterForStartup, } from '@memberjunction/core';
8
8
  import { BaseSingleton, MJGlobal, EscapeSQLString } from '@memberjunction/global';
9
- import { AIBridgeEngineBase, BaseRealtimeBridge, BaseTelephonyBridge, TurnTakingPolicy, BridgeNativeSdkRegistry, } from '@memberjunction/ai-bridge-base';
9
+ import { AIBridgeEngineBase, BaseRealtimeBridge, BaseTelephonyBridge, TurnTakingPolicy, BridgeNativeSdkRegistry, BuildAddressedMatcher, ParseTurnTakingToolCall, IsTurnTakingTool, MODEL_SIDE_TURN_TAKING_FRAMING, } from '@memberjunction/ai-bridge-base';
10
10
  import { MultiAgentRoomCoordinator } from './multi-agent-room-coordinator.js';
11
+ import { FullDuplexTurnGate, HumanSpeechDetector } from './full-duplex-turn-gate.js';
12
+ import { DtmfCoalescer } from './dtmf-coalescer.js';
13
+ import { AppendTranscriptTurn, BuildPriorTranscript } from './bridge-prior-transcript.js';
11
14
  /**
12
15
  * Entity names — centralised so the `MJ:`-prefix convention is applied in exactly one place.
13
16
  */
@@ -51,6 +54,19 @@ const ROOM_AGENT_TURN_HARD_CEILING = 30;
51
54
  const SESSION_IDLE_TTL_MS = 10 * 60 * 1000; // 10 min with no transcript activity
52
55
  const SESSION_MAX_DURATION_MS = 4 * 60 * 60 * 1000; // 4 h absolute cap
53
56
  const STALE_SWEEP_INTERVAL_MS = 60 * 1000; // sweep cadence when self-scheduled
57
+ /**
58
+ * How often a live session's `MJ: AI Agent Sessions.LastActiveAt` is refreshed. The host session janitor closes any
59
+ * session idle past its threshold (15 min by default); a phone call that never touches the row would be closed
60
+ * mid-call, finalizing its run while the caller is still talking. Well under that threshold.
61
+ */
62
+ const SESSION_HEARTBEAT_INTERVAL_MS = 5 * 60 * 1000;
63
+ /** How often prior-boot orphans are reconciled after the one-off pass at startup. */
64
+ const ORPHAN_RECONCILE_INTERVAL_MS = 10 * 60 * 1000;
65
+ /** How many times a dropped model session is re-opened before the call is ended. Never a loop. */
66
+ const MAX_MODEL_RECOVERY_ATTEMPTS = 1;
67
+ /** Said to the caller, at the carrier, when the model session is lost and cannot be recovered. */
68
+ const MODEL_LOSS_CALLER_MESSAGE = 'We are sorry, we are having technical difficulties and cannot continue this call. Please try again later. Goodbye.';
69
+ const AGENT_SESSION_ENTITY = 'MJ: AI Agent Sessions';
54
70
  /** Context note injected into a re-gated agent so it knows it's now in a meeting (its prompt predates it). */
55
71
  const MEETING_REGATE_CONTEXT_NOTE = 'You are now in a multi-party meeting with other people and agents. Stop responding to everything you ' +
56
72
  'hear — listen, and speak only when you are addressed by name or the conversation clearly needs your ' +
@@ -179,6 +195,10 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
179
195
  // Begin reaping stale live sessions (idle / over-duration) — the same-process backstop to the
180
196
  // occupancy auto-leave + the prior-boot orphan reconcile. Idempotent.
181
197
  this.StartStaleSessionSweep();
198
+ // Reconcile prior-boot orphans now and periodically. Needs a user + provider for the writes.
199
+ if (contextUser && provider) {
200
+ this.StartOrphanReconciliation(contextUser, provider);
201
+ }
182
202
  }
183
203
  /**
184
204
  * Loads (or refreshes) the composed base's bridge metadata cache. Delegates to
@@ -366,7 +386,9 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
366
386
  * @throws When the driver cannot be resolved or `Connect` fails (the row is stamped `Failed`).
367
387
  */
368
388
  async StartBridgeSession(params) {
369
- const bridgeRow = await this.createBridgeRow(params);
389
+ const fullDuplex = params.RealtimeSession.Capabilities?.FullDuplex === true;
390
+ const turn = this.buildTurnPolicy(params, fullDuplex);
391
+ const bridgeRow = await this.createBridgeRow(params, turn.Mode);
370
392
  try {
371
393
  // Resolve the driver inside the try so a resolution failure still stamps the row Failed
372
394
  // (the row already exists at this point — it must not be left dangling as Pending).
@@ -383,14 +405,15 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
383
405
  bridgeRow.BotParticipantID = result.BotParticipantId;
384
406
  bridgeRow.ConnectedAt = new Date();
385
407
  await this.transitionStatus(bridgeRow, 'Connected', params);
386
- const turnPolicy = this.buildTurnPolicy(params);
387
408
  const active = {
388
409
  SessionBridgeID: bridgeRow.ID,
389
410
  AgentSessionID: params.AgentSessionID,
390
411
  AgentID: params.AgentID,
391
412
  Bridge: driver,
392
413
  RealtimeSession: params.RealtimeSession,
393
- TurnPolicy: turnPolicy,
414
+ TurnPolicy: turn.Policy,
415
+ AddressingMode: turn.Mode,
416
+ ModelSideMatcher: turn.ModelSide,
394
417
  DisableAutoResponse: params.DisableAutoResponse === true,
395
418
  HasSeenHuman: false,
396
419
  RoomKey: result.ExternalConnectionId,
@@ -409,6 +432,15 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
409
432
  MetadataProvider: params.MetadataProvider,
410
433
  ChannelHost: params.ChannelHost,
411
434
  ServerChannelTools: [],
435
+ TranscriptSink: params.TranscriptSink,
436
+ OnBargeIn: params.OnBargeIn,
437
+ RecoverRealtimeSession: params.RecoverRealtimeSession,
438
+ OnSessionEnded: params.OnSessionEnded,
439
+ TranscriptTail: [],
440
+ ModelRecoveryAttempts: 0,
441
+ ModelRecovering: false,
442
+ Ending: false,
443
+ LastSessionHeartbeatMs: Date.now(),
412
444
  };
413
445
  this.electTranscriptScribe(active);
414
446
  // Join the room's floor-control roster (keyed on the shared room). For a single-agent room this
@@ -421,8 +453,11 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
421
453
  this.wireParticipantTracking(active);
422
454
  this.wireTelephonyLifecycle(active);
423
455
  this.wireTurnTaking(active);
456
+ this.wireFullDuplexTurnGate(active, params);
424
457
  await this.wireChannelPlane(active);
458
+ this.wireTurnTakingTools(active);
425
459
  this.activeSessions.set(bridgeRow.ID.toLowerCase(), active);
460
+ this.announceTurnTaking(active.RoomKey); // after registration, so the newcomer is counted among the room's agents
426
461
  LogStatus(`[AIBridgeEngine] Bridge session ${bridgeRow.ID} connected via ${params.Provider.Name}`);
427
462
  return active;
428
463
  }
@@ -446,13 +481,25 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
446
481
  const key = sessionBridgeID.toLowerCase();
447
482
  const active = this.activeSessions.get(key);
448
483
  if (active) {
484
+ active.Ending = true; // ignore model-loss signals that race the teardown
449
485
  await this.disconnectDriver(active, reason);
450
486
  this.activeSessions.delete(key);
451
- return this.markBridgeDisconnected(sessionBridgeID, reason, active.ContextUser ?? contextUser, active.MetadataProvider ?? provider);
487
+ const done = await this.markBridgeDisconnected(sessionBridgeID, reason, active.ContextUser ?? contextUser, active.MetadataProvider ?? provider);
488
+ await this.runSessionEndedHook(active, reason);
489
+ return done;
452
490
  }
453
491
  // Not held by this process — still reconcile the durable row (janitor / cross-host close).
454
492
  return this.markBridgeDisconnected(sessionBridgeID, reason, contextUser, provider);
455
493
  }
494
+ /** Runs the host's end-of-session hook. A failure is logged — teardown bookkeeping must not be blocked by it. */
495
+ async runSessionEndedHook(active, reason) {
496
+ try {
497
+ await active.OnSessionEnded?.(reason);
498
+ }
499
+ catch (err) {
500
+ LogError(`[AIBridgeEngine] session-ended hook failed for bridge ${active.SessionBridgeID}: ${err instanceof Error ? err.message : String(err)}`);
501
+ }
502
+ }
456
503
  // ──────────────────────────────────────────────────────────────────────────────
457
504
  // THE TRANSPORT SEAM — the deferred "unified-transport track" completed here.
458
505
  // ──────────────────────────────────────────────────────────────────────────────
@@ -476,24 +523,8 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
476
523
  * @param active The live bridged session whose driver and realtime session are wired together.
477
524
  */
478
525
  wireTransportSeam(active) {
479
- const { Bridge, RealtimeSession } = active;
480
- // Barge-in: on a TRUE interruption (the user speaks over the agent), the model stops generating —
481
- // but the driver may still hold queued outbound audio that would keep playing. Flush it so the
482
- // agent goes quiet immediately. Without this, interruption "doesn't work" on the bridge surface.
483
- RealtimeSession.OnInterruption(() => {
484
- if (this.diagOutbound.has(active.SessionBridgeID)) {
485
- LogStatusEx({ message: `[AIBridgeEngine][diag] barge-in — flushing the agent's queued audio (bridge ${active.SessionBridgeID}).`, verboseOnly: true });
486
- }
487
- Bridge.FlushOutboundMedia();
488
- // A human cut in → any moderator decision staged for the prior turn is now stale. Drop the queued
489
- // speakers (the human's new turn will drive a fresh decision); also free the floor this agent held.
490
- if (active.RoomKey) {
491
- this.clearRoomModeratorState(active.RoomKey, false);
492
- if (active.HoldsFloor) {
493
- this.releaseRoomFloor(active);
494
- }
495
- }
496
- });
526
+ const { Bridge } = active;
527
+ this.wireModelSession(active);
497
528
  if (Bridge.Features.DetachedMediaPlane) {
498
529
  // Detached media plane (e.g. OpenAISipBridge): the carrier/platform terminates the media leg
499
530
  // directly with the AI provider. MJ is NOT in the media relay path.
@@ -501,6 +532,7 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
501
532
  }
502
533
  // Inbound: endpoint media → the agent hears (and, for a video model, SEES) it. The frame's
503
534
  // Track tags the plane, so a human's camera (`video-in`) reaches the model as a `video` frame.
535
+ // Always read `active.RealtimeSession` — a recovered session replaces it mid-call.
504
536
  Bridge.OnMedia((frame) => {
505
537
  active.LastActivityMs = Date.now();
506
538
  // DIARIZATION: the inbound frame carries the speaking participant's identity (when the provider
@@ -511,33 +543,94 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
511
543
  active.LastInboundSpeaker = frame.SpeakerLabel;
512
544
  }
513
545
  const chunk = this.frameToArrayBuffer(frame);
514
- if (chunk) {
546
+ this.observeInboundHumanSpeech(active, frame, chunk);
547
+ if (chunk && !active.ModelRecovering) {
515
548
  if (!this.diagInbound.has(active.SessionBridgeID)) {
516
549
  this.diagInbound.add(active.SessionBridgeID);
517
550
  LogStatusEx({ message: `[AIBridgeEngine][diag] FIRST inbound media frame reached the agent (bridge ${active.SessionBridgeID}, track=${frame.Track}). The agent is HEARING you.`, verboseOnly: true });
518
551
  }
519
- RealtimeSession.SendInput(chunk, frame.Track === 'video-in' ? 'video' : 'audio');
552
+ active.RealtimeSession.SendInput(chunk, frame.Track === 'video-in' ? 'video' : 'audio');
520
553
  }
521
554
  });
555
+ }
556
+ /**
557
+ * Wires everything that hangs off the MODEL session: barge-in, the lifecycle (drop) signals, and — unless the
558
+ * media plane is detached — the agent's outbound audio/video. Called at connect AND again for a replacement
559
+ * session after a recovery, so every handler checks it still belongs to the active session.
560
+ *
561
+ * @param active The live bridged session.
562
+ */
563
+ wireModelSession(active) {
564
+ const { Bridge } = active;
565
+ const session = active.RealtimeSession;
566
+ // Barge-in: on a TRUE interruption (the user speaks over the agent), the model stops generating —
567
+ // but the driver may still hold queued outbound audio that would keep playing. Flush it so the
568
+ // agent goes quiet immediately. Without this, interruption "doesn't work" on the bridge surface.
569
+ session.OnInterruption(() => this.handleBargeIn(active));
570
+ this.wireModelLifecycle(active, session);
571
+ if (Bridge.Features.DetachedMediaPlane) {
572
+ return;
573
+ }
522
574
  // Outbound: the agent speaks → into the meeting/call.
523
- RealtimeSession.OnOutput((chunk) => {
575
+ session.OnOutput((chunk) => {
576
+ if (active.RealtimeSession !== session) {
577
+ return; // a stale (replaced) session
578
+ }
524
579
  active.LastActivityMs = Date.now();
525
580
  if (!this.diagOutbound.has(active.SessionBridgeID)) {
526
581
  this.diagOutbound.add(active.SessionBridgeID);
527
582
  LogStatusEx({ message: `[AIBridgeEngine][diag] FIRST outbound audio from the agent (bridge ${active.SessionBridgeID}). The agent is SPEAKING into the room.`, verboseOnly: true });
528
583
  }
584
+ const verdict = this.gateOutput(active, chunk.byteLength);
585
+ if (verdict !== 'Forward') {
586
+ if (verdict === 'Cut') {
587
+ Bridge.FlushOutboundMedia(); // the burst was just refused — drop audio already queued for it too
588
+ }
589
+ return;
590
+ }
529
591
  const track = 'audio-out';
530
592
  Bridge.SendMedia(track, this.arrayBufferToFrame(chunk, track));
531
593
  });
532
594
  // Outbound VIDEO: a video-capable session ALSO emits a synced avatar/video track. Optional —
533
595
  // audio-only sessions don't implement OnVideoOutput, so call it null-safely. The bridge driver
534
596
  // gates the actual publish on its `VideoOut` capability.
535
- RealtimeSession.OnVideoOutput?.((chunk) => {
597
+ session.OnVideoOutput?.((chunk) => {
598
+ if (active.RealtimeSession !== session) {
599
+ return;
600
+ }
536
601
  active.LastActivityMs = Date.now();
537
602
  const track = 'video-out';
538
603
  Bridge.SendMedia(track, this.arrayBufferToFrame(chunk, track));
539
604
  });
540
605
  }
606
+ /** A true barge-in: flush queued audio, drop stale room moderator state, free the floor, tell the host. */
607
+ handleBargeIn(active) {
608
+ if (this.diagOutbound.has(active.SessionBridgeID)) {
609
+ LogStatusEx({ message: `[AIBridgeEngine][diag] barge-in — flushing the agent's queued audio (bridge ${active.SessionBridgeID}).`, verboseOnly: true });
610
+ }
611
+ active.Bridge.FlushOutboundMedia();
612
+ // A human cut in → any moderator decision staged for the prior turn is now stale. Drop the queued
613
+ // speakers (the human's new turn will drive a fresh decision); also free the floor this agent held.
614
+ if (active.RoomKey) {
615
+ if (this.isHumanSpeaker(active.LastInboundSpeaker)) {
616
+ this.preemptForHuman(active.RoomKey); // a person cut in — every agent yields, not just this one
617
+ }
618
+ this.clearRoomModeratorState(active.RoomKey, false);
619
+ if (active.HoldsFloor) {
620
+ this.releaseRoomFloor(active);
621
+ }
622
+ }
623
+ this.notifyBargeIn(active);
624
+ }
625
+ /** Tells the host about a barge-in so it can drop now-stale narration (never delegated work). A hook failure is logged, never fatal. */
626
+ notifyBargeIn(active) {
627
+ try {
628
+ active.OnBargeIn?.();
629
+ }
630
+ catch (err) {
631
+ LogError(`[AIBridgeEngine] barge-in hook failed for bridge ${active.SessionBridgeID}: ${err instanceof Error ? err.message : String(err)}`);
632
+ }
633
+ }
541
634
  /**
542
635
  * Unwraps a {@link BridgeMediaFrame} to the raw `ArrayBuffer` the realtime session consumes,
543
636
  * preferring the binary `Bytes` payload and decoding `Base64` when only that is present. Returns
@@ -624,6 +717,110 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
624
717
  LogStatus(`[AIBridgeEngine] Telephony call ended for bridge ${active.SessionBridgeID} — stopping bridge session.`);
625
718
  void this.StopBridgeSession(active.SessionBridgeID, 'HostEnded', active.ContextUser, active.MetadataProvider);
626
719
  });
720
+ this.wireInboundDtmf(active, active.Bridge);
721
+ }
722
+ }
723
+ /**
724
+ * Routes the caller's keypad presses to the model as one short context note per burst ("the caller pressed
725
+ * 1234"). Capability-gated: a provider with DTMF off throws from `OnDTMF`, which just means no keypad input.
726
+ */
727
+ wireInboundDtmf(active, bridge) {
728
+ const coalescer = new DtmfCoalescer((digits) => {
729
+ if (!active.Ending) {
730
+ active.RealtimeSession.SendContextNote?.(`[caller keypad] The caller pressed: ${digits}`);
731
+ }
732
+ });
733
+ try {
734
+ bridge.OnDTMF((digits) => coalescer.Push(digits));
735
+ active.DtmfCoalescer = coalescer;
736
+ }
737
+ catch (err) {
738
+ coalescer.Dispose();
739
+ LogStatusEx({ message: `[AIBridgeEngine] inbound DTMF not routed for bridge ${active.SessionBridgeID}: ${err instanceof Error ? err.message : String(err)}`, verboseOnly: true });
740
+ }
741
+ }
742
+ /**
743
+ * Subscribes to the model session's fatal-error and unexpected-close signals. Either means the caller is now
744
+ * talking to a dead line, so it starts {@link handleModelLoss}. Both can fire for one drop; the handler
745
+ * de-duplicates.
746
+ */
747
+ wireModelLifecycle(active, session) {
748
+ session.OnError((error) => {
749
+ if (error.Fatal) {
750
+ void this.handleModelLoss(active, session, `fatal session error${error.Code ? ` [${error.Code}]` : ''}: ${error.Message}`);
751
+ }
752
+ });
753
+ session.OnClose?.(() => {
754
+ void this.handleModelLoss(active, session, 'the provider closed the connection');
755
+ });
756
+ }
757
+ /**
758
+ * The model session dropped mid-call. Re-open it ONCE, seeded with what was said, and carry on; if that is not
759
+ * possible (no recovery factory, attempts spent, the factory fails, or the replacement uses different audio
760
+ * rates) end the call cleanly instead of leaving the caller in silence.
761
+ */
762
+ async handleModelLoss(active, lost, why) {
763
+ if (active.Ending || active.ModelRecovering || active.RealtimeSession !== lost) {
764
+ return; // already tearing down, already recovering, or a signal from a session we replaced
765
+ }
766
+ LogError(`[AIBridgeEngine] model session lost for bridge ${active.SessionBridgeID}: ${why}`);
767
+ if (!active.RecoverRealtimeSession || active.ModelRecoveryAttempts >= MAX_MODEL_RECOVERY_ATTEMPTS) {
768
+ await this.endCallAfterModelLoss(active);
769
+ return;
770
+ }
771
+ active.ModelRecovering = true;
772
+ active.ModelRecoveryAttempts++;
773
+ try {
774
+ const fresh = await active.RecoverRealtimeSession({
775
+ PriorTranscript: BuildPriorTranscript(active.TranscriptTail),
776
+ Attempt: active.ModelRecoveryAttempts,
777
+ Reason: why,
778
+ });
779
+ await this.adoptRecoveredSession(active, lost, fresh);
780
+ }
781
+ catch (err) {
782
+ LogError(`[AIBridgeEngine] model session recovery failed for bridge ${active.SessionBridgeID}: ${err instanceof Error ? err.message : String(err)}`);
783
+ active.ModelRecovering = false;
784
+ await this.endCallAfterModelLoss(active);
785
+ }
786
+ }
787
+ /** Swaps a recovered model session in for the lost one, or refuses it when it cannot carry the call's audio. */
788
+ async adoptRecoveredSession(active, lost, fresh) {
789
+ const sameRates = (fresh.InputSampleRate ?? 24000) === (lost.InputSampleRate ?? 24000) && (fresh.OutputSampleRate ?? 24000) === (lost.OutputSampleRate ?? 24000);
790
+ if (active.Ending || !sameRates) {
791
+ await this.closeQuietly(fresh);
792
+ throw new Error(active.Ending ? 'the call ended during recovery' : 'the replacement session uses different audio sample rates');
793
+ }
794
+ active.RealtimeSession = fresh;
795
+ this.wireModelSession(active);
796
+ this.wireTurnTaking(active);
797
+ active.ModelRecovering = false;
798
+ LogStatus(`[AIBridgeEngine] model session re-opened for bridge ${active.SessionBridgeID} (attempt ${active.ModelRecoveryAttempts}).`);
799
+ await this.closeQuietly(lost); // releases the dead socket and finalizes its observability run
800
+ }
801
+ /** Ends a call whose model session cannot be recovered: a spoken goodbye at the carrier (telephony), then a clean stop. */
802
+ async endCallAfterModelLoss(active) {
803
+ if (active.Ending) {
804
+ return;
805
+ }
806
+ active.Ending = true; // a signal that races this one must not start a second teardown
807
+ if (active.Bridge instanceof BaseTelephonyBridge) {
808
+ try {
809
+ await active.Bridge.AnnounceAndEndCall(MODEL_LOSS_CALLER_MESSAGE);
810
+ }
811
+ catch (err) {
812
+ LogError(`[AIBridgeEngine] could not announce the failure to the caller on bridge ${active.SessionBridgeID}: ${err instanceof Error ? err.message : String(err)}`);
813
+ }
814
+ }
815
+ await this.StopBridgeSession(active.SessionBridgeID, 'Error', active.ContextUser, active.MetadataProvider);
816
+ }
817
+ /** Closes a realtime session, logging (never throwing) a provider error. */
818
+ async closeQuietly(session) {
819
+ try {
820
+ await session.Close();
821
+ }
822
+ catch (err) {
823
+ LogError(`[AIBridgeEngine] closing a realtime session failed: ${err instanceof Error ? err.message : String(err)}`);
627
824
  }
628
825
  }
629
826
  /**
@@ -746,17 +943,26 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
746
943
  * @param active The live bridged session.
747
944
  */
748
945
  wireTurnTaking(active) {
749
- active.RealtimeSession.OnTranscript((t) => {
946
+ const session = active.RealtimeSession;
947
+ session.OnTranscript((t) => {
948
+ if (active.RealtimeSession !== session) {
949
+ return; // a stale (replaced) session
950
+ }
750
951
  active.LastActivityMs = Date.now(); // any transcript = the session is alive (drives the idle sweep)
751
952
  if (!t.IsFinal) {
752
953
  return; // partials fire per-word — act only on a completed turn (and don't flood the log)
753
954
  }
754
955
  LogStatusEx({ message: `[AIBridgeEngine][diag] transcript(final): role=${t.Role} text="${(t.Text ?? '').slice(0, 80)}" (bridge ${active.SessionBridgeID})`, verboseOnly: true });
755
- // Persist the unified room transcript (scribe only — emits both roles).
956
+ if (t.Role === 'user' || t.Role === 'assistant') {
957
+ AppendTranscriptTurn(active.TranscriptTail, { Role: t.Role, Text: t.Text ?? '' });
958
+ }
959
+ // Persist the transcript: this session's own sink, or the unified room transcript (scribe only).
756
960
  this.emitTranscriptLine(active, t);
757
961
  // Record into the room's diarized lookback so the moderator (and observability) see the full thread.
758
962
  this.recordRoomTurn(active, t);
759
963
  if (t.Role === 'assistant') {
964
+ // Full-duplex gate: settle the turn first so a short acknowledgement is reclassified as a backchannel.
965
+ active.TurnGate?.EndTurn({ Text: t.Text });
760
966
  // The agent finished its own turn → release the room floor so the next can speak. Then advance:
761
967
  // run the moderator for "who responds to this agent?" (the agent↔agent + pre-stage path) — this
762
968
  // executes while the agent's audio is still playing out, hiding the moderator latency.
@@ -800,6 +1006,9 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
800
1006
  for (const peer of peers) {
801
1007
  this.noteHumanPresence(peer);
802
1008
  }
1009
+ if (source.RoomKey) {
1010
+ this.roomCoordinator.NoteHumanTurn(source.RoomKey); // a human spoke: agents may take turns again
1011
+ }
803
1012
  }
804
1013
  if (source.RoomKey) {
805
1014
  this.roomConsecutiveAgentTurns.set(source.RoomKey.toLowerCase(), 0);
@@ -1107,20 +1316,258 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
1107
1316
  break;
1108
1317
  }
1109
1318
  }
1319
+ // ──────────────────────────────────────────────────────────────────────────────
1320
+ // Full-duplex turn-taking — the room floor as a safety net behind the model's own judgement.
1321
+ // ──────────────────────────────────────────────────────────────────────────────
1322
+ /**
1323
+ * Gives a FULL-DUPLEX model the floor gate + human-speech detector (see {@link FullDuplexTurnGate}).
1324
+ * Turn-based models are never gated: the engine triggers their speech, so it already decides when.
1325
+ *
1326
+ * @param active The freshly connected session.
1327
+ * @param params The start parameters (`FullDuplexTurnGate: false` opts out).
1328
+ */
1329
+ wireFullDuplexTurnGate(active, params) {
1330
+ if (!active.RoomKey || params.FullDuplexTurnGate === false) {
1331
+ return;
1332
+ }
1333
+ if (active.RealtimeSession.Capabilities?.FullDuplex !== true) {
1334
+ return;
1335
+ }
1336
+ active.TurnGate = new FullDuplexTurnGate({
1337
+ Coordinator: this.roomCoordinator,
1338
+ RoomId: active.RoomKey,
1339
+ AgentSessionId: active.AgentSessionID,
1340
+ SampleRateHz: active.RealtimeSession.OutputSampleRate,
1341
+ });
1342
+ active.HumanSpeech = new HumanSpeechDetector();
1343
+ }
1344
+ /**
1345
+ * Runs one chunk of a full-duplex model's outbound audio through its floor gate. Sessions without a gate,
1346
+ * and rooms with a single agent, are never gated.
1347
+ *
1348
+ * @param active The speaking session.
1349
+ * @param byteLength The chunk size (PCM16).
1350
+ * @returns Whether to forward the chunk, drop it, or cut the burst (drop + flush queued audio).
1351
+ */
1352
+ gateOutput(active, byteLength) {
1353
+ const gate = active.TurnGate;
1354
+ if (!gate || !active.RoomKey || !this.roomCoordinator.IsMultiAgentRoom(active.RoomKey)) {
1355
+ return 'Forward';
1356
+ }
1357
+ const result = gate.OnOutputAudio(byteLength);
1358
+ if (result.TookFloor) {
1359
+ this.armFloorHold(active);
1360
+ }
1361
+ if (result.Verdict === 'Cut') {
1362
+ LogStatusEx({ message: `[AIBridgeEngine][diag] full-duplex gate CUT bridge ${active.SessionBridgeID} — it spoke without the floor`, verboseOnly: true });
1363
+ }
1364
+ return result.Verdict;
1365
+ }
1366
+ /** Whether an inbound speaker label belongs to a human (diarized, and not a peer `agent-…` bot). */
1367
+ isHumanSpeaker(label) {
1368
+ return label !== undefined && label.length > 0 && !label.toLowerCase().startsWith('agent-');
1369
+ }
1370
+ /**
1371
+ * Watches inbound room audio for a human speaking and, on the first activity, makes every agent yield.
1372
+ * Only a DIARIZED human counts — without a speaker label the audio could be a peer agent, and a peer must
1373
+ * never preempt another agent's turn.
1374
+ */
1375
+ observeInboundHumanSpeech(active, frame, chunk) {
1376
+ const detector = active.HumanSpeech;
1377
+ if (!detector || !chunk || !active.RoomKey || frame.Track !== 'audio-in' || !this.isHumanSpeaker(frame.SpeakerLabel)) {
1378
+ return;
1379
+ }
1380
+ if (this.roomCoordinator.IsMultiAgentRoom(active.RoomKey) && detector.ShouldReportSpeech(chunk)) {
1381
+ this.preemptForHuman(active.RoomKey);
1382
+ }
1383
+ }
1384
+ /**
1385
+ * A human started talking: tell the coordinator (humans win), and for the agent that was holding the floor
1386
+ * flush its queued audio, mute the rest of its burst, free its floor, and fire the barge-in hook so the host
1387
+ * drops now-stale narration. Delegated work keeps running — the same policy as a direct barge-in.
1388
+ *
1389
+ * @param roomKey The room the human spoke in.
1390
+ */
1391
+ preemptForHuman(roomKey) {
1392
+ const { PreemptedAgentSessionId } = this.roomCoordinator.NoteHumanSpeech(roomKey);
1393
+ if (!PreemptedAgentSessionId) {
1394
+ return;
1395
+ }
1396
+ const target = this.roomAgents(roomKey).find((a) => a.AgentSessionID.toLowerCase() === PreemptedAgentSessionId.toLowerCase());
1397
+ if (!target) {
1398
+ return;
1399
+ }
1400
+ LogStatusEx({ message: `[AIBridgeEngine][diag] human speech preempted bridge ${target.SessionBridgeID} — flushing its output`, verboseOnly: true });
1401
+ target.TurnGate?.Cut();
1402
+ target.Bridge.FlushOutboundMedia();
1403
+ this.clearRoomModeratorState(roomKey, false);
1404
+ this.releaseRoomFloor(target, /*skipDrain*/ true);
1405
+ this.notifyBargeIn(target);
1406
+ }
1407
+ /**
1408
+ * Binds the turn-taking host tools (`i_am_addressed`, `yield_turn`) to a session that needs them: a
1409
+ * full-duplex model in a room, or any model using model-side addressing. The tool DEFINITIONS are
1410
+ * {@link TURN_TAKING_TOOL_DEFINITIONS}; the layer that owns the model session registers them at connect and
1411
+ * installs {@link ActiveBridgeSession.TurnTakingToolHandler} as its local tool handler.
1412
+ *
1413
+ * @param active The live bridged session.
1414
+ */
1415
+ wireTurnTakingTools(active) {
1416
+ if (!active.RoomKey || !(active.AddressingMode === 'ModelSide' || active.TurnGate)) {
1417
+ return;
1418
+ }
1419
+ active.TurnTakingToolHandler = {
1420
+ Handles: (toolName) => IsTurnTakingTool(toolName),
1421
+ Execute: async (call) => this.executeTurnTakingTool(active, call.ToolName, call.Arguments),
1422
+ };
1423
+ }
1424
+ /**
1425
+ * Once a room holds 2+ agents, tells each tool-equipped (full-duplex / model-side) agent in it — once — how to
1426
+ * take turns: speak when addressed, stop for a person, only acknowledge briefly over someone, hand over by name.
1427
+ * It is a context note rather than part of the system prompt on purpose: the FIRST agent joins before anyone
1428
+ * else, and a solo agent in a one-on-one call must keep answering everything it hears.
1429
+ *
1430
+ * @param roomKey The room to announce in (no-op when `undefined`, or while the room has a single agent).
1431
+ */
1432
+ announceTurnTaking(roomKey) {
1433
+ if (!roomKey || !this.roomCoordinator.IsMultiAgentRoom(roomKey)) {
1434
+ return;
1435
+ }
1436
+ for (const agent of this.roomAgents(roomKey)) {
1437
+ if (agent.TurnTakingToolHandler && !agent.TurnTakingAnnounced) {
1438
+ agent.RealtimeSession.SendContextNote?.(MODEL_SIDE_TURN_TAKING_FRAMING);
1439
+ agent.TurnTakingAnnounced = true;
1440
+ }
1441
+ }
1442
+ }
1443
+ /** Runs one turn-taking tool call and returns the JSON the model is handed back. Never throws. */
1444
+ executeTurnTakingTool(active, toolName, argsJson) {
1445
+ try {
1446
+ const parsed = ParseTurnTakingToolCall(toolName, argsJson);
1447
+ if (!parsed) {
1448
+ return JSON.stringify({ ok: false, error: `Unknown turn-taking tool '${toolName}'.` });
1449
+ }
1450
+ switch (parsed.Kind) {
1451
+ case 'Addressed':
1452
+ return this.onModelAddressed(active);
1453
+ case 'Yield':
1454
+ return this.onModelYield(active, parsed.To);
1455
+ default:
1456
+ return JSON.stringify({ ok: false, error: parsed.Reason });
1457
+ }
1458
+ }
1459
+ catch (err) {
1460
+ LogError(`[AIBridgeEngine] turn-taking tool ${toolName} failed for bridge ${active.SessionBridgeID}: ${err instanceof Error ? err.message : String(err)}`);
1461
+ return JSON.stringify({ ok: false, error: 'The turn-taking action failed.' });
1462
+ }
1463
+ }
1464
+ /**
1465
+ * The model said it is addressed: latch the model-side matcher and — in a multi-agent room — reserve the
1466
+ * floor NOW, before any audio, so a peer cannot start in the gap. A denial tells the model to stay silent,
1467
+ * which is how a cooperative model learns it lost the race.
1468
+ */
1469
+ onModelAddressed(active) {
1470
+ active.ModelSideMatcher?.NoteModelAddressed();
1471
+ if (!active.RoomKey || !this.roomCoordinator.IsMultiAgentRoom(active.RoomKey)) {
1472
+ return JSON.stringify({ ok: true, floor: 'granted' });
1473
+ }
1474
+ const floor = this.roomCoordinator.TakeFloor(active.RoomKey, active.AgentSessionID);
1475
+ if (!floor.Granted) {
1476
+ return JSON.stringify({ ok: false, floor: 'denied', reason: floor.Reason, instruction: 'Do not speak now; stay silent.' });
1477
+ }
1478
+ this.armFloorHold(active);
1479
+ return JSON.stringify({ ok: true, floor: 'granted' });
1480
+ }
1481
+ /**
1482
+ * The model hands the floor over, optionally to a named agent: release it, reserve it for the target, and
1483
+ * nudge the target to speak. A name that matches nobody degrades to a plain release.
1484
+ */
1485
+ onModelYield(active, toName) {
1486
+ if (!active.RoomKey) {
1487
+ return JSON.stringify({ ok: true, floor: 'released' });
1488
+ }
1489
+ const target = toName ? this.findRoomAgentByName(active.RoomKey, toName, active) : undefined;
1490
+ const result = this.roomCoordinator.YieldFloor(active.RoomKey, active.AgentSessionID, target?.AgentSessionID);
1491
+ active.TurnGate?.Reset();
1492
+ this.releaseRoomFloor(active, /*skipDrain*/ true);
1493
+ if (target && result.HandoffToAgentSessionId) {
1494
+ this.handOffFloor(active, target);
1495
+ }
1496
+ const note = toName && !target ? `No agent named '${toName}' is in the room; the floor went back to the room.` : undefined;
1497
+ const handedTo = result.HandoffToAgentSessionId ? target?.AgentNames[0] ?? null : null;
1498
+ return JSON.stringify({ ok: true, floor: 'released', handedTo, reason: result.Reason, note });
1499
+ }
1500
+ /** Finds another agent in the room by any of its names (case-insensitive), excluding the asker. */
1501
+ findRoomAgentByName(roomKey, name, asker) {
1502
+ const wanted = name.trim().toLowerCase();
1503
+ return this.roomAgents(roomKey).find((a) => a !== asker && a.AgentNames.some((n) => n.trim().toLowerCase() === wanted));
1504
+ }
1505
+ /** Tells a hand-off target it was given the floor and triggers it to speak (when its driver can be triggered). */
1506
+ handOffFloor(from, target) {
1507
+ const fromName = from.AgentNames[0] ?? 'Another agent';
1508
+ target.RealtimeSession.SendContextNote?.(`[turn] ${fromName} handed the floor to you. Continue the conversation now.`);
1509
+ if (typeof target.RealtimeSession.RequestSpokenUpdate === 'function') {
1510
+ this.triggerMeetingSpeak(target);
1511
+ }
1512
+ }
1513
+ /**
1514
+ * Adjusts the turn-taking limits every room uses (the agent-to-agent loop cap, hand-off TTL, human-speech
1515
+ * hold). Omitted values keep their current setting. Call once at startup to tune.
1516
+ *
1517
+ * @param limits The limits to change.
1518
+ */
1519
+ ConfigureTurnLimits(limits) {
1520
+ this.roomCoordinator.ConfigureLimits(limits);
1521
+ }
1522
+ /**
1523
+ * A room's live turn-taking state: who holds the floor, whether a human is speaking, any pending hand-off,
1524
+ * the loop-cap progress, recent floor/backchannel/yield events, and who is seated. Read-only; the test bed
1525
+ * polls it. `null` when the room is unknown (no agent in it).
1526
+ *
1527
+ * @param roomKey The room (external connection id — a LiveKit room's name).
1528
+ * @returns The snapshot, or `null`.
1529
+ */
1530
+ GetRoomTurnSnapshot(roomKey) {
1531
+ const state = this.roomCoordinator.GetRoomState(roomKey);
1532
+ if (!state) {
1533
+ return null;
1534
+ }
1535
+ const agents = this.roomAgents(roomKey).map((a) => ({
1536
+ AgentSessionID: a.AgentSessionID,
1537
+ SessionBridgeID: a.SessionBridgeID,
1538
+ Names: a.AgentNames,
1539
+ TurnMode: a.TurnPolicy.Mode,
1540
+ Addressing: a.AddressingMode ?? 'Regex',
1541
+ FullDuplex: a.RealtimeSession.Capabilities?.FullDuplex === true,
1542
+ }));
1543
+ return { ...state, Agents: agents };
1544
+ }
1110
1545
  /**
1111
1546
  * Builds the per-session {@link TurnTakingPolicy} from the start params.
1112
1547
  *
1113
1548
  * @param params The session parameters.
1114
- * @returns The configured turn-taking policy.
1549
+ * @param fullDuplex Whether the session's model reports full-duplex capability (enables model-side addressing).
1550
+ * @returns The configured policy plus the addressing mode in effect and the model-side latch, when any.
1115
1551
  */
1116
- buildTurnPolicy(params) {
1552
+ buildTurnPolicy(params, fullDuplex) {
1553
+ let matcher = params.TurnMatcher;
1554
+ let mode = 'Regex';
1555
+ let modelSide;
1556
+ if (params.TurnAddressing !== undefined) {
1557
+ // The model's own judgement when it is full-duplex (and asked for); otherwise name matching, with
1558
+ // a caller-supplied matcher (e.g. a 1:1 call's always-addressed one) taking precedence as the fallback.
1559
+ const built = BuildAddressedMatcher(params.AgentNames ?? [], params.TurnAddressing, fullDuplex);
1560
+ mode = built.Mode;
1561
+ modelSide = built.ModelSide;
1562
+ matcher = built.Mode === 'ModelSide' ? built.Matcher : (params.TurnMatcher ?? built.Matcher);
1563
+ }
1117
1564
  const config = {
1118
1565
  Mode: params.TurnMode ?? 'Passive',
1119
- Matcher: params.TurnMatcher,
1566
+ Matcher: matcher,
1120
1567
  Scorer: params.TurnScorer,
1121
1568
  ...(params.TurnTuning ?? {}),
1122
1569
  };
1123
- return new TurnTakingPolicy(config);
1570
+ return { Policy: new TurnTakingPolicy(config), Mode: mode, ModelSide: modelSide };
1124
1571
  }
1125
1572
  /**
1126
1573
  * Retroactively switches an already-running session into **meeting mode** (auto-response off +
@@ -1214,8 +1661,8 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
1214
1661
  * @param active The freshly connected session.
1215
1662
  */
1216
1663
  electTranscriptScribe(active) {
1217
- if (!this.transcriptSink || !active.RoomKey) {
1218
- return;
1664
+ if (active.TranscriptSink || !this.transcriptSink || !active.RoomKey) {
1665
+ return; // a session with its own sink never takes part in the room's scribe election
1219
1666
  }
1220
1667
  const roomKey = active.RoomKey.toLowerCase();
1221
1668
  if (!this.roomScribes.has(roomKey)) {
@@ -1259,7 +1706,8 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
1259
1706
  * @param t The final transcript line.
1260
1707
  */
1261
1708
  emitTranscriptLine(active, t) {
1262
- if (!active.IsTranscriptScribe || !this.transcriptSink || !active.RoomKey) {
1709
+ const sink = active.TranscriptSink ?? (active.IsTranscriptScribe ? this.transcriptSink : undefined);
1710
+ if (!sink || !active.RoomKey) {
1263
1711
  return;
1264
1712
  }
1265
1713
  const text = (t.Text ?? '').trim();
@@ -1267,7 +1715,7 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
1267
1715
  return;
1268
1716
  }
1269
1717
  const isAgentSpeech = t.Role === 'assistant';
1270
- void Promise.resolve(this.transcriptSink({
1718
+ void Promise.resolve(sink({
1271
1719
  RoomKey: active.RoomKey,
1272
1720
  AgentSessionID: active.AgentSessionID,
1273
1721
  AgentID: active.AgentID,
@@ -1390,11 +1838,82 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
1390
1838
  return;
1391
1839
  }
1392
1840
  this.staleSweepTimer = setInterval(() => {
1393
- void this.SweepStaleSessions().catch((err) => LogError(`[AIBridgeEngine] stale sweep tick failed: ${err instanceof Error ? err.message : String(err)}`));
1841
+ void this.SweepStaleSessions()
1842
+ .then(() => this.HeartbeatLiveSessions())
1843
+ .catch((err) => LogError(`[AIBridgeEngine] stale sweep tick failed: ${err instanceof Error ? err.message : String(err)}`));
1394
1844
  }, intervalMs);
1395
1845
  // Don't keep the process alive solely for the sweep (Node-only; guarded for non-Node hosts).
1396
1846
  this.staleSweepTimer?.unref?.();
1397
1847
  }
1848
+ /**
1849
+ * Refreshes `LastActiveAt` on the agent-session row of every live bridge that has not been touched for
1850
+ * {@link SESSION_HEARTBEAT_INTERVAL_MS}. The host session janitor closes sessions idle past its threshold; a
1851
+ * long phone call writes nothing else to the row, so without this it would be closed (and its run finalized)
1852
+ * mid-call. Tolerant: a failed write is logged and the rest are still touched.
1853
+ *
1854
+ * @param nowMs Current epoch-ms (injectable for tests).
1855
+ * @returns The number of rows refreshed.
1856
+ */
1857
+ async HeartbeatLiveSessions(nowMs = Date.now()) {
1858
+ let touched = 0;
1859
+ for (const active of this.activeSessions.values()) {
1860
+ if (nowMs - active.LastSessionHeartbeatMs < SESSION_HEARTBEAT_INTERVAL_MS) {
1861
+ continue;
1862
+ }
1863
+ active.LastSessionHeartbeatMs = nowMs;
1864
+ if (await this.touchAgentSession(active)) {
1865
+ touched++;
1866
+ }
1867
+ }
1868
+ return touched;
1869
+ }
1870
+ /** Writes `LastActiveAt = now` on the session's agent-session row. Returns whether it saved. */
1871
+ async touchAgentSession(active) {
1872
+ const provider = active.MetadataProvider;
1873
+ if (!provider || !active.AgentSessionID) {
1874
+ return false;
1875
+ }
1876
+ try {
1877
+ const row = await provider.GetEntityObject(AGENT_SESSION_ENTITY, active.ContextUser);
1878
+ if (!(await row.Load(active.AgentSessionID))) {
1879
+ return false;
1880
+ }
1881
+ row.LastActiveAt = new Date();
1882
+ if (await row.Save()) {
1883
+ return true;
1884
+ }
1885
+ LogError(`[AIBridgeEngine] session heartbeat save failed for ${active.AgentSessionID}: ${row.LatestResult?.CompleteMessage ?? 'unknown error'}`);
1886
+ }
1887
+ catch (err) {
1888
+ LogError(`[AIBridgeEngine] session heartbeat failed for ${active.AgentSessionID}: ${err instanceof Error ? err.message : String(err)}`);
1889
+ }
1890
+ return false;
1891
+ }
1892
+ /**
1893
+ * Reconciles prior-boot orphans ({@link ReconcileOrphans}) once now and then every
1894
+ * {@link ORPHAN_RECONCILE_INTERVAL_MS}. Idempotent — a no-op while already scheduled. The timer is `unref`'d.
1895
+ *
1896
+ * @param contextUser The user the reconciliation writes run as.
1897
+ * @param provider The metadata provider for the reads/writes.
1898
+ */
1899
+ StartOrphanReconciliation(contextUser, provider, intervalMs = ORPHAN_RECONCILE_INTERVAL_MS) {
1900
+ if (this.orphanReconcileTimer) {
1901
+ return;
1902
+ }
1903
+ const tick = () => {
1904
+ void this.ReconcileOrphans(contextUser, provider).catch((err) => LogError(`[AIBridgeEngine] orphan reconciliation failed: ${err instanceof Error ? err.message : String(err)}`));
1905
+ };
1906
+ tick();
1907
+ this.orphanReconcileTimer = setInterval(tick, intervalMs);
1908
+ this.orphanReconcileTimer?.unref?.();
1909
+ }
1910
+ /** Cancels the periodic orphan reconciliation, if running. */
1911
+ StopOrphanReconciliation() {
1912
+ if (this.orphanReconcileTimer) {
1913
+ clearInterval(this.orphanReconcileTimer);
1914
+ this.orphanReconcileTimer = undefined;
1915
+ }
1916
+ }
1398
1917
  /** Cancels the self-scheduled stale-session sweep, if running. */
1399
1918
  StopStaleSessionSweep() {
1400
1919
  if (this.staleSweepTimer) {
@@ -1525,7 +2044,7 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
1525
2044
  * @returns The saved bridge row.
1526
2045
  * @throws When the row cannot be created (no metadata provider, or save failure).
1527
2046
  */
1528
- async createBridgeRow(params) {
2047
+ async createBridgeRow(params, addressingMode) {
1529
2048
  const provider = params.MetadataProvider;
1530
2049
  if (!provider) {
1531
2050
  throw new Error('AIBridgeEngine.StartBridgeSession requires a MetadataProvider.');
@@ -1537,6 +2056,7 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
1537
2056
  row.Direction = params.Direction ?? 'Outbound';
1538
2057
  row.JoinMethod = params.JoinMethod ?? 'OnDemand';
1539
2058
  row.TurnMode = params.TurnMode ?? 'Passive';
2059
+ row.TurnAddressing = addressingMode ?? 'Regex';
1540
2060
  row.Address = params.Address;
1541
2061
  row.Status = 'Pending';
1542
2062
  row.HostInstanceID = this.hostIdentity.GetHostInstanceID();
@@ -1582,6 +2102,7 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
1582
2102
  clearTimeout(active.LeaveGraceTimer);
1583
2103
  active.LeaveGraceTimer = undefined;
1584
2104
  }
2105
+ active.DtmfCoalescer?.Dispose();
1585
2106
  // Hand the transcript scribe role to another live session in the room (if this was the scribe), so a
1586
2107
  // multi-agent room keeps recording after the first agent leaves. Done before the active map removal.
1587
2108
  this.releaseTranscriptScribe(active);