@livx.cc/agentx 0.99.89 → 0.99.92

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -978,6 +978,8 @@ interface TaskRecord {
978
978
  budgetSpent?: boolean;
979
979
  /** The budget offer spoken in place of the cut rest — folded into the transcript after the written result. */
980
980
  capOffer?: string;
981
+ /** The live worker — Act `refines` injects a user refinement into it (DuplexAgent.amendTask). */
982
+ worker?: Agent;
981
983
  }
982
984
  type WorkerTier = 'act' | 'think';
983
985
  declare class DuplexAgentOptions {
@@ -1047,6 +1049,9 @@ declare class DuplexAgentOptions {
1047
1049
  /** Host overrides for QuickLook lookups (keyed by `what`). The engine's defaults go through the
1048
1050
  * (possibly jailed) fs — e.g. `.git/**` is deny-listed, so the CLI supplies 'branch' itself. */
1049
1051
  quickLook?: Record<string, (path?: string) => string | Promise<string>>;
1052
+ /** Extra roots QuickLook ls/file try for a relative path not found under the cwd (the CLI passes ~ and ~/Documents:
1053
+ * a spoken "Projects/X" means ~/Documents/Projects/X far more often than <cwd>/Projects/X). */
1054
+ lookRoots: string[];
1050
1055
  /** Memory directory/directories on the WORKER fs. If set, the voice agent gets Remember + Recall
1051
1056
  * tools directly (no delegation needed) and implicit capture guidance. */
1052
1057
  memoryDir?: string | string[];
@@ -1109,6 +1114,8 @@ declare class DuplexAgent {
1109
1114
  private reflexForwarded;
1110
1115
  private fabricationCut;
1111
1116
  private leakCuts;
1117
+ private midPhraseBounced;
1118
+ private repeatCuts;
1112
1119
  private leakStep;
1113
1120
  private leakHit;
1114
1121
  private stepMarks;
@@ -1191,10 +1198,11 @@ declare class DuplexAgent {
1191
1198
  * not dead air, and a nudge would run on the same aborted signal (live: the "[reminder]" landed in the
1192
1199
  * transcript as a user turn with no reply, session 20260923-101910 msg 27). */
1193
1200
  private endTurn;
1194
- /** Remove complete stage-direction parentheticals from the UNFORWARDED reflex text (STAGE_DIRECTION_RE).
1195
- * Only the unforwarded region is touched — already-spoken audio can't be unsent, and splicing before
1196
- * reflexForwarded would corrupt the forward offset. */
1197
- private scrubStageDirections;
1201
+ /** Rewrite the UNFORWARDED reflex text: drop complete stage-direction parentheticals (STAGE_DIRECTION_RE) and spoken
1202
+ * junk (scrubSpokenJunk). Only the unforwarded region is touched — already-spoken audio can't be unsent, and
1203
+ * splicing before reflexForwarded would corrupt the forward offset. Rewritten per step segment so the stepMarks
1204
+ * after it move with the text (a mark is a reflexBuf offset); a segment that ends at a step mark is complete. */
1205
+ private scrubUnforwarded;
1198
1206
  /** Clear the per-turn guards. Called at the head of every voice turn (user send + re-voice flush). */
1199
1207
  private resetTurn;
1200
1208
  /** preToolUse guard on the reflex: once it has dispatched this turn, a dispatch is "said my piece,
@@ -1266,6 +1274,10 @@ declare class DuplexAgent {
1266
1274
  * Called on divergence (send), a stale partial (VoiceEngine.onSpeculateAbort), a side-effect tool
1267
1275
  * attempt (dispatchGuard), or host paths that will never dispatch a final (commands, voice-off). */
1268
1276
  abortSpeculation(): void;
1277
+ /** Fold a refinement into a RUNNING task's worker (Agent.inject — picked up at its next step) instead of cancel +
1278
+ * respawn: live 20261013-085238 one request spoken over three fragments became t5 → cancel → t6 → cancel → t7, each
1279
+ * worker restarting from zero. Returns the id when amended, undefined when the task is not running (→ dispatch new). */
1280
+ amendTask(id: string, brief: string): string | undefined;
1269
1281
  /** Cancel a running background task — shared by the CancelTask tool and the CLI /tasks picker. */
1270
1282
  cancelTask(id: string): string;
1271
1283
  /** Barge-in (or a dispatch-driven supersede): suppress running tasks' remaining SPOKEN delivery so a
@@ -1401,6 +1413,12 @@ declare class DuplexAgent {
1401
1413
  * fs-only (no shell; the engine is VFS-abstracted): time, git branch (.git/HEAD read), ls, file
1402
1414
  * head. Output is hard-capped so a lookup can never bloat the skinny voice context. */
1403
1415
  private quickLookTool;
1416
+ /** Where QuickLook tries a path: as given (cwd-relative or absolute), then — relative only — under each lookRoot. */
1417
+ private lookCandidates;
1418
+ /** A QuickLook path not found anywhere: say where it looked and, at the deepest folder that DID exist, the few closest
1419
+ * names (a mis-heard segment — "Lead Sheets" for "Livshitz" — is usually one of them). Never the whole cwd listing:
1420
+ * live 20261013-085238 dumped it three times for three spellings of the same path. */
1421
+ private lookMiss;
1404
1422
  private answerTaskTool;
1405
1423
  private holdTool;
1406
1424
  private cancelTaskTool;
package/dist/index.js CHANGED
@@ -3545,6 +3545,13 @@ async function loadMemory(fs, dir, opts = {}) {
3545
3545
  - (${restSlugs.length} more learnings, slugs only \u2014 call \`Recall\` if relevant): ${restSlugs.join(", ")}` : "");
3546
3546
  return { index, tools };
3547
3547
  }
3548
+ var TERM_STOPWORDS = new Set(`the and for but not you your yours our ours his her hers its their they them this that these those
3549
+ there here what when where which who whom whose why how all any each every some many much more most few other such only own same
3550
+ also just very can will would should could may might must shall have has had does did done was were are been being use used using
3551
+ always never often sometimes usually once then than now today tomorrow yesterday before after later soon first last next new old
3552
+ read write see make take give get set keep run add note notes user users company name names project projects team work works
3553
+ working home inbox label labels file files code prefer prefers please don't doesn't via per with without from into about over
3554
+ under yes okay important example one two three monday tuesday wednesday thursday friday saturday sunday`.split(/\s+/));
3548
3555
  function slugify(s, fallback = "note") {
3549
3556
  const base = String(s ?? "").trim().toLowerCase().replace(/\.md$/i, "").replace(/[^\w\s-]/g, "").replace(/[\s_]+/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "").slice(0, 48);
3550
3557
  return base || fallback;
@@ -9316,7 +9323,7 @@ var SUSPECT = [
9316
9323
  /\bwe(?: have|'ve)\b|\bwe (?:already )?(?:responded|replied|dispatched|used|called|did|gave|said|asked)\b/i,
9317
9324
  /\bno (?:further|more|other)\b/i,
9318
9325
  /\[\s*task\b|\bt\d+\b|\bwait(?:ing)? for (?:the )?(?:events?|results?|task)\b/i,
9319
- /\w\s*\{\s*"|\bwhat:\s*"/,
9326
+ /[\p{L}\p{N}.!?…]\s*\{\s*"|\bwhat:\s*"/u,
9320
9327
  /\b(?:last|previous) (?:response|reply|message|turn)\b|\bthe (?:conversation|transcript|context)\b/i
9321
9328
  ];
9322
9329
  var STRICT = [
@@ -9333,6 +9340,12 @@ var STRICT = [
9333
9340
  // its own protocol: using its tools, tool-call syntax, task events
9334
9341
  new RegExp(String.raw`(?:\b[Ww]e(?: need to| should| must| have to| will|'ll)|\b[Ll]et'?s|^[Ss]hould|^[Nn]ow we should) (?:call|use|do|dispatch(?: to)?|invoke) (?:the )?${TOOL}\b`),
9335
9342
  new RegExp(String.raw`\b(?:[Ww]e (?:called|dispatched)|responded with) ${TOOL}\b|\b${TOOL}\s*\{|\bwhat:\s*"|\b${TOOL} (?:tool )?(?:brief|call|args?|arguments)\b`),
9343
+ // telegraphic self-instruction naming its own tool ("Use Act with brief to search npm.", "Then dispatch Act.") and
9344
+ // tool-call arguments glued onto the text ("One sentence ack.{"brief":…}" — harmony lost the call's recipient;
9345
+ // agentx sessions 20260713-124250, 20261012-225902). A JSON block printed for the listener follows whitespace.
9346
+ // "Use <Tool>" only in the planning shape (with/to/punctuation next) — "Use Act two of the play…" is speech.
9347
+ new RegExp(String.raw`^(?:Use|Call|Invoke) ${TOOL}(?= with\b| to\b|\s*[.,;:]|\s*$)|^(?:(?:Then|Now|So) )?[Dd]ispatch(?: to)? (?:the )?${TOOL}\b`),
9348
+ /[\p{L}\p{N}.!?…]\{\s*"\w+"\s*:/u,
9336
9349
  /\bwait(?:ing)? for (?:the )?(?:events?|t\d+)\b|\bt\d+ (?:completed|failed)\b|\[\s*task\b/i
9337
9350
  ];
9338
9351
  var SENTENCE_END = new RegExp(`[.!?\u2026]+["')\\]]*(?:\\s|(?=\\p{Lu}|\\[))`, "gu");
@@ -9366,6 +9379,19 @@ async function judgeLeak(decider, sentence, userSaid) {
9366
9379
  if (!Number.isFinite(p)) throw new Error("leak judge: no noul in the answer");
9367
9380
  return p;
9368
9381
  }
9382
+ function scrubSpokenJunk(text, final = false) {
9383
+ let s = text.replace(/[​-‍⁠]/g, "").replace(/\[\s*emotion\b([^[\]]*)\]/gi, (_m, inner) => {
9384
+ const e = normalizeEmotion(inner.trim());
9385
+ return e ? `[${e}]` : "";
9386
+ }).replace(/\[[^\p{L}\p{N}[\]]*\]/gu, "").replace(/(?:[\s ]*(?:…|\.{2,}|[—–]|-{2,})){3,}/g, (m) => /^[\s ]/.test(m) ? " \u2026" : "\u2026");
9387
+ if (final) s = s.replace(/\[\s*emotion\b[^\]]*$/i, "");
9388
+ return s;
9389
+ }
9390
+ function isRepeatOf(sentence, spoken) {
9391
+ const norm2 = (x) => x.replace(/\[[a-z_ ]+\]/gi, "").replace(/[^\p{L}\p{N}]+/gu, " ").trim().toLowerCase();
9392
+ const s = norm2(sentence);
9393
+ return s.replace(/ /g, "").length >= 16 && spoken.split(SENTENCE_SPLIT).some((x) => norm2(x) === s);
9394
+ }
9369
9395
 
9370
9396
  // src/duplex.ts
9371
9397
  var log22 = forComponent("DuplexAgent");
@@ -9448,6 +9474,9 @@ var DuplexAgentOptions = class {
9448
9474
  /** Host overrides for QuickLook lookups (keyed by `what`). The engine's defaults go through the
9449
9475
  * (possibly jailed) fs — e.g. `.git/**` is deny-listed, so the CLI supplies 'branch' itself. */
9450
9476
  quickLook;
9477
+ /** Extra roots QuickLook ls/file try for a relative path not found under the cwd (the CLI passes ~ and ~/Documents:
9478
+ * a spoken "Projects/X" means ~/Documents/Projects/X far more often than <cwd>/Projects/X). */
9479
+ lookRoots = [];
9451
9480
  /** Memory directory/directories on the WORKER fs. If set, the voice agent gets Remember + Recall
9452
9481
  * tools directly (no delegation needed) and implicit capture guidance. */
9453
9482
  memoryDir;
@@ -9455,6 +9484,60 @@ var DuplexAgentOptions = class {
9455
9484
  memoryUserDir;
9456
9485
  };
9457
9486
  var SESSION_ID_RE = /^\d{8}-\d{6}(?:-[\w-]+)?$/;
9487
+ var MID_PHRASE_WORDS = /* @__PURE__ */ new Set([
9488
+ "slash",
9489
+ "backslash",
9490
+ "dash",
9491
+ "hyphen",
9492
+ "dot",
9493
+ "underscore",
9494
+ "colon",
9495
+ "comma",
9496
+ "and",
9497
+ "or",
9498
+ "but",
9499
+ "so",
9500
+ "because",
9501
+ "if",
9502
+ "then",
9503
+ "called",
9504
+ "named",
9505
+ "the",
9506
+ "a",
9507
+ "an",
9508
+ "my",
9509
+ "your",
9510
+ "our",
9511
+ "their",
9512
+ "is",
9513
+ "are",
9514
+ "um",
9515
+ "uh"
9516
+ ]);
9517
+ var TRAILING_PREPS = /* @__PURE__ */ new Set(["to", "for", "with", "about", "of", "at", "in", "on", "from", "by", "into", "under", "inside"]);
9518
+ var QUESTION_START = /^(?:what|who|whom|whose|where|when|why|how|which|is|are|was|were|do|does|did|can|could|will|would|should|have|has)\b/i;
9519
+ var PHRASAL_HOST = /* @__PURE__ */ new Set(["it", "this", "that", "them", "him", "her", "me", "us", "you", "up", "out", "off", "down", "back", "over", "away"]);
9520
+ function endsMidPhrase(text) {
9521
+ const t = text.split("\n[")[0].trim();
9522
+ if (!t || /[.?!…]["')\]]*$/.test(t)) return false;
9523
+ if (/\b[a-z][\w+.-]*:\/\/\S+$/i.test(t)) return false;
9524
+ if (/[,/\\:\-–—]$/.test(t)) return true;
9525
+ const [last, prev] = (t.toLowerCase().match(/[\p{L}']+/gu) ?? []).reverse();
9526
+ if (!last) return false;
9527
+ if (TRAILING_PREPS.has(last)) return !QUESTION_START.test(t) && !PHRASAL_HOST.has(prev);
9528
+ return MID_PHRASE_WORDS.has(last);
9529
+ }
9530
+ function nameScore(want, have) {
9531
+ const a = want.toLowerCase().replace(/[^\p{L}\p{N}]/gu, ""), b = have.toLowerCase().replace(/[^\p{L}\p{N}]/gu, "");
9532
+ if (!a || !b) return 0;
9533
+ let pre = 0;
9534
+ while (pre < a.length && a[pre] === b[pre]) pre++;
9535
+ const grams = (x) => new Set(Array.from({ length: Math.max(0, x.length - 1) }, (_, i) => x.slice(i, i + 2)));
9536
+ const ga = grams(a), gb = grams(b);
9537
+ let common = 0;
9538
+ for (const g of ga) if (gb.has(g)) common++;
9539
+ return pre * 2 + 2 * common / (ga.size + gb.size || 1);
9540
+ }
9458
9541
  var RESERVED_EVENT_MARKER = /\[task\b[^\]\n]*\b(?:completed|failed|progress|asks)\b/i;
9459
9542
  var RESERVED_EVENT_OPENER = /\[\s*task\b/i;
9460
9543
  var STAGE_DIRECTION_RE = /^\(\s*(?:(?:waiting|checking|searching|thinking|processing|loading|working|fetching|looking)\b[^)]*|[^)]*(?:\.\.\.|…)\s*)\)$/i;
@@ -9477,11 +9560,11 @@ function isOfferAcceptance(text) {
9477
9560
  }
9478
9561
  var isQuestion = (s) => /\?["'”’)\]]*$/.test(s.trim());
9479
9562
  var OFFER_OVERRUN = 150;
9480
- 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 exists ONLY once the task finishes (the worker speaks it, and `TaskStatus` then returns it); 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.';
9563
+ 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 exists ONLY once the task finishes (the worker speaks it, and `TaskStatus` then returns it); 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 \u2014 to stop everything ("stop all", "cancel everything") pass id "all". When the user only ADDS to or CORRECTS a request whose task is still running (a detail, a path, a name, a spelling), call `Act` with `refines` set to that task id \u2014 it updates the running worker in place; never cancel and re-dispatch for a refinement.\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 (audio transcribed to text) and can carry transcription errors \u2014 odd words, cut-offs, homophones ("for you" vs "folder"), and especially MISHEARD NAMES: a surname, company, or project name often comes out as ordinary sound-alike words. Read for INTENT, not surface text, and do not silently rewrite what they said. If a message seems garbled, surprising, or only half-parses, or a word sounds like a name you already know (from memory or this conversation) but is spelled differently, treat it with suspicion \u2014 do NOT act on the odd word blindly or improvise content from it; briefly confirm what they meant ("did you mean\u2026?") and wait. A one-line confirm beats a confident wrong answer. NEVER save to memory a name, spelling, or term you only HEARD (it may be a transcription error) \u2014 when the user spells something aloud, read the spelling back and get a yes before storing it.';
9481
9564
  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.";
9482
9565
  var THINK_DISABLED_GUIDANCE = "(Think tier is not available \u2014 use Act for all escalations.)";
9483
9566
  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).`;
9484
- 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(", ")}.`;
9567
+ var EMOTION_TAGS_GUIDANCE = `EMOTION: your voice is synthesized with emotion control. Prefix a sentence with an inline emotion tag \u2014 ONE emotion word from the list below in square brackets, the word alone (never the word "emotion" itself, never a guess or a question mark), 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(", ")}.`;
9485
9568
  var DuplexAgent = class _DuplexAgent {
9486
9569
  options;
9487
9570
  voice;
@@ -9542,6 +9625,10 @@ var DuplexAgent = class _DuplexAgent {
9542
9625
  // reflex emitted a reserved [task …] marker → suppress its tail
9543
9626
  leakCuts = [];
9544
9627
  // heads of analysis-register leaks cut this turn — scrubbed from the transcript at turn end
9628
+ midPhraseBounced = false;
9629
+ // this turn's dispatch on a mid-phrase fragment was already bounced to Hold
9630
+ repeatCuts = [];
9631
+ // same-turn repeated sentences skipped this turn — their LATER copy is scrubbed from the transcript
9545
9632
  leakStep = false;
9546
9633
  // the CURRENT step's tail is muted by a leak cut (the next step speaks again, unlike a fabricated marker)
9547
9634
  leakHit = false;
@@ -9705,7 +9792,7 @@ ${nowLine()}. Anchor every relative or time-sensitive reference \u2014 "today",
9705
9792
  pumpReflex(final) {
9706
9793
  for (; ; ) {
9707
9794
  if (this.leakStep) return;
9708
- this.scrubStageDirections();
9795
+ this.scrubUnforwarded(final);
9709
9796
  const from = this.reflexForwarded;
9710
9797
  const buf = this.reflexBuf;
9711
9798
  const lastMark = Math.max(from, ...this.stepMarks);
@@ -9715,6 +9802,8 @@ ${nowLine()}. Anchor every relative or time-sensitive reference \u2014 "today",
9715
9802
  if (tail) upto -= tail[0].length;
9716
9803
  const paren = buf.lastIndexOf("(");
9717
9804
  if (paren >= lastMark && !buf.includes(")", paren) && buf.length - paren <= 80) upto = Math.min(upto, paren);
9805
+ const brk = buf.lastIndexOf("[");
9806
+ if (brk >= lastMark && !buf.includes("]", brk) && buf.length - brk <= 60) upto = Math.min(upto, brk);
9718
9807
  }
9719
9808
  if (upto <= from) return;
9720
9809
  const region = buf.slice(from, upto);
@@ -9722,9 +9811,14 @@ ${nowLine()}. Anchor every relative or time-sensitive reference \u2014 "today",
9722
9811
  for (const k of this.stepMarks) if (k > from && k <= upto) ends.push(k - from);
9723
9812
  if (final || !ends.length && region.length >= 160) ends.push(region.length);
9724
9813
  ends.sort((a, b) => a - b);
9725
- let ok = 0, leak;
9814
+ let ok = 0, leak, repeat;
9726
9815
  for (const e of ends) {
9727
9816
  if (e <= ok) continue;
9817
+ const sent = region.slice(ok, e);
9818
+ if (sent.trim() && !/[\p{L}\p{N}]/u.test(sent) || isRepeatOf(sent, this.turnSpoken + region.slice(0, ok))) {
9819
+ repeat = e;
9820
+ break;
9821
+ }
9728
9822
  const v = this.leakVerdict(region.slice(ok, e));
9729
9823
  if (v === void 0) break;
9730
9824
  if (v) {
@@ -9734,6 +9828,15 @@ ${nowLine()}. Anchor every relative or time-sensitive reference \u2014 "today",
9734
9828
  ok = e;
9735
9829
  }
9736
9830
  this.forwardReflex(from + ok);
9831
+ if (repeat !== void 0) {
9832
+ const cut = region.slice(ok, repeat).trim();
9833
+ if (/[\p{L}\p{N}]/u.test(cut)) {
9834
+ this.repeatCuts.push(cut);
9835
+ this.notify("diag", "reflex_repeat", { text: cut.slice(0, 80) });
9836
+ }
9837
+ this.reflexForwarded = from + repeat;
9838
+ continue;
9839
+ }
9737
9840
  if (leak === void 0) return;
9738
9841
  const at = from + ok;
9739
9842
  this.leakHit = true;
@@ -9808,6 +9911,22 @@ ${nowLine()}. Anchor every relative or time-sensitive reference \u2014 "today",
9808
9911
  scrubLeakFromTranscript() {
9809
9912
  const keys = this.leakCuts.splice(0);
9810
9913
  const t = this.voice.transcript;
9914
+ for (let i = this.turnBase; i < t.length; i++) {
9915
+ const m = t[i];
9916
+ if (m.role === "assistant" && typeof m.content === "string") m.content = scrubSpokenJunk(m.content, true).trim();
9917
+ }
9918
+ for (const cut of this.repeatCuts.splice(0)) {
9919
+ const rep = cut.replace(/^(?:\[[^\]]*\]\s*)+/, "");
9920
+ if (!rep) continue;
9921
+ for (let i = t.length - 1; i >= this.turnBase; i--) {
9922
+ const m = t[i];
9923
+ if (m.role !== "assistant" || typeof m.content !== "string") continue;
9924
+ const at = m.content.lastIndexOf(rep);
9925
+ if (at <= 0 && !(at === 0 && t.slice(this.turnBase, i).some((x) => x.role === "assistant" && contentText(x.content).includes(rep)))) continue;
9926
+ m.content = (m.content.slice(0, at).replace(/\[[^\]]*\]\s*$/, "") + m.content.slice(at + rep.length)).trim();
9927
+ break;
9928
+ }
9929
+ }
9811
9930
  for (const key of keys) {
9812
9931
  let i = t.length - 1;
9813
9932
  while (i >= this.turnBase && !(t[i].role === "assistant" && typeof t[i].content === "string" && t[i].content.includes(key))) i--;
@@ -9854,14 +9973,25 @@ ${nowLine()}. Anchor every relative or time-sensitive reference \u2014 "today",
9854
9973
  if (this.silentTurn && res?.finishReason === "error" && refusedCall(res.error)) this.emitHost({ kind: "text_delta", message: fallback ?? _DuplexAgent.FALLBACK_ERROR });
9855
9974
  else if (this.silentTurn) await this.ackIfSilent(fallback);
9856
9975
  }
9857
- /** Remove complete stage-direction parentheticals from the UNFORWARDED reflex text (STAGE_DIRECTION_RE).
9858
- * Only the unforwarded region is touched — already-spoken audio can't be unsent, and splicing before
9859
- * reflexForwarded would corrupt the forward offset. */
9860
- scrubStageDirections() {
9861
- if (this.reflexForwarded >= this.reflexBuf.length) return;
9862
- const region = this.reflexBuf.slice(this.reflexForwarded);
9863
- const scrubbed = region.replace(/\([^()]*\)/g, (s) => STAGE_DIRECTION_RE.test(s) ? "" : s);
9864
- if (scrubbed !== region) this.reflexBuf = this.reflexBuf.slice(0, this.reflexForwarded) + scrubbed;
9976
+ /** Rewrite the UNFORWARDED reflex text: drop complete stage-direction parentheticals (STAGE_DIRECTION_RE) and spoken
9977
+ * junk (scrubSpokenJunk). Only the unforwarded region is touched — already-spoken audio can't be unsent, and
9978
+ * splicing before reflexForwarded would corrupt the forward offset. Rewritten per step segment so the stepMarks
9979
+ * after it move with the text (a mark is a reflexBuf offset); a segment that ends at a step mark is complete. */
9980
+ scrubUnforwarded(final) {
9981
+ const from = this.reflexForwarded, buf = this.reflexBuf;
9982
+ if (from >= buf.length) return;
9983
+ const scrub = (seg, complete) => scrubSpokenJunk(seg.replace(/\([^()]*\)/g, (x) => STAGE_DIRECTION_RE.test(x) ? "" : x), complete);
9984
+ const marks = new Set(this.stepMarks.filter((k) => k > from && k <= buf.length));
9985
+ let out = buf.slice(0, from), at = from;
9986
+ const moved = /* @__PURE__ */ new Map();
9987
+ for (const k of [.../* @__PURE__ */ new Set([...marks, buf.length])].sort((x, y) => x - y)) {
9988
+ out += scrub(buf.slice(at, k), final || marks.has(k));
9989
+ moved.set(k, out.length);
9990
+ at = k;
9991
+ }
9992
+ if (out === buf) return;
9993
+ this.reflexBuf = out;
9994
+ this.stepMarks = this.stepMarks.map((k) => moved.get(k) ?? k);
9865
9995
  }
9866
9996
  /** Clear the per-turn guards. Called at the head of every voice turn (user send + re-voice flush). */
9867
9997
  resetTurn() {
@@ -9875,6 +10005,8 @@ ${nowLine()}. Anchor every relative or time-sensitive reference \u2014 "today",
9875
10005
  this.reflexForwarded = 0;
9876
10006
  this.fabricationCut = false;
9877
10007
  this.leakCuts = [];
10008
+ this.repeatCuts = [];
10009
+ this.midPhraseBounced = false;
9878
10010
  this.leakStep = this.leakHit = false;
9879
10011
  this.stepMarks = [];
9880
10012
  this.leakVerdicts.clear();
@@ -9898,6 +10030,13 @@ ${nowLine()}. Anchor every relative or time-sensitive reference \u2014 "today",
9898
10030
  return { block: true, reason: "Speculative turn aborted." };
9899
10031
  }
9900
10032
  if (this.nudging) return { block: true, reason: "Just say one short spoken acknowledgement \u2014 no tools this turn." };
10033
+ if ((call.name === "Act" || call.name === "Think") && !this.turnDispatched && !this.midPhraseBounced) {
10034
+ const said = [...this.voice.transcript].reverse().find((m) => m.role === "user");
10035
+ if (said && endsMidPhrase(contentText(said.content))) {
10036
+ this.midPhraseBounced = true;
10037
+ return { block: true, reason: "The user stopped mid-phrase \u2014 the rest of their request is still coming. Call Hold now (no filler) and wait for it; do not dispatch on a fragment." };
10038
+ }
10039
+ }
9901
10040
  if (!this.turnDispatched) return;
9902
10041
  if (call.name === "TaskStatus")
9903
10042
  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." };
@@ -10231,6 +10370,20 @@ ${nowLine()}. Anchor every relative or time-sensitive reference \u2014 "today",
10231
10370
  spec.decide("abort");
10232
10371
  this.notify("diag", "speculation_aborted", { text: spec.text.slice(0, 80) });
10233
10372
  }
10373
+ /** Fold a refinement into a RUNNING task's worker (Agent.inject — picked up at its next step) instead of cancel +
10374
+ * respawn: live 20261013-085238 one request spoken over three fragments became t5 → cancel → t6 → cancel → t7, each
10375
+ * worker restarting from zero. Returns the id when amended, undefined when the task is not running (→ dispatch new). */
10376
+ amendTask(id, brief) {
10377
+ const rec = this.tasks.get(id);
10378
+ if (!rec || rec.status !== "running" || !rec.worker || !brief.trim()) return void 0;
10379
+ rec.worker.inject(`[update from the user while you work \u2014 fold it into the SAME task, do not start over]
10380
+ ${brief}`);
10381
+ rec.brief += `
10382
+
10383
+ Update: ${brief}`;
10384
+ this.notify("diag", "task_amended", { id, brief: brief.slice(0, 80) });
10385
+ return rec.id;
10386
+ }
10234
10387
  /** Cancel a running background task — shared by the CancelTask tool and the CLI /tasks picker. */
10235
10388
  cancelTask(id) {
10236
10389
  const rec = this.tasks.get(id);
@@ -10517,14 +10670,15 @@ ${recent}` : brief) + verify + deliverContract;
10517
10670
  signal: controller.signal
10518
10671
  // shared with the checker so a cancel tears down both
10519
10672
  };
10520
- const promise = new Agent(agentOpts).run(briefText).then((res) => {
10673
+ const worker = new Agent(agentOpts);
10674
+ const promise = worker.run(briefText).then((res) => {
10521
10675
  const { spoken, detail } = splitter.flush();
10522
10676
  feedSpoken(spoken);
10523
10677
  if (detail.trim()) pushTail(detail.trim());
10524
10678
  flushSpoken();
10525
10679
  return res;
10526
10680
  }).then((res) => this.maybeVerify(id, brief, res, tier, agentOpts, askBridge)).then((res) => this.onWorkerSettled(id, res)).catch((err) => this.onWorkerFailed(id, err));
10527
- this.tasks.set(id, { id, label, status: "running", controller, promise, tail, brief, followUp, splitter, createdTurn: this.turn });
10681
+ this.tasks.set(id, { id, label, status: "running", controller, promise, tail, brief, followUp, splitter, createdTurn: this.turn, worker });
10528
10682
  if (this.tasks.size > this.options.maxTaskRecords)
10529
10683
  for (const [tid, rec] of this.tasks) {
10530
10684
  if (this.tasks.size <= this.options.maxTaskRecords) break;
@@ -10777,14 +10931,17 @@ Another agent just implemented the above. Independently check the CURRENT state
10777
10931
  required: ["brief"],
10778
10932
  properties: {
10779
10933
  brief: { type: "string", description: "full, self-contained instructions for the worker" },
10780
- label: { type: "string", description: "a short (2-4 word) label for the task" }
10934
+ label: { type: "string", description: "a short (2-4 word) label for the task" },
10935
+ refines: { type: "string", description: "id of a STILL-RUNNING task this message only adds detail to or corrects (a path, a name, a spelling) \u2014 the running worker is updated in place instead of starting a new task" }
10781
10936
  }
10782
10937
  },
10783
- run: async ({ brief, label }) => {
10938
+ run: async ({ brief, label, refines }) => {
10784
10939
  this.spokeBeforeDispatch = this.spokeThisTurn;
10785
10940
  this.turnDispatched = true;
10786
10941
  this.turnBriefs.add(String(brief ?? ""));
10787
10942
  this.voice.options.toolChoice = "none";
10943
+ const amended = refines ? this.amendTask(String(refines), String(brief ?? "")) : void 0;
10944
+ if (amended) return this.dispatchResult(amended, "Updated the running");
10788
10945
  const id = await this.dispatch(String(brief ?? ""), "act", label ? String(label) : void 0, this.turnFollowUp);
10789
10946
  return this.dispatchResult(id, "Acting on");
10790
10947
  }
@@ -10882,29 +11039,36 @@ Another agent just implemented the above. Independently check the CURRENT state
10882
11039
  case "ls": {
10883
11040
  if (!fs) return "unavailable (no filesystem)";
10884
11041
  const p = String(path ?? ".");
10885
- try {
10886
- const names = await fs.readDir(p);
10887
- return names.slice(0, 50).join("\n") + (names.length > 50 ? `
10888
- \u2026 (+${names.length - 50} more)` : "");
10889
- } catch {
10890
- const names = await fs.readDir(".").catch(() => []);
10891
- return `'${p}' not found here \u2014 you are likely already inside it. Current directory listing:
10892
- ` + names.slice(0, 50).join("\n") + (names.length > 50 ? `
11042
+ const list = (at, names) => (at === p ? "" : `(${at})
11043
+ `) + names.slice(0, 50).join("\n") + (names.length > 50 ? `
10893
11044
  \u2026 (+${names.length - 50} more)` : "");
11045
+ for (const at of this.lookCandidates(p)) {
11046
+ try {
11047
+ return list(at, await fs.readDir(at));
11048
+ } catch {
11049
+ }
10894
11050
  }
11051
+ const cwd = (fs.getCwd?.() ?? "").replace(/\/+$/, "");
11052
+ if (cwd && p.replace(/^\.\/|\/+$/g, "") === cwd.split("/").pop()) return `'${p}' is the current directory:
11053
+ ` + list(".", await fs.readDir(".").catch(() => []));
11054
+ return await this.lookMiss(p);
10895
11055
  }
10896
11056
  case "file": {
10897
11057
  if (!fs) return "unavailable (no filesystem)";
10898
11058
  if (!path) return "file lookup needs a path";
10899
- try {
10900
- const text = await fs.readFile(String(path));
10901
- return text.length > CAP ? text.slice(0, CAP) + `
10902
- \u2026 (truncated \u2014 ${text.length} chars total; Act for the full file)` : text;
10903
- } catch {
10904
- const names = await fs.readDir(".").catch(() => []);
10905
- return `'${path}' not found. Current directory contains:
10906
- ` + names.slice(0, 50).join("\n");
11059
+ for (const at of this.lookCandidates(String(path))) {
11060
+ let text;
11061
+ try {
11062
+ text = await fs.readFile(at);
11063
+ } catch {
11064
+ continue;
11065
+ }
11066
+ const head = at === String(path) ? "" : `(${at})
11067
+ `;
11068
+ return head + (text.length > CAP ? text.slice(0, CAP) + `
11069
+ \u2026 (truncated \u2014 ${text.length} chars total; Act for the full file)` : text);
10907
11070
  }
11071
+ return await this.lookMiss(String(path));
10908
11072
  }
10909
11073
  default:
10910
11074
  return `unknown lookup '${what}'`;
@@ -10915,6 +11079,41 @@ Another agent just implemented the above. Independently check the CURRENT state
10915
11079
  }
10916
11080
  };
10917
11081
  }
11082
+ /** Where QuickLook tries a path: as given (cwd-relative or absolute), then — relative only — under each lookRoot. */
11083
+ lookCandidates(p) {
11084
+ const rel = p.replace(/^~\/?/, "");
11085
+ const roots = this.options.lookRoots;
11086
+ if (p.startsWith("~")) return roots.length ? [`${roots[0].replace(/\/+$/, "")}/${rel}`.replace(/\/$/, "")] : [p];
11087
+ if (p.startsWith("/")) return [p];
11088
+ return [p, ...roots.map((r) => `${r.replace(/\/+$/, "")}/${rel}`)];
11089
+ }
11090
+ /** A QuickLook path not found anywhere: say where it looked and, at the deepest folder that DID exist, the few closest
11091
+ * names (a mis-heard segment — "Lead Sheets" for "Livshitz" — is usually one of them). Never the whole cwd listing:
11092
+ * live 20261013-085238 dumped it three times for three spellings of the same path. */
11093
+ async lookMiss(p) {
11094
+ const fs = this.options.fs;
11095
+ const segs = p.replace(/^~\/?/, "").split("/").filter((x) => x && x !== ".");
11096
+ const bases = p.startsWith("/") ? ["/"] : p.startsWith("~") ? this.options.lookRoots.slice(0, 1) : [".", ...this.options.lookRoots];
11097
+ let best;
11098
+ for (const base of bases) {
11099
+ let dir = base;
11100
+ for (let i = 0; i < segs.length; i++) {
11101
+ const names = await fs.readDir(dir).catch(() => void 0);
11102
+ if (!names) break;
11103
+ const hit = names.find((n) => n.toLowerCase() === segs[i].toLowerCase());
11104
+ if (!hit) {
11105
+ if (i > (best?.depth ?? -1)) best = { dir, depth: i, names };
11106
+ break;
11107
+ }
11108
+ dir = dir === "." ? hit : `${dir.replace(/\/+$/, "")}/${hit}`;
11109
+ }
11110
+ }
11111
+ const where = ["the current folder", ...this.options.lookRoots].join(", ");
11112
+ if (!best || !best.names.length) return `'${p}' not found (looked under ${where}). Ask the user for the exact path, or Act to search for it.`;
11113
+ const missing = segs[best.depth];
11114
+ const close = [...best.names].sort((x, y) => nameScore(missing, y) - nameScore(missing, x)).slice(0, 6);
11115
+ return `'${p}' not found (looked under ${where}). '${missing}' is not in ${best.dir} \u2014 closest names there: ${close.join(", ")}. If one of these is what they meant (speech-to-text often mishears names), use it; otherwise ask the user or Act to search.`;
11116
+ }
10918
11117
  answerTaskTool() {
10919
11118
  return {
10920
11119
  name: "AnswerTask",
@@ -10952,13 +11151,21 @@ Another agent just implemented the above. Independently check the CURRENT state
10952
11151
  cancelTaskTool() {
10953
11152
  return {
10954
11153
  name: "CancelTask",
10955
- description: "Cancel a running background task by id.",
10956
- parameters: { type: "object", required: ["id"], properties: { id: { type: "string" } } },
11154
+ description: 'Cancel a running background task by id \u2014 or id "all" to cancel EVERY running task (the user said "stop everything", "stop all the searches").',
11155
+ parameters: { type: "object", required: ["id"], properties: { id: { type: "string", description: 'a task id, or "all"' } } },
10957
11156
  // Cancel-and-redirect ("stop — do Y instead") is ONE user line: live, the reflex cancelled, said "fetching Y now" and
10958
11157
  // never dispatched (2/5 Bare voice runs). The tool result is where it looks next — tell it the redirect needs Act.
11158
+ // "Stop all the searches" cancelled one task (and hit a done one) and left t4 running (live 20261013-085238): the
11159
+ // result always names what is STILL running, and "all" stops every one in a single call.
10959
11160
  run: async ({ id }) => {
10960
- const r = this.cancelTask(String(id));
10961
- return this.tasks.get(String(id))?.status === "cancelled" && r.endsWith("cancelled.") ? `${r} If the user's message ALSO asked for different work (a redirect \u2014 "instead\u2026", "actually\u2026", "do Y"), call Act NOW with that new brief: saying you are on it without calling Act does nothing. If they only asked to stop, just acknowledge in a few words.` : r;
11161
+ const want = String(id ?? "").trim();
11162
+ const running = () => [...this.tasks.values()].filter((t) => t.status === "running");
11163
+ const ids = /^(?:all|\*|everything)$/i.test(want) ? running().map((t) => t.id) : [want];
11164
+ const lines = ids.length ? ids.map((x) => this.cancelTask(x)) : ["No running tasks."];
11165
+ const left = running();
11166
+ const tail = left.length ? ` Still running: ${left.map((t) => `${t.id} (${t.label})`).join(", ")} \u2014 if the user asked to stop ALL, cancel these too (or call CancelTask with id "all").` : " No tasks are running now.";
11167
+ const cancelled = ids.some((x) => this.tasks.get(x)?.status === "cancelled");
11168
+ return lines.join(" ") + tail + (cancelled ? ` If the user's message ALSO asked for different work (a redirect \u2014 "instead\u2026", "actually\u2026", "do Y"), call Act NOW with that new brief: saying you are on it without calling Act does nothing. If they only asked to stop, just acknowledge in a few words.` : "");
10962
11169
  }
10963
11170
  };
10964
11171
  }