@memberjunction/ai-bridge-server 6.2.0-edge.2 → 6.2.0-edge.4
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/README.md +86 -12
- package/dist/ai-bridge-engine.d.ts +436 -38
- package/dist/ai-bridge-engine.d.ts.map +1 -1
- package/dist/ai-bridge-engine.js +878 -84
- package/dist/ai-bridge-engine.js.map +1 -1
- package/dist/bridge-prior-transcript.d.ts +39 -0
- package/dist/bridge-prior-transcript.d.ts.map +1 -0
- package/dist/bridge-prior-transcript.js +56 -0
- package/dist/bridge-prior-transcript.js.map +1 -0
- package/dist/calendar-watcher.d.ts.map +1 -1
- package/dist/calendar-watcher.js +1 -0
- package/dist/calendar-watcher.js.map +1 -1
- package/dist/dtmf-coalescer.d.ts +32 -0
- package/dist/dtmf-coalescer.d.ts.map +1 -0
- package/dist/dtmf-coalescer.js +60 -0
- package/dist/dtmf-coalescer.js.map +1 -0
- package/dist/full-duplex-turn-gate.d.ts +155 -0
- package/dist/full-duplex-turn-gate.d.ts.map +1 -0
- package/dist/full-duplex-turn-gate.js +229 -0
- package/dist/full-duplex-turn-gate.js.map +1 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -1
- package/dist/loopback-bridge.d.ts +33 -1
- package/dist/loopback-bridge.d.ts.map +1 -1
- package/dist/loopback-bridge.js +39 -0
- package/dist/loopback-bridge.js.map +1 -1
- package/dist/multi-agent-room-coordinator.d.ts +226 -24
- package/dist/multi-agent-room-coordinator.d.ts.map +1 -1
- package/dist/multi-agent-room-coordinator.js +376 -39
- package/dist/multi-agent-room-coordinator.js.map +1 -1
- package/package.json +6 -6
package/dist/ai-bridge-engine.js
CHANGED
|
@@ -5,9 +5,16 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
|
|
|
5
5
|
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
6
|
};
|
|
7
7
|
import { LogError, LogStatus, LogStatusEx, RunView, RegisterForStartup, } from '@memberjunction/core';
|
|
8
|
+
import { performance } from 'node:perf_hooks';
|
|
9
|
+
import { hostname } from 'node:os';
|
|
10
|
+
import { randomUUID } from 'node:crypto';
|
|
8
11
|
import { BaseSingleton, MJGlobal, EscapeSQLString } from '@memberjunction/global';
|
|
9
|
-
import {
|
|
12
|
+
import { Fmp4AudioSeconds, InboundVideoRateOf, InboundVideoStreamsOf, IsAgentParticipantIdentity, ReadFmp4Init, UnnamedVideoSourceLabel, VideoSourceEndedNote, VideoSourceSeenNote, } from '@memberjunction/ai';
|
|
13
|
+
import { AIBridgeEngineBase, BaseRealtimeBridge, BaseTelephonyBridge, TurnTakingPolicy, BridgeNativeSdkRegistry, BuildAddressedMatcher, ParseTurnTakingToolCall, IsTurnTakingTool, MODEL_SIDE_TURN_TAKING_FRAMING, } from '@memberjunction/ai-bridge-base';
|
|
10
14
|
import { MultiAgentRoomCoordinator } from './multi-agent-room-coordinator.js';
|
|
15
|
+
import { FullDuplexTurnGate, HumanSpeechDetector } from './full-duplex-turn-gate.js';
|
|
16
|
+
import { DtmfCoalescer } from './dtmf-coalescer.js';
|
|
17
|
+
import { AppendTranscriptTurn, BuildPriorTranscript } from './bridge-prior-transcript.js';
|
|
11
18
|
/**
|
|
12
19
|
* Entity names — centralised so the `MJ:`-prefix convention is applied in exactly one place.
|
|
13
20
|
*/
|
|
@@ -51,31 +58,52 @@ const ROOM_AGENT_TURN_HARD_CEILING = 30;
|
|
|
51
58
|
const SESSION_IDLE_TTL_MS = 10 * 60 * 1000; // 10 min with no transcript activity
|
|
52
59
|
const SESSION_MAX_DURATION_MS = 4 * 60 * 60 * 1000; // 4 h absolute cap
|
|
53
60
|
const STALE_SWEEP_INTERVAL_MS = 60 * 1000; // sweep cadence when self-scheduled
|
|
61
|
+
/**
|
|
62
|
+
* How often a live session's `MJ: AI Agent Sessions.LastActiveAt` is refreshed. The host session janitor closes any
|
|
63
|
+
* session idle past its threshold (15 min by default); a phone call that never touches the row would be closed
|
|
64
|
+
* mid-call, finalizing its run while the caller is still talking. Well under that threshold.
|
|
65
|
+
*/
|
|
66
|
+
const SESSION_HEARTBEAT_INTERVAL_MS = 5 * 60 * 1000;
|
|
67
|
+
/** How often prior-boot orphans are reconciled after the one-off pass at startup. */
|
|
68
|
+
const ORPHAN_RECONCILE_INTERVAL_MS = 10 * 60 * 1000;
|
|
69
|
+
/** How many times a dropped model session is re-opened before the call is ended. Never a loop. */
|
|
70
|
+
const MAX_MODEL_RECOVERY_ATTEMPTS = 1;
|
|
71
|
+
/** Said to the caller, at the carrier, when the model session is lost and cannot be recovered. */
|
|
72
|
+
const MODEL_LOSS_CALLER_MESSAGE = 'We are sorry, we are having technical difficulties and cannot continue this call. Please try again later. Goodbye.';
|
|
73
|
+
const AGENT_SESSION_ENTITY = 'MJ: AI Agent Sessions';
|
|
54
74
|
/** Context note injected into a re-gated agent so it knows it's now in a meeting (its prompt predates it). */
|
|
55
75
|
const MEETING_REGATE_CONTEXT_NOTE = 'You are now in a multi-party meeting with other people and agents. Stop responding to everything you ' +
|
|
56
76
|
'hear — listen, and speak only when you are addressed by name or the conversation clearly needs your ' +
|
|
57
77
|
'expertise. Never talk over others, and keep your replies brief.';
|
|
78
|
+
/** What follows an instance's prefix in a `HostInstanceID`: a process id, then a boot id. */
|
|
79
|
+
const PID_AND_BOOT_ID = /^\d+:[^:]+$/;
|
|
58
80
|
/**
|
|
59
|
-
*
|
|
60
|
-
*
|
|
61
|
-
*
|
|
62
|
-
*
|
|
81
|
+
* The {@link IHostInstanceIdentity} the engine uses until the host injects one: this process alone, on this host.
|
|
82
|
+
* Its id is `hostname:pid-<pid>:<pid>:<bootId>`, the shape MJServer gives a process that serves no port, so
|
|
83
|
+
* {@link DefaultHostInstanceIdentity.IsPriorBoot} matches only an earlier process that had this pid on this host,
|
|
84
|
+
* which has ended. It never matches another live process's bridges. A host whose instance outlives a restart (MJServer:
|
|
85
|
+
* a host and a port) injects its own identity, so that its reconcile closes what an earlier boot left.
|
|
63
86
|
*/
|
|
64
87
|
export class DefaultHostInstanceIdentity {
|
|
65
88
|
constructor() {
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
const bootId = Math.random().toString(36).slice(2) + Date.now().toString(36);
|
|
69
|
-
this.hostName = 'unknown-host';
|
|
70
|
-
this.instanceId = `${this.hostName}:${pid}:${bootId}`;
|
|
89
|
+
this.instancePrefix = `${hostname()}:pid-${process.pid}:`;
|
|
90
|
+
this.instanceId = `${this.instancePrefix}${process.pid}:${randomUUID()}`;
|
|
71
91
|
}
|
|
72
92
|
/** @inheritdoc */
|
|
73
93
|
GetHostInstanceID() {
|
|
74
94
|
return this.instanceId;
|
|
75
95
|
}
|
|
76
96
|
/** @inheritdoc */
|
|
77
|
-
|
|
78
|
-
return
|
|
97
|
+
GetInstancePrefix() {
|
|
98
|
+
return this.instancePrefix;
|
|
99
|
+
}
|
|
100
|
+
/** @inheritdoc */
|
|
101
|
+
IsPriorBoot(hostInstanceID) {
|
|
102
|
+
if (!hostInstanceID || hostInstanceID === this.instanceId) {
|
|
103
|
+
return false;
|
|
104
|
+
}
|
|
105
|
+
const prefix = this.instancePrefix;
|
|
106
|
+
return hostInstanceID.startsWith(prefix) && PID_AND_BOOT_ID.test(hostInstanceID.slice(prefix.length));
|
|
79
107
|
}
|
|
80
108
|
}
|
|
81
109
|
/**
|
|
@@ -101,8 +129,8 @@ export class DefaultHostInstanceIdentity {
|
|
|
101
129
|
* `AIAgentSessionBridgeParticipant` rows.
|
|
102
130
|
* - **Turn-taking integration** — holds a {@link TurnTakingPolicy} per session and feeds diarized
|
|
103
131
|
* transcript segments through it, acting on the decision (Speak / PostToChat / Silent).
|
|
104
|
-
* - **Janitor scaffold** — {@link ReconcileOrphans} force-closes Connected bridges left by
|
|
105
|
-
*
|
|
132
|
+
* - **Janitor scaffold** — {@link ReconcileOrphans} force-closes Connected bridges left by an earlier
|
|
133
|
+
* boot of this instance (see {@link IHostInstanceIdentity}), following the `SessionJanitor` shape.
|
|
106
134
|
*
|
|
107
135
|
* The engine never constructs the realtime model: the {@link IRealtimeSession} is injected via
|
|
108
136
|
* {@link StartBridgeSessionParams}, keeping the only coupling the transport seam itself and making
|
|
@@ -120,8 +148,12 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
120
148
|
this.floorMaxHoldMs = FLOOR_MAX_HOLD_MS;
|
|
121
149
|
/** roomKey (lowercased) → the bridge id of that room's current transcript scribe. Election dedup. */
|
|
122
150
|
this.roomScribes = new Map();
|
|
123
|
-
/**
|
|
151
|
+
/**
|
|
152
|
+
* Diagnostic: the bridges (by `SessionBridgeID`) that have logged their first inbound media frame. An ending bridge
|
|
153
|
+
* adds no id, and {@link StopBridgeSession} drops its id, so a long-running host keeps only its live bridges.
|
|
154
|
+
*/
|
|
124
155
|
this.diagInbound = new Set();
|
|
156
|
+
/** Diagnostic: the bridges that have logged the agent's first outbound audio, kept the same way as {@link diagInbound}. */
|
|
125
157
|
this.diagOutbound = new Set();
|
|
126
158
|
/** In-memory registry of bridged sessions this process currently hosts, keyed by bridge id (lowercased). */
|
|
127
159
|
this.activeSessions = new Map();
|
|
@@ -169,7 +201,11 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
169
201
|
/**
|
|
170
202
|
* Deferred-startup entry point (per {@link IStartupSink}). Warms the ONE composed base cache by
|
|
171
203
|
* delegating to {@link AIBridgeEngineBase.Config}; mirrors `AIEngine.HandleStartup`. No double
|
|
172
|
-
* load — there is only the base's cache to warm.
|
|
204
|
+
* load — there is only the base's cache to warm. Then starts the same-process stale-session sweep.
|
|
205
|
+
*
|
|
206
|
+
* It does not start the orphan reconcile. The host starts that ({@link StartOrphanReconciliation}) once it owns
|
|
207
|
+
* its instance: the deferred startup can run before MJServer listens on its port, while another live MJAPI may
|
|
208
|
+
* still hold that port, and a reconcile then would close that MJAPI's bridges as this instance's orphans.
|
|
173
209
|
*
|
|
174
210
|
* @param contextUser The boot/system user context.
|
|
175
211
|
* @param provider Optional metadata provider override (multi-provider scenarios).
|
|
@@ -286,11 +322,12 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
286
322
|
return this.Base.DefaultChannelsForProvider(providerId);
|
|
287
323
|
}
|
|
288
324
|
/**
|
|
289
|
-
* Injects the
|
|
290
|
-
*
|
|
291
|
-
*
|
|
325
|
+
* Injects the identity of the server instance hosting this engine ({@link IHostInstanceIdentity}): the engine
|
|
326
|
+
* stamps it into every bridge row it creates and reconciles orphans by it. Call it once at boot, before anything
|
|
327
|
+
* can start a bridge. MJServer's `Serve` passes the identity its agent-session rows carry, right after it sets its
|
|
328
|
+
* port. Until then the engine uses a {@link DefaultHostInstanceIdentity}.
|
|
292
329
|
*
|
|
293
|
-
* @param identity The identity
|
|
330
|
+
* @param identity The identity to use.
|
|
294
331
|
*/
|
|
295
332
|
SetHostInstanceIdentity(identity) {
|
|
296
333
|
this.hostIdentity = identity;
|
|
@@ -366,7 +403,9 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
366
403
|
* @throws When the driver cannot be resolved or `Connect` fails (the row is stamped `Failed`).
|
|
367
404
|
*/
|
|
368
405
|
async StartBridgeSession(params) {
|
|
369
|
-
const
|
|
406
|
+
const fullDuplex = params.FullDuplex ?? params.RealtimeSession.Capabilities?.FullDuplex === true;
|
|
407
|
+
const turn = this.buildTurnPolicy(params, fullDuplex);
|
|
408
|
+
const bridgeRow = await this.createBridgeRow(params, turn.Mode);
|
|
370
409
|
try {
|
|
371
410
|
// Resolve the driver inside the try so a resolution failure still stamps the row Failed
|
|
372
411
|
// (the row already exists at this point — it must not be left dangling as Pending).
|
|
@@ -383,14 +422,16 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
383
422
|
bridgeRow.BotParticipantID = result.BotParticipantId;
|
|
384
423
|
bridgeRow.ConnectedAt = new Date();
|
|
385
424
|
await this.transitionStatus(bridgeRow, 'Connected', params);
|
|
386
|
-
const turnPolicy = this.buildTurnPolicy(params);
|
|
387
425
|
const active = {
|
|
388
426
|
SessionBridgeID: bridgeRow.ID,
|
|
389
427
|
AgentSessionID: params.AgentSessionID,
|
|
390
428
|
AgentID: params.AgentID,
|
|
391
429
|
Bridge: driver,
|
|
392
430
|
RealtimeSession: params.RealtimeSession,
|
|
393
|
-
TurnPolicy:
|
|
431
|
+
TurnPolicy: turn.Policy,
|
|
432
|
+
AddressingMode: turn.Mode,
|
|
433
|
+
ModelSideMatcher: turn.ModelSide,
|
|
434
|
+
FullDuplex: fullDuplex,
|
|
394
435
|
DisableAutoResponse: params.DisableAutoResponse === true,
|
|
395
436
|
HasSeenHuman: false,
|
|
396
437
|
RoomKey: result.ExternalConnectionId,
|
|
@@ -409,6 +450,17 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
409
450
|
MetadataProvider: params.MetadataProvider,
|
|
410
451
|
ChannelHost: params.ChannelHost,
|
|
411
452
|
ServerChannelTools: [],
|
|
453
|
+
TranscriptSink: params.TranscriptSink,
|
|
454
|
+
OnBargeIn: params.OnBargeIn,
|
|
455
|
+
RecoverRealtimeSession: params.RecoverRealtimeSession,
|
|
456
|
+
RecoverRealtimeSessionWithoutAvatar: params.RecoverRealtimeSessionWithoutAvatar,
|
|
457
|
+
OnSessionEnded: params.OnSessionEnded,
|
|
458
|
+
TranscriptTail: [],
|
|
459
|
+
ModelRecoveryAttempts: 0,
|
|
460
|
+
ModelRecovering: false,
|
|
461
|
+
Ending: false,
|
|
462
|
+
LastSessionHeartbeatMs: Date.now(),
|
|
463
|
+
SeenVideoSources: new Map(),
|
|
412
464
|
};
|
|
413
465
|
this.electTranscriptScribe(active);
|
|
414
466
|
// Join the room's floor-control roster (keyed on the shared room). For a single-agent room this
|
|
@@ -421,8 +473,11 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
421
473
|
this.wireParticipantTracking(active);
|
|
422
474
|
this.wireTelephonyLifecycle(active);
|
|
423
475
|
this.wireTurnTaking(active);
|
|
476
|
+
this.wireFullDuplexTurnGate(active, params);
|
|
424
477
|
await this.wireChannelPlane(active);
|
|
478
|
+
this.wireTurnTakingTools(active);
|
|
425
479
|
this.activeSessions.set(bridgeRow.ID.toLowerCase(), active);
|
|
480
|
+
this.announceTurnTaking(active.RoomKey); // after registration, so the newcomer is counted among the room's agents
|
|
426
481
|
LogStatus(`[AIBridgeEngine] Bridge session ${bridgeRow.ID} connected via ${params.Provider.Name}`);
|
|
427
482
|
return active;
|
|
428
483
|
}
|
|
@@ -446,13 +501,29 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
446
501
|
const key = sessionBridgeID.toLowerCase();
|
|
447
502
|
const active = this.activeSessions.get(key);
|
|
448
503
|
if (active) {
|
|
504
|
+
active.Ending = true; // ignore model-loss signals that race the teardown
|
|
449
505
|
await this.disconnectDriver(active, reason);
|
|
450
506
|
this.activeSessions.delete(key);
|
|
451
|
-
|
|
507
|
+
// Forget its first-frame diagnostics. A frame that arrives after this can't add the id back: an ending bridge
|
|
508
|
+
// records none.
|
|
509
|
+
this.diagInbound.delete(active.SessionBridgeID);
|
|
510
|
+
this.diagOutbound.delete(active.SessionBridgeID);
|
|
511
|
+
const done = await this.markBridgeDisconnected(sessionBridgeID, reason, active.ContextUser ?? contextUser, active.MetadataProvider ?? provider);
|
|
512
|
+
await this.runSessionEndedHook(active, reason);
|
|
513
|
+
return done;
|
|
452
514
|
}
|
|
453
515
|
// Not held by this process — still reconcile the durable row (janitor / cross-host close).
|
|
454
516
|
return this.markBridgeDisconnected(sessionBridgeID, reason, contextUser, provider);
|
|
455
517
|
}
|
|
518
|
+
/** Runs the host's end-of-session hook. A failure is logged — teardown bookkeeping must not be blocked by it. */
|
|
519
|
+
async runSessionEndedHook(active, reason) {
|
|
520
|
+
try {
|
|
521
|
+
await active.OnSessionEnded?.(reason);
|
|
522
|
+
}
|
|
523
|
+
catch (err) {
|
|
524
|
+
LogError(`[AIBridgeEngine] session-ended hook failed for bridge ${active.SessionBridgeID}: ${err instanceof Error ? err.message : String(err)}`);
|
|
525
|
+
}
|
|
526
|
+
}
|
|
456
527
|
// ──────────────────────────────────────────────────────────────────────────────
|
|
457
528
|
// THE TRANSPORT SEAM — the deferred "unified-transport track" completed here.
|
|
458
529
|
// ──────────────────────────────────────────────────────────────────────────────
|
|
@@ -463,9 +534,11 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
463
534
|
* that pipe.
|
|
464
535
|
*
|
|
465
536
|
* Two hooks, one per direction:
|
|
466
|
-
* - **Inbound** (`bridge.OnMedia` → `session.SendInput`): what the agent HEARS
|
|
467
|
-
* {@link BridgeMediaFrame} from the endpoint is unwrapped to its raw `ArrayBuffer` payload and
|
|
468
|
-
* streamed straight to the model.
|
|
537
|
+
* - **Inbound** (`bridge.OnMedia` → `session.SendInput`): what the agent HEARS (and, for a video model, SEES).
|
|
538
|
+
* Each inbound {@link BridgeMediaFrame} from the endpoint is unwrapped to its raw `ArrayBuffer` payload and
|
|
539
|
+
* streamed straight to the model. Camera and screen frames go only to a session that declares inbound video; the
|
|
540
|
+
* first frame of a source new to the model session is preceded by a note naming it, and the end of a source the
|
|
541
|
+
* model saw is followed by one (see {@link VideoSourceSeenNote}, {@link VideoSourceEndedNote}).
|
|
469
542
|
* - **Outbound** (`session.OnOutput` → `bridge.SendMedia`): what the agent SAYS. Each model
|
|
470
543
|
* output `ArrayBuffer` is wrapped in an outbound audio {@link BridgeMediaFrame} and sent into
|
|
471
544
|
* the meeting/call.
|
|
@@ -476,31 +549,18 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
476
549
|
* @param active The live bridged session whose driver and realtime session are wired together.
|
|
477
550
|
*/
|
|
478
551
|
wireTransportSeam(active) {
|
|
479
|
-
const { Bridge
|
|
480
|
-
|
|
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
|
-
});
|
|
552
|
+
const { Bridge } = active;
|
|
553
|
+
this.wireModelSession(active);
|
|
497
554
|
if (Bridge.Features.DetachedMediaPlane) {
|
|
498
555
|
// Detached media plane (e.g. OpenAISipBridge): the carrier/platform terminates the media leg
|
|
499
556
|
// directly with the AI provider. MJ is NOT in the media relay path.
|
|
500
557
|
return;
|
|
501
558
|
}
|
|
502
|
-
// Inbound: endpoint media → the agent hears (and, for a video model, SEES) it. The frame's
|
|
503
|
-
//
|
|
559
|
+
// Inbound: endpoint media → the agent hears (and, for a video model, SEES) it. The frame's Track tags the
|
|
560
|
+
// plane: a camera (`video-in`) or a shared screen (`screen-in`) reaches the model as a `video` frame. Only a
|
|
561
|
+
// session that declares inbound video gets one; any other driver would read the image as audio. Always read
|
|
562
|
+
// `active.RealtimeSession` — a recovered session replaces it mid-call.
|
|
563
|
+
let videoDropNoted = false;
|
|
504
564
|
Bridge.OnMedia((frame) => {
|
|
505
565
|
active.LastActivityMs = Date.now();
|
|
506
566
|
// DIARIZATION: the inbound frame carries the speaking participant's identity (when the provider
|
|
@@ -510,34 +570,206 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
510
570
|
if (frame.Track === 'audio-in' && frame.SpeakerLabel) {
|
|
511
571
|
active.LastInboundSpeaker = frame.SpeakerLabel;
|
|
512
572
|
}
|
|
573
|
+
const kind = mediaKindOf(frame.Track);
|
|
574
|
+
if (kind === 'video' && InboundVideoStreamsOf(active.RealtimeSession.Capabilities) === 0) {
|
|
575
|
+
if (!videoDropNoted) {
|
|
576
|
+
videoDropNoted = true;
|
|
577
|
+
LogStatusEx({ message: `[AIBridgeEngine] ${frame.Track} frames are not sent to bridge ${active.SessionBridgeID}: its realtime session does not take inbound video.`, verboseOnly: true });
|
|
578
|
+
}
|
|
579
|
+
return;
|
|
580
|
+
}
|
|
513
581
|
const chunk = this.frameToArrayBuffer(frame);
|
|
514
|
-
|
|
515
|
-
|
|
582
|
+
this.observeInboundHumanSpeech(active, frame, chunk);
|
|
583
|
+
if (chunk && !active.ModelRecovering) {
|
|
584
|
+
if (!active.Ending && !this.diagInbound.has(active.SessionBridgeID)) {
|
|
516
585
|
this.diagInbound.add(active.SessionBridgeID);
|
|
517
|
-
LogStatusEx({ message: `[AIBridgeEngine][diag] FIRST inbound media frame reached the agent (bridge ${active.SessionBridgeID}, track=${frame.Track}).
|
|
586
|
+
LogStatusEx({ message: `[AIBridgeEngine][diag] FIRST inbound media frame reached the agent (bridge ${active.SessionBridgeID}, track=${frame.Track}). ${firstInboundFrameMeaning(frame.Track)}`, verboseOnly: true });
|
|
518
587
|
}
|
|
519
|
-
|
|
588
|
+
if (kind === 'video') {
|
|
589
|
+
this.tellModelVideoSourceSeen(active, frame);
|
|
590
|
+
}
|
|
591
|
+
active.RealtimeSession.SendInput({
|
|
592
|
+
Data: chunk,
|
|
593
|
+
Kind: kind,
|
|
594
|
+
MimeType: frame.MimeType,
|
|
595
|
+
TimestampMs: frame.TimestampMs,
|
|
596
|
+
});
|
|
520
597
|
}
|
|
521
598
|
});
|
|
599
|
+
Bridge.OnVideoSourceEnded((source) => this.tellModelVideoSourceEnded(active, source));
|
|
600
|
+
Bridge.OnAvatarUnavailable((reason) => void this.replaceModelSessionWithoutAvatar(active, reason));
|
|
601
|
+
}
|
|
602
|
+
/**
|
|
603
|
+
* Tells the model what it can now see, right before the first frame of a camera or screen new to the current model
|
|
604
|
+
* session: the first source, the next one after a switch, a source seen again after it ended, or a replacement
|
|
605
|
+
* session's first frame. Records the source, so its end is reported. A frame without a `SourceID` is not tracked.
|
|
606
|
+
* Reads `active.RealtimeSession` each time: a recovered session replaces it.
|
|
607
|
+
*
|
|
608
|
+
* @param active The live bridged session.
|
|
609
|
+
* @param frame The camera or screen frame about to be sent.
|
|
610
|
+
*/
|
|
611
|
+
tellModelVideoSourceSeen(active, frame) {
|
|
612
|
+
if (!frame.SourceID || active.SeenVideoSources.has(frame.SourceID)) {
|
|
613
|
+
return;
|
|
614
|
+
}
|
|
615
|
+
const label = frame.SourceLabel ?? fallbackVideoSourceLabel(frame.Track);
|
|
616
|
+
active.SeenVideoSources.set(frame.SourceID, label);
|
|
617
|
+
active.RealtimeSession.SendContextNote?.(VideoSourceSeenNote(label));
|
|
618
|
+
}
|
|
619
|
+
/**
|
|
620
|
+
* Tells the model it can no longer see a camera or screen whose frames reached it (the person stopped letting agents
|
|
621
|
+
* see them, left, stopped sharing or turned the camera off, or the view moved to another source), so it stops
|
|
622
|
+
* describing the last frame as current. The note names the source as the model was told with its first frame, not by
|
|
623
|
+
* the label the driver reports at the end: the two differ when the person was renamed in between, or had no name when
|
|
624
|
+
* that first frame was read. A source the model never saw is ignored. Reads `active.RealtimeSession` each time: a
|
|
625
|
+
* recovered session replaces it.
|
|
626
|
+
*
|
|
627
|
+
* @param active The live bridged session.
|
|
628
|
+
* @param source The source that ended, as the driver reported it.
|
|
629
|
+
*/
|
|
630
|
+
tellModelVideoSourceEnded(active, source) {
|
|
631
|
+
const seenLabel = active.SeenVideoSources.get(source.SourceID);
|
|
632
|
+
if (seenLabel === undefined) {
|
|
633
|
+
return;
|
|
634
|
+
}
|
|
635
|
+
active.SeenVideoSources.delete(source.SourceID);
|
|
636
|
+
active.RealtimeSession.SendContextNote?.(VideoSourceEndedNote(seenLabel));
|
|
637
|
+
}
|
|
638
|
+
/**
|
|
639
|
+
* Wires everything that hangs off the MODEL session: barge-in, the lifecycle (drop) signals, and — unless the
|
|
640
|
+
* media plane is detached — the agent's outbound audio/video. Called at connect AND again for a replacement
|
|
641
|
+
* session after a recovery, so every handler checks it still belongs to the active session.
|
|
642
|
+
*
|
|
643
|
+
* @param active The live bridged session.
|
|
644
|
+
*/
|
|
645
|
+
wireModelSession(active) {
|
|
646
|
+
const { Bridge } = active;
|
|
647
|
+
const session = active.RealtimeSession;
|
|
648
|
+
// A replacement model session has seen no frames yet; the sources it sees are recorded afresh as they arrive.
|
|
649
|
+
active.SeenVideoSources.clear();
|
|
650
|
+
// Barge-in: on a TRUE interruption (the user speaks over the agent), the model stops generating —
|
|
651
|
+
// but the driver may still hold queued outbound audio that would keep playing. Flush it so the
|
|
652
|
+
// agent goes quiet immediately. Without this, interruption "doesn't work" on the bridge surface.
|
|
653
|
+
session.OnInterruption(() => this.handleBargeIn(active));
|
|
654
|
+
this.wireModelLifecycle(active, session);
|
|
655
|
+
if (Bridge.Features.DetachedMediaPlane) {
|
|
656
|
+
return;
|
|
657
|
+
}
|
|
522
658
|
// Outbound: the agent speaks → into the meeting/call.
|
|
523
|
-
|
|
659
|
+
session.OnOutput((chunk) => {
|
|
660
|
+
if (active.RealtimeSession !== session) {
|
|
661
|
+
return; // a stale (replaced) session
|
|
662
|
+
}
|
|
524
663
|
active.LastActivityMs = Date.now();
|
|
525
|
-
if (
|
|
664
|
+
if (active.LastUserSpeechEndMs !== undefined) {
|
|
665
|
+
const latencyMs = Math.round(performance.now() - active.LastUserSpeechEndMs);
|
|
666
|
+
active.LastUserSpeechEndMs = undefined;
|
|
667
|
+
LogStatusEx({
|
|
668
|
+
message: `[AIBridgeEngine][telemetry] transcript-to-next-audio latency: ${latencyMs}ms (bridge ${active.SessionBridgeID})`,
|
|
669
|
+
verboseOnly: true,
|
|
670
|
+
});
|
|
671
|
+
}
|
|
672
|
+
if (!active.Ending && !this.diagOutbound.has(active.SessionBridgeID)) {
|
|
526
673
|
this.diagOutbound.add(active.SessionBridgeID);
|
|
527
674
|
LogStatusEx({ message: `[AIBridgeEngine][diag] FIRST outbound audio from the agent (bridge ${active.SessionBridgeID}). The agent is SPEAKING into the room.`, verboseOnly: true });
|
|
528
675
|
}
|
|
676
|
+
const verdict = this.gateOutput(active, chunk.byteLength);
|
|
677
|
+
if (verdict !== 'Forward') {
|
|
678
|
+
if (verdict === 'Cut') {
|
|
679
|
+
Bridge.FlushOutboundMedia(); // the burst was just refused — drop audio already queued for it too
|
|
680
|
+
}
|
|
681
|
+
return;
|
|
682
|
+
}
|
|
529
683
|
const track = 'audio-out';
|
|
530
684
|
Bridge.SendMedia(track, this.arrayBufferToFrame(chunk, track));
|
|
531
685
|
});
|
|
532
|
-
// Outbound VIDEO: a video-capable session
|
|
533
|
-
// audio-only sessions don't implement
|
|
534
|
-
// gates the actual publish on its `VideoOut` capability.
|
|
535
|
-
|
|
686
|
+
// Outbound VIDEO: a video-capable session also emits typed frames (a live avatar's fragmented MP4, encoded
|
|
687
|
+
// chunks, images). Optional: audio-only sessions don't implement OnVideoFrame, so call it null-safely. The
|
|
688
|
+
// bridge driver gates the actual publish on its `VideoOut` capability.
|
|
689
|
+
session.OnVideoFrame?.((frame) => this.forwardVideoFrame(active, session, frame));
|
|
690
|
+
// The deprecated untyped video output, still forwarded as it was (bytes without a MIME type).
|
|
691
|
+
session.OnVideoOutput?.((chunk) => {
|
|
692
|
+
if (active.RealtimeSession !== session) {
|
|
693
|
+
return;
|
|
694
|
+
}
|
|
536
695
|
active.LastActivityMs = Date.now();
|
|
537
696
|
const track = 'video-out';
|
|
538
697
|
Bridge.SendMedia(track, this.arrayBufferToFrame(chunk, track));
|
|
539
698
|
});
|
|
540
699
|
}
|
|
700
|
+
/**
|
|
701
|
+
* Sends one frame of the agent's video to the bridge on `video-out`, with its MIME type so the driver can publish it
|
|
702
|
+
* (a fragmented MP4 piece as an avatar), and what the frame says about its video (see {@link frameVideoFacts}). In a
|
|
703
|
+
* full-duplex multi-agent room the frame passes the floor gate first.
|
|
704
|
+
*/
|
|
705
|
+
forwardVideoFrame(active, session, frame) {
|
|
706
|
+
if (active.RealtimeSession !== session) {
|
|
707
|
+
return; // a stale (replaced) session
|
|
708
|
+
}
|
|
709
|
+
active.LastActivityMs = Date.now();
|
|
710
|
+
const verdict = this.gateVideoFrame(active, frame);
|
|
711
|
+
if (verdict !== 'Forward') {
|
|
712
|
+
if (verdict === 'Cut') {
|
|
713
|
+
active.Bridge.FlushOutboundMedia(); // the burst was just refused — drop what is queued for it, voice and face
|
|
714
|
+
}
|
|
715
|
+
return;
|
|
716
|
+
}
|
|
717
|
+
active.Bridge.SendMedia('video-out', {
|
|
718
|
+
Track: 'video-out',
|
|
719
|
+
Bytes: frame.Data,
|
|
720
|
+
MimeType: frame.MimeType,
|
|
721
|
+
TimestampMs: Date.now(),
|
|
722
|
+
...frameVideoFacts(frame, active.AvatarInit),
|
|
723
|
+
});
|
|
724
|
+
}
|
|
725
|
+
/**
|
|
726
|
+
* The floor gate's verdict on one video frame. An fMP4 piece carries the voice on its audio track, so a fragment is
|
|
727
|
+
* counted by its audio's duration: that is how long the agent speaks. A fragment its driver marks `Idle` (the face an
|
|
728
|
+
* avatar shows between answers) counts as no speech, whatever its audio track holds; so does one with video only.
|
|
729
|
+
* Neither starts a burst or takes the floor (see {@link FullDuplexTurnGate.OnOutputDuration}). An init segment
|
|
730
|
+
* carries no speech: it is remembered (its audio track's timescale times the fragments) and passes. An encoded chunk
|
|
731
|
+
* or an image carries no voice (that comes through `OnOutput`, which is gated) and passes.
|
|
732
|
+
*/
|
|
733
|
+
gateVideoFrame(active, frame) {
|
|
734
|
+
if (frame.Kind !== 'fmp4') {
|
|
735
|
+
return 'Forward';
|
|
736
|
+
}
|
|
737
|
+
if (frame.Piece === 'init') {
|
|
738
|
+
active.AvatarInit = ReadFmp4Init(frame.Data) ?? active.AvatarInit;
|
|
739
|
+
return 'Forward';
|
|
740
|
+
}
|
|
741
|
+
const speechSeconds = frame.Idle || !active.AvatarInit ? 0 : (Fmp4AudioSeconds(frame.Data, active.AvatarInit) ?? 0);
|
|
742
|
+
return this.gateOutputDuration(active, speechSeconds * 1000);
|
|
743
|
+
}
|
|
744
|
+
/** A true barge-in: flush queued audio, drop stale room moderator state, free the floor, tell the host. */
|
|
745
|
+
handleBargeIn(active) {
|
|
746
|
+
active.LastUserSpeechEndMs = undefined;
|
|
747
|
+
if (this.diagOutbound.has(active.SessionBridgeID)) {
|
|
748
|
+
LogStatusEx({ message: `[AIBridgeEngine][diag] barge-in — flushing the agent's queued audio (bridge ${active.SessionBridgeID}).`, verboseOnly: true });
|
|
749
|
+
}
|
|
750
|
+
active.Bridge.FlushOutboundMedia();
|
|
751
|
+
// A human cut in → any moderator decision staged for the prior turn is now stale. Drop the queued
|
|
752
|
+
// speakers (the human's new turn will drive a fresh decision); also free the floor this agent held.
|
|
753
|
+
if (active.RoomKey) {
|
|
754
|
+
if (this.isHumanSpeaker(active.LastInboundSpeaker)) {
|
|
755
|
+
this.preemptForHuman(active.RoomKey); // a person cut in — every agent yields, not just this one
|
|
756
|
+
}
|
|
757
|
+
this.clearRoomModeratorState(active.RoomKey, false);
|
|
758
|
+
if (active.HoldsFloor) {
|
|
759
|
+
this.releaseRoomFloor(active);
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
this.notifyBargeIn(active);
|
|
763
|
+
}
|
|
764
|
+
/** Tells the host about a barge-in so it can drop now-stale narration (never delegated work). A hook failure is logged, never fatal. */
|
|
765
|
+
notifyBargeIn(active) {
|
|
766
|
+
try {
|
|
767
|
+
active.OnBargeIn?.();
|
|
768
|
+
}
|
|
769
|
+
catch (err) {
|
|
770
|
+
LogError(`[AIBridgeEngine] barge-in hook failed for bridge ${active.SessionBridgeID}: ${err instanceof Error ? err.message : String(err)}`);
|
|
771
|
+
}
|
|
772
|
+
}
|
|
541
773
|
/**
|
|
542
774
|
* Unwraps a {@link BridgeMediaFrame} to the raw `ArrayBuffer` the realtime session consumes,
|
|
543
775
|
* preferring the binary `Bytes` payload and decoding `Base64` when only that is present. Returns
|
|
@@ -624,6 +856,136 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
624
856
|
LogStatus(`[AIBridgeEngine] Telephony call ended for bridge ${active.SessionBridgeID} — stopping bridge session.`);
|
|
625
857
|
void this.StopBridgeSession(active.SessionBridgeID, 'HostEnded', active.ContextUser, active.MetadataProvider);
|
|
626
858
|
});
|
|
859
|
+
this.wireInboundDtmf(active, active.Bridge);
|
|
860
|
+
}
|
|
861
|
+
}
|
|
862
|
+
/**
|
|
863
|
+
* Routes the caller's keypad presses to the model as one short context note per burst ("the caller pressed
|
|
864
|
+
* 1234"). Capability-gated: a provider with DTMF off throws from `OnDTMF`, which just means no keypad input.
|
|
865
|
+
*/
|
|
866
|
+
wireInboundDtmf(active, bridge) {
|
|
867
|
+
const coalescer = new DtmfCoalescer((digits) => {
|
|
868
|
+
if (!active.Ending) {
|
|
869
|
+
active.RealtimeSession.SendContextNote?.(`[caller keypad] The caller pressed: ${digits}`);
|
|
870
|
+
}
|
|
871
|
+
});
|
|
872
|
+
try {
|
|
873
|
+
bridge.OnDTMF((digits) => coalescer.Push(digits));
|
|
874
|
+
active.DtmfCoalescer = coalescer;
|
|
875
|
+
}
|
|
876
|
+
catch (err) {
|
|
877
|
+
coalescer.Dispose();
|
|
878
|
+
LogStatusEx({ message: `[AIBridgeEngine] inbound DTMF not routed for bridge ${active.SessionBridgeID}: ${err instanceof Error ? err.message : String(err)}`, verboseOnly: true });
|
|
879
|
+
}
|
|
880
|
+
}
|
|
881
|
+
/**
|
|
882
|
+
* Subscribes to the model session's fatal-error and unexpected-close signals. Either means the caller is now
|
|
883
|
+
* talking to a dead line, so it starts {@link handleModelLoss}. Both can fire for one drop; the handler
|
|
884
|
+
* de-duplicates.
|
|
885
|
+
*/
|
|
886
|
+
wireModelLifecycle(active, session) {
|
|
887
|
+
session.OnError((error) => {
|
|
888
|
+
if (error.Fatal) {
|
|
889
|
+
void this.handleModelLoss(active, session, `fatal session error${error.Code ? ` [${error.Code}]` : ''}: ${error.Message}`);
|
|
890
|
+
}
|
|
891
|
+
});
|
|
892
|
+
session.OnClose?.(() => {
|
|
893
|
+
void this.handleModelLoss(active, session, 'the provider closed the connection');
|
|
894
|
+
});
|
|
895
|
+
}
|
|
896
|
+
/**
|
|
897
|
+
* The model session dropped mid-call. Re-open it ONCE, seeded with what was said, and carry on; if that is not
|
|
898
|
+
* possible (no recovery factory, attempts spent, the factory fails, or the replacement uses different audio
|
|
899
|
+
* rates) end the call cleanly instead of leaving the caller in silence.
|
|
900
|
+
*/
|
|
901
|
+
async handleModelLoss(active, lost, why) {
|
|
902
|
+
if (active.Ending || active.ModelRecovering || active.RealtimeSession !== lost) {
|
|
903
|
+
return; // already tearing down, already recovering, or a signal from a session we replaced
|
|
904
|
+
}
|
|
905
|
+
LogError(`[AIBridgeEngine] model session lost for bridge ${active.SessionBridgeID}: ${why}`);
|
|
906
|
+
if (!active.RecoverRealtimeSession || active.ModelRecoveryAttempts >= MAX_MODEL_RECOVERY_ATTEMPTS) {
|
|
907
|
+
await this.endCallAfterModelLoss(active);
|
|
908
|
+
return;
|
|
909
|
+
}
|
|
910
|
+
active.ModelRecovering = true;
|
|
911
|
+
active.ModelRecoveryAttempts++;
|
|
912
|
+
try {
|
|
913
|
+
const fresh = await active.RecoverRealtimeSession({
|
|
914
|
+
PriorTranscript: BuildPriorTranscript(active.TranscriptTail),
|
|
915
|
+
Attempt: active.ModelRecoveryAttempts,
|
|
916
|
+
Reason: why,
|
|
917
|
+
});
|
|
918
|
+
await this.adoptRecoveredSession(active, lost, fresh);
|
|
919
|
+
}
|
|
920
|
+
catch (err) {
|
|
921
|
+
LogError(`[AIBridgeEngine] model session recovery failed for bridge ${active.SessionBridgeID}: ${err instanceof Error ? err.message : String(err)}`);
|
|
922
|
+
active.ModelRecovering = false;
|
|
923
|
+
await this.endCallAfterModelLoss(active);
|
|
924
|
+
}
|
|
925
|
+
}
|
|
926
|
+
/** Swaps a recovered model session in for the lost one, or refuses it when it cannot carry the call's audio. */
|
|
927
|
+
async adoptRecoveredSession(active, lost, fresh, note = `attempt ${active.ModelRecoveryAttempts}`) {
|
|
928
|
+
const sameRates = (fresh.InputSampleRate ?? 24000) === (lost.InputSampleRate ?? 24000) && (fresh.OutputSampleRate ?? 24000) === (lost.OutputSampleRate ?? 24000);
|
|
929
|
+
if (active.Ending || !sameRates) {
|
|
930
|
+
await this.closeQuietly(fresh);
|
|
931
|
+
throw new Error(active.Ending ? 'the call ended during recovery' : 'the replacement session uses different audio sample rates');
|
|
932
|
+
}
|
|
933
|
+
active.RealtimeSession = fresh;
|
|
934
|
+
this.wireModelSession(active);
|
|
935
|
+
this.wireTurnTaking(active);
|
|
936
|
+
active.ModelRecovering = false;
|
|
937
|
+
LogStatus(`[AIBridgeEngine] model session re-opened for bridge ${active.SessionBridgeID} (${note}).`);
|
|
938
|
+
await this.closeQuietly(lost); // releases the dead socket and finalizes its observability run
|
|
939
|
+
}
|
|
940
|
+
/**
|
|
941
|
+
* The bridge can no longer show the agent's avatar: replace the model session, once, with one that renders no avatar
|
|
942
|
+
* (through the host's {@link StartBridgeSessionParams.RecoverRealtimeSessionWithoutAvatar}), seeded with what was said,
|
|
943
|
+
* so the model stops generating video nobody sees and, if the voice decoder was the one that failed, the voice comes
|
|
944
|
+
* back as PCM. Inbound audio is held back while the replacement opens, as in a recovery. If it fails, the session goes
|
|
945
|
+
* on as it was.
|
|
946
|
+
*/
|
|
947
|
+
async replaceModelSessionWithoutAvatar(active, reason) {
|
|
948
|
+
const replace = active.RecoverRealtimeSessionWithoutAvatar;
|
|
949
|
+
if (active.Ending || active.ModelRecovering || active.AvatarReplaced || !replace) {
|
|
950
|
+
LogStatus(`[AIBridgeEngine] bridge ${active.SessionBridgeID} lost its avatar (${reason}); its model session is not replaced${replace ? ' (busy, ending or already replaced)' : ' (the host gave no audio-only replacement)'}.`);
|
|
951
|
+
return;
|
|
952
|
+
}
|
|
953
|
+
active.AvatarReplaced = true;
|
|
954
|
+
active.ModelRecovering = true;
|
|
955
|
+
const lost = active.RealtimeSession;
|
|
956
|
+
LogStatus(`[AIBridgeEngine] bridge ${active.SessionBridgeID} lost its avatar (${reason}); replacing its model session with an audio-only one.`);
|
|
957
|
+
try {
|
|
958
|
+
const fresh = await replace({ PriorTranscript: BuildPriorTranscript(active.TranscriptTail), Attempt: 1, Reason: `the avatar could not be shown (${reason})` });
|
|
959
|
+
await this.adoptRecoveredSession(active, lost, fresh, `audio only, after the avatar's ${reason}`);
|
|
960
|
+
}
|
|
961
|
+
catch (err) {
|
|
962
|
+
LogError(`[AIBridgeEngine] the audio-only replacement for bridge ${active.SessionBridgeID} failed; the session goes on as it was: ${err instanceof Error ? err.message : String(err)}`);
|
|
963
|
+
active.ModelRecovering = false;
|
|
964
|
+
}
|
|
965
|
+
}
|
|
966
|
+
/** Ends a call whose model session cannot be recovered: a spoken goodbye at the carrier (telephony), then a clean stop. */
|
|
967
|
+
async endCallAfterModelLoss(active) {
|
|
968
|
+
if (active.Ending) {
|
|
969
|
+
return;
|
|
970
|
+
}
|
|
971
|
+
active.Ending = true; // a signal that races this one must not start a second teardown
|
|
972
|
+
if (active.Bridge instanceof BaseTelephonyBridge) {
|
|
973
|
+
try {
|
|
974
|
+
await active.Bridge.AnnounceAndEndCall(MODEL_LOSS_CALLER_MESSAGE);
|
|
975
|
+
}
|
|
976
|
+
catch (err) {
|
|
977
|
+
LogError(`[AIBridgeEngine] could not announce the failure to the caller on bridge ${active.SessionBridgeID}: ${err instanceof Error ? err.message : String(err)}`);
|
|
978
|
+
}
|
|
979
|
+
}
|
|
980
|
+
await this.StopBridgeSession(active.SessionBridgeID, 'Error', active.ContextUser, active.MetadataProvider);
|
|
981
|
+
}
|
|
982
|
+
/** Closes a realtime session, logging (never throwing) a provider error. */
|
|
983
|
+
async closeQuietly(session) {
|
|
984
|
+
try {
|
|
985
|
+
await session.Close();
|
|
986
|
+
}
|
|
987
|
+
catch (err) {
|
|
988
|
+
LogError(`[AIBridgeEngine] closing a realtime session failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
627
989
|
}
|
|
628
990
|
}
|
|
629
991
|
/**
|
|
@@ -746,17 +1108,29 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
746
1108
|
* @param active The live bridged session.
|
|
747
1109
|
*/
|
|
748
1110
|
wireTurnTaking(active) {
|
|
749
|
-
active.RealtimeSession
|
|
1111
|
+
const session = active.RealtimeSession;
|
|
1112
|
+
session.OnTranscript((t) => {
|
|
1113
|
+
if (active.RealtimeSession !== session) {
|
|
1114
|
+
return; // a stale (replaced) session
|
|
1115
|
+
}
|
|
750
1116
|
active.LastActivityMs = Date.now(); // any transcript = the session is alive (drives the idle sweep)
|
|
751
1117
|
if (!t.IsFinal) {
|
|
752
1118
|
return; // partials fire per-word — act only on a completed turn (and don't flood the log)
|
|
753
1119
|
}
|
|
754
1120
|
LogStatusEx({ message: `[AIBridgeEngine][diag] transcript(final): role=${t.Role} text="${(t.Text ?? '').slice(0, 80)}" (bridge ${active.SessionBridgeID})`, verboseOnly: true });
|
|
755
|
-
|
|
1121
|
+
if (t.Role === 'user') {
|
|
1122
|
+
active.LastUserSpeechEndMs = performance.now();
|
|
1123
|
+
}
|
|
1124
|
+
if (t.Role === 'user' || t.Role === 'assistant') {
|
|
1125
|
+
AppendTranscriptTurn(active.TranscriptTail, { Role: t.Role, Text: t.Text ?? '' });
|
|
1126
|
+
}
|
|
1127
|
+
// Persist the transcript: this session's own sink, or the unified room transcript (scribe only).
|
|
756
1128
|
this.emitTranscriptLine(active, t);
|
|
757
1129
|
// Record into the room's diarized lookback so the moderator (and observability) see the full thread.
|
|
758
1130
|
this.recordRoomTurn(active, t);
|
|
759
1131
|
if (t.Role === 'assistant') {
|
|
1132
|
+
// Full-duplex gate: settle the turn first so a short acknowledgement is reclassified as a backchannel.
|
|
1133
|
+
active.TurnGate?.EndTurn({ Text: t.Text });
|
|
760
1134
|
// The agent finished its own turn → release the room floor so the next can speak. Then advance:
|
|
761
1135
|
// run the moderator for "who responds to this agent?" (the agent↔agent + pre-stage path) — this
|
|
762
1136
|
// executes while the agent's audio is still playing out, hiding the moderator latency.
|
|
@@ -791,15 +1165,18 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
791
1165
|
// Only a REAL human turn counts as presence. In a multi-agent room every agent transcribes its peers'
|
|
792
1166
|
// speech as a 'user' turn (it has no other role to assign overheard audio); if those counted as a human,
|
|
793
1167
|
// an agents-only room would keep cancelling its own auto-leave and babble forever after the humans left —
|
|
794
|
-
// burning realtime tokens at full cost. The diarized inbound speaker tells us: an
|
|
795
|
-
// peer agent, NOT a human, so it must NOT keep the room alive.
|
|
796
|
-
const overheardAgent = source.LastInboundSpeaker
|
|
1168
|
+
// burning realtime tokens at full cost. The diarized inbound speaker tells us: an agent's identity
|
|
1169
|
+
// (`agent-…`, IsAgentParticipantIdentity) is a peer agent, NOT a human, so it must NOT keep the room alive.
|
|
1170
|
+
const overheardAgent = IsAgentParticipantIdentity(source.LastInboundSpeaker);
|
|
797
1171
|
if (!overheardAgent) {
|
|
798
1172
|
// A real human just spoke → definitive presence for EVERY agent in the room. Cancel any pending
|
|
799
1173
|
// empty-room auto-leave + reset the consecutive-agent-only counter.
|
|
800
1174
|
for (const peer of peers) {
|
|
801
1175
|
this.noteHumanPresence(peer);
|
|
802
1176
|
}
|
|
1177
|
+
if (source.RoomKey) {
|
|
1178
|
+
this.roomCoordinator.NoteHumanTurn(source.RoomKey); // a human spoke: agents may take turns again
|
|
1179
|
+
}
|
|
803
1180
|
}
|
|
804
1181
|
if (source.RoomKey) {
|
|
805
1182
|
this.roomConsecutiveAgentTurns.set(source.RoomKey.toLowerCase(), 0);
|
|
@@ -882,7 +1259,7 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
882
1259
|
if (!active.IsTranscriptScribe) {
|
|
883
1260
|
return; // only the scribe records human turns (avoids one copy per transcribing agent)
|
|
884
1261
|
}
|
|
885
|
-
if (active.LastInboundSpeaker
|
|
1262
|
+
if (IsAgentParticipantIdentity(active.LastInboundSpeaker)) {
|
|
886
1263
|
return; // the scribe is overhearing another agent — that agent's own bridge records it
|
|
887
1264
|
}
|
|
888
1265
|
}
|
|
@@ -1107,20 +1484,291 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
1107
1484
|
break;
|
|
1108
1485
|
}
|
|
1109
1486
|
}
|
|
1487
|
+
// ──────────────────────────────────────────────────────────────────────────────
|
|
1488
|
+
// Full-duplex turn-taking — the room floor as a safety net behind the model's own judgement.
|
|
1489
|
+
// ──────────────────────────────────────────────────────────────────────────────
|
|
1490
|
+
/**
|
|
1491
|
+
* Gives a FULL-DUPLEX model the floor gate + human-speech detector (see {@link FullDuplexTurnGate})
|
|
1492
|
+
* ONLY when moderator mode (`MJ_REALTIME_MODERATOR_MODE=on`) is explicitly enabled (or explicitly opted into).
|
|
1493
|
+
* In normal operation (solo and multi-agent rooms alike), full-duplex models are never gated:
|
|
1494
|
+
* native full-duplex models are better at turn-taking and ignoring background noise.
|
|
1495
|
+
*
|
|
1496
|
+
* @param active The freshly connected session.
|
|
1497
|
+
* @param params The start parameters (`FullDuplexTurnGate: false` opts out).
|
|
1498
|
+
*/
|
|
1499
|
+
wireFullDuplexTurnGate(active, params) {
|
|
1500
|
+
if (!active.RoomKey || params.FullDuplexTurnGate === false) {
|
|
1501
|
+
return;
|
|
1502
|
+
}
|
|
1503
|
+
if (!active.FullDuplex) {
|
|
1504
|
+
return;
|
|
1505
|
+
}
|
|
1506
|
+
const moderatorMode = process.env.MJ_REALTIME_MODERATOR_MODE === 'on';
|
|
1507
|
+
if (!moderatorMode && params.FullDuplexTurnGate !== true) {
|
|
1508
|
+
return;
|
|
1509
|
+
}
|
|
1510
|
+
active.TurnGate = new FullDuplexTurnGate({
|
|
1511
|
+
Coordinator: this.roomCoordinator,
|
|
1512
|
+
RoomId: active.RoomKey,
|
|
1513
|
+
AgentSessionId: active.AgentSessionID,
|
|
1514
|
+
SampleRateHz: active.RealtimeSession.OutputSampleRate,
|
|
1515
|
+
});
|
|
1516
|
+
active.HumanSpeech = new HumanSpeechDetector();
|
|
1517
|
+
}
|
|
1518
|
+
/**
|
|
1519
|
+
* Runs one chunk of a full-duplex model's outbound audio through its floor gate. Sessions without a gate,
|
|
1520
|
+
* and rooms with a single agent, are never gated.
|
|
1521
|
+
*
|
|
1522
|
+
* @param active The speaking session.
|
|
1523
|
+
* @param byteLength The chunk size (PCM16).
|
|
1524
|
+
* @returns Whether to forward the chunk, drop it, or cut the burst (drop + flush queued audio).
|
|
1525
|
+
*/
|
|
1526
|
+
gateOutput(active, byteLength) {
|
|
1527
|
+
return this.applyTurnGate(active, (gate) => gate.OnOutputAudio(byteLength));
|
|
1528
|
+
}
|
|
1529
|
+
/**
|
|
1530
|
+
* Runs one chunk of a full-duplex model's outbound speech through its floor gate by how long it plays (an avatar
|
|
1531
|
+
* piece). Sessions without a gate, and rooms with a single agent, are never gated.
|
|
1532
|
+
*
|
|
1533
|
+
* @param active The speaking session.
|
|
1534
|
+
* @param durationMs How long the chunk's speech plays.
|
|
1535
|
+
*/
|
|
1536
|
+
gateOutputDuration(active, durationMs) {
|
|
1537
|
+
return this.applyTurnGate(active, (gate) => gate.OnOutputDuration(durationMs));
|
|
1538
|
+
}
|
|
1539
|
+
/** Asks the session's floor gate about one chunk (when it is gated at all) and acts on the floor it took or lost. */
|
|
1540
|
+
applyTurnGate(active, decide) {
|
|
1541
|
+
const gate = active.TurnGate;
|
|
1542
|
+
if (!gate || !active.RoomKey || !this.roomCoordinator.IsMultiAgentRoom(active.RoomKey)) {
|
|
1543
|
+
return 'Forward';
|
|
1544
|
+
}
|
|
1545
|
+
const result = decide(gate);
|
|
1546
|
+
if (result.TookFloor) {
|
|
1547
|
+
this.armFloorHold(active);
|
|
1548
|
+
}
|
|
1549
|
+
if (result.Verdict === 'Cut') {
|
|
1550
|
+
LogStatusEx({ message: `[AIBridgeEngine][diag] full-duplex gate CUT bridge ${active.SessionBridgeID} — it spoke without the floor`, verboseOnly: true });
|
|
1551
|
+
}
|
|
1552
|
+
return result.Verdict;
|
|
1553
|
+
}
|
|
1554
|
+
/** Whether an inbound speaker label belongs to a human (diarized, and not a peer `agent-…` bot). */
|
|
1555
|
+
isHumanSpeaker(label) {
|
|
1556
|
+
return label !== undefined && label.length > 0 && !IsAgentParticipantIdentity(label);
|
|
1557
|
+
}
|
|
1558
|
+
/**
|
|
1559
|
+
* Watches inbound room audio for a human speaking and, on the first activity, makes every agent yield.
|
|
1560
|
+
* Only a DIARIZED human counts — without a speaker label the audio could be a peer agent, and a peer must
|
|
1561
|
+
* never preempt another agent's turn.
|
|
1562
|
+
*/
|
|
1563
|
+
observeInboundHumanSpeech(active, frame, chunk) {
|
|
1564
|
+
const detector = active.HumanSpeech;
|
|
1565
|
+
if (!detector || !chunk || !active.RoomKey || frame.Track !== 'audio-in' || !this.isHumanSpeaker(frame.SpeakerLabel)) {
|
|
1566
|
+
return;
|
|
1567
|
+
}
|
|
1568
|
+
if (this.roomCoordinator.IsMultiAgentRoom(active.RoomKey) && detector.ShouldReportSpeech(chunk)) {
|
|
1569
|
+
this.preemptForHuman(active.RoomKey);
|
|
1570
|
+
}
|
|
1571
|
+
}
|
|
1572
|
+
/**
|
|
1573
|
+
* A human started talking: tell the coordinator (humans win), and for the agent that was holding the floor
|
|
1574
|
+
* flush its queued audio, mute the rest of its burst, free its floor, and fire the barge-in hook so the host
|
|
1575
|
+
* drops now-stale narration. Delegated work keeps running — the same policy as a direct barge-in.
|
|
1576
|
+
*
|
|
1577
|
+
* @param roomKey The room the human spoke in.
|
|
1578
|
+
*/
|
|
1579
|
+
preemptForHuman(roomKey) {
|
|
1580
|
+
const { PreemptedAgentSessionId } = this.roomCoordinator.NoteHumanSpeech(roomKey);
|
|
1581
|
+
if (!PreemptedAgentSessionId) {
|
|
1582
|
+
return;
|
|
1583
|
+
}
|
|
1584
|
+
const target = this.roomAgents(roomKey).find((a) => a.AgentSessionID.toLowerCase() === PreemptedAgentSessionId.toLowerCase());
|
|
1585
|
+
if (!target) {
|
|
1586
|
+
return;
|
|
1587
|
+
}
|
|
1588
|
+
LogStatusEx({ message: `[AIBridgeEngine][diag] human speech preempted bridge ${target.SessionBridgeID} — flushing its output`, verboseOnly: true });
|
|
1589
|
+
target.TurnGate?.Cut();
|
|
1590
|
+
target.Bridge.FlushOutboundMedia();
|
|
1591
|
+
this.clearRoomModeratorState(roomKey, false);
|
|
1592
|
+
this.releaseRoomFloor(target, /*skipDrain*/ true);
|
|
1593
|
+
this.notifyBargeIn(target);
|
|
1594
|
+
}
|
|
1595
|
+
/**
|
|
1596
|
+
* Binds the turn-taking host tools (`i_am_addressed`, `yield_turn`) to a session that needs them: a
|
|
1597
|
+
* full-duplex model in a room, or any model using model-side addressing. The tool DEFINITIONS are
|
|
1598
|
+
* {@link TURN_TAKING_TOOL_DEFINITIONS}; the layer that owns the model session registers them at connect and
|
|
1599
|
+
* installs {@link ActiveBridgeSession.TurnTakingToolHandler} as its local tool handler.
|
|
1600
|
+
*
|
|
1601
|
+
* @param active The live bridged session.
|
|
1602
|
+
*/
|
|
1603
|
+
wireTurnTakingTools(active) {
|
|
1604
|
+
const moderatorMode = process.env.MJ_REALTIME_MODERATOR_MODE === 'on';
|
|
1605
|
+
const isFullDuplex = active.FullDuplex;
|
|
1606
|
+
if (isFullDuplex && !moderatorMode) {
|
|
1607
|
+
return;
|
|
1608
|
+
}
|
|
1609
|
+
if (!active.RoomKey || !(active.AddressingMode === 'ModelSide' || active.TurnGate)) {
|
|
1610
|
+
return;
|
|
1611
|
+
}
|
|
1612
|
+
active.TurnTakingToolHandler = {
|
|
1613
|
+
Handles: (toolName) => IsTurnTakingTool(toolName),
|
|
1614
|
+
Execute: async (call) => this.executeTurnTakingTool(active, call.ToolName, call.Arguments),
|
|
1615
|
+
};
|
|
1616
|
+
}
|
|
1617
|
+
/**
|
|
1618
|
+
* Once a room holds 2+ agents, tells each tool-equipped (full-duplex / model-side) agent in it — once — how to
|
|
1619
|
+
* take turns: speak when addressed, stop for a person, only acknowledge briefly over someone, hand over by name.
|
|
1620
|
+
* It is a context note rather than part of the system prompt on purpose: the FIRST agent joins before anyone
|
|
1621
|
+
* else, and a solo agent in a one-on-one call must keep answering everything it hears.
|
|
1622
|
+
*
|
|
1623
|
+
* @param roomKey The room to announce in (no-op when `undefined`, or while the room has a single agent).
|
|
1624
|
+
*/
|
|
1625
|
+
announceTurnTaking(roomKey) {
|
|
1626
|
+
if (!roomKey || !this.roomCoordinator.IsMultiAgentRoom(roomKey)) {
|
|
1627
|
+
return;
|
|
1628
|
+
}
|
|
1629
|
+
const moderatorMode = process.env.MJ_REALTIME_MODERATOR_MODE === 'on';
|
|
1630
|
+
for (const agent of this.roomAgents(roomKey)) {
|
|
1631
|
+
const isFullDuplex = agent.FullDuplex;
|
|
1632
|
+
if (isFullDuplex && !moderatorMode) {
|
|
1633
|
+
continue;
|
|
1634
|
+
}
|
|
1635
|
+
if (agent.TurnTakingToolHandler && !agent.TurnTakingAnnounced) {
|
|
1636
|
+
agent.RealtimeSession.SendContextNote?.(MODEL_SIDE_TURN_TAKING_FRAMING);
|
|
1637
|
+
agent.TurnTakingAnnounced = true;
|
|
1638
|
+
}
|
|
1639
|
+
}
|
|
1640
|
+
}
|
|
1641
|
+
/** Runs one turn-taking tool call and returns the JSON the model is handed back. Never throws. */
|
|
1642
|
+
executeTurnTakingTool(active, toolName, argsJson) {
|
|
1643
|
+
try {
|
|
1644
|
+
const parsed = ParseTurnTakingToolCall(toolName, argsJson);
|
|
1645
|
+
if (!parsed) {
|
|
1646
|
+
return JSON.stringify({ ok: false, error: `Unknown turn-taking tool '${toolName}'.` });
|
|
1647
|
+
}
|
|
1648
|
+
switch (parsed.Kind) {
|
|
1649
|
+
case 'Addressed':
|
|
1650
|
+
return this.onModelAddressed(active);
|
|
1651
|
+
case 'Yield':
|
|
1652
|
+
return this.onModelYield(active, parsed.To);
|
|
1653
|
+
default:
|
|
1654
|
+
return JSON.stringify({ ok: false, error: parsed.Reason });
|
|
1655
|
+
}
|
|
1656
|
+
}
|
|
1657
|
+
catch (err) {
|
|
1658
|
+
LogError(`[AIBridgeEngine] turn-taking tool ${toolName} failed for bridge ${active.SessionBridgeID}: ${err instanceof Error ? err.message : String(err)}`);
|
|
1659
|
+
return JSON.stringify({ ok: false, error: 'The turn-taking action failed.' });
|
|
1660
|
+
}
|
|
1661
|
+
}
|
|
1662
|
+
/**
|
|
1663
|
+
* The model said it is addressed: latch the model-side matcher and — in a multi-agent room — reserve the
|
|
1664
|
+
* floor NOW, before any audio, so a peer cannot start in the gap. A denial tells the model to stay silent,
|
|
1665
|
+
* which is how a cooperative model learns it lost the race.
|
|
1666
|
+
*/
|
|
1667
|
+
onModelAddressed(active) {
|
|
1668
|
+
active.ModelSideMatcher?.NoteModelAddressed();
|
|
1669
|
+
if (!active.RoomKey || !this.roomCoordinator.IsMultiAgentRoom(active.RoomKey)) {
|
|
1670
|
+
return JSON.stringify({ ok: true, floor: 'granted' });
|
|
1671
|
+
}
|
|
1672
|
+
const floor = this.roomCoordinator.TakeFloor(active.RoomKey, active.AgentSessionID);
|
|
1673
|
+
if (!floor.Granted) {
|
|
1674
|
+
return JSON.stringify({ ok: false, floor: 'denied', reason: floor.Reason, instruction: 'Do not speak now; stay silent.' });
|
|
1675
|
+
}
|
|
1676
|
+
this.armFloorHold(active);
|
|
1677
|
+
return JSON.stringify({ ok: true, floor: 'granted' });
|
|
1678
|
+
}
|
|
1679
|
+
/**
|
|
1680
|
+
* The model hands the floor over, optionally to a named agent: release it, reserve it for the target, and
|
|
1681
|
+
* nudge the target to speak. A name that matches nobody degrades to a plain release.
|
|
1682
|
+
*/
|
|
1683
|
+
onModelYield(active, toName) {
|
|
1684
|
+
if (!active.RoomKey) {
|
|
1685
|
+
return JSON.stringify({ ok: true, floor: 'released' });
|
|
1686
|
+
}
|
|
1687
|
+
const target = toName ? this.findRoomAgentByName(active.RoomKey, toName, active) : undefined;
|
|
1688
|
+
const result = this.roomCoordinator.YieldFloor(active.RoomKey, active.AgentSessionID, target?.AgentSessionID);
|
|
1689
|
+
active.TurnGate?.Reset();
|
|
1690
|
+
this.releaseRoomFloor(active, /*skipDrain*/ true);
|
|
1691
|
+
if (target && result.HandoffToAgentSessionId) {
|
|
1692
|
+
this.handOffFloor(active, target);
|
|
1693
|
+
}
|
|
1694
|
+
const note = toName && !target ? `No agent named '${toName}' is in the room; the floor went back to the room.` : undefined;
|
|
1695
|
+
const handedTo = result.HandoffToAgentSessionId ? target?.AgentNames[0] ?? null : null;
|
|
1696
|
+
return JSON.stringify({ ok: true, floor: 'released', handedTo, reason: result.Reason, note });
|
|
1697
|
+
}
|
|
1698
|
+
/** Finds another agent in the room by any of its names (case-insensitive), excluding the asker. */
|
|
1699
|
+
findRoomAgentByName(roomKey, name, asker) {
|
|
1700
|
+
const wanted = name.trim().toLowerCase();
|
|
1701
|
+
return this.roomAgents(roomKey).find((a) => a !== asker && a.AgentNames.some((n) => n.trim().toLowerCase() === wanted));
|
|
1702
|
+
}
|
|
1703
|
+
/** Tells a hand-off target it was given the floor and triggers it to speak (when its driver can be triggered). */
|
|
1704
|
+
handOffFloor(from, target) {
|
|
1705
|
+
const fromName = from.AgentNames[0] ?? 'Another agent';
|
|
1706
|
+
target.RealtimeSession.SendContextNote?.(`[turn] ${fromName} handed the floor to you. Continue the conversation now.`);
|
|
1707
|
+
if (typeof target.RealtimeSession.RequestSpokenUpdate === 'function') {
|
|
1708
|
+
this.triggerMeetingSpeak(target);
|
|
1709
|
+
}
|
|
1710
|
+
}
|
|
1711
|
+
/**
|
|
1712
|
+
* Adjusts the turn-taking limits every room uses (the agent-to-agent loop cap, hand-off TTL, human-speech
|
|
1713
|
+
* hold). Omitted values keep their current setting. Call once at startup to tune.
|
|
1714
|
+
*
|
|
1715
|
+
* @param limits The limits to change.
|
|
1716
|
+
*/
|
|
1717
|
+
ConfigureTurnLimits(limits) {
|
|
1718
|
+
this.roomCoordinator.ConfigureLimits(limits);
|
|
1719
|
+
}
|
|
1720
|
+
/**
|
|
1721
|
+
* A room's live turn-taking state: who holds the floor, whether a human is speaking, any pending hand-off,
|
|
1722
|
+
* the loop-cap progress, recent floor/backchannel/yield events, and who is seated. Read-only; the test bed
|
|
1723
|
+
* polls it. `null` when the room is unknown (no agent in it).
|
|
1724
|
+
*
|
|
1725
|
+
* @param roomKey The room (external connection id — a LiveKit room's name).
|
|
1726
|
+
* @returns The snapshot, or `null`.
|
|
1727
|
+
*/
|
|
1728
|
+
GetRoomTurnSnapshot(roomKey) {
|
|
1729
|
+
const state = this.roomCoordinator.GetRoomState(roomKey);
|
|
1730
|
+
if (!state) {
|
|
1731
|
+
return null;
|
|
1732
|
+
}
|
|
1733
|
+
const agents = this.roomAgents(roomKey).map((a) => ({
|
|
1734
|
+
AgentSessionID: a.AgentSessionID,
|
|
1735
|
+
SessionBridgeID: a.SessionBridgeID,
|
|
1736
|
+
Names: a.AgentNames,
|
|
1737
|
+
TurnMode: a.TurnPolicy.Mode,
|
|
1738
|
+
Addressing: a.AddressingMode ?? 'Regex',
|
|
1739
|
+
FullDuplex: a.FullDuplex,
|
|
1740
|
+
}));
|
|
1741
|
+
return { ...state, Agents: agents };
|
|
1742
|
+
}
|
|
1110
1743
|
/**
|
|
1111
1744
|
* Builds the per-session {@link TurnTakingPolicy} from the start params.
|
|
1112
1745
|
*
|
|
1113
1746
|
* @param params The session parameters.
|
|
1114
|
-
* @
|
|
1747
|
+
* @param fullDuplex Whether the session's model reports full-duplex capability (enables model-side addressing).
|
|
1748
|
+
* @returns The configured policy plus the addressing mode in effect and the model-side latch, when any.
|
|
1115
1749
|
*/
|
|
1116
|
-
buildTurnPolicy(params) {
|
|
1750
|
+
buildTurnPolicy(params, fullDuplex) {
|
|
1751
|
+
const moderatorMode = process.env.MJ_REALTIME_MODERATOR_MODE === 'on';
|
|
1752
|
+
let matcher = params.TurnMatcher;
|
|
1753
|
+
let mode = 'Regex';
|
|
1754
|
+
let modelSide;
|
|
1755
|
+
if (params.TurnAddressing !== undefined) {
|
|
1756
|
+
// Full-duplex models only use ModelSide addressing automatically when moderator mode is enabled.
|
|
1757
|
+
// Outside moderator mode, Auto falls back to name/regex matching (keeping AlwaysAddressedMatcher for 1:1 / solo),
|
|
1758
|
+
// while explicit 'ModelSide' is still honoured.
|
|
1759
|
+
const enableModelSide = params.TurnAddressing === 'ModelSide' || (fullDuplex && moderatorMode);
|
|
1760
|
+
const built = BuildAddressedMatcher(params.AgentNames ?? [], params.TurnAddressing, enableModelSide);
|
|
1761
|
+
mode = built.Mode;
|
|
1762
|
+
modelSide = built.ModelSide;
|
|
1763
|
+
matcher = built.Mode === 'ModelSide' ? built.Matcher : (params.TurnMatcher ?? built.Matcher);
|
|
1764
|
+
}
|
|
1117
1765
|
const config = {
|
|
1118
1766
|
Mode: params.TurnMode ?? 'Passive',
|
|
1119
|
-
Matcher:
|
|
1767
|
+
Matcher: matcher,
|
|
1120
1768
|
Scorer: params.TurnScorer,
|
|
1121
1769
|
...(params.TurnTuning ?? {}),
|
|
1122
1770
|
};
|
|
1123
|
-
return new TurnTakingPolicy(config);
|
|
1771
|
+
return { Policy: new TurnTakingPolicy(config), Mode: mode, ModelSide: modelSide };
|
|
1124
1772
|
}
|
|
1125
1773
|
/**
|
|
1126
1774
|
* Retroactively switches an already-running session into **meeting mode** (auto-response off +
|
|
@@ -1214,8 +1862,8 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
1214
1862
|
* @param active The freshly connected session.
|
|
1215
1863
|
*/
|
|
1216
1864
|
electTranscriptScribe(active) {
|
|
1217
|
-
if (!this.transcriptSink || !active.RoomKey) {
|
|
1218
|
-
return;
|
|
1865
|
+
if (active.TranscriptSink || !this.transcriptSink || !active.RoomKey) {
|
|
1866
|
+
return; // a session with its own sink never takes part in the room's scribe election
|
|
1219
1867
|
}
|
|
1220
1868
|
const roomKey = active.RoomKey.toLowerCase();
|
|
1221
1869
|
if (!this.roomScribes.has(roomKey)) {
|
|
@@ -1259,7 +1907,8 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
1259
1907
|
* @param t The final transcript line.
|
|
1260
1908
|
*/
|
|
1261
1909
|
emitTranscriptLine(active, t) {
|
|
1262
|
-
|
|
1910
|
+
const sink = active.TranscriptSink ?? (active.IsTranscriptScribe ? this.transcriptSink : undefined);
|
|
1911
|
+
if (!sink || !active.RoomKey) {
|
|
1263
1912
|
return;
|
|
1264
1913
|
}
|
|
1265
1914
|
const text = (t.Text ?? '').trim();
|
|
@@ -1267,7 +1916,7 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
1267
1916
|
return;
|
|
1268
1917
|
}
|
|
1269
1918
|
const isAgentSpeech = t.Role === 'assistant';
|
|
1270
|
-
void Promise.resolve(
|
|
1919
|
+
void Promise.resolve(sink({
|
|
1271
1920
|
RoomKey: active.RoomKey,
|
|
1272
1921
|
AgentSessionID: active.AgentSessionID,
|
|
1273
1922
|
AgentID: active.AgentID,
|
|
@@ -1390,11 +2039,86 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
1390
2039
|
return;
|
|
1391
2040
|
}
|
|
1392
2041
|
this.staleSweepTimer = setInterval(() => {
|
|
1393
|
-
void this.SweepStaleSessions()
|
|
2042
|
+
void this.SweepStaleSessions()
|
|
2043
|
+
.then(() => this.HeartbeatLiveSessions())
|
|
2044
|
+
.catch((err) => LogError(`[AIBridgeEngine] stale sweep tick failed: ${err instanceof Error ? err.message : String(err)}`));
|
|
1394
2045
|
}, intervalMs);
|
|
1395
2046
|
// Don't keep the process alive solely for the sweep (Node-only; guarded for non-Node hosts).
|
|
1396
2047
|
this.staleSweepTimer?.unref?.();
|
|
1397
2048
|
}
|
|
2049
|
+
/**
|
|
2050
|
+
* Refreshes `LastActiveAt` on the agent-session row of every live bridge that has not been touched for
|
|
2051
|
+
* {@link SESSION_HEARTBEAT_INTERVAL_MS}. The host session janitor closes sessions idle past its threshold; a
|
|
2052
|
+
* long phone call writes nothing else to the row, so without this it would be closed (and its run finalized)
|
|
2053
|
+
* mid-call. Tolerant: a failed write is logged and the rest are still touched.
|
|
2054
|
+
*
|
|
2055
|
+
* @param nowMs Current epoch-ms (injectable for tests).
|
|
2056
|
+
* @returns The number of rows refreshed.
|
|
2057
|
+
*/
|
|
2058
|
+
async HeartbeatLiveSessions(nowMs = Date.now()) {
|
|
2059
|
+
let touched = 0;
|
|
2060
|
+
for (const active of this.activeSessions.values()) {
|
|
2061
|
+
if (nowMs - active.LastSessionHeartbeatMs < SESSION_HEARTBEAT_INTERVAL_MS) {
|
|
2062
|
+
continue;
|
|
2063
|
+
}
|
|
2064
|
+
active.LastSessionHeartbeatMs = nowMs;
|
|
2065
|
+
if (await this.touchAgentSession(active)) {
|
|
2066
|
+
touched++;
|
|
2067
|
+
}
|
|
2068
|
+
}
|
|
2069
|
+
return touched;
|
|
2070
|
+
}
|
|
2071
|
+
/** Writes `LastActiveAt = now` on the session's agent-session row. Returns whether it saved. */
|
|
2072
|
+
async touchAgentSession(active) {
|
|
2073
|
+
const provider = active.MetadataProvider;
|
|
2074
|
+
if (!provider || !active.AgentSessionID) {
|
|
2075
|
+
return false;
|
|
2076
|
+
}
|
|
2077
|
+
try {
|
|
2078
|
+
const row = await provider.GetEntityObject(AGENT_SESSION_ENTITY, active.ContextUser);
|
|
2079
|
+
if (!(await row.Load(active.AgentSessionID))) {
|
|
2080
|
+
return false;
|
|
2081
|
+
}
|
|
2082
|
+
row.LastActiveAt = new Date();
|
|
2083
|
+
if (await row.Save()) {
|
|
2084
|
+
return true;
|
|
2085
|
+
}
|
|
2086
|
+
LogError(`[AIBridgeEngine] session heartbeat save failed for ${active.AgentSessionID}: ${row.LatestResult?.CompleteMessage ?? 'unknown error'}`);
|
|
2087
|
+
}
|
|
2088
|
+
catch (err) {
|
|
2089
|
+
LogError(`[AIBridgeEngine] session heartbeat failed for ${active.AgentSessionID}: ${err instanceof Error ? err.message : String(err)}`);
|
|
2090
|
+
}
|
|
2091
|
+
return false;
|
|
2092
|
+
}
|
|
2093
|
+
/**
|
|
2094
|
+
* Reconciles prior-boot orphans ({@link ReconcileOrphans}) once now and then every
|
|
2095
|
+
* {@link ORPHAN_RECONCILE_INTERVAL_MS}. Idempotent — a no-op while already scheduled. The timer is `unref`'d.
|
|
2096
|
+
*
|
|
2097
|
+
* The host calls it once it owns its instance, so that no other live process can be that instance: MJServer calls
|
|
2098
|
+
* it after the server listens on its port. {@link HandleStartup} does not start it.
|
|
2099
|
+
*
|
|
2100
|
+
* @param contextUser The user the reconciliation writes run as.
|
|
2101
|
+
* @param provider The metadata provider for the reads/writes.
|
|
2102
|
+
* @param intervalMs How often to reconcile after the first pass.
|
|
2103
|
+
*/
|
|
2104
|
+
StartOrphanReconciliation(contextUser, provider, intervalMs = ORPHAN_RECONCILE_INTERVAL_MS) {
|
|
2105
|
+
if (this.orphanReconcileTimer) {
|
|
2106
|
+
return;
|
|
2107
|
+
}
|
|
2108
|
+
const tick = () => {
|
|
2109
|
+
void this.ReconcileOrphans(contextUser, provider).catch((err) => LogError(`[AIBridgeEngine] orphan reconciliation failed: ${err instanceof Error ? err.message : String(err)}`));
|
|
2110
|
+
};
|
|
2111
|
+
tick();
|
|
2112
|
+
this.orphanReconcileTimer = setInterval(tick, intervalMs);
|
|
2113
|
+
this.orphanReconcileTimer?.unref?.();
|
|
2114
|
+
}
|
|
2115
|
+
/** Cancels the periodic orphan reconciliation, if running. */
|
|
2116
|
+
StopOrphanReconciliation() {
|
|
2117
|
+
if (this.orphanReconcileTimer) {
|
|
2118
|
+
clearInterval(this.orphanReconcileTimer);
|
|
2119
|
+
this.orphanReconcileTimer = undefined;
|
|
2120
|
+
}
|
|
2121
|
+
}
|
|
1398
2122
|
/** Cancels the self-scheduled stale-session sweep, if running. */
|
|
1399
2123
|
StopStaleSessionSweep() {
|
|
1400
2124
|
if (this.staleSweepTimer) {
|
|
@@ -1403,39 +2127,48 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
1403
2127
|
}
|
|
1404
2128
|
}
|
|
1405
2129
|
/**
|
|
1406
|
-
* Force-closes `Connected`/`Connecting` bridges
|
|
1407
|
-
*
|
|
1408
|
-
*
|
|
1409
|
-
*
|
|
2130
|
+
* Force-closes the `Connected`/`Connecting` bridges an **earlier boot of this instance** left, stamping
|
|
2131
|
+
* `CloseReason = 'Janitor'` and finalizing each one's co-agent run. Mirrors `SessionJanitor.RunStartupRecovery`:
|
|
2132
|
+
* a crash/redeploy vaporizes the in-memory driver sockets but leaves the durable rows reading `Connected`
|
|
2133
|
+
* forever; this reconciles them.
|
|
2134
|
+
*
|
|
2135
|
+
* Ownership comes from the injected {@link IHostInstanceIdentity}: the read is narrowed to the rows under its
|
|
2136
|
+
* instance prefix other than this boot's, and a row is closed only when
|
|
2137
|
+
* {@link IHostInstanceIdentity.IsPriorBoot} says another boot of this instance stamped it. Another instance's
|
|
2138
|
+
* bridges (another MJAPI on this host, or on another host) are never touched, live or not.
|
|
1410
2139
|
*
|
|
1411
|
-
*
|
|
1412
|
-
* application (MJServer's startup + janitor timer) so this engine package carries no timer/IO of
|
|
1413
|
-
* its own; call this method from that scheduler.
|
|
2140
|
+
* Run it only once this process owns its instance; {@link StartOrphanReconciliation} schedules it.
|
|
1414
2141
|
*
|
|
1415
2142
|
* @param contextUser The system user the reconciliation writes run as.
|
|
1416
2143
|
* @param provider The metadata provider for the reconciliation reads/writes.
|
|
1417
2144
|
* @returns The number of orphaned bridges closed.
|
|
1418
2145
|
*/
|
|
1419
2146
|
async ReconcileOrphans(contextUser, provider) {
|
|
1420
|
-
const
|
|
1421
|
-
const
|
|
2147
|
+
const identity = this.hostIdentity;
|
|
2148
|
+
const prefix = EscapeSQLString(identity.GetInstancePrefix());
|
|
2149
|
+
const current = EscapeSQLString(identity.GetHostInstanceID());
|
|
1422
2150
|
const filter = `Status IN ('Connecting','Connected') ` +
|
|
1423
2151
|
`AND HostInstanceID LIKE '${prefix}%' ` +
|
|
1424
2152
|
`AND HostInstanceID <> '${current}'`;
|
|
1425
2153
|
const rows = await this.loadOrphanRows(filter, contextUser, provider);
|
|
1426
2154
|
let closed = 0;
|
|
1427
2155
|
for (const row of rows) {
|
|
2156
|
+
// The LIKE narrows the read; the identity decides, since LIKE reads a `_` in a host name as any character.
|
|
2157
|
+
if (!identity.IsPriorBoot(row.HostInstanceID)) {
|
|
2158
|
+
continue;
|
|
2159
|
+
}
|
|
1428
2160
|
const ok = await this.markBridgeDisconnected(row.ID, 'Janitor', contextUser, provider);
|
|
1429
2161
|
if (ok) {
|
|
1430
2162
|
closed++;
|
|
1431
2163
|
}
|
|
1432
2164
|
}
|
|
1433
2165
|
if (closed > 0) {
|
|
1434
|
-
LogStatus(`[AIBridgeEngine] Janitor reconciled ${closed} orphaned bridge(s) from
|
|
2166
|
+
LogStatus(`[AIBridgeEngine] Janitor reconciled ${closed} orphaned bridge(s) from an earlier boot of this instance ` +
|
|
2167
|
+
`(${identity.GetInstancePrefix()})`);
|
|
1435
2168
|
}
|
|
1436
2169
|
return closed;
|
|
1437
2170
|
}
|
|
1438
|
-
/** Loads the
|
|
2171
|
+
/** Loads the bridge rows the janitor filter matches: the candidates {@link ReconcileOrphans} checks one by one. */
|
|
1439
2172
|
async loadOrphanRows(filter, contextUser, provider) {
|
|
1440
2173
|
const rv = RunView.FromMetadataProvider(provider);
|
|
1441
2174
|
const result = await rv.RunView({
|
|
@@ -1514,6 +2247,10 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
1514
2247
|
...params.Configuration,
|
|
1515
2248
|
InboundSampleRate: params.RealtimeSession.InputSampleRate ?? 24000,
|
|
1516
2249
|
OutboundSampleRate: params.RealtimeSession.OutputSampleRate ?? 24000,
|
|
2250
|
+
// The model's video facts, for a driver that sends camera or screen frames: how many sources it may send
|
|
2251
|
+
// at once and how often. Read from the session, so the rate always comes from the model.
|
|
2252
|
+
InboundVideoStreams: InboundVideoStreamsOf(params.RealtimeSession.Capabilities),
|
|
2253
|
+
InboundVideoRate: InboundVideoRateOf(params.RealtimeSession.Capabilities),
|
|
1517
2254
|
},
|
|
1518
2255
|
ContextUser: params.ContextUser,
|
|
1519
2256
|
};
|
|
@@ -1525,7 +2262,7 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
1525
2262
|
* @returns The saved bridge row.
|
|
1526
2263
|
* @throws When the row cannot be created (no metadata provider, or save failure).
|
|
1527
2264
|
*/
|
|
1528
|
-
async createBridgeRow(params) {
|
|
2265
|
+
async createBridgeRow(params, addressingMode) {
|
|
1529
2266
|
const provider = params.MetadataProvider;
|
|
1530
2267
|
if (!provider) {
|
|
1531
2268
|
throw new Error('AIBridgeEngine.StartBridgeSession requires a MetadataProvider.');
|
|
@@ -1537,6 +2274,7 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
1537
2274
|
row.Direction = params.Direction ?? 'Outbound';
|
|
1538
2275
|
row.JoinMethod = params.JoinMethod ?? 'OnDemand';
|
|
1539
2276
|
row.TurnMode = params.TurnMode ?? 'Passive';
|
|
2277
|
+
row.TurnAddressing = addressingMode ?? 'Regex';
|
|
1540
2278
|
row.Address = params.Address;
|
|
1541
2279
|
row.Status = 'Pending';
|
|
1542
2280
|
row.HostInstanceID = this.hostIdentity.GetHostInstanceID();
|
|
@@ -1582,6 +2320,7 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
1582
2320
|
clearTimeout(active.LeaveGraceTimer);
|
|
1583
2321
|
active.LeaveGraceTimer = undefined;
|
|
1584
2322
|
}
|
|
2323
|
+
active.DtmfCoalescer?.Dispose();
|
|
1585
2324
|
// Hand the transcript scribe role to another live session in the room (if this was the scribe), so a
|
|
1586
2325
|
// multi-agent room keeps recording after the first agent leaves. Done before the active map removal.
|
|
1587
2326
|
this.releaseTranscriptScribe(active);
|
|
@@ -1674,4 +2413,59 @@ AIBridgeEngine = __decorate([
|
|
|
1674
2413
|
})
|
|
1675
2414
|
], AIBridgeEngine);
|
|
1676
2415
|
export { AIBridgeEngine };
|
|
2416
|
+
/** The realtime media plane a bridge track feeds: cameras and shared screens are both video to the model. */
|
|
2417
|
+
function mediaKindOf(track) {
|
|
2418
|
+
return track === 'video-in' || track === 'screen-in' ? 'video' : 'audio';
|
|
2419
|
+
}
|
|
2420
|
+
/**
|
|
2421
|
+
* The name a camera or screen gets in a note when its driver gave none, never its `SourceID`: the name for an unnamed
|
|
2422
|
+
* source in `@memberjunction/ai` ({@link UnnamedVideoSourceLabel}), which the LiveKit bridge also gives a person with no
|
|
2423
|
+
* display name.
|
|
2424
|
+
*/
|
|
2425
|
+
function fallbackVideoSourceLabel(track) {
|
|
2426
|
+
return UnnamedVideoSourceLabel(track === 'screen-in' ? 'screen' : 'camera');
|
|
2427
|
+
}
|
|
2428
|
+
/**
|
|
2429
|
+
* What a bridge's first inbound frame tells the diagnostic log: a camera or screen frame means the agent can see it, and
|
|
2430
|
+
* any other frame means the agent hears the room.
|
|
2431
|
+
*/
|
|
2432
|
+
function firstInboundFrameMeaning(track) {
|
|
2433
|
+
switch (track) {
|
|
2434
|
+
case 'video-in':
|
|
2435
|
+
return 'The agent can SEE your camera.';
|
|
2436
|
+
case 'screen-in':
|
|
2437
|
+
return 'The agent can SEE your screen.';
|
|
2438
|
+
default:
|
|
2439
|
+
return 'The agent is HEARING you.';
|
|
2440
|
+
}
|
|
2441
|
+
}
|
|
2442
|
+
/**
|
|
2443
|
+
* What a frame of the agent's video says about its video, for the bridge frame that carries it (`Width`, `Height`,
|
|
2444
|
+
* `KeyFrame`; absent means unknown), copied from the frame. An image always stands alone: a key frame. A chunk says
|
|
2445
|
+
* whether it is a key frame. An fMP4 init segment carries its own size (read from the piece itself, never from an earlier
|
|
2446
|
+
* stream) and no key frame: it holds no frame. An fMP4 fragment with video carries whether its first video frame is a key
|
|
2447
|
+
* frame and the size the stream's init segment gives the video track; an audio-only fragment, a fragment before any init,
|
|
2448
|
+
* or one the driver couldn't read carries nothing.
|
|
2449
|
+
*
|
|
2450
|
+
* @param frame The frame.
|
|
2451
|
+
* @param streamInit The init segment of the stream an fMP4 fragment belongs to, read.
|
|
2452
|
+
*/
|
|
2453
|
+
function frameVideoFacts(frame, streamInit) {
|
|
2454
|
+
const ownSize = frame.Width && frame.Height ? { Width: frame.Width, Height: frame.Height } : {};
|
|
2455
|
+
if (frame.Kind === 'image') {
|
|
2456
|
+
return { ...ownSize, KeyFrame: true };
|
|
2457
|
+
}
|
|
2458
|
+
if (frame.Kind === 'chunk') {
|
|
2459
|
+
return { ...ownSize, KeyFrame: frame.KeyFrame };
|
|
2460
|
+
}
|
|
2461
|
+
if (frame.Piece === 'init') {
|
|
2462
|
+
return ownSize;
|
|
2463
|
+
}
|
|
2464
|
+
if (frame.KeyFrame === undefined) {
|
|
2465
|
+
return {};
|
|
2466
|
+
}
|
|
2467
|
+
const video = streamInit?.Tracks.find((track) => track.Handler === 'vide');
|
|
2468
|
+
const streamSize = video?.Width && video.Height ? { Width: video.Width, Height: video.Height } : {};
|
|
2469
|
+
return { ...streamSize, KeyFrame: frame.KeyFrame };
|
|
2470
|
+
}
|
|
1677
2471
|
//# sourceMappingURL=ai-bridge-engine.js.map
|