@jskit-ai/assistant-voice 0.1.44 → 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.
@@ -44,10 +44,15 @@ function sendPcm(socket, audio = Buffer.alloc(0)) {
44
44
  return true;
45
45
  }
46
46
 
47
- function voiceDaemonError(error, fallback = "Voice operation failed.") {
47
+ // An error event keeps its code and English message, and carries what a browser
48
+ // needs to show that sentence in the user's language.
49
+ function voiceDaemonError(error, fallback = { message: "Voice operation failed.", messageCode: "assistant.voice.daemon.operationFailed" }) {
50
+ const source = error?.message || error ? error : fallback;
48
51
  return {
49
52
  code: String(error?.code || "voice_operation_failed"),
50
- message: String(error?.message || error || fallback)
53
+ message: String(error?.message || error || fallback.message),
54
+ ...(source?.params ? { params: source.params } : {}),
55
+ ...(source?.messageCode ? { messageCode: source.messageCode, messageParams: source.messageParams || {} } : {})
51
56
  };
52
57
  }
53
58
 
@@ -78,8 +83,9 @@ function createBoundedSerialQueue({ maximumQueued = 4 } = {}) {
78
83
  return Object.freeze({
79
84
  close() {
80
85
  closed = true;
81
- const error = new Error("Voice speech queue is shutting down.");
82
- error.code = "voice_queue_closed";
86
+ const error = Object.assign(new Error("Voice speech queue is shutting down."), {
87
+ code: "voice_queue_closed", messageCode: "assistant.voice.daemon.queueClosing", messageParams: {}
88
+ });
83
89
  for (const entry of pending.splice(0)) {
84
90
  entry.reject(error);
85
91
  }
@@ -89,16 +95,18 @@ function createBoundedSerialQueue({ maximumQueued = 4 } = {}) {
89
95
  },
90
96
  run(operation) {
91
97
  if (closed) {
92
- const error = new Error("Voice speech queue is unavailable.");
93
- error.code = "voice_queue_closed";
98
+ const error = Object.assign(new Error("Voice speech queue is unavailable."), {
99
+ code: "voice_queue_closed", messageCode: "assistant.voice.daemon.queueUnavailable", messageParams: {}
100
+ });
94
101
  return Promise.reject(error);
95
102
  }
96
103
  if (typeof operation !== "function") {
97
104
  return Promise.reject(new TypeError("Voice speech queue requires an operation."));
98
105
  }
99
106
  if (pending.length >= maximumQueued) {
100
- const error = new Error("Voice speech capacity is currently busy. Try again shortly.");
101
- error.code = "voice_busy";
107
+ const error = Object.assign(new Error("Voice speech capacity is currently busy. Try again shortly."), {
108
+ code: "voice_busy", messageCode: "assistant.voice.daemon.capacityBusy", messageParams: {}
109
+ });
102
110
  return Promise.reject(error);
103
111
  }
104
112
  return new Promise((resolve, reject) => {
@@ -301,7 +309,7 @@ function createVoiceDaemon({
301
309
  active.pendingBytes -= frame.byteLength;
302
310
  if (active.recognizer.acceptedSamples + frame.byteLength / 2 > VOICE_INPUT_SAMPLE_RATE * VOICE_MAX_UTTERANCE_SECONDS) {
303
311
  throw Object.assign(new Error(`Voice recordings are limited to ${VOICE_MAX_UTTERANCE_SECONDS} seconds.`), {
304
- code: "voice_utterance_too_long"
312
+ code: "voice_utterance_too_long", params: { seconds: VOICE_MAX_UTTERANCE_SECONDS }
305
313
  });
306
314
  }
307
315
  active.recognizer.acceptPcm(frame);
@@ -404,7 +412,7 @@ function createVoiceDaemon({
404
412
  }
405
413
  } catch (error) {
406
414
  if (!controller.signal.aborted) sendJson(socket, error?.code === "voice_busy" ? "busy" : "error", {
407
- ...voiceDaemonError(error, "Speech could not be generated."), turnId
415
+ ...voiceDaemonError(error, { message: "Speech could not be generated.", messageCode: "assistant.voice.daemon.speechFailed" }), turnId
408
416
  });
409
417
  controller.abort();
410
418
  if (speaking === active) speaking = null;
@@ -414,7 +422,9 @@ function createVoiceDaemon({
414
422
  const startSpeaking = (control) => {
415
423
  const voiceId = control.voiceId || engine.defaultVoice;
416
424
  if (voiceId && !engine.voices?.some(voice => voice.id === voiceId)) {
417
- throw Object.assign(new Error("This voice is unavailable. Choose another voice."), { code: "voice_selection_invalid" });
425
+ throw Object.assign(new Error("This voice is unavailable. Choose another voice."), {
426
+ code: "voice_selection_invalid", messageCode: "assistant.voice.daemon.voiceUnavailable", messageParams: {}
427
+ });
418
428
  }
419
429
  cancelSpeaking();
420
430
  speaking = { controller: new AbortController(), turnId: control.turnId,
@@ -428,9 +438,9 @@ function createVoiceDaemon({
428
438
  try {
429
439
  if (isBinary) {
430
440
  if (!listening || listening.ending) {
431
- const error = new Error("Audio arrived without an active recording.");
432
- error.code = "voice_listen_not_active";
433
- throw error;
441
+ throw Object.assign(new Error("Audio arrived without an active recording."), {
442
+ code: "voice_listen_not_active", messageCode: "assistant.voice.daemon.audioWithoutRecording", messageParams: {}
443
+ });
434
444
  }
435
445
  const frame = assertVoiceAudioFrame(raw);
436
446
  const active = listening;
@@ -448,7 +458,9 @@ function createVoiceDaemon({
448
458
  startListening(control);
449
459
  } else if (control.type === "listen.stop") {
450
460
  if (!listening || listening.ending || listening.turnId !== control.turnId) {
451
- throw Object.assign(new Error("No matching voice recording is active."), { code: "voice_listen_not_active" });
461
+ throw Object.assign(new Error("No matching voice recording is active."), {
462
+ code: "voice_listen_not_active", messageCode: "assistant.voice.daemon.noRecording", messageParams: {}
463
+ });
452
464
  }
453
465
  listening.ending = true;
454
466
  queueListening(listening, { control });
@@ -476,7 +488,11 @@ function createVoiceDaemon({
476
488
  throw Object.assign(new Error("No matching speech stream is open."), { code: "voice_speech_not_active" });
477
489
  }
478
490
  if (control.type === "speak.append") {
479
- if (speaking.pending.length >= 2) throw Object.assign(new Error("Speech is arriving faster than playback."), { code: "voice_busy" });
491
+ if (speaking.pending.length >= 2) {
492
+ throw Object.assign(new Error("Speech is arriving faster than playback."), {
493
+ code: "voice_busy", messageCode: "assistant.voice.daemon.speechTooFast", messageParams: {}
494
+ });
495
+ }
480
496
  speaking.pending.push(control.text);
481
497
  } else speaking.ended = true;
482
498
  void drainSpeech(speaking);
@@ -53,7 +53,8 @@ async function readVoiceCatalogue(config, { fetchImpl = fetch } = {}) {
53
53
  return catalogue;
54
54
  } catch (cause) {
55
55
  throw Object.assign(new Error("Speaking voices could not load. Check the speech service and retry."), {
56
- code: "voice_unavailable", statusCode: 503, cause
56
+ code: "voice_unavailable", statusCode: 503, cause,
57
+ messageCode: "assistant.voice.proxy.voicesUnavailable", messageParams: {}
57
58
  });
58
59
  }
59
60
  }
@@ -65,9 +66,13 @@ function closeSocket(socket, code, reason) {
65
66
  }
66
67
  }
67
68
 
68
- function sendSocketError(socket, code, message) {
69
+ // code and message stay the wire contract. params fill a catalogued code's sentence,
70
+ // and messageCode names the sentence where one code has several.
71
+ function sendSocketError(socket, code, message, { params, messageCode, messageParams = {} } = {}) {
69
72
  if (socket?.readyState === WEBSOCKET_OPEN) {
70
- socket.send(voiceServerMessage("error", { code, message }));
73
+ socket.send(voiceServerMessage("error", {
74
+ code, message, ...(params ? { params } : {}), ...(messageCode ? { messageCode, messageParams } : {})
75
+ }));
71
76
  }
72
77
  }
73
78
 
@@ -103,7 +108,9 @@ function registerVoiceProxyRoute(fastify, {
103
108
  browserSocket.once("error", () => closeBoth(1011, "Browser voice connection failed"));
104
109
 
105
110
  if (!config.available) {
106
- sendSocketError(browserSocket, "voice_unavailable", "Voice is not installed on this server.");
111
+ sendSocketError(browserSocket, "voice_unavailable", "Voice is not installed on this server.", {
112
+ messageCode: "assistant.voice.proxy.notInstalled"
113
+ });
107
114
  closeBoth(1013, "Voice service unavailable");
108
115
  return;
109
116
  }
@@ -150,7 +157,8 @@ function registerVoiceProxyRoute(fastify, {
150
157
  sendSocketError(
151
158
  browserSocket,
152
159
  String(error?.code || "voice_control_invalid"),
153
- String(error?.message || error)
160
+ String(error?.message || error),
161
+ { params: error?.params, messageCode: error?.messageCode, messageParams: error?.messageParams }
154
162
  );
155
163
  return;
156
164
  }
@@ -190,25 +198,27 @@ function registerVoiceProxyRoute(fastify, {
190
198
  browserSocket.send(frame, { binary: isBinary });
191
199
  });
192
200
  serviceSocket.once("unexpected-response", (_request, response) => {
193
- const code = Number(response?.statusCode) === 429 ? "voice_busy" : "voice_unavailable";
194
- const message = code === "voice_busy"
195
- ? "Voice is busy. Try again shortly."
196
- : "Voice service could not be reached.";
197
- sendSocketError(browserSocket, code, message);
201
+ const { code, message, messageCode } = Number(response?.statusCode) === 429
202
+ ? { code: "voice_busy", message: "Voice is busy. Try again shortly.", messageCode: "assistant.voice.proxy.busy" }
203
+ : { code: "voice_unavailable", message: "Voice service could not be reached.", messageCode: "assistant.voice.proxy.unreachable" };
204
+ sendSocketError(browserSocket, code, message, { messageCode });
198
205
  closeBoth(1013, message);
199
206
  });
200
207
  serviceSocket.once("close", (code, reason) => {
201
208
  closeBoth(code || 1012, reason?.toString() || "Voice service closed");
202
209
  });
203
210
  serviceSocket.once("error", () => {
204
- sendSocketError(browserSocket, "voice_unavailable", "Voice service could not be reached.");
211
+ sendSocketError(browserSocket, "voice_unavailable", "Voice service could not be reached.", {
212
+ messageCode: "assistant.voice.proxy.unreachable"
213
+ });
205
214
  closeBoth(1013, "Voice service unavailable");
206
215
  });
207
216
  })().catch((error) => {
208
217
  sendSocketError(
209
218
  browserSocket,
210
219
  String(error?.code || "voice_session_failed"),
211
- "Voice could not open for this conversation."
220
+ "Voice could not open for this conversation.",
221
+ { messageCode: "assistant.voice.proxy.sessionFailed" }
212
222
  );
213
223
  closeBoth([401, 403].includes(error?.statusCode) ? 1008 : 1011, "Voice session failed");
214
224
  });
@@ -1,3 +1,6 @@
1
+ import { catalogMessage } from "@jskit-ai/kernel/shared/i18n";
2
+ import en from "../../locales/en.json" with { type: "json" };
3
+
1
4
  const VOICE_PROTOCOL_VERSION = 1;
2
5
  const VOICE_DAEMON_WEBSOCKET_PATH = "/v1/voice";
3
6
  const VOICE_INPUT_SAMPLE_RATE = 16_000;
@@ -28,12 +31,25 @@ const VOICE_CLIENT_CONTROL_TYPES = new Set([
28
31
  "speak.stop-after"
29
32
  ]);
30
33
 
31
- function voiceProtocolError(code, message) {
34
+ // code and the English message are the wire contract; params fill the code's
35
+ // catalogued sentence so a browser can show it in the user's language.
36
+ function voiceProtocolError(code, message, params) {
32
37
  const error = new Error(message);
33
38
  error.code = code;
39
+ if (params) error.params = params;
34
40
  return error;
35
41
  }
36
42
 
43
+ // What speech says in place of content it leaves on screen. The browser passes the
44
+ // wording of its active language; the default is JSKIT's English.
45
+ const VOICE_SPEECH_WORDING = Object.freeze({
46
+ code: catalogMessage(en, "jskit.assistant.voice.speech.codeOnScreen"),
47
+ sql: catalogMessage(en, "jskit.assistant.voice.speech.sqlOnScreen"),
48
+ details: catalogMessage(en, "jskit.assistant.voice.speech.detailsInChat"),
49
+ image: catalogMessage(en, "jskit.assistant.voice.speech.image"),
50
+ link: catalogMessage(en, "jskit.assistant.voice.speech.link")
51
+ });
52
+
37
53
  function voiceTurnId(value = "") {
38
54
  const turnId = String(value || "").trim();
39
55
  if (!VOICE_TURN_ID_PATTERN.test(turnId)) {
@@ -74,7 +90,8 @@ function parseVoiceClientControl(raw = "") {
74
90
  if (!VOICE_CLIENT_CONTROL_TYPES.has(type)) {
75
91
  throw voiceProtocolError(
76
92
  "voice_control_type_invalid",
77
- `Unsupported voice control type: ${type || "(missing)"}.`
93
+ `Unsupported voice control type: ${type || "(missing)"}.`,
94
+ { type: type || "(missing)" }
78
95
  );
79
96
  }
80
97
  const turnId = voiceTurnId(input.turnId);
@@ -83,7 +100,8 @@ function parseVoiceClientControl(raw = "") {
83
100
  if (sampleRate !== VOICE_INPUT_SAMPLE_RATE) {
84
101
  throw voiceProtocolError(
85
102
  "voice_input_sample_rate_invalid",
86
- `Voice input must be ${VOICE_INPUT_SAMPLE_RATE} Hz mono PCM.`
103
+ `Voice input must be ${VOICE_INPUT_SAMPLE_RATE} Hz mono PCM.`,
104
+ { sampleRate: VOICE_INPUT_SAMPLE_RATE }
87
105
  );
88
106
  }
89
107
  return Object.freeze({ sampleRate, turnId, type, ...(input.continuous === true ? { continuous: true } : {}) });
@@ -98,13 +116,16 @@ function parseVoiceClientControl(raw = "") {
98
116
  }
99
117
  if (type === "speak.start" || type === "speak.append") {
100
118
  if (input.voiceId !== undefined && (type !== "speak.start" || typeof input.voiceId !== "string" || !VOICE_ID_PATTERN.test(input.voiceId))) {
101
- throw voiceProtocolError("voice_selection_invalid", "Choose an available voice before starting speech.");
119
+ throw Object.assign(voiceProtocolError("voice_selection_invalid", "Choose an available voice before starting speech."), {
120
+ messageCode: "assistant.voice.protocol.chooseVoice", messageParams: {}
121
+ });
102
122
  }
103
123
  const text = String(input.text || "");
104
124
  if ((!text.trim() && !/[\r\n]/u.test(text)) || text.length > VOICE_MAX_SPEECH_TEXT_CHARACTERS) {
105
125
  throw voiceProtocolError(
106
126
  "voice_speech_text_invalid",
107
- `Speech text must contain 1-${VOICE_MAX_SPEECH_TEXT_CHARACTERS} characters.`
127
+ `Speech text must contain 1-${VOICE_MAX_SPEECH_TEXT_CHARACTERS} characters.`,
128
+ { maximum: VOICE_MAX_SPEECH_TEXT_CHARACTERS }
108
129
  );
109
130
  }
110
131
  return Object.freeze({ text, turnId, type, ...(input.stream === true ? { stream: true } : {}), ...(input.voiceId ? { voiceId: input.voiceId } : {}) });
@@ -224,24 +245,24 @@ function normalizeRecognizedText(value = "", vocabulary = {}) {
224
245
  return result;
225
246
  }
226
247
 
227
- function speechTextFromAssistant(value = "", maximumCharacters = VOICE_MAX_SPEECH_TEXT_CHARACTERS) {
248
+ function speechTextFromAssistant(value = "", maximumCharacters = VOICE_MAX_SPEECH_TEXT_CHARACTERS, wording = VOICE_SPEECH_WORDING) {
228
249
  let omittedCode = false;
229
250
  let omittedTable = false;
230
251
  let text = String(value || "").slice(0, maximumCharacters * 2);
231
252
  text = text.replace(/```([a-z0-9_-]*)[^\n]*\n[\s\S]*?```/giu, (_match, language) => {
232
253
  omittedCode = true;
233
254
  return String(language || "").toLowerCase() === "sql"
234
- ? " I put the SQL on screen. "
235
- : " I put the code on screen. ";
255
+ ? ` ${wording.sql} `
256
+ : ` ${wording.code} `;
236
257
  });
237
258
  text = text.replace(/(?:^|\n)\s*\|[^\n]+\|\s*(?=\n|$)/gu, () => {
238
259
  omittedTable = true;
239
260
  return "\n";
240
261
  });
241
262
  text = text
242
- .replace(/!\[[^\]]*\]\([^)]*\)/gu, " an image ")
263
+ .replace(/!\[[^\]]*\]\([^)]*\)/gu, () => ` ${wording.image} `)
243
264
  .replace(/\[([^\]]+)\]\([^)]*\)/gu, "$1")
244
- .replace(/https?:\/\/\S+/giu, " a link ")
265
+ .replace(/https?:\/\/\S+/giu, () => ` ${wording.link} `)
245
266
  .replace(/`([^`\n]+)`/gu, "$1")
246
267
  .replace(/^[\t ]{0,3}#{1,6}[\t ]+/gmu, "");
247
268
  const lines = text.split(/\r?\n/u);
@@ -255,11 +276,11 @@ function speechTextFromAssistant(value = "", maximumCharacters = VOICE_MAX_SPEEC
255
276
  .replace(/[^\S\r\n]+/gu, " ").trim();
256
277
  return boundary + words;
257
278
  }).join("").replace(/\n{3,}/gu, "\n\n");
258
- if (omittedTable && !/details (?:are|remain) in (?:the )?chat/iu.test(text)) {
259
- text = `${text}${text ? " " : ""}The details are in the chat.`;
279
+ if (omittedTable && !/details (?:are|remain) in (?:the )?chat/iu.test(text) && !text.includes(wording.details)) {
280
+ text = `${text}${text ? " " : ""}${wording.details}`;
260
281
  }
261
282
  if (omittedCode && !text) {
262
- text = "I put the code on screen.";
283
+ text = wording.code;
263
284
  }
264
285
  return text.slice(0, maximumCharacters);
265
286
  }
@@ -358,7 +379,7 @@ function splitSpeechText(value = "", maximumCharacters = VOICE_MAX_SPEECH_CHUNK_
358
379
 
359
380
  // Consume only a speakable prefix. Incomplete Markdown stays buffered so code,
360
381
  // link targets and revised last words never leak into speech a token at a time.
361
- function takeStreamingSpeech(text = "", final = false, maximumCharacters = 140) {
382
+ function takeStreamingSpeech(text = "", final = false, maximumCharacters = 140, wording = VOICE_SPEECH_WORDING) {
362
383
  const source = String(text);
363
384
  // Wait for the whole table before summarizing it. Splitting inside a long
364
385
  // row would read cells aloud and repeat the summary for every later row.
@@ -372,7 +393,7 @@ function takeStreamingSpeech(text = "", final = false, maximumCharacters = 140)
372
393
  }
373
394
  if (consumed) {
374
395
  const boundary = source.slice(0, consumed).match(/(?:\r?\n[\t ]*)+$/u)?.[0] || "";
375
- return { text: speechTextFromAssistant(`The details are in the chat.${boundary}`), consumed };
396
+ return { text: speechTextFromAssistant(`${wording.details}${boundary}`, undefined, wording), consumed };
376
397
  }
377
398
  }
378
399
  let fence = false;
@@ -417,8 +438,8 @@ function takeStreamingSpeech(text = "", final = false, maximumCharacters = 140)
417
438
  if (/\n[\t ]*$/u.test(raw) && /^(?:[-*+]|\d+[.)])[\t ]+/u.test(source.slice(end))) {
418
439
  raw = `${raw.trimEnd()}\n\n`;
419
440
  }
420
- if (final && fence) raw = raw.replace(/```[\s\S]*$/u, " I put the code on screen. ");
421
- return { text: speechTextFromAssistant(raw), consumed: end };
441
+ if (final && fence) raw = raw.replace(/```[\s\S]*$/u, () => ` ${wording.code} `);
442
+ return { text: speechTextFromAssistant(raw, undefined, wording), consumed: end };
422
443
  }
423
444
 
424
445
  function voiceServerMessage(type = "", fields = {}) {