reasonix 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -334,7 +334,7 @@ async function harvest(reasoningContent, client, options = {}, signal) {
334
334
  const minLen = options.minReasoningLen ?? 40;
335
335
  const trimmed = reasoningContent.trim();
336
336
  if (trimmed.length < minLen) return emptyPlanState();
337
- const model = options.model ?? "deepseek-chat";
337
+ const model = options.model ?? "deepseek-v4-flash";
338
338
  const maxItems = options.maxItems ?? 5;
339
339
  const maxItemLen = options.maxItemLen ?? 80;
340
340
  const system = SYSTEM_PROMPT.replace("{maxItems}", String(maxItems)).replace(
@@ -1729,8 +1729,9 @@ var ARGS_COMPACT_THRESHOLD_TOKENS = 800;
1729
1729
  var TURN_END_RESULT_CAP_TOKENS = 3e3;
1730
1730
  var FAILURE_ESCALATION_THRESHOLD = 3;
1731
1731
  var ESCALATION_MODEL = "deepseek-v4-pro";
1732
- var NEEDS_PRO_MARKER = "<<<NEEDS_PRO>>>";
1733
- var NEEDS_PRO_BUFFER_CHARS = 80;
1732
+ var NEEDS_PRO_MARKER_PREFIX = "<<<NEEDS_PRO";
1733
+ var NEEDS_PRO_MARKER_RE = /^<<<NEEDS_PRO(?::\s*([^>]*))?>>>/;
1734
+ var NEEDS_PRO_BUFFER_CHARS = 256;
1734
1735
  var CacheFirstLoop = class {
1735
1736
  client;
1736
1737
  prefix;
@@ -1796,6 +1797,14 @@ var CacheFirstLoop = class {
1796
1797
  * the user doesn't watch flash retry the same edit 5 times.
1797
1798
  */
1798
1799
  _turnFailureCount = 0;
1800
+ /**
1801
+ * Per-type breakdown of failure signals counted toward the turn's
1802
+ * auto-escalation threshold. Surfaced in the warning when the
1803
+ * threshold trips so the user sees what kind of trouble flash
1804
+ * actually hit ("3× search-mismatch, 2× truncated") rather than
1805
+ * just a bare count. Reset alongside _turnFailureCount.
1806
+ */
1807
+ _turnFailureTypes = {};
1799
1808
  constructor(opts) {
1800
1809
  this.client = opts.client;
1801
1810
  this.prefix = opts.prefix;
@@ -1823,10 +1832,11 @@ var CacheFirstLoop = class {
1823
1832
  this.sessionName = opts.session ?? null;
1824
1833
  if (this.sessionName) {
1825
1834
  const prior = loadSessionMessages(this.sessionName);
1826
- const { messages, healedCount, tokensSaved } = healLoadedMessagesByTokens(
1827
- prior,
1828
- DEFAULT_MAX_RESULT_TOKENS
1829
- );
1835
+ const shrunk = healLoadedMessagesByTokens(prior, DEFAULT_MAX_RESULT_TOKENS);
1836
+ const stamped = stampMissingReasoningForThinkingMode(shrunk.messages, this.model);
1837
+ const messages = stamped.messages;
1838
+ const healedCount = shrunk.healedCount + stamped.stampedCount;
1839
+ const tokensSaved = shrunk.tokensSaved;
1830
1840
  for (const msg of messages) this.log.append(msg);
1831
1841
  this.resumedMessageCount = messages.length;
1832
1842
  if (healedCount > 0) {
@@ -2053,15 +2063,41 @@ var CacheFirstLoop = class {
2053
2063
  return this._escalateThisTurn ? ESCALATION_MODEL : this.model;
2054
2064
  }
2055
2065
  /**
2056
- * True when the assistant's content is a self-reported escalation
2057
- * request. Only the FIRST line matters the model is instructed
2058
- * to emit the marker as the first output token if at all. Matching
2059
- * anywhere else in the text is a normal content reference (e.g.
2060
- * the user asked about the marker itself, or prose that happens
2061
- * to contain angle-brackets).
2066
+ * Parse the escalation marker out of the model's leading content.
2067
+ * Returns `{ matched: true, reason? }` for both bare and reason-
2068
+ * carrying forms. Only the FIRST line matters the model is
2069
+ * instructed to emit the marker as the first output token if at
2070
+ * all. Matches anywhere else in the text are normal content
2071
+ * references (e.g. the user asked about the marker itself).
2062
2072
  */
2073
+ parseEscalationMarker(content) {
2074
+ const m = NEEDS_PRO_MARKER_RE.exec(content.trimStart());
2075
+ if (!m) return { matched: false };
2076
+ const reason = m[1]?.trim();
2077
+ return { matched: true, reason: reason || void 0 };
2078
+ }
2079
+ /** Convenience boolean — same gate the streaming path used to call. */
2063
2080
  isEscalationRequest(content) {
2064
- return content.trimStart().startsWith(NEEDS_PRO_MARKER);
2081
+ return this.parseEscalationMarker(content).matched;
2082
+ }
2083
+ /**
2084
+ * Could `buf` STILL plausibly become the full marker as more chunks
2085
+ * arrive? Drives the streaming buffer's flush decision: while this
2086
+ * is true we keep accumulating; once it's false (or the buffer
2087
+ * exceeds the byte limit) we flush so the user isn't staring at a
2088
+ * delayed display for arbitrary content that just happens to start
2089
+ * with `<`.
2090
+ */
2091
+ looksLikePartialEscalationMarker(buf) {
2092
+ const t = buf.trimStart();
2093
+ if (t.length === 0) return true;
2094
+ if (t.length <= NEEDS_PRO_MARKER_PREFIX.length) {
2095
+ return NEEDS_PRO_MARKER_PREFIX.startsWith(t);
2096
+ }
2097
+ if (!t.startsWith(NEEDS_PRO_MARKER_PREFIX)) return false;
2098
+ const rest = t.slice(NEEDS_PRO_MARKER_PREFIX.length);
2099
+ if (rest[0] !== ">" && rest[0] !== ":") return false;
2100
+ return true;
2065
2101
  }
2066
2102
  /**
2067
2103
  * Check whether a tool result string looks like a "flash struggled"
@@ -2075,16 +2111,18 @@ var CacheFirstLoop = class {
2075
2111
  */
2076
2112
  noteToolFailureSignal(resultJson, repair) {
2077
2113
  let bumped = false;
2078
- if (resultJson.includes('"error"') && resultJson.includes("search text not found")) {
2079
- this._turnFailureCount += 1;
2114
+ const bump = (kind, by = 1) => {
2115
+ this._turnFailureCount += by;
2116
+ this._turnFailureTypes[kind] = (this._turnFailureTypes[kind] ?? 0) + by;
2080
2117
  bumped = true;
2118
+ };
2119
+ if (resultJson.includes('"error"') && resultJson.includes("search text not found")) {
2120
+ bump("search-mismatch");
2081
2121
  }
2082
2122
  if (repair) {
2083
- const repairs = repair.scavenged + repair.truncationsFixed + repair.stormsBroken;
2084
- if (repairs > 0) {
2085
- this._turnFailureCount += repairs;
2086
- bumped = true;
2087
- }
2123
+ if (repair.scavenged > 0) bump("scavenged", repair.scavenged);
2124
+ if (repair.truncationsFixed > 0) bump("truncated", repair.truncationsFixed);
2125
+ if (repair.stormsBroken > 0) bump("storm-broken", repair.stormsBroken);
2088
2126
  }
2089
2127
  if (bumped && !this._escalateThisTurn && this._turnFailureCount >= FAILURE_ESCALATION_THRESHOLD) {
2090
2128
  this._escalateThisTurn = true;
@@ -2092,6 +2130,16 @@ var CacheFirstLoop = class {
2092
2130
  }
2093
2131
  return false;
2094
2132
  }
2133
+ /**
2134
+ * Render `_turnFailureTypes` as a comma-separated breakdown like
2135
+ * "2× search-mismatch, 1× truncated" for the auto-escalation
2136
+ * warning. Empty if no types have been recorded yet (defensive —
2137
+ * the warning sites only call this after a bump).
2138
+ */
2139
+ formatFailureBreakdown() {
2140
+ const parts = Object.entries(this._turnFailureTypes).filter(([, n]) => n > 0).map(([kind, n]) => `${n}\xD7 ${kind}`);
2141
+ return parts.length > 0 ? parts.join(", ") : `${this._turnFailureCount} repair/error signal(s)`;
2142
+ }
2095
2143
  buildMessages(pendingUser) {
2096
2144
  const healed = healLoadedMessages(this.log.toMessages(), DEFAULT_MAX_RESULT_CHARS);
2097
2145
  const msgs = [...this.prefix.toMessages(), ...healed.messages];
@@ -2147,6 +2195,7 @@ var CacheFirstLoop = class {
2147
2195
  this.scratch.reset();
2148
2196
  this.repair.resetStorm();
2149
2197
  this._turnFailureCount = 0;
2198
+ this._turnFailureTypes = {};
2150
2199
  this._escalateThisTurn = false;
2151
2200
  let armedConsumed = false;
2152
2201
  if (this._proArmedForNextTurn) {
@@ -2335,7 +2384,7 @@ var CacheFirstLoop = class {
2335
2384
  if (this.isEscalationRequest(escalationBuf)) {
2336
2385
  break;
2337
2386
  }
2338
- if (escalationBuf.length >= NEEDS_PRO_BUFFER_CHARS || escalationBuf.includes("\n")) {
2387
+ if (escalationBuf.length >= NEEDS_PRO_BUFFER_CHARS || !this.looksLikePartialEscalationMarker(escalationBuf)) {
2339
2388
  escalationBufFlushed = true;
2340
2389
  yield {
2341
2390
  turn: this._turn,
@@ -2430,11 +2479,13 @@ var CacheFirstLoop = class {
2430
2479
  return;
2431
2480
  }
2432
2481
  if (this.modelForCurrentCall() !== ESCALATION_MODEL && this.isEscalationRequest(assistantContent)) {
2482
+ const { reason } = this.parseEscalationMarker(assistantContent);
2433
2483
  this._escalateThisTurn = true;
2484
+ const reasonSuffix = reason ? ` \u2014 ${reason}` : "";
2434
2485
  yield {
2435
2486
  turn: this._turn,
2436
2487
  role: "warning",
2437
- content: `\u21E7 flash requested escalation \u2014 retrying this turn on ${ESCALATION_MODEL}`
2488
+ content: `\u21E7 flash requested escalation \u2014 retrying this turn on ${ESCALATION_MODEL}${reasonSuffix}`
2438
2489
  };
2439
2490
  assistantContent = "";
2440
2491
  reasoningContent = "";
@@ -2469,7 +2520,12 @@ var CacheFirstLoop = class {
2469
2520
  assistantContent || null
2470
2521
  );
2471
2522
  this.appendAndPersist(
2472
- this.assistantMessage(assistantContent, repairedCalls, reasoningContent)
2523
+ this.assistantMessage(
2524
+ assistantContent,
2525
+ repairedCalls,
2526
+ this.modelForCurrentCall(),
2527
+ reasoningContent
2528
+ )
2473
2529
  );
2474
2530
  yield {
2475
2531
  turn: this._turn,
@@ -2484,7 +2540,7 @@ var CacheFirstLoop = class {
2484
2540
  yield {
2485
2541
  turn: this._turn,
2486
2542
  role: "warning",
2487
- content: `\u21E7 auto-escalating to ${ESCALATION_MODEL} for the rest of this turn \u2014 flash hit ${this._turnFailureCount} repair/error signals. Next turn falls back to ${this.model} unless /pro is armed.`
2543
+ content: `\u21E7 auto-escalating to ${ESCALATION_MODEL} for the rest of this turn \u2014 flash hit ${this.formatFailureBreakdown()}. Next turn falls back to ${this.model} unless /pro is armed.`
2488
2544
  };
2489
2545
  }
2490
2546
  if (report.stormsBroken > 0) {
@@ -2608,7 +2664,7 @@ ${reason}`;
2608
2664
  yield {
2609
2665
  turn: this._turn,
2610
2666
  role: "warning",
2611
- content: `\u21E7 auto-escalating to ${ESCALATION_MODEL} for the rest of this turn \u2014 flash hit ${this._turnFailureCount} edit failure(s). Next turn falls back to ${this.model} unless /pro is armed.`
2667
+ content: `\u21E7 auto-escalating to ${ESCALATION_MODEL} for the rest of this turn \u2014 flash hit ${this.formatFailureBreakdown()}. Next turn falls back to ${this.model} unless /pro is armed.`
2612
2668
  };
2613
2669
  }
2614
2670
  yield {
@@ -2652,7 +2708,9 @@ ${reason}`;
2652
2708
 
2653
2709
  ${summary}`;
2654
2710
  const summaryStats = this.stats.record(this._turn, summaryModel, resp.usage ?? new Usage());
2655
- this.appendAndPersist(this.assistantMessage(summary, [], resp.reasoningContent ?? void 0));
2711
+ this.appendAndPersist(
2712
+ this.assistantMessage(summary, [], summaryModel, resp.reasoningContent)
2713
+ );
2656
2714
  yield {
2657
2715
  turn: this._turn,
2658
2716
  role: "assistant_final",
@@ -2683,28 +2741,39 @@ ${summary}`;
2683
2741
  }
2684
2742
  return final;
2685
2743
  }
2686
- assistantMessage(content, toolCalls, reasoningContent) {
2744
+ /**
2745
+ * Build an assistant message for the log. The `producingModel` arg is
2746
+ * the model that actually generated this turn (flash, pro, the
2747
+ * forced-summary flash call, `this.model` for synthetics, etc.) —
2748
+ * NOT `this.model`, because escalation + forced-summary can both
2749
+ * route a single turn to a different model.
2750
+ *
2751
+ * The single invariant this encodes: if the producing model is
2752
+ * thinking-mode, `reasoning_content` MUST be present on the
2753
+ * persisted message — even as an empty string. DeepSeek's validator
2754
+ * 400s the NEXT request if any historical thinking-mode assistant
2755
+ * turn is missing it. We used to gate on `reasoning.length > 0`,
2756
+ * which silently dropped the field whenever the stream emitted zero
2757
+ * reasoning deltas or the API returned `reasoning_content: null` —
2758
+ * both legitimate edge cases the 0.5.15/0.5.18 fixes missed.
2759
+ */
2760
+ assistantMessage(content, toolCalls, producingModel, reasoningContent) {
2687
2761
  const msg = { role: "assistant", content };
2688
2762
  if (toolCalls.length > 0) msg.tool_calls = toolCalls;
2689
- if (reasoningContent && reasoningContent.length > 0) {
2690
- msg.reasoning_content = reasoningContent;
2763
+ if (isThinkingModeModel(producingModel)) {
2764
+ msg.reasoning_content = reasoningContent ?? "";
2691
2765
  }
2692
2766
  return msg;
2693
2767
  }
2694
2768
  /**
2695
- * Build a synthetic assistant message we insert into the log without
2696
- * a real API round trip (abort notices, future system injections).
2697
- * Reasoner models reject follow-up requests whose assistant history
2698
- * is missing `reasoning_content`, so we stamp an empty-string
2699
- * placeholder on reasoner sessions to satisfy the validator. V3
2700
- * doesn't care — field stays absent there.
2769
+ * Synthetic assistant message (abort notices, future system injections)
2770
+ * no real API round trip. Delegates to {@link assistantMessage} with
2771
+ * `this.model` as the stand-in producer, so the same thinking-mode
2772
+ * invariant applies: reasoner sessions get an empty-string
2773
+ * `reasoning_content`; V3 sessions get nothing.
2701
2774
  */
2702
2775
  syntheticAssistantMessage(content) {
2703
- const msg = { role: "assistant", content };
2704
- if (isThinkingModeModel(this.model)) {
2705
- msg.reasoning_content = "";
2706
- }
2707
- return msg;
2776
+ return this.assistantMessage(content, [], this.model, "");
2708
2777
  }
2709
2778
  };
2710
2779
  function isThinkingModeModel(model) {
@@ -2897,6 +2966,19 @@ function healLoadedMessages(messages, maxChars) {
2897
2966
  const healedCount = shrunk.healedCount + paired.droppedAssistantCalls + paired.droppedStrayTools;
2898
2967
  return { messages: paired.messages, healedCount, healedFrom: shrunk.healedFrom };
2899
2968
  }
2969
+ function stampMissingReasoningForThinkingMode(messages, model) {
2970
+ if (!isThinkingModeModel(model)) {
2971
+ return { messages, stampedCount: 0 };
2972
+ }
2973
+ let stampedCount = 0;
2974
+ const out = messages.map((msg) => {
2975
+ if (msg.role !== "assistant") return msg;
2976
+ if (Object.hasOwn(msg, "reasoning_content")) return msg;
2977
+ stampedCount += 1;
2978
+ return { ...msg, reasoning_content: "" };
2979
+ });
2980
+ return { messages: out, stampedCount };
2981
+ }
2900
2982
  function healLoadedMessagesByTokens(messages, maxTokens) {
2901
2983
  const shrunk = shrinkOversizedToolResultsByTokens(messages, maxTokens);
2902
2984
  const paired = fixToolCallPairing(shrunk.messages);
@@ -3212,9 +3294,13 @@ var TUI_FORMATTING_RULES = `Formatting (rendered in a TUI with a real markdown r
3212
3294
  - For flow charts and diagrams: a plain bullet list with \`\u2192\` or \`\u2193\` between steps. Don't try to draw boxes-and-arrows in ASCII; it never survives word-wrap.`;
3213
3295
  var ESCALATION_CONTRACT = `Cost-aware escalation (when you're running on deepseek-v4-flash):
3214
3296
 
3215
- If a task CLEARLY exceeds what flash can do well \u2014 complex cross-file architecture refactors, subtle concurrency / security / correctness invariants you can't resolve with confidence, or a design trade-off you'd be guessing at \u2014 output the exact string \`<<<NEEDS_PRO>>>\` as the FIRST line of your response (nothing before it, not even whitespace on a separate line). This aborts the current call and retries this turn on deepseek-v4-pro, one shot. Do NOT emit any other content in the same response when you request escalation.
3297
+ If a task CLEARLY exceeds what flash can do well \u2014 complex cross-file architecture refactors, subtle concurrency / security / correctness invariants you can't resolve with confidence, or a design trade-off you'd be guessing at \u2014 output the marker as the FIRST line of your response (nothing before it, not even whitespace on a separate line). This aborts the current call and retries this turn on deepseek-v4-pro, one shot.
3298
+
3299
+ Two accepted forms:
3300
+ - \`<<<NEEDS_PRO>>>\` \u2014 bare marker, no rationale.
3301
+ - \`<<<NEEDS_PRO: <one-sentence reason>>>>\` \u2014 preferred. The reason text appears in the user-visible warning ("\u21E7 flash requested escalation \u2014 <your reason>"), so they understand WHY a more expensive call is happening. Keep it under ~150 chars, no newlines, no nested \`>\` characters. Examples: \`<<<NEEDS_PRO: cross-file refactor across 6 modules with circular imports>>>\` or \`<<<NEEDS_PRO: subtle session-token race; flash would likely miss the locking invariant>>>\`.
3216
3302
 
3217
- Use this sparingly. Normal tasks \u2014 reading files, small edits, clear bug fixes, straightforward feature additions \u2014 stay on flash. Request escalation ONLY when you would otherwise produce a guess or a visibly-mediocre answer. If in doubt, attempt the task on flash first; the system also escalates automatically if you hit 3+ repair / SEARCH-mismatch errors in a single turn.`;
3303
+ Do NOT emit any other content in the same response when you request escalation. Use this sparingly: normal tasks \u2014 reading files, small edits, clear bug fixes, straightforward feature additions \u2014 stay on flash. Request escalation ONLY when you would otherwise produce a guess or a visibly-mediocre answer. If in doubt, attempt the task on flash first; the system also escalates automatically if you hit 3+ repair / SEARCH-mismatch errors in a single turn (the user sees a typed breakdown).`;
3218
3304
  var NEGATIVE_CLAIM_RULE = `Negative claims ("X is missing", "Y isn't implemented", "there's no Z") are the #1 hallucination shape. They feel safe to write because no citation seems possible \u2014 but that's exactly why you must NOT write them on instinct.
3219
3305
 
3220
3306
  If you have a search tool (\`search_content\`, \`grep\`, web search), call it FIRST before asserting absence:
@@ -4439,28 +4525,233 @@ function registerMemoryTools(registry, opts = {}) {
4439
4525
  return registry;
4440
4526
  }
4441
4527
 
4442
- // src/tools/plan.ts
4528
+ // src/tools/choice.ts
4529
+ var ChoiceRequestedError = class extends Error {
4530
+ question;
4531
+ options;
4532
+ allowCustom;
4533
+ constructor(question, options, allowCustom) {
4534
+ super(
4535
+ "ChoiceRequestedError: choice submitted. STOP calling tools now \u2014 the TUI has shown the options to the user. Wait for their next message; it will either be 'user picked <id>' (carry on with that branch), 'user answered: <text>' (custom free-form reply; read and proceed), or 'user cancelled the choice' (drop the question and ask what they want instead). Don't call any tools in the meantime."
4536
+ );
4537
+ this.name = "ChoiceRequestedError";
4538
+ this.question = question;
4539
+ this.options = options;
4540
+ this.allowCustom = allowCustom;
4541
+ }
4542
+ toToolResult() {
4543
+ return {
4544
+ error: `${this.name}: ${this.message}`,
4545
+ question: this.question,
4546
+ options: this.options,
4547
+ allowCustom: this.allowCustom
4548
+ };
4549
+ }
4550
+ };
4551
+ function sanitizeOptions(raw) {
4552
+ if (!Array.isArray(raw)) return [];
4553
+ const out = [];
4554
+ const seen = /* @__PURE__ */ new Set();
4555
+ for (const entry of raw) {
4556
+ if (!entry || typeof entry !== "object") continue;
4557
+ const e = entry;
4558
+ const id = typeof e.id === "string" ? e.id.trim() : "";
4559
+ const title = typeof e.title === "string" ? e.title.trim() : "";
4560
+ if (!id || !title) continue;
4561
+ if (seen.has(id)) continue;
4562
+ seen.add(id);
4563
+ const summary = typeof e.summary === "string" ? e.summary.trim() || void 0 : void 0;
4564
+ const opt = { id, title };
4565
+ if (summary) opt.summary = summary;
4566
+ out.push(opt);
4567
+ }
4568
+ return out;
4569
+ }
4570
+ function registerChoiceTool(registry, opts = {}) {
4571
+ registry.register({
4572
+ name: "ask_choice",
4573
+ description: "Present 2\u20136 alternatives to the user. The principle: if the user is supposed to pick, the tool picks \u2014 you don't enumerate the choices as prose. Prose menus have no picker in this TUI, so the user gets a wall of text to scroll through and a letter to type, strictly worse than the magenta picker this tool renders. Call it whenever (a) the user has asked for options, (b) you've analyzed multiple approaches and the final call is theirs, or (c) it's a preference fork you can't resolve without them. Skip it when one option is clearly best (just do it, or submit_plan) or a free-form text answer fits (ask in prose). Keep option ids short and stable (A/B/C). Each option: title + optional summary. allowCustom=true when their real answer might not fit. Max 6 options \u2014 narrow first if more. A one-sentence lead-in before the call is fine; don't repeat the options in it.",
4574
+ readOnly: true,
4575
+ parameters: {
4576
+ type: "object",
4577
+ properties: {
4578
+ question: {
4579
+ type: "string",
4580
+ description: "The question to put in front of the user. One sentence. Don't repeat the options in the question text \u2014 the picker renders them separately."
4581
+ },
4582
+ options: {
4583
+ type: "array",
4584
+ description: "2\u20134 alternatives. Each needs a stable id and a short title; summary is optional.",
4585
+ items: {
4586
+ type: "object",
4587
+ properties: {
4588
+ id: { type: "string", description: "Short stable id (A, B, C, or option-1)." },
4589
+ title: { type: "string", description: "One-line title shown as the option label." },
4590
+ summary: {
4591
+ type: "string",
4592
+ description: "Optional. A second dimmed line with more detail. Keep under ~80 chars."
4593
+ }
4594
+ },
4595
+ required: ["id", "title"]
4596
+ }
4597
+ },
4598
+ allowCustom: {
4599
+ type: "boolean",
4600
+ description: "If true, the picker shows a 'Let me type my own answer' escape hatch. Default false. Turn on when the user's real answer might not fit any of your pre-defined options."
4601
+ }
4602
+ },
4603
+ required: ["question", "options"]
4604
+ },
4605
+ fn: async (args) => {
4606
+ const question = (args?.question ?? "").trim();
4607
+ if (!question) {
4608
+ throw new Error(
4609
+ "ask_choice: question is required \u2014 write one sentence explaining the decision."
4610
+ );
4611
+ }
4612
+ const options = sanitizeOptions(args?.options);
4613
+ if (options.length < 2) {
4614
+ throw new Error(
4615
+ "ask_choice: need at least 2 well-formed options (each with a non-empty id and title). If you just need a text answer, ask the user in plain assistant text instead."
4616
+ );
4617
+ }
4618
+ if (options.length > 6) {
4619
+ throw new Error(
4620
+ "ask_choice: too many options (max 6). If you really have this many branches, split into two sequential ask_choice calls or narrow down first."
4621
+ );
4622
+ }
4623
+ const allowCustom = args?.allowCustom === true;
4624
+ opts.onChoiceRequested?.(question, options);
4625
+ throw new ChoiceRequestedError(question, options, allowCustom);
4626
+ }
4627
+ });
4628
+ return registry;
4629
+ }
4630
+
4631
+ // src/tools/plan-errors.ts
4443
4632
  var PlanProposedError = class extends Error {
4444
4633
  plan;
4445
- constructor(plan) {
4634
+ steps;
4635
+ summary;
4636
+ constructor(plan, steps, summary) {
4446
4637
  super(
4447
4638
  "PlanProposedError: plan submitted. STOP calling tools now \u2014 the TUI has shown the plan to the user. Wait for their next message; it will either approve (you'll then implement the plan), request a refinement (you should explore more and submit an updated plan), or cancel (drop the plan and ask what they want instead). Don't call any tools in the meantime."
4448
4639
  );
4449
4640
  this.name = "PlanProposedError";
4450
4641
  this.plan = plan;
4642
+ this.steps = steps;
4643
+ this.summary = summary;
4451
4644
  }
4452
4645
  /**
4453
4646
  * Structured tool-result shape. Consumed by the TUI to extract the
4454
- * plan without regex-scraping the error message.
4647
+ * plan without regex-scraping the error message. Optional fields
4648
+ * are omitted from the payload when absent so consumers don't see
4649
+ * `undefined` keys in the JSON.
4455
4650
  */
4456
4651
  toToolResult() {
4457
- return { error: `${this.name}: ${this.message}`, plan: this.plan };
4652
+ const payload = {
4653
+ error: `${this.name}: ${this.message}`,
4654
+ plan: this.plan
4655
+ };
4656
+ if (this.steps && this.steps.length > 0) payload.steps = this.steps;
4657
+ if (this.summary) payload.summary = this.summary;
4658
+ return payload;
4458
4659
  }
4459
4660
  };
4460
- function registerPlanTool(registry, opts = {}) {
4661
+ var PlanCheckpointError = class extends Error {
4662
+ stepId;
4663
+ title;
4664
+ result;
4665
+ notes;
4666
+ constructor(update) {
4667
+ super(
4668
+ "PlanCheckpointError: step complete \u2014 STOP calling tools. The TUI has paused the plan for user review. Wait for the next user message; it will either say continue (proceed to the next step), request a revision (adjust the remaining plan), or stop (summarize and end)."
4669
+ );
4670
+ this.name = "PlanCheckpointError";
4671
+ this.stepId = update.stepId;
4672
+ this.title = update.title;
4673
+ this.result = update.result;
4674
+ this.notes = update.notes;
4675
+ }
4676
+ toToolResult() {
4677
+ const payload = {
4678
+ error: `${this.name}: ${this.message}`,
4679
+ kind: "step_completed",
4680
+ stepId: this.stepId,
4681
+ result: this.result
4682
+ };
4683
+ if (this.title) payload.title = this.title;
4684
+ if (this.notes) payload.notes = this.notes;
4685
+ return payload;
4686
+ }
4687
+ };
4688
+ var PlanRevisionProposedError = class extends Error {
4689
+ reason;
4690
+ remainingSteps;
4691
+ summary;
4692
+ constructor(reason, remainingSteps, summary) {
4693
+ super(
4694
+ "PlanRevisionProposedError: revision submitted. STOP calling tools now \u2014 the TUI has paused for the user to review your proposed change. Wait for their next message; it will say 'revision accepted' (proceed with the new step list), 'revision rejected' (keep the original plan and continue), or 'revision cancelled' (drop the proposal entirely). Don't call any tools in the meantime."
4695
+ );
4696
+ this.name = "PlanRevisionProposedError";
4697
+ this.reason = reason;
4698
+ this.remainingSteps = remainingSteps;
4699
+ this.summary = summary;
4700
+ }
4701
+ toToolResult() {
4702
+ const payload = {
4703
+ error: `${this.name}: ${this.message}`,
4704
+ reason: this.reason,
4705
+ remainingSteps: this.remainingSteps
4706
+ };
4707
+ if (this.summary) payload.summary = this.summary;
4708
+ return payload;
4709
+ }
4710
+ };
4711
+
4712
+ // src/tools/plan-core.ts
4713
+ var SUBMIT_PLAN_DESCRIPTION = "Submit ONE concrete plan you've already decided on. Use this for tasks that warrant a review gate \u2014 multi-file refactors, architecture changes, anything that would be expensive or confusing to undo. Skip it for small fixes (one-line typo, obvious bug with a clear fix) \u2014 just make the change. The user will either approve (you then implement it), ask for refinement, or cancel. If the user has already enabled /plan mode, writes are blocked at dispatch and you MUST use this. CRITICAL: do NOT use submit_plan to present alternative routes (A/B/C, option 1/2/3) for the user to pick from \u2014 the picker only exposes approve/refine/cancel, so a menu plan strands the user with no way to choose. For branching decisions, call `ask_choice` instead; only call submit_plan once the user has picked a direction and you have a single actionable plan. Write the plan as markdown with a one-line summary, a bulleted list of files to touch and what will change, and any risks or open questions. STRONGLY PREFERRED: pass `steps` \u2014 an array of {id, title, action, risk?} \u2014 so the UI renders a structured step list above the approval picker and tracks per-step progress. Use risk='high' for steps that touch prod data / break public APIs / are hard to undo; 'med' for non-trivial but reversible (multi-file edits, schema tweaks); 'low' for safe local work. After each step, call `mark_step_complete` so the user sees progress ticks.";
4714
+ var MARK_STEP_COMPLETE_DESCRIPTION = "Mark one step of the approved plan as done AND pause for the user to review. Call this after finishing each step. The TUI shows a \u2713 progress row and mounts a Continue / Revise / Stop picker \u2014 you MUST stop calling tools after this fires and wait for the next user message. Pass the `stepId` from the plan's steps array, a short `result` (what you did), and optional `notes` for anything surprising (errors, scope changes, follow-ups). This tool doesn't change any files. Don't call it if the plan didn't include structured steps, and don't invent ids that weren't in the original plan.";
4715
+ var REVISE_PLAN_DESCRIPTION = "Surgically replace the REMAINING steps of an in-flight plan. Call this when the user has given feedback at a checkpoint that warrants a structured plan change \u2014 skip a step, swap two steps, add a new step, change risk, etc. Pass: `reason` (one sentence why), `remainingSteps` (the new tail of the plan, replacing whatever steps haven't been done yet), and optional `summary` (updated one-line plan summary). Done steps are NEVER touched \u2014 keep them out of `remainingSteps`. The TUI shows a diff (removed in red, kept in gray, added in green) and the user accepts or rejects. Don't call this for trivial mid-step adjustments \u2014 just keep executing. Don't call submit_plan for revisions either \u2014 that resets the whole plan including completed steps. Use submit_plan only when the entire approach has changed; use revise_plan when the tail needs editing.";
4716
+ var STEP_ITEM_SCHEMA = {
4717
+ type: "object",
4718
+ properties: {
4719
+ id: { type: "string", description: "Stable id, e.g. step-1." },
4720
+ title: { type: "string", description: "Short imperative title." },
4721
+ action: { type: "string", description: "One-sentence description of the concrete action." },
4722
+ risk: {
4723
+ type: "string",
4724
+ enum: ["low", "med", "high"],
4725
+ description: "Self-assessed risk. 'high' = hard-to-undo / touches prod / breaks API; 'med' = non-trivial but reversible; 'low' = safe local work. The UI shows a colored dot per step so the user knows where to focus review. Omit if you're unsure."
4726
+ }
4727
+ },
4728
+ required: ["id", "title", "action"]
4729
+ };
4730
+ function sanitizeRisk(raw) {
4731
+ if (raw === "low" || raw === "med" || raw === "high") return raw;
4732
+ return void 0;
4733
+ }
4734
+ function sanitizeSteps(raw) {
4735
+ if (!Array.isArray(raw)) return void 0;
4736
+ const steps = [];
4737
+ for (const entry of raw) {
4738
+ if (!entry || typeof entry !== "object") continue;
4739
+ const e = entry;
4740
+ const id = typeof e.id === "string" ? e.id.trim() : "";
4741
+ const title = typeof e.title === "string" ? e.title.trim() : "";
4742
+ const action = typeof e.action === "string" ? e.action.trim() : "";
4743
+ if (!id || !title || !action) continue;
4744
+ const step = { id, title, action };
4745
+ const risk = sanitizeRisk(e.risk);
4746
+ if (risk) step.risk = risk;
4747
+ steps.push(step);
4748
+ }
4749
+ return steps.length > 0 ? steps : void 0;
4750
+ }
4751
+ function registerSubmitPlan(registry, opts) {
4461
4752
  registry.register({
4462
4753
  name: "submit_plan",
4463
- description: "Submit a concrete plan to the user for review before executing. Use this for tasks that warrant a review gate \u2014 multi-file refactors, architecture changes, anything that would be expensive or confusing to undo. Skip it for small fixes (one-line typo, obvious bug with a clear fix) \u2014 just make the change. The user will either approve (you then implement it), ask for refinement, or cancel. If the user has already enabled /plan mode, writes are blocked at dispatch and you MUST use this. Write the plan as markdown with a one-line summary, a bulleted list of files to touch and what will change, and any risks or open questions.",
4754
+ description: SUBMIT_PLAN_DESCRIPTION,
4464
4755
  readOnly: true,
4465
4756
  parameters: {
4466
4757
  type: "object",
@@ -4468,6 +4759,15 @@ function registerPlanTool(registry, opts = {}) {
4468
4759
  plan: {
4469
4760
  type: "string",
4470
4761
  description: "Markdown-formatted plan. Lead with a one-sentence summary. Then a file-by-file breakdown of what you'll change and why. Flag any risks or open questions at the end so the user can weigh in before you start."
4762
+ },
4763
+ steps: {
4764
+ type: "array",
4765
+ description: "Structured step list (strongly recommended). When provided, the UI renders a compact step list above the approval picker AND tracks per-step progress via `mark_step_complete`. Use stable ids (step-1, step-2, ...). Skip only for tiny one-step plans where the markdown body is enough.",
4766
+ items: STEP_ITEM_SCHEMA
4767
+ },
4768
+ summary: {
4769
+ type: "string",
4770
+ description: "Optional. One-sentence human-friendly title for the plan, ~80 chars max. Surfaces in the PlanConfirm picker header and in /plans listings ('\u25B8 refactor auth into signed tokens \xB7 2/5 done'). Skip for trivial plans where the first line of the markdown body is already short and clear."
4471
4771
  }
4472
4772
  },
4473
4773
  required: ["plan"]
@@ -4477,10 +4777,108 @@ function registerPlanTool(registry, opts = {}) {
4477
4777
  if (!plan) {
4478
4778
  throw new Error("submit_plan: empty plan \u2014 write a markdown plan and try again.");
4479
4779
  }
4480
- opts.onPlanSubmitted?.(plan);
4481
- throw new PlanProposedError(plan);
4780
+ const steps = sanitizeSteps(args?.steps);
4781
+ const summary = typeof args?.summary === "string" ? args.summary.trim() || void 0 : void 0;
4782
+ opts.onPlanSubmitted?.(plan, steps);
4783
+ throw new PlanProposedError(plan, steps, summary);
4784
+ }
4785
+ });
4786
+ }
4787
+ function registerMarkStepComplete(registry, opts) {
4788
+ registry.register({
4789
+ name: "mark_step_complete",
4790
+ description: MARK_STEP_COMPLETE_DESCRIPTION,
4791
+ readOnly: true,
4792
+ parameters: {
4793
+ type: "object",
4794
+ properties: {
4795
+ stepId: {
4796
+ type: "string",
4797
+ description: "The id of the step being marked complete. Must match one from submit_plan's steps array."
4798
+ },
4799
+ title: {
4800
+ type: "string",
4801
+ description: "Optional. The step's title, echoed back for the UI. If omitted, the UI falls back to the id."
4802
+ },
4803
+ result: {
4804
+ type: "string",
4805
+ description: "One-sentence summary of what was done for this step."
4806
+ },
4807
+ notes: {
4808
+ type: "string",
4809
+ description: "Optional. Anything surprising \u2014 blockers hit, assumptions revised, follow-ups for later steps."
4810
+ }
4811
+ },
4812
+ required: ["stepId", "result"]
4813
+ },
4814
+ fn: async (args) => {
4815
+ const stepId = (args?.stepId ?? "").trim();
4816
+ const result = (args?.result ?? "").trim();
4817
+ if (!stepId) {
4818
+ throw new Error("mark_step_complete: stepId is required.");
4819
+ }
4820
+ if (!result) {
4821
+ throw new Error(
4822
+ "mark_step_complete: result is required \u2014 say in one sentence what you did."
4823
+ );
4824
+ }
4825
+ const title = typeof args?.title === "string" ? args.title.trim() || void 0 : void 0;
4826
+ const notes = typeof args?.notes === "string" ? args.notes.trim() || void 0 : void 0;
4827
+ const update = { kind: "step_completed", stepId, result };
4828
+ if (title) update.title = title;
4829
+ if (notes) update.notes = notes;
4830
+ opts.onStepCompleted?.(update);
4831
+ throw new PlanCheckpointError({ stepId, title, result, notes });
4482
4832
  }
4483
4833
  });
4834
+ }
4835
+ function registerRevisePlan(registry, opts) {
4836
+ registry.register({
4837
+ name: "revise_plan",
4838
+ description: REVISE_PLAN_DESCRIPTION,
4839
+ readOnly: true,
4840
+ parameters: {
4841
+ type: "object",
4842
+ properties: {
4843
+ reason: {
4844
+ type: "string",
4845
+ description: "One sentence explaining why you're revising \u2014 what the user asked for, what changed your assessment."
4846
+ },
4847
+ remainingSteps: {
4848
+ type: "array",
4849
+ description: "The new tail of the plan \u2014 what should run from here on. Each entry: {id, title, action, risk?}. Use stable ids; reuse old ids when a step is just being adjusted, generate new ones for genuinely new steps.",
4850
+ items: STEP_ITEM_SCHEMA
4851
+ },
4852
+ summary: {
4853
+ type: "string",
4854
+ description: "Optional. Updated one-line plan summary if the overall framing has shifted."
4855
+ }
4856
+ },
4857
+ required: ["reason", "remainingSteps"]
4858
+ },
4859
+ fn: async (args) => {
4860
+ const reason = (args?.reason ?? "").trim();
4861
+ if (!reason) {
4862
+ throw new Error(
4863
+ "revise_plan: reason is required \u2014 write one sentence explaining the change."
4864
+ );
4865
+ }
4866
+ const remainingSteps = sanitizeSteps(args?.remainingSteps);
4867
+ if (!remainingSteps || remainingSteps.length === 0) {
4868
+ throw new Error(
4869
+ "revise_plan: remainingSteps must be a non-empty array of well-formed steps. If the user wants to STOP rather than continue, don't revise \u2014 the picker has its own Stop option."
4870
+ );
4871
+ }
4872
+ const summary = typeof args?.summary === "string" ? args.summary.trim() || void 0 : void 0;
4873
+ opts.onPlanRevisionProposed?.(reason, remainingSteps, summary);
4874
+ throw new PlanRevisionProposedError(reason, remainingSteps, summary);
4875
+ }
4876
+ });
4877
+ }
4878
+ function registerPlanTool(registry, opts = {}) {
4879
+ registerSubmitPlan(registry, opts);
4880
+ registerMarkStepComplete(registry, opts);
4881
+ registerRevisePlan(registry, opts);
4484
4882
  return registry;
4485
4883
  }
4486
4884
 
@@ -4657,8 +5055,8 @@ function registerSubagentTool(parentRegistry, opts) {
4657
5055
  },
4658
5056
  model: {
4659
5057
  type: "string",
4660
- enum: ["deepseek-v4-flash", "deepseek-v4-pro", "deepseek-chat", "deepseek-reasoner"],
4661
- description: "Which DeepSeek model the subagent runs on. Default is 'deepseek-v4-pro' \u2014 the strongest model, best for complex subtasks. Override to 'deepseek-v4-flash' (or the legacy 'deepseek-chat' / 'deepseek-reasoner' aliases, which route to flash non-thinking / thinking modes) when the subtask is simple enough that flash's quality suffices \u2014 flash is roughly 12\xD7 cheaper."
5058
+ enum: ["deepseek-v4-flash", "deepseek-v4-pro"],
5059
+ description: "Which DeepSeek model the subagent runs on. Default is 'deepseek-v4-flash' \u2014 cheap and fast, fine for explore/research-style subtasks. Override to 'deepseek-v4-pro' (~12\xD7 more expensive) when the subtask genuinely needs the stronger model: cross-file architecture, subtle bug hunts, anything where flash has empirically underperformed."
4662
5060
  }
4663
5061
  },
4664
5062
  required: ["task"]
@@ -6970,6 +7368,21 @@ Skip submit_plan for small, obvious changes: one-line typo, clear bug with a cle
6970
7368
 
6971
7369
  Plan body: one-sentence summary, then a file-by-file breakdown of what you'll change and why, and any risks or open questions. If some decisions are genuinely up to the user (naming, tradeoffs, out-of-scope possibilities), list them in an "Open questions" section \u2014 the user sees the plan in a picker and has a text input to answer your questions before approving. Don't pretend certainty you don't have; flagged questions are how the user tells you what they care about. After calling submit_plan, STOP \u2014 don't call any more tools, wait for the user's verdict.
6972
7370
 
7371
+ **Do NOT use submit_plan to present A/B/C route menus.** The approve/refine/cancel picker has no branch selector \u2014 a menu plan strands the user. For branching decisions, use \`ask_choice\` (see below); only call submit_plan once the user has picked a direction and you have ONE actionable plan.
7372
+
7373
+ # When to ask the user to pick (ask_choice)
7374
+
7375
+ You have an \`ask_choice\` tool. **If the user is supposed to pick between alternatives, the tool picks \u2014 you don't enumerate the choices as prose.** Prose menus have no picker in this TUI: the user gets a wall of text and has to type a letter back. The tool fires an arrow-key picker that's strictly better.
7376
+
7377
+ Call it when:
7378
+ - The user has asked for options / doesn't want a recommendation / wants to decide.
7379
+ - You've analyzed multiple approaches and the final call is theirs.
7380
+ - It's a preference fork you can't resolve without them (deployment target, team convention, taste).
7381
+
7382
+ Skip it when one option is clearly correct (just do it, or submit_plan) or a free-form text answer fits (ask in prose).
7383
+
7384
+ Each option: short stable id (A/B/C), one-line title, optional summary. \`allowCustom: true\` when their real answer might not fit. Max 6. A ~1-sentence lead-in before the call is fine ("I see three directions \u2014 letting you pick"); don't repeat the options in it. After the call, STOP.
7385
+
6973
7386
  # Plan mode (/plan)
6974
7387
 
6975
7388
  The user can ALSO enter "plan mode" via /plan, which is a stronger, explicit constraint:
@@ -7429,6 +7842,7 @@ export {
7429
7842
  AppendOnlyLog,
7430
7843
  CODE_SYSTEM_PROMPT,
7431
7844
  CacheFirstLoop,
7845
+ ChoiceRequestedError,
7432
7846
  DEFAULT_AT_MENTION_MAX_BYTES,
7433
7847
  DEFAULT_MAX_RESULT_CHARS,
7434
7848
  DEFAULT_MAX_RESULT_TOKENS,
@@ -7448,7 +7862,9 @@ export {
7448
7862
  NeedsConfirmationError,
7449
7863
  PROJECT_MEMORY_FILE,
7450
7864
  PROJECT_MEMORY_MAX_CHARS,
7865
+ PlanCheckpointError,
7451
7866
  PlanProposedError,
7867
+ PlanRevisionProposedError,
7452
7868
  SessionStats,
7453
7869
  SseTransport,
7454
7870
  StdioTransport,
@@ -7538,6 +7954,7 @@ export {
7538
7954
  readUsageLog,
7539
7955
  recordFromLoopEvent,
7540
7956
  redactKey,
7957
+ registerChoiceTool,
7541
7958
  registerFilesystemTools,
7542
7959
  registerMemoryTools,
7543
7960
  registerPlanTool,