@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/cli.js CHANGED
@@ -3406,6 +3406,27 @@ var Agent = class _Agent {
3406
3406
  if (this.options.tools) this.options.tools = this.options.tools.filter((t) => !s.has(t.name));
3407
3407
  return before - this.activeTools.length;
3408
3408
  }
3409
+ /** Messages the host queued to steer the RUNNING turn (Claude-Code-style mid-turn input). The loop
3410
+ * drains them at each step boundary — after tool results are appended, before the next model call —
3411
+ * so they ride along with the latest tool results. A no-op between turns (nothing drains it). */
3412
+ pendingInjections = [];
3413
+ /** Queue a user message into the in-flight turn. It lands as a `user` message at the next step
3414
+ * boundary; if the model was about to stop, the injection re-opens the loop so it's never lost.
3415
+ * Pushing onto `transcript` directly from outside would race the loop — this drains inside it. */
3416
+ inject(content) {
3417
+ this.pendingInjections.push(content);
3418
+ }
3419
+ /** Drop any queued-but-unconsumed injections. The REPL calls this after a LOCAL command (/cmd, !bash)
3420
+ * — which runs no send() to drain them — so a mid-command steer can't leak into the next real turn. */
3421
+ clearInjections() {
3422
+ this.pendingInjections.length = 0;
3423
+ }
3424
+ /** Fold any host-injected messages into the transcript as user turns. Returns true if any landed. */
3425
+ drainInjections() {
3426
+ if (!this.pendingInjections.length) return false;
3427
+ for (const content of this.pendingInjections.splice(0)) this.transcript.push({ role: "user", content });
3428
+ return true;
3429
+ }
3409
3430
  constructor(options) {
3410
3431
  this.options = { ...new AgentOptions(), ...options };
3411
3432
  if (this.options.fs) this.buildCtx();
@@ -3671,6 +3692,7 @@ var Agent = class _Agent {
3671
3692
  });
3672
3693
  }
3673
3694
  if (toolCalls.length === 0) {
3695
+ if (this.drainInjections()) continue;
3674
3696
  log4.verbose(`completed in ${steps} step(s)`);
3675
3697
  await this.ctx.jobs?.drain();
3676
3698
  await this.activeHooks?.onStop?.(res.content ?? "");
@@ -3695,6 +3717,7 @@ var Agent = class _Agent {
3695
3717
  }
3696
3718
  this.transcript.push({ role: "tool", tool_call_id: tc.id, name: tc.function.name, content });
3697
3719
  }
3720
+ this.drainInjections();
3698
3721
  }
3699
3722
  }
3700
3723
  /**
@@ -4382,14 +4405,14 @@ function makeScheduleTools(scheduler, os) {
4382
4405
  backend: { type: "string", enum: ["auto", "session", "os"], description: "Where the job lives (default auto)." }
4383
4406
  }
4384
4407
  },
4385
- async run({ prompt, trigger, label, backend }) {
4408
+ async run({ prompt, trigger, label, backend: backend2 }) {
4386
4409
  try {
4387
- if (os && os.route(trigger, backend) === "os") {
4410
+ if (os && os.route(trigger, backend2) === "os") {
4388
4411
  const id2 = `os-${Date.now().toString(36)}`;
4389
4412
  const mechanism = os.schedule({ id: id2, prompt, sessionId: os.sessionId, cwd: os.cwd, trigger, label });
4390
4413
  return `Scheduled ${id2}${label ? ` (${label})` : ""} on the OS scheduler (${mechanism}) \u2014 survives quitting; fires \`agentx --resume ${os.sessionId}\` headless.`;
4391
4414
  }
4392
- if (backend === "os") return "Error: no OS scheduler available on this platform \u2014 job not created (use the default in-session backend).";
4415
+ if (backend2 === "os") return "Error: no OS scheduler available on this platform \u2014 job not created (use the default in-session backend).";
4393
4416
  const id = scheduler.add({ prompt, trigger, label });
4394
4417
  const job = scheduler.get(id);
4395
4418
  const next = scheduler.nextFire(job);
@@ -4668,9 +4691,37 @@ function digestRun(messages, maxChars) {
4668
4691
  import { MemFilesystem as MemFilesystem2 } from "@livx.cc/wcli/core";
4669
4692
  init_logging();
4670
4693
 
4671
- // src/voice/emotion.ts
4672
- init_logging();
4673
- var log8 = forComponent("Emotion");
4694
+ // node_modules/@bod.ee/voice/src/core/logging.ts
4695
+ function consoleForComponent(name) {
4696
+ const debugEnv = typeof process !== "undefined" && process.env?.DEBUG || typeof localStorage !== "undefined" && localStorage.getItem("DEBUG") || "";
4697
+ const gated = debugEnv === "*" || debugEnv.split(",").some((p) => p.trim() === name);
4698
+ const gate = (fn) => gated ? fn : () => {
4699
+ };
4700
+ const tag = `[${name}]`;
4701
+ return {
4702
+ debug: gate((...a) => console.debug(tag, ...a)),
4703
+ verbose: gate((...a) => console.debug(tag, ...a)),
4704
+ info: (...a) => console.info(tag, ...a),
4705
+ warn: (...a) => console.warn(tag, ...a),
4706
+ error: (...a) => console.error(tag, ...a)
4707
+ };
4708
+ }
4709
+ var backend = consoleForComponent;
4710
+ function configureLogging(forComponentImpl) {
4711
+ backend = forComponentImpl;
4712
+ }
4713
+ function forComponent2(name) {
4714
+ return {
4715
+ debug: (...a) => backend(name).debug(...a),
4716
+ verbose: (...a) => backend(name).verbose(...a),
4717
+ info: (...a) => backend(name).info(...a),
4718
+ warn: (...a) => backend(name).warn(...a),
4719
+ error: (...a) => backend(name).error(...a)
4720
+ };
4721
+ }
4722
+
4723
+ // node_modules/@bod.ee/voice/src/core/emotion.ts
4724
+ var log8 = forComponent2("Emotion");
4674
4725
  var EMOTIONS = [
4675
4726
  // primary (best results)
4676
4727
  "neutral",
@@ -4866,9 +4917,8 @@ var EmotionStream = class {
4866
4917
  }
4867
4918
  };
4868
4919
 
4869
- // src/voice/engine.ts
4870
- init_logging();
4871
- var log9 = forComponent("VoiceEngine");
4920
+ // node_modules/@bod.ee/voice/src/core/engine.ts
4921
+ var log9 = forComponent2("VoiceEngine");
4872
4922
  var realClock = {
4873
4923
  now: () => performance.now(),
4874
4924
  setTimeout: (fn, ms) => setTimeout(fn, ms),
@@ -5052,6 +5102,13 @@ var VoiceEngine = class _VoiceEngine {
5052
5102
  // the exact ack text last spoken (fixed OR adaptive) — the echo-leak guard matches it
5053
5103
  ackTimer = null;
5054
5104
  // one-shot adaptive-ack timer (armed at dispatch, cancelled on first delta)
5105
+ // The adaptive micro-ack ALREADY spoke this turn → the reflex's own leading ack ("Still on it.") is now
5106
+ // redundant (live: host said "On it." then the reflex said "Still on it."). While this is set, speakDelta
5107
+ // probes the reflex's opening sentence and DROPS it if it's purely an acknowledgement; real content passes
5108
+ // through. Reset per turn in beginSpeech()/interrupt().
5109
+ adaptiveAckFired = false;
5110
+ ackProbe = null;
5111
+ // buffered reflex prose while probing the leading ack (null = not probing)
5055
5112
  bargeGraceUntil = 0;
5056
5113
  // no barge-in until this time — the user's OWN trailing audio (after the
5057
5114
  // utterance that JUST dispatched this turn) must not immediately re-interrupt the reply it requested.
@@ -5194,6 +5251,8 @@ var VoiceEngine = class _VoiceEngine {
5194
5251
  this.speaking = true;
5195
5252
  this.ctxOpen = true;
5196
5253
  this.spokeDeltas = false;
5254
+ this.adaptiveAckFired = false;
5255
+ this.ackProbe = null;
5197
5256
  this.reply = "";
5198
5257
  this.revealText = "";
5199
5258
  this.wordStarts = [];
@@ -5222,6 +5281,8 @@ var VoiceEngine = class _VoiceEngine {
5222
5281
  this.lastAck = phrase;
5223
5282
  for (const w of this.words(phrase)) this.echoWords.add(w);
5224
5283
  this.setState("speaking");
5284
+ this.adaptiveAckFired = true;
5285
+ this.ackProbe = "";
5225
5286
  this.options.onAdaptiveAck();
5226
5287
  }, this.options.adaptiveAckMs);
5227
5288
  }
@@ -5233,6 +5294,25 @@ var VoiceEngine = class _VoiceEngine {
5233
5294
  speakDelta(text) {
5234
5295
  if (this.interrupted) return "";
5235
5296
  this.clearAckTimer("first_delta");
5297
+ if (this.adaptiveAckFired && this.ackProbe !== null) {
5298
+ this.ackProbe += text;
5299
+ const probe = this.ackProbe;
5300
+ const bare = probe.replace(/\[emotion[^\]]*\]/gi, "").replace(/^\s+/, "");
5301
+ const m = bare.match(/^([^.!?…\n]*[.!?…\n])([\s\S]*)$/);
5302
+ if (!m && bare.length < 80) return "";
5303
+ this.ackProbe = null;
5304
+ this.adaptiveAckFired = false;
5305
+ const lead = m ? m[1] : bare;
5306
+ const norm2 = lead.replace(/[^a-z ]/gi, " ").replace(/\s+/g, " ").trim().toLowerCase();
5307
+ if (_VoiceEngine.ACK_LEADING.test(norm2)) {
5308
+ const rest = m ? m[2] : "";
5309
+ this.diag("reflex_ack_suppressed", { lead: lead.trim() });
5310
+ if (!rest.trim()) return "";
5311
+ text = rest;
5312
+ } else {
5313
+ text = probe;
5314
+ }
5315
+ }
5236
5316
  if (!this.speaking || !this.ctxOpen) this.beginSpeech();
5237
5317
  let { speech, display, prose } = this.emo ? this.emo.feed(text) : { speech: text, display: text, prose: text };
5238
5318
  if (this.reply && /[.!?…]$/.test(this.reply) && /^[A-Z]/.test(prose)) {
@@ -5291,6 +5371,14 @@ var VoiceEngine = class _VoiceEngine {
5291
5371
  endSpeech() {
5292
5372
  this.interrupted = false;
5293
5373
  this.clearAckTimer("turn_end");
5374
+ const heldProbe = this.ackProbe;
5375
+ this.adaptiveAckFired = false;
5376
+ this.ackProbe = null;
5377
+ if (heldProbe) {
5378
+ const norm2 = heldProbe.replace(/\[emotion[^\]]*\]/gi, "").replace(/[^a-z ]/gi, " ").replace(/\s+/g, " ").trim().toLowerCase();
5379
+ if (_VoiceEngine.ACK_LEADING.test(norm2)) this.diag("reflex_ack_suppressed", { lead: heldProbe.trim() });
5380
+ else this.speakDelta(heldProbe);
5381
+ }
5294
5382
  if (!this.speaking) return;
5295
5383
  this.diag("tts_turn_end", { spoke: this.spokeDeltas, replyChars: this.reply.length });
5296
5384
  this.ctxOpen = false;
@@ -5372,6 +5460,9 @@ var VoiceEngine = class _VoiceEngine {
5372
5460
  * No 'Okay.': a genuine user "Okay." within the 6s squash window would be swallowed as ack echo. */
5373
5461
  static ACKS_NEUTRAL = ["Mm-hm.", "One sec.", "Right.", "Sec.", "On it.", "Sure, moment.", "Uh, one moment.", "Let me see."];
5374
5462
  static ACKS_QUESTION = ["Hmm.", "Let me think.", "Hm, let me see.", "Good question.", "Mm, one sec.", "Let's see."];
5463
+ /** A reflex opening sentence that is PURELY an acknowledgement (no content) — dropped when the adaptive
5464
+ * micro-ack already spoke one. Anchored end-to-end so only a whole ack-only clause matches. */
5465
+ 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))[ ,]*)+$/;
5375
5466
  recentAcks = [];
5376
5467
  pickAck() {
5377
5468
  const pool = this.lastDispatchWasQuestion ? _VoiceEngine.ACKS_QUESTION : _VoiceEngine.ACKS_NEUTRAL;
@@ -5396,6 +5487,8 @@ var VoiceEngine = class _VoiceEngine {
5396
5487
  /** barge-in: stop audio NOW, cancel generation, reset for the user's utterance */
5397
5488
  interrupt() {
5398
5489
  this.clearAckTimer("interrupt");
5490
+ this.adaptiveAckFired = false;
5491
+ this.ackProbe = null;
5399
5492
  if (this.uttQueue.length) log9.info(`barge-in dropped ${this.uttQueue.length} queued worker utterance(s)`);
5400
5493
  const droppedQueued = this.uttQueue.length;
5401
5494
  this.uttQueue = [];
@@ -5856,7 +5949,14 @@ var VoiceEngine = class _VoiceEngine {
5856
5949
  }
5857
5950
  };
5858
5951
 
5859
- // src/voice/spokenSplitter.ts
5952
+ // node_modules/@bod.ee/voice/src/core/types.ts
5953
+ var STT_SAMPLE_RATE = 16e3;
5954
+ var TTS_SAMPLE_RATE = 44100;
5955
+ async function resolveAuth(auth) {
5956
+ return typeof auth === "function" ? await auth() : auth;
5957
+ }
5958
+
5959
+ // node_modules/@bod.ee/voice/src/core/spokenSplitter.ts
5860
5960
  var OPEN = "<spoken>";
5861
5961
  var CLOSE = "</spoken>";
5862
5962
  var CLOSERS = `"')]}\xBB\u201D\u2019`;
@@ -5928,1594 +6028,1589 @@ var SpokenSplitter = class {
5928
6028
  }
5929
6029
  };
5930
6030
 
5931
- // src/duplex.ts
5932
- var log10 = forComponent("DuplexAgent");
5933
- function describeCall(call) {
5934
- const v = call.args && Object.values(call.args).find((x) => typeof x === "string" && x.trim());
5935
- const hint = v ? ` (${String(v).replace(/\s+/g, " ").trim().slice(0, 48)})` : "";
5936
- return `${call.name}${hint}`;
5937
- }
5938
- var DuplexAgentOptions = class {
5939
- /** Any ai.libx.js AIClient — shared by all tiers (routed by model). */
5940
- ai;
5941
- /** The WORKER's filesystem (act + think). If omitted the worker keeps Agent's jailed-disk-at-cwd default. */
5942
- fs;
5943
- // The reflex IS the voice. 120b (not 20b) for channel discipline + instruction-following: the 20b
5944
- // mislabels gpt-oss harmony channels under load, leaking raw analysis into the spoken `final` channel
5945
- // (and misfiring Hold). 120b is the same price tier (~$0.15/$0.60) — the quality/cost trade is free.
5946
- reflexModel = "groq/openai/gpt-oss-120b";
5947
- actModel = "anthropic/claude-sonnet-4-6";
5948
- /** Premium reasoning model. Set to `false` to disable the Think tier entirely. */
5949
- thinkModel = "anthropic/claude-opus-4-8";
5950
- /** Per-worker providerOptions, derived from the worker's actual model at spawn time (IoC — keeps duplex
5951
- * provider-agnostic). Workers override the reflex/main model, so provider-specific options (e.g. cursor's
5952
- * cwd/cursorSession) must be recomputed for the worker's model, never inherited from the main template —
5953
- * leaking cursor options to an anthropic worker is a hard 400. Returns undefined → no providerOptions. */
5954
- providerOptionsFor;
5955
- /** Escape hatches merged over the derived per-agent options. */
5956
- reflexOptions;
5957
- actOptions;
5958
- thinkOptions;
5959
- /** Fresh-context check on each successful Act task: a NEW agent (no self-confirmation bias) re-reads
5960
- * the file state against the brief and fixes any gap before the result is re-voiced. Bounded to one
5961
- * pass; ~2x Act cost so default OFF. The self-verify FOOTER (same context) was measured ineffective —
5962
- * this is the structural fix (see mind/10). Think tasks are pure reasoning, never checked. */
5963
- verifyActTasks = false;
5964
- /** Receives the voice text_delta stream + task lifecycle events. */
5965
- host;
5966
- /** How many recent transcript messages are rendered into a worker's brief. */
5967
- excerptTurns = 6;
5968
- /** Voice register: 'neutral' = clean spoken style; 'conversational' = human-like — fillers,
5969
- * backchannels, impulsive first reactions before content (mimics real duplex conversation). */
5970
- voiceStyle = "neutral";
5971
- /** Teach the model to emit inline `[emotion]` tags for Cartesia emotion control. Only set when the
5972
- * TTS actually speaks them — text-duplex (no TTS) would otherwise print literal tags. */
5973
- emotionTags = false;
5974
- /** Awaited BEFORE a worker spawns — open a per-task checkpoint frame, audit, etc.
5975
- * (post-spawn would race the worker's first edits). */
5976
- onTaskStart;
5977
- /** Re-voice throttled worker progress asides ('[task t1 progress] …') so long tasks aren't dead
5978
- * air. Off by default — each update costs a voice turn (LLM call + speech). */
5979
- progressUpdates = false;
5980
- /** Min ms between progress re-voices per task. */
5981
- progressIntervalMs = 25e3;
5982
- /** Relay worker questions (AskUserQuestion + permission asks via parkQuestion) through the VOICE:
5983
- * the question re-voices as '[task <id> asks] …', the user answers conversationally, and the
5984
- * voice model resolves it with the AnswerTask tool. Off → host.ask passthrough (text menus). */
5985
- askRelay = false;
5986
- /** Parked questions auto-resolve empty after this long (callers map '' to deny/best-judgment). */
5987
- askTimeoutMs = 12e4;
5988
- /** Max retained task records: oldest SETTLED tasks (and their activity tails) are evicted past this,
5989
- * bounding memory over a long-lived session. Running tasks are never evicted. */
5990
- maxTaskRecords = 50;
5991
- /** Host overrides for QuickLook lookups (keyed by `what`). The engine's defaults go through the
5992
- * (possibly jailed) fs — e.g. `.git/**` is deny-listed, so the CLI supplies 'branch' itself. */
5993
- quickLook;
5994
- /** Memory directory/directories on the WORKER fs. If set, the voice agent gets Remember + Recall
5995
- * tools directly (no delegation needed) and implicit capture guidance. */
5996
- memoryDir;
5997
- /** User-scope memory dir for global facts (type=user/feedback). Forwarded to Remember's routing. */
5998
- memoryUserDir;
6031
+ // node_modules/@bod.ee/voice/src/adapters/soniox.ts
6032
+ var log10 = forComponent2("SonioxSTT");
6033
+ var now = () => performance.now();
6034
+ var SonioxSTTOptions = class {
6035
+ auth = "";
6036
+ source;
6037
+ model = "stt-rt-preview";
6038
+ languageHints = ["en"];
6039
+ /** Client-side endpoint: finalized text + no new tokens for this long = utterance (don't wait for
6040
+ * Soniox's semantic <end>, which adds 0.5-1.5s — the difference between ping-pong and lag). */
6041
+ silenceEndpointMs = 500;
6042
+ /** No-audio watchdog: if the mic source stops delivering chunks for this long, capture is dead →
6043
+ * fire onFatal + stop (else Soniox idle-timeouts and reconnect-loops forever). 0 = disable. */
6044
+ noAudioTimeoutMs = 1e4;
5999
6045
  };
6000
- var RESERVED_EVENT_MARKER = /\[task\b[^\]\n]*\b(?:completed|failed|progress|asks)\b/i;
6001
- var RESERVED_EVENT_OPENER = /\[\s*task\b/i;
6002
- var STAGE_DIRECTION_RE = /^\(\s*(?:(?:waiting|checking|searching|thinking|processing|loading|working|fetching|looking)\b[^)]*|[^)]*(?:\.\.\.|…)\s*)\)$/i;
6003
- function nowLine() {
6004
- 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" })}`;
6005
- }
6006
- function isTrivialBarge(text) {
6007
- const t = text.trim().toLowerCase().replace(/[.,!?…\s]+$/g, "").replace(/^[.,!?…\s]+/, "");
6008
- if (!t) return false;
6009
- 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;
6010
- const core = t.replace(/^(?:oh|um+|uh+|er+|hmm+|ah+|well|so|okay|ok|yeah|yep)[\s,]+/, "").trim();
6011
- 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);
6012
- }
6013
- 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.';
6014
- 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.";
6015
- var THINK_DISABLED_GUIDANCE = "(Think tier is not available \u2014 use Act for all escalations.)";
6016
- 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).`;
6017
- 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(", ")}.`;
6018
- var DuplexAgent = class _DuplexAgent {
6046
+ var SonioxSTT = class {
6019
6047
  options;
6020
- voice;
6021
- tasks = /* @__PURE__ */ new Map();
6022
- queue = Promise.resolve();
6023
- seq = 0;
6024
- pendingEvents = [];
6025
- /** Spoken text of parked deliveries that have SETTLED, awaiting a trivial-barge resume decision on the
6026
- * next turn (a substantive turn clears it — the result stays in the transcript, recoverable by asking). */
6027
- parkedRedeliver = [];
6028
- /** A trivial barge arrived while a parked delivery was STILL RUNNING → resume it the moment it settles. */
6029
- awaitTrivialRedeliver = false;
6030
- /** Set by a SUBSTANTIVE turn after a barge: the user moved on, so a parked delivery that settles LATER
6031
- * must NOT arm a resume (else a much-later "go on" replays a stale result). Reset by a fresh barge. */
6032
- suppressParkedResume = false;
6033
- /** Out-of-band follow-up attribution for the events coalescing into the next flush turn: TRUE iff ≥1 of
6034
- * the tasks being integrated was NON-CLEAN (early-stop/failure). Carried out-of-band on the enqueue call
6035
- * by the caller that KNOWS the outcome — a plain boolean the MODEL CANNOT PERTURB. It is NOT scanned from
6036
- * worker-authored event text (v1: an "Outcome:" substring over-stamped siblings) and NOT keyed on a brief
6037
- * string the reflex re-authors (v2: a paraphrased escalation brief missed the Set → followUp:false →
6038
- * RE-ENABLED unbounded auto-escalation, the dangerous runaway direction). See [[wrong-discriminator]] /
6039
- * [[drive-real-reflex]] / [[fakeaiclient-blind-to-wire-format]]. */
6040
- pendingNonClean = false;
6041
- flushQueued = false;
6042
- /** Per-voice-turn guards (reset by resetTurn at each turn's start). The reflex is a weak model:
6043
- * left unguarded it polls TaskStatus after a dispatch and/or dispatches silently (dead air).
6044
- * Like CC's Task tool, a dispatch is "said my piece, now wait for the push" — these enforce that. */
6045
- turnDispatched = false;
6046
- // an Act/Think fired this turn
6047
- spokeBeforeDispatch = false;
6048
- // the reflex ALREADY acked before dispatching — the forced post-dispatch text step must stay silent (live: "Got it…" twice)
6049
- turnBriefs = /* @__PURE__ */ new Set();
6050
- // briefs dispatched this turn (detect identical re-dispatch)
6051
- spokeThisTurn = false;
6052
- // any non-empty text_delta streamed this turn
6053
- externalSpeech = false;
6054
- // host spoke on our behalf (adaptive micro-ack) — not reflex output
6055
- heldThisTurn = false;
6056
- // Hold called this turn → turn is INTENTIONALLY silent (suppress reflex text + no dead-air ack)
6057
- nudging = false;
6058
- // re-ack pass in flight: block ALL tools, prevent recursion
6059
- reflexBuf = "";
6060
- // accumulated reflex text this turn (fabricated-event detection)
6061
- reflexForwarded = 0;
6062
- // chars of reflexBuf already forwarded to the host/TTS
6063
- fabricationCut = false;
6064
- // reflex emitted a reserved [task …] marker → suppress its tail
6065
- /** TRUE for the duration of a re-voice turn that is integrating ≥1 NON-CLEAN task (turn-eligibility,
6066
- * carried out-of-band — NOT derived from any worker/brief string). ANY Act/Think dispatched in such a
6067
- * turn is stamped followUp:true. This GUARANTEES the dangerous direction is impossible: a genuine
6068
- * escalation (even one with a paraphrased brief) ALWAYS lands in a non-clean integration turn, so it is
6069
- * ALWAYS recognized as a follow-up and CANNOT re-escalate (one hop). The single-dispatch-per-turn guard
6070
- * means at most one dispatch happens per flush, so realistically "the one dispatch IS the escalation".
6071
- * ACCEPTED SAFE-DIRECTION ERROR: if the reflex instead dispatches FRESH unrelated work during a non-clean
6072
- * flush (rare — and only possible when it batches multiple calls in one step, bypassing the guard), that
6073
- * fresh task is over-stamped followUp:true and forgoes ONE future auto-escalation. That is SAFE (it only
6074
- * ever REMOVES a future escalation, never adds one — no runaway) and is the correct side to err on. */
6075
- turnFollowUp = false;
6076
- /** Hard absolute backstop against runaway regardless of attribution: total automatic escalations across
6077
- * the whole conversation. Once it hits MAX_AUTO_ESCALATIONS, no integration turn offers escalate/re-delegate. */
6078
- autoEscalations = 0;
6079
- static MAX_AUTO_ESCALATIONS = 8;
6080
- /** Parked worker questions awaiting a (voice-relayed) user answer, keyed by ask id. */
6081
- pendingAsks = /* @__PURE__ */ new Map();
6082
- /** SPECULATIVE REFLEX (VoiceEngine.onSpeculate → speculate()): the reflex turn starts on a stable
6083
- * PARTIAL transcript, its spoken output buffered — nothing reaches TTS until the endpointed final
6084
- * confirms via send() (which flushes the buffer and adopts the call as THE turn). A divergent final
6085
- * aborts it: output dropped, history rolled back, the final dispatches normally. */
6086
- spec;
6087
- /** Aborted speculative calls (double-billing visibility — each one paid for tokens never spoken). */
6088
- speculativeAbortedCalls = 0;
6089
- /** Tools the reflex may execute on UNCONFIRMED (speculated) input — read-only lookups and the
6090
- * intentionally-silent Hold. Anything else (Act/Think/AnswerTask/CancelTask/ExitSession/memory
6091
- * writes/…) is a side effect on input the user may not have said: the guard ABORTS the speculation
6092
- * instead (the endpointed final then dispatches normally and may use the tool for real). */
6093
- static SPEC_SAFE_TOOLS = /* @__PURE__ */ new Set(["QuickLook", "TaskStatus", "Hold"]);
6094
- /** Lazily resolved memory tools (async loadMemory runs in initMemory). */
6095
- memoryReady;
6096
- constructor(options) {
6097
- this.options = { ...new DuplexAgentOptions(), ...options };
6098
- const o = this.options;
6099
- if (o.memoryDir && o.fs) {
6100
- this.memoryReady = loadMemory(o.fs, o.memoryDir, { maxWritesPerSession: 10, userDir: o.memoryUserDir });
6048
+ ws;
6049
+ stopped = false;
6050
+ sourceStarted = false;
6051
+ onPartial = () => {
6052
+ };
6053
+ onUtterance = () => {
6054
+ };
6055
+ /** mic energy (RMS) per chunk — drives the energy-based heuristic barge-in tier */
6056
+ onLevel = () => {
6057
+ };
6058
+ /** Unrecoverable: the mic source stopped delivering audio (Soniox starves → idle-timeout reconnect
6059
+ * loop). The host tears voice down instead of spinning forever. */
6060
+ onFatal = () => {
6061
+ };
6062
+ /** Diagnostic tap (provider errors, ws reconnects, no-audio watchdog). Fire-and-forget: a throwing
6063
+ * handler disables itself — never affects transcription. Wired by VoiceIO / the lab bridge. */
6064
+ onDiag = () => {
6065
+ };
6066
+ diagOn = true;
6067
+ diag(kind, fields) {
6068
+ if (!this.diagOn) return;
6069
+ try {
6070
+ this.onDiag({ t: now(), kind, ...fields });
6071
+ } catch (e) {
6072
+ this.diagOn = false;
6073
+ log10.debug(`onDiag threw \u2014 STT diagnostics disabled: ${e instanceof Error ? e.message : e}`);
6101
6074
  }
6102
- 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.";
6103
- const thinkSlot = o.thinkModel !== false ? THINK_GUIDANCE : THINK_DISABLED_GUIDANCE;
6104
- const workerToolNames = (o.actOptions?.tools ?? []).map((t) => t.name);
6105
- const canSearch = workerToolNames.some((n) => /WebSearch/i.test(n));
6106
- const canFetch = workerToolNames.some((n) => /WebFetch/i.test(n));
6107
- 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)" : "";
6108
- const mcpNames = [
6109
- ...Object.keys(o.actOptions?.providerOptions?.mcpServers ?? {}),
6110
- ...new Set(workerToolNames.filter((n) => n.startsWith("mcp__")).map((n) => n.slice(5).split("__")[0]))
6111
- ];
6112
- 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' : "") : "";
6113
- 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 : "") + `
6114
- ${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.`;
6115
- const tools = [
6116
- ...o.reflexOptions?.tools ?? [],
6117
- this.actTool(),
6118
- ...o.thinkModel !== false ? [this.thinkTool()] : [],
6119
- this.taskStatusTool(),
6120
- this.cancelTaskTool(),
6121
- this.quickLookTool(),
6122
- this.answerTaskTool(),
6123
- this.holdTool()
6124
- ];
6125
- const host = o.host;
6126
- const voiceHost = host && {
6127
- ask: host.ask ? (q2) => host.ask(q2) : void 0,
6128
- confirm: host.confirm ? (p, m) => host.confirm(p, m) : void 0,
6129
- notify: (ev) => {
6130
- if (ev?.kind === "text_delta" && typeof ev.message === "string") {
6131
- if (this.heldThisTurn) return;
6132
- if (this.fabricationCut) return;
6133
- if (this.turnDispatched && this.spokeBeforeDispatch) return;
6134
- const msg = ev.message;
6135
- this.reflexBuf += msg;
6136
- this.scrubStageDirections();
6137
- const m = this.reflexBuf.match(RESERVED_EVENT_MARKER) ?? this.reflexBuf.match(RESERVED_EVENT_OPENER);
6138
- if (m) {
6139
- this.fabricationCut = true;
6140
- log10.warn(`reflex fabricated a [task \u2026] event in its spoken stream \u2014 cutting it (kept ${m.index} chars)`);
6141
- const safe = this.reflexBuf.slice(this.reflexForwarded, m.index);
6142
- if (!safe) return;
6143
- if (safe.trim()) this.spokeThisTurn = true;
6144
- this.emitHost({ ...ev, message: safe });
6145
- return;
6146
- }
6147
- const held = this.reflexBuf.length - this.reflexForwarded;
6148
- const partial = held > 0 && /\[\s*t?a?s?k?$/i.test(this.reflexBuf.slice(-Math.min(held, 6)));
6149
- let upto = partial ? this.reflexBuf.length - this.reflexBuf.slice(-6).match(/\[\s*t?a?s?k?$/i)[0].length : this.reflexBuf.length;
6150
- const paren = this.reflexBuf.lastIndexOf("(");
6151
- if (paren >= this.reflexForwarded && !this.reflexBuf.includes(")", paren) && this.reflexBuf.length - paren <= 80)
6152
- upto = Math.min(upto, paren);
6153
- const out = this.reflexBuf.slice(this.reflexForwarded, upto);
6154
- this.reflexForwarded = upto;
6155
- if (!out) return;
6156
- if (out.trim()) this.spokeThisTurn = true;
6157
- this.emitHost({ ...ev, message: out });
6158
- return;
6159
- }
6160
- host.notify?.(ev);
6161
- }
6162
- };
6163
- this.voice = new Agent({
6164
- ai: o.ai,
6165
- fs: new MemFilesystem2(),
6166
- model: o.reflexModel,
6167
- stream: true,
6168
- host: voiceHost,
6169
- // The reflex IS the conversational channel — it confirms ambiguity inline ("did you mean…?"),
6170
- // never via the blocking AskUserQuestion tool (Agent auto-adds it whenever a host is set). Left in,
6171
- // it stalls a voice turn until the kill-switch. Worker questions still reach the user via parkQuestion.
6172
- askUserQuestion: false,
6173
- systemPrompt: prompt,
6174
- instructionFiles: false,
6175
- maxSteps: 8,
6176
- timeoutMs: 3e4,
6177
- ...o.reflexOptions,
6178
- tools,
6179
- // Composed AFTER the spread so the dispatch guard can't be dropped by reflexOptions.
6180
- hooks: composeHooks(this.dispatchGuard(), o.reflexOptions?.hooks)
6181
- });
6182
- }
6183
- /** Resolve memory tools + inject index into voice system prompt (once). */
6184
- async initMemory() {
6185
- if (!this.memoryReady) return;
6186
- const mem = await this.memoryReady;
6187
- this.memoryReady = void 0;
6188
- this.voice.options.tools.push(...mem.tools);
6189
- if (mem.index) this.voice.options.systemPrompt += "\n\n" + mem.index;
6190
6075
  }
6191
- /** Flush any held-back trailing fragment (a possible `[task` opener that never completed) once the
6192
- * turn's stream is done — so a legit message ending in "[t" isn't silently dropped. */
6193
- flushHeldReflexTail() {
6194
- if (this.fabricationCut) return;
6195
- this.scrubStageDirections();
6196
- const tail = this.reflexBuf.slice(this.reflexForwarded);
6197
- this.reflexForwarded = this.reflexBuf.length;
6198
- if (!tail) return;
6199
- if (tail.trim()) this.spokeThisTurn = true;
6200
- this.emitHost({ kind: "text_delta", message: tail });
6076
+ lastChunkAt = 0;
6077
+ // timestamp of the most recent mic chunk (0 = none yet)
6078
+ startedChunksAt = 0;
6079
+ // when capture started (grace before the first chunk)
6080
+ noAudioTimer = null;
6081
+ finalText = "";
6082
+ partialText = "";
6083
+ lastChangeAt = 0;
6084
+ lastCombined = "";
6085
+ endpointTimer = null;
6086
+ firstTokenAt = 0;
6087
+ // first speech token in current utterance
6088
+ constructor(options) {
6089
+ this.options = { ...new SonioxSTTOptions(), ...options };
6201
6090
  }
6202
- /** Remove complete stage-direction parentheticals from the UNFORWARDED reflex text (STAGE_DIRECTION_RE).
6203
- * Only the unforwarded region is touched — already-spoken audio can't be unsent, and splicing before
6204
- * reflexForwarded would corrupt the forward offset. */
6205
- scrubStageDirections() {
6206
- if (this.reflexForwarded >= this.reflexBuf.length) return;
6207
- const region = this.reflexBuf.slice(this.reflexForwarded);
6208
- const scrubbed = region.replace(/\([^()]*\)/g, (s) => STAGE_DIRECTION_RE.test(s) ? "" : s);
6209
- if (scrubbed !== region) this.reflexBuf = this.reflexBuf.slice(0, this.reflexForwarded) + scrubbed;
6091
+ get usingAec() {
6092
+ return this.options.source?.aec ?? false;
6210
6093
  }
6211
- /** Clear the per-turn guards. Called at the head of every voice turn (user send + re-voice flush). */
6212
- resetTurn() {
6213
- this.turnDispatched = false;
6214
- this.spokeBeforeDispatch = false;
6215
- this.turnBriefs.clear();
6216
- this.spokeThisTurn = false;
6217
- this.externalSpeech = false;
6218
- this.heldThisTurn = false;
6219
- this.reflexBuf = "";
6220
- this.reflexForwarded = 0;
6221
- this.fabricationCut = false;
6222
- this.turnFollowUp = false;
6223
- this.voice.options.toolChoice = void 0;
6094
+ async connectWs() {
6095
+ const apiKey = await resolveAuth(this.options.auth);
6096
+ this.ws = new WebSocket("wss://stt-rt.soniox.com/transcribe-websocket");
6097
+ await new Promise((res, rej) => {
6098
+ this.ws.onopen = () => res();
6099
+ this.ws.onerror = (e) => rej(new Error(`soniox ws: ${e.message || "connect failed"}`));
6100
+ });
6101
+ this.ws.send(
6102
+ JSON.stringify({
6103
+ api_key: apiKey,
6104
+ model: this.options.model,
6105
+ audio_format: "pcm_s16le",
6106
+ sample_rate: STT_SAMPLE_RATE,
6107
+ num_channels: 1,
6108
+ language_hints: this.options.languageHints,
6109
+ enable_endpoint_detection: true
6110
+ })
6111
+ );
6112
+ this.ws.onmessage = (ev) => this.handle(JSON.parse(String(ev.data)));
6113
+ this.ws.onclose = (ev) => {
6114
+ if (this.stopped) return;
6115
+ log10.warn(`soniox ws closed (${ev.code} ${ev.reason || ""}) \u2014 reconnecting`);
6116
+ this.diag("stt_ws_closed", { code: ev.code, reason: String(ev.reason || ""), reconnecting: true });
6117
+ this.reset();
6118
+ this.connectWs().catch((e) => {
6119
+ log10.error(`soniox reconnect failed: ${e.message}`);
6120
+ this.diag("stt_reconnect_failed", { message: e.message });
6121
+ });
6122
+ };
6224
6123
  }
6225
- /** preToolUse guard on the reflex: once it has dispatched this turn, a dispatch is "said my piece,
6226
- * now wait for the push" (CC's Task model). Block the temptations — TaskStatus polling and identical
6227
- * re-dispatch — so the only remaining move is to voice a short ack and end. A genuinely NEW Act is
6228
- * still allowed (parallel independent work). During a re-ack pass, block every tool. */
6229
- dispatchGuard() {
6230
- return {
6231
- preToolUse: (call) => {
6232
- if (this.spec?.state === "pending" && !_DuplexAgent.SPEC_SAFE_TOOLS.has(call.name)) {
6233
- log10.verbose(`speculation aborted: reflex called ${call.name} on unconfirmed input`);
6234
- this.abortSpeculation();
6235
- return { block: true, reason: "Speculative turn aborted." };
6124
+ async start() {
6125
+ await this.connectWs();
6126
+ if (this.sourceStarted) return;
6127
+ this.sourceStarted = true;
6128
+ this.endpointTimer = setInterval(() => {
6129
+ const combined = (this.finalText + this.partialText).trim();
6130
+ if (!combined || now() - this.lastChangeAt < this.options.silenceEndpointMs) return;
6131
+ if (this.firstTokenAt) log10.debug(`stt: ${Math.round(now() - this.firstTokenAt)}ms first-token\u2192silence-endpoint, "${combined.slice(0, 60)}"`);
6132
+ this.reset();
6133
+ this.onUtterance(combined, now());
6134
+ }, 120);
6135
+ this.endpointTimer.unref?.();
6136
+ this.startedChunksAt = now();
6137
+ const noAudioMs = this.options.noAudioTimeoutMs;
6138
+ if (noAudioMs > 0) {
6139
+ this.noAudioTimer = setInterval(() => {
6140
+ if (this.stopped) return;
6141
+ const ref = this.lastChunkAt || this.startedChunksAt;
6142
+ if (now() - ref > noAudioMs) {
6143
+ log10.error(`stt: no mic audio for >${Math.round(noAudioMs / 1e3)}s \u2014 capture device stopped delivering`);
6144
+ this.diag("stt_watchdog_fatal", { noAudioMs });
6145
+ this.onFatal("microphone stopped delivering audio (try a different input device, e.g. AirPods, or check System Settings \u2192 Sound \u2192 Input)");
6146
+ this.stop();
6236
6147
  }
6237
- if (this.nudging) return { block: true, reason: "Just say one short spoken acknowledgement \u2014 no tools this turn." };
6238
- if (!this.turnDispatched) return;
6239
- if (call.name === "TaskStatus")
6240
- 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." };
6241
- if ((call.name === "Act" || call.name === "Think") && this.turnBriefs.has(String(call.args?.brief ?? "")))
6242
- return { block: true, reason: "You already dispatched this exact task \u2014 acknowledge briefly and end your turn." };
6148
+ }, Math.max(250, Math.min(2e3, noAudioMs / 4)));
6149
+ this.noAudioTimer.unref?.();
6150
+ }
6151
+ await this.options.source.start((chunk) => {
6152
+ this.lastChunkAt = now();
6153
+ let sum = 0;
6154
+ const view = new DataView(chunk.buffer, chunk.byteOffset, chunk.byteLength);
6155
+ for (let i = 0; i + 1 < chunk.byteLength; i += 2) {
6156
+ const v = view.getInt16(i, true);
6157
+ sum += v * v;
6243
6158
  }
6244
- };
6245
- }
6246
- /** The host spoke on this turn's behalf OUTSIDE the reflex stream (e.g. the voice engine's adaptive
6247
- * micro-ack). For a DISPATCHED turn that's a sufficient ack (don't stack a second one); for an
6248
- * inline turn whose reply came back empty it is NOT — "One sec." followed by permanent silence is
6249
- * still dead air, so silentTurn ignores external speech unless work was dispatched. */
6250
- noteExternalSpeech() {
6251
- this.externalSpeech = true;
6252
- }
6253
- /** True when the just-finished turn voiced NOTHING — dead air to repair. Two ways this happens:
6254
- * (a) a dispatch with no spoken ack, and (b) an INLINE turn whose `final` channel came back empty —
6255
- * gpt-oss harmony sometimes puts the whole reply in `analysis` (→ thinking_delta, suppressed in
6256
- * voice) and emits an empty `final`, so no text_delta ever streams. Both ship silence; both repair.
6257
- * Requires a host: without one there's no stream to detect speech on (and no one to speak to). */
6258
- get silentTurn() {
6259
- const ackedByHost = this.externalSpeech && this.turnDispatched;
6260
- return !!this.options.host && !this.spokeThisTurn && !ackedByHost && !this.heldThisTurn;
6159
+ this.onLevel(Math.sqrt(sum / (chunk.byteLength / 2)));
6160
+ if (this.ws.readyState === WebSocket.OPEN) this.ws.send(chunk);
6161
+ });
6261
6162
  }
6262
- /** A turn that voiced nothing is dead air. Re-prompt the reflex ONCE so the LLM itself voices a short
6263
- * line (no template). If it STILL says nothing, fall back to a minimal line so silence never ships.
6264
- * Wording adapts to whether work was dispatched (an ack) or the inline reply was simply lost. */
6265
- async ackIfSilent(fallback) {
6266
- const dispatched = this.turnDispatched;
6267
- this.nudging = true;
6268
- try {
6269
- 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.");
6270
- } catch (e) {
6271
- log10.warn(`ack nudge failed: ${e instanceof Error ? e.message : e}`);
6272
- } finally {
6273
- this.nudging = false;
6163
+ handle(m) {
6164
+ if (m.error_message) {
6165
+ this.diag("stt_error", { message: String(m.error_message), code: m.error_code });
6166
+ return log10.error(`soniox: ${m.error_message}`);
6274
6167
  }
6275
- if (!this.spokeThisTurn) {
6276
- const pool = fallback ? [fallback] : dispatched ? _DuplexAgent.FALLBACK_ACKS : _DuplexAgent.FALLBACK_RETRY;
6277
- const fresh = pool.filter((p) => p !== this.lastFallback);
6278
- const line = (fresh.length ? fresh : pool)[Math.floor(Math.random() * (fresh.length || pool.length))];
6279
- this.lastFallback = line;
6280
- this.emitHost({ kind: "text_delta", message: line });
6168
+ let endpoint = false;
6169
+ for (const t of m.tokens ?? []) {
6170
+ if (t.text === "<end>") endpoint = true;
6171
+ else if (t.is_final) this.finalText += t.text;
6281
6172
  }
6282
- }
6283
- /** Dead-air fallback pools (see ackIfSilent). Both retry lines keep the 'say that again' phrase —
6284
- * hosts/tests key on it. */
6285
- static FALLBACK_ACKS = ["Okay, on it.", "On it.", "Alright, working on it."];
6286
- static FALLBACK_RETRY = ["Sorry, could you say that again?", "Hm, I missed that \u2014 could you say that again?"];
6287
- lastFallback = "";
6288
- /** One user turn: the voice agent streams the reply (and may Act/Think). Serialized with re-voice turns.
6289
- * If a speculative reflex call is pending and this content CONFIRMS it (the final matches the
6290
- * speculated partial), the in-flight call is adopted as THE turn: its buffered output flushes to the
6291
- * host NOW (this is the latency win) and streaming continues live. Any other content aborts the
6292
- * speculation first (rolled back silently) and runs a normal turn behind it. */
6293
- send(content) {
6294
- if (typeof content === "string" && isTrivialBarge(content) && this.hasParkedDelivery()) {
6295
- if (this.spec) this.abortSpeculation();
6296
- return this.enqueue(async () => {
6297
- this.resetTurn();
6298
- if (!this.redeliverParked()) this.awaitTrivialRedeliver = true;
6299
- return { text: "", steps: 0, finishReason: "stop", messages: [] };
6300
- });
6173
+ this.partialText = (m.tokens ?? []).filter((t) => !t.is_final && t.text !== "<end>").map((t) => t.text).join("");
6174
+ const combined = this.finalText + this.partialText;
6175
+ if (combined !== this.lastCombined) {
6176
+ this.lastCombined = combined;
6177
+ this.lastChangeAt = now();
6178
+ if (!this.firstTokenAt && combined.trim()) this.firstTokenAt = now();
6301
6179
  }
6302
- const spec = this.spec;
6303
- if (spec?.state === "pending") {
6304
- if (typeof content === "string" && speculationConfirms(spec.text, content)) {
6305
- spec.state = "confirmed";
6306
- spec.finalText = content;
6307
- for (const ev of spec.buf.splice(0)) this.options.host?.notify?.(ev);
6308
- spec.decide("confirm");
6309
- this.notify("diag", "speculation_confirmed", { text: spec.text.slice(0, 80) });
6310
- return spec.done;
6311
- }
6312
- this.abortSpeculation();
6180
+ this.onPartial(combined);
6181
+ if (endpoint && this.finalText.trim()) {
6182
+ const utterance = this.finalText.trim();
6183
+ if (this.firstTokenAt) log10.debug(`stt: ${Math.round(now() - this.firstTokenAt)}ms first-token\u2192endpoint, "${utterance.slice(0, 60)}"`);
6184
+ this.reset();
6185
+ this.onUtterance(utterance, now());
6313
6186
  }
6314
- return this.enqueue(async () => {
6315
- await this.initMemory();
6316
- this.resetTurn();
6317
- this.awaitTrivialRedeliver = false;
6318
- this.parkedRedeliver = [];
6319
- this.suppressParkedResume = true;
6320
- const res = await this.voice.send(content);
6321
- this.flushHeldReflexTail();
6322
- if (this.silentTurn) await this.ackIfSilent();
6323
- return res;
6324
- });
6325
6187
  }
6326
- /** Start a HELD speculative reflex turn on a stable partial (VoiceEngine.onSpeculate). Its spoken
6327
- * output buffers in emitHost; send() later confirms (flush + adopt) or aborts it. The turn holds the
6328
- * voice mutex until that decision (bounded by a safety timeout), so no other turn can interleave
6329
- * into the transcript between the speculative messages and their rollback. No-op if a speculation
6330
- * is already in flight. */
6331
- speculate(text) {
6332
- if (!text.trim() || this.spec) return;
6333
- let decide;
6334
- const decision = new Promise((r) => {
6335
- decide = r;
6188
+ reset() {
6189
+ this.finalText = "";
6190
+ this.partialText = "";
6191
+ this.lastCombined = "";
6192
+ this.firstTokenAt = 0;
6193
+ }
6194
+ stop() {
6195
+ this.stopped = true;
6196
+ if (this.endpointTimer) clearInterval(this.endpointTimer);
6197
+ if (this.noAudioTimer) clearInterval(this.noAudioTimer);
6198
+ this.options.source?.stop();
6199
+ if (this.ws) this.ws.onclose = null;
6200
+ this.ws?.close();
6201
+ }
6202
+ };
6203
+
6204
+ // node_modules/@bod.ee/voice/src/adapters/cartesia.ts
6205
+ var log11 = forComponent2("CartesiaTTS");
6206
+ var now2 = () => performance.now();
6207
+ var CartesiaTTSOptions = class {
6208
+ auth = "";
6209
+ voiceId = "";
6210
+ model = "sonic-3.5";
6211
+ /** 'apiKey' (server/CLI) → `api_key=` URL param; 'token' (browser, BE-minted) → `access_token=`. */
6212
+ authMode = "apiKey";
6213
+ };
6214
+ var CartesiaTTS = class _CartesiaTTS {
6215
+ options;
6216
+ ws;
6217
+ ctxSeq = 0;
6218
+ ctxId = "";
6219
+ onAudio = () => {
6220
+ };
6221
+ onDone = () => {
6222
+ };
6223
+ /** Word-level timestamps for karaoke reveal: `start[i]` = seconds from turn-audio start (absolute
6224
+ * across continuation chunks). Fired only when a consumer opts into reveal (see `wantTimestamps`). */
6225
+ onTimestamps = () => {
6226
+ };
6227
+ /** Request `add_timestamps` from Cartesia. Off by default (saves bandwidth) — the engine sets it
6228
+ * when revealMode==='word'. */
6229
+ wantTimestamps = false;
6230
+ /** Diagnostic tap (provider errors, circuit-breaker open/close, ws reconnects). Fire-and-forget:
6231
+ * a throwing handler disables itself — never affects synthesis. Wired by VoiceIO / the lab bridge. */
6232
+ onDiag = () => {
6233
+ };
6234
+ diagOn = true;
6235
+ diag(kind, fields) {
6236
+ if (!this.diagOn) return;
6237
+ try {
6238
+ this.onDiag({ t: now2(), kind, ...fields });
6239
+ } catch (e) {
6240
+ this.diagOn = false;
6241
+ log11.debug(`onDiag threw \u2014 TTS diagnostics disabled: ${e instanceof Error ? e.message : e}`);
6242
+ }
6243
+ }
6244
+ firstAudioAt = 0;
6245
+ /** Circuit breaker: consecutive error count + down flag. */
6246
+ consecutiveErrors = 0;
6247
+ consecutiveOk = 0;
6248
+ down = false;
6249
+ downAt = 0;
6250
+ probeTimer = null;
6251
+ static CB_THRESHOLD = 3;
6252
+ // open after 3 consecutive errors
6253
+ static CB_RECOVER_OK = 2;
6254
+ // close only after 2 consecutive good frames (no single-frame flap)
6255
+ static CB_PROBE_MS = 3e4;
6256
+ constructor(options) {
6257
+ this.options = { ...new CartesiaTTSOptions(), ...options };
6258
+ }
6259
+ closed = false;
6260
+ connecting = null;
6261
+ async connect() {
6262
+ this.closed = false;
6263
+ this.connecting = this.doConnect();
6264
+ await this.connecting;
6265
+ this.connecting = null;
6266
+ }
6267
+ async doConnect() {
6268
+ const key = await resolveAuth(this.options.auth);
6269
+ const param = this.options.authMode === "token" ? "access_token" : "api_key";
6270
+ this.ws = new WebSocket(`wss://api.cartesia.ai/tts/websocket?cartesia_version=2026-03-01&${param}=${key}`);
6271
+ await new Promise((res, rej) => {
6272
+ this.ws.onopen = () => res();
6273
+ this.ws.onerror = (e) => rej(new Error(`cartesia ws: ${e.message || "connect failed"}`));
6336
6274
  });
6337
- const spec = {
6338
- text,
6339
- state: "pending",
6340
- buf: [],
6341
- ctl: new AbortController(),
6342
- decide,
6343
- decision,
6344
- done: void 0
6345
- };
6346
- this.spec = spec;
6347
- spec.done = this.enqueue(async () => {
6348
- const empty = { text: "", steps: 0, finishReason: "aborted", messages: this.voice.transcript };
6349
- if (spec.state === "aborted") {
6350
- this.speculativeAbortedCalls++;
6351
- if (this.spec === spec) this.spec = void 0;
6352
- return empty;
6353
- }
6354
- await this.initMemory();
6355
- this.resetTurn();
6356
- const base = this.voice.transcript.length;
6357
- const prevSignal = this.voice.options.signal;
6358
- this.voice.options.signal = spec.ctl.signal;
6359
- let res;
6360
- try {
6361
- res = await this.voice.send(spec.text);
6362
- } catch (e) {
6363
- log10.warn(`speculative turn failed: ${e instanceof Error ? e.message : e}`);
6364
- } finally {
6365
- this.voice.options.signal = prevSignal;
6366
- }
6367
- const timer = setTimeout(() => {
6368
- spec.state = spec.state === "pending" ? "aborted" : spec.state;
6369
- spec.decide("abort");
6370
- }, 1e4);
6371
- timer.unref?.();
6372
- const d = await spec.decision;
6373
- clearTimeout(timer);
6374
- if (d === "abort") {
6375
- if (this.voice.transcript.length > base) this.voice.transcript.length = base;
6376
- this.speculativeAbortedCalls++;
6377
- log10.verbose(`speculation aborted (${this.speculativeAbortedCalls} total): "${spec.text.slice(0, 50)}"`);
6378
- if (this.spec === spec) this.spec = void 0;
6379
- return res ?? empty;
6275
+ this.ws.onclose = (ev) => {
6276
+ log11.warn(`cartesia ws closed (${ev.code} ${ev.reason || ""})`);
6277
+ this.diag("tts_ws_closed", { code: ev.code, reason: String(ev.reason || ""), reconnecting: !this.closed });
6278
+ if (!this.closed) {
6279
+ this.connecting = this.doConnect().catch((e) => {
6280
+ log11.error(`cartesia reconnect failed: ${e.message}`);
6281
+ this.diag("tts_reconnect_failed", { message: e.message });
6282
+ });
6380
6283
  }
6381
- for (let i = base; i < this.voice.transcript.length; i++) {
6382
- const m = this.voice.transcript[i];
6383
- if (m.role === "user" && contentText(m.content) === spec.text) {
6384
- m.content = spec.finalText;
6385
- break;
6284
+ };
6285
+ this.ws.onmessage = (ev) => {
6286
+ const m = JSON.parse(String(ev.data));
6287
+ if (m.context_id && m.context_id !== this.ctxId) return;
6288
+ if (m.type === "chunk" && m.data) {
6289
+ this.consecutiveErrors = 0;
6290
+ this.markRecovered();
6291
+ if (!this.firstAudioAt) this.firstAudioAt = now2();
6292
+ this.onAudio(base64ToBytes(m.data));
6293
+ } else if (m.type === "done") {
6294
+ this.consecutiveErrors = 0;
6295
+ this.markRecovered();
6296
+ this.onDone();
6297
+ } else if (m.type === "timestamps" && m.word_timestamps) {
6298
+ const wt = m.word_timestamps;
6299
+ if (wt.words?.length && wt.start?.length) this.onTimestamps(wt.words, wt.start);
6300
+ } else if (m.type === "error") {
6301
+ if (/already been cancelled|does not exist/.test(m.message || "")) return;
6302
+ this.consecutiveErrors++;
6303
+ this.diag("tts_error", { message: String(m.message || ""), code: m.status_code, contextId: m.context_id, consecutive: this.consecutiveErrors });
6304
+ if (!this.down && this.consecutiveErrors >= _CartesiaTTS.CB_THRESHOLD) {
6305
+ this.down = true;
6306
+ this.downAt = now2();
6307
+ this.consecutiveOk = 0;
6308
+ log11.warn(`TTS circuit breaker open \u2014 ${this.consecutiveErrors} consecutive errors, switching to text-only`);
6309
+ this.diag("tts_breaker_open", { errors: this.consecutiveErrors });
6310
+ this.onDone();
6311
+ this.startProbe();
6312
+ } else if (!this.down) {
6313
+ (/No valid transcripts/i.test(m.message || "") ? log11.debug : log11.warn)(`cartesia: ${JSON.stringify(m)}`);
6386
6314
  }
6387
6315
  }
6388
- this.spec = void 0;
6389
- this.flushHeldReflexTail();
6390
- if (this.silentTurn) await this.ackIfSilent();
6391
- return res ?? empty;
6392
- });
6316
+ };
6393
6317
  }
6394
- /** Abort a pending speculation (idempotent): kill the in-flight call, drop its buffered output.
6395
- * Called on divergence (send), a stale partial (VoiceEngine.onSpeculateAbort), a side-effect tool
6396
- * attempt (dispatchGuard), or host paths that will never dispatch a final (commands, voice-off). */
6397
- abortSpeculation() {
6398
- const spec = this.spec;
6399
- if (spec?.state !== "pending") return;
6400
- spec.state = "aborted";
6401
- spec.buf.length = 0;
6402
- spec.ctl.abort();
6403
- spec.decide("abort");
6404
- this.notify("diag", "speculation_aborted", { text: spec.text.slice(0, 80) });
6318
+ /** Close the breaker only after CB_RECOVER_OK consecutive good frames, so a single straggler chunk
6319
+ * after a 503 burst doesn't flap open→recover in <1s. A sub-2s down-window is a transient blip → debug. */
6320
+ markRecovered() {
6321
+ if (!this.down) return;
6322
+ if (++this.consecutiveOk < _CartesiaTTS.CB_RECOVER_OK) return;
6323
+ this.down = false;
6324
+ this.consecutiveOk = 0;
6325
+ this.stopProbe();
6326
+ const downMs = this.downAt ? now2() - this.downAt : 0;
6327
+ this.diag("tts_breaker_close", { downMs: Math.round(downMs) });
6328
+ (downMs < 2e3 ? log11.debug : log11.info)(`TTS recovered${downMs ? ` (down ${downMs}ms)` : ""}`);
6405
6329
  }
6406
- /** Cancel a running background task — shared by the CancelTask tool and the CLI /tasks picker. */
6407
- cancelTask(id) {
6408
- const rec = this.tasks.get(id);
6409
- if (!rec) return `No task '${id}'.`;
6410
- if (rec.status !== "running") return `Task ${rec.id} is already ${rec.status}.`;
6411
- rec.status = "cancelled";
6412
- rec.controller.abort();
6413
- return `Task ${rec.id} (${rec.label}) cancelled.`;
6330
+ /** Ensure the WS is open before sending — reconnects if idle-closed. */
6331
+ async ensureConnected() {
6332
+ if (this.connecting) await this.connecting;
6333
+ if (this.ws?.readyState !== WebSocket.OPEN) await this.connect();
6414
6334
  }
6415
- /** Barge-in: the user took the floor while task(s) were running. Suppress those tasks' remaining SPOKEN
6416
- * delivery so a superseded topic never talks over the new one (the debt-after-jokes regression). The
6417
- * tasks keep running and still fold their result into the transcript — recoverable, just not spoken.
6418
- * Returns the parked ids (for logging). Does NOT cancel: that's a deliberate reflex/user action. */
6419
- parkInFlightDeliveries() {
6420
- this.suppressParkedResume = false;
6421
- const parked = [];
6422
- for (const rec of this.tasks.values())
6423
- if (rec.status === "running" && !rec.deliveryParked) {
6424
- rec.deliveryParked = true;
6425
- parked.push(rec.id);
6426
- }
6427
- return parked;
6335
+ /** Prime the synthesis pipeline on a throwaway context right after connect: the FIRST synthesis on
6336
+ * a fresh WS pays Cartesia's cold spin-up (~1s+ live) — absorb it at mic-on instead of turn one.
6337
+ * The returned audio is discarded (engine drops onAudio while not speaking; once a real turn calls
6338
+ * newContext() any stragglers are stale-context-filtered). Respects the circuit breaker. */
6339
+ warmup() {
6340
+ if (this.down) return;
6341
+ this.newContext();
6342
+ if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(this.frame("Ok.", false));
6428
6343
  }
6429
- /** True while there is a parked delivery to potentially resume: either one already settled (queued) or
6430
- * one still running that was parked by a barge. */
6431
- hasParkedDelivery() {
6432
- return this.parkedRedeliver.length > 0 || [...this.tasks.values()].some((t) => t.status === "running" && t.deliveryParked);
6344
+ newContext() {
6345
+ this.ctxId = `ctx-${++this.ctxSeq}`;
6346
+ this.firstAudioAt = 0;
6347
+ return this.ctxId;
6433
6348
  }
6434
- /** Speak any settled-and-queued parked delivery now (trivial-barge resume). Returns false if nothing was
6435
- * queued yet (the caller then arms awaitTrivialRedeliver so the task resumes the instant it settles). */
6436
- redeliverParked() {
6437
- if (!this.parkedRedeliver.length) return false;
6438
- const text = this.parkedRedeliver.splice(0).join(" ").trim();
6439
- if (text) {
6440
- this.options.host?.notify?.({ kind: "speak_utterance", message: text });
6441
- this.notify("diag", "parked_redelivered", { chars: text.length });
6442
- }
6443
- return true;
6349
+ frame(transcript, cont) {
6350
+ return JSON.stringify({
6351
+ model_id: this.options.model,
6352
+ transcript,
6353
+ voice: { mode: "id", id: this.options.voiceId },
6354
+ output_format: { container: "raw", encoding: "pcm_s16le", sample_rate: TTS_SAMPLE_RATE },
6355
+ context_id: this.ctxId,
6356
+ continue: cont,
6357
+ ...this.wantTimestamps ? { add_timestamps: true } : {}
6358
+ });
6444
6359
  }
6445
- /** Resolve when all queued voice turns AND all in-flight worker tasks have settled (tests, graceful shutdown). */
6446
- async idle() {
6447
- while (true) {
6448
- const q2 = this.queue;
6449
- await q2.catch(() => {
6450
- });
6451
- await Promise.all([...this.tasks.values()].map((t) => t.promise));
6452
- if (this.queue === q2 && ![...this.tasks.values()].some((t) => t.status === "running")) return;
6453
- }
6360
+ speak(text, cont) {
6361
+ if (this.down) return;
6362
+ if (cont && !text) return;
6363
+ if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(this.frame(text, cont));
6364
+ else void this.ensureConnected().then(() => this.ws?.readyState === WebSocket.OPEN && this.ws.send(this.frame(text, cont)));
6454
6365
  }
6455
- /** Promise-chain mutex: turns run strictly one at a time; a failed turn doesn't poison the chain. */
6456
- enqueue(fn) {
6457
- const run = this.queue.then(fn, fn);
6458
- this.queue = run.then(() => {
6459
- }, () => {
6460
- });
6461
- return run;
6366
+ end() {
6367
+ if (this.down) {
6368
+ this.onDone();
6369
+ return;
6370
+ }
6371
+ if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(this.frame("", false));
6462
6372
  }
6463
- notify(kind, message, data) {
6464
- this.emitHost({ kind, message, data });
6373
+ cancel() {
6374
+ if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(JSON.stringify({ context_id: this.ctxId, cancel: true }));
6465
6375
  }
6466
- /** Host-boundary emit for the reflex's spoken channel: during a PENDING speculation, text_delta and
6467
- * hold_filler are BUFFERED (nothing may reach TTS on unconfirmed input); confirm flushes them in
6468
- * order, abort drops them silently. Everything else (task_* lifecycle, worker speak_utterance —
6469
- * which bypasses this via host.notify directly) passes through untouched. */
6470
- emitHost(ev) {
6471
- const spec = this.spec;
6472
- if (spec && (ev.kind === "text_delta" || ev.kind === "hold_filler")) {
6473
- if (spec.state === "pending") {
6474
- spec.buf.push(ev);
6376
+ startProbe() {
6377
+ if (this.probeTimer) return;
6378
+ this.probeTimer = setInterval(() => {
6379
+ if (!this.down) {
6380
+ this.stopProbe();
6475
6381
  return;
6476
6382
  }
6477
- if (spec.state === "aborted") return;
6383
+ this.consecutiveErrors = 0;
6384
+ this.newContext();
6385
+ if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(this.frame("Ok.", false));
6386
+ }, _CartesiaTTS.CB_PROBE_MS);
6387
+ this.probeTimer.unref?.();
6388
+ }
6389
+ stopProbe() {
6390
+ if (this.probeTimer) {
6391
+ clearInterval(this.probeTimer);
6392
+ this.probeTimer = null;
6478
6393
  }
6479
- this.options.host?.notify?.(ev);
6480
6394
  }
6481
- /** Queue a `[task …]` event for re-voicing. Events arriving while the voice is busy coalesce into ONE turn.
6482
- * `nonClean` (out-of-band boolean, set by the caller that KNOWS this event integrates a NON-CLEAN outcome)
6483
- * marks the coalesced flush as a non-clean integration turn — turn-eligibility, never inferred from event
6484
- * text and never keyed on a (re-authored) brief string. Any dispatch in such a turn is a follow-up. */
6485
- queueRevoice(event, nonClean = false) {
6486
- this.pendingEvents.push(event);
6487
- if (nonClean) this.pendingNonClean = true;
6488
- if (this.flushQueued) return;
6489
- this.flushQueued = true;
6490
- void this.enqueue(async () => {
6491
- this.flushQueued = false;
6492
- const events = this.pendingEvents.splice(0);
6493
- const nonCleanTurn = this.pendingNonClean;
6494
- this.pendingNonClean = false;
6495
- if (!events.length) return;
6496
- const failed = events.find((e) => /^\[task\b[^\]\n]*\bfailed\b/i.test(e));
6497
- this.resetTurn();
6498
- this.turnFollowUp = nonCleanTurn;
6499
- await this.voice.send(events.join("\n"));
6500
- this.flushHeldReflexTail();
6501
- if (this.silentTurn) await this.ackIfSilent(failed ? "Sorry, that didn't work \u2014 the task failed." : void 0);
6502
- this.notify("revoice_done", "");
6503
- });
6395
+ close() {
6396
+ this.closed = true;
6397
+ this.stopProbe();
6398
+ if (this.ws) this.ws.onclose = null;
6399
+ this.ws?.close();
6504
6400
  }
6505
- /** The worker's brief: the Act/Think args + a STATIC text snapshot of the recent conversation.
6506
- * Act briefs get a self-verify footer — the worker's report is trusted without review, so it
6507
- * must check its own work before reporting (nearly free under prompt caching; measured honest:
6508
- * it does NOT fix one-shot logic bugs — see mind/10). Think tasks are pure reasoning — no footer. */
6509
- buildBrief(brief, tier = "act", deliver = true) {
6510
- 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");
6511
- 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." : "";
6512
- const deliverContract = deliver ? `
6513
-
6514
- ## DELIVER (spoken delivery)
6515
- 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." : "") : "";
6516
- return `${nowLine()}.
6517
-
6518
- ` + (recent ? `${brief}
6401
+ };
6402
+ function base64ToBytes(b64) {
6403
+ if (typeof Buffer !== "undefined") return Buffer.from(b64, "base64");
6404
+ const bin = atob(b64);
6405
+ const out = new Uint8Array(bin.length);
6406
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
6407
+ return out;
6408
+ }
6519
6409
 
6520
- ## Recent conversation (for context)
6521
- ${recent}` : brief) + verify + deliverContract;
6522
- }
6523
- /** Spawn a detached worker for task `id`; its settlement notifies + enqueues the re-voice turn. */
6524
- spawnWorker(id, label, briefText, tier, brief, followUp) {
6525
- const o = this.options;
6526
- const tierOpts = tier === "think" ? o.thinkOptions : o.actOptions;
6527
- const tierModel = tier === "think" ? o.thinkModel : o.actModel;
6528
- const controller = new AbortController();
6529
- const base = tierOpts?.hooks ?? o.actOptions?.hooks;
6530
- const report = o.progressUpdates ? this.progressReporter(id) : void 0;
6531
- const tail = [];
6532
- const pushTail = (line) => {
6533
- tail.push(line.slice(0, 200));
6534
- if (tail.length > 120) tail.splice(0, tail.length - 120);
6535
- };
6536
- const hooks = {
6537
- ...base,
6538
- preToolUse: async (call, meta) => {
6539
- const d = await base?.preToolUse?.(call, meta);
6540
- pushTail(`\u2699 ${describeCall(call)}`);
6541
- report?.pre(call);
6542
- return d;
6543
- },
6544
- postToolUse: async (call, result, meta) => {
6545
- await base?.postToolUse?.(call, result, meta);
6546
- const last = result?.trim().split("\n").filter(Boolean).pop();
6547
- if (last) pushTail(` \u21B3 ${last}`);
6548
- report?.post(call);
6549
- },
6550
- onToolOutput: (call, chunk, meta) => {
6551
- base?.onToolOutput?.(call, chunk, meta);
6552
- report?.output(chunk);
6553
- }
6554
- };
6555
- const relayAsk = async (q2) => {
6556
- const opts = q2.options?.length ? ` Options: ${q2.options.map((x) => x.label).join(", ")}.` : "";
6557
- const a = await this.parkQuestion(id, `${q2.question}${opts}`);
6558
- return a || "(no answer from the user \u2014 use your best judgment and note the assumption)";
6559
- };
6560
- const splitter = new SpokenSplitter();
6561
- const speak = (seg) => {
6562
- if (!seg) return;
6563
- const r = this.tasks.get(id);
6564
- if (r) r.spokenText = (r.spokenText ? r.spokenText + " " : "") + seg;
6565
- if (!r?.deliveryParked) o.host?.notify?.({ kind: "speak_utterance", message: seg });
6566
- };
6567
- const coalescer = new SentenceCoalescer();
6568
- const feedSpoken = (s) => {
6569
- const ready = coalescer.feed(s);
6570
- if (ready) speak(ready);
6571
- };
6572
- const flushSpoken = () => speak(coalescer.flush());
6573
- const askBridge = o.askRelay ? { ask: relayAsk } : o.host?.ask ? { ask: (q2) => o.host.ask(q2) } : {};
6574
- const workerHost = {
6575
- ...askBridge,
6576
- notify: (ev) => {
6577
- if (ev?.kind === "text_delta" && typeof ev.message === "string") {
6578
- const { spoken, detail } = splitter.feed(ev.message);
6579
- feedSpoken(spoken);
6580
- if (detail.trim()) pushTail(detail.trim());
6581
- return;
6582
- }
6583
- }
6584
- };
6585
- const agentOpts = {
6586
- ai: o.ai,
6587
- fs: o.fs,
6588
- model: tierModel,
6589
- ...tier === "think" ? { reasoning: tierOpts?.reasoning ?? "high" } : {},
6590
- ...tierOpts,
6591
- // Recompute providerOptions for THIS worker's model (after tierOpts so it wins over any inherited
6592
- // main-template value) — prevents cursor-only cwd/cursorSession leaking onto an anthropic worker.
6593
- providerOptions: o.providerOptionsFor?.(tierModel),
6594
- stream: true,
6595
- // worker streams text_delta so the splitter can extract <spoken> live (after tierOpts: never overridden off)
6596
- host: workerHost,
6597
- // carries BOTH ask AND the <spoken>-splitting notify
6598
- ...hooks ? { hooks } : {},
6599
- signal: controller.signal
6600
- // shared with the checker so a cancel tears down both
6601
- };
6602
- const promise = new Agent(agentOpts).run(briefText).then((res) => {
6603
- const { spoken, detail } = splitter.flush();
6604
- feedSpoken(spoken);
6605
- if (detail.trim()) pushTail(detail.trim());
6606
- flushSpoken();
6607
- return res;
6608
- }).then((res) => this.maybeVerify(id, brief, res, tier, agentOpts, askBridge)).then((res) => this.onWorkerSettled(id, res)).catch((err2) => this.onWorkerFailed(id, err2));
6609
- this.tasks.set(id, { id, label, status: "running", controller, promise, tail, brief, followUp, splitter });
6610
- if (this.tasks.size > this.options.maxTaskRecords)
6611
- for (const [tid, rec] of this.tasks) {
6612
- if (this.tasks.size <= this.options.maxTaskRecords) break;
6613
- if (rec.status !== "running") this.tasks.delete(tid);
6614
- }
6615
- }
6616
- /** Fresh-context check of a successful Act task: a NEW agent (same model/fs/tools, but NO shared
6617
- * conversation context) re-reads the file state against the brief and fixes any gap. The fix lands
6618
- * on the shared fs automatically (workers write fs directly, no overlay), so grading sees the
6619
- * corrected state. Bounded to ONE pass. Off unless `verifyActTasks`; never runs for think/failed/
6620
- * cancelled tasks. Usage is merged so /cost reflects the real (worker + checker) spend. */
6621
- async maybeVerify(id, brief, res, tier, agentOpts, askBridge) {
6622
- if (!this.options.verifyActTasks || tier !== "act" || res.finishReason !== "stop") return res;
6623
- if (this.tasks.get(id)?.status === "cancelled") return res;
6624
- const { stream: _stream, host: _host, ...restOpts } = agentOpts;
6625
- const checkerOpts = {
6626
- ...restOpts,
6627
- ...askBridge.ask ? { host: { ask: askBridge.ask } } : {}
6628
- };
6629
- const checkBrief = `${this.buildBrief(brief, tier, false)}
6410
+ // src/voice/engine.ts
6411
+ init_logging();
6412
+ configureLogging((name) => {
6413
+ const l = forComponent(name);
6414
+ const at = (m) => (...a) => l[m]?.(...a);
6415
+ return { debug: at("debug"), verbose: at("verbose"), info: at("info"), warn: at("warn"), error: at("error") };
6416
+ });
6630
6417
 
6631
- ## VERIFY MODE
6632
- 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".`;
6633
- this.notify("task_verify", `task ${id}: verifying`, { id });
6634
- const cres = await new Agent(checkerOpts).run(checkBrief);
6635
- if (cres.finishReason !== "stop") {
6636
- log10.warn(`task ${id}: verify inconclusive (${cres.finishReason})`);
6637
- this.notify("task_verify", `task ${id}: verify inconclusive (${cres.finishReason})`, { id, finishReason: cres.finishReason });
6638
- }
6639
- const sum = (a = 0, b = 0) => a + b;
6640
- return {
6641
- ...res,
6642
- steps: res.steps + cres.steps,
6643
- // Merge the checker's messages so downstream tool-call/step accounting includes BOTH agents
6644
- // (else a verified task's toolCalls would undercount vs its steps/usage).
6645
- messages: [...res.messages, ...cres.messages],
6646
- usageEstimated: res.usageEstimated || cres.usageEstimated,
6647
- usage: res.usage && cres.usage ? {
6648
- promptTokens: sum(res.usage.promptTokens, cres.usage.promptTokens),
6649
- completionTokens: sum(res.usage.completionTokens, cres.usage.completionTokens),
6650
- totalTokens: sum(res.usage.totalTokens, cres.usage.totalTokens),
6651
- cacheCreationTokens: sum(res.usage.cacheCreationTokens, cres.usage.cacheCreationTokens),
6652
- cacheReadTokens: sum(res.usage.cacheReadTokens, cres.usage.cacheReadTokens)
6653
- } : res.usage ?? cres.usage
6654
- };
6655
- }
6656
- /** Throttled per-task progress: worker tool calls → at most one progress re-voice per interval.
6657
- * Two sources, one throttle: completed steps (post) and a heartbeat for a SINGLE long tool call
6658
- * (pre records the in-flight call; a self-cleaning timer narrates "still inside Bash — 70s").
6659
- * Completion supersedes: nothing is emitted once the task has settled. */
6660
- progressReporter(id) {
6661
- let lastAt = Date.now();
6662
- let steps = 0;
6663
- let inflight = null;
6664
- const due = () => {
6665
- if (this.pendingAsks.size) return void 0;
6666
- const rec = this.tasks.get(id);
6667
- return rec && rec.status === "running" && Date.now() - lastAt >= this.options.progressIntervalMs ? rec : void 0;
6668
- };
6669
- const emit = (rec, line, call) => {
6670
- lastAt = Date.now();
6671
- this.notify("task_progress", `task ${id} (${rec.label}): ${line}`, { id, steps, call: call.name });
6672
- this.queueRevoice(`[task ${id} progress] ${line}`);
6673
- };
6674
- const timer = setInterval(() => {
6675
- const rec = this.tasks.get(id);
6676
- if (!rec || rec.status !== "running") return clearInterval(timer);
6677
- if (!inflight || !due()) return;
6678
- const last = inflight.tail.trim().split("\n").filter(Boolean).pop()?.slice(-80);
6679
- 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);
6680
- }, Math.max(this.options.progressIntervalMs, 250));
6681
- timer.unref?.();
6682
- return {
6683
- pre: (call) => {
6684
- inflight = { call, at: Date.now(), tail: "" };
6685
- },
6686
- output: (chunk) => {
6687
- if (inflight) inflight.tail = (inflight.tail + chunk).slice(-500);
6688
- },
6689
- // digest only — NEVER re-voices directly
6690
- post: (call) => {
6691
- steps++;
6692
- inflight = null;
6693
- const rec = due();
6694
- if (rec) emit(rec, `still running \u2014 ${steps} steps so far, now: ${describeCall(call)}`, call);
6695
- }
6696
- };
6697
- }
6698
- /** Park a question under `askId` (a task id, or any unique key for permission asks): re-voices
6699
- * '[task <id> asks] …' and resolves with the user's answer via AnswerTask — or '' on timeout/
6700
- * task settle (callers map '' to deny / best-judgment). Workers never block forever. */
6701
- parkQuestion(askId, question) {
6702
- return new Promise((resolve4) => {
6703
- let settled = false;
6704
- const finish = (answer) => {
6705
- if (settled) return;
6706
- settled = true;
6707
- clearTimeout(timer);
6708
- this.pendingAsks.delete(askId);
6709
- resolve4(answer);
6710
- };
6711
- const timer = setTimeout(() => {
6712
- this.notify("task_ask_timeout", `task ${askId}: question timed out \u2014 proceeding without an answer`);
6713
- finish("");
6714
- }, this.options.askTimeoutMs);
6715
- this.pendingAsks.set(askId, { question, resolve: finish });
6716
- this.notify("task_ask", `task ${askId} asks: ${question}`, { id: askId, question });
6717
- this.queueRevoice(`[task ${askId} asks] ${question}
6718
- (Relay this to the user in your own words. When they answer, call AnswerTask with id "${askId}" and their answer.)`);
6719
- });
6720
- }
6721
- /** Resolve any question a settling/cancelled task left parked (its answer can no longer matter). */
6722
- dropAsk(id) {
6723
- this.pendingAsks.get(id)?.resolve("");
6724
- }
6725
- /** Build the INTEGRATION TURN prompt for a NON-CLEAN settled worker (early stop / failure). A clean
6726
- * success never reaches here — it streams its own `<spoken>` delivery during the run. For a partial
6727
- * or failed result the outcome re-enters the reflex as a decision (like a tool_result flowing back
6728
- * into a normal agent loop): the reflex evaluates the outcome against the original intent and chooses
6729
- * what to do next.
6730
- *
6731
- * Decision branches (the reflex acts on them with EXISTING tools — no new surface):
6732
- * • accept → SPEAK the (partial) result plainly — don't dress a failure up as success.
6733
- * • escalate → call `Think` with the SAME brief — only when Act failed/stalled AND a Think tier
6734
- * exists AND this task wasn't already a follow-up (one hop max). Wires the dead
6735
- * "Reserve Think for a problem Act already FAILED at" promise.
6736
- * • re-delegate→ call `Act` with a CORRECTED brief — for a recoverable error / partial result.
6737
- * • ask → ask the user ONE concrete question if genuinely blocked.
6738
- *
6739
- * Keeps the `[task <id> completed]` / `[task <id> failed]` opener so existing coalescing + the
6740
- * failed-revoice fallback still fire, and the per-event transcript markers stay intact. */
6741
- integrationPrompt(rec, outcome, body, finishReason) {
6742
- const opener = outcome === "error" ? `[task ${rec.id} failed]` : `[task ${rec.id} completed]`;
6743
- const underCap = this.autoEscalations < _DuplexAgent.MAX_AUTO_ESCALATIONS;
6744
- const canEscalate = (outcome === "error" || outcome === "incomplete") && underCap;
6745
- const hasThink = this.options.thinkModel !== false;
6746
- const options = [];
6747
- if (!rec.followUp && canEscalate && hasThink)
6748
- 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");
6749
- if (!rec.followUp && canEscalate)
6750
- options.push("RE-DELEGATE to Act with a corrected brief if the failure looks recoverable (a wrong path, a fixable mistake)");
6751
- options.push("ASK the user one short, concrete question if you genuinely cannot proceed without their input");
6752
- options.push("ACCEPT and tell the user plainly what happened (don't dress a failure up as success)");
6753
- 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.`;
6754
- const state = outcome === "error" ? `the worker FAILED with: ${body}` : `the worker STOPPED EARLY (${finishReason}) \u2014 its result is PARTIAL, not a finished success: ${body}`;
6755
- return `${opener} Original request: "${rec.brief}". Outcome: ${state}.${decision}`;
6756
- }
6757
- onWorkerSettled(id, res) {
6758
- this.dropAsk(id);
6759
- const rec = this.tasks.get(id);
6760
- if (res.finishReason === "aborted" || rec.status === "cancelled") {
6761
- rec.status = "cancelled";
6762
- this.notify("task_cancelled", `task ${id} (${rec.label}) cancelled`);
6763
- return;
6764
- }
6765
- if (res.finishReason === "error") {
6766
- const msg = res.error instanceof Error ? res.error.message : String(res.error ?? "unknown error");
6767
- return this.failTask(rec, msg);
6768
- }
6769
- rec.status = "done";
6770
- rec.result = res.text;
6771
- const incomplete = res.finishReason !== "stop";
6772
- log10.verbose(`task ${id} done (${res.steps} steps${incomplete ? `, INCOMPLETE: ${res.finishReason}` : ""})`);
6773
- this.notify("task_done", `task ${id} (${rec.label}) completed`, {
6774
- id,
6775
- text: res.text,
6776
- usage: res.usage,
6777
- usageEstimated: res.usageEstimated,
6778
- finishReason: res.finishReason,
6779
- steps: res.steps,
6780
- toolCalls: res.messages.filter((m) => m.role === "tool").length
6781
- });
6782
- if (incomplete) {
6783
- return this.queueRevoice(this.integrationPrompt(rec, "incomplete", res.text, res.finishReason), true);
6418
+ // src/duplex.ts
6419
+ var log12 = forComponent("DuplexAgent");
6420
+ function describeCall(call) {
6421
+ const v = call.args && Object.values(call.args).find((x) => typeof x === "string" && x.trim());
6422
+ const hint = v ? ` (${String(v).replace(/\s+/g, " ").trim().slice(0, 48)})` : "";
6423
+ return `${call.name}${hint}`;
6424
+ }
6425
+ var DuplexAgentOptions = class {
6426
+ /** Any ai.libx.js AIClient — shared by all tiers (routed by model). */
6427
+ ai;
6428
+ /** The WORKER's filesystem (act + think). If omitted the worker keeps Agent's jailed-disk-at-cwd default. */
6429
+ fs;
6430
+ // The reflex IS the voice. 120b (not 20b) for channel discipline + instruction-following: the 20b
6431
+ // mislabels gpt-oss harmony channels under load, leaking raw analysis into the spoken `final` channel
6432
+ // (and misfiring Hold). 120b is the same price tier (~$0.15/$0.60) — the quality/cost trade is free.
6433
+ reflexModel = "groq/openai/gpt-oss-120b";
6434
+ actModel = "anthropic/claude-sonnet-4-6";
6435
+ /** Premium reasoning model. Set to `false` to disable the Think tier entirely. */
6436
+ thinkModel = "anthropic/claude-opus-4-8";
6437
+ /** Per-worker providerOptions, derived from the worker's actual model at spawn time (IoC — keeps duplex
6438
+ * provider-agnostic). Workers override the reflex/main model, so provider-specific options (e.g. cursor's
6439
+ * cwd/cursorSession) must be recomputed for the worker's model, never inherited from the main template —
6440
+ * leaking cursor options to an anthropic worker is a hard 400. Returns undefined → no providerOptions. */
6441
+ providerOptionsFor;
6442
+ /** Escape hatches merged over the derived per-agent options. */
6443
+ reflexOptions;
6444
+ actOptions;
6445
+ thinkOptions;
6446
+ /** Fresh-context check on each successful Act task: a NEW agent (no self-confirmation bias) re-reads
6447
+ * the file state against the brief and fixes any gap before the result is re-voiced. Bounded to one
6448
+ * pass; ~2x Act cost so default OFF. The self-verify FOOTER (same context) was measured ineffective —
6449
+ * this is the structural fix (see mind/10). Think tasks are pure reasoning, never checked. */
6450
+ verifyActTasks = false;
6451
+ /** Receives the voice text_delta stream + task lifecycle events. */
6452
+ host;
6453
+ /** How many recent transcript messages are rendered into a worker's brief. */
6454
+ excerptTurns = 6;
6455
+ /** Voice register: 'neutral' = clean spoken style; 'conversational' = human-like — fillers,
6456
+ * backchannels, impulsive first reactions before content (mimics real duplex conversation). */
6457
+ voiceStyle = "neutral";
6458
+ /** Teach the model to emit inline `[emotion]` tags for Cartesia emotion control. Only set when the
6459
+ * TTS actually speaks them — text-duplex (no TTS) would otherwise print literal tags. */
6460
+ emotionTags = false;
6461
+ /** Awaited BEFORE a worker spawns — open a per-task checkpoint frame, audit, etc.
6462
+ * (post-spawn would race the worker's first edits). */
6463
+ onTaskStart;
6464
+ /** Re-voice throttled worker progress asides ('[task t1 progress] …') so long tasks aren't dead
6465
+ * air. Off by default — each update costs a voice turn (LLM call + speech). */
6466
+ progressUpdates = false;
6467
+ /** Min ms between progress re-voices per task. */
6468
+ progressIntervalMs = 25e3;
6469
+ /** Relay worker questions (AskUserQuestion + permission asks via parkQuestion) through the VOICE:
6470
+ * the question re-voices as '[task <id> asks] …', the user answers conversationally, and the
6471
+ * voice model resolves it with the AnswerTask tool. Off → host.ask passthrough (text menus). */
6472
+ askRelay = false;
6473
+ /** Parked questions auto-resolve empty after this long (callers map '' to deny/best-judgment). */
6474
+ askTimeoutMs = 12e4;
6475
+ /** Max retained task records: oldest SETTLED tasks (and their activity tails) are evicted past this,
6476
+ * bounding memory over a long-lived session. Running tasks are never evicted. */
6477
+ maxTaskRecords = 50;
6478
+ /** Host overrides for QuickLook lookups (keyed by `what`). The engine's defaults go through the
6479
+ * (possibly jailed) fs — e.g. `.git/**` is deny-listed, so the CLI supplies 'branch' itself. */
6480
+ quickLook;
6481
+ /** Memory directory/directories on the WORKER fs. If set, the voice agent gets Remember + Recall
6482
+ * tools directly (no delegation needed) and implicit capture guidance. */
6483
+ memoryDir;
6484
+ /** User-scope memory dir for global facts (type=user/feedback). Forwarded to Remember's routing. */
6485
+ memoryUserDir;
6486
+ };
6487
+ var RESERVED_EVENT_MARKER = /\[task\b[^\]\n]*\b(?:completed|failed|progress|asks)\b/i;
6488
+ var RESERVED_EVENT_OPENER = /\[\s*task\b/i;
6489
+ var STAGE_DIRECTION_RE = /^\(\s*(?:(?:waiting|checking|searching|thinking|processing|loading|working|fetching|looking)\b[^)]*|[^)]*(?:\.\.\.|…)\s*)\)$/i;
6490
+ function nowLine() {
6491
+ 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" })}`;
6492
+ }
6493
+ function isTrivialBarge(text) {
6494
+ const t = text.trim().toLowerCase().replace(/[.,!?…\s]+$/g, "").replace(/^[.,!?…\s]+/, "");
6495
+ if (!t) return false;
6496
+ 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;
6497
+ const core = t.replace(/^(?:oh|um+|uh+|er+|hmm+|ah+|well|so|okay|ok|yeah|yep)[\s,]+/, "").trim();
6498
+ 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);
6499
+ }
6500
+ 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.';
6501
+ 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.";
6502
+ var THINK_DISABLED_GUIDANCE = "(Think tier is not available \u2014 use Act for all escalations.)";
6503
+ 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).`;
6504
+ 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(", ")}.`;
6505
+ var DuplexAgent = class _DuplexAgent {
6506
+ options;
6507
+ voice;
6508
+ tasks = /* @__PURE__ */ new Map();
6509
+ queue = Promise.resolve();
6510
+ seq = 0;
6511
+ pendingEvents = [];
6512
+ /** Spoken text of parked deliveries that have SETTLED, awaiting a trivial-barge resume decision on the
6513
+ * next turn (a substantive turn clears it — the result stays in the transcript, recoverable by asking). */
6514
+ parkedRedeliver = [];
6515
+ /** A trivial barge arrived while a parked delivery was STILL RUNNING → resume it the moment it settles. */
6516
+ awaitTrivialRedeliver = false;
6517
+ /** Set by a SUBSTANTIVE turn after a barge: the user moved on, so a parked delivery that settles LATER
6518
+ * must NOT arm a resume (else a much-later "go on" replays a stale result). Reset by a fresh barge. */
6519
+ suppressParkedResume = false;
6520
+ /** Out-of-band follow-up attribution for the events coalescing into the next flush turn: TRUE iff ≥1 of
6521
+ * the tasks being integrated was NON-CLEAN (early-stop/failure). Carried out-of-band on the enqueue call
6522
+ * by the caller that KNOWS the outcome — a plain boolean the MODEL CANNOT PERTURB. It is NOT scanned from
6523
+ * worker-authored event text (v1: an "Outcome:" substring over-stamped siblings) and NOT keyed on a brief
6524
+ * string the reflex re-authors (v2: a paraphrased escalation brief missed the Set → followUp:false →
6525
+ * RE-ENABLED unbounded auto-escalation, the dangerous runaway direction). See [[wrong-discriminator]] /
6526
+ * [[drive-real-reflex]] / [[fakeaiclient-blind-to-wire-format]]. */
6527
+ pendingNonClean = false;
6528
+ flushQueued = false;
6529
+ /** Per-voice-turn guards (reset by resetTurn at each turn's start). The reflex is a weak model:
6530
+ * left unguarded it polls TaskStatus after a dispatch and/or dispatches silently (dead air).
6531
+ * Like CC's Task tool, a dispatch is "said my piece, now wait for the push" — these enforce that. */
6532
+ turnDispatched = false;
6533
+ // an Act/Think fired this turn
6534
+ spokeBeforeDispatch = false;
6535
+ // the reflex ALREADY acked before dispatching — the forced post-dispatch text step must stay silent (live: "Got it…" twice)
6536
+ turnBriefs = /* @__PURE__ */ new Set();
6537
+ // briefs dispatched this turn (detect identical re-dispatch)
6538
+ spokeThisTurn = false;
6539
+ // any non-empty text_delta streamed this turn
6540
+ externalSpeech = false;
6541
+ // host spoke on our behalf (adaptive micro-ack) — not reflex output
6542
+ heldThisTurn = false;
6543
+ // Hold called this turn → turn is INTENTIONALLY silent (suppress reflex text + no dead-air ack)
6544
+ nudging = false;
6545
+ // re-ack pass in flight: block ALL tools, prevent recursion
6546
+ reflexBuf = "";
6547
+ // accumulated reflex text this turn (fabricated-event detection)
6548
+ reflexForwarded = 0;
6549
+ // chars of reflexBuf already forwarded to the host/TTS
6550
+ fabricationCut = false;
6551
+ // reflex emitted a reserved [task …] marker → suppress its tail
6552
+ /** TRUE for the duration of a re-voice turn that is integrating ≥1 NON-CLEAN task (turn-eligibility,
6553
+ * carried out-of-band — NOT derived from any worker/brief string). ANY Act/Think dispatched in such a
6554
+ * turn is stamped followUp:true. This GUARANTEES the dangerous direction is impossible: a genuine
6555
+ * escalation (even one with a paraphrased brief) ALWAYS lands in a non-clean integration turn, so it is
6556
+ * ALWAYS recognized as a follow-up and CANNOT re-escalate (one hop). The single-dispatch-per-turn guard
6557
+ * means at most one dispatch happens per flush, so realistically "the one dispatch IS the escalation".
6558
+ * ACCEPTED SAFE-DIRECTION ERROR: if the reflex instead dispatches FRESH unrelated work during a non-clean
6559
+ * flush (rare — and only possible when it batches multiple calls in one step, bypassing the guard), that
6560
+ * fresh task is over-stamped followUp:true and forgoes ONE future auto-escalation. That is SAFE (it only
6561
+ * ever REMOVES a future escalation, never adds one — no runaway) and is the correct side to err on. */
6562
+ turnFollowUp = false;
6563
+ /** Hard absolute backstop against runaway regardless of attribution: total automatic escalations across
6564
+ * the whole conversation. Once it hits MAX_AUTO_ESCALATIONS, no integration turn offers escalate/re-delegate. */
6565
+ autoEscalations = 0;
6566
+ static MAX_AUTO_ESCALATIONS = 8;
6567
+ /** Parked worker questions awaiting a (voice-relayed) user answer, keyed by ask id. */
6568
+ pendingAsks = /* @__PURE__ */ new Map();
6569
+ /** SPECULATIVE REFLEX (VoiceEngine.onSpeculate → speculate()): the reflex turn starts on a stable
6570
+ * PARTIAL transcript, its spoken output buffered — nothing reaches TTS until the endpointed final
6571
+ * confirms via send() (which flushes the buffer and adopts the call as THE turn). A divergent final
6572
+ * aborts it: output dropped, history rolled back, the final dispatches normally. */
6573
+ spec;
6574
+ /** Aborted speculative calls (double-billing visibility — each one paid for tokens never spoken). */
6575
+ speculativeAbortedCalls = 0;
6576
+ /** Tools the reflex may execute on UNCONFIRMED (speculated) input — read-only lookups and the
6577
+ * intentionally-silent Hold. Anything else (Act/Think/AnswerTask/CancelTask/ExitSession/memory
6578
+ * writes/…) is a side effect on input the user may not have said: the guard ABORTS the speculation
6579
+ * instead (the endpointed final then dispatches normally and may use the tool for real). */
6580
+ static SPEC_SAFE_TOOLS = /* @__PURE__ */ new Set(["QuickLook", "TaskStatus", "Hold"]);
6581
+ /** Lazily resolved memory tools (async loadMemory runs in initMemory). */
6582
+ memoryReady;
6583
+ constructor(options) {
6584
+ this.options = { ...new DuplexAgentOptions(), ...options };
6585
+ const o = this.options;
6586
+ if (o.memoryDir && o.fs) {
6587
+ this.memoryReady = loadMemory(o.fs, o.memoryDir, { maxWritesPerSession: 10, userDir: o.memoryUserDir });
6784
6588
  }
6785
- const tail = rec.splitter?.flush();
6786
- if (tail?.spoken && !rec.deliveryParked) this.options.host?.notify?.({ kind: "speak_utterance", message: tail.spoken });
6787
- if (res.text.trim()) this.voice.transcript.push({ role: "assistant", content: res.text });
6788
- if (rec.deliveryParked && !this.suppressParkedResume) {
6789
- const gist = (rec.spokenText ?? "").trim() || res.text.trim();
6790
- if (gist) {
6791
- if (this.awaitTrivialRedeliver) {
6792
- this.awaitTrivialRedeliver = false;
6793
- this.options.host?.notify?.({ kind: "speak_utterance", message: gist });
6794
- this.notify("diag", "parked_redelivered", { chars: gist.length });
6795
- } else this.parkedRedeliver.push(gist);
6589
+ 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.";
6590
+ const thinkSlot = o.thinkModel !== false ? THINK_GUIDANCE : THINK_DISABLED_GUIDANCE;
6591
+ const workerToolNames = (o.actOptions?.tools ?? []).map((t) => t.name);
6592
+ const canSearch = workerToolNames.some((n) => /WebSearch/i.test(n));
6593
+ const canFetch = workerToolNames.some((n) => /WebFetch/i.test(n));
6594
+ 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)" : "";
6595
+ const mcpNames = [
6596
+ ...Object.keys(o.actOptions?.providerOptions?.mcpServers ?? {}),
6597
+ ...new Set(workerToolNames.filter((n) => n.startsWith("mcp__")).map((n) => n.slice(5).split("__")[0]))
6598
+ ];
6599
+ 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' : "") : "";
6600
+ 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 : "") + `
6601
+ ${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.`;
6602
+ const tools = [
6603
+ ...o.reflexOptions?.tools ?? [],
6604
+ this.actTool(),
6605
+ ...o.thinkModel !== false ? [this.thinkTool()] : [],
6606
+ this.taskStatusTool(),
6607
+ this.cancelTaskTool(),
6608
+ this.quickLookTool(),
6609
+ this.answerTaskTool(),
6610
+ this.holdTool()
6611
+ ];
6612
+ const host = o.host;
6613
+ const voiceHost = host && {
6614
+ ask: host.ask ? (q2) => host.ask(q2) : void 0,
6615
+ confirm: host.confirm ? (p, m) => host.confirm(p, m) : void 0,
6616
+ notify: (ev) => {
6617
+ if (ev?.kind === "text_delta" && typeof ev.message === "string") {
6618
+ if (this.heldThisTurn) return;
6619
+ if (this.fabricationCut) return;
6620
+ if (this.turnDispatched && this.spokeBeforeDispatch) return;
6621
+ const msg = ev.message;
6622
+ this.reflexBuf += msg;
6623
+ this.scrubStageDirections();
6624
+ const m = this.reflexBuf.match(RESERVED_EVENT_MARKER) ?? this.reflexBuf.match(RESERVED_EVENT_OPENER);
6625
+ if (m) {
6626
+ this.fabricationCut = true;
6627
+ log12.warn(`reflex fabricated a [task \u2026] event in its spoken stream \u2014 cutting it (kept ${m.index} chars)`);
6628
+ const safe = this.reflexBuf.slice(this.reflexForwarded, m.index);
6629
+ if (!safe) return;
6630
+ if (safe.trim()) this.spokeThisTurn = true;
6631
+ this.emitHost({ ...ev, message: safe });
6632
+ return;
6633
+ }
6634
+ const held = this.reflexBuf.length - this.reflexForwarded;
6635
+ const partial = held > 0 && /\[\s*t?a?s?k?$/i.test(this.reflexBuf.slice(-Math.min(held, 6)));
6636
+ let upto = partial ? this.reflexBuf.length - this.reflexBuf.slice(-6).match(/\[\s*t?a?s?k?$/i)[0].length : this.reflexBuf.length;
6637
+ const paren = this.reflexBuf.lastIndexOf("(");
6638
+ if (paren >= this.reflexForwarded && !this.reflexBuf.includes(")", paren) && this.reflexBuf.length - paren <= 80)
6639
+ upto = Math.min(upto, paren);
6640
+ const out = this.reflexBuf.slice(this.reflexForwarded, upto);
6641
+ this.reflexForwarded = upto;
6642
+ if (!out) return;
6643
+ if (out.trim()) this.spokeThisTurn = true;
6644
+ this.emitHost({ ...ev, message: out });
6645
+ return;
6646
+ }
6647
+ host.notify?.(ev);
6796
6648
  }
6797
- }
6798
- if (!rec.splitter?.spokeAny && res.text.trim() && !rec.deliveryParked)
6799
- this.options.host?.notify?.({ kind: "speak_utterance", message: res.text });
6649
+ };
6650
+ this.voice = new Agent({
6651
+ ai: o.ai,
6652
+ fs: new MemFilesystem2(),
6653
+ model: o.reflexModel,
6654
+ stream: true,
6655
+ host: voiceHost,
6656
+ // The reflex IS the conversational channel — it confirms ambiguity inline ("did you mean…?"),
6657
+ // never via the blocking AskUserQuestion tool (Agent auto-adds it whenever a host is set). Left in,
6658
+ // it stalls a voice turn until the kill-switch. Worker questions still reach the user via parkQuestion.
6659
+ askUserQuestion: false,
6660
+ systemPrompt: prompt,
6661
+ instructionFiles: false,
6662
+ maxSteps: 8,
6663
+ timeoutMs: 3e4,
6664
+ ...o.reflexOptions,
6665
+ tools,
6666
+ // Composed AFTER the spread so the dispatch guard can't be dropped by reflexOptions.
6667
+ hooks: composeHooks(this.dispatchGuard(), o.reflexOptions?.hooks)
6668
+ });
6800
6669
  }
6801
- onWorkerFailed(id, err2) {
6802
- this.failTask(this.tasks.get(id), err2 instanceof Error ? err2.message : String(err2));
6670
+ /** Resolve memory tools + inject index into voice system prompt (once). */
6671
+ async initMemory() {
6672
+ if (!this.memoryReady) return;
6673
+ const mem = await this.memoryReady;
6674
+ this.memoryReady = void 0;
6675
+ this.voice.options.tools.push(...mem.tools);
6676
+ if (mem.index) this.voice.options.systemPrompt += "\n\n" + mem.index;
6803
6677
  }
6804
- failTask(rec, msg) {
6805
- this.dropAsk(rec.id);
6806
- rec.status = "error";
6807
- rec.result = msg;
6808
- log10.warn(`task ${rec.id} failed: ${msg}`);
6809
- this.notify("task_error", `task ${rec.id} (${rec.label}) failed: ${msg}`);
6810
- this.queueRevoice(this.integrationPrompt(rec, "error", msg, "error"), true);
6678
+ /** Flush any held-back trailing fragment (a possible `[task` opener that never completed) once the
6679
+ * turn's stream is done — so a legit message ending in "[t" isn't silently dropped. */
6680
+ flushHeldReflexTail() {
6681
+ if (this.fabricationCut) return;
6682
+ this.scrubStageDirections();
6683
+ const tail = this.reflexBuf.slice(this.reflexForwarded);
6684
+ this.reflexForwarded = this.reflexBuf.length;
6685
+ if (!tail) return;
6686
+ if (tail.trim()) this.spokeThisTurn = true;
6687
+ this.emitHost({ kind: "text_delta", message: tail });
6811
6688
  }
6812
- // --- voice tools (closures over this instance) ---
6813
- /** Live-switch the think tier: `false` disables (removes the Think tool from the voice agent),
6814
- * a model id enables (adds the tool if missing). The system-prompt THINK_SLOT text is frozen at
6815
- * construction — the tool's own description carries the routing guidance, so a live enable works;
6816
- * dispatch()'s think→act fallback covers any straggler calls after a live disable. */
6817
- setThinkModel(model) {
6818
- this.options.thinkModel = model;
6819
- const tools = this.voice.options.tools;
6820
- const i = tools.findIndex((t) => t.name === "Think");
6821
- if (model === false && i >= 0) tools.splice(i, 1);
6822
- else if (model !== false && i < 0) tools.push(this.thinkTool());
6689
+ /** Remove complete stage-direction parentheticals from the UNFORWARDED reflex text (STAGE_DIRECTION_RE).
6690
+ * Only the unforwarded region is touched — already-spoken audio can't be unsent, and splicing before
6691
+ * reflexForwarded would corrupt the forward offset. */
6692
+ scrubStageDirections() {
6693
+ if (this.reflexForwarded >= this.reflexBuf.length) return;
6694
+ const region = this.reflexBuf.slice(this.reflexForwarded);
6695
+ const scrubbed = region.replace(/\([^()]*\)/g, (s) => STAGE_DIRECTION_RE.test(s) ? "" : s);
6696
+ if (scrubbed !== region) this.reflexBuf = this.reflexBuf.slice(0, this.reflexForwarded) + scrubbed;
6823
6697
  }
6824
- /** User/programmatic spawn: the CLI's /act and /think commands. Returns the task id.
6825
- * `followUp` marks an automatic escalation/re-delegation (set by the integration turn) so the new
6826
- * task's own integration turn won't escalate again — capping auto-follow-ups to one hop. */
6827
- async dispatch(brief, tier = "act", label, followUp = false) {
6828
- if (tier === "think" && this.options.thinkModel === false) tier = "act";
6829
- if (followUp) this.autoEscalations++;
6830
- const id = `t${++this.seq}`;
6831
- const lbl = label ?? tier;
6832
- await this.options.onTaskStart?.(id, lbl);
6833
- this.spawnWorker(id, lbl, this.buildBrief(brief, tier), tier, brief, followUp);
6834
- this.notify("task_started", `task ${id} (${lbl}) started`, { id, brief, tier });
6835
- return id;
6698
+ /** Clear the per-turn guards. Called at the head of every voice turn (user send + re-voice flush). */
6699
+ resetTurn() {
6700
+ this.turnDispatched = false;
6701
+ this.spokeBeforeDispatch = false;
6702
+ this.turnBriefs.clear();
6703
+ this.spokeThisTurn = false;
6704
+ this.externalSpeech = false;
6705
+ this.heldThisTurn = false;
6706
+ this.reflexBuf = "";
6707
+ this.reflexForwarded = 0;
6708
+ this.fabricationCut = false;
6709
+ this.turnFollowUp = false;
6710
+ this.voice.options.toolChoice = void 0;
6836
6711
  }
6837
- actTool() {
6712
+ /** preToolUse guard on the reflex: once it has dispatched this turn, a dispatch is "said my piece,
6713
+ * now wait for the push" (CC's Task model). Block the temptations — TaskStatus polling and identical
6714
+ * re-dispatch — so the only remaining move is to voice a short ack and end. A genuinely NEW Act is
6715
+ * still allowed (parallel independent work). During a re-ack pass, block every tool. */
6716
+ dispatchGuard() {
6838
6717
  return {
6839
- name: "Act",
6840
- 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).',
6841
- parameters: {
6842
- type: "object",
6843
- required: ["brief"],
6844
- properties: {
6845
- brief: { type: "string", description: "full, self-contained instructions for the worker" },
6846
- label: { type: "string", description: "a short (2-4 word) label for the task" }
6718
+ preToolUse: (call) => {
6719
+ if (this.spec?.state === "pending" && !_DuplexAgent.SPEC_SAFE_TOOLS.has(call.name)) {
6720
+ log12.verbose(`speculation aborted: reflex called ${call.name} on unconfirmed input`);
6721
+ this.abortSpeculation();
6722
+ return { block: true, reason: "Speculative turn aborted." };
6847
6723
  }
6848
- },
6849
- run: async ({ brief, label }) => {
6850
- this.spokeBeforeDispatch = this.spokeThisTurn;
6851
- this.turnDispatched = true;
6852
- this.turnBriefs.add(String(brief ?? ""));
6853
- this.voice.options.toolChoice = "none";
6854
- const id = await this.dispatch(String(brief ?? ""), "act", label ? String(label) : void 0, this.turnFollowUp);
6855
- 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.`;
6724
+ if (this.nudging) return { block: true, reason: "Just say one short spoken acknowledgement \u2014 no tools this turn." };
6725
+ if (!this.turnDispatched) return;
6726
+ if (call.name === "TaskStatus")
6727
+ 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." };
6728
+ if ((call.name === "Act" || call.name === "Think") && this.turnBriefs.has(String(call.args?.brief ?? "")))
6729
+ return { block: true, reason: "You already dispatched this exact task \u2014 acknowledge briefly and end your turn." };
6856
6730
  }
6857
6731
  };
6858
6732
  }
6859
- thinkTool() {
6860
- return {
6861
- name: "Think",
6862
- 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.",
6863
- parameters: {
6864
- type: "object",
6865
- required: ["brief"],
6866
- properties: {
6867
- brief: { type: "string", description: "the question or problem to reason about deeply" },
6868
- label: { type: "string", description: "a short (2-4 word) label for the task" }
6869
- }
6870
- },
6871
- run: async ({ brief, label }) => {
6872
- this.spokeBeforeDispatch = this.spokeThisTurn;
6873
- this.turnDispatched = true;
6874
- this.turnBriefs.add(String(brief ?? ""));
6875
- this.voice.options.toolChoice = "none";
6876
- const id = await this.dispatch(String(brief ?? ""), "think", label ? String(label) : void 0, this.turnFollowUp);
6877
- 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.`;
6878
- }
6879
- };
6733
+ /** The host spoke on this turn's behalf OUTSIDE the reflex stream (e.g. the voice engine's adaptive
6734
+ * micro-ack). For a DISPATCHED turn that's a sufficient ack (don't stack a second one); for an
6735
+ * inline turn whose reply came back empty it is NOT — "One sec." followed by permanent silence is
6736
+ * still dead air, so silentTurn ignores external speech unless work was dispatched. */
6737
+ noteExternalSpeech() {
6738
+ this.externalSpeech = true;
6880
6739
  }
6881
- taskStatusTool() {
6882
- return {
6883
- name: "TaskStatus",
6884
- description: "Status of background tasks. Pass `id` for one task, or omit it to list all.",
6885
- parameters: { type: "object", properties: { id: { type: "string" } } },
6886
- run: async ({ id }) => {
6887
- const list = id ? [this.tasks.get(String(id))].filter(Boolean) : [...this.tasks.values()];
6888
- if (!list.length) return id ? `No task '${id}'.` : "No background tasks.";
6889
- return list.map((t) => `${t.id} (${t.label}): ${t.status}`).join("\n");
6890
- }
6891
- };
6740
+ /** True when the just-finished turn voiced NOTHING — dead air to repair. Two ways this happens:
6741
+ * (a) a dispatch with no spoken ack, and (b) an INLINE turn whose `final` channel came back empty —
6742
+ * gpt-oss harmony sometimes puts the whole reply in `analysis` (→ thinking_delta, suppressed in
6743
+ * voice) and emits an empty `final`, so no text_delta ever streams. Both ship silence; both repair.
6744
+ * Requires a host: without one there's no stream to detect speech on (and no one to speak to). */
6745
+ get silentTurn() {
6746
+ const ackedByHost = this.externalSpeech && this.turnDispatched;
6747
+ return !!this.options.host && !this.spokeThisTurn && !ackedByHost && !this.heldThisTurn;
6892
6748
  }
6893
- /** Sub-100ms read-only lookups the voice may do itself — everything else stays Act-only.
6894
- * fs-only (no shell; the engine is VFS-abstracted): time, git branch (.git/HEAD read), ls, file
6895
- * head. Output is hard-capped so a lookup can never bloat the skinny voice context. */
6896
- quickLookTool() {
6897
- const CAP2 = 2e3;
6898
- const kinds = [.../* @__PURE__ */ new Set(["time", "branch", "ls", "file", "capabilities", ...Object.keys(this.options.quickLook ?? {})])];
6899
- return {
6900
- name: "QuickLook",
6901
- description: `Instant read-only lookup \u2014 one of: ${kinds.join(", ")}. For trivial facts only; anything needing search, commands, or reasoning goes through Act.`,
6902
- parameters: {
6903
- type: "object",
6904
- required: ["what"],
6905
- properties: {
6906
- what: { type: "string", enum: kinds, description: "what to look up" },
6907
- path: { type: "string", description: "for ls/file: the path to look at" }
6908
- }
6909
- },
6910
- run: async ({ what, path }) => {
6911
- const fs = this.options.fs;
6912
- try {
6913
- const over = this.options.quickLook?.[String(what)];
6914
- if (over) return await over(path ? String(path) : void 0);
6915
- switch (String(what)) {
6916
- case "capabilities": {
6917
- const actTools = this.options.actOptions?.tools ?? [];
6918
- const names = actTools.map((t) => t.name);
6919
- const mcpServers = Object.keys(this.options.actOptions?.providerOptions?.mcpServers ?? {});
6920
- 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).` : "";
6921
- if (!names.length)
6922
- 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;
6923
- const hasFetch = names.some((n) => /WebFetch/i.test(n));
6924
- const hasBrowser = names.some((n) => /browser.*(navigate|click|page|type)/i.test(n));
6925
- const hasSearch = names.some((n) => /(^|_)WebSearch$|search/i.test(n) && !/WebFetch|browser/i.test(n));
6926
- const notes = [];
6927
- if (hasFetch) notes.push("WebFetch retrieves ONE specific URL you are given \u2014 it is not a search engine.");
6928
- 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.");
6929
- 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.');
6930
- const webNote = notes.length ? " NOTE: " + notes.join(" ") : "";
6931
- 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;
6932
- }
6933
- case "time":
6934
- return (/* @__PURE__ */ new Date()).toString();
6935
- case "branch": {
6936
- if (!fs) return "unavailable (no filesystem)";
6937
- const head = (await fs.readFile(".git/HEAD")).trim();
6938
- return head.startsWith("ref: refs/heads/") ? `branch: ${head.slice("ref: refs/heads/".length)}` : `detached HEAD at ${head.slice(0, 12)}`;
6939
- }
6940
- case "ls": {
6941
- if (!fs) return "unavailable (no filesystem)";
6942
- const p = String(path ?? ".");
6943
- try {
6944
- const names = await fs.readDir(p);
6945
- return names.slice(0, 50).join("\n") + (names.length > 50 ? `
6946
- \u2026 (+${names.length - 50} more)` : "");
6947
- } catch {
6948
- const names = await fs.readDir(".").catch(() => []);
6949
- return `'${p}' not found here \u2014 you are likely already inside it. Current directory listing:
6950
- ` + names.slice(0, 50).join("\n") + (names.length > 50 ? `
6951
- \u2026 (+${names.length - 50} more)` : "");
6952
- }
6953
- }
6954
- case "file": {
6955
- if (!fs) return "unavailable (no filesystem)";
6956
- if (!path) return "file lookup needs a path";
6957
- try {
6958
- const text = await fs.readFile(String(path));
6959
- return text.length > CAP2 ? text.slice(0, CAP2) + `
6960
- \u2026 (truncated \u2014 ${text.length} chars total; Act for the full file)` : text;
6961
- } catch {
6962
- const names = await fs.readDir(".").catch(() => []);
6963
- return `'${path}' not found. Current directory contains:
6964
- ` + names.slice(0, 50).join("\n");
6965
- }
6966
- }
6967
- default:
6968
- return `unknown lookup '${what}'`;
6969
- }
6970
- } catch (e) {
6971
- return `lookup failed: ${e?.message ?? e}`;
6972
- }
6749
+ /** A turn that voiced nothing is dead air. Re-prompt the reflex ONCE so the LLM itself voices a short
6750
+ * line (no template). If it STILL says nothing, fall back to a minimal line so silence never ships.
6751
+ * Wording adapts to whether work was dispatched (an ack) or the inline reply was simply lost. */
6752
+ async ackIfSilent(fallback) {
6753
+ const dispatched = this.turnDispatched;
6754
+ this.nudging = true;
6755
+ try {
6756
+ 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.");
6757
+ } catch (e) {
6758
+ log12.warn(`ack nudge failed: ${e instanceof Error ? e.message : e}`);
6759
+ } finally {
6760
+ this.nudging = false;
6761
+ }
6762
+ if (!this.spokeThisTurn) {
6763
+ const pool = fallback ? [fallback] : dispatched ? _DuplexAgent.FALLBACK_ACKS : _DuplexAgent.FALLBACK_RETRY;
6764
+ const fresh = pool.filter((p) => p !== this.lastFallback);
6765
+ const line = (fresh.length ? fresh : pool)[Math.floor(Math.random() * (fresh.length || pool.length))];
6766
+ this.lastFallback = line;
6767
+ this.emitHost({ kind: "text_delta", message: line });
6768
+ }
6769
+ }
6770
+ /** Dead-air fallback pools (see ackIfSilent). Both retry lines keep the 'say that again' phrase —
6771
+ * hosts/tests key on it. */
6772
+ static FALLBACK_ACKS = ["Okay, on it.", "On it.", "Alright, working on it."];
6773
+ static FALLBACK_RETRY = ["Sorry, could you say that again?", "Hm, I missed that \u2014 could you say that again?"];
6774
+ lastFallback = "";
6775
+ /** One user turn: the voice agent streams the reply (and may Act/Think). Serialized with re-voice turns.
6776
+ * If a speculative reflex call is pending and this content CONFIRMS it (the final matches the
6777
+ * speculated partial), the in-flight call is adopted as THE turn: its buffered output flushes to the
6778
+ * host NOW (this is the latency win) and streaming continues live. Any other content aborts the
6779
+ * speculation first (rolled back silently) and runs a normal turn behind it. */
6780
+ send(content) {
6781
+ if (typeof content === "string" && isTrivialBarge(content) && this.hasParkedDelivery()) {
6782
+ if (this.spec) this.abortSpeculation();
6783
+ return this.enqueue(async () => {
6784
+ this.resetTurn();
6785
+ if (!this.redeliverParked()) this.awaitTrivialRedeliver = true;
6786
+ return { text: "", steps: 0, finishReason: "stop", messages: [] };
6787
+ });
6788
+ }
6789
+ const spec = this.spec;
6790
+ if (spec?.state === "pending") {
6791
+ if (typeof content === "string" && speculationConfirms(spec.text, content)) {
6792
+ spec.state = "confirmed";
6793
+ spec.finalText = content;
6794
+ for (const ev of spec.buf.splice(0)) this.options.host?.notify?.(ev);
6795
+ spec.decide("confirm");
6796
+ this.notify("diag", "speculation_confirmed", { text: spec.text.slice(0, 80) });
6797
+ return spec.done;
6973
6798
  }
6974
- };
6799
+ this.abortSpeculation();
6800
+ }
6801
+ return this.enqueue(async () => {
6802
+ await this.initMemory();
6803
+ this.resetTurn();
6804
+ this.awaitTrivialRedeliver = false;
6805
+ this.parkedRedeliver = [];
6806
+ this.suppressParkedResume = true;
6807
+ const res = await this.voice.send(content);
6808
+ this.flushHeldReflexTail();
6809
+ if (this.silentTurn) await this.ackIfSilent();
6810
+ return res;
6811
+ });
6975
6812
  }
6976
- answerTaskTool() {
6977
- return {
6978
- name: "AnswerTask",
6979
- 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.`,
6980
- parameters: {
6981
- type: "object",
6982
- required: ["id", "answer"],
6983
- properties: { id: { type: "string" }, answer: { type: "string", description: "the user's answer, verbatim or faithfully summarized" } }
6984
- },
6985
- run: async ({ id, answer }) => {
6986
- const ask = this.pendingAsks.get(String(id));
6987
- if (!ask) return `No pending question for '${id}' \u2014 it may have been answered already or timed out.`;
6988
- ask.resolve(String(answer ?? ""));
6989
- return `Answer relayed \u2014 task ${id} resumes.`;
6990
- }
6813
+ /** Start a HELD speculative reflex turn on a stable partial (VoiceEngine.onSpeculate). Its spoken
6814
+ * output buffers in emitHost; send() later confirms (flush + adopt) or aborts it. The turn holds the
6815
+ * voice mutex until that decision (bounded by a safety timeout), so no other turn can interleave
6816
+ * into the transcript between the speculative messages and their rollback. No-op if a speculation
6817
+ * is already in flight. */
6818
+ speculate(text) {
6819
+ if (!text.trim() || this.spec) return;
6820
+ let decide;
6821
+ const decision = new Promise((r) => {
6822
+ decide = r;
6823
+ });
6824
+ const spec = {
6825
+ text,
6826
+ state: "pending",
6827
+ buf: [],
6828
+ ctl: new AbortController(),
6829
+ decide,
6830
+ decision,
6831
+ done: void 0
6991
6832
  };
6992
- }
6993
- holdTool() {
6994
- return {
6995
- name: "Hold",
6996
- 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.',
6997
- parameters: {
6998
- type: "object",
6999
- properties: {
7000
- filler: { type: "string", description: 'optional short filler to speak ("mhm", "go on", "mm-hm")' }
6833
+ this.spec = spec;
6834
+ spec.done = this.enqueue(async () => {
6835
+ const empty = { text: "", steps: 0, finishReason: "aborted", messages: this.voice.transcript };
6836
+ if (spec.state === "aborted") {
6837
+ this.speculativeAbortedCalls++;
6838
+ if (this.spec === spec) this.spec = void 0;
6839
+ return empty;
6840
+ }
6841
+ await this.initMemory();
6842
+ this.resetTurn();
6843
+ const base = this.voice.transcript.length;
6844
+ const prevSignal = this.voice.options.signal;
6845
+ this.voice.options.signal = spec.ctl.signal;
6846
+ let res;
6847
+ try {
6848
+ res = await this.voice.send(spec.text);
6849
+ } catch (e) {
6850
+ log12.warn(`speculative turn failed: ${e instanceof Error ? e.message : e}`);
6851
+ } finally {
6852
+ this.voice.options.signal = prevSignal;
6853
+ }
6854
+ const timer = setTimeout(() => {
6855
+ spec.state = spec.state === "pending" ? "aborted" : spec.state;
6856
+ spec.decide("abort");
6857
+ }, 1e4);
6858
+ timer.unref?.();
6859
+ const d = await spec.decision;
6860
+ clearTimeout(timer);
6861
+ if (d === "abort") {
6862
+ if (this.voice.transcript.length > base) this.voice.transcript.length = base;
6863
+ this.speculativeAbortedCalls++;
6864
+ log12.verbose(`speculation aborted (${this.speculativeAbortedCalls} total): "${spec.text.slice(0, 50)}"`);
6865
+ if (this.spec === spec) this.spec = void 0;
6866
+ return res ?? empty;
6867
+ }
6868
+ for (let i = base; i < this.voice.transcript.length; i++) {
6869
+ const m = this.voice.transcript[i];
6870
+ if (m.role === "user" && contentText(m.content) === spec.text) {
6871
+ m.content = spec.finalText;
6872
+ break;
7001
6873
  }
7002
- },
7003
- run: async ({ filler }) => {
7004
- this.heldThisTurn = true;
7005
- this.notify("hold_filler", filler ? String(filler) : "");
7006
- return "Holding \u2014 listening for the rest of the user's thought. Do not respond further this turn.";
7007
6874
  }
7008
- };
6875
+ this.spec = void 0;
6876
+ this.flushHeldReflexTail();
6877
+ if (this.silentTurn) await this.ackIfSilent();
6878
+ return res ?? empty;
6879
+ });
7009
6880
  }
7010
- cancelTaskTool() {
7011
- return {
7012
- name: "CancelTask",
7013
- description: "Cancel a running background task by id.",
7014
- parameters: { type: "object", required: ["id"], properties: { id: { type: "string" } } },
7015
- run: async ({ id }) => this.cancelTask(String(id))
7016
- };
6881
+ /** Abort a pending speculation (idempotent): kill the in-flight call, drop its buffered output.
6882
+ * Called on divergence (send), a stale partial (VoiceEngine.onSpeculateAbort), a side-effect tool
6883
+ * attempt (dispatchGuard), or host paths that will never dispatch a final (commands, voice-off). */
6884
+ abortSpeculation() {
6885
+ const spec = this.spec;
6886
+ if (spec?.state !== "pending") return;
6887
+ spec.state = "aborted";
6888
+ spec.buf.length = 0;
6889
+ spec.ctl.abort();
6890
+ spec.decide("abort");
6891
+ this.notify("diag", "speculation_aborted", { text: spec.text.slice(0, 80) });
7017
6892
  }
7018
- };
7019
-
7020
- // src/mcp.ts
7021
- function toResult(result) {
7022
- if (result == null) return { text: "" };
7023
- if (typeof result === "string") return { text: result };
7024
- const content = result.content;
7025
- if (Array.isArray(content)) {
7026
- const texts = [];
7027
- const images = [];
7028
- for (const c of content) {
7029
- if (c?.type === "image" && typeof c.data === "string" && c.mimeType) {
7030
- images.push({ mimeType: c.mimeType, data: c.data });
7031
- } else if (typeof c?.text === "string") {
7032
- texts.push(c.text);
7033
- } else {
7034
- texts.push(JSON.stringify(c));
7035
- }
7036
- }
7037
- const text = texts.join("\n");
7038
- if (text || images.length) return { text, ...images.length ? { images } : {} };
6893
+ /** Cancel a running background task — shared by the CancelTask tool and the CLI /tasks picker. */
6894
+ cancelTask(id) {
6895
+ const rec = this.tasks.get(id);
6896
+ if (!rec) return `No task '${id}'.`;
6897
+ if (rec.status !== "running") return `Task ${rec.id} is already ${rec.status}.`;
6898
+ rec.status = "cancelled";
6899
+ rec.controller.abort();
6900
+ return `Task ${rec.id} (${rec.label}) cancelled.`;
7039
6901
  }
7040
- return { text: JSON.stringify(result) };
7041
- }
7042
- function mcpToolToAgentTool(spec, callTool, prefix = "mcp__") {
7043
- return {
7044
- name: `${prefix}${spec.name}`,
7045
- description: spec.description ?? `MCP tool ${spec.name}`,
7046
- parameters: spec.inputSchema ?? { type: "object", properties: {} },
7047
- async run(args, _ctx) {
7048
- const r = toResult(await callTool(spec.name, args ?? {}));
7049
- return r.images?.length ? r : r.text;
7050
- }
7051
- };
7052
- }
7053
- function mcpToolsToAgentTools(specs, callTool, prefix = "mcp__", filter) {
7054
- return (filter ? specs.filter(filter) : specs).map((s) => mcpToolToAgentTool(s, callTool, prefix));
7055
- }
7056
- function describeSpec(s) {
7057
- const schema = s.inputSchema ? `
7058
- args: ${JSON.stringify(s.inputSchema)}` : "";
7059
- return `${s.name} \u2014 ${s.description ?? "(no description)"}${schema}`;
7060
- }
7061
- function makeMcpToolSearch(specs, callTool, options = {}) {
7062
- const maxResults = options.maxResults ?? 10;
7063
- const byName = new Map(specs.map((s) => [s.name, s]));
7064
- const catalogLine = `${specs.length} MCP tool(s) available \u2014 search by keyword, then call by exact name.`;
7065
- const searchTool = {
7066
- name: "ToolSearch",
7067
- description: `Search the available MCP tools by keyword (${catalogLine}). Returns matching tool names + their argument schemas; call one with \`McpCall\`.`,
7068
- parameters: { type: "object", required: ["query"], properties: { query: { type: "string", description: "keywords to match against tool name + description" } } },
7069
- async run({ query }) {
7070
- const q2 = String(query ?? "").trim();
7071
- if (!q2) return catalogLine;
7072
- const { kept } = topByRelevance(specs, q2, (s) => `${s.name} ${s.description ?? ""}`, maxResults);
7073
- if (!kept.length) return `(no MCP tool matches "${q2}" \u2014 try broader keywords)`;
7074
- return kept.map(describeSpec).join("\n");
7075
- }
7076
- };
7077
- const callMcpTool = {
7078
- name: "McpCall",
7079
- description: "Call an MCP tool discovered via `ToolSearch`, by its exact name. Pass its arguments as `args`.",
7080
- parameters: {
7081
- type: "object",
7082
- required: ["name"],
7083
- properties: {
7084
- name: { type: "string", description: "exact tool name from ToolSearch" },
7085
- args: { type: "object", description: "arguments object for the tool (per its schema)" }
6902
+ /** Barge-in: the user took the floor while task(s) were running. Suppress those tasks' remaining SPOKEN
6903
+ * delivery so a superseded topic never talks over the new one (the debt-after-jokes regression). The
6904
+ * tasks keep running and still fold their result into the transcript — recoverable, just not spoken.
6905
+ * Returns the parked ids (for logging). Does NOT cancel: that's a deliberate reflex/user action. */
6906
+ parkInFlightDeliveries() {
6907
+ this.suppressParkedResume = false;
6908
+ const parked = [];
6909
+ for (const rec of this.tasks.values())
6910
+ if (rec.status === "running" && !rec.deliveryParked) {
6911
+ rec.deliveryParked = true;
6912
+ parked.push(rec.id);
7086
6913
  }
7087
- },
7088
- async run({ name, args }) {
7089
- const n = String(name ?? "");
7090
- if (!byName.has(n)) return `Error: unknown MCP tool '${n}'. Use ToolSearch to find valid names.`;
7091
- const r = toResult(await callTool(n, args ?? {}));
7092
- return r.images?.length ? r : r.text;
7093
- }
7094
- };
7095
- return [searchTool, callMcpTool];
7096
- }
7097
- function buildMcpCatalog(servers) {
7098
- const specs = [];
7099
- const routes = /* @__PURE__ */ new Map();
7100
- for (const m of servers) {
7101
- for (const s of m.specs) {
7102
- const base = `mcp__${m.name}__${s.name}`.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 128);
7103
- let display = base;
7104
- for (let i = 2; routes.has(display); i++) display = `${base.slice(0, 128 - String(i).length - 1)}_${i}`;
7105
- specs.push({ name: display, description: s.description, inputSchema: s.inputSchema });
7106
- routes.set(display, { server: m.name, rawName: s.name });
6914
+ return parked;
6915
+ }
6916
+ /** True while there is a parked delivery to potentially resume: either one already settled (queued) or
6917
+ * one still running that was parked by a barge. */
6918
+ hasParkedDelivery() {
6919
+ return this.parkedRedeliver.length > 0 || [...this.tasks.values()].some((t) => t.status === "running" && t.deliveryParked);
6920
+ }
6921
+ /** Speak any settled-and-queued parked delivery now (trivial-barge resume). Returns false if nothing was
6922
+ * queued yet (the caller then arms awaitTrivialRedeliver so the task resumes the instant it settles). */
6923
+ redeliverParked() {
6924
+ if (!this.parkedRedeliver.length) return false;
6925
+ const text = this.parkedRedeliver.splice(0).join(" ").trim();
6926
+ if (text) {
6927
+ this.options.host?.notify?.({ kind: "speak_utterance", message: text });
6928
+ this.notify("diag", "parked_redelivered", { chars: text.length });
7107
6929
  }
6930
+ return true;
7108
6931
  }
7109
- return { specs, routes };
7110
- }
7111
- function searchOverCatalog(servers, specs, routes, resolve4, options) {
7112
- const tools = specs.length ? makeMcpToolSearch(specs, (name, args) => {
7113
- const r = routes.get(name);
7114
- if (!r) throw new Error(`unknown MCP tool '${name}' \u2014 use ToolSearch to find valid names`);
7115
- return resolve4(r.server, r.rawName, args ?? {});
7116
- }, options) : [];
7117
- return { tools, serverNames: servers, toolCount: specs.length };
7118
- }
7119
- function makeMcpToolSearchFromMounted(mounted, options) {
7120
- const { specs, routes } = buildMcpCatalog(mounted);
7121
- const byName = new Map(mounted.map((m) => [m.name, m]));
7122
- return searchOverCatalog(mounted.map((m) => m.name), specs, routes, (server, rawName, args) => byName.get(server).client.callTool(rawName, args), options);
7123
- }
7124
-
7125
- // src/index.ts
7126
- init_logging();
7127
-
7128
- // src/voice/soniox.ts
7129
- init_logging();
7130
-
7131
- // src/voice/types.ts
7132
- var STT_SAMPLE_RATE = 16e3;
7133
- var TTS_SAMPLE_RATE = 44100;
7134
- async function resolveAuth(auth) {
7135
- return typeof auth === "function" ? await auth() : auth;
7136
- }
7137
-
7138
- // src/voice/soniox.ts
7139
- var log11 = forComponent("SonioxSTT");
7140
- var now = () => performance.now();
7141
- var SonioxSTTOptions = class {
7142
- auth = "";
7143
- source;
7144
- model = "stt-rt-preview";
7145
- languageHints = ["en"];
7146
- /** Client-side endpoint: finalized text + no new tokens for this long = utterance (don't wait for
7147
- * Soniox's semantic <end>, which adds 0.5-1.5s — the difference between ping-pong and lag). */
7148
- silenceEndpointMs = 500;
7149
- /** No-audio watchdog: if the mic source stops delivering chunks for this long, capture is dead →
7150
- * fire onFatal + stop (else Soniox idle-timeouts and reconnect-loops forever). 0 = disable. */
7151
- noAudioTimeoutMs = 1e4;
7152
- };
7153
- var SonioxSTT = class {
7154
- options;
7155
- ws;
7156
- stopped = false;
7157
- sourceStarted = false;
7158
- onPartial = () => {
7159
- };
7160
- onUtterance = () => {
7161
- };
7162
- /** mic energy (RMS) per chunk — drives the energy-based heuristic barge-in tier */
7163
- onLevel = () => {
7164
- };
7165
- /** Unrecoverable: the mic source stopped delivering audio (Soniox starves → idle-timeout reconnect
7166
- * loop). The host tears voice down instead of spinning forever. */
7167
- onFatal = () => {
7168
- };
7169
- /** Diagnostic tap (provider errors, ws reconnects, no-audio watchdog). Fire-and-forget: a throwing
7170
- * handler disables itself — never affects transcription. Wired by VoiceIO / the lab bridge. */
7171
- onDiag = () => {
7172
- };
7173
- diagOn = true;
7174
- diag(kind, fields) {
7175
- if (!this.diagOn) return;
7176
- try {
7177
- this.onDiag({ t: now(), kind, ...fields });
7178
- } catch (e) {
7179
- this.diagOn = false;
7180
- log11.debug(`onDiag threw \u2014 STT diagnostics disabled: ${e instanceof Error ? e.message : e}`);
6932
+ /** Resolve when all queued voice turns AND all in-flight worker tasks have settled (tests, graceful shutdown). */
6933
+ async idle() {
6934
+ while (true) {
6935
+ const q2 = this.queue;
6936
+ await q2.catch(() => {
6937
+ });
6938
+ await Promise.all([...this.tasks.values()].map((t) => t.promise));
6939
+ if (this.queue === q2 && ![...this.tasks.values()].some((t) => t.status === "running")) return;
7181
6940
  }
7182
6941
  }
7183
- lastChunkAt = 0;
7184
- // timestamp of the most recent mic chunk (0 = none yet)
7185
- startedChunksAt = 0;
7186
- // when capture started (grace before the first chunk)
7187
- noAudioTimer = null;
7188
- finalText = "";
7189
- partialText = "";
7190
- lastChangeAt = 0;
7191
- lastCombined = "";
7192
- endpointTimer = null;
7193
- firstTokenAt = 0;
7194
- // first speech token in current utterance
7195
- constructor(options) {
7196
- this.options = { ...new SonioxSTTOptions(), ...options };
6942
+ /** Promise-chain mutex: turns run strictly one at a time; a failed turn doesn't poison the chain. */
6943
+ enqueue(fn) {
6944
+ const run = this.queue.then(fn, fn);
6945
+ this.queue = run.then(() => {
6946
+ }, () => {
6947
+ });
6948
+ return run;
7197
6949
  }
7198
- get usingAec() {
7199
- return this.options.source?.aec ?? false;
6950
+ notify(kind, message, data) {
6951
+ this.emitHost({ kind, message, data });
7200
6952
  }
7201
- async connectWs() {
7202
- const apiKey = await resolveAuth(this.options.auth);
7203
- this.ws = new WebSocket("wss://stt-rt.soniox.com/transcribe-websocket");
7204
- await new Promise((res, rej) => {
7205
- this.ws.onopen = () => res();
7206
- this.ws.onerror = (e) => rej(new Error(`soniox ws: ${e.message || "connect failed"}`));
6953
+ /** Host-boundary emit for the reflex's spoken channel: during a PENDING speculation, text_delta and
6954
+ * hold_filler are BUFFERED (nothing may reach TTS on unconfirmed input); confirm flushes them in
6955
+ * order, abort drops them silently. Everything else (task_* lifecycle, worker speak_utterance —
6956
+ * which bypasses this via host.notify directly) passes through untouched. */
6957
+ emitHost(ev) {
6958
+ const spec = this.spec;
6959
+ if (spec && (ev.kind === "text_delta" || ev.kind === "hold_filler")) {
6960
+ if (spec.state === "pending") {
6961
+ spec.buf.push(ev);
6962
+ return;
6963
+ }
6964
+ if (spec.state === "aborted") return;
6965
+ }
6966
+ this.options.host?.notify?.(ev);
6967
+ }
6968
+ /** Queue a `[task …]` event for re-voicing. Events arriving while the voice is busy coalesce into ONE turn.
6969
+ * `nonClean` (out-of-band boolean, set by the caller that KNOWS this event integrates a NON-CLEAN outcome)
6970
+ * marks the coalesced flush as a non-clean integration turn — turn-eligibility, never inferred from event
6971
+ * text and never keyed on a (re-authored) brief string. Any dispatch in such a turn is a follow-up. */
6972
+ queueRevoice(event, nonClean = false) {
6973
+ this.pendingEvents.push(event);
6974
+ if (nonClean) this.pendingNonClean = true;
6975
+ if (this.flushQueued) return;
6976
+ this.flushQueued = true;
6977
+ void this.enqueue(async () => {
6978
+ this.flushQueued = false;
6979
+ const events = this.pendingEvents.splice(0);
6980
+ const nonCleanTurn = this.pendingNonClean;
6981
+ this.pendingNonClean = false;
6982
+ if (!events.length) return;
6983
+ const failed = events.find((e) => /^\[task\b[^\]\n]*\bfailed\b/i.test(e));
6984
+ this.resetTurn();
6985
+ this.turnFollowUp = nonCleanTurn;
6986
+ await this.voice.send(events.join("\n"));
6987
+ this.flushHeldReflexTail();
6988
+ if (this.silentTurn) await this.ackIfSilent(failed ? "Sorry, that didn't work \u2014 the task failed." : void 0);
6989
+ this.notify("revoice_done", "");
7207
6990
  });
7208
- this.ws.send(
7209
- JSON.stringify({
7210
- api_key: apiKey,
7211
- model: this.options.model,
7212
- audio_format: "pcm_s16le",
7213
- sample_rate: STT_SAMPLE_RATE,
7214
- num_channels: 1,
7215
- language_hints: this.options.languageHints,
7216
- enable_endpoint_detection: true
7217
- })
7218
- );
7219
- this.ws.onmessage = (ev) => this.handle(JSON.parse(String(ev.data)));
7220
- this.ws.onclose = (ev) => {
7221
- if (this.stopped) return;
7222
- log11.warn(`soniox ws closed (${ev.code} ${ev.reason || ""}) \u2014 reconnecting`);
7223
- this.diag("stt_ws_closed", { code: ev.code, reason: String(ev.reason || ""), reconnecting: true });
7224
- this.reset();
7225
- this.connectWs().catch((e) => {
7226
- log11.error(`soniox reconnect failed: ${e.message}`);
7227
- this.diag("stt_reconnect_failed", { message: e.message });
7228
- });
6991
+ }
6992
+ /** The worker's brief: the Act/Think args + a STATIC text snapshot of the recent conversation.
6993
+ * Act briefs get a self-verify footer — the worker's report is trusted without review, so it
6994
+ * must check its own work before reporting (nearly free under prompt caching; measured honest:
6995
+ * it does NOT fix one-shot logic bugs — see mind/10). Think tasks are pure reasoning — no footer. */
6996
+ buildBrief(brief, tier = "act", deliver = true) {
6997
+ 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");
6998
+ 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." : "";
6999
+ const deliverContract = deliver ? `
7000
+
7001
+ ## DELIVER (spoken delivery)
7002
+ 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." : "") : "";
7003
+ return `${nowLine()}.
7004
+
7005
+ ` + (recent ? `${brief}
7006
+
7007
+ ## Recent conversation (for context)
7008
+ ${recent}` : brief) + verify + deliverContract;
7009
+ }
7010
+ /** Spawn a detached worker for task `id`; its settlement notifies + enqueues the re-voice turn. */
7011
+ spawnWorker(id, label, briefText, tier, brief, followUp) {
7012
+ const o = this.options;
7013
+ const tierOpts = tier === "think" ? o.thinkOptions : o.actOptions;
7014
+ const tierModel = tier === "think" ? o.thinkModel : o.actModel;
7015
+ const controller = new AbortController();
7016
+ const base = tierOpts?.hooks ?? o.actOptions?.hooks;
7017
+ const report = o.progressUpdates ? this.progressReporter(id) : void 0;
7018
+ const tail = [];
7019
+ const pushTail = (line) => {
7020
+ tail.push(line.slice(0, 200));
7021
+ if (tail.length > 120) tail.splice(0, tail.length - 120);
7022
+ };
7023
+ const hooks = {
7024
+ ...base,
7025
+ preToolUse: async (call, meta) => {
7026
+ const d = await base?.preToolUse?.(call, meta);
7027
+ pushTail(`\u2699 ${describeCall(call)}`);
7028
+ report?.pre(call);
7029
+ return d;
7030
+ },
7031
+ postToolUse: async (call, result, meta) => {
7032
+ await base?.postToolUse?.(call, result, meta);
7033
+ const last = result?.trim().split("\n").filter(Boolean).pop();
7034
+ if (last) pushTail(` \u21B3 ${last}`);
7035
+ report?.post(call);
7036
+ },
7037
+ onToolOutput: (call, chunk, meta) => {
7038
+ base?.onToolOutput?.(call, chunk, meta);
7039
+ report?.output(chunk);
7040
+ }
7041
+ };
7042
+ const relayAsk = async (q2) => {
7043
+ const opts = q2.options?.length ? ` Options: ${q2.options.map((x) => x.label).join(", ")}.` : "";
7044
+ const a = await this.parkQuestion(id, `${q2.question}${opts}`);
7045
+ return a || "(no answer from the user \u2014 use your best judgment and note the assumption)";
7046
+ };
7047
+ const splitter = new SpokenSplitter();
7048
+ const speak = (seg) => {
7049
+ if (!seg) return;
7050
+ const r = this.tasks.get(id);
7051
+ if (r) r.spokenText = (r.spokenText ? r.spokenText + " " : "") + seg;
7052
+ if (!r?.deliveryParked) o.host?.notify?.({ kind: "speak_utterance", message: seg });
7053
+ };
7054
+ const coalescer = new SentenceCoalescer();
7055
+ const feedSpoken = (s) => {
7056
+ const ready = coalescer.feed(s);
7057
+ if (ready) speak(ready);
7058
+ };
7059
+ const flushSpoken = () => speak(coalescer.flush());
7060
+ const askBridge = o.askRelay ? { ask: relayAsk } : o.host?.ask ? { ask: (q2) => o.host.ask(q2) } : {};
7061
+ const workerHost = {
7062
+ ...askBridge,
7063
+ notify: (ev) => {
7064
+ if (ev?.kind === "text_delta" && typeof ev.message === "string") {
7065
+ const { spoken, detail } = splitter.feed(ev.message);
7066
+ feedSpoken(spoken);
7067
+ if (detail.trim()) pushTail(detail.trim());
7068
+ return;
7069
+ }
7070
+ }
7071
+ };
7072
+ const agentOpts = {
7073
+ ai: o.ai,
7074
+ fs: o.fs,
7075
+ model: tierModel,
7076
+ ...tier === "think" ? { reasoning: tierOpts?.reasoning ?? "high" } : {},
7077
+ ...tierOpts,
7078
+ // Recompute providerOptions for THIS worker's model (after tierOpts so it wins over any inherited
7079
+ // main-template value) — prevents cursor-only cwd/cursorSession leaking onto an anthropic worker.
7080
+ providerOptions: o.providerOptionsFor?.(tierModel),
7081
+ stream: true,
7082
+ // worker streams text_delta so the splitter can extract <spoken> live (after tierOpts: never overridden off)
7083
+ host: workerHost,
7084
+ // carries BOTH ask AND the <spoken>-splitting notify
7085
+ ...hooks ? { hooks } : {},
7086
+ signal: controller.signal
7087
+ // shared with the checker so a cancel tears down both
7229
7088
  };
7089
+ const promise = new Agent(agentOpts).run(briefText).then((res) => {
7090
+ const { spoken, detail } = splitter.flush();
7091
+ feedSpoken(spoken);
7092
+ if (detail.trim()) pushTail(detail.trim());
7093
+ flushSpoken();
7094
+ return res;
7095
+ }).then((res) => this.maybeVerify(id, brief, res, tier, agentOpts, askBridge)).then((res) => this.onWorkerSettled(id, res)).catch((err2) => this.onWorkerFailed(id, err2));
7096
+ this.tasks.set(id, { id, label, status: "running", controller, promise, tail, brief, followUp, splitter });
7097
+ if (this.tasks.size > this.options.maxTaskRecords)
7098
+ for (const [tid, rec] of this.tasks) {
7099
+ if (this.tasks.size <= this.options.maxTaskRecords) break;
7100
+ if (rec.status !== "running") this.tasks.delete(tid);
7101
+ }
7230
7102
  }
7231
- async start() {
7232
- await this.connectWs();
7233
- if (this.sourceStarted) return;
7234
- this.sourceStarted = true;
7235
- this.endpointTimer = setInterval(() => {
7236
- const combined = (this.finalText + this.partialText).trim();
7237
- if (!combined || now() - this.lastChangeAt < this.options.silenceEndpointMs) return;
7238
- if (this.firstTokenAt) log11.debug(`stt: ${Math.round(now() - this.firstTokenAt)}ms first-token\u2192silence-endpoint, "${combined.slice(0, 60)}"`);
7239
- this.reset();
7240
- this.onUtterance(combined, now());
7241
- }, 120);
7242
- this.endpointTimer.unref?.();
7243
- this.startedChunksAt = now();
7244
- const noAudioMs = this.options.noAudioTimeoutMs;
7245
- if (noAudioMs > 0) {
7246
- this.noAudioTimer = setInterval(() => {
7247
- if (this.stopped) return;
7248
- const ref = this.lastChunkAt || this.startedChunksAt;
7249
- if (now() - ref > noAudioMs) {
7250
- log11.error(`stt: no mic audio for >${Math.round(noAudioMs / 1e3)}s \u2014 capture device stopped delivering`);
7251
- this.diag("stt_watchdog_fatal", { noAudioMs });
7252
- this.onFatal("microphone stopped delivering audio (try a different input device, e.g. AirPods, or check System Settings \u2192 Sound \u2192 Input)");
7253
- this.stop();
7254
- }
7255
- }, Math.max(250, Math.min(2e3, noAudioMs / 4)));
7256
- this.noAudioTimer.unref?.();
7103
+ /** Fresh-context check of a successful Act task: a NEW agent (same model/fs/tools, but NO shared
7104
+ * conversation context) re-reads the file state against the brief and fixes any gap. The fix lands
7105
+ * on the shared fs automatically (workers write fs directly, no overlay), so grading sees the
7106
+ * corrected state. Bounded to ONE pass. Off unless `verifyActTasks`; never runs for think/failed/
7107
+ * cancelled tasks. Usage is merged so /cost reflects the real (worker + checker) spend. */
7108
+ async maybeVerify(id, brief, res, tier, agentOpts, askBridge) {
7109
+ if (!this.options.verifyActTasks || tier !== "act" || res.finishReason !== "stop") return res;
7110
+ if (this.tasks.get(id)?.status === "cancelled") return res;
7111
+ const { stream: _stream, host: _host, ...restOpts } = agentOpts;
7112
+ const checkerOpts = {
7113
+ ...restOpts,
7114
+ ...askBridge.ask ? { host: { ask: askBridge.ask } } : {}
7115
+ };
7116
+ const checkBrief = `${this.buildBrief(brief, tier, false)}
7117
+
7118
+ ## VERIFY MODE
7119
+ 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".`;
7120
+ this.notify("task_verify", `task ${id}: verifying`, { id });
7121
+ const cres = await new Agent(checkerOpts).run(checkBrief);
7122
+ if (cres.finishReason !== "stop") {
7123
+ log12.warn(`task ${id}: verify inconclusive (${cres.finishReason})`);
7124
+ this.notify("task_verify", `task ${id}: verify inconclusive (${cres.finishReason})`, { id, finishReason: cres.finishReason });
7257
7125
  }
7258
- await this.options.source.start((chunk) => {
7259
- this.lastChunkAt = now();
7260
- let sum = 0;
7261
- const view = new DataView(chunk.buffer, chunk.byteOffset, chunk.byteLength);
7262
- for (let i = 0; i + 1 < chunk.byteLength; i += 2) {
7263
- const v = view.getInt16(i, true);
7264
- sum += v * v;
7126
+ const sum = (a = 0, b = 0) => a + b;
7127
+ return {
7128
+ ...res,
7129
+ steps: res.steps + cres.steps,
7130
+ // Merge the checker's messages so downstream tool-call/step accounting includes BOTH agents
7131
+ // (else a verified task's toolCalls would undercount vs its steps/usage).
7132
+ messages: [...res.messages, ...cres.messages],
7133
+ usageEstimated: res.usageEstimated || cres.usageEstimated,
7134
+ usage: res.usage && cres.usage ? {
7135
+ promptTokens: sum(res.usage.promptTokens, cres.usage.promptTokens),
7136
+ completionTokens: sum(res.usage.completionTokens, cres.usage.completionTokens),
7137
+ totalTokens: sum(res.usage.totalTokens, cres.usage.totalTokens),
7138
+ cacheCreationTokens: sum(res.usage.cacheCreationTokens, cres.usage.cacheCreationTokens),
7139
+ cacheReadTokens: sum(res.usage.cacheReadTokens, cres.usage.cacheReadTokens)
7140
+ } : res.usage ?? cres.usage
7141
+ };
7142
+ }
7143
+ /** Throttled per-task progress: worker tool calls → at most one progress re-voice per interval.
7144
+ * Two sources, one throttle: completed steps (post) and a heartbeat for a SINGLE long tool call
7145
+ * (pre records the in-flight call; a self-cleaning timer narrates "still inside Bash — 70s").
7146
+ * Completion supersedes: nothing is emitted once the task has settled. */
7147
+ progressReporter(id) {
7148
+ let lastAt = Date.now();
7149
+ let steps = 0;
7150
+ let inflight = null;
7151
+ const due = () => {
7152
+ if (this.pendingAsks.size) return void 0;
7153
+ const rec = this.tasks.get(id);
7154
+ return rec && rec.status === "running" && Date.now() - lastAt >= this.options.progressIntervalMs ? rec : void 0;
7155
+ };
7156
+ const emit = (rec, line, call) => {
7157
+ lastAt = Date.now();
7158
+ this.notify("task_progress", `task ${id} (${rec.label}): ${line}`, { id, steps, call: call.name });
7159
+ this.queueRevoice(`[task ${id} progress] ${line}`);
7160
+ };
7161
+ const timer = setInterval(() => {
7162
+ const rec = this.tasks.get(id);
7163
+ if (!rec || rec.status !== "running") return clearInterval(timer);
7164
+ if (!inflight || !due()) return;
7165
+ const last = inflight.tail.trim().split("\n").filter(Boolean).pop()?.slice(-80);
7166
+ 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);
7167
+ }, Math.max(this.options.progressIntervalMs, 250));
7168
+ timer.unref?.();
7169
+ return {
7170
+ pre: (call) => {
7171
+ inflight = { call, at: Date.now(), tail: "" };
7172
+ },
7173
+ output: (chunk) => {
7174
+ if (inflight) inflight.tail = (inflight.tail + chunk).slice(-500);
7175
+ },
7176
+ // digest only — NEVER re-voices directly
7177
+ post: (call) => {
7178
+ steps++;
7179
+ inflight = null;
7180
+ const rec = due();
7181
+ if (rec) emit(rec, `still running \u2014 ${steps} steps so far, now: ${describeCall(call)}`, call);
7265
7182
  }
7266
- this.onLevel(Math.sqrt(sum / (chunk.byteLength / 2)));
7267
- if (this.ws.readyState === WebSocket.OPEN) this.ws.send(chunk);
7183
+ };
7184
+ }
7185
+ /** Park a question under `askId` (a task id, or any unique key for permission asks): re-voices
7186
+ * '[task <id> asks] …' and resolves with the user's answer via AnswerTask — or '' on timeout/
7187
+ * task settle (callers map '' to deny / best-judgment). Workers never block forever. */
7188
+ parkQuestion(askId, question) {
7189
+ return new Promise((resolve4) => {
7190
+ let settled = false;
7191
+ const finish = (answer) => {
7192
+ if (settled) return;
7193
+ settled = true;
7194
+ clearTimeout(timer);
7195
+ this.pendingAsks.delete(askId);
7196
+ resolve4(answer);
7197
+ };
7198
+ const timer = setTimeout(() => {
7199
+ this.notify("task_ask_timeout", `task ${askId}: question timed out \u2014 proceeding without an answer`);
7200
+ finish("");
7201
+ }, this.options.askTimeoutMs);
7202
+ this.pendingAsks.set(askId, { question, resolve: finish });
7203
+ this.notify("task_ask", `task ${askId} asks: ${question}`, { id: askId, question });
7204
+ this.queueRevoice(`[task ${askId} asks] ${question}
7205
+ (Relay this to the user in your own words. When they answer, call AnswerTask with id "${askId}" and their answer.)`);
7268
7206
  });
7269
7207
  }
7270
- handle(m) {
7271
- if (m.error_message) {
7272
- this.diag("stt_error", { message: String(m.error_message), code: m.error_code });
7273
- return log11.error(`soniox: ${m.error_message}`);
7208
+ /** Resolve any question a settling/cancelled task left parked (its answer can no longer matter). */
7209
+ dropAsk(id) {
7210
+ this.pendingAsks.get(id)?.resolve("");
7211
+ }
7212
+ /** Build the INTEGRATION TURN prompt for a NON-CLEAN settled worker (early stop / failure). A clean
7213
+ * success never reaches here — it streams its own `<spoken>` delivery during the run. For a partial
7214
+ * or failed result the outcome re-enters the reflex as a decision (like a tool_result flowing back
7215
+ * into a normal agent loop): the reflex evaluates the outcome against the original intent and chooses
7216
+ * what to do next.
7217
+ *
7218
+ * Decision branches (the reflex acts on them with EXISTING tools — no new surface):
7219
+ * • accept → SPEAK the (partial) result plainly — don't dress a failure up as success.
7220
+ * • escalate → call `Think` with the SAME brief — only when Act failed/stalled AND a Think tier
7221
+ * exists AND this task wasn't already a follow-up (one hop max). Wires the dead
7222
+ * "Reserve Think for a problem Act already FAILED at" promise.
7223
+ * • re-delegate→ call `Act` with a CORRECTED brief — for a recoverable error / partial result.
7224
+ * • ask → ask the user ONE concrete question if genuinely blocked.
7225
+ *
7226
+ * Keeps the `[task <id> completed]` / `[task <id> failed]` opener so existing coalescing + the
7227
+ * failed-revoice fallback still fire, and the per-event transcript markers stay intact. */
7228
+ integrationPrompt(rec, outcome, body, finishReason) {
7229
+ const opener = outcome === "error" ? `[task ${rec.id} failed]` : `[task ${rec.id} completed]`;
7230
+ const underCap = this.autoEscalations < _DuplexAgent.MAX_AUTO_ESCALATIONS;
7231
+ const canEscalate = (outcome === "error" || outcome === "incomplete") && underCap;
7232
+ const hasThink = this.options.thinkModel !== false;
7233
+ const options = [];
7234
+ if (!rec.followUp && canEscalate && hasThink)
7235
+ 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");
7236
+ if (!rec.followUp && canEscalate)
7237
+ options.push("RE-DELEGATE to Act with a corrected brief if the failure looks recoverable (a wrong path, a fixable mistake)");
7238
+ options.push("ASK the user one short, concrete question if you genuinely cannot proceed without their input");
7239
+ options.push("ACCEPT and tell the user plainly what happened (don't dress a failure up as success)");
7240
+ 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.`;
7241
+ const state = outcome === "error" ? `the worker FAILED with: ${body}` : `the worker STOPPED EARLY (${finishReason}) \u2014 its result is PARTIAL, not a finished success: ${body}`;
7242
+ return `${opener} Original request: "${rec.brief}". Outcome: ${state}.${decision}`;
7243
+ }
7244
+ onWorkerSettled(id, res) {
7245
+ this.dropAsk(id);
7246
+ const rec = this.tasks.get(id);
7247
+ if (res.finishReason === "aborted" || rec.status === "cancelled") {
7248
+ rec.status = "cancelled";
7249
+ this.notify("task_cancelled", `task ${id} (${rec.label}) cancelled`);
7250
+ return;
7274
7251
  }
7275
- let endpoint = false;
7276
- for (const t of m.tokens ?? []) {
7277
- if (t.text === "<end>") endpoint = true;
7278
- else if (t.is_final) this.finalText += t.text;
7252
+ if (res.finishReason === "error") {
7253
+ const msg = res.error instanceof Error ? res.error.message : String(res.error ?? "unknown error");
7254
+ return this.failTask(rec, msg);
7279
7255
  }
7280
- this.partialText = (m.tokens ?? []).filter((t) => !t.is_final && t.text !== "<end>").map((t) => t.text).join("");
7281
- const combined = this.finalText + this.partialText;
7282
- if (combined !== this.lastCombined) {
7283
- this.lastCombined = combined;
7284
- this.lastChangeAt = now();
7285
- if (!this.firstTokenAt && combined.trim()) this.firstTokenAt = now();
7256
+ rec.status = "done";
7257
+ rec.result = res.text;
7258
+ const incomplete = res.finishReason !== "stop";
7259
+ log12.verbose(`task ${id} done (${res.steps} steps${incomplete ? `, INCOMPLETE: ${res.finishReason}` : ""})`);
7260
+ this.notify("task_done", `task ${id} (${rec.label}) completed`, {
7261
+ id,
7262
+ text: res.text,
7263
+ usage: res.usage,
7264
+ usageEstimated: res.usageEstimated,
7265
+ finishReason: res.finishReason,
7266
+ steps: res.steps,
7267
+ toolCalls: res.messages.filter((m) => m.role === "tool").length
7268
+ });
7269
+ if (incomplete) {
7270
+ return this.queueRevoice(this.integrationPrompt(rec, "incomplete", res.text, res.finishReason), true);
7286
7271
  }
7287
- this.onPartial(combined);
7288
- if (endpoint && this.finalText.trim()) {
7289
- const utterance = this.finalText.trim();
7290
- if (this.firstTokenAt) log11.debug(`stt: ${Math.round(now() - this.firstTokenAt)}ms first-token\u2192endpoint, "${utterance.slice(0, 60)}"`);
7291
- this.reset();
7292
- this.onUtterance(utterance, now());
7272
+ const tail = rec.splitter?.flush();
7273
+ if (tail?.spoken && !rec.deliveryParked) this.options.host?.notify?.({ kind: "speak_utterance", message: tail.spoken });
7274
+ if (res.text.trim()) this.voice.transcript.push({ role: "assistant", content: res.text });
7275
+ if (rec.deliveryParked && !this.suppressParkedResume) {
7276
+ const gist = (rec.spokenText ?? "").trim() || res.text.trim();
7277
+ if (gist) {
7278
+ if (this.awaitTrivialRedeliver) {
7279
+ this.awaitTrivialRedeliver = false;
7280
+ this.options.host?.notify?.({ kind: "speak_utterance", message: gist });
7281
+ this.notify("diag", "parked_redelivered", { chars: gist.length });
7282
+ } else this.parkedRedeliver.push(gist);
7283
+ }
7293
7284
  }
7285
+ if (!rec.splitter?.spokeAny && res.text.trim() && !rec.deliveryParked)
7286
+ this.options.host?.notify?.({ kind: "speak_utterance", message: res.text });
7294
7287
  }
7295
- reset() {
7296
- this.finalText = "";
7297
- this.partialText = "";
7298
- this.lastCombined = "";
7299
- this.firstTokenAt = 0;
7288
+ onWorkerFailed(id, err2) {
7289
+ this.failTask(this.tasks.get(id), err2 instanceof Error ? err2.message : String(err2));
7300
7290
  }
7301
- stop() {
7302
- this.stopped = true;
7303
- if (this.endpointTimer) clearInterval(this.endpointTimer);
7304
- if (this.noAudioTimer) clearInterval(this.noAudioTimer);
7305
- this.options.source?.stop();
7306
- if (this.ws) this.ws.onclose = null;
7307
- this.ws?.close();
7291
+ failTask(rec, msg) {
7292
+ this.dropAsk(rec.id);
7293
+ rec.status = "error";
7294
+ rec.result = msg;
7295
+ log12.warn(`task ${rec.id} failed: ${msg}`);
7296
+ this.notify("task_error", `task ${rec.id} (${rec.label}) failed: ${msg}`);
7297
+ this.queueRevoice(this.integrationPrompt(rec, "error", msg, "error"), true);
7308
7298
  }
7309
- };
7310
-
7311
- // src/voice/cartesia.ts
7312
- init_logging();
7313
- var log12 = forComponent("CartesiaTTS");
7314
- var now2 = () => performance.now();
7315
- var CartesiaTTSOptions = class {
7316
- auth = "";
7317
- voiceId = "";
7318
- model = "sonic-3.5";
7319
- /** 'apiKey' (server/CLI) → `api_key=` URL param; 'token' (browser, BE-minted) → `access_token=`. */
7320
- authMode = "apiKey";
7321
- };
7322
- var CartesiaTTS = class _CartesiaTTS {
7323
- options;
7324
- ws;
7325
- ctxSeq = 0;
7326
- ctxId = "";
7327
- onAudio = () => {
7328
- };
7329
- onDone = () => {
7330
- };
7331
- /** Word-level timestamps for karaoke reveal: `start[i]` = seconds from turn-audio start (absolute
7332
- * across continuation chunks). Fired only when a consumer opts into reveal (see `wantTimestamps`). */
7333
- onTimestamps = () => {
7334
- };
7335
- /** Request `add_timestamps` from Cartesia. Off by default (saves bandwidth) — the engine sets it
7336
- * when revealMode==='word'. */
7337
- wantTimestamps = false;
7338
- /** Diagnostic tap (provider errors, circuit-breaker open/close, ws reconnects). Fire-and-forget:
7339
- * a throwing handler disables itself — never affects synthesis. Wired by VoiceIO / the lab bridge. */
7340
- onDiag = () => {
7341
- };
7342
- diagOn = true;
7343
- diag(kind, fields) {
7344
- if (!this.diagOn) return;
7345
- try {
7346
- this.onDiag({ t: now2(), kind, ...fields });
7347
- } catch (e) {
7348
- this.diagOn = false;
7349
- log12.debug(`onDiag threw \u2014 TTS diagnostics disabled: ${e instanceof Error ? e.message : e}`);
7350
- }
7299
+ // --- voice tools (closures over this instance) ---
7300
+ /** Live-switch the think tier: `false` disables (removes the Think tool from the voice agent),
7301
+ * a model id enables (adds the tool if missing). The system-prompt THINK_SLOT text is frozen at
7302
+ * construction — the tool's own description carries the routing guidance, so a live enable works;
7303
+ * dispatch()'s think→act fallback covers any straggler calls after a live disable. */
7304
+ setThinkModel(model) {
7305
+ this.options.thinkModel = model;
7306
+ const tools = this.voice.options.tools;
7307
+ const i = tools.findIndex((t) => t.name === "Think");
7308
+ if (model === false && i >= 0) tools.splice(i, 1);
7309
+ else if (model !== false && i < 0) tools.push(this.thinkTool());
7351
7310
  }
7352
- firstAudioAt = 0;
7353
- /** Circuit breaker: consecutive error count + down flag. */
7354
- consecutiveErrors = 0;
7355
- consecutiveOk = 0;
7356
- down = false;
7357
- downAt = 0;
7358
- probeTimer = null;
7359
- static CB_THRESHOLD = 3;
7360
- // open after 3 consecutive errors
7361
- static CB_RECOVER_OK = 2;
7362
- // close only after 2 consecutive good frames (no single-frame flap)
7363
- static CB_PROBE_MS = 3e4;
7364
- constructor(options) {
7365
- this.options = { ...new CartesiaTTSOptions(), ...options };
7311
+ /** User/programmatic spawn: the CLI's /act and /think commands. Returns the task id.
7312
+ * `followUp` marks an automatic escalation/re-delegation (set by the integration turn) so the new
7313
+ * task's own integration turn won't escalate again — capping auto-follow-ups to one hop. */
7314
+ async dispatch(brief, tier = "act", label, followUp = false) {
7315
+ if (tier === "think" && this.options.thinkModel === false) tier = "act";
7316
+ if (followUp) this.autoEscalations++;
7317
+ const id = `t${++this.seq}`;
7318
+ const lbl = label ?? tier;
7319
+ await this.options.onTaskStart?.(id, lbl);
7320
+ this.spawnWorker(id, lbl, this.buildBrief(brief, tier), tier, brief, followUp);
7321
+ this.notify("task_started", `task ${id} (${lbl}) started`, { id, brief, tier });
7322
+ return id;
7366
7323
  }
7367
- closed = false;
7368
- connecting = null;
7369
- async connect() {
7370
- this.closed = false;
7371
- this.connecting = this.doConnect();
7372
- await this.connecting;
7373
- this.connecting = null;
7324
+ actTool() {
7325
+ return {
7326
+ name: "Act",
7327
+ 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).',
7328
+ parameters: {
7329
+ type: "object",
7330
+ required: ["brief"],
7331
+ properties: {
7332
+ brief: { type: "string", description: "full, self-contained instructions for the worker" },
7333
+ label: { type: "string", description: "a short (2-4 word) label for the task" }
7334
+ }
7335
+ },
7336
+ run: async ({ brief, label }) => {
7337
+ this.spokeBeforeDispatch = this.spokeThisTurn;
7338
+ this.turnDispatched = true;
7339
+ this.turnBriefs.add(String(brief ?? ""));
7340
+ this.voice.options.toolChoice = "none";
7341
+ const id = await this.dispatch(String(brief ?? ""), "act", label ? String(label) : void 0, this.turnFollowUp);
7342
+ 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.`;
7343
+ }
7344
+ };
7374
7345
  }
7375
- async doConnect() {
7376
- const key = await resolveAuth(this.options.auth);
7377
- const param = this.options.authMode === "token" ? "access_token" : "api_key";
7378
- this.ws = new WebSocket(`wss://api.cartesia.ai/tts/websocket?cartesia_version=2026-03-01&${param}=${key}`);
7379
- await new Promise((res, rej) => {
7380
- this.ws.onopen = () => res();
7381
- this.ws.onerror = (e) => rej(new Error(`cartesia ws: ${e.message || "connect failed"}`));
7382
- });
7383
- this.ws.onclose = (ev) => {
7384
- log12.warn(`cartesia ws closed (${ev.code} ${ev.reason || ""})`);
7385
- this.diag("tts_ws_closed", { code: ev.code, reason: String(ev.reason || ""), reconnecting: !this.closed });
7386
- if (!this.closed) {
7387
- this.connecting = this.doConnect().catch((e) => {
7388
- log12.error(`cartesia reconnect failed: ${e.message}`);
7389
- this.diag("tts_reconnect_failed", { message: e.message });
7390
- });
7346
+ thinkTool() {
7347
+ return {
7348
+ name: "Think",
7349
+ 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.",
7350
+ parameters: {
7351
+ type: "object",
7352
+ required: ["brief"],
7353
+ properties: {
7354
+ brief: { type: "string", description: "the question or problem to reason about deeply" },
7355
+ label: { type: "string", description: "a short (2-4 word) label for the task" }
7356
+ }
7357
+ },
7358
+ run: async ({ brief, label }) => {
7359
+ this.spokeBeforeDispatch = this.spokeThisTurn;
7360
+ this.turnDispatched = true;
7361
+ this.turnBriefs.add(String(brief ?? ""));
7362
+ this.voice.options.toolChoice = "none";
7363
+ const id = await this.dispatch(String(brief ?? ""), "think", label ? String(label) : void 0, this.turnFollowUp);
7364
+ 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.`;
7391
7365
  }
7392
7366
  };
7393
- this.ws.onmessage = (ev) => {
7394
- const m = JSON.parse(String(ev.data));
7395
- if (m.context_id && m.context_id !== this.ctxId) return;
7396
- if (m.type === "chunk" && m.data) {
7397
- this.consecutiveErrors = 0;
7398
- this.markRecovered();
7399
- if (!this.firstAudioAt) this.firstAudioAt = now2();
7400
- this.onAudio(base64ToBytes(m.data));
7401
- } else if (m.type === "done") {
7402
- this.consecutiveErrors = 0;
7403
- this.markRecovered();
7404
- this.onDone();
7405
- } else if (m.type === "timestamps" && m.word_timestamps) {
7406
- const wt = m.word_timestamps;
7407
- if (wt.words?.length && wt.start?.length) this.onTimestamps(wt.words, wt.start);
7408
- } else if (m.type === "error") {
7409
- if (/already been cancelled|does not exist/.test(m.message || "")) return;
7410
- this.consecutiveErrors++;
7411
- this.diag("tts_error", { message: String(m.message || ""), code: m.status_code, contextId: m.context_id, consecutive: this.consecutiveErrors });
7412
- if (!this.down && this.consecutiveErrors >= _CartesiaTTS.CB_THRESHOLD) {
7413
- this.down = true;
7414
- this.downAt = now2();
7415
- this.consecutiveOk = 0;
7416
- log12.warn(`TTS circuit breaker open \u2014 ${this.consecutiveErrors} consecutive errors, switching to text-only`);
7417
- this.diag("tts_breaker_open", { errors: this.consecutiveErrors });
7418
- this.onDone();
7419
- this.startProbe();
7420
- } else if (!this.down) {
7421
- (/No valid transcripts/i.test(m.message || "") ? log12.debug : log12.warn)(`cartesia: ${JSON.stringify(m)}`);
7367
+ }
7368
+ taskStatusTool() {
7369
+ return {
7370
+ name: "TaskStatus",
7371
+ description: "Status of background tasks. Pass `id` for one task, or omit it to list all.",
7372
+ parameters: { type: "object", properties: { id: { type: "string" } } },
7373
+ run: async ({ id }) => {
7374
+ const list = id ? [this.tasks.get(String(id))].filter(Boolean) : [...this.tasks.values()];
7375
+ if (!list.length) return id ? `No task '${id}'.` : "No background tasks.";
7376
+ return list.map((t) => `${t.id} (${t.label}): ${t.status}`).join("\n");
7377
+ }
7378
+ };
7379
+ }
7380
+ /** Sub-100ms read-only lookups the voice may do itself — everything else stays Act-only.
7381
+ * fs-only (no shell; the engine is VFS-abstracted): time, git branch (.git/HEAD read), ls, file
7382
+ * head. Output is hard-capped so a lookup can never bloat the skinny voice context. */
7383
+ quickLookTool() {
7384
+ const CAP2 = 2e3;
7385
+ const kinds = [.../* @__PURE__ */ new Set(["time", "branch", "ls", "file", "capabilities", ...Object.keys(this.options.quickLook ?? {})])];
7386
+ return {
7387
+ name: "QuickLook",
7388
+ description: `Instant read-only lookup \u2014 one of: ${kinds.join(", ")}. For trivial facts only; anything needing search, commands, or reasoning goes through Act.`,
7389
+ parameters: {
7390
+ type: "object",
7391
+ required: ["what"],
7392
+ properties: {
7393
+ what: { type: "string", enum: kinds, description: "what to look up" },
7394
+ path: { type: "string", description: "for ls/file: the path to look at" }
7395
+ }
7396
+ },
7397
+ run: async ({ what, path }) => {
7398
+ const fs = this.options.fs;
7399
+ try {
7400
+ const over = this.options.quickLook?.[String(what)];
7401
+ if (over) return await over(path ? String(path) : void 0);
7402
+ switch (String(what)) {
7403
+ case "capabilities": {
7404
+ const actTools = this.options.actOptions?.tools ?? [];
7405
+ const names = actTools.map((t) => t.name);
7406
+ const mcpServers = Object.keys(this.options.actOptions?.providerOptions?.mcpServers ?? {});
7407
+ 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).` : "";
7408
+ if (!names.length)
7409
+ 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;
7410
+ const hasFetch = names.some((n) => /WebFetch/i.test(n));
7411
+ const hasBrowser = names.some((n) => /browser.*(navigate|click|page|type)/i.test(n));
7412
+ const hasSearch = names.some((n) => /(^|_)WebSearch$|search/i.test(n) && !/WebFetch|browser/i.test(n));
7413
+ const notes = [];
7414
+ if (hasFetch) notes.push("WebFetch retrieves ONE specific URL you are given \u2014 it is not a search engine.");
7415
+ 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.");
7416
+ 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.');
7417
+ const webNote = notes.length ? " NOTE: " + notes.join(" ") : "";
7418
+ 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;
7419
+ }
7420
+ case "time":
7421
+ return (/* @__PURE__ */ new Date()).toString();
7422
+ case "branch": {
7423
+ if (!fs) return "unavailable (no filesystem)";
7424
+ const head = (await fs.readFile(".git/HEAD")).trim();
7425
+ return head.startsWith("ref: refs/heads/") ? `branch: ${head.slice("ref: refs/heads/".length)}` : `detached HEAD at ${head.slice(0, 12)}`;
7426
+ }
7427
+ case "ls": {
7428
+ if (!fs) return "unavailable (no filesystem)";
7429
+ const p = String(path ?? ".");
7430
+ try {
7431
+ const names = await fs.readDir(p);
7432
+ return names.slice(0, 50).join("\n") + (names.length > 50 ? `
7433
+ \u2026 (+${names.length - 50} more)` : "");
7434
+ } catch {
7435
+ const names = await fs.readDir(".").catch(() => []);
7436
+ return `'${p}' not found here \u2014 you are likely already inside it. Current directory listing:
7437
+ ` + names.slice(0, 50).join("\n") + (names.length > 50 ? `
7438
+ \u2026 (+${names.length - 50} more)` : "");
7439
+ }
7440
+ }
7441
+ case "file": {
7442
+ if (!fs) return "unavailable (no filesystem)";
7443
+ if (!path) return "file lookup needs a path";
7444
+ try {
7445
+ const text = await fs.readFile(String(path));
7446
+ return text.length > CAP2 ? text.slice(0, CAP2) + `
7447
+ \u2026 (truncated \u2014 ${text.length} chars total; Act for the full file)` : text;
7448
+ } catch {
7449
+ const names = await fs.readDir(".").catch(() => []);
7450
+ return `'${path}' not found. Current directory contains:
7451
+ ` + names.slice(0, 50).join("\n");
7452
+ }
7453
+ }
7454
+ default:
7455
+ return `unknown lookup '${what}'`;
7456
+ }
7457
+ } catch (e) {
7458
+ return `lookup failed: ${e?.message ?? e}`;
7422
7459
  }
7423
7460
  }
7424
7461
  };
7425
7462
  }
7426
- /** Close the breaker only after CB_RECOVER_OK consecutive good frames, so a single straggler chunk
7427
- * after a 503 burst doesn't flap open→recover in <1s. A sub-2s down-window is a transient blip → debug. */
7428
- markRecovered() {
7429
- if (!this.down) return;
7430
- if (++this.consecutiveOk < _CartesiaTTS.CB_RECOVER_OK) return;
7431
- this.down = false;
7432
- this.consecutiveOk = 0;
7433
- this.stopProbe();
7434
- const downMs = this.downAt ? now2() - this.downAt : 0;
7435
- this.diag("tts_breaker_close", { downMs: Math.round(downMs) });
7436
- (downMs < 2e3 ? log12.debug : log12.info)(`TTS recovered${downMs ? ` (down ${downMs}ms)` : ""}`);
7437
- }
7438
- /** Ensure the WS is open before sending — reconnects if idle-closed. */
7439
- async ensureConnected() {
7440
- if (this.connecting) await this.connecting;
7441
- if (this.ws?.readyState !== WebSocket.OPEN) await this.connect();
7442
- }
7443
- /** Prime the synthesis pipeline on a throwaway context right after connect: the FIRST synthesis on
7444
- * a fresh WS pays Cartesia's cold spin-up (~1s+ live) — absorb it at mic-on instead of turn one.
7445
- * The returned audio is discarded (engine drops onAudio while not speaking; once a real turn calls
7446
- * newContext() any stragglers are stale-context-filtered). Respects the circuit breaker. */
7447
- warmup() {
7448
- if (this.down) return;
7449
- this.newContext();
7450
- if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(this.frame("Ok.", false));
7451
- }
7452
- newContext() {
7453
- this.ctxId = `ctx-${++this.ctxSeq}`;
7454
- this.firstAudioAt = 0;
7455
- return this.ctxId;
7463
+ answerTaskTool() {
7464
+ return {
7465
+ name: "AnswerTask",
7466
+ 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.`,
7467
+ parameters: {
7468
+ type: "object",
7469
+ required: ["id", "answer"],
7470
+ properties: { id: { type: "string" }, answer: { type: "string", description: "the user's answer, verbatim or faithfully summarized" } }
7471
+ },
7472
+ run: async ({ id, answer }) => {
7473
+ const ask = this.pendingAsks.get(String(id));
7474
+ if (!ask) return `No pending question for '${id}' \u2014 it may have been answered already or timed out.`;
7475
+ ask.resolve(String(answer ?? ""));
7476
+ return `Answer relayed \u2014 task ${id} resumes.`;
7477
+ }
7478
+ };
7456
7479
  }
7457
- frame(transcript, cont) {
7458
- return JSON.stringify({
7459
- model_id: this.options.model,
7460
- transcript,
7461
- voice: { mode: "id", id: this.options.voiceId },
7462
- output_format: { container: "raw", encoding: "pcm_s16le", sample_rate: TTS_SAMPLE_RATE },
7463
- context_id: this.ctxId,
7464
- continue: cont,
7465
- ...this.wantTimestamps ? { add_timestamps: true } : {}
7466
- });
7480
+ holdTool() {
7481
+ return {
7482
+ name: "Hold",
7483
+ 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.',
7484
+ parameters: {
7485
+ type: "object",
7486
+ properties: {
7487
+ filler: { type: "string", description: 'optional short filler to speak ("mhm", "go on", "mm-hm")' }
7488
+ }
7489
+ },
7490
+ run: async ({ filler }) => {
7491
+ this.heldThisTurn = true;
7492
+ this.notify("hold_filler", filler ? String(filler) : "");
7493
+ return "Holding \u2014 listening for the rest of the user's thought. Do not respond further this turn.";
7494
+ }
7495
+ };
7467
7496
  }
7468
- speak(text, cont) {
7469
- if (this.down) return;
7470
- if (cont && !text) return;
7471
- if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(this.frame(text, cont));
7472
- else void this.ensureConnected().then(() => this.ws?.readyState === WebSocket.OPEN && this.ws.send(this.frame(text, cont)));
7497
+ cancelTaskTool() {
7498
+ return {
7499
+ name: "CancelTask",
7500
+ description: "Cancel a running background task by id.",
7501
+ parameters: { type: "object", required: ["id"], properties: { id: { type: "string" } } },
7502
+ run: async ({ id }) => this.cancelTask(String(id))
7503
+ };
7473
7504
  }
7474
- end() {
7475
- if (this.down) {
7476
- this.onDone();
7477
- return;
7505
+ };
7506
+
7507
+ // src/mcp.ts
7508
+ function toResult(result) {
7509
+ if (result == null) return { text: "" };
7510
+ if (typeof result === "string") return { text: result };
7511
+ const content = result.content;
7512
+ if (Array.isArray(content)) {
7513
+ const texts = [];
7514
+ const images = [];
7515
+ for (const c of content) {
7516
+ if (c?.type === "image" && typeof c.data === "string" && c.mimeType) {
7517
+ images.push({ mimeType: c.mimeType, data: c.data });
7518
+ } else if (typeof c?.text === "string") {
7519
+ texts.push(c.text);
7520
+ } else {
7521
+ texts.push(JSON.stringify(c));
7522
+ }
7478
7523
  }
7479
- if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(this.frame("", false));
7480
- }
7481
- cancel() {
7482
- if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(JSON.stringify({ context_id: this.ctxId, cancel: true }));
7524
+ const text = texts.join("\n");
7525
+ if (text || images.length) return { text, ...images.length ? { images } : {} };
7483
7526
  }
7484
- startProbe() {
7485
- if (this.probeTimer) return;
7486
- this.probeTimer = setInterval(() => {
7487
- if (!this.down) {
7488
- this.stopProbe();
7489
- return;
7527
+ return { text: JSON.stringify(result) };
7528
+ }
7529
+ function mcpToolToAgentTool(spec, callTool, prefix = "mcp__") {
7530
+ return {
7531
+ name: `${prefix}${spec.name}`,
7532
+ description: spec.description ?? `MCP tool ${spec.name}`,
7533
+ parameters: spec.inputSchema ?? { type: "object", properties: {} },
7534
+ async run(args, _ctx) {
7535
+ const r = toResult(await callTool(spec.name, args ?? {}));
7536
+ return r.images?.length ? r : r.text;
7537
+ }
7538
+ };
7539
+ }
7540
+ function mcpToolsToAgentTools(specs, callTool, prefix = "mcp__", filter) {
7541
+ return (filter ? specs.filter(filter) : specs).map((s) => mcpToolToAgentTool(s, callTool, prefix));
7542
+ }
7543
+ function describeSpec(s) {
7544
+ const schema = s.inputSchema ? `
7545
+ args: ${JSON.stringify(s.inputSchema)}` : "";
7546
+ return `${s.name} \u2014 ${s.description ?? "(no description)"}${schema}`;
7547
+ }
7548
+ function makeMcpToolSearch(specs, callTool, options = {}) {
7549
+ const maxResults = options.maxResults ?? 10;
7550
+ const byName = new Map(specs.map((s) => [s.name, s]));
7551
+ const catalogLine = `${specs.length} MCP tool(s) available \u2014 search by keyword, then call by exact name.`;
7552
+ const searchTool = {
7553
+ name: "ToolSearch",
7554
+ description: `Search the available MCP tools by keyword (${catalogLine}). Returns matching tool names + their argument schemas; call one with \`McpCall\`.`,
7555
+ parameters: { type: "object", required: ["query"], properties: { query: { type: "string", description: "keywords to match against tool name + description" } } },
7556
+ async run({ query }) {
7557
+ const q2 = String(query ?? "").trim();
7558
+ if (!q2) return catalogLine;
7559
+ const { kept } = topByRelevance(specs, q2, (s) => `${s.name} ${s.description ?? ""}`, maxResults);
7560
+ if (!kept.length) return `(no MCP tool matches "${q2}" \u2014 try broader keywords)`;
7561
+ return kept.map(describeSpec).join("\n");
7562
+ }
7563
+ };
7564
+ const callMcpTool = {
7565
+ name: "McpCall",
7566
+ description: "Call an MCP tool discovered via `ToolSearch`, by its exact name. Pass its arguments as `args`.",
7567
+ parameters: {
7568
+ type: "object",
7569
+ required: ["name"],
7570
+ properties: {
7571
+ name: { type: "string", description: "exact tool name from ToolSearch" },
7572
+ args: { type: "object", description: "arguments object for the tool (per its schema)" }
7490
7573
  }
7491
- this.consecutiveErrors = 0;
7492
- this.newContext();
7493
- if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(this.frame("Ok.", false));
7494
- }, _CartesiaTTS.CB_PROBE_MS);
7495
- this.probeTimer.unref?.();
7496
- }
7497
- stopProbe() {
7498
- if (this.probeTimer) {
7499
- clearInterval(this.probeTimer);
7500
- this.probeTimer = null;
7574
+ },
7575
+ async run({ name, args }) {
7576
+ const n = String(name ?? "");
7577
+ if (!byName.has(n)) return `Error: unknown MCP tool '${n}'. Use ToolSearch to find valid names.`;
7578
+ const r = toResult(await callTool(n, args ?? {}));
7579
+ return r.images?.length ? r : r.text;
7580
+ }
7581
+ };
7582
+ return [searchTool, callMcpTool];
7583
+ }
7584
+ function buildMcpCatalog(servers) {
7585
+ const specs = [];
7586
+ const routes = /* @__PURE__ */ new Map();
7587
+ for (const m of servers) {
7588
+ for (const s of m.specs) {
7589
+ const base = `mcp__${m.name}__${s.name}`.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 128);
7590
+ let display = base;
7591
+ for (let i = 2; routes.has(display); i++) display = `${base.slice(0, 128 - String(i).length - 1)}_${i}`;
7592
+ specs.push({ name: display, description: s.description, inputSchema: s.inputSchema });
7593
+ routes.set(display, { server: m.name, rawName: s.name });
7501
7594
  }
7502
7595
  }
7503
- close() {
7504
- this.closed = true;
7505
- this.stopProbe();
7506
- if (this.ws) this.ws.onclose = null;
7507
- this.ws?.close();
7508
- }
7509
- };
7510
- function base64ToBytes(b64) {
7511
- if (typeof Buffer !== "undefined") return Buffer.from(b64, "base64");
7512
- const bin = atob(b64);
7513
- const out = new Uint8Array(bin.length);
7514
- for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
7515
- return out;
7596
+ return { specs, routes };
7597
+ }
7598
+ function searchOverCatalog(servers, specs, routes, resolve4, options) {
7599
+ const tools = specs.length ? makeMcpToolSearch(specs, (name, args) => {
7600
+ const r = routes.get(name);
7601
+ if (!r) throw new Error(`unknown MCP tool '${name}' \u2014 use ToolSearch to find valid names`);
7602
+ return resolve4(r.server, r.rawName, args ?? {});
7603
+ }, options) : [];
7604
+ return { tools, serverNames: servers, toolCount: specs.length };
7605
+ }
7606
+ function makeMcpToolSearchFromMounted(mounted, options) {
7607
+ const { specs, routes } = buildMcpCatalog(mounted);
7608
+ const byName = new Map(mounted.map((m) => [m.name, m]));
7609
+ return searchOverCatalog(mounted.map((m) => m.name), specs, routes, (server, rawName, args) => byName.get(server).client.callTool(rawName, args), options);
7516
7610
  }
7517
7611
 
7518
7612
  // src/index.ts
7613
+ init_logging();
7519
7614
  init_worktree();
7520
7615
  import { MemFilesystem as MemFilesystem3, IndexedDbFilesystem, CommandExecutor as CommandExecutor2, registerHeadlessCommands as registerHeadlessCommands2 } from "@livx.cc/wcli/core";
7521
7616
 
@@ -10803,8 +10898,8 @@ function applyKey(s, key, str) {
10803
10898
  }
10804
10899
  return "none";
10805
10900
  }
10806
- function createLineEditor(out) {
10807
- const isTTY = !!out.isTTY && !!process.stdin.isTTY;
10901
+ function createLineEditor(out, input = keyInput) {
10902
+ const isTTY = !!out.isTTY && !!input.isTTY;
10808
10903
  const dim2 = (x) => `\x1B[2m${x}\x1B[0m`;
10809
10904
  const inverse = (x) => `\x1B[7m${x}\x1B[0m`;
10810
10905
  const COLOR = {
@@ -10892,9 +10987,9 @@ function createLineEditor(out) {
10892
10987
  curRow = 0;
10893
10988
  if (opts.initial) s.insert(opts.initial);
10894
10989
  s.refresh();
10895
- emitKeypressEvents(keyInput);
10896
- keyInput.setRawMode(true);
10897
- keyInput.resume();
10990
+ emitKeypressEvents(input);
10991
+ input.setRawMode(true);
10992
+ input.resume();
10898
10993
  out.write("\x1B[?2004h");
10899
10994
  const promptOf = () => typeof opts.prompt === "function" ? opts.prompt() : opts.prompt;
10900
10995
  render(s, promptOf(), maxVisible, opts.status);
@@ -10978,9 +11073,9 @@ function createLineEditor(out) {
10978
11073
  return;
10979
11074
  }
10980
11075
  if (key?.meta && key.name === "p" && opts.onPickModel) {
10981
- keyInput.off("keypress", onKey);
11076
+ input.off("keypress", onKey);
10982
11077
  void opts.onPickModel().finally(() => {
10983
- keyInput.on("keypress", onKey);
11078
+ input.on("keypress", onKey);
10984
11079
  curRow = 0;
10985
11080
  redraw();
10986
11081
  });
@@ -11017,7 +11112,7 @@ function createLineEditor(out) {
11017
11112
  activeRedraw = void 0;
11018
11113
  activeAbort = void 0;
11019
11114
  if (ticker) clearInterval(ticker);
11020
- keyInput.off("keypress", onKey);
11115
+ input.off("keypress", onKey);
11021
11116
  process.removeListener("SIGWINCH", onResize);
11022
11117
  s.closeMenu();
11023
11118
  if (suspended) {
@@ -11034,7 +11129,7 @@ function createLineEditor(out) {
11034
11129
  out.write([prompt + lines[0], ...lines.slice(1)].map((l) => wrapAnsi(l, cols, " ")).join("\r\n") + "\r\n");
11035
11130
  curRow = 0;
11036
11131
  };
11037
- keyInput.on("keypress", onKey);
11132
+ input.on("keypress", onKey);
11038
11133
  });
11039
11134
  }
11040
11135
  return {
@@ -11053,6 +11148,7 @@ function createLineEditor(out) {
11053
11148
  curRow = 0;
11054
11149
  activeRedraw?.();
11055
11150
  },
11151
+ isSuspended: () => suspended,
11056
11152
  abort: () => activeAbort?.()
11057
11153
  };
11058
11154
  }
@@ -11667,6 +11763,13 @@ function installUpdate() {
11667
11763
  const r = spawnSync6("bun", ["add", "-g", "@livx.cc/agentx"], { stdio: "inherit" });
11668
11764
  return (r.status ?? 1) === 0;
11669
11765
  }
11766
+ var typeaheadOnLine = false;
11767
+ var clearTypeaheadLine = () => {
11768
+ if (typeaheadOnLine) {
11769
+ err("\r\x1B[2K");
11770
+ typeaheadOnLine = false;
11771
+ }
11772
+ };
11670
11773
  var spinner = /* @__PURE__ */ (() => {
11671
11774
  const frames = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
11672
11775
  let timer;
@@ -11695,8 +11798,10 @@ var spinner = /* @__PURE__ */ (() => {
11695
11798
  clearInterval(timer);
11696
11799
  timer = void 0;
11697
11800
  err("\r\x1B[2K");
11801
+ typeaheadOnLine = false;
11698
11802
  }
11699
11803
  }
11804
+ // the tail (type-ahead) went with it
11700
11805
  };
11701
11806
  })();
11702
11807
  var setTermTitle = (t) => {
@@ -11874,7 +11979,7 @@ REPL slash commands: /help /version /tools /permissions /status /cost /context /
11874
11979
  REPL completion: type / (commands+skills) or @ (files) for a LIVE menu \u2014 \u2191/\u2193 select, \u23CE/Tab accept, Esc dismiss.
11875
11980
  REPL multi-line: Option/Alt+Enter inserts a newline, or end a line with \\ to continue. Esc cancels a running turn / clears the input line; double-Esc jumps back to edit a previous message.
11876
11981
  REPL shortcuts: Shift+Tab cycles permission posture (ask \u2192 accept-edits \u2192 plan) \xB7 Alt+T toggles reasoning \xB7 Alt+P switches model \xB7 Ctrl+O toggles verbose tool output \xB7 Ctrl+X Ctrl+E edits the buffer in $EDITOR \xB7 \u2192 or Tab accepts the dim history ghost-suggestion \xB7 Alt+S/Ctrl+S stash/unstash.
11877
- REPL stash: type while a turn is running \u2192 Enter queues it (auto-submits when the turn finishes). Alt+S (or Ctrl+S) with text stashes it; on an empty prompt pops the next entry for editing.
11982
+ REPL steer/stash: type while a turn is running \u2192 Enter STEERS it (the text reaches the model at its next step, alongside the next tool result). Alt+S (or Ctrl+S) with text stashes it for AFTER the turn instead; on an empty prompt pops the next stashed entry for editing.
11878
11983
  REPL editing (emacs/readline): Ctrl-A/E line start/end \xB7 Ctrl-B/F char \xB7 Alt-B/F or Alt/Ctrl-\u2190/\u2192 word \xB7 Ctrl-W kill word \xB7 Ctrl-U/K kill to start/end \xB7 Ctrl-Y yank \xB7 Ctrl-_ undo \xB7 Alt-D kill word fwd \xB7 Ctrl-L clear screen. Set editorMode:'vim' (or /config) for modal vim editing.
11879
11984
  REPL paste: large/multi-line pastes collapse to a [Pasted text +N lines] preview (expands on send); a pasted image/file path attaches as [Image]/[File]; Ctrl-V or /paste grabs a clipboard image (macOS).`;
11880
11985
  function newestModel() {
@@ -11962,9 +12067,11 @@ function makeHost(format = "text", opts) {
11962
12067
  notify(e) {
11963
12068
  if (e.kind === "turn_start") {
11964
12069
  activitySeen.clear();
12070
+ typeaheadOnLine = false;
11965
12071
  return;
11966
12072
  }
11967
12073
  spinner.stop();
12074
+ clearTypeaheadLine();
11968
12075
  if (e.kind === "text_delta") {
11969
12076
  flushLookupGroup();
11970
12077
  if (streamJson) process.stdout.write(JSON.stringify({ type: "text", text: e.message }) + "\n");
@@ -12111,7 +12218,10 @@ function displayHooks(fs, opts) {
12111
12218
  if (call.name === "TodoWrite" && Array.isArray(call.args?.todos)) latestTodos = call.args.todos;
12112
12219
  if (!on()) return;
12113
12220
  if (bg) err("\r\x1B[0J");
12114
- else spinner.stop();
12221
+ else {
12222
+ spinner.stop();
12223
+ clearTypeaheadLine();
12224
+ }
12115
12225
  flush();
12116
12226
  if (!bg && !verboseOutput && LOOKUP.has(call.name)) {
12117
12227
  pendingHeader = header(call);
@@ -12132,7 +12242,10 @@ function displayHooks(fs, opts) {
12132
12242
  async postToolUse(call, result) {
12133
12243
  if (!on()) return;
12134
12244
  if (bg) err("\r\x1B[0J");
12135
- else spinner.stop();
12245
+ else {
12246
+ spinner.stop();
12247
+ clearTypeaheadLine();
12248
+ }
12136
12249
  try {
12137
12250
  if (pendingHeader) {
12138
12251
  const t = String(result).replace(/\s+$/, "");
@@ -12929,6 +13042,12 @@ async function repl(args, ai, cfg, cwd) {
12929
13042
  };
12930
13043
  let toggleVoice;
12931
13044
  let editorRef;
13045
+ const emitChrome = (write) => {
13046
+ const wasSusp = editorRef?.isSuspended() ?? true;
13047
+ editorRef?.suspend();
13048
+ write();
13049
+ if (!wasSusp) editorRef?.resume();
13050
+ };
12932
13051
  let repaintStash = () => {
12933
13052
  };
12934
13053
  let workerOptions;
@@ -13050,23 +13169,23 @@ async function repl(args, ai, cfg, cwd) {
13050
13169
  if (e.kind === "task_done" && e.data?.text) {
13051
13170
  const lines = String(e.data.text).split("\n");
13052
13171
  const shown = lines.slice(0, previewLines());
13053
- err("\r\x1B[0J\n" + dim(` \u29BF ${e.message}
13172
+ emitChrome(() => {
13173
+ err("\n" + dim(` \u29BF ${e.message}
13054
13174
  `) + shown.map((l) => dim(` ${plainLine(l)}
13055
13175
  `)).join(""));
13056
- if (lines.length > shown.length) err(dim(` \u2026 (+${lines.length - shown.length} more lines)
13176
+ if (lines.length > shown.length) err(dim(` \u2026 (+${lines.length - shown.length} more lines)
13057
13177
  `));
13178
+ });
13058
13179
  duplexAccount(e.data);
13059
- editorRef?.redrawNow();
13060
13180
  repaintStash();
13061
13181
  return;
13062
13182
  }
13063
13183
  if (typeof e.kind === "string" && e.kind.startsWith("task_")) {
13064
13184
  spinner.stop();
13065
- err("\r\x1B[0J" + (e.kind === "task_ask" ? yellow(` ? ${e.message} \u2014 answer by voice or type yes/no
13185
+ emitChrome(() => err(e.kind === "task_ask" ? yellow(` ? ${e.message} \u2014 answer by voice or type yes/no
13066
13186
  `) : e.kind === "task_error" ? yellow(` \u2717 ${e.message}
13067
13187
  `) : dim(` \xB7 ${e.message}
13068
13188
  `)));
13069
- editorRef?.redrawNow();
13070
13189
  repaintStash();
13071
13190
  return;
13072
13191
  }
@@ -14583,6 +14702,7 @@ ${task}`;
14583
14702
  const renderStashBuf = () => {
14584
14703
  if (spinner.active) return;
14585
14704
  err(`\r\x1B[K${sEd.buf ? " " + stashView() : ""}`);
14705
+ typeaheadOnLine = !!sEd.buf;
14586
14706
  };
14587
14707
  repaintStash = renderStashBuf;
14588
14708
  keyInput.on("keypress", (_s, key) => {
@@ -14615,11 +14735,18 @@ ${task}`;
14615
14735
  if (action === "submit") {
14616
14736
  const text = sEd.expand().trim();
14617
14737
  sEd.reset();
14738
+ typeaheadOnLine = false;
14618
14739
  if (text) {
14619
- inputStash.push(text);
14620
14740
  const view = text.replace(/\n+/g, " \u23CE ");
14621
- err(`\r\x1B[K${green(" \u2713 stashed")} ${dim(`#${inputStash.length}: ${view.slice(0, 50)}${view.length > 50 ? "\u2026" : ""}`)}
14741
+ if ((activeTurn || dispatchPending) && !duplex) {
14742
+ agent.inject(text);
14743
+ err(`\r\x1B[K${bold(cyan(" \u21B3 steering \u203A"))} ${cyan(`${view.slice(0, 60)}${view.length > 60 ? "\u2026" : ""}`)}
14744
+ `);
14745
+ } else {
14746
+ inputStash.push(text);
14747
+ err(`\r\x1B[K${green(" \u2713 stashed")} ${dim(`#${inputStash.length}: ${view.slice(0, 50)}${view.length > 50 ? "\u2026" : ""}`)}
14622
14748
  `);
14749
+ }
14623
14750
  }
14624
14751
  return;
14625
14752
  }
@@ -15000,6 +15127,7 @@ ${out}
15000
15127
  }
15001
15128
  let quit = await dispatchLine(line) === "quit";
15002
15129
  const wasLocal = /^[!#/]/.test(line);
15130
+ if (wasLocal) agent.clearInjections();
15003
15131
  while (!quit && !wasLocal && inputStash.length) {
15004
15132
  const next = inputStash.shift();
15005
15133
  const nview = next.replace(/\n+/g, " \u23CE ");