Compare commits

...
117 Commits
Author SHA1 Message Date
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
esengine 7542aca687 feat(ui): show "N ready · building call M" during multi-tool turns (0.5.19)
Long assistant responses with many tool_calls used to render as a
single static "building tool call <write_file> · 37 chars" spinner
for 10–30s — user could see tokens being consumed but had no sense of
how many files were coming or how far along the stream was.

Each tool_call's `arguments` blob is now tried as JSON at every delta.
Once it first parses, the index is marked "ready" and the count goes
into subsequent `tool_call_delta` events. The UI label becomes
"building tool call (call 3) <write_file> · 127 chars · 2 ready"
so the user sees progress accumulating.

Dispatch timing is UNCHANGED — this is purely a visibility upgrade.
Mid-stream eager dispatch was considered and punted because it would
interact awkwardly with the repair step (truncation fix, storm
breaker, scavenge) that runs post-stream.

+6 tests locking down looksLikeCompleteJson (the gate that decides
when a streaming call counts as "ready"). 991 tests.
2026-04-23 20:18:10 -07:00
esengine 1e906bb577 fix(r1): round-trip reasoning_content on EVERY reasoner assistant turn (0.5.18)
0.5.15 scoped the fix too narrowly — only attached reasoning_content
when `tool_calls.length > 0`. DeepSeek's "thinking mode must be
passed back" rule applies to ANY R1-generated assistant message.

Symptom: plan approved → synthetic user message "implement it now" →
next API call 400s. The intermediate "plan submitted — awaiting
approval" plain-text R1 turn was persisted without its reasoning,
and R1 rejected the entire history the next time around.

Changes:
- assistantMessage() drops the tool_calls guard; reasoning attaches
  whenever the model emitted any (even on plain-text turns).
- Forced-summary path (no-tools fallback) now captures reasoning from
  the summary response.
- New syntheticAssistantMessage() stamps an empty-string
  reasoning_content on synthetic turns (Esc-abort notices) when the
  model is a reasoner, so R1's validator is satisfied even when no
  real reasoning exists. V3 stays clean.
