@yaks/speech 0.0.0-stage → 0.2.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/mod.js ADDED
@@ -0,0 +1,1113 @@
1
+ // Speech to text, text to speech, and speech to speech. A provider is data:
2
+ // where it answers, which models hear and speak, what each costs, and how its
3
+ // requests and streams are worded, all in its own entry (deepgram.ts,
4
+ // openai.ts, elevenlabs.ts). One implementation here calls any provider
5
+ // described so; the key is an argument, and nothing here reads the
6
+ // environment.
7
+ export { DEEPGRAM } from "./deepgram.js";
8
+ export { ELEVENLABS } from "./elevenlabs.js";
9
+ export { OPENAI, openaiLiveBackend } from "./openai.js";
10
+ export { base64, mulawed, mulawOf, muted, sounds, trimmed, unbase64 } from "./audio.js";
11
+ export { query } from "./query.js";
12
+ export { speechFrom } from "./speech-from.js";
13
+ import { message } from "@yaks/model";
14
+ import { system } from "@yaks/fp";
15
+ import { muted, sounds, trimmed } from "./audio.js";
16
+ /** `speed` as near as `speeds` allows.
17
+ *
18
+ * ```ts
19
+ * import { equal } from '@yaks/testing'
20
+ * equal(paced({ min: 0.7, max: 1.5 }, 1.3), 1.3)
21
+ * equal(paced({ min: 0.25, max: 1.5 }, 2), 1.5)
22
+ * ```
23
+ */ export let paced = ({ min, max }, speed = 1)=>Math.min(max, Math.max(min, speed));
24
+ /** A spoken line as prose. Apply after assembling transcript fragments,
25
+ * which can split words and directions as well as sentences. */ export let spokenProse = (text)=>text.replace(/(?:[ \t]*\[[^[\]\r\n]+\])+[ \t]*([,.;:!?])?/g, (_, punctuation)=>punctuation ?? ' ').replace(/((?:[\p{L}\p{N}]{2}\.|[!?])["”’]?)(?=\p{Lu})/gu, '$1 ').trim();
26
+ /** A multipart request with an audio file, including recordings read as a stream. */ export let audioForm = (fields, audio, type)=>{
27
+ if (!(audio instanceof ReadableStream)) {
28
+ let body = new FormData();
29
+ for (let [name, value] of Object.entries(fields))body.set(name, value);
30
+ body.set('file', new Blob([
31
+ audio
32
+ ], {
33
+ type
34
+ }), 'audio');
35
+ return {
36
+ method: 'POST',
37
+ body
38
+ };
39
+ }
40
+ let boundary = crypto.randomUUID();
41
+ let encode = new TextEncoder();
42
+ let parts = Object.entries(fields).map(([name, value])=>`--${boundary}\r\nContent-Disposition: form-data; name="${name}"\r\n\r\n${value}\r\n`).join('');
43
+ let media = new Blob([], {
44
+ type
45
+ }).type || 'application/octet-stream';
46
+ let header = parts + `--${boundary}\r\n` + 'Content-Disposition: form-data; name="file"; filename="audio"\r\n' + `Content-Type: ${media}\r\n\r\n`;
47
+ let reader = audio.getReader();
48
+ let body = new ReadableStream({
49
+ start: (out)=>out.enqueue(encode.encode(header)),
50
+ pull: async (out)=>{
51
+ let next = await reader.read();
52
+ if (!next.done) out.enqueue(next.value);
53
+ else {
54
+ out.enqueue(encode.encode(`\r\n--${boundary}--\r\n`));
55
+ out.close();
56
+ }
57
+ },
58
+ cancel: (reason)=>reader.cancel(reason)
59
+ });
60
+ return {
61
+ method: 'POST',
62
+ headers: {
63
+ 'content-type': `multipart/form-data; boundary=${boundary}`
64
+ },
65
+ body
66
+ };
67
+ };
68
+ /**
69
+ * The model of `provider`'s that speaks as `model` asks: that one where it
70
+ * has it, else its first.
71
+ *
72
+ * ```ts
73
+ * import { equal } from '@yaks/testing'
74
+ * import { ELEVENLABS, speakerOf } from '@yaks/speech'
75
+ * equal(speakerOf(ELEVENLABS, 'eleven_flash_v2_5').perThousand, 0.04)
76
+ * equal(speakerOf(ELEVENLABS, 'aura-2').model, 'eleven_v4')
77
+ * ```
78
+ */ export let speakerOf = (provider, model)=>provider.speak.models.find((m)=>m.model == model) ?? provider.speak.models[0];
79
+ /** The entry of `provider`'s that streams with `model`, or its first when
80
+ * none is given.
81
+ *
82
+ * ```ts
83
+ * import { equal } from '@yaks/testing'
84
+ * import { DEEPGRAM, streamOf } from '@yaks/speech'
85
+ * equal(streamOf(DEEPGRAM).model, 'flux-general-en')
86
+ * equal(streamOf(DEEPGRAM, 'nova-3').speakers, true)
87
+ * ```
88
+ */ export let streamOf = (provider, model)=>{
89
+ let s = model == undefined ? provider.turns[0] : provider.turns.find((t)=>t.model == model);
90
+ if (!s) throw new Error(`${provider.name} streams no model ${model}`);
91
+ return s;
92
+ };
93
+ let MEDIA = {
94
+ mp3: 'audio/mpeg',
95
+ mulaw: 'audio/basic',
96
+ linear16: 'audio/L16'
97
+ };
98
+ /** The bytes a second of raw audio takes, or undefined for a compressed one. */ export let perSecond = (format)=>format.encoding == 'mulaw' ? format.rate : format.encoding == 'linear16' ? format.rate * 2 : undefined;
99
+ /** What speaking `text` costs, in dollars, by `model` (`speakerOf`). */ export let spoken = (provider, text, model)=>text.length / 1000 * speakerOf(provider, model).perThousand;
100
+ /** What hearing `seconds` of audio costs, in dollars, on a model priced by
101
+ * the minute: a provider's `hear`, or one of its `turns`. */ export let heard = (priced, seconds)=>seconds / 60 * priced.perMinute;
102
+ /** A provider's refusal: `status` is its HTTP status, and `retry` says a
103
+ * later try may go through (a 429 or 5xx, or no answer at all). */ export class SpeechError extends Error {
104
+ status;
105
+ retry;
106
+ constructor(message, status = 0){
107
+ super(message);
108
+ this.name = 'SpeechError';
109
+ this.status = status;
110
+ this.retry = status == 0 || status == 429 || status >= 500;
111
+ }
112
+ }
113
+ /** The provider's API, asked with the key; a refusal is a SpeechError. */ export let asking = ({ provider, key, fetch: given, signal })=>async (path, init = {})=>{
114
+ let response;
115
+ try {
116
+ response = await (given ?? globalThis.fetch)(provider.api + path, {
117
+ ...init,
118
+ signal,
119
+ headers: {
120
+ [provider.header ?? 'authorization']: provider.authorization(key),
121
+ ...init.headers
122
+ }
123
+ });
124
+ } catch (error) {
125
+ if (signal?.aborted) throw error;
126
+ throw new SpeechError(`${provider.name} could not be reached: ${error}`);
127
+ }
128
+ if (response.ok) return response;
129
+ let said = await response.text().catch(()=>'');
130
+ throw new SpeechError(`${provider.name} answered ${response.status} to ${path.split('?')[0]}: ${said.slice(0, 300) || 'no reason given'}`, response.status);
131
+ };
132
+ /**
133
+ * `text` spoken: the audio as it streams from the provider, its media type,
134
+ * and what it cost. Raw samples come without a container, ready for a call.
135
+ *
136
+ * ```ts
137
+ * import { equal } from '@yaks/testing'
138
+ * import { DEEPGRAM, speak } from '@yaks/speech'
139
+ * let asked: string[] = []
140
+ * let fetch = (url: string | URL | Request) => {
141
+ * asked.push(String(url))
142
+ * return Promise.resolve(new Response(new Uint8Array([1, 2, 3])))
143
+ * }
144
+ * let said = await speak({
145
+ * provider: DEEPGRAM,
146
+ * key: 'k',
147
+ * text: 'Hello',
148
+ * format: { encoding: 'mulaw', rate: 8000 },
149
+ * fetch: fetch as typeof globalThis.fetch,
150
+ * })
151
+ * equal(said.type, 'audio/basic')
152
+ * equal(asked[0].includes('container=none'), true)
153
+ * ```
154
+ */ export let speak = async (o)=>{
155
+ let format = o.format ?? {
156
+ encoding: 'mp3'
157
+ };
158
+ let { speak } = o.provider;
159
+ let { path, init } = speak.request(o.text, o.voice ?? speak.voice, format, paced(speak.speeds, o.speed), speakerOf(o.provider, o.model).model);
160
+ let response = await asking(o)(path, init);
161
+ if (!response.body) {
162
+ throw new SpeechError(`${o.provider.name} returned no audio`, 502);
163
+ }
164
+ let audio = speak.audio?.(format);
165
+ let body = audio ? response.body.pipeThrough(audio) : response.body;
166
+ return {
167
+ // A call's sentences are each a clip: none pauses for the provider's
168
+ // padding around it (`trimmed`).
169
+ body: format.encoding == 'mulaw' ? body.pipeThrough(trimmed(format.rate)) : body,
170
+ type: MEDIA[format.encoding],
171
+ dollars: spoken(o.provider, o.text, o.model)
172
+ };
173
+ };
174
+ // What a provider that tells no speakers apart heard: one speaker's turn.
175
+ let alone = (text)=>text ? [
176
+ {
177
+ speaker: 0,
178
+ text
179
+ }
180
+ ] : [];
181
+ /**
182
+ * A recording heard whole: its words, its turns, how long it was, and what
183
+ * hearing it cost. A provider that tells speakers apart (`speakers`) answers
184
+ * a turn each time one of them speaks; one that cannot, the words as one
185
+ * speaker's.
186
+ *
187
+ * ```ts
188
+ * import { equal } from '@yaks/testing'
189
+ * import { hear, OPENAI } from '@yaks/speech'
190
+ * let fetch = () =>
191
+ * Promise.resolve(Response.json({ text: 'Hi there', usage: { seconds: 30 } }))
192
+ * let got = await hear({
193
+ * provider: OPENAI,
194
+ * key: 'k',
195
+ * audio: new Uint8Array([1]),
196
+ * type: 'audio/wav',
197
+ * fetch: fetch as typeof globalThis.fetch,
198
+ * })
199
+ * equal(got.turns, [{ speaker: 0, text: 'Hi there' }])
200
+ * equal(got.dollars, 0.00225)
201
+ * ```
202
+ */ export let hear = async (o)=>{
203
+ let { hear } = o.provider;
204
+ let { path, init } = hear.request(o.audio, o.type, hear.model);
205
+ let said = hear.read(await (await asking(o)(path, init)).json());
206
+ let seconds = said.seconds ?? o.seconds ?? 0;
207
+ return {
208
+ text: said.text,
209
+ turns: said.turns ?? alone(said.text),
210
+ seconds,
211
+ dollars: heard(hear, seconds)
212
+ };
213
+ };
214
+ /** The account's credit left, in dollars, or undefined where the provider
215
+ * does not say. */ export let balance = (o)=>o.provider.balance?.(asking(o)) ?? Promise.resolve(undefined);
216
+ // The most pages of voices read: 2,000 voices at 100 a page.
217
+ let PAGES = 20;
218
+ /**
219
+ * The voices the key's account speaks in, where the provider keeps them per
220
+ * account (ElevenLabs: its premade voices and the ones it designed, cloned or
221
+ * added), else the provider's own list.
222
+ *
223
+ * ```ts
224
+ * import { equal } from '@yaks/testing'
225
+ * import { DEEPGRAM, ELEVENLABS, voices } from '@yaks/speech'
226
+ * let pages = [
227
+ * { voices: [{ voice_id: 'a', name: 'A' }], has_more: true, next_page_token: 't' },
228
+ * { voices: [{ voice_id: 'b', name: 'B' }], has_more: false },
229
+ * ]
230
+ * let asked: string[] = []
231
+ * let fetch = (url: string | URL | Request, init?: RequestInit) => {
232
+ * asked.push(String(url) + ' ' + new Headers(init?.headers).get('xi-api-key'))
233
+ * return Promise.resolve(Response.json(pages.shift()))
234
+ * }
235
+ * let got = await voices({
236
+ * provider: ELEVENLABS,
237
+ * key: 'k',
238
+ * fetch: fetch as typeof globalThis.fetch,
239
+ * })
240
+ * equal(got.map((v) => v.id), ['a', 'b'])
241
+ * equal(asked[1].includes('next_page_token=t'), true)
242
+ * equal(asked[1].endsWith(' k'), true)
243
+ * equal((await voices({ provider: DEEPGRAM, key: 'k' })).length > 0, true)
244
+ * ```
245
+ */ export let voices = async (o)=>{
246
+ let listed = o.provider.voices;
247
+ if (!listed) return o.provider.speak.voices;
248
+ let ask = asking(o), all = [], page;
249
+ for(let n = 0; n < PAGES; n++){
250
+ let { path, init } = listed.request(page);
251
+ let got = listed.read(await (await ask(path, init)).json());
252
+ all.push(...got.voices);
253
+ if (!(page = got.next)) break;
254
+ }
255
+ return all;
256
+ };
257
+ // What makes voices on `provider`, refused where it makes none.
258
+ let maker = (provider)=>{
259
+ if (!provider.make) {
260
+ throw new SpeechError(`${provider.title} makes no voices of its own`, 400);
261
+ }
262
+ return provider.make;
263
+ };
264
+ /**
265
+ * Voices designed from `description`, each a sample saying `text` (or words
266
+ * the provider picks), for one to be kept with `keep`.
267
+ *
268
+ * ```ts
269
+ * import { equal } from '@yaks/testing'
270
+ * import { design, ELEVENLABS } from '@yaks/speech'
271
+ * let fetch = () =>
272
+ * Promise.resolve(Response.json({
273
+ * previews: [{ generated_voice_id: 'g1', audio_base_64: 'AQID', duration_secs: 4 }],
274
+ * }))
275
+ * let got = await design({
276
+ * provider: ELEVENLABS,
277
+ * key: 'k',
278
+ * description: 'An old sea captain, gravelly and warm',
279
+ * fetch: fetch as typeof globalThis.fetch,
280
+ * })
281
+ * equal(got, [{ id: 'g1', audio: new Uint8Array([1, 2, 3]), type: 'audio/mpeg', seconds: 4 }])
282
+ * ```
283
+ */ export let design = async (o)=>{
284
+ let make = maker(o.provider);
285
+ let { path, init } = make.design(o.description, o.text);
286
+ return make.designs(await (await asking(o)(path, init)).json());
287
+ };
288
+ /** A design (`design`) kept as a voice of the account's, answering its id. */ export let keep = async (o)=>{
289
+ let make = maker(o.provider);
290
+ let { path, init } = make.keep(o.design, o.name, o.description);
291
+ return make.made(await (await asking(o)(path, init)).json());
292
+ };
293
+ /**
294
+ * A voice cloned from recordings of it, answering its id. A provider refuses
295
+ * one the account's plan does not allow, with its reason.
296
+ *
297
+ * ```ts
298
+ * import { equal } from '@yaks/testing'
299
+ * import { clone, ELEVENLABS } from '@yaks/speech'
300
+ * let sent: FormData | undefined
301
+ * let fetch = (_: unknown, init?: RequestInit) => {
302
+ * sent = init?.body as FormData
303
+ * return Promise.resolve(Response.json({ voice_id: 'v9' }))
304
+ * }
305
+ * let id = await clone({
306
+ * provider: ELEVENLABS,
307
+ * key: 'k',
308
+ * name: 'Narrator',
309
+ * samples: [new Blob([new Uint8Array([1])], { type: 'audio/mpeg' })],
310
+ * fetch: fetch as typeof globalThis.fetch,
311
+ * })
312
+ * equal([id, sent?.get('name'), sent?.getAll('files').length], ['v9', 'Narrator', 1])
313
+ * ```
314
+ */ export let clone = async (o)=>{
315
+ let make = maker(o.provider);
316
+ let { path, init } = make.clone(o.name, o.samples, o.description);
317
+ return make.made(await (await asking(o)(path, init)).json());
318
+ };
319
+ let browser = (url, { protocols })=>new WebSocket(url, protocols);
320
+ // A socket to `url` that holds what is sent until it opens, sends `opening`
321
+ // first, and says once if it fails or closes before `close` or `end` is
322
+ // asked. `end` sends `last` and waits for the other side to close, its
323
+ // messages heard until then.
324
+ let stream = (o, url, opening, heard, lost)=>{
325
+ let socket = (o.open ?? browser)(url, {
326
+ authorization: o.provider.authorization(o.key),
327
+ protocols: o.provider.protocols(o.key)
328
+ });
329
+ let ready = false, closing = false;
330
+ let waiting = [
331
+ ...opening
332
+ ];
333
+ let shut;
334
+ let gone = new Promise((resolve)=>shut = resolve);
335
+ socket.addEventListener('open', ()=>{
336
+ ready = true;
337
+ for (let part of waiting.splice(0))socket.send(part);
338
+ });
339
+ socket.addEventListener('message', (event)=>heard(event.data));
340
+ let dropped = (reason)=>(event)=>{
341
+ if (!closing) lost(reason, event?.code == 1000 || event?.code == 1001);
342
+ closing = true;
343
+ shut();
344
+ };
345
+ socket.addEventListener('close', dropped('the stream closed'));
346
+ socket.addEventListener('error', dropped('the stream failed'));
347
+ let close = (last)=>{
348
+ if (closing) return;
349
+ closing = true;
350
+ try {
351
+ if (ready && last) socket.send(last);
352
+ socket.close(1000);
353
+ } catch {
354
+ // A socket already gone has nothing more to close.
355
+ }
356
+ shut();
357
+ };
358
+ return {
359
+ closed: ()=>closing,
360
+ send: (data)=>{
361
+ if (closing) return;
362
+ if (ready) socket.send(data);
363
+ else waiting.push(data);
364
+ },
365
+ close,
366
+ end: (last)=>{
367
+ if (closing) return gone;
368
+ closing = true;
369
+ if (ready) socket.send(last);
370
+ else waiting.push(last);
371
+ return gone;
372
+ }
373
+ };
374
+ };
375
+ /**
376
+ * Audio heard as it streams, told back a turn at a time (`told`), by
377
+ * `model`, one of the provider's `turns` (its first by default). `send`
378
+ * takes raw samples in `format`; `close` ends the stream and answers how
379
+ * many seconds were heard and what they cost, and `end` answers the same
380
+ * once the provider has told the turns it was still hearing. `open` makes
381
+ * the socket, the platform's WebSocket by default, offering the key as
382
+ * subprotocols.
383
+ */ export let turns = (o)=>{
384
+ let t = streamOf(o.provider, o.model);
385
+ let read = t.reader();
386
+ let bytes = 0;
387
+ let s = stream(o, o.provider.live + t.path(o.format, t.model), t.opening(o.format, t.model), (data)=>{
388
+ let cue = read(data);
389
+ if (cue.start) o.told.start?.();
390
+ if (cue.hearing) o.told.hearing?.(cue.hearing.text, cue.hearing.key);
391
+ for (let turn of cue.ended ?? []){
392
+ if (turn.text) o.told.end(turn);
393
+ else o.told.hearing?.('', turn.key);
394
+ }
395
+ if (cue.error) o.told.lost?.(cue.error);
396
+ }, (reason)=>o.told.lost?.(reason));
397
+ let spent = ()=>{
398
+ let seconds = bytes / perSecond(o.format);
399
+ return {
400
+ seconds,
401
+ dollars: heard(t, seconds)
402
+ };
403
+ };
404
+ return {
405
+ send: (audio)=>{
406
+ if (s.closed()) return;
407
+ bytes += audio.length;
408
+ s.send(t.audio(audio));
409
+ },
410
+ spent,
411
+ close: ()=>{
412
+ s.close(t.closing);
413
+ return spent();
414
+ },
415
+ end: async ()=>{
416
+ if (t.closing) await s.end(t.closing);
417
+ else s.close();
418
+ return spent();
419
+ }
420
+ };
421
+ };
422
+ let wording = (words, from = 'the system')=>message({
423
+ kind: 'user',
424
+ text: typeof words == 'string' ? words : words.text
425
+ }, typeof words == 'string' ? from : words.from).text;
426
+ // What a caller says to show they are listening, not to be heard: a sound
427
+ // of these alone, while the model speaks, lets it go on.
428
+ let FILLERS = new Set('ah aha alright cool fine good gotcha great ha haha hm hmm huh mhm mm mmhm nice oh ok okay right sure uh uhhuh um wow yeah yep yes yup'.split(' '));
429
+ // The words a sentence goes on after: articles, prepositions, conjunctions,
430
+ // possessives, "is", and the fillers of a caller thinking.
431
+ let ON = new Set('a an the to of for with from into at by and or but because if my your our their is ah er hm hmm mm uh um'.split(' '));
432
+ let words = (text)=>text.toLowerCase().split(/\s+/).map((w)=>w.replace(/[^a-z]/g, '')).filter(Boolean);
433
+ /** Whether `text` holds a word a transcript may have made of `name`, which
434
+ * it mishears even when told to expect it: one of the same letters where
435
+ * `name` has consonants, and any vowels where it has vowels ("Amber" for
436
+ * "Ember"). A name of fewer than three consonants sounds like too many words
437
+ * to be told apart this way.
438
+ *
439
+ * ```ts
440
+ * import { equal } from '@yaks/testing'
441
+ * import { heardAs } from '@yaks/speech'
442
+ * let heard = ['Thanks, Amber.', 'ember, you there?', 'remember the barn',
443
+ * 'Embers']
444
+ * equal(heard.map((t) => heardAs(t, 'Ember')), [true, true, false, false])
445
+ * equal(heardAs('Eve said so', 'Ava'), false)
446
+ * ```
447
+ */ export let heardAs = (text, name)=>{
448
+ let shape = (w)=>w.replace(/[aeiouy]/g, '_');
449
+ let want = shape(words(name).join(''));
450
+ return want.replaceAll('_', '').length >= 3 && words(text).some((w)=>shape(w) == want);
451
+ };
452
+ /** How many of `text`'s words say something, the `FILLERS` aside.
453
+ *
454
+ * ```ts
455
+ * import { equal } from '@yaks/testing'
456
+ * import { meant } from '@yaks/speech'
457
+ * equal(meant(' Okay. Ha. Cool, uh'), 0)
458
+ * equal(meant('Okay, hold on'), 2)
459
+ * ```
460
+ */ export let meant = (text)=>words(text).filter((w)=>!FILLERS.has(w)).length;
461
+ /** Whether `text` stops where a sentence goes on: on a comma or a dash, or
462
+ * on a word a sentence goes on after (`ON`: "the", "to", "is", "um"). A caller
463
+ * heard to stop there has more to say.
464
+ *
465
+ * ```ts
466
+ * import { equal } from '@yaks/testing'
467
+ * import { open } from '@yaks/speech'
468
+ * let lines = ['My address is', 'So what I need is, um', 'Okay,', 'Okay.',
469
+ * 'Forty-two Elm Street.', 'Can you come out tomorrow?', '']
470
+ * equal(lines.map(open), [true, true, true, false, false, false, false])
471
+ * ```
472
+ */ export let open = (text)=>{
473
+ let w = words(text);
474
+ return !!w.length && (/[,\-–—…]\s*$/.test(text) || ON.has(w.at(-1)));
475
+ };
476
+ // The words a caller says over the model before it stops: fewer, or only
477
+ // fillers, and it goes on. Two say "wait, stop" or "hold on".
478
+ let OVER = 2;
479
+ // The seconds a caller is quiet before their turn ends, when the model has
480
+ // not heard it end: it waits on some whole sentences, and on a lone "Okay.".
481
+ // One going on ("Okay, so…") is mostly talking again by then.
482
+ let QUIET = 0.7;
483
+ // The seconds a turn left unanswered waits for more before it is answered,
484
+ // longer than a caller's pause to think.
485
+ let LONG = 5;
486
+ // The seconds a duplex model is quiet after its first words before they are
487
+ // over: gpt-live-1 paused up to 0.4 s between a greeting's sentences. And the
488
+ // seconds a line waits for a call's first words to begin before the caller
489
+ // is heard anyway.
490
+ let PAUSED = 0.6;
491
+ let SILENT = 6;
492
+ /**
493
+ * A call's first words, such as its greeting, said before the caller is
494
+ * heard: a hello of theirs said over them, or the sound of the line picking
495
+ * up, is no turn to answer. `said` takes the words' audio as it is given to
496
+ * the line, which may be faster than it plays, and `done` that it is all
497
+ * given. `heard` takes the caller's audio a frame at a time, as the line
498
+ * sends it, and answers what whoever listens should hear: a quiet line
499
+ * (`muted`) until the words have played, which they have once the line has
500
+ * run as long as they last. Words not begun in 6 s are given up, and the
501
+ * caller is heard.
502
+ *
503
+ * ```ts
504
+ * import { equal } from '@yaks/testing'
505
+ * import { first, sounds } from '@yaks/speech'
506
+ * let mulaw = { encoding: 'mulaw', rate: 8000 } as const
507
+ * let words = first(mulaw)
508
+ * let hello = (seconds: number) =>
509
+ * sounds(words.heard(new Uint8Array(seconds * 8000).fill(0x10)), mulaw)
510
+ * equal(hello(0.5), false)
511
+ * words.said(new Uint8Array(8000))
512
+ * words.done()
513
+ * equal([hello(0.5), hello(0.5), hello(1)], [false, true, true])
514
+ * ```
515
+ */ export let first = (format)=>{
516
+ let seconds = (audio)=>audio.length / perSecond(format);
517
+ // The seconds of them given, the seconds the line ran before them and
518
+ // since, whether they are all given, and whether they have played.
519
+ let spoken = 0, waited = 0, played = 0, done = false, over = false;
520
+ return {
521
+ said: (audio)=>void (done || (spoken += seconds(audio))),
522
+ done: ()=>void (done = true),
523
+ heard: (audio)=>{
524
+ if (over) return audio;
525
+ if (spoken) played += seconds(audio);
526
+ else waited += seconds(audio);
527
+ over = done ? played >= spoken : waited >= SILENT;
528
+ return over ? audio : muted(audio, format);
529
+ }
530
+ };
531
+ };
532
+ // The stream's own tools. With `LISTEN` the model says nothing this turn,
533
+ // while the caller has more to say. With `HUSH` it only listens from then
534
+ // on: each turn is put to it as a choice of tools, never words, so it says
535
+ // nothing (`LISTEN`) until it calls `ANSWER`, or `TALK` to stop listening.
536
+ let LISTEN = {
537
+ name: 'listen',
538
+ description: 'Say nothing this turn and keep listening: they stopped partway through what they are saying, cut off mid-sentence, trailing off to think, or with only an um or uh; or, while you only listen, what was said is not for you.',
539
+ parameters: {
540
+ type: 'object',
541
+ properties: {}
542
+ }
543
+ };
544
+ let HUSH = {
545
+ name: 'stay_silent',
546
+ description: 'They asked you only to listen, take notes or keep a transcript, or not to respond: call it instead of answering, with no words. From then on you only listen, still hearing everything and free to use your other tools, and speak only by calling answer.',
547
+ parameters: {
548
+ type: 'object',
549
+ properties: {}
550
+ }
551
+ };
552
+ let ANSWER = {
553
+ name: 'answer',
554
+ description: 'While you only listen, speak: only when you were named or asked a question, or something urgent went wrong with what they asked of you. A statement, an update, an idea, thinking aloud, or a question put to others is never asked of you, and work you did with your other tools is not reported unless asked: for those call listen. Call it, then say your answer; you go on only listening after it.',
555
+ parameters: {
556
+ type: 'object',
557
+ properties: {}
558
+ }
559
+ };
560
+ let TALK = {
561
+ name: 'talk',
562
+ description: 'While you only listen, they asked you to stop only listening and talk with them as before. Call it, then answer them.',
563
+ parameters: {
564
+ type: 'object',
565
+ properties: {}
566
+ }
567
+ };
568
+ // What a model that only listens is told with each turn put to it.
569
+ let HEEDING = 'You only listen now. This turn is put to you as a choice of tools, never words. listen, letting it pass, is the usual choice: for anything not said to you, and anything that asks nothing of you, such as news, a plan, agreement or a question to others. Call answer only when you are named, even where the transcript mishears the name, or asked a question yourself. Use another tool only for work someone asked of you. When unsure, listen.';
570
+ /** The entry of `provider`'s that talks with `model`, or with its first
571
+ * model when none is given, if any. */ export let talkerOf = (provider, model)=>model == undefined ? provider.talk?.[0] : provider.talk?.find((t)=>t.models.includes(model));
572
+ let talker = (provider, model)=>{
573
+ let t = talkerOf(provider, model);
574
+ if (!t) {
575
+ throw new Error(`${provider.name} has no model ${model ?? ''} that talks`);
576
+ }
577
+ return t;
578
+ };
579
+ // The stream's own `LISTEN` and `HUSH` come first among a turned model's
580
+ // tools, `HUSH` where it does not always listen; a duplex model's tools are
581
+ // whoever runs the call.
582
+ let setup = (t, o, format)=>({
583
+ model: o.model ?? t.models[0],
584
+ voice: o.voice ?? t.voice,
585
+ format,
586
+ speed: paced(t.speeds, o.speed),
587
+ instructions: wording(o.instructions) + '\n\nMessages name their source. Source labels are context for you; never read them aloud.',
588
+ tools: t.duplex ? [] : [
589
+ LISTEN,
590
+ ...o.listening ? [] : [
591
+ HUSH
592
+ ],
593
+ ...o.tools ?? []
594
+ ],
595
+ ...o.opens ? {
596
+ opens: o.opens
597
+ } : {},
598
+ ...o.words?.length ? {
599
+ words: o.words
600
+ } : {},
601
+ ...t.duplex && o.backend ? {
602
+ backend: {
603
+ ...o.backend,
604
+ instructions: wording(o.backend.instructions)
605
+ }
606
+ } : {}
607
+ });
608
+ let carrier = (provider, model)=>{
609
+ let calls = talker(provider, model).calls;
610
+ if (!calls) throw new Error(`${provider.name}'s line carries no calls`);
611
+ return calls;
612
+ };
613
+ let calling = async (o, { path, init })=>{
614
+ await asking(o)(path, init);
615
+ };
616
+ /** A call the provider's own line carries picked up, its model set up as
617
+ * `talk` sets one up; `talk` with the `call` then joins it. */ export let accept = (o)=>calling(o, carrier(o.provider, o.model).accept(o.call, setup(talker(o.provider, o.model), o)));
618
+ /** A call the provider's own line carries, refused before it is picked up. */ export let reject = (o)=>calling(o, carrier(o.provider).reject(o.call));
619
+ /** A call the provider's own line carries, ended. */ export let hangup = (o)=>calling(o, carrier(o.provider).hangup(o.call));
620
+ /**
621
+ * A model that hears and speaks in one stream: `send` takes the caller's raw
622
+ * samples in `format`, and `told` hears what the model says back and the
623
+ * tools it asks for, each answered with its output before it goes on. The
624
+ * provider's `talk` entry for `model` says how (its first model by default);
625
+ * one without it refuses.
626
+ *
627
+ * Given `opens`, the model's first words, it is asked for them as the stream
628
+ * opens, and the caller's audio reaches it as a quiet line (`muted`) until
629
+ * they have played: what the caller says over them, a hello or the sound of
630
+ * picking up, is no turn the model answers with a greeting of its own. A
631
+ * model that never begins them hears the caller after `SILENT`. A call its
632
+ * own line carries is asked for them too, its audio heard throughout.
633
+ *
634
+ * Asked to say given words (`opens`, `say`), a `Turned` model answers with
635
+ * no tool, and only its answer plays: a part it says before the answer
636
+ * (`Said.aside`) would be the words a second time.
637
+ *
638
+ * A `Duplex` model takes its own turns and hands its work to
639
+ * `told.delegate`; what it is asked to `say` while the caller talks is sent
640
+ * once they are `QUIET`. Everything below is for a `Turned` one, which
641
+ * takes a turn as it is told here.
642
+ *
643
+ * A caller who talks over the model stops it (`over`) once their words say
644
+ * something (`meant`): an "okay", a laugh, or a noise, lets it go on. The
645
+ * model writes its audio faster than it is said, so what it says is mostly
646
+ * still playing, its response long done, when the caller talks.
647
+ *
648
+ * The caller's turn ends when the model hears it end, or once they are
649
+ * `QUIET`, and is answered. What the model says to it waits for the caller's
650
+ * words, and is never said when they stopped where a sentence goes on
651
+ * (`open`), when the model asks to `LISTEN`, or when the caller talks again
652
+ * before it plays. A turn left unanswered is answered once they have been
653
+ * quiet `LONG`.
654
+ *
655
+ * Asked to stay silent (`HUSH`), or always (`listening`), the model only
656
+ * listens: each turn is still put to it once its words are heard, but as a
657
+ * choice of tools, never words, so it keeps hearing and may work without a
658
+ * word, and nothing is said until it calls `ANSWER`; a turn left unanswered
659
+ * stays so. A turn whose words are said to it (`addressed`) is answered.
660
+ *
661
+ * Given a `call` its own line carries, picked up with `accept`, the stream
662
+ * joins that call instead: the caller's audio and the model's go over the
663
+ * line, never through `send` or `told.audio`, and what plays is stopped on
664
+ * the line; `told.plays` says when the model's audio begins, and
665
+ * `told.ended` when the call ends. Its audio never heard here, a turn ends
666
+ * only when the model hears it end, and what the model says plays before
667
+ * the turn's words are heard.
668
+ */ export let talk = (o)=>{
669
+ let t = talker(o.provider, o.model);
670
+ return t.duplex ? duplexed(o, t) : turned(o, t);
671
+ };
672
+ // A model that takes a turn when asked: the caller's turn is ended, each
673
+ // response asked for, and the response stopped when they talk over it, here.
674
+ let turned = (o, t)=>{
675
+ let set = setup(t, o, o.format);
676
+ let model = set.model;
677
+ let joined = o.call == undefined ? undefined : carrier(o.provider, model);
678
+ let seconds = (bytes)=>o.format ? bytes / perSecond(o.format) : 0;
679
+ let bytes = 0, dollars = 0;
680
+ // The model answers one response at a time: one asked for while another is
681
+ // under way waits for it to be done. `last` is the one asked for last, asked
682
+ // again if it was refused; waiting asks to go on are one.
683
+ let busy = false, last;
684
+ let waiting = [], going = t.respond();
685
+ // Whether the model only listens, which it asks for with `HUSH` and
686
+ // stops with `TALK`, or does always; and how a turn is put to it then.
687
+ let listens = false;
688
+ let listening = ()=>!!o.listening || listens;
689
+ let heeding = t.respond({
690
+ tools: [
691
+ LISTEN,
692
+ ANSWER,
693
+ ...o.listening ? [] : [
694
+ TALK
695
+ ],
696
+ ...o.tools ?? []
697
+ ],
698
+ call: true,
699
+ instructions: `${set.instructions}\n\n${HEEDING}`
700
+ });
701
+ // While it listens, a turn whose words are said to it (`addressed`) is
702
+ // answered in words, and any other put to it as a choice of tools, once
703
+ // its words are heard (`awaiting`). Whether the turn is being answered,
704
+ // so a tool's output is followed by words; and whether the response under
705
+ // way is a choice of tools, whose words, if any, are never said.
706
+ // A turn said to it that it let go on, such as its name alone, or one
707
+ // whose words stop where a sentence goes on ("Ember,"), carries to the
708
+ // next (`called`).
709
+ let awaiting = false, answering = false, choosing = false, called = false;
710
+ let put = ()=>{
711
+ let to = called || !!o.addressed?.(heard);
712
+ let m = !listening() || to ? going : heeding;
713
+ answering = m == going;
714
+ called = false;
715
+ ask(pending = m);
716
+ };
717
+ // The responses asked to say given words, and whether the one under way
718
+ // is one. Such a response plays its answer alone: what the model says
719
+ // before it (`aside`) is the words a second time, or words of its own.
720
+ let scripts = new Set(), scripted = false;
721
+ let asides = new Set();
722
+ let script = (text)=>{
723
+ let m = t.respond({
724
+ text
725
+ });
726
+ scripts.add(m);
727
+ ask(m);
728
+ };
729
+ // What the caller has said since they started talking, whether it stopped
730
+ // the model, and whether the response it stopped is still sending audio.
731
+ let hearing = '', over = false, hushed = false;
732
+ let partials = new Map();
733
+ // Whether the caller's turn ended, whether they spoke since it last did,
734
+ // and for how many seconds their audio has been quiet. `heard` is their
735
+ // words last heard; `unheard`, that the turn's are still to come.
736
+ let ended = true, spoke = false, quiet = 0, heard = '', unheard = false;
737
+ // The ask for the turn's answer while it is not yet played or asked of a
738
+ // tool, and whether the turn was left unanswered. What the model says while
739
+ // the turn's words are `unheard` is `held`: each thing to do once they are,
740
+ // and to do instead if it is never said.
741
+ let pending, unanswered = false;
742
+ let held;
743
+ let out = (run, drop)=>held ? held.push({
744
+ run,
745
+ drop
746
+ }) : run();
747
+ // Its first words (`opens`), on a stream that carries the caller's audio,
748
+ // which the model writes faster than they are said.
749
+ let opens = o.opens && o.format && !o.interruptible ? first(o.format) : undefined;
750
+ let end = ()=>{
751
+ if (ended) return;
752
+ ended = true;
753
+ if (spoke) spoke = false, unheard = true;
754
+ if (unheard) held = [];
755
+ o.told.stopped?.();
756
+ if (!unheard && open(heard)) return void (unanswered = true);
757
+ if (unheard && listening()) return void (awaiting = true);
758
+ put();
759
+ };
760
+ let soon = ()=>{
761
+ if (!ended && quiet >= QUIET) s.send(t.commit), end();
762
+ if (unanswered && !listening() && quiet >= LONG) {
763
+ unanswered = false;
764
+ ask(pending = t.respond({
765
+ tools: o.tools ?? []
766
+ }));
767
+ }
768
+ };
769
+ // The turn's answer is not said: what is held is dropped, the ask still
770
+ // waiting is not sent, and the response under way is stopped.
771
+ let withdraw = ()=>{
772
+ for (let h of held ?? [])h.drop?.();
773
+ let m = pending;
774
+ held = pending = undefined;
775
+ if (waiting.includes(m)) waiting.splice(waiting.indexOf(m), 1);
776
+ else if (busy && last == m) s.send(t.cancel), hushed = true;
777
+ if (joined) s.send(joined.hush);
778
+ };
779
+ let ask = (m)=>{
780
+ let on = m == going || m == heeding;
781
+ if (!on || !waiting.includes(m)) waiting.push(m);
782
+ next();
783
+ };
784
+ let next = ()=>{
785
+ if (busy || !waiting.length) return;
786
+ busy = true;
787
+ s.send(last = waiting.shift());
788
+ };
789
+ let s = stream(o, o.provider.live + (joined ? joined.join(o.call) : t.path(model)), joined ? [] : t.opening(set), (data)=>{
790
+ for (let said of t.read(data, model)){
791
+ if (said.start) {
792
+ if (pending) withdraw();
793
+ hearing = '', spoke = true, awaiting = false;
794
+ over = ended = unanswered = false;
795
+ }
796
+ // Their words still heard once their turn ended are its own.
797
+ if (said.hearing) {
798
+ hearing += said.hearing;
799
+ let text = hearing;
800
+ if (o.told.hearing && said.key) {
801
+ text = (partials.get(said.key) ?? '') + said.hearing;
802
+ partials.set(said.key, text);
803
+ }
804
+ o.told.hearing?.(text, said.key);
805
+ }
806
+ if (said.hearing && !ended && !over && meant(hearing) >= OVER) {
807
+ over = true;
808
+ if (busy) s.send(t.cancel), hushed = true;
809
+ if (joined) s.send(joined.hush);
810
+ o.told.over?.();
811
+ }
812
+ if (said.stopped) end();
813
+ if (said.heard != undefined) {
814
+ if (said.key) partials.delete(said.key);
815
+ if (said.heard) o.told.heard?.(said.heard, said.key);
816
+ else o.told.hearing?.('', said.key);
817
+ heard = said.heard, unheard = false;
818
+ if (listening() && o.addressed?.(heard)) called = true;
819
+ if (pending && open(heard)) withdraw(), unanswered = true;
820
+ if (awaiting && !open(heard)) put();
821
+ awaiting = false;
822
+ let h = held ?? [];
823
+ held = undefined;
824
+ for (let { run } of h)run();
825
+ }
826
+ if (said.aside) asides.add(said.aside);
827
+ let spare = choosing || scripted && said.of != undefined && asides.has(said.of);
828
+ let audio = spare ? undefined : said.audio;
829
+ if (audio) opens?.said(audio);
830
+ if (audio && !hushed) {
831
+ out(()=>(pending = undefined, o.told.audio(audio)));
832
+ }
833
+ let text = spare || !said.said ? '' : spokenProse(said.said);
834
+ if (text) out(()=>o.told.said?.(text));
835
+ if (said.plays) o.told.plays?.();
836
+ if (said.spent) dollars += said.spent;
837
+ if (said.begun) {
838
+ busy = true;
839
+ scripted = scripts.has(last);
840
+ choosing = last == heeding;
841
+ if (hushed) s.send(t.cancel);
842
+ }
843
+ if (said.busy && last) waiting.unshift(last), busy = true;
844
+ if (said.done) {
845
+ out(()=>o.told.done?.(), ()=>o.told.done?.());
846
+ busy = hushed = false;
847
+ opens?.done();
848
+ next();
849
+ }
850
+ if (said.error) o.told.lost?.(said.error);
851
+ let call = said.call;
852
+ if (call?.name == LISTEN.name) {
853
+ called = listening() && answering;
854
+ if (pending) withdraw(), unanswered = true;
855
+ for (let m of t.answer(call.id, wording('Listening.')))s.send(m);
856
+ } else if (call?.name == HUSH.name) {
857
+ listens = true;
858
+ if (pending) withdraw();
859
+ let told = 'Silent: you only listen until you are addressed.';
860
+ for (let m of t.answer(call.id, wording(told)))s.send(m);
861
+ } else if (call?.name == ANSWER.name || call?.name == TALK.name) {
862
+ // Asked to speak while it only listens, it is asked for its words.
863
+ if (call.name == TALK.name) listens = false;
864
+ answering = true;
865
+ let speak = ()=>{
866
+ for (let m of t.answer(call.id, wording('Say it now.')))s.send(m);
867
+ ask(pending = going);
868
+ };
869
+ out(speak, ()=>{
870
+ let output = wording('Not asked: they went on talking.');
871
+ for (let m of t.answer(call.id, output))s.send(m);
872
+ });
873
+ } else if (call) {
874
+ let answer = (output, more = true)=>{
875
+ for (let m of t.answer(call.id, wording(output, `the ${call.name} tool`)))s.send(m);
876
+ // While it listens, work on a turn it is not answering is
877
+ // done without a word.
878
+ if (more && (answering || !listening())) ask(going);
879
+ };
880
+ out(()=>{
881
+ pending = undefined;
882
+ o.told.call(call.name, call.args, answering || !listening()).catch((error)=>({
883
+ text: `That did not work: ${error?.message ?? error}`,
884
+ from: 'the system'
885
+ })).then(answer);
886
+ }, ()=>answer({
887
+ text: 'Not asked: they went on talking.',
888
+ from: 'the system'
889
+ }, false));
890
+ }
891
+ }
892
+ }, (reason, clean)=>joined && clean ? o.told.ended?.() : o.told.lost?.(reason));
893
+ if (o.opens) script(o.opens);
894
+ return {
895
+ send: (audio)=>{
896
+ if (s.closed() || !o.format) return;
897
+ bytes += audio.length;
898
+ if (opens) audio = opens.heard(audio);
899
+ s.send(t.audio(audio));
900
+ if (!sounds(audio, o.format)) {
901
+ quiet += seconds(audio.length);
902
+ return soon();
903
+ }
904
+ // Talking again before the answer plays, the caller is not done.
905
+ quiet = 0;
906
+ if (pending) withdraw(), ended = false;
907
+ },
908
+ say: (text, from)=>script(wording(text, from)),
909
+ tell: (text, from)=>{
910
+ for (let m of t.tell(wording(text, from)))s.send(m);
911
+ },
912
+ spent: ()=>({
913
+ seconds: seconds(bytes),
914
+ dollars
915
+ }),
916
+ close: ()=>{
917
+ s.close();
918
+ return {
919
+ seconds: seconds(bytes),
920
+ dollars
921
+ };
922
+ }
923
+ };
924
+ };
925
+ // A model that hears and speaks at once and takes its own turns, so nothing
926
+ // here ends a turn, asks for a response or stops one: what is left is
927
+ // keeping the words each side says as lines, timing each answer from the
928
+ // caller's last sound, and doing the work it hands over. Its audio comes as
929
+ // it is said, quiet included, and plays as it comes.
930
+ let duplexed = (o, t)=>{
931
+ let format = o.format;
932
+ if (!format || o.call != undefined) {
933
+ throw new Error(`${o.provider.name}'s duplex model joins no call`);
934
+ }
935
+ let set = setup(t, o, format);
936
+ if (set.backend && !t.backends.includes(set.backend.model)) {
937
+ throw new Error(`${o.provider.name}'s ${set.model} hands no work to ${set.backend.model}`);
938
+ }
939
+ // The stream's seconds and what its backend's work cost.
940
+ let bytes = 0, backed = 0;
941
+ // Each side's words since the other last spoke, and the caller's since the
942
+ // model last handed work over.
943
+ let hearing = '', saying = '', asked = '', latest = '';
944
+ // Whether the caller made a sound since the model last began to, and for
945
+ // how many seconds they have been quiet.
946
+ let spoke = false, quiet = 0, interrupted = false;
947
+ let stop = ()=>{
948
+ if (!spoke) return;
949
+ spoke = false;
950
+ o.told.stopped?.(quiet);
951
+ };
952
+ // What the model is asked to say while the caller talks, sent once they
953
+ // are `QUIET`: appended over their words, it can go unsaid.
954
+ let talking = false, unsaid = [];
955
+ let cancelHeard;
956
+ let cancelSaid;
957
+ let time = o.time ?? system;
958
+ let heard = ()=>{
959
+ cancelHeard?.();
960
+ cancelHeard = undefined;
961
+ let text = hearing.trim();
962
+ hearing = '';
963
+ if (text) o.told.heard?.(text), asked += ' ' + text, latest = text;
964
+ };
965
+ let heardPause = ()=>{
966
+ if (!hearing || quiet < QUIET) return;
967
+ cancelHeard?.();
968
+ cancelHeard = time.after(PAUSED * 1000, heard);
969
+ };
970
+ let said = ()=>{
971
+ cancelSaid?.();
972
+ cancelSaid = undefined;
973
+ let line = saying.trim();
974
+ saying = '';
975
+ if (!line) return;
976
+ let text = spokenProse(line);
977
+ if (text) o.told.said?.(text);
978
+ o.told.done?.();
979
+ };
980
+ // GPT-Live has no transcript-done event. A reply can end with silence
981
+ // on both sides and no next turn to settle its text.
982
+ let spokenPause = ()=>{
983
+ cancelSaid?.();
984
+ cancelSaid = time.after(PAUSED * 1000, said);
985
+ };
986
+ // What is sent before the stream is ready, sent once it is.
987
+ let held = [];
988
+ let send = (m)=>held ? held.push(m) : s.send(m);
989
+ // Its first words (`opens`): whether it has begun them, the seconds it has
990
+ // been quiet since, and the seconds the caller's line ran before them.
991
+ // Its audio comes as it is said, so they are over once it has spoken and
992
+ // paused, or never began them.
993
+ let opens = o.opens && !o.interruptible ? {
994
+ began: false,
995
+ quiet: 0,
996
+ waited: 0
997
+ } : undefined;
998
+ let spoken = (audio)=>{
999
+ if (!opens) return;
1000
+ if (sounds(audio, format)) opens.began = true, opens.quiet = 0;
1001
+ else if (opens.began) opens.quiet += audio.length / perSecond(format);
1002
+ if (opens.quiet >= PAUSED) opens = undefined;
1003
+ };
1004
+ let s = stream(o, o.provider.live + t.path(set.model), t.opening(set), (data)=>{
1005
+ for (let x of t.read(data, set.model, set.backend?.model)){
1006
+ if (x.ready && held) {
1007
+ for (let m of held.splice(0))s.send(m);
1008
+ }
1009
+ if (x.ready) held = undefined;
1010
+ if (x.hearing) {
1011
+ said();
1012
+ hearing += x.hearing;
1013
+ o.told.hearing?.(hearing);
1014
+ heardPause();
1015
+ if (spoke && !interrupted && meant(hearing) >= OVER) {
1016
+ interrupted = true;
1017
+ o.told.over?.();
1018
+ }
1019
+ }
1020
+ if (x.saying) {
1021
+ if (quiet >= QUIET) heard();
1022
+ saying += x.saying;
1023
+ spokenPause();
1024
+ }
1025
+ if (x.audio) {
1026
+ spoken(x.audio);
1027
+ if (sounds(x.audio, format)) {
1028
+ if (saying) spokenPause();
1029
+ stop();
1030
+ }
1031
+ o.told.audio(x.audio);
1032
+ }
1033
+ // One refused event leaves the stream open: a stream that failed
1034
+ // closes, and is lost.
1035
+ if (x.error) o.told.refused?.(x.error);
1036
+ if (x.spent) backed += x.spent;
1037
+ let call = x.call;
1038
+ if (call) {
1039
+ stop();
1040
+ heard();
1041
+ Promise.resolve(o.told.call(call.name, call.args, !o.listening || !!o.addressed?.(latest))).catch((error)=>({
1042
+ text: `That did not work: ${error?.message ?? error}`,
1043
+ from: 'the system'
1044
+ })).then((output)=>t.result(call.id, wording(output, `the ${call.name} tool`)).forEach(send));
1045
+ }
1046
+ let id = x.delegated;
1047
+ if (id) {
1048
+ stop();
1049
+ heard(), said();
1050
+ let request = asked.trim();
1051
+ asked = '';
1052
+ if (!request) continue;
1053
+ Promise.resolve(o.told.delegate?.(request, !o.listening || !!o.addressed?.(latest))).catch((error)=>({
1054
+ text: `That did not work: ${error?.message ?? error}`,
1055
+ from: 'the system'
1056
+ })).then((output)=>{
1057
+ if (output) {
1058
+ t.answer(id, wording(output, 'the delegate')).forEach(send);
1059
+ }
1060
+ });
1061
+ }
1062
+ }
1063
+ }, (reason)=>{
1064
+ heard();
1065
+ said();
1066
+ o.told.lost?.(reason);
1067
+ });
1068
+ let spent = ()=>{
1069
+ let seconds = bytes / perSecond(format);
1070
+ return {
1071
+ seconds,
1072
+ dollars: seconds / 60 * t.perMinute + backed
1073
+ };
1074
+ };
1075
+ if (o.opens) t.opens(o.opens).forEach(send);
1076
+ return {
1077
+ send: (audio)=>{
1078
+ if (s.closed()) return;
1079
+ bytes += audio.length;
1080
+ if (opens && !opens.began) {
1081
+ opens.waited += audio.length / perSecond(format);
1082
+ if (opens.waited >= SILENT) opens = undefined;
1083
+ }
1084
+ if (opens) audio = muted(audio, format);
1085
+ send(t.audio(audio));
1086
+ if (sounds(audio, format)) {
1087
+ cancelHeard?.();
1088
+ cancelHeard = undefined;
1089
+ if (!spoke) interrupted = false;
1090
+ spoke = talking = true, quiet = 0;
1091
+ } else {
1092
+ quiet += audio.length / perSecond(format);
1093
+ if (!cancelHeard) heardPause();
1094
+ }
1095
+ if (talking && quiet >= QUIET) {
1096
+ talking = false;
1097
+ unsaid.splice(0).forEach(send);
1098
+ }
1099
+ },
1100
+ say: (text, from)=>{
1101
+ let m = t.say(wording(text, from));
1102
+ talking ? unsaid.push(...m) : m.forEach(send);
1103
+ },
1104
+ tell: (text, from)=>t.tell(wording(text, from)).forEach(send),
1105
+ spent,
1106
+ close: ()=>{
1107
+ heard(), said();
1108
+ s.close();
1109
+ return spent();
1110
+ }
1111
+ };
1112
+ };
1113
+ //# sourceMappingURL=mod.js.map