@vellumai/assistant 0.11.3-staging.2 → 0.11.3-staging.3

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.
Files changed (60) hide show
  1. package/package.json +1 -1
  2. package/src/__tests__/call-controller.test.ts +120 -0
  3. package/src/__tests__/config-loader-backfill.test.ts +19 -0
  4. package/src/__tests__/config-schema.test.ts +139 -5
  5. package/src/__tests__/events-dev-bypass-actor.test.ts +112 -1
  6. package/src/__tests__/media-stream-output.test.ts +175 -0
  7. package/src/__tests__/media-stream-stt-session.test.ts +67 -0
  8. package/src/calls/__tests__/tts-text-sanitizer.test.ts +13 -0
  9. package/src/calls/__tests__/voice-session-bridge.test.ts +81 -12
  10. package/src/calls/__tests__/voice-triage-escalate.test.ts +106 -0
  11. package/src/calls/call-controller.ts +30 -2
  12. package/src/calls/call-speech-output.ts +12 -4
  13. package/src/calls/call-transport.ts +18 -1
  14. package/src/calls/media-stream-output.ts +53 -5
  15. package/src/calls/media-stream-server.ts +12 -0
  16. package/src/calls/media-stream-stt-session.ts +34 -0
  17. package/src/calls/telephony-synthesis-language.ts +84 -0
  18. package/src/calls/tts-text-sanitizer.ts +12 -5
  19. package/src/calls/voice-session-bridge.ts +31 -3
  20. package/src/calls/voice-triage-escalate.ts +52 -5
  21. package/src/config/bundled-skills/phone-calls/references/CONFIG.md +15 -15
  22. package/src/config/loader.ts +5 -0
  23. package/src/config/schemas/calls.ts +0 -4
  24. package/src/config/schemas/tts.ts +63 -0
  25. package/src/live-voice/__tests__/front-decision.test.ts +120 -0
  26. package/src/live-voice/__tests__/live-voice-events.test.ts +1 -1
  27. package/src/live-voice/__tests__/live-voice-progress.test.ts +178 -11
  28. package/src/live-voice/__tests__/live-voice-stt.test.ts +304 -1
  29. package/src/live-voice/__tests__/live-voice-triage-escalate.test.ts +102 -2
  30. package/src/live-voice/__tests__/live-voice-tts.test.ts +148 -2
  31. package/src/live-voice/__tests__/progress-phrases.test.ts +167 -0
  32. package/src/live-voice/front-decision.ts +50 -3
  33. package/src/live-voice/live-voice-session.ts +202 -25
  34. package/src/live-voice/live-voice-tts.ts +18 -2
  35. package/src/live-voice/progress-phrases.ts +105 -2
  36. package/src/providers/speech-to-text/deepgram-realtime.test.ts +283 -1
  37. package/src/providers/speech-to-text/deepgram-realtime.ts +117 -3
  38. package/src/providers/speech-to-text/provider-catalog.ts +38 -0
  39. package/src/runtime/__tests__/local-actor-identity-force-refresh.test.ts +104 -0
  40. package/src/runtime/assistant-event-hub.ts +23 -0
  41. package/src/runtime/local-actor-identity.ts +18 -5
  42. package/src/runtime/routes/__tests__/sse-actor-principal-heal.test.ts +165 -0
  43. package/src/runtime/routes/__tests__/surface-action-routes.test.ts +2 -0
  44. package/src/runtime/routes/events-routes.ts +17 -16
  45. package/src/runtime/routes/sse-actor-principal-heal.ts +113 -0
  46. package/src/stt/__tests__/language-metadata.test.ts +85 -0
  47. package/src/stt/language-metadata.ts +65 -0
  48. package/src/stt/types.ts +16 -0
  49. package/src/tts/__tests__/provider-adapters.test.ts +147 -0
  50. package/src/tts/__tests__/speakable-segments.test.ts +470 -0
  51. package/src/tts/language-voices.ts +23 -0
  52. package/src/tts/providers/deepgram-provider.ts +3 -1
  53. package/src/tts/providers/elevenlabs-provider.ts +73 -1
  54. package/src/tts/providers/xai-provider.ts +28 -2
  55. package/src/tts/speakable-segments.ts +293 -23
  56. package/src/tts/synthesis-stream.ts +7 -0
  57. package/src/tts/types.ts +7 -0
  58. package/src/util/__tests__/language-subtag.test.ts +54 -0
  59. package/src/util/language-subtag.ts +43 -0
  60. package/src/util/unicode.ts +1 -1
@@ -165,7 +165,9 @@ async function performTtsRequest(
165
165
 
166
166
  const config = getConfig().services.tts.providers.deepgram;
167
167
  const outputParams = resolveOutputParams(request, config);
168
- const model = config.model;
168
+ // A request-level voiceId is the per-request Aura model override and wins
169
+ // over the configured model.
170
+ const model = request.voiceId?.trim() || config.model;
169
171
 
170
172
  const params = new URLSearchParams({
171
173
  model,
@@ -169,6 +169,69 @@ function resolveVoiceId(
169
169
  return voiceId;
170
170
  }
171
171
 
172
+ /**
173
+ * Models that accept the `language_code` request parameter for language
174
+ * enforcement (per the ElevenLabs text-to-speech API docs). Other models
175
+ * (e.g. `eleven_multilingual_v2`) reject the field, so it is omitted for
176
+ * anything not listed here.
177
+ */
178
+ const LANGUAGE_ENFORCEMENT_MODEL_IDS = new Set([
179
+ "eleven_flash_v2_5",
180
+ "eleven_turbo_v2_5",
181
+ ]);
182
+
183
+ /**
184
+ * ISO 639-1 codes for the 32 languages the v2.5 flash/turbo models accept in
185
+ * `language_code` (per the ElevenLabs models documentation: the Multilingual
186
+ * v2 roster plus Hungarian, Norwegian, and Vietnamese; Filipino uses the
187
+ * ISO 639-2 code `fil` since 639-1 has none). The request-level language is
188
+ * a hint sourced from the wider STT roster, so codes outside this set are
189
+ * dropped rather than forwarded: ElevenLabs rejects unknown codes with a 400,
190
+ * which would fail every synthesis segment in a session.
191
+ */
192
+ const ELEVENLABS_V2_5_LANGUAGE_CODES = new Set([
193
+ "en",
194
+ "ja",
195
+ "zh",
196
+ "de",
197
+ "hi",
198
+ "fr",
199
+ "ko",
200
+ "pt",
201
+ "it",
202
+ "es",
203
+ "id",
204
+ "nl",
205
+ "tr",
206
+ "fil",
207
+ "pl",
208
+ "sv",
209
+ "bg",
210
+ "ro",
211
+ "ar",
212
+ "cs",
213
+ "el",
214
+ "fi",
215
+ "hr",
216
+ "ms",
217
+ "sk",
218
+ "da",
219
+ "ta",
220
+ "uk",
221
+ "ru",
222
+ "hu",
223
+ "no",
224
+ "vi",
225
+ ]);
226
+
227
+ /**
228
+ * Repo language subtags whose ElevenLabs `language_code` spelling differs:
229
+ * the STT rosters tag Tagalog with the ISO 639-1 code `tl`, while the
230
+ * ElevenLabs roster lists Filipino under the ISO 639-2 code `fil`. Aliases
231
+ * are applied before the roster check above.
232
+ */
233
+ const ELEVENLABS_LANGUAGE_CODE_ALIASES = new Map([["tl", "fil"]]);
234
+
172
235
  /** ElevenLabs `pcm_*` rates available on every subscription tier. */
173
236
  const UNRESTRICTED_PCM_SAMPLE_RATES_HZ = [16_000, 22_050, 24_000] as const;
174
237
 
@@ -251,16 +314,25 @@ async function performTtsRequest(
251
314
  const defaultModelId = stream
252
315
  ? "eleven_flash_v2_5"
253
316
  : "eleven_multilingual_v2";
317
+ const modelId = config.voiceModelId?.trim() || defaultModelId;
254
318
 
255
319
  const body: Record<string, unknown> = {
256
320
  text: request.text,
257
- model_id: config.voiceModelId?.trim() || defaultModelId,
321
+ model_id: modelId,
258
322
  voice_settings: {
259
323
  stability: config.stability,
260
324
  similarity_boost: config.similarityBoost,
261
325
  speed: config.speed,
262
326
  },
263
327
  };
328
+ if (request.language && LANGUAGE_ENFORCEMENT_MODEL_IDS.has(modelId)) {
329
+ const languageCode =
330
+ ELEVENLABS_LANGUAGE_CODE_ALIASES.get(request.language) ??
331
+ request.language;
332
+ if (ELEVENLABS_V2_5_LANGUAGE_CODES.has(languageCode)) {
333
+ body.language_code = languageCode;
334
+ }
335
+ }
264
336
 
265
337
  log.info(
266
338
  { voiceId, outputFormat, stream, textLength: request.text.length },
@@ -11,6 +11,7 @@
11
11
 
12
12
  import { getConfig } from "../../config/loader.js";
13
13
  import type { TtsXaiProviderConfig } from "../../config/schemas/tts.js";
14
+ import { DEEPGRAM_MULTI_LANGUAGE_CODES } from "../../providers/speech-to-text/deepgram.js";
14
15
  import { credentialKey } from "../../security/credential-key.js";
15
16
  import { getSecureKeyAsync } from "../../security/secure-keys.js";
16
17
  import { getLogger } from "../../util/logger.js";
@@ -149,6 +150,31 @@ function resolveVoiceId(
149
150
  return request.voiceId?.trim() || config.voiceId || "eve";
150
151
  }
151
152
 
153
+ /**
154
+ * Language codes a request-level hint may carry into the xAI API. xAI does
155
+ * not document a supported-language roster, so the hint is bounded by the
156
+ * Deepgram code-switching set: languages the STT layer detects are always in
157
+ * it, and only an out-of-roster `services.stt.language` pin can exceed it.
158
+ */
159
+ const REQUEST_LANGUAGE_CODES: ReadonlySet<string> = new Set(
160
+ DEEPGRAM_MULTI_LANGUAGE_CODES,
161
+ );
162
+
163
+ /**
164
+ * Resolve the synthesis language: request override > configured default.
165
+ * A request language outside {@link REQUEST_LANGUAGE_CODES} is dropped in
166
+ * favor of the configured value (default "auto", which self-detects).
167
+ */
168
+ function resolveLanguage(
169
+ request: TtsSynthesisRequest,
170
+ config: TtsXaiProviderConfig,
171
+ ): string {
172
+ if (request.language && REQUEST_LANGUAGE_CODES.has(request.language)) {
173
+ return request.language;
174
+ }
175
+ return config.language;
176
+ }
177
+
152
178
  /** Resolve the xAI API key, throwing `XAI_TTS_NO_API_KEY` when unset. */
153
179
  async function requireApiKey(): Promise<string> {
154
180
  const apiKey = await getSecureKeyAsync(credentialKey("xai", "api_key"));
@@ -173,7 +199,7 @@ function buildStreamUrl(
173
199
  outputParams: XaiOutputParams,
174
200
  ): string {
175
201
  const params = new URLSearchParams({
176
- language: config.language,
202
+ language: resolveLanguage(request, config),
177
203
  voice: resolveVoiceId(request, config),
178
204
  codec: outputParams.codec,
179
205
  sample_rate: String(outputParams.sample_rate),
@@ -209,7 +235,7 @@ export function createXaiProvider(
209
235
  const body = {
210
236
  text: request.text,
211
237
  voice_id: voiceId,
212
- language: config.language,
238
+ language: resolveLanguage(request, config),
213
239
  output_format: {
214
240
  codec: output.codec,
215
241
  sample_rate: output.sample_rate,
@@ -7,20 +7,90 @@
7
7
  * as soon as it is complete, so speech starts before the full response lands.
8
8
  */
9
9
 
10
+ import { isHighSurrogate, isLowSurrogate } from "../util/unicode.js";
11
+
10
12
  const DEFAULT_CHAR_THRESHOLD = 180;
11
13
  const EAGER_CHAR_THRESHOLD = 60;
12
14
 
13
- const SENTENCE_ENDING_PUNCTUATION = new Set([".", "!", "?"]);
15
+ // Sentence enders in scripts without inter-word whitespace (CJK, Thai) or
16
+ // with their own terminators (Devanagari danda, Arabic-script marks). Unlike
17
+ // ASCII `. ! ?`, these are unambiguous: a boundary after one is valid even
18
+ // with no following whitespace.
19
+ export const NON_LATIN_SENTENCE_ENDING_PUNCTUATION = new Set([
20
+ "。", // ideographic full stop
21
+ "。", // halfwidth ideographic full stop
22
+ "!", // fullwidth exclamation mark
23
+ "?", // fullwidth question mark
24
+ ".", // fullwidth full stop (digit-guarded below: also a decimal point)
25
+ "।", // Devanagari danda
26
+ "॥", // Devanagari double danda
27
+ "؟", // Arabic question mark
28
+ "۔", // Arabic full stop
29
+ ]);
30
+ const SENTENCE_ENDING_PUNCTUATION = new Set([
31
+ ".",
32
+ "!",
33
+ "?",
34
+ ...NON_LATIN_SENTENCE_ENDING_PUNCTUATION,
35
+ ]);
36
+ // Unlike the other non-Latin enders, the fullwidth full stop also serves as
37
+ // a decimal point in fullwidth numbers (3.14), so it is not a boundary
38
+ // when a digit follows. The ideographic full stop 。 never marks decimals
39
+ // and stays unconditional.
40
+ const FULLWIDTH_FULL_STOP = ".";
14
41
  const TRAILING_SENTENCE_PUNCTUATION = new Set(['"', "'", ")", "]"]);
15
- const EAGER_CLAUSE_PUNCTUATION = new Set([",", ";", ":"]);
42
+ // After a non-Latin ender, locale closers (CJK corner brackets, curly
43
+ // quotes, guillemets) belong to the sentence they follow, exactly like the
44
+ // ASCII closers above; without this, 「こんにちは。」 would orphan 」 into
45
+ // the next segment. Superset of the ASCII closers so mixed-script text still
46
+ // consumes those too.
47
+ const NON_LATIN_TRAILING_SENTENCE_PUNCTUATION = new Set([
48
+ ...TRAILING_SENTENCE_PUNCTUATION,
49
+ "」",
50
+ "」", // halfwidth corner bracket closer
51
+ "』",
52
+ ")",
53
+ "】",
54
+ "〕",
55
+ "〙",
56
+ "〗",
57
+ "〛",
58
+ "》",
59
+ "〉",
60
+ "]",
61
+ "}",
62
+ "”",
63
+ "’",
64
+ "»",
65
+ ]);
66
+ // Clause punctuation in whitespace-free scripts is likewise a valid eager
67
+ // boundary regardless of what follows.
68
+ const NON_LATIN_EAGER_CLAUSE_PUNCTUATION = new Set([
69
+ "、", // ideographic comma
70
+ "、", // halfwidth ideographic comma
71
+ ",", // fullwidth comma
72
+ ";", // fullwidth semicolon
73
+ "،", // Arabic comma
74
+ ]);
75
+ const EAGER_CLAUSE_PUNCTUATION = new Set([
76
+ ",",
77
+ ";",
78
+ ":",
79
+ ...NON_LATIN_EAGER_CLAUSE_PUNCTUATION,
80
+ ]);
81
+ // The fullwidth comma also serves as a thousands separator in fullwidth
82
+ // numbers (1,000円), so it is not a clause boundary inside a number. The
83
+ // ideographic comma 、 never appears in numbers and needs no guard.
84
+ const FULLWIDTH_COMMA = ",";
16
85
  // A clause boundary only counts in eager mode once this much text precedes
17
86
  // it — "Sure, " alone would be a one-word blip.
18
87
  const EAGER_MIN_CLAUSE_PREFIX_CHARS = 24;
19
88
 
20
89
  export interface ExtractSpeakableSegmentsOptions {
21
90
  /**
22
- * Trade segment quality for onset latency: clause punctuation (`,` `;` `:`)
23
- * followed by whitespace also ends a segment once at least
91
+ * Trade segment quality for onset latency: clause punctuation (`,` `;` `:`
92
+ * followed by whitespace, or a non-Latin clause mark like `、` `,` `،`
93
+ * regardless of what follows) also ends a segment once at least
24
94
  * ~24 chars precede it, and the max buffered length before a forced split
25
95
  * drops from 180 to 60 chars. Applies only until the
26
96
  * first segment of the call is found — later segments keep full-sentence
@@ -79,6 +149,27 @@ function findSpeakableBoundary(
79
149
  let inItalic = false;
80
150
  let inUnderscore = false;
81
151
  let skipSpanChar = false;
152
+ // Inside a Markdown link URL (`](...)`), non-Latin terminators are path
153
+ // characters, not sentence enders: splitting there leaves both fragments
154
+ // unmatchable by the sanitizer's complete-link pattern, so markup or the
155
+ // raw URL gets spoken. Tracked as a paren depth, not a boolean, because
156
+ // the sanitizer's link pattern accepts balanced parens inside the URL
157
+ // (https://example.com/a_(b)/c) and the suppression must cover the same
158
+ // links. 0 = not inside a URL.
159
+ let linkUrlDepth = 0;
160
+ // Inside a potential Markdown link label (`[label](url)`, `![alt](url)`),
161
+ // between `[` and `](`. Terminators there are label text, and a boundary
162
+ // splits the link the same way a URL split does. The state resolves
163
+ // deterministically so a stray `[` in prose cannot suppress boundaries
164
+ // forever: `](` hands off to the URL state; `]` without `(` or a newline
165
+ // cancels the label, splitting at the first boundary it suppressed; a
166
+ // buffer-final `]` or an unterminated label keeps buffering (the rest may
167
+ // arrive in the next delta), bounded by the force flush and the length
168
+ // cap.
169
+ let inLinkLabel = false;
170
+ // First boundary suppressed while the current label is open; returned when
171
+ // the label turns out not to be a link.
172
+ let suppressedLabelBoundary: number | null = null;
82
173
 
83
174
  for (let index = 0; index < text.length; index += 1) {
84
175
  const char = text[index];
@@ -87,8 +178,54 @@ function findSpeakableBoundary(
87
178
  }
88
179
  const inOpenSpan = inBacktick || inBold || inItalic || inUnderscore;
89
180
 
90
- if (!inOpenSpan && char === "\n") {
91
- return index + 1;
181
+ if (char === "\n") {
182
+ // A URL never spans a line: an unclosed link stops suppressing here so
183
+ // malformed markup cannot defer the newline split. Labels do not span
184
+ // lines either; a suppressed boundary reopens ahead of the newline.
185
+ linkUrlDepth = 0;
186
+ inLinkLabel = false;
187
+ if (suppressedLabelBoundary !== null) {
188
+ return suppressedLabelBoundary;
189
+ }
190
+ if (!inOpenSpan) {
191
+ return index + 1;
192
+ }
193
+ }
194
+
195
+ if (linkUrlDepth > 0) {
196
+ if (char === "(") {
197
+ linkUrlDepth += 1;
198
+ } else if (char === ")") {
199
+ linkUrlDepth -= 1;
200
+ }
201
+ continue;
202
+ }
203
+ if (char === "]" && inLinkLabel && text[index + 1] !== "(") {
204
+ if (index + 1 === text.length) {
205
+ // A buffer-final `]` is ambiguous while streaming: the `(` may open
206
+ // the next delta. Keep buffering; force and the length cap below
207
+ // still flush.
208
+ break;
209
+ }
210
+ // Not a link after all: the label text is plain prose, so the first
211
+ // boundary it suppressed becomes the split point again.
212
+ inLinkLabel = false;
213
+ if (suppressedLabelBoundary !== null) {
214
+ return suppressedLabelBoundary;
215
+ }
216
+ }
217
+ if (char === "]" && text[index + 1] === "(") {
218
+ inLinkLabel = false;
219
+ suppressedLabelBoundary = null;
220
+ linkUrlDepth = 1;
221
+ // Skip the opening paren so it does not double-count the depth.
222
+ index += 1;
223
+ continue;
224
+ }
225
+ // A `[` inside an open inline span is literal text (e.g. inline code
226
+ // containing an array literal), never a link-label opener.
227
+ if (char === "[" && !inLinkLabel && !inOpenSpan) {
228
+ inLinkLabel = true;
92
229
  }
93
230
 
94
231
  if (
@@ -96,21 +233,75 @@ function findSpeakableBoundary(
96
233
  eager &&
97
234
  EAGER_CLAUSE_PUNCTUATION.has(char) &&
98
235
  index >= EAGER_MIN_CLAUSE_PREFIX_CHARS &&
99
- isWhitespace(text[index + 1] ?? "")
236
+ (NON_LATIN_EAGER_CLAUSE_PUNCTUATION.has(char) ||
237
+ isWhitespace(text[index + 1] ?? "")) &&
238
+ !isFullwidthGroupingComma(text, index)
100
239
  ) {
101
- return index + 1;
240
+ if (inLinkLabel) {
241
+ suppressedLabelBoundary ??= index + 1;
242
+ } else {
243
+ return index + 1;
244
+ }
102
245
  }
103
246
 
104
247
  if (!inOpenSpan && SENTENCE_ENDING_PUNCTUATION.has(char)) {
105
- let boundary = index + 1;
106
- while (
107
- boundary < text.length &&
108
- TRAILING_SENTENCE_PUNCTUATION.has(text[boundary] ?? "")
109
- ) {
110
- boundary += 1;
248
+ const isNonLatinEnder = NON_LATIN_SENTENCE_ENDING_PUNCTUATION.has(char);
249
+ // The fullwidth full stop doubles as a decimal point in fullwidth
250
+ // numbers (3.14です), so a following digit suppresses the boundary.
251
+ // It also appears inside Latin filename-style tokens (report.pdf):
252
+ // ASCII word chars on both sides mark it as part of the token, not a
253
+ // sentence end. CJK neighbors keep the boundary, since Japanese
254
+ // sentences legitimately end in . between CJK words.
255
+ const isAmbiguousDecimalPoint =
256
+ char === FULLWIDTH_FULL_STOP &&
257
+ (isDecimalDigit(text[index + 1]) ||
258
+ (isAsciiWordChar(text[index - 1]) &&
259
+ isAsciiWordChar(text[index + 1])));
260
+ if (isNonLatinEnder && !isAmbiguousDecimalPoint) {
261
+ // Non-Latin enders are valid boundaries regardless of what follows;
262
+ // consume adjacent enders (本当!?) so combined punctuation keeps
263
+ // its prosody and never becomes a punctuation-only segment, then
264
+ // consume locale closers so they stay with their sentence.
265
+ let boundary = index + 1;
266
+ while (
267
+ boundary < text.length &&
268
+ (NON_LATIN_SENTENCE_ENDING_PUNCTUATION.has(text[boundary] ?? "") ||
269
+ NON_LATIN_TRAILING_SENTENCE_PUNCTUATION.has(text[boundary] ?? ""))
270
+ ) {
271
+ boundary += 1;
272
+ }
273
+ // A buffer-final ender is ambiguous while streaming: the next delta
274
+ // may open with closers that belong to this sentence (`「こんにちは。`
275
+ // then `」`) or, for ., with decimal digits (`3.` then `14です`).
276
+ // Keep buffering; the `force` flush path still emits a buffer-final
277
+ // sentence at end of turn, and the length cap below still bounds the
278
+ // buffer. ASCII enders keep their end-of-text boundary: whitespace
279
+ // scripts do not attach closers across deltas the same way.
280
+ if (boundary < text.length) {
281
+ if (inLinkLabel) {
282
+ suppressedLabelBoundary ??= boundary;
283
+ } else {
284
+ return boundary;
285
+ }
286
+ }
111
287
  }
112
- if (boundary === text.length || isWhitespace(text[boundary] ?? "")) {
113
- return boundary;
288
+ if (!isNonLatinEnder) {
289
+ // ASCII enders require following whitespace so decimals (3.14) and
290
+ // file names don't split.
291
+ let boundary = index + 1;
292
+ while (
293
+ boundary < text.length &&
294
+ TRAILING_SENTENCE_PUNCTUATION.has(text[boundary] ?? "")
295
+ ) {
296
+ boundary += 1;
297
+ }
298
+ if (boundary === text.length || isWhitespace(text[boundary] ?? "")) {
299
+ if (inLinkLabel) {
300
+ suppressedLabelBoundary ??= boundary;
301
+ } else {
302
+ return boundary;
303
+ }
304
+ }
114
305
  }
115
306
  }
116
307
 
@@ -119,8 +310,8 @@ function findSpeakableBoundary(
119
310
  } else if (char === "`") {
120
311
  inBacktick = !inBacktick;
121
312
  } else if (char === "*") {
122
- const prev = text[index - 1];
123
- const next = text[index + 1];
313
+ const prev = codePointBefore(text, index);
314
+ const next = codePointAfter(text, index);
124
315
  if (next === "*") {
125
316
  inBold = !inBold;
126
317
  skipSpanChar = true;
@@ -141,8 +332,8 @@ function findSpeakableBoundary(
141
332
  } else if (char === "_") {
142
333
  // Same word-boundary rule as `*`. Since `_` neighbors in identifiers
143
334
  // like `my_var` are word chars, they never open or close a span.
144
- const prev = text[index - 1];
145
- const next = text[index + 1];
335
+ const prev = codePointBefore(text, index);
336
+ const next = codePointAfter(text, index);
146
337
  if (inUnderscore) {
147
338
  if (prev !== undefined && !isWhitespace(prev) && !isWordChar(next)) {
148
339
  inUnderscore = false;
@@ -161,14 +352,93 @@ function findSpeakableBoundary(
161
352
  return null;
162
353
  }
163
354
 
355
+ // The length cap bounds how long an open label can defer: past it, the
356
+ // first boundary the label suppressed beats an arbitrary mid-text split.
357
+ if (suppressedLabelBoundary !== null) {
358
+ return suppressedLabelBoundary;
359
+ }
360
+
164
361
  // Length-threshold splits are a hard cap and must flush even inside an
165
- // open span — unbalanced markers there are an accepted edge.
362
+ // open span: unbalanced markers there are an accepted edge.
166
363
  const preferredBoundary = findLastWhitespaceBoundary(text, charThreshold);
167
- return preferredBoundary ?? charThreshold;
364
+ if (preferredBoundary !== null) {
365
+ return preferredBoundary;
366
+ }
367
+ // Never split a UTF-16 surrogate pair: if the cap lands mid-pair, step
368
+ // back one unit so both halves stay in the same segment.
369
+ if (isHighSurrogate(text.charCodeAt(charThreshold - 1))) {
370
+ return charThreshold - 1;
371
+ }
372
+ return charThreshold;
168
373
  }
169
374
 
375
+ /**
376
+ * Accepts a full code point (one or two UTF-16 units) so non-BMP letters
377
+ * like 𠮟 count as word chars, matching the sanitizer's Unicode lookarounds
378
+ * in calls/tts-text-sanitizer.ts.
379
+ */
170
380
  function isWordChar(value: string | undefined): boolean {
171
- return value !== undefined && /\w/.test(value);
381
+ return value !== undefined && /[\p{L}\p{N}_]/u.test(value);
382
+ }
383
+
384
+ function isDecimalDigit(value: string | undefined): boolean {
385
+ return value !== undefined && /[0-90-9]/.test(value);
386
+ }
387
+
388
+ // ASCII-only on purpose: filename-style tokens (report.pdf) are Latin
389
+ // script, while CJK neighbors around . mark real sentence text.
390
+ function isAsciiWordChar(value: string | undefined): boolean {
391
+ return value !== undefined && /[A-Za-z0-9_]/.test(value);
392
+ }
393
+
394
+ /**
395
+ * A fullwidth comma acting as a thousands separator (1,000円): a digit
396
+ * precedes it and a digit follows, or the buffer ends right after it while
397
+ * streaming (the digits may arrive in the next delta, so keep buffering).
398
+ */
399
+ function isFullwidthGroupingComma(text: string, index: number): boolean {
400
+ if (text[index] !== FULLWIDTH_COMMA || !isDecimalDigit(text[index - 1])) {
401
+ return false;
402
+ }
403
+ const next = text[index + 1];
404
+ return next === undefined || isDecimalDigit(next);
405
+ }
406
+
407
+ /**
408
+ * The full code point ending just before `index`. When the preceding unit is
409
+ * a low surrogate, includes its high surrogate so `isWordChar` sees the
410
+ * whole character instead of half a pair.
411
+ */
412
+ function codePointBefore(text: string, index: number): string | undefined {
413
+ const unit = text[index - 1];
414
+ if (unit === undefined) {
415
+ return undefined;
416
+ }
417
+ if (isLowSurrogate(unit.charCodeAt(0))) {
418
+ const high = text[index - 2];
419
+ if (high !== undefined && isHighSurrogate(high.charCodeAt(0))) {
420
+ return high + unit;
421
+ }
422
+ }
423
+ return unit;
424
+ }
425
+
426
+ /**
427
+ * The full code point starting just after `index`. When the following unit
428
+ * is a high surrogate, includes its low surrogate.
429
+ */
430
+ function codePointAfter(text: string, index: number): string | undefined {
431
+ const unit = text[index + 1];
432
+ if (unit === undefined) {
433
+ return undefined;
434
+ }
435
+ if (isHighSurrogate(unit.charCodeAt(0))) {
436
+ const low = text[index + 2];
437
+ if (low !== undefined && isLowSurrogate(low.charCodeAt(0))) {
438
+ return unit + low;
439
+ }
440
+ }
441
+ return unit;
172
442
  }
173
443
 
174
444
  function findLastWhitespaceBoundary(
@@ -56,6 +56,12 @@ export interface SynthesisEmitOptions {
56
56
  /** Preferred PCM sample rate in Hz, forwarded on the provider request. */
57
57
  sampleRateHz?: number;
58
58
 
59
+ /**
60
+ * Language hint forwarded on the provider request
61
+ * (see {@link TtsSynthesisRequest.language}).
62
+ */
63
+ language?: string;
64
+
59
65
  /** Abort signal forwarded to the provider and checked before each emit. */
60
66
  signal?: AbortSignal;
61
67
 
@@ -106,6 +112,7 @@ export async function synthesizeAndEmit(
106
112
  voiceId: options.voiceId,
107
113
  outputFormat: options.outputFormat,
108
114
  sampleRateHz: options.sampleRateHz,
115
+ language: options.language,
109
116
  signal,
110
117
  };
111
118
 
package/src/tts/types.ts CHANGED
@@ -113,6 +113,13 @@ export interface TtsSynthesisRequest {
113
113
  * on provider-documented behavior (see each provider's format mapping).
114
114
  */
115
115
  sampleRateHz?: number;
116
+
117
+ /**
118
+ * Optional lowercase BCP-47 base subtag (e.g. `"es"`, `"hi"`) hinting the
119
+ * language of `text`. Providers that support language enforcement apply
120
+ * it; providers that cannot use it must ignore it.
121
+ */
122
+ language?: string;
116
123
  }
117
124
 
118
125
  /** Output of a completed TTS synthesis call. */
@@ -0,0 +1,54 @@
1
+ import { describe, expect, test } from "bun:test";
2
+
3
+ import { baseLanguageSubtag, localizedOrDefault } from "../language-subtag.js";
4
+
5
+ describe("baseLanguageSubtag", () => {
6
+ test("lowercases a bare tag", () => {
7
+ expect(baseLanguageSubtag("EN")).toBe("en");
8
+ });
9
+
10
+ test("strips a hyphenated region", () => {
11
+ expect(baseLanguageSubtag("en-US")).toBe("en");
12
+ expect(baseLanguageSubtag("PT-br")).toBe("pt");
13
+ });
14
+
15
+ test("strips an underscore-separated region", () => {
16
+ expect(baseLanguageSubtag("hi_IN")).toBe("hi");
17
+ expect(baseLanguageSubtag("es_419")).toBe("es");
18
+ });
19
+
20
+ test("trims surrounding whitespace", () => {
21
+ expect(baseLanguageSubtag(" hi ")).toBe("hi");
22
+ expect(baseLanguageSubtag(" pt-BR ")).toBe("pt");
23
+ });
24
+
25
+ test("returns undefined for undefined and blank input", () => {
26
+ expect(baseLanguageSubtag(undefined)).toBeUndefined();
27
+ expect(baseLanguageSubtag("")).toBeUndefined();
28
+ expect(baseLanguageSubtag(" ")).toBeUndefined();
29
+ });
30
+ });
31
+
32
+ describe("localizedOrDefault", () => {
33
+ const table: Readonly<Record<string, string>> = { en: "hello", es: "hola" };
34
+
35
+ test("selects by the language's base subtag", () => {
36
+ expect(localizedOrDefault(table, "es", "hello")).toBe("hola");
37
+ expect(localizedOrDefault(table, "ES-mx", "hello")).toBe("hola");
38
+ expect(localizedOrDefault(table, "en_GB", "fallback")).toBe("hello");
39
+ });
40
+
41
+ test("falls back for unset, blank, and unknown languages", () => {
42
+ expect(localizedOrDefault(table, undefined, "fallback")).toBe("fallback");
43
+ expect(localizedOrDefault(table, "", "fallback")).toBe("fallback");
44
+ expect(localizedOrDefault(table, "ko", "fallback")).toBe("fallback");
45
+ });
46
+
47
+ test("never resolves prototype keys as entries", () => {
48
+ expect(localizedOrDefault(table, "constructor", "fallback")).toBe(
49
+ "fallback",
50
+ );
51
+ expect(localizedOrDefault(table, "toString", "fallback")).toBe("fallback");
52
+ expect(localizedOrDefault(table, "__proto__", "fallback")).toBe("fallback");
53
+ });
54
+ });
@@ -0,0 +1,43 @@
1
+ /**
2
+ * The lowercased primary subtag of a BCP 47 (or underscore-separated)
3
+ * language tag: "pt-BR" -> "pt", "es_419" -> "es", " EN-us " -> "en".
4
+ * Undefined for undefined or blank input. The one language-tag
5
+ * normalizer in the daemon: every language comparison, table lookup, and
6
+ * prompt interpolation goes through this so a regional variant can never
7
+ * slip past a base-subtag consumer.
8
+ */
9
+ export function baseLanguageSubtag(language?: string): string | undefined {
10
+ const base = language?.trim().toLowerCase().split(/[-_]/)[0];
11
+ return base ? base : undefined;
12
+ }
13
+
14
+ /**
15
+ * Whether the table carries its own entry for the language, keyed by
16
+ * lowercased base subtag. False for unset languages and for prototype keys
17
+ * ("constructor", "toString") rather than table entries. When this is
18
+ * false, {@link localizedOrDefault} returns the fallback, so callers whose
19
+ * fallback is English text can label the result as English (e.g. for a TTS
20
+ * language hint) instead of the requested language.
21
+ */
22
+ export function hasLocalizedEntry(
23
+ table: Readonly<Record<string, unknown>>,
24
+ language: string | undefined,
25
+ ): boolean {
26
+ const base = baseLanguageSubtag(language);
27
+ return base !== undefined && Object.hasOwn(table, base);
28
+ }
29
+
30
+ /**
31
+ * Look up a per-language value in a plain-record table keyed by lowercase
32
+ * base subtags, falling back when the language is unset, unknown, or a
33
+ * prototype key ("constructor", "toString") rather than a table entry.
34
+ */
35
+ export function localizedOrDefault<T>(
36
+ table: Readonly<Record<string, T>>,
37
+ language: string | undefined,
38
+ fallback: T,
39
+ ): T {
40
+ return hasLocalizedEntry(table, language)
41
+ ? (table[baseLanguageSubtag(language)!] as T)
42
+ : fallback;
43
+ }