- Test updated: plain-text reasoner turn now asserts reasoning
  DOES round-trip (reversed from 0.5.15's assumption).

985 tests.
2026-04-23 20:03:06 -07:00
esengine a8c367ad0c fix(citation): leading / resolves to project root, not filesystem root (0.5.17)
Symptom: user wrote a game design doc to `F:/Reasonix/game-design-doc.md`,
the model cited it as `[...](/game-design-doc.md)`, and Reasonix rendered
"✗ /game-design-doc.md → file not found" even though the file was
right there on disk.

Cause: `validateCitation` ran `isAbsolute(path)` on the raw URL. A model
writing `/foo.md` means "project-root relative" (Aider / Claude-Code
convention), but Node's isAbsolute returns true, so the validator
stat'd the literal `/foo.md` under the filesystem root and got ENOENT.

Fix: strip leading `/` or `\` before the absoluteness test. Drive-letter
paths (`C:\...`) still pass isAbsolute and are respected; plain
leading-slash paths become project-relative. Unix absolute citations
like `/etc/hosts` lose precision but are vanishingly rare in code
citations — if we need them we'll add an explicit scheme.

+2 markdown tests for the new leading-slash behavior (both `/` and `\`).
985 tests.
2026-04-23 19:57:49 -07:00
esengine 2d35cab39e fix(plan): actually stop the flicker — pause ticker, tighten clamp, stabilize onChoose (0.5.16)
0.5.14's clamp was insufficient. Three root causes the earlier fix missed:

1. TickerProvider kept pumping 120ms re-renders even while the picker
   was up — the memo'd PlanConfirm still re-evaluated on every tick
   because `onChoose` identity changed (handlePlanConfirm has `busy` in
   its deps; busy toggles during model streaming). Fix: disable the
   ticker while `pendingPlan` or `pendingShell` is set. No ticker = no
   re-render cadence to drive Ink redraws.

2. `clampBodyByLines` clamped SOURCE lines, not rendered rows.
   Markdown expands ~2× (wrap, code fences, heading blanks, list
   indent), so `rows - 18` source lines still overflowed on a 40-row
   terminal. Fix: divide by MARKDOWN_EXPANSION before clamping so the
   rendered output actually fits.

3. `handlePlanConfirm` identity churns — wrapped in a ref-stable
   `stableHandlePlanConfirm` so `React.memo(PlanConfirm)`'s shallow
   compare actually skips re-renders when `plan` + `projectRoot`
   haven't changed.

Together these pin the picker's rendered height to a known budget AND
eliminate the re-render loop that caused Ink to clear+redraw each
frame. The overflow-can't-scroll symptom is inherent to Ink's live
mode; only remedy is to make content fit, which the tightened clamp
now guarantees.
2026-04-23 19:54:19 -07:00
esengine 874d7df2f7 fix(r1): round-trip reasoning_content through tool loop (0.5.15)
DeepSeek R1 thinking mode 400s with "The reasoning_content in the
thinking mode must be passed back to the API" when a tool-loop
continuation replays an assistant message that had tool_calls but
no reasoning. Root cause: assistantMessage() stripped the field.

Fix: ChatMessage gains optional reasoning_content. Loop passes the
captured reasoning into assistantMessage; we attach it only when
the turn has tool_calls AND reasoning is non-empty — plain-text
R1 turns stay lean, deepseek-chat is unaffected.

+2 tests (loop-r1-reasoning): turn-2 body asserts the echoed
assistant message carries reasoning_content on a tool-call turn,
and does NOT carry it on a plain-text turn.
2026-04-23 19:50:18 -07:00
esengine 4d39744d99 feat(0.5.14): visible/durable/reachable + plan-flicker + pending-edit persistence
- !cmd bang output now persists via loop.appendAndPersist, so session
  resume sees the shell history the model already reasoned against.
- Subagent runs (run_skill · runAs:subagent) now emit cost/model/usage
  on their end event. App.tsx writes one row to ~/.reasonix/usage.jsonl
  per run; the completion line also shows $X inline. `/stats` and
  `reasonix stats` render a new "subagent activity" section with
  per-skill breakdown.
- `/resource [uri]` + `/prompt [name]` slashes with argument-level
  pickers (reusing 0.5.13's SlashArgPicker). No arg lists what every
  connected MCP server exposes; with arg reads via live McpClient
  stored on McpServerSummary. Display-only v1 — no loop injection.
  `/mcp` now hints toward these when servers expose resources/prompts,
  `/keys` gets an "MCP exploration" section, `/help` lists both.
- Bug A — plan picker flicker on small terminals: PlanConfirm's
  markdown body is now line-clamped to (rows − 18), and the component
  is React.memoed so tick-driven parent re-renders skip the heavy
  Markdown subtree when props are unchanged.
- Bug B — pending-edit queue wiped on crash: new
  src/code/pending-edits.ts checkpoints the queue to
  ~/.reasonix/sessions/<name>.pending.json on every parse. /apply
  and /discard clear the file; session resume restores it with a
  visible banner. deleteSession removes the sidecar too.

981 tests (+31). lint / typecheck / build clean.
2026-04-23 19:44:28 -07:00
esengine 74da4f2a92 revert /edit slash + fix picker blocking Enter on exact match (still 0.5.13)
Two small course-corrections on the 0.5.13 work-in-progress. Version
stays at 0.5.13 — these land before publish.

### 1. Remove /edit

The one-shot `/edit <file> <instruction>` slash was 99% redundant
with `@path/file.ts <instruction>`: the 0.5.5 `@`-mention already
inlines the file, and code-mode's system prompt already teaches the
model to output SEARCH/REPLACE blocks. `/edit` added only the
"output ONLY a block, no prose" hint — not worth a whole slash.

Reverted:
- case "edit" handler (slash.ts)
- SLASH_COMMANDS registry entry
- /help line
- /edit test describe block + "/help mentions /edit" + required-list
- "file" from the argCompleter union type (no consumer left; the
  `@` picker remains the single file-picker surface, avoiding two
  competing file-autocompletes)
- "file" branch in App.tsx's slashArgMatches memo + the trailing-
  space special case in pickSlashArg

Users who want one-shot edits type `@src/foo.ts fix the typo` —
clearer to read in history and the model obliges by default.

### 2. Picker blocked Enter after exact match

Typing `/preset smart` left the picker visible with one match
("smart") → Enter was intercepted and re-substituted the same value
instead of submitting the command. Fix: slashArgMatches memo now
returns null when the partial is a case-insensitive EXACT match for
an enum value (or a model id). Picker hides; Enter submits.

- Test added documenting that the detector itself remains kind-
  only — the hide-on-exact-match logic lives in the App-side memo
  so the detector stays UI-agnostic.

### Tests

946 (was 952; dropped 6 /edit-specific tests, added 1 regression
for the exact-match fix, dropped the File-picker-for-/edit detector
test since that path is gone). Lint + typecheck + build clean.
2026-04-23 19:08:14 -07:00
esengine 36f6d245f9 feat(ui): argument-level pickers for slash commands (0.5.13)
User feedback: "after I type `/edit` there's no hint about what files
exist — same for other commands with args." Fixed.

### Mechanism

SlashCommandSpec gains an `argCompleter` field:

- `"file"`    → file picker (reuses atFiles + rankPickerCandidates
                with mtime + recently-used ranking from 0.5.12)
- `"models"`  → DeepSeek model-id list fetched at startup
- `string[]`  → small enum (e.g. `["fast", "smart", "max"]`)
- omitted     → no picker, just a dim usage hint below the prompt

Attached to: /edit → file, /preset → enum, /model → models,
/plan → on/off, /harvest → on/off, /branch → off + a few N values.

`detectSlashArgContext(input, codeMode)` in slash.ts classifies the
buffer once the user has typed `/<cmd> ` — returns `{spec, partial,
partialOffset, kind}`. `kind` is "picker" (completable first-arg
position) or "hint" (past the first arg / no completer).

`src/cli/ui/SlashArgPicker.tsx` — new component mirroring the
SlashSuggestions / AtMentionSuggestions layout. Header row always
shows `/<cmd> <argsHint>  — <summary>` so even when no matches,
the user sees what's expected. Hint-only mode is a single dim row.

App.tsx: `slashArgSelected` state, `slashArgContext` memo,
`slashArgMatches` memo (dispatches on completer type), useEffect
clamp, `pickSlashArg` callback (splices at partialOffset; adds
trailing space for file picker so user can keep typing the
instruction; no trailing space for enum picks since those commands
take no further args). Wired into useInput arrow/Tab and
handleSubmit Enter intercept. Renders after SlashSuggestions +
AtMentionSuggestions.

### Tests (+11, suite 941 → 952)

tests/slash.test.ts — `detectSlashArgContext` suite covers: null
before name commit, null on unknown cmd, file picker for /edit in
code mode, contextual-command gating outside code mode, enum picker
for /preset, models completer for /model, /plan gated to code mode,
hint kind once partial has internal whitespace, picker with empty
partial (just-typed space), hint kind for free-form arg commands
like /commit.

Lint + typecheck + build clean. 952 tests, 7.5s.
2026-04-23 19:02:38 -07:00
esengine a44c23c0a8 feat(ui): @-picker recency ranking + /keys cheatsheet (0.5.12)
Two UX polishers bundled, closing out the A-E batch.

### D. `@` picker ranking by mtime + recently-used

Alphabetical sort was arbitrary on large repos — 500 files deep, the
first page was almost never what the user wanted. New ranking:

- Empty query → recently-used paths first, then mtime descending,
  then path alpha. "Recently used" = files touched by `read_file` /
  `edit_file` / `write_file` / `search_content` / etc. tool calls
  this session (20-slot LRU; resets on session change).
- Non-empty query → existing substring/prefix scoring, tiebreak by
  recently-used membership then mtime.
- Back-compat: `string[]` input with no recency list still returns
  input order (old tests pass unchanged).

Implementation:

- `listFilesWithStatsSync(root, opts)` — same walk as listFilesSync
  plus a statSync per file. Stat failures don't throw; the entry
  keeps `mtimeMs: 0` and sinks to the bottom of the recency bucket.
- `FileWithStats` / `PickerCandidate` / `RankPickerOptions` types
  exported for library callers.
- `rankPickerCandidates(files, query, limitOrOpts)` — overloaded:
  bare number still works (back-compat), or pass
  `{ limit, recentlyUsed }`.
- App.tsx: `atFiles` memo switched to listFilesWithStatsSync;
  `recentFilesRef` (useRef<string[]>) + `recordRecentFile(p)` LRU
  callback; `tool_start` event handler inspects `toolArgs` for
  `path` / `file_path` / `file` fields and feeds the LRU.

### E. `/keys` cheatsheet slash

Discoverability gap: `!` bang, `@` picker, `/` slash, Shift+Enter,
Ctrl+J, Ctrl+A/E, Esc, y/n — the kit is extensive but undocumented
in one place. `/keys` dumps a formatted table:

    Keyboard & prompt shortcuts:
      Enter                  submit the current prompt
      Shift+Enter / Ctrl+J   insert a newline
      ...

    Prompt prefixes:
      /<name>    slash command
      @<path>    inline a file (code mode)
      !<cmd>     run <cmd> as shell

    Pickers (slash + @-mention):
      ↑ / ↓      navigate
      Tab        insert without submitting
      Enter      insert + run/keep-editing

Added to SLASH_COMMANDS registry + cross-linked from `/help`.

### Tests (+9, suite 932 → 941)

- tests/at-mentions.test.ts — 5 new for rankPickerCandidates:
  mtime sort on empty query with FileWithStats, recently-used boost
  trumps mtime, non-empty query tiebreak by recent+mtime, back-compat
  input-order preservation for bare strings, numeric-limit literal
  as third arg.
- tests/slash.test.ts — 4 new for /keys: shortcuts listed, prefixes
  listed, pickers mentioned, /help cross-reference.

### Note on release cadence

A (0.5.9) + B (0.5.10) + C (0.5.11) + D + E were split across five
commits but each dist is cumulative — publishing only the final one
gets users everything. Going forward I'll bundle closer unless the
user asks otherwise.

Lint + typecheck + build clean. 941 tests, 8.3s.
2026-04-23 18:54:04 -07:00
esengine 337ded3839 feat(code): unified-diff preview for pending edit blocks (0.5.11)
Before /apply, the UI used to show only
    ▸ 2 pending edit block(s) — /apply or /discard
          src/a.ts  (-3 +4 lines)
          src/b.ts  (-1 +1 lines)
— a count summary, nothing about what was actually changing. Common
mistake shape: press y, look at git diff afterwards, discover the
model edited the wrong block / wrong file.

Now each pending block is rendered as a compact diff with ±2 lines of
context and a hard cap at 20 lines per block:

    ▸ 2 pending edit block(s) — /apply (or y) to commit · /discard (or n) to drop
          src/foo.ts  (-1 +1 lines)
            function foo() {
        -   const x = 1;
        +   const x = 2;
            return x;

      NEW src/bar.ts  (-0 +3 lines)
        + export const bar = 1;
        + export const baz = 2;
        + export default { bar, baz };

### Mechanism

`src/code/diff-preview.ts`:

- `formatEditBlockDiff(block, opts)` — shared leading/trailing lines
  collapse to context (default 2 lines each side, `… N unchanged lines
  above/below` when truncated). Middle divergence is `-old` / `+new`.
  Whole block capped at 20 lines with `… (N more diff lines — full
  content applies on /apply)` footer when exceeded. Empty-search
  (new file) case shows all-`+` lines.
- `formatAllBlockDiffs(blocks, opts)` — stitches each block's header
  (path + ±line counts, `NEW` prefix for new files) + its diff body,
  separated by blank lines.

Zero new deps. Small hand-rolled helper using prefix/suffix-compare;
sufficient for the typical SEARCH/REPLACE shape (small change inside
a function body, wrapped in a few lines of surrounding context).
Myers-diff quality is not needed — the model's SEARCH block already
minimizes context.

`formatPendingPreview` in App.tsx dropped its own summary line list
(paths now come from the per-block diff header) and its local
`countLines` helper (moved to diff-preview.ts alongside its only
consumer).

### No colors yet

Plain text, `-` / `+` / ` ` prefixes. ANSI colorization would need
Ink component plumbing that isn't worth the complexity for v1 —
the prefix convention is clear and universal (git / hunks / etc.).

### Tests (+10, suite 922 → 932)

tests/diff-preview.test.ts — new-file all-`+`, context collapse for
shared prefix/suffix, maxLines truncation with footer, leading and
trailing hidden-context annotations, single-line edits, custom
indent, multi-block formatAllBlockDiffs (path+counts headers, blank
separators, empty-input).

Lint + typecheck + build clean. 932 tests.
2026-04-23 18:47:01 -07:00
esengine 8ec6c630bd feat(slash): /edit <file> <instruction> — one-shot surgical edit (0.5.10)
One-liner shortcut for "change this one thing in this one file" —
faster than the multi-turn code-mode dance of "explain the file",
"here's my plan", "apply", etc. Code mode only.

### Mechanism

Zero new code paths. The slash is sugar: it builds a resubmit text of

    @<file> <instruction>

    Output ONLY a SEARCH/REPLACE block for this one edit. No prose,
    no explanation.

and hands that back through the normal turn machinery:

- 0.5.5's `@`-mention expansion inlines `<file>` under
  `[Referenced files]` so the model sees the current content.
- Code-mode's SEARCH/REPLACE handling already catches the output
  into `pendingEdits` (0.4.0+).
- The existing y/n confirm gate fires on the next event.

So `/edit src/foo.ts fix the typo` becomes equivalent to the user
typing `@src/foo.ts fix the typo. Output ONLY a SEARCH/REPLACE
block…` — the value is (a) discoverability via /help and slash
autocomplete, (b) the guaranteed-good prompt format without the user
having to remember it.

### Validation

- Outside code mode (no `codeRoot` in SlashContext) → refusal with a
  pointer to `reasonix code <dir>`.
- Missing file arg → usage hint.
- Missing instruction → usage hint with the file name echoed back.

### /help + discovery

Added to the slash autocomplete registry (`contextual: "code"` so
it only surfaces in code mode) and to the /help code-mode block.

### Tests (+6, suite 916 → 922)

tests/slash.test.ts — /edit describe block covers: non-code-mode
refusal, missing file, missing instruction, resubmit shape
(contains `@file` + instruction + SEARCH/REPLACE + ONLY), multi-
word instruction preservation. Plus `/help mentions /edit` and
`edit` added to the `SLASH_COMMANDS registry contains every handler`
required-list.

Lint + typecheck + build clean. 922 tests.
2026-04-23 18:41:12 -07:00
esengine a787272ceb feat(ui): collapse large user pastes in Historical display (0.5.9)
Pasting a stack trace / log dump / sample file flooded the Historical
scrollback with a massive block, hiding prior turns. Now user input
that exceeds a threshold renders as:

    ▸ pasted 2.3 KB (84 lines) — first 10 shown, full text sent to model
    line 1
    …
    line 10
    … (74 more lines)

The MODEL still receives the full text. Only the displayed row
collapses — `loop.step(modelInput)` gets the original string
(including any `@`-mention expansion) unchanged.

### Mechanism

- `src/cli/ui/paste-collapse.ts` — `formatLongPaste(text, opts)` pure
  helper. Collapse triggers when line count > 40 OR char count > 2000
  (defaults, override via opts). Head shows 10 lines; remaining
  footer reads "… (N more lines)". Byte header formats B/KB/MB.
- App.tsx — wired at the user-row push site in handleSubmit
  (between the UserPromptSubmit hook gate and the loop.step dispatch).
  The `pasteDisplay.displayText` goes to the Historical row; the
  existing `modelInput` variable (raw or `@`-expanded) goes to the
  loop.

### Scope

Affects only the regular user-message row. Separate paths for
`!`-bang commands, `@` expansions, and slash outputs are untouched.
Skipped on short messages (pass-through, no allocation overhead
beyond a `split("\n")`).

### Tests (+10, suite 906 → 916)

tests/paste-collapse.test.ts covers: short pass-through, multi-line
pass-through, line-threshold collapse, char-threshold collapse,
KB/MB formatting, 1-vs-N-more-lines pluralization, custom
thresholds, custom headLines, zero remaining (head covers all),
exported defaults.

Lint + typecheck + build clean. 916 tests.
2026-04-23 18:37:26 -07:00
esengine 0ca16d6e2d feat(ui): !cmd bash-mode prefix — user-typed shell passthrough (0.5.8)
Claude-Code-style bash mode. User types `!ls src/` or `!git status`;
Reasonix runs the command in the sandbox root, shows both the command
and its output, and appends the combined text to the conversation log
so the next model turn has the context automatically.

Faster than round-tripping through the model just to cat a file or
check git state, and closes a common UX gap vs. Claude Code.

### Mechanism

- `src/cli/ui/bang.ts` — `detectBangCommand(text)` returns the command
  body (whitespace-trimmed) or null. Only a LEADING `!` counts; `!`
  alone / `!   ` returns null; `echo !hi` doesn't trigger (the `!`
  isn't at position 0).
- `formatBangUserMessage(cmd, output)` — prepends a `[!cmd]\n`
  header so the model can distinguish user-typed shell output from
  its own `run_command` tool results (which are `role: tool`,
  structurally different).
- App.tsx handleSubmit intercept — fires AFTER the y/n fast-path (so
  pending edits still resolve cleanly) and BEFORE slash parsing:
  - Push `role: "user"` Historical row with the raw `!cmd` text.
  - `await runCommand(cmd, { cwd: codeMode?.rootDir ?? cwd,
    timeoutSec: 60, maxOutputChars: 32_000 })`.
  - Push `role: "info"` Historical row with
    `formatCommandResult(cmd, result)`.
  - `loop.log.append({ role: "user", content: formatBangUserMessage
    (cmd, formatted) })` so the next step() includes it in
    buildMessages.
  - setBusy true/false around the run so PromptInput reflects the
    in-flight state.
  - Catch errors → warning row, don't log.

### No allowlist gate

User-typed `!` is explicit consent (consistent with Claude Code; the
allowlist exists to bound what the MODEL can do with `run_command`,
not what the user chooses by hand). If someone wants stricter gating
later a `REASONIX_BANG_CONFIRM=1` toggle could layer on — out of
scope here.

### Known limitation: session durability

`loop.log.append` updates in-memory only. On session resume, the bang
output is gone (the session file didn't see it). The next actual
step() does appendAndPersist for the next user turn, and the model
sees this bang output live within the same session either way.
Treating bang as ephemeral keeps the fast-path simple; durable
capture could land later if real usage surfaces demand.

### /help + discovery

/help gains a "Shell shortcut" section documenting `!cmd` with
example commands (`!git status   !ls src/   !npm test`), plus a
"File references" section covering the `@` picker from 0.5.5 / 0.5.7
that was undocumented there.

### Tests (+9, suite 897 → 906)

tests/bang.test.ts — detectBangCommand covers: body extraction,
whitespace trim, non-bang pass-through, `!`-alone / blank body,
mid-string `!` rejection, embedded-trailing-`!` preservation,
multi-word with flags/quotes. formatBangUserMessage covers header
prepending and verbatim body preservation.

Lint + typecheck + build clean. 906 tests, 8.6s.
2026-04-23 18:31:30 -07:00
esengine ecf2ea372b feat(ui): @mentions picker + post-build bundle smoke test (0.5.7)
Two shipped, both extending 0.5's foundation:

### 1. @mentions picker UI

0.5.5 shipped `@path/to/file` inline expansion but made the user type
the full path. 0.5.7 adds a picker that mirrors the existing
/slash autocomplete: type `@` (with optional partial) in code mode,
get a filtered file list with ↑/↓ navigation and Tab/Enter pick.

- `listFilesSync(root, opts)` — sync recursive walk, skips
  node_modules / .git / dist / build / .next / etc. + any dot-dirs.
  Caps at 500 results by default. Forward-slash paths on all
  platforms. 10-50ms on moderate repos — fits the TUI's single-turn-
  per-tick model cleanly.
- `detectAtPicker(input)` — returns `{query, atOffset}` when the
  buffer ends with an in-progress mention; `null` otherwise. Distinct
  from `AT_MENTION_PATTERN` which finds completed mentions anywhere
  for expandAtMentions.
- `rankPickerCandidates(files, query, limit)` — case-insensitive
  substring filter with a boost for basename-prefix matches. Empty
  query returns the first `limit` candidates alpha.
- `AtMentionSuggestions.tsx` — same shape as `SlashSuggestions`
  (matches null = hide, empty = "no matches", array = highlight
  selected cyan/bold). Shows basename bold + dir dimmed à la
  VS Code Quick Open.
- App.tsx wiring: `atFiles` memo (walk on rootDir change), `atPicker`
  / `atMatches` memos, `atSelected` state with useEffect clamp.
  Arrow keys + Tab in useInput (before slash so they don't conflict
  — mutually exclusive by construction). Enter in handleSubmit
  substitutes at the `@` offset and appends a space (space auto-
  dismisses the picker, next Enter submits).
- Limitation intentionally not fixed: files created mid-session by
  edit tools won't appear in the picker until next launch. User can
  always type the full path. Rebuilding the list on every turn would
  be wasteful for the 95% case.

### 2. Bundle smoke test

v0.5.4 shipped to npm with a tokenizer path resolution bug that
crashed on first API call. The unit tests were fine — they load
modules from src/, which doesn't exercise the post-bundle directory
layout. These two tests close that gap:

- `dist/index.js`: dynamic import (via file:// URL on Windows),
  invoke `truncateForModelByTokens` to force a tokenizer load. ENOENT
  ⇒ fail.
- `dist/cli/index.js`: spawn with `DEEPSEEK_BASE_URL=127.0.0.1:1` so
  fetch fails fast. Preflight's tokenizer load runs BEFORE fetch, so
  if the bundled layout can't find the data file we see the ENOENT
  in stderr. If tokenizer loads fine, we see connection-refused and
  the test passes.
- Both tests skip when the bundle is absent (dev runs that haven't
  built yet). CI runs `build` before `test` → always exercised.

Would have caught 0.5.4's regression pre-publish.

### Tests (+23, suite 874 → 897)

- tests/at-mentions.test.ts — 7 new for detectAtPicker, 2 for
  AT_PICKER_PREFIX vs AT_MENTION_PATTERN sanity, 6 for
  rankPickerCandidates (empty query, substring, basename-prefix
  boost, path-prefix, no-match, limit), 6 for listFilesSync (recurse,
  forward slashes, ignore dirs, dotfile inclusion, custom ignores,
  maxResults cap, unreadable root).
- tests/bundle-smoke.test.ts — 2 tests for lib + CLI bundle
  tokenizer resolution.

Library exports: `detectAtPicker`, `listFilesSync`,
`rankPickerCandidates`, `AT_PICKER_PREFIX`, `DEFAULT_PICKER_IGNORE_DIRS`,
`ListFilesOptions`.

Lint + typecheck + build clean. 897 tests, 8.1s.
2026-04-23 18:14:46 -07:00
esengine 335de43db5 fix(tokenizer): resolve data-file path in bundled builds (0.5.6)
**Critical production bug.** Since 0.5.0 introduced the tokenizer, any
bundled `reasonix run` / `code` / `chat` crashed with ENOENT on the
first API turn after 0.5.4 put the tokenizer on the hot path.

Root cause: `resolveDataPath()` used
`join(dirname(import.meta.url), "..", "data", "deepseek-tokenizer.json.gz")`.

- In dev (`src/tokenizer.ts`) → resolves to `data/` ✓
- In the bundled CLI (`dist/cli/index.js`) → `dist/cli/` + `..` +
  `data/` = `dist/data/` ✗ — the data file ships at PACKAGE ROOT per
  package.json `files` entry; `dist/data/` doesn't exist.

Why this slipped through: before 0.5.4, `countTokens()` was only
called from the opt-in `/context` slash. Casual smoke tests and unit
tests (which run tokenizer.ts directly from src/) never hit the
bundled resolution. 0.5.4's preflight put `countTokens()` on every
step() call — so the first user-facing turn after `npm publish 0.5.4`
would have crashed.

Fix: `resolveDataPath()` now tries multiple candidate paths and
returns the first one that `existsSync`:

1. `REASONIX_TOKENIZER_PATH` env override (unchanged).
2. `../data/...` — dev + bundled `dist/index.js`.
3. `../../data/...` — bundled CLI at `dist/cli/index.js`.
4. `require.resolve("reasonix/package.json")` root — fallback for
   unusual bundlers.

Also falls back to `process.cwd() + data/...` if all candidates
missed, so readFileSync surfaces a concrete path in the error rather
than silently missing.

Caught via live `DEEPSEEK_API_KEY=... node dist/cli/index.js run
"hi"` against the actual bundled output. Unit tests alone would not
have caught this (they load src/tokenizer.ts directly, bypassing
the bundle path). Follow-up consideration: an integration test that
runs the bundled CLI against a fake API response — out of scope here.

874 tests still pass. Lint + typecheck + build clean.
2026-04-23 17:58:35 -07:00
esengine af077ddb24 feat: @file mentions in code mode + session-load heal → tokens (0.5.5)
Two shipped in one release, both closing out the 0.5 arc:

### 1. Session-load heal migrated to tokens

0.5.2 and 0.5.3 made dispatch truncation, /compact, and auto-compact
token-aware. Session load was the last char-based truncation surface;
now closed. CJK tool results in a resumed session come back at the
same effective context footprint as English instead of slipping past
the old 32k-char cap at 2× the token cost.

- `healLoadedMessagesByTokens(messages, maxTokens)` — sibling of the
  existing char-based `healLoadedMessages`.
- `fixToolCallPairing(messages)` — pure helper extracted so both
  variants reuse the structural tool_calls ↔ tool pairing pass.
- Session-resume call in loop.ts constructor switched to the token
  variant with `DEFAULT_MAX_RESULT_TOKENS`. Stderr "healed" line now
  reads "shrunk N tokens of oversized tool output" instead of chars.
- buildMessages's per-turn heal (hot path) stays on the char variant
  — avoids a per-turn tokenizer pass on every tool message.

### 2. `@file` mentions in code mode

User types `@src/loop.ts` → the model sees the file content inlined
under a "Referenced files" block:

    look at @src/loop.ts and explain

    [Referenced files]
    <file path="src/loop.ts">
    ...
    </file>

The user's original text is preserved verbatim; expansion is append-
only so the display stays clean and the model can cite the file
unambiguously.

- Regex `(?<=^|\s)@([a-zA-Z0-9_./\-]+)` — requires word boundary so
  `[email protected]` and `foo@bar` don't trigger. Trailing sentence
  period (`@foo.ts.`) is stripped before lookup.
- Sandbox: relative paths only, resolved against `rootDir`, no `..`
  escape, no absolute paths. Violations get
  `<file path="..." skipped="escape"/>` so the model sees the refusal.
- `DEFAULT_AT_MENTION_MAX_BYTES = 64 KB` (matches tool-result cap
  ballpark). Larger → skipped="too-large" with byte count.
- Missing / not-a-regular-file → skipped with reason.
- De-dupe: same file referenced twice inlines once.
- UI feedback: an info row lists inlined/skipped files so the user
  sees what reached the model.
- Only active in code mode (codeMode.rootDir). Plain chat mode
  doesn't expand — file references there are ambiguous.

### Tests (+15, suite 859 → 874)

- tests/at-mentions.test.ts — regex: boundary matching, email
  rejection, multi-mention; expansion: inline content, de-dupe,
  multiple distinct files, missing/escape/absolute/too-large skips,
  trailing-dot stripping, directory rejection.

Library exports: `expandAtMentions`, `AT_MENTION_PATTERN`,
`DEFAULT_AT_MENTION_MAX_BYTES`, `AtMentionExpansion`,
`AtMentionOptions`. Plus `healLoadedMessagesByTokens` and
`fixToolCallPairing` from loop.ts.

Lint + typecheck + build clean. 874 tests, 5.2s.
2026-04-23 17:48:50 -07:00
esengine 84ea648c84 feat(loop): preflight context-size check before each request (0.5.4)
Reactive auto-compact (60%/80% on prior prompt_tokens) keys off the
PREVIOUS turn's server usage, so a fresh resumed session — or one new
oversized tool result — can push the current turn's buildMessages
straight past 131,072 tokens and make DeepSeek 400 with "maximum
context length" before we see any usage number. Preflight closes that
hole by estimating locally before sending.

Mechanism:

- `estimateRequestTokens(messages, toolSpecs)` in src/tokenizer.ts:
  `estimateConversationTokens(messages) + countTokens(JSON.stringify
  (toolSpecs))`. Mirrors the arithmetic `/context` slash already uses
  so the two numbers don't drift.

- loop.step() injection right after buildMessages(). If the estimate
  exceeds 95% of `DEEPSEEK_CONTEXT_TOKENS[model]` (fallback
  `DEFAULT_CONTEXT_TOKENS`), run `compact(1_000)` and rebuild
  messages from the shrunk log. Warning event names the preflight
  path + tokens saved.

- When there's nothing to compact (first-ever turn with a bulky
  system prompt, for example), still yield a warning naming the
  preflight estimate + "nothing to auto-compact — DeepSeek will likely
  400". User sees the reason before the crash, can /forget or /clear.
  We don't short-circuit the request — let DeepSeek decide; its 400
  catch path already surfaces a useful hint.

- Non-branching AND branching paths share the `messages` variable
  from the outer buildMessages call, so the one injection covers
  both. Forced-summary fallback keeps its own path (a preflight
  there would be too late; the summary is the recovery step).

Tests (+3, suite 856 → 859) in tests/preflight.test.ts:

- Fires when estimate > 95%: compact runs, "pre-compacted N tool
  result(s), saved M tokens" warning appears, loop still completes.
- Stays silent when estimate is comfortably under 95%.
- Warns (but does not block) when over 95% with nothing to compact.

Per-test context budgets are set by mutating `DEEPSEEK_CONTEXT_TOKENS
[TEST_MODEL]` — the table is `Record<string, number>` so the write
is well-typed; teardown deletes the key. Seeded tool results are
properly paired with a prior assistant.tool_calls so
healLoadedMessages doesn't strip them as orphans (which would make
preflight never fire).

Lint + typecheck + build clean. 859 tests, 5.0s.
2026-04-23 17:32:09 -07:00
esengine 2d95c5787d feat(loop): token-aware /compact + auto-compact (0.5.3)
0.5.2 put the DeepSeek V3 tokenizer on the dispatch hot path to cap
NEW tool results by real tokens. 0.5.3 extends that to the live log:
/compact and auto-compact now shrink existing tool results by tokens
too, closing the last surface where CJK text slipped past a char cap
at 2× the intended context cost.

Mechanism:

- `shrinkOversizedToolResultsByTokens(messages, maxTokens)` in
  src/loop.ts — sibling of the char-based `shrinkOversizedToolResults`.
  Fast-pathes tool entries whose length ≤ cap (tokens ≤ length
  guarantee); otherwise tokenizes each candidate twice (before +
  after `truncateForModelByTokens`) to report exact tokensSaved.
  Never tokenizes the full input (same 0.5.2 guard against BPE
  O(n²) on pathological repetitive content).

- `loop.compact(maxTokens = 4000)` now shrinks by tokens and returns
  `{ healedCount, tokensSaved, charsSaved }` (was `{ healedCount,
  charsSaved }`). Persists to the session file when present.

- Auto-compact thresholds in `step()`:
  · 60%-80% band: soft compact at 4000 tokens/result (was 16k chars,
    which was 4k tokens in English but 16k tokens in CJK).
  · >80% band: hard compact at 1000 tokens/result (was 4k chars).
  Warnings report exact tokensSaved instead of `charsSaved / 4`.

- `/compact [N]` slash cap semantic flipped from chars to tokens
  (default 4000). The `info` line now reads "saved N tokens
  (M chars)". Help text + suggestion hint updated.

- Session-load heal (`healLoadedMessages`) left on the char cap so
  stored session files keep loading under their existing semantics.
  Live compaction and dispatch-time truncation are the only two
  surfaces that went token-aware.

Tests (+6, suite 850 → 856):

- tests/compact-tokens.test.ts — small-tool no-op, oversize shrink,
  input non-mutation, user/assistant protection, CJK parity, fast
  path by length.
- tests/loop.test.ts — seeded log content in the two auto-compact
  tests reshaped from `"Z".repeat(N)` to realistic log lines (was
  hitting BPE pathological path; also the 60%-80% warning now
  reads "4k tokens" instead of "16k" chars).
- tests/slash.test.ts — /compact assertions updated for token-based
  output ("saved N tokens", "N tokens each"); test content reshaped
  to realistic log lines.

Breaking change: library callers that pass an explicit number to
`loop.compact(N)` expecting chars will now get a tighter cap (4000
tokens ≈ 16k chars English, ~4k chars CJK). Fail mode is "compaction
is more aggressive than expected," which is the safe direction.

Lint + typecheck + build clean. 856 tests, 5.1s.
2026-04-23 17:21:02 -07:00
esengine 19a2b8d2be feat(tools): token-aware tool-result truncation at dispatch (0.5.2)
Before: every tool result was char-capped at 32K chars (8K English
tokens, but 16K+ tokens for CJK — Chinese/Japanese/Korean tool output
slipped past the budget at 2× the intended context cost).

After: dispatch truncates by REAL DeepSeek V3 tokens, using the
tokenizer that shipped in 0.5.0. Default 8K tokens per result, same
effective footprint regardless of char density.

Mechanism (src/mcp/registry.ts:truncateForModelByTokens):

- Fast path `s.length <= maxTokens` — every token is ≥1 char, so
  length bounds tokens. Skip tokenize entirely for small results.
- Intermediate check for moderate strings (`length <= maxTokens * 4`)
  — tokenize once to confirm it really is over budget.
- For large strings: char-slice head + tail by budget, tokenize the
  slices (NOT the full input), shrink on overshoot. 1–2 iterations per
  slice, bounded at 6. We explicitly never tokenize the whole input —
  pathological repetitive content (`"A".repeat(50_000)`) costs 30s+
  in the pure-TS BPE and is bounded to small slices.
- Dropped-tokens count in the marker is estimated from the per-slice
  char/token ratio (marker reads "~N tokens") so we don't pay a full
  tokenize just for diagnostics.

Wire-up:

- src/tools.ts — `ToolRegistry.dispatch` accepts both `maxResultChars`
  (legacy) and `maxResultTokens` (new). Both apply if both set; the
  tighter one wins. Char-only callers keep their old behavior.
- src/loop.ts — hot-path dispatch switched from
  `maxResultChars: 32_000` to `maxResultTokens: DEFAULT_MAX_RESULT_TOKENS`
  (8_000). Session-healing paths still use chars (preserves backwards
  compat on loaded session files).
- `DEFAULT_MAX_RESULT_TOKENS` and `truncateForModelByTokens` exported
  via src/index.ts for library consumers.

Tests (+9, suite 841 → 850):

- tests/truncate-tokens.test.ts — fast-path, short-string verify,
  CJK cap parity with English, head+tail preservation, zero-budget,
  empty input, marker format.
- tests/loop.test.ts — existing "pre-clips at dispatch" test reshaped
  to use realistic log-line content (was `"A".repeat(50_000)` which
  hit the BPE O(n²) pathological path, 46s+ in the suite).

Lint + typecheck clean. Suite now 5.2s total.
2026-04-23 16:52:23 -07:00
esengine ca27ca50bf fix(shell): reject shell operators (|, >, <, &, &&, ||, 2>) with a clear error (0.5.1)
Before: model writes `dir | findstr foo` → tokenizer produced `["dir",
"/b", "|", "findstr", "foo"]` → quoteForCmdExe wrapped `|` as `"|"`
(literal) → cmd.exe passed `|` as an argument to dir → no pipe, no
error, silent wrong output. The 0.4.26 memory flagged this as a known
issue; encoding fix from that release made the failure visible but
didn't address the root confusion.

After: detectShellOperator() walks the raw command with quote-tracking
and returns the first unquoted operator token at a token boundary.
runCommand rejects before spawn with:

  run_command: shell operator "|" is not supported — this tool spawns
  one process, no shell expansion. Split into separate run_command
  calls and combine the output in your reasoning...

Quoted operators (`grep "a|b" file.txt`) and chars embedded in larger
tokens (`--flag=1&2`) pass through — those are literal argv bytes.
Matches the tool's stated "no shell expansion, no pipes, no redirects"
contract; turns the silent failure into a loud, actionable one.

Tool description updated to document the rejection + the quote-it-as-
a-literal workaround so the model learns the constraint from the spec.

Tests: 841 (+13 covering pipe, redirect, fd-redirect, &&/||, stuck-
redirect, quoted operators, embedded operators).
2026-04-23 16:38:27 -07:00
esengine d4615d6e76 chore(0.5.0): fix CI + add animated SVG logo
CI fix — biome lint surfaced 9 errors on the 0.5.0 commit:
- tokenizer.ts: Infinity → Number.POSITIVE_INFINITY (style/useNumberNamespace)
- tokenizer.ts: formatter wrap on the CJS fallback branch
- StatsPanel.tsx: noArrayIndexKey on the Wordmark map — restructured to a
  module-level WORDMARK_STYLES table keyed by char+color pair, dropped
  the `i` parameter entirely (previous biome-ignore comment only
  suppressed one of two sites the rule fires on)
- various whitespace / line-wrap fixes from `biome check --write`

Animated SVG logo at docs/logo.svg, embedded at the top of README:
- Concentric diamond brand mark (◈) with three layers of motion:
  slow rotation (18s), outer-stroke pulse (2.4s), inner-fill breathing
- REASONIX wordmark in the same cyan → fuchsia gradient the TUI uses,
  so the README and the running app share one visual identity
- Tagline underneath for SEO-style context
- Colors (~4.5:1 contrast on both GitHub dark and light) — no
  prefers-color-scheme switching needed

828 tests, lint + typecheck clean.
2026-04-23 09:34:25 -07:00
esengine 9eff2e2cfc feat(0.5.0): Reasonix visual identity + DeepSeek tokenizer + models/pricing/context
Visual redesign — drop the generic vertical bars for a Reasonix-native
design language. The UI should be recognizable as ours at a glance:

- ◈ REASONIX wordmark in truecolor gradient (cyan → violet), with
  breathing animation — slow when idle, faster when the model is
  thinking, so the app's state is readable from the edge of vision.
- Geometric role glyphs replace all text labels: ◇ user · ◆ assistant ·
  ▣ tool · ▥ tool-err · ▲ warn · ✦ error. Consistent geometric family,
  distinct per role, no overlap with Claude / Cursor / Cline.
- Streaming assistant glyph pulses ◆↔◇ at ~480ms — visible heartbeat
  during R1's long (20-90s) pre-first-byte silence.
- Turn separators render "─── ◆ ───" with the Reasonix mark centered.
- Responsive StatsPanel: stacks metrics vertically on <120-col
  terminals (SSH, split-pane); inline when there's room. Context
  cell gains a 10-cell progress bar in the stacked layout.
- Cold-start cache hit ratio (turn ≤ 3) renders dim gray with a
  "(cold start)" hint instead of red — new users stopped reading
  "0% cache on turn 1" as a configuration error.
- Tool results tail-truncate by default (useful signal is usually at
  the end). ERROR-prefixed results keep the first line + a tail.
- Modal footers gain "[↑↓] navigate · [Enter] select · [Esc] cancel"
  hints; Esc actually cancels now (ShellConfirm → deny, PlanConfirm →
  cancel); SingleSelect gained an optional footer slot.
- Wait-phase messaging (pre-first-byte, R1 reasoning, branching,
  tool-call streaming) gets visible yellow italic instead of dim —
  users had been misreading the dim variant as "frozen".

New features:

- Pure-TS port of DeepSeek's V3 tokenizer (vocab + merges + pre_tokenizer
  from the official tokenizer.json). Bundled as data/deepseek-
  tokenizer.json.gz (1.74MB, slimmed + gzipped from 7.5MB). Zero new
  deps — uses built-in zlib. Encodes ~12k tokens of mixed source in
  ~40ms. scripts/prepare-tokenizer.ts regenerates the bundle from
  upstream.
- /context slash — renders a breakdown of the next request's tokens:
  system prompt, tool specs, per-turn log, top 5 heaviest tool results.
  Answers "where is my context going?" directly; closes the gap where
  StatsPanel showed ctx % without saying why.
- /models slash — fetches DeepSeek's live model catalog via
  GET /models. Renders the list with the current model marked.
- /model <id> now soft-validates against the fetched catalog (warn
  but still switch — accommodates newly-released models we haven't
  indexed). DeepSeekClient gains a listModels() method.

Loop + billing correctness:

- Tool results pre-clipped at dispatch time (default 32k chars) via
  ToolRegistry.dispatch({ maxResultChars }). Oversized results no
  longer bloat the AppendOnlyLog or the persisted session file.
- New proactive-compact tier: when promptTokens / ctxMax crosses 60%
  (before the existing 80% reactive guard), shrink oversized tool
  results to 16k chars. Catches slow-growth patterns before they
  compound into a forced summary.
- DEEPSEEK_PRICING updated to the current unified rates (¥0.2 / ¥2 /
  ¥3 per 1M at cache-hit / cache-miss / output; USD 0.028 / 0.28 /
  0.42 at 7.2 CNY/USD). chat and reasoner are now priced identically
  at source. Stats dashboard figures were systematically high under
  the old tiered constants — new sessions bill correctly.
- Context display switches to binary-K (128K) to match DeepSeek's
  marketing label. DEEPSEEK_CONTEXT_TOKENS stays at 131072 — only
  the formatter divisor changed.

OSC 8 clickable hyperlinks in markdown were attempted and reverted:
Ink 5 strips \x1b / \x07 from Text output, so file:// links never
reach the terminal. Documented as a known limit; re-visit with a
future Ink release or raw-stdout approach.

828 tests (14 new: tokenizer golden cases + /context + /models +
listModels + pricing unification + proactive compact). Lint +
typecheck + build clean.
2026-04-23 09:28:40 -07:00
esengine c2f8e9b734 feat(0.4.28): reasonix code defaults harvest OFF — opt in via --harvest
Pillar 2 harvesting fires an extra V3 call per turn to extract a typed
plan state (subgoals/hypotheses/uncertainties/rejectedPaths) from R1's
reasoning_content. Cost ~10-15% per turn. Closer audit of who actually
consumes the output:

- subgoals / hypotheses / rejectedPaths — purely cosmetic, only rendered
  in PlanStateBlock. No programmatic consumer. Can mislead users by
  giving structured-looking output extra perceived authority (today's
  citation work was triggered by hallucinated "hypotheses" that looked
  thoughtful).
- uncertainties.length — single real downstream use, drives self-
  consistency branching when count exceeds threshold. Could be replaced
  with a cheap heuristic on the raw reasoning text.

For coding tasks specifically, branching is rarely on (default budget=1)
and the cosmetic display value doesn't justify the per-turn premium.
Flip the default off; users who genuinely want the plan state surfaced
can pass --harvest. `reasonix chat` is unchanged — preset behaviour
there still controls harvest.

799 tests, lint + build clean.
2026-04-23 05:13:20 -07:00
esengine d52599ec44 feat(0.4.27): citation-first answers — validated [text](path:line) links + broken-citation surface
Anti-hallucination intervention for evaluative tasks. Two real R1 sessions
where the model invented "Resources/Prompts/Progress not implemented" gaps
that had been shipped months ago (v0.4.5, v0.4.8) motivated this — same
hallucination shape both times, across independent prefixes. The fix is
structural: force the model to ground every codebase claim in a clickable
citation, validate them, render broken ones in red so the user sees
fabrications instantly.

- markdown.tsx: parse [text](url) links (was unsupported — rendered as
  literal). External URLs (https://, mailto:, //) → blue underline.
  Citation-shaped URLs (path / path:line / path:start-end / path#L42) →
  validated against projectRoot, valid = cyan underline, broken = red
  strikethrough + ❌. Bottom-of-message BrokenCitationsBlock lists each
  failure with reason ("file not found", "line 999 > 250") so the user
  can challenge the specific claim.
- code/prompt.ts + cli/index.ts: "Cite or shut up — non-negotiable"
  section moved to TOP of system prompt (was at the end and ignored).
  Concrete ✅/❌ examples. Negative-claim rule made imperative — "STOP.
  Call search_content FIRST" instead of "qualify it" — because asserting
  absence without checking is the #1 failure mode.
- App.tsx / EventLog.tsx / PlanConfirm.tsx: thread projectRoot through
  every <Markdown /> callsite (defaults to process.cwd() for safety).

Behavioural validation: same "analyze the project" prompt that produced
5/8 hallucinations pre-fix returned 3/3 verifiable specific claims +
1 auto-detected broken citation post-fix. Citation feature working in
production.

799 tests (17 new in markdown.test.ts: parseCitationUrl, isExternalUrl,
validateCitation, collectCitations dedup + external skip, parseBlocks
no-regression). Lint + typecheck + build clean.
2026-04-23 04:47:10 -07:00
esengine 3c8669577d feat(0.4.26): subagents-via-Skills + search_content + render/shell/sandbox fixes
- Subagents-via-Skills (replaces 0.4.25's spawn_subagent user-facing
  surface; library API kept). Skills frontmatter gains runAs:subagent +
  optional model:deepseek-*. Builtin explore + research skills ship in
  src/skills.ts as constants. spawnSubagent(opts) extracted from
  registerSubagentTool — both surfaces share it via formatSubagentResult.
  registerSkillTools moved into App.tsx with subagentRunner closure;
  reasonix code no longer registers spawn_subagent in the model tool list.
  Pinned Skills index marks subagent skills with a 🧬 prefix so the model
  pattern-matches "user says explore -> use 🧬 explore" instead of
  reasoning about whether a task is "big enough" to delegate.
- search_content: real content grep tool. Skips 18 dependency / build /
  VCS dirs by default + skips binaries by extension (30+ types) and
  by content sniff (NUL byte in first 8KB). Per-file 2 MB cap, output
  capped to maxListBytes. Regex + literal fallback, glob substring
  filter, case_sensitive + include_deps options. Closes the gap that
  made subagents waste their iter budget calling search_files (which
  is filename-only) for content-grep questions.
- markdown renderer: recognizes Unicode box-drawing tables (│ ─ ┼) +
  ┌─┐ │ └─┘ frames as code blocks. Table cells now render through
  InlineMd with padTo so backticks/bold inside cells parse and column
  widths align by visible (post-strip) width. Multi-line table cell
  continuation rows fold back into the previous row's last cell.
- shell on Windows: prepareSpawn injects chcp 65001 prefix into every
  cmd.exe /c payload + injects [Console]::OutputEncoding=UTF8 into
  PowerShell -Command invocations. Fixes mojibake on CJK Windows where
  cmd builtins (dir, findstr, where) and PowerShell emit text in CP936
  / CP932 / CP949 — previously poisoned the next turn's prompt with
  garbled bytes.
- sandbox: filesystem tools' safePath strips leading / and \ so
  POSIX-absolute paths (path: "/" or "/src/foo.ts") resolve to the
  sandbox root instead of the actual filesystem root. Models routinely
  pass these intending the project root; the old behavior failed the
  escape check with a confusing error.
- loop: aborted signal in the API-call catch yields a clean done
  instead of a red error event. The "This operation was aborted" row
  was always a self-inflicted UX bug — App.tsx calls loop.abort() to
  switch turns when the user picks ShellConfirm "always allow" or
  PlanConfirm approve, and the resulting AbortError got rendered as
  a real error. Subagent layer compensates by synthesizing an error
  result when no final answer was produced (so success!=true on abort).
- prompts: dropped the fictional `grep` tool reference from
  CODE_SYSTEM_PROMPT; explicit list of available exploration tools
  (read_file, list_directory, directory_tree, search_files,
  search_content, get_file_info). New "Path conventions" section
  distinguishes filesystem-tool sandbox-relative paths from
  run_command OS-shell paths (don't use leading / in shell args).

781 tests (+26 vs 0.4.24), lint + typecheck + build clean.
2026-04-23 02:30:15 -07:00
esengine 3fee4e6883 feat: reasonix stats — cross-session cost dashboard + /stats slash (0.4.24)
Every turn run through `reasonix chat|code|run` now appends one line
to ~/.reasonix/usage.jsonl carrying tokens + cost + the equivalent
Claude Sonnet 4.6 cost. `reasonix stats` (no arg) rolls that log up
into today / week / month / all-time windows with a "saved vs
Claude" column. Pillar 1's pitch (94–97% cost reduction) becomes a
fact users can check on their own machine.

Same dashboard is available in-session via the new /stats slash,
reading from the same file and rendering through a shared pure
renderer. reasonix stats <transcript> keeps the old per-file
summary (assistant turns + tool calls) for scripts.

Privacy: only tokens, costs, session name. No prompts, completions,
or tool args. Log append is best-effort — disk failure never blocks
a turn.

New files:
  src/usage.ts                 — appendUsage, readUsageLog, aggregateUsage,
                                  bucketCacheHitRatio / SavingsFraction
  tests/usage.test.ts          — 15 tests (round-trip, malformed line,
                                  rolling windows, renderer, zero denom)

Modified:
  src/cli/commands/stats.ts    — dashboard mode + extracted renderDashboard
  src/cli/commands/run.ts      — appendUsage on assistant_final (for CI)
  src/cli/ui/App.tsx           — appendUsage on assistant_final (TUI)
  src/cli/ui/slash.ts          — /stats slash (shared renderer)
  src/cli/index.ts             — `stats <transcript>` → `stats [transcript]`
  src/index.ts                 — re-export usage module

+17 tests (suite 708 → 725). Lint + typecheck + build clean.
2026-04-22 22:24:59 -07:00
esengine 41d21f7cea feat(slash): /update shows current vs latest + shell command (0.4.23)
Adds an in-session `/update` slash that reports the running version
and the last-resolved latest from the App's background npm-registry
check. Deliberately does NOT spawn `npm install` — stdio:inherit
into a running Ink renderer corrupts the display, and on Windows
the currently-running binary can be locked. Users exit and run
`reasonix update` in a fresh shell when they actually want to
install.

Also splits App state: we now track `latestVersion` regardless of
whether it's newer (so the slash can tell "on the latest" apart
from "still fetching") and derive the yellow header badge from
that. Before this, `updateAvailable` was only set on strictly-
newer, so `/update` saw null when the user was already on the
latest — the message misleadingly said "background check in
flight or offline".

`/update` also triggers a fresh `getLatestVersion({force:true})`
when latestVersion is null, so a retry a few seconds later sees
a concrete answer.

4 new tests (suite 704 → 708). All green; lint / typecheck / build
clean.
2026-04-22 22:13:32 -07:00
esengine 715d8b5950 feat: hooks — user-defined automation at PreToolUse / PostToolUse / UserPromptSubmit / Stop (0.4.23)
Same two-scope layout as memory and skills:
  - <project>/.reasonix/settings.json (committable per-project)
  - ~/.reasonix/settings.json         (per-user)

A hook is a shell command. Reasonix invokes it with stdin = a JSON
envelope carrying the event, tool name, tool args, etc. Exit code
drives the decision:
  - 0 = pass; loop continues normally
  - 2 = block (only on PreToolUse / UserPromptSubmit); hook's stderr
    becomes the synthetic tool result the model sees, or the prompt
    is dropped entirely
  - anything else = warn; loop continues, stderr renders inline as a
    yellow row

Project hooks fire before global hooks. `match` is anchored regex on
the tool name (ignored for prompt / Stop events). Default timeouts:
5s for blocking events, 30s for logging events; per-hook `timeout`
overrides. Settings malformed? loadHooks swallows it so a typo
doesn't bring down the whole CLI.

Deliberate non-goals: no workflow DSL, no conditional chaining, no
hook templates. Hooks are shell commands — the user already has a
programming language.

New files:
  - src/hooks.ts                      (loadHooks, runHooks, decideOutcome, matchesTool, formatHookOutcomeMessage)
  - tests/hooks.test.ts               (26 unit tests)
  - tests/loop-hooks.test.ts          (6 smoke tests — loop wiring)

Modified:
  - src/loop.ts          — PreToolUse + PostToolUse dispatch around tool.dispatch
  - src/cli/ui/App.tsx   — load settings on mount, UserPromptSubmit before handleSubmit, Stop after loop.step
  - src/cli/ui/slash.ts  — /hooks list + /hooks reload
  - src/index.ts         — re-exports

+32 tests (suite 672 → 704). Lint / typecheck / build clean.
2026-04-22 22:06:29 -07:00
esengine 911f043db8 feat: version display in TUI header + reasonix update self-upgrade (0.4.22)
Two small quality-of-life additions.

The stats panel now carries the running version (`Reasonix v0.4.22 ·
model …`) so users can tell at a glance whether they're on the latest
build. A 24-hour background check against the npm registry surfaces a
yellow `update: X.Y.Z` nudge on the right side of the same row when a
newer version has been published — 2s timeout, cache at
`~/.reasonix/version-cache.json`, silent on failure.

`reasonix update` is the command form: detects global install vs npx,
spawns `npm install -g reasonix@latest` for the former or prints a
cache-refresh hint for the latter. `--dry-run` prints the plan.

Also fixes a drifted VERSION constant: `src/index.ts` hard-coded
"0.4.20" while package.json was on 0.4.21. Now re-exports from
`src/version.ts`, which walks up from import.meta.url to the
manifest on first access. A regression test pins them together.

New files: `src/version.ts`, `src/cli/commands/update.ts`,
`tests/version.test.ts`, `tests/update-command.test.ts`. +24 tests
(suite 648 → 672). Lint/typecheck/build clean.
2026-04-22 21:34:11 -07:00
esengine ce85319c9b docs(readme): promote reasonix code to the hero section, document skills
- Quick start now leads with `reasonix code` and a real SEARCH/REPLACE
  walkthrough — nobody enters through plain chat.
- New Skills section covers the SKILL.md format, project vs global
  scopes, /skill slash family, autonomous run_skill invocation, and
  the 'not tied to .claude/' stance.
- chat mode demoted to a brief 'also works as' section pointing at MCP.
- Commands table grouped by category (Core / Model / Context & tools /
  Memory & skills / Sessions / Code-mode only) instead of one flat list.
- Benchmarks promoted into their own 'verify yourself' section.
- Non-goals now names workflow DSL / DAG engine and DeepSeek-only
  positioning explicitly.
- Test count 444 → 648, Node requirement 18 → 20.10, added
  REASONIX_UI=plain to the env-var list.
2026-04-22 19:07:44 -07:00
esengine 2a9a9b386b feat: skills — project/global SKILL.md packs pinned into the prefix + shell fixes (0.4.21)
Skills are user-authored prompt packs read from `<project>/.reasonix/skills/`
and `~/.reasonix/skills/`. Pinned index (names + one-liners) lives in
the immutable prefix; bodies load lazily via the new `run_skill` tool
or `/skill <name> [args]`. Project scope wins on name collisions.
Deliberately NOT tied to any other client's dir (.claude/, .glm/) —
Reasonix is model-agnostic at the conversation layer.

No workflow DSL or DAG engine: skills are prose, the model sequences
via the existing tool-use loop. Preserves single-loop + append-only +
cache-first invariants; "no multi-agent orchestration" non-goal stands.

Shell fixes bundled in:
- ShellConfirm "always allow" now takes effect mid-session.
  extraAllowed is re-read on every dispatch via a getter, so a prefix
  saved to ~/.reasonix/config.json applies to the running tool
  without needing /new or a relaunch.
- Windows cmd.exe built-ins (dir, echo, type, ver, ...) no longer
  crash with ENOENT. prepareSpawn routes bare unresolved Windows
  commands through `cmd.exe /d /s /c` with verbatim-args quoting,
  matching the wrapping strategy for .cmd/.bat files.
2026-04-22 18:58:48 -07:00
esengine e3cfbb58dd feat: user memory — ~/.reasonix/memory/ pinned into the immutable prefix · remember/forget/recall tools · prompt cleanup (0.4.20)
- MemoryStore + applyUserMemory + applyMemoryStack (src/user-memory.ts):
  two scopes — global (cross-project) and project (per sandbox-root sha1).
  Each scope keeps a MEMORY.md index pinned into ImmutablePrefix.system;
  detail files loaded on demand via recall_memory. Byte-stable rewrite
  so identical file sets produce identical prefix hashes.
- remember / forget / recall_memory tools (src/tools/memory.ts) — chat
  mode gets global-only; reasonix code gets both scopes. remember's
  return text is imperative so R1 treats the fact as authoritative on
  the same turn.
- /memory slash extended: list | show <name> | forget <name> |
  clear <scope> confirm. Bare /memory renders REASONIX.md + both
  MEMORY.md blocks together.
- Prompt cleanup: dropped hardcoded dir enumerations, bun/npm examples,
  "待确认" CJK fallback, DSML-hallucination historical note, and
  Linear/Slack type-hint specifics. Principle-only wording + reference
  to the pinned .gitignore block. Net -tokens on every turn.
- README: new "User memory" subsection under REASONIX.md.
- scripts/smoke-memory.mts: 30-assertion end-to-end regression script.
- REASONIX_MEMORY=off now disables every memory source (REASONIX.md +
  user memory) — previous semantics was REASONIX.md only.

Tests: 542 → 624 (+82 incl. 36 memory-layer unit tests). Lint / tsc /
build clean.
2026-04-22 17:30:26 -07:00
esengine becaf487e8 fix(shell): use path.win32.join so CI tests with platform:win32 pass on Linux
CI runs on Linux, where pathMod.join defaults to POSIX (`/`). The
PATHEXT resolver mocks its isFile predicate with back-slashed keys
(`C:\tools\npm.CMD`), so join with POSIX produced `C:\tools/npm.CMD`
and lookups missed, failing 8 tests at origin. The runtime call path
is unaffected either way since the win32 branch is only active when
platform === "win32" anyway — but making the join explicitly win32
also hardens against weird PATHs on Windows where forward slashes
have historically crept in.
2026-04-22 06:38:41 -07:00
esengine 6111d8f621 fix(loop): surface StormBreaker suppression as a visible warning + reset on user turn
A silent storm-break was indistinguishable from a stalled turn — the
model would look like it gave up when really we'd suppressed its
repeat tool call. Now `step()` emits a dedicated warning event when
`report.stormsBroken > 0`, with distinct messages for the two cases:

- All calls suppressed (stuck retry): tell the user the model is
  looping on the same (tool, args) and point them at /retry or
  rewording the instruction. This is the case that used to dead-end
  the turn with nothing on screen.
- Some calls suppressed (one redundant): the rest of the turn
  proceeds; the warning is informational.

Also reset the StormBreaker's sliding window at the top of every
`step()` so a new user message doesn't inherit last turn's repeat
patterns (false-positive blocks on legitimate "try again" flows).

Part of the 0.4.19 batch — tag will be moved to this commit.
2026-04-22 06:35:13 -07:00
esengine d8ba9f9669 fix(shell): Windows — PATHEXT resolution + cmd.exe wrapping for .cmd/.bat (0.4.19)
Two layered fixes so `run_command` actually runs npm/npx/tsc/yarn/
pnpm/bun/pytest and every other Node-ecosystem wrapper on Windows:

1. resolveExecutable() walks PATH × PATHEXT manually — spawn
   with shell:false uses CreateProcess, which ignores PATHEXT, so
   bare `npm` missed `npm.cmd` and ENOENT'd.

2. prepareSpawn() wraps .cmd/.bat via `cmd.exe /d /s /c` with
   windowsVerbatimArguments + per-arg quoteForCmdExe — Node 21.7.3+/
   24 (CVE-2024-27980) refuses direct spawn of .cmd/.bat even with
   shell:false, throwing EINVAL. cmd.exe wrapping with manual
   safe-quoting keeps shell metacharacters (&, |, <, >, etc.) in
   arguments literal so the previous security posture holds.

Unix path unchanged. Suite 566 → 587.
2026-04-22 06:09:11 -07:00
esengine e409e9d8d9 feat: Plan Mode — autonomous plan proposals + /plan gate + answer-questions flow (0.4.18)
submit_plan tool: model proposes a markdown plan for large tasks
(multi-file refactors, ambiguous requests, risky changes). Picker
shows Approve / Refine / Cancel with the plan rendered as live
Markdown, not raw text. Open-questions sections ("Open questions",
"待确认", "Risks", etc.) are detected; default selection flips to
Refine and a yellow hint surfaces.

Both Approve and Refine take an inline text input afterward so the
user can answer the model's open questions or attach last-minute
instructions before the loop resumes. Empty Enter on Approve skips
the extras; empty Enter on Refine tells the model to ask concrete
clarifying questions.

/plan slash flips a dispatch-level read-only gate on the
ToolRegistry — writes + non-allowlisted shell bounce with a refusal
the model reads. Read tools, web_search/fetch, and allowlisted shell
(git status / cargo check / npm test etc.) still work during
exploration. Tool specs stay pinned across the toggle so the DeepSeek
prefix cache doesn't break.

/apply-plan is a fallback that force-approves without the picker,
for cases where the model wrote the plan in assistant text instead
of calling submit_plan.

Suite 542 → 566.
2026-04-22 05:50:28 -07:00
esengine 4d21ca4c4c feat: project memory — REASONIX.md pinned into the immutable prefix (0.4.17)
Drop a REASONIX.md in the project root and its contents are pinned
into the system prompt every session that opens there. Cache-first:
read once, hashed into the prefix fingerprint, no per-turn budget.
/memory prints what's currently pinned; REASONIX_MEMORY=off opts out.

Suite 517 → 542. Re-exported applyProjectMemory / readProjectMemory /
memoryEnabled + PROJECT_MEMORY_FILE / PROJECT_MEMORY_MAX_CHARS for
library consumers that build their own system prompt.
2026-04-22 04:55:06 -07:00
esengine 1ccc1d7e67 feat: run_command shell tool · session picker · ShellConfirm picker · backspace/markdown fixes (0.4.16) 2026-04-22 04:43:17 -07:00
esengine fd344986e8 feat: web_search via Mojeek · cursor editing in prompt · REASONIX_UI=plain · ticker consolidation (0.4.15) 2026-04-22 04:05:25 -07:00
esengine 6ceb73d367 fix(ui): consolidate timers · patchConsole:false · REASONIX_UI=plain opt-out (0.4.14) 2026-04-22 02:35:02 -07:00
esengine dee96f66a2 fix(ui): tool_call_delta progress · reset streamRef per iter · expanded README (0.4.13) 2026-04-22 01:59:44 -07:00
esengine 6b4d8652e4 fix(loop): full tool_calls↔tool pairing validator + auto-compact on context-guard (0.4.12)
Two DeepSeek 400s users hit in succession:
- "insufficient tool messages following tool_calls" on forced
  summary: context-guard appended assistant.tool_calls then bailed
  before dispatching. Fix: strip the tail before forceSummary.
- "tool must be a response to a preceding tool_calls" on the next
  message: partial heals left stray tool messages in the log.

Root fix: healLoadedMessages now runs a full tool_calls↔tool pairing
validator. Any assistant.tool_calls with an incomplete response set
is dropped (with its partial responses); any stray tool message is
dropped. Runs on session load (rewrites the file so damage doesn't
re-surface) AND on every buildMessages call (defensive).

Context-guard now auto-compacts before forcing summary. Previously
80% context meant you lost a turn immediately. Now: try shrinking
oversized tool payloads first; only fall back to forced summary
when nothing's compactable.

Split shrinkOversizedToolResults from healLoadedMessages so
`/compact` (mid-turn) doesn't strip legitimate structural state.

443 tests (+5 new, 4 reshaped).
2026-04-22 01:07:07 -07:00
168 changed files with 35187 additions and 2165 deletions

No files matched your search

+1066
View File
File diff suppressed because it is too large. Load diff
+678 -219
View File
@@ -1,3 +1,11 @@
<p align="center">
<img src="docs/logo.svg" alt="Reasonix — DeepSeek-native agent framework" width="640"/>
</p>
<p align="center">
<em>Cache-first agent loop for DeepSeek V4 (flash + pro) — Ink TUI, MCP first-class, no LangChain.</em>
</p>
# Reasonix
[![npm version](https://img.shields.io/npm/v/reasonix.svg)](https://www.npmjs.com/package/reasonix)
@@ -6,230 +14,630 @@
[![downloads](https://img.shields.io/npm/dm/reasonix.svg)](https://www.npmjs.com/package/reasonix)
[![node](https://img.shields.io/node/v/reasonix.svg)](./package.json)
**A DeepSeek-native AI coding assistant in your terminal.** Ink TUI. MCP
first-class. No LangChain.
```bash
npx reasonix
```
One command. First run walks you through a 30-second wizard (API key →
preset → pick MCP servers from a checklist); every run after that drops
straight into chat with your tools wired up. Inside the chat, type `/help`.
Why bother with yet another agent framework? Because every abstraction
here earns its weight against a DeepSeek-specific property — dirt-cheap
tokens, R1 reasoning traces, automatic prefix caching, JSON mode.
Generic wrappers treat DeepSeek as "OpenAI with a different base URL"
and leave these advantages on the table. Reasonix leans into them:
on the same τ-bench-lite workload,
[**94.4% cache hit, ~40% cheaper tokens, 100% pass rate**](#validated-numbers)
vs. a cache-hostile baseline.
**A DeepSeek-native AI coding agent in your terminal.** Edits files as
reviewable SEARCH/REPLACE blocks. Ink TUI. MCP first-class. No
LangChain.
---
## What you get
## Quick start (60 seconds)
| Feature | How it works | Opt in |
|---|---|---|
| **Setup wizard** | First run of `npx reasonix`: pick preset, multi-select MCP servers from a curated catalog, saved to config so the next run just launches chat | always on (first run) |
| **MCP (stdio + SSE)** | Multi-server bridge — every MCP tool inherits Cache-First + repair + context-safety automatically. `reasonix mcp list` shows the catalog | always on |
| **Cache-First Loop** | Immutable prefix + append-only log = prefix byte-stable across turns → DeepSeek's automatic prefix cache hits at 70–95% | always on |
| **Context safety net** | Tool results capped at 32k chars · oversized sessions auto-heal on load · `/compact` to shrink further · ctx gauge in the status bar · Esc to abort exploration and get a forced summary | always on |
| **R1 Thought Harvesting** | Parses `reasoning_content` into typed `{ subgoals, hypotheses, uncertainties, rejectedPaths }` via a cheap V3 call | `/preset smart` |
| **Self-Consistency Branching** | Runs N parallel samples at spread temperatures; picks the one with the fewest flagged uncertainties | `/preset max` / `/branch N` |
| **Tool-Call Repair** | Auto-flattens deep/wide schemas, scavenges tool calls leaked into `<think>`, repairs truncated JSON, breaks call-storms | always on |
| **Retry layer** | Exponential backoff + jitter on 408/429/500/502/503/504 and network errors. 4xx auth errors don't retry | always on |
| **Ink TUI** | Live cache-hit / cost / context panel. Streams R1 thinking to a compact preview. Renders Markdown (bold / lists / code / stripped LaTeX) | always on |
**1. Get a DeepSeek API key.** Free credit on signup:
<https://platform.deepseek.com/api_keys>
---
## Why not just use LangChain?
Even on the default `fast` preset (no harvest, no branching), Reasonix bakes
in five DeepSeek-specific defences that generic agent frameworks leave to you:
| | Reasonix default | generic frameworks |
|---|---|---|
| Prefix-stable loop (→ 85–95% cache hit) | ✅ | ❌ prompts rebuilt each turn |
| Auto-flatten deep tool schemas | ✅ | ❌ DeepSeek drops args |
| Retry with jittered backoff (429/503) | ✅ | ❌ custom callbacks |
| Scavenge tool calls leaked into `<think>` | ✅ | ❌ |
| Call-storm breaker on identical-arg repeats | ✅ | ❌ |
| Live cache-hit / cost / vs-Claude panel | ✅ | ❌ |
| First-run config prompt + Markdown TUI | ✅ | ❌ |
Harvest and self-consistency branching are bonuses on top. The everyday
win is that **a plain chat with Reasonix already pays for ~40% less tokens
than the same chat through a naive LangChain setup**, because the prefix
actually stays byte-stable.
## Validated numbers
**τ-bench-lite** — 8 multi-turn tool-use tasks × 3 repeats = 48 runs per
side. Same tools / same prompt / same client on both sides, sole variable
is prefix stability. Measured on live DeepSeek `deepseek-chat`:
| metric | baseline (cache-hostile) | Reasonix | delta |
|---|---:|---:|---:|
| runs | 24 | 24 | — |
| **cache hit** | 46.6% | **94.4%** | **+47.7pp** |
| cost / task | $0.002599 | $0.001579 | **−39% (×0.61)** |
| vs Claude Sonnet 4.6 (token-count estimate) | — | — | **~96% cheaper** |
| pass rate | 96% (23/24) | **100% (24/24)** | Reasonix held the guardrail on every run |
**Verify it yourself — no API key, zero cost:**
```bash
git clone https://github.com/esengine/reasonix.git && cd reasonix && npm install
npx reasonix replay benchmarks/tau-bench/transcripts/t01_address_happy.reasonix.r1.jsonl
npx reasonix diff \
benchmarks/tau-bench/transcripts/t01_address_happy.baseline.r1.jsonl \
benchmarks/tau-bench/transcripts/t01_address_happy.reasonix.r1.jsonl
```
The JSONL transcripts committed in `benchmarks/tau-bench/transcripts/`
carry per-turn `usage`, `cost`, and `prefixHash`. Reasonix's prefix hash
stays byte-stable across every model call; baseline's prefix churns on
every turn. The cache delta is *mechanically* attributable to log
stability, not to a different system prompt.
Full 48-run report: [`benchmarks/tau-bench/report.md`][r]. Reproduce
with your own API key: `npx tsx benchmarks/tau-bench/runner.ts --repeats 3`.
[r]: ./benchmarks/tau-bench/report.md
### MCP — works out of the box
Any [MCP](https://spec.modelcontextprotocol.io/) server's tools inherit
Cache-First + repair + context-safety automatically. The wizard (`npx
reasonix`) lets you multi-select from a curated catalog — no flags, no
JSON-by-hand. Three live reference runs:
| server | turns | tool calls | cache hit | cost | vs Claude |
|---|---:|---:|---:|---:|---:|
| bundled demo (`add` / `echo` / `get_time`) | 2 | 1 | **96.6%** (turn 2) | $0.000254 | −94.0% |
| official `@modelcontextprotocol/server-filesystem` | 5 | 4 | **96.7%** overall | $0.001235 | −97.0% |
| **both concurrently** (`demo_add` + `fs_write_file`) | 5 | 4 | **81.1%** | $0.001852 | −95.9% |
The third row is the ecosystem proof: two MCP servers running as
separate subprocesses, tools from both exercised in one conversation.
**One single prefix hash across all 5 turns** — byte-stability survives
concurrent MCP subprocesses.
Reproduce without an API key (replay the committed transcripts):
```bash
npx reasonix replay benchmarks/tau-bench/transcripts/mcp-demo.add.jsonl
npx reasonix replay benchmarks/tau-bench/transcripts/mcp-filesystem.jsonl
```
Supported transports: **stdio** (local `npx` or binary) and **HTTP+SSE**
(remote / hosted servers, MCP 2024-11-05 spec). Pass an `http(s)://`
URL to `--mcp` and Reasonix opens the SSE stream and POSTs JSON-RPC
to the endpoint the server advertises.
[mcp]: ./benchmarks/tau-bench/transcripts/mcp-demo.add.jsonl
---
## Usage
### One command
```bash
npx reasonix
```
First run: a wizard asks for your API key, lets you pick a preset
(fast / smart / max), then offers a multi-select checklist of MCP
servers — filesystem, memory, github, puppeteer, everything. Everything
is saved to `~/.reasonix/config.json`. Subsequent runs drop straight
into chat.
### Inside the chat
A status bar at the top shows cache hit %, cost, Claude-equivalent, and
the **context gauge** (`ctx 42k/131k (32%)` — yellow at 50%, red + a
`/compact` nudge at 80%). A command strip under the input lists the
slash commands:
```
/help full list + hints
/preset <fast|smart|max> one-tap bundles (model + harvest + branch)
/mcp list attached MCP servers and tools
/compact [cap] shrink oversized tool results in history
/sessions · /forget list / delete saved sessions
/setup reconfigure (exits and tells you to run `reasonix setup`)
/clear · /exit
```
**Esc while thinking** — abort the current exploration and force the
model to summarize what it already found. No more "model ran 24 tool
calls and gave up" — you get an answer every time.
Sessions live as JSONL under `~/.reasonix/sessions/<name>.jsonl` —
every message appended atomically, so killing the CLI never loses
context. Oversized tool results auto-heal on load, so poisoning a
session with one giant `read_file` doesn't brick your history.
### Code mode — `npx reasonix code`
A thin opinionated layer on top of chat: filesystem MCP bridged at
`cwd`, coding system prompt, reasoner preset, per-directory session.
The model proposes edits as **SEARCH/REPLACE blocks**:
```
src/foo.ts
<<<<<<< SEARCH
const x = 1;
=======
const x = 2;
>>>>>>> REPLACE
```
Reasonix parses them out of each turn, applies them to disk, reports
`✓ applied src/foo.ts` in the TUI. SEARCH must match byte-for-byte;
we never fuzzy-match (silent wrong edits are worse than loud
rejections). Run `git diff` to review, `git checkout .` to undo.
**2. Point it at a project.** No install needed.
```bash
cd my-project
npx reasonix code # default: cwd, reasoner, per-dir session
npx reasonix code src/ # scope the filesystem sandbox tighter
npx reasonix code --no-session # ephemeral
npx reasonix code
```
First-run sandbox: because code mode uses the filesystem MCP from
`@modelcontextprotocol/server-filesystem`, the model can only read
and write inside the directory you pointed at. It literally can't
touch files above that root.
First run walks you through a 30-second wizard (paste API key → pick
preset → multi-select MCP servers). Every run after that drops you
straight in.
### Advanced — CLI subcommands and flags
**3. Ask it to edit.** The model proposes edits as SEARCH/REPLACE
blocks — nothing hits disk until you `/apply`.
```
reasonix code › users.ts 里 findByEmail 对大小写敏感导致登录失败,帮我改
assistant
▸ tool<search_files> → src/users.ts, src/users.test.ts
▸ tool<read_file> → (src/users.ts, 412 chars)
▸ 找到了。findByEmail 直接用 === 比对。改成小写规范化并补一条测试。
src/users.ts
<<<<<<< SEARCH
return users.find(u => u.email === email);
=======
const needle = email.toLowerCase();
return users.find(u => u.email.toLowerCase() === needle);
>>>>>>> REPLACE
▸ 1 pending edit across 1 file — /apply to write · /discard to drop
reasonix code › /apply
▸ ✓ applied src/users.ts
```
Requires Node ≥ 20.10. macOS, Linux, Windows (PowerShell / Git Bash /
Windows Terminal). Press `Esc` anytime to abort; `/help` for the full
command list.
---
## `reasonix code` — pair programmer in your terminal
Scoped to the directory you launch from. The model has native
`read_file` / `write_file` / `edit_file` / `list_directory` /
`search_files` / `directory_tree` / `get_file_info` /
`create_directory` / `move_file` tools, all sandboxed — any path that
resolves outside the launch root (including `..` and symlink escapes)
is refused. Plus `run_command` with a read-only allowlist; anything
state-mutating (`npm install`, `git commit`, …) is gated behind a
confirmation picker.
### Walkthrough: explore before editing
For "what does this code do?" questions the model uses the read-side
tools and replies in prose — no SEARCH/REPLACE blocks, no file
writes. Ask to change something only when you mean it:
```
reasonix code › 这个项目的路由是怎么组织的?
assistant
▸ tool<directory_tree> → (src/ tree, 47 entries)
▸ tool<read_file> → (src/router.ts, 1.2 KB)
▸ 路由分三层:顶层 AppRouter 注册 tab,每个 tab 用 React Router 的
nested routes 写子路径,最后 …
```
If an `edit_file` SEARCH block doesn't match the file byte-for-byte,
the edit is refused loudly rather than fuzzy-matched. The model sees
the error and retries — silent wrong edits are worse than visible
rejections.
### Plan mode — review before executing
For anything bigger than a typo, the model is encouraged to propose a
markdown plan first. You'll see a picker with **Approve / Refine /
Cancel**:
```
reasonix code › 把 auth 从 JWT 迁移到 session cookies
▸ plan submitted — awaiting your review
────────────────────────────────────────
## Summary
Swap JWT middleware for session cookies, keep user table intact.
## Files
- src/auth/middleware.ts — replace `verifyJwt` with `readSession`
- src/auth/session.ts — new file, in-memory store + signed cookie
- src/routes/login.ts — return Set-Cookie instead of a token
- tests/auth/*.test.ts — update fixtures
## Risks
- Existing logged-in users get logged out (no migration).
- Session store is in-memory; restart clears sessions.
────────────────────────────────────────
▸ Approve and implement
Refine — explore more
Cancel
```
**Force it** with `/plan` — enters an explicit read-only phase where
the model *must* submit a plan before any edit or non-allowlisted
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
```
reasonix code › /commit "fix: findByEmail case-insensitive"
▸ git add -A && git commit -m "fix: findByEmail case-insensitive"
[main a1b2c3d] fix: findByEmail case-insensitive
```
### Things to try
- `/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 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.
- `/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).
- `npx reasonix code --no-session` — ephemeral; nothing saved.
### `reasonix stats` — how much did you actually save?
Every turn `reasonix chat|code|run` runs appends a compact record
(tokens + cost + what Claude Sonnet 4.6 would have charged) to
`~/.reasonix/usage.jsonl`. `reasonix stats` with no args rolls that
log into today / week / month / all-time windows:
```
Reasonix usage — /Users/you/.reasonix/usage.jsonl
turns cache hit cost (USD) vs Claude saved
----------------------------------------------------------------------
today 8 95.1% $0.004821 $0.1348 96.4%
week 34 93.8% $0.023104 $0.6081 96.2%
month 127 94.2% $0.081530 $2.1452 96.2%
all-time 342 94.0% $0.210881 $5.8934 96.4%
```
Privacy: only tokens, costs, and the session name you chose land
in the file. No prompts, no completions, no tool arguments.
`reasonix stats <transcript>` keeps the old per-file summary
(assistant turns + tool calls) for scripts that already use it.
### Staying current
The panel header shows the running version next to `Reasonix` (e.g.
`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
(offline, firewall, etc.).
```bash
npx reasonix setup # reconfigure any time
npx reasonix chat --session work # a different named session
npx reasonix chat --no-session # ephemeral — nothing persisted
reasonix update # print current vs latest, run `npm i -g reasonix@latest`
reasonix update --dry-run # print the plan without running anything
```
Running via `npx`? The command detects that and prints a
cache-refresh hint instead — npx picks up the newest version on
its next invocation automatically.
### Project conventions — `REASONIX.md`
Drop a `REASONIX.md` in the project root and its contents are pinned
into the system prompt every launch. Committable team memory — house
conventions, domain glossary, things the model keeps forgetting:
```bash
cat > REASONIX.md <<'EOF'
# Notes for Reasonix
- Use snake_case for new Python modules; legacy camelCase modules keep their style.
- `cargo check` is in the auto-run allowlist; full `cargo test` needs confirmation.
- The `api/` dir mirrors `backend/` — keep schemas in sync.
EOF
```
Re-launch (or `/new`) to pick it up; the prefix is hashed once per
session to keep the DeepSeek cache warm. `/memory` prints what's
currently pinned. `REASONIX_MEMORY=off` disables every memory source
for CI / offline repro.
### User memory — `~/.reasonix/memory/`
A second, **private per-user** memory layer lives under your home
directory. Unlike `REASONIX.md` it's never committed, and the model
can write to it itself via the `remember` tool. Two scopes:
- `~/.reasonix/memory/global/` — cross-project (your preferences,
tooling).
- `~/.reasonix/memory/<project-hash>/` — scoped to one sandbox root
in `reasonix code` (decisions, local facts, per-repo shortcuts).
Each scope keeps an always-loaded `MEMORY.md` index of one-liners
plus zero or more `<name>.md` detail files (loaded on demand via
`recall_memory`). Writes land immediately; pinning into the system
prompt takes effect on next `/new` or launch so the cache prefix
stays stable for the current session.
```
reasonix code › 我用 bun 而不是 npm,请以后都用 bun 跑构建
assistant
▸ tool<remember> → project/bun_build saved
"Build command on this machine is `bun run build`"
```
**Slash**: `/memory` · `/memory list` · `/memory show <name>` ·
`/memory forget <name>` · `/memory clear <scope> confirm`.
**Model tools**: `remember(type, scope, name, description, content)` ·
`forget(scope, name)` · `recall_memory(scope, name)`.
Project scope is only available inside `reasonix code` (needs a real
sandbox root to hash); plain `reasonix` gets the global scope only.
### Skills — user-authored prompt packs
Skills are prose instruction blocks you drop on disk. Reasonix pins
their names + one-line descriptions into the system prompt; the
model can call `run_skill({name: "..."})` on its own when a match
fits, or you can type `/skill <name> [args]` to run one manually.
Two scopes, same layout as user memory:
- `<project>/.reasonix/skills/` — per-project skills (commit them to
share with your team, or add to `.gitignore` for personal drafts).
- `~/.reasonix/skills/` — global skills available everywhere.
Either layout works: `<name>/SKILL.md` (preferred — can bundle
additional assets alongside) or flat `<name>.md`.
```markdown
---
name: review
description: Review uncommitted changes and flag risks
---
Run `git diff` on staged and unstaged changes. Summarize what each
hunk does, call out potential regressions, and list files that might
need additional tests. Don't propose edits unless I ask.
```
Use it:
```
reasonix code › /skill review
▸ running skill: review
assistant
▸ tool<run_command> → git diff --cached
▸ 3 改动,1 个需要回归测试 …
```
Or let the model pick autonomously — because the skill's name +
description are pinned in the prefix, asking "帮我看下未提交的改动有没
有风险" triggers `run_skill({name: "review"})` without you typing the
slash command.
**Slash**: `/skill` (list) · `/skill show <name>` · `/skill <name>
[args]` (inject body as user turn).
**Deliberately not tied** to any other client's directory convention
(`.claude/skills`, etc.) — Reasonix is model-agnostic at the
conversation layer. Any SKILL.md you author works; the body is
prose, so skills authored for other tools usually port over unchanged
(Reasonix's tool names differ — `filesystem` / `shell` / `web` — but
the model reads the instructions and picks our equivalents).
### Hooks — automate around tool calls and turns
Drop a `settings.json` under `.reasonix/` (project or `~/`) and
Reasonix will fire shell commands at four well-known points in
the loop: before a tool runs, after a tool returns, before your
prompt reaches the model, and after the turn ends.
```json
// <project>/.reasonix/settings.json ← committable
// ~/.reasonix/settings.json ← per-user
{
"hooks": {
"PreToolUse": [{ "match": "edit_file|write_file", "command": "bun scripts/guard.ts" }],
"PostToolUse": [{ "match": "edit_file", "command": "biome format --write" }],
"UserPromptSubmit": [{ "command": "echo $(date +%s) >> ~/.reasonix/prompts.log" }],
"Stop": [{ "command": "bun test --run", "timeout": 60000 }]
}
}
```
Each hook is a shell command. Reasonix invokes it with stdin = a
JSON envelope describing the event:
```json
{ "event": "PreToolUse", "cwd": "/path/to/project",
"toolName": "edit_file", "toolArgs": { "path": "src/x.ts", "..." } }
```
Exit code drives the decision:
- **0** — pass; loop continues normally
- **2** — block (only on `PreToolUse` / `UserPromptSubmit`); the
hook's stderr becomes the synthetic tool result the model sees,
or the prompt is dropped entirely
- **anything else** — warn; loop continues, stderr renders as a
yellow row inline
`match` is anchored regex on the tool name; `*` or omitted matches
every tool. Project hooks fire before global hooks. Default
timeouts: 5s for blocking events, 30s for logging events; per-hook
`timeout` overrides.
**Slash**: `/hooks` (list active hooks) · `/hooks reload` (re-read
`settings.json` from disk without losing your session).
### Staying current from inside the TUI
`/update` inside a running session shows your current version, the
last-resolved latest version (from the quiet 24h background check),
and the shell command to run. The slash does *not* spawn
`npm install` — stdio:inherit into a running Ink renderer corrupts
the display. Exit the session and run `reasonix update` in a
fresh shell when you actually want to install.
---
## `reasonix` — also works as general chat
Same TUI, no filesystem tools unless you opt in via MCP. Good for
drafting, Q&A, schema design, architecture discussions, or driving
your own MCP servers. Sessions persist per name under
`~/.reasonix/sessions/`.
```bash
npx reasonix # uses saved config + wizard-selected MCP
npx reasonix --preset smart # reasoner + R1 harvest for this run
npx reasonix --session design # named session — resume later with --session design
```
Bridge your own MCP servers on the fly:
```bash
npx reasonix \
--mcp "fs=npx -y @modelcontextprotocol/server-filesystem /tmp/safe" \
--mcp "kb=https://mcp.example.com/sse"
```
MCP tools go through the same Cache-First + repair + context-safety
plumbing as native tools — 32k result cap, live progress-notification
rendering, retries.
---
## Commands inside the session
**Core**
| command | what it does |
|---|---|
| `/help` · `/?` | full command reference with hints |
| `/status` | current model · flags · context · session |
| `/new` · `/reset` | fresh conversation in the same session |
| `/clear` | clear visible scrollback only (log kept) |
| `/retry` | truncate and resend your last message (fresh sample) |
| `/exit` · `/quit` | quit |
**Model**
| command | what it does |
|---|---|
| `/preset <fast\|smart\|max>` | one-tap bundle (model + harvest + branch) |
| `/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) |
| `/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 / 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 [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**
| command | what it does |
|---|---|
| `/memory` | show pinned memory (REASONIX.md + ~/.reasonix/memory) |
| `/memory list` · `show <name>` · `forget <name>` · `clear <scope> confirm` | manage the store |
| `/skill` · `/skill list` | list discovered skills (project + global) |
| `/skill show <name>` | dump one skill's body |
| `/skill <name> [args]` | run a skill (inject body as user turn) |
**Sessions**
| command | what it does |
|---|---|
| `/sessions` | list saved sessions (current marked with `▸`) |
| `/forget` | delete the current session from disk |
| `/setup` | reconfigure (exit and run `reasonix setup`) |
**Code mode only** (`reasonix code`)
| command | what it does |
|---|---|
| `/apply` | commit the pending SEARCH/REPLACE blocks to disk |
| `/discard` | drop the pending edit blocks without writing |
| `/undo` | roll back the last applied edit batch |
| `/commit "msg"` | `git add -A && git commit -m "msg"` |
| `/plan [on\|off]` | toggle read-only plan mode |
| `/apply-plan` | force-approve a pending plan |
**Keyboard**
- `Enter` — submit
- `Shift+Enter` / `Ctrl+J` — newline (multi-line paste also supported;
`\` + Enter as a portable fallback)
- `↑` / `↓` — walk prompt history while idle; navigate slash-autocomplete
- `Tab` / `Enter` on a `/foo` prefix — accept the highlighted suggestion
- `Esc` — abort the current turn (stops the API call, cancels any
in-flight tool, rejects pending MCP requests)
- `y` / `n` on confirm prompts — hotkey accept / reject
---
## Sessions and safety nets
- Sessions live as JSONL under `~/.reasonix/sessions/<name>.jsonl`
(per directory for `reasonix code`). Every message appended
atomically; `Ctrl+C` never loses context.
- Tool results are capped at 32k chars per call. Oversized sessions
self-heal on load (shrinks + rewrites the file).
- 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 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.
### Troubleshooting: duplicate rows / ghost rendering
Some Windows terminals (Git Bash / MINTTY / winpty-wrapped shells)
don't fully implement the ANSI cursor-up escapes Ink uses to repaint
the live spinner region. Symptom: spinners, streaming previews, or
tool-result rows print multiple copies into scrollback instead of
overwriting in place.
If you hit this, run with plain mode:
```bash
REASONIX_UI=plain npx reasonix code
```
Plain mode suppresses live/animated rows and disables the internal
tick timer. You lose the streaming preview and spinners but gain
stable scrollback. Windows Terminal, PowerShell 7 in Windows
Terminal, and WezTerm don't need this opt-out.
---
## Web search — on by default
The model has two web tools the moment you launch: `web_search` and
`web_fetch`. No flag, no API key, no signup. When you ask about
something the model wasn't trained on (new releases, current events,
obscure APIs), it decides to call `web_search` on its own; if a
snippet isn't enough it follows up with `web_fetch`.
Backed by **Mojeek**'s public search page — an independent web
index, bot-friendly, no cookies/sessions. Coverage on niche or very
recent queries can be thinner than Google/Bing, but it's reliable
from scripts. (DDG was the original backend but started serving
anti-bot pages in 2026.)
**Turn it off** (offline mode / privacy / CI):
```json
// ~/.reasonix/config.json
{ "apiKey": "sk-…", "search": false }
```
```bash
REASONIX_SEARCH=off npx reasonix code
```
**Bring your own** (Kagi, SearXNG, internal caches): implement the
`WebSearchProvider` interface and call
`registerWebTools(registry, { provider })` yourself, or bridge an
existing MCP search server via `--mcp`.
---
## MCP — bring your own tools
Any [MCP](https://spec.modelcontextprotocol.io/) server works. The
wizard lets you pick from a catalog, or drive it by flag:
```bash
# stdio (local subprocess)
npx reasonix --mcp "fs=npx -y @modelcontextprotocol/server-filesystem /tmp/safe"
# multiple at once
npx reasonix \
--mcp "fs=npx -y @modelcontextprotocol/server-filesystem /tmp/safe" \
--mcp "demo=npx tsx examples/mcp-server-demo.ts"
# HTTP+SSE (remote / hosted)
npx reasonix --mcp "kb=https://mcp.example.com/sse"
```
`reasonix mcp list` shows the curated catalog. `reasonix mcp inspect
<spec>` connects once and dumps the server's tools / resources /
prompts without starting a chat. Progress notifications from
long-running tools (2025-03-26 spec) render live as a progress bar
in the spinner.
Supported transports: **stdio** (local command) and **HTTP+SSE**
(remote, MCP 2024-11-05 spec).
---
## CLI reference
```bash
npx reasonix code [path] # coding mode scoped to path (default: cwd)
npx reasonix # chat (uses saved config)
npx reasonix setup # reconfigure the wizard
npx reasonix chat --session work # named session
npx reasonix chat --no-session # ephemeral
npx reasonix run "ask anything" # one-shot, streams to stdout
npx reasonix stats session.jsonl # summarize a transcript
npx reasonix replay chat.jsonl # scrub a transcript + rebuild cost/cache
npx reasonix replay chat.jsonl # rebuild cost/cache from a transcript
npx reasonix diff a.jsonl b.jsonl --md # compare two transcripts
npx reasonix mcp list # curated MCP server catalog
npx reasonix mcp list # curated MCP catalog
npx reasonix mcp inspect <spec> # probe a single MCP server
npx reasonix sessions # list saved sessions
```
Power users can still bypass config and drive Reasonix with flags:
Common flags:
```bash
npx reasonix chat \
--preset max \
--mcp "filesystem=npx -y @modelcontextprotocol/server-filesystem /tmp/safe" \
--mcp "kb=https://mcp.example.com/sse" \
--transcript session.jsonl \
--no-config # ignore ~/.reasonix/config.json (for CI / reproducing issues)
--preset <fast|smart|max> # bundle (model + harvest + branch)
--model <id> # explicit model id
--harvest / --no-harvest # R1 plan-state extraction
--branch <N> # self-consistency budget
--mcp "name=cmd args…" # attach an MCP server (repeatable)
--transcript path.jsonl # write a JSONL transcript on the side
--session <name> # named session (default: per-dir for code mode)
--no-session # ephemeral
--no-config # ignore ~/.reasonix/config.json (CI-friendly)
```
### Library
Env vars (win over config):
```bash
export DEEPSEEK_API_KEY=sk-...
export DEEPSEEK_BASE_URL=https://... # optional alternate endpoint
export REASONIX_MEMORY=off # disable REASONIX.md + user memory
export REASONIX_SEARCH=off # disable web_search / web_fetch
export REASONIX_UI=plain # disable live rows (ghosting workaround)
```
---
## Library usage
```ts
import {
@@ -261,7 +669,7 @@ const loop = new CacheFirstLoop({
toolSpecs: tools.specs(),
}),
harvest: true,
branch: 3, // self-consistency budget
branch: 3,
});
for await (const ev of loop.step("What is 17 + 25?")) {
@@ -270,29 +678,82 @@ for await (const ev of loop.step("What is 17 + 25?")) {
console.log(loop.stats.summary());
```
### Configuration
`ChatOptions.seedTools` accepts a pre-built `ToolRegistry` for
callers who want the `reasonix code` loop wiring without the CLI
wrapper. See [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) for
internals.
The wizard handles everything on first run. If you'd rather use env vars
(CI, shared boxes, etc.):
---
## Benchmarks — verify the cache-hit claim yourself
Every abstraction here earns its weight against a DeepSeek-specific
property — dirt-cheap tokens, R1 reasoning traces, automatic prefix
caching, JSON mode. Generic wrappers leave these on the table.
| | Reasonix default | generic frameworks |
|---|---|---|
| Prefix-stable loop (→ 85–95% cache hit) | yes | no (prompts rebuilt each turn) |
| Auto-flatten deep tool schemas | yes | no (DeepSeek drops args) |
| Retry with jittered backoff (429/503) | yes | no (custom callbacks) |
| Scavenge tool calls leaked into `<think>` | yes | no |
| Call-storm breaker on identical-arg repeats | yes | no |
| Live cache-hit / cost / vs-Claude panel | yes | no |
On the same τ-bench-lite workload — 8 multi-turn tool-use tasks × 3
repeats = 48 runs per side, live DeepSeek `deepseek-chat`, sole
variable prefix stability:
| metric | baseline (cache-hostile) | Reasonix | delta |
|---|---:|---:|---:|
| cache hit | 46.6% | **94.4%** | +47.7 pp |
| cost / task | $0.002599 | $0.001579 | **−39%** |
| pass rate | 96% (23/24) | **100% (24/24)** | — |
**Reproduce without spending an API credit:**
```bash
export DEEPSEEK_API_KEY=sk-... # wins over ~/.reasonix/config.json
export DEEPSEEK_BASE_URL=https://... # optional alternate endpoint
git clone https://github.com/esengine/reasonix.git && cd reasonix && npm install
npx reasonix replay benchmarks/tau-bench/transcripts/t01_address_happy.reasonix.r1.jsonl
npx reasonix diff \
benchmarks/tau-bench/transcripts/t01_address_happy.baseline.r1.jsonl \
benchmarks/tau-bench/transcripts/t01_address_happy.reasonix.r1.jsonl
```
Get a key (free credit on signup): <https://platform.deepseek.com/api_keys>
The committed JSONL transcripts carry per-turn `usage`, `cost`, and
`prefixHash`. Reasonix's prefix hash stays byte-stable across every
model call; baseline's churns on every turn. The cache delta is
*mechanically* attributable to log stability, not to a different
system prompt.
Re-run `npx reasonix setup` any time to add/remove MCP servers or switch
preset — your existing selections are pre-checked.
Full 48-run report:
[`benchmarks/tau-bench/report.md`](./benchmarks/tau-bench/report.md).
Reproduce with your own API key: `npx tsx
benchmarks/tau-bench/runner.ts --repeats 3`.
MCP reference runs (one single prefix hash across all 5 turns even
with two concurrent MCP subprocesses):
| server | turns | cache hit | cost | vs Claude |
|---|---:|---:|---:|---:|
| bundled demo (`add` / `echo` / `get_time`) | 2 | **96.6%** (turn 2) | $0.000254 | −94.0% |
| official `server-filesystem` | 5 | **96.7%** | $0.001235 | −97.0% |
| **both concurrently** | 5 | **81.1%** | $0.001852 | −95.9% |
---
## Non-goals
- Multi-agent orchestration (use LangGraph).
- RAG / vector stores (use LlamaIndex or do it yourself).
- Multi-provider abstraction (use LiteLLM).
- Web UI / SaaS.
- **Multi-agent orchestration / sub-agents** (use LangGraph).
- **Workflow DSL / DAG scheduler / parallel-branch engine** — skills
are prose; the model sequences via the normal tool-use loop.
Keeps single-loop + append-only + cache-first invariants intact.
- **Multi-provider abstraction** (use LiteLLM). Reasonix is
DeepSeek-only on purpose — every pillar (cache-first loop, R1
harvesting, tool-call repair) is tuned against DeepSeek-specific
behavior and economics. Coupling to one backend is the feature.
- **RAG / vector stores** (use LlamaIndex).
- **Web UI / SaaS.**
Reasonix does DeepSeek, deeply.
@@ -304,15 +765,13 @@ Reasonix does DeepSeek, deeply.
git clone https://github.com/esengine/reasonix.git
cd reasonix
npm install
npm run dev chat # run CLI from source via tsx
npm run dev code # run CLI from source via tsx
npm run build # tsup to dist/
npm test # vitest (279 tests)
npm test # vitest (1007 tests)
npm run lint # biome
npm run typecheck # tsc --noEmit
```
See [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) for internals.
---
## License
Binary file not shown.
+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.
+95
View File
@@ -0,0 +1,95 @@
<svg xmlns="http://www.w3.org/2000/svg" width="760" height="170" viewBox="0 0 760 170" role="img" aria-label="Reasonix — DeepSeek-native agent framework">
<title>Reasonix</title>
<defs>
<!-- Signature cyan → violet → fuchsia gradient used across the TUI wordmark
and the brand mark. Renders well on both GitHub dark and light bg. -->
<linearGradient id="rx-grad" x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0%" stop-color="#5eead4"/>
<stop offset="15%" stop-color="#67e8f9"/>
<stop offset="30%" stop-color="#7dd3fc"/>
<stop offset="45%" stop-color="#93c5fd"/>
<stop offset="60%" stop-color="#a5b4fc"/>
<stop offset="75%" stop-color="#c4b5fd"/>
<stop offset="90%" stop-color="#d8b4fe"/>
<stop offset="100%" stop-color="#f0abfc"/>
</linearGradient>
<linearGradient id="rx-grad-mark" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" stop-color="#5eead4"/>
<stop offset="50%" stop-color="#93c5fd"/>
<stop offset="100%" stop-color="#c4b5fd"/>
</linearGradient>
<filter id="glow" x="-50%" y="-50%" width="200%" height="200%">
<feGaussianBlur stdDeviation="3" result="blur"/>
<feMerge>
<feMergeNode in="blur"/>
<feMergeNode in="SourceGraphic"/>
</feMerge>
</filter>
</defs>
<!-- ◈ brand mark: concentric diamonds. Outer stroke pulses,
inner fill breathes, whole group rotates slowly. The rotation
is subtle (12s / full turn) so it feels like a heartbeat, not a
spinner. -->
<g transform="translate(90, 85)" filter="url(#glow)">
<g>
<animateTransform attributeName="transform" type="rotate"
from="0" to="360" dur="18s" repeatCount="indefinite"/>
<!-- Outer hollow diamond -->
<path d="M 0,-46 L 46,0 L 0,46 L -46,0 Z"
fill="none"
stroke="url(#rx-grad-mark)"
stroke-width="3.5"
stroke-linejoin="round">
<animate attributeName="stroke-width"
values="3.5;5.5;3.5"
dur="2.4s"
repeatCount="indefinite"/>
</path>
<!-- Middle hollow diamond -->
<path d="M 0,-26 L 26,0 L 0,26 L -26,0 Z"
fill="none"
stroke="url(#rx-grad-mark)"
stroke-width="2"
stroke-linejoin="round"
opacity="0.7">
<animate attributeName="opacity"
values="0.4;0.9;0.4"
dur="2.4s"
begin="0.8s"
repeatCount="indefinite"/>
</path>
<!-- Inner solid diamond -->
<path d="M 0,-11 L 11,0 L 0,11 L -11,0 Z"
fill="url(#rx-grad-mark)">
<animate attributeName="opacity"
values="0.75;1;0.75"
dur="2.4s"
repeatCount="indefinite"/>
</path>
</g>
</g>
<!-- REASONIX wordmark with shifting gradient. The x1 offset animates
so the gradient crawls left-to-right across the letters — a
slow rainbow sweep that gives the logo life without being noisy. -->
<text x="170" y="102"
font-family="ui-monospace, SFMono-Regular, 'Cascadia Code', Menlo, Consolas, 'DejaVu Sans Mono', monospace"
font-size="68"
font-weight="800"
fill="url(#rx-grad)"
letter-spacing="6">REASONIX
<animate attributeName="opacity"
values="0.9;1;0.9"
dur="3.2s"
repeatCount="indefinite"/>
</text>
<!-- Tagline sits just below the wordmark. Slate-500 reads well on
both GitHub dark and light themes (~4.5:1 contrast either way). -->
<text x="172" y="136"
font-family="ui-monospace, SFMono-Regular, 'Cascadia Code', Menlo, Consolas, 'DejaVu Sans Mono', monospace"
font-size="15"
fill="#64748b"
letter-spacing="0.5">DeepSeek-native agent framework · cache-first loop · Ink TUI</text>
</svg>

After

Width:  |  Height:  |  Size: 3.8 KiB

+3 -2
View File
@@ -1,7 +1,7 @@
{
"name": "reasonix",
"version": "0.4.11",
"description": "DeepSeek-native agent framework: cache-first loop, R1 thought harvesting, tool-call repair.",
"version": "0.7.5",
"description": "DeepSeek-native coding agent: cache-first loop, flash-first cost control, tool-call repair.",
"type": "module",
"bin": {
"reasonix": "dist/cli/index.js"
@@ -17,6 +17,7 @@
},
"files": [
"dist",
"data/deepseek-tokenizer.json.gz",
"README.md",
"LICENSE"
],
+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);
});
+34
View File
@@ -0,0 +1,34 @@
#!/usr/bin/env node
/**
* Regenerate `data/deepseek-tokenizer.json.gz` from an upstream
* `tokenizer.json` (as shipped in DeepSeek's deepseek_v3_tokenizer.zip).
*
* Why slim+gz: the full tokenizer.json is 7.5MB; we only need four
* fields (vocab, merges, pre_tokenizer, added_tokens). Strip + gzip
* drops the committed artifact to ~1.7MB with no loss of fidelity
* for encode-side token counting.
*
* Usage: `node --experimental-strip-types scripts/prepare-tokenizer.ts <path/to/tokenizer.json>`
* (or via `tsx` / `ts-node`.)
*/
import { readFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { gzipSync } from "node:zlib";
const src = process.argv[2];
if (!src) {
process.stderr.write("usage: prepare-tokenizer.ts <tokenizer.json>\n");
process.exit(2);
}
const raw = JSON.parse(readFileSync(src, "utf8"));
const slim = {
added_tokens: raw.added_tokens,
pre_tokenizer: raw.pre_tokenizer,
model: { type: raw.model.type, vocab: raw.model.vocab, merges: raw.model.merges },
};
const gz = gzipSync(Buffer.from(JSON.stringify(slim)), { level: 9 });
const outPath = join(process.cwd(), "data", "deepseek-tokenizer.json.gz");
writeFileSync(outPath, gz);
process.stdout.write(`wrote ${outPath} (${(gz.length / 1024).toFixed(1)} KB)\n`);
+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);
}
});
+192
View File
@@ -0,0 +1,192 @@
/**
* End-to-end smoke test for the memory layer. Runs against a temp
* homeDir so the developer's real ~/.reasonix/memory/ is never touched.
* Exercises: write → index regeneration → prefix assembly →
* recall → delete → REASONIX_MEMORY=off short-circuit.
*
* Run: npx tsx scripts/smoke-memory.mts
* Exit code 0 on success, 1 on any assertion failure.
*/
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { ToolRegistry } from "../src/tools.js";
import { registerMemoryTools } from "../src/tools/memory.js";
import {
MemoryStore,
applyMemoryStack,
applyUserMemory,
projectHash,
} from "../src/user-memory.js";
let failures = 0;
function check(label: string, cond: unknown, detail?: string) {
if (cond) {
process.stdout.write(` ✓ ${label}\n`);
} else {
failures++;
process.stdout.write(` ✗ ${label}${detail ? ` — ${detail}` : ""}\n`);
}
}
async function main() {
const home = mkdtempSync(join(tmpdir(), "reasonix-smoke-home-"));
const projectRoot = mkdtempSync(join(tmpdir(), "reasonix-smoke-proj-"));
process.stdout.write(`home: ${home}\nproject: ${projectRoot}\n\n`);
try {
// ── 1. MemoryStore write + index regeneration ────────────────────
process.stdout.write("1. MemoryStore write → index regen\n");
const store = new MemoryStore({ homeDir: home, projectRoot });
store.write({
name: "bun_build",
type: "project",
scope: "project",
description: "Build command on this machine is `bun run build`",
body: "On this machine, no npm — always `bun run build` / `bun run test`.",
});
store.write({
name: "tabs_not_spaces",
type: "user",
scope: "global",
description: "Use tabs for indentation across all projects",
body: "Rule.\n\n**Why:** muscle memory, editor config across machines.\n\n**How to apply:** always tabs.",
});
const hash = projectHash(projectRoot);
const projectFile = join(home, "memory", hash, "bun_build.md");
const globalFile = join(home, "memory", "global", "tabs_not_spaces.md");
check("project-scoped file landed in <hash>/ dir", existsSync(projectFile));
check("global-scoped file landed in global/ dir", existsSync(globalFile));
check("no cross-contamination project ⇒ global", !existsSync(join(home, "memory", "global", "bun_build.md")));
const projectIndex = readFileSync(join(home, "memory", hash, "MEMORY.md"), "utf8");
check("project MEMORY.md points at bun_build.md", projectIndex.includes("[bun_build](bun_build.md)"));
const globalIndex = readFileSync(join(home, "memory", "global", "MEMORY.md"), "utf8");
check("global MEMORY.md points at tabs_not_spaces.md", globalIndex.includes("[tabs_not_spaces](tabs_not_spaces.md)"));
const raw = readFileSync(projectFile, "utf8");
check("frontmatter has name/type/scope/created", /^---\nname: bun_build\n/.test(raw) && /type: project/.test(raw) && /scope: project/.test(raw) && /created: \d{4}-\d{2}-\d{2}/.test(raw));
// ── 2. Prefix assembly via applyMemoryStack (+ REASONIX.md) ────────
process.stdout.write("\n2. Prefix assembly (REASONIX.md + user memory)\n");
writeFileSync(join(projectRoot, "REASONIX.md"), "# Project notes\nPrefer explicit types over inference.\n", "utf8");
const BASE = "You are a test assistant.";
const withProjOnly = applyUserMemory(BASE, { homeDir: home, projectRoot });
check("applyUserMemory contains global block", withProjOnly.includes("# User memory — global"));
check("applyUserMemory contains project block", withProjOnly.includes("# User memory — this project"));
check("bun_build description present in prefix", withProjOnly.includes("bun run build"));
check("tabs_not_spaces description present in prefix", withProjOnly.includes("Use tabs for indentation"));
// Order: base → (REASONIX.md would go first via applyMemoryStack) → global → project
const ordered = applyUserMemory(BASE, { homeDir: home, projectRoot });
const iGlobalBlock = ordered.indexOf("# User memory — global");
const iProjBlock = ordered.indexOf("# User memory — this project");
check("global block precedes project block (stable for cache)", iGlobalBlock > 0 && iGlobalBlock < iProjBlock);
// Determinism — two calls with same state produce byte-identical prompts.
const a = applyUserMemory(BASE, { homeDir: home, projectRoot });
const b = applyUserMemory(BASE, { homeDir: home, projectRoot });
check("applyUserMemory is deterministic (byte-stable)", a === b);
// ── 3. The `remember` / `recall_memory` / `forget` tools ───────────
process.stdout.write("\n3. Tool dispatch (remember / recall / forget)\n");
const reg = new ToolRegistry();
registerMemoryTools(reg, { homeDir: home, projectRoot });
check("remember tool registered", reg.has("remember"));
check("forget tool registered", reg.has("forget"));
check("recall_memory tool registered", reg.has("recall_memory"));
check("recall_memory is readOnly (plan-mode safe)", reg.get("recall_memory")?.readOnly === true);
check("remember is NOT readOnly (plan-mode blocked)", reg.get("remember")?.readOnly !== true);
const remOut = await reg.dispatch("remember", {
type: "feedback",
scope: "global",
name: "prefers_short_replies",
description: "User wants terse answers, no trailing summaries",
content: "Default to terse. If the user wants detail they'll ask.",
});
check("remember returns a confirmation (not an error)", remOut.includes("REMEMBERED (global/prefers_short_replies)"), remOut);
const recallOut = await reg.dispatch("recall_memory", {
scope: "global",
name: "prefers_short_replies",
});
check("recall_memory returns the body", recallOut.includes("Default to terse"));
const forgetOut = await reg.dispatch("forget", {
scope: "global",
name: "prefers_short_replies",
});
check("forget returns a confirmation", forgetOut.includes("forgot (global/prefers_short_replies)"));
check("recall_memory after forget returns an error", (await reg.dispatch("recall_memory", { scope: "global", name: "prefers_short_replies" })).includes("error"));
// ── 4. Project scope refused when projectRoot is absent ────────────
process.stdout.write("\n4. Chat-mode (no projectRoot) refuses project scope\n");
const chatReg = new ToolRegistry();
registerMemoryTools(chatReg, { homeDir: home });
const projInChat = await chatReg.dispatch("remember", {
type: "project",
scope: "project",
name: "should_fail",
description: "d",
content: "c",
});
check("scope='project' in chat mode → error payload", projInChat.includes("error") && projInChat.includes("project"));
const globalInChat = await chatReg.dispatch("remember", {
type: "user",
scope: "global",
name: "global_from_chat",
description: "works across projects",
content: "body",
});
check("scope='global' in chat mode → writes successfully", globalInChat.includes("REMEMBERED (global/"));
// ── 5. REASONIX_MEMORY=off short-circuit ───────────────────────────
process.stdout.write("\n5. REASONIX_MEMORY=off opt-out\n");
process.env.REASONIX_MEMORY = "off";
try {
const silenced = applyUserMemory(BASE, { homeDir: home, projectRoot });
check("applyUserMemory returns BASE unchanged when off", silenced === BASE);
const fullStack = applyMemoryStack(BASE, projectRoot);
check("applyMemoryStack returns BASE unchanged when off (REASONIX.md also skipped)", fullStack === BASE);
} finally {
delete process.env.REASONIX_MEMORY;
}
// ── 6. Delete regeneration: MEMORY.md matches current file set ─────
process.stdout.write("\n6. Delete + index regeneration\n");
store.delete("global", "tabs_not_spaces");
store.delete("global", "global_from_chat");
const globalIdxAfter = join(home, "memory", "global", "MEMORY.md");
check("global MEMORY.md removed when last file deleted", !existsSync(globalIdxAfter));
const projectIdxStill = readFileSync(join(home, "memory", hash, "MEMORY.md"), "utf8");
check("project MEMORY.md untouched (different scope)", projectIdxStill.includes("bun_build"));
// ── 7. Name-sanitization boundary ──────────────────────────────────
process.stdout.write("\n7. Name sanitization (path-traversal refused)\n");
const badOut = await reg.dispatch("remember", {
type: "user",
scope: "global",
name: "../../etc/passwd",
description: "d",
content: "c",
});
check("remember refuses path-traversal name", badOut.includes("invalid memory name"));
const outsideFile = join(home, "etc", "passwd.md");
check("no file written outside the memory dir", !existsSync(outsideFile));
process.stdout.write(`\n${failures === 0 ? "✅ all smoke checks passed" : `❌ ${failures} failure(s)`}\n`);
} finally {
rmSync(home, { recursive: true, force: true });
rmSync(projectRoot, { recursive: true, force: true });
}
process.exit(failures === 0 ? 0 : 1);
}
main().catch((err) => {
console.error(err);
process.exit(1);
});
+397
View File
@@ -0,0 +1,397 @@
/**
* Expand `@path/to/file` mentions in a user prompt to inline file
* content.
*
* Why: most interactive coding sessions start with "look at X, then
* change Y". Typing `@src/loop.ts` reads faster and cheaper than
* "look at src/loop.ts (and the model fires read_file, and we pay for
* the round trip)" — the model sees the file content from turn 1
* instead of round-tripping a tool call for it.
*
* Shape: the user's text is kept verbatim. Expanded file contents are
* appended in a "Referenced files" block at the end, each wrapped in
* `<file path="...">...</file>` so the model can cite them back
* unambiguously.
*
* Safety: paths must resolve inside `rootDir` (no `..` escape, no
* absolute paths), must exist as a regular file, and must be under
* `maxBytes`. Missing / too-large / escaping paths get a short note
* appended instead of content so the user sees why it was skipped.
*/
import { type Dirent, existsSync, readFileSync, readdirSync, statSync } from "node:fs";
import { isAbsolute, join, relative, resolve } from "node:path";
/** Caps match tool-result dispatch truncation (0.5.2). */
export const DEFAULT_AT_MENTION_MAX_BYTES = 64 * 1024;
/**
* Default directory names skipped when listing files for the picker.
* Matches what most repos gitignore AND keeps the picker off the
* hottest bloat — `node_modules` alone can be 100k+ entries.
*/
export const DEFAULT_PICKER_IGNORE_DIRS: readonly string[] = [
"node_modules",
".git",
"dist",
"build",
".next",
"out",
"coverage",
".cache",
".vscode",
".idea",
"target",
".venv",
"venv",
"__pycache__",
];
export interface ListFilesOptions {
/** Cap the walk once we've collected this many entries. Default 500. */
maxResults?: number;
/** Directory names to skip entirely. Defaults to {@link DEFAULT_PICKER_IGNORE_DIRS}. */
ignoreDirs?: readonly string[];
}
/**
* Walk `root` recursively and return relative file paths (forward-slash
* separator, regardless of platform) for the `@` picker.
*
* Synchronous on purpose: this runs once at App mount (and on each turn
* so newly-created files show up) and blocks the render thread for a
* predictable ~10-50ms on a moderate repo. An async variant would need
* to coordinate with the Ink render loop; sync fits the rest of the
* TUI's single-turn-per-tick model cleanly.
*
* Skips:
* - directories in `ignoreDirs` (default: DEFAULT_PICKER_IGNORE_DIRS)
* - any directory whose name starts with `.` (covers `.git`,
* `.vscode`, dotfile vendors). Dotfile REGULAR FILES (`.env`,
* `.gitignore`, `.prettierrc`) are kept — users reference them.
* - entries the walker can't read (permission errors, broken links).
*/
export function listFilesSync(root: string, opts: ListFilesOptions = {}): string[] {
return listFilesWithStatsSync(root, opts).map((e) => e.path);
}
export interface FileWithStats {
/** Relative path with forward-slash separator. */
path: string;
/** Modification time (Date.getTime() / ms since epoch). 0 when stat failed. */
mtimeMs: number;
}
/**
* Same walk as {@link listFilesSync} but also statS each file for
* modification time. Used by the `@` picker to surface recently-
* edited files first — matches VS Code Quick Open / similar UX.
*
* Stat failures don't throw: the entry is kept with `mtimeMs: 0` so
* it still appears in the picker (just sinks to the bottom of the
* recency sort).
*/
export function listFilesWithStatsSync(root: string, opts: ListFilesOptions = {}): FileWithStats[] {
const maxResults = Math.max(1, opts.maxResults ?? 500);
const ignore = new Set(opts.ignoreDirs ?? DEFAULT_PICKER_IGNORE_DIRS);
const rootAbs = resolve(root);
const out: FileWithStats[] = [];
const walk = (dirAbs: string, dirRel: string) => {
if (out.length >= maxResults) return;
let entries: Dirent[];
try {
entries = readdirSync(dirAbs, { withFileTypes: true });
} catch {
return;
}
entries.sort((a, b) => a.name.localeCompare(b.name));
for (const ent of entries) {
if (out.length >= maxResults) return;
const relPath = dirRel ? `${dirRel}/${ent.name}` : ent.name;
if (ent.isDirectory()) {
if (ent.name.startsWith(".") || ignore.has(ent.name)) continue;
walk(join(dirAbs, ent.name), relPath);
} else if (ent.isFile()) {
let mtimeMs = 0;
try {
mtimeMs = statSync(join(dirAbs, ent.name)).mtimeMs;
} catch {
/* stat failed (permission / EAGAIN) — keep the entry with mtime=0 */
}
out.push({ path: relPath, mtimeMs });
}
}
};
walk(rootAbs, "");
return out;
}
/**
* Prefix pattern used by the `@` picker to detect an IN-PROGRESS
* mention at the END of the input buffer. Captures the partial path
* (which may be empty — just `@`) so the picker can use it as a
* substring filter.
*
* Distinct from {@link AT_MENTION_PATTERN} (which finds completed
* mentions anywhere in the text for expansion-at-submit). This one
* fires on the trailing token only, anchored at end-of-input.
*/
export const AT_PICKER_PREFIX = /(?:^|\s)@([a-zA-Z0-9_./\\-]*)$/;
/**
* Return the picker state for a given input buffer: the partial query
* (may be empty string — just `@`) and the buffer offset of the `@`
* character. `null` when the buffer doesn't end in a mention-in-
* progress.
*/
export function detectAtPicker(input: string): { query: string; atOffset: number } | null {
const m = AT_PICKER_PREFIX.exec(input);
if (!m) return null;
const query = m[1] ?? "";
// `m.index` is the offset of the capture group's SURROUNDING match —
// which starts at either ^ or the preceding whitespace. The `@`
// itself is at `end-of-input - query.length - 1`.
const atOffset = input.length - query.length - 1;
return { query, atOffset };
}
/** A candidate accepted by the picker ranker — either a bare path or a path with mtime. */
export type PickerCandidate = string | FileWithStats;
export interface RankPickerOptions {
/** Upper bound on returned entries. Default 40. */
limit?: number;
/**
* Paths the user or model has touched recently (via tool calls like
* `read_file` / `edit_file`). Matching paths get a recency boost so
* the picker surfaces "stuff I just looked at" near the top.
*/
recentlyUsed?: readonly string[];
}
/**
* Filter and rank candidate files against the picker's partial query.
*
* Empty query:
* - Sort by "recently used" bucket first (if provided), then mtime
* descending (newer first), then path alpha.
* - Pure-string input (no mtime data) falls back to alpha since
* recency info isn't available.
*
* Non-empty query:
* - Case-insensitive substring match, with a basename-prefix boost
* so `lo` floats `loop.ts`-shaped paths to the top.
* - Ties broken first by recently-used membership, then mtime.
*
* Back-compat: passes `string[]` through the same logic (mtime = 0,
* recently-used still honored).
*/
export function rankPickerCandidates(
files: readonly PickerCandidate[],
query: string,
limitOrOpts?: number | RankPickerOptions,
): string[] {
const opts: RankPickerOptions =
typeof limitOrOpts === "number" ? { limit: limitOrOpts } : (limitOrOpts ?? {});
const limit = opts.limit ?? 40;
const recent = new Set(opts.recentlyUsed ?? []);
const entries: FileWithStats[] = files.map((f) =>
typeof f === "string" ? { path: f, mtimeMs: 0 } : f,
);
if (!query) {
// Only re-sort when we actually have signal to sort by. If input
// is bare strings (mtime = 0 everywhere) AND there's no recent-
// used list, preserve input order so callers keep their existing
// layout. Passing FileWithStats or a non-empty recentlyUsed opts
// you into mtime+recency ranking.
const anyMtime = entries.some((e) => e.mtimeMs > 0);
if (!anyMtime && recent.size === 0) {
return entries.slice(0, limit).map((e) => e.path);
}
const sorted = [...entries].sort((a, b) => {
const aRecent = recent.has(a.path) ? 1 : 0;
const bRecent = recent.has(b.path) ? 1 : 0;
if (aRecent !== bRecent) return bRecent - aRecent;
if (a.mtimeMs !== b.mtimeMs) return b.mtimeMs - a.mtimeMs;
return a.path.localeCompare(b.path);
});
return sorted.slice(0, limit).map((e) => e.path);
}
const needle = query.toLowerCase();
const scored: Array<{ path: string; score: number; mtimeMs: number; recent: boolean }> = [];
for (const e of entries) {
const lower = e.path.toLowerCase();
const hit = lower.indexOf(needle);
if (hit < 0) continue;
const slash = lower.lastIndexOf("/");
const base = slash >= 0 ? lower.slice(slash + 1) : lower;
let score = 2;
if (base.startsWith(needle)) score = 0;
else if (lower.startsWith(needle)) score = 1;
scored.push({
path: e.path,
score: score * 10_000 + hit,
mtimeMs: e.mtimeMs,
recent: recent.has(e.path),
});
}
scored.sort((a, b) => {
if (a.score !== b.score) return a.score - b.score;
// Tie-break: recently-used, then mtime (newer first).
if (a.recent !== b.recent) return a.recent ? -1 : 1;
return b.mtimeMs - a.mtimeMs;
});
return scored.slice(0, limit).map((s) => s.path);
}
/**
* Matches `@` at a word boundary (start-of-string or preceded by
* whitespace) followed by a path-like token. Deliberately rejects `@`
* embedded in longer words (email addresses, mentions on social sites)
* by requiring the word boundary.
*
* Path charset keeps it to the characters that appear in real repo
* paths — letters, digits, `_` `-` `.` `/` `\`. Trailing `.` (e.g.
* `@foo.ts.`) is stripped before lookup so a sentence-terminating
* period doesn't break the mention.
*/
export const AT_MENTION_PATTERN = /(?<=^|\s)@([a-zA-Z0-9_./\\-]+)/g;
export interface AtMentionExpansion {
/** The raw `@path` token as it appeared in the text. */
token: string;
/** The relative path, as resolved against rootDir. */
path: string;
/** True if the content was inlined. False = skipped (reason in `skip`). */
ok: boolean;
/** Bytes read (only for ok=true). */
bytes?: number;
/** Why the mention was skipped. Set when ok=false. */
skip?: "missing" | "not-file" | "too-large" | "escape" | "read-error";
}
export interface AtMentionOptions {
/** Max file size in bytes before a mention is skipped. */
maxBytes?: number;
/**
* Optional file-system overrides for tests. Real callers omit these;
* the helper falls through to `node:fs`.
*/
fs?: {
exists: (path: string) => boolean;
isFile: (path: string) => boolean;
size: (path: string) => number;
read: (path: string) => string;
};
}
/**
* Expand `@path` mentions in `text`. Returns the (possibly augmented)
* text plus a per-mention report so the caller can surface expansions
* in the UI.
*/
export function expandAtMentions(
text: string,
rootDir: string,
opts: AtMentionOptions = {},
): { text: string; expansions: AtMentionExpansion[] } {
const maxBytes = opts.maxBytes ?? DEFAULT_AT_MENTION_MAX_BYTES;
const fs = opts.fs ?? defaultFs;
const root = resolve(rootDir);
// De-dupe by token so `@file.ts` referenced twice inlines once.
const seen = new Map<string, AtMentionExpansion>();
const expansions: AtMentionExpansion[] = [];
for (const match of text.matchAll(AT_MENTION_PATTERN)) {
const rawPath = match[1] ?? "";
// Strip trailing dot (sentence terminator): `@foo.ts.` → `@foo.ts`.
// Keep internal dots intact.
const cleaned = rawPath.replace(/\.+$/, "");
if (!cleaned) continue;
const token = `@${cleaned}`;
if (seen.has(token)) continue;
const expansion = resolveMention(cleaned, root, maxBytes, fs);
seen.set(token, expansion);
expansions.push(expansion);
}
if (expansions.length === 0) return { text, expansions };
// Build the trailing "Referenced files" block. Keep successful
// inlines and skipped ones (with their reason) so the model sees
// both what's here and what's missing.
const blocks: string[] = [];
for (const ex of expansions) {
if (ex.ok) {
const content = readSafe(root, ex.path, fs);
blocks.push(`<file path="${ex.path}">\n${content}\n</file>`);
} else {
blocks.push(`<file path="${ex.path}" skipped="${ex.skip}" />`);
}
}
const augmented = `${text}\n\n[Referenced files]\n${blocks.join("\n\n")}`;
return { text: augmented, expansions };
}
function resolveMention(
rawPath: string,
root: string,
maxBytes: number,
fs: NonNullable<AtMentionOptions["fs"]>,
): AtMentionExpansion {
// Reject absolute paths — `@/etc/passwd` should not inline.
if (isAbsolute(rawPath)) {
return { token: `@${rawPath}`, path: rawPath, ok: false, skip: "escape" };
}
const resolved = resolve(root, rawPath);
// Sandbox escape: after resolution the path must still be inside root.
const rel = relative(root, resolved);
if (rel.startsWith("..") || isAbsolute(rel)) {
return { token: `@${rawPath}`, path: rawPath, ok: false, skip: "escape" };
}
if (!fs.exists(resolved)) {
return { token: `@${rawPath}`, path: rawPath, ok: false, skip: "missing" };
}
if (!fs.isFile(resolved)) {
return { token: `@${rawPath}`, path: rawPath, ok: false, skip: "not-file" };
}
const size = fs.size(resolved);
if (size > maxBytes) {
return { token: `@${rawPath}`, path: rawPath, ok: false, skip: "too-large", bytes: size };
}
return { token: `@${rawPath}`, path: rawPath, ok: true, bytes: size };
}
function readSafe(root: string, rawPath: string, fs: NonNullable<AtMentionOptions["fs"]>): string {
const resolved = resolve(root, rawPath);
try {
return fs.read(resolved);
} catch {
return "(read failed)";
}
}
const defaultFs: NonNullable<AtMentionOptions["fs"]> = {
exists: (p) => existsSync(p),
isFile: (p) => {
try {
return statSync(p).isFile();
} catch {
return false;
}
},
size: (p) => {
try {
return statSync(p).size;
} catch {
return 0;
}
},
read: (p) => readFileSync(p, "utf8"),
};
+136 -17
View File
@@ -1,6 +1,7 @@
import { existsSync, statSync } from "node:fs";
import { render } from "ink";
import React, { useState } from "react";
import { loadApiKey } from "../../config.js";
import { loadApiKey, searchEnabled } from "../../config.js";
import { loadDotenv } from "../../env.js";
import { McpClient } from "../../mcp/client.js";
import { type InspectionReport, inspectMcpServer } from "../../mcp/inspect.js";
@@ -8,9 +9,19 @@ import { bridgeMcpTools } from "../../mcp/registry.js";
import { parseMcpSpec } from "../../mcp/spec.js";
import { SseTransport } from "../../mcp/sse.js";
import { type McpTransport, StdioTransport } from "../../mcp/stdio.js";
import {
loadSessionMessages,
rewriteSession,
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 {
@@ -42,7 +53,11 @@ 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). */
forceNew?: boolean;
}
interface RootProps extends ChatOptions {
@@ -58,10 +73,24 @@ interface RootProps extends ChatOptions {
* React reconciliation (no effect-timing surprises).
*/
progressSink: { current: ((info: ProgressInfo) => void) | null };
/** Present when the session has prior messages; drives the picker. */
sessionPreview?: { messageCount: number; lastActive: Date };
}
function Root({ initialKey, tools, mcpSpecs, mcpServers, progressSink, ...appProps }: RootProps) {
function Root({
initialKey,
tools,
mcpSpecs,
mcpServers,
progressSink,
sessionPreview,
...appProps
}: RootProps) {
const [key, setKey] = useState<string | undefined>(initialKey);
// `null` once the picker is resolved (or was never needed). Starts as
// the preview so we can render the picker once before mounting App.
const [pending, setPending] = useState<typeof sessionPreview>(sessionPreview);
if (!key) {
return (
<Setup
@@ -73,20 +102,50 @@ function Root({ initialKey, tools, mcpSpecs, mcpServers, progressSink, ...appPro
);
}
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 (
<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>
);
}
@@ -164,6 +223,7 @@ export async function chatCommand(opts: ChatOptions): Promise<void> {
spec: raw,
toolCount: bridge.registeredNames.length,
report,
client: mcp,
});
} catch (err) {
// Per-server failure is non-fatal: one broken server shouldn't
@@ -189,6 +249,62 @@ export async function chatCommand(opts: ChatOptions): Promise<void> {
}
const mcpSpecs = successfulSpecs;
// Register web search/fetch tools unless explicitly disabled. DDG
// backs them with no key required; the model invokes them whenever
// a question needs info fresher than its training data.
if (searchEnabled()) {
if (!tools) tools = new ToolRegistry();
registerWebTools(tools);
}
// Memory tools — available in every session, not just code mode.
// Chat-mode callers get global scope only; project scope requires
// the seedTools path from `reasonix code` (which registers its own
// MemoryStore bound to rootDir before chatCommand runs).
// `run_skill` is registered later in App.tsx (where the client
// exists) so it can wire the subagent runner for runAs:subagent
// skills.
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
// persistence is on, the session file already has prior messages, and
// the caller didn't pre-commit to one of the choices via --resume /
// --new flags. `--new` wipes the file now (before the loop opens),
// so the App mounts against a fresh log.
let sessionPreview: { messageCount: number; lastActive: Date } | undefined;
if (opts.session && !opts.forceResume && !opts.forceNew) {
const prior = loadSessionMessages(opts.session);
if (prior.length > 0) {
const p = sessionPathOf(opts.session);
const mtime = existsSync(p) ? statSync(p).mtime : new Date();
sessionPreview = { messageCount: prior.length, lastActive: mtime };
}
} else if (opts.session && opts.forceNew) {
rewriteSession(opts.session, []);
}
// Clear the terminal viewport AND scrollback before mounting Ink
// so the user lands on a fresh canvas — no leftover prompt /
// last-command output bleeding into the TUI's first frame.
// \x1b[2J — erase visible screen
// \x1b[3J — erase scrollback (xterm extension; safely ignored
// by terminals that don't implement it)
// \x1b[H — cursor home
// Stdout-only — stderr stays untouched so any startup diagnostics
// we wrote earlier (loadDotenv, MCP connect logs) aren't lost.
// Skipped on non-TTY runs (CI, piped output) where ANSI sequences
// would leak into the captured output.
if (process.stdout.isTTY) {
process.stdout.write("\x1b[2J\x1b[3J\x1b[H");
}
const { waitUntilExit } = render(
<Root
initialKey={initialKey}
@@ -196,9 +312,12 @@ export async function chatCommand(opts: ChatOptions): Promise<void> {
mcpSpecs={mcpSpecs}
mcpServers={mcpServers}
progressSink={progressSink}
sessionPreview={sessionPreview}
{...opts}
/>,
{ exitOnCtrlC: true },
// patchConsole:false — we never log to console during the TUI, and the
// patch is a known redraw-glitch source on winpty/MINTTY terminals.
{ exitOnCtrlC: true, patchConsole: false },
);
try {
await waitUntilExit();
+73 -4
View File
@@ -19,9 +19,15 @@
*/
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";
import { chatCommand } from "./chat.js";
export interface CodeOptions {
@@ -33,6 +39,19 @@ export interface CodeOptions {
noSession?: boolean;
/** Transcript file for replay/diff. */
transcript?: string;
/** Skip the session picker — always resume prior messages. */
forceResume?: boolean;
/** Skip the session picker — always wipe prior messages and start fresh. */
forceNew?: boolean;
/**
* Opt into Pillar 2 harvesting (extracts a typed plan state from R1
* reasoning via an extra V3 call). Default OFF in code mode — the
* displayed subgoals/hypotheses/rejectedPaths have no programmatic
* consumer, only `uncertainties.length` feeds branching, and the
* extra V3 call adds ~10-15% per-turn cost. Users who want the
* reasoning surfaced explicitly can pass `--harvest`.
*/
harvest?: boolean;
}
export async function codeCommand(opts: CodeOptions = {}): Promise<void> {
@@ -49,18 +68,68 @@ 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
// choices; merged on top of the built-in allowlist in shell.ts.
// GETTER form — re-read every dispatch so a prefix the user adds
// 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.
registerMemoryTools(tools, { projectRoot: rootDir });
// `run_skill` is intentionally NOT registered here — App.tsx wires it
// up with the subagent runner attached, so `runAs: subagent` skills
// can spawn isolated child loops. Doing it here would mean the App's
// re-registration would shadow the no-runner version, which works
// (last write wins) but obscures the wiring.
process.stderr.write(
`▸ reasonix code: rooted at ${rootDir}, session "${session ?? "(ephemeral)"}" · ${tools.size} native fs tool(s)\n`,
`▸ 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",
harvest: true, // smart preset's harvest setting, always on for code
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,
});
}
+1
View File
@@ -51,6 +51,7 @@ export async function diffCommand(opts: DiffOptions): Promise<void> {
if (wantTui) {
const { waitUntilExit } = render(React.createElement(DiffApp, { report }), {
exitOnCtrlC: true,
patchConsole: false,
});
await waitUntilExit();
return;
+1
View File
@@ -31,6 +31,7 @@ export async function replayCommand(opts: ReplayOptions): Promise<void> {
const pages = groupRecordsByTurn(parsed.records);
const { waitUntilExit } = render(React.createElement(ReplayApp, { meta: parsed.meta, pages }), {
exitOnCtrlC: true,
patchConsole: false,
});
await waitUntilExit();
}
+7
View File
@@ -11,6 +11,7 @@ import { SseTransport } from "../../mcp/sse.js";
import { type McpTransport, StdioTransport } from "../../mcp/stdio.js";
import { ToolRegistry } from "../../tools.js";
import { openTranscriptFile, recordFromLoopEvent, writeRecord } from "../../transcript.js";
import { appendUsage } from "../../usage.js";
export interface RunOptions {
task: string;
@@ -148,6 +149,12 @@ export async function runCommand(opts: RunOptions): Promise<void> {
if (ev.role === "tool") process.stdout.write(`\n[tool ${ev.toolName}] ${ev.content}\n`);
if (ev.role === "error") process.stderr.write(`\n[error] ${ev.error}\n`);
if (ev.role === "done") process.stdout.write("\n");
if (ev.role === "assistant_final" && ev.stats?.usage) {
// `reasonix run` is often used in CI / scripting — we want
// those turns to show up in `reasonix stats` too so the
// dashboard reflects all DeepSeek spend, not just TUI sessions.
appendUsage({ session: null, model: ev.stats.model, usage: ev.stats.usage });
}
// Persist every non-streaming event — deltas would flood the file and
// aren't useful for replay (replay renders final content, not keystrokes).
if (transcriptStream && ev.role !== "assistant_delta") {
+1 -1
View File
@@ -39,7 +39,7 @@ export async function setupCommand(_opts: SetupOptions = {}): Promise<void> {
unmount();
}}
/>,
{ exitOnCtrlC: true },
{ exitOnCtrlC: true, patchConsole: false },
);
await waitUntilExit();
}
+163 -5
View File
@@ -1,15 +1,60 @@
/**
* `reasonix stats` — two modes, decided by whether the user passed
* a transcript path.
*
* - `reasonix stats` → cross-session usage dashboard
* (reads `~/.reasonix/usage.jsonl`)
* - `reasonix stats <path>` → summary of a single JSONL transcript
* (original v0.1 behavior, kept so
* existing scripts don't break)
*
* The dashboard is the new story: for every turn `reasonix chat|code|run`
* has ever executed on this machine, we aggregate tokens + cost + the
* equivalent Claude spend, and print rolling-window totals (today /
* week / month / all-time). The savings column is the Pillar 1 pitch
* made concrete — "you paid $X; Claude would have charged $Y, a N%
* reduction."
*/
import { existsSync, readFileSync } from "node:fs";
import {
type UsageAggregate,
type UsageBucket,
aggregateUsage,
bucketCacheHitRatio,
bucketSavingsFraction,
defaultUsageLogPath,
formatLogSize,
readUsageLog,
} from "../../usage.js";
export interface StatsOptions {
transcript: string;
/** Optional transcript path. Absent → dashboard mode. */
transcript?: string;
/** Override usage log location (tests). */
logPath?: string;
/** Inject a fixed timestamp (tests) so rolling windows are deterministic. */
now?: number;
}
export function statsCommand(opts: StatsOptions): void {
if (!existsSync(opts.transcript)) {
console.error(`no such transcript: ${opts.transcript}`);
if (opts.transcript) {
transcriptSummary(opts.transcript);
return;
}
dashboard(opts);
}
// ---------------------------------------------------------------------
// Transcript summary — legacy v0.1 behavior, preserved verbatim.
// ---------------------------------------------------------------------
function transcriptSummary(path: string): void {
if (!existsSync(path)) {
console.error(`no such transcript: ${path}`);
process.exit(1);
}
const lines = readFileSync(opts.transcript, "utf8").split(/\r?\n/).filter(Boolean);
const lines = readFileSync(path, "utf8").split(/\r?\n/).filter(Boolean);
let assistantTurns = 0;
let toolCalls = 0;
let lastTurn = 0;
@@ -23,8 +68,121 @@ export function statsCommand(opts: StatsOptions): void {
/* skip */
}
}
console.log(`transcript: ${opts.transcript}`);
console.log(`transcript: ${path}`);
console.log(`assistant turns: ${assistantTurns}`);
console.log(`tool invocations: ${toolCalls}`);
console.log(`last turn index: ${lastTurn}`);
}
// ---------------------------------------------------------------------
// Dashboard — aggregates ~/.reasonix/usage.jsonl.
// ---------------------------------------------------------------------
function dashboard(opts: StatsOptions): void {
const path = opts.logPath ?? defaultUsageLogPath();
const records = readUsageLog(path);
if (records.length === 0) {
console.log("no usage data yet.");
console.log("");
console.log(` ${path}`);
console.log("");
console.log("run `reasonix chat`, `reasonix code`, or `reasonix run <task>` — every turn");
console.log("appends one line to the log and `reasonix stats` will roll it up.");
return;
}
const agg = aggregateUsage(records, { now: opts.now });
console.log(renderDashboard(agg, path));
}
/** Pure renderer — pulled out so tests can assert on the string directly. */
export function renderDashboard(agg: UsageAggregate, logPath: string): string {
const lines: string[] = [];
const size = formatLogSize(logPath);
lines.push(`Reasonix usage — ${logPath}${size ? ` (${size})` : ""}`);
lines.push("");
lines.push(header());
lines.push(divider());
for (const b of agg.buckets) {
lines.push(bucketRow(b));
}
lines.push("");
// Model + session breakdown — both trim to top 3 so a user with 20
// sessions doesn't drown the table.
if (agg.byModel.length > 0) {
const totalTurns = agg.buckets[agg.buckets.length - 1]?.turns ?? 0;
const top = agg.byModel[0];
if (top && totalTurns > 0) {
const pct = ((top.turns / totalTurns) * 100).toFixed(0);
lines.push(`most used model: ${top.model} (${pct}% of turns)`);
}
}
if (agg.bySession.length > 0) {
const top = agg.bySession[0];
if (top) lines.push(`top session: ${top.session} (${top.turns} turns)`);
}
if (agg.firstSeen) {
lines.push(`tracked since: ${new Date(agg.firstSeen).toISOString().slice(0, 10)}`);
}
if (agg.subagents) {
lines.push("");
lines.push(renderSubagentSection(agg.subagents));
}
return lines.join("\n");
}
function renderSubagentSection(sub: NonNullable<UsageAggregate["subagents"]>): string {
const lines: string[] = [];
const seconds = (sub.totalDurationMs / 1000).toFixed(1);
lines.push(
`subagent activity: ${sub.total} run(s) · $${sub.costUsd.toFixed(6)} · ${seconds}s total`,
);
// Show at most 5 skills so the section never dwarfs the main table.
const top = sub.bySkill.slice(0, 5);
for (const s of top) {
const sec = (s.durationMs / 1000).toFixed(1);
lines.push(
` ${pad(s.skillName, 18)} ${pad(`${s.count}`, 4, "right")} $${s.costUsd.toFixed(6)} ${sec}s`,
);
}
if (sub.bySkill.length > top.length) {
lines.push(` (+${sub.bySkill.length - top.length} more)`);
}
return lines.join("\n");
}
function header(): string {
// Fixed column widths so alignment works in any TTY.
return [
pad("", 10),
pad("turns", 8, "right"),
pad("cache hit", 10, "right"),
pad("cost (USD)", 14, "right"),
pad("vs Claude", 14, "right"),
pad("saved", 10, "right"),
].join(" ");
}
function divider(): string {
return "-".repeat(70);
}
function bucketRow(b: UsageBucket): string {
const hit = bucketCacheHitRatio(b);
const savings = bucketSavingsFraction(b);
return [
pad(b.label, 10),
pad(b.turns.toString(), 8, "right"),
pad(b.turns > 0 ? `${(hit * 100).toFixed(1)}%` : "—", 10, "right"),
pad(b.turns > 0 ? `$${b.costUsd.toFixed(6)}` : "—", 14, "right"),
pad(b.turns > 0 ? `$${b.claudeEquivUsd.toFixed(4)}` : "—", 14, "right"),
pad(b.turns > 0 && savings > 0 ? `${(savings * 100).toFixed(1)}%` : "—", 10, "right"),
].join(" ");
}
function pad(s: string, width: number, align: "left" | "right" = "left"): string {
if (s.length >= width) return s;
const fill = " ".repeat(width - s.length);
return align === "right" ? `${fill}${s}` : `${s}${fill}`;
}
+143
View File
@@ -0,0 +1,143 @@
/**
* `reasonix update` — self-upgrade command.
*
* Talks to the npm registry, compares against the running version,
* and either runs `npm install -g reasonix@latest` (global install)
* or advises how to refresh the npx cache (ephemeral install).
*
* The decision logic is factored into `planUpdate()` so it can be
* unit-tested without spawning child processes or hitting the
* network. `updateCommand()` is the thin CLI wrapper that calls
* `getLatestVersion`, passes the result into `planUpdate`, and
* executes any suggested command.
*/
import { spawn } from "node:child_process";
import { VERSION, compareVersions, getLatestVersion, isNpxInstall } from "../../version.js";
export type UpdateAction = "up-to-date" | "newer-local" | "npx-hint" | "run-npm-install";
export interface UpdatePlan {
action: UpdateAction;
/** Human-readable summary; the CLI prints this verbatim. */
message: string;
/**
* Argv for the install command when `action === "run-npm-install"`.
* Absent otherwise. Kept as array so the CLI can pass it straight
* to `spawn` without re-parsing shell syntax.
*/
command?: string[];
}
export interface PlanUpdateInput {
current: string;
latest: string;
/** Overrides `isNpxInstall()` (tests). */
npx?: boolean;
}
/**
* Pure decision function: given current + latest + install kind,
* decide what the CLI should do. No I/O.
*
* newer-local — current > latest (dev build, local publish)
* up-to-date — current === latest
* npx-hint — current < latest AND running under npx
* run-npm-install — current < latest AND running as a real install
*/
export function planUpdate(input: PlanUpdateInput): UpdatePlan {
const diff = compareVersions(input.current, input.latest);
if (diff > 0) {
return {
action: "newer-local",
message: `current (${input.current}) is newer than the published ${input.latest} — nothing to do.`,
};
}
if (diff === 0) {
return { action: "up-to-date", message: `reasonix ${input.current} is up to date.` };
}
if (input.npx) {
return {
action: "npx-hint",
message: [
`reasonix ${input.latest} is available.`,
"you're running via npx — the next `npx reasonix ...` launch will auto-fetch",
"the latest (npx caches packages for a short window). to force a refresh",
"sooner, clear the cache: `npm cache clean --force`.",
].join("\n"),
};
}
return {
action: "run-npm-install",
message: `upgrading reasonix ${input.current} → ${input.latest}`,
command: ["npm", "install", "-g", "reasonix@latest"],
};
}
export interface UpdateCommandOptions {
/** Skip spawning npm; print the decision only. */
dryRun?: boolean;
/** Test seam: override the registry lookup. Returns null = offline. */
fetchLatest?: () => Promise<string | null>;
/** Test seam: override the npx detector. */
isNpx?: () => boolean;
/** Test seam: override the spawner. Must return exit code. */
spawnInstall?: (argv: string[]) => Promise<number>;
/** Test seam: stdout writer. */
write?: (msg: string) => void;
/** Test seam: process exit — tests don't want to tear down vitest. */
exit?: (code: number) => void;
}
function defaultSpawn(argv: string[]): Promise<number> {
return new Promise((resolve, reject) => {
// `shell: true` on Windows is what lets `npm` resolve to `npm.cmd`
// without routing through our `prepareSpawn` helper. The args here
// are literal strings under our control — no user input flows in,
// so injection is not a concern. Avoiding `prepareSpawn` keeps
// this command free of a dep on the shell tools module.
const child = spawn(argv[0]!, argv.slice(1), {
stdio: "inherit",
shell: process.platform === "win32",
});
child.once("error", reject);
child.once("exit", (code) => resolve(code ?? 1));
});
}
/**
* Run the update command. Prints a banner, resolves the latest
* version, prints the plan, and (unless `--dry-run`) executes the
* install when applicable.
*/
export async function updateCommand(opts: UpdateCommandOptions = {}): Promise<void> {
const write = opts.write ?? ((m: string) => process.stdout.write(m));
const exit = opts.exit ?? ((c: number) => process.exit(c));
const fetchLatest = opts.fetchLatest ?? (() => getLatestVersion({ force: true }));
const isNpx = opts.isNpx ?? isNpxInstall;
const doSpawn = opts.spawnInstall ?? defaultSpawn;
write(`current: reasonix ${VERSION}\n`);
const latest = await fetchLatest();
if (!latest) {
write("could not reach registry.npmjs.org — check your network.\n");
exit(1);
return;
}
write(`latest: reasonix ${latest}\n`);
const plan = planUpdate({ current: VERSION, latest, npx: isNpx() });
write(`\n${plan.message}\n`);
if (plan.action !== "run-npm-install" || !plan.command) return;
if (opts.dryRun) {
write(`(dry run) would run: ${plan.command.join(" ")}\n`);
return;
}
write(`\nrunning: ${plan.command.join(" ")}\n`);
const code = await doSpawn(plan.command);
if (code !== 0) {
write(`\nnpm exited with code ${code}. upgrade did not complete.\n`);
exit(code);
}
}
+61 -13
View File
@@ -1,6 +1,8 @@
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";
import { diffCommand } from "./commands/diff.js";
@@ -11,11 +13,31 @@ import { runCommand } from "./commands/run.js";
import { sessionsCommand } from "./commands/sessions.js";
import { setupCommand } from "./commands/setup.js";
import { statsCommand } from "./commands/stats.js";
import { updateCommand } from "./commands/update.js";
import { versionCommand } from "./commands/version.js";
import { resolveDefaults } from "./resolve.js";
const DEFAULT_SYSTEM =
"You are Reasonix, a helpful DeepSeek-powered assistant. Be concise and accurate. Use tools when available.";
const DEFAULT_SYSTEM = `You are Reasonix, a helpful DeepSeek-powered assistant. Be concise and accurate. Use tools when available.
# Cite or shut up — non-negotiable
Every factual claim about a codebase must be backed by evidence. Reasonix VALIDATES your citations — broken paths render in **red strikethrough with ❌** in front of the user.
**Positive claims** — append a markdown link:
- ✅ \`The MCP client supports listResources [listResources](src/mcp/client.ts:142).\`
- ❌ \`The MCP client supports listResources.\` ← unverifiable, do not write.
**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.
# 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
@@ -37,7 +59,7 @@ program.action(async () => {
const defaults = resolveDefaults({});
await chatCommand({
model: defaults.model,
system: DEFAULT_SYSTEM,
system: applyMemoryStack(DEFAULT_SYSTEM, process.cwd()),
harvest: defaults.harvest,
branch: defaults.branch,
session: defaults.session,
@@ -55,17 +77,26 @@ program
program
.command("code [dir]")
.description(
"Code-editing chat — filesystem MCP auto-bridged at <dir> (default: cwd), coding system prompt, smart preset. 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",
"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({
dir,
model: opts.model,
noSession: opts.session === false,
transcript: opts.transcript,
forceResume: !!opts.resume,
forceNew: !!opts.new,
harvest: !!opts.harvest,
});
});
@@ -77,19 +108,21 @@ 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').")
.option("--no-session", "Disable session persistence for this run (ephemeral chat)")
.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(
"--mcp <spec>",
'MCP server spec; repeatable. "name=cmd args...", "cmd args...", or a URL (http/https → SSE transport). Overrides config.mcp when provided.',
@@ -113,13 +146,15 @@ program
});
await chatCommand({
model: defaults.model,
system: opts.system,
system: applyMemoryStack(opts.system, process.cwd()),
transcript: opts.transcript,
harvest: defaults.harvest,
branch: defaults.branch,
session: defaults.session,
mcp: defaults.mcp,
mcpPrefix: opts.mcpPrefix,
forceResume: !!opts.resume,
forceNew: !!opts.new,
});
});
@@ -159,7 +194,7 @@ program
await runCommand({
task,
model: defaults.model,
system: opts.system,
system: applyMemoryStack(opts.system, process.cwd()),
harvest: defaults.harvest,
branch: defaults.branch,
transcript: opts.transcript,
@@ -169,9 +204,12 @@ program
});
program
.command("stats <transcript>")
.description("Summarize a JSONL transcript produced by `reasonix chat --transcript`.")
.action((transcript: string) => {
.command("stats [transcript]")
.description(
"Show usage dashboard (today / week / month / all-time · turns · cache hit · cost · savings vs Claude). " +
"Pass a transcript path to fall back to the per-file summary (assistant turns + tool calls).",
)
.action((transcript: string | undefined) => {
statsCommand({ transcript });
});
@@ -251,6 +289,16 @@ mcp
program.command("version").description("Print Reasonix version.").action(versionCommand);
program
.command("update")
.description(
"Check the npm registry for a newer Reasonix and install it. Detects npx vs global install; for npx users, prints a cache-refresh hint instead of running `npm i -g`.",
)
.option("--dry-run", "Print the plan without executing the install")
.action(async (opts: { dryRun?: boolean }) => {
await updateCommand({ dryRun: !!opts.dryRun });
});
program.parseAsync(process.argv).catch((err) => {
console.error(err);
process.exit(1);
+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 {
+2255 -385
View File
File diff suppressed because it is too large. Load diff
+82
View File
@@ -0,0 +1,82 @@
import { Box, Text } from "ink";
// biome-ignore lint/style/useImportType: tsconfig.jsx = "react" needs React in value scope for JSX compilation
import React from "react";
export interface AtMentionSuggestionsProps {
/**
* Current matching file paths, ranked by the picker. `null` means
* "not in @-prefix mode" — render nothing. Empty array means "in @
* mode but no files match that partial" — render a hint.
*/
matches: readonly string[] | null;
/** Index (within `matches`) of the currently highlighted row. */
selectedIndex: number;
/** The partial query the user typed after `@`. Shown in the hint row. */
query: string;
}
/**
* Floating `@`-mention picker. Rendered below the input box when the
* user is typing an `@…` prefix in code mode. Navigation state lives
* in the parent (App.tsx owns `atSelected`) — this component is pure
* display. Mirrors {@link SlashSuggestions} shape so the keybindings
* and layout feel identical across the two pickers.
*/
export function AtMentionSuggestions({
matches,
selectedIndex,
query,
}: AtMentionSuggestionsProps): React.ReactElement | null {
if (matches === null) return null;
if (matches.length === 0) {
return (
<Box paddingX={1} marginTop={1}>
<Text color="yellow">no files match "@{query}"</Text>
<Text dimColor>
{" "}
— keep typing, or Backspace to edit. Paths resolve from the code root.
</Text>
</Box>
);
}
const MAX = 8;
const total = matches.length;
const windowStart =
total <= MAX ? 0 : Math.max(0, Math.min(selectedIndex - Math.floor(MAX / 2), total - MAX));
const shown = matches.slice(windowStart, windowStart + MAX);
const hiddenAbove = windowStart;
const hiddenBelow = total - windowStart - shown.length;
return (
<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} />
))}
{hiddenBelow > 0 ? <Text dimColor> ↓ {hiddenBelow} more below</Text> : null}
<Text dimColor> [↑↓] navigate · [Tab]/[Enter] pick · file content inlined on send</Text>
</Box>
);
}
function FileRow({ path, isSelected }: { path: string; isSelected: boolean }) {
// Split the path so the basename visually pops — same dropdown
// affordance as VS Code's Quick Open.
const slash = path.lastIndexOf("/");
const dir = slash >= 0 ? `${path.slice(0, slash)}/` : "";
const base = slash >= 0 ? path.slice(slash + 1) : path;
if (isSelected) {
return (
<Box>
<Text backgroundColor="#67e8f9" color="black" bold>
{` ▸ ${base}${dir ? ` ${dir}` : ""} `}
</Text>
</Box>
);
}
return (
<Box>
<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>
);
}
+676 -151
View File
@@ -1,12 +1,52 @@
import { Box, Text } from "ink";
import React, { useEffect, useState } from "react";
import { Box, Text, useStdout } from "ink";
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;
@@ -17,19 +57,153 @@ 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
* pacing — without it, five-turn sessions read as one wall of
* text. Only the *first* user message in a session should leave
* this off; App.tsx sets it based on whether history is empty.
*/
leadSeparator?: boolean;
}
export const EventRow = React.memo(function EventRow({ event }: { event: DisplayEvent }) {
/**
* Reasonix visual language: every event is anchored by a geometric
* glyph in its role color. Together they form a consistent alphabet
* (◇ ◆ ▣ ▥ ▲ ✦) the eye learns fast — no text labels needed after
* the first couple of turns. `◈` is the brand mark, reserved for
* the app header.
*/
const ROLE_GLYPH = {
user: "◇",
assistant: "◆",
assistantPulse: "◇", // pulse alternate for streaming state
toolOk: "▣",
toolErr: "▥",
warning: "▲",
error: "✦",
} as const;
function RoleGlyph({
glyph,
color,
}: {
glyph: string;
color: "cyan" | "green" | "yellow" | "red" | "magenta" | "blue";
}) {
return (
<Text color={color} bold>
{glyph}
</Text>
);
}
/**
* 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,
}: {
event: DisplayEvent;
projectRoot?: string;
}) {
if (event.role === "user") {
return (
<Box>
<Text bold color="cyan">
you ›{" "}
</Text>
<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>
);
}
@@ -38,73 +212,274 @@ export const EventRow = React.memo(function EventRow({ event }: { event: Display
return (
<Box flexDirection="column" marginTop={1}>
<Box>
<Text bold color="green">
assistant
</Text>
<RoleGlyph glyph={ROLE_GLYPH.assistant} color="green" />
{event.stats ? (
<>
<Text>{" "}</Text>
<Text backgroundColor={COLOR.assistant} color="black" bold>
{` ${event.stats.model.replace(/^deepseek-/, "")} `}
</Text>
</>
) : null}
</Box>
<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) ? (
<PlanStateBlock planState={event.planState!} />
) : null}
{event.text ? (
<Markdown text={event.text} projectRoot={projectRoot} />
) : (
<Text dimColor>(no content)</Text>
)}
{event.stats ? <StatsLine stats={event.stats} /> : null}
{event.repair ? <Text color={COLOR.accent}>{event.repair}</Text> : null}
</Box>
{event.branch ? <BranchBlock branch={event.branch} /> : null}
{event.reasoning ? <ReasoningBlock reasoning={event.reasoning} /> : null}
{!isPlanStateEmpty(event.planState) ? (
<PlanStateBlock planState={event.planState!} />
) : null}
{event.text ? <Markdown text={event.text} /> : <Text dimColor>(no content)</Text>}
{event.stats ? <StatsLine stats={event.stats} /> : null}
{event.repair ? <Text color="magenta">{event.repair}</Text> : null}
</Box>
);
}
if (event.role === "tool") {
// `flattenMcpResult` prefixes server-side errors with "ERROR: ".
// Render those in red with a ✗ marker so they don't blend into
// successful tool output (yellow) — the failure mode is what the
// model most likely needs to act on next, and the user needs to
// see at a glance.
const isError = event.text.startsWith("ERROR:");
const color = isError ? "red" : "yellow";
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;
(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} />
</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 flexDirection="column" marginTop={1}>
<Text color={color}>{`tool<${event.toolName ?? "?"}> ${marker}`}</Text>
{isEditFile ? (
<EditFileDiff text={event.text} />
) : (
<Text color={isError ? "red" : undefined} dimColor={!isError}>
{" "}
{truncate(event.text, 400)}
</Text>
)}
<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}>
<Text color="red" bold>
error{" "}
<Text backgroundColor="#f87171" color="black" bold>
{" ✦ ERROR "}
</Text>
<Text color="red">{event.text}</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>
<Text color="yellow">▸ </Text>
<Text color="yellow">{event.text}</Text>
<Text backgroundColor="#fbbf24" color="black" bold>
{" ▲ WARN "}
</Text>
<Text>{" "}</Text>
<Text color="#fbbf24">{indentContinuationLines(event.text)}</Text>
</Box>
);
}
@@ -115,6 +490,43 @@ export const EventRow = React.memo(function EventRow({ event }: { event: Display
);
});
/**
* 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);
// 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}>
{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>
{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>
);
}
/**
* Render the payload of an `edit_file` tool result with proper
* diff coloring: first line is the header ("edited X (A→B chars)"),
@@ -128,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>
@@ -171,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>
);
}
@@ -202,8 +644,11 @@ function ReasoningBlock({ reasoning }: { reasoning: string }) {
flat.length <= max ? flat : `… (+${flat.length - max} earlier chars) ${flat.slice(-max)}`;
return (
<Box marginBottom={1}>
<Text dimColor italic>
{"↳ thinking: "}
<Text backgroundColor={COLOR.accent} color="black" bold>
{" ⋯ thinking "}
</Text>
<Text> </Text>
<Text color={COLOR.accent} italic dimColor>
{preview}
</Text>
</Box>
@@ -216,17 +661,28 @@ function ReasoningBlock({ reasoning }: { reasoning: string }) {
* the terminal viewport and leaves artifacts in scrollback.
*/
function Elapsed() {
const [s, setS] = useState(0);
useEffect(() => {
const start = Date.now();
const id = setInterval(() => setS(Math.floor((Date.now() - start) / 1000)), 1000);
return () => clearInterval(id);
}, []);
const s = useElapsedSeconds();
const mm = String(Math.floor(s / 60)).padStart(2, "0");
const ss = String(s % 60).padStart(2, "0");
return <Text dimColor>{`${mm}:${ss}`}</Text>;
}
/**
* Animated role glyph for the actively-streaming assistant. Alternates
* ◆ ↔ ◇ every ~480ms so the user can see the model is alive even
* during R1's long pre-first-byte silence. Settles back to a static
* ◆ once the turn ends (StreamingAssistant is unmounted).
*/
function PulsingAssistantGlyph() {
const tick = useTick();
const on = Math.floor(tick / 4) % 2 === 0;
return (
<Text color="green" bold>
{on ? ROLE_GLYPH.assistant : ROLE_GLYPH.assistantPulse}
</Text>
);
}
function StreamingAssistant({ event }: { event: DisplayEvent }) {
if (event.branchProgress) {
const p = event.branchProgress;
@@ -235,15 +691,17 @@ function StreamingAssistant({ event }: { event: DisplayEvent }) {
return (
<Box flexDirection="column" marginTop={1}>
<Box>
<Text bold color="green">
assistant{" "}
</Text>
<PulsingAssistantGlyph />
<Text color="blue">
🔀 launching {p.total} parallel samples (R1 thinking in parallel)…{" "}
{" ⎇ launching "}
{p.total}
{" parallel samples (R1 thinking in parallel)… "}
</Text>
<Elapsed />
</Box>
<Text dimColor>{" "}spread across T=0.0/0.5/1.0 · typical wait 30-90s for reasoner</Text>
<Text color="yellow">
{" "}spread across T=0.0/0.5/1.0 · reasoner typically takes 30-90s — this is normal
</Text>
</Box>
);
}
@@ -251,11 +709,13 @@ function StreamingAssistant({ event }: { event: DisplayEvent }) {
return (
<Box flexDirection="column" marginTop={1}>
<Box>
<Text bold color="green">
assistant{" "}
</Text>
<PulsingAssistantGlyph />
<Text color="blue">
🔀 branching {p.completed}/{p.total} ({pct}%){" "}
{" ⎇ branching "}
{p.completed}/{p.total}
{" ("}
{pct}
{"%) "}
</Text>
<Elapsed />
</Box>
@@ -274,79 +734,138 @@ function StreamingAssistant({ event }: { event: DisplayEvent }) {
const tail = lastLine(event.text, 140);
const reasoningTail = event.reasoning ? lastLine(event.reasoning, 120) : "";
const toolCallBuild = event.toolCallBuild;
// Four distinct phases a turn can be in — label them plainly so
// the user doesn't have to decode "streaming · 391 + think 4506
// chars" to figure out what's happening:
// pre-first-byte: request in flight, no bytes back yet
// reasoning-only: R1 thinking, no visible content yet
// tool-call-only: tool_call arguments streaming, no content/reasoning bytes
// writing: content streaming (R1 has already produced its thought)
// both: rare — content present AND reasoning still growing
// We can't cheaply distinguish "reasoning still growing" from
// "reasoning finished but we already saw it", so when content is
// present we just say "writing response" and surface both counts.
const preFirstByte = !event.text && !event.reasoning;
const reasoningOnly = !event.text && !!event.reasoning;
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" | 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) {
pillBg = "#f0abfc"; // fuchsia
pillText = "DISPATCH";
label = `assembling${formatToolCallIndex(toolCallBuild)} <${toolCallBuild.name}> · ${toolCallBuild.chars} chars${formatReadyTail(toolCallBuild)}`;
} else {
// Content phase. If reasoning is non-empty we include its size
// so the user knows R1 did a thinking pass before speaking.
label = event.reasoning
? `writing response · ${event.text.length} chars · after ${event.reasoning.length} chars of reasoning`
: `writing response · ${event.text.length} chars`;
labelColor = "green";
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(
`tool${formatToolCallIndex(toolCallBuild)} <${toolCallBuild.name}> ${toolCallBuild.chars}c${formatReadyTail(toolCallBuild)}`,
);
}
label = parts.join(" · ");
}
return (
<Box flexDirection="column" marginTop={1}>
<Box>
<Text bold color="green">
assistant{" "}
</Text>
<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 amber: first-time users misread the dim version as
// "app frozen". The reassurance has to be VISIBLE to do its job.
<Box paddingLeft={3}>
<Text color="#fbbf24" italic>
{"waiting for first byte — typical 5–60s depending on model + load"}
</Text>
</Box>
) : reasoningOnly ? (
<Text color="yellow" dimColor>
{
" R1 is thinking before it speaks — body text starts when reasoning completes (typically 20-90s)."
}
</Text>
) : (
<Text dimColor italic>
{" connection open, first byte typically in 5-60s depending on model + load"}
</Text>
)}
<Box paddingLeft={3}>
<Text color="#c4b5fd" italic>
{"R1 thinks before it speaks — body text arrives when reasoning finishes (20–90s)"}
</Text>
</Box>
) : toolCallOnly ? (
<Box paddingLeft={3}>
<Text color="#f0abfc" italic>
{"tool-call arguments streaming — about to dispatch"}
</Text>
</Box>
) : event.reasoning ? (
<Box paddingLeft={3}>
<Text color="#fbbf24" italic>
{"R1 still reasoning — body text or tool call arrives when thinking finishes"}
</Text>
</Box>
) : null}
</Box>
);
}
/**
* Blinking indicator so the user can tell the stream is alive even
* when the reasoner hasn't produced body text yet. Ticks every 500 ms
* regardless of content flow — it's a heartbeat, not a progress bar.
* when the reasoner hasn't produced body text yet. Uses the shared
* tick (TICK_MS ≈ 120ms) scaled down 4× so the visible blink rate
* lands around 500ms — feels like a heartbeat, not a progress bar.
*/
function Pulse() {
const [tick, setTick] = useState(0);
useEffect(() => {
const id = setInterval(() => setTick((t) => t + 1), 500);
return () => clearInterval(id);
}, []);
const tick = useTick();
const frames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
return <Text color="cyan">{frames[tick % frames.length]}</Text>;
return <Text color="cyan">{frames[Math.floor(tick / 4) % frames.length]}</Text>;
}
/**
* "(call 3)" suffix for the tool-call label when we have the index.
* Hides when the turn only has one call so the common case stays tidy.
*/
function formatToolCallIndex(tb: { index?: number; readyCount?: number } | undefined): string {
if (!tb || tb.index === undefined) return "";
// Only show the index when this isn't obviously the first + only call.
if (tb.index === 0 && (tb.readyCount ?? 0) === 0) return "";
return ` (call ${tb.index + 1})`;
}
/**
* "· 2 ready" tail that answers "how many tool calls have finished
* streaming so far this turn?" — user feedback for multi-file turns
* where the response takes 10–30s to stream. Hidden until readyCount
* > 0 so single-call turns aren't cluttered.
*/
function formatReadyTail(tb: { readyCount?: number } | undefined): string {
const n = tb?.readyCount ?? 0;
if (n <= 0) return "";
return ` · ${n} ready`;
}
function lastLine(s: string, maxChars: number): string {
@@ -357,20 +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 (
<Text dimColor>
{" ↳ cache "}
{hit}
{"% · tokens "}
{stats.usage.promptTokens}
{"→"}
{stats.usage.completionTokens}
{" · $"}
{stats.cost.toFixed(6)}
</Text>
<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>
);
}
function truncate(s: string, max: number): string {
return s.length <= max ? s : `${s.slice(0, max)}… (+${s.length - max} chars)`;
}
+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;
}
+100
View File
@@ -0,0 +1,100 @@
/**
* Modal-style approval for a `submit_plan` proposal.
*
* Three choices:
* 1. Approve + implement — exits plan mode, pushes a synthetic user
* message telling the model to implement the plan now.
* 2. Refine — stays in plan mode; tells the model to explore more
* and submit an improved plan.
* 3. Cancel — exits plan mode, drops the plan, tells the model the
* user didn't want any of it.
*
* 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";
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;
projectRoot?: string;
}
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.
const hasOpenQuestions =
/^#{1,6}\s*(open[-\s]?questions?|risks?|unknowns?|assumptions?|unclear)/im.test(plan) ||
/^#{1,6}\s*(待确认|开放问题|风险|未知|假设|不确定)/im.test(plan);
return (
<ModalCard
accent="#67e8f9"
icon="📋"
title="plan proposed"
subtitle={summary ?? "approve / refine / cancel"}
>
{hasOpenQuestions ? (
<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}
{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>
);
}
// React.memo: parent App re-renders every 120ms while the global ticker
// is running (even with the live status rows hidden — context changes
// propagate). Unless props change, skip re-rendering the heavy Markdown
// subtree. Default shallow prop compare is fine — `plan` + `onChoose`
// identity + `projectRoot` are the only fields that change.
export const PlanConfirm = React.memo(PlanConfirmInner);
+133
View File
@@ -0,0 +1,133 @@
/**
* Inline text input shown after the user picks Approve or Refine in
* PlanConfirm. Collects free-form feedback before the loop resumes.
*
* Why both paths: the plan may contain open questions or risks the
* model asked the user to weigh in on. If the user just picks Approve
* with no chance to answer, the model implements against its own
* guesses. This input lets the user answer questions, pass last-minute
* constraints, or (on Refine) request concrete changes. Empty input is
* fine for Approve (skip straight to implement) and triggers a
* "ask the user clarifying questions" path for Refine.
*
* Kept minimal: single-line prompt, Enter to submit, Esc to return to
* the picker without resuming.
*/
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";
* 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" | "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. */
onCancel: () => void;
}
export function PlanRefineInput({ mode, onSubmit, onCancel }: PlanRefineInputProps) {
const [value, setValue] = useState("");
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 (ev.return) {
onSubmit(value.trim());
return;
}
if (ev.backspace || ev.delete) {
setValue((v) => v.slice(0, -1));
return;
}
// Filter out non-printable chars; accept ordinary text + CJK.
if (ev.input && !ev.ctrl && !ev.meta) {
setValue((v) => v + ev.input);
}
});
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"
? {
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."
: 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.)"
: 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 (
<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>
<Text color={meta.accent} bold>
{"› "}
</Text>
<Text>{value}</Text>
<Text color={meta.accent} bold>
{cursorOn ? "▍" : " "}
</Text>
</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;
}
+536 -87
View File
@@ -1,6 +1,53 @@
import { Box, Text, useInput } from "ink";
import React, { useEffect, useState } from "react";
import { type MultilineKey, processMultilineKey } from "./multiline-keys.js";
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 {
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";
import { useTick } from "./ticker.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;
@@ -8,113 +55,515 @@ 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 multi-line composition support. Behaves like the
* old single-line prompt by default, but:
* - Ctrl+J inserts a newline (universal across terminals).
* - Shift+Enter inserts a newline (only on terminals that report
* the modifier via CSI-u — many don't).
* - `\<Enter>` at end of line acts as bash-style continuation —
* always works, even on terminals without modifier reporting.
* - Pasted multi-line text lands as-is instead of submitting on
* the first '\r'.
*
* No mid-string insertion cursor — edits happen at the end, like
* a readline prompt in raw mode. Simple, predictable, enough for
* 95% of prompts and any code paste.
*/
export function PromptInput({
value,
onChange,
onSubmit,
disabled,
placeholder,
onHistoryPrev,
onHistoryNext,
}: PromptInputProps) {
const [showCursor, setShowCursor] = useState(true);
const [cursor, setCursor] = useState(value.length);
// Blink the end-of-input cursor so it's visibly alive even when
// the user hasn't typed for a while. 500 ms matches a typical
// terminal cursor blink.
useEffect(() => {
if (disabled) {
setShowCursor(false);
// 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) setCursor(value.length);
}
/**
* 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);
};
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;
}
setShowCursor(true);
const id = setInterval(() => setShowCursor((s) => !s), 500);
return () => clearInterval(id);
}, [disabled]);
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);
}
onSubmit(expanded);
}
if (action.historyHandoff === "prev") onHistoryPrev?.();
if (action.historyHandoff === "next") onHistoryNext?.();
}, !disabled);
useInput(
(input, key) => {
const keyEvent: 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, keyEvent);
if (action.next !== null) onChange(action.next);
if (action.submit) onSubmit(action.submitValue ?? value);
},
{ isActive: !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 (Shift+Enter where supported)";
const effectivePlaceholder = disabled
? (placeholder ?? "…waiting for response…")
: (placeholder ?? "type a message, or /command · Ctrl+J for newline");
: (placeholder ?? placeholderActive);
const lines = value.length > 0 ? value.split("\n") : [""];
const borderColor = disabled ? "gray" : "cyan";
const accentColor = disabled ? "gray" : "cyan";
// Animation gate. Below ~100 cols a typed line plus prefix can
// wrap; Ink's eraseLines miscounts on wrap and ghost rows pile up
// every tick. Suppress the bar gradient + cursor blink when
// narrow so the prompt renders statically — same fix the
// StatsPanel uses on its rules.
const animate = !disabled && cols >= 100;
const tick = useTick();
const barOffset = animate ? Math.floor(tick / 6) : 0;
const barColorAt = (rowIdx: number): string =>
disabled
? "gray"
: GRADIENT[(((rowIdx + barOffset) % GRADIENT.length) + GRADIENT.length) % GRADIENT.length]!;
// Cursor blink — toggles every 4 ticks (~480 ms) so the prompt
// looks alive at rest. Cursor stays solid while disabled (busy
// turn) or narrow (anti-flash) so the screen reads as frozen,
// not dead.
const cursorVisible = animate ? Math.floor(tick / 4) % 2 === 0 : 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 isLast = i === lines.length - 1;
const isFirst = i === 0;
const showPlaceholder = isFirst && value.length === 0;
// Line content never survives a re-keying here: the value buffer
// fully re-renders on every keystroke, so the array index IS the
// stable identity. Biome's rule targets list reordering, which
// doesn't apply to an append-only splits-by-newline view.
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>
)}
{/* When showing the placeholder, the cursor is at position 0 —
put it BEFORE the dimmed hint text so it visually matches
"you're about to type here," not "you typed the placeholder."
When showing real content, the cursor follows the last char
of the last line (append-only edit model). */}
{showPlaceholder && isLast && !disabled ? (
<Text color={borderColor}>{showCursor ? "▌" : " "}</Text>
) : null}
{showPlaceholder ? <Text dimColor>{effectivePlaceholder}</Text> : <Text>{line}</Text>}
{!showPlaceholder && isLast && !disabled ? (
<Text color={borderColor}>{showCursor ? "▌" : " "}</Text>
) : null}
</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>
);
}
// ── PromptLine ────────────────────────────────────────────────────
interface PromptLineProps {
line: string;
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 (
<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 (
<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 =
+29 -13
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. */
@@ -28,6 +29,13 @@ export interface SingleSelectProps<V extends string> {
initialValue?: V;
onSubmit: (value: V) => void;
onCancel?: () => void;
/**
* Optional footer rendered dim beneath the list, e.g.
* `"[↑↓] navigate · [Enter] select · [Esc] cancel"`. Makes keyboard
* affordances discoverable — otherwise new users hit `y`/`n` and
* wonder why nothing happens.
*/
footer?: string;
}
export function SingleSelect<V extends string>({
@@ -35,6 +43,7 @@ export function SingleSelect<V extends string>({
initialValue,
onSubmit,
onCancel,
footer,
}: SingleSelectProps<V>) {
const initialIndex = Math.max(
0,
@@ -42,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();
}
});
@@ -65,6 +75,11 @@ export function SingleSelect<V extends string>({
marker={i === index ? "▸" : " "}
/>
))}
{footer ? (
<Box marginTop={1}>
<Text dimColor>{footer}</Text>
</Box>
) : null}
</Box>
);
}
@@ -74,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;
}
@@ -91,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) => {
@@ -105,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();
}
});
+72
View File
@@ -0,0 +1,72 @@
import { Box, Text } from "ink";
import React from "react";
import { SingleSelect } from "./Select.js";
export type SessionChoice = "resume" | "new" | "delete";
export interface SessionPickerProps {
sessionName: string;
messageCount: number;
/** mtime of the session file; used to render "last active Nh ago". */
lastActive: Date;
onChoose: (choice: SessionChoice) => void;
}
export function SessionPicker({
sessionName,
messageCount,
lastActive,
onChoose,
}: SessionPickerProps) {
return (
<Box flexDirection="column" marginY={1}>
<Box marginBottom={1}>
<Text bold color="cyan">
{`Session "${sessionName}" has ${messageCount} prior message${messageCount === 1 ? "" : "s"}`}
</Text>
<Text dimColor>{` · last active ${relativeTime(lastActive)}`}</Text>
</Box>
<SingleSelect
initialValue="new"
items={[
{
value: "new",
label: "Start new conversation",
hint: "Previous messages kept on disk; your turn starts fresh.",
},
{
value: "resume",
label: "Resume",
hint: `Continue where you left off (${messageCount} messages in context).`,
},
{
value: "delete",
label: "Delete and start new",
hint: "Wipes the session file irreversibly. Other sessions untouched.",
},
]}
onSubmit={(v) => onChoose(v as SessionChoice)}
/>
<Box marginTop={1}>
<Text dimColor>[↑↓] navigate · [Enter] select</Text>
</Box>
</Box>
);
}
/**
* "Nh ago" / "Nm ago" / "yesterday" style relative time. Deliberately
* coarse — the picker just needs a sense of "how stale is this session".
*/
function relativeTime(date: Date): string {
const ms = Date.now() - date.getTime();
const mins = Math.floor(ms / 60_000);
if (mins < 1) return "just now";
if (mins < 60) return `${mins}m ago`;
const hours = Math.floor(mins / 60);
if (hours < 24) return `${hours}h ago`;
const days = Math.floor(hours / 24);
if (days === 1) return "yesterday";
if (days < 7) return `${days}d ago`;
return date.toISOString().slice(0, 10);
}
+117
View File
@@ -0,0 +1,117 @@
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";
export interface ShellConfirmProps {
command: string;
/**
* The prefix that would be persisted if the user picks
* "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;
}
/**
* Modal-style approval for a shell command the model wants to run.
* Three choices:
* 1. Run once — execute this invocation, prefix NOT remembered.
* 2. Always allow — persist the prefix to `~/.reasonix/config.json`
* under this project so every future invocation with that prefix
* auto-runs.
* 3. Deny — tell the model the user refused.
* 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, 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 (
<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>
<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>
);
}
/**
* Pick the "always allow" prefix from a full command. Heuristic:
* - one-token commands ("ls", "pytest") → the token itself
* - multi-token → first two tokens for well-known wrappers
* (`npm install`, `git commit`, `cargo add`, `docker run` …)
* otherwise just the first token (covers `node <script>` where the
* second token is usually a file path specific to this invocation).
* Exported so tests can pin the heuristic.
*/
export function derivePrefix(command: string): string {
const tokens = command.trim().split(/\s+/).filter(Boolean);
if (tokens.length === 0) return "";
if (tokens.length === 1) return tokens[0]!;
const first = tokens[0]!;
const TWO_TOKEN_WRAPPERS = new Set([
"npm",
"npx",
"pnpm",
"yarn",
"bun",
"git",
"cargo",
"go",
"docker",
"kubectl",
"python",
"python3",
"deno",
"pip",
"pip3",
"make",
"rake",
"bundle",
"gem",
]);
return TWO_TOKEN_WRAPPERS.has(first) ? `${first} ${tokens[1]}` : first;
}
+108
View File
@@ -0,0 +1,108 @@
import { Box, Text } from "ink";
// biome-ignore lint/style/useImportType: tsconfig.jsx = "react" needs React in value scope for JSX compilation
import React from "react";
import type { SlashCommandSpec } from "./slash.js";
export interface SlashArgPickerProps {
/**
* When set, render a picker with these matches (filter already
* applied upstream). Null → not in picker mode; check `hintSpec`
* for a usage hint instead.
*/
matches: readonly string[] | null;
/** Highlighted row within `matches`. */
selectedIndex: number;
/**
* Spec of the command the user is typing args for. Used to render
* the header label ("/edit <file>") even when matches is empty or
* the caller wants a hint instead of a picker.
*/
spec: SlashCommandSpec;
/** What kind of arg guidance to render. */
kind: "picker" | "hint";
/** The user's partial input — shown in the "no matches" hint. */
partial: string;
}
/**
* Argument-level picker for a slash command. Mirrors the visual
* layout of SlashSuggestions / AtMentionSuggestions so the UI stays
* consistent across all three picker surfaces.
*/
export function SlashArgPicker({
matches,
selectedIndex,
spec,
kind,
partial,
}: SlashArgPickerProps): React.ReactElement | null {
// Hint mode: a single dim row explaining the argsHint + summary.
if (kind === "hint") {
return (
<Box paddingX={1} marginTop={1}>
<Text dimColor>
{" "}
<Text bold>/{spec.cmd}</Text>
{spec.argsHint ? ` ${spec.argsHint}` : ""} — {spec.summary}
</Text>
</Box>
);
}
if (matches === null) return null;
if (matches.length === 0) {
return (
<Box flexDirection="column" paddingX={1} marginTop={1}>
<Text dimColor>
{" "}
<Text bold>/{spec.cmd}</Text>
{spec.argsHint ? ` ${spec.argsHint}` : ""} — {spec.summary}
</Text>
<Text color="yellow"> no match for "{partial}" — keep typing, or Backspace to edit</Text>
</Box>
);
}
const MAX = 8;
const total = matches.length;
const windowStart =
total <= MAX ? 0 : Math.max(0, Math.min(selectedIndex - Math.floor(MAX / 2), total - MAX));
const shown = matches.slice(windowStart, windowStart + MAX);
const hiddenAbove = windowStart;
const hiddenBelow = total - windowStart - shown.length;
return (
<Box flexDirection="column" paddingX={1} marginTop={1}>
<Text dimColor>
{" "}
<Text bold>/{spec.cmd}</Text>
{spec.argsHint ? ` ${spec.argsHint}` : ""} — {spec.summary}
</Text>
{hiddenAbove > 0 ? <Text dimColor> ↑ {hiddenAbove} more above</Text> : null}
{shown.map((value, i) => (
<ArgRow key={value} value={value} isSelected={windowStart + i === selectedIndex} />
))}
{hiddenBelow > 0 ? <Text dimColor> ↓ {hiddenBelow} more below</Text> : null}
<Text dimColor> [↑↓] navigate · [Tab]/[Enter] pick</Text>
</Box>
);
}
function ArgRow({ value, isSelected }: { value: string; isSelected: boolean }) {
const marker = isSelected ? "▸" : " ";
if (isSelected) {
return (
<Box>
<Text bold color="cyan">
{marker} {value}
</Text>
</Box>
);
}
return (
<Box>
<Text dimColor>
{marker} {value}
</Text>
</Box>
);
}
+9 -15
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,41 +45,35 @@ 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} />
))}
{hiddenBelow > 0 ? <Text dimColor> ↓ {hiddenBelow} more below</Text> : null}
<Text dimColor> ↑/↓ navigate · Tab or Enter to pick</Text>
<Text dimColor> [↑↓] navigate · [Tab]/[Enter] pick</Text>
</Box>
);
}
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>
);
}
+598 -69
View File
@@ -1,7 +1,55 @@
import { Box, Text } from "ink";
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 { COLOR, GRADIENT } from "./theme.js";
import { useTick } from "./ticker.js";
const WORDMARK_LETTERS: ReadonlyArray<string> = ["R", "E", "A", "S", "O", "N", "I", "X"];
/**
* 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.
*/
function Wordmark({ busy, animate }: { busy: boolean; animate: boolean }) {
const tick = useTick();
// Bold pulse on the brand mark — kept even when animations are
// suppressed because it's just a single-cell bold toggle, no
// re-rendered text width that could wrap.
const pulsePeriod = busy ? 5 : 12;
const bright = animate ? Math.floor(tick / pulsePeriod) % 2 === 0 : true;
// Gradient flow. Higher value = slower flow. When `animate` is
// false (narrow terminal — wrapping risk) we freeze the offset
// at 0 so re-renders don't pile up ghost rows from miscounted
// erases.
const rotateEvery = busy ? 2 : 4;
const offset = animate ? Math.floor(tick / rotateEvery) : 0;
const colorAt = (i: number) =>
GRADIENT[(((i + offset) % GRADIENT.length) + GRADIENT.length) % GRADIENT.length]!;
return (
<Text>
<Text color={colorAt(0)} bold={bright}>
◈
</Text>
<Text> </Text>
{WORDMARK_LETTERS.map((letter, i) => (
<Text key={letter} color={colorAt(i + 1)} bold>
{letter}
</Text>
))}
</Text>
);
}
export interface StatsPanelProps {
summary: SessionSummary;
@@ -9,6 +57,26 @@ 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
* can tell at a glance that edits are gated behind submit_plan +
* 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
@@ -18,96 +86,557 @@ export interface StatsPanelProps {
* with USD both see "getting low."
*/
balance?: { currency: string; total: number } | null;
/**
* Published npm version newer than VERSION. Rendered as a yellow
* "· update: X" nudge in the panel header. `null` / `undefined`
* hides the nudge (offline launch, already up to date, or check
* still in flight).
*/
updateAvailable?: string | null;
/**
* True when the loop is currently mid-turn — drives the wordmark's
* "busy breathing" animation. Visual signal that the app is thinking,
* 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;
}
/**
* Terminal width under which we switch from one-line metrics to a
* stacked layout. Below 120 cols the wide version wraps mid-number
* and the parens ("in $X · out $Y") get split across lines — which
* looks broken. Stacking costs one row but stays readable on every
* SSH / split-pane case we've hit.
*/
const NARROW_BREAKPOINT = 120;
/**
* Cache-hit ratio is always zero on turn 1 (there's literally no cache
* to hit yet). Showing that as red "0.0%" is a false alarm — new users
* read it as "something is broken." We suppress the gradient until a
* few turns have landed; by turn 4 the cache has had time to warm up.
*/
const COLD_START_TURNS = 3;
export function StatsPanel({
summary,
model,
prefixHash,
harvestOn,
branchBudget,
reasoningEffort,
planMode,
editMode,
balance,
updateAvailable,
busy,
proArmed,
escalated,
}: StatsPanelProps) {
const hitPct = (summary.cacheHitRatio * 100).toFixed(1);
const hitColor =
summary.cacheHitRatio >= 0.7 ? "green" : summary.cacheHitRatio >= 0.4 ? "yellow" : "red";
const branchOn = (branchBudget ?? 1) > 1;
const ctxMax = DEEPSEEK_CONTEXT_TOKENS[model] ?? DEFAULT_CONTEXT_TOKENS;
const ctxRatio = summary.lastPromptTokens / ctxMax;
const ctxColor = ctxRatio >= 0.8 ? "red" : ctxRatio >= 0.5 ? "yellow" : undefined;
const { stdout } = useStdout();
const columns = stdout?.columns ?? 80;
const narrow = columns < NARROW_BREAKPOINT;
// Cold-start: first few turns render cache+cost muted so a 0.0% hit
// rate on turn 1 doesn't look like an error. Once the cache has
// actually had a chance to build, we flip to the live gradient.
const coldStart = summary.turns <= COLD_START_TURNS;
// The two decorative gradient rules (top + bottom) frame the panel
// as one visual unit instead of leaving the wordmark floating in
// the void. Width tracks the terminal so the bar always stretches
// edge-to-edge; falls back to 78 cells in tests / no-stdout.
const ruleWidth = Math.max(20, columns - 2);
// Animation gate. Re-rendering every tick is fine when nothing in
// the live region wraps — Ink's eraseLines counts visible rows
// accurately. But at narrow widths the header / rules / pills
// wrap, Ink miscounts, and ghost rows pile up on every tick = the
// "screen flashing" symptom users see. We suppress all live-
// region animation below a safe threshold so static rendering can
// still look good without the churn.
const animate = columns >= 100;
return (
<Box borderStyle="round" borderColor="cyan" flexDirection="column" paddingX={1}>
<Box justifyContent="space-between">
<Text>
<Text color="cyan" bold>
Reasonix
</Text>
<Text dimColor> · model </Text>
<Text color="yellow">{model}</Text>
<Text dimColor> · prefix </Text>
<Text dimColor>{prefixHash}</Text>
{harvestOn ? <Text color="magenta"> · harvest</Text> : null}
{branchOn ? <Text color="blue"> · branch{branchBudget}</Text> : null}
</Text>
<Text dimColor>turns {summary.turns} · type /help</Text>
// Borderless layout: no `borderStyle`, no rounded box. Bordered
// Boxes were the most visible amplifier of Ink's eraseLines
// miscount on Windows terminals. Visual weight here comes from
// truecolor gradient rules at the top and bottom (rendered as
// pure Text so they never trigger the eraseLines bug), the
// animated wordmark + pill row, and a soft inner padding.
<Box flexDirection="column" paddingX={1} marginBottom={1}>
<GradientRule width={ruleWidth} animate={animate} />
<Box marginTop={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={animate}
/>
</Box>
<Box marginTop={1} gap={3}>
<Text>
<Text dimColor>cache hit </Text>
<Text color={hitColor} bold>
{hitPct}%
</Text>
</Text>
<Text>
<Text dimColor>cost </Text>
<Text color="green" bold>
${summary.totalCostUsd.toFixed(6)}
</Text>
<Text dimColor>
{" (in "}${summary.totalInputCostUsd.toFixed(6)}
{" · out "}${summary.totalOutputCostUsd.toFixed(6)}
{")"}
</Text>
</Text>
{summary.lastPromptTokens > 0 ? (
<Text>
<Text dimColor>ctx </Text>
<Text color={ctxColor} bold={ctxColor !== undefined}>
{formatTokens(summary.lastPromptTokens)}/{formatTokens(ctxMax)}
</Text>
<Text dimColor> ({(ctxRatio * 100).toFixed(0)}%)</Text>
{ctxRatio >= 0.8 ? (
<Text color="red" bold>
{" "}
· /compact
</Text>
) : null}
</Text>
) : null}
{balance ? (
<Text>
<Text dimColor>balance </Text>
<Text color={balance.total < 1 ? "red" : balance.total < 5 ? "yellow" : "green"} bold>
{balance.currency === "USD" ? "$" : ""}
{balance.total.toFixed(2)}
{balance.currency !== "USD" ? ` ${balance.currency}` : ""}
</Text>
</Text>
) : null}
{narrow ? (
<StackedMetrics
summary={summary}
ctxRatio={ctxRatio}
ctxMax={ctxMax}
balance={balance}
coldStart={coldStart}
/>
) : (
<InlineMetrics
summary={summary}
ctxRatio={ctxRatio}
ctxMax={ctxMax}
balance={balance}
coldStart={coldStart}
/>
)}
<Box marginTop={1}>
<GradientRule width={ruleWidth} thin animate={animate} />
</Box>
</Box>
);
}
/**
* Compact integer formatter: 1234 → "1.2k", 131072 → "131k". Keeps the
* panel narrow enough to fit on 80-col terminals even when the context
* is near full.
* One-line gradient bar spanning the panel width. `thin` swaps the
* solid block for a half-block so the bottom of the panel is
* visually quieter than the top — top reads as "header band", bottom
* reads as "section close." Colors flow over time (one cell every
* ~720 ms) so the panel feels alive without being twitchy. Each
* cell renders as its own Text so Ink's runtime can color each
* character independently; this is the pattern the wordmark uses
* too.
*/
function GradientRule({
width,
thin,
animate,
}: {
width: number;
thin?: boolean;
animate: boolean;
}) {
const tick = useTick();
// When animation is suppressed (narrow terminal) freeze offset
// so the bar still gets the gradient sweep but doesn't re-render.
const offset = animate ? Math.floor(tick / 6) : 0;
const ch = thin ? "▁" : "▄";
const len = GRADIENT.length;
return (
<Box>
{Array.from({ length: width }, (_, i) => {
const t = width === 1 ? 0 : (i * (len - 1)) / (width - 1);
const idx = (Math.round(t) + offset) % len;
const color = GRADIENT[((idx % len) + len) % len]!;
return (
// biome-ignore lint/suspicious/noArrayIndexKey: fixed-width gradient cells never reorder
<Text key={`grule-${i}`} color={color}>
{ch}
</Text>
);
})}
</Box>
);
}
function Header({
model,
prefixHash,
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} animate={animate} />
<Text dimColor>{` ${VERSION}`}</Text>
<Text dimColor>{" "}</Text>
<Text color="yellow" bold>
{model.replace(/^deepseek-/, "")}
</Text>
{modePill ? (
<>
<Text>{" "}</Text>
<Pill label={modePill.label} bg={modePill.bg} />
</>
) : 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>{`↑ ${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
* treatment folded in.
*/
function InlineMetrics({
summary,
ctxRatio,
ctxMax,
balance,
coldStart,
}: {
summary: SessionSummary;
ctxRatio: number;
ctxMax: number;
balance?: { currency: string; total: number } | null;
coldStart: boolean;
}) {
return (
<Box marginTop={1} gap={3}>
<ContextCell ratio={ctxRatio} promptTokens={summary.lastPromptTokens} ctxMax={ctxMax} />
<CacheCell hitRatio={summary.cacheHitRatio} coldStart={coldStart} turns={summary.turns} />
<CostCell summary={summary} coldStart={coldStart} />
{balance ? <BalanceCell balance={balance} /> : null}
</Box>
);
}
/**
* Narrow-terminal layout (<120 cols): one metric per line, in priority
* order (ctx → balance → cache → cost). Order matters because users
* scanning a cramped terminal want "am I about to hit a wall?" answered
* first; dollars spent comes later.
*/
function StackedMetrics({
summary,
ctxRatio,
ctxMax,
balance,
coldStart,
}: {
summary: SessionSummary;
ctxRatio: number;
ctxMax: number;
balance?: { currency: string; total: number } | null;
coldStart: boolean;
}) {
return (
<Box marginTop={1} flexDirection="column">
<ContextCell
ratio={ctxRatio}
promptTokens={summary.lastPromptTokens}
ctxMax={ctxMax}
showBar
/>
{balance ? <BalanceCell balance={balance} /> : null}
<CacheCell hitRatio={summary.cacheHitRatio} coldStart={coldStart} turns={summary.turns} />
<CostCell summary={summary} coldStart={coldStart} />
</Box>
);
}
function ContextCell({
ratio,
promptTokens,
ctxMax,
showBar,
}: {
ratio: number;
promptTokens: number;
ctxMax: number;
showBar?: boolean;
}) {
if (promptTokens === 0) {
return (
<Text>
<Text color={COLOR.info} dimColor>
{"▣ ctx "}
</Text>
<Text dimColor>— (no turns yet)</Text>
</Text>
);
}
const color = ratio >= 0.8 ? COLOR.err : ratio >= 0.6 ? COLOR.warn : COLOR.ok;
const pct = Math.round(ratio * 100);
return (
<Text>
<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={COLOR.err} bold>
{" · /compact"}
</Text>
) : null}
</Text>
);
}
function CacheCell({
hitRatio,
coldStart,
turns,
}: {
hitRatio: number;
coldStart: boolean;
turns: number;
}) {
const pct = (hitRatio * 100).toFixed(1);
if (turns === 0) {
return (
<Text>
<Text color={COLOR.info} dimColor>
{"⌬ cache "}
</Text>
<Text dimColor>—</Text>
</Text>
);
}
if (coldStart) {
return (
<Text>
<Text color={COLOR.info} dimColor>
{"⌬ cache "}
</Text>
<Text dimColor>{pct}% </Text>
<Text dimColor italic>
(cold start)
</Text>
</Text>
);
}
const color = hitRatio >= 0.7 ? COLOR.ok : hitRatio >= 0.4 ? COLOR.warn : COLOR.err;
return (
<Text>
<Text color={COLOR.info}>{"⌬ cache "}</Text>
<Text color={color} bold>
{pct}%
</Text>
</Text>
);
}
/**
* 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,
}: {
summary: SessionSummary;
coldStart: boolean;
}) {
if (summary.turns === 0) {
return (
<Text>
<Text color={COLOR.info} dimColor>
{"◴ cost "}
</Text>
<Text dimColor>—</Text>
</Text>
);
}
// The first turn is unavoidably a cache-miss (nothing to hit),
// 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 turnColor = coldStart ? undefined : turnCostColor(summary.lastTurnCostUsd);
const sessionColor = coldStart ? undefined : sessionCostColor(summary.totalCostUsd);
return (
<Text>
<Text color={COLOR.info}>{"◴ turn "}</Text>
<Text color={turnColor} bold={!coldStart} dimColor={coldStart}>
${summary.lastTurnCostUsd.toFixed(4)}
</Text>
<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 ? COLOR.err : balance.total < 5 ? COLOR.warn : COLOR.ok;
return (
<Text>
<Text color={COLOR.info}>{"◐ balance "}</Text>
<Text color={color} bold>
{balance.currency === "USD" ? "$" : ""}
{balance.total.toFixed(2)}
{balance.currency !== "USD" ? ` ${balance.currency}` : ""}
</Text>
</Text>
);
}
/**
* 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,
cells = 14,
}: {
ratio: number;
color: string;
cells?: number;
}) {
const filled = Math.max(0, Math.min(cells, Math.round(ratio * cells)));
return (
<Text>
<Text color={color}>{"▰".repeat(filled)}</Text>
<Text dimColor>{"▱".repeat(cells - filled)}</Text>
</Text>
);
}
/**
* Compact token formatter using binary K (÷1024): 1234 → "1.2K",
* 131072 → "128K". Matches DeepSeek's marketing label of "128K context
* length" — showing "131k" confused users (the actual limit is
* 128×1024 = 131,072 tokens, but the doc consistently says "128K").
* Uppercase K signals binary-K to anyone who notices.
*/
function formatTokens(n: number): string {
if (n < 1000) return String(n);
const k = n / 1000;
return k >= 100 ? `${k.toFixed(0)}k` : `${k.toFixed(1)}k`;
if (n < 1024) return String(n);
const k = n / 1024;
return k >= 100 ? `${k.toFixed(0)}K` : `${k.toFixed(1)}K`;
}
+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>
+39
View File
@@ -0,0 +1,39 @@
/**
* Bash-mode (`!cmd`) prefix parsing.
*
* A `!` at the start of the user's input means "run this as a shell
* command in the sandbox root, and put both the command and its output
* into the conversation so the model sees it next turn." Same idea as
* Claude Code's `!` prefix — faster than round-tripping through the
* model just to cat a file or check git status.
*
* Design choice: user-typed `!` commands skip the allowlist. The
* allowlist exists to bound what the MODEL can do with run_command;
* the user typing `!git push` by hand is explicit consent. If a user
* wants stricter gating they can set `REASONIX_BANG_CONFIRM=1` in a
* future iteration.
*/
/**
* Return the command portion of a `!`-prefixed input, or `null` if
* the text isn't a bang invocation. Trims leading/trailing whitespace
* from the command body. `!` alone (or `!` followed by only whitespace)
* returns `null` — no command to run.
*/
export function detectBangCommand(text: string): string | null {
if (!text.startsWith("!")) return null;
const body = text.slice(1).trim();
if (!body) return null;
return body;
}
/**
* Format a bang command + its output into a single user-role message
* body that the model will see on the next turn. The `[!cmd]` header
* marks the run explicitly so the model can distinguish
* user-typed shell output from its own `run_command` tool results
* (which are `role: tool`, different message shape entirely).
*/
export function formatBangUserMessage(cmd: string, output: string): string {
return `[!${cmd}]\n${output}`;
}
+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 };
}
+989 -92
View File
File diff suppressed because it is too large. Load diff
+242
View File
@@ -0,0 +1,242 @@
/**
* `/resource` and `/prompt` slash handlers for the chat/code TUI.
*
* The slash-command registry (slash.ts) advertises both commands so the
* argument-level picker and /help surface them, but the actual read/fetch
* work is async — McpClient.readResource and getPrompt both round-trip to
* the server — so it doesn't fit the synchronous `handleSlash` shape used
* by every other slash command. App.tsx intercepts the commands directly
* and calls into the helpers below.
*
* Split by effect boundary:
* - formatters (resource list, contents, prompt list, messages) are
* pure over already-fetched data and unit-tested
* - find-server helpers are pure lookups against inspection reports
* - `handleMcpBrowseSlash` is the async orchestrator App.tsx calls
*
* v1 intentionally does NOT inject the fetched resource/prompt into the
* next model turn. It's a display-only browser so users can see what
* their MCP servers expose. A future version may add a Tab-to-inject
* hotkey once the UX is settled.
*/
import type { McpClient } from "../../mcp/client.js";
import type {
GetPromptResult,
McpPromptMessage,
McpResourceContents,
ReadResourceResult,
} from "../../mcp/types.js";
import type { DisplayEvent } from "./EventLog.js";
import type { McpServerSummary } from "./slash.js";
/**
* React setState for Historical — typed loose because the App state
* shape is App-internal. We only ever append, so `(prev) => prev.concat(row)`
* works against any array-of-DisplayEvent state.
*/
export type HistoricalSetter = (updater: (prev: DisplayEvent[]) => DisplayEvent[]) => void;
export function formatResourceList(servers: readonly McpServerSummary[]): string {
const lines: string[] = [];
let total = 0;
for (const s of servers) {
if (!s.report.resources.supported) continue;
const items = s.report.resources.items;
if (items.length === 0) continue;
lines.push(`[${s.label}] ${items.length} resource(s):`);
for (const r of items.slice(0, 20)) {
const name = r.name && r.name !== r.uri ? ` ${r.name}` : "";
const mime = r.mimeType ? ` · ${r.mimeType}` : "";
lines.push(` · ${r.uri}${name}${mime}`);
total++;
}
if (items.length > 20) lines.push(` (+${items.length - 20} more)`);
lines.push("");
}
if (total === 0) {
return "No resources on any connected MCP server (or no servers connected). `/mcp` shows the current set.";
}
lines.push("Read one: `/resource <uri>` — or use Tab in the picker.");
return lines.join("\n");
}
export function formatPromptList(servers: readonly McpServerSummary[]): string {
const lines: string[] = [];
let total = 0;
for (const s of servers) {
if (!s.report.prompts.supported) continue;
const items = s.report.prompts.items;
if (items.length === 0) continue;
lines.push(`[${s.label}] ${items.length} prompt(s):`);
for (const p of items.slice(0, 20)) {
const desc = p.description ? ` — ${p.description}` : "";
const argHint =
p.arguments && p.arguments.length > 0
? ` (args: ${p.arguments.map((a) => a.name + (a.required ? "*" : "?")).join(", ")})`
: "";
lines.push(` · ${p.name}${argHint}${desc}`);
total++;
}
if (items.length > 20) lines.push(` (+${items.length - 20} more)`);
lines.push("");
}
if (total === 0) {
return "No prompts on any connected MCP server (or no servers connected). `/mcp` shows the current set.";
}
lines.push(
"Fetch one: `/prompt <name>` — args are not supported yet; prompts with required args will surface an error from the server.",
);
return lines.join("\n");
}
export function findServerForResource(
servers: readonly McpServerSummary[],
uri: string,
): McpServerSummary | null {
for (const s of servers) {
if (!s.report.resources.supported) continue;
if (s.report.resources.items.some((r) => r.uri === uri)) return s;
}
return null;
}
export function findServerForPrompt(
servers: readonly McpServerSummary[],
name: string,
): McpServerSummary | null {
for (const s of servers) {
if (!s.report.prompts.supported) continue;
if (s.report.prompts.items.some((p) => p.name === name)) return s;
}
return null;
}
export function formatResourceContents(uri: string, result: ReadResourceResult): string {
const lines: string[] = [`Resource ${uri} (${result.contents.length} content block(s)):`, ""];
for (let i = 0; i < result.contents.length; i++) {
const c = result.contents[i]!;
const header = `— block ${i + 1}${c.mimeType ? ` · ${c.mimeType}` : ""}`;
lines.push(header);
lines.push(formatOneResourceContent(c));
lines.push("");
}
return lines.join("\n").trimEnd();
}
function formatOneResourceContent(c: McpResourceContents): string {
if ("text" in c) {
const MAX = 8_000;
if (c.text.length > MAX) {
return `${c.text.slice(0, MAX)}\n\n[…truncated ${c.text.length - MAX} chars; full contents available via McpClient.readResource in library mode.]`;
}
return c.text;
}
// blob — we can't render arbitrary binary in the TUI; give the size.
const bytes = typeof c.blob === "string" ? approximateBase64ByteSize(c.blob) : 0;
return `[binary · ~${bytes.toLocaleString()} bytes · base64]`;
}
function approximateBase64ByteSize(b64: string): number {
// 4 base64 chars encode 3 bytes; padding `=` trims the output.
const padding = b64.endsWith("==") ? 2 : b64.endsWith("=") ? 1 : 0;
return Math.floor((b64.length * 3) / 4) - padding;
}
export function formatPromptMessages(name: string, result: GetPromptResult): string {
const lines: string[] = [
`Prompt ${name}${result.description ? ` — ${result.description}` : ""}`,
`(${result.messages.length} message(s))`,
"",
];
for (let i = 0; i < result.messages.length; i++) {
const m = result.messages[i]!;
lines.push(`— ${i + 1}. ${m.role}`);
lines.push(formatOnePromptMessage(m));
lines.push("");
}
return lines.join("\n").trimEnd();
}
function formatOnePromptMessage(m: McpPromptMessage): string {
const block = m.content as { type?: string; text?: string; resource?: McpResourceContents };
if (block.type === "text" && typeof block.text === "string") return block.text;
if (block.type === "resource" && block.resource) {
return `[resource: ${block.resource.uri}]\n${formatOneResourceContent(block.resource)}`;
}
return `[non-text content: ${block.type ?? "unknown"}]`;
}
/**
* Orchestrator. Looks up the right server, calls readResource/getPrompt
* via its `client`, and pushes one info row into `Historical`. Errors
* (server missing, -32601, network) surface as a warning row; the user
* can always fall back to `reasonix mcp inspect <spec>` for diagnostics.
*/
export async function handleMcpBrowseSlash(
kind: "resource" | "prompt",
arg: string,
servers: readonly McpServerSummary[],
setHistorical: HistoricalSetter,
): Promise<void> {
const ts = Date.now();
const push = (role: DisplayEvent["role"], text: string) => {
setHistorical((prev) => [...prev, { id: `mcp-${role}-${ts}-${prev.length}`, role, text }]);
};
// No arg → list mode.
if (!arg) {
push("info", kind === "resource" ? formatResourceList(servers) : formatPromptList(servers));
return;
}
if (kind === "resource") {
const server = findServerForResource(servers, arg);
if (!server) {
push(
"warning",
`no server exposes resource "${arg}". \`/resource\` with no arg lists what's available.`,
);
return;
}
const client: McpClient | undefined = server.client;
if (!client) {
push(
"warning",
`server [${server.label}] is not connected (display-only). Resource read requires a live MCP client.`,
);
return;
}
try {
const result = await client.readResource(arg);
push("info", formatResourceContents(arg, result));
} catch (err) {
push("warning", `readResource failed: ${(err as Error).message}`);
}
return;
}
// prompt
const server = findServerForPrompt(servers, arg);
if (!server) {
push(
"warning",
`no server exposes prompt "${arg}". \`/prompt\` with no arg lists what's available.`,
);
return;
}
const client: McpClient | undefined = server.client;
if (!client) {
push(
"warning",
`server [${server.label}] is not connected (display-only). Prompt fetch requires a live MCP client.`,
);
return;
}
try {
const result = await client.getPrompt(arg);
push("info", formatPromptMessages(arg, result));
} catch (err) {
push("warning", `getPrompt failed: ${(err as Error).message}`);
}
}
+267 -75
View File
@@ -1,30 +1,40 @@
/**
* Pure keystroke → action reducer for MultilineInput.
* Pure keystroke → action reducer for PromptInput.
*
* Kept separate from the React component so the keyboard
* semantics are easy to unit-test. MultilineInput is otherwise
* a thin Ink wrapper that threads its `useInput` callback
* through this function and applies the result.
* Kept separate from the React component so the keyboard semantics
* are easy to unit-test. The component threads `useInput` through
* this function and applies the returned action.
*
* Terminal reality check: on most terminals, pressing Shift+Enter
* sends the exact same byte as plain Enter — the modifier is lost.
* That's why the reliable newline insertion path is Ctrl+J (which
* really is LF, distinct from CR), with Shift+Enter only working
* on terminals that opt into CSI-u modifier encoding. The `\<Enter>`
* bash-style continuation is the portable fallback.
* Edit model:
* - Full cursor support. ←/→ move one column. ↑/↓ move across
* lines in a multi-line buffer (column preserved when possible).
* Ctrl+A / Ctrl+E jump to start / end of the current line.
* - Backspace deletes the char before the cursor; Delete deletes
* the char under the cursor.
* - Printable chars (including multi-char paste bursts) insert
* at the cursor.
* - Enter submits unless Shift is held (newline), the line ends
* with '\' and cursor is at end (bash-style continuation), or
* the input is Ctrl+J (LF, terminal-universal newline).
* - 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 {
/** Printable character(s) delivered by the key event, may be empty. */
input: string;
/** Modifier + named-key flags as Ink reports them. */
return?: boolean;
shift?: boolean;
ctrl?: boolean;
meta?: boolean;
backspace?: boolean;
delete?: boolean;
/** Navigation/editing keys owned by the parent App (slash-nav, history). */
tab?: boolean;
upArrow?: boolean;
downArrow?: boolean;
@@ -36,87 +46,269 @@ export interface MultilineKey {
}
export interface MultilineAction {
/** New value to set on the text buffer. `null` = unchanged. */
/** New buffer value. `null` = unchanged. */
next: string | null;
/** When `true`, the caller should fire `onSubmit(next ?? value)`. */
/** New cursor position (0..value.length). `null` = unchanged. */
cursor: number | null;
/** When `true`, fire `onSubmit(submitValue ?? value)`. */
submit: boolean;
/** When submitting, which value to submit (after any final trims). */
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 = /\\$/;
/**
* Decide what to do with a single keystroke against the current buffer.
*
* Decisions:
* Ctrl+J → insert '\n' (terminal-universal newline)
* Shift+Return → insert '\n' (works where CSI-u is on)
* Enter with "\" end → replace trailing '\' with '\n' (bash continuation)
* Enter → submit the current buffer
* Backspace/Delete → drop one char from the end (cursor-at-end model)
* Printable char(s) → append at the end
*
* We don't model an insertion cursor inside the string: always-at-end
* keeps the reducer tiny and matches how readline-in-raw-mode feels. The
* user can still edit by backspacing — for deep edits, exit and compose
* in $EDITOR.
*/
export function processMultilineKey(value: string, key: MultilineKey): MultilineAction {
// Parent App owns these keys: Tab for slash auto-complete, arrows
// for slash-nav/history, Esc for abort. Bowing out here keeps the
// text buffer from eating a stray "\t" or arrow escape sequence
// when both the parent and child useInput fire on the same event.
if (
key.tab ||
key.upArrow ||
key.downArrow ||
key.leftArrow ||
key.rightArrow ||
key.escape ||
key.pageUp ||
key.pageDown
) {
return { next: null, submit: false };
const NOOP: MultilineAction = { next: null, cursor: null, submit: false };
export function processMultilineKey(
value: string,
cursor: number,
keyIn: MultilineKey,
): MultilineAction {
// 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;
}
// Reliable newline: Ctrl+J arrives as literal '\n' in key.input on
// every terminal we've checked. We also accept key.ctrl && input=='j'
// as a belt-and-braces match against terminals that normalize the
// control-char into its ASCII letter form.
// Buffer-wide navigation. Per-line motion (↑/↓ / Ctrl+A / Ctrl+E)
// is already covered; PageUp/PageDown are the missing "jump to
// top / bottom of the WHOLE buffer" pair, useful after pasting a
// 500-line blob where ↑×500 is absurd. Repurposed from the
// previous NOOP behavior (PageUp/Down had no binding).
if (key.pageUp) {
return cursor === 0 ? NOOP : { next: null, cursor: 0, submit: false };
}
if (key.pageDown) {
return cursor === value.length ? NOOP : { next: null, cursor: value.length, submit: false };
}
// Empty buffer + ↑/↓ → parent handles history recall.
if (value.length === 0 && (key.upArrow || key.downArrow)) {
return { ...NOOP, historyHandoff: key.upArrow ? "prev" : "next" };
}
// Cursor motion.
if (key.leftArrow) {
return { next: null, cursor: Math.max(0, cursor - 1), submit: false };
}
if (key.rightArrow) {
return { next: null, cursor: Math.min(value.length, cursor + 1), submit: false };
}
if (key.upArrow) {
const moved = moveCursorUp(value, cursor);
// Cursor already on the first line — hand off to history recall
// instead of sitting stuck. Users can now escape into history
// from the middle of a multi-line draft.
if (moved === cursor) return { ...NOOP, historyHandoff: "prev" };
return { next: null, cursor: moved, submit: false };
}
if (key.downArrow) {
const moved = moveCursorDown(value, cursor);
if (moved === cursor) return { ...NOOP, historyHandoff: "next" };
return { next: null, cursor: moved, submit: false };
}
// Emacs-style line jumps (universal across terminals; Home/End aren't
// reliably reported by Ink so we don't depend on them).
if (key.ctrl && key.input === "a") {
return { next: null, cursor: startOfLine(value, cursor), submit: false };
}
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,
};
}
// 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 { next: `${value}\n`, submit: false };
return insertAt(value, cursor, "\n");
}
if (key.return) {
// Shift+Return → newline (when terminal reports the modifier).
if (key.shift) {
return { next: `${value}\n`, submit: false };
if (key.shift) return insertAt(value, cursor, "\n");
// Bash-style line continuation: trailing '\' + Enter (only when the
// cursor sits at end-of-buffer, so a stray '\' mid-line doesn't
// trigger it).
if (cursor === value.length && BACKSLASH_SUFFIX.test(value)) {
const replaced = `${value.slice(0, -1)}\n`;
return { next: replaced, cursor: replaced.length, submit: false };
}
// Bash-style line continuation: trailing '\' + Enter.
if (BACKSLASH_SUFFIX.test(value)) {
return { next: `${value.slice(0, -1)}\n`, submit: false };
}
// Plain Enter → submit.
return { next: null, submit: true, submitValue: value };
return { next: null, cursor: null, submit: true, submitValue: value };
}
if (key.backspace || key.delete) {
if (value.length === 0) return { next: null, submit: false };
return { next: value.slice(0, -1), submit: false };
// Backspace = delete the char BEFORE the cursor. We also accept
// `key.delete` and the raw DEL (0x7f) / BS (0x08) bytes as backspace
// for the same purpose — some Windows terminals (cmd.exe, certain
// winpty configs) report plain Backspace without setting
// `key.backspace`, which used to leave the user typing into a prompt
// where the Backspace key did nothing. Reasonix doesn't offer a
// separate forward-delete operation, so collapsing them is safe.
if (key.backspace || key.delete || key.input === "\x7f" || key.input === "\b") {
if (cursor === 0) return NOOP;
return {
next: value.slice(0, cursor - 1) + value.slice(cursor),
cursor: cursor - 1,
submit: false,
};
}
// Ignore bare modifier keys (ctrl/meta without accompanying printable).
if ((key.ctrl || key.meta) && key.input.length === 0) {
return { next: null, submit: false };
// Bare modifier events (Ctrl/Meta with no printable) and unhandled
// Ctrl-<letter> chords are dropped so a stray Ctrl+L doesn't insert "l".
if ((key.ctrl || key.meta) && key.input.length === 0) return NOOP;
if (key.ctrl || key.meta) return NOOP;
// Printable input (may be a multi-char paste; pasted newlines land
// inside the buffer rather than triggering submit on the first line).
if (key.input.length > 0) {
return insertAt(value, cursor, key.input);
}
// Printable input (may be a multi-char paste burst — accept as-is;
// pasted newlines become part of the buffer rather than triggering
// submit on the first line).
if (key.input.length > 0 && !key.ctrl && !key.meta) {
return { next: value + key.input, submit: false };
return NOOP;
}
function insertAt(value: string, cursor: number, insert: string): MultilineAction {
return {
next: value.slice(0, cursor) + insert + value.slice(cursor),
cursor: cursor + insert.length,
submit: false,
};
}
/**
* Line + column of a cursor inside a buffer. Exported because the
* renderer needs the same mapping for drawing the cursor block on the
* right line.
*/
export function lineAndColumn(value: string, cursor: number): { line: number; col: number } {
let line = 0;
let col = 0;
const n = Math.min(cursor, value.length);
for (let i = 0; i < n; i++) {
if (value[i] === "\n") {
line++;
col = 0;
} else {
col++;
}
}
return { line, col };
}
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;
}
function moveCursorUp(value: string, cursor: number): number {
const curStart = startOfLine(value, cursor);
if (curStart === 0) return cursor; // already on the first line
const col = cursor - curStart;
const prevEnd = curStart - 1; // the '\n' between the two lines
const prevStart = value.lastIndexOf("\n", prevEnd - 1) + 1;
const prevLen = prevEnd - prevStart;
return prevStart + Math.min(col, prevLen);
}
return { next: null, submit: false };
function moveCursorDown(value: string, cursor: number): number {
const nextNl = value.indexOf("\n", cursor);
if (nextNl === -1) return cursor; // already on the last line
const curStart = startOfLine(value, cursor);
const col = cursor - curStart;
const nextStart = nextNl + 1;
const followingNl = value.indexOf("\n", nextStart);
const nextLen = (followingNl === -1 ? value.length : followingNl) - nextStart;
return nextStart + Math.min(col, nextLen);
}
+81
View File
@@ -0,0 +1,81 @@
/**
* Collapse long user-typed input for display purposes.
*
* Problem: pasting a stack trace, log dump, or sample file into the
* prompt box floods the Historical scrollback with a huge block — the
* user can't see their previous turns, the assistant's replies, or
* where the cursor is. Terminal UIs have shipped this shape for
* years (iTerm's "pasted text" notation, Claude Code's preview).
*
* Split of concerns: the MODEL still gets the full text. This helper
* only rewrites what we render in the Historical row. `@` expansions
* and `!` bang outputs have their own display paths (unaffected).
*/
/** Defaults tuned to typical prose vs. typical code-paste shapes. */
export const DEFAULT_PASTE_LINE_THRESHOLD = 40;
export const DEFAULT_PASTE_CHAR_THRESHOLD = 2000;
/** Lines kept visible at the head of a collapsed paste. */
export const DEFAULT_PASTE_HEAD_LINES = 10;
export interface PasteCollapseOptions {
lineThreshold?: number;
charThreshold?: number;
headLines?: number;
}
export interface PasteCollapseResult {
/** Text to render in the Historical row (possibly collapsed). */
displayText: string;
/** True when collapsing happened. False = input passed through verbatim. */
collapsed: boolean;
/** Original char length — exposed so callers can log/annotate. */
originalChars: number;
/** Original line count. */
originalLines: number;
}
/**
* Collapse `input` when it exceeds either the line OR char threshold.
* Display shape:
*
* ▸ pasted 2.3 KB (84 lines) — first 10 shown, full text sent to model
* line 1
* line 2
* …
* line 10
* … (74 more lines)
*
* Short input passes through unchanged — collapsed = false.
*/
export function formatLongPaste(
input: string,
opts: PasteCollapseOptions = {},
): PasteCollapseResult {
const lineCap = opts.lineThreshold ?? DEFAULT_PASTE_LINE_THRESHOLD;
const charCap = opts.charThreshold ?? DEFAULT_PASTE_CHAR_THRESHOLD;
const headN = Math.max(1, opts.headLines ?? DEFAULT_PASTE_HEAD_LINES);
const originalChars = input.length;
const lines = input.split("\n");
const originalLines = lines.length;
if (originalChars <= charCap && originalLines <= lineCap) {
return { displayText: input, collapsed: false, originalChars, originalLines };
}
const header = `▸ pasted ${formatBytes(originalChars)} (${originalLines} lines) — first ${Math.min(headN, originalLines)} shown, full text sent to model`;
const head = lines.slice(0, headN).join("\n");
const remaining = originalLines - headN;
const footer = remaining > 0 ? `… (${remaining} more line${remaining === 1 ? "" : "s"})` : "";
const displayText = footer ? `${header}\n${head}\n${footer}` : `${header}\n${head}`;
return { displayText, collapsed: true, originalChars, originalLines };
}
function formatBytes(n: number): string {
if (n < 1024) return `${n} B`;
const kb = n / 1024;
if (kb < 1024) return `${kb.toFixed(kb >= 10 ? 0 : 1)} KB`;
const mb = kb / 1024;
return `${mb.toFixed(mb >= 10 ? 0 : 1)} MB`;
}
+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 -642
View File
@@ -1,642 +1,20 @@
import { spawnSync } from "node:child_process";
import type { CacheFirstLoop } from "../../loop.js";
import type { InspectionReport } from "../../mcp/inspect.js";
import { deleteSession, listSessions } from "../../session.js";
import { DEEPSEEK_CONTEXT_TOKENS, DEFAULT_CONTEXT_TOKENS } from "../../telemetry.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;
}
/**
* 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".
*/
codeUndo?: () => 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;
/**
* 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[];
}
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;
}
/**
* 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;
}
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",
},
{ cmd: "model", argsHint: "<id>", summary: "switch DeepSeek model id" },
{ cmd: "harvest", argsHint: "[on|off]", summary: "toggle Pillar-2 plan-state extraction" },
{ cmd: "branch", argsHint: "<N|off>", summary: "run N parallel samples per turn (N>=2)" },
{ cmd: "mcp", summary: "list MCP servers + tools attached to this session" },
{ cmd: "tool", argsHint: "[N]", summary: "dump full output of the Nth tool call (1=latest)" },
{ cmd: "think", summary: "dump the last turn's full R1 reasoning (reasoner only)" },
{ cmd: "retry", summary: "truncate & resend your last message (fresh sample)" },
{ cmd: "compact", argsHint: "[cap]", summary: "shrink oversized tool results in the log" },
{ 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: "commit",
argsHint: '"msg"',
summary: "git add -A && git commit -m ...",
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);
});
}
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) };
}
export function handleSlash(
cmd: string,
args: string[],
loop: CacheFirstLoop,
ctx: SlashContext = {},
): SlashResult {
switch (cmd) {
case "exit":
case "quit":
return { exit: true };
case "clear":
return {
clear: true,
info: "▸ cleared visible scrollback only. Context (message log) is intact — next turn still sees everything. Use /new to start fresh, or /forget to delete the session entirely.",
};
case "new":
case "reset": {
// 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.`,
};
}
case "help":
case "?":
return {
info: [
"Commands:",
" /help this message",
" /status show current settings",
" /preset <fast|smart|max> one-tap presets — see below",
" /model <id> deepseek-chat or deepseek-reasoner",
" /harvest [on|off] Pillar 2: structured plan-state extraction",
" /branch <N|off> run N parallel samples (N>=2), pick most confident",
" /mcp list MCP servers + tools attached to this session",
" /setup (exit + reconfigure) → run `reasonix setup`",
" /compact [cap] shrink large tool results in history (default 4k/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)",
" /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 last applied edit batch",
' /commit "msg" (code mode) git add -A && git commit -m "msg"',
" /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",
"",
"Presets:",
" fast deepseek-chat no harvest no branch ~1¢/100turns ← default",
" smart reasoner harvest ~10x cost, slower",
" max reasoner harvest branch 3 ~30x cost, slowest",
"",
"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",
].join("\n"),
};
case "mcp": {
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[] = [];
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);
lines.push("");
}
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") };
}
case "setup":
return {
info:
"To reconfigure (preset, MCP servers, API key), exit this chat and run " +
"`reasonix setup`. Changes take effect on next launch.",
};
case "retry": {
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,
};
}
case "think":
case "reasoning": {
const raw = loop.scratch.reasoning;
if (!raw || !raw.trim()) {
return {
info:
"no reasoning cached. `/think` shows the full R1 thought for the most recent turn — " +
"only `deepseek-reasoner` produces it, and only once the turn completes.",
};
}
return { info: `↳ full thinking (${raw.length} chars):\n\n${raw.trim()}` };
}
case "tool": {
// EventLog truncates tool results at 400 chars 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}`,
};
}
case "undo": {
if (!ctx.codeUndo) {
return {
info: "/undo is only available inside `reasonix code` — chat mode doesn't apply edits.",
};
}
return { info: ctx.codeUndo() };
}
case "apply": {
if (!ctx.codeApply) {
return {
info: "/apply is only available inside `reasonix code` (nothing to apply here).",
};
}
return { info: ctx.codeApply() };
}
case "discard": {
if (!ctx.codeDiscard) {
return {
info: "/discard is only available inside `reasonix code`.",
};
}
return { info: ctx.codeDiscard() };
}
case "commit": {
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);
}
case "compact": {
// Manual companion to the automatic heal-on-load. Re-applies
// truncation with a tighter cap (4k chars 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 >= 500 ? tight : 4000;
const { healedCount, charsSaved } = loop.compact(cap);
if (healedCount === 0) {
return {
info: `▸ nothing to compact — no tool result in history exceeds ${cap.toLocaleString()} chars.`,
};
}
return {
info: `▸ compacted ${healedCount} tool result(s), saved ${charsSaved.toLocaleString()} chars (~${Math.round(charsSaved / 4).toLocaleString()} tokens). Session file rewritten.`,
};
}
case "sessions": {
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") };
}
case "forget": {
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?)`,
};
}
case "status": {
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 lines = [
` model ${loop.model}`,
` flags harvest=${loop.harvestEnabled ? "on" : "off"} · branch=${branchBudget > 1 ? branchBudget : "off"} · stream=${loop.stream ? "on" : "off"}`,
ctxLine,
mcpLine,
sessionLine,
];
if (pendingLine) lines.push(pendingLine);
return { info: lines.join("\n") };
}
case "model": {
const id = args[0];
if (!id) return { info: "usage: /model <id> (try deepseek-chat or deepseek-reasoner)" };
loop.configure({ model: id });
return { info: `model → ${id}` };
}
case "harvest": {
const arg = (args[0] ?? "").toLowerCase();
const on = arg === "" ? !loop.harvestEnabled : arg === "on" || arg === "true" || arg === "1";
loop.configure({ harvest: on });
return { info: `harvest → ${loop.harvestEnabled ? "on" : "off"}` };
}
case "preset": {
const name = (args[0] ?? "").toLowerCase();
if (name === "fast" || name === "default") {
loop.configure({ model: "deepseek-chat", harvest: false, branch: 1 });
return { info: "preset → fast (deepseek-chat, no harvest, no branch)" };
}
if (name === "smart") {
loop.configure({ model: "deepseek-reasoner", harvest: true, branch: 1 });
return { info: "preset → smart (reasoner + harvest, ~10x cost vs fast)" };
}
if (name === "max" || name === "best") {
loop.configure({ model: "deepseek-reasoner", harvest: true, branch: 3 });
return {
info: "preset → max (reasoner + harvest + branch3, ~30x cost vs fast, slowest)",
};
}
return { info: "usage: /preset <fast|smart|max>" };
}
case "branch": {
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} (harvest auto-enabled; streaming disabled)` };
}
default:
return { unknown: true, info: `unknown command: /${cmd} (try /help)` };
}
}
/**
* 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.
*/
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}]`);
}
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");
}
function compactNum(n: number): string {
if (n < 1000) return String(n);
const k = n / 1000;
return k >= 100 ? `${Math.round(k)}k` : `${k.toFixed(1)}k`;
}
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.).
*/
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.
*/
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)";
}
// Slash-command barrel. Public surface is stable across the slash/
// split — App.tsx, tests, and sibling components continue to import
// { handleSlash, parseSlash, suggestSlashCommands, SLASH_COMMANDS, ... }
// from "./slash.js". Everything below is re-exported from the per-topic
// modules under ./slash/.
export {
SLASH_COMMANDS,
detectSlashArgContext,
parseSlash,
suggestSlashCommands,
} from "./slash/commands.js";
export { handleSlash } from "./slash/dispatch.js";
export type { SlashHandler } from "./slash/dispatch.js";
export type {
McpServerSummary,
SlashArgContext,
SlashCommandSpec,
SlashContext,
SlashResult,
} from "./slash/types.js";
+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;
}
+55
View File
@@ -0,0 +1,55 @@
import React, { type ReactNode, createContext, useContext, useEffect, useState } from "react";
/**
* Global heartbeat for every animated component (braille spinners,
* elapsed-seconds counters, cursor blink). A single setInterval feeds
* all of them instead of each component owning one. Consolidating the
* 5-6 independent timers that used to exist in App.tsx + EventLog.tsx +
* PromptInput.tsx into one source dramatically cuts the number of
* React re-renders per second on heavy turns and stops Ink from
* patching the terminal 30+ times/sec — the main amplifier of redraw
* artifacts on winpty/MINTTY-class Windows terminals.
*
* Resolution: `TICK_MS` (default 120). Components that want 500ms or
* 1s cadence just modulo the tick counter.
*/
export const TICK_MS = 120;
const TickContext = createContext(0);
export interface TickerProviderProps {
children: ReactNode;
/**
* When true, the provider skips the setInterval entirely — tick stays at
* 0, all consumers render once and never re-render from the timer. Used
* by PLAIN_UI mode so the cursor and any surviving spinners don't drive
* repaints on fragile Windows terminals.
*/
disabled?: boolean;
}
export function TickerProvider({ children, disabled }: TickerProviderProps) {
const [tick, setTick] = useState(0);
useEffect(() => {
if (disabled) return;
const id = setInterval(() => setTick((t) => t + 1), TICK_MS);
return () => clearInterval(id);
}, [disabled]);
return <TickContext.Provider value={tick}>{children}</TickContext.Provider>;
}
/** Current global tick. Re-renders the calling component every `TICK_MS`. */
export function useTick(): number {
return useContext(TickContext);
}
/**
* Seconds elapsed since the calling component mounted. Derived from
* the shared tick + a fresh Date.now() read, so no dedicated timer
* is needed.
*/
export function useElapsedSeconds(): number {
const [start] = useState(() => Date.now());
useTick(); // subscribe to the tick so we re-render
return Math.floor((Date.now() - start) / 1000);
}
+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 };
}
+63 -1
View File
@@ -64,6 +64,23 @@ export interface UserBalance {
balance_infos: BalanceInfo[];
}
/**
* Response shape for DeepSeek's `/models` endpoint. Mirrors the OpenAI
* models list shape DeepSeek copied — `id` is the model name to pass to
* `/chat/completions`, `owned_by` is the provider string (always
* `"deepseek"` today).
*/
export interface ModelInfo {
id: string;
object: "model";
owned_by: string;
}
export interface ModelList {
object: "list";
data: ModelInfo[];
}
export interface DeepSeekClientOptions {
apiKey?: string;
baseUrl?: string;
@@ -93,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 ?? {};
}
@@ -108,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;
}
@@ -133,6 +172,29 @@ export class DeepSeekClient {
}
}
/**
* Fetch the model catalog DeepSeek currently exposes. Today this is
* `deepseek-chat` (V3) and `deepseek-reasoner` (R1), but querying is
* the only way to learn about new ones without a Reasonix release.
* Returns null on any network/auth failure so callers can degrade
* gracefully — e.g. `/models` falls back to the hardcoded hint.
*/
async listModels(opts: { signal?: AbortSignal } = {}): Promise<ModelList | null> {
try {
const resp = await this._fetch(`${this.baseUrl}/models`, {
method: "GET",
headers: { Authorization: `Bearer ${this.apiKey}` },
signal: opts.signal,
});
if (!resp.ok) return null;
const data = (await resp.json()) as ModelList;
if (!data || !Array.isArray(data.data)) return null;
return data;
} catch {
return null;
}
}
async chat(opts: ChatRequestOptions): Promise<ChatResponse> {
const ctrl = new AbortController();
const timer = setTimeout(() => ctrl.abort(), this.timeoutMs);
+124
View File
@@ -0,0 +1,124 @@
/**
* Render a SEARCH/REPLACE edit block as a compact unified-diff-style
* preview for the code-mode confirm gate. Shows the user what's about
* to land on disk BEFORE they press `y` — catches "wrong file" and
* "wrong replacement" mistakes that the old path + line-count summary
* couldn't.
*
* Not a full Myers diff: we trim shared leading/trailing lines as
* context and render the middle divergence as `-old` / `+new`. That's
* enough for the common SEARCH/REPLACE shape (small change inside a
* function body, wrapped with a few lines of surrounding code for
* uniqueness) and avoids pulling in a diff library.
*/
import type { EditBlock } from "./edit-blocks.js";
export interface DiffPreviewOptions {
/** How many lines of unchanged context to show at each end. Default 2. */
contextLines?: number;
/** Hard cap on total rendered lines. Default 20 — beyond this the preview collapses. */
maxLines?: number;
/** Indent applied to every output line. Default 8 spaces — matches the pending-preview nesting. */
indent?: string;
}
/** Render one edit block's diff. Returns an array of formatted lines. */
export function formatEditBlockDiff(block: EditBlock, opts: DiffPreviewOptions = {}): string[] {
const contextLines = Math.max(0, opts.contextLines ?? 2);
const maxLines = Math.max(4, opts.maxLines ?? 20);
const indent = opts.indent ?? " ";
const search = block.search === "" ? [] : block.search.split("\n");
const replace = block.replace.split("\n");
// New-file case: no search to compare, show the full new content
// (capped). Mark every line `+` so the user knows it's all additions.
if (search.length === 0) {
return renderAllPlus(replace, indent, maxLines);
}
// Common leading / trailing lines — shared context we can collapse.
let leading = 0;
while (
leading < search.length &&
leading < replace.length &&
search[leading] === replace[leading]
) {
leading++;
}
let trailing = 0;
while (
trailing < search.length - leading &&
trailing < replace.length - leading &&
search[search.length - 1 - trailing] === replace[replace.length - 1 - trailing]
) {
trailing++;
}
const searchMiddle = search.slice(leading, search.length - trailing);
const replaceMiddle = replace.slice(leading, replace.length - trailing);
// Trim context to `contextLines` on each side.
const leadShown = search.slice(Math.max(0, leading - contextLines), leading);
const leadHidden = leading - leadShown.length;
const trailShown = search.slice(
search.length - trailing,
search.length - trailing + contextLines,
);
const trailHidden = trailing - trailShown.length;
const out: string[] = [];
if (leadHidden > 0) {
out.push(`${indent} … ${leadHidden} unchanged line${leadHidden === 1 ? "" : "s"} above`);
}
for (const l of leadShown) out.push(`${indent} ${l}`);
for (const l of searchMiddle) out.push(`${indent}- ${l}`);
for (const l of replaceMiddle) out.push(`${indent}+ ${l}`);
for (const l of trailShown) out.push(`${indent} ${l}`);
if (trailHidden > 0) {
out.push(`${indent} … ${trailHidden} unchanged line${trailHidden === 1 ? "" : "s"} below`);
}
return capLines(out, maxLines, indent);
}
/**
* Render the full set of blocks back-to-back, each preceded by a
* path-and-size header so the user can tell which file owns each
* diff chunk. Blocks are separated by a blank line for breathing room.
*/
export function formatAllBlockDiffs(
blocks: readonly EditBlock[],
opts: DiffPreviewOptions = {},
): string[] {
const out: string[] = [];
for (let i = 0; i < blocks.length; i++) {
const b = blocks[i]!;
const removed = b.search === "" ? 0 : countLines(b.search);
const added = countLines(b.replace);
const tag = b.search === "" ? "NEW " : " ";
if (i > 0) out.push("");
out.push(` ${tag}${b.path} (-${removed} +${added} lines)`);
out.push(...formatEditBlockDiff(b, opts));
}
return out;
}
function countLines(s: string): number {
if (s.length === 0) return 0;
return (s.match(/\n/g)?.length ?? 0) + 1;
}
function renderAllPlus(lines: string[], indent: string, maxLines: number): string[] {
const out = lines.map((l) => `${indent}+ ${l}`);
return capLines(out, maxLines, indent);
}
function capLines(lines: string[], maxLines: number, indent: string): string[] {
if (lines.length <= maxLines) return lines;
const head = lines.slice(0, maxLines - 1);
const hidden = lines.length - head.length;
head.push(`${indent}… (${hidden} more diff lines — full content applies on /apply)`);
return head;
}
+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 {
+111
View File
@@ -0,0 +1,111 @@
/**
* Durable checkpoint for the pending-edits queue.
*
* Code mode holds parsed SEARCH/REPLACE blocks in an in-memory
* `useRef<EditBlock[]>` until the user runs `/apply` or `/discard`.
* Pre-0.5.14 that was ephemeral: a crash or accidental Ctrl+C after
* the model proposed seven edits discarded all seven — the session
* log had the assistant text, but the "please review this batch"
* state was gone.
*
* This module checkpoints the queue to
* `~/.reasonix/sessions/<name>.pending.json`
* after every mutation (parse → set / apply → clear / discard →
* clear). On session resume the App reads the file and re-populates
* the queue. If the file doesn't exist the session resumes as before.
*
* Format choices:
* - JSON (not JSONL) — the queue is a single array written at once,
* not a stream of records.
* - Overwrite-on-write — the queue is small (kilobytes) and atomicity
* is "last write wins"; partial-write on crash is fine since we'd
* rather lose the checkpoint than have a torn file block resume.
* - Best-effort I/O — disk full or permission denied must not break
* the session. Silent skip matches the rest of the durable logs
* (session.ts, usage.ts).
*
* Ephemeral sessions (sessionName === null) skip persistence entirely:
* there's no stable name to key the checkpoint to.
*/
import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { sanitizeName, sessionsDir } from "../session.js";
import type { EditBlock } from "./edit-blocks.js";
/** Absolute path for the checkpoint file that belongs to this session. */
export function pendingEditsPath(sessionName: string): string {
return join(sessionsDir(), `${sanitizeName(sessionName)}.pending.json`);
}
/**
* Write the queue to disk, or delete the checkpoint file when `blocks`
* is empty. Callers pass the full current queue every time; we don't
* attempt append-style deltas because the queue is tiny.
*
* No-op when `sessionName` is null (ephemeral session has nowhere to
* write), so call sites can pass the session name directly without a
* null guard.
*/
export function savePendingEdits(sessionName: string | null, blocks: EditBlock[]): void {
if (!sessionName) return;
const path = pendingEditsPath(sessionName);
try {
if (blocks.length === 0) {
if (existsSync(path)) unlinkSync(path);
return;
}
mkdirSync(dirname(path), { recursive: true });
writeFileSync(path, JSON.stringify(blocks, null, 2), "utf8");
} catch {
/* best-effort — disk full / perms should not break the session */
}
}
/**
* Load the queue from disk, returns `null` when there's no checkpoint.
* A malformed file (power-loss torn write, user hand-edit) also returns
* null — silent recovery beats failing to open the session.
*/
export function loadPendingEdits(sessionName: string | null): EditBlock[] | null {
if (!sessionName) return null;
const path = pendingEditsPath(sessionName);
if (!existsSync(path)) return null;
let raw: string;
try {
raw = readFileSync(path, "utf8");
} catch {
return null;
}
try {
const parsed = JSON.parse(raw);
if (!Array.isArray(parsed)) return null;
const out: EditBlock[] = [];
for (const item of parsed) {
if (
item &&
typeof item === "object" &&
typeof item.path === "string" &&
typeof item.search === "string" &&
typeof item.replace === "string" &&
typeof item.offset === "number"
) {
out.push(item as EditBlock);
}
}
return out;
} catch {
return null;
}
}
/** Delete the checkpoint file unconditionally — called by /apply and /discard. */
export function clearPendingEdits(sessionName: string | null): void {
if (!sessionName) return;
const path = pendingEditsPath(sessionName);
try {
if (existsSync(path)) unlinkSync(path);
} catch {
/* best-effort */
}
}
+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);
}
+147 -8
View File
@@ -15,8 +15,86 @@
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
Every factual claim you make about THIS codebase must be backed by evidence. Reasonix VALIDATES the citations you write — broken paths or out-of-range lines render in **red strikethrough with ❌** in front of the user.
**Positive claims** (a file exists, a function does X, a feature IS implemented) — append a markdown link to the source:
- ✅ Correct: \`The MCP client supports listResources [listResources](src/mcp/client.ts:142).\`
- ❌ Wrong: \`The MCP client supports listResources.\` ← no citation, looks authoritative but unverifiable.
**Negative claims** (X is missing, Y is not implemented, lacks Z, doesn't have W) are the **most common 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 are about to write "X is missing" or "Y is not implemented" — **STOP**. Call \`search_content\` for the relevant symbol or term FIRST. Only then:
- If the search returns matches → you were wrong; correct yourself and cite the matches.
- If the search returns nothing → state the absence with the search query as your evidence: \`No callers of \\\`foo()\\\` found (search_content "foo").\`
Asserting absence without a search is the #1 way evaluative answers go wrong. Treat the urge to write "missing" as a red flag in your own reasoning.
# When to propose a plan (submit_plan)
You have a \`submit_plan\` tool that shows the user a markdown plan and lets them Approve / Refine / Cancel before you execute. Use it proactively when the task is large enough to deserve a review gate:
- Multi-file refactors or renames.
- Architecture changes (moving modules, splitting / merging files, new abstractions).
- Anything where "undo" after the fact would be expensive — migrations, destructive cleanups, API shape changes.
- When the user's request is ambiguous and multiple reasonable interpretations exist — propose your reading as a plan and let them confirm.
Skip submit_plan for small, obvious changes: one-line typo, clear bug with a clear fix, adding a missing import, renaming a local variable. Just do those.
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:
- Write tools (edit_file, write_file, create_directory, move_file) and non-allowlisted run_command calls are BOUNCED at dispatch — you'll get a tool result like "unavailable in plan mode". Don't retry them.
- Read tools (read_file, list_directory, search_files, directory_tree, get_file_info) and allowlisted read-only / test shell commands still work — use them to investigate.
- 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
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** \`[🧬 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 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).
When NOT to delegate:
- Direct, narrow questions answerable in 1-2 tool calls — just do them.
- Anything where you need to track intermediate results yourself (planning, multi-step edits).
- Anything that requires user interaction (subagents can't submit plans or ask you for clarification).
Always pass a clear, self-contained \`arguments\` — that text is the **only** context the subagent gets.
# When to edit vs. when to explore
@@ -29,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:
@@ -52,16 +139,66 @@ Rules:
- Do NOT use write_file to change existing files — the user reviews your edits as SEARCH/REPLACE. write_file is only for files you explicitly want to overwrite wholesale (rare).
- Paths are relative to the working directory. Don't use absolute paths.
# Trust what you already know
Before exploring the filesystem to answer a factual question, check whether the answer is already in context: the user's current message, earlier turns in this conversation (including prior tool results from \`remember\`), and the pinned memory blocks at the top of this prompt. When the user has stated a fact or you have remembered one, it outranks what the files say — don't re-derive from code what the user already told you. Explore when you genuinely don't know.
# Exploration
- Avoid listing or reading inside these common dependency / build directories unless the user explicitly asks about them: node_modules, dist, build, out, .next, .nuxt, .svelte-kit, .git, .venv, venv, __pycache__, target, coverage, .turbo, .cache. They're expensive and usually irrelevant.
- Prefer search_files / grep over list_directory when you know roughly what you're looking for — it saves context and avoids enumerating huge trees.
- Skip dependency, build, and VCS directories unless the user explicitly asks. The pinned .gitignore block (if any, below) is your authoritative denylist.
- Prefer \`search_files\` over \`list_directory\` when you know roughly what you're looking for — it saves context and avoids enumerating huge trees. Note: \`search_files\` matches file NAMES; for searching file CONTENTS use \`search_content\`.
- Available exploration tools: \`read_file\`, \`list_directory\`, \`directory_tree\`, \`search_files\` (filename match), \`search_content\` (content grep — use for "where is X called", "find all references to Y"), \`get_file_info\`. Don't call \`grep\` or other tools that aren't in this list — they don't exist as functions.
# Path conventions
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 / grep / read), do it with tool calls before writing any prose — silence while exploring is fine.
- 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}
`;
/**
@@ -70,23 +207,25 @@ Rules:
* the file — we hand it to the model as-is. Truncate long ones so we
* don't eat context budget on huge generated ignore lists.
*
* Missing or unreadable .gitignore → returns the base prompt unchanged.
* Stacking order (stable for cache prefix):
* base prompt → REASONIX.md → global MEMORY.md → project MEMORY.md → .gitignore
*/
export function codeSystemPrompt(rootDir: string): string {
const withMemory = applyMemoryStack(CODE_SYSTEM_PROMPT, rootDir);
const gitignorePath = join(rootDir, ".gitignore");
if (!existsSync(gitignorePath)) return CODE_SYSTEM_PROMPT;
if (!existsSync(gitignorePath)) return withMemory;
let content: string;
try {
content = readFileSync(gitignorePath, "utf8");
} catch {
return CODE_SYSTEM_PROMPT;
return withMemory;
}
const MAX = 2000;
const truncated =
content.length > MAX
? `${content.slice(0, MAX)}\n… (truncated ${content.length - MAX} chars)`
: content;
return `${CODE_SYSTEM_PROMPT}
return `${withMemory}
# Project .gitignore
+146
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
@@ -44,6 +77,23 @@ export interface ReasonixConfig {
session?: string | null;
/** Marks that `reasonix setup` has completed at least once. */
setupCompleted?: boolean;
/**
* Whether `web_search` + `web_fetch` tools are registered. Default:
* enabled (no key required — backed by DuckDuckGo's public HTML
* endpoint). Set to `false` to keep the session offline.
*/
search?: boolean;
/**
* Per-project state keyed by absolute directory path. Written by the
* "always allow" choice on a shell confirmation prompt; merged into
* `registerShellTools({ extraAllowed })` when `reasonix code` runs
* against that directory again.
*/
projects?: {
[absoluteRootDir: string]: {
shellAllowed?: string[];
};
};
}
export function defaultConfigPath(): string {
@@ -78,12 +128,108 @@ export function loadApiKey(path: string = defaultConfigPath()): string | undefin
return readConfig(path).apiKey;
}
/**
* Resolve whether web-search tools should be registered. Default: on.
* Env `REASONIX_SEARCH=off` or config `search: false` turns it off.
* Any other value falls through to enabled.
*/
export function searchEnabled(path: string = defaultConfigPath()): boolean {
const env = process.env.REASONIX_SEARCH;
if (env === "off" || env === "false" || env === "0") return false;
const cfg = readConfig(path).search;
if (cfg === false) return false;
return true;
}
export function saveApiKey(key: string, path: string = defaultConfigPath()): void {
const cfg = readConfig(path);
cfg.apiKey = key.trim();
writeConfig(cfg, path);
}
/**
* Read the persisted "always allow" shell-command prefixes for a
* given project root. Returns an empty array when nothing's stored.
*/
export function loadProjectShellAllowed(
rootDir: string,
path: string = defaultConfigPath(),
): string[] {
const cfg = readConfig(path);
return cfg.projects?.[rootDir]?.shellAllowed ?? [];
}
/**
* Append a prefix to the project's shell-allowed list, dedup and
* persist. No-op if the prefix is empty/whitespace or already stored.
*/
export function addProjectShellAllowed(
rootDir: string,
prefix: string,
path: string = defaultConfigPath(),
): void {
const trimmed = prefix.trim();
if (!trimmed) return;
const cfg = readConfig(path);
if (!cfg.projects) cfg.projects = {};
if (!cfg.projects[rootDir]) cfg.projects[rootDir] = {};
const existing = cfg.projects[rootDir].shellAllowed ?? [];
if (existing.includes(trimmed)) return;
cfg.projects[rootDir].shellAllowed = [...existing, trimmed];
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);
+404
View File
@@ -0,0 +1,404 @@
/**
* Hooks — user-defined automation that fires at well-known points in
* the agent loop. Mirrors the two-scope layout we use for memory and
* skills:
*
* - `<project>/.reasonix/settings.json` — committable per-project
* - `~/.reasonix/settings.json` — every session
*
* A hook is a shell command. We invoke it with stdin = a JSON
* payload describing the event, and interpret the exit code:
*
* - `0` — pass; loop continues normally
* - `2` — block; for `PreToolUse` / `UserPromptSubmit` the
* loop refuses to continue with that step and surfaces the
* hook's stderr as the reason. For `PostToolUse` / `Stop` block
* is meaningless (the action already happened) — treat as warn.
* - anything else — warn; loop continues but stderr is rendered
* to the user as an inline notice.
*
* stdin JSON shape (one envelope per event):
*
* {
* "event": "PreToolUse" | "PostToolUse" | "UserPromptSubmit" | "Stop",
* "cwd": "<absolute project root or process.cwd()>",
* "toolName": "<string>", // tool events only
* "toolArgs": <unknown>, // tool events only — already JSON-decoded
* "toolResult": "<string>", // PostToolUse only — same body the model sees
* "prompt": "<string>", // UserPromptSubmit only
* "lastAssistantText": "<string>", // Stop only
* "turn": <number>, // Stop only
* }
*
* Hooks are executed in order: project scope first, then global.
* `Pre*` events stop dispatching at the first block; non-block
* outcomes accumulate into a single report so the UI can render
* each warning inline.
*/
import { spawn } from "node:child_process";
import { existsSync, readFileSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
export type HookEvent = "PreToolUse" | "PostToolUse" | "UserPromptSubmit" | "Stop";
/** All four events as a const array — drives slash listing + validation. */
export const HOOK_EVENTS: readonly HookEvent[] = [
"PreToolUse",
"PostToolUse",
"UserPromptSubmit",
"Stop",
] as const;
/** Only the gating events can block the loop. */
const BLOCKING_EVENTS: ReadonlySet<HookEvent> = new Set(["PreToolUse", "UserPromptSubmit"]);
/** Per-event default timeout. Tool/prompt hooks gate progress, so they're tight. */
const DEFAULT_TIMEOUTS_MS: Record<HookEvent, number> = {
PreToolUse: 5_000,
UserPromptSubmit: 5_000,
PostToolUse: 30_000,
Stop: 30_000,
};
export type HookScope = "project" | "global";
export interface HookConfig {
/**
* Tool-name pattern (PreToolUse / PostToolUse only). Anchored regex.
* Omitted or `"*"` matches every tool. Ignored for prompt / Stop
* events (they have no tool name to match against).
*/
match?: string;
/** Shell command to run. Spawned through the platform shell. */
command: string;
/** Optional human description — surfaced in `/hooks`. */
description?: string;
/** Per-hook timeout override in ms. */
timeout?: number;
/**
* Working directory for the spawned process. Defaults to:
* - project scope → the project root
* - global scope → process.cwd()
*/
cwd?: string;
}
/** Shape of `<scope>/.reasonix/settings.json` — only `hooks` for now. */
export interface HookSettings {
hooks?: Partial<Record<HookEvent, HookConfig[]>>;
}
/** A loaded hook with its origin scope baked in (used for ordering and `/hooks`). */
export interface ResolvedHook extends HookConfig {
event: HookEvent;
scope: HookScope;
/** Absolute path to the settings.json the hook came from. */
source: string;
}
/** Outcome of a single hook invocation. */
export interface HookOutcome {
/** Which hook fired. */
hook: ResolvedHook;
/**
* Decision:
* - `pass` — exit 0
* - `block` — exit 2 on a blocking event (otherwise downgraded to `warn`)
* - `warn` — non-zero exit that is not a successful block
* - `timeout` — the spawn was killed past `timeout`
* - `error` — could not spawn at all (missing command, etc.)
*/
decision: "pass" | "block" | "warn" | "timeout" | "error";
exitCode: number | null;
/** Captured stdout (trimmed). May be empty. */
stdout: string;
/** Captured stderr (trimmed). The block / warn message comes from here. */
stderr: string;
durationMs: number;
}
/** Aggregate report for `runHooks`. */
export interface HookReport {
event: HookEvent;
outcomes: HookOutcome[];
/** True iff at least one outcome was a `block` — only meaningful for blocking events. */
blocked: boolean;
}
export const HOOK_SETTINGS_FILENAME = "settings.json";
export const HOOK_SETTINGS_DIRNAME = ".reasonix";
/** Where the global settings.json lives. Equivalent to `~/.reasonix/settings.json`. */
export function globalSettingsPath(homeDirOverride?: string): string {
return join(homeDirOverride ?? homedir(), HOOK_SETTINGS_DIRNAME, HOOK_SETTINGS_FILENAME);
}
/** Where the project settings.json lives for a given root. */
export function projectSettingsPath(projectRoot: string): string {
return join(projectRoot, HOOK_SETTINGS_DIRNAME, HOOK_SETTINGS_FILENAME);
}
function readSettingsFile(path: string): HookSettings | null {
if (!existsSync(path)) return null;
try {
const raw = readFileSync(path, "utf8");
const parsed = JSON.parse(raw);
if (parsed && typeof parsed === "object") return parsed as HookSettings;
} catch {
/* malformed JSON → treat as no hooks; do NOT throw, the user
* shouldn't lose the whole CLI to a typo in their settings */
}
return null;
}
/**
* Pull every configured hook out of the project + global settings
* files, in the order they should fire (project first, global second,
* within each scope: array order from the file).
*
* Returns a flat list — the dispatcher filters by event + match
* pattern at run time. Loading is cheap (one or two JSON files), so
* we don't memoize across processes; re-load is allowed via
* `/hooks reload` and on every fresh App mount.
*/
export interface LoadHookSettingsOptions {
/** Absolute project root, if any. Without it, only global hooks load. */
projectRoot?: string;
/** Override `~` for tests. */
homeDir?: string;
}
export function loadHooks(opts: LoadHookSettingsOptions = {}): ResolvedHook[] {
const out: ResolvedHook[] = [];
if (opts.projectRoot) {
const projPath = projectSettingsPath(opts.projectRoot);
const settings = readSettingsFile(projPath);
if (settings) appendResolved(out, settings, "project", projPath);
}
const globalPath = globalSettingsPath(opts.homeDir);
const settings = readSettingsFile(globalPath);
if (settings) appendResolved(out, settings, "global", globalPath);
return out;
}
function appendResolved(
out: ResolvedHook[],
settings: HookSettings,
scope: HookScope,
source: string,
): void {
if (!settings.hooks) return;
for (const event of HOOK_EVENTS) {
const list = settings.hooks[event];
if (!Array.isArray(list)) continue;
for (const cfg of list) {
if (!cfg || typeof cfg.command !== "string" || cfg.command.trim() === "") continue;
out.push({ ...cfg, event, scope, source });
}
}
}
/**
* True if `toolName` matches the hook's `match` field. `"*"` and
* undefined match everything. Otherwise we anchor the field as a
* regex — partial-name matches don't fire, so `"file"` would not
* trigger on `read_file` (use `".*file"` for that).
*/
export function matchesTool(hook: ResolvedHook, toolName: string): boolean {
if (hook.event !== "PreToolUse" && hook.event !== "PostToolUse") return true;
const m = hook.match;
if (!m || m === "*") return true;
try {
const re = new RegExp(`^(?:${m})$`);
return re.test(toolName);
} catch {
/* malformed regex → don't fire (safer than firing on every tool) */
return false;
}
}
/** Payload envelope passed to hook stdin. */
export interface HookPayload {
event: HookEvent;
cwd: string;
toolName?: string;
toolArgs?: unknown;
toolResult?: string;
prompt?: string;
lastAssistantText?: string;
turn?: number;
}
/** Test seam — same shape as Node's spawn but returns a Promise of the raw outcome bits. */
export interface HookSpawnInput {
command: string;
cwd: string;
stdin: string;
timeoutMs: number;
}
export interface HookSpawnResult {
exitCode: number | null;
stdout: string;
stderr: string;
timedOut: boolean;
/** True iff spawn() itself failed (ENOENT, EACCES, …). */
spawnError?: Error;
}
export type HookSpawner = (input: HookSpawnInput) => Promise<HookSpawnResult>;
/**
* Default spawner — runs `command` through the platform shell so
* `&&`, pipes, env-var expansion all work without a tokenizer.
* Stdin is the JSON payload, stdout / stderr are buffered.
*
* Why `shell: true`? A hook is intentionally a shell command — that's
* the contract. Treating it like an argv array would surprise users
* who write `bun run check && eslint .` and expect it to behave the
* way it does in their terminal.
*/
function defaultSpawner(input: HookSpawnInput): Promise<HookSpawnResult> {
return new Promise<HookSpawnResult>((resolve) => {
const child = spawn(input.command, {
cwd: input.cwd,
shell: true,
stdio: ["pipe", "pipe", "pipe"],
});
let stdout = "";
let stderr = "";
let timedOut = false;
const timer = setTimeout(() => {
timedOut = true;
child.kill("SIGTERM");
// SIGTERM may not land on Windows for shell children — followed
// by a hard kill a moment later if the process is still around.
setTimeout(() => {
try {
child.kill("SIGKILL");
} catch {
/* already gone */
}
}, 500);
}, input.timeoutMs);
child.stdout.on("data", (chunk: Buffer) => {
stdout += chunk.toString("utf8");
});
child.stderr.on("data", (chunk: Buffer) => {
stderr += chunk.toString("utf8");
});
child.once("error", (err) => {
clearTimeout(timer);
resolve({
exitCode: null,
stdout,
stderr,
timedOut: false,
spawnError: err,
});
});
child.once("close", (code) => {
clearTimeout(timer);
resolve({
exitCode: code,
stdout: stdout.trim(),
stderr: stderr.trim(),
timedOut,
});
});
try {
child.stdin.write(input.stdin);
child.stdin.end();
} catch {
/* stdin write can race with spawn errors; the close handler
* still fires with exit 0/null */
}
});
}
/**
* Format a hook outcome as a single-line UI string. Used by both the
* loop (for `warning` events) and the App (for UserPromptSubmit /
* Stop outcomes). Centralizing keeps the language consistent across
* scopes.
*/
export function formatHookOutcomeMessage(outcome: HookOutcome): string {
if (outcome.decision === "pass") return "";
const detail = (outcome.stderr || outcome.stdout || "").trim();
const tag = `${outcome.hook.scope}/${outcome.hook.event}`;
const cmd =
outcome.hook.command.length > 60
? `${outcome.hook.command.slice(0, 60)}…`
: outcome.hook.command;
const head = `hook ${tag} \`${cmd}\` ${outcome.decision}`;
return detail ? `${head}: ${detail}` : head;
}
/**
* Decide the hook's outcome decision from raw spawn results.
* Pulled out as a pure function so tests can pin the matrix.
*/
export function decideOutcome(
event: HookEvent,
raw: HookSpawnResult,
): "pass" | "block" | "warn" | "timeout" | "error" {
if (raw.spawnError) return "error";
if (raw.timedOut) return BLOCKING_EVENTS.has(event) ? "block" : "warn";
if (raw.exitCode === 0) return "pass";
if (raw.exitCode === 2 && BLOCKING_EVENTS.has(event)) return "block";
return "warn";
}
export interface RunHooksOptions {
payload: HookPayload;
hooks: ResolvedHook[];
/** Test seam — defaults to a real `spawn`. */
spawner?: HookSpawner;
}
/**
* Filter hooks down to the ones that match `payload.event` (and
* `payload.toolName`, for tool events), then run them in order.
* Stops at the first `block` outcome on a blocking event so a
* gating hook can prevent later hooks from incorrectly seeing a
* success that wasn't going to happen.
*/
export async function runHooks(opts: RunHooksOptions): Promise<HookReport> {
const spawner = opts.spawner ?? defaultSpawner;
const event = opts.payload.event;
const toolName = opts.payload.toolName ?? "";
const matching = opts.hooks.filter((h) => h.event === event && matchesTool(h, toolName));
const outcomes: HookOutcome[] = [];
let blocked = false;
const stdin = `${JSON.stringify(opts.payload)}\n`;
for (const hook of matching) {
const start = Date.now();
const timeoutMs = hook.timeout ?? DEFAULT_TIMEOUTS_MS[event];
const cwd = hook.cwd ?? opts.payload.cwd;
const raw = await spawner({ command: hook.command, cwd, stdin, timeoutMs });
const decision = decideOutcome(event, raw);
outcomes.push({
hook,
decision,
exitCode: raw.exitCode,
stdout: raw.stdout,
stderr:
raw.stderr ||
(raw.spawnError ? raw.spawnError.message : "") ||
(raw.timedOut ? `hook timed out after ${timeoutMs}ms` : ""),
durationMs: Date.now() - start,
});
if (decision === "block") {
blocked = true;
break;
}
}
return { event, outcomes, blocked };
}
+150 -1
View File
@@ -6,9 +6,30 @@ export type { ChatResponse, StreamChunk, DeepSeekClientOptions } from "./client.
export {
CacheFirstLoop,
formatLoopError,
fixToolCallPairing,
healLoadedMessages,
healLoadedMessagesByTokens,
stripHallucinatedToolMarkup,
} from "./loop.js";
export {
AT_MENTION_PATTERN,
AT_PICKER_PREFIX,
DEFAULT_AT_MENTION_MAX_BYTES,
DEFAULT_PICKER_IGNORE_DIRS,
detectAtPicker,
expandAtMentions,
listFilesSync,
listFilesWithStatsSync,
rankPickerCandidates,
} from "./at-mentions.js";
export type {
AtMentionExpansion,
AtMentionOptions,
FileWithStats,
ListFilesOptions,
PickerCandidate,
RankPickerOptions,
} from "./at-mentions.js";
export type {
CacheFirstLoopOptions,
LoopEvent,
@@ -29,10 +50,84 @@ export type {
export { ImmutablePrefix, AppendOnlyLog, VolatileScratch } from "./memory.js";
export type { ImmutablePrefixOptions } from "./memory.js";
export {
PROJECT_MEMORY_FILE,
PROJECT_MEMORY_MAX_CHARS,
applyProjectMemory,
memoryEnabled,
readProjectMemory,
} from "./project-memory.js";
export type { ProjectMemory } from "./project-memory.js";
export {
MEMORY_INDEX_FILE,
MEMORY_INDEX_MAX_CHARS,
MemoryStore,
USER_MEMORY_DIR,
applyMemoryStack,
applyUserMemory,
projectHash,
sanitizeMemoryName,
} from "./user-memory.js";
export type {
MemoryEntry,
MemoryScope,
MemoryStoreOptions,
MemoryType,
WriteInput as MemoryWriteInput,
} from "./user-memory.js";
export { ToolRegistry } from "./tools.js";
export type { ToolDefinition, ToolCallContext } from "./tools.js";
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 { 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,
SubagentSink,
SubagentToolOptions,
} from "./tools/subagent.js";
export {
NeedsConfirmationError,
detectShellOperator,
formatCommandResult,
injectPowerShellUtf8,
isAllowed,
prepareSpawn,
quoteForCmdExe,
registerShellTools,
resolveExecutable,
runCommand,
tokenizeCommand,
withUtf8Codepage,
} from "./tools/shell.js";
export type { RunCommandResult, ShellToolsOptions } from "./tools/shell.js";
export {
formatSearchResults,
htmlToText,
parseMojeekResults,
registerWebTools,
webFetch,
webSearch,
} from "./tools/web.js";
export type {
PageContent,
SearchResult,
WebFetchOptions,
WebSearchOptions,
WebToolsOptions,
} from "./tools/web.js";
export {
SessionStats,
@@ -107,9 +202,11 @@ export { SseTransport } from "./mcp/sse.js";
export type { SseTransportOptions } from "./mcp/sse.js";
export {
DEFAULT_MAX_RESULT_CHARS,
DEFAULT_MAX_RESULT_TOKENS,
bridgeMcpTools,
flattenMcpResult,
truncateForModel,
truncateForModelByTokens,
} from "./mcp/registry.js";
export type { BridgeOptions, BridgeResult, FlattenOptions } from "./mcp/registry.js";
export { parseMcpSpec } from "./mcp/spec.js";
@@ -186,4 +283,56 @@ export type {
JSONSchema,
} from "./types.js";
export const VERSION = "0.4.3";
export {
LATEST_CACHE_TTL_MS,
LATEST_FETCH_TIMEOUT_MS,
VERSION,
compareVersions,
getLatestVersion,
isNpxInstall,
} from "./version.js";
export type { GetLatestVersionOptions } from "./version.js";
export {
HOOK_EVENTS,
HOOK_SETTINGS_DIRNAME,
HOOK_SETTINGS_FILENAME,
decideOutcome,
formatHookOutcomeMessage,
globalSettingsPath,
loadHooks,
matchesTool,
projectSettingsPath,
runHooks,
} from "./hooks.js";
export {
aggregateUsage,
appendUsage,
bucketCacheHitRatio,
bucketSavingsFraction,
defaultUsageLogPath,
formatLogSize,
readUsageLog,
} from "./usage.js";
export type {
AggregateOptions,
AppendUsageInput,
UsageAggregate,
UsageBucket,
UsageRecord,
} from "./usage.js";
export type {
HookConfig,
HookEvent,
HookOutcome,
HookPayload,
HookReport,
HookScope,
HookSettings,
HookSpawner,
HookSpawnInput,
HookSpawnResult,
LoadHookSettingsOptions,
ResolvedHook,
RunHooksOptions,
} from "./hooks.js";
+1380 -60
View File
File diff suppressed because it is too large. Load diff
+101
View File
@@ -7,6 +7,7 @@
* MCP ecosystem tool, wrapped in Reasonix's Pillar 1 + Pillar 3 benefits.
*/
import { countTokens } from "../tokenizer.js";
import { ToolRegistry } from "../tools.js";
import type { JSONSchema } from "../types.js";
import type { McpClient } from "./client.js";
@@ -58,6 +59,18 @@ export interface BridgeOptions {
*/
export const DEFAULT_MAX_RESULT_CHARS = 32_000;
/**
* Token-aware cap for tool results, in DeepSeek V3 tokens.
*
* 8,000 tokens ≈ 6% of DeepSeek V3's 131K context. One oversized tool
* result can't eat more than that no matter what character density the
* content has. The char cap (32K chars) only bounds tokens for English
* — CJK text at 1 char/token blows past 16K tokens under the same
* ceiling. With the tokenizer shipped in 0.5.0 we can cap the thing
* that actually matters.
*/
export const DEFAULT_MAX_RESULT_TOKENS = 8_000;
export interface BridgeResult {
registry: ToolRegistry;
/** Names actually registered (may differ from MCP names when a prefix is applied). */
@@ -159,6 +172,94 @@ export function truncateForModel(s: string, maxChars: number): string {
return `${head}\n\n[…truncated ${dropped} chars — raise BridgeOptions.maxResultChars, or call the tool with a narrower scope (filter, head, pagination)…]\n\n${tail}`;
}
/**
* Token-aware truncation. Same head+tail policy as `truncateForModel`,
* but sizes the slices against a DeepSeek V3 token budget instead of a
* raw character count — so CJK text (which previously survived at 2×
* the token cost per char) gets capped at the same effective context
* footprint as English.
*
* Strategy: fast path when `s.length <= maxTokens` (every token is ≥1
* char, so this bounds tokens ≤ maxTokens — skip tokenize entirely).
* Short-ish strings are confirmed against the real token count.
* Long strings go straight to char-sliced head+tail with one or two
* tokenize-verify-and-shrink rounds per slice — we deliberately never
* tokenize the full input, because pathological repetitive text
* (megabytes of `AAAA…`) can cost 30s+ on the pure-TS BPE port.
*/
export function truncateForModelByTokens(s: string, maxTokens: number): string {
if (maxTokens <= 0) return "";
// Every token is ≥1 char — if length ≤ budget, tokens ≤ budget.
if (s.length <= maxTokens) return s;
// Small enough to tokenize-check without pathological cost: confirm
// whether we're actually over budget. (Threshold is the char-bound
// worst case for English/code — ~4 chars/token.)
if (s.length <= maxTokens * 4) {
const tokens = countTokens(s);
if (tokens <= maxTokens) return s;
}
const markerOverhead = 48; // rough token cost of the truncation marker
const contentBudget = Math.max(0, maxTokens - markerOverhead);
const tailBudget = Math.min(256, Math.floor(contentBudget * 0.1));
const headBudget = Math.max(0, contentBudget - tailBudget);
const head = sizePrefixToTokens(s, headBudget);
const tail = sizeSuffixToTokens(s, tailBudget);
const droppedChars = s.length - head.length - tail.length;
// Estimate dropped tokens from the per-slice char/token ratio we
// already measured, rather than paying another full-string tokenize.
// The marker says "~N tokens" so the ≤10% slop is visible to readers.
const headTokens = head ? countTokens(head) : 0;
const tailTokens = tail ? countTokens(tail) : 0;
const sampleChars = head.length + tail.length;
const sampleTokens = headTokens + tailTokens;
const ratio = sampleChars > 0 ? sampleTokens / sampleChars : 0.3;
const estTotalTokens = Math.ceil(s.length * ratio);
const droppedTokens = Math.max(0, estTotalTokens - sampleTokens);
return `${head}\n\n[…truncated ~${droppedTokens} tokens (${droppedChars} chars) — raise BridgeOptions.maxResultTokens, or call the tool with a narrower scope (filter, head, pagination)…]\n\n${tail}`;
}
/**
* Slice `s` from the start to the largest prefix that fits `budget`
* tokens. Never tokenizes the full input: starts with a char-bound
* estimate, then verifies and shrinks. Converges in 1–2 iterations.
*/
function sizePrefixToTokens(s: string, budget: number): string {
if (budget <= 0 || s.length === 0) return "";
// Optimistic starting size: assume ~4 chars/token (English/code
// average). If the content is denser (CJK ~1 char/token), the first
// tokenize will show we're over and we shrink.
let size = Math.min(s.length, budget * 4);
for (let iter = 0; iter < 6; iter++) {
if (size <= 0) return "";
const slice = s.slice(0, size);
const count = countTokens(slice);
if (count <= budget) return slice;
// Shrink by the overshoot fraction plus a small safety margin.
const next = Math.floor(size * (budget / count) * 0.95);
if (next >= size) return s.slice(0, Math.max(0, size - 1));
size = next;
}
return s.slice(0, Math.max(0, size));
}
/** Slice `s` from the end to the largest suffix that fits `budget` tokens. */
function sizeSuffixToTokens(s: string, budget: number): string {
if (budget <= 0 || s.length === 0) return "";
let size = Math.min(s.length, budget * 4);
for (let iter = 0; iter < 6; iter++) {
if (size <= 0) return "";
const slice = s.slice(-size);
const count = countTokens(slice);
if (count <= budget) return slice;
const next = Math.floor(size * (budget / count) * 0.95);
if (next >= size) return s.slice(-Math.max(0, size - 1));
size = next;
}
return s.slice(-Math.max(0, size));
}
function blockToString(block: McpContentBlock): string {
if (block.type === "text") return block.text;
if (block.type === "image") return `[image ${block.mimeType}, ${block.data.length} chars base64]`;
+99
View File
@@ -0,0 +1,99 @@
/**
* Project memory — a user-authored `REASONIX.md` in the project root
* that gets pinned into the immutable-prefix system prompt.
*
* Design notes:
*
* - The file lands in `ImmutablePrefix.system`, so the whole memory
* block is hashed into the cache prefix fingerprint. Editing the
* file invalidates the prefix; unchanged memory across sessions
* keeps the DeepSeek prefix cache warm. That matches Pillar 1 —
* memory is a deliberate, stable prefix, not per-turn drift.
* - Only one source: the working-root `REASONIX.md`. No parent walk,
* no `~/.reasonix/REASONIX.md`, no CLAUDE.md fallback. User-global
* memory can come later; for v1 one file == one mental model.
* - Truncated at 8 000 chars (≈ 2k tokens). `.gitignore` gets 2 000
* because it's a constraint dump; memory gets more headroom because
* it's deliberate instructions.
* - Opt-out via `REASONIX_MEMORY=off|false|0`. No CLI flag — memory
* is a file, `rm REASONIX.md` is the other opt-out.
*/
import { existsSync, readFileSync } from "node:fs";
import { join } from "node:path";
export const PROJECT_MEMORY_FILE = "REASONIX.md";
export const PROJECT_MEMORY_MAX_CHARS = 8000;
export interface ProjectMemory {
/** Absolute path the memory was read from. */
path: string;
/** Post-truncation content (may include a "… (truncated N chars)" marker). */
content: string;
/** Original byte length before truncation. */
originalChars: number;
/** True iff `originalChars > PROJECT_MEMORY_MAX_CHARS`. */
truncated: boolean;
}
/**
* Read `REASONIX.md` from `rootDir`. Returns `null` when the file is
* missing, unreadable, or empty (whitespace-only counts as empty — an
* empty memory file shouldn't perturb the cache prefix).
*/
export function readProjectMemory(rootDir: string): ProjectMemory | null {
const path = join(rootDir, PROJECT_MEMORY_FILE);
if (!existsSync(path)) return null;
let raw: string;
try {
raw = readFileSync(path, "utf8");
} catch {
return null;
}
const trimmed = raw.trim();
if (!trimmed) return null;
const originalChars = trimmed.length;
const truncated = originalChars > PROJECT_MEMORY_MAX_CHARS;
const content = truncated
? `${trimmed.slice(0, PROJECT_MEMORY_MAX_CHARS)}\n… (truncated ${
originalChars - PROJECT_MEMORY_MAX_CHARS
} chars)`
: trimmed;
return { path, content, originalChars, truncated };
}
/**
* Resolve whether project memory should be read. Default: on.
* `REASONIX_MEMORY=off|false|0` turns it off (CI, reproducing issues,
* intentional offline runs).
*/
export function memoryEnabled(): boolean {
const env = process.env.REASONIX_MEMORY;
if (env === "off" || env === "false" || env === "0") return false;
return true;
}
/**
* Return `basePrompt` with the project's `REASONIX.md` appended as a
* "Project memory" section. No-op when the file is absent, empty, or
* memory is disabled via env.
*
* The appended block is deterministic — identical input ⇒ identical
* output — so every session that opens against the same memory file
* gets the same prefix hash.
*/
export function applyProjectMemory(basePrompt: string, rootDir: string): string {
if (!memoryEnabled()) return basePrompt;
const mem = readProjectMemory(rootDir);
if (!mem) return basePrompt;
return `${basePrompt}
# Project memory (REASONIX.md)
The user pinned these notes about this project — treat them as authoritative context for every turn:
\`\`\`
${mem.content}
\`\`\`
`;
}
+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.`;
+11
View File
@@ -46,6 +46,17 @@ export class ToolCallRepair {
this.storm = new StormBreaker(opts.stormWindow ?? 6, opts.stormThreshold ?? 3);
}
/**
* Drop the StormBreaker's sliding window of recent (name, args)
* signatures. Called at the start of every user turn — a fresh user
* message is a new intent, so carrying old repetition state into it
* would turn a valid "try again with different input" flow into a
* false-positive block.
*/
resetStorm(): void {
this.storm.reset();
}
process(
declaredCalls: ToolCall[],
reasoningContent: string | null,
+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),
};
}
+9
View File
@@ -107,6 +107,15 @@ export function deleteSession(name: string): boolean {
const path = sessionPath(name);
try {
unlinkSync(path);
// Best-effort cleanup of side-car files that belong to this session
// so `/forget` doesn't leave orphans in `sessionsDir()`. Currently
// just the pending-edits checkpoint (src/code/pending-edits.ts).
const sidecar = path.replace(/\.jsonl$/, ".pending.json");
try {
unlinkSync(sidecar);
} catch {
/* no sidecar present — expected for sessions without pending edits */
}
return true;
} catch {
return false;
+399
View File
@@ -0,0 +1,399 @@
/**
* Skills — user-defined prompt packs pinned (by name) into the
* immutable prefix and loaded (by body) on demand.
*
* Two scopes mirror the user-memory layout:
* - `project` → `<projectRoot>/.reasonix/skills/` (this repo only)
* - `global` → `~/.reasonix/skills/` (every session)
*
* Project scope wins on a name collision. Deliberately NOT tied to
* any specific client's directory convention (`.claude/`, `.glm/`,
* etc.) — Reasonix is model-agnostic at the conversation layer, so
* coupling the skill filesystem to one vendor would break any user
* running a different backend.
*
* Accepted file layouts (both emit the same `Skill`):
* - `{dir}/<name>/SKILL.md` (preferred — lets a skill bundle
* additional assets alongside)
* - `{dir}/<name>.md` (flat, one-file shorthand)
*
* Frontmatter keys we read:
* - `name` — optional, defaults to the file / dir name
* - `description` — one-line index description (REQUIRED for listing)
* - `allowed-tools` — parsed but UNUSED in v1 (see tools/skills.ts)
*
* Cache-First contract (Pillar 1):
* - The PREFIX sees only names + descriptions (one line each).
* - Bodies enter the APPEND-ONLY LOG lazily, via `run_skill` or
* `/skill <name>` — never the prefix. That keeps the prefix hash
* stable across skill additions to the body store.
*/
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";
/** Cap on the pinned skills-index block, mirrors memory-index cap. */
export const SKILLS_INDEX_MAX_CHARS = 4000;
/** Skill identifier shape — alnum + `_` + `-` + interior `.`, 1-64 chars. */
const VALID_SKILL_NAME = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/;
export type SkillScope = "project" | "global" | "builtin";
/**
* Execution mode for a skill. `inline` (default) returns the body as a
* tool result so the body enters the parent's append-only log — the
* model continues the loop using the loaded instructions. `subagent`
* spawns an isolated child loop with the body as the system prompt and
* the user-supplied `arguments` as the task; only the child's final
* answer comes back. Use `subagent` for big-context exploration / research
* playbooks where the parent doesn't need to see the trail.
*/
export type SkillRunAs = "inline" | "subagent";
export interface Skill {
/** Canonical name — sanitized, matches the directory / filename stem. */
name: string;
/** One-line description shown in the pinned index. */
description: string;
/** Full markdown body (post-frontmatter). Loaded on demand. */
body: string;
/** Which scope this skill was loaded from. */
scope: SkillScope;
/** Absolute path to the SKILL.md (or {name}.md) file, or "(builtin)" for shipped defaults. */
path: string;
/** Raw `allowed-tools` field from frontmatter, if any. Unused in v1. */
allowedTools?: string;
/**
* Execution mode (frontmatter `runAs`). Defaults to `inline` for
* backwards compatibility with skills written before this field
* existed.
*/
runAs: SkillRunAs;
/**
* Frontmatter `model` — when set, overrides the default model the
* subagent runs on. Only meaningful when `runAs === "subagent"`.
* Accept any DeepSeek model id; the subagent layer falls back to its
* own default if this is missing or invalid.
*/
model?: string;
}
export interface SkillStoreOptions {
/** Override `$HOME` — tests point this at a tmpdir. */
homeDir?: string;
/**
* Absolute project root. Required to surface project-scope skills;
* omit (e.g. in `reasonix chat` without `code`) and the store only
* reads the global scope.
*/
projectRoot?: string;
/**
* Suppress the bundled built-in skills (`explore`, `research`).
* Used by unit tests that want to assert exact list contents
* without the +2 builtins distorting counts. Production callers
* leave this off so users always get the bundled defaults.
*/
disableBuiltins?: boolean;
}
/**
* Parse a `---` frontmatter block. Same minimal shape as user-memory:
* `key: value` lines, no quoting, no nesting. Returns `{}` data and the
* full input as body when no frontmatter fence is present — so hand-
* written files without frontmatter still surface (with empty desc).
*/
function parseFrontmatter(raw: string): { data: Record<string, string>; body: string } {
const lines = raw.split(/\r?\n/);
if (lines[0] !== "---") return { data: {}, body: raw };
const end = lines.indexOf("---", 1);
if (end < 0) return { data: {}, body: raw };
const data: Record<string, string> = {};
for (let i = 1; i < end; i++) {
const line = lines[i];
if (!line) continue;
const m = line.match(/^([a-zA-Z_][a-zA-Z0-9_-]*):\s*(.*)$/);
if (m?.[1]) data[m[1]] = (m[2] ?? "").trim();
}
return {
data,
body: lines
.slice(end + 1)
.join("\n")
.replace(/^\n+/, ""),
};
}
function isValidSkillName(name: string): boolean {
return VALID_SKILL_NAME.test(name);
}
export class SkillStore {
private readonly homeDir: string;
private readonly projectRoot: string | undefined;
private readonly disableBuiltins: boolean;
constructor(opts: SkillStoreOptions = {}) {
this.homeDir = opts.homeDir ?? homedir();
this.projectRoot = opts.projectRoot ? resolve(opts.projectRoot) : undefined;
this.disableBuiltins = opts.disableBuiltins === true;
}
/** True iff this store was configured with a project root. */
hasProjectScope(): boolean {
return this.projectRoot !== undefined;
}
/**
* Root directories scanned, in priority order. Project scope first
* so a per-repo skill overrides a global one with the same name —
* users expect the local copy to win when both exist.
*/
roots(): Array<{ dir: string; scope: SkillScope }> {
const out: Array<{ dir: string; scope: SkillScope }> = [];
if (this.projectRoot) {
out.push({
dir: join(this.projectRoot, ".reasonix", SKILLS_DIRNAME),
scope: "project",
});
}
out.push({ dir: join(this.homeDir, ".reasonix", SKILLS_DIRNAME), scope: "global" });
return out;
}
/**
* List every skill visible to this store. On name collisions the
* higher-priority root (project over global over builtin) wins.
* Sorted by name for stable prefix hashing.
*/
list(): Skill[] {
const byName = new Map<string, Skill>();
for (const { dir, scope } of this.roots()) {
if (!existsSync(dir)) continue;
let entries: import("node:fs").Dirent[];
try {
entries = readdirSync(dir, { withFileTypes: true });
} catch {
continue;
}
for (const entry of entries) {
const skill = this.readEntry(dir, scope, entry);
if (!skill) continue;
if (!byName.has(skill.name)) byName.set(skill.name, skill);
}
}
// Builtins are appended last so user/project files take precedence
// when names collide. The same priority you'd expect: my-project's
// "explore" overrides the shipped one without forcing a different
// name.
if (!this.disableBuiltins) {
for (const skill of BUILTIN_SKILLS) {
if (!byName.has(skill.name)) byName.set(skill.name, skill);
}
}
return [...byName.values()].sort((a, b) => a.name.localeCompare(b.name));
}
/** Resolve one skill by name. Returns `null` if not found or malformed. */
read(name: string): Skill | null {
if (!isValidSkillName(name)) return null;
for (const { dir, scope } of this.roots()) {
if (!existsSync(dir)) continue;
const dirCandidate = join(dir, name, SKILL_FILE);
if (existsSync(dirCandidate) && statSync(dirCandidate).isFile()) {
return this.parse(dirCandidate, name, scope);
}
const flatCandidate = join(dir, `${name}.md`);
if (existsSync(flatCandidate) && statSync(flatCandidate).isFile()) {
return this.parse(flatCandidate, name, scope);
}
}
// Fall back to builtins. Same precedence as `list()` — user-authored
// wins, builtins are the floor.
if (!this.disableBuiltins) {
for (const skill of BUILTIN_SKILLS) {
if (skill.name === name) return skill;
}
}
return null;
}
private readEntry(dir: string, scope: SkillScope, entry: import("node:fs").Dirent): Skill | null {
if (entry.isDirectory()) {
if (!isValidSkillName(entry.name)) return null;
const file = join(dir, entry.name, SKILL_FILE);
if (!existsSync(file)) return null;
return this.parse(file, entry.name, scope);
}
if (entry.isFile() && entry.name.endsWith(".md")) {
const stem = entry.name.slice(0, -3);
if (!isValidSkillName(stem)) return null;
return this.parse(join(dir, entry.name), stem, scope);
}
return null;
}
private parse(path: string, stem: string, scope: SkillScope): Skill | null {
let raw: string;
try {
raw = readFileSync(path, "utf8");
} catch {
return null;
}
const { data, body } = parseFrontmatter(raw);
const name = data.name && isValidSkillName(data.name) ? data.name : stem;
return {
name,
description: (data.description ?? "").trim(),
body: body.trim(),
scope,
path,
allowedTools: data["allowed-tools"],
runAs: parseRunAs(data.runAs),
model: data.model?.startsWith("deepseek-") ? data.model : undefined,
};
}
}
/**
* Coerce a frontmatter `runAs` string to the discriminated union. Any
* value other than the literal "subagent" is treated as inline — typos
* and unknown values default to the safe (non-spawning) mode rather
* than failing the load.
*/
function parseRunAs(raw: string | undefined): SkillRunAs {
return raw?.trim() === "subagent" ? "subagent" : "inline";
}
/**
* 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 `[🧬 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 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 ? `- ${s.name}${tag} — ${clipped}` : `- ${s.name}${tag}`;
}
/**
* Append a `# Skills` block to `basePrompt` listing every discovered
* skill (name + description only). Bodies are NOT inlined — that's the
* whole point: the prefix stays short and cacheable; full content loads
* on demand via `run_skill` or `/skill <name>`.
*
* Emits nothing when no skills are discovered — keeps the prefix hash
* stable for users who don't use skills at all.
*/
export function applySkillsIndex(basePrompt: string, opts: SkillStoreOptions = {}): string {
const store = new SkillStore(opts);
const skills = store.list().filter((s) => s.description);
if (skills.length === 0) return basePrompt;
const lines = skills.map(skillIndexLine);
const joined = lines.join("\n");
const truncated =
joined.length > SKILLS_INDEX_MAX_CHARS
? `${joined.slice(0, SKILLS_INDEX_MAX_CHARS)}\n… (truncated ${
joined.length - SKILLS_INDEX_MAX_CHARS
} chars)`
: joined;
return [
basePrompt,
"",
"# 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>" })` — 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,
"```",
].join("\n");
}
/**
* Built-in skills shipped with Reasonix. These are always available
* (no install step) and live as constants rather than files because:
* - Zero filesystem coupling — no copy-on-first-run dance, nothing
* to migrate when we update them.
* - They participate in the same `byName` priority as user/project
* skills: write `~/.reasonix/skills/explore.md` to override.
*
* Keep this list small and high-leverage. The bar for adding one: it
* demonstrates a pattern users would otherwise have to invent
* themselves, and the body fits in a screen.
*/
const BUILTIN_EXPLORE_BODY = `You are running as an exploration subagent. Your job is to investigate the codebase the parent agent pointed you at, then return one focused, distilled answer.
How to operate:
- Use read_file, search_files, search_content, directory_tree, list_directory, get_file_info as your primary tools. Stay read-only.
- For "find all places that call / reference / use X" questions, use \`search_content\` (content grep) — NOT \`search_files\` (which only matches file names). This is the most common subagent mistake; using the wrong tool gives empty results and you waste your iter budget chasing a phantom.
- Cast a wide net first (search_content for symbol references, directory_tree for structure) to map the territory; then read the 3-10 most relevant files in full.
- Don't read every file — be selective. Aim for breadth on the first pass, depth only where the question demands it.
- Stop exploring as soon as you can answer the question. The parent doesn't see your tool calls, so over-exploration is pure waste.
Your final answer:
- One paragraph (or a few short bullets). Lead with the conclusion.
- Cite specific file paths + line ranges when they support the 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.
${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.`;
const BUILTIN_RESEARCH_BODY = `You are running as a research subagent. Your job is to gather information from code AND the web, synthesize it, and return one focused conclusion.
How to operate:
- Combine code reading (read_file, search_files) with web tools (web_search, web_fetch) as appropriate to the question.
- For "how does X work" / "is Y supported" questions: web first to find the canonical reference, then verify against the local code.
- For "what's our policy on Z" / "where do we use Q": local code first, web only if you need to compare against external standards.
- Cap yourself at ~10 tool calls. If you can't converge in 10, return what you have plus a note about what's missing.
Your final answer:
- One paragraph (or short bullets). Lead with the conclusion.
- Cite both code (file:line) AND web sources (URL) when they back the 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.
${NEGATIVE_CLAIM_RULE}
${TUI_FORMATTING_RULES}
The 'task' the parent gave you is the research question. Stay on it.`;
const BUILTIN_SKILLS: readonly Skill[] = Object.freeze([
Object.freeze<Skill>({
name: "explore",
description:
"Explore the codebase in an isolated subagent — wide-net read-only investigation that returns one distilled answer. Best for: 'find all places that...', 'how does X work across the project', 'survey the code for Y'.",
body: BUILTIN_EXPLORE_BODY,
scope: "builtin",
path: "(builtin)",
runAs: "subagent",
}),
Object.freeze<Skill>({
name: "research",
description:
"Research a question by combining web search + code reading in an isolated subagent. Best for: 'is X feature supported by lib Y', 'what's the canonical way to do Z', 'compare our impl against the spec'.",
body: BUILTIN_RESEARCH_BODY,
scope: "builtin",
path: "(builtin)",
runAs: "subagent",
}),
]);
+45 -8
View File
@@ -1,12 +1,33 @@
import type { Usage } from "./client.js";
/** USD per 1M tokens. Update as DeepSeek pricing changes. */
/**
* 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%.
*
* 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.07, inputCacheMiss: 0.27, output: 1.1 },
"deepseek-reasoner": { inputCacheHit: 0.14, inputCacheMiss: 0.55, output: 2.19 },
"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). */
@@ -14,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. */
@@ -94,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 {
@@ -155,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),
};
}
}
+375
View File
@@ -0,0 +1,375 @@
/**
* Pure-TS port of DeepSeek's V3 tokenizer. Reads the slimmed+gzipped
* HuggingFace-format tokenizer data shipped at
* `data/deepseek-tokenizer.json.gz` and implements enough of the HF
* pipeline (Split pre-tokenizers → ByteLevel → BPE) to count tokens
* offline without pulling the `@lenml/tokenizers` or native Rust deps.
*
* Accuracy target: within ~3% of the API-returned `usage.prompt_tokens`
* for mixed CJK+English+code input. Exact-to-API match would also
* require replaying the Jinja chat template (role markers / tool call
* framing); we intentionally skip that — for a gauge/UI estimate the
* raw-text count is the useful number.
*
* Scope: ENCODE-SIDE ONLY. We don't need decode for counting; adding
* it later is trivial via the inverse byte-level table.
*/
import { existsSync, readFileSync } from "node:fs";
import { createRequire } from "node:module";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { gunzipSync } from "node:zlib";
interface AddedToken {
id: number;
content: string;
special: boolean;
normalized: boolean;
}
interface SplitPretokenizer {
type: "Split";
pattern: { Regex: string };
behavior: "Isolated" | "Removed" | string;
invert: boolean;
}
interface ByteLevelPretokenizer {
type: "ByteLevel";
add_prefix_space: boolean;
trim_offsets: boolean;
use_regex: boolean;
}
type Pretokenizer = SplitPretokenizer | ByteLevelPretokenizer;
interface TokenizerData {
added_tokens: AddedToken[];
pre_tokenizer: {
type: "Sequence";
pretokenizers: Pretokenizer[];
};
model: {
type: "BPE";
vocab: Record<string, number>;
merges: string[];
};
}
interface LoadedTokenizer {
vocab: Record<string, number>;
mergeRank: Map<string, number>;
splitRegexes: RegExp[];
byteToChar: string[];
/**
* Non-special added tokens (e.g. `<think>`, `<|fim▁hole|>`) that the
* HF tokenizer recognizes as atomic units when they appear inline in
* the text. Special tokens like `<|begin▁of▁sentence|>` are NOT in
* this list — the model ignores them when they appear in user text
* (the default HF `split_special_tokens=False` behavior), so we do
* the same: they get tokenized byte-by-byte, not as the special ID.
*/
addedPattern: RegExp | null;
addedMap: Map<string, number>;
}
/**
* GPT-2 byte-to-unicode mapping. Covers every byte 0..255 with a
* deterministic visible-printable unicode char — this is what lets the
* byte-level BPE show up in JSON vocabs as readable strings (`Ġ` for
* space, `Ċ` for `\n`, etc). Identical across every byte-level BPE
* tokenizer DeepSeek ships.
*/
function buildByteToChar(): string[] {
const result: string[] = new Array(256);
const bs: number[] = [];
for (let b = 33; b <= 126; b++) bs.push(b);
for (let b = 161; b <= 172; b++) bs.push(b);
for (let b = 174; b <= 255; b++) bs.push(b);
const cs = bs.slice();
let n = 0;
for (let b = 0; b < 256; b++) {
if (!bs.includes(b)) {
bs.push(b);
cs.push(256 + n);
n++;
}
}
for (let i = 0; i < bs.length; i++) {
result[bs[i]!] = String.fromCodePoint(cs[i]!);
}
return result;
}
let cached: LoadedTokenizer | null = null;
/**
* Find the bundled tokenizer data file. Resolution order (first hit wins):
* 1. `REASONIX_TOKENIZER_PATH` env var (tests / custom builds).
* 2. `../data/deepseek-tokenizer.json.gz` relative to this module —
* covers dev (src/tokenizer.ts → data/) AND production bundled at
* dist/index.js → dist/../data = data/.
* 3. `../../data/deepseek-tokenizer.json.gz` — covers the CLI bundle
* at dist/cli/index.js → dist/cli/../../data = data/. Without this
* step 2 resolves to dist/data/ which doesn't exist (the data file
* is shipped at package root per package.json `files` entry), and
* every step() preflight crashes the loop with ENOENT.
* 4. `require.resolve("reasonix/package.json")` — last-resort package
* root lookup for unusual bundlers.
*/
function resolveDataPath(): string {
if (process.env.REASONIX_TOKENIZER_PATH) return process.env.REASONIX_TOKENIZER_PATH;
const candidates: string[] = [];
try {
const here = dirname(fileURLToPath(import.meta.url));
candidates.push(join(here, "..", "data", "deepseek-tokenizer.json.gz"));
candidates.push(join(here, "..", "..", "data", "deepseek-tokenizer.json.gz"));
} catch {
/* import.meta.url unavailable — skip to the package resolution step. */
}
try {
const req = createRequire(import.meta.url);
candidates.push(
join(dirname(req.resolve("reasonix/package.json")), "data", "deepseek-tokenizer.json.gz"),
);
} catch {
/* Not installed as `reasonix/` — the earlier candidates still may hit. */
}
for (const p of candidates) {
if (existsSync(p)) return p;
}
// Nothing exists — return the first candidate anyway so readFileSync
// surfaces a concrete path in the ENOENT message (better than silent miss).
return candidates[0] ?? join(process.cwd(), "data", "deepseek-tokenizer.json.gz");
}
function loadTokenizer(): LoadedTokenizer {
if (cached) return cached;
const buf = readFileSync(resolveDataPath());
const json = gunzipSync(buf).toString("utf8");
const data = JSON.parse(json) as TokenizerData;
const mergeRank = new Map<string, number>();
for (let i = 0; i < data.model.merges.length; i++) {
mergeRank.set(data.model.merges[i]!, i);
}
const splitRegexes: RegExp[] = [];
for (const p of data.pre_tokenizer.pretokenizers) {
if (p.type === "Split") {
// All three Split rules use Isolated — matches become their own
// pre-tokens and so do the in-between stretches. The ByteLevel
// stage in the Sequence does no extra splitting here
// (use_regex:false), so our 3 Split regexes are the whole story.
splitRegexes.push(new RegExp(p.pattern.Regex, "gu"));
}
}
const addedMap = new Map<string, number>();
const addedContents: string[] = [];
for (const t of data.added_tokens) {
if (!t.special) {
addedMap.set(t.content, t.id);
addedContents.push(t.content);
}
}
// Longest-first ensures greedy matching doesn't lose a longer token
// to a shorter prefix (e.g. `<think>` before `<`).
addedContents.sort((a, b) => b.length - a.length);
const addedPattern = addedContents.length
? new RegExp(addedContents.map(escapeRegex).join("|"), "g")
: null;
cached = {
vocab: data.model.vocab,
mergeRank,
splitRegexes,
byteToChar: buildByteToChar(),
addedPattern,
addedMap,
};
return cached;
}
function escapeRegex(s: string): string {
return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
/**
* Apply one "Isolated" Split: the matches become their own pre-tokens,
* stretches between matches pass through unchanged. Empty pre-tokens
* are dropped so downstream stages don't see them.
*/
function applySplit(chunks: string[], re: RegExp): string[] {
const out: string[] = [];
for (const chunk of chunks) {
if (!chunk) continue;
// Reset lastIndex — reusing a /g regex across matchAll iterations
// is safe (matchAll internally advances), but across different
// input strings we want a clean start.
re.lastIndex = 0;
let last = 0;
for (const m of chunk.matchAll(re)) {
const idx = m.index ?? 0;
if (idx > last) out.push(chunk.slice(last, idx));
if (m[0].length > 0) out.push(m[0]);
last = idx + m[0].length;
}
if (last < chunk.length) out.push(chunk.slice(last));
}
return out;
}
/** UTF-8 bytes of `s`, each mapped to its byte-level visible char. */
function byteLevelEncode(s: string, byteToChar: string[]): string {
const bytes = new TextEncoder().encode(s);
let out = "";
for (let i = 0; i < bytes.length; i++) out += byteToChar[bytes[i]!];
return out;
}
/**
* Standard BPE merge loop. Starts from single byte-level chars and
* repeatedly applies the lowest-rank merge until none remain. O(n²)
* in chunk length, which is fine because chunks are ≤ a few hundred
* byte-level chars after pre-tokenization (and most are <50).
*/
function bpeEncode(piece: string, mergeRank: Map<string, number>): string[] {
if (piece.length <= 1) return piece ? [piece] : [];
let word: string[] = Array.from(piece);
while (true) {
let bestIdx = -1;
let bestRank = Number.POSITIVE_INFINITY;
for (let i = 0; i < word.length - 1; i++) {
const pair = `${word[i]} ${word[i + 1]}`;
const rank = mergeRank.get(pair);
if (rank !== undefined && rank < bestRank) {
bestRank = rank;
bestIdx = i;
if (rank === 0) break; // 0 is already the best possible
}
}
if (bestIdx < 0) break;
word = [
...word.slice(0, bestIdx),
word[bestIdx]! + word[bestIdx + 1]!,
...word.slice(bestIdx + 2),
];
if (word.length === 1) break;
}
return word;
}
/**
* Tokenize a UTF-8 string into DeepSeek token IDs. Mirrors the HF
* pipeline: (1) isolate non-special added tokens so they stay atomic,
* (2) for each in-between segment run the three Split regexes, (3)
* byte-level encode, (4) BPE merge, (5) look up vocab IDs.
*
* Not reentrancy-hazardous: loads a module-level singleton on first
* call and reuses it. Subsequent calls are pure compute.
*/
export function encode(text: string): number[] {
if (!text) return [];
const t = loadTokenizer();
const ids: number[] = [];
const process = (segment: string) => {
if (!segment) return;
let chunks: string[] = [segment];
for (const re of t.splitRegexes) chunks = applySplit(chunks, re);
for (const chunk of chunks) {
if (!chunk) continue;
const byteLevel = byteLevelEncode(chunk, t.byteToChar);
const pieces = bpeEncode(byteLevel, t.mergeRank);
for (const p of pieces) {
const id = t.vocab[p];
// If not in vocab we silently skip: shouldn't happen for
// byte-level BPE (every single byte has its own vocab entry),
// but if a future tokenizer update breaks that invariant we'd
// rather under-count than throw from a UI gauge.
if (id !== undefined) ids.push(id);
}
}
};
if (t.addedPattern) {
t.addedPattern.lastIndex = 0;
let last = 0;
for (const m of text.matchAll(t.addedPattern)) {
const idx = m.index ?? 0;
if (idx > last) process(text.slice(last, idx));
const id = t.addedMap.get(m[0]);
if (id !== undefined) ids.push(id);
last = idx + m[0].length;
}
if (last < text.length) process(text.slice(last));
} else {
process(text);
}
return ids;
}
/**
* Fast path for UI: we only need the count, not the IDs. Saves a
* per-call array allocation and lets callers batch large logs
* without holding the full ID stream.
*/
export function countTokens(text: string): number {
return encode(text).length;
}
/**
* Estimate the tokens a full conversation would cost. Sums raw-text
* counts for every message's content; we do NOT add overhead for the
* chat template's role markers (`<|User|>`, `<|Assistant|>`) because
* the exact framing varies between the chat/reasoner templates and
* DeepSeek applies them server-side anyway. Empirically adds ~3-6%
* to the real `prompt_tokens` — callers who care can post-multiply.
*/
export function estimateConversationTokens(
messages: Array<{ content?: string | null; tool_calls?: unknown }>,
): number {
let total = 0;
for (const m of messages) {
if (typeof m.content === "string" && m.content) {
total += countTokens(m.content);
}
// Tool-call arguments are serialized as JSON in the prompt by the
// chat template; their bytes WILL count upstream, so we count
// them too. Stringify-once is cheap relative to the tokenize.
if (m.tool_calls && Array.isArray(m.tool_calls) && m.tool_calls.length > 0) {
total += countTokens(JSON.stringify(m.tool_calls));
}
}
return total;
}
/**
* Estimate the tokens a full DeepSeek request would cost: the
* conversation-side tokens (what `estimateConversationTokens` already
* counts) PLUS the serialized tool-spec payload. Tool specs ride in
* their own JSON blob in the request body, not folded into any
* message's `content`, so they need a separate count to land an
* accurate preflight estimate.
*
* Returned number matches what `/context` displays for "next request"
* — reuse this helper anywhere (preflight guard, diagnostics, UI) to
* keep the two values from drifting.
*/
export function estimateRequestTokens(
messages: Array<{ content?: string | null; tool_calls?: unknown }>,
toolSpecs?: ReadonlyArray<unknown> | null,
): number {
let total = estimateConversationTokens(messages);
if (toolSpecs && toolSpecs.length > 0) {
total += countTokens(JSON.stringify(toolSpecs));
}
return total;
}
/** Exposed for tests — resets the lazy-load singleton. */
export function _resetForTests(): void {
cached = null;
}
Loaded 100 of 168 files, more files were not shown because too many files have changed in this diff. Show more