@astratra/live 0.1.0 → 0.2.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 +60 -0
- package/package.json +2 -2
- package/src/continuity.js +3 -1
- package/src/gemini.js +115 -64
- package/src/index.d.ts +90 -10
- package/src/index.js +1 -0
- package/src/relay.js +102 -0
- package/src/session.js +270 -96
package/README.md
CHANGED
|
@@ -41,10 +41,70 @@ The provider contract is `connect({ instructions, tools, earlier, mode, onEvent,
|
|
|
41
41
|
|
|
42
42
|
The `registry` follows `@astratra/ai`'s `ToolRegistry` contract. The `actions` adapter queues and executes write actions. A spoken confirmation needs a proposed action, assistant readback, and recognized affirmative answer with no negative answer. Supply language-specific `catalog.affirmative` and `catalog.negative` phrase arrays. The same pending action can be confirmed by an explicit client `confirm` message. `createLiveShield` composes injected text masking, unmasking, outbound redaction, and structural key filtering. Its `input`/`output` hooks protect model speech, while `args`/`result` protect local tool calls and `external` protects third-party tool arguments. Supply an injected `catalog` and `persona` for instructions and repeat prompts; the package emits codes rather than fixed user-facing sentences.
|
|
43
43
|
|
|
44
|
+
## A host with its own prompt, tools and protocol
|
|
45
|
+
|
|
46
|
+
`createLiveSession` takes what a host already has instead of the package's
|
|
47
|
+
defaults:
|
|
48
|
+
|
|
49
|
+
- `instructions`: the whole text (or a function making it when the call starts,
|
|
50
|
+
given `{ context, mode }`), instead of `persona` and `catalog`. The shield
|
|
51
|
+
still masks it.
|
|
52
|
+
- `tools`: `{ declarations, call({ id, name, args }) }` (or a function making it
|
|
53
|
+
when the call starts) instead of `registry` and `actions`. What
|
|
54
|
+
`annotateToolResult` returns is still attached to the reply that follows.
|
|
55
|
+
- `wire`: `{ encode(message), decode(raw) }` for a client that speaks other
|
|
56
|
+
shapes (a message renamed, reshaped, or left unsent by returning `null`).
|
|
57
|
+
`attachLive` takes the same `encode` for what it sends by itself (a refused
|
|
58
|
+
call: `{ type: 'error', reason: 'BUSY' }`).
|
|
59
|
+
- `microphone`: options for `createMicrophoneGate` of `@astratra/voice`
|
|
60
|
+
(`{ vad, echo }`), a gate, or a function making either when the call starts.
|
|
61
|
+
The sound goes through it before the provider or the local transcription;
|
|
62
|
+
the provider's voice tells it when it plays, so the echo guard knows when to
|
|
63
|
+
listen. A filter that cannot be made, or throws, never stands in the call's
|
|
64
|
+
way.
|
|
65
|
+
- `observe(message)`: every message the session sends, as the session writes
|
|
66
|
+
it; `onEnd({ reason, code, turns, conversationId, ... })`: once, after the
|
|
67
|
+
client is let go (a host writes its logs there without delaying the hang-up).
|
|
68
|
+
- `directInterrupt: false`: a client's `interrupt` is not sent to a provider
|
|
69
|
+
that hears the person itself.
|
|
70
|
+
- `transcripts.create` is given `first`, the first thing the person said, to
|
|
71
|
+
title the conversation; `saved` reaches the client even when the call is
|
|
72
|
+
closing.
|
|
73
|
+
|
|
74
|
+
A call is alive while the person or the assistant does something (words, a photo
|
|
75
|
+
taken, the assistant's voice, a tool at work), not while the microphone runs: the
|
|
76
|
+
sound alone does not keep a call open.
|
|
77
|
+
|
|
78
|
+
The Gemini adapter takes `candidates` as a function (asked again at every change
|
|
79
|
+
of line, for keys that are reloaded while the server runs); `gaveOut` decides
|
|
80
|
+
whether a refusal or a cut was the key's fault (default: code 1008, or a reason
|
|
81
|
+
that speaks of a quota, a key, a limit): the key rests and the next one takes
|
|
82
|
+
over, otherwise the same key picks the line up with its handle. Once a line
|
|
83
|
+
opens, what failed before may be tried again at the next change. A new session
|
|
84
|
+
knows nothing, so it is told what was said: `handover({ kind, turns })` words it
|
|
85
|
+
(`resume`: the first line of a call that goes on with a conversation, the
|
|
86
|
+
assistant speaks first; `switch`: another line of the same call, it waits for the
|
|
87
|
+
person). The tools Google asks for at once run at once; `toolError(error)` words
|
|
88
|
+
the answer for one that throws; `maxImageChars` bounds a photo.
|
|
89
|
+
|
|
44
90
|
## Confidential path
|
|
45
91
|
|
|
46
92
|
`local` supplies `transcribe`, a `thinker` or injected `textModel`, and a `reader` or voice provider list. `createTextThinker` and `createGeminiTextModel` are available for a streaming text model with tool rounds and candidate fallback. `createGeminiLiveReader` gathers Live audio, checks spoken words against requested text through `@astratra/voice`, and falls back through injected TTS providers. The call uses `@astratra/voice` for VAD segmentation, echo filtering, local transcript analysis, confidential fallback policy, and TTS chunking. Configure `createConfidentialPolicy` from `@astratra/voice` to lock roles or permit explicit cloud fallback. A doubtful transcript emits `repeat` and never reaches the model. The host owns its local decoder, text model, voice provider, and playback format. If a role cannot use cloud audio and local dependencies are absent, the call ends with `LOCAL_UNAVAILABLE`.
|
|
47
93
|
|
|
94
|
+
The other confidential path keeps the provider's voice: `local` gives only a
|
|
95
|
+
`transcriber` (`{ push(base64), finish() }`, for instance
|
|
96
|
+
`createUtteranceSegmenter` of `@astratra/voice`), the sound is transcribed on
|
|
97
|
+
the server, sentence by sentence, and the provider receives text and answers
|
|
98
|
+
with its own voice and tools (`createTranscribedRelay`). The person sees what was
|
|
99
|
+
heard; a doubtful sentence is never sent, `repeat` is emitted, and after
|
|
100
|
+
repeated doubt (or a decoder that fails) the policy may move the call to normal
|
|
101
|
+
without opening a new line: the sound goes to the provider as it is, the last
|
|
102
|
+
sentence replayed first. `local` may be a function, asked once when a
|
|
103
|
+
confidential call starts: one that throws (a model that will not load) is a local
|
|
104
|
+
path that is not there, and the policy decides between `fallback` and
|
|
105
|
+
`LOCAL_UNAVAILABLE`, before the instructions are made, so they are written for
|
|
106
|
+
the mode the call really has.
|
|
107
|
+
|
|
48
108
|
## Client protocol
|
|
49
109
|
|
|
50
110
|
`encodeMessage` and `decodeMessage` handle JSON messages. `nextCallState` tracks connecting, listening, thinking, speaking, confirming, reconnecting, and ended phases. `floatToPcm16`, `pcm16ToFloat`, base64 helpers, `resample`, `encodeMicroChunk`, `decodeVoiceChunk`, `audioLevel`, `shouldInterrupt`, and `createAudioPacer` cover the 16 kHz microphone / 24 kHz playback pattern. The default pacer sends 25 chunks per second and bounds its queue. All client messages use `type` and optional fields; reason codes are stable and should be rendered through the host's catalog.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@astratra/live",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Injected real-time voice call sessions and client protocol helpers.",
|
|
5
5
|
"engines": { "node": ">=20" },
|
|
6
6
|
"main": "src/index.js",
|
|
@@ -11,6 +11,6 @@
|
|
|
11
11
|
"jest": { "testMatch": ["**/__tests__/**/*.test.js"] },
|
|
12
12
|
"license": "MIT",
|
|
13
13
|
"publishConfig": { "access": "public" },
|
|
14
|
-
"dependencies": { "@astratra/voice": "^0.
|
|
14
|
+
"dependencies": { "@astratra/voice": "^0.3.0", "@astratra/ai": "^1.4.0" },
|
|
15
15
|
"devDependencies": { "jest": "30.4.2" }
|
|
16
16
|
}
|
package/src/continuity.js
CHANGED
|
@@ -56,7 +56,9 @@ function createTranscriptRecorder({
|
|
|
56
56
|
id = await store.create({
|
|
57
57
|
userId,
|
|
58
58
|
updatedAt: now(),
|
|
59
|
-
turns: []
|
|
59
|
+
turns: [],
|
|
60
|
+
/* What the conversation begins with: a host titles it after that. */
|
|
61
|
+
first: fresh.find(turn => turn.role === 'user')
|
|
60
62
|
});
|
|
61
63
|
onSaved(id);
|
|
62
64
|
}
|
package/src/gemini.js
CHANGED
|
@@ -53,7 +53,7 @@ function geminiSetup({
|
|
|
53
53
|
}
|
|
54
54
|
function geminiEvents(message) {
|
|
55
55
|
const events = [];
|
|
56
|
-
if (message.sessionResumptionUpdate?.newHandle) events.push({
|
|
56
|
+
if (message.sessionResumptionUpdate?.newHandle && message.sessionResumptionUpdate.resumable !== false) events.push({
|
|
57
57
|
type: 'handle',
|
|
58
58
|
handle: message.sessionResumptionUpdate.newHandle
|
|
59
59
|
});
|
|
@@ -69,14 +69,7 @@ function geminiEvents(message) {
|
|
|
69
69
|
ids: message.toolCallCancellation.ids
|
|
70
70
|
});
|
|
71
71
|
const content = message.serverContent;
|
|
72
|
-
|
|
73
|
-
type: 'heard',
|
|
74
|
-
text: content.inputTranscription.text
|
|
75
|
-
});
|
|
76
|
-
if (content?.outputTranscription?.text) events.push({
|
|
77
|
-
type: 'said',
|
|
78
|
-
text: content.outputTranscription.text
|
|
79
|
-
});
|
|
72
|
+
/* In the order it is heard: the voice first, then what is written of it, then the end of what it said. */
|
|
80
73
|
for (const part of content?.modelTurn?.parts || []) {
|
|
81
74
|
if (part.inlineData?.data) events.push({
|
|
82
75
|
type: 'audio',
|
|
@@ -88,6 +81,14 @@ function geminiEvents(message) {
|
|
|
88
81
|
text: part.text
|
|
89
82
|
});
|
|
90
83
|
}
|
|
84
|
+
if (content?.inputTranscription?.text) events.push({
|
|
85
|
+
type: 'heard',
|
|
86
|
+
text: content.inputTranscription.text
|
|
87
|
+
});
|
|
88
|
+
if (content?.outputTranscription?.text) events.push({
|
|
89
|
+
type: 'said',
|
|
90
|
+
text: content.outputTranscription.text
|
|
91
|
+
});
|
|
91
92
|
if (content?.interrupted) events.push({
|
|
92
93
|
type: 'interrupted'
|
|
93
94
|
});
|
|
@@ -100,6 +101,20 @@ function geminiEvents(message) {
|
|
|
100
101
|
});
|
|
101
102
|
return events;
|
|
102
103
|
}
|
|
104
|
+
/* What Google says when a session is refused or cut for a key or a quota (or 1008, policy violation): the next key, not the same one again. */
|
|
105
|
+
const GAVE_OUT = /quota|exhausted|rate|limit|api key|permission|billing|unauthori[sz]ed|forbidden|not found|not supported/i;
|
|
106
|
+
function defaultGaveOut({ code, reason }) {
|
|
107
|
+
return code === 1008 || GAVE_OUT.test(String(reason || ''));
|
|
108
|
+
}
|
|
109
|
+
/* What a session that knows nothing is told: the latest part of what was said, one line a turn. */
|
|
110
|
+
function defaultHandover({ kind, turns, maxChars = 6000 }) {
|
|
111
|
+
const text = turns.map(turn => `${turn.who}: ${String(turn.text).trim()}`).join('\n');
|
|
112
|
+
return {
|
|
113
|
+
text: text.length > maxChars ? `…${text.slice(-maxChars)}` : text,
|
|
114
|
+
/* Picking up a conversation, the assistant speaks first; on another line of the same call, it waits for the person. */
|
|
115
|
+
turnComplete: kind === 'resume'
|
|
116
|
+
};
|
|
117
|
+
}
|
|
103
118
|
function createGeminiLiveAdapter({
|
|
104
119
|
websocketFactory,
|
|
105
120
|
candidates = [],
|
|
@@ -110,13 +125,22 @@ function createGeminiLiveAdapter({
|
|
|
110
125
|
cooldownMs = 600000,
|
|
111
126
|
maxHeld = 200,
|
|
112
127
|
maxImageBytes = 200000,
|
|
128
|
+
maxImageChars = Math.ceil(maxImageBytes * 4 / 3) + 4,
|
|
113
129
|
imageEveryMs = 1000,
|
|
130
|
+
gaveOut = defaultGaveOut,
|
|
131
|
+
handover = defaultHandover,
|
|
132
|
+
toolError = () => ({
|
|
133
|
+
result: {
|
|
134
|
+
code: 'TOOL_FAILED'
|
|
135
|
+
}
|
|
136
|
+
}),
|
|
114
137
|
logger = {}
|
|
115
138
|
}) {
|
|
116
139
|
if (typeof websocketFactory !== 'function' || !clock) throw new TypeError('ADAPTER_DEPENDENCY_REQUIRED');
|
|
117
140
|
const resting = new Map();
|
|
141
|
+
/* `candidates` may be a function: the keys of a host that reloads them are read again at every change of line. */
|
|
118
142
|
function ordered() {
|
|
119
|
-
const available = candidates.filter(candidate => candidate?.key && candidate?.model);
|
|
143
|
+
const available = (typeof candidates === 'function' ? candidates() : candidates).filter(candidate => candidate?.key && candidate?.model);
|
|
120
144
|
return [...available.filter(item => (resting.get(item.key) || 0) <= clock.now()), ...available.filter(item => (resting.get(item.key) || 0) > clock.now())];
|
|
121
145
|
}
|
|
122
146
|
return {
|
|
@@ -140,14 +164,19 @@ function createGeminiLiveAdapter({
|
|
|
140
164
|
let generation = 0;
|
|
141
165
|
let lastImageAt = -Infinity;
|
|
142
166
|
const held = [];
|
|
143
|
-
|
|
167
|
+
/* What was tried since the last line that opened: once one opens, the others may be tried again at the next change. */
|
|
168
|
+
let tried = new Set();
|
|
144
169
|
const cancelled = new Set();
|
|
145
170
|
const send = value => {
|
|
146
171
|
if (socket?.readyState === 1) socket.send(JSON.stringify(value));
|
|
147
172
|
};
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
const
|
|
173
|
+
/* A session that knows nothing is told what was said: the conversation the call goes on with, or the call so far on another line. */
|
|
174
|
+
const tell = kind => {
|
|
175
|
+
const turns = kind === 'resume' || typeof getHistory !== 'function' ? earlier : getHistory();
|
|
176
|
+
const { text, turnComplete } = handover({
|
|
177
|
+
kind,
|
|
178
|
+
turns
|
|
179
|
+
});
|
|
151
180
|
if (text) send({
|
|
152
181
|
clientContent: {
|
|
153
182
|
turns: [{
|
|
@@ -156,11 +185,45 @@ function createGeminiLiveAdapter({
|
|
|
156
185
|
text
|
|
157
186
|
}]
|
|
158
187
|
}],
|
|
159
|
-
turnComplete:
|
|
188
|
+
turnComplete: Boolean(turnComplete)
|
|
160
189
|
}
|
|
161
190
|
});
|
|
162
191
|
};
|
|
163
|
-
|
|
192
|
+
/* A tool Google asks for: run by the host, its result given back to the session that asked (one that took over never asked). */
|
|
193
|
+
async function runTools(calls, source) {
|
|
194
|
+
await Promise.all(calls.map(async call => {
|
|
195
|
+
onEvent({
|
|
196
|
+
type: 'tool',
|
|
197
|
+
name: call.name
|
|
198
|
+
});
|
|
199
|
+
let response;
|
|
200
|
+
try {
|
|
201
|
+
response = {
|
|
202
|
+
result: await tools.call({
|
|
203
|
+
id: call.id,
|
|
204
|
+
name: call.name,
|
|
205
|
+
args: call.args || {}
|
|
206
|
+
})
|
|
207
|
+
};
|
|
208
|
+
} catch (error) {
|
|
209
|
+
response = toolError(error);
|
|
210
|
+
}
|
|
211
|
+
onEvent({
|
|
212
|
+
type: 'tool_done',
|
|
213
|
+
name: call.name
|
|
214
|
+
});
|
|
215
|
+
if (!cancelled.has(call.id) && source === socket) send({
|
|
216
|
+
toolResponse: {
|
|
217
|
+
functionResponses: [{
|
|
218
|
+
id: call.id,
|
|
219
|
+
name: call.name,
|
|
220
|
+
response
|
|
221
|
+
}]
|
|
222
|
+
}
|
|
223
|
+
});
|
|
224
|
+
}));
|
|
225
|
+
}
|
|
226
|
+
function routeEvents(raw, source) {
|
|
164
227
|
let parsed;
|
|
165
228
|
try {
|
|
166
229
|
parsed = JSON.parse(String(raw));
|
|
@@ -170,41 +233,7 @@ function createGeminiLiveAdapter({
|
|
|
170
233
|
for (const event of geminiEvents(parsed)) {
|
|
171
234
|
if (event.type === 'handle') handle = event.handle;else if (event.type === 'goAway') {
|
|
172
235
|
if (source === socket) void move(Boolean(handle));
|
|
173
|
-
} else if (event.type === 'toolCancel') event.ids.forEach(id => cancelled.add(id));else if (event.type === 'tools')
|
|
174
|
-
for (const call of event.calls) {
|
|
175
|
-
onEvent({
|
|
176
|
-
type: 'tool',
|
|
177
|
-
name: call.name
|
|
178
|
-
});
|
|
179
|
-
let result;
|
|
180
|
-
try {
|
|
181
|
-
result = await tools.call({
|
|
182
|
-
id: call.id,
|
|
183
|
-
name: call.name,
|
|
184
|
-
args: call.args || {}
|
|
185
|
-
});
|
|
186
|
-
} catch (_error) {
|
|
187
|
-
result = {
|
|
188
|
-
code: 'TOOL_FAILED'
|
|
189
|
-
};
|
|
190
|
-
}
|
|
191
|
-
onEvent({
|
|
192
|
-
type: 'tool_done',
|
|
193
|
-
name: call.name
|
|
194
|
-
});
|
|
195
|
-
if (!cancelled.has(call.id) && source === socket) send({
|
|
196
|
-
toolResponse: {
|
|
197
|
-
functionResponses: [{
|
|
198
|
-
id: call.id,
|
|
199
|
-
name: call.name,
|
|
200
|
-
response: {
|
|
201
|
-
result
|
|
202
|
-
}
|
|
203
|
-
}]
|
|
204
|
-
}
|
|
205
|
-
});
|
|
206
|
-
}
|
|
207
|
-
} else onEvent(event);
|
|
236
|
+
} else if (event.type === 'toolCancel') event.ids.forEach(id => cancelled.add(id));else if (event.type === 'tools') void runTools(event.calls, source);else onEvent(event);
|
|
208
237
|
}
|
|
209
238
|
}
|
|
210
239
|
function open(candidate, resume) {
|
|
@@ -212,12 +241,13 @@ function createGeminiLiveAdapter({
|
|
|
212
241
|
const next = websocketFactory(`${endpoint}?key=${encodeURIComponent(candidate.key)}`);
|
|
213
242
|
let ready = false;
|
|
214
243
|
let settled = false;
|
|
215
|
-
const fail = code => {
|
|
244
|
+
const fail = (code, closed = {}) => {
|
|
216
245
|
if (settled) return;
|
|
217
246
|
settled = true;
|
|
218
247
|
clock.clearTimeout(timer);
|
|
219
248
|
reject(Object.assign(new Error(code), {
|
|
220
|
-
code
|
|
249
|
+
code,
|
|
250
|
+
...closed
|
|
221
251
|
}));
|
|
222
252
|
};
|
|
223
253
|
const timer = clock.setTimeout(() => {
|
|
@@ -244,12 +274,23 @@ function createGeminiLiveAdapter({
|
|
|
244
274
|
settled = true;
|
|
245
275
|
clock.clearTimeout(timer);
|
|
246
276
|
resolve(next);
|
|
247
|
-
} else if (ready && next === socket)
|
|
277
|
+
} else if (ready && next === socket) routeEvents(data, next);
|
|
248
278
|
});
|
|
249
|
-
next.on('close', code => {
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
279
|
+
next.on('close', (code, reason) => {
|
|
280
|
+
const closed = {
|
|
281
|
+
closeCode: code,
|
|
282
|
+
reason: String(reason || '')
|
|
283
|
+
};
|
|
284
|
+
if (!ready) fail('OPEN_CLOSED', closed);else if (next === socket && !ended && !moving) {
|
|
285
|
+
/* A key or quota problem: this key rests and the next one takes over; otherwise the same key picks the line up again. */
|
|
286
|
+
const out = gaveOut(closed.closeCode === undefined ? {
|
|
287
|
+
reason: closed.reason
|
|
288
|
+
} : {
|
|
289
|
+
code: closed.closeCode,
|
|
290
|
+
reason: closed.reason
|
|
291
|
+
});
|
|
292
|
+
if (out) resting.set(candidate.key, clock.now() + cooldownMs);
|
|
293
|
+
void move(!out && Boolean(handle));
|
|
253
294
|
}
|
|
254
295
|
});
|
|
255
296
|
next.on('error', () => {
|
|
@@ -257,6 +298,7 @@ function createGeminiLiveAdapter({
|
|
|
257
298
|
});
|
|
258
299
|
});
|
|
259
300
|
}
|
|
301
|
+
/* Opens the next session: first the same one (with its handle) when asked, then every model and key not tried yet. All failing: the call ends. */
|
|
260
302
|
async function move(resume) {
|
|
261
303
|
if (ended || moving) return;
|
|
262
304
|
moving = true;
|
|
@@ -269,19 +311,25 @@ function createGeminiLiveAdapter({
|
|
|
269
311
|
const available = ordered();
|
|
270
312
|
for (const candidate of available) {
|
|
271
313
|
const id = `${candidate.model}:${candidate.key}`;
|
|
272
|
-
|
|
314
|
+
const resumeHere = Boolean(resume && handle && current && candidate.key === current.key && candidate.model === current.model);
|
|
315
|
+
if (tried.has(id) && !resumeHere) continue;
|
|
273
316
|
tried.add(id);
|
|
274
317
|
try {
|
|
275
|
-
const next = await open(candidate,
|
|
318
|
+
const next = await open(candidate, resumeHere);
|
|
276
319
|
if (ended) {
|
|
277
320
|
next.close?.();
|
|
278
321
|
break;
|
|
279
322
|
}
|
|
280
323
|
socket = next;
|
|
281
|
-
const
|
|
324
|
+
const first = generation === 0;
|
|
282
325
|
current = candidate;
|
|
283
326
|
generation += 1;
|
|
284
|
-
|
|
327
|
+
/* A session that took over on another line remembers nothing of the last one's handle. */
|
|
328
|
+
if (!resumeHere) {
|
|
329
|
+
handle = null;
|
|
330
|
+
if (first ? earlier.length : true) tell(first ? 'resume' : 'switch');
|
|
331
|
+
}
|
|
332
|
+
tried = new Set([id, ...(resumeHere ? tried : [])]);
|
|
285
333
|
while (held.length) send(held.shift());
|
|
286
334
|
onEvent({
|
|
287
335
|
type: 'ready',
|
|
@@ -294,7 +342,10 @@ function createGeminiLiveAdapter({
|
|
|
294
342
|
logger.warn?.('PROVIDER_CONNECT_FAILED', {
|
|
295
343
|
code: error.code
|
|
296
344
|
});
|
|
297
|
-
|
|
345
|
+
if (gaveOut({
|
|
346
|
+
code: error.closeCode,
|
|
347
|
+
reason: error.reason
|
|
348
|
+
})) resting.set(candidate.key, clock.now() + cooldownMs);
|
|
298
349
|
}
|
|
299
350
|
}
|
|
300
351
|
moving = false;
|
|
@@ -328,7 +379,7 @@ function createGeminiLiveAdapter({
|
|
|
328
379
|
if (socket) send(message);else if (held.length < maxHeld) held.push(message);
|
|
329
380
|
},
|
|
330
381
|
sendImage(data) {
|
|
331
|
-
if (typeof data !== 'string' || data.length >
|
|
382
|
+
if (typeof data !== 'string' || data.length > maxImageChars || !socket || clock.now() - lastImageAt < imageEveryMs) return false;
|
|
332
383
|
lastImageAt = clock.now();
|
|
333
384
|
send({
|
|
334
385
|
realtimeInput: {
|
package/src/index.d.ts
CHANGED
|
@@ -299,12 +299,19 @@ export declare function geminiSetup(options: {
|
|
|
299
299
|
mode?: string;
|
|
300
300
|
}): unknown;
|
|
301
301
|
export declare function geminiEvents(message: Record<string, unknown>): CallMessage[];
|
|
302
|
+
export interface LiveCandidate {
|
|
303
|
+
model: string;
|
|
304
|
+
key: string;
|
|
305
|
+
}
|
|
306
|
+
export interface HandoverTurn {
|
|
307
|
+
who: string;
|
|
308
|
+
text: string;
|
|
309
|
+
[key: string]: unknown;
|
|
310
|
+
}
|
|
302
311
|
export declare function createGeminiLiveAdapter(options: {
|
|
303
312
|
websocketFactory(url: string): unknown;
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
key: string;
|
|
307
|
-
}>;
|
|
313
|
+
/** Ordered {model, key} pairs, or a function giving them: asked again at every change of line (keys that are reloaded while the server runs). */
|
|
314
|
+
candidates: LiveCandidate[] | (() => LiveCandidate[]);
|
|
308
315
|
endpoint?: string;
|
|
309
316
|
voice?: string;
|
|
310
317
|
clock: Clock;
|
|
@@ -312,7 +319,15 @@ export declare function createGeminiLiveAdapter(options: {
|
|
|
312
319
|
cooldownMs?: number;
|
|
313
320
|
maxHeld?: number;
|
|
314
321
|
maxImageBytes?: number;
|
|
322
|
+
/** The most characters of a base64 image (default: what maxImageBytes gives). */
|
|
323
|
+
maxImageChars?: number;
|
|
315
324
|
imageEveryMs?: number;
|
|
325
|
+
/** Whether a session was refused or cut for its key or its quota: the key rests and the next one takes over. */
|
|
326
|
+
gaveOut?(closed: { code?: number; reason?: string }): boolean;
|
|
327
|
+
/** What a session that knows nothing is told: `resume` at the first line of a call that goes on with a conversation, `switch` on another line of the same call. */
|
|
328
|
+
handover?(input: { kind: 'resume' | 'switch'; turns: HandoverTurn[] }): { text: string; turnComplete?: boolean };
|
|
329
|
+
/** The response given to the provider when a tool throws (default: { result: { code: 'TOOL_FAILED' } }). */
|
|
330
|
+
toolError?(error: unknown): Record<string, unknown>;
|
|
316
331
|
logger?: unknown;
|
|
317
332
|
}): ProviderAdapter;
|
|
318
333
|
export declare function parseSse(stream: AsyncIterable<Uint8Array>): AsyncIterable<unknown>;
|
|
@@ -449,22 +464,78 @@ export declare const CLOSE: Readonly<{
|
|
|
449
464
|
UNAVAILABLE: number;
|
|
450
465
|
NORMAL: number;
|
|
451
466
|
}>;
|
|
467
|
+
export interface LiveTools {
|
|
468
|
+
declarations: unknown[];
|
|
469
|
+
call(request: { id?: string; name: string; args?: Record<string, unknown> }): Promise<unknown>;
|
|
470
|
+
confirmByClient?(actionId: string): Promise<{ code?: string }>;
|
|
471
|
+
cancelByClient?(actionId: string): Promise<{ code?: string }>;
|
|
472
|
+
}
|
|
473
|
+
export interface MicrophoneGate {
|
|
474
|
+
push(base64: string): Promise<string>;
|
|
475
|
+
playbackSent(bytes: number, sampleRate: number): void;
|
|
476
|
+
playbackInterrupted(): void;
|
|
477
|
+
}
|
|
478
|
+
export interface MicrophoneFilters {
|
|
479
|
+
vad?: unknown;
|
|
480
|
+
echo?: unknown;
|
|
481
|
+
outputRate?: number;
|
|
482
|
+
}
|
|
483
|
+
export interface LocalTranscriber {
|
|
484
|
+
push(base64: string): Promise<Array<{ text: string; confidence?: number | null; audio?: string }>>;
|
|
485
|
+
finish(): Promise<Array<{ text: string; confidence?: number | null; audio?: string }>>;
|
|
486
|
+
}
|
|
487
|
+
export interface LiveWire {
|
|
488
|
+
/** What goes to the client: a string, or null for a message that client never knew. */
|
|
489
|
+
encode?(message: CallMessage): string | null;
|
|
490
|
+
/** What the client sent, as a message, or null. */
|
|
491
|
+
decode?(raw: unknown): CallMessage | null;
|
|
492
|
+
}
|
|
493
|
+
export declare function createTranscribedRelay(options: {
|
|
494
|
+
transcriber: LocalTranscriber;
|
|
495
|
+
decision: unknown;
|
|
496
|
+
send(message: CallMessage): void;
|
|
497
|
+
onHeard(text: string): void;
|
|
498
|
+
onSentence(text: string): void;
|
|
499
|
+
onFallback(reason: string, audio?: string): Awaitable<void>;
|
|
500
|
+
onUnavailable(): Awaitable<void>;
|
|
501
|
+
minConfidence?: number;
|
|
502
|
+
}): {
|
|
503
|
+
push(base64: string): Promise<void>;
|
|
504
|
+
finish(): Promise<void>;
|
|
505
|
+
};
|
|
452
506
|
export declare function createLiveSession(options: {
|
|
453
507
|
socket: Socket;
|
|
454
508
|
context: CallContext;
|
|
455
509
|
provider?: ProviderAdapter;
|
|
456
|
-
|
|
510
|
+
/**
|
|
511
|
+
* What the confidential path runs on, here: `{ transcribe, thinker | textModel, reader | readers }` (the whole
|
|
512
|
+
* local pipeline), or `{ transcriber, minConfidence? }` (only the transcription is local: the provider answers,
|
|
513
|
+
* given text). A function is asked once, when a confidential call starts; one that throws (a model that will
|
|
514
|
+
* not load) is a local path that is not there.
|
|
515
|
+
*/
|
|
516
|
+
local?: unknown | ((context: CallContext) => Awaitable<unknown>);
|
|
457
517
|
policy?: unknown;
|
|
458
518
|
registry?: unknown;
|
|
459
519
|
actions?: unknown;
|
|
460
520
|
quota?: unknown;
|
|
461
521
|
lease?: ReturnType<typeof createCallLease>;
|
|
522
|
+
/** `create` is also given `first`, the first thing the person said (a host titles the conversation after it). */
|
|
462
523
|
transcripts?: unknown;
|
|
463
524
|
memory?: unknown;
|
|
464
525
|
clock: Clock;
|
|
465
526
|
logger?: unknown;
|
|
466
527
|
catalog?: Record<string, unknown>;
|
|
467
528
|
persona?: string;
|
|
529
|
+
/** The host's own instructions (the whole text), or a function making them when the call starts. */
|
|
530
|
+
instructions?: string | ((input: { context: CallContext; mode: string | null; now: number }) => Awaitable<string>);
|
|
531
|
+
/** The host's own tools (replacing registry and actions), or a function making them when the call starts. */
|
|
532
|
+
tools?: LiveTools | ((context: CallContext) => Awaitable<LiveTools>);
|
|
533
|
+
/** The shapes the client speaks, when they are not this package's. */
|
|
534
|
+
wire?: LiveWire;
|
|
535
|
+
/** Every message the session sends, as the session writes it (before the wire changes it). A host that throws here changes nothing. */
|
|
536
|
+
observe?(message: CallMessage): void;
|
|
537
|
+
/** Called once, after the client is let go, with how the call ended. */
|
|
538
|
+
onEnd?(info: { reason: string; code: number; startedAt: number; endedAt: number; turns: unknown[]; conversationId: string | null }): Awaitable<void>;
|
|
468
539
|
resumeWindowMs?: number;
|
|
469
540
|
resumeTurns?: number;
|
|
470
541
|
transcriptCompleteOnly?: boolean;
|
|
@@ -474,11 +545,16 @@ export declare function createLiveSession(options: {
|
|
|
474
545
|
maxCallMs?: number;
|
|
475
546
|
shield?: unknown;
|
|
476
547
|
annotateToolResult?(name: string, result: unknown): unknown;
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
548
|
+
/**
|
|
549
|
+
* What the microphone is sorted with before it reaches the provider or the local transcription: options for
|
|
550
|
+
* createMicrophoneGate (`{ vad, echo }` of @astratra/voice), a gate, or a function making either when the call
|
|
551
|
+
* starts (null: no filter; one that throws: no filter either).
|
|
552
|
+
*/
|
|
553
|
+
microphone?: MicrophoneFilters | MicrophoneGate | ((context: CallContext) => Awaitable<MicrophoneFilters | MicrophoneGate | null>) | null;
|
|
554
|
+
/** The name the filters had before they served both modes. */
|
|
555
|
+
directAudio?: MicrophoneFilters | MicrophoneGate | ((context: CallContext) => Awaitable<MicrophoneFilters | MicrophoneGate | null>) | null;
|
|
556
|
+
/** Whether a client's `interrupt` goes to the provider when the sound goes to it as it is (default true). */
|
|
557
|
+
directInterrupt?: boolean;
|
|
482
558
|
}): {
|
|
483
559
|
start(): Promise<void>;
|
|
484
560
|
receive(raw: unknown): Promise<void>;
|
|
@@ -487,6 +563,8 @@ export declare function createLiveSession(options: {
|
|
|
487
563
|
readonly mode: string | null;
|
|
488
564
|
readonly ended: boolean;
|
|
489
565
|
readonly turns: unknown[];
|
|
566
|
+
/** The turns of the conversation this call goes on with. */
|
|
567
|
+
readonly history: unknown[];
|
|
490
568
|
};
|
|
491
569
|
export declare function attachLive(options: {
|
|
492
570
|
httpServer: {
|
|
@@ -513,6 +591,8 @@ export declare function attachLive(options: {
|
|
|
513
591
|
languages?: string[];
|
|
514
592
|
modes?: string[];
|
|
515
593
|
conversationIdPattern?: RegExp;
|
|
594
|
+
/** How the messages the server sends by itself (a refused call) are written for the client. */
|
|
595
|
+
encode?(message: CallMessage): string | null;
|
|
516
596
|
}): {
|
|
517
597
|
readonly size: number;
|
|
518
598
|
close(): void;
|
package/src/index.js
CHANGED
package/src/relay.js
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The confidential path where the provider still speaks: the microphone's sound
|
|
5
|
+
* stays on this server and is transcribed here (`transcriber`, sentence by
|
|
6
|
+
* sentence); the provider receives text only, and answers with its own voice,
|
|
7
|
+
* tools and transcription. A sentence the local decoder doubts is never sent: the
|
|
8
|
+
* person is asked to repeat (`repeat`), and after repeated doubt (or a decoder
|
|
9
|
+
* that fails) the policy may move the call to normal, where the sound goes to
|
|
10
|
+
* the provider as it is, the last sentence replayed first.
|
|
11
|
+
*
|
|
12
|
+
* @param {{ transcriber: { push: (base64: string) => Promise<{ text: string, confidence?: number | null, audio?: string }[]>, finish: () => Promise<{ text: string, confidence?: number | null, audio?: string }[]> },
|
|
13
|
+
* decision: ReturnType<typeof import('@astratra/voice').createConfidentialSession>,
|
|
14
|
+
* send: (message: object) => void, onHeard: (text: string) => void, onSentence: (text: string) => void,
|
|
15
|
+
* onFallback: (reason: string, audio?: string) => Promise<void> | void, onUnavailable: () => Promise<void> | void,
|
|
16
|
+
* minConfidence?: number }} options
|
|
17
|
+
* `onHeard`: a sentence was transcribed (the call is alive); `onSentence`: it is sure enough to go to the provider
|
|
18
|
+
*/
|
|
19
|
+
function createTranscribedRelay({ transcriber, decision, send, onHeard, onSentence, onFallback, onUnavailable, minConfidence = 0.35 }) {
|
|
20
|
+
if (!transcriber || typeof transcriber.push !== 'function' || typeof transcriber.finish !== 'function') throw new TypeError('LOCAL_DEPENDENCY_REQUIRED');
|
|
21
|
+
const doubtful = item => Number.isFinite(item.confidence) && item.confidence < minConfidence;
|
|
22
|
+
const sentence = item => String(item?.text ?? '').trim();
|
|
23
|
+
return {
|
|
24
|
+
/** Sound the gates let through, in order (never two at once): the sentences it ends are handled one after the other. */
|
|
25
|
+
async push(base64) {
|
|
26
|
+
let items;
|
|
27
|
+
try {
|
|
28
|
+
items = await transcriber.push(base64);
|
|
29
|
+
} catch (error) {
|
|
30
|
+
const verdict = decision.onLocalFailure();
|
|
31
|
+
if (verdict.mode === 'normal') await onFallback(verdict.reason, typeof error?.audio === 'string' ? error.audio : base64);else if (verdict.state === 'ended') {
|
|
32
|
+
send({
|
|
33
|
+
type: 'error',
|
|
34
|
+
reason: 'LOCAL_UNAVAILABLE'
|
|
35
|
+
});
|
|
36
|
+
await onUnavailable();
|
|
37
|
+
} else send({
|
|
38
|
+
type: 'repeat',
|
|
39
|
+
code: verdict.reason
|
|
40
|
+
});
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
for (const item of items) {
|
|
44
|
+
const text = sentence(item);
|
|
45
|
+
if (!text) continue;
|
|
46
|
+
onHeard(text);
|
|
47
|
+
/* The person sees what was heard, even when it is not trusted. */
|
|
48
|
+
send({
|
|
49
|
+
type: 'heard',
|
|
50
|
+
text,
|
|
51
|
+
...(doubtful(item) ? {
|
|
52
|
+
uncertain: true
|
|
53
|
+
} : {})
|
|
54
|
+
});
|
|
55
|
+
if (doubtful(item)) {
|
|
56
|
+
const verdict = decision.onDoubt();
|
|
57
|
+
if (verdict.mode === 'normal') {
|
|
58
|
+
await onFallback(verdict.reason, item.audio);
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
send({
|
|
62
|
+
type: 'repeat',
|
|
63
|
+
code: verdict.reason
|
|
64
|
+
});
|
|
65
|
+
continue;
|
|
66
|
+
}
|
|
67
|
+
decision.onAccepted();
|
|
68
|
+
onSentence(text);
|
|
69
|
+
}
|
|
70
|
+
},
|
|
71
|
+
/** What the person was still saying when the call ends: written down, asked again if doubtful, never a reason for the call to fail. */
|
|
72
|
+
async finish() {
|
|
73
|
+
let items;
|
|
74
|
+
try {
|
|
75
|
+
items = await transcriber.finish();
|
|
76
|
+
} catch (_error) {
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
for (const item of items) {
|
|
80
|
+
const text = sentence(item);
|
|
81
|
+
if (!text) continue;
|
|
82
|
+
send({
|
|
83
|
+
type: 'heard',
|
|
84
|
+
text,
|
|
85
|
+
...(doubtful(item) ? {
|
|
86
|
+
uncertain: true
|
|
87
|
+
} : {})
|
|
88
|
+
});
|
|
89
|
+
if (doubtful(item)) {
|
|
90
|
+
send({
|
|
91
|
+
type: 'repeat'
|
|
92
|
+
});
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
onSentence(text);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
module.exports = {
|
|
101
|
+
createTranscribedRelay
|
|
102
|
+
};
|
package/src/session.js
CHANGED
|
@@ -20,13 +20,14 @@ const {
|
|
|
20
20
|
const {
|
|
21
21
|
createConfidentialCall
|
|
22
22
|
} = require('./confidential');
|
|
23
|
+
const {
|
|
24
|
+
createTranscribedRelay
|
|
25
|
+
} = require('./relay');
|
|
23
26
|
const {
|
|
24
27
|
createTextThinker
|
|
25
28
|
} = require('./textModel');
|
|
26
29
|
const voice = require('@astratra/voice');
|
|
27
30
|
const {
|
|
28
|
-
base64ToBytes,
|
|
29
|
-
pcm16ToFloat,
|
|
30
31
|
floatToPcm16,
|
|
31
32
|
bytesToBase64
|
|
32
33
|
} = require('./protocol');
|
|
@@ -38,6 +39,8 @@ const CLOSE = Object.freeze({
|
|
|
38
39
|
UNAVAILABLE: 4503,
|
|
39
40
|
NORMAL: 1000
|
|
40
41
|
});
|
|
42
|
+
/* Only what a person does (not the microphone running) shows that a call is alive. */
|
|
43
|
+
const HUMAN_MESSAGES = new Set(['text', 'confirm', 'cancel', 'mode']);
|
|
41
44
|
function createLiveSession({
|
|
42
45
|
socket,
|
|
43
46
|
context,
|
|
@@ -54,6 +57,11 @@ function createLiveSession({
|
|
|
54
57
|
logger = {},
|
|
55
58
|
catalog = {},
|
|
56
59
|
persona = '',
|
|
60
|
+
instructions: instructionsOption,
|
|
61
|
+
tools: toolsOption,
|
|
62
|
+
wire = {},
|
|
63
|
+
observe,
|
|
64
|
+
onEnd,
|
|
57
65
|
resumeWindowMs = 1800000,
|
|
58
66
|
resumeTurns = 12,
|
|
59
67
|
transcriptCompleteOnly = false,
|
|
@@ -63,9 +71,13 @@ function createLiveSession({
|
|
|
63
71
|
maxCallMs = 1800000,
|
|
64
72
|
shield = {},
|
|
65
73
|
annotateToolResult,
|
|
66
|
-
|
|
74
|
+
microphone = null,
|
|
75
|
+
directAudio = null,
|
|
76
|
+
directInterrupt = true
|
|
67
77
|
}) {
|
|
68
78
|
if (!socket || !context?.userId || !clock) throw new TypeError('SESSION_DEPENDENCY_REQUIRED');
|
|
79
|
+
const encode = wire.encode || encodeMessage;
|
|
80
|
+
const decode = wire.decode || decodeMessage;
|
|
69
81
|
const startedAt = clock.now();
|
|
70
82
|
const callId = context.callId || `${context.userId}:${startedAt}`;
|
|
71
83
|
let lastDebitAt = startedAt;
|
|
@@ -77,14 +89,17 @@ function createLiveSession({
|
|
|
77
89
|
let muted = false;
|
|
78
90
|
let mode = null;
|
|
79
91
|
let line = null;
|
|
92
|
+
let relay = null;
|
|
80
93
|
let recorder = null;
|
|
81
94
|
let timer = null;
|
|
82
95
|
let warned = false;
|
|
83
96
|
let conversationId = null;
|
|
84
97
|
let history = [];
|
|
85
98
|
let instructions = '';
|
|
99
|
+
let tools = null;
|
|
86
100
|
let gate = null;
|
|
87
|
-
|
|
101
|
+
/* What the confidential path needs on this server: undefined until asked (only a confidential call asks). */
|
|
102
|
+
let localSet;
|
|
88
103
|
let audioQueue = Promise.resolve();
|
|
89
104
|
let turnOver = false;
|
|
90
105
|
const pendingMessages = [];
|
|
@@ -95,8 +110,16 @@ function createLiveSession({
|
|
|
95
110
|
affirmative: catalog.affirmative,
|
|
96
111
|
negative: catalog.negative
|
|
97
112
|
});
|
|
113
|
+
const emit = message => {
|
|
114
|
+
if (socket.readyState !== 1) return;
|
|
115
|
+
try {
|
|
116
|
+
observe?.(message);
|
|
117
|
+
} catch (_error) {/* Observing is optional. */}
|
|
118
|
+
const raw = encode(message);
|
|
119
|
+
if (raw) socket.send(raw);
|
|
120
|
+
};
|
|
98
121
|
const safeSend = message => {
|
|
99
|
-
if (!ended
|
|
122
|
+
if (!ended) emit(message);
|
|
100
123
|
};
|
|
101
124
|
const recordTurn = (who, text) => {
|
|
102
125
|
if (!text) return;
|
|
@@ -122,20 +145,18 @@ function createLiveSession({
|
|
|
122
145
|
code: error?.code
|
|
123
146
|
}));
|
|
124
147
|
};
|
|
125
|
-
const
|
|
126
|
-
|
|
127
|
-
context,
|
|
128
|
-
confirmation,
|
|
129
|
-
actions,
|
|
130
|
-
shield,
|
|
131
|
-
clock,
|
|
132
|
-
send: safeSend,
|
|
133
|
-
onResult: (name, result) => {
|
|
148
|
+
const annotate = (name, result) => {
|
|
149
|
+
try {
|
|
134
150
|
const annotation = annotateToolResult?.(name, result);
|
|
135
151
|
if (annotation != null) pendingAnnotations.push(annotation);
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
|
|
152
|
+
} catch (_error) {/* Annotations are optional. */}
|
|
153
|
+
};
|
|
154
|
+
/* What the confidential path may run on: the whole local pipeline (transcribe, think, read), or only the transcription (the provider answers). */
|
|
155
|
+
const localKind = () => {
|
|
156
|
+
if (!localSet) return null;
|
|
157
|
+
if (localSet.transcribe && (localSet.thinker || localSet.textModel) && (localSet.reader || localSet.readers)) return 'full';
|
|
158
|
+
return localSet.transcriber ? 'relay' : null;
|
|
159
|
+
};
|
|
139
160
|
async function close(reason = 'NORMAL', code = CLOSE.NORMAL) {
|
|
140
161
|
if (ended || closing) return;
|
|
141
162
|
closing = true;
|
|
@@ -146,6 +167,13 @@ function createLiveSession({
|
|
|
146
167
|
logger.warn?.('FINAL_AUDIO_FLUSH_FAILED');
|
|
147
168
|
}
|
|
148
169
|
}
|
|
170
|
+
if (relay) {
|
|
171
|
+
try {
|
|
172
|
+
await relay.finish();
|
|
173
|
+
} catch (_error) {
|
|
174
|
+
logger.warn?.('FINAL_AUDIO_FLUSH_FAILED');
|
|
175
|
+
}
|
|
176
|
+
}
|
|
149
177
|
ended = true;
|
|
150
178
|
if (timer) clock.clearInterval(timer);
|
|
151
179
|
line?.end?.();
|
|
@@ -174,12 +202,21 @@ function createLiveSession({
|
|
|
174
202
|
userId: context.userId
|
|
175
203
|
}, turns, conversationId, logger);
|
|
176
204
|
if (socket.readyState === 1) {
|
|
177
|
-
|
|
205
|
+
emit({
|
|
178
206
|
type: 'end',
|
|
179
207
|
reason
|
|
180
|
-
})
|
|
208
|
+
});
|
|
181
209
|
socket.close(code);
|
|
182
210
|
}
|
|
211
|
+
/* Once the phone is let go: what the host keeps of the call (its logs) never delays the hang-up. */
|
|
212
|
+
void Promise.resolve().then(() => onEnd?.({
|
|
213
|
+
reason,
|
|
214
|
+
code,
|
|
215
|
+
startedAt,
|
|
216
|
+
endedAt: clock.now(),
|
|
217
|
+
turns: turns.slice(),
|
|
218
|
+
conversationId
|
|
219
|
+
})).catch(() => logger.warn?.('END_HOOK_FAILED'));
|
|
183
220
|
}
|
|
184
221
|
async function tick() {
|
|
185
222
|
if (ended || closing) return;
|
|
@@ -221,19 +258,21 @@ function createLiveSession({
|
|
|
221
258
|
logger.warn?.('QUOTA_CHECK_FAILED');
|
|
222
259
|
}
|
|
223
260
|
}
|
|
261
|
+
/* How long a stretch of the provider's voice plays, for the echo guard: from its own mime type when it gives a rate. */
|
|
262
|
+
const audioRate = event => Number(/rate=(\d+)/.exec(String(event.mimeType || ''))?.[1]) || directAudio?.outputRate || microphone?.outputRate || 24000;
|
|
224
263
|
function onProviderEvent(event) {
|
|
225
264
|
if (ended) return;
|
|
226
265
|
if (event.type === 'heard') recordTurn('person', event.text);
|
|
227
266
|
if (event.type === 'said' || event.type === 'text') recordTurn('assistant', event.text);
|
|
228
267
|
if (event.type === 'tool') busy += 1;
|
|
229
268
|
if (event.type === 'tool_done') busy = Math.max(0, busy - 1);
|
|
230
|
-
if (event.type === 'audio' || event.type === 'ready' || event.type === 'turn') lastActivity = clock.now();
|
|
269
|
+
if (event.type === 'audio' || event.type === 'ready' || event.type === 'turn' || event.type === 'tool_done') lastActivity = clock.now();
|
|
231
270
|
if (event.type === 'turn') {
|
|
232
271
|
turnOver = true;
|
|
233
272
|
persist();
|
|
234
273
|
}
|
|
235
|
-
if (event.type === 'audio' &&
|
|
236
|
-
if (event.type === 'interrupted')
|
|
274
|
+
if (event.type === 'audio' && gate && event.data) gate.playbackSent(Buffer.byteLength(event.data, 'base64'), audioRate(event));
|
|
275
|
+
if (event.type === 'interrupted') gate?.playbackInterrupted();
|
|
237
276
|
if (event.type === 'error') {
|
|
238
277
|
safeSend({
|
|
239
278
|
type: 'error',
|
|
@@ -243,16 +282,107 @@ function createLiveSession({
|
|
|
243
282
|
}
|
|
244
283
|
if (event.type !== 'handle' && event.type !== 'goAway' && event.type !== 'tools' && event.type !== 'toolCancel') safeSend(event);
|
|
245
284
|
}
|
|
285
|
+
/* The confidential path is asked for: what it needs is resolved once. Not there, the policy decides: the call goes on as normal (told), or ends. Null: the call was closed. */
|
|
286
|
+
async function settle(requested) {
|
|
287
|
+
if (requested !== 'confidential') return requested;
|
|
288
|
+
if (localSet === undefined) {
|
|
289
|
+
try {
|
|
290
|
+
localSet = (typeof local === 'function' ? await local(context) : local) || null;
|
|
291
|
+
} catch (_error) {
|
|
292
|
+
localSet = null;
|
|
293
|
+
logger.warn?.('LOCAL_LOAD_FAILED');
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
if (localKind()) return 'confidential';
|
|
297
|
+
const fallback = (policy || createConfidentialPolicy()).onLocalFailure({
|
|
298
|
+
role: context.role,
|
|
299
|
+
language: context.language,
|
|
300
|
+
requestedMode: 'confidential',
|
|
301
|
+
allowCloudFallback: context.allowCloudFallback
|
|
302
|
+
});
|
|
303
|
+
if (!fallback.cloudAudioAllowed) {
|
|
304
|
+
await close('LOCAL_UNAVAILABLE', CLOSE.UNAVAILABLE);
|
|
305
|
+
return null;
|
|
306
|
+
}
|
|
307
|
+
safeSend({
|
|
308
|
+
type: 'fallback',
|
|
309
|
+
reason: fallback.reason
|
|
310
|
+
});
|
|
311
|
+
return 'normal';
|
|
312
|
+
}
|
|
313
|
+
/* The person's sound goes to the provider as it is: from now on, and first the last sentence the local decoder could not read. */
|
|
314
|
+
async function leaveRelay(reason, audio) {
|
|
315
|
+
if (closing || !relay) return;
|
|
316
|
+
relay = null;
|
|
317
|
+
mode = 'normal';
|
|
318
|
+
safeSend({
|
|
319
|
+
type: 'fallback',
|
|
320
|
+
reason
|
|
321
|
+
});
|
|
322
|
+
if (audio) line?.sendAudio(audio);
|
|
323
|
+
}
|
|
324
|
+
function startRelay(decisionSession) {
|
|
325
|
+
relay = createTranscribedRelay({
|
|
326
|
+
transcriber: localSet.transcriber,
|
|
327
|
+
decision: decisionSession,
|
|
328
|
+
send: safeSend,
|
|
329
|
+
onHeard: () => {
|
|
330
|
+
lastActivity = clock.now();
|
|
331
|
+
},
|
|
332
|
+
onSentence: text => {
|
|
333
|
+
recordTurn('person', text);
|
|
334
|
+
line?.sendText(text);
|
|
335
|
+
},
|
|
336
|
+
onFallback: leaveRelay,
|
|
337
|
+
onUnavailable: () => close('LOCAL_UNAVAILABLE', CLOSE.UNAVAILABLE),
|
|
338
|
+
minConfidence: localSet.minConfidence
|
|
339
|
+
});
|
|
340
|
+
}
|
|
341
|
+
async function connectProvider(earlier) {
|
|
342
|
+
if (!provider?.connect) {
|
|
343
|
+
await close('PROVIDER_UNAVAILABLE', CLOSE.UNAVAILABLE);
|
|
344
|
+
return false;
|
|
345
|
+
}
|
|
346
|
+
const protectedEarlier = earlier.map(turn => ({
|
|
347
|
+
...turn,
|
|
348
|
+
text: typeof shield.history === 'function' ? shield.history(turn.text) : turn.text
|
|
349
|
+
}));
|
|
350
|
+
try {
|
|
351
|
+
line = await provider.connect({
|
|
352
|
+
instructions,
|
|
353
|
+
tools,
|
|
354
|
+
earlier: protectedEarlier,
|
|
355
|
+
getHistory: () => [...history, ...turns].map(turn => ({
|
|
356
|
+
...turn,
|
|
357
|
+
text: typeof shield.history === 'function' ? shield.history(turn.text) : turn.text
|
|
358
|
+
})),
|
|
359
|
+
onEvent: onProviderEvent,
|
|
360
|
+
onClose: code => void close(code, CLOSE.UNAVAILABLE)
|
|
361
|
+
});
|
|
362
|
+
/* The phone hung up while the line was opening: it is not left open on the provider's side. */
|
|
363
|
+
if (closing) {
|
|
364
|
+
line.close?.();
|
|
365
|
+
line = null;
|
|
366
|
+
return false;
|
|
367
|
+
}
|
|
368
|
+
return true;
|
|
369
|
+
} catch (_error) {
|
|
370
|
+
await close('PROVIDER_UNAVAILABLE', CLOSE.UNAVAILABLE);
|
|
371
|
+
return false;
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
/* Opens the line for a mode `settle` has confirmed. */
|
|
246
375
|
async function openLine(nextMode, earlier) {
|
|
247
376
|
line?.end?.();
|
|
248
377
|
line?.close?.();
|
|
249
378
|
line = null;
|
|
379
|
+
relay = null;
|
|
250
380
|
mode = nextMode;
|
|
251
|
-
if (mode === 'confidential' &&
|
|
252
|
-
const service =
|
|
253
|
-
providers:
|
|
381
|
+
if (mode === 'confidential' && localKind() === 'full') {
|
|
382
|
+
const service = localSet.readers ? voice.createPieceVoiceService({
|
|
383
|
+
providers: localSet.readers
|
|
254
384
|
}) : null;
|
|
255
|
-
const reader =
|
|
385
|
+
const reader = localSet.reader || {
|
|
256
386
|
synthesize: ({
|
|
257
387
|
text,
|
|
258
388
|
language
|
|
@@ -260,15 +390,15 @@ function createLiveSession({
|
|
|
260
390
|
language
|
|
261
391
|
})
|
|
262
392
|
};
|
|
263
|
-
const textThinker =
|
|
264
|
-
model:
|
|
393
|
+
const textThinker = localSet.textModel ? createTextThinker({
|
|
394
|
+
model: localSet.textModel,
|
|
265
395
|
instructions,
|
|
266
396
|
declarations: tools.declarations,
|
|
267
397
|
tools,
|
|
268
398
|
earlier,
|
|
269
399
|
onTool: (name, state) => safeSend({ type: state === 'start' ? 'tool' : 'tool_done', name })
|
|
270
400
|
}) : null;
|
|
271
|
-
const thinker =
|
|
401
|
+
const thinker = localSet.thinker || (({
|
|
272
402
|
text,
|
|
273
403
|
onText,
|
|
274
404
|
signal
|
|
@@ -276,9 +406,9 @@ function createLiveSession({
|
|
|
276
406
|
onText,
|
|
277
407
|
signal
|
|
278
408
|
}));
|
|
279
|
-
if (textThinker && !
|
|
409
|
+
if (textThinker && !localSet.thinker) thinker.undoLast = () => textThinker.undoLast();
|
|
280
410
|
line = createConfidentialCall({
|
|
281
|
-
...
|
|
411
|
+
...localSet,
|
|
282
412
|
thinker,
|
|
283
413
|
reader,
|
|
284
414
|
policy,
|
|
@@ -323,46 +453,13 @@ function createLiveSession({
|
|
|
323
453
|
});
|
|
324
454
|
return;
|
|
325
455
|
}
|
|
326
|
-
if (
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
});
|
|
333
|
-
if (!fallback.cloudAudioAllowed) {
|
|
334
|
-
await close('LOCAL_UNAVAILABLE', CLOSE.UNAVAILABLE);
|
|
335
|
-
return;
|
|
336
|
-
}
|
|
337
|
-
mode = 'normal';
|
|
338
|
-
safeSend({
|
|
339
|
-
type: 'fallback',
|
|
340
|
-
reason: fallback.reason
|
|
341
|
-
});
|
|
342
|
-
}
|
|
343
|
-
if (!provider?.connect) {
|
|
344
|
-
await close('PROVIDER_UNAVAILABLE', CLOSE.UNAVAILABLE);
|
|
345
|
-
return;
|
|
346
|
-
}
|
|
347
|
-
const protectedEarlier = earlier.map(turn => ({
|
|
348
|
-
...turn,
|
|
349
|
-
text: typeof shield.history === 'function' ? shield.history(turn.text) : turn.text
|
|
456
|
+
if (!(await connectProvider(earlier))) return;
|
|
457
|
+
if (mode === 'confidential') startRelay(voice.createConfidentialSession(policy || createConfidentialPolicy(), {
|
|
458
|
+
role: context.role,
|
|
459
|
+
language: context.language,
|
|
460
|
+
requestedMode: 'confidential',
|
|
461
|
+
allowCloudFallback: context.allowCloudFallback
|
|
350
462
|
}));
|
|
351
|
-
try {
|
|
352
|
-
line = await provider.connect({
|
|
353
|
-
instructions,
|
|
354
|
-
tools,
|
|
355
|
-
earlier: protectedEarlier,
|
|
356
|
-
getHistory: () => [...history, ...turns].map(turn => ({
|
|
357
|
-
...turn,
|
|
358
|
-
text: typeof shield.history === 'function' ? shield.history(turn.text) : turn.text
|
|
359
|
-
})),
|
|
360
|
-
onEvent: onProviderEvent,
|
|
361
|
-
onClose: code => void close(code, CLOSE.UNAVAILABLE)
|
|
362
|
-
});
|
|
363
|
-
} catch (_error) {
|
|
364
|
-
await close('PROVIDER_UNAVAILABLE', CLOSE.UNAVAILABLE);
|
|
365
|
-
}
|
|
366
463
|
}
|
|
367
464
|
async function start() {
|
|
368
465
|
if (quota) {
|
|
@@ -398,7 +495,8 @@ function createLiveSession({
|
|
|
398
495
|
now: clock.now,
|
|
399
496
|
completeOnly: transcriptCompleteOnly,
|
|
400
497
|
deferLatestExchange,
|
|
401
|
-
|
|
498
|
+
/* Even while the call is closing: the conversation made at the person's last words is still theirs to open. */
|
|
499
|
+
onSaved: id => emit({
|
|
402
500
|
type: 'saved',
|
|
403
501
|
conversationId: id
|
|
404
502
|
})
|
|
@@ -412,8 +510,33 @@ function createLiveSession({
|
|
|
412
510
|
language: context.language,
|
|
413
511
|
requestedMode: context.mode
|
|
414
512
|
});
|
|
415
|
-
mode = decision.mode;
|
|
416
|
-
|
|
513
|
+
mode = decision.mode === 'confidential' ? await settle(decision.mode) : decision.mode;
|
|
514
|
+
if (mode === null || closing) return;
|
|
515
|
+
const given = typeof toolsOption === 'function' ? await toolsOption(context) : toolsOption;
|
|
516
|
+
if (given) tools = {
|
|
517
|
+
...given,
|
|
518
|
+
call: async request => {
|
|
519
|
+
const result = await given.call(request);
|
|
520
|
+
annotate(request.name, result);
|
|
521
|
+
return result;
|
|
522
|
+
}
|
|
523
|
+
};else tools = createCallTools({
|
|
524
|
+
registry,
|
|
525
|
+
context,
|
|
526
|
+
confirmation,
|
|
527
|
+
actions,
|
|
528
|
+
shield,
|
|
529
|
+
clock,
|
|
530
|
+
send: safeSend,
|
|
531
|
+
onResult: annotate,
|
|
532
|
+
catalog
|
|
533
|
+
});
|
|
534
|
+
const prompt = typeof instructionsOption === 'function' ? await instructionsOption({
|
|
535
|
+
context,
|
|
536
|
+
mode,
|
|
537
|
+
now: clock.now()
|
|
538
|
+
}) : instructionsOption;
|
|
539
|
+
instructions = typeof prompt === 'string' ? typeof shield.input === 'function' ? shield.input(prompt) : prompt : buildInstructions({
|
|
417
540
|
persona,
|
|
418
541
|
language: context.language,
|
|
419
542
|
role: context.role,
|
|
@@ -421,32 +544,51 @@ function createLiveSession({
|
|
|
421
544
|
catalog,
|
|
422
545
|
shield
|
|
423
546
|
});
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
547
|
+
/* The microphone's filters: a failure to make them never stands in the call's way. */
|
|
548
|
+
try {
|
|
549
|
+
const filtering = microphone || directAudio;
|
|
550
|
+
const filters = typeof filtering === 'function' ? await filtering(context) : filtering;
|
|
551
|
+
if (filters) gate = typeof filters.push === 'function' ? filters : voice.createMicrophoneGate({
|
|
552
|
+
vad: filters.vad,
|
|
553
|
+
echo: filters.echo,
|
|
554
|
+
now: clock.now
|
|
429
555
|
});
|
|
556
|
+
} catch (_error) {
|
|
557
|
+
logger.warn?.('MICROPHONE_FILTERS_FAILED');
|
|
430
558
|
}
|
|
431
559
|
await openLine(mode, history);
|
|
432
|
-
if (ended) return;
|
|
560
|
+
if (ended || closing) return;
|
|
433
561
|
timer = clock.setInterval(() => {
|
|
434
562
|
void tick();
|
|
435
563
|
}, checkMs);
|
|
436
564
|
timer?.unref?.();
|
|
437
565
|
for (const raw of pendingMessages.splice(0)) await receive(raw);
|
|
438
566
|
}
|
|
567
|
+
/* The microphone's sound, in order: through the filters, then to the local transcription or to the provider. */
|
|
568
|
+
async function hear(data) {
|
|
569
|
+
let audio = data;
|
|
570
|
+
if (gate) {
|
|
571
|
+
try {
|
|
572
|
+
audio = await gate.push(data);
|
|
573
|
+
} catch (_error) {
|
|
574
|
+
audio = data;
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
if (!audio || ended) return;
|
|
578
|
+
if (relay) await relay.push(audio);else line?.sendAudio(audio);
|
|
579
|
+
}
|
|
439
580
|
async function receive(raw) {
|
|
440
581
|
if (ended || closing) return;
|
|
441
|
-
const message =
|
|
582
|
+
const message = decode(raw);
|
|
442
583
|
if (!message) return;
|
|
443
584
|
if (!line && message.type !== 'end') {
|
|
444
585
|
if (pendingMessages.length < 200) pendingMessages.push(raw);
|
|
445
586
|
return;
|
|
446
587
|
}
|
|
447
|
-
lastActivity = clock.now();
|
|
588
|
+
if (HUMAN_MESSAGES.has(message.type)) lastActivity = clock.now();
|
|
448
589
|
if (message.type === 'end') return close('NORMAL');
|
|
449
590
|
if (message.type === 'confirm' || message.type === 'cancel') {
|
|
591
|
+
if (!tools?.confirmByClient) return;
|
|
450
592
|
const result = await (message.type === 'confirm' ? tools.confirmByClient(message.actionId) : tools.cancelByClient(message.actionId));
|
|
451
593
|
if (result.code && result.code !== 'ACTION_DONE' && result.code !== 'ACTION_CANCELLED') safeSend({
|
|
452
594
|
type: 'error',
|
|
@@ -460,9 +602,21 @@ function createLiveSession({
|
|
|
460
602
|
language: context.language,
|
|
461
603
|
requestedMode: message.mode
|
|
462
604
|
});
|
|
463
|
-
|
|
605
|
+
const settled = await settle(decision.mode);
|
|
606
|
+
if (settled === null) return;
|
|
607
|
+
if (settled !== mode) {
|
|
464
608
|
persist();
|
|
465
|
-
|
|
609
|
+
/* Only the transcription is local: the provider's line stays open, the sound is just sent to the other place. */
|
|
610
|
+
if (localKind() === 'relay' && line && !line.receive) {
|
|
611
|
+
mode = settled;
|
|
612
|
+
relay = null;
|
|
613
|
+
if (mode === 'confidential') startRelay(voice.createConfidentialSession(policy || createConfidentialPolicy(), {
|
|
614
|
+
role: context.role,
|
|
615
|
+
language: context.language,
|
|
616
|
+
requestedMode: 'confidential',
|
|
617
|
+
allowCloudFallback: context.allowCloudFallback
|
|
618
|
+
}));
|
|
619
|
+
} else await openLine(settled, [...history, ...turns]);
|
|
466
620
|
}
|
|
467
621
|
safeSend({
|
|
468
622
|
type: 'mode',
|
|
@@ -476,15 +630,10 @@ function createLiveSession({
|
|
|
476
630
|
line?.mute?.();
|
|
477
631
|
}
|
|
478
632
|
if (message.type === 'unmute') muted = false;
|
|
479
|
-
if (mode === 'confidential') return line
|
|
633
|
+
if (mode === 'confidential' && line?.receive) return line.receive(message);
|
|
480
634
|
if (message.type === 'audio' && !muted && typeof message.data === 'string') {
|
|
481
|
-
if (!gate && !
|
|
482
|
-
audioQueue = audioQueue.then(
|
|
483
|
-
const raw = pcm16ToFloat(base64ToBytes(message.data));
|
|
484
|
-
const filtered = await gate.push(raw);
|
|
485
|
-
const accepted = await echo.filter(filtered);
|
|
486
|
-
if (accepted?.length) line?.sendAudio(bytesToBase64(floatToPcm16(accepted)));
|
|
487
|
-
}).catch(() => line?.sendAudio(message.data));
|
|
635
|
+
if (!gate && !relay && localKind() !== 'relay') line?.sendAudio(message.data);else {
|
|
636
|
+
audioQueue = audioQueue.then(() => hear(message.data)).catch(() => {});
|
|
488
637
|
await audioQueue;
|
|
489
638
|
}
|
|
490
639
|
}
|
|
@@ -493,8 +642,18 @@ function createLiveSession({
|
|
|
493
642
|
turnOver = true;
|
|
494
643
|
line?.sendText(message.text);
|
|
495
644
|
}
|
|
496
|
-
if (message.type === 'image' && typeof message.data === 'string' && message.data.length <= 256 * 1024)
|
|
497
|
-
|
|
645
|
+
if (message.type === 'image' && typeof message.data === 'string' && message.data.length <= 256 * 1024) {
|
|
646
|
+
if (line?.sendImage?.(message.data) !== false) lastActivity = clock.now();
|
|
647
|
+
}
|
|
648
|
+
if (message.type === 'interrupt') {
|
|
649
|
+
if (relay) {
|
|
650
|
+
/* The text turn that follows the person's words is what stops the provider: the phone is told, and the guard stops waiting for an echo. */
|
|
651
|
+
gate?.playbackInterrupted();
|
|
652
|
+
safeSend({
|
|
653
|
+
type: 'interrupted'
|
|
654
|
+
});
|
|
655
|
+
} else if (directInterrupt) line?.interrupt?.();
|
|
656
|
+
}
|
|
498
657
|
}
|
|
499
658
|
return {
|
|
500
659
|
start,
|
|
@@ -509,6 +668,9 @@ function createLiveSession({
|
|
|
509
668
|
},
|
|
510
669
|
get turns() {
|
|
511
670
|
return turns.slice();
|
|
671
|
+
},
|
|
672
|
+
get history() {
|
|
673
|
+
return history.slice();
|
|
512
674
|
}
|
|
513
675
|
};
|
|
514
676
|
}
|
|
@@ -523,13 +685,19 @@ function attachLive({
|
|
|
523
685
|
logger = {},
|
|
524
686
|
languages = [],
|
|
525
687
|
modes = ['normal', 'confidential'],
|
|
526
|
-
conversationIdPattern = /^[\w:.-]{1,120}
|
|
688
|
+
conversationIdPattern = /^[\w:.-]{1,120}$/,
|
|
689
|
+
encode = encodeMessage
|
|
527
690
|
}) {
|
|
528
691
|
if (!httpServer?.on || !websocketServer?.handleUpgrade ||
|
|
529
692
|
typeof authenticate !== 'function' || typeof createSession !== 'function') {
|
|
530
693
|
throw new TypeError('SERVER_DEPENDENCY_REQUIRED');
|
|
531
694
|
}
|
|
532
695
|
const calls = new Map();
|
|
696
|
+
/* What the server says by itself, in the client's own words (or not at all, if the client never knew it). */
|
|
697
|
+
const tell = (client, message) => {
|
|
698
|
+
const raw = encode(message);
|
|
699
|
+
if (raw) client.send(raw);
|
|
700
|
+
};
|
|
533
701
|
async function upgrade(request, socket, head) {
|
|
534
702
|
let url;
|
|
535
703
|
try {
|
|
@@ -554,7 +722,7 @@ function attachLive({
|
|
|
554
722
|
try { verdict = await authorize(request, context); }
|
|
555
723
|
catch (_error) { verdict = { allowed: false, reason: 'DENIED' }; }
|
|
556
724
|
if (verdict === false || verdict?.allowed === false) {
|
|
557
|
-
if (verdict?.reason && client.readyState === 1) client
|
|
725
|
+
if (verdict?.reason && client.readyState === 1) tell(client, { type: 'error', reason: verdict.reason });
|
|
558
726
|
client.close(verdict?.code || CLOSE.DENIED);
|
|
559
727
|
return;
|
|
560
728
|
}
|
|
@@ -565,6 +733,7 @@ function attachLive({
|
|
|
565
733
|
calls.delete(userId);
|
|
566
734
|
}
|
|
567
735
|
if (calls.size >= maxCalls) {
|
|
736
|
+
if (client.readyState === 1) tell(client, { type: 'error', reason: 'BUSY' });
|
|
568
737
|
client.close(CLOSE.BUSY);
|
|
569
738
|
return;
|
|
570
739
|
}
|
|
@@ -596,6 +765,10 @@ function attachLive({
|
|
|
596
765
|
logger.warn?.('SESSION_START_FAILED', {
|
|
597
766
|
code: error?.code
|
|
598
767
|
});
|
|
768
|
+
/* What the session had already opened (a line to the provider) is closed with it. */
|
|
769
|
+
try {
|
|
770
|
+
await session?.close?.('SESSION_START_FAILED', CLOSE.UNAVAILABLE);
|
|
771
|
+
} catch (_error) {/* The client is closed below all the same. */}
|
|
599
772
|
client.close(CLOSE.UNAVAILABLE);
|
|
600
773
|
if (calls.get(userId) === session) calls.delete(userId);
|
|
601
774
|
}
|
|
@@ -608,7 +781,8 @@ function attachLive({
|
|
|
608
781
|
},
|
|
609
782
|
close() {
|
|
610
783
|
httpServer.off?.('upgrade', upgrade);
|
|
611
|
-
|
|
784
|
+
/* 1001, "going away": a server that stops is not a call that ended well. */
|
|
785
|
+
for (const session of calls.values()) void session.close('SERVER_CLOSED', 1001);
|
|
612
786
|
calls.clear();
|
|
613
787
|
websocketServer.close?.();
|
|
614
788
|
}
|