@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.ts ADDED
@@ -0,0 +1,1777 @@
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
+
8
+ export { DEEPGRAM } from './deepgram.js'
9
+ export { ELEVENLABS } from './elevenlabs.js'
10
+ export { OPENAI, openaiLiveBackend } from './openai.js'
11
+ export {
12
+ base64,
13
+ mulawed,
14
+ mulawOf,
15
+ muted,
16
+ sounds,
17
+ trimmed,
18
+ unbase64,
19
+ } from './audio.js'
20
+ export { query } from './query.js'
21
+ export { type Speech, speechFrom } from './speech-from.js'
22
+ import { message } from '@yaks/model'
23
+ import { type Clock, system } from '@yaks/fp'
24
+ import { muted, sounds, trimmed } from './audio.js'
25
+
26
+ /** How audio is encoded: an MP3, or raw samples at a rate (`mulaw` is the
27
+ * telephone's 8 kHz μ-law; `linear16` is 16-bit PCM). */
28
+ export type Format =
29
+ | { encoding: 'mp3' }
30
+ | { encoding: 'mulaw' | 'linear16'; rate: number }
31
+
32
+ /** Raw samples at a rate, as a call streams them. */
33
+ export type Raw = Extract<Format, { rate: number }>
34
+
35
+ /** A voice a provider speaks in: the `id` a request names, what a person
36
+ * calls it, how it sounds, and where a sample of it plays. A provider marks
37
+ * a voice `custom` when it was made or added to the account's library. */
38
+ export type Voice = {
39
+ id: string
40
+ name: string
41
+ about: string
42
+ sample?: string
43
+ custom?: true
44
+ }
45
+
46
+ /** A voice designed from a description, not yet kept: the id `keep` takes,
47
+ * and a sample of it. */
48
+ export type Design = {
49
+ id: string
50
+ audio: Uint8Array
51
+ type: string
52
+ seconds: number
53
+ }
54
+
55
+ /** The speeds a provider speaks at, as multiples of its own pace. */
56
+ export type Speeds = { min: number; max: number }
57
+
58
+ /** `speed` as near as `speeds` allows.
59
+ *
60
+ * ```ts
61
+ * import { equal } from '@yaks/testing'
62
+ * equal(paced({ min: 0.7, max: 1.5 }, 1.3), 1.3)
63
+ * equal(paced({ min: 0.25, max: 1.5 }, 2), 1.5)
64
+ * ```
65
+ */
66
+ export let paced = ({ min, max }: Speeds, speed = 1): number =>
67
+ Math.min(max, Math.max(min, speed))
68
+
69
+ /** A spoken line as prose. Apply after assembling transcript fragments,
70
+ * which can split words and directions as well as sentences. */
71
+ export let spokenProse = (text: string): string =>
72
+ text.replace(
73
+ /(?:[ \t]*\[[^[\]\r\n]+\])+[ \t]*([,.;:!?])?/g,
74
+ (_, punctuation) => punctuation ?? ' ',
75
+ ).replace(/((?:[\p{L}\p{N}]{2}\.|[!?])["”’]?)(?=\p{Lu})/gu, '$1 ').trim()
76
+
77
+ /** A request as a provider words it: the path under its API, and the rest. */
78
+ export type Asked = { path: string; init: RequestInit }
79
+
80
+ /** A multipart request with an audio file, including recordings read as a stream. */
81
+ export let audioForm = (
82
+ fields: Record<string, string>,
83
+ audio: BodyInit,
84
+ type: string,
85
+ ): RequestInit => {
86
+ if (!(audio instanceof ReadableStream)) {
87
+ let body = new FormData()
88
+ for (let [name, value] of Object.entries(fields)) body.set(name, value)
89
+ body.set('file', new Blob([audio as BlobPart], { type }), 'audio')
90
+ return { method: 'POST', body }
91
+ }
92
+ let boundary = crypto.randomUUID()
93
+ let encode = new TextEncoder()
94
+ let parts = Object.entries(fields).map(([name, value]) =>
95
+ `--${boundary}\r\nContent-Disposition: form-data; name="${name}"\r\n\r\n${value}\r\n`
96
+ ).join('')
97
+ let media = new Blob([], { type }).type || 'application/octet-stream'
98
+ let header = parts + `--${boundary}\r\n` +
99
+ 'Content-Disposition: form-data; name="file"; filename="audio"\r\n' +
100
+ `Content-Type: ${media}\r\n\r\n`
101
+ let reader = audio.getReader()
102
+ let body = new ReadableStream<Uint8Array>({
103
+ start: (out) => out.enqueue(encode.encode(header)),
104
+ pull: async (out) => {
105
+ let next = await reader.read()
106
+ if (!next.done) out.enqueue(next.value)
107
+ else {
108
+ out.enqueue(encode.encode(`\r\n--${boundary}--\r\n`))
109
+ out.close()
110
+ }
111
+ },
112
+ cancel: (reason) => reader.cancel(reason),
113
+ })
114
+ return {
115
+ method: 'POST',
116
+ headers: { 'content-type': `multipart/form-data; boundary=${boundary}` },
117
+ body,
118
+ }
119
+ }
120
+
121
+ /** A provider's HTTP API, its base and key already given. */
122
+ export type Ask = (path: string, init?: RequestInit) => Promise<Response>
123
+
124
+ /** A turn heard: what one speaker said, and when. `speaker` numbers the
125
+ * voices a provider tells apart from 0, and is 0 throughout where it tells
126
+ * none apart (its `speakers`); `from` and `to` are seconds into the audio,
127
+ * where the provider says. */
128
+ export type Turn = {
129
+ speaker: number
130
+ text: string
131
+ from?: number
132
+ to?: number
133
+ key?: string
134
+ }
135
+
136
+ /** What one message on a turns stream means: the speaker started a turn,
137
+ * turns ended (`ended`, in order), or the stream failed. */
138
+ export type Cue = {
139
+ start?: true
140
+ hearing?: { text: string; key?: string }
141
+ ended?: Turn[]
142
+ error?: string
143
+ }
144
+
145
+ /** What one message on a talk stream means. */
146
+ export type Said = {
147
+ /** the caller started talking */
148
+ start?: true
149
+ /** the caller stopped talking, and the model is about to answer */
150
+ stopped?: true
151
+ /** what the caller said, once heard: nothing, when no words were */
152
+ heard?: string
153
+ /** the next of the caller's words, heard as they talk */
154
+ hearing?: string
155
+ /** the provider's identity for the input utterance */
156
+ key?: string
157
+ /** audio the model speaks, in the stream's format */
158
+ audio?: Uint8Array
159
+ /** what the model said, once said */
160
+ said?: string
161
+ /** the part of a response the `audio` or the words `said` belong to, by
162
+ * its id, where a response has parts */
163
+ of?: string
164
+ /** the model began a part it says before its answer, by its id: a word
165
+ * while it works, or its answer rehearsed */
166
+ aside?: string
167
+ /** the next of the model's words, said as it speaks */
168
+ saying?: string
169
+ /** the stream takes what is sent after its opening from now on, held
170
+ * until then */
171
+ ready?: true
172
+ /** the model hands work to whoever runs the call, by this id: what the
173
+ * caller asked is in their words so far */
174
+ delegated?: string
175
+ /** the model asks for a tool */
176
+ call?: { id: string; name: string; args: string }
177
+ /** what the turn just finished cost, in dollars */
178
+ spent?: number
179
+ /** the model's audio began playing to the caller, on a call its own line
180
+ * carries */
181
+ plays?: true
182
+ /** the model began a response: no other may be asked for until it is done */
183
+ begun?: true
184
+ /** the model's response ended */
185
+ done?: true
186
+ /** the response last asked for was refused, one being under way: ask
187
+ * again once it is done */
188
+ busy?: true
189
+ error?: string
190
+ }
191
+
192
+ /** What a talk stream is set up with. */
193
+ export type Setup = {
194
+ model: string
195
+ voice: string
196
+ /** none on a call the provider's own line carries, which says its own */
197
+ format?: Raw
198
+ /** how fast it speaks, within the talking model's `speeds` */
199
+ speed: number
200
+ instructions: string
201
+ tools: { name: string; description: string; parameters: object }[]
202
+ /** its first words, said as the stream opens (`Talking.opens`) */
203
+ opens?: string
204
+ /** words its hearing should expect, such as the names it is called by */
205
+ words?: string[]
206
+ /** a larger model a duplex model hands its work to on the provider's
207
+ * side, one of its `backends`, told `instructions` and calling `tools`
208
+ * through `told.call`; without one, the work goes to whoever runs the
209
+ * call (`told.delegate`) */
210
+ backend?: Backend
211
+ }
212
+
213
+ /** A larger model a duplex model hands its work to on the provider's side. */
214
+ export type Backend = {
215
+ model: string
216
+ instructions: string
217
+ tools: Setup['tools']
218
+ /** Whether the provider may search without going through the client. */
219
+ webSearch?: boolean
220
+ }
221
+
222
+ /** A speech provider as data. */
223
+ export type Provider = {
224
+ name: string
225
+ /** what a person calls it */
226
+ title: string
227
+ /** the HTTP API's base */
228
+ api: string
229
+ /** the streaming API's base */
230
+ live: string
231
+ /** the header a request carries its key in, `authorization` unless
232
+ * named */
233
+ header?: string
234
+ /** that header's value for a key */
235
+ authorization: (key: string) => string
236
+ /** the WebSocket subprotocols a browser offers a key under */
237
+ protocols: (key: string) => string[]
238
+ /** a recording heard whole, priced by the minute of audio */
239
+ hear: {
240
+ model: string
241
+ perMinute: number
242
+ /** whether it tells one speaker from another */
243
+ speakers: boolean
244
+ /** the largest recording it hears, in bytes */
245
+ bytes: number
246
+ request: (audio: BodyInit, type: string, model: string) => Asked
247
+ /** the words in its answer, the seconds heard and its turns, where it
248
+ * says */
249
+ read: (said: unknown) => { text: string; seconds?: number; turns?: Turn[] }
250
+ }
251
+ /** the models that hear audio as it streams, the first unless another
252
+ * is asked for (`streamOf`) */
253
+ turns: Stream[]
254
+ /** text spoken in `voice` unless another of `voices` is asked for, by
255
+ * the first of `models` unless another is (`speakerOf`) */
256
+ speak: {
257
+ voice: string
258
+ voices: Voice[]
259
+ speeds: Speeds
260
+ models: Speaker[]
261
+ /** `speed` is within `speeds`, `model` one of `models` */
262
+ request: (
263
+ text: string,
264
+ voice: string,
265
+ format: Format,
266
+ speed: number,
267
+ model: string,
268
+ ) => Asked
269
+ /** what turns its audio into `format`, when it does not speak it */
270
+ audio?: (
271
+ format: Format,
272
+ ) => TransformStream<Uint8Array, Uint8Array> | undefined
273
+ }
274
+ /** the models that hear and speak in one stream, answering as they go */
275
+ talk?: Talker[]
276
+ /** the account's credit left, in dollars, where the provider says */
277
+ balance?: (ask: Ask) => Promise<number>
278
+ /** the voices the key's account speaks in, where it keeps its own: a
279
+ * page of them, and the next page's token while there are more */
280
+ voices?: {
281
+ request: (page?: string) => Asked
282
+ read: (said: unknown) => { voices: Voice[]; next?: string }
283
+ }
284
+ /** making voices of the account's own, where the provider does */
285
+ make?: {
286
+ /** voices designed from a description, each saying `text`, or words
287
+ * the provider picks */
288
+ design: (description: string, text?: string) => Asked
289
+ designs: (said: unknown) => Design[]
290
+ /** a design kept as a voice of the account's */
291
+ keep: (design: string, name: string, description: string) => Asked
292
+ /** a voice cloned from recordings of it */
293
+ clone: (name: string, samples: Blob[], description?: string) => Asked
294
+ /** the id of the voice `keep` or `clone` made */
295
+ made: (said: unknown) => string
296
+ }
297
+ }
298
+
299
+ /** A model that speaks text, priced by the thousand characters. */
300
+ export type Speaker = { model: string; perThousand: number }
301
+
302
+ /**
303
+ * The model of `provider`'s that speaks as `model` asks: that one where it
304
+ * has it, else its first.
305
+ *
306
+ * ```ts
307
+ * import { equal } from '@yaks/testing'
308
+ * import { ELEVENLABS, speakerOf } from '@yaks/speech'
309
+ * equal(speakerOf(ELEVENLABS, 'eleven_flash_v2_5').perThousand, 0.04)
310
+ * equal(speakerOf(ELEVENLABS, 'aura-2').model, 'eleven_v4')
311
+ * ```
312
+ */
313
+ export let speakerOf = (provider: Provider, model?: string | null): Speaker =>
314
+ provider.speak.models.find((m) => m.model == model) ??
315
+ provider.speak.models[0]
316
+
317
+ /** A model that hears audio as it streams, told back a turn at a time, as
318
+ * its provider words it. */
319
+ export type Stream = {
320
+ model: string
321
+ perMinute: number
322
+ /** whether it tells one speaker from another */
323
+ speakers: boolean
324
+ path: (format: Raw, model: string) => string
325
+ /** what is sent once the stream opens, before any audio */
326
+ opening: (format: Raw, model: string) => string[]
327
+ /** raw samples as the stream carries them */
328
+ audio: (bytes: Uint8Array) => string | Uint8Array
329
+ /** what reads one stream's messages, made as it opens, so a provider that
330
+ * tells a turn over several messages keeps its words until it ends */
331
+ reader: () => (data: unknown) => Cue
332
+ /** what ends the stream: the provider tells what it still heard, then
333
+ * closes */
334
+ closing?: string
335
+ }
336
+
337
+ /** The entry of `provider`'s that streams with `model`, or its first when
338
+ * none is given.
339
+ *
340
+ * ```ts
341
+ * import { equal } from '@yaks/testing'
342
+ * import { DEEPGRAM, streamOf } from '@yaks/speech'
343
+ * equal(streamOf(DEEPGRAM).model, 'flux-general-en')
344
+ * equal(streamOf(DEEPGRAM, 'nova-3').speakers, true)
345
+ * ```
346
+ */
347
+ export let streamOf = (provider: Provider, model?: string): Stream => {
348
+ let s = model == undefined
349
+ ? provider.turns[0]
350
+ : provider.turns.find((t) => t.model == model)
351
+ if (!s) throw new Error(`${provider.name} streams no model ${model}`)
352
+ return s
353
+ }
354
+
355
+ /** Models that hear and speak in one stream, as their provider words it. */
356
+ export type Talker = {
357
+ /** the models it offers, the fastest first */
358
+ models: string[]
359
+ voice: string
360
+ voices: Voice[]
361
+ speeds: Speeds
362
+ path: (model: string) => string
363
+ opening: (setup: Setup) => string[]
364
+ audio: (bytes: Uint8Array) => string
365
+ /** what one message means, on a stream talking with `model`, handing its
366
+ * work to `backend` where it has one */
367
+ read: (data: unknown, model: string, backend?: string) => Said[]
368
+ /** a tool's answer given back, or a delegation's */
369
+ answer: (call: string, output: string) => string[]
370
+ /** something the model is told mid-stream, for what it says next,
371
+ * answered by nothing */
372
+ tell: (text: string) => string[]
373
+ /** calls its own line carries, such as one sent to it over SIP: their
374
+ * audio never passes here, and a stream joins one to hear and steer it */
375
+ calls?: {
376
+ /** a webhook's event that a call rang: its id and the headers it came
377
+ * with, their names lower case; undefined for any other event */
378
+ rang: (
379
+ event: unknown,
380
+ ) => { id: string; headers: Record<string, string> } | undefined
381
+ /** pick a call up, talking as `setup` says */
382
+ accept: (call: string, setup: Setup) => Asked
383
+ reject: (call: string) => Asked
384
+ hangup: (call: string) => Asked
385
+ /** the path of the stream that joins a call */
386
+ join: (call: string) => string
387
+ /** what stops the audio playing to the caller */
388
+ hush: string
389
+ }
390
+ } & (Turned | Duplex)
391
+
392
+ /** A model that takes a turn when asked: here is said when the caller's
393
+ * turn ended, and when to stop. */
394
+ export type Turned = {
395
+ duplex?: undefined
396
+ /** the model asked for a response: to say `text`, or without it to go
397
+ * on, asking for `tools` alone when they are given, and with `call` for
398
+ * a call of one of them, never words; `instructions` are the response's
399
+ * in place of the session's */
400
+ respond: (asked?: {
401
+ text?: string
402
+ tools?: Setup['tools']
403
+ call?: boolean
404
+ instructions?: string
405
+ }) => string
406
+ /** what stops the response under way */
407
+ cancel: string
408
+ /** what ends the caller's turn now, before the model hears it end */
409
+ commit: string
410
+ }
411
+
412
+ /** A model that hears and speaks at once, as a person on the phone does,
413
+ * and takes its own turns: it hears when the caller is done and yields when
414
+ * they talk over it, sending its audio as it is said, quiet and all. Its
415
+ * tools are whoever runs the call, which it hands work to (`delegated`). */
416
+ export type Duplex = {
417
+ duplex: true
418
+ /** what a minute of the stream costs */
419
+ perMinute: number
420
+ /** the model asked to say `text` now */
421
+ say: (text: string) => string[]
422
+ /** the model asked for its first words, `text`, once its session started;
423
+ * the session it is set up with (`Setup.opens`) asks the same */
424
+ opens: (text: string) => string[]
425
+ /** the larger models it hands its work to on the provider's side
426
+ * (`Setup.backend`), the quickest first */
427
+ backends: string[]
428
+ /** a backend's tool call answered, and its work let go on */
429
+ result: (call: string, output: string) => string[]
430
+ }
431
+
432
+ let MEDIA: Record<Format['encoding'], string> = {
433
+ mp3: 'audio/mpeg',
434
+ mulaw: 'audio/basic',
435
+ linear16: 'audio/L16',
436
+ }
437
+
438
+ /** The bytes a second of raw audio takes, or undefined for a compressed one. */
439
+ export let perSecond = (format: Format): number | undefined =>
440
+ format.encoding == 'mulaw'
441
+ ? format.rate
442
+ : format.encoding == 'linear16'
443
+ ? format.rate * 2
444
+ : undefined
445
+
446
+ /** What speaking `text` costs, in dollars, by `model` (`speakerOf`). */
447
+ export let spoken = (
448
+ provider: Provider,
449
+ text: string,
450
+ model?: string | null,
451
+ ): number => text.length / 1000 * speakerOf(provider, model).perThousand
452
+
453
+ /** What hearing `seconds` of audio costs, in dollars, on a model priced by
454
+ * the minute: a provider's `hear`, or one of its `turns`. */
455
+ export let heard = (
456
+ priced: { perMinute: number },
457
+ seconds: number,
458
+ ): number => seconds / 60 * priced.perMinute
459
+
460
+ /** A provider's refusal: `status` is its HTTP status, and `retry` says a
461
+ * later try may go through (a 429 or 5xx, or no answer at all). */
462
+ export class SpeechError extends Error {
463
+ readonly status: number
464
+ readonly retry: boolean
465
+ constructor(message: string, status = 0) {
466
+ super(message)
467
+ this.name = 'SpeechError'
468
+ this.status = status
469
+ this.retry = status == 0 || status == 429 || status >= 500
470
+ }
471
+ }
472
+
473
+ /** Text spoken: the audio as it streams, its media type, and its cost. */
474
+ export type Spoken = {
475
+ body: ReadableStream<Uint8Array>
476
+ type: string
477
+ dollars: number
478
+ }
479
+
480
+ /** A recording heard: its words, its turns, its length, and its cost. */
481
+ export type Heard = {
482
+ text: string
483
+ turns: Turn[]
484
+ seconds: number
485
+ dollars: number
486
+ }
487
+
488
+ /** The seconds a stream heard, and what they cost. */
489
+ export type Spent = { seconds: number; dollars: number }
490
+
491
+ /** A stream being heard. */
492
+ export type Turns = {
493
+ send: (audio: Uint8Array) => void
494
+ /** the seconds heard so far, and what they cost */
495
+ spent: () => Spent
496
+ /** ends the stream at once: what it was still hearing is not told */
497
+ close: () => Spent
498
+ /** ends the stream once the provider has told every turn it heard, which
499
+ * it does before it closes */
500
+ end: () => Promise<Spent>
501
+ }
502
+
503
+ /** What a call to the provider needs. */
504
+ export type Calling = {
505
+ provider: Provider
506
+ key: string
507
+ fetch?: typeof fetch
508
+ signal?: AbortSignal
509
+ }
510
+
511
+ /** The provider's API, asked with the key; a refusal is a SpeechError. */
512
+ export let asking = (
513
+ { provider, key, fetch: given, signal }: Calling,
514
+ ): Ask =>
515
+ async (path, init = {}) => {
516
+ let response
517
+ try {
518
+ response = await (given ?? globalThis.fetch)(provider.api + path, {
519
+ ...init,
520
+ signal,
521
+ headers: {
522
+ [provider.header ?? 'authorization']: provider.authorization(key),
523
+ ...init.headers as Record<string, string>,
524
+ },
525
+ })
526
+ } catch (error) {
527
+ if (signal?.aborted) throw error
528
+ throw new SpeechError(`${provider.name} could not be reached: ${error}`)
529
+ }
530
+ if (response.ok) return response
531
+ let said = await response.text().catch(() => '')
532
+ throw new SpeechError(
533
+ `${provider.name} answered ${response.status} to ${path.split('?')[0]}: ${
534
+ said.slice(0, 300) || 'no reason given'
535
+ }`,
536
+ response.status,
537
+ )
538
+ }
539
+
540
+ /**
541
+ * `text` spoken: the audio as it streams from the provider, its media type,
542
+ * and what it cost. Raw samples come without a container, ready for a call.
543
+ *
544
+ * ```ts
545
+ * import { equal } from '@yaks/testing'
546
+ * import { DEEPGRAM, speak } from '@yaks/speech'
547
+ * let asked: string[] = []
548
+ * let fetch = (url: string | URL | Request) => {
549
+ * asked.push(String(url))
550
+ * return Promise.resolve(new Response(new Uint8Array([1, 2, 3])))
551
+ * }
552
+ * let said = await speak({
553
+ * provider: DEEPGRAM,
554
+ * key: 'k',
555
+ * text: 'Hello',
556
+ * format: { encoding: 'mulaw', rate: 8000 },
557
+ * fetch: fetch as typeof globalThis.fetch,
558
+ * })
559
+ * equal(said.type, 'audio/basic')
560
+ * equal(asked[0].includes('container=none'), true)
561
+ * ```
562
+ */
563
+ export let speak = async (
564
+ o: Calling & {
565
+ text: string
566
+ voice?: string
567
+ format?: Format
568
+ /** a multiple of the provider's pace (`paced`) */
569
+ speed?: number
570
+ /** one of the provider's `speak.models`, its first by default */
571
+ model?: string
572
+ },
573
+ ): Promise<Spoken> => {
574
+ let format = o.format ?? { encoding: 'mp3' }
575
+ let { speak } = o.provider
576
+ let { path, init } = speak.request(
577
+ o.text,
578
+ o.voice ?? speak.voice,
579
+ format,
580
+ paced(speak.speeds, o.speed),
581
+ speakerOf(o.provider, o.model).model,
582
+ )
583
+ let response = await asking(o)(path, init)
584
+ if (!response.body) {
585
+ throw new SpeechError(`${o.provider.name} returned no audio`, 502)
586
+ }
587
+ let audio = speak.audio?.(format)
588
+ let body = audio ? response.body.pipeThrough(audio) : response.body
589
+ return {
590
+ // A call's sentences are each a clip: none pauses for the provider's
591
+ // padding around it (`trimmed`).
592
+ body: format.encoding == 'mulaw'
593
+ ? body.pipeThrough(trimmed(format.rate))
594
+ : body,
595
+ type: MEDIA[format.encoding],
596
+ dollars: spoken(o.provider, o.text, o.model),
597
+ }
598
+ }
599
+
600
+ // What a provider that tells no speakers apart heard: one speaker's turn.
601
+ let alone = (text: string): Turn[] => text ? [{ speaker: 0, text }] : []
602
+
603
+ /**
604
+ * A recording heard whole: its words, its turns, how long it was, and what
605
+ * hearing it cost. A provider that tells speakers apart (`speakers`) answers
606
+ * a turn each time one of them speaks; one that cannot, the words as one
607
+ * speaker's.
608
+ *
609
+ * ```ts
610
+ * import { equal } from '@yaks/testing'
611
+ * import { hear, OPENAI } from '@yaks/speech'
612
+ * let fetch = () =>
613
+ * Promise.resolve(Response.json({ text: 'Hi there', usage: { seconds: 30 } }))
614
+ * let got = await hear({
615
+ * provider: OPENAI,
616
+ * key: 'k',
617
+ * audio: new Uint8Array([1]),
618
+ * type: 'audio/wav',
619
+ * fetch: fetch as typeof globalThis.fetch,
620
+ * })
621
+ * equal(got.turns, [{ speaker: 0, text: 'Hi there' }])
622
+ * equal(got.dollars, 0.00225)
623
+ * ```
624
+ */
625
+ export let hear = async (
626
+ o: Calling & { audio: BodyInit; type: string; seconds?: number },
627
+ ): Promise<Heard> => {
628
+ let { hear } = o.provider
629
+ let { path, init } = hear.request(o.audio, o.type, hear.model)
630
+ let said = hear.read(await (await asking(o)(path, init)).json())
631
+ let seconds = said.seconds ?? o.seconds ?? 0
632
+ return {
633
+ text: said.text,
634
+ turns: said.turns ?? alone(said.text),
635
+ seconds,
636
+ dollars: heard(hear, seconds),
637
+ }
638
+ }
639
+
640
+ /** The account's credit left, in dollars, or undefined where the provider
641
+ * does not say. */
642
+ export let balance = (o: Calling): Promise<number | undefined> =>
643
+ o.provider.balance?.(asking(o)) ?? Promise.resolve(undefined)
644
+
645
+ // The most pages of voices read: 2,000 voices at 100 a page.
646
+ let PAGES = 20
647
+
648
+ /**
649
+ * The voices the key's account speaks in, where the provider keeps them per
650
+ * account (ElevenLabs: its premade voices and the ones it designed, cloned or
651
+ * added), else the provider's own list.
652
+ *
653
+ * ```ts
654
+ * import { equal } from '@yaks/testing'
655
+ * import { DEEPGRAM, ELEVENLABS, voices } from '@yaks/speech'
656
+ * let pages = [
657
+ * { voices: [{ voice_id: 'a', name: 'A' }], has_more: true, next_page_token: 't' },
658
+ * { voices: [{ voice_id: 'b', name: 'B' }], has_more: false },
659
+ * ]
660
+ * let asked: string[] = []
661
+ * let fetch = (url: string | URL | Request, init?: RequestInit) => {
662
+ * asked.push(String(url) + ' ' + new Headers(init?.headers).get('xi-api-key'))
663
+ * return Promise.resolve(Response.json(pages.shift()))
664
+ * }
665
+ * let got = await voices({
666
+ * provider: ELEVENLABS,
667
+ * key: 'k',
668
+ * fetch: fetch as typeof globalThis.fetch,
669
+ * })
670
+ * equal(got.map((v) => v.id), ['a', 'b'])
671
+ * equal(asked[1].includes('next_page_token=t'), true)
672
+ * equal(asked[1].endsWith(' k'), true)
673
+ * equal((await voices({ provider: DEEPGRAM, key: 'k' })).length > 0, true)
674
+ * ```
675
+ */
676
+ export let voices = async (o: Calling): Promise<Voice[]> => {
677
+ let listed = o.provider.voices
678
+ if (!listed) return o.provider.speak.voices
679
+ let ask = asking(o), all: Voice[] = [], page: string | undefined
680
+ for (let n = 0; n < PAGES; n++) {
681
+ let { path, init } = listed.request(page)
682
+ let got = listed.read(await (await ask(path, init)).json())
683
+ all.push(...got.voices)
684
+ if (!(page = got.next)) break
685
+ }
686
+ return all
687
+ }
688
+
689
+ // What makes voices on `provider`, refused where it makes none.
690
+ let maker = (provider: Provider) => {
691
+ if (!provider.make) {
692
+ throw new SpeechError(`${provider.title} makes no voices of its own`, 400)
693
+ }
694
+ return provider.make
695
+ }
696
+
697
+ /**
698
+ * Voices designed from `description`, each a sample saying `text` (or words
699
+ * the provider picks), for one to be kept with `keep`.
700
+ *
701
+ * ```ts
702
+ * import { equal } from '@yaks/testing'
703
+ * import { design, ELEVENLABS } from '@yaks/speech'
704
+ * let fetch = () =>
705
+ * Promise.resolve(Response.json({
706
+ * previews: [{ generated_voice_id: 'g1', audio_base_64: 'AQID', duration_secs: 4 }],
707
+ * }))
708
+ * let got = await design({
709
+ * provider: ELEVENLABS,
710
+ * key: 'k',
711
+ * description: 'An old sea captain, gravelly and warm',
712
+ * fetch: fetch as typeof globalThis.fetch,
713
+ * })
714
+ * equal(got, [{ id: 'g1', audio: new Uint8Array([1, 2, 3]), type: 'audio/mpeg', seconds: 4 }])
715
+ * ```
716
+ */
717
+ export let design = async (
718
+ o: Calling & { description: string; text?: string },
719
+ ): Promise<Design[]> => {
720
+ let make = maker(o.provider)
721
+ let { path, init } = make.design(o.description, o.text)
722
+ return make.designs(await (await asking(o)(path, init)).json())
723
+ }
724
+
725
+ /** A design (`design`) kept as a voice of the account's, answering its id. */
726
+ export let keep = async (
727
+ o: Calling & { design: string; name: string; description: string },
728
+ ): Promise<string> => {
729
+ let make = maker(o.provider)
730
+ let { path, init } = make.keep(o.design, o.name, o.description)
731
+ return make.made(await (await asking(o)(path, init)).json())
732
+ }
733
+
734
+ /**
735
+ * A voice cloned from recordings of it, answering its id. A provider refuses
736
+ * one the account's plan does not allow, with its reason.
737
+ *
738
+ * ```ts
739
+ * import { equal } from '@yaks/testing'
740
+ * import { clone, ELEVENLABS } from '@yaks/speech'
741
+ * let sent: FormData | undefined
742
+ * let fetch = (_: unknown, init?: RequestInit) => {
743
+ * sent = init?.body as FormData
744
+ * return Promise.resolve(Response.json({ voice_id: 'v9' }))
745
+ * }
746
+ * let id = await clone({
747
+ * provider: ELEVENLABS,
748
+ * key: 'k',
749
+ * name: 'Narrator',
750
+ * samples: [new Blob([new Uint8Array([1])], { type: 'audio/mpeg' })],
751
+ * fetch: fetch as typeof globalThis.fetch,
752
+ * })
753
+ * equal([id, sent?.get('name'), sent?.getAll('files').length], ['v9', 'Narrator', 1])
754
+ * ```
755
+ */
756
+ export let clone = async (
757
+ o: Calling & { name: string; samples: Blob[]; description?: string },
758
+ ): Promise<string> => {
759
+ let make = maker(o.provider)
760
+ let { path, init } = make.clone(o.name, o.samples, o.description)
761
+ return make.made(await (await asking(o)(path, init)).json())
762
+ }
763
+
764
+ /** The socket a stream speaks over: the platform's WebSocket, or a stand-in. */
765
+ export type Socket = {
766
+ send: (data: string | Uint8Array) => void
767
+ close: (code?: number, reason?: string) => void
768
+ addEventListener: (
769
+ type: 'open' | 'message' | 'close' | 'error',
770
+ listener: (event: { data?: unknown; code?: number }) => void,
771
+ ) => void
772
+ }
773
+
774
+ /** How a stream's key is offered: as a header where the platform's sockets
775
+ * take one, else as subprotocols. */
776
+ export type Keyed = { authorization: string; protocols: string[] }
777
+
778
+ /** What makes a stream's socket. */
779
+ export type Open = (url: string, key: Keyed) => Socket
780
+
781
+ let browser: Open = (url, { protocols }) =>
782
+ new WebSocket(url, protocols) as unknown as Socket
783
+
784
+ // A socket to `url` that holds what is sent until it opens, sends `opening`
785
+ // first, and says once if it fails or closes before `close` or `end` is
786
+ // asked. `end` sends `last` and waits for the other side to close, its
787
+ // messages heard until then.
788
+ let stream = (
789
+ o: { provider: Provider; key: string; open?: Open },
790
+ url: string,
791
+ opening: string[],
792
+ heard: (data: unknown) => void,
793
+ lost: (reason: string, clean?: boolean) => void,
794
+ ) => {
795
+ let socket = (o.open ?? browser)(url, {
796
+ authorization: o.provider.authorization(o.key),
797
+ protocols: o.provider.protocols(o.key),
798
+ })
799
+ let ready = false, closing = false
800
+ let waiting: (string | Uint8Array)[] = [...opening]
801
+ let shut: () => void
802
+ let gone = new Promise<void>((resolve) => shut = resolve)
803
+ socket.addEventListener('open', () => {
804
+ ready = true
805
+ for (let part of waiting.splice(0)) socket.send(part)
806
+ })
807
+ socket.addEventListener('message', (event) => heard(event.data))
808
+ let dropped = (reason: string) => (event?: { code?: number }) => {
809
+ if (!closing) lost(reason, event?.code == 1000 || event?.code == 1001)
810
+ closing = true
811
+ shut()
812
+ }
813
+ socket.addEventListener('close', dropped('the stream closed'))
814
+ socket.addEventListener('error', dropped('the stream failed'))
815
+ let close = (last?: string) => {
816
+ if (closing) return
817
+ closing = true
818
+ try {
819
+ if (ready && last) socket.send(last)
820
+ socket.close(1000)
821
+ } catch {
822
+ // A socket already gone has nothing more to close.
823
+ }
824
+ shut()
825
+ }
826
+ return {
827
+ closed: () => closing,
828
+ send: (data: string | Uint8Array) => {
829
+ if (closing) return
830
+ if (ready) socket.send(data)
831
+ else waiting.push(data)
832
+ },
833
+ close,
834
+ end: (last: string) => {
835
+ if (closing) return gone
836
+ closing = true
837
+ if (ready) socket.send(last)
838
+ else waiting.push(last)
839
+ return gone
840
+ },
841
+ }
842
+ }
843
+
844
+ /** What a stream tells as a speaker talks. */
845
+ export type Told = {
846
+ /** they started talking: whatever is playing to them should stop */
847
+ start?: () => void
848
+ /** their words so far in one utterance, empty if it was discarded */
849
+ hearing?: (text: string, key?: string) => void
850
+ /** they finished a turn: what they said, who said it and when */
851
+ end: (turn: Turn) => void
852
+ /** the stream failed or closed before `close` was asked */
853
+ lost?: (reason: string) => void
854
+ }
855
+
856
+ /**
857
+ * Audio heard as it streams, told back a turn at a time (`told`), by
858
+ * `model`, one of the provider's `turns` (its first by default). `send`
859
+ * takes raw samples in `format`; `close` ends the stream and answers how
860
+ * many seconds were heard and what they cost, and `end` answers the same
861
+ * once the provider has told the turns it was still hearing. `open` makes
862
+ * the socket, the platform's WebSocket by default, offering the key as
863
+ * subprotocols.
864
+ */
865
+ export let turns = (
866
+ o: {
867
+ provider: Provider
868
+ key: string
869
+ format: Raw
870
+ told: Told
871
+ model?: string
872
+ open?: Open
873
+ },
874
+ ): Turns => {
875
+ let t = streamOf(o.provider, o.model)
876
+ let read = t.reader()
877
+ let bytes = 0
878
+ let s = stream(
879
+ o,
880
+ o.provider.live + t.path(o.format, t.model),
881
+ t.opening(o.format, t.model),
882
+ (data) => {
883
+ let cue = read(data)
884
+ if (cue.start) o.told.start?.()
885
+ if (cue.hearing) o.told.hearing?.(cue.hearing.text, cue.hearing.key)
886
+ for (let turn of cue.ended ?? []) {
887
+ if (turn.text) o.told.end(turn)
888
+ else o.told.hearing?.('', turn.key)
889
+ }
890
+ if (cue.error) o.told.lost?.(cue.error)
891
+ },
892
+ (reason) => o.told.lost?.(reason),
893
+ )
894
+ let spent = () => {
895
+ let seconds = bytes / perSecond(o.format)!
896
+ return { seconds, dollars: heard(t, seconds) }
897
+ }
898
+ return {
899
+ send: (audio) => {
900
+ if (s.closed()) return
901
+ bytes += audio.length
902
+ s.send(t.audio(audio))
903
+ },
904
+ spent,
905
+ close: () => {
906
+ s.close(t.closing)
907
+ return spent()
908
+ },
909
+ end: async () => {
910
+ if (t.closing) await s.end(t.closing)
911
+ else s.close()
912
+ return spent()
913
+ },
914
+ }
915
+ }
916
+
917
+ /** Words supplied to a talking model, with their author where known. */
918
+ export type Words = string | { text: string; from: string }
919
+
920
+ let wording = (words: Words, from = 'the system'): string =>
921
+ message({
922
+ kind: 'user',
923
+ text: typeof words == 'string' ? words : words.text,
924
+ }, typeof words == 'string' ? from : words.from).text
925
+
926
+ /** What a talk stream tells as the caller and the model speak. */
927
+ export type Talked = {
928
+ /** the caller talked over the model: whatever is playing should stop */
929
+ over?: () => void
930
+ /** the caller stopped talking, `ago` seconds before now (none: now); the
931
+ * model's answer is on its way */
932
+ stopped?: (ago?: number) => void
933
+ /** the caller's words so far in one utterance, empty if discarded */
934
+ hearing?: (text: string, key?: string) => void
935
+ /** what the caller said, once heard */
936
+ heard?: (text: string, key?: string) => void
937
+ /** audio to play to the caller */
938
+ audio: (bytes: Uint8Array) => void
939
+ /** what the model said, once said */
940
+ said?: (text: string) => void
941
+ /** a tool the model asked for, answered with its output */
942
+ call: (name: string, args: string, speaking?: boolean) => Promise<Words>
943
+ /** work a duplex model handed over: what the caller asked, in their
944
+ * words, answered with what to tell them */
945
+ delegate?: (request: string, speaking?: boolean) => Promise<Words>
946
+ /** the model's response ended, whatever it said or asked in it */
947
+ done?: () => void
948
+ /** the model's audio began playing, on a call its own line carries */
949
+ plays?: () => void
950
+ /** the call a joined stream steers ended: its stream closed cleanly */
951
+ ended?: () => void
952
+ /** the stream failed or closed before `close` was asked */
953
+ lost?: (reason: string) => void
954
+ /** a duplex model refused something it was sent, its stream still open */
955
+ refused?: (reason: string) => void
956
+ }
957
+
958
+ /** A talk stream: audio in, the model's audio and words out. */
959
+ export type Talk = {
960
+ send: (audio: Uint8Array) => void
961
+ /** ask the model to say `text` */
962
+ say: (text: string, from?: string) => void
963
+ /** tell the model something it knows from now on, saying nothing of it */
964
+ tell: (text: string, from?: string) => void
965
+ /** the seconds heard so far, and what the stream cost */
966
+ spent: () => { seconds: number; dollars: number }
967
+ /** end the stream; what it cost */
968
+ close: () => { seconds: number; dollars: number }
969
+ }
970
+
971
+ // What a caller says to show they are listening, not to be heard: a sound
972
+ // of these alone, while the model speaks, lets it go on.
973
+ let FILLERS = new Set(
974
+ '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'
975
+ .split(' '),
976
+ )
977
+
978
+ // The words a sentence goes on after: articles, prepositions, conjunctions,
979
+ // possessives, "is", and the fillers of a caller thinking.
980
+ let ON = new Set(
981
+ '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'
982
+ .split(' '),
983
+ )
984
+
985
+ let words = (text: string) =>
986
+ text.toLowerCase().split(/\s+/).map((w) => w.replace(/[^a-z]/g, ''))
987
+ .filter(Boolean)
988
+
989
+ /** Whether `text` holds a word a transcript may have made of `name`, which
990
+ * it mishears even when told to expect it: one of the same letters where
991
+ * `name` has consonants, and any vowels where it has vowels ("Amber" for
992
+ * "Ember"). A name of fewer than three consonants sounds like too many words
993
+ * to be told apart this way.
994
+ *
995
+ * ```ts
996
+ * import { equal } from '@yaks/testing'
997
+ * import { heardAs } from '@yaks/speech'
998
+ * let heard = ['Thanks, Amber.', 'ember, you there?', 'remember the barn',
999
+ * 'Embers']
1000
+ * equal(heard.map((t) => heardAs(t, 'Ember')), [true, true, false, false])
1001
+ * equal(heardAs('Eve said so', 'Ava'), false)
1002
+ * ```
1003
+ */
1004
+ export let heardAs = (text: string, name: string): boolean => {
1005
+ let shape = (w: string) => w.replace(/[aeiouy]/g, '_')
1006
+ let want = shape(words(name).join(''))
1007
+ return want.replaceAll('_', '').length >= 3 &&
1008
+ words(text).some((w) => shape(w) == want)
1009
+ }
1010
+
1011
+ /** How many of `text`'s words say something, the `FILLERS` aside.
1012
+ *
1013
+ * ```ts
1014
+ * import { equal } from '@yaks/testing'
1015
+ * import { meant } from '@yaks/speech'
1016
+ * equal(meant(' Okay. Ha. Cool, uh'), 0)
1017
+ * equal(meant('Okay, hold on'), 2)
1018
+ * ```
1019
+ */
1020
+ export let meant = (text: string): number =>
1021
+ words(text).filter((w) => !FILLERS.has(w)).length
1022
+
1023
+ /** Whether `text` stops where a sentence goes on: on a comma or a dash, or
1024
+ * on a word a sentence goes on after (`ON`: "the", "to", "is", "um"). A caller
1025
+ * heard to stop there has more to say.
1026
+ *
1027
+ * ```ts
1028
+ * import { equal } from '@yaks/testing'
1029
+ * import { open } from '@yaks/speech'
1030
+ * let lines = ['My address is', 'So what I need is, um', 'Okay,', 'Okay.',
1031
+ * 'Forty-two Elm Street.', 'Can you come out tomorrow?', '']
1032
+ * equal(lines.map(open), [true, true, true, false, false, false, false])
1033
+ * ```
1034
+ */
1035
+ export let open = (text: string): boolean => {
1036
+ let w = words(text)
1037
+ return !!w.length && (/[,\-–—…]\s*$/.test(text) || ON.has(w.at(-1)!))
1038
+ }
1039
+
1040
+ // The words a caller says over the model before it stops: fewer, or only
1041
+ // fillers, and it goes on. Two say "wait, stop" or "hold on".
1042
+ let OVER = 2
1043
+
1044
+ // The seconds a caller is quiet before their turn ends, when the model has
1045
+ // not heard it end: it waits on some whole sentences, and on a lone "Okay.".
1046
+ // One going on ("Okay, so…") is mostly talking again by then.
1047
+ let QUIET = 0.7
1048
+
1049
+ // The seconds a turn left unanswered waits for more before it is answered,
1050
+ // longer than a caller's pause to think.
1051
+ let LONG = 5
1052
+
1053
+ // The seconds a duplex model is quiet after its first words before they are
1054
+ // over: gpt-live-1 paused up to 0.4 s between a greeting's sentences. And the
1055
+ // seconds a line waits for a call's first words to begin before the caller
1056
+ // is heard anyway.
1057
+ let PAUSED = 0.6
1058
+ let SILENT = 6
1059
+
1060
+ /**
1061
+ * A call's first words, such as its greeting, said before the caller is
1062
+ * heard: a hello of theirs said over them, or the sound of the line picking
1063
+ * up, is no turn to answer. `said` takes the words' audio as it is given to
1064
+ * the line, which may be faster than it plays, and `done` that it is all
1065
+ * given. `heard` takes the caller's audio a frame at a time, as the line
1066
+ * sends it, and answers what whoever listens should hear: a quiet line
1067
+ * (`muted`) until the words have played, which they have once the line has
1068
+ * run as long as they last. Words not begun in 6 s are given up, and the
1069
+ * caller is heard.
1070
+ *
1071
+ * ```ts
1072
+ * import { equal } from '@yaks/testing'
1073
+ * import { first, sounds } from '@yaks/speech'
1074
+ * let mulaw = { encoding: 'mulaw', rate: 8000 } as const
1075
+ * let words = first(mulaw)
1076
+ * let hello = (seconds: number) =>
1077
+ * sounds(words.heard(new Uint8Array(seconds * 8000).fill(0x10)), mulaw)
1078
+ * equal(hello(0.5), false)
1079
+ * words.said(new Uint8Array(8000))
1080
+ * words.done()
1081
+ * equal([hello(0.5), hello(0.5), hello(1)], [false, true, true])
1082
+ * ```
1083
+ */
1084
+ export let first = (format: Raw): {
1085
+ said: (audio: Uint8Array) => void
1086
+ done: () => void
1087
+ heard: (audio: Uint8Array) => Uint8Array
1088
+ } => {
1089
+ let seconds = (audio: Uint8Array) => audio.length / perSecond(format)!
1090
+ // The seconds of them given, the seconds the line ran before them and
1091
+ // since, whether they are all given, and whether they have played.
1092
+ let spoken = 0, waited = 0, played = 0, done = false, over = false
1093
+ return {
1094
+ said: (audio) => void (done || (spoken += seconds(audio))),
1095
+ done: () => void (done = true),
1096
+ heard: (audio) => {
1097
+ if (over) return audio
1098
+ if (spoken) played += seconds(audio)
1099
+ else waited += seconds(audio)
1100
+ over = done ? played >= spoken : waited >= SILENT
1101
+ return over ? audio : muted(audio, format)
1102
+ },
1103
+ }
1104
+ }
1105
+
1106
+ // The stream's own tools. With `LISTEN` the model says nothing this turn,
1107
+ // while the caller has more to say. With `HUSH` it only listens from then
1108
+ // on: each turn is put to it as a choice of tools, never words, so it says
1109
+ // nothing (`LISTEN`) until it calls `ANSWER`, or `TALK` to stop listening.
1110
+ let LISTEN = {
1111
+ name: 'listen',
1112
+ description:
1113
+ '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.',
1114
+ parameters: { type: 'object', properties: {} },
1115
+ }
1116
+
1117
+ let HUSH = {
1118
+ name: 'stay_silent',
1119
+ description:
1120
+ '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.',
1121
+ parameters: { type: 'object', properties: {} },
1122
+ }
1123
+
1124
+ let ANSWER = {
1125
+ name: 'answer',
1126
+ description:
1127
+ '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.',
1128
+ parameters: { type: 'object', properties: {} },
1129
+ }
1130
+
1131
+ let TALK = {
1132
+ name: 'talk',
1133
+ description:
1134
+ 'While you only listen, they asked you to stop only listening and talk with them as before. Call it, then answer them.',
1135
+ parameters: { type: 'object', properties: {} },
1136
+ }
1137
+
1138
+ // What a model that only listens is told with each turn put to it.
1139
+ let HEEDING =
1140
+ '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.'
1141
+
1142
+ /** How a talking model is set up: its model, voice, pace, instructions and
1143
+ * tools, each its provider's own where none is given. */
1144
+ export type Talking = {
1145
+ model?: string
1146
+ voice?: string
1147
+ /** a multiple of the provider's pace (`paced`) */
1148
+ speed?: number
1149
+ instructions: string
1150
+ tools?: Setup['tools']
1151
+ /** its first words, said as the stream opens: the model is asked for them
1152
+ * once, and the caller's audio reaches it as a quiet line until they have
1153
+ * played, so a sound made as the call is picked up, or a hello said over
1154
+ * them, is no turn it answers */
1155
+ opens?: string
1156
+ /** Keep listening while the opening words play. */
1157
+ interruptible?: boolean
1158
+ /** a duplex model's larger model on the provider's side (`Setup.backend`) */
1159
+ backend?: Backend
1160
+ /** words its hearing should expect, such as the names it is called by */
1161
+ words?: string[]
1162
+ /** whether words heard are said to the model, such as naming it: while it
1163
+ * listens, a turn they end is answered in words */
1164
+ addressed?: (words: string) => boolean
1165
+ /** a turned model only listens (`HUSH`), always, as in a room of several
1166
+ * people: each turn is put to it as a choice of tools, and it speaks only
1167
+ * by calling `ANSWER` */
1168
+ listening?: boolean
1169
+ }
1170
+
1171
+ type Calls = NonNullable<Talker['calls']>
1172
+
1173
+ /** The entry of `provider`'s that talks with `model`, or with its first
1174
+ * model when none is given, if any. */
1175
+ export let talkerOf = (
1176
+ provider: Provider,
1177
+ model?: string,
1178
+ ): Talker | undefined =>
1179
+ model == undefined
1180
+ ? provider.talk?.[0]
1181
+ : provider.talk?.find((t) => t.models.includes(model))
1182
+
1183
+ let talker = (provider: Provider, model?: string): Talker => {
1184
+ let t = talkerOf(provider, model)
1185
+ if (!t) {
1186
+ throw new Error(`${provider.name} has no model ${model ?? ''} that talks`)
1187
+ }
1188
+ return t
1189
+ }
1190
+
1191
+ // The stream's own `LISTEN` and `HUSH` come first among a turned model's
1192
+ // tools, `HUSH` where it does not always listen; a duplex model's tools are
1193
+ // whoever runs the call.
1194
+ let setup = (
1195
+ t: Talker,
1196
+ o: Talking,
1197
+ format?: Raw,
1198
+ ): Setup => ({
1199
+ model: o.model ?? t.models[0],
1200
+ voice: o.voice ?? t.voice,
1201
+ format,
1202
+ speed: paced(t.speeds, o.speed),
1203
+ instructions: wording(o.instructions) +
1204
+ '\n\nMessages name their source. Source labels are context for you; never read them aloud.',
1205
+ tools: t.duplex
1206
+ ? []
1207
+ : [LISTEN, ...o.listening ? [] : [HUSH], ...o.tools ?? []],
1208
+ ...o.opens ? { opens: o.opens } : {},
1209
+ ...o.words?.length ? { words: o.words } : {},
1210
+ ...t.duplex && o.backend
1211
+ ? {
1212
+ backend: { ...o.backend, instructions: wording(o.backend.instructions) },
1213
+ }
1214
+ : {},
1215
+ })
1216
+
1217
+ let carrier = (provider: Provider, model?: string): Calls => {
1218
+ let calls = talker(provider, model).calls
1219
+ if (!calls) throw new Error(`${provider.name}'s line carries no calls`)
1220
+ return calls
1221
+ }
1222
+
1223
+ let calling = async (o: Calling, { path, init }: Asked): Promise<void> => {
1224
+ await asking(o)(path, init)
1225
+ }
1226
+
1227
+ /** A call the provider's own line carries picked up, its model set up as
1228
+ * `talk` sets one up; `talk` with the `call` then joins it. */
1229
+ export let accept = (
1230
+ o: Calling & Talking & { call: string },
1231
+ ): Promise<void> =>
1232
+ calling(
1233
+ o,
1234
+ carrier(o.provider, o.model).accept(
1235
+ o.call,
1236
+ setup(talker(o.provider, o.model), o),
1237
+ ),
1238
+ )
1239
+
1240
+ /** A call the provider's own line carries, refused before it is picked up. */
1241
+ export let reject = (o: Calling & { call: string }): Promise<void> =>
1242
+ calling(o, carrier(o.provider).reject(o.call))
1243
+
1244
+ /** A call the provider's own line carries, ended. */
1245
+ export let hangup = (o: Calling & { call: string }): Promise<void> =>
1246
+ calling(o, carrier(o.provider).hangup(o.call))
1247
+
1248
+ /**
1249
+ * A model that hears and speaks in one stream: `send` takes the caller's raw
1250
+ * samples in `format`, and `told` hears what the model says back and the
1251
+ * tools it asks for, each answered with its output before it goes on. The
1252
+ * provider's `talk` entry for `model` says how (its first model by default);
1253
+ * one without it refuses.
1254
+ *
1255
+ * Given `opens`, the model's first words, it is asked for them as the stream
1256
+ * opens, and the caller's audio reaches it as a quiet line (`muted`) until
1257
+ * they have played: what the caller says over them, a hello or the sound of
1258
+ * picking up, is no turn the model answers with a greeting of its own. A
1259
+ * model that never begins them hears the caller after `SILENT`. A call its
1260
+ * own line carries is asked for them too, its audio heard throughout.
1261
+ *
1262
+ * Asked to say given words (`opens`, `say`), a `Turned` model answers with
1263
+ * no tool, and only its answer plays: a part it says before the answer
1264
+ * (`Said.aside`) would be the words a second time.
1265
+ *
1266
+ * A `Duplex` model takes its own turns and hands its work to
1267
+ * `told.delegate`; what it is asked to `say` while the caller talks is sent
1268
+ * once they are `QUIET`. Everything below is for a `Turned` one, which
1269
+ * takes a turn as it is told here.
1270
+ *
1271
+ * A caller who talks over the model stops it (`over`) once their words say
1272
+ * something (`meant`): an "okay", a laugh, or a noise, lets it go on. The
1273
+ * model writes its audio faster than it is said, so what it says is mostly
1274
+ * still playing, its response long done, when the caller talks.
1275
+ *
1276
+ * The caller's turn ends when the model hears it end, or once they are
1277
+ * `QUIET`, and is answered. What the model says to it waits for the caller's
1278
+ * words, and is never said when they stopped where a sentence goes on
1279
+ * (`open`), when the model asks to `LISTEN`, or when the caller talks again
1280
+ * before it plays. A turn left unanswered is answered once they have been
1281
+ * quiet `LONG`.
1282
+ *
1283
+ * Asked to stay silent (`HUSH`), or always (`listening`), the model only
1284
+ * listens: each turn is still put to it once its words are heard, but as a
1285
+ * choice of tools, never words, so it keeps hearing and may work without a
1286
+ * word, and nothing is said until it calls `ANSWER`; a turn left unanswered
1287
+ * stays so. A turn whose words are said to it (`addressed`) is answered.
1288
+ *
1289
+ * Given a `call` its own line carries, picked up with `accept`, the stream
1290
+ * joins that call instead: the caller's audio and the model's go over the
1291
+ * line, never through `send` or `told.audio`, and what plays is stopped on
1292
+ * the line; `told.plays` says when the model's audio begins, and
1293
+ * `told.ended` when the call ends. Its audio never heard here, a turn ends
1294
+ * only when the model hears it end, and what the model says plays before
1295
+ * the turn's words are heard.
1296
+ */
1297
+ export let talk = (
1298
+ o: Talking & {
1299
+ provider: Provider
1300
+ key: string
1301
+ /** the caller's audio, on a stream that carries it */
1302
+ format?: Raw
1303
+ /** the call a stream joins, one the provider's own line carries */
1304
+ call?: string
1305
+ told: Talked
1306
+ open?: Open
1307
+ time?: Clock
1308
+ },
1309
+ ): Talk => {
1310
+ let t = talker(o.provider, o.model)
1311
+ return t.duplex ? duplexed(o, t) : turned(o, t)
1312
+ }
1313
+
1314
+ /** What a talk stream is opened with. */
1315
+ type Talks = Parameters<typeof talk>[0]
1316
+
1317
+ // A model that takes a turn when asked: the caller's turn is ended, each
1318
+ // response asked for, and the response stopped when they talk over it, here.
1319
+ let turned = (o: Talks, t: Talker & Turned): Talk => {
1320
+ let set = setup(t, o, o.format)
1321
+ let model = set.model
1322
+ let joined = o.call == undefined ? undefined : carrier(o.provider, model)
1323
+ let seconds = (bytes: number) => o.format ? bytes / perSecond(o.format)! : 0
1324
+ let bytes = 0, dollars = 0
1325
+ // The model answers one response at a time: one asked for while another is
1326
+ // under way waits for it to be done. `last` is the one asked for last, asked
1327
+ // again if it was refused; waiting asks to go on are one.
1328
+ let busy = false, last: string | undefined
1329
+ let waiting: string[] = [], going = t.respond()
1330
+ // Whether the model only listens, which it asks for with `HUSH` and
1331
+ // stops with `TALK`, or does always; and how a turn is put to it then.
1332
+ let listens = false
1333
+ let listening = () => !!o.listening || listens
1334
+ let heeding = t.respond({
1335
+ tools: [LISTEN, ANSWER, ...o.listening ? [] : [TALK], ...o.tools ?? []],
1336
+ call: true,
1337
+ instructions: `${set.instructions}\n\n${HEEDING}`,
1338
+ })
1339
+ // While it listens, a turn whose words are said to it (`addressed`) is
1340
+ // answered in words, and any other put to it as a choice of tools, once
1341
+ // its words are heard (`awaiting`). Whether the turn is being answered,
1342
+ // so a tool's output is followed by words; and whether the response under
1343
+ // way is a choice of tools, whose words, if any, are never said.
1344
+ // A turn said to it that it let go on, such as its name alone, or one
1345
+ // whose words stop where a sentence goes on ("Ember,"), carries to the
1346
+ // next (`called`).
1347
+ let awaiting = false, answering = false, choosing = false, called = false
1348
+ let put = () => {
1349
+ let to = called || !!o.addressed?.(heard)
1350
+ let m = !listening() || to ? going : heeding
1351
+ answering = m == going
1352
+ called = false
1353
+ ask(pending = m)
1354
+ }
1355
+ // The responses asked to say given words, and whether the one under way
1356
+ // is one. Such a response plays its answer alone: what the model says
1357
+ // before it (`aside`) is the words a second time, or words of its own.
1358
+ let scripts = new Set<string>(), scripted = false
1359
+ let asides = new Set<string>()
1360
+ let script = (text: string) => {
1361
+ let m = t.respond({ text })
1362
+ scripts.add(m)
1363
+ ask(m)
1364
+ }
1365
+ // What the caller has said since they started talking, whether it stopped
1366
+ // the model, and whether the response it stopped is still sending audio.
1367
+ let hearing = '', over = false, hushed = false
1368
+ let partials = new Map<string, string>()
1369
+ // Whether the caller's turn ended, whether they spoke since it last did,
1370
+ // and for how many seconds their audio has been quiet. `heard` is their
1371
+ // words last heard; `unheard`, that the turn's are still to come.
1372
+ let ended = true, spoke = false, quiet = 0, heard = '', unheard = false
1373
+ // The ask for the turn's answer while it is not yet played or asked of a
1374
+ // tool, and whether the turn was left unanswered. What the model says while
1375
+ // the turn's words are `unheard` is `held`: each thing to do once they are,
1376
+ // and to do instead if it is never said.
1377
+ let pending: string | undefined, unanswered = false
1378
+ let held: { run: () => void; drop?: () => void }[] | undefined
1379
+ let out = (run: () => void, drop?: () => void) =>
1380
+ held ? held.push({ run, drop }) : run()
1381
+ // Its first words (`opens`), on a stream that carries the caller's audio,
1382
+ // which the model writes faster than they are said.
1383
+ let opens = o.opens && o.format && !o.interruptible
1384
+ ? first(o.format)
1385
+ : undefined
1386
+ let end = () => {
1387
+ if (ended) return
1388
+ ended = true
1389
+ if (spoke) spoke = false, unheard = true
1390
+ if (unheard) held = []
1391
+ o.told.stopped?.()
1392
+ if (!unheard && open(heard)) return void (unanswered = true)
1393
+ if (unheard && listening()) return void (awaiting = true)
1394
+ put()
1395
+ }
1396
+ let soon = () => {
1397
+ if (!ended && quiet >= QUIET) s.send(t.commit), end()
1398
+ if (unanswered && !listening() && quiet >= LONG) {
1399
+ unanswered = false
1400
+ ask(pending = t.respond({ tools: o.tools ?? [] }))
1401
+ }
1402
+ }
1403
+ // The turn's answer is not said: what is held is dropped, the ask still
1404
+ // waiting is not sent, and the response under way is stopped.
1405
+ let withdraw = () => {
1406
+ for (let h of held ?? []) h.drop?.()
1407
+ let m = pending!
1408
+ held = pending = undefined
1409
+ if (waiting.includes(m)) waiting.splice(waiting.indexOf(m), 1)
1410
+ else if (busy && last == m) s.send(t.cancel), hushed = true
1411
+ if (joined) s.send(joined.hush)
1412
+ }
1413
+ let ask = (m: string) => {
1414
+ let on = m == going || m == heeding
1415
+ if (!on || !waiting.includes(m)) waiting.push(m)
1416
+ next()
1417
+ }
1418
+ let next = () => {
1419
+ if (busy || !waiting.length) return
1420
+ busy = true
1421
+ s.send(last = waiting.shift()!)
1422
+ }
1423
+ let s = stream(
1424
+ o,
1425
+ o.provider.live + (joined ? joined.join(o.call!) : t.path(model)),
1426
+ joined ? [] : t.opening(set),
1427
+ (data) => {
1428
+ for (let said of t.read(data, model)) {
1429
+ if (said.start) {
1430
+ if (pending) withdraw()
1431
+ hearing = '', spoke = true, awaiting = false
1432
+ over = ended = unanswered = false
1433
+ }
1434
+ // Their words still heard once their turn ended are its own.
1435
+ if (said.hearing) {
1436
+ hearing += said.hearing
1437
+ let text = hearing
1438
+ if (o.told.hearing && said.key) {
1439
+ text = (partials.get(said.key) ?? '') + said.hearing
1440
+ partials.set(said.key, text)
1441
+ }
1442
+ o.told.hearing?.(text, said.key)
1443
+ }
1444
+ if (said.hearing && !ended && !over && meant(hearing) >= OVER) {
1445
+ over = true
1446
+ if (busy) s.send(t.cancel), hushed = true
1447
+ if (joined) s.send(joined.hush)
1448
+ o.told.over?.()
1449
+ }
1450
+ if (said.stopped) end()
1451
+ if (said.heard != undefined) {
1452
+ if (said.key) partials.delete(said.key)
1453
+ if (said.heard) o.told.heard?.(said.heard, said.key)
1454
+ else o.told.hearing?.('', said.key)
1455
+ heard = said.heard, unheard = false
1456
+ if (listening() && o.addressed?.(heard)) called = true
1457
+ if (pending && open(heard)) withdraw(), unanswered = true
1458
+ if (awaiting && !open(heard)) put()
1459
+ awaiting = false
1460
+ let h = held ?? []
1461
+ held = undefined
1462
+ for (let { run } of h) run()
1463
+ }
1464
+ if (said.aside) asides.add(said.aside)
1465
+ let spare = choosing ||
1466
+ scripted && said.of != undefined && asides.has(said.of)
1467
+ let audio = spare ? undefined : said.audio
1468
+ if (audio) opens?.said(audio)
1469
+ if (audio && !hushed) {
1470
+ out(() => (pending = undefined, o.told.audio(audio)))
1471
+ }
1472
+ let text = spare || !said.said ? '' : spokenProse(said.said)
1473
+ if (text) out(() => o.told.said?.(text))
1474
+ if (said.plays) o.told.plays?.()
1475
+ if (said.spent) dollars += said.spent
1476
+ if (said.begun) {
1477
+ busy = true
1478
+ scripted = scripts.has(last!)
1479
+ choosing = last == heeding
1480
+ if (hushed) s.send(t.cancel)
1481
+ }
1482
+ if (said.busy && last) waiting.unshift(last), busy = true
1483
+ if (said.done) {
1484
+ out(() => o.told.done?.(), () => o.told.done?.())
1485
+ busy = hushed = false
1486
+ opens?.done()
1487
+ next()
1488
+ }
1489
+ if (said.error) o.told.lost?.(said.error)
1490
+ let call = said.call
1491
+ if (call?.name == LISTEN.name) {
1492
+ called = listening() && answering
1493
+ if (pending) withdraw(), unanswered = true
1494
+ for (let m of t.answer(call.id, wording('Listening.'))) s.send(m)
1495
+ } else if (call?.name == HUSH.name) {
1496
+ listens = true
1497
+ if (pending) withdraw()
1498
+ let told = 'Silent: you only listen until you are addressed.'
1499
+ for (let m of t.answer(call.id, wording(told))) s.send(m)
1500
+ } else if (call?.name == ANSWER.name || call?.name == TALK.name) {
1501
+ // Asked to speak while it only listens, it is asked for its words.
1502
+ if (call.name == TALK.name) listens = false
1503
+ answering = true
1504
+ let speak = () => {
1505
+ for (let m of t.answer(call.id, wording('Say it now.'))) s.send(m)
1506
+ ask(pending = going)
1507
+ }
1508
+ out(speak, () => {
1509
+ let output = wording('Not asked: they went on talking.')
1510
+ for (let m of t.answer(call.id, output)) s.send(m)
1511
+ })
1512
+ } else if (call) {
1513
+ let answer = (output: Words, more = true) => {
1514
+ for (
1515
+ let m of t.answer(
1516
+ call.id,
1517
+ wording(output, `the ${call.name} tool`),
1518
+ )
1519
+ ) s.send(m)
1520
+ // While it listens, work on a turn it is not answering is
1521
+ // done without a word.
1522
+ if (more && (answering || !listening())) ask(going)
1523
+ }
1524
+ out(
1525
+ () => {
1526
+ pending = undefined
1527
+ o.told.call(call.name, call.args, answering || !listening())
1528
+ .catch((error) => ({
1529
+ text: `That did not work: ${error?.message ?? error}`,
1530
+ from: 'the system',
1531
+ }))
1532
+ .then(answer)
1533
+ },
1534
+ () =>
1535
+ answer({
1536
+ text: 'Not asked: they went on talking.',
1537
+ from: 'the system',
1538
+ }, false),
1539
+ )
1540
+ }
1541
+ }
1542
+ },
1543
+ (reason, clean) =>
1544
+ joined && clean ? o.told.ended?.() : o.told.lost?.(reason),
1545
+ )
1546
+ if (o.opens) script(o.opens)
1547
+ return {
1548
+ send: (audio) => {
1549
+ if (s.closed() || !o.format) return
1550
+ bytes += audio.length
1551
+ if (opens) audio = opens.heard(audio)
1552
+ s.send(t.audio(audio))
1553
+ if (!sounds(audio, o.format)) {
1554
+ quiet += seconds(audio.length)
1555
+ return soon()
1556
+ }
1557
+ // Talking again before the answer plays, the caller is not done.
1558
+ quiet = 0
1559
+ if (pending) withdraw(), ended = false
1560
+ },
1561
+ say: (text, from) => script(wording(text, from)),
1562
+ tell: (text, from) => {
1563
+ for (let m of t.tell(wording(text, from))) s.send(m)
1564
+ },
1565
+ spent: () => ({ seconds: seconds(bytes), dollars }),
1566
+ close: () => {
1567
+ s.close()
1568
+ return { seconds: seconds(bytes), dollars }
1569
+ },
1570
+ }
1571
+ }
1572
+
1573
+ // A model that hears and speaks at once and takes its own turns, so nothing
1574
+ // here ends a turn, asks for a response or stops one: what is left is
1575
+ // keeping the words each side says as lines, timing each answer from the
1576
+ // caller's last sound, and doing the work it hands over. Its audio comes as
1577
+ // it is said, quiet included, and plays as it comes.
1578
+ let duplexed = (o: Talks, t: Talker & Duplex): Talk => {
1579
+ let format = o.format
1580
+ if (!format || o.call != undefined) {
1581
+ throw new Error(`${o.provider.name}'s duplex model joins no call`)
1582
+ }
1583
+ let set = setup(t, o, format)
1584
+ if (set.backend && !t.backends.includes(set.backend.model)) {
1585
+ throw new Error(
1586
+ `${o.provider.name}'s ${set.model} hands no work to ${set.backend.model}`,
1587
+ )
1588
+ }
1589
+ // The stream's seconds and what its backend's work cost.
1590
+ let bytes = 0, backed = 0
1591
+ // Each side's words since the other last spoke, and the caller's since the
1592
+ // model last handed work over.
1593
+ let hearing = '', saying = '', asked = '', latest = ''
1594
+ // Whether the caller made a sound since the model last began to, and for
1595
+ // how many seconds they have been quiet.
1596
+ let spoke = false, quiet = 0, interrupted = false
1597
+ let stop = () => {
1598
+ if (!spoke) return
1599
+ spoke = false
1600
+ o.told.stopped?.(quiet)
1601
+ }
1602
+ // What the model is asked to say while the caller talks, sent once they
1603
+ // are `QUIET`: appended over their words, it can go unsaid.
1604
+ let talking = false, unsaid: string[] = []
1605
+ let cancelHeard: (() => void) | undefined
1606
+ let cancelSaid: (() => void) | undefined
1607
+ let time = o.time ?? system
1608
+ let heard = () => {
1609
+ cancelHeard?.()
1610
+ cancelHeard = undefined
1611
+ let text = hearing.trim()
1612
+ hearing = ''
1613
+ if (text) o.told.heard?.(text), asked += ' ' + text, latest = text
1614
+ }
1615
+ let heardPause = () => {
1616
+ if (!hearing || quiet < QUIET) return
1617
+ cancelHeard?.()
1618
+ cancelHeard = time.after(PAUSED * 1000, heard)
1619
+ }
1620
+ let said = () => {
1621
+ cancelSaid?.()
1622
+ cancelSaid = undefined
1623
+ let line = saying.trim()
1624
+ saying = ''
1625
+ if (!line) return
1626
+ let text = spokenProse(line)
1627
+ if (text) o.told.said?.(text)
1628
+ o.told.done?.()
1629
+ }
1630
+ // GPT-Live has no transcript-done event. A reply can end with silence
1631
+ // on both sides and no next turn to settle its text.
1632
+ let spokenPause = () => {
1633
+ cancelSaid?.()
1634
+ cancelSaid = time.after(PAUSED * 1000, said)
1635
+ }
1636
+ // What is sent before the stream is ready, sent once it is.
1637
+ let held: string[] | undefined = []
1638
+ let send = (m: string) => held ? held.push(m) : s.send(m)
1639
+ // Its first words (`opens`): whether it has begun them, the seconds it has
1640
+ // been quiet since, and the seconds the caller's line ran before them.
1641
+ // Its audio comes as it is said, so they are over once it has spoken and
1642
+ // paused, or never began them.
1643
+ let opens = o.opens && !o.interruptible
1644
+ ? { began: false, quiet: 0, waited: 0 }
1645
+ : undefined
1646
+ let spoken = (audio: Uint8Array) => {
1647
+ if (!opens) return
1648
+ if (sounds(audio, format)) opens.began = true, opens.quiet = 0
1649
+ else if (opens.began) opens.quiet += audio.length / perSecond(format)!
1650
+ if (opens.quiet >= PAUSED) opens = undefined
1651
+ }
1652
+ let s = stream(
1653
+ o,
1654
+ o.provider.live + t.path(set.model),
1655
+ t.opening(set),
1656
+ (data) => {
1657
+ for (let x of t.read(data, set.model, set.backend?.model)) {
1658
+ if (x.ready && held) { for (let m of held.splice(0)) s.send(m) }
1659
+ if (x.ready) held = undefined
1660
+ if (x.hearing) {
1661
+ said()
1662
+ hearing += x.hearing
1663
+ o.told.hearing?.(hearing)
1664
+ heardPause()
1665
+ if (spoke && !interrupted && meant(hearing) >= OVER) {
1666
+ interrupted = true
1667
+ o.told.over?.()
1668
+ }
1669
+ }
1670
+ if (x.saying) {
1671
+ if (quiet >= QUIET) heard()
1672
+ saying += x.saying
1673
+ spokenPause()
1674
+ }
1675
+ if (x.audio) {
1676
+ spoken(x.audio)
1677
+ if (sounds(x.audio, format)) {
1678
+ if (saying) spokenPause()
1679
+ stop()
1680
+ }
1681
+ o.told.audio(x.audio)
1682
+ }
1683
+ // One refused event leaves the stream open: a stream that failed
1684
+ // closes, and is lost.
1685
+ if (x.error) o.told.refused?.(x.error)
1686
+ if (x.spent) backed += x.spent
1687
+ let call = x.call
1688
+ if (call) {
1689
+ stop()
1690
+ heard()
1691
+ Promise.resolve(o.told.call(
1692
+ call.name,
1693
+ call.args,
1694
+ !o.listening || !!o.addressed?.(latest),
1695
+ ))
1696
+ .catch((error) => ({
1697
+ text: `That did not work: ${error?.message ?? error}`,
1698
+ from: 'the system',
1699
+ }))
1700
+ .then((output) =>
1701
+ t.result(call.id, wording(output, `the ${call.name} tool`))
1702
+ .forEach(send)
1703
+ )
1704
+ }
1705
+ let id = x.delegated
1706
+ if (id) {
1707
+ stop()
1708
+ heard(), said()
1709
+ let request = asked.trim()
1710
+ asked = ''
1711
+ if (!request) continue
1712
+ Promise.resolve(
1713
+ o.told.delegate?.(
1714
+ request,
1715
+ !o.listening || !!o.addressed?.(latest),
1716
+ ),
1717
+ )
1718
+ .catch((error) => ({
1719
+ text: `That did not work: ${error?.message ?? error}`,
1720
+ from: 'the system',
1721
+ }))
1722
+ .then((output) => {
1723
+ if (output) {
1724
+ t.answer(id, wording(output, 'the delegate')).forEach(send)
1725
+ }
1726
+ })
1727
+ }
1728
+ }
1729
+ },
1730
+ (reason) => {
1731
+ heard()
1732
+ said()
1733
+ o.told.lost?.(reason)
1734
+ },
1735
+ )
1736
+ let spent = () => {
1737
+ let seconds = bytes / perSecond(format)!
1738
+ return { seconds, dollars: seconds / 60 * t.perMinute + backed }
1739
+ }
1740
+ if (o.opens) t.opens(o.opens).forEach(send)
1741
+ return {
1742
+ send: (audio) => {
1743
+ if (s.closed()) return
1744
+ bytes += audio.length
1745
+ if (opens && !opens.began) {
1746
+ opens.waited += audio.length / perSecond(format)!
1747
+ if (opens.waited >= SILENT) opens = undefined
1748
+ }
1749
+ if (opens) audio = muted(audio, format)
1750
+ send(t.audio(audio))
1751
+ if (sounds(audio, format)) {
1752
+ cancelHeard?.()
1753
+ cancelHeard = undefined
1754
+ if (!spoke) interrupted = false
1755
+ spoke = talking = true, quiet = 0
1756
+ } else {
1757
+ quiet += audio.length / perSecond(format)!
1758
+ if (!cancelHeard) heardPause()
1759
+ }
1760
+ if (talking && quiet >= QUIET) {
1761
+ talking = false
1762
+ unsaid.splice(0).forEach(send)
1763
+ }
1764
+ },
1765
+ say: (text, from) => {
1766
+ let m = t.say(wording(text, from))
1767
+ talking ? unsaid.push(...m) : m.forEach(send)
1768
+ },
1769
+ tell: (text, from) => t.tell(wording(text, from)).forEach(send),
1770
+ spent,
1771
+ close: () => {
1772
+ heard(), said()
1773
+ s.close()
1774
+ return spent()
1775
+ },
1776
+ }
1777
+ }