@skaile/forge-voice 0.0.0-stage → 0.1.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/dist/wire.mjs ADDED
@@ -0,0 +1,792 @@
1
+ // src/shared/audio-tags.ts
2
+ /**
3
+ * Audio tags in a spoken reply: `[[whispers]]`, `[[laughs]]`. The reply-format contract between an
4
+ * agent that writes tags and the speech model that performs them. The stored text keeps them; what a
5
+ * chat shows of a voice reply, what Talk counts as heard (`heardChars`) and what a server reuses of one
6
+ * (history, search, recaps) is the text without them. Only voice replies have tags: anywhere else
7
+ * `[[...]]` is code or a wiki link. Browser and server import the same functions, so both count
8
+ * offsets the same way; keep this file free of runtime-specific imports.
9
+ */
10
+ /** `[[` + letters, spaces, commas, hyphens or apostrophes (at most 40) + `]]`. */
11
+ const TAG_SOURCE = "\\[\\[[\\p{L} ,'-]{1,40}\\]\\]";
12
+ const anyDoubleBracket = /\[\[[^\]\n]*\]\]/gu;
13
+ const pendingTail = /\[\[[\p{L} ,'-]{0,40}\]?$/u;
14
+ /** The text without its audio tags. */
15
+ function stripAudioTags(text) {
16
+ return text.replace(new RegExp(TAG_SOURCE, "gu"), "");
17
+ }
18
+ /**
19
+ * Where `rawOffset` in the stored text lands in the stripped text. An offset inside a tag lands
20
+ * where the tag was.
21
+ */
22
+ function strippedOffset(raw, rawOffset) {
23
+ const end = Math.max(0, Math.min(rawOffset, raw.length));
24
+ let removed = 0;
25
+ for (const match of raw.matchAll(new RegExp(TAG_SOURCE, "gu"))) {
26
+ const start = match.index ?? 0;
27
+ if (start >= end) break;
28
+ removed += Math.min(match[0].length, end - start);
29
+ }
30
+ return end - removed;
31
+ }
32
+ /**
33
+ * The text without any double-bracket tag, malformed ones too (`[[laughs!]]`): what Talk speaks
34
+ * on the fallback model or shows as a caption, never a `[[`. Not for offsets: `stripAudioTags`.
35
+ */
36
+ function stripAnyAudioTags(text) {
37
+ return text.replace(anyDoubleBracket, "");
38
+ }
39
+ /**
40
+ * Where a trailing, not yet closed tag starts (`[[laug`, `[[laughs]`, or a lone final `[`), so
41
+ * Talk holds it back until it closes instead of speaking or cutting half of it; -1 otherwise.
42
+ */
43
+ function pendingTagStart(text) {
44
+ const match = pendingTail.exec(text);
45
+ if (match) return match.index;
46
+ return text.endsWith("[") ? text.length - 1 : -1;
47
+ }
48
+ /**
49
+ * The ElevenLabs v4 form: `[[x]]` becomes `[x]`; a malformed double-bracket tag is dropped.
50
+ */
51
+ function toElevenLabsTags(text) {
52
+ const valid = new RegExp(`^${TAG_SOURCE}$`, "u");
53
+ return text.replace(anyDoubleBracket, (tag) => valid.test(tag) ? tag.slice(1, -1) : "");
54
+ }
55
+ const codeSpan = /```[\s\S]*?(?:```|$)|`[^`\n]+`/g;
56
+ /** The [start, end) ranges of fenced code blocks and inline code spans in `text`. */
57
+ function codeRanges(text) {
58
+ return [...text.matchAll(codeSpan)].map((m) => [m.index, m.index + m[0].length]);
59
+ }
60
+ function inCode(ranges, at) {
61
+ return ranges.some(([start, end]) => at >= start && at < end);
62
+ }
63
+ /**
64
+ * What Chat shows of a voice reply: its valid tags removed, except inside code (a fenced block or
65
+ * an inline span), where `[[x]]` is the code's own (bash `[[ -d x ]]`, a wiki link).
66
+ */
67
+ function stripAudioTagsForDisplay(text) {
68
+ if (!text.includes("[[")) return text;
69
+ const ranges = codeRanges(text);
70
+ return text.replace(new RegExp(TAG_SOURCE, "gu"), (tag, at) => inCode(ranges, at) ? tag : "");
71
+ }
72
+ /** The [start, end) ranges of the audio tags in `raw`. */
73
+ function audioTagRanges(raw) {
74
+ return [...raw.matchAll(new RegExp(TAG_SOURCE, "gu"))].map((m) => [m.index ?? 0, (m.index ?? 0) + m[0].length]);
75
+ }
76
+ /**
77
+ * A voice reply's text for reuse as plain text (history, search, recaps, read-aloud): every
78
+ * `[[...]]` removed, malformed ones too since Flash reads them aloud, but none inside code. Text
79
+ * without one comes back unchanged; a removed tag takes one adjacent space, nothing else is touched.
80
+ * Callers outside `/voice/speak` apply it to voice replies only. `inCodeToo`: code as well, for
81
+ * `/voice/speak`, where the fast model would read a tag aloud wherever it is.
82
+ * Not for offsets: `stripAudioTags`.
83
+ */
84
+ function stripAudioTagsForText(text, { inCodeToo = false } = {}) {
85
+ if (!text.includes("[[")) return text;
86
+ const ranges = inCodeToo ? [] : codeRanges(text);
87
+ let out = "";
88
+ let pos = 0;
89
+ for (const match of text.matchAll(anyDoubleBracket)) {
90
+ if (inCode(ranges, match.index)) continue;
91
+ out += text.slice(pos, match.index);
92
+ let end = match.index + match[0].length;
93
+ const next = text[end];
94
+ if (next === " " && (out === "" || /\s$/.test(out))) end += 1;
95
+ else if ((next === void 0 || !/[\p{L}\p{N}]/u.test(next)) && out.endsWith(" ")) out = out.slice(0, -1);
96
+ pos = end;
97
+ }
98
+ return out + text.slice(pos);
99
+ }
100
+ // src/shared/voice-languages.ts
101
+ /**
102
+ * Spoken languages a session may pin for speech-to-text, as Deepgram nova-3 codes.
103
+ * `multi` is nova-3's multilingual mode, which a relay default language of `auto` maps to.
104
+ * A closed list: the value is interpolated into the upstream URL.
105
+ */
106
+ const STT_LANGUAGES = [
107
+ "multi",
108
+ "en",
109
+ "en-US",
110
+ "en-GB",
111
+ "de",
112
+ "de-CH",
113
+ "fr",
114
+ "es",
115
+ "it",
116
+ "nl",
117
+ "pt",
118
+ "pt-BR",
119
+ "pl",
120
+ "sv",
121
+ "da",
122
+ "no",
123
+ "fi",
124
+ "tr",
125
+ "ru",
126
+ "uk",
127
+ "ja",
128
+ "ko",
129
+ "hi"
130
+ ];
131
+ const STT_LANGUAGE_SET = new Set(STT_LANGUAGES);
132
+ /** The requested language when it is on the list, else null (the caller falls back to the deployment default). */
133
+ function parseSttLanguage(value) {
134
+ return typeof value === "string" && STT_LANGUAGE_SET.has(value) ? value : null;
135
+ }
136
+ /**
137
+ * The ElevenLabs `language_code` for a pinned STT language: the bare ISO 639-1 part,
138
+ * or null for `multi` / anything malformed.
139
+ */
140
+ function ttsLanguageCode(value) {
141
+ const lang = parseSttLanguage(typeof value === "string" ? value.trim() : value);
142
+ if (!lang || lang === "multi") return null;
143
+ return lang.slice(0, 2);
144
+ }
145
+ /**
146
+ * ElevenLabs refuses `language_code` on models that do not enforce a language; today
147
+ * that is everything except the v2.5 Flash and Turbo models and the v3 / v4 family
148
+ * (which Talk's text-to-dialogue stream uses).
149
+ */
150
+ function modelAcceptsLanguageCode(modelId) {
151
+ return /^eleven_(flash|turbo)_v2_5$/.test(modelId) || /^eleven_v[34](_|$)/.test(modelId);
152
+ }
153
+ // src/shared/speech-terms.ts
154
+ /**
155
+ * Speech terms: words Talk should hear and say right. Each entry is for one spoken language; its
156
+ * `term` is boosted in Deepgram's recognition (keyterm prompting), and an optional
157
+ * `pronunciation` is the spelling the speech model reads instead (a text alias). Plain types and
158
+ * functions only: a host that validates stored terms builds its schema from the constants here
159
+ * (`SPEECH_TERM_LANGUAGES`, `SPEECH_TERM_PATTERN`, the length limits, `sameSpeechTerm`).
160
+ */
161
+ /** Base language codes a term can be for (`multi` and regional variants fold into these). */
162
+ const SPEECH_TERM_LANGUAGES = [...new Set(STT_LANGUAGES.filter((lang) => lang !== "multi").map((lang) => lang.slice(0, 2)))];
163
+ const MAX_SPEECH_TERMS = 60;
164
+ const MAX_SPEECH_TERM_CHARS = 50;
165
+ const MAX_PRONUNCIATION_CHARS = 80;
166
+ /**
167
+ * Letters, digits, spaces and the punctuation names use; nothing that could act as markup. A stored
168
+ * term or pronunciation also has no double or trailing spaces (`tidySpeechTermText` folds them).
169
+ */
170
+ const SPEECH_TERM_PATTERN = /^[\p{L}\p{N}][\p{L}\p{N} .'’&+-]*$/u;
171
+ /** Folds whitespace the way stored terms are written, before they are validated. */
172
+ function tidySpeechTermText(value) {
173
+ return value.normalize("NFC").replace(/\s+/g, " ").trim();
174
+ }
175
+ /** Whether two entries name the same term: same language, same term ignoring case. */
176
+ function sameSpeechTerm(a, b) {
177
+ return a.language === b.language && a.term.toLowerCase() === b.term.toLowerCase();
178
+ }
179
+ /** The list with `entry` added, or replacing the same term in the same language. */
180
+ function withSpeechTerm(list, entry) {
181
+ return [...list.filter((other) => !sameSpeechTerm(other, entry)), entry];
182
+ }
183
+ /** The list without that term in that language. */
184
+ function withoutSpeechTerm(list, entry) {
185
+ return list.filter((other) => !sameSpeechTerm(other, entry));
186
+ }
187
+ /** A term's base language matches the stream's; `multi` or no language means every term. */
188
+ function speechTermLanguageMatches(termLanguage, streamLanguage) {
189
+ return !streamLanguage || streamLanguage === "multi" || streamLanguage.slice(0, 2) === termLanguage;
190
+ }
191
+ /**
192
+ * Dev words Talk hears in every conversation about work, per base language. German speech uses
193
+ * the English words with German endings ("mergen", "gemergt"), which Deepgram heard as "Merchant".
194
+ */
195
+ const BUILT_IN_KEYTERMS = {
196
+ de: [
197
+ "mergen",
198
+ "gemergt",
199
+ "Merge",
200
+ "Pull Request",
201
+ "Issue",
202
+ "Deploy",
203
+ "deployen",
204
+ "Branch",
205
+ "Commit",
206
+ "Review"
207
+ ],
208
+ en: [
209
+ "merge",
210
+ "pull request",
211
+ "issue",
212
+ "deploy",
213
+ "branch",
214
+ "commit"
215
+ ]
216
+ };
217
+ /**
218
+ * Spellings German speech reads English dev words with. ElevenLabs reads "mergen" with a German
219
+ * g; respelled, the German voice says it the English way. Matched as whole words, case-insensitively.
220
+ */
221
+ const BUILT_IN_PRONUNCIATIONS = { de: [
222
+ {
223
+ term: "mergen",
224
+ pronunciation: "mördschen"
225
+ },
226
+ {
227
+ term: "gemergt",
228
+ pronunciation: "gemördscht"
229
+ },
230
+ {
231
+ term: "gemerged",
232
+ pronunciation: "gemördscht"
233
+ },
234
+ {
235
+ term: "merge",
236
+ pronunciation: "mördsch"
237
+ },
238
+ {
239
+ term: "merges",
240
+ pronunciation: "mördsches"
241
+ },
242
+ {
243
+ term: "mergt",
244
+ pronunciation: "mördscht"
245
+ },
246
+ {
247
+ term: "Pull Request",
248
+ pronunciation: "Pull Riquest"
249
+ },
250
+ {
251
+ term: "Pull Requests",
252
+ pronunciation: "Pull Riquests"
253
+ },
254
+ {
255
+ term: "Issue",
256
+ pronunciation: "Ischu"
257
+ },
258
+ {
259
+ term: "Issues",
260
+ pronunciation: "Ischus"
261
+ },
262
+ {
263
+ term: "deployen",
264
+ pronunciation: "diploien"
265
+ },
266
+ {
267
+ term: "deployt",
268
+ pronunciation: "diploit"
269
+ },
270
+ {
271
+ term: "Deploy",
272
+ pronunciation: "Diploi"
273
+ }
274
+ ] };
275
+ /**
276
+ * Deepgram refuses a request whose keyterms exceed 500 tokens in total, and its tokenizer is not
277
+ * public. A term is counted at its UTF-8 bytes (spaces included) plus one per word, which no subword tokenizer
278
+ * exceeds (umlauts count twice), and the budget stays well below 500. Deepgram advises 20-50 terms.
279
+ */
280
+ const KEYTERM_TOKEN_BUDGET = 400;
281
+ const MAX_KEYTERMS = 50;
282
+ /** The user's own terms may fill at most this share, so the assistant name and dev words always fit. */
283
+ const USER_KEYTERM_TOKEN_BUDGET = 240;
284
+ const MAX_USER_KEYTERMS = 30;
285
+ const MAX_KEYTERM_WORDS = 5;
286
+ const utf8 = new TextEncoder();
287
+ function estimateKeytermTokens(term) {
288
+ return utf8.encode(term).length + term.split(" ").filter(Boolean).length;
289
+ }
290
+ /** A name fit to prompt with: short, made of words, no markup. Null when it is not. */
291
+ function cleanKeyterm(raw) {
292
+ const term = raw.normalize("NFC").replace(/[\p{Cc}\p{Cf}]/gu, "").replace(/\s+/g, " ").trim();
293
+ if (!term || term.length > 50 || !/\p{L}/u.test(term)) return null;
294
+ if (term.split(" ").length > MAX_KEYTERM_WORDS) return null;
295
+ return term;
296
+ }
297
+ /**
298
+ * The keyterms for one request in a fixed priority: the user's own terms (newest first, within
299
+ * their own share), the assistant's name, the built-in dev words, org/project/agent names, then
300
+ * own session names. Deduplicated
301
+ * case-insensitively, within {@link MAX_KEYTERMS} and {@link KEYTERM_TOKEN_BUDGET}; a term over the
302
+ * remaining budget is skipped and a shorter later one may still fit, so the result is deterministic.
303
+ */
304
+ function buildKeyterms({ language, userTerms, assistantName, names, sessionNames = [] }) {
305
+ const builtIn = Object.entries(BUILT_IN_KEYTERMS).filter(([lang]) => speechTermLanguageMatches(lang, language)).flatMap(([, terms]) => terms);
306
+ const own = userTerms.filter((entry) => speechTermLanguageMatches(entry.language, language)).map((entry) => entry.term).reverse();
307
+ const seen = /* @__PURE__ */ new Set();
308
+ const out = [];
309
+ let tokens = 0;
310
+ const take = (raws, maxTokens, maxTerms) => {
311
+ for (const raw of raws) {
312
+ const term = cleanKeyterm(raw);
313
+ if (!term || seen.has(term.toLowerCase())) continue;
314
+ const cost = estimateKeytermTokens(term);
315
+ if (tokens + cost > maxTokens) continue;
316
+ seen.add(term.toLowerCase());
317
+ out.push(term);
318
+ tokens += cost;
319
+ if (out.length >= maxTerms) return;
320
+ }
321
+ };
322
+ take(own, 240, 30);
323
+ take([
324
+ ...assistantName ? [assistantName] : [],
325
+ ...builtIn,
326
+ ...names,
327
+ ...sessionNames
328
+ ], 400, 50);
329
+ return out;
330
+ }
331
+ // src/shared/spoken-language-default.ts
332
+ /**
333
+ * The spoken language for a conversation language (a locale such as `de-DE`): the locale
334
+ * itself when the recognizer knows that region, else its bare language, else null (the
335
+ * deployment default).
336
+ */
337
+ function sttLanguageForLocale(locale) {
338
+ if (!locale) return null;
339
+ return parseSttLanguage(locale) ?? parseSttLanguage(locale.split("-")[0]);
340
+ }
341
+ /**
342
+ * What dictation and read-aloud use: the language the person pinned by hand, else the one
343
+ * they converse in here. A pin is never replaced; clearing it returns to following them.
344
+ */
345
+ function effectiveSttLanguage(pinned, conversationLocale) {
346
+ return pinned ?? sttLanguageForLocale(conversationLocale);
347
+ }
348
+ // src/shared/spoken-sentences.ts
349
+ /**
350
+ * Splits a reply that is still streaming into sentences that can be spoken now.
351
+ * A sentence ends at `.`, `!`, `?` or `…` followed by whitespace, or at a line
352
+ * break. Very short pieces ("1.", "OK.") wait for the next one, so one request
353
+ * never carries a single syllable.
354
+ */
355
+ const MIN_SENTENCE_CHARS = 12;
356
+ const BOUNDARY = /[.!?…]+["')\]]*\s+|\n+/g;
357
+ function takeCompleteSentences(text, from) {
358
+ const sentences = [];
359
+ let start = from;
360
+ BOUNDARY.lastIndex = from;
361
+ for (let match = BOUNDARY.exec(text); match; match = BOUNDARY.exec(text)) {
362
+ const end = match.index + match[0].length;
363
+ const piece = text.slice(start, end).trim();
364
+ if (stripAudioTags(piece).trim().length >= 12 || match[0].includes("\n") && piece.length > 0) {
365
+ sentences.push(piece);
366
+ start = end;
367
+ }
368
+ }
369
+ return {
370
+ sentences,
371
+ next: start
372
+ };
373
+ }
374
+ /**
375
+ * Removes the markdown that would be read out as symbols: emphasis, headings,
376
+ * inline code ticks, list bullets, and link targets (the link text stays).
377
+ * Fenced code blocks are dropped entirely.
378
+ */
379
+ function toSpeakableText(markdown) {
380
+ return markdown.replace(/```[\s\S]*?(```|$)/g, " ").replace(/!?\[([^\]]*)\]\([^)]*\)/g, "$1").replace(/^\s{0,3}#{1,6}\s+/gm, "").replace(/^\s*[-*+]\s+/gm, "").replace(/(\*\*|__|\*|_|`)/g, "").replace(/[ \t]+/g, " ").trim();
381
+ }
382
+ // src/shared/stop-phrases.ts
383
+ /**
384
+ * Utterances the hands-free loop acts on instead of sending. Matched against the
385
+ * whole utterance, so "stop the deployment" still reaches the agent.
386
+ */
387
+ /**
388
+ * "Stop talking" / "be quiet and listen": barge-in has already silenced the reply; the
389
+ * words are not sent and the loop goes on.
390
+ */
391
+ const HUSH_PHRASES = /* @__PURE__ */ new Set([
392
+ "stop",
393
+ "stopp",
394
+ "quiet",
395
+ "ruhe",
396
+ "pause",
397
+ "warte",
398
+ "warte mal",
399
+ "moment",
400
+ "einen moment",
401
+ "kurz",
402
+ "halt",
403
+ "wait",
404
+ "hold on",
405
+ "one moment"
406
+ ]);
407
+ const LONGEST_HUSH_PHRASE = Math.max(...[...HUSH_PHRASES].map((phrase) => phrase.split(" ").length));
408
+ /** End the loop. */
409
+ const STOP_PHRASES = /* @__PURE__ */ new Set([
410
+ "stop listening",
411
+ "stop hands free",
412
+ "end hands free",
413
+ "hands free off",
414
+ "hör auf",
415
+ "hör auf zuzuhören",
416
+ "freihändig aus",
417
+ "arrête",
418
+ "arrête d’écouter"
419
+ ]);
420
+ /** Lowercases and drops punctuation and hyphens, so "Stop listening." matches "stop listening". */
421
+ function normalize(utterance) {
422
+ return utterance.toLowerCase().replace(/['’]/g, "’").replace(/[-–]/g, " ").replace(/[^\p{L}\p{N}’ ]/gu, "").replace(/\s+/g, " ").trim();
423
+ }
424
+ /** What a hands-free utterance asks of the loop itself; null when it is a message for the agent. */
425
+ function loopCommand(utterance) {
426
+ const phrase = normalize(utterance);
427
+ if (STOP_PHRASES.has(phrase)) return "end";
428
+ return HUSH_PHRASES.has(phrase) ? "hush" : null;
429
+ }
430
+ /**
431
+ * True when the whole utterance is made of hush phrases (greedy longest match), so
432
+ * "Stopp, warte mal" hushes but "Stopp, was meinst du damit?" is a message.
433
+ */
434
+ function isHushOnly(utterance) {
435
+ const tokens = normalize(utterance).split(" ").filter(Boolean);
436
+ if (tokens.length === 0) return false;
437
+ let i = 0;
438
+ while (i < tokens.length) {
439
+ let matched = 0;
440
+ for (let len = Math.min(LONGEST_HUSH_PHRASE, tokens.length - i); len > 0 && matched === 0; len--) if (HUSH_PHRASES.has(tokens.slice(i, i + len).join(" "))) matched = len;
441
+ if (matched === 0) return false;
442
+ i += matched;
443
+ }
444
+ return true;
445
+ }
446
+ // src/shared/utterance-end.ts
447
+ /**
448
+ * How long the hands-free loop waits after Deepgram reports the end of speech before
449
+ * it sends what was said. Deepgram ends an utterance after 300 ms of silence, which a
450
+ * breath mid-sentence already reaches, so a sentence would leave as several messages.
451
+ * Speech inside the wait joins the same message; a transcript that stops mid-sentence
452
+ * waits longer, but is still sent, so the loop never stalls on a dropped thought.
453
+ */
454
+ /** After a finished sentence. */
455
+ const UTTERANCE_HOLD_MS = 2e3;
456
+ /** After a transcript that stops mid-sentence, and the cap while the user is still talking. */
457
+ const UTTERANCE_HOLD_MID_SENTENCE_MS = 5e3;
458
+ const TERMINAL_PUNCTUATION = /[.?!。?!]["'”’)\]]*$/u;
459
+ const QUESTION_OR_EXCLAMATION = /[?!?!]["'”’)\]]*$/u;
460
+ const DANGLING_PUNCTUATION = /(?:[,;:–—-]|\.\.\.|…)["'”’)\]]*$/u;
461
+ const CONTINUATION_WORDS = /* @__PURE__ */ new Set([
462
+ "a",
463
+ "an",
464
+ "the",
465
+ "and",
466
+ "or",
467
+ "but",
468
+ "because",
469
+ "if",
470
+ "to",
471
+ "of",
472
+ "with",
473
+ "is",
474
+ "are",
475
+ "was",
476
+ "were",
477
+ "my",
478
+ "your",
479
+ "our",
480
+ "their",
481
+ "der",
482
+ "die",
483
+ "das",
484
+ "den",
485
+ "dem",
486
+ "des",
487
+ "ein",
488
+ "eine",
489
+ "einen",
490
+ "einem",
491
+ "einer",
492
+ "und",
493
+ "oder",
494
+ "aber",
495
+ "weil",
496
+ "dass",
497
+ "wenn",
498
+ "für",
499
+ "von",
500
+ "ist",
501
+ "sind"
502
+ ]);
503
+ /** True when the transcript reads as a thought that has not finished yet. */
504
+ function endsMidSentence(transcript) {
505
+ const text = transcript.trim();
506
+ if (!text || DANGLING_PUNCTUATION.test(text)) return true;
507
+ if (QUESTION_OR_EXCLAMATION.test(text)) return false;
508
+ const lastWord = text.toLowerCase().split(/\s+/).at(-1).replace(/[^\p{L}\p{N}’']/gu, "");
509
+ if (CONTINUATION_WORDS.has(lastWord)) return true;
510
+ return !TERMINAL_PUNCTUATION.test(text);
511
+ }
512
+ /** The wait before sending `transcript`, the utterance collected so far. */
513
+ function utteranceHoldMs(transcript) {
514
+ return endsMidSentence(transcript) ? UTTERANCE_HOLD_MID_SENTENCE_MS : UTTERANCE_HOLD_MS;
515
+ }
516
+ /**
517
+ * Talk answers aloud, so it hands an utterance over sooner than dictation: after a finished
518
+ * sentence and this much silence (on top of Deepgram's 300 ms endpointing). A sentence the user
519
+ * goes on with after a longer pause still reaches the agent as one request: Talk restarts the
520
+ * turn with the whole of it.
521
+ */
522
+ const TALK_HOLD_MS = 800;
523
+ /** A short answer ("Ja", "Nein, danke", "Okay."), whatever its punctuation: sent promptly. */
524
+ const TALK_HOLD_SHORT_MS = 250;
525
+ /** The most Talk waits after a transcript that reads unfinished ("…, wenn ich", "mit meinen"). */
526
+ const TALK_HOLD_UNFINISHED_MS = 1200;
527
+ /** Up to this many words an utterance is a short answer, unless its words end openly. */
528
+ const TALK_SHORT_WORDS = 3;
529
+ const TALK_FILLER_WORDS = /* @__PURE__ */ new Set([
530
+ "also",
531
+ "so",
532
+ "äh",
533
+ "ähm",
534
+ "öh",
535
+ "öhm",
536
+ "hm",
537
+ "uh",
538
+ "uhm",
539
+ "um",
540
+ "erm"
541
+ ]);
542
+ const TALK_OPEN_WORDS = /* @__PURE__ */ new Set([
543
+ "in",
544
+ "im",
545
+ "ins",
546
+ "zum",
547
+ "zur",
548
+ "beim",
549
+ "vom",
550
+ "über",
551
+ "unter",
552
+ "ohne",
553
+ "gegen",
554
+ "seit",
555
+ "mein",
556
+ "meine",
557
+ "meinen",
558
+ "meinem",
559
+ "meiner",
560
+ "dein",
561
+ "deine",
562
+ "deinen",
563
+ "deinem",
564
+ "deiner",
565
+ "seine",
566
+ "seinen",
567
+ "seinem",
568
+ "seiner",
569
+ "unser",
570
+ "unsere",
571
+ "unseren",
572
+ "unserem",
573
+ "for",
574
+ "from",
575
+ "into"
576
+ ]);
577
+ const CLAUSE_OPENERS = /* @__PURE__ */ new Set([
578
+ "wenn",
579
+ "dass",
580
+ "weil",
581
+ "ob",
582
+ "als",
583
+ "obwohl",
584
+ "damit",
585
+ "bevor",
586
+ "nachdem",
587
+ "falls",
588
+ "wo",
589
+ "wie",
590
+ "was",
591
+ "warum",
592
+ "wieso",
593
+ "if",
594
+ "when",
595
+ "because",
596
+ "whether",
597
+ "that"
598
+ ]);
599
+ const PRONOUNS = /* @__PURE__ */ new Set([
600
+ "ich",
601
+ "du",
602
+ "er",
603
+ "sie",
604
+ "es",
605
+ "wir",
606
+ "ihr",
607
+ "man",
608
+ "i",
609
+ "you",
610
+ "he",
611
+ "she",
612
+ "it",
613
+ "we",
614
+ "they"
615
+ ]);
616
+ const MODAL_VERBS = /* @__PURE__ */ new Set([
617
+ "kann",
618
+ "kannst",
619
+ "könnte",
620
+ "könntest",
621
+ "soll",
622
+ "sollst",
623
+ "sollte",
624
+ "solltest",
625
+ "muss",
626
+ "musst",
627
+ "müsste",
628
+ "will",
629
+ "willst",
630
+ "möchte",
631
+ "möchtest",
632
+ "darf",
633
+ "darfst",
634
+ "wird",
635
+ "wirst",
636
+ "würde",
637
+ "würdest"
638
+ ]);
639
+ const NOT_INFINITIVES = /* @__PURE__ */ new Set([
640
+ "den",
641
+ "einen",
642
+ "meinen",
643
+ "deinen",
644
+ "seinen",
645
+ "ihren",
646
+ "unseren",
647
+ "euren",
648
+ "keinen",
649
+ "diesen",
650
+ "jenen",
651
+ "welchen",
652
+ "allen",
653
+ "vielen",
654
+ "anderen",
655
+ "denen",
656
+ "wen",
657
+ "zwischen",
658
+ "oben",
659
+ "unten",
660
+ "hinten",
661
+ "wegen",
662
+ "gegen",
663
+ "neben"
664
+ ]);
665
+ function wordsOf(transcript) {
666
+ return transcript.trim().toLowerCase().split(/\s+/).map((word) => word.replace(/[^\p{L}\p{N}’']/gu, "")).filter(Boolean);
667
+ }
668
+ function looksLikeVerbEnd(word) {
669
+ if (NOT_INFINITIVES.has(word)) return false;
670
+ return word.length >= 4 && /(?:en|ern|eln)$/u.test(word) || word.length >= 5 && /^ge.*(?:t|en)$/u.test(word);
671
+ }
672
+ /** The last clause has a modal verb and no infinitive after it yet: "du sollst auf den Kalender". */
673
+ function modalWithoutInfinitive(transcript) {
674
+ const clause = wordsOf(transcript.split(/[,;:]/u).at(-1) ?? "");
675
+ const modal = clause.findIndex((word) => MODAL_VERBS.has(word));
676
+ return modal !== -1 && !clause.slice(modal + 1).some(looksLikeVerbEnd);
677
+ }
678
+ const MODAL_COMPLETERS = /* @__PURE__ */ new Set([
679
+ "los",
680
+ "weg",
681
+ "nicht",
682
+ "schon",
683
+ "ja",
684
+ "auch",
685
+ "mit",
686
+ "hin",
687
+ "her",
688
+ "raus",
689
+ "rein",
690
+ "zu",
691
+ "an",
692
+ "aus",
693
+ "gern",
694
+ "gerne",
695
+ ...PRONOUNS
696
+ ]);
697
+ const SENTENCE_FINAL_ARTICLES = /* @__PURE__ */ new Set(["das"]);
698
+ /**
699
+ * True when the words themselves leave the thought open, whatever the punctuation: a joining word,
700
+ * a preposition or possessive, a filler, a subordinating word and its pronoun ("wenn ich"), or a
701
+ * modal verb still waiting for its infinitive. A question or an exclamation is finished.
702
+ */
703
+ function talkOpenEnding(transcript) {
704
+ const words = wordsOf(transcript);
705
+ const last = words.at(-1);
706
+ if (!last || QUESTION_OR_EXCLAMATION.test(transcript.trim())) return false;
707
+ if (CONTINUATION_WORDS.has(last) && !SENTENCE_FINAL_ARTICLES.has(last) || TALK_OPEN_WORDS.has(last)) return true;
708
+ const before = words.at(-2);
709
+ if (before && CLAUSE_OPENERS.has(before) && PRONOUNS.has(last)) return true;
710
+ if (TERMINAL_PUNCTUATION.test(transcript.trim())) return false;
711
+ return TALK_FILLER_WORDS.has(last) || modalWithoutInfinitive(transcript) && !MODAL_COMPLETERS.has(last);
712
+ }
713
+ const ANNOUNCING_PUNCTUATION = /(?:[;:–—-]|\.\.\.|…)["'”’)\]]*$/u;
714
+ /**
715
+ * True when a Talk transcript reads as unfinished: its words end openly, it stops on a colon, dash
716
+ * or ellipsis, or a longer one stops on a comma. A short answer's comma ("Ja,") and a missing full
717
+ * stop count for nothing; STT puts both on finished words.
718
+ */
719
+ function talkLooksUnfinished(transcript) {
720
+ const text = transcript.trim();
721
+ if (!text) return false;
722
+ if (talkOpenEnding(text) || ANNOUNCING_PUNCTUATION.test(text)) return true;
723
+ return wordsOf(text).length > 3 && DANGLING_PUNCTUATION.test(text);
724
+ }
725
+ /** The silence Talk waits for after the end of speech before it sends `transcript`, and why. */
726
+ function talkUtteranceHold(transcript) {
727
+ if (talkLooksUnfinished(transcript)) return {
728
+ ms: TALK_HOLD_UNFINISHED_MS,
729
+ reason: "unfinished"
730
+ };
731
+ if (wordsOf(transcript).length <= 3) return {
732
+ ms: 250,
733
+ reason: "short"
734
+ };
735
+ return {
736
+ ms: 800,
737
+ reason: "finished"
738
+ };
739
+ }
740
+ // src/shared/wire.ts
741
+ /**
742
+ * Wire protocol v1 between a browser transport and a voice relay: two WebSockets (speech to text,
743
+ * streamed text to speech) and two HTTP routes (re-transcription of one utterance, one spoken clip).
744
+ * Frozen: a change to a frame is a breaking change and a new protocol version. Fields marked optional
745
+ * are additive and old clients ignore them.
746
+ */
747
+ /** The version of the frames below. */
748
+ const VOICE_WIRE_PROTOCOL_VERSION = 1;
749
+ /** Where the relay routes live by default; a host may mount them elsewhere. */
750
+ const VOICE_RELAY_DEFAULT_PATHS = {
751
+ stt: "/voice/transcribe-stream",
752
+ tts: "/voice/speak-stream",
753
+ retranscribe: "/voice/retranscribe",
754
+ speak: "/voice/speak"
755
+ };
756
+ /**
757
+ * Query parameters the relay reads itself. Every other query parameter (or, for `speak`, every other
758
+ * body field) is the host's opaque scope (`sessionId`, `organizationId`, `spaceId`, …).
759
+ * `token` carries a bearer, since a browser cannot set headers on `new WebSocket()`.
760
+ */
761
+ const RELAY_QUERY_PARAMS = [
762
+ "token",
763
+ "language",
764
+ "encoding",
765
+ "voiceId",
766
+ "languageCode"
767
+ ];
768
+ /** Closed list: the value selects upstream URL params. Anything else means the container format. */
769
+ function parseSttEncoding(value) {
770
+ return value === "linear16" ? "linear16" : null;
771
+ }
772
+ /** The sample rate of `linear16` audio, on the STT socket and the re-transcription body alike. */
773
+ const LINEAR16_SAMPLE_RATE = 16e3;
774
+ /** Every client frame is a short JSON text frame of at most this many bytes; binary frames are ignored. */
775
+ const TTS_MAX_CLIENT_FRAME_BYTES = 65536;
776
+ /** The PCM the TTS stream answers with: s16le, mono, this rate. */
777
+ const TTS_STREAM_SAMPLE_RATE = 24e3;
778
+ const RELAY_CLOSE_CODES = {
779
+ /** `done`, `max-duration`, `idle-timeout`. */
780
+ normal: 1e3,
781
+ /** `text-limit` (TTS). */
782
+ policy: 1008,
783
+ /** `upstream-error`. */
784
+ upstreamError: 1011
785
+ };
786
+ /** The body's content type: raw `linear16` at 16 kHz. */
787
+ const RETRANSCRIBE_CONTENT_TYPE = "audio/l16";
788
+ /** 30 s of 16 kHz mono linear16: the client's utterance ring holds no more. Above it: 413. */
789
+ const RETRANSCRIBE_MAX_BYTES = 96e4;
790
+ export { pendingTagStart as $, BUILT_IN_PRONUNCIATIONS as A, buildKeyterms as B, loopCommand as C, effectiveSttLanguage as D, toSpeakableText as E, MAX_SPEECH_TERM_CHARS as F, tidySpeechTermText as G, estimateKeytermTokens as H, MAX_USER_KEYTERMS as I, STT_LANGUAGES as J, withSpeechTerm as K, SPEECH_TERM_LANGUAGES as L, MAX_KEYTERMS as M, MAX_PRONUNCIATION_CHARS as N, sttLanguageForLocale as O, MAX_SPEECH_TERMS as P, audioTagRanges as Q, SPEECH_TERM_PATTERN as R, isHushOnly as S, takeCompleteSentences as T, sameSpeechTerm as U, cleanKeyterm as V, speechTermLanguageMatches as W, parseSttLanguage as X, modelAcceptsLanguageCode as Y, ttsLanguageCode as Z, endsMidSentence as _, RETRANSCRIBE_MAX_BYTES as a, toElevenLabsTags as at, talkUtteranceHold as b, VOICE_RELAY_DEFAULT_PATHS as c, TALK_HOLD_MS as d, stripAnyAudioTags as et, TALK_HOLD_SHORT_MS as f, UTTERANCE_HOLD_MS as g, UTTERANCE_HOLD_MID_SENTENCE_MS as h, RETRANSCRIBE_CONTENT_TYPE as i, strippedOffset as it, KEYTERM_TOKEN_BUDGET as j, BUILT_IN_KEYTERMS as k, VOICE_WIRE_PROTOCOL_VERSION as l, TALK_SHORT_WORDS as m, RELAY_CLOSE_CODES as n, stripAudioTagsForDisplay as nt, TTS_MAX_CLIENT_FRAME_BYTES as o, TALK_HOLD_UNFINISHED_MS as p, withoutSpeechTerm as q, RELAY_QUERY_PARAMS as r, stripAudioTagsForText as rt, TTS_STREAM_SAMPLE_RATE as s, LINEAR16_SAMPLE_RATE as t, stripAudioTags as tt, parseSttEncoding as u, talkLooksUnfinished as v, MIN_SENTENCE_CHARS as w, utteranceHoldMs as x, talkOpenEnding as y, USER_KEYTERM_TOKEN_BUDGET as z };
791
+
792
+ //# sourceMappingURL=wire.mjs.map