@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/dist/index.js CHANGED
@@ -106,7 +106,18 @@ function Copilot({ endpoint = "/api/copilot", registeredActions = [], onDo, repo
106
106
  const rtMicMutedRef = (0, react_1.useRef)(false);
107
107
  const rtSpeakerMutedRef = (0, react_1.useRef)(false);
108
108
  const rtStartingRef = (0, react_1.useRef)(false); // closes the click-to-first-state-update gap so a rapid double-click can't open two sessions
109
- const activeAudioRef = (0, react_1.useRef)(null);
109
+ // Progressive PCM playback for the buffered (non-realtime) speak endpoint
110
+ // — the same gapless AudioBufferSourceNode scheduling the realtime path
111
+ // uses for its audio_chunk messages (see rtPlaybackCtxRef below), just fed
112
+ // by a fetch() ReadableStream instead of WebSocket messages. This exists
113
+ // because res.blob()/res.arrayBuffer() always wait for the whole response
114
+ // body in every browser no matter how the server sent it — streaming the
115
+ // wire alone (speak-server.ts) doesn't help unless playback also starts
116
+ // before the full reply has arrived.
117
+ const typedPlaybackCtxRef = (0, react_1.useRef)(null);
118
+ const typedPlaybackGainRef = (0, react_1.useRef)(null);
119
+ const typedNextPlayTimeRef = (0, react_1.useRef)(0);
120
+ const typedScheduledSourcesRef = (0, react_1.useRef)([]);
110
121
  // Watchdog for the "rt-thinking" state: started on every "final" transcript,
111
122
  // cleared the moment the server responds with anything for that turn
112
123
  // (verb/speaking_start/speaking_end/turn_complete/error). If it ever
@@ -433,30 +444,105 @@ function Copilot({ endpoint = "/api/copilot", registeredActions = [], onDo, repo
433
444
  { role: "assistant", text: "(gave up after too many steps)" },
434
445
  ].slice(-MAX_HISTORY_TURNS);
435
446
  }
447
+ function ensureTypedPlaybackGraph() {
448
+ if (!typedPlaybackCtxRef.current) {
449
+ const ctx = new AudioContext();
450
+ const gain = ctx.createGain();
451
+ gain.connect(ctx.destination);
452
+ typedPlaybackCtxRef.current = ctx;
453
+ typedPlaybackGainRef.current = gain;
454
+ }
455
+ return { ctx: typedPlaybackCtxRef.current, gain: typedPlaybackGainRef.current };
456
+ }
457
+ /** Stops whatever's currently playing on the typed/mic path's playback
458
+ * graph, so two responses (e.g. a rapid double-click, or two answers
459
+ * resolved close together) can never be heard overlapping. */
460
+ function stopTypedPlayback() {
461
+ for (const source of typedScheduledSourcesRef.current) {
462
+ source.onended = null;
463
+ try {
464
+ source.stop();
465
+ }
466
+ catch {
467
+ // may already have finished naturally
468
+ }
469
+ }
470
+ typedScheduledSourcesRef.current = [];
471
+ typedNextPlayTimeRef.current = typedPlaybackCtxRef.current?.currentTime ?? 0;
472
+ }
473
+ function concatBytes(a, b) {
474
+ const out = new Uint8Array(a.length + b.length);
475
+ out.set(a, 0);
476
+ out.set(b, a.length);
477
+ return out;
478
+ }
436
479
  /**
437
- * The one place that starts audio playback for a spoken response — stops
438
- * whatever's currently playing first, so two responses (e.g. a rapid
439
- * double-click on "start conversation", or two utterances resolved close
440
- * together) can never be heard overlapping. Used by both the typed/mic
441
- * path and the realtime path.
480
+ * Reads a raw linear16 PCM stream (mono, 24kHz matches speak-server.ts)
481
+ * and schedules it gapless-appended into the Web Audio graph as chunks
482
+ * arrive the same technique the realtime path uses for its audio_chunk
483
+ * messages, just driven by a fetch() reader instead of WebSocket frames.
484
+ * Resolves once every scheduled chunk has actually finished *playing*,
485
+ * not just finished arriving.
442
486
  */
443
- function playResponseAudio(blob) {
444
- if (activeAudioRef.current) {
445
- activeAudioRef.current.pause();
446
- activeAudioRef.current.currentTime = 0;
447
- }
448
- const url = URL.createObjectURL(blob);
449
- const audio = new Audio(url);
450
- activeAudioRef.current = audio;
487
+ function playPcmStream(stream) {
488
+ stopTypedPlayback();
489
+ const { ctx, gain } = ensureTypedPlaybackGraph();
490
+ void ctx.resume().catch(() => { });
451
491
  return new Promise((resolve) => {
452
- const clear = () => {
453
- URL.revokeObjectURL(url);
454
- if (activeAudioRef.current === audio)
455
- activeAudioRef.current = null;
456
- resolve();
492
+ let doneArriving = false;
493
+ let leftover = new Uint8Array(0);
494
+ const maybeResolve = () => {
495
+ if (doneArriving && typedScheduledSourcesRef.current.length === 0)
496
+ resolve();
497
+ };
498
+ const scheduleChunk = (bytes) => {
499
+ const sampleCount = Math.floor(bytes.length / 2);
500
+ if (sampleCount === 0)
501
+ return;
502
+ const float32 = new Float32Array(sampleCount);
503
+ const view = new DataView(bytes.buffer, bytes.byteOffset, sampleCount * 2);
504
+ for (let i = 0; i < sampleCount; i++)
505
+ float32[i] = view.getInt16(i * 2, true) / 32768;
506
+ const buffer = ctx.createBuffer(1, sampleCount, 24000);
507
+ buffer.copyToChannel(float32, 0);
508
+ const source = ctx.createBufferSource();
509
+ source.buffer = buffer;
510
+ source.connect(gain);
511
+ const startAt = Math.max(ctx.currentTime, typedNextPlayTimeRef.current);
512
+ source.start(startAt);
513
+ typedNextPlayTimeRef.current = startAt + buffer.duration;
514
+ typedScheduledSourcesRef.current.push(source);
515
+ source.onended = () => {
516
+ typedScheduledSourcesRef.current = typedScheduledSourcesRef.current.filter((s) => s !== source);
517
+ maybeResolve();
518
+ };
457
519
  };
458
- audio.onended = clear;
459
- audio.play().catch(clear);
520
+ (async () => {
521
+ const reader = stream.getReader();
522
+ try {
523
+ for (;;) {
524
+ const { done, value } = await reader.read();
525
+ if (done)
526
+ break;
527
+ if (!value || value.length === 0)
528
+ continue;
529
+ // PCM16 samples are 2 bytes each — a chunk boundary can split a
530
+ // sample in half, so carry any odd trailing byte into the next
531
+ // read instead of corrupting one sample at every chunk seam.
532
+ const combined = concatBytes(leftover, value);
533
+ const usableLen = combined.length - (combined.length % 2);
534
+ scheduleChunk(combined.subarray(0, usableLen));
535
+ leftover = combined.subarray(usableLen);
536
+ }
537
+ }
538
+ catch {
539
+ // Best-effort — never let a stream read failure hang the caller forever.
540
+ }
541
+ finally {
542
+ doneArriving = true;
543
+ maybeResolve();
544
+ }
545
+ })();
460
546
  });
461
547
  }
462
548
  async function speak(text) {
@@ -468,9 +554,9 @@ function Copilot({ endpoint = "/api/copilot", registeredActions = [], onDo, repo
468
554
  headers: { "content-type": "application/json" },
469
555
  body: JSON.stringify({ text }),
470
556
  });
471
- if (!res.ok)
557
+ if (!res.ok || !res.body)
472
558
  return;
473
- void playResponseAudio(await res.blob());
559
+ void playPcmStream(res.body);
474
560
  }
475
561
  catch {
476
562
  // Best-effort — never let speech playback break the widget.
@@ -488,9 +574,9 @@ function Copilot({ endpoint = "/api/copilot", registeredActions = [], onDo, repo
488
574
  headers: { "content-type": "application/json" },
489
575
  body: JSON.stringify({ text }),
490
576
  });
491
- if (!res.ok)
577
+ if (!res.ok || !res.body)
492
578
  return;
493
- await playResponseAudio(await res.blob());
579
+ await playPcmStream(res.body);
494
580
  }
495
581
  catch {
496
582
  // Best-effort — never let a synthesis failure hang the tour forever.
@@ -884,8 +970,7 @@ function Copilot({ endpoint = "/api/copilot", registeredActions = [], onDo, repo
884
970
  rtThinkingWatchdogRef.current = null;
885
971
  }
886
972
  rtStartingRef.current = false;
887
- activeAudioRef.current?.pause();
888
- activeAudioRef.current = null;
973
+ stopTypedPlayback();
889
974
  rtSocketRef.current?.close();
890
975
  rtSocketRef.current = null;
891
976
  rtCleanupRef.current?.();
@@ -39,6 +39,12 @@ const tts_stream_1 = require("./tts-stream");
39
39
  const DEEPGRAM_LIVE_URL = "wss://api.deepgram.com/v1/listen";
40
40
  const DEFAULT_STT_MODEL = "nova-2";
41
41
  const DEFAULT_TTS_VOICE = "aura-2-thalia-en";
42
+ // The Talker half of a Talker/Reasoner split (see finalizeTurn): spoken the
43
+ // instant a turn turns out to need more than one step, so the user hears
44
+ // something within about a second instead of dead air while the real
45
+ // multi-step work runs. A short rotating set, not one fixed line, so it
46
+ // doesn't read as a canned bot phrase on every multi-step question.
47
+ 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."];
42
48
  // Not constrained by any telephony 8kHz requirement — this is just "what
43
49
  // quality does Deepgram render at" for browser playback, and the Web Audio
44
50
  // API resamples an AudioBuffer at any declared rate transparently.
@@ -348,6 +354,14 @@ async function finalizeTurn(turnState, client, deps, getContext, speakStreamed,
348
354
  const myGeneration = getGeneration();
349
355
  safeSend(client, { type: "final", text: transcript });
350
356
  let loopHistory = history;
357
+ // The Talker: set once, the first time a turn turns out to need more
358
+ // than one step (see the loop below) — a real, in-flight speakStreamed()
359
+ // call, never awaited until we're actually ready to speak the real
360
+ // answer. Deliberately not re-triggered per step: the Speak connection
361
+ // (speakStreamed) only ever handles one utterance at a time, so a second
362
+ // ack mid-loop would race the first one's own audio_chunk/Flushed
363
+ // handling instead of queuing cleanly.
364
+ let ackPromise = null;
351
365
  try {
352
366
  for (let i = 0; i < MAX_LOOP_ITERATIONS; i++) {
353
367
  const { route, visible, liveElements, webMcpTools } = getContext();
@@ -367,9 +381,19 @@ async function finalizeTurn(turnState, client, deps, getContext, speakStreamed,
367
381
  // speak, not after.
368
382
  safeSend(client, { type: "verb", verb });
369
383
  if (!core_1.TERMINAL_VERBS.has(verb.verb)) {
370
- // A continuing step — no speech for it (keeps the loop fast;
371
- // the client still shows it visually) wait for its real result
372
- // and go around again instead of ending the turn.
384
+ if (i === 0) {
385
+ // This turn just revealed it needs more than one step speak a
386
+ // quick, cheap acknowledgment *now*, in parallel with the rest
387
+ // of the loop's own real work below (not awaited here), so the
388
+ // user hears something within about a second instead of dead
389
+ // air for however long the real multi-step answer takes.
390
+ // Single-step turns (the common case) never reach this branch
391
+ // at all, so they keep today's latency exactly as it is.
392
+ ackPromise = speakStreamed(ACK_PHRASES[Math.floor(Math.random() * ACK_PHRASES.length)]);
393
+ }
394
+ // A continuing step itself stays silent (keeps the loop fast; the
395
+ // client still shows it visually) — wait for its real result and
396
+ // go around again instead of ending the turn.
373
397
  const observation = await waitForToolResult();
374
398
  if (myGeneration !== getGeneration())
375
399
  return;
@@ -381,6 +405,17 @@ async function finalizeTurn(turnState, client, deps, getContext, speakStreamed,
381
405
  }
382
406
  history.push({ role: "user", text: transcript }, { role: "assistant", text: summarizeVerbForHistory(verb) });
383
407
  history.splice(0, Math.max(0, history.length - MAX_HISTORY_TURNS));
408
+ if (ackPromise) {
409
+ // Never start a second speakStreamed call before the first (the
410
+ // ack) has actually finished — same single Speak connection, one
411
+ // utterance at a time. In the common multi-step case the real
412
+ // work below already took about as long as the ack itself did, so
413
+ // this rarely adds a real wait.
414
+ await ackPromise;
415
+ ackPromise = null;
416
+ if (myGeneration !== getGeneration())
417
+ return; // a barge-in could have landed during the ack itself
418
+ }
384
419
  // A verb with no spoken text (highlight/navigate/do often have none)
385
420
  // still needs to unstick the client's "thinking" state and let the mic
386
421
  // resume — turn_complete covers that with no audio path involved.
@@ -397,6 +432,11 @@ async function finalizeTurn(turnState, client, deps, getContext, speakStreamed,
397
432
  history.push({ role: "user", text: transcript }, { role: "assistant", text: "(gave up after too many steps)" });
398
433
  history.splice(0, Math.max(0, history.length - MAX_HISTORY_TURNS));
399
434
  safeSend(client, { type: "verb", verb: { verb: "explain", text: "I wasn't able to finish that — try asking again or breaking it into smaller steps." } });
435
+ if (ackPromise) {
436
+ await ackPromise;
437
+ if (myGeneration !== getGeneration())
438
+ return;
439
+ }
400
440
  await speakStreamed("I wasn't able to finish that — try asking again or breaking it into smaller steps.");
401
441
  }
402
442
  catch (err) {
@@ -4,12 +4,14 @@ export interface LiveScan {
4
4
  byId: Map<string, HTMLElement>;
5
5
  }
6
6
  /**
7
- * Scans the live DOM for interactive elements currently in the viewport.
8
- * Returns both the bounded list to send to the model (`elements`, capped at
9
- * MAX_ELEMENTS and MAX_LABEL_LENGTH the actual privacy/payload backstop,
10
- * mirrored server-side in CopilotRequestSchema) and the real elements it
11
- * maps to, keyed by the same ids (`byId`) — resolve a verb's target by
12
- * looking it up here, never by re-deriving a selector from the id string.
7
+ * Scans the live DOM for interactive elements, on screen right now or just
8
+ * off it (see viewportDistance) anything rendered on the page at all, not
9
+ * just what's currently scrolled into view. Returns both the bounded list to
10
+ * send to the model (`elements`, capped at MAX_ELEMENTS and
11
+ * MAX_LABEL_LENGTH the actual privacy/payload backstop, mirrored
12
+ * server-side in CopilotRequestSchema) and the real elements it maps to,
13
+ * keyed by the same ids (`byId`) — resolve a verb's target by looking it up
14
+ * here, never by re-deriving a selector from the id string.
13
15
  */
14
16
  export declare function scanInteractiveElements(root?: ParentNode): LiveScan;
15
17
  export interface LiveElementRegistry {
@@ -17,12 +17,37 @@ exports.createLiveElementRegistry = createLiveElementRegistry;
17
17
  // these to be discoverable the same way a click target already is.
18
18
  const CANDIDATE_SELECTOR = "[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
- function isInViewport(el) {
26
+ /** Excludes elements that aren't rendered anywhere (display:none, a closed
27
+ * modal's contents, an inactive tab panel) — these get an all-zero rect from
28
+ * getBoundingClientRect() in every real browser, unlike anything actually on
29
+ * the page, however far off-screen. Not the same question as "is this
30
+ * scrolled into view" (viewportDistance, below) — this is "does it exist on
31
+ * the page at all right now." */
32
+ function isRendered(el) {
24
33
  const rect = el.getBoundingClientRect();
25
- return rect.bottom > 0 && rect.top < window.innerHeight && rect.right > 0 && rect.left < window.innerWidth;
34
+ return rect.width > 0 || rect.height > 0;
35
+ }
36
+ /**
37
+ * 0 for anything already in the viewport; otherwise the pixel gap to the
38
+ * nearest edge, summed across both axes. Used to RANK candidates instead of
39
+ * hard-filtering them — an element below the fold or in an unscrolled
40
+ * carousel is still real and still actionable (highlightElement already
41
+ * scrolls to it before acting on it), the agent just couldn't discover it
42
+ * existed under the old viewport-only scan. Ranking keeps what's on screen
43
+ * right now winning every tie, while still surfacing what's just out of
44
+ * view when there's room under MAX_ELEMENTS.
45
+ */
46
+ function viewportDistance(el) {
47
+ const rect = el.getBoundingClientRect();
48
+ const verticalGap = rect.top > window.innerHeight ? rect.top - window.innerHeight : rect.bottom < 0 ? -rect.bottom : 0;
49
+ const horizontalGap = rect.left > window.innerWidth ? rect.left - window.innerWidth : rect.right < 0 ? -rect.right : 0;
50
+ return verticalGap + horizontalGap;
26
51
  }
27
52
  /** A form field's own text content is always empty — its identity comes
28
53
  * from an associated <label>, a placeholder, or its name attribute
@@ -58,12 +83,14 @@ function roleFor(el) {
58
83
  return el.tagName.toLowerCase();
59
84
  }
60
85
  /**
61
- * Scans the live DOM for interactive elements currently in the viewport.
62
- * Returns both the bounded list to send to the model (`elements`, capped at
63
- * MAX_ELEMENTS and MAX_LABEL_LENGTH the actual privacy/payload backstop,
64
- * mirrored server-side in CopilotRequestSchema) and the real elements it
65
- * maps to, keyed by the same ids (`byId`) — resolve a verb's target by
66
- * looking it up here, never by re-deriving a selector from the id string.
86
+ * Scans the live DOM for interactive elements, on screen right now or just
87
+ * off it (see viewportDistance) anything rendered on the page at all, not
88
+ * just what's currently scrolled into view. Returns both the bounded list to
89
+ * send to the model (`elements`, capped at MAX_ELEMENTS and
90
+ * MAX_LABEL_LENGTH the actual privacy/payload backstop, mirrored
91
+ * server-side in CopilotRequestSchema) and the real elements it maps to,
92
+ * keyed by the same ids (`byId`) — resolve a verb's target by looking it up
93
+ * here, never by re-deriving a selector from the id string.
67
94
  */
68
95
  function scanInteractiveElements(root = document) {
69
96
  const elements = [];
@@ -71,12 +98,11 @@ function scanInteractiveElements(root = document) {
71
98
  let counter = 0;
72
99
  if (typeof document === "undefined")
73
100
  return { elements, byId };
74
- const candidates = root.querySelectorAll(CANDIDATE_SELECTOR);
75
- for (const el of Array.from(candidates)) {
101
+ const candidates = Array.from(root.querySelectorAll(CANDIDATE_SELECTOR)).filter(isRendered);
102
+ candidates.sort((a, b) => viewportDistance(a) - viewportDistance(b));
103
+ for (const el of candidates) {
76
104
  if (elements.length >= MAX_ELEMENTS)
77
105
  break;
78
- if (!isInViewport(el))
79
- continue;
80
106
  const dataAi = el.getAttribute("data-ai");
81
107
  const id = dataAi ?? `live-${counter++}`;
82
108
  if (byId.has(id))
package/dist/server.d.ts CHANGED
@@ -93,7 +93,9 @@ export declare class GroqVerbLLM implements VerbLLM {
93
93
  private clientFactory;
94
94
  constructor(keys: KeyRotator, model: string, toolSchema: Record<string, unknown>, clientFactory?: (apiKey: string) => GroqLikeClient);
95
95
  respond(systemPrompt: string, userMessage: string): Promise<unknown>;
96
+ private attemptRespond;
96
97
  }
98
+ export declare function buildVerbToolSchema(registeredActions: string[]): Record<string, unknown>;
97
99
  /**
98
100
  * A compact route directory — NOT every element on every page. Found live
99
101
  * and necessary, not theoretical: a real 17-page production app's full
package/dist/server.js CHANGED
@@ -12,6 +12,7 @@ exports.createCopilotHandler = createCopilotHandler;
12
12
  exports.createCopilotHandlerWithLLM = createCopilotHandlerWithLLM;
13
13
  exports.resolveVerb = resolveVerb;
14
14
  exports.createVerbLLM = createVerbLLM;
15
+ exports.buildVerbToolSchema = buildVerbToolSchema;
15
16
  exports.buildSystemPrompt = buildSystemPrompt;
16
17
  const sdk_1 = __importDefault(require("@anthropic-ai/sdk"));
17
18
  const groq_sdk_1 = __importDefault(require("groq-sdk"));
@@ -210,6 +211,28 @@ class GroqVerbLLM {
210
211
  this.clientFactory = clientFactory;
211
212
  }
212
213
  async respond(systemPrompt, userMessage) {
214
+ try {
215
+ return await this.attemptRespond(systemPrompt, userMessage);
216
+ }
217
+ catch (err) {
218
+ // Real, live bug, not theoretical: openai/gpt-oss-120b (a reasoning-
219
+ // capable open model) occasionally "thinks out loud" in plain prose
220
+ // instead of emitting the forced tool call — Groq's own server-side
221
+ // validation rejects that outright, a 400 with code
222
+ // "output_parse_failed", before this code ever sees a real response
223
+ // to work with. Non-deterministic (found live re-asking the exact
224
+ // same question a moment later succeeded cleanly), so one retry —
225
+ // not exponential backoff, this is a latency-sensitive voice/chat
226
+ // path — genuinely helps rather than just delaying the same
227
+ // failure. Anything else still propagates to resolveVerb's own
228
+ // catch, unchanged.
229
+ if (isOutputParseFailure(err)) {
230
+ return await this.attemptRespond(systemPrompt, userMessage);
231
+ }
232
+ throw err;
233
+ }
234
+ }
235
+ async attemptRespond(systemPrompt, userMessage) {
213
236
  const client = this.clientFactory(this.keys.take());
214
237
  const completion = await client.chat.completions.create({
215
238
  model: this.model,
@@ -241,6 +264,19 @@ class GroqVerbLLM {
241
264
  }
242
265
  }
243
266
  exports.GroqVerbLLM = GroqVerbLLM;
267
+ /** Groq's SDK doesn't export a stable error shape to import and check
268
+ * against, so this checks defensively across the ways the real error has
269
+ * actually been observed to surface — a thrown APIError with a nested
270
+ * `.error.code`, a plain `.code`, or just the code string showing up
271
+ * somewhere in the message — rather than relying on exactly one of them. */
272
+ function isOutputParseFailure(err) {
273
+ if (!err || typeof err !== "object")
274
+ return false;
275
+ const e = err;
276
+ if (e.code === "output_parse_failed" || e.error?.code === "output_parse_failed")
277
+ return true;
278
+ return typeof e.message === "string" && e.message.includes("output_parse_failed");
279
+ }
244
280
  // ---------------------------------------------------------------------------
245
281
  // Shared tool schema / system prompt
246
282
  // ---------------------------------------------------------------------------
@@ -264,7 +300,7 @@ function buildVerbToolSchema(registeredActions) {
264
300
  type: "object",
265
301
  properties: {
266
302
  verb: { type: "string", enum: [...core_1.VERBS] },
267
- text: { type: "string", description: "Shown to the user. Required for explain." },
303
+ text: nullableString("Shown to the user. Required for explain. null (or omitted) if not applicable."),
268
304
  target: nullableString("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."),
269
305
  route: nullableString("A route from the manifest. Required for navigate. null (or omitted) if not applicable."),
270
306
  action: nullableString("Required for do. A short label for what's being done, e.g. \"archive-invoice\" " +
@@ -279,8 +315,8 @@ function buildVerbToolSchema(registeredActions) {
279
315
  description: "For call_tool — the arguments object, matching that tool's own inputSchema. null (or omitted) if the tool takes none.",
280
316
  },
281
317
  steps: {
282
- type: "array",
283
- description: "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.",
318
+ type: ["array", "null"],
319
+ description: "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.",
284
320
  items: {
285
321
  type: "object",
286
322
  properties: {
@@ -1,16 +1,26 @@
1
+ import { DeepgramSpeakStream, type DeepgramSpeakStreamOptions, type SpeakChunkCallback } from "./tts-stream";
1
2
  export interface CreateSpeakHandlerOptions {
2
3
  apiKey: string;
3
4
  model?: string;
4
5
  }
5
6
  export interface SpeakResult {
6
7
  status: number;
7
- /** `audio` is raw MP3 bytes on success. */
8
+ /** `stream` yields raw linear16 PCM chunks (mono, 24kHz) as Deepgram
9
+ * renders them — forward it directly, unbuffered; do not await it into a
10
+ * Blob/ArrayBuffer or the whole point of streaming is lost. */
8
11
  body: {
9
- audio: ArrayBuffer;
12
+ stream: ReadableStream<Uint8Array>;
10
13
  contentType: string;
11
14
  } | {
12
15
  error: string;
13
16
  };
14
17
  }
15
18
  export type SpeakHandler = (text: string) => Promise<SpeakResult>;
16
- export declare function createSpeakHandler(options: CreateSpeakHandlerOptions): SpeakHandler;
19
+ /** Test-only seam: lets tests inject a fake stream instead of opening a real
20
+ * Deepgram WebSocket. Not part of CreateSpeakHandlerOptions on purpose — real
21
+ * call sites (the scaffolded route templates) never pass this. */
22
+ export type SpeakStreamFactory = (opts: DeepgramSpeakStreamOptions, onAudioChunk: SpeakChunkCallback, handlers?: {
23
+ onFlushed?: (sequenceId: number) => void;
24
+ onError?: (err: Error) => void;
25
+ }) => DeepgramSpeakStream;
26
+ export declare function createSpeakHandler(options: CreateSpeakHandlerOptions, streamFactory?: SpeakStreamFactory): SpeakHandler;
@@ -1,41 +1,97 @@
1
1
  "use strict";
2
- // Server-side text-to-speech for the Copilot widget's spoken answers (see
3
- // `speakEndpoint` in index.tsx). The Deepgram key must never reach the
4
- // client, so this is a plain fetch to Deepgram's /v1/speak REST endpoint —
5
- // no SDK dependency needed for one request shape.
6
2
  Object.defineProperty(exports, "__esModule", { value: true });
7
3
  exports.createSpeakHandler = createSpeakHandler;
8
- const DEEPGRAM_SPEAK_URL = "https://api.deepgram.com/v1/speak";
9
- // Verified against Deepgram's docs while building this re-check if this
10
- // starts erroring, voice model names retire over time.
4
+ // Server-side text-to-speech for the Copilot widget's spoken answers (see
5
+ // `speakEndpoint` in index.tsx). The Deepgram key must never reach the
6
+ // client.
7
+ //
8
+ // This used to be one fetch to Deepgram's /v1/speak REST endpoint, buffered
9
+ // into an ArrayBuffer with `await response.arrayBuffer()` before returning
10
+ // anything. That's the exact same bug the realtime path already fixed once
11
+ // (see tts-stream.ts's own comment): nothing plays until Deepgram renders
12
+ // AND the network delivers the *entire* reply, which measured 5-8s for a
13
+ // normal explain answer in real production logs. It also hit Deepgram's
14
+ // REST-only 2000-character cap on longer replies with no handling at all.
15
+ //
16
+ // Fixed the same way the realtime path was: open the streaming Speak
17
+ // WebSocket (tts-stream.ts's DeepgramSpeakStream, the same class the
18
+ // realtime server already uses) and forward audio chunks to the caller as
19
+ // they arrive, via a ReadableStream — not buffered. The route handler
20
+ // forwards that stream straight through as the HTTP response body, and the
21
+ // client (index.tsx) reads it progressively instead of awaiting a full
22
+ // Blob, so playback can start on the first chunk. Splitting the text into
23
+ // sentence-sized `Speak` messages before one `Flush` sidesteps the old
24
+ // 2000-char REST limit entirely (it doesn't apply to the WS protocol) and
25
+ // lets Deepgram start rendering the first sentence sooner.
26
+ const tts_stream_1 = require("./tts-stream");
11
27
  const DEEPGRAM_DEFAULT_VOICE = "aura-2-thalia-en";
12
- function createSpeakHandler(options) {
28
+ // Matches the realtime path's own playback sample rate (index.tsx's
29
+ // audio_chunk handling defaults to 24000 too) — keeping them identical lets
30
+ // both paths share one raw-PCM16 decode/schedule routine on the client.
31
+ const SAMPLE_RATE = 24000;
32
+ // Not a protocol limit (the WS Speak protocol has none like REST's 2000
33
+ // chars) — just keeps each queued chunk sentence-sized so Deepgram can start
34
+ // rendering the first one quickly instead of parsing one giant message.
35
+ const MAX_CHUNK_CHARS = 300;
36
+ function splitIntoChunks(text, maxChars) {
37
+ const sentences = text.match(/[^.!?]+[.!?]*\s*/g) ?? [text];
38
+ const chunks = [];
39
+ let current = "";
40
+ for (const sentence of sentences) {
41
+ if (current && current.length + sentence.length > maxChars) {
42
+ chunks.push(current);
43
+ current = "";
44
+ }
45
+ current += sentence;
46
+ }
47
+ if (current)
48
+ chunks.push(current);
49
+ return chunks;
50
+ }
51
+ function createSpeakHandler(options, streamFactory = (opts, onAudioChunk, handlers) => new tts_stream_1.DeepgramSpeakStream(opts, onAudioChunk, handlers)) {
13
52
  const model = options.model ?? process.env.DEEPGRAM_VOICE ?? DEEPGRAM_DEFAULT_VOICE;
14
53
  return async function handleSpeak(text) {
15
54
  if (!text || !text.trim()) {
16
55
  return { status: 400, body: { error: "no text provided" } };
17
56
  }
18
- let response;
57
+ let enqueue = null;
58
+ let closeOut = null;
59
+ let failOut = null;
60
+ const stream = new ReadableStream({
61
+ start(controller) {
62
+ enqueue = (chunk) => controller.enqueue(chunk);
63
+ closeOut = () => controller.close();
64
+ failOut = (err) => controller.error(err);
65
+ },
66
+ });
67
+ // True once connect() below resolves — an onError before that point is
68
+ // already reported through connect()'s own rejection, so it's ignored
69
+ // here to avoid double-handling the same failure.
70
+ let connected = false;
71
+ const speakStream = streamFactory({ apiKey: options.apiKey, model, encoding: "linear16", sampleRate: SAMPLE_RATE }, (chunk) => enqueue?.(new Uint8Array(chunk)), {
72
+ onFlushed: () => {
73
+ closeOut?.();
74
+ speakStream.close();
75
+ },
76
+ onError: (err) => {
77
+ if (!connected)
78
+ return;
79
+ console.error("[cairn] speak stream error:", err);
80
+ failOut?.(err);
81
+ },
82
+ });
19
83
  try {
20
- response = await fetch(`${DEEPGRAM_SPEAK_URL}?model=${encodeURIComponent(model)}`, {
21
- method: "POST",
22
- headers: {
23
- Authorization: `Token ${options.apiKey}`,
24
- "content-type": "application/json",
25
- },
26
- body: JSON.stringify({ text }),
27
- });
84
+ await speakStream.connect();
28
85
  }
29
86
  catch (err) {
30
87
  console.error("[cairn] speak request failed:", err);
31
88
  return { status: 200, body: { error: "speech service unreachable" } };
32
89
  }
33
- if (!response.ok) {
34
- const detail = await response.text().catch(() => "");
35
- console.error("[cairn] Deepgram speak returned an error:", response.status, detail);
36
- return { status: 200, body: { error: "speech synthesis failed" } };
90
+ connected = true;
91
+ for (const chunk of splitIntoChunks(text, MAX_CHUNK_CHARS)) {
92
+ speakStream.sendText(chunk);
37
93
  }
38
- const audio = await response.arrayBuffer();
39
- return { status: 200, body: { audio, contentType: response.headers.get("content-type") ?? "audio/mpeg" } };
94
+ speakStream.flush();
95
+ return { status: 200, body: { stream, contentType: `audio/L16;rate=${SAMPLE_RATE}` } };
40
96
  };
41
97
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cairnvibe/sdk",
3
- "version": "0.2.8",
3
+ "version": "0.2.10",
4
4
  "description": "In-app AI copilot — <Copilot/> for React/Next.js, <cairn-widget> for any framework — plus the server handlers and realtime voice relay behind them.",
5
5
  "license": "MIT",
6
6
  "publishConfig": { "access": "public" },