@livx.cc/agentx 0.99.13 → 0.99.15

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
@@ -3318,7 +3318,34 @@ var AgentOptions = class {
3318
3318
  * `'off'`/undefined = none; `'low'|'medium'|'high'` or a raw token budget. Mapped to the
3319
3319
  * provider-specific request shape via {@link reasoningToChatFragment}; explicit `providerOptions` wins. */
3320
3320
  reasoning;
3321
+ /** Seed a fresh `run()` with prior conversation turns (real role/content messages) so the model
3322
+ * sees history as structured turns instead of a flattened text blob. They are inserted AFTER the
3323
+ * stable system prompt and BEFORE the current user turn — so the cached system(+tools) prefix never
3324
+ * shifts. Turns are normalized before sending (empties dropped, adjacent same-role coalesced, and the
3325
+ * first tail turn forced to `user`) so the transcript is always a valid Anthropic alternation ending
3326
+ * at the current user prompt. Unset/empty ⇒ current behavior, byte-for-byte. */
3327
+ priorMessages;
3321
3328
  };
3329
+ function seedTranscriptTail(prior, current) {
3330
+ const seq = (prior ?? []).filter((m) => contentText(m.content).trim().length > 0).map((m) => ({ role: m.role, content: m.content }));
3331
+ seq.push({ role: "user", content: current });
3332
+ const out = [];
3333
+ for (const m of seq) {
3334
+ const last = out[out.length - 1];
3335
+ if (last && last.role === m.role) {
3336
+ if (typeof last.content === "string" && typeof m.content === "string") {
3337
+ last.content = `${last.content}
3338
+
3339
+ ${m.content}`;
3340
+ continue;
3341
+ }
3342
+ out.push({ role: m.role === "user" ? "assistant" : "user", content: "(continuing)" });
3343
+ }
3344
+ out.push({ role: m.role, content: m.content });
3345
+ }
3346
+ if (out.length && out[0].role !== "user") out.unshift({ role: "user", content: "(Earlier conversation)" });
3347
+ return out;
3348
+ }
3322
3349
  var Agent = class _Agent {
3323
3350
  options;
3324
3351
  transcript = [];
@@ -3486,7 +3513,9 @@ var Agent = class _Agent {
3486
3513
  const userContent = await this.applyPromptSubmit(task);
3487
3514
  this.transcript = [
3488
3515
  { role: "system", content: systemPrompt + (startCtx ? "\n\n" + startCtx : "") },
3489
- { role: "user", content: userContent }
3516
+ // Prior turns (if any) sit between the stable system prefix and the live user turn — the cached
3517
+ // system(+tools) prefix is unaffected; normalization keeps the alternation valid.
3518
+ ...seedTranscriptTail(this.options.priorMessages, userContent)
3490
3519
  ];
3491
3520
  return this.runLoop();
3492
3521
  }
@@ -4353,14 +4382,14 @@ function makeScheduleTools(scheduler, os) {
4353
4382
  backend: { type: "string", enum: ["auto", "session", "os"], description: "Where the job lives (default auto)." }
4354
4383
  }
4355
4384
  },
4356
- async run({ prompt, trigger, label, backend }) {
4385
+ async run({ prompt, trigger, label, backend: backend2 }) {
4357
4386
  try {
4358
- if (os && os.route(trigger, backend) === "os") {
4387
+ if (os && os.route(trigger, backend2) === "os") {
4359
4388
  const id2 = `os-${Date.now().toString(36)}`;
4360
4389
  const mechanism = os.schedule({ id: id2, prompt, sessionId: os.sessionId, cwd: os.cwd, trigger, label });
4361
4390
  return `Scheduled ${id2}${label ? ` (${label})` : ""} on the OS scheduler (${mechanism}) \u2014 survives quitting; fires \`agentx --resume ${os.sessionId}\` headless.`;
4362
4391
  }
4363
- if (backend === "os") return "Error: no OS scheduler available on this platform \u2014 job not created (use the default in-session backend).";
4392
+ if (backend2 === "os") return "Error: no OS scheduler available on this platform \u2014 job not created (use the default in-session backend).";
4364
4393
  const id = scheduler.add({ prompt, trigger, label });
4365
4394
  const job = scheduler.get(id);
4366
4395
  const next = scheduler.nextFire(job);
@@ -4639,9 +4668,37 @@ function digestRun(messages, maxChars) {
4639
4668
  import { MemFilesystem as MemFilesystem2 } from "@livx.cc/wcli/core";
4640
4669
  init_logging();
4641
4670
 
4642
- // src/voice/emotion.ts
4643
- init_logging();
4644
- var log8 = forComponent("Emotion");
4671
+ // node_modules/@bod.ee/voice/src/core/logging.ts
4672
+ function consoleForComponent(name) {
4673
+ const debugEnv = typeof process !== "undefined" && process.env?.DEBUG || typeof localStorage !== "undefined" && localStorage.getItem("DEBUG") || "";
4674
+ const gated = debugEnv === "*" || debugEnv.split(",").some((p) => p.trim() === name);
4675
+ const gate = (fn) => gated ? fn : () => {
4676
+ };
4677
+ const tag = `[${name}]`;
4678
+ return {
4679
+ debug: gate((...a) => console.debug(tag, ...a)),
4680
+ verbose: gate((...a) => console.debug(tag, ...a)),
4681
+ info: (...a) => console.info(tag, ...a),
4682
+ warn: (...a) => console.warn(tag, ...a),
4683
+ error: (...a) => console.error(tag, ...a)
4684
+ };
4685
+ }
4686
+ var backend = consoleForComponent;
4687
+ function configureLogging(forComponentImpl) {
4688
+ backend = forComponentImpl;
4689
+ }
4690
+ function forComponent2(name) {
4691
+ return {
4692
+ debug: (...a) => backend(name).debug(...a),
4693
+ verbose: (...a) => backend(name).verbose(...a),
4694
+ info: (...a) => backend(name).info(...a),
4695
+ warn: (...a) => backend(name).warn(...a),
4696
+ error: (...a) => backend(name).error(...a)
4697
+ };
4698
+ }
4699
+
4700
+ // node_modules/@bod.ee/voice/src/core/emotion.ts
4701
+ var log8 = forComponent2("Emotion");
4645
4702
  var EMOTIONS = [
4646
4703
  // primary (best results)
4647
4704
  "neutral",
@@ -4837,9 +4894,8 @@ var EmotionStream = class {
4837
4894
  }
4838
4895
  };
4839
4896
 
4840
- // src/voice/engine.ts
4841
- init_logging();
4842
- var log9 = forComponent("VoiceEngine");
4897
+ // node_modules/@bod.ee/voice/src/core/engine.ts
4898
+ var log9 = forComponent2("VoiceEngine");
4843
4899
  var realClock = {
4844
4900
  now: () => performance.now(),
4845
4901
  setTimeout: (fn, ms) => setTimeout(fn, ms),
@@ -5023,6 +5079,13 @@ var VoiceEngine = class _VoiceEngine {
5023
5079
  // the exact ack text last spoken (fixed OR adaptive) — the echo-leak guard matches it
5024
5080
  ackTimer = null;
5025
5081
  // one-shot adaptive-ack timer (armed at dispatch, cancelled on first delta)
5082
+ // The adaptive micro-ack ALREADY spoke this turn → the reflex's own leading ack ("Still on it.") is now
5083
+ // redundant (live: host said "On it." then the reflex said "Still on it."). While this is set, speakDelta
5084
+ // probes the reflex's opening sentence and DROPS it if it's purely an acknowledgement; real content passes
5085
+ // through. Reset per turn in beginSpeech()/interrupt().
5086
+ adaptiveAckFired = false;
5087
+ ackProbe = null;
5088
+ // buffered reflex prose while probing the leading ack (null = not probing)
5026
5089
  bargeGraceUntil = 0;
5027
5090
  // no barge-in until this time — the user's OWN trailing audio (after the
5028
5091
  // utterance that JUST dispatched this turn) must not immediately re-interrupt the reply it requested.
@@ -5165,6 +5228,8 @@ var VoiceEngine = class _VoiceEngine {
5165
5228
  this.speaking = true;
5166
5229
  this.ctxOpen = true;
5167
5230
  this.spokeDeltas = false;
5231
+ this.adaptiveAckFired = false;
5232
+ this.ackProbe = null;
5168
5233
  this.reply = "";
5169
5234
  this.revealText = "";
5170
5235
  this.wordStarts = [];
@@ -5193,6 +5258,8 @@ var VoiceEngine = class _VoiceEngine {
5193
5258
  this.lastAck = phrase;
5194
5259
  for (const w of this.words(phrase)) this.echoWords.add(w);
5195
5260
  this.setState("speaking");
5261
+ this.adaptiveAckFired = true;
5262
+ this.ackProbe = "";
5196
5263
  this.options.onAdaptiveAck();
5197
5264
  }, this.options.adaptiveAckMs);
5198
5265
  }
@@ -5204,6 +5271,25 @@ var VoiceEngine = class _VoiceEngine {
5204
5271
  speakDelta(text) {
5205
5272
  if (this.interrupted) return "";
5206
5273
  this.clearAckTimer("first_delta");
5274
+ if (this.adaptiveAckFired && this.ackProbe !== null) {
5275
+ this.ackProbe += text;
5276
+ const probe = this.ackProbe;
5277
+ const bare = probe.replace(/\[emotion[^\]]*\]/gi, "").replace(/^\s+/, "");
5278
+ const m = bare.match(/^([^.!?…\n]*[.!?…\n])([\s\S]*)$/);
5279
+ if (!m && bare.length < 80) return "";
5280
+ this.ackProbe = null;
5281
+ this.adaptiveAckFired = false;
5282
+ const lead = m ? m[1] : bare;
5283
+ const norm2 = lead.replace(/[^a-z ]/gi, " ").replace(/\s+/g, " ").trim().toLowerCase();
5284
+ if (_VoiceEngine.ACK_LEADING.test(norm2)) {
5285
+ const rest = m ? m[2] : "";
5286
+ this.diag("reflex_ack_suppressed", { lead: lead.trim() });
5287
+ if (!rest.trim()) return "";
5288
+ text = rest;
5289
+ } else {
5290
+ text = probe;
5291
+ }
5292
+ }
5207
5293
  if (!this.speaking || !this.ctxOpen) this.beginSpeech();
5208
5294
  let { speech, display, prose } = this.emo ? this.emo.feed(text) : { speech: text, display: text, prose: text };
5209
5295
  if (this.reply && /[.!?…]$/.test(this.reply) && /^[A-Z]/.test(prose)) {
@@ -5262,6 +5348,14 @@ var VoiceEngine = class _VoiceEngine {
5262
5348
  endSpeech() {
5263
5349
  this.interrupted = false;
5264
5350
  this.clearAckTimer("turn_end");
5351
+ const heldProbe = this.ackProbe;
5352
+ this.adaptiveAckFired = false;
5353
+ this.ackProbe = null;
5354
+ if (heldProbe) {
5355
+ const norm2 = heldProbe.replace(/\[emotion[^\]]*\]/gi, "").replace(/[^a-z ]/gi, " ").replace(/\s+/g, " ").trim().toLowerCase();
5356
+ if (_VoiceEngine.ACK_LEADING.test(norm2)) this.diag("reflex_ack_suppressed", { lead: heldProbe.trim() });
5357
+ else this.speakDelta(heldProbe);
5358
+ }
5265
5359
  if (!this.speaking) return;
5266
5360
  this.diag("tts_turn_end", { spoke: this.spokeDeltas, replyChars: this.reply.length });
5267
5361
  this.ctxOpen = false;
@@ -5343,6 +5437,9 @@ var VoiceEngine = class _VoiceEngine {
5343
5437
  * No 'Okay.': a genuine user "Okay." within the 6s squash window would be swallowed as ack echo. */
5344
5438
  static ACKS_NEUTRAL = ["Mm-hm.", "One sec.", "Right.", "Sec.", "On it.", "Sure, moment.", "Uh, one moment.", "Let me see."];
5345
5439
  static ACKS_QUESTION = ["Hmm.", "Let me think.", "Hm, let me see.", "Good question.", "Mm, one sec.", "Let's see."];
5440
+ /** A reflex opening sentence that is PURELY an acknowledgement (no content) — dropped when the adaptive
5441
+ * micro-ack already spoke one. Anchored end-to-end so only a whole ack-only clause matches. */
5442
+ 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))[ ,]*)+$/;
5346
5443
  recentAcks = [];
5347
5444
  pickAck() {
5348
5445
  const pool = this.lastDispatchWasQuestion ? _VoiceEngine.ACKS_QUESTION : _VoiceEngine.ACKS_NEUTRAL;
@@ -5367,6 +5464,8 @@ var VoiceEngine = class _VoiceEngine {
5367
5464
  /** barge-in: stop audio NOW, cancel generation, reset for the user's utterance */
5368
5465
  interrupt() {
5369
5466
  this.clearAckTimer("interrupt");
5467
+ this.adaptiveAckFired = false;
5468
+ this.ackProbe = null;
5370
5469
  if (this.uttQueue.length) log9.info(`barge-in dropped ${this.uttQueue.length} queued worker utterance(s)`);
5371
5470
  const droppedQueued = this.uttQueue.length;
5372
5471
  this.uttQueue = [];
@@ -5827,7 +5926,14 @@ var VoiceEngine = class _VoiceEngine {
5827
5926
  }
5828
5927
  };
5829
5928
 
5830
- // src/voice/spokenSplitter.ts
5929
+ // node_modules/@bod.ee/voice/src/core/types.ts
5930
+ var STT_SAMPLE_RATE = 16e3;
5931
+ var TTS_SAMPLE_RATE = 44100;
5932
+ async function resolveAuth(auth) {
5933
+ return typeof auth === "function" ? await auth() : auth;
5934
+ }
5935
+
5936
+ // node_modules/@bod.ee/voice/src/core/spokenSplitter.ts
5831
5937
  var OPEN = "<spoken>";
5832
5938
  var CLOSE = "</spoken>";
5833
5939
  var CLOSERS = `"')]}\xBB\u201D\u2019`;
@@ -5899,1594 +6005,1589 @@ var SpokenSplitter = class {
5899
6005
  }
5900
6006
  };
5901
6007
 
5902
- // src/duplex.ts
5903
- var log10 = forComponent("DuplexAgent");
5904
- function describeCall(call) {
5905
- const v = call.args && Object.values(call.args).find((x) => typeof x === "string" && x.trim());
5906
- const hint = v ? ` (${String(v).replace(/\s+/g, " ").trim().slice(0, 48)})` : "";
5907
- return `${call.name}${hint}`;
5908
- }
5909
- var DuplexAgentOptions = class {
5910
- /** Any ai.libx.js AIClient — shared by all tiers (routed by model). */
5911
- ai;
5912
- /** The WORKER's filesystem (act + think). If omitted the worker keeps Agent's jailed-disk-at-cwd default. */
5913
- fs;
5914
- // The reflex IS the voice. 120b (not 20b) for channel discipline + instruction-following: the 20b
5915
- // mislabels gpt-oss harmony channels under load, leaking raw analysis into the spoken `final` channel
5916
- // (and misfiring Hold). 120b is the same price tier (~$0.15/$0.60) — the quality/cost trade is free.
5917
- reflexModel = "groq/openai/gpt-oss-120b";
5918
- actModel = "anthropic/claude-sonnet-4-6";
5919
- /** Premium reasoning model. Set to `false` to disable the Think tier entirely. */
5920
- thinkModel = "anthropic/claude-opus-4-8";
5921
- /** Per-worker providerOptions, derived from the worker's actual model at spawn time (IoC — keeps duplex
5922
- * provider-agnostic). Workers override the reflex/main model, so provider-specific options (e.g. cursor's
5923
- * cwd/cursorSession) must be recomputed for the worker's model, never inherited from the main template —
5924
- * leaking cursor options to an anthropic worker is a hard 400. Returns undefined → no providerOptions. */
5925
- providerOptionsFor;
5926
- /** Escape hatches merged over the derived per-agent options. */
5927
- reflexOptions;
5928
- actOptions;
5929
- thinkOptions;
5930
- /** Fresh-context check on each successful Act task: a NEW agent (no self-confirmation bias) re-reads
5931
- * the file state against the brief and fixes any gap before the result is re-voiced. Bounded to one
5932
- * pass; ~2x Act cost so default OFF. The self-verify FOOTER (same context) was measured ineffective —
5933
- * this is the structural fix (see mind/10). Think tasks are pure reasoning, never checked. */
5934
- verifyActTasks = false;
5935
- /** Receives the voice text_delta stream + task lifecycle events. */
5936
- host;
5937
- /** How many recent transcript messages are rendered into a worker's brief. */
5938
- excerptTurns = 6;
5939
- /** Voice register: 'neutral' = clean spoken style; 'conversational' = human-like — fillers,
5940
- * backchannels, impulsive first reactions before content (mimics real duplex conversation). */
5941
- voiceStyle = "neutral";
5942
- /** Teach the model to emit inline `[emotion]` tags for Cartesia emotion control. Only set when the
5943
- * TTS actually speaks them — text-duplex (no TTS) would otherwise print literal tags. */
5944
- emotionTags = false;
5945
- /** Awaited BEFORE a worker spawns — open a per-task checkpoint frame, audit, etc.
5946
- * (post-spawn would race the worker's first edits). */
5947
- onTaskStart;
5948
- /** Re-voice throttled worker progress asides ('[task t1 progress] …') so long tasks aren't dead
5949
- * air. Off by default — each update costs a voice turn (LLM call + speech). */
5950
- progressUpdates = false;
5951
- /** Min ms between progress re-voices per task. */
5952
- progressIntervalMs = 25e3;
5953
- /** Relay worker questions (AskUserQuestion + permission asks via parkQuestion) through the VOICE:
5954
- * the question re-voices as '[task <id> asks] …', the user answers conversationally, and the
5955
- * voice model resolves it with the AnswerTask tool. Off → host.ask passthrough (text menus). */
5956
- askRelay = false;
5957
- /** Parked questions auto-resolve empty after this long (callers map '' to deny/best-judgment). */
5958
- askTimeoutMs = 12e4;
5959
- /** Max retained task records: oldest SETTLED tasks (and their activity tails) are evicted past this,
5960
- * bounding memory over a long-lived session. Running tasks are never evicted. */
5961
- maxTaskRecords = 50;
5962
- /** Host overrides for QuickLook lookups (keyed by `what`). The engine's defaults go through the
5963
- * (possibly jailed) fs — e.g. `.git/**` is deny-listed, so the CLI supplies 'branch' itself. */
5964
- quickLook;
5965
- /** Memory directory/directories on the WORKER fs. If set, the voice agent gets Remember + Recall
5966
- * tools directly (no delegation needed) and implicit capture guidance. */
5967
- memoryDir;
5968
- /** User-scope memory dir for global facts (type=user/feedback). Forwarded to Remember's routing. */
5969
- memoryUserDir;
6008
+ // node_modules/@bod.ee/voice/src/adapters/soniox.ts
6009
+ var log10 = forComponent2("SonioxSTT");
6010
+ var now = () => performance.now();
6011
+ var SonioxSTTOptions = class {
6012
+ auth = "";
6013
+ source;
6014
+ model = "stt-rt-preview";
6015
+ languageHints = ["en"];
6016
+ /** Client-side endpoint: finalized text + no new tokens for this long = utterance (don't wait for
6017
+ * Soniox's semantic <end>, which adds 0.5-1.5s — the difference between ping-pong and lag). */
6018
+ silenceEndpointMs = 500;
6019
+ /** No-audio watchdog: if the mic source stops delivering chunks for this long, capture is dead →
6020
+ * fire onFatal + stop (else Soniox idle-timeouts and reconnect-loops forever). 0 = disable. */
6021
+ noAudioTimeoutMs = 1e4;
5970
6022
  };
5971
- var RESERVED_EVENT_MARKER = /\[task\b[^\]\n]*\b(?:completed|failed|progress|asks)\b/i;
5972
- var RESERVED_EVENT_OPENER = /\[\s*task\b/i;
5973
- var STAGE_DIRECTION_RE = /^\(\s*(?:(?:waiting|checking|searching|thinking|processing|loading|working|fetching|looking)\b[^)]*|[^)]*(?:\.\.\.|…)\s*)\)$/i;
5974
- function nowLine() {
5975
- 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" })}`;
5976
- }
5977
- function isTrivialBarge(text) {
5978
- const t = text.trim().toLowerCase().replace(/[.,!?…\s]+$/g, "").replace(/^[.,!?…\s]+/, "");
5979
- if (!t) return false;
5980
- 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;
5981
- const core = t.replace(/^(?:oh|um+|uh+|er+|hmm+|ah+|well|so|okay|ok|yeah|yep)[\s,]+/, "").trim();
5982
- 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);
5983
- }
5984
- 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.';
5985
- 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.";
5986
- var THINK_DISABLED_GUIDANCE = "(Think tier is not available \u2014 use Act for all escalations.)";
5987
- 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).`;
5988
- 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(", ")}.`;
5989
- var DuplexAgent = class _DuplexAgent {
6023
+ var SonioxSTT = class {
5990
6024
  options;
5991
- voice;
5992
- tasks = /* @__PURE__ */ new Map();
5993
- queue = Promise.resolve();
5994
- seq = 0;
5995
- pendingEvents = [];
5996
- /** Spoken text of parked deliveries that have SETTLED, awaiting a trivial-barge resume decision on the
5997
- * next turn (a substantive turn clears it — the result stays in the transcript, recoverable by asking). */
5998
- parkedRedeliver = [];
5999
- /** A trivial barge arrived while a parked delivery was STILL RUNNING → resume it the moment it settles. */
6000
- awaitTrivialRedeliver = false;
6001
- /** Set by a SUBSTANTIVE turn after a barge: the user moved on, so a parked delivery that settles LATER
6002
- * must NOT arm a resume (else a much-later "go on" replays a stale result). Reset by a fresh barge. */
6003
- suppressParkedResume = false;
6004
- /** Out-of-band follow-up attribution for the events coalescing into the next flush turn: TRUE iff ≥1 of
6005
- * the tasks being integrated was NON-CLEAN (early-stop/failure). Carried out-of-band on the enqueue call
6006
- * by the caller that KNOWS the outcome — a plain boolean the MODEL CANNOT PERTURB. It is NOT scanned from
6007
- * worker-authored event text (v1: an "Outcome:" substring over-stamped siblings) and NOT keyed on a brief
6008
- * string the reflex re-authors (v2: a paraphrased escalation brief missed the Set → followUp:false →
6009
- * RE-ENABLED unbounded auto-escalation, the dangerous runaway direction). See [[wrong-discriminator]] /
6010
- * [[drive-real-reflex]] / [[fakeaiclient-blind-to-wire-format]]. */
6011
- pendingNonClean = false;
6012
- flushQueued = false;
6013
- /** Per-voice-turn guards (reset by resetTurn at each turn's start). The reflex is a weak model:
6014
- * left unguarded it polls TaskStatus after a dispatch and/or dispatches silently (dead air).
6015
- * Like CC's Task tool, a dispatch is "said my piece, now wait for the push" — these enforce that. */
6016
- turnDispatched = false;
6017
- // an Act/Think fired this turn
6018
- spokeBeforeDispatch = false;
6019
- // the reflex ALREADY acked before dispatching — the forced post-dispatch text step must stay silent (live: "Got it…" twice)
6020
- turnBriefs = /* @__PURE__ */ new Set();
6021
- // briefs dispatched this turn (detect identical re-dispatch)
6022
- spokeThisTurn = false;
6023
- // any non-empty text_delta streamed this turn
6024
- externalSpeech = false;
6025
- // host spoke on our behalf (adaptive micro-ack) — not reflex output
6026
- heldThisTurn = false;
6027
- // Hold called this turn → turn is INTENTIONALLY silent (suppress reflex text + no dead-air ack)
6028
- nudging = false;
6029
- // re-ack pass in flight: block ALL tools, prevent recursion
6030
- reflexBuf = "";
6031
- // accumulated reflex text this turn (fabricated-event detection)
6032
- reflexForwarded = 0;
6033
- // chars of reflexBuf already forwarded to the host/TTS
6034
- fabricationCut = false;
6035
- // reflex emitted a reserved [task …] marker → suppress its tail
6036
- /** TRUE for the duration of a re-voice turn that is integrating ≥1 NON-CLEAN task (turn-eligibility,
6037
- * carried out-of-band — NOT derived from any worker/brief string). ANY Act/Think dispatched in such a
6038
- * turn is stamped followUp:true. This GUARANTEES the dangerous direction is impossible: a genuine
6039
- * escalation (even one with a paraphrased brief) ALWAYS lands in a non-clean integration turn, so it is
6040
- * ALWAYS recognized as a follow-up and CANNOT re-escalate (one hop). The single-dispatch-per-turn guard
6041
- * means at most one dispatch happens per flush, so realistically "the one dispatch IS the escalation".
6042
- * ACCEPTED SAFE-DIRECTION ERROR: if the reflex instead dispatches FRESH unrelated work during a non-clean
6043
- * flush (rare — and only possible when it batches multiple calls in one step, bypassing the guard), that
6044
- * fresh task is over-stamped followUp:true and forgoes ONE future auto-escalation. That is SAFE (it only
6045
- * ever REMOVES a future escalation, never adds one — no runaway) and is the correct side to err on. */
6046
- turnFollowUp = false;
6047
- /** Hard absolute backstop against runaway regardless of attribution: total automatic escalations across
6048
- * the whole conversation. Once it hits MAX_AUTO_ESCALATIONS, no integration turn offers escalate/re-delegate. */
6049
- autoEscalations = 0;
6050
- static MAX_AUTO_ESCALATIONS = 8;
6051
- /** Parked worker questions awaiting a (voice-relayed) user answer, keyed by ask id. */
6052
- pendingAsks = /* @__PURE__ */ new Map();
6053
- /** SPECULATIVE REFLEX (VoiceEngine.onSpeculate → speculate()): the reflex turn starts on a stable
6054
- * PARTIAL transcript, its spoken output buffered — nothing reaches TTS until the endpointed final
6055
- * confirms via send() (which flushes the buffer and adopts the call as THE turn). A divergent final
6056
- * aborts it: output dropped, history rolled back, the final dispatches normally. */
6057
- spec;
6058
- /** Aborted speculative calls (double-billing visibility — each one paid for tokens never spoken). */
6059
- speculativeAbortedCalls = 0;
6060
- /** Tools the reflex may execute on UNCONFIRMED (speculated) input — read-only lookups and the
6061
- * intentionally-silent Hold. Anything else (Act/Think/AnswerTask/CancelTask/ExitSession/memory
6062
- * writes/…) is a side effect on input the user may not have said: the guard ABORTS the speculation
6063
- * instead (the endpointed final then dispatches normally and may use the tool for real). */
6064
- static SPEC_SAFE_TOOLS = /* @__PURE__ */ new Set(["QuickLook", "TaskStatus", "Hold"]);
6065
- /** Lazily resolved memory tools (async loadMemory runs in initMemory). */
6066
- memoryReady;
6067
- constructor(options) {
6068
- this.options = { ...new DuplexAgentOptions(), ...options };
6069
- const o = this.options;
6070
- if (o.memoryDir && o.fs) {
6071
- this.memoryReady = loadMemory(o.fs, o.memoryDir, { maxWritesPerSession: 10, userDir: o.memoryUserDir });
6025
+ ws;
6026
+ stopped = false;
6027
+ sourceStarted = false;
6028
+ onPartial = () => {
6029
+ };
6030
+ onUtterance = () => {
6031
+ };
6032
+ /** mic energy (RMS) per chunk — drives the energy-based heuristic barge-in tier */
6033
+ onLevel = () => {
6034
+ };
6035
+ /** Unrecoverable: the mic source stopped delivering audio (Soniox starves → idle-timeout reconnect
6036
+ * loop). The host tears voice down instead of spinning forever. */
6037
+ onFatal = () => {
6038
+ };
6039
+ /** Diagnostic tap (provider errors, ws reconnects, no-audio watchdog). Fire-and-forget: a throwing
6040
+ * handler disables itself — never affects transcription. Wired by VoiceIO / the lab bridge. */
6041
+ onDiag = () => {
6042
+ };
6043
+ diagOn = true;
6044
+ diag(kind, fields) {
6045
+ if (!this.diagOn) return;
6046
+ try {
6047
+ this.onDiag({ t: now(), kind, ...fields });
6048
+ } catch (e) {
6049
+ this.diagOn = false;
6050
+ log10.debug(`onDiag threw \u2014 STT diagnostics disabled: ${e instanceof Error ? e.message : e}`);
6072
6051
  }
6073
- 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.";
6074
- const thinkSlot = o.thinkModel !== false ? THINK_GUIDANCE : THINK_DISABLED_GUIDANCE;
6075
- const workerToolNames = (o.actOptions?.tools ?? []).map((t) => t.name);
6076
- const canSearch = workerToolNames.some((n) => /WebSearch/i.test(n));
6077
- const canFetch = workerToolNames.some((n) => /WebFetch/i.test(n));
6078
- 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)" : "";
6079
- const mcpNames = [
6080
- ...Object.keys(o.actOptions?.providerOptions?.mcpServers ?? {}),
6081
- ...new Set(workerToolNames.filter((n) => n.startsWith("mcp__")).map((n) => n.slice(5).split("__")[0]))
6082
- ];
6083
- 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' : "") : "";
6084
- 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 : "") + `
6085
- ${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.`;
6086
- const tools = [
6087
- ...o.reflexOptions?.tools ?? [],
6088
- this.actTool(),
6089
- ...o.thinkModel !== false ? [this.thinkTool()] : [],
6090
- this.taskStatusTool(),
6091
- this.cancelTaskTool(),
6092
- this.quickLookTool(),
6093
- this.answerTaskTool(),
6094
- this.holdTool()
6095
- ];
6096
- const host = o.host;
6097
- const voiceHost = host && {
6098
- ask: host.ask ? (q2) => host.ask(q2) : void 0,
6099
- confirm: host.confirm ? (p, m) => host.confirm(p, m) : void 0,
6100
- notify: (ev) => {
6101
- if (ev?.kind === "text_delta" && typeof ev.message === "string") {
6102
- if (this.heldThisTurn) return;
6103
- if (this.fabricationCut) return;
6104
- if (this.turnDispatched && this.spokeBeforeDispatch) return;
6105
- const msg = ev.message;
6106
- this.reflexBuf += msg;
6107
- this.scrubStageDirections();
6108
- const m = this.reflexBuf.match(RESERVED_EVENT_MARKER) ?? this.reflexBuf.match(RESERVED_EVENT_OPENER);
6109
- if (m) {
6110
- this.fabricationCut = true;
6111
- log10.warn(`reflex fabricated a [task \u2026] event in its spoken stream \u2014 cutting it (kept ${m.index} chars)`);
6112
- const safe = this.reflexBuf.slice(this.reflexForwarded, m.index);
6113
- if (!safe) return;
6114
- if (safe.trim()) this.spokeThisTurn = true;
6115
- this.emitHost({ ...ev, message: safe });
6116
- return;
6117
- }
6118
- const held = this.reflexBuf.length - this.reflexForwarded;
6119
- const partial = held > 0 && /\[\s*t?a?s?k?$/i.test(this.reflexBuf.slice(-Math.min(held, 6)));
6120
- let upto = partial ? this.reflexBuf.length - this.reflexBuf.slice(-6).match(/\[\s*t?a?s?k?$/i)[0].length : this.reflexBuf.length;
6121
- const paren = this.reflexBuf.lastIndexOf("(");
6122
- if (paren >= this.reflexForwarded && !this.reflexBuf.includes(")", paren) && this.reflexBuf.length - paren <= 80)
6123
- upto = Math.min(upto, paren);
6124
- const out = this.reflexBuf.slice(this.reflexForwarded, upto);
6125
- this.reflexForwarded = upto;
6126
- if (!out) return;
6127
- if (out.trim()) this.spokeThisTurn = true;
6128
- this.emitHost({ ...ev, message: out });
6129
- return;
6130
- }
6131
- host.notify?.(ev);
6132
- }
6133
- };
6134
- this.voice = new Agent({
6135
- ai: o.ai,
6136
- fs: new MemFilesystem2(),
6137
- model: o.reflexModel,
6138
- stream: true,
6139
- host: voiceHost,
6140
- // The reflex IS the conversational channel — it confirms ambiguity inline ("did you mean…?"),
6141
- // never via the blocking AskUserQuestion tool (Agent auto-adds it whenever a host is set). Left in,
6142
- // it stalls a voice turn until the kill-switch. Worker questions still reach the user via parkQuestion.
6143
- askUserQuestion: false,
6144
- systemPrompt: prompt,
6145
- instructionFiles: false,
6146
- maxSteps: 8,
6147
- timeoutMs: 3e4,
6148
- ...o.reflexOptions,
6149
- tools,
6150
- // Composed AFTER the spread so the dispatch guard can't be dropped by reflexOptions.
6151
- hooks: composeHooks(this.dispatchGuard(), o.reflexOptions?.hooks)
6152
- });
6153
- }
6154
- /** Resolve memory tools + inject index into voice system prompt (once). */
6155
- async initMemory() {
6156
- if (!this.memoryReady) return;
6157
- const mem = await this.memoryReady;
6158
- this.memoryReady = void 0;
6159
- this.voice.options.tools.push(...mem.tools);
6160
- if (mem.index) this.voice.options.systemPrompt += "\n\n" + mem.index;
6161
6052
  }
6162
- /** Flush any held-back trailing fragment (a possible `[task` opener that never completed) once the
6163
- * turn's stream is done — so a legit message ending in "[t" isn't silently dropped. */
6164
- flushHeldReflexTail() {
6165
- if (this.fabricationCut) return;
6166
- this.scrubStageDirections();
6167
- const tail = this.reflexBuf.slice(this.reflexForwarded);
6168
- this.reflexForwarded = this.reflexBuf.length;
6169
- if (!tail) return;
6170
- if (tail.trim()) this.spokeThisTurn = true;
6171
- this.emitHost({ kind: "text_delta", message: tail });
6053
+ lastChunkAt = 0;
6054
+ // timestamp of the most recent mic chunk (0 = none yet)
6055
+ startedChunksAt = 0;
6056
+ // when capture started (grace before the first chunk)
6057
+ noAudioTimer = null;
6058
+ finalText = "";
6059
+ partialText = "";
6060
+ lastChangeAt = 0;
6061
+ lastCombined = "";
6062
+ endpointTimer = null;
6063
+ firstTokenAt = 0;
6064
+ // first speech token in current utterance
6065
+ constructor(options) {
6066
+ this.options = { ...new SonioxSTTOptions(), ...options };
6172
6067
  }
6173
- /** Remove complete stage-direction parentheticals from the UNFORWARDED reflex text (STAGE_DIRECTION_RE).
6174
- * Only the unforwarded region is touched — already-spoken audio can't be unsent, and splicing before
6175
- * reflexForwarded would corrupt the forward offset. */
6176
- scrubStageDirections() {
6177
- if (this.reflexForwarded >= this.reflexBuf.length) return;
6178
- const region = this.reflexBuf.slice(this.reflexForwarded);
6179
- const scrubbed = region.replace(/\([^()]*\)/g, (s) => STAGE_DIRECTION_RE.test(s) ? "" : s);
6180
- if (scrubbed !== region) this.reflexBuf = this.reflexBuf.slice(0, this.reflexForwarded) + scrubbed;
6068
+ get usingAec() {
6069
+ return this.options.source?.aec ?? false;
6181
6070
  }
6182
- /** Clear the per-turn guards. Called at the head of every voice turn (user send + re-voice flush). */
6183
- resetTurn() {
6184
- this.turnDispatched = false;
6185
- this.spokeBeforeDispatch = false;
6186
- this.turnBriefs.clear();
6187
- this.spokeThisTurn = false;
6188
- this.externalSpeech = false;
6189
- this.heldThisTurn = false;
6190
- this.reflexBuf = "";
6191
- this.reflexForwarded = 0;
6192
- this.fabricationCut = false;
6193
- this.turnFollowUp = false;
6194
- this.voice.options.toolChoice = void 0;
6071
+ async connectWs() {
6072
+ const apiKey = await resolveAuth(this.options.auth);
6073
+ this.ws = new WebSocket("wss://stt-rt.soniox.com/transcribe-websocket");
6074
+ await new Promise((res, rej) => {
6075
+ this.ws.onopen = () => res();
6076
+ this.ws.onerror = (e) => rej(new Error(`soniox ws: ${e.message || "connect failed"}`));
6077
+ });
6078
+ this.ws.send(
6079
+ JSON.stringify({
6080
+ api_key: apiKey,
6081
+ model: this.options.model,
6082
+ audio_format: "pcm_s16le",
6083
+ sample_rate: STT_SAMPLE_RATE,
6084
+ num_channels: 1,
6085
+ language_hints: this.options.languageHints,
6086
+ enable_endpoint_detection: true
6087
+ })
6088
+ );
6089
+ this.ws.onmessage = (ev) => this.handle(JSON.parse(String(ev.data)));
6090
+ this.ws.onclose = (ev) => {
6091
+ if (this.stopped) return;
6092
+ log10.warn(`soniox ws closed (${ev.code} ${ev.reason || ""}) \u2014 reconnecting`);
6093
+ this.diag("stt_ws_closed", { code: ev.code, reason: String(ev.reason || ""), reconnecting: true });
6094
+ this.reset();
6095
+ this.connectWs().catch((e) => {
6096
+ log10.error(`soniox reconnect failed: ${e.message}`);
6097
+ this.diag("stt_reconnect_failed", { message: e.message });
6098
+ });
6099
+ };
6195
6100
  }
6196
- /** preToolUse guard on the reflex: once it has dispatched this turn, a dispatch is "said my piece,
6197
- * now wait for the push" (CC's Task model). Block the temptations — TaskStatus polling and identical
6198
- * re-dispatch — so the only remaining move is to voice a short ack and end. A genuinely NEW Act is
6199
- * still allowed (parallel independent work). During a re-ack pass, block every tool. */
6200
- dispatchGuard() {
6201
- return {
6202
- preToolUse: (call) => {
6203
- if (this.spec?.state === "pending" && !_DuplexAgent.SPEC_SAFE_TOOLS.has(call.name)) {
6204
- log10.verbose(`speculation aborted: reflex called ${call.name} on unconfirmed input`);
6205
- this.abortSpeculation();
6206
- return { block: true, reason: "Speculative turn aborted." };
6101
+ async start() {
6102
+ await this.connectWs();
6103
+ if (this.sourceStarted) return;
6104
+ this.sourceStarted = true;
6105
+ this.endpointTimer = setInterval(() => {
6106
+ const combined = (this.finalText + this.partialText).trim();
6107
+ if (!combined || now() - this.lastChangeAt < this.options.silenceEndpointMs) return;
6108
+ if (this.firstTokenAt) log10.debug(`stt: ${Math.round(now() - this.firstTokenAt)}ms first-token\u2192silence-endpoint, "${combined.slice(0, 60)}"`);
6109
+ this.reset();
6110
+ this.onUtterance(combined, now());
6111
+ }, 120);
6112
+ this.endpointTimer.unref?.();
6113
+ this.startedChunksAt = now();
6114
+ const noAudioMs = this.options.noAudioTimeoutMs;
6115
+ if (noAudioMs > 0) {
6116
+ this.noAudioTimer = setInterval(() => {
6117
+ if (this.stopped) return;
6118
+ const ref = this.lastChunkAt || this.startedChunksAt;
6119
+ if (now() - ref > noAudioMs) {
6120
+ log10.error(`stt: no mic audio for >${Math.round(noAudioMs / 1e3)}s \u2014 capture device stopped delivering`);
6121
+ this.diag("stt_watchdog_fatal", { noAudioMs });
6122
+ this.onFatal("microphone stopped delivering audio (try a different input device, e.g. AirPods, or check System Settings \u2192 Sound \u2192 Input)");
6123
+ this.stop();
6207
6124
  }
6208
- if (this.nudging) return { block: true, reason: "Just say one short spoken acknowledgement \u2014 no tools this turn." };
6209
- if (!this.turnDispatched) return;
6210
- if (call.name === "TaskStatus")
6211
- 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." };
6212
- if ((call.name === "Act" || call.name === "Think") && this.turnBriefs.has(String(call.args?.brief ?? "")))
6213
- return { block: true, reason: "You already dispatched this exact task \u2014 acknowledge briefly and end your turn." };
6125
+ }, Math.max(250, Math.min(2e3, noAudioMs / 4)));
6126
+ this.noAudioTimer.unref?.();
6127
+ }
6128
+ await this.options.source.start((chunk) => {
6129
+ this.lastChunkAt = now();
6130
+ let sum = 0;
6131
+ const view = new DataView(chunk.buffer, chunk.byteOffset, chunk.byteLength);
6132
+ for (let i = 0; i + 1 < chunk.byteLength; i += 2) {
6133
+ const v = view.getInt16(i, true);
6134
+ sum += v * v;
6214
6135
  }
6215
- };
6216
- }
6217
- /** The host spoke on this turn's behalf OUTSIDE the reflex stream (e.g. the voice engine's adaptive
6218
- * micro-ack). For a DISPATCHED turn that's a sufficient ack (don't stack a second one); for an
6219
- * inline turn whose reply came back empty it is NOT — "One sec." followed by permanent silence is
6220
- * still dead air, so silentTurn ignores external speech unless work was dispatched. */
6221
- noteExternalSpeech() {
6222
- this.externalSpeech = true;
6223
- }
6224
- /** True when the just-finished turn voiced NOTHING — dead air to repair. Two ways this happens:
6225
- * (a) a dispatch with no spoken ack, and (b) an INLINE turn whose `final` channel came back empty —
6226
- * gpt-oss harmony sometimes puts the whole reply in `analysis` (→ thinking_delta, suppressed in
6227
- * voice) and emits an empty `final`, so no text_delta ever streams. Both ship silence; both repair.
6228
- * Requires a host: without one there's no stream to detect speech on (and no one to speak to). */
6229
- get silentTurn() {
6230
- const ackedByHost = this.externalSpeech && this.turnDispatched;
6231
- return !!this.options.host && !this.spokeThisTurn && !ackedByHost && !this.heldThisTurn;
6136
+ this.onLevel(Math.sqrt(sum / (chunk.byteLength / 2)));
6137
+ if (this.ws.readyState === WebSocket.OPEN) this.ws.send(chunk);
6138
+ });
6232
6139
  }
6233
- /** A turn that voiced nothing is dead air. Re-prompt the reflex ONCE so the LLM itself voices a short
6234
- * line (no template). If it STILL says nothing, fall back to a minimal line so silence never ships.
6235
- * Wording adapts to whether work was dispatched (an ack) or the inline reply was simply lost. */
6236
- async ackIfSilent(fallback) {
6237
- const dispatched = this.turnDispatched;
6238
- this.nudging = true;
6239
- try {
6240
- 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.");
6241
- } catch (e) {
6242
- log10.warn(`ack nudge failed: ${e instanceof Error ? e.message : e}`);
6243
- } finally {
6244
- this.nudging = false;
6140
+ handle(m) {
6141
+ if (m.error_message) {
6142
+ this.diag("stt_error", { message: String(m.error_message), code: m.error_code });
6143
+ return log10.error(`soniox: ${m.error_message}`);
6245
6144
  }
6246
- if (!this.spokeThisTurn) {
6247
- const pool = fallback ? [fallback] : dispatched ? _DuplexAgent.FALLBACK_ACKS : _DuplexAgent.FALLBACK_RETRY;
6248
- const fresh = pool.filter((p) => p !== this.lastFallback);
6249
- const line = (fresh.length ? fresh : pool)[Math.floor(Math.random() * (fresh.length || pool.length))];
6250
- this.lastFallback = line;
6251
- this.emitHost({ kind: "text_delta", message: line });
6145
+ let endpoint = false;
6146
+ for (const t of m.tokens ?? []) {
6147
+ if (t.text === "<end>") endpoint = true;
6148
+ else if (t.is_final) this.finalText += t.text;
6252
6149
  }
6253
- }
6254
- /** Dead-air fallback pools (see ackIfSilent). Both retry lines keep the 'say that again' phrase —
6255
- * hosts/tests key on it. */
6256
- static FALLBACK_ACKS = ["Okay, on it.", "On it.", "Alright, working on it."];
6257
- static FALLBACK_RETRY = ["Sorry, could you say that again?", "Hm, I missed that \u2014 could you say that again?"];
6258
- lastFallback = "";
6259
- /** One user turn: the voice agent streams the reply (and may Act/Think). Serialized with re-voice turns.
6260
- * If a speculative reflex call is pending and this content CONFIRMS it (the final matches the
6261
- * speculated partial), the in-flight call is adopted as THE turn: its buffered output flushes to the
6262
- * host NOW (this is the latency win) and streaming continues live. Any other content aborts the
6263
- * speculation first (rolled back silently) and runs a normal turn behind it. */
6264
- send(content) {
6265
- if (typeof content === "string" && isTrivialBarge(content) && this.hasParkedDelivery()) {
6266
- if (this.spec) this.abortSpeculation();
6267
- return this.enqueue(async () => {
6268
- this.resetTurn();
6269
- if (!this.redeliverParked()) this.awaitTrivialRedeliver = true;
6270
- return { text: "", steps: 0, finishReason: "stop", messages: [] };
6271
- });
6150
+ this.partialText = (m.tokens ?? []).filter((t) => !t.is_final && t.text !== "<end>").map((t) => t.text).join("");
6151
+ const combined = this.finalText + this.partialText;
6152
+ if (combined !== this.lastCombined) {
6153
+ this.lastCombined = combined;
6154
+ this.lastChangeAt = now();
6155
+ if (!this.firstTokenAt && combined.trim()) this.firstTokenAt = now();
6272
6156
  }
6273
- const spec = this.spec;
6274
- if (spec?.state === "pending") {
6275
- if (typeof content === "string" && speculationConfirms(spec.text, content)) {
6276
- spec.state = "confirmed";
6277
- spec.finalText = content;
6278
- for (const ev of spec.buf.splice(0)) this.options.host?.notify?.(ev);
6279
- spec.decide("confirm");
6280
- this.notify("diag", "speculation_confirmed", { text: spec.text.slice(0, 80) });
6281
- return spec.done;
6282
- }
6283
- this.abortSpeculation();
6157
+ this.onPartial(combined);
6158
+ if (endpoint && this.finalText.trim()) {
6159
+ const utterance = this.finalText.trim();
6160
+ if (this.firstTokenAt) log10.debug(`stt: ${Math.round(now() - this.firstTokenAt)}ms first-token\u2192endpoint, "${utterance.slice(0, 60)}"`);
6161
+ this.reset();
6162
+ this.onUtterance(utterance, now());
6284
6163
  }
6285
- return this.enqueue(async () => {
6286
- await this.initMemory();
6287
- this.resetTurn();
6288
- this.awaitTrivialRedeliver = false;
6289
- this.parkedRedeliver = [];
6290
- this.suppressParkedResume = true;
6291
- const res = await this.voice.send(content);
6292
- this.flushHeldReflexTail();
6293
- if (this.silentTurn) await this.ackIfSilent();
6294
- return res;
6295
- });
6296
- }
6297
- /** Start a HELD speculative reflex turn on a stable partial (VoiceEngine.onSpeculate). Its spoken
6298
- * output buffers in emitHost; send() later confirms (flush + adopt) or aborts it. The turn holds the
6299
- * voice mutex until that decision (bounded by a safety timeout), so no other turn can interleave
6300
- * into the transcript between the speculative messages and their rollback. No-op if a speculation
6301
- * is already in flight. */
6302
- speculate(text) {
6303
- if (!text.trim() || this.spec) return;
6304
- let decide;
6305
- const decision = new Promise((r) => {
6306
- decide = r;
6307
- });
6308
- const spec = {
6309
- text,
6310
- state: "pending",
6311
- buf: [],
6312
- ctl: new AbortController(),
6313
- decide,
6314
- decision,
6315
- done: void 0
6316
- };
6317
- this.spec = spec;
6318
- spec.done = this.enqueue(async () => {
6319
- const empty = { text: "", steps: 0, finishReason: "aborted", messages: this.voice.transcript };
6320
- if (spec.state === "aborted") {
6321
- this.speculativeAbortedCalls++;
6322
- if (this.spec === spec) this.spec = void 0;
6323
- return empty;
6324
- }
6325
- await this.initMemory();
6326
- this.resetTurn();
6327
- const base = this.voice.transcript.length;
6328
- const prevSignal = this.voice.options.signal;
6329
- this.voice.options.signal = spec.ctl.signal;
6330
- let res;
6331
- try {
6332
- res = await this.voice.send(spec.text);
6333
- } catch (e) {
6334
- log10.warn(`speculative turn failed: ${e instanceof Error ? e.message : e}`);
6335
- } finally {
6336
- this.voice.options.signal = prevSignal;
6337
- }
6338
- const timer = setTimeout(() => {
6339
- spec.state = spec.state === "pending" ? "aborted" : spec.state;
6340
- spec.decide("abort");
6341
- }, 1e4);
6342
- timer.unref?.();
6343
- const d = await spec.decision;
6344
- clearTimeout(timer);
6345
- if (d === "abort") {
6346
- if (this.voice.transcript.length > base) this.voice.transcript.length = base;
6347
- this.speculativeAbortedCalls++;
6348
- log10.verbose(`speculation aborted (${this.speculativeAbortedCalls} total): "${spec.text.slice(0, 50)}"`);
6349
- if (this.spec === spec) this.spec = void 0;
6350
- return res ?? empty;
6351
- }
6352
- for (let i = base; i < this.voice.transcript.length; i++) {
6353
- const m = this.voice.transcript[i];
6354
- if (m.role === "user" && contentText(m.content) === spec.text) {
6355
- m.content = spec.finalText;
6356
- break;
6357
- }
6358
- }
6359
- this.spec = void 0;
6360
- this.flushHeldReflexTail();
6361
- if (this.silentTurn) await this.ackIfSilent();
6362
- return res ?? empty;
6363
- });
6364
- }
6365
- /** Abort a pending speculation (idempotent): kill the in-flight call, drop its buffered output.
6366
- * Called on divergence (send), a stale partial (VoiceEngine.onSpeculateAbort), a side-effect tool
6367
- * attempt (dispatchGuard), or host paths that will never dispatch a final (commands, voice-off). */
6368
- abortSpeculation() {
6369
- const spec = this.spec;
6370
- if (spec?.state !== "pending") return;
6371
- spec.state = "aborted";
6372
- spec.buf.length = 0;
6373
- spec.ctl.abort();
6374
- spec.decide("abort");
6375
- this.notify("diag", "speculation_aborted", { text: spec.text.slice(0, 80) });
6376
- }
6377
- /** Cancel a running background task — shared by the CancelTask tool and the CLI /tasks picker. */
6378
- cancelTask(id) {
6379
- const rec = this.tasks.get(id);
6380
- if (!rec) return `No task '${id}'.`;
6381
- if (rec.status !== "running") return `Task ${rec.id} is already ${rec.status}.`;
6382
- rec.status = "cancelled";
6383
- rec.controller.abort();
6384
- return `Task ${rec.id} (${rec.label}) cancelled.`;
6385
- }
6386
- /** Barge-in: the user took the floor while task(s) were running. Suppress those tasks' remaining SPOKEN
6387
- * delivery so a superseded topic never talks over the new one (the debt-after-jokes regression). The
6388
- * tasks keep running and still fold their result into the transcript — recoverable, just not spoken.
6389
- * Returns the parked ids (for logging). Does NOT cancel: that's a deliberate reflex/user action. */
6390
- parkInFlightDeliveries() {
6391
- this.suppressParkedResume = false;
6392
- const parked = [];
6393
- for (const rec of this.tasks.values())
6394
- if (rec.status === "running" && !rec.deliveryParked) {
6395
- rec.deliveryParked = true;
6396
- parked.push(rec.id);
6397
- }
6398
- return parked;
6399
6164
  }
6400
- /** True while there is a parked delivery to potentially resume: either one already settled (queued) or
6401
- * one still running that was parked by a barge. */
6402
- hasParkedDelivery() {
6403
- return this.parkedRedeliver.length > 0 || [...this.tasks.values()].some((t) => t.status === "running" && t.deliveryParked);
6165
+ reset() {
6166
+ this.finalText = "";
6167
+ this.partialText = "";
6168
+ this.lastCombined = "";
6169
+ this.firstTokenAt = 0;
6404
6170
  }
6405
- /** Speak any settled-and-queued parked delivery now (trivial-barge resume). Returns false if nothing was
6406
- * queued yet (the caller then arms awaitTrivialRedeliver so the task resumes the instant it settles). */
6407
- redeliverParked() {
6408
- if (!this.parkedRedeliver.length) return false;
6409
- const text = this.parkedRedeliver.splice(0).join(" ").trim();
6410
- if (text) {
6411
- this.options.host?.notify?.({ kind: "speak_utterance", message: text });
6412
- this.notify("diag", "parked_redelivered", { chars: text.length });
6413
- }
6414
- return true;
6171
+ stop() {
6172
+ this.stopped = true;
6173
+ if (this.endpointTimer) clearInterval(this.endpointTimer);
6174
+ if (this.noAudioTimer) clearInterval(this.noAudioTimer);
6175
+ this.options.source?.stop();
6176
+ if (this.ws) this.ws.onclose = null;
6177
+ this.ws?.close();
6415
6178
  }
6416
- /** Resolve when all queued voice turns AND all in-flight worker tasks have settled (tests, graceful shutdown). */
6417
- async idle() {
6418
- while (true) {
6419
- const q2 = this.queue;
6420
- await q2.catch(() => {
6421
- });
6422
- await Promise.all([...this.tasks.values()].map((t) => t.promise));
6423
- if (this.queue === q2 && ![...this.tasks.values()].some((t) => t.status === "running")) return;
6179
+ };
6180
+
6181
+ // node_modules/@bod.ee/voice/src/adapters/cartesia.ts
6182
+ var log11 = forComponent2("CartesiaTTS");
6183
+ var now2 = () => performance.now();
6184
+ var CartesiaTTSOptions = class {
6185
+ auth = "";
6186
+ voiceId = "";
6187
+ model = "sonic-3.5";
6188
+ /** 'apiKey' (server/CLI) → `api_key=` URL param; 'token' (browser, BE-minted) → `access_token=`. */
6189
+ authMode = "apiKey";
6190
+ };
6191
+ var CartesiaTTS = class _CartesiaTTS {
6192
+ options;
6193
+ ws;
6194
+ ctxSeq = 0;
6195
+ ctxId = "";
6196
+ onAudio = () => {
6197
+ };
6198
+ onDone = () => {
6199
+ };
6200
+ /** Word-level timestamps for karaoke reveal: `start[i]` = seconds from turn-audio start (absolute
6201
+ * across continuation chunks). Fired only when a consumer opts into reveal (see `wantTimestamps`). */
6202
+ onTimestamps = () => {
6203
+ };
6204
+ /** Request `add_timestamps` from Cartesia. Off by default (saves bandwidth) — the engine sets it
6205
+ * when revealMode==='word'. */
6206
+ wantTimestamps = false;
6207
+ /** Diagnostic tap (provider errors, circuit-breaker open/close, ws reconnects). Fire-and-forget:
6208
+ * a throwing handler disables itself — never affects synthesis. Wired by VoiceIO / the lab bridge. */
6209
+ onDiag = () => {
6210
+ };
6211
+ diagOn = true;
6212
+ diag(kind, fields) {
6213
+ if (!this.diagOn) return;
6214
+ try {
6215
+ this.onDiag({ t: now2(), kind, ...fields });
6216
+ } catch (e) {
6217
+ this.diagOn = false;
6218
+ log11.debug(`onDiag threw \u2014 TTS diagnostics disabled: ${e instanceof Error ? e.message : e}`);
6424
6219
  }
6425
6220
  }
6426
- /** Promise-chain mutex: turns run strictly one at a time; a failed turn doesn't poison the chain. */
6427
- enqueue(fn) {
6428
- const run = this.queue.then(fn, fn);
6429
- this.queue = run.then(() => {
6430
- }, () => {
6431
- });
6432
- return run;
6221
+ firstAudioAt = 0;
6222
+ /** Circuit breaker: consecutive error count + down flag. */
6223
+ consecutiveErrors = 0;
6224
+ consecutiveOk = 0;
6225
+ down = false;
6226
+ downAt = 0;
6227
+ probeTimer = null;
6228
+ static CB_THRESHOLD = 3;
6229
+ // open after 3 consecutive errors
6230
+ static CB_RECOVER_OK = 2;
6231
+ // close only after 2 consecutive good frames (no single-frame flap)
6232
+ static CB_PROBE_MS = 3e4;
6233
+ constructor(options) {
6234
+ this.options = { ...new CartesiaTTSOptions(), ...options };
6433
6235
  }
6434
- notify(kind, message, data) {
6435
- this.emitHost({ kind, message, data });
6236
+ closed = false;
6237
+ connecting = null;
6238
+ async connect() {
6239
+ this.closed = false;
6240
+ this.connecting = this.doConnect();
6241
+ await this.connecting;
6242
+ this.connecting = null;
6436
6243
  }
6437
- /** Host-boundary emit for the reflex's spoken channel: during a PENDING speculation, text_delta and
6438
- * hold_filler are BUFFERED (nothing may reach TTS on unconfirmed input); confirm flushes them in
6439
- * order, abort drops them silently. Everything else (task_* lifecycle, worker speak_utterance —
6440
- * which bypasses this via host.notify directly) passes through untouched. */
6441
- emitHost(ev) {
6442
- const spec = this.spec;
6443
- if (spec && (ev.kind === "text_delta" || ev.kind === "hold_filler")) {
6444
- if (spec.state === "pending") {
6445
- spec.buf.push(ev);
6446
- return;
6244
+ async doConnect() {
6245
+ const key = await resolveAuth(this.options.auth);
6246
+ const param = this.options.authMode === "token" ? "access_token" : "api_key";
6247
+ this.ws = new WebSocket(`wss://api.cartesia.ai/tts/websocket?cartesia_version=2026-03-01&${param}=${key}`);
6248
+ await new Promise((res, rej) => {
6249
+ this.ws.onopen = () => res();
6250
+ this.ws.onerror = (e) => rej(new Error(`cartesia ws: ${e.message || "connect failed"}`));
6251
+ });
6252
+ this.ws.onclose = (ev) => {
6253
+ log11.warn(`cartesia ws closed (${ev.code} ${ev.reason || ""})`);
6254
+ this.diag("tts_ws_closed", { code: ev.code, reason: String(ev.reason || ""), reconnecting: !this.closed });
6255
+ if (!this.closed) {
6256
+ this.connecting = this.doConnect().catch((e) => {
6257
+ log11.error(`cartesia reconnect failed: ${e.message}`);
6258
+ this.diag("tts_reconnect_failed", { message: e.message });
6259
+ });
6447
6260
  }
6448
- if (spec.state === "aborted") return;
6449
- }
6450
- this.options.host?.notify?.(ev);
6451
- }
6452
- /** Queue a `[task …]` event for re-voicing. Events arriving while the voice is busy coalesce into ONE turn.
6453
- * `nonClean` (out-of-band boolean, set by the caller that KNOWS this event integrates a NON-CLEAN outcome)
6454
- * marks the coalesced flush as a non-clean integration turn — turn-eligibility, never inferred from event
6455
- * text and never keyed on a (re-authored) brief string. Any dispatch in such a turn is a follow-up. */
6456
- queueRevoice(event, nonClean = false) {
6457
- this.pendingEvents.push(event);
6458
- if (nonClean) this.pendingNonClean = true;
6459
- if (this.flushQueued) return;
6460
- this.flushQueued = true;
6461
- void this.enqueue(async () => {
6462
- this.flushQueued = false;
6463
- const events = this.pendingEvents.splice(0);
6464
- const nonCleanTurn = this.pendingNonClean;
6465
- this.pendingNonClean = false;
6466
- if (!events.length) return;
6467
- const failed = events.find((e) => /^\[task\b[^\]\n]*\bfailed\b/i.test(e));
6468
- this.resetTurn();
6469
- this.turnFollowUp = nonCleanTurn;
6470
- await this.voice.send(events.join("\n"));
6471
- this.flushHeldReflexTail();
6472
- if (this.silentTurn) await this.ackIfSilent(failed ? "Sorry, that didn't work \u2014 the task failed." : void 0);
6473
- this.notify("revoice_done", "");
6261
+ };
6262
+ this.ws.onmessage = (ev) => {
6263
+ const m = JSON.parse(String(ev.data));
6264
+ if (m.context_id && m.context_id !== this.ctxId) return;
6265
+ if (m.type === "chunk" && m.data) {
6266
+ this.consecutiveErrors = 0;
6267
+ this.markRecovered();
6268
+ if (!this.firstAudioAt) this.firstAudioAt = now2();
6269
+ this.onAudio(base64ToBytes(m.data));
6270
+ } else if (m.type === "done") {
6271
+ this.consecutiveErrors = 0;
6272
+ this.markRecovered();
6273
+ this.onDone();
6274
+ } else if (m.type === "timestamps" && m.word_timestamps) {
6275
+ const wt = m.word_timestamps;
6276
+ if (wt.words?.length && wt.start?.length) this.onTimestamps(wt.words, wt.start);
6277
+ } else if (m.type === "error") {
6278
+ if (/already been cancelled|does not exist/.test(m.message || "")) return;
6279
+ this.consecutiveErrors++;
6280
+ this.diag("tts_error", { message: String(m.message || ""), code: m.status_code, contextId: m.context_id, consecutive: this.consecutiveErrors });
6281
+ if (!this.down && this.consecutiveErrors >= _CartesiaTTS.CB_THRESHOLD) {
6282
+ this.down = true;
6283
+ this.downAt = now2();
6284
+ this.consecutiveOk = 0;
6285
+ log11.warn(`TTS circuit breaker open \u2014 ${this.consecutiveErrors} consecutive errors, switching to text-only`);
6286
+ this.diag("tts_breaker_open", { errors: this.consecutiveErrors });
6287
+ this.onDone();
6288
+ this.startProbe();
6289
+ } else if (!this.down) {
6290
+ (/No valid transcripts/i.test(m.message || "") ? log11.debug : log11.warn)(`cartesia: ${JSON.stringify(m)}`);
6291
+ }
6292
+ }
6293
+ };
6294
+ }
6295
+ /** Close the breaker only after CB_RECOVER_OK consecutive good frames, so a single straggler chunk
6296
+ * after a 503 burst doesn't flap open→recover in <1s. A sub-2s down-window is a transient blip → debug. */
6297
+ markRecovered() {
6298
+ if (!this.down) return;
6299
+ if (++this.consecutiveOk < _CartesiaTTS.CB_RECOVER_OK) return;
6300
+ this.down = false;
6301
+ this.consecutiveOk = 0;
6302
+ this.stopProbe();
6303
+ const downMs = this.downAt ? now2() - this.downAt : 0;
6304
+ this.diag("tts_breaker_close", { downMs: Math.round(downMs) });
6305
+ (downMs < 2e3 ? log11.debug : log11.info)(`TTS recovered${downMs ? ` (down ${downMs}ms)` : ""}`);
6306
+ }
6307
+ /** Ensure the WS is open before sending — reconnects if idle-closed. */
6308
+ async ensureConnected() {
6309
+ if (this.connecting) await this.connecting;
6310
+ if (this.ws?.readyState !== WebSocket.OPEN) await this.connect();
6311
+ }
6312
+ /** Prime the synthesis pipeline on a throwaway context right after connect: the FIRST synthesis on
6313
+ * a fresh WS pays Cartesia's cold spin-up (~1s+ live) — absorb it at mic-on instead of turn one.
6314
+ * The returned audio is discarded (engine drops onAudio while not speaking; once a real turn calls
6315
+ * newContext() any stragglers are stale-context-filtered). Respects the circuit breaker. */
6316
+ warmup() {
6317
+ if (this.down) return;
6318
+ this.newContext();
6319
+ if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(this.frame("Ok.", false));
6320
+ }
6321
+ newContext() {
6322
+ this.ctxId = `ctx-${++this.ctxSeq}`;
6323
+ this.firstAudioAt = 0;
6324
+ return this.ctxId;
6325
+ }
6326
+ frame(transcript, cont) {
6327
+ return JSON.stringify({
6328
+ model_id: this.options.model,
6329
+ transcript,
6330
+ voice: { mode: "id", id: this.options.voiceId },
6331
+ output_format: { container: "raw", encoding: "pcm_s16le", sample_rate: TTS_SAMPLE_RATE },
6332
+ context_id: this.ctxId,
6333
+ continue: cont,
6334
+ ...this.wantTimestamps ? { add_timestamps: true } : {}
6474
6335
  });
6475
6336
  }
6476
- /** The worker's brief: the Act/Think args + a STATIC text snapshot of the recent conversation.
6477
- * Act briefs get a self-verify footer — the worker's report is trusted without review, so it
6478
- * must check its own work before reporting (nearly free under prompt caching; measured honest:
6479
- * it does NOT fix one-shot logic bugs — see mind/10). Think tasks are pure reasoning — no footer. */
6480
- buildBrief(brief, tier = "act", deliver = true) {
6481
- 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");
6482
- 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." : "";
6483
- const deliverContract = deliver ? `
6484
-
6485
- ## DELIVER (spoken delivery)
6486
- 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." : "") : "";
6487
- return `${nowLine()}.
6337
+ speak(text, cont) {
6338
+ if (this.down) return;
6339
+ if (cont && !text) return;
6340
+ if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(this.frame(text, cont));
6341
+ else void this.ensureConnected().then(() => this.ws?.readyState === WebSocket.OPEN && this.ws.send(this.frame(text, cont)));
6342
+ }
6343
+ end() {
6344
+ if (this.down) {
6345
+ this.onDone();
6346
+ return;
6347
+ }
6348
+ if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(this.frame("", false));
6349
+ }
6350
+ cancel() {
6351
+ if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(JSON.stringify({ context_id: this.ctxId, cancel: true }));
6352
+ }
6353
+ startProbe() {
6354
+ if (this.probeTimer) return;
6355
+ this.probeTimer = setInterval(() => {
6356
+ if (!this.down) {
6357
+ this.stopProbe();
6358
+ return;
6359
+ }
6360
+ this.consecutiveErrors = 0;
6361
+ this.newContext();
6362
+ if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(this.frame("Ok.", false));
6363
+ }, _CartesiaTTS.CB_PROBE_MS);
6364
+ this.probeTimer.unref?.();
6365
+ }
6366
+ stopProbe() {
6367
+ if (this.probeTimer) {
6368
+ clearInterval(this.probeTimer);
6369
+ this.probeTimer = null;
6370
+ }
6371
+ }
6372
+ close() {
6373
+ this.closed = true;
6374
+ this.stopProbe();
6375
+ if (this.ws) this.ws.onclose = null;
6376
+ this.ws?.close();
6377
+ }
6378
+ };
6379
+ function base64ToBytes(b64) {
6380
+ if (typeof Buffer !== "undefined") return Buffer.from(b64, "base64");
6381
+ const bin = atob(b64);
6382
+ const out = new Uint8Array(bin.length);
6383
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
6384
+ return out;
6385
+ }
6488
6386
 
6489
- ` + (recent ? `${brief}
6387
+ // src/voice/engine.ts
6388
+ init_logging();
6389
+ configureLogging((name) => {
6390
+ const l = forComponent(name);
6391
+ const at = (m) => (...a) => l[m]?.(...a);
6392
+ return { debug: at("debug"), verbose: at("verbose"), info: at("info"), warn: at("warn"), error: at("error") };
6393
+ });
6490
6394
 
6491
- ## Recent conversation (for context)
6492
- ${recent}` : brief) + verify + deliverContract;
6493
- }
6494
- /** Spawn a detached worker for task `id`; its settlement notifies + enqueues the re-voice turn. */
6495
- spawnWorker(id, label, briefText, tier, brief, followUp) {
6395
+ // src/duplex.ts
6396
+ var log12 = forComponent("DuplexAgent");
6397
+ function describeCall(call) {
6398
+ const v = call.args && Object.values(call.args).find((x) => typeof x === "string" && x.trim());
6399
+ const hint = v ? ` (${String(v).replace(/\s+/g, " ").trim().slice(0, 48)})` : "";
6400
+ return `${call.name}${hint}`;
6401
+ }
6402
+ var DuplexAgentOptions = class {
6403
+ /** Any ai.libx.js AIClient — shared by all tiers (routed by model). */
6404
+ ai;
6405
+ /** The WORKER's filesystem (act + think). If omitted the worker keeps Agent's jailed-disk-at-cwd default. */
6406
+ fs;
6407
+ // The reflex IS the voice. 120b (not 20b) for channel discipline + instruction-following: the 20b
6408
+ // mislabels gpt-oss harmony channels under load, leaking raw analysis into the spoken `final` channel
6409
+ // (and misfiring Hold). 120b is the same price tier (~$0.15/$0.60) — the quality/cost trade is free.
6410
+ reflexModel = "groq/openai/gpt-oss-120b";
6411
+ actModel = "anthropic/claude-sonnet-4-6";
6412
+ /** Premium reasoning model. Set to `false` to disable the Think tier entirely. */
6413
+ thinkModel = "anthropic/claude-opus-4-8";
6414
+ /** Per-worker providerOptions, derived from the worker's actual model at spawn time (IoC — keeps duplex
6415
+ * provider-agnostic). Workers override the reflex/main model, so provider-specific options (e.g. cursor's
6416
+ * cwd/cursorSession) must be recomputed for the worker's model, never inherited from the main template —
6417
+ * leaking cursor options to an anthropic worker is a hard 400. Returns undefined → no providerOptions. */
6418
+ providerOptionsFor;
6419
+ /** Escape hatches merged over the derived per-agent options. */
6420
+ reflexOptions;
6421
+ actOptions;
6422
+ thinkOptions;
6423
+ /** Fresh-context check on each successful Act task: a NEW agent (no self-confirmation bias) re-reads
6424
+ * the file state against the brief and fixes any gap before the result is re-voiced. Bounded to one
6425
+ * pass; ~2x Act cost so default OFF. The self-verify FOOTER (same context) was measured ineffective —
6426
+ * this is the structural fix (see mind/10). Think tasks are pure reasoning, never checked. */
6427
+ verifyActTasks = false;
6428
+ /** Receives the voice text_delta stream + task lifecycle events. */
6429
+ host;
6430
+ /** How many recent transcript messages are rendered into a worker's brief. */
6431
+ excerptTurns = 6;
6432
+ /** Voice register: 'neutral' = clean spoken style; 'conversational' = human-like — fillers,
6433
+ * backchannels, impulsive first reactions before content (mimics real duplex conversation). */
6434
+ voiceStyle = "neutral";
6435
+ /** Teach the model to emit inline `[emotion]` tags for Cartesia emotion control. Only set when the
6436
+ * TTS actually speaks them — text-duplex (no TTS) would otherwise print literal tags. */
6437
+ emotionTags = false;
6438
+ /** Awaited BEFORE a worker spawns — open a per-task checkpoint frame, audit, etc.
6439
+ * (post-spawn would race the worker's first edits). */
6440
+ onTaskStart;
6441
+ /** Re-voice throttled worker progress asides ('[task t1 progress] …') so long tasks aren't dead
6442
+ * air. Off by default — each update costs a voice turn (LLM call + speech). */
6443
+ progressUpdates = false;
6444
+ /** Min ms between progress re-voices per task. */
6445
+ progressIntervalMs = 25e3;
6446
+ /** Relay worker questions (AskUserQuestion + permission asks via parkQuestion) through the VOICE:
6447
+ * the question re-voices as '[task <id> asks] …', the user answers conversationally, and the
6448
+ * voice model resolves it with the AnswerTask tool. Off → host.ask passthrough (text menus). */
6449
+ askRelay = false;
6450
+ /** Parked questions auto-resolve empty after this long (callers map '' to deny/best-judgment). */
6451
+ askTimeoutMs = 12e4;
6452
+ /** Max retained task records: oldest SETTLED tasks (and their activity tails) are evicted past this,
6453
+ * bounding memory over a long-lived session. Running tasks are never evicted. */
6454
+ maxTaskRecords = 50;
6455
+ /** Host overrides for QuickLook lookups (keyed by `what`). The engine's defaults go through the
6456
+ * (possibly jailed) fs — e.g. `.git/**` is deny-listed, so the CLI supplies 'branch' itself. */
6457
+ quickLook;
6458
+ /** Memory directory/directories on the WORKER fs. If set, the voice agent gets Remember + Recall
6459
+ * tools directly (no delegation needed) and implicit capture guidance. */
6460
+ memoryDir;
6461
+ /** User-scope memory dir for global facts (type=user/feedback). Forwarded to Remember's routing. */
6462
+ memoryUserDir;
6463
+ };
6464
+ var RESERVED_EVENT_MARKER = /\[task\b[^\]\n]*\b(?:completed|failed|progress|asks)\b/i;
6465
+ var RESERVED_EVENT_OPENER = /\[\s*task\b/i;
6466
+ var STAGE_DIRECTION_RE = /^\(\s*(?:(?:waiting|checking|searching|thinking|processing|loading|working|fetching|looking)\b[^)]*|[^)]*(?:\.\.\.|…)\s*)\)$/i;
6467
+ function nowLine() {
6468
+ 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" })}`;
6469
+ }
6470
+ function isTrivialBarge(text) {
6471
+ const t = text.trim().toLowerCase().replace(/[.,!?…\s]+$/g, "").replace(/^[.,!?…\s]+/, "");
6472
+ if (!t) return false;
6473
+ 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;
6474
+ const core = t.replace(/^(?:oh|um+|uh+|er+|hmm+|ah+|well|so|okay|ok|yeah|yep)[\s,]+/, "").trim();
6475
+ 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);
6476
+ }
6477
+ 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.';
6478
+ 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.";
6479
+ var THINK_DISABLED_GUIDANCE = "(Think tier is not available \u2014 use Act for all escalations.)";
6480
+ 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).`;
6481
+ 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(", ")}.`;
6482
+ var DuplexAgent = class _DuplexAgent {
6483
+ options;
6484
+ voice;
6485
+ tasks = /* @__PURE__ */ new Map();
6486
+ queue = Promise.resolve();
6487
+ seq = 0;
6488
+ pendingEvents = [];
6489
+ /** Spoken text of parked deliveries that have SETTLED, awaiting a trivial-barge resume decision on the
6490
+ * next turn (a substantive turn clears it — the result stays in the transcript, recoverable by asking). */
6491
+ parkedRedeliver = [];
6492
+ /** A trivial barge arrived while a parked delivery was STILL RUNNING → resume it the moment it settles. */
6493
+ awaitTrivialRedeliver = false;
6494
+ /** Set by a SUBSTANTIVE turn after a barge: the user moved on, so a parked delivery that settles LATER
6495
+ * must NOT arm a resume (else a much-later "go on" replays a stale result). Reset by a fresh barge. */
6496
+ suppressParkedResume = false;
6497
+ /** Out-of-band follow-up attribution for the events coalescing into the next flush turn: TRUE iff ≥1 of
6498
+ * the tasks being integrated was NON-CLEAN (early-stop/failure). Carried out-of-band on the enqueue call
6499
+ * by the caller that KNOWS the outcome — a plain boolean the MODEL CANNOT PERTURB. It is NOT scanned from
6500
+ * worker-authored event text (v1: an "Outcome:" substring over-stamped siblings) and NOT keyed on a brief
6501
+ * string the reflex re-authors (v2: a paraphrased escalation brief missed the Set → followUp:false →
6502
+ * RE-ENABLED unbounded auto-escalation, the dangerous runaway direction). See [[wrong-discriminator]] /
6503
+ * [[drive-real-reflex]] / [[fakeaiclient-blind-to-wire-format]]. */
6504
+ pendingNonClean = false;
6505
+ flushQueued = false;
6506
+ /** Per-voice-turn guards (reset by resetTurn at each turn's start). The reflex is a weak model:
6507
+ * left unguarded it polls TaskStatus after a dispatch and/or dispatches silently (dead air).
6508
+ * Like CC's Task tool, a dispatch is "said my piece, now wait for the push" — these enforce that. */
6509
+ turnDispatched = false;
6510
+ // an Act/Think fired this turn
6511
+ spokeBeforeDispatch = false;
6512
+ // the reflex ALREADY acked before dispatching — the forced post-dispatch text step must stay silent (live: "Got it…" twice)
6513
+ turnBriefs = /* @__PURE__ */ new Set();
6514
+ // briefs dispatched this turn (detect identical re-dispatch)
6515
+ spokeThisTurn = false;
6516
+ // any non-empty text_delta streamed this turn
6517
+ externalSpeech = false;
6518
+ // host spoke on our behalf (adaptive micro-ack) — not reflex output
6519
+ heldThisTurn = false;
6520
+ // Hold called this turn → turn is INTENTIONALLY silent (suppress reflex text + no dead-air ack)
6521
+ nudging = false;
6522
+ // re-ack pass in flight: block ALL tools, prevent recursion
6523
+ reflexBuf = "";
6524
+ // accumulated reflex text this turn (fabricated-event detection)
6525
+ reflexForwarded = 0;
6526
+ // chars of reflexBuf already forwarded to the host/TTS
6527
+ fabricationCut = false;
6528
+ // reflex emitted a reserved [task …] marker → suppress its tail
6529
+ /** TRUE for the duration of a re-voice turn that is integrating ≥1 NON-CLEAN task (turn-eligibility,
6530
+ * carried out-of-band — NOT derived from any worker/brief string). ANY Act/Think dispatched in such a
6531
+ * turn is stamped followUp:true. This GUARANTEES the dangerous direction is impossible: a genuine
6532
+ * escalation (even one with a paraphrased brief) ALWAYS lands in a non-clean integration turn, so it is
6533
+ * ALWAYS recognized as a follow-up and CANNOT re-escalate (one hop). The single-dispatch-per-turn guard
6534
+ * means at most one dispatch happens per flush, so realistically "the one dispatch IS the escalation".
6535
+ * ACCEPTED SAFE-DIRECTION ERROR: if the reflex instead dispatches FRESH unrelated work during a non-clean
6536
+ * flush (rare — and only possible when it batches multiple calls in one step, bypassing the guard), that
6537
+ * fresh task is over-stamped followUp:true and forgoes ONE future auto-escalation. That is SAFE (it only
6538
+ * ever REMOVES a future escalation, never adds one — no runaway) and is the correct side to err on. */
6539
+ turnFollowUp = false;
6540
+ /** Hard absolute backstop against runaway regardless of attribution: total automatic escalations across
6541
+ * the whole conversation. Once it hits MAX_AUTO_ESCALATIONS, no integration turn offers escalate/re-delegate. */
6542
+ autoEscalations = 0;
6543
+ static MAX_AUTO_ESCALATIONS = 8;
6544
+ /** Parked worker questions awaiting a (voice-relayed) user answer, keyed by ask id. */
6545
+ pendingAsks = /* @__PURE__ */ new Map();
6546
+ /** SPECULATIVE REFLEX (VoiceEngine.onSpeculate → speculate()): the reflex turn starts on a stable
6547
+ * PARTIAL transcript, its spoken output buffered — nothing reaches TTS until the endpointed final
6548
+ * confirms via send() (which flushes the buffer and adopts the call as THE turn). A divergent final
6549
+ * aborts it: output dropped, history rolled back, the final dispatches normally. */
6550
+ spec;
6551
+ /** Aborted speculative calls (double-billing visibility — each one paid for tokens never spoken). */
6552
+ speculativeAbortedCalls = 0;
6553
+ /** Tools the reflex may execute on UNCONFIRMED (speculated) input — read-only lookups and the
6554
+ * intentionally-silent Hold. Anything else (Act/Think/AnswerTask/CancelTask/ExitSession/memory
6555
+ * writes/…) is a side effect on input the user may not have said: the guard ABORTS the speculation
6556
+ * instead (the endpointed final then dispatches normally and may use the tool for real). */
6557
+ static SPEC_SAFE_TOOLS = /* @__PURE__ */ new Set(["QuickLook", "TaskStatus", "Hold"]);
6558
+ /** Lazily resolved memory tools (async loadMemory runs in initMemory). */
6559
+ memoryReady;
6560
+ constructor(options) {
6561
+ this.options = { ...new DuplexAgentOptions(), ...options };
6496
6562
  const o = this.options;
6497
- const tierOpts = tier === "think" ? o.thinkOptions : o.actOptions;
6498
- const tierModel = tier === "think" ? o.thinkModel : o.actModel;
6499
- const controller = new AbortController();
6500
- const base = tierOpts?.hooks ?? o.actOptions?.hooks;
6501
- const report = o.progressUpdates ? this.progressReporter(id) : void 0;
6502
- const tail = [];
6503
- const pushTail = (line) => {
6504
- tail.push(line.slice(0, 200));
6505
- if (tail.length > 120) tail.splice(0, tail.length - 120);
6506
- };
6507
- const hooks = {
6508
- ...base,
6509
- preToolUse: async (call, meta) => {
6510
- const d = await base?.preToolUse?.(call, meta);
6511
- pushTail(`\u2699 ${describeCall(call)}`);
6512
- report?.pre(call);
6513
- return d;
6514
- },
6515
- postToolUse: async (call, result, meta) => {
6516
- await base?.postToolUse?.(call, result, meta);
6517
- const last = result?.trim().split("\n").filter(Boolean).pop();
6518
- if (last) pushTail(` \u21B3 ${last}`);
6519
- report?.post(call);
6520
- },
6521
- onToolOutput: (call, chunk, meta) => {
6522
- base?.onToolOutput?.(call, chunk, meta);
6523
- report?.output(chunk);
6524
- }
6525
- };
6526
- const relayAsk = async (q2) => {
6527
- const opts = q2.options?.length ? ` Options: ${q2.options.map((x) => x.label).join(", ")}.` : "";
6528
- const a = await this.parkQuestion(id, `${q2.question}${opts}`);
6529
- return a || "(no answer from the user \u2014 use your best judgment and note the assumption)";
6530
- };
6531
- const splitter = new SpokenSplitter();
6532
- const speak = (seg) => {
6533
- if (!seg) return;
6534
- const r = this.tasks.get(id);
6535
- if (r) r.spokenText = (r.spokenText ? r.spokenText + " " : "") + seg;
6536
- if (!r?.deliveryParked) o.host?.notify?.({ kind: "speak_utterance", message: seg });
6537
- };
6538
- const coalescer = new SentenceCoalescer();
6539
- const feedSpoken = (s) => {
6540
- const ready = coalescer.feed(s);
6541
- if (ready) speak(ready);
6542
- };
6543
- const flushSpoken = () => speak(coalescer.flush());
6544
- const askBridge = o.askRelay ? { ask: relayAsk } : o.host?.ask ? { ask: (q2) => o.host.ask(q2) } : {};
6545
- const workerHost = {
6546
- ...askBridge,
6563
+ if (o.memoryDir && o.fs) {
6564
+ this.memoryReady = loadMemory(o.fs, o.memoryDir, { maxWritesPerSession: 10, userDir: o.memoryUserDir });
6565
+ }
6566
+ 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.";
6567
+ const thinkSlot = o.thinkModel !== false ? THINK_GUIDANCE : THINK_DISABLED_GUIDANCE;
6568
+ const workerToolNames = (o.actOptions?.tools ?? []).map((t) => t.name);
6569
+ const canSearch = workerToolNames.some((n) => /WebSearch/i.test(n));
6570
+ const canFetch = workerToolNames.some((n) => /WebFetch/i.test(n));
6571
+ 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)" : "";
6572
+ const mcpNames = [
6573
+ ...Object.keys(o.actOptions?.providerOptions?.mcpServers ?? {}),
6574
+ ...new Set(workerToolNames.filter((n) => n.startsWith("mcp__")).map((n) => n.slice(5).split("__")[0]))
6575
+ ];
6576
+ 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' : "") : "";
6577
+ 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 : "") + `
6578
+ ${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.`;
6579
+ const tools = [
6580
+ ...o.reflexOptions?.tools ?? [],
6581
+ this.actTool(),
6582
+ ...o.thinkModel !== false ? [this.thinkTool()] : [],
6583
+ this.taskStatusTool(),
6584
+ this.cancelTaskTool(),
6585
+ this.quickLookTool(),
6586
+ this.answerTaskTool(),
6587
+ this.holdTool()
6588
+ ];
6589
+ const host = o.host;
6590
+ const voiceHost = host && {
6591
+ ask: host.ask ? (q2) => host.ask(q2) : void 0,
6592
+ confirm: host.confirm ? (p, m) => host.confirm(p, m) : void 0,
6547
6593
  notify: (ev) => {
6548
6594
  if (ev?.kind === "text_delta" && typeof ev.message === "string") {
6549
- const { spoken, detail } = splitter.feed(ev.message);
6550
- feedSpoken(spoken);
6551
- if (detail.trim()) pushTail(detail.trim());
6595
+ if (this.heldThisTurn) return;
6596
+ if (this.fabricationCut) return;
6597
+ if (this.turnDispatched && this.spokeBeforeDispatch) return;
6598
+ const msg = ev.message;
6599
+ this.reflexBuf += msg;
6600
+ this.scrubStageDirections();
6601
+ const m = this.reflexBuf.match(RESERVED_EVENT_MARKER) ?? this.reflexBuf.match(RESERVED_EVENT_OPENER);
6602
+ if (m) {
6603
+ this.fabricationCut = true;
6604
+ log12.warn(`reflex fabricated a [task \u2026] event in its spoken stream \u2014 cutting it (kept ${m.index} chars)`);
6605
+ const safe = this.reflexBuf.slice(this.reflexForwarded, m.index);
6606
+ if (!safe) return;
6607
+ if (safe.trim()) this.spokeThisTurn = true;
6608
+ this.emitHost({ ...ev, message: safe });
6609
+ return;
6610
+ }
6611
+ const held = this.reflexBuf.length - this.reflexForwarded;
6612
+ const partial = held > 0 && /\[\s*t?a?s?k?$/i.test(this.reflexBuf.slice(-Math.min(held, 6)));
6613
+ let upto = partial ? this.reflexBuf.length - this.reflexBuf.slice(-6).match(/\[\s*t?a?s?k?$/i)[0].length : this.reflexBuf.length;
6614
+ const paren = this.reflexBuf.lastIndexOf("(");
6615
+ if (paren >= this.reflexForwarded && !this.reflexBuf.includes(")", paren) && this.reflexBuf.length - paren <= 80)
6616
+ upto = Math.min(upto, paren);
6617
+ const out = this.reflexBuf.slice(this.reflexForwarded, upto);
6618
+ this.reflexForwarded = upto;
6619
+ if (!out) return;
6620
+ if (out.trim()) this.spokeThisTurn = true;
6621
+ this.emitHost({ ...ev, message: out });
6552
6622
  return;
6553
6623
  }
6624
+ host.notify?.(ev);
6554
6625
  }
6555
6626
  };
6556
- const agentOpts = {
6627
+ this.voice = new Agent({
6557
6628
  ai: o.ai,
6558
- fs: o.fs,
6559
- model: tierModel,
6560
- ...tier === "think" ? { reasoning: tierOpts?.reasoning ?? "high" } : {},
6561
- ...tierOpts,
6562
- // Recompute providerOptions for THIS worker's model (after tierOpts so it wins over any inherited
6563
- // main-template value) — prevents cursor-only cwd/cursorSession leaking onto an anthropic worker.
6564
- providerOptions: o.providerOptionsFor?.(tierModel),
6629
+ fs: new MemFilesystem2(),
6630
+ model: o.reflexModel,
6565
6631
  stream: true,
6566
- // worker streams text_delta so the splitter can extract <spoken> live (after tierOpts: never overridden off)
6567
- host: workerHost,
6568
- // carries BOTH ask AND the <spoken>-splitting notify
6569
- ...hooks ? { hooks } : {},
6570
- signal: controller.signal
6571
- // shared with the checker so a cancel tears down both
6572
- };
6573
- const promise = new Agent(agentOpts).run(briefText).then((res) => {
6574
- const { spoken, detail } = splitter.flush();
6575
- feedSpoken(spoken);
6576
- if (detail.trim()) pushTail(detail.trim());
6577
- flushSpoken();
6578
- return res;
6579
- }).then((res) => this.maybeVerify(id, brief, res, tier, agentOpts, askBridge)).then((res) => this.onWorkerSettled(id, res)).catch((err2) => this.onWorkerFailed(id, err2));
6580
- this.tasks.set(id, { id, label, status: "running", controller, promise, tail, brief, followUp, splitter });
6581
- if (this.tasks.size > this.options.maxTaskRecords)
6582
- for (const [tid, rec] of this.tasks) {
6583
- if (this.tasks.size <= this.options.maxTaskRecords) break;
6584
- if (rec.status !== "running") this.tasks.delete(tid);
6585
- }
6586
- }
6587
- /** Fresh-context check of a successful Act task: a NEW agent (same model/fs/tools, but NO shared
6588
- * conversation context) re-reads the file state against the brief and fixes any gap. The fix lands
6589
- * on the shared fs automatically (workers write fs directly, no overlay), so grading sees the
6590
- * corrected state. Bounded to ONE pass. Off unless `verifyActTasks`; never runs for think/failed/
6591
- * cancelled tasks. Usage is merged so /cost reflects the real (worker + checker) spend. */
6592
- async maybeVerify(id, brief, res, tier, agentOpts, askBridge) {
6593
- if (!this.options.verifyActTasks || tier !== "act" || res.finishReason !== "stop") return res;
6594
- if (this.tasks.get(id)?.status === "cancelled") return res;
6595
- const { stream: _stream, host: _host, ...restOpts } = agentOpts;
6596
- const checkerOpts = {
6597
- ...restOpts,
6598
- ...askBridge.ask ? { host: { ask: askBridge.ask } } : {}
6599
- };
6600
- const checkBrief = `${this.buildBrief(brief, tier, false)}
6601
-
6602
- ## VERIFY MODE
6603
- 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".`;
6604
- this.notify("task_verify", `task ${id}: verifying`, { id });
6605
- const cres = await new Agent(checkerOpts).run(checkBrief);
6606
- if (cres.finishReason !== "stop") {
6607
- log10.warn(`task ${id}: verify inconclusive (${cres.finishReason})`);
6608
- this.notify("task_verify", `task ${id}: verify inconclusive (${cres.finishReason})`, { id, finishReason: cres.finishReason });
6609
- }
6610
- const sum = (a = 0, b = 0) => a + b;
6611
- return {
6612
- ...res,
6613
- steps: res.steps + cres.steps,
6614
- // Merge the checker's messages so downstream tool-call/step accounting includes BOTH agents
6615
- // (else a verified task's toolCalls would undercount vs its steps/usage).
6616
- messages: [...res.messages, ...cres.messages],
6617
- usageEstimated: res.usageEstimated || cres.usageEstimated,
6618
- usage: res.usage && cres.usage ? {
6619
- promptTokens: sum(res.usage.promptTokens, cres.usage.promptTokens),
6620
- completionTokens: sum(res.usage.completionTokens, cres.usage.completionTokens),
6621
- totalTokens: sum(res.usage.totalTokens, cres.usage.totalTokens),
6622
- cacheCreationTokens: sum(res.usage.cacheCreationTokens, cres.usage.cacheCreationTokens),
6623
- cacheReadTokens: sum(res.usage.cacheReadTokens, cres.usage.cacheReadTokens)
6624
- } : res.usage ?? cres.usage
6625
- };
6626
- }
6627
- /** Throttled per-task progress: worker tool calls → at most one progress re-voice per interval.
6628
- * Two sources, one throttle: completed steps (post) and a heartbeat for a SINGLE long tool call
6629
- * (pre records the in-flight call; a self-cleaning timer narrates "still inside Bash — 70s").
6630
- * Completion supersedes: nothing is emitted once the task has settled. */
6631
- progressReporter(id) {
6632
- let lastAt = Date.now();
6633
- let steps = 0;
6634
- let inflight = null;
6635
- const due = () => {
6636
- if (this.pendingAsks.size) return void 0;
6637
- const rec = this.tasks.get(id);
6638
- return rec && rec.status === "running" && Date.now() - lastAt >= this.options.progressIntervalMs ? rec : void 0;
6639
- };
6640
- const emit = (rec, line, call) => {
6641
- lastAt = Date.now();
6642
- this.notify("task_progress", `task ${id} (${rec.label}): ${line}`, { id, steps, call: call.name });
6643
- this.queueRevoice(`[task ${id} progress] ${line}`);
6644
- };
6645
- const timer = setInterval(() => {
6646
- const rec = this.tasks.get(id);
6647
- if (!rec || rec.status !== "running") return clearInterval(timer);
6648
- if (!inflight || !due()) return;
6649
- const last = inflight.tail.trim().split("\n").filter(Boolean).pop()?.slice(-80);
6650
- 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);
6651
- }, Math.max(this.options.progressIntervalMs, 250));
6652
- timer.unref?.();
6653
- return {
6654
- pre: (call) => {
6655
- inflight = { call, at: Date.now(), tail: "" };
6656
- },
6657
- output: (chunk) => {
6658
- if (inflight) inflight.tail = (inflight.tail + chunk).slice(-500);
6659
- },
6660
- // digest only — NEVER re-voices directly
6661
- post: (call) => {
6662
- steps++;
6663
- inflight = null;
6664
- const rec = due();
6665
- if (rec) emit(rec, `still running \u2014 ${steps} steps so far, now: ${describeCall(call)}`, call);
6666
- }
6667
- };
6668
- }
6669
- /** Park a question under `askId` (a task id, or any unique key for permission asks): re-voices
6670
- * '[task <id> asks] …' and resolves with the user's answer via AnswerTask — or '' on timeout/
6671
- * task settle (callers map '' to deny / best-judgment). Workers never block forever. */
6672
- parkQuestion(askId, question) {
6673
- return new Promise((resolve4) => {
6674
- let settled = false;
6675
- const finish = (answer) => {
6676
- if (settled) return;
6677
- settled = true;
6678
- clearTimeout(timer);
6679
- this.pendingAsks.delete(askId);
6680
- resolve4(answer);
6681
- };
6682
- const timer = setTimeout(() => {
6683
- this.notify("task_ask_timeout", `task ${askId}: question timed out \u2014 proceeding without an answer`);
6684
- finish("");
6685
- }, this.options.askTimeoutMs);
6686
- this.pendingAsks.set(askId, { question, resolve: finish });
6687
- this.notify("task_ask", `task ${askId} asks: ${question}`, { id: askId, question });
6688
- this.queueRevoice(`[task ${askId} asks] ${question}
6689
- (Relay this to the user in your own words. When they answer, call AnswerTask with id "${askId}" and their answer.)`);
6690
- });
6691
- }
6692
- /** Resolve any question a settling/cancelled task left parked (its answer can no longer matter). */
6693
- dropAsk(id) {
6694
- this.pendingAsks.get(id)?.resolve("");
6695
- }
6696
- /** Build the INTEGRATION TURN prompt for a NON-CLEAN settled worker (early stop / failure). A clean
6697
- * success never reaches here — it streams its own `<spoken>` delivery during the run. For a partial
6698
- * or failed result the outcome re-enters the reflex as a decision (like a tool_result flowing back
6699
- * into a normal agent loop): the reflex evaluates the outcome against the original intent and chooses
6700
- * what to do next.
6701
- *
6702
- * Decision branches (the reflex acts on them with EXISTING tools — no new surface):
6703
- * • accept → SPEAK the (partial) result plainly — don't dress a failure up as success.
6704
- * • escalate → call `Think` with the SAME brief — only when Act failed/stalled AND a Think tier
6705
- * exists AND this task wasn't already a follow-up (one hop max). Wires the dead
6706
- * "Reserve Think for a problem Act already FAILED at" promise.
6707
- * • re-delegate→ call `Act` with a CORRECTED brief — for a recoverable error / partial result.
6708
- * • ask → ask the user ONE concrete question if genuinely blocked.
6709
- *
6710
- * Keeps the `[task <id> completed]` / `[task <id> failed]` opener so existing coalescing + the
6711
- * failed-revoice fallback still fire, and the per-event transcript markers stay intact. */
6712
- integrationPrompt(rec, outcome, body, finishReason) {
6713
- const opener = outcome === "error" ? `[task ${rec.id} failed]` : `[task ${rec.id} completed]`;
6714
- const underCap = this.autoEscalations < _DuplexAgent.MAX_AUTO_ESCALATIONS;
6715
- const canEscalate = (outcome === "error" || outcome === "incomplete") && underCap;
6716
- const hasThink = this.options.thinkModel !== false;
6717
- const options = [];
6718
- if (!rec.followUp && canEscalate && hasThink)
6719
- 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");
6720
- if (!rec.followUp && canEscalate)
6721
- options.push("RE-DELEGATE to Act with a corrected brief if the failure looks recoverable (a wrong path, a fixable mistake)");
6722
- options.push("ASK the user one short, concrete question if you genuinely cannot proceed without their input");
6723
- options.push("ACCEPT and tell the user plainly what happened (don't dress a failure up as success)");
6724
- 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.`;
6725
- const state = outcome === "error" ? `the worker FAILED with: ${body}` : `the worker STOPPED EARLY (${finishReason}) \u2014 its result is PARTIAL, not a finished success: ${body}`;
6726
- return `${opener} Original request: "${rec.brief}". Outcome: ${state}.${decision}`;
6727
- }
6728
- onWorkerSettled(id, res) {
6729
- this.dropAsk(id);
6730
- const rec = this.tasks.get(id);
6731
- if (res.finishReason === "aborted" || rec.status === "cancelled") {
6732
- rec.status = "cancelled";
6733
- this.notify("task_cancelled", `task ${id} (${rec.label}) cancelled`);
6734
- return;
6735
- }
6736
- if (res.finishReason === "error") {
6737
- const msg = res.error instanceof Error ? res.error.message : String(res.error ?? "unknown error");
6738
- return this.failTask(rec, msg);
6739
- }
6740
- rec.status = "done";
6741
- rec.result = res.text;
6742
- const incomplete = res.finishReason !== "stop";
6743
- log10.verbose(`task ${id} done (${res.steps} steps${incomplete ? `, INCOMPLETE: ${res.finishReason}` : ""})`);
6744
- this.notify("task_done", `task ${id} (${rec.label}) completed`, {
6745
- id,
6746
- text: res.text,
6747
- usage: res.usage,
6748
- usageEstimated: res.usageEstimated,
6749
- finishReason: res.finishReason,
6750
- steps: res.steps,
6751
- toolCalls: res.messages.filter((m) => m.role === "tool").length
6632
+ host: voiceHost,
6633
+ // The reflex IS the conversational channel — it confirms ambiguity inline ("did you mean…?"),
6634
+ // never via the blocking AskUserQuestion tool (Agent auto-adds it whenever a host is set). Left in,
6635
+ // it stalls a voice turn until the kill-switch. Worker questions still reach the user via parkQuestion.
6636
+ askUserQuestion: false,
6637
+ systemPrompt: prompt,
6638
+ instructionFiles: false,
6639
+ maxSteps: 8,
6640
+ timeoutMs: 3e4,
6641
+ ...o.reflexOptions,
6642
+ tools,
6643
+ // Composed AFTER the spread so the dispatch guard can't be dropped by reflexOptions.
6644
+ hooks: composeHooks(this.dispatchGuard(), o.reflexOptions?.hooks)
6752
6645
  });
6753
- if (incomplete) {
6754
- return this.queueRevoice(this.integrationPrompt(rec, "incomplete", res.text, res.finishReason), true);
6755
- }
6756
- const tail = rec.splitter?.flush();
6757
- if (tail?.spoken && !rec.deliveryParked) this.options.host?.notify?.({ kind: "speak_utterance", message: tail.spoken });
6758
- if (res.text.trim()) this.voice.transcript.push({ role: "assistant", content: res.text });
6759
- if (rec.deliveryParked && !this.suppressParkedResume) {
6760
- const gist = (rec.spokenText ?? "").trim() || res.text.trim();
6761
- if (gist) {
6762
- if (this.awaitTrivialRedeliver) {
6763
- this.awaitTrivialRedeliver = false;
6764
- this.options.host?.notify?.({ kind: "speak_utterance", message: gist });
6765
- this.notify("diag", "parked_redelivered", { chars: gist.length });
6766
- } else this.parkedRedeliver.push(gist);
6767
- }
6768
- }
6769
- if (!rec.splitter?.spokeAny && res.text.trim() && !rec.deliveryParked)
6770
- this.options.host?.notify?.({ kind: "speak_utterance", message: res.text });
6771
6646
  }
6772
- onWorkerFailed(id, err2) {
6773
- this.failTask(this.tasks.get(id), err2 instanceof Error ? err2.message : String(err2));
6647
+ /** Resolve memory tools + inject index into voice system prompt (once). */
6648
+ async initMemory() {
6649
+ if (!this.memoryReady) return;
6650
+ const mem = await this.memoryReady;
6651
+ this.memoryReady = void 0;
6652
+ this.voice.options.tools.push(...mem.tools);
6653
+ if (mem.index) this.voice.options.systemPrompt += "\n\n" + mem.index;
6774
6654
  }
6775
- failTask(rec, msg) {
6776
- this.dropAsk(rec.id);
6777
- rec.status = "error";
6778
- rec.result = msg;
6779
- log10.warn(`task ${rec.id} failed: ${msg}`);
6780
- this.notify("task_error", `task ${rec.id} (${rec.label}) failed: ${msg}`);
6781
- this.queueRevoice(this.integrationPrompt(rec, "error", msg, "error"), true);
6655
+ /** Flush any held-back trailing fragment (a possible `[task` opener that never completed) once the
6656
+ * turn's stream is done — so a legit message ending in "[t" isn't silently dropped. */
6657
+ flushHeldReflexTail() {
6658
+ if (this.fabricationCut) return;
6659
+ this.scrubStageDirections();
6660
+ const tail = this.reflexBuf.slice(this.reflexForwarded);
6661
+ this.reflexForwarded = this.reflexBuf.length;
6662
+ if (!tail) return;
6663
+ if (tail.trim()) this.spokeThisTurn = true;
6664
+ this.emitHost({ kind: "text_delta", message: tail });
6782
6665
  }
6783
- // --- voice tools (closures over this instance) ---
6784
- /** Live-switch the think tier: `false` disables (removes the Think tool from the voice agent),
6785
- * a model id enables (adds the tool if missing). The system-prompt THINK_SLOT text is frozen at
6786
- * construction — the tool's own description carries the routing guidance, so a live enable works;
6787
- * dispatch()'s think→act fallback covers any straggler calls after a live disable. */
6788
- setThinkModel(model) {
6789
- this.options.thinkModel = model;
6790
- const tools = this.voice.options.tools;
6791
- const i = tools.findIndex((t) => t.name === "Think");
6792
- if (model === false && i >= 0) tools.splice(i, 1);
6793
- else if (model !== false && i < 0) tools.push(this.thinkTool());
6666
+ /** Remove complete stage-direction parentheticals from the UNFORWARDED reflex text (STAGE_DIRECTION_RE).
6667
+ * Only the unforwarded region is touched — already-spoken audio can't be unsent, and splicing before
6668
+ * reflexForwarded would corrupt the forward offset. */
6669
+ scrubStageDirections() {
6670
+ if (this.reflexForwarded >= this.reflexBuf.length) return;
6671
+ const region = this.reflexBuf.slice(this.reflexForwarded);
6672
+ const scrubbed = region.replace(/\([^()]*\)/g, (s) => STAGE_DIRECTION_RE.test(s) ? "" : s);
6673
+ if (scrubbed !== region) this.reflexBuf = this.reflexBuf.slice(0, this.reflexForwarded) + scrubbed;
6794
6674
  }
6795
- /** User/programmatic spawn: the CLI's /act and /think commands. Returns the task id.
6796
- * `followUp` marks an automatic escalation/re-delegation (set by the integration turn) so the new
6797
- * task's own integration turn won't escalate again — capping auto-follow-ups to one hop. */
6798
- async dispatch(brief, tier = "act", label, followUp = false) {
6799
- if (tier === "think" && this.options.thinkModel === false) tier = "act";
6800
- if (followUp) this.autoEscalations++;
6801
- const id = `t${++this.seq}`;
6802
- const lbl = label ?? tier;
6803
- await this.options.onTaskStart?.(id, lbl);
6804
- this.spawnWorker(id, lbl, this.buildBrief(brief, tier), tier, brief, followUp);
6805
- this.notify("task_started", `task ${id} (${lbl}) started`, { id, brief, tier });
6806
- return id;
6675
+ /** Clear the per-turn guards. Called at the head of every voice turn (user send + re-voice flush). */
6676
+ resetTurn() {
6677
+ this.turnDispatched = false;
6678
+ this.spokeBeforeDispatch = false;
6679
+ this.turnBriefs.clear();
6680
+ this.spokeThisTurn = false;
6681
+ this.externalSpeech = false;
6682
+ this.heldThisTurn = false;
6683
+ this.reflexBuf = "";
6684
+ this.reflexForwarded = 0;
6685
+ this.fabricationCut = false;
6686
+ this.turnFollowUp = false;
6687
+ this.voice.options.toolChoice = void 0;
6807
6688
  }
6808
- actTool() {
6689
+ /** preToolUse guard on the reflex: once it has dispatched this turn, a dispatch is "said my piece,
6690
+ * now wait for the push" (CC's Task model). Block the temptations — TaskStatus polling and identical
6691
+ * re-dispatch — so the only remaining move is to voice a short ack and end. A genuinely NEW Act is
6692
+ * still allowed (parallel independent work). During a re-ack pass, block every tool. */
6693
+ dispatchGuard() {
6809
6694
  return {
6810
- name: "Act",
6811
- 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).',
6812
- parameters: {
6813
- type: "object",
6814
- required: ["brief"],
6815
- properties: {
6816
- brief: { type: "string", description: "full, self-contained instructions for the worker" },
6817
- label: { type: "string", description: "a short (2-4 word) label for the task" }
6695
+ preToolUse: (call) => {
6696
+ if (this.spec?.state === "pending" && !_DuplexAgent.SPEC_SAFE_TOOLS.has(call.name)) {
6697
+ log12.verbose(`speculation aborted: reflex called ${call.name} on unconfirmed input`);
6698
+ this.abortSpeculation();
6699
+ return { block: true, reason: "Speculative turn aborted." };
6818
6700
  }
6819
- },
6820
- run: async ({ brief, label }) => {
6821
- this.spokeBeforeDispatch = this.spokeThisTurn;
6822
- this.turnDispatched = true;
6823
- this.turnBriefs.add(String(brief ?? ""));
6824
- this.voice.options.toolChoice = "none";
6825
- const id = await this.dispatch(String(brief ?? ""), "act", label ? String(label) : void 0, this.turnFollowUp);
6826
- 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.`;
6701
+ if (this.nudging) return { block: true, reason: "Just say one short spoken acknowledgement \u2014 no tools this turn." };
6702
+ if (!this.turnDispatched) return;
6703
+ if (call.name === "TaskStatus")
6704
+ 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." };
6705
+ if ((call.name === "Act" || call.name === "Think") && this.turnBriefs.has(String(call.args?.brief ?? "")))
6706
+ return { block: true, reason: "You already dispatched this exact task \u2014 acknowledge briefly and end your turn." };
6827
6707
  }
6828
6708
  };
6829
6709
  }
6830
- thinkTool() {
6831
- return {
6832
- name: "Think",
6833
- 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.",
6834
- parameters: {
6835
- type: "object",
6836
- required: ["brief"],
6837
- properties: {
6838
- brief: { type: "string", description: "the question or problem to reason about deeply" },
6839
- label: { type: "string", description: "a short (2-4 word) label for the task" }
6840
- }
6841
- },
6842
- run: async ({ brief, label }) => {
6843
- this.spokeBeforeDispatch = this.spokeThisTurn;
6844
- this.turnDispatched = true;
6845
- this.turnBriefs.add(String(brief ?? ""));
6846
- this.voice.options.toolChoice = "none";
6847
- const id = await this.dispatch(String(brief ?? ""), "think", label ? String(label) : void 0, this.turnFollowUp);
6848
- 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.`;
6849
- }
6850
- };
6710
+ /** The host spoke on this turn's behalf OUTSIDE the reflex stream (e.g. the voice engine's adaptive
6711
+ * micro-ack). For a DISPATCHED turn that's a sufficient ack (don't stack a second one); for an
6712
+ * inline turn whose reply came back empty it is NOT — "One sec." followed by permanent silence is
6713
+ * still dead air, so silentTurn ignores external speech unless work was dispatched. */
6714
+ noteExternalSpeech() {
6715
+ this.externalSpeech = true;
6851
6716
  }
6852
- taskStatusTool() {
6853
- return {
6854
- name: "TaskStatus",
6855
- description: "Status of background tasks. Pass `id` for one task, or omit it to list all.",
6856
- parameters: { type: "object", properties: { id: { type: "string" } } },
6857
- run: async ({ id }) => {
6858
- const list = id ? [this.tasks.get(String(id))].filter(Boolean) : [...this.tasks.values()];
6859
- if (!list.length) return id ? `No task '${id}'.` : "No background tasks.";
6860
- return list.map((t) => `${t.id} (${t.label}): ${t.status}`).join("\n");
6861
- }
6862
- };
6717
+ /** True when the just-finished turn voiced NOTHING — dead air to repair. Two ways this happens:
6718
+ * (a) a dispatch with no spoken ack, and (b) an INLINE turn whose `final` channel came back empty —
6719
+ * gpt-oss harmony sometimes puts the whole reply in `analysis` (→ thinking_delta, suppressed in
6720
+ * voice) and emits an empty `final`, so no text_delta ever streams. Both ship silence; both repair.
6721
+ * Requires a host: without one there's no stream to detect speech on (and no one to speak to). */
6722
+ get silentTurn() {
6723
+ const ackedByHost = this.externalSpeech && this.turnDispatched;
6724
+ return !!this.options.host && !this.spokeThisTurn && !ackedByHost && !this.heldThisTurn;
6863
6725
  }
6864
- /** Sub-100ms read-only lookups the voice may do itself — everything else stays Act-only.
6865
- * fs-only (no shell; the engine is VFS-abstracted): time, git branch (.git/HEAD read), ls, file
6866
- * head. Output is hard-capped so a lookup can never bloat the skinny voice context. */
6867
- quickLookTool() {
6868
- const CAP2 = 2e3;
6869
- const kinds = [.../* @__PURE__ */ new Set(["time", "branch", "ls", "file", "capabilities", ...Object.keys(this.options.quickLook ?? {})])];
6870
- return {
6871
- name: "QuickLook",
6872
- description: `Instant read-only lookup \u2014 one of: ${kinds.join(", ")}. For trivial facts only; anything needing search, commands, or reasoning goes through Act.`,
6873
- parameters: {
6874
- type: "object",
6875
- required: ["what"],
6876
- properties: {
6877
- what: { type: "string", enum: kinds, description: "what to look up" },
6878
- path: { type: "string", description: "for ls/file: the path to look at" }
6879
- }
6880
- },
6881
- run: async ({ what, path }) => {
6882
- const fs = this.options.fs;
6883
- try {
6884
- const over = this.options.quickLook?.[String(what)];
6885
- if (over) return await over(path ? String(path) : void 0);
6886
- switch (String(what)) {
6887
- case "capabilities": {
6888
- const actTools = this.options.actOptions?.tools ?? [];
6889
- const names = actTools.map((t) => t.name);
6890
- const mcpServers = Object.keys(this.options.actOptions?.providerOptions?.mcpServers ?? {});
6891
- 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).` : "";
6892
- if (!names.length)
6893
- 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;
6894
- const hasFetch = names.some((n) => /WebFetch/i.test(n));
6895
- const hasBrowser = names.some((n) => /browser.*(navigate|click|page|type)/i.test(n));
6896
- const hasSearch = names.some((n) => /(^|_)WebSearch$|search/i.test(n) && !/WebFetch|browser/i.test(n));
6897
- const notes = [];
6898
- if (hasFetch) notes.push("WebFetch retrieves ONE specific URL you are given \u2014 it is not a search engine.");
6899
- 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.");
6900
- 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.');
6901
- const webNote = notes.length ? " NOTE: " + notes.join(" ") : "";
6902
- 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;
6903
- }
6904
- case "time":
6905
- return (/* @__PURE__ */ new Date()).toString();
6906
- case "branch": {
6907
- if (!fs) return "unavailable (no filesystem)";
6908
- const head = (await fs.readFile(".git/HEAD")).trim();
6909
- return head.startsWith("ref: refs/heads/") ? `branch: ${head.slice("ref: refs/heads/".length)}` : `detached HEAD at ${head.slice(0, 12)}`;
6910
- }
6911
- case "ls": {
6912
- if (!fs) return "unavailable (no filesystem)";
6913
- const p = String(path ?? ".");
6914
- try {
6915
- const names = await fs.readDir(p);
6916
- return names.slice(0, 50).join("\n") + (names.length > 50 ? `
6917
- \u2026 (+${names.length - 50} more)` : "");
6918
- } catch {
6919
- const names = await fs.readDir(".").catch(() => []);
6920
- return `'${p}' not found here \u2014 you are likely already inside it. Current directory listing:
6921
- ` + names.slice(0, 50).join("\n") + (names.length > 50 ? `
6922
- \u2026 (+${names.length - 50} more)` : "");
6923
- }
6924
- }
6925
- case "file": {
6926
- if (!fs) return "unavailable (no filesystem)";
6927
- if (!path) return "file lookup needs a path";
6928
- try {
6929
- const text = await fs.readFile(String(path));
6930
- return text.length > CAP2 ? text.slice(0, CAP2) + `
6931
- \u2026 (truncated \u2014 ${text.length} chars total; Act for the full file)` : text;
6932
- } catch {
6933
- const names = await fs.readDir(".").catch(() => []);
6934
- return `'${path}' not found. Current directory contains:
6935
- ` + names.slice(0, 50).join("\n");
6936
- }
6937
- }
6938
- default:
6939
- return `unknown lookup '${what}'`;
6940
- }
6941
- } catch (e) {
6942
- return `lookup failed: ${e?.message ?? e}`;
6943
- }
6944
- }
6945
- };
6726
+ /** A turn that voiced nothing is dead air. Re-prompt the reflex ONCE so the LLM itself voices a short
6727
+ * line (no template). If it STILL says nothing, fall back to a minimal line so silence never ships.
6728
+ * Wording adapts to whether work was dispatched (an ack) or the inline reply was simply lost. */
6729
+ async ackIfSilent(fallback) {
6730
+ const dispatched = this.turnDispatched;
6731
+ this.nudging = true;
6732
+ try {
6733
+ 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.");
6734
+ } catch (e) {
6735
+ log12.warn(`ack nudge failed: ${e instanceof Error ? e.message : e}`);
6736
+ } finally {
6737
+ this.nudging = false;
6738
+ }
6739
+ if (!this.spokeThisTurn) {
6740
+ const pool = fallback ? [fallback] : dispatched ? _DuplexAgent.FALLBACK_ACKS : _DuplexAgent.FALLBACK_RETRY;
6741
+ const fresh = pool.filter((p) => p !== this.lastFallback);
6742
+ const line = (fresh.length ? fresh : pool)[Math.floor(Math.random() * (fresh.length || pool.length))];
6743
+ this.lastFallback = line;
6744
+ this.emitHost({ kind: "text_delta", message: line });
6745
+ }
6946
6746
  }
6947
- answerTaskTool() {
6948
- return {
6949
- name: "AnswerTask",
6950
- 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.`,
6951
- parameters: {
6952
- type: "object",
6953
- required: ["id", "answer"],
6954
- properties: { id: { type: "string" }, answer: { type: "string", description: "the user's answer, verbatim or faithfully summarized" } }
6955
- },
6956
- run: async ({ id, answer }) => {
6957
- const ask = this.pendingAsks.get(String(id));
6958
- if (!ask) return `No pending question for '${id}' \u2014 it may have been answered already or timed out.`;
6959
- ask.resolve(String(answer ?? ""));
6960
- return `Answer relayed \u2014 task ${id} resumes.`;
6747
+ /** Dead-air fallback pools (see ackIfSilent). Both retry lines keep the 'say that again' phrase —
6748
+ * hosts/tests key on it. */
6749
+ static FALLBACK_ACKS = ["Okay, on it.", "On it.", "Alright, working on it."];
6750
+ static FALLBACK_RETRY = ["Sorry, could you say that again?", "Hm, I missed that \u2014 could you say that again?"];
6751
+ lastFallback = "";
6752
+ /** One user turn: the voice agent streams the reply (and may Act/Think). Serialized with re-voice turns.
6753
+ * If a speculative reflex call is pending and this content CONFIRMS it (the final matches the
6754
+ * speculated partial), the in-flight call is adopted as THE turn: its buffered output flushes to the
6755
+ * host NOW (this is the latency win) and streaming continues live. Any other content aborts the
6756
+ * speculation first (rolled back silently) and runs a normal turn behind it. */
6757
+ send(content) {
6758
+ if (typeof content === "string" && isTrivialBarge(content) && this.hasParkedDelivery()) {
6759
+ if (this.spec) this.abortSpeculation();
6760
+ return this.enqueue(async () => {
6761
+ this.resetTurn();
6762
+ if (!this.redeliverParked()) this.awaitTrivialRedeliver = true;
6763
+ return { text: "", steps: 0, finishReason: "stop", messages: [] };
6764
+ });
6765
+ }
6766
+ const spec = this.spec;
6767
+ if (spec?.state === "pending") {
6768
+ if (typeof content === "string" && speculationConfirms(spec.text, content)) {
6769
+ spec.state = "confirmed";
6770
+ spec.finalText = content;
6771
+ for (const ev of spec.buf.splice(0)) this.options.host?.notify?.(ev);
6772
+ spec.decide("confirm");
6773
+ this.notify("diag", "speculation_confirmed", { text: spec.text.slice(0, 80) });
6774
+ return spec.done;
6961
6775
  }
6962
- };
6776
+ this.abortSpeculation();
6777
+ }
6778
+ return this.enqueue(async () => {
6779
+ await this.initMemory();
6780
+ this.resetTurn();
6781
+ this.awaitTrivialRedeliver = false;
6782
+ this.parkedRedeliver = [];
6783
+ this.suppressParkedResume = true;
6784
+ const res = await this.voice.send(content);
6785
+ this.flushHeldReflexTail();
6786
+ if (this.silentTurn) await this.ackIfSilent();
6787
+ return res;
6788
+ });
6963
6789
  }
6964
- holdTool() {
6965
- return {
6966
- name: "Hold",
6967
- 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.',
6968
- parameters: {
6969
- type: "object",
6970
- properties: {
6971
- filler: { type: "string", description: 'optional short filler to speak ("mhm", "go on", "mm-hm")' }
6790
+ /** Start a HELD speculative reflex turn on a stable partial (VoiceEngine.onSpeculate). Its spoken
6791
+ * output buffers in emitHost; send() later confirms (flush + adopt) or aborts it. The turn holds the
6792
+ * voice mutex until that decision (bounded by a safety timeout), so no other turn can interleave
6793
+ * into the transcript between the speculative messages and their rollback. No-op if a speculation
6794
+ * is already in flight. */
6795
+ speculate(text) {
6796
+ if (!text.trim() || this.spec) return;
6797
+ let decide;
6798
+ const decision = new Promise((r) => {
6799
+ decide = r;
6800
+ });
6801
+ const spec = {
6802
+ text,
6803
+ state: "pending",
6804
+ buf: [],
6805
+ ctl: new AbortController(),
6806
+ decide,
6807
+ decision,
6808
+ done: void 0
6809
+ };
6810
+ this.spec = spec;
6811
+ spec.done = this.enqueue(async () => {
6812
+ const empty = { text: "", steps: 0, finishReason: "aborted", messages: this.voice.transcript };
6813
+ if (spec.state === "aborted") {
6814
+ this.speculativeAbortedCalls++;
6815
+ if (this.spec === spec) this.spec = void 0;
6816
+ return empty;
6817
+ }
6818
+ await this.initMemory();
6819
+ this.resetTurn();
6820
+ const base = this.voice.transcript.length;
6821
+ const prevSignal = this.voice.options.signal;
6822
+ this.voice.options.signal = spec.ctl.signal;
6823
+ let res;
6824
+ try {
6825
+ res = await this.voice.send(spec.text);
6826
+ } catch (e) {
6827
+ log12.warn(`speculative turn failed: ${e instanceof Error ? e.message : e}`);
6828
+ } finally {
6829
+ this.voice.options.signal = prevSignal;
6830
+ }
6831
+ const timer = setTimeout(() => {
6832
+ spec.state = spec.state === "pending" ? "aborted" : spec.state;
6833
+ spec.decide("abort");
6834
+ }, 1e4);
6835
+ timer.unref?.();
6836
+ const d = await spec.decision;
6837
+ clearTimeout(timer);
6838
+ if (d === "abort") {
6839
+ if (this.voice.transcript.length > base) this.voice.transcript.length = base;
6840
+ this.speculativeAbortedCalls++;
6841
+ log12.verbose(`speculation aborted (${this.speculativeAbortedCalls} total): "${spec.text.slice(0, 50)}"`);
6842
+ if (this.spec === spec) this.spec = void 0;
6843
+ return res ?? empty;
6844
+ }
6845
+ for (let i = base; i < this.voice.transcript.length; i++) {
6846
+ const m = this.voice.transcript[i];
6847
+ if (m.role === "user" && contentText(m.content) === spec.text) {
6848
+ m.content = spec.finalText;
6849
+ break;
6972
6850
  }
6973
- },
6974
- run: async ({ filler }) => {
6975
- this.heldThisTurn = true;
6976
- this.notify("hold_filler", filler ? String(filler) : "");
6977
- return "Holding \u2014 listening for the rest of the user's thought. Do not respond further this turn.";
6978
6851
  }
6979
- };
6852
+ this.spec = void 0;
6853
+ this.flushHeldReflexTail();
6854
+ if (this.silentTurn) await this.ackIfSilent();
6855
+ return res ?? empty;
6856
+ });
6980
6857
  }
6981
- cancelTaskTool() {
6982
- return {
6983
- name: "CancelTask",
6984
- description: "Cancel a running background task by id.",
6985
- parameters: { type: "object", required: ["id"], properties: { id: { type: "string" } } },
6986
- run: async ({ id }) => this.cancelTask(String(id))
6987
- };
6858
+ /** Abort a pending speculation (idempotent): kill the in-flight call, drop its buffered output.
6859
+ * Called on divergence (send), a stale partial (VoiceEngine.onSpeculateAbort), a side-effect tool
6860
+ * attempt (dispatchGuard), or host paths that will never dispatch a final (commands, voice-off). */
6861
+ abortSpeculation() {
6862
+ const spec = this.spec;
6863
+ if (spec?.state !== "pending") return;
6864
+ spec.state = "aborted";
6865
+ spec.buf.length = 0;
6866
+ spec.ctl.abort();
6867
+ spec.decide("abort");
6868
+ this.notify("diag", "speculation_aborted", { text: spec.text.slice(0, 80) });
6988
6869
  }
6989
- };
6990
-
6991
- // src/mcp.ts
6992
- function toResult(result) {
6993
- if (result == null) return { text: "" };
6994
- if (typeof result === "string") return { text: result };
6995
- const content = result.content;
6996
- if (Array.isArray(content)) {
6997
- const texts = [];
6998
- const images = [];
6999
- for (const c of content) {
7000
- if (c?.type === "image" && typeof c.data === "string" && c.mimeType) {
7001
- images.push({ mimeType: c.mimeType, data: c.data });
7002
- } else if (typeof c?.text === "string") {
7003
- texts.push(c.text);
7004
- } else {
7005
- texts.push(JSON.stringify(c));
6870
+ /** Cancel a running background task — shared by the CancelTask tool and the CLI /tasks picker. */
6871
+ cancelTask(id) {
6872
+ const rec = this.tasks.get(id);
6873
+ if (!rec) return `No task '${id}'.`;
6874
+ if (rec.status !== "running") return `Task ${rec.id} is already ${rec.status}.`;
6875
+ rec.status = "cancelled";
6876
+ rec.controller.abort();
6877
+ return `Task ${rec.id} (${rec.label}) cancelled.`;
6878
+ }
6879
+ /** Barge-in: the user took the floor while task(s) were running. Suppress those tasks' remaining SPOKEN
6880
+ * delivery so a superseded topic never talks over the new one (the debt-after-jokes regression). The
6881
+ * tasks keep running and still fold their result into the transcript — recoverable, just not spoken.
6882
+ * Returns the parked ids (for logging). Does NOT cancel: that's a deliberate reflex/user action. */
6883
+ parkInFlightDeliveries() {
6884
+ this.suppressParkedResume = false;
6885
+ const parked = [];
6886
+ for (const rec of this.tasks.values())
6887
+ if (rec.status === "running" && !rec.deliveryParked) {
6888
+ rec.deliveryParked = true;
6889
+ parked.push(rec.id);
7006
6890
  }
7007
- }
7008
- const text = texts.join("\n");
7009
- if (text || images.length) return { text, ...images.length ? { images } : {} };
6891
+ return parked;
7010
6892
  }
7011
- return { text: JSON.stringify(result) };
7012
- }
7013
- function mcpToolToAgentTool(spec, callTool, prefix = "mcp__") {
7014
- return {
7015
- name: `${prefix}${spec.name}`,
7016
- description: spec.description ?? `MCP tool ${spec.name}`,
7017
- parameters: spec.inputSchema ?? { type: "object", properties: {} },
7018
- async run(args, _ctx) {
7019
- const r = toResult(await callTool(spec.name, args ?? {}));
7020
- return r.images?.length ? r : r.text;
6893
+ /** True while there is a parked delivery to potentially resume: either one already settled (queued) or
6894
+ * one still running that was parked by a barge. */
6895
+ hasParkedDelivery() {
6896
+ return this.parkedRedeliver.length > 0 || [...this.tasks.values()].some((t) => t.status === "running" && t.deliveryParked);
6897
+ }
6898
+ /** Speak any settled-and-queued parked delivery now (trivial-barge resume). Returns false if nothing was
6899
+ * queued yet (the caller then arms awaitTrivialRedeliver so the task resumes the instant it settles). */
6900
+ redeliverParked() {
6901
+ if (!this.parkedRedeliver.length) return false;
6902
+ const text = this.parkedRedeliver.splice(0).join(" ").trim();
6903
+ if (text) {
6904
+ this.options.host?.notify?.({ kind: "speak_utterance", message: text });
6905
+ this.notify("diag", "parked_redelivered", { chars: text.length });
7021
6906
  }
7022
- };
7023
- }
7024
- function mcpToolsToAgentTools(specs, callTool, prefix = "mcp__", filter) {
7025
- return (filter ? specs.filter(filter) : specs).map((s) => mcpToolToAgentTool(s, callTool, prefix));
7026
- }
7027
- function describeSpec(s) {
7028
- const schema = s.inputSchema ? `
7029
- args: ${JSON.stringify(s.inputSchema)}` : "";
7030
- return `${s.name} \u2014 ${s.description ?? "(no description)"}${schema}`;
7031
- }
7032
- function makeMcpToolSearch(specs, callTool, options = {}) {
7033
- const maxResults = options.maxResults ?? 10;
7034
- const byName = new Map(specs.map((s) => [s.name, s]));
7035
- const catalogLine = `${specs.length} MCP tool(s) available \u2014 search by keyword, then call by exact name.`;
7036
- const searchTool = {
7037
- name: "ToolSearch",
7038
- description: `Search the available MCP tools by keyword (${catalogLine}). Returns matching tool names + their argument schemas; call one with \`McpCall\`.`,
7039
- parameters: { type: "object", required: ["query"], properties: { query: { type: "string", description: "keywords to match against tool name + description" } } },
7040
- async run({ query }) {
7041
- const q2 = String(query ?? "").trim();
7042
- if (!q2) return catalogLine;
7043
- const { kept } = topByRelevance(specs, q2, (s) => `${s.name} ${s.description ?? ""}`, maxResults);
7044
- if (!kept.length) return `(no MCP tool matches "${q2}" \u2014 try broader keywords)`;
7045
- return kept.map(describeSpec).join("\n");
6907
+ return true;
6908
+ }
6909
+ /** Resolve when all queued voice turns AND all in-flight worker tasks have settled (tests, graceful shutdown). */
6910
+ async idle() {
6911
+ while (true) {
6912
+ const q2 = this.queue;
6913
+ await q2.catch(() => {
6914
+ });
6915
+ await Promise.all([...this.tasks.values()].map((t) => t.promise));
6916
+ if (this.queue === q2 && ![...this.tasks.values()].some((t) => t.status === "running")) return;
7046
6917
  }
7047
- };
7048
- const callMcpTool = {
7049
- name: "McpCall",
7050
- description: "Call an MCP tool discovered via `ToolSearch`, by its exact name. Pass its arguments as `args`.",
7051
- parameters: {
7052
- type: "object",
7053
- required: ["name"],
7054
- properties: {
7055
- name: { type: "string", description: "exact tool name from ToolSearch" },
7056
- args: { type: "object", description: "arguments object for the tool (per its schema)" }
6918
+ }
6919
+ /** Promise-chain mutex: turns run strictly one at a time; a failed turn doesn't poison the chain. */
6920
+ enqueue(fn) {
6921
+ const run = this.queue.then(fn, fn);
6922
+ this.queue = run.then(() => {
6923
+ }, () => {
6924
+ });
6925
+ return run;
6926
+ }
6927
+ notify(kind, message, data) {
6928
+ this.emitHost({ kind, message, data });
6929
+ }
6930
+ /** Host-boundary emit for the reflex's spoken channel: during a PENDING speculation, text_delta and
6931
+ * hold_filler are BUFFERED (nothing may reach TTS on unconfirmed input); confirm flushes them in
6932
+ * order, abort drops them silently. Everything else (task_* lifecycle, worker speak_utterance —
6933
+ * which bypasses this via host.notify directly) passes through untouched. */
6934
+ emitHost(ev) {
6935
+ const spec = this.spec;
6936
+ if (spec && (ev.kind === "text_delta" || ev.kind === "hold_filler")) {
6937
+ if (spec.state === "pending") {
6938
+ spec.buf.push(ev);
6939
+ return;
7057
6940
  }
7058
- },
7059
- async run({ name, args }) {
7060
- const n = String(name ?? "");
7061
- if (!byName.has(n)) return `Error: unknown MCP tool '${n}'. Use ToolSearch to find valid names.`;
7062
- const r = toResult(await callTool(n, args ?? {}));
7063
- return r.images?.length ? r : r.text;
7064
- }
7065
- };
7066
- return [searchTool, callMcpTool];
7067
- }
7068
- function buildMcpCatalog(servers) {
7069
- const specs = [];
7070
- const routes = /* @__PURE__ */ new Map();
7071
- for (const m of servers) {
7072
- for (const s of m.specs) {
7073
- const base = `mcp__${m.name}__${s.name}`.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 128);
7074
- let display = base;
7075
- for (let i = 2; routes.has(display); i++) display = `${base.slice(0, 128 - String(i).length - 1)}_${i}`;
7076
- specs.push({ name: display, description: s.description, inputSchema: s.inputSchema });
7077
- routes.set(display, { server: m.name, rawName: s.name });
6941
+ if (spec.state === "aborted") return;
7078
6942
  }
6943
+ this.options.host?.notify?.(ev);
7079
6944
  }
7080
- return { specs, routes };
7081
- }
7082
- function searchOverCatalog(servers, specs, routes, resolve4, options) {
7083
- const tools = specs.length ? makeMcpToolSearch(specs, (name, args) => {
7084
- const r = routes.get(name);
7085
- if (!r) throw new Error(`unknown MCP tool '${name}' \u2014 use ToolSearch to find valid names`);
7086
- return resolve4(r.server, r.rawName, args ?? {});
7087
- }, options) : [];
7088
- return { tools, serverNames: servers, toolCount: specs.length };
7089
- }
7090
- function makeMcpToolSearchFromMounted(mounted, options) {
7091
- const { specs, routes } = buildMcpCatalog(mounted);
7092
- const byName = new Map(mounted.map((m) => [m.name, m]));
7093
- return searchOverCatalog(mounted.map((m) => m.name), specs, routes, (server, rawName, args) => byName.get(server).client.callTool(rawName, args), options);
7094
- }
7095
-
7096
- // src/index.ts
7097
- init_logging();
6945
+ /** Queue a `[task …]` event for re-voicing. Events arriving while the voice is busy coalesce into ONE turn.
6946
+ * `nonClean` (out-of-band boolean, set by the caller that KNOWS this event integrates a NON-CLEAN outcome)
6947
+ * marks the coalesced flush as a non-clean integration turn — turn-eligibility, never inferred from event
6948
+ * text and never keyed on a (re-authored) brief string. Any dispatch in such a turn is a follow-up. */
6949
+ queueRevoice(event, nonClean = false) {
6950
+ this.pendingEvents.push(event);
6951
+ if (nonClean) this.pendingNonClean = true;
6952
+ if (this.flushQueued) return;
6953
+ this.flushQueued = true;
6954
+ void this.enqueue(async () => {
6955
+ this.flushQueued = false;
6956
+ const events = this.pendingEvents.splice(0);
6957
+ const nonCleanTurn = this.pendingNonClean;
6958
+ this.pendingNonClean = false;
6959
+ if (!events.length) return;
6960
+ const failed = events.find((e) => /^\[task\b[^\]\n]*\bfailed\b/i.test(e));
6961
+ this.resetTurn();
6962
+ this.turnFollowUp = nonCleanTurn;
6963
+ await this.voice.send(events.join("\n"));
6964
+ this.flushHeldReflexTail();
6965
+ if (this.silentTurn) await this.ackIfSilent(failed ? "Sorry, that didn't work \u2014 the task failed." : void 0);
6966
+ this.notify("revoice_done", "");
6967
+ });
6968
+ }
6969
+ /** The worker's brief: the Act/Think args + a STATIC text snapshot of the recent conversation.
6970
+ * Act briefs get a self-verify footer — the worker's report is trusted without review, so it
6971
+ * must check its own work before reporting (nearly free under prompt caching; measured honest:
6972
+ * it does NOT fix one-shot logic bugs — see mind/10). Think tasks are pure reasoning — no footer. */
6973
+ buildBrief(brief, tier = "act", deliver = true) {
6974
+ 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");
6975
+ 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." : "";
6976
+ const deliverContract = deliver ? `
7098
6977
 
7099
- // src/voice/soniox.ts
7100
- init_logging();
6978
+ ## DELIVER (spoken delivery)
6979
+ 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." : "") : "";
6980
+ return `${nowLine()}.
7101
6981
 
7102
- // src/voice/types.ts
7103
- var STT_SAMPLE_RATE = 16e3;
7104
- var TTS_SAMPLE_RATE = 44100;
7105
- async function resolveAuth(auth) {
7106
- return typeof auth === "function" ? await auth() : auth;
7107
- }
6982
+ ` + (recent ? `${brief}
7108
6983
 
7109
- // src/voice/soniox.ts
7110
- var log11 = forComponent("SonioxSTT");
7111
- var now = () => performance.now();
7112
- var SonioxSTTOptions = class {
7113
- auth = "";
7114
- source;
7115
- model = "stt-rt-preview";
7116
- languageHints = ["en"];
7117
- /** Client-side endpoint: finalized text + no new tokens for this long = utterance (don't wait for
7118
- * Soniox's semantic <end>, which adds 0.5-1.5s — the difference between ping-pong and lag). */
7119
- silenceEndpointMs = 500;
7120
- /** No-audio watchdog: if the mic source stops delivering chunks for this long, capture is dead →
7121
- * fire onFatal + stop (else Soniox idle-timeouts and reconnect-loops forever). 0 = disable. */
7122
- noAudioTimeoutMs = 1e4;
7123
- };
7124
- var SonioxSTT = class {
7125
- options;
7126
- ws;
7127
- stopped = false;
7128
- sourceStarted = false;
7129
- onPartial = () => {
7130
- };
7131
- onUtterance = () => {
7132
- };
7133
- /** mic energy (RMS) per chunk — drives the energy-based heuristic barge-in tier */
7134
- onLevel = () => {
7135
- };
7136
- /** Unrecoverable: the mic source stopped delivering audio (Soniox starves → idle-timeout reconnect
7137
- * loop). The host tears voice down instead of spinning forever. */
7138
- onFatal = () => {
7139
- };
7140
- /** Diagnostic tap (provider errors, ws reconnects, no-audio watchdog). Fire-and-forget: a throwing
7141
- * handler disables itself — never affects transcription. Wired by VoiceIO / the lab bridge. */
7142
- onDiag = () => {
7143
- };
7144
- diagOn = true;
7145
- diag(kind, fields) {
7146
- if (!this.diagOn) return;
7147
- try {
7148
- this.onDiag({ t: now(), kind, ...fields });
7149
- } catch (e) {
7150
- this.diagOn = false;
7151
- log11.debug(`onDiag threw \u2014 STT diagnostics disabled: ${e instanceof Error ? e.message : e}`);
7152
- }
7153
- }
7154
- lastChunkAt = 0;
7155
- // timestamp of the most recent mic chunk (0 = none yet)
7156
- startedChunksAt = 0;
7157
- // when capture started (grace before the first chunk)
7158
- noAudioTimer = null;
7159
- finalText = "";
7160
- partialText = "";
7161
- lastChangeAt = 0;
7162
- lastCombined = "";
7163
- endpointTimer = null;
7164
- firstTokenAt = 0;
7165
- // first speech token in current utterance
7166
- constructor(options) {
7167
- this.options = { ...new SonioxSTTOptions(), ...options };
7168
- }
7169
- get usingAec() {
7170
- return this.options.source?.aec ?? false;
6984
+ ## Recent conversation (for context)
6985
+ ${recent}` : brief) + verify + deliverContract;
7171
6986
  }
7172
- async connectWs() {
7173
- const apiKey = await resolveAuth(this.options.auth);
7174
- this.ws = new WebSocket("wss://stt-rt.soniox.com/transcribe-websocket");
7175
- await new Promise((res, rej) => {
7176
- this.ws.onopen = () => res();
7177
- this.ws.onerror = (e) => rej(new Error(`soniox ws: ${e.message || "connect failed"}`));
7178
- });
7179
- this.ws.send(
7180
- JSON.stringify({
7181
- api_key: apiKey,
7182
- model: this.options.model,
7183
- audio_format: "pcm_s16le",
7184
- sample_rate: STT_SAMPLE_RATE,
7185
- num_channels: 1,
7186
- language_hints: this.options.languageHints,
7187
- enable_endpoint_detection: true
7188
- })
7189
- );
7190
- this.ws.onmessage = (ev) => this.handle(JSON.parse(String(ev.data)));
7191
- this.ws.onclose = (ev) => {
7192
- if (this.stopped) return;
7193
- log11.warn(`soniox ws closed (${ev.code} ${ev.reason || ""}) \u2014 reconnecting`);
7194
- this.diag("stt_ws_closed", { code: ev.code, reason: String(ev.reason || ""), reconnecting: true });
7195
- this.reset();
7196
- this.connectWs().catch((e) => {
7197
- log11.error(`soniox reconnect failed: ${e.message}`);
7198
- this.diag("stt_reconnect_failed", { message: e.message });
7199
- });
6987
+ /** Spawn a detached worker for task `id`; its settlement notifies + enqueues the re-voice turn. */
6988
+ spawnWorker(id, label, briefText, tier, brief, followUp) {
6989
+ const o = this.options;
6990
+ const tierOpts = tier === "think" ? o.thinkOptions : o.actOptions;
6991
+ const tierModel = tier === "think" ? o.thinkModel : o.actModel;
6992
+ const controller = new AbortController();
6993
+ const base = tierOpts?.hooks ?? o.actOptions?.hooks;
6994
+ const report = o.progressUpdates ? this.progressReporter(id) : void 0;
6995
+ const tail = [];
6996
+ const pushTail = (line) => {
6997
+ tail.push(line.slice(0, 200));
6998
+ if (tail.length > 120) tail.splice(0, tail.length - 120);
6999
+ };
7000
+ const hooks = {
7001
+ ...base,
7002
+ preToolUse: async (call, meta) => {
7003
+ const d = await base?.preToolUse?.(call, meta);
7004
+ pushTail(`\u2699 ${describeCall(call)}`);
7005
+ report?.pre(call);
7006
+ return d;
7007
+ },
7008
+ postToolUse: async (call, result, meta) => {
7009
+ await base?.postToolUse?.(call, result, meta);
7010
+ const last = result?.trim().split("\n").filter(Boolean).pop();
7011
+ if (last) pushTail(` \u21B3 ${last}`);
7012
+ report?.post(call);
7013
+ },
7014
+ onToolOutput: (call, chunk, meta) => {
7015
+ base?.onToolOutput?.(call, chunk, meta);
7016
+ report?.output(chunk);
7017
+ }
7018
+ };
7019
+ const relayAsk = async (q2) => {
7020
+ const opts = q2.options?.length ? ` Options: ${q2.options.map((x) => x.label).join(", ")}.` : "";
7021
+ const a = await this.parkQuestion(id, `${q2.question}${opts}`);
7022
+ return a || "(no answer from the user \u2014 use your best judgment and note the assumption)";
7023
+ };
7024
+ const splitter = new SpokenSplitter();
7025
+ const speak = (seg) => {
7026
+ if (!seg) return;
7027
+ const r = this.tasks.get(id);
7028
+ if (r) r.spokenText = (r.spokenText ? r.spokenText + " " : "") + seg;
7029
+ if (!r?.deliveryParked) o.host?.notify?.({ kind: "speak_utterance", message: seg });
7030
+ };
7031
+ const coalescer = new SentenceCoalescer();
7032
+ const feedSpoken = (s) => {
7033
+ const ready = coalescer.feed(s);
7034
+ if (ready) speak(ready);
7035
+ };
7036
+ const flushSpoken = () => speak(coalescer.flush());
7037
+ const askBridge = o.askRelay ? { ask: relayAsk } : o.host?.ask ? { ask: (q2) => o.host.ask(q2) } : {};
7038
+ const workerHost = {
7039
+ ...askBridge,
7040
+ notify: (ev) => {
7041
+ if (ev?.kind === "text_delta" && typeof ev.message === "string") {
7042
+ const { spoken, detail } = splitter.feed(ev.message);
7043
+ feedSpoken(spoken);
7044
+ if (detail.trim()) pushTail(detail.trim());
7045
+ return;
7046
+ }
7047
+ }
7048
+ };
7049
+ const agentOpts = {
7050
+ ai: o.ai,
7051
+ fs: o.fs,
7052
+ model: tierModel,
7053
+ ...tier === "think" ? { reasoning: tierOpts?.reasoning ?? "high" } : {},
7054
+ ...tierOpts,
7055
+ // Recompute providerOptions for THIS worker's model (after tierOpts so it wins over any inherited
7056
+ // main-template value) — prevents cursor-only cwd/cursorSession leaking onto an anthropic worker.
7057
+ providerOptions: o.providerOptionsFor?.(tierModel),
7058
+ stream: true,
7059
+ // worker streams text_delta so the splitter can extract <spoken> live (after tierOpts: never overridden off)
7060
+ host: workerHost,
7061
+ // carries BOTH ask AND the <spoken>-splitting notify
7062
+ ...hooks ? { hooks } : {},
7063
+ signal: controller.signal
7064
+ // shared with the checker so a cancel tears down both
7200
7065
  };
7066
+ const promise = new Agent(agentOpts).run(briefText).then((res) => {
7067
+ const { spoken, detail } = splitter.flush();
7068
+ feedSpoken(spoken);
7069
+ if (detail.trim()) pushTail(detail.trim());
7070
+ flushSpoken();
7071
+ return res;
7072
+ }).then((res) => this.maybeVerify(id, brief, res, tier, agentOpts, askBridge)).then((res) => this.onWorkerSettled(id, res)).catch((err2) => this.onWorkerFailed(id, err2));
7073
+ this.tasks.set(id, { id, label, status: "running", controller, promise, tail, brief, followUp, splitter });
7074
+ if (this.tasks.size > this.options.maxTaskRecords)
7075
+ for (const [tid, rec] of this.tasks) {
7076
+ if (this.tasks.size <= this.options.maxTaskRecords) break;
7077
+ if (rec.status !== "running") this.tasks.delete(tid);
7078
+ }
7201
7079
  }
7202
- async start() {
7203
- await this.connectWs();
7204
- if (this.sourceStarted) return;
7205
- this.sourceStarted = true;
7206
- this.endpointTimer = setInterval(() => {
7207
- const combined = (this.finalText + this.partialText).trim();
7208
- if (!combined || now() - this.lastChangeAt < this.options.silenceEndpointMs) return;
7209
- if (this.firstTokenAt) log11.debug(`stt: ${Math.round(now() - this.firstTokenAt)}ms first-token\u2192silence-endpoint, "${combined.slice(0, 60)}"`);
7210
- this.reset();
7211
- this.onUtterance(combined, now());
7212
- }, 120);
7213
- this.endpointTimer.unref?.();
7214
- this.startedChunksAt = now();
7215
- const noAudioMs = this.options.noAudioTimeoutMs;
7216
- if (noAudioMs > 0) {
7217
- this.noAudioTimer = setInterval(() => {
7218
- if (this.stopped) return;
7219
- const ref = this.lastChunkAt || this.startedChunksAt;
7220
- if (now() - ref > noAudioMs) {
7221
- log11.error(`stt: no mic audio for >${Math.round(noAudioMs / 1e3)}s \u2014 capture device stopped delivering`);
7222
- this.diag("stt_watchdog_fatal", { noAudioMs });
7223
- this.onFatal("microphone stopped delivering audio (try a different input device, e.g. AirPods, or check System Settings \u2192 Sound \u2192 Input)");
7224
- this.stop();
7225
- }
7226
- }, Math.max(250, Math.min(2e3, noAudioMs / 4)));
7227
- this.noAudioTimer.unref?.();
7080
+ /** Fresh-context check of a successful Act task: a NEW agent (same model/fs/tools, but NO shared
7081
+ * conversation context) re-reads the file state against the brief and fixes any gap. The fix lands
7082
+ * on the shared fs automatically (workers write fs directly, no overlay), so grading sees the
7083
+ * corrected state. Bounded to ONE pass. Off unless `verifyActTasks`; never runs for think/failed/
7084
+ * cancelled tasks. Usage is merged so /cost reflects the real (worker + checker) spend. */
7085
+ async maybeVerify(id, brief, res, tier, agentOpts, askBridge) {
7086
+ if (!this.options.verifyActTasks || tier !== "act" || res.finishReason !== "stop") return res;
7087
+ if (this.tasks.get(id)?.status === "cancelled") return res;
7088
+ const { stream: _stream, host: _host, ...restOpts } = agentOpts;
7089
+ const checkerOpts = {
7090
+ ...restOpts,
7091
+ ...askBridge.ask ? { host: { ask: askBridge.ask } } : {}
7092
+ };
7093
+ const checkBrief = `${this.buildBrief(brief, tier, false)}
7094
+
7095
+ ## VERIFY MODE
7096
+ 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".`;
7097
+ this.notify("task_verify", `task ${id}: verifying`, { id });
7098
+ const cres = await new Agent(checkerOpts).run(checkBrief);
7099
+ if (cres.finishReason !== "stop") {
7100
+ log12.warn(`task ${id}: verify inconclusive (${cres.finishReason})`);
7101
+ this.notify("task_verify", `task ${id}: verify inconclusive (${cres.finishReason})`, { id, finishReason: cres.finishReason });
7228
7102
  }
7229
- await this.options.source.start((chunk) => {
7230
- this.lastChunkAt = now();
7231
- let sum = 0;
7232
- const view = new DataView(chunk.buffer, chunk.byteOffset, chunk.byteLength);
7233
- for (let i = 0; i + 1 < chunk.byteLength; i += 2) {
7234
- const v = view.getInt16(i, true);
7235
- sum += v * v;
7103
+ const sum = (a = 0, b = 0) => a + b;
7104
+ return {
7105
+ ...res,
7106
+ steps: res.steps + cres.steps,
7107
+ // Merge the checker's messages so downstream tool-call/step accounting includes BOTH agents
7108
+ // (else a verified task's toolCalls would undercount vs its steps/usage).
7109
+ messages: [...res.messages, ...cres.messages],
7110
+ usageEstimated: res.usageEstimated || cres.usageEstimated,
7111
+ usage: res.usage && cres.usage ? {
7112
+ promptTokens: sum(res.usage.promptTokens, cres.usage.promptTokens),
7113
+ completionTokens: sum(res.usage.completionTokens, cres.usage.completionTokens),
7114
+ totalTokens: sum(res.usage.totalTokens, cres.usage.totalTokens),
7115
+ cacheCreationTokens: sum(res.usage.cacheCreationTokens, cres.usage.cacheCreationTokens),
7116
+ cacheReadTokens: sum(res.usage.cacheReadTokens, cres.usage.cacheReadTokens)
7117
+ } : res.usage ?? cres.usage
7118
+ };
7119
+ }
7120
+ /** Throttled per-task progress: worker tool calls → at most one progress re-voice per interval.
7121
+ * Two sources, one throttle: completed steps (post) and a heartbeat for a SINGLE long tool call
7122
+ * (pre records the in-flight call; a self-cleaning timer narrates "still inside Bash — 70s").
7123
+ * Completion supersedes: nothing is emitted once the task has settled. */
7124
+ progressReporter(id) {
7125
+ let lastAt = Date.now();
7126
+ let steps = 0;
7127
+ let inflight = null;
7128
+ const due = () => {
7129
+ if (this.pendingAsks.size) return void 0;
7130
+ const rec = this.tasks.get(id);
7131
+ return rec && rec.status === "running" && Date.now() - lastAt >= this.options.progressIntervalMs ? rec : void 0;
7132
+ };
7133
+ const emit = (rec, line, call) => {
7134
+ lastAt = Date.now();
7135
+ this.notify("task_progress", `task ${id} (${rec.label}): ${line}`, { id, steps, call: call.name });
7136
+ this.queueRevoice(`[task ${id} progress] ${line}`);
7137
+ };
7138
+ const timer = setInterval(() => {
7139
+ const rec = this.tasks.get(id);
7140
+ if (!rec || rec.status !== "running") return clearInterval(timer);
7141
+ if (!inflight || !due()) return;
7142
+ const last = inflight.tail.trim().split("\n").filter(Boolean).pop()?.slice(-80);
7143
+ 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);
7144
+ }, Math.max(this.options.progressIntervalMs, 250));
7145
+ timer.unref?.();
7146
+ return {
7147
+ pre: (call) => {
7148
+ inflight = { call, at: Date.now(), tail: "" };
7149
+ },
7150
+ output: (chunk) => {
7151
+ if (inflight) inflight.tail = (inflight.tail + chunk).slice(-500);
7152
+ },
7153
+ // digest only — NEVER re-voices directly
7154
+ post: (call) => {
7155
+ steps++;
7156
+ inflight = null;
7157
+ const rec = due();
7158
+ if (rec) emit(rec, `still running \u2014 ${steps} steps so far, now: ${describeCall(call)}`, call);
7236
7159
  }
7237
- this.onLevel(Math.sqrt(sum / (chunk.byteLength / 2)));
7238
- if (this.ws.readyState === WebSocket.OPEN) this.ws.send(chunk);
7160
+ };
7161
+ }
7162
+ /** Park a question under `askId` (a task id, or any unique key for permission asks): re-voices
7163
+ * '[task <id> asks] …' and resolves with the user's answer via AnswerTask — or '' on timeout/
7164
+ * task settle (callers map '' to deny / best-judgment). Workers never block forever. */
7165
+ parkQuestion(askId, question) {
7166
+ return new Promise((resolve4) => {
7167
+ let settled = false;
7168
+ const finish = (answer) => {
7169
+ if (settled) return;
7170
+ settled = true;
7171
+ clearTimeout(timer);
7172
+ this.pendingAsks.delete(askId);
7173
+ resolve4(answer);
7174
+ };
7175
+ const timer = setTimeout(() => {
7176
+ this.notify("task_ask_timeout", `task ${askId}: question timed out \u2014 proceeding without an answer`);
7177
+ finish("");
7178
+ }, this.options.askTimeoutMs);
7179
+ this.pendingAsks.set(askId, { question, resolve: finish });
7180
+ this.notify("task_ask", `task ${askId} asks: ${question}`, { id: askId, question });
7181
+ this.queueRevoice(`[task ${askId} asks] ${question}
7182
+ (Relay this to the user in your own words. When they answer, call AnswerTask with id "${askId}" and their answer.)`);
7239
7183
  });
7240
7184
  }
7241
- handle(m) {
7242
- if (m.error_message) {
7243
- this.diag("stt_error", { message: String(m.error_message), code: m.error_code });
7244
- return log11.error(`soniox: ${m.error_message}`);
7185
+ /** Resolve any question a settling/cancelled task left parked (its answer can no longer matter). */
7186
+ dropAsk(id) {
7187
+ this.pendingAsks.get(id)?.resolve("");
7188
+ }
7189
+ /** Build the INTEGRATION TURN prompt for a NON-CLEAN settled worker (early stop / failure). A clean
7190
+ * success never reaches here — it streams its own `<spoken>` delivery during the run. For a partial
7191
+ * or failed result the outcome re-enters the reflex as a decision (like a tool_result flowing back
7192
+ * into a normal agent loop): the reflex evaluates the outcome against the original intent and chooses
7193
+ * what to do next.
7194
+ *
7195
+ * Decision branches (the reflex acts on them with EXISTING tools — no new surface):
7196
+ * • accept → SPEAK the (partial) result plainly — don't dress a failure up as success.
7197
+ * • escalate → call `Think` with the SAME brief — only when Act failed/stalled AND a Think tier
7198
+ * exists AND this task wasn't already a follow-up (one hop max). Wires the dead
7199
+ * "Reserve Think for a problem Act already FAILED at" promise.
7200
+ * • re-delegate→ call `Act` with a CORRECTED brief — for a recoverable error / partial result.
7201
+ * • ask → ask the user ONE concrete question if genuinely blocked.
7202
+ *
7203
+ * Keeps the `[task <id> completed]` / `[task <id> failed]` opener so existing coalescing + the
7204
+ * failed-revoice fallback still fire, and the per-event transcript markers stay intact. */
7205
+ integrationPrompt(rec, outcome, body, finishReason) {
7206
+ const opener = outcome === "error" ? `[task ${rec.id} failed]` : `[task ${rec.id} completed]`;
7207
+ const underCap = this.autoEscalations < _DuplexAgent.MAX_AUTO_ESCALATIONS;
7208
+ const canEscalate = (outcome === "error" || outcome === "incomplete") && underCap;
7209
+ const hasThink = this.options.thinkModel !== false;
7210
+ const options = [];
7211
+ if (!rec.followUp && canEscalate && hasThink)
7212
+ 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");
7213
+ if (!rec.followUp && canEscalate)
7214
+ options.push("RE-DELEGATE to Act with a corrected brief if the failure looks recoverable (a wrong path, a fixable mistake)");
7215
+ options.push("ASK the user one short, concrete question if you genuinely cannot proceed without their input");
7216
+ options.push("ACCEPT and tell the user plainly what happened (don't dress a failure up as success)");
7217
+ 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.`;
7218
+ const state = outcome === "error" ? `the worker FAILED with: ${body}` : `the worker STOPPED EARLY (${finishReason}) \u2014 its result is PARTIAL, not a finished success: ${body}`;
7219
+ return `${opener} Original request: "${rec.brief}". Outcome: ${state}.${decision}`;
7220
+ }
7221
+ onWorkerSettled(id, res) {
7222
+ this.dropAsk(id);
7223
+ const rec = this.tasks.get(id);
7224
+ if (res.finishReason === "aborted" || rec.status === "cancelled") {
7225
+ rec.status = "cancelled";
7226
+ this.notify("task_cancelled", `task ${id} (${rec.label}) cancelled`);
7227
+ return;
7245
7228
  }
7246
- let endpoint = false;
7247
- for (const t of m.tokens ?? []) {
7248
- if (t.text === "<end>") endpoint = true;
7249
- else if (t.is_final) this.finalText += t.text;
7229
+ if (res.finishReason === "error") {
7230
+ const msg = res.error instanceof Error ? res.error.message : String(res.error ?? "unknown error");
7231
+ return this.failTask(rec, msg);
7250
7232
  }
7251
- this.partialText = (m.tokens ?? []).filter((t) => !t.is_final && t.text !== "<end>").map((t) => t.text).join("");
7252
- const combined = this.finalText + this.partialText;
7253
- if (combined !== this.lastCombined) {
7254
- this.lastCombined = combined;
7255
- this.lastChangeAt = now();
7256
- if (!this.firstTokenAt && combined.trim()) this.firstTokenAt = now();
7233
+ rec.status = "done";
7234
+ rec.result = res.text;
7235
+ const incomplete = res.finishReason !== "stop";
7236
+ log12.verbose(`task ${id} done (${res.steps} steps${incomplete ? `, INCOMPLETE: ${res.finishReason}` : ""})`);
7237
+ this.notify("task_done", `task ${id} (${rec.label}) completed`, {
7238
+ id,
7239
+ text: res.text,
7240
+ usage: res.usage,
7241
+ usageEstimated: res.usageEstimated,
7242
+ finishReason: res.finishReason,
7243
+ steps: res.steps,
7244
+ toolCalls: res.messages.filter((m) => m.role === "tool").length
7245
+ });
7246
+ if (incomplete) {
7247
+ return this.queueRevoice(this.integrationPrompt(rec, "incomplete", res.text, res.finishReason), true);
7257
7248
  }
7258
- this.onPartial(combined);
7259
- if (endpoint && this.finalText.trim()) {
7260
- const utterance = this.finalText.trim();
7261
- if (this.firstTokenAt) log11.debug(`stt: ${Math.round(now() - this.firstTokenAt)}ms first-token\u2192endpoint, "${utterance.slice(0, 60)}"`);
7262
- this.reset();
7263
- this.onUtterance(utterance, now());
7249
+ const tail = rec.splitter?.flush();
7250
+ if (tail?.spoken && !rec.deliveryParked) this.options.host?.notify?.({ kind: "speak_utterance", message: tail.spoken });
7251
+ if (res.text.trim()) this.voice.transcript.push({ role: "assistant", content: res.text });
7252
+ if (rec.deliveryParked && !this.suppressParkedResume) {
7253
+ const gist = (rec.spokenText ?? "").trim() || res.text.trim();
7254
+ if (gist) {
7255
+ if (this.awaitTrivialRedeliver) {
7256
+ this.awaitTrivialRedeliver = false;
7257
+ this.options.host?.notify?.({ kind: "speak_utterance", message: gist });
7258
+ this.notify("diag", "parked_redelivered", { chars: gist.length });
7259
+ } else this.parkedRedeliver.push(gist);
7260
+ }
7264
7261
  }
7262
+ if (!rec.splitter?.spokeAny && res.text.trim() && !rec.deliveryParked)
7263
+ this.options.host?.notify?.({ kind: "speak_utterance", message: res.text });
7265
7264
  }
7266
- reset() {
7267
- this.finalText = "";
7268
- this.partialText = "";
7269
- this.lastCombined = "";
7270
- this.firstTokenAt = 0;
7265
+ onWorkerFailed(id, err2) {
7266
+ this.failTask(this.tasks.get(id), err2 instanceof Error ? err2.message : String(err2));
7271
7267
  }
7272
- stop() {
7273
- this.stopped = true;
7274
- if (this.endpointTimer) clearInterval(this.endpointTimer);
7275
- if (this.noAudioTimer) clearInterval(this.noAudioTimer);
7276
- this.options.source?.stop();
7277
- if (this.ws) this.ws.onclose = null;
7278
- this.ws?.close();
7268
+ failTask(rec, msg) {
7269
+ this.dropAsk(rec.id);
7270
+ rec.status = "error";
7271
+ rec.result = msg;
7272
+ log12.warn(`task ${rec.id} failed: ${msg}`);
7273
+ this.notify("task_error", `task ${rec.id} (${rec.label}) failed: ${msg}`);
7274
+ this.queueRevoice(this.integrationPrompt(rec, "error", msg, "error"), true);
7279
7275
  }
7280
- };
7281
-
7282
- // src/voice/cartesia.ts
7283
- init_logging();
7284
- var log12 = forComponent("CartesiaTTS");
7285
- var now2 = () => performance.now();
7286
- var CartesiaTTSOptions = class {
7287
- auth = "";
7288
- voiceId = "";
7289
- model = "sonic-3.5";
7290
- /** 'apiKey' (server/CLI) → `api_key=` URL param; 'token' (browser, BE-minted) → `access_token=`. */
7291
- authMode = "apiKey";
7292
- };
7293
- var CartesiaTTS = class _CartesiaTTS {
7294
- options;
7295
- ws;
7296
- ctxSeq = 0;
7297
- ctxId = "";
7298
- onAudio = () => {
7299
- };
7300
- onDone = () => {
7301
- };
7302
- /** Word-level timestamps for karaoke reveal: `start[i]` = seconds from turn-audio start (absolute
7303
- * across continuation chunks). Fired only when a consumer opts into reveal (see `wantTimestamps`). */
7304
- onTimestamps = () => {
7305
- };
7306
- /** Request `add_timestamps` from Cartesia. Off by default (saves bandwidth) — the engine sets it
7307
- * when revealMode==='word'. */
7308
- wantTimestamps = false;
7309
- /** Diagnostic tap (provider errors, circuit-breaker open/close, ws reconnects). Fire-and-forget:
7310
- * a throwing handler disables itself — never affects synthesis. Wired by VoiceIO / the lab bridge. */
7311
- onDiag = () => {
7312
- };
7313
- diagOn = true;
7314
- diag(kind, fields) {
7315
- if (!this.diagOn) return;
7316
- try {
7317
- this.onDiag({ t: now2(), kind, ...fields });
7318
- } catch (e) {
7319
- this.diagOn = false;
7320
- log12.debug(`onDiag threw \u2014 TTS diagnostics disabled: ${e instanceof Error ? e.message : e}`);
7321
- }
7276
+ // --- voice tools (closures over this instance) ---
7277
+ /** Live-switch the think tier: `false` disables (removes the Think tool from the voice agent),
7278
+ * a model id enables (adds the tool if missing). The system-prompt THINK_SLOT text is frozen at
7279
+ * construction — the tool's own description carries the routing guidance, so a live enable works;
7280
+ * dispatch()'s think→act fallback covers any straggler calls after a live disable. */
7281
+ setThinkModel(model) {
7282
+ this.options.thinkModel = model;
7283
+ const tools = this.voice.options.tools;
7284
+ const i = tools.findIndex((t) => t.name === "Think");
7285
+ if (model === false && i >= 0) tools.splice(i, 1);
7286
+ else if (model !== false && i < 0) tools.push(this.thinkTool());
7322
7287
  }
7323
- firstAudioAt = 0;
7324
- /** Circuit breaker: consecutive error count + down flag. */
7325
- consecutiveErrors = 0;
7326
- consecutiveOk = 0;
7327
- down = false;
7328
- downAt = 0;
7329
- probeTimer = null;
7330
- static CB_THRESHOLD = 3;
7331
- // open after 3 consecutive errors
7332
- static CB_RECOVER_OK = 2;
7333
- // close only after 2 consecutive good frames (no single-frame flap)
7334
- static CB_PROBE_MS = 3e4;
7335
- constructor(options) {
7336
- this.options = { ...new CartesiaTTSOptions(), ...options };
7288
+ /** User/programmatic spawn: the CLI's /act and /think commands. Returns the task id.
7289
+ * `followUp` marks an automatic escalation/re-delegation (set by the integration turn) so the new
7290
+ * task's own integration turn won't escalate again — capping auto-follow-ups to one hop. */
7291
+ async dispatch(brief, tier = "act", label, followUp = false) {
7292
+ if (tier === "think" && this.options.thinkModel === false) tier = "act";
7293
+ if (followUp) this.autoEscalations++;
7294
+ const id = `t${++this.seq}`;
7295
+ const lbl = label ?? tier;
7296
+ await this.options.onTaskStart?.(id, lbl);
7297
+ this.spawnWorker(id, lbl, this.buildBrief(brief, tier), tier, brief, followUp);
7298
+ this.notify("task_started", `task ${id} (${lbl}) started`, { id, brief, tier });
7299
+ return id;
7337
7300
  }
7338
- closed = false;
7339
- connecting = null;
7340
- async connect() {
7341
- this.closed = false;
7342
- this.connecting = this.doConnect();
7343
- await this.connecting;
7344
- this.connecting = null;
7301
+ actTool() {
7302
+ return {
7303
+ name: "Act",
7304
+ 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).',
7305
+ parameters: {
7306
+ type: "object",
7307
+ required: ["brief"],
7308
+ properties: {
7309
+ brief: { type: "string", description: "full, self-contained instructions for the worker" },
7310
+ label: { type: "string", description: "a short (2-4 word) label for the task" }
7311
+ }
7312
+ },
7313
+ run: async ({ brief, label }) => {
7314
+ this.spokeBeforeDispatch = this.spokeThisTurn;
7315
+ this.turnDispatched = true;
7316
+ this.turnBriefs.add(String(brief ?? ""));
7317
+ this.voice.options.toolChoice = "none";
7318
+ const id = await this.dispatch(String(brief ?? ""), "act", label ? String(label) : void 0, this.turnFollowUp);
7319
+ 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.`;
7320
+ }
7321
+ };
7345
7322
  }
7346
- async doConnect() {
7347
- const key = await resolveAuth(this.options.auth);
7348
- const param = this.options.authMode === "token" ? "access_token" : "api_key";
7349
- this.ws = new WebSocket(`wss://api.cartesia.ai/tts/websocket?cartesia_version=2026-03-01&${param}=${key}`);
7350
- await new Promise((res, rej) => {
7351
- this.ws.onopen = () => res();
7352
- this.ws.onerror = (e) => rej(new Error(`cartesia ws: ${e.message || "connect failed"}`));
7353
- });
7354
- this.ws.onclose = (ev) => {
7355
- log12.warn(`cartesia ws closed (${ev.code} ${ev.reason || ""})`);
7356
- this.diag("tts_ws_closed", { code: ev.code, reason: String(ev.reason || ""), reconnecting: !this.closed });
7357
- if (!this.closed) {
7358
- this.connecting = this.doConnect().catch((e) => {
7359
- log12.error(`cartesia reconnect failed: ${e.message}`);
7360
- this.diag("tts_reconnect_failed", { message: e.message });
7361
- });
7323
+ thinkTool() {
7324
+ return {
7325
+ name: "Think",
7326
+ 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.",
7327
+ parameters: {
7328
+ type: "object",
7329
+ required: ["brief"],
7330
+ properties: {
7331
+ brief: { type: "string", description: "the question or problem to reason about deeply" },
7332
+ label: { type: "string", description: "a short (2-4 word) label for the task" }
7333
+ }
7334
+ },
7335
+ run: async ({ brief, label }) => {
7336
+ this.spokeBeforeDispatch = this.spokeThisTurn;
7337
+ this.turnDispatched = true;
7338
+ this.turnBriefs.add(String(brief ?? ""));
7339
+ this.voice.options.toolChoice = "none";
7340
+ const id = await this.dispatch(String(brief ?? ""), "think", label ? String(label) : void 0, this.turnFollowUp);
7341
+ 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.`;
7362
7342
  }
7363
7343
  };
7364
- this.ws.onmessage = (ev) => {
7365
- const m = JSON.parse(String(ev.data));
7366
- if (m.context_id && m.context_id !== this.ctxId) return;
7367
- if (m.type === "chunk" && m.data) {
7368
- this.consecutiveErrors = 0;
7369
- this.markRecovered();
7370
- if (!this.firstAudioAt) this.firstAudioAt = now2();
7371
- this.onAudio(base64ToBytes(m.data));
7372
- } else if (m.type === "done") {
7373
- this.consecutiveErrors = 0;
7374
- this.markRecovered();
7375
- this.onDone();
7376
- } else if (m.type === "timestamps" && m.word_timestamps) {
7377
- const wt = m.word_timestamps;
7378
- if (wt.words?.length && wt.start?.length) this.onTimestamps(wt.words, wt.start);
7379
- } else if (m.type === "error") {
7380
- if (/already been cancelled|does not exist/.test(m.message || "")) return;
7381
- this.consecutiveErrors++;
7382
- this.diag("tts_error", { message: String(m.message || ""), code: m.status_code, contextId: m.context_id, consecutive: this.consecutiveErrors });
7383
- if (!this.down && this.consecutiveErrors >= _CartesiaTTS.CB_THRESHOLD) {
7384
- this.down = true;
7385
- this.downAt = now2();
7386
- this.consecutiveOk = 0;
7387
- log12.warn(`TTS circuit breaker open \u2014 ${this.consecutiveErrors} consecutive errors, switching to text-only`);
7388
- this.diag("tts_breaker_open", { errors: this.consecutiveErrors });
7389
- this.onDone();
7390
- this.startProbe();
7391
- } else if (!this.down) {
7392
- (/No valid transcripts/i.test(m.message || "") ? log12.debug : log12.warn)(`cartesia: ${JSON.stringify(m)}`);
7344
+ }
7345
+ taskStatusTool() {
7346
+ return {
7347
+ name: "TaskStatus",
7348
+ description: "Status of background tasks. Pass `id` for one task, or omit it to list all.",
7349
+ parameters: { type: "object", properties: { id: { type: "string" } } },
7350
+ run: async ({ id }) => {
7351
+ const list = id ? [this.tasks.get(String(id))].filter(Boolean) : [...this.tasks.values()];
7352
+ if (!list.length) return id ? `No task '${id}'.` : "No background tasks.";
7353
+ return list.map((t) => `${t.id} (${t.label}): ${t.status}`).join("\n");
7354
+ }
7355
+ };
7356
+ }
7357
+ /** Sub-100ms read-only lookups the voice may do itself — everything else stays Act-only.
7358
+ * fs-only (no shell; the engine is VFS-abstracted): time, git branch (.git/HEAD read), ls, file
7359
+ * head. Output is hard-capped so a lookup can never bloat the skinny voice context. */
7360
+ quickLookTool() {
7361
+ const CAP2 = 2e3;
7362
+ const kinds = [.../* @__PURE__ */ new Set(["time", "branch", "ls", "file", "capabilities", ...Object.keys(this.options.quickLook ?? {})])];
7363
+ return {
7364
+ name: "QuickLook",
7365
+ description: `Instant read-only lookup \u2014 one of: ${kinds.join(", ")}. For trivial facts only; anything needing search, commands, or reasoning goes through Act.`,
7366
+ parameters: {
7367
+ type: "object",
7368
+ required: ["what"],
7369
+ properties: {
7370
+ what: { type: "string", enum: kinds, description: "what to look up" },
7371
+ path: { type: "string", description: "for ls/file: the path to look at" }
7372
+ }
7373
+ },
7374
+ run: async ({ what, path }) => {
7375
+ const fs = this.options.fs;
7376
+ try {
7377
+ const over = this.options.quickLook?.[String(what)];
7378
+ if (over) return await over(path ? String(path) : void 0);
7379
+ switch (String(what)) {
7380
+ case "capabilities": {
7381
+ const actTools = this.options.actOptions?.tools ?? [];
7382
+ const names = actTools.map((t) => t.name);
7383
+ const mcpServers = Object.keys(this.options.actOptions?.providerOptions?.mcpServers ?? {});
7384
+ 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).` : "";
7385
+ if (!names.length)
7386
+ 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;
7387
+ const hasFetch = names.some((n) => /WebFetch/i.test(n));
7388
+ const hasBrowser = names.some((n) => /browser.*(navigate|click|page|type)/i.test(n));
7389
+ const hasSearch = names.some((n) => /(^|_)WebSearch$|search/i.test(n) && !/WebFetch|browser/i.test(n));
7390
+ const notes = [];
7391
+ if (hasFetch) notes.push("WebFetch retrieves ONE specific URL you are given \u2014 it is not a search engine.");
7392
+ 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.");
7393
+ 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.');
7394
+ const webNote = notes.length ? " NOTE: " + notes.join(" ") : "";
7395
+ 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;
7396
+ }
7397
+ case "time":
7398
+ return (/* @__PURE__ */ new Date()).toString();
7399
+ case "branch": {
7400
+ if (!fs) return "unavailable (no filesystem)";
7401
+ const head = (await fs.readFile(".git/HEAD")).trim();
7402
+ return head.startsWith("ref: refs/heads/") ? `branch: ${head.slice("ref: refs/heads/".length)}` : `detached HEAD at ${head.slice(0, 12)}`;
7403
+ }
7404
+ case "ls": {
7405
+ if (!fs) return "unavailable (no filesystem)";
7406
+ const p = String(path ?? ".");
7407
+ try {
7408
+ const names = await fs.readDir(p);
7409
+ return names.slice(0, 50).join("\n") + (names.length > 50 ? `
7410
+ \u2026 (+${names.length - 50} more)` : "");
7411
+ } catch {
7412
+ const names = await fs.readDir(".").catch(() => []);
7413
+ return `'${p}' not found here \u2014 you are likely already inside it. Current directory listing:
7414
+ ` + names.slice(0, 50).join("\n") + (names.length > 50 ? `
7415
+ \u2026 (+${names.length - 50} more)` : "");
7416
+ }
7417
+ }
7418
+ case "file": {
7419
+ if (!fs) return "unavailable (no filesystem)";
7420
+ if (!path) return "file lookup needs a path";
7421
+ try {
7422
+ const text = await fs.readFile(String(path));
7423
+ return text.length > CAP2 ? text.slice(0, CAP2) + `
7424
+ \u2026 (truncated \u2014 ${text.length} chars total; Act for the full file)` : text;
7425
+ } catch {
7426
+ const names = await fs.readDir(".").catch(() => []);
7427
+ return `'${path}' not found. Current directory contains:
7428
+ ` + names.slice(0, 50).join("\n");
7429
+ }
7430
+ }
7431
+ default:
7432
+ return `unknown lookup '${what}'`;
7433
+ }
7434
+ } catch (e) {
7435
+ return `lookup failed: ${e?.message ?? e}`;
7393
7436
  }
7394
7437
  }
7395
7438
  };
7396
7439
  }
7397
- /** Close the breaker only after CB_RECOVER_OK consecutive good frames, so a single straggler chunk
7398
- * after a 503 burst doesn't flap open→recover in <1s. A sub-2s down-window is a transient blip → debug. */
7399
- markRecovered() {
7400
- if (!this.down) return;
7401
- if (++this.consecutiveOk < _CartesiaTTS.CB_RECOVER_OK) return;
7402
- this.down = false;
7403
- this.consecutiveOk = 0;
7404
- this.stopProbe();
7405
- const downMs = this.downAt ? now2() - this.downAt : 0;
7406
- this.diag("tts_breaker_close", { downMs: Math.round(downMs) });
7407
- (downMs < 2e3 ? log12.debug : log12.info)(`TTS recovered${downMs ? ` (down ${downMs}ms)` : ""}`);
7408
- }
7409
- /** Ensure the WS is open before sending — reconnects if idle-closed. */
7410
- async ensureConnected() {
7411
- if (this.connecting) await this.connecting;
7412
- if (this.ws?.readyState !== WebSocket.OPEN) await this.connect();
7413
- }
7414
- /** Prime the synthesis pipeline on a throwaway context right after connect: the FIRST synthesis on
7415
- * a fresh WS pays Cartesia's cold spin-up (~1s+ live) — absorb it at mic-on instead of turn one.
7416
- * The returned audio is discarded (engine drops onAudio while not speaking; once a real turn calls
7417
- * newContext() any stragglers are stale-context-filtered). Respects the circuit breaker. */
7418
- warmup() {
7419
- if (this.down) return;
7420
- this.newContext();
7421
- if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(this.frame("Ok.", false));
7422
- }
7423
- newContext() {
7424
- this.ctxId = `ctx-${++this.ctxSeq}`;
7425
- this.firstAudioAt = 0;
7426
- return this.ctxId;
7440
+ answerTaskTool() {
7441
+ return {
7442
+ name: "AnswerTask",
7443
+ 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.`,
7444
+ parameters: {
7445
+ type: "object",
7446
+ required: ["id", "answer"],
7447
+ properties: { id: { type: "string" }, answer: { type: "string", description: "the user's answer, verbatim or faithfully summarized" } }
7448
+ },
7449
+ run: async ({ id, answer }) => {
7450
+ const ask = this.pendingAsks.get(String(id));
7451
+ if (!ask) return `No pending question for '${id}' \u2014 it may have been answered already or timed out.`;
7452
+ ask.resolve(String(answer ?? ""));
7453
+ return `Answer relayed \u2014 task ${id} resumes.`;
7454
+ }
7455
+ };
7427
7456
  }
7428
- frame(transcript, cont) {
7429
- return JSON.stringify({
7430
- model_id: this.options.model,
7431
- transcript,
7432
- voice: { mode: "id", id: this.options.voiceId },
7433
- output_format: { container: "raw", encoding: "pcm_s16le", sample_rate: TTS_SAMPLE_RATE },
7434
- context_id: this.ctxId,
7435
- continue: cont,
7436
- ...this.wantTimestamps ? { add_timestamps: true } : {}
7437
- });
7457
+ holdTool() {
7458
+ return {
7459
+ name: "Hold",
7460
+ 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.',
7461
+ parameters: {
7462
+ type: "object",
7463
+ properties: {
7464
+ filler: { type: "string", description: 'optional short filler to speak ("mhm", "go on", "mm-hm")' }
7465
+ }
7466
+ },
7467
+ run: async ({ filler }) => {
7468
+ this.heldThisTurn = true;
7469
+ this.notify("hold_filler", filler ? String(filler) : "");
7470
+ return "Holding \u2014 listening for the rest of the user's thought. Do not respond further this turn.";
7471
+ }
7472
+ };
7438
7473
  }
7439
- speak(text, cont) {
7440
- if (this.down) return;
7441
- if (cont && !text) return;
7442
- if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(this.frame(text, cont));
7443
- else void this.ensureConnected().then(() => this.ws?.readyState === WebSocket.OPEN && this.ws.send(this.frame(text, cont)));
7474
+ cancelTaskTool() {
7475
+ return {
7476
+ name: "CancelTask",
7477
+ description: "Cancel a running background task by id.",
7478
+ parameters: { type: "object", required: ["id"], properties: { id: { type: "string" } } },
7479
+ run: async ({ id }) => this.cancelTask(String(id))
7480
+ };
7444
7481
  }
7445
- end() {
7446
- if (this.down) {
7447
- this.onDone();
7448
- return;
7482
+ };
7483
+
7484
+ // src/mcp.ts
7485
+ function toResult(result) {
7486
+ if (result == null) return { text: "" };
7487
+ if (typeof result === "string") return { text: result };
7488
+ const content = result.content;
7489
+ if (Array.isArray(content)) {
7490
+ const texts = [];
7491
+ const images = [];
7492
+ for (const c of content) {
7493
+ if (c?.type === "image" && typeof c.data === "string" && c.mimeType) {
7494
+ images.push({ mimeType: c.mimeType, data: c.data });
7495
+ } else if (typeof c?.text === "string") {
7496
+ texts.push(c.text);
7497
+ } else {
7498
+ texts.push(JSON.stringify(c));
7499
+ }
7449
7500
  }
7450
- if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(this.frame("", false));
7451
- }
7452
- cancel() {
7453
- if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(JSON.stringify({ context_id: this.ctxId, cancel: true }));
7501
+ const text = texts.join("\n");
7502
+ if (text || images.length) return { text, ...images.length ? { images } : {} };
7454
7503
  }
7455
- startProbe() {
7456
- if (this.probeTimer) return;
7457
- this.probeTimer = setInterval(() => {
7458
- if (!this.down) {
7459
- this.stopProbe();
7460
- return;
7504
+ return { text: JSON.stringify(result) };
7505
+ }
7506
+ function mcpToolToAgentTool(spec, callTool, prefix = "mcp__") {
7507
+ return {
7508
+ name: `${prefix}${spec.name}`,
7509
+ description: spec.description ?? `MCP tool ${spec.name}`,
7510
+ parameters: spec.inputSchema ?? { type: "object", properties: {} },
7511
+ async run(args, _ctx) {
7512
+ const r = toResult(await callTool(spec.name, args ?? {}));
7513
+ return r.images?.length ? r : r.text;
7514
+ }
7515
+ };
7516
+ }
7517
+ function mcpToolsToAgentTools(specs, callTool, prefix = "mcp__", filter) {
7518
+ return (filter ? specs.filter(filter) : specs).map((s) => mcpToolToAgentTool(s, callTool, prefix));
7519
+ }
7520
+ function describeSpec(s) {
7521
+ const schema = s.inputSchema ? `
7522
+ args: ${JSON.stringify(s.inputSchema)}` : "";
7523
+ return `${s.name} \u2014 ${s.description ?? "(no description)"}${schema}`;
7524
+ }
7525
+ function makeMcpToolSearch(specs, callTool, options = {}) {
7526
+ const maxResults = options.maxResults ?? 10;
7527
+ const byName = new Map(specs.map((s) => [s.name, s]));
7528
+ const catalogLine = `${specs.length} MCP tool(s) available \u2014 search by keyword, then call by exact name.`;
7529
+ const searchTool = {
7530
+ name: "ToolSearch",
7531
+ description: `Search the available MCP tools by keyword (${catalogLine}). Returns matching tool names + their argument schemas; call one with \`McpCall\`.`,
7532
+ parameters: { type: "object", required: ["query"], properties: { query: { type: "string", description: "keywords to match against tool name + description" } } },
7533
+ async run({ query }) {
7534
+ const q2 = String(query ?? "").trim();
7535
+ if (!q2) return catalogLine;
7536
+ const { kept } = topByRelevance(specs, q2, (s) => `${s.name} ${s.description ?? ""}`, maxResults);
7537
+ if (!kept.length) return `(no MCP tool matches "${q2}" \u2014 try broader keywords)`;
7538
+ return kept.map(describeSpec).join("\n");
7539
+ }
7540
+ };
7541
+ const callMcpTool = {
7542
+ name: "McpCall",
7543
+ description: "Call an MCP tool discovered via `ToolSearch`, by its exact name. Pass its arguments as `args`.",
7544
+ parameters: {
7545
+ type: "object",
7546
+ required: ["name"],
7547
+ properties: {
7548
+ name: { type: "string", description: "exact tool name from ToolSearch" },
7549
+ args: { type: "object", description: "arguments object for the tool (per its schema)" }
7461
7550
  }
7462
- this.consecutiveErrors = 0;
7463
- this.newContext();
7464
- if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(this.frame("Ok.", false));
7465
- }, _CartesiaTTS.CB_PROBE_MS);
7466
- this.probeTimer.unref?.();
7467
- }
7468
- stopProbe() {
7469
- if (this.probeTimer) {
7470
- clearInterval(this.probeTimer);
7471
- this.probeTimer = null;
7551
+ },
7552
+ async run({ name, args }) {
7553
+ const n = String(name ?? "");
7554
+ if (!byName.has(n)) return `Error: unknown MCP tool '${n}'. Use ToolSearch to find valid names.`;
7555
+ const r = toResult(await callTool(n, args ?? {}));
7556
+ return r.images?.length ? r : r.text;
7557
+ }
7558
+ };
7559
+ return [searchTool, callMcpTool];
7560
+ }
7561
+ function buildMcpCatalog(servers) {
7562
+ const specs = [];
7563
+ const routes = /* @__PURE__ */ new Map();
7564
+ for (const m of servers) {
7565
+ for (const s of m.specs) {
7566
+ const base = `mcp__${m.name}__${s.name}`.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 128);
7567
+ let display = base;
7568
+ for (let i = 2; routes.has(display); i++) display = `${base.slice(0, 128 - String(i).length - 1)}_${i}`;
7569
+ specs.push({ name: display, description: s.description, inputSchema: s.inputSchema });
7570
+ routes.set(display, { server: m.name, rawName: s.name });
7472
7571
  }
7473
7572
  }
7474
- close() {
7475
- this.closed = true;
7476
- this.stopProbe();
7477
- if (this.ws) this.ws.onclose = null;
7478
- this.ws?.close();
7479
- }
7480
- };
7481
- function base64ToBytes(b64) {
7482
- if (typeof Buffer !== "undefined") return Buffer.from(b64, "base64");
7483
- const bin = atob(b64);
7484
- const out = new Uint8Array(bin.length);
7485
- for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
7486
- return out;
7573
+ return { specs, routes };
7574
+ }
7575
+ function searchOverCatalog(servers, specs, routes, resolve4, options) {
7576
+ const tools = specs.length ? makeMcpToolSearch(specs, (name, args) => {
7577
+ const r = routes.get(name);
7578
+ if (!r) throw new Error(`unknown MCP tool '${name}' \u2014 use ToolSearch to find valid names`);
7579
+ return resolve4(r.server, r.rawName, args ?? {});
7580
+ }, options) : [];
7581
+ return { tools, serverNames: servers, toolCount: specs.length };
7582
+ }
7583
+ function makeMcpToolSearchFromMounted(mounted, options) {
7584
+ const { specs, routes } = buildMcpCatalog(mounted);
7585
+ const byName = new Map(mounted.map((m) => [m.name, m]));
7586
+ return searchOverCatalog(mounted.map((m) => m.name), specs, routes, (server, rawName, args) => byName.get(server).client.callTool(rawName, args), options);
7487
7587
  }
7488
7588
 
7489
7589
  // src/index.ts
7590
+ init_logging();
7490
7591
  init_worktree();
7491
7592
  import { MemFilesystem as MemFilesystem3, IndexedDbFilesystem, CommandExecutor as CommandExecutor2, registerHeadlessCommands as registerHeadlessCommands2 } from "@livx.cc/wcli/core";
7492
7593
 
@@ -10774,8 +10875,8 @@ function applyKey(s, key, str) {
10774
10875
  }
10775
10876
  return "none";
10776
10877
  }
10777
- function createLineEditor(out) {
10778
- const isTTY = !!out.isTTY && !!process.stdin.isTTY;
10878
+ function createLineEditor(out, input = keyInput) {
10879
+ const isTTY = !!out.isTTY && !!input.isTTY;
10779
10880
  const dim2 = (x) => `\x1B[2m${x}\x1B[0m`;
10780
10881
  const inverse = (x) => `\x1B[7m${x}\x1B[0m`;
10781
10882
  const COLOR = {
@@ -10863,9 +10964,9 @@ function createLineEditor(out) {
10863
10964
  curRow = 0;
10864
10965
  if (opts.initial) s.insert(opts.initial);
10865
10966
  s.refresh();
10866
- emitKeypressEvents(keyInput);
10867
- keyInput.setRawMode(true);
10868
- keyInput.resume();
10967
+ emitKeypressEvents(input);
10968
+ input.setRawMode(true);
10969
+ input.resume();
10869
10970
  out.write("\x1B[?2004h");
10870
10971
  const promptOf = () => typeof opts.prompt === "function" ? opts.prompt() : opts.prompt;
10871
10972
  render(s, promptOf(), maxVisible, opts.status);
@@ -10949,9 +11050,9 @@ function createLineEditor(out) {
10949
11050
  return;
10950
11051
  }
10951
11052
  if (key?.meta && key.name === "p" && opts.onPickModel) {
10952
- keyInput.off("keypress", onKey);
11053
+ input.off("keypress", onKey);
10953
11054
  void opts.onPickModel().finally(() => {
10954
- keyInput.on("keypress", onKey);
11055
+ input.on("keypress", onKey);
10955
11056
  curRow = 0;
10956
11057
  redraw();
10957
11058
  });
@@ -10988,7 +11089,7 @@ function createLineEditor(out) {
10988
11089
  activeRedraw = void 0;
10989
11090
  activeAbort = void 0;
10990
11091
  if (ticker) clearInterval(ticker);
10991
- keyInput.off("keypress", onKey);
11092
+ input.off("keypress", onKey);
10992
11093
  process.removeListener("SIGWINCH", onResize);
10993
11094
  s.closeMenu();
10994
11095
  if (suspended) {
@@ -11005,7 +11106,7 @@ function createLineEditor(out) {
11005
11106
  out.write([prompt + lines[0], ...lines.slice(1)].map((l) => wrapAnsi(l, cols, " ")).join("\r\n") + "\r\n");
11006
11107
  curRow = 0;
11007
11108
  };
11008
- keyInput.on("keypress", onKey);
11109
+ input.on("keypress", onKey);
11009
11110
  });
11010
11111
  }
11011
11112
  return {
@@ -11024,6 +11125,7 @@ function createLineEditor(out) {
11024
11125
  curRow = 0;
11025
11126
  activeRedraw?.();
11026
11127
  },
11128
+ isSuspended: () => suspended,
11027
11129
  abort: () => activeAbort?.()
11028
11130
  };
11029
11131
  }
@@ -12900,6 +13002,12 @@ async function repl(args, ai, cfg, cwd) {
12900
13002
  };
12901
13003
  let toggleVoice;
12902
13004
  let editorRef;
13005
+ const emitChrome = (write) => {
13006
+ const wasSusp = editorRef?.isSuspended() ?? true;
13007
+ editorRef?.suspend();
13008
+ write();
13009
+ if (!wasSusp) editorRef?.resume();
13010
+ };
12903
13011
  let repaintStash = () => {
12904
13012
  };
12905
13013
  let workerOptions;
@@ -13021,23 +13129,23 @@ async function repl(args, ai, cfg, cwd) {
13021
13129
  if (e.kind === "task_done" && e.data?.text) {
13022
13130
  const lines = String(e.data.text).split("\n");
13023
13131
  const shown = lines.slice(0, previewLines());
13024
- err("\r\x1B[0J\n" + dim(` \u29BF ${e.message}
13132
+ emitChrome(() => {
13133
+ err("\n" + dim(` \u29BF ${e.message}
13025
13134
  `) + shown.map((l) => dim(` ${plainLine(l)}
13026
13135
  `)).join(""));
13027
- if (lines.length > shown.length) err(dim(` \u2026 (+${lines.length - shown.length} more lines)
13136
+ if (lines.length > shown.length) err(dim(` \u2026 (+${lines.length - shown.length} more lines)
13028
13137
  `));
13138
+ });
13029
13139
  duplexAccount(e.data);
13030
- editorRef?.redrawNow();
13031
13140
  repaintStash();
13032
13141
  return;
13033
13142
  }
13034
13143
  if (typeof e.kind === "string" && e.kind.startsWith("task_")) {
13035
13144
  spinner.stop();
13036
- err("\r\x1B[0J" + (e.kind === "task_ask" ? yellow(` ? ${e.message} \u2014 answer by voice or type yes/no
13145
+ emitChrome(() => err(e.kind === "task_ask" ? yellow(` ? ${e.message} \u2014 answer by voice or type yes/no
13037
13146
  `) : e.kind === "task_error" ? yellow(` \u2717 ${e.message}
13038
13147
  `) : dim(` \xB7 ${e.message}
13039
13148
  `)));
13040
- editorRef?.redrawNow();
13041
13149
  repaintStash();
13042
13150
  return;
13043
13151
  }