@memberjunction/ai-bridge-server 6.2.0-edge.3 → 6.2.0-edge.5
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 +165 -37
- package/dist/ai-bridge-engine.d.ts.map +1 -1
- package/dist/ai-bridge-engine.js +336 -63
- package/dist/ai-bridge-engine.js.map +1 -1
- package/dist/full-duplex-turn-gate.d.ts +19 -1
- package/dist/full-duplex-turn-gate.d.ts.map +1 -1
- package/dist/full-duplex-turn-gate.js +34 -12
- package/dist/full-duplex-turn-gate.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/package.json +6 -6
package/dist/ai-bridge-engine.js
CHANGED
|
@@ -5,7 +5,11 @@ 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';
|
|
12
|
+
import { Fmp4AudioSeconds, InboundVideoRateOf, InboundVideoStreamsOf, IsAgentParticipantIdentity, ReadFmp4Init, UnnamedVideoSourceLabel, VideoSourceEndedNote, VideoSourceSeenNote, } from '@memberjunction/ai';
|
|
9
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';
|
|
11
15
|
import { FullDuplexTurnGate, HumanSpeechDetector } from './full-duplex-turn-gate.js';
|
|
@@ -71,27 +75,35 @@ const AGENT_SESSION_ENTITY = 'MJ: AI Agent Sessions';
|
|
|
71
75
|
const MEETING_REGATE_CONTEXT_NOTE = 'You are now in a multi-party meeting with other people and agents. Stop responding to everything you ' +
|
|
72
76
|
'hear — listen, and speak only when you are addressed by name or the conversation clearly needs your ' +
|
|
73
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+:[^:]+$/;
|
|
74
80
|
/**
|
|
75
|
-
*
|
|
76
|
-
*
|
|
77
|
-
*
|
|
78
|
-
*
|
|
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.
|
|
79
86
|
*/
|
|
80
87
|
export class DefaultHostInstanceIdentity {
|
|
81
88
|
constructor() {
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
const bootId = Math.random().toString(36).slice(2) + Date.now().toString(36);
|
|
85
|
-
this.hostName = 'unknown-host';
|
|
86
|
-
this.instanceId = `${this.hostName}:${pid}:${bootId}`;
|
|
89
|
+
this.instancePrefix = `${hostname()}:pid-${process.pid}:`;
|
|
90
|
+
this.instanceId = `${this.instancePrefix}${process.pid}:${randomUUID()}`;
|
|
87
91
|
}
|
|
88
92
|
/** @inheritdoc */
|
|
89
93
|
GetHostInstanceID() {
|
|
90
94
|
return this.instanceId;
|
|
91
95
|
}
|
|
92
96
|
/** @inheritdoc */
|
|
93
|
-
|
|
94
|
-
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));
|
|
95
107
|
}
|
|
96
108
|
}
|
|
97
109
|
/**
|
|
@@ -117,8 +129,8 @@ export class DefaultHostInstanceIdentity {
|
|
|
117
129
|
* `AIAgentSessionBridgeParticipant` rows.
|
|
118
130
|
* - **Turn-taking integration** — holds a {@link TurnTakingPolicy} per session and feeds diarized
|
|
119
131
|
* transcript segments through it, acting on the decision (Speak / PostToChat / Silent).
|
|
120
|
-
* - **Janitor scaffold** — {@link ReconcileOrphans} force-closes Connected bridges left by
|
|
121
|
-
*
|
|
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.
|
|
122
134
|
*
|
|
123
135
|
* The engine never constructs the realtime model: the {@link IRealtimeSession} is injected via
|
|
124
136
|
* {@link StartBridgeSessionParams}, keeping the only coupling the transport seam itself and making
|
|
@@ -136,8 +148,12 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
136
148
|
this.floorMaxHoldMs = FLOOR_MAX_HOLD_MS;
|
|
137
149
|
/** roomKey (lowercased) → the bridge id of that room's current transcript scribe. Election dedup. */
|
|
138
150
|
this.roomScribes = new Map();
|
|
139
|
-
/**
|
|
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
|
+
*/
|
|
140
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}. */
|
|
141
157
|
this.diagOutbound = new Set();
|
|
142
158
|
/** In-memory registry of bridged sessions this process currently hosts, keyed by bridge id (lowercased). */
|
|
143
159
|
this.activeSessions = new Map();
|
|
@@ -185,7 +201,11 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
185
201
|
/**
|
|
186
202
|
* Deferred-startup entry point (per {@link IStartupSink}). Warms the ONE composed base cache by
|
|
187
203
|
* delegating to {@link AIBridgeEngineBase.Config}; mirrors `AIEngine.HandleStartup`. No double
|
|
188
|
-
* 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.
|
|
189
209
|
*
|
|
190
210
|
* @param contextUser The boot/system user context.
|
|
191
211
|
* @param provider Optional metadata provider override (multi-provider scenarios).
|
|
@@ -195,10 +215,6 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
195
215
|
// Begin reaping stale live sessions (idle / over-duration) — the same-process backstop to the
|
|
196
216
|
// occupancy auto-leave + the prior-boot orphan reconcile. Idempotent.
|
|
197
217
|
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
|
-
}
|
|
202
218
|
}
|
|
203
219
|
/**
|
|
204
220
|
* Loads (or refreshes) the composed base's bridge metadata cache. Delegates to
|
|
@@ -306,11 +322,12 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
306
322
|
return this.Base.DefaultChannelsForProvider(providerId);
|
|
307
323
|
}
|
|
308
324
|
/**
|
|
309
|
-
* Injects the
|
|
310
|
-
*
|
|
311
|
-
*
|
|
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}.
|
|
312
329
|
*
|
|
313
|
-
* @param identity The identity
|
|
330
|
+
* @param identity The identity to use.
|
|
314
331
|
*/
|
|
315
332
|
SetHostInstanceIdentity(identity) {
|
|
316
333
|
this.hostIdentity = identity;
|
|
@@ -386,7 +403,7 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
386
403
|
* @throws When the driver cannot be resolved or `Connect` fails (the row is stamped `Failed`).
|
|
387
404
|
*/
|
|
388
405
|
async StartBridgeSession(params) {
|
|
389
|
-
const fullDuplex = params.RealtimeSession.Capabilities?.FullDuplex === true;
|
|
406
|
+
const fullDuplex = params.FullDuplex ?? params.RealtimeSession.Capabilities?.FullDuplex === true;
|
|
390
407
|
const turn = this.buildTurnPolicy(params, fullDuplex);
|
|
391
408
|
const bridgeRow = await this.createBridgeRow(params, turn.Mode);
|
|
392
409
|
try {
|
|
@@ -414,6 +431,7 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
414
431
|
TurnPolicy: turn.Policy,
|
|
415
432
|
AddressingMode: turn.Mode,
|
|
416
433
|
ModelSideMatcher: turn.ModelSide,
|
|
434
|
+
FullDuplex: fullDuplex,
|
|
417
435
|
DisableAutoResponse: params.DisableAutoResponse === true,
|
|
418
436
|
HasSeenHuman: false,
|
|
419
437
|
RoomKey: result.ExternalConnectionId,
|
|
@@ -435,12 +453,14 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
435
453
|
TranscriptSink: params.TranscriptSink,
|
|
436
454
|
OnBargeIn: params.OnBargeIn,
|
|
437
455
|
RecoverRealtimeSession: params.RecoverRealtimeSession,
|
|
456
|
+
RecoverRealtimeSessionWithoutAvatar: params.RecoverRealtimeSessionWithoutAvatar,
|
|
438
457
|
OnSessionEnded: params.OnSessionEnded,
|
|
439
458
|
TranscriptTail: [],
|
|
440
459
|
ModelRecoveryAttempts: 0,
|
|
441
460
|
ModelRecovering: false,
|
|
442
461
|
Ending: false,
|
|
443
462
|
LastSessionHeartbeatMs: Date.now(),
|
|
463
|
+
SeenVideoSources: new Map(),
|
|
444
464
|
};
|
|
445
465
|
this.electTranscriptScribe(active);
|
|
446
466
|
// Join the room's floor-control roster (keyed on the shared room). For a single-agent room this
|
|
@@ -484,6 +504,10 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
484
504
|
active.Ending = true; // ignore model-loss signals that race the teardown
|
|
485
505
|
await this.disconnectDriver(active, reason);
|
|
486
506
|
this.activeSessions.delete(key);
|
|
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);
|
|
487
511
|
const done = await this.markBridgeDisconnected(sessionBridgeID, reason, active.ContextUser ?? contextUser, active.MetadataProvider ?? provider);
|
|
488
512
|
await this.runSessionEndedHook(active, reason);
|
|
489
513
|
return done;
|
|
@@ -510,9 +534,11 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
510
534
|
* that pipe.
|
|
511
535
|
*
|
|
512
536
|
* Two hooks, one per direction:
|
|
513
|
-
* - **Inbound** (`bridge.OnMedia` → `session.SendInput`): what the agent HEARS
|
|
514
|
-
* {@link BridgeMediaFrame} from the endpoint is unwrapped to its raw `ArrayBuffer` payload and
|
|
515
|
-
* 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}).
|
|
516
542
|
* - **Outbound** (`session.OnOutput` → `bridge.SendMedia`): what the agent SAYS. Each model
|
|
517
543
|
* output `ArrayBuffer` is wrapped in an outbound audio {@link BridgeMediaFrame} and sent into
|
|
518
544
|
* the meeting/call.
|
|
@@ -530,9 +556,11 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
530
556
|
// directly with the AI provider. MJ is NOT in the media relay path.
|
|
531
557
|
return;
|
|
532
558
|
}
|
|
533
|
-
// Inbound: endpoint media → the agent hears (and, for a video model, SEES) it. The frame's
|
|
534
|
-
//
|
|
535
|
-
//
|
|
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;
|
|
536
564
|
Bridge.OnMedia((frame) => {
|
|
537
565
|
active.LastActivityMs = Date.now();
|
|
538
566
|
// DIARIZATION: the inbound frame carries the speaking participant's identity (when the provider
|
|
@@ -542,16 +570,70 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
542
570
|
if (frame.Track === 'audio-in' && frame.SpeakerLabel) {
|
|
543
571
|
active.LastInboundSpeaker = frame.SpeakerLabel;
|
|
544
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
|
+
}
|
|
545
581
|
const chunk = this.frameToArrayBuffer(frame);
|
|
546
582
|
this.observeInboundHumanSpeech(active, frame, chunk);
|
|
547
583
|
if (chunk && !active.ModelRecovering) {
|
|
548
|
-
if (!this.diagInbound.has(active.SessionBridgeID)) {
|
|
584
|
+
if (!active.Ending && !this.diagInbound.has(active.SessionBridgeID)) {
|
|
549
585
|
this.diagInbound.add(active.SessionBridgeID);
|
|
550
|
-
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 });
|
|
551
587
|
}
|
|
552
|
-
|
|
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
|
+
});
|
|
553
597
|
}
|
|
554
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));
|
|
555
637
|
}
|
|
556
638
|
/**
|
|
557
639
|
* Wires everything that hangs off the MODEL session: barge-in, the lifecycle (drop) signals, and — unless the
|
|
@@ -563,6 +645,8 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
563
645
|
wireModelSession(active) {
|
|
564
646
|
const { Bridge } = active;
|
|
565
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();
|
|
566
650
|
// Barge-in: on a TRUE interruption (the user speaks over the agent), the model stops generating —
|
|
567
651
|
// but the driver may still hold queued outbound audio that would keep playing. Flush it so the
|
|
568
652
|
// agent goes quiet immediately. Without this, interruption "doesn't work" on the bridge surface.
|
|
@@ -577,7 +661,15 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
577
661
|
return; // a stale (replaced) session
|
|
578
662
|
}
|
|
579
663
|
active.LastActivityMs = Date.now();
|
|
580
|
-
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)) {
|
|
581
673
|
this.diagOutbound.add(active.SessionBridgeID);
|
|
582
674
|
LogStatusEx({ message: `[AIBridgeEngine][diag] FIRST outbound audio from the agent (bridge ${active.SessionBridgeID}). The agent is SPEAKING into the room.`, verboseOnly: true });
|
|
583
675
|
}
|
|
@@ -591,9 +683,11 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
591
683
|
const track = 'audio-out';
|
|
592
684
|
Bridge.SendMedia(track, this.arrayBufferToFrame(chunk, track));
|
|
593
685
|
});
|
|
594
|
-
// Outbound VIDEO: a video-capable session
|
|
595
|
-
// audio-only sessions don't implement
|
|
596
|
-
// gates the actual publish on its `VideoOut` capability.
|
|
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).
|
|
597
691
|
session.OnVideoOutput?.((chunk) => {
|
|
598
692
|
if (active.RealtimeSession !== session) {
|
|
599
693
|
return;
|
|
@@ -603,8 +697,53 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
603
697
|
Bridge.SendMedia(track, this.arrayBufferToFrame(chunk, track));
|
|
604
698
|
});
|
|
605
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
|
+
}
|
|
606
744
|
/** A true barge-in: flush queued audio, drop stale room moderator state, free the floor, tell the host. */
|
|
607
745
|
handleBargeIn(active) {
|
|
746
|
+
active.LastUserSpeechEndMs = undefined;
|
|
608
747
|
if (this.diagOutbound.has(active.SessionBridgeID)) {
|
|
609
748
|
LogStatusEx({ message: `[AIBridgeEngine][diag] barge-in — flushing the agent's queued audio (bridge ${active.SessionBridgeID}).`, verboseOnly: true });
|
|
610
749
|
}
|
|
@@ -785,7 +924,7 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
785
924
|
}
|
|
786
925
|
}
|
|
787
926
|
/** 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) {
|
|
927
|
+
async adoptRecoveredSession(active, lost, fresh, note = `attempt ${active.ModelRecoveryAttempts}`) {
|
|
789
928
|
const sameRates = (fresh.InputSampleRate ?? 24000) === (lost.InputSampleRate ?? 24000) && (fresh.OutputSampleRate ?? 24000) === (lost.OutputSampleRate ?? 24000);
|
|
790
929
|
if (active.Ending || !sameRates) {
|
|
791
930
|
await this.closeQuietly(fresh);
|
|
@@ -795,9 +934,35 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
795
934
|
this.wireModelSession(active);
|
|
796
935
|
this.wireTurnTaking(active);
|
|
797
936
|
active.ModelRecovering = false;
|
|
798
|
-
LogStatus(`[AIBridgeEngine] model session re-opened for bridge ${active.SessionBridgeID} (
|
|
937
|
+
LogStatus(`[AIBridgeEngine] model session re-opened for bridge ${active.SessionBridgeID} (${note}).`);
|
|
799
938
|
await this.closeQuietly(lost); // releases the dead socket and finalizes its observability run
|
|
800
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
|
+
}
|
|
801
966
|
/** Ends a call whose model session cannot be recovered: a spoken goodbye at the carrier (telephony), then a clean stop. */
|
|
802
967
|
async endCallAfterModelLoss(active) {
|
|
803
968
|
if (active.Ending) {
|
|
@@ -953,6 +1118,9 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
953
1118
|
return; // partials fire per-word — act only on a completed turn (and don't flood the log)
|
|
954
1119
|
}
|
|
955
1120
|
LogStatusEx({ message: `[AIBridgeEngine][diag] transcript(final): role=${t.Role} text="${(t.Text ?? '').slice(0, 80)}" (bridge ${active.SessionBridgeID})`, verboseOnly: true });
|
|
1121
|
+
if (t.Role === 'user') {
|
|
1122
|
+
active.LastUserSpeechEndMs = performance.now();
|
|
1123
|
+
}
|
|
956
1124
|
if (t.Role === 'user' || t.Role === 'assistant') {
|
|
957
1125
|
AppendTranscriptTurn(active.TranscriptTail, { Role: t.Role, Text: t.Text ?? '' });
|
|
958
1126
|
}
|
|
@@ -997,9 +1165,9 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
997
1165
|
// Only a REAL human turn counts as presence. In a multi-agent room every agent transcribes its peers'
|
|
998
1166
|
// speech as a 'user' turn (it has no other role to assign overheard audio); if those counted as a human,
|
|
999
1167
|
// an agents-only room would keep cancelling its own auto-leave and babble forever after the humans left —
|
|
1000
|
-
// burning realtime tokens at full cost. The diarized inbound speaker tells us: an
|
|
1001
|
-
// peer agent, NOT a human, so it must NOT keep the room alive.
|
|
1002
|
-
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);
|
|
1003
1171
|
if (!overheardAgent) {
|
|
1004
1172
|
// A real human just spoke → definitive presence for EVERY agent in the room. Cancel any pending
|
|
1005
1173
|
// empty-room auto-leave + reset the consecutive-agent-only counter.
|
|
@@ -1091,7 +1259,7 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
1091
1259
|
if (!active.IsTranscriptScribe) {
|
|
1092
1260
|
return; // only the scribe records human turns (avoids one copy per transcribing agent)
|
|
1093
1261
|
}
|
|
1094
|
-
if (active.LastInboundSpeaker
|
|
1262
|
+
if (IsAgentParticipantIdentity(active.LastInboundSpeaker)) {
|
|
1095
1263
|
return; // the scribe is overhearing another agent — that agent's own bridge records it
|
|
1096
1264
|
}
|
|
1097
1265
|
}
|
|
@@ -1320,8 +1488,10 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
1320
1488
|
// Full-duplex turn-taking — the room floor as a safety net behind the model's own judgement.
|
|
1321
1489
|
// ──────────────────────────────────────────────────────────────────────────────
|
|
1322
1490
|
/**
|
|
1323
|
-
* Gives a FULL-DUPLEX model the floor gate + human-speech detector (see {@link FullDuplexTurnGate})
|
|
1324
|
-
*
|
|
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.
|
|
1325
1495
|
*
|
|
1326
1496
|
* @param active The freshly connected session.
|
|
1327
1497
|
* @param params The start parameters (`FullDuplexTurnGate: false` opts out).
|
|
@@ -1330,7 +1500,11 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
1330
1500
|
if (!active.RoomKey || params.FullDuplexTurnGate === false) {
|
|
1331
1501
|
return;
|
|
1332
1502
|
}
|
|
1333
|
-
if (active.
|
|
1503
|
+
if (!active.FullDuplex) {
|
|
1504
|
+
return;
|
|
1505
|
+
}
|
|
1506
|
+
const moderatorMode = process.env.MJ_REALTIME_MODERATOR_MODE === 'on';
|
|
1507
|
+
if (!moderatorMode && params.FullDuplexTurnGate !== true) {
|
|
1334
1508
|
return;
|
|
1335
1509
|
}
|
|
1336
1510
|
active.TurnGate = new FullDuplexTurnGate({
|
|
@@ -1350,11 +1524,25 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
1350
1524
|
* @returns Whether to forward the chunk, drop it, or cut the burst (drop + flush queued audio).
|
|
1351
1525
|
*/
|
|
1352
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) {
|
|
1353
1541
|
const gate = active.TurnGate;
|
|
1354
1542
|
if (!gate || !active.RoomKey || !this.roomCoordinator.IsMultiAgentRoom(active.RoomKey)) {
|
|
1355
1543
|
return 'Forward';
|
|
1356
1544
|
}
|
|
1357
|
-
const result = gate
|
|
1545
|
+
const result = decide(gate);
|
|
1358
1546
|
if (result.TookFloor) {
|
|
1359
1547
|
this.armFloorHold(active);
|
|
1360
1548
|
}
|
|
@@ -1365,7 +1553,7 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
1365
1553
|
}
|
|
1366
1554
|
/** Whether an inbound speaker label belongs to a human (diarized, and not a peer `agent-…` bot). */
|
|
1367
1555
|
isHumanSpeaker(label) {
|
|
1368
|
-
return label !== undefined && label.length > 0 && !label
|
|
1556
|
+
return label !== undefined && label.length > 0 && !IsAgentParticipantIdentity(label);
|
|
1369
1557
|
}
|
|
1370
1558
|
/**
|
|
1371
1559
|
* Watches inbound room audio for a human speaking and, on the first activity, makes every agent yield.
|
|
@@ -1413,6 +1601,11 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
1413
1601
|
* @param active The live bridged session.
|
|
1414
1602
|
*/
|
|
1415
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
|
+
}
|
|
1416
1609
|
if (!active.RoomKey || !(active.AddressingMode === 'ModelSide' || active.TurnGate)) {
|
|
1417
1610
|
return;
|
|
1418
1611
|
}
|
|
@@ -1433,7 +1626,12 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
1433
1626
|
if (!roomKey || !this.roomCoordinator.IsMultiAgentRoom(roomKey)) {
|
|
1434
1627
|
return;
|
|
1435
1628
|
}
|
|
1629
|
+
const moderatorMode = process.env.MJ_REALTIME_MODERATOR_MODE === 'on';
|
|
1436
1630
|
for (const agent of this.roomAgents(roomKey)) {
|
|
1631
|
+
const isFullDuplex = agent.FullDuplex;
|
|
1632
|
+
if (isFullDuplex && !moderatorMode) {
|
|
1633
|
+
continue;
|
|
1634
|
+
}
|
|
1437
1635
|
if (agent.TurnTakingToolHandler && !agent.TurnTakingAnnounced) {
|
|
1438
1636
|
agent.RealtimeSession.SendContextNote?.(MODEL_SIDE_TURN_TAKING_FRAMING);
|
|
1439
1637
|
agent.TurnTakingAnnounced = true;
|
|
@@ -1538,7 +1736,7 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
1538
1736
|
Names: a.AgentNames,
|
|
1539
1737
|
TurnMode: a.TurnPolicy.Mode,
|
|
1540
1738
|
Addressing: a.AddressingMode ?? 'Regex',
|
|
1541
|
-
FullDuplex: a.
|
|
1739
|
+
FullDuplex: a.FullDuplex,
|
|
1542
1740
|
}));
|
|
1543
1741
|
return { ...state, Agents: agents };
|
|
1544
1742
|
}
|
|
@@ -1550,13 +1748,16 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
1550
1748
|
* @returns The configured policy plus the addressing mode in effect and the model-side latch, when any.
|
|
1551
1749
|
*/
|
|
1552
1750
|
buildTurnPolicy(params, fullDuplex) {
|
|
1751
|
+
const moderatorMode = process.env.MJ_REALTIME_MODERATOR_MODE === 'on';
|
|
1553
1752
|
let matcher = params.TurnMatcher;
|
|
1554
1753
|
let mode = 'Regex';
|
|
1555
1754
|
let modelSide;
|
|
1556
1755
|
if (params.TurnAddressing !== undefined) {
|
|
1557
|
-
//
|
|
1558
|
-
//
|
|
1559
|
-
|
|
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);
|
|
1560
1761
|
mode = built.Mode;
|
|
1561
1762
|
modelSide = built.ModelSide;
|
|
1562
1763
|
matcher = built.Mode === 'ModelSide' ? built.Matcher : (params.TurnMatcher ?? built.Matcher);
|
|
@@ -1893,8 +2094,12 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
1893
2094
|
* Reconciles prior-boot orphans ({@link ReconcileOrphans}) once now and then every
|
|
1894
2095
|
* {@link ORPHAN_RECONCILE_INTERVAL_MS}. Idempotent — a no-op while already scheduled. The timer is `unref`'d.
|
|
1895
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
|
+
*
|
|
1896
2100
|
* @param contextUser The user the reconciliation writes run as.
|
|
1897
2101
|
* @param provider The metadata provider for the reads/writes.
|
|
2102
|
+
* @param intervalMs How often to reconcile after the first pass.
|
|
1898
2103
|
*/
|
|
1899
2104
|
StartOrphanReconciliation(contextUser, provider, intervalMs = ORPHAN_RECONCILE_INTERVAL_MS) {
|
|
1900
2105
|
if (this.orphanReconcileTimer) {
|
|
@@ -1922,39 +2127,48 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
1922
2127
|
}
|
|
1923
2128
|
}
|
|
1924
2129
|
/**
|
|
1925
|
-
* Force-closes `Connected`/`Connecting` bridges
|
|
1926
|
-
*
|
|
1927
|
-
*
|
|
1928
|
-
*
|
|
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.
|
|
1929
2139
|
*
|
|
1930
|
-
*
|
|
1931
|
-
* application (MJServer's startup + janitor timer) so this engine package carries no timer/IO of
|
|
1932
|
-
* its own; call this method from that scheduler.
|
|
2140
|
+
* Run it only once this process owns its instance; {@link StartOrphanReconciliation} schedules it.
|
|
1933
2141
|
*
|
|
1934
2142
|
* @param contextUser The system user the reconciliation writes run as.
|
|
1935
2143
|
* @param provider The metadata provider for the reconciliation reads/writes.
|
|
1936
2144
|
* @returns The number of orphaned bridges closed.
|
|
1937
2145
|
*/
|
|
1938
2146
|
async ReconcileOrphans(contextUser, provider) {
|
|
1939
|
-
const
|
|
1940
|
-
const
|
|
2147
|
+
const identity = this.hostIdentity;
|
|
2148
|
+
const prefix = EscapeSQLString(identity.GetInstancePrefix());
|
|
2149
|
+
const current = EscapeSQLString(identity.GetHostInstanceID());
|
|
1941
2150
|
const filter = `Status IN ('Connecting','Connected') ` +
|
|
1942
2151
|
`AND HostInstanceID LIKE '${prefix}%' ` +
|
|
1943
2152
|
`AND HostInstanceID <> '${current}'`;
|
|
1944
2153
|
const rows = await this.loadOrphanRows(filter, contextUser, provider);
|
|
1945
2154
|
let closed = 0;
|
|
1946
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
|
+
}
|
|
1947
2160
|
const ok = await this.markBridgeDisconnected(row.ID, 'Janitor', contextUser, provider);
|
|
1948
2161
|
if (ok) {
|
|
1949
2162
|
closed++;
|
|
1950
2163
|
}
|
|
1951
2164
|
}
|
|
1952
2165
|
if (closed > 0) {
|
|
1953
|
-
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()})`);
|
|
1954
2168
|
}
|
|
1955
2169
|
return closed;
|
|
1956
2170
|
}
|
|
1957
|
-
/** Loads the
|
|
2171
|
+
/** Loads the bridge rows the janitor filter matches: the candidates {@link ReconcileOrphans} checks one by one. */
|
|
1958
2172
|
async loadOrphanRows(filter, contextUser, provider) {
|
|
1959
2173
|
const rv = RunView.FromMetadataProvider(provider);
|
|
1960
2174
|
const result = await rv.RunView({
|
|
@@ -2033,6 +2247,10 @@ let AIBridgeEngine = class AIBridgeEngine extends BaseSingleton {
|
|
|
2033
2247
|
...params.Configuration,
|
|
2034
2248
|
InboundSampleRate: params.RealtimeSession.InputSampleRate ?? 24000,
|
|
2035
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),
|
|
2036
2254
|
},
|
|
2037
2255
|
ContextUser: params.ContextUser,
|
|
2038
2256
|
};
|
|
@@ -2195,4 +2413,59 @@ AIBridgeEngine = __decorate([
|
|
|
2195
2413
|
})
|
|
2196
2414
|
], AIBridgeEngine);
|
|
2197
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
|
+
}
|
|
2198
2471
|
//# sourceMappingURL=ai-bridge-engine.js.map
|