@memberjunction/ai-bridge-server 0.0.1 → 5.42.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +120 -42
- package/dist/ai-bridge-engine.d.ts +663 -0
- package/dist/ai-bridge-engine.d.ts.map +1 -0
- package/dist/ai-bridge-engine.js +1085 -0
- package/dist/ai-bridge-engine.js.map +1 -0
- package/dist/calendar-source.d.ts +142 -0
- package/dist/calendar-source.d.ts.map +1 -0
- package/dist/calendar-source.js +63 -0
- package/dist/calendar-source.js.map +1 -0
- package/dist/calendar-watcher.d.ts +174 -0
- package/dist/calendar-watcher.d.ts.map +1 -0
- package/dist/calendar-watcher.js +248 -0
- package/dist/calendar-watcher.js.map +1 -0
- package/dist/identity-provisioner.d.ts +109 -0
- package/dist/identity-provisioner.d.ts.map +1 -0
- package/dist/identity-provisioner.js +71 -0
- package/dist/identity-provisioner.js.map +1 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +9 -0
- package/dist/index.js.map +1 -0
- package/dist/join-url-resolver.d.ts +37 -0
- package/dist/join-url-resolver.d.ts.map +1 -0
- package/dist/join-url-resolver.js +102 -0
- package/dist/join-url-resolver.js.map +1 -0
- package/dist/loopback-bridge.d.ts +165 -0
- package/dist/loopback-bridge.d.ts.map +1 -0
- package/dist/loopback-bridge.js +255 -0
- package/dist/loopback-bridge.js.map +1 -0
- package/dist/multi-agent-room-coordinator.d.ts +198 -0
- package/dist/multi-agent-room-coordinator.d.ts.map +1 -0
- package/dist/multi-agent-room-coordinator.js +296 -0
- package/dist/multi-agent-room-coordinator.js.map +1 -0
- package/dist/scheduled-bridge-runner.d.ts +126 -0
- package/dist/scheduled-bridge-runner.d.ts.map +1 -0
- package/dist/scheduled-bridge-runner.js +140 -0
- package/dist/scheduled-bridge-runner.js.map +1 -0
- package/package.json +34 -7
|
@@ -0,0 +1,296 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Multi-agent room coordination — the inter-agent **speaking discipline** for "1+ agents in one shared
|
|
3
|
+
* room" (`/plans/realtime/realtime-bridges-architecture.md` §4c).
|
|
4
|
+
*
|
|
5
|
+
* ## The model — the room IS the shared media plane; this only adds discipline
|
|
6
|
+
* Multi-party is an **emergent property of the bridge**, not a separate build. When several agents each
|
|
7
|
+
* open their OWN bridge connection into the SAME room (a Zoom meeting, a Teams meeting, or an MJ-native
|
|
8
|
+
* LiveKit room), the conferencing platform *is* the shared media plane: it does the SFU, the mixing, the
|
|
9
|
+
* multi-party transport. **Each agent hears the others through the room's own mix** — Sage's voice is
|
|
10
|
+
* part of "everyone else" in Demo Loop's inbound audio and vice-versa. There is NO transcript-relay hack
|
|
11
|
+
* and NO mixer in MJ; the room already mixes.
|
|
12
|
+
*
|
|
13
|
+
* So the ONLY genuinely new problem is **turn-taking discipline among multiple agents** so they don't
|
|
14
|
+
* talk over each other or loop forever. This coordinator solves exactly that and nothing else:
|
|
15
|
+
*
|
|
16
|
+
* 1. **Floor arbitration** — at most ONE agent "holds the floor" (is speaking) in a room at any instant.
|
|
17
|
+
* An agent calls {@link CanTakeFloor} before generating speech; it returns `true` only if no OTHER
|
|
18
|
+
* agent currently holds the floor. {@link TakeFloor} grants it; {@link ReleaseFloor} frees it.
|
|
19
|
+
* 2. **Passive-default loop safety** — combined with passive turn-taking (an agent speaks only when
|
|
20
|
+
* *addressed by name*, per {@link import('@memberjunction/ai-bridge-base').TurnTakingPolicy}), two
|
|
21
|
+
* agents in a room never loop: neither speaks unless a human calls on it, and even then only one holds
|
|
22
|
+
* the floor. This coordinator is the SECOND guard — passivity prevents the loop, the floor prevents
|
|
23
|
+
* the overlap.
|
|
24
|
+
* 3. **Facilitator override** — an optional designated **facilitator** agent (one that runs the Meeting
|
|
25
|
+
* Controls channel) may be granted the floor even while another agent holds it, so it can arbitrate /
|
|
26
|
+
* call on a specific agent. See {@link RegisterRoom}'s `facilitatorAgentSessionId` and
|
|
27
|
+
* {@link CanTakeFloor}'s facilitator path.
|
|
28
|
+
*
|
|
29
|
+
* ## Echo / self-audio (documented, handled by the bridge, not here)
|
|
30
|
+
* A bot must not hear its OWN output, or it would react to itself and loop. Conferencing platforms
|
|
31
|
+
* (and the LiveKit SFU) **exclude a participant's own published audio from that participant's inbound
|
|
32
|
+
* mix**, so the bridge driver naturally never feeds the agent its own voice — the LiveKitBridge documents
|
|
33
|
+
* this explicitly. Where a platform does NOT exclude own-audio, the bridge driver must gate it before
|
|
34
|
+
* `OnMedia`. This coordinator assumes that property holds and does not itself touch media — it operates
|
|
35
|
+
* purely on floor state.
|
|
36
|
+
*
|
|
37
|
+
* ## Purity & testability
|
|
38
|
+
* This class is **pure and synchronous** — no I/O, no entities, no clock dependence (an optional injected
|
|
39
|
+
* clock only stamps `since` for observability). Every decision is a deterministic function of the
|
|
40
|
+
* in-memory room/floor state, so it is exhaustively unit-testable with no network, DB, or real session.
|
|
41
|
+
*/
|
|
42
|
+
/**
|
|
43
|
+
* Coordinates speaking discipline for multiple agents sharing one room. Construct one per process (the
|
|
44
|
+
* engine holds a single instance) and key everything on the **room id** — the shared external connection
|
|
45
|
+
* id (or ConversationID) that all co-located agent sessions belong to.
|
|
46
|
+
*
|
|
47
|
+
* The coordinator is additive: single-agent sessions never register here and are wholly unaffected. Only
|
|
48
|
+
* when 2+ agent sessions share a room does floor arbitration come into play.
|
|
49
|
+
*/
|
|
50
|
+
export class MultiAgentRoomCoordinator {
|
|
51
|
+
/**
|
|
52
|
+
* @param now Optional injected clock returning epoch-ms (for `FloorHeldSince` stamps). Defaults to
|
|
53
|
+
* `Date.now`. Tests inject a controllable function for determinism.
|
|
54
|
+
*/
|
|
55
|
+
constructor(now = Date.now) {
|
|
56
|
+
/** Room id (lowercased) → room record. */
|
|
57
|
+
this.rooms = new Map();
|
|
58
|
+
this.now = now;
|
|
59
|
+
}
|
|
60
|
+
// ──────────────────────────────────────────────────────────────────────────────
|
|
61
|
+
// Membership.
|
|
62
|
+
// ──────────────────────────────────────────────────────────────────────────────
|
|
63
|
+
/**
|
|
64
|
+
* Registers an agent session as a participant in a shared room, creating the room on first member.
|
|
65
|
+
* Idempotent — re-registering the same agent updates its facilitator flag without disturbing the
|
|
66
|
+
* floor. Designating an agent as the facilitator records it as the room's arbiter; only one
|
|
67
|
+
* facilitator is tracked (the latest designation wins, mirroring "one chair").
|
|
68
|
+
*
|
|
69
|
+
* @param roomId The shared room id (external connection id / ConversationID) all agents key on.
|
|
70
|
+
* @param agentSessionId The agent's `MJ: AI Agent Sessions` row id.
|
|
71
|
+
* @param isFacilitator Whether this agent is the room's facilitator (may override the floor).
|
|
72
|
+
*/
|
|
73
|
+
RegisterRoomParticipant(roomId, agentSessionId, isFacilitator = false) {
|
|
74
|
+
const room = this.ensureRoom(roomId);
|
|
75
|
+
const memberKey = this.key(agentSessionId);
|
|
76
|
+
room.members.set(memberKey, { AgentSessionId: agentSessionId, IsFacilitator: isFacilitator });
|
|
77
|
+
if (isFacilitator) {
|
|
78
|
+
room.facilitatorAgentSessionId = agentSessionId;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Unregisters an agent session from a room (the agent left / its bridge stopped). If the leaving
|
|
83
|
+
* agent held the floor, the floor is released. If it was the facilitator, the facilitator slot is
|
|
84
|
+
* cleared. When the last member leaves, the room record is discarded.
|
|
85
|
+
*
|
|
86
|
+
* @param roomId The room the agent is leaving.
|
|
87
|
+
* @param agentSessionId The agent session leaving.
|
|
88
|
+
*/
|
|
89
|
+
UnregisterRoomParticipant(roomId, agentSessionId) {
|
|
90
|
+
const room = this.rooms.get(this.key(roomId));
|
|
91
|
+
if (!room) {
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
const memberKey = this.key(agentSessionId);
|
|
95
|
+
room.members.delete(memberKey);
|
|
96
|
+
if (room.floorHolderAgentSessionId && this.key(room.floorHolderAgentSessionId) === memberKey) {
|
|
97
|
+
room.floorHolderAgentSessionId = null;
|
|
98
|
+
room.floorHeldSinceMs = null;
|
|
99
|
+
}
|
|
100
|
+
if (room.facilitatorAgentSessionId && this.key(room.facilitatorAgentSessionId) === memberKey) {
|
|
101
|
+
room.facilitatorAgentSessionId = null;
|
|
102
|
+
}
|
|
103
|
+
if (room.members.size === 0) {
|
|
104
|
+
this.rooms.delete(this.key(roomId));
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Whether a room currently has more than one agent session — i.e. floor arbitration is meaningful.
|
|
109
|
+
* Single-agent rooms can skip the floor dance entirely.
|
|
110
|
+
*
|
|
111
|
+
* @param roomId The room to check.
|
|
112
|
+
* @returns `true` when 2+ agents share the room.
|
|
113
|
+
*/
|
|
114
|
+
IsMultiAgentRoom(roomId) {
|
|
115
|
+
const room = this.rooms.get(this.key(roomId));
|
|
116
|
+
return room ? room.members.size > 1 : false;
|
|
117
|
+
}
|
|
118
|
+
// ──────────────────────────────────────────────────────────────────────────────
|
|
119
|
+
// Floor arbitration.
|
|
120
|
+
// ──────────────────────────────────────────────────────────────────────────────
|
|
121
|
+
/**
|
|
122
|
+
* Asks whether an agent MAY take the floor (speak) now — the read-only arbitration check an agent
|
|
123
|
+
* runs before generating speech. Returns `true` only when no OTHER agent holds the floor, with the
|
|
124
|
+
* facilitator exception:
|
|
125
|
+
*
|
|
126
|
+
* - **Floor free** → granted (`FloorFree`).
|
|
127
|
+
* - **The requester already holds it** → granted (`AlreadyHolder`) — re-asserting is fine.
|
|
128
|
+
* - **The requester is the facilitator** → granted (`FacilitatorOverride`) even if another agent
|
|
129
|
+
* holds it, so the facilitator can cut in to arbitrate / call on a specific agent.
|
|
130
|
+
* - **Another (non-facilitator) agent holds it** → denied (`HeldByOtherAgent`).
|
|
131
|
+
* - **The requester is not a member of the room** → denied (`NotInRoom`).
|
|
132
|
+
* - **The room is unknown** → denied (`UnknownRoom`).
|
|
133
|
+
*
|
|
134
|
+
* This is purely advisory until {@link TakeFloor} actually claims the floor — keeping the check
|
|
135
|
+
* (read) and the claim (write) separate lets a caller test-then-act atomically within its own turn.
|
|
136
|
+
*
|
|
137
|
+
* @param roomId The shared room id.
|
|
138
|
+
* @param agentSessionId The agent asking to speak.
|
|
139
|
+
* @returns The floor decision (granted + reason).
|
|
140
|
+
*/
|
|
141
|
+
CanTakeFloor(roomId, agentSessionId) {
|
|
142
|
+
const room = this.rooms.get(this.key(roomId));
|
|
143
|
+
if (!room) {
|
|
144
|
+
return { Granted: false, Reason: 'UnknownRoom' };
|
|
145
|
+
}
|
|
146
|
+
if (!room.members.has(this.key(agentSessionId))) {
|
|
147
|
+
return { Granted: false, Reason: 'NotInRoom' };
|
|
148
|
+
}
|
|
149
|
+
const holder = room.floorHolderAgentSessionId;
|
|
150
|
+
if (holder === null) {
|
|
151
|
+
return { Granted: true, Reason: 'FloorFree' };
|
|
152
|
+
}
|
|
153
|
+
if (this.key(holder) === this.key(agentSessionId)) {
|
|
154
|
+
return { Granted: true, Reason: 'AlreadyHolder' };
|
|
155
|
+
}
|
|
156
|
+
if (this.isFacilitator(room, agentSessionId)) {
|
|
157
|
+
return { Granted: true, Reason: 'FacilitatorOverride' };
|
|
158
|
+
}
|
|
159
|
+
return { Granted: false, Reason: 'HeldByOtherAgent' };
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* Atomically attempts to claim the floor for an agent: runs {@link CanTakeFloor} and, when granted,
|
|
163
|
+
* records the agent as the floor holder (stamping the take time) and returns the decision. When a
|
|
164
|
+
* **facilitator** overrides a sitting holder, the holder is replaced — the facilitator now holds the
|
|
165
|
+
* floor (the prior holder should observe this via {@link IsFloorHolder} on its next check and yield).
|
|
166
|
+
*
|
|
167
|
+
* @param roomId The shared room id.
|
|
168
|
+
* @param agentSessionId The agent claiming the floor.
|
|
169
|
+
* @returns The decision; on `Granted` the agent now holds the floor.
|
|
170
|
+
*/
|
|
171
|
+
TakeFloor(roomId, agentSessionId) {
|
|
172
|
+
const decision = this.CanTakeFloor(roomId, agentSessionId);
|
|
173
|
+
if (!decision.Granted) {
|
|
174
|
+
return decision;
|
|
175
|
+
}
|
|
176
|
+
const room = this.rooms.get(this.key(roomId));
|
|
177
|
+
// Already-holder re-assert: keep the original since-stamp; otherwise stamp now.
|
|
178
|
+
if (room.floorHolderAgentSessionId === null || this.key(room.floorHolderAgentSessionId) !== this.key(agentSessionId)) {
|
|
179
|
+
room.floorHolderAgentSessionId = agentSessionId;
|
|
180
|
+
room.floorHeldSinceMs = this.now();
|
|
181
|
+
}
|
|
182
|
+
return decision;
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* Releases the floor held by an agent (it finished speaking). A no-op when the agent is not the
|
|
186
|
+
* current holder, so a late/duplicate release can never steal the floor from another agent.
|
|
187
|
+
*
|
|
188
|
+
* @param roomId The shared room id.
|
|
189
|
+
* @param agentSessionId The agent releasing the floor.
|
|
190
|
+
* @returns `true` when this call actually freed the floor (the agent was the holder).
|
|
191
|
+
*/
|
|
192
|
+
ReleaseFloor(roomId, agentSessionId) {
|
|
193
|
+
const room = this.rooms.get(this.key(roomId));
|
|
194
|
+
if (!room || room.floorHolderAgentSessionId === null) {
|
|
195
|
+
return false;
|
|
196
|
+
}
|
|
197
|
+
if (this.key(room.floorHolderAgentSessionId) !== this.key(agentSessionId)) {
|
|
198
|
+
return false; // not the holder — don't free someone else's floor
|
|
199
|
+
}
|
|
200
|
+
room.floorHolderAgentSessionId = null;
|
|
201
|
+
room.floorHeldSinceMs = null;
|
|
202
|
+
return true;
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* Whether a given agent currently holds the floor in a room. An agent that was bumped by a
|
|
206
|
+
* facilitator override checks this to learn it should yield.
|
|
207
|
+
*
|
|
208
|
+
* @param roomId The shared room id.
|
|
209
|
+
* @param agentSessionId The agent to test.
|
|
210
|
+
* @returns `true` when the agent is the current floor holder.
|
|
211
|
+
*/
|
|
212
|
+
IsFloorHolder(roomId, agentSessionId) {
|
|
213
|
+
const room = this.rooms.get(this.key(roomId));
|
|
214
|
+
if (!room || room.floorHolderAgentSessionId === null) {
|
|
215
|
+
return false;
|
|
216
|
+
}
|
|
217
|
+
return this.key(room.floorHolderAgentSessionId) === this.key(agentSessionId);
|
|
218
|
+
}
|
|
219
|
+
/**
|
|
220
|
+
* Designates (or re-designates) a room's facilitator at runtime — e.g. when the agent running the
|
|
221
|
+
* Meeting Controls channel is determined after join. The agent must already be a room member.
|
|
222
|
+
*
|
|
223
|
+
* @param roomId The shared room id.
|
|
224
|
+
* @param agentSessionId The agent to make facilitator (must be a member).
|
|
225
|
+
* @returns `true` when the facilitator was set; `false` when the room/agent is unknown.
|
|
226
|
+
*/
|
|
227
|
+
SetFacilitator(roomId, agentSessionId) {
|
|
228
|
+
const room = this.rooms.get(this.key(roomId));
|
|
229
|
+
const member = room?.members.get(this.key(agentSessionId));
|
|
230
|
+
if (!room || !member) {
|
|
231
|
+
return false;
|
|
232
|
+
}
|
|
233
|
+
member.IsFacilitator = true;
|
|
234
|
+
room.facilitatorAgentSessionId = agentSessionId;
|
|
235
|
+
return true;
|
|
236
|
+
}
|
|
237
|
+
// ──────────────────────────────────────────────────────────────────────────────
|
|
238
|
+
// Observability.
|
|
239
|
+
// ──────────────────────────────────────────────────────────────────────────────
|
|
240
|
+
/**
|
|
241
|
+
* Returns a snapshot of a room's floor state, or `null` when the room is unknown. Read-only — for
|
|
242
|
+
* the realtime dashboard / observer console and tests.
|
|
243
|
+
*
|
|
244
|
+
* @param roomId The room to inspect.
|
|
245
|
+
* @returns The room's floor state snapshot, or `null`.
|
|
246
|
+
*/
|
|
247
|
+
GetRoomState(roomId) {
|
|
248
|
+
const room = this.rooms.get(this.key(roomId));
|
|
249
|
+
if (!room) {
|
|
250
|
+
return null;
|
|
251
|
+
}
|
|
252
|
+
return {
|
|
253
|
+
RoomId: room.roomId,
|
|
254
|
+
AgentSessionIds: Array.from(room.members.values()).map(m => m.AgentSessionId),
|
|
255
|
+
FacilitatorAgentSessionId: room.facilitatorAgentSessionId,
|
|
256
|
+
FloorHolderAgentSessionId: room.floorHolderAgentSessionId,
|
|
257
|
+
FloorHeldSinceMs: room.floorHeldSinceMs,
|
|
258
|
+
};
|
|
259
|
+
}
|
|
260
|
+
/** The ids of all rooms the coordinator currently tracks (those with ≥1 agent member). */
|
|
261
|
+
get RoomIds() {
|
|
262
|
+
return Array.from(this.rooms.values()).map(r => r.roomId);
|
|
263
|
+
}
|
|
264
|
+
// ──────────────────────────────────────────────────────────────────────────────
|
|
265
|
+
// Internals.
|
|
266
|
+
// ──────────────────────────────────────────────────────────────────────────────
|
|
267
|
+
/** Gets the room record, creating an empty one (preserving the caller's casing) on first use. */
|
|
268
|
+
ensureRoom(roomId) {
|
|
269
|
+
const k = this.key(roomId);
|
|
270
|
+
let room = this.rooms.get(k);
|
|
271
|
+
if (!room) {
|
|
272
|
+
room = {
|
|
273
|
+
roomId,
|
|
274
|
+
members: new Map(),
|
|
275
|
+
facilitatorAgentSessionId: null,
|
|
276
|
+
floorHolderAgentSessionId: null,
|
|
277
|
+
floorHeldSinceMs: null,
|
|
278
|
+
};
|
|
279
|
+
this.rooms.set(k, room);
|
|
280
|
+
}
|
|
281
|
+
return room;
|
|
282
|
+
}
|
|
283
|
+
/** Whether an agent is the room's facilitator (by membership flag or the room's facilitator slot). */
|
|
284
|
+
isFacilitator(room, agentSessionId) {
|
|
285
|
+
const member = room.members.get(this.key(agentSessionId));
|
|
286
|
+
if (member?.IsFacilitator) {
|
|
287
|
+
return true;
|
|
288
|
+
}
|
|
289
|
+
return room.facilitatorAgentSessionId !== null && this.key(room.facilitatorAgentSessionId) === this.key(agentSessionId);
|
|
290
|
+
}
|
|
291
|
+
/** Normalizes an id for case-insensitive map keying (UUIDs differ in case across DB platforms). */
|
|
292
|
+
key(id) {
|
|
293
|
+
return id.trim().toLowerCase();
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
//# sourceMappingURL=multi-agent-room-coordinator.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file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AAG,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QAC3B,IAAI,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;QAC7B,IAAI,CAAC,IAAI,EAAE,CAAC;YACR,IAAI,GAAG;gBACH,MAAM;gBACN,OAAO,EAAE,IAAI,GAAG,EAA+B;gBAC/C,yBAAyB,EAAE,IAAI;gBAC/B,yBAAyB,EAAE,IAAI;gBAC/B,gBAAgB,EAAE,IAAI;aACzB,CAAC;YACF,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC;QAC5B,CAAC;QACD,OAAO,IAAI,CAAC;IAChB,CAAC;IAED,sGAAsG;IAC9F,aAAa,CAAC,IAAgB,EAAE,cAAsB;QAC1D,MAAM,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC,CAAC;QAC1D,IAAI,MAAM,EAAE,aAAa,EAAE,CAAC;YACxB,OAAO,IAAI,CAAC;QAChB,CAAC;QACD,OAAO,IAAI,CAAC,yBAAyB,KAAK,IAAI,IAAI,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,yBAAyB,CAAC,KAAK,IAAI,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC;IAC5H,CAAC;IAED,mGAAmG;IAC3F,GAAG,CAAC,EAAU;QAClB,OAAO,EAAE,CAAC,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;IACnC,CAAC;CACJ"}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { IMetadataProvider, UserInfo } from '@memberjunction/core';
|
|
2
|
+
import { MJAIBridgeProviderEntity, MJAIAgentSessionBridgeEntity } from '@memberjunction/core-entities';
|
|
3
|
+
import { AIBridgeEngine, StartBridgeSessionParams } from './ai-bridge-engine.js';
|
|
4
|
+
/**
|
|
5
|
+
* The context the {@link ScheduledBridgeRunner} hands to the host's session factory for one due
|
|
6
|
+
* bridge. The factory uses this to construct the live {@link StartBridgeSessionParams} — most
|
|
7
|
+
* importantly the `IRealtimeSession` (whose construction is intentionally the host's job, never the
|
|
8
|
+
* runner's, keeping the transport seam clean exactly like `AIBridgeEngine.StartBridgeSession`).
|
|
9
|
+
*/
|
|
10
|
+
export interface DueBridgeContext {
|
|
11
|
+
/** The due `AIAgentSessionBridge` row to start. */
|
|
12
|
+
BridgeRow: MJAIAgentSessionBridgeEntity;
|
|
13
|
+
/** The resolved transport provider for the bridge (looked up from the engine cache by the runner). */
|
|
14
|
+
Provider: MJAIBridgeProviderEntity;
|
|
15
|
+
/** The MJ user the started session runs as. */
|
|
16
|
+
ContextUser: UserInfo;
|
|
17
|
+
/** The metadata provider bound to the start. */
|
|
18
|
+
MetadataProvider: IMetadataProvider;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* The **session-construction seam** — the host-supplied factory that turns a due bridge into the
|
|
22
|
+
* {@link StartBridgeSessionParams} the engine starts (notably the injected `IRealtimeSession`). This
|
|
23
|
+
* is the one piece the runner cannot own: constructing the realtime model + the
|
|
24
|
+
* `RealtimeSessionRunner` is the host/agent layer's responsibility (it owns the model lifecycle).
|
|
25
|
+
*
|
|
26
|
+
* Returning `null`/`undefined` tells the runner to skip this bridge this pass (e.g. the host can't
|
|
27
|
+
* service it on this node yet) without marking it failed.
|
|
28
|
+
*
|
|
29
|
+
* @param ctx The due-bridge context.
|
|
30
|
+
* @returns The start params, or `null`/`undefined` to skip.
|
|
31
|
+
*/
|
|
32
|
+
export type ScheduledBridgeSessionFactory = (ctx: DueBridgeContext) => Promise<StartBridgeSessionParams | null | undefined> | StartBridgeSessionParams | null | undefined;
|
|
33
|
+
/**
|
|
34
|
+
* Configuration for {@link ScheduledBridgeRunner}.
|
|
35
|
+
*/
|
|
36
|
+
export interface ScheduledBridgeRunnerConfig {
|
|
37
|
+
/** The server engine the runner triggers `StartBridgeSession` on. Defaults to {@link AIBridgeEngine.Instance}. */
|
|
38
|
+
Engine?: AIBridgeEngine;
|
|
39
|
+
/** The host-supplied factory that builds start params (incl. the `IRealtimeSession`) for a due bridge. */
|
|
40
|
+
SessionFactory: ScheduledBridgeSessionFactory;
|
|
41
|
+
/** The MJ user the runner's reads/writes + started sessions run as. */
|
|
42
|
+
ContextUser: UserInfo;
|
|
43
|
+
/** The request-scoped metadata provider for all entity operations. */
|
|
44
|
+
MetadataProvider: IMetadataProvider;
|
|
45
|
+
/** Clock seam for the due-time comparison and testability. Defaults to `Date.now`. */
|
|
46
|
+
Now?: () => number;
|
|
47
|
+
/** Max due bridges to start per pass (back-pressure). Defaults to 25. */
|
|
48
|
+
MaxPerPass?: number;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* The outcome of one {@link ScheduledBridgeRunner.RunDueBridges} pass.
|
|
52
|
+
*/
|
|
53
|
+
export interface ScheduledRunResult {
|
|
54
|
+
/** Due bridges examined this pass. */
|
|
55
|
+
DueFound: number;
|
|
56
|
+
/** Bridges successfully handed to `StartBridgeSession`. */
|
|
57
|
+
Started: number;
|
|
58
|
+
/** Due bridges the factory declined to service (returned null) — left `Scheduled` for a later pass. */
|
|
59
|
+
Skipped: number;
|
|
60
|
+
/** Due bridges whose start threw — stamped `Failed` by the engine; counted here. */
|
|
61
|
+
Failed: number;
|
|
62
|
+
/** Bridges skipped because their provider could not be resolved from the engine cache. */
|
|
63
|
+
Unresolved: number;
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* The **scheduled-bridge runner** — a documented host hook (mirroring the engine janitor's
|
|
67
|
+
* {@link AIBridgeEngine.ReconcileOrphans}) that starts `Scheduled` bridges when their time arrives.
|
|
68
|
+
*
|
|
69
|
+
* Each pass it loads every `AIAgentSessionBridge` with `Status='Scheduled'` and
|
|
70
|
+
* `ScheduledStartTime <= now`, resolves each one's provider, asks the host's
|
|
71
|
+
* {@link ScheduledBridgeSessionFactory} to build the start params (the host constructs the
|
|
72
|
+
* `IRealtimeSession` — the runner never does), and calls {@link AIBridgeEngine.StartBridgeSession}.
|
|
73
|
+
*
|
|
74
|
+
* Properties (per spec):
|
|
75
|
+
* - **No timer.** Only {@link RunDueBridges} is exposed; the host schedules the cadence (e.g. every
|
|
76
|
+
* 30s), exactly like the janitor.
|
|
77
|
+
* - **Idempotent.** `StartBridgeSession` transitions the row off `Scheduled` (to `Connecting` →
|
|
78
|
+
* `Connected`, or `Failed`), so the next pass no longer sees it. A factory that declines leaves the
|
|
79
|
+
* row `Scheduled` for a later pass, never double-starting.
|
|
80
|
+
* - **Clean seam.** The runner constructs no realtime session; that stays the host's job.
|
|
81
|
+
* - **Tolerant.** A per-bridge failure is captured in the result and the pass continues.
|
|
82
|
+
*
|
|
83
|
+
* @see `/plans/realtime/realtime-bridges-architecture.md` §5 / §7 (Scheduled join + lifecycle).
|
|
84
|
+
*/
|
|
85
|
+
export declare class ScheduledBridgeRunner {
|
|
86
|
+
private readonly engine;
|
|
87
|
+
private readonly sessionFactory;
|
|
88
|
+
private readonly contextUser;
|
|
89
|
+
private readonly metadataProvider;
|
|
90
|
+
private readonly now;
|
|
91
|
+
private readonly maxPerPass;
|
|
92
|
+
constructor(config: ScheduledBridgeRunnerConfig);
|
|
93
|
+
/**
|
|
94
|
+
* Runs one pass: finds due scheduled bridges and starts each through the engine. Never throws — a
|
|
95
|
+
* per-bridge failure is recorded in the returned {@link ScheduledRunResult} and the pass proceeds.
|
|
96
|
+
*
|
|
97
|
+
* @returns Observability counts for the pass.
|
|
98
|
+
*/
|
|
99
|
+
RunDueBridges(): Promise<ScheduledRunResult>;
|
|
100
|
+
/**
|
|
101
|
+
* Loads the due scheduled bridges: `Status='Scheduled'` and `ScheduledStartTime <= now`, oldest
|
|
102
|
+
* first, capped at {@link ScheduledBridgeRunnerConfig.MaxPerPass}.
|
|
103
|
+
*
|
|
104
|
+
* @returns The due bridge rows (possibly empty).
|
|
105
|
+
*/
|
|
106
|
+
private loadDueBridges;
|
|
107
|
+
/**
|
|
108
|
+
* Resolves the provider, asks the factory for start params, and starts one due bridge — capturing
|
|
109
|
+
* every failure mode in the result counters.
|
|
110
|
+
*
|
|
111
|
+
* @param row The due bridge row.
|
|
112
|
+
* @param result The running pass result to update.
|
|
113
|
+
*/
|
|
114
|
+
private startOne;
|
|
115
|
+
/**
|
|
116
|
+
* Calls {@link AIBridgeEngine.StartBridgeSession} for a due bridge, tallying success/failure. The
|
|
117
|
+
* engine owns the `Scheduled → Connecting → Connected`/`Failed` transition, so the runner does not
|
|
118
|
+
* mutate the row's status itself — keeping a single source of truth for the state machine.
|
|
119
|
+
*
|
|
120
|
+
* @param params The host-built start params.
|
|
121
|
+
* @param row The due bridge row (for logging).
|
|
122
|
+
* @param result The running pass result to update.
|
|
123
|
+
*/
|
|
124
|
+
private invokeStart;
|
|
125
|
+
}
|
|
126
|
+
//# sourceMappingURL=scheduled-bridge-runner.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"scheduled-bridge-runner.d.ts","sourceRoot":"","sources":["../src/scheduled-bridge-runner.ts"],"names":[],"mappings":"AAAA,OAAO,EACH,iBAAiB,EACjB,QAAQ,EAIX,MAAM,sBAAsB,CAAC;AAE9B,OAAO,EACH,wBAAwB,EACxB,4BAA4B,EAC/B,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,cAAc,EAAE,wBAAwB,EAAuB,MAAM,oBAAoB,CAAC;AAInG;;;;;GAKG;AACH,MAAM,WAAW,gBAAgB;IAC7B,mDAAmD;IACnD,SAAS,EAAE,4BAA4B,CAAC;IAExC,sGAAsG;IACtG,QAAQ,EAAE,wBAAwB,CAAC;IAEnC,+CAA+C;IAC/C,WAAW,EAAE,QAAQ,CAAC;IAEtB,gDAAgD;IAChD,gBAAgB,EAAE,iBAAiB,CAAC;CACvC;AAED;;;;;;;;;;;GAWG;AACH,MAAM,MAAM,6BAA6B,GAAG,CACxC,GAAG,EAAE,gBAAgB,KACpB,OAAO,CAAC,wBAAwB,GAA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140 @@
|
|
|
1
|
+
import { LogError, LogStatus, RunView, } from '@memberjunction/core';
|
|
2
|
+
import { UUIDsEqual } from '@memberjunction/global';
|
|
3
|
+
import { AIBridgeEngine } from './ai-bridge-engine.js';
|
|
4
|
+
const SESSION_BRIDGE_ENTITY = 'MJ: AI Agent Session Bridges';
|
|
5
|
+
/**
|
|
6
|
+
* The **scheduled-bridge runner** — a documented host hook (mirroring the engine janitor's
|
|
7
|
+
* {@link AIBridgeEngine.ReconcileOrphans}) that starts `Scheduled` bridges when their time arrives.
|
|
8
|
+
*
|
|
9
|
+
* Each pass it loads every `AIAgentSessionBridge` with `Status='Scheduled'` and
|
|
10
|
+
* `ScheduledStartTime <= now`, resolves each one's provider, asks the host's
|
|
11
|
+
* {@link ScheduledBridgeSessionFactory} to build the start params (the host constructs the
|
|
12
|
+
* `IRealtimeSession` — the runner never does), and calls {@link AIBridgeEngine.StartBridgeSession}.
|
|
13
|
+
*
|
|
14
|
+
* Properties (per spec):
|
|
15
|
+
* - **No timer.** Only {@link RunDueBridges} is exposed; the host schedules the cadence (e.g. every
|
|
16
|
+
* 30s), exactly like the janitor.
|
|
17
|
+
* - **Idempotent.** `StartBridgeSession` transitions the row off `Scheduled` (to `Connecting` →
|
|
18
|
+
* `Connected`, or `Failed`), so the next pass no longer sees it. A factory that declines leaves the
|
|
19
|
+
* row `Scheduled` for a later pass, never double-starting.
|
|
20
|
+
* - **Clean seam.** The runner constructs no realtime session; that stays the host's job.
|
|
21
|
+
* - **Tolerant.** A per-bridge failure is captured in the result and the pass continues.
|
|
22
|
+
*
|
|
23
|
+
* @see `/plans/realtime/realtime-bridges-architecture.md` §5 / §7 (Scheduled join + lifecycle).
|
|
24
|
+
*/
|
|
25
|
+
export class ScheduledBridgeRunner {
|
|
26
|
+
constructor(config) {
|
|
27
|
+
this.engine = config.Engine ?? AIBridgeEngine.Instance;
|
|
28
|
+
this.sessionFactory = config.SessionFactory;
|
|
29
|
+
this.contextUser = config.ContextUser;
|
|
30
|
+
this.metadataProvider = config.MetadataProvider;
|
|
31
|
+
this.now = config.Now ?? (() => Date.now());
|
|
32
|
+
this.maxPerPass = config.MaxPerPass ?? 25;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Runs one pass: finds due scheduled bridges and starts each through the engine. Never throws — a
|
|
36
|
+
* per-bridge failure is recorded in the returned {@link ScheduledRunResult} and the pass proceeds.
|
|
37
|
+
*
|
|
38
|
+
* @returns Observability counts for the pass.
|
|
39
|
+
*/
|
|
40
|
+
async RunDueBridges() {
|
|
41
|
+
const result = {
|
|
42
|
+
DueFound: 0,
|
|
43
|
+
Started: 0,
|
|
44
|
+
Skipped: 0,
|
|
45
|
+
Failed: 0,
|
|
46
|
+
Unresolved: 0,
|
|
47
|
+
};
|
|
48
|
+
const due = await this.loadDueBridges();
|
|
49
|
+
result.DueFound = due.length;
|
|
50
|
+
for (const row of due) {
|
|
51
|
+
await this.startOne(row, result);
|
|
52
|
+
}
|
|
53
|
+
if (result.DueFound > 0) {
|
|
54
|
+
LogStatus(`[ScheduledBridgeRunner] Pass done: started ${result.Started}/${result.DueFound} due bridge(s) ` +
|
|
55
|
+
`(${result.Skipped} skipped, ${result.Failed} failed, ${result.Unresolved} unresolved).`);
|
|
56
|
+
}
|
|
57
|
+
return result;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Loads the due scheduled bridges: `Status='Scheduled'` and `ScheduledStartTime <= now`, oldest
|
|
61
|
+
* first, capped at {@link ScheduledBridgeRunnerConfig.MaxPerPass}.
|
|
62
|
+
*
|
|
63
|
+
* @returns The due bridge rows (possibly empty).
|
|
64
|
+
*/
|
|
65
|
+
async loadDueBridges() {
|
|
66
|
+
const rv = RunView.FromMetadataProvider(this.metadataProvider);
|
|
67
|
+
const nowIso = new Date(this.now()).toISOString();
|
|
68
|
+
const result = await rv.RunView({
|
|
69
|
+
EntityName: SESSION_BRIDGE_ENTITY,
|
|
70
|
+
ExtraFilter: `Status='Scheduled' AND ScheduledStartTime <= '${nowIso}'`,
|
|
71
|
+
OrderBy: 'ScheduledStartTime ASC',
|
|
72
|
+
MaxRows: this.maxPerPass,
|
|
73
|
+
ResultType: 'entity_object',
|
|
74
|
+
}, this.contextUser);
|
|
75
|
+
if (!result.Success) {
|
|
76
|
+
LogError(`[ScheduledBridgeRunner] Failed to load due bridges: ${result.ErrorMessage}`);
|
|
77
|
+
return [];
|
|
78
|
+
}
|
|
79
|
+
return result.Results;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Resolves the provider, asks the factory for start params, and starts one due bridge — capturing
|
|
83
|
+
* every failure mode in the result counters.
|
|
84
|
+
*
|
|
85
|
+
* @param row The due bridge row.
|
|
86
|
+
* @param result The running pass result to update.
|
|
87
|
+
*/
|
|
88
|
+
async startOne(row, result) {
|
|
89
|
+
const provider = this.engine.Providers.find(p => UUIDsEqual(p.ID, row.ProviderID));
|
|
90
|
+
if (!provider) {
|
|
91
|
+
result.Unresolved++;
|
|
92
|
+
LogError(`[ScheduledBridgeRunner] No provider ${row.ProviderID} for due bridge ${row.ID}; leaving Scheduled.`);
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
let params;
|
|
96
|
+
try {
|
|
97
|
+
params = await this.sessionFactory({
|
|
98
|
+
BridgeRow: row,
|
|
99
|
+
Provider: provider,
|
|
100
|
+
ContextUser: this.contextUser,
|
|
101
|
+
MetadataProvider: this.metadataProvider,
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
catch (err) {
|
|
105
|
+
result.Failed++;
|
|
106
|
+
LogError(`[ScheduledBridgeRunner] Session factory threw for bridge ${row.ID}: ` +
|
|
107
|
+
`${err instanceof Error ? err.message : String(err)}`);
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
if (!params) {
|
|
111
|
+
result.Skipped++;
|
|
112
|
+
return; // host declined to service this bridge this pass — leave it Scheduled.
|
|
113
|
+
}
|
|
114
|
+
await this.invokeStart(params, row, result);
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Calls {@link AIBridgeEngine.StartBridgeSession} for a due bridge, tallying success/failure. The
|
|
118
|
+
* engine owns the `Scheduled → Connecting → Connected`/`Failed` transition, so the runner does not
|
|
119
|
+
* mutate the row's status itself — keeping a single source of truth for the state machine.
|
|
120
|
+
*
|
|
121
|
+
* @param params The host-built start params.
|
|
122
|
+
* @param row The due bridge row (for logging).
|
|
123
|
+
* @param result The running pass result to update.
|
|
124
|
+
*/
|
|
125
|
+
async invokeStart(params, row, result) {
|
|
126
|
+
try {
|
|
127
|
+
const active = await this.engine.StartBridgeSession(params);
|
|
128
|
+
result.Started++;
|
|
129
|
+
LogStatus(`[ScheduledBridgeRunner] Started scheduled bridge ${row.ID} → live session ${active.SessionBridgeID}.`);
|
|
130
|
+
}
|
|
131
|
+
catch (err) {
|
|
132
|
+
// StartBridgeSession already stamped the originating row Failed; the runner-created row
|
|
133
|
+
// (if the factory created a fresh one) is the engine's concern. Just record + continue.
|
|
134
|
+
result.Failed++;
|
|
135
|
+
LogError(`[ScheduledBridgeRunner] StartBridgeSession failed for due bridge ${row.ID}: ` +
|
|
136
|
+
`${err instanceof Error ? err.message : String(err)}`);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
//# sourceMappingURL=scheduled-bridge-runner.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"scheduled-bridge-runner.js","sourceRoot":"","sources":["../src/scheduled-bridge-runner.ts"],"names":[],"mappings":"AAAA,OAAO,EAGH,QAAQ,EACR,SAAS,EACT,OAAO,GACV,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AAKpD,OAAO,EAAE,cAAc,EAAiD,MAAM,oBAAoB,CAAC;AAEnG,MAAM,qBAAqB,GAAG,8BAA8B,CAAC;AAiF7D;;;;;;;;;;;;;;;;;;;GAmBG;AACH,MAAM,OAAO,qBAAqB;IAQ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",
|
|
3
|
-
"
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
3
|
+
"type": "module",
|
|
4
|
+
"version": "5.42.0",
|
|
5
|
+
"description": "MemberJunction: Server-tier coordination + execution for Realtime Bridges — completes the unified media-transport seam (the bridge ↔ IRealtimeSession pipe), bot-session lifecycle, host affinity + janitor, participant tracking, and turn-taking integration. Mirrors the AIEngineBase/AIEngine pair.",
|
|
6
|
+
"main": "dist/index.js",
|
|
7
|
+
"types": "dist/index.d.ts",
|
|
8
|
+
"files": [
|
|
9
|
+
"/dist"
|
|
10
|
+
],
|
|
11
|
+
"scripts": {
|
|
12
|
+
"start": "ts-node-dev src/index.ts",
|
|
13
|
+
"build": "tsc && tsc-alias -f",
|
|
14
|
+
"test": "vitest run",
|
|
15
|
+
"test:watch": "vitest"
|
|
16
|
+
},
|
|
17
|
+
"author": "MemberJunction.com",
|
|
18
|
+
"license": "ISC",
|
|
19
|
+
"dependencies": {
|
|
20
|
+
"@memberjunction/core": "5.42.0",
|
|
21
|
+
"@memberjunction/global": "5.42.0",
|
|
22
|
+
"@memberjunction/core-entities": "5.42.0",
|
|
23
|
+
"@memberjunction/ai": "5.42.0",
|
|
24
|
+
"@memberjunction/ai-bridge-base": "5.42.0",
|
|
25
|
+
"rxjs": "^7.8.2"
|
|
26
|
+
},
|
|
27
|
+
"devDependencies": {
|
|
28
|
+
"@types/node": "24.10.11",
|
|
29
|
+
"ts-node-dev": "^2.0.0",
|
|
30
|
+
"typescript": "^5.9.3",
|
|
31
|
+
"vitest": "^4.0.18"
|
|
32
|
+
},
|
|
33
|
+
"repository": {
|
|
34
|
+
"type": "git",
|
|
35
|
+
"url": "https://github.com/MemberJunction/MJ"
|
|
36
|
+
}
|
|
10
37
|
}
|