@jskit-ai/assistant-voice 0.2.87 → 0.2.89

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.
@@ -1,16 +1,20 @@
1
+ import { readFileSync } from "node:fs";
1
2
  import http from "node:http";
2
3
 
3
4
  import { WebSocketServer } from "ws";
4
5
 
5
6
  import {
7
+ VOICE_CATALOGUE_PATH,
6
8
  VOICE_DAEMON_WEBSOCKET_PATH,
7
9
  VOICE_DEFAULT_SYNTHESIS_TIMEOUT_MS,
10
+ VOICE_HEALTH_PATH,
8
11
  VOICE_INPUT_SAMPLE_RATE,
9
12
  VOICE_MAX_AUDIO_FRAME_BYTES,
10
13
  VOICE_MAX_CONTROL_BYTES,
11
14
  VOICE_MAX_UTTERANCE_SECONDS,
12
15
  VOICE_MAX_SYNTHESIS_TIMEOUT_MS,
13
16
  VOICE_PROTOCOL_VERSION,
17
+ VOICE_VOICES_PATH,
14
18
  assertVoiceAudioFrame,
15
19
  parseVoiceClientControl,
16
20
  speechPauseDurationMs,
@@ -18,12 +22,12 @@ import {
18
22
  voiceServerMessage
19
23
  } from "../shared/protocol.js";
20
24
  import { visemeCuesFromText } from "../shared/visemes.js";
21
- import {
22
- bearerVoiceAccessToken,
23
- verifyVoiceAccessToken
24
- } from "./voiceAccessToken.js";
25
+ import { bearerVoiceAccessToken, createVoiceCredentialStore } from "./voiceCredentials.js";
26
+ import { refuseUpgrade, requestPathname, writeJsonResponse } from "./voiceDaemonHttp.js";
27
+ import { createBoundedSpeechQueue } from "./voiceSpeechQueue.js";
25
28
 
26
29
  const WEBSOCKET_OPEN = 1;
30
+ const PACKAGE_VERSION = JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8")).version;
27
31
 
28
32
  function sendJson(socket, type, fields = {}) {
29
33
  if (socket.readyState !== WEBSOCKET_OPEN) {
@@ -56,96 +60,26 @@ function voiceDaemonError(error, fallback = { message: "Voice operation failed."
56
60
  };
57
61
  }
58
62
 
59
- function createBoundedSerialQueue({ maximumQueued = 4 } = {}) {
60
- const pending = [];
61
- let running = false;
62
- let closed = false;
63
-
64
- const drain = async () => {
65
- if (running || closed) {
66
- return;
67
- }
68
- const next = pending.shift();
69
- if (!next) {
70
- return;
71
- }
72
- running = true;
73
- try {
74
- next.resolve(await next.operation());
75
- } catch (error) {
76
- next.reject(error);
77
- } finally {
78
- running = false;
79
- void drain();
80
- }
81
- };
82
-
83
- function close() {
84
- closed = true;
85
- const error = Object.assign(new Error("Voice speech queue is shutting down."), {
86
- code: "voice_queue_closed", messageCode: "assistant.voice.daemon.queueClosing", messageParams: {}
87
- });
88
- for (const entry of pending.splice(0)) {
89
- entry.reject(error);
90
- }
91
- }
92
-
93
- function run(operation) {
94
- if (closed) {
95
- const error = Object.assign(new Error("Voice speech queue is unavailable."), {
96
- code: "voice_queue_closed", messageCode: "assistant.voice.daemon.queueUnavailable", messageParams: {}
97
- });
98
- return Promise.reject(error);
99
- }
100
- if (typeof operation !== "function") {
101
- return Promise.reject(new TypeError("Voice speech queue requires an operation."));
102
- }
103
- if (pending.length >= maximumQueued) {
104
- const error = Object.assign(new Error("Voice speech capacity is currently busy. Try again shortly."), {
105
- code: "voice_busy", messageCode: "assistant.voice.daemon.capacityBusy", messageParams: {}
106
- });
107
- return Promise.reject(error);
108
- }
109
- return new Promise((resolve, reject) => {
110
- pending.push({ operation, reject, resolve });
111
- void drain();
112
- });
113
- }
114
-
115
- return Object.freeze({
116
- close,
117
- get depth() {
118
- return pending.length + (running ? 1 : 0);
119
- },
120
- run
121
- });
122
- }
63
+ /** A connection that has not started work has none to cancel. */
64
+ function nothingToCancel() {}
123
65
 
124
- function requestPathname(request = {}) {
125
- try {
126
- return new URL(String(request.url || "/"), "http://voice.local").pathname;
127
- } catch {
128
- return "/";
129
- }
66
+ function poolSize(value) {
67
+ return Number.isSafeInteger(value) && value > 0 ? value : 1;
130
68
  }
131
69
 
132
- function writeJsonResponse(response, statusCode, payload) {
133
- const body = Buffer.from(JSON.stringify(payload));
134
- response.writeHead(statusCode, {
135
- "cache-control": "no-store",
136
- "content-length": String(body.byteLength),
137
- "content-type": "application/json; charset=utf-8"
138
- });
139
- response.end(body);
70
+ /** Writes each access record as one JSON line on standard output. */
71
+ function writeAccessLine(record) {
72
+ process.stdout.write(`${JSON.stringify(record)}\n`);
140
73
  }
141
74
 
142
75
  /**
143
- * A speech engine's recognition of one recording.
76
+ * A speech engine's recognition of one recording. Each method may answer a
77
+ * promise; the host runs one at a time per recording.
144
78
  * @typedef {object} VoiceRecognizer
145
- * @property {(frame: Buffer) => string} acceptPcm Recognizes a slice of 16 kHz PCM and answers the words so far.
146
- * @property {() => string} finish Ends the recording and answers its final words.
147
- * @property {() => string} reset Starts the next utterance of a continuous recording and answers the last one's words.
148
- * @property {() => boolean} isEndpoint Whether the speaker has paused at the end of an utterance.
79
+ * @property {(frame: Buffer) => string | Promise<string>} acceptPcm Recognizes a slice of 16 kHz PCM and answers the words so far.
80
+ * @property {() => string | Promise<string>} finish Ends the recording and answers its final words.
81
+ * @property {() => string | Promise<string>} reset Starts the next utterance of a continuous recording and answers the last one's words.
82
+ * @property {() => boolean | Promise<boolean>} isEndpoint Whether the speaker has paused at the end of an utterance.
149
83
  * @property {() => void} cancel Drops the recording.
150
84
  * @property {number} acceptedSamples The samples recognized so far.
151
85
  */
@@ -160,96 +94,150 @@ function writeJsonResponse(response, statusCode, payload) {
160
94
  * @property {number} [synthesisTimeoutMs] How long one phrase's synthesis may take, when longer than the protocol's default.
161
95
  * @property {{ id: string, label: string, language?: string }[]} [voices]
162
96
  * @property {string} [defaultVoice]
97
+ * @property {{ id: string, language?: string, hotwords?: number, spellings?: number }[]} [recognitionModels]
98
+ * @property {{ recognition?: number, synthesis?: number }} [concurrency] How many recognitions and syntheses it runs at once (default one each).
99
+ * @property {Record<string, string>} [versions] Its packages and native runtime, by name.
163
100
  */
164
101
 
165
102
  /**
166
- * The principal a request's access token names. Each of its ids has its own
167
- * connection quota.
168
- * @typedef {{ tenant: string, parentTenant?: string }} VoicePrincipal
103
+ * What a voice host records about one connection: never its audio or words.
104
+ * @typedef {object} VoiceAccessRecord
105
+ * @property {"voice.connection"} type
106
+ * @property {string | null} client The credentials file's client name, or null when the token named none.
107
+ * @property {string} startedAt
108
+ * @property {string} endedAt
109
+ * @property {number} audioSecondsHeard Seconds of microphone audio received.
110
+ * @property {number} charactersSpoken Characters of reply text given to synthesis.
111
+ * @property {"client" | "idle" | "revoked" | "shutdown" | "protocol" | "error" | "unauthorized" | "capacity"} closed
112
+ * @property {number} [closeCode]
169
113
  */
170
114
 
171
- /** A host without extra HTTP routes answers no request itself, so it falls through to 404. */
172
- function answerNoHostRoute() {
173
- return false;
174
- }
115
+ /**
116
+ * What a voice host records when it loads its credentials, at start and on each
117
+ * change of the file; voice.credentials.refused names a file it could not use,
118
+ * with the credentials still in use.
119
+ * @typedef {object} VoiceCredentialsRecord
120
+ * @property {"voice.credentials" | "voice.credentials.refused"} type
121
+ * @property {string} at
122
+ * @property {string | null} credentialsSha256 The SHA-256 of the file in use, or null when it is missing.
123
+ * @property {number} [clients]
124
+ * @property {string[]} [clientsAdded]
125
+ * @property {string[]} [clientsRemoved]
126
+ * @property {string[]} [clientsChanged] Clients whose tokens or limit changed.
127
+ * @property {number} [sessionsEnded] Open sessions whose token the change removed.
128
+ * @property {string} [reason]
129
+ */
175
130
 
176
131
  /**
177
132
  * A voice host: an HTTP server whose WebSocket connections recognize the speaker's
178
- * words and speak the answer, with the health and voice-catalogue routes.
133
+ * words and speak the answer, with the health and catalogue routes. Clients sign
134
+ * in with a bearer token whose SHA-256 the host's credentials file lists.
179
135
  * @param {object} options
180
- * @param {Buffer | string} [options.accessKey] The key that signs voice access tokens, when authorize is the default.
181
- * @param {(token: string, request: import("node:http").IncomingMessage) => VoicePrincipal | null} [options.authorize]
182
- * @param {(request: import("node:http").IncomingMessage, response: import("node:http").ServerResponse) => boolean | Promise<boolean>} [options.handleRequest] The host's own HTTP routes; true when it answered.
136
+ * @param {string} options.credentialsFile
137
+ * @param {number} [options.credentialsPollMs] How often the credentials file is checked for changes.
138
+ * @param {(record: VoiceAccessRecord | VoiceCredentialsRecord) => void} [options.accessLog] Receives one record per connection and one per credentials load; by default a JSON line on standard output.
183
139
  * @param {VoiceSpeechEngine} options.engine
184
140
  * @param {string} [options.host]
185
141
  * @param {number} [options.idleTimeoutMs]
186
142
  * @param {{ warn: (fields: object, message: string) => void }} [options.logger]
187
- * @param {number} [options.maximumConnections]
188
- * @param {number} [options.maximumConnectionsPerTenant]
189
- * @param {number} [options.maximumQueuedSpeech]
143
+ * @param {number} [options.maximumConnections] Default eight per recognition worker.
144
+ * @param {number} [options.maximumConnectionsPerClient] Default two per recognition worker; a client's own maximumConnections replaces it.
145
+ * @param {number} [options.maximumQueuedSpeech] Default four per synthesis worker.
190
146
  * @param {number} [options.port]
191
147
  */
192
148
  function createVoiceDaemon({
193
- accessKey,
194
- authorize = token => verifyVoiceAccessToken(token, { key: accessKey }),
195
- handleRequest = answerNoHostRoute,
149
+ credentialsFile,
150
+ credentialsPollMs = 1000,
151
+ accessLog = writeAccessLine,
196
152
  engine,
197
153
  host = "127.0.0.1",
198
154
  idleTimeoutMs = 90_000,
199
155
  logger = console,
200
- maximumConnections = 8,
201
- maximumConnectionsPerTenant = 2,
202
- maximumQueuedSpeech = 4,
156
+ maximumConnections,
157
+ maximumConnectionsPerClient,
158
+ maximumQueuedSpeech,
203
159
  port = 3092
204
160
  }) {
205
161
  // readable-check: allow method-probe - input validation: an application hands over the speech engine its host runs
206
162
  if (!engine || typeof engine.createListeningSession !== "function" || typeof engine.synthesize !== "function" || typeof engine.warmup !== "function") {
207
163
  throw new TypeError("createVoiceDaemon requires a speech engine.");
208
164
  }
209
- // readable-check: allow method-probe - input validation: an application hands over its own authorization and routes
210
- if (typeof authorize !== "function" || typeof handleRequest !== "function") throw new TypeError("Voice host authorization and request handlers must be functions.");
211
- const tenantConnections = new Map();
212
- const sockets = new Set();
213
- const principals = new WeakMap();
214
- const speechQueue = createBoundedSerialQueue({ maximumQueued: maximumQueuedSpeech });
215
- // One acceptance rule for every request: the host authorizer is synchronous
216
- // and must name a tenant; anything else, including a thrown error, denies.
217
- function principalFor(request) {
218
- let principal;
219
- try { principal = authorize(bearerVoiceAccessToken(request.headers), request); } catch { return null; }
220
- return principal && typeof principal.tenant === "string" && principal.tenant ? principal : null;
221
- }
165
+ const recognitionWorkers = poolSize(engine.concurrency?.recognition);
166
+ const synthesisWorkers = poolSize(engine.concurrency?.synthesis);
167
+ const totalLimit = maximumConnections ?? 8 * recognitionWorkers;
168
+ const clientLimit = maximumConnectionsPerClient ?? 2 * recognitionWorkers;
169
+ const clientConnections = new Map();
170
+ const connections = new Map();
171
+ const speechQueue = createBoundedSpeechQueue({
172
+ concurrency: synthesisWorkers,
173
+ maximumQueued: maximumQueuedSpeech ?? 4 * synthesisWorkers
174
+ });
175
+ const credentials = createVoiceCredentialStore({
176
+ file: credentialsFile,
177
+ pollIntervalMs: credentialsPollMs,
178
+ onRefused(reason) {
179
+ logAccess({ type: "voice.credentials.refused", at: new Date().toISOString(), reason, credentialsSha256: credentials.sha256 });
180
+ },
181
+ onChange(changes) {
182
+ const sessionsEnded = endRevokedConnections();
183
+ logAccess({ type: "voice.credentials", at: new Date().toISOString(), credentialsSha256: credentials.sha256, ...changes, sessionsEnded });
184
+ }
185
+ });
222
186
  let ready = false;
223
187
  let startedAt = "";
224
188
  let stopping = false;
189
+ const versions = Object.freeze({ "@jskit-ai/assistant-voice": PACKAGE_VERSION, ...engine.versions });
225
190
  const voiceCatalogue = () => ({
226
191
  voices: (engine.voices || []).map(({ id, label, language }) => ({ id, label, ...(language ? { language } : {}) })),
227
192
  defaultVoice: engine.defaultVoice || ""
228
193
  });
229
- const server = http.createServer(async (request, response) => {
230
- if (request.method === "GET" && requestPathname(request) === "/health") {
194
+ const serviceCatalogue = () => ({
195
+ protocolVersion: VOICE_PROTOCOL_VERSION,
196
+ inputSampleRate: VOICE_INPUT_SAMPLE_RATE,
197
+ outputSampleRate: Number(engine.sampleRate),
198
+ recognitionModels: (engine.recognitionModels || []).map(({ id, language, hotwords, spellings }) => ({
199
+ id, ...(language ? { language } : {}), ...(Number.isSafeInteger(hotwords) ? { hotwords } : {}),
200
+ ...(Number.isSafeInteger(spellings) ? { spellings } : {})
201
+ })),
202
+ ...voiceCatalogue()
203
+ });
204
+
205
+ function logAccess(record) {
206
+ try {
207
+ accessLog(Object.freeze({ type: "voice.connection", ...record }));
208
+ } catch (error) {
209
+ logger.warn({ error: String(error?.message || error) }, "Voice access log failed.");
210
+ }
211
+ }
212
+
213
+ function logRefusal(client, closed) {
214
+ const at = new Date().toISOString();
215
+ logAccess({ client, startedAt: at, endedAt: at, audioSecondsHeard: 0, charactersSpoken: 0, closed });
216
+ }
217
+
218
+ const authenticatedRoutes = new Map([
219
+ [VOICE_VOICES_PATH, voiceCatalogue],
220
+ [VOICE_CATALOGUE_PATH, serviceCatalogue]
221
+ ]);
222
+ const server = http.createServer((request, response) => {
223
+ const pathname = requestPathname(request);
224
+ if (request.method === "GET" && pathname === VOICE_HEALTH_PATH) {
231
225
  writeJsonResponse(response, ready && !stopping ? 200 : 503, {
232
- connections: sockets.size,
226
+ connections: connections.size,
233
227
  ok: ready && !stopping,
234
228
  protocolVersion: VOICE_PROTOCOL_VERSION,
235
229
  queueDepth: speechQueue.depth,
236
- startedAt
230
+ startedAt,
231
+ versions,
232
+ credentialsSha256: credentials.sha256
237
233
  });
238
234
  return;
239
235
  }
240
- try {
241
- if (request.method === "GET" && requestPathname(request) === "/voices") {
242
- if (!principalFor(request)) { writeJsonResponse(response, 401, { ok: false }); return; }
243
- if (!ready || stopping) { writeJsonResponse(response, 503, { ok: false }); return; }
244
- writeJsonResponse(response, 200, voiceCatalogue());
245
- return;
246
- }
247
- if (await handleRequest(request, response)) return;
248
- writeJsonResponse(response, 404, { ok: false });
249
- } catch {
250
- if (!response.headersSent) writeJsonResponse(response, 500, { ok: false, error: "Voice host request failed." });
251
- else response.end();
252
- }
236
+ const route = request.method === "GET" ? authenticatedRoutes.get(pathname) : null;
237
+ if (!route) { writeJsonResponse(response, 404, { ok: false }); return; }
238
+ if (!ready || stopping) { writeJsonResponse(response, 503, { ok: false }); return; }
239
+ if (!credentials.principalFor(bearerVoiceAccessToken(request.headers))) { writeJsonResponse(response, 401, { ok: false }); return; }
240
+ writeJsonResponse(response, 200, route());
253
241
  });
254
242
  const websocketServer = new WebSocketServer({
255
243
  maxPayload: Math.max(VOICE_MAX_AUDIO_FRAME_BYTES, VOICE_MAX_CONTROL_BYTES),
@@ -257,49 +245,73 @@ function createVoiceDaemon({
257
245
  perMessageDeflate: false
258
246
  });
259
247
 
260
- function quotaKeys(principal) { return [...new Set([principal.tenant, principal.parentTenant].filter(Boolean))]; }
261
-
262
248
  function connectionCapacityAvailable(principal) {
263
- return sockets.size < maximumConnections && quotaKeys(principal).every(key =>
264
- (tenantConnections.get(key) || 0) < maximumConnectionsPerTenant);
249
+ return connections.size < totalLimit &&
250
+ (clientConnections.get(principal.client) || 0) < (principal.maximumConnections ?? clientLimit);
265
251
  }
266
252
 
267
253
  function claimConnection(principal, socket) {
268
- sockets.add(socket);
269
- principals.set(socket, { ...principal });
270
- for (const key of quotaKeys(principal)) tenantConnections.set(key, (tenantConnections.get(key) || 0) + 1);
254
+ connections.set(socket, {
255
+ client: principal.client,
256
+ tokenSha256: principal.tokenSha256,
257
+ startedAt: new Date().toISOString(),
258
+ heardBytes: 0,
259
+ charactersSpoken: 0,
260
+ closed: "client",
261
+ cancel: nothingToCancel
262
+ });
263
+ clientConnections.set(principal.client, (clientConnections.get(principal.client) || 0) + 1);
271
264
  }
272
265
 
273
- function releaseConnection(socket) {
274
- if (!sockets.delete(socket)) return;
275
- for (const key of quotaKeys(principals.get(socket))) {
276
- const next = (tenantConnections.get(key) || 1) - 1;
277
- if (next) tenantConnections.set(key, next);
278
- else tenantConnections.delete(key);
279
- }
280
- principals.delete(socket);
266
+ function releaseConnection(socket, closeCode) {
267
+ const connection = connections.get(socket);
268
+ if (!connection) return;
269
+ connections.delete(socket);
270
+ const next = (clientConnections.get(connection.client) || 1) - 1;
271
+ if (next) clientConnections.set(connection.client, next);
272
+ else clientConnections.delete(connection.client);
273
+ logAccess({
274
+ client: connection.client,
275
+ startedAt: connection.startedAt,
276
+ endedAt: new Date().toISOString(),
277
+ audioSecondsHeard: Math.round(connection.heardBytes / 2 / VOICE_INPUT_SAMPLE_RATE * 100) / 100,
278
+ charactersSpoken: connection.charactersSpoken,
279
+ closed: connection.closed,
280
+ ...(Number.isInteger(closeCode) ? { closeCode } : {})
281
+ });
281
282
  }
282
283
 
283
- function revokeTenant(tenant) {
284
- for (const socket of sockets) {
285
- if (quotaKeys(principals.get(socket)).includes(tenant)) {
286
- principals.get(socket).cancel();
287
- sendJson(socket, "error", { code: "voice_access_revoked", message: "This application's voice access was revoked." });
288
- socket.close(1008, "Voice access was revoked");
289
- }
284
+ function closeConnection(socket, reason, code, message) {
285
+ const connection = connections.get(socket);
286
+ if (connection && connection.closed === "client") connection.closed = reason;
287
+ socket.close(code, message);
288
+ }
289
+
290
+ // A credential the host removed ends its open sessions at once, work and all,
291
+ // and the connection is cut a second later if the peer does not answer the close.
292
+ function endRevokedConnections() {
293
+ let ended = 0;
294
+ for (const [socket, connection] of connections) {
295
+ if (connection.closed === "revoked" || credentials.accepts(connection.tokenSha256, connection.client)) continue;
296
+ ended += 1;
297
+ connection.cancel();
298
+ sendJson(socket, "error", { code: "voice_access_revoked", message: "This application's voice access was revoked." });
299
+ closeConnection(socket, "revoked", 1008, "Voice access was revoked");
300
+ setTimeout(() => socket.terminate(), 1000).unref();
290
301
  }
302
+ return ended;
291
303
  }
292
304
 
293
- websocketServer.on("connection", (socket, request, context = {}) => {
294
- const tenantId = context.tenant;
295
- claimConnection(context, socket);
305
+ websocketServer.on("connection", (socket, request, principal) => {
306
+ claimConnection(principal, socket);
307
+ const connection = connections.get(socket);
296
308
  let listening = null;
309
+ let finishing = null;
297
310
  let speaking = null;
298
311
  let invalidMessages = 0;
299
312
  let lastActivity = Date.now();
300
313
 
301
314
  const cancelListening = () => {
302
- clearImmediate(listening?.decodeTimer);
303
315
  if (listening) listening.recognizer.cancel();
304
316
  listening = null;
305
317
  };
@@ -314,7 +326,7 @@ function createVoiceDaemon({
314
326
  if (Date.now() - lastActivity < idleTimeoutMs || socket.readyState !== WEBSOCKET_OPEN) {
315
327
  return;
316
328
  }
317
- socket.close(1000, "Voice connection idle");
329
+ closeConnection(socket, "idle", 1000, "Voice connection idle");
318
330
  }, Math.min(idleTimeoutMs, 15_000));
319
331
  idleTimer.unref();
320
332
 
@@ -323,11 +335,15 @@ function createVoiceDaemon({
323
335
  const publicError = voiceDaemonError(error);
324
336
  sendJson(socket, "error", publicError);
325
337
  if (invalidMessages >= 3) {
326
- socket.close(1008, "Invalid voice protocol messages");
338
+ closeConnection(socket, "protocol", 1008, "Invalid voice protocol messages");
327
339
  }
328
340
  };
329
341
 
330
- principals.get(socket).cancel = () => { cancelListening(); cancelSpeaking(); };
342
+ connection.cancel = () => {
343
+ cancelListening();
344
+ if (finishing) { finishing.cancelled = true; finishing.recognizer.cancel(); }
345
+ cancelSpeaking();
346
+ };
331
347
 
332
348
  const startListening = (control) => {
333
349
  cancelListening();
@@ -348,49 +364,61 @@ function createVoiceDaemon({
348
364
  }
349
365
  });
350
366
  listening = { recognizer, turnId, revision: 0, candidateRevision: 0, continuous: control.continuous === true,
351
- pending: [], pendingBytes: 0, decodeTimer: null, ending: false };
367
+ pending: [], pendingBytes: 0, draining: false, ending: false, cancelled: false };
352
368
  sendJson(socket, "listen.started", { turnId });
353
369
  };
354
370
 
355
- const drainListening = (active) => {
356
- if (active.decodeTimer || listening !== active || !active.pending.length) return;
357
- // Native recognition is synchronous. Yield between small audio slices so
358
- // a burst of microphone frames cannot starve PCM delivery or controls.
359
- active.decodeTimer = setImmediate(() => {
360
- active.decodeTimer = null;
361
- if (listening !== active) return;
362
- const { frame, control } = active.pending.shift();
371
+ const recognizeNext = async (active) => {
372
+ const { frame, control } = active.pending.shift();
373
+ if (frame) {
374
+ active.pendingBytes -= frame.byteLength;
375
+ if (active.recognizer.acceptedSamples + frame.byteLength / 2 > VOICE_INPUT_SAMPLE_RATE * VOICE_MAX_UTTERANCE_SECONDS) {
376
+ throw Object.assign(new Error(`Voice recordings are limited to ${VOICE_MAX_UTTERANCE_SECONDS} seconds.`), {
377
+ code: "voice_utterance_too_long", params: { seconds: VOICE_MAX_UTTERANCE_SECONDS }
378
+ });
379
+ }
380
+ await active.recognizer.acceptPcm(frame);
381
+ } else if (control.type === "listen.stop") {
382
+ listening = null;
383
+ finishing = active;
363
384
  try {
364
- if (frame) {
365
- active.pendingBytes -= frame.byteLength;
366
- if (active.recognizer.acceptedSamples + frame.byteLength / 2 > VOICE_INPUT_SAMPLE_RATE * VOICE_MAX_UTTERANCE_SECONDS) {
367
- throw Object.assign(new Error(`Voice recordings are limited to ${VOICE_MAX_UTTERANCE_SECONDS} seconds.`), {
368
- code: "voice_utterance_too_long", params: { seconds: VOICE_MAX_UTTERANCE_SECONDS }
369
- });
370
- }
371
- active.recognizer.acceptPcm(frame);
372
- } else if (control.type === "listen.stop") {
373
- listening = null;
374
- const text = active.recognizer.finish();
375
- sendJson(socket, "transcript.final", { text, turnId: active.turnId });
376
- } else if (!active.continuous || active.candidateRevision !== control.revision || !active.recognizer.isEndpoint()) {
377
- sendJson(socket, "transcript.stale", { turnId: active.turnId, revision: control.revision });
378
- } else {
379
- const text = active.recognizer.reset();
380
- active.candidateRevision = 0;
381
- active.revision += 1;
382
- if (control.type === "listen.commit") sendJson(socket, "transcript.final", {
383
- text, turnId: active.turnId, revision: control.revision, continuous: true
384
- });
385
- sendJson(socket, "transcript.reset", { turnId: active.turnId, revision: active.revision });
385
+ const text = await active.recognizer.finish();
386
+ if (!active.cancelled) sendJson(socket, "transcript.final", { text, turnId: active.turnId });
387
+ } finally { if (finishing === active) finishing = null; }
388
+ } else if (!active.continuous || active.candidateRevision !== control.revision || !(await active.recognizer.isEndpoint())) {
389
+ sendJson(socket, "transcript.stale", { turnId: active.turnId, revision: control.revision });
390
+ } else {
391
+ const text = await active.recognizer.reset();
392
+ if (listening !== active) return;
393
+ active.candidateRevision = 0;
394
+ active.revision += 1;
395
+ if (control.type === "listen.commit") sendJson(socket, "transcript.final", {
396
+ text, turnId: active.turnId, revision: control.revision, continuous: true
397
+ });
398
+ sendJson(socket, "transcript.reset", { turnId: active.turnId, revision: active.revision });
399
+ }
400
+ };
401
+
402
+ // One recognition step at a time per recording, each after a turn of the
403
+ // event loop, so a burst of microphone frames cannot starve PCM delivery or
404
+ // controls, and a recording's steps keep their order.
405
+ const drainListening = async (active) => {
406
+ if (active.draining) return;
407
+ active.draining = true;
408
+ try {
409
+ while (listening === active && active.pending.length) {
410
+ await new Promise(resolve => setImmediate(resolve));
411
+ if (listening !== active) return;
412
+ try {
413
+ await recognizeNext(active);
414
+ } catch (error) {
415
+ if (listening === active) cancelListening();
416
+ else active.recognizer.cancel();
417
+ if (!active.cancelled) failMessage(error);
418
+ return;
386
419
  }
387
- } catch (error) {
388
- if (listening === active) cancelListening();
389
- else active.recognizer.cancel();
390
- failMessage(error);
391
420
  }
392
- drainListening(active);
393
- });
421
+ } finally { active.draining = false; }
394
422
  };
395
423
 
396
424
  const queueListening = (active, entry) => {
@@ -405,7 +433,7 @@ function createVoiceDaemon({
405
433
  }
406
434
  active.pending.push(entry);
407
435
  active.pendingBytes += bytes;
408
- drainListening(active);
436
+ void drainListening(active);
409
437
  };
410
438
 
411
439
  const drainSpeech = async (active) => {
@@ -415,7 +443,7 @@ function createVoiceDaemon({
415
443
  try {
416
444
  while (active.pending.length && !controller.signal.aborted) {
417
445
  const chunk = active.pending.shift();
418
- // Queue each phrase separately so another tenant can get a turn.
446
+ // Queue each phrase separately so another client can get a turn.
419
447
  const phrases = splitSpeechText(chunk);
420
448
  for (const [position, text] of phrases.entries()) {
421
449
  if (active.segmentIndex > active.stopAfter || controller.signal.aborted) break;
@@ -432,7 +460,9 @@ function createVoiceDaemon({
432
460
  ...(Number.isSafeInteger(synthesisTimeoutMs) && synthesisTimeoutMs > VOICE_DEFAULT_SYNTHESIS_TIMEOUT_MS &&
433
461
  synthesisTimeoutMs <= VOICE_MAX_SYNTHESIS_TIMEOUT_MS ? { synthesisTimeoutMs } : {}) });
434
462
  let sampleCount = 0;
435
- const result = text.trim() ? await engine.synthesize(text.trim(), {
463
+ const words = text.trim();
464
+ if (words) connection.charactersSpoken += [...words].length;
465
+ const result = words ? await engine.synthesize(words, {
436
466
  onAudio(frame) {
437
467
  if (controller.signal.aborted || socket.readyState !== WEBSOCKET_OPEN) return;
438
468
  // Do not wait for the phrase's duration/visemes to start audio.
@@ -499,6 +529,7 @@ function createVoiceDaemon({
499
529
  });
500
530
  }
501
531
  const frame = assertVoiceAudioFrame(raw);
532
+ connection.heardBytes += frame.byteLength;
502
533
  const active = listening;
503
534
  const sliceBytes = VOICE_INPUT_SAMPLE_RATE / 10 * 2;
504
535
  for (let offset = 0; offset < frame.byteLength; offset += sliceBytes) {
@@ -554,8 +585,13 @@ function createVoiceDaemon({
554
585
  void drainSpeech(speaking);
555
586
  } else if (control.type === "cancel") {
556
587
  if (listening?.turnId === control.turnId) {
588
+ listening.cancelled = true;
557
589
  cancelListening();
558
590
  }
591
+ if (finishing?.turnId === control.turnId) {
592
+ finishing.cancelled = true;
593
+ finishing.recognizer.cancel();
594
+ }
559
595
  if (speaking?.turnId === control.turnId) {
560
596
  cancelSpeaking();
561
597
  }
@@ -567,14 +603,14 @@ function createVoiceDaemon({
567
603
  }
568
604
  });
569
605
 
570
- socket.once("close", () => {
606
+ socket.once("close", (code) => {
571
607
  clearInterval(idleTimer);
572
- cancelListening();
573
- cancelSpeaking();
574
- releaseConnection(socket);
608
+ connection.cancel();
609
+ releaseConnection(socket, code);
575
610
  });
576
611
  socket.once("error", (error) => {
577
- logger.warn({ error: String(error?.message || error), tenantId }, "Voice WebSocket failed.");
612
+ if (connection.closed === "client") connection.closed = "error";
613
+ logger.warn({ error: String(error?.message || error), client: connection.client }, "Voice WebSocket failed.");
578
614
  });
579
615
  sendJson(socket, "voice.ready", {
580
616
  inputSampleRate: VOICE_INPUT_SAMPLE_RATE,
@@ -585,23 +621,22 @@ function createVoiceDaemon({
585
621
 
586
622
  server.on("upgrade", (request, socket, head) => {
587
623
  if (stopping || !ready || requestPathname(request) !== VOICE_DAEMON_WEBSOCKET_PATH) {
588
- socket.write("HTTP/1.1 503 Service Unavailable\r\nConnection: close\r\n\r\n");
589
- socket.destroy();
624
+ refuseUpgrade(socket, "503 Service Unavailable");
590
625
  return;
591
626
  }
592
- const verified = principalFor(request);
593
- if (!verified) {
594
- socket.write("HTTP/1.1 401 Unauthorized\r\nConnection: close\r\n\r\n");
595
- socket.destroy();
627
+ const principal = credentials.principalFor(bearerVoiceAccessToken(request.headers));
628
+ if (!principal) {
629
+ logRefusal(null, "unauthorized");
630
+ refuseUpgrade(socket, "401 Unauthorized");
596
631
  return;
597
632
  }
598
- if (!connectionCapacityAvailable(verified)) {
599
- socket.write("HTTP/1.1 429 Too Many Requests\r\nConnection: close\r\nRetry-After: 2\r\n\r\n");
600
- socket.destroy();
633
+ if (!connectionCapacityAvailable(principal)) {
634
+ logRefusal(principal.client, "capacity");
635
+ refuseUpgrade(socket, "429 Too Many Requests", "Retry-After: 2\r\n");
601
636
  return;
602
637
  }
603
638
  websocketServer.handleUpgrade(request, socket, head, (websocket) => {
604
- websocketServer.emit("connection", websocket, request, verified);
639
+ websocketServer.emit("connection", websocket, request, principal);
605
640
  });
606
641
  });
607
642
 
@@ -609,20 +644,26 @@ function createVoiceDaemon({
609
644
  if (ready) {
610
645
  return address();
611
646
  }
612
- await engine.warmup();
613
- await new Promise((resolve, reject) => {
614
- const fail = (error) => {
615
- server.off("listening", listen);
616
- reject(error);
617
- };
618
- const listen = () => {
619
- server.off("error", fail);
620
- resolve();
621
- };
622
- server.once("error", fail);
623
- server.once("listening", listen);
624
- server.listen(port, host);
625
- });
647
+ credentials.start();
648
+ try {
649
+ await engine.warmup();
650
+ await new Promise((resolve, reject) => {
651
+ const fail = (error) => {
652
+ server.off("listening", listen);
653
+ reject(error);
654
+ };
655
+ const listen = () => {
656
+ server.off("error", fail);
657
+ resolve();
658
+ };
659
+ server.once("error", fail);
660
+ server.once("listening", listen);
661
+ server.listen(port, host);
662
+ });
663
+ } catch (error) {
664
+ credentials.stop();
665
+ throw error;
666
+ }
626
667
  ready = true;
627
668
  startedAt = new Date().toISOString();
628
669
  return address();
@@ -641,9 +682,10 @@ function createVoiceDaemon({
641
682
  }
642
683
  stopping = true;
643
684
  ready = false;
685
+ credentials.stop();
644
686
  speechQueue.close();
645
- for (const socket of sockets) {
646
- socket.close(1012, "Voice service restarting");
687
+ for (const socket of connections.keys()) {
688
+ closeConnection(socket, "shutdown", 1012, "Voice service restarting");
647
689
  }
648
690
  await new Promise((resolve, reject) => {
649
691
  websocketServer.close(() => {
@@ -658,23 +700,24 @@ function createVoiceDaemon({
658
700
 
659
701
  function metrics() {
660
702
  return Object.freeze({
661
- connections: sockets.size,
662
- queueDepth: speechQueue.depth,
663
- tenants: tenantConnections.size
703
+ clients: clientConnections.size,
704
+ connections: connections.size,
705
+ queueDepth: speechQueue.depth
664
706
  });
665
707
  }
666
708
 
667
709
  return Object.freeze({
668
710
  address,
669
711
  close,
670
- revokeTenant,
671
712
  metrics,
672
- start
713
+ start,
714
+ /** The SHA-256 of the credentials file in use, as /health reports it. */
715
+ get credentialsSha256() { return credentials.sha256; }
673
716
  });
674
717
  }
675
718
 
676
719
  export {
677
- createBoundedSerialQueue,
720
+ createBoundedSpeechQueue,
678
721
  createVoiceDaemon,
679
722
  sendJson,
680
723
  voiceDaemonError