@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.
@@ -0,0 +1,2102 @@
1
+ import { C as SttLanguage, K as VoiceRelayRoute, P as SpeakRequestBody, f as SpeechTerm } from "../speech-terms.mjs";
2
+ /**
3
+ * Talk's diagnostic log: short events about what the browser decided (utterance sent, steer or
4
+ * fold, playback stopped and why, mute, route), batched to the host's `send`, which writes them
5
+ * where an incident can be followed (the platform: the home session's log).
6
+ *
7
+ * Lengths, ids and reasons only. A string value that is not a token (whitespace, other
8
+ * characters, too long) is dropped here, and the host should check again, so text passed by
9
+ * mistake never leaves the browser.
10
+ */
11
+ export type TalkDiagFields = Record<string, string | number | boolean | null>;
12
+ export type TalkDiag = (event: string, fields?: TalkDiagFields) => void;
13
+ export type TalkDiagEvent = {
14
+ event: string;
15
+ atMs: number;
16
+ fields?: TalkDiagFields;
17
+ };
18
+ type Timers$3 = {
19
+ setTimeout: (fn: () => void, ms: number) => unknown;
20
+ clearTimeout: (handle: unknown) => void;
21
+ };
22
+ export declare const TALK_DIAG_FLUSH_MS = 2000;
23
+ export declare const TALK_DIAG_BATCH = 30;
24
+ /** Per minute, all events together; the server's batch limit sits above what this can send. */
25
+ export declare const TALK_DIAG_PER_MINUTE = 120;
26
+ /** Per minute for one event name, so a chatty one (a level or route flapping) can't fill the budget. */
27
+ export declare const TALK_DIAG_PER_NAME_PER_MINUTE = 30;
28
+ export type TalkDiagSink = {
29
+ log: TalkDiag;
30
+ flush(): void;
31
+ dispose(): void;
32
+ };
33
+ /**
34
+ * Batches events (every 2 s, or at 30), throttles them (120 a minute, 30 per name; what is
35
+ * dropped is reported once as `diag.dropped`), and never throws or rejects into the caller.
36
+ */
37
+ export declare function createTalkDiagSink({ send, now, timers }: {
38
+ send: (events: TalkDiagEvent[]) => Promise<unknown>;
39
+ now?: () => number;
40
+ timers?: Timers$3;
41
+ }): TalkDiagSink;
42
+ /**
43
+ * The short filler ("Mhm...", "Hmm, mal sehen...") Talk plays while the user waits for an answer
44
+ * that will take a while. It plays once that is known: the turn starts a tool call, or a fixed
45
+ * wait passes with no text. At most one per request, plus one "still on it" line on a very long
46
+ * wait, and none once the assistant wrote anything (it often says "Moment, ich schau nach"
47
+ * itself). Clips are generated once per (voice, language, phrase) through the TTS route and kept
48
+ * in memory; they are never messages.
49
+ */
50
+ /** No text and no tool call yet: the filler this long after the user's utterance ended. */
51
+ export declare const FILLER_FALLBACK_MS = 3500;
52
+ /** A tool call started: the filler this much later, so text written just before the call wins. */
53
+ export declare const FILLER_TOOL_DELAY_MS = 300;
54
+ /** Still no text this long after the utterance ended: one "still on it" line. */
55
+ export declare const FILLER_LONG_WAIT_MS = 10000;
56
+ /** A tool this device saw return faster than this, on average, starts no filler. */
57
+ export declare const FAST_TOOL_MS = 1500;
58
+ /** `first`: the one filler of a request; `long`: the "still on it" line after a very long wait. */
59
+ export type FillerKind = 'first' | 'long';
60
+ export type AckClipKey = {
61
+ voiceId: string | null;
62
+ language: string | null;
63
+ phrase: string;
64
+ };
65
+ /**
66
+ * The spoken-clip body for a filler: `expressive` has the v4 model perform its `[[thinking]]`
67
+ * tag; should v4 fail, the fast model (`lowLatency`) speaks it without the tag.
68
+ */
69
+ export declare function ackClipRequestBody({ voiceId, language, phrase }: AckClipKey): SpeakRequestBody;
70
+ /** Generated clips, keyed by voice, language and phrase; a failed fetch is retried next time. */
71
+ export declare class AckClipCache {
72
+ private readonly fetchClip;
73
+ private readonly clips;
74
+ constructor(fetchClip: (key: AckClipKey) => Promise<ArrayBuffer | null>);
75
+ get(key: AckClipKey): Promise<ArrayBuffer | null>;
76
+ /** Fills the cache for a voice and language, so a filler plays without a fetch. */
77
+ warm(voiceId: string | null, language: string | null): void;
78
+ }
79
+ type Timers$2 = {
80
+ setTimeout: (fn: () => void, ms: number) => unknown;
81
+ clearTimeout: (handle: unknown) => void;
82
+ };
83
+ export declare const TOOL_STATS_KEY = "skaile.talk.toolDurations";
84
+ /** Where the device keeps how long each tool took (`localStorage`); none in tests. */
85
+ export type ToolStatsStorage = Pick<Storage, 'getItem' | 'setItem'>;
86
+ /**
87
+ * How long tools take on this device, by name, kept locally: a tool that usually returns quickly
88
+ * starts no filler.
89
+ */
90
+ export declare class ToolDurations {
91
+ private readonly storage;
92
+ private readonly storageKey;
93
+ private stats;
94
+ constructor(storage?: ToolStatsStorage | null, storageKey?: string);
95
+ record(name: string, ms: number): void;
96
+ /** Fast by what this device saw, once it saw enough runs; a tool it does not know is not. */
97
+ isFast(name: string): boolean;
98
+ }
99
+ /**
100
+ * When to play a filler, per request (see the module comment). `turnId` keys a request: the
101
+ * final after an eager send, and a turn restarted because the user went on after a pause, keep
102
+ * the key and get no second filler. Off entirely when the flag is false.
103
+ */
104
+ export declare class AckScheduler {
105
+ private readonly options;
106
+ private firstTimer;
107
+ private longTimer;
108
+ private turn;
109
+ private readonly played;
110
+ /** Tools running right now, with when each started (one entry per call). */
111
+ private readonly running;
112
+ private readonly durations;
113
+ constructor(options: {
114
+ /** `language` is the utterance's; null when it reported none. */
115
+ play: (turnId: string, language: string | null, kind: FillerKind) => void;
116
+ /** Defaults to on. */
117
+ enabled?: boolean;
118
+ timers?: Timers$2;
119
+ now?: () => number;
120
+ durations?: ToolDurations;
121
+ /** The Talk diagnostic log: every filler decision, timings only. */
122
+ diag?: TalkDiag;
123
+ });
124
+ private get enabled();
125
+ private get timers();
126
+ private now;
127
+ private diag;
128
+ /**
129
+ * The user's utterance ended and its request went out. `restart`: the same request sent again
130
+ * whole after its cut-off start; none of it was heard, so text the cancelled turn wrote no
131
+ * longer counts. No filler in a language Talk cannot speak.
132
+ */
133
+ utteranceEnded(turnId: string, language?: string | null, { restart }?: {
134
+ restart?: boolean | undefined;
135
+ }): void;
136
+ /** The agent started a tool: the answer will take a while, so the filler comes now. */
137
+ toolStarted(name: string): void;
138
+ /** A tool returned; its duration teaches the device which tools are fast. */
139
+ toolEnded(name: string): void;
140
+ /** The assistant's text for the request arrived (or Talk spoke itself): no more fillers. */
141
+ assistantText(): void;
142
+ /** A filler played for the open request: a short first line of the reply may only repeat it. */
143
+ get fillerPlayed(): boolean;
144
+ /** The request ended or a new one replaced it: nothing more for it. */
145
+ cancel(): void;
146
+ private schedule;
147
+ /** The first filler after `delay`; a tool call brings a pending timer forward, never back. */
148
+ private armFirst;
149
+ private fire;
150
+ private sinceEnd;
151
+ private clearTimers;
152
+ }
153
+ /**
154
+ * The acknowledgment phrases per language. A module of its own, with no imports, so the e2e
155
+ * suite can tell an ack clip's TTS request from a reply's. Spoken by the v4 model, which performs
156
+ * the `[[thinking]]` tag; the longer ones stay under about 2.5 s.
157
+ */
158
+ export declare const ACK_PHRASES: Record<string, readonly string[]>;
159
+ /** The phrases for a language (its base code), English when there are none. */
160
+ export declare function ackPhrasesFor(language: string | null | undefined): readonly string[];
161
+ /** The one "still on it" line after a very long wait; untagged, it should sound plain. */
162
+ export declare const LONG_WAIT_PHRASES: Record<string, readonly string[]>;
163
+ /** The long-wait lines for a language (its base code), English when there are none. */
164
+ export declare function longWaitPhrasesFor(language: string | null | undefined): readonly string[];
165
+ /**
166
+ * Maps Deepgram stream time (seconds since the first audio sent on a socket) onto the
167
+ * AudioContext clock, so speech start and playback end compare on one clock. Each STT
168
+ * socket has its own anchor: a reconnect, the 10-min rollover and a language switch all
169
+ * start a new stream at 0.
170
+ */
171
+ export declare class AudioClock {
172
+ private anchor;
173
+ /**
174
+ * Stream time 0 is the first audio sent on the socket. With the pre-open buffer that is
175
+ * the capture time of the oldest buffered frame, not the moment the socket opened.
176
+ */
177
+ anchorAt(contextTime: number): void;
178
+ get anchored(): boolean;
179
+ /** The AudioContext time of a stream timestamp; null before anything was sent. */
180
+ toContextTime(streamSeconds: number): number | null;
181
+ }
182
+ type LatencyInfo = {
183
+ outputLatency?: number;
184
+ baseLatency?: number;
185
+ };
186
+ /** When the listener stops hearing a clip that ended at `endedAt`: Bluetooth adds hundreds of ms. */
187
+ export declare function playbackEnd(endedAt: number, ctx: LatencyInfo): number;
188
+ /**
189
+ * Whether Talk may let the user's voice interrupt it (headphones mode) or only a tap
190
+ * (phone-speaker mode): phone echo cancellation is too weak for free barge-in over the
191
+ * built-in speaker. Mobile browsers rarely say where audio goes, so a device-local
192
+ * toggle decides and detection only fills in while it was never set.
193
+ */
194
+ export type TalkAudioMode = 'headphones' | 'phone-speaker';
195
+ export declare function talkAudioMode(input: {
196
+ coarsePointer: boolean;
197
+ /** The device-local toggle; null when never set on this device. */
198
+ headphonesToggle: boolean | null;
199
+ detectedHeadphones: boolean;
200
+ }): TalkAudioMode;
201
+ /** The toggle once set on this device, else what detection found. */
202
+ export declare function headphonesInEffect(toggle: boolean | null, detected: boolean): boolean;
203
+ type DeviceInfo = {
204
+ kind: string;
205
+ label: string;
206
+ };
207
+ /** True when `enumerateDevices()` exposes an output (or a Bluetooth/headset input) that reads as headphones. */
208
+ export declare function detectHeadphones(devices: readonly DeviceInfo[]): boolean;
209
+ type KeyValueStore = Pick<Storage, 'getItem' | 'setItem'>;
210
+ /**
211
+ * The toggle on this device; null when never set or storage is unavailable. `key` is the host's,
212
+ * per user and device: a server field would carry one device's answer to another.
213
+ */
214
+ export declare function readHeadphonesToggle(key: string, storage?: KeyValueStore | null): boolean | null;
215
+ export declare function writeHeadphonesToggle(key: string, on: boolean, storage?: KeyValueStore | null): void;
216
+ /** The part of a browser `WebSocket` the engine uses; tests and native hosts pass their own. */
217
+ export type WebSocketLike = {
218
+ binaryType: string;
219
+ readonly readyState: number;
220
+ send(data: string | ArrayBufferLike): void;
221
+ close(): void;
222
+ onmessage: ((event: {
223
+ data: unknown;
224
+ }) => void) | null;
225
+ onclose: ((event?: unknown) => void) | null;
226
+ onerror: ((event?: unknown) => void) | null;
227
+ };
228
+ /**
229
+ * How the voice layer reaches the host's voice relay (wire protocol v1): the STT and TTS stream
230
+ * sockets, the re-transcription and the spoken clip. The layer knows no URLs, scopes or
231
+ * credentials; the host builds this, usually with {@link createRelayTransport}.
232
+ */
233
+ export type SpeechTransport = {
234
+ /**
235
+ * A fresh credential for the next socket (browsers cannot set a socket's headers), fetched
236
+ * before each one opens; null when the host authenticates otherwise.
237
+ */
238
+ socketCredential(): Promise<string | null | undefined>;
239
+ /** Opens the STT stream socket (`linear16` PCM in, transcripts out). */
240
+ openStt(query: {
241
+ language: string | null;
242
+ }, credential: string | null | undefined): WebSocketLike;
243
+ /** Opens one reply's TTS stream socket. */
244
+ openTtsStream(query: {
245
+ voiceId: string | null;
246
+ languageCode: string | null;
247
+ }, credential: string | null | undefined): WebSocketLike;
248
+ /** Transcribes 16 kHz `linear16` audio again; the layer reads the protocol's JSON answer. */
249
+ retranscribe(pcm16k: ArrayBuffer, query: {
250
+ language: string | null;
251
+ }, signal: AbortSignal): Promise<Response>;
252
+ /** Speaks one clip (`audio/mpeg`). */
253
+ speakClip(body: SpeakRequestBody, signal?: AbortSignal): Promise<Response>;
254
+ };
255
+ export type RelayTransportOptions = {
256
+ /**
257
+ * The relay's base URL; HTTP routes are appended to it, sockets go to its host (its path is not
258
+ * used). Relative URLs resolve against the page (`location.href`).
259
+ */
260
+ baseUrl: string;
261
+ /**
262
+ * Where the host mounted the routes; defaults to {@link VOICE_RELAY_DEFAULT_PATHS}. `retranscribe`
263
+ * and `speak` are appended to `baseUrl`; `stt` and `tts` are full paths on its host.
264
+ */
265
+ paths?: Partial<Record<VoiceRelayRoute, string>>;
266
+ /** Opaque host parameters every request carries (the platform: `{ sessionId }`). */
267
+ scope?: () => Record<string, string>;
268
+ /** The bearer for the socket's query string; omit when the relay authenticates otherwise (a cookie). */
269
+ getToken?: () => Promise<string | null | undefined>;
270
+ /** Defaults to the global `fetch`; a host passes its own to add HTTP auth. */
271
+ fetch?: (url: string, init: RequestInit) => Promise<Response>;
272
+ /** Defaults to the global `WebSocket`. */
273
+ WebSocket?: new (url: string) => WebSocketLike;
274
+ };
275
+ /** The default transport: protocol v1 to a relay at `baseUrl`, `scope` added to every request. */
276
+ export declare function createRelayTransport(options: RelayTransportOptions): SpeechTransport;
277
+ /**
278
+ * The `ws:`/`wss:` URL of a relay socket route on the base URL's host. The base URL's path is not
279
+ * used: the platform's sockets live at the API host's root.
280
+ */
281
+ export declare function relaySocketUrl(baseUrl: string, path: string, params: URLSearchParams): string;
282
+ /**
283
+ * Talk's STT language. Single-language recognition is far more accurate than `multi`, so Talk
284
+ * streams in one language. A pinned language always wins and never switches.
285
+ *
286
+ * Among the member's own languages (the Talk languages on this device) none is privileged: the
287
+ * home is the one last confidently spoken in, and one confidently detected utterance of
288
+ * {@link OWN_SWITCH_WORDS} words or more in another of them moves the stream. A shorter one is
289
+ * transcribed right without moving it. A language outside their own needs a very confident
290
+ * detection twice in a row; from there, any detection of their own brings the stream back.
291
+ * Without own languages, the device's long-term majority is the home: leaving it needs strong
292
+ * evidence, and coming back is immediate.
293
+ */
294
+ /** Below this mean word confidence an utterance is re-transcribed from its own audio. */
295
+ export declare const RETRANSCRIBE_CONFIDENCE = 0.7;
296
+ /** Away from home the check is cheaper: the home language misheard as another reads as fair. */
297
+ export declare const RECHECK_AWAY_CONFIDENCE = 0.9;
298
+ /** A detection at least this confident counts at all (and brings Talk back home). */
299
+ export declare const SWITCH_CONFIDENCE = 0.6;
300
+ /** Leaving the home language needs a detection at least this confident ... */
301
+ export declare const SWITCH_AWAY_CONFIDENCE = 0.8;
302
+ /** ... and an utterance of at least this many words, or two such utterances in a row. */
303
+ export declare const SWITCH_AWAY_WORDS = 6;
304
+ export declare const SWITCH_AWAY_UTTERANCES = 2;
305
+ /** Among the member's own languages, one confident utterance this long moves the stream. */
306
+ export declare const OWN_SWITCH_WORDS = 3;
307
+ /** A language outside the member's own needs this detection confidence on every utterance. */
308
+ export declare const OUTSIDE_PREFERRED_CONFIDENCE = 0.9;
309
+ /**
310
+ * The home language: what this device has mostly heard, else the conversation's language, else
311
+ * the last spoken utterance's (a one-off foreign sentence never becomes home on its own).
312
+ */
313
+ export declare function homeTalkLanguage(deviceHome: SttLanguage | null | undefined, conversationLocale: string | null | undefined, lastUtteranceLanguage: string | null | undefined,
314
+ /**
315
+ * The browser's language, the last resort: without any home the stream ran as `multi`, where
316
+ * Deepgram may answer in any language at all (German came back as Indonesian).
317
+ */
318
+ deviceLocale?: string | null): SttLanguage | null;
319
+ /**
320
+ * Whether a re-transcription may replace what the stream heard. Without a home anything goes;
321
+ * with one, a result in the home or current language always counts, another language only when
322
+ * detected at least {@link SWITCH_AWAY_CONFIDENCE} confidently (or when the stream heard no words).
323
+ */
324
+ export declare function retranscriptionTrusted(result: {
325
+ language: string | null;
326
+ languageConfidence: number | null;
327
+ }, context: {
328
+ home: SttLanguage | null;
329
+ current: string | null;
330
+ hasText: boolean;
331
+ preferred?: readonly SttLanguage[];
332
+ }): boolean;
333
+ export type RetranscribeCandidate = {
334
+ /** Mean word confidence of the utterance's final segments, null when none was scored. */
335
+ meanConfidence: number | null;
336
+ text: string;
337
+ /** Deepgram reported speech for this utterance. */
338
+ speechStarted: boolean;
339
+ /** Started while TTS played or in the echo tail: never re-transcribed. */
340
+ startedDuringPlayback: boolean;
341
+ /** The stream is not in the home language: a lower bar, so Talk finds its way back quickly. */
342
+ awayFromHome?: boolean;
343
+ /** The language the stream transcribes in; with it, words of another language trigger a check. */
344
+ streamLanguage?: string | null;
345
+ };
346
+ /**
347
+ * The utterance reads as another language than the stream's: at least two of that language's
348
+ * function words, and more of them than of the stream's own. Only a reason to check.
349
+ */
350
+ export declare function looksLikeOtherLanguage(text: string, streamLanguage: string | null | undefined): boolean;
351
+ /** The language whose function words the utterance reads as, when not the stream's; else null. */
352
+ export declare function otherLanguageOf(text: string, streamLanguage: string | null | undefined): SttLanguage | null;
353
+ export declare function shouldRetranscribe(u: RetranscribeCandidate): boolean;
354
+ /**
355
+ * Decides the stream's language from one utterance's evidence at a time. A run of foreign
356
+ * utterances counts only while uninterrupted: any utterance that is not evidence for the same
357
+ * language (confident in the current one, undetected, or another language) starts it over.
358
+ */
359
+ export declare class TalkLanguageSwitch {
360
+ private run;
361
+ /**
362
+ * `detected` and `confidence` come from a re-transcription (null when none ran); `words` is the
363
+ * utterance's length. Returns the language to switch the stream to, or null to stay.
364
+ */
365
+ next(input: {
366
+ pinned: SttLanguage | null | undefined;
367
+ current: string | null;
368
+ home: SttLanguage | null;
369
+ detected: string | null | undefined;
370
+ confidence: number | null | undefined;
371
+ words: number;
372
+ /** The member's own languages: one clear utterance switches among them. */
373
+ preferred?: readonly SttLanguage[];
374
+ }): SttLanguage | null;
375
+ }
376
+ /**
377
+ * The home among the member's own languages: the one last confidently spoken in, else the
378
+ * device's or conversation's home when it is one of them, else the first of them.
379
+ */
380
+ export declare function ownHomeLanguage(own: readonly SttLanguage[], lastSpoken: SttLanguage | null, fallback: SttLanguage | null): SttLanguage | null;
381
+ export type LanguageStorage = Pick<Storage, 'getItem' | 'setItem'>;
382
+ export declare const LANGUAGE_HOME_KEY = "skaile.talk.language-home.v1";
383
+ export declare const LANGUAGE_LAST_KEY = "skaile.talk.language-last.v1";
384
+ /** Where the home language and the last spoken one are stored. */
385
+ export type LanguageHomeKeys = {
386
+ home: string;
387
+ last: string;
388
+ };
389
+ /**
390
+ * The long-term majority of confidently recognised utterances on this device, kept in
391
+ * `localStorage`. Reads and writes never throw: without storage there is just no device home.
392
+ */
393
+ export declare class LanguageHome {
394
+ private readonly storage;
395
+ private weights;
396
+ private lastSpoken;
397
+ private readonly keys;
398
+ constructor(storage: LanguageStorage | null, keys?: Partial<LanguageHomeKeys>);
399
+ /** The language the stream last ran in on a confident utterance, kept across sessions. */
400
+ get last(): SttLanguage | null;
401
+ recordLast(language: string): void;
402
+ private readLast;
403
+ get language(): SttLanguage | null;
404
+ /** One utterance confidently heard in `language`. */
405
+ record(language: string): void;
406
+ private read;
407
+ }
408
+ /**
409
+ * The seam between the Talk UI and whatever produces and plays speech. Today it is the
410
+ * STT → assistant → TTS pipeline (`PipelineVoiceLayer`); a speech-to-speech provider can
411
+ * replace it later without the Talk screen noticing.
412
+ */
413
+ export type TalkUtterance = {
414
+ /** Stable per utterance; an eager send and the final one that supersedes it share it. */
415
+ id: string;
416
+ text: string;
417
+ /** Detected or configured language. */
418
+ language: string | null;
419
+ /** AudioContext seconds, speech start. */
420
+ startedAt: number;
421
+ endedAt: number;
422
+ /** `endedAt` in monotonic ms (`performance.now()`), for the turn latency record. */
423
+ endedAtMs?: number;
424
+ /** When the layer handed the utterance over (the end-of-turn decision), monotonic ms. */
425
+ decidedAtMs?: number;
426
+ /** false = eager (is_final + 400 ms silence); true = speech_final + hold. */
427
+ final: boolean;
428
+ /** Made only of hush phrases: stop playback, never send. */
429
+ hush: boolean;
430
+ /** Started after playback ended, so it may decide an approval. */
431
+ consentEligible: boolean;
432
+ };
433
+ export type TalkBargeIn = {
434
+ /**
435
+ * `pause`: the session paused (the page went to the background on iPhone), nobody spoke.
436
+ * `ended`: the conversation ended. `replaced`: a newer reply, or the user's own words, took
437
+ * its place. `error`: the speech output failed, its fallback too.
438
+ */
439
+ reason: 'voice' | 'hush' | 'tap' | 'pause' | 'ended' | 'replaced' | 'error';
440
+ /** The `speak` turn that was cut; null when only an acknowledgment clip played. */
441
+ turnId: string | null;
442
+ /** Offset into the text passed to `speak` at the end of the last fully played chunk. */
443
+ heardChars: number;
444
+ heardText: string;
445
+ lastHeardSentence: string;
446
+ /** The first words of the cut reply (up to 200 characters): finds it when nothing was heard. */
447
+ replyStart: string;
448
+ };
449
+ /**
450
+ * A step of a reply on its way to the speaker, for the turn latency record: its first sentence
451
+ * was cut for speech, the speech model's first audio arrived, its first audio started playing.
452
+ * Once per stage and speak turn; `atMs` is monotonic (`performance.now()`).
453
+ */
454
+ export type TalkReplyStage = {
455
+ stage: 'cut' | 'ttsAudio' | 'playback';
456
+ turnId: string;
457
+ atMs: number;
458
+ /** `ttsAudio` only: the audio came from the streaming speech model. */
459
+ realtime?: boolean;
460
+ };
461
+ export type TalkLayerState = {
462
+ listening: boolean;
463
+ speaking: boolean;
464
+ connected: boolean;
465
+ /** The language the speech recognition runs in now. */
466
+ streamLanguage?: string;
467
+ /** While speaking: the text of the chunk audible now, for the caption. */
468
+ speakingText?: string;
469
+ error?: 'connection_lost';
470
+ /** The session runs with the mic muted (`setMicMuted`): nothing is captured or transcribed. */
471
+ micMuted?: true;
472
+ /** The OS muted or ended the mic track, e.g. iOS while the page is in the background. */
473
+ micBlocked?: true;
474
+ /** A reply's speech is on its way but none of it plays yet: the orb shows thinking, not listening. */
475
+ replyPending?: true;
476
+ };
477
+ export type VoiceLayer = {
478
+ /** Opens mic + STT; audio is buffered until the socket is open. */
479
+ start(): Promise<void>;
480
+ /** Closes everything. */
481
+ stop(): void;
482
+ /** Mutes or unmutes the mic; the session, playback and everything else run on. */
483
+ setMicMuted(muted: boolean): void;
484
+ /**
485
+ * Back in the foreground: reopens what the browser took meanwhile (a dead mic track, the STT
486
+ * stream, a dropped connection). Never opens anything twice. Rejects when the mic can't reopen.
487
+ * `reopenMutedMic` (an explicit resume, with a user gesture) also replaces a track the OS
488
+ * still holds muted.
489
+ */
490
+ recover(options?: {
491
+ reopenMutedMic?: boolean;
492
+ }): Promise<void>;
493
+ setPushToTalk(on: boolean): void;
494
+ pressTalk(): void;
495
+ releaseTalk(): void;
496
+ /**
497
+ * Chunked for speech as it streams. Each yielded string is the next piece of the text
498
+ * (a delta, not the text so far). Repeated calls with the same turn id append a segment,
499
+ * joined by a line break; a new turn id drops the previous turn's playback; after an
500
+ * interrupt the turn's further text is ignored.
501
+ */
502
+ speak(turnId: string, text: AsyncIterable<string> | string): void;
503
+ /**
504
+ * A request went out: its reply will be spoken soon, so the speech output may get ready now
505
+ * (open its stream) instead of when the first words arrive.
506
+ */
507
+ prepareReply?(): void;
508
+ playAck(text: string, audio: ArrayBuffer): void;
509
+ /**
510
+ * Stops playback synchronously; null when nothing was playing or queued. It does not
511
+ * emit `bargeIn`: that event is only for barge-ins the layer detects in the user's voice.
512
+ */
513
+ interrupt(reason: TalkBargeIn['reason']): TalkBargeIn | null;
514
+ /**
515
+ * The raw mic and playback levels (RMS, 0..1). `micDevice` names the open microphone (its
516
+ * `deviceId`), so a learned calibration follows the device; null or absent when unknown.
517
+ */
518
+ readonly levels: {
519
+ mic(): number;
520
+ output(): number;
521
+ micDevice?(): string | null;
522
+ };
523
+ /**
524
+ * An eager utterance (`final: false`) may be followed by another eager one and then the
525
+ * final one, all with the same id; each supersedes the one before.
526
+ */
527
+ on(event: 'utterance', cb: (u: TalkUtterance) => void): () => void;
528
+ on(event: 'partial', cb: (text: string) => void): () => void;
529
+ /**
530
+ * `bargeIn`: playback was stopped by the user's voice. `reason: 'hush'` names what triggered
531
+ * it; whether anything is sent follows the utterance's own `hush` flag, which can still turn
532
+ * out false ("Stopp, was meinst du damit?").
533
+ * `dropped`: the layer dropped a reply with part of it unheard, on its own: a newer turn
534
+ * replaced it, the user talked past an eager answer, or its speech failed.
535
+ */
536
+ on(event: 'bargeIn' | 'dropped', cb: (b: TalkBargeIn) => void): () => void;
537
+ on(event: 'state', cb: (s: TalkLayerState) => void): () => void;
538
+ on(event: 'language', cb: (lang: string, supportedByTts: boolean) => void): () => void;
539
+ on(event: 'replyStage', cb: (s: TalkReplyStage) => void): () => void;
540
+ setAudioMode?(mode: TalkAudioMode): void;
541
+ /** Real headphones in effect: the user's voice may mute the reply before the words confirm it. */
542
+ setHeadphones?(on: boolean): void;
543
+ setLanguageContext?(pinned: SttLanguage | null, conversationLocale: string | null): void;
544
+ setVoice?(voiceId: string | null): void;
545
+ /** Pitch-preserving speed of the spoken replies; applies from the next audio on. */
546
+ setPlaybackRate?(rate: number): void;
547
+ /** The languages the user speaks; the stream switches only among these. */
548
+ setSpeakLanguages?(languages: SttLanguage[]): void;
549
+ /** Moves the speech recognition (and the replies) to this language now. */
550
+ switchToLanguage?(language: SttLanguage): void;
551
+ /** The user's speech terms; their pronunciations apply from the next spoken chunk. */
552
+ setSpeechTerms?(terms: readonly SpeechTerm[]): void;
553
+ };
554
+ /**
555
+ * Talk's voice layer on the STT → assistant → TTS pipeline: one 16 kHz PCM capture feeds
556
+ * the Deepgram socket, the pre-open buffer and the re-transcription ring; replies play
557
+ * through WebAudio so playback end, output latency and the output level are known on the
558
+ * same clock as the user's speech. Every browser dependency is injected (`deps`).
559
+ */
560
+ type AudioNodeLike = {
561
+ connect(destination: unknown): unknown;
562
+ disconnect(): void;
563
+ };
564
+ /** A mic track; the optional members are what lets the layer mute it and see the OS take it. */
565
+ export type MediaStreamTrackLike = {
566
+ stop(): void;
567
+ enabled?: boolean;
568
+ readonly readyState?: string;
569
+ readonly muted?: boolean;
570
+ getSettings?(): {
571
+ deviceId?: string;
572
+ };
573
+ addEventListener?(type: 'mute' | 'unmute' | 'ended', listener: () => void): void;
574
+ removeEventListener?(type: 'mute' | 'unmute' | 'ended', listener: () => void): void;
575
+ };
576
+ export type MediaStreamLike = {
577
+ getTracks(): MediaStreamTrackLike[];
578
+ };
579
+ export type AudioBufferSourceLike = AudioNodeLike & {
580
+ buffer: unknown;
581
+ onended: (() => void) | null;
582
+ start(when?: number): void;
583
+ stop(when?: number): void;
584
+ };
585
+ type GainNodeLike = AudioNodeLike & {
586
+ gain: {
587
+ value: number;
588
+ setValueAtTime(value: number, at: number): unknown;
589
+ linearRampToValueAtTime(value: number, at: number): unknown;
590
+ cancelScheduledValues?(at: number): unknown;
591
+ };
592
+ };
593
+ type ScriptProcessorLike = AudioNodeLike & {
594
+ onaudioprocess: ((event: {
595
+ inputBuffer: {
596
+ getChannelData(channel: number): Float32Array;
597
+ };
598
+ }) => void) | null;
599
+ };
600
+ export type AudioContextLike = {
601
+ readonly currentTime: number;
602
+ readonly sampleRate: number;
603
+ readonly outputLatency?: number;
604
+ readonly baseLatency?: number;
605
+ readonly destination: unknown;
606
+ resume?(): Promise<void>;
607
+ close(): Promise<void>;
608
+ createMediaStreamSource(stream: MediaStreamLike): AudioNodeLike;
609
+ createScriptProcessor(bufferSize: number, inputs: number, outputs: number): ScriptProcessorLike;
610
+ createGain(): GainNodeLike;
611
+ createAnalyser(): AudioNodeLike & {
612
+ fftSize: number;
613
+ getFloatTimeDomainData(array: Float32Array): void;
614
+ };
615
+ createBufferSource(): AudioBufferSourceLike;
616
+ decodeAudioData(data: ArrayBuffer): Promise<{
617
+ duration: number;
618
+ }>;
619
+ createBuffer(channels: number, length: number, sampleRate: number): AudioBufferLike;
620
+ };
621
+ export type AudioBufferLike = {
622
+ readonly duration: number;
623
+ getChannelData(channel: number): Float32Array;
624
+ };
625
+ type Timers$1 = {
626
+ setTimeout: (fn: () => void, ms: number) => unknown;
627
+ clearTimeout: (handle: unknown) => void;
628
+ };
629
+ export type PipelineVoiceDeps = {
630
+ getUserMedia: (constraints: MediaStreamConstraints) => Promise<MediaStreamLike>;
631
+ createAudioContext: () => AudioContextLike;
632
+ /** The host's voice relay: speech sockets, re-transcription and clips. */
633
+ transport: SpeechTransport;
634
+ /**
635
+ * An AudioWorklet capture node calling `onSamples` with mono float32 at the context rate.
636
+ * Absent or failing, capture falls back to a ScriptProcessor.
637
+ */
638
+ createCaptureNode?: (ctx: AudioContextLike, onSamples: (samples: Float32Array) => void) => Promise<AudioNodeLike>;
639
+ timers?: Timers$1;
640
+ createId?: () => string;
641
+ /** Where the device's home language is learned (`localStorage`); none in tests. */
642
+ storage?: LanguageStorage | null;
643
+ /** The storage keys of the device's home language; defaults keep what devices stored. */
644
+ storageKeys?: Partial<LanguageHomeKeys>;
645
+ /** The Talk diagnostic log: lengths, ids and reasons only, never transcript or reply text. */
646
+ diag?: TalkDiag;
647
+ /** Wall-clock milliseconds (`performance.now`): barge-in latency, and when the user's words last changed. */
648
+ nowMs?: () => number;
649
+ };
650
+ export type PipelineVoiceOptions = {
651
+ voiceId?: string | null;
652
+ pinnedLanguage?: SttLanguage | null;
653
+ conversationLocale?: string | null;
654
+ audioMode?: TalkAudioMode;
655
+ pushToTalk?: boolean;
656
+ /** Hush phrases interrupt over a phone speaker too. Defaults to on. */
657
+ speakerHush?: boolean;
658
+ /** The language of the last spoken utterance in the conversation: Talk stays in it across starts. */
659
+ lastUtteranceLanguage?: string | null;
660
+ /** Speak over the TTS stream socket (one per reply), else clip by clip. Defaults to on. */
661
+ realtimeTts?: boolean;
662
+ /** Talk's speaking speed (1 to 2); see `setPlaybackRate`. */
663
+ playbackRate?: number;
664
+ /** The languages the member speaks: favoured in recognition, switched between at once. */
665
+ speakLanguages?: SttLanguage[];
666
+ /** The browser's language (`navigator.language`): the home of last resort, so Talk never streams as `multi`. */
667
+ deviceLocale?: string | null;
668
+ /**
669
+ * The output really is headphones (the toggle, or detection), not a desktop speaker that only
670
+ * counts as headphones mode: the mic level alone may then mute the reply (`setHeadphones`).
671
+ */
672
+ headphones?: boolean;
673
+ /** The user's speech terms; those with a pronunciation are said that way (see `speech-aliases.ts`). */
674
+ speechTerms?: readonly SpeechTerm[];
675
+ };
676
+ export declare const TALK_MIC_CONSTRAINTS: MediaStreamConstraints;
677
+ export declare const RETRANSCRIBE_TIMEOUT_MS = 2000;
678
+ export declare const ACK_FADE_SECONDS = 0.18;
679
+ /**
680
+ * An utterance already sent eagerly whose words stopped this long ago no longer holds its answer
681
+ * back, whatever Deepgram's voice detection says (room noise keeps it open for seconds). New
682
+ * words after that are a barge-in or a continuation, as for any reply.
683
+ */
684
+ export declare const WORD_SILENCE_CLOSE_MS = 1200;
685
+ /** Voice without words extends the hold before a send by this much, at most to the cap below. */
686
+ export declare const VAD_HOLD_GRACE_MS = 1500;
687
+ /** Voice detection alone never holds a send longer than this past the end of the words. */
688
+ export declare const VAD_HOLD_CAP_MS = 3000;
689
+ /** An opened speech stream waits this long for the reply it was opened for, then closes. */
690
+ export declare const WARM_STREAM_MS = 45000;
691
+ export declare class PipelineVoiceLayer implements VoiceLayer {
692
+ private readonly deps;
693
+ private readonly options;
694
+ private readonly timers;
695
+ private readonly createId;
696
+ private readonly listeners;
697
+ private ctx;
698
+ private analyser;
699
+ private running;
700
+ private gen;
701
+ private stream;
702
+ private captureNodes;
703
+ private trackListeners;
704
+ /** Muted by the user (Media Session pause) or for a background pause: no capture, no STT stream. */
705
+ private micMuted;
706
+ /** The OS muted or ended the mic track (iOS in the background, a phone call). */
707
+ private micBlocked;
708
+ private micLevel;
709
+ private micDeviceId;
710
+ /** Utterances being finished (re-transcription in flight): no reply starts meanwhile. */
711
+ private finishing;
712
+ private pushToTalk;
713
+ private held;
714
+ private audioMode;
715
+ private voiceId;
716
+ private playbackRate;
717
+ private speakLanguages;
718
+ private speechTerms;
719
+ private readonly speakerHush;
720
+ private readonly realtimeTts;
721
+ private headphones;
722
+ private readonly nowMs;
723
+ /** Between the analyser and the speaker: the voice-onset trigger mutes the reply here. */
724
+ private outGain;
725
+ private readonly onset;
726
+ /** The reply is muted on the user's voice, waiting for words to confirm the barge-in. */
727
+ private duck;
728
+ /** The last muted stretch (audio clock): a clip ending inside it was not heard. */
729
+ private muteSpan;
730
+ /** The realtime stream failed once: the rest of this session speaks over `/voice/speak`. */
731
+ private realtimeBroken;
732
+ /** Re-runs the pump once an eagerly sent utterance's words have been silent long enough. */
733
+ private wordSilenceTimer;
734
+ /** Until when voice without words may still hold the open utterance (wall-clock ms). */
735
+ private vadHoldUntilMs;
736
+ /** When the pending hold sends the utterance (wall-clock ms). */
737
+ private holdUntilMs;
738
+ /** The reply's continuous stretch while Talk speaks faster or slower than normal. */
739
+ private stretch;
740
+ private stretchFlushTimer;
741
+ /** A speech stream opened ahead of the reply (`prepareReply`), with what it was opened for. */
742
+ private warm;
743
+ private live;
744
+ private connecting;
745
+ /** The generation a socket's token is being fetched for; a second caller waits for that one. */
746
+ private fetchingTokenFor;
747
+ private readonly draining;
748
+ private readonly preOpen;
749
+ private readonly ring;
750
+ private utt;
751
+ private holdTimer;
752
+ private readonly eager;
753
+ private pinned;
754
+ private conversationLocale;
755
+ private lastUtteranceLanguage;
756
+ private readonly languageHome;
757
+ private readonly languageSwitch;
758
+ private language;
759
+ private emittedLanguage;
760
+ private readonly echoRef;
761
+ private lastPlaybackEnd;
762
+ private turn;
763
+ private queue;
764
+ private scheduled;
765
+ private pumping;
766
+ /** Some of the queued speech already played: a gap between chunks still counts as speaking. */
767
+ private inTurnPlayback;
768
+ /** Speech went on after this utterance's eager send: the answer to that send stays silent. */
769
+ private supersededEager;
770
+ private lastState;
771
+ private error;
772
+ constructor(deps: PipelineVoiceDeps, options: PipelineVoiceOptions);
773
+ readonly levels: {
774
+ mic: () => number;
775
+ output: () => number;
776
+ micDevice: () => string | null;
777
+ };
778
+ on(event: 'utterance', cb: (u: TalkUtterance) => void): () => void;
779
+ on(event: 'partial', cb: (text: string) => void): () => void;
780
+ on(event: 'bargeIn' | 'dropped', cb: (b: TalkBargeIn) => void): () => void;
781
+ on(event: 'state', cb: (s: TalkLayerState) => void): () => void;
782
+ on(event: 'language', cb: (lang: string, supportedByTts: boolean) => void): () => void;
783
+ on(event: 'replyStage', cb: (s: TalkReplyStage) => void): () => void;
784
+ private emit;
785
+ /** A reply step for the turn latency record; reported once per stage and turn by the caller. */
786
+ private replyStage;
787
+ /** The speech model's first audio for `turn`, once. */
788
+ private noteTurnAudio;
789
+ private diag;
790
+ private emitState;
791
+ start(): Promise<void>;
792
+ stop(): void;
793
+ setPushToTalk(on: boolean): void;
794
+ pressTalk(): void;
795
+ releaseTalk(): void;
796
+ /**
797
+ * Mutes the mic without ending the session. The track is only disabled, not stopped, so
798
+ * unmuting needs no new `getUserMedia` (which may fail with the screen off) and the page keeps
799
+ * its capture, which stops Chrome from freezing it. The STT stream closes: no idle minutes.
800
+ */
801
+ setMicMuted(muted: boolean): void;
802
+ /**
803
+ * Back in the foreground: reopens whatever the browser took while the page was away. A session
804
+ * the connection dropped from restarts; a dead track is reopened; a missing STT stream opens
805
+ * again. Nothing is opened twice: every step checks what is still live.
806
+ */
807
+ recover({ reopenMutedMic }?: {
808
+ reopenMutedMic?: boolean;
809
+ }): Promise<void>;
810
+ /** The utterance in flight still finishes on its socket; nothing new is sent while muted. */
811
+ private closeStreamForMute;
812
+ /** Which barge-in rules apply: the UI decides from the pointer, the toggle and detection. */
813
+ setAudioMode(mode: TalkAudioMode): void;
814
+ /** Real headphones in effect or not; see `PipelineVoiceOptions.headphones`. */
815
+ setHeadphones(on: boolean): void;
816
+ /**
817
+ * The assistant's voice changed in the settings: the next sentence fetched speaks with it, so a
818
+ * running conversation never needs a restart. Clips already fetched keep the old voice.
819
+ */
820
+ setVoice(voiceId: string | null): void;
821
+ /**
822
+ * Talk's speaking speed, all on the client: every clip is time-stretched (pitch kept) as it is
823
+ * scheduled, a reply's pieces as one continuous stream. Clips scheduled but not started yet are
824
+ * stretched again, so a change is heard from the next clip on; the one playing finishes at the
825
+ * old speed.
826
+ */
827
+ setPlaybackRate(rate: number): void;
828
+ /** An acknowledgment clip at Talk's speed, at the same pitch: one clip, stretched on its own. */
829
+ private stretched;
830
+ /** The pinned language or conversation language changed; a different STT language reconnects. */
831
+ setLanguageContext(pinned: SttLanguage | null, conversationLocale: string | null): void;
832
+ private homeLanguage;
833
+ /** The member's languages changed in the settings; the stream moves only if it left them. */
834
+ setSpeakLanguages(languages: SttLanguage[]): void;
835
+ /** The user's speech terms changed (the assistant added one): said that way from the next chunk on. */
836
+ setSpeechTerms(terms: readonly SpeechTerm[]): void;
837
+ /** `text` as the speech model should read it in the reply language. */
838
+ private toSpeech;
839
+ /** Switch the stream now ("sprich Englisch", the language chip). */
840
+ switchToLanguage(language: SttLanguage): void;
841
+ private audioContext;
842
+ private openMic;
843
+ /** The OS can take the mic (iOS in the background, a call): the session hears of it by state. */
844
+ private watchTracks;
845
+ private setMicBlocked;
846
+ private releaseMic;
847
+ private onFrame;
848
+ /** Over headphones the user's voice mutes the reply at once; the transcript then decides. */
849
+ private watchForVoiceOnset;
850
+ private duckForVoice;
851
+ /**
852
+ * Lifts the voice-onset mute. Without words confirming it (a cough, a door) the reply is heard
853
+ * again from where it is now: the muted part is lost, but a false trigger never cuts a reply.
854
+ */
855
+ private releaseDuck;
856
+ private outputLatencyMs;
857
+ private send;
858
+ private openSocket;
859
+ private onSocketMessage;
860
+ private onReady;
861
+ /** Stops sending to `socket` and lets it deliver its last transcripts. */
862
+ private retire;
863
+ private onSocketGone;
864
+ private connectionLost;
865
+ private closeSockets;
866
+ private switchLanguage;
867
+ private newUtterance;
868
+ private resetUtterance;
869
+ private now;
870
+ private onSpeechStarted;
871
+ private onTranscript;
872
+ /**
873
+ * For the log: how long the words took after the speech began (the STT wait), and how long the
874
+ * voice-onset mute held the reply before them.
875
+ */
876
+ private wordsDetection;
877
+ private judgeDuringPlayback;
878
+ private displayText;
879
+ private meanConfidence;
880
+ /**
881
+ * Not for a hush (it is never sent), a low-confidence one (it is re-transcribed first), nor one
882
+ * whose words leave the thought open: sending half a sentence there made the agent start on it.
883
+ */
884
+ private eagerAllowed;
885
+ /** The stream runs in another language than the (unpinned) home one. */
886
+ private awayFromHome;
887
+ private hold;
888
+ private onSpeechFinal;
889
+ private sendEager;
890
+ /** The language STT reported for the utterance (its configured one), else the sticky language. */
891
+ private utteranceLanguage;
892
+ private toUtterance;
893
+ private finishUtterance;
894
+ private finishUtteranceInner;
895
+ /** Moves the stream's language on this utterance's evidence, and teaches the device its home. */
896
+ private followLanguage;
897
+ /**
898
+ * The utterance's language checked against the member's own languages, within one
899
+ * re-transcription budget. Words that read as another of them are re-transcribed in it at once;
900
+ * otherwise Deepgram detects the language, and a third language it is unsure of is re-checked in
901
+ * the member's other language. A pinned re-check counts only when its words are surer than the
902
+ * stream's; else the stream's text stands. Nothing is dropped: null keeps the stream's text.
903
+ */
904
+ private recheckLanguage;
905
+ private retranscribe;
906
+ private requestRetranscription;
907
+ /** A reply is audible, or between two of its chunks. */
908
+ private isSpeaking;
909
+ /** Speech is queued for the reply but none of it played yet. */
910
+ private pendingPlayback;
911
+ /** Speech waits to be scheduled: queued clips, or text on the realtime stream not yet heard back. */
912
+ private speechQueued;
913
+ /** The current reply's stream still owes audio for text it was sent (the realtime "queue"). */
914
+ private realtimePending;
915
+ /**
916
+ * The open utterance has words: the user is talking, or paused inside the utterance hold. One
917
+ * already sent eagerly stops counting once its words have been silent for a moment.
918
+ */
919
+ private userTalking;
920
+ private closedByWordSilence;
921
+ /** The pump is held for an eagerly sent utterance: look again once its words were silent long enough. */
922
+ private recheckWordSilence;
923
+ /** Speech for the current reply is on its way and none of it plays yet. */
924
+ private replyOnItsWay;
925
+ /** No reply starts while the user talks; one already audible is left to the barge-in rules. */
926
+ private holdsForUser;
927
+ /** The reply queued is the answer to this very utterance's eager send. */
928
+ private isOwnEagerAnswer;
929
+ /**
930
+ * The user said more while an earlier reply waited unheard: it answers what came before, so it
931
+ * is dropped (a barge-in with nothing heard) as the utterance that replaces it is sent. Any
932
+ * finished utterance counts, one word too: it is sent, and its answer replaces this one.
933
+ */
934
+ private dropReplyTheUserTalkedPast;
935
+ speak(turnId: string, text: AsyncIterable<string> | string): void;
936
+ /** One `speak` call is one segment of the turn's text; segments are joined by a line break. */
937
+ private consumeSegment;
938
+ private cut;
939
+ /**
940
+ * Chunks are joined by one space, so the model hears one continuous reply. A segment that
941
+ * follows an ended one gets its own stream, opened once the earlier stream is over so its
942
+ * audio cannot overtake.
943
+ */
944
+ private sendRealtime;
945
+ private endRealtime;
946
+ private startRealtime;
947
+ /**
948
+ * A request went out: the reply's speech stream opens now, so its handshake (and the voice
949
+ * provider's) is done by the time the first sentence arrives. One at a time; it closes unused
950
+ * after {@link WARM_STREAM_MS}.
951
+ */
952
+ prepareReply(): void;
953
+ /** The warm stream, when it is still open and speaks in the voice and language wanted now. */
954
+ private takeWarmStream;
955
+ private closeWarmStream;
956
+ private warmKey;
957
+ /** Opens the reply's TTS socket once a fresh credential is in, in the voice and language of then. */
958
+ private realtimeDial;
959
+ /**
960
+ * Queues one PCM piece like a fetched clip. Heard tracking stays per chunk: the piece whose
961
+ * alignment completes a chunk carries that chunk's source range; others carry an empty one.
962
+ */
963
+ private onRealtimeAudio;
964
+ /**
965
+ * Sets the item's source range to the spoken (non-code) chunks it completes; with none, an
966
+ * empty range at what is already covered, which `onPlayed` does not count as a sentence.
967
+ */
968
+ private markCovered;
969
+ /** Without alignment, coverage settles here: the stream's last piece completes what is left. */
970
+ private onRealtimeDone;
971
+ /** The stream failed: what it has not voiced yet is spoken over `/voice/speak`, as is the rest of the session. */
972
+ private onRealtimeError;
973
+ private queueOverHttp;
974
+ /** Hands over to the turn's next segment stream (or, after a failure, to HTTP). */
975
+ private afterRealtime;
976
+ /** Drops the reply's streams: nothing more is sent, late audio is ignored. */
977
+ private closeRealtime;
978
+ playAck(text: string, audio: ArrayBuffer): void;
979
+ private prefetch;
980
+ private fetchSpeech;
981
+ private pump;
982
+ /**
983
+ * A reply clip came back without audio (its fallback failed too): the reply ends after what
984
+ * already plays rather than skip a sentence, and the rest is reported unheard.
985
+ */
986
+ private speechFailed;
987
+ /** Reply audio is decoded or already playing: an acknowledgment not started yet is not needed. */
988
+ private replyAudioReady;
989
+ /**
990
+ * The reply's audio is about to play: an acknowledgment still audible fades out and the reply
991
+ * follows the fade, not the clip's natural end; one not started yet is dropped.
992
+ */
993
+ private yieldAcks;
994
+ private schedule;
995
+ /**
996
+ * A reply piece at Talk's speed. Every piece of the reply goes through one continuous stretch,
997
+ * so the pieces join without the faded, misaligned edges each would get stretched on its own.
998
+ * Null when the stretch holds all of a tiny piece back: its range rides on the next piece.
999
+ */
1000
+ private streamStretched;
1001
+ /** A piece held back whole gave its source range to this one. */
1002
+ private takeCarry;
1003
+ /**
1004
+ * The stretch holds back the last few milliseconds, which the next piece overlaps. When no next
1005
+ * piece comes before the audio scheduled so far runs out, they are played on their own.
1006
+ */
1007
+ private armStretchFlush;
1008
+ /** Plays what the stretch still holds right after the reply's last piece, and ends it. */
1009
+ private flushStretch;
1010
+ /** The reply was cut or replaced: what the stretch holds is never played. */
1011
+ private dropStretch;
1012
+ private play;
1013
+ private onPlayed;
1014
+ interrupt(reason: TalkBargeIn['reason']): TalkBargeIn | null;
1015
+ /** Stops every clip now and drops the rest of the turn; null when nothing was playing or queued. */
1016
+ private stopPlayback;
1017
+ /**
1018
+ * Every way playback stops ends here, so none of them leaves sound behind: each scheduled
1019
+ * source (the ones queued ahead too) is stopped and disconnected, the clips waiting are
1020
+ * dropped, the turn's fetches are aborted and its streams closed (late pieces are refused in
1021
+ * `schedule`), and a voice-onset mute is lifted for the next reply. `keep` spares the
1022
+ * acknowledgment of a new message when a new turn replaces the old one.
1023
+ */
1024
+ private stopPlaybackNow;
1025
+ /** Offsets and text in the reply without audio tags, as Chat shows and splits it. */
1026
+ private cutReport;
1027
+ /** The turn still owed speech: clips queued or playing, text on its stream, or text not cut yet. */
1028
+ private owesSpeech;
1029
+ /** A new turn replaces the previous one's speech; an acknowledgment clip plays on. */
1030
+ private dropTurnPlayback;
1031
+ /** The user kept talking after an eager send: its answer is dropped without a barge-in. */
1032
+ private supersedeEager;
1033
+ private silenceEagerAnswer;
1034
+ }
1035
+ export declare function createWorkletCaptureNode(ctx: AudioContextLike, onSamples: (samples: Float32Array) => void): Promise<AudioWorkletNode>;
1036
+ /**
1037
+ * Eager start: an utterance leaves at the first `is_final` segment followed by 400 ms of
1038
+ * silence, without waiting for `speech_final` and the utterance-end hold. If the user
1039
+ * keeps talking, the final utterance supersedes it (same utterance id), so the eager
1040
+ * one's answer is never spoken.
1041
+ */
1042
+ export declare const EAGER_SILENCE_MS = 400;
1043
+ type Timers = {
1044
+ setTimeout: (fn: () => void, ms: number) => unknown;
1045
+ clearTimeout: (handle: unknown) => void;
1046
+ };
1047
+ export declare class EagerSend {
1048
+ private readonly onEager;
1049
+ private readonly timers;
1050
+ private timer;
1051
+ private sentText;
1052
+ constructor(onEager: (text: string) => void, timers?: Timers);
1053
+ /**
1054
+ * A final segment arrived; `text` is the utterance so far. Sends it after 400 ms of silence,
1055
+ * at most once per utterance: each further eager send reached the agent as another prompt, so a
1056
+ * sentence with pauses arrived as several growing copies of itself.
1057
+ */
1058
+ finalSegment(text: string): void;
1059
+ /** The user is still talking: no eager send yet. */
1060
+ speechContinued(): void;
1061
+ /** The text an eager send already carried, or null. */
1062
+ get sent(): string | null;
1063
+ /** True when the final utterance must replace what was sent eagerly. */
1064
+ supersedes(finalText: string): boolean;
1065
+ /** The utterance ended; the next one starts fresh. */
1066
+ reset(): void;
1067
+ private clear;
1068
+ }
1069
+ /**
1070
+ * Tells the assistant's own voice, leaking from the speaker into the microphone, apart
1071
+ * from the user. All times are AudioContext seconds (the audio clock), never event
1072
+ * arrival times: an echo that arrives late is still judged by when its audio began.
1073
+ */
1074
+ /** How long played text stays in the reference: a phone speaker's echo lags by a sentence. */
1075
+ export declare const ECHO_REFERENCE_SECONDS = 12;
1076
+ /** Speech that began this soon after playback ended may still be the echo of its last words. */
1077
+ export declare const ECHO_TAIL_SECONDS = 0.3;
1078
+ /** Lowercase, hyphens removed (so "Excel-Tabellen" is one token), punctuation dropped, split on whitespace. */
1079
+ export declare function normalizeTokens(text: string): string[];
1080
+ /** Letters and digits only, so compound spellings compare equal. */
1081
+ export declare function compactForm(text: string): string;
1082
+ type EchoEntry = {
1083
+ text: string;
1084
+ playedFrom: number;
1085
+ /** null while it is still playing. */
1086
+ playedTo: number | null;
1087
+ tokens: Set<string>;
1088
+ compact: string;
1089
+ };
1090
+ /** Everything played in the last 12 s, the acknowledgment clips included. */
1091
+ export declare class EchoReference {
1092
+ private entries;
1093
+ /** Records text that starts playing; returns a handle to mark its end. */
1094
+ add(text: string, playedFrom: number, playedTo?: number | null): {
1095
+ end(at: number): void;
1096
+ };
1097
+ /** The entries still in the window at `now`; older ones are dropped. */
1098
+ current(now: number): readonly EchoEntry[];
1099
+ clear(): void;
1100
+ }
1101
+ /**
1102
+ * Echo when ≥ 60 % of the transcript's tokens were played, or when its compact form is
1103
+ * at least 8 characters and sits inside a single played entry. Short replies ("ja
1104
+ * bitte", "nein") are never echo just by being substrings.
1105
+ */
1106
+ export declare function isEcho(text: string, ref: EchoReference, now: number): boolean;
1107
+ /** Speech that started before playback end + 300 ms may be the echo of the last words. */
1108
+ export declare function isEchoTail(speechStart: number, playbackEnd: number | null): boolean;
1109
+ /** Whole-token equality, so "halt" is not found in "Inhalt" nor "moment" in "momentan". */
1110
+ export declare function wholeTokenInReference(token: string, ref: EchoReference, now: number): boolean;
1111
+ /**
1112
+ * Scales the Talk level to the speaker and the voice. Real speech has an RMS of about 0.05–0.25,
1113
+ * far from full scale, and how loud it is depends on the microphone, the person and the TTS voice.
1114
+ * A peak tracker learns that top end, so normal speech moves the orb to about 0.8 and emphasis
1115
+ * reaches 1, on any device.
1116
+ *
1117
+ * The learned peaks are kept per mic device and per TTS voice in `localStorage`, so a new
1118
+ * conversation starts calibrated. The noise floor is not kept: it belongs to the room and the
1119
+ * noise gate relearns it within seconds.
1120
+ */
1121
+ /** Time constant for the peak rising to louder speech. */
1122
+ export declare const PEAK_ATTACK_TAU_MS = 60;
1123
+ /** Time constant for the peak settling to the current speech; it moves only while there is speech. */
1124
+ export declare const PEAK_RELEASE_TAU_MS = 8000;
1125
+ /**
1126
+ * The lowest peak, in level units above the noise floor: anything quieter than this is not
1127
+ * speech, so it is never stretched to full movement. Playback has no noise, so it may go lower.
1128
+ */
1129
+ export declare const MIN_PEAK = 0.03;
1130
+ /** The mic's lowest peak: room noise bursts past the dead zone stay well under full movement. */
1131
+ export declare const MIC_MIN_PEAK = 0.05;
1132
+ /**
1133
+ * Starting peaks when nothing is stored, set so normal speech (RMS ~0.1) lands at about 0.8–0.85
1134
+ * from the first sentence. Low on purpose: the peak rises within a second, but settles over minutes.
1135
+ */
1136
+ export declare const DEFAULT_MIC_PEAK = 0.075;
1137
+ export declare const DEFAULT_OUTPUT_PEAK = 0.13;
1138
+ /** The peak settles this far above the current speech, so normal speech keeps room for emphasis. */
1139
+ export declare const PEAK_HEADROOM = 1.35;
1140
+ /** Below 1 lifts the middle: steady speech lands at about 0.83, quiet words stay visible. */
1141
+ export declare const CURVE_EXPONENT = 0.6;
1142
+ /** Time constant for the speech mean, which bounds the peak against a single loud transient. */
1143
+ export declare const SPEECH_MEAN_TAU_MS = 2000;
1144
+ /** The peak never sits above this multiple of the recent speech: a cough cannot set it. */
1145
+ export declare const PEAK_MEAN_CAP = 2;
1146
+ /** Mic levels this little above the noise threshold are room noise, not speech: the orb stays still. */
1147
+ export declare const MIC_DEAD_ZONE = 0.01;
1148
+ /** Learns the top end of a level and maps the level to 0..1 against it. */
1149
+ export declare class PeakTracker {
1150
+ private readonly minPeak;
1151
+ private value;
1152
+ private speechMean;
1153
+ constructor(initialPeak?: number, minPeak?: number);
1154
+ get peak(): number;
1155
+ /**
1156
+ * The peak the recent speech settles to: what is worth keeping for the next conversation. It
1157
+ * follows the speech mean, so a transient that briefly lifted the live peak is not stored.
1158
+ */
1159
+ get settledPeak(): number;
1160
+ /** Feeds one level (above the floor, 0..1) sampled `elapsedMs` after the previous one. */
1161
+ next(raw: number, elapsedMs: number): number;
1162
+ }
1163
+ export type PeakStorage = Pick<Storage, 'getItem' | 'setItem'>;
1164
+ export declare const PEAK_STORAGE_KEY = "skaile.talk.level-peaks.v1";
1165
+ /** Stored peaks outside this range are a bug or a broken device, not a speaker: ignored. */
1166
+ export declare const MAX_STORED_PEAK = 0.8;
1167
+ export declare const PEAK_MAX_AGE_MS: number;
1168
+ /** The stored peak for `key`, or null when none is stored or it is implausible or stale. */
1169
+ export declare function readStoredPeak(storage: PeakStorage | null, key: string, now: number, storageKey?: string): number | null;
1170
+ /** Stores the peak for `key`; a full or blocked storage is ignored. */
1171
+ export declare function writeStoredPeak(storage: PeakStorage | null, key: string, peak: number, now: number, storageKey?: string): void;
1172
+ /** How often a changed peak is written while a conversation runs. */
1173
+ export declare const PEAK_SAVE_INTERVAL_MS = 10000;
1174
+ export type TalkLevelCalibrationOptions = {
1175
+ storage?: PeakStorage | null;
1176
+ /** Where the learned peaks are stored; the default keeps what devices stored. */
1177
+ storageKey?: string;
1178
+ now?: () => number;
1179
+ };
1180
+ /**
1181
+ * The mic level (noise gate, then the mic's peak) and the output level (the voice's peak; playback
1182
+ * has no noise floor), each mapped to 0..1 for the orb.
1183
+ */
1184
+ export declare class TalkLevelCalibration {
1185
+ private readonly storage;
1186
+ private readonly storageKey;
1187
+ private readonly now;
1188
+ private readonly gate;
1189
+ private micChannel;
1190
+ private outputChannel;
1191
+ constructor(options?: TalkLevelCalibrationOptions);
1192
+ /** The learned mic peak, for tests and diagnostics. */
1193
+ get micPeak(): number | null;
1194
+ get outputPeak(): number | null;
1195
+ mic(raw: number, elapsedMs: number, deviceId: string | null | undefined): number;
1196
+ output(raw: number, elapsedMs: number, voiceId: string | null | undefined): number;
1197
+ /** Writes what changed since the last write; at the end of a conversation. */
1198
+ flush(): void;
1199
+ }
1200
+ /**
1201
+ * Smooths the calibrated Talk level before it reaches the orb. The level is a per-frame RMS
1202
+ * pushed through a lifting curve, so it flickers from frame to frame; a fast attack keeps each
1203
+ * syllable's onset and a slower release lets it fall back without twitching.
1204
+ */
1205
+ /** Time constant for a rising level: a syllable still lands within about a tenth of a second. */
1206
+ export declare const LEVEL_ATTACK_MS = 70;
1207
+ /** Time constant for a falling level: the orb settles between syllables instead of dropping. */
1208
+ export declare const LEVEL_RELEASE_MS = 220;
1209
+ type LevelEnvelopeOptions = {
1210
+ attackMs?: number;
1211
+ releaseMs?: number;
1212
+ };
1213
+ /** A one-pole envelope follower with separate attack and release, frame-rate independent. */
1214
+ export declare class LevelEnvelope {
1215
+ private value;
1216
+ private readonly attackMs;
1217
+ private readonly releaseMs;
1218
+ constructor({ attackMs, releaseMs }?: LevelEnvelopeOptions);
1219
+ get level(): number;
1220
+ /** Feeds one level (0..1) sampled `elapsedMs` after the previous one; returns the smoothed level. */
1221
+ next(raw: number, elapsedMs: number): number;
1222
+ }
1223
+ /**
1224
+ * Turns the raw microphone level into the part that is speech. A real microphone is never silent
1225
+ * (room noise, a fan, a car), so the raw level keeps the logo trembling in the user's pauses. The
1226
+ * gate learns that floor and passes on only what rises above it, normalised to 0..1.
1227
+ *
1228
+ * The floor follows a slow minimum: it drops quickly to a quieter level and rises slowly, so the
1229
+ * pauses between words keep pulling it down while seconds of steady noise lift it up.
1230
+ */
1231
+ export declare class AdaptiveNoiseGate {
1232
+ private floor;
1233
+ /** The learned noise floor, or null before the first sample. */
1234
+ get noiseFloor(): number | null;
1235
+ /** Feeds one raw level (0..1) sampled `elapsedMs` after the previous one; returns the gated level. */
1236
+ next(raw: number, elapsedMs: number): number;
1237
+ /**
1238
+ * Like `next`, but returns how far the level rises above the noise threshold in raw units, for a
1239
+ * caller that scales it itself (the peak normaliser, which learns the speaker's top end).
1240
+ */
1241
+ excess(raw: number, elapsedMs: number): number;
1242
+ /** Forgets the floor, e.g. when the microphone or the room changes. */
1243
+ reset(): void;
1244
+ }
1245
+ /**
1246
+ * Talk's one capture path: microphone float32 at the device rate → 16 kHz linear16. The
1247
+ * same frames feed the STT socket, the pre-open buffer and the re-transcription ring.
1248
+ */
1249
+ export declare const PCM_SAMPLE_RATE = 16000;
1250
+ /** Audio held while the STT socket is not open yet (start, reconnect, rollover). */
1251
+ export declare const PRE_OPEN_SECONDS = 10;
1252
+ /** What the re-transcription route takes: 30 s of 16-bit samples, 960,000 bytes. */
1253
+ export declare const RETRANSCRIBE_SECONDS = 30;
1254
+ export type PcmFrame = {
1255
+ samples: Int16Array;
1256
+ /** AudioContext time of the frame's first sample. */
1257
+ capturedAt: number;
1258
+ };
1259
+ /** Frame duration in seconds. */
1260
+ export declare function frameSeconds(frame: PcmFrame): number;
1261
+ /**
1262
+ * Downsamples by averaging each output sample's input window. It keeps the fractional
1263
+ * position across calls: dropping it per frame (44.1 kHz → 16 kHz is 2.756) would let the
1264
+ * stream run ~1 % short and drift against the audio clock.
1265
+ */
1266
+ export declare class Downsampler {
1267
+ private readonly ratio;
1268
+ private pos;
1269
+ constructor(inputRate: number, outputRate?: number);
1270
+ process(input: Float32Array): Int16Array;
1271
+ }
1272
+ /** Root mean square of a frame, 0..1, for the level meter. */
1273
+ export declare function frameLevel(samples: Int16Array): number;
1274
+ /** Frames waiting for the socket, oldest dropped past 10 s, flushed in order. */
1275
+ export declare class PreOpenBuffer {
1276
+ private frames;
1277
+ private samples;
1278
+ private readonly cap;
1279
+ constructor(seconds?: number);
1280
+ push(frame: PcmFrame): void;
1281
+ /** Everything buffered, oldest first; the buffer is empty afterwards. */
1282
+ drain(): PcmFrame[];
1283
+ get length(): number;
1284
+ }
1285
+ /**
1286
+ * The last 30 s of captured audio, so an utterance can be re-transcribed from its own
1287
+ * audio. An utterance longer than that is cut to its last 30 s; `startedAt` tells the
1288
+ * caller where the kept audio begins, so the earlier part keeps its original text.
1289
+ */
1290
+ export declare class UtteranceRing {
1291
+ private frames;
1292
+ private samples;
1293
+ private readonly cap;
1294
+ constructor(seconds?: number);
1295
+ push(frame: PcmFrame): void;
1296
+ /**
1297
+ * The audio between `from` and `until` (AudioContext seconds), at most 30 s, as
1298
+ * linear16 bytes, with the time its first kept sample was captured.
1299
+ */
1300
+ since(from: number, until?: number): {
1301
+ bytes: ArrayBuffer;
1302
+ startedAt: number;
1303
+ truncated: boolean;
1304
+ };
1305
+ clear(): void;
1306
+ }
1307
+ export type RealtimeTtsCallbacks = {
1308
+ onReady?: (sampleRate: number) => void;
1309
+ /** `alignedText`: the characters of the reply this piece speaks, when the server sent them. */
1310
+ onAudio: (pcm: Int16Array, alignedText: string | null, sampleRate: number) => void;
1311
+ onDone: () => void;
1312
+ /** An error frame, a failed connect, or the socket closing before `done`. Fires at most once. */
1313
+ onError: (reason: RealtimeTtsFailure) => void;
1314
+ };
1315
+ /** Why a stream failed, for the Talk diagnostic log. */
1316
+ export type RealtimeTtsFailure = 'no_url' | 'error_frame' | 'closed_before_ready' | 'closed_before_done';
1317
+ export declare class RealtimeTtsStream {
1318
+ private ws;
1319
+ private ready;
1320
+ private finished;
1321
+ private sampleRate;
1322
+ private readonly pending;
1323
+ private alignment;
1324
+ private callbacks;
1325
+ /**
1326
+ * `dial` resolves once a fresh credential is in, to what opens the socket; text sent meanwhile
1327
+ * is buffered. Without callbacks the stream opens warm, for a reply that has not started yet,
1328
+ * and `attach` hands it over.
1329
+ */
1330
+ constructor(dial: Promise<() => WebSocketLike>, callbacks?: RealtimeTtsCallbacks);
1331
+ /** Still open (or opening), with no text sent: a reply can take it over. */
1332
+ get usable(): boolean;
1333
+ /** The reply that takes over a warm stream; `onReady` fires at once when it is ready already. */
1334
+ attach(callbacks: RealtimeTtsCallbacks): void;
1335
+ send(text: string, { flush }?: {
1336
+ flush?: boolean;
1337
+ }): void;
1338
+ /** No more text: the server speaks what it holds, then answers `done`. */
1339
+ end(): void;
1340
+ /** Drops the reply: nothing more is sent and no callback fires. */
1341
+ close(): void;
1342
+ private connect;
1343
+ private post;
1344
+ private onMessage;
1345
+ private fail;
1346
+ }
1347
+ /**
1348
+ * Cuts a streaming reply into the pieces Talk sends to TTS. The first piece leaves as
1349
+ * early as possible (first sentence end, or the first comma after ≥ 4 words); later
1350
+ * pieces are sentence-sized. Each piece keeps its `[start, end)` offsets in the source
1351
+ * text, which is what an interruption reports as heard. Audio tags (`[[laughs]]`) stay
1352
+ * whole and with their sentence; a tag still streaming in waits until it closes, and one
1353
+ * left unclosed at the reply's end is not spoken.
1354
+ */
1355
+ export declare const CODE_BLOCK_NOTICE = "I've put the details in the chat.";
1356
+ export type SpeakableChunk = {
1357
+ /** What is spoken, without audio tags (markdown and URLs stripped); empty for a tag alone. */
1358
+ text: string;
1359
+ /** The same with its audio tags as ElevenLabs v4 reads them (`[laughs]`), for the realtime stream. */
1360
+ tagged: string;
1361
+ /** Source offsets of the piece; `end` is where "heard" stops once it played fully. */
1362
+ start: number;
1363
+ end: number;
1364
+ /** A code block, spoken as `CODE_BLOCK_NOTICE`. */
1365
+ code: boolean;
1366
+ };
1367
+ export type ChunkCut = {
1368
+ chunks: SpeakableChunk[];
1369
+ next: number;
1370
+ };
1371
+ /**
1372
+ * Speakable pieces of `text` from `from` on. `first`: nothing of this reply was cut yet.
1373
+ * `final`: the reply is complete, so the remainder is a piece too.
1374
+ */
1375
+ export declare function takeSpeakableChunks(source: string, from: number, { first, final }?: {
1376
+ first?: boolean;
1377
+ final?: boolean;
1378
+ }): ChunkCut;
1379
+ /**
1380
+ * Pronunciation by text alias: before a reply goes to the speech model, a word with a known
1381
+ * pronunciation is replaced by a spelling the voice reads right ("mergen" → "mördschen" in German
1382
+ * speech). Only the text sent to ElevenLabs changes; captions, the echo reference and what Talk
1383
+ * reports as heard keep the reply's own words.
1384
+ *
1385
+ * Why an alias and not ElevenLabs' own mechanisms: pronunciation dictionaries are not documented
1386
+ * for the text-to-dialogue stream Talk uses (v4), phoneme tags work on a single Flash model only,
1387
+ * and v4's inline IPA would be read aloud by the Flash fallback. A respelling works on every model
1388
+ * and both paths. Its limit: it is only as good as the spelling, and the voice may still stress it
1389
+ * the German way.
1390
+ */
1391
+ export type SpeechAlias = {
1392
+ term: string;
1393
+ pronunciation: string;
1394
+ };
1395
+ /** The aliases for speech in `language`: the user's own entries first, then the built-in ones. */
1396
+ export declare function speechAliasesFor(language: string | null, userTerms: readonly SpeechTerm[]): SpeechAlias[];
1397
+ /** One replacement: `source*` in the original text, `spoken*` in the aliased one. */
1398
+ type AliasSpan = {
1399
+ sourceStart: number;
1400
+ sourceEnd: number;
1401
+ spokenStart: number;
1402
+ spokenEnd: number;
1403
+ };
1404
+ /**
1405
+ * The text with every whole-word, case-insensitive match replaced, and where each replacement
1406
+ * sits in both texts. Text outside the spans is unchanged, so an offset maps through them.
1407
+ */
1408
+ export declare function applySpeechAliases(text: string, aliases: readonly SpeechAlias[]): {
1409
+ text: string;
1410
+ spans: AliasSpan[];
1411
+ };
1412
+ /**
1413
+ * The seams of a Talk session (`createTalk`): what it needs from the host's conversation with its
1414
+ * agent, and how a host extension (an approval flow, say) plugs in. Nothing here knows about a
1415
+ * particular host, its transport or its sessions.
1416
+ */
1417
+ /** One utterance (or a part of one) going to the agent. */
1418
+ export type TalkOutgoing = {
1419
+ text: string;
1420
+ /** UUID; a later send with the same id supersedes the eager one. */
1421
+ utteranceId: string;
1422
+ /** false = eager send. */
1423
+ final: boolean;
1424
+ language?: SttLanguage;
1425
+ /** The words go on with the previous message after a pause; the agent's marker says how. */
1426
+ continuation?: 'fold' | 'restart';
1427
+ /** Set while a turn runs: `now` replaces the turn, `fold` is read at its next step. */
1428
+ steer?: 'now' | 'fold';
1429
+ };
1430
+ /**
1431
+ * What the user heard of a cut reply. Nothing heard: `lastHeardSentence` is empty and
1432
+ * `replyStart` (the reply's first words) finds the reply instead.
1433
+ */
1434
+ export type TalkMarkInterrupted = {
1435
+ lastHeardSentence: string;
1436
+ heardChars: number;
1437
+ replyStart?: string;
1438
+ /** The prompt the cut reply answered, so the host searches only its turn. */
1439
+ promptId?: string;
1440
+ phase: 'barge' | 'settle';
1441
+ /** `system`: the speech stopped without the user cutting in (a pause, a failed voice). */
1442
+ cause?: 'user' | 'system';
1443
+ };
1444
+ /** The running conversation as the session reads it; emitted synchronously by the host. */
1445
+ export type ConversationEvent = {
1446
+ type: 'turn';
1447
+ running: boolean;
1448
+ } |
1449
+ /** The running turn's reply text so far (a snapshot; a tool call may empty it). */
1450
+ {
1451
+ type: 'text';
1452
+ text: string;
1453
+ } |
1454
+ /**
1455
+ * Alternative to `text` for hosts that only have deltas; `segmentStart` begins a new segment
1456
+ * (a tool call does too). A reply that replaces a running turn starts with `segmentStart` or
1457
+ * follows that turn's `turnEnded`, else it reads as the old reply going on.
1458
+ */
1459
+ {
1460
+ type: 'delta';
1461
+ delta: string;
1462
+ segmentStart?: boolean;
1463
+ } |
1464
+ /**
1465
+ * A tool started in the running turn. The agent's own call (`subagent` unset) ends its text
1466
+ * segment; a subagent's call lands mid-sentence and only tells the fillers that a wait is coming.
1467
+ */
1468
+ {
1469
+ type: 'toolStarted';
1470
+ name?: string;
1471
+ subagent?: boolean;
1472
+ } |
1473
+ /** A tool returned: the fillers learn how long it takes on this device. Optional. */
1474
+ {
1475
+ type: 'toolEnded';
1476
+ name?: string;
1477
+ subagent?: boolean;
1478
+ } | {
1479
+ type: 'turnEnded';
1480
+ outcome?: 'finished' | 'cancelled' | 'error';
1481
+ };
1482
+ /** The host's agent conversation, as Talk sends to and listens on it. */
1483
+ export type ConversationPort = {
1484
+ /** Resolves with the host's id for the prompt (host cards name it), if it has one. */
1485
+ send(message: TalkOutgoing): Promise<string | undefined>;
1486
+ /** Ends the running turn, keeping what streamed so far. */
1487
+ cancelTurn(): void;
1488
+ /** What the user heard of a cut reply; resolves `marked: false` while the rows are not stored yet. */
1489
+ markInterrupted(mark: TalkMarkInterrupted): Promise<{
1490
+ marked: boolean;
1491
+ }>;
1492
+ /**
1493
+ * A failed send, for the diagnostic log and the retry: `refused` sends are not tried again.
1494
+ * Without it every failure is `error` and retried once.
1495
+ */
1496
+ describeSendError?(error: unknown): {
1497
+ code: string;
1498
+ refused: boolean;
1499
+ };
1500
+ /** The conversation's events; Talk listens from construction until `dispose`. */
1501
+ subscribe(listener: (event: ConversationEvent) => void): () => void;
1502
+ };
1503
+ /** Why a running session is not listening: muted from outside the app, or paused in the background. */
1504
+ export type TalkPause = 'muted' | 'background';
1505
+ /** What the Talk screen shows of the session core; replaced on every change. */
1506
+ export type TalkSnapshot = {
1507
+ active: boolean;
1508
+ layer: TalkLayerState;
1509
+ /** The user's partial transcript while they speak. */
1510
+ partial: string;
1511
+ /** The detected language can't be spoken: replies are text only. */
1512
+ unsupportedLanguage: boolean;
1513
+ turnRunning: boolean;
1514
+ /** The prompt ids Talk sent in this conversation, oldest first. */
1515
+ promptIds: readonly string[];
1516
+ /** The session runs but the mic is closed; `background` wins when both apply. */
1517
+ paused: TalkPause | null;
1518
+ };
1519
+ /** One of Talk's own turns, newest last, as an extension may read it. */
1520
+ export type TalkTurnView = {
1521
+ readonly id: string;
1522
+ /** Device time. */
1523
+ readonly startMs: number;
1524
+ readonly endMs: number | null;
1525
+ /** Some of its reply (or a host question) was spoken. */
1526
+ readonly spoken: boolean;
1527
+ /** The host's id for its prompt; null until the send answered (or when it named none). */
1528
+ readonly promptId: string | null;
1529
+ readonly sendPending: boolean;
1530
+ /** A host question was spoken in it: an answer never continues the request. */
1531
+ readonly asked: boolean;
1532
+ };
1533
+ /** A question the host has open as an utterance ends; Talk lets the host claim the answer. */
1534
+ export type TalkHostQuestion = {
1535
+ /**
1536
+ * An answer is expected: spoken commands need their explicit form, the words never continue the
1537
+ * request and start no filler. False for a softer question that only holds eager sends back.
1538
+ */
1539
+ answering: boolean;
1540
+ /**
1541
+ * The final utterance's words before Talk sends them: resolves true when the host consumed them,
1542
+ * or is `false` at once when it does not take them.
1543
+ */
1544
+ claim(text: string): Promise<boolean> | false;
1545
+ };
1546
+ /** A host extension of the session, such as a flow that asks the user to approve something. */
1547
+ export type TalkInterceptor = {
1548
+ attach(api: TalkInterceptorApi): void;
1549
+ /** The user's words started (the first partial). */
1550
+ utteranceStarted?(): void;
1551
+ /**
1552
+ * An utterance (eager or final) ended, before Talk decides anything about it: the host question
1553
+ * it may answer, read before anything moves. While one is open, eager sends wait.
1554
+ */
1555
+ utteranceEnded?(u: TalkUtterance): TalkHostQuestion | null;
1556
+ /** A speak id of the host's own question, not of an agent turn: a cut of it marks nothing. */
1557
+ ownsTurn?(turnId: string): boolean;
1558
+ /** The first words of a turn's reply went to the speaker. */
1559
+ turnSpoken?(turnId: string): void;
1560
+ /** A send answered (its prompt id, or a failure): host state tied to turns may be judged again. */
1561
+ turnsChanged?(): void;
1562
+ /** The session stopped. */
1563
+ stopped?(): void;
1564
+ dispose?(): void;
1565
+ };
1566
+ /** What the session core offers its extension. */
1567
+ export type TalkInterceptorApi = {
1568
+ readonly state: TalkSnapshot;
1569
+ /** Paused because the page went to the background or the OS took the mic. */
1570
+ readonly suspended: boolean;
1571
+ /** The language Talk hears and speaks in now. */
1572
+ readonly spokenLanguage: string | null;
1573
+ /** When Talk last spoke anything, device time. */
1574
+ readonly lastSpokenAtMs: number;
1575
+ /**
1576
+ * Talk's recent turns, newest last. A read-only view: each entry reads the live turn and stays
1577
+ * the same object for as long as the turn is kept, so it may be held and compared by identity.
1578
+ */
1579
+ readonly turns: readonly TalkTurnView[];
1580
+ /** The turn whose reply the user cut off, if the latest cut was one. */
1581
+ readonly interruptedTurnId: string | null;
1582
+ /** Device time. */
1583
+ now(): number;
1584
+ /**
1585
+ * Speaks a host question as `turnId` (one of Talk's turns, or an id of the host's own): it counts
1586
+ * as spoken and asked, so no filler follows it and an answer never continues the request.
1587
+ */
1588
+ ask(turnId: string, text: string): void;
1589
+ /** Speaks a host sentence under its own id; nothing else changes. */
1590
+ say(id: string, text: string): void;
1591
+ /** Host state shown next to the snapshot changed: subscribers are told. */
1592
+ changed(): void;
1593
+ };
1594
+ /** A `now` send waits this long for the cancelled turn to end, then goes out anyway. */
1595
+ export declare const STEER_FALLBACK_END_TIMEOUT_MS = 5000;
1596
+ export type SteerFallbackOptions = {
1597
+ /** See {@link STEER_FALLBACK_END_TIMEOUT_MS}. */
1598
+ endTimeoutMs?: number;
1599
+ timers?: {
1600
+ setTimeout: (fn: () => void, ms: number) => unknown;
1601
+ clearTimeout: (handle: unknown) => void;
1602
+ };
1603
+ };
1604
+ /**
1605
+ * For a host whose agent cannot take a message into a running turn (no steer): a `now` send
1606
+ * cancels the running turn, waits for it to end (at most `endTimeoutMs`) and goes out as a new
1607
+ * message; a `fold` send is held until the running turn ends, then goes out as the next message.
1608
+ * Sends while no turn runs pass through. The wrapped port's events tell whether a turn runs, so
1609
+ * the session must be subscribed.
1610
+ *
1611
+ * Held words are never sent twice nor lost: a `now` send carries the held words it does not
1612
+ * already contain in front of its own; `cancelTurn` (a hush, a tap) drops them with the turn, as
1613
+ * an agent that steers would; the last unsubscribe drops them too. A dropped send resolves
1614
+ * `undefined`.
1615
+ */
1616
+ export declare function withSteerFallback(port: ConversationPort, options?: SteerFallbackOptions): ConversationPort;
1617
+ export declare const TALK_LANGUAGE_NOTICE = "I can't speak this language yet — I'll answer in the chat";
1618
+ /** The bare language of a code ("pt-BR" → "pt"). */
1619
+ export declare function baseLanguage(lang: string): string;
1620
+ /** True when Talk can speak the reply. An unknown language (null, `multi`) is assumed speakable. */
1621
+ export declare function isSpeakable(lang: string | null | undefined): boolean;
1622
+ /** Per device: the languages the user speaks with Talk, which it switches between. */
1623
+ export declare const TALK_SPEAK_LANGUAGES_KEY = "skaile:talk:speak-languages";
1624
+ /** The base languages Talk offers: the STT list without `multi` and regional variants. */
1625
+ export declare const TALK_SPEAKABLE_LANGUAGES: readonly SttLanguage[];
1626
+ /** Unset: the account's (or the device's) language plus English. */
1627
+ export declare function defaultTalkSpeakLanguages(locale: string | null | undefined): SttLanguage[];
1628
+ /** The stored set as written (JSON), else the default for `locale`. */
1629
+ export declare function parseTalkSpeakLanguages(raw: string | null | undefined, locale: string | null | undefined): SttLanguage[];
1630
+ /** Stores the set; an empty one is refused, since Talk needs at least one language. */
1631
+ export declare function writeTalkSpeakLanguages(storage: Pick<Storage, 'setItem'> | null, langs: readonly string[], storageKey?: string): boolean;
1632
+ /** The language after `current` in the set, wrapping; the first one when `current` is not in it. */
1633
+ export declare function nextTalkLanguage(langs: readonly SttLanguage[], current: string | null | undefined): SttLanguage | null;
1634
+ /** "DE" for the chip; the base part of whatever the stream runs in. */
1635
+ export declare function talkLanguageShort(lang: string | null | undefined): string;
1636
+ /** The language's own name ("Deutsch"), falling back to its code. */
1637
+ export declare function talkLanguageName(lang: SttLanguage): string;
1638
+ export declare function talkLanguagesStorage(): Storage | null;
1639
+ /**
1640
+ * How long the user waits in a Talk turn, from the end of their speech to the first audio of the
1641
+ * reply, split into stages: the end-of-turn decision (silence wait or eager send), the agent's
1642
+ * first token, the first sentence cut for speech, the speech model's first audio and the start of
1643
+ * playback. One record per turn, logged as the `turn.latency` Talk diagnostic event.
1644
+ *
1645
+ * Numbers and enum tokens only: no transcript, no reply text. Every stage time is in one
1646
+ * monotonic clock (`performance.now()` ms); the end of speech arrives in AudioContext seconds and
1647
+ * is converted with {@link audioTimeToMonotonicMs}. The p50 / p95 report over these records is `turn-latency-report.ts`.
1648
+ */
1649
+ /** Stages after the end-of-turn decision, in the order they normally happen. */
1650
+ export type TurnLatencyStage = 'firstToken' | 'cut' | 'ttsAudio' | 'playback';
1651
+ /**
1652
+ * `played`: the reply's first audio started. `interrupted`: a barge-in, a tap or a pause stopped
1653
+ * the turn before that. `replaced`: a newer send or reply took its place first (including a turn
1654
+ * whose reply was never spoken). `failed`: the send or the speech output failed. `ended`: the
1655
+ * conversation stopped first.
1656
+ */
1657
+ export type TurnLatencyOutcome = 'played' | 'interrupted' | 'replaced' | 'failed' | 'ended';
1658
+ /**
1659
+ * `answered`: the reply answers an eager send (sent before the end-of-utterance hold ended).
1660
+ * `replaced`: an eager send fired, but the utterance grew and the final send is the one answered.
1661
+ */
1662
+ export type TurnLatencyEager = 'none' | 'answered' | 'replaced';
1663
+ export type TurnLatencyStart = {
1664
+ /** The speak turn id the reply plays under; stage marks for any other turn are ignored. */
1665
+ turnId: string;
1666
+ /** The end of the user's last word, monotonic ms; null when unknown. */
1667
+ speechEndMs: number | null;
1668
+ /** When the end of the turn was decided (the utterance was handed over), monotonic ms. */
1669
+ decidedMs: number;
1670
+ eager: TurnLatencyEager;
1671
+ /** Sent into a running turn (a steer) rather than opening a new one. */
1672
+ steer: boolean;
1673
+ };
1674
+ export type TurnLatencyRecord = {
1675
+ /** End of speech → playback start: what the user waited. */
1676
+ totalMs: number | null;
1677
+ outcome: TurnLatencyOutcome;
1678
+ eager: TurnLatencyEager;
1679
+ steer: boolean;
1680
+ /** Whether the first audio came from the streaming speech model; null when no audio came. */
1681
+ realtime: boolean | null;
1682
+ /** End of speech → end-of-turn decision. */
1683
+ decideMs: number | null;
1684
+ /** Decision → the agent's first reply token (includes the send). */
1685
+ firstTokenMs: number | null;
1686
+ /** First token → the first sentence cut for speech. */
1687
+ cutMs: number | null;
1688
+ /** First cut → the speech model's first audio. */
1689
+ ttsMs: number | null;
1690
+ /** First audio → playback start. */
1691
+ playMs: number | null;
1692
+ };
1693
+ /**
1694
+ * An AudioContext time (seconds) as monotonic ms, given both clocks read at the same moment.
1695
+ * Both clocks run at the same rate, so the offset between them is enough.
1696
+ */
1697
+ export declare function audioTimeToMonotonicMs(audioSec: number, nowAudioSec: number, nowMs: number): number;
1698
+ type Marks = Partial<Record<TurnLatencyStage, number>>;
1699
+ /** The stage breakdown of one turn. A missing stage leaves its own span and the next one null. */
1700
+ export declare function turnLatencyRecord(start: TurnLatencyStart, marks: Marks, realtime: boolean | null, outcome: TurnLatencyOutcome): TurnLatencyRecord;
1701
+ /**
1702
+ * Holds the one turn the user is waiting on. A turn ends at its playback start, or when it is
1703
+ * interrupted, replaced by the next send or the conversation ends; each ends exactly once.
1704
+ */
1705
+ export declare class TurnLatencyRecorder {
1706
+ private readonly emit;
1707
+ private readonly nowMs;
1708
+ private pending;
1709
+ constructor(emit: (record: TurnLatencyRecord) => void, nowMs?: () => number);
1710
+ /** A send opened a new wait; one still open is reported as `replaced`. */
1711
+ start(start: Omit<TurnLatencyStart, 'decidedMs'> & {
1712
+ decidedMs?: number | null;
1713
+ }): void;
1714
+ /**
1715
+ * More words folded into the open turn before any of its reply played: the wait now runs from
1716
+ * their end. `afterEager` marks a turn opened by an eager send whose utterance grew.
1717
+ */
1718
+ extend(update: {
1719
+ speechEndMs?: number | null;
1720
+ decidedMs?: number | null;
1721
+ afterEager?: boolean;
1722
+ }): void;
1723
+ /** The first time a stage happens for the open turn; `playback` ends it as `played`. */
1724
+ mark(stage: TurnLatencyStage, turnId: string, atMs?: number, realtime?: boolean): void;
1725
+ /** Reports the open turn, if any, with what it reached so far; with `turnId`, only that turn. */
1726
+ finish(outcome: TurnLatencyOutcome, turnId?: string): void;
1727
+ }
1728
+ /** The acknowledgment fillers Talk plays when an answer looks like it will take a while. */
1729
+ type TalkFillers = {
1730
+ /** `restart`: the same request sent again whole; its filler count carries over. */
1731
+ utteranceEnded: (turnId: string, language: string | null, opts?: {
1732
+ restart?: boolean;
1733
+ }) => void;
1734
+ assistantText: () => void;
1735
+ cancel: () => void;
1736
+ /** A filler already played for the open request. */
1737
+ readonly fillerPlayed?: boolean;
1738
+ /** A tool started in the running turn (the agent's or a subagent's): the wait will be long. */
1739
+ toolStarted?: (name: string) => void;
1740
+ /** A tool returned; its duration may teach which tools are fast. */
1741
+ toolEnded?: (name: string) => void;
1742
+ };
1743
+ /**
1744
+ * The language a whole "sprich Englisch" / "switch to German" utterance asks for, else null.
1745
+ * `explicitOnly`: only a form with a verb, never a short one ("auf Englisch"), which may answer a
1746
+ * question.
1747
+ */
1748
+ export declare function talkLanguageCommand(text: string, { explicitOnly }?: {
1749
+ explicitOnly?: boolean | undefined;
1750
+ }): SttLanguage | null;
1751
+ type TalkSpeedCommand = 'faster' | 'slower' | 'normal';
1752
+ /** The speed command an utterance is made of, whole; anything more is a normal message. */
1753
+ export declare function talkSpeedCommand(text: string): TalkSpeedCommand | null;
1754
+ /** After a tap stops the reply, an utterance this soon steers the turn instead of the tap ending it. */
1755
+ export declare const TAP_CANCEL_GRACE_MS = 1500;
1756
+ /**
1757
+ * The user started speaking again within this long after a send: the words continue the same
1758
+ * request. Before any of the answer streamed they fold into the turn whenever they come; once
1759
+ * the answer started, only a continuation this soon (or after a sentence left unfinished) joins
1760
+ * the first half into one message.
1761
+ */
1762
+ export declare const CONTINUATION_MS = 2500;
1763
+ /** A continuation that began this soon after the answer became audible still joins the first half. */
1764
+ export declare const CONTINUATION_AFTER_HEARD_MS = 1000;
1765
+ /**
1766
+ * Longest reply text that may still be a note the agent wrote to itself between tool calls, or a
1767
+ * "let me check" repeating the filler Talk already played: such a segment is held back from
1768
+ * speech until it grows past this, the turn ends (spoken) or a tool call follows (dropped). A host
1769
+ * that hides such notes in its own chat view should use the same limit.
1770
+ */
1771
+ export declare const INTERNAL_NOTE_MAX_CHARS = 160;
1772
+ /** A first line after a filler longer than this is the answer, not a second "let me check". */
1773
+ export declare const FILLER_ECHO_MAX_CHARS = 80;
1774
+ /** A connection that drops this soon after the page came back (a frozen page's dead socket) reconnects by itself. */
1775
+ export declare const RECOVER_AFTER_RETURN_MS = 5000;
1776
+ /** Where a session keeps what it learns on the device (`localStorage`, or the host's own store). */
1777
+ export type TalkStorage = Pick<Storage, 'getItem' | 'setItem'>;
1778
+ /** The fillers Talk plays while the user waits for a slow answer ("Mhm...", "Hmm, let's see..."). */
1779
+ export type TalkFillerOptions = {
1780
+ /** Defaults to on. */
1781
+ enabled?: boolean;
1782
+ /** The phrases per language and kind; defaults to `ackPhrasesFor` / `longWaitPhrasesFor` (eight languages). */
1783
+ phrases?: (language: string | null, kind: FillerKind) => readonly string[];
1784
+ /**
1785
+ * The generated clips; pass one to share it across sessions. Defaults to a cache per session that
1786
+ * speaks each clip once through the transport's `speakClip`.
1787
+ */
1788
+ clips?: AckClipCache;
1789
+ /** How long tools take on this device; defaults to one kept in `storage`. */
1790
+ durations?: ToolDurations;
1791
+ };
1792
+ export type TalkOptions = {
1793
+ /** The host's conversation with its agent. */
1794
+ conversation: ConversationPort;
1795
+ /**
1796
+ * Either the transport to the host's voice relay (the session builds a `PipelineVoiceLayer` on the
1797
+ * browser's microphone and WebAudio), or a ready layer (a native layer, a test fake). With a layer,
1798
+ * `transport` is only used for the fillers' clips.
1799
+ */
1800
+ speech: SpeechTransport | {
1801
+ layer: VoiceLayer;
1802
+ transport?: SpeechTransport;
1803
+ };
1804
+ /** A host extension that speaks its own questions and may claim answers to them. */
1805
+ interceptor?: TalkInterceptor;
1806
+ /** The diagnostic log: lengths, ids and reasons only, never what was said. */
1807
+ diag?: TalkDiag;
1808
+ /** Where the home language and the tool durations are learned; none by default. */
1809
+ storage?: TalkStorage | null;
1810
+ /** The storage keys; the defaults keep what devices stored before. */
1811
+ storageKeys?: {
1812
+ languageHome?: Partial<LanguageHomeKeys>;
1813
+ toolDurations?: string;
1814
+ };
1815
+ voice?: {
1816
+ voiceId?: string | null;
1817
+ /** Speaking speed, 1 to 2 (`TALK_SPEEDS`). */
1818
+ speed?: number;
1819
+ /** The languages the user speaks; the stream switches only among these. */
1820
+ speakLanguages?: SttLanguage[];
1821
+ pinnedLanguage?: SttLanguage | null;
1822
+ /** The conversation's language; also the fillers' language when an utterance names none. */
1823
+ conversationLocale?: string | null;
1824
+ /** The language last spoken in this conversation: Talk stays in it across starts. */
1825
+ lastUtteranceLanguage?: string | null;
1826
+ /** `navigator.language`: the home language of last resort. */
1827
+ deviceLocale?: string | null;
1828
+ speechTerms?: readonly SpeechTerm[];
1829
+ };
1830
+ audio?: {
1831
+ mode?: TalkAudioMode;
1832
+ /** Real headphones: the user's voice may cut the reply before the words confirm it. */
1833
+ headphones?: boolean;
1834
+ pushToTalk?: boolean;
1835
+ /** Hush phrases interrupt over a phone speaker too. Defaults to on. */
1836
+ speakerHush?: boolean;
1837
+ /** Speak over the TTS stream socket, else clip by clip. Defaults to on. */
1838
+ realtimeTts?: boolean;
1839
+ /** Pause while the page is hidden (iPhone, where the OS mutes the mic there anyway). */
1840
+ pauseInBackground?: boolean;
1841
+ };
1842
+ /**
1843
+ * Fillers: options, `false` for none, or the host's own `TalkFillers` (it then feeds and plays
1844
+ * them itself; tool events still reach its `toolStarted` / `toolEnded`).
1845
+ */
1846
+ fillers?: false | TalkFillerOptions | TalkFillers;
1847
+ /** Spoken commands ("faster", "sprich Englisch"): applied by the session and never sent. Both default to on. */
1848
+ commands?: {
1849
+ speed?: boolean;
1850
+ language?: boolean;
1851
+ };
1852
+ /** The device tags of each turn latency record (the audio route can change mid-conversation). */
1853
+ latencyTags?: () => {
1854
+ platform: string;
1855
+ audioMode: string;
1856
+ };
1857
+ /** Browser seams; each defaults to the real browser, read when first used. */
1858
+ browser?: Partial<Pick<PipelineVoiceDeps, 'getUserMedia' | 'createAudioContext' | 'createCaptureNode'>> & {
1859
+ timers?: PipelineVoiceDeps['timers'];
1860
+ createId?: () => string;
1861
+ /** Device wall clock, ms. */
1862
+ now?: () => number;
1863
+ /** Monotonic ms (`performance.now()`), the clock the layer stamps its stages with. */
1864
+ nowMs?: () => number;
1865
+ /** Picks a filler phrase; defaults to `Math.random`. */
1866
+ random?: () => number;
1867
+ };
1868
+ };
1869
+ /** What a host may change while the session runs. */
1870
+ export type TalkSettings = {
1871
+ voiceId: string | null;
1872
+ speed: number;
1873
+ speakLanguages: SttLanguage[];
1874
+ /** Moves the speech recognition (and the replies) to this language now. */
1875
+ language: SttLanguage;
1876
+ languageContext: {
1877
+ pinned: SttLanguage | null;
1878
+ conversationLocale: string | null;
1879
+ };
1880
+ audioMode: TalkAudioMode;
1881
+ headphones: boolean;
1882
+ pushToTalk: boolean;
1883
+ speechTerms: readonly SpeechTerm[];
1884
+ };
1885
+ export type TalkEvents = {
1886
+ utterance: (u: TalkUtterance) => void;
1887
+ bargeIn: (b: TalkBargeIn) => void;
1888
+ dropped: (b: TalkBargeIn) => void;
1889
+ language: (language: string, speakable: boolean) => void;
1890
+ replyStage: (stage: TalkReplyStage) => void;
1891
+ /** A spoken speed command was applied; `speed` is the new rate (persist it if you keep one). */
1892
+ speed: (command: TalkSpeedCommand, speed: number) => void;
1893
+ /** A spoken language command moved the conversation to `language`. */
1894
+ languageCommand: (language: SttLanguage) => void;
1895
+ turnLatency: (record: TurnLatencyRecord) => void;
1896
+ };
1897
+ /** A running Talk conversation: state for the host's UI, and the controls it offers. */
1898
+ export type TalkSession = {
1899
+ /** Replaced on every change. */
1900
+ readonly state: TalkSnapshot;
1901
+ /** Called on every change of `state` (and when the interceptor reports host state changed). */
1902
+ subscribe(listener: () => void): () => void;
1903
+ on<E extends keyof TalkEvents>(event: E, listener: TalkEvents[E]): () => void;
1904
+ /** Opens the mic and the speech stream; rejects when the mic cannot open. */
1905
+ start(): Promise<void>;
1906
+ /** Hangs up; `start` may follow. A reply cut by it is marked as heard so far. */
1907
+ stop(): void;
1908
+ /** Stops and removes every listener it added, on the layer too; the session is not used again. */
1909
+ dispose(): void;
1910
+ /** Closes the mic, keeps the conversation (a media-controls pause); `resume` lifts it. */
1911
+ muteMic(): void;
1912
+ /** Back to listening; false when the mic could not reopen (a tap retries, with its gesture). */
1913
+ resume(): Promise<boolean>;
1914
+ pageHidden(): void;
1915
+ /** The page is back: reopens what the browser took meanwhile. */
1916
+ pageVisible(): Promise<boolean>;
1917
+ /** Stops the reply like a spoken barge-in; the running turn ends unless the user speaks soon. */
1918
+ tapInterrupt(): void;
1919
+ pressTalk(): void;
1920
+ releaseTalk(): void;
1921
+ /** A message the host sent another way (typed) while Talk runs: its reply is spoken. */
1922
+ expectReplyToTypedSend(sent: Promise<string | undefined>): void;
1923
+ set(settings: Partial<TalkSettings>): void;
1924
+ /** The current speaking speed. */
1925
+ readonly speed: number;
1926
+ /** The raw mic and playback levels (RMS); `TalkLevelCalibration` maps them to 0..1 for a visual. */
1927
+ readonly levels: VoiceLayer['levels'];
1928
+ /** The voice layer underneath, for what the session does not wrap. */
1929
+ readonly layer: VoiceLayer;
1930
+ };
1931
+ /**
1932
+ * Starts a Talk conversation: full-duplex voice with the host's agent. The session decides what to
1933
+ * send for each utterance (eagerly, folded into the running turn, or restarting it), speaks the
1934
+ * reply as it streams, marks what the user heard of a reply they cut off, plays fillers while a
1935
+ * slow answer is on its way, and applies spoken speed and language commands. It ships state and
1936
+ * events only; the host draws the UI.
1937
+ */
1938
+ export declare function createTalk(options: TalkOptions): TalkSession;
1939
+ /** One word for what the conversation is doing, for a host's orb or label. */
1940
+ export type TalkPhase = 'idle' | 'listening' | 'userSpeaking' | 'thinking' | 'speaking' | 'paused' | 'error';
1941
+ /** The phase a snapshot shows: not active, paused, failed, speaking, hearing the user, waiting, else listening. */
1942
+ export declare function talkPhase(state: TalkSnapshot): TalkPhase;
1943
+ /**
1944
+ * A text stream Talk hands to `VoiceLayer.speak` while the reply is still arriving: pushed
1945
+ * chunks are yielded in order, `end()` finishes the iteration.
1946
+ */
1947
+ export declare class TextFeed implements AsyncIterable<string> {
1948
+ private readonly chunks;
1949
+ private ended;
1950
+ private wake;
1951
+ push(chunk: string): void;
1952
+ end(): void;
1953
+ [Symbol.asyncIterator](): AsyncIterator<string>;
1954
+ }
1955
+ /**
1956
+ * How the final transcript of an utterance relates to what its eager send already carried:
1957
+ * `same` when only punctuation or case differ (STT adds the full stop at the end), `more` with
1958
+ * the words said after it when the final starts with the eager's words, else `other`.
1959
+ */
1960
+ export declare function finalAfterEager(eager: string, final: string): {
1961
+ kind: 'same';
1962
+ } | {
1963
+ kind: 'more';
1964
+ rest: string;
1965
+ } | {
1966
+ kind: 'other';
1967
+ };
1968
+ /** Talk's speaking speeds, slowest first; the chip and the voice commands step through them. */
1969
+ export declare const TALK_SPEEDS: readonly [1, 1.25, 1.5, 1.75, 2];
1970
+ export type TalkSpeed = (typeof TALK_SPEEDS)[number];
1971
+ export declare const DEFAULT_TALK_SPEED: TalkSpeed;
1972
+ /** Per device: what every Talk start resets the speed to. */
1973
+ export declare const TALK_DEFAULT_SPEED_KEY = "skaile:talk:default-speed";
1974
+ export declare function isTalkSpeed(rate: number): rate is TalkSpeed;
1975
+ /** The next speed up, wrapping from the fastest back to normal (the chip's cycle). */
1976
+ export declare function nextTalkSpeed(rate: number): TalkSpeed;
1977
+ /** A spoken "faster" / "slower" / "normal": one step up or down, held at the ends; normal is 1. */
1978
+ export declare function talkSpeedAfter(command: 'faster' | 'slower' | 'normal', rate: number): TalkSpeed;
1979
+ /** "1×", "1.25×". */
1980
+ export declare function talkSpeedLabel(rate: number): string;
1981
+ export declare function talkSpeedStorage(): Storage | null;
1982
+ export declare function readDefaultTalkSpeed(storage: Pick<Storage, 'getItem'> | null, storageKey?: string): TalkSpeed;
1983
+ export declare function writeDefaultTalkSpeed(storage: Pick<Storage, 'setItem'> | null, rate: number, storageKey?: string): void;
1984
+ /**
1985
+ * Pitch-preserving speed change for Talk's speech (WSOLA: windowed overlap-add with a waveform
1986
+ * similarity search). Talk plays through WebAudio, where `playbackRate` on a buffer source also
1987
+ * raises the pitch, so the speech is time-stretched before it is scheduled and plays at rate 1.
1988
+ * A reply arrives in many small pieces; {@link StreamingTimeStretch} carries its state from one
1989
+ * piece to the next, so the pieces join as one continuous signal instead of each starting and
1990
+ * ending on a faded, misaligned frame. Pure and DOM-free.
1991
+ */
1992
+ export declare const MIN_PLAYBACK_RATE = 0.5;
1993
+ export declare const MAX_PLAYBACK_RATE = 2;
1994
+ export declare function clampPlaybackRate(rate: number): number;
1995
+ /**
1996
+ * One continuous stretch over audio pushed piece by piece. `push` returns the output that is
1997
+ * final so far; about one frame (30 ms) and the search window stay held back, because the next
1998
+ * piece's frames overlap them. `flush` ends the stream: it returns the held-back rest, so the
1999
+ * total comes to about `input / rate` samples, and the next `push` starts afresh.
2000
+ */
2001
+ export declare class StreamingTimeStretch {
2002
+ readonly sampleRate: number;
2003
+ readonly rate: number;
2004
+ private readonly frame;
2005
+ private readonly hopOut;
2006
+ private readonly hopIn;
2007
+ private readonly search;
2008
+ private readonly window;
2009
+ /** Input from absolute sample `base` on; what lies before it is no longer read. */
2010
+ private input;
2011
+ private base;
2012
+ private total;
2013
+ /** The next frame's index, and where the previous frame's natural continuation starts. */
2014
+ private k;
2015
+ private follow;
2016
+ /** Overlap-add of the frames from output sample `k * hopOut` on, not final yet. */
2017
+ private acc;
2018
+ private norm;
2019
+ private emitted;
2020
+ constructor(rate: number, sampleRate: number);
2021
+ /** Samples pushed since the last flush. */
2022
+ get pushed(): number;
2023
+ push(samples: Float32Array): Float32Array;
2024
+ flush(): Float32Array;
2025
+ private reset;
2026
+ private append;
2027
+ private at;
2028
+ /** Places frame `k`, the input clamped to `limit` samples, and emits the samples now final. */
2029
+ private place;
2030
+ /** Drops input no later frame or search can reach. */
2031
+ private trim;
2032
+ }
2033
+ /**
2034
+ * `input` played `rate` times as fast at the same pitch: about `input.length / rate` samples.
2035
+ * Rate 1, or a clip shorter than two analysis frames, comes back unchanged.
2036
+ */
2037
+ export declare function timeStretch(input: Float32Array, rate: number, sampleRate: number): Float32Array;
2038
+ /** The log message the backend writes for a `turn.latency` event (`talk <event>`). */
2039
+ export declare const TURN_LATENCY_MESSAGE = "talk turn.latency";
2040
+ /** One parsed `turn.latency` log row: the record plus the device tags it was logged with. */
2041
+ export type TurnLatencyRow = Partial<TurnLatencyRecord> & {
2042
+ platform?: string;
2043
+ audioMode?: string;
2044
+ };
2045
+ export type TurnLatencySummary = {
2046
+ platform: string;
2047
+ /** Rows of this platform, all outcomes. */
2048
+ turns: number;
2049
+ /** Rows that reached playback: the ones the percentiles are over. */
2050
+ played: number;
2051
+ stages: Record<'decideMs' | 'firstTokenMs' | 'cutMs' | 'ttsMs' | 'playMs' | 'totalMs', {
2052
+ n: number;
2053
+ p50: number | null;
2054
+ p95: number | null;
2055
+ }>;
2056
+ };
2057
+ /** Nearest-rank percentile of an ascending list; null when empty. */
2058
+ export declare function percentile(sorted: readonly number[], p: number): number | null;
2059
+ /** p50 / p95 per platform over the played turns; platforms sorted by name. */
2060
+ export declare function summarizeTurnLatency(rows: readonly TurnLatencyRow[]): TurnLatencySummary[];
2061
+ /**
2062
+ * The `turn.latency` rows of a log dump: one JSON array, or NDJSON (one
2063
+ * entry per line, as `--tail` prints). Other entries and unreadable lines are skipped.
2064
+ */
2065
+ export declare function turnLatencyRowsFromLog(text: string): TurnLatencyRow[];
2066
+ /**
2067
+ * The fast barge-in trigger: the user's voice rising above the room, seen on the mic level long
2068
+ * before the STT socket returns two words (one to three seconds). It only mutes the reply; the
2069
+ * words still decide, through the echo filter, whether it was a barge-in (`judgeDuringPlayback`).
2070
+ */
2071
+ /** How far above the learned noise threshold (raw RMS) a frame must be to count as voice. */
2072
+ export declare const VAD_ONSET_EXCESS = 0.02;
2073
+ /** Voice this long without a dip mutes the reply: shorter than a word, longer than a click. */
2074
+ export declare const VAD_ONSET_MS = 200;
2075
+ /** Words must confirm the barge-in within this time, or the reply is heard again. */
2076
+ export declare const VAD_CONFIRM_MS = 1500;
2077
+ /** Ramp of the mute and of the release, so neither clicks. */
2078
+ export declare const VAD_RAMP_SECONDS = 0.015;
2079
+ /**
2080
+ * Only over real headphones (the toggle or detection, not a desktop speaker that merely counts as
2081
+ * headphones mode): there the reply cannot reach the mic, so a rise in level is the user. Over
2082
+ * any speaker the echo would trigger it, and barge-in stays word-confirmed.
2083
+ */
2084
+ export declare function vadBargeInAllowed(input: {
2085
+ audioMode: TalkAudioMode;
2086
+ headphones: boolean;
2087
+ pushToTalk: boolean;
2088
+ micMuted: boolean;
2089
+ /** Reply audio is playing right now, not only queued. */
2090
+ audible: boolean;
2091
+ /** The open utterance already barged in, or the reply is already muted for it. */
2092
+ alreadyStopped: boolean;
2093
+ }): boolean;
2094
+ /** Fires once per stretch of voice: `VAD_ONSET_MS` of frames above the noise threshold. */
2095
+ export declare class SpeechOnsetDetector {
2096
+ private readonly gate;
2097
+ private aboveMs;
2098
+ private fired;
2099
+ /** Feeds one frame's raw level (0..1) lasting `frameMs`; true on the frame the onset is reached. */
2100
+ next(level: number, frameMs: number): boolean;
2101
+ }
2102
+ export type { TalkFillers, TalkSpeedCommand };