Compare commits

...
40 Commits
Author SHA1 Message Date
esengine 9e3c62ed1e chore(release): 0.7.1 2026-04-25 04:47:34 -07:00
esengine ee274035c6 fix(loop,prompt): storm recovery, PYTHONUTF8, recency rule
Three runtime fixes that all surfaced from a single user trace
(model looped on a broken read_file, the chat ended without
explanation, embedded GBK encoding errors, plus a separate
"PDF report on global economy" turn that wrote a 2024 report
from training memory instead of searching).

Storm-break no longer dead-ends the turn
- When the storm-breaker suppressed every tool call in a turn,
  the loop yielded `done` with empty assistant content. The user
  saw a one-line warning then silence and didn't know what to do.
  Now routes through `forceSummaryAfterIterLimit` with a new
  `"stuck"` reason: the model gets one no-tools call to explain
  what it tried, what blocked, and what would unblock — turning
  the silent stop into actionable feedback the user can act on.

PYTHONUTF8 / PYTHONIOENCODING for spawned shells
- run_command's spawn env now sets PYTHONIOENCODING=utf-8 and
  PYTHONUTF8=1. On Chinese Windows, Python's default stdout
  encoder is GBK; emoji / non-GBK output raises UnicodeEncodeError
  and the model sees a Python traceback instead of the script's
  real result, then loops trying to fix the wrong problem.
  These env vars force UTF-8 unconditionally. Harmless on
  non-Python processes (env vars they don't read).

Recency rule in default chat system prompt
- New short section in DEFAULT_SYSTEM telling the model that
  when an answer's correctness depends on something that
  changes over time (the user is asking what's *happening*,
  not what's *true*) and a search tool is available, search
  before composing. Phrased as a principle ("if I'm wrong
  about this, is it because reality moved on?") rather than
  a topic list, so it doesn't go stale or over-prescribe.
- web_search description rewritten in matching language —
  emphasis on "current state" rather than enumerating
  topics like markets / news / releases, which tied the
  description to a particular moment in time.

Tests: loop +1 (storm→summary regression). 1264 tests total,
lint + tsc + build clean.
2026-04-25 04:47:27 -07:00
esengine 500868b490 fix(ui,prompt): paste sentinels, hard /clear, multi-line nav
Several long-standing input-box and TUI annoyances fixed in one batch.

Paste handling
- Big pastes (3000-line error logs, etc.) used to be inlined into
  the buffer verbatim — surrounding typed text drowned, every
  keystroke re-rendered hundreds of rows. Replace with a sentinel
  scheme: each paste blob becomes ONE PUA codepoint in the buffer
  (`\uE100..\uE1FF`), full content lives in a side registry,
  rendered as `[paste #N · 33l · 1.0KB]` magenta block. Buffer
  stays small, cursor steps over the placeholder as one unit, a
  single Backspace removes the whole paste. On submit the
  sentinels expand back to full content for the model.
- Bracketed-paste mode (DECSET 2004) enabled at app start so
  cooperating terminals deliver one marker pair per paste action.
- For terminals where the markers don't reach Ink (PowerShell +
  ConPTY parses them out), a sub-30ms time-window + position-guard
  fallback collapses chunks of one paste into a single sentinel.
  30ms is well below human reaction for double-pasting (~100ms+),
  so two deliberate pastes never falsely merge.
- Critical fix: PowerShell+Ink fires useInput TWICE per stdin
  chunk, both with stale React closure over `value` / `cursor`.
  The merge guard read stale state and never matched the previous
  sentinel — one Ctrl+V kept producing four `[paste #N]`
  placeholders. registerPaste now reads from refs we update
  synchronously inside the function, so the second fire sees the
  first's insert.
- Pasted CR/CRLF normalize to LF; bracketed-paste markers are
  stripped if they leak through.

Multi-line cursor
- ↑/↓ at the buffer boundary (line 0 / last line) used to be
  silent NOOP — felt stuck. Now hands off to the parent's history
  recall, so users can escape into history from a multi-line
  draft without first emptying it.
- Raw-escape fallback: terminals that don't set `key.upArrow`
  and instead leak `\x1b[A` into `input` (older Windows configs)
  now get the escape rewritten into the structured key event,
  preventing the literal escape bytes from being inserted.

Buffer-wide shortcuts
- PageUp / PageDown jump to top / bottom of the WHOLE buffer
  (was NOOP).
- Ctrl+U clears the entire buffer (readline-style; necessary
  given the renderer can collapse the buffer to a few visible
  rows after a paste — backspacing N times wasn't ergonomic).
- Ctrl+W deletes the word before the cursor (eats trailing
  whitespace first, spans newlines).
- Hint row appears under the input when buffer has > 20 lines:
  `[N lines · PageUp/PageDown jump to top/bottom · Ctrl+U clear ·
  Ctrl+W del word]` so users discover the shortcuts in the
  exact moment they need them.

Visual stability
- StatsPanel pinned to `width={columns}` so each render's frame
  is exactly terminal-width — reduces (doesn't eliminate) the
  resize ghost-frame stacking from Ink's eraseLines miscount on
  re-wrapped lines.
- /help gains a "Known limitation" section about the resize
  artifact so users aren't blindsided.

`/clear` actually clears
- Used to only `setHistorical([])` (React state). Terminal
  scrollback was untouched — user kept seeing prior turns until
  they scrolled past them. Now writes CSI 2J + 3J + H so the
  viewport AND scrollback buffer are nuked. Ink's next render
  paints the TUI on the fresh screen.

Tests: paste-sentinels (new file, 18 tests), multiline-keys +57.
Total 1264 tests, lint + tsc + build clean.
2026-04-25 04:47:05 -07:00
esengine 7aa71324c4 feat(md): extended markdown rendering
Substantial expansion of the chat-output Markdown renderer.

Block-level
- Blockquote `>` with proper recursion: nested quotes (`> >`) render as
  adjacent left bars, lists / code fences / tables INSIDE a quote
  parse via the same `parseBlocks` recursively (instead of being
  flattened to text), GFM-style.
- Task lists (`- [ ]` / `- [x]`) — item text gains `task: "todo" |
  "done"`, rendered as `☐` / `☒` with strikethrough on done items.
- Diagram code blocks (mermaid / dot / graphviz / plantuml / puml /
  flowchart / sequencediagram / gantt / erdiagram) render with a
  distinct magenta double-line frame + `◇ <lang> diagram (source)`
  header + viewer-URL hint. Terminal can't draw the graph, but the
  user knows it's source-of-a-diagram and where to paste it.
- Hard line break: trailing `  ` (two-or-more spaces) on a line now
  inserts a real `\n` in the rendered paragraph instead of being
  silently collapsed into a space.

Inline
- `***bold-italic***` (added as the first INLINE_RE alternative
  before the bold and italic checks).
- `~~strikethrough~~` (with proper guards so subscript / strike
  don't fight).
- Pandoc-style `^x^` superscript and `~x~` subscript — only
  fire when every char is in the Unicode SUPERSCRIPT/SUBSCRIPT
  table; otherwise leave the markers literal so we don't drop the
  user's intent.
- Math: `$inline$` and `$$block$$` delimiters are stripped
  (delimiters only — content still flows through the existing
  LaTeX → Unicode pipeline).
- Emoji shortcodes: ~70-entry curated table covering the common
  faces / hearts / gestures / signals (`:smile:`, `:fire:`, `:+1:`,
  `:white_check_mark:`, etc.). Unknown names pass through literal.
- Autolinks: `<http://…>`, `<https://…>`, `<mailto:…>`, `<ftp://…>`
  rewrite to `[url](url)` so the existing link path renders them.
- Backslash escapes: `\*` / `\` ` ` / `\~` / `\[` / `\]` / `\`  etc.
  emit literal characters via a final INLINE_RE branch — the
  surrounding markup parsers don't get to consume the escaped
  punctuation. `stripInlineMarkup` rebuilt around a single-pass
  INLINE_RE walk so escape precedence matches the runtime.

Citation guard
- `collectCitations` now skips URLs that obviously aren't repo
  paths: anchor-only (`#foo`), bare `/`, and short placeholder
  words with no `/` `\` or `.` in them. Eliminates the false
  "broken citation" red-strikethrough on demo / non-citation
  links.

Bug fixes uncovered along the way
- `\sum_{i=1}^n` and friends were being eaten by the catch-all
  LaTeX command stripper because `\b` doesn't match between `m`
  and `_` (both are word chars). Switched the relevant rules to
  `(?![a-zA-Z])` so the specific Σ / Π / ∫ / etc. substitutions
  fire even when followed by a subscript.

Tests: markdown 60 → 173 (+113).
2026-04-25 04:45:21 -07:00
esengine e530cab7a7 chore(release): 0.7.0 2026-04-24 20:14:25 -07:00
esengine bf45687414 chore(models): retire deepseek-chat/-reasoner defaults, name v4 directly
deepseek-chat and deepseek-reasoner are now just compat aliases for
v4-flash's non-thinking and thinking modes (same underlying model,
same bill per telemetry.ts). Presets already all point at
deepseek-v4-flash / deepseek-v4-pro. Retire the old names everywhere
they were still surfacing as the default or discoverable surface:

- harvest.ts default model: deepseek-chat → deepseek-v4-flash
  (behaviorally identical — both route to v4-flash non-thinking)
- subagent tool enum: drop deepseek-chat/-reasoner; users pick
  flash vs pro now, no legacy names to distract the model
- subagent JSDoc: default was documented as pro but the actual
  constant is flash; fix the docs
- /model empty-arg hint: suggest v4 names instead of legacy aliases
- /think empty-reasoning hint: explain "thinking-mode models"
  generically instead of pinning to deepseek-reasoner

Kept legacy names in telemetry.ts (DEEPSEEK_PRICING,
DEEPSEEK_CONTEXT_TOKENS) because historical usage.jsonl rows still
reference them — the table is for pricing old sessions, not routing
new requests. Runtime `--model deepseek-chat` still works; the
isThinkingModeModel() abstraction is semantic (thinking vs
non-thinking), not version-bound, so it stays correct.
2026-04-24 20:14:20 -07:00
esengine f28d27290c fix(r1): unify reasoning_content round-trip around producing model
Prior fixes (0.5.15, 0.5.18) progressively unscoped the stamp but kept
a reasoning.length > 0 guard that silently dropped the field whenever
the model happened to return empty reasoning — legitimate on flash
thinking-mode turns with zero reasoning deltas, forced-summary paths
whose resp.reasoningContent is null, and non-streaming responses
returning reasoning_content: null. The next API call then 400'd with
"The reasoning_content in the thinking mode must be passed back."

Architectural smell: assistantMessage gated on reasoning-content
presence, while syntheticAssistantMessage gated on model type — two
different encodings of the same invariant.

Unify both around isThinkingModeModel(producingModel): the field is
present on the persisted assistant turn iff the model that generated
it runs in thinking mode, using the captured reasoning (or empty
string) as the value. Call sites pass the real producing model — not
this.model — so escalation (pro) and forced-summary (flash)
round-trip correctly.

Session-load heal: stampMissingReasoningForThinkingMode back-fills
empty reasoning_content on assistant turns from pre-fix session
files, so resuming an older session on a thinking-mode model no
longer 400s on the first request.

Tests: +5 (null-reasoning stamping on v4-flash, chat stays clean,
session-load heal for reasoner/v4-pro/chat). 1150 tests, tsc clean.
2026-04-24 20:14:05 -07:00
esengine 5453fc6dc3 refactor(plan): finish the split model started — types out, explicit barrel, per-tool helpers
The agent's live-run refactor (2c8... in the local log) correctly
split plan.ts into plan-core + plan-errors and preserved the barrel,
but stopped short of three things worth doing:

1. plan-errors.ts was mis-named — it also held the value types
   (PlanStep, PlanStepRisk, StepCompletion). Extracted those to
   a new plan-types.ts so file names match contents. Dependency
   direction is now plan-core → plan-errors → plan-types.

2. Barrel used \`export *\` from both modules, which would silently
   shadow on any future name collision. Replaced with explicit named
   re-exports so TS catches duplicates the moment they appear.

3. plan-core.ts was still ~240 lines, mostly a single
   registerPlanTool body with three inline tool-description strings.
   Split into registerSubmitPlan / registerMarkStepComplete /
   registerRevisePlan (one per screen) with descriptions hoisted to
   SCREAMING_SNAKE constants at the top and the duplicated step-item
   schema extracted to STEP_ITEM_SCHEMA. Function bodies now read as
   control flow, not prose. Public API unchanged.

1145 tests still green, typecheck + lint clean. Zero behavior change.
2026-04-24 19:55:39 -07:00
esengine 94a3c9d56e fix(choice): rewrite ask_choice guidance as one principle, not pattern list
Previous pass at tightening ask_choice guidance leaned on specific
anti-patterns — "方案 A:" headers, "你选哪个?" trailers, markdown
comparison tables. Ugly and brittle: next time the model adopts a
slightly different phrasing, we'd be patching yet another bullet.

Reframe as a single principle in both the tool description and the
code system prompt: "if the user is supposed to pick, the tool
picks — you don't enumerate the choices as prose." The model can
generalize from that.

Behavior contract is unchanged; the guidance is just cleaner and
easier to maintain. Prompt-engineering change only, no code logic.
2026-04-24 19:28:50 -07:00
esengine 4cb445b280 feat(plan): /replay — Time Travel canvas for archived plans
Atlas W2 wave 2: load an archived plan as a read-only snapshot.
'/replay' defaults to the newest archive; '/replay 2' jumps to the
second-newest; '/plans' enumerates the full set.

- SlashResult grows replayPlan field so the handler can push a
  structured payload — App.tsx mounts it as a plan-replay event
  rather than flattening to info text. Keeps the bordered box +
  step list + markdown body styling consistent with plan-resumed.
- New plan-replay DisplayRole + EventRow branch: gray border, ⏪
  icon, dim header (completed time, N/total nav, archive filename),
  markdown body rendered through the full pipeline, PlanStepList
  with every step marked done, footer hint for jumping archives.
- /replay handler in plans.ts looks up listPlanArchives(session)
  by 1-based index, validates range, carries the payload through.
  Per-session only — same project-isolation as /plans.
- /replay added to commands.ts with argsHint=[N] so slash
  autocomplete / hint surface picks it up.

Tests: 6 new slash tests cover default-newest, indexed lookup,
out-of-range rejection, empty-archive state, no-session guard, and
/plans summary label surfacing. Full suite 1145 green.
2026-04-24 19:16:18 -07:00
esengine 918ed2ca50 feat(plan): persist markdown body + add human summary field
Two schema additions that unblock Time Travel and make /plans
listings useful.

- submit_plan accepts optional \`summary\`: one-line title. Surfaces
  in the PlanConfirm header, the resume banner, and /plans so users
  identify plans by intent ('Refactor auth into signed tokens')
  rather than by filename.
- plan.json now stores the markdown \`body\` that came in with
  submit_plan. Replay will read this; previously the body only
  lived in the JSONL log, which is fine for the active session but
  hard to surface in a closed archive without re-parsing tool-call
  JSON.

Both fields are optional. Older plans without them still load and
render cleanly; /plans falls back to filename when no summary is set.

PlanProposedError carries summary through toToolResult. plan-store's
savePlanState grows an extras bag so callers don't have to care
about field proliferation. listPlanArchives surfaces both fields
on the PlanArchiveSummary type.

Tests: body+summary roundtrip, omission default, submit_plan
summary trim behavior, blank-rejection. Total: 1139 tests green.
2026-04-24 19:06:43 -07:00
esengine ebc967be35 feat(plan): /plans slash — list active + archived plans for the session
Adds a per-session history view. Active plan (from plan.json) +
archived completed plans (.done.json), newest-first. Project-local
by design — cd to another project to see its plans, no cross-project
listing.

Output:
  ▸ active plan: 2/5 steps done · last touched 1h ago

  Archived (3):
    ✓ 3d ago     5 steps · complete  code-foo.plan.2026-04-21-...done.json
    ✓ 2026-04-15 8 steps · complete  code-foo.plan.2026-04-15-...done.json
    ✓ 2026-04-10 3 steps · complete  code-foo.plan.2026-04-10-...done.json

- listPlanArchives scans sessionsDir() for the session-prefixed
  .done.json files. Sorts by stored updatedAt (with mtime fallback
  for hand-edited archives). Skips corrupt JSON / wrong-version /
  zero-steps archives instead of failing the whole list.
- /plans handler renders both views; falls back to a discovery hint
  when no plans exist yet.
- Tests: 6 new — empty state, ordering, active-only ignored,
  cross-session isolation, corrupt-resilience, mtime fallback.

Foundation for upcoming /replay <archive> + Time Travel canvas —
both will read these summaries to find replayable artifacts.
2026-04-24 18:55:42 -07:00
esengine 2e64d63c8b feat(plan): auto-archive completed plans for the artifact trail
When the model marks the final step done, the active plan.json moves
to a timestamped .done.json archive instead of lingering. Two reasons
this matters: (1) the next session starts with a clean slate — no
stale resume banner for work that's actually finished; (2) the
archive is the foundation Time Travel replay will read from in W2
wave 2 to show "what the model actually did vs what was planned".

- archivePlanState renames plan.json → plan.<ISO-stamp>-<rand>.done.json
  in sessionsDir(). Random 4-char suffix dodges within-millisecond
  collisions if two plans finalize back-to-back. Returns the archive
  path, or null when there's no active plan / rename fails.
- App.tsx mark_step_complete handler: after the progress row pushes,
  if total > 0 && completed >= total, archive and post a
  '▸ plan complete — all 5 steps done · archived' info row.
- Tests: 4 new — null-return on missing, rename verification,
  payload preservation through archive, collision-resistance.
2026-04-24 18:50:30 -07:00
esengine 6d8a2c596c feat(loop): visible reasons for auto-escalation decisions
Auto-escalation (flash → pro) was the only truly automatic per-turn
decision the user couldn't see into. The warning fired but said only
'flash requested escalation' or 'flash hit N edit failure(s)' — no
WHY. Two changes surface the rationale.

1. Self-report marker now carries an optional reason:
     <<<NEEDS_PRO>>>                    ← bare, still works
     <<<NEEDS_PRO: <reason>>>>          ← preferred, surfaces in warning

   parseEscalationMarker pulls the reason out, the warning becomes
   '⇧ flash requested escalation — <reason>'. Buffer bumped to 256
   chars so reasons aren't truncated mid-stream. The streaming
   look-ahead now uses looksLikePartialEscalationMarker so multi-
   line / colon-form markers don't flush prematurely.

2. Failure-threshold escalation tracks PER-TYPE counts (search-
   mismatch, scavenged, truncated, storm-broken). The warning now
   says 'flash hit 2× search-mismatch, 1× truncated' instead of
   '3 repair/error signals'. Same FAILURE_ESCALATION_THRESHOLD
   semantics; just better attribution.

ESCALATION_CONTRACT prompt fragment teaches both forms with examples.
Three new tests cover the reason-carrying marker, empty-reason edge,
and the unclosed-marker fallthrough (still treats as content, no
silent retry on a malformed signal).
2026-04-24 18:45:27 -07:00
esengine f6931481ba feat(plan): render full step list on resume, not just a one-liner
The W2 resume banner was a single info row — '▸ resumed plan: 2/5
steps done · last touched 3h ago'. Useful but minimal. Users had no
way to see WHICH steps were done or what's coming next without
scrolling back through the prior session's log.

New plan-resumed display role mounts a bordered box at the top of
the new session: header (badge + counter + relative time) plus
the full PlanStepList — same component used in PlanConfirm and the
checkpoint picker, with done steps dimmed + ✓, the next pending
step focused with the › cursor, and the risk gutter color-coded.

Carries the structured plan data through DisplayEvent.resumedPlan
so the renderer doesn't need access to the live planStepsRef. Pure
render layer; no new logic, no new tests needed (plan-store tests
already cover the data side).
2026-04-24 18:21:04 -07:00
esengine 15b0cfc894 feat(plan): persist structured plan state across session restarts
Atlas W2 wave 1: the plan the model submits via submit_plan (and
mutates via mark_step_complete / revise_plan) now survives terminal
close. Without this, all the structured-step / risk / checkpoint /
revise UX evaporated whenever you took a coffee break.

- New src/code/plan-store.ts: loadPlanState / savePlanState /
  clearPlanState / relativeTime. Storage path mirrors the JSONL
  convention: ~/.reasonix/sessions/<sanitized>.plan.json. Format is
  versioned (v1) with defensive parsing — corrupt files load as
  null, malformed step entries are filtered, invalid risk values
  are stripped, the rest of the plan still loads.
- App.tsx: load on mount, save after every plan-state change
  (submit_plan, mark_step_complete, revise_plan accept), clear on
  PlanConfirm cancel. The persistPlanState callback is threaded
  through all the relevant useCallback deps so React's exhaustive-
  deps rule stays clean.
- Resume banner: when an existing plan loads on startup, push
  '▸ resumed plan: 2/5 steps done · last touched 3h ago' into the
  scrollback so the user immediately sees the picked-up state.
- Tests: 15 covering save/load roundtrip, malformed-JSON recovery,
  version mismatch, partial step sanitization, completedStepIds
  filtering, path safety, and relativeTime branches.

The plan markdown body itself is NOT persisted here — it lives in
the session JSONL (it was a tool result), so resuming the session
replays it naturally. We carry forward only the live state needed
to keep mark_step_complete and revise_plan meaningful.
2026-04-24 18:16:05 -07:00
esengine 331e01fda1 feat(ui): tool duration + /tool N hint on compact rows
Compact tool rows now annotate with timing and a navigation hint:

  ▣ run_command (1.2s) → exit 0 · ✓ tests passed       /tool 12
  ▣ read_file → import { foo } · 234 lines · 4.5KB     /tool 13
  ▣ search_content (8.5s) → 5 matches · src/foo.ts:12  /tool 14

Duration is suppressed under 100ms (every read_file would scream
'47ms' otherwise — noise). Above that, formatDuration picks a tight
representation: ms → s.s → s → m+s as the magnitude grows.

The /tool N suffix makes the existing slash command discoverable
without scrolling — users can jump straight to full content via
`/tool 14` instead of guessing the position. toolIndex is captured
at push time as the 1-based length of the tool history.

App.tsx: toolStartedAtRef captures Date.now() on tool_start and
diffs at result. Single ref is enough — tools dispatch serially.
2026-04-24 18:04:07 -07:00
esengine 877a9ee03b feat(ui): compact one-line tool rendering with smart per-tool summary
Old tool rows were 6–8 vertical lines each (glyph row + blank + 400-
char body block). 10 tool calls in a session = ~70 lines of
mostly-noise content drowning the actually-interesting events
(checkpoint pickers, plan submissions, edit diffs).

New rendering: one line per tool call.

  ▣ read_file      →  import { foo } from 'bar' · 234 lines · 4.5KB
  ▣ list_directory →  17 entries
  ▣ search_content →  5 matches · src/foo.ts:12: const x = 1
  ▣ run_command    →  exit 0 · ✓ 17 tests passed
  ▥ run_command    ✗  exit 1 · TypeError: Cannot read property
  ▣ submit_plan    →  PlanProposedError — STOP, picker shown to user.

edit_file keeps its multi-line colored diff renderer (the diff IS the
value). Plan / Choice control-flow signals (PlanProposedError etc.)
render in non-error yellow even though they technically come through
the error envelope — they're picker triggers, not failures.

The summarizer is a pure function in tool-summary.ts so it tests
without Ink and can be reused by replay / transcript export later.
Full content remains accessible via `/tool N`.
2026-04-24 17:58:42 -07:00
esengine a4ff99236b feat(plan): revise_plan tool — surgical mid-flight plan edits with diff picker
Phase 2 Revise was just text-forwarding: user typed feedback, model
got a synthetic, model adjusted however it wanted with no structured
contract. Add revise_plan as the structured counterpart — the model
proposes new remainingSteps + a one-sentence reason, the TUI shows
a step-level diff, user accepts or rejects.

- New revise_plan tool (readOnly, throws PlanRevisionProposedError).
  Sanitization reuses sanitizeSteps so risk levels and malformed
  entries are handled the same as submit_plan.
- New PlanReviseConfirm modal: amber border, reason header, diff
  rows (-removed/red+strikethrough, +added/green, kept/dim), counter
  badge -N +M (K kept), Accept/Reject picker.
- App.tsx: pendingRevision state + handler. Accept splices the new
  steps onto the done-step prefix in planStepsRef (done work never
  undone), pushes an info row with -N+M counts, sends a continue
  synthetic. Reject sends a 'keep original' synthetic. Picker takes
  priority over checkpoint picker so a checkpoint-revise → revision-
  proposal flow chains naturally.
- Checkpoint Revise synthetic now nudges the model toward revise_plan
  for structural changes vs submit_plan for full reset.

Tests cover the error roundtrip, sanitization, risk preservation,
empty-input rejection, and the readOnly flag.
2026-04-24 17:38:53 -07:00
esengine c3d327e27f feat(plan): risk gutter + structured step list in plan pickers
Phase 1 structured steps were only used for post-approval progress
tallying — the user never saw them at decision time. Add risk-coded
step list to both PlanConfirm (approval) and PlanCheckpointConfirm
(mid-execution) so the plan shape is visible where it matters.

- New PlanStep.risk: "low"|"med"|"high" (optional). submit_plan
  description guides the model: high = hard-to-undo / prod / API
  changes; med = non-trivial but reversible; low = safe local.
- PlanStepList renders a compact list with 1–3 colored dots per step
  (●/●●/●●● green/yellow/red) + a ✓/▶/— glyph, a legend row, and
  a '3 steps · 1 done' counter. Steps without risk render a blank
  gutter, so pure-markdown plans degrade cleanly.
- PlanConfirm mounts the list above the approve/refine/cancel picker
  when steps are supplied.
- PlanCheckpointConfirm mounts the same list with the current step
  highlighted via a › cursor and completed steps dimmed, so the user
  can see what just finished and what's next before picking
  continue/revise/stop.

Result: a structured plan with risks looks like a real plan, not a
markdown blob. Pure-markdown plans keep working unchanged.
2026-04-24 10:14:48 -07:00
esengine acb3a3ffee fix(choice): make ask_choice reliably fire via tool desc + system prompt
Phase 1 ask_choice was technically working but models rarely called it
— the description leaned defensive ('don't misuse') with only a light
'use when genuinely user's call' nudge, so DeepSeek Flash kept writing
prose comparisons that ended with '你选哪个?' (no picker rendered).

Two-layer fix:
- Tool description leads with 'CALL THIS WHENEVER your next reply
  would end with A/B/C — 你选哪个?'. Spells out the self-detect
  triggers and the failure mode of text menus. 'When in doubt, call
  the tool' as the tiebreaker.
- Code system prompt gains a dedicated '# When to ask the user to
  pick (ask_choice)' section sibling to the submit_plan one, plus an
  inline warning in the submit_plan section against option-menu
  plans cross-referencing ask_choice.

Costs one prefix-cache miss on first turn after the update; hit rate
re-stabilizes after that. No test changes (the behavior under test
was already correct — this is pure prompt-engineering).
2026-04-24 09:15:28 -07:00
esengine 7e1695f945 feat(choice): ask_choice primitive for A/B/C branching decisions
New tool gives the model a proper home for branching questions —
submit_plan was getting misused as a route-picker and leaving users
stuck at approve/refine/cancel with no way to choose.

Tool throws ChoiceRequestedError (same toToolResult protocol as
PlanProposedError), TUI mounts ChoiceConfirm — a magenta-bordered
modal with the question, the option rows (title + dim summary), an
optional "Let me type my own answer" escape hatch, and cancel.
Picking routes a synthetic 'user picked <id>' back to the model;
custom ships whatever the user typed verbatim.

Registered in both code and chat modes so branching works anywhere.
Sanitizes malformed option arrays (DeepSeek V3/R1 occasionally drops
fields even with Pillar 3 auto-flatten) and caps at 6 options so the
model can't drown the user in choices. submit_plan's description now
cross-references ask_choice so the model learns the dispatch.

Foundation for the Atlas redesign — Fork Nodes in W2 will render
pending choices inline in the plan canvas instead of as a separate
modal.
2026-04-24 08:44:45 -07:00
esengine 248dd134ba fix(plan): forbid submit_plan from presenting A/B/C option menus
Tool description now explicitly tells the model not to use submit_plan
as a "pick one of these routes" menu. The approve/refine/cancel picker
has no branch selector, so a menu plan strands the user — hit in the
wild where the model used submit_plan to offer three project directions.

Branches belong in plain assistant text with a question; submit_plan
stays reserved for a single actionable plan.
2026-04-24 08:17:02 -07:00
esengine e5a75119cb feat(plan): mid-execution checkpoints — Continue / Revise / Stop
mark_step_complete now throws PlanCheckpointError so the loop pauses
after each step. A new PlanCheckpointConfirm picker drives what happens
next: Continue resumes the plan, Revise opens a feedback box whose
text is threaded into the next turn's context, Stop ends cleanly with
a summary.

Revise reuses PlanRefineInput's single-line UX with a new
"checkpoint-revise" mode label. Esc on the feedback input restores the
picker. The ✓ progress row from Phase 1 still renders before the
picker mounts, so the scrollback always records what was just done.

Ports the useful half of @imlingdu/reasonix-tools' dynamic-plan loop
into Reasonix's submit-plan / approval-gate model — Phase 3 will add
an LLM-driven revise helper on top.
2026-04-24 08:10:56 -07:00
esengine 11155add8a feat(plan): structured steps + mark_step_complete progress rows
submit_plan now accepts an optional steps:[{id,title,action}] array;
new mark_step_complete tool ticks them off during execution so the
scrollback shows `✓ step-1 · title — result (2/5)` instead of leaving
the user to infer progress from tool noise.

Pure-markdown plans keep working unchanged — steps and progress
rows only render when the model opted into the structured form.
2026-04-24 08:02:36 -07:00
esengine f82f93559b chore(release): 0.6.0
Cost control promoted to Pillar 4. Breaking behavior: default model
flipped from v4-pro to v4-flash; smart (default) preset no longer
auto-enables harvest; max preset no longer auto-enables branch 3.
New: /pro one-shot arming, failure-triggered auto-escalate, model
self-report <<<NEEDS_PRO>>>, turn-end auto-compaction, per-turn cost
badges. UI refactor: App.tsx -33%, slash.ts split into slash/ with
13 focused modules. See CHANGELOG for the full matrix.
2026-04-24 07:26:40 -07:00
esengine 5a7d16c24f fix(ui,prompt): dedupe edit_file result display; teach run_command its shell limits upfront
Two small papercuts from a 70-turn live run surfaced:

1. Every edit_file tool call showed the apply result TWICE — once
   as a dim info row (pushed by applyNow in the edit-mode
   interceptor), then again as a full `▣ edit_file → …` tool row
   yielded by the loop. Both with identical text. Wasted rows, made
   long sessions harder to skim.

   Fix: drop the info-row push inside applyNow. The returned string
   still becomes the tool result AND the model sees it via the tool
   event; the user sees it once via the tool row with its
   identifying header. The auto-text branch at turn-end (for
   text-form SEARCH/REPLACE blocks parsed from assistant prose)
   still pushes its own info row — there's no tool event to back
   it up.

2. The model repeatedly tried `cd dir && cmd`, `cmd1 | cmd2`,
   `cmd 2>&1`, learning only from the error reply. run_command's
   top-level description didn't spell the constraints upfront.

   Fix: front-load a "Constraints (read these before the first
   call):" block in both run_command and run_background
   descriptions. Explicit list of rejected operators, cd-doesn't-
   persist, and concrete alternatives (`npm --prefix`, `cargo -C`,
   `git -C`, `pytest tests/…` instead of `cd && …`). Also warns
   against unbounded-output commands like `netstat -ano` /
   `find /` that balloon context for no reason, with filtered
   alternatives.

Both are tool/UI changes only; 1054 tests green, typecheck + biome
clean.
2026-04-24 07:12:14 -07:00
esengine 292e51f0c2 fix(plan): render full plan body in scrollback, shrink PlanConfirm to picker only
User bug: "submit_plan" proposals were being truncated inside the
PlanConfirm modal with "(25 more lines truncated — resize the terminal
to see more)". The whole point of a plan review gate is that the user
can read the full thing before approving; the old design cut it off
at roughly 11 source lines to keep the picker on-screen.

Root cause: PlanConfirm rendered both the plan body (via Markdown)
AND the 3-option picker inside one Ink modal, with a hard line clamp
so total height never exceeded the TTY. The clamp fired unavoidably
on any non-trivial plan.

Fix: push the plan body to Static scrollback as a new display role
"plan" the moment submit_plan fires. The Static component renders
once into the terminal's permanent buffer (users can scroll back
through the terminal itself), and the PlanConfirm modal below
shrinks to a tight picker header + choice list. No truncation ever.

Changes:
- EventLog.tsx: new DisplayRole "plan" renders the plan body through
  the full Markdown pipeline inside a cyan-bordered box with a 📋
  header. Goes into <Static> so it's render-once + scrollable.
- App.tsx: on submit_plan detection, setHistorical pushes a "plan"
  row BEFORE setPendingPlan so the body is in scrollback by the
  time the modal mounts.
- PlanConfirm.tsx: dropped the embedded Markdown render, the line-
  clamp helper (clampBodyByLines), maxRenderedChars / terminalRows
  props, and the two constants that drove them. The modal is now
  just a header + open-questions hint + SingleSelect.
- tests/plan-confirm.test.ts deleted — its 5 tests were all for
  the removed clampBodyByLines helper.

Everything else (approve/refine/cancel semantics, staged-input
handoff, hasOpenQuestions hint toggle) unchanged. 1054 tests green.
2026-04-24 07:05:40 -07:00
esengine c5b0906576 fix(skill): run_skill accepts decorated names; index uses trailing [🧬 subagent] tag
Users hit \`run_skill({"name":"🧬 explore"}) → {"error":"unknown skill: \"🧬 explore\""}\`.
The Skills index wrote entries like \`- 🧬 explore — …\`, with the marker
LEADING the name. Models copied the whole thing verbatim into the
\`name\` argument and the lookup failed (VALID_SKILL_NAME regex rejects
emoji + spaces).

Two fixes, defense in depth:

1. Prompt format (primary fix). Rewrite skillIndexLine so the
   subagent marker trails the name, bracketed and labeled:
     old: \`- 🧬 explore — …\`
     new: \`- explore [🧬 subagent] — …\`
   Name comes first, unambiguous. The index intro + tool descriptions
   + CODE_SYSTEM_PROMPT all explicitly spell out "the \`name\` is ONLY
   the identifier before the tag."

2. run_skill normalization (belt-and-suspenders). If the model still
   passes a decorated name, strip \`[...]\` bracketed tags and pick
   the first whitespace-delimited token that starts with a word
   character. Handles every shape observed in the wild:
     "🧬 explore", "[🧬 subagent] explore", "[🧬] explore",
     "explore [🧬 subagent]", "  explore  "  → all resolve to "explore"

Tests:
- tests/skills.test.ts: updated to expect the trailing-tag format,
  explicit regression assertion against the old \`- 🧬 name\` pattern.
- tests/tools-skills.test.ts: new "normalizes decorated names" case
  exercising each decoration shape through run_skill dispatch.

All 1059 tests green.
2026-04-24 06:55:07 -07:00
esengine 30ca814809 feat(cost): model self-report escalation — flash emits <<<NEEDS_PRO>>>, loop retries on pro
Reactive-only escalation (wait for flash to rack up 3+ errors before
bumping to pro) burns tokens and time on tasks flash itself could
recognize as too hard upfront. Add a prompt-level contract: on flash,
the model can output `<<<NEEDS_PRO>>>` as the FIRST line of its
response to abort the current call and retry this turn on v4-pro,
one shot. Pro never self-escalates (the check short-circuits when
modelForCurrentCall === ESCALATION_MODEL).

This matters because non-expert users can't reliably predict which
tasks need the frontier tier. Letting the model self-assess catches
hard tasks upfront — design tradeoffs, architecture refactors, subtle
invariants — without auto-upgrading every prompt (which would destroy
the cost savings from flash-first defaults).

Implementation:
- loop.ts: NEEDS_PRO_MARKER constant, isEscalationRequest() helper,
  post-call retry check that sets _escalateThisTurn and re-enters
  the iter with `iter--; continue` on match. Streaming path buffers
  the first 80 chars / first line before yielding assistant_delta
  events so the marker never flickers on-screen before retry fires.
  Guarded against infinite retries by checking modelForCurrentCall
  against ESCALATION_MODEL — users who already chose /preset max
  see the marker as normal content.

- prompt-fragments.ts: new ESCALATION_CONTRACT fragment spells out
  when to use the marker (cross-file refactors, subtle correctness
  invariants, design tradeoffs) and when NOT to (small edits, clear
  bug fixes). Embedded into CODE_SYSTEM_PROMPT, DEFAULT_SYSTEM, and
  DEFAULT_SUBAGENT_SYSTEM — subagents default to flash+high too,
  so they benefit from the same escape hatch.

Tests (3 new in loop.test.ts):
- flash emits marker → retry on pro, final content is pro's response
- marker mid-text (not lead-in) → no retry
- pro emits marker → no infinite-retry loop

All 1058 tests green.
2026-04-24 06:47:31 -07:00
esengine 000e7c3ac0 docs(architecture): rewrite for v0.6 — four pillars, flash-first, new module layout
The previous ARCHITECTURE.md stopped at v0.3 (MCP + session persistence)
and read three-pillar (cache loop, harvest, tool-call repair) with a
roadmap that predates everything from v0.4 onward. After six months
of cost and refactor work the codebase is fundamentally different:
file layout reorganized, defaults flipped flash-first, branch + harvest
removed from every preset, /pro arming and failure-triggered
auto-escalation added.

New sections:
- Pillar 4 — Cost Control as a first-class subsystem: tiered defaults,
  turn-end auto-compaction, /pro one-shot arming, failure-signal
  auto-escalation, cost transparency thresholds.
- Module layout refreshed — reflects the slash/ + handlers/ split,
  the six hooks under cli/ui/, prompt-fragments.ts, and actual LOC
  counts (App.tsx 2931 → 1984).
- Design evolution replaces the stale roadmap — covers v0.0 through
  v0.6 with a line each so readers orient without reading six months
  of CHANGELOG.
- Non-goals updated to call out "automatic cost escalation without
  user-visible announcement" as explicitly rejected.

Pillar 2 (harvest) and Pillar 3 (tool-call repair) content kept intact
and marked as before. Pillar 1 unchanged.

Pure docs change — no code touched.
2026-04-24 06:32:00 -07:00
esengine a22355a2ab feat(cost): per-turn cost badge in StatsPanel + pro armed/escalated pills
Cost transparency is the last piece of the cost-control design —
users can now see at a glance how much the current turn cost and
which model it ran on, without opening /stats.

StatsPanel header picks up two new pills:
- ⇧ pro armed (yellow) — /pro queued, next turn will run on v4-pro
- ⇧ pro escalated (red) — current turn is on v4-pro (either /pro
  armed was consumed at turn start, or the failure threshold
  tripped mid-turn auto-escalation)

The cost cell now splits into two readings:
- turn $0.0042 — last turn's cost, colored by threshold
  (green <$0.05, yellow $0.05-0.20, red ≥$0.20)
- session $0.1234 — cumulative, same color scale 10× up
  (green <$0.50, yellow $0.50-5, red ≥$5)

No hard circuit-breaker that blocks turns — a mid-session pop-up
gate would be annoying. The colored thresholds are the signal;
users who notice yellow/red can /preset fast or /compact before
shipping the next message.

Plumbing:
- telemetry.ts: SessionSummary.lastTurnCostUsd added. Populated by
  SessionStats.summary() from the most recent TurnStats.cost.
- replay.ts + ReplayApp.tsx: summary-shape call sites updated.
- StatsPanel.tsx: proArmed/escalated props; CostCell refactor;
  turnCostColor/sessionCostColor threshold helpers.
- slash types: armPro / disarmPro ctx callbacks so the /pro handler
  can update App's mirror state synchronously.
- App.tsx: proArmed + turnOnPro state mirrors, turn-start/end
  transitions, warning-event sniff for "⇧" prefix flips turnOnPro.

Tests: 1055 green, typecheck + biome clean.
2026-04-24 06:27:23 -07:00
esengine 39a4e137dc feat(cost): /pro single-turn arming + auto-escalate on repeated flash failures
Two cost-aware escalation paths join the loop, keeping flash-first
as the default but letting the system (or the user) bump to v4-pro
when flash is visibly struggling — without requiring a persistent
preset switch.

1. `/pro` slash command arms pro for the NEXT turn only. Consumed
   at turn start, auto-disarms after the turn ends. Use case: the
   user knows the upcoming ask is hard and wants one-shot strength
   without typing /preset max + remembering to revert. Separate from
   /preset max (persistent, changes this.model) — armed state is
   strictly single-turn.

2. Auto-escalation on failure. The loop tracks visible "flash is
   struggling" signals per turn:
     - edit_file / write_file SEARCH-not-found errors
     - ToolCallRepair fires: scavenge, truncation-fix, storm-break
   Once the count hits FAILURE_ESCALATION_THRESHOLD (3) in one
   turn, the remainder of that turn's model calls upgrade to
   v4-pro. Announced via a yellow warning row — no silent cost
   surprises. Counter + escalation flag reset at every turn start.

Wiring:
- loop.ts: `_proArmedForNextTurn`, `_escalateThisTurn`,
  `_turnFailureCount` private state. Public `armProForNextTurn`,
  `disarmPro`, `proArmed`, `escalatedThisTurn` getters for UI.
  `modelForCurrentCall()` returns the effective model (escalated
  or this.model). `noteToolFailureSignal()` centralizes the
  increment+threshold logic.
- All three chat call sites (branch path, streaming, non-streaming)
  use `modelForCurrentCall()` instead of `this.model` directly.
- stats.record uses the actual model for cost attribution.
- Library-mode default model: v4-pro → v4-flash (aligned with CLI).
- slash/handlers/model.ts: new `pro` handler with /pro, /pro off.
- slash/commands.ts: /pro registered in SLASH_COMMANDS + /help text.

Tests: 1055 green, typecheck + biome clean.
2026-04-24 05:51:24 -07:00
esengine 0383255de2 feat(cost): auto-compact tool results at turn end + lower proactive threshold
Context bloat was the real cost driver, not model tier. A single
read_file returning 12K tokens rides every subsequent turn's prompt
at the cache-hit rate; 10 reads accumulate to 100K+ carry-cost
that each turn pays until the 60% reactive threshold kicks in.
By then the user has already paid for 20-40 turns of inflated
context.

Two changes shift us from reactive to preventive:

1. autoCompactToolResultsOnTurnEnd — fires at every `done` event
   (normal completion, abort, forced summary). Shrinks every tool
   result in the log over 3000 tokens to a tight cap. The model
   can re-read the file if it needs fresh detail — one extra
   read_file call is far cheaper than dragging 12KB through every
   future turn.

2. Proactive in-turn threshold lowered from 60% → 40%. The turn-end
   compact already handles the common case; this threshold now
   only catches multi-iter turns where one tool returned a huge
   payload mid-turn, before the turn ends. 40% triggers earlier
   without waiting for context to get tight.

Net impact on long sessions: per-turn prompt tokens stop compounding.
Expected monthly cost reduction for active users: ~3-5× on long
projects where tool results accumulate.

Constants:
- TURN_END_RESULT_CAP_TOKENS = 3000 (new)
- ARGS_COMPACT_THRESHOLD_TOKENS = 800 (unchanged; per-response args shrink)

Tests: 1055 green, typecheck + biome clean.
2026-04-24 05:22:32 -07:00
esengine b2a50d50f5 feat(cost): cheap defaults everywhere — flash-first, pro opt-in, no auto-branch/harvest
Overhauls the cost model so `reasonix code` doesn't burn pro-tier
tokens by default. Three principles:

1. The default turn runs on v4-flash, not v4-pro. Pro is a ~12× tier
   and shouldn't be implicit. Users escalate with /preset max.
2. Branch and harvest are NEVER auto-enabled by any preset. Both
   multiply per-turn cost (N× and +1 flash call respectively); both
   now require explicit /branch N or /harvest on.
3. Non-user-facing model calls (forced summary on budget exhaustion,
   subagent runs, truncation repair) route through flash+high
   regardless of the user's main-turn tier. No reason to pay pro
   rates for a wrap-up paragraph or an explore subagent's grep chain.

Preset redefinition (branch=1, harvest=false for all three):
  fast   v4-flash + effort=high   cheapest · Q&A, one-line edits
  smart  v4-flash + effort=max    default · day-to-day coding
  max    v4-pro   + effort=max    ~12× fast · hard single-shots

Default preset is now `smart` (was `fast`) — flash+max is the best
price-per-quality point for coding work. `fast` is the "I just want
a quick answer" escape hatch.

Specific changes:
- cli/ui/presets.ts — new PresetSettings shape adds `reasoningEffort`;
  PRESETS values rewritten; PRESET_DESCRIPTIONS reflect cost story;
  `resolvePreset` default is now "smart".
- cli/resolve.ts — ResolvedDefaults gains `reasoningEffort`; default
  preset is "smart".
- cli/commands/code.tsx — default model v4-pro → v4-flash.
- tools/subagent.ts — DEFAULT_SUBAGENT_MODEL v4-pro → v4-flash;
  DEFAULT_SUBAGENT_EFFORT = "high" (down from parent's "max").
  Skill frontmatter `model:` / `effort:` remain the escape hatches.
- loop.ts — forceSummaryAfterIterLimit hard-codes flash+high for the
  wrap-up call; stats.record attributes the actual summaryModel so
  /stats reflects reality.
- slash handlers — /preset rewritten (persists effort now); /harvest
  and /branch print cost-warning suffixes; /help + /keys text updated
  to match new presets and warn harvest/branch are opt-in only.
- CLI --help strings for `reasonix chat` / `reasonix code` / `--preset`
  / `--harvest` / `--branch` updated.

Tests:
- resolve.test.ts: expectations updated to new defaults (flash+max,
  no branch in max preset).
- slash.test.ts: preset test expectations updated to new combos.
- subagent.test.ts: default-model fallback expectation updated.
All 1055 tests green; typecheck + biome clean.
2026-04-24 04:59:15 -07:00
esengine e486a8e23a refactor(prompt): share TUI formatting + negative-claim rules across prompts
The TUI formatting rules (GFM tables, no Unicode box-drawing, no
decorative ┌──┐ frames, flow charts as bullet lists) were
maintained as three near-identical copies across
DEFAULT_SUBAGENT_SYSTEM, BUILTIN_EXPLORE_BODY, and
BUILTIN_RESEARCH_BODY — and missing entirely from
CODE_SYSTEM_PROMPT, even though the main code reply goes through
the same markdown renderer.

Subagents also lacked the "negative claims are the #1
hallucination shape" guardrail that the main code prompt has.
When an explore/research subagent confidently reported "X is
missing", the parent swallowed it at face value.

Changes:
- New src/prompt-fragments.ts holds TUI_FORMATTING_RULES and
  NEGATIVE_CLAIM_RULE as shared constants — single source of
  truth, embedded literally so prefix-cache hashing stays stable.
- DEFAULT_SUBAGENT_SYSTEM, BUILTIN_EXPLORE_BODY, and
  BUILTIN_RESEARCH_BODY import and interpolate both fragments
  instead of open-coding their own copies.
- CODE_SYSTEM_PROMPT imports TUI_FORMATTING_RULES and appends it
  after the Style section.
- CODE_SYSTEM_PROMPT's intro tool list now names every
  filesystem tool (read_file, write_file, edit_file,
  list_directory, directory_tree, search_files, search_content,
  get_file_info) instead of trailing off at "etc." before the
  essential search_content / edit_file were listed.

Behavior change is small and aligned: fewer hallucinated absences
from subagents, fewer Unicode-box-drawing tables to patch around
in markdown.tsx. Typecheck + biome + 1055 tests green.
2026-04-24 04:38:56 -07:00
esengine a4c1e9b478 refactor(ui): split slash.ts into per-topic handler modules
slash.ts had 1786 lines: types + SLASH_COMMANDS spec + parse
helpers + a ~800-line handleSlash switch + five private feature
handlers + utility helpers. Adding a command meant editing a
monolith; tests had to load the whole thing just to call one
handler. Layout:

    slash.ts                   20-line barrel (re-exports only)
    slash/types.ts             SlashResult / SlashContext / ...
    slash/commands.ts          SLASH_COMMANDS + parse functions
    slash/helpers.ts           git/memory/token/MCP utilities
    slash/dispatch.ts          SlashHandler type + registry +
                               handleSlash lookup
    slash/handlers/
      basic.ts     exit/clear/new/keys/help/setup/retry
      mcp.ts       mcp
      memory.ts    memory family
      skill.ts     skill/skills
      admin.ts     hooks/update/stats
      observability.ts   think/tool/context/status/compact
      edits.ts     undo/history/show/apply/discard/plan/mode/commit
      jobs.ts      jobs/kill/logs
      sessions.ts  sessions/forget
      model.ts     model/models/harvest/preset/branch/effort

Each handler is a plain (args, loop, ctx) => SlashResult function;
aliases (exit/quit, new/reset, skill/skills, apply-plan/applyplan,
hook/hooks, think/reasoning, help/?) are just duplicate keys in
the per-module handlers bag. The public import surface is
preserved via the barrel so App.tsx, tests, and sibling
components keep their existing imports.

Result: slash.ts 1786 -> 20 lines, fanned out into 13 focused
files each under 265 lines. Typecheck + biome + 1055 tests green.
2026-04-24 04:28:52 -07:00
esengine 9fdbdf738b refactor(ui): extract hooks + live components from App.tsx
App.tsx had grown to 2931 lines: streaming state, edit history,
pending-edits, shell/plan/edit confirm, @-picker, slash pickers,
subagent sink, hooks live-reload and cursor tracking all in one
function body. Split the cohesive clusters into dedicated modules
with no behavior change:

- LiveRows.tsx      StatusRow / ModeStatusBar / UndoBanner /
                    SubagentRow / OngoingToolRow + summarizeToolArgs
- edit-history.ts   EditHistoryEntry type + isEntryFullyUndone /
                    entryStatus / format{EditResults,PendingPreview,
                    UndoRows} / describeRepair
- useEditHistory    session-scoped /undo /history /show machinery
- useCompletionPickers  slash-name, @-mention, slash-arg pickers
- useSessionInfo    mount-time fetch of balance / models /
                    latestVersion + refresh callbacks
- useSubagent       subagent sink ref + live activity row

Also drops two dead helpers (formatQueuedEditPreview,
formatUndoResults) that had no callers.

Result: App.tsx 2931 -> 1984 lines (-32%). Typecheck + biome +
1055 tests green.
2026-04-24 04:28:33 -07:00
esengine f3f844b3dc fix(lint): pass biome check for 0.5.24 (format + unused template + exhaustive deps + comma/assign)
- biome format pass on EditConfirm / edit-blocks / jobs / shell /
  filesystem / compact-tokens / App / slash (auto-fixes)
- drop backtick template on a plain-string literal ("failed",
  "(already reverted — …)")
- annotate interceptor useEffect with a useExhaustiveDependencies
  ignore — the closure captures are intentional; adding the refs as
  deps would tear down the interceptor on every mode flip
- add codeHistory / codeShowEdit to handleSubmit deps
- expand comma-operator tricks in tests/tools.test.ts into
  explicit statements (biome rejects `(x = 1, "y")` and comma
  operator under lint/style/noCommaOperator + noAssignInExpressions)

prepublishOnly (lint + typecheck + test + build) now passes clean.
1055 tests, dist built.
2026-04-24 02:23:37 -07:00
esengine d65ca4f67f feat(code): review/auto edit gate, background jobs, context hygiene (0.5.24)
- EditConfirm modal for per-edit review (scrollable diff); Shift+Tab
  cycles review/auto; 5s undo banner + `u` keybind; session edit
  history with /history, /show [id] [path], /undo [id] [path]
- run_background / job_output / stop_job / list_jobs tools with
  ready-signal detection; /jobs, /kill, /logs; tree-kill (Windows
  taskkill /T /F, POSIX process.kill(-pid)) so dev servers actually
  stop; cleanup on SIGINT / SIGTERM / exit
- Bottom mode status bar always above the prompt: mode, pending
  count, Shift+Tab hint, running-jobs tag; one-time onboarding tip
  on first launch after upgrade
- Context hygiene: read_file `range:"A-B"` + auto-preview for files
  >200 lines; directory_tree default depth 4→2 + skip deps
  (node_modules / .git / dist / …) + per-directory 50-child collapse;
  auto-compact tool-call args after each tool response (>800 tok);
  /compact now covers both tool results and tool-call args
- Persist reasoningEffort to config so /effort high survives restart
  (earlier: silently reverted to max); editMode already persisted
- Prompt: scope discipline on "run/start/launch" requests so the
  model stops after verifying instead of auto-refactoring; teach
  model that run_background is for dev servers and review-mode
  rejections should not be retried with the same SEARCH/REPLACE

tests: 1055 passing (+17 new)
2026-04-24 02:17:34 -07:00
92 changed files with 13353 additions and 2902 deletions

No files matched your search

+200
View File
@@ -3,6 +3,206 @@
All notable changes to Reasonix. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/);
this project uses [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [0.6.0] — 2026-04-24
**Headline:** Cost control becomes a first-class pillar. Default flips
flash-first, `v4-pro` is opt-in, tool results auto-compact between
turns, and the TUI grows per-turn cost visibility + a `/pro`
one-shot upgrade. Month-over-month cost on an active coding project
drops ~6–10× in practice.
### ⚠ Breaking (behavior, not API)
- **Default model is now `deepseek-v4-flash`**, not `deepseek-v4-pro`.
`reasonix code`, `reasonix chat`, and subagents all land on flash
by default. Users who need the frontier tier:
`/preset max`, `/pro`, or `--model deepseek-v4-pro` on CLI.
- **Preset defaults changed**. None of the three presets auto-enable
`branch` or `harvest` anymore — both were hidden multipliers. The
new matrix:
| preset | model | effort | harvest | branch |
|---|---|---|---|---|
| fast | v4-flash | high | off | 1 |
| smart (default) | v4-flash | max | off | 1 |
| max | v4-pro | max | off | 1 |
Users who want branching still get it via `/branch N`; users who
want harvest still get it via `/harvest on`. Neither is implicit.
- **Default preset is now `smart` (was `fast`).** Flash + full
thinking budget is the best price/quality point for coding.
- **`deepseek-chat` / `deepseek-reasoner` aliases scheduled for
removal.** Still accepted (they map to flash non-thinking /
thinking), but every user-facing surface (`/models`, setup wizard,
`--help`) now advertises `v4-flash` / `v4-pro` only.
### Added — Cost control (Pillar 4)
- **`/pro` single-turn arming** — queue v4-pro for just the next
turn; auto-disarms after. Separate from `/preset max` (persistent)
so "this one task is hard" doesn't require a preset round-trip.
Status bar shows `⇧ pro armed` in yellow while queued, `⇧ pro
escalated` in red while the turn is actually running on pro.
- **Failure-triggered auto-escalation** — the loop tracks
`edit_file` SEARCH-not-found errors + ToolCallRepair fires per
turn. 3+ signals flip the rest of the turn to `v4-pro` with a
visible warning row. Counter resets at every turn start. No
silent cost surprises.
- **Model self-report escalation (`<<<NEEDS_PRO>>>`)** — system
prompt teaches the model that when a task CLEARLY exceeds flash's
capability (complex architecture, subtle correctness, genuine
design trade-offs), emit the marker as the first line of its
response. The loop aborts that call, retries this turn on pro,
one shot. Guarded against infinite retry (pro never self-
escalates) and streaming output is buffered so the marker never
flickers on-screen before the retry fires.
- **Turn-end auto-compaction** — every tool result over 3000 tokens
gets shrunk to a cap at turn end. Biggest win for long sessions:
a 12KB `read_file` output stops re-paying its cost on every
future prompt. The proactive in-turn threshold also dropped from
60% → 40% so the reactive 80% path rarely fires.
- **Forced-summary + truncation-repair auxiliary calls hard-route to
flash+effort=high** regardless of the main-turn tier. No reason to
pay pro rates for "paraphrase these tool results into prose" or
"close this truncated JSON."
- **Subagent default flipped to `v4-flash` + `effort=high`**. Skill
frontmatter `model:` / `effort:` remain the per-skill override.
- **StatsPanel cost badges** — per-turn cost alongside session total.
Colored thresholds: turn green under $0.05, yellow $0.05–0.20,
red ≥$0.20; session same scale ×10.
### Added — UX
- **Plan body now flows into scrollback**, not inside the modal.
`submit_plan` pushes a dedicated `role: "plan"` row into the
Static log (rendered via the full markdown pipeline, never
truncated); the PlanConfirm modal below shrinks to a tight
approve/refine/cancel picker. Long plans are fully readable via
terminal scrollback.
- **Shared prompt fragments** — `TUI_FORMATTING_RULES` and
`NEGATIVE_CLAIM_RULE` live once in `src/prompt-fragments.ts`,
embedded into every system prompt (main code, default chat,
subagent, built-in skills). Three near-identical copies
collapsed; subagents gain the "don't assert absence without
checking" guardrail they previously lacked.
### Fixed
- **`run_skill` accepts decorated names.** The Skills index wrote
entries like `- 🧬 explore`, and models copied the whole thing
verbatim into `run_skill({name:"🧬 explore"})`. The index now
uses a trailing `[🧬 subagent]` tag after the name, and
`run_skill` normalizes inputs by stripping bracketed tags +
leading emoji before lookup. Handles `"🧬 explore"`,
`"[🧬 subagent] explore"`, `"explore [🧬 subagent]"`, etc.
- **`edit_file` result no longer shown twice.** The interceptor's
`applyNow` was pushing an info row, and the loop's tool event
re-displayed the same text as a proper tool row. Dropped the info
row push; the tool row alone carries the content.
- **`run_command` / `run_background` descriptions teach their shell
constraints upfront.** Explicit list of rejected operators
(`&&`, `||`, `|`, `;`, `>`, `<`, `2>&1`), the `cd` doesn't-persist
rule, a warning against unbounded-output commands (`netstat -ano`,
`find /`), and concrete alternatives (`npm --prefix`, `cargo -C`,
`git -C`). Models stop burning turns rediscovering these via
error replies.
### Refactored (no behavior change)
- **App.tsx split** from 2931 → ~1980 lines by extracting
`LiveRows.tsx`, `edit-history.ts`, `useEditHistory.ts`,
`useCompletionPickers.ts`, `useSessionInfo.ts`, and
`useSubagent.ts`. Every hook under 310 lines.
- **slash.ts split** from 1786 → 20-line barrel. Types,
SLASH_COMMANDS data + parse helpers, shared utility helpers, a
handler registry (`dispatch.ts`), and 10 per-topic handler files
all under `src/cli/ui/slash/`. Adding a command now means editing
one handler file + one registry line.
### Docs
- **`docs/ARCHITECTURE.md` rewritten** for v0.6. The four pillars,
current module layout (slash + handlers + hooks all reflected),
design-evolution timeline replacing the stale roadmap,
non-goals updated to call out "automatic cost escalation without
user-visible announcement" as explicitly rejected.
## [0.5.24] — 2026-04-24
**Headline:** `reasonix code` gets a proper review gate, background
process support, and aggressive context hygiene so long coding
sessions stop bleeding money.
### Added
- **Edit-gate modes (review / auto)** — `edit_file` and `write_file`
tool calls now route through a user gate. `review` (default) pops
an `EditConfirm` modal with a scrollable diff + `y/n/a/A/Esc`
keys; `auto` applies immediately and arms a 5-second undo banner.
`Shift+Tab` cycles, `/mode` sets explicitly. Persisted to
`~/.reasonix/config.json`.
- **Session edit history** — every applied batch lands in an
in-memory ring. `/history` lists them, `/show [id] [path]` dumps
a stored diff (per-file when path given), `/undo [id] [path]`
rolls back at any granularity (latest batch, specific batch,
single file inside a batch). `u` keybind reaches back past the
5-second banner as long as history has a non-undone entry.
- **Background processes** — new `run_background` / `job_output` /
`stop_job` / `list_jobs` tools for dev servers and watchers. Spawn
returns after a ready-signal match (`listening on`, `Local:`,
`compiled successfully`, …) or `waitSec` seconds. `/jobs` /
`/kill <id>` / `/logs <id>` surface them to the user. Cleanup on
SIGINT / SIGTERM / exit kills every child.
- **Per-edit review modal (`src/cli/ui/EditConfirm.tsx`)** — diff
viewport sized to terminal rows; `↑↓/j/k/Space/PgUp/PgDn/g/G`
scroll a big diff in place. `a` applies rest of turn, `A` flips
to AUTO for the session.
- **Bottom mode status bar** — always-visible line above the prompt
shows mode / pending count / Shift+Tab hint / running-jobs tag;
flashes on mode change.
- **Onboarding tip** — first `reasonix code` launch after upgrade
posts the edit-gate keybindings once; suppressed after via the
`editModeHintShown` flag.
### Changed
- **`read_file`** — adds `range:"A-B"` param (1-indexed, inclusive).
Files longer than 200 lines with no scope return an auto-preview
(head 80 + tail 40 + "N lines omitted" marker) instead of dumping
everything. One `read_file` used to burn 6.5K tokens on a fat
file; scoped reads cut that 3-5×.
- **`directory_tree`** — default `maxDepth` 4 → 2; skips
`node_modules`, `.git`, `dist`, `build`, `out`, `.next`, `.nuxt`,
`target`, `.venv`, `venv`, `__pycache__`, `.pytest_cache`,
`.mypy_cache`, `.cache`, `coverage` unless `include_deps:true`;
collapses any directory past 50 children with a nudge toward
`list_directory`.
- **Auto-compact tool-call args** — after every `tool` response, the
loop shrinks that call's `arguments` JSON if it exceeds 800
tokens. Paths and short fields stay verbatim; long SEARCH /
REPLACE / content strings get replaced with a `[…shrunk: N chars,
M lines — tool already responded, see result]` marker. Cuts
stale-args drag across every subsequent turn.
- **`/compact`** — now covers both tool results (existing) and
tool-call args (new) in one pass.
- **`reasoningEffort` persistence** — `/effort high` now writes the
choice to `~/.reasonix/config.json` and the loop picks it up at
launch. Earlier versions silently reverted to `max` every relaunch.
- **Prompt scope discipline** — code-mode prompt tells the model to
stop after "run / start / launch" tasks instead of proactively
refactoring, running tsc, or chasing unused imports.
### Fixed
- **`run_background` confirmation path** — TUI now pops the shell
confirm modal for `run_background` (not just `run_command`). A
`kind` field on `pendingShell` routes approval to
`JobRegistry.start()` so approving doesn't synchronously block on
a dev server that never exits.
- **`/kill` actually kills the tree** — Windows `taskkill /T /F`,
POSIX `process.kill(-pid, …)` on a detached child. Earlier
`SIGTERM` only killed the `npm.cmd` wrapper; `node → vite →
esbuild` survived. `/kill` also posts a late "job N exit M" row
when the stop resolves, so the user doesn't have to poll `/jobs`.
## [0.4.24] — 2026-04-22
**Headline:** `reasonix stats` is now a cross-session cost dashboard.
+166 -62
View File
@@ -6,7 +6,11 @@ Reasonix is **opinionated, not general**. Every abstraction is justified by a
DeepSeek-specific behavior or economic property. If it's generic, we don't
ship it.
## The three pillars
The product north star: **coding agent that stays cheap enough to leave on**.
A tool that quietly burns $200/month on a background project is one nobody
uses. Every subsystem below is answerable to that goal.
## The four pillars
### Pillar 1 — Cache-First Loop
@@ -37,49 +41,29 @@ timestamps each turn — cache hit rate in practice: <20%.
into the log.
**Metric.** `prompt_cache_hit_tokens / (hit + miss)` exposed per-turn and
aggregated per-session. This is the user-visible proof of Pillar 1's value.
aggregated per-session. Visible in the TUI's top-bar cache cell.
### Pillar 2 — R1 Thought Harvesting *(v0.0.3, opt-in)*
### Pillar 2 — R1 Thought Harvesting *(opt-in)*
**Problem.** R1 emits extensive `reasoning_content`. DeepSeek's own docs
recommend *not* feeding it back to the next turn. Most frameworks display it
to the user and discard. The planning signal inside is lost.
**Problem.** R1 / V4-thinking emits extensive `reasoning_content`. DeepSeek's
own docs recommend *not* feeding it back to the next turn. Most frameworks
display it to the user and discard. The planning signal inside is lost.
**Solution.** A two-stage process:
```
R1 output → Harvester (V3, cheap) → TypedPlanState
├─ subgoals: string[]
├─ hypotheses: string[]
├─ uncertainties: string[]
└─ rejectedPaths: string[]
R1 output → Harvester (v4-flash, thinking off) → TypedPlanState
├─ subgoals: string[]
├─ hypotheses: string[]
├─ uncertainties: string[]
└─ rejectedPaths: string[]
```
The harvester is a cheap V3 call with a strict JSON schema. Output is
validated at runtime. The typed state is queryable by the orchestrator — e.g.
"if `uncertainties.length > 2`, trigger branch sampling."
The harvester is a cheap flash call with a strict JSON schema. Output is
validated at runtime. **Not enabled in any preset** (see Pillar 4) — the
additional round-trip rarely pays back, so it's `/harvest on` opt-in.
### Branch-and-Select *(v0.0.5, opt-in, builds on Pillar 2)*
**Why now.** DeepSeek is cheap enough that running N=3 R1 samples is still
cheaper than a single Claude call. What was research luxury (self-consistency
sampling) becomes a practical default.
**How.** When `--branch N` (or `{ branch: N }` in code) is passed:
1. The turn is forced non-streaming (N samples must complete before we can
compare).
2. `runBranches` fires N `client.chat` calls in parallel, spreading
temperatures across `[0, 1]` to diversify reasoning paths.
3. Each sample's `reasoning_content` is piped through Pillar 2's harvest.
4. The default selector picks the sample with the fewest `uncertainties`;
ties are broken by shorter answer length (Occam).
5. The loop emits a `branch_summary` alongside the winning `assistant_final`.
**Cost.** 3× R1 on a hard math problem ≈ \$0.02 — still dominates Claude on
cost/quality for agentic work.
### Pillar 3 — Tool-Call Repair *(v0.0.1 ships complete)*
### Pillar 3 — Tool-Call Repair
**Problem.** Empirical DeepSeek failure modes:
- Tool-call JSON emitted inside `<think>`, missing from the final message.
@@ -92,7 +76,6 @@ cost/quality for agentic work.
1. **`flatten`** — schemas with >10 leaf params or depth >2 are auto-detected
on `ToolRegistry.register()` and presented to the model in dot-notation
form. `dispatch()` re-nests the args before calling the user's `fn`.
Opt out with `new ToolRegistry({ autoFlatten: false })`.
2. **`scavenge`** — regex + JSON parser sweeps `reasoning_content` for any tool
call the model forgot to emit in `tool_calls`.
3. **`truncation`** — detect unbalanced JSON and repair by closing braces or
@@ -100,48 +83,169 @@ cost/quality for agentic work.
4. **`storm`** — identical `(tool, args)` tuple within a sliding window →
suppress the call, inject a reflection turn.
### Pillar 4 — Cost Control *(v0.6)*
**Problem.** Coding agents that default to the frontier model (v4-pro, ~12×
flash cost) and accumulate full tool results in context are $150-$250/month
for active users. Most turns don't need frontier reasoning; most sessions
re-pay for tool results that were only useful once.
**Solution.** Four complementary mechanisms, none of which require manual
tuning in the common case:
#### 4.1 Tiered defaults (flash-first)
The three presets now trade only **model tier** and **reasoning effort**:
| Preset | Model | Effort | Harvest | Branch | Cost |
|---|---|---|---|---|---:|
| `fast` | `v4-flash` | `high` | off | 1 | 1× |
| `smart` (default) | `v4-flash` | `max` | off | 1 | ~1.5× |
| `max` | `v4-pro` | `max` | off | 1 | ~12× |
**Branching and harvest are never in a preset.** Both multiply cost and
rarely pay back; `/branch N` and `/harvest on` are pure opt-ins. A user can
run for weeks without ever touching them.
All auxiliary calls — `forceSummaryAfterIterLimit`, subagent spawns,
truncation repair retries — hard-code `v4-flash + effort=high` regardless
of the user's preset. There's no reason to pay pro rates for "paraphrase
these tool results into prose" or for an `explore` subagent's grep chain.
#### 4.2 Turn-end auto-compaction
Every tool result in the log exceeding `TURN_END_RESULT_CAP_TOKENS` (3000)
is shrunk to that cap when a turn ends. The model had the full text for
the turn that read it; subsequent turns see a compact summary and can
re-read if needed. One extra `read_file` call is vastly cheaper than
dragging 12KB through every future prompt.
A proactive 40% context-ratio threshold runs the same shrink pre-emptively
inside long multi-iter turns before the 80% emergency threshold fires.
#### 4.3 `/pro` single-turn arming
Users who predict a hard task type `/pro`; the **next** turn runs on
`v4-pro`, then auto-disarms. No preset churn, no forgotten revert. Armed
state is visible as a yellow `⇧ pro armed` pill in the header.
#### 4.4 Failure-signal auto-escalation
The loop counts visible "flash is struggling" events per turn:
- `edit_file` / `write_file` SEARCH-not-found errors
- ToolCallRepair fires (scavenge / truncation-fix / storm-break)
Once the count hits `FAILURE_ESCALATION_THRESHOLD` (3), the **remainder of
the current turn** runs on `v4-pro`. Announced via a yellow warning row —
no silent cost surprises. Counter + escalation flag reset at every turn
start.
Header shows a red `⇧ pro escalated` pill while the turn is on pro.
#### Cost transparency
Per-turn and session cost are colored in the StatsPanel:
- `turn $0.003` — green <$0.05, yellow $0.05–0.20, red ≥$0.20
- `session $0.12` — same scale ×10
## Module layout
```
src/
├── client.ts # httpx-equivalent DeepSeek client (fetch + SSE)
├── loop.ts # Pillar 1: Cache-First Loop (async iterator)
├── harvest.ts # Pillar 2 stub (v0.0.1 surface only)
├── repair/
│ ├── index.ts # Pillar 3 pipeline
├── client.ts # DeepSeek client (fetch + SSE)
├── loop.ts # Pillar 1 + 4 — CacheFirstLoop
├── harvest.ts # Pillar 2 — flash-backed plan-state extraction
├── repair/ # Pillar 3 pipeline
│ ├── index.ts
│ ├── scavenge.ts
│ ├── flatten.ts
│ ├── truncation.ts
│ └── storm.ts
├── tools.ts # Tool registry + dispatch
├── memory.ts # Prefix / Log / Scratch primitives
├── telemetry.ts # Cost & cache-hit accounting
├── types.ts # Shared type definitions
├── index.ts # Library barrel export
├── prompt-fragments.ts # TUI_FORMATTING_RULES, NEGATIVE_CLAIM_RULE —
│ # reused by main + subagent + skill prompts
├── code/prompt.ts # reasonix code main system prompt
├── tools/ # Tool implementations
│ ├── filesystem.ts # read / list / search / edit / write
│ ├── shell.ts # run_command + run_background (JobRegistry)
│ ├── jobs.ts # background-process registry
│ ├── memory.ts # remember / forget / list user memories
│ ├── skills.ts # list + invoke SKILL.md playbooks
│ ├── subagent.ts # spawn_subagent — flash+high by default
│ ├── plan.ts # submit_plan (review gate)
│ └── web.ts # web_search, web_fetch
├── mcp/ # MCP client + bridge (stdio + SSE)
├── memory.ts # ImmutablePrefix / AppendOnlyLog / VolatileScratch
├── project-memory.ts # REASONIX.md loader
├── user-memory.ts # ~/.reasonix/memory/ store (project + global)
├── skills.ts # built-in explore + research skills
├── session.ts # JSONL session persistence
├── telemetry.ts # cost + cache-hit accounting + SessionSummary
├── tokenizer.ts # DeepSeek V3 tokenizer (ported)
├── usage.ts # ~/.reasonix/usage.jsonl roll-up
├── types.ts # ChatMessage, ToolCall, ToolSpec
├── index.ts # library barrel
└── cli/
├── index.ts # commander entry
├── commands/ # chat, run, stats, version
└── ui/ # Ink React components (App, StatsPanel, EventLog, PromptInput)
├── index.ts # commander entry
├── resolve.ts # config + CLI flag precedence
├── commands/ # chat, code, run, stats, sessions, ...
└── ui/
├── App.tsx # root Ink component (~1984 LOC, was 2931)
├── LiveRows.tsx # spinner rows (OngoingTool / Status / ...)
├── EventLog.tsx # Historical row rendering
├── StatsPanel.tsx # top bar + cost badges
├── PromptInput.tsx # cursor-aware multi-line input
├── PlanConfirm.tsx # submit_plan review modal
├── ShellConfirm.tsx # run_command approval modal
├── EditConfirm.tsx # per-edit review modal
├── markdown.tsx # Ink-native markdown renderer
├── edit-history.ts # EditHistoryEntry + formatters
├── useEditHistory.ts # /undo, /history, /show state machine
├── useCompletionPickers.ts # slash, @, slash-arg pickers
├── useSessionInfo.ts # balance + models + updates fetch
├── useSubagent.ts # subagent sink wiring
└── slash/ # /-command implementation
├── types.ts # SlashContext, SlashResult, ...
├── commands.ts # SLASH_COMMANDS data + parse + suggest
├── helpers.ts # git, memory, token formatters
├── dispatch.ts # registry + handleSlash lookup
└── handlers/ # per-topic: basic, mcp, memory,
# skill, admin, observability, edits,
# jobs, sessions, model (/pro lives here)
```
## Roadmap
Files kept small by design: the largest module under `cli/ui/` is 2K
lines (App.tsx), every handler under `slash/handlers/` is ≤200 lines,
every hook under `cli/ui/` is ≤310 lines. Adding a new slash command
means editing one handler file and one registry line.
- **v0.0.1** — Pillar 1 end-to-end, Pillar 3 complete, Ink TUI, τ-bench scaffold.
- **v0.0.2** — First-run key prompt, saved to `~/.reasonix/config.json`.
- **v0.0.3** — Pillar 2 MVP (opt-in harvest), retry layer, TextInput fix.
- **v0.0.4** — Schema flatten auto-applied in ToolRegistry (closes Pillar 3).
- **v0.0.5** — Self-consistency branching (`--branch N`) driven by Pillar 2
plan-state uncertainty count.
- **v0.0.6** — Named session persistence (`--session <name>`), JSONL log
stored under `~/.reasonix/sessions/`, restored into the append-only log
on resume.
## Design evolution
- **v0.0.x** — Pillar 1 end-to-end, Pillar 3 complete, Ink TUI scaffold.
- **v0.1** — τ-bench numbers published, streaming polish, transcript replay.
- **v0.2** — Self-consistency / branch-budget sampling driven by plan state.
- **v0.3** — MCP client, session persistence.
- **v0.3** — MCP client (stdio + SSE), session persistence.
- **v0.4.x** — `reasonix code` with SEARCH/REPLACE edits, review/auto
gate, background jobs, hooks.
- **v0.5.x** — V4 model support, skills, memory, subagents, actionable
error messages.
- **v0.6** *(current)* —
- **Pillar 4 cost control** (flash-first defaults, auto-compaction,
`/pro` one-shot, failure-triggered escalation, cost badges).
- `deepseek-chat` / `deepseek-reasoner` scheduled for deprecation —
all user-facing surfaces updated to `v4-flash` / `v4-pro`.
- `branch` + `harvest` removed from every preset; manual opt-in only.
- Shared prompt fragments (`TUI_FORMATTING_RULES`, `NEGATIVE_CLAIM_RULE`).
- UI refactor: App.tsx split into 6 hooks/components, slash.ts split
into 13 per-topic modules.
## Explicit non-goals
- Multi-agent orchestration.
- Multi-agent orchestration as a first-class concept (subagents are a
cost-reduction mechanism, not a coordination primitive).
- RAG / vector retrieval.
- Support for non-DeepSeek backends.
- Support for non-DeepSeek backends (an OpenAI-compatible shim would
work today via `--model` override, but is not tested).
- Web UI / SaaS.
- Automatic cost escalation without user-visible announcement. Every
pro-tier model call is surfaced; silent escalation was considered
and rejected.
+2 -2
View File
@@ -1,7 +1,7 @@
{
"name": "reasonix",
"version": "0.5.23",
"description": "DeepSeek-native agent framework: cache-first loop, R1 thought harvesting, tool-call repair.",
"version": "0.7.1",
"description": "DeepSeek-native coding agent: cache-first loop, flash-first cost control, tool-call repair.",
"type": "module",
"bin": {
"reasonix": "dist/cli/index.js"
+6 -1
View File
@@ -15,6 +15,7 @@ import {
sessionPath as sessionPathOf,
} from "../../session.js";
import { ToolRegistry } from "../../tools.js";
import { registerChoiceTool } from "../../tools/choice.js";
import { registerMemoryTools } from "../../tools/memory.js";
import { registerWebTools } from "../../tools/web.js";
import { App } from "../ui/App.js";
@@ -51,7 +52,7 @@ export interface ChatOptions {
* Enable SEARCH/REPLACE edit-block processing after each assistant turn.
* Set by `reasonix code`; plain `reasonix chat` leaves this off.
*/
codeMode?: { rootDir: string };
codeMode?: { rootDir: string; jobs?: import("../../tools/jobs.js").JobRegistry };
/** Skip the session picker — assume "Resume" (backwards-compatible auto-continue). */
forceResume?: boolean;
/** Skip the session picker — assume "New" (wipe the session file and start fresh). */
@@ -255,6 +256,10 @@ export async function chatCommand(opts: ChatOptions): Promise<void> {
if (!opts.seedTools) {
if (!tools) tools = new ToolRegistry();
registerMemoryTools(tools, {});
// `ask_choice` — branching primitive, useful in chat too (stylistic
// preferences, doc language, library picks). Independent of plan
// mode, which chat doesn't have anyway.
registerChoiceTool(tools);
}
// Decide whether to show the session picker. It's gated on: session
+28 -2
View File
@@ -22,7 +22,9 @@ import { basename, resolve } from "node:path";
import { loadProjectShellAllowed } from "../../config.js";
import { sanitizeName } from "../../session.js";
import { ToolRegistry } from "../../tools.js";
import { registerChoiceTool } from "../../tools/choice.js";
import { registerFilesystemTools } from "../../tools/filesystem.js";
import { JobRegistry } from "../../tools/jobs.js";
import { registerMemoryTools } from "../../tools/memory.js";
import { registerPlanTool } from "../../tools/plan.js";
import { registerShellTools } from "../../tools/shell.js";
@@ -66,6 +68,11 @@ export async function codeCommand(opts: CodeOptions = {}): Promise<void> {
// triggered R1's DSML hallucinations all through 0.4.x.
const tools = new ToolRegistry();
registerFilesystemTools(tools, { rootDir });
// Background-process registry shared between the shell tools and the
// TUI's /jobs + /kill slashes + exit cleanup. One per `reasonix code`
// run — orphan prevention on SIGINT / process exit kills everything
// it owns, so dev servers don't outlive the Reasonix process.
const jobs = new JobRegistry();
registerShellTools(tools, {
rootDir,
// Per-project "always allow" list persisted from prior ShellConfirm
@@ -74,12 +81,19 @@ export async function codeCommand(opts: CodeOptions = {}): Promise<void> {
// via ShellConfirm mid-session takes effect on the next shell call
// instead of waiting for `/new` or a relaunch.
extraAllowed: () => loadProjectShellAllowed(rootDir),
jobs,
});
// `submit_plan` is always in the spec list so the prefix cache stays
// stable across plan-mode toggles (Pillar 1). The tool itself is a
// no-op outside plan mode and throws `PlanProposedError` when the
// user has `/plan`-enabled the session.
registerPlanTool(tools);
// `ask_choice` — branching primitive. Independent of plan mode: the
// model uses it to put a 2–4 way choice in front of the user
// (strategy, style, library pick) without trying to squeeze the
// menu into a submit_plan body. Keeping it always-registered
// preserves the prefix cache across plan-mode toggles.
registerChoiceTool(tools);
// `remember` / `forget` / `recall_memory` — cross-session user memory.
// Project scope hashes off rootDir so switching projects gets a fresh
// per-project memory store; the global scope is shared across runs.
@@ -94,14 +108,26 @@ export async function codeCommand(opts: CodeOptions = {}): Promise<void> {
`▸ reasonix code: rooted at ${rootDir}, session "${session ?? "(ephemeral)"}" · ${tools.size} native tool(s)\n`,
);
// Belt-and-suspenders cleanup: even though spawn(detached:false)
// should tie child processes to the parent's lifetime, Windows cmd.exe
// wrappers occasionally leak. Kill everything on both clean and
// signal-driven exits. 'exit' fires too late for async I/O but is our
// only guaranteed last word; the signal handlers do the heavy lifting.
const sigShutdown = () => {
void jobs.shutdown();
};
process.once("SIGINT", sigShutdown);
process.once("SIGTERM", sigShutdown);
process.once("exit", sigShutdown);
await chatCommand({
model: opts.model ?? "deepseek-v4-pro",
model: opts.model ?? "deepseek-v4-flash",
harvest: opts.harvest ?? false,
system: codeSystemPrompt(rootDir),
transcript: opts.transcript,
session,
seedTools: tools,
codeMode: { rootDir },
codeMode: { rootDir, jobs },
forceResume: opts.forceResume,
forceNew: opts.forceNew,
});
+16 -7
View File
@@ -1,6 +1,7 @@
import { Command } from "commander";
import { readConfig } from "../config.js";
import { VERSION } from "../index.js";
import { ESCALATION_CONTRACT } from "../prompt-fragments.js";
import { applyMemoryStack } from "../user-memory.js";
import { chatCommand } from "./commands/chat.js";
import { codeCommand } from "./commands/code.js";
@@ -28,7 +29,15 @@ Every factual claim about a codebase must be backed by evidence. Reasonix VALIDA
**Negative claims** ("X is missing", "Y isn't implemented", "lacks Z") are the #1 hallucination shape. STOP before writing them. If you have a search tool, call it first; if the search returns nothing, cite the search itself as evidence (\`No matches for "foo" in src/\`). If you have no tool, qualify hard: "I haven't verified — this is a guess."
Asserting absence without checking is how evaluative answers go wrong. Treat the urge to write "missing" as a red flag in your own reasoning.`;
Asserting absence without checking is how evaluative answers go wrong. Treat the urge to write "missing" as a red flag in your own reasoning.
# Don't invent what changes — search instead
Your training data has a cutoff. When an answer's correctness depends on something that changes over time (the user is asking what's happening, not what's true) and a search tool is available, search first. Inventing currently-correct values from training memory is the most common way these answers go wrong, and the user usually can't tell until much later.
The signal isn't a topic list — it's: "if I'm wrong about this, is it because reality moved on?". If yes, ground the answer in fresh evidence; if no (definitions, mechanisms, well-established APIs), answer from memory.
${ESCALATION_CONTRACT}`;
const program = new Command();
program
@@ -68,16 +77,16 @@ program
program
.command("code [dir]")
.description(
"Code-editing chat — filesystem tools rooted at <dir> (default: cwd), coding system prompt, deepseek-reasoner. Model proposes SEARCH/REPLACE blocks; Reasonix applies them to disk.",
"Code-editing chat — filesystem tools rooted at <dir> (default: cwd), coding system prompt, v4-flash. Model proposes SEARCH/REPLACE blocks; Reasonix applies them to disk. Use /preset max or /pro to escalate to v4-pro on hard tasks.",
)
.option("-m, --model <id>", "Override default reasoner model")
.option("-m, --model <id>", "Override default model (v4-flash)")
.option("--no-session", "Disable session persistence for this run")
.option("-r, --resume", "Skip the session picker — always continue prior messages")
.option("-n, --new", "Skip the session picker — always wipe prior messages and start fresh")
.option("--transcript <path>", "Write a JSONL transcript to this path")
.option(
"--harvest",
"Extract typed plan state from R1 reasoning (Pillar 2). Adds ~10-15% cost per turn. Off by default in code mode.",
"Opt-in Pillar-2 plan-state extraction. Adds one flash call per turn; off by default (no preset enables it).",
)
.action(async (dir: string | undefined, opts) => {
await codeCommand({
@@ -99,15 +108,15 @@ program
.option("--transcript <path>", "Write a JSONL transcript to this path")
.option(
"--preset <name>",
"Bundle of model + harvest + branch. One of: fast, smart, max. Overrides config.preset.",
"Model + effort bundle. One of: fast (flash·high), smart (flash·max, default), max (pro·max). Overrides config.preset.",
)
.option(
"--harvest",
"Extract typed plan state from R1 reasoning (Pillar 2). Overrides preset's harvest setting.",
"Opt-in Pillar-2 plan-state extraction. Off by default — no preset enables it.",
)
.option(
"--branch <n>",
"Self-consistency: run N parallel samples per turn and pick the most confident (disables streaming; enables harvest)",
"Self-consistency: run N parallel samples per turn (N× cost). Manual only — never auto-enabled.",
(v) => Number.parseInt(v, 10),
)
.option("--session <name>", "Use a named session (default: from config, usually 'default').")
+5 -3
View File
@@ -6,7 +6,7 @@
* 1. Explicit per-setting CLI flag (`--model`, `--harvest`, `--branch`, `--mcp`)
* 2. Explicit `--preset <name>` CLI flag
* 3. `config.preset` from `~/.reasonix/config.json` (set by `reasonix setup`)
* 4. Hardcoded "fast" preset defaults
* 4. Hardcoded "smart" preset defaults (flash + effort=max)
*
* Keeping this logic in one place — rather than duplicating across
* `chat` and `run` — means the precedence rule only lives in one unit
@@ -18,6 +18,7 @@ import { PRESETS } from "./ui/presets.js";
export interface ResolvedDefaults {
model: string;
reasoningEffort: "high" | "max";
harvest: boolean;
branch: number | undefined;
mcp: string[];
@@ -44,6 +45,7 @@ export function resolveDefaults(flags: RawCliFlags): ResolvedDefaults {
const presetSettings = PRESETS[preset];
const model = flags.model ?? presetSettings.model;
const reasoningEffort = presetSettings.reasoningEffort;
const harvest = flags.harvest === true ? true : presetSettings.harvest;
const branchFromFlag = normalizeBranch(flags.branch);
const branch = branchFromFlag ?? (presetSettings.branch > 1 ? presetSettings.branch : undefined);
@@ -55,7 +57,7 @@ export function resolveDefaults(flags: RawCliFlags): ResolvedDefaults {
const session = resolveSession(flags.session, cfg.session);
return { model, harvest, branch, mcp, session };
return { model, reasoningEffort, harvest, branch, mcp, session };
}
function pickPreset(
@@ -64,7 +66,7 @@ function pickPreset(
): PresetName {
if (flagPreset && isPresetName(flagPreset)) return flagPreset;
if (configPreset) return configPreset;
return "fast";
return "smart";
}
function isPresetName(s: string): s is PresetName {
+1342 -693
View File
File diff suppressed because it is too large. Load diff
+82
View File
@@ -0,0 +1,82 @@
/**
* Modal picker shown when the model calls `ask_choice`. Renders the
* question + 2–4 option rows (title + dimmed summary) + an optional
* "Let me type my own answer" escape hatch when `allowCustom` is true.
*
* The escape hatch matters because DeepSeek flash sometimes misframes
* the alternatives — none actually fit the user's intent. Without a
* bailout the user would have to cancel, type feedback, and wait for
* another round-trip. With it they just type and ship.
*
* Border color: magenta — deliberately distinct from cyan (plan),
* green (checkpoint), red (shell) so the user's eye learns the modes
* without reading headers.
*/
import { Box, Text } from "ink";
import React from "react";
import type { ChoiceOption } from "../../tools/choice.js";
import { SingleSelect } from "./Select.js";
export type ChoiceConfirmChoice =
| { kind: "pick"; optionId: string }
| { kind: "custom" }
| { kind: "cancel" };
export interface ChoiceConfirmProps {
question: string;
options: ChoiceOption[];
allowCustom: boolean;
onChoose: (choice: ChoiceConfirmChoice) => void;
}
const CUSTOM_VALUE = "__custom__";
const CANCEL_VALUE = "__cancel__";
function ChoiceConfirmInner({ question, options, allowCustom, onChoose }: ChoiceConfirmProps) {
const items: Array<{ value: string; label: string; hint?: string }> = options.map((opt) => ({
value: opt.id,
label: `${opt.id} · ${opt.title}`,
hint: opt.summary,
}));
if (allowCustom) {
items.push({
value: CUSTOM_VALUE,
label: "Let me type my own answer",
hint: "None of the above fits — type a free-form reply. The model reads it verbatim.",
});
}
items.push({
value: CANCEL_VALUE,
label: "Cancel — drop the question",
hint: "Model stops and asks what you want instead.",
});
return (
<Box flexDirection="column" borderStyle="round" borderColor="magenta" paddingX={1} marginY={1}>
<Box>
<Text bold color="magenta">
🔀 the model is asking you to pick
</Text>
</Box>
<Box marginTop={1}>
<Text>{question}</Text>
</Box>
<Box marginTop={1}>
<SingleSelect
initialValue={options[0]?.id}
items={items}
onSubmit={(v) => {
if (v === CUSTOM_VALUE) onChoose({ kind: "custom" });
else if (v === CANCEL_VALUE) onChoose({ kind: "cancel" });
else onChoose({ kind: "pick", optionId: v });
}}
onCancel={() => onChoose({ kind: "cancel" })}
footer="[↑↓] navigate · [Enter] select · [Esc] cancel"
/>
</Box>
</Box>
);
}
export const ChoiceConfirm = React.memo(ChoiceConfirmInner);
+220
View File
@@ -0,0 +1,220 @@
import { Box, Text, useInput, useStdout } from "ink";
import React, { useMemo, useState } from "react";
import { formatEditBlockDiff } from "../../code/diff-preview.js";
import type { EditBlock } from "../../code/edit-blocks.js";
/**
* Choice surfaced to the interceptor when the user resolves the modal:
* - `apply` → apply this edit, keep prompting on next.
* - `reject` → tell the model the user refused; do NOT
* retry the same edit.
* - `apply-rest-of-turn` → apply this edit AND every remaining edit
* this turn without further prompts. Resets
* at the next user turn.
* - `flip-to-auto` → apply this edit + persistently switch the
* session to AUTO mode (survives restart).
*/
export type EditReviewChoice = "apply" | "reject" | "apply-rest-of-turn" | "flip-to-auto";
export interface EditConfirmProps {
block: EditBlock;
onChoose: (choice: EditReviewChoice) => void;
}
/**
* Overhead reserved for non-diff UI inside the modal: border (2),
* title (1), separator (1), file-header (1), scroll-indicator rows
* (up to 2), footer + margin (3), plus breathing room for the host
* TUI's chrome above (stats panel ≈ 4, historical live rows, prompt
* input ≈ 2). 18 rows absorbed before the diff gets any budget.
*/
const MODAL_OVERHEAD_ROWS = 18;
/**
* Absolute floor on the diff viewport. If the terminal is absurdly
* short (< 26 rows total) we still show at least 8 diff lines so the
* modal is usable; the user scrolls more aggressively but can't end up
* with a zero-height viewport.
*/
const MIN_DIFF_ROWS = 8;
/**
* Modal-style approval for a single model-proposed file edit.
*
* Why per-edit instead of end-of-turn batch: users reported they can't
* tell if the model is about to make one small change or seven sprawling
* ones until the turn is over. Per-edit prompts let the user intervene
* early — reject a bad direction before the model builds on it, or
* approve the first few and hit `a` to let the rest land.
*
* Diff viewport: we compute the UNCAPPED diff once, then slice to a
* height budget derived from terminal rows. Large diffs (100+ lines)
* are scrollable via j/k/↑/↓/Space/PgUp/PgDn/g/G — the user can page
* through the whole change before deciding, and the action footer
* never scrolls off the bottom. Before the scroll support a 97-line
* scene.ts diff truncated at "… 67 more …" which was unreviewable.
*/
export function EditConfirm({ block, onChoose }: EditConfirmProps) {
const { stdout } = useStdout();
const rows = stdout?.rows ?? 40;
const budget = Math.max(MIN_DIFF_ROWS, rows - MODAL_OVERHEAD_ROWS);
// Full diff — maxLines pushed high enough that the diff-preview
// renderer never inserts its own truncation marker. Context trimming
// (contextLines) still applies for tight scan.
const allLines = useMemo(
() => formatEditBlockDiff(block, { contextLines: 2, maxLines: 100_000, indent: " " }),
[block],
);
const [scroll, setScroll] = useState(0);
const maxScroll = Math.max(0, allLines.length - budget);
// Clamp scroll if budget shrinks (terminal resized) after a previous
// keypress drove the offset past the new ceiling.
const effectiveScroll = Math.min(scroll, maxScroll);
useInput((input, key) => {
// Action keys first — decision wins over scroll so a user who
// hammered PgDn can still hit `y` at the end without a stray
// extra scroll.
if (key.return || input === "y") {
onChoose("apply");
return;
}
if (input === "n") {
onChoose("reject");
return;
}
if (input === "a") {
onChoose("apply-rest-of-turn");
return;
}
if (input === "A") {
onChoose("flip-to-auto");
return;
}
// Scroll navigation — vim-ish (j/k) and emacs-ish (arrows) both
// work. Space for "next page" is the pager convention.
if (key.downArrow || input === "j") {
setScroll((s) => Math.min(maxScroll, s + 1));
return;
}
if (key.upArrow || input === "k") {
setScroll((s) => Math.max(0, s - 1));
return;
}
if (key.pageDown || input === " " || input === "f") {
setScroll((s) => Math.min(maxScroll, s + Math.max(1, budget - 2)));
return;
}
if (key.pageUp || input === "b") {
setScroll((s) => Math.max(0, s - Math.max(1, budget - 2)));
return;
}
if (input === "g") {
setScroll(0);
return;
}
if (input === "G") {
setScroll(maxScroll);
return;
}
// Esc falls through to the parent abort handler.
});
const isNew = block.search === "";
const removed = isNew ? 0 : (block.search.match(/\n/g)?.length ?? 0) + 1;
const added = block.replace === "" ? 0 : (block.replace.match(/\n/g)?.length ?? 0) + 1;
const tag = isNew ? "NEW" : "EDIT";
const visibleLines = allLines.slice(effectiveScroll, effectiveScroll + budget);
const hiddenAbove = effectiveScroll;
const hiddenBelow = Math.max(0, allLines.length - effectiveScroll - budget);
const totalLines = allLines.length;
const showScrollHud = hiddenAbove + hiddenBelow > 0;
return (
<Box flexDirection="column" borderStyle="round" borderColor="cyan" paddingX={1} marginY={1}>
<Box>
<Text bold color="cyan">
{"▸ model wants to edit a file"}
</Text>
</Box>
<Box>
<Text color="cyan" dimColor>
{"──────────────────────────────────────────"}
</Text>
</Box>
<Box marginTop={1}>
<Text>
<Text color={isNew ? "green" : "yellow"} bold>{`[${tag}] `}</Text>
<Text color="cyan">{block.path}</Text>
<Text dimColor>{` (-${removed} +${added} lines)`}</Text>
{showScrollHud ? (
<Text dimColor>
{` · viewing ${effectiveScroll + 1}-${effectiveScroll + visibleLines.length}/${totalLines}`}
</Text>
) : null}
</Text>
</Box>
{hiddenAbove > 0 ? (
<Text
dimColor
>{` ↑ ${hiddenAbove} line${hiddenAbove === 1 ? "" : "s"} above (↑/k or PgUp)`}</Text>
) : null}
<Box marginTop={hiddenAbove > 0 ? 0 : 1} flexDirection="column">
{visibleLines.map((line, i) => {
const trimmed = line.trimStart();
const color = trimmed.startsWith("+")
? "green"
: trimmed.startsWith("-")
? "red"
: undefined;
const dim = !color;
return (
<Text
// Stable-enough: slice only shifts by scroll; React keys only
// need to be unique within the current render.
// biome-ignore lint/suspicious/noArrayIndexKey: list is static per render
key={`diff-${effectiveScroll}-${i}`}
color={color}
dimColor={dim}
>
{line}
</Text>
);
})}
</Box>
{hiddenBelow > 0 ? (
<Text
dimColor
>{` ↓ ${hiddenBelow} line${hiddenBelow === 1 ? "" : "s"} below (↓/j or Space/PgDn)`}</Text>
) : null}
<Box marginTop={1}>
<Text dimColor>
{"["}
<Text color="cyan" bold>
y
</Text>
{"/Enter] apply · ["}
<Text color="cyan" bold>
n
</Text>
{"] reject · ["}
<Text color="cyan" bold>
a
</Text>
{"] apply rest · ["}
<Text color="cyan" bold>
A
</Text>
{"] flip AUTO · ["}
<Text color="cyan" bold>
↑↓/Space
</Text>
{"] scroll · [Esc] abort"}
</Text>
</Box>
</Box>
);
}
+258 -58
View File
@@ -3,11 +3,49 @@ import React from "react";
import { type TypedPlanState, isPlanStateEmpty } from "../../harvest.js";
import type { BranchProgress, BranchSummary } from "../../loop.js";
import type { TurnStats } from "../../telemetry.js";
import type { PlanStep } from "../../tools/plan.js";
import { PlanStateBlock } from "./PlanStateBlock.js";
import { PlanStepList } from "./PlanStepList.js";
import { Markdown } from "./markdown.js";
import { useElapsedSeconds, useTick } from "./ticker.js";
import { formatDuration, summarizeToolResult } from "./tool-summary.js";
export type DisplayRole = "user" | "assistant" | "tool" | "system" | "error" | "info" | "warning";
export type DisplayRole =
| "user"
| "assistant"
| "tool"
| "system"
| "error"
| "info"
| "warning"
/**
* A plan body pushed to scrollback when the model calls `submit_plan`.
* Rendered through the full markdown pipeline (not truncated), so the
* user reads the whole thing in the permanent Static log and the
* PlanConfirm modal below it stays a tight picker.
*/
| "plan"
/**
* One step of an approved plan ticked off via `mark_step_complete`.
* Rendered as a compact `✓ step-id · title — result (N/M)` row so
* the user can glance at the scrollback and see how far along the
* execution is without scrolling through every tool call.
*/
| "step-progress"
/**
* Pushed once at session startup when an existing plan was loaded
* from disk. Renders as a bordered box with the step list and
* progress so the user sees exactly where they left off — much
* more useful than the bare "2/5 done" info line it replaced.
*/
| "plan-resumed"
/**
* Read-only snapshot of an archived (completed) plan, pushed by
* the `/replay` slash. Visually distinct from `plan-resumed` —
* dim border + ⏪ icon — so the user immediately sees this is
* historical, not the active plan.
*/
| "plan-replay";
export interface DisplayEvent {
id: string;
@@ -18,10 +56,58 @@ export interface DisplayEvent {
branch?: BranchSummary;
branchProgress?: BranchProgress;
toolName?: string;
/**
* 1-based position in the session's tool-call history. Rendered as a
* dim `/tool N` suffix on compact rows so the user can quickly jump
* to the full output via the existing `/tool` slash command.
*/
toolIndex?: number;
/** Wall-clock duration in ms between tool_start and result. */
durationMs?: number;
stats?: TurnStats;
repair?: string;
streaming?: boolean;
toolCallBuild?: { name: string; chars: number; index?: number; readyCount?: number };
/**
* Populated on `step-progress` rows: the step id, optional title,
* completion counter, and optional notes. Rendered into the compact
* single-row layout — no other role reads these fields.
*/
stepProgress?: {
stepId: string;
title?: string;
completed: number;
total: number;
notes?: string;
};
/**
* Populated on `plan-resumed` rows: the structured plan loaded from
* disk + the set of step ids the user had already completed +
* a relative-time hint for the header. Rendered as a bordered
* snapshot so the user picks back up immediately.
*/
resumedPlan?: {
steps: PlanStep[];
completedStepIds: string[];
relativeTime: string;
/** Optional human-friendly title; rendered in the banner header when set. */
summary?: string;
};
/**
* Populated on `plan-replay` rows: the archived plan plus enough
* navigation context (index / total) for the user to know where
* they are in the archive history.
*/
replayPlan?: {
summary?: string;
body?: string;
steps: PlanStep[];
completedStepIds: string[];
relativeTime: string;
archiveBasename: string;
index: number;
total: number;
};
/**
* Render a thin horizontal rule above this event. Used to mark
* "start of a new user turn" so long scrollbacks get visual
@@ -107,37 +193,53 @@ export const EventRow = React.memo(function EventRow({
);
}
if (event.role === "tool") {
// `flattenMcpResult` prefixes server-side errors with "ERROR: ".
// Render the tool glyph in red with a ✗ direction marker so the
// failure mode is unmissable — it's the signal the model needs
// most for its next decision.
const isError = event.text.startsWith("ERROR:");
const color = isError ? "red" : "yellow";
const glyph = isError ? ROLE_GLYPH.toolErr : ROLE_GLYPH.toolOk;
const marker = isError ? "✗" : "→";
// `edit_file` results get a dedicated diff renderer — colored
// line-by-line so `-` removals show red, `+` additions show
// green, unchanged context lines dim. Always full, never
// truncated: users need to see the whole change to trust
// /apply. Other tools keep the 400-char clip + /tool N escape.
// `edit_file` results get a dedicated multi-line diff renderer —
// colored line-by-line so `-` removals show red, `+` additions
// show green, unchanged context lines dim. Always full, never
// truncated: users need to see the whole change to trust /apply.
const isExplicitError = event.text.startsWith("ERROR:");
const isEditFile =
(event.toolName === "edit_file" || event.toolName?.endsWith("_edit_file")) && !isError;
return (
<Box flexDirection="column" marginTop={1}>
<Box>
<RoleGlyph glyph={glyph} color={color} />
<Text color={color} bold>{` ${event.toolName ?? "?"}`}</Text>
<Text color={color} dimColor>{` ${marker}`}</Text>
</Box>
<Box flexDirection="column" paddingLeft={2} marginTop={1}>
{isEditFile ? (
<EditFileDiff text={event.text} />
) : (
<Text color={isError ? "red" : undefined} dimColor={!isError}>
{truncate(event.text, 400)}
(event.toolName === "edit_file" || event.toolName?.endsWith("_edit_file")) &&
!isExplicitError;
if (isEditFile) {
return (
<Box flexDirection="column" marginTop={1}>
<Box>
<RoleGlyph glyph={ROLE_GLYPH.toolOk} color="yellow" />
<Text color="yellow" bold>{` ${event.toolName ?? "?"}`}</Text>
<Text color="yellow" dimColor>
{" →"}
</Text>
)}
</Box>
<Box flexDirection="column" paddingLeft={2} marginTop={1}>
<EditFileDiff text={event.text} />
</Box>
</Box>
);
}
// Compact one-line render for everything else. The summarizer
// produces a tool-aware one-liner (exit code for shell, line
// count for read_file, error tag for failures, ...). Full content
// remains accessible via `/tool N`, hinted as a dim suffix.
const summary = summarizeToolResult(event.toolName ?? "?", event.text);
const color = summary.isError ? "red" : "yellow";
const glyph = summary.isError ? ROLE_GLYPH.toolErr : ROLE_GLYPH.toolOk;
const marker = summary.isError ? "✗" : "→";
const durationLabel =
event.durationMs !== undefined && event.durationMs >= 100
? ` (${formatDuration(event.durationMs)})`
: "";
const indexHint = event.toolIndex !== undefined ? ` /tool ${event.toolIndex}` : "";
return (
<Box>
<RoleGlyph glyph={glyph} color={color} />
<Text color={color} bold>{` ${event.toolName ?? "?"}`}</Text>
{durationLabel ? <Text dimColor>{durationLabel}</Text> : null}
<Text color={color} dimColor>{` ${marker} `}</Text>
<Text color={summary.isError ? "red" : undefined} dimColor={!summary.isError}>
{summary.summary}
</Text>
{indexHint ? <Text dimColor>{indexHint}</Text> : null}
</Box>
);
}
@@ -159,6 +261,133 @@ export const EventRow = React.memo(function EventRow({
</Box>
);
}
if (event.role === "plan") {
return (
<Box flexDirection="column" borderStyle="round" borderColor="cyan" paddingX={1} marginY={1}>
<Box>
<Text bold color="cyan">
{"📋 plan proposed — pick a choice below"}
</Text>
</Box>
<Box marginTop={1} flexDirection="column">
<Markdown text={event.text} projectRoot={projectRoot} />
</Box>
</Box>
);
}
if (event.role === "step-progress") {
const sp = event.stepProgress;
const counter = sp && sp.total > 0 ? ` (${sp.completed}/${sp.total})` : "";
const label = sp?.title ? `${sp.stepId} · ${sp.title}` : (sp?.stepId ?? "");
return (
<Box flexDirection="column" marginTop={1}>
<Box>
<Text color="green" bold>
✓
</Text>
<Text color="green">{` ${label}`}</Text>
<Text dimColor>{counter}</Text>
</Box>
{event.text ? (
<Box paddingLeft={2}>
<Text dimColor>{event.text}</Text>
</Box>
) : null}
{sp?.notes ? (
<Box paddingLeft={2}>
<Text color="yellow" dimColor>
{`note: ${sp.notes}`}
</Text>
</Box>
) : null}
</Box>
);
}
if (event.role === "plan-resumed") {
const rp = event.resumedPlan;
if (!rp || rp.steps.length === 0) return null;
const total = rp.steps.length;
const done = rp.completedStepIds.length;
const completedSet = new Set(rp.completedStepIds);
const statuses = new Map(
rp.steps.map((s) => [
s.id,
completedSet.has(s.id) ? ("done" as const) : ("pending" as const),
]),
);
// Focus the first pending step so the user immediately sees where
// execution will resume from. If the plan is fully done, no focus
// (the picker pattern uses › for "next up").
const nextStep = rp.steps.find((s) => !completedSet.has(s.id));
return (
<Box flexDirection="column" borderStyle="round" borderColor="cyan" paddingX={1} marginY={1}>
<Box flexDirection="column">
<Box>
<Text bold color="cyan">
▸ resumed plan
</Text>
<Text dimColor>{` ${done}/${total} done · last touched ${rp.relativeTime}`}</Text>
</Box>
{rp.summary ? (
<Box>
<Text color="cyan">{` ${rp.summary}`}</Text>
</Box>
) : null}
</Box>
<Box marginTop={1} flexDirection="column">
<PlanStepList steps={rp.steps} statuses={statuses} focusStepId={nextStep?.id} />
</Box>
</Box>
);
}
if (event.role === "plan-replay") {
const r = event.replayPlan;
if (!r || r.steps.length === 0) return null;
const total = r.steps.length;
const completedSet = new Set(r.completedStepIds);
const done = completedSet.size;
const statuses = new Map(
r.steps.map((s) => [s.id, completedSet.has(s.id) ? ("done" as const) : ("pending" as const)]),
);
const navHint = r.total > 1 ? ` · ${r.index}/${r.total}` : "";
return (
<Box flexDirection="column" borderStyle="round" borderColor="gray" paddingX={1} marginY={1}>
<Box flexDirection="column">
<Box>
<Text bold dimColor>
⏪ replay
</Text>
<Text
dimColor
>{` completed ${r.relativeTime} · ${done}/${total} done${navHint}`}</Text>
</Box>
{r.summary ? (
<Box>
<Text dimColor>{` ${r.summary}`}</Text>
</Box>
) : null}
<Box>
<Text dimColor>{` ${r.archiveBasename}`}</Text>
</Box>
</Box>
{r.body ? (
<Box marginTop={1} flexDirection="column">
<Markdown text={r.body} projectRoot={projectRoot} />
</Box>
) : null}
<Box marginTop={1} flexDirection="column">
<PlanStepList steps={r.steps} statuses={statuses} />
</Box>
<Box marginTop={1}>
<Text dimColor>
{r.total > 1
? `(read-only · /replay ${r.index === 1 ? 2 : 1} for the ${r.index === 1 ? "next" : "newest"} archive)`
: "(read-only · this is an archived plan)"}
</Text>
</Box>
</Box>
);
}
if (event.role === "warning") {
return (
<Box>
@@ -518,32 +747,3 @@ function StatsLine({ stats }: { stats: TurnStats }) {
</Box>
);
}
/**
* Show the *tail* of a long tool result by default — the useful signal
* (return value, summary, error line) usually lives at the end, not the
* top-of-file boilerplate. For `ERROR:`-prefixed results, keep the
* first line intact (that's the actual error message) AND include the
* tail, so stack-trace endings stay visible too.
*
* Rendered like: `(+N earlier chars) …<tail>` so users can tell at a
* glance that something was elided. `/tool N` still dumps the full
* content for cases where the middle matters.
*/
function truncate(s: string, max: number): string {
if (s.length <= max) return s;
if (s.startsWith("ERROR:")) {
const firstNl = s.indexOf("\n");
const firstLine = firstNl === -1 ? s : s.slice(0, firstNl);
// If the first line alone is bigger than max, just show it truncated.
if (firstLine.length >= max) {
return `${firstLine.slice(0, max)}… (+${s.length - max} chars — /tool N for full)`;
}
const budget = max - firstLine.length - 10; // reserve space for separator + ellipsis
const tail = s.slice(-budget);
const skipped = s.length - firstLine.length - tail.length;
return `${firstLine}\n… (+${skipped} chars) …\n${tail}`;
}
const skipped = s.length - max;
return `… (+${skipped} earlier chars — /tool N for full) …\n${s.slice(-max)}`;
}
+275
View File
@@ -0,0 +1,275 @@
import { Box, Text } from "ink";
import React from "react";
import type { ApplyResult } from "../../code/edit-blocks.js";
import type { EditMode } from "../../config.js";
import type { JobRegistry } from "../../tools/jobs.js";
import { useElapsedSeconds, useTick } from "./ticker.js";
export const SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
/**
* Transient "what's happening now" row shown during silent phases
* between the primary events — harvest round-trip, R1 thinking
* about a tool result before the next streaming delta, forced
* summary. Matches OngoingToolRow's visual language (braille
* spinner + elapsed seconds) so the user's eyes track the same
* spot regardless of which kind of wait it is.
*/
export function StatusRow({ text }: { text: string }) {
const tick = useTick();
const elapsed = useElapsedSeconds();
return (
<Box marginY={1}>
<Text color="magenta">{SPINNER_FRAMES[tick % SPINNER_FRAMES.length]}</Text>
<Text color="magenta">{` ${text}`}</Text>
<Text dimColor>{` ${elapsed}s`}</Text>
</Box>
);
}
/**
* One-line bottom status bar showing the current edit mode, pending
* queue size (review only), an undo hint (auto only / after /apply),
* and the Shift+Tab nudge. Rendered immediately above PromptInput so
* the mode is always in peripheral vision when the user's eyes are at
* the prompt. Flashes briefly on mode change so Shift+Tab gives a
* visible acknowledgment without the user having to scan the header.
*
* The plan-mode pill takes precedence — when plan mode is on, writes
* are bounced regardless of edit mode, so surfacing it is more useful
* than the review/auto toggle.
*/
export function ModeStatusBar({
editMode,
pendingCount,
flash,
planMode,
undoArmed,
jobs,
}: {
editMode: EditMode;
pendingCount: number;
flash: boolean;
planMode: boolean;
undoArmed: boolean;
jobs?: JobRegistry;
}) {
// Subscribe to tick so the jobs count stays live — the registry is
// mutated outside React, so we need a periodic repaint to catch it.
// No-op when there's no registry (chat mode / tests).
useTick();
const running = jobs?.runningCount() ?? 0;
const jobsTag =
running > 0 ? (
<Text color="yellow" bold>{` · ⏵ ${running} job${running === 1 ? "" : "s"}`}</Text>
) : null;
if (planMode) {
return (
<Box paddingX={1}>
<Text color="red" bold inverse={flash}>
{"▸ PLAN"}
</Text>
<Text dimColor>
{" writes gated — submit_plan + approval required · /plan off to leave"}
</Text>
{jobsTag}
</Box>
);
}
const label = editMode === "auto" ? "AUTO" : "review";
const color = editMode === "auto" ? "magenta" : "cyan";
const mid =
editMode === "auto"
? undoArmed
? "edits apply immediately · u = undo last batch"
: "edits apply immediately · 5s undo window after each batch"
: pendingCount > 0
? `${pendingCount} queued · y = /apply · n = /discard`
: "edits queue for review · y = /apply · n = /discard";
const flip = editMode === "auto" ? "Shift+Tab → review" : "Shift+Tab → AUTO";
return (
<Box paddingX={1}>
<Text color={color} bold inverse={flash}>
{`▸ ${label}`}
</Text>
<Text dimColor>{` ${mid} · ${flip}`}</Text>
{jobsTag}
</Box>
);
}
/**
* "Just auto-applied N edits — press u to undo" banner. Rendered below
* the live rows after an auto-mode edit batch lands, visible for 5s.
* `useTick` drives a crude live countdown so the user sees the window
* shrinking. State cleanup (the banner disappearing) happens in the
* parent's setTimeout — the component is purely display.
*/
export function UndoBanner({
banner,
}: {
banner: { results: ApplyResult[]; expiresAt: number };
}) {
useTick();
const remainingMs = Math.max(0, banner.expiresAt - Date.now());
const remainingSec = Math.ceil(remainingMs / 1000);
const ok = banner.results.filter((r) => r.status === "applied" || r.status === "created").length;
const total = banner.results.length;
return (
<Box marginY={1} borderStyle="round" borderColor="magenta" paddingX={1}>
<Text color="magenta" bold>
{"✓ auto-applied "}
</Text>
<Text color="magenta">{`${ok}/${total} edit${total === 1 ? "" : "s"}`}</Text>
<Text dimColor>{" · press "}</Text>
<Text color="magenta" bold>
{"u"}
</Text>
<Text dimColor>{" to undo ("}</Text>
<Text color={remainingSec <= 1 ? "red" : "magenta"}>{`${remainingSec}s`}</Text>
<Text dimColor>{")"}</Text>
</Box>
);
}
/**
* Live one-line indicator for a running subagent. Sits below the
* OngoingToolRow (the parent's tool dispatch row for `spawn_subagent`)
* so the user sees both layers at once: outer "spawn_subagent
* running…" + inner "⌬ subagent: <task> · iter N · 12.3s". Cleared
* when the subagent ends; a one-line summary lands in historical.
*/
export function SubagentRow({
activity,
}: {
activity: { task: string; iter: number; elapsedMs: number };
}) {
const tick = useTick();
const seconds = (activity.elapsedMs / 1000).toFixed(1);
return (
<Box paddingLeft={2}>
<Text color="magenta">{SPINNER_FRAMES[tick % SPINNER_FRAMES.length]}</Text>
<Text color="magenta">{` ⌬ subagent: ${activity.task}`}</Text>
<Text dimColor>{` · iter ${activity.iter} · ${seconds}s`}</Text>
</Box>
);
}
/**
* Live spinner row while a tool call is in flight. Without this the
* window between the model's `tool_calls` decision and the tool's
* result (often seconds for a multi-KB `filesystem_edit_file`) looks
* like the app has frozen — the streaming assistant display is
* already cleared and the input is disabled, so there's nothing to
* look at.
*
* Shows three signals: a braille spinner (liveness), an elapsed
* timer in seconds (so "long" has a number attached), and a
* per-tool summary of the most informative argument fields (path,
* edits count, pattern, etc.). As of 0.4.8, MCP progress frames
* (`notifications/progress`) land here too — bar + "n/N" when the
* server reports a total, free-form message when not.
*/
export function OngoingToolRow({
tool,
progress,
}: {
tool: { name: string; args?: string };
progress: { progress: number; total?: number; message?: string } | null;
}) {
const tick = useTick();
const elapsed = useElapsedSeconds();
const summary = summarizeToolArgs(tool.name, tool.args);
return (
<Box marginY={1} flexDirection="column">
<Box>
<Text color="cyan">{SPINNER_FRAMES[tick % SPINNER_FRAMES.length]}</Text>
<Text color="yellow">{` tool<${tool.name}> running…`}</Text>
<Text dimColor>{` ${elapsed}s`}</Text>
</Box>
{progress ? (
<Box paddingLeft={2}>
<Text color="cyan">{renderProgressLine(progress)}</Text>
</Box>
) : null}
{summary ? (
<Box paddingLeft={2}>
<Text dimColor>{summary}</Text>
</Box>
) : null}
</Box>
);
}
/**
* Render an MCP progress frame as a single line. When the server
* reports `total`, show an ASCII progress bar + "n/total pct%";
* otherwise just "progress" + optional message. Width is modest
* so the line fits even in a narrow terminal.
*/
function renderProgressLine(p: { progress: number; total?: number; message?: string }): string {
const msg = p.message ? ` ${p.message}` : "";
if (p.total && p.total > 0) {
const ratio = Math.max(0, Math.min(1, p.progress / p.total));
const width = 20;
const filled = Math.round(ratio * width);
const bar = "█".repeat(filled) + "░".repeat(width - filled);
const pct = (ratio * 100).toFixed(0);
return `[${bar}] ${p.progress}/${p.total} ${pct}%${msg}`;
}
return `progress: ${p.progress}${msg}`;
}
/**
* Turn raw JSON tool arguments into a one-line human summary. For
* common filesystem MCP tools we pull the actually-useful fields; for
* anything else we fall back to a truncated raw string so the user
* still sees *something* beyond the tool name.
*
* Match on suffix (e.g. `_read_file`) rather than exact name because
* `bridgeMcpTools({ namePrefix: "filesystem_" })` prepends the server
* namespace — tools arrive as `filesystem_read_file` in practice but
* callers might wire up anonymous too.
*/
function summarizeToolArgs(name: string, args?: string): string {
if (!args || args === "{}") return "";
let parsed: Record<string, unknown>;
try {
parsed = JSON.parse(args) as Record<string, unknown>;
} catch {
// Unparseable JSON — show a head slice so user at least sees
// what the model tried.
return args.length > 80 ? `${args.slice(0, 80)}…` : args;
}
const hasSuffix = (s: string) => name === s || name.endsWith(`_${s}`);
const path = typeof parsed.path === "string" ? parsed.path : undefined;
if (hasSuffix("read_file")) {
const head = typeof parsed.head === "number" ? `, head=${parsed.head}` : "";
const tail = typeof parsed.tail === "number" ? `, tail=${parsed.tail}` : "";
return `path: ${path ?? "?"}${head}${tail}`;
}
if (hasSuffix("write_file")) {
const content = typeof parsed.content === "string" ? parsed.content : "";
return `path: ${path ?? "?"} (${content.length} chars)`;
}
if (hasSuffix("edit_file")) {
const edits = Array.isArray(parsed.edits) ? parsed.edits.length : 0;
return `path: ${path ?? "?"} (${edits} edit${edits === 1 ? "" : "s"})`;
}
if (hasSuffix("list_directory") || hasSuffix("directory_tree")) {
return `path: ${path ?? "?"}`;
}
if (hasSuffix("search_files")) {
const pattern = typeof parsed.pattern === "string" ? parsed.pattern : "?";
return `path: ${path ?? "?"} · pattern: ${pattern}`;
}
if (hasSuffix("move_file")) {
const src = typeof parsed.source === "string" ? parsed.source : "?";
const dst = typeof parsed.destination === "string" ? parsed.destination : "?";
return `${src} → ${dst}`;
}
if (hasSuffix("get_file_info")) {
return `path: ${path ?? "?"}`;
}
return args.length > 80 ? `${args.slice(0, 80)}…` : args;
}
+124
View File
@@ -0,0 +1,124 @@
/**
* Modal-style picker shown when `mark_step_complete` pauses the loop
* via `PlanCheckpointError`. Three choices:
*
* 1. Continue — push "Step X done, proceed." so the model starts
* the next step on the next turn.
* 2. Revise — open a feedback input; whatever the user types
* becomes a synthetic "user feedback for remaining steps" message.
* The model can then adjust its approach without starting the
* whole plan over.
* 3. Stop — push "User stopped the plan. Summarize what was
* done." so the run ends cleanly rather than being abandoned.
*
* The ✓ step-progress scrollback row is pushed separately (by App.tsx
* at checkpoint detection time), so this modal stays a tight picker —
* no need to re-render the step body here.
*/
import { Box, Text } from "ink";
import React from "react";
import type { PlanStep } from "../../tools/plan.js";
import { PlanStepList, type StepStatus } from "./PlanStepList.js";
import { SingleSelect } from "./Select.js";
export type CheckpointChoice = "continue" | "revise" | "stop";
export interface PlanCheckpointConfirmProps {
stepId: string;
title?: string;
completed: number;
total: number;
/** Full step list from the approved plan, when available. */
steps?: PlanStep[];
/** Set of stepIds the model has marked complete so far. */
completedStepIds?: Set<string>;
onChoose: (choice: CheckpointChoice) => void;
}
function PlanCheckpointConfirmInner({
stepId,
title,
completed,
total,
steps,
completedStepIds,
onChoose,
}: PlanCheckpointConfirmProps) {
const label = title ? `${stepId} · ${title}` : stepId;
const counter = total > 0 ? ` (${completed}/${total})` : "";
const isLast = total > 0 && completed >= total;
const statuses = buildStatusMap(steps, completedStepIds, stepId, isLast);
return (
<Box flexDirection="column" borderStyle="round" borderColor="green" paddingX={1} marginY={1}>
<Box>
<Text bold color="green">
▸ checkpoint — step done
</Text>
<Text dimColor>{` ${label}${counter}`}</Text>
</Box>
{steps && steps.length > 0 ? (
<Box marginTop={1} flexDirection="column">
<PlanStepList steps={steps} statuses={statuses} focusStepId={stepId} />
</Box>
) : null}
<Box marginTop={1}>
<SingleSelect
initialValue={isLast ? "stop" : "continue"}
items={[
{
value: "continue",
label: "Continue — run the next step",
hint: "Model resumes with the next step. Use this when the result looks right and you don't need to tweak the remaining plan.",
},
{
value: "revise",
label: "Revise — give feedback before the next step",
hint: "Stay paused, type guidance (scope changes, skip steps, alternative approach). The model adjusts the remaining plan based on your message.",
},
{
value: "stop",
label: "Stop — end the plan here",
hint: "Model summarizes what was done and ends. Remaining steps are skipped.",
},
]}
onSubmit={(v) => onChoose(v as CheckpointChoice)}
onCancel={() => onChoose("stop")}
footer="[↑↓] navigate · [Enter] select · [Esc] stop"
/>
</Box>
</Box>
);
}
export const PlanCheckpointConfirm = React.memo(PlanCheckpointConfirmInner);
/**
* Derive a status map from the plan + completion set + current step.
* The currently-just-finished step always renders as "done" even if
* completedStepIds hasn't been flushed yet (it gets added in the
* same render cycle, order not guaranteed). Steps ahead of the
* cursor are "pending"; the next step after the current one isn't
* marked "running" because nothing is actually running while the
* picker is up — that belongs to the post-continue state.
*/
function buildStatusMap(
steps: PlanStep[] | undefined,
completedStepIds: Set<string> | undefined,
currentStepId: string,
isLast: boolean,
): Map<string, StepStatus> {
const map = new Map<string, StepStatus>();
if (!steps) return map;
for (const step of steps) {
if (completedStepIds?.has(step.id) || step.id === currentStepId) {
map.set(step.id, "done");
} else {
map.set(step.id, "pending");
}
}
if (isLast) {
// Every step is done; leave as "done" — no "running" overlay.
}
return map;
}
+30 -92
View File
@@ -9,99 +9,33 @@
* 3. Cancel — exits plan mode, drops the plan, tells the model the
* user didn't want any of it.
*
* Mirrors ShellConfirm in structure (border, SingleSelect, three
* options, no y/n hotkey — mid-typing triggers would be painful).
* The plan body is rendered verbatim above the picker so the user can
* actually read what they're approving.
* The plan BODY is NOT rendered inside this modal — App.tsx pushes it
* into the Static scrollback as a `role: "plan"` display event the
* moment submit_plan fires. That's a one-time markdown render into
* permanent history, so the user reads the full proposal above and
* the modal below stays a tight picker. The previous design (body
* rendered inside the modal with an aggressive line clamp) left users
* staring at "(25 more lines truncated)" and unable to approve safely.
*/
import { Box, Text } from "ink";
import React from "react";
import type { PlanStep } from "../../tools/plan.js";
import { PlanStepList } from "./PlanStepList.js";
import { SingleSelect } from "./Select.js";
import { Markdown } from "./markdown.js";
export type PlanConfirmChoice = "approve" | "refine" | "cancel";
export interface PlanConfirmProps {
plan: string;
steps?: PlanStep[];
/** Optional human-friendly title from the model — surfaced in the header. */
summary?: string;
onChoose: (choice: PlanConfirmChoice) => void;
/**
* Cap on rendered plan length. A pathological 20-KB plan would push
* the picker off the bottom of the terminal; we show the head +
* "(…N chars truncated — /tool for full output)" instead. The picker
* itself gets the full plan (it's already been committed to the
* transcript via the tool result).
*/
maxRenderedChars?: number;
projectRoot?: string;
/**
* Override the terminal-row count used for vertical clamping. Tests
* pass this to avoid depending on `process.stdout.rows`; runtime
* callers leave it unset and we read the real TTY size.
*/
terminalRows?: number;
}
const DEFAULT_MAX_RENDERED = 2400;
/**
* Reserved terminal rows for the picker chrome (border + header +
* divider + open-questions hint + SingleSelect with three options +
* footer + the assistant-turn block Ink already printed above).
* Empirically ~16; we round up to 18 for safety.
*/
const PICKER_CHROME_ROWS = 18;
/**
* Rough markdown expansion factor. One source line commonly renders
* as 1–3 terminal rows: wrap on narrow terminals doubles long lines,
* code fences add top/bottom rules, list items get bullet indent,
* headings sometimes pick up blank rows. A factor of 2 is the
* conservative bet that lets us keep `bodyRowBudget` > 0 on a 24-row
* terminal while still guaranteeing the picker stays on-screen. If
* this is wrong in practice it's wrong in the "trim too aggressively"
* direction, which shows a truncation marker rather than flickering.
*/
const MARKDOWN_EXPANSION = 2;
const MIN_BODY_ROWS = 4;
/**
* Trim `text` to the first `maxLines` source lines, appending a
* truncation marker when it was cut. Source lines, NOT rendered rows
* — callers must divide their row budget by the expected markdown
* expansion factor before passing it here.
*/
export function clampBodyByLines(text: string, maxLines: number): string {
const lines = text.split("\n");
if (lines.length <= maxLines) return text;
const kept = lines.slice(0, maxLines).join("\n");
const dropped = lines.length - maxLines;
return `${kept}\n\n… (${dropped} more lines truncated — resize the terminal to see more, or /tool for the full proposal)`;
}
function PlanConfirmInner({
plan,
onChoose,
maxRenderedChars,
projectRoot,
terminalRows,
}: PlanConfirmProps) {
const cap = maxRenderedChars ?? DEFAULT_MAX_RENDERED;
const charTrunc = plan.length > cap;
const charCapped = charTrunc
? `${plan.slice(0, cap)}\n\n… (${plan.length - cap} chars truncated — use /tool to view the full proposal)`
: plan;
// Vertical clamp. Flicker root-cause: when rendered content exceeds
// the TTY row count Ink falls back to "clear + full redraw" each
// frame, and every parent re-render redraws the big Markdown subtree.
// Capping the body to (rows - picker chrome) keeps the whole modal
// inside the terminal so Ink uses incremental diffs and the picker
// stops thrashing. See Bug A in 0.5.14.
const rows = terminalRows ?? process.stdout?.rows ?? 24;
const renderedBudget = Math.max(MIN_BODY_ROWS * MARKDOWN_EXPANSION, rows - PICKER_CHROME_ROWS);
// Divide by the expansion factor so source-line clamp produces a
// rendered height that actually fits the terminal. Without this the
// rendered body overflows → Ink clears + redraws each frame → flicker.
const sourceLineBudget = Math.max(MIN_BODY_ROWS, Math.floor(renderedBudget / MARKDOWN_EXPANSION));
const visible = clampBodyByLines(charCapped, sourceLineBudget);
function PlanConfirmInner({ plan, steps, summary, onChoose }: PlanConfirmProps) {
// Crude signal for "the model left questions or risks for me" — the
// typical section headings. Triggers an extra hint toward the Refine
// option so users know where to answer them.
@@ -111,28 +45,32 @@ function PlanConfirmInner({
return (
<Box flexDirection="column" borderStyle="round" borderColor="cyan" paddingX={1} marginY={1}>
<Box>
<Text bold color="cyan">
▸ plan submitted — awaiting your review
</Text>
</Box>
<Box>
<Text color="cyan" dimColor>
{"──────────────────────────────────────────"}
</Text>
</Box>
<Box marginTop={1} flexDirection="column">
<Markdown text={visible} projectRoot={projectRoot} />
<Box flexDirection="column">
<Box>
<Text bold color="cyan">
▸ plan proposed (full text above) — approve / refine / cancel
</Text>
</Box>
{summary ? (
<Box>
<Text color="cyan">{` ${summary}`}</Text>
</Box>
) : null}
</Box>
{hasOpenQuestions ? (
<Box marginTop={1}>
<Text color="yellow">
▲ the plan has open questions or flagged risks — pick{" "}
▲ the plan flags open questions or risks — pick{" "}
<Text bold>Refine / answer questions</Text> to write concrete answers before the model
moves on.
</Text>
</Box>
) : null}
{steps && steps.length > 0 ? (
<Box marginTop={1} flexDirection="column">
<PlanStepList steps={steps} />
</Box>
) : null}
<Box marginTop={1}>
<SingleSelect
initialValue={hasOpenQuestions ? "refine" : "approve"}
+23 -8
View File
@@ -19,12 +19,15 @@ import React, { useState } from "react";
export interface PlanRefineInputProps {
/**
* Which path the user is on. Approve = "implement with these last
* instructions"; refine = "revise the plan with this feedback".
* Drives the header + hint text so users know what kind of message
* they're writing.
* Which path the user is on. approve = "implement with these last
* instructions"; refine = "revise the plan with this feedback";
* checkpoint-revise = mid-execution pause, user is tweaking the
* remaining plan after seeing a step's result; choice-custom = user
* typed an off-list answer to an ask_choice branch. Drives the
* header + hint text so users know what kind of message they're
* writing.
*/
mode: "approve" | "refine";
mode: "approve" | "refine" | "checkpoint-revise" | "choice-custom";
/** Called with trimmed feedback. Empty string is allowed. */
onSubmit: (feedback: string) => void;
/** Called when the user presses Esc to return to the picker. */
@@ -56,15 +59,27 @@ export function PlanRefineInput({ mode, onSubmit, onCancel }: PlanRefineInputPro
const title =
mode === "approve"
? "▸ approving — any last instructions or answers to open questions?"
: "▸ refining — what should the model change?";
: mode === "checkpoint-revise"
? "▸ revising — what should change before the next step?"
: mode === "choice-custom"
? "▸ custom answer — type whatever fits"
: "▸ refining — what should the model change?";
const hint =
mode === "approve"
? "Answer questions the plan raised, add constraints, or just press Enter to approve as-is."
: "Describe what's wrong or missing, or answer questions the plan raised.";
: mode === "checkpoint-revise"
? "Scope change, skip steps, alternative approach — the model will adjust the remaining plan based on this."
: mode === "choice-custom"
? "Free-form reply. The model reads it verbatim and proceeds — no need to match the listed options."
: "Describe what's wrong or missing, or answer questions the plan raised.";
const blankHint =
mode === "approve"
? " (Enter with blank = approve without extra instructions.)"
: " (Enter with blank = ask the model to list concrete questions.)";
: mode === "checkpoint-revise"
? " (Enter with blank = continue with the current plan.)"
: mode === "choice-custom"
? " (Enter with blank = ask the model what you actually want.)"
: " (Enter with blank = ask the model to list concrete questions.)";
return (
<Box flexDirection="column" borderStyle="round" borderColor="yellow" paddingX={1} marginY={1}>
+146
View File
@@ -0,0 +1,146 @@
/**
* Modal shown when the model proposes a plan revision via
* `revise_plan`. Renders a step-level diff between the old remaining
* tail and the new proposed tail:
*
* ●● ✓ step-2 · Wire middleware (kept, dim)
* − ●●● ✗ step-3 · Migrate session cookies (removed, red)
* + ●● ▶ step-3 · Skip cookie migration (added, green)
* + ●● ▶ step-4 · Update cookie tests (added, green)
*
* Two buttons: Accept / Reject. Accept replaces the in-memory plan's
* remaining steps with the new ones; Reject leaves the original plan
* intact and lets the model continue. The picker's border is amber
* to distinguish from the green checkpoint picker — revisions are a
* different decision point, deserve a different visual lane.
*/
import { Box, Text } from "ink";
import React from "react";
import type { PlanStep } from "../../tools/plan.js";
import { SingleSelect } from "./Select.js";
export type ReviseChoice = "accept" | "reject";
export interface PlanReviseConfirmProps {
reason: string;
/** Remaining steps from the current plan (before this revision). */
oldRemaining: PlanStep[];
/** Remaining steps the model is proposing as a replacement. */
newRemaining: PlanStep[];
/** Optional updated plan summary. */
summary?: string;
onChoose: (choice: ReviseChoice) => void;
}
interface DiffRow {
kind: "kept" | "removed" | "added";
step: PlanStep;
}
function computeDiff(oldSteps: PlanStep[], newSteps: PlanStep[]): DiffRow[] {
const oldIds = new Set(oldSteps.map((s) => s.id));
const newIds = new Set(newSteps.map((s) => s.id));
const rows: DiffRow[] = [];
// Show removed (in old, not in new) first — preserve original order.
for (const s of oldSteps) {
if (!newIds.has(s.id)) rows.push({ kind: "removed", step: s });
}
// Then walk new list. Steps in both lists render as kept; new-only as added.
for (const s of newSteps) {
rows.push({ kind: oldIds.has(s.id) ? "kept" : "added", step: s });
}
return rows;
}
function riskDots(risk: PlanStep["risk"]): {
dots: string;
color: "green" | "yellow" | "red" | "gray";
} {
switch (risk) {
case "high":
return { dots: "●●●", color: "red" };
case "med":
return { dots: "●● ", color: "yellow" };
case "low":
return { dots: "● ", color: "green" };
default:
return { dots: " ", color: "gray" };
}
}
function PlanReviseConfirmInner({
reason,
oldRemaining,
newRemaining,
summary,
onChoose,
}: PlanReviseConfirmProps) {
const rows = computeDiff(oldRemaining, newRemaining);
const removedCount = rows.filter((r) => r.kind === "removed").length;
const addedCount = rows.filter((r) => r.kind === "added").length;
const keptCount = rows.filter((r) => r.kind === "kept").length;
return (
<Box flexDirection="column" borderStyle="round" borderColor="yellow" paddingX={1} marginY={1}>
<Box>
<Text bold color="yellow">
✏ plan revision proposed
</Text>
<Text dimColor>{` −${removedCount} +${addedCount} (${keptCount} kept)`}</Text>
</Box>
<Box marginTop={1}>
<Text>{reason}</Text>
</Box>
{summary ? (
<Box marginTop={1}>
<Text dimColor>{`updated summary: ${summary}`}</Text>
</Box>
) : null}
<Box marginTop={1} flexDirection="column">
{rows.map((row) => {
const risk = riskDots(row.step.risk);
const prefix = row.kind === "removed" ? "−" : row.kind === "added" ? "+" : " ";
const prefixColor =
row.kind === "removed" ? "red" : row.kind === "added" ? "green" : "gray";
const dim = row.kind === "kept";
const strike = row.kind === "removed";
return (
<Box key={`${row.kind}-${row.step.id}`}>
<Text color={prefixColor} bold>
{`${prefix} `}
</Text>
<Text color={risk.color} bold dimColor={dim}>
{risk.dots}
</Text>
<Text dimColor={dim} strikethrough={strike}>
{` ${row.step.id} · ${row.step.title}`}
</Text>
</Box>
);
})}
</Box>
<Box marginTop={1}>
<SingleSelect
initialValue="accept"
items={[
{
value: "accept",
label: "Accept revision — apply the new step list",
hint: "Replaces the remaining plan with the proposed steps. Done steps are untouched.",
},
{
value: "reject",
label: "Reject — keep the original plan",
hint: "Drops the proposal. Model continues with the original remaining steps.",
},
]}
onSubmit={(v) => onChoose(v as ReviseChoice)}
onCancel={() => onChoose("reject")}
footer="[↑↓] navigate · [Enter] select · [Esc] reject"
/>
</Box>
</Box>
);
}
export const PlanReviseConfirm = React.memo(PlanReviseConfirmInner);
+138
View File
@@ -0,0 +1,138 @@
/**
* Shared compact renderer for a plan's structured step list. Used by
* PlanConfirm (on approval) and PlanCheckpointConfirm (mid-execution)
* so the user always sees the same visual representation of the plan.
*
* Layout per step:
*
* ● ✓ step-1 · Extract tokens into a module
* ●●▶ step-2 · Migrate session cookies
* ●●● step-3 · Update tests
*
* The risk gutter (1–3 dots, green/yellow/red) is the signal the user
* learns to scan: high-risk steps are what deserves review before
* approve; low-risk is noise.
*/
import { Box, Text } from "ink";
import React from "react";
import type { PlanStep, PlanStepRisk } from "../../tools/plan.js";
export type StepStatus = "pending" | "running" | "done" | "skipped";
export interface PlanStepListProps {
steps: PlanStep[];
/**
* Map of stepId → status. Missing ids default to "pending" so a
* plan just submitted (no completions yet) renders cleanly.
*/
statuses?: Map<string, StepStatus> | Record<string, StepStatus>;
/**
* Optional current step — rendered with a `›` gutter mark so the
* user sees which one just completed / is about to run.
*/
focusStepId?: string;
}
function riskDots(risk: PlanStep["risk"]): {
dots: string;
color: "green" | "yellow" | "red" | "gray";
} {
switch (risk) {
case "high":
return { dots: "●●●", color: "red" };
case "med":
return { dots: "●● ", color: "yellow" };
case "low":
return { dots: "● ", color: "green" };
default:
return { dots: " ", color: "gray" };
}
}
function statusGlyph(status: StepStatus): {
glyph: string;
color: "green" | "cyan" | "gray" | "yellow";
} {
switch (status) {
case "done":
return { glyph: "✓", color: "green" };
case "running":
return { glyph: "▶", color: "cyan" };
case "skipped":
return { glyph: "—", color: "gray" };
default:
return { glyph: " ", color: "yellow" };
}
}
function getStatus(stepId: string, statuses: PlanStepListProps["statuses"]): StepStatus {
if (!statuses) return "pending";
if (statuses instanceof Map) {
return statuses.get(stepId) ?? "pending";
}
return statuses[stepId] ?? "pending";
}
function PlanStepListInner({ steps, statuses, focusStepId }: PlanStepListProps) {
if (steps.length === 0) return null;
const hasAnyRisk = steps.some((s) => s.risk !== undefined);
const doneCount = Array.from({ length: steps.length }, (_, i) =>
getStatus(steps[i]!.id, statuses),
).filter((s) => s === "done").length;
return (
<Box flexDirection="column">
<Box>
<Text dimColor>
{`${steps.length} step${steps.length === 1 ? "" : "s"}`}
{doneCount > 0 ? ` · ${doneCount} done` : ""}
{hasAnyRisk ? " · risk: " : ""}
</Text>
{hasAnyRisk ? <RiskLegend /> : null}
</Box>
<Box flexDirection="column" marginTop={1}>
{steps.map((step) => {
const status = getStatus(step.id, statuses);
const focus = focusStepId === step.id;
const risk = riskDots(step.risk);
const glyph = statusGlyph(status);
const titleDim = status === "done" || status === "skipped";
return (
<Box key={step.id}>
<Text color={focus ? "cyan" : "gray"} bold={focus}>
{focus ? "› " : " "}
</Text>
<Text color={risk.color} bold>
{risk.dots}
</Text>
<Text color={glyph.color} bold>
{` ${glyph.glyph} `}
</Text>
<Text dimColor={titleDim}>{`${step.id} · ${step.title}`}</Text>
</Box>
);
})}
</Box>
</Box>
);
}
function RiskLegend() {
return (
<Box>
<Text color="green">●</Text>
<Text dimColor> low </Text>
<Text color="yellow">●●</Text>
<Text dimColor> med </Text>
<Text color="red">●●●</Text>
<Text dimColor> high</Text>
</Box>
);
}
export const PlanStepList = React.memo(PlanStepListInner);
export function riskOf(step: PlanStep): PlanStepRisk | undefined {
return step.risk;
}
+346 -9
View File
@@ -1,14 +1,53 @@
import { Box, Text, useInput } from "ink";
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React as a runtime value (classic transform compiles JSX to React.createElement)
import React, { useRef, useState } from "react";
import { type MultilineKey, lineAndColumn, processMultilineKey } from "./multiline-keys.js";
import {
PASTE_SENTINEL_RANGE,
type PasteEntry,
decodePasteSentinel,
encodePasteSentinel,
expandPasteSentinels,
formatBytesShort,
listPasteIdsInBuffer,
makePasteEntry,
} from "./paste-sentinels.js";
import { useTick } from "./ticker.js";
/**
* DECSET 2004 (bracketed paste) markers. The terminal sends these
* around every paste action when bracketed-paste mode is enabled
* (App.tsx writes the enable sequence at mount). Surface as exact
* literal byte strings so we can locate them in `input` regardless
* of how stdin chunks the surrounding bytes.
*/
const PASTE_START_MARKER = "\u001b[200~";
const PASTE_END_MARKER = "\u001b[201~";
/**
* Merge-fallback window for terminals that strip bracketed-paste
* markers (Windows PowerShell + ConPTY + Ink eats `\x1b[200~`).
* One Ctrl+V arrives as N chunks 1-5ms apart; we collapse them by
* checking arrival time + that the previous sentinel is still at
* cursor-1 (no typing happened). 30ms is well below the ~100ms
* minimum a human can release+repress Ctrl+V, so deliberate
* back-to-back pastes never falsely merge.
*/
const PASTE_MERGE_WINDOW_MS = 30;
export interface PromptInputProps {
value: string;
onChange: (v: string) => void;
onSubmit: (v: string) => void;
disabled?: boolean;
placeholder?: string;
/**
* History recall. Fired when ↑/↓ hits a buffer boundary (empty
* buffer, or cursor already at the first/last line of a multi-line
* buffer). Parent walks its prompt history and swaps the value via
* `onChange`. Absent → keys are consumed silently.
*/
onHistoryPrev?: () => void;
onHistoryNext?: () => void;
}
/**
@@ -29,8 +68,40 @@ export function PromptInput({
onSubmit,
disabled,
placeholder,
onHistoryPrev,
onHistoryNext,
}: PromptInputProps) {
const [cursor, setCursor] = useState(value.length);
// Paste registry. Maps sentinel id → original paste content. Each
// entry is keyed by the codepoint stored in the buffer string.
// Lives in a ref because rendering doesn't depend on identity —
// mutating the map in-place is fine, the per-keystroke render
// reads the current state directly. `nextPasteIdRef` wraps modulo
// PASTE_SENTINEL_RANGE; collisions are rare in practice (256 slots,
// typical session has <10 pastes).
const pastesRef = useRef<Map<number, PasteEntry>>(new Map());
const nextPasteIdRef = useRef<number>(0);
// Bracketed-paste accumulator. When a paste begins, the terminal
// sends `\x1b[200~`; when it ends, `\x1b[201~`. We accumulate
// everything between markers into ONE entry. Works on terminals
// that pass markers through to Ink intact (iTerm, kitty, alacritty,
// most modern terminals on macOS/Linux). Doesn't work on Windows
// PowerShell+ConPTY where Ink's parse-keypress eats the markers
// before we see them — fallback below covers that case.
// null = not currently inside a paste; string = accumulating.
const pasteAccumRef = useRef<string | null>(null);
// Tight time-window merge fallback. When bracketed-paste markers
// don't reach us (Ink ate them, terminal didn't send them, etc.),
// a single user paste arrives as N stdin chunks 1-5ms apart, and
// each chunk on its own looks like a paste burst (multi-line
// content). Without merging the user gets four `[paste #N]`
// placeholders for one Ctrl+V. With a 30ms window + a guard that
// the previous sentinel is still right at cursor-1 (no typing
// happened in between), chunks of one paste collapse into one
// entry. The window is below human reaction time for double-
// pasting (Ctrl+V release → re-press takes 100ms+), so two
// deliberate pastes never falsely merge.
const lastPasteRef = useRef<{ id: number; at: number } | null>(null);
// Tracks the last `value` we ourselves produced via onChange. If the
// incoming `value` prop diverges from this, the parent (or some other
// source) replaced the buffer — we reset the cursor to end.
@@ -44,14 +115,110 @@ export function PromptInput({
setCursor(value.length);
}
}
// Synchronous mirror of `cursor` for the same reason. When two
// useInput firings happen in the same React tick (PowerShell+Ink
// emits useInput twice per stdin chunk), the second fire's
// closure still sees the stale `cursor` from before the first
// fire's setCursor took effect. Reading from a ref we update
// synchronously inside `registerPaste` lets the second fire's
// merge guard see the just-inserted sentinel at cursor-1.
const cursorRef = useRef(cursor);
cursorRef.current = cursor;
// Shared ticker drives the cursor blink. Dividing the tick by 4 lands
// the visible on/off cycle around 480ms — standard cursor cadence.
const tick = useTick();
const showCursor = disabled ? false : Math.floor(tick / 4) % 2 === 0;
// Helper: register an accumulated paste blob and insert its
// sentinel into the buffer at the current cursor. If the previous
// paste's sentinel is still at cursor-1 AND we're inside the
// sub-human-reaction merge window, append to that entry instead
// of creating a new sentinel — this collapses chunks of one
// user paste action that arrived as multiple stdin reads (the
// PowerShell+ConPTY+Ink case where bracketed-paste markers got
// eaten upstream).
const registerPaste = (content: string) => {
// Read from refs, NOT from closure variables. PowerShell+Ink
// fires useInput twice per stdin chunk; both fires close over
// the same stale `value` and `cursor` from React state. Refs
// get updated synchronously below, so the second fire sees the
// just-inserted sentinel at cursor-1 and the merge guard fires
// correctly. This was the core reason a single Ctrl+V kept
// producing four `[paste #N]` placeholders.
const v = lastLocalValueRef.current;
const c = cursorRef.current;
const now = Date.now();
const last = lastPasteRef.current;
const prevChar = c > 0 ? v[c - 1] : null;
const prevId = prevChar ? decodePasteSentinel(prevChar) : null;
const canMerge =
last !== null &&
prevId === last.id &&
now - last.at < PASTE_MERGE_WINDOW_MS &&
pastesRef.current.has(last.id);
if (canMerge && last) {
const existing = pastesRef.current.get(last.id);
if (existing) {
const merged = existing.content + content;
pastesRef.current.set(last.id, makePasteEntry(last.id, merged));
lastPasteRef.current = { id: last.id, at: now };
return;
}
}
const id = nextPasteIdRef.current % PASTE_SENTINEL_RANGE;
nextPasteIdRef.current = id + 1;
pastesRef.current.set(id, makePasteEntry(id, content));
const sentinel = encodePasteSentinel(id);
const next = v.slice(0, c) + sentinel + v.slice(c);
// Update refs synchronously so the SECOND useInput fire (same
// React tick) sees the new buffer + cursor. Then schedule the
// React state updates for re-render.
lastLocalValueRef.current = next;
cursorRef.current = c + 1;
onChange(next);
setCursor(c + 1);
lastPasteRef.current = { id, at: now };
};
useInput(
(input, key) => {
// Bracketed-paste accumulator. The terminal tells us EXACTLY
// when a paste begins / ends via `\x1b[200~` / `\x1b[201~`.
// Even when a 50KB paste arrives across many stdin reads,
// the markers bracket the entire paste once. We accumulate
// everything between them into a single sentinel — solving
// the "one user paste shows up as N adjacent placeholders"
// bug without resorting to time-based heuristics that would
// wrongly merge two quick deliberate pastes. On terminals
// that don't support DECSET 2004 (cmd.exe), markers never
// appear and we fall back to the per-chunk pasteRequest
// path below — chunks split visually but stay correct.
if (pasteAccumRef.current !== null) {
const endIdx = input.indexOf(PASTE_END_MARKER);
if (endIdx === -1) {
pasteAccumRef.current += input;
return;
}
const content = pasteAccumRef.current + input.slice(0, endIdx);
pasteAccumRef.current = null;
registerPaste(content);
return;
}
const startIdx = input.indexOf(PASTE_START_MARKER);
if (startIdx !== -1) {
const afterStart = input.slice(startIdx + PASTE_START_MARKER.length);
const endIdx = afterStart.indexOf(PASTE_END_MARKER);
if (endIdx !== -1) {
// Whole paste in one read — register and we're done.
registerPaste(afterStart.slice(0, endIdx));
} else {
// Open paste mode for subsequent useInput events.
pasteAccumRef.current = afterStart;
}
return;
}
const ke: MultilineKey = {
input,
return: key.return,
@@ -70,6 +237,15 @@ export function PromptInput({
pageDown: key.pageDown,
};
const action = processMultilineKey(value, cursor, ke);
if (action.pasteRequest) {
// No bracketed-paste markers were seen — terminal doesn't
// support DECSET 2004, or Ink's key parser ate them. Fall
// back to per-chunk paste registration. Two chunks of the
// same big paste land as two placeholders; correctness
// preserved, only visual cohesion lost.
registerPaste(action.pasteRequest.content);
return;
}
if (action.next !== null) {
lastLocalValueRef.current = action.next;
onChange(action.next);
@@ -77,7 +253,23 @@ export function PromptInput({
if (action.cursor !== null) {
setCursor(action.cursor);
}
if (action.submit) onSubmit(action.submitValue ?? value);
if (action.submit) {
// Expand sentinels back to real paste content before handing
// the prompt up to the parent. The buffer carries placeholders
// for display; the model needs the full text.
const raw = action.submitValue ?? value;
const expanded = expandPasteSentinels(raw, pastesRef.current);
// GC unreachable paste entries — anything whose sentinel was
// backspace'd out of the buffer before submit. Keeps the
// registry from growing unbounded across many turns.
const reachable = new Set(listPasteIdsInBuffer(raw));
for (const id of pastesRef.current.keys()) {
if (!reachable.has(id)) pastesRef.current.delete(id);
}
onSubmit(expanded);
}
if (action.historyHandoff === "prev") onHistoryPrev?.();
if (action.historyHandoff === "next") onHistoryNext?.();
},
{ isActive: !disabled },
);
@@ -89,16 +281,43 @@ export function PromptInput({
const lines = value.length > 0 ? value.split("\n") : [""];
const borderColor = disabled ? "gray" : "cyan";
const { line: cursorLine, col: cursorCol } = lineAndColumn(value, cursor);
// For large buffers (e.g. a big paste), rendering every line
// re-runs Ink's layout + terminal write on every keystroke. Each
// keystroke touching 500 rendered lines flickers visibly on most
// terminals. Collapse to HEAD + cursor-line + TAIL with a dim
// `[… N lines hidden …]` marker. Edit position is still anywhere;
// the visible cursor line follows the cursor into/out of the
// collapsed region so the user never loses sight of what they're
// typing. Submitted value is the FULL buffer — collapse is purely
// visual.
const renderItems = collapseLinesForDisplay(lines, cursorLine);
// When the buffer is large enough to be collapsed, surface a dim
// hint about the buffer-wide shortcuts. The user just pasted 500
// lines; without this they have no idea PageUp/Ctrl+U exist and
// ↑×500 is the only path back to the top.
const showHugeBufferHints = lines.length > 20;
return (
<Box borderStyle="round" borderColor={borderColor} paddingX={1} flexDirection="column">
{lines.map((line, i) => {
{renderItems.map((item, renderIdx) => {
if (item.kind === "skip") {
return (
// biome-ignore lint/suspicious/noArrayIndexKey: stable — skip markers are derived from a fixed-size window over `lines`
<Box key={`skip-${renderIdx}`}>
<Text dimColor>{" "}</Text>
<Text
dimColor
>{`[… ${item.linesHidden} line${item.linesHidden === 1 ? "" : "s"} hidden — full content kept, submitted on Enter …]`}</Text>
</Box>
);
}
const line = item.line;
const i = item.originalIndex;
const isFirst = i === 0;
const showPlaceholder = isFirst && value.length === 0;
const isCursorLine = i === cursorLine;
return (
// biome-ignore lint/suspicious/noArrayIndexKey: stable by construction — lines are derived from `value.split("\n")` and never reordered
<Box key={i}>
<Box key={`ln-${i}`}>
{isFirst ? (
<Text bold color={borderColor}>
you ›{" "}
@@ -119,27 +338,145 @@ export function PromptInput({
col={cursorCol}
showCursor={showCursor}
borderColor={borderColor}
pastes={pastesRef.current}
/>
) : (
<Text>{line}</Text>
<RenderLine line={line} pastes={pastesRef.current} />
)}
</Box>
);
})}
{showHugeBufferHints && !disabled ? (
<Box>
<Text dimColor>{" "}</Text>
<Text dimColor>
{`[${lines.length} lines · PageUp/PageDown jump to top/bottom · Ctrl+U clear · Ctrl+W del word]`}
</Text>
</Box>
) : null}
</Box>
);
}
/**
* One visual slot in the rendered prompt box. Either a real buffer
* line (with its original index so the cursor / first-line prefix
* still line up) or a "skip" marker summarizing hidden rows.
*/
type RenderItem =
| { kind: "line"; line: string; originalIndex: number }
| { kind: "skip"; linesHidden: number };
/**
* Above this line count we stop rendering every line on every
* keystroke — a 500-line paste would otherwise make Ink redraw
* hundreds of rows per character typed, which is visibly janky.
* Chosen empirically: under 20 lines the user is still visually
* scanning the buffer; above that they're almost always looking
* at a pasted blob that should be summarized.
*/
const COLLAPSE_THRESHOLD = 20;
const COLLAPSE_HEAD_LINES = 3;
const COLLAPSE_TAIL_LINES = 2;
export function collapseLinesForDisplay(lines: string[], cursorLine: number): RenderItem[] {
if (lines.length <= COLLAPSE_THRESHOLD) {
return lines.map((line, i) => ({ kind: "line" as const, line, originalIndex: i }));
}
// Always show the first HEAD lines, the last TAIL lines, and
// the cursor line if it falls in the collapsed middle. Union
// the indices so head/cursor/tail overlap collapses cleanly.
const keep = new Set<number>();
for (let i = 0; i < COLLAPSE_HEAD_LINES && i < lines.length; i++) keep.add(i);
for (let i = Math.max(0, lines.length - COLLAPSE_TAIL_LINES); i < lines.length; i++) keep.add(i);
if (cursorLine >= 0 && cursorLine < lines.length) keep.add(cursorLine);
const sorted = [...keep].sort((a, b) => a - b);
const out: RenderItem[] = [];
let prev = -1;
for (const idx of sorted) {
if (idx - prev > 1) {
out.push({ kind: "skip", linesHidden: idx - prev - 1 });
}
out.push({ kind: "line", line: lines[idx] ?? "", originalIndex: idx });
prev = idx;
}
return out;
}
/**
* Render a buffer line with paste sentinels expanded into magenta
* `[paste #N · …]` placeholder blocks. Used for non-cursor lines and
* for the prefix / suffix segments around the cursor on the cursor
* line.
*
* Each codepoint is emitted as either:
* - text: accumulated in `buf`, flushed when a sentinel or the end
* of the line is reached.
* - placeholder block: a styled `[paste #N · 3337l · 184KB]` Text.
*
* No layout magic — the emitted segments sit inline in the parent
* Box's row, just like plain text.
*/
function RenderLine({
line,
pastes,
inverse,
}: {
line: string;
pastes: ReadonlyMap<number, PasteEntry>;
inverse?: boolean;
}) {
const segments: React.ReactNode[] = [];
let buf = "";
let segIdx = 0;
const flushBuf = () => {
if (buf.length === 0) return;
segments.push(
<Text key={`t-${segIdx++}`} inverse={inverse}>
{buf}
</Text>,
);
buf = "";
};
for (let i = 0; i < line.length; i++) {
const ch = line[i]!;
const id = decodePasteSentinel(ch);
if (id === null) {
buf += ch;
continue;
}
flushBuf();
const entry = pastes.get(id);
const label = entry
? `[paste #${id + 1} · ${entry.lineCount}l · ${formatBytesShort(entry.charCount)}]`
: `[paste #${id + 1} · (missing)]`;
segments.push(
<Text key={`p-${segIdx++}`} color="magenta" bold inverse={inverse}>
{label}
</Text>,
);
}
flushBuf();
if (segments.length === 0) {
// Empty line — return a single empty Text so Ink still renders a
// row. Otherwise this Box collapses to zero height.
return <Text> </Text>;
}
return <>{segments}</>;
}
function LineWithCursor({
line,
col,
showCursor,
borderColor,
pastes,
}: {
line: string;
col: number;
showCursor: boolean;
borderColor: "cyan" | "gray";
pastes: ReadonlyMap<number, PasteEntry>;
}) {
const before = line.slice(0, col);
const atCursor = line.slice(col, col + 1);
@@ -149,16 +486,16 @@ function LineWithCursor({
// a trailing block so the user sees where they're typing next.
return (
<>
<Text>{before}</Text>
<RenderLine line={before} pastes={pastes} />
<Text color={borderColor}>{showCursor ? "▌" : " "}</Text>
</>
);
}
return (
<>
<Text>{before}</Text>
<Text inverse={showCursor}>{atCursor}</Text>
<Text>{after}</Text>
<RenderLine line={before} pastes={pastes} />
<RenderLine line={atCursor} pastes={pastes} inverse={showCursor} />
<RenderLine line={after} pastes={pastes} />
</>
);
}
+1
View File
@@ -59,6 +59,7 @@ export function ReplayApp({ meta, pages }: ReplayAppProps) {
cacheHitRatio: cumStats.cacheHitRatio,
// Replay is read-only — no live last-turn prompt tokens to show.
lastPromptTokens: 0,
lastTurnCostUsd: 0,
};
const prefixHash =
+19 -2
View File
@@ -11,6 +11,13 @@ export interface ShellConfirmProps {
* "always allow". Typically the first 1-2 tokens of `command`.
*/
allowPrefix: string;
/**
* Which tool is asking. `run_background` spawns via JobRegistry and
* returns early; `run_command` (default) blocks until the process
* exits. Shown as a hint in the modal so the user knows whether
* approving will block the TUI or not.
*/
kind?: "run_command" | "run_background";
onChoose: (choice: ShellConfirmChoice) => void;
}
@@ -25,14 +32,24 @@ export interface ShellConfirmProps {
* Arrow keys + Enter. No y/n hotkey — too easy to trigger by accident
* when the user was mid-typing a response.
*/
export function ShellConfirm({ command, allowPrefix, onChoose }: ShellConfirmProps) {
export function ShellConfirm({ command, allowPrefix, kind, onChoose }: ShellConfirmProps) {
const isBackground = kind === "run_background";
return (
<Box flexDirection="column" borderStyle="round" borderColor="yellow" paddingX={1} marginY={1}>
<Box>
<Text bold color="yellow">
▸ model wants to run a shell command
{isBackground
? "▸ model wants to start a BACKGROUND process"
: "▸ model wants to run a shell command"}
</Text>
</Box>
{isBackground ? (
<Box>
<Text dimColor>
{" (long-running: dev server / watcher; keeps running after approval, /kill to stop)"}
</Text>
</Box>
) : null}
<Box>
<Text color="yellow" dimColor>
{"──────────────────────────────────────────"}
+82 -9
View File
@@ -1,5 +1,6 @@
import { Box, Text, useStdout } from "ink";
import React from "react";
import type { EditMode } from "../../config.js";
import { DEEPSEEK_CONTEXT_TOKENS, DEFAULT_CONTEXT_TOKENS } from "../../telemetry.js";
import type { SessionSummary } from "../../telemetry.js";
import { VERSION } from "../../version.js";
@@ -70,6 +71,12 @@ export interface StatsPanelProps {
* approval.
*/
planMode?: boolean;
/**
* Edit-gate mode. Surfaced as a small pill in the header so the user
* can see at a glance whether edits will be queued for review or
* applied immediately. Omitted in chat (non-code) mode.
*/
editMode?: EditMode;
/**
* Account balance fetched once at launch (and optionally refreshed
* per-turn by the TUI). `null` or absent hides the balance cell
@@ -92,6 +99,19 @@ export interface StatsPanelProps {
* visible at a glance from anywhere on screen.
*/
busy?: boolean;
/**
* /pro is queued — the next turn will run on v4-pro regardless of
* `model`. Rendered as a yellow `⇧ pro armed` pill in the header so
* the user has a clear "this turn will be expensive" signal before
* submitting their message.
*/
proArmed?: boolean;
/**
* The CURRENT turn is running on v4-pro because the failure-
* escalation threshold fired mid-turn. Rendered as a red `⇧ pro
* escalated` pill. Clears at turn end.
*/
escalated?: boolean;
}
/**
@@ -119,9 +139,12 @@ export function StatsPanel({
branchBudget,
reasoningEffort,
planMode,
editMode,
balance,
updateAvailable,
busy,
proArmed,
escalated,
}: StatsPanelProps) {
const branchOn = (branchBudget ?? 1) > 1;
const ctxMax = DEEPSEEK_CONTEXT_TOKENS[model] ?? DEFAULT_CONTEXT_TOKENS;
@@ -136,7 +159,16 @@ export function StatsPanel({
const coldStart = summary.turns <= COLD_START_TURNS;
return (
<Box borderStyle="round" borderColor="cyan" flexDirection="column" paddingX={1}>
// Explicit `width={columns}` pins the border frame to the exact
// terminal width. Without this, Ink auto-flexes the Box to
// container width, and on terminal resize the prior frame's
// wrapped-overflow can leave tails in the scrollback (each
// redraw stacks a slightly-wider-or-narrower frame). Fixing
// width per-render doesn't eliminate the underlying Ink
// limitation (eraseLines counts logical rows, not post-wrap
// display rows) but makes each frame's dimensions exact so
// there's no residual uncertainty in the erase.
<Box borderStyle="round" borderColor="cyan" flexDirection="column" paddingX={1} width={columns}>
<Header
model={model}
prefixHash={prefixHash}
@@ -145,10 +177,13 @@ export function StatsPanel({
branchBudget={branchBudget ?? 1}
reasoningEffort={reasoningEffort}
planMode={planMode}
editMode={editMode}
turns={summary.turns}
updateAvailable={updateAvailable}
narrow={narrow}
busy={busy ?? false}
proArmed={proArmed ?? false}
escalated={escalated ?? false}
/>
{narrow ? (
<StackedMetrics
@@ -179,10 +214,13 @@ function Header({
branchBudget,
reasoningEffort,
planMode,
editMode,
turns,
updateAvailable,
narrow,
busy,
proArmed,
escalated,
}: {
model: string;
prefixHash: string;
@@ -191,10 +229,13 @@ function Header({
branchBudget: number;
reasoningEffort?: "high" | "max";
planMode?: boolean;
editMode?: EditMode;
turns: number;
updateAvailable?: string | null;
narrow: boolean;
busy: boolean;
proArmed: boolean;
escalated: boolean;
}) {
return (
<Box justifyContent="space-between">
@@ -218,6 +259,20 @@ function Header({
{" · PLAN"}
</Text>
) : null}
{editMode ? (
<Text color={editMode === "auto" ? "magenta" : "cyan"} bold>
{editMode === "auto" ? " · AUTO" : " · review"}
</Text>
) : null}
{escalated ? (
<Text color="red" bold>
{" · ⇧ pro escalated"}
</Text>
) : proArmed ? (
<Text color="yellow" bold>
{" · ⇧ pro armed"}
</Text>
) : null}
</Box>
<Text>
{updateAvailable ? (
@@ -370,6 +425,24 @@ function CacheCell({
);
}
/**
* Color thresholds. Per-turn and session cumulative scale roughly 10×
* apart — a $0.20 single turn should feel just as warn-worthy as a $2
* session total. Values are rough "notice this" points, not hard caps.
*/
function turnCostColor(cost: number): "green" | "yellow" | "red" | undefined {
if (cost <= 0) return undefined;
if (cost >= 0.2) return "red";
if (cost >= 0.05) return "yellow";
return "green";
}
function sessionCostColor(cost: number): "green" | "yellow" | "red" | undefined {
if (cost <= 0) return undefined;
if (cost >= 5) return "red";
if (cost >= 0.5) return "yellow";
return "green";
}
function CostCell({
summary,
coldStart,
@@ -389,17 +462,17 @@ function CostCell({
// so the dollar figure is front-loaded. Muting it during the
// cold-start window keeps the "expensive first turn" from
// reading as "something is wrong."
const primaryColor = coldStart ? undefined : "green";
const turnColor = coldStart ? undefined : turnCostColor(summary.lastTurnCostUsd);
const sessionColor = coldStart ? undefined : sessionCostColor(summary.totalCostUsd);
return (
<Text>
<Text dimColor>cost </Text>
<Text color={primaryColor} bold={!coldStart} dimColor={coldStart}>
${summary.totalCostUsd.toFixed(6)}
<Text dimColor>turn </Text>
<Text color={turnColor} bold={!coldStart} dimColor={coldStart}>
${summary.lastTurnCostUsd.toFixed(4)}
</Text>
<Text dimColor>
{" (in "}${summary.totalInputCostUsd.toFixed(6)}
{" · out "}${summary.totalOutputCostUsd.toFixed(6)}
{")"}
<Text dimColor>{" · session "}</Text>
<Text color={sessionColor} bold={!coldStart} dimColor={coldStart}>
${summary.totalCostUsd.toFixed(4)}
</Text>
</Text>
);
+109
View File
@@ -0,0 +1,109 @@
import { formatAllBlockDiffs } from "../../code/diff-preview.js";
import type { ApplyResult, EditBlock, EditSnapshot } from "../../code/edit-blocks.js";
/**
* One batch of edits that actually landed on disk — durable enough for
* `/undo`, `/history`, and `/show` within a session. Not persisted
* across restarts: restoring pre-apply content from a process that
* crashed last week is git's job, not ours.
*/
export interface EditHistoryEntry {
/** Sequence number within the session, stable for `/show <id>`. */
id: number;
/** Epoch ms when the entry was opened (first edit landed). */
at: number;
/**
* Short tag for what produced the batch — "auto" (auto-mode tool
* call), "auto-text" (auto-mode text SEARCH/REPLACE at turn end),
* "review-apply" (user-approved modal edit or /apply flush).
*/
source: string;
/** Edit blocks included in this batch, in arrival order. */
blocks: EditBlock[];
/** Per-block outcome — some may be "not-found" if SEARCH drifted. */
results: ApplyResult[];
/**
* First-snapshot-per-path wins: this is what `/undo` restores to.
* Deduped so multi-edit turns still roll back to pre-turn state.
*/
snapshots: EditSnapshot[];
/**
* Paths within this entry that have already been reverted (via
* `/undo <id>`, `/undo <id> <path>`, or the newest-non-undone /undo
* shortcut). Per-path instead of entry-level so a batch can be
* partially undone — user reverts src/foo.ts out of a 3-file batch
* without rolling back the other two.
*/
undoneFiles: Set<string>;
}
/** True when every path in the entry has been undone. */
export function isEntryFullyUndone(e: EditHistoryEntry): boolean {
return e.snapshots.length > 0 && e.snapshots.every((s) => e.undoneFiles.has(s.path));
}
/** Per-entry three-state status label for display. */
export function entryStatus(e: EditHistoryEntry): "applied" | "UNDONE" | "PARTIAL" {
if (e.undoneFiles.size === 0) return "applied";
if (isEntryFullyUndone(e)) return "UNDONE";
return "PARTIAL";
}
/**
* Render a batch of SEARCH/REPLACE application results as one
* human-scannable info line per edit. Prefixes denote status so the
* line reads well even without color (e.g. when piped to a log file
* or stripped for screenshots):
* ✓ applied src/foo.ts
* ✓ created src/new.ts
* ✗ not-found src/bar.ts (SEARCH text does not match…)
*/
export function formatEditResults(results: ApplyResult[]): string {
const lines = results.map((r) => {
const mark = r.status === "applied" || r.status === "created" ? "✓" : "✗";
const detail = r.message ? ` (${r.message})` : "";
return ` ${mark} ${r.status.padEnd(11)} ${r.path}${detail}`;
});
const ok = results.filter((r) => r.status === "applied" || r.status === "created").length;
const total = results.length;
const header = `▸ edit blocks: ${ok}/${total} applied — /undo to roll back, or \`git diff\` to review`;
return [header, ...lines].join("\n");
}
/**
* Pending-edits preview shown after each assistant turn that proposed
* changes. Per-block path header + ±line-count, then a unified-diff-
* style preview (context trimmed to 2 lines each side, total capped
* at 20 lines per block). Users can eyeball what's about to land
* BEFORE pressing `y` — the old summary-only view was a common
* mistake surface.
*/
export function formatPendingPreview(blocks: EditBlock[]): string {
const header = `▸ ${blocks.length} pending edit block(s) — /apply (or y) to commit · /discard (or n) to drop`;
const diffLines = formatAllBlockDiffs(blocks);
return [header, ...diffLines].join("\n");
}
/**
* Per-file rows for the multi-level `/undo` output, without the
* single-batch header (the caller prepends its own).
*/
export function formatUndoRows(results: ApplyResult[]): string[] {
return results.map((r) => {
const mark = r.status === "applied" ? "✓" : "✗";
const detail = r.message ? ` (${r.message})` : "";
return ` ${mark} ${r.path}${detail}`;
});
}
export function describeRepair(repair: {
scavenged: number;
truncationsFixed: number;
stormsBroken: number;
}): string {
const parts: string[] = [];
if (repair.scavenged) parts.push(`scavenged ${repair.scavenged}`);
if (repair.truncationsFixed) parts.push(`repaired ${repair.truncationsFixed} truncation`);
if (repair.stormsBroken) parts.push(`broke ${repair.stormsBroken} storm`);
return parts.length ? `[repair] ${parts.join(", ")}` : "";
}
+549 -49
View File
@@ -4,10 +4,13 @@
* Handles the subset that actually shows up in LLM answers:
* - ATX headers (# ##)
* - Unordered / ordered lists
* - Fenced code blocks (```lang)
* - Inline **bold**, *italic*, `code`
* - Task lists (- [ ] / - [x])
* - Blockquotes (> …) — rendered with a left bar; nested / list-in-quote OK
* - Fenced code blocks (```lang) — diagram langs get a distinct frame
* - Inline **bold**, *italic*, `code`, ~~strikethrough~~
* - GFM emoji shortcodes (:smile: :heart: :+1: …) — curated set
* - Paragraphs separated by blank lines
* - LaTeX delimiters are stripped (\( \), \[ \], \boxed{X})
* - LaTeX delimiters stripped (\( \), \[ \], \boxed{X}); $…$ / $$…$$ too
*
* The goal is not TeX-perfect math — it's "stop showing raw backslashes to
* the user." When the model insists on LaTeX, we strip the scaffolding and
@@ -63,7 +66,22 @@ function toSubscript(s: string): string {
export function stripMath(s: string): string {
return (
s
// Delimiters
// Dollar-delimited math (KaTeX / MathJax convention). Block
// `$$…$$` is unambiguous — strip the delimiters, wrap content
// in double newlines so parseBlocks surfaces it as its own
// paragraph instead of folding it into adjacent prose. Must
// run BEFORE inline `$…$` so the block regex gets first crack.
.replace(/\$\$([\s\S]+?)\$\$/g, (_m, c: string) => `\n\n${c.trim()}\n\n`)
// Inline `$…$` is only stripped when a non-space char sits
// immediately inside EACH dollar. That rules out:
// - prices: `$5 per unit` (no closing $)
// - `$5 and $10` (content ends/starts with space)
// - `echo $HOME` (no closing $)
// - `$ prompt` (space after open $)
// The lookbehind/lookahead on `$` also keeps us from eating
// half of a `$$…$$` pair that the block regex somehow missed.
.replace(/(?<!\$)\$(?!\s)([^$\n]+?)(?<!\s)\$(?!\$)/g, "$1")
// LaTeX delimiters
.replace(/\\\(\s*/g, "")
.replace(/\s*\\\)/g, "")
.replace(/\\\[\s*/g, "\n")
@@ -95,12 +113,19 @@ export function stripMath(s: string): string {
.replace(/\\geq/g, "≥")
.replace(/\\neq/g, "≠")
.replace(/\\approx/g, "≈")
.replace(/\\in\b/g, "∈")
.replace(/\\notin\b/g, "∉")
// Use `(?![a-zA-Z])` instead of `\b` because LaTeX commands
// often abut subscript/superscript markers: `\sum_{i=1}^n`,
// `\int_0^1`, etc. `\b` only fires between a word char and a
// non-word char, but `_` IS a word char, so `\b` silently
// refuses to match. The catch-all `\\[a-zA-Z]+` at the bottom
// would then eat `\sum` to empty — losing the Σ entirely.
// Lookahead-for-non-letter is the right fence: end of command.
.replace(/\\in(?![a-zA-Z])/g, "∈")
.replace(/\\notin(?![a-zA-Z])/g, "∉")
.replace(/\\infty/g, "∞")
.replace(/\\sum\b/g, "Σ")
.replace(/\\prod\b/g, "Π")
.replace(/\\int\b/g, "∫")
.replace(/\\sum(?![a-zA-Z])/g, "Σ")
.replace(/\\prod(?![a-zA-Z])/g, "Π")
.replace(/\\int(?![a-zA-Z])/g, "∫")
// Greek letters
.replace(/\\alpha/g, "α")
.replace(/\\beta/g, "β")
@@ -114,9 +139,9 @@ export function stripMath(s: string): string {
.replace(/\\phi/g, "φ")
.replace(/\\omega/g, "ω")
// Arrows / logic
.replace(/\\implies\b/g, "⇒")
.replace(/\\iff\b/g, "⇔")
.replace(/\\to\b/g, "→")
.replace(/\\implies(?![a-zA-Z])/g, "⇒")
.replace(/\\iff(?![a-zA-Z])/g, "⇔")
.replace(/\\to(?![a-zA-Z])/g, "→")
.replace(/\\rightarrow/g, "→")
.replace(/\\Rightarrow/g, "⇒")
.replace(/\\leftarrow/g, "←")
@@ -130,7 +155,27 @@ export function stripMath(s: string): string {
.replace(/\\;/g, " ")
.replace(/\\!/g, "")
.replace(/\\\\/g, "\n")
// Superscripts / subscripts — single token or {braced group of [\w+-]}
// Pandoc-style inline super/subscripts — `x^2^` for superscript,
// `H~2~O` for subscript. Handled HERE (not in INLINE_RE) because
// the only useful rendering for a terminal is Unicode
// super/subscript characters, which live in the same transform
// pipeline as the LaTeX ^/_ rules below.
//
// Policy: only convert when EVERY character inside the markers
// maps to a Unicode super/subscript glyph. `^2^` → `²` (good),
// but `^foo^` can't be truly superscripted, so we leave the
// whole thing literal rather than dropping the markers and
// losing the model's intent. Guards on `~` use lookaround so
// the subscript rule never fires inside a `~~strikethrough~~`.
.replace(/\^([A-Za-z0-9+\-]+)\^/g, (m, g: string) => {
for (const c of g) if (SUPERSCRIPT[c] === undefined) return m;
return toSuperscript(g);
})
.replace(/(?<!~)~(?!~)([A-Za-z0-9+\-]+)~(?!~)/g, (m, g: string) => {
for (const c of g) if (SUBSCRIPT[c] === undefined) return m;
return toSubscript(g);
})
// LaTeX super/subscripts — single token or {braced group of [\w+-]}
.replace(/\^\{([\w+-]+)\}/g, (_m, g: string) => toSuperscript(g))
.replace(/\^([0-9+\-n])/g, (_m, g: string) => toSuperscript(g))
.replace(/_\{([\w+-]+)\}/g, (_m, g: string) => toSubscript(g))
@@ -146,6 +191,154 @@ export function stripMath(s: string): string {
);
}
/**
* GFM emoji shortcode table. Curated ~70 entries covering what LLMs
* actually emit in chat — faces, hearts, gestures, common signals
* (✅ ❌ ⚠️), tech / productivity glyphs, a handful of weather and
* objects. We deliberately skip flags (region codes, rarely used)
* and the long tail.
*
* Unknown shortcodes pass through as literal `:name:` — safer than
* guessing, and prevents false positives like `file.ts:10:` or a
* `:classname:` in code from turning into garbage.
*/
const EMOJI_MAP: Record<string, string> = {
// faces
smile: "😄",
smiley: "😃",
grin: "😁",
grinning: "😀",
joy: "😂",
laughing: "😆",
heart_eyes: "😍",
blush: "😊",
sunglasses: "😎",
thinking: "🤔",
neutral_face: "😐",
confused: "😕",
cry: "😢",
sob: "😭",
rage: "😡",
angry: "😠",
scream: "😱",
wink: "😉",
kissing_heart: "😘",
// hearts
heart: "❤️",
orange_heart: "🧡",
yellow_heart: "💛",
green_heart: "💚",
blue_heart: "💙",
purple_heart: "💜",
black_heart: "🖤",
white_heart: "🤍",
broken_heart: "💔",
sparkling_heart: "💖",
two_hearts: "💕",
// gestures
"+1": "👍",
"-1": "👎",
thumbsup: "👍",
thumbsdown: "👎",
wave: "👋",
clap: "👏",
muscle: "💪",
ok_hand: "👌",
pray: "🙏",
fist: "✊",
point_up: "☝️",
raised_hands: "🙌",
handshake: "🤝",
// symbols / signals
rocket: "🚀",
fire: "🔥",
star: "⭐",
star2: "🌟",
sparkles: "✨",
boom: "💥",
zap: "⚡",
tada: "🎉",
bulb: "💡",
warning: "⚠️",
x: "❌",
white_check_mark: "✅",
heavy_check_mark: "✔️",
ballot_box_with_check: "☑️",
no_entry: "⛔",
question: "❓",
exclamation: "❗",
bangbang: "‼️",
bell: "🔔",
mute: "🔕",
hundred: "💯",
"100": "💯",
eyes: "👀",
// tech / productivity
computer: "💻",
iphone: "📱",
hammer: "🔨",
wrench: "🔧",
gear: "⚙️",
package: "📦",
floppy_disk: "💾",
key: "🔑",
lock: "🔒",
unlock: "🔓",
mag: "🔍",
memo: "📝",
pencil: "✏️",
bookmark: "🔖",
// charts / time
chart_with_upwards_trend: "📈",
chart_with_downwards_trend: "📉",
bar_chart: "📊",
hourglass: "⏳",
calendar: "📅",
// misc
robot: "🤖",
ghost: "👻",
bug: "🐛",
coffee: "☕",
beer: "🍺",
sun: "☀️",
cloud: "☁️",
rainbow: "🌈",
speech_balloon: "💬",
thought_balloon: "💭",
construction: "🚧",
};
/**
* GFM autolinks — bare `<url>` / `<email>` shorthand. Rewrite to the
* full `[url](url)` form so the existing link-rendering path applies
* (blue + underline for external, URL validated for local). Only
* unambiguous URL schemes are expanded: http(s) / ftp / mailto.
* Anything else stays as literal `<foo>` text — some prose has
* angle-bracketed phrases that aren't URLs.
*/
export function expandAutolinks(s: string): string {
return s.replace(/<((?:https?|ftp|mailto):[^\s<>]+)>/g, "[$1]($1)");
}
/**
* Expand `:name:` GFM emoji shortcodes via {@link EMOJI_MAP}. The
* regex matches broadly (letters / digits / `+` / `_` / `-`) so
* `:+1:` works, but the ultimate gate is the map lookup — unknown
* names stay literal. That's what keeps `file.ts:10:` and
* `:classname:` from being mangled.
*/
export function expandEmoji(s: string): string {
// Character class covers the whole GFM shortcode alphabet
// (letters, digits, `_`, `+`, `-`). The leading `-` slot is
// needed so `:-1:` resolves; putting it at the end of the class
// keeps it literal. The map lookup is the true gate — unknown
// names pass through untouched, so false-positive regex matches
// in prose / code don't corrupt the text.
return s.replace(/:([a-z0-9_+-]+):/gi, (m, name: string) => {
return EMOJI_MAP[name.toLowerCase()] ?? m;
});
}
/**
* Citation links: `[text](url)` where url either points outside the repo
* (rendered as a plain external link) or resolves to a file/line in the
@@ -229,11 +422,36 @@ export function validateCitation(url: string, projectRoot: string): CitationStat
return { ok: true };
}
/**
* Heuristic: should this link URL be treated as a repo-file citation
* (and thus validated / marked red-strikethrough if missing)? The
* point is to STOP flagging things that obviously aren't paths —
* otherwise users see a red "broken citations" box for content the
* model wrote legitimately:
* - `#anchor` — in-page anchor jump (not a file ref)
* - `url` / `path` — placeholder words in demo text
* - `/` — bare root
* Rule: must contain a path separator, a dot, OR a `#` with a non-
* bare-anchor prefix. Those are the shapes real file references use.
*/
export function shouldValidateAsCitation(url: string): boolean {
// Anchor-only: `#foo` / `#` — page-local, not a file
if (url.startsWith("#")) return false;
// Bare root placeholders
if (url === "/" || url === "\\" || url === "") return false;
// Must look like a path: contains `/`, `\`, or `.` somewhere
if (!/[/\\.]/.test(url)) return false;
return true;
}
/**
* Pre-scan rendered text for every `[text](url)` link, validate the
* citation-shaped ones, and cache the result. Done once per Markdown
* mount so InlineMd doesn't re-stat the filesystem on every keystroke
* during streaming. External links short-circuit (no fs work).
* during streaming. External links short-circuit (no fs work);
* non-citation-shaped URLs are skipped entirely (left as default
* cyan-underline link rendering) so placeholders in demo prose don't
* clutter the broken-citation summary with false positives.
*/
export function collectCitations(text: string, projectRoot: string): CitationMap {
const map: CitationMap = new Map();
@@ -241,6 +459,7 @@ export function collectCitations(text: string, projectRoot: string): CitationMap
for (const m of text.matchAll(re)) {
const url = m[2] ?? "";
if (!url || isExternalUrl(url)) continue;
if (!shouldValidateAsCitation(url)) continue;
if (map.has(url)) continue;
map.set(url, validateCitation(url, projectRoot));
}
@@ -264,7 +483,7 @@ export function collectCitations(text: string, projectRoot: string): CitationMap
* `parseBlocks`.
*/
const INLINE_RE =
/(\[([^\]\n]+)\]\(([^)\n]+)\)|\*\*([^*\n]+?)\*\*|```([^\n]+?)```|`([^`\n]+?)`|(?<![*\w])\*([^*\n]+?)\*(?!\w))/g;
/(\[([^\]\n]+)\]\(([^)\n]+)\)|\*\*\*([^*\n]+?)\*\*\*|\*\*([^*\n]+?)\*\*|```([^\n]+?)```|`([^`\n]+?)`|~~([^~\n]+?)~~|(?<![*\w])\*([^*\n]+?)\*(?!\w)|\\([*_~`[\](){}#+\-.!\\]))/g;
function InlineMd({
text,
@@ -285,10 +504,13 @@ function InlineMd({
}
// Groups, in the order they appear in INLINE_RE:
// m[2] = link text m[3] = link url
// m[4] = bold content (inside ** **)
// m[5] = triple-backtick content (strip leading lang tag)
// m[6] = single-backtick inline code
// m[7] = italic content (inside * *)
// m[4] = bold-italic content (inside *** ***)
// m[5] = bold content (inside ** **)
// m[6] = triple-backtick content (strip leading lang tag)
// m[7] = single-backtick inline code
// m[8] = strikethrough content (inside ~~ ~~)
// m[9] = italic content (inside * *)
// m[10] = backslash-escaped char (emit as literal)
if (m[2] !== undefined && m[3] !== undefined) {
const linkText = m[2];
const url = m[3];
@@ -316,31 +538,49 @@ function InlineMd({
}
} else if (m[4] !== undefined) {
parts.push(
<Text key={`b${idx++}`} bold>
<Text key={`bi${idx++}`} bold italic>
{m[4]}
</Text>,
);
} else if (m[5] !== undefined) {
parts.push(
<Text key={`b${idx++}`} bold>
{m[5]}
</Text>,
);
} else if (m[6] !== undefined) {
// One-line fenced span: ```bash echo hi``` → drop the "bash "
// language tag so the user doesn't see it rendered in code color.
const stripped = m[5].replace(/^(\w+)\s+/, "");
const stripped = m[6].replace(/^(\w+)\s+/, "");
parts.push(
<Text key={`c${idx++}`} color="yellow">
{stripped}
</Text>,
);
} else if (m[6] !== undefined) {
parts.push(
<Text key={`c${idx++}`} color="yellow">
{m[6]}
</Text>,
);
} else if (m[7] !== undefined) {
parts.push(
<Text key={`i${idx++}`} italic>
<Text key={`c${idx++}`} color="yellow">
{m[7]}
</Text>,
);
} else if (m[8] !== undefined) {
parts.push(
<Text key={`s${idx++}`} strikethrough dimColor>
{m[8]}
</Text>,
);
} else if (m[9] !== undefined) {
parts.push(
<Text key={`i${idx++}`} italic>
{m[9]}
</Text>,
);
} else if (m[10] !== undefined) {
// Backslash escape — emit the escaped char as a plain Text node
// so the subsequent pass of the regex engine doesn't re-interpret
// the `*` / `` ` `` / `~` as markup. The `\` is dropped; only the
// escaped char survives.
parts.push(<Text key={`esc${idx++}`}>{m[10]}</Text>);
}
last = start + m[0].length;
}
@@ -367,12 +607,37 @@ function InlineMd({
* length includes invisible markup chars.
*/
export function stripInlineMarkup(s: string): string {
return s
.replace(/\[([^\]\n]+)\]\(([^)\n]+)\)/g, "$1")
.replace(/\*\*([^*\n]+?)\*\*/g, "$1")
.replace(/```([^\n]+?)```/g, (_m, c: string) => c.replace(/^(\w+)\s+/, ""))
.replace(/`([^`\n]+?)`/g, "$1")
.replace(/(?<![*\w])\*([^*\n]+?)\*(?!\w)/g, "$1");
// Single-pass strip using INLINE_RE so alternation precedence exactly
// matches the runtime renderer. The prior implementation chained
// sequential .replace() calls, which broke backslash escapes — the
// inline-code regex would eat `\`code\`` as a `code\`` span before
// the escape pass got a chance to neutralize each `\``.
return s.replace(
INLINE_RE,
(
match: string,
_alt: string,
linkText: string | undefined,
_url: string | undefined,
boldItalic: string | undefined,
bold: string | undefined,
code3: string | undefined,
code1: string | undefined,
strike: string | undefined,
italic: string | undefined,
escapeChar: string | undefined,
) => {
if (linkText !== undefined) return linkText;
if (boldItalic !== undefined) return boldItalic;
if (bold !== undefined) return bold;
if (code3 !== undefined) return code3.replace(/^(\w+)\s+/, "");
if (code1 !== undefined) return code1;
if (strike !== undefined) return strike;
if (italic !== undefined) return italic;
if (escapeChar !== undefined) return escapeChar;
return match;
},
);
}
/**
@@ -392,12 +657,35 @@ interface HeadingBlock {
level: number;
text: string;
}
/**
* One bullet-list item. `task` marks GFM task-list entries:
* - `- [ ] do the thing` → `{ text: "do the thing", task: "todo" }`
* - `- [x] shipped` → `{ text: "shipped", task: "done" }`
* Regular bullets leave `task` undefined.
*/
export interface BulletItem {
text: string;
task?: "done" | "todo";
}
interface BulletBlock {
kind: "bullet";
items: string[];
items: BulletItem[];
ordered: boolean;
start: number;
}
interface BlockquoteBlock {
kind: "quote";
/**
* Parsed child blocks. After stripping one `>` prefix from each
* gathered line, the remainder is re-fed through `parseBlocks` so
* block-level constructs inside the quote (nested `>>` quotes,
* lists, code fences, tables, …) render with their normal
* formatting instead of as flattened text. Nesting depth is
* whatever the markdown source expresses — the recursion closes
* naturally when no line starts with `>` at its current level.
*/
children: Block[];
}
interface CodeBlock {
kind: "code";
lang: string;
@@ -436,6 +724,7 @@ type Block =
| ParagraphBlock
| HeadingBlock
| BulletBlock
| BlockquoteBlock
| CodeBlock
| HrBlock
| EditBlockView
@@ -444,7 +733,12 @@ type Block =
export function parseBlocks(raw: string): Block[] {
const lines = raw.split(/\r?\n/);
const out: Block[] = [];
let para: string[] = [];
// Each entry is one source line inside the current paragraph plus
// the hard-break flag that applies AFTER it. Hard break = trailing
// ` ` (two+ spaces before newline) per GFM. The flag decides
// whether this line's content joins to the next with `\n` (hard,
// preserves visual newline) or ` ` (soft, default paragraph reflow).
let para: Array<{ text: string; hardBreak: boolean }> = [];
let inCode = false;
let codeLang = "";
let codeBuf: string[] = [];
@@ -456,10 +750,16 @@ export function parseBlocks(raw: string): Block[] {
let codeFence = "";
const flushPara = () => {
if (para.length) {
out.push({ kind: "paragraph", text: para.join(" ") });
para = [];
if (para.length === 0) return;
let joined = "";
for (let k = 0; k < para.length; k++) {
joined += para[k]!.text;
if (k < para.length - 1) {
joined += para[k]!.hardBreak ? "\n" : " ";
}
}
out.push({ kind: "paragraph", text: joined });
para = [];
};
const flushList = () => {
if (listBuf) {
@@ -480,7 +780,7 @@ export function parseBlocks(raw: string): Block[] {
if (!inCode && /^<{7} SEARCH\s*$/.test(line)) {
// Filename is the previous non-blank line we just pushed to para.
// Pull it back out; if there isn't one, treat as literal text.
const filename = para.pop()?.trim();
const filename = para.pop()?.text.trim();
if (filename) {
flushPara();
flushList();
@@ -508,7 +808,7 @@ export function parseBlocks(raw: string): Block[] {
}
// Malformed — no separator or no close. Fall through: put
// the filename back in the paragraph so we don't lose it.
para.push(filename);
para.push({ text: filename, hardBreak: false });
}
}
@@ -664,6 +964,38 @@ export function parseBlocks(raw: string): Block[] {
}
}
// Blockquote: consecutive `>` lines gather into one quote block.
// We strip exactly one level of `>` prefix, then recursively run
// the inner text through `parseBlocks`. That gets us:
// - Nested `>>` rendering as a quote-in-a-quote (inner `>` is
// still present after the outer strip, so the recursion fires).
// - Lists, code fences, tables inside a quote — all keep their
// normal formatting because parseBlocks handles them again.
// - Blank-`>` lines become paragraph breaks inside the quote.
//
// We don't implement GFM "lazy continuation" (a line without `>`
// after a non-empty quote line is still part of the quote) — LLMs
// reliably re-emit `>` on each line, and enforcing the explicit
// prefix avoids accidentally swallowing the paragraph that
// follows a quote.
const quoteMatch = line.match(/^\s*>\s?(.*)$/);
if (quoteMatch) {
flushPara();
flushList();
const innerLines: string[] = [quoteMatch[1] ?? ""];
let j = i + 1;
while (j < lines.length) {
const nxt = lines[j]!.replace(/\s+$/g, "");
const m = nxt.match(/^\s*>\s?(.*)$/);
if (!m) break;
innerLines.push(m[1] ?? "");
j++;
}
out.push({ kind: "quote", children: parseBlocks(innerLines.join("\n")) });
i = j - 1;
continue;
}
const bm = line.match(/^\s*[-*+]\s+(.+)$/);
if (bm) {
flushPara();
@@ -671,7 +1003,7 @@ export function parseBlocks(raw: string): Block[] {
flushList();
listBuf = { kind: "bullet", items: [], ordered: false, start: 1 };
}
listBuf.items.push(bm[1]!);
listBuf.items.push(parseBulletItem(bm[1]!));
continue;
}
@@ -682,12 +1014,18 @@ export function parseBlocks(raw: string): Block[] {
flushList();
listBuf = { kind: "bullet", items: [], ordered: true, start: Number(om[1]) };
}
listBuf.items.push(om[2]!);
listBuf.items.push(parseBulletItem(om[2]!));
continue;
}
flushList();
para.push(line);
// Hard line break: trailing ` ` (two or more spaces) on the raw
// line before whitespace was stripped. Per GFM, this forces a
// visible newline inside a paragraph (where soft-wrapped lines
// normally join with a space). We stash the flag on THIS line
// so flushPara knows whether to emit `\n` or ` ` AFTER it.
const hardBreak = / {2,}\r?$/.test(rawLine);
para.push({ text: line, hardBreak });
}
if (inCode && codeBuf.length) {
@@ -698,6 +1036,20 @@ export function parseBlocks(raw: string): Block[] {
return out;
}
/**
* GFM task-list prefix sniff: `[ ] …` / `[x] …` / `[X] …` at the start
* of a bullet item's text becomes a task entry; anything else stays a
* plain item. The bracket form without a trailing space (e.g. `[x]end`)
* isn't standard and rarely appears — we require the space to avoid
* false positives on array-index-style prose like `[1] see ref`.
*/
function parseBulletItem(raw: string): BulletItem {
const m = raw.match(/^\[([ xX])\]\s+(.*)$/);
if (!m) return { text: raw };
const done = m[1]!.toLowerCase() === "x";
return { text: m[2] ?? "", task: done ? "done" : "todo" };
}
function BlockView({ block, citations }: { block: Block; citations?: CitationMap }) {
switch (block.kind) {
case "heading":
@@ -707,19 +1059,32 @@ function BlockView({ block, citations }: { block: Block; citations?: CitationMap
</Text>
);
case "paragraph":
return <InlineMd text={block.text} citations={citations} />;
return <ParagraphView text={block.text} citations={citations} />;
case "bullet":
return (
<Box flexDirection="column">
{block.items.map((item, i) => (
<Box key={`${i}-${item.slice(0, 24)}`}>
<Text color="cyan">{block.ordered ? ` ${block.start + i}. ` : " • "}</Text>
<InlineMd text={item} citations={citations} />
<Box key={`${i}-${item.text.slice(0, 24)}`}>
<Text color={item.task === "done" ? "green" : "cyan"}>
{bulletPrefix(block, i, item)}
</Text>
{item.task === "done" ? (
<Text strikethrough dimColor>
<InlineMd text={item.text} citations={citations} />
</Text>
) : (
<InlineMd text={item.text} citations={citations} />
)}
</Box>
))}
</Box>
);
case "quote":
return <BlockquoteView block={block} citations={citations} />;
case "code":
if (DIAGRAM_LANGS.has(block.lang.toLowerCase())) {
return <DiagramCodeBlock lang={block.lang} text={block.text} />;
}
return (
<Box borderStyle="single" borderColor="gray" paddingX={1}>
<Text color="yellow">{block.text}</Text>
@@ -734,6 +1099,83 @@ function BlockView({ block, citations }: { block: Block; citations?: CitationMap
}
}
/**
* Paragraph renderer. Plain text goes straight to InlineMd. If the
* paragraph carries embedded `\n` (inserted by parseBlocks when it
* sees a GFM hard break — trailing ` ` on a source line), split
* and render each segment as its own row so the newline is visible
* in the terminal. Single-line paragraphs still render as one row
* for tight layout.
*/
function ParagraphView({ text, citations }: { text: string; citations?: CitationMap }) {
if (!text.includes("\n")) {
return <InlineMd text={text} citations={citations} />;
}
const rows = text.split("\n");
return (
<Box flexDirection="column">
{rows.map((row, i) => (
// biome-ignore lint/suspicious/noArrayIndexKey: hard-break rows are source-ordered and never reorder
<InlineMd key={`ln-${i}`} text={row} citations={citations} />
))}
</Box>
);
}
/**
* Pick the gutter glyph for a bullet-list item:
* - ordered → ` N. `
* - task done → ` ☒ ` (green + struck-through in the caller)
* - task todo → ` ☐ `
* - plain → ` • `
* Width is stable within a list so text after the prefix stays aligned.
*/
function bulletPrefix(block: BulletBlock, i: number, item: BulletItem): string {
if (block.ordered) return ` ${block.start + i}. `;
if (item.task === "done") return " ☒ ";
if (item.task === "todo") return " ☐ ";
return " • ";
}
/**
* Blockquote renderer: left-bar frame (`borderLeft` only, dim) that
* wraps any child block content. The bar grows with the rendered
* height automatically — no manual per-line prefix — so a quote
* containing a list, a code block, or another quote still looks
* right regardless of how many rows each child consumes.
*
* Nested `>>` quotes surface as a BlockquoteView inside another
* BlockquoteView, producing two adjacent bars (visually nested).
* Inner blocks keep their normal colors (code yellow, bullet cyan,
* etc.) — we dim only the bar, not the content, so a code snippet
* inside a quote still reads as code.
*/
function BlockquoteView({
block,
citations,
}: {
block: BlockquoteBlock;
citations?: CitationMap;
}) {
return (
<Box
borderStyle="single"
borderColor="gray"
borderDimColor
borderTop={false}
borderRight={false}
borderBottom={false}
paddingLeft={1}
flexDirection="column"
gap={1}
>
{block.children.map((child, i) => (
<BlockView key={`q-${i}-${child.kind}`} block={child} citations={citations} />
))}
</Box>
);
}
/**
* Split one table row into trimmed cells. Leading/trailing column
* markers are optional (both `| a | b |` and `a | b` are accepted).
@@ -875,8 +1317,66 @@ function EditBlockRow({ block }: { block: EditBlockView }) {
);
}
/**
* Code-block languages that render as graphs/diagrams in real
* browsers but can't be drawn in a terminal. For these we show the
* SOURCE with a distinct frame + a header and a "paste into viewer"
* hint, so the user knows they're looking at a diagram-source block
* rather than executable code.
*/
const DIAGRAM_LANGS = new Set([
"mermaid",
"dot",
"graphviz",
"plantuml",
"puml",
"flowchart",
"sequencediagram",
"gantt",
"erdiagram",
]);
/**
* Viewer URL hint keyed by language — shown dim at the bottom of a
* diagram-source block so users know where to paste it to see the
* actual graph. Fallback is a generic "use the matching viewer" for
* less common langs.
*/
const DIAGRAM_VIEWER_HINT: Record<string, string> = {
mermaid: "→ paste at https://mermaid.live to view",
plantuml: "→ paste at https://www.plantuml.com/plantuml to view",
puml: "→ paste at https://www.plantuml.com/plantuml to view",
dot: "→ paste at https://dreampuf.github.io/GraphvizOnline to view",
graphviz: "→ paste at https://dreampuf.github.io/GraphvizOnline to view",
};
/**
* Render a diagram-source code block with a magenta double-line
* frame + a `◇ lang diagram (source)` header + a viewer hint
* underneath. Distinct from the plain code-block rendering so the
* user can tell at a glance that the terminal couldn't draw the
* actual graph — they're looking at source to copy out.
*/
function DiagramCodeBlock({ lang, text }: { lang: string; text: string }) {
const hint =
DIAGRAM_VIEWER_HINT[lang.toLowerCase()] ?? "→ render with the matching viewer to view";
return (
<Box flexDirection="column" borderStyle="double" borderColor="magenta" paddingX={1}>
<Text bold color="magenta">
{`◇ ${lang} diagram (source — terminal can't draw the graph)`}
</Text>
<Box marginTop={1}>
<Text color="yellow">{text}</Text>
</Box>
<Box marginTop={1}>
<Text dimColor>{hint}</Text>
</Box>
</Box>
);
}
export function Markdown({ text, projectRoot }: { text: string; projectRoot?: string }) {
const cleaned = stripMath(text);
const cleaned = expandAutolinks(expandEmoji(stripMath(text)));
const root = projectRoot ?? process.cwd();
const citations = React.useMemo(() => collectCitations(cleaned, root), [cleaned, root]);
const blocks = React.useMemo(() => parseBlocks(cleaned), [cleaned]);
+122 -7
View File
@@ -47,25 +47,72 @@ export interface MultilineAction {
/** When `true`, fire `onSubmit(submitValue ?? value)`. */
submit: boolean;
submitValue?: string;
/**
* When set, the key was ↑/↓ at a buffer boundary (empty buffer, or
* cursor already at first/last line) and the component should hand
* off to the parent's history-recall handler. The child's cursor
* didn't move; the parent decides whether to swap in a prior
* prompt. Lets users escape out of a multi-line buffer into
* history without first emptying it — previously NOOP felt stuck.
*/
historyHandoff?: "prev" | "next";
/**
* Multi-char paste detected. The reducer is pure so it can't
* allocate a sentinel id or write to the registry — it hands the
* raw normalized payload up to PromptInput, which registers the
* paste, picks a sentinel codepoint, and inserts THAT (one char)
* into the buffer. Result: the user sees a `[paste #N · M lines]`
* placeholder instead of the full content drowning the typed text.
*/
pasteRequest?: { content: string };
}
const BACKSLASH_SUFFIX = /\\$/;
const NOOP: MultilineAction = { next: null, cursor: null, submit: false };
function rewriteRawArrowEscape(key: MultilineKey): MultilineKey {
if (key.upArrow || key.downArrow || key.leftArrow || key.rightArrow) return key;
if (key.input === "\x1b[A") return { ...key, upArrow: true, input: "" };
if (key.input === "\x1b[B") return { ...key, downArrow: true, input: "" };
if (key.input === "\x1b[C") return { ...key, rightArrow: true, input: "" };
if (key.input === "\x1b[D") return { ...key, leftArrow: true, input: "" };
return key;
}
export function processMultilineKey(
value: string,
cursor: number,
key: MultilineKey,
keyIn: MultilineKey,
): MultilineAction {
// Parent-owned keys: Tab (slash-complete), Esc (abort), PageUp/Down.
if (key.tab || key.escape || key.pageUp || key.pageDown) {
// Raw-escape fallback for terminals (some Windows configurations —
// cmd.exe, older winpty) that don't set `key.upArrow` / etc. on
// arrow-key press and instead leak the raw ANSI CSI sequence into
// `input`. Without this, `\x1b[A` lands on the "printable" branch
// below and the user sees literal escape bytes inserted into their
// buffer. Rewrite the event into the structured key here.
const key: MultilineKey = rewriteRawArrowEscape(keyIn);
// Parent-owned keys: Tab (slash-complete), Esc (abort).
if (key.tab || key.escape) {
return NOOP;
}
// Buffer-wide navigation. Per-line motion (↑/↓ / Ctrl+A / Ctrl+E)
// is already covered; PageUp/PageDown are the missing "jump to
// top / bottom of the WHOLE buffer" pair, useful after pasting a
// 500-line blob where ↑×500 is absurd. Repurposed from the
// previous NOOP behavior (PageUp/Down had no binding).
if (key.pageUp) {
return cursor === 0 ? NOOP : { next: null, cursor: 0, submit: false };
}
if (key.pageDown) {
return cursor === value.length ? NOOP : { next: null, cursor: value.length, submit: false };
}
// Empty buffer + ↑/↓ → parent handles history recall.
if (value.length === 0 && (key.upArrow || key.downArrow)) {
return NOOP;
return { ...NOOP, historyHandoff: key.upArrow ? "prev" : "next" };
}
// Cursor motion.
@@ -77,11 +124,16 @@ export function processMultilineKey(
}
if (key.upArrow) {
const moved = moveCursorUp(value, cursor);
return moved === cursor ? NOOP : { next: null, cursor: moved, submit: false };
// Cursor already on the first line — hand off to history recall
// instead of sitting stuck. Users can now escape into history
// from the middle of a multi-line draft.
if (moved === cursor) return { ...NOOP, historyHandoff: "prev" };
return { next: null, cursor: moved, submit: false };
}
if (key.downArrow) {
const moved = moveCursorDown(value, cursor);
return moved === cursor ? NOOP : { next: null, cursor: moved, submit: false };
if (moved === cursor) return { ...NOOP, historyHandoff: "next" };
return { next: null, cursor: moved, submit: false };
}
// Emacs-style line jumps (universal across terminals; Home/End aren't
@@ -92,8 +144,55 @@ export function processMultilineKey(
if (key.ctrl && key.input === "e") {
return { next: null, cursor: endOfLine(value, cursor), submit: false };
}
// Bash / readline conventions:
// Ctrl+U — clear the whole buffer (readline treats this as
// "clear from cursor to start"; for our text-area we treat it
// as "clear all" because there's no ergonomic way to clear a
// huge paste otherwise).
// Ctrl+W — delete the word before the cursor.
if (key.ctrl && key.input === "u") {
return value.length === 0 ? NOOP : { next: "", cursor: 0, submit: false };
}
if (key.ctrl && key.input === "w") {
if (cursor === 0) return NOOP;
const wordStart = previousWordStart(value, cursor);
return {
next: value.slice(0, wordStart) + value.slice(cursor),
cursor: wordStart,
submit: false,
};
}
// Newline: Ctrl+J (LF literal) or ctrl+'j' normalized form.
// Paste-burst detection. If `input` contains a newline (or
// bracketed-paste markers from a terminal that supports them),
// this is a paste — surface it as a `pasteRequest` so the parent
// can register the blob and insert ONE sentinel codepoint instead
// of the full content. The buffer stays small + readable; the
// user sees `[paste #N · M lines]` where the paste lives.
//
// Always overrides `key.return` for pastes: Ink occasionally sets
// key.return when a paste's trailing \n looks like Enter, which
// would submit the partial buffer mid-paste and silently truncate
// the content. Pastes always insert; Enter only submits typed
// content. We normalize \r\n and bare \r to \n so mixed-line-
// ending pastes (Windows clipboard, web copy) land cleanly.
const stripped = key.input.replaceAll("\u001b[200~", "").replaceAll("\u001b[201~", "");
// Paste = newline-containing input with MORE than just the newline
// itself. A bare "\n" is Ctrl+J / one-keystroke newline (handled
// below); only multi-char input wrapped around a newline is a real
// paste burst that warrants a sentinel.
const looksLikePaste =
stripped.length > 1 && (stripped.includes("\n") || stripped.includes("\r"));
if (looksLikePaste) {
const normalized = stripped.replace(/\r\n?/g, "\n");
return {
next: null,
cursor: null,
submit: false,
pasteRequest: { content: normalized },
};
}
// Single-char Ctrl+J / LF: insert one newline.
if (key.input === "\n" || (key.ctrl && key.input === "j")) {
return insertAt(value, cursor, "\n");
}
@@ -172,6 +271,22 @@ function startOfLine(value: string, cursor: number): number {
return value.lastIndexOf("\n", cursor - 1) + 1;
}
/**
* Find the start of the word immediately to the left of the cursor.
* Skips trailing whitespace first (so Ctrl+W after typing space
* still removes the previous word, not just the space), then walks
* back over the word characters until a whitespace boundary or
* start-of-buffer. Newlines count as whitespace, so Ctrl+W at the
* start of a line deletes the preceding line's last word — same
* behavior as bash/readline.
*/
function previousWordStart(value: string, cursor: number): number {
let i = cursor;
while (i > 0 && /\s/.test(value[i - 1] ?? "")) i--;
while (i > 0 && !/\s/.test(value[i - 1] ?? "")) i--;
return i;
}
function endOfLine(value: string, cursor: number): number {
const nl = value.indexOf("\n", cursor);
return nl === -1 ? value.length : nl;
+133
View File
@@ -0,0 +1,133 @@
/**
* Paste sentinels — represent a pasted blob as a single codepoint in
* the input buffer instead of inlining its full contents.
*
* Why: a 3000-line paste shoved verbatim into the buffer drowns the
* surrounding typed text, costs a lot to render per keystroke, and
* makes navigation/clear awkward. Replace it with one PUA char (a
* "sentinel") and store the real content in a side registry. The
* buffer string stays small, the user types around the sentinel as
* if it were a single character, and a Backspace at the sentinel
* deletes the whole paste in one stroke. On submit we expand the
* sentinels back to real content.
*
* Encoding:
* - One codepoint per paste, in PUA range U+E100..U+E1FF (256 slots).
* - The codepoint's offset within that range is the paste id.
* - That gives us 256 distinct paste blobs per session before ids
* wrap. In practice users paste a handful per session — wrap is
* a non-issue, but if it happens, the new paste overwrites the
* oldest registry entry; any stale sentinels still in the buffer
* will render with a "(missing)" badge so the user can clean up.
*
* Range chosen from the Supplementary PUA-A region's neighbor (BMP
* PUA) so a single `String.fromCharCode` works — no surrogate pairs,
* no `length === 2` weirdness for cursor arithmetic.
*/
export const PASTE_SENTINEL_BASE = 0xe100;
export const PASTE_SENTINEL_RANGE = 256;
export const PASTE_SENTINEL_END = PASTE_SENTINEL_BASE + PASTE_SENTINEL_RANGE;
export interface PasteEntry {
id: number;
content: string;
lineCount: number;
charCount: number;
}
export function encodePasteSentinel(id: number): string {
if (id < 0 || id >= PASTE_SENTINEL_RANGE) {
throw new Error(`paste sentinel id ${id} out of range [0, ${PASTE_SENTINEL_RANGE})`);
}
return String.fromCharCode(PASTE_SENTINEL_BASE + id);
}
/** Returns the paste id, or `null` if `ch` is not a sentinel codepoint. */
export function decodePasteSentinel(ch: string): number | null {
if (ch.length === 0) return null;
const cp = ch.charCodeAt(0);
if (cp < PASTE_SENTINEL_BASE || cp >= PASTE_SENTINEL_END) return null;
return cp - PASTE_SENTINEL_BASE;
}
export function isPasteSentinel(ch: string): boolean {
return decodePasteSentinel(ch) !== null;
}
/**
* Build a PasteEntry from raw paste content. Computes line + char
* counts once at registration time so the renderer doesn't re-count
* on every keystroke.
*/
export function makePasteEntry(id: number, content: string): PasteEntry {
return {
id,
content,
lineCount: content.split("\n").length,
charCount: content.length,
};
}
/**
* Expand every sentinel in `text` back to its registered paste
* content. Unknown sentinels (entry missing — registry was wiped, or
* id wrap collision) drop to empty string so the resulting prompt
* doesn't carry a literal PUA codepoint to the model.
*
* Used at submit time to recover the full prompt the user composed.
*/
export function expandPasteSentinels(
text: string,
pastes: ReadonlyMap<number, PasteEntry>,
): string {
let out = "";
for (let i = 0; i < text.length; i++) {
const ch = text[i]!;
const id = decodePasteSentinel(ch);
if (id === null) {
out += ch;
continue;
}
const entry = pastes.get(id);
out += entry?.content ?? "";
}
return out;
}
/**
* Quick check: does the buffer contain ANY sentinel? Used to gate
* UI hints (the "paste #N" listing in the prompt-box footer) without
* walking the whole buffer twice.
*/
export function bufferHasPaste(text: string): boolean {
for (let i = 0; i < text.length; i++) {
if (decodePasteSentinel(text[i]!) !== null) return true;
}
return false;
}
/**
* Walk the buffer and return the ids of every sentinel still
* present, in source order. Used by the registry's GC pass at
* submit time so unreachable paste entries don't accumulate.
* (No-op when the buffer is sentinel-free.)
*/
export function listPasteIdsInBuffer(text: string): number[] {
const ids: number[] = [];
for (let i = 0; i < text.length; i++) {
const id = decodePasteSentinel(text[i]!);
if (id !== null) ids.push(id);
}
return ids;
}
/**
* Format `1234` chars as `1.2KB` etc. Tiny helper used in placeholder
* labels — kept here so paste-related display logic is co-located.
*/
export function formatBytesShort(n: number): string {
if (n < 1024) return `${n}B`;
if (n < 1024 * 1024) return `${(n / 1024).toFixed(n < 1024 * 10 ? 1 : 0)}KB`;
return `${(n / (1024 * 1024)).toFixed(1)}MB`;
}
+50 -18
View File
@@ -3,45 +3,77 @@
* (in-chat `/preset`) and the wizard (first-run setup) read from here.
*
* Presets are the single vocabulary we teach new users: they don't need
* to know model IDs, Pillar 2, branch budgets, or cost tradeoffs
* independently — they pick "fast / smart / max" and we translate.
* to know model IDs, reasoning effort, or thinking mode independently
* — they pick "fast / smart / max" and we translate.
*
* Design rules (v0.6+):
* - Branching (`branch >= 2`) is NEVER in a preset. Self-consistency
* sampling is `N×` cost; auto-enabling it would ambush users into
* multi-dollar turns without asking. Opt-in only via `/branch N`.
* - Harvest (Pillar-2 plan-state extraction) is NEVER in a preset.
* In practice it's display sugar — the typed plan state hasn't
* fed back into orchestration decisions (branch trigger) often
* enough to pay for the extra round-trip. Opt-in only via
* `/harvest on`.
* - The three tiers differ on only TWO knobs: model (flash/pro) and
* reasoning effort (high/max). Same on-the-wire billing axis,
* easy to reason about, easy to budget.
*/
import type { PresetName } from "../../config.js";
export interface PresetSettings {
model: string;
/**
* Reasoning-effort cap sent per turn. `high` = shorter chain of
* thought (cheaper, faster); `max` = agent-class default (deeper,
* more output tokens). DeepSeek ignores this field on non-thinking
* calls, so it's safe to pin across models.
*/
reasoningEffort: "high" | "max";
/**
* Pillar-2 plan-state extraction. Every preset ships `false` (see
* module header); kept in the shape so a user who later flips it on
* at runtime still round-trips cleanly. `/harvest on` toggles it.
*/
harvest: boolean;
/** Branch budget. `1` means branching off. */
/**
* Branch budget. Every preset ships `1` (off). `/branch N` with
* N>=2 is the only way to enable self-consistency sampling.
*/
branch: number;
}
export const PRESETS: Record<PresetName, PresetSettings> = {
// `deepseek-chat` / `deepseek-reasoner` are retained as the fast /
// smart models because they're deprecated-but-working compat aliases
// for v4-flash's non-thinking and thinking modes respectively. Same
// billing, smaller config churn for existing users. `max` promotes
// to v4-pro — 12× flash on input/output, reserved for hard tasks.
fast: { model: "deepseek-chat", harvest: false, branch: 1 },
smart: { model: "deepseek-reasoner", harvest: true, branch: 1 },
max: { model: "deepseek-v4-pro", harvest: true, branch: 3 },
// fast — flash + effort=high. Quick Q&A, one-line tweaks, anything
// where shallow reasoning is enough. Cheapest turn possible.
fast: { model: "deepseek-v4-flash", reasoningEffort: "high", harvest: false, branch: 1 },
// smart — flash + effort=max. Full thinking budget on the cheap
// model. The default: handles 90%+ of coding work at a fraction
// of pro's cost.
smart: { model: "deepseek-v4-flash", reasoningEffort: "max", harvest: false, branch: 1 },
// max — pro + effort=max. Frontier model for hard tasks: cross-
// file architecture, subtle bug hunts, anything where flash's
// reasoning has measurably failed. ~12× per-token vs flash; save
// for when you need it, or use `/pro` to escalate a single turn.
max: { model: "deepseek-v4-pro", reasoningEffort: "max", harvest: false, branch: 1 },
};
export const PRESET_DESCRIPTIONS: Record<PresetName, { headline: string; cost: string }> = {
fast: {
headline: "deepseek-chat (= v4-flash non-thinking), no harvest, no branching",
cost: "~1¢ per 100 turns · default",
headline: "v4-flash · effort=high",
cost: "cheapest · quick Q&A, one-line edits",
},
smart: {
headline: "deepseek-reasoner (= v4-flash thinking) + Pillar 2 harvest",
cost: "same price as fast · slower · better on multi-step tasks",
headline: "v4-flash · effort=max",
cost: "~1.5× fast · default · day-to-day coding",
},
max: {
headline: "deepseek-v4-pro + harvest + self-consistency (3 branches)",
cost: "~30× cost vs fast · slowest · for hard single-shots",
headline: "v4-pro · effort=max",
cost: "~12× fast · hard single-shots · use /pro for a single-turn bump",
},
};
export function resolvePreset(name: PresetName | undefined): PresetSettings {
return PRESETS[name ?? "fast"];
return PRESETS[name ?? "smart"];
}
+20 -1574
View File
File diff suppressed because it is too large. Load diff
+219
View File
@@ -0,0 +1,219 @@
import type { SlashArgContext, SlashCommandSpec } from "./types.js";
export const SLASH_COMMANDS: readonly SlashCommandSpec[] = [
{ cmd: "help", summary: "show the full command reference" },
{ cmd: "status", summary: "current model, flags, context, session" },
{
cmd: "preset",
argsHint: "<fast|smart|max>",
summary: "one-tap model + harvest + branch bundle",
argCompleter: ["fast", "smart", "max"],
},
{
cmd: "model",
argsHint: "<id>",
summary: "switch DeepSeek model id",
argCompleter: "models",
},
{ cmd: "models", summary: "list available models fetched from DeepSeek /models" },
{
cmd: "harvest",
argsHint: "[on|off]",
summary: "toggle Pillar-2 plan-state extraction",
argCompleter: ["on", "off"],
},
{
cmd: "branch",
argsHint: "<N|off>",
summary: "run N parallel samples per turn (N>=2)",
argCompleter: ["off", "2", "3", "4", "5"],
},
{
cmd: "effort",
argsHint: "<high|max>",
summary: "reasoning_effort cap — max is default (agent-class), high is cheaper/faster",
argCompleter: ["max", "high"],
},
{
cmd: "pro",
argsHint: "[off]",
summary: "arm v4-pro for the NEXT turn only (one-shot · auto-disarms after turn)",
argCompleter: ["off"],
},
{ cmd: "mcp", summary: "list MCP servers + tools attached to this session" },
{
cmd: "resource",
argsHint: "[uri]",
summary: "browse + read MCP resources (no arg → list URIs; <uri> → fetch contents)",
argCompleter: "mcp-resources",
},
{
cmd: "prompt",
argsHint: "[name]",
summary: "browse + fetch MCP prompts (no arg → list names; <name> → render prompt)",
argCompleter: "mcp-prompts",
},
{ cmd: "tool", argsHint: "[N]", summary: "dump full output of the Nth tool call (1=latest)" },
{
cmd: "memory",
argsHint: "[list|show <name>|forget <name>|clear <scope> confirm]",
summary: "show / manage pinned memory (REASONIX.md + ~/.reasonix/memory)",
},
{
cmd: "skill",
argsHint: "[list|show <name>|<name> [args]]",
summary: "list / run user skills (<project>/.reasonix/skills + ~/.reasonix/skills)",
},
{
cmd: "hooks",
argsHint: "[reload]",
summary: "list active hooks (settings.json under .reasonix/) · reload re-reads from disk",
},
{
cmd: "update",
summary: "show current vs latest version + the shell command to upgrade",
},
{
cmd: "stats",
summary:
"cross-session cost dashboard (today / week / month / all-time · cache hit · vs Claude)",
},
{ cmd: "think", summary: "dump the last turn's full R1 reasoning (reasoner only)" },
{
cmd: "context",
summary: "break down where context tokens are going: system / tools / per-turn log",
},
{ cmd: "retry", summary: "truncate & resend your last message (fresh sample)" },
{
cmd: "compact",
argsHint: "[tokens]",
summary:
"shrink oversized tool results AND tool-call args (edit_file search/replace) in the log; cap in tokens, default 4000",
},
{ cmd: "keys", summary: "show all keyboard shortcuts and prompt prefixes" },
{ cmd: "plans", summary: "list this session's active + archived plans, newest first" },
{
cmd: "replay",
summary: "load an archived plan as a read-only Time Travel snapshot (default: newest)",
argsHint: "[N]",
},
{ cmd: "sessions", summary: "list saved sessions (current marked with ▸)" },
{ cmd: "forget", summary: "delete the current session from disk" },
{ cmd: "setup", summary: "reminds you to exit and run `reasonix setup`" },
{ cmd: "clear", summary: "clear visible scrollback only (log/context kept)" },
{ cmd: "new", summary: "start a fresh conversation (clear context + scrollback)" },
{ cmd: "exit", summary: "quit the TUI" },
// Code-mode only
{ cmd: "apply", summary: "commit pending edit blocks to disk", contextual: "code" },
{ cmd: "discard", summary: "drop pending edit blocks without writing", contextual: "code" },
{ cmd: "undo", summary: "roll back the last applied edit batch", contextual: "code" },
{
cmd: "history",
summary: "list every edit batch this session (ids for /show, undone markers)",
contextual: "code",
},
{
cmd: "show",
argsHint: "[id]",
summary: "dump a stored edit diff (omit id for newest non-undone)",
contextual: "code",
},
{
cmd: "commit",
argsHint: '"msg"',
summary: "git add -A && git commit -m ...",
contextual: "code",
},
{
cmd: "plan",
argsHint: "[on|off]",
summary: "toggle read-only plan mode (writes bounced until submit_plan + approval)",
contextual: "code",
argCompleter: ["on", "off"],
},
{
cmd: "apply-plan",
summary: "force-approve a pending / in-text plan (fallback if picker was missed)",
contextual: "code",
},
{
cmd: "mode",
argsHint: "[review|auto]",
summary: "edit-gate: review (queue for /apply) or auto (apply+undo banner). Shift+Tab cycles.",
contextual: "code",
argCompleter: ["review", "auto"],
},
{ cmd: "jobs", summary: "list background jobs started by run_background", contextual: "code" },
{
cmd: "kill",
argsHint: "<id>",
summary: "stop a background job by id (SIGTERM → SIGKILL after grace)",
contextual: "code",
},
{
cmd: "logs",
argsHint: "<id> [lines]",
summary: "tail a background job's output (default last 80 lines)",
contextual: "code",
},
];
/**
* Filter the registry by a prefix string (without the leading `/`).
* Empty prefix returns the full non-contextual list (plus code-mode
* entries when `codeMode` is true). Case-insensitive.
*/
export function suggestSlashCommands(prefix: string, codeMode = false): SlashCommandSpec[] {
const p = prefix.toLowerCase();
return SLASH_COMMANDS.filter((c) => {
if (c.contextual === "code" && !codeMode) return false;
return c.cmd.startsWith(p);
});
}
/**
* Classify the prompt buffer for argument completion. Returns `null`
* when the buffer isn't in a slash-with-args state.
*
* Firing shape: input must start with `/<cmd> ` (space after a known
* command). The character right after the space through end-of-buffer
* is the "arg tail"; if the tail has NO internal whitespace the
* picker is live (tail is the partial). If the tail has whitespace,
* the user has moved past the first argument position and we surface
* the usage hint only.
*/
export function detectSlashArgContext(input: string, codeMode = false): SlashArgContext | null {
// `/cmd <rest>` — one space, rest captured up to end-of-buffer.
const m = /^\/(\S+) ([\s\S]*)$/.exec(input);
if (!m) return null;
const cmdName = m[1]!.toLowerCase();
const tail = m[2] ?? "";
const spec = SLASH_COMMANDS.find(
(s) => s.cmd === cmdName && (s.contextual !== "code" || codeMode),
);
if (!spec) return null;
const hasInternalSpace = /\s/.test(tail);
const partialOffset = input.length - tail.length;
if (hasInternalSpace) {
// Past the first arg position (typing the second arg for e.g.
// `/edit <file> <instruction>`, or mid-sentence for free-form).
return { spec, partial: tail, partialOffset, kind: "hint" };
}
// No internal whitespace — we're still typing the first arg. Picker
// is live if the spec declares a completer; otherwise show a hint
// ("what goes here?") since the user's guessing.
return {
spec,
partial: tail,
partialOffset,
kind: spec.argCompleter ? "picker" : "hint",
};
}
export function parseSlash(text: string): { cmd: string; args: string[] } | null {
if (!text.startsWith("/")) return null;
const parts = text.slice(1).trim().split(/\s+/);
const cmd = parts[0]?.toLowerCase() ?? "";
if (!cmd) return null;
return { cmd, args: parts.slice(1) };
}
+54
View File
@@ -0,0 +1,54 @@
import type { CacheFirstLoop } from "../../../loop.js";
import { handlers as adminHandlers } from "./handlers/admin.js";
import { handlers as basicHandlers } from "./handlers/basic.js";
import { handlers as editsHandlers } from "./handlers/edits.js";
import { handlers as jobsHandlers } from "./handlers/jobs.js";
import { handlers as mcpHandlers } from "./handlers/mcp.js";
import { handlers as memoryHandlers } from "./handlers/memory.js";
import { handlers as modelHandlers } from "./handlers/model.js";
import { handlers as observabilityHandlers } from "./handlers/observability.js";
import { handlers as plansHandlers } from "./handlers/plans.js";
import { handlers as sessionsHandlers } from "./handlers/sessions.js";
import { handlers as skillHandlers } from "./handlers/skill.js";
import type { SlashContext, SlashResult } from "./types.js";
/**
* A slash handler receives the command's args + the loop + shared
* runtime context, and returns a synchronous SlashResult. Async work
* (balance fetches, stop_job) fires-and-forgets via `ctx.postInfo`
* instead — keeps the TUI input non-blocking.
*/
export type SlashHandler = (args: string[], loop: CacheFirstLoop, ctx: SlashContext) => SlashResult;
/**
* Flat map of cmd → handler. Composed from per-topic modules so each
* feature's logic stays local; aliases (e.g. `exit` / `quit`) are just
* extra keys in the per-module handlers bag pointing at the same fn.
*
* Ordering of the spread matters only for duplicate keys; there are
* none. Keep alphabetical for diff sanity when adding modules.
*/
const HANDLERS: Record<string, SlashHandler> = {
...adminHandlers,
...basicHandlers,
...editsHandlers,
...jobsHandlers,
...mcpHandlers,
...memoryHandlers,
...modelHandlers,
...observabilityHandlers,
...plansHandlers,
...sessionsHandlers,
...skillHandlers,
};
export function handleSlash(
cmd: string,
args: string[],
loop: CacheFirstLoop,
ctx: SlashContext = {},
): SlashResult {
const h = HANDLERS[cmd];
if (h) return h(args, loop, ctx);
return { unknown: true, info: `unknown command: /${cmd} (try /help)` };
}
+158
View File
@@ -0,0 +1,158 @@
import {
HOOK_EVENTS,
type HookEvent,
type ResolvedHook,
globalSettingsPath,
projectSettingsPath,
} from "../../../../hooks.js";
import { aggregateUsage, defaultUsageLogPath, readUsageLog } from "../../../../usage.js";
import { VERSION, compareVersions, isNpxInstall } from "../../../../version.js";
import { renderDashboard } from "../../../commands/stats.js";
import type { SlashHandler } from "../dispatch.js";
const hooks: SlashHandler = (args, loop, ctx) => {
const sub = (args[0] ?? "").toLowerCase();
if (sub === "reload") {
if (!ctx.reloadHooks) {
return {
info: "/hooks reload is not available in this context (no reload callback wired).",
};
}
const count = ctx.reloadHooks();
return { info: `▸ reloaded hooks · ${count} active` };
}
if (sub !== "" && sub !== "list" && sub !== "ls") {
return {
info: "usage: /hooks list active hooks\n /hooks reload re-read settings.json files",
};
}
const all = loop.hooks;
const projPath = ctx.codeRoot ? projectSettingsPath(ctx.codeRoot) : undefined;
const globPath = globalSettingsPath();
if (all.length === 0) {
const lines = [
"no hooks configured.",
"",
"drop a settings.json with a `hooks` key into either of:",
ctx.codeRoot
? ` · ${projPath} (project)`
: " · <project>/.reasonix/settings.json (project)",
` · ${globPath} (global)`,
"",
"events: PreToolUse, PostToolUse, UserPromptSubmit, Stop",
"exit 0 = pass · exit 2 = block (Pre*) · other = warn",
];
return { info: lines.join("\n") };
}
const grouped = new Map<HookEvent, ResolvedHook[]>();
for (const event of HOOK_EVENTS) grouped.set(event, []);
for (const h of all) grouped.get(h.event)?.push(h);
const lines: string[] = [`▸ ${all.length} hook(s) loaded`];
for (const event of HOOK_EVENTS) {
const list = grouped.get(event) ?? [];
if (list.length === 0) continue;
lines.push("", `${event}:`);
for (const h of list) {
const match = h.match && h.match !== "*" ? ` match=${h.match}` : "";
const desc = h.description ? ` — ${h.description}` : "";
lines.push(` [${h.scope}]${match} ${h.command}${desc}`);
}
}
lines.push("", `sources: project=${projPath ?? "(none — chat mode)"} · global=${globPath}`);
return { info: lines.join("\n") };
};
/**
* `/update` — inside the TUI we deliberately do NOT spawn `npm install`.
* stdio:inherit into a running Ink renderer corrupts the display, and
* the process being upgraded is the same process that's still reading
* its own binaries (messy on Windows). Instead we surface what we
* already know from the App's background registry check and print the
* exact shell command the user should run after exiting.
*
* The `latestVersion` ctx field is populated by App.tsx's mount-time
* `getLatestVersion()` effect. When it's `null` we report the check
* as pending/offline — still a useful output (current version + how
* to force a fresh check from another terminal).
*/
const update: SlashHandler = (_args, _loop, ctx) => {
const latest = ctx.latestVersion ?? null;
const lines: string[] = [`current: reasonix ${VERSION}`];
if (latest === null) {
// Kick off a fresh fetch so a follow-up /update a few seconds
// later has a real answer instead of the same pending message.
ctx.refreshLatestVersion?.();
lines.push(
"latest: (not yet resolved — background check in flight or offline)",
"",
"triggered a fresh registry fetch — retry `/update` in a few seconds,",
"or run `reasonix update` in another terminal to force it synchronously.",
);
return { info: lines.join("\n") };
}
lines.push(`latest: reasonix ${latest}`);
const diff = compareVersions(VERSION, latest);
if (diff >= 0) {
lines.push("", "you're on the latest. nothing to do.");
return { info: lines.join("\n") };
}
if (isNpxInstall()) {
lines.push(
"",
"you're running via npx — the next `npx reasonix ...` launch will auto-fetch.",
"to force a refresh sooner: `npm cache clean --force`.",
);
} else {
lines.push(
"",
"to upgrade, exit this session and run:",
" reasonix update (interactive, dry-run supported via --dry-run)",
" npm install -g reasonix@latest (direct)",
"",
"in-session install is deliberately disabled — the npm spawn would",
"corrupt this TUI's rendering and Windows can lock the running binary.",
);
}
return { info: lines.join("\n") };
};
/**
* `/stats` — dashboard view of `~/.reasonix/usage.jsonl`, the same
* roll-up `reasonix stats` (no arg) prints at the shell. Synchronous
* disk read; cheap enough that we don't bother caching between slash
* invocations.
*
* No transcript-path variant in-TUI: the per-file summary is scripty
* and rarely wanted mid-session. If someone needs it they have the
* CLI form (`reasonix stats <path>`).
*/
const stats: SlashHandler = () => {
const path = defaultUsageLogPath();
const records = readUsageLog(path);
if (records.length === 0) {
return {
info: [
"no usage data yet.",
"",
` ${path}`,
"",
"every turn you run here appends one record — this session's turns",
"will show up in the dashboard once you send a message.",
].join("\n"),
};
}
const agg = aggregateUsage(records);
return { info: renderDashboard(agg, path) };
};
export const handlers: Record<string, SlashHandler> = {
hook: hooks,
hooks,
update,
stats,
};
+160
View File
@@ -0,0 +1,160 @@
import type { SlashHandler } from "../dispatch.js";
const exit: SlashHandler = () => ({ exit: true });
const clear: SlashHandler = () => ({
clear: true,
info: "▸ terminal cleared (viewport + scrollback). Context (message log) is intact — next turn still sees everything. Use /new to start fresh, or /forget to delete the session entirely.",
});
const resetLog: SlashHandler = (_args, loop) => {
// Actually drop the in-memory log + rewrite the session file so the
// NEXT call has no prior context. Keeps session name, model, and
// other config — just the conversation is reset.
const { dropped } = loop.clearLog();
return {
clear: true,
info: `▸ new conversation — dropped ${dropped} message(s) from context. Same session, fresh slate.`,
};
};
const keys: SlashHandler = () => ({
info: [
"Keyboard & prompt shortcuts:",
"",
" Enter submit the current prompt",
" Shift+Enter / Ctrl+J insert a newline (multi-line prompt)",
" \\<Enter> bash-style line continuation",
" ← → ↑ ↓ move cursor / recall history at buffer boundary",
" PageUp / PageDown jump to top / bottom of the WHOLE buffer (handy after a big paste)",
" Ctrl+A / Ctrl+E jump to start / end of the CURRENT line",
" Ctrl+U clear the entire input buffer",
" Ctrl+W delete the word before the cursor",
" Backspace delete left; Delete delete under cursor",
" Esc abort the in-flight turn",
" y / n accept / reject pending edits (code mode)",
" Shift+Tab cycle edit gate: review ↔ AUTO (code mode, persists to config)",
" u undo the latest non-undone edit batch (session-wide, not just banner)",
"",
"Prompt prefixes:",
" /<name> slash command; Tab/Enter picks from the suggestion list",
" @<path> inline a file under [Referenced files] (code mode).",
" Trailing `@…` opens a file picker; ↑/↓ navigate, Tab/Enter pick.",
" !<cmd> run <cmd> as shell in the sandbox root; output goes into context",
" so the model sees it next turn. No allowlist gate.",
"",
"Pickers (slash + @-mention):",
" ↑ / ↓ navigate the suggestion list",
" Tab insert the highlighted item without submitting",
" Enter insert and (slash) run it, (@) keep editing",
"",
"MCP exploration:",
" /mcp servers + tool/resource/prompt counts",
" /resource [uri] browse & read resources exposed by your MCP servers",
" /prompt [name] browse & fetch prompts exposed by your MCP servers",
"",
"Useful slashes: /help · /context · /stats · /compact · /new · /exit",
].join("\n"),
});
const help: SlashHandler = () => ({
info: [
"Commands:",
" /help this message",
" /keys keyboard shortcuts + prompt prefixes (!, @, /)",
" /status show current settings",
" /preset <fast|smart|max> one-tap presets — see below",
" /model <id> deepseek-v4-flash or deepseek-v4-pro",
" /pro [off] arm v4-pro for NEXT turn only (one-shot, auto-disarms)",
" /harvest [on|off] Pillar 2: structured plan-state extraction (OPT-IN — costs extra)",
" /branch <N|off> run N parallel samples (N>=2) — MANUAL ONLY, N× cost",
" /effort <high|max> reasoning_effort cap (max=full thinking, high=cheaper/faster)",
" /mcp list MCP servers + tools attached to this session",
" /resource [uri] browse + read MCP resources (no arg → list URIs; <uri> → fetch)",
" /prompt [name] browse + fetch MCP prompts (no arg → list names; <name> → render)",
" /setup (exit + reconfigure) → run `reasonix setup`",
" /compact [tokens] shrink large tool results in history (default 4000 tokens/result)",
" /think dump the most recent turn's full R1 reasoning (reasoner only)",
" /tool [N] list tool calls (or dump full output of #N, 1=most recent)",
" /memory [sub] show pinned memory (REASONIX.md + ~/.reasonix/memory).",
" subs: list | show <name> | forget <name> | clear <scope> confirm",
" /skill [sub] list / run user skills (project/.reasonix/skills + ~/.reasonix/skills).",
" subs: list | show <name> | <name> [args] (injects skill body as user turn)",
" /retry truncate & resend your last message (fresh sample from the model)",
" /apply (code mode) commit the pending edit blocks to disk",
" /discard (code mode) drop pending edits without writing",
" /undo (code mode) roll back the latest non-undone edit batch",
" /history (code mode) list every edit batch this session",
" /show [id] (code mode) dump a stored edit diff (newest when id omitted)",
' /commit "msg" (code mode) git add -A && git commit -m "msg"',
" /plan [on|off] (code mode) toggle read-only plan mode; writes gated behind submit_plan + your approval",
" /apply-plan (code mode) force-approve pending/in-text plan (fallback)",
" /mode [review|auto] (code mode) edit-gate: queue edits for /apply or apply instantly (Shift+Tab cycles, u undoes within 5s)",
" /jobs (code mode) list background processes (run_background) — running and exited",
" /kill <id> (code mode) stop a background job by id (SIGTERM → SIGKILL)",
" /logs <id> [lines] (code mode) tail a background job's output (default 80 lines)",
" /sessions list saved sessions (current is marked with ▸)",
" /forget delete the current session from disk",
" /new start fresh: drop all context + clear scrollback",
" /clear clear displayed scrollback only (context kept — model still sees it)",
" /exit quit",
"",
"Shell shortcut:",
" !<cmd> run <cmd> in the sandbox root; output goes into",
" the conversation so the model sees it next turn.",
" No allowlist gate — user-typed = explicit consent.",
" Example: !git status !ls src/ !npm test",
"",
"File references (code mode):",
" @path/to/file inline file content under [Referenced files] on send.",
" Type `@` to open the picker (↑↓ navigate, Tab/Enter pick).",
"",
"Presets (branch + harvest are NEVER auto-enabled — opt-in only):",
" fast v4-flash · effort=high cheapest · quick Q&A, one-line edits",
" smart v4-flash · effort=max ← default · day-to-day coding",
" max v4-pro · effort=max ~12× fast · hard single-shots",
"",
"Sessions (auto-enabled by default, named 'default'):",
" reasonix chat --session <name> use a different named session",
" reasonix chat --no-session disable persistence for this run",
"",
"Known limitation:",
" Resizing the terminal mid-session may stack ghost header frames in",
" scrollback (Ink library's live-region clear doesn't account for line",
" re-wrapping at the new width). Scroll-up history is unaffected; the",
" artifact is purely visual and clears the next time you /clear.",
].join("\n"),
});
const setup: SlashHandler = () => ({
info:
"To reconfigure (preset, MCP servers, API key), exit this chat and run " +
"`reasonix setup`. Changes take effect on next launch.",
});
const retry: SlashHandler = (_args, loop) => {
const prev = loop.retryLastUser();
if (!prev) {
return {
info: "nothing to retry — no prior user message in this session's log.",
};
}
const preview = prev.length > 80 ? `${prev.slice(0, 80)}…` : prev;
return {
info: `▸ retrying: "${preview}"`,
resubmit: prev,
};
};
export const handlers: Record<string, SlashHandler> = {
exit,
quit: exit,
clear,
new: resetLog,
reset: resetLog,
keys,
help,
"?": help,
setup,
retry,
};
+142
View File
@@ -0,0 +1,142 @@
import type { EditMode } from "../../../../config.js";
import type { SlashHandler } from "../dispatch.js";
import { runGitCommit, stripOuterQuotes } from "../helpers.js";
const undo: SlashHandler = (args, _loop, ctx) => {
if (!ctx.codeUndo) {
return {
info: "/undo is only available inside `reasonix code` — chat mode doesn't apply edits.",
};
}
return { info: ctx.codeUndo(args) };
};
const history: SlashHandler = (_args, _loop, ctx) => {
if (!ctx.codeHistory) {
return { info: "/history is only available inside `reasonix code`." };
}
return { info: ctx.codeHistory() };
};
const show: SlashHandler = (args, _loop, ctx) => {
if (!ctx.codeShowEdit) {
return { info: "/show is only available inside `reasonix code`." };
}
return { info: ctx.codeShowEdit(args) };
};
const apply: SlashHandler = (_args, _loop, ctx) => {
if (!ctx.codeApply) {
return {
info: "/apply is only available inside `reasonix code` (nothing to apply here).",
};
}
return { info: ctx.codeApply() };
};
const discard: SlashHandler = (_args, _loop, ctx) => {
if (!ctx.codeDiscard) {
return {
info: "/discard is only available inside `reasonix code`.",
};
}
return { info: ctx.codeDiscard() };
};
const plan: SlashHandler = (args, _loop, ctx) => {
if (!ctx.setPlanMode) {
return {
info: "/plan is only available inside `reasonix code` — chat mode doesn't gate tool writes.",
};
}
const currentOn = Boolean(ctx.planMode);
const raw = (args[0] ?? "").toLowerCase();
let target: boolean;
if (raw === "on" || raw === "true" || raw === "1") target = true;
else if (raw === "off" || raw === "false" || raw === "0") target = false;
else target = !currentOn;
ctx.setPlanMode(target);
if (target) {
return {
info: "▸ plan mode ON — write tools are gated; the model MUST call `submit_plan` before anything executes. (The model can also call submit_plan on its own for big tasks even when plan mode is off — this toggle is the stronger, explicit constraint.) Type /plan off to leave.",
};
}
return {
info: "▸ plan mode OFF — write tools are live again. Model can still propose plans autonomously for large tasks.",
};
};
const applyPlan: SlashHandler = (_args, _loop, ctx) => {
if (!ctx.setPlanMode) {
return {
info: "/apply-plan is only available inside `reasonix code`.",
};
}
ctx.setPlanMode(false);
ctx.clearPendingPlan?.();
return {
info: "▸ plan approved — implementing",
resubmit:
"The plan above has been approved. Implement it now. You are out of plan mode — use edit_file / write_file / run_command as needed. Stick to the plan unless you discover a concrete reason to deviate; if you do, tell me and wait for a response before making that deviation.",
};
};
const mode: SlashHandler = (args, _loop, ctx) => {
if (!ctx.setEditMode) {
return {
info: "/mode is only available inside `reasonix code`.",
};
}
const raw = (args[0] ?? "").toLowerCase();
const current = ctx.editMode ?? "review";
let target: EditMode;
if (raw === "review") target = "review";
else if (raw === "auto") target = "auto";
else if (raw === "") {
// Bare /mode toggles, mirroring Shift+Tab. Users who just want to
// see current mode without flipping can read /status.
target = current === "auto" ? "review" : "auto";
} else {
return { info: "usage: /mode <review|auto> (Shift+Tab also cycles)" };
}
ctx.setEditMode(target);
return {
info:
target === "auto"
? "▸ edit mode: AUTO — edits apply immediately; press u within 5s to undo, or /undo later"
: "▸ edit mode: review — edits queue for /apply (or y) / /discard (or n)",
};
};
const commit: SlashHandler = (args, _loop, ctx) => {
if (!ctx.codeRoot) {
return {
info: "/commit is only available inside `reasonix code` (needs a rooted git repo).",
};
}
// Reassemble the original argv. The parser lowercases cmd but leaves
// args alone, and the TUI splits on whitespace which mangles quoted
// messages — rejoin with spaces and strip a surrounding pair of
// double quotes if the user wrote them.
const raw = args.join(" ").trim();
const message = stripOuterQuotes(raw);
if (!message) {
return {
info: `usage: /commit "your commit message" — runs \`git add -A && git commit -m "…"\` in ${ctx.codeRoot}`,
};
}
return runGitCommit(ctx.codeRoot, message);
};
export const handlers: Record<string, SlashHandler> = {
undo,
history,
show,
apply,
discard,
plan,
"apply-plan": applyPlan,
applyplan: applyPlan,
mode,
commit,
};
+84
View File
@@ -0,0 +1,84 @@
import type { SlashHandler } from "../dispatch.js";
const jobs: SlashHandler = (_args, _loop, ctx) => {
if (!ctx.jobs) {
return { info: "/jobs is only available inside `reasonix code`." };
}
const rows = ctx.jobs.list();
if (rows.length === 0) {
return { info: "no background jobs yet — use run_background to start one" };
}
const lines = ["Background jobs:"];
for (const r of rows) {
const age = ((Date.now() - r.startedAt) / 1000).toFixed(1);
const state = r.running
? `running · pid ${r.pid ?? "?"}`
: r.exitCode !== null
? `exit ${r.exitCode}`
: r.spawnError
? "failed"
: "stopped";
lines.push(
` ${String(r.id).padStart(3)} ${state.padEnd(20)} ${age.padStart(6)}s ago $ ${r.command}`,
);
}
lines.push("");
lines.push("/kill <id> to stop one · /logs <id> [lines] to tail output");
return { info: lines.join("\n") };
};
const kill: SlashHandler = (args, _loop, ctx) => {
if (!ctx.jobs) return { info: "/kill is only available inside `reasonix code`." };
const id = Number.parseInt(args[0] ?? "", 10);
if (!Number.isFinite(id)) return { info: "usage: /kill <id> (see /jobs for ids)" };
const rec = ctx.jobs.list().find((r) => r.id === id);
if (!rec) return { info: `job ${id}: not found` };
if (!rec.running) return { info: `job ${id} already exited (${rec.exitCode ?? "?"})` };
// Fire-and-forget: the registry waits for grace + SIGKILL internally;
// returning immediately keeps the slash synchronous so the user's
// prompt doesn't lock up for 2s on every /kill. The postInfo
// callback lands a follow-up row in historical when the kill
// actually completes, so the user sees "job N stopped" without
// polling /jobs.
const jobsRef = ctx.jobs;
void (async () => {
const final = await jobsRef.stop(id);
if (!final) return;
const status = final.running
? "still alive after SIGKILL (!) — report this as a bug"
: final.exitCode !== null
? `exit ${final.exitCode}`
: "stopped";
ctx.postInfo?.(`▸ job ${id} ${status}`);
})();
return {
info: `▸ stopping job ${id} (tree kill: SIGTERM → SIGKILL after 2s grace; Windows: taskkill /T /F)`,
};
};
const logs: SlashHandler = (args, _loop, ctx) => {
if (!ctx.jobs) return { info: "/logs is only available inside `reasonix code`." };
const id = Number.parseInt(args[0] ?? "", 10);
if (!Number.isFinite(id)) {
return { info: "usage: /logs <id> [lines] (default last 80 lines)" };
}
const requested = Number.parseInt(args[1] ?? "", 10);
const tail = Number.isFinite(requested) && requested > 0 ? requested : 80;
const out = ctx.jobs.read(id, { tailLines: tail });
if (!out) return { info: `job ${id}: not found` };
const status = out.running
? `running · pid ${out.pid ?? "?"}`
: out.exitCode !== null
? `exited ${out.exitCode}`
: out.spawnError
? `failed (${out.spawnError})`
: "stopped";
const header = `[job ${id} · ${status}]\n$ ${out.command}`;
return { info: out.output ? `${header}\n${out.output}` : header };
};
export const handlers: Record<string, SlashHandler> = {
jobs,
kill,
logs,
};
+64
View File
@@ -0,0 +1,64 @@
import type { SlashHandler } from "../dispatch.js";
import { appendSection } from "../helpers.js";
const mcp: SlashHandler = (_args, loop, ctx) => {
const servers = ctx.mcpServers ?? [];
const specs = ctx.mcpSpecs ?? [];
const toolSpecs = loop.prefix.toolSpecs ?? [];
if (servers.length === 0 && specs.length === 0 && toolSpecs.length === 0) {
return {
info:
"no MCP servers attached. Run `reasonix setup` to pick some, " +
'or launch with --mcp "<spec>". `reasonix mcp list` shows the catalog.',
};
}
// Rich path — we have full inspection reports, so show each server
// with its tools / resources / prompts grouped together.
if (servers.length > 0) {
const lines: string[] = [];
let anyResources = false;
let anyPrompts = false;
for (const s of servers) {
const { report } = s;
const serverName = report.serverInfo.name || "(unknown)";
const serverVer = report.serverInfo.version ? ` v${report.serverInfo.version}` : "";
lines.push(`[${s.label}] ${serverName}${serverVer} — ${s.spec}`);
lines.push(` tools ${s.toolCount}`);
appendSection(lines, "resources", report.resources);
appendSection(lines, "prompts ", report.prompts);
if (report.resources.supported && report.resources.items.length > 0) anyResources = true;
if (report.prompts.supported && report.prompts.items.length > 0) anyPrompts = true;
lines.push("");
}
if (anyResources || anyPrompts) {
const hints: string[] = [];
if (anyResources) hints.push("`/resource` to browse+read");
if (anyPrompts) hints.push("`/prompt` to browse+fetch");
lines.push(hints.join(" · "));
} else {
lines.push(
"Chat mode consumes tools today; resources+prompts are surfaced here for awareness.",
);
}
lines.push(
"Full catalog: `reasonix mcp list` · deeper diagnosis: `reasonix mcp inspect <spec>`.",
);
return { info: lines.join("\n") };
}
// Fallback — older path when the TUI hasn't populated `mcpServers`.
const lines: string[] = [];
if (specs.length > 0) {
lines.push(`MCP servers (${specs.length}):`);
for (const spec of specs) lines.push(` · ${spec}`);
lines.push("");
}
if (toolSpecs.length > 0) {
lines.push(`Tools in registry (${toolSpecs.length}):`);
for (const t of toolSpecs) lines.push(` · ${t.function.name}`);
}
lines.push("");
lines.push("To change this set, exit and run `reasonix setup`.");
return { info: lines.join("\n") };
};
export const handlers: Record<string, SlashHandler> = { mcp };
+169
View File
@@ -0,0 +1,169 @@
import {
PROJECT_MEMORY_FILE,
memoryEnabled,
readProjectMemory,
} from "../../../../project-memory.js";
import { type MemoryScope, MemoryStore } from "../../../../user-memory.js";
import type { SlashHandler } from "../dispatch.js";
import { resolveMemoryTarget } from "../helpers.js";
/**
* `/memory` family. Bare `/memory` shows what's pinned (REASONIX.md +
* both MEMORY.md blocks). Subcommands manage the user-memory store:
* list — every memory file, both scopes
* show <name> — dump one file's body
* show <scope>/<name> — disambiguate when name exists in both scopes
* forget <name> — delete (same scope resolution as show)
* clear <scope> confirm — wipe a scope (typed literal "confirm" required)
*/
const memory: SlashHandler = (args, _loop, ctx) => {
if (!memoryEnabled()) {
return {
info: "memory is disabled (REASONIX_MEMORY=off in env). Unset the var to re-enable — no REASONIX.md or ~/.reasonix/memory content will be pinned in the meantime.",
};
}
if (!ctx.memoryRoot) {
return {
info: "no working directory on this session — `/memory` needs a root to resolve REASONIX.md from. (Running in a test harness?)",
};
}
// `codeRoot` is set only when running `reasonix code`. Chat mode has
// `memoryRoot` = cwd (for REASONIX.md), but we don't treat cwd as a
// sandbox — project-scope user memory requires a real code-mode root.
const store = new MemoryStore({ projectRoot: ctx.codeRoot });
const sub = (args[0] ?? "").toLowerCase();
if (sub === "list" || sub === "ls") {
const entries = store.list();
if (entries.length === 0) {
return {
info: "no user memories yet. The model can call `remember` to save one, or you can create files by hand in ~/.reasonix/memory/global/ or the per-project subdir.",
};
}
const lines = [`User memories (${entries.length}):`];
for (const e of entries) {
const tag = `${e.scope}/${e.type}`.padEnd(18);
const name = e.name.padEnd(28);
const desc = e.description.length > 70 ? `${e.description.slice(0, 69)}…` : e.description;
lines.push(` ${tag} ${name} ${desc}`);
}
lines.push("");
lines.push("View body: /memory show <name> Delete: /memory forget <name>");
return { info: lines.join("\n") };
}
if (sub === "show" || sub === "cat") {
const target = args[1];
if (!target) return { info: "usage: /memory show <name> or /memory show <scope>/<name>" };
const resolved = resolveMemoryTarget(store, target);
if (!resolved) return { info: `no memory found: ${target}` };
try {
const entry = store.read(resolved.scope, resolved.name);
return {
info: [
`▸ ${entry.scope}/${entry.name} (${entry.type}, created ${entry.createdAt || "?"})`,
entry.description ? ` ${entry.description}` : "",
"",
entry.body,
]
.filter((l) => l !== "")
.concat("")
.join("\n"),
};
} catch (err) {
return { info: `show failed: ${(err as Error).message}` };
}
}
if (sub === "forget" || sub === "rm" || sub === "delete") {
const target = args[1];
if (!target) return { info: "usage: /memory forget <name> or /memory forget <scope>/<name>" };
const resolved = resolveMemoryTarget(store, target);
if (!resolved) return { info: `no memory found: ${target}` };
try {
const ok = store.delete(resolved.scope, resolved.name);
return {
info: ok
? `▸ forgot ${resolved.scope}/${resolved.name}. Next /new or launch won't see it.`
: `could not forget ${resolved.scope}/${resolved.name} (already gone?)`,
};
} catch (err) {
return { info: `forget failed: ${(err as Error).message}` };
}
}
if (sub === "clear") {
const rawScope = (args[1] ?? "").toLowerCase();
if (rawScope !== "global" && rawScope !== "project") {
return { info: "usage: /memory clear <global|project> confirm" };
}
if ((args[2] ?? "").toLowerCase() !== "confirm") {
return {
info: `about to delete every memory in scope=${rawScope}. Re-run with the word 'confirm' to proceed: /memory clear ${rawScope} confirm`,
};
}
const scope = rawScope as MemoryScope;
const entries = store.list().filter((e) => e.scope === scope);
let deleted = 0;
for (const e of entries) {
try {
if (store.delete(scope, e.name)) deleted++;
} catch {
/* skip */
}
}
return { info: `▸ cleared scope=${scope} — deleted ${deleted} memory file(s).` };
}
// Bare `/memory` — show REASONIX.md + both MEMORY.md blocks.
const parts: string[] = [];
const projMem = readProjectMemory(ctx.memoryRoot);
if (projMem) {
const hdr = projMem.truncated
? `▸ ${PROJECT_MEMORY_FILE}: ${projMem.path} (${projMem.originalChars.toLocaleString()} chars, truncated)`
: `▸ ${PROJECT_MEMORY_FILE}: ${projMem.path} (${projMem.originalChars.toLocaleString()} chars)`;
parts.push(hdr, "", projMem.content);
}
const globalIdx = store.loadIndex("global");
if (globalIdx) {
parts.push(
"",
`▸ global memory (${globalIdx.originalChars.toLocaleString()} chars${globalIdx.truncated ? ", truncated" : ""})`,
"",
globalIdx.content,
);
}
const projectIdx = store.loadIndex("project");
if (projectIdx) {
parts.push(
"",
`▸ project memory (${projectIdx.originalChars.toLocaleString()} chars${projectIdx.truncated ? ", truncated" : ""})`,
"",
projectIdx.content,
);
}
if (parts.length === 0) {
return {
info: [
`no memory pinned in ${ctx.memoryRoot}.`,
"",
"Three layers are available:",
` 1. ${PROJECT_MEMORY_FILE} — committable team memory (in the repo).`,
" 2. ~/.reasonix/memory/global/ — your cross-project private memory.",
` 3. ~/.reasonix/memory/<project-hash>/ — this project's private memory.`,
"",
"Ask the model to `remember` something, or hand-edit files directly.",
"Changes take effect on next /new or launch — the system prompt is hashed once per session to keep the prefix cache warm.",
"",
"Subcommands: /memory list | /memory show <name> | /memory forget <name> | /memory clear <scope> confirm",
].join("\n"),
};
}
parts.push(
"",
"Changes take effect on next /new or launch. Subcommands: /memory list | show | forget | clear",
);
return { info: parts.join("\n") };
};
export const handlers: Record<string, SlashHandler> = { memory };
+187
View File
@@ -0,0 +1,187 @@
import { saveReasoningEffort } from "../../../../config.js";
import type { SlashHandler } from "../dispatch.js";
const model: SlashHandler = (args, loop, ctx) => {
const id = args[0];
const known = ctx.models ?? null;
if (!id) {
const hint =
known && known.length > 0
? known.join(" | ")
: "try deepseek-v4-flash or deepseek-v4-pro — run /models to fetch the live list";
return { info: `usage: /model <id> (${hint})` };
}
loop.configure({ model: id });
// Soft validation: if we have the live list and the id isn't in
// it, flag a warning but still switch — DeepSeek may have just
// released something we haven't indexed yet, and refusing would
// be worse than a bad API error on the next call.
if (known && known.length > 0 && !known.includes(id)) {
return {
info: `model → ${id} (⚠ not in the fetched catalog: ${known.join(", ")}. If this is wrong the next call will 400 — run /models to refresh.)`,
};
}
return { info: `model → ${id}` };
};
const models: SlashHandler = (_args, loop, ctx) => {
const list = ctx.models ?? null;
if (list === null) {
ctx.refreshModels?.();
return {
info: "fetching /models from DeepSeek… run /models again in a moment. If it stays empty, your API key may lack permission or the network is blocked.",
};
}
if (list.length === 0) {
return {
info: "DeepSeek /models returned an empty list. Try /models again, or check your account status at api-docs.deepseek.com.",
};
}
const current = loop.model;
const lines = list.map((id) => (id === current ? `▸ ${id} (current)` : ` ${id}`));
return {
info: [
`Available models (DeepSeek /models · ${list.length} total):`,
"",
...lines,
"",
"Switch with: /model <id>",
].join("\n"),
};
};
const harvest: SlashHandler = (args, loop) => {
const arg = (args[0] ?? "").toLowerCase();
const on = arg === "" ? !loop.harvestEnabled : arg === "on" || arg === "true" || arg === "1";
loop.configure({ harvest: on });
if (loop.harvestEnabled) {
return {
info: "harvest → on (Pillar-2 plan-state extraction · +1 cheap flash call per turn · opt-in only; no preset turns it on)",
};
}
return { info: "harvest → off" };
};
const preset: SlashHandler = (args, loop) => {
const name = (args[0] ?? "").toLowerCase();
// Persist the effort along with the preset change so a relaunch
// doesn't revert to the previously-saved /effort value.
const applyAndPersist = (effort: "high" | "max") => {
try {
saveReasoningEffort(effort);
} catch {
/* disk full / perms — runtime change still took effect */
}
};
if (name === "fast" || name === "default") {
loop.configure({
model: "deepseek-v4-flash",
reasoningEffort: "high",
harvest: false,
branch: 1,
});
applyAndPersist("high");
return { info: "preset → fast (v4-flash · effort=high · cheapest)" };
}
if (name === "smart") {
loop.configure({
model: "deepseek-v4-flash",
reasoningEffort: "max",
harvest: false,
branch: 1,
});
applyAndPersist("max");
return { info: "preset → smart (v4-flash · effort=max · default · ~1.5× fast)" };
}
if (name === "max" || name === "best") {
loop.configure({
model: "deepseek-v4-pro",
reasoningEffort: "max",
harvest: false,
branch: 1,
});
applyAndPersist("max");
return {
info: "preset → max (v4-pro · effort=max · ~12× fast · save for hard tasks, or use /pro for a single-turn bump)",
};
}
return { info: "usage: /preset <fast|smart|max>" };
};
const branch: SlashHandler = (args, loop) => {
const raw = (args[0] ?? "").toLowerCase();
if (raw === "" || raw === "off" || raw === "0" || raw === "1") {
loop.configure({ branch: 1 });
return { info: "branch → off" };
}
const n = Number.parseInt(raw, 10);
if (!Number.isFinite(n) || n < 2) {
return { info: "usage: /branch <N> (N>=2, or 'off')" };
}
if (n > 8) {
return { info: "branch budget capped at 8 to prevent runaway cost" };
}
loop.configure({ branch: n });
return {
info: `branch → ${n} (runs ${n} parallel samples per turn · ${n}× per-turn cost · streaming disabled · manual only, no preset enables branching)`,
};
};
const effort: SlashHandler = (args, loop) => {
const raw = (args[0] ?? "").toLowerCase();
if (raw === "") {
return {
info: `reasoning_effort → ${loop.reasoningEffort} (use /effort high for cheaper/faster, /effort max for the agent-class default · persisted across relaunches)`,
};
}
if (raw !== "high" && raw !== "max") {
return { info: "usage: /effort <high|max>" };
}
loop.configure({ reasoningEffort: raw });
// Persist so the next launch starts with this value instead of
// reverting to the constructor default.
try {
saveReasoningEffort(raw);
} catch {
/* disk full / perms — runtime change still took effect */
}
return { info: `reasoning_effort → ${raw} (persisted)` };
};
const pro: SlashHandler = (args, loop, ctx) => {
const arg = (args[0] ?? "").toLowerCase();
if (arg === "off" || arg === "cancel" || arg === "disarm") {
if (!loop.proArmed) {
return { info: "nothing armed — /pro with no args will arm pro for your next turn" };
}
if (ctx.disarmPro) ctx.disarmPro();
else loop.disarmPro();
return { info: "▸ /pro disarmed — next turn falls back to the current preset" };
}
if (arg && arg !== "on" && arg !== "arm") {
return {
info: "usage: /pro arm pro for the next turn (one-shot, auto-disarms after)\n /pro off cancel armed state before the next turn",
};
}
if (ctx.armPro) ctx.armPro();
else loop.armProForNextTurn();
return {
info: `▸ /pro armed — your NEXT message runs on ${ESCALATION_MODEL_ID} regardless of preset. Auto-disarms after one turn. Use /preset max for a persistent switch.`,
};
};
// Kept in sync with loop.ts ESCALATION_MODEL — hard-coding rather than
// importing it because loop.ts already exports enough surface, and this
// string is user-facing (description strings stay verbatim even if the
// internal constant renames).
const ESCALATION_MODEL_ID = "deepseek-v4-pro";
export const handlers: Record<string, SlashHandler> = {
model,
models,
harvest,
preset,
branch,
effort,
pro,
};
+192
View File
@@ -0,0 +1,192 @@
import { DEEPSEEK_CONTEXT_TOKENS, DEFAULT_CONTEXT_TOKENS } from "../../../../telemetry.js";
import { countTokens } from "../../../../tokenizer.js";
import type { SlashHandler } from "../dispatch.js";
import { compactNum, formatToolList } from "../helpers.js";
const think: SlashHandler = (_args, loop) => {
const raw = loop.scratch.reasoning;
if (!raw || !raw.trim()) {
return {
info:
"no reasoning cached. `/think` shows the full thinking-mode thought for the most recent " +
"turn — only thinking-mode models (deepseek-v4-flash / -v4-pro / -reasoner) produce it, " +
"and only once the turn completes.",
};
}
return { info: `↳ full thinking (${raw.length} chars):\n\n${raw.trim()}` };
};
const tool: SlashHandler = (args, _loop, ctx) => {
// EventLog renders tool results as a one-line summary for display.
// When the user wants to check what the model actually read (e.g.
// to verify it isn't hallucinating a file's contents), they need
// the full text. `/tool` is the escape hatch.
const history = ctx.toolHistory?.() ?? [];
if (history.length === 0) {
return {
info:
"no tool calls yet in this session. `/tool` lists them once the model has actually " +
"used a tool; `/tool N` dumps the full (untruncated) output of the Nth-most-recent.",
};
}
const raw = (args[0] ?? "").toLowerCase();
if (raw === "" || raw === "list" || raw === "ls") {
return { info: formatToolList(history) };
}
const n = Number.parseInt(raw, 10);
if (!Number.isFinite(n) || n < 1) {
return {
info: "usage: /tool [N] (no arg → list; N=1 → most recent result in full, N=2 → previous, …)",
};
}
if (n > history.length) {
return {
info: `only ${history.length} tool call(s) in history — asked for #${n}. Try /tool with no arg to see the list.`,
};
}
const entry = history[history.length - n];
if (!entry) {
return { info: `could not read tool call #${n}` };
}
return {
info: `↳ tool<${entry.toolName}> #${n} (${entry.text.length} chars):\n\n${entry.text}`,
};
};
const context: SlashHandler = (_args, loop) => {
// Measure each slice of the next request locally so the user can see
// *where* context is being spent — a much more useful number than
// the "last turn's total" the gauge shows. Tokenization is lazy so
// the first /context call carries the data-file load cost (~100ms);
// subsequent calls are pure compute.
const systemTokens = countTokens(loop.prefix.system);
const toolsTokens = countTokens(JSON.stringify(loop.prefix.toolSpecs));
const entries = loop.log.toMessages();
let userTokens = 0;
let assistantTokens = 0;
let toolResultTokens = 0;
let toolCallTokens = 0;
const toolBreakdown: Array<{ name: string; tokens: number; turn: number }> = [];
let logTurn = 0;
for (const e of entries) {
const content = typeof e.content === "string" ? e.content : "";
if (e.role === "user") {
userTokens += countTokens(content);
logTurn += 1;
} else if (e.role === "assistant") {
assistantTokens += countTokens(content);
if (Array.isArray(e.tool_calls) && e.tool_calls.length > 0) {
toolCallTokens += countTokens(JSON.stringify(e.tool_calls));
}
} else if (e.role === "tool") {
const n = countTokens(content);
toolResultTokens += n;
toolBreakdown.push({ name: e.name ?? "?", tokens: n, turn: logTurn });
}
}
const logTokens = userTokens + assistantTokens + toolResultTokens + toolCallTokens;
const total = systemTokens + toolsTokens + logTokens;
const ctxMax = DEEPSEEK_CONTEXT_TOKENS[loop.model] ?? DEFAULT_CONTEXT_TOKENS;
const pct = (n: number) => (total > 0 ? `${Math.round((n / total) * 100)}%`.padStart(4) : " 0%");
const row = (label: string, n: number, note = "") =>
` ${label.padEnd(20)}${compactNum(n).padStart(8)} tokens ${pct(n)}${note ? ` ${note}` : ""}`;
const lines = [
`Next-request estimate: ~${compactNum(total)} tokens of ${compactNum(ctxMax)} (${Math.round(
(total / ctxMax) * 100,
)}% of window)`,
"",
row("system prompt", systemTokens),
row("tool specs", toolsTokens, `(${loop.prefix.toolSpecs.length} tools)`),
row("log (all turns)", logTokens, `(${entries.length} messages)`),
` user ${compactNum(userTokens).padStart(8)} tokens`,
` assistant ${compactNum(assistantTokens).padStart(8)} tokens`,
` tool-call args ${compactNum(toolCallTokens).padStart(8)} tokens`,
` tool results ${compactNum(toolResultTokens).padStart(8)} tokens`,
];
// Top 5 heaviest tool results — usually where unexpected bloat
// lives (a big read_file, an unfiltered search_content).
if (toolBreakdown.length > 0) {
const top = [...toolBreakdown].sort((a, b) => b.tokens - a.tokens).slice(0, 5);
lines.push("");
lines.push(`Top tool results by cost (of ${toolBreakdown.length} total):`);
for (const t of top) {
lines.push(
` turn ${String(t.turn).padStart(3)} ${t.name.padEnd(22)} ${compactNum(t.tokens).padStart(8)} tokens`,
);
}
}
lines.push("");
lines.push(
"Count is a local estimate (DeepSeek V3 tokenizer, pure-TS port); server prompt_tokens may add ~3-6% for chat-template role markers.",
);
return { info: lines.join("\n") };
};
const status: SlashHandler = (_args, loop, ctx) => {
const branchBudget = loop.branchOptions.budget ?? 1;
const ctxMax = DEEPSEEK_CONTEXT_TOKENS[loop.model] ?? DEFAULT_CONTEXT_TOKENS;
const lastPromptTokens = loop.stats.summary().lastPromptTokens;
const ctxPct = ctxMax > 0 ? Math.round((lastPromptTokens / ctxMax) * 100) : 0;
const ctxLine =
lastPromptTokens > 0
? ` ctx ${compactNum(lastPromptTokens)}/${compactNum(ctxMax)} (${ctxPct}%)`
: " ctx no turns yet";
const pending = ctx.pendingEditCount ?? 0;
const sessionLine = loop.sessionName
? ` session "${loop.sessionName}" · ${loop.log.length} messages in log (resumed ${loop.resumedMessageCount})`
: " session (ephemeral — no persistence)";
const mcpCount = ctx.mcpSpecs?.length ?? 0;
const toolCount = loop.prefix.toolSpecs.length;
const mcpLine = ` mcp ${mcpCount} server(s), ${toolCount} tool(s) in registry`;
const pendingLine =
pending > 0 ? ` edits ${pending} pending (/apply to commit, /discard to drop)` : "";
const planLine = ctx.planMode ? " plan ON — writes gated (submit_plan + approval)" : "";
const modeLine =
ctx.editMode === "auto"
? " mode AUTO — edits apply immediately (u to undo within 5s · Shift+Tab to flip)"
: ctx.editMode === "review"
? " mode review — edits queue for /apply or y (Shift+Tab to flip)"
: "";
const lines = [
` model ${loop.model}`,
` flags harvest=${loop.harvestEnabled ? "on" : "off"} · branch=${branchBudget > 1 ? branchBudget : "off"} · stream=${loop.stream ? "on" : "off"} · effort=${loop.reasoningEffort}`,
ctxLine,
mcpLine,
sessionLine,
];
if (pendingLine) lines.push(pendingLine);
if (planLine) lines.push(planLine);
if (modeLine) lines.push(modeLine);
return { info: lines.join("\n") };
};
const compact: SlashHandler = (args, loop) => {
// Manual companion to the automatic 60%/80% auto-compact. Re-applies
// token-aware truncation with a tighter cap (default 4000 tokens per
// tool result) and rewrites the session file so the shrink persists.
// Useful when the ctx gauge in StatsPanel goes yellow/red mid-session
// and the user wants to keep chatting without /forget'ing everything.
const tight = Number.parseInt(args[0] ?? "", 10);
const cap = Number.isFinite(tight) && tight >= 100 ? tight : 4000;
const { healedCount, tokensSaved, charsSaved } = loop.compact(cap);
if (healedCount === 0) {
return {
info: `▸ nothing to compact — no tool result or tool-call args in history exceed ${cap.toLocaleString()} tokens.`,
};
}
return {
info: `▸ compacted ${healedCount} payload(s) to ${cap.toLocaleString()} tokens each (tool results + tool-call args), saved ${tokensSaved.toLocaleString()} tokens (${charsSaved.toLocaleString()} chars). Session file rewritten.`,
};
};
export const handlers: Record<string, SlashHandler> = {
think,
reasoning: think,
tool,
context,
status,
compact,
};
+111
View File
@@ -0,0 +1,111 @@
/**
* `/plans` — show this session's plan history. Both the live in-flight
* plan (if any) and the archive of completed `.done.json` files. Local
* to the current session by design — a plan lives with its project,
* and resuming one just means cd'ing back to that project directory.
*/
import { basename } from "node:path";
import { listPlanArchives, loadPlanState, relativeTime } from "../../../../code/plan-store.js";
import type { SlashHandler } from "../dispatch.js";
const plans: SlashHandler = (_args, loop) => {
const sessionName = loop.sessionName;
if (!sessionName) {
return {
info: "no session attached — `/plans` is per-session. Run `reasonix code` in a project to get a session.",
};
}
const lines: string[] = [];
// Active (in-flight) plan summary first — it's the one the user is
// most likely asking about.
const active = loadPlanState(sessionName);
if (active && active.steps.length > 0) {
const total = active.steps.length;
const done = active.completedStepIds.length;
const when = relativeTime(active.updatedAt);
const label = active.summary ? `: ${active.summary}` : "";
lines.push(
`▸ active plan${label} — ${done}/${total} step${total === 1 ? "" : "s"} done · last touched ${when}`,
);
} else {
lines.push("▸ active plan: (none)");
}
// Archives (completed plans) — newest first.
const archives = listPlanArchives(sessionName);
if (archives.length === 0) {
lines.push("");
lines.push(
"no archived plans yet for this session — they auto-archive when every step is done",
);
return { info: lines.join("\n") };
}
lines.push("");
lines.push(`Archived (${archives.length}):`);
for (const a of archives) {
const when = relativeTime(a.completedAt);
const total = a.steps.length;
const done = a.completedStepIds.length;
const completion = done >= total ? "complete" : `${done}/${total}`;
// Prefer the model-supplied summary as the label; fall back to
// the bare filename so legacy archives without a summary still
// show something identifying.
const label = a.summary ?? a.path.split(/[\\/]/).pop() ?? a.path;
lines.push(
` ✓ ${when.padEnd(10)} ${total} step${total === 1 ? "" : "s"} · ${completion} ${label}`,
);
}
return { info: lines.join("\n") };
};
/**
* `/replay [N]` — Time Travel. Loads archive #N (1-based, newest
* first; defaults to 1) and asks the TUI to render it as a read-only
* snapshot. Pure display — no execution, no plan state changes.
*
* The structured payload (steps + completedStepIds + body + summary)
* goes back through SlashResult.replayPlan so EventLog can apply the
* same step-list rendering used elsewhere, complete with risk gutter
* and ✓ status.
*/
const replay: SlashHandler = (args, loop) => {
const sessionName = loop.sessionName;
if (!sessionName) {
return {
info: "no session attached — `/replay` is per-session. Run `reasonix code` in a project to get a session.",
};
}
const archives = listPlanArchives(sessionName);
if (archives.length === 0) {
return {
info: "no archived plans yet for this session — `/replay` lights up once a plan completes (auto-archives when every step is done).",
};
}
const arg = args[0]?.trim() ?? "";
const index = arg ? Number.parseInt(arg, 10) : 1;
if (!Number.isFinite(index) || index < 1 || index > archives.length) {
return {
info: `invalid index — \`/replay\` takes 1..${archives.length} (newest = 1). Use \`/plans\` to see the list.`,
};
}
const a = archives[index - 1]!;
return {
replayPlan: {
summary: a.summary,
body: a.body,
steps: a.steps,
completedStepIds: a.completedStepIds,
completedAt: a.completedAt,
relativeTime: relativeTime(a.completedAt),
archiveBasename: basename(a.path),
index,
total: archives.length,
},
};
};
export const handlers: Record<string, SlashHandler> = {
plans,
replay,
};
+41
View File
@@ -0,0 +1,41 @@
import { deleteSession, listSessions } from "../../../../session.js";
import type { SlashHandler } from "../dispatch.js";
const sessions: SlashHandler = (_args, loop) => {
const items = listSessions();
if (items.length === 0) {
return {
info: "no saved sessions yet — chat normally and your messages will be saved automatically",
};
}
const lines = ["Saved sessions:"];
for (const s of items) {
const sizeKb = (s.size / 1024).toFixed(1);
const when = s.mtime.toISOString().replace("T", " ").slice(0, 16);
const marker = s.name === loop.sessionName ? "▸" : " ";
lines.push(
` ${marker} ${s.name.padEnd(22)} ${String(s.messageCount).padStart(5)} msgs ${sizeKb.padStart(7)} KB ${when}`,
);
}
lines.push("");
lines.push("Resume with: reasonix chat --session <name>");
return { info: lines.join("\n") };
};
const forget: SlashHandler = (_args, loop) => {
if (!loop.sessionName) {
return { info: "not in a session — nothing to forget" };
}
const name = loop.sessionName;
const ok = deleteSession(name);
return {
info: ok
? `▸ deleted session "${name}" — current screen still shows the conversation, but next launch starts fresh`
: `could not delete session "${name}" (already gone?)`,
};
};
export const handlers: Record<string, SlashHandler> = {
sessions,
forget,
};
+94
View File
@@ -0,0 +1,94 @@
import { SkillStore } from "../../../../skills.js";
import type { SlashHandler } from "../dispatch.js";
/**
* `/skill` family. Bare `/skill` (or `/skill list`) prints the
* discovered skills from `<projectRoot>/.reasonix/skills` (code mode
* only) + `~/.reasonix/skills`. `/skill show <name>` dumps one body
* inline for reading. `/skill <name> [args...]` injects the skill body
* as a user turn via `resubmit` — the same mechanism `/apply-plan`
* uses — so the next model turn runs with the skill's instructions
* fresh in the log.
*
* Project scope is only populated when the session has a `codeRoot`
* (set by `reasonix code`). In plain chat mode the store reads the
* global scope only, matching how user-memory behaves.
*/
const skill: SlashHandler = (args, _loop, ctx) => {
const store = new SkillStore({ projectRoot: ctx.codeRoot });
const sub = (args[0] ?? "").toLowerCase();
if (sub === "" || sub === "list" || sub === "ls") {
const skills = store.list();
if (skills.length === 0) {
const lines = ["no skills found. Reasonix reads skills from:"];
if (store.hasProjectScope()) {
lines.push(
" · <project>/.reasonix/skills/<name>/SKILL.md (or <name>.md) — project scope",
);
}
lines.push(" · ~/.reasonix/skills/<name>/SKILL.md (or <name>.md) — global scope");
if (!store.hasProjectScope()) {
lines.push(" (project scope is only active in `reasonix code`)");
}
lines.push(
"",
"Each file's frontmatter needs at least `name` and `description`.",
"Invoke a skill with `/skill <name> [args]` or by asking the model to call `run_skill`.",
);
return { info: lines.join("\n") };
}
const lines = [`User skills (${skills.length}):`];
for (const s of skills) {
const scope = `(${s.scope})`.padEnd(11);
const name = s.name.padEnd(24);
const desc = s.description.length > 70 ? `${s.description.slice(0, 69)}…` : s.description;
lines.push(` ${scope} ${name} ${desc}`);
}
lines.push("");
lines.push("View body: /skill show <name> Run: /skill <name> [args]");
return { info: lines.join("\n") };
}
if (sub === "show" || sub === "cat") {
const target = args[1];
if (!target) return { info: "usage: /skill show <name>" };
const found = store.read(target);
if (!found) return { info: `no skill found: ${target}` };
return {
info: [
`▸ ${found.name} (${found.scope})`,
found.description ? ` ${found.description}` : "",
` ${found.path}`,
"",
found.body,
]
.filter((l) => l !== "")
.join("\n"),
};
}
// Bare `/skill <name> [args...]` — inject the body as a user turn.
// The first arg is the skill name; remaining args are forwarded
// verbatim as the skill's "Arguments:" line.
const name = args[0] ?? "";
const found = store.read(name);
if (!found) {
return {
info: `no skill found: ${name} (try /skill list)`,
};
}
const extra = args.slice(1).join(" ").trim();
const header = `# Skill: ${found.name}${found.description ? `\n> ${found.description}` : ""}`;
const argsLine = extra ? `\n\nArguments: ${extra}` : "";
const payload = `${header}\n\n${found.body}${argsLine}`;
return {
info: `▸ running skill: ${found.name}${extra ? ` — ${extra}` : ""}`,
resubmit: payload,
};
};
export const handlers: Record<string, SlashHandler> = {
skill,
skills: skill,
};
+145
View File
@@ -0,0 +1,145 @@
import { spawnSync } from "node:child_process";
import type { MemoryScope, MemoryStore } from "../../../user-memory.js";
import type { SlashResult } from "./types.js";
/**
* Parse a `/memory show|forget` argument. Accepts bare `<name>` or
* `<scope>/<name>`. For bare names, tries project scope first (more
* specific, usually what the user means) then falls back to global.
*/
export function resolveMemoryTarget(
store: MemoryStore,
raw: string,
): { scope: MemoryScope; name: string } | null {
const slash = raw.indexOf("/");
if (slash > 0) {
const scopeRaw = raw.slice(0, slash).toLowerCase();
const name = raw.slice(slash + 1);
if (scopeRaw !== "global" && scopeRaw !== "project") return null;
const scope = scopeRaw as MemoryScope;
if (scope === "project" && !store.hasProjectScope()) return null;
return { scope, name };
}
for (const scope of ["project", "global"] as MemoryScope[]) {
if (scope === "project" && !store.hasProjectScope()) continue;
try {
store.read(scope, raw);
return { scope, name: raw };
} catch {
/* next scope */
}
}
return null;
}
/**
* Render a section (resources / prompts) of an MCP inspection into a
* compact "name count items" form, collapsing when unsupported.
* Names-only — descriptions and full metadata live in
* `reasonix mcp inspect`, which is purpose-built for the deep view.
*/
export function appendSection(
lines: string[],
label: string,
section:
| { supported: true; items: Array<{ name: string }> }
| { supported: false; reason: string }
| undefined,
): void {
if (!section || !section.supported) {
lines.push(
` ${label.trim()} ${section?.supported === false ? "(not supported)" : "(none)"}`,
);
return;
}
const names = section.items.map((i) => i.name);
if (names.length === 0) {
lines.push(` ${label.trim()} (none)`);
return;
}
const head = names.slice(0, 5).join(", ");
const more = names.length > 5 ? ` +${names.length - 5} more` : "";
lines.push(` ${label.trim()} ${names.length} [${head}${more}]`);
}
export function formatToolList(history: Array<{ toolName: string; text: string }>): string {
const total = history.length;
const header = `Tool calls in this session (${total}, most recent first):`;
// Show the 10 most recent. Older ones are rarely what the user
// wants — and the help footer tells them how to reach any entry
// by index if they do.
const shown = Math.min(total, 10);
const lines: string[] = [header];
for (let i = 0; i < shown; i++) {
const entry = history[total - 1 - i];
if (!entry) continue;
const idx = i + 1; // 1-based from most recent
const flat = entry.text.replace(/\s+/g, " ").trim();
const preview = flat.length > 80 ? `${flat.slice(0, 80)}…` : flat;
const name = entry.toolName.length > 24 ? `${entry.toolName.slice(0, 23)}…` : entry.toolName;
lines.push(
` #${String(idx).padStart(2)} ${name.padEnd(24)} ${String(entry.text.length).padStart(6)} chars ${preview}`,
);
}
if (total > shown) {
lines.push(` … (${total - shown} earlier, reach with /tool N)`);
}
lines.push("");
lines.push("View full output: /tool N (N=1 → most recent)");
return lines.join("\n");
}
/**
* Binary-K token formatter: 1234 → "1.2K", 131072 → "128K". Matches
* DeepSeek's doc ("128K context"). Every call site here is rendering
* token counts — if a future caller wants decimal-K for dollars or
* similar, add a separate formatter rather than reusing this one.
*/
export function compactNum(n: number): string {
if (n < 1024) return String(n);
const k = n / 1024;
return k >= 100 ? `${Math.round(k)}K` : `${k.toFixed(1)}K`;
}
export function stripOuterQuotes(s: string): string {
if (s.length >= 2 && s.startsWith('"') && s.endsWith('"')) {
return s.slice(1, -1);
}
return s;
}
/**
* Run `git add -A` then `git commit -m <message>` in `rootDir`. Returns
* a SlashResult with a human-scannable info line. We surface stderr on
* failure so the user sees exactly what git complained about (bad
* config, pre-commit hook rejection, nothing staged, etc.).
*/
export function runGitCommit(rootDir: string, message: string): SlashResult {
const add = spawnSync("git", ["add", "-A"], { cwd: rootDir, encoding: "utf8" });
if (add.error || add.status !== 0) {
return { info: `git add failed (${add.status ?? "?"}):\n${gitTail(add)}` };
}
const commit = spawnSync("git", ["commit", "-m", message], {
cwd: rootDir,
encoding: "utf8",
});
if (commit.error || commit.status !== 0) {
return { info: `git commit failed (${commit.status ?? "?"}):\n${gitTail(commit)}` };
}
const firstLine = (commit.stdout || "").split(/\r?\n/)[0] ?? "";
return { info: `▸ committed: ${message}${firstLine ? `\n ${firstLine}` : ""}` };
}
/**
* Safely extract whatever diagnostic text is available from a spawnSync
* result — on Windows or when cwd doesn't exist, `stderr`/`stdout` can
* be `undefined` and the caller has only `error.message` to go on.
*/
export function gitTail(res: ReturnType<typeof spawnSync>): string {
const stderr = (res.stderr as string | undefined) ?? "";
const stdout = (res.stdout as string | undefined) ?? "";
const body = stderr.trim() || stdout.trim();
if (body) return body;
if (res.error) return (res.error as Error).message;
return "(no output from git)";
}
+294
View File
@@ -0,0 +1,294 @@
import type { EditMode } from "../../../config.js";
import type { McpClient } from "../../../mcp/client.js";
import type { InspectionReport } from "../../../mcp/inspect.js";
import type { JobRegistry } from "../../../tools/jobs.js";
import type { PlanStep } from "../../../tools/plan.js";
export interface SlashResult {
/** Text to display back to the user as a system/info line. */
info?: string;
/** Exit the app. */
exit?: boolean;
/** Clear the visible history. */
clear?: boolean;
/** Unknown command — display usage hint. */
unknown?: boolean;
/**
* Re-submit this text as a user message after displaying `info`.
* Used by `/retry` — the slash command truncates the log, then
* asks the TUI to push the original text back through the normal
* submit flow so a fresh turn runs.
*/
resubmit?: string;
/**
* Render an archived plan as a read-only "Time Travel" block in
* scrollback. Populated by `/replay [N]`. The TUI mounts it as a
* `plan-replay` DisplayEvent so the same step-list / risk gutter
* styling gets reused. Strictly a display payload — no execution.
*/
replayPlan?: {
summary?: string;
body?: string;
steps: PlanStep[];
completedStepIds: string[];
completedAt: string;
relativeTime: string;
archiveBasename: string;
/** 1-based index in `/plans` listing — surfaced in the header. */
index: number;
/** Total archives at the time of the lookup; helps the user navigate. */
total: number;
};
}
/**
* Extra runtime context a slash handler may care about but that isn't
* already on the loop. Kept as an optional object so tests that only
* need loop-scoped commands can skip it, and callers only populate the
* slots that apply to their session.
*/
export interface SlashContext {
/**
* The exact `--mcp` / config-derived spec strings that were bridged
* into this session (one entry per server). Used by `/mcp`. Empty or
* omitted → no MCP servers attached.
*/
mcpSpecs?: string[];
/**
* Callback for `/undo` — provided by the TUI when it's running in
* code mode. Returns a human-readable report of what was restored.
* Absent outside code mode → `/undo` replies "not available here".
* Accepts slash args: `[id]`, `[id, path]`.
*/
codeUndo?: (args: readonly string[]) => string;
/**
* Callback for `/apply` — commits pending edit blocks to disk. Returns
* a report of what landed. Absent → `/apply` replies "nothing pending"
* or "not available outside code mode".
*/
codeApply?: () => string;
/**
* Callback for `/discard` — drops the pending edit blocks without
* touching disk.
*/
codeDiscard?: () => string;
/**
* Callback for `/history` — returns a human-readable list of every
* edit batch this session, newest last. Includes entry ids (for
* `/show`) and undone status.
*/
codeHistory?: () => string;
/**
* Callback for `/show [id] [path]` — with no args, shows a per-file
* summary of the newest non-undone entry. With id only, the entry's
* per-file summary. With id + path, the full diff of that single
* file in that entry.
*/
codeShowEdit?: (args: readonly string[]) => string;
/**
* Root directory passed by `reasonix code`. Enables `/commit`, which
* runs `git add -A && git commit` in this directory. Missing → `/commit`
* replies "only available in code mode".
*/
codeRoot?: string;
/**
* How many edit blocks are currently pending `/apply` or `/discard`.
* Surfaced by `/status`. TUI populates it live from its pending ref;
* omitted → treat as 0 (chat-only session).
*/
pendingEditCount?: number;
/**
* Callback returning every tool result seen this session in
* chronological order (oldest first). Powers `/tool [N]` for
* inspecting the full untruncated output that `EventLog` clips at
* 400 chars for display. Absent → `/tool` replies "not available".
*/
toolHistory?: () => Array<{ toolName: string; text: string }>;
/**
* Pre-captured inspection reports for each connected MCP server.
* Populated once at chat startup (chat.tsx) so `/mcp` can render
* tools + resources + prompts synchronously without needing async
* handler support.
*/
mcpServers?: McpServerSummary[];
/**
* Directory `/memory` should resolve `REASONIX.md` from. In code
* mode this is the rootDir the filesystem tools are pinned to; in
* plain chat this is `process.cwd()` at launch time. Absent → the
* TUI is running in some non-cwd context (tests) and `/memory`
* replies "root unknown" instead of silently reading a different dir.
*/
memoryRoot?: string;
/**
* Current plan-mode state, surfaced in `/status` and toggled by
* `/plan`. Present iff the session is a `reasonix code` run — chat
* mode doesn't have plan mode.
*/
planMode?: boolean;
/**
* Current edit-gate mode (`review` or `auto`). Surfaced in `/status`,
* toggled by `/mode`, also flipped by the Shift+Tab keybind in the
* TUI. Absent → not in `reasonix code`.
*/
editMode?: EditMode;
/**
* Set the edit-gate mode. Callback rather than raw state so App can
* also persist the choice to config and echo the change in historical.
*/
setEditMode?: (mode: EditMode) => void;
/**
* Background-process registry backing /jobs / /kill / /logs. Present
* iff the session is a `reasonix code` run. Slash handlers expect
* synchronous info strings, but stop_job is async — we return a
* "stopping, watch /jobs" info and let the registry do its thing.
*/
jobs?: JobRegistry;
/**
* Async-late append to the historical log. /kill uses this to
* surface "job N stopped" the moment stop() actually resolves,
* rather than leaving the user to poll /jobs themselves.
*/
postInfo?: (text: string) => void;
/**
* Callback the `/plan` slash uses to flip plan mode on/off. Also
* mirrors the state to the underlying ToolRegistry so dispatch
* enforcement follows. Absent → `/plan` replies "only available in
* code mode".
*/
setPlanMode?: (on: boolean) => void;
/**
* Callback that clears a pending-plan picker state. Called by
* `/apply-plan` so that when the user force-approves, the picker
* dismisses without also firing its own approval synthetic (the
* slash returns its own `resubmit` instead). Safe to call with no
* pending plan.
*/
clearPendingPlan?: () => void;
/**
* Re-load `~/.reasonix/settings.json` + `<project>/.reasonix/settings.json`
* and update both the App's hook state and the loop's mutable hook
* list. Returns the new hook count so the slash can echo a sane
* confirmation. Absent → `/hooks reload` replies "not available".
*/
reloadHooks?: () => number;
/**
* Latest published version if App's background registry check
* has completed, `null` otherwise (still in flight OR offline).
* Drives `/update` — the slash shows whatever the async check
* already resolved, so the command is fully synchronous.
*/
latestVersion?: string | null;
/**
* Fire-and-forget: kick off a fresh registry fetch. `/update`
* calls this whenever it encounters `latestVersion === null`
* so the user can rerun the slash a few seconds later and see
* a concrete answer. Absent → the slash just reports "pending"
* with no retry path.
*/
refreshLatestVersion?: () => void;
/**
* Model catalog fetched from DeepSeek's `/models` endpoint at App
* mount. `null` → still in flight or the call failed (auth / offline);
* `[]` → the API answered with zero entries. `/models` uses this to
* render the list, and `/model <id>` uses it for soft validation
* (warn-only — we still switch even on unknown ids since the list
* can lag a newly-released model).
*/
models?: string[] | null;
/**
* Fire-and-forget refresh for the models list. Lets `/models` retry
* after a flaky first fetch without needing async slash support.
*/
refreshModels?: () => void;
/**
* Arm pro for the next turn. Called by `/pro`. The TUI wires this
* to both `loop.armProForNextTurn()` and its React mirror state so
* the StatsPanel badge flips immediately. Absent → the handler
* calls `loop.armProForNextTurn()` directly and the badge updates
* on the next render tick (slightly laggy but still correct).
*/
armPro?: () => void;
/** Cancel a pending /pro arming. Mirrors `armPro` semantics. */
disarmPro?: () => void;
}
export interface McpServerSummary {
/** Short label shown in the `/mcp` output (server namespace or "anon"). */
label: string;
/** Original --mcp spec string. */
spec: string;
/** Count of tools bridged into the Reasonix registry from this server. */
toolCount: number;
/** Full inspection snapshot — used for the resources + prompts sections. */
report: InspectionReport;
/**
* Live MCP client, kept so `/resource` and `/prompt` can call
* `readResource` / `getPrompt` against this server. Omitted by
* callers that only build the summary for display; those slashes
* fall back to "not available" when the client is missing.
*/
client?: McpClient;
}
/**
* Slash command registry. Drives `/help`, the on-type suggestion
* popup (`SlashSuggestions`), and auto-complete. Kept as data rather
* than derived from the `handleSlash` switch so summaries can be
* user-facing rather than code comments.
*
* `contextual` gates commands that only make sense in certain modes:
* - `"code"` — only show when the TUI is running `reasonix code`
* - absent → always shown
*/
export interface SlashCommandSpec {
cmd: string;
summary: string;
contextual?: "code";
/** If the command takes args, hint text shown after the name. */
argsHint?: string;
/**
* How the first argument position should autocomplete. Shapes the
* picker that appears below the prompt once the user types `/<cmd>`
* + space:
* - `"models"` → DeepSeek model-id list fetched at startup.
* - `"mcp-resources"` → live URIs aggregated across connected MCP servers.
* - `"mcp-prompts"` → live prompt names aggregated across MCP servers.
* - `string[]` → small enum of literal values (e.g. `["on", "off"]`).
* - omitted → no picker; a persistent usage hint shows the
* argsHint + summary so the user knows what to type.
*
* File-path completion is deliberately NOT offered here. Users who
* want to reference a file in a prompt use `@path/to/file` (0.5.5);
* the `@` picker already surfaces files with mtime + recently-used
* ranking. Adding a second file-picker surface for slash commands
* would split the UX without adding leverage.
*/
argCompleter?: "models" | "mcp-resources" | "mcp-prompts" | readonly string[];
}
/**
* Shape describing what the prompt buffer is asking for AFTER the
* user has committed to a slash command (`/<cmd>`) and started
* typing its first argument. Consumed by the TUI to drive an
* argument-level picker.
*/
export interface SlashArgContext {
/** The command spec (looked up by name from SLASH_COMMANDS). */
spec: SlashCommandSpec;
/** The partial first-argument text, possibly empty. */
partial: string;
/**
* Buffer offset where `partial` begins. Used by the TUI to splice
* a picked completion back in at the right position.
*/
partialOffset: number;
/**
* Classification of what the caller should show:
* - `"picker"` → an interactive picker (file / enum / models). The
* caller uses `spec.argCompleter` to pick the data source and
* filters against `partial`.
* - `"hint"` → past the completable position (additional args or
* no completer declared). Caller shows a dim usage hint only.
*/
kind: "picker" | "hint";
}
+190
View File
@@ -0,0 +1,190 @@
/**
* One-line tool-result summarizer for the compact scrollback row.
*
* Old rendering: glyph + arrow + blank line + 400-char body block.
* Cost ~6–8 vertical lines per tool call. Long sessions drown in
* noise; the actually-interesting tool result (an edit diff, a
* checkpoint signal) gets buried.
*
* New rendering: glyph + tool name + arrow + a SINGLE-LINE summary
* tailored to the tool family. Full content stays in the tool history
* and can be expanded via `/tool N`. edit_file keeps its multi-line
* diff renderer (the diff IS the value).
*
* Pure function — lives outside EventLog.tsx so it's testable without
* Ink and can be reused if other surfaces (replay, transcript export)
* want the same one-liner.
*/
const MAX_SUMMARY_CHARS = 80;
const TRAILING_ELLIPSIS = "…";
export interface ToolSummary {
/** Single-line summary text. Empty string if the result was empty. */
summary: string;
/** True when the tool result represents a failure the renderer should color red. */
isError: boolean;
}
function clip(s: string, max: number): string {
if (s.length <= max) return s;
return s.slice(0, Math.max(1, max - TRAILING_ELLIPSIS.length)) + TRAILING_ELLIPSIS;
}
function firstNonEmptyLine(text: string): string {
for (const line of text.split(/\r?\n/)) {
const trimmed = line.trim();
if (trimmed) return trimmed;
}
return "";
}
/**
* Render a duration in milliseconds as a tight human label for the
* compact tool row. Picks a representation that fits in ~5 chars so
* the surrounding row stays readable on narrow terminals.
*
* < 100ms → "47ms"
* < 1000ms → "0.4s"
* < 60s → "12s" (or "1.2s" for sub-10-second times)
* >= 60s → "1m30s"
*/
export function formatDuration(ms: number): string {
if (!Number.isFinite(ms) || ms < 0) return "";
if (ms < 100) return `${Math.round(ms)}ms`;
if (ms < 1000) return `${(ms / 1000).toFixed(1)}s`;
if (ms < 10_000) return `${(ms / 1000).toFixed(1)}s`;
if (ms < 60_000) return `${Math.round(ms / 1000)}s`;
const totalSec = Math.round(ms / 1000);
const m = Math.floor(totalSec / 60);
const s = totalSec % 60;
return s === 0 ? `${m}m` : `${m}m${s}s`;
}
function formatBytes(n: number): string {
if (n < 1000) return `${n}B`;
if (n < 1_000_000) return `${(n / 1000).toFixed(1)}KB`;
return `${(n / 1_000_000).toFixed(1)}MB`;
}
function formatLineCount(text: string): string {
// Cheap line count — the +1 covers files without a trailing newline.
const lines = text.split(/\r?\n/).length;
return `${lines} line${lines === 1 ? "" : "s"}`;
}
/**
* Try to recognize a structured error envelope. Reasonix tools emit
* `{ "error": "..." }` JSON for failures and structured payloads
* (PlanProposedError carries `{error, plan, ...}`) for special
* signals. We surface the error name as the summary so the user
* sees what kind of failure happened at a glance.
*/
function summarizeStructured(content: string): ToolSummary | null {
const trimmed = content.trim();
if (!trimmed.startsWith("{")) return null;
try {
const parsed = JSON.parse(trimmed);
if (!parsed || typeof parsed !== "object") return null;
const obj = parsed as Record<string, unknown>;
// Plan / choice signals come through as errors carrying structured
// payloads — the App-level handlers extract the structured part.
// For the tool row here we just want the tag.
if (typeof obj.error === "string") {
const tag = obj.error.split(":", 1)[0]?.trim() ?? "error";
const detail = obj.error.slice(tag.length + 1).trim();
// The tag-only case (no colon body) — show the bare tag.
const summary = detail ? `${tag} — ${detail}` : tag;
// Plan / Choice errors are control-flow signals, not real errors.
const isControlSignal =
tag === "PlanProposedError" ||
tag === "PlanCheckpointError" ||
tag === "PlanRevisionProposedError" ||
tag === "ChoiceRequestedError" ||
tag === "NeedsConfirmationError";
return { summary: clip(summary, MAX_SUMMARY_CHARS), isError: !isControlSignal };
}
// step_completed payload (when used outside the error path, kept
// for forward-compat with non-throwing variants).
if (obj.kind === "step_completed" && typeof obj.stepId === "string") {
const result = typeof obj.result === "string" ? obj.result : "";
return {
summary: clip(`✓ ${obj.stepId}: ${result}`, MAX_SUMMARY_CHARS),
isError: false,
};
}
return null;
} catch {
return null;
}
}
/**
* Per-tool-name overrides for cases where a smarter summary is cheap
* to compute. Returning null means "fall through to the generic
* summary path."
*/
function summarizeKnownTool(toolName: string, content: string): ToolSummary | null {
if (toolName === "read_file") {
const lines = formatLineCount(content);
const bytes = formatBytes(content.length);
const head = clip(
firstNonEmptyLine(content),
MAX_SUMMARY_CHARS - lines.length - bytes.length - 8,
);
return {
summary: head ? `${head} · ${lines} · ${bytes}` : `${lines} · ${bytes}`,
isError: false,
};
}
if (toolName === "list_directory" || toolName === "directory_tree") {
const entries = content.split(/\r?\n/).filter((l) => l.trim()).length;
return { summary: `${entries} entr${entries === 1 ? "y" : "ies"}`, isError: false };
}
if (toolName === "search_files" || toolName === "search_content") {
const matches = content.split(/\r?\n/).filter((l) => l.trim()).length;
if (matches === 0) return { summary: "no matches", isError: false };
const first = firstNonEmptyLine(content);
return {
summary: clip(`${matches} match${matches === 1 ? "" : "es"} · ${first}`, MAX_SUMMARY_CHARS),
isError: false,
};
}
if (toolName === "run_command" || toolName === "run_background") {
// Native shell tools prepend "exit 0:" / "exit N:" or the result
// already mentions exit code. Try to surface it.
const exitMatch = content.match(/exit (?:code )?(-?\d+)/i);
const first = firstNonEmptyLine(content);
if (exitMatch) {
const code = exitMatch[1];
const isError = code !== "0";
return {
summary: clip(`exit ${code} · ${first}`, MAX_SUMMARY_CHARS),
isError,
};
}
return { summary: clip(first || "(no output)", MAX_SUMMARY_CHARS), isError: false };
}
return null;
}
export function summarizeToolResult(toolName: string, content: string): ToolSummary {
const isExplicitError = content.startsWith("ERROR:");
if (isExplicitError) {
const stripped = content.slice("ERROR:".length).trim();
return { summary: clip(stripped || "(unknown error)", MAX_SUMMARY_CHARS), isError: true };
}
const structured = summarizeStructured(content);
if (structured) return structured;
const known = summarizeKnownTool(toolName, content);
if (known) return known;
// Generic: first line + size hint.
const first = firstNonEmptyLine(content);
if (!content.trim()) return { summary: "(empty)", isError: false };
if (content.length <= MAX_SUMMARY_CHARS) {
return { summary: clip(first, MAX_SUMMARY_CHARS), isError: false };
}
const sizeHint = formatBytes(content.length);
const head = clip(first, MAX_SUMMARY_CHARS - sizeHint.length - 3);
return { summary: `${head} · ${sizeHint}`, isError: false };
}
+218
View File
@@ -0,0 +1,218 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
type FileWithStats,
detectAtPicker,
listFilesWithStatsSync,
rankPickerCandidates,
} from "../../at-mentions.js";
import {
type McpServerSummary,
type SlashArgContext,
type SlashCommandSpec,
detectSlashArgContext,
suggestSlashCommands,
} from "./slash.js";
export interface UseCompletionPickersParams {
input: string;
setInput: (v: string) => void;
codeMode: { rootDir: string } | undefined;
models: string[] | null;
mcpServers: McpServerSummary[] | undefined;
}
export interface UseCompletionPickersResult {
// ── slash-name picker ──
slashMatches: SlashCommandSpec[] | null;
slashSelected: number;
setSlashSelected: React.Dispatch<React.SetStateAction<number>>;
// ── @-mention picker ──
atPicker: ReturnType<typeof detectAtPicker>;
atMatches: readonly string[] | null;
atSelected: number;
setAtSelected: React.Dispatch<React.SetStateAction<number>>;
pickAtMention: (chosenPath: string) => void;
recordRecentFile: (path: string) => void;
// ── slash-arg picker ──
slashArgContext: SlashArgContext | null;
slashArgMatches: readonly string[] | null;
slashArgSelected: number;
setSlashArgSelected: React.Dispatch<React.SetStateAction<number>>;
pickSlashArg: (chosen: string) => void;
}
/**
* The three mutually-exclusive input-prefix pickers share enough
* structure (matches list + highlighted index + reset-on-shrink effect
* + commit-back-into-buffer callback) that they live together here.
* Priority in the parent useInput handler:
* atMatches > slashArgMatches > slashMatches > prompt history
* detection already disambiguates by construction — the slash-name
* picker fires only when the buffer has no space; the slash-arg picker
* only after a space; the @-picker only outside slash mode.
*/
export function useCompletionPickers({
input,
setInput,
codeMode,
models,
mcpServers,
}: UseCompletionPickersParams): UseCompletionPickersResult {
// ── slash-name picker ──
const [slashSelected, setSlashSelected] = useState(0);
const slashMatches = useMemo(() => {
if (!input.startsWith("/") || input.includes(" ")) return null;
return suggestSlashCommands(input.slice(1), !!codeMode);
}, [input, codeMode]);
useEffect(() => {
setSlashSelected((prev) => {
if (!slashMatches || slashMatches.length === 0) return 0;
if (prev >= slashMatches.length) return slashMatches.length - 1;
return prev;
});
}, [slashMatches]);
// ── @-mention picker ──
const [atSelected, setAtSelected] = useState(0);
// Walk the code root ONCE on mount, collecting mtime alongside path
// so the picker can surface recently-edited files first. Files
// created mid-session via tool edits won't appear until restart —
// rare, and the user can always type the full path.
const atFiles = useMemo<readonly FileWithStats[]>(() => {
if (!codeMode?.rootDir) return [];
try {
return listFilesWithStatsSync(codeMode.rootDir, { maxResults: 500 });
} catch {
return [];
}
}, [codeMode?.rootDir]);
// LRU of files touched by recent tool calls. Seeds the picker with
// "stuff I just looked at" at the top, so a user typing `@` in the
// same file they were just discussing gets it instantly.
const recentFilesRef = useRef<string[]>([]);
const recordRecentFile = useCallback((p: string) => {
const list = recentFilesRef.current;
const i = list.indexOf(p);
if (i >= 0) list.splice(i, 1);
list.unshift(p);
if (list.length > 20) list.length = 20;
}, []);
const atPicker = useMemo(() => {
if (!codeMode?.rootDir) return null;
// Slash prefix wins — avoids the picker confusingly surfacing on
// `/@wat`-style edge inputs.
if (slashMatches !== null) return null;
return detectAtPicker(input);
}, [codeMode?.rootDir, input, slashMatches]);
const atMatches = useMemo<readonly string[] | null>(() => {
if (!atPicker) return null;
return rankPickerCandidates(atFiles, atPicker.query, {
limit: 40,
recentlyUsed: recentFilesRef.current,
});
}, [atPicker, atFiles]);
useEffect(() => {
setAtSelected((prev) => {
if (!atMatches || atMatches.length === 0) return 0;
if (prev >= atMatches.length) return atMatches.length - 1;
return prev;
});
}, [atMatches]);
const pickAtMention = useCallback(
(chosenPath: string) => {
if (!atPicker) return;
const before = input.slice(0, atPicker.atOffset);
setInput(`${before}@${chosenPath} `);
},
[atPicker, input, setInput],
);
// ── slash-arg picker ──
const [slashArgSelected, setSlashArgSelected] = useState(0);
const slashArgContext = useMemo<SlashArgContext | null>(() => {
if (!input.startsWith("/")) return null;
if (slashMatches !== null) return null;
return detectSlashArgContext(input, !!codeMode);
}, [input, slashMatches, codeMode]);
const slashArgMatches = useMemo<readonly string[] | null>(() => {
if (!slashArgContext || slashArgContext.kind !== "picker") return null;
const completer = slashArgContext.spec.argCompleter;
const partial = slashArgContext.partial;
const needle = partial.toLowerCase();
// Once the partial is an EXACT match for a valid completion, hide
// the picker so Enter submits the command instead of re-picking
// the same value in an infinite loop. Case-insensitive — users
// may type `/preset FAST` and still mean the same thing.
if (Array.isArray(completer)) {
if (partial && completer.some((v) => v.toLowerCase() === needle)) return null;
if (!partial) return completer.slice();
return completer.filter((v) => v.toLowerCase().startsWith(needle));
}
if (completer === "models") {
const all = models ?? [];
if (partial && all.some((m) => m.toLowerCase() === needle)) return null;
if (!partial) return all.slice(0, 40);
return all.filter((m) => m.toLowerCase().includes(needle)).slice(0, 40);
}
if (completer === "mcp-resources") {
// Aggregate URIs across every server's cached inspection.
const uris: string[] = [];
const servers = mcpServers ?? [];
for (const s of servers) {
if (!s.report.resources.supported) continue;
for (const r of s.report.resources.items) uris.push(r.uri);
}
if (partial && uris.some((u) => u.toLowerCase() === needle)) return null;
if (!partial) return uris.slice(0, 40);
return uris.filter((u) => u.toLowerCase().includes(needle)).slice(0, 40);
}
if (completer === "mcp-prompts") {
const names: string[] = [];
const servers = mcpServers ?? [];
for (const s of servers) {
if (!s.report.prompts.supported) continue;
for (const p of s.report.prompts.items) names.push(p.name);
}
if (partial && names.some((n) => n.toLowerCase() === needle)) return null;
if (!partial) return names.slice(0, 40);
return names.filter((n) => n.toLowerCase().includes(needle)).slice(0, 40);
}
return null;
}, [slashArgContext, models, mcpServers]);
useEffect(() => {
setSlashArgSelected((prev) => {
if (!slashArgMatches || slashArgMatches.length === 0) return 0;
if (prev >= slashArgMatches.length) return slashArgMatches.length - 1;
return prev;
});
}, [slashArgMatches]);
const pickSlashArg = useCallback(
(chosen: string) => {
if (!slashArgContext) return;
const before = input.slice(0, slashArgContext.partialOffset);
// No trailing space — enum picks take no further args, so the
// user presses Enter once more to run the command.
setInput(`${before}${chosen}`);
},
[slashArgContext, input, setInput],
);
return {
slashMatches,
slashSelected,
setSlashSelected,
atPicker,
atMatches,
atSelected,
setAtSelected,
pickAtMention,
recordRecentFile,
slashArgContext,
slashArgMatches,
slashArgSelected,
setSlashArgSelected,
pickSlashArg,
};
}
+309
View File
@@ -0,0 +1,309 @@
import { useCallback, useRef, useState } from "react";
import { formatAllBlockDiffs } from "../../code/diff-preview.js";
import {
type ApplyResult,
type EditBlock,
type EditSnapshot,
restoreSnapshots,
} from "../../code/edit-blocks.js";
import {
type EditHistoryEntry,
entryStatus,
formatUndoRows,
isEntryFullyUndone,
} from "./edit-history.js";
export interface UndoBannerState {
results: ApplyResult[];
expiresAt: number;
}
export interface UseEditHistoryResult {
/** Post-auto-apply banner state — rendered at the bottom for 5s. */
undoBanner: UndoBannerState | null;
/**
* Append a batch of successfully-applied edits into the session's
* edit history. If the current turn already has an open entry,
* append into it (first-wins-per-path so `/undo` restores the
* pre-turn state, not an intermediate half-edit). Otherwise open a
* new entry.
*/
recordEdit: (
source: string,
blocks: readonly EditBlock[],
results: readonly ApplyResult[],
snaps: readonly EditSnapshot[],
) => void;
/**
* Show the post-auto-apply undo banner for 5 seconds. Overwrites any
* prior banner and replaces the auto-dismiss timer so multiple
* edits inside a single turn don't prematurely expire the window.
*/
armUndoBanner: (results: ApplyResult[]) => void;
/**
* `/undo` — revert applied edits.
* `/undo` → newest non-fully-undone entry, all its
* remaining (non-undone) files.
* `/undo <id>` → that specific entry's remaining files.
* `/undo <id> <path>` → just that one file in that entry.
* Works as long as the session is alive; no 5-second banner limit.
*/
codeUndo: (args?: readonly string[]) => string;
/**
* `/history` — list every edit batch this session. Each entry's id
* is the token for `/show <id>` and the target of per-batch undo.
*/
codeHistory: () => string;
/**
* `/show` — inspect a stored edit batch.
* `/show` → newest non-fully-undone entry, per-file summary.
* `/show <id>` → that entry's per-file summary.
* `/show <id> <path>` → full diff of one file in that entry.
*/
codeShowEdit: (args?: readonly string[]) => string;
/**
* Seal the in-progress entry so the next edit opens a fresh one.
* Called at handleSubmit start — prior turns stay intact for
* `/history` and `/undo` to walk through independently.
*/
sealCurrentEntry: () => void;
/**
* True when there's at least one history entry that isn't fully
* undone yet. Used by the `u` keybind and the bottom ModeStatusBar.
* Reads the ref fresh — callers must re-read each time.
*/
hasUndoable: () => boolean;
}
/**
* Session-scoped edit history and undo machinery for `reasonix code`.
* Keeps the history ref + snapshot bookkeeping out of App.tsx so the
* parent only sees a small API: append, banner, three slash handlers,
* a turn sealer, and an undoable probe.
*
* `codeMode` is optional because the hook is always mounted but its
* handlers turn into no-ops when code mode isn't active.
*/
export function useEditHistory(codeMode: { rootDir: string } | undefined): UseEditHistoryResult {
const editHistory = useRef<EditHistoryEntry[]>([]);
const nextHistoryId = useRef(1);
const currentTurnEntry = useRef<EditHistoryEntry | null>(null);
const [undoBanner, setUndoBanner] = useState<UndoBannerState | null>(null);
const undoTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const recordEdit = useCallback<UseEditHistoryResult["recordEdit"]>(
(source, blocks, results, snaps) => {
if (snaps.length === 0) return;
let entry = currentTurnEntry.current;
if (!entry) {
entry = {
id: nextHistoryId.current++,
at: Date.now(),
source,
blocks: [],
results: [],
snapshots: [],
undoneFiles: new Set<string>(),
};
currentTurnEntry.current = entry;
editHistory.current.push(entry);
}
entry.blocks.push(...blocks);
entry.results.push(...results);
const seen = new Set(entry.snapshots.map((s) => s.path));
for (const s of snaps) {
if (!seen.has(s.path)) entry.snapshots.push(s);
}
},
[],
);
const armUndoBanner = useCallback<UseEditHistoryResult["armUndoBanner"]>((results) => {
setUndoBanner({ results, expiresAt: Date.now() + 5000 });
if (undoTimeoutRef.current) clearTimeout(undoTimeoutRef.current);
undoTimeoutRef.current = setTimeout(() => {
setUndoBanner(null);
undoTimeoutRef.current = null;
}, 5000);
}, []);
const codeUndo = useCallback<UseEditHistoryResult["codeUndo"]>(
(args = []) => {
if (!codeMode) return "not in code mode";
const root = codeMode.rootDir;
const revert = (entry: EditHistoryEntry, paths: readonly string[]): string => {
const subset = entry.snapshots.filter((s) => paths.includes(s.path));
if (subset.length === 0) {
return `batch #${entry.id}: nothing to undo (already restored or path not in batch)`;
}
const results = restoreSnapshots(subset, root);
for (const s of subset) entry.undoneFiles.add(s.path);
if (currentTurnEntry.current === entry && isEntryFullyUndone(entry)) {
currentTurnEntry.current = null;
}
if (undoTimeoutRef.current) {
clearTimeout(undoTimeoutRef.current);
undoTimeoutRef.current = null;
}
setUndoBanner(null);
const when = new Date(entry.at).toISOString().replace("T", " ").slice(11, 19);
const scope = subset.length === 1 ? subset[0]!.path : `${subset.length} file(s)`;
const header = `▸ undo: reverted ${scope} from batch #${entry.id} (${when})`;
return [header, ...formatUndoRows(results)].join("\n");
};
const idArg = args[0];
const pathArg = args[1];
if (!idArg) {
for (let i = editHistory.current.length - 1; i >= 0; i--) {
const e = editHistory.current[i]!;
if (isEntryFullyUndone(e)) continue;
const remaining = e.snapshots.map((s) => s.path).filter((p) => !e.undoneFiles.has(p));
return revert(e, remaining);
}
return "nothing to undo — every batch in the session history is already undone";
}
const id = Number.parseInt(idArg, 10);
if (!Number.isFinite(id)) {
return "usage: /undo [id] [path] (omit id for newest; id from /history; path from /show <id>)";
}
const entry = editHistory.current.find((e) => e.id === id);
if (!entry) return `no edit #${id} — run /history to see valid ids`;
if (!pathArg) {
const remaining = entry.snapshots
.map((s) => s.path)
.filter((p) => !entry.undoneFiles.has(p));
if (remaining.length === 0) return `batch #${id} is already fully undone`;
return revert(entry, remaining);
}
const snap = entry.snapshots.find((s) => s.path === pathArg);
if (!snap) {
const files = [...new Set(entry.blocks.map((b) => b.path))];
return `batch #${id} doesn't include "${pathArg}" — files in this batch: ${files.join(", ")}`;
}
if (entry.undoneFiles.has(pathArg)) {
return `${pathArg} in batch #${id} is already undone`;
}
return revert(entry, [pathArg]);
},
[codeMode],
);
const codeHistory = useCallback<UseEditHistoryResult["codeHistory"]>(() => {
if (!codeMode) return "not in code mode";
const entries = editHistory.current;
if (entries.length === 0) return "no edits recorded this session yet";
const lines = ["Edit history (oldest first):"];
for (const e of entries) {
const when = new Date(e.at).toISOString().replace("T", " ").slice(11, 19);
const files = new Set(e.blocks.map((b) => b.path));
const fileList = [...files].join(", ");
const fileSummary = fileList.length > 60 ? `${fileList.slice(0, 60)}…` : fileList;
const status = entryStatus(e);
const statusText =
status === "applied" ? "applied" : status === "PARTIAL" ? "PARTIAL" : "UNDONE ";
lines.push(
` #${String(e.id).padStart(3)} ${when} ${statusText} ${e.source.padEnd(12)} ${files.size} file · ${e.blocks.length} block ${fileSummary}`,
);
}
lines.push("");
lines.push(
"/show <id> → per-file summary · /show <id> <path> → full diff of one file",
);
lines.push(
"/undo → newest non-undone · /undo <id> [path] → target a specific batch or file",
);
return lines.join("\n");
}, [codeMode]);
const codeShowEdit = useCallback<UseEditHistoryResult["codeShowEdit"]>(
(args = []) => {
if (!codeMode) return "not in code mode";
const entries = editHistory.current;
if (entries.length === 0) return "no edits recorded this session — /history is empty";
const idArg = args[0];
const pathArg = args[1];
let entry: EditHistoryEntry | undefined;
if (!idArg) {
entry =
[...entries].reverse().find((e) => !isEntryFullyUndone(e)) ?? entries[entries.length - 1];
} else {
const id = Number.parseInt(idArg, 10);
if (!Number.isFinite(id)) {
return "usage: /show [id] [path] (omit id for newest; path from the per-file summary)";
}
entry = entries.find((e) => e.id === id);
if (!entry) return `no edit #${id} — run /history to see valid ids`;
}
if (!entry) return "unexpected: history lookup failed";
if (pathArg) {
const fileBlocks = entry.blocks.filter((b) => b.path === pathArg);
if (fileBlocks.length === 0) {
const files = [...new Set(entry.blocks.map((b) => b.path))];
return `batch #${entry.id} doesn't include "${pathArg}" — files in this batch: ${files.join(", ")}`;
}
const when = new Date(entry.at).toISOString().replace("T", " ").slice(11, 19);
const state = entry.undoneFiles.has(pathArg) ? "UNDONE" : "applied";
const header = `▸ edit #${entry.id} · ${when} · ${pathArg} · ${state} · ${fileBlocks.length} block(s)`;
const diff = formatAllBlockDiffs(fileBlocks, { maxLines: 60, contextLines: 2 });
const footer = entry.undoneFiles.has(pathArg)
? "(already reverted — /history shows the batch-level status)"
: `/undo ${entry.id} ${pathArg} → revert just this file`;
return [header, ...diff, "", footer].join("\n");
}
const when = new Date(entry.at).toISOString().replace("T", " ").slice(11, 19);
const files = [...new Set(entry.blocks.map((b) => b.path))];
const status = entryStatus(entry);
const header = `▸ edit #${entry.id} · ${when} · ${entry.source} · ${status} · ${files.length} file(s)`;
const countLines = (s: string) => (s.length === 0 ? 0 : (s.match(/\n/g)?.length ?? 0) + 1);
const fileLines = files.map((path) => {
const fileBlocks = entry!.blocks.filter((b) => b.path === path);
let removed = 0;
let added = 0;
for (const b of fileBlocks) {
removed += countLines(b.search);
added += countLines(b.replace);
}
const state = entry!.undoneFiles.has(path) ? "UNDONE" : "applied";
return ` ${state.padEnd(7)} -${String(removed).padStart(3)}/+${String(added).padStart(3)} ${path} (${fileBlocks.length} block${fileBlocks.length === 1 ? "" : "s"})`;
});
return [
header,
...fileLines,
"",
`/show ${entry.id} <path> → full diff of one file`,
`/undo ${entry.id} <path> → revert just that file · /undo ${entry.id} → revert whole batch`,
].join("\n");
},
[codeMode],
);
const sealCurrentEntry = useCallback(() => {
currentTurnEntry.current = null;
}, []);
const hasUndoable = useCallback(
() => editHistory.current.some((e) => !isEntryFullyUndone(e)),
[],
);
return {
undoBanner,
recordEdit,
armUndoBanner,
codeUndo,
codeHistory,
codeShowEdit,
sealCurrentEntry,
hasUndoable,
};
}
+119
View File
@@ -0,0 +1,119 @@
import { useCallback, useEffect, useState } from "react";
import type { CacheFirstLoop } from "../../loop.js";
import { VERSION, compareVersions, getLatestVersion } from "../../version.js";
export interface Balance {
currency: string;
total: number;
}
export interface UseSessionInfoResult {
balance: Balance | null;
models: string[] | null;
latestVersion: string | null;
/** Strictly-newer version string (for the header badge) — else `null`. */
updateAvailable: string | null;
refreshBalance: () => void;
refreshModels: () => void;
refreshLatestVersion: () => void;
}
/**
* Ambient session-level data fetched from DeepSeek + the npm registry
* at mount, refreshed either implicitly (balance after each turn) or
* on demand (`/update`, `/models`).
*
* All three are best-effort — a `null` value means "not loaded yet or
* the endpoint failed." The StatsPanel hides the cell in that case.
*/
export function useSessionInfo(loop: CacheFirstLoop): UseSessionInfoResult {
const [balance, setBalance] = useState<Balance | null>(null);
const [models, setModels] = useState<string[] | null>(null);
const [latestVersion, setLatestVersion] = useState<string | null>(null);
// Fetch balance on mount. Non-blocking — the session works without
// it; `null` hides the cell. handleSubmit calls refreshBalance in
// its finally so the number tracks actual spend rather than
// freezing at mount-time.
useEffect(() => {
let cancelled = false;
void (async () => {
const bal = await loop.client.getBalance().catch(() => null);
if (cancelled || !bal || !bal.balance_infos.length) return;
const primary = bal.balance_infos[0]!;
setBalance({ currency: primary.currency, total: Number(primary.total_balance) });
})();
return () => {
cancelled = true;
};
}, [loop]);
// Fetch the model catalog from DeepSeek once. Silent degrade on
// failure (stays null), so `/models` can tell "still loading /
// offline" apart from "loaded, here's the list."
useEffect(() => {
let cancelled = false;
void (async () => {
const list = await loop.client.listModels().catch(() => null);
if (cancelled || !list) return;
setModels(list.data.map((m) => m.id));
})();
return () => {
cancelled = true;
};
}, [loop]);
// Background registry check — 24h disk cache absorbs repeated
// launches, timeout bounded so a flaky network doesn't delay the
// notification. `null` on failure (silent). We store the raw version
// regardless of whether it's newer; the header badge's newer-only
// check happens at the `updateAvailable` derivation below.
useEffect(() => {
let cancelled = false;
void (async () => {
const latest = await getLatestVersion();
if (cancelled || !latest) return;
setLatestVersion(latest);
})();
return () => {
cancelled = true;
};
}, []);
const updateAvailable =
latestVersion && compareVersions(VERSION, latestVersion) < 0 ? latestVersion : null;
const refreshBalance = useCallback(() => {
void (async () => {
const bal = await loop.client.getBalance().catch(() => null);
if (bal?.balance_infos.length) {
const p = bal.balance_infos[0]!;
setBalance({ currency: p.currency, total: Number(p.total_balance) });
}
})();
}, [loop]);
const refreshModels = useCallback(() => {
void (async () => {
const list = await loop.client.listModels().catch(() => null);
if (list) setModels(list.data.map((m) => m.id));
})();
}, [loop]);
const refreshLatestVersion = useCallback(() => {
void (async () => {
const fresh = await getLatestVersion({ force: true });
if (fresh) setLatestVersion(fresh);
})();
}, []);
return {
balance,
models,
latestVersion,
updateAvailable,
refreshBalance,
refreshModels,
refreshLatestVersion,
};
}
+99
View File
@@ -0,0 +1,99 @@
import { useEffect, useRef, useState } from "react";
import type { SubagentEvent, SubagentSink } from "../../tools/subagent.js";
import { appendUsage } from "../../usage.js";
import type { DisplayEvent } from "./EventLog.js";
export interface SubagentActivity {
task: string;
iter: number;
elapsedMs: number;
}
export interface UseSubagentParams {
session: string | undefined;
setHistorical: React.Dispatch<React.SetStateAction<DisplayEvent[]>>;
}
export interface UseSubagentResult {
/** Live state for an in-flight subagent, null when none is running. */
activity: SubagentActivity | null;
/**
* Ref captured by the loop's `subagentRunner` closure so even
* late-spawned subagents find the current handler. Consumers pass
* this to `spawnSubagent({ sink })`.
*/
sinkRef: React.MutableRefObject<SubagentSink>;
}
/**
* Subagent UI wiring. `start` opens the activity row; each `progress`
* updates iter + elapsed in place; `end` clears the row and posts a
* one-line summary (with inline cost) into Historical. Only one
* subagent is active at a time in the MVP — overlapping events just
* replace the prior activity.
*/
export function useSubagent({ session, setHistorical }: UseSubagentParams): UseSubagentResult {
const [activity, setActivity] = useState<SubagentActivity | null>(null);
const sinkRef = useRef<SubagentSink>({ current: null });
useEffect(() => {
sinkRef.current.current = (ev: SubagentEvent) => {
if (ev.kind === "start") {
setActivity({
task: ev.task,
iter: ev.iter ?? 0,
elapsedMs: ev.elapsedMs ?? 0,
});
return;
}
if (ev.kind === "progress") {
setActivity({
task: ev.task,
iter: ev.iter ?? 0,
elapsedMs: ev.elapsedMs ?? 0,
});
return;
}
// end
setActivity(null);
const seconds = ((ev.elapsedMs ?? 0) / 1000).toFixed(1);
// Inline cost: the one number most users look at. Shown in the
// Historical row so they don't have to run `/stats` to see it.
const costTail =
ev.costUsd !== undefined && ev.costUsd > 0 ? ` · $${ev.costUsd.toFixed(4)}` : "";
const summary = ev.error
? `⌬ subagent "${ev.task}" failed after ${seconds}s · ${ev.iter ?? 0} tool call(s) — ${ev.error}`
: `⌬ subagent "${ev.task}" done in ${seconds}s · ${ev.iter ?? 0} tool call(s) · ${ev.turns ?? 0} turn(s)${costTail}`;
setHistorical((prev) => [
...prev,
{
id: `subagent-end-${Date.now()}`,
role: "info",
text: summary,
},
]);
// Persist a subagent summary row to ~/.reasonix/usage.jsonl so
// `/stats` and `reasonix stats` surface it. Skipped on error —
// we only record what actually cost money and did work.
if (!ev.error && ev.usage && ev.model) {
appendUsage({
session: session ?? null,
model: ev.model,
usage: ev.usage,
kind: "subagent",
subagent: {
skillName: ev.skillName,
taskPreview: ev.task.slice(0, 60),
toolIters: ev.iter ?? 0,
durationMs: ev.elapsedMs ?? 0,
},
});
}
};
return () => {
sinkRef.current.current = null;
};
}, [session, setHistorical]);
return { activity, sinkRef };
}
+21
View File
@@ -153,6 +153,27 @@ export function applyEditBlocks(blocks: EditBlock[], rootDir: string): ApplyResu
return blocks.map((b) => applyEditBlock(b, rootDir));
}
/**
* Build an EditBlock that represents a whole-file overwrite. If the
* target exists, SEARCH = current content so applyEditBlock replaces
* the whole thing when committed; if it doesn't, SEARCH is empty (the
* create-new sentinel). Used by the edit-mode gate when routing a
* `write_file` tool call through the review queue without executing
* the write inline.
*/
export function toWholeFileEditBlock(path: string, content: string, rootDir: string): EditBlock {
const abs = resolve(rootDir, path);
let search = "";
if (existsSync(abs)) {
try {
search = readFileSync(abs, "utf8");
} catch {
search = "";
}
}
return { path, search, replace: content, offset: 0 };
}
// ---------- snapshot / restore (for /undo) ----------
export interface EditSnapshot {
+292
View File
@@ -0,0 +1,292 @@
/**
* Per-session plan persistence.
*
* The structured plan that the model submits via `submit_plan` (and
* subsequently mutates via `mark_step_complete` / `revise_plan`) is a
* meaningful artifact of the user's work. Without persistence it
* evaporates the moment the terminal closes — which means the user
* loses context every time they take a coffee break, and the rich
* checkpoint / revise / progress UX has nothing to attach to in
* resumed sessions.
*
* This module ships the smallest useful piece: read/write a plan
* state JSON next to the session's JSONL log. App.tsx loads on
* mount and saves after every state change. Storage path mirrors
* the JSONL convention: `~/.reasonix/sessions/<sanitized>.plan.json`.
*
* What's persisted: the structured `steps[]` (with risk levels), the
* set of completedStepIds, and an updatedAt timestamp. The plan's
* markdown body is NOT persisted here — it lives in the JSONL log
* (it was a tool result), so resuming the session replays it
* naturally if the user wants to re-read it. We only carry forward
* the live state needed to keep mark_step_complete and revise_plan
* meaningful.
*/
import {
existsSync,
mkdirSync,
readFileSync,
readdirSync,
renameSync,
statSync,
unlinkSync,
writeFileSync,
} from "node:fs";
import { dirname, join } from "node:path";
import { sanitizeName, sessionsDir } from "../session.js";
import type { PlanStep } from "../tools/plan.js";
export interface PlanStateOnDisk {
/** File format version — bump when shape changes. */
version: 1;
steps: PlanStep[];
completedStepIds: string[];
/** ISO8601 timestamp of the last write. */
updatedAt: string;
/**
* Markdown body the model submitted via submit_plan. Persisted so
* Time Travel replay can show the full proposal without going back
* to the JSONL log. Optional — older / minimal plans may lack it.
*/
body?: string;
/**
* Optional one-sentence human-friendly title. Surfaces in the
* PlanConfirm header, the resume banner, and /plans listings so
* the user identifies plans by intent rather than file path.
*/
summary?: string;
}
export function planStatePath(sessionName: string): string {
return join(sessionsDir(), `${sanitizeName(sessionName)}.plan.json`);
}
/**
* Read the persisted plan for this session, if any. Returns `null`
* for missing / unreadable / malformed files — callers should treat
* the absence of a stored plan as "no plan yet", not a hard error.
*/
export function loadPlanState(sessionName: string): PlanStateOnDisk | null {
const path = planStatePath(sessionName);
if (!existsSync(path)) return null;
try {
const raw = readFileSync(path, "utf8");
const parsed = JSON.parse(raw) as Partial<PlanStateOnDisk>;
if (!parsed || typeof parsed !== "object") return null;
if (parsed.version !== 1) return null;
if (!Array.isArray(parsed.steps)) return null;
if (!Array.isArray(parsed.completedStepIds)) return null;
if (typeof parsed.updatedAt !== "string") return null;
// Defensive: filter out any malformed step entries so a partially
// corrupted file still yields a usable subset.
const steps: PlanStep[] = [];
for (const s of parsed.steps) {
if (!s || typeof s !== "object") continue;
const e = s as unknown as Record<string, unknown>;
if (typeof e.id !== "string" || !e.id) continue;
if (typeof e.title !== "string" || !e.title) continue;
if (typeof e.action !== "string" || !e.action) continue;
const step: PlanStep = { id: e.id, title: e.title, action: e.action };
if (e.risk === "low" || e.risk === "med" || e.risk === "high") step.risk = e.risk;
steps.push(step);
}
if (steps.length === 0) return null;
const completedStepIds = parsed.completedStepIds.filter(
(id): id is string => typeof id === "string" && id.length > 0,
);
const out: PlanStateOnDisk = {
version: 1,
steps,
completedStepIds,
updatedAt: parsed.updatedAt,
};
if (typeof parsed.body === "string" && parsed.body) out.body = parsed.body;
if (typeof parsed.summary === "string" && parsed.summary) out.summary = parsed.summary;
return out;
} catch {
return null;
}
}
/**
* Persist the current plan state. Called whenever the in-memory plan
* meaningfully changes (submit, complete, revise). Best-effort: a
* write failure logs to stderr but doesn't propagate — losing the
* persisted copy is annoying but shouldn't crash the TUI.
*/
export function savePlanState(
sessionName: string,
steps: PlanStep[],
completedStepIds: Iterable<string>,
extras?: { body?: string; summary?: string },
): void {
const path = planStatePath(sessionName);
try {
mkdirSync(dirname(path), { recursive: true });
const state: PlanStateOnDisk = {
version: 1,
steps,
completedStepIds: [...completedStepIds],
updatedAt: new Date().toISOString(),
};
if (extras?.body) state.body = extras.body;
if (extras?.summary) state.summary = extras.summary;
writeFileSync(path, `${JSON.stringify(state, null, 2)}\n`, "utf8");
} catch (err) {
process.stderr.write(
`▸ plan-store: failed to save plan for "${sessionName}": ${(err as Error).message}\n`,
);
}
}
/** Remove the persisted plan, if any. Used on cancel / clean reset. */
export function clearPlanState(sessionName: string): void {
const path = planStatePath(sessionName);
try {
if (existsSync(path)) unlinkSync(path);
} catch {
/* nothing to do — leftover file is harmless, will be overwritten next save */
}
}
/**
* Move the active plan to a timestamped .done.json archive when the
* model has marked every step complete. Future Time-Travel replay
* will load these archives; for now the archive just exists as a
* historical artifact and frees the active plan.json so the next
* session starts fresh.
*
* Returns the archive path on success, or null if there was nothing
* to archive (no active plan) / the rename failed (logged to stderr,
* not propagated — losing the archive is annoying but shouldn't
* crash the TUI).
*
* The timestamp uses ISO 8601 with a millisecond suffix and `:` and
* `.` swapped for `-` so the filename is filesystem-safe on Windows.
* Two archives created within the same millisecond would collide;
* we append a short random suffix to dodge that.
*/
export function archivePlanState(sessionName: string): string | null {
const active = planStatePath(sessionName);
if (!existsSync(active)) return null;
const stamp = new Date().toISOString().replace(/[:.]/g, "-");
const suffix = Math.random().toString(36).slice(2, 6);
const archive = join(
sessionsDir(),
`${sanitizeName(sessionName)}.plan.${stamp}-${suffix}.done.json`,
);
try {
renameSync(active, archive);
return archive;
} catch (err) {
process.stderr.write(
`▸ plan-store: failed to archive plan for "${sessionName}": ${(err as Error).message}\n`,
);
return null;
}
}
/**
* Summary of one archived (completed) plan, as returned by
* `listPlanArchives`. The `completedAt` ISO string comes from the
* archive file's stored `updatedAt` (or its mtime as fallback) so it
* survives across machines / clock skew. `path` is absolute and ready
* for a future `/replay` to read directly.
*/
export interface PlanArchiveSummary {
path: string;
completedAt: string;
steps: PlanStep[];
completedStepIds: string[];
/** Markdown body, when the archive carried it. */
body?: string;
/** One-line human-friendly title, when supplied. */
summary?: string;
}
/**
* List all archived `.done.json` files for this session, newest
* first. Used by `/plans` to give the user a project-local history.
* Cross-project listing is intentionally NOT supported here — a plan
* lives next to its session, and resuming it just means switching
* back to that project's directory.
*
* Robust to missing dir / unreadable entries: a corrupt archive is
* skipped, not propagated. Worst case the user sees a shorter list
* than reality.
*/
export function listPlanArchives(sessionName: string): PlanArchiveSummary[] {
const dir = sessionsDir();
if (!existsSync(dir)) return [];
const prefix = `${sanitizeName(sessionName)}.plan.`;
const suffix = ".done.json";
let entries: string[];
try {
entries = readdirSync(dir);
} catch {
return [];
}
const summaries: PlanArchiveSummary[] = [];
for (const name of entries) {
if (!name.startsWith(prefix) || !name.endsWith(suffix)) continue;
const full = join(dir, name);
try {
const raw = readFileSync(full, "utf8");
const parsed = JSON.parse(raw) as Partial<PlanStateOnDisk>;
if (parsed.version !== 1) continue;
if (!Array.isArray(parsed.steps) || parsed.steps.length === 0) continue;
const steps = parsed.steps.filter(
(s): s is PlanStep =>
!!s &&
typeof s === "object" &&
typeof (s as PlanStep).id === "string" &&
typeof (s as PlanStep).title === "string" &&
typeof (s as PlanStep).action === "string",
);
if (steps.length === 0) continue;
const completedStepIds = Array.isArray(parsed.completedStepIds)
? parsed.completedStepIds.filter((id): id is string => typeof id === "string" && !!id)
: [];
// Prefer the file's own updatedAt; fall back to mtime if missing
// or unparseable so a hand-edited archive still sorts sensibly.
let completedAt = typeof parsed.updatedAt === "string" ? parsed.updatedAt : "";
if (!completedAt || Number.isNaN(Date.parse(completedAt))) {
try {
completedAt = statSync(full).mtime.toISOString();
} catch {
completedAt = new Date(0).toISOString();
}
}
const entry: PlanArchiveSummary = { path: full, completedAt, steps, completedStepIds };
if (typeof parsed.body === "string" && parsed.body) entry.body = parsed.body;
if (typeof parsed.summary === "string" && parsed.summary) entry.summary = parsed.summary;
summaries.push(entry);
} catch {
// Skip the corrupt archive entirely.
}
}
summaries.sort((a, b) => b.completedAt.localeCompare(a.completedAt));
return summaries;
}
/**
* Render `updatedAt` as a short relative-time string for the resume
* notice ("2h ago", "3 days ago"). Falls back to the raw ISO string
* for anything beyond a week so users don't see misleading
* "47 days ago" approximations.
*/
export function relativeTime(updatedAt: string, now: number = Date.now()): string {
const t = Date.parse(updatedAt);
if (Number.isNaN(t)) return updatedAt;
const diffMs = Math.max(0, now - t);
const sec = Math.floor(diffMs / 1000);
if (sec < 60) return `${sec}s ago`;
const min = Math.floor(sec / 60);
if (min < 60) return `${min}m ago`;
const hr = Math.floor(min / 60);
if (hr < 24) return `${hr}h ago`;
const day = Math.floor(hr / 24);
if (day < 7) return `${day}d ago`;
return updatedAt.slice(0, 10);
}
+71 -6
View File
@@ -15,9 +15,10 @@
import { existsSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { ESCALATION_CONTRACT, TUI_FORMATTING_RULES } from "../prompt-fragments.js";
import { applyMemoryStack } from "../user-memory.js";
export const CODE_SYSTEM_PROMPT = `You are Reasonix Code, a coding assistant. You have filesystem tools (read_file, write_file, list_directory, search_files, etc.) rooted at the user's working directory.
export const CODE_SYSTEM_PROMPT = `You are Reasonix Code, a coding assistant. You have filesystem tools (read_file, write_file, edit_file, list_directory, directory_tree, search_files, search_content, get_file_info) rooted at the user's working directory, plus run_command / run_background for shell.
# Cite or shut up — non-negotiable
@@ -50,6 +51,21 @@ Skip submit_plan for small, obvious changes: one-line typo, clear bug with a cle
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 — 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 — don't call any more tools, wait for the user's verdict.
**Do NOT use submit_plan to present A/B/C route menus.** The approve/refine/cancel picker has no branch selector — 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.
# When to ask the user to pick (ask_choice)
You have an \`ask_choice\` tool. **If the user is supposed to pick between alternatives, the tool picks — 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.
Call it when:
- The user has asked for options / doesn't want a recommendation / wants to decide.
- You've analyzed multiple approaches and the final call is theirs.
- It's a preference fork you can't resolve without them (deployment target, team convention, taste).
Skip it when one option is clearly correct (just do it, or submit_plan) or a free-form text answer fits (ask in prose).
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 — letting you pick"); don't repeat the options in it. After the call, STOP.
# Plan mode (/plan)
The user can ALSO enter "plan mode" via /plan, which is a stronger, explicit constraint:
@@ -58,15 +74,17 @@ The user can ALSO enter "plan mode" via /plan, which is a stronger, explicit con
- You MUST call submit_plan before anything will execute. Approve exits plan mode; Refine stays in; Cancel exits without implementing.
# Delegating to subagents via Skills (🧬)
# Delegating to subagents via Skills
The pinned Skills index below lists playbooks you can invoke with \`run_skill\`. Skills marked with **🧬** spawn an **isolated subagent** — a fresh child loop that runs the playbook in its own context and returns only the final answer. The subagent's tool calls and reasoning never enter your context, so 🧬 skills are how you keep the main session lean.
The pinned Skills index below lists playbooks you can invoke with \`run_skill\`. Entries tagged \`[🧬 subagent]\` spawn an **isolated subagent** — a fresh child loop that runs the playbook in its own context and returns only the final answer. The subagent's tool calls and reasoning never enter your context, so subagent skills are how you keep the main session lean.
**When you call \`run_skill\`, the \`name\` is ONLY the identifier before the tag** — e.g. \`run_skill({ name: "explore", arguments: "..." })\`, NOT \`"[🧬 subagent] explore"\` and NOT \`"explore [🧬 subagent]"\`. The tag is display sugar; the name argument is just the bare identifier.
Two built-ins ship by default:
- **🧬 explore** — read-only investigation across the codebase. Use when the user says things like "find all places that...", "how does X work across the project", "survey the code for Y". Pass \`arguments\` describing the concrete question.
- **🧬 research** — combines web search + code reading. Use for "is X supported by lib Y", "what's the canonical way to Z", "compare our impl to the spec".
- **explore** \`[🧬 subagent]\` — read-only investigation across the codebase. Use when the user says things like "find all places that...", "how does X work across the project", "survey the code for Y". Pass \`arguments\` describing the concrete question.
- **research** \`[🧬 subagent]\` — combines web search + code reading. Use for "is X supported by lib Y", "what's the canonical way to Z", "compare our impl to the spec".
When to delegate (call \`run_skill\` with a 🧬 skill):
When to delegate (call \`run_skill\` with a subagent skill):
- The task would otherwise need >5 file reads or searches.
- You only need the conclusion, not the exploration trail.
- The work is self-contained (you can describe it in one paragraph).
@@ -89,6 +107,15 @@ In those cases, use tools to gather what you need, then reply in prose. No SEARC
When you do propose edits, the user will review them and decide whether to \`/apply\` or \`/discard\`. Don't assume they'll accept — write as if each edit will be audited, because it will.
Reasonix runs an **edit gate**. The user's current mode (\`review\` or \`auto\`) decides what happens to your writes; you DO NOT see which mode is active, and you SHOULD NOT ask. Write the same way in both cases.
- In \`auto\` mode \`edit_file\` / \`write_file\` calls land on disk immediately with an undo window — you'll get the normal "edit blocks: 1/1 applied" style response.
- In \`review\` mode EACH \`edit_file\` / \`write_file\` call pauses tool dispatch while the user decides. You'll get one of these responses:
- \`"edit blocks: 1/1 applied"\` — user approved it. Continue as normal.
- \`"User rejected this edit to <path>. Don't retry the same SEARCH/REPLACE…"\` — user said no to THIS specific edit. Do NOT re-emit the same block, do NOT switch tools to sneak it past the gate (write_file → edit_file, or text-form SEARCH/REPLACE). Either take a clearly different approach or stop and ask the user what they want instead.
- Text-form SEARCH/REPLACE blocks in your assistant reply queue for end-of-turn /apply — same "don't retry on rejection" rule.
- If the user presses Esc mid-prompt the whole turn is aborted; you won't get another tool response. Don't keep spamming tool calls after an abort.
# Editing files
When you've been asked to change a file, output one or more SEARCH/REPLACE blocks in this exact format:
@@ -129,11 +156,49 @@ Two different rules depending on which tool:
- **Filesystem tools** (\`read_file\`, \`list_directory\`, \`search_files\`, \`edit_file\`, etc.): paths are sandbox-relative. \`/\` means the project root, \`/src/foo.ts\` means \`<project>/src/foo.ts\`. Both relative (\`src/foo.ts\`) and POSIX-absolute (\`/src/foo.ts\`) forms work.
- **\`run_command\`**: the command runs in a real OS shell with cwd pinned to the project root. Paths inside the shell command are interpreted by THAT shell, not by us. **Never use leading \`/\` in run_command arguments** — Windows treats \`/tests\` as drive-root \`F:\\tests\` (non-existent), POSIX shells treat it as filesystem root. Use plain relative paths (\`tests\`, \`./tests\`, \`src/loop.ts\`) instead.
# Foreground vs. background commands
You have TWO tools for running shell commands, and picking the right one is non-negotiable:
- \`run_command\` — blocks until the process exits. Use for: **tests, builds, lints, typechecks, git operations, one-shot scripts**. Anything that naturally returns in under a minute.
- \`run_background\` — spawns and detaches after a brief startup window. Use for: **dev servers, watchers, any command with "dev" / "serve" / "watch" / "start" in the name**. Examples: \`npm run dev\`, \`pnpm dev\`, \`yarn start\`, \`vite\`, \`next dev\`, \`uvicorn app:app --reload\`, \`flask run\`, \`python -m http.server\`, \`cargo watch\`, \`tsc --watch\`, \`webpack serve\`.
**Never use run_command for a dev server.** It will block for 60s, time out, and the user will see a frozen tool call while the server was actually running fine. Always \`run_background\`, then \`job_output\` to peek at the logs when you need to verify something.
After \`run_background\`, tools available to you:
- \`job_output(jobId, tailLines?)\` — read recent logs to verify startup / debug errors.
- \`list_jobs\` — see every job this session (running + exited).
- \`stop_job(jobId)\` — SIGTERM → SIGKILL after grace. Stop before switching port / config.
Don't re-start an already-running dev server — call \`list_jobs\` first when in doubt.
# Scope discipline on "run it" / "start it" requests
When the user's request is to **run / start / launch / serve / boot up** something, your job is ONLY:
1. Start it (\`run_background\` for dev servers, \`run_command\` for one-shots).
2. Verify it came up (read a ready signal via \`job_output\`, or fetch the URL with \`web_fetch\` if they want you to confirm).
3. Report what's running, where (URL / port / pid), and STOP.
Do NOT, in the same turn:
- Run \`tsc\` / type-checkers / linters unless the user asked for it.
- Scan for bugs to "proactively" fix. The page rendering is success.
- Clean up unused imports, dead code, or refactor "while you're here."
- Edit files to improve anything the user didn't mention.
If you notice an obvious issue, MENTION it in one sentence and wait for the user to say "fix it." The cost of over-eagerness is real: you burn tokens, make surprise edits the user didn't want, and chain into cascading "fix the new error I just introduced" loops. The storm-breaker will cut you off, but the user still sees the mess.
"It works" is the end state. Resist the urge to polish.
# Style
- Show edits; don't narrate them in prose. "Here's the fix:" is enough.
- One short paragraph explaining *why*, then the blocks.
- If you need to explore first (list / read / search), do it with tool calls before writing any prose — silence while exploring is fine.
${ESCALATION_CONTRACT}
${TUI_FORMATTING_RULES}
`;
/**
+84
View File
@@ -21,6 +21,23 @@ import { dirname, join } from "node:path";
/** One of the preset bundles (model + harvest + branch combo). */
export type PresetName = "fast" | "smart" | "max";
/**
* How `reasonix code` handles model-issued edits:
* - "review" — queue the edit into pendingEdits; user /apply or `y` commits.
* - "auto" — apply immediately, snapshot for /undo, show a short undo
* banner so the user can roll back with one keystroke.
* Persisted so `/mode auto` survives a relaunch. Missing → "review".
*/
export type EditMode = "review" | "auto";
/**
* reasoning_effort cap for the model. "max" is the agent-class default;
* "high" is cheaper / faster. Persisted so `/effort high` survives a
* relaunch — earlier versions silently reverted to "max" on every new
* session, which burned budget unexpectedly.
*/
export type ReasoningEffort = "high" | "max";
export interface ReasonixConfig {
apiKey?: string;
baseUrl?: string;
@@ -29,6 +46,22 @@ export interface ReasonixConfig {
* Maps to model + harvest + branch combos (see presets.ts). Missing → "fast".
*/
preset?: PresetName;
/**
* Edit-gate mode for `reasonix code`. See EditMode doc. Absent → "review".
*/
editMode?: EditMode;
/**
* Set to `true` the first time we've shown the "Shift+Tab cycles
* review/AUTO" onboarding tip in `reasonix code`. Once seen, we stop
* posting the tip — the bottom status bar carries the knowledge
* forward without further nagging.
*/
editModeHintShown?: boolean;
/**
* Last reasoning_effort chosen via `/effort`. Loaded on launch so
* "high" stays "high" — default is "max" when unset.
*/
reasoningEffort?: ReasoningEffort;
/**
* Default MCP server specs to bridge on every `reasonix chat`, in the
* same `"name=cmd args..."` format that `--mcp` takes. Stored as strings
@@ -146,6 +179,57 @@ export function addProjectShellAllowed(
writeConfig(cfg, path);
}
/**
* Read the persisted edit-mode. Unknown values fall back to "review" so
* a user who hand-edits the file into an invalid state still gets the
* safe default. `reasonix code` calls this at launch and the App lets
* `/mode` / Shift+Tab flip it.
*/
export function loadEditMode(path: string = defaultConfigPath()): EditMode {
const v = readConfig(path).editMode;
return v === "auto" ? "auto" : "review";
}
/** Persist the edit mode so `/mode auto` survives a relaunch. */
export function saveEditMode(mode: EditMode, path: string = defaultConfigPath()): void {
const cfg = readConfig(path);
cfg.editMode = mode;
writeConfig(cfg, path);
}
/** True when the onboarding tip for the review/AUTO gate has been shown. */
export function editModeHintShown(path: string = defaultConfigPath()): boolean {
return readConfig(path).editModeHintShown === true;
}
/**
* Read the persisted reasoning_effort. Unknown / missing values fall
* back to "max" so the agent-class default is never silently overridden
* by a hand-edited bad value in config.json.
*/
export function loadReasoningEffort(path: string = defaultConfigPath()): ReasoningEffort {
const v = readConfig(path).reasoningEffort;
return v === "high" ? "high" : "max";
}
/** Persist the reasoning_effort cap so `/effort high` survives a relaunch. */
export function saveReasoningEffort(
effort: ReasoningEffort,
path: string = defaultConfigPath(),
): void {
const cfg = readConfig(path);
cfg.reasoningEffort = effort;
writeConfig(cfg, path);
}
/** Mark the onboarding tip as shown so subsequent launches skip it. */
export function markEditModeHintShown(path: string = defaultConfigPath()): void {
const cfg = readConfig(path);
if (cfg.editModeHintShown === true) return;
cfg.editModeHintShown = true;
writeConfig(cfg, path);
}
export function isPlausibleKey(key: string): boolean {
const trimmed = key.trim();
return /^sk-[A-Za-z0-9_-]{16,}$/.test(trimmed);
+6 -5
View File
@@ -79,12 +79,13 @@ export async function harvest(
if (trimmed.length < minLen) return emptyPlanState();
// Harvest is schema-constrained JSON extraction, not agent reasoning.
// Default to `deepseek-chat` (= v4-flash non-thinking mode) — a few
// Default to v4-flash with `thinking: "disabled"` below — a few
// hundred output tokens fit easily in the non-thinking budget, the
// reply comes back ~10× faster than thinking mode, and the
// per-turn cost stays an asterisk next to the main loop's spend
// rather than a visible slice of it.
const model = options.model ?? "deepseek-chat";
// reply comes back ~10× faster than thinking mode, and the per-turn
// cost stays an asterisk next to the main loop's spend rather than a
// visible slice of it. (`deepseek-chat` was the compat alias for this
// same route; we now name the real model.)
const model = options.model ?? "deepseek-v4-flash";
const maxItems = options.maxItems ?? 5;
const maxItemLen = options.maxItemLen ?? 80;
const system = SYSTEM_PROMPT.replace("{maxItems}", String(maxItems)).replace(
+9 -2
View File
@@ -83,8 +83,15 @@ export { registerFilesystemTools } from "./tools/filesystem.js";
export type { FilesystemToolsOptions } from "./tools/filesystem.js";
export { registerMemoryTools } from "./tools/memory.js";
export type { MemoryToolsOptions } from "./tools/memory.js";
export { PlanProposedError, registerPlanTool } from "./tools/plan.js";
export type { PlanToolOptions } from "./tools/plan.js";
export { ChoiceRequestedError, registerChoiceTool } from "./tools/choice.js";
export type { ChoiceOption, ChoiceToolOptions } from "./tools/choice.js";
export {
PlanCheckpointError,
PlanProposedError,
PlanRevisionProposedError,
registerPlanTool,
} from "./tools/plan.js";
export type { PlanStep, PlanStepRisk, PlanToolOptions, StepCompletion } from "./tools/plan.js";
export { forkRegistryExcluding, registerSubagentTool } from "./tools/subagent.js";
export type {
SubagentEvent,
+725 -63
View File
File diff suppressed because it is too large. Load diff
+65
View File
@@ -0,0 +1,65 @@
/**
* Reusable prompt fragments. Every rule that applies across multiple
* prompt surfaces (main agent + subagents + built-in skills) lives
* here so one edit covers every place the model learns the house
* style. The 4-copy formatting-rule drift that motivated this was a
* real bug: Unicode box-drawing warnings diverged between subagent
* prompts, and the main code prompt lacked them entirely even though
* its reply goes through the same markdown renderer.
*/
/**
* How replies get rendered. Matches behaviors the TUI's markdown
* pipeline (src/cli/ui/markdown.tsx) actually handles best.
* Embedded literally into prompts — no string interpolation, so it
* survives Reasonix's prefix-cache hashing unchanged across sessions.
*/
export const TUI_FORMATTING_RULES = `Formatting (rendered in a TUI with a real markdown renderer):
- Tabular data → GitHub-Flavored Markdown tables with ASCII pipes (\`| col | col |\` header + \`| --- | --- |\` separator). Never use Unicode box-drawing characters (│ ─ ┼ ┌ ┐ └ ┘ ├ ┤) — they look intentional but break terminal word-wrap and render as garbled columns at narrow widths.
- Keep table cells short (one phrase each). If a cell needs a paragraph, use bullets below the table instead.
- Code, file paths with line ranges, and shell commands → fenced code blocks (\`\`\`).
- Do NOT draw decorative frames around content with \`┌──┐ │ └──┘\` characters. The renderer adds its own borders; extra ASCII art adds noise and shatters at narrow widths.
- For flow charts and diagrams: a plain bullet list with \`→\` or \`↓\` between steps. Don't try to draw boxes-and-arrows in ASCII; it never survives word-wrap.`;
/**
* Self-report escalation contract — teaches the model (running on
* flash by default) how to ask for a retry on v4-pro. When Reasonix
* sees "<<<NEEDS_PRO>>>" as the first line of assistant output on
* flash, it aborts the call, upgrades this turn to pro, and re-issues
* the same messages. One retry per turn; pro never re-escalates.
*
* Why this exists: non-expert users can't reliably predict which
* tasks need the frontier tier, and reactive-only escalation (wait
* for flash to fail N times) wastes tokens + time. Letting the model
* self-assess catches hard tasks upfront when flash recognizes the
* difficulty — without silently auto-upgrading every prompt (which
* would destroy cost savings).
*
* Use sparingly: most coding tasks stay on flash. The escape hatch
* is for tasks where flash would otherwise emit a mediocre / guessed
* answer.
*/
export const ESCALATION_CONTRACT = `Cost-aware escalation (when you're running on deepseek-v4-flash):
If a task CLEARLY exceeds what flash can do well — 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 — 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.
Two accepted forms:
- \`<<<NEEDS_PRO>>>\` — bare marker, no rationale.
- \`<<<NEEDS_PRO: <one-sentence reason>>>>\` — preferred. The reason text appears in the user-visible warning ("⇧ flash requested escalation — <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>>>\`.
Do NOT emit any other content in the same response when you request escalation. Use this sparingly: normal tasks — reading files, small edits, clear bug fixes, straightforward feature additions — 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).`;
/**
* "Don't assert absence without checking." Subagents that run without
* this rule will confidently report "X is missing" based on their
* partial exploration, and the parent agent swallows it as fact. The
* main code prompt has its own, longer version of this — kept separate
* because the code agent is in a richer conversational frame.
*/
export const 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 — but that's exactly why you must NOT write them on instinct.
If you have a search tool (\`search_content\`, \`grep\`, web search), call it FIRST before asserting absence:
- Returns matches → you were wrong; correct yourself and cite the matches.
- Returns nothing → state the absence WITH the search query as evidence: \`No callers of \\\`foo()\\\` found (search_content "foo").\`
If you have no search tool, qualify hard: "I haven't verified — this is a guess." Never assert absence with fake authority.`;
+1
View File
@@ -170,6 +170,7 @@ function summarizeTurns(turns: TurnStats[]): SessionSummary {
savingsVsClaudePct: round(savingsVsClaude * 100, 2),
cacheHitRatio: round(cacheHitRatio, 4),
lastPromptTokens: lastTurn?.usage.promptTokens ?? 0,
lastTurnCostUsd: round(lastTurn?.cost ?? 0, 6),
};
}
+20 -18
View File
@@ -32,6 +32,7 @@
import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
import { homedir } from "node:os";
import { join, resolve } from "node:path";
import { NEGATIVE_CLAIM_RULE, TUI_FORMATTING_RULES } from "./prompt-fragments.js";
export const SKILLS_DIRNAME = "skills";
export const SKILL_FILE = "SKILL.md";
@@ -271,15 +272,22 @@ function parseRunAs(raw: string | undefined): SkillRunAs {
* Build a single index line for one skill. Shape mirrors memory's
* `indexLine` — a bullet suitable for a markdown fenced block in the
* system prompt. Description is truncated to keep the full line under
* ~150 chars. Subagent-runAs skills carry a 🧬 marker so the model
* sees at a glance which skills will spawn an isolated child loop.
* ~150 chars.
*
* Subagent-runAs skills carry a `[🧬 subagent]` tag AFTER the name
* so the model can't confuse the marker for part of the skill name.
* (Historical bug: when the marker led the name — `- 🧬 explore` —
* models would call `run_skill({ name: "🧬 explore" })` verbatim
* and fail lookup. Wrapping the marker in brackets AFTER the name
* eliminates that confusion; `run_skill`'s name arg also strips any
* leading non-word chars as a belt-and-suspenders measure.)
*/
function skillIndexLine(s: Pick<Skill, "name" | "description" | "runAs">): string {
const safeDesc = s.description.replace(/\n/g, " ").trim();
const marker = s.runAs === "subagent" ? "🧬 " : "";
const max = 130 - s.name.length - marker.length;
const tag = s.runAs === "subagent" ? " [🧬 subagent]" : "";
const max = 130 - s.name.length - tag.length;
const clipped = safeDesc.length > max ? `${safeDesc.slice(0, Math.max(1, max - 1))}…` : safeDesc;
return clipped ? `- ${marker}${s.name} — ${clipped}` : `- ${marker}${s.name}`;
return clipped ? `- ${s.name}${tag} — ${clipped}` : `- ${s.name}${tag}`;
}
/**
@@ -308,7 +316,7 @@ export function applySkillsIndex(basePrompt: string, opts: SkillStoreOptions = {
"",
"# Skills — playbooks you can invoke",
"",
'One-liner index. Each entry is either a built-in or a user-authored playbook. Call `run_skill({ name: "<skill-name>", arguments: "<task>" })` to invoke one. Skills marked with 🧬 spawn an **isolated subagent** — its tool calls and reasoning never enter your context, only its final answer does. Use 🧬 skills for tasks that would otherwise flood your context (deep exploration, multi-step research, anything where you only need the conclusion). Plain skills are inlined: their body becomes a tool result you read and act on directly. The user can also invoke a skill via `/skill <name>`.',
'One-liner index. Each entry is either a built-in or a user-authored playbook. Call `run_skill({ name: "<skill-name>", arguments: "<task>" })` — the `name` is JUST the skill identifier (e.g. `"explore"`), NOT the `[🧬 subagent]` tag that appears after it. Entries tagged `[🧬 subagent]` spawn an **isolated subagent** — its tool calls and reasoning never enter your context, only its final answer does. Use subagent skills for tasks that would otherwise flood your context (deep exploration, multi-step research, anything where you only need the conclusion). Plain skills are inlined: their body becomes a tool result you read and act on directly. The user can also invoke a skill via `/skill <name>`.',
"",
"```",
truncated,
@@ -343,12 +351,9 @@ Your final answer:
- If the question can't be answered from what you found, say so plainly and suggest where to look next.
- No follow-up offers, no "let me know if you need more." The parent will ask again if they need more.
Formatting (rendered in a TUI):
- Tabular data → GitHub-Flavored Markdown tables with ASCII pipes (\`| col | col |\` + \`| --- | --- |\`). Never use Unicode box-drawing characters (│ ─ ┼) — they break word-wrap.
- Keep table cells short; if a cell needs a paragraph, use bullets below the table instead.
- Code, file paths with line ranges, and shell commands → fenced code blocks (\`\`\`).
- NEVER draw decorative frames around code or text with \`┌──┐ │ └──┘\` box-drawing characters. Use plain code blocks; the renderer adds its own border.
- For flow charts: use a bullet list with \`→\` or \`↓\` between steps, not ASCII boxes-and-arrows.
${NEGATIVE_CLAIM_RULE}
${TUI_FORMATTING_RULES}
The 'task' the parent gave you is the question you must answer. Treat any other reading of it as scope creep.`;
@@ -366,12 +371,9 @@ Your final answer:
- Distinguish "I verified this in code" from "I read this on a docs page" — the parent will trust the former more.
- If the answer is uncertain, say so. Don't invent confidence.
Formatting (rendered in a TUI):
- Tabular data → GitHub-Flavored Markdown tables with ASCII pipes (\`| col | col |\` + \`| --- | --- |\`). Never use Unicode box-drawing characters (│ ─ ┼) — they break word-wrap.
- Keep table cells short; if a cell needs a paragraph, use bullets below the table instead.
- Code, file paths with line ranges, and shell commands → fenced code blocks (\`\`\`).
- NEVER draw decorative frames around code or text with \`┌──┐ │ └──┘\` box-drawing characters. Use plain code blocks; the renderer adds its own border.
- For flow charts: use a bullet list with \`→\` or \`↓\` between steps, not ASCII boxes-and-arrows.
${NEGATIVE_CLAIM_RULE}
${TUI_FORMATTING_RULES}
The 'task' the parent gave you is the research question. Stay on it.`;
+8
View File
@@ -123,6 +123,13 @@ export interface SessionSummary {
* prompt + user delta + any new tool outputs).
*/
lastPromptTokens: number;
/**
* Most recent turn's USD cost. Complements `totalCostUsd` so the TUI
* can render "this turn: $X · session: $Y" — users asked for a
* per-turn signal so a mid-session jump from flash to pro is
* immediately visible, not hidden inside the session aggregate.
*/
lastTurnCostUsd: number;
}
export class SessionStats {
@@ -184,6 +191,7 @@ export class SessionStats {
savingsVsClaudePct: round(this.savingsVsClaude * 100, 2),
cacheHitRatio: round(this.aggregateCacheHitRatio, 4),
lastPromptTokens: last?.usage.promptTokens ?? 0,
lastTurnCostUsd: round(last?.cost ?? 0, 6),
};
}
}
+47
View File
@@ -59,6 +59,22 @@ export interface ToolRegistryOptions {
autoFlatten?: boolean;
}
/**
* Callback form for `setToolInterceptor` — receives the tool name and
* already-parsed arguments; returns a string to short-circuit dispatch
* (the returned value becomes the tool result the model sees), or
* `null` / `undefined` to fall through to the registered tool fn.
*
* Used by `reasonix code`'s edit-mode gate: `edit_file` / `write_file`
* are intercepted in "review" mode (queued into pendingEdits, returning
* "queued for /apply") or handled inline in "auto" mode (snapshot +
* apply, then surface an undo banner). Other tools pass through.
*/
export type ToolInterceptor = (
name: string,
args: Record<string, unknown>,
) => string | null | undefined | Promise<string | null | undefined>;
export class ToolRegistry {
private readonly _tools = new Map<string, InternalTool>();
private readonly _autoFlatten: boolean;
@@ -70,6 +86,12 @@ export class ToolRegistry {
* bounced until the user approves a submitted plan.
*/
private _planMode = false;
/**
* Optional hook run after arg parsing but before tool.fn. Lets the TUI
* reroute specific tool calls (e.g. edit_file in review mode) without
* modifying the tool definitions themselves.
*/
private _interceptor: ToolInterceptor | null = null;
constructor(opts: ToolRegistryOptions = {}) {
this._autoFlatten = opts.autoFlatten !== false;
@@ -85,6 +107,15 @@ export class ToolRegistry {
return this._planMode;
}
/**
* Install or clear the dispatch interceptor. At most one interceptor
* is active at a time — calling twice replaces the previous. Pass
* `null` to remove.
*/
setToolInterceptor(fn: ToolInterceptor | null): void {
this._interceptor = fn;
}
register<A, R>(def: ToolDefinition<A, R>): this {
if (!def.name) throw new Error("tool requires a name");
const internal: InternalTool = { ...(def as ToolDefinition) };
@@ -167,6 +198,22 @@ export class ToolRegistry {
});
}
// Interceptor runs after plan-mode (so a plan-mode refusal still
// wins) but before the real tool fn. A string return is treated as
// the full tool result; null / undefined means "not my concern,
// fall through." Uncaught throws from the interceptor are surfaced
// through the same error path as a failed tool fn below.
if (this._interceptor) {
try {
const short = await this._interceptor(name, args);
if (typeof short === "string") return short;
} catch (err) {
return JSON.stringify({
error: `${name}: interceptor failed — ${(err as Error).message}`,
});
}
}
try {
const result = await tool.fn(args, { signal: opts.signal });
const str = typeof result === "string" ? result : JSON.stringify(result);
+173
View File
@@ -0,0 +1,173 @@
/**
* ask_choice — the primitive for "user needs to pick between alternatives".
*
* Why it exists: `submit_plan` is for ONE concrete plan the user approves.
* Models routinely misused it to present A/B/C option menus, leaving the
* user stuck with an approve/refine/cancel picker that had no way to
* select a route. `ask_choice` gives branching its own tool so plan
* mode stays about one actionable thing at a time.
*
* Shape mirrors `submit_plan`:
* 1. Model calls `ask_choice` with a question and 2–4 options.
* 2. The tool throws `ChoiceRequestedError`; the registry serializes
* the payload via `toToolResult`.
* 3. TUI parses the tagged error, mounts `ChoiceConfirm`, user picks
* one option (or types a custom answer via the escape hatch, or
* cancels).
* 4. A synthetic user message feeds the choice back — "user picked
* <id>" or "user answered: <text>" — and the loop resumes.
*
* Auto-flatten note: the `options` array of objects is exactly the
* schema shape that DeepSeek V3/R1 is known to drop. `ToolRegistry`
* auto-flattens and re-nests on dispatch (Pillar 3), so we don't need
* to hand-flatten here. We still `sanitizeOptions` at runtime because
* even with flatten-repair, models occasionally emit empty strings or
* miss fields entirely.
*/
import type { ToolRegistry } from "../tools.js";
/**
* One option in a branching question. `id` is what gets fed back to
* the model when the user picks; keep it short and stable (A, B, C,
* or option-1 / option-2 / ...). `summary` is optional extra context
* the UI shows as a dimmed sub-line under the title.
*/
export interface ChoiceOption {
id: string;
title: string;
summary?: string;
}
/**
* Thrown by `ask_choice`. Carries the branching question plus the
* options list out to the TUI via the `toToolResult` protocol. The
* error message tells the model to STOP so it doesn't race past the
* picker with more tool calls — same pattern as `PlanProposedError`.
*/
export class ChoiceRequestedError extends Error {
readonly question: string;
readonly options: ChoiceOption[];
readonly allowCustom: boolean;
constructor(question: string, options: ChoiceOption[], allowCustom: boolean) {
super(
"ChoiceRequestedError: choice submitted. STOP calling tools now — 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.",
);
this.name = "ChoiceRequestedError";
this.question = question;
this.options = options;
this.allowCustom = allowCustom;
}
toToolResult(): {
error: string;
question: string;
options: ChoiceOption[];
allowCustom: boolean;
} {
return {
error: `${this.name}: ${this.message}`,
question: this.question,
options: this.options,
allowCustom: this.allowCustom,
};
}
}
export interface ChoiceToolOptions {
/**
* Side-channel preview fired when the model asks. The tool-result
* event also carries the payload; this is the earlier hook for
* test harnesses or alternative UIs that don't want to parse JSON.
*/
onChoiceRequested?: (question: string, options: ChoiceOption[]) => void;
}
function sanitizeOptions(raw: unknown): ChoiceOption[] {
if (!Array.isArray(raw)) return [];
const out: ChoiceOption[] = [];
const seen = new Set<string>();
for (const entry of raw) {
if (!entry || typeof entry !== "object") continue;
const e = entry as Record<string, unknown>;
const id = typeof e.id === "string" ? e.id.trim() : "";
const title = typeof e.title === "string" ? e.title.trim() : "";
if (!id || !title) continue;
if (seen.has(id)) continue;
seen.add(id);
const summary = typeof e.summary === "string" ? e.summary.trim() || undefined : undefined;
const opt: ChoiceOption = { id, title };
if (summary) opt.summary = summary;
out.push(opt);
}
return out;
}
export function registerChoiceTool(
registry: ToolRegistry,
opts: ChoiceToolOptions = {},
): ToolRegistry {
registry.register({
name: "ask_choice",
description:
"Present 2–6 alternatives to the user. The principle: if the user is supposed to pick, the tool picks — 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 — narrow first if more. A one-sentence lead-in before the call is fine; don't repeat the options in it.",
readOnly: true,
parameters: {
type: "object",
properties: {
question: {
type: "string",
description:
"The question to put in front of the user. One sentence. Don't repeat the options in the question text — the picker renders them separately.",
},
options: {
type: "array",
description:
"2–4 alternatives. Each needs a stable id and a short title; summary is optional.",
items: {
type: "object",
properties: {
id: { type: "string", description: "Short stable id (A, B, C, or option-1)." },
title: { type: "string", description: "One-line title shown as the option label." },
summary: {
type: "string",
description:
"Optional. A second dimmed line with more detail. Keep under ~80 chars.",
},
},
required: ["id", "title"],
},
},
allowCustom: {
type: "boolean",
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.",
},
},
required: ["question", "options"],
},
fn: async (args: { question: string; options: unknown; allowCustom?: boolean }) => {
const question = (args?.question ?? "").trim();
if (!question) {
throw new Error(
"ask_choice: question is required — write one sentence explaining the decision.",
);
}
const options = sanitizeOptions(args?.options);
if (options.length < 2) {
throw new Error(
"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.",
);
}
if (options.length > 6) {
throw new Error(
"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.",
);
}
const allowCustom = args?.allowCustom === true;
opts.onChoiceRequested?.(question, options);
throw new ChoiceRequestedError(question, options, allowCustom);
},
});
return registry;
}
+132 -20
View File
@@ -48,6 +48,28 @@ export interface FilesystemToolsOptions {
const DEFAULT_MAX_READ_BYTES = 2 * 1024 * 1024;
const DEFAULT_MAX_LIST_BYTES = 256 * 1024;
/**
* When `read_file` is called without `head` / `tail` / `range`, files
* above this line count auto-trim to a head-plus-tail preview instead
* of dumping everything into the turn's context. Observed: five
* `read_file` calls in one session accounted for ~18K tokens (6.5K +
* 3.9K + 3.2K + 2.4K + 1.6K), a sizable chunk of the 27K total in
* tool results. Most of those reads wanted ~20 lines near one edit —
* the other 480 lines were inventory the model never cites.
*
* 200 is a deliberate middle ground: typical CLI / config / test
* files fit entirely; sprawling service files force the model to say
* what it actually wants (`range:"120-180"` or `search_content`).
*/
const DEFAULT_AUTO_PREVIEW_LINES = 200;
/**
* When auto-preview triggers, show this many lines at the top
* (structure / imports / public API) plus `AUTO_PREVIEW_TAIL_LINES`
* at the bottom (often the recently-edited tail).
*/
const AUTO_PREVIEW_HEAD_LINES = 80;
const AUTO_PREVIEW_TAIL_LINES = 40;
/**
* Directory names skipped by `search_content` unless `include_deps:true`
* is passed. The intent is "user is asking about THEIR code, not the
@@ -171,8 +193,11 @@ export function registerFilesystemTools(
registry.register({
name: "read_file",
description:
"Read a file under the sandbox root. Returns the full contents (truncated with a notice if larger than the per-call cap). Paths may be relative to the root or absolute-under-root.",
description: `Read a file under the sandbox root. To save context, PREFER to scope the read instead of pulling the whole file:
- head: N → first N lines (imports, public API, small configs)
- tail: N → last N lines (recently-added code, log tails)
- range: "A-B" → inclusive line range A..B, 1-indexed (e.g. "120-180" around an edit site)
When none of these is given AND the file is longer than ${DEFAULT_AUTO_PREVIEW_LINES} lines, the tool auto-returns a head+tail preview with an "N lines omitted" marker rather than dumping everything. If you need the middle, re-call with a range. Prefer search_content to locate a symbol first, then read_file with a range around the hit — one scoped read beats three full-file reads.`,
readOnly: true,
parameters: {
type: "object",
@@ -180,10 +205,15 @@ export function registerFilesystemTools(
path: { type: "string", description: "Path to read (relative to rootDir or absolute)." },
head: { type: "integer", description: "If set, return only the first N lines." },
tail: { type: "integer", description: "If set, return only the last N lines." },
range: {
type: "string",
description:
'Inclusive line range like "50-100" or "50-50". 1-indexed. Takes precedence over head/tail when all three are set. Out-of-range requests clamp to file bounds.',
},
},
required: ["path"],
},
fn: async (args: { path: string; head?: number; tail?: number }) => {
fn: async (args: { path: string; head?: number; tail?: number; range?: string }) => {
const abs = safePath(args.path);
const stat = await fs.stat(abs);
if (stat.isDirectory()) {
@@ -191,22 +221,64 @@ export function registerFilesystemTools(
}
const raw = await fs.readFile(abs);
if (raw.length > maxReadBytes) {
const head = raw.slice(0, maxReadBytes).toString("utf8");
return `${head}\n\n[…truncated ${raw.length - maxReadBytes} bytes — file is ${raw.length} B, cap ${maxReadBytes} B. Retry with head/tail for targeted view.]`;
const headBytes = raw.slice(0, maxReadBytes).toString("utf8");
return `${headBytes}\n\n[…truncated ${raw.length - maxReadBytes} bytes — file is ${raw.length} B, cap ${maxReadBytes} B. Retry with head/tail/range for targeted view.]`;
}
const text = raw.toString("utf8");
let lines = text.split(/\r?\n/);
// Most files end with '\n' which splits into an empty trailing
// entry; drop it so head/tail/range counts match the user's
// visible line numbers in an editor.
if (lines.length > 0 && lines[lines.length - 1] === "") lines = lines.slice(0, -1);
const totalLines = lines.length;
// range wins over head/tail when set — the most precise ask
// should dominate. Parse "A-B" strictly; bad formats fall through
// to head/tail / auto-preview instead of erroring.
if (typeof args.range === "string" && /^\d+\s*-\s*\d+$/.test(args.range)) {
const [rawStart, rawEnd] = args.range.split("-").map((s) => Number.parseInt(s, 10));
const start = Math.max(1, rawStart ?? 1);
const end = Math.min(totalLines, Math.max(start, rawEnd ?? totalLines));
const slice = lines.slice(start - 1, end);
const label = `[range ${start}-${end} of ${totalLines} lines]`;
return `${label}\n${slice.join("\n")}`;
}
if (typeof args.head === "number" && args.head > 0) {
return text.split(/\r?\n/).slice(0, args.head).join("\n");
const count = Math.min(args.head, totalLines);
const slice = lines.slice(0, count);
const marker =
count < totalLines
? `\n\n[…head ${count} of ${totalLines} lines — call again with range / tail for more]`
: "";
return slice.join("\n") + marker;
}
if (typeof args.tail === "number" && args.tail > 0) {
let lines = text.split(/\r?\n/);
// Most files end with a final '\n', which splits into an empty
// trailing string. Drop it before slicing so tail=2 returns the
// last two *real* lines, not "last line + empty".
if (lines.length > 0 && lines[lines.length - 1] === "") lines = lines.slice(0, -1);
return lines.slice(Math.max(0, lines.length - args.tail)).join("\n");
const count = Math.min(args.tail, totalLines);
const slice = lines.slice(totalLines - count);
const marker =
count < totalLines
? `[…tail ${count} of ${totalLines} lines — call again with range / head for more]\n\n`
: "";
return marker + slice.join("\n");
}
return text;
// No explicit scope + file is small → full content.
if (totalLines <= DEFAULT_AUTO_PREVIEW_LINES) return lines.join("\n");
// No explicit scope + file is large → head + tail preview plus
// a marker telling the model how much it missed and how to get
// it. This is the single biggest lever on read_file token cost —
// historically a 500-line file dumped ~4K tokens into the turn
// even when the model only needed 20 of them.
const head = lines.slice(0, AUTO_PREVIEW_HEAD_LINES).join("\n");
const tail = lines.slice(totalLines - AUTO_PREVIEW_TAIL_LINES).join("\n");
const omitted = totalLines - AUTO_PREVIEW_HEAD_LINES - AUTO_PREVIEW_TAIL_LINES;
return [
`[auto-preview: head ${AUTO_PREVIEW_HEAD_LINES} + tail ${AUTO_PREVIEW_TAIL_LINES} of ${totalLines} lines]`,
head,
`\n[… ${omitted} lines omitted — call read_file again with range:"A-B" (1-indexed) or head / tail to get the middle]\n`,
tail,
].join("\n");
},
});
@@ -234,22 +306,40 @@ export function registerFilesystemTools(
registry.register({
name: "directory_tree",
description:
"Recursively list entries in a directory. Shows indented tree structure with directories marked '/'. Caps output so a huge tree doesn't drown the context.",
description: `Recursively list entries in a directory. Shows indented tree structure with directories marked '/'. Budget-aware by default:
- maxDepth defaults to 2 (root + one level). A depth-4 tree on a real repo blew ~5K tokens in one call. If you truly need deeper, pass maxDepth:N explicitly.
- Skips ${[...SKIP_DIR_NAMES].sort().join(", ")} unless include_deps:true. Traversing into node_modules / .git / dist is almost always token-waste.
- Large subtrees (>50 children) auto-collapse to "[N files, M dirs hidden — list_directory <path> to inspect]" so one huge folder can't dominate the output.
Prefer \`list_directory\` for a single-level view, \`search_files\` to find specific paths, and \`search_content\` to find code.`,
readOnly: true,
parameters: {
type: "object",
properties: {
path: { type: "string", description: "Root of the tree (default: sandbox root)." },
maxDepth: { type: "integer", description: "Max recursion depth (default 4)." },
maxDepth: {
type: "integer",
description:
"Max recursion depth (default 2). Depth 0 shows only the top-level entries; depth 2 is usually enough to see module structure.",
},
include_deps: {
type: "boolean",
description:
"When true, also traverse node_modules / .git / dist / build / etc. Off by default — most exploration questions are about the user's own code.",
},
},
},
fn: async (args: { path?: string; maxDepth?: number }) => {
fn: async (args: { path?: string; maxDepth?: number; include_deps?: boolean }) => {
const startAbs = safePath(args.path ?? ".");
const maxDepth = typeof args.maxDepth === "number" ? args.maxDepth : 4;
const maxDepth = typeof args.maxDepth === "number" ? args.maxDepth : 2;
const includeDeps = args.include_deps === true;
const lines: string[] = [];
let totalBytes = 0;
let truncated = false;
// Per-directory child cap — long fixture / asset folders (200+
// snapshots) would otherwise dominate; the collapse keeps the
// overall shape visible. Modest: normal source dirs have <50
// entries.
const PER_DIR_CHILD_CAP = 50;
const walk = async (dir: string, depth: number): Promise<void> => {
if (truncated) return;
if (depth > maxDepth) return;
@@ -260,10 +350,31 @@ export function registerFilesystemTools(
return;
}
entries.sort((a, b) => a.name.localeCompare(b.name));
let emitted = 0;
for (const e of entries) {
if (truncated) return;
// Dep-skip applies only to DIRECTORIES (a file named
// "node_modules" is fine to list). Anything in the skip set
// still shows up as a single node with a trailing " (skipped)"
// hint so the model knows the dir exists but wasn't walked.
const skip = e.isDirectory() && !includeDeps && SKIP_DIR_NAMES.has(e.name);
if (emitted >= PER_DIR_CHILD_CAP) {
const remaining = entries.length - emitted;
let restFiles = 0;
let restDirs = 0;
for (const r of entries.slice(emitted)) {
if (r.isDirectory()) restDirs++;
else restFiles++;
}
const indent = " ".repeat(depth);
lines.push(
`${indent}[… ${remaining} entries hidden (${restDirs} dirs, ${restFiles} files) — list_directory on this path to see all]`,
);
return;
}
const indent = " ".repeat(depth);
const line = e.isDirectory() ? `${indent}${e.name}/` : `${indent}${e.name}`;
const suffix = skip ? " (skipped — pass include_deps:true to traverse)" : "";
const line = e.isDirectory() ? `${indent}${e.name}/${suffix}` : `${indent}${e.name}`;
totalBytes += line.length + 1;
if (totalBytes > maxListBytes) {
lines.push(` [… tree truncated at ${maxListBytes} bytes …]`);
@@ -271,7 +382,8 @@ export function registerFilesystemTools(
return;
}
lines.push(line);
if (e.isDirectory()) {
emitted++;
if (e.isDirectory() && !skip) {
await walk(pathMod.join(dir, e.name), depth + 1);
}
}
+470
View File
@@ -0,0 +1,470 @@
/**
* Long-running process registry — the "background run" counterpart to
* `run_command`. `run_command` spawns a child, waits for it to exit,
* then returns combined output; perfect for tests / builds / one-shots
* but useless for `npm run dev` / `python -m http.server` / watchers,
* which never exit and just time the tool out.
*
* JobRegistry lets the model fire-and-almost-forget: we spawn the
* child, wait at most `waitSec` (default 3s) OR until output matches
* a readiness regex, then return the startup preview plus a job id.
* The child keeps running in the background; later tool calls tail
* its output, stop it, or list what's still alive.
*
* Shape-wise this is modeled on Claude Code's `BashOutput` / `KillBash`
* pair. We diverge on one point: ready-signal detection is on by default
* because dev servers almost universally print "Local:", "listening on",
* "ready in N ms", "compiled successfully" when they come up — short-
* circuiting the wait on those keeps the model's first tool-result
* useful ("server is up at http://localhost:5173") instead of spending
* the full 3s on a stabilization timer.
*/
import { type ChildProcess, type SpawnOptions, spawn } from "node:child_process";
import * as pathMod from "node:path";
import { detectShellOperator, prepareSpawn, tokenizeCommand } from "./shell.js";
/**
* Kill an entire process tree rooted at `pid`.
*
* Why plain `child.kill(signal)` isn't enough:
* - Windows: Node maps signals to `TerminateProcess(handle)`, which
* only targets the direct child. `npm.cmd` spawned via cmd.exe
* launches `node`, which spawns Vite / Webpack / etc. Killing the
* npm wrapper leaves the whole JS server orphaned and still bound
* to the port. `taskkill /T /F /PID` walks the tree and terminates
* every descendant.
* - POSIX: a normal signal goes to the child process only. If we
* spawn with `detached:true` the child becomes a process-group
* leader; `process.kill(-pid, signal)` then reaches every process
* in that group, including grandchildren spawned after startup.
*
* Graceful vs forceful: SIGTERM gives the app a chance to cleanup; if
* it ignores the signal we follow up with SIGKILL after a grace window
* (handled by the caller, not here).
*/
function killProcessTree(pid: number, signal: "SIGTERM" | "SIGKILL"): void {
if (process.platform === "win32") {
// taskkill: /T = tree, /F = force (TerminateProcess, no cleanup).
// Graceful path still uses /F on Windows because there's no signal
// in the POSIX sense — the closest equivalent is Ctrl+Break, which
// is unreliable from another console. /F with /T is what most
// process managers ship on Windows.
const args = ["/pid", String(pid), "/T"];
if (signal === "SIGKILL") args.push("/F");
try {
const killer = spawn("taskkill", args, {
stdio: "ignore",
windowsHide: true,
});
// Swallow ENOENT / EACCES — we did our best. Not awaiting is
// intentional: taskkill can take a few hundred ms and the caller
// already has its own deadline.
killer.on("error", () => {
/* ignore */
});
} catch {
/* ignore */
}
return;
}
// POSIX: negative pid signals the whole process group. Requires the
// spawn to have been detached (which `start()` does below).
try {
process.kill(-pid, signal);
return;
} catch {
/* group-kill failed — fall back to direct */
}
try {
process.kill(pid, signal);
} catch {
/* ignore — already dead */
}
}
/** Per-job output ring. Capped so a chatty dev server doesn't OOM. */
const DEFAULT_OUTPUT_CAP_BYTES = 64 * 1024; // 64 KB
/**
* Regexes that signal "the server is up / the watcher has stabilized."
* Case-insensitive. Matched against the accumulated stdout+stderr; first
* hit cuts the startup wait short. Patterns are conservative — false
* positives waste nothing (we'd have returned at waitSec anyway), but
* a false negative costs the model a real stall.
*/
const READY_SIGNALS: ReadonlyArray<RegExp> = [
// HTTP server banners
/\blistening on\b/i,
/\blocal:\s+https?:\/\//i,
/\bhttps?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0)(?::\d+)?\b/i,
/\b(?:ready|server started|started server|app listening)\b/i,
// Bundlers / compilers
/\bcompiled successfully\b/i,
/\bbuild complete(?:d)?\b/i,
/\bwatching for (?:file )?changes\b/i,
/\bready in \d+/i,
// Generic
/\bstartup (?:complete|finished)\b/i,
];
export interface JobStartOptions {
/** Absolute path to cwd for the spawned child. */
cwd: string;
/**
* Max seconds to wait for the initial burst before returning. Capped
* at 30. A ready-signal match short-circuits this. Default 3.
*/
waitSec?: number;
/** Signal plumbed through from the calling tool's AbortSignal. */
signal?: AbortSignal;
/** Total per-job output buffer cap (bytes). Default 64 KB. */
maxBufferBytes?: number;
}
export interface JobStartResult {
jobId: number;
pid: number | null;
/** True iff the child was still running at the point we returned. */
stillRunning: boolean;
/** True iff a READY_SIGNALS pattern matched during the wait window. */
readyMatched: boolean;
/** Preview of combined stdout+stderr accumulated during the wait. */
preview: string;
/** If the child exited during the wait, its exit code; else null. */
exitCode: number | null;
}
export interface JobRecord {
id: number;
command: string;
pid: number | null;
startedAt: number;
/** Exit code once the process terminates; null while running. */
exitCode: number | null;
/** Combined stdout+stderr, ring-trimmed. */
output: string;
/**
* Total bytes ever written by the child (not just what's in `output`).
* Useful for "how much got dropped" diagnostics.
*/
totalBytesWritten: number;
/** True iff the child is still alive. */
running: boolean;
/** Error from spawn() itself (ENOENT, etc.) once surfaced. */
spawnError?: string;
}
export class JobRegistry {
private readonly jobs = new Map<number, InternalJob>();
private nextId = 1;
/**
* Spawn a background child. Resolves after `waitSec` OR on ready
* signal OR on early exit, whichever comes first. The child continues
* to run (and buffer output) regardless of which path fires.
*/
async start(command: string, opts: JobStartOptions): Promise<JobStartResult> {
const trimmed = command.trim();
if (!trimmed) throw new Error("run_background: empty command");
const op = detectShellOperator(trimmed);
if (op !== null) {
throw new Error(
`run_background: shell operator "${op}" is not supported — spawn one process per background job. Compose via your orchestration, not the shell.`,
);
}
const argv = tokenizeCommand(trimmed);
if (argv.length === 0) throw new Error("run_background: empty command");
const waitMs = Math.max(0, Math.min(30, opts.waitSec ?? 3)) * 1000;
const maxBytes = opts.maxBufferBytes ?? DEFAULT_OUTPUT_CAP_BYTES;
const { bin, args, spawnOverrides } = prepareSpawn(argv);
const spawnOpts: SpawnOptions = {
cwd: pathMod.resolve(opts.cwd),
shell: false,
windowsHide: true,
env: process.env,
// POSIX: detach so the child becomes its own process-group leader.
// Required for `process.kill(-pid, …)` later — without it a group
// kill fails and we end up only signaling the wrapper, leaving
// grandchildren (node → vite → esbuild …) orphaned.
// Windows: detached would spawn a new console window; leave the
// default and use taskkill /T for tree termination.
detached: process.platform !== "win32",
...spawnOverrides,
};
let child: ChildProcess;
try {
child = spawn(bin, args, spawnOpts);
} catch (err) {
// Can't even spawn — record a dead job so the model sees the
// failure in list_jobs, and return a synthetic result.
const id = this.nextId++;
const job: InternalJob = {
id,
command: trimmed,
pid: null,
startedAt: Date.now(),
exitCode: null,
output: `[spawn failed] ${(err as Error).message}`,
totalBytesWritten: 0,
running: false,
spawnError: (err as Error).message,
child: null,
readyPromise: Promise.resolve(),
signalReady: () => {},
};
this.jobs.set(id, job);
return {
jobId: id,
pid: null,
stillRunning: false,
readyMatched: false,
preview: job.output,
exitCode: null,
};
}
const id = this.nextId++;
let readyResolve: () => void = () => {};
const readyPromise = new Promise<void>((res) => {
readyResolve = res;
});
const job: InternalJob = {
id,
command: trimmed,
pid: child.pid ?? null,
startedAt: Date.now(),
exitCode: null,
output: "",
totalBytesWritten: 0,
running: true,
child,
readyPromise,
signalReady: readyResolve,
};
this.jobs.set(id, job);
let readyMatched = false;
const onData = (chunk: Buffer | string) => {
const s = chunk.toString();
job.totalBytesWritten += s.length;
job.output += s;
if (job.output.length > maxBytes) {
// Drop the oldest bytes, but keep a marker so the model can see
// output was truncated. Trim on a rough line boundary to avoid
// chopping a line mid-sentence.
const overflow = job.output.length - maxBytes;
const cut = job.output.indexOf("\n", overflow);
const start = cut >= 0 ? cut + 1 : overflow;
job.output = `[… older output dropped …]\n${job.output.slice(start)}`;
}
if (!readyMatched) {
for (const re of READY_SIGNALS) {
if (re.test(s) || re.test(job.output)) {
readyMatched = true;
job.signalReady();
break;
}
}
}
};
child.stdout?.on("data", onData);
child.stderr?.on("data", onData);
child.on("error", (err) => {
job.running = false;
job.spawnError = err.message;
job.signalReady();
});
child.on("close", (code) => {
job.running = false;
job.exitCode = code;
job.signalReady();
});
const onAbort = () => this.stop(id, { graceMs: 100 });
opts.signal?.addEventListener("abort", onAbort, { once: true });
// Race: (a) ready signal, (b) child exit, (c) wait deadline.
let timer: ReturnType<typeof setTimeout> | null = null;
await Promise.race([
readyPromise,
new Promise<void>((res) => {
timer = setTimeout(res, waitMs);
}),
]);
if (timer) clearTimeout(timer);
return {
jobId: id,
pid: job.pid,
stillRunning: job.running,
readyMatched,
preview: job.output,
exitCode: job.exitCode,
};
}
/**
* Read a job's accumulated output. `since` lets a caller poll
* incrementally: pass the byte count returned from the last call to
* get only newly-written content. Returns both full output and a
* running snapshot so the caller can use whichever.
*/
read(id: number, opts: { since?: number; tailLines?: number } = {}): JobReadResult | null {
const job = this.jobs.get(id);
if (!job) return null;
const full = job.output;
let slice = full;
if (typeof opts.since === "number" && opts.since >= 0 && opts.since < full.length) {
slice = full.slice(opts.since);
}
if (typeof opts.tailLines === "number" && opts.tailLines > 0) {
const lines = slice.split("\n");
const keep = lines.slice(Math.max(0, lines.length - opts.tailLines));
slice = keep.join("\n");
}
return {
output: slice,
byteLength: full.length,
running: job.running,
exitCode: job.exitCode,
command: job.command,
pid: job.pid,
spawnError: job.spawnError,
};
}
/**
* Send SIGTERM, wait `graceMs`, then SIGKILL if still alive. Returns
* the final job record (or null when the job id is unknown). Safe to
* call on an already-exited job — returns the record unchanged.
*/
async stop(id: number, opts: { graceMs?: number } = {}): Promise<JobRecord | null> {
const job = this.jobs.get(id);
if (!job) return null;
if (!job.running || !job.child) return snapshot(job);
const graceMs = Math.max(0, opts.graceMs ?? 2000);
// Tree kill — reaches grandchildren (vite, esbuild, etc.) instead
// of just the npm/cmd.exe wrapper that our direct child represents.
// Falls back to child.kill() only when we somehow don't have a pid.
if (job.pid !== null) {
killProcessTree(job.pid, "SIGTERM");
} else {
try {
job.child.kill("SIGTERM");
} catch {
/* already dead — fall through */
}
}
// Wait for the close event or graceMs, then SIGKILL.
await Promise.race([job.readyPromise, new Promise<void>((res) => setTimeout(res, graceMs))]);
if (job.running) {
if (job.pid !== null) {
killProcessTree(job.pid, "SIGKILL");
} else {
try {
job.child.kill("SIGKILL");
} catch {
/* ignore */
}
}
// Give the OS a moment to reap the tree so our exitCode field
// catches it before we return. Windows taskkill can take up to
// ~700ms to propagate on a three-level tree (npm → node → vite).
await new Promise<void>((res) => setTimeout(res, 800));
}
return snapshot(job);
}
list(): JobRecord[] {
return [...this.jobs.values()].map(snapshot);
}
/**
* Best-effort kill of every still-running job. Called on TUI shutdown
* so dev servers don't outlive the Reasonix process. Resolves after
* every child has closed or a hard deadline passes (3s total).
*/
async shutdown(deadlineMs = 5000): Promise<void> {
const start = Date.now();
const runningJobs = [...this.jobs.values()].filter((j) => j.running && j.child);
if (runningJobs.length === 0) return;
for (const job of runningJobs) {
if (job.pid !== null) killProcessTree(job.pid, "SIGTERM");
else
try {
job.child?.kill("SIGTERM");
} catch {
/* ignore */
}
}
const allClose = Promise.all(runningJobs.map((j) => j.readyPromise));
const elapsed = () => Date.now() - start;
// Grace window: give well-behaved apps time to clean up, capped at
// half the deadline so we always leave room for a SIGKILL pass +
// reap confirmation.
const graceMs = Math.min(1500, Math.max(0, deadlineMs / 2));
await Promise.race([allClose, new Promise<void>((res) => setTimeout(res, graceMs))]);
// Force-kill everything still alive.
for (const job of runningJobs) {
if (!job.running) continue;
if (job.pid !== null) killProcessTree(job.pid, "SIGKILL");
else
try {
job.child?.kill("SIGKILL");
} catch {
/* ignore */
}
}
// Wait for close events post-SIGKILL. taskkill /T on Windows is
// async — without this final wait, shutdown() can return while
// grandchildren are still mid-teardown, which is what "runningCount
// non-zero after shutdown" looks like.
const remaining = Math.max(800, deadlineMs - elapsed());
await Promise.race([allClose, new Promise<void>((res) => setTimeout(res, remaining))]);
}
/** Count of still-running jobs — drives the TUI status-bar indicator. */
runningCount(): number {
let n = 0;
for (const job of this.jobs.values()) if (job.running) n++;
return n;
}
}
interface InternalJob extends JobRecord {
/** Underlying Node child process. Null only on spawn failure. */
child: ChildProcess | null;
/** Resolved when ready-signal fires OR the child exits. */
readyPromise: Promise<void>;
/** Fires readyPromise — called by ready-signal OR close/error handlers. */
signalReady: () => void;
}
export interface JobReadResult {
output: string;
/** Total bytes ever in the buffer (pre-slice). Caller passes back as `since`. */
byteLength: number;
running: boolean;
exitCode: number | null;
command: string;
pid: number | null;
spawnError?: string;
}
function snapshot(job: InternalJob): JobRecord {
return {
id: job.id,
command: job.command,
pid: job.pid,
startedAt: job.startedAt,
exitCode: job.exitCode,
output: job.output,
totalBytesWritten: job.totalBytesWritten,
running: job.running,
spawnError: job.spawnError,
};
}
+266
View File
@@ -0,0 +1,266 @@
/**
* Plan Mode tool registration. Owns `registerPlanTool` — which wires
* `submit_plan`, `mark_step_complete`, and `revise_plan` into a
* ToolRegistry — plus the arg sanitizers these tools share.
*
* Structure rationale: the three registrations are parallel in shape
* (each throws a structured error the TUI renders as a picker), so
* they're broken out into `registerSubmitPlan` / `registerMarkStep` /
* `registerRevisePlan` — one per screen of logic rather than one
* 230-line `registerPlanTool` body. Tool descriptions live at the top
* as named constants so the function bodies stay readable; the strings
* themselves are long because they teach the model when to call each
* tool, which is load-bearing behavior.
*
* Dependency direction: plan-core → plan-errors → plan-types.
*/
import type { ToolRegistry } from "../tools.js";
import {
PlanCheckpointError,
PlanProposedError,
PlanRevisionProposedError,
} from "./plan-errors.js";
import type { PlanStep, PlanStepRisk, StepCompletion } from "./plan-types.js";
// ---------------------------------------------------------------------------
// Tool descriptions (teaching prompts for the model). Edit here, not inline.
// ---------------------------------------------------------------------------
const SUBMIT_PLAN_DESCRIPTION =
"Submit ONE concrete plan you've already decided on. Use this for tasks that warrant a review gate — 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) — 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 — 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` — an array of {id, title, action, risk?} — 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.";
const 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 ✓ progress row and mounts a Continue / Revise / Stop picker — 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.";
const 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 — 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 — 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 — just keep executing. Don't call submit_plan for revisions either — 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.";
// Reused by both submit_plan and revise_plan — the step list shape is
// identical, only the outer wrapper differs. Deliberately NOT `as const`:
// ToolRegistry's JSONSchema type expects mutable arrays.
const STEP_ITEM_SCHEMA = {
type: "object",
properties: {
id: { type: "string", description: "Stable id, e.g. step-1." },
title: { type: "string", description: "Short imperative title." },
action: { type: "string", description: "One-sentence description of the concrete action." },
risk: {
type: "string",
enum: ["low", "med", "high"],
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.",
},
},
required: ["id", "title", "action"],
};
// ---------------------------------------------------------------------------
// Registration options
// ---------------------------------------------------------------------------
export interface PlanToolOptions {
/**
* Optional side-channel callback fired when the model submits a plan.
* The TUI uses this to preview the plan in real time (the tool-result
* event is also emitted; this is just earlier and friendlier to
* test harnesses that don't want to parse JSON).
*/
onPlanSubmitted?: (plan: string, steps?: PlanStep[]) => void;
/**
* Optional callback fired when the model marks a step complete via
* `mark_step_complete`. Analogous to `onPlanSubmitted` — the tool
* event carries the same payload, but this firing point is earlier
* and avoids JSON parsing for consumers that don't need it.
*/
onStepCompleted?: (update: StepCompletion) => void;
/**
* Optional preview callback fired when the model proposes a plan
* revision via `revise_plan`. Same earlier-than-event timing as
* the other on* hooks.
*/
onPlanRevisionProposed?: (reason: string, remainingSteps: PlanStep[], summary?: string) => void;
}
// ---------------------------------------------------------------------------
// Arg sanitizers — defensive cleanup shared between submit_plan and revise_plan
// ---------------------------------------------------------------------------
function sanitizeRisk(raw: unknown): PlanStepRisk | undefined {
if (raw === "low" || raw === "med" || raw === "high") return raw;
return undefined;
}
function sanitizeSteps(raw: unknown): PlanStep[] | undefined {
if (!Array.isArray(raw)) return undefined;
const steps: PlanStep[] = [];
for (const entry of raw) {
if (!entry || typeof entry !== "object") continue;
const e = entry as Record<string, unknown>;
const id = typeof e.id === "string" ? e.id.trim() : "";
const title = typeof e.title === "string" ? e.title.trim() : "";
const action = typeof e.action === "string" ? e.action.trim() : "";
if (!id || !title || !action) continue;
const step: PlanStep = { id, title, action };
const risk = sanitizeRisk(e.risk);
if (risk) step.risk = risk;
steps.push(step);
}
return steps.length > 0 ? steps : undefined;
}
// ---------------------------------------------------------------------------
// Individual tool registrations — one per screen
// ---------------------------------------------------------------------------
function registerSubmitPlan(registry: ToolRegistry, opts: PlanToolOptions): void {
registry.register({
name: "submit_plan",
description: SUBMIT_PLAN_DESCRIPTION,
readOnly: true,
parameters: {
type: "object",
properties: {
plan: {
type: "string",
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.",
},
steps: {
type: "array",
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.",
items: STEP_ITEM_SCHEMA,
},
summary: {
type: "string",
description:
"Optional. One-sentence human-friendly title for the plan, ~80 chars max. Surfaces in the PlanConfirm picker header and in /plans listings ('▸ refactor auth into signed tokens · 2/5 done'). Skip for trivial plans where the first line of the markdown body is already short and clear.",
},
},
required: ["plan"],
},
fn: async (args: { plan: string; steps?: unknown; summary?: string }) => {
const plan = (args?.plan ?? "").trim();
if (!plan) {
throw new Error("submit_plan: empty plan — write a markdown plan and try again.");
}
const steps = sanitizeSteps(args?.steps);
const summary =
typeof args?.summary === "string" ? args.summary.trim() || undefined : undefined;
opts.onPlanSubmitted?.(plan, steps);
throw new PlanProposedError(plan, steps, summary);
},
});
}
function registerMarkStepComplete(registry: ToolRegistry, opts: PlanToolOptions): void {
registry.register({
name: "mark_step_complete",
description: MARK_STEP_COMPLETE_DESCRIPTION,
readOnly: true,
parameters: {
type: "object",
properties: {
stepId: {
type: "string",
description:
"The id of the step being marked complete. Must match one from submit_plan's steps array.",
},
title: {
type: "string",
description:
"Optional. The step's title, echoed back for the UI. If omitted, the UI falls back to the id.",
},
result: {
type: "string",
description: "One-sentence summary of what was done for this step.",
},
notes: {
type: "string",
description:
"Optional. Anything surprising — blockers hit, assumptions revised, follow-ups for later steps.",
},
},
required: ["stepId", "result"],
},
fn: async (args: { stepId: string; title?: string; result: string; notes?: string }) => {
const stepId = (args?.stepId ?? "").trim();
const result = (args?.result ?? "").trim();
if (!stepId) {
throw new Error("mark_step_complete: stepId is required.");
}
if (!result) {
throw new Error(
"mark_step_complete: result is required — say in one sentence what you did.",
);
}
const title = typeof args?.title === "string" ? args.title.trim() || undefined : undefined;
const notes = typeof args?.notes === "string" ? args.notes.trim() || undefined : undefined;
const update: StepCompletion = { kind: "step_completed", stepId, result };
if (title) update.title = title;
if (notes) update.notes = notes;
opts.onStepCompleted?.(update);
throw new PlanCheckpointError({ stepId, title, result, notes });
},
});
}
function registerRevisePlan(registry: ToolRegistry, opts: PlanToolOptions): void {
registry.register({
name: "revise_plan",
description: REVISE_PLAN_DESCRIPTION,
readOnly: true,
parameters: {
type: "object",
properties: {
reason: {
type: "string",
description:
"One sentence explaining why you're revising — what the user asked for, what changed your assessment.",
},
remainingSteps: {
type: "array",
description:
"The new tail of the plan — 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.",
items: STEP_ITEM_SCHEMA,
},
summary: {
type: "string",
description:
"Optional. Updated one-line plan summary if the overall framing has shifted.",
},
},
required: ["reason", "remainingSteps"],
},
fn: async (args: { reason: string; remainingSteps: unknown; summary?: string }) => {
const reason = (args?.reason ?? "").trim();
if (!reason) {
throw new Error(
"revise_plan: reason is required — write one sentence explaining the change.",
);
}
const remainingSteps = sanitizeSteps(args?.remainingSteps);
if (!remainingSteps || remainingSteps.length === 0) {
throw new Error(
"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 — the picker has its own Stop option.",
);
}
const summary =
typeof args?.summary === "string" ? args.summary.trim() || undefined : undefined;
opts.onPlanRevisionProposed?.(reason, remainingSteps, summary);
throw new PlanRevisionProposedError(reason, remainingSteps, summary);
},
});
}
// ---------------------------------------------------------------------------
// Public entry point
// ---------------------------------------------------------------------------
export function registerPlanTool(registry: ToolRegistry, opts: PlanToolOptions = {}): ToolRegistry {
registerSubmitPlan(registry, opts);
registerMarkStepComplete(registry, opts);
registerRevisePlan(registry, opts);
return registry;
}
+132
View File
@@ -0,0 +1,132 @@
/**
* Error classes for Plan Mode tools. Each one implements the
* `toToolResult` protocol so `ToolRegistry.dispatch` serializes the
* structured payload into the tool-result JSON — the TUI parses that
* shape to mount the right picker (approve / checkpoint / revise).
*
* Types live in plan-types.ts; registration logic in plan-core.ts.
* Dependency direction: plan-core → plan-errors → plan-types.
*/
import type { PlanStep, StepCompletion } from "./plan-types.js";
/**
* Thrown by `submit_plan` when the model has produced a plan for the
* user to approve. Carries the markdown body, optional structured
* steps, and an optional one-line summary. The TUI uses all three to
* render the PlanConfirm picker.
*/
export class PlanProposedError extends Error {
readonly plan: string;
readonly steps?: PlanStep[];
readonly summary?: string;
constructor(plan: string, steps?: PlanStep[], summary?: string) {
super(
"PlanProposedError: plan submitted. STOP calling tools now — 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.",
);
this.name = "PlanProposedError";
this.plan = plan;
this.steps = steps;
this.summary = summary;
}
/**
* Structured tool-result shape. Consumed by the TUI to extract the
* plan without regex-scraping the error message. Optional fields
* are omitted from the payload when absent so consumers don't see
* `undefined` keys in the JSON.
*/
toToolResult(): { error: string; plan: string; steps?: PlanStep[]; summary?: string } {
const payload: { error: string; plan: string; steps?: PlanStep[]; summary?: string } = {
error: `${this.name}: ${this.message}`,
plan: this.plan,
};
if (this.steps && this.steps.length > 0) payload.steps = this.steps;
if (this.summary) payload.summary = this.summary;
return payload;
}
}
/**
* Thrown by `mark_step_complete`. The registry serializes the
* structured payload via `toToolResult`, the TUI catches the error
* tag and pauses the loop until the user decides continue / revise /
* stop. The error message tells the model to stop calling tools so
* it doesn't race past the picker.
*/
export class PlanCheckpointError extends Error {
readonly stepId: string;
readonly title?: string;
readonly result: string;
readonly notes?: string;
constructor(update: { stepId: string; title?: string; result: string; notes?: string }) {
super(
"PlanCheckpointError: step complete — 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).",
);
this.name = "PlanCheckpointError";
this.stepId = update.stepId;
this.title = update.title;
this.result = update.result;
this.notes = update.notes;
}
toToolResult(): { error: string } & StepCompletion {
const payload: { error: string } & StepCompletion = {
error: `${this.name}: ${this.message}`,
kind: "step_completed",
stepId: this.stepId,
result: this.result,
};
if (this.title) payload.title = this.title;
if (this.notes) payload.notes = this.notes;
return payload;
}
}
/**
* Thrown by `revise_plan`. Carries the proposed remaining-step list,
* a one-sentence reason, and an optional updated summary out to the
* TUI. Mirrors PlanProposedError / PlanCheckpointError. The picker
* shows a diff between the current remaining steps and the proposed
* ones; the user accepts (replaces) or rejects (keeps current).
*
* Why a separate tool from submit_plan: revising is surgical (replace
* the tail of an in-flight plan), submitting is a fresh proposal.
* Different intent, different UI. Calling submit_plan again mid-
* execution would reset the whole plan including done steps, which
* is heavier than usually needed.
*/
export class PlanRevisionProposedError extends Error {
readonly reason: string;
readonly remainingSteps: PlanStep[];
readonly summary?: string;
constructor(reason: string, remainingSteps: PlanStep[], summary?: string) {
super(
"PlanRevisionProposedError: revision submitted. STOP calling tools now — 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.",
);
this.name = "PlanRevisionProposedError";
this.reason = reason;
this.remainingSteps = remainingSteps;
this.summary = summary;
}
toToolResult(): {
error: string;
reason: string;
remainingSteps: PlanStep[];
summary?: string;
} {
const payload: {
error: string;
reason: string;
remainingSteps: PlanStep[];
summary?: string;
} = {
error: `${this.name}: ${this.message}`,
reason: this.reason,
remainingSteps: this.remainingSteps,
};
if (this.summary) payload.summary = this.summary;
return payload;
}
}
+42
View File
@@ -0,0 +1,42 @@
/**
* Shared types for Plan Mode. Consumed by plan-errors.ts (error
* classes carry these as fields) and plan-core.ts (tool registration
* validates against them). Kept in a separate module so a consumer
* that only wants the types doesn't pull in either the error classes
* or the registration machinery.
*/
export type PlanStepRisk = "low" | "med" | "high";
/**
* Structured step in a submitted plan. Optional — plans can still be
* pure markdown. When provided, each step is addressable by `id` so
* the model can later mark it complete via `mark_step_complete`.
*/
export interface PlanStep {
id: string;
title: string;
action: string;
/**
* Optional self-reported risk level. Drives the colored dot gutter
* in PlanConfirm / PlanCheckpointConfirm: green (low) / yellow
* (med) / red (high). High-risk steps are the ones the user should
* actually read before approving — everything else is noise.
* Omitted when the model didn't categorize (treated as neutral).
*/
risk?: PlanStepRisk;
}
/**
* Payload surfaced by `mark_step_complete` via `PlanCheckpointError`.
* The TUI parses the tool result JSON, pushes a `✓ step` progress row,
* and mounts the checkpoint picker. `kind` is kept on the payload so
* consumers that peek at the JSON can dispatch on a stable tag.
*/
export interface StepCompletion {
kind: "step_completed";
stepId: string;
title?: string;
result: string;
notes?: string;
}
+16 -96
View File
@@ -1,101 +1,21 @@
/**
* Plan Mode — read-only exploration phase for `reasonix code`.
* Plan Mode — barrel re-export. Existing consumers that import from
* `./plan.js` continue to work unchanged.
*
* Shape (mirrors claude-code's plan/act split, adapted for Reasonix):
* Internal layout:
* - plan-types.ts — shared value types (PlanStep, StepCompletion)
* - plan-errors.ts — error classes thrown by the tools
* - plan-core.ts — registerPlanTool + sanitizers
*
* 1. User types `/plan` → registry switches to plan-mode enforcement
* (write tools refused at dispatch; reads + allowlisted shell
* still work).
* 2. Model explores, then calls `submit_plan` with a markdown plan.
* 3. `submit_plan` throws `PlanProposedError`, which the TUI renders
* as a picker: Approve / Refine / Cancel.
* 4. Approve → registry leaves plan mode, a synthetic user message
* "The plan has been approved. Implement it now." is pushed into
* the loop so the next turn executes.
*
* The read-only enforcement lives in `ToolRegistry.dispatch` via
* `readOnly` / `readOnlyCheck`; this file only ships the `submit_plan`
* escape hatch and the error type that carries the plan out of the
* registry without stuffing it into the message.
*
* We do not change `ImmutablePrefix.toolSpecs` when plan mode toggles —
* that would break Pillar 1's prefix cache. Instead the same full spec
* list stays pinned, and the registry enforces mode at dispatch time.
* The refusal string teaches the model the rule; cache hits stay
* intact.
* Named exports (vs `export *`) so TS catches a collision the moment
* someone adds a duplicate symbol in one of the modules.
*/
import type { ToolRegistry } from "../tools.js";
/**
* Thrown by `submit_plan` when plan mode is active, carrying the plan
* text the TUI will render for the user's approval.
*
* Implements the `toToolResult` protocol so `ToolRegistry.dispatch`
* serializes the full plan into the tool-result JSON (not just the
* error message). The TUI parses `{ error, plan }` from the tool event
* and mounts the `PlanConfirm` picker.
*/
export class PlanProposedError extends Error {
readonly plan: string;
constructor(plan: string) {
super(
"PlanProposedError: plan submitted. STOP calling tools now — 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.",
);
this.name = "PlanProposedError";
this.plan = plan;
}
/**
* Structured tool-result shape. Consumed by the TUI to extract the
* plan without regex-scraping the error message.
*/
toToolResult(): { error: string; plan: string } {
return { error: `${this.name}: ${this.message}`, plan: this.plan };
}
}
export interface PlanToolOptions {
/**
* Optional side-channel callback fired when the model submits a plan.
* The TUI uses this to preview the plan in real time (the tool-result
* event is also emitted; this is just earlier and friendlier to
* test harnesses that don't want to parse JSON).
*/
onPlanSubmitted?: (plan: string) => void;
}
export function registerPlanTool(registry: ToolRegistry, opts: PlanToolOptions = {}): ToolRegistry {
registry.register({
name: "submit_plan",
description:
"Submit a concrete plan to the user for review before executing. Use this for tasks that warrant a review gate — 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) — 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.",
readOnly: true,
parameters: {
type: "object",
properties: {
plan: {
type: "string",
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.",
},
},
required: ["plan"],
},
fn: async (args: { plan: string }) => {
const plan = (args?.plan ?? "").trim();
if (!plan) {
throw new Error("submit_plan: empty plan — write a markdown plan and try again.");
}
// Always fire the picker, not just inside plan mode. Plan mode's
// role is the *stronger* constraint — it forces you into read-only
// until you submit. Outside plan mode, submit_plan is your own
// call: use it when the task is large enough to deserve a review
// gate (multi-file refactors, architecture changes, anything
// that would be expensive to undo), skip it for small fixes.
opts.onPlanSubmitted?.(plan);
throw new PlanProposedError(plan);
},
});
return registry;
}
export {
PlanCheckpointError,
PlanProposedError,
PlanRevisionProposedError,
} from "./plan-errors.js";
export type { PlanStep, PlanStepRisk, StepCompletion } from "./plan-types.js";
export { registerPlanTool } from "./plan-core.js";
export type { PlanToolOptions } from "./plan-core.js";
+166 -2
View File
@@ -30,6 +30,7 @@ import { type SpawnOptions, spawn } from "node:child_process";
import { existsSync, statSync } from "node:fs";
import * as pathMod from "node:path";
import type { ToolRegistry } from "../tools.js";
import { JobRegistry } from "./jobs.js";
export interface ShellToolsOptions {
/** Directory to run commands in. Must be an absolute path. */
@@ -58,6 +59,13 @@ export interface ShellToolsOptions {
* (CI, benchmarks) where a human can't be in the loop to confirm.
*/
allowAll?: boolean;
/**
* Background-process registry shared between `run_background`,
* `job_output`, `stop_job`, `list_jobs`, and the /jobs /kill slashes.
* When omitted, the registrar builds its own — but the caller
* usually wants to provide one so the TUI can tail it too.
*/
jobs?: JobRegistry;
}
const DEFAULT_TIMEOUT_SEC = 60;
@@ -283,7 +291,15 @@ export async function runCommand(
cwd: opts.cwd,
shell: false, // no shell-expansion — see header comment
windowsHide: true,
env: process.env,
// PYTHONIOENCODING + PYTHONUTF8 force any spawned Python child
// (run_command running `python script.py`, etc.) to emit UTF-8
// on stdout/stderr. Without this, Chinese-Windows defaults
// Python's stdout encoder to GBK and `print("…")` raises
// UnicodeEncodeError on emoji / non-GBK chars — the model then
// sees a Python traceback instead of the script's real output
// and goes around in circles trying to fix the wrong problem.
// Harmless on non-Python processes (env vars they don't read).
env: { ...process.env, PYTHONIOENCODING: "utf-8", PYTHONUTF8: "1" },
};
// Windows: two layered fixes on top of shell:false —
@@ -576,6 +592,7 @@ export function registerShellTools(registry: ToolRegistry, opts: ShellToolsOptio
const rootDir = pathMod.resolve(opts.rootDir);
const timeoutSec = opts.timeoutSec ?? DEFAULT_TIMEOUT_SEC;
const maxOutputChars = opts.maxOutputChars ?? DEFAULT_MAX_OUTPUT_CHARS;
const jobs = opts.jobs ?? new JobRegistry();
// Resolved on every dispatch so newly-persisted "always allow"
// prefixes take effect inside the session that added them, not just
// on the next launch. Static arrays are wrapped into a constant
@@ -592,7 +609,7 @@ export function registerShellTools(registry: ToolRegistry, opts: ShellToolsOptio
registry.register({
name: "run_command",
description:
"Run a shell command in the project root and return its combined stdout+stderr. Common read-only inspection and test/lint/typecheck commands run immediately; anything that could mutate state, install dependencies, or touch the network is refused until the user confirms it in the TUI. Prefer this over asking the user to run a command manually — after edits, run the project's tests to verify.",
"Run a shell command in the project root and return its combined stdout+stderr.\n\nConstraints (read these before the first call):\n• ONE process per call, NO shell expansion. `&&`, `||`, `|`, `;`, `>`, `<`, `2>&1` are all rejected up-front — split into separate calls and combine results in reasoning. Example: instead of `grep foo *.ts | wc -l`, use `grep -c foo *.ts`; instead of `cd sub && npm test`, use `npm test --prefix sub` (or whatever --cwd flag the binary accepts).\n• `cd` DOES NOT PERSIST between calls — each call spawns a fresh process rooted at the project. If a tool needs a subdirectory, pass it via the tool's own flag (`npm --prefix`, `cargo -C`, `git -C`, `pytest tests/…`), NOT via a preceding `cd`.\n• Avoid commands with unbounded output (`netstat -ano`, `find /`, etc.) — they waste tokens. Filter at source: `netstat -ano -p TCP`, `find src -name '*.ts'`, `grep -c`, `wc -l`.\n\nCommon read-only inspection and test/lint/typecheck commands run immediately; anything that could mutate state, install dependencies, or touch the network is refused until the user confirms it in the TUI. Prefer this over asking the user to run a command manually — after edits, run the project's tests to verify.",
// Plan-mode gate: allow allowlisted commands through (git status,
// cargo check, ls, grep …) so the model can actually investigate
// during planning. Anything that would otherwise trigger a
@@ -635,9 +652,156 @@ export function registerShellTools(registry: ToolRegistry, opts: ShellToolsOptio
},
});
registry.register({
name: "run_background",
description:
"Spawn a long-running process (dev server, watcher, any command that doesn't naturally exit) and detach. Waits up to `waitSec` seconds for startup (or until the output matches a readiness signal like 'Local:', 'listening on', 'compiled successfully'), then returns the job id + startup preview. The process keeps running; call `job_output` to tail its logs, `stop_job` to kill it, `list_jobs` to see all running jobs.\n\nSame shell constraints as run_command: NO `&&` / `||` / `|` / `;` / `>` / `<` / `2>&1`, `cd` doesn't persist. Dev servers that need a subdirectory: use the tool's own --prefix / --cwd flag. For Vite specifically, `--prefix` on npm only tells npm where package.json is; vite's server root still defaults to process cwd, so pass `vite <project-dir>` or configure via `vite.config.ts` root.\n\nUSE THIS — not `run_command` — for: npm/yarn/pnpm run dev, uvicorn / flask run, go run, cargo watch, tsc --watch, webpack serve, anything with 'dev' / 'serve' / 'watch' in the name.",
parameters: {
type: "object",
properties: {
command: {
type: "string",
description:
"Full command line. Same quoting rules as run_command (no pipes / redirects / chaining).",
},
waitSec: {
type: "integer",
description:
"Max seconds to wait for startup before returning. 0..30, default 3. A ready-signal match short-circuits this.",
},
},
required: ["command"],
},
fn: async (args: { command: string; waitSec?: number }, ctx) => {
const cmd = args.command.trim();
if (!cmd) throw new Error("run_background: empty command");
if (!allowAll && !isAllowed(cmd, getExtraAllowed())) {
throw new NeedsConfirmationError(cmd);
}
const result = await jobs.start(cmd, {
cwd: rootDir,
waitSec: args.waitSec,
signal: ctx?.signal,
});
return formatJobStart(result);
},
});
registry.register({
name: "job_output",
description:
"Read the latest output of a background job started with `run_background`. By default returns the tail of the buffer (last 80 lines). Pass `since` (the `byteLength` from a previous call) to stream only new content incrementally. Tells you whether the job is still running, so you can stop polling when it's done.",
readOnly: true,
parameters: {
type: "object",
properties: {
jobId: { type: "integer", description: "Job id returned by run_background." },
since: {
type: "integer",
description:
"Return only output written past this byte offset (for incremental polling).",
},
tailLines: {
type: "integer",
description: "Cap the returned slice to the last N lines. Default 80, 0 = unlimited.",
},
},
required: ["jobId"],
},
fn: async (args: { jobId: number; since?: number; tailLines?: number }) => {
const out = jobs.read(args.jobId, {
since: args.since,
tailLines: args.tailLines ?? 80,
});
if (!out) return `job ${args.jobId}: not found (use list_jobs)`;
return formatJobRead(args.jobId, out);
},
});
registry.register({
name: "stop_job",
description:
"Stop a background job started with `run_background`. SIGTERM first; SIGKILL after a short grace period if it doesn't exit cleanly. Returns the final output + exit code. Safe to call on an already-exited job.",
parameters: {
type: "object",
properties: {
jobId: { type: "integer" },
},
required: ["jobId"],
},
fn: async (args: { jobId: number }) => {
const rec = await jobs.stop(args.jobId);
if (!rec) return `job ${args.jobId}: not found`;
return formatJobStop(rec);
},
});
registry.register({
name: "list_jobs",
description:
"List every background job started this session — running and exited — with id, command, pid, status. Use when you've lost track of which job_id corresponds to which process, or to see what's still alive.",
readOnly: true,
parameters: { type: "object", properties: {} },
fn: async () => {
const all = jobs.list();
if (all.length === 0) return "(no background jobs started this session)";
return all.map(formatJobRow).join("\n");
},
});
return registry;
}
function formatJobStart(r: import("./jobs.js").JobStartResult): string {
const header = r.stillRunning
? `[job ${r.jobId} started · pid ${r.pid ?? "?"} · ${r.readyMatched ? "READY signal matched" : "running (no ready signal yet)"}]`
: r.exitCode !== null
? `[job ${r.jobId} exited during startup · exit ${r.exitCode}]`
: `[job ${r.jobId} failed to start]`;
return r.preview ? `${header}\n${r.preview}` : header;
}
function formatJobRead(jobId: number, r: import("./jobs.js").JobReadResult): string {
const status = r.running
? `running · pid ${r.pid ?? "?"}`
: r.exitCode !== null
? `exited ${r.exitCode}`
: r.spawnError
? `failed (${r.spawnError})`
: "stopped";
const header = `[job ${jobId} · ${status} · byteLength=${r.byteLength}]\n$ ${r.command}`;
return r.output ? `${header}\n${r.output}` : header;
}
function formatJobStop(r: import("./jobs.js").JobRecord): string {
const running = r.running
? "still running (SIGKILL may be pending)"
: `exit ${r.exitCode ?? "?"}`;
const tail = tailLines(r.output, 40);
const header = `[job ${r.id} stopped · ${running}]\n$ ${r.command}`;
return tail ? `${header}\n${tail}` : header;
}
function formatJobRow(r: import("./jobs.js").JobRecord): string {
const age = ((Date.now() - r.startedAt) / 1000).toFixed(1);
const state = r.running
? `running · pid ${r.pid ?? "?"}`
: r.exitCode !== null
? `exit ${r.exitCode}`
: r.spawnError
? "failed"
: "stopped";
return ` ${String(r.id).padStart(3)} ${state.padEnd(24)} ${age}s ago $ ${r.command}`;
}
function tailLines(s: string, n: number): string {
if (!s) return "";
const lines = s.split("\n");
if (lines.length <= n) return s;
const dropped = lines.length - n;
return [`[… ${dropped} earlier lines …]`, ...lines.slice(-n)].join("\n");
}
export function formatCommandResult(cmd: string, r: RunCommandResult): string {
const header = r.timedOut
? `$ ${cmd}\n[killed after timeout]`
+22 -4
View File
@@ -77,7 +77,7 @@ export function registerSkillTools(
registry.register({
name: "run_skill",
description:
"Invoke a playbook from the Skills index pinned in the system prompt. Each entry is a self-contained instruction block. Skills marked with 🧬 in the index spawn an isolated subagent — only the final distilled answer comes back, the model's tool calls + reasoning during the run never enter your context. Plain skills are inlined: the body becomes a tool result you read and follow. For 🧬 subagent skills, supply 'arguments' describing the concrete task — they'll be the only context the subagent has.",
"Invoke a playbook from the Skills index pinned in the system prompt. Each entry is a self-contained instruction block. Pass `name` as the BARE skill identifier (e.g. 'explore'), NOT the `[🧬 subagent]` tag that appears after it in the index. Entries tagged `[🧬 subagent]` spawn an isolated subagent — only the final distilled answer comes back, the model's tool calls + reasoning during the run never enter your context. Plain skills are inlined: the body becomes a tool result you read and follow. For subagent skills, supply 'arguments' describing the concrete task — they'll be the only context the subagent has.",
readOnly: true,
parameters: {
type: "object",
@@ -90,16 +90,34 @@ export function registerSkillTools(
arguments: {
type: "string",
description:
"Free-form arguments the skill should act on. For inline skills: appended to the body as an 'Arguments:' line; the skill's own instructions decide how to consume them. For 🧬 subagent skills: REQUIRED — becomes the entire task description the subagent receives, since it has no other context.",
"Free-form arguments the skill should act on. For inline skills: appended to the body as an 'Arguments:' line; the skill's own instructions decide how to consume them. For `[🧬 subagent]` skills: REQUIRED — becomes the entire task description the subagent receives, since it has no other context.",
},
},
required: ["name"],
},
fn: async (args: { name?: unknown; arguments?: unknown }) => {
const name = typeof args.name === "string" ? args.name.trim() : "";
if (!name) {
const raw = typeof args.name === "string" ? args.name.trim() : "";
if (!raw) {
return JSON.stringify({ error: "run_skill requires a 'name' argument" });
}
// Defensive: The Skills index writes entries like
// `explore [🧬 subagent]`, and models sometimes copy the
// decoration verbatim into the `name` argument instead of just
// the identifier. Rather than reject those calls:
// 1. Drop any `[...]` bracketed tag (possibly containing
// emoji + "subagent" label).
// 2. Find the first whitespace-delimited token whose first
// char is alphanumeric — that's the skill identifier,
// whether the tag came before or after the name.
const stripped = raw.replace(/\[[^\]]*\]/g, " ").trim();
const tokens = stripped.split(/\s+/).filter(Boolean);
const name = tokens.find((t) => /^[a-zA-Z0-9]/.test(t)) ?? "";
if (!name) {
return JSON.stringify({
error: "run_skill requires a 'name' argument",
hint: `'${raw}' is just a marker/tag, not a skill name`,
});
}
const skill = store.read(name);
if (!skill) {
const available = store
+27 -10
View File
@@ -45,6 +45,11 @@ import { type DeepSeekClient, Usage } from "../client.js";
import { CacheFirstLoop } from "../loop.js";
import { ImmutablePrefix } from "../memory.js";
import { applyProjectMemory } from "../project-memory.js";
import {
ESCALATION_CONTRACT,
NEGATIVE_CLAIM_RULE,
TUI_FORMATTING_RULES,
} from "../prompt-fragments.js";
import { ToolRegistry } from "../tools.js";
/**
@@ -173,7 +178,7 @@ export interface SubagentToolOptions {
defaultSystem?: string;
/** Project root for `applyProjectMemory` lookup. Omit in chat mode. */
projectRoot?: string;
/** Default model. `deepseek-v4-pro` by default. */
/** Default model. `deepseek-v4-flash` by default (see DEFAULT_SUBAGENT_MODEL). */
defaultModel?: string;
/** Iteration ceiling. Lower than the parent (16 by default). */
maxToolIters?: number;
@@ -191,16 +196,24 @@ Rules:
- When you're done, your final assistant message is the only thing the parent will see — make it complete and self-contained. No follow-up offers, no questions, no "let me know if you need more."
- Prefer one clear, distilled answer over a long log of what you tried.
Formatting rules (the parent renders your reply in a TUI with a real markdown renderer):
- For tabular data use GitHub-Flavored Markdown tables with ASCII pipes: \`| col | col |\` headers, \`| --- | --- |\` separator. NEVER draw tables with Unicode box-drawing characters (│ ─ ┼ ┌ ┐ └ ┘ ├ ┤). They look intentional but break terminal word-wrap and produce garbled output.
- Keep table cells short — one short phrase per cell, not multi-line paragraphs. If a description doesn't fit in ~40 chars, use bullets below the table instead.
- Use fenced code blocks (\`\`\`) for any code, file paths with line ranges, or shell commands.
- NEVER draw decorative frames around content with \`┌──┐ │ └──┘\` box-drawing characters. The renderer handles code blocks and headings on its own — extra ASCII art adds noise without value and breaks at narrow terminal widths.
- For flow charts and diagrams: use a markdown bullet list with \`→\` or \`↓\` between steps. Don't try to draw boxes-and-arrows in ASCII; it never survives word-wrap.`;
${NEGATIVE_CLAIM_RULE}
${ESCALATION_CONTRACT}
${TUI_FORMATTING_RULES}`;
const DEFAULT_MAX_RESULT_CHARS = 8000;
const DEFAULT_MAX_ITERS = 16;
const DEFAULT_SUBAGENT_MODEL = "deepseek-v4-pro";
// Subagents default to flash — their work is read-and-synthesize
// (explore, research), which doesn't need the 12× pro tier. Skill
// frontmatter `model: deepseek-v4-pro` is the opt-in override for
// skills that empirically benefit from the stronger model.
const DEFAULT_SUBAGENT_MODEL = "deepseek-v4-flash";
// Subagents default to effort=high — less thinking budget than a
// main turn (which defaults to `max` in the preset). The parent's
// task arg is already a distilled prompt; explore/research rarely
// need deep chains of thought, and `high` saves output tokens.
const DEFAULT_SUBAGENT_EFFORT: "high" | "max" = "high";
const SUBAGENT_TOOL_NAME = "spawn_subagent";
/**
@@ -250,6 +263,10 @@ export async function spawnSubagent(opts: SpawnSubagentOptions): Promise<Subagen
prefix: childPrefix,
tools: childTools,
model,
// Subagents run on a constrained thinking budget by default — the
// task is already narrow by construction, and `high` cuts output
// tokens substantially vs `max`.
reasoningEffort: DEFAULT_SUBAGENT_EFFORT,
maxToolIters,
hooks: [],
stream: false,
@@ -423,9 +440,9 @@ export function registerSubagentTool(
},
model: {
type: "string",
enum: ["deepseek-v4-flash", "deepseek-v4-pro", "deepseek-chat", "deepseek-reasoner"],
enum: ["deepseek-v4-flash", "deepseek-v4-pro"],
description:
"Which DeepSeek model the subagent runs on. Default is 'deepseek-v4-pro' — 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 — flash is roughly 12× cheaper.",
"Which DeepSeek model the subagent runs on. Default is 'deepseek-v4-flash' — cheap and fast, fine for explore/research-style subtasks. Override to 'deepseek-v4-pro' (~12× more expensive) when the subtask genuinely needs the stronger model: cross-file architecture, subtle bug hunts, anything where flash has empirically underperformed.",
},
},
required: ["task"],
+1 -1
View File
@@ -243,7 +243,7 @@ export function registerWebTools(registry: ToolRegistry, opts: WebToolsOptions =
registry.register({
name: "web_search",
description:
"Search the public web. Returns ranked results with title, url, and snippet. Use this when the question needs information more current than your training data, when you're unsure of a factual detail, or when the user asks about a specific webpage/library/release you haven't seen.",
"Search the public web. Returns ranked results with title, url, and snippet. Call this when the answer's correctness depends on current state — anything that changes over time (events, prices, releases, status of a thing in the real world). Composing such answers from training memory invents stale numbers; search first, then ground the answer in the results. For evergreen / definitional questions you don't need this.",
readOnly: true,
parameters: {
type: "object",
+197
View File
@@ -0,0 +1,197 @@
/**
* ask_choice — the branching primitive that keeps A/B/C decisions out
* of submit_plan. Covers the schema, the sanitization layer (DeepSeek
* sometimes emits malformed options arrays even with auto-flatten),
* and the ChoiceRequestedError toToolResult protocol.
*/
import { describe, expect, it } from "vitest";
import { ToolRegistry } from "../src/tools.js";
import { ChoiceRequestedError, registerChoiceTool } from "../src/tools/choice.js";
describe("ChoiceRequestedError", () => {
it("carries the question / options / allowCustom on the instance and in toToolResult()", () => {
const err = new ChoiceRequestedError(
"Which framework?",
[
{ id: "A", title: "Vitest" },
{ id: "B", title: "Jest", summary: "familiar to most" },
],
true,
);
expect(err.name).toBe("ChoiceRequestedError");
expect(err.question).toBe("Which framework?");
expect(err.options).toHaveLength(2);
expect(err.allowCustom).toBe(true);
const payload = err.toToolResult();
expect(payload.question).toBe("Which framework?");
expect(payload.options).toEqual([
{ id: "A", title: "Vitest" },
{ id: "B", title: "Jest", summary: "familiar to most" },
]);
expect(payload.allowCustom).toBe(true);
expect(payload.error).toMatch(/^ChoiceRequestedError:/);
// STOP instruction — same pattern as PlanProposedError so flash
// doesn't race past the picker with more tool calls.
expect(payload.error).toMatch(/STOP/);
});
});
describe("registerChoiceTool + ask_choice", () => {
it("registers ask_choice as readOnly (safe during plan mode too)", () => {
const reg = new ToolRegistry();
registerChoiceTool(reg);
expect(reg.has("ask_choice")).toBe(true);
expect(reg.get("ask_choice")?.readOnly).toBe(true);
});
it("throws ChoiceRequestedError and surfaces the full payload via toToolResult", async () => {
const reg = new ToolRegistry();
const seen: Array<{ question: string; options: unknown }> = [];
registerChoiceTool(reg, {
onChoiceRequested: (q, o) => seen.push({ question: q, options: o }),
});
const out = await reg.dispatch(
"ask_choice",
JSON.stringify({
question: "Pick a route.",
options: [
{ id: "A", title: "Deepen demo" },
{ id: "B", title: "Start UE5", summary: "fresh engine" },
],
allowCustom: true,
}),
);
const parsed = JSON.parse(out);
expect(parsed.question).toBe("Pick a route.");
expect(parsed.options).toEqual([
{ id: "A", title: "Deepen demo" },
{ id: "B", title: "Start UE5", summary: "fresh engine" },
]);
expect(parsed.allowCustom).toBe(true);
expect(parsed.error).toMatch(/^ChoiceRequestedError:/);
expect(seen).toHaveLength(1);
expect(seen[0]?.question).toBe("Pick a route.");
});
it("defaults allowCustom to false when not provided", async () => {
const reg = new ToolRegistry();
registerChoiceTool(reg);
const out = await reg.dispatch(
"ask_choice",
JSON.stringify({
question: "Which one?",
options: [
{ id: "A", title: "one" },
{ id: "B", title: "two" },
],
}),
);
expect(JSON.parse(out).allowCustom).toBe(false);
});
it("drops malformed option entries (DeepSeek sometimes misses fields)", async () => {
const reg = new ToolRegistry();
registerChoiceTool(reg);
const out = await reg.dispatch(
"ask_choice",
JSON.stringify({
question: "Pick.",
options: [
{ id: "A", title: "good" },
{ id: "", title: "no id" },
{ id: "B", title: "" },
"not-an-object",
null,
{ id: "C", title: "also good" },
],
}),
);
const parsed = JSON.parse(out);
expect(parsed.options).toEqual([
{ id: "A", title: "good" },
{ id: "C", title: "also good" },
]);
});
it("deduplicates options with the same id (first one wins)", async () => {
const reg = new ToolRegistry();
registerChoiceTool(reg);
const out = await reg.dispatch(
"ask_choice",
JSON.stringify({
question: "Pick.",
options: [
{ id: "A", title: "first" },
{ id: "A", title: "dup" },
{ id: "B", title: "second" },
],
}),
);
const parsed = JSON.parse(out);
expect(parsed.options).toEqual([
{ id: "A", title: "first" },
{ id: "B", title: "second" },
]);
});
it("rejects an empty question", async () => {
const reg = new ToolRegistry();
registerChoiceTool(reg);
const out = await reg.dispatch(
"ask_choice",
JSON.stringify({
question: " ",
options: [
{ id: "A", title: "one" },
{ id: "B", title: "two" },
],
}),
);
expect(JSON.parse(out).error).toMatch(/question is required/);
});
it("rejects when fewer than 2 well-formed options remain", async () => {
const reg = new ToolRegistry();
registerChoiceTool(reg);
const out = await reg.dispatch(
"ask_choice",
JSON.stringify({
question: "Pick.",
options: [{ id: "A", title: "only one" }],
}),
);
expect(JSON.parse(out).error).toMatch(/at least 2 well-formed options/);
});
it("rejects runaway option lists (>6 entries)", async () => {
const reg = new ToolRegistry();
registerChoiceTool(reg);
const options = Array.from({ length: 7 }, (_, i) => ({
id: `opt-${i}`,
title: `option ${i}`,
}));
const out = await reg.dispatch("ask_choice", JSON.stringify({ question: "too many", options }));
expect(JSON.parse(out).error).toMatch(/too many options/);
});
it("keeps the tool passable in plan mode (branching questions can fire mid-plan)", async () => {
const reg = new ToolRegistry();
registerChoiceTool(reg);
reg.setPlanMode(true);
const out = await reg.dispatch(
"ask_choice",
JSON.stringify({
question: "Which branch?",
options: [
{ id: "A", title: "a" },
{ id: "B", title: "b" },
],
}),
);
const parsed = JSON.parse(out);
// Plan mode doesn't block ask_choice — it's readOnly.
expect(parsed.error).toMatch(/^ChoiceRequestedError:/);
expect(parsed.options).toHaveLength(2);
});
});
+106 -1
View File
@@ -1,5 +1,8 @@
import { describe, expect, it } from "vitest";
import { shrinkOversizedToolResultsByTokens } from "../src/loop.js";
import {
shrinkOversizedToolCallArgsByTokens,
shrinkOversizedToolResultsByTokens,
} from "../src/loop.js";
import { countTokens } from "../src/tokenizer.js";
import type { ChatMessage } from "../src/types.js";
@@ -72,3 +75,105 @@ describe("shrinkOversizedToolResultsByTokens", () => {
expect(r.messages[0]!.content).toBe(content);
});
});
describe("shrinkOversizedToolCallArgsByTokens", () => {
it("leaves small tool-call args alone", () => {
const msgs: ChatMessage[] = [
{
role: "assistant",
content: null,
tool_calls: [
{
id: "c1",
type: "function",
function: { name: "read_file", arguments: '{"path":"src/foo.ts"}' },
},
],
},
];
const r = shrinkOversizedToolCallArgsByTokens(msgs, 1000);
expect(r.healedCount).toBe(0);
expect(r.messages).toEqual(msgs);
});
it("shrinks long edit_file search/replace payloads into markers", () => {
const longSearch = "old code line\n".repeat(200);
const longReplace = "new code line\n".repeat(300);
const argsJson = JSON.stringify({
path: "src/foo.ts",
search: longSearch,
replace: longReplace,
});
const msgs: ChatMessage[] = [
{
role: "assistant",
content: null,
tool_calls: [
{ id: "c1", type: "function", function: { name: "edit_file", arguments: argsJson } },
],
},
{ role: "tool", tool_call_id: "c1", content: "applied" },
];
const r = shrinkOversizedToolCallArgsByTokens(msgs, 500);
expect(r.healedCount).toBe(1);
expect(r.tokensSaved).toBeGreaterThan(0);
expect(r.charsSaved).toBeGreaterThan(0);
const a = r.messages[0];
if (a?.role !== "assistant" || !a.tool_calls) throw new Error("assistant missing");
const shrunkArgs = a.tool_calls[0]!.function.arguments;
const parsed = JSON.parse(shrunkArgs) as { path: string; search: string; replace: string };
expect(parsed.path).toBe("src/foo.ts");
expect(parsed.search).toMatch(/shrunk/);
expect(parsed.replace).toMatch(/shrunk/);
});
it("leaves tool results intact (only targets assistant.tool_calls args)", () => {
const hugeResult = "log line ".repeat(2000);
const msgs: ChatMessage[] = [{ role: "tool", tool_call_id: "c1", content: hugeResult }];
const r = shrinkOversizedToolCallArgsByTokens(msgs, 100);
expect(r.healedCount).toBe(0);
expect(r.messages[0]!.content).toBe(hugeResult);
});
it("preserves short string fields next to long ones", () => {
const longBody = "x".repeat(4000);
const argsJson = JSON.stringify({
path: "src/foo.ts",
content: longBody,
mode: "append",
});
const msgs: ChatMessage[] = [
{
role: "assistant",
content: null,
tool_calls: [
{ id: "c1", type: "function", function: { name: "write_file", arguments: argsJson } },
],
},
];
const r = shrinkOversizedToolCallArgsByTokens(msgs, 500);
expect(r.healedCount).toBe(1);
const a = r.messages[0];
if (a?.role !== "assistant" || !a.tool_calls) throw new Error("assistant missing");
const parsed = JSON.parse(a.tool_calls[0]!.function.arguments) as Record<string, unknown>;
expect(parsed.path).toBe("src/foo.ts");
expect(parsed.mode).toBe("append");
expect(String(parsed.content)).toMatch(/shrunk/);
});
it("never mutates the input array or its tool_calls", () => {
const bigArgs = JSON.stringify({ path: "a", search: "x".repeat(4000) });
const msgs: ChatMessage[] = [
{
role: "assistant",
content: null,
tool_calls: [
{ id: "c1", type: "function", function: { name: "edit_file", arguments: bigArgs } },
],
},
];
const originalArgs = (msgs[0] as any).tool_calls[0].function.arguments;
shrinkOversizedToolCallArgsByTokens(msgs, 100);
expect((msgs[0] as any).tool_calls[0].function.arguments).toBe(originalArgs);
});
});
+55
View File
@@ -4,12 +4,18 @@ import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import {
addProjectShellAllowed,
editModeHintShown,
isPlausibleKey,
loadApiKey,
loadEditMode,
loadProjectShellAllowed,
loadReasoningEffort,
markEditModeHintShown,
readConfig,
redactKey,
saveApiKey,
saveEditMode,
saveReasoningEffort,
searchEnabled,
writeConfig,
} from "../src/config.js";
@@ -166,4 +172,53 @@ describe("config", () => {
addProjectShellAllowed("/a", " ", path);
expect(loadProjectShellAllowed("/a", path)).toEqual([]);
});
it("loadEditMode defaults to 'review' when unset", () => {
expect(loadEditMode(path)).toBe("review");
});
it("saveEditMode + loadEditMode round-trip 'auto'", () => {
saveEditMode("auto", path);
expect(loadEditMode(path)).toBe("auto");
// Doesn't clobber other fields in the config.
expect(readConfig(path).editMode).toBe("auto");
});
it("loadEditMode coerces unknown values back to 'review'", () => {
writeConfig({ editMode: "garbage" as any }, path);
expect(loadEditMode(path)).toBe("review");
});
it("loadReasoningEffort defaults to 'max' when unset", () => {
expect(loadReasoningEffort(path)).toBe("max");
});
it("saveReasoningEffort + loadReasoningEffort round-trip 'high'", () => {
saveReasoningEffort("high", path);
expect(loadReasoningEffort(path)).toBe("high");
expect(readConfig(path).reasoningEffort).toBe("high");
});
it("loadReasoningEffort coerces unknown values back to 'max'", () => {
writeConfig({ reasoningEffort: "turbo" as any }, path);
expect(loadReasoningEffort(path)).toBe("max");
});
it("saveReasoningEffort doesn't clobber other persisted fields", () => {
saveEditMode("auto", path);
saveReasoningEffort("high", path);
expect(loadEditMode(path)).toBe("auto");
expect(loadReasoningEffort(path)).toBe("high");
});
it("editModeHintShown defaults to false and toggles on markEditModeHintShown", () => {
expect(editModeHintShown(path)).toBe(false);
markEditModeHintShown(path);
expect(editModeHintShown(path)).toBe(true);
// Idempotent — calling again doesn't rewrite or clobber other fields.
saveEditMode("auto", path);
markEditModeHintShown(path);
expect(editModeHintShown(path)).toBe(true);
expect(loadEditMode(path)).toBe("auto");
});
});
+31
View File
@@ -15,6 +15,7 @@ import {
parseEditBlocks,
restoreSnapshots,
snapshotBeforeEdits,
toWholeFileEditBlock,
} from "../src/code/edit-blocks.js";
describe("parseEditBlocks", () => {
@@ -237,6 +238,36 @@ describe("snapshotBeforeEdits + restoreSnapshots", () => {
});
});
describe("toWholeFileEditBlock", () => {
let root: string;
beforeEach(() => {
root = mkdtempSync(join(tmpdir(), "reasonix-whole-"));
});
afterEach(() => {
rmSync(root, { recursive: true, force: true });
});
it("captures existing content as SEARCH for overwrites", () => {
writeFileSync(join(root, "hello.txt"), "old content\n", "utf8");
const block = toWholeFileEditBlock("hello.txt", "new content\n", root);
expect(block.search).toBe("old content\n");
expect(block.replace).toBe("new content\n");
// Round-trip: applying this block swaps the whole file.
const [res] = applyEditBlocks([block], root);
expect(res!.status).toBe("applied");
expect(readFileSync(join(root, "hello.txt"), "utf8")).toBe("new content\n");
});
it("leaves SEARCH empty when the file doesn't exist (create-new sentinel)", () => {
const block = toWholeFileEditBlock("new.txt", "fresh\n", root);
expect(block.search).toBe("");
expect(block.replace).toBe("fresh\n");
const [res] = applyEditBlocks([block], root);
expect(res!.status).toBe("created");
expect(readFileSync(join(root, "new.txt"), "utf8")).toBe("fresh\n");
});
});
describe("applyEditBlocks (batch)", () => {
let root: string;
beforeEach(() => {
+107 -1
View File
@@ -33,7 +33,11 @@ describe("filesystem tools (built-in, sandbox-enforced)", () => {
it("honors head=N to return only the first N lines", async () => {
const out = await tools.dispatch("read_file", JSON.stringify({ path: "hello.txt", head: 2 }));
expect(out).toBe("line 1\nline 2");
// Head output now includes an "N of M lines" marker so the model
// knows it didn't get the whole file. The actual content still
// leads the string, un-escaped.
expect(out).toMatch(/^line 1\nline 2/);
expect(out).toMatch(/head 2 of 3 lines/);
});
it("honors tail=N", async () => {
@@ -41,6 +45,56 @@ describe("filesystem tools (built-in, sandbox-enforced)", () => {
expect(out).toContain("line 2");
expect(out).toContain("line 3");
expect(out).not.toContain("line 1");
expect(out).toMatch(/tail 2 of 3 lines/);
});
it("range='A-B' returns the inclusive line range", async () => {
// Write a bigger file so the range slice is distinguishable from
// the head/tail paths and the auto-preview cutover.
await fs.writeFile(
join(root, "big.txt"),
Array.from({ length: 10 }, (_, i) => `line ${i + 1}`).join("\n"),
);
const out = await tools.dispatch(
"read_file",
JSON.stringify({ path: "big.txt", range: "3-5" }),
);
expect(out).toMatch(/\[range 3-5 of 10 lines\]/);
expect(out).toContain("line 3");
expect(out).toContain("line 5");
expect(out).not.toContain("line 2");
expect(out).not.toContain("line 6");
});
it("range clamps out-of-range values to the file bounds", async () => {
const out = await tools.dispatch(
"read_file",
JSON.stringify({ path: "hello.txt", range: "2-99" }),
);
expect(out).toMatch(/\[range 2-3 of 3 lines\]/);
expect(out).toContain("line 2");
expect(out).toContain("line 3");
});
it("auto-previews large files when no scope is given", async () => {
// File larger than DEFAULT_AUTO_PREVIEW_LINES (200) triggers the
// head+tail preview + omitted-lines marker.
const bigLines = Array.from({ length: 250 }, (_, i) => `line ${i + 1}`);
await fs.writeFile(join(root, "huge.txt"), bigLines.join("\n"));
const out = await tools.dispatch("read_file", JSON.stringify({ path: "huge.txt" }));
expect(out).toMatch(/auto-preview: head 80 \+ tail 40 of 250 lines/);
expect(out).toMatch(/130 lines omitted/);
expect(out).toContain("line 1");
expect(out).toContain("line 80");
expect(out).toContain("line 211");
expect(out).toContain("line 250");
expect(out).not.toContain("line 100");
expect(out).not.toContain("line 200");
});
it("returns full content when file is at or below the auto-preview threshold", async () => {
const out = await tools.dispatch("read_file", JSON.stringify({ path: "hello.txt" }));
expect(out).toBe("line 1\nline 2\nline 3");
});
it("rejects paths outside the sandbox root", async () => {
@@ -97,6 +151,58 @@ describe("filesystem tools (built-in, sandbox-enforced)", () => {
expect(out).toContain("src/");
expect(out).not.toContain("index.ts");
});
it("directory_tree skips node_modules / .git / dist by default", async () => {
await fs.mkdir(join(root, "node_modules", "foo"), { recursive: true });
await fs.writeFile(join(root, "node_modules", "foo", "dep.js"), "// dep\n");
await fs.mkdir(join(root, ".git"), { recursive: true });
await fs.writeFile(join(root, ".git", "HEAD"), "ref\n");
await fs.mkdir(join(root, "dist"), { recursive: true });
await fs.writeFile(join(root, "dist", "out.js"), "// out\n");
const out = await tools.dispatch("directory_tree", JSON.stringify({ path: "." }));
// Skip markers show the dir exists but don't walk into it.
expect(out).toMatch(/node_modules\/\s+\(skipped/);
expect(out).toMatch(/\.git\/\s+\(skipped/);
expect(out).toMatch(/dist\/\s+\(skipped/);
expect(out).not.toContain("dep.js");
expect(out).not.toContain("HEAD");
expect(out).not.toContain("out.js");
});
it("directory_tree traverses deps when include_deps:true", async () => {
await fs.mkdir(join(root, "node_modules", "foo"), { recursive: true });
await fs.writeFile(join(root, "node_modules", "foo", "dep.js"), "// dep\n");
const out = await tools.dispatch(
"directory_tree",
JSON.stringify({ path: ".", include_deps: true, maxDepth: 3 }),
);
expect(out).toContain("dep.js");
expect(out).not.toMatch(/skipped/);
});
it("directory_tree default maxDepth is 2", async () => {
await fs.mkdir(join(root, "a", "b", "c"), { recursive: true });
await fs.writeFile(join(root, "a", "b", "c", "deep.txt"), "x\n");
await fs.writeFile(join(root, "a", "b", "shallow.txt"), "y\n");
const out = await tools.dispatch("directory_tree", JSON.stringify({ path: "." }));
// depth 2 shows a/, a/b/, a/b/shallow.txt — but NOT a/b/c's children.
expect(out).toContain("shallow.txt");
expect(out).toContain("c/");
expect(out).not.toContain("deep.txt");
});
it("directory_tree collapses directories with >50 entries", async () => {
await fs.mkdir(join(root, "huge"), { recursive: true });
for (let i = 0; i < 60; i++) {
await fs.writeFile(join(root, "huge", `f${String(i).padStart(3, "0")}.txt`), "x");
}
const out = await tools.dispatch(
"directory_tree",
JSON.stringify({ path: "huge", maxDepth: 1 }),
);
expect(out).toMatch(/\[… \d+ entries hidden/);
expect(out).toMatch(/list_directory/);
});
});
describe("search_files", () => {
+180
View File
@@ -0,0 +1,180 @@
/**
* JobRegistry — background-process lifecycle. Each test uses a real
* child process via `node -e "..."` so we actually exercise the spawn/
* pipe/kill plumbing. Inline scripts keep fixtures self-contained; no
* temp files to clean up.
*/
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { JobRegistry } from "../src/tools/jobs.js";
describe("JobRegistry", () => {
let cwd: string;
let registry: JobRegistry;
beforeEach(() => {
cwd = mkdtempSync(join(tmpdir(), "reasonix-job-"));
registry = new JobRegistry();
});
afterEach(async () => {
await registry.shutdown(1500);
// Windows occasionally hangs on to the cwd handle for a few ms
// after the child exits; a retry-with-delay catches that without
// failing the suite when cleanup is a lost cause.
for (let i = 0; i < 5; i++) {
try {
rmSync(cwd, { recursive: true, force: true });
break;
} catch {
await new Promise((r) => setTimeout(r, 100));
}
}
});
it("returns after waitSec for a process that stays alive", async () => {
// Long-lived child that prints a line and sleeps 10s. We'll return
// after waitSec=1 while it's still running.
const cmd = `node -e "console.log('hi'); setTimeout(() => {}, 10000)"`;
const t0 = Date.now();
const res = await registry.start(cmd, { cwd, waitSec: 1 });
const elapsed = Date.now() - t0;
expect(res.stillRunning).toBe(true);
expect(res.preview).toContain("hi");
expect(elapsed).toBeGreaterThanOrEqual(900);
// readiness pattern may or may not match "hi" depending on env;
// the test's primary claim is "we came back without waiting 10s".
expect(elapsed).toBeLessThan(3000);
});
it("short-circuits on ready signal before waitSec elapses", async () => {
// Print a known ready banner immediately; waitSec=5 should be
// cut short when the regex fires.
const cmd = `node -e "console.log('listening on http://localhost:1234'); setTimeout(() => {}, 10000)"`;
const t0 = Date.now();
const res = await registry.start(cmd, { cwd, waitSec: 5 });
const elapsed = Date.now() - t0;
expect(res.stillRunning).toBe(true);
expect(res.readyMatched).toBe(true);
// Must be well under the 5s ceiling — startup + ready-regex match
// should land in a few hundred ms at most.
expect(elapsed).toBeLessThan(2500);
});
it("captures exit code when the child dies during wait", async () => {
const cmd = `node -e "console.log('bye'); process.exit(7)"`;
const res = await registry.start(cmd, { cwd, waitSec: 3 });
expect(res.stillRunning).toBe(false);
expect(res.exitCode).toBe(7);
expect(res.preview).toContain("bye");
});
it("read(jobId) returns live output and running flag", async () => {
const cmd = `node -e "console.log('a'); setTimeout(() => console.log('b'), 80); setTimeout(() => {}, 10000)"`;
const res = await registry.start(cmd, { cwd, waitSec: 0.3 });
const early = registry.read(res.jobId);
expect(early?.running).toBe(true);
expect(early?.output).toContain("a");
// Wait for the second print, then re-read.
await new Promise((r) => setTimeout(r, 300));
const later = registry.read(res.jobId);
expect(later?.output).toContain("b");
expect((later?.byteLength ?? 0) >= (early?.byteLength ?? 0)).toBe(true);
});
it("read supports `since` for incremental polling", async () => {
// `first` prints synchronously at child startup so snap catches it
// reliably; `second` is delayed well past the waitSec ceiling so it
// arrives AFTER the snapshot, guaranteeing the `since`-slice actually
// has new bytes to return.
const cmd = `node -e "console.log('first'); setTimeout(()=>console.log('second'), 1500); setTimeout(()=>{}, 10000)"`;
const res = await registry.start(cmd, { cwd, waitSec: 0.6 });
// Poll briefly in case Windows node startup is slow — we need
// `first` in the buffer before capturing the cursor, otherwise the
// whole premise of the test falls apart.
let snap = registry.read(res.jobId);
for (let i = 0; i < 10 && !snap?.output.includes("first"); i++) {
await new Promise((r) => setTimeout(r, 100));
snap = registry.read(res.jobId);
}
expect(snap?.output).toContain("first");
expect(snap?.output).not.toContain("second");
const cursor = snap?.byteLength ?? 0;
expect(cursor).toBeGreaterThan(0);
// Wait past the delayed print so we have new content.
await new Promise((r) => setTimeout(r, 1800));
const delta = registry.read(res.jobId, { since: cursor });
expect(delta?.output).not.toContain("first");
expect(delta?.output).toContain("second");
});
it("tailLines caps returned output to the last N lines", async () => {
const cmd = `node -e "for (let i=0;i<50;i++) console.log('line'+i); setTimeout(()=>{}, 10000)"`;
const res = await registry.start(cmd, { cwd, waitSec: 0.5 });
const tailed = registry.read(res.jobId, { tailLines: 5 });
const lines = (tailed?.output ?? "").split("\n").filter(Boolean);
expect(lines.length).toBeLessThanOrEqual(5);
expect(tailed?.output).toContain("line49");
expect(tailed?.output).not.toContain("line0\n");
});
it("stop() kills a running job", async () => {
const cmd = `node -e "setTimeout(()=>{}, 10000)"`;
const res = await registry.start(cmd, { cwd, waitSec: 0.2 });
expect(res.stillRunning).toBe(true);
const rec = await registry.stop(res.jobId, { graceMs: 200 });
expect(rec?.running).toBe(false);
});
it("stop() on an already-exited job is idempotent", async () => {
const cmd = `node -e "process.exit(0)"`;
const res = await registry.start(cmd, { cwd, waitSec: 2 });
expect(res.stillRunning).toBe(false);
const rec = await registry.stop(res.jobId);
expect(rec?.running).toBe(false);
expect(rec?.exitCode).toBe(0);
});
it("list() reports running and exited jobs together", async () => {
const running = await registry.start(`node -e "setTimeout(()=>{}, 10000)"`, {
cwd,
waitSec: 0.2,
});
const exited = await registry.start(`node -e "process.exit(0)"`, { cwd, waitSec: 2 });
const rows = registry.list();
expect(rows).toHaveLength(2);
const r1 = rows.find((r) => r.id === running.jobId);
const r2 = rows.find((r) => r.id === exited.jobId);
expect(r1?.running).toBe(true);
expect(r2?.running).toBe(false);
expect(r2?.exitCode).toBe(0);
});
it("runningCount() reflects live state", async () => {
expect(registry.runningCount()).toBe(0);
const a = await registry.start(`node -e "setTimeout(()=>{}, 10000)"`, { cwd, waitSec: 0.2 });
expect(registry.runningCount()).toBe(1);
await registry.stop(a.jobId);
expect(registry.runningCount()).toBe(0);
});
it("rejects shell operators with a clear message", async () => {
await expect(registry.start("echo hi | grep h", { cwd })).rejects.toThrow(/shell operator/);
});
it("read() returns null for unknown job id", () => {
expect(registry.read(999)).toBeNull();
});
it("shutdown() kills all running jobs", async () => {
await registry.start(`node -e "setTimeout(()=>{}, 10000)"`, { cwd, waitSec: 0.2 });
await registry.start(`node -e "setTimeout(()=>{}, 10000)"`, { cwd, waitSec: 0.2 });
expect(registry.runningCount()).toBe(2);
// 4s deadline: Windows taskkill /T is async and needs ~500-800ms
// per process to propagate through the tree + reap confirmation.
await registry.shutdown(4000);
expect(registry.runningCount()).toBe(0);
});
});
+102 -1
View File
@@ -9,7 +9,12 @@
import { describe, expect, it, vi } from "vitest";
import { DeepSeekClient } from "../src/client.js";
import { CacheFirstLoop, isThinkingModeModel, thinkingModeForModel } from "../src/loop.js";
import {
CacheFirstLoop,
isThinkingModeModel,
stampMissingReasoningForThinkingMode,
thinkingModeForModel,
} from "../src/loop.js";
import { ImmutablePrefix } from "../src/memory.js";
import { ToolRegistry } from "../src/tools.js";
import type { ChatMessage } from "../src/types.js";
@@ -105,6 +110,41 @@ function capturingFetch(responses: FakeResponseShape[]): {
return { fetch: fn, bodies };
}
describe("stampMissingReasoningForThinkingMode (session-load heal)", () => {
it("stamps empty reasoning_content on assistant turns missing the field for thinking-mode sessions", () => {
const msgs: ChatMessage[] = [
{ role: "user", content: "hi" },
// Pre-fix session: no reasoning_content attached.
{ role: "assistant", content: "hello" },
{ role: "user", content: "again" },
{ role: "assistant", content: "b", reasoning_content: "kept" },
];
const { messages, stampedCount } = stampMissingReasoningForThinkingMode(
msgs,
"deepseek-reasoner",
);
expect(stampedCount).toBe(1);
expect(messages[1]!.reasoning_content).toBe("");
expect(messages[3]!.reasoning_content).toBe("kept");
});
it("no-ops on non-thinking-mode sessions (deepseek-chat stays clean)", () => {
const msgs: ChatMessage[] = [
{ role: "user", content: "hi" },
{ role: "assistant", content: "hello" },
];
const { messages, stampedCount } = stampMissingReasoningForThinkingMode(msgs, "deepseek-chat");
expect(stampedCount).toBe(0);
expect(Object.hasOwn(messages[1]!, "reasoning_content")).toBe(false);
});
it("preserves existing empty-string reasoning_content without double-stamping", () => {
const msgs: ChatMessage[] = [{ role: "assistant", content: "hi", reasoning_content: "" }];
const { stampedCount } = stampMissingReasoningForThinkingMode(msgs, "deepseek-v4-pro");
expect(stampedCount).toBe(0);
});
});
describe("R1 reasoning_content round-trip", () => {
it("preserves reasoning_content on the assistant message when the turn has tool_calls", async () => {
const tools = new ToolRegistry();
@@ -190,6 +230,67 @@ describe("R1 reasoning_content round-trip", () => {
expect(assistant?.reasoning_content).toBe("reasoning attached to a plain-text turn");
});
it("stamps empty reasoning_content on a thinking-mode turn that returned null reasoning", async () => {
// 0.5.18 covered "reasoner turn with reasoning present." This is
// the inverse: thinking-mode model returns `reasoning_content:
// null` (legitimate edge case — zero reasoning deltas on a flash
// turn, or forced-summary paths that don't emit reasoning). Prior
// behavior was `if (reasoning.length > 0)` which silently dropped
// the field, and the NEXT API call 400'd. Invariant is now keyed
// to the producing model, not to whether reasoning arrived.
const { fetch: fakeFetch, bodies } = capturingFetch([
{ content: "straight answer", reasoning_content: undefined },
{ content: "follow-up" },
]);
const client = new DeepSeekClient({ apiKey: "sk-test", fetch: fakeFetch });
const loop = new CacheFirstLoop({
client,
prefix: new ImmutablePrefix({ system: "s" }),
model: "deepseek-v4-flash",
stream: false,
});
for await (const _ev of loop.step("hello")) {
/* drain */
}
for await (const _ev of loop.step("next")) {
/* drain */
}
const turn2Messages = bodies[1]!.messages;
const assistant = turn2Messages.find((m) => m.role === "assistant");
expect(assistant).toBeDefined();
// Field must be PRESENT (even empty) — presence is what satisfies
// DeepSeek's thinking-mode validator.
expect(Object.hasOwn(assistant!, "reasoning_content")).toBe(true);
expect(assistant?.reasoning_content).toBe("");
});
it("does NOT stamp reasoning_content on a deepseek-chat turn that returned null", async () => {
// Mirror image: non-thinking-mode sessions must stay clean —
// sending an empty string here would still be valid per the API
// but would needlessly churn the prefix cache across V3 calls.
const { fetch: fakeFetch, bodies } = capturingFetch([
{ content: "hi", reasoning_content: undefined },
{ content: "bye" },
]);
const client = new DeepSeekClient({ apiKey: "sk-test", fetch: fakeFetch });
const loop = new CacheFirstLoop({
client,
prefix: new ImmutablePrefix({ system: "s" }),
model: "deepseek-chat",
stream: false,
});
for await (const _ev of loop.step("hello")) {
/* drain */
}
for await (const _ev of loop.step("next")) {
/* drain */
}
const turn2Messages = bodies[1]!.messages;
const assistant = turn2Messages.find((m) => m.role === "assistant");
expect(assistant).toBeDefined();
expect(Object.hasOwn(assistant!, "reasoning_content")).toBe(false);
});
it("pins thinking=enabled + reasoning_effort=max for v4-pro (agent-class default)", async () => {
const { fetch: fakeFetch, bodies } = capturingFetch([{ content: "done" }]);
const client = new DeepSeekClient({ apiKey: "sk-test", fetch: fakeFetch });
+214
View File
@@ -380,6 +380,62 @@ describe("CacheFirstLoop (non-streaming)", () => {
expect(events[events.length - 1]!.role).toBe("done");
});
it("storm-broken-all-suppressed forces a summary instead of stopping silently", async () => {
// Repro of the user-reported "怎么就直接停了" — model loops on the
// same broken tool call (e.g. read_file with empty path), the
// storm-breaker suppresses every call after the threshold, and
// pre-fix the loop would yield `done` with no prose. Fix routes
// through forceSummaryAfterIterLimit so the model gets one
// no-tools call to explain what was tried + what's blocking.
const reg = new ToolRegistry();
reg.register({
name: "probe",
description: "no-op",
parameters: { type: "object", properties: {} },
fn: async () => "ok",
});
// Same (name, args) signature each iter — storm-breaker fires on
// the third identical call. Threshold = 3, window = 6 (defaults).
const dupCall = {
id: "c1",
type: "function",
function: { name: "probe", arguments: "{}" },
};
const responses: FakeResponseShape[] = [
{ content: "", tool_calls: [dupCall] },
{ content: "", tool_calls: [{ ...dupCall, id: "c2" }] },
{ content: "", tool_calls: [{ ...dupCall, id: "c3" }] },
// Forced-summary call — no tools advertised, model just narrates.
{
content:
"I tried probe(no args) three times — same result each call. Need a different approach.",
},
];
const client = makeClient(responses);
const loop = new CacheFirstLoop({
client,
prefix: new ImmutablePrefix({ system: "s", toolSpecs: reg.specs() }),
tools: reg,
stream: false,
maxToolIters: 8,
});
const events: { role: string; forcedSummary?: boolean; content?: string }[] = [];
for await (const ev of loop.step("explore")) {
events.push({ role: ev.role, forcedSummary: ev.forcedSummary, content: ev.content });
}
// Storm warning fires.
expect(events.some((e) => e.role === "warning" && /storm/i.test(e.content ?? ""))).toBe(true);
// Final assistant_final must be tagged forcedSummary with the
// "stuck" prefix — proves we didn't just yield `done`.
const finals = events.filter((e) => e.role === "assistant_final");
const summary = finals[finals.length - 1];
expect(summary?.forcedSummary).toBe(true);
expect(summary?.content).toMatch(/stuck on a repeated tool call/);
});
it("context-guard diverts to summary when promptTokens > 80% of the window, tagging forcedSummary", async () => {
const reg = new ToolRegistry();
reg.register({
@@ -648,6 +704,164 @@ describe("CacheFirstLoop (non-streaming)", () => {
});
});
describe("CacheFirstLoop — self-reported escalation via <<<NEEDS_PRO>>>", () => {
function modelCapturingFetch(responses: FakeResponseShape[]): {
fetch: typeof fetch;
seenModels: string[];
} {
const seenModels: string[] = [];
let i = 0;
const fetchFn = vi.fn(async (_url: any, init: any) => {
const body = init?.body ? JSON.parse(init.body) : {};
seenModels.push(body.model);
const resp = responses[i++] ?? responses[responses.length - 1]!;
return new Response(
JSON.stringify({
choices: [
{
index: 0,
message: {
role: "assistant",
content: resp.content ?? "",
reasoning_content: resp.reasoning_content ?? null,
tool_calls: resp.tool_calls ?? undefined,
},
finish_reason: resp.tool_calls ? "tool_calls" : "stop",
},
],
usage: resp.usage ?? {
prompt_tokens: 100,
completion_tokens: 20,
total_tokens: 120,
prompt_cache_hit_tokens: 0,
prompt_cache_miss_tokens: 100,
},
}),
{ status: 200, headers: { "Content-Type": "application/json" } },
);
}) as unknown as typeof fetch;
return { fetch: fetchFn, seenModels };
}
it("retries on v4-pro when flash outputs the NEEDS_PRO marker as lead-in", async () => {
const { fetch, seenModels } = modelCapturingFetch([
{ content: "<<<NEEDS_PRO>>>" }, // first call on flash → escalation request
{ content: "OK, here's the answer on pro." }, // retry on pro → real response
]);
const loop = new CacheFirstLoop({
client: new DeepSeekClient({ apiKey: "sk-test", fetch }),
prefix: new ImmutablePrefix({ system: "be brief" }),
model: "deepseek-v4-flash",
stream: false,
});
const events: { role: string; content?: string }[] = [];
for await (const ev of loop.step("hard question")) {
events.push({ role: ev.role, content: ev.content });
}
// Two model calls total: first flash, second pro
expect(seenModels).toEqual(["deepseek-v4-flash", "deepseek-v4-pro"]);
// A warning surfaced about the retry
expect(events.some((e) => e.role === "warning" && /escalat/i.test(e.content ?? ""))).toBe(true);
// The final assistant message is the pro-generated content, not the marker
const finalEv = events.find((e) => e.role === "assistant_final");
expect(finalEv?.content).toBe("OK, here's the answer on pro.");
});
it("does not retry when the response merely mentions the marker mid-text", async () => {
const { fetch, seenModels } = modelCapturingFetch([
{ content: "See the docs: <<<NEEDS_PRO>>> is a reserved marker." },
]);
const loop = new CacheFirstLoop({
client: new DeepSeekClient({ apiKey: "sk-test", fetch }),
prefix: new ImmutablePrefix({ system: "be brief" }),
model: "deepseek-v4-flash",
stream: false,
});
for await (const _ev of loop.step("explain the marker")) {
/* drain */
}
expect(seenModels).toEqual(["deepseek-v4-flash"]);
});
it("does not escalate again when the model is already on pro", async () => {
// Even if pro happens to echo the marker, no infinite-retry loop.
const { fetch, seenModels } = modelCapturingFetch([
{ content: "<<<NEEDS_PRO>>>" }, // on pro — should NOT trigger retry
]);
const loop = new CacheFirstLoop({
client: new DeepSeekClient({ apiKey: "sk-test", fetch }),
prefix: new ImmutablePrefix({ system: "be brief" }),
model: "deepseek-v4-pro",
stream: false,
});
for await (const _ev of loop.step("hi")) {
/* drain */
}
// Exactly one call; no retry.
expect(seenModels).toEqual(["deepseek-v4-pro"]);
});
it("surfaces the model's reason in the warning when marker carries one", async () => {
const { fetch } = modelCapturingFetch([
{ content: "<<<NEEDS_PRO: cross-file refactor with circular imports>>>" },
{ content: "Done on pro." },
]);
const loop = new CacheFirstLoop({
client: new DeepSeekClient({ apiKey: "sk-test", fetch }),
prefix: new ImmutablePrefix({ system: "be brief" }),
model: "deepseek-v4-flash",
stream: false,
});
const events: { role: string; content?: string }[] = [];
for await (const ev of loop.step("refactor this")) {
events.push({ role: ev.role, content: ev.content });
}
const warning = events.find((e) => e.role === "warning" && /escalat/i.test(e.content ?? ""));
expect(warning).toBeDefined();
expect(warning?.content).toContain("cross-file refactor with circular imports");
});
it("treats an empty reason payload the same as the bare marker", async () => {
const { fetch, seenModels } = modelCapturingFetch([
{ content: "<<<NEEDS_PRO: >>>" }, // empty reason
{ content: "Done on pro." },
]);
const loop = new CacheFirstLoop({
client: new DeepSeekClient({ apiKey: "sk-test", fetch }),
prefix: new ImmutablePrefix({ system: "be brief" }),
model: "deepseek-v4-flash",
stream: false,
});
for await (const _ev of loop.step("x")) {
/* drain */
}
expect(seenModels).toEqual(["deepseek-v4-flash", "deepseek-v4-pro"]);
});
it("does not match a malformed marker (no closing >>>)", async () => {
const { fetch, seenModels } = modelCapturingFetch([
{ content: "<<<NEEDS_PRO: this looks like a marker but never closes" },
]);
const loop = new CacheFirstLoop({
client: new DeepSeekClient({ apiKey: "sk-test", fetch }),
prefix: new ImmutablePrefix({ system: "be brief" }),
model: "deepseek-v4-flash",
stream: false,
});
for await (const _ev of loop.step("x")) {
/* drain */
}
// No retry — the marker never closed, so the content streams as-is.
expect(seenModels).toEqual(["deepseek-v4-flash"]);
});
});
describe("CacheFirstLoop (streaming) — tool_call_delta emission", () => {
it("yields tool_call_delta events carrying growing arg-char count", async () => {
const client = new DeepSeekClient({
+456
View File
@@ -4,9 +4,12 @@ import { join } from "node:path";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import {
collectCitations,
expandAutolinks,
expandEmoji,
isExternalUrl,
parseBlocks,
parseCitationUrl,
shouldValidateAsCitation,
stripInlineMarkup,
stripMath,
validateCitation,
@@ -553,3 +556,456 @@ describe("citation links — parseBlocks regression", () => {
expect(visibleWidth("see [foo](path.ts:10) here")).toBe(12);
});
});
describe("parseBlocks — blockquote", () => {
it("single `> line` parses to a quote with one paragraph child", () => {
const blocks = parseBlocks("> a quoted line");
expect(blocks).toHaveLength(1);
if (blocks[0]?.kind !== "quote") throw new Error("unreachable");
expect(blocks[0].children).toHaveLength(1);
expect(blocks[0].children[0]?.kind).toBe("paragraph");
if (blocks[0].children[0]?.kind === "paragraph") {
expect(blocks[0].children[0].text).toBe("a quoted line");
}
});
it("consecutive `>` lines fold into one paragraph inside the quote", () => {
const blocks = parseBlocks(["> first", "> second", "> third"].join("\n"));
if (blocks[0]?.kind !== "quote") throw new Error("unreachable");
// Three adjacent `>` lines with no blank separator → one paragraph
// (paragraph parser joins with spaces, same as outside a quote).
expect(blocks[0].children).toHaveLength(1);
if (blocks[0].children[0]?.kind === "paragraph") {
expect(blocks[0].children[0].text).toBe("first second third");
}
});
it("blank `>` line splits the quote into two paragraph children", () => {
const blocks = parseBlocks(["> para 1", ">", "> para 2"].join("\n"));
if (blocks[0]?.kind !== "quote") throw new Error("unreachable");
expect(blocks[0].children).toHaveLength(2);
expect(blocks[0].children.map((c) => c.kind)).toEqual(["paragraph", "paragraph"]);
});
it("non-`>` line after a quote closes it — following prose becomes its own paragraph", () => {
const blocks = parseBlocks(["> quoted", "", "not quoted"].join("\n"));
expect(blocks).toHaveLength(2);
expect(blocks[0]?.kind).toBe("quote");
expect(blocks[1]?.kind).toBe("paragraph");
if (blocks[1]?.kind === "paragraph") expect(blocks[1].text).toBe("not quoted");
});
it("quote content carries inline markdown (bold, code) through intact", () => {
const blocks = parseBlocks("> **important**: call `foo()` first");
if (blocks[0]?.kind !== "quote") throw new Error("unreachable");
const child = blocks[0].children[0];
if (child?.kind !== "paragraph") throw new Error("unreachable");
expect(child.text).toBe("**important**: call `foo()` first");
});
it("`>` with no space before content still parses (GFM-tolerant)", () => {
const blocks = parseBlocks(">no space");
if (blocks[0]?.kind !== "quote") throw new Error("unreachable");
if (blocks[0].children[0]?.kind === "paragraph") {
expect(blocks[0].children[0].text).toBe("no space");
}
});
it("nested `> >` becomes a blockquote inside a blockquote", () => {
const blocks = parseBlocks(["> outer", ">", "> > inner"].join("\n"));
if (blocks[0]?.kind !== "quote") throw new Error("unreachable");
expect(blocks[0].children.map((c) => c.kind)).toEqual(["paragraph", "quote"]);
const inner = blocks[0].children[1];
if (inner?.kind !== "quote") throw new Error("unreachable");
const innerPara = inner.children[0];
if (innerPara?.kind !== "paragraph") throw new Error("unreachable");
expect(innerPara.text).toBe("inner");
});
it("triple-nested `> > >` produces three levels of quote", () => {
const blocks = parseBlocks("> > > deep");
if (blocks[0]?.kind !== "quote") throw new Error("unreachable");
const lvl2 = blocks[0].children[0];
if (lvl2?.kind !== "quote") throw new Error("unreachable");
const lvl3 = lvl2.children[0];
if (lvl3?.kind !== "quote") throw new Error("unreachable");
const leaf = lvl3.children[0];
if (leaf?.kind !== "paragraph") throw new Error("unreachable");
expect(leaf.text).toBe("deep");
});
it("list inside a quote parses as a real bullet block, not flattened text", () => {
const blocks = parseBlocks(["> - item a", "> - item b"].join("\n"));
if (blocks[0]?.kind !== "quote") throw new Error("unreachable");
expect(blocks[0].children).toHaveLength(1);
const inner = blocks[0].children[0];
if (inner?.kind !== "bullet") throw new Error("unreachable");
expect(inner.items.map((x) => x.text)).toEqual(["item a", "item b"]);
});
it("fenced code block inside a quote parses as a real code block", () => {
const blocks = parseBlocks(["> ```js", "> const x = 1;", "> ```"].join("\n"));
if (blocks[0]?.kind !== "quote") throw new Error("unreachable");
const inner = blocks[0].children[0];
if (inner?.kind !== "code") throw new Error("unreachable");
expect(inner.lang).toBe("js");
expect(inner.text).toBe("const x = 1;");
});
it("mixed content inside a quote: paragraph + list keeps both structured", () => {
const src = ["> 引用可以包含其他元素:", ">", "> - 列表项一", "> - 列表项二"].join("\n");
const blocks = parseBlocks(src);
if (blocks[0]?.kind !== "quote") throw new Error("unreachable");
expect(blocks[0].children.map((c) => c.kind)).toEqual(["paragraph", "bullet"]);
});
it("horizontal rule inside a quote stays as literal `---` (no HR promotion)", () => {
// Inside the quote, `> ---` strips to `---` — THAT does match the
// HR regex in the recursive parse, so nested HR IS a real thing.
// Just checking it's a quote with an hr child (not eaten at the
// outer level).
const blocks = parseBlocks("> ---");
expect(blocks).toHaveLength(1);
if (blocks[0]?.kind !== "quote") throw new Error("unreachable");
expect(blocks[0].children[0]?.kind).toBe("hr");
});
});
describe("parseBlocks — task lists", () => {
it("`- [ ] …` produces a todo item", () => {
const blocks = parseBlocks("- [ ] do the thing");
if (blocks[0]?.kind !== "bullet") throw new Error("unreachable");
expect(blocks[0].items).toHaveLength(1);
expect(blocks[0].items[0]).toEqual({ text: "do the thing", task: "todo" });
});
it("`- [x] …` produces a done item", () => {
const blocks = parseBlocks("- [x] shipped");
if (blocks[0]?.kind !== "bullet") throw new Error("unreachable");
expect(blocks[0].items[0]).toEqual({ text: "shipped", task: "done" });
});
it("uppercase `[X]` is also treated as done (case-insensitive)", () => {
const blocks = parseBlocks("- [X] uppercase");
if (blocks[0]?.kind !== "bullet") throw new Error("unreachable");
expect(blocks[0].items[0]?.task).toBe("done");
});
it("mixed tasks and plain bullets coexist in one list", () => {
const text = ["- plain item", "- [ ] todo", "- [x] done"].join("\n");
const blocks = parseBlocks(text);
if (blocks[0]?.kind !== "bullet") throw new Error("unreachable");
expect(blocks[0].items).toEqual([
{ text: "plain item" },
{ text: "todo", task: "todo" },
{ text: "done", task: "done" },
]);
});
it("array-index-style prose `[1] ref` does NOT become a task", () => {
// Regression: task regex requires a space after the bracket, so
// `- [1] ref` is a plain bullet whose item text is "[1] ref".
const blocks = parseBlocks("- [1] reference");
if (blocks[0]?.kind !== "bullet") throw new Error("unreachable");
expect(blocks[0].items[0]).toEqual({ text: "[1] reference" });
});
});
describe("stripMath — $ / $$ delimiters", () => {
it("strips inline `$E = mc^2$` to `E = mc²` (delimiter gone, superscript converted)", () => {
expect(stripMath("$E = mc^2$")).toBe("E = mc²");
});
it("strips surrounding `$$…$$` on block math and isolates it as its own paragraph", () => {
const out = stripMath("prose $$x + y = z$$ more prose");
// Block math gets \n\n on each side so parseBlocks later treats
// it as its own paragraph instead of folding into prose.
expect(out).not.toContain("$$");
expect(out).toContain("x + y = z");
});
it("handles `$$\\sum_{i=1}^{n} i = \\frac{n(n+1)}{2}$$` end-to-end", () => {
const out = stripMath("$$\\sum_{i=1}^{n} i = \\frac{n(n+1)}{2}$$");
expect(out).not.toContain("$");
expect(out).not.toContain("\\");
expect(out).toContain("Σ"); // \sum → Σ
expect(out).toContain("(n(n+1))/(2)"); // \frac → ( )/( )
expect(out).toContain("ⁿ"); // ^{n} → ⁿ
});
it("does NOT eat a price like `$5 per unit` (no closing $ adjacent to non-space)", () => {
expect(stripMath("$5 per unit")).toBe("$5 per unit");
});
it("does NOT eat `$5 and $10` prose (content starts/ends with space at boundaries)", () => {
expect(stripMath("$5 and $10 extra")).toBe("$5 and $10 extra");
});
it("does NOT eat a shell var `echo $HOME`", () => {
expect(stripMath("echo $HOME")).toBe("echo $HOME");
});
it("leaves `$ prompt:` alone (space immediately after opening $)", () => {
expect(stripMath("$ prompt:")).toBe("$ prompt:");
});
it("strips a single-character inline expression `$x$`", () => {
// With non-greedy + 1-or-more content, $x$ matches as content `x`.
expect(stripMath("$x$")).toBe("x");
});
});
describe("expandEmoji — GFM shortcodes", () => {
it(":smile: → 😄", () => {
expect(expandEmoji(":smile:")).toBe("😄");
});
it(":+1: and :-1: resolve to thumb emojis", () => {
expect(expandEmoji(":+1:")).toBe("👍");
expect(expandEmoji(":-1:")).toBe("👎");
});
it("inline prose: `great :fire: job` → `great 🔥 job`", () => {
expect(expandEmoji("great :fire: job")).toBe("great 🔥 job");
});
it("unknown shortcode stays literal (no mangling of `:unknown_thing:`)", () => {
expect(expandEmoji(":unknown_thing:")).toBe(":unknown_thing:");
});
it("numeric `:10:` stays literal (not in map; protects timestamps / file:line:col)", () => {
expect(expandEmoji("file.ts:10: error")).toBe("file.ts:10: error");
});
it("case-insensitive match (`:SMILE:` also resolves)", () => {
expect(expandEmoji(":SMILE:")).toBe("😄");
});
it(":100: resolves via the numeric alias", () => {
expect(expandEmoji(":100:")).toBe("💯");
});
it("multiple emoji on one line all expand", () => {
expect(expandEmoji(":rocket: :fire: :tada:")).toBe("🚀 🔥 🎉");
});
});
describe("inline — bold-italic `***text***`", () => {
it("stripInlineMarkup unwraps the whole three-star envelope (no leftover asterisks)", () => {
expect(stripInlineMarkup("***both***")).toBe("both");
});
it("visibleWidth counts only the inner text", () => {
// "both" = 4 visible chars, `***` markers contribute 0.
expect(visibleWidth("***both***")).toBe(4);
});
it("bold-italic coexists with surrounding plain text", () => {
expect(stripInlineMarkup("hi ***emphasis*** there")).toBe("hi emphasis there");
});
it("does NOT greedily consume a following `**bold**` on the same line", () => {
// Concrete regression: the bold-italic regex is non-greedy and
// content excludes `*`, so `***a*** **b**` stays as two distinct
// spans with 4 chars visible.
expect(stripInlineMarkup("***a*** **b**")).toBe("a b");
});
});
describe("stripMath — Pandoc super/subscript (^text^ / ~text~)", () => {
it("`x^2^` → `x²` (all chars convertible)", () => {
expect(stripMath("x^2^")).toBe("x²");
});
it("`H~2~O` → `H₂O` (subscript)", () => {
expect(stripMath("H~2~O")).toBe("H₂O");
});
it("`a^123^` → `a¹²³` (multi-digit superscript)", () => {
expect(stripMath("a^123^")).toBe("a¹²³");
});
it("leaves `^foo^` literal when content has non-convertible chars", () => {
// `f`, `o` aren't in SUPERSCRIPT map, so dropping the markers
// would lose the model's intent — better to leave literal.
expect(stripMath("x^foo^")).toBe("x^foo^");
});
it("subscript rule does NOT fire inside `~~strikethrough~~`", () => {
// Both `~` are guarded by (?<!~)(?!~) so `~~text~~` passes through
// to the inline parser intact. `text` contains letters → would
// fail the conversion guard anyway, but also the outer lookarounds
// skip the strikethrough bounds — double protection.
expect(stripMath("~~gone~~")).toBe("~~gone~~");
});
it("LaTeX form `H^{2}` still works (handled by the existing {braced} rule)", () => {
expect(stripMath("H^{2}O")).toBe("H²O");
});
});
describe("parseBlocks — hard line break (GFM trailing two spaces)", () => {
it("a single ` ` hard break injects a `\\n` inside the paragraph text", () => {
const src = "line one \nline two";
const blocks = parseBlocks(src);
expect(blocks).toHaveLength(1);
if (blocks[0]?.kind !== "paragraph") throw new Error("unreachable");
expect(blocks[0].text).toBe("line one\nline two");
});
it("without trailing ` ` a soft break still collapses to a space", () => {
const src = "line one\nline two";
const blocks = parseBlocks(src);
if (blocks[0]?.kind !== "paragraph") throw new Error("unreachable");
expect(blocks[0].text).toBe("line one line two");
});
it("mixed hard + soft breaks preserve the distinction", () => {
// line 1 → hard → line 2 → soft → line 3
const src = "line one \nline two\nline three";
const blocks = parseBlocks(src);
if (blocks[0]?.kind !== "paragraph") throw new Error("unreachable");
expect(blocks[0].text).toBe("line one\nline two line three");
});
it("three trailing spaces also trigger hard break (GFM: two-or-more)", () => {
const src = "one \ntwo";
const blocks = parseBlocks(src);
if (blocks[0]?.kind !== "paragraph") throw new Error("unreachable");
expect(blocks[0].text).toBe("one\ntwo");
});
it("one trailing space is NOT a hard break (two required)", () => {
const src = "one \ntwo";
const blocks = parseBlocks(src);
if (blocks[0]?.kind !== "paragraph") throw new Error("unreachable");
expect(blocks[0].text).toBe("one two");
});
});
describe("inline — backslash escapes", () => {
it("stripInlineMarkup drops `\\` before punctuation (CommonMark escape)", () => {
expect(stripInlineMarkup("\\*not italic\\*")).toBe("*not italic*");
});
it("stripInlineMarkup keeps ``\\``` before backtick", () => {
expect(stripInlineMarkup("\\`code\\`")).toBe("`code`");
});
it("escape survives a would-be strikethrough at the edges", () => {
// `\~...\~` has only single ~ each side after escape — not strike.
expect(stripInlineMarkup("\\~foo\\~")).toBe("~foo~");
});
it("`\\\\` becomes a single literal backslash", () => {
expect(stripInlineMarkup("a\\\\b")).toBe("a\\b");
});
it("escape only triggers on markup punctuation — `\\a` stays `\\a`", () => {
// `a` isn't in the escape class, so the backslash is preserved.
expect(stripInlineMarkup("hi\\a")).toBe("hi\\a");
});
it("visibleWidth skips the `\\` when escape fires", () => {
// "\\*not\\*" renders as 5 visible chars: "*not*"
expect(visibleWidth("\\*not\\*")).toBe(5);
});
});
describe("expandAutolinks — `<url>` shorthand", () => {
it("rewrites `<https://example.com>` to a full `[url](url)`", () => {
expect(expandAutolinks("see <https://example.com> now")).toBe(
"see [https://example.com](https://example.com) now",
);
});
it("rewrites `<mailto:[email protected]>`", () => {
expect(expandAutolinks("<mailto:[email protected]>")).toBe(
"[mailto:[email protected]](mailto:[email protected])",
);
});
it("leaves `<non-url text>` alone (no recognized scheme)", () => {
expect(expandAutolinks("<angle-bracketed prose>")).toBe("<angle-bracketed prose>");
});
it("leaves `<kbd>`, `<span>`, and other HTML tags alone", () => {
expect(expandAutolinks("<kbd>Ctrl</kbd>")).toBe("<kbd>Ctrl</kbd>");
});
});
describe("shouldValidateAsCitation — citation guard", () => {
it("skips anchor-only `#foo` (in-page jump, not a file)", () => {
expect(shouldValidateAsCitation("#foo")).toBe(false);
expect(shouldValidateAsCitation("#")).toBe(false);
expect(shouldValidateAsCitation("#section-1")).toBe(false);
});
it("skips bare `/` and empty", () => {
expect(shouldValidateAsCitation("/")).toBe(false);
expect(shouldValidateAsCitation("")).toBe(false);
});
it("skips placeholder words without path separators or extensions", () => {
expect(shouldValidateAsCitation("url")).toBe(false);
expect(shouldValidateAsCitation("placeholder")).toBe(false);
});
it("accepts a real path with slash", () => {
expect(shouldValidateAsCitation("src/foo.ts")).toBe(true);
});
it("accepts a file with extension but no slash", () => {
expect(shouldValidateAsCitation("README.md")).toBe(true);
});
});
describe("collectCitations — no false positives from anchors / placeholders", () => {
it("does NOT add `#anchor` URLs to the citation map (no broken-citation red)", () => {
const map = collectCitations("jump to [top](#1-header) here", "/tmp");
expect(map.size).toBe(0);
});
it("does NOT add placeholder words like `url` to the map", () => {
const map = collectCitations("demo link: [see this](url)", "/tmp");
expect(map.size).toBe(0);
});
});
describe("parseBlocks — diagram code blocks (mermaid / dot / plantuml / …)", () => {
it("parses a ```mermaid block as a CodeBlock with lang='mermaid'", () => {
const src = ["```mermaid", "graph TD", " A --> B", "```"].join("\n");
const blocks = parseBlocks(src);
expect(blocks).toHaveLength(1);
if (blocks[0]?.kind !== "code") throw new Error("unreachable");
expect(blocks[0].lang).toBe("mermaid");
expect(blocks[0].text).toBe("graph TD\n A --> B");
});
it("parses a ```dot block as a CodeBlock (rendering branches on lang at display time)", () => {
const src = ["```dot", "digraph G { A -> B }", "```"].join("\n");
const blocks = parseBlocks(src);
if (blocks[0]?.kind !== "code") throw new Error("unreachable");
expect(blocks[0].lang).toBe("dot");
});
});
describe("inline — strikethrough", () => {
it("stripInlineMarkup unwraps `~~text~~`", () => {
expect(stripInlineMarkup("before ~~gone~~ after")).toBe("before gone after");
});
it("visibleWidth ignores `~~` markers", () => {
// "abc" + " " + "xy" = 6 visible chars; `~~` on each side = 0 visible.
expect(visibleWidth("abc ~~xy~~")).toBe(6);
});
it("bold, code, and strikethrough can coexist on one line", () => {
const input = "**bold** then `code` then ~~gone~~";
expect(stripInlineMarkup(input)).toBe("bold then code then gone");
});
it("two strikethroughs on one line are both captured", () => {
expect(stripInlineMarkup("~~one~~ and ~~two~~")).toBe("one and two");
});
});
+207 -9
View File
@@ -1,4 +1,5 @@
import { describe, expect, it } from "vitest";
import { collapseLinesForDisplay } from "../src/cli/ui/PromptInput.js";
import {
type MultilineKey,
lineAndColumn,
@@ -35,10 +36,16 @@ describe("processMultilineKey — inserts at cursor", () => {
expect(r.cursor).toBe(4);
});
it("pasted newline lands inline (not a submit)", () => {
it("pasted newline-containing input surfaces as a pasteRequest (not direct insert)", () => {
// 0.8 changed paste handling: multi-char input with a newline is
// routed up as `pasteRequest` so the parent can register the
// blob and insert ONE sentinel codepoint instead of inlining
// the whole content. Direct insertion only happens for typed
// input without a newline.
const r = processMultilineKey("a", 1, key({ input: "\nmore" }));
expect(r.next).toBe("a\nmore");
expect(r.next).toBeNull();
expect(r.submit).toBe(false);
expect(r.pasteRequest?.content).toBe("\nmore");
});
});
@@ -141,29 +148,68 @@ describe("processMultilineKey — cursor motion", () => {
expect(processMultilineKey("abc", 3, key({ rightArrow: true })).cursor).toBe(3);
});
it("↑/↓ on a single-line non-empty buffer is a no-op (doesn't eat for history)", () => {
// Single-line buffer: moveCursorUp has nowhere to go. Returns NOOP so
// the parent can decide what to do — but parent only does history on
// empty buffer, so the net effect is "nothing happens."
it("↑/↓ on a single-line non-empty buffer hands off to history recall (nowhere to move)", () => {
// 0.7.1: previously this was a pure NOOP, which left the user
// feeling stuck when they wanted to recall a prior prompt from
// a non-empty buffer. Now we emit `historyHandoff` so the
// parent can decide — typically swap the buffer for the
// previous prompt.
const up = processMultilineKey("hello", 3, key({ upArrow: true }));
expect(up).toEqual({ next: null, cursor: null, submit: false });
expect(up).toEqual({ next: null, cursor: null, submit: false, historyHandoff: "prev" });
const down = processMultilineKey("hello", 3, key({ downArrow: true }));
expect(down).toEqual({ next: null, cursor: null, submit: false });
expect(down).toEqual({ next: null, cursor: null, submit: false, historyHandoff: "next" });
});
it("↑/↓ on an empty buffer defers to the parent (history recall)", () => {
it("↑/↓ on an empty buffer hands off to the parent (history recall)", () => {
expect(processMultilineKey("", 0, key({ upArrow: true }))).toEqual({
next: null,
cursor: null,
submit: false,
historyHandoff: "prev",
});
expect(processMultilineKey("", 0, key({ downArrow: true }))).toEqual({
next: null,
cursor: null,
submit: false,
historyHandoff: "next",
});
});
it("↑ at line 0 of a multi-line buffer hands off to history (escape hatch from a draft)", () => {
// Cursor on first line, buffer has a second line below — ↑ has
// nowhere to move, so we emit the handoff. Previously this was
// a silent NOOP that trapped the user.
const v = "first\nsecond";
const handoff = processMultilineKey(v, 3, key({ upArrow: true }));
expect(handoff).toEqual({
next: null,
cursor: null,
submit: false,
historyHandoff: "prev",
});
});
it("↓ at last line hands off similarly", () => {
// cursor at pos 8 = col 2 on line 1 ("second")
const v = "first\nsecond";
const handoff = processMultilineKey(v, 8, key({ downArrow: true }));
expect(handoff.historyHandoff).toBe("next");
});
it("raw `\\x1b[A` escape sequence is rewritten into upArrow (Windows-terminal fallback)", () => {
// Some Windows consoles don't set key.upArrow; the raw CSI leaks
// through as `input` and would otherwise be inserted verbatim
// into the buffer. Rewrite into structured key instead.
const handoff = processMultilineKey("", 0, { input: "\x1b[A" });
expect(handoff.historyHandoff).toBe("prev");
});
it("raw `\\x1b[B` becomes downArrow; `\\x1b[C` rightArrow; `\\x1b[D` leftArrow", () => {
expect(processMultilineKey("", 0, { input: "\x1b[B" }).historyHandoff).toBe("next");
expect(processMultilineKey("abc", 0, { input: "\x1b[C" }).cursor).toBe(1);
expect(processMultilineKey("abc", 2, { input: "\x1b[D" }).cursor).toBe(1);
});
it("↑ moves cursor to the previous line, preserving column when possible", () => {
// line 0: "hello" (cols 0-5)
// line 1: "world" (cols 0-5)
@@ -230,6 +276,158 @@ describe("processMultilineKey — parent-owned keys are ignored", () => {
});
});
describe("processMultilineKey — buffer-wide navigation + clear shortcuts", () => {
it("PageUp jumps cursor to position 0 (top of buffer)", () => {
const v = "line1\nline2\nline3\nline4";
const r = processMultilineKey(v, 18, key({ pageUp: true }));
expect(r.cursor).toBe(0);
});
it("PageDown jumps cursor to value.length (end of buffer)", () => {
const v = "line1\nline2\nline3\nline4";
const r = processMultilineKey(v, 0, key({ pageDown: true }));
expect(r.cursor).toBe(v.length);
});
it("PageUp at top is a no-op (no cursor churn)", () => {
const r = processMultilineKey("hello", 0, key({ pageUp: true }));
expect(r).toEqual({ next: null, cursor: null, submit: false });
});
it("PageDown at end is a no-op", () => {
const v = "hello";
const r = processMultilineKey(v, v.length, key({ pageDown: true }));
expect(r).toEqual({ next: null, cursor: null, submit: false });
});
it("Ctrl+U clears the entire buffer", () => {
const r = processMultilineKey("a long\nmulti-line\npaste", 7, key({ input: "u", ctrl: true }));
expect(r.next).toBe("");
expect(r.cursor).toBe(0);
});
it("Ctrl+U on empty buffer is a no-op", () => {
const r = processMultilineKey("", 0, key({ input: "u", ctrl: true }));
expect(r).toEqual({ next: null, cursor: null, submit: false });
});
it("Ctrl+W deletes the word before the cursor", () => {
// cursor at end of "hello world", deletes "world"
const r = processMultilineKey("hello world", 11, key({ input: "w", ctrl: true }));
expect(r.next).toBe("hello ");
expect(r.cursor).toBe(6);
});
it("Ctrl+W eats trailing whitespace then the previous word", () => {
// cursor after "hello " (3 spaces). Should delete the spaces AND "hello".
const r = processMultilineKey("hello ", 8, key({ input: "w", ctrl: true }));
expect(r.next).toBe("");
expect(r.cursor).toBe(0);
});
it("Ctrl+W mid-word stops at the word's start", () => {
// cursor in middle of "hello", deletes "hel"
const r = processMultilineKey("hello world", 3, key({ input: "w", ctrl: true }));
expect(r.next).toBe("lo world");
expect(r.cursor).toBe(0);
});
it("Ctrl+W at start of buffer is a no-op", () => {
const r = processMultilineKey("hello", 0, key({ input: "w", ctrl: true }));
expect(r).toEqual({ next: null, cursor: null, submit: false });
});
it("Ctrl+W spans newlines — deletes the previous line's last word from line start", () => {
// cursor at start of "world" line (index 6), Ctrl+W deletes "hello\n"
const r = processMultilineKey("hello\nworld", 6, key({ input: "w", ctrl: true }));
expect(r.next).toBe("world");
expect(r.cursor).toBe(0);
});
});
describe("processMultilineKey — paste burst handling", () => {
it("paste with embedded \\n surfaces a pasteRequest, does NOT submit even with key.return set", () => {
// Repro of the reported bug: Ink occasionally sets key.return on
// a paste whose trailing \n looks like Enter. Pre-fix this would
// submit the partial buffer mid-paste. Now the reducer hands the
// paste up as a `pasteRequest` and never touches `submit`.
const r = processMultilineKey("", 0, key({ input: "line1\nline2\nline3", return: true }));
expect(r.submit).toBe(false);
expect(r.next).toBeNull();
expect(r.pasteRequest?.content).toBe("line1\nline2\nline3");
});
it("paste normalizes CRLF and bare CR to LF (Windows clipboard / web copy)", () => {
const r1 = processMultilineKey("", 0, key({ input: "a\r\nb\r\nc" }));
expect(r1.pasteRequest?.content).toBe("a\nb\nc");
const r2 = processMultilineKey("", 0, key({ input: "x\ry\rz" }));
expect(r2.pasteRequest?.content).toBe("x\ny\nz");
});
it("strips bracketed-paste markers if they leak through (DECSET 2004 supported terminals)", () => {
const wrapped = "\u001b[200~hello\nworld\u001b[201~";
const r = processMultilineKey("", 0, key({ input: wrapped }));
expect(r.pasteRequest?.content).toBe("hello\nworld");
expect(r.submit).toBe(false);
});
it("real Enter (input='', return=true) still submits — not mistaken for paste", () => {
const r = processMultilineKey("foo", 3, key({ input: "", return: true }));
expect(r.submit).toBe(true);
expect(r.submitValue).toBe("foo");
});
it("single-char Ctrl+J still inserts one newline directly (no pasteRequest)", () => {
const r = processMultilineKey("ab", 1, key({ input: "j", ctrl: true }));
expect(r.next).toBe("a\nb");
expect(r.pasteRequest).toBeUndefined();
});
});
describe("collapseLinesForDisplay — big-paste mitigation", () => {
it("returns all lines unchanged when under the threshold", () => {
const lines = ["a", "b", "c"];
const out = collapseLinesForDisplay(lines, 1);
expect(out).toHaveLength(3);
expect(out.every((x) => x.kind === "line")).toBe(true);
});
it("collapses long buffers into head + cursor + tail with skip markers", () => {
// 30 lines, cursor on line 15 (middle). Should render first 3,
// cursor line, last 2 — plus skip markers between the runs.
const lines = Array.from({ length: 30 }, (_, i) => `line${i}`);
const out = collapseLinesForDisplay(lines, 15);
const kinds = out.map((x) => x.kind);
// Shape: line×3, skip, line(cursor), skip, line×2
expect(kinds).toEqual(["line", "line", "line", "skip", "line", "skip", "line", "line"]);
// Cursor-line preserves its original index so the `you ›` prefix
// and the cursor column still line up with the correct row.
const cursorItem = out.find((x) => x.kind === "line" && x.originalIndex === 15);
expect(cursorItem).toBeDefined();
});
it("does NOT inject a skip marker when runs are adjacent", () => {
// Cursor on line 2 (already inside head=0..2). Head covers 0..2,
// tail covers 28..29. The cursor overlaps the head, so no
// middle skip is needed — only the gap between head and tail.
const lines = Array.from({ length: 30 }, (_, i) => `${i}`);
const out = collapseLinesForDisplay(lines, 2);
const kinds = out.map((x) => x.kind);
expect(kinds).toEqual(["line", "line", "line", "skip", "line", "line"]);
});
it("hidden count adds up to total - visible", () => {
const lines = Array.from({ length: 100 }, (_, i) => `${i}`);
const out = collapseLinesForDisplay(lines, 50);
const hidden = out.reduce(
(sum, item) => sum + (item.kind === "skip" ? item.linesHidden : 0),
0,
);
const visible = out.filter((x) => x.kind === "line").length;
expect(hidden + visible).toBe(100);
});
});
describe("lineAndColumn", () => {
it("maps a cursor offset to {line, col}", () => {
expect(lineAndColumn("abc", 2)).toEqual({ line: 0, col: 2 });
+126
View File
@@ -0,0 +1,126 @@
import { describe, expect, it } from "vitest";
import {
PASTE_SENTINEL_BASE,
PASTE_SENTINEL_RANGE,
type PasteEntry,
bufferHasPaste,
decodePasteSentinel,
encodePasteSentinel,
expandPasteSentinels,
formatBytesShort,
isPasteSentinel,
listPasteIdsInBuffer,
makePasteEntry,
} from "../src/cli/ui/paste-sentinels.js";
describe("paste sentinel encoding", () => {
it("encode/decode round-trip across the full id range", () => {
for (const id of [0, 1, 7, 42, 128, 255]) {
const ch = encodePasteSentinel(id);
expect(ch.length).toBe(1);
expect(ch.charCodeAt(0)).toBe(PASTE_SENTINEL_BASE + id);
expect(decodePasteSentinel(ch)).toBe(id);
expect(isPasteSentinel(ch)).toBe(true);
}
});
it("decode returns null for non-sentinel chars", () => {
expect(decodePasteSentinel("a")).toBeNull();
expect(decodePasteSentinel(" ")).toBeNull();
expect(decodePasteSentinel("\n")).toBeNull();
expect(decodePasteSentinel("中")).toBeNull();
expect(decodePasteSentinel("")).toBeNull();
});
it("encode rejects ids outside [0, 256)", () => {
expect(() => encodePasteSentinel(-1)).toThrow();
expect(() => encodePasteSentinel(PASTE_SENTINEL_RANGE)).toThrow();
expect(() => encodePasteSentinel(999)).toThrow();
});
});
describe("makePasteEntry — line + char counts", () => {
it("counts lines via \\n split (single-line content = 1 line)", () => {
const e = makePasteEntry(0, "hello world");
expect(e.lineCount).toBe(1);
expect(e.charCount).toBe(11);
});
it("multi-line content counts each \\n as a delimiter", () => {
const e = makePasteEntry(3, "line1\nline2\nline3");
expect(e.lineCount).toBe(3);
});
it("trailing newline still counts as one line (split('\\n') has empty tail)", () => {
const e = makePasteEntry(0, "line1\n");
expect(e.lineCount).toBe(2);
});
});
describe("expandPasteSentinels — round-trip back to full content", () => {
function makeReg(entries: PasteEntry[]): Map<number, PasteEntry> {
const m = new Map<number, PasteEntry>();
for (const e of entries) m.set(e.id, e);
return m;
}
it("expands a buffer with one sentinel back to typed-prose + paste content", () => {
const reg = makeReg([makePasteEntry(0, "ERROR\nstack\ntrace")]);
const buf = `prefix ${encodePasteSentinel(0)} suffix`;
expect(expandPasteSentinels(buf, reg)).toBe("prefix ERROR\nstack\ntrace suffix");
});
it("expands multiple sentinels in source order", () => {
const reg = makeReg([makePasteEntry(0, "AAA"), makePasteEntry(1, "BBB")]);
const buf = `${encodePasteSentinel(0)} between ${encodePasteSentinel(1)}`;
expect(expandPasteSentinels(buf, reg)).toBe("AAA between BBB");
});
it("unknown sentinels (id not in registry) collapse to empty string", () => {
const reg = makeReg([]);
const buf = `before ${encodePasteSentinel(7)} after`;
expect(expandPasteSentinels(buf, reg)).toBe("before after");
});
it("buffer with no sentinels passes through unchanged", () => {
const reg = makeReg([]);
expect(expandPasteSentinels("just typed text", reg)).toBe("just typed text");
});
});
describe("bufferHasPaste / listPasteIdsInBuffer", () => {
it("bufferHasPaste returns false for sentinel-free text", () => {
expect(bufferHasPaste("plain text")).toBe(false);
expect(bufferHasPaste("")).toBe(false);
});
it("bufferHasPaste returns true once any sentinel appears", () => {
expect(bufferHasPaste(`x${encodePasteSentinel(0)}`)).toBe(true);
});
it("listPasteIdsInBuffer returns ids in source order", () => {
const buf = `${encodePasteSentinel(2)}.${encodePasteSentinel(5)}.${encodePasteSentinel(0)}`;
expect(listPasteIdsInBuffer(buf)).toEqual([2, 5, 0]);
});
it("listPasteIdsInBuffer is empty for sentinel-free text", () => {
expect(listPasteIdsInBuffer("hi")).toEqual([]);
});
});
describe("formatBytesShort", () => {
it("under 1 KB prints as bytes", () => {
expect(formatBytesShort(0)).toBe("0B");
expect(formatBytesShort(900)).toBe("900B");
});
it("under 10 KB shows one decimal place", () => {
expect(formatBytesShort(1024)).toBe("1.0KB");
expect(formatBytesShort(5120)).toBe("5.0KB");
});
it("10 KB and above drops the decimal", () => {
expect(formatBytesShort(15 * 1024)).toBe("15KB");
});
it("MB format kicks in past 1 MB", () => {
expect(formatBytesShort(2 * 1024 * 1024)).toBe("2.0MB");
});
});
-30
View File
@@ -1,30 +0,0 @@
import { describe, expect, it } from "vitest";
import { clampBodyByLines } from "../src/cli/ui/PlanConfirm.js";
describe("clampBodyByLines", () => {
it("returns text unchanged when already within the row budget", () => {
const text = "line 1\nline 2\nline 3";
expect(clampBodyByLines(text, 10)).toBe(text);
});
it("trims to the first N lines and appends a truncation marker", () => {
const lines = Array.from({ length: 40 }, (_, i) => `line ${i + 1}`);
const out = clampBodyByLines(lines.join("\n"), 10);
expect(out.split("\n").slice(0, 10)).toEqual(lines.slice(0, 10));
expect(out).toContain("30 more lines truncated");
});
it("shows the dropped-line count for the truncation hint", () => {
const text = Array.from({ length: 25 }, (_, i) => `row${i}`).join("\n");
expect(clampBodyByLines(text, 5)).toContain("20 more lines truncated");
});
it("handles an empty body without throwing", () => {
expect(clampBodyByLines("", 5)).toBe("");
});
it("does not trim when exactly at the budget", () => {
const text = "a\nb\nc";
expect(clampBodyByLines(text, 3)).toBe(text);
});
});
+383
View File
@@ -0,0 +1,383 @@
/**
* plan-store — load/save the structured plan state next to the
* session JSONL log so plans survive terminal restarts. Tests cover
* the roundtrip, malformed-file recovery, and the relativeTime
* helper that powers the resume notice.
*/
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname } from "node:path";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
function writeFixture(path: string, content: string): void {
mkdirSync(dirname(path), { recursive: true });
writeFileSync(path, content);
}
import {
archivePlanState,
clearPlanState,
listPlanArchives,
loadPlanState,
planStatePath,
relativeTime,
savePlanState,
} from "../src/code/plan-store.js";
// We point the test at a temp HOME so the real ~/.reasonix isn't
// touched. sessionsDir() reads homedir() via os, which honors HOME on
// POSIX and USERPROFILE on Windows. Setting both keeps the test
// portable across the matrix.
let tempHome: string;
let originalHome: string | undefined;
let originalUserProfile: string | undefined;
beforeEach(() => {
tempHome = mkdtempSync(join(tmpdir(), "reasonix-plan-store-"));
originalHome = process.env.HOME;
originalUserProfile = process.env.USERPROFILE;
process.env.HOME = tempHome;
process.env.USERPROFILE = tempHome;
});
afterEach(() => {
process.env.HOME = originalHome;
process.env.USERPROFILE = originalUserProfile;
rmSync(tempHome, { recursive: true, force: true });
});
describe("plan-store roundtrip", () => {
it("returns null when no plan file exists", () => {
expect(loadPlanState("never-touched")).toBeNull();
});
it("save then load preserves steps + completed ids", () => {
const steps = [
{ id: "step-1", title: "extract", action: "split tokens", risk: "low" as const },
{ id: "step-2", title: "rewire", action: "wire middleware", risk: "med" as const },
];
savePlanState("test-session", steps, ["step-1"]);
const loaded = loadPlanState("test-session");
expect(loaded).not.toBeNull();
expect(loaded?.steps).toEqual(steps);
expect(loaded?.completedStepIds).toEqual(["step-1"]);
expect(loaded?.version).toBe(1);
expect(typeof loaded?.updatedAt).toBe("string");
});
it("round-trips optional body + summary when supplied", () => {
savePlanState("with-extras", [{ id: "x", title: "y", action: "z" }], [], {
body: "# Plan\n- do thing",
summary: "Refactor foo into bar",
});
const loaded = loadPlanState("with-extras");
expect(loaded?.body).toBe("# Plan\n- do thing");
expect(loaded?.summary).toBe("Refactor foo into bar");
});
it("omits body / summary when not supplied (keeps older plans clean)", () => {
savePlanState("no-extras", [{ id: "x", title: "y", action: "z" }], []);
const loaded = loadPlanState("no-extras");
expect(loaded?.body).toBeUndefined();
expect(loaded?.summary).toBeUndefined();
});
it("clearPlanState removes the file", () => {
savePlanState("test", [{ id: "x", title: "y", action: "z" }], []);
expect(loadPlanState("test")).not.toBeNull();
clearPlanState("test");
expect(loadPlanState("test")).toBeNull();
});
it("clearPlanState is a no-op when no file exists", () => {
expect(() => clearPlanState("nonexistent")).not.toThrow();
});
it("returns null on malformed JSON", () => {
writeFixture(planStatePath("broken"), "not json {");
expect(loadPlanState("broken")).toBeNull();
});
it("returns null on wrong version", () => {
writeFixture(
planStatePath("v0"),
JSON.stringify({ version: 0, steps: [], completedStepIds: [], updatedAt: "x" }),
);
expect(loadPlanState("v0")).toBeNull();
});
it("filters out malformed step entries", () => {
writeFixture(
planStatePath("partial"),
JSON.stringify({
version: 1,
steps: [
{ id: "ok", title: "good", action: "do" },
{ id: "", title: "no id", action: "x" },
{ id: "bad", title: "", action: "x" },
null,
"not-an-object",
{ id: "ok-2", title: "also good", action: "do2" },
],
completedStepIds: ["ok"],
updatedAt: new Date().toISOString(),
}),
);
const loaded = loadPlanState("partial");
expect(loaded?.steps).toHaveLength(2);
expect(loaded?.steps.map((s) => s.id)).toEqual(["ok", "ok-2"]);
});
it("returns null when sanitization leaves zero steps (empty plan is no plan)", () => {
writeFixture(
planStatePath("emptied"),
JSON.stringify({
version: 1,
steps: [{ id: "", title: "", action: "" }],
completedStepIds: [],
updatedAt: new Date().toISOString(),
}),
);
expect(loadPlanState("emptied")).toBeNull();
});
it("strips invalid risk values rather than failing the whole file", () => {
writeFixture(
planStatePath("riskcheck"),
JSON.stringify({
version: 1,
steps: [
{ id: "a", title: "t", action: "a", risk: "critical" },
{ id: "b", title: "t", action: "a", risk: "low" },
],
completedStepIds: [],
updatedAt: new Date().toISOString(),
}),
);
const loaded = loadPlanState("riskcheck");
expect(loaded?.steps[0]?.risk).toBeUndefined();
expect(loaded?.steps[1]?.risk).toBe("low");
});
it("filters out non-string entries from completedStepIds", () => {
writeFixture(
planStatePath("badcompleted"),
JSON.stringify({
version: 1,
steps: [{ id: "x", title: "y", action: "z" }],
completedStepIds: ["x", null, 42, "", "y"],
updatedAt: new Date().toISOString(),
}),
);
const loaded = loadPlanState("badcompleted");
expect(loaded?.completedStepIds).toEqual(["x", "y"]);
});
it("sanitizes session names so unsafe chars don't escape the dir", () => {
const path = planStatePath("../etc/passwd");
expect(path).toMatch(/\.plan\.json$/);
expect(path).not.toMatch(/\.\.[\\/]etc/);
});
});
describe("archivePlanState", () => {
it("returns null when no active plan exists", () => {
expect(archivePlanState("never-touched")).toBeNull();
});
it("renames the active plan to a timestamped .done.json", () => {
savePlanState("done-test", [{ id: "x", title: "y", action: "z" }], ["x"]);
const before = loadPlanState("done-test");
expect(before).not.toBeNull();
const archive = archivePlanState("done-test");
expect(archive).not.toBeNull();
expect(archive).toMatch(/\.done\.json$/);
// Active plan is gone after archive
expect(loadPlanState("done-test")).toBeNull();
});
it("preserves the original payload in the archive", async () => {
const steps = [
{ id: "step-1", title: "extract", action: "split tokens", risk: "med" as const },
];
savePlanState("payload-test", steps, ["step-1"]);
const archive = archivePlanState("payload-test");
expect(archive).not.toBeNull();
const fs = await import("node:fs");
const raw = fs.readFileSync(archive!, "utf8");
const parsed = JSON.parse(raw);
expect(parsed.steps).toEqual(steps);
expect(parsed.completedStepIds).toEqual(["step-1"]);
expect(parsed.version).toBe(1);
});
it("two archives within the same millisecond don't collide", () => {
// Random suffix prevents filename collision when consecutive
// mark_step_complete calls finalize a plan and immediately a new
// submit_plan + complete cycle archives again. Hard to literally
// race in a test; we settle for archiving twice rapidly and
// checking we got two different paths.
savePlanState("race-1", [{ id: "x", title: "y", action: "z" }], ["x"]);
const a = archivePlanState("race-1");
savePlanState("race-1", [{ id: "x", title: "y", action: "z" }], ["x"]);
const b = archivePlanState("race-1");
expect(a).not.toBeNull();
expect(b).not.toBeNull();
expect(a).not.toBe(b);
});
});
describe("listPlanArchives", () => {
it("returns empty when no archives exist", () => {
expect(listPlanArchives("nothing-here")).toEqual([]);
});
it("lists archived plans newest-first by completedAt", async () => {
// Two plans for the same session, archived ~milliseconds apart.
// Force completedAt by hand-writing instead of going through
// savePlanState so timing isn't a flaky factor.
const oldStamp = "2026-04-01T10:00:00.000Z";
const newStamp = "2026-04-20T15:30:00.000Z";
const fs = await import("node:fs");
const { join: pj } = await import("node:path");
const dir = pj(tempHome, ".reasonix", "sessions");
fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(
pj(dir, "test-list.plan.2026-04-01-old.done.json"),
JSON.stringify({
version: 1,
steps: [{ id: "x", title: "y", action: "z" }],
completedStepIds: ["x"],
updatedAt: oldStamp,
}),
);
fs.writeFileSync(
pj(dir, "test-list.plan.2026-04-20-new.done.json"),
JSON.stringify({
version: 1,
steps: [
{ id: "a", title: "b", action: "c" },
{ id: "d", title: "e", action: "f" },
],
completedStepIds: ["a", "d"],
updatedAt: newStamp,
}),
);
const archives = listPlanArchives("test-list");
expect(archives).toHaveLength(2);
expect(archives[0]?.completedAt).toBe(newStamp);
expect(archives[1]?.completedAt).toBe(oldStamp);
expect(archives[0]?.steps).toHaveLength(2);
});
it("ignores active plan.json (only .done.json files count)", () => {
savePlanState("active-only", [{ id: "x", title: "y", action: "z" }], []);
expect(listPlanArchives("active-only")).toEqual([]);
});
it("does NOT cross sessions — each project sees its own archives", async () => {
const fs = await import("node:fs");
const { join: pj } = await import("node:path");
const dir = pj(tempHome, ".reasonix", "sessions");
fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(
pj(dir, "project-a.plan.2026-04-01-x.done.json"),
JSON.stringify({
version: 1,
steps: [{ id: "x", title: "y", action: "z" }],
completedStepIds: [],
updatedAt: "2026-04-01T10:00:00.000Z",
}),
);
fs.writeFileSync(
pj(dir, "project-b.plan.2026-04-02-y.done.json"),
JSON.stringify({
version: 1,
steps: [{ id: "x", title: "y", action: "z" }],
completedStepIds: [],
updatedAt: "2026-04-02T10:00:00.000Z",
}),
);
expect(listPlanArchives("project-a")).toHaveLength(1);
expect(listPlanArchives("project-b")).toHaveLength(1);
});
it("skips corrupt archives without failing the whole list", async () => {
const fs = await import("node:fs");
const { join: pj } = await import("node:path");
const dir = pj(tempHome, ".reasonix", "sessions");
fs.mkdirSync(dir, { recursive: true });
// One good, one malformed JSON, one wrong-version, one zero-steps.
fs.writeFileSync(
pj(dir, "robust.plan.2026-01-good.done.json"),
JSON.stringify({
version: 1,
steps: [{ id: "x", title: "y", action: "z" }],
completedStepIds: [],
updatedAt: "2026-01-15T00:00:00.000Z",
}),
);
fs.writeFileSync(pj(dir, "robust.plan.2026-01-bad-json.done.json"), "{ not json");
fs.writeFileSync(
pj(dir, "robust.plan.2026-01-bad-version.done.json"),
JSON.stringify({ version: 99, steps: [], completedStepIds: [] }),
);
fs.writeFileSync(
pj(dir, "robust.plan.2026-01-empty.done.json"),
JSON.stringify({
version: 1,
steps: [],
completedStepIds: [],
updatedAt: "2026-01-01T00:00:00.000Z",
}),
);
const archives = listPlanArchives("robust");
expect(archives).toHaveLength(1);
expect(archives[0]?.steps).toHaveLength(1);
});
it("falls back to mtime when updatedAt is missing or unparseable", async () => {
const fs = await import("node:fs");
const { join: pj } = await import("node:path");
const dir = pj(tempHome, ".reasonix", "sessions");
fs.mkdirSync(dir, { recursive: true });
// Archive without updatedAt should still surface, dated by mtime.
fs.writeFileSync(
pj(dir, "fallback.plan.2026-01-x.done.json"),
JSON.stringify({
version: 1,
steps: [{ id: "x", title: "y", action: "z" }],
completedStepIds: [],
// updatedAt deliberately omitted
}),
);
const archives = listPlanArchives("fallback");
expect(archives).toHaveLength(1);
// Should be a valid ISO timestamp (mtime fallback) — not empty
expect(archives[0]?.completedAt).toMatch(/^\d{4}-\d{2}-\d{2}T/);
});
});
describe("relativeTime", () => {
const NOW = Date.parse("2026-04-24T12:00:00.000Z");
it("renders sub-minute as seconds", () => {
expect(relativeTime("2026-04-24T11:59:30.000Z", NOW)).toBe("30s ago");
expect(relativeTime("2026-04-24T12:00:00.000Z", NOW)).toBe("0s ago");
});
it("renders minutes / hours / days", () => {
expect(relativeTime("2026-04-24T11:55:00.000Z", NOW)).toBe("5m ago");
expect(relativeTime("2026-04-24T10:00:00.000Z", NOW)).toBe("2h ago");
expect(relativeTime("2026-04-22T12:00:00.000Z", NOW)).toBe("2d ago");
});
it("falls back to date-only for >7 days", () => {
expect(relativeTime("2026-04-01T12:00:00.000Z", NOW)).toBe("2026-04-01");
});
it("returns the raw string for unparseable input", () => {
expect(relativeTime("not a date", NOW)).toBe("not a date");
});
});
+372 -1
View File
@@ -6,7 +6,12 @@
import { describe, expect, it } from "vitest";
import { ToolRegistry } from "../src/tools.js";
import { PlanProposedError, registerPlanTool } from "../src/tools/plan.js";
import {
PlanCheckpointError,
PlanProposedError,
PlanRevisionProposedError,
registerPlanTool,
} from "../src/tools/plan.js";
describe("ToolRegistry plan mode", () => {
it("starts with plan mode off by default", () => {
@@ -192,4 +197,370 @@ describe("registerPlanTool + submit_plan", () => {
const out = await reg.dispatch("submit_plan", JSON.stringify({ plan: "\n\n trimmed \n" }));
expect(JSON.parse(out).plan).toBe("trimmed");
});
it("carries an optional summary through toToolResult", async () => {
const reg = new ToolRegistry();
registerPlanTool(reg);
reg.setPlanMode(true);
const out = await reg.dispatch(
"submit_plan",
JSON.stringify({ plan: "# Plan", summary: "Refactor auth into signed tokens" }),
);
expect(JSON.parse(out).summary).toBe("Refactor auth into signed tokens");
});
it("omits summary when blank / whitespace-only", async () => {
const reg = new ToolRegistry();
registerPlanTool(reg);
reg.setPlanMode(true);
const out = await reg.dispatch(
"submit_plan",
JSON.stringify({ plan: "# Plan", summary: " " }),
);
expect(JSON.parse(out).summary).toBeUndefined();
});
it("accepts an optional steps array and surfaces it in the tool result", async () => {
const reg = new ToolRegistry();
const submitted: Array<{ plan: string; steps?: unknown }> = [];
registerPlanTool(reg, {
onPlanSubmitted: (plan, steps) => submitted.push({ plan, steps }),
});
reg.setPlanMode(true);
const steps = [
{ id: "step-1", title: "Refactor auth", action: "Extract tokens into a module." },
{
id: "step-2",
title: "Update tests",
action: "Rewrite auth.test.ts to use the new module.",
},
];
const out = await reg.dispatch("submit_plan", JSON.stringify({ plan: "# Plan", steps }));
const parsed = JSON.parse(out);
expect(parsed.steps).toEqual(steps);
expect(submitted[0]?.steps).toEqual(steps);
});
it("drops malformed step entries and omits steps entirely when none remain", async () => {
const reg = new ToolRegistry();
registerPlanTool(reg);
reg.setPlanMode(true);
const out = await reg.dispatch(
"submit_plan",
JSON.stringify({
plan: "# Plan",
steps: [
{ id: "", title: "missing id", action: "a" },
{ id: "x", title: "", action: "a" },
{ id: "y", title: "t", action: "" },
"not-an-object",
null,
],
}),
);
const parsed = JSON.parse(out);
expect(parsed.steps).toBeUndefined();
});
it("accepts and preserves valid risk levels on steps", async () => {
const reg = new ToolRegistry();
registerPlanTool(reg);
reg.setPlanMode(true);
const out = await reg.dispatch(
"submit_plan",
JSON.stringify({
plan: "# Plan",
steps: [
{ id: "step-1", title: "safe", action: "local edit", risk: "low" },
{ id: "step-2", title: "medium", action: "multi-file edit", risk: "med" },
{ id: "step-3", title: "risky", action: "prod migration", risk: "high" },
],
}),
);
const parsed = JSON.parse(out);
expect(parsed.steps).toEqual([
{ id: "step-1", title: "safe", action: "local edit", risk: "low" },
{ id: "step-2", title: "medium", action: "multi-file edit", risk: "med" },
{ id: "step-3", title: "risky", action: "prod migration", risk: "high" },
]);
});
it("drops malformed risk values rather than letting them through", async () => {
const reg = new ToolRegistry();
registerPlanTool(reg);
reg.setPlanMode(true);
const out = await reg.dispatch(
"submit_plan",
JSON.stringify({
plan: "# Plan",
steps: [
{ id: "step-1", title: "a", action: "b", risk: "critical" },
{ id: "step-2", title: "c", action: "d", risk: 3 },
{ id: "step-3", title: "e", action: "f" },
],
}),
);
const parsed = JSON.parse(out);
// "critical" and 3 are rejected → risk field omitted; step-3 had
// no risk to begin with. All three steps survive (the step itself
// was well-formed; only the bad risk got dropped).
expect(parsed.steps).toEqual([
{ id: "step-1", title: "a", action: "b" },
{ id: "step-2", title: "c", action: "d" },
{ id: "step-3", title: "e", action: "f" },
]);
});
it("keeps only the well-formed steps when the array is mixed", async () => {
const reg = new ToolRegistry();
registerPlanTool(reg);
reg.setPlanMode(true);
const out = await reg.dispatch(
"submit_plan",
JSON.stringify({
plan: "# Plan",
steps: [
{ id: "step-1", title: "good", action: "do thing" },
{ id: "", title: "bad", action: "x" },
{ id: "step-2", title: "also good", action: "do other thing" },
],
}),
);
const parsed = JSON.parse(out);
expect(parsed.steps).toEqual([
{ id: "step-1", title: "good", action: "do thing" },
{ id: "step-2", title: "also good", action: "do other thing" },
]);
});
});
describe("registerPlanTool + mark_step_complete", () => {
it("registers mark_step_complete as readOnly (safe during plan mode)", () => {
const reg = new ToolRegistry();
registerPlanTool(reg);
expect(reg.has("mark_step_complete")).toBe(true);
expect(reg.get("mark_step_complete")?.readOnly).toBe(true);
});
it("throws PlanCheckpointError with the step_completed payload and fires onStepCompleted", async () => {
const reg = new ToolRegistry();
const seen: unknown[] = [];
registerPlanTool(reg, { onStepCompleted: (u) => seen.push(u) });
const out = await reg.dispatch(
"mark_step_complete",
JSON.stringify({
stepId: "step-1",
title: "Refactor auth",
result: "Moved tokens into src/auth/tokens.ts.",
notes: "Had to rename one export.",
}),
);
const parsed = JSON.parse(out);
expect(parsed.kind).toBe("step_completed");
expect(parsed.stepId).toBe("step-1");
expect(parsed.title).toBe("Refactor auth");
expect(parsed.result).toBe("Moved tokens into src/auth/tokens.ts.");
expect(parsed.notes).toBe("Had to rename one export.");
expect(parsed.error).toMatch(/^PlanCheckpointError:/);
// STOP instruction — same pattern as PlanProposedError so the
// model doesn't race past the picker with more tool calls.
expect(parsed.error).toMatch(/STOP/);
expect(seen).toHaveLength(1);
expect((seen[0] as { stepId: string }).stepId).toBe("step-1");
});
it("omits optional fields when empty", async () => {
const reg = new ToolRegistry();
registerPlanTool(reg);
const out = await reg.dispatch(
"mark_step_complete",
JSON.stringify({ stepId: "step-1", result: "done" }),
);
const parsed = JSON.parse(out);
expect(parsed.title).toBeUndefined();
expect(parsed.notes).toBeUndefined();
expect(parsed.result).toBe("done");
expect(parsed.error).toMatch(/^PlanCheckpointError:/);
});
it("rejects an empty stepId", async () => {
const reg = new ToolRegistry();
registerPlanTool(reg);
const out = await reg.dispatch(
"mark_step_complete",
JSON.stringify({ stepId: " ", result: "done" }),
);
expect(JSON.parse(out).error).toMatch(/stepId is required/);
});
it("rejects an empty result with a pointer at what to write", async () => {
const reg = new ToolRegistry();
registerPlanTool(reg);
const out = await reg.dispatch(
"mark_step_complete",
JSON.stringify({ stepId: "step-1", result: " " }),
);
expect(JSON.parse(out).error).toMatch(/result is required/);
});
});
describe("PlanCheckpointError", () => {
it("carries the step payload on the instance and in toToolResult()", () => {
const err = new PlanCheckpointError({
stepId: "step-2",
title: "Update tests",
result: "Rewrote three suites.",
notes: "One test still flaky.",
});
expect(err.name).toBe("PlanCheckpointError");
expect(err.stepId).toBe("step-2");
expect(err.title).toBe("Update tests");
expect(err.result).toBe("Rewrote three suites.");
expect(err.notes).toBe("One test still flaky.");
const payload = err.toToolResult();
expect(payload.kind).toBe("step_completed");
expect(payload.stepId).toBe("step-2");
expect(payload.error).toMatch(/^PlanCheckpointError:/);
expect(payload.error).toMatch(/STOP/);
});
it("omits title/notes from toToolResult when they weren't supplied", () => {
const err = new PlanCheckpointError({ stepId: "step-1", result: "done" });
const payload = err.toToolResult();
expect(payload.title).toBeUndefined();
expect(payload.notes).toBeUndefined();
expect(payload.result).toBe("done");
});
});
describe("PlanRevisionProposedError", () => {
it("carries reason / remainingSteps / summary on the instance and in toToolResult()", () => {
const err = new PlanRevisionProposedError(
"User asked to skip cookie migration.",
[
{ id: "step-3", title: "Skip migration", action: "Document the skip", risk: "low" },
{ id: "step-4", title: "Update tests", action: "Adjust suite", risk: "med" },
],
"Refactor without prod migration",
);
expect(err.name).toBe("PlanRevisionProposedError");
expect(err.remainingSteps).toHaveLength(2);
const payload = err.toToolResult();
expect(payload.reason).toBe("User asked to skip cookie migration.");
expect(payload.summary).toBe("Refactor without prod migration");
expect(payload.remainingSteps).toHaveLength(2);
expect(payload.error).toMatch(/^PlanRevisionProposedError:/);
expect(payload.error).toMatch(/STOP/);
});
it("omits summary from toToolResult when not provided", () => {
const err = new PlanRevisionProposedError("a reason", [{ id: "x", title: "y", action: "z" }]);
expect(err.toToolResult().summary).toBeUndefined();
});
});
describe("registerPlanTool + revise_plan", () => {
it("registers revise_plan as readOnly (it only emits a proposal, no side effects)", () => {
const reg = new ToolRegistry();
registerPlanTool(reg);
expect(reg.has("revise_plan")).toBe(true);
expect(reg.get("revise_plan")?.readOnly).toBe(true);
});
it("throws PlanRevisionProposedError with the structured payload", async () => {
const reg = new ToolRegistry();
const seen: Array<{ reason: string; steps: number }> = [];
registerPlanTool(reg, {
onPlanRevisionProposed: (reason, steps) => seen.push({ reason, steps: steps.length }),
});
const out = await reg.dispatch(
"revise_plan",
JSON.stringify({
reason: "User asked to skip step 3.",
remainingSteps: [
{ id: "step-3", title: "skip", action: "do nothing", risk: "low" },
{ id: "step-4", title: "tests", action: "update", risk: "med" },
],
}),
);
const parsed = JSON.parse(out);
expect(parsed.reason).toBe("User asked to skip step 3.");
expect(parsed.remainingSteps).toHaveLength(2);
expect(parsed.error).toMatch(/^PlanRevisionProposedError:/);
expect(seen).toHaveLength(1);
expect(seen[0]?.steps).toBe(2);
});
it("rejects empty reason", async () => {
const reg = new ToolRegistry();
registerPlanTool(reg);
const out = await reg.dispatch(
"revise_plan",
JSON.stringify({
reason: " ",
remainingSteps: [{ id: "x", title: "y", action: "z" }],
}),
);
expect(JSON.parse(out).error).toMatch(/reason is required/);
});
it("rejects empty remainingSteps array", async () => {
const reg = new ToolRegistry();
registerPlanTool(reg);
const out = await reg.dispatch(
"revise_plan",
JSON.stringify({ reason: "skip everything", remainingSteps: [] }),
);
expect(JSON.parse(out).error).toMatch(/non-empty array/);
});
it("rejects when sanitization drops all steps", async () => {
const reg = new ToolRegistry();
registerPlanTool(reg);
const out = await reg.dispatch(
"revise_plan",
JSON.stringify({
reason: "ok",
remainingSteps: [
{ id: "", title: "no id", action: "x" },
{ id: "x", title: "", action: "x" },
{ id: "y", title: "z", action: "" },
"not-an-object",
],
}),
);
expect(JSON.parse(out).error).toMatch(/non-empty array/);
});
it("preserves valid risk levels through revision", async () => {
const reg = new ToolRegistry();
registerPlanTool(reg);
const out = await reg.dispatch(
"revise_plan",
JSON.stringify({
reason: "tighten",
remainingSteps: [
{ id: "a", title: "t", action: "a", risk: "high" },
{ id: "b", title: "t", action: "a", risk: "low" },
],
}),
);
const parsed = JSON.parse(out);
expect(parsed.remainingSteps[0].risk).toBe("high");
expect(parsed.remainingSteps[1].risk).toBe("low");
});
it("includes an optional summary when provided", async () => {
const reg = new ToolRegistry();
registerPlanTool(reg);
const out = await reg.dispatch(
"revise_plan",
JSON.stringify({
reason: "ok",
remainingSteps: [{ id: "x", title: "y", action: "z" }],
summary: "Refactor without migration",
}),
);
expect(JSON.parse(out).summary).toBe("Refactor without migration");
});
});
+21 -14
View File
@@ -42,36 +42,42 @@ describe("resolveDefaults", () => {
}
});
it("empty flags + empty config → hard-coded fast preset", () => {
it("empty flags + empty config → hard-coded smart preset (flash + max)", () => {
const r = resolveDefaults({});
expect(r.model).toBe("deepseek-chat");
expect(r.model).toBe("deepseek-v4-flash");
expect(r.reasoningEffort).toBe("max");
expect(r.harvest).toBe(false);
expect(r.branch).toBeUndefined();
expect(r.mcp).toEqual([]);
expect(r.session).toBe("default");
});
it("config.preset 'smart' flips harvest on and switches model", () => {
writeConfig({ preset: "smart" }, join(home, ".reasonix", "config.json"));
it("config.preset 'fast' drops effort to high (still flash, no harvest)", () => {
writeConfig({ preset: "fast" }, join(home, ".reasonix", "config.json"));
const r = resolveDefaults({});
expect(r.model).toBe("deepseek-reasoner");
expect(r.harvest).toBe(true);
expect(r.model).toBe("deepseek-v4-flash");
expect(r.reasoningEffort).toBe("high");
expect(r.harvest).toBe(false);
expect(r.branch).toBeUndefined();
});
it("--preset max overrides config.preset=fast", () => {
it("--preset max overrides config.preset=fast → pro + max, no branch", () => {
writeConfig({ preset: "fast" }, join(home, ".reasonix", "config.json"));
const r = resolveDefaults({ preset: "max" });
expect(r.model).toBe("deepseek-v4-pro");
expect(r.branch).toBe(3);
expect(r.reasoningEffort).toBe("max");
expect(r.harvest).toBe(false);
// branch is NEVER part of a preset — only /branch or --branch turns it on.
expect(r.branch).toBeUndefined();
});
it("--model wins even when --preset is set", () => {
const r = resolveDefaults({ preset: "max", model: "deepseek-chat" });
expect(r.model).toBe("deepseek-chat");
// preset still controls harvest/branch
expect(r.harvest).toBe(true);
expect(r.branch).toBe(3);
const r = resolveDefaults({ preset: "max", model: "deepseek-v4-flash" });
expect(r.model).toBe("deepseek-v4-flash");
// preset still controls effort/harvest/branch
expect(r.reasoningEffort).toBe("max");
expect(r.harvest).toBe(false);
expect(r.branch).toBeUndefined();
});
it("--mcp overrides config.mcp wholesale (no merging)", () => {
@@ -96,7 +102,8 @@ describe("resolveDefaults", () => {
it("--no-config ignores the config entirely", () => {
writeConfig({ preset: "max", mcp: ["x=cmd"] }, join(home, ".reasonix", "config.json"));
const r = resolveDefaults({ noConfig: true });
expect(r.model).toBe("deepseek-chat"); // fast defaults
expect(r.model).toBe("deepseek-v4-flash"); // smart defaults (new default)
expect(r.reasoningEffort).toBe("max");
expect(r.mcp).toEqual([]);
});
+9 -2
View File
@@ -239,10 +239,17 @@ describe("registerShellTools — dispatch integration", () => {
rmSync(tmp, { recursive: true, force: true });
});
it("registers run_command", () => {
it("registers run_command + background tools", () => {
const registry = new ToolRegistry();
registerShellTools(registry, { rootDir: tmp });
expect(registry.size).toBe(1);
// run_command (sync) + run_background / job_output / stop_job /
// list_jobs (background family).
expect(registry.size).toBe(5);
expect(registry.has("run_command")).toBe(true);
expect(registry.has("run_background")).toBe(true);
expect(registry.has("job_output")).toBe(true);
expect(registry.has("stop_job")).toBe(true);
expect(registry.has("list_jobs")).toBe(true);
});
it("auto-runs allowlisted commands and returns formatted output", async () => {
+10 -5
View File
@@ -221,7 +221,7 @@ describe("applySkillsIndex", () => {
expect(first).toBe(second);
});
it("marks subagent-runAs skills with the 🧬 prefix in the index", () => {
it("tags subagent-runAs skills AFTER the name in the index (not before)", () => {
writeSkillDir(
projectRoot,
"global",
@@ -239,8 +239,13 @@ describe("applySkillsIndex", () => {
home,
);
const out = applySkillsIndex(BASE, { homeDir: home, projectRoot, disableBuiltins: true });
expect(out).toContain("- 🧬 lookup — Look something up");
// Name-first, tag-after: prevents the model from copying "🧬 lookup"
// as the skill name into `run_skill({ name: ... })`.
expect(out).toContain("- lookup [🧬 subagent] — Look something up");
expect(out).toContain("- fmt — Format the codebase");
// Old "🧬 name" format must not regress — there was a user bug where
// the model copied the marker verbatim and run_skill failed lookup.
expect(out).not.toMatch(/- 🧬 lookup\b/);
expect(out).not.toContain("- 🧬 fmt");
});
});
@@ -341,10 +346,10 @@ describe("Built-in skills", () => {
expect(store.list()).toEqual([]);
});
it("builtins surface with the 🧬 marker in applySkillsIndex", () => {
it("builtins surface with the subagent tag after the name in applySkillsIndex", () => {
const out = applySkillsIndex(BASE, { homeDir: home }); // builtins ON
expect(out).toContain("# Skills");
expect(out).toContain("🧬 explore");
expect(out).toContain("🧬 research");
expect(out).toContain("explore [🧬 subagent]");
expect(out).toContain("research [🧬 subagent]");
});
});
+167 -14
View File
@@ -49,8 +49,10 @@ describe("handleSlash", () => {
const r = handleSlash("clear", [], makeLoop());
expect(r.clear).toBe(true);
// Clear should also explain that context is NOT dropped — users
// keep confusing this with /new.
expect(r.info).toMatch(/visible scrollback only/);
// keep confusing this with /new. 0.7.1 bumped the action from a
// React-state-only clear to a real terminal wipe (CSI 2J+3J),
// so the info line says "terminal cleared" now.
expect(r.info).toMatch(/terminal cleared/);
expect(r.info).toMatch(/\/new/);
});
@@ -265,7 +267,10 @@ describe("handleSlash", () => {
content: "ERROR: line failed with detail and context\n".repeat(2000),
});
const r = handleSlash("compact", [], loop);
expect(r.info).toMatch(/compacted 1 tool result/);
// Slash message now covers both passes (tool results + tool-call
// args); the "1 payload" and a token-saved count are what matters
// for this test's invariant.
expect(r.info).toMatch(/compacted 1 payload/);
expect(r.info).toMatch(/saved [\d,]+ tokens/);
// After compaction the tool content should be much smaller than
// the original 84KB, comfortably under the cap's char worst-case.
@@ -294,31 +299,35 @@ describe("handleSlash", () => {
expect(r.info).toMatch(/\/compact/);
});
it("/preset fast = deepseek-chat, no harvest, no branch", () => {
it("/preset fast = v4-flash + effort=high, no harvest, no branch", () => {
const loop = makeLoop();
handleSlash("model", ["deepseek-reasoner"], loop);
handleSlash("model", ["deepseek-v4-pro"], loop);
handleSlash("harvest", ["on"], loop);
handleSlash("branch", ["3"], loop);
handleSlash("preset", ["fast"], loop);
expect(loop.model).toBe("deepseek-chat");
expect(loop.model).toBe("deepseek-v4-flash");
expect(loop.reasoningEffort).toBe("high");
expect(loop.harvestEnabled).toBe(false);
expect(loop.branchEnabled).toBe(false);
});
it("/preset smart = reasoner + harvest, no branch", () => {
it("/preset smart = v4-flash + effort=max, no harvest, no branch", () => {
const loop = makeLoop();
handleSlash("preset", ["smart"], loop);
expect(loop.model).toBe("deepseek-reasoner");
expect(loop.harvestEnabled).toBe(true);
expect(loop.model).toBe("deepseek-v4-flash");
expect(loop.reasoningEffort).toBe("max");
expect(loop.harvestEnabled).toBe(false);
expect(loop.branchEnabled).toBe(false);
});
it("/preset max = reasoner + harvest + branch3", () => {
it("/preset max = v4-pro + effort=max, no harvest, no branch", () => {
const loop = makeLoop();
handleSlash("preset", ["max"], loop);
expect(loop.model).toBe("deepseek-reasoner");
expect(loop.harvestEnabled).toBe(true);
expect(loop.branchOptions.budget).toBe(3);
expect(loop.model).toBe("deepseek-v4-pro");
expect(loop.reasoningEffort).toBe("max");
expect(loop.harvestEnabled).toBe(false);
// Branch is NEVER auto-enabled by a preset — manual /branch only.
expect(loop.branchEnabled).toBe(false);
});
it("/preset with bad name returns usage", () => {
@@ -328,7 +337,7 @@ describe("handleSlash", () => {
it("/help mentions presets", () => {
const r = handleSlash("help", [], makeLoop());
expect(r.info).toMatch(/Presets:/);
expect(r.info).toMatch(/Presets/);
expect(r.info).toMatch(/fast/);
expect(r.info).toMatch(/smart/);
expect(r.info).toMatch(/max/);
@@ -849,6 +858,150 @@ describe("handleSlash", () => {
expect(r.info).toMatch(/nothing to forget/);
});
describe("/plans + /replay", () => {
let tempHome: string;
let originalHome: string | undefined;
let originalUserProfile: string | undefined;
beforeEach(() => {
tempHome = mkdtempSync(join(tmpdir(), "reasonix-replay-slash-"));
originalHome = process.env.HOME;
originalUserProfile = process.env.USERPROFILE;
process.env.HOME = tempHome;
process.env.USERPROFILE = tempHome;
});
afterEach(() => {
process.env.HOME = originalHome;
process.env.USERPROFILE = originalUserProfile;
rmSync(tempHome, { recursive: true, force: true });
});
function loopWithSession(name: string): CacheFirstLoop {
const client = new DeepSeekClient({
apiKey: "sk-test",
fetch: vi.fn() as unknown as typeof fetch,
});
return new CacheFirstLoop({
client,
prefix: new ImmutablePrefix({ system: "s" }),
session: name,
});
}
function writeArchive(
sessionName: string,
stamp: string,
payload: Record<string, unknown>,
): void {
const dir = join(tempHome, ".reasonix", "sessions");
const fs = require("node:fs") as typeof import("node:fs");
fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(
join(dir, `${sessionName}.plan.${stamp}.done.json`),
JSON.stringify(payload),
);
}
it("/replay without args returns the newest archive", () => {
const loop = loopWithSession("replay-test");
writeArchive("replay-test", "2026-04-01-old", {
version: 1,
steps: [{ id: "step-1", title: "old work", action: "a" }],
completedStepIds: ["step-1"],
updatedAt: "2026-04-01T00:00:00.000Z",
summary: "Older plan",
});
writeArchive("replay-test", "2026-04-20-new", {
version: 1,
steps: [
{ id: "step-1", title: "extract", action: "a" },
{ id: "step-2", title: "rewire", action: "b" },
],
completedStepIds: ["step-1", "step-2"],
updatedAt: "2026-04-20T00:00:00.000Z",
summary: "Newer plan",
body: "# Plan\n- do thing",
});
const r = handleSlash("replay", [], loop);
expect(r.replayPlan).toBeDefined();
expect(r.replayPlan?.summary).toBe("Newer plan");
expect(r.replayPlan?.steps).toHaveLength(2);
expect(r.replayPlan?.body).toBe("# Plan\n- do thing");
expect(r.replayPlan?.index).toBe(1);
expect(r.replayPlan?.total).toBe(2);
});
it("/replay 2 returns the older archive in a 2-archive session", () => {
const loop = loopWithSession("replay-idx");
writeArchive("replay-idx", "2026-04-01-a", {
version: 1,
steps: [{ id: "x", title: "y", action: "z" }],
completedStepIds: ["x"],
updatedAt: "2026-04-01T00:00:00.000Z",
summary: "Older",
});
writeArchive("replay-idx", "2026-04-20-b", {
version: 1,
steps: [{ id: "x", title: "y", action: "z" }],
completedStepIds: ["x"],
updatedAt: "2026-04-20T00:00:00.000Z",
summary: "Newer",
});
const r = handleSlash("replay", ["2"], loop);
expect(r.replayPlan?.summary).toBe("Older");
expect(r.replayPlan?.index).toBe(2);
});
it("/replay rejects out-of-range index", () => {
const loop = loopWithSession("replay-oob");
writeArchive("replay-oob", "2026-04-20-a", {
version: 1,
steps: [{ id: "x", title: "y", action: "z" }],
completedStepIds: [],
updatedAt: "2026-04-20T00:00:00.000Z",
});
const r = handleSlash("replay", ["5"], loop);
expect(r.replayPlan).toBeUndefined();
expect(r.info).toMatch(/invalid index/);
});
it("/replay says nothing to replay when no archives exist", () => {
const loop = loopWithSession("replay-empty");
const r = handleSlash("replay", [], loop);
expect(r.replayPlan).toBeUndefined();
expect(r.info).toMatch(/no archived plans yet/);
});
it("/replay needs a session", () => {
const r = handleSlash("replay", [], makeLoop());
expect(r.replayPlan).toBeUndefined();
expect(r.info).toMatch(/no session attached/);
});
it("/plans surfaces the summary as the active plan label", () => {
const loop = loopWithSession("plans-summary");
const fs = require("node:fs") as typeof import("node:fs");
const dir = join(tempHome, ".reasonix", "sessions");
fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(
join(dir, "plans-summary.plan.json"),
JSON.stringify({
version: 1,
steps: [
{ id: "s1", title: "a", action: "b" },
{ id: "s2", title: "c", action: "d" },
],
completedStepIds: ["s1"],
updatedAt: new Date().toISOString(),
summary: "Refactor auth into signed tokens",
}),
);
const r = handleSlash("plans", [], loop);
expect(r.info).toMatch(/Refactor auth into signed tokens/);
expect(r.info).toMatch(/1\/2/);
});
});
describe("/memory", () => {
let root: string;
const originalEnv = process.env.REASONIX_MEMORY;
+4 -1
View File
@@ -288,7 +288,10 @@ describe("registerSubagentTool", () => {
registerSubagentTool(parent, { client });
// "gpt-4" is not a deepseek-* model — should be ignored.
await parent.dispatch("spawn_subagent", JSON.stringify({ task: "go", model: "gpt-4" }));
expect(seenModels[0]).toBe("deepseek-v4-pro");
// Subagent default was pro pre-0.6; now flash to keep explore/research
// cheap. Skill frontmatter `model:` is the opt-in override for skills
// that empirically benefit from pro.
expect(seenModels[0]).toBe("deepseek-v4-flash");
});
it("aborts the child when the parent's tool ctx signal fires", async () => {
+164
View File
@@ -0,0 +1,164 @@
/**
* summarizeToolResult — the one-line tool-row renderer that powers
* compact scrollback. Pure function; lives outside Ink so we can
* test the per-tool-name and structured-payload branches directly.
*/
import { describe, expect, it } from "vitest";
import { formatDuration, summarizeToolResult } from "../src/cli/ui/tool-summary.js";
describe("summarizeToolResult — error envelopes", () => {
it("flags ERROR:-prefixed text as a real error and strips the prefix", () => {
const out = summarizeToolResult("anything", "ERROR: file not found");
expect(out.isError).toBe(true);
expect(out.summary).toBe("file not found");
});
it("treats structured {error:...} JSON as an error and shows tag + detail", () => {
const out = summarizeToolResult("read_file", JSON.stringify({ error: "ENOENT: no such file" }));
expect(out.isError).toBe(true);
expect(out.summary).toMatch(/^ENOENT/);
});
it("recognizes Plan / Choice control-flow signals as NON-errors", () => {
const cases = [
"PlanProposedError",
"PlanCheckpointError",
"PlanRevisionProposedError",
"ChoiceRequestedError",
"NeedsConfirmationError",
];
for (const tag of cases) {
const out = summarizeToolResult(
"any_tool",
JSON.stringify({ error: `${tag}: STOP — picker shown to user.` }),
);
expect(out.isError, tag).toBe(false);
expect(out.summary, tag).toMatch(new RegExp(tag));
}
});
it("falls back to the bare error tag when no detail follows the colon", () => {
const out = summarizeToolResult("x", JSON.stringify({ error: "SomeError" }));
expect(out.isError).toBe(true);
expect(out.summary).toBe("SomeError");
});
it("handles step_completed payload as a non-error tick", () => {
const out = summarizeToolResult(
"mark_step_complete",
JSON.stringify({ kind: "step_completed", stepId: "step-2", result: "wired middleware" }),
);
expect(out.isError).toBe(false);
expect(out.summary).toMatch(/✓ step-2/);
});
});
describe("summarizeToolResult — known tools", () => {
it("read_file: shows first line + line count + size", () => {
const content = "import { foo } from 'bar';\nexport function baz() {}\n";
const out = summarizeToolResult("read_file", content);
expect(out.isError).toBe(false);
expect(out.summary).toMatch(/import.*foo/);
expect(out.summary).toMatch(/3 lines/);
expect(out.summary).toMatch(/B/);
});
it("list_directory: shows entry count", () => {
const out = summarizeToolResult("list_directory", "src/\ntests/\nREADME.md\n");
expect(out.summary).toBe("3 entries");
});
it("list_directory with one entry uses singular", () => {
const out = summarizeToolResult("list_directory", "only-thing\n");
expect(out.summary).toBe("1 entry");
});
it("search_content: shows match count + first match", () => {
const out = summarizeToolResult(
"search_content",
"src/foo.ts:12: const x = 1\nsrc/bar.ts:34: const x = 2",
);
expect(out.summary).toMatch(/2 matches/);
expect(out.summary).toMatch(/src\/foo\.ts/);
});
it("search_content: explicit no-match path", () => {
const out = summarizeToolResult("search_content", "");
expect(out.summary).toBe("no matches");
});
it("run_command: surfaces exit code and first line", () => {
const out = summarizeToolResult("run_command", "exit 0\nhello world");
expect(out.isError).toBe(false);
expect(out.summary).toMatch(/exit 0/);
});
it("run_command: non-zero exit flags the row as an error", () => {
const out = summarizeToolResult("run_command", "exit 1\nError: something went wrong");
expect(out.isError).toBe(true);
expect(out.summary).toMatch(/exit 1/);
});
});
describe("formatDuration", () => {
it("renders sub-100ms in milliseconds", () => {
expect(formatDuration(0)).toBe("0ms");
expect(formatDuration(47)).toBe("47ms");
expect(formatDuration(99)).toBe("99ms");
});
it("renders sub-second times in 1-decimal seconds", () => {
expect(formatDuration(100)).toBe("0.1s");
expect(formatDuration(450)).toBe("0.5s");
expect(formatDuration(999)).toBe("1.0s");
});
it("renders sub-10s times with one decimal", () => {
expect(formatDuration(1234)).toBe("1.2s");
expect(formatDuration(8500)).toBe("8.5s");
});
it("renders 10s–60s as integer seconds", () => {
expect(formatDuration(10_000)).toBe("10s");
expect(formatDuration(45_900)).toBe("46s");
});
it("renders minutes-and-seconds for long runs", () => {
expect(formatDuration(60_000)).toBe("1m");
expect(formatDuration(90_000)).toBe("1m30s");
expect(formatDuration(125_500)).toBe("2m6s");
});
it("returns empty string for invalid input", () => {
expect(formatDuration(Number.NaN)).toBe("");
expect(formatDuration(-1)).toBe("");
expect(formatDuration(Number.POSITIVE_INFINITY)).toBe("");
});
});
describe("summarizeToolResult — generic fallback", () => {
it("returns first line only for short content", () => {
const out = summarizeToolResult("custom_tool", "hello");
expect(out.summary).toBe("hello");
expect(out.isError).toBe(false);
});
it("appends a size hint for long content", () => {
const long = `first line\n${"x".repeat(2000)}`;
const out = summarizeToolResult("custom_tool", long);
expect(out.summary).toMatch(/first line/);
expect(out.summary).toMatch(/KB/);
});
it("handles empty string as (empty)", () => {
const out = summarizeToolResult("anything", "");
expect(out.summary).toBe("(empty)");
});
it("clips overly long single lines with an ellipsis and stays under the budget", () => {
const out = summarizeToolResult("anything", "a".repeat(500));
expect(out.summary).toMatch(/…/);
expect(out.summary.length).toBeLessThanOrEqual(80);
});
});
+26
View File
@@ -113,6 +113,32 @@ describe("run_skill tool", () => {
expect(JSON.parse(out).error).toMatch(/requires a 'name'/);
});
it("normalizes decorated names (emoji / brackets) to the bare identifier", async () => {
// Reproduces the bug where the model copied the `[🧬 subagent]` tag
// from the Skills index into the `name` argument verbatim. The
// tool strips leading non-word chars + anything past the first
// whitespace token, so these all resolve to the same skill.
writeSkill(home, "explore", "Look around", "body");
const reg = new ToolRegistry();
registerSkillTools(reg, { homeDir: home, disableBuiltins: true });
const cases = [
"🧬 explore",
"[🧬 subagent] explore",
"[🧬] explore",
" explore ",
"explore [🧬 subagent]",
];
for (const name of cases) {
const out = await reg.dispatch("run_skill", { name });
// Inline skills return the body (non-JSON markdown) on success;
// an unknown-skill error returns JSON. Presence of the unknown-
// skill text in the output is a guaranteed failure marker.
expect(out, `case ${JSON.stringify(name)}`).not.toMatch(/unknown skill/i);
expect(out, `case ${JSON.stringify(name)}`).toContain("Skill: explore");
}
});
it("dispatches subagent-runAs skills through subagentRunner", async () => {
writeSkillWithFrontmatter(
home,
+79
View File
@@ -188,4 +188,83 @@ describe("ToolRegistry", () => {
expect(reg.wasFlattened("deep")).toBe(false);
expect(reg.specs()[0]!.function.parameters.properties).toHaveProperty("a");
});
describe("tool interceptor", () => {
it("short-circuits dispatch when interceptor returns a string", async () => {
const reg = new ToolRegistry();
let fnCalled = false;
reg.register({
name: "edit_file",
fn: () => {
fnCalled = true;
return "should not run";
},
});
reg.setToolInterceptor((name) => (name === "edit_file" ? "queued" : null));
const out = await reg.dispatch("edit_file", '{"path":"foo"}');
expect(out).toBe("queued");
expect(fnCalled).toBe(false);
});
it("falls through to tool.fn when interceptor returns null", async () => {
const reg = new ToolRegistry();
reg.register({ name: "read_file", fn: () => "content" });
reg.setToolInterceptor(() => null);
const out = await reg.dispatch("read_file", "{}");
expect(out).toBe("content");
});
it("receives parsed args (including flattened→nested)", async () => {
const reg = new ToolRegistry();
reg.register({
name: "edit_file",
fn: () => "ok",
parameters: {
type: "object",
properties: { path: { type: "string" }, search: { type: "string" } },
required: ["path"],
},
});
let seen: Record<string, unknown> | null = null;
reg.setToolInterceptor((_name, args) => {
seen = args;
return "captured";
});
await reg.dispatch("edit_file", '{"path":"a","search":"b"}');
expect(seen).toEqual({ path: "a", search: "b" });
});
it("does not fire in plan mode — plan-mode refusal wins", async () => {
const reg = new ToolRegistry();
let interceptorCalled = false;
reg.register({ name: "edit_file", fn: () => "ok" });
reg.setToolInterceptor(() => {
interceptorCalled = true;
return "queued";
});
reg.setPlanMode(true);
const out = await reg.dispatch("edit_file", '{"path":"x"}');
expect(JSON.parse(out).error).toMatch(/unavailable in plan mode/);
expect(interceptorCalled).toBe(false);
});
it("setToolInterceptor(null) clears a prior install", async () => {
const reg = new ToolRegistry();
reg.register({ name: "edit_file", fn: () => "fn-output" });
reg.setToolInterceptor(() => "queued");
expect(await reg.dispatch("edit_file", "{}")).toBe("queued");
reg.setToolInterceptor(null);
expect(await reg.dispatch("edit_file", "{}")).toBe("fn-output");
});
it("surfaces interceptor throws as structured errors", async () => {
const reg = new ToolRegistry();
reg.register({ name: "edit_file", fn: () => "ok" });
reg.setToolInterceptor(() => {
throw new Error("boom");
});
const out = await reg.dispatch("edit_file", "{}");
expect(JSON.parse(out).error).toMatch(/interceptor failed — boom/);
});
});
});