@cairnvibe/sdk 0.2.8 → 0.2.10

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/src/index.tsx CHANGED
@@ -161,7 +161,18 @@ export function Copilot({
161
161
  const rtMicMutedRef = useRef(false);
162
162
  const rtSpeakerMutedRef = useRef(false);
163
163
  const rtStartingRef = useRef(false); // closes the click-to-first-state-update gap so a rapid double-click can't open two sessions
164
- const activeAudioRef = useRef<HTMLAudioElement | null>(null);
164
+ // Progressive PCM playback for the buffered (non-realtime) speak endpoint
165
+ // — the same gapless AudioBufferSourceNode scheduling the realtime path
166
+ // uses for its audio_chunk messages (see rtPlaybackCtxRef below), just fed
167
+ // by a fetch() ReadableStream instead of WebSocket messages. This exists
168
+ // because res.blob()/res.arrayBuffer() always wait for the whole response
169
+ // body in every browser no matter how the server sent it — streaming the
170
+ // wire alone (speak-server.ts) doesn't help unless playback also starts
171
+ // before the full reply has arrived.
172
+ const typedPlaybackCtxRef = useRef<AudioContext | null>(null);
173
+ const typedPlaybackGainRef = useRef<GainNode | null>(null);
174
+ const typedNextPlayTimeRef = useRef(0);
175
+ const typedScheduledSourcesRef = useRef<AudioBufferSourceNode[]>([]);
165
176
  // Watchdog for the "rt-thinking" state: started on every "final" transcript,
166
177
  // cleared the moment the server responds with anything for that turn
167
178
  // (verb/speaking_start/speaking_end/turn_complete/error). If it ever
@@ -497,29 +508,108 @@ export function Copilot({
497
508
  ].slice(-MAX_HISTORY_TURNS);
498
509
  }
499
510
 
511
+ function ensureTypedPlaybackGraph(): { ctx: AudioContext; gain: GainNode } {
512
+ if (!typedPlaybackCtxRef.current) {
513
+ const ctx = new AudioContext();
514
+ const gain = ctx.createGain();
515
+ gain.connect(ctx.destination);
516
+ typedPlaybackCtxRef.current = ctx;
517
+ typedPlaybackGainRef.current = gain;
518
+ }
519
+ return { ctx: typedPlaybackCtxRef.current, gain: typedPlaybackGainRef.current! };
520
+ }
521
+
522
+ /** Stops whatever's currently playing on the typed/mic path's playback
523
+ * graph, so two responses (e.g. a rapid double-click, or two answers
524
+ * resolved close together) can never be heard overlapping. */
525
+ function stopTypedPlayback() {
526
+ for (const source of typedScheduledSourcesRef.current) {
527
+ source.onended = null;
528
+ try {
529
+ source.stop();
530
+ } catch {
531
+ // may already have finished naturally
532
+ }
533
+ }
534
+ typedScheduledSourcesRef.current = [];
535
+ typedNextPlayTimeRef.current = typedPlaybackCtxRef.current?.currentTime ?? 0;
536
+ }
537
+
538
+ function concatBytes(a: Uint8Array, b: Uint8Array): Uint8Array {
539
+ const out = new Uint8Array(a.length + b.length);
540
+ out.set(a, 0);
541
+ out.set(b, a.length);
542
+ return out;
543
+ }
544
+
500
545
  /**
501
- * The one place that starts audio playback for a spoken response — stops
502
- * whatever's currently playing first, so two responses (e.g. a rapid
503
- * double-click on "start conversation", or two utterances resolved close
504
- * together) can never be heard overlapping. Used by both the typed/mic
505
- * path and the realtime path.
546
+ * Reads a raw linear16 PCM stream (mono, 24kHz matches speak-server.ts)
547
+ * and schedules it gapless-appended into the Web Audio graph as chunks
548
+ * arrive the same technique the realtime path uses for its audio_chunk
549
+ * messages, just driven by a fetch() reader instead of WebSocket frames.
550
+ * Resolves once every scheduled chunk has actually finished *playing*,
551
+ * not just finished arriving.
506
552
  */
507
- function playResponseAudio(blob: Blob): Promise<void> {
508
- if (activeAudioRef.current) {
509
- activeAudioRef.current.pause();
510
- activeAudioRef.current.currentTime = 0;
511
- }
512
- const url = URL.createObjectURL(blob);
513
- const audio = new Audio(url);
514
- activeAudioRef.current = audio;
553
+ function playPcmStream(stream: ReadableStream<Uint8Array>): Promise<void> {
554
+ stopTypedPlayback();
555
+ const { ctx, gain } = ensureTypedPlaybackGraph();
556
+ void ctx.resume().catch(() => {});
557
+
515
558
  return new Promise((resolve) => {
516
- const clear = () => {
517
- URL.revokeObjectURL(url);
518
- if (activeAudioRef.current === audio) activeAudioRef.current = null;
519
- resolve();
559
+ let doneArriving = false;
560
+ let leftover: Uint8Array<ArrayBufferLike> = new Uint8Array(0);
561
+
562
+ const maybeResolve = () => {
563
+ if (doneArriving && typedScheduledSourcesRef.current.length === 0) resolve();
520
564
  };
521
- audio.onended = clear;
522
- audio.play().catch(clear);
565
+
566
+ const scheduleChunk = (bytes: Uint8Array) => {
567
+ const sampleCount = Math.floor(bytes.length / 2);
568
+ if (sampleCount === 0) return;
569
+ const float32 = new Float32Array(sampleCount);
570
+ const view = new DataView(bytes.buffer, bytes.byteOffset, sampleCount * 2);
571
+ for (let i = 0; i < sampleCount; i++) float32[i] = view.getInt16(i * 2, true) / 32768;
572
+
573
+ const buffer = ctx.createBuffer(1, sampleCount, 24000);
574
+ buffer.copyToChannel(float32, 0);
575
+
576
+ const source = ctx.createBufferSource();
577
+ source.buffer = buffer;
578
+ source.connect(gain);
579
+
580
+ const startAt = Math.max(ctx.currentTime, typedNextPlayTimeRef.current);
581
+ source.start(startAt);
582
+ typedNextPlayTimeRef.current = startAt + buffer.duration;
583
+
584
+ typedScheduledSourcesRef.current.push(source);
585
+ source.onended = () => {
586
+ typedScheduledSourcesRef.current = typedScheduledSourcesRef.current.filter((s) => s !== source);
587
+ maybeResolve();
588
+ };
589
+ };
590
+
591
+ (async () => {
592
+ const reader = stream.getReader();
593
+ try {
594
+ for (;;) {
595
+ const { done, value } = await reader.read();
596
+ if (done) break;
597
+ if (!value || value.length === 0) continue;
598
+ // PCM16 samples are 2 bytes each — a chunk boundary can split a
599
+ // sample in half, so carry any odd trailing byte into the next
600
+ // read instead of corrupting one sample at every chunk seam.
601
+ const combined = concatBytes(leftover, value);
602
+ const usableLen = combined.length - (combined.length % 2);
603
+ scheduleChunk(combined.subarray(0, usableLen));
604
+ leftover = combined.subarray(usableLen);
605
+ }
606
+ } catch {
607
+ // Best-effort — never let a stream read failure hang the caller forever.
608
+ } finally {
609
+ doneArriving = true;
610
+ maybeResolve();
611
+ }
612
+ })();
523
613
  });
524
614
  }
525
615
 
@@ -531,8 +621,8 @@ export function Copilot({
531
621
  headers: { "content-type": "application/json" },
532
622
  body: JSON.stringify({ text }),
533
623
  });
534
- if (!res.ok) return;
535
- void playResponseAudio(await res.blob());
624
+ if (!res.ok || !res.body) return;
625
+ void playPcmStream(res.body);
536
626
  } catch {
537
627
  // Best-effort — never let speech playback break the widget.
538
628
  }
@@ -549,8 +639,8 @@ export function Copilot({
549
639
  headers: { "content-type": "application/json" },
550
640
  body: JSON.stringify({ text }),
551
641
  });
552
- if (!res.ok) return;
553
- await playResponseAudio(await res.blob());
642
+ if (!res.ok || !res.body) return;
643
+ await playPcmStream(res.body);
554
644
  } catch {
555
645
  // Best-effort — never let a synthesis failure hang the tour forever.
556
646
  }
@@ -938,8 +1028,7 @@ export function Copilot({
938
1028
  rtThinkingWatchdogRef.current = null;
939
1029
  }
940
1030
  rtStartingRef.current = false;
941
- activeAudioRef.current?.pause();
942
- activeAudioRef.current = null;
1031
+ stopTypedPlayback();
943
1032
  rtSocketRef.current?.close();
944
1033
  rtSocketRef.current = null;
945
1034
  rtCleanupRef.current?.();
@@ -34,6 +34,12 @@ import { DeepgramSpeakStream } from "./tts-stream";
34
34
  const DEEPGRAM_LIVE_URL = "wss://api.deepgram.com/v1/listen";
35
35
  const DEFAULT_STT_MODEL = "nova-2";
36
36
  const DEFAULT_TTS_VOICE = "aura-2-thalia-en";
37
+ // The Talker half of a Talker/Reasoner split (see finalizeTurn): spoken the
38
+ // instant a turn turns out to need more than one step, so the user hears
39
+ // something within about a second instead of dead air while the real
40
+ // multi-step work runs. A short rotating set, not one fixed line, so it
41
+ // doesn't read as a canned bot phrase on every multi-step question.
42
+ const ACK_PHRASES = ["Let me check that for you.", "One moment, let me look into that.", "Give me a second to check.", "Let me take a look."];
37
43
  // Not constrained by any telephony 8kHz requirement — this is just "what
38
44
  // quality does Deepgram render at" for browser playback, and the Web Audio
39
45
  // API resamples an AudioBuffer at any declared rate transparently.
@@ -413,6 +419,14 @@ async function finalizeTurn(
413
419
  safeSend(client, { type: "final", text: transcript });
414
420
 
415
421
  let loopHistory = history;
422
+ // The Talker: set once, the first time a turn turns out to need more
423
+ // than one step (see the loop below) — a real, in-flight speakStreamed()
424
+ // call, never awaited until we're actually ready to speak the real
425
+ // answer. Deliberately not re-triggered per step: the Speak connection
426
+ // (speakStreamed) only ever handles one utterance at a time, so a second
427
+ // ack mid-loop would race the first one's own audio_chunk/Flushed
428
+ // handling instead of queuing cleanly.
429
+ let ackPromise: Promise<void> | null = null;
416
430
 
417
431
  try {
418
432
  for (let i = 0; i < MAX_LOOP_ITERATIONS; i++) {
@@ -435,9 +449,19 @@ async function finalizeTurn(
435
449
  safeSend(client, { type: "verb", verb });
436
450
 
437
451
  if (!TERMINAL_VERBS.has(verb.verb)) {
438
- // A continuing step — no speech for it (keeps the loop fast;
439
- // the client still shows it visually) wait for its real result
440
- // and go around again instead of ending the turn.
452
+ if (i === 0) {
453
+ // This turn just revealed it needs more than one step speak a
454
+ // quick, cheap acknowledgment *now*, in parallel with the rest
455
+ // of the loop's own real work below (not awaited here), so the
456
+ // user hears something within about a second instead of dead
457
+ // air for however long the real multi-step answer takes.
458
+ // Single-step turns (the common case) never reach this branch
459
+ // at all, so they keep today's latency exactly as it is.
460
+ ackPromise = speakStreamed(ACK_PHRASES[Math.floor(Math.random() * ACK_PHRASES.length)]);
461
+ }
462
+ // A continuing step itself stays silent (keeps the loop fast; the
463
+ // client still shows it visually) — wait for its real result and
464
+ // go around again instead of ending the turn.
441
465
  const observation = await waitForToolResult();
442
466
  if (myGeneration !== getGeneration()) return;
443
467
  loopHistory = [
@@ -450,6 +474,17 @@ async function finalizeTurn(
450
474
  history.push({ role: "user", text: transcript }, { role: "assistant", text: summarizeVerbForHistory(verb) });
451
475
  history.splice(0, Math.max(0, history.length - MAX_HISTORY_TURNS));
452
476
 
477
+ if (ackPromise) {
478
+ // Never start a second speakStreamed call before the first (the
479
+ // ack) has actually finished — same single Speak connection, one
480
+ // utterance at a time. In the common multi-step case the real
481
+ // work below already took about as long as the ack itself did, so
482
+ // this rarely adds a real wait.
483
+ await ackPromise;
484
+ ackPromise = null;
485
+ if (myGeneration !== getGeneration()) return; // a barge-in could have landed during the ack itself
486
+ }
487
+
453
488
  // A verb with no spoken text (highlight/navigate/do often have none)
454
489
  // still needs to unstick the client's "thinking" state and let the mic
455
490
  // resume — turn_complete covers that with no audio path involved.
@@ -466,6 +501,10 @@ async function finalizeTurn(
466
501
  history.push({ role: "user", text: transcript }, { role: "assistant", text: "(gave up after too many steps)" });
467
502
  history.splice(0, Math.max(0, history.length - MAX_HISTORY_TURNS));
468
503
  safeSend(client, { type: "verb", verb: { verb: "explain", text: "I wasn't able to finish that — try asking again or breaking it into smaller steps." } });
504
+ if (ackPromise) {
505
+ await ackPromise;
506
+ if (myGeneration !== getGeneration()) return;
507
+ }
469
508
  await speakStreamed("I wasn't able to finish that — try asking again or breaking it into smaller steps.");
470
509
  } catch (err) {
471
510
  console.error("[cairn realtime] failed to resolve/speak this turn:", err);
@@ -17,7 +17,10 @@ import type { LiveElement } from "@cairnvibe/core";
17
17
  const CANDIDATE_SELECTOR =
18
18
  "[data-ai], button, a, [role='button'], input[type='submit'], input[type='button'], " +
19
19
  "input:not([type='submit']):not([type='button']):not([type='hidden']), textarea, select";
20
- const MAX_ELEMENTS = 40;
20
+ // Bumped from 40 now that off-screen candidates (see viewportDistance below)
21
+ // compete for a slot too — still comfortably under CopilotRequestSchema's
22
+ // liveElements cap (60) server-side.
23
+ const MAX_ELEMENTS = 50;
21
24
  const MAX_LABEL_LENGTH = 80;
22
25
  const RESCAN_DEBOUNCE_MS = 250;
23
26
 
@@ -26,9 +29,32 @@ export interface LiveScan {
26
29
  byId: Map<string, HTMLElement>;
27
30
  }
28
31
 
29
- function isInViewport(el: Element): boolean {
32
+ /** Excludes elements that aren't rendered anywhere (display:none, a closed
33
+ * modal's contents, an inactive tab panel) — these get an all-zero rect from
34
+ * getBoundingClientRect() in every real browser, unlike anything actually on
35
+ * the page, however far off-screen. Not the same question as "is this
36
+ * scrolled into view" (viewportDistance, below) — this is "does it exist on
37
+ * the page at all right now." */
38
+ function isRendered(el: Element): boolean {
30
39
  const rect = el.getBoundingClientRect();
31
- return rect.bottom > 0 && rect.top < window.innerHeight && rect.right > 0 && rect.left < window.innerWidth;
40
+ return rect.width > 0 || rect.height > 0;
41
+ }
42
+
43
+ /**
44
+ * 0 for anything already in the viewport; otherwise the pixel gap to the
45
+ * nearest edge, summed across both axes. Used to RANK candidates instead of
46
+ * hard-filtering them — an element below the fold or in an unscrolled
47
+ * carousel is still real and still actionable (highlightElement already
48
+ * scrolls to it before acting on it), the agent just couldn't discover it
49
+ * existed under the old viewport-only scan. Ranking keeps what's on screen
50
+ * right now winning every tie, while still surfacing what's just out of
51
+ * view when there's room under MAX_ELEMENTS.
52
+ */
53
+ function viewportDistance(el: Element): number {
54
+ const rect = el.getBoundingClientRect();
55
+ const verticalGap = rect.top > window.innerHeight ? rect.top - window.innerHeight : rect.bottom < 0 ? -rect.bottom : 0;
56
+ const horizontalGap = rect.left > window.innerWidth ? rect.left - window.innerWidth : rect.right < 0 ? -rect.right : 0;
57
+ return verticalGap + horizontalGap;
32
58
  }
33
59
 
34
60
  /** A form field's own text content is always empty — its identity comes
@@ -66,12 +92,14 @@ function roleFor(el: HTMLElement): string {
66
92
  }
67
93
 
68
94
  /**
69
- * Scans the live DOM for interactive elements currently in the viewport.
70
- * Returns both the bounded list to send to the model (`elements`, capped at
71
- * MAX_ELEMENTS and MAX_LABEL_LENGTH the actual privacy/payload backstop,
72
- * mirrored server-side in CopilotRequestSchema) and the real elements it
73
- * maps to, keyed by the same ids (`byId`) — resolve a verb's target by
74
- * looking it up here, never by re-deriving a selector from the id string.
95
+ * Scans the live DOM for interactive elements, on screen right now or just
96
+ * off it (see viewportDistance) anything rendered on the page at all, not
97
+ * just what's currently scrolled into view. Returns both the bounded list to
98
+ * send to the model (`elements`, capped at MAX_ELEMENTS and
99
+ * MAX_LABEL_LENGTH the actual privacy/payload backstop, mirrored
100
+ * server-side in CopilotRequestSchema) and the real elements it maps to,
101
+ * keyed by the same ids (`byId`) — resolve a verb's target by looking it up
102
+ * here, never by re-deriving a selector from the id string.
75
103
  */
76
104
  export function scanInteractiveElements(root: ParentNode = document): LiveScan {
77
105
  const elements: LiveElement[] = [];
@@ -80,10 +108,11 @@ export function scanInteractiveElements(root: ParentNode = document): LiveScan {
80
108
 
81
109
  if (typeof document === "undefined") return { elements, byId };
82
110
 
83
- const candidates = root.querySelectorAll<HTMLElement>(CANDIDATE_SELECTOR);
84
- for (const el of Array.from(candidates)) {
111
+ const candidates = Array.from(root.querySelectorAll<HTMLElement>(CANDIDATE_SELECTOR)).filter(isRendered);
112
+ candidates.sort((a, b) => viewportDistance(a) - viewportDistance(b));
113
+
114
+ for (const el of candidates) {
85
115
  if (elements.length >= MAX_ELEMENTS) break;
86
- if (!isInViewport(el)) continue;
87
116
 
88
117
  const dataAi = el.getAttribute("data-ai");
89
118
  const id = dataAi ?? `live-${counter++}`;
package/src/server.ts CHANGED
@@ -303,6 +303,28 @@ export class GroqVerbLLM implements VerbLLM {
303
303
  ) {}
304
304
 
305
305
  async respond(systemPrompt: string, userMessage: string): Promise<unknown> {
306
+ try {
307
+ return await this.attemptRespond(systemPrompt, userMessage);
308
+ } catch (err) {
309
+ // Real, live bug, not theoretical: openai/gpt-oss-120b (a reasoning-
310
+ // capable open model) occasionally "thinks out loud" in plain prose
311
+ // instead of emitting the forced tool call — Groq's own server-side
312
+ // validation rejects that outright, a 400 with code
313
+ // "output_parse_failed", before this code ever sees a real response
314
+ // to work with. Non-deterministic (found live re-asking the exact
315
+ // same question a moment later succeeded cleanly), so one retry —
316
+ // not exponential backoff, this is a latency-sensitive voice/chat
317
+ // path — genuinely helps rather than just delaying the same
318
+ // failure. Anything else still propagates to resolveVerb's own
319
+ // catch, unchanged.
320
+ if (isOutputParseFailure(err)) {
321
+ return await this.attemptRespond(systemPrompt, userMessage);
322
+ }
323
+ throw err;
324
+ }
325
+ }
326
+
327
+ private async attemptRespond(systemPrompt: string, userMessage: string): Promise<unknown> {
306
328
  const client = this.clientFactory(this.keys.take());
307
329
  const completion = await client.chat.completions.create({
308
330
  model: this.model,
@@ -333,13 +355,25 @@ export class GroqVerbLLM implements VerbLLM {
333
355
  }
334
356
  }
335
357
 
358
+ /** Groq's SDK doesn't export a stable error shape to import and check
359
+ * against, so this checks defensively across the ways the real error has
360
+ * actually been observed to surface — a thrown APIError with a nested
361
+ * `.error.code`, a plain `.code`, or just the code string showing up
362
+ * somewhere in the message — rather than relying on exactly one of them. */
363
+ function isOutputParseFailure(err: unknown): boolean {
364
+ if (!err || typeof err !== "object") return false;
365
+ const e = err as { code?: unknown; error?: { code?: unknown }; message?: unknown };
366
+ if (e.code === "output_parse_failed" || e.error?.code === "output_parse_failed") return true;
367
+ return typeof e.message === "string" && e.message.includes("output_parse_failed");
368
+ }
369
+
336
370
  // ---------------------------------------------------------------------------
337
371
  // Shared tool schema / system prompt
338
372
  // ---------------------------------------------------------------------------
339
373
 
340
374
  const VERB_TOOL_DESCRIPTION = "Respond with exactly one action for the UI to take. Never invent selectors, routes, or code.";
341
375
 
342
- function buildVerbToolSchema(registeredActions: string[]): Record<string, unknown> {
376
+ export function buildVerbToolSchema(registeredActions: string[]): Record<string, unknown> {
343
377
  // Every genuinely-optional field allows `null` as well as its real type
344
378
  // (`["string", "null"]`, not just `"string"`) — found live, not
345
379
  // theoretical: real models (verified against Groq's openai/gpt-oss-120b)
@@ -358,7 +392,7 @@ function buildVerbToolSchema(registeredActions: string[]): Record<string, unknow
358
392
  type: "object",
359
393
  properties: {
360
394
  verb: { type: "string", enum: [...VERBS] },
361
- text: { type: "string", description: "Shown to the user. Required for explain." },
395
+ text: nullableString("Shown to the user. Required for explain. null (or omitted) if not applicable."),
362
396
  target: nullableString(
363
397
  "An id from currentPageElements or liveElements. Required for highlight/open/click/fill/read. For do, the id of what the action applies to, if it needs one — prefer a liveElements id when the user means one specific item among several. null (or omitted) if not applicable.",
364
398
  ),
@@ -377,9 +411,9 @@ function buildVerbToolSchema(registeredActions: string[]): Record<string, unknow
377
411
  description: "For call_tool — the arguments object, matching that tool's own inputSchema. null (or omitted) if the tool takes none.",
378
412
  },
379
413
  steps: {
380
- type: "array",
414
+ type: ["array", "null"],
381
415
  description:
382
- "Required for tour, 2-6 items. Each step is spoken/shown in order while highlighting its target (if any) — use this instead of explain when the answer genuinely covers several distinct elements, so the user sees what's being talked about instead of reading a wall of text.",
416
+ "Required for tour, 2-6 items. Each step is spoken/shown in order while highlighting its target (if any) — use this instead of explain when the answer genuinely covers several distinct elements, so the user sees what's being talked about instead of reading a wall of text. null (or omitted) if not applicable.",
383
417
  items: {
384
418
  type: "object",
385
419
  properties: {
@@ -1,12 +1,36 @@
1
1
  // Server-side text-to-speech for the Copilot widget's spoken answers (see
2
2
  // `speakEndpoint` in index.tsx). The Deepgram key must never reach the
3
- // client, so this is a plain fetch to Deepgram's /v1/speak REST endpoint —
4
- // no SDK dependency needed for one request shape.
3
+ // client.
4
+ //
5
+ // This used to be one fetch to Deepgram's /v1/speak REST endpoint, buffered
6
+ // into an ArrayBuffer with `await response.arrayBuffer()` before returning
7
+ // anything. That's the exact same bug the realtime path already fixed once
8
+ // (see tts-stream.ts's own comment): nothing plays until Deepgram renders
9
+ // AND the network delivers the *entire* reply, which measured 5-8s for a
10
+ // normal explain answer in real production logs. It also hit Deepgram's
11
+ // REST-only 2000-character cap on longer replies with no handling at all.
12
+ //
13
+ // Fixed the same way the realtime path was: open the streaming Speak
14
+ // WebSocket (tts-stream.ts's DeepgramSpeakStream, the same class the
15
+ // realtime server already uses) and forward audio chunks to the caller as
16
+ // they arrive, via a ReadableStream — not buffered. The route handler
17
+ // forwards that stream straight through as the HTTP response body, and the
18
+ // client (index.tsx) reads it progressively instead of awaiting a full
19
+ // Blob, so playback can start on the first chunk. Splitting the text into
20
+ // sentence-sized `Speak` messages before one `Flush` sidesteps the old
21
+ // 2000-char REST limit entirely (it doesn't apply to the WS protocol) and
22
+ // lets Deepgram start rendering the first sentence sooner.
23
+ import { DeepgramSpeakStream, type DeepgramSpeakStreamOptions, type SpeakChunkCallback } from "./tts-stream";
5
24
 
6
- const DEEPGRAM_SPEAK_URL = "https://api.deepgram.com/v1/speak";
7
- // Verified against Deepgram's docs while building this — re-check if this
8
- // starts erroring, voice model names retire over time.
9
25
  const DEEPGRAM_DEFAULT_VOICE = "aura-2-thalia-en";
26
+ // Matches the realtime path's own playback sample rate (index.tsx's
27
+ // audio_chunk handling defaults to 24000 too) — keeping them identical lets
28
+ // both paths share one raw-PCM16 decode/schedule routine on the client.
29
+ const SAMPLE_RATE = 24000;
30
+ // Not a protocol limit (the WS Speak protocol has none like REST's 2000
31
+ // chars) — just keeps each queued chunk sentence-sized so Deepgram can start
32
+ // rendering the first one quickly instead of parsing one giant message.
33
+ const MAX_CHUNK_CHARS = 300;
10
34
 
11
35
  export interface CreateSpeakHandlerOptions {
12
36
  apiKey: string;
@@ -15,13 +39,42 @@ export interface CreateSpeakHandlerOptions {
15
39
 
16
40
  export interface SpeakResult {
17
41
  status: number;
18
- /** `audio` is raw MP3 bytes on success. */
19
- body: { audio: ArrayBuffer; contentType: string } | { error: string };
42
+ /** `stream` yields raw linear16 PCM chunks (mono, 24kHz) as Deepgram
43
+ * renders them forward it directly, unbuffered; do not await it into a
44
+ * Blob/ArrayBuffer or the whole point of streaming is lost. */
45
+ body: { stream: ReadableStream<Uint8Array>; contentType: string } | { error: string };
20
46
  }
21
47
 
22
48
  export type SpeakHandler = (text: string) => Promise<SpeakResult>;
23
49
 
24
- export function createSpeakHandler(options: CreateSpeakHandlerOptions): SpeakHandler {
50
+ /** Test-only seam: lets tests inject a fake stream instead of opening a real
51
+ * Deepgram WebSocket. Not part of CreateSpeakHandlerOptions on purpose — real
52
+ * call sites (the scaffolded route templates) never pass this. */
53
+ export type SpeakStreamFactory = (
54
+ opts: DeepgramSpeakStreamOptions,
55
+ onAudioChunk: SpeakChunkCallback,
56
+ handlers?: { onFlushed?: (sequenceId: number) => void; onError?: (err: Error) => void },
57
+ ) => DeepgramSpeakStream;
58
+
59
+ function splitIntoChunks(text: string, maxChars: number): string[] {
60
+ const sentences = text.match(/[^.!?]+[.!?]*\s*/g) ?? [text];
61
+ const chunks: string[] = [];
62
+ let current = "";
63
+ for (const sentence of sentences) {
64
+ if (current && current.length + sentence.length > maxChars) {
65
+ chunks.push(current);
66
+ current = "";
67
+ }
68
+ current += sentence;
69
+ }
70
+ if (current) chunks.push(current);
71
+ return chunks;
72
+ }
73
+
74
+ export function createSpeakHandler(
75
+ options: CreateSpeakHandlerOptions,
76
+ streamFactory: SpeakStreamFactory = (opts, onAudioChunk, handlers) => new DeepgramSpeakStream(opts, onAudioChunk, handlers),
77
+ ): SpeakHandler {
25
78
  const model = options.model ?? process.env.DEEPGRAM_VOICE ?? DEEPGRAM_DEFAULT_VOICE;
26
79
 
27
80
  return async function handleSpeak(text: string) {
@@ -29,28 +82,51 @@ export function createSpeakHandler(options: CreateSpeakHandlerOptions): SpeakHan
29
82
  return { status: 400, body: { error: "no text provided" } };
30
83
  }
31
84
 
32
- let response: Response;
33
- try {
34
- response = await fetch(`${DEEPGRAM_SPEAK_URL}?model=${encodeURIComponent(model)}`, {
35
- method: "POST",
36
- headers: {
37
- Authorization: `Token ${options.apiKey}`,
38
- "content-type": "application/json",
85
+ let enqueue: ((chunk: Uint8Array) => void) | null = null;
86
+ let closeOut: (() => void) | null = null;
87
+ let failOut: ((err: Error) => void) | null = null;
88
+ const stream = new ReadableStream<Uint8Array>({
89
+ start(controller) {
90
+ enqueue = (chunk) => controller.enqueue(chunk);
91
+ closeOut = () => controller.close();
92
+ failOut = (err) => controller.error(err);
93
+ },
94
+ });
95
+
96
+ // True once connect() below resolves — an onError before that point is
97
+ // already reported through connect()'s own rejection, so it's ignored
98
+ // here to avoid double-handling the same failure.
99
+ let connected = false;
100
+
101
+ const speakStream = streamFactory(
102
+ { apiKey: options.apiKey, model, encoding: "linear16", sampleRate: SAMPLE_RATE },
103
+ (chunk) => enqueue?.(new Uint8Array(chunk)),
104
+ {
105
+ onFlushed: () => {
106
+ closeOut?.();
107
+ speakStream.close();
108
+ },
109
+ onError: (err) => {
110
+ if (!connected) return;
111
+ console.error("[cairn] speak stream error:", err);
112
+ failOut?.(err);
39
113
  },
40
- body: JSON.stringify({ text }),
41
- });
114
+ },
115
+ );
116
+
117
+ try {
118
+ await speakStream.connect();
42
119
  } catch (err) {
43
120
  console.error("[cairn] speak request failed:", err);
44
121
  return { status: 200, body: { error: "speech service unreachable" } };
45
122
  }
123
+ connected = true;
46
124
 
47
- if (!response.ok) {
48
- const detail = await response.text().catch(() => "");
49
- console.error("[cairn] Deepgram speak returned an error:", response.status, detail);
50
- return { status: 200, body: { error: "speech synthesis failed" } };
125
+ for (const chunk of splitIntoChunks(text, MAX_CHUNK_CHARS)) {
126
+ speakStream.sendText(chunk);
51
127
  }
128
+ speakStream.flush();
52
129
 
53
- const audio = await response.arrayBuffer();
54
- return { status: 200, body: { audio, contentType: response.headers.get("content-type") ?? "audio/mpeg" } };
130
+ return { status: 200, body: { stream, contentType: `audio/L16;rate=${SAMPLE_RATE}` } };
55
131
  };
56
132
  }