Compare commits

...
81 Commits
Author SHA1 Message Date
esengine 02fcadf9e8 fix(ui): stop erasing scrollback on resize / startup so VSCode wheel-scroll works
User reported on VSCode integrated terminal: resizing the window
loses chat history and mouse wheel can no longer scroll up. Two
related symptoms, one cause:

  - VSCode's terminal interprets \x1b[3J (xterm scrollback erase)
    aggressively — wipes everything, not just the saved-off
    history. Combined with my prepended resize listener that wrote
    \x1b[2J on every resize, every drag was wiping scrollback. With
    nothing in scrollback, wheel-up has nothing to scroll to.

  - Even \x1b[2J (visible-only erase) on each resize tick takes
    the chat history with it on terminals where the spec is
    interpreted loosely.

Fix: drop the resize listener entirely; drop \x1b[3J from the
startup clear. Startup now only erases the visible viewport so the
previous shell prompt scrolls up into scrollback rather than
vanishing. Resize ghosts (Ink's eraseLines miscount on wrap)
return as a known limitation; `/clear` is the documented manual
reset.

History recall stays on Ctrl+P/N (0.7.10) so wheel-as-arrow events
don't clobber the prompt.
2026-04-26 00:26:39 -07:00
esengine 9254d3ae87 fix(ui): unbind history recall from arrow keys; use Ctrl+P / Ctrl+N
Mouse wheel on Windows Terminal + ConPTY translates to up/down
arrow key events for raw-mode child processes. Indistinguishable
from keyboard arrows at the byte level. With history recall bound
to up/down on empty buffer, every wheel-scroll on the prompt was
clobbering it with a recalled prior message.

Fix: rebind history recall to Ctrl+P (prev) / Ctrl+N (next), the
bash readline convention. Up/down arrows now no-op on a single-
line buffer and only move the cursor across lines in a multi-line
draft. Wheel scrolls again belong entirely to the terminal.

Tests updated to reflect the new binding. Placeholder hint mentions
Ctrl+P/N alongside the Ctrl+J newline hint.
2026-04-25 23:36:24 -07:00
esengine 1d3b9e9c77 fix(ui): revert alt-screen so mouse wheel scrolls again, restore main-screen + resize clear
Alt-screen fixed the resize ghost stacking but cost the user wheel
scrollback — terminals translate wheel to up/down arrow keystrokes
for alt-screen apps, and those land in PromptInput's history recall
instead of scrolling chat history. Trade-off the user rejected.

Reverted to main-screen mode:

  - Restored startup viewport+scrollback clear (\x1b[2J\x1b[3J\x1b[H).
  - Restored prepended resize listener that writes \x1b[2J\x1b[H
    before Ink's own resize handler runs.
  - Added REASONIX_DEBUG_RESIZE env-gated stderr diagnostic so we
    can verify the listener fires on the user's specific terminal +
    host (Windows Terminal + PowerShell suspected of not
    surfacing the 'resize' event consistently).

Resize ghost stacking returns as a known limitation; `/clear` resets
the screen state. This is the trade-off for keeping wheel scrollback
working.
2026-04-25 23:13:52 -07:00
esengine 8694f7767e fix(ui): switch TUI to alternate screen buffer, fix .ts↔.tsx citation typos
Two unrelated fixes shipping together as 0.7.8:

  1. Resize ghost stacking on chat.tsx: previous attempts (stdout 2J
     listener, ticker pause, killing animations) all reduced the
     symptom but couldn't fix it — Ink's eraseLines fundamentally
     miscounts logical vs visible rows on wrap, and resize re-renders
     pile up stale frames in scrollback.

     Fix: enter the terminal's alternate screen buffer (\x1b[?1049h)
     on Ink mount, leave it (\x1b[?1049l) on unmount. This is what
     vim, less, htop, lazygit, etc. do. Inside alt-screen the
     terminal owns the entire viewport; resize is handled natively
     and there's no scrollback to leak ghosts into. Trade-off: chat
     scrollback above the live region is gone after exit (returns
     to the user's pre-launch shell view). /history still dumps
     prior turns on demand.

     Removed: the previous \x1b[2J\x1b[3J\x1b[H startup clear and
     the prepended resize listener — both made redundant by alt-
     screen.

  2. Citation validator was reporting  /  as
     'file not found' even when the source is  /
     . Models routinely cite the wrong extension when
     they remember the file. Added a sibling-extensions probe in
     validateCitation: when the literal path fails, try common
     siblings (.ts↔.tsx, .js↔.jsx↔.mjs↔.cjs, .ts↔.mts↔.cts).
     Genuinely missing paths still flag.
2026-04-25 23:04:57 -07:00
esengine 6fb3de2261 fix(ui): kill animations + gradient bars to root-cause the resize ghost stacking
0.7.6 tried to mitigate ghost stacking on resize via stdout-clear
listener + ticker pause. User confirmed those still produce 3-4
stacked panels when the window is shrunk and re-expanded.

Root cause: Ink's eraseLines(N) counts LOGICAL lines, not VISUAL
rows after wrap. The 100+ char top/bottom gradient bars on the
StatsPanel always wrap on narrow widths; the per-tick wordmark
animation and per-tick prompt-bar gradient flow re-render every
120 ms; together they layer ghost frames on every resize event.

Real fix:

  - Remove the top/bottom GradientRule entirely from StatsPanel.
    Those were the dominant wrap source — wide bars on a narrow
    terminal were the eraseLines miscount's main payload.
  - Wordmark drops its useTick subscription. Sweep is now a
    static teal→fuchsia gradient computed once per render. Brand
    mark ◈ stays bold but no longer pulse-blinks.
  - PromptInput drops its useTick subscription. Left-bar gets a
    static row-indexed gradient color, cursor is a solid block
    with no blink.

Net effect: no per-tick re-render anywhere in the live region
except the existing spinners (StatusRow, OngoingToolRow,
SubagentRow) — those are short single-row strings that don't
wrap. Ink's eraseLines now matches visible row count because
nothing in the panel wraps. Resize produces at most one
state-change re-render, which the chat.tsx 2J listener catches.

Visual loss: brand wordmark no longer flows colors over time, the
prompt cursor doesn't blink. Visual structure (pills, color, role
bands, full-height left bars on assistant messages) is unchanged.

Bumps to 0.7.7.
2026-04-25 22:41:44 -07:00
esengine f5df1f9f5f fix(ui): freeze ticker during resize bursts so animations stop ghosting
User reported StatsPanel rendering 3-4 stacked ghost copies when the
terminal is resized. Two-prong fix:

  - chat.tsx — prepended stdout 'resize' listener writes \x1b[2J\x1b[H
    on every resize event so Ink's next re-render starts at cursor
    home, neutralizing eraseLines's stale storedHeight count.

  - App.tsx — new isResizing state debounced from stdout 'resize'
    events (400 ms tail). While the resize burst is in flight, the
    TickerProvider's disabled flag is set, which kills the 120 ms
    tick. With the tick frozen the per-frame animations (wordmark
    gradient flow, gradient rule flow, prompt left-bar flow, cursor
    blink) stop firing — they were the multiplier turning a single
    resize event into a stack of N ghost frames. After 400 ms with
    no further resize the ticker resumes and one clean render
    catches up.

Together: each resize event is followed by exactly one Ink re-render
on a freshly-cleared viewport, with no animation re-renders piggy-
backing on top.

Bumps package version to 0.7.6.
2026-04-25 22:25:20 -07:00
esengine 73660729ab chore(release): 0.7.5
Visual overhaul wave on top of 0.7.4. Highlights:

  - theme module: brand teal→fuchsia gradient, semantic palette, glyph
    set + gradientCells helper used across every animated surface.
  - StatsPanel: gradient header/footer rules, neon-flowing wordmark,
    threshold-colored ▰▰▰▱ context bar, icon-prefixed metric cells.
    Animations gate at cols ≥ 100 to avoid Ink eraseLines miscount.
  - PromptInput: animated left bar (vertical gradient flow), blinking
    cursor, fuchsia-bg paste sentinels, [Ctrl+J] newline hint.
  - EventLog: full-height role bands on user + assistant + edit-file
    diffs, gradient turn separators, role-pilled headers (model in
    bg-green pill, tools in yellow/red bg pill), violet bg-pill for
    reasoning previews + diff hunks, pill-ified branch/plan-state/
    stats/step-progress/plan-resumed/plan-replay rows, semantic info
    icons (▸/▲/✓/✗/↻ auto-detected from text).
  - Markdown: H1 cyan / H2 violet / H3 fuchsia bg-pill headings,
    round-bordered code blocks with language pill, brand-color
    blockquote bar.
  - Modals: shared ModalCard frame across choice / plan / shell /
    edit / checkpoint / revise / refine — each with its own accent
    so the user learns by sight.
  - LiveRows: solid-bg pill ModeStatusBar (vim modeline feel),
    streaming phase pills (WAITING/THINKING/DISPATCH/WRITING),
    UndoBanner + SubagentRow + OngoingToolRow + StatusRow all
    pill-ified.
  - Welcome card: gradient rules + sectioned hint card on first run.
  - Misc: clear viewport + scrollback at startup, fix WelcomeBanner
    gate (was never showing because the session info row already
    populated history), markdown headings drop literal '###'.
2026-04-25 22:06:48 -07:00
esengine 701dbcc32b feat(ui): clear terminal viewport + scrollback at startup
Before Ink mounts, write \x1b[2J\x1b[3J\x1b[H so the user lands on a
fresh canvas — no leftover shell prompt, last command output, or
unrelated terminal history bleeding into the first frame. Same
sequence the /clear slash command already uses. TTY-gated so CI /
piped runs don't get raw escapes in their captured stdout.
2026-04-25 22:05:37 -07:00
esengine 1603479a3d fix(ui): gate animations + secondary pills on cols≥100 to stop narrow-term flashing
Root cause: at narrow widths the StatsPanel header (wordmark +
version + model + N pills) and the PromptInput's typed line both
wrap to multiple visual rows. Ink's eraseLines counts logical rows,
not visible rows, so each tick (~120 ms re-render driven by the
wordmark / gradient bar / cursor blink animations) miscounts the
erase and leaves ghost rows in scrollback. Several seconds in the
screen looks like it's continuously scrolling — the user-reported
'screen flashing' symptom.

Fix:

  - StatsPanel — added `animate = columns >= 100` gate. Below the
    threshold the gradient rules + wordmark freeze (no per-tick
    color shift), and the secondary pills (harvest / branch×N /
    reasoning effort) hide so the header always fits one row. The
    primary pills (PLAN / AUTO / REVIEW / ⇧ PRO) and metrics row
    stay; only the optional decorations are dropped.
  - PromptInput — same gate on the prompt. Below 100 cols the
    left-bar gradient freezes and the cursor stops blinking. Above
    100 cols nothing changes.
  - 100-col threshold matches NARROW_BREAKPOINT closely (120) but is
    a hair tighter — the panel can survive 80–100 cols without
    wrapping if we drop the secondary content.

The bordered Boxes added recently (assistant left band, user left
band, edit-file diff band) live inside `<Static>`, render once per
event, never re-render, so they don't contribute to the per-tick
miscount.
2026-04-25 22:01:06 -07:00
esengine d263068bb2 fix(ui): markdown headings — drop literal '###', H3 gets fuchsia pill
User reported H3 was showing the literal sigils ('### 📖 代码探索')
inside assistant output, which defeats the heading semantic. Fixed:

  - H1 cyan pill, H2 violet pill, H3 fuchsia pill, H4+ bold accent
    with a leading ▸ marker.
  - Sigils (#, ##, ###) are stripped at the pill — the level chooses
    the bg color, not the title text. Three tiers walk down the
    brand gradient so the heading tree reads at a glance.
  - H4+ kept as bold-only (no bg) so deeply nested sections don't
    visually overpower body content.
2026-04-25 21:55:59 -07:00
esengine 83768b92e4 feat(ui): diff hunk pill, brand-color blockquote bar, paste sentinel pill
- EditFileDiff — hunk header is now a violet bg-pill (` @@ -10,3
    +10,5 @@ `) instead of a plain cyan-bold one-liner. Body lines
    have a colored gutter glyph (− for removed, + for added)
    followed by tinted body text, so add/remove rows scan as
    distinct lanes rather than colored prose.
  - Markdown blockquote — left bar now uses the brand violet
    (#c4b5fd) instead of dim gray, so quoted content carries
    visual weight that matches the rest of the palette.
  - Paste sentinel — was a magenta bold token (`[paste #1 · 12l ·
    1.4KB]`); now a solid fuchsia bg-pill so the collapsed paste
    block is unambiguous. Matches the mode/tool/badge pill idiom
    used everywhere else.
2026-04-25 21:53:35 -07:00
esengine 9174c1ba59 feat(ui): cursor blinks, refine input wrapped in ModalCard with mode-aware accent
- PromptInput cursor — was a static ▌ block; now toggles ▌↔space
    every 4 ticks (~480 ms half-period) via the same ticker that
    flows the bar gradient. Inverse-char cursor (mid-line) and
    paste-sentinel cursor toggle their `inverse` prop in lockstep
    so the character stays legible during the cursor's "off"
    half-cycle. Disabled state freezes the cursor solid so the
    busy-turn prompt reads as "frozen" not "dead".
  - PlanRefineInput — wrapped in the shared ModalCard frame with
    mode-specific accent: cyan for approve, amber for refine /
    checkpoint-revise, fuchsia for choice-custom. Each accent
    matches the related confirm modal so users learn "amber =
    plan adjustment", "fuchsia = choice flow" by sight. Inline
    cursor blinks too, on the same tick.
  - Docstring on PromptInput updated — the old "no blink" comment
    is no longer accurate.
2026-04-25 21:50:22 -07:00
esengine 95c978722a feat(ui): plan-resumed/replay/step badges, error/warn pills, modal frames everywhere
- step-progress event row — replaced the green ✓ glyph with a
    solid-bg ` ✓ STEP ` pill plus colored counter, body and notes
    indented under for visual nesting.
  - plan-resumed event row — opens with a ` ↻ RESUMED PLAN ` cyan
    pill + bold counter; summary + step list flow underneath.
  - plan-replay event row — slate ` ⏪ REPLAY ` pill mirroring the
    resumed shape, so live and archived plans use the same idiom.
  - error / warning event rows — now use the same pill idiom
    (` ✦ ERROR ` rose, ` ▲ WARN ` amber) instead of one colored
    glyph + colored body.
  - PlanCheckpointConfirm + PlanReviseConfirm modals — wrapped in
    the shared ModalCard frame (green ✓ checkpoint, amber ✏
    revision). All four confirm-style modals now share the same
    top/bottom rule + bg-pill title visual language: choice
    (magenta), plan (cyan), shell (red), edit (yellow / green NEW),
    checkpoint (green), revision (amber). User learns the modal
    type by accent before reading the title.
2026-04-25 21:45:38 -07:00
esengine 37e741afa1 feat(ui): plan state pills, branch block redesign, semantic info icons
- PlanStateBlock — labels are now solid-bg pills (` subgoals 3 `,
    ` hypotheses 2 `, ` uncertainties 1 `, ` rejected 4 `) with
    truecolor hex backgrounds matching the role palette (cyan /
    green / amber / slate). Items render to the right of the pill.
  - BranchBlock — replaced the dim blue one-liner with a stacked
    layout: blue ` ⎇ BRANCH ×N ` pill on the header row, then
    one row per sample beneath with the chosen sample bolded and
    arrow-marked.
  - StatsLine (assistant footer) — was a flat dim row; now uses
    threshold-colored cache % (green/amber/rose), cyan/violet for
    in/out token counts, green for cost, with mid-dot separators.
  - Info rows — auto-detect tone from the leading glyph: ▲/⚠ →
    warn (amber), ✓ → ok (green), ✗/✖ → err (rose), ↻ → reload
    (cyan), default ▸ → info (slate). The glyph is colored-bold,
    body stays dim. Existing info messages with embedded prefixes
    pick up their semantic without callers changing anything.
2026-04-25 21:40:56 -07:00
esengine 526e3edc97 feat(ui): plan-step status pills, streaming phase pills, undo + subagent badges
- PlanStepList — replaced the colored ✓/▶/—/space glyph column
    with solid-bg status pills: ` ✓ DONE ` (green) / ` ▶ RUN  `
    (cyan) / ` — SKIP ` (slate) / ` ☐ PEND ` (slate dim). Header
    row now shows percent done. Focus row gets bold + accent
    arrow + bold title. Reads at a glance from across the screen.
  - StreamingAssistant — phase header is now a solid-bg pill
    (` WAITING ` amber, ` THINKING ` violet, ` DISPATCH ` fuchsia,
    ` WRITING ` green) instead of a long colored sentence. Pre-
    first-byte / reasoning-only / tool-call-only hints get
    paddingLeft so they sit visually under the pill. Same info
    density, far better visual hierarchy.
  - UndoBanner — replaced the magenta-text version with a violet
    bg-pill header (` ✓ AUTO-APPLIED N/M `) + a cyan key-pill on
    the `u` shortcut. Countdown turns red bold in the last second.
  - SubagentRow — violet bg-pill for the ⌬ subagent label,
    paddingLeft={3} so it visually nests under the parent
    OngoingToolRow when both are visible.
2026-04-25 21:33:14 -07:00
esengine 60024a5223 feat(ui): markdown headings get bg pills, modals share a card frame
Five surfaces touched, all visible during normal coding:

  - Markdown H1 → solid cyan-bg pill (` # title `).
  - Markdown H2 → solid violet-bg pill (` ## title `).
  - Markdown H3 → bold fuchsia ### with bold body, no bg (avoids
    visual overpower at the third nest level).
  - Modals — ChoiceConfirm, PlanConfirm, ShellConfirm, EditConfirm
    all wrap in a new <ModalCard> primitive: top accent rule, bg-pill
    title row with optional icon + dim subtitle, content area, bottom
    accent rule. Each modal keeps its own accent color so the user
    learns by sight: magenta=choice, cyan=plan, red=shell, yellow=edit.
  - Info rows in scrollback get a slate `▸ ` prefix so they read as
    structured "system note" lines instead of dim continuation text.

ModalCard is plain Text for the rules + a bg-pill title — no Ink
borderStyle, so it stays compatible with the live region's eraseLines
constraint. EditConfirm's diff slicing budget is unchanged
(MODAL_OVERHEAD_ROWS still accounts for ~3 rows of frame).
2026-04-25 21:27:33 -07:00
esengine e463fe7518 feat(ui): animated prompt bar, user-msg band, reasoning pill, pickers polished
Five more visual upgrades across the most-touched surfaces:

  - PromptInput left bar — each row's ▎ picks a color from the
    brand gradient with a tick offset, so the bar visually flows
    vertically in sync with the StatsPanel's wordmark + rules.
    When the prompt is disabled (busy turn), the gradient is
    suppressed and the bar reverts to dim gray so the screen
    calms down for the active spinner above it.
  - User message — wrapped in a cyan left-only border Box matching
    the assistant treatment, so both sides of the conversation
    have the Discord-style avatar bar. Continuation lines align
    under the band.
  - ReasoningBlock — was a flat dim italic line, now opens with a
    solid violet pill (` ⋯ thinking `) and the body in violet
    italic. Reads as its own surface instead of blending into the
    rest of the message.
  - SlashSuggestions selected row — solid cyan-bg highlight (the
    whole row, like an editor's autocomplete focus row) instead
    of just colored text.
  - AtMentionSuggestions selected row — same solid cyan-bg
    treatment, basename + dir on one line for a tighter VS Code
    Quick Open feel.
2026-04-25 21:21:13 -07:00
esengine 53ab16bab4 feat(ui): wordmark + gradient rules now flow — colors travel each tick
Tick is ~120 ms. Wordmark shifts the gradient one step every 4 ticks
idle / 2 ticks busy, so the teal→cyan→blue→purple→fuchsia sweep
visibly travels across REASONIX like a neon sign. Top/bottom
GradientRule bars share the flow logic (slower — every 6 ticks) so
the whole panel feels alive without being twitchy. Brand mark ◈ keeps
its existing bold-pulse so 'app is thinking' stays distinct from
'colors are flowing.'
2026-04-25 21:05:49 -07:00
esengine 4b2f2bf183 feat(ui): full-height role bands, code block cards, modeline divider
Big visual upgrades on the surfaces with the most pixels:

  - Assistant message — Box with left-only border in role color
    (COLOR.assistant green) running the FULL height of the message,
    Discord-style avatar bar. Reasoning, branch, plan-state, body
    Markdown, stats footer, repair note all sit inside the band.
  - Tool result for edit_file — same left-band treatment in
    COLOR.tool yellow so the diff reads as a continuation of the
    pill above.
  - Markdown code blocks — round-bordered card in cyan, with the
    language label as a solid-bg pill in the top-left and amber
    body text. Fenced code now feels like a code block, not a
    bare yellow-on-default text dump.
  - OngoingToolRow — solid amber pill on the tool name, gradient
    progress line, paddingX so the row sits in its own column zone.
  - StatusRow — violet accent + paddingX + middle-dot separator
    instead of a grey one-liner.
  - ModeStatusBar — wrapped in a top dotted rule so the modeline
    reads as its own zone, separate from the prompt above. Helix /
    vim modeline feel.

Border usage notes: the assistant + tool left-only borders live
inside `<Static>` (scrollback) so Ink's eraseLines miscount that
banned bordered Boxes from the LIVE region doesn't apply. The live
region (StatsPanel, OngoingToolRow, ModeStatusBar, PromptInput)
still uses Text-only rules and pills, so the Windows ghost-row
class of regression stays out.
2026-04-25 20:57:02 -07:00
esengine 9d775acb94 feat(ui): theme module + gradient bars, gradient turn separator, polished metrics
Centralised palette/glyphs in theme.ts so the TUI reads as one
designed surface instead of fifteen components inventing their own
color choices. Reuses the brand teal→cyan→blue→purple→fuchsia
gradient that the wordmark already establishes.

  - StatsPanel: top + bottom gradient rules frame the header band;
    progress bar redesigned with ▰/▱ glyphs and threshold colors
    (green/amber/rose) using truecolor hex; metric cells now lead
    with a dim icon (▣ ctx, ⌬ cache, ◴ cost, ◐ balance) and the
    inline layout always shows the bar.
  - TurnSeparator: gradient rule on both sides of the brand mark
    instead of a flat dim minus row, so turn boundaries read as
    designed accents.
  - WelcomeBanner: gradient top/bottom rules + brand-color left bar
    + accent-color hint tokens. Card now feels like a card.
  - theme.ts: GRADIENT array, semantic COLOR map, GLYPH set,
    `gradientCells(width, glyph)` helper that other components
    consume to render colored rules without duplicating the
    interpolation logic.
2026-04-25 20:50:53 -07:00
esengine 70bffed518 feat(ui): visual upgrade — pills, card-style welcome, status bar weight
Three high-frequency surfaces redesigned with solid-bg pills + card
framing so the TUI reads as a designed product instead of a wall of
glyphs:

  - WelcomeBanner — left-bar card frame; sectioned 'welcome / quick
    start / tip' rows; first thing on screen now has visual weight
    instead of looking like a one-liner list.
  - ModeStatusBar — solid-bg pills (AUTO / REVIEW / PLAN MODE) like
    a vim/helix modeline so the bottom bar reads at a glance.
  - Tool result rows — bg pill on the tool name (yellow ✓ / red ✗)
    so a session full of dispatches has visible status hierarchy.
  - Assistant header — model name now a solid-green pill next to the
    ◆ glyph, matching the visual language of the other pills.

No new abstractions, no border boxes (still avoiding Ink's Windows
eraseLines miscount). Just pills + bars + paddingX consistently
applied to the surfaces the user sees most.
2026-04-25 20:41:52 -07:00
esengine 77285a251c fix(ui): WelcomeBanner gated on real conversation, not historical.length
historical always has at least one info row at startup (session state
banner, edit-mode hint, restored plan, etc.), so historical.length
=== 0 never holds and the welcome card never showed. Switch the gate
to 'no user/assistant message yet' so the card greets the empty
conversation as intended.
2026-04-25 20:36:19 -07:00
esengine 7f7b48021e fix(lint): biome wants the long Text body wrapped 2026-04-25 20:33:04 -07:00
esengine 732593e4ed chore(release): 0.7.4 2026-04-25 20:29:46 -07:00
esengine d4662df023 fix(input): hoist KeystrokeProvider above App; restore Ctrl+C/J + Shift+Enter
The 49d4648 stdin-reader refactor moved the KeystrokeProvider INSIDE
App's render but kept App-body `useKeystroke` calls — `useContext`
runs at hook-call time, so the provider wasn't mounted yet and the
returned bus was always null. Every global hotkey (Ctrl+C exit, Esc
abort, Shift+Tab edit-mode cycle, @-mention picker nav, slash
suggestion nav) silently never subscribed; PromptInput worked because
it lives in the provider subtree.

Fixes:
  - chat.tsx wraps <App> in <KeystrokeProvider> from outside; remove
    the inner one in App.tsx.
  - stdin-reader splits \r vs \n: \r → Enter (return:true),
    \n → Ctrl+J ({ctrl:true, input:"j"}). Was conflating both as
    Enter, so Ctrl+J fired submit instead of newline.
  - stdin-reader recognises modifyOtherKeys + kitty Enter sequences
    (27;2;13~ / 13;2u and shift/ctrl variants) so terminals that
    enable those protocols can distinguish Shift+Enter / Ctrl+Enter.
    On Windows + ConPTY the bytes get stripped before reaching us, so
    Shift+Enter still falls back to Enter there — Ctrl+J remains the
    universal newline.
  - App.tsx writes \x1b[>4;2m at startup (paired disable on unmount)
    to opt into modifyOtherKeys for terminals that honor it.
  - code.tsx drops the SIGINT/SIGTERM `once` handler that ran
    jobs.shutdown without exiting (it overrode Node's default
    "exit on Ctrl+C" with a silent no-op). Job cleanup moves to the
    `exit` event so any termination path drains the registry.
  - App.tsx: SIGINT and \x03 byte both call process.exit(0). Using
    Ink's exit() left the singleton stdin-reader's data listener
    attached and the event loop alive, so the terminal would hang.

Hint text updated to lead with [Ctrl+J] since Shift+Enter is
unreliable on the most common Windows host. Two diagnostic probe
scripts added under scripts/ for future input regressions.

Visual structure tightened along the way: a left-bar (▎) anchor
running down PromptInput, a thin rule under the StatsPanel, the
existing TurnSeparator now actually rendered between user turns,
StatsPanel pills/wordmark restored from the in-flight working tree.
2026-04-25 20:29:38 -07:00
esengine 06f4716e17 feat(ui): welcome banner on the empty session
When the user opens reasonix and nothing has happened yet, the screen
showed StatsPanel + the bare prompt — no signpost for what to type.
Add a small Welcome card with three or four hand-picked hints
(/help, /skill, @path / !cmd in code mode, /exit). Disappears the
moment the first event lands so it never gets in the way during a
real session.

Tight on purpose. Full reference is /help; this is just the friction-
removing first impression.
2026-04-25 18:38:17 -07:00
esengine 49d4648b07 refactor(input): replace Ink useInput with our own stdin reader
The 0.7.x bug parade (paste markers leaking, arrows not crossing
newlines, Shift+Tab broken, CJK ghost rows) traced back to two upstream
limitations we couldn't patch around forever:

  1. Ink's `parse-keypress` uses a 100 ms intra-CSI timeout that is too
     short for Windows ConPTY. Sequences like `\x1b[A` arrive split
     across reads with > 100 ms gaps, so the lone `\x1b` fires as
     `key.escape:true` and `[A` lands in `input` as plain text.

  2. Ink/Yoga measures cell width with `string-width`, but on CJK
     terminals some glyphs render at a different cell count than that
     library reports. The terminal wraps to a 2nd visual row that
     Ink's `eraseLines` doesn't account for, so each render leaks a
     row into permanent scrollback.

Patching consumers one at a time was a Whac-A-Mole. This change
replaces the entire input layer:

  - **`stdin-reader.ts`** — owns `process.stdin`, parses bytes with
    our own state machine. ESC ambiguity timer is 250 ms (vs. Ink's
    100). ESC-stripped CSI tails (`[A`, `[5~`, `[Z`, `[200~`) are
    recognised at idle-state lookahead. SS3 (`\x1bOA`) supported. Drops
    unknown CSI silently rather than inserting bytes as text.

  - **`keystroke-context.tsx`** — React Context that owns the singleton
    StdinReader and fans events out to subscribers via `useKeystroke`.
    Replaces every `useInput` import in our tree.

  - **`prompt-viewport.ts`** — pure helpers that slice each logical
    prompt line into exactly one visual row. The cursor's window
    slides so it stays visible; `‹` / `›` markers indicate clipped
    content. CJK cell widths handled explicitly so our math matches
    the terminal grid (no more `string-width` disagreement with the
    real renderer).

  - **PromptInput v2** — rewritten on top of these. No `useTick` (no
    cursor blink — the 8 Hz repaint was amplifying the eraseLines
    leak). One Box row per logical line, fixed visual height, viewport
    clipping for content longer than the terminal width.

  - **App / Select / EditConfirm / PlanRefineInput** migrated to
    `useKeystroke`. Wizard / DiffApp / ReplayApp keep Ink's `useInput`
    — separate render calls, no provider in their tree, no conflict.
    SessionPicker (which uses our migrated SingleSelect) gets its own
    KeystrokeProvider wrapper in chat.tsx.

  - As long as no `useInput` is called inside the Ink tree, Ink itself
    never attaches a stdin listener, so our reader is the sole consumer
    of stdin. No race with parse-keypress.

41 new tests covering every CSI tail, paste accumulator across chunks,
ConPTY ESC-stripping, viewport clipping for CJK / paste sentinels.
1283 → 1324 tests, lint + typecheck clean.
2026-04-25 10:50:08 -07:00
esengine 634f8e6028 refactor(input): centralise CSI recovery in key-normalize boundary
Audit context. We've shipped three patches in two days for the same
class of bug:
  1. paste markers `[201~` leaking into the prompt buffer
  2. arrow keys not advancing the cursor across newlines on Windows
  3. (foreseeable) Shift+Tab / PgUp / PgDn / Delete next, since they
     all share the root cause.

Root cause is upstream: Ink's parse-keypress uses a 100ms timeout
to assemble CSI sequences from stdin. On Windows PowerShell + ConPTY
the bytes of `\x1b [ A` arrive split across reads with > 100ms
gaps. The standalone `\x1b` fires as `key.escape:true`, the trailing
`[A` fires as a regular character event with `input:"[A", upArrow:
undefined`. Every useInput consumer that reads structured key flags
silently misses the keystroke and the bare bytes get inserted into
the buffer as text.

Each individual patch was correct but localised — multiline-keys had
its own arrow recovery, PromptInput had its own paste-marker recovery,
App.tsx / Select / EditConfirm didn't recover anything at all and
would have been the next bugs found.

Fix is a single boundary. `src/cli/ui/key-normalize.ts` exposes:

  - `recoverCsiTail(input, existingFlags?)` — the canonical mapping
    from bare-or-prefixed CSI tails to structured Ink key flags.
    Covers `[A`/`[B`/`[C`/`[D` (arrows), `[5~`/`[6~` (PgUp/PgDn),
    `[3~` (Delete), `[Z` (Shift+Tab). Bracketed-paste markers
    intentionally excluded — they have collect-between-markers
    semantics and live in PromptInput's accumulator.

  - `stripCsiFragments(input)` — defensive scrub for the edge case
    where a fragment slips past structured-key recovery (e.g. arrived
    embedded inside a paste burst). Replaces the inline replaceAll
    chains we'd grown in multiline-keys.

Wired into every useInput call site that reads structured key flags:
multiline-keys (PromptInput's reducer), App's global hotkey handler
(Esc / Shift+Tab), Select's SingleSelect + MultiSelect (modal
navigation), EditConfirm's scroll/decision handler. DiffApp /
ReplayApp left for follow-up — separate subcommands, lower blast
radius.

+14 tests covering every supported tail, the pass-through path, the
already-structured-event short-circuit, and the literal `[A](url)`
non-rewrite. 1267 → 1283 tests.
2026-04-25 09:28:44 -07:00
esengine 9d09a14f91 fix(prompt): ESC-stripped arrow keys (Windows ConPTY) move the cursor
User reported pressing right-arrow at end of line 1 would not advance
the cursor to line 2. Same root cause as the recent [201~ paste-marker
fix: Windows PowerShell + ConPTY consumes the leading \x1b of the
arrow's CSI sequence and routes the remaining '[C' through useInput
as plain text. Our rewriteRawArrowEscape only matched the full
'\x1b[C' form, so the keystroke landed on the printable-char branch
and inserted literal '[C' into the buffer instead of moving the
cursor.

Add fallbacks for the bare '[A'/'[B'/'[C'/'[D' input strings. +1 test
covering the cross-newline rightArrow case directly.
2026-04-25 09:11:00 -07:00
esengine 1c023126d9 fix(prompt): handle ESC-less bracketed-paste markers
Windows PowerShell + ConPTY + Ink's parse-keypress consumes the
leading \x1b of \x1b[200~ / \x1b[201~ and routes the rest into
useInput as plain text. Our markers were the full sequence, so
indexOf missed them and the literal '[201~' ended up inserted into
the user's prompt buffer.

PromptInput now searches for both the full marker and the bare
'[200~'/'[201~' fallback. multiline-keys.ts strips both forms
defensively too. +1 test.
2026-04-25 09:06:21 -07:00
esengine 87d87c8f47 feat(ui): drop bordered Boxes throughout the live region
User reported repeating ghost top-borders accumulating in scrollback
on Windows + CJK input — every render leaked one row, so 17+ ghost
`╭──...─╮` lines stacked at the top within seconds. Root cause: Ink's
eraseLines counts logical rows, not post-wrap visual rows. Bordered
Boxes were both the most common wrap source AND the most visually
obvious thing to duplicate.

Fix: remove `borderStyle="round"` from every component in the live
region — StatsPanel, PromptInput, all *Confirm modals, UndoBanner,
EventLog plan/plan-resumed/plan-replay rows. Visual hierarchy now
comes from bold colored headers + indentation + marginY breathing.

Also pillify the active mode tag in ModeStatusBar — `▸ AUTO` becomes a
solid colored background block ` AUTO ` so the current mode reads at
a glance and the focus animation (briefly inserting a ◆) is more
distinct than `inverse` toggling.

No content lost; same affordances, less paint surface for Ink to get
wrong on fragile terminals.
2026-04-25 09:01:59 -07:00
esengine 50c757d203 fix(prompt): pin PromptInput Box to width=cols, fold Esc hint inside
User reported ghost top borders stacking up in scrollback after typing
two lines of CJK content, plus apparent cursor-stuck-on-line-1. Same
class of Ink eraseLines miscount that StatsPanel solved with explicit
width={cols} — long Chinese input (2 cells per char) overflows the
auto-flexed Box, every ticker tick leaves a ~1 row residual, and after
~3s the user sees 20+ ghost border tops.

Two changes:
- Pin the bordered Box to `width={cols}` so Ink's measurement matches
  reality (same fix StatsPanel applies).
- Fold the disabled-state [Esc] hint back inside the bordered Box. The
  `<>`-wrapped sibling Box from 0.7.2 was a structural variable with no
  layout benefit. Continuation-indented row inside the box matches the
  visual hierarchy without changing the live-region shape.

The cursor-stuck symptom was rendering corruption — once the live
region stops accumulating ghost rows, useInput delivery + setCursor
land where they should.
2026-04-25 08:34:19 -07:00
esengine 50670ee41b chore(release): 0.7.2
UX polish + two small fixes since 0.7.1:

- pickers / narrow-term reflow / multi-line indent (d6bb405)
- Wizard + SessionPicker keybinding hint unification (98f19d1)
- tool-summary suffix-match for MCP-bridged tools + write_file branch (1de2349)
- replay: align multi-line user msg under the prefix in RecordView (70e0ad1)

Tests 1264 → 1267, lint + typecheck + build clean.
2026-04-25 08:00:30 -07:00
esengine 70e0ad1aba fix(replay): align multi-line user msg under the prefix in RecordView
Same fix as EventLog ate earlier. RecordView is the read-only viewer
shared by reasonix replay and reasonix diff — multi-line transcripts
were wrapping under col 0 instead of under the body text. Continuation
indent of 6 spaces matches the 'you › ' prefix width.
2026-04-25 06:44:11 -07:00
esengine 1de2349350 fix(ui): tool-summary suffix-match bridges MCP-prefixed names
LiveRows.tsx already used `name === s || name.endsWith("_" + s)` so MCP
tools like `filesystem_read_file` picked up the same per-tool argument
summary as the bare local `read_file`. tool-summary.ts used exact-name
match only, so bridged tools fell through to the generic "first line +
size hint" path in the compact scrollback row. Switch to the same
suffix predicate; add a write_file branch while there. +3 tests
covering the bridged path + a non-underscore-prefix non-match.
2026-04-25 06:21:57 -07:00
esengine 98f19d1d47 chore(ui): unify keybinding hints in Wizard + SessionPicker
Bracket-style `[↑↓] navigate · [Enter] X · [Esc] Y` matches the Confirm
modals; Wizard and SessionPicker were the last surfaces using the older
free-form `↑/↓ move · enter X · esc Y` style. Doc-comment examples in
Select.tsx updated to match.
2026-04-25 06:18:19 -07:00
esengine d6bb4054dc feat(ui): polish pickers, narrow-term reflow, multi-line indent
- ShellConfirm border yellow→red (highest-risk gate distinct from review)
- EditConfirm border cyan→yellow (decouple from PlanConfirm cyan)
- PromptInput: extract [Esc]-to-stop into separate dim row; narrow mode
  (≤90 cols) condenses prefix `you ›`→`›` with proportional indent
- EventLog: user/warning/error multi-line text now aligns under glyph
  via indentContinuationLines helper
- Slash/At/SlashArg suggestion overlays: marginTop separates from scrollback
2026-04-25 06:15:33 -07:00
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
esengine ee577995d0 fix(errors): actionable messages for 401/402/422 + V4 context-overflow hint (0.5.23)
Before: DeepSeek auth/balance/parameter errors surfaced as raw
"DeepSeek 401: {\"error\":{\"message\":\"...\"}}" JSON blobs. Users
saw a wall of JSON and had to know to parse it themselves to learn
their API key was bad or they were out of credit.

formatLoopError now recognizes the per-code cases:

  401 → "Authentication failed (DeepSeek 401): <inner msg>. Your API
         key is rejected. Fix with `reasonix setup` or
         `export DEEPSEEK_API_KEY=sk-...`. Get one at
         https://platform.deepseek.com/api_keys."
  402 → "Out of balance (DeepSeek 402): <inner msg>. Top up at
         https://platform.deepseek.com/top_up — the panel header
         shows your balance once it's non-zero."
  422 → "Invalid parameter (DeepSeek 422): <inner msg>"
  400 → "Bad request (DeepSeek 400): <inner msg>"

Each unwraps `{"error":{"message":"..."}}` so the reader sees prose,
not JSON. Fallback keeps the raw body if parsing fails.

Context-overflow text also refreshed: mentions V4's 1M window AND
the legacy 131k for the chat/reasoner aliases, and drops the stale
"v0.3.0-alpha.6+" reference that's long-since rolled into the 0.5
release line. The "8k tokens per tool result" cap is current
(src/mcp/registry.ts DEFAULT_MAX_RESULT_TOKENS).

429/500/502/503/504/408 retries unchanged — fully absorbed by
retry.ts before they reach formatLoopError.

1013 tests (+6). Lint / typecheck / build clean.
2026-04-23 21:22:14 -07:00
esengine e3d6fe3a86 fix(client): bump default timeout past DeepSeek's 10-min queue cap (0.5.22)
DeepSeek's 2026-04 docs spell out that when concurrency is saturated
but the request is accepted, the connection stays open for up to 10
minutes while the request waits in the queue — non-streaming bodies
fill with empty lines, streaming bodies fill with `:` SSE keep-alive
comments. Both are invisible to our parsers (JSON.parse tolerates
leading whitespace; eventsource-parser drops `:`-prefixed comment
lines per the SSE spec), so no separate handling is needed.

What WAS broken: `timeoutMs` defaulted to 120s. A request that sat
in the queue past 2 min triggered our AbortController, which burned
the queue slot and bounced through retryWithBackoff — potentially
looping through the whole queue repeatedly and never landing.

Fix: bump default to 660_000ms (11 min). Server's own 10-min cap
closes the connection first on genuine queue overflow (clean EOF
→ our retry is normal), while still catching truly hung sockets.

Callers that want a tighter budget (short-lived CI checks, smoke
tests) keep their explicit `timeoutMs` override. No API shape change.

1007 tests. Lint / typecheck / build clean.
2026-04-23 21:17:04 -07:00
esengine bfc4cd38ee docs(readme): update for V4 models, /effort, /resource, /prompt, 1M context, !/@ shortcuts
- Tagline + /preset max + /think: V3/R1 → V4 (flash + pro)
- /model row lists v4-flash/pro as primary, chat/reasoner as compat aliases
- Add /effort, /resource, /prompt, /models, /context, /stats, /keys rows
- Context window 131k → 1M; test count 648 → 1007
- New "Prompt prefixes — !cmd and @path" section documenting the bang-
  mode shell shortcut (0.5.8, now session-durable) and @-mentions
  picker (0.5.5-0.5.7) — both are daily-use features that had no home
  in the README until now.
- Panel header example bumped from 0.4.22 to the current 0.5.21 with
  the reasoning-effort `· max` badge visible.

No code changes.
2026-04-23 21:13:00 -07:00
esengine 0ccc419d0d feat(v4): integrate DeepSeek V4 — models, pricing, thinking toggle, effort control (0.5.21)
Models & pricing (src/telemetry.ts):
- Add deepseek-v4-flash (¥0.2 / ¥1 / ¥2 per 1M hit/miss/out) and
  deepseek-v4-pro (¥1 / ¥12 / ¥24), converted at 7.2 CNY/USD.
- deepseek-chat and deepseek-reasoner now priced identically to
  v4-flash — per the 2026-04 V4 launch they're compat aliases for
  flash non-thinking / thinking modes respectively.
- Context bumped to 1M tokens across all four entries.

Defaults shifted to v4-pro (agent-class flagship):
- `reasonix code` mode, subagent DEFAULT_SUBAGENT_MODEL, loop
  constructor fallback, `max` preset all point at deepseek-v4-pro.
- `fast` / `smart` presets stay on chat/reasoner — those aliases are
  currently our only way to pin thinking ON or OFF via model name,
  so the preset system still has a cheap/fast option.
- Subagent tool enum widened to [v4-flash, v4-pro, chat, reasoner];
  description flipped to treat flash as the "cheaper opt-out" path.

Thinking-mode toggle + reasoning_effort (new API params):
- src/types.ts ChatRequestOptions gains `thinking?: "enabled" | "disabled"`
  serialized as extra_body.thinking.type, and `reasoningEffort?:
  "high" | "max"` as the top-level reasoning_effort field.
- src/loop.ts exposes thinkingModeForModel(model) and pins the
  correct value per model name (chat=disabled, reasoner=enabled,
  v4-*=enabled, unknown=undefined/server-default). Every turn now
  sets thinking + reasoningEffort explicitly — no more relying on
  server defaults to match what reasoning_content round-trip expects.
- reasoning_effort defaults to "max" because Reasonix is exactly the
  agent-class use case DeepSeek's docs call out.

UI: /effort slash + StatsPanel badge:
- `/effort [high|max]` flips the loop's reasoningEffort mid-session.
- `/effort` no-arg reports the current value.
- StatsPanel header shows a green `· max` or yellow `· high` tag next
  to harvest/branch/PLAN so users always see which tier the next turn
  will use. `/status` flags line also reports it.

Harvest cost tuning (src/harvest.ts):
- Default model reverted to deepseek-chat — harvest is a micro-
  extraction (4 small arrays of strings), not agent work.
- chat() call explicitly pins thinking=disabled + effort=high so a
  future default-model swap can't accidentally promote this micro-
  call into a multi-thousand-reasoning-token request.

1007 tests (+9 new: thinking toggle, /effort slash, v4 pricing).
Lint / typecheck / build clean.
2026-04-23 21:10:13 -07:00
117 changed files with 16964 additions and 3501 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.
+51 -12
View File
@@ -3,7 +3,7 @@
</p>
<p align="center">
<em>Cache-first agent loop for DeepSeek V3 &amp; R1 — Ink TUI, MCP first-class, no LangChain.</em>
<em>Cache-first agent loop for DeepSeek V4 (flash + pro) — Ink TUI, MCP first-class, no LangChain.</em>
</p>
# Reasonix
@@ -133,6 +133,34 @@ shell call will execute. Use for high-stakes changes you want to
audit before the model touches disk. `/plan off` or picker
Approve/Cancel exits.
### Prompt prefixes — `!cmd` and `@path`
Two inline shortcuts that don't need a slash:
**`!<cmd>` — run a shell command in the sandbox and feed it to the
model.** Typed at the prompt, like bash. Output lands in the visible
log AND in the session so the model's next turn reasons about it:
```
reasonix code › !git status --short
▸ M src/users.ts
▸ M src/users.test.ts
reasonix code › 把这两个文件的改动说明一下
assistant
▸ tool<read_file> → src/users.ts, src/users.test.ts
▸ …
```
No allowlist gate — user-typed shell = explicit consent. 60s timeout,
32k char cap, survives session resume since 0.5.14.
**`@path/to/file` — inline a file under "Referenced files."** Start
typing `@` and a picker appears (↑/↓ navigate, Tab/Enter to insert).
Good for "what does @src/users.ts do?" without making the model
`read_file` it first. Sandboxed: relative paths only, no `..` escape,
64KB per-file cap. Recent files rank higher.
### `/commit` — stage + commit in one step
```
@@ -145,12 +173,14 @@ reasonix code › /commit "fix: findByEmail case-insensitive"
- `/tool 1` — dump the last tool call's full output (when the 400-char
inline clip isn't enough).
- `/think` — see the model's full R1 reasoning for the last turn
(reasoner preset only).
- `/think` — see the model's full reasoning for the last turn
(thinking-mode models: v4-flash / v4-pro / reasoner alias).
- `/undo` — roll back the last applied edit batch.
- `/new` — start fresh in the same directory without losing the
session file.
- `npx reasonix code --preset max` — R1 + 3-way self-consistency
- `/effort high` — step down from the default `max` agent-class
reasoning_effort for cheaper/faster turns on simple tasks.
- `npx reasonix code --preset max` — v4-pro + 3-way self-consistency
branching for gnarly refactors.
- `npx reasonix code src/` — narrower sandbox (only `src/` is
writable).
@@ -182,7 +212,9 @@ in the file. No prompts, no completions, no tool arguments.
### Staying current
The panel header shows the running version next to `Reasonix` (e.g.
`Reasonix v0.4.22 · model …`). A quiet 24-hour background check against
`Reasonix v0.5.21 · deepseek-v4-pro · harvest · max …`, the trailing
`max` is the reasoning-effort badge — `/effort high` to step down).
A quiet 24-hour background check against
the npm registry surfaces a yellow `update: X.Y.Z` on the right side
of the same row when a newer version has been published. No blocking,
no nagging — the check runs once per day max and is silent on failure
@@ -403,18 +435,25 @@ rendering, retries.
| command | what it does |
|---|---|
| `/preset <fast\|smart\|max>` | one-tap bundle (model + harvest + branch) |
| `/model <id>` | switch DeepSeek model (`deepseek-chat`, `deepseek-reasoner`) |
| `/model <id>` | switch DeepSeek model (`deepseek-v4-flash`, `deepseek-v4-pro`, plus `deepseek-chat` / `deepseek-reasoner` compat aliases) |
| `/models` | list live models from DeepSeek `/models` endpoint |
| `/harvest [on\|off]` | toggle R1 plan-state extraction |
| `/branch <N\|off>` | run N parallel samples per turn, pick best (N ≥ 2) |
| `/think` | dump the last turn's full R1 reasoning |
| `/effort <high\|max>` | reasoning_effort cap — `max` is the agent default, `high` is cheaper/faster |
| `/think` | dump the last turn's full thinking-mode reasoning |
**Context & tools**
| command | what it does |
|---|---|
| `/mcp` | list attached MCP servers and their tools |
| `/mcp` | list attached MCP servers and their tools / resources / prompts |
| `/resource [uri]` | browse + read MCP resources (no arg → list URIs; `<uri>` → fetch) |
| `/prompt [name]` | browse + fetch MCP prompts |
| `/tool [N]` | dump the Nth tool call's full output (1 = latest) |
| `/compact [cap]` | shrink oversized tool results in the log |
| `/compact [tokens]` | shrink oversized tool results in the log (default 4000 tokens/result) |
| `/context` | break down where context tokens are going (system / tools / log) |
| `/stats` | cross-session cost dashboard (today / week / month / all-time) |
| `/keys` | keyboard shortcuts + prompt prefixes (`!` / `@` / `/`) cheatsheet |
**Memory & skills**
@@ -468,8 +507,8 @@ rendering, retries.
- Malformed `assistant.tool_calls` / `tool` pairing is validated on
every outgoing API call so a corrupted session can't keep 400ing.
- Context gauge turns yellow at 50%, red at 80% with a `/compact`
nudge. Approaching the 131k window triggers an automatic
compaction attempt before falling back to a forced summary.
nudge. Approaching the 1M-token window (V4 flash + pro) triggers an
automatic compaction attempt before falling back to a forced summary.
- The `reasonix code` sandbox refuses any path that resolves outside
the launch directory, including symlink escape and `..` traversal.
@@ -728,7 +767,7 @@ cd reasonix
npm install
npm run dev code # run CLI from source via tsx
npm run build # tsup to dist/
npm test # vitest (648 tests)
npm test # vitest (1007 tests)
npm run lint # biome
npm run typecheck # tsc --noEmit
```
+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.19",
"description": "DeepSeek-native agent framework: cache-first loop, R1 thought harvesting, tool-call repair.",
"version": "0.7.11",
"description": "DeepSeek-native coding agent: cache-first loop, flash-first cost control, tool-call repair.",
"type": "module",
"bin": {
"reasonix": "dist/cli/index.js"
+28
View File
@@ -0,0 +1,28 @@
// Minimal Ctrl+C probe. Usage: node scripts/ctrlc-probe.mjs
// Reproduces the exact stdin setup Reasonix uses, then logs every byte
// it sees and exits on \x03. Tells us whether the OS even delivers
// Ctrl+C to a Node child on this terminal.
process.stdin.setRawMode(true);
process.stdin.setEncoding("utf8");
process.stdin.resume();
console.log("ctrl+c probe armed. press keys; ctrl+c should exit.");
console.log("if ctrl+c does NOT exit, the byte never reaches Node on this terminal.\n");
process.stdin.on("data", (chunk) => {
const s = String(chunk);
for (const ch of s) {
const code = ch.charCodeAt(0);
process.stdout.write(`got byte: 0x${code.toString(16).padStart(2, "0")} (${JSON.stringify(ch)})\r\n`);
if (ch === "\x03") {
process.stdout.write("→ \\x03 detected, exiting.\r\n");
process.exit(0);
}
}
});
process.on("SIGINT", () => {
process.stdout.write("→ SIGINT received, exiting.\r\n");
process.exit(0);
});
+30
View File
@@ -0,0 +1,30 @@
// Shift+Enter probe. Usage: node scripts/shift-enter-probe.mjs
// Enables modifyOtherKeys + kitty keyboard protocol, then prints the
// raw bytes for every keypress. Press Shift+Enter and see what your
// terminal actually emits — if it's just "0x0d", the host doesn't
// support either protocol and there's nothing Reasonix can do at the
// raw-stdin layer.
process.stdout.write("\u001b[>4;2m"); // modifyOtherKeys level 2 (xterm)
process.stdout.write("\u001b[>1u"); // kitty keyboard protocol level 1
process.stdin.setRawMode(true);
process.stdin.setEncoding("utf8");
process.stdin.resume();
console.log("shift+enter probe armed. press keys; ctrl+c exits.");
console.log("expected for shift+enter:");
console.log(" modifyOtherKeys → 0x1b 0x5b 0x32 0x37 0x3b 0x32 0x3b 0x31 0x33 0x7e (\\x1b[27;2;13~)");
console.log(" kitty → 0x1b 0x5b 0x31 0x33 0x3b 0x32 0x75 (\\x1b[13;2u)");
console.log(" unsupported → 0x0d (just \\r — no way to distinguish)\n");
process.stdin.on("data", (chunk) => {
const s = String(chunk);
const bytes = [...s].map((c) => `0x${c.charCodeAt(0).toString(16).padStart(2, "0")}`).join(" ");
process.stdout.write(`got: ${bytes} (${JSON.stringify(s)})\r\n`);
if (s.includes("\x03")) {
process.stdout.write("\u001b[>4m"); // disable modifyOtherKeys
process.stdout.write("\u001b[<u"); // pop kitty level
process.exit(0);
}
});
+63 -28
View File
@@ -15,11 +15,13 @@ 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";
import { SessionPicker } from "../ui/SessionPicker.js";
import { Setup } from "../ui/Setup.js";
import { KeystrokeProvider } from "../ui/keystroke-context.js";
import type { McpServerSummary } from "../ui/slash.js";
export interface ProgressInfo {
@@ -51,7 +53,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). */
@@ -101,39 +103,49 @@ function Root({
}
process.env.DEEPSEEK_API_KEY = key;
// KeystrokeProvider must wrap App from OUTSIDE — App.tsx itself
// calls `useKeystroke` in its function body for global hotkeys
// (Ctrl+C, Esc abort, Shift+Tab edit-mode cycle, @-mention picker,
// slash-suggestion navigation). If the provider lives inside App's
// render, `useContext(KeystrokeContext)` returns `null` at hook
// call time and those handlers silently never subscribe.
if (pending && appProps.session) {
return (
<SessionPicker
sessionName={appProps.session}
messageCount={pending.messageCount}
lastActive={pending.lastActive}
onChoose={(choice) => {
if (choice === "new" || choice === "delete") {
// Wipe the session file. "new" and "delete" do the same thing
// at this step — the distinction is only in the picker's
// wording. A future enhancement could archive on "new".
rewriteSession(appProps.session!, []);
}
setPending(undefined);
}}
/>
<KeystrokeProvider>
<SessionPicker
sessionName={appProps.session}
messageCount={pending.messageCount}
lastActive={pending.lastActive}
onChoose={(choice) => {
if (choice === "new" || choice === "delete") {
// Wipe the session file. "new" and "delete" do the same thing
// at this step — the distinction is only in the picker's
// wording. A future enhancement could archive on "new".
rewriteSession(appProps.session!, []);
}
setPending(undefined);
}}
/>
</KeystrokeProvider>
);
}
return (
<App
model={appProps.model}
system={appProps.system}
transcript={appProps.transcript}
harvest={appProps.harvest}
branch={appProps.branch}
session={appProps.session}
tools={tools}
mcpSpecs={mcpSpecs}
mcpServers={mcpServers}
progressSink={progressSink}
codeMode={appProps.codeMode}
/>
<KeystrokeProvider>
<App
model={appProps.model}
system={appProps.system}
transcript={appProps.transcript}
harvest={appProps.harvest}
branch={appProps.branch}
session={appProps.session}
tools={tools}
mcpSpecs={mcpSpecs}
mcpServers={mcpServers}
progressSink={progressSink}
codeMode={appProps.codeMode}
/>
</KeystrokeProvider>
);
}
@@ -255,6 +267,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
@@ -274,6 +290,25 @@ export async function chatCommand(opts: ChatOptions): Promise<void> {
rewriteSession(opts.session, []);
}
// Visible-only clear at startup so the user lands on a fresh
// canvas. We deliberately DON'T send \x1b[3J (erase scrollback)
// because some terminal emulators — notably VSCode's integrated
// terminal — interpret it as "wipe everything we have", and the
// user then can't scroll up to see anything that came before.
// Visible clear (\x1b[2J + cursor home) is portable and
// sufficient: the previous shell prompt scrolls up into
// scrollback rather than vanishing.
if (process.stdout.isTTY) {
process.stdout.write("\x1b[2J\x1b[H");
}
// No resize listener. Earlier versions wrote \x1b[2J on every
// resize event to neutralize Ink's eraseLines miscount, but on
// VSCode + similar terminals that 2J also wipes the chat history
// sitting in scrollback above the live region. Resize ghosts are
// an accepted known limitation now — `/clear` is the documented
// workaround when the live region accumulates duplicate panels.
const { waitUntilExit } = render(
<Root
initialKey={initialKey}
+29 -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,27 @@ 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. We DON'T install SIGINT/SIGTERM
// handlers here — that overrode Node's default "exit on Ctrl+C" with
// a silent no-op, which made Ctrl+C feel broken in the TUI. App.tsx
// owns the SIGINT path now (it shows the quit-armed banner and calls
// exit() on confirmation); this 'exit' hook just guarantees the job
// registry is drained on the way out, regardless of which exit path
// fired.
process.once("exit", () => {
void jobs.shutdown();
});
await chatCommand({
model: opts.model ?? "deepseek-reasoner",
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 {
+1523 -776
View File
File diff suppressed because it is too large. Load diff
+6 -10
View File
@@ -30,7 +30,7 @@ export function AtMentionSuggestions({
if (matches === null) return null;
if (matches.length === 0) {
return (
<Box paddingX={1}>
<Box paddingX={1} marginTop={1}>
<Text color="yellow">no files match "@{query}"</Text>
<Text dimColor>
{" "}
@@ -47,7 +47,7 @@ export function AtMentionSuggestions({
const hiddenAbove = windowStart;
const hiddenBelow = total - windowStart - shown.length;
return (
<Box flexDirection="column" paddingX={1}>
<Box flexDirection="column" paddingX={1} marginTop={1}>
{hiddenAbove > 0 ? <Text dimColor> ↑ {hiddenAbove} more above</Text> : null}
{shown.map((path, i) => (
<FileRow key={path} path={path} isSelected={windowStart + i === selectedIndex} />
@@ -59,7 +59,6 @@ export function AtMentionSuggestions({
}
function FileRow({ path, isSelected }: { path: string; isSelected: boolean }) {
const marker = isSelected ? "▸" : " ";
// Split the path so the basename visually pops — same dropdown
// affordance as VS Code's Quick Open.
const slash = path.lastIndexOf("/");
@@ -68,19 +67,16 @@ function FileRow({ path, isSelected }: { path: string; isSelected: boolean }) {
if (isSelected) {
return (
<Box>
<Text bold color="cyan">
{marker} {base}
<Text backgroundColor="#67e8f9" color="black" bold>
{` ▸ ${base}${dir ? ` ${dir}` : ""} `}
</Text>
<Text color="cyan">{dir ? ` ${dir}` : ""}</Text>
</Box>
);
}
return (
<Box>
<Text dimColor>
{marker} {base}
{dir ? ` ${dir}` : ""}
</Text>
<Text color="#94a3b8">{` ${base}`}</Text>
{dir ? <Text dimColor>{` ${dir}`}</Text> : null}
</Box>
);
}
+75
View File
@@ -0,0 +1,75 @@
/**
* 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 } from "ink";
import React from "react";
import type { ChoiceOption } from "../../tools/choice.js";
import { ModalCard } from "./ModalCard.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 (
<ModalCard accent="#f0abfc" icon="🔀" title="model wants you to pick" subtitle={question}>
<Box>
<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>
</ModalCard>
);
}
export const ChoiceConfirm = React.memo(ChoiceConfirmInner);
+214
View File
@@ -0,0 +1,214 @@
import { Box, Text, useStdout } from "ink";
import React, { useMemo, useState } from "react";
import { formatEditBlockDiff } from "../../code/diff-preview.js";
import type { EditBlock } from "../../code/edit-blocks.js";
import { ModalCard } from "./ModalCard.js";
import { useKeystroke } from "./keystroke-context.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);
useKeystroke((ev) => {
if (ev.paste) return;
const input = ev.input;
const key = ev;
// 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;
const subtitleParts = [`-${removed} +${added} lines`];
if (showScrollHud) {
subtitleParts.push(
`viewing ${effectiveScroll + 1}-${effectiveScroll + visibleLines.length}/${totalLines}`,
);
}
return (
<ModalCard
accent={isNew ? "#86efac" : "#fcd34d"}
icon={isNew ? "✚" : "✎"}
title={`${tag} ${block.path}`}
subtitle={subtitleParts.join(" · ")}
>
{hiddenAbove > 0 ? (
<Text
dimColor
>{` ↑ ${hiddenAbove} line${hiddenAbove === 1 ? "" : "s"} above (↑/k or PgUp)`}</Text>
) : null}
<Box flexDirection="column">
{visibleLines.map((line, i) => {
const trimmed = line.trimStart();
const color = trimmed.startsWith("+")
? "#4ade80"
: trimmed.startsWith("-")
? "#f87171"
: 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="#67e8f9" bold>
y
</Text>
{"/Enter] apply · ["}
<Text color="#67e8f9" bold>
n
</Text>
{"] reject · ["}
<Text color="#67e8f9" bold>
a
</Text>
{"] apply rest · ["}
<Text color="#67e8f9" bold>
A
</Text>
{"] flip AUTO · ["}
<Text color="#67e8f9" bold>
↑↓/Space
</Text>
{"] scroll · [Esc] abort"}
</Text>
</Box>
</ModalCard>
);
}
+521 -169
View File
@@ -3,11 +3,50 @@ 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 { COLOR, gradientCells } from "./theme.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 +57,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
@@ -63,6 +150,34 @@ function RoleGlyph({
);
}
/**
* Solid-background pill for tool names. Mirrors the StatsPanel's mode
* pills so the visual language stays consistent across the screen:
* status (auto/review/plan), tool name, model. Status drives the
* background color — yellow for ok/in-flight, red for errors — so a
* scrollback full of tool dispatches reads at a glance.
*/
function ToolPill({ label, status }: { label: string; status: "ok" | "err" }) {
const bg = status === "err" ? "red" : "yellow";
const symbol = status === "err" ? "✗" : "✓";
return (
<Text backgroundColor={bg} color="black" bold>
{` ${symbol} ${label} `}
</Text>
);
}
/**
* Pad continuation lines so wrapped multi-line text aligns under the
* glyph indent instead of jumping back to column 0. Header is `glyph
* (1 col) + " " (2 cols)`, so subsequent lines need 3 leading spaces
* to land under the body's first character.
*/
function indentContinuationLines(text: string): string {
if (!text.includes("\n")) return text;
return text.split("\n").join("\n ");
}
export const EventRow = React.memo(function EventRow({
event,
projectRoot,
@@ -72,12 +187,23 @@ export const EventRow = React.memo(function EventRow({
}) {
if (event.role === "user") {
return (
<Box marginTop={event.leadSeparator ? 1 : 0}>
<RoleGlyph glyph={ROLE_GLYPH.user} color="cyan" />
<Text>
{" "}
{event.text}
</Text>
<Box flexDirection="column">
{event.leadSeparator ? <TurnSeparator /> : null}
<Box>
<RoleGlyph glyph={ROLE_GLYPH.user} color="cyan" />
<Text>{" "}</Text>
<Box
flexDirection="column"
borderStyle="single"
borderTop={false}
borderRight={false}
borderBottom={false}
borderColor={COLOR.user}
paddingLeft={1}
>
<Text>{indentContinuationLines(event.text)}</Text>
</Box>
</Box>
</Box>
);
}
@@ -87,9 +213,25 @@ export const EventRow = React.memo(function EventRow({
<Box flexDirection="column" marginTop={1}>
<Box>
<RoleGlyph glyph={ROLE_GLYPH.assistant} color="green" />
{event.stats ? <Text dimColor>{` ${event.stats.model}`}</Text> : null}
{event.stats ? (
<>
<Text>{" "}</Text>
<Text backgroundColor={COLOR.assistant} color="black" bold>
{` ${event.stats.model.replace(/^deepseek-/, "")} `}
</Text>
</>
) : null}
</Box>
<Box flexDirection="column" paddingLeft={2} marginTop={1}>
<Box
flexDirection="column"
marginTop={1}
borderStyle="single"
borderTop={false}
borderRight={false}
borderBottom={false}
borderColor={COLOR.assistant}
paddingLeft={1}
>
{event.branch ? <BranchBlock branch={event.branch} /> : null}
{event.reasoning ? <ReasoningBlock reasoning={event.reasoning} /> : null}
{!isPlanStateEmpty(event.planState) ? (
@@ -101,72 +243,243 @@ export const EventRow = React.memo(function EventRow({
<Text dimColor>(no content)</Text>
)}
{event.stats ? <StatsLine stats={event.stats} /> : null}
{event.repair ? <Text color="magenta">{event.repair}</Text> : null}
{event.repair ? <Text color={COLOR.accent}>{event.repair}</Text> : null}
</Box>
</Box>
);
}
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 ? (
(event.toolName === "edit_file" || event.toolName?.endsWith("_edit_file")) &&
!isExplicitError;
if (isEditFile) {
return (
<Box flexDirection="column" marginTop={1}>
<Box>
<ToolPill label={event.toolName ?? "?"} status="ok" />
<Text dimColor>{" diff:"}</Text>
</Box>
<Box
flexDirection="column"
marginTop={1}
borderStyle="single"
borderTop={false}
borderRight={false}
borderBottom={false}
borderColor={COLOR.tool}
paddingLeft={1}
>
<EditFileDiff text={event.text} />
) : (
<Text color={isError ? "red" : undefined} dimColor={!isError}>
{truncate(event.text, 400)}
</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 status: "ok" | "err" = summary.isError ? "err" : "ok";
const durationLabel =
event.durationMs !== undefined && event.durationMs >= 100
? formatDuration(event.durationMs)
: "";
const indexHint = event.toolIndex !== undefined ? ` /tool ${event.toolIndex}` : "";
return (
<Box>
<ToolPill label={event.toolName ?? "?"} status={status} />
{durationLabel ? <Text dimColor>{` ${durationLabel}`}</Text> : null}
<Text dimColor>{" "}</Text>
<Text color={status === "err" ? "red" : undefined} dimColor={status === "ok"}>
{summary.summary}
</Text>
{indexHint ? <Text dimColor>{indexHint}</Text> : null}
</Box>
);
}
if (event.role === "error") {
return (
<Box marginTop={1}>
<RoleGlyph glyph={ROLE_GLYPH.error} color="red" />
<Text color="red">
{" "}
{event.text}
<Text backgroundColor="#f87171" color="black" bold>
{" ✦ ERROR "}
</Text>
<Text>{" "}</Text>
<Text color="#f87171">{indentContinuationLines(event.text)}</Text>
</Box>
);
}
if (event.role === "info") {
// Detect tone from the text so the info row carries semantic
// weight: ▲/⚠ → warn, ✓ → ok, ✗/✖ → error, ↻ → reload, otherwise
// a neutral ▸. The leading glyph (if any) is consumed and the
// body renders dim.
const m = event.text.match(/^([▸▶▲⚠✓✗✖↻ⓘ])\s*(.*)$/s);
const lead = m?.[1] ?? "▸";
const body = m?.[2] ?? event.text;
let leadColor: string = COLOR.info;
if (lead === "▲" || lead === "⚠") leadColor = COLOR.warn;
else if (lead === "✓") leadColor = COLOR.ok;
else if (lead === "✗" || lead === "✖") leadColor = COLOR.err;
else if (lead === "↻") leadColor = COLOR.primary;
return (
<Box>
<Text dimColor>{event.text}</Text>
<Text color={leadColor} bold>
{lead}
</Text>
<Text> </Text>
<Text dimColor>{body}</Text>
</Box>
);
}
if (event.role === "plan") {
return (
<Box flexDirection="column" 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 backgroundColor="#4ade80" color="black" bold>
{" ✓ STEP "}
</Text>
{counter ? (
<>
<Text>{" "}</Text>
<Text color="#4ade80" bold>
{counter}
</Text>
</>
) : null}
<Text>{" "}</Text>
<Text color="#86efac">{label}</Text>
</Box>
{event.text ? (
<Box paddingLeft={2}>
<Text dimColor>{event.text}</Text>
</Box>
) : null}
{sp?.notes ? (
<Box paddingLeft={2}>
<Text color="#fbbf24" 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.
const nextStep = rp.steps.find((s) => !completedSet.has(s.id));
return (
<Box flexDirection="column" paddingX={1} marginY={1}>
<Box>
<Text backgroundColor="#67e8f9" color="black" bold>
{" ↻ RESUMED PLAN "}
</Text>
<Text>{" "}</Text>
<Text color="#67e8f9" bold>
{`${done}/${total}`}
</Text>
<Text dimColor>{` done · last touched ${rp.relativeTime}`}</Text>
</Box>
{rp.summary ? (
<Box marginTop={1}>
<Text color="#67e8f9">{rp.summary}</Text>
</Box>
) : null}
<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" paddingX={1} marginY={1}>
<Box>
<Text backgroundColor="#94a3b8" color="black" bold>
{" ⏪ REPLAY "}
</Text>
<Text>{" "}</Text>
<Text color="#94a3b8" bold>
{`${done}/${total}`}
</Text>
<Text dimColor>{` done · ${r.relativeTime}${navHint}`}</Text>
</Box>
{r.summary ? (
<Box marginTop={1}>
<Text color="#94a3b8">{r.summary}</Text>
</Box>
) : null}
<Box>
<Text dimColor>{r.archiveBasename}</Text>
</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>
<RoleGlyph glyph={ROLE_GLYPH.warning} color="yellow" />
<Text color="yellow">
{" "}
{event.text}
<Text backgroundColor="#fbbf24" color="black" bold>
{" ▲ WARN "}
</Text>
<Text>{" "}</Text>
<Text color="#fbbf24">{indentContinuationLines(event.text)}</Text>
</Box>
);
}
@@ -178,27 +491,38 @@ export const EventRow = React.memo(function EventRow({
});
/**
* Thin horizontal rule between turns with a cyan ◆ centered as the
* Reasonix mark. Past-turn separators live inside `<Static>` (Ink's
* render-once optimization), so animation here would freeze at
* tick=0 on every past turn — we keep it static by design. The
* animated heartbeat lives in PulsingAssistantGlyph (current turn)
* and the Wordmark (StatsPanel) where rerender is free.
* Decorative gradient rule between turns. Uses the brand gradient
* (teal → fuchsia) so the boundary between "old turn" and "new
* turn" reads as a designed accent rather than a dim minus-sign
* row. Static — past separators live inside Ink's `<Static>`, so
* animation would freeze at tick=0 anyway.
*/
function TurnSeparator() {
const { stdout } = useStdout();
const cols = stdout?.columns ?? 80;
const width = Math.max(16, cols - 2);
const half = Math.floor((width - 3) / 2);
const left = "─".repeat(half);
const right = "─".repeat(width - half - 3);
// Reserve 5 cells for ` ◆ ` in the middle. Split the remainder
// into two gradient halves so the brand mark sits on the seam.
const sideWidth = Math.max(2, Math.floor((width - 5) / 2));
const leftCells = gradientCells(sideWidth, "─");
const rightCells = gradientCells(sideWidth, "─");
return (
<Box marginTop={1} marginBottom={1}>
<Text dimColor>{left}</Text>
<Text color="cyan" bold>
{" ◆ "}
{leftCells.map((c, i) => (
// biome-ignore lint/suspicious/noArrayIndexKey: fixed-width gradient row
<Text key={`tsep-l-${i}`} color={c.color}>
{c.ch}
</Text>
))}
<Text color={COLOR.brand} bold>
{" ◆ "}
</Text>
<Text dimColor>{right}</Text>
{rightCells.map((c, i) => (
// biome-ignore lint/suspicious/noArrayIndexKey: fixed-width gradient row
<Text key={`tsep-r-${i}`} color={c.color}>
{c.ch}
</Text>
))}
</Box>
);
}
@@ -216,42 +540,57 @@ function EditFileDiff({ text }: { text: string }) {
const lines = text.split(/\r?\n/);
// Line 0 is the status header ("edited X (A→B chars)"), Line 1 is
// the unified-diff hunk header ("@@ -N,M +N,M @@"), the rest is
// the colored diff body. We style the two headers distinctly so
// the hunk marker stands out the way git-diff's cyan `@@` does in
// most terminals.
// the colored diff body. The hunk header gets a magenta-bg pill —
// same idiom as the rest of the TUI — so it visually anchors each
// hunk. Body lines render with a colored gutter glyph + tinted bg
// for + and -, so the diff scans like a syntax-highlighted patch
// file rather than a wall of monochrome text.
const [statusHeader, hunkHeader, ...body] = lines;
return (
<Box flexDirection="column">
<Text dimColor>{` ${statusHeader ?? ""}`}</Text>
{hunkHeader !== undefined ? (
<Text color="cyan" bold>
{hunkHeader}
</Text>
<Box marginTop={1}>
<Text backgroundColor="#c4b5fd" color="black" bold>
{` ${hunkHeader.trim()} `}
</Text>
</Box>
) : null}
{body.map((line, i) => {
// Key includes the line content slice so React isn't forced
// to treat purely-positional identity; lines in the same
// diff don't reorder but could repeat (e.g. blank lines).
const key = `${i}-${line.slice(0, 32)}`;
if (line.startsWith("- ")) {
// Strip the leading " " indent diff-preview adds to every
// body line so the gutter glyph is column 0 regardless of
// formatter changes upstream.
const stripped = line.replace(/^ {2}/, "");
if (stripped.startsWith("- ")) {
return (
<Text key={key} color="red">
{line}
</Text>
<Box key={key}>
<Text color="#f87171" bold>
{"− "}
</Text>
<Text color="#fca5a5">{stripped.slice(2)}</Text>
</Box>
);
}
if (line.startsWith("+ ")) {
if (stripped.startsWith("+ ")) {
return (
<Text key={key} color="green">
{line}
</Text>
<Box key={key}>
<Text color="#4ade80" bold>
{"+ "}
</Text>
<Text color="#86efac">{stripped.slice(2)}</Text>
</Box>
);
}
// Context line (starts with " ") or unknown — dim.
// Context line (starts with " ") or unknown — dim.
return (
<Text key={key} dimColor>
{line}
</Text>
<Box key={key}>
<Text dimColor>{" "}</Text>
<Text dimColor>{stripped}</Text>
</Box>
);
})}
</Box>
@@ -259,21 +598,36 @@ function EditFileDiff({ text }: { text: string }) {
}
function BranchBlock({ branch }: { branch: BranchSummary }) {
const per = branch.uncertainties
.map((u, i) => {
const marker = i === branch.chosenIndex ? "▸" : " ";
const t = (branch.temperatures[i] ?? 0).toFixed(1);
return `${marker} #${i} T=${t} u=${u}`;
})
.join(" ");
return (
<Box>
<Text color="blue">
{"⎇ branched "}
<Text bold>{branch.budget}</Text>
{` samples → picked #${branch.chosenIndex} `}
<Text dimColor>{per}</Text>
</Text>
<Box flexDirection="column" marginBottom={1}>
<Box>
<Text backgroundColor="#93c5fd" color="black" bold>
{` ⎇ BRANCH ×${branch.budget} `}
</Text>
<Text>{" "}</Text>
<Text color="#93c5fd">picked </Text>
<Text color="#93c5fd" bold>
#{branch.chosenIndex}
</Text>
</Box>
<Box paddingLeft={2} marginTop={1}>
{branch.uncertainties.map((u, i) => {
const chosen = i === branch.chosenIndex;
const t = (branch.temperatures[i] ?? 0).toFixed(1);
return (
// biome-ignore lint/suspicious/noArrayIndexKey: branch index is positional and stable
<Text key={`b-${i}`}>
<Text color={chosen ? "#93c5fd" : "#475569"} bold={chosen}>
{chosen ? "▸ " : " "}
</Text>
<Text color={chosen ? "#93c5fd" : "#94a3b8"} bold={chosen}>
{`#${i}`}
</Text>
<Text dimColor>{` T=${t} u=${u} `}</Text>
</Text>
);
})}
</Box>
</Box>
);
}
@@ -288,15 +642,14 @@ function ReasoningBlock({ reasoning }: { reasoning: string }) {
// Users can dump the full reasoning with `/think` if needed.
const preview =
flat.length <= max ? flat : `… (+${flat.length - max} earlier chars) ${flat.slice(-max)}`;
// ▏ (LEFT ONE EIGHTH BLOCK) renders as a thin vertical rule at the
// cell edge — subtler than the role-level ▎ above, giving a
// visual hierarchy: thick bar = role, thin bar = nested detail
// under that role (thinking, stats, citations, etc).
return (
<Box marginBottom={1}>
<Text dimColor>▏ </Text>
<Text dimColor italic>
thinking {preview}
<Text backgroundColor={COLOR.accent} color="black" bold>
{" ⋯ thinking "}
</Text>
<Text> </Text>
<Text color={COLOR.accent} italic dimColor>
{preview}
</Text>
</Box>
);
@@ -396,27 +749,34 @@ function StreamingAssistant({ event }: { event: DisplayEvent }) {
const preFirstByte = !event.text && !event.reasoning && !toolCallBuild;
const reasoningOnly = !event.text && !!event.reasoning && !toolCallBuild;
const toolCallOnly = !event.text && !event.reasoning && !!toolCallBuild;
// Phase pill — solid bg color per phase so the user reads
// "what's happening" at a glance from across the screen.
let pillBg: string;
let pillText: string;
let label: string;
let labelColor: "yellow" | "cyan" | "green" | "magenta" | undefined;
if (preFirstByte) {
pillBg = "#fbbf24"; // amber
pillText = "WAITING";
label = "request sent · waiting for server";
labelColor = "yellow";
} else if (reasoningOnly) {
label = `R1 reasoning · ${event.reasoning?.length ?? 0} chars of thought`;
labelColor = "cyan";
pillBg = "#c4b5fd"; // violet
pillText = "THINKING";
label = `${event.reasoning?.length ?? 0} chars of thought`;
} else if (toolCallOnly) {
label = `assembling tool call${formatToolCallIndex(toolCallBuild)} <${toolCallBuild.name}> · ${toolCallBuild.chars} chars of arguments${formatReadyTail(toolCallBuild)}`;
labelColor = "magenta";
pillBg = "#f0abfc"; // fuchsia
pillText = "DISPATCH";
label = `assembling${formatToolCallIndex(toolCallBuild)} <${toolCallBuild.name}> · ${toolCallBuild.chars} chars${formatReadyTail(toolCallBuild)}`;
} else {
const parts: string[] = [`writing response · ${event.text.length} chars`];
if (event.reasoning) parts.push(`after ${event.reasoning.length} chars of reasoning`);
pillBg = "#86efac"; // green
pillText = "WRITING";
const parts: string[] = [`${event.text.length} chars`];
if (event.reasoning) parts.push(`after ${event.reasoning.length} reasoning`);
if (toolCallBuild) {
parts.push(
`building tool call${formatToolCallIndex(toolCallBuild)} <${toolCallBuild.name}> · ${toolCallBuild.chars} chars${formatReadyTail(toolCallBuild)}`,
`tool${formatToolCallIndex(toolCallBuild)} <${toolCallBuild.name}> ${toolCallBuild.chars}c${formatReadyTail(toolCallBuild)}`,
);
}
label = parts.join(" · ");
labelColor = "green";
}
return (
<Box flexDirection="column" marginTop={1}>
@@ -424,36 +784,50 @@ function StreamingAssistant({ event }: { event: DisplayEvent }) {
<PulsingAssistantGlyph />
<Text>{" "}</Text>
<Pulse />
<Text color={labelColor}>{` ${label} `}</Text>
<Text> </Text>
<Text backgroundColor={pillBg} color="black" bold>
{` ${pillText} `}
</Text>
<Text dimColor>{` ${label} `}</Text>
<Elapsed />
</Box>
{reasoningTail ? (
<Text dimColor italic>
↳ thinking: {reasoningTail}
</Text>
<Box paddingLeft={3}>
<Text color="#c4b5fd" italic dimColor>
↳ {reasoningTail}
</Text>
</Box>
) : null}
{tail ? (
<Text dimColor>▸ {tail}</Text>
<Box paddingLeft={3}>
<Text dimColor>▸ {tail}</Text>
</Box>
) : preFirstByte ? (
// Non-dim yellow: first-time users misread the dim version as
// Non-dim amber: first-time users misread the dim version as
// "app frozen". The reassurance has to be VISIBLE to do its job.
<Text color="yellow" italic>
{" waiting for first byte — this is normal, typically 5-60s depending on model + load"}
</Text>
<Box paddingLeft={3}>
<Text color="#fbbf24" italic>
{"waiting for first byte — typical 5–60s depending on model + load"}
</Text>
</Box>
) : reasoningOnly ? (
<Text color="yellow" italic>
{
" R1 is thinking before it speaks — body text arrives when reasoning finishes (typically 20-90s, this is normal)"
}
</Text>
<Box paddingLeft={3}>
<Text color="#c4b5fd" italic>
{"R1 thinks before it speaks — body text arrives when reasoning finishes (20–90s)"}
</Text>
</Box>
) : toolCallOnly ? (
<Text color="magenta" italic>
{" tool-call arguments streaming — the model is about to dispatch a tool"}
</Text>
<Box paddingLeft={3}>
<Text color="#f0abfc" italic>
{"tool-call arguments streaming — about to dispatch"}
</Text>
</Box>
) : event.reasoning ? (
<Text color="yellow" italic>
{" R1 still reasoning — body text or tool call arrives when thinking finishes"}
</Text>
<Box paddingLeft={3}>
<Text color="#fbbf24" italic>
{"R1 still reasoning — body text or tool call arrives when thinking finishes"}
</Text>
</Box>
) : null}
</Box>
);
@@ -502,48 +876,26 @@ function lastLine(s: string, maxChars: number): string {
function StatsLine({ stats }: { stats: TurnStats }) {
const hit = (stats.cacheHitRatio * 100).toFixed(1);
const hitColor =
stats.cacheHitRatio >= 0.7 ? "#4ade80" : stats.cacheHitRatio >= 0.4 ? "#fcd34d" : "#f87171";
return (
<Box>
<Text dimColor>▏ </Text>
<Text dimColor>
{"cache "}
{hit}
{"% · tokens "}
{stats.usage.promptTokens}
{" → "}
{stats.usage.completionTokens}
{" · $"}
{stats.cost.toFixed(6)}
<Box marginTop={1}>
<Text color={hitColor} bold>
{`⌬ ${hit}%`}
</Text>
<Text dimColor>{" · "}</Text>
<Text color="#94a3b8">
{"in "}
<Text color="#67e8f9" bold>
{stats.usage.promptTokens}
</Text>
{" → out "}
<Text color="#c4b5fd" bold>
{stats.usage.completionTokens}
</Text>
</Text>
<Text dimColor>{" · "}</Text>
<Text color="#86efac" bold>{`$${stats.cost.toFixed(6)}`}</Text>
</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)}`;
}
+333
View File
@@ -0,0 +1,333 @@
import { Box, Text, useStdout } from "ink";
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React as a runtime value (classic transform)
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} paddingX={1}>
<Text color="#c4b5fd" bold>
{SPINNER_FRAMES[tick % SPINNER_FRAMES.length]}
</Text>
<Text>{" "}</Text>
<Text color="#c4b5fd">{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;
// The same mode pill is already in the StatsPanel header — here we
// skip the pill and keep just a tight inline hint right above the
// input so the user has the actionable bit (what y/n/u/Shift+Tab
// do) without the whole tutorial.
if (planMode) {
return (
<ModeBarFrame>
<ModePill label="PLAN MODE" bg="red" flash={flash} />
<Text dimColor>{" writes gated · /plan off to leave"}</Text>
{jobsTag}
</ModeBarFrame>
);
}
const isAuto = editMode === "auto";
const label = isAuto ? "AUTO" : "REVIEW";
const bg = isAuto ? "magenta" : "cyan";
const mid = isAuto
? "edits land now · u to undo"
: pendingCount > 0
? `${pendingCount} queued · y apply · n discard`
: "edits queued · y apply · n discard";
return (
<ModeBarFrame>
<ModePill label={label} bg={bg} flash={flash} />
<Text dimColor>{` ${mid} · Shift+Tab to flip`}</Text>
{jobsTag}
</ModeBarFrame>
);
}
/**
* Wraps the bottom mode/jobs row in a dim top rule + side padding
* so the modeline reads as its own zone, separate from the prompt
* input above. Keeps the live region border-free (the rule is a
* single Text row, not a bordered Box) so Ink's eraseLines miscount
* stays out of it.
*/
function ModeBarFrame({ children }: { children: React.ReactNode }) {
const { stdout } = useStdout();
const cols = stdout?.columns ?? 80;
const ruleWidth = Math.max(20, cols - 2);
return (
<Box flexDirection="column">
<Box paddingX={1}>
<Text color="#475569" dimColor>
{"╌".repeat(ruleWidth)}
</Text>
</Box>
<Box paddingX={1}>{children}</Box>
</Box>
);
}
/**
* Solid-background mode badge so the bottom status bar reads at a
* glance like a real editor's modeline (vim/helix style) instead of a
* dim text label that blends into the prompt above. `flash` inverts
* briefly after a mode flip — the existing modeFlash signal — for a
* "yes, it changed" acknowledgement.
*/
function ModePill({
label,
bg,
flash,
}: {
label: string;
bg: "magenta" | "cyan" | "red";
flash: boolean;
}) {
return (
<Text backgroundColor={bg} color="white" bold inverse={flash}>
{` ${label} `}
</Text>
);
}
/**
* "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;
const urgent = remainingSec <= 1;
return (
<Box marginY={1} paddingX={1}>
<Text backgroundColor="#c4b5fd" color="black" bold>
{` ✓ AUTO-APPLIED ${ok}/${total} `}
</Text>
<Text dimColor>{" press "}</Text>
<Text backgroundColor="#67e8f9" color="black" bold>
{" u "}
</Text>
<Text dimColor>{" to undo "}</Text>
<Text color={urgent ? "#f87171" : "#c4b5fd"} bold={urgent}>
{`${remainingSec}s`}
</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={3}>
<Text color="#c4b5fd" bold>
{SPINNER_FRAMES[tick % SPINNER_FRAMES.length]}
</Text>
<Text>{" "}</Text>
<Text backgroundColor="#c4b5fd" color="black" bold>
{" ⌬ subagent "}
</Text>
<Text color="#c4b5fd">{` ${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" paddingX={1}>
<Box>
<Text color="#fcd34d" bold>
{SPINNER_FRAMES[tick % SPINNER_FRAMES.length]}
</Text>
<Text>{" "}</Text>
<Text backgroundColor="#fcd34d" color="black" bold>
{` ⏵ ${tool.name} `}
</Text>
<Text color="#fcd34d">{" running"}</Text>
<Text dimColor>{` · ${elapsed}s`}</Text>
</Box>
{progress ? (
<Box paddingLeft={3}>
<Text color="#67e8f9">{renderProgressLine(progress)}</Text>
</Box>
) : null}
{summary ? (
<Box paddingLeft={3}>
<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;
}
+70
View File
@@ -0,0 +1,70 @@
/**
* Shared visual frame for confirmation modals (ChoiceConfirm,
* PlanConfirm, ShellConfirm, EditConfirm, PlanCheckpointConfirm,
* PlanReviseConfirm). Each modal opens inside the live region — so
* we keep the frame to plain Text rules and bg-pill headers, no
* Ink `borderStyle` (that's the eraseLines miscount class of bug).
*
* Layout:
*
* ▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
* [ ICON TITLE ] optional subtitle
*
* <children — body of the modal>
*
* ▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁
*
* Color drives the accent (top + bottom rules + title pill bg)
* so the user learns to recognize "magenta = choice", "cyan =
* plan", "red = shell", "yellow = edit review" by sight.
*/
import { Box, Text, useStdout } from "ink";
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React in value scope
import React from "react";
export interface ModalCardProps {
/** Accent color — title pill bg + top/bottom rule color. */
accent: string;
/** Section title shown in the bg-pill header. */
title: string;
/** Optional dim subtitle next to the title. */
subtitle?: string;
/** Optional leading glyph inside the title pill (icon). */
icon?: string;
children: React.ReactNode;
}
export function ModalCard({
accent,
title,
subtitle,
icon,
children,
}: ModalCardProps): React.ReactElement {
const { stdout } = useStdout();
const cols = stdout?.columns ?? 80;
const ruleWidth = Math.min(80, Math.max(28, cols - 4));
const titleText = icon ? ` ${icon} ${title} ` : ` ${title} `;
return (
<Box flexDirection="column" paddingX={1} marginY={1}>
<Box>
<Text color={accent}>{"▔".repeat(ruleWidth)}</Text>
</Box>
<Box marginTop={1}>
<Text backgroundColor={accent} color="black" bold>
{titleText}
</Text>
{subtitle ? <Text dimColor>{` ${subtitle}`}</Text> : null}
</Box>
<Box marginTop={1} flexDirection="column">
{children}
</Box>
<Box marginTop={1}>
<Text color={accent} dimColor>
{"▁".repeat(ruleWidth)}
</Text>
</Box>
</Box>
);
}
+118
View File
@@ -0,0 +1,118 @@
/**
* 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 } from "ink";
import React from "react";
import type { PlanStep } from "../../tools/plan.js";
import { ModalCard } from "./ModalCard.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);
const subtitle = counter ? `${counter} · ${label}` : label;
return (
<ModalCard accent="#86efac" icon="✓" title="checkpoint — step done" subtitle={subtitle}>
{steps && steps.length > 0 ? (
<Box marginBottom={1} flexDirection="column">
<PlanStepList steps={steps} statuses={statuses} focusStepId={stepId} />
</Box>
) : null}
<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"
/>
</ModalCard>
);
}
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;
}
+52 -122
View File
@@ -9,99 +9,34 @@
* 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 { ModalCard } from "./ModalCard.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.
@@ -110,55 +45,50 @@ function PlanConfirmInner({
/^#{1,6}\s*(待确认|开放问题|风险|未知|假设|不确定)/im.test(plan);
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>
<ModalCard
accent="#67e8f9"
icon="📋"
title="plan proposed"
subtitle={summary ?? "approve / refine / cancel"}
>
{hasOpenQuestions ? (
<Box marginTop={1}>
<Text color="yellow">
▲ the plan has open questions or flagged risks — pick{" "}
<Box marginBottom={1}>
<Text color="#fbbf24">
▲ 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}
<Box marginTop={1}>
<SingleSelect
initialValue={hasOpenQuestions ? "refine" : "approve"}
items={[
{
value: "approve",
label: "Approve and implement",
hint: "Exit plan mode. The model starts executing. You'll get a text input to add any last instructions (or just press Enter to skip).",
},
{
value: "refine",
label: "Refine / answer questions",
hint: "Stay in plan mode. Write answers, modifications, or critiques; the model revises and re-submits.",
},
{
value: "cancel",
label: "Cancel",
hint: "Exit plan mode. Drop the plan; the model won't implement it.",
},
]}
onSubmit={(v) => onChoose(v as PlanConfirmChoice)}
onCancel={() => onChoose("cancel")}
footer="[↑↓] navigate · [Enter] select · [Esc] cancel"
/>
</Box>
</Box>
{steps && steps.length > 0 ? (
<Box marginBottom={1} flexDirection="column">
<PlanStepList steps={steps} />
</Box>
) : null}
<SingleSelect
initialValue={hasOpenQuestions ? "refine" : "approve"}
items={[
{
value: "approve",
label: "Approve and implement",
hint: "Exit plan mode. The model starts executing. You'll get a text input to add any last instructions (or just press Enter to skip).",
},
{
value: "refine",
label: "Refine / answer questions",
hint: "Stay in plan mode. Write answers, modifications, or critiques; the model revises and re-submits.",
},
{
value: "cancel",
label: "Cancel",
hint: "Exit plan mode. Drop the plan; the model won't implement it.",
},
]}
onSubmit={(v) => onChoose(v as PlanConfirmChoice)}
onCancel={() => onChoose("cancel")}
footer="[↑↓] navigate · [Enter] select · [Esc] cancel"
/>
</ModalCard>
);
}
+72 -30
View File
@@ -14,17 +14,23 @@
* the picker without resuming.
*/
import { Box, Text, useInput } from "ink";
import { Box, Text } from "ink";
import React, { useState } from "react";
import { ModalCard } from "./ModalCard.js";
import { useKeystroke } from "./keystroke-context.js";
import { useTick } from "./ticker.js";
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. */
@@ -34,58 +40,94 @@ export interface PlanRefineInputProps {
export function PlanRefineInput({ mode, onSubmit, onCancel }: PlanRefineInputProps) {
const [value, setValue] = useState("");
useInput((input, key) => {
if (key.escape) {
useKeystroke((ev) => {
if (ev.paste) {
// Insert paste content as-is. Multi-line pastes flatten via
// newlines becoming spaces because this is a single-line input.
setValue((v) => v + ev.input.replace(/\r?\n/g, " "));
return;
}
if (ev.escape) {
onCancel();
return;
}
if (key.return) {
if (ev.return) {
onSubmit(value.trim());
return;
}
if (key.backspace || key.delete) {
if (ev.backspace || ev.delete) {
setValue((v) => v.slice(0, -1));
return;
}
// Filter out non-printable chars; accept ordinary text + CJK.
if (input && !key.ctrl && !key.meta) {
setValue((v) => v + input);
if (ev.input && !ev.ctrl && !ev.meta) {
setValue((v) => v + ev.input);
}
});
const title =
const tick = useTick();
// Slow blink for the cursor block (~480 ms on/off). Same cadence
// as the wordmark's brand-mark pulse; reads as "input is alive".
const cursorOn = Math.floor(tick / 4) % 2 === 0;
const meta =
mode === "approve"
? "▸ approving — any last instructions or answers to open questions?"
: "▸ refining — what should the model change?";
? {
title: "approving — any last instructions?",
icon: "📋",
accent: "#67e8f9",
}
: mode === "checkpoint-revise"
? {
title: "revising — what should change before the next step?",
icon: "✏",
accent: "#fbbf24",
}
: mode === "choice-custom"
? {
title: "custom answer — type whatever fits",
icon: "🔀",
accent: "#f0abfc",
}
: {
title: "refining — what should the model change?",
icon: "✏",
accent: "#fbbf24",
};
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 adjusts the remaining plan."
: 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}>
<Box>
<Text bold color="yellow">
{title}
</Text>
</Box>
<Box marginTop={1}>
<ModalCard accent={meta.accent} icon={meta.icon} title={meta.title}>
<Box marginBottom={1}>
<Text dimColor>
{hint} Enter to send · Esc to return to the picker.
{value === "" ? blankHint : ""}
</Text>
</Box>
<Box marginTop={1}>
<Text>
<Text color="yellow">› </Text>
<Text>{value || " "}</Text>
<Text color="yellow">▍</Text>
<Box>
<Text color={meta.accent} bold>
{"› "}
</Text>
<Text>{value}</Text>
<Text color={meta.accent} bold>
{cursorOn ? "▍" : " "}
</Text>
</Box>
</Box>
</ModalCard>
);
}
+141
View File
@@ -0,0 +1,141 @@
/**
* 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 { ModalCard } from "./ModalCard.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: string } {
switch (risk) {
case "high":
return { dots: "●●●", color: "#f87171" };
case "med":
return { dots: "●● ", color: "#fbbf24" };
case "low":
return { dots: "● ", color: "#4ade80" };
default:
return { dots: " ", color: "#94a3b8" };
}
}
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 (
<ModalCard
accent="#fbbf24"
icon="✏"
title="plan revision proposed"
subtitle={`−${removedCount} +${addedCount} · ${keptCount} kept`}
>
<Box marginBottom={1}>
<Text>{reason}</Text>
</Box>
{summary ? (
<Box marginBottom={1}>
<Text dimColor>{`updated summary: ${summary}`}</Text>
</Box>
) : null}
<Box marginBottom={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" ? "#f87171" : row.kind === "added" ? "#4ade80" : "#94a3b8";
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>
<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"
/>
</ModalCard>
);
}
export const PlanReviseConfirm = React.memo(PlanReviseConfirmInner);
+11 -12
View File
@@ -18,30 +18,29 @@ import { Box, Text } from "ink";
import React from "react";
import type { TypedPlanState } from "../../harvest.js";
type FieldColor = "cyan" | "green" | "yellow" | "red";
type FieldColor = string;
export function PlanStateBlock({ planState }: { planState: TypedPlanState }) {
const fields: Array<[string, string[], FieldColor, boolean]> = [];
if (planState.subgoals.length) fields.push(["subgoals", planState.subgoals, "cyan", false]);
if (planState.subgoals.length) fields.push(["subgoals", planState.subgoals, "#67e8f9", false]);
if (planState.hypotheses.length)
fields.push(["hypotheses", planState.hypotheses, "green", false]);
fields.push(["hypotheses", planState.hypotheses, "#86efac", false]);
if (planState.uncertainties.length)
fields.push(["uncertainties", planState.uncertainties, "yellow", false]);
fields.push(["uncertainties", planState.uncertainties, "#fcd34d", false]);
if (planState.rejectedPaths.length)
fields.push(["rejected", planState.rejectedPaths, "red", true]);
fields.push(["rejected", planState.rejectedPaths, "#94a3b8", true]);
if (fields.length === 0) return null;
return (
<Box flexDirection="column" marginBottom={1}>
{fields.map(([label, items, color, dim]) => (
<Text key={label}>
<Text color={color} bold dimColor={dim}>
{"‹ "}
{label}
<Box key={label}>
<Text backgroundColor={color} color="black" bold dimColor={dim}>
{` ${label} ${items.length} `}
</Text>
<Text dimColor>{` (${items.length})`}</Text>
<Text>{`: ${items.join(" · ")}`}</Text>
</Text>
<Text>{" "}</Text>
<Text dimColor={dim}>{items.join(" · ")}</Text>
</Box>
))}
</Box>
);
+159
View File
@@ -0,0 +1,159 @@
/**
* 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 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;
const pct = Math.round((doneCount / steps.length) * 100);
return (
<Box flexDirection="column">
<Box>
<Text dimColor>
{`${steps.length} step${steps.length === 1 ? "" : "s"}`}
{doneCount > 0 ? ` · ${doneCount}/${steps.length} done (${pct}%)` : ""}
{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 titleDim = status === "done" || status === "skipped";
return (
<Box key={step.id}>
<Text color={focus ? "#67e8f9" : "gray"} bold={focus}>
{focus ? "▸ " : " "}
</Text>
<Text color={risk.color} bold>
{risk.dots}
</Text>
<Text> </Text>
<StatusBadge status={status} />
<Text> </Text>
<Text dimColor={titleDim} bold={focus}>
{`${step.id} · ${step.title}`}
</Text>
</Box>
);
})}
</Box>
</Box>
);
}
/**
* Status pill — solid-bg badge per step state. Reads at a glance
* better than a glyph + color text: ` DONE `, ` RUN `, ` SKIP `,
* ` PEND `. The label widths are normalized so the column under
* the badge stays aligned even when statuses mix.
*/
function StatusBadge({ status }: { status: StepStatus }) {
switch (status) {
case "done":
return (
<Text backgroundColor="#4ade80" color="black" bold>
{" ✓ DONE "}
</Text>
);
case "running":
return (
<Text backgroundColor="#67e8f9" color="black" bold>
{" ▶ RUN "}
</Text>
);
case "skipped":
return (
<Text backgroundColor="#94a3b8" color="black" bold>
{" — SKIP "}
</Text>
);
default:
return (
<Text color="#94a3b8" dimColor>
{" ☐ PEND "}
</Text>
);
}
}
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;
}
+513 -117
View File
@@ -1,7 +1,52 @@
import { Box, Text, useInput } from "ink";
import { Box, Text, useStdout } 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 { useKeystroke } from "./keystroke-context.js";
import { type MultilineKey, lineAndColumn, processMultilineKey } from "./multiline-keys.js";
import { useTick } from "./ticker.js";
import {
PASTE_SENTINEL_RANGE,
type PasteEntry,
encodePasteSentinel,
expandPasteSentinels,
listPasteIdsInBuffer,
makePasteEntry,
} from "./paste-sentinels.js";
import { type Segment, buildViewport, stringCells } from "./prompt-viewport.js";
import { GRADIENT } from "./theme.js";
/**
* Visual anchor: a left vertical rule (▎ + space) running down every
* line of the input. Colored with the accent color so disabled state
* dims it; gives the input area a clear "you type here" boundary
* without using bordered Boxes (those amplified Ink's eraseLines
* miscount on Windows). Length is fixed at 2 so the prefix-cell math
* stays trivial.
*/
const BAR = "▎ ";
/**
* Prompt input v2 — no Ink useInput, no Yoga text wrapping, no
* cursor blink. Replaces the bordered-Box / multi-Text approach
* that was driving the Windows ghost-row regressions.
*
* Pipeline:
* - Subscribes to the global keystroke bus (which is fed by our
* own raw stdin parser, NOT Ink's parse-keypress).
* - Pure events: `paste` events go to the paste registry; everything
* else flows through `processMultilineKey` (the existing reducer
* with all the cursor / submit / history-recall semantics).
* - Render: one logical line per <Box> row. Each row renders as
* EXACTLY one visual row — content longer than the visible cell
* budget is clipped via `buildViewport`, with `‹` / `›` markers
* where content is hidden. The cursor moves the viewport so it
* stays visible.
*
* Cursor blinks at ~480 ms half-period. The ticker that drives the
* blink also flows the left-bar gradient and the wordmark, so
* we're already paying for re-render every tick — the cursor blink
* is free on top of that. Disabled state freezes the cursor solid
* so the disabled prompt doesn't compete with the active spinner.
*/
export interface PromptInputProps {
value: string;
@@ -9,156 +54,507 @@ export interface PromptInputProps {
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;
}
/**
* Input box with real cursor support. ←/→ move one column, ↑/↓ move
* across lines in multi-line buffers, Ctrl+A / Ctrl+E jump to
* start/end of the current line. Backspace deletes before cursor,
* Delete deletes under cursor. Multi-line composition via Ctrl+J,
* Shift+Enter, or bash-style `\<Enter>`.
*
* Cursor state lives locally. When the parent replaces `value` out
* of band (history recall, slash completion, setup wizard) the
* cursor jumps to end; the `lastLocalValueRef` guards distinguishes
* that case from our own edits.
*/
export function PromptInput({
value,
onChange,
onSubmit,
disabled,
placeholder,
onHistoryPrev,
onHistoryNext,
}: PromptInputProps) {
const [cursor, setCursor] = useState(value.length);
// 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.
// Paste registry — keyed by sentinel id, holds original content.
const pastesRef = useRef<Map<number, PasteEntry>>(new Map());
const nextPasteIdRef = useRef<number>(0);
// Track external value replacement (history recall, slash completion).
// When the parent swaps `value` we snap cursor to end.
const lastLocalValueRef = useRef(value);
if (value !== lastLocalValueRef.current) {
lastLocalValueRef.current = value;
if (cursor !== value.length) {
// Conditional setState during render is the "derived state" pattern;
// React schedules the re-render and the else branch of the `if`
// prevents infinite loops.
setCursor(value.length);
}
if (cursor !== value.length) setCursor(value.length);
}
// 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;
/**
* Register one paste blob and insert its sentinel at the current
* cursor. Used both by `paste` events from the stdin reader (the
* normal path on terminals that support DECSET 2004) and by the
* fallback path inside `processMultilineKey` for chunks that
* arrived without bracketed-paste markers.
*/
const registerPaste = (content: string) => {
const v = lastLocalValueRef.current;
const c = cursor;
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);
lastLocalValueRef.current = next;
onChange(next);
setCursor(c + 1);
};
useInput(
(input, key) => {
const ke: MultilineKey = {
input,
return: key.return,
shift: key.shift,
ctrl: key.ctrl,
meta: key.meta,
backspace: key.backspace,
delete: key.delete,
tab: key.tab,
upArrow: key.upArrow,
downArrow: key.downArrow,
leftArrow: key.leftArrow,
rightArrow: key.rightArrow,
escape: key.escape,
pageUp: key.pageUp,
pageDown: key.pageDown,
};
const action = processMultilineKey(value, cursor, ke);
if (action.next !== null) {
lastLocalValueRef.current = action.next;
onChange(action.next);
useKeystroke((ev) => {
if (disabled) return;
if (ev.paste) {
// Bracketed-paste content delivered by the stdin reader.
// Insert as one sentinel regardless of length.
if (ev.input.length > 0) registerPaste(ev.input);
return;
}
const key: MultilineKey = {
input: ev.input,
return: ev.return,
shift: ev.shift,
ctrl: ev.ctrl,
meta: ev.meta,
backspace: ev.backspace,
delete: ev.delete,
tab: ev.tab,
upArrow: ev.upArrow,
downArrow: ev.downArrow,
leftArrow: ev.leftArrow,
rightArrow: ev.rightArrow,
escape: ev.escape,
pageUp: ev.pageUp,
pageDown: ev.pageDown,
};
const action = processMultilineKey(value, cursor, key);
if (action.pasteRequest) {
registerPaste(action.pasteRequest.content);
return;
}
if (action.next !== null) {
lastLocalValueRef.current = action.next;
onChange(action.next);
}
if (action.cursor !== null) {
setCursor(action.cursor);
}
if (action.submit) {
const raw = action.submitValue ?? value;
const expanded = expandPasteSentinels(raw, pastesRef.current);
// GC unreachable paste entries — anything 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);
}
if (action.cursor !== null) {
setCursor(action.cursor);
}
if (action.submit) onSubmit(action.submitValue ?? value);
},
{ isActive: !disabled },
);
onSubmit(expanded);
}
if (action.historyHandoff === "prev") onHistoryPrev?.();
if (action.historyHandoff === "next") onHistoryNext?.();
}, !disabled);
// ── Render ──────────────────────────────────────────────────────
const { stdout } = useStdout();
const cols = stdout?.columns ?? 80;
const narrow = cols <= 90;
const promptBody = narrow ? "› " : "you › ";
const promptPrefix = BAR + promptBody;
const continuationIndent = BAR + " ".repeat(promptBody.length);
const prefixCells = promptPrefix.length;
// Reserve 2 cells for the surrounding `paddingX={1}` plus 1 cell
// for the cursor block when at end-of-line. Net visible budget per
// line.
const visibleCells = Math.max(8, cols - prefixCells - 3);
const placeholderActive = narrow
? "type a message, or /command"
: "type a message, or /command · [Ctrl+J] newline · [Ctrl+P/N] history";
const effectivePlaceholder = disabled
? (placeholder ?? "…waiting for response… · [Esc] to stop")
: (placeholder ?? "type a message, or /command · [Shift+Enter] / [Ctrl+J] newline");
? (placeholder ?? "…waiting for response…")
: (placeholder ?? placeholderActive);
const lines = value.length > 0 ? value.split("\n") : [""];
const borderColor = disabled ? "gray" : "cyan";
const accentColor = disabled ? "gray" : "cyan";
// Static bar + static cursor. Earlier versions flowed the bar
// gradient and blinked the cursor via the global ticker; both
// drove per-tick re-renders that interleaved badly with terminal
// resize (Ink's eraseLines miscounts logical vs visual rows on
// wrap, ghost frames stack). The bar still gets a gradient — just
// a fixed sweep based on row index, no time component.
const barColorAt = (rowIdx: number): string =>
disabled ? "gray" : GRADIENT[((rowIdx % GRADIENT.length) + GRADIENT.length) % GRADIENT.length]!;
const cursorVisible = true;
const { line: cursorLine, col: cursorCol } = lineAndColumn(value, cursor);
// Big-buffer mitigation: if the buffer has many logical lines,
// collapse middle rows so Ink isn't redrawing 500+ rows per
// keystroke.
const renderItems = collapseLinesForDisplay(lines, cursorLine);
const showHugeBufferHints = lines.length > 20;
return (
<Box borderStyle="round" borderColor={borderColor} paddingX={1} flexDirection="column">
{lines.map((line, i) => {
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}>
{isFirst ? (
<Text bold color={borderColor}>
you ›{" "}
<Box flexDirection="column" paddingX={1}>
{renderItems.map((item, renderIdx) => {
if (item.kind === "skip") {
return (
// biome-ignore lint/suspicious/noArrayIndexKey: stable — collapse markers derive from a fixed sliding window
<Box key={`skip-${renderIdx}`}>
<Text color={barColorAt(renderIdx)}>{BAR}</Text>
<Text dimColor>{continuationIndent.slice(BAR.length)}</Text>
<Text dimColor>
{`[… ${item.linesHidden} line${item.linesHidden === 1 ? "" : "s"} hidden — full content kept, submitted on Enter …]`}
</Text>
) : (
<Text dimColor>{" "}</Text>
)}
{showPlaceholder ? (
<>
{isCursorLine && !disabled ? (
<Text color={borderColor}>{showCursor ? "▌" : " "}</Text>
) : null}
<Text dimColor>{effectivePlaceholder}</Text>
</>
) : isCursorLine && !disabled ? (
<LineWithCursor
line={line}
col={cursorCol}
showCursor={showCursor}
borderColor={borderColor}
/>
) : (
<Text>{line}</Text>
)}
</Box>
</Box>
);
}
const i = item.originalIndex;
const line = item.line;
const isFirst = i === 0;
const isCursorLine = i === cursorLine;
const showPlaceholder = isFirst && value.length === 0;
return (
<PromptLine
key={`ln-${i}`}
line={line}
isFirst={isFirst}
isCursorLine={isCursorLine && !disabled}
cursorCol={isCursorLine ? cursorCol : null}
cursorVisible={cursorVisible}
showPlaceholder={showPlaceholder}
placeholderText={effectivePlaceholder}
promptPrefix={promptPrefix}
continuationIndent={continuationIndent}
visibleCells={visibleCells}
accentColor={accentColor}
barColor={barColorAt(i)}
pastes={pastesRef.current}
disabled={disabled === true}
/>
);
})}
{showHugeBufferHints && !disabled ? (
<Box>
<Text color={barColorAt(0)}>{BAR}</Text>
<Text dimColor>{continuationIndent.slice(BAR.length)}</Text>
<Text dimColor>
{`[${lines.length} lines · PageUp/PageDown jump to top/bottom · Ctrl+U clear · Ctrl+W del word]`}
</Text>
</Box>
) : null}
{!disabled && !narrow && value.length > 0 && !value.includes("\n") ? (
<Box>
<Text color={barColorAt(0)}>{BAR}</Text>
<Text dimColor>{continuationIndent.slice(BAR.length)}</Text>
<Text dimColor>
[Ctrl+J] newline · [Enter] submit · ends with \ for line continuation
</Text>
</Box>
) : null}
{disabled ? (
<Box>
<Text color={barColorAt(0)}>{BAR}</Text>
<Text dimColor>{continuationIndent.slice(BAR.length)}</Text>
<Text dimColor>[Esc] to stop</Text>
</Box>
) : null}
</Box>
);
}
function LineWithCursor({
line,
col,
showCursor,
borderColor,
}: {
// ── PromptLine ────────────────────────────────────────────────────
interface PromptLineProps {
line: string;
col: number;
showCursor: boolean;
borderColor: "cyan" | "gray";
}) {
const before = line.slice(0, col);
const atCursor = line.slice(col, col + 1);
const after = line.slice(col + 1);
if (atCursor.length === 0) {
// Cursor sits past the last char of this line (end-of-line). Render
// a trailing block so the user sees where they're typing next.
isFirst: boolean;
isCursorLine: boolean;
cursorCol: number | null;
/** True when the cursor block / inverse char should be drawn this tick. */
cursorVisible: boolean;
showPlaceholder: boolean;
placeholderText: string;
promptPrefix: string;
continuationIndent: string;
visibleCells: number;
accentColor: "cyan" | "gray";
/** Animated gradient color for the leading ▎ bar. Differs per row + tick. */
barColor: string;
pastes: ReadonlyMap<number, PasteEntry>;
disabled: boolean;
}
function PromptLine({
line,
isFirst,
isCursorLine,
cursorCol,
cursorVisible,
showPlaceholder,
placeholderText,
promptPrefix,
continuationIndent,
visibleCells,
accentColor,
barColor,
pastes,
disabled,
}: PromptLineProps) {
// The leading BAR cells of every prefix/continuation are the left
// anchor bar — render them as a separate span colored by the
// animated gradient so the bar appears to flow vertically.
const barText = promptPrefix.slice(0, BAR.length);
const bodyPrefix = promptPrefix.slice(BAR.length);
const bodyContinuation = continuationIndent.slice(BAR.length);
if (showPlaceholder) {
return (
<>
<Text>{before}</Text>
<Text color={borderColor}>{showCursor ? "▌" : " "}</Text>
</>
<Box>
<Text color={barColor}>{barText}</Text>
<Text bold color={accentColor}>
{bodyPrefix}
</Text>
{!disabled ? <Text color={accentColor}>{cursorVisible ? "▌" : " "}</Text> : null}
<Text dimColor>{placeholderText}</Text>
</Box>
);
}
const viewport = buildViewport(line, isCursorLine ? cursorCol : null, visibleCells, pastes);
// Render: prefix + (left marker?) + segments-with-cursor + (right marker?)
return (
<>
<Text>{before}</Text>
<Text inverse={showCursor}>{atCursor}</Text>
<Text>{after}</Text>
</>
<Box>
<Text color={barColor}>{barText}</Text>
{isFirst ? (
<Text bold color={accentColor}>
{bodyPrefix}
</Text>
) : (
<Text dimColor>{bodyContinuation}</Text>
)}
{viewport.hiddenLeft ? (
<Text color="gray" dimColor>
‹
</Text>
) : null}
<ViewportContent
segments={viewport.segments}
cursorCell={isCursorLine ? viewport.cursorCell : null}
accentColor={accentColor}
cursorVisible={cursorVisible}
/>
{viewport.hiddenRight ? (
<Text color="gray" dimColor>
›
</Text>
) : null}
</Box>
);
}
// ── ViewportContent ────────────────────────────────────────────────
/**
* Render a viewport's segments with a cursor block at `cursorCell`.
* Walks segments in order; the cursor splits at most one segment
* (the one containing the cursor cell), producing an inverted char
* at that position.
*
* End-of-line cursor (cursorCell points past the last cell of the
* last segment): emit a trailing block.
*/
function ViewportContent({
segments,
cursorCell,
accentColor,
cursorVisible,
}: {
segments: Segment[];
cursorCell: number | null;
accentColor: "cyan" | "gray";
cursorVisible: boolean;
}) {
// No cursor on this line — straight render.
if (cursorCell === null) {
return <>{segments.map((seg, i) => renderSegment(seg, i, false))}</>;
}
// Walk segments tallying cells; once we reach `cursorCell`, split
// the segment to insert the cursor block.
const out: React.ReactNode[] = [];
let cells = 0;
let placed = false;
for (let i = 0; i < segments.length; i++) {
const seg = segments[i]!;
const segCells = segmentCells(seg);
if (placed) {
out.push(renderSegment(seg, i, false));
continue;
}
if (cursorCell >= cells + segCells) {
// Cursor isn't in this segment.
out.push(renderSegment(seg, i, false));
cells += segCells;
continue;
}
// Cursor lands inside this segment.
if (seg.kind === "paste") {
// The cursor is "on" the paste sentinel — render the paste
// block inversed so the user sees they're at it. Inverse
// toggles with the blink so the paste sentinel stays
// legible during the cursor's "off" half-cycle.
out.push(
<Text key={`p-${i}-cursor`} color="magenta" bold inverse={cursorVisible}>
{seg.label}
</Text>,
);
placed = true;
cells += segCells;
continue;
}
// text segment — split before/at-cursor/after by cell offset.
const offsetIntoSeg = cursorCell - cells;
const split = splitTextByCells(seg.text, offsetIntoSeg);
if (split.before.length > 0) {
out.push(<Text key={`t-${i}-b`}>{split.before}</Text>);
}
if (split.atCursor.length > 0) {
out.push(
<Text key={`t-${i}-c`} inverse={cursorVisible} color={accentColor}>
{split.atCursor}
</Text>,
);
} else {
// Cursor sits past the segment's last char (end-of-text in this
// segment). Render block here, blinking with the tick.
out.push(
<Text key={`t-${i}-c-eol`} color={accentColor}>
{cursorVisible ? "▌" : " "}
</Text>,
);
}
if (split.after.length > 0) {
out.push(<Text key={`t-${i}-a`}>{split.after}</Text>);
}
placed = true;
cells += segCells;
}
// Cursor sits past every segment (end of line).
if (!placed) {
out.push(
<Text key="cursor-eol" color={accentColor}>
{cursorVisible ? "▌" : " "}
</Text>,
);
}
return <>{out}</>;
}
function segmentCells(seg: Segment): number {
if (seg.kind === "paste") return seg.label.length;
return stringCells(seg.text);
}
/**
* Split a text string at a cell offset, returning the chars before
* the offset, the char AT the offset (the cursor block highlights
* it), and the chars after. A wide char that straddles the offset
* is treated as the cursor's char.
*/
function splitTextByCells(
text: string,
cellOffset: number,
): { before: string; atCursor: string; after: string } {
let cells = 0;
for (let i = 0; i < text.length; i++) {
const ch = text[i]!;
const cw = charCellsForText(ch);
if (cells === cellOffset) {
return { before: text.slice(0, i), atCursor: ch, after: text.slice(i + 1) };
}
if (cells + cw > cellOffset) {
// The wide char straddles the offset — show it as the cursor char.
return { before: text.slice(0, i), atCursor: ch, after: text.slice(i + 1) };
}
cells += cw;
}
// Cursor at end of text.
return { before: text, atCursor: "", after: "" };
}
/**
* Local cell-counting helper — duplicates `charCells` from
* prompt-viewport but inlined to avoid a back-and-forth import (this
* function is hot per-keystroke). Keep in sync.
*/
function charCellsForText(ch: string): number {
const code = ch.charCodeAt(0);
if (code < 0x20 || code === 0x7f) return 0;
if (code < 0x1100) return 1;
if (code >= 0x1100 && code <= 0x115f) return 2;
if (code >= 0x2e80 && code <= 0x303e) return 2;
if (code >= 0x3041 && code <= 0x33ff) return 2;
if (code >= 0x3400 && code <= 0x4dbf) return 2;
if (code >= 0x4e00 && code <= 0x9fff) return 2;
if (code >= 0xa000 && code <= 0xa4cf) return 2;
if (code >= 0xac00 && code <= 0xd7a3) return 2;
if (code >= 0xf900 && code <= 0xfaff) return 2;
if (code >= 0xfe30 && code <= 0xfe4f) return 2;
if (code >= 0xff00 && code <= 0xff60) return 2;
if (code >= 0xffe0 && code <= 0xffe6) return 2;
return 1;
}
function renderSegment(seg: Segment, key: number, _inverse: boolean): React.ReactNode {
if (seg.kind === "text") {
return <Text key={`s-${key}`}>{seg.text}</Text>;
}
// Paste sentinels render as a fuchsia bg-pill so they're visually
// distinct from typed text — the user can see "this is the
// collapsed paste, not 47 lines of code I typed". Matches the
// bg-pill idiom used elsewhere (mode bars, tool names).
return (
<Text key={`s-${key}`} backgroundColor="#f0abfc" color="black" bold>
{seg.label}
</Text>
);
}
// ── collapse helper (preserved from v1) ────────────────────────────
type RenderItem =
| { kind: "line"; line: string; originalIndex: number }
| { kind: "skip"; linesHidden: number };
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 }));
}
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;
}
+7 -1
View File
@@ -28,12 +28,18 @@ export function RecordView({ rec, compact = false }: RecordViewProps) {
const toolContentMax = compact ? 200 : 400;
if (rec.role === "user") {
// Continuation indent of 6 spaces matches the `you › ` prefix width
// so wrapped multi-line user messages align under the body text
// instead of jumping to column 0.
const content = rec.content.includes("\n")
? rec.content.split("\n").join("\n ")
: rec.content;
return (
<Box marginTop={1}>
<Text bold color="cyan">
you ›{" "}
</Text>
<Text>{rec.content}</Text>
<Text>{content}</Text>
</Box>
);
}
+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 =
+17 -14
View File
@@ -9,8 +9,9 @@
* rendering quirk bundled (`ink-text-input`); adding more is low value.
*/
import { Box, Text, useInput } from "ink";
import { Box, Text } from "ink";
import React, { useState } from "react";
import { useKeystroke } from "./keystroke-context.js";
export interface SelectItem<V extends string = string> {
/** Stable identifier — returned to caller on submit. */
@@ -30,7 +31,7 @@ export interface SingleSelectProps<V extends string> {
onCancel?: () => void;
/**
* Optional footer rendered dim beneath the list, e.g.
* `"↑/↓ navigate · Enter select · Esc cancel"`. Makes keyboard
* `"[↑↓] navigate · [Enter] select · [Esc] cancel"`. Makes keyboard
* affordances discoverable — otherwise new users hit `y`/`n` and
* wonder why nothing happens.
*/
@@ -50,15 +51,16 @@ export function SingleSelect<V extends string>({
);
const [index, setIndex] = useState(initialIndex === -1 ? 0 : initialIndex);
useInput((_input, key) => {
if (key.upArrow) {
useKeystroke((ev) => {
if (ev.paste) return;
if (ev.upArrow) {
setIndex((i) => findNextEnabled(items, i, -1));
} else if (key.downArrow) {
} else if (ev.downArrow) {
setIndex((i) => findNextEnabled(items, i, +1));
} else if (key.return) {
} else if (ev.return) {
const chosen = items[index];
if (chosen && !chosen.disabled) onSubmit(chosen.value);
} else if (key.escape && onCancel) {
} else if (ev.escape && onCancel) {
onCancel();
}
});
@@ -87,7 +89,7 @@ export interface MultiSelectProps<V extends string> {
initialSelected?: V[];
onSubmit: (values: V[]) => void;
onCancel?: () => void;
/** Footer hint under the list — e.g. "space toggle · enter confirm". */
/** Footer hint under the list — e.g. "[Space] toggle · [Enter] confirm". */
footer?: string;
}
@@ -104,12 +106,13 @@ export function MultiSelect<V extends string>({
});
const [selected, setSelected] = useState<Set<V>>(new Set(initialSelected));
useInput((input, key) => {
if (key.upArrow) {
useKeystroke((ev) => {
if (ev.paste) return;
if (ev.upArrow) {
setIndex((i) => findNextEnabled(items, i, -1));
} else if (key.downArrow) {
} else if (ev.downArrow) {
setIndex((i) => findNextEnabled(items, i, +1));
} else if (input === " ") {
} else if (ev.input === " ") {
const item = items[index];
if (!item || item.disabled) return;
setSelected((prev) => {
@@ -118,13 +121,13 @@ export function MultiSelect<V extends string>({
else next.add(item.value);
return next;
});
} else if (key.return) {
} else if (ev.return) {
// Preserve catalog order rather than insertion order, so reruns
// produce the same spec list for the same checkbox set — makes the
// `config.json` diff trivially stable.
const ordered = items.filter((i) => selected.has(i.value)).map((i) => i.value);
onSubmit(ordered);
} else if (key.escape && onCancel) {
} else if (ev.escape && onCancel) {
onCancel();
}
});
+1 -1
View File
@@ -48,7 +48,7 @@ export function SessionPicker({
onSubmit={(v) => onChoose(v as SessionChoice)}
/>
<Box marginTop={1}>
<Text dimColor>↑↓ to move · Enter to pick</Text>
<Text dimColor>[↑↓] navigate · [Enter] select</Text>
</Box>
</Box>
);
+47 -42
View File
@@ -1,5 +1,6 @@
import { Box, Text } from "ink";
import React from "react";
import { ModalCard } from "./ModalCard.js";
import { SingleSelect } from "./Select.js";
export type ShellConfirmChoice = "run_once" | "always_allow" | "deny";
@@ -11,6 +12,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,51 +33,48 @@ 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";
const subtitle = isBackground
? "long-running process — keeps running after approval, /kill to stop"
: "model wants to run a shell command";
return (
<Box flexDirection="column" borderStyle="round" borderColor="yellow" paddingX={1} marginY={1}>
<Box>
<Text bold color="yellow">
▸ model wants to run a shell command
<ModalCard
accent="#f87171"
icon={isBackground ? "⏱" : "⚡"}
title={isBackground ? "background process" : "shell command"}
subtitle={subtitle}
>
<Box marginBottom={1}>
<Text dimColor>{"$ "}</Text>
<Text color="#67e8f9" bold>
{command}
</Text>
</Box>
<Box>
<Text color="yellow" dimColor>
{"──────────────────────────────────────────"}
</Text>
</Box>
<Box marginTop={1}>
<Text>
<Text dimColor>{"$ "}</Text>
<Text color="cyan">{command}</Text>
</Text>
</Box>
<Box marginTop={1}>
<SingleSelect
initialValue="run_once"
items={[
{
value: "run_once",
label: "Run once",
hint: "Execute this command, don't remember it.",
},
{
value: "always_allow",
label: `Always allow "${allowPrefix}" in this project`,
hint: "Save the prefix to ~/.reasonix/config.json; future matches auto-run.",
},
{
value: "deny",
label: "Deny",
hint: "Tell the model the user refused; it will continue without this command.",
},
]}
onSubmit={(v) => onChoose(v as ShellConfirmChoice)}
onCancel={() => onChoose("deny")}
footer="[↑↓] navigate · [Enter] select · [Esc] deny"
/>
</Box>
</Box>
<SingleSelect
initialValue="run_once"
items={[
{
value: "run_once",
label: "Run once",
hint: "Execute this command, don't remember it.",
},
{
value: "always_allow",
label: `Always allow "${allowPrefix}" in this project`,
hint: "Save the prefix to ~/.reasonix/config.json; future matches auto-run.",
},
{
value: "deny",
label: "Deny",
hint: "Tell the model the user refused; it will continue without this command.",
},
]}
onSubmit={(v) => onChoose(v as ShellConfirmChoice)}
onCancel={() => onChoose("deny")}
footer="[↑↓] navigate · [Enter] select · [Esc] deny"
/>
</ModalCard>
);
}
+3 -3
View File
@@ -39,7 +39,7 @@ export function SlashArgPicker({
// Hint mode: a single dim row explaining the argsHint + summary.
if (kind === "hint") {
return (
<Box paddingX={1}>
<Box paddingX={1} marginTop={1}>
<Text dimColor>
{" "}
<Text bold>/{spec.cmd}</Text>
@@ -52,7 +52,7 @@ export function SlashArgPicker({
if (matches === null) return null;
if (matches.length === 0) {
return (
<Box flexDirection="column" paddingX={1}>
<Box flexDirection="column" paddingX={1} marginTop={1}>
<Text dimColor>
{" "}
<Text bold>/{spec.cmd}</Text>
@@ -71,7 +71,7 @@ export function SlashArgPicker({
const hiddenAbove = windowStart;
const hiddenBelow = total - windowStart - shown.length;
return (
<Box flexDirection="column" paddingX={1}>
<Box flexDirection="column" paddingX={1} marginTop={1}>
<Text dimColor>
{" "}
<Text bold>/{spec.cmd}</Text>
+8 -14
View File
@@ -28,7 +28,7 @@ export function SlashSuggestions({
if (matches === null) return null;
if (matches.length === 0) {
return (
<Box paddingX={1}>
<Box paddingX={1} marginTop={1}>
<Text color="yellow">no slash command matches that prefix</Text>
<Text dimColor> — Backspace to edit, or /help for the full list</Text>
</Box>
@@ -45,7 +45,7 @@ export function SlashSuggestions({
const hiddenAbove = windowStart;
const hiddenBelow = total - windowStart - shown.length;
return (
<Box flexDirection="column" paddingX={1}>
<Box flexDirection="column" paddingX={1} marginTop={1}>
{hiddenAbove > 0 ? <Text dimColor> ↑ {hiddenAbove} more above</Text> : null}
{shown.map((spec, i) => (
<SuggestionRow key={spec.cmd} spec={spec} isSelected={windowStart + i === selectedIndex} />
@@ -57,29 +57,23 @@ export function SlashSuggestions({
}
function SuggestionRow({ spec, isSelected }: { spec: SlashCommandSpec; isSelected: boolean }) {
const marker = isSelected ? "▸" : " ";
const name = `/${spec.cmd}`;
const argsSuffix = spec.argsHint ? ` ${spec.argsHint}` : "";
// Selected row gets full cyan coloring so it pops out against the
// dimmed others — mirrors the style GitHub Issues / Discord use
// for focused dropdown rows.
// Selected row gets a solid-bg highlight (cyan) so it pops like
// an editor's focused autocomplete entry. Non-selected rows stay
// dim with a leading bullet for vertical rhythm.
if (isSelected) {
return (
<Box>
<Text bold color="cyan">
{marker} {name.padEnd(12)}
{argsSuffix.padEnd(16)}
<Text backgroundColor="#67e8f9" color="black" bold>
{` ▸ ${name.padEnd(12)}${argsSuffix.padEnd(16)} ${spec.summary} `}
</Text>
<Text color="cyan"> {spec.summary}</Text>
</Box>
);
}
return (
<Box>
<Text dimColor>
{marker} {name.padEnd(12)}
{argsSuffix.padEnd(16)} {spec.summary}
</Text>
<Text color="#94a3b8">{` ${name.padEnd(12)}${argsSuffix.padEnd(16)} ${spec.summary}`}</Text>
</Box>
);
}
+232 -82
View File
@@ -1,49 +1,49 @@
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";
import { useTick } from "./ticker.js";
import { COLOR, GRADIENT } from "./theme.js";
const WORDMARK_LETTERS: ReadonlyArray<string> = ["R", "E", "A", "S", "O", "N", "I", "X"];
/**
* Cyan → blue → purple truecolor gradient for the REASONIX wordmark.
* Each char gets its own hex color — terminals that support 24-bit
* color (nearly all since 2016) render this as a smooth fade. Older
* 256-color terminals snap to nearest; 8-color fall all the way back
* to plain cyan via Ink's color pipeline, so the worst case is still
* legible.
* Gradient-flowing wordmark. Every tick the gradient shifts one
* position so the colors visibly travel across the letters — like
* a neon sign. Brand mark `◈` rides the same flow but also pulses
* bold on/off (slow when idle, fast when busy) so a glance at the
* top of the screen tells you whether the app is thinking.
*
* Tick is ~120 ms. `rotateEvery=4` ticks → one shift every ~480 ms
* idle, ~240 ms when busy. Slow enough to be ambient, fast enough
* to feel alive. Truecolor terminals get the smooth flow; 8-color
* fallbacks just see all-cyan, which is still legible.
*/
const WORDMARK_STYLES: ReadonlyArray<{ ch: string; color: string; isLogo: boolean }> = [
{ ch: "◈", color: "#5eead4", isLogo: true }, // teal — brand mark
{ ch: " ", color: "#5eead4", isLogo: false },
{ ch: "R", color: "#67e8f9", isLogo: false }, // cyan
{ ch: "E", color: "#7dd3fc", isLogo: false }, // sky
{ ch: "A", color: "#93c5fd", isLogo: false }, // blue
{ ch: "S", color: "#a5b4fc", isLogo: false }, // indigo
{ ch: "O", color: "#c4b5fd", isLogo: false }, // violet
{ ch: "N", color: "#d8b4fe", isLogo: false }, // purple
{ ch: "I", color: "#f0abfc", isLogo: false }, // fuchsia
{ ch: "X", color: "#f0abfc", isLogo: false }, // fuchsia
];
/**
* Gradient-filled, animated app wordmark. The `◈` brand mark breathes
* (bold on/off) once every ~1.6s when idle, ~600ms when the model is
* working, so a glance at the top of the screen tells you immediately
* whether the app is doing something. Letters' keys use the char+color
* pair (not an index) so React state attaches to the glyph itself;
* fine because WORDMARK_STYLES never reorders.
*/
function Wordmark({ busy }: { busy: boolean }) {
const tick = useTick();
// Slow pulse = 12 ticks (~1.4s). Busy pulse = 5 ticks (~600ms).
const period = busy ? 5 : 12;
const bright = Math.floor(tick / period) % 2 === 0;
function Wordmark({
busy: _busy,
animate: _animate,
}: {
busy: boolean;
animate: boolean;
}) {
// Static gradient. The brand sweep teal → fuchsia is precomputed
// once per render — no useTick subscription, no per-tick
// re-render. Earlier versions flowed the colors over time, but
// the per-tick re-render interleaved badly with terminal resize
// (Ink's eraseLines misjudges row count when bars / wide text
// wrap, ghost frames stack). Keeping this static eliminates the
// multiplier; resize artifacts at most leave a single stale
// frame instead of N.
return (
<Text>
{WORDMARK_STYLES.map((c) => (
<Text key={`${c.ch}-${c.color}`} color={c.color} bold={c.isLogo ? bright : true}>
{c.ch}
<Text color={GRADIENT[0]} bold>
◈
</Text>
<Text> </Text>
{WORDMARK_LETTERS.map((letter, i) => (
<Text key={letter} color={GRADIENT[i % GRADIENT.length]} bold>
{letter}
</Text>
))}
</Text>
@@ -56,6 +56,13 @@ export interface StatsPanelProps {
prefixHash: string;
harvestOn?: boolean;
branchBudget?: number;
/**
* Current `reasoning_effort` cap. Shown as a green "· max" / yellow
* "· high" tag in the header so the user always sees which tier the
* next turn will use. Absent/undefined hides the tag (e.g. before
* the loop is constructed).
*/
reasoningEffort?: "high" | "max";
/**
* True when `reasonix code` is currently running in read-only Plan
* Mode. Surfaced as a red "PLAN" tag in the panel header so the user
@@ -63,6 +70,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
@@ -85,6 +98,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;
}
/**
@@ -110,10 +136,14 @@ export function StatsPanel({
prefixHash,
harvestOn,
branchBudget,
reasoningEffort,
planMode,
editMode,
balance,
updateAvailable,
busy,
proArmed,
escalated,
}: StatsPanelProps) {
const branchOn = (branchBudget ?? 1) > 1;
const ctxMax = DEEPSEEK_CONTEXT_TOKENS[model] ?? DEFAULT_CONTEXT_TOKENS;
@@ -127,19 +157,32 @@ export function StatsPanel({
// actually had a chance to build, we flip to the live gradient.
const coldStart = summary.turns <= COLD_START_TURNS;
// No gradient bars, no animation. Earlier versions had truecolor
// gradient rules top+bottom and a tick-driven wordmark/bar flow,
// but those are exactly the elements Ink's eraseLines miscounts
// on resize: ~100-char gradient strings wrap 2-3 visual rows at
// narrow widths, the per-tick re-render writes new frames before
// the stale rows are erased, and ghost panels stack vertically
// (the user-reported "刷屏" / multi-frame artifact). Fixed-row
// panel + no per-tick churn keeps Ink's row math honest.
return (
<Box borderStyle="round" borderColor="cyan" flexDirection="column" paddingX={1}>
<Box flexDirection="column" paddingX={1} marginBottom={1}>
<Header
model={model}
prefixHash={prefixHash}
harvestOn={harvestOn}
branchOn={branchOn}
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}
animate={false}
/>
{narrow ? (
<StackedMetrics
@@ -168,54 +211,121 @@ function Header({
harvestOn,
branchOn,
branchBudget,
reasoningEffort,
planMode,
editMode,
turns,
updateAvailable,
narrow,
busy,
proArmed,
escalated,
animate,
}: {
model: string;
prefixHash: string;
harvestOn?: boolean;
branchOn: boolean;
branchBudget: number;
reasoningEffort?: "high" | "max";
planMode?: boolean;
editMode?: EditMode;
turns: number;
updateAvailable?: string | null;
narrow: boolean;
busy: boolean;
proArmed: boolean;
escalated: boolean;
/** When false, suppress optional pills + animation to avoid wraps. */
animate: boolean;
}) {
// Mode pill — pick the most informative one to surface in the
// header. PLAN beats AUTO/review beats nothing. Pro armed/escalated
// gets its own pill alongside.
const modePill = planMode
? { label: "PLAN", bg: "red" as const }
: editMode === "auto"
? { label: "AUTO", bg: "magenta" as const }
: editMode === "review"
? { label: "REVIEW", bg: "cyan" as const }
: null;
const proPill = escalated
? { label: "⇧ PRO", bg: "red" as const }
: proArmed
? { label: "⇧ PRO", bg: "yellow" as const }
: null;
// Narrow / non-animate mode hides the secondary pills (harvest,
// branch, reasoning effort) so the header always fits on one
// visual row. Wrapping the header is the main amplifier of the
// eraseLines miscount that produces the "screen flashing" effect.
const showSecondary = animate && !narrow;
return (
<Box justifyContent="space-between">
<Box>
<Wordmark busy={busy} />
<Text dimColor>{` v${VERSION}`}</Text>
<Text dimColor> · </Text>
<Text color="yellow">{model}</Text>
{narrow ? null : (
<Wordmark busy={busy} animate={animate} />
<Text dimColor>{` ${VERSION}`}</Text>
<Text dimColor>{" "}</Text>
<Text color="yellow" bold>
{model.replace(/^deepseek-/, "")}
</Text>
{modePill ? (
<>
<Text dimColor> · </Text>
<Text dimColor>{prefixHash}</Text>
<Text>{" "}</Text>
<Pill label={modePill.label} bg={modePill.bg} />
</>
)}
{harvestOn ? <Text color="magenta"> · harvest</Text> : null}
{branchOn ? <Text color="blue"> · branch{branchBudget}</Text> : null}
{planMode ? (
<Text color="red" bold>
{" · PLAN"}
) : null}
{proPill ? (
<>
<Text>{" "}</Text>
<Pill label={proPill.label} bg={proPill.bg} />
</>
) : null}
{showSecondary && harvestOn ? (
<Text dimColor>
<Text>{" "}</Text>
<Text color="magenta">harvest</Text>
</Text>
) : null}
{showSecondary && branchOn ? (
<Text dimColor>
<Text>{" "}</Text>
<Text color="blue">{`branch×${branchBudget}`}</Text>
</Text>
) : null}
{showSecondary && reasoningEffort === "max" ? (
<>
<Text>{" "}</Text>
<Text color="green" dimColor>
max
</Text>
</>
) : null}
{showSecondary && reasoningEffort === "high" ? (
<>
<Text>{" "}</Text>
<Text color="yellow" dimColor>
high
</Text>
</>
) : null}
</Box>
<Text>
{updateAvailable ? (
<Text color="yellow" bold>{`update: ${updateAvailable} · `}</Text>
) : null}
<Text dimColor>{narrow ? `turn ${turns}` : `turn ${turns} · /help`}</Text>
{updateAvailable ? <Text color="yellow" bold>{`↑ ${updateAvailable} `}</Text> : null}
<Text dimColor>{narrow ? `t${turns}` : `turn ${turns} · /help`}</Text>
</Text>
</Box>
);
}
/** Solid-background tag, used for primary mode + pro indicators. */
function Pill({ label, bg }: { label: string; bg: "red" | "magenta" | "cyan" | "yellow" }) {
return (
<Text backgroundColor={bg} color="white" bold>
{` ${label} `}
</Text>
);
}
/**
* Wide-terminal layout (≥120 cols): single metrics row. Matches the
* original panel, just with calmer spacing and the cold-start
@@ -292,24 +402,26 @@ function ContextCell({
if (promptTokens === 0) {
return (
<Text>
<Text dimColor>ctx </Text>
<Text color={COLOR.info} dimColor>
{"▣ ctx "}
</Text>
<Text dimColor>— (no turns yet)</Text>
</Text>
);
}
const color = ratio >= 0.8 ? "red" : ratio >= 0.6 ? "yellow" : "green";
const color = ratio >= 0.8 ? COLOR.err : ratio >= 0.6 ? COLOR.warn : COLOR.ok;
const pct = Math.round(ratio * 100);
return (
<Text>
<Text dimColor>ctx </Text>
{showBar ? <Bar ratio={ratio} color={color} /> : null}
{showBar ? <Text> </Text> : null}
<Text color={COLOR.info}>{"▣ ctx "}</Text>
<Bar ratio={ratio} color={color} cells={showBar ? 14 : 10} />
<Text> </Text>
<Text color={color} bold>
{formatTokens(promptTokens)}/{formatTokens(ctxMax)}
</Text>
<Text dimColor> ({pct}%)</Text>
{ratio >= 0.8 ? (
<Text color="red" bold>
<Text color={COLOR.err} bold>
{" · /compact"}
</Text>
) : null}
@@ -330,7 +442,9 @@ function CacheCell({
if (turns === 0) {
return (
<Text>
<Text dimColor>cache </Text>
<Text color={COLOR.info} dimColor>
{"⌬ cache "}
</Text>
<Text dimColor>—</Text>
</Text>
);
@@ -338,7 +452,9 @@ function CacheCell({
if (coldStart) {
return (
<Text>
<Text dimColor>cache </Text>
<Text color={COLOR.info} dimColor>
{"⌬ cache "}
</Text>
<Text dimColor>{pct}% </Text>
<Text dimColor italic>
(cold start)
@@ -346,10 +462,10 @@ function CacheCell({
</Text>
);
}
const color = hitRatio >= 0.7 ? "green" : hitRatio >= 0.4 ? "yellow" : "red";
const color = hitRatio >= 0.7 ? COLOR.ok : hitRatio >= 0.4 ? COLOR.warn : COLOR.err;
return (
<Text>
<Text dimColor>cache </Text>
<Text color={COLOR.info}>{"⌬ cache "}</Text>
<Text color={color} bold>
{pct}%
</Text>
@@ -357,6 +473,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): string | undefined {
if (cost <= 0) return undefined;
if (cost >= 0.2) return COLOR.err;
if (cost >= 0.05) return COLOR.warn;
return COLOR.ok;
}
function sessionCostColor(cost: number): string | undefined {
if (cost <= 0) return undefined;
if (cost >= 5) return COLOR.err;
if (cost >= 0.5) return COLOR.warn;
return COLOR.ok;
}
function CostCell({
summary,
coldStart,
@@ -367,7 +501,9 @@ function CostCell({
if (summary.turns === 0) {
return (
<Text>
<Text dimColor>cost </Text>
<Text color={COLOR.info} dimColor>
{"◴ cost "}
</Text>
<Text dimColor>—</Text>
</Text>
);
@@ -376,27 +512,27 @@ 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 color={COLOR.info}>{"◴ 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>
);
}
function BalanceCell({ balance }: { balance: { currency: string; total: number } }) {
const color = balance.total < 1 ? "red" : balance.total < 5 ? "yellow" : "green";
const color = balance.total < 1 ? COLOR.err : balance.total < 5 ? COLOR.warn : COLOR.ok;
return (
<Text>
<Text dimColor>balance </Text>
<Text color={COLOR.info}>{"◐ balance "}</Text>
<Text color={color} bold>
{balance.currency === "USD" ? "$" : ""}
{balance.total.toFixed(2)}
@@ -407,15 +543,29 @@ function BalanceCell({ balance }: { balance: { currency: string; total: number }
}
/**
* Unicode progress bar for the narrow layout's context cell. 10 cells
* wide — narrow terminals are already cramped, and the bar is just a
* visual cue for the percentage next to it, not the primary readout.
* Truecolor progress bar. Filled cells use the threshold color (green
* → amber → rose) so the bar communicates pressure at a glance;
* empty cells use a dim shade so the empty portion is visible
* without dominating. ▰/▱ have distinct shapes (filled vs hollow)
* so the boundary is clear even when colors snap to 8-color slots
* on legacy terminals.
*/
function Bar({ ratio, color }: { ratio: number; color: "green" | "yellow" | "red" }) {
const cells = 10;
function Bar({
ratio,
color,
cells = 14,
}: {
ratio: number;
color: string;
cells?: number;
}) {
const filled = Math.max(0, Math.min(cells, Math.round(ratio * cells)));
const bar = "█".repeat(filled) + "░".repeat(cells - filled);
return <Text color={color}>{bar}</Text>;
return (
<Text>
<Text color={color}>{"▰".repeat(filled)}</Text>
<Text dimColor>{"▱".repeat(cells - filled)}</Text>
</Text>
);
}
/**
+113
View File
@@ -0,0 +1,113 @@
/**
* Welcome card on the empty session. The first thing a user sees
* after launching `reasonix code` — needs to communicate, in the
* ~5 seconds before they type, three things: brand, what to type,
* how to escape. Card framing uses a gradient top rule + left-side
* accent bar + sectioned hints so it reads as a designed surface
* rather than a bare list. No bordered Boxes — those amplified
* Ink's Windows eraseLines miscount.
*/
import { Box, Text, useStdout } from "ink";
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React in value scope
import React from "react";
import { COLOR, gradientCells } from "./theme.js";
export interface WelcomeBannerProps {
/** True when running `reasonix code`. Surfaces code-mode hints. */
inCodeMode?: boolean;
}
export function WelcomeBanner({ inCodeMode }: WelcomeBannerProps): React.ReactElement {
const { stdout } = useStdout();
const cols = stdout?.columns ?? 80;
const ruleWidth = Math.min(60, Math.max(28, cols - 4));
return (
<Box flexDirection="column" paddingX={1} marginY={1}>
<GradientRule width={ruleWidth} />
<BarRow>
<Text bold color={COLOR.brand}>
◈ welcome
</Text>
<Text dimColor>{" · type a message to start"}</Text>
</BarRow>
<BarRow />
<BarRow>
<Text bold color={COLOR.primary}>
quick start
</Text>
</BarRow>
<Hint cmd="/help" desc="every command + keyboard shortcut" />
<Hint cmd="/skill" desc="invoke a stored playbook" />
{inCodeMode ? (
<>
<Hint cmd="@path" desc="inline a file in your message" />
<Hint cmd="!cmd" desc="run a shell command, output goes to context" />
</>
) : null}
<Hint cmd="/exit" desc="quit (Ctrl+C also works)" />
<BarRow />
<BarRow>
<Text dimColor italic>
tip:
</Text>
<Text dimColor>{" Ctrl+J inserts a newline · trailing \\ also continues"}</Text>
</BarRow>
<Box marginTop={1}>
<GradientRule width={ruleWidth} thin />
</Box>
</Box>
);
}
/**
* One-line gradient rule. `thin` swaps the half-block top/bottom so
* the top of the card reads as a "header band" (▄ — bottom-half
* filled) and the bottom as "section close" (▁ — minimal pixel
* row). Same primitive the StatsPanel uses, kept consistent.
*/
function GradientRule({ width, thin }: { width: number; thin?: boolean }) {
const cells = gradientCells(width, thin ? "▁" : "▄");
return (
<Box>
{cells.map((c, i) => (
// biome-ignore lint/suspicious/noArrayIndexKey: fixed-width gradient row, never reordered
<Text key={`wrule-${i}`} color={c.color}>
{c.ch}
</Text>
))}
</Box>
);
}
/**
* Card row — left-side accent bar followed by content. Children
* optional so we can use this for blank spacer rows (bar only).
*/
function BarRow({ children }: { children?: React.ReactNode }) {
return (
<Box>
<Text color={COLOR.brand} bold>
▎
</Text>
<Text> </Text>
{children}
</Box>
);
}
/**
* Single hint row — bold accent cmd token + dim description.
* Padded so all cmd tokens line up regardless of length, like a
* man-page synopsis.
*/
function Hint({ cmd, desc }: { cmd: string; desc: string }) {
return (
<BarRow>
<Text bold color={COLOR.accent}>
{cmd.padEnd(8)}
</Text>
<Text dimColor>{` ${desc}`}</Text>
</BarRow>
);
}
+4 -4
View File
@@ -97,7 +97,7 @@ export function Wizard({ onComplete, onCancel, existingApiKey, initial }: Wizard
}}
/>
<Box marginTop={1}>
<Text dimColor>↑/↓ move · enter confirm · esc cancel</Text>
<Text dimColor>[↑↓] navigate · [Enter] confirm · [Esc] cancel</Text>
</Box>
</StepFrame>
);
@@ -115,7 +115,7 @@ export function Wizard({ onComplete, onCancel, existingApiKey, initial }: Wizard
const needsArgs = selected.some((name) => CATALOG_BY_NAME.get(name)?.userArgs);
setStep(needsArgs ? "mcpArgs" : "review");
}}
footer="↑/↓ move · space toggle · enter confirm · esc cancel · leave empty to skip"
footer="[↑↓] navigate · [Space] toggle · [Enter] confirm · [Esc] cancel · empty = skip"
/>
</StepFrame>
);
@@ -174,7 +174,7 @@ export function Wizard({ onComplete, onCancel, existingApiKey, initial }: Wizard
</Box>
) : null}
<Box marginTop={1}>
<Text dimColor>enter save · esc cancel</Text>
<Text dimColor>[Enter] save · [Esc] cancel</Text>
</Box>
</Box>
<ReviewConfirm
@@ -213,7 +213,7 @@ export function Wizard({ onComplete, onCancel, existingApiKey, initial }: Wizard
<Text>Run `reasonix` any time to start chatting — your settings are remembered.</Text>
</Box>
<Box marginTop={1}>
<Text dimColor>Press enter to exit.</Text>
<Text dimColor>[Enter] to exit</Text>
</Box>
<ExitOnEnter onExit={exit} />
</Box>
+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(", ")}` : "";
}
+144
View File
@@ -0,0 +1,144 @@
/**
* CSI sequence recovery for Ink's `useInput`.
*
* Why this exists. Ink delivers keyboard events through `parse-keypress`,
* which reads stdin and recognises ANSI control-sequence-introducer
* (CSI) sequences with a state machine plus a short timeout. On most
* terminals this works: the byte stream `\x1b [ A` arrives in one
* read, parse-keypress emits `{key.upArrow:true, input:""}`, life is
* good.
*
* On Windows PowerShell + ConPTY (and a handful of embedded shells)
* the bytes don't always arrive together. parse-keypress's timeout
* expires between chunks, so it dispatches the lone `\x1b` as
* `key.escape:true` and then dispatches the trailing `[A` as a
* regular character event — `input:"[A", key.upArrow:undefined`. The
* useInput consumer sees `[A` as plain text, inserts it into the
* buffer, and the cursor never moves. Same shape on `[C` (right
* arrow), `[Z` (Shift+Tab), `[5~` (PgUp), `[201~` (bracketed-paste
* end), etc.
*
* Every Reasonix UI component that calls `useInput` is exposed to
* this. Patching each one to re-recognise the bare CSI tail was
* fragile — every release a new symptom appeared (cursor stuck,
* paste markers leaking, Shift+Tab not toggling). So this module is
* the single source of truth for CSI recovery: every input handler
* runs the raw event through `recoverCsiTail` before reading
* structured key flags.
*
* Recovery is conservative. We only rewrite when:
* 1. None of the structured key flags Ink already populated for
* this event is set (so a real upArrow press isn't second-
* guessed).
* 2. `input` exactly matches a recognised tail in either form —
* the full `\x1b[X` sequence (in case the timeout merged it)
* or the bare `[X` ConPTY-stripped variant.
*
* Anything else passes through unchanged.
*/
/**
* Subset of Ink's `Key` interface that contains the structured flags
* we know how to recover. Optional everywhere because callers from
* different Ink versions may not populate every field.
*/
export interface CsiKeyFlags {
upArrow?: boolean;
downArrow?: boolean;
leftArrow?: boolean;
rightArrow?: boolean;
pageUp?: boolean;
pageDown?: boolean;
delete?: boolean;
shift?: boolean;
tab?: boolean;
}
/**
* CSI tails we recognise. Each maps the printable bytes of a CSI
* tail (the part after the `\x1b`) to the structured key flags they
* should set. Bracketed-paste markers `[200~` / `[201~` are
* intentionally absent — they're handled by PromptInput's paste
* accumulator, which has different semantics (collect content
* between markers rather than emit one keystroke).
*/
const CSI_TAIL_TO_FLAGS: ReadonlyArray<{ tail: string; flags: CsiKeyFlags }> = [
// Arrow keys — the most common ConPTY victim.
{ tail: "[A", flags: { upArrow: true } },
{ tail: "[B", flags: { downArrow: true } },
{ tail: "[C", flags: { rightArrow: true } },
{ tail: "[D", flags: { leftArrow: true } },
// Page navigation.
{ tail: "[5~", flags: { pageUp: true } },
{ tail: "[6~", flags: { pageDown: true } },
// Forward-delete (the key labelled Delete on most keyboards).
{ tail: "[3~", flags: { delete: true } },
// Shift+Tab — terminal sends `\x1b[Z` rather than tab-with-shift.
{ tail: "[Z", flags: { shift: true, tab: true } },
];
/**
* Did Ink already give us a structured key for this event? When
* `true`, recovery is unnecessary and would risk overriding a real
* keypress that happens to share `input` with a CSI tail.
*/
function alreadyStructured(flags: CsiKeyFlags): boolean {
return Boolean(
flags.upArrow ||
flags.downArrow ||
flags.leftArrow ||
flags.rightArrow ||
flags.pageUp ||
flags.pageDown ||
flags.delete ||
(flags.tab && flags.shift),
);
}
/**
* If `input` is a recognisable CSI tail (with or without the leading
* `\x1b`), return the structured flags it should produce. Otherwise
* `null`. Bracketed-paste markers always return `null` here — those
* are handled by their own accumulator.
*
* Pure function. Pass already-structured events through (they
* short-circuit) so a real arrow press doesn't get rewritten.
*/
export function recoverCsiTail(input: string, existing: CsiKeyFlags = {}): CsiKeyFlags | null {
if (alreadyStructured(existing)) return null;
for (const entry of CSI_TAIL_TO_FLAGS) {
if (input === entry.tail || input === `\x1b${entry.tail}`) {
return entry.flags;
}
}
return null;
}
/**
* Tail forms (with and without the leading `\x1b`) that should never
* end up as literal text in a user's prompt buffer. Used as a final
* defensive pass before treating input as printable — if a CSI
* fragment slipped past structured-key recovery (e.g. arrived
* embedded inside a paste burst), at least drop the raw bytes
* rather than insert them as garbage text.
*
* Includes the bracketed-paste markers `[200~` / `[201~` because a
* paste whose start/end markers got chunked across reads can leave
* those bytes in the printable input.
*/
export const STRIPPABLE_CSI_FRAGMENTS: readonly string[] = [
"\u001b[200~",
"\u001b[201~",
"[200~",
"[201~",
...CSI_TAIL_TO_FLAGS.flatMap((e) => [`\u001b${e.tail}`, e.tail]),
];
/** Remove every recognised CSI fragment from a string. */
export function stripCsiFragments(input: string): string {
let out = input;
for (const frag of STRIPPABLE_CSI_FRAGMENTS) {
if (out.includes(frag)) out = out.replaceAll(frag, "");
}
return out;
}
+120
View File
@@ -0,0 +1,120 @@
/**
* KeystrokeContext — React surface in front of the raw stdin reader.
*
* Replaces Ink's `useInput` chain. Reasonix's components no longer
* import `useInput` from "ink"; they call `useKeystroke(handler,
* isActive)` from this module. The provider mounted once at App
* level owns a `StdinReader`, subscribes a single fan-out function
* to it, and dispatches each parsed `KeyEvent` to every active
* consumer.
*
* Why a Context instead of a singleton import: the provider can be
* disabled in tests / replay mode without touching the components,
* and the lifecycle (start/stop on mount/unmount) is tied to the
* React tree rather than a global side effect.
*
* Why not just keep Ink's useInput: Ink's parse-keypress uses a
* 100 ms intra-CSI timeout that's too short for Windows ConPTY,
* leaking arrow-key bytes / paste markers into the buffer. Our
* reader uses 250 ms and recognises the ESC-stripped variants too
* — see `stdin-reader.ts`.
*/
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React as a runtime value
import React, { createContext, useContext, useEffect, useRef } from "react";
import { type KeyEvent, type StdinReader, getStdinReader } from "./stdin-reader.js";
interface KeystrokeBus {
/** Subscribe — returns an unsubscribe function. */
subscribe(handler: KeystrokeHandler): () => void;
}
export type KeystrokeHandler = (ev: KeyEvent) => void;
const KeystrokeContext = createContext<KeystrokeBus | null>(null);
export interface KeystrokeProviderProps {
children: React.ReactNode;
/**
* Optional reader override. Tests inject a synthetic reader so
* they can `feed()` chunks instead of touching real stdin. Production
* callers leave this unset and get the singleton.
*/
reader?: StdinReader;
}
export function KeystrokeProvider({
children,
reader: providedReader,
}: KeystrokeProviderProps): React.ReactElement {
const handlersRef = useRef<Set<KeystrokeHandler>>(new Set());
// Ref so the bus value's identity is stable across re-renders —
// consumers don't accidentally re-subscribe every render.
const busRef = useRef<KeystrokeBus | null>(null);
if (busRef.current === null) {
busRef.current = {
subscribe(handler) {
handlersRef.current.add(handler);
return () => {
handlersRef.current.delete(handler);
};
},
};
}
useEffect(() => {
const reader = providedReader ?? getStdinReader();
reader.start();
const unsubscribe = reader.subscribe((ev) => {
// Snapshot the handler set so handlers added/removed during
// dispatch don't perturb iteration. Cheap — typical N=1-3.
for (const fn of [...handlersRef.current]) fn(ev);
});
return () => {
unsubscribe();
// Don't `stop()` the singleton on every unmount — multiple
// mounts (test reruns, hot-reload) must not tear down stdin.
// The singleton's own start() is idempotent; stop() is the
// process-exit handler's job.
};
}, [providedReader]);
return <KeystrokeContext.Provider value={busRef.current}>{children}</KeystrokeContext.Provider>;
}
/**
* Subscribe to keystroke events. Mirrors Ink's `useInput` shape —
* `handler(ev)` runs on every event while `isActive` is truthy
* (default true). Set `isActive=false` to suspend the handler
* (e.g. while a modal is up and shouldn't respond to global keys).
*
* Handler identity changes are tolerated — we re-subscribe via
* useEffect on every render. Wrap your handler in `useCallback` if
* you want to avoid that.
*/
export function useKeystroke(handler: KeystrokeHandler, isActive = true): void {
const bus = useContext(KeystrokeContext);
// Latest-handler ref so we can subscribe ONCE per active toggle
// and still call the freshest closure on each event.
const handlerRef = useRef(handler);
handlerRef.current = handler;
useEffect(() => {
if (!bus || !isActive) return undefined;
return bus.subscribe((ev) => handlerRef.current(ev));
}, [bus, isActive]);
}
/**
* Lower-level hook for components that need a stable subscription
* across the lifetime of the consumer (typically StdinReader-aware
* unit tests).
*/
export function useKeystrokeBus(): KeystrokeBus | null {
return useContext(KeystrokeContext);
}
/** Test helper — assemble a KeyEvent with sensible defaults. */
export function makeKeyEvent(overrides: Partial<KeyEvent> = {}): KeyEvent {
return { input: "", ...overrides };
}
+678 -65
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
@@ -192,6 +385,28 @@ export function parseCitationUrl(url: string): CitationParts | null {
return { path: trimmed };
}
/**
* Common typo-equivalents per file extension. When the model cites
* `foo.ts` but the real file is `foo.tsx`, the validator still
* resolves it via this map. Symmetric pairs (`.ts` ↔ `.tsx`,
* `.js` ↔ `.jsx`, etc.) keep both directions working.
*/
const SIBLING_EXTENSIONS = new Map<string, ReadonlyArray<string>>([
[".ts", [".tsx", ".mts", ".cts"]],
[".tsx", [".ts"]],
[".js", [".jsx", ".mjs", ".cjs"]],
[".jsx", [".js"]],
[".mjs", [".js", ".cjs"]],
[".cjs", [".js", ".mjs"]],
[".mts", [".ts"]],
[".cts", [".ts"]],
]);
function extOf(p: string): string {
const m = /\.[^./\\]+$/.exec(p);
return m ? m[0] : "";
}
export function validateCitation(url: string, projectRoot: string): CitationStatus {
const parts = parseCitationUrl(url);
if (!parts || !parts.path) return { ok: false, reason: "empty path" };
@@ -203,13 +418,30 @@ export function validateCitation(url: string, projectRoot: string): CitationStat
// absolute references like `/etc/hosts` in a code citation are vanishingly
// rare — if anyone needs one we can revisit.
const normalized = parts.path.replace(/^[/\\]+/, "");
const fullPath = isAbsolute(normalized) ? normalized : join(projectRoot, normalized);
let stat: ReturnType<typeof statSync>;
try {
stat = statSync(fullPath);
} catch {
return { ok: false, reason: "file not found" };
const baseFullPath = isAbsolute(normalized) ? normalized : join(projectRoot, normalized);
// Sibling-extension fallback: models routinely cite `foo.ts` when
// the actual file is `foo.tsx` (or `.js`/`.jsx`/`.mjs`/`.cjs`).
// The citation is the model's intent — it's right about WHICH
// file, just typed the wrong extension. Probing siblings keeps a
// genuinely missing path flagged while letting `.ts`↔`.tsx` slip
// through silently.
const siblings = SIBLING_EXTENSIONS.get(extOf(baseFullPath)) ?? [];
const candidates = [
baseFullPath,
...siblings.map((ext) => baseFullPath.replace(/\.[^./\\]+$/, ext)),
];
let fullPath = baseFullPath;
let stat: ReturnType<typeof statSync> | null = null;
for (const candidate of candidates) {
try {
stat = statSync(candidate);
fullPath = candidate;
break;
} catch {
// try next candidate
}
}
if (!stat) return { ok: false, reason: "file not found" };
if (!stat.isFile()) return { ok: false, reason: "not a file" };
if (parts.startLine === undefined) return { ok: true };
let lineCount: number;
@@ -229,11 +461,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 +498,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 +522,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 +543,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 +577,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 +646,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 +696,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 +763,7 @@ type Block =
| ParagraphBlock
| HeadingBlock
| BulletBlock
| BlockquoteBlock
| CodeBlock
| HrBlock
| EditBlockView
@@ -444,7 +772,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 +789,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 +819,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 +847,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 +1003,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 +1042,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 +1053,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,33 +1075,52 @@ 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":
return (
<Text bold color="cyan">
<InlineMd text={block.text} citations={citations} />
</Text>
);
return <HeadingView level={block.level} text={block.text} citations={citations} />;
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":
return (
<Box borderStyle="single" borderColor="gray" paddingX={1}>
<Text color="yellow">{block.text}</Text>
</Box>
);
if (DIAGRAM_LANGS.has(block.lang.toLowerCase())) {
return <DiagramCodeBlock lang={block.lang} text={block.text} />;
}
return <CodeBlockView lang={block.lang} text={block.text} />;
case "edit-block":
return <EditBlockRow block={block} />;
case "table":
@@ -734,6 +1130,82 @@ 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="#c4b5fd"
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 +1347,149 @@ 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.
*/
/**
* Heading renderer. Three tiers of solid-bg pill (cyan / violet /
* fuchsia, walking down the brand gradient) so the heading tree is
* scannable at a glance. H4+ collapses to bold accent text with a
* leading ▸ marker — four pills stacked would visually overwhelm
* the body, and headings rarely go that deep in answers anyway.
*
* Markdown sigils (#, ##, ###) are NEVER rendered literally inside
* the pill: showing `### 标题` defeats the whole "this is a heading"
* semantic. The sigil count goes into the pill's BG color choice;
* the title text stands on its own.
*/
function HeadingView({
level,
text,
citations,
}: {
level: number;
text: string;
citations?: CitationMap;
}) {
if (level === 1) {
return (
<Box marginY={1}>
<Text backgroundColor="#67e8f9" color="black" bold>
{` ${text} `}
</Text>
</Box>
);
}
if (level === 2) {
return (
<Box marginTop={1}>
<Text backgroundColor="#c4b5fd" color="black" bold>
{` ${text} `}
</Text>
</Box>
);
}
if (level === 3) {
return (
<Box marginTop={1}>
<Text backgroundColor="#f0abfc" color="black" bold>
{` ${text} `}
</Text>
</Box>
);
}
return (
<Box marginTop={1}>
<Text bold color="#f0abfc">
▸{" "}
</Text>
<Text bold>
<InlineMd text={text} citations={citations} />
</Text>
</Box>
);
}
/**
* Fenced code block. Round-cornered frame, language pill in the
* top-left, body in syntax-flavored colors. Lives inside event rows
* which Ink renders into `<Static>` (scrollback) — the eraseLines
* miscount that bans bordered Boxes from the *live* region doesn't
* apply here, since Static items render once and never repaint.
*/
function CodeBlockView({ lang, text }: { lang: string; text: string }) {
const langLabel = lang.trim();
return (
<Box flexDirection="column" borderStyle="round" borderColor="#7dd3fc" paddingX={1}>
{langLabel ? (
<Box>
<Text backgroundColor="#7dd3fc" color="black" bold>
{` ${langLabel} `}
</Text>
</Box>
) : null}
<Text color="#fde68a">{text}</Text>
</Box>
);
}
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]);
+127 -8
View File
@@ -19,6 +19,12 @@
* - Parent owns Tab, Esc, PageUp/Down (slash-complete, abort,
* unused). Arrow keys are split: empty buffer → parent (history
* recall); non-empty → child (cursor movement).
*
* CSI recovery is delegated to `key-normalize.ts` — see there for
* the rationale. Every event flows through `recoverCsiTail` first,
* which is the single source of truth for the Windows ConPTY case
* (parse-keypress eats the leading `\x1b` and routes the bare
* `[A`/`[C`/`[201~`/etc. through useInput as plain text).
*/
export interface MultilineKey {
@@ -47,8 +53,28 @@ 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 };
}
import { recoverCsiTail, stripCsiFragments } from "./key-normalize.js";
const BACKSLASH_SUFFIX = /\\$/;
const NOOP: MultilineAction = { next: null, cursor: null, submit: false };
@@ -56,19 +82,46 @@ const NOOP: MultilineAction = { next: null, cursor: null, submit: false };
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) {
// CSI recovery — bare `[A` / `[C` / `[Z` / `[5~` / etc. that
// Windows ConPTY leaves in `input` after parse-keypress eats the
// leading `\x1b`. See key-normalize.ts for the long version.
const recovered = recoverCsiTail(keyIn.input, keyIn);
const key: MultilineKey = recovered ? { ...keyIn, ...recovered, input: "" } : keyIn;
// Parent-owned keys: Tab (slash-complete), Esc (abort).
if (key.tab || key.escape) {
return NOOP;
}
// Empty buffer + ↑/↓ → parent handles history recall.
if (value.length === 0 && (key.upArrow || key.downArrow)) {
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 };
}
// Cursor motion.
// History recall is bound to Ctrl+P / Ctrl+N (bash readline
// convention) rather than ↑/↓. Reason: Windows Terminal + ConPTY
// translates mouse wheel events to ↑/↓ keystrokes for raw-mode
// child processes — indistinguishable at the byte level. If ↑/↓
// recalled history, every wheel-scroll would corrupt the prompt
// with a prior message. Ctrl+P/N is wheel-immune.
if (key.ctrl && key.input === "p") {
return { ...NOOP, historyHandoff: "prev" };
}
if (key.ctrl && key.input === "n") {
return { ...NOOP, historyHandoff: "next" };
}
// Cursor motion. Empty single-line buffer + ↑/↓ is now a no-op
// (used to recall history; see Ctrl+P/N comment above).
if (key.leftArrow) {
return { next: null, cursor: Math.max(0, cursor - 1), submit: false };
}
@@ -92,8 +145,58 @@ 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.
// Strip every recognised CSI fragment (paste markers, arrow tails,
// etc.) defensively — if any leaked past structured-key recovery
// they shouldn't get inserted into the buffer as text.
const stripped = stripCsiFragments(key.input);
// 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 +275,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 -13
View File
@@ -3,40 +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> = {
fast: { model: "deepseek-chat", harvest: false, branch: 1 },
smart: { model: "deepseek-reasoner", harvest: true, branch: 1 },
max: { model: "deepseek-reasoner", 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, no reasoning 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 + Pillar 2 harvest",
cost: "~10× cost vs fast · slower · better on multi-step tasks",
headline: "v4-flash · effort=max",
cost: "~1.5× fast · default · day-to-day coding",
},
max: {
headline: "reasoner + 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"];
}
+318
View File
@@ -0,0 +1,318 @@
/**
* Pure helpers for rendering one logical line of the prompt input as
* exactly one visual row, regardless of how wide the line's content
* is. Splitting this out from PromptInput so the math is testable
* without React/Ink.
*
* Why we can't trust Ink/Yoga's text wrap: Ink uses `string-width` to
* measure cells, but on CJK Windows terminals some glyphs render at
* a different cell count than `string-width` reports. The terminal
* wraps to a 2nd visual row, Ink's eraseLines miscounts, and the
* scrollback fills with ghost rows from the previous frame's leak.
*
* Our fix is to never let the line wrap. We slice the text down to
* the visible-cell budget ourselves and feed Ink a single Text whose
* width is known to fit.
*
* Cursor visibility: when the user types past the visible width the
* window slides so the cursor stays in view. `‹` and `›` markers
* appear at the trimmed edges so the user can see content is hidden
* to one side.
*/
import { type PasteEntry, decodePasteSentinel, formatBytesShort } from "./paste-sentinels.js";
/**
* One renderable atom of a viewport. The line's content is broken
* into a sequence of these so a paste sentinel becomes a magenta
* `[paste #N · Ml · KKB]` block while the surrounding text stays
* normal.
*/
export type Segment = { kind: "text"; text: string } | { kind: "paste"; id: number; label: string };
export interface Viewport {
/** Segments to render left-to-right. Sum of cells <= visibleCells. */
segments: Segment[];
/**
* Visual cell column at which to draw the cursor block, measured
* from the start of the viewport (0 = leftmost cell after the
* prompt prefix). `null` means cursor is not on this line — the
* caller renders a static line.
*/
cursorCell: number | null;
/** True when content was clipped on the left side. */
hiddenLeft: boolean;
/** True when content was clipped on the right side. */
hiddenRight: boolean;
}
/**
* Cell width of a single character in a typical terminal grid.
*
* Approximation of Unicode East Asian Width=Wide / W treatment.
* Range table is intentionally compact — covers the codepoints we
* see in practice (CJK ideographs, fullwidth forms, Hangul syllables,
* Hiragana / Katakana). Anything outside the wide ranges counts as
* one cell. Control characters count as zero so we don't over-budget
* for them.
*
* Not a full `string-width` clone. We deliberately don't honour the
* "Ambiguous=2 in CJK locale" rule because it produces inconsistent
* results across terminals and is the very source of Ink's wrap
* miscount. Treating ambiguous chars as 1 cell here matches what
* Ink/Yoga also does, so our slice math agrees with what Ink would
* have rendered (had it not wrapped).
*/
export function charCells(ch: string): number {
if (ch.length === 0) return 0;
const code = ch.charCodeAt(0);
if (code < 0x20 || code === 0x7f) return 0;
if (code < 0x1100) return 1;
// Hangul Jamo
if (code >= 0x1100 && code <= 0x115f) return 2;
// CJK Radicals, Kangxi Radicals, Ideographic Description, CJK Symbols
if (code >= 0x2e80 && code <= 0x303e) return 2;
// Hiragana, Katakana, Bopomofo, Hangul Compat Jamo, Kanbun
if (code >= 0x3041 && code <= 0x33ff) return 2;
// CJK Unified Ext A
if (code >= 0x3400 && code <= 0x4dbf) return 2;
// CJK Unified Ideographs
if (code >= 0x4e00 && code <= 0x9fff) return 2;
// Yi Syllables
if (code >= 0xa000 && code <= 0xa4cf) return 2;
// Hangul Syllables
if (code >= 0xac00 && code <= 0xd7a3) return 2;
// CJK Compatibility Ideographs
if (code >= 0xf900 && code <= 0xfaff) return 2;
// CJK Compatibility Forms
if (code >= 0xfe30 && code <= 0xfe4f) return 2;
// Halfwidth and Fullwidth Forms (fullwidth half is wide)
if (code >= 0xff00 && code <= 0xff60) return 2;
// Fullwidth signs
if (code >= 0xffe0 && code <= 0xffe6) return 2;
return 1;
}
/** Total cells of a string, with paste sentinels expanded to placeholder width. */
export function stringCells(s: string, pastes?: ReadonlyMap<number, PasteEntry>): number {
let n = 0;
for (let i = 0; i < s.length; i++) {
const ch = s[i]!;
const id = decodePasteSentinel(ch);
if (id !== null) {
n += pasteSentinelCells(id, pastes);
} else {
n += charCells(ch);
}
}
return n;
}
/** Paste sentinel placeholder width — what we'd render for that sentinel. */
export function pasteSentinelLabel(id: number, entry: PasteEntry | undefined): string {
if (!entry) return `[paste #${id + 1} · (missing)]`;
return `[paste #${id + 1} · ${entry.lineCount}l · ${formatBytesShort(entry.charCount)}]`;
}
function pasteSentinelCells(id: number, pastes?: ReadonlyMap<number, PasteEntry>): number {
const entry = pastes?.get(id);
return pasteSentinelLabel(id, entry).length;
}
/**
* Compute the viewport for a line, keeping the cursor visible. When
* the line's total cells fit in `visibleCells`, return the whole
* line. Otherwise slice a window centred on the cursor with `‹` /
* `›` markers indicating clipped sides.
*
* `cursorCol` is the cursor's char index within `line` (0 = before
* first char; `line.length` = past last char). Pass `null` for
* lines that don't host the cursor — the function returns a left-
* aligned static viewport with truncation on the right.
*/
export function buildViewport(
line: string,
cursorCol: number | null,
visibleCells: number,
pastes?: ReadonlyMap<number, PasteEntry>,
): Viewport {
if (visibleCells <= 0) {
return {
segments: [],
cursorCell: cursorCol === null ? null : 0,
hiddenLeft: false,
hiddenRight: line.length > 0,
};
}
const totalCells = stringCells(line, pastes);
// Fast path: whole line fits.
if (totalCells <= visibleCells) {
const segments = textToSegments(line, pastes);
let cursorCell: number | null = null;
if (cursorCol !== null) {
cursorCell = stringCells(line.slice(0, cursorCol), pastes);
}
return { segments, cursorCell, hiddenLeft: false, hiddenRight: false };
}
// Static viewport (cursor not on this line) — clip from the right.
if (cursorCol === null) {
return clipFromLeft(line, visibleCells, pastes);
}
// Cursor-bearing line: slide a window so cursor stays visible.
// Reserve 1 cell on each potentially-clipped side for the marker.
return clipAroundCursor(line, cursorCol, visibleCells, pastes);
}
function clipFromLeft(
line: string,
visibleCells: number,
pastes?: ReadonlyMap<number, PasteEntry>,
): Viewport {
// Show as much of the head as fits; mark the right edge as hidden.
// Reserve 1 cell for the `›` marker.
const budget = Math.max(1, visibleCells - 1);
let used = 0;
let end = 0;
while (end < line.length) {
const ch = line[end]!;
const cw = charCellsAt(line, end, pastes);
if (used + cw > budget) break;
used += cw;
end++;
}
const segments = textToSegments(line.slice(0, end), pastes);
return { segments, cursorCell: null, hiddenLeft: false, hiddenRight: end < line.length };
}
/**
* Sliding window around the cursor. Algorithm:
*
* 1. Start with `start` and `end` both at the cursor index.
* 2. Expand `end` rightward while there's budget, until cursor cell
* visible or we hit end-of-line.
* 3. Expand `start` leftward to fill remaining budget.
* 4. Reserve 1 cell on each clipped side for the `‹`/`›` marker.
*
* The cursor cell is computed AFTER the slice is fixed, by counting
* cells from `start` up to `cursorCol`.
*/
function clipAroundCursor(
line: string,
cursorCol: number,
visibleCells: number,
pastes?: ReadonlyMap<number, PasteEntry>,
): Viewport {
// `cursorCol` is between 0 and line.length (inclusive). The cursor
// visually sits BEFORE the char at line[cursorCol] (or after the
// last char when cursorCol === line.length).
// We want both the char at the cursor (if any) AND a cell of cursor
// padding visible.
// Budget — leave 1 cell for each marker we may need.
let budget = visibleCells;
// Right marker: needed if we don't reach end of line.
// Left marker: needed if start > 0.
// We don't know in advance, so allocate conservatively: -2 cells.
const reservedForMarkers = 2;
budget = Math.max(1, budget - reservedForMarkers);
// Try to keep cursor roughly centred. Start by aiming `start` ~
// halfway behind cursorCol.
const halfBudget = Math.floor(budget / 2);
// Walk left from cursor, accumulating cells, until we've spent
// halfBudget OR hit the start of the line.
let start = cursorCol;
let leftCells = 0;
while (start > 0 && leftCells < halfBudget) {
const cw = charCellsAt(line, start - 1, pastes);
if (leftCells + cw > halfBudget) break;
start--;
leftCells += cw;
}
// Walk right from cursor, filling the remaining budget. We always
// include a cell for the cursor itself if line[cursorCol] exists
// (since the cursor block covers that char). At end-of-line we
// include a phantom cell of cursor space.
const rightBudget = budget - leftCells;
let end = cursorCol;
let rightCells = 0;
// Include the char at the cursor (1 or 2 cells depending on width)
// if there is one.
const cursorChar = cursorCol < line.length ? charCellsAt(line, cursorCol, pastes) : 1;
if (rightBudget >= cursorChar) {
if (cursorCol < line.length) end = cursorCol + 1;
rightCells = cursorChar;
while (end < line.length && rightCells < rightBudget) {
const cw = charCellsAt(line, end, pastes);
if (rightCells + cw > rightBudget) break;
rightCells += cw;
end++;
}
}
// If we have leftover right-budget and there's still room on the
// left, expand leftwards more (cursor stays towards the right
// edge but more left context is shown — common when typing at
// end of a long line).
let extraLeftBudget = rightBudget - rightCells;
while (start > 0 && extraLeftBudget > 0) {
const cw = charCellsAt(line, start - 1, pastes);
if (cw > extraLeftBudget) break;
start--;
leftCells += cw;
extraLeftBudget -= cw;
}
const hiddenLeft = start > 0;
const hiddenRight = end < line.length;
const segments = textToSegments(line.slice(start, end), pastes);
// Cursor cell relative to the start of the slice. Markers are
// rendered separately by the caller — they don't shift the
// segment-relative offset so we don't add them here.
const cursorCell = stringCells(line.slice(start, cursorCol), pastes);
return { segments, cursorCell, hiddenLeft, hiddenRight };
}
function charCellsAt(line: string, idx: number, pastes?: ReadonlyMap<number, PasteEntry>): number {
const ch = line[idx]!;
const id = decodePasteSentinel(ch);
if (id !== null) {
const entry = pastes?.get(id);
return pasteSentinelLabel(id, entry).length;
}
return charCells(ch);
}
/**
* Walk the string and split it into text/paste segments. Pure —
* doesn't allocate per-character objects (text runs accumulate in a
* single segment). Used by both the fast and clipped paths.
*/
export function textToSegments(line: string, pastes?: ReadonlyMap<number, PasteEntry>): Segment[] {
const out: Segment[] = [];
let buf = "";
const flushBuf = () => {
if (buf.length > 0) {
out.push({ kind: "text", text: buf });
buf = "";
}
};
for (let i = 0; i < line.length; i++) {
const ch = line[i]!;
const id = decodePasteSentinel(ch);
if (id !== null) {
flushBuf();
const label = pasteSentinelLabel(id, pastes?.get(id));
out.push({ kind: "paste", id, label });
} else {
buf += ch;
}
}
flushBuf();
return out;
}
+20 -1553
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";
}
+462
View File
@@ -0,0 +1,462 @@
/**
* Raw stdin reader with our own CSI parser.
*
* Replaces Ink's `useInput` chain (which uses `parse-keypress` with a
* 100 ms intra-sequence timeout that's too short for Windows ConPTY).
* That timeout was the root cause of every keyboard regression we
* shipped a patch for in 0.7.x — paste markers leaking into the
* buffer, arrow keys not crossing newlines, Shift+Tab silently failing.
*
* Design:
* - One reader owns `process.stdin`. We call `setRawMode(true)`,
* register a single `data` listener, and emit parsed `KeyEvent`s
* to subscribers. As long as no `useInput` is called inside the
* Ink tree, Ink itself never attaches its own listener — we're
* the sole consumer of stdin.
*
* - The state machine is tiny: idle → esc → csi/ss3 → idle, plus a
* `paste` accumulator that swallows everything between `\x1b[200~`
* and `\x1b[201~`. ESC ambiguity (standalone Esc vs. start of a
* CSI) is resolved by a 250 ms timer — much longer than parse-
* keypress's 100 ms, so ConPTY-split sequences land in the
* correct branch.
*
* - We also recognise the ESC-stripped variants (`[A`, `[200~`) at
* idle-state lookahead, in case ConPTY consumed the leading ESC
* before we even saw it. That used to be a recovery layer in
* `key-normalize.ts`; with this reader as the sole input source
* it folds into the parser proper.
*
* - `paste` events carry the full content so the consumer can route
* it through paste-sentinel registration without re-parsing.
*/
import { stdin } from "node:process";
/**
* Single keystroke event. Shape mirrors Ink's `(input, key)` callback
* pair for migration ergonomics — consumers reading `key.upArrow`
* etc. can keep doing so. `paste` is the one new field; consumers
* that care about pastes (PromptInput) check it explicitly.
*/
export interface KeyEvent {
/**
* Printable character(s). Non-empty for normal typing, Ctrl+letter
* (the letter goes here with `ctrl:true`), Alt+letter (with
* `meta:true`), and bracketed paste content (with `paste:true`).
* Always empty for control keystrokes like arrows / Enter / Esc.
*/
input: string;
upArrow?: boolean;
downArrow?: boolean;
leftArrow?: boolean;
rightArrow?: boolean;
pageUp?: boolean;
pageDown?: boolean;
home?: boolean;
end?: boolean;
delete?: boolean;
backspace?: boolean;
tab?: boolean;
return?: boolean;
escape?: boolean;
shift?: boolean;
ctrl?: boolean;
meta?: boolean;
/**
* True iff this event delivers bracketed-paste content. `input`
* holds the entire paste; consumers MUST NOT re-interpret it as
* keystrokes (e.g. a `\n` in a paste shouldn't fire submit).
*/
paste?: boolean;
}
type Subscriber = (ev: KeyEvent) => void;
/** ESC ambiguity timeout. Long enough for ConPTY-split sequences. */
const ESC_TIMEOUT_MS = 250;
/** Bracketed-paste markers (DECSET 2004). */
const PASTE_START = "\x1b[200~";
const PASTE_END = "\x1b[201~";
/** ESC-stripped variants — ConPTY occasionally eats the leading ESC. */
const PASTE_START_BARE = "[200~";
const PASTE_END_BARE = "[201~";
/**
* CSI tails (the bytes that follow `\x1b[`) we recognise and the
* structured event each produces. Order doesn't matter — lookups
* are exact-match.
*/
const CSI_TAIL_MAP: ReadonlyArray<{ tail: string; ev: KeyEvent }> = [
{ tail: "A", ev: { input: "", upArrow: true } },
{ tail: "B", ev: { input: "", downArrow: true } },
{ tail: "C", ev: { input: "", rightArrow: true } },
{ tail: "D", ev: { input: "", leftArrow: true } },
{ tail: "H", ev: { input: "", home: true } },
{ tail: "F", ev: { input: "", end: true } },
{ tail: "1~", ev: { input: "", home: true } },
{ tail: "4~", ev: { input: "", end: true } },
{ tail: "5~", ev: { input: "", pageUp: true } },
{ tail: "6~", ev: { input: "", pageDown: true } },
{ tail: "3~", ev: { input: "", delete: true } },
{ tail: "Z", ev: { input: "", shift: true, tab: true } },
// modifyOtherKeys (xterm CSI > 4 ; 2 m) sequences for Enter with
// modifiers. Only fired when App.tsx has enabled the mode at
// startup; otherwise Shift+Enter stays indistinguishable from Enter.
// Modifier encoding: 2=shift, 3=alt, 4=alt+shift, 5=ctrl,
// 6=ctrl+shift, 7=ctrl+alt, 8=ctrl+alt+shift. Keycode 13 = Enter.
{ tail: "27;2;13~", ev: { input: "", return: true, shift: true } },
{ tail: "27;5;13~", ev: { input: "", return: true, ctrl: true } },
{ tail: "27;6;13~", ev: { input: "", return: true, ctrl: true, shift: true } },
// Kitty keyboard protocol — same idea, different envelope:
// `\x1b[<keycode>;<mod>u`. Some terminals (kitty, recent Windows
// Terminal previews) prefer this shape. Harmless to map here too.
{ tail: "13;2u", ev: { input: "", return: true, shift: true } },
{ tail: "13;5u", ev: { input: "", return: true, ctrl: true } },
{ tail: "13;6u", ev: { input: "", return: true, ctrl: true, shift: true } },
];
/** SS3 sequences (`\x1bO<letter>`) — some terminals send these for arrows. */
const SS3_MAP: Record<string, KeyEvent> = {
A: { input: "", upArrow: true },
B: { input: "", downArrow: true },
C: { input: "", rightArrow: true },
D: { input: "", leftArrow: true },
H: { input: "", home: true },
F: { input: "", end: true },
};
/**
* Lookahead matcher for ESC-stripped sequences. When `chunk[i]` is
* `[`, we check the bytes immediately after to see if they form a
* recognised CSI tail. If so we emit the structured event and tell
* the caller how many bytes to consume. Returns `null` when no
* recognised tail starts here.
*/
function tryEscapelessCsi(chunk: string, i: number): { advance: number; ev: KeyEvent } | null {
if (chunk[i] !== "[") return null;
// Paste start as a special case (handled by caller).
// Try each known tail.
for (const entry of CSI_TAIL_MAP) {
const candidate = `[${entry.tail}`;
if (chunk.slice(i, i + candidate.length) === candidate) {
return { advance: candidate.length, ev: entry.ev };
}
}
return null;
}
/**
* Final byte of a CSI sequence is in the range `0x40` (`@`) –
* `0x7E` (`~`). Anything else is a parameter / intermediate byte.
*/
function isCsiFinal(ch: string): boolean {
const code = ch.charCodeAt(0);
return code >= 0x40 && code <= 0x7e;
}
/**
* Look up the CSI event for a fully-assembled sequence (without the
* leading `\x1b[`). Returns `null` if we don't recognise it — which
* is fine, we just drop the bytes silently rather than insert them
* into the buffer as garbage text.
*/
function lookupCsi(tail: string): KeyEvent | null {
for (const entry of CSI_TAIL_MAP) {
if (entry.tail === tail) return entry.ev;
}
return null;
}
export class StdinReader {
private subscribers = new Set<Subscriber>();
private state: "idle" | "esc" | "csi" | "ss3" | "paste" = "idle";
/** Buffer for partial sequences across chunks. */
private csiBuf = "";
/** Buffer for paste content. */
private pasteBuf = "";
private escTimer: NodeJS.Timeout | null = null;
private started = false;
/** The actual `data` listener — kept as a field so `stop()` can detach it. */
private listener: ((chunk: Buffer | string) => void) | null = null;
start(): void {
if (this.started) return;
if (!stdin.isTTY) {
// Non-TTY (piped input). We can't run interactively — don't try.
return;
}
stdin.setRawMode(true);
stdin.setEncoding("utf8");
stdin.resume();
this.listener = (chunk) =>
this.handleChunk(typeof chunk === "string" ? chunk : chunk.toString("utf8"));
stdin.on("data", this.listener);
this.started = true;
}
stop(): void {
if (!this.started) return;
if (this.listener) {
stdin.off("data", this.listener);
this.listener = null;
}
if (stdin.isTTY) {
try {
stdin.setRawMode(false);
} catch {
// setRawMode may throw if stdin is already closed; ignore.
}
}
stdin.pause();
this.cancelEscTimer();
this.state = "idle";
this.csiBuf = "";
this.pasteBuf = "";
this.started = false;
}
/**
* Subscribe to parsed key events. Returns an unsubscribe function.
* Multiple subscribers are supported — every event fans out to all
* of them; the React Context layer above uses one subscriber and
* dispatches further to its own consumer list.
*/
subscribe(fn: Subscriber): () => void {
this.subscribers.add(fn);
return () => {
this.subscribers.delete(fn);
};
}
/**
* Inject a chunk of bytes as if it came from stdin. Used by tests
* to drive the parser without a real TTY.
*/
feed(chunk: string): void {
this.handleChunk(chunk);
}
private dispatch(ev: KeyEvent): void {
for (const sub of this.subscribers) sub(ev);
}
private cancelEscTimer(): void {
if (this.escTimer) {
clearTimeout(this.escTimer);
this.escTimer = null;
}
}
private scheduleEscTimer(): void {
this.cancelEscTimer();
this.escTimer = setTimeout(() => {
// Standalone Esc — no follow-up byte arrived in time.
if (this.state === "esc") {
this.state = "idle";
this.dispatch({ input: "", escape: true });
}
}, ESC_TIMEOUT_MS);
}
private handleChunk(chunk: string): void {
this.cancelEscTimer();
let i = 0;
while (i < chunk.length) {
// ── paste accumulator ──
if (this.state === "paste") {
// Look for end marker (with or without ESC).
const endA = chunk.indexOf(PASTE_END, i);
const endB = chunk.indexOf(PASTE_END_BARE, i);
let endIdx = -1;
let endLen = 0;
if (endA !== -1 && (endB === -1 || endA <= endB)) {
endIdx = endA;
endLen = PASTE_END.length;
} else if (endB !== -1) {
endIdx = endB;
endLen = PASTE_END_BARE.length;
}
if (endIdx === -1) {
this.pasteBuf += chunk.slice(i);
i = chunk.length;
break;
}
this.pasteBuf += chunk.slice(i, endIdx);
this.dispatch({ input: this.pasteBuf, paste: true });
this.pasteBuf = "";
this.state = "idle";
i = endIdx + endLen;
continue;
}
// ── CSI accumulator ──
if (this.state === "csi") {
const ch = chunk[i]!;
this.csiBuf += ch;
if (isCsiFinal(ch)) {
this.dispatchCsi(this.csiBuf);
this.csiBuf = "";
// Only reset state if `dispatchCsi` didn't already mutate it
// (it transitions to `paste` for the `200~` start marker —
// resetting here would clobber that and the paste content
// would be parsed as keystrokes).
if (this.state === "csi") this.state = "idle";
}
i++;
continue;
}
// ── SS3 single-byte tail ──
if (this.state === "ss3") {
const ev = SS3_MAP[chunk[i]!];
if (ev) this.dispatch(ev);
this.state = "idle";
i++;
continue;
}
// ── ESC pending ──
if (this.state === "esc") {
const ch = chunk[i]!;
if (ch === "[") {
this.state = "csi";
this.csiBuf = "";
i++;
continue;
}
if (ch === "O") {
this.state = "ss3";
i++;
continue;
}
// ESC + any other char = Alt+key (rare; we still dispatch).
this.dispatch({ input: ch, meta: true });
this.state = "idle";
i++;
continue;
}
// ── idle ──
const ch = chunk[i]!;
if (ch === "\x1b") {
this.state = "esc";
i++;
continue;
}
// ESC-stripped paste-start (ConPTY): bare `[200~` at idle.
if (chunk.slice(i, i + PASTE_START_BARE.length) === PASTE_START_BARE) {
this.state = "paste";
this.pasteBuf = "";
i += PASTE_START_BARE.length;
continue;
}
// ESC-stripped CSI tails — recover before treating `[` as text.
const escapeless = tryEscapelessCsi(chunk, i);
if (escapeless) {
this.dispatch(escapeless.ev);
i += escapeless.advance;
continue;
}
// Single-byte control keys.
// \r (CR, 0x0D) is Enter on every terminal in raw mode.
// \n (LF, 0x0A) is what Ctrl+J emits — keep it distinct so the
// multiline reducer can map it to "insert newline" instead of
// "submit". Pastes containing \n still arrive via either the
// bracketed-paste accumulator or a multi-byte printable chunk
// that includes the newline; neither hits this single-byte
// branch, so this split is safe.
if (ch === "\r") {
this.dispatch({ input: "", return: true });
i++;
continue;
}
if (ch === "\n") {
this.dispatch({ input: "j", ctrl: true });
i++;
continue;
}
if (ch === "\t") {
this.dispatch({ input: "", tab: true });
i++;
continue;
}
if (ch === "\x7f" || ch === "\b") {
this.dispatch({ input: "", backspace: true });
i++;
continue;
}
if (ch === "\x03") {
// Ctrl+C — terminate the process. Raw mode disables the
// default SIGINT, so we have to handle it ourselves.
this.dispatch({ input: "c", ctrl: true });
i++;
continue;
}
const code = ch.charCodeAt(0);
// Other Ctrl+letter (0x01-0x1A → A-Z, except already-handled).
if (code >= 1 && code <= 26) {
const letter = String.fromCharCode(0x60 + code); // a..z
this.dispatch({ input: letter, ctrl: true });
i++;
continue;
}
// Regular printable input. Coalesce a run of printable chars
// into one event so a multi-byte UTF-8 paste-burst arrives as
// one `input` rather than N adjacent events.
let end = i + 1;
while (end < chunk.length) {
const c = chunk[end]!;
if (c === "\x1b" || c === "\r" || c === "\n" || c === "\t") break;
if (c === "\x7f" || c === "\b" || c === "\x03") break;
const cc = c.charCodeAt(0);
if (cc >= 1 && cc <= 26) break;
// Don't swallow into a printable run if a CSI / paste prefix
// starts at this position.
if (c === "[" && tryEscapelessCsi(chunk, end)) break;
if (chunk.slice(end, end + PASTE_START_BARE.length) === PASTE_START_BARE) break;
end++;
}
this.dispatch({ input: chunk.slice(i, end) });
i = end;
}
// After processing, if we're still in `esc` state, schedule the
// ambiguity timer. The next chunk may carry the rest of the CSI;
// if not, the timer fires and dispatches a standalone Esc.
if (this.state === "esc") {
this.scheduleEscTimer();
}
}
private dispatchCsi(seq: string): void {
// seq is the bytes after `\x1b[`, e.g. "A", "5~", "200~", "Z".
if (seq === "200~") {
this.state = "paste";
this.pasteBuf = "";
return;
}
if (seq === "201~") {
// Stray paste-end — we shouldn't reach here outside paste mode,
// but if we do, drop it silently.
return;
}
const ev = lookupCsi(seq);
if (ev) this.dispatch(ev);
// Unknown CSI → drop. Do NOT insert raw bytes as text.
}
}
/** Singleton — one reader per process. */
let singleton: StdinReader | null = null;
export function getStdinReader(): StdinReader {
if (!singleton) singleton = new StdinReader();
return singleton;
}
+97
View File
@@ -0,0 +1,97 @@
/**
* Reasonix visual theme.
*
* One source of truth for colors, glyphs, and decorative blocks so
* the TUI reads as one designed surface instead of fifteen
* components inventing their own palette. All colors are truecolor
* hex; Ink degrades to the nearest 256-color / 8-color slot on
* older terminals, so the worst case is still legible.
*
* Why a module rather than a context: tests import these strings,
* Ink components consume them as `color={...}` props, and there's
* no theming switch (light/dark) — one project, one palette.
*/
/** Brand gradient — the same teal → cyan → blue → purple → fuchsia
* sweep used by the REASONIX wordmark. Reused for accent bars,
* progress fills, and decorative dividers. */
export const GRADIENT: ReadonlyArray<string> = [
"#5eead4", // teal
"#67e8f9", // cyan
"#7dd3fc", // sky
"#93c5fd", // blue
"#a5b4fc", // indigo
"#c4b5fd", // violet
"#d8b4fe", // purple
"#f0abfc", // fuchsia
];
/** Solid palette — semantic colors used for status, role, and
* accent surfaces. Sourced from the Tailwind 400/500 row so the
* tone is consistent with the gradient. */
export const COLOR = {
primary: "#67e8f9", // cyan-300
accent: "#c4b5fd", // violet-300
brand: "#5eead4", // teal-300
user: "#67e8f9", // user message glyph + bar
assistant: "#86efac", // green-300, assistant glyph + bar
tool: "#fcd34d", // amber-300, tool ok pill bg
toolErr: "#fda4af", // rose-300, tool err pill bg
info: "#94a3b8", // slate-400, info / dim
warn: "#fbbf24", // amber-400
err: "#f87171", // red-400
ok: "#4ade80", // green-400
} as const;
/**
* Glyphs — one consistent alphabet for the whole TUI. Geometric
* shapes (◇ ◆ ▣ ▥) make the role of a row readable at a glance
* after one or two turns; arrows (› ▸ ▶) consistently mean
* "selection / focus / next." Brand mark is reserved for the app
* header.
*/
export const GLYPH = {
brand: "◈",
user: "◇",
assistant: "◆",
toolOk: "▣",
toolErr: "▥",
warn: "▲",
err: "✦",
arrow: "›",
bullet: "·",
bar: "▎",
thinBar: "▏",
block: "█",
shade1: "░",
shade2: "▒",
shade3: "▓",
} as const;
/**
* Render a horizontal gradient rule of the given width. Each cell
* picks a color from the brand gradient interpolated across the
* width, so at cols=80 the rule spans the full sweep. Used for
* StatsPanel header/footer decoration and other "this section is
* important" anchors.
*/
export function gradientCells(
width: number,
glyph: string = GLYPH.block,
): Array<{ ch: string; color: string }> {
const cells: Array<{ ch: string; color: string }> = [];
if (width <= 0) return cells;
const last = GRADIENT.length - 1;
for (let i = 0; i < width; i++) {
const t = width === 1 ? 0 : (i * last) / (width - 1);
const lo = Math.floor(t);
const hi = Math.min(last, lo + 1);
// Pick the closer of the two anchor colors for this cell. Linear
// hex blending could be fancier but the discrete steps already
// read as a smooth fade at any reasonable width.
const color = t - lo < 0.5 ? GRADIENT[lo]! : GRADIENT[hi]!;
cells.push({ ch: glyph, color });
}
return cells;
}
+200
View File
@@ -0,0 +1,200 @@
/**
* 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."
*
* Suffix-match is on purpose: MCP-bridged tools come in prefixed
* (`filesystem_read_file`, `git_search_files`) and we want them to
* pick up the same specialized summary as the bare local name.
*/
function summarizeKnownTool(toolName: string, content: string): ToolSummary | null {
const hasSuffix = (s: string) => toolName === s || toolName.endsWith(`_${s}`);
if (hasSuffix("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 (hasSuffix("list_directory") || hasSuffix("directory_tree")) {
const entries = content.split(/\r?\n/).filter((l) => l.trim()).length;
return { summary: `${entries} entr${entries === 1 ? "y" : "ies"}`, isError: false };
}
if (hasSuffix("search_files") || hasSuffix("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 (hasSuffix("write_file")) {
const lines = formatLineCount(content);
const bytes = formatBytes(content.length);
return { summary: `wrote ${lines} · ${bytes}`, isError: false };
}
if (hasSuffix("run_command") || hasSuffix("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 };
}
+23 -1
View File
@@ -110,7 +110,17 @@ export class DeepSeekClient {
process.env.DEEPSEEK_BASE_URL ??
"https://api.deepseek.com"
).replace(/\/+$/, "");
this.timeoutMs = opts.timeoutMs ?? 120_000;
// 11 min. DeepSeek's load-balancer may keep a connection open for
// up to 10 minutes while the request waits in queue (non-streaming
// sends empty lines, streaming sends `:` SSE keep-alive comments —
// both are invisible to our parsers, so neither surfaces until the
// real response starts). Timing out at the legacy 2-min default
// killed queued requests prematurely, burned the queue slot on
// retry, and could loop through the whole queue repeatedly.
// Setting 11 min lets the server's own 10-min cap close the
// connection first (clean EOF → natural retry), and our timer
// is a safety net for genuinely hung sockets.
this.timeoutMs = opts.timeoutMs ?? 660_000;
this._fetch = opts.fetch ?? globalThis.fetch.bind(globalThis);
this.retry = opts.retry ?? {};
}
@@ -125,6 +135,18 @@ export class DeepSeekClient {
if (opts.temperature !== undefined) payload.temperature = opts.temperature;
if (opts.maxTokens !== undefined) payload.max_tokens = opts.maxTokens;
if (opts.responseFormat) payload.response_format = opts.responseFormat;
// V4 thinking-mode toggle: lives under `extra_body.thinking.type` per
// DeepSeek's docs. Docs also note that in thinking mode `temperature`,
// `top_p`, `presence_penalty`, `frequency_penalty` are silently
// ignored — we don't strip them here because the server's explicit
// "setting won't report an error" contract means leaving them in is
// safe and keeps the request payload diffable against OpenAI tooling.
if (opts.thinking) {
payload.extra_body = { thinking: { type: opts.thinking } };
}
if (opts.reasoningEffort) {
payload.reasoning_effort = opts.reasoningEffort;
}
return payload;
}
+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);
+15 -1
View File
@@ -78,7 +78,14 @@ export async function harvest(
const trimmed = reasoningContent.trim();
if (trimmed.length < minLen) return emptyPlanState();
const model = options.model ?? "deepseek-chat";
// Harvest is schema-constrained JSON extraction, not agent reasoning.
// 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. (`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(
@@ -96,6 +103,13 @@ export async function harvest(
responseFormat: { type: "json_object" },
temperature: 0,
maxTokens: 600,
// Pin mode + effort so a future default-model swap (e.g. someone
// sets `options.model = "deepseek-v4-pro"`) can't accidentally
// turn this micro-extraction into a multi-thousand-reasoning-
// token call. DeepSeek ignores these on non-thinking models, so
// the request stays valid regardless of the chosen model.
thinking: "disabled",
reasoningEffort: "high",
signal,
});
return parsePlanState(resp.content, maxItems, maxItemLen);
+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,
+840 -66
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.`;
+41 -16
View File
@@ -1,24 +1,33 @@
import type { Usage } from "./client.js";
/**
* USD per 1M tokens. Source of truth is DeepSeek's CNY price sheet at
* https://api-docs.deepseek.com/zh-cn/quick_start/pricing (as of
* 2026-04-23): chat and reasoner are unified at ¥0.2 / ¥2 / ¥3 per 1M
* tokens (cache-hit input / cache-miss input / output). Converted at
* a fixed 7.2 CNY/USD rate so stats stay stable across the daily FX
* USD per 1M tokens. Source: DeepSeek's CNY price sheet
* (https://api-docs.deepseek.com/zh-cn/quick_start/pricing) converted
* at a fixed 7.2 CNY/USD rate so billing stays stable across daily FX
* drift; revisit if the rate moves more than ±5%.
*
* Historical note: the pre-unification prices were chat $0.07/$0.27/$1.10
* and reasoner $0.14/$0.55/$2.19. Sessions logged under those values
* in `~/.reasonix/usage.jsonl` remain as-is (USD frozen at record time)
* — we never retroactively rewrite billing history.
* 2026-04 V4 launch:
* - deepseek-v4-flash ¥0.2 / ¥1 / ¥2 (hit / miss / out per 1M)
* - deepseek-v4-pro ¥1 / ¥12 / ¥24
*
* deepseek-chat and deepseek-reasoner are now thin compat aliases for
* v4-flash's non-thinking and thinking modes respectively — same
* underlying model, same bill. We keep them in the table so existing
* sessions (and configs that hard-code these names) keep pricing.
*
* Historical note: sessions logged before this file was updated remain
* as-is in `~/.reasonix/usage.jsonl` — USD is frozen at record time,
* we never retroactively rewrite billing history.
*/
export const DEEPSEEK_PRICING: Record<
string,
{ inputCacheHit: number; inputCacheMiss: number; output: number }
> = {
"deepseek-chat": { inputCacheHit: 0.028, inputCacheMiss: 0.28, output: 0.42 },
"deepseek-reasoner": { inputCacheHit: 0.028, inputCacheMiss: 0.28, output: 0.42 },
"deepseek-v4-flash": { inputCacheHit: 0.028, inputCacheMiss: 0.139, output: 0.278 },
"deepseek-v4-pro": { inputCacheHit: 0.139, inputCacheMiss: 1.667, output: 3.333 },
// Compat aliases — priced as v4-flash per the deprecation notice.
"deepseek-chat": { inputCacheHit: 0.028, inputCacheMiss: 0.139, output: 0.278 },
"deepseek-reasoner": { inputCacheHit: 0.028, inputCacheMiss: 0.139, output: 0.278 },
};
/** Reference Claude Sonnet 4.6 pricing (USD per 1M tokens). */
@@ -26,13 +35,21 @@ export const CLAUDE_SONNET_PRICING = { input: 3.0, output: 15.0 };
/**
* Maximum prompt-side context window per DeepSeek model, in tokens.
* Both V3 (`deepseek-chat`) and R1 (`deepseek-reasoner`) currently expose
* a 131,072-token prompt limit per the OpenAPI spec; completion caps
* differ but don't affect the prompt budget the StatsPanel shows.
* V4 (flash + pro) jumps to 1,000,000 tokens. The compat aliases
* (deepseek-chat / deepseek-reasoner) inherit that through the
* v4-flash route — we bump them so the StatsPanel gauge reflects
* what the API actually accepts.
*
* Completion caps (e.g. 384K for V4) are enforced by the server, not
* tracked here — they don't affect the prompt-side budget the panel
* shows. If a future feature surfaces output-cap warnings we'll add
* a sibling table.
*/
export const DEEPSEEK_CONTEXT_TOKENS: Record<string, number> = {
"deepseek-chat": 131_072,
"deepseek-reasoner": 131_072,
"deepseek-v4-flash": 1_000_000,
"deepseek-v4-pro": 1_000_000,
"deepseek-chat": 1_000_000,
"deepseek-reasoner": 1_000_000,
};
/** Fallback when the caller's model id isn't in the table — safe lower bound. */
@@ -106,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 {
@@ -167,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
+28 -11
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";
/**
@@ -109,7 +114,7 @@ export interface SpawnSubagentOptions {
system: string;
/** The task / question / instruction the subagent must address. */
task: string;
/** Model id for the child loop. Defaults to `deepseek-chat`. */
/** Model id for the child loop. Defaults to `deepseek-v4-pro`. */
model?: string;
/** Iteration ceiling for the child loop. Defaults to 16. */
maxToolIters?: number;
@@ -173,7 +178,7 @@ export interface SubagentToolOptions {
defaultSystem?: string;
/** Project root for `applyProjectMemory` lookup. Omit in chat mode. */
projectRoot?: string;
/** Default model. `deepseek-chat` (V3) 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-chat";
// 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-chat", "deepseek-reasoner"],
enum: ["deepseek-v4-flash", "deepseek-v4-pro"],
description:
"Which DeepSeek model the subagent runs on. 'deepseek-chat' (V3) is the default — fast and cheap. Use 'deepseek-reasoner' (R1) only when the subtask genuinely needs planning or multi-step reasoning; it is roughly 5-10x more expensive.",
"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",
+15
View File
@@ -64,4 +64,19 @@ export interface ChatRequestOptions {
signal?: AbortSignal;
/** DeepSeek response_format — use { type: "json_object" } to force valid JSON. */
responseFormat?: { type: "json_object" | "text" };
/**
* Explicitly toggle V4 thinking mode. Serialized as
* `extra_body.thinking.type = enabled|disabled`. Omit to let the
* server default apply (thinking enabled). Mainly used so the loop
* can pin the mode per model: `deepseek-chat` → disabled (legacy
* non-thinking compat), everything else → enabled.
*/
thinking?: "enabled" | "disabled";
/**
* Per-request reasoning-effort cap. Serialized as the top-level
* `reasoning_effort` field. DeepSeek accepts `high` (standard) or
* `max` (Agent-class, auto-applied to Claude-Code-style flows per
* the V4 docs). Reasonix pins `max` because every turn is agent-like.
*/
reasoningEffort?: "high" | "max";
}
+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);
});
});
+110
View File
@@ -0,0 +1,110 @@
/**
* Tests for the CSI recovery boundary. Every keystroke that flows
* through Ink's `useInput` runs through `recoverCsiTail` first, so a
* regression here would silently re-break arrow keys / paste markers
* / Shift+Tab on Windows ConPTY.
*/
import { describe, expect, it } from "vitest";
import {
STRIPPABLE_CSI_FRAGMENTS,
recoverCsiTail,
stripCsiFragments,
} from "../src/cli/ui/key-normalize.js";
describe("recoverCsiTail — ESC-stripped fallbacks (Windows ConPTY)", () => {
it("recovers arrow keys from bare CSI tails", () => {
expect(recoverCsiTail("[A")).toEqual({ upArrow: true });
expect(recoverCsiTail("[B")).toEqual({ downArrow: true });
expect(recoverCsiTail("[C")).toEqual({ rightArrow: true });
expect(recoverCsiTail("[D")).toEqual({ leftArrow: true });
});
it("recovers page navigation tails", () => {
expect(recoverCsiTail("[5~")).toEqual({ pageUp: true });
expect(recoverCsiTail("[6~")).toEqual({ pageDown: true });
});
it("recovers forward-delete tail", () => {
expect(recoverCsiTail("[3~")).toEqual({ delete: true });
});
it("recovers Shift+Tab tail", () => {
expect(recoverCsiTail("[Z")).toEqual({ shift: true, tab: true });
});
});
describe("recoverCsiTail — full CSI sequences (well-behaved terminals)", () => {
it("also matches ESC-prefixed forms (in case parse-keypress merged them)", () => {
expect(recoverCsiTail("\x1b[A")).toEqual({ upArrow: true });
expect(recoverCsiTail("\x1b[5~")).toEqual({ pageUp: true });
expect(recoverCsiTail("\x1b[Z")).toEqual({ shift: true, tab: true });
});
});
describe("recoverCsiTail — pass-through cases", () => {
it("returns null for unrelated input", () => {
expect(recoverCsiTail("hello")).toBeNull();
expect(recoverCsiTail("")).toBeNull();
expect(recoverCsiTail("a")).toBeNull();
});
it("returns null for paste markers (handled separately by accumulator)", () => {
expect(recoverCsiTail("[200~")).toBeNull();
expect(recoverCsiTail("[201~")).toBeNull();
expect(recoverCsiTail("\x1b[200~")).toBeNull();
});
it("returns null when Ink already populated a structured nav flag", () => {
// Ink parsed `\x1b[A` correctly and set upArrow — don't second-guess
// by also recovering from the raw `input` (the input would be ""
// anyway in that case, but the guard is defence-in-depth).
expect(recoverCsiTail("[A", { upArrow: true })).toBeNull();
expect(recoverCsiTail("[C", { rightArrow: true })).toBeNull();
expect(recoverCsiTail("[5~", { pageUp: true })).toBeNull();
});
it("returns null for already-structured Shift+Tab", () => {
expect(recoverCsiTail("[Z", { shift: true, tab: true })).toBeNull();
});
it("plain `[` or `[A` substring within other text is NOT rewritten", () => {
// The recover is exact-match on `input`. A user typing a Markdown
// link `[A](url)` should not have it eaten as up-arrow.
expect(recoverCsiTail("[A](url)")).toBeNull();
expect(recoverCsiTail("[")).toBeNull();
expect(recoverCsiTail("[ABC")).toBeNull();
});
});
describe("stripCsiFragments", () => {
it("removes paste markers (with and without ESC)", () => {
expect(stripCsiFragments("\x1b[200~hello\x1b[201~")).toBe("hello");
expect(stripCsiFragments("[200~hello[201~")).toBe("hello");
});
it("removes recognised arrow tails embedded in text", () => {
// An arrow tail that somehow ended up inside a paste blob — this
// can happen if the user pastes content immediately followed by
// an arrow key on a slow terminal. We scrub them out so no
// garbage text lands in the prompt buffer.
expect(stripCsiFragments("hello[Aworld")).toBe("helloworld");
expect(stripCsiFragments("a\x1b[5~b")).toBe("ab");
});
it("leaves non-fragment text alone", () => {
expect(stripCsiFragments("hello world")).toBe("hello world");
expect(stripCsiFragments("foo[](url)bar")).toBe("foo[](url)bar");
});
});
describe("STRIPPABLE_CSI_FRAGMENTS", () => {
it("includes both ESC-prefixed and bare forms of each tail", () => {
// Sanity check: every bare form has its ESC-prefixed sibling.
for (const frag of STRIPPABLE_CSI_FRAGMENTS) {
if (frag.startsWith("[")) {
expect(STRIPPABLE_CSI_FRAGMENTS).toContain(`\x1b${frag}`);
}
}
});
});
+58 -3
View File
@@ -21,9 +21,48 @@ describe("formatLoopError", () => {
expect(out).toMatch(/929,452 tokens/); // pretty-printed from the raw JSON
});
it("leaves non-overflow errors unchanged", () => {
const raw = new Error("DeepSeek 401: invalid api key");
expect(formatLoopError(raw)).toBe("DeepSeek 401: invalid api key");
it("401 → authentication hint with setup/env var fix", () => {
const raw = new Error(
'DeepSeek 401: {"error":{"message":"Authentication Fails, Your api key is invalid"}}',
);
const out = formatLoopError(raw);
expect(out).toMatch(/Authentication failed/);
expect(out).toMatch(/reasonix setup/);
expect(out).toMatch(/DEEPSEEK_API_KEY/);
// Inner error.message survives the unwrap
expect(out).toContain("Your api key is invalid");
});
it("402 → balance hint with top-up URL", () => {
const raw = new Error('DeepSeek 402: {"error":{"message":"Insufficient Balance"}}');
const out = formatLoopError(raw);
expect(out).toMatch(/Out of balance/);
expect(out).toMatch(/top_up/);
expect(out).toContain("Insufficient Balance");
});
it("422 → invalid parameter with the server's reason", () => {
const raw = new Error(
'DeepSeek 422: {"error":{"message":"Invalid value for `temperature`: must be between 0 and 2"}}',
);
const out = formatLoopError(raw);
expect(out).toMatch(/Invalid parameter/);
expect(out).toContain("temperature");
});
it("400 (non-overflow) → extracts the inner error message, drops the JSON wrapping", () => {
const raw = new Error(
'DeepSeek 400: {"error":{"message":"request body malformed at messages[3].role"}}',
);
const out = formatLoopError(raw);
expect(out).toMatch(/Bad request/);
expect(out).toContain("messages[3].role");
expect(out).not.toContain("{"); // JSON wrapping is gone
});
it("leaves non-DeepSeek-shaped errors untouched", () => {
const raw = new Error("socket hang up");
expect(formatLoopError(raw)).toBe("socket hang up");
});
it("tolerates an overflow error without a requested-tokens figure", () => {
@@ -32,6 +71,22 @@ describe("formatLoopError", () => {
expect(out).toMatch(/Context overflow/);
expect(out).toMatch(/too many tokens/);
});
it("context-overflow message mentions both the 1M V4 limit and the legacy 131k", () => {
const raw = new Error(
'DeepSeek 400: {"error":{"message":"This model\'s maximum context length is 131072 tokens. However, you requested 200000 tokens."}}',
);
const out = formatLoopError(raw);
expect(out).toMatch(/1M/);
expect(out).toMatch(/131k/);
});
it("tolerates an empty or malformed JSON body on the error payload", () => {
const raw = new Error("DeepSeek 500: ");
const out = formatLoopError(raw);
// 500 isn't in the remapped set, so it passes through as-is
expect(out).toBe("DeepSeek 500: ");
});
});
describe("healLoadedMessages", () => {
+201 -4
View File
@@ -9,11 +9,50 @@
import { describe, expect, it, vi } from "vitest";
import { DeepSeekClient } from "../src/client.js";
import { CacheFirstLoop } 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";
describe("isThinkingModeModel", () => {
it("deepseek-reasoner → true (legacy R1 alias)", () => {
expect(isThinkingModeModel("deepseek-reasoner")).toBe(true);
});
it("deepseek-v4-flash → true (default thinking)", () => {
expect(isThinkingModeModel("deepseek-v4-flash")).toBe(true);
});
it("deepseek-v4-pro → true (default thinking)", () => {
expect(isThinkingModeModel("deepseek-v4-pro")).toBe(true);
});
it("deepseek-chat → false (non-thinking compat alias)", () => {
expect(isThinkingModeModel("deepseek-chat")).toBe(false);
});
it("unknown models → false (safe default)", () => {
expect(isThinkingModeModel("gpt-4")).toBe(false);
expect(isThinkingModeModel("")).toBe(false);
});
});
describe("thinkingModeForModel", () => {
it("chat → disabled, reasoner → enabled (compat aliases pin the mode)", () => {
expect(thinkingModeForModel("deepseek-chat")).toBe("disabled");
expect(thinkingModeForModel("deepseek-reasoner")).toBe("enabled");
});
it("v4 models → enabled (docs default)", () => {
expect(thinkingModeForModel("deepseek-v4-flash")).toBe("enabled");
expect(thinkingModeForModel("deepseek-v4-pro")).toBe("enabled");
});
it("unknown models → undefined (let server decide)", () => {
expect(thinkingModeForModel("gpt-4")).toBeUndefined();
expect(thinkingModeForModel("anthropic-claude")).toBeUndefined();
});
});
interface FakeResponseShape {
content?: string;
reasoning_content?: string;
@@ -23,13 +62,25 @@ interface FakeResponseShape {
function capturingFetch(responses: FakeResponseShape[]): {
fetch: typeof fetch;
bodies: Array<{ messages: ChatMessage[] }>;
bodies: Array<{
messages: ChatMessage[];
extra_body?: { thinking?: { type?: string } };
reasoning_effort?: string;
}>;
} {
const bodies: Array<{ messages: ChatMessage[] }> = [];
const bodies: Array<{
messages: ChatMessage[];
extra_body?: { thinking?: { type?: string } };
reasoning_effort?: string;
}> = [];
let i = 0;
const fn = vi.fn(async (_url: any, init: any) => {
const body = init?.body ? JSON.parse(init.body) : {};
bodies.push({ messages: body.messages });
bodies.push({
messages: body.messages,
extra_body: body.extra_body,
reasoning_effort: body.reasoning_effort,
});
const resp = responses[i++] ?? responses[responses.length - 1]!;
return new Response(
JSON.stringify({
@@ -59,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();
@@ -143,4 +229,115 @@ describe("R1 reasoning_content round-trip", () => {
expect(assistant).toBeDefined();
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 });
const loop = new CacheFirstLoop({
client,
prefix: new ImmutablePrefix({ system: "s" }),
model: "deepseek-v4-pro",
stream: false,
});
for await (const _ev of loop.step("hello")) {
/* drain */
}
expect(bodies[0]!.extra_body?.thinking?.type).toBe("enabled");
expect(bodies[0]!.reasoning_effort).toBe("max");
});
it("pins thinking=disabled for deepseek-chat (non-thinking compat alias)", async () => {
const { fetch: fakeFetch, bodies } = capturingFetch([{ content: "done" }]);
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 */
}
expect(bodies[0]!.extra_body?.thinking?.type).toBe("disabled");
expect(bodies[0]!.reasoning_effort).toBe("max");
});
it("omits thinking entirely for unknown models (let the server decide)", async () => {
const { fetch: fakeFetch, bodies } = capturingFetch([{ content: "done" }]);
const client = new DeepSeekClient({ apiKey: "sk-test", fetch: fakeFetch });
const loop = new CacheFirstLoop({
client,
prefix: new ImmutablePrefix({ system: "s" }),
model: "some-third-party-model",
stream: false,
});
for await (const _ev of loop.step("hello")) {
/* drain */
}
expect(bodies[0]!.extra_body).toBeUndefined();
// reasoning_effort is always set — it's a benign field for models
// that don't know it (OpenAI just ignores unknown top-level fields).
expect(bodies[0]!.reasoning_effort).toBe("max");
});
});
+236 -17
View File
@@ -102,7 +102,10 @@ describe("CacheFirstLoop (non-streaming)", () => {
await loop.run("q");
expect(loop.stats.aggregateCacheHitRatio).toBeCloseTo(0.8);
expect(loop.stats.totalCost).toBeGreaterThan(0);
expect(loop.stats.savingsVsClaude).toBeGreaterThan(0.9);
// Savings vs Claude depends on which DeepSeek model is the loop's
// default. v4-pro lands around 0.85; v4-flash around 0.97. Test the
// lower bound so a future default swap doesn't churn this assertion.
expect(loop.stats.savingsVsClaude).toBeGreaterThan(0.8);
});
it("dispatches a tool call and loops until the model stops", async () => {
@@ -377,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({
@@ -386,18 +445,18 @@ describe("CacheFirstLoop (non-streaming)", () => {
fn: async () => "ok",
});
// First response: chaining tool call with a prompt-token count
// deliberately over 80% of DeepSeek's 131k window (131k * 0.8 = 104_857).
// 120k trips the guard.
// deliberately over 80% of DeepSeek V4's 1M window (1M * 0.8 =
// 800k). 900k trips the guard.
const responses: FakeResponseShape[] = [
{
content: "",
tool_calls: [{ id: "c", type: "function", function: { name: "probe", arguments: "{}" } }],
usage: {
prompt_tokens: 120_000,
prompt_tokens: 900_000,
completion_tokens: 50,
total_tokens: 120_050,
prompt_cache_hit_tokens: 90_000,
prompt_cache_miss_tokens: 30_000,
total_tokens: 900_050,
prompt_cache_hit_tokens: 700_000,
prompt_cache_miss_tokens: 200_000,
},
},
// Forced-summary response (no tools)
@@ -446,16 +505,17 @@ describe("CacheFirstLoop (non-streaming)", () => {
fn: async () => "ok",
});
const responses: FakeResponseShape[] = [
// Iter 0: chains a tool call, usage trips the guard.
// Iter 0: chains a tool call, usage trips the 80% guard against
// V4's 1M window.
{
content: "",
tool_calls: [{ id: "c1", type: "function", function: { name: "probe", arguments: "{}" } }],
usage: {
prompt_tokens: 120_000,
prompt_tokens: 900_000,
completion_tokens: 10,
total_tokens: 120_010,
prompt_cache_hit_tokens: 100_000,
prompt_cache_miss_tokens: 20_000,
total_tokens: 900_010,
prompt_cache_hit_tokens: 750_000,
prompt_cache_miss_tokens: 150_000,
},
},
// Iter 1: model wraps up normally after the tool result.
@@ -505,16 +565,17 @@ describe("CacheFirstLoop (non-streaming)", () => {
fn: async () => "ok",
});
const responses: FakeResponseShape[] = [
// 131k * 0.72 ≈ 94,320 tokens — squarely in the proactive band.
// V4's 1M window × 0.72 ≈ 720k tokens — squarely in the 60–80%
// proactive band without tripping the reactive 80% guard.
{
content: "",
tool_calls: [{ id: "c1", type: "function", function: { name: "probe", arguments: "{}" } }],
usage: {
prompt_tokens: 95_000,
prompt_tokens: 720_000,
completion_tokens: 10,
total_tokens: 95_010,
prompt_cache_hit_tokens: 70_000,
prompt_cache_miss_tokens: 25_000,
total_tokens: 720_010,
prompt_cache_hit_tokens: 550_000,
prompt_cache_miss_tokens: 170_000,
},
},
{ content: "done." },
@@ -643,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({
Loaded 100 of 117 files, more files were not shown because too many files have changed in this diff. Show more