@livx.cc/agentx 0.99.14 → 0.99.16

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
@@ -3368,6 +3368,27 @@ var Agent = class _Agent {
3368
3368
  if (this.options.tools) this.options.tools = this.options.tools.filter((t) => !s.has(t.name));
3369
3369
  return before - this.activeTools.length;
3370
3370
  }
3371
+ /** Messages the host queued to steer the RUNNING turn (Claude-Code-style mid-turn input). The loop
3372
+ * drains them at each step boundary — after tool results are appended, before the next model call —
3373
+ * so they ride along with the latest tool results. A no-op between turns (nothing drains it). */
3374
+ pendingInjections = [];
3375
+ /** Queue a user message into the in-flight turn. It lands as a `user` message at the next step
3376
+ * boundary; if the model was about to stop, the injection re-opens the loop so it's never lost.
3377
+ * Pushing onto `transcript` directly from outside would race the loop — this drains inside it. */
3378
+ inject(content) {
3379
+ this.pendingInjections.push(content);
3380
+ }
3381
+ /** Drop any queued-but-unconsumed injections. The REPL calls this after a LOCAL command (/cmd, !bash)
3382
+ * — which runs no send() to drain them — so a mid-command steer can't leak into the next real turn. */
3383
+ clearInjections() {
3384
+ this.pendingInjections.length = 0;
3385
+ }
3386
+ /** Fold any host-injected messages into the transcript as user turns. Returns true if any landed. */
3387
+ drainInjections() {
3388
+ if (!this.pendingInjections.length) return false;
3389
+ for (const content of this.pendingInjections.splice(0)) this.transcript.push({ role: "user", content });
3390
+ return true;
3391
+ }
3371
3392
  constructor(options) {
3372
3393
  this.options = { ...new AgentOptions(), ...options };
3373
3394
  if (this.options.fs) this.buildCtx();
@@ -3633,6 +3654,7 @@ var Agent = class _Agent {
3633
3654
  });
3634
3655
  }
3635
3656
  if (toolCalls.length === 0) {
3657
+ if (this.drainInjections()) continue;
3636
3658
  log4.verbose(`completed in ${steps} step(s)`);
3637
3659
  await this.ctx.jobs?.drain();
3638
3660
  await this.activeHooks?.onStop?.(res.content ?? "");
@@ -3657,6 +3679,7 @@ var Agent = class _Agent {
3657
3679
  }
3658
3680
  this.transcript.push({ role: "tool", tool_call_id: tc.id, name: tc.function.name, content });
3659
3681
  }
3682
+ this.drainInjections();
3660
3683
  }
3661
3684
  }
3662
3685
  /**
@@ -4474,14 +4497,14 @@ function makeScheduleTools(scheduler, os) {
4474
4497
  backend: { type: "string", enum: ["auto", "session", "os"], description: "Where the job lives (default auto)." }
4475
4498
  }
4476
4499
  },
4477
- async run({ prompt, trigger, label, backend }) {
4500
+ async run({ prompt, trigger, label, backend: backend2 }) {
4478
4501
  try {
4479
- if (os && os.route(trigger, backend) === "os") {
4502
+ if (os && os.route(trigger, backend2) === "os") {
4480
4503
  const id2 = `os-${Date.now().toString(36)}`;
4481
4504
  const mechanism = os.schedule({ id: id2, prompt, sessionId: os.sessionId, cwd: os.cwd, trigger, label });
4482
4505
  return `Scheduled ${id2}${label ? ` (${label})` : ""} on the OS scheduler (${mechanism}) \u2014 survives quitting; fires \`agentx --resume ${os.sessionId}\` headless.`;
4483
4506
  }
4484
- if (backend === "os") return "Error: no OS scheduler available on this platform \u2014 job not created (use the default in-session backend).";
4507
+ if (backend2 === "os") return "Error: no OS scheduler available on this platform \u2014 job not created (use the default in-session backend).";
4485
4508
  const id = scheduler.add({ prompt, trigger, label });
4486
4509
  const job = scheduler.get(id);
4487
4510
  const next = scheduler.nextFire(job);
@@ -4773,9 +4796,37 @@ function digestRun(messages, maxChars) {
4773
4796
  import { MemFilesystem as MemFilesystem2 } from "@livx.cc/wcli/core";
4774
4797
  init_logging();
4775
4798
 
4776
- // src/voice/emotion.ts
4777
- init_logging();
4778
- var log9 = forComponent("Emotion");
4799
+ // node_modules/@bod.ee/voice/src/core/logging.ts
4800
+ function consoleForComponent(name) {
4801
+ const debugEnv = typeof process !== "undefined" && process.env?.DEBUG || typeof localStorage !== "undefined" && localStorage.getItem("DEBUG") || "";
4802
+ const gated = debugEnv === "*" || debugEnv.split(",").some((p) => p.trim() === name);
4803
+ const gate = (fn) => gated ? fn : () => {
4804
+ };
4805
+ const tag = `[${name}]`;
4806
+ return {
4807
+ debug: gate((...a) => console.debug(tag, ...a)),
4808
+ verbose: gate((...a) => console.debug(tag, ...a)),
4809
+ info: (...a) => console.info(tag, ...a),
4810
+ warn: (...a) => console.warn(tag, ...a),
4811
+ error: (...a) => console.error(tag, ...a)
4812
+ };
4813
+ }
4814
+ var backend = consoleForComponent;
4815
+ function configureLogging(forComponentImpl) {
4816
+ backend = forComponentImpl;
4817
+ }
4818
+ function forComponent2(name) {
4819
+ return {
4820
+ debug: (...a) => backend(name).debug(...a),
4821
+ verbose: (...a) => backend(name).verbose(...a),
4822
+ info: (...a) => backend(name).info(...a),
4823
+ warn: (...a) => backend(name).warn(...a),
4824
+ error: (...a) => backend(name).error(...a)
4825
+ };
4826
+ }
4827
+
4828
+ // node_modules/@bod.ee/voice/src/core/emotion.ts
4829
+ var log9 = forComponent2("Emotion");
4779
4830
  var EMOTIONS = [
4780
4831
  // primary (best results)
4781
4832
  "neutral",
@@ -4951,9 +5002,8 @@ var EmotionStream = class {
4951
5002
  }
4952
5003
  };
4953
5004
 
4954
- // src/voice/engine.ts
4955
- init_logging();
4956
- var log10 = forComponent("VoiceEngine");
5005
+ // node_modules/@bod.ee/voice/src/core/engine.ts
5006
+ var log10 = forComponent2("VoiceEngine");
4957
5007
  var realClock = {
4958
5008
  now: () => performance.now(),
4959
5009
  setTimeout: (fn, ms) => setTimeout(fn, ms),
@@ -5137,6 +5187,13 @@ var VoiceEngine = class _VoiceEngine {
5137
5187
  // the exact ack text last spoken (fixed OR adaptive) — the echo-leak guard matches it
5138
5188
  ackTimer = null;
5139
5189
  // one-shot adaptive-ack timer (armed at dispatch, cancelled on first delta)
5190
+ // The adaptive micro-ack ALREADY spoke this turn → the reflex's own leading ack ("Still on it.") is now
5191
+ // redundant (live: host said "On it." then the reflex said "Still on it."). While this is set, speakDelta
5192
+ // probes the reflex's opening sentence and DROPS it if it's purely an acknowledgement; real content passes
5193
+ // through. Reset per turn in beginSpeech()/interrupt().
5194
+ adaptiveAckFired = false;
5195
+ ackProbe = null;
5196
+ // buffered reflex prose while probing the leading ack (null = not probing)
5140
5197
  bargeGraceUntil = 0;
5141
5198
  // no barge-in until this time — the user's OWN trailing audio (after the
5142
5199
  // utterance that JUST dispatched this turn) must not immediately re-interrupt the reply it requested.
@@ -5279,6 +5336,8 @@ var VoiceEngine = class _VoiceEngine {
5279
5336
  this.speaking = true;
5280
5337
  this.ctxOpen = true;
5281
5338
  this.spokeDeltas = false;
5339
+ this.adaptiveAckFired = false;
5340
+ this.ackProbe = null;
5282
5341
  this.reply = "";
5283
5342
  this.revealText = "";
5284
5343
  this.wordStarts = [];
@@ -5307,6 +5366,8 @@ var VoiceEngine = class _VoiceEngine {
5307
5366
  this.lastAck = phrase;
5308
5367
  for (const w of this.words(phrase)) this.echoWords.add(w);
5309
5368
  this.setState("speaking");
5369
+ this.adaptiveAckFired = true;
5370
+ this.ackProbe = "";
5310
5371
  this.options.onAdaptiveAck();
5311
5372
  }, this.options.adaptiveAckMs);
5312
5373
  }
@@ -5318,6 +5379,25 @@ var VoiceEngine = class _VoiceEngine {
5318
5379
  speakDelta(text) {
5319
5380
  if (this.interrupted) return "";
5320
5381
  this.clearAckTimer("first_delta");
5382
+ if (this.adaptiveAckFired && this.ackProbe !== null) {
5383
+ this.ackProbe += text;
5384
+ const probe = this.ackProbe;
5385
+ const bare = probe.replace(/\[emotion[^\]]*\]/gi, "").replace(/^\s+/, "");
5386
+ const m = bare.match(/^([^.!?…\n]*[.!?…\n])([\s\S]*)$/);
5387
+ if (!m && bare.length < 80) return "";
5388
+ this.ackProbe = null;
5389
+ this.adaptiveAckFired = false;
5390
+ const lead = m ? m[1] : bare;
5391
+ const norm2 = lead.replace(/[^a-z ]/gi, " ").replace(/\s+/g, " ").trim().toLowerCase();
5392
+ if (_VoiceEngine.ACK_LEADING.test(norm2)) {
5393
+ const rest = m ? m[2] : "";
5394
+ this.diag("reflex_ack_suppressed", { lead: lead.trim() });
5395
+ if (!rest.trim()) return "";
5396
+ text = rest;
5397
+ } else {
5398
+ text = probe;
5399
+ }
5400
+ }
5321
5401
  if (!this.speaking || !this.ctxOpen) this.beginSpeech();
5322
5402
  let { speech, display, prose } = this.emo ? this.emo.feed(text) : { speech: text, display: text, prose: text };
5323
5403
  if (this.reply && /[.!?…]$/.test(this.reply) && /^[A-Z]/.test(prose)) {
@@ -5376,6 +5456,14 @@ var VoiceEngine = class _VoiceEngine {
5376
5456
  endSpeech() {
5377
5457
  this.interrupted = false;
5378
5458
  this.clearAckTimer("turn_end");
5459
+ const heldProbe = this.ackProbe;
5460
+ this.adaptiveAckFired = false;
5461
+ this.ackProbe = null;
5462
+ if (heldProbe) {
5463
+ const norm2 = heldProbe.replace(/\[emotion[^\]]*\]/gi, "").replace(/[^a-z ]/gi, " ").replace(/\s+/g, " ").trim().toLowerCase();
5464
+ if (_VoiceEngine.ACK_LEADING.test(norm2)) this.diag("reflex_ack_suppressed", { lead: heldProbe.trim() });
5465
+ else this.speakDelta(heldProbe);
5466
+ }
5379
5467
  if (!this.speaking) return;
5380
5468
  this.diag("tts_turn_end", { spoke: this.spokeDeltas, replyChars: this.reply.length });
5381
5469
  this.ctxOpen = false;
@@ -5457,6 +5545,9 @@ var VoiceEngine = class _VoiceEngine {
5457
5545
  * No 'Okay.': a genuine user "Okay." within the 6s squash window would be swallowed as ack echo. */
5458
5546
  static ACKS_NEUTRAL = ["Mm-hm.", "One sec.", "Right.", "Sec.", "On it.", "Sure, moment.", "Uh, one moment.", "Let me see."];
5459
5547
  static ACKS_QUESTION = ["Hmm.", "Let me think.", "Hm, let me see.", "Good question.", "Mm, one sec.", "Let's see."];
5548
+ /** A reflex opening sentence that is PURELY an acknowledgement (no content) — dropped when the adaptive
5549
+ * micro-ack already spoke one. Anchored end-to-end so only a whole ack-only clause matches. */
5550
+ static ACK_LEADING = /^(?:(?:okay|ok|alright|sure|yeah|yep|right|got it|on it|still|still on it|still working on it|working on it|checking|one sec|one moment|mm hm|mmhm|hmm|let me (?:see|check|think))[ ,]*)+$/;
5460
5551
  recentAcks = [];
5461
5552
  pickAck() {
5462
5553
  const pool = this.lastDispatchWasQuestion ? _VoiceEngine.ACKS_QUESTION : _VoiceEngine.ACKS_NEUTRAL;
@@ -5481,6 +5572,8 @@ var VoiceEngine = class _VoiceEngine {
5481
5572
  /** barge-in: stop audio NOW, cancel generation, reset for the user's utterance */
5482
5573
  interrupt() {
5483
5574
  this.clearAckTimer("interrupt");
5575
+ this.adaptiveAckFired = false;
5576
+ this.ackProbe = null;
5484
5577
  if (this.uttQueue.length) log10.info(`barge-in dropped ${this.uttQueue.length} queued worker utterance(s)`);
5485
5578
  const droppedQueued = this.uttQueue.length;
5486
5579
  this.uttQueue = [];
@@ -5941,7 +6034,14 @@ var VoiceEngine = class _VoiceEngine {
5941
6034
  }
5942
6035
  };
5943
6036
 
5944
- // src/voice/spokenSplitter.ts
6037
+ // node_modules/@bod.ee/voice/src/core/types.ts
6038
+ var STT_SAMPLE_RATE = 16e3;
6039
+ var TTS_SAMPLE_RATE = 44100;
6040
+ async function resolveAuth(auth) {
6041
+ return typeof auth === "function" ? await auth() : auth;
6042
+ }
6043
+
6044
+ // node_modules/@bod.ee/voice/src/core/spokenSplitter.ts
5945
6045
  var OPEN = "<spoken>";
5946
6046
  var CLOSE = "</spoken>";
5947
6047
  var CLOSERS = `"')]}\xBB\u201D\u2019`;
@@ -6013,1652 +6113,1647 @@ var SpokenSplitter = class {
6013
6113
  }
6014
6114
  };
6015
6115
 
6016
- // src/duplex.ts
6017
- var log11 = forComponent("DuplexAgent");
6018
- function describeCall(call) {
6019
- const v = call.args && Object.values(call.args).find((x) => typeof x === "string" && x.trim());
6020
- const hint = v ? ` (${String(v).replace(/\s+/g, " ").trim().slice(0, 48)})` : "";
6021
- return `${call.name}${hint}`;
6022
- }
6023
- var DuplexAgentOptions = class {
6024
- /** Any ai.libx.js AIClient — shared by all tiers (routed by model). */
6025
- ai;
6026
- /** The WORKER's filesystem (act + think). If omitted the worker keeps Agent's jailed-disk-at-cwd default. */
6027
- fs;
6028
- // The reflex IS the voice. 120b (not 20b) for channel discipline + instruction-following: the 20b
6029
- // mislabels gpt-oss harmony channels under load, leaking raw analysis into the spoken `final` channel
6030
- // (and misfiring Hold). 120b is the same price tier (~$0.15/$0.60) — the quality/cost trade is free.
6031
- reflexModel = "groq/openai/gpt-oss-120b";
6032
- actModel = "anthropic/claude-sonnet-4-6";
6033
- /** Premium reasoning model. Set to `false` to disable the Think tier entirely. */
6034
- thinkModel = "anthropic/claude-opus-4-8";
6035
- /** Per-worker providerOptions, derived from the worker's actual model at spawn time (IoC — keeps duplex
6036
- * provider-agnostic). Workers override the reflex/main model, so provider-specific options (e.g. cursor's
6037
- * cwd/cursorSession) must be recomputed for the worker's model, never inherited from the main template —
6038
- * leaking cursor options to an anthropic worker is a hard 400. Returns undefined → no providerOptions. */
6039
- providerOptionsFor;
6040
- /** Escape hatches merged over the derived per-agent options. */
6041
- reflexOptions;
6042
- actOptions;
6043
- thinkOptions;
6044
- /** Fresh-context check on each successful Act task: a NEW agent (no self-confirmation bias) re-reads
6045
- * the file state against the brief and fixes any gap before the result is re-voiced. Bounded to one
6046
- * pass; ~2x Act cost so default OFF. The self-verify FOOTER (same context) was measured ineffective —
6047
- * this is the structural fix (see mind/10). Think tasks are pure reasoning, never checked. */
6048
- verifyActTasks = false;
6049
- /** Receives the voice text_delta stream + task lifecycle events. */
6050
- host;
6051
- /** How many recent transcript messages are rendered into a worker's brief. */
6052
- excerptTurns = 6;
6053
- /** Voice register: 'neutral' = clean spoken style; 'conversational' = human-like — fillers,
6054
- * backchannels, impulsive first reactions before content (mimics real duplex conversation). */
6055
- voiceStyle = "neutral";
6056
- /** Teach the model to emit inline `[emotion]` tags for Cartesia emotion control. Only set when the
6057
- * TTS actually speaks them — text-duplex (no TTS) would otherwise print literal tags. */
6058
- emotionTags = false;
6059
- /** Awaited BEFORE a worker spawns — open a per-task checkpoint frame, audit, etc.
6060
- * (post-spawn would race the worker's first edits). */
6061
- onTaskStart;
6062
- /** Re-voice throttled worker progress asides ('[task t1 progress] …') so long tasks aren't dead
6063
- * air. Off by default — each update costs a voice turn (LLM call + speech). */
6064
- progressUpdates = false;
6065
- /** Min ms between progress re-voices per task. */
6066
- progressIntervalMs = 25e3;
6067
- /** Relay worker questions (AskUserQuestion + permission asks via parkQuestion) through the VOICE:
6068
- * the question re-voices as '[task <id> asks] …', the user answers conversationally, and the
6069
- * voice model resolves it with the AnswerTask tool. Off → host.ask passthrough (text menus). */
6070
- askRelay = false;
6071
- /** Parked questions auto-resolve empty after this long (callers map '' to deny/best-judgment). */
6072
- askTimeoutMs = 12e4;
6073
- /** Max retained task records: oldest SETTLED tasks (and their activity tails) are evicted past this,
6074
- * bounding memory over a long-lived session. Running tasks are never evicted. */
6075
- maxTaskRecords = 50;
6076
- /** Host overrides for QuickLook lookups (keyed by `what`). The engine's defaults go through the
6077
- * (possibly jailed) fs — e.g. `.git/**` is deny-listed, so the CLI supplies 'branch' itself. */
6078
- quickLook;
6079
- /** Memory directory/directories on the WORKER fs. If set, the voice agent gets Remember + Recall
6080
- * tools directly (no delegation needed) and implicit capture guidance. */
6081
- memoryDir;
6082
- /** User-scope memory dir for global facts (type=user/feedback). Forwarded to Remember's routing. */
6083
- memoryUserDir;
6116
+ // node_modules/@bod.ee/voice/src/adapters/soniox.ts
6117
+ var log11 = forComponent2("SonioxSTT");
6118
+ var now = () => performance.now();
6119
+ var SonioxSTTOptions = class {
6120
+ auth = "";
6121
+ source;
6122
+ model = "stt-rt-preview";
6123
+ languageHints = ["en"];
6124
+ /** Client-side endpoint: finalized text + no new tokens for this long = utterance (don't wait for
6125
+ * Soniox's semantic <end>, which adds 0.5-1.5s — the difference between ping-pong and lag). */
6126
+ silenceEndpointMs = 500;
6127
+ /** No-audio watchdog: if the mic source stops delivering chunks for this long, capture is dead →
6128
+ * fire onFatal + stop (else Soniox idle-timeouts and reconnect-loops forever). 0 = disable. */
6129
+ noAudioTimeoutMs = 1e4;
6084
6130
  };
6085
- var RESERVED_EVENT_MARKER = /\[task\b[^\]\n]*\b(?:completed|failed|progress|asks)\b/i;
6086
- var RESERVED_EVENT_OPENER = /\[\s*task\b/i;
6087
- var STAGE_DIRECTION_RE = /^\(\s*(?:(?:waiting|checking|searching|thinking|processing|loading|working|fetching|looking)\b[^)]*|[^)]*(?:\.\.\.|…)\s*)\)$/i;
6088
- function nowLine() {
6089
- return `Current date and time: ${(/* @__PURE__ */ new Date()).toLocaleString("en-US", { weekday: "long", year: "numeric", month: "long", day: "numeric", hour: "numeric", minute: "2-digit", timeZoneName: "short" })}`;
6090
- }
6091
- function isTrivialBarge(text) {
6092
- const t = text.trim().toLowerCase().replace(/[.,!?…\s]+$/g, "").replace(/^[.,!?…\s]+/, "");
6093
- if (!t) return false;
6094
- if (/\b(stop|cancel|no|nope|nah|never\s?mind|nvm|forget it|drop it|don'?t|quiet|shut up|enough|hold on|wait|pause|hang on|actually)\b/.test(t)) return false;
6095
- const core = t.replace(/^(?:oh|um+|uh+|er+|hmm+|ah+|well|so|okay|ok|yeah|yep)[\s,]+/, "").trim();
6096
- return /^(?:oh|um+|uh+|er+|hmm+|ah+|sorry|oops|whoops|my bad|pardon|excuse me|apologies|go on|go ahead|continue|keep going|carry on|as you were|please continue|you were saying|sorry go on|sorry continue|go on then|go on please)$/.test(core || t);
6097
- }
6098
- var VOICE_SYSTEM_PROMPT = 'You are a spoken voice assistant \u2014 the user HEARS everything you say. Use short sentences. One idea per sentence. No markdown, no bullet lists, no code blocks, no headings, no emoji. Never emit stage directions or parenthetical asides about your own process \u2014 nothing like "(waiting for the result...)" or "(checking)"; while work runs, either say it as plain speech or end your turn.\nThis holds even when asked to "print", "list", "show", or "make a table" \u2014 there is no screen for the spoken channel. Speak it as flowing prose ("Tuesday is half a meter, Wednesday a bit less\u2026"), or if they truly need it on screen, route it to Act to render. Never emit dashes or pipes into speech.\nKeep turns SHORT \u2014 one to three sentences, then stop. Never lecture, enumerate cases, or add caveats unprompted. Conversation is a fast exchange: give the one thing asked, and let the user pull more if they want it.\nYou have three cognitive tiers \u2014 like a human brain:\n\u2022 YOU (reflex) \u2014 instant, lightweight. Handle greetings, simple questions, status checks, QuickLook.\n\u2022 `Act` \u2014 your hands. A background worker with its own configured tools and access to the user\'s environment (files and shell{{WORKER_WEB}}). Use for reading, editing, searching, running tasks, building \u2014 any real work.\n{{THINK_SLOT}}\nWhen you are unsure whether you can do or access something, do NOT assume and do NOT claim a capability you have not confirmed. To check what you can do, QuickLook `capabilities` (instant \u2014 it lists your worker\'s real tools) and answer from that. Never promise an ability that is not in your capabilities; if it is not there, tell the user plainly you can\'t. To actually DO real work, call `Act`. When the user mentions their project, folder, files, or environment ("this project", "the current folder", "my code"), call `Act` IMMEDIATELY \u2014 do not ask for paths or details the worker can discover itself. Never pretend to have done the work or invent results \u2014 the worker\'s report is your only source.\nYou cannot mute the microphone or stop voice capture yourself \u2014 no tool does it. If the user asks you to stop listening or turn the voice off, never claim you did: tell them to say exactly "voice off" (handled by the app directly), or type /voice.\nYou are NOT a knowledge base. For any question whose answer needs SPECIFIC verifiable facts you do not already have in hand \u2014 how to build/configure/implement something, exact API, library, entitlement, command or option names, current events, or particular numbers, dates, or names \u2014 do NOT answer from your own memory: you will confidently make things up (a fake API, a wrong entitlement, an event that did not happen). Route it to `Act`, which can search and verify, and speak only what its report says. DELEGATION RULE \u2014 decide for yourself, the user never has to push: if you cannot answer confidently from the conversation plus trivial well-known knowledge, do NOT refuse and do NOT guess \u2014 dispatch `Act` immediately with a clear brief and say you are checking. Anything needing CURRENT data (weather, news, prices, dates, sky/astronomy, "right now"), real computation, or verification is an automatic dispatch \u2014 never a refusal. The user should never need to say "search the web" or "think harder" to make you act; needing fresh or verified information IS the trigger. Refuse only what your worker genuinely cannot do (check `capabilities`), and say why. Answer inline ONLY for general conversation, chit-chat, and trivia you are sure of, or facts you can see via QuickLook. When elaborating on a completed task ("tell me more", "the gist"), stay strictly within what that result actually said \u2014 if the user asks for something the result did not cover, that is NEW information: dispatch `Act`, do not improvise.\nALWAYS react before you work: the FIRST thing in your turn is a brief spoken acknowledgement of what you heard and what you are about to do ("got it \u2014 opening that now", "sure, let me pull it up", "okay, checking"). NEVER call a tool (Act, Think, QuickLook) silently \u2014 the user must hear you react before you go quiet to work. After dispatching Act or Think, that same one short sentence IS your turn \u2014 end it and do not wait for the result. Exactly ONE short line: never stack a second acknowledgement, and never narrate your own presence or status while waiting ("I\'m here", "let me see", "still checking" right after you already acked). One clean ack then silence reads as competent; repeated check-ins read as nervous.\nA completed task speaks its OWN result to the user (the worker voices what matters as it finishes) \u2014 you do NOT re-voice clean task results. A FAILED or INCOMPLETE task still arrives as a "[task t1 failed] \u2026" event for you to handle. The completed result stays in YOUR context \u2014 it is yours to draw on. When the user follows up ("tell me more", "what else", "and?"), answer FROM that result first: you already have the detail, so elaborate on what you have. Do NOT spawn a fresh worker to re-search or re-gather what you were just handed. Re-dispatch ONLY when genuinely new information is needed \u2014 e.g. the user wants the full contents of a SPECIFIC source, which is one WebFetch of that URL, not a brand-new search. "[task t1 progress] \u2026" events are interim status, NOT results \u2014 on a genuinely LONG wait you MAY give one brief half-sentence aside, but only occasionally; silence while working is normal and fine (the user knows you are on it). Do NOT narrate every step or re-announce yourself. Never present progress as a finished result.\nCRITICAL: while a task is still running you have NO answer yet \u2014 never state a specific result of any kind (a number, size, count, name, path, or value). The real answer arrives ONLY in the "[task \u2026 completed]" event; inventing one meanwhile (a made-up disk size, commit count, etc.) is a serious error. Until then, only acknowledge and wait.\nNever read raw file paths, diffs, or code aloud verbatim.\nDo NOT end every turn with the same canned offer ("want a rundown?", "want the steps?"). Offer once at most; if the user pushes back, repeats themselves, or sounds unsatisfied ("you know what I mean?", "think deeper", "are you sure?"), do NOT re-offer the same thing \u2014 change approach: dispatch `Act`/`Think` to actually dig in, or ask one concrete clarifying question. Repeating a non-answer is worse than silence.\n"[task t1 asks] \u2026" events are QUESTIONS from a background task \u2014 relay to the user in your own words, short, then end your turn. When the user answers, call `AnswerTask` with that id and their answer. NEVER answer on the user\'s behalf for permissions or risky operations; if their reply is ambiguous, confirm first.\nIf the user\'s message sounds INCOMPLETE \u2014 trailing off mid-sentence, a fragment that needs more context ("and then we", "but the problem is"), hesitation fillers ("uh", "um") \u2014 call `Hold` instead of answering. This keeps listening for the rest of their thought. Only respond with substance when you have a complete question or request.\nDispatch discipline: send ONE self-contained task per request \u2014 a single worker with the full brief beats several workers with fragments (each worker starts fresh and re-discovers context). NEVER dispatch a worker just to read files or gather information \u2014 workers explore and discover context themselves; pass on what you already know and let one worker do the whole job. Split into parallel tasks only when the user asks for genuinely independent things. When a task completes, report its result and stop \u2014 do NOT dispatch follow-up work (verification, polish, extras) the user did not ask for, unless the report itself signals failure or doubt.\nDo not fire a second Act/Think for work already in flight, and NEVER spawn a second task to re-count, cross-check, or verify a result a worker already gave you \u2014 trust its answer; a single question gets ONE task. Call `TaskStatus` at most ONCE per turn; if a task is still running, just say "still on it" and end the turn \u2014 never poll it again and again in a loop. Use `CancelTask` when the user asks to stop something.\nPRIORITY: when the user says goodbye or wants to end/finish/wrap up the session ("ok bye", "that\'s all", "let\'s finish", "let\'s end", "goodnight", "exit", "wrap up"), call `ExitSession` IMMEDIATELY \u2014 do not act, do not check status, just exit.\nFor TRIVIAL instant lookups only \u2014 current time, git branch, listing a folder, peeking at a small file, or checking your own `capabilities`/tools \u2014 use `QuickLook` (instant, no task). Whenever the user asks what you can do or whether you have some ability, QuickLook `capabilities` and answer from that \u2014 never guess. Anything requiring searching, reasoning, running commands, or editing goes through `Act`.\n{{MEMORY_SLOT}}\nUser messages may arrive via speech-to-text and can carry transcription artifacts \u2014 odd words, cut-offs, homophones ("for you" vs "folder"). Read for INTENT, not surface text. If a message seems garbled, surprising, or only half-parses, do NOT guess an action or improvise content from it \u2014 briefly confirm what they meant ("did you mean\u2026?") and wait. A one-line confirm beats a confident wrong answer or an invented response to a request you did not actually understand.';
6099
- var THINK_GUIDANCE = "\u2022 `Think` \u2014 your brain. A premium reasoning model, FAR more expensive than Act. Reserve it for open-ended architecture/design questions, or a problem Act already FAILED at. ALL implementation work \u2014 coding, refactoring, debugging, edge cases, tests \u2014 goes to Act; Act is highly capable. Never send the same work to both.";
6100
- var THINK_DISABLED_GUIDANCE = "(Think tier is not available \u2014 use Act for all escalations.)";
6101
- var VOICE_STYLE_CONVERSATIONAL = `Speak like a person in a live conversation, not an assistant reading a script. React first, then deliver: a quick impulsive beat ("oh nice", "hmm, hold on", "ah, got it") before the substance. Use contractions always. Vary sentence length \u2014 some very short. Light fillers and backchannels are fine ("mm-hm", "right", "let's see") but at most one per reply \u2014 never stack them. When you escalate to Act or Think, say it like a human would ("hang on, let me actually dig into that \u2014 gimme a minute") instead of announcing a task. When a result comes back, react to it like you just found out ("okay so \u2014 turns out\u2026"). Match the user's energy: a quick question gets a quick answer \u2014 a few words is a perfectly good turn. Prefer a short answer plus an offer ("want the details?") over covering everything. Never narrate your own mechanics (no "I will now act", no task ids out loud).`;
6102
- var EMOTION_TAGS_GUIDANCE = `EMOTION: your voice is synthesized with emotion control. Prefix a sentence with an inline [emotion] tag, placed directly before the sentence it colors, to shape how it is spoken. Use it ONLY when the emotion genuinely fits the words (it amplifies real feeling, it cannot fake it) \u2014 do not tag every sentence; reserve it for moments that carry feeling, and vary which one you use. You may also drop [laughter] for a natural laugh. Available emotions: ${EMOTIONS.join(", ")}.`;
6103
- var DuplexAgent = class _DuplexAgent {
6131
+ var SonioxSTT = class {
6104
6132
  options;
6105
- voice;
6106
- tasks = /* @__PURE__ */ new Map();
6107
- queue = Promise.resolve();
6108
- seq = 0;
6109
- pendingEvents = [];
6110
- /** Spoken text of parked deliveries that have SETTLED, awaiting a trivial-barge resume decision on the
6111
- * next turn (a substantive turn clears it — the result stays in the transcript, recoverable by asking). */
6112
- parkedRedeliver = [];
6113
- /** A trivial barge arrived while a parked delivery was STILL RUNNING → resume it the moment it settles. */
6114
- awaitTrivialRedeliver = false;
6115
- /** Set by a SUBSTANTIVE turn after a barge: the user moved on, so a parked delivery that settles LATER
6116
- * must NOT arm a resume (else a much-later "go on" replays a stale result). Reset by a fresh barge. */
6117
- suppressParkedResume = false;
6118
- /** Out-of-band follow-up attribution for the events coalescing into the next flush turn: TRUE iff ≥1 of
6119
- * the tasks being integrated was NON-CLEAN (early-stop/failure). Carried out-of-band on the enqueue call
6120
- * by the caller that KNOWS the outcome — a plain boolean the MODEL CANNOT PERTURB. It is NOT scanned from
6121
- * worker-authored event text (v1: an "Outcome:" substring over-stamped siblings) and NOT keyed on a brief
6122
- * string the reflex re-authors (v2: a paraphrased escalation brief missed the Set → followUp:false →
6123
- * RE-ENABLED unbounded auto-escalation, the dangerous runaway direction). See [[wrong-discriminator]] /
6124
- * [[drive-real-reflex]] / [[fakeaiclient-blind-to-wire-format]]. */
6125
- pendingNonClean = false;
6126
- flushQueued = false;
6127
- /** Per-voice-turn guards (reset by resetTurn at each turn's start). The reflex is a weak model:
6128
- * left unguarded it polls TaskStatus after a dispatch and/or dispatches silently (dead air).
6129
- * Like CC's Task tool, a dispatch is "said my piece, now wait for the push" — these enforce that. */
6130
- turnDispatched = false;
6131
- // an Act/Think fired this turn
6132
- spokeBeforeDispatch = false;
6133
- // the reflex ALREADY acked before dispatching — the forced post-dispatch text step must stay silent (live: "Got it…" twice)
6134
- turnBriefs = /* @__PURE__ */ new Set();
6135
- // briefs dispatched this turn (detect identical re-dispatch)
6136
- spokeThisTurn = false;
6137
- // any non-empty text_delta streamed this turn
6138
- externalSpeech = false;
6139
- // host spoke on our behalf (adaptive micro-ack) — not reflex output
6140
- heldThisTurn = false;
6141
- // Hold called this turn → turn is INTENTIONALLY silent (suppress reflex text + no dead-air ack)
6142
- nudging = false;
6143
- // re-ack pass in flight: block ALL tools, prevent recursion
6144
- reflexBuf = "";
6145
- // accumulated reflex text this turn (fabricated-event detection)
6146
- reflexForwarded = 0;
6147
- // chars of reflexBuf already forwarded to the host/TTS
6148
- fabricationCut = false;
6149
- // reflex emitted a reserved [task …] marker → suppress its tail
6150
- /** TRUE for the duration of a re-voice turn that is integrating ≥1 NON-CLEAN task (turn-eligibility,
6151
- * carried out-of-band — NOT derived from any worker/brief string). ANY Act/Think dispatched in such a
6152
- * turn is stamped followUp:true. This GUARANTEES the dangerous direction is impossible: a genuine
6153
- * escalation (even one with a paraphrased brief) ALWAYS lands in a non-clean integration turn, so it is
6154
- * ALWAYS recognized as a follow-up and CANNOT re-escalate (one hop). The single-dispatch-per-turn guard
6155
- * means at most one dispatch happens per flush, so realistically "the one dispatch IS the escalation".
6156
- * ACCEPTED SAFE-DIRECTION ERROR: if the reflex instead dispatches FRESH unrelated work during a non-clean
6157
- * flush (rare — and only possible when it batches multiple calls in one step, bypassing the guard), that
6158
- * fresh task is over-stamped followUp:true and forgoes ONE future auto-escalation. That is SAFE (it only
6159
- * ever REMOVES a future escalation, never adds one — no runaway) and is the correct side to err on. */
6160
- turnFollowUp = false;
6161
- /** Hard absolute backstop against runaway regardless of attribution: total automatic escalations across
6162
- * the whole conversation. Once it hits MAX_AUTO_ESCALATIONS, no integration turn offers escalate/re-delegate. */
6163
- autoEscalations = 0;
6164
- static MAX_AUTO_ESCALATIONS = 8;
6165
- /** Parked worker questions awaiting a (voice-relayed) user answer, keyed by ask id. */
6166
- pendingAsks = /* @__PURE__ */ new Map();
6167
- /** SPECULATIVE REFLEX (VoiceEngine.onSpeculate → speculate()): the reflex turn starts on a stable
6168
- * PARTIAL transcript, its spoken output buffered — nothing reaches TTS until the endpointed final
6169
- * confirms via send() (which flushes the buffer and adopts the call as THE turn). A divergent final
6170
- * aborts it: output dropped, history rolled back, the final dispatches normally. */
6171
- spec;
6172
- /** Aborted speculative calls (double-billing visibility — each one paid for tokens never spoken). */
6173
- speculativeAbortedCalls = 0;
6174
- /** Tools the reflex may execute on UNCONFIRMED (speculated) input — read-only lookups and the
6175
- * intentionally-silent Hold. Anything else (Act/Think/AnswerTask/CancelTask/ExitSession/memory
6176
- * writes/…) is a side effect on input the user may not have said: the guard ABORTS the speculation
6177
- * instead (the endpointed final then dispatches normally and may use the tool for real). */
6178
- static SPEC_SAFE_TOOLS = /* @__PURE__ */ new Set(["QuickLook", "TaskStatus", "Hold"]);
6179
- /** Lazily resolved memory tools (async loadMemory runs in initMemory). */
6180
- memoryReady;
6181
- constructor(options) {
6182
- this.options = { ...new DuplexAgentOptions(), ...options };
6183
- const o = this.options;
6184
- if (o.memoryDir && o.fs) {
6185
- this.memoryReady = loadMemory(o.fs, o.memoryDir, { maxWritesPerSession: 10, userDir: o.memoryUserDir });
6133
+ ws;
6134
+ stopped = false;
6135
+ sourceStarted = false;
6136
+ onPartial = () => {
6137
+ };
6138
+ onUtterance = () => {
6139
+ };
6140
+ /** mic energy (RMS) per chunk — drives the energy-based heuristic barge-in tier */
6141
+ onLevel = () => {
6142
+ };
6143
+ /** Unrecoverable: the mic source stopped delivering audio (Soniox starves → idle-timeout reconnect
6144
+ * loop). The host tears voice down instead of spinning forever. */
6145
+ onFatal = () => {
6146
+ };
6147
+ /** Diagnostic tap (provider errors, ws reconnects, no-audio watchdog). Fire-and-forget: a throwing
6148
+ * handler disables itself — never affects transcription. Wired by VoiceIO / the lab bridge. */
6149
+ onDiag = () => {
6150
+ };
6151
+ diagOn = true;
6152
+ diag(kind, fields) {
6153
+ if (!this.diagOn) return;
6154
+ try {
6155
+ this.onDiag({ t: now(), kind, ...fields });
6156
+ } catch (e) {
6157
+ this.diagOn = false;
6158
+ log11.debug(`onDiag threw \u2014 STT diagnostics disabled: ${e instanceof Error ? e.message : e}`);
6186
6159
  }
6187
- const memSlot = o.memoryDir && o.fs ? VOICE_MEMORY_PROMPT : "NEVER claim to have stored, saved, or remembered something durably \u2014 you cannot. Anything the user wants persisted (their name, preferences, notes) must go through Act so a worker writes it to memory.";
6188
- const thinkSlot = o.thinkModel !== false ? THINK_GUIDANCE : THINK_DISABLED_GUIDANCE;
6189
- const workerToolNames = (o.actOptions?.tools ?? []).map((t) => t.name);
6190
- const canSearch = workerToolNames.some((n) => /WebSearch/i.test(n));
6191
- const canFetch = workerToolNames.some((n) => /WebFetch/i.test(n));
6192
- const workerWeb = canSearch ? `, and it CAN search the web and read web pages \u2014 so when the user gives you something specific to look up ("search for X", "find me\u2026", "what's the latest on\u2026"), route it to Act. But a bare capability QUESTION like "can you search the web?" just gets a short spoken "yes, I can" \u2014 do NOT dispatch and NEVER invent a query the user did not give you` : canFetch ? ", and it can fetch a specific web page URL (but cannot search the web)" : "";
6193
- const mcpNames = [
6194
- ...Object.keys(o.actOptions?.providerOptions?.mcpServers ?? {}),
6195
- ...new Set(workerToolNames.filter((n) => n.startsWith("mcp__")).map((n) => n.slice(5).split("__")[0]))
6196
- ];
6197
- const workerMcp = mcpNames.length ? `, and it can use these MCP servers: ${[...new Set(mcpNames)].join(", ")}` + (mcpNames.some((n) => /browser/i.test(n)) ? ' \u2014 including driving a REAL browser (open tabs, navigate, click, screenshot), so answer "yes" if asked whether you can control/drive a browser and route an actual browse to Act' : "") : "";
6198
- const prompt = VOICE_SYSTEM_PROMPT.replace("{{MEMORY_SLOT}}", memSlot).replace("{{THINK_SLOT}}", thinkSlot).replace("{{WORKER_WEB}}", workerWeb + workerMcp) + (o.voiceStyle === "conversational" ? "\n" + VOICE_STYLE_CONVERSATIONAL : "") + (o.emotionTags ? "\n" + EMOTION_TAGS_GUIDANCE : "") + `
6199
- ${nowLine()}. Anchor every relative or time-sensitive reference \u2014 "today", "now", "current", "recent", "latest", "this year" \u2014 to THIS moment. When the user asks about something recent (news, sports, events), they mean near this date, not a well-known past instance; brief your worker with the current year so it searches for what is happening NOW, not a famous older event.`;
6200
- const tools = [
6201
- ...o.reflexOptions?.tools ?? [],
6202
- this.actTool(),
6203
- ...o.thinkModel !== false ? [this.thinkTool()] : [],
6204
- this.taskStatusTool(),
6205
- this.cancelTaskTool(),
6206
- this.quickLookTool(),
6207
- this.answerTaskTool(),
6208
- this.holdTool()
6209
- ];
6210
- const host = o.host;
6211
- const voiceHost = host && {
6212
- ask: host.ask ? (q) => host.ask(q) : void 0,
6213
- confirm: host.confirm ? (p, m) => host.confirm(p, m) : void 0,
6214
- notify: (ev) => {
6215
- if (ev?.kind === "text_delta" && typeof ev.message === "string") {
6216
- if (this.heldThisTurn) return;
6217
- if (this.fabricationCut) return;
6218
- if (this.turnDispatched && this.spokeBeforeDispatch) return;
6219
- const msg = ev.message;
6220
- this.reflexBuf += msg;
6221
- this.scrubStageDirections();
6222
- const m = this.reflexBuf.match(RESERVED_EVENT_MARKER) ?? this.reflexBuf.match(RESERVED_EVENT_OPENER);
6223
- if (m) {
6224
- this.fabricationCut = true;
6225
- log11.warn(`reflex fabricated a [task \u2026] event in its spoken stream \u2014 cutting it (kept ${m.index} chars)`);
6226
- const safe = this.reflexBuf.slice(this.reflexForwarded, m.index);
6227
- if (!safe) return;
6228
- if (safe.trim()) this.spokeThisTurn = true;
6229
- this.emitHost({ ...ev, message: safe });
6230
- return;
6231
- }
6232
- const held = this.reflexBuf.length - this.reflexForwarded;
6233
- const partial = held > 0 && /\[\s*t?a?s?k?$/i.test(this.reflexBuf.slice(-Math.min(held, 6)));
6234
- let upto = partial ? this.reflexBuf.length - this.reflexBuf.slice(-6).match(/\[\s*t?a?s?k?$/i)[0].length : this.reflexBuf.length;
6235
- const paren = this.reflexBuf.lastIndexOf("(");
6236
- if (paren >= this.reflexForwarded && !this.reflexBuf.includes(")", paren) && this.reflexBuf.length - paren <= 80)
6237
- upto = Math.min(upto, paren);
6238
- const out = this.reflexBuf.slice(this.reflexForwarded, upto);
6239
- this.reflexForwarded = upto;
6240
- if (!out) return;
6241
- if (out.trim()) this.spokeThisTurn = true;
6242
- this.emitHost({ ...ev, message: out });
6243
- return;
6244
- }
6245
- host.notify?.(ev);
6246
- }
6247
- };
6248
- this.voice = new Agent({
6249
- ai: o.ai,
6250
- fs: new MemFilesystem2(),
6251
- model: o.reflexModel,
6252
- stream: true,
6253
- host: voiceHost,
6254
- // The reflex IS the conversational channel — it confirms ambiguity inline ("did you mean…?"),
6255
- // never via the blocking AskUserQuestion tool (Agent auto-adds it whenever a host is set). Left in,
6256
- // it stalls a voice turn until the kill-switch. Worker questions still reach the user via parkQuestion.
6257
- askUserQuestion: false,
6258
- systemPrompt: prompt,
6259
- instructionFiles: false,
6260
- maxSteps: 8,
6261
- timeoutMs: 3e4,
6262
- ...o.reflexOptions,
6263
- tools,
6264
- // Composed AFTER the spread so the dispatch guard can't be dropped by reflexOptions.
6265
- hooks: composeHooks(this.dispatchGuard(), o.reflexOptions?.hooks)
6266
- });
6267
- }
6268
- /** Resolve memory tools + inject index into voice system prompt (once). */
6269
- async initMemory() {
6270
- if (!this.memoryReady) return;
6271
- const mem = await this.memoryReady;
6272
- this.memoryReady = void 0;
6273
- this.voice.options.tools.push(...mem.tools);
6274
- if (mem.index) this.voice.options.systemPrompt += "\n\n" + mem.index;
6275
6160
  }
6276
- /** Flush any held-back trailing fragment (a possible `[task` opener that never completed) once the
6277
- * turn's stream is done — so a legit message ending in "[t" isn't silently dropped. */
6278
- flushHeldReflexTail() {
6279
- if (this.fabricationCut) return;
6280
- this.scrubStageDirections();
6281
- const tail = this.reflexBuf.slice(this.reflexForwarded);
6282
- this.reflexForwarded = this.reflexBuf.length;
6283
- if (!tail) return;
6284
- if (tail.trim()) this.spokeThisTurn = true;
6285
- this.emitHost({ kind: "text_delta", message: tail });
6161
+ lastChunkAt = 0;
6162
+ // timestamp of the most recent mic chunk (0 = none yet)
6163
+ startedChunksAt = 0;
6164
+ // when capture started (grace before the first chunk)
6165
+ noAudioTimer = null;
6166
+ finalText = "";
6167
+ partialText = "";
6168
+ lastChangeAt = 0;
6169
+ lastCombined = "";
6170
+ endpointTimer = null;
6171
+ firstTokenAt = 0;
6172
+ // first speech token in current utterance
6173
+ constructor(options) {
6174
+ this.options = { ...new SonioxSTTOptions(), ...options };
6286
6175
  }
6287
- /** Remove complete stage-direction parentheticals from the UNFORWARDED reflex text (STAGE_DIRECTION_RE).
6288
- * Only the unforwarded region is touched — already-spoken audio can't be unsent, and splicing before
6289
- * reflexForwarded would corrupt the forward offset. */
6290
- scrubStageDirections() {
6291
- if (this.reflexForwarded >= this.reflexBuf.length) return;
6292
- const region = this.reflexBuf.slice(this.reflexForwarded);
6293
- const scrubbed = region.replace(/\([^()]*\)/g, (s) => STAGE_DIRECTION_RE.test(s) ? "" : s);
6294
- if (scrubbed !== region) this.reflexBuf = this.reflexBuf.slice(0, this.reflexForwarded) + scrubbed;
6176
+ get usingAec() {
6177
+ return this.options.source?.aec ?? false;
6295
6178
  }
6296
- /** Clear the per-turn guards. Called at the head of every voice turn (user send + re-voice flush). */
6297
- resetTurn() {
6298
- this.turnDispatched = false;
6299
- this.spokeBeforeDispatch = false;
6300
- this.turnBriefs.clear();
6301
- this.spokeThisTurn = false;
6302
- this.externalSpeech = false;
6303
- this.heldThisTurn = false;
6304
- this.reflexBuf = "";
6305
- this.reflexForwarded = 0;
6306
- this.fabricationCut = false;
6307
- this.turnFollowUp = false;
6308
- this.voice.options.toolChoice = void 0;
6179
+ async connectWs() {
6180
+ const apiKey = await resolveAuth(this.options.auth);
6181
+ this.ws = new WebSocket("wss://stt-rt.soniox.com/transcribe-websocket");
6182
+ await new Promise((res, rej) => {
6183
+ this.ws.onopen = () => res();
6184
+ this.ws.onerror = (e) => rej(new Error(`soniox ws: ${e.message || "connect failed"}`));
6185
+ });
6186
+ this.ws.send(
6187
+ JSON.stringify({
6188
+ api_key: apiKey,
6189
+ model: this.options.model,
6190
+ audio_format: "pcm_s16le",
6191
+ sample_rate: STT_SAMPLE_RATE,
6192
+ num_channels: 1,
6193
+ language_hints: this.options.languageHints,
6194
+ enable_endpoint_detection: true
6195
+ })
6196
+ );
6197
+ this.ws.onmessage = (ev) => this.handle(JSON.parse(String(ev.data)));
6198
+ this.ws.onclose = (ev) => {
6199
+ if (this.stopped) return;
6200
+ log11.warn(`soniox ws closed (${ev.code} ${ev.reason || ""}) \u2014 reconnecting`);
6201
+ this.diag("stt_ws_closed", { code: ev.code, reason: String(ev.reason || ""), reconnecting: true });
6202
+ this.reset();
6203
+ this.connectWs().catch((e) => {
6204
+ log11.error(`soniox reconnect failed: ${e.message}`);
6205
+ this.diag("stt_reconnect_failed", { message: e.message });
6206
+ });
6207
+ };
6309
6208
  }
6310
- /** preToolUse guard on the reflex: once it has dispatched this turn, a dispatch is "said my piece,
6311
- * now wait for the push" (CC's Task model). Block the temptations — TaskStatus polling and identical
6312
- * re-dispatch — so the only remaining move is to voice a short ack and end. A genuinely NEW Act is
6313
- * still allowed (parallel independent work). During a re-ack pass, block every tool. */
6314
- dispatchGuard() {
6315
- return {
6316
- preToolUse: (call) => {
6317
- if (this.spec?.state === "pending" && !_DuplexAgent.SPEC_SAFE_TOOLS.has(call.name)) {
6318
- log11.verbose(`speculation aborted: reflex called ${call.name} on unconfirmed input`);
6319
- this.abortSpeculation();
6320
- return { block: true, reason: "Speculative turn aborted." };
6209
+ async start() {
6210
+ await this.connectWs();
6211
+ if (this.sourceStarted) return;
6212
+ this.sourceStarted = true;
6213
+ this.endpointTimer = setInterval(() => {
6214
+ const combined = (this.finalText + this.partialText).trim();
6215
+ if (!combined || now() - this.lastChangeAt < this.options.silenceEndpointMs) return;
6216
+ if (this.firstTokenAt) log11.debug(`stt: ${Math.round(now() - this.firstTokenAt)}ms first-token\u2192silence-endpoint, "${combined.slice(0, 60)}"`);
6217
+ this.reset();
6218
+ this.onUtterance(combined, now());
6219
+ }, 120);
6220
+ this.endpointTimer.unref?.();
6221
+ this.startedChunksAt = now();
6222
+ const noAudioMs = this.options.noAudioTimeoutMs;
6223
+ if (noAudioMs > 0) {
6224
+ this.noAudioTimer = setInterval(() => {
6225
+ if (this.stopped) return;
6226
+ const ref = this.lastChunkAt || this.startedChunksAt;
6227
+ if (now() - ref > noAudioMs) {
6228
+ log11.error(`stt: no mic audio for >${Math.round(noAudioMs / 1e3)}s \u2014 capture device stopped delivering`);
6229
+ this.diag("stt_watchdog_fatal", { noAudioMs });
6230
+ this.onFatal("microphone stopped delivering audio (try a different input device, e.g. AirPods, or check System Settings \u2192 Sound \u2192 Input)");
6231
+ this.stop();
6321
6232
  }
6322
- if (this.nudging) return { block: true, reason: "Just say one short spoken acknowledgement \u2014 no tools this turn." };
6323
- if (!this.turnDispatched) return;
6324
- if (call.name === "TaskStatus")
6325
- return { block: true, reason: "You just dispatched a task this turn \u2014 do NOT poll. Give one short spoken acknowledgement and end your turn; the result arrives later as a [task \u2026] event." };
6326
- if ((call.name === "Act" || call.name === "Think") && this.turnBriefs.has(String(call.args?.brief ?? "")))
6327
- return { block: true, reason: "You already dispatched this exact task \u2014 acknowledge briefly and end your turn." };
6233
+ }, Math.max(250, Math.min(2e3, noAudioMs / 4)));
6234
+ this.noAudioTimer.unref?.();
6235
+ }
6236
+ await this.options.source.start((chunk) => {
6237
+ this.lastChunkAt = now();
6238
+ let sum = 0;
6239
+ const view = new DataView(chunk.buffer, chunk.byteOffset, chunk.byteLength);
6240
+ for (let i = 0; i + 1 < chunk.byteLength; i += 2) {
6241
+ const v = view.getInt16(i, true);
6242
+ sum += v * v;
6328
6243
  }
6329
- };
6330
- }
6331
- /** The host spoke on this turn's behalf OUTSIDE the reflex stream (e.g. the voice engine's adaptive
6332
- * micro-ack). For a DISPATCHED turn that's a sufficient ack (don't stack a second one); for an
6333
- * inline turn whose reply came back empty it is NOT — "One sec." followed by permanent silence is
6334
- * still dead air, so silentTurn ignores external speech unless work was dispatched. */
6335
- noteExternalSpeech() {
6336
- this.externalSpeech = true;
6337
- }
6338
- /** True when the just-finished turn voiced NOTHING — dead air to repair. Two ways this happens:
6339
- * (a) a dispatch with no spoken ack, and (b) an INLINE turn whose `final` channel came back empty —
6340
- * gpt-oss harmony sometimes puts the whole reply in `analysis` (→ thinking_delta, suppressed in
6341
- * voice) and emits an empty `final`, so no text_delta ever streams. Both ship silence; both repair.
6342
- * Requires a host: without one there's no stream to detect speech on (and no one to speak to). */
6343
- get silentTurn() {
6344
- const ackedByHost = this.externalSpeech && this.turnDispatched;
6345
- return !!this.options.host && !this.spokeThisTurn && !ackedByHost && !this.heldThisTurn;
6244
+ this.onLevel(Math.sqrt(sum / (chunk.byteLength / 2)));
6245
+ if (this.ws.readyState === WebSocket.OPEN) this.ws.send(chunk);
6246
+ });
6346
6247
  }
6347
- /** A turn that voiced nothing is dead air. Re-prompt the reflex ONCE so the LLM itself voices a short
6348
- * line (no template). If it STILL says nothing, fall back to a minimal line so silence never ships.
6349
- * Wording adapts to whether work was dispatched (an ack) or the inline reply was simply lost. */
6350
- async ackIfSilent(fallback) {
6351
- const dispatched = this.turnDispatched;
6352
- this.nudging = true;
6353
- try {
6354
- await this.voice.send(fallback ? "[reminder] You said nothing to the user this turn. Tell them, in ONE short spoken sentence, what just happened \u2014 no tools." : dispatched ? "[reminder] You dispatched a task but said nothing to the user. Say ONE short spoken acknowledgement now \u2014 no tools." : "[reminder] You said nothing to the user this turn. Give your ONE short spoken reply now \u2014 no tools.");
6355
- } catch (e) {
6356
- log11.warn(`ack nudge failed: ${e instanceof Error ? e.message : e}`);
6357
- } finally {
6358
- this.nudging = false;
6248
+ handle(m) {
6249
+ if (m.error_message) {
6250
+ this.diag("stt_error", { message: String(m.error_message), code: m.error_code });
6251
+ return log11.error(`soniox: ${m.error_message}`);
6359
6252
  }
6360
- if (!this.spokeThisTurn) {
6361
- const pool = fallback ? [fallback] : dispatched ? _DuplexAgent.FALLBACK_ACKS : _DuplexAgent.FALLBACK_RETRY;
6362
- const fresh = pool.filter((p) => p !== this.lastFallback);
6363
- const line = (fresh.length ? fresh : pool)[Math.floor(Math.random() * (fresh.length || pool.length))];
6364
- this.lastFallback = line;
6365
- this.emitHost({ kind: "text_delta", message: line });
6253
+ let endpoint = false;
6254
+ for (const t of m.tokens ?? []) {
6255
+ if (t.text === "<end>") endpoint = true;
6256
+ else if (t.is_final) this.finalText += t.text;
6366
6257
  }
6367
- }
6368
- /** Dead-air fallback pools (see ackIfSilent). Both retry lines keep the 'say that again' phrase —
6369
- * hosts/tests key on it. */
6370
- static FALLBACK_ACKS = ["Okay, on it.", "On it.", "Alright, working on it."];
6371
- static FALLBACK_RETRY = ["Sorry, could you say that again?", "Hm, I missed that \u2014 could you say that again?"];
6372
- lastFallback = "";
6373
- /** One user turn: the voice agent streams the reply (and may Act/Think). Serialized with re-voice turns.
6374
- * If a speculative reflex call is pending and this content CONFIRMS it (the final matches the
6375
- * speculated partial), the in-flight call is adopted as THE turn: its buffered output flushes to the
6376
- * host NOW (this is the latency win) and streaming continues live. Any other content aborts the
6377
- * speculation first (rolled back silently) and runs a normal turn behind it. */
6378
- send(content) {
6379
- if (typeof content === "string" && isTrivialBarge(content) && this.hasParkedDelivery()) {
6380
- if (this.spec) this.abortSpeculation();
6381
- return this.enqueue(async () => {
6382
- this.resetTurn();
6383
- if (!this.redeliverParked()) this.awaitTrivialRedeliver = true;
6384
- return { text: "", steps: 0, finishReason: "stop", messages: [] };
6385
- });
6258
+ this.partialText = (m.tokens ?? []).filter((t) => !t.is_final && t.text !== "<end>").map((t) => t.text).join("");
6259
+ const combined = this.finalText + this.partialText;
6260
+ if (combined !== this.lastCombined) {
6261
+ this.lastCombined = combined;
6262
+ this.lastChangeAt = now();
6263
+ if (!this.firstTokenAt && combined.trim()) this.firstTokenAt = now();
6386
6264
  }
6387
- const spec = this.spec;
6388
- if (spec?.state === "pending") {
6389
- if (typeof content === "string" && speculationConfirms(spec.text, content)) {
6390
- spec.state = "confirmed";
6391
- spec.finalText = content;
6392
- for (const ev of spec.buf.splice(0)) this.options.host?.notify?.(ev);
6393
- spec.decide("confirm");
6394
- this.notify("diag", "speculation_confirmed", { text: spec.text.slice(0, 80) });
6395
- return spec.done;
6396
- }
6397
- this.abortSpeculation();
6265
+ this.onPartial(combined);
6266
+ if (endpoint && this.finalText.trim()) {
6267
+ const utterance = this.finalText.trim();
6268
+ if (this.firstTokenAt) log11.debug(`stt: ${Math.round(now() - this.firstTokenAt)}ms first-token\u2192endpoint, "${utterance.slice(0, 60)}"`);
6269
+ this.reset();
6270
+ this.onUtterance(utterance, now());
6398
6271
  }
6399
- return this.enqueue(async () => {
6400
- await this.initMemory();
6401
- this.resetTurn();
6402
- this.awaitTrivialRedeliver = false;
6403
- this.parkedRedeliver = [];
6404
- this.suppressParkedResume = true;
6405
- const res = await this.voice.send(content);
6406
- this.flushHeldReflexTail();
6407
- if (this.silentTurn) await this.ackIfSilent();
6408
- return res;
6409
- });
6410
6272
  }
6411
- /** Start a HELD speculative reflex turn on a stable partial (VoiceEngine.onSpeculate). Its spoken
6412
- * output buffers in emitHost; send() later confirms (flush + adopt) or aborts it. The turn holds the
6413
- * voice mutex until that decision (bounded by a safety timeout), so no other turn can interleave
6414
- * into the transcript between the speculative messages and their rollback. No-op if a speculation
6415
- * is already in flight. */
6416
- speculate(text) {
6417
- if (!text.trim() || this.spec) return;
6418
- let decide;
6419
- const decision = new Promise((r) => {
6420
- decide = r;
6273
+ reset() {
6274
+ this.finalText = "";
6275
+ this.partialText = "";
6276
+ this.lastCombined = "";
6277
+ this.firstTokenAt = 0;
6278
+ }
6279
+ stop() {
6280
+ this.stopped = true;
6281
+ if (this.endpointTimer) clearInterval(this.endpointTimer);
6282
+ if (this.noAudioTimer) clearInterval(this.noAudioTimer);
6283
+ this.options.source?.stop();
6284
+ if (this.ws) this.ws.onclose = null;
6285
+ this.ws?.close();
6286
+ }
6287
+ };
6288
+
6289
+ // node_modules/@bod.ee/voice/src/adapters/cartesia.ts
6290
+ var log12 = forComponent2("CartesiaTTS");
6291
+ var now2 = () => performance.now();
6292
+ var CartesiaTTSOptions = class {
6293
+ auth = "";
6294
+ voiceId = "";
6295
+ model = "sonic-3.5";
6296
+ /** 'apiKey' (server/CLI) → `api_key=` URL param; 'token' (browser, BE-minted) → `access_token=`. */
6297
+ authMode = "apiKey";
6298
+ };
6299
+ var CartesiaTTS = class _CartesiaTTS {
6300
+ options;
6301
+ ws;
6302
+ ctxSeq = 0;
6303
+ ctxId = "";
6304
+ onAudio = () => {
6305
+ };
6306
+ onDone = () => {
6307
+ };
6308
+ /** Word-level timestamps for karaoke reveal: `start[i]` = seconds from turn-audio start (absolute
6309
+ * across continuation chunks). Fired only when a consumer opts into reveal (see `wantTimestamps`). */
6310
+ onTimestamps = () => {
6311
+ };
6312
+ /** Request `add_timestamps` from Cartesia. Off by default (saves bandwidth) — the engine sets it
6313
+ * when revealMode==='word'. */
6314
+ wantTimestamps = false;
6315
+ /** Diagnostic tap (provider errors, circuit-breaker open/close, ws reconnects). Fire-and-forget:
6316
+ * a throwing handler disables itself — never affects synthesis. Wired by VoiceIO / the lab bridge. */
6317
+ onDiag = () => {
6318
+ };
6319
+ diagOn = true;
6320
+ diag(kind, fields) {
6321
+ if (!this.diagOn) return;
6322
+ try {
6323
+ this.onDiag({ t: now2(), kind, ...fields });
6324
+ } catch (e) {
6325
+ this.diagOn = false;
6326
+ log12.debug(`onDiag threw \u2014 TTS diagnostics disabled: ${e instanceof Error ? e.message : e}`);
6327
+ }
6328
+ }
6329
+ firstAudioAt = 0;
6330
+ /** Circuit breaker: consecutive error count + down flag. */
6331
+ consecutiveErrors = 0;
6332
+ consecutiveOk = 0;
6333
+ down = false;
6334
+ downAt = 0;
6335
+ probeTimer = null;
6336
+ static CB_THRESHOLD = 3;
6337
+ // open after 3 consecutive errors
6338
+ static CB_RECOVER_OK = 2;
6339
+ // close only after 2 consecutive good frames (no single-frame flap)
6340
+ static CB_PROBE_MS = 3e4;
6341
+ constructor(options) {
6342
+ this.options = { ...new CartesiaTTSOptions(), ...options };
6343
+ }
6344
+ closed = false;
6345
+ connecting = null;
6346
+ async connect() {
6347
+ this.closed = false;
6348
+ this.connecting = this.doConnect();
6349
+ await this.connecting;
6350
+ this.connecting = null;
6351
+ }
6352
+ async doConnect() {
6353
+ const key = await resolveAuth(this.options.auth);
6354
+ const param = this.options.authMode === "token" ? "access_token" : "api_key";
6355
+ this.ws = new WebSocket(`wss://api.cartesia.ai/tts/websocket?cartesia_version=2026-03-01&${param}=${key}`);
6356
+ await new Promise((res, rej) => {
6357
+ this.ws.onopen = () => res();
6358
+ this.ws.onerror = (e) => rej(new Error(`cartesia ws: ${e.message || "connect failed"}`));
6421
6359
  });
6422
- const spec = {
6423
- text,
6424
- state: "pending",
6425
- buf: [],
6426
- ctl: new AbortController(),
6427
- decide,
6428
- decision,
6429
- done: void 0
6430
- };
6431
- this.spec = spec;
6432
- spec.done = this.enqueue(async () => {
6433
- const empty = { text: "", steps: 0, finishReason: "aborted", messages: this.voice.transcript };
6434
- if (spec.state === "aborted") {
6435
- this.speculativeAbortedCalls++;
6436
- if (this.spec === spec) this.spec = void 0;
6437
- return empty;
6438
- }
6439
- await this.initMemory();
6440
- this.resetTurn();
6441
- const base = this.voice.transcript.length;
6442
- const prevSignal = this.voice.options.signal;
6443
- this.voice.options.signal = spec.ctl.signal;
6444
- let res;
6445
- try {
6446
- res = await this.voice.send(spec.text);
6447
- } catch (e) {
6448
- log11.warn(`speculative turn failed: ${e instanceof Error ? e.message : e}`);
6449
- } finally {
6450
- this.voice.options.signal = prevSignal;
6451
- }
6452
- const timer = setTimeout(() => {
6453
- spec.state = spec.state === "pending" ? "aborted" : spec.state;
6454
- spec.decide("abort");
6455
- }, 1e4);
6456
- timer.unref?.();
6457
- const d = await spec.decision;
6458
- clearTimeout(timer);
6459
- if (d === "abort") {
6460
- if (this.voice.transcript.length > base) this.voice.transcript.length = base;
6461
- this.speculativeAbortedCalls++;
6462
- log11.verbose(`speculation aborted (${this.speculativeAbortedCalls} total): "${spec.text.slice(0, 50)}"`);
6463
- if (this.spec === spec) this.spec = void 0;
6464
- return res ?? empty;
6360
+ this.ws.onclose = (ev) => {
6361
+ log12.warn(`cartesia ws closed (${ev.code} ${ev.reason || ""})`);
6362
+ this.diag("tts_ws_closed", { code: ev.code, reason: String(ev.reason || ""), reconnecting: !this.closed });
6363
+ if (!this.closed) {
6364
+ this.connecting = this.doConnect().catch((e) => {
6365
+ log12.error(`cartesia reconnect failed: ${e.message}`);
6366
+ this.diag("tts_reconnect_failed", { message: e.message });
6367
+ });
6465
6368
  }
6466
- for (let i = base; i < this.voice.transcript.length; i++) {
6467
- const m = this.voice.transcript[i];
6468
- if (m.role === "user" && contentText(m.content) === spec.text) {
6469
- m.content = spec.finalText;
6470
- break;
6369
+ };
6370
+ this.ws.onmessage = (ev) => {
6371
+ const m = JSON.parse(String(ev.data));
6372
+ if (m.context_id && m.context_id !== this.ctxId) return;
6373
+ if (m.type === "chunk" && m.data) {
6374
+ this.consecutiveErrors = 0;
6375
+ this.markRecovered();
6376
+ if (!this.firstAudioAt) this.firstAudioAt = now2();
6377
+ this.onAudio(base64ToBytes(m.data));
6378
+ } else if (m.type === "done") {
6379
+ this.consecutiveErrors = 0;
6380
+ this.markRecovered();
6381
+ this.onDone();
6382
+ } else if (m.type === "timestamps" && m.word_timestamps) {
6383
+ const wt = m.word_timestamps;
6384
+ if (wt.words?.length && wt.start?.length) this.onTimestamps(wt.words, wt.start);
6385
+ } else if (m.type === "error") {
6386
+ if (/already been cancelled|does not exist/.test(m.message || "")) return;
6387
+ this.consecutiveErrors++;
6388
+ this.diag("tts_error", { message: String(m.message || ""), code: m.status_code, contextId: m.context_id, consecutive: this.consecutiveErrors });
6389
+ if (!this.down && this.consecutiveErrors >= _CartesiaTTS.CB_THRESHOLD) {
6390
+ this.down = true;
6391
+ this.downAt = now2();
6392
+ this.consecutiveOk = 0;
6393
+ log12.warn(`TTS circuit breaker open \u2014 ${this.consecutiveErrors} consecutive errors, switching to text-only`);
6394
+ this.diag("tts_breaker_open", { errors: this.consecutiveErrors });
6395
+ this.onDone();
6396
+ this.startProbe();
6397
+ } else if (!this.down) {
6398
+ (/No valid transcripts/i.test(m.message || "") ? log12.debug : log12.warn)(`cartesia: ${JSON.stringify(m)}`);
6471
6399
  }
6472
6400
  }
6473
- this.spec = void 0;
6474
- this.flushHeldReflexTail();
6475
- if (this.silentTurn) await this.ackIfSilent();
6476
- return res ?? empty;
6477
- });
6401
+ };
6478
6402
  }
6479
- /** Abort a pending speculation (idempotent): kill the in-flight call, drop its buffered output.
6480
- * Called on divergence (send), a stale partial (VoiceEngine.onSpeculateAbort), a side-effect tool
6481
- * attempt (dispatchGuard), or host paths that will never dispatch a final (commands, voice-off). */
6482
- abortSpeculation() {
6483
- const spec = this.spec;
6484
- if (spec?.state !== "pending") return;
6485
- spec.state = "aborted";
6486
- spec.buf.length = 0;
6487
- spec.ctl.abort();
6488
- spec.decide("abort");
6489
- this.notify("diag", "speculation_aborted", { text: spec.text.slice(0, 80) });
6403
+ /** Close the breaker only after CB_RECOVER_OK consecutive good frames, so a single straggler chunk
6404
+ * after a 503 burst doesn't flap open→recover in <1s. A sub-2s down-window is a transient blip → debug. */
6405
+ markRecovered() {
6406
+ if (!this.down) return;
6407
+ if (++this.consecutiveOk < _CartesiaTTS.CB_RECOVER_OK) return;
6408
+ this.down = false;
6409
+ this.consecutiveOk = 0;
6410
+ this.stopProbe();
6411
+ const downMs = this.downAt ? now2() - this.downAt : 0;
6412
+ this.diag("tts_breaker_close", { downMs: Math.round(downMs) });
6413
+ (downMs < 2e3 ? log12.debug : log12.info)(`TTS recovered${downMs ? ` (down ${downMs}ms)` : ""}`);
6490
6414
  }
6491
- /** Cancel a running background task — shared by the CancelTask tool and the CLI /tasks picker. */
6492
- cancelTask(id) {
6493
- const rec = this.tasks.get(id);
6494
- if (!rec) return `No task '${id}'.`;
6495
- if (rec.status !== "running") return `Task ${rec.id} is already ${rec.status}.`;
6496
- rec.status = "cancelled";
6497
- rec.controller.abort();
6498
- return `Task ${rec.id} (${rec.label}) cancelled.`;
6415
+ /** Ensure the WS is open before sending — reconnects if idle-closed. */
6416
+ async ensureConnected() {
6417
+ if (this.connecting) await this.connecting;
6418
+ if (this.ws?.readyState !== WebSocket.OPEN) await this.connect();
6499
6419
  }
6500
- /** Barge-in: the user took the floor while task(s) were running. Suppress those tasks' remaining SPOKEN
6501
- * delivery so a superseded topic never talks over the new one (the debt-after-jokes regression). The
6502
- * tasks keep running and still fold their result into the transcript — recoverable, just not spoken.
6503
- * Returns the parked ids (for logging). Does NOT cancel: that's a deliberate reflex/user action. */
6504
- parkInFlightDeliveries() {
6505
- this.suppressParkedResume = false;
6506
- const parked = [];
6507
- for (const rec of this.tasks.values())
6508
- if (rec.status === "running" && !rec.deliveryParked) {
6509
- rec.deliveryParked = true;
6510
- parked.push(rec.id);
6511
- }
6512
- return parked;
6420
+ /** Prime the synthesis pipeline on a throwaway context right after connect: the FIRST synthesis on
6421
+ * a fresh WS pays Cartesia's cold spin-up (~1s+ live) — absorb it at mic-on instead of turn one.
6422
+ * The returned audio is discarded (engine drops onAudio while not speaking; once a real turn calls
6423
+ * newContext() any stragglers are stale-context-filtered). Respects the circuit breaker. */
6424
+ warmup() {
6425
+ if (this.down) return;
6426
+ this.newContext();
6427
+ if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(this.frame("Ok.", false));
6513
6428
  }
6514
- /** True while there is a parked delivery to potentially resume: either one already settled (queued) or
6515
- * one still running that was parked by a barge. */
6516
- hasParkedDelivery() {
6517
- return this.parkedRedeliver.length > 0 || [...this.tasks.values()].some((t) => t.status === "running" && t.deliveryParked);
6429
+ newContext() {
6430
+ this.ctxId = `ctx-${++this.ctxSeq}`;
6431
+ this.firstAudioAt = 0;
6432
+ return this.ctxId;
6518
6433
  }
6519
- /** Speak any settled-and-queued parked delivery now (trivial-barge resume). Returns false if nothing was
6520
- * queued yet (the caller then arms awaitTrivialRedeliver so the task resumes the instant it settles). */
6521
- redeliverParked() {
6522
- if (!this.parkedRedeliver.length) return false;
6523
- const text = this.parkedRedeliver.splice(0).join(" ").trim();
6524
- if (text) {
6525
- this.options.host?.notify?.({ kind: "speak_utterance", message: text });
6526
- this.notify("diag", "parked_redelivered", { chars: text.length });
6527
- }
6528
- return true;
6434
+ frame(transcript, cont) {
6435
+ return JSON.stringify({
6436
+ model_id: this.options.model,
6437
+ transcript,
6438
+ voice: { mode: "id", id: this.options.voiceId },
6439
+ output_format: { container: "raw", encoding: "pcm_s16le", sample_rate: TTS_SAMPLE_RATE },
6440
+ context_id: this.ctxId,
6441
+ continue: cont,
6442
+ ...this.wantTimestamps ? { add_timestamps: true } : {}
6443
+ });
6529
6444
  }
6530
- /** Resolve when all queued voice turns AND all in-flight worker tasks have settled (tests, graceful shutdown). */
6531
- async idle() {
6532
- while (true) {
6533
- const q = this.queue;
6534
- await q.catch(() => {
6535
- });
6536
- await Promise.all([...this.tasks.values()].map((t) => t.promise));
6537
- if (this.queue === q && ![...this.tasks.values()].some((t) => t.status === "running")) return;
6538
- }
6445
+ speak(text, cont) {
6446
+ if (this.down) return;
6447
+ if (cont && !text) return;
6448
+ if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(this.frame(text, cont));
6449
+ else void this.ensureConnected().then(() => this.ws?.readyState === WebSocket.OPEN && this.ws.send(this.frame(text, cont)));
6539
6450
  }
6540
- /** Promise-chain mutex: turns run strictly one at a time; a failed turn doesn't poison the chain. */
6541
- enqueue(fn) {
6542
- const run = this.queue.then(fn, fn);
6543
- this.queue = run.then(() => {
6544
- }, () => {
6545
- });
6546
- return run;
6451
+ end() {
6452
+ if (this.down) {
6453
+ this.onDone();
6454
+ return;
6455
+ }
6456
+ if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(this.frame("", false));
6547
6457
  }
6548
- notify(kind, message, data) {
6549
- this.emitHost({ kind, message, data });
6458
+ cancel() {
6459
+ if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(JSON.stringify({ context_id: this.ctxId, cancel: true }));
6550
6460
  }
6551
- /** Host-boundary emit for the reflex's spoken channel: during a PENDING speculation, text_delta and
6552
- * hold_filler are BUFFERED (nothing may reach TTS on unconfirmed input); confirm flushes them in
6553
- * order, abort drops them silently. Everything else (task_* lifecycle, worker speak_utterance —
6554
- * which bypasses this via host.notify directly) passes through untouched. */
6555
- emitHost(ev) {
6556
- const spec = this.spec;
6557
- if (spec && (ev.kind === "text_delta" || ev.kind === "hold_filler")) {
6558
- if (spec.state === "pending") {
6559
- spec.buf.push(ev);
6461
+ startProbe() {
6462
+ if (this.probeTimer) return;
6463
+ this.probeTimer = setInterval(() => {
6464
+ if (!this.down) {
6465
+ this.stopProbe();
6560
6466
  return;
6561
6467
  }
6562
- if (spec.state === "aborted") return;
6468
+ this.consecutiveErrors = 0;
6469
+ this.newContext();
6470
+ if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(this.frame("Ok.", false));
6471
+ }, _CartesiaTTS.CB_PROBE_MS);
6472
+ this.probeTimer.unref?.();
6473
+ }
6474
+ stopProbe() {
6475
+ if (this.probeTimer) {
6476
+ clearInterval(this.probeTimer);
6477
+ this.probeTimer = null;
6563
6478
  }
6564
- this.options.host?.notify?.(ev);
6565
6479
  }
6566
- /** Queue a `[task …]` event for re-voicing. Events arriving while the voice is busy coalesce into ONE turn.
6567
- * `nonClean` (out-of-band boolean, set by the caller that KNOWS this event integrates a NON-CLEAN outcome)
6568
- * marks the coalesced flush as a non-clean integration turn — turn-eligibility, never inferred from event
6569
- * text and never keyed on a (re-authored) brief string. Any dispatch in such a turn is a follow-up. */
6570
- queueRevoice(event, nonClean = false) {
6571
- this.pendingEvents.push(event);
6572
- if (nonClean) this.pendingNonClean = true;
6573
- if (this.flushQueued) return;
6574
- this.flushQueued = true;
6575
- void this.enqueue(async () => {
6576
- this.flushQueued = false;
6577
- const events = this.pendingEvents.splice(0);
6578
- const nonCleanTurn = this.pendingNonClean;
6579
- this.pendingNonClean = false;
6580
- if (!events.length) return;
6581
- const failed = events.find((e) => /^\[task\b[^\]\n]*\bfailed\b/i.test(e));
6582
- this.resetTurn();
6583
- this.turnFollowUp = nonCleanTurn;
6584
- await this.voice.send(events.join("\n"));
6585
- this.flushHeldReflexTail();
6586
- if (this.silentTurn) await this.ackIfSilent(failed ? "Sorry, that didn't work \u2014 the task failed." : void 0);
6587
- this.notify("revoice_done", "");
6588
- });
6480
+ close() {
6481
+ this.closed = true;
6482
+ this.stopProbe();
6483
+ if (this.ws) this.ws.onclose = null;
6484
+ this.ws?.close();
6589
6485
  }
6590
- /** The worker's brief: the Act/Think args + a STATIC text snapshot of the recent conversation.
6591
- * Act briefs get a self-verify footer — the worker's report is trusted without review, so it
6592
- * must check its own work before reporting (nearly free under prompt caching; measured honest:
6593
- * it does NOT fix one-shot logic bugs — see mind/10). Think tasks are pure reasoning — no footer. */
6594
- buildBrief(brief, tier = "act", deliver = true) {
6595
- const recent = this.voice.transcript.filter((m) => (m.role === "user" || m.role === "assistant") && contentText(m.content).trim()).slice(-this.options.excerptTurns).map((m) => `${m.role}: ${contentText(m.content)}`).join("\n");
6596
- const verify = tier === "act" ? "\n\nBefore reporting done: re-read what you changed and check it against EVERY requirement above \u2014 fix any gap first. Your report is trusted without review." : "";
6597
- const deliverContract = deliver ? `
6598
-
6599
- ## DELIVER (spoken delivery)
6600
- You are reporting back to a user who is LISTENING. Stream your work normally \u2014 your prose is the written work record and detail, and is NOT spoken. Wrap anything the user should HEAR in <spoken>\u2026</spoken> tags. LEAD WITH the actual content they asked for: if they asked for a specific piece of content \u2014 a value, a name, the actual lines, the writing itself \u2014 that content goes INSIDE the <spoken> tags, not a remark about it. Your FIRST <spoken> segment is substantive \u2014 never a greeting or an acknowledgement (the front-end has already acked; do not double-ack). Keep spoken text concise and natural for the ear: short sentences, no markdown. NEVER enumerate in speech \u2014 no numbered or bulleted lists ("One. \u2026 Two. \u2026" is robotic). Deliver multiple items as flowing conversation with brief connective phrasing ("here's one\u2026", "and another\u2026", "oh, and\u2026"), pausing between items with sentence breaks, not numbers.` + (this.options.emotionTags ? " Inside <spoken>, you may prefix a sentence with an inline [emotion] tag (e.g. [excited], [curious]) to color how it is voiced \u2014 only when it genuinely fits, and vary it; [laughter] gives a natural laugh." : "") : "";
6601
- return `${nowLine()}.
6602
-
6603
- ` + (recent ? `${brief}
6486
+ };
6487
+ function base64ToBytes(b64) {
6488
+ if (typeof Buffer !== "undefined") return Buffer.from(b64, "base64");
6489
+ const bin = atob(b64);
6490
+ const out = new Uint8Array(bin.length);
6491
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
6492
+ return out;
6493
+ }
6604
6494
 
6605
- ## Recent conversation (for context)
6606
- ${recent}` : brief) + verify + deliverContract;
6607
- }
6608
- /** Spawn a detached worker for task `id`; its settlement notifies + enqueues the re-voice turn. */
6609
- spawnWorker(id, label, briefText, tier, brief, followUp) {
6610
- const o = this.options;
6611
- const tierOpts = tier === "think" ? o.thinkOptions : o.actOptions;
6612
- const tierModel = tier === "think" ? o.thinkModel : o.actModel;
6613
- const controller = new AbortController();
6614
- const base = tierOpts?.hooks ?? o.actOptions?.hooks;
6615
- const report = o.progressUpdates ? this.progressReporter(id) : void 0;
6616
- const tail = [];
6617
- const pushTail = (line) => {
6618
- tail.push(line.slice(0, 200));
6619
- if (tail.length > 120) tail.splice(0, tail.length - 120);
6620
- };
6621
- const hooks = {
6622
- ...base,
6623
- preToolUse: async (call, meta) => {
6624
- const d = await base?.preToolUse?.(call, meta);
6625
- pushTail(`\u2699 ${describeCall(call)}`);
6626
- report?.pre(call);
6627
- return d;
6628
- },
6629
- postToolUse: async (call, result, meta) => {
6630
- await base?.postToolUse?.(call, result, meta);
6631
- const last = result?.trim().split("\n").filter(Boolean).pop();
6632
- if (last) pushTail(` \u21B3 ${last}`);
6633
- report?.post(call);
6634
- },
6635
- onToolOutput: (call, chunk, meta) => {
6636
- base?.onToolOutput?.(call, chunk, meta);
6637
- report?.output(chunk);
6638
- }
6639
- };
6640
- const relayAsk = async (q) => {
6641
- const opts = q.options?.length ? ` Options: ${q.options.map((x) => x.label).join(", ")}.` : "";
6642
- const a = await this.parkQuestion(id, `${q.question}${opts}`);
6643
- return a || "(no answer from the user \u2014 use your best judgment and note the assumption)";
6644
- };
6645
- const splitter = new SpokenSplitter();
6646
- const speak = (seg) => {
6647
- if (!seg) return;
6648
- const r = this.tasks.get(id);
6649
- if (r) r.spokenText = (r.spokenText ? r.spokenText + " " : "") + seg;
6650
- if (!r?.deliveryParked) o.host?.notify?.({ kind: "speak_utterance", message: seg });
6651
- };
6652
- const coalescer = new SentenceCoalescer();
6653
- const feedSpoken = (s) => {
6654
- const ready = coalescer.feed(s);
6655
- if (ready) speak(ready);
6656
- };
6657
- const flushSpoken = () => speak(coalescer.flush());
6658
- const askBridge = o.askRelay ? { ask: relayAsk } : o.host?.ask ? { ask: (q) => o.host.ask(q) } : {};
6659
- const workerHost = {
6660
- ...askBridge,
6661
- notify: (ev) => {
6662
- if (ev?.kind === "text_delta" && typeof ev.message === "string") {
6663
- const { spoken, detail } = splitter.feed(ev.message);
6664
- feedSpoken(spoken);
6665
- if (detail.trim()) pushTail(detail.trim());
6666
- return;
6667
- }
6668
- }
6669
- };
6670
- const agentOpts = {
6671
- ai: o.ai,
6672
- fs: o.fs,
6673
- model: tierModel,
6674
- ...tier === "think" ? { reasoning: tierOpts?.reasoning ?? "high" } : {},
6675
- ...tierOpts,
6676
- // Recompute providerOptions for THIS worker's model (after tierOpts so it wins over any inherited
6677
- // main-template value) — prevents cursor-only cwd/cursorSession leaking onto an anthropic worker.
6678
- providerOptions: o.providerOptionsFor?.(tierModel),
6679
- stream: true,
6680
- // worker streams text_delta so the splitter can extract <spoken> live (after tierOpts: never overridden off)
6681
- host: workerHost,
6682
- // carries BOTH ask AND the <spoken>-splitting notify
6683
- ...hooks ? { hooks } : {},
6684
- signal: controller.signal
6685
- // shared with the checker so a cancel tears down both
6686
- };
6687
- const promise = new Agent(agentOpts).run(briefText).then((res) => {
6688
- const { spoken, detail } = splitter.flush();
6689
- feedSpoken(spoken);
6690
- if (detail.trim()) pushTail(detail.trim());
6691
- flushSpoken();
6692
- return res;
6693
- }).then((res) => this.maybeVerify(id, brief, res, tier, agentOpts, askBridge)).then((res) => this.onWorkerSettled(id, res)).catch((err) => this.onWorkerFailed(id, err));
6694
- this.tasks.set(id, { id, label, status: "running", controller, promise, tail, brief, followUp, splitter });
6695
- if (this.tasks.size > this.options.maxTaskRecords)
6696
- for (const [tid, rec] of this.tasks) {
6697
- if (this.tasks.size <= this.options.maxTaskRecords) break;
6698
- if (rec.status !== "running") this.tasks.delete(tid);
6699
- }
6700
- }
6701
- /** Fresh-context check of a successful Act task: a NEW agent (same model/fs/tools, but NO shared
6702
- * conversation context) re-reads the file state against the brief and fixes any gap. The fix lands
6703
- * on the shared fs automatically (workers write fs directly, no overlay), so grading sees the
6704
- * corrected state. Bounded to ONE pass. Off unless `verifyActTasks`; never runs for think/failed/
6705
- * cancelled tasks. Usage is merged so /cost reflects the real (worker + checker) spend. */
6706
- async maybeVerify(id, brief, res, tier, agentOpts, askBridge) {
6707
- if (!this.options.verifyActTasks || tier !== "act" || res.finishReason !== "stop") return res;
6708
- if (this.tasks.get(id)?.status === "cancelled") return res;
6709
- const { stream: _stream, host: _host, ...restOpts } = agentOpts;
6710
- const checkerOpts = {
6711
- ...restOpts,
6712
- ...askBridge.ask ? { host: { ask: askBridge.ask } } : {}
6713
- };
6714
- const checkBrief = `${this.buildBrief(brief, tier, false)}
6495
+ // src/voice/engine.ts
6496
+ init_logging();
6497
+ configureLogging((name) => {
6498
+ const l = forComponent(name);
6499
+ const at = (m) => (...a) => l[m]?.(...a);
6500
+ return { debug: at("debug"), verbose: at("verbose"), info: at("info"), warn: at("warn"), error: at("error") };
6501
+ });
6715
6502
 
6716
- ## VERIFY MODE
6717
- Another agent just implemented the above. Independently check the CURRENT state of the files against EVERY requirement. Fix any gap you find. If everything is already correct, make NO changes \u2014 do not refactor or improve \u2014 and report "verified".`;
6718
- this.notify("task_verify", `task ${id}: verifying`, { id });
6719
- const cres = await new Agent(checkerOpts).run(checkBrief);
6720
- if (cres.finishReason !== "stop") {
6721
- log11.warn(`task ${id}: verify inconclusive (${cres.finishReason})`);
6722
- this.notify("task_verify", `task ${id}: verify inconclusive (${cres.finishReason})`, { id, finishReason: cres.finishReason });
6723
- }
6724
- const sum = (a = 0, b = 0) => a + b;
6725
- return {
6726
- ...res,
6727
- steps: res.steps + cres.steps,
6728
- // Merge the checker's messages so downstream tool-call/step accounting includes BOTH agents
6729
- // (else a verified task's toolCalls would undercount vs its steps/usage).
6730
- messages: [...res.messages, ...cres.messages],
6731
- usageEstimated: res.usageEstimated || cres.usageEstimated,
6732
- usage: res.usage && cres.usage ? {
6733
- promptTokens: sum(res.usage.promptTokens, cres.usage.promptTokens),
6734
- completionTokens: sum(res.usage.completionTokens, cres.usage.completionTokens),
6735
- totalTokens: sum(res.usage.totalTokens, cres.usage.totalTokens),
6736
- cacheCreationTokens: sum(res.usage.cacheCreationTokens, cres.usage.cacheCreationTokens),
6737
- cacheReadTokens: sum(res.usage.cacheReadTokens, cres.usage.cacheReadTokens)
6738
- } : res.usage ?? cres.usage
6739
- };
6740
- }
6741
- /** Throttled per-task progress: worker tool calls → at most one progress re-voice per interval.
6742
- * Two sources, one throttle: completed steps (post) and a heartbeat for a SINGLE long tool call
6743
- * (pre records the in-flight call; a self-cleaning timer narrates "still inside Bash — 70s").
6744
- * Completion supersedes: nothing is emitted once the task has settled. */
6745
- progressReporter(id) {
6746
- let lastAt = Date.now();
6747
- let steps = 0;
6748
- let inflight = null;
6749
- const due = () => {
6750
- if (this.pendingAsks.size) return void 0;
6751
- const rec = this.tasks.get(id);
6752
- return rec && rec.status === "running" && Date.now() - lastAt >= this.options.progressIntervalMs ? rec : void 0;
6753
- };
6754
- const emit = (rec, line, call) => {
6755
- lastAt = Date.now();
6756
- this.notify("task_progress", `task ${id} (${rec.label}): ${line}`, { id, steps, call: call.name });
6757
- this.queueRevoice(`[task ${id} progress] ${line}`);
6758
- };
6759
- const timer = setInterval(() => {
6760
- const rec = this.tasks.get(id);
6761
- if (!rec || rec.status !== "running") return clearInterval(timer);
6762
- if (!inflight || !due()) return;
6763
- const last = inflight.tail.trim().split("\n").filter(Boolean).pop()?.slice(-80);
6764
- emit(rec, `still inside ${describeCall(inflight.call)} \u2014 ${Math.round((Date.now() - inflight.at) / 1e3)}s on this step${last ? `, last output: ${last}` : ""}`, inflight.call);
6765
- }, Math.max(this.options.progressIntervalMs, 250));
6766
- timer.unref?.();
6767
- return {
6768
- pre: (call) => {
6769
- inflight = { call, at: Date.now(), tail: "" };
6770
- },
6771
- output: (chunk) => {
6772
- if (inflight) inflight.tail = (inflight.tail + chunk).slice(-500);
6773
- },
6774
- // digest only — NEVER re-voices directly
6775
- post: (call) => {
6776
- steps++;
6777
- inflight = null;
6778
- const rec = due();
6779
- if (rec) emit(rec, `still running \u2014 ${steps} steps so far, now: ${describeCall(call)}`, call);
6780
- }
6781
- };
6782
- }
6783
- /** Park a question under `askId` (a task id, or any unique key for permission asks): re-voices
6784
- * '[task <id> asks] …' and resolves with the user's answer via AnswerTask — or '' on timeout/
6785
- * task settle (callers map '' to deny / best-judgment). Workers never block forever. */
6786
- parkQuestion(askId, question) {
6787
- return new Promise((resolve) => {
6788
- let settled = false;
6789
- const finish = (answer) => {
6790
- if (settled) return;
6791
- settled = true;
6792
- clearTimeout(timer);
6793
- this.pendingAsks.delete(askId);
6794
- resolve(answer);
6795
- };
6796
- const timer = setTimeout(() => {
6797
- this.notify("task_ask_timeout", `task ${askId}: question timed out \u2014 proceeding without an answer`);
6798
- finish("");
6799
- }, this.options.askTimeoutMs);
6800
- this.pendingAsks.set(askId, { question, resolve: finish });
6801
- this.notify("task_ask", `task ${askId} asks: ${question}`, { id: askId, question });
6802
- this.queueRevoice(`[task ${askId} asks] ${question}
6803
- (Relay this to the user in your own words. When they answer, call AnswerTask with id "${askId}" and their answer.)`);
6804
- });
6805
- }
6806
- /** Resolve any question a settling/cancelled task left parked (its answer can no longer matter). */
6807
- dropAsk(id) {
6808
- this.pendingAsks.get(id)?.resolve("");
6809
- }
6810
- /** Build the INTEGRATION TURN prompt for a NON-CLEAN settled worker (early stop / failure). A clean
6811
- * success never reaches here — it streams its own `<spoken>` delivery during the run. For a partial
6812
- * or failed result the outcome re-enters the reflex as a decision (like a tool_result flowing back
6813
- * into a normal agent loop): the reflex evaluates the outcome against the original intent and chooses
6814
- * what to do next.
6815
- *
6816
- * Decision branches (the reflex acts on them with EXISTING tools — no new surface):
6817
- * • accept → SPEAK the (partial) result plainly — don't dress a failure up as success.
6818
- * • escalate → call `Think` with the SAME brief — only when Act failed/stalled AND a Think tier
6819
- * exists AND this task wasn't already a follow-up (one hop max). Wires the dead
6820
- * "Reserve Think for a problem Act already FAILED at" promise.
6821
- * • re-delegate→ call `Act` with a CORRECTED brief — for a recoverable error / partial result.
6822
- * • ask → ask the user ONE concrete question if genuinely blocked.
6823
- *
6824
- * Keeps the `[task <id> completed]` / `[task <id> failed]` opener so existing coalescing + the
6825
- * failed-revoice fallback still fire, and the per-event transcript markers stay intact. */
6826
- integrationPrompt(rec, outcome, body, finishReason) {
6827
- const opener = outcome === "error" ? `[task ${rec.id} failed]` : `[task ${rec.id} completed]`;
6828
- const underCap = this.autoEscalations < _DuplexAgent.MAX_AUTO_ESCALATIONS;
6829
- const canEscalate = (outcome === "error" || outcome === "incomplete") && underCap;
6830
- const hasThink = this.options.thinkModel !== false;
6831
- const options = [];
6832
- if (!rec.followUp && canEscalate && hasThink)
6833
- options.push("ESCALATE to the Think tier (call Think with the same brief) if this is a hard/architectural problem the Act worker stalled or failed on");
6834
- if (!rec.followUp && canEscalate)
6835
- options.push("RE-DELEGATE to Act with a corrected brief if the failure looks recoverable (a wrong path, a fixable mistake)");
6836
- options.push("ASK the user one short, concrete question if you genuinely cannot proceed without their input");
6837
- options.push("ACCEPT and tell the user plainly what happened (don't dress a failure up as success)");
6838
- const decision = options.length > 1 ? ` You must decide what to do next \u2014 choose ONE: ${options.map((o, i) => `(${i + 1}) ${o}`).join("; ")}. Pick exactly one and act on it; do not voice this as a finished success.` : ` Tell the user plainly what happened \u2014 do not present this as a finished success.`;
6839
- const state = outcome === "error" ? `the worker FAILED with: ${body}` : `the worker STOPPED EARLY (${finishReason}) \u2014 its result is PARTIAL, not a finished success: ${body}`;
6840
- return `${opener} Original request: "${rec.brief}". Outcome: ${state}.${decision}`;
6841
- }
6842
- onWorkerSettled(id, res) {
6843
- this.dropAsk(id);
6844
- const rec = this.tasks.get(id);
6845
- if (res.finishReason === "aborted" || rec.status === "cancelled") {
6846
- rec.status = "cancelled";
6847
- this.notify("task_cancelled", `task ${id} (${rec.label}) cancelled`);
6848
- return;
6849
- }
6850
- if (res.finishReason === "error") {
6851
- const msg = res.error instanceof Error ? res.error.message : String(res.error ?? "unknown error");
6852
- return this.failTask(rec, msg);
6853
- }
6854
- rec.status = "done";
6855
- rec.result = res.text;
6856
- const incomplete = res.finishReason !== "stop";
6857
- log11.verbose(`task ${id} done (${res.steps} steps${incomplete ? `, INCOMPLETE: ${res.finishReason}` : ""})`);
6858
- this.notify("task_done", `task ${id} (${rec.label}) completed`, {
6859
- id,
6860
- text: res.text,
6861
- usage: res.usage,
6862
- usageEstimated: res.usageEstimated,
6863
- finishReason: res.finishReason,
6864
- steps: res.steps,
6865
- toolCalls: res.messages.filter((m) => m.role === "tool").length
6866
- });
6867
- if (incomplete) {
6868
- return this.queueRevoice(this.integrationPrompt(rec, "incomplete", res.text, res.finishReason), true);
6869
- }
6870
- const tail = rec.splitter?.flush();
6871
- if (tail?.spoken && !rec.deliveryParked) this.options.host?.notify?.({ kind: "speak_utterance", message: tail.spoken });
6872
- if (res.text.trim()) this.voice.transcript.push({ role: "assistant", content: res.text });
6873
- if (rec.deliveryParked && !this.suppressParkedResume) {
6874
- const gist = (rec.spokenText ?? "").trim() || res.text.trim();
6875
- if (gist) {
6876
- if (this.awaitTrivialRedeliver) {
6877
- this.awaitTrivialRedeliver = false;
6878
- this.options.host?.notify?.({ kind: "speak_utterance", message: gist });
6879
- this.notify("diag", "parked_redelivered", { chars: gist.length });
6880
- } else this.parkedRedeliver.push(gist);
6881
- }
6882
- }
6883
- if (!rec.splitter?.spokeAny && res.text.trim() && !rec.deliveryParked)
6884
- this.options.host?.notify?.({ kind: "speak_utterance", message: res.text });
6885
- }
6886
- onWorkerFailed(id, err) {
6887
- this.failTask(this.tasks.get(id), err instanceof Error ? err.message : String(err));
6888
- }
6889
- failTask(rec, msg) {
6890
- this.dropAsk(rec.id);
6891
- rec.status = "error";
6892
- rec.result = msg;
6893
- log11.warn(`task ${rec.id} failed: ${msg}`);
6894
- this.notify("task_error", `task ${rec.id} (${rec.label}) failed: ${msg}`);
6895
- this.queueRevoice(this.integrationPrompt(rec, "error", msg, "error"), true);
6896
- }
6897
- // --- voice tools (closures over this instance) ---
6898
- /** Live-switch the think tier: `false` disables (removes the Think tool from the voice agent),
6899
- * a model id enables (adds the tool if missing). The system-prompt THINK_SLOT text is frozen at
6900
- * construction — the tool's own description carries the routing guidance, so a live enable works;
6901
- * dispatch()'s think→act fallback covers any straggler calls after a live disable. */
6902
- setThinkModel(model) {
6903
- this.options.thinkModel = model;
6904
- const tools = this.voice.options.tools;
6905
- const i = tools.findIndex((t) => t.name === "Think");
6906
- if (model === false && i >= 0) tools.splice(i, 1);
6907
- else if (model !== false && i < 0) tools.push(this.thinkTool());
6908
- }
6909
- /** User/programmatic spawn: the CLI's /act and /think commands. Returns the task id.
6910
- * `followUp` marks an automatic escalation/re-delegation (set by the integration turn) so the new
6911
- * task's own integration turn won't escalate again — capping auto-follow-ups to one hop. */
6912
- async dispatch(brief, tier = "act", label, followUp = false) {
6913
- if (tier === "think" && this.options.thinkModel === false) tier = "act";
6914
- if (followUp) this.autoEscalations++;
6915
- const id = `t${++this.seq}`;
6916
- const lbl = label ?? tier;
6917
- await this.options.onTaskStart?.(id, lbl);
6918
- this.spawnWorker(id, lbl, this.buildBrief(brief, tier), tier, brief, followUp);
6919
- this.notify("task_started", `task ${id} (${lbl}) started`, { id, brief, tier });
6920
- return id;
6921
- }
6922
- actTool() {
6923
- return {
6924
- name: "Act",
6925
- description: 'Escalate real work (reading/editing files, searching, running tasks, building) to a standard background worker. Returns immediately with a task id; the result arrives later as a "[task <id> completed]" event. Provide a clear, self-contained `brief` (the worker does not hear the live conversation).',
6926
- parameters: {
6927
- type: "object",
6928
- required: ["brief"],
6929
- properties: {
6930
- brief: { type: "string", description: "full, self-contained instructions for the worker" },
6931
- label: { type: "string", description: "a short (2-4 word) label for the task" }
6932
- }
6933
- },
6934
- run: async ({ brief, label }) => {
6935
- this.spokeBeforeDispatch = this.spokeThisTurn;
6936
- this.turnDispatched = true;
6937
- this.turnBriefs.add(String(brief ?? ""));
6938
- this.voice.options.toolChoice = "none";
6939
- const id = await this.dispatch(String(brief ?? ""), "act", label ? String(label) : void 0, this.turnFollowUp);
6940
- return this.spokeBeforeDispatch ? `Acting on task ${id}. You already acknowledged \u2014 end your turn now with NO further text; the result will arrive as a [task ${id} completed] event.` : `Acting on task ${id}. Acknowledge briefly; the result will arrive as a [task ${id} completed] event.`;
6941
- }
6942
- };
6943
- }
6944
- thinkTool() {
6945
- return {
6946
- name: "Think",
6947
- description: "Escalate to a premium deep-reasoning agent for complex analysis, architecture decisions, hard debugging, or planning. Same async pattern as Act \u2014 returns a task id. Use when the problem needs careful thought before (or instead of) action. Do not use Think for simple tasks \u2014 Act is cheaper and faster.",
6948
- parameters: {
6949
- type: "object",
6950
- required: ["brief"],
6951
- properties: {
6952
- brief: { type: "string", description: "the question or problem to reason about deeply" },
6953
- label: { type: "string", description: "a short (2-4 word) label for the task" }
6954
- }
6955
- },
6956
- run: async ({ brief, label }) => {
6957
- this.spokeBeforeDispatch = this.spokeThisTurn;
6958
- this.turnDispatched = true;
6959
- this.turnBriefs.add(String(brief ?? ""));
6960
- this.voice.options.toolChoice = "none";
6961
- const id = await this.dispatch(String(brief ?? ""), "think", label ? String(label) : void 0, this.turnFollowUp);
6962
- return this.spokeBeforeDispatch ? `Thinking on task ${id}. You already acknowledged \u2014 end your turn now with NO further text; the result will arrive as a [task ${id} completed] event.` : `Thinking on task ${id}. Acknowledge briefly; the result will arrive as a [task ${id} completed] event.`;
6963
- }
6964
- };
6965
- }
6966
- taskStatusTool() {
6967
- return {
6968
- name: "TaskStatus",
6969
- description: "Status of background tasks. Pass `id` for one task, or omit it to list all.",
6970
- parameters: { type: "object", properties: { id: { type: "string" } } },
6971
- run: async ({ id }) => {
6972
- const list = id ? [this.tasks.get(String(id))].filter(Boolean) : [...this.tasks.values()];
6973
- if (!list.length) return id ? `No task '${id}'.` : "No background tasks.";
6974
- return list.map((t) => `${t.id} (${t.label}): ${t.status}`).join("\n");
6975
- }
6976
- };
6977
- }
6978
- /** Sub-100ms read-only lookups the voice may do itself — everything else stays Act-only.
6979
- * fs-only (no shell; the engine is VFS-abstracted): time, git branch (.git/HEAD read), ls, file
6980
- * head. Output is hard-capped so a lookup can never bloat the skinny voice context. */
6981
- quickLookTool() {
6982
- const CAP = 2e3;
6983
- const kinds = [.../* @__PURE__ */ new Set(["time", "branch", "ls", "file", "capabilities", ...Object.keys(this.options.quickLook ?? {})])];
6984
- return {
6985
- name: "QuickLook",
6986
- description: `Instant read-only lookup \u2014 one of: ${kinds.join(", ")}. For trivial facts only; anything needing search, commands, or reasoning goes through Act.`,
6987
- parameters: {
6988
- type: "object",
6989
- required: ["what"],
6990
- properties: {
6991
- what: { type: "string", enum: kinds, description: "what to look up" },
6992
- path: { type: "string", description: "for ls/file: the path to look at" }
6993
- }
6994
- },
6995
- run: async ({ what, path }) => {
6996
- const fs = this.options.fs;
6997
- try {
6998
- const over = this.options.quickLook?.[String(what)];
6999
- if (over) return await over(path ? String(path) : void 0);
7000
- switch (String(what)) {
7001
- case "capabilities": {
7002
- const actTools = this.options.actOptions?.tools ?? [];
7003
- const names = actTools.map((t) => t.name);
7004
- const mcpServers = Object.keys(this.options.actOptions?.providerOptions?.mcpServers ?? {});
7005
- const mcpNote = mcpServers.length ? ` Plus MCP servers your worker can use: ${mcpServers.join(", ")} (e.g. browser-bridge \u2192 drive a real browser: open tabs, navigate, click, screenshot).` : "";
7006
- if (!names.length)
7007
- return "Your worker uses Act's default local toolset (reading/editing files, running shell commands). No extra tools (e.g. web/internet) are configured; if a request is not a basic file or shell operation, assume you can't do it and say so." + mcpNote;
7008
- const hasFetch = names.some((n) => /WebFetch/i.test(n));
7009
- const hasBrowser = names.some((n) => /browser.*(navigate|click|page|type)/i.test(n));
7010
- const hasSearch = names.some((n) => /(^|_)WebSearch$|search/i.test(n) && !/WebFetch|browser/i.test(n));
7011
- const notes = [];
7012
- if (hasFetch) notes.push("WebFetch retrieves ONE specific URL you are given \u2014 it is not a search engine.");
7013
- if (hasBrowser) notes.push("The browser tools drive a real browser: you CAN open a site and, if needed, navigate to a search engine and search there \u2014 but it is manual and takes a moment, not an instant lookup.");
7014
- else if (!hasSearch && hasFetch) notes.push('You have no general web-search tool, so for an instant "search the web" you can only fetch a URL they provide.');
7015
- const webNote = notes.length ? " NOTE: " + notes.join(" ") : "";
7016
- return `Tools your background worker (Act) can actually use: ${names.join(", ")}. Read each name literally and match the request to a SPECIFIC tool; if none fits, you do NOT have that ability \u2014 say so honestly.` + webNote + mcpNote;
7017
- }
7018
- case "time":
7019
- return (/* @__PURE__ */ new Date()).toString();
7020
- case "branch": {
7021
- if (!fs) return "unavailable (no filesystem)";
7022
- const head = (await fs.readFile(".git/HEAD")).trim();
7023
- return head.startsWith("ref: refs/heads/") ? `branch: ${head.slice("ref: refs/heads/".length)}` : `detached HEAD at ${head.slice(0, 12)}`;
7024
- }
7025
- case "ls": {
7026
- if (!fs) return "unavailable (no filesystem)";
7027
- const p = String(path ?? ".");
7028
- try {
7029
- const names = await fs.readDir(p);
7030
- return names.slice(0, 50).join("\n") + (names.length > 50 ? `
7031
- \u2026 (+${names.length - 50} more)` : "");
7032
- } catch {
7033
- const names = await fs.readDir(".").catch(() => []);
7034
- return `'${p}' not found here \u2014 you are likely already inside it. Current directory listing:
7035
- ` + names.slice(0, 50).join("\n") + (names.length > 50 ? `
7036
- \u2026 (+${names.length - 50} more)` : "");
7037
- }
7038
- }
7039
- case "file": {
7040
- if (!fs) return "unavailable (no filesystem)";
7041
- if (!path) return "file lookup needs a path";
7042
- try {
7043
- const text = await fs.readFile(String(path));
7044
- return text.length > CAP ? text.slice(0, CAP) + `
7045
- \u2026 (truncated \u2014 ${text.length} chars total; Act for the full file)` : text;
7046
- } catch {
7047
- const names = await fs.readDir(".").catch(() => []);
7048
- return `'${path}' not found. Current directory contains:
7049
- ` + names.slice(0, 50).join("\n");
7050
- }
7051
- }
7052
- default:
7053
- return `unknown lookup '${what}'`;
6503
+ // src/duplex.ts
6504
+ var log13 = forComponent("DuplexAgent");
6505
+ function describeCall(call) {
6506
+ const v = call.args && Object.values(call.args).find((x) => typeof x === "string" && x.trim());
6507
+ const hint = v ? ` (${String(v).replace(/\s+/g, " ").trim().slice(0, 48)})` : "";
6508
+ return `${call.name}${hint}`;
6509
+ }
6510
+ var DuplexAgentOptions = class {
6511
+ /** Any ai.libx.js AIClient — shared by all tiers (routed by model). */
6512
+ ai;
6513
+ /** The WORKER's filesystem (act + think). If omitted the worker keeps Agent's jailed-disk-at-cwd default. */
6514
+ fs;
6515
+ // The reflex IS the voice. 120b (not 20b) for channel discipline + instruction-following: the 20b
6516
+ // mislabels gpt-oss harmony channels under load, leaking raw analysis into the spoken `final` channel
6517
+ // (and misfiring Hold). 120b is the same price tier (~$0.15/$0.60) — the quality/cost trade is free.
6518
+ reflexModel = "groq/openai/gpt-oss-120b";
6519
+ actModel = "anthropic/claude-sonnet-4-6";
6520
+ /** Premium reasoning model. Set to `false` to disable the Think tier entirely. */
6521
+ thinkModel = "anthropic/claude-opus-4-8";
6522
+ /** Per-worker providerOptions, derived from the worker's actual model at spawn time (IoC — keeps duplex
6523
+ * provider-agnostic). Workers override the reflex/main model, so provider-specific options (e.g. cursor's
6524
+ * cwd/cursorSession) must be recomputed for the worker's model, never inherited from the main template —
6525
+ * leaking cursor options to an anthropic worker is a hard 400. Returns undefined → no providerOptions. */
6526
+ providerOptionsFor;
6527
+ /** Escape hatches merged over the derived per-agent options. */
6528
+ reflexOptions;
6529
+ actOptions;
6530
+ thinkOptions;
6531
+ /** Fresh-context check on each successful Act task: a NEW agent (no self-confirmation bias) re-reads
6532
+ * the file state against the brief and fixes any gap before the result is re-voiced. Bounded to one
6533
+ * pass; ~2x Act cost so default OFF. The self-verify FOOTER (same context) was measured ineffective —
6534
+ * this is the structural fix (see mind/10). Think tasks are pure reasoning, never checked. */
6535
+ verifyActTasks = false;
6536
+ /** Receives the voice text_delta stream + task lifecycle events. */
6537
+ host;
6538
+ /** How many recent transcript messages are rendered into a worker's brief. */
6539
+ excerptTurns = 6;
6540
+ /** Voice register: 'neutral' = clean spoken style; 'conversational' = human-like — fillers,
6541
+ * backchannels, impulsive first reactions before content (mimics real duplex conversation). */
6542
+ voiceStyle = "neutral";
6543
+ /** Teach the model to emit inline `[emotion]` tags for Cartesia emotion control. Only set when the
6544
+ * TTS actually speaks them — text-duplex (no TTS) would otherwise print literal tags. */
6545
+ emotionTags = false;
6546
+ /** Awaited BEFORE a worker spawns — open a per-task checkpoint frame, audit, etc.
6547
+ * (post-spawn would race the worker's first edits). */
6548
+ onTaskStart;
6549
+ /** Re-voice throttled worker progress asides ('[task t1 progress] …') so long tasks aren't dead
6550
+ * air. Off by default — each update costs a voice turn (LLM call + speech). */
6551
+ progressUpdates = false;
6552
+ /** Min ms between progress re-voices per task. */
6553
+ progressIntervalMs = 25e3;
6554
+ /** Relay worker questions (AskUserQuestion + permission asks via parkQuestion) through the VOICE:
6555
+ * the question re-voices as '[task <id> asks] …', the user answers conversationally, and the
6556
+ * voice model resolves it with the AnswerTask tool. Off → host.ask passthrough (text menus). */
6557
+ askRelay = false;
6558
+ /** Parked questions auto-resolve empty after this long (callers map '' to deny/best-judgment). */
6559
+ askTimeoutMs = 12e4;
6560
+ /** Max retained task records: oldest SETTLED tasks (and their activity tails) are evicted past this,
6561
+ * bounding memory over a long-lived session. Running tasks are never evicted. */
6562
+ maxTaskRecords = 50;
6563
+ /** Host overrides for QuickLook lookups (keyed by `what`). The engine's defaults go through the
6564
+ * (possibly jailed) fs — e.g. `.git/**` is deny-listed, so the CLI supplies 'branch' itself. */
6565
+ quickLook;
6566
+ /** Memory directory/directories on the WORKER fs. If set, the voice agent gets Remember + Recall
6567
+ * tools directly (no delegation needed) and implicit capture guidance. */
6568
+ memoryDir;
6569
+ /** User-scope memory dir for global facts (type=user/feedback). Forwarded to Remember's routing. */
6570
+ memoryUserDir;
6571
+ };
6572
+ var RESERVED_EVENT_MARKER = /\[task\b[^\]\n]*\b(?:completed|failed|progress|asks)\b/i;
6573
+ var RESERVED_EVENT_OPENER = /\[\s*task\b/i;
6574
+ var STAGE_DIRECTION_RE = /^\(\s*(?:(?:waiting|checking|searching|thinking|processing|loading|working|fetching|looking)\b[^)]*|[^)]*(?:\.\.\.|…)\s*)\)$/i;
6575
+ function nowLine() {
6576
+ return `Current date and time: ${(/* @__PURE__ */ new Date()).toLocaleString("en-US", { weekday: "long", year: "numeric", month: "long", day: "numeric", hour: "numeric", minute: "2-digit", timeZoneName: "short" })}`;
6577
+ }
6578
+ function isTrivialBarge(text) {
6579
+ const t = text.trim().toLowerCase().replace(/[.,!?…\s]+$/g, "").replace(/^[.,!?…\s]+/, "");
6580
+ if (!t) return false;
6581
+ if (/\b(stop|cancel|no|nope|nah|never\s?mind|nvm|forget it|drop it|don'?t|quiet|shut up|enough|hold on|wait|pause|hang on|actually)\b/.test(t)) return false;
6582
+ const core = t.replace(/^(?:oh|um+|uh+|er+|hmm+|ah+|well|so|okay|ok|yeah|yep)[\s,]+/, "").trim();
6583
+ return /^(?:oh|um+|uh+|er+|hmm+|ah+|sorry|oops|whoops|my bad|pardon|excuse me|apologies|go on|go ahead|continue|keep going|carry on|as you were|please continue|you were saying|sorry go on|sorry continue|go on then|go on please)$/.test(core || t);
6584
+ }
6585
+ var VOICE_SYSTEM_PROMPT = 'You are a spoken voice assistant \u2014 the user HEARS everything you say. Use short sentences. One idea per sentence. No markdown, no bullet lists, no code blocks, no headings, no emoji. Never emit stage directions or parenthetical asides about your own process \u2014 nothing like "(waiting for the result...)" or "(checking)"; while work runs, either say it as plain speech or end your turn.\nThis holds even when asked to "print", "list", "show", or "make a table" \u2014 there is no screen for the spoken channel. Speak it as flowing prose ("Tuesday is half a meter, Wednesday a bit less\u2026"), or if they truly need it on screen, route it to Act to render. Never emit dashes or pipes into speech.\nKeep turns SHORT \u2014 one to three sentences, then stop. Never lecture, enumerate cases, or add caveats unprompted. Conversation is a fast exchange: give the one thing asked, and let the user pull more if they want it.\nYou have three cognitive tiers \u2014 like a human brain:\n\u2022 YOU (reflex) \u2014 instant, lightweight. Handle greetings, simple questions, status checks, QuickLook.\n\u2022 `Act` \u2014 your hands. A background worker with its own configured tools and access to the user\'s environment (files and shell{{WORKER_WEB}}). Use for reading, editing, searching, running tasks, building \u2014 any real work.\n{{THINK_SLOT}}\nWhen you are unsure whether you can do or access something, do NOT assume and do NOT claim a capability you have not confirmed. To check what you can do, QuickLook `capabilities` (instant \u2014 it lists your worker\'s real tools) and answer from that. Never promise an ability that is not in your capabilities; if it is not there, tell the user plainly you can\'t. To actually DO real work, call `Act`. When the user mentions their project, folder, files, or environment ("this project", "the current folder", "my code"), call `Act` IMMEDIATELY \u2014 do not ask for paths or details the worker can discover itself. Never pretend to have done the work or invent results \u2014 the worker\'s report is your only source.\nYou cannot mute the microphone or stop voice capture yourself \u2014 no tool does it. If the user asks you to stop listening or turn the voice off, never claim you did: tell them to say exactly "voice off" (handled by the app directly), or type /voice.\nYou are NOT a knowledge base. For any question whose answer needs SPECIFIC verifiable facts you do not already have in hand \u2014 how to build/configure/implement something, exact API, library, entitlement, command or option names, current events, or particular numbers, dates, or names \u2014 do NOT answer from your own memory: you will confidently make things up (a fake API, a wrong entitlement, an event that did not happen). Route it to `Act`, which can search and verify, and speak only what its report says. DELEGATION RULE \u2014 decide for yourself, the user never has to push: if you cannot answer confidently from the conversation plus trivial well-known knowledge, do NOT refuse and do NOT guess \u2014 dispatch `Act` immediately with a clear brief and say you are checking. Anything needing CURRENT data (weather, news, prices, dates, sky/astronomy, "right now"), real computation, or verification is an automatic dispatch \u2014 never a refusal. The user should never need to say "search the web" or "think harder" to make you act; needing fresh or verified information IS the trigger. Refuse only what your worker genuinely cannot do (check `capabilities`), and say why. Answer inline ONLY for general conversation, chit-chat, and trivia you are sure of, or facts you can see via QuickLook. When elaborating on a completed task ("tell me more", "the gist"), stay strictly within what that result actually said \u2014 if the user asks for something the result did not cover, that is NEW information: dispatch `Act`, do not improvise.\nALWAYS react before you work: the FIRST thing in your turn is a brief spoken acknowledgement of what you heard and what you are about to do ("got it \u2014 opening that now", "sure, let me pull it up", "okay, checking"). NEVER call a tool (Act, Think, QuickLook) silently \u2014 the user must hear you react before you go quiet to work. After dispatching Act or Think, that same one short sentence IS your turn \u2014 end it and do not wait for the result. Exactly ONE short line: never stack a second acknowledgement, and never narrate your own presence or status while waiting ("I\'m here", "let me see", "still checking" right after you already acked). One clean ack then silence reads as competent; repeated check-ins read as nervous.\nA completed task speaks its OWN result to the user (the worker voices what matters as it finishes) \u2014 you do NOT re-voice clean task results. A FAILED or INCOMPLETE task still arrives as a "[task t1 failed] \u2026" event for you to handle. The completed result stays in YOUR context \u2014 it is yours to draw on. When the user follows up ("tell me more", "what else", "and?"), answer FROM that result first: you already have the detail, so elaborate on what you have. Do NOT spawn a fresh worker to re-search or re-gather what you were just handed. Re-dispatch ONLY when genuinely new information is needed \u2014 e.g. the user wants the full contents of a SPECIFIC source, which is one WebFetch of that URL, not a brand-new search. "[task t1 progress] \u2026" events are interim status, NOT results \u2014 on a genuinely LONG wait you MAY give one brief half-sentence aside, but only occasionally; silence while working is normal and fine (the user knows you are on it). Do NOT narrate every step or re-announce yourself. Never present progress as a finished result.\nCRITICAL: while a task is still running you have NO answer yet \u2014 never state a specific result of any kind (a number, size, count, name, path, or value). The real answer arrives ONLY in the "[task \u2026 completed]" event; inventing one meanwhile (a made-up disk size, commit count, etc.) is a serious error. Until then, only acknowledge and wait.\nNever read raw file paths, diffs, or code aloud verbatim.\nDo NOT end every turn with the same canned offer ("want a rundown?", "want the steps?"). Offer once at most; if the user pushes back, repeats themselves, or sounds unsatisfied ("you know what I mean?", "think deeper", "are you sure?"), do NOT re-offer the same thing \u2014 change approach: dispatch `Act`/`Think` to actually dig in, or ask one concrete clarifying question. Repeating a non-answer is worse than silence.\n"[task t1 asks] \u2026" events are QUESTIONS from a background task \u2014 relay to the user in your own words, short, then end your turn. When the user answers, call `AnswerTask` with that id and their answer. NEVER answer on the user\'s behalf for permissions or risky operations; if their reply is ambiguous, confirm first.\nIf the user\'s message sounds INCOMPLETE \u2014 trailing off mid-sentence, a fragment that needs more context ("and then we", "but the problem is"), hesitation fillers ("uh", "um") \u2014 call `Hold` instead of answering. This keeps listening for the rest of their thought. Only respond with substance when you have a complete question or request.\nDispatch discipline: send ONE self-contained task per request \u2014 a single worker with the full brief beats several workers with fragments (each worker starts fresh and re-discovers context). NEVER dispatch a worker just to read files or gather information \u2014 workers explore and discover context themselves; pass on what you already know and let one worker do the whole job. Split into parallel tasks only when the user asks for genuinely independent things. When a task completes, report its result and stop \u2014 do NOT dispatch follow-up work (verification, polish, extras) the user did not ask for, unless the report itself signals failure or doubt.\nDo not fire a second Act/Think for work already in flight, and NEVER spawn a second task to re-count, cross-check, or verify a result a worker already gave you \u2014 trust its answer; a single question gets ONE task. Call `TaskStatus` at most ONCE per turn; if a task is still running, give one brief status aside and end the turn \u2014 never poll it again and again in a loop. "Still on it" is ONLY for a repeat check on a task you already acknowledged earlier \u2014 NEVER as the ack when you first dispatch work ("still" is wrong when nothing was running yet; use a fresh "on it"/"got it, checking" instead). Use `CancelTask` when the user asks to stop something.\nPRIORITY: when the user says goodbye or wants to end/finish/wrap up the session ("ok bye", "that\'s all", "let\'s finish", "let\'s end", "goodnight", "exit", "wrap up"), call `ExitSession` IMMEDIATELY \u2014 do not act, do not check status, just exit.\nFor TRIVIAL instant lookups only \u2014 current time, git branch, listing a folder, peeking at a small file, or checking your own `capabilities`/tools \u2014 use `QuickLook` (instant, no task). Whenever the user asks what you can do or whether you have some ability, QuickLook `capabilities` and answer from that \u2014 never guess. Anything requiring searching, reasoning, running commands, or editing goes through `Act`.\n{{MEMORY_SLOT}}\nUser messages may arrive via speech-to-text and can carry transcription artifacts \u2014 odd words, cut-offs, homophones ("for you" vs "folder"). Read for INTENT, not surface text. If a message seems garbled, surprising, or only half-parses, do NOT guess an action or improvise content from it \u2014 briefly confirm what they meant ("did you mean\u2026?") and wait. A one-line confirm beats a confident wrong answer or an invented response to a request you did not actually understand.';
6586
+ var THINK_GUIDANCE = "\u2022 `Think` \u2014 your brain. A premium reasoning model, FAR more expensive than Act. Reserve it for open-ended architecture/design questions, or a problem Act already FAILED at. ALL implementation work \u2014 coding, refactoring, debugging, edge cases, tests \u2014 goes to Act; Act is highly capable. Never send the same work to both.";
6587
+ var THINK_DISABLED_GUIDANCE = "(Think tier is not available \u2014 use Act for all escalations.)";
6588
+ var VOICE_STYLE_CONVERSATIONAL = `Speak like a person in a live conversation, not an assistant reading a script. React first, then deliver: a quick impulsive beat ("oh nice", "hmm, hold on", "ah, got it") before the substance. Use contractions always. Vary sentence length \u2014 some very short. Light fillers and backchannels are fine ("mm-hm", "right", "let's see") but at most one per reply \u2014 never stack them. When you escalate to Act or Think, say it like a human would ("hang on, let me actually dig into that \u2014 gimme a minute") instead of announcing a task. When a result comes back, react to it like you just found out ("okay so \u2014 turns out\u2026"). Match the user's energy: a quick question gets a quick answer \u2014 a few words is a perfectly good turn. Prefer a short answer plus an offer ("want the details?") over covering everything. Never narrate your own mechanics (no "I will now act", no task ids out loud).`;
6589
+ var EMOTION_TAGS_GUIDANCE = `EMOTION: your voice is synthesized with emotion control. Prefix a sentence with an inline [emotion] tag, placed directly before the sentence it colors, to shape how it is spoken. Use it ONLY when the emotion genuinely fits the words (it amplifies real feeling, it cannot fake it) \u2014 do not tag every sentence; reserve it for moments that carry feeling, and vary which one you use. You may also drop [laughter] for a natural laugh. Available emotions: ${EMOTIONS.join(", ")}.`;
6590
+ var DuplexAgent = class _DuplexAgent {
6591
+ options;
6592
+ voice;
6593
+ tasks = /* @__PURE__ */ new Map();
6594
+ queue = Promise.resolve();
6595
+ seq = 0;
6596
+ pendingEvents = [];
6597
+ /** Spoken text of parked deliveries that have SETTLED, awaiting a trivial-barge resume decision on the
6598
+ * next turn (a substantive turn clears it — the result stays in the transcript, recoverable by asking). */
6599
+ parkedRedeliver = [];
6600
+ /** A trivial barge arrived while a parked delivery was STILL RUNNING → resume it the moment it settles. */
6601
+ awaitTrivialRedeliver = false;
6602
+ /** Set by a SUBSTANTIVE turn after a barge: the user moved on, so a parked delivery that settles LATER
6603
+ * must NOT arm a resume (else a much-later "go on" replays a stale result). Reset by a fresh barge. */
6604
+ suppressParkedResume = false;
6605
+ /** Out-of-band follow-up attribution for the events coalescing into the next flush turn: TRUE iff ≥1 of
6606
+ * the tasks being integrated was NON-CLEAN (early-stop/failure). Carried out-of-band on the enqueue call
6607
+ * by the caller that KNOWS the outcome — a plain boolean the MODEL CANNOT PERTURB. It is NOT scanned from
6608
+ * worker-authored event text (v1: an "Outcome:" substring over-stamped siblings) and NOT keyed on a brief
6609
+ * string the reflex re-authors (v2: a paraphrased escalation brief missed the Set → followUp:false →
6610
+ * RE-ENABLED unbounded auto-escalation, the dangerous runaway direction). See [[wrong-discriminator]] /
6611
+ * [[drive-real-reflex]] / [[fakeaiclient-blind-to-wire-format]]. */
6612
+ pendingNonClean = false;
6613
+ flushQueued = false;
6614
+ /** Per-voice-turn guards (reset by resetTurn at each turn's start). The reflex is a weak model:
6615
+ * left unguarded it polls TaskStatus after a dispatch and/or dispatches silently (dead air).
6616
+ * Like CC's Task tool, a dispatch is "said my piece, now wait for the push" — these enforce that. */
6617
+ turnDispatched = false;
6618
+ // an Act/Think fired this turn
6619
+ spokeBeforeDispatch = false;
6620
+ // the reflex ALREADY acked before dispatching — the forced post-dispatch text step must stay silent (live: "Got it…" twice)
6621
+ turnBriefs = /* @__PURE__ */ new Set();
6622
+ // briefs dispatched this turn (detect identical re-dispatch)
6623
+ spokeThisTurn = false;
6624
+ // any non-empty text_delta streamed this turn
6625
+ externalSpeech = false;
6626
+ // host spoke on our behalf (adaptive micro-ack) — not reflex output
6627
+ heldThisTurn = false;
6628
+ // Hold called this turn → turn is INTENTIONALLY silent (suppress reflex text + no dead-air ack)
6629
+ nudging = false;
6630
+ // re-ack pass in flight: block ALL tools, prevent recursion
6631
+ reflexBuf = "";
6632
+ // accumulated reflex text this turn (fabricated-event detection)
6633
+ reflexForwarded = 0;
6634
+ // chars of reflexBuf already forwarded to the host/TTS
6635
+ fabricationCut = false;
6636
+ // reflex emitted a reserved [task …] marker → suppress its tail
6637
+ /** TRUE for the duration of a re-voice turn that is integrating ≥1 NON-CLEAN task (turn-eligibility,
6638
+ * carried out-of-band — NOT derived from any worker/brief string). ANY Act/Think dispatched in such a
6639
+ * turn is stamped followUp:true. This GUARANTEES the dangerous direction is impossible: a genuine
6640
+ * escalation (even one with a paraphrased brief) ALWAYS lands in a non-clean integration turn, so it is
6641
+ * ALWAYS recognized as a follow-up and CANNOT re-escalate (one hop). The single-dispatch-per-turn guard
6642
+ * means at most one dispatch happens per flush, so realistically "the one dispatch IS the escalation".
6643
+ * ACCEPTED SAFE-DIRECTION ERROR: if the reflex instead dispatches FRESH unrelated work during a non-clean
6644
+ * flush (rare — and only possible when it batches multiple calls in one step, bypassing the guard), that
6645
+ * fresh task is over-stamped followUp:true and forgoes ONE future auto-escalation. That is SAFE (it only
6646
+ * ever REMOVES a future escalation, never adds one — no runaway) and is the correct side to err on. */
6647
+ turnFollowUp = false;
6648
+ /** Hard absolute backstop against runaway regardless of attribution: total automatic escalations across
6649
+ * the whole conversation. Once it hits MAX_AUTO_ESCALATIONS, no integration turn offers escalate/re-delegate. */
6650
+ autoEscalations = 0;
6651
+ static MAX_AUTO_ESCALATIONS = 8;
6652
+ /** Parked worker questions awaiting a (voice-relayed) user answer, keyed by ask id. */
6653
+ pendingAsks = /* @__PURE__ */ new Map();
6654
+ /** SPECULATIVE REFLEX (VoiceEngine.onSpeculate → speculate()): the reflex turn starts on a stable
6655
+ * PARTIAL transcript, its spoken output buffered — nothing reaches TTS until the endpointed final
6656
+ * confirms via send() (which flushes the buffer and adopts the call as THE turn). A divergent final
6657
+ * aborts it: output dropped, history rolled back, the final dispatches normally. */
6658
+ spec;
6659
+ /** Aborted speculative calls (double-billing visibility — each one paid for tokens never spoken). */
6660
+ speculativeAbortedCalls = 0;
6661
+ /** Tools the reflex may execute on UNCONFIRMED (speculated) input — read-only lookups and the
6662
+ * intentionally-silent Hold. Anything else (Act/Think/AnswerTask/CancelTask/ExitSession/memory
6663
+ * writes/…) is a side effect on input the user may not have said: the guard ABORTS the speculation
6664
+ * instead (the endpointed final then dispatches normally and may use the tool for real). */
6665
+ static SPEC_SAFE_TOOLS = /* @__PURE__ */ new Set(["QuickLook", "TaskStatus", "Hold"]);
6666
+ /** Lazily resolved memory tools (async loadMemory runs in initMemory). */
6667
+ memoryReady;
6668
+ constructor(options) {
6669
+ this.options = { ...new DuplexAgentOptions(), ...options };
6670
+ const o = this.options;
6671
+ if (o.memoryDir && o.fs) {
6672
+ this.memoryReady = loadMemory(o.fs, o.memoryDir, { maxWritesPerSession: 10, userDir: o.memoryUserDir });
6673
+ }
6674
+ const memSlot = o.memoryDir && o.fs ? VOICE_MEMORY_PROMPT : "NEVER claim to have stored, saved, or remembered something durably \u2014 you cannot. Anything the user wants persisted (their name, preferences, notes) must go through Act so a worker writes it to memory.";
6675
+ const thinkSlot = o.thinkModel !== false ? THINK_GUIDANCE : THINK_DISABLED_GUIDANCE;
6676
+ const workerToolNames = (o.actOptions?.tools ?? []).map((t) => t.name);
6677
+ const canSearch = workerToolNames.some((n) => /WebSearch/i.test(n));
6678
+ const canFetch = workerToolNames.some((n) => /WebFetch/i.test(n));
6679
+ const workerWeb = canSearch ? `, and it CAN search the web and read web pages \u2014 so when the user gives you something specific to look up ("search for X", "find me\u2026", "what's the latest on\u2026"), route it to Act. But a bare capability QUESTION like "can you search the web?" just gets a short spoken "yes, I can" \u2014 do NOT dispatch and NEVER invent a query the user did not give you` : canFetch ? ", and it can fetch a specific web page URL (but cannot search the web)" : "";
6680
+ const mcpNames = [
6681
+ ...Object.keys(o.actOptions?.providerOptions?.mcpServers ?? {}),
6682
+ ...new Set(workerToolNames.filter((n) => n.startsWith("mcp__")).map((n) => n.slice(5).split("__")[0]))
6683
+ ];
6684
+ const workerMcp = mcpNames.length ? `, and it can use these MCP servers: ${[...new Set(mcpNames)].join(", ")}` + (mcpNames.some((n) => /browser/i.test(n)) ? ' \u2014 including driving a REAL browser (open tabs, navigate, click, screenshot), so answer "yes" if asked whether you can control/drive a browser and route an actual browse to Act' : "") : "";
6685
+ const prompt = VOICE_SYSTEM_PROMPT.replace("{{MEMORY_SLOT}}", memSlot).replace("{{THINK_SLOT}}", thinkSlot).replace("{{WORKER_WEB}}", workerWeb + workerMcp) + (o.voiceStyle === "conversational" ? "\n" + VOICE_STYLE_CONVERSATIONAL : "") + (o.emotionTags ? "\n" + EMOTION_TAGS_GUIDANCE : "") + `
6686
+ ${nowLine()}. Anchor every relative or time-sensitive reference \u2014 "today", "now", "current", "recent", "latest", "this year" \u2014 to THIS moment. When the user asks about something recent (news, sports, events), they mean near this date, not a well-known past instance; brief your worker with the current year so it searches for what is happening NOW, not a famous older event.`;
6687
+ const tools = [
6688
+ ...o.reflexOptions?.tools ?? [],
6689
+ this.actTool(),
6690
+ ...o.thinkModel !== false ? [this.thinkTool()] : [],
6691
+ this.taskStatusTool(),
6692
+ this.cancelTaskTool(),
6693
+ this.quickLookTool(),
6694
+ this.answerTaskTool(),
6695
+ this.holdTool()
6696
+ ];
6697
+ const host = o.host;
6698
+ const voiceHost = host && {
6699
+ ask: host.ask ? (q) => host.ask(q) : void 0,
6700
+ confirm: host.confirm ? (p, m) => host.confirm(p, m) : void 0,
6701
+ notify: (ev) => {
6702
+ if (ev?.kind === "text_delta" && typeof ev.message === "string") {
6703
+ if (this.heldThisTurn) return;
6704
+ if (this.fabricationCut) return;
6705
+ if (this.turnDispatched && this.spokeBeforeDispatch) return;
6706
+ const msg = ev.message;
6707
+ this.reflexBuf += msg;
6708
+ this.scrubStageDirections();
6709
+ const m = this.reflexBuf.match(RESERVED_EVENT_MARKER) ?? this.reflexBuf.match(RESERVED_EVENT_OPENER);
6710
+ if (m) {
6711
+ this.fabricationCut = true;
6712
+ log13.warn(`reflex fabricated a [task \u2026] event in its spoken stream \u2014 cutting it (kept ${m.index} chars)`);
6713
+ const safe = this.reflexBuf.slice(this.reflexForwarded, m.index);
6714
+ if (!safe) return;
6715
+ if (safe.trim()) this.spokeThisTurn = true;
6716
+ this.emitHost({ ...ev, message: safe });
6717
+ return;
7054
6718
  }
7055
- } catch (e) {
7056
- return `lookup failed: ${e?.message ?? e}`;
6719
+ const held = this.reflexBuf.length - this.reflexForwarded;
6720
+ const partial = held > 0 && /\[\s*t?a?s?k?$/i.test(this.reflexBuf.slice(-Math.min(held, 6)));
6721
+ let upto = partial ? this.reflexBuf.length - this.reflexBuf.slice(-6).match(/\[\s*t?a?s?k?$/i)[0].length : this.reflexBuf.length;
6722
+ const paren = this.reflexBuf.lastIndexOf("(");
6723
+ if (paren >= this.reflexForwarded && !this.reflexBuf.includes(")", paren) && this.reflexBuf.length - paren <= 80)
6724
+ upto = Math.min(upto, paren);
6725
+ const out = this.reflexBuf.slice(this.reflexForwarded, upto);
6726
+ this.reflexForwarded = upto;
6727
+ if (!out) return;
6728
+ if (out.trim()) this.spokeThisTurn = true;
6729
+ this.emitHost({ ...ev, message: out });
6730
+ return;
7057
6731
  }
6732
+ host.notify?.(ev);
7058
6733
  }
7059
6734
  };
6735
+ this.voice = new Agent({
6736
+ ai: o.ai,
6737
+ fs: new MemFilesystem2(),
6738
+ model: o.reflexModel,
6739
+ stream: true,
6740
+ host: voiceHost,
6741
+ // The reflex IS the conversational channel — it confirms ambiguity inline ("did you mean…?"),
6742
+ // never via the blocking AskUserQuestion tool (Agent auto-adds it whenever a host is set). Left in,
6743
+ // it stalls a voice turn until the kill-switch. Worker questions still reach the user via parkQuestion.
6744
+ askUserQuestion: false,
6745
+ systemPrompt: prompt,
6746
+ instructionFiles: false,
6747
+ maxSteps: 8,
6748
+ timeoutMs: 3e4,
6749
+ ...o.reflexOptions,
6750
+ tools,
6751
+ // Composed AFTER the spread so the dispatch guard can't be dropped by reflexOptions.
6752
+ hooks: composeHooks(this.dispatchGuard(), o.reflexOptions?.hooks)
6753
+ });
7060
6754
  }
7061
- answerTaskTool() {
7062
- return {
7063
- name: "AnswerTask",
7064
- description: `Relay the user's answer to a pending question from a background task (the "[task <id> asks]" events). Pass the id from the event and the user's answer.`,
7065
- parameters: {
7066
- type: "object",
7067
- required: ["id", "answer"],
7068
- properties: { id: { type: "string" }, answer: { type: "string", description: "the user's answer, verbatim or faithfully summarized" } }
7069
- },
7070
- run: async ({ id, answer }) => {
7071
- const ask = this.pendingAsks.get(String(id));
7072
- if (!ask) return `No pending question for '${id}' \u2014 it may have been answered already or timed out.`;
7073
- ask.resolve(String(answer ?? ""));
7074
- return `Answer relayed \u2014 task ${id} resumes.`;
7075
- }
7076
- };
6755
+ /** Resolve memory tools + inject index into voice system prompt (once). */
6756
+ async initMemory() {
6757
+ if (!this.memoryReady) return;
6758
+ const mem = await this.memoryReady;
6759
+ this.memoryReady = void 0;
6760
+ this.voice.options.tools.push(...mem.tools);
6761
+ if (mem.index) this.voice.options.systemPrompt += "\n\n" + mem.index;
7077
6762
  }
7078
- holdTool() {
6763
+ /** Flush any held-back trailing fragment (a possible `[task` opener that never completed) once the
6764
+ * turn's stream is done — so a legit message ending in "[t" isn't silently dropped. */
6765
+ flushHeldReflexTail() {
6766
+ if (this.fabricationCut) return;
6767
+ this.scrubStageDirections();
6768
+ const tail = this.reflexBuf.slice(this.reflexForwarded);
6769
+ this.reflexForwarded = this.reflexBuf.length;
6770
+ if (!tail) return;
6771
+ if (tail.trim()) this.spokeThisTurn = true;
6772
+ this.emitHost({ kind: "text_delta", message: tail });
6773
+ }
6774
+ /** Remove complete stage-direction parentheticals from the UNFORWARDED reflex text (STAGE_DIRECTION_RE).
6775
+ * Only the unforwarded region is touched — already-spoken audio can't be unsent, and splicing before
6776
+ * reflexForwarded would corrupt the forward offset. */
6777
+ scrubStageDirections() {
6778
+ if (this.reflexForwarded >= this.reflexBuf.length) return;
6779
+ const region = this.reflexBuf.slice(this.reflexForwarded);
6780
+ const scrubbed = region.replace(/\([^()]*\)/g, (s) => STAGE_DIRECTION_RE.test(s) ? "" : s);
6781
+ if (scrubbed !== region) this.reflexBuf = this.reflexBuf.slice(0, this.reflexForwarded) + scrubbed;
6782
+ }
6783
+ /** Clear the per-turn guards. Called at the head of every voice turn (user send + re-voice flush). */
6784
+ resetTurn() {
6785
+ this.turnDispatched = false;
6786
+ this.spokeBeforeDispatch = false;
6787
+ this.turnBriefs.clear();
6788
+ this.spokeThisTurn = false;
6789
+ this.externalSpeech = false;
6790
+ this.heldThisTurn = false;
6791
+ this.reflexBuf = "";
6792
+ this.reflexForwarded = 0;
6793
+ this.fabricationCut = false;
6794
+ this.turnFollowUp = false;
6795
+ this.voice.options.toolChoice = void 0;
6796
+ }
6797
+ /** preToolUse guard on the reflex: once it has dispatched this turn, a dispatch is "said my piece,
6798
+ * now wait for the push" (CC's Task model). Block the temptations — TaskStatus polling and identical
6799
+ * re-dispatch — so the only remaining move is to voice a short ack and end. A genuinely NEW Act is
6800
+ * still allowed (parallel independent work). During a re-ack pass, block every tool. */
6801
+ dispatchGuard() {
7079
6802
  return {
7080
- name: "Hold",
7081
- description: 'The user seems mid-thought \u2014 hold the turn (stay listening) instead of answering. Optionally pass a short filler ("mhm", "go on") to speak while waiting. Use when the message sounds incomplete, trailing off, or like they paused to think.',
7082
- parameters: {
7083
- type: "object",
7084
- properties: {
7085
- filler: { type: "string", description: 'optional short filler to speak ("mhm", "go on", "mm-hm")' }
6803
+ preToolUse: (call) => {
6804
+ if (this.spec?.state === "pending" && !_DuplexAgent.SPEC_SAFE_TOOLS.has(call.name)) {
6805
+ log13.verbose(`speculation aborted: reflex called ${call.name} on unconfirmed input`);
6806
+ this.abortSpeculation();
6807
+ return { block: true, reason: "Speculative turn aborted." };
7086
6808
  }
7087
- },
7088
- run: async ({ filler }) => {
7089
- this.heldThisTurn = true;
7090
- this.notify("hold_filler", filler ? String(filler) : "");
7091
- return "Holding \u2014 listening for the rest of the user's thought. Do not respond further this turn.";
6809
+ if (this.nudging) return { block: true, reason: "Just say one short spoken acknowledgement \u2014 no tools this turn." };
6810
+ if (!this.turnDispatched) return;
6811
+ if (call.name === "TaskStatus")
6812
+ return { block: true, reason: "You just dispatched a task this turn \u2014 do NOT poll. Give one short spoken acknowledgement and end your turn; the result arrives later as a [task \u2026] event." };
6813
+ if ((call.name === "Act" || call.name === "Think") && this.turnBriefs.has(String(call.args?.brief ?? "")))
6814
+ return { block: true, reason: "You already dispatched this exact task \u2014 acknowledge briefly and end your turn." };
7092
6815
  }
7093
6816
  };
7094
6817
  }
7095
- cancelTaskTool() {
7096
- return {
7097
- name: "CancelTask",
7098
- description: "Cancel a running background task by id.",
7099
- parameters: { type: "object", required: ["id"], properties: { id: { type: "string" } } },
7100
- run: async ({ id }) => this.cancelTask(String(id))
7101
- };
6818
+ /** The host spoke on this turn's behalf OUTSIDE the reflex stream (e.g. the voice engine's adaptive
6819
+ * micro-ack). For a DISPATCHED turn that's a sufficient ack (don't stack a second one); for an
6820
+ * inline turn whose reply came back empty it is NOT — "One sec." followed by permanent silence is
6821
+ * still dead air, so silentTurn ignores external speech unless work was dispatched. */
6822
+ noteExternalSpeech() {
6823
+ this.externalSpeech = true;
7102
6824
  }
7103
- };
7104
-
7105
- // src/mcp.ts
7106
- function toResult(result) {
7107
- if (result == null) return { text: "" };
7108
- if (typeof result === "string") return { text: result };
7109
- const content = result.content;
7110
- if (Array.isArray(content)) {
7111
- const texts = [];
7112
- const images = [];
7113
- for (const c of content) {
7114
- if (c?.type === "image" && typeof c.data === "string" && c.mimeType) {
7115
- images.push({ mimeType: c.mimeType, data: c.data });
7116
- } else if (typeof c?.text === "string") {
7117
- texts.push(c.text);
7118
- } else {
7119
- texts.push(JSON.stringify(c));
7120
- }
7121
- }
7122
- const text = texts.join("\n");
7123
- if (text || images.length) return { text, ...images.length ? { images } : {} };
6825
+ /** True when the just-finished turn voiced NOTHING — dead air to repair. Two ways this happens:
6826
+ * (a) a dispatch with no spoken ack, and (b) an INLINE turn whose `final` channel came back empty —
6827
+ * gpt-oss harmony sometimes puts the whole reply in `analysis` (→ thinking_delta, suppressed in
6828
+ * voice) and emits an empty `final`, so no text_delta ever streams. Both ship silence; both repair.
6829
+ * Requires a host: without one there's no stream to detect speech on (and no one to speak to). */
6830
+ get silentTurn() {
6831
+ const ackedByHost = this.externalSpeech && this.turnDispatched;
6832
+ return !!this.options.host && !this.spokeThisTurn && !ackedByHost && !this.heldThisTurn;
7124
6833
  }
7125
- return { text: JSON.stringify(result) };
7126
- }
7127
- function mcpToolToAgentTool(spec, callTool, prefix = "mcp__") {
7128
- return {
7129
- name: `${prefix}${spec.name}`,
7130
- description: spec.description ?? `MCP tool ${spec.name}`,
7131
- parameters: spec.inputSchema ?? { type: "object", properties: {} },
7132
- async run(args, _ctx) {
7133
- const r = toResult(await callTool(spec.name, args ?? {}));
7134
- return r.images?.length ? r : r.text;
6834
+ /** A turn that voiced nothing is dead air. Re-prompt the reflex ONCE so the LLM itself voices a short
6835
+ * line (no template). If it STILL says nothing, fall back to a minimal line so silence never ships.
6836
+ * Wording adapts to whether work was dispatched (an ack) or the inline reply was simply lost. */
6837
+ async ackIfSilent(fallback) {
6838
+ const dispatched = this.turnDispatched;
6839
+ this.nudging = true;
6840
+ try {
6841
+ await this.voice.send(fallback ? "[reminder] You said nothing to the user this turn. Tell them, in ONE short spoken sentence, what just happened \u2014 no tools." : dispatched ? "[reminder] You dispatched a task but said nothing to the user. Say ONE short spoken acknowledgement now \u2014 no tools." : "[reminder] You said nothing to the user this turn. Give your ONE short spoken reply now \u2014 no tools.");
6842
+ } catch (e) {
6843
+ log13.warn(`ack nudge failed: ${e instanceof Error ? e.message : e}`);
6844
+ } finally {
6845
+ this.nudging = false;
7135
6846
  }
7136
- };
7137
- }
7138
- function mcpToolsToAgentTools(specs, callTool, prefix = "mcp__", filter) {
7139
- return (filter ? specs.filter(filter) : specs).map((s) => mcpToolToAgentTool(s, callTool, prefix));
7140
- }
7141
- function describeSpec(s) {
7142
- const schema = s.inputSchema ? `
7143
- args: ${JSON.stringify(s.inputSchema)}` : "";
7144
- return `${s.name} \u2014 ${s.description ?? "(no description)"}${schema}`;
7145
- }
7146
- function makeMcpToolSearch(specs, callTool, options = {}) {
7147
- const maxResults = options.maxResults ?? 10;
7148
- const byName = new Map(specs.map((s) => [s.name, s]));
7149
- const catalogLine = `${specs.length} MCP tool(s) available \u2014 search by keyword, then call by exact name.`;
7150
- const searchTool = {
7151
- name: "ToolSearch",
7152
- description: `Search the available MCP tools by keyword (${catalogLine}). Returns matching tool names + their argument schemas; call one with \`McpCall\`.`,
7153
- parameters: { type: "object", required: ["query"], properties: { query: { type: "string", description: "keywords to match against tool name + description" } } },
7154
- async run({ query }) {
7155
- const q = String(query ?? "").trim();
7156
- if (!q) return catalogLine;
7157
- const { kept } = topByRelevance(specs, q, (s) => `${s.name} ${s.description ?? ""}`, maxResults);
7158
- if (!kept.length) return `(no MCP tool matches "${q}" \u2014 try broader keywords)`;
7159
- return kept.map(describeSpec).join("\n");
6847
+ if (!this.spokeThisTurn) {
6848
+ const pool = fallback ? [fallback] : dispatched ? _DuplexAgent.FALLBACK_ACKS : _DuplexAgent.FALLBACK_RETRY;
6849
+ const fresh = pool.filter((p) => p !== this.lastFallback);
6850
+ const line = (fresh.length ? fresh : pool)[Math.floor(Math.random() * (fresh.length || pool.length))];
6851
+ this.lastFallback = line;
6852
+ this.emitHost({ kind: "text_delta", message: line });
7160
6853
  }
7161
- };
7162
- const callMcpTool = {
7163
- name: "McpCall",
7164
- description: "Call an MCP tool discovered via `ToolSearch`, by its exact name. Pass its arguments as `args`.",
7165
- parameters: {
7166
- type: "object",
7167
- required: ["name"],
7168
- properties: {
7169
- name: { type: "string", description: "exact tool name from ToolSearch" },
7170
- args: { type: "object", description: "arguments object for the tool (per its schema)" }
7171
- }
7172
- },
7173
- async run({ name, args }) {
7174
- const n = String(name ?? "");
7175
- if (!byName.has(n)) return `Error: unknown MCP tool '${n}'. Use ToolSearch to find valid names.`;
7176
- const r = toResult(await callTool(n, args ?? {}));
7177
- return r.images?.length ? r : r.text;
6854
+ }
6855
+ /** Dead-air fallback pools (see ackIfSilent). Both retry lines keep the 'say that again' phrase —
6856
+ * hosts/tests key on it. */
6857
+ static FALLBACK_ACKS = ["Okay, on it.", "On it.", "Alright, working on it."];
6858
+ static FALLBACK_RETRY = ["Sorry, could you say that again?", "Hm, I missed that \u2014 could you say that again?"];
6859
+ lastFallback = "";
6860
+ /** One user turn: the voice agent streams the reply (and may Act/Think). Serialized with re-voice turns.
6861
+ * If a speculative reflex call is pending and this content CONFIRMS it (the final matches the
6862
+ * speculated partial), the in-flight call is adopted as THE turn: its buffered output flushes to the
6863
+ * host NOW (this is the latency win) and streaming continues live. Any other content aborts the
6864
+ * speculation first (rolled back silently) and runs a normal turn behind it. */
6865
+ send(content) {
6866
+ if (typeof content === "string" && isTrivialBarge(content) && this.hasParkedDelivery()) {
6867
+ if (this.spec) this.abortSpeculation();
6868
+ return this.enqueue(async () => {
6869
+ this.resetTurn();
6870
+ if (!this.redeliverParked()) this.awaitTrivialRedeliver = true;
6871
+ return { text: "", steps: 0, finishReason: "stop", messages: [] };
6872
+ });
7178
6873
  }
7179
- };
7180
- return [searchTool, callMcpTool];
7181
- }
7182
- function buildMcpCatalog(servers) {
7183
- const specs = [];
7184
- const routes = /* @__PURE__ */ new Map();
7185
- for (const m of servers) {
7186
- for (const s of m.specs) {
7187
- const base = `mcp__${m.name}__${s.name}`.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 128);
7188
- let display = base;
7189
- for (let i = 2; routes.has(display); i++) display = `${base.slice(0, 128 - String(i).length - 1)}_${i}`;
7190
- specs.push({ name: display, description: s.description, inputSchema: s.inputSchema });
7191
- routes.set(display, { server: m.name, rawName: s.name });
6874
+ const spec = this.spec;
6875
+ if (spec?.state === "pending") {
6876
+ if (typeof content === "string" && speculationConfirms(spec.text, content)) {
6877
+ spec.state = "confirmed";
6878
+ spec.finalText = content;
6879
+ for (const ev of spec.buf.splice(0)) this.options.host?.notify?.(ev);
6880
+ spec.decide("confirm");
6881
+ this.notify("diag", "speculation_confirmed", { text: spec.text.slice(0, 80) });
6882
+ return spec.done;
6883
+ }
6884
+ this.abortSpeculation();
7192
6885
  }
6886
+ return this.enqueue(async () => {
6887
+ await this.initMemory();
6888
+ this.resetTurn();
6889
+ this.awaitTrivialRedeliver = false;
6890
+ this.parkedRedeliver = [];
6891
+ this.suppressParkedResume = true;
6892
+ const res = await this.voice.send(content);
6893
+ this.flushHeldReflexTail();
6894
+ if (this.silentTurn) await this.ackIfSilent();
6895
+ return res;
6896
+ });
7193
6897
  }
7194
- return { specs, routes };
7195
- }
7196
- function searchOverCatalog(servers, specs, routes, resolve, options) {
7197
- const tools = specs.length ? makeMcpToolSearch(specs, (name, args) => {
7198
- const r = routes.get(name);
7199
- if (!r) throw new Error(`unknown MCP tool '${name}' \u2014 use ToolSearch to find valid names`);
7200
- return resolve(r.server, r.rawName, args ?? {});
7201
- }, options) : [];
7202
- return { tools, serverNames: servers, toolCount: specs.length };
7203
- }
7204
- function makeMcpToolSearchFromMounted(mounted, options) {
7205
- const { specs, routes } = buildMcpCatalog(mounted);
7206
- const byName = new Map(mounted.map((m) => [m.name, m]));
7207
- return searchOverCatalog(mounted.map((m) => m.name), specs, routes, (server, rawName, args) => byName.get(server).client.callTool(rawName, args), options);
7208
- }
7209
- function makeLazyMcpToolSearch(servers, resolve, options) {
7210
- const { specs, routes } = buildMcpCatalog(servers);
7211
- return searchOverCatalog(servers.map((s) => s.name), specs, routes, resolve, options);
7212
- }
7213
-
7214
- // src/hooks.ts
7215
- var RecordingHooks = class {
7216
- /** tool name -> reason; a matching preToolUse call is blocked with that reason. */
7217
- constructor(blocks = {}) {
7218
- this.blocks = blocks;
6898
+ /** Start a HELD speculative reflex turn on a stable partial (VoiceEngine.onSpeculate). Its spoken
6899
+ * output buffers in emitHost; send() later confirms (flush + adopt) or aborts it. The turn holds the
6900
+ * voice mutex until that decision (bounded by a safety timeout), so no other turn can interleave
6901
+ * into the transcript between the speculative messages and their rollback. No-op if a speculation
6902
+ * is already in flight. */
6903
+ speculate(text) {
6904
+ if (!text.trim() || this.spec) return;
6905
+ let decide;
6906
+ const decision = new Promise((r) => {
6907
+ decide = r;
6908
+ });
6909
+ const spec = {
6910
+ text,
6911
+ state: "pending",
6912
+ buf: [],
6913
+ ctl: new AbortController(),
6914
+ decide,
6915
+ decision,
6916
+ done: void 0
6917
+ };
6918
+ this.spec = spec;
6919
+ spec.done = this.enqueue(async () => {
6920
+ const empty = { text: "", steps: 0, finishReason: "aborted", messages: this.voice.transcript };
6921
+ if (spec.state === "aborted") {
6922
+ this.speculativeAbortedCalls++;
6923
+ if (this.spec === spec) this.spec = void 0;
6924
+ return empty;
6925
+ }
6926
+ await this.initMemory();
6927
+ this.resetTurn();
6928
+ const base = this.voice.transcript.length;
6929
+ const prevSignal = this.voice.options.signal;
6930
+ this.voice.options.signal = spec.ctl.signal;
6931
+ let res;
6932
+ try {
6933
+ res = await this.voice.send(spec.text);
6934
+ } catch (e) {
6935
+ log13.warn(`speculative turn failed: ${e instanceof Error ? e.message : e}`);
6936
+ } finally {
6937
+ this.voice.options.signal = prevSignal;
6938
+ }
6939
+ const timer = setTimeout(() => {
6940
+ spec.state = spec.state === "pending" ? "aborted" : spec.state;
6941
+ spec.decide("abort");
6942
+ }, 1e4);
6943
+ timer.unref?.();
6944
+ const d = await spec.decision;
6945
+ clearTimeout(timer);
6946
+ if (d === "abort") {
6947
+ if (this.voice.transcript.length > base) this.voice.transcript.length = base;
6948
+ this.speculativeAbortedCalls++;
6949
+ log13.verbose(`speculation aborted (${this.speculativeAbortedCalls} total): "${spec.text.slice(0, 50)}"`);
6950
+ if (this.spec === spec) this.spec = void 0;
6951
+ return res ?? empty;
6952
+ }
6953
+ for (let i = base; i < this.voice.transcript.length; i++) {
6954
+ const m = this.voice.transcript[i];
6955
+ if (m.role === "user" && contentText(m.content) === spec.text) {
6956
+ m.content = spec.finalText;
6957
+ break;
6958
+ }
6959
+ }
6960
+ this.spec = void 0;
6961
+ this.flushHeldReflexTail();
6962
+ if (this.silentTurn) await this.ackIfSilent();
6963
+ return res ?? empty;
6964
+ });
7219
6965
  }
7220
- blocks;
7221
- pre = [];
7222
- post = [];
7223
- outputs = [];
7224
- stops = [];
7225
- preToolUse(call, meta) {
7226
- this.pre.push({ call, meta });
7227
- const reason = this.blocks[call.name];
7228
- if (reason != null) return { block: true, reason };
6966
+ /** Abort a pending speculation (idempotent): kill the in-flight call, drop its buffered output.
6967
+ * Called on divergence (send), a stale partial (VoiceEngine.onSpeculateAbort), a side-effect tool
6968
+ * attempt (dispatchGuard), or host paths that will never dispatch a final (commands, voice-off). */
6969
+ abortSpeculation() {
6970
+ const spec = this.spec;
6971
+ if (spec?.state !== "pending") return;
6972
+ spec.state = "aborted";
6973
+ spec.buf.length = 0;
6974
+ spec.ctl.abort();
6975
+ spec.decide("abort");
6976
+ this.notify("diag", "speculation_aborted", { text: spec.text.slice(0, 80) });
7229
6977
  }
7230
- postToolUse(call, result, meta) {
7231
- this.post.push({ call, result, meta });
6978
+ /** Cancel a running background task — shared by the CancelTask tool and the CLI /tasks picker. */
6979
+ cancelTask(id) {
6980
+ const rec = this.tasks.get(id);
6981
+ if (!rec) return `No task '${id}'.`;
6982
+ if (rec.status !== "running") return `Task ${rec.id} is already ${rec.status}.`;
6983
+ rec.status = "cancelled";
6984
+ rec.controller.abort();
6985
+ return `Task ${rec.id} (${rec.label}) cancelled.`;
7232
6986
  }
7233
- onToolOutput(call, chunk, meta) {
7234
- this.outputs.push({ call, chunk, meta });
6987
+ /** Barge-in: the user took the floor while task(s) were running. Suppress those tasks' remaining SPOKEN
6988
+ * delivery so a superseded topic never talks over the new one (the debt-after-jokes regression). The
6989
+ * tasks keep running and still fold their result into the transcript — recoverable, just not spoken.
6990
+ * Returns the parked ids (for logging). Does NOT cancel: that's a deliberate reflex/user action. */
6991
+ parkInFlightDeliveries() {
6992
+ this.suppressParkedResume = false;
6993
+ const parked = [];
6994
+ for (const rec of this.tasks.values())
6995
+ if (rec.status === "running" && !rec.deliveryParked) {
6996
+ rec.deliveryParked = true;
6997
+ parked.push(rec.id);
6998
+ }
6999
+ return parked;
7235
7000
  }
7236
- onStop(finalText) {
7237
- this.stops.push(finalText);
7001
+ /** True while there is a parked delivery to potentially resume: either one already settled (queued) or
7002
+ * one still running that was parked by a barge. */
7003
+ hasParkedDelivery() {
7004
+ return this.parkedRedeliver.length > 0 || [...this.tasks.values()].some((t) => t.status === "running" && t.deliveryParked);
7238
7005
  }
7239
- };
7240
- var RecordingLifecycle = class {
7241
- /** @param startContext injected at session start; @param rewrite maps a submitted prompt to a new one. */
7242
- constructor(startContext, rewrite) {
7243
- this.startContext = startContext;
7244
- this.rewrite = rewrite;
7006
+ /** Speak any settled-and-queued parked delivery now (trivial-barge resume). Returns false if nothing was
7007
+ * queued yet (the caller then arms awaitTrivialRedeliver so the task resumes the instant it settles). */
7008
+ redeliverParked() {
7009
+ if (!this.parkedRedeliver.length) return false;
7010
+ const text = this.parkedRedeliver.splice(0).join(" ").trim();
7011
+ if (text) {
7012
+ this.options.host?.notify?.({ kind: "speak_utterance", message: text });
7013
+ this.notify("diag", "parked_redelivered", { chars: text.length });
7014
+ }
7015
+ return true;
7245
7016
  }
7246
- startContext;
7247
- rewrite;
7248
- starts = 0;
7249
- prompts = [];
7250
- compactions = [];
7251
- subagentStops = [];
7252
- onSessionStart() {
7253
- this.starts++;
7254
- return this.startContext;
7017
+ /** Resolve when all queued voice turns AND all in-flight worker tasks have settled (tests, graceful shutdown). */
7018
+ async idle() {
7019
+ while (true) {
7020
+ const q = this.queue;
7021
+ await q.catch(() => {
7022
+ });
7023
+ await Promise.all([...this.tasks.values()].map((t) => t.promise));
7024
+ if (this.queue === q && ![...this.tasks.values()].some((t) => t.status === "running")) return;
7025
+ }
7255
7026
  }
7256
- onUserPromptSubmit(text) {
7257
- this.prompts.push(text);
7258
- return this.rewrite?.(text);
7027
+ /** Promise-chain mutex: turns run strictly one at a time; a failed turn doesn't poison the chain. */
7028
+ enqueue(fn) {
7029
+ const run = this.queue.then(fn, fn);
7030
+ this.queue = run.then(() => {
7031
+ }, () => {
7032
+ });
7033
+ return run;
7259
7034
  }
7260
- onPreCompact(messages) {
7261
- this.compactions.push(messages.length);
7035
+ notify(kind, message, data) {
7036
+ this.emitHost({ kind, message, data });
7262
7037
  }
7263
- onSubagentStop(summary, info) {
7264
- this.subagentStops.push({ summary, label: info?.label });
7038
+ /** Host-boundary emit for the reflex's spoken channel: during a PENDING speculation, text_delta and
7039
+ * hold_filler are BUFFERED (nothing may reach TTS on unconfirmed input); confirm flushes them in
7040
+ * order, abort drops them silently. Everything else (task_* lifecycle, worker speak_utterance —
7041
+ * which bypasses this via host.notify directly) passes through untouched. */
7042
+ emitHost(ev) {
7043
+ const spec = this.spec;
7044
+ if (spec && (ev.kind === "text_delta" || ev.kind === "hold_filler")) {
7045
+ if (spec.state === "pending") {
7046
+ spec.buf.push(ev);
7047
+ return;
7048
+ }
7049
+ if (spec.state === "aborted") return;
7050
+ }
7051
+ this.options.host?.notify?.(ev);
7265
7052
  }
7266
- };
7267
-
7268
- // src/index.ts
7269
- init_logging();
7053
+ /** Queue a `[task …]` event for re-voicing. Events arriving while the voice is busy coalesce into ONE turn.
7054
+ * `nonClean` (out-of-band boolean, set by the caller that KNOWS this event integrates a NON-CLEAN outcome)
7055
+ * marks the coalesced flush as a non-clean integration turn — turn-eligibility, never inferred from event
7056
+ * text and never keyed on a (re-authored) brief string. Any dispatch in such a turn is a follow-up. */
7057
+ queueRevoice(event, nonClean = false) {
7058
+ this.pendingEvents.push(event);
7059
+ if (nonClean) this.pendingNonClean = true;
7060
+ if (this.flushQueued) return;
7061
+ this.flushQueued = true;
7062
+ void this.enqueue(async () => {
7063
+ this.flushQueued = false;
7064
+ const events = this.pendingEvents.splice(0);
7065
+ const nonCleanTurn = this.pendingNonClean;
7066
+ this.pendingNonClean = false;
7067
+ if (!events.length) return;
7068
+ const failed = events.find((e) => /^\[task\b[^\]\n]*\bfailed\b/i.test(e));
7069
+ this.resetTurn();
7070
+ this.turnFollowUp = nonCleanTurn;
7071
+ await this.voice.send(events.join("\n"));
7072
+ this.flushHeldReflexTail();
7073
+ if (this.silentTurn) await this.ackIfSilent(failed ? "Sorry, that didn't work \u2014 the task failed." : void 0);
7074
+ this.notify("revoice_done", "");
7075
+ });
7076
+ }
7077
+ /** The worker's brief: the Act/Think args + a STATIC text snapshot of the recent conversation.
7078
+ * Act briefs get a self-verify footer — the worker's report is trusted without review, so it
7079
+ * must check its own work before reporting (nearly free under prompt caching; measured honest:
7080
+ * it does NOT fix one-shot logic bugs — see mind/10). Think tasks are pure reasoning — no footer. */
7081
+ buildBrief(brief, tier = "act", deliver = true) {
7082
+ const recent = this.voice.transcript.filter((m) => (m.role === "user" || m.role === "assistant") && contentText(m.content).trim()).slice(-this.options.excerptTurns).map((m) => `${m.role}: ${contentText(m.content)}`).join("\n");
7083
+ const verify = tier === "act" ? "\n\nBefore reporting done: re-read what you changed and check it against EVERY requirement above \u2014 fix any gap first. Your report is trusted without review." : "";
7084
+ const deliverContract = deliver ? `
7270
7085
 
7271
- // src/voice/soniox.ts
7272
- init_logging();
7086
+ ## DELIVER (spoken delivery)
7087
+ You are reporting back to a user who is LISTENING. Stream your work normally \u2014 your prose is the written work record and detail, and is NOT spoken. Wrap anything the user should HEAR in <spoken>\u2026</spoken> tags. LEAD WITH the actual content they asked for: if they asked for a specific piece of content \u2014 a value, a name, the actual lines, the writing itself \u2014 that content goes INSIDE the <spoken> tags, not a remark about it. Your FIRST <spoken> segment is substantive \u2014 never a greeting or an acknowledgement (the front-end has already acked; do not double-ack). Keep spoken text concise and natural for the ear: short sentences, no markdown. NEVER enumerate in speech \u2014 no numbered or bulleted lists ("One. \u2026 Two. \u2026" is robotic). Deliver multiple items as flowing conversation with brief connective phrasing ("here's one\u2026", "and another\u2026", "oh, and\u2026"), pausing between items with sentence breaks, not numbers.` + (this.options.emotionTags ? " Inside <spoken>, you may prefix a sentence with an inline [emotion] tag (e.g. [excited], [curious]) to color how it is voiced \u2014 only when it genuinely fits, and vary it; [laughter] gives a natural laugh." : "") : "";
7088
+ return `${nowLine()}.
7273
7089
 
7274
- // src/voice/types.ts
7275
- var STT_SAMPLE_RATE = 16e3;
7276
- var TTS_SAMPLE_RATE = 44100;
7277
- async function resolveAuth(auth) {
7278
- return typeof auth === "function" ? await auth() : auth;
7279
- }
7090
+ ` + (recent ? `${brief}
7280
7091
 
7281
- // src/voice/soniox.ts
7282
- var log12 = forComponent("SonioxSTT");
7283
- var now = () => performance.now();
7284
- var SonioxSTTOptions = class {
7285
- auth = "";
7286
- source;
7287
- model = "stt-rt-preview";
7288
- languageHints = ["en"];
7289
- /** Client-side endpoint: finalized text + no new tokens for this long = utterance (don't wait for
7290
- * Soniox's semantic <end>, which adds 0.5-1.5s — the difference between ping-pong and lag). */
7291
- silenceEndpointMs = 500;
7292
- /** No-audio watchdog: if the mic source stops delivering chunks for this long, capture is dead →
7293
- * fire onFatal + stop (else Soniox idle-timeouts and reconnect-loops forever). 0 = disable. */
7294
- noAudioTimeoutMs = 1e4;
7295
- };
7296
- var SonioxSTT = class {
7297
- options;
7298
- ws;
7299
- stopped = false;
7300
- sourceStarted = false;
7301
- onPartial = () => {
7302
- };
7303
- onUtterance = () => {
7304
- };
7305
- /** mic energy (RMS) per chunk — drives the energy-based heuristic barge-in tier */
7306
- onLevel = () => {
7307
- };
7308
- /** Unrecoverable: the mic source stopped delivering audio (Soniox starves → idle-timeout reconnect
7309
- * loop). The host tears voice down instead of spinning forever. */
7310
- onFatal = () => {
7311
- };
7312
- /** Diagnostic tap (provider errors, ws reconnects, no-audio watchdog). Fire-and-forget: a throwing
7313
- * handler disables itself — never affects transcription. Wired by VoiceIO / the lab bridge. */
7314
- onDiag = () => {
7315
- };
7316
- diagOn = true;
7317
- diag(kind, fields) {
7318
- if (!this.diagOn) return;
7319
- try {
7320
- this.onDiag({ t: now(), kind, ...fields });
7321
- } catch (e) {
7322
- this.diagOn = false;
7323
- log12.debug(`onDiag threw \u2014 STT diagnostics disabled: ${e instanceof Error ? e.message : e}`);
7324
- }
7325
- }
7326
- lastChunkAt = 0;
7327
- // timestamp of the most recent mic chunk (0 = none yet)
7328
- startedChunksAt = 0;
7329
- // when capture started (grace before the first chunk)
7330
- noAudioTimer = null;
7331
- finalText = "";
7332
- partialText = "";
7333
- lastChangeAt = 0;
7334
- lastCombined = "";
7335
- endpointTimer = null;
7336
- firstTokenAt = 0;
7337
- // first speech token in current utterance
7338
- constructor(options) {
7339
- this.options = { ...new SonioxSTTOptions(), ...options };
7092
+ ## Recent conversation (for context)
7093
+ ${recent}` : brief) + verify + deliverContract;
7340
7094
  }
7341
- get usingAec() {
7342
- return this.options.source?.aec ?? false;
7095
+ /** Spawn a detached worker for task `id`; its settlement notifies + enqueues the re-voice turn. */
7096
+ spawnWorker(id, label, briefText, tier, brief, followUp) {
7097
+ const o = this.options;
7098
+ const tierOpts = tier === "think" ? o.thinkOptions : o.actOptions;
7099
+ const tierModel = tier === "think" ? o.thinkModel : o.actModel;
7100
+ const controller = new AbortController();
7101
+ const base = tierOpts?.hooks ?? o.actOptions?.hooks;
7102
+ const report = o.progressUpdates ? this.progressReporter(id) : void 0;
7103
+ const tail = [];
7104
+ const pushTail = (line) => {
7105
+ tail.push(line.slice(0, 200));
7106
+ if (tail.length > 120) tail.splice(0, tail.length - 120);
7107
+ };
7108
+ const hooks = {
7109
+ ...base,
7110
+ preToolUse: async (call, meta) => {
7111
+ const d = await base?.preToolUse?.(call, meta);
7112
+ pushTail(`\u2699 ${describeCall(call)}`);
7113
+ report?.pre(call);
7114
+ return d;
7115
+ },
7116
+ postToolUse: async (call, result, meta) => {
7117
+ await base?.postToolUse?.(call, result, meta);
7118
+ const last = result?.trim().split("\n").filter(Boolean).pop();
7119
+ if (last) pushTail(` \u21B3 ${last}`);
7120
+ report?.post(call);
7121
+ },
7122
+ onToolOutput: (call, chunk, meta) => {
7123
+ base?.onToolOutput?.(call, chunk, meta);
7124
+ report?.output(chunk);
7125
+ }
7126
+ };
7127
+ const relayAsk = async (q) => {
7128
+ const opts = q.options?.length ? ` Options: ${q.options.map((x) => x.label).join(", ")}.` : "";
7129
+ const a = await this.parkQuestion(id, `${q.question}${opts}`);
7130
+ return a || "(no answer from the user \u2014 use your best judgment and note the assumption)";
7131
+ };
7132
+ const splitter = new SpokenSplitter();
7133
+ const speak = (seg) => {
7134
+ if (!seg) return;
7135
+ const r = this.tasks.get(id);
7136
+ if (r) r.spokenText = (r.spokenText ? r.spokenText + " " : "") + seg;
7137
+ if (!r?.deliveryParked) o.host?.notify?.({ kind: "speak_utterance", message: seg });
7138
+ };
7139
+ const coalescer = new SentenceCoalescer();
7140
+ const feedSpoken = (s) => {
7141
+ const ready = coalescer.feed(s);
7142
+ if (ready) speak(ready);
7143
+ };
7144
+ const flushSpoken = () => speak(coalescer.flush());
7145
+ const askBridge = o.askRelay ? { ask: relayAsk } : o.host?.ask ? { ask: (q) => o.host.ask(q) } : {};
7146
+ const workerHost = {
7147
+ ...askBridge,
7148
+ notify: (ev) => {
7149
+ if (ev?.kind === "text_delta" && typeof ev.message === "string") {
7150
+ const { spoken, detail } = splitter.feed(ev.message);
7151
+ feedSpoken(spoken);
7152
+ if (detail.trim()) pushTail(detail.trim());
7153
+ return;
7154
+ }
7155
+ }
7156
+ };
7157
+ const agentOpts = {
7158
+ ai: o.ai,
7159
+ fs: o.fs,
7160
+ model: tierModel,
7161
+ ...tier === "think" ? { reasoning: tierOpts?.reasoning ?? "high" } : {},
7162
+ ...tierOpts,
7163
+ // Recompute providerOptions for THIS worker's model (after tierOpts so it wins over any inherited
7164
+ // main-template value) — prevents cursor-only cwd/cursorSession leaking onto an anthropic worker.
7165
+ providerOptions: o.providerOptionsFor?.(tierModel),
7166
+ stream: true,
7167
+ // worker streams text_delta so the splitter can extract <spoken> live (after tierOpts: never overridden off)
7168
+ host: workerHost,
7169
+ // carries BOTH ask AND the <spoken>-splitting notify
7170
+ ...hooks ? { hooks } : {},
7171
+ signal: controller.signal
7172
+ // shared with the checker so a cancel tears down both
7173
+ };
7174
+ const promise = new Agent(agentOpts).run(briefText).then((res) => {
7175
+ const { spoken, detail } = splitter.flush();
7176
+ feedSpoken(spoken);
7177
+ if (detail.trim()) pushTail(detail.trim());
7178
+ flushSpoken();
7179
+ return res;
7180
+ }).then((res) => this.maybeVerify(id, brief, res, tier, agentOpts, askBridge)).then((res) => this.onWorkerSettled(id, res)).catch((err) => this.onWorkerFailed(id, err));
7181
+ this.tasks.set(id, { id, label, status: "running", controller, promise, tail, brief, followUp, splitter });
7182
+ if (this.tasks.size > this.options.maxTaskRecords)
7183
+ for (const [tid, rec] of this.tasks) {
7184
+ if (this.tasks.size <= this.options.maxTaskRecords) break;
7185
+ if (rec.status !== "running") this.tasks.delete(tid);
7186
+ }
7343
7187
  }
7344
- async connectWs() {
7345
- const apiKey = await resolveAuth(this.options.auth);
7346
- this.ws = new WebSocket("wss://stt-rt.soniox.com/transcribe-websocket");
7347
- await new Promise((res, rej) => {
7348
- this.ws.onopen = () => res();
7349
- this.ws.onerror = (e) => rej(new Error(`soniox ws: ${e.message || "connect failed"}`));
7350
- });
7351
- this.ws.send(
7352
- JSON.stringify({
7353
- api_key: apiKey,
7354
- model: this.options.model,
7355
- audio_format: "pcm_s16le",
7356
- sample_rate: STT_SAMPLE_RATE,
7357
- num_channels: 1,
7358
- language_hints: this.options.languageHints,
7359
- enable_endpoint_detection: true
7360
- })
7361
- );
7362
- this.ws.onmessage = (ev) => this.handle(JSON.parse(String(ev.data)));
7363
- this.ws.onclose = (ev) => {
7364
- if (this.stopped) return;
7365
- log12.warn(`soniox ws closed (${ev.code} ${ev.reason || ""}) \u2014 reconnecting`);
7366
- this.diag("stt_ws_closed", { code: ev.code, reason: String(ev.reason || ""), reconnecting: true });
7367
- this.reset();
7368
- this.connectWs().catch((e) => {
7369
- log12.error(`soniox reconnect failed: ${e.message}`);
7370
- this.diag("stt_reconnect_failed", { message: e.message });
7371
- });
7188
+ /** Fresh-context check of a successful Act task: a NEW agent (same model/fs/tools, but NO shared
7189
+ * conversation context) re-reads the file state against the brief and fixes any gap. The fix lands
7190
+ * on the shared fs automatically (workers write fs directly, no overlay), so grading sees the
7191
+ * corrected state. Bounded to ONE pass. Off unless `verifyActTasks`; never runs for think/failed/
7192
+ * cancelled tasks. Usage is merged so /cost reflects the real (worker + checker) spend. */
7193
+ async maybeVerify(id, brief, res, tier, agentOpts, askBridge) {
7194
+ if (!this.options.verifyActTasks || tier !== "act" || res.finishReason !== "stop") return res;
7195
+ if (this.tasks.get(id)?.status === "cancelled") return res;
7196
+ const { stream: _stream, host: _host, ...restOpts } = agentOpts;
7197
+ const checkerOpts = {
7198
+ ...restOpts,
7199
+ ...askBridge.ask ? { host: { ask: askBridge.ask } } : {}
7372
7200
  };
7373
- }
7374
- async start() {
7375
- await this.connectWs();
7376
- if (this.sourceStarted) return;
7377
- this.sourceStarted = true;
7378
- this.endpointTimer = setInterval(() => {
7379
- const combined = (this.finalText + this.partialText).trim();
7380
- if (!combined || now() - this.lastChangeAt < this.options.silenceEndpointMs) return;
7381
- if (this.firstTokenAt) log12.debug(`stt: ${Math.round(now() - this.firstTokenAt)}ms first-token\u2192silence-endpoint, "${combined.slice(0, 60)}"`);
7382
- this.reset();
7383
- this.onUtterance(combined, now());
7384
- }, 120);
7385
- this.endpointTimer.unref?.();
7386
- this.startedChunksAt = now();
7387
- const noAudioMs = this.options.noAudioTimeoutMs;
7388
- if (noAudioMs > 0) {
7389
- this.noAudioTimer = setInterval(() => {
7390
- if (this.stopped) return;
7391
- const ref = this.lastChunkAt || this.startedChunksAt;
7392
- if (now() - ref > noAudioMs) {
7393
- log12.error(`stt: no mic audio for >${Math.round(noAudioMs / 1e3)}s \u2014 capture device stopped delivering`);
7394
- this.diag("stt_watchdog_fatal", { noAudioMs });
7395
- this.onFatal("microphone stopped delivering audio (try a different input device, e.g. AirPods, or check System Settings \u2192 Sound \u2192 Input)");
7396
- this.stop();
7397
- }
7398
- }, Math.max(250, Math.min(2e3, noAudioMs / 4)));
7399
- this.noAudioTimer.unref?.();
7201
+ const checkBrief = `${this.buildBrief(brief, tier, false)}
7202
+
7203
+ ## VERIFY MODE
7204
+ Another agent just implemented the above. Independently check the CURRENT state of the files against EVERY requirement. Fix any gap you find. If everything is already correct, make NO changes \u2014 do not refactor or improve \u2014 and report "verified".`;
7205
+ this.notify("task_verify", `task ${id}: verifying`, { id });
7206
+ const cres = await new Agent(checkerOpts).run(checkBrief);
7207
+ if (cres.finishReason !== "stop") {
7208
+ log13.warn(`task ${id}: verify inconclusive (${cres.finishReason})`);
7209
+ this.notify("task_verify", `task ${id}: verify inconclusive (${cres.finishReason})`, { id, finishReason: cres.finishReason });
7400
7210
  }
7401
- await this.options.source.start((chunk) => {
7402
- this.lastChunkAt = now();
7403
- let sum = 0;
7404
- const view = new DataView(chunk.buffer, chunk.byteOffset, chunk.byteLength);
7405
- for (let i = 0; i + 1 < chunk.byteLength; i += 2) {
7406
- const v = view.getInt16(i, true);
7407
- sum += v * v;
7211
+ const sum = (a = 0, b = 0) => a + b;
7212
+ return {
7213
+ ...res,
7214
+ steps: res.steps + cres.steps,
7215
+ // Merge the checker's messages so downstream tool-call/step accounting includes BOTH agents
7216
+ // (else a verified task's toolCalls would undercount vs its steps/usage).
7217
+ messages: [...res.messages, ...cres.messages],
7218
+ usageEstimated: res.usageEstimated || cres.usageEstimated,
7219
+ usage: res.usage && cres.usage ? {
7220
+ promptTokens: sum(res.usage.promptTokens, cres.usage.promptTokens),
7221
+ completionTokens: sum(res.usage.completionTokens, cres.usage.completionTokens),
7222
+ totalTokens: sum(res.usage.totalTokens, cres.usage.totalTokens),
7223
+ cacheCreationTokens: sum(res.usage.cacheCreationTokens, cres.usage.cacheCreationTokens),
7224
+ cacheReadTokens: sum(res.usage.cacheReadTokens, cres.usage.cacheReadTokens)
7225
+ } : res.usage ?? cres.usage
7226
+ };
7227
+ }
7228
+ /** Throttled per-task progress: worker tool calls → at most one progress re-voice per interval.
7229
+ * Two sources, one throttle: completed steps (post) and a heartbeat for a SINGLE long tool call
7230
+ * (pre records the in-flight call; a self-cleaning timer narrates "still inside Bash — 70s").
7231
+ * Completion supersedes: nothing is emitted once the task has settled. */
7232
+ progressReporter(id) {
7233
+ let lastAt = Date.now();
7234
+ let steps = 0;
7235
+ let inflight = null;
7236
+ const due = () => {
7237
+ if (this.pendingAsks.size) return void 0;
7238
+ const rec = this.tasks.get(id);
7239
+ return rec && rec.status === "running" && Date.now() - lastAt >= this.options.progressIntervalMs ? rec : void 0;
7240
+ };
7241
+ const emit = (rec, line, call) => {
7242
+ lastAt = Date.now();
7243
+ this.notify("task_progress", `task ${id} (${rec.label}): ${line}`, { id, steps, call: call.name });
7244
+ this.queueRevoice(`[task ${id} progress] ${line}`);
7245
+ };
7246
+ const timer = setInterval(() => {
7247
+ const rec = this.tasks.get(id);
7248
+ if (!rec || rec.status !== "running") return clearInterval(timer);
7249
+ if (!inflight || !due()) return;
7250
+ const last = inflight.tail.trim().split("\n").filter(Boolean).pop()?.slice(-80);
7251
+ emit(rec, `still inside ${describeCall(inflight.call)} \u2014 ${Math.round((Date.now() - inflight.at) / 1e3)}s on this step${last ? `, last output: ${last}` : ""}`, inflight.call);
7252
+ }, Math.max(this.options.progressIntervalMs, 250));
7253
+ timer.unref?.();
7254
+ return {
7255
+ pre: (call) => {
7256
+ inflight = { call, at: Date.now(), tail: "" };
7257
+ },
7258
+ output: (chunk) => {
7259
+ if (inflight) inflight.tail = (inflight.tail + chunk).slice(-500);
7260
+ },
7261
+ // digest only — NEVER re-voices directly
7262
+ post: (call) => {
7263
+ steps++;
7264
+ inflight = null;
7265
+ const rec = due();
7266
+ if (rec) emit(rec, `still running \u2014 ${steps} steps so far, now: ${describeCall(call)}`, call);
7408
7267
  }
7409
- this.onLevel(Math.sqrt(sum / (chunk.byteLength / 2)));
7410
- if (this.ws.readyState === WebSocket.OPEN) this.ws.send(chunk);
7268
+ };
7269
+ }
7270
+ /** Park a question under `askId` (a task id, or any unique key for permission asks): re-voices
7271
+ * '[task <id> asks] …' and resolves with the user's answer via AnswerTask — or '' on timeout/
7272
+ * task settle (callers map '' to deny / best-judgment). Workers never block forever. */
7273
+ parkQuestion(askId, question) {
7274
+ return new Promise((resolve) => {
7275
+ let settled = false;
7276
+ const finish = (answer) => {
7277
+ if (settled) return;
7278
+ settled = true;
7279
+ clearTimeout(timer);
7280
+ this.pendingAsks.delete(askId);
7281
+ resolve(answer);
7282
+ };
7283
+ const timer = setTimeout(() => {
7284
+ this.notify("task_ask_timeout", `task ${askId}: question timed out \u2014 proceeding without an answer`);
7285
+ finish("");
7286
+ }, this.options.askTimeoutMs);
7287
+ this.pendingAsks.set(askId, { question, resolve: finish });
7288
+ this.notify("task_ask", `task ${askId} asks: ${question}`, { id: askId, question });
7289
+ this.queueRevoice(`[task ${askId} asks] ${question}
7290
+ (Relay this to the user in your own words. When they answer, call AnswerTask with id "${askId}" and their answer.)`);
7411
7291
  });
7412
7292
  }
7413
- handle(m) {
7414
- if (m.error_message) {
7415
- this.diag("stt_error", { message: String(m.error_message), code: m.error_code });
7416
- return log12.error(`soniox: ${m.error_message}`);
7417
- }
7418
- let endpoint = false;
7419
- for (const t of m.tokens ?? []) {
7420
- if (t.text === "<end>") endpoint = true;
7421
- else if (t.is_final) this.finalText += t.text;
7293
+ /** Resolve any question a settling/cancelled task left parked (its answer can no longer matter). */
7294
+ dropAsk(id) {
7295
+ this.pendingAsks.get(id)?.resolve("");
7296
+ }
7297
+ /** Build the INTEGRATION TURN prompt for a NON-CLEAN settled worker (early stop / failure). A clean
7298
+ * success never reaches here — it streams its own `<spoken>` delivery during the run. For a partial
7299
+ * or failed result the outcome re-enters the reflex as a decision (like a tool_result flowing back
7300
+ * into a normal agent loop): the reflex evaluates the outcome against the original intent and chooses
7301
+ * what to do next.
7302
+ *
7303
+ * Decision branches (the reflex acts on them with EXISTING tools — no new surface):
7304
+ * • accept → SPEAK the (partial) result plainly — don't dress a failure up as success.
7305
+ * • escalate → call `Think` with the SAME brief — only when Act failed/stalled AND a Think tier
7306
+ * exists AND this task wasn't already a follow-up (one hop max). Wires the dead
7307
+ * "Reserve Think for a problem Act already FAILED at" promise.
7308
+ * • re-delegate→ call `Act` with a CORRECTED brief — for a recoverable error / partial result.
7309
+ * • ask → ask the user ONE concrete question if genuinely blocked.
7310
+ *
7311
+ * Keeps the `[task <id> completed]` / `[task <id> failed]` opener so existing coalescing + the
7312
+ * failed-revoice fallback still fire, and the per-event transcript markers stay intact. */
7313
+ integrationPrompt(rec, outcome, body, finishReason) {
7314
+ const opener = outcome === "error" ? `[task ${rec.id} failed]` : `[task ${rec.id} completed]`;
7315
+ const underCap = this.autoEscalations < _DuplexAgent.MAX_AUTO_ESCALATIONS;
7316
+ const canEscalate = (outcome === "error" || outcome === "incomplete") && underCap;
7317
+ const hasThink = this.options.thinkModel !== false;
7318
+ const options = [];
7319
+ if (!rec.followUp && canEscalate && hasThink)
7320
+ options.push("ESCALATE to the Think tier (call Think with the same brief) if this is a hard/architectural problem the Act worker stalled or failed on");
7321
+ if (!rec.followUp && canEscalate)
7322
+ options.push("RE-DELEGATE to Act with a corrected brief if the failure looks recoverable (a wrong path, a fixable mistake)");
7323
+ options.push("ASK the user one short, concrete question if you genuinely cannot proceed without their input");
7324
+ options.push("ACCEPT and tell the user plainly what happened (don't dress a failure up as success)");
7325
+ const decision = options.length > 1 ? ` You must decide what to do next \u2014 choose ONE: ${options.map((o, i) => `(${i + 1}) ${o}`).join("; ")}. Pick exactly one and act on it; do not voice this as a finished success.` : ` Tell the user plainly what happened \u2014 do not present this as a finished success.`;
7326
+ const state = outcome === "error" ? `the worker FAILED with: ${body}` : `the worker STOPPED EARLY (${finishReason}) \u2014 its result is PARTIAL, not a finished success: ${body}`;
7327
+ return `${opener} Original request: "${rec.brief}". Outcome: ${state}.${decision}`;
7328
+ }
7329
+ onWorkerSettled(id, res) {
7330
+ this.dropAsk(id);
7331
+ const rec = this.tasks.get(id);
7332
+ if (res.finishReason === "aborted" || rec.status === "cancelled") {
7333
+ rec.status = "cancelled";
7334
+ this.notify("task_cancelled", `task ${id} (${rec.label}) cancelled`);
7335
+ return;
7422
7336
  }
7423
- this.partialText = (m.tokens ?? []).filter((t) => !t.is_final && t.text !== "<end>").map((t) => t.text).join("");
7424
- const combined = this.finalText + this.partialText;
7425
- if (combined !== this.lastCombined) {
7426
- this.lastCombined = combined;
7427
- this.lastChangeAt = now();
7428
- if (!this.firstTokenAt && combined.trim()) this.firstTokenAt = now();
7337
+ if (res.finishReason === "error") {
7338
+ const msg = res.error instanceof Error ? res.error.message : String(res.error ?? "unknown error");
7339
+ return this.failTask(rec, msg);
7429
7340
  }
7430
- this.onPartial(combined);
7431
- if (endpoint && this.finalText.trim()) {
7432
- const utterance = this.finalText.trim();
7433
- if (this.firstTokenAt) log12.debug(`stt: ${Math.round(now() - this.firstTokenAt)}ms first-token\u2192endpoint, "${utterance.slice(0, 60)}"`);
7434
- this.reset();
7435
- this.onUtterance(utterance, now());
7341
+ rec.status = "done";
7342
+ rec.result = res.text;
7343
+ const incomplete = res.finishReason !== "stop";
7344
+ log13.verbose(`task ${id} done (${res.steps} steps${incomplete ? `, INCOMPLETE: ${res.finishReason}` : ""})`);
7345
+ this.notify("task_done", `task ${id} (${rec.label}) completed`, {
7346
+ id,
7347
+ text: res.text,
7348
+ usage: res.usage,
7349
+ usageEstimated: res.usageEstimated,
7350
+ finishReason: res.finishReason,
7351
+ steps: res.steps,
7352
+ toolCalls: res.messages.filter((m) => m.role === "tool").length
7353
+ });
7354
+ if (incomplete) {
7355
+ return this.queueRevoice(this.integrationPrompt(rec, "incomplete", res.text, res.finishReason), true);
7436
7356
  }
7437
- }
7438
- reset() {
7439
- this.finalText = "";
7440
- this.partialText = "";
7441
- this.lastCombined = "";
7442
- this.firstTokenAt = 0;
7443
- }
7444
- stop() {
7445
- this.stopped = true;
7446
- if (this.endpointTimer) clearInterval(this.endpointTimer);
7447
- if (this.noAudioTimer) clearInterval(this.noAudioTimer);
7448
- this.options.source?.stop();
7449
- if (this.ws) this.ws.onclose = null;
7450
- this.ws?.close();
7451
- }
7452
- };
7453
-
7454
- // src/voice/cartesia.ts
7455
- init_logging();
7456
- var log13 = forComponent("CartesiaTTS");
7457
- var now2 = () => performance.now();
7458
- var CartesiaTTSOptions = class {
7459
- auth = "";
7460
- voiceId = "";
7461
- model = "sonic-3.5";
7462
- /** 'apiKey' (server/CLI) → `api_key=` URL param; 'token' (browser, BE-minted) → `access_token=`. */
7463
- authMode = "apiKey";
7464
- };
7465
- var CartesiaTTS = class _CartesiaTTS {
7466
- options;
7467
- ws;
7468
- ctxSeq = 0;
7469
- ctxId = "";
7470
- onAudio = () => {
7471
- };
7472
- onDone = () => {
7473
- };
7474
- /** Word-level timestamps for karaoke reveal: `start[i]` = seconds from turn-audio start (absolute
7475
- * across continuation chunks). Fired only when a consumer opts into reveal (see `wantTimestamps`). */
7476
- onTimestamps = () => {
7477
- };
7478
- /** Request `add_timestamps` from Cartesia. Off by default (saves bandwidth) — the engine sets it
7479
- * when revealMode==='word'. */
7480
- wantTimestamps = false;
7481
- /** Diagnostic tap (provider errors, circuit-breaker open/close, ws reconnects). Fire-and-forget:
7482
- * a throwing handler disables itself — never affects synthesis. Wired by VoiceIO / the lab bridge. */
7483
- onDiag = () => {
7484
- };
7485
- diagOn = true;
7486
- diag(kind, fields) {
7487
- if (!this.diagOn) return;
7488
- try {
7489
- this.onDiag({ t: now2(), kind, ...fields });
7490
- } catch (e) {
7491
- this.diagOn = false;
7492
- log13.debug(`onDiag threw \u2014 TTS diagnostics disabled: ${e instanceof Error ? e.message : e}`);
7357
+ const tail = rec.splitter?.flush();
7358
+ if (tail?.spoken && !rec.deliveryParked) this.options.host?.notify?.({ kind: "speak_utterance", message: tail.spoken });
7359
+ if (res.text.trim()) this.voice.transcript.push({ role: "assistant", content: res.text });
7360
+ if (rec.deliveryParked && !this.suppressParkedResume) {
7361
+ const gist = (rec.spokenText ?? "").trim() || res.text.trim();
7362
+ if (gist) {
7363
+ if (this.awaitTrivialRedeliver) {
7364
+ this.awaitTrivialRedeliver = false;
7365
+ this.options.host?.notify?.({ kind: "speak_utterance", message: gist });
7366
+ this.notify("diag", "parked_redelivered", { chars: gist.length });
7367
+ } else this.parkedRedeliver.push(gist);
7368
+ }
7493
7369
  }
7370
+ if (!rec.splitter?.spokeAny && res.text.trim() && !rec.deliveryParked)
7371
+ this.options.host?.notify?.({ kind: "speak_utterance", message: res.text });
7494
7372
  }
7495
- firstAudioAt = 0;
7496
- /** Circuit breaker: consecutive error count + down flag. */
7497
- consecutiveErrors = 0;
7498
- consecutiveOk = 0;
7499
- down = false;
7500
- downAt = 0;
7501
- probeTimer = null;
7502
- static CB_THRESHOLD = 3;
7503
- // open after 3 consecutive errors
7504
- static CB_RECOVER_OK = 2;
7505
- // close only after 2 consecutive good frames (no single-frame flap)
7506
- static CB_PROBE_MS = 3e4;
7507
- constructor(options) {
7508
- this.options = { ...new CartesiaTTSOptions(), ...options };
7373
+ onWorkerFailed(id, err) {
7374
+ this.failTask(this.tasks.get(id), err instanceof Error ? err.message : String(err));
7509
7375
  }
7510
- closed = false;
7511
- connecting = null;
7512
- async connect() {
7513
- this.closed = false;
7514
- this.connecting = this.doConnect();
7515
- await this.connecting;
7516
- this.connecting = null;
7376
+ failTask(rec, msg) {
7377
+ this.dropAsk(rec.id);
7378
+ rec.status = "error";
7379
+ rec.result = msg;
7380
+ log13.warn(`task ${rec.id} failed: ${msg}`);
7381
+ this.notify("task_error", `task ${rec.id} (${rec.label}) failed: ${msg}`);
7382
+ this.queueRevoice(this.integrationPrompt(rec, "error", msg, "error"), true);
7517
7383
  }
7518
- async doConnect() {
7519
- const key = await resolveAuth(this.options.auth);
7520
- const param = this.options.authMode === "token" ? "access_token" : "api_key";
7521
- this.ws = new WebSocket(`wss://api.cartesia.ai/tts/websocket?cartesia_version=2026-03-01&${param}=${key}`);
7522
- await new Promise((res, rej) => {
7523
- this.ws.onopen = () => res();
7524
- this.ws.onerror = (e) => rej(new Error(`cartesia ws: ${e.message || "connect failed"}`));
7525
- });
7526
- this.ws.onclose = (ev) => {
7527
- log13.warn(`cartesia ws closed (${ev.code} ${ev.reason || ""})`);
7528
- this.diag("tts_ws_closed", { code: ev.code, reason: String(ev.reason || ""), reconnecting: !this.closed });
7529
- if (!this.closed) {
7530
- this.connecting = this.doConnect().catch((e) => {
7531
- log13.error(`cartesia reconnect failed: ${e.message}`);
7532
- this.diag("tts_reconnect_failed", { message: e.message });
7533
- });
7384
+ // --- voice tools (closures over this instance) ---
7385
+ /** Live-switch the think tier: `false` disables (removes the Think tool from the voice agent),
7386
+ * a model id enables (adds the tool if missing). The system-prompt THINK_SLOT text is frozen at
7387
+ * construction — the tool's own description carries the routing guidance, so a live enable works;
7388
+ * dispatch()'s think→act fallback covers any straggler calls after a live disable. */
7389
+ setThinkModel(model) {
7390
+ this.options.thinkModel = model;
7391
+ const tools = this.voice.options.tools;
7392
+ const i = tools.findIndex((t) => t.name === "Think");
7393
+ if (model === false && i >= 0) tools.splice(i, 1);
7394
+ else if (model !== false && i < 0) tools.push(this.thinkTool());
7395
+ }
7396
+ /** User/programmatic spawn: the CLI's /act and /think commands. Returns the task id.
7397
+ * `followUp` marks an automatic escalation/re-delegation (set by the integration turn) so the new
7398
+ * task's own integration turn won't escalate again — capping auto-follow-ups to one hop. */
7399
+ async dispatch(brief, tier = "act", label, followUp = false) {
7400
+ if (tier === "think" && this.options.thinkModel === false) tier = "act";
7401
+ if (followUp) this.autoEscalations++;
7402
+ const id = `t${++this.seq}`;
7403
+ const lbl = label ?? tier;
7404
+ await this.options.onTaskStart?.(id, lbl);
7405
+ this.spawnWorker(id, lbl, this.buildBrief(brief, tier), tier, brief, followUp);
7406
+ this.notify("task_started", `task ${id} (${lbl}) started`, { id, brief, tier });
7407
+ return id;
7408
+ }
7409
+ actTool() {
7410
+ return {
7411
+ name: "Act",
7412
+ description: 'Escalate real work (reading/editing files, searching, running tasks, building) to a standard background worker. Returns immediately with a task id; the result arrives later as a "[task <id> completed]" event. Provide a clear, self-contained `brief` (the worker does not hear the live conversation).',
7413
+ parameters: {
7414
+ type: "object",
7415
+ required: ["brief"],
7416
+ properties: {
7417
+ brief: { type: "string", description: "full, self-contained instructions for the worker" },
7418
+ label: { type: "string", description: "a short (2-4 word) label for the task" }
7419
+ }
7420
+ },
7421
+ run: async ({ brief, label }) => {
7422
+ this.spokeBeforeDispatch = this.spokeThisTurn;
7423
+ this.turnDispatched = true;
7424
+ this.turnBriefs.add(String(brief ?? ""));
7425
+ this.voice.options.toolChoice = "none";
7426
+ const id = await this.dispatch(String(brief ?? ""), "act", label ? String(label) : void 0, this.turnFollowUp);
7427
+ return this.spokeBeforeDispatch ? `Acting on task ${id}. You already acknowledged \u2014 end your turn now with NO further text; the result will arrive as a [task ${id} completed] event.` : `Acting on task ${id}. Acknowledge briefly; the result will arrive as a [task ${id} completed] event.`;
7534
7428
  }
7535
7429
  };
7536
- this.ws.onmessage = (ev) => {
7537
- const m = JSON.parse(String(ev.data));
7538
- if (m.context_id && m.context_id !== this.ctxId) return;
7539
- if (m.type === "chunk" && m.data) {
7540
- this.consecutiveErrors = 0;
7541
- this.markRecovered();
7542
- if (!this.firstAudioAt) this.firstAudioAt = now2();
7543
- this.onAudio(base64ToBytes(m.data));
7544
- } else if (m.type === "done") {
7545
- this.consecutiveErrors = 0;
7546
- this.markRecovered();
7547
- this.onDone();
7548
- } else if (m.type === "timestamps" && m.word_timestamps) {
7549
- const wt = m.word_timestamps;
7550
- if (wt.words?.length && wt.start?.length) this.onTimestamps(wt.words, wt.start);
7551
- } else if (m.type === "error") {
7552
- if (/already been cancelled|does not exist/.test(m.message || "")) return;
7553
- this.consecutiveErrors++;
7554
- this.diag("tts_error", { message: String(m.message || ""), code: m.status_code, contextId: m.context_id, consecutive: this.consecutiveErrors });
7555
- if (!this.down && this.consecutiveErrors >= _CartesiaTTS.CB_THRESHOLD) {
7556
- this.down = true;
7557
- this.downAt = now2();
7558
- this.consecutiveOk = 0;
7559
- log13.warn(`TTS circuit breaker open \u2014 ${this.consecutiveErrors} consecutive errors, switching to text-only`);
7560
- this.diag("tts_breaker_open", { errors: this.consecutiveErrors });
7561
- this.onDone();
7562
- this.startProbe();
7563
- } else if (!this.down) {
7564
- (/No valid transcripts/i.test(m.message || "") ? log13.debug : log13.warn)(`cartesia: ${JSON.stringify(m)}`);
7430
+ }
7431
+ thinkTool() {
7432
+ return {
7433
+ name: "Think",
7434
+ description: "Escalate to a premium deep-reasoning agent for complex analysis, architecture decisions, hard debugging, or planning. Same async pattern as Act \u2014 returns a task id. Use when the problem needs careful thought before (or instead of) action. Do not use Think for simple tasks \u2014 Act is cheaper and faster.",
7435
+ parameters: {
7436
+ type: "object",
7437
+ required: ["brief"],
7438
+ properties: {
7439
+ brief: { type: "string", description: "the question or problem to reason about deeply" },
7440
+ label: { type: "string", description: "a short (2-4 word) label for the task" }
7441
+ }
7442
+ },
7443
+ run: async ({ brief, label }) => {
7444
+ this.spokeBeforeDispatch = this.spokeThisTurn;
7445
+ this.turnDispatched = true;
7446
+ this.turnBriefs.add(String(brief ?? ""));
7447
+ this.voice.options.toolChoice = "none";
7448
+ const id = await this.dispatch(String(brief ?? ""), "think", label ? String(label) : void 0, this.turnFollowUp);
7449
+ return this.spokeBeforeDispatch ? `Thinking on task ${id}. You already acknowledged \u2014 end your turn now with NO further text; the result will arrive as a [task ${id} completed] event.` : `Thinking on task ${id}. Acknowledge briefly; the result will arrive as a [task ${id} completed] event.`;
7450
+ }
7451
+ };
7452
+ }
7453
+ taskStatusTool() {
7454
+ return {
7455
+ name: "TaskStatus",
7456
+ description: "Status of background tasks. Pass `id` for one task, or omit it to list all.",
7457
+ parameters: { type: "object", properties: { id: { type: "string" } } },
7458
+ run: async ({ id }) => {
7459
+ const list = id ? [this.tasks.get(String(id))].filter(Boolean) : [...this.tasks.values()];
7460
+ if (!list.length) return id ? `No task '${id}'.` : "No background tasks.";
7461
+ return list.map((t) => `${t.id} (${t.label}): ${t.status}`).join("\n");
7462
+ }
7463
+ };
7464
+ }
7465
+ /** Sub-100ms read-only lookups the voice may do itself — everything else stays Act-only.
7466
+ * fs-only (no shell; the engine is VFS-abstracted): time, git branch (.git/HEAD read), ls, file
7467
+ * head. Output is hard-capped so a lookup can never bloat the skinny voice context. */
7468
+ quickLookTool() {
7469
+ const CAP = 2e3;
7470
+ const kinds = [.../* @__PURE__ */ new Set(["time", "branch", "ls", "file", "capabilities", ...Object.keys(this.options.quickLook ?? {})])];
7471
+ return {
7472
+ name: "QuickLook",
7473
+ description: `Instant read-only lookup \u2014 one of: ${kinds.join(", ")}. For trivial facts only; anything needing search, commands, or reasoning goes through Act.`,
7474
+ parameters: {
7475
+ type: "object",
7476
+ required: ["what"],
7477
+ properties: {
7478
+ what: { type: "string", enum: kinds, description: "what to look up" },
7479
+ path: { type: "string", description: "for ls/file: the path to look at" }
7480
+ }
7481
+ },
7482
+ run: async ({ what, path }) => {
7483
+ const fs = this.options.fs;
7484
+ try {
7485
+ const over = this.options.quickLook?.[String(what)];
7486
+ if (over) return await over(path ? String(path) : void 0);
7487
+ switch (String(what)) {
7488
+ case "capabilities": {
7489
+ const actTools = this.options.actOptions?.tools ?? [];
7490
+ const names = actTools.map((t) => t.name);
7491
+ const mcpServers = Object.keys(this.options.actOptions?.providerOptions?.mcpServers ?? {});
7492
+ const mcpNote = mcpServers.length ? ` Plus MCP servers your worker can use: ${mcpServers.join(", ")} (e.g. browser-bridge \u2192 drive a real browser: open tabs, navigate, click, screenshot).` : "";
7493
+ if (!names.length)
7494
+ return "Your worker uses Act's default local toolset (reading/editing files, running shell commands). No extra tools (e.g. web/internet) are configured; if a request is not a basic file or shell operation, assume you can't do it and say so." + mcpNote;
7495
+ const hasFetch = names.some((n) => /WebFetch/i.test(n));
7496
+ const hasBrowser = names.some((n) => /browser.*(navigate|click|page|type)/i.test(n));
7497
+ const hasSearch = names.some((n) => /(^|_)WebSearch$|search/i.test(n) && !/WebFetch|browser/i.test(n));
7498
+ const notes = [];
7499
+ if (hasFetch) notes.push("WebFetch retrieves ONE specific URL you are given \u2014 it is not a search engine.");
7500
+ if (hasBrowser) notes.push("The browser tools drive a real browser: you CAN open a site and, if needed, navigate to a search engine and search there \u2014 but it is manual and takes a moment, not an instant lookup.");
7501
+ else if (!hasSearch && hasFetch) notes.push('You have no general web-search tool, so for an instant "search the web" you can only fetch a URL they provide.');
7502
+ const webNote = notes.length ? " NOTE: " + notes.join(" ") : "";
7503
+ return `Tools your background worker (Act) can actually use: ${names.join(", ")}. Read each name literally and match the request to a SPECIFIC tool; if none fits, you do NOT have that ability \u2014 say so honestly.` + webNote + mcpNote;
7504
+ }
7505
+ case "time":
7506
+ return (/* @__PURE__ */ new Date()).toString();
7507
+ case "branch": {
7508
+ if (!fs) return "unavailable (no filesystem)";
7509
+ const head = (await fs.readFile(".git/HEAD")).trim();
7510
+ return head.startsWith("ref: refs/heads/") ? `branch: ${head.slice("ref: refs/heads/".length)}` : `detached HEAD at ${head.slice(0, 12)}`;
7511
+ }
7512
+ case "ls": {
7513
+ if (!fs) return "unavailable (no filesystem)";
7514
+ const p = String(path ?? ".");
7515
+ try {
7516
+ const names = await fs.readDir(p);
7517
+ return names.slice(0, 50).join("\n") + (names.length > 50 ? `
7518
+ \u2026 (+${names.length - 50} more)` : "");
7519
+ } catch {
7520
+ const names = await fs.readDir(".").catch(() => []);
7521
+ return `'${p}' not found here \u2014 you are likely already inside it. Current directory listing:
7522
+ ` + names.slice(0, 50).join("\n") + (names.length > 50 ? `
7523
+ \u2026 (+${names.length - 50} more)` : "");
7524
+ }
7525
+ }
7526
+ case "file": {
7527
+ if (!fs) return "unavailable (no filesystem)";
7528
+ if (!path) return "file lookup needs a path";
7529
+ try {
7530
+ const text = await fs.readFile(String(path));
7531
+ return text.length > CAP ? text.slice(0, CAP) + `
7532
+ \u2026 (truncated \u2014 ${text.length} chars total; Act for the full file)` : text;
7533
+ } catch {
7534
+ const names = await fs.readDir(".").catch(() => []);
7535
+ return `'${path}' not found. Current directory contains:
7536
+ ` + names.slice(0, 50).join("\n");
7537
+ }
7538
+ }
7539
+ default:
7540
+ return `unknown lookup '${what}'`;
7541
+ }
7542
+ } catch (e) {
7543
+ return `lookup failed: ${e?.message ?? e}`;
7544
+ }
7545
+ }
7546
+ };
7547
+ }
7548
+ answerTaskTool() {
7549
+ return {
7550
+ name: "AnswerTask",
7551
+ description: `Relay the user's answer to a pending question from a background task (the "[task <id> asks]" events). Pass the id from the event and the user's answer.`,
7552
+ parameters: {
7553
+ type: "object",
7554
+ required: ["id", "answer"],
7555
+ properties: { id: { type: "string" }, answer: { type: "string", description: "the user's answer, verbatim or faithfully summarized" } }
7556
+ },
7557
+ run: async ({ id, answer }) => {
7558
+ const ask = this.pendingAsks.get(String(id));
7559
+ if (!ask) return `No pending question for '${id}' \u2014 it may have been answered already or timed out.`;
7560
+ ask.resolve(String(answer ?? ""));
7561
+ return `Answer relayed \u2014 task ${id} resumes.`;
7562
+ }
7563
+ };
7564
+ }
7565
+ holdTool() {
7566
+ return {
7567
+ name: "Hold",
7568
+ description: 'The user seems mid-thought \u2014 hold the turn (stay listening) instead of answering. Optionally pass a short filler ("mhm", "go on") to speak while waiting. Use when the message sounds incomplete, trailing off, or like they paused to think.',
7569
+ parameters: {
7570
+ type: "object",
7571
+ properties: {
7572
+ filler: { type: "string", description: 'optional short filler to speak ("mhm", "go on", "mm-hm")' }
7565
7573
  }
7574
+ },
7575
+ run: async ({ filler }) => {
7576
+ this.heldThisTurn = true;
7577
+ this.notify("hold_filler", filler ? String(filler) : "");
7578
+ return "Holding \u2014 listening for the rest of the user's thought. Do not respond further this turn.";
7566
7579
  }
7567
7580
  };
7568
7581
  }
7569
- /** Close the breaker only after CB_RECOVER_OK consecutive good frames, so a single straggler chunk
7570
- * after a 503 burst doesn't flap open→recover in <1s. A sub-2s down-window is a transient blip → debug. */
7571
- markRecovered() {
7572
- if (!this.down) return;
7573
- if (++this.consecutiveOk < _CartesiaTTS.CB_RECOVER_OK) return;
7574
- this.down = false;
7575
- this.consecutiveOk = 0;
7576
- this.stopProbe();
7577
- const downMs = this.downAt ? now2() - this.downAt : 0;
7578
- this.diag("tts_breaker_close", { downMs: Math.round(downMs) });
7579
- (downMs < 2e3 ? log13.debug : log13.info)(`TTS recovered${downMs ? ` (down ${downMs}ms)` : ""}`);
7582
+ cancelTaskTool() {
7583
+ return {
7584
+ name: "CancelTask",
7585
+ description: "Cancel a running background task by id.",
7586
+ parameters: { type: "object", required: ["id"], properties: { id: { type: "string" } } },
7587
+ run: async ({ id }) => this.cancelTask(String(id))
7588
+ };
7580
7589
  }
7581
- /** Ensure the WS is open before sending — reconnects if idle-closed. */
7582
- async ensureConnected() {
7583
- if (this.connecting) await this.connecting;
7584
- if (this.ws?.readyState !== WebSocket.OPEN) await this.connect();
7590
+ };
7591
+
7592
+ // src/mcp.ts
7593
+ function toResult(result) {
7594
+ if (result == null) return { text: "" };
7595
+ if (typeof result === "string") return { text: result };
7596
+ const content = result.content;
7597
+ if (Array.isArray(content)) {
7598
+ const texts = [];
7599
+ const images = [];
7600
+ for (const c of content) {
7601
+ if (c?.type === "image" && typeof c.data === "string" && c.mimeType) {
7602
+ images.push({ mimeType: c.mimeType, data: c.data });
7603
+ } else if (typeof c?.text === "string") {
7604
+ texts.push(c.text);
7605
+ } else {
7606
+ texts.push(JSON.stringify(c));
7607
+ }
7608
+ }
7609
+ const text = texts.join("\n");
7610
+ if (text || images.length) return { text, ...images.length ? { images } : {} };
7585
7611
  }
7586
- /** Prime the synthesis pipeline on a throwaway context right after connect: the FIRST synthesis on
7587
- * a fresh WS pays Cartesia's cold spin-up (~1s+ live) — absorb it at mic-on instead of turn one.
7588
- * The returned audio is discarded (engine drops onAudio while not speaking; once a real turn calls
7589
- * newContext() any stragglers are stale-context-filtered). Respects the circuit breaker. */
7590
- warmup() {
7591
- if (this.down) return;
7592
- this.newContext();
7593
- if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(this.frame("Ok.", false));
7612
+ return { text: JSON.stringify(result) };
7613
+ }
7614
+ function mcpToolToAgentTool(spec, callTool, prefix = "mcp__") {
7615
+ return {
7616
+ name: `${prefix}${spec.name}`,
7617
+ description: spec.description ?? `MCP tool ${spec.name}`,
7618
+ parameters: spec.inputSchema ?? { type: "object", properties: {} },
7619
+ async run(args, _ctx) {
7620
+ const r = toResult(await callTool(spec.name, args ?? {}));
7621
+ return r.images?.length ? r : r.text;
7622
+ }
7623
+ };
7624
+ }
7625
+ function mcpToolsToAgentTools(specs, callTool, prefix = "mcp__", filter) {
7626
+ return (filter ? specs.filter(filter) : specs).map((s) => mcpToolToAgentTool(s, callTool, prefix));
7627
+ }
7628
+ function describeSpec(s) {
7629
+ const schema = s.inputSchema ? `
7630
+ args: ${JSON.stringify(s.inputSchema)}` : "";
7631
+ return `${s.name} \u2014 ${s.description ?? "(no description)"}${schema}`;
7632
+ }
7633
+ function makeMcpToolSearch(specs, callTool, options = {}) {
7634
+ const maxResults = options.maxResults ?? 10;
7635
+ const byName = new Map(specs.map((s) => [s.name, s]));
7636
+ const catalogLine = `${specs.length} MCP tool(s) available \u2014 search by keyword, then call by exact name.`;
7637
+ const searchTool = {
7638
+ name: "ToolSearch",
7639
+ description: `Search the available MCP tools by keyword (${catalogLine}). Returns matching tool names + their argument schemas; call one with \`McpCall\`.`,
7640
+ parameters: { type: "object", required: ["query"], properties: { query: { type: "string", description: "keywords to match against tool name + description" } } },
7641
+ async run({ query }) {
7642
+ const q = String(query ?? "").trim();
7643
+ if (!q) return catalogLine;
7644
+ const { kept } = topByRelevance(specs, q, (s) => `${s.name} ${s.description ?? ""}`, maxResults);
7645
+ if (!kept.length) return `(no MCP tool matches "${q}" \u2014 try broader keywords)`;
7646
+ return kept.map(describeSpec).join("\n");
7647
+ }
7648
+ };
7649
+ const callMcpTool = {
7650
+ name: "McpCall",
7651
+ description: "Call an MCP tool discovered via `ToolSearch`, by its exact name. Pass its arguments as `args`.",
7652
+ parameters: {
7653
+ type: "object",
7654
+ required: ["name"],
7655
+ properties: {
7656
+ name: { type: "string", description: "exact tool name from ToolSearch" },
7657
+ args: { type: "object", description: "arguments object for the tool (per its schema)" }
7658
+ }
7659
+ },
7660
+ async run({ name, args }) {
7661
+ const n = String(name ?? "");
7662
+ if (!byName.has(n)) return `Error: unknown MCP tool '${n}'. Use ToolSearch to find valid names.`;
7663
+ const r = toResult(await callTool(n, args ?? {}));
7664
+ return r.images?.length ? r : r.text;
7665
+ }
7666
+ };
7667
+ return [searchTool, callMcpTool];
7668
+ }
7669
+ function buildMcpCatalog(servers) {
7670
+ const specs = [];
7671
+ const routes = /* @__PURE__ */ new Map();
7672
+ for (const m of servers) {
7673
+ for (const s of m.specs) {
7674
+ const base = `mcp__${m.name}__${s.name}`.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 128);
7675
+ let display = base;
7676
+ for (let i = 2; routes.has(display); i++) display = `${base.slice(0, 128 - String(i).length - 1)}_${i}`;
7677
+ specs.push({ name: display, description: s.description, inputSchema: s.inputSchema });
7678
+ routes.set(display, { server: m.name, rawName: s.name });
7679
+ }
7594
7680
  }
7595
- newContext() {
7596
- this.ctxId = `ctx-${++this.ctxSeq}`;
7597
- this.firstAudioAt = 0;
7598
- return this.ctxId;
7681
+ return { specs, routes };
7682
+ }
7683
+ function searchOverCatalog(servers, specs, routes, resolve, options) {
7684
+ const tools = specs.length ? makeMcpToolSearch(specs, (name, args) => {
7685
+ const r = routes.get(name);
7686
+ if (!r) throw new Error(`unknown MCP tool '${name}' \u2014 use ToolSearch to find valid names`);
7687
+ return resolve(r.server, r.rawName, args ?? {});
7688
+ }, options) : [];
7689
+ return { tools, serverNames: servers, toolCount: specs.length };
7690
+ }
7691
+ function makeMcpToolSearchFromMounted(mounted, options) {
7692
+ const { specs, routes } = buildMcpCatalog(mounted);
7693
+ const byName = new Map(mounted.map((m) => [m.name, m]));
7694
+ return searchOverCatalog(mounted.map((m) => m.name), specs, routes, (server, rawName, args) => byName.get(server).client.callTool(rawName, args), options);
7695
+ }
7696
+ function makeLazyMcpToolSearch(servers, resolve, options) {
7697
+ const { specs, routes } = buildMcpCatalog(servers);
7698
+ return searchOverCatalog(servers.map((s) => s.name), specs, routes, resolve, options);
7699
+ }
7700
+
7701
+ // src/hooks.ts
7702
+ var RecordingHooks = class {
7703
+ /** tool name -> reason; a matching preToolUse call is blocked with that reason. */
7704
+ constructor(blocks = {}) {
7705
+ this.blocks = blocks;
7599
7706
  }
7600
- frame(transcript, cont) {
7601
- return JSON.stringify({
7602
- model_id: this.options.model,
7603
- transcript,
7604
- voice: { mode: "id", id: this.options.voiceId },
7605
- output_format: { container: "raw", encoding: "pcm_s16le", sample_rate: TTS_SAMPLE_RATE },
7606
- context_id: this.ctxId,
7607
- continue: cont,
7608
- ...this.wantTimestamps ? { add_timestamps: true } : {}
7609
- });
7707
+ blocks;
7708
+ pre = [];
7709
+ post = [];
7710
+ outputs = [];
7711
+ stops = [];
7712
+ preToolUse(call, meta) {
7713
+ this.pre.push({ call, meta });
7714
+ const reason = this.blocks[call.name];
7715
+ if (reason != null) return { block: true, reason };
7610
7716
  }
7611
- speak(text, cont) {
7612
- if (this.down) return;
7613
- if (cont && !text) return;
7614
- if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(this.frame(text, cont));
7615
- else void this.ensureConnected().then(() => this.ws?.readyState === WebSocket.OPEN && this.ws.send(this.frame(text, cont)));
7717
+ postToolUse(call, result, meta) {
7718
+ this.post.push({ call, result, meta });
7616
7719
  }
7617
- end() {
7618
- if (this.down) {
7619
- this.onDone();
7620
- return;
7621
- }
7622
- if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(this.frame("", false));
7720
+ onToolOutput(call, chunk, meta) {
7721
+ this.outputs.push({ call, chunk, meta });
7623
7722
  }
7624
- cancel() {
7625
- if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(JSON.stringify({ context_id: this.ctxId, cancel: true }));
7723
+ onStop(finalText) {
7724
+ this.stops.push(finalText);
7626
7725
  }
7627
- startProbe() {
7628
- if (this.probeTimer) return;
7629
- this.probeTimer = setInterval(() => {
7630
- if (!this.down) {
7631
- this.stopProbe();
7632
- return;
7633
- }
7634
- this.consecutiveErrors = 0;
7635
- this.newContext();
7636
- if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(this.frame("Ok.", false));
7637
- }, _CartesiaTTS.CB_PROBE_MS);
7638
- this.probeTimer.unref?.();
7726
+ };
7727
+ var RecordingLifecycle = class {
7728
+ /** @param startContext injected at session start; @param rewrite maps a submitted prompt to a new one. */
7729
+ constructor(startContext, rewrite) {
7730
+ this.startContext = startContext;
7731
+ this.rewrite = rewrite;
7639
7732
  }
7640
- stopProbe() {
7641
- if (this.probeTimer) {
7642
- clearInterval(this.probeTimer);
7643
- this.probeTimer = null;
7644
- }
7733
+ startContext;
7734
+ rewrite;
7735
+ starts = 0;
7736
+ prompts = [];
7737
+ compactions = [];
7738
+ subagentStops = [];
7739
+ onSessionStart() {
7740
+ this.starts++;
7741
+ return this.startContext;
7645
7742
  }
7646
- close() {
7647
- this.closed = true;
7648
- this.stopProbe();
7649
- if (this.ws) this.ws.onclose = null;
7650
- this.ws?.close();
7743
+ onUserPromptSubmit(text) {
7744
+ this.prompts.push(text);
7745
+ return this.rewrite?.(text);
7746
+ }
7747
+ onPreCompact(messages) {
7748
+ this.compactions.push(messages.length);
7749
+ }
7750
+ onSubagentStop(summary, info) {
7751
+ this.subagentStops.push({ summary, label: info?.label });
7651
7752
  }
7652
7753
  };
7653
- function base64ToBytes(b64) {
7654
- if (typeof Buffer !== "undefined") return Buffer.from(b64, "base64");
7655
- const bin = atob(b64);
7656
- const out = new Uint8Array(bin.length);
7657
- for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
7658
- return out;
7659
- }
7660
7754
 
7661
7755
  // src/index.ts
7756
+ init_logging();
7662
7757
  import { MemFilesystem as MemFilesystem3, IndexedDbFilesystem, CommandExecutor as CommandExecutor2, registerHeadlessCommands as registerHeadlessCommands2 } from "@livx.cc/wcli/core";
7663
7758
  export {
7664
7759
  Agent,