Compare commits

...
147 Commits
Author SHA1 Message Date
esengine 146ddb0658 chore(release): 0.16.0 — drag-select with auto-scroll · /copy retired
feat(ui): plain mouse drag in the log now paints a reverse-video
selection, dragging past the viewport edge auto-scrolls the log, and
releasing copies the selected text to the system clipboard via OSC 52
+ tempfile fallback. Shift+drag still bypasses tracking for native
terminal selection.

chore(ui): the old /copy slash command, copyMode lifecycle, and
mouse-tracking helpers are gone — the new flow stays inside
alt-screen so there's no main-buffer dump to manage.
2026-04-29 08:10:50 -07:00
esengine 0620c8ee4e fix(ui): correct mouse→abs-row math when content is shorter than viewport
The old mouseToAbsRow assumed log content always started at the top of
the box. Two cases broke that:
1. ChromeBar is 2 rows (pills + ChromeRule), not 1 — log starts at row 3.
2. At logScrollOffset=0, the inner Box uses justifyContent="flex-end",
   so when totalRows < available the content is bottom-anchored and the
   top of the box is empty — clicks there were mapping to row 0.

Now the geometry IIFE computes contentTopRow / contentBottomRow per
render based on the actual layout (scrolled vs latest, BottomHint
present vs not), and mouseToAbsRow uses those instead of guessing from
logTopRow. Auto-scroll edge triggers use the real content edges too.
2026-04-29 08:10:09 -07:00
esengine 13a15bb665 feat(ui): native drag-select with auto-scroll at edge — replaces /copy
App now owns mouse selection. Plain drag in the log paints a reverse-
video selection highlight; dragging past the top/bottom edge of the
viewport auto-scrolls one row every 60ms; releasing copies the selected
text via OSC 52 to the system clipboard plus a tempfile fallback for
terminals that don't honor it. Shift+drag still bypasses tracking for
native terminal selection.

stdin-reader surfaces mouseDrag (SGR btn=32) and mouseRelease (tail='m')
events; alt-screen switches from mode 1000 (press only) to 1002
(button-event tracking with drag motion); log-frame extends AtomViewport
with firstRowAbs and adds extractSelection() to pull plain text out of
the selected absolute-row range.

Old /copy slash command, copyMode lifecycle, and the
isMouseTrackingOn / setMouseTracking helpers are removed — the new
flow stays inside alt-screen the whole time so there's no main-buffer
dump to manage.
2026-04-29 08:02:21 -07:00
esengine ef787f8eba fix(benchmarks): point harvest/tau runners at src/transcript/log.js
The structure refactor (3b0dd73) moved src/transcript.ts under
src/transcript/, but the two benchmark runners kept the old import
path and tripped CI's tau-bench dry-run.
2026-04-29 07:53:48 -07:00
esengine 3b0dd73d31 fix(tests): de-flake jobs read test under CPU load
read(jobId) test fired fixed 300ms sleeps after child spawn; under
parallel-suite contention the child hadn't printed yet and the
"contains 'a'" assertion failed. Replace fixed waits with a 100ms × 20
poll loop. Same shape as the `since` test below it.
2026-04-29 07:43:35 -07:00
esengine d84de144b7 refactor(structure): consolidate root scatter into memory/ telemetry/ transcript/
The root of src/ had 25 top-level *.ts files mixed with subdirs, including
several that map directly to architectural layers in design/architecture.md.

- memory pyramid → src/memory/{runtime,session,project,user}.ts
- telemetry      → src/telemetry/{stats,usage}.ts
- transcript     → src/transcript/{log,replay,diff}.ts

git mv preserves history. Internal cross-imports updated (siblings drop
the prefix; references to non-moved root files gain `../`). Public barrel
in src/index.ts and all consumers (~50 sites in src + 18 test files)
retargeted. Behavior is unchanged; verify (lint + typecheck + tests) green.
2026-04-29 07:40:58 -07:00
esengine a47f457ef2 chore(release): 0.15.0 — event-log replay · deny-with-context · comment-policy gate
feat(core): replay() reads events.jsonl sidecar and runs the same
pure reducers as in-process apply() — first deterministic proof of
the v0.14 projection layer.
feat(cli): reasonix events <name> for inspecting any session's event
stream from the command line.
feat(ui): deny-with-context shipped via PR #1 (@wviana) — Tab on a
tool-confirm modal opens inline reason entry, forwarded to the model
so it knows *why* the user refused.
chore: tests/comment-policy.test.ts enforces CLAUDE.md rules under
npm run verify; companion sweep removed 6.3k LoC of dead-weight
comments across 148 files.
2026-04-29 07:24:33 -07:00
esengine 9a5bbcc0e8 chore(comments): enforce CLAUDE.md no-essay rule via vitest + sweep -6.3k LoC
tests/comment-policy.test.ts pins six rules: ≤2-line module headers, no
Phase-N narrative, no version refs in comments, no incident history, no
banner separators, ≤3-line block comments. Runs under `npm run verify`
so pre-push catches new violations.

148 src files touched: 116 module-essay headers compressed to one line,
577 over-long block comments distilled or deleted, 44 banner separators
stripped, all v0.x / Phase-N / "user reported" / "fix for #N" narrative
removed. Net -6367 LoC of dead-weight comments. No behavior change;
1759/1759 tests, lint, typecheck pass.
2026-04-29 07:13:40 -07:00
esengine a1dd12008d chore(ui): trim deny-with-context comments to one-liners
Multi-paragraph docstrings + restated-what comments shipped via PR #1
trimmed back per CLAUDE.md.
2026-04-29 06:21:12 -07:00
Wesley Viana 622d5f89bb feat(ui): allow user to add context when denying a tool call
Pressing Tab on a Deny item (or n on edit-review) opens an inline input so the user can tell the model *why* they refused. Context is forwarded into the synthetic message and the historical log.

Also: stdin-reader.ts now probes setRawMode directly so bun (where isTTY is undefined) can still go interactive; useKeystroke falls back to Ink useInput when no KeystrokeProvider is mounted.

Closes #1
2026-04-29 06:14:21 -07:00
esengine f29eb405e6 feat(cli): reasonix events <name> + sweep dead comments off the kernel
reasonix events <name> pretty-prints the event-log sidecar — the first
user-facing consumer of events.jsonl. Renders one line per event with
per-type detail synopses; --type / --since / --tail filters; --json
for jq pipelines; --projection dumps the reduced ProjectionSet. Closes
the v0.14 kernel loop: events get written by every session, and now
there's a tool to read them.

Sweep pass: trimmed verbose jsdoc / restated-the-code comments off
eventize.ts, event-sink-jsonl.ts, event-source-jsonl.ts, and the
tests. ~80 lines of comment cruft gone, no logic changed.

- src/cli/commands/events.ts: command formatter + per-event detail
  table covering all 25 Event variants
- src/cli/index.ts: command registration with commander, help text
- tests/events-command.test.ts: 6 tests pinning the formatter + each
  flag (type filter, tail, json passthrough, projection, missing
  session error path)

1753 tests pass (was 1747 + 6 new).
2026-04-29 06:01:21 -07:00
esengine d3613ddb18 feat(core): event-log replay — first consumer reads sidecar + projects
Closes the loop on the v0.14 kernel architecture: the events.jsonl
sidecar from the prior commit is now demonstrably reduceable into a
useful projection. Synthetic LoopEvents → Eventizer → JsonlEventSink
→ disk → JsonlEventSource → reducers.replay() → ProjectionSet round-
trips correctly, conversation messages reconstructed in order, tool
result correlation preserved, replay() deterministic across runs.

This is the architecture-value tipping point: events are no longer
just write-only artifacts, they're the source of truth a consumer
can rebuild state from. Future work — UI re-rendering from a
projection, time-travel, multi-agent event trees — has a working
foundation.

- src/adapters/event-source-jsonl.ts: EventSource port impl. Pure
  read side: parses jsonl, skips malformed lines silently (best-
  effort replay over a possibly-truncated live writer).
- tests/event-sink-jsonl.test.ts: 5 tests pinning the sink mechanics
  (append-per-line round-trip, re-open on existing file, parent dir
  creation, flush no-op, port-shape conformance).
- tests/event-replay.test.ts: 5 tests pinning the architecture
  promise — synthetic LoopEvents reduce to expected projections,
  error-shaped tool results land with ok=false, replay determinism,
  missing-file safety, malformed-line tolerance.

1747 tests pass (was 1737 + 10 new). Zero touches to existing
production code.
2026-04-29 05:48:15 -07:00
esengine f36282d258 feat(core): event-log sidecar — kernel artifact alongside LoopEvent
Adds a new durable artifact: every session now writes a typed Event
log to ~/.reasonix/sessions/<name>.events.jsonl as a sidecar to the
existing ChatMessage / transcript files. Foundation for future
replay / projection / multi-agent consumers reading kernel events
instead of LoopEvent.

Architecturally a pure addition: no edits to loop.ts, transcript.ts,
EventLog, log-frame, replay, dashboard server, or any existing test.
LoopEvent stays as the internal protocol between loop and immediate
consumers — events.jsonl is a parallel kernel artifact, not a
migration target.

- src/core/eventize.ts: pure stateful translator. Holds monotonic
  event id seq, last-turn tracker (synthesizes model.turn.started),
  and a callId stack (correlates tool.intent → tool.dispatched →
  tool.result chains since LoopEvent.tool_start doesn't carry
  call.id).
- src/adapters/event-sink-jsonl.ts: concrete EventSink port impl —
  append-only JSONL with append/flush/close lifecycle. eventLogPath
  helper derives the sidecar path from a session name (mirrors
  src/session.ts:sessionPath).
- src/cli/ui/App.tsx: ~30 lines additive — refs for sink + eventizer
  opened on session mount (skipped for ephemeral sessions), pipe
  attached inside the existing for-await consumer alongside
  writeTranscript, sink.close on unmount, session.opened emitted at
  open time.
- tests/eventize.test.ts: 11 unit tests pinning the mapper —
  turn-start synthesis, delta channel split, tool callId
  correlation, error detection, warning categorization, control-
  marker passthrough.

1737 tests pass (was 1726 + 11 new). Zero existing-test edits.
2026-04-29 05:48:15 -07:00
esengine 33a3a7fd49 chore(release): 0.14.0 — abort-race fix · /copy mode · ctx footer · primitives
fix(loop): streaming-abort path resets _turnAbort before returning,
so a queued-submit triggered by ShellConfirm "run once" no longer
trips a spurious "aborted at iter 0/64" on the next user message.
fix(tui): edit_file interceptor reads root via currentRootDirRef so
post-workspace-switch writes don't go to the stale root while
read_file looks at the new one.

feat(tui): /copy exits alt-screen and dumps the rendered log to
main screen, returning on any keystroke — native scrollback + drag
select work on the dump.
feat(tui): always-on context-pressure footer above the prompt
(`ctx ▰▱… 14K/977K · 1% · sys 5.8K · tools 6.1K · log 0`); /context
toggles visibility, full breakdown panel still pushed to scrollback
for headless / replay.
feat(tui): chrome bar drops the cols<120 hard cutoff in favor of
width-aware shed by priority (balance > cache > session > update);
cache pill default-on with cold-start dim treatment.

refactor(ui): Bar / formatTokens / ChromeRule / ContextCell promoted
to primitives.tsx; CtxBreakdownBlock + computeCtxBreakdown share a
single compute path; StatsPanel shrunk 769 → ~280 lines (dead
chrome-redesign helpers removed).

feat(core): v0.14 architecture scaffold — Event log + pure-reducer
projections (core/) and 6 ports (ports/). Types only, zero behavior
change. 19 new reducer tests pin the projections + prove replay
determinism.
2026-04-29 04:56:45 -07:00
esengine 535a8ebb3b chore(release): 0.13.5 — TUI overhaul (chrome / streaming / scroll progress)
* chrome → native Ink Box+flexGrow (Phase 6a Frame-compiler path
  was clipping pills on Windows Terminal / ConPTY); preset pill
  replaces edit-mode pill; CNY balance uses ¥; cost includes
  inline budget when set
* streaming: full body text streams in (was 140-char tail) with a
  ▌ cursor blink and design-matching ░▒▓█▓▒ marquee row
* scroll: drop vertical ScrollBar (column alignment unreliable
  while legacy LogBlock atoms exist); chrome shows [↑ N%] when
  scrolled, BottomHint shows ↑ N · ▕──●──▏ X% · ↓ M · End
* frame/width: delegate to string-width package; hand-rolled
  width tables removed
* chore: project CLAUDE.md codifies code/comment conventions
2026-04-29 02:16:05 -07:00
esengine 8860cedc2a fix(frame): unify viewport-row math across log slicer + scrollbar (off-by-one)
Three places were computing 'rows the log can use' with subtly
different formulas:

  · slicer:         max(8, rows - 10)
  · scrollbar bar:  max(5, rows - 9)
  · scrollbar math: max(8, rows - 10)

Bar height (the cell count) and thumb math (the divisor) didn't
match — thumb was computed for a 20-row viewport but rendered into
21 cells, so thumb position drifted vs. the actually-rendered log
slice. User reported visual oddness consistent with this drift.

Unify on  (the parent log column's true height)
for both bar and thumb math. Slicer subtracts 1 when BottomHint
is active so the slicer doesn't claim the row the hint occupies —
the bar mirrors the same conditional so position stays in sync.

Tests: 1732/1732 pass.
2026-04-28 23:40:37 -07:00
esengine 98d6021ba9 fix(frame): restore 1-cell side padding to chrome (matches StatsPanel paddingX) + revert kitty keyboard protocol
Two reverts after the user reported chrome truncating worse than
before (only `[$` visible) and scrollbar display issues:

  · The Phase 6a chrome migration removed the legacy
    `paddingX={1}` from the StatsPanel outer Box but didn't
    restore the equivalent inner-width budget. Inner content
    rendered at full `cols` width, where on terminals that
    reserve their last column for cursor/scrollbar (Windows
    Terminal in some configs, ConPTY) the rightmost pill got
    clipped mid-glyph. Restore: build chrome at `width - 2` and
    wrap with 1-cell SPACE padding on each side so the visual
    matches the legacy chrome and the right-edge pill is safely
    inside the visible area.

  · The Phase 8 kitty keyboard protocol push (`\x1b[>1u`) was
    too aggressive — terminals without protocol support sometimes
    displayed the unrecognized CSI as visible chars, distorting
    the chrome layout. Revert until we wire feature detection
    (DA1/DA2 query response) before pushing the flag. The
    setImmediate-based ESC ambiguity timer in stdin-reader keeps
    handling the bogus-Esc bug class for now.

The earlier 1-cell safety margin (`width - 1` in App.tsx) is
removed since the new `paddingX`-equivalent already provides
the right-edge buffer.

Tests: 1732/1732 pass. Lint clean. Typecheck clean.
2026-04-28 23:37:52 -07:00
esengine 3e71089068 fix(frame): leave 1-cell right-edge margin for chrome to avoid terminal clipping
User reported wallet pill still clipped at "[w" even after the
appendCells / composeRow fixes. Reproduction confirmed our Frame
output is correct (full 120-col row, all cells styled, ANSI bytes
intact) — the clipping happens at the Ink/terminal layer.

Most likely culprit: terminals that reserve their rightmost column
for the cursor or a scrollbar (some Windows Terminal / ConPTY
configurations report 120 cols but only render 119 visibly), or
Ink miscounting our SGR-rich row width.

Cheapest fix: build chrome at stdout.columns - 1, leaving a 1-cell
safety margin. The cost is one column of empty space at the right
edge; the gain is the wallet / cache pills survive on every
terminal we've seen.

Tests: 1732/1732 still pass.
2026-04-28 23:29:22 -07:00
esengine 7a5ef3b163 fix(frame): wallet pill truncation + composeRow overflow handling in chrome
User reported the wallet pill at the top wasn't displaying fully.
Two bugs in `chrome-frame.ts`:

1. `appendCells` was padding to a generous width then stripping
   trailing-space-with-no-style cells. That stripped REAL spaces
   the caller had explicitly added as inter-pill separators
   (`appendCells(right, "  ")`), collapsing pills into each other
   visually. Fix: pass the EXACT visual width of the input string
   to `text()` so no padding is added in the first place.

2. `composeRow` only handled "left+right combined exceeds width"
   by truncating left. When `right alone` exceeded width, cells
   were appended past the row budget — Frame width invariant
   violated, terminal showed pills cut off mid-glyph. Fix: add a
   case-3 branch that truncates from the LEFT EDGE of the right
   group (drop update / mode / pro pills first; cost / balance /
   cache live at the rightmost end and survive longest), so the
   wallet pill stays visible even on terminals where every
   optional pill is active.

Three new tests:
  · wallet preserved when right side overflows (case 2)
  · width invariant holds when right alone exceeds width (case 3)
  · inter-pill spacer is NOT collapsed (the appendCells regression)

Tests: 1732/1732 pass (1729 prior + 3 new). Lint clean.
2026-04-28 23:20:28 -07:00
esengine 28b3f40b9e feat(frame): Phase 6a — StatsPanel chrome → Frame; generic frame-render helper
Chrome row + horizontal rule + optional budget row now compile to
a single Frame via `chromeFrame()` in `src/cli/ui/chrome-frame.ts`.
App.tsx renders it via the new generic `renderFrame(f, keyPrefix)`
helper in `src/cli/ui/frame-render.tsx`, which wraps each Frame
row in `<Box height={1}><Text>{ansi}</Text></Box>` — same
single-row-Box translation the log path uses.

  · `chromeFrame(props)` composes:
      · brand wordmark + project crumb (left)
      · status pills — update, mode, pro, cost, balance, cache —
        (right, with truncate-on-narrow rules)
      · 1-row dim ─ rule
      · optional budget row (`budget  $X / $Y  (Z%)` with amber
        at 80% / red at 100%)

  · `renderFrame(f, keyPrefix)` is generic — log atoms, chrome,
    and future modals/prompt all flow through it. Phase 7's
    direct-stdout paint layer will replace this helper without
    touching call sites.

  · App.tsx no longer imports `<StatsPanel>`. The legacy file is
    untouched (tests/observability still reference some helpers)
    and can be deleted in a follow-up once the dashboard panel
    confirms it's unused too.

Tests: 1729/1729 pass (1714 prior + 15 new chrome-frame tests
covering brand / project crumb / narrow truncation / cost / mode /
pro / update / balance / cold-start cache / rule / budget / row-
width invariant under all configurations). Lint clean. Typecheck clean.

Phase 6 progress:
  · 6a chrome  ← this commit
  · 6b modals  (next: ModalCard + EditConfirm + ShellConfirm + …)
  · 6c prompt  (PromptInput + suggestion area)
2026-04-28 23:13:54 -07:00
esengine efb0a77648 feat(frame): Phase 5 — markdown → Frame compiler, restores rich text styling on assistant / plan bodies
Reuses the existing block-level parser (`parseBlocks` from
markdown.tsx) and adds a per-block Frame compiler in
`src/cli/ui/markdown-frame.ts`. Closes the visual regression
introduced in Phase 4 where assistant body / plan body fell back
to plain text in exchange for row-level scrolling.

Coverage in this first pass — most common 90% of model output:
  · paragraphs with inline markup (bold, italic, code, link, strike)
  · headings (H1–H6, bold + tone keys off level)
  · bullet lists (`- ` / `* ` / `1. `) including GFM task items
                  with `[x]` / `[ ]` indicators
  · fenced code blocks with bg tint per line
  · blockquotes (left-border + dim text, recursive on children)
  · horizontal rule

Inline parser:
  · regex shared with `markdown.tsx`'s INLINE_RE so styling
    matches the legacy renderer for the same input
  · soft-wrap at last whitespace; hard-wrap as fallback when a
    single token exceeds line budget
  · 2-wide CJK / emoji handled via the Phase-1 width module

Wiring:
  · `simpleAssistantFrame` and `complexAssistantFrame` body now
    flow through `markdownToFrame()`; empty body still falls back
    to the dim "(empty body — likely tool-call only)" placeholder
  · `planFrame` body is markdown-compiled

Deferred (still plain-text fall-back inside the markdown pipeline):
  · tables                → header row + dim body rows for now
  · Aider edit-blocks     → SEARCH/REPLACE summary as plain text
  · citation validation   → URL passes through unchanged

Also tweaks `markdown.tsx` to export the `Block` AST union so the
Frame compiler can consume it without re-defining the type.

Tests: 1714/1714 pass (1699 prior + 15 new markdown-frame tests
covering paragraphs / inline / headings / lists / task items /
code / blockquote / hr / wrap / row-width invariant / links /
strike-through). Lint clean. Typecheck clean.
2026-04-28 22:49:11 -07:00
esengine 70dcad6401 feat(frame): Phase 4 — reasoning / branch / planState / ctx-breakdown / complex assistant / plan to Frame
Migrate the remaining "complex" event roles off the ink-atom
fallback. Each sub-block has been ported from its Ink component to
a Frame builder using Phase-1 primitives, then composed into the
parent role's frame.

  · reasoningFrame      "R1 ↯ reasoning · ~Nk tok · /think for full"
                         header + violet-bordered preview body (last
                         260 chars of reasoning, italic dim).

  · branchFrame         "⎇ BRANCH ×N picked #M" pill + per-branch
                         uncertainty list with the chosen one called
                         out in cyan bold.

  · planStateFrame      One row per non-empty TypedPlanState field
                         (subgoals / hypotheses / uncertainties /
                         rejected) with its bold colored label,
                         count, and items joined by " · ".

  · ctxBreakdownFrame   `/context` 4-color stacked char-bar across
                         48 cells + legend with token counts. Used
                         to be `<CtxBreakdownBlock>`.

  · complexAssistantFrame  Composes branch / reasoning / planState /
                            body / stats / repair into one
                            assistant-accent bordered column. Body
                            is plain-text for now (markdown→Frame
                            is deferred to a future phase) — code
                            blocks / bold spans render unstyled but
                            scrolling works row-by-row.

  · planFrame           "📋 plan proposed" header + plain-text body.
                         Markdown rendering deferred (same as
                         complex assistant body).

Dispatch updated:
  · plan / ctx-breakdown / assistant-with-reasoning|branch|planState
    now produce frame atoms
  · ink fallback shrinks to: streaming assistant (transient),
    plan-replay, plan-resumed (rare turn-state events)

Tests: 1699/1699 pass (1696 prior + 3 new). Lint clean. Typecheck clean.

Visible regressions on the migrated paths:
  · markdown formatting (bold / italic / code spans / lists / code
    blocks) is rendered as plain text. The original formatted text
    still lives in `~/.reasonix/sessions/<name>.jsonl`. This is the
    last remaining trade-off; closing it requires a markdown→Frame
    compiler which is the next phase.

What's next:
  · markdown → Frame  (preserves bold / code / lists in frames)
  · frame-based ScrollBar / BottomHint  (sibling components) so the
    log-rows.tsx file can be deleted entirely
  · streaming assistant migration (live atomic frame updates as
    chunks arrive)
2026-04-28 22:42:12 -07:00
esengine 3e6fdac9c0 feat(frame): Phase 3 — user / tool compact / edit_file diff to Frame
Three more roles migrated off the ink-atom fallback. Each is now
composed from Frame primitives — no Ink layout, no flex-engine
quirks, deterministic row count.

  · userFrame   — `◇ ` glyph header + cyan accent-bar body. Wraps
                   long text across rows, accent bar continues down
                   every row. Conditional turn-separator (gradient
                   rule with centered `◆` brand mark) above when
                   `event.leadSeparator` is set.

  · toolCompactFrame — `[bar] ▣ name [duration] [summary] /tool N`,
                        single-row, color tone keys off whether the
                        result starts with `ERROR:` (red pill +
                        accent vs. cyan pill + tool-yellow accent).

  · editFileDiffFrame — multi-row block:
                          1) `▣ edit_file   diff:` header
                          2) status header line (`edited X (A→B chars)`)
                          3) magenta-pill hunk header (`@@ -N,M +N,M @@`)
                          4) body — each line gutter-glyphed and
                             tinted (`−` red for removals, `+` green
                             for additions, `  ` dim for context)

  · turnSeparatorFrame — gradient `─` rule with centered `◆` mark,
                          composed from `gradientCells()` cells.

  · rowFrame helper — concat-cells-and-pad-to-width for layouts
                       conceptually one line of mixed-style segments
                       (tool pills, header rows). Truncates if too
                       wide, right-pads if too narrow.

Tests: 1696/1696 pass (1690 prior + 6 new). Lint clean. Typecheck clean.

Remaining ink-atom escape hatch (next):
  · plan / plan-replay / plan-resumed  (uses Markdown renderer —
                                        either render markdown to
                                        Frame OR keep markdown as
                                        ink for now)
  · ctx-breakdown                       (4-color stacked char-bar)
  · assistant with branch / reasoning /
    non-empty planState                 (rich sub-blocks)
2026-04-28 22:35:58 -07:00
esengine 5ec643033c feat(frame): Phase 2 — EventLog → Frame compiler, atom slicer
Migrate the log rendering path off the hand-rolled `log-rows.tsx`
LogRow/LogBlock pipeline onto the Frame primitives from Phase 1.

  · src/cli/ui/log-frame.tsx — new module:
      · `eventToAtom(e, projectRoot, width): LogAtom` — produces
        a `frame` atom for migrated roles (info, warning, error,
        step-progress, simple finished assistant turns) and an
        `ink` atom (legacy `<EventRow>` + estimated row count) for
        roles still pending migration (user, tool, plan / replay /
        resumed, ctx-breakdown, assistant-with-reasoning/branch).
      · `viewportLog(atoms, scrollOffset, available)` — slicer that
        operates on cumulative-row coordinates and returns
        `{ atoms, topSkip, bottomSkip, totalRows, maxScrollRows }`.
        Frame atoms support row-precise clip via `topSkip`/
        `bottomSkip`; ink atoms snap (no partial rendering).
      · `renderViewport(v)` — emits each visible row of a frame
        atom as `<Box height={1}><Text>{ansi}</Text></Box>`, and
        each ink atom as its legacy ReactElement directly.

  · App.tsx wiring:
      · imports `eventsToAtoms` / `viewportLog` / `renderViewport`
        from log-frame; keeps `ScrollBar` / `BottomHint` from
        log-rows (they're orthogonal to the slicer)
      · the renderer's IIFE replaces `eventToItems` + `sliceLogItems`
        + `slice.items.map(renderLogItem)` with the new pipeline;
        `scrollMaxRowsRef` / `lastTotalRowsRef` are filled the same
        way so the keystroke handler + scrollbar still work
      · the append-anchor effect (`historical` grows while user is
        scrolled up) sums `frame.rows.length` for frame atoms and
        `atom.rows` for ink atoms — exact for migrated roles.

  · Frame composition for these 5 roles uses primitives:
      · info / warning / error → accentFrame() = vstack(per-line
        rows of indent+body) → borderLeft for the colored bar
      · step-progress → vstack(spacer, header, optional body /
        note rows). Pill is bg-styled cells via `text()`.
      · simple assistant → vstack(spacer, header w/ optional model
        badge, borderLeft+padded body, optional repair / stats
        lines)

The OLD log-rows.tsx is no longer imported for slicing; only
ScrollBar / BottomHint remain in use. It can be deleted in a
follow-up once we're confident the new path covers every scenario.

Why this is the right shape:
  · Width invariant of every Frame is asserted by the Phase-1
    tests, so cross-event row arithmetic CAN'T drift
  · Topmost / bottommost frame atom in the viewport gets row-
    precise clip — a long summary you've scrolled past now still
    contributes its lower rows correctly, no more "long entry
    disappears when scrolling up" (user complaint that originally
    motivated this whole migration)
  · Frame data is pure → tests like log-frame.test.ts (17 cases,
    added this commit) can assert exact slice behaviour without
    spinning up Ink

Tests: 1690/1690 pass (1673 prior + 17 new). Lint clean. Typecheck clean.

Phase 3 next: migrate user / tool / plan / ctx-breakdown to
Frame builders, shrinking the ink-atom escape hatch toward zero.
Once it's empty the entire log becomes one big composable Frame.
2026-04-28 22:30:01 -07:00
esengine 7f20ccf6ac feat(frame): Phase 1 — Frame primitives, width, ANSI serializer (0.13.4)
Phase 1 of the long-term Frame-compiler architecture. New
`src/frame/` module replaces the runtime dependency on Ink's
layout engine for the log region (Phase 2 next). All pure
functions over a single immutable `Frame` data type — no React,
no Yoga, no estimates.

  · types.ts        Cell + Frame types. Each Cell carries its own
                     visual width (1 or 2) and an optional `tail`
                     marker for the second half of CJK / emoji /
                     fullwidth graphemes. The row-width invariant
                     (sum of non-tail widths == Frame.width) is
                     what every primitive guarantees.

  · width.ts        Grapheme cluster aware via `Intl.Segmenter`,
                     so ZWJ emoji like 👨‍👩‍👧 count as one cell.
                     Custom char-width tables for East Asian Wide
                     ranges (Hangul, CJK Unified Ideographs A-G,
                     Hiragana, Katakana, Fullwidth, common emoji
                     blocks). Replaces the `string-width` npm
                     dependency, which Ink uses but which was the
                     cause of the dashboard-pill OSC-8 width bug.

  · frame.ts        Primitives: empty, blank, text, vstack, hstack,
                     pad, borderLeft, slice, bottom, viewport,
                     overlay, fitWidth. All composable, all
                     deterministic. `viewport(stack, offset, height)`
                     is the slicer that future log rendering will
                     use — clamps offset, never returns empty for
                     non-empty input.

  · ansi.ts         Frame → ANSI string. Style-run batching so we
                     emit ONE SGR escape per consecutive same-style
                     run instead of per-cell. Plain-text mode for
                     snapshot tests; OSC-8 hyperlink open/close
                     bracketed around linked cells.

  · index.ts        Public surface for downstream phases.

48 new tests in `tests/frame.test.ts` covering:
  · grapheme width for ASCII / CJK / emoji / combining marks / ZWJ
  · text wrapping at width boundary, hard-break on \n,
    style propagation to every cell
  · vstack / hstack with mixed widths and heights
  · pad / borderLeft / slice / viewport / overlay / fitWidth
  · the row-width invariant, asserted on every composition output
  · ANSI serialization: style runs, OSC-8 hyperlinks, plain mode
  · CJK split-clip handling in fitWidth (replace orphan head with
    space when truncation would split a 2-wide grapheme)

Tests: 1673/1673 pass (1625 prior + 48 new). Lint clean. Typecheck clean.

Phase 2 (next): convert one EventLog role at a time to produce
Frames instead of JSX, replace `log-rows.tsx`'s row pipeline with
the Frame compiler. The current `LogRow`/`LogBlock` distinction
goes away — every event compiles to a Frame, slicer is just
`viewport(vstack(...frames), offset, height)`.
2026-04-28 22:22:56 -07:00
esengine fd26900d48 chore(infra): pre-commit + pre-push git hooks via simple-git-hooks (0.13.3)
Phase 0 of the long-term Frame-compiler architecture migration:
foundation infrastructure to make sure the rest of the migration
can't accidentally ship broken.

  · pre-commit  → npm run lint     (fast, enforces format + style
                                     before staging)
  · pre-push    → npm run verify   (lint + typecheck + test, full
                                     gate before anything reaches
                                     origin)

`simple-git-hooks` chosen over husky for zero runtime overhead and
no shell-script generation magic — the hooks live as 2-line shell
files in .git/hooks/, installed by `prepare` on every npm install
so a fresh clone gets them automatically.

`verify` script added so CI / contributors can run the same gate
locally without remembering the three sub-commands.

This replaces "remember to run lint before push", which 0.13.0
demonstrated is unreliable (CI failed on 23 Biome diagnostics
because it was forgotten). Foundation for Phase 1 (Frame primitives)
which will land next.

Tests: 1625/1625 pass. Lint clean. Typecheck clean.
2026-04-28 22:15:01 -07:00
esengine baedbf7292 feat(tui): row-granular log scroll + scrollbar + bogus-Esc fix (0.13.2)
Three significant fixes / additions on top of 0.13.1:

1. **Row-granular scrolling.** `sliceVisibleEvents` is replaced by a
   pre-flattened row pipeline in `log-rows.tsx`. Each migrated event
   role decomposes into one or more `LogRow`s (each ≈ one terminal
   line); unmigrated roles fall back to a multi-row `LogBlock` that
   wraps the legacy `<EventRow>` component. Migrated this commit:
     · info / warning / error / step-progress
     · finished assistant turns (header + body lines + stats line)
   The slicer picks items by ROW range, the renderer wraps each item
   in `<Box height={1}>`, and `overflow="hidden"` + `justifyContent`
   handle clipping. Wheel = 3 rows / tick, PgUp/Dn = ~viewport.
   Append-anchor sums row counts (not event counts) so the user's
   logical scroll position is preserved exactly when content arrives.

   The earlier negative-marginTop attempt is gone — Ink's overflow=
   hidden does NOT reliably clip negative-margin children (verified
   empirically), which let log content bleed up into the chrome and
   hide the cost / cache pills. The pre-flatten approach avoids the
   layout fight entirely.

2. **Vertical scrollbar + bottom-hint.** A 1-cell column on the
   right of the log viewport renders a brand-colored thumb whose
   position and size track the visible row range. Hidden when
   `totalRows <= viewportRows`. The scrollbar component clamps its
   own offset internally so a momentarily-stale `logScrollOffset`
   can't make the thumb shrink toward zero in "scrolling into
   emptiness" territory. Paired with a `BottomHint` row that surfaces
   "↓ N rows below — End to jump" whenever the user is scrolled up,
   so newly-arrived content at the bottom is never silently missed.

3. **No more bogus "aborted by user (Esc)".** When the event loop
   was blocked >250ms (heavy Ink render on a long log), a
   multi-byte sequence like `\x1b` + `[A` (Up arrow) split across
   chunks would dispatch as `escape` THEN `upArrow` because the
   `setTimeout`-based ESC ambiguity timer fires in the timers phase
   ahead of the poll phase where stdin data events queue. The
   spurious `escape` triggered `loop.abort()`, killing the running
   turn — the same thing the PR #1 author reported as "sometimes
   it's saying the user had aborted by pressing esc when I didn't".
   Fix: defer the timer's dispatch via `setImmediate`, which runs in
   the CHECK phase after POLL — giving any queued data events a
   chance to consume the rest of the sequence first. The chunk
   handler's `cancelEscTimer` already cancels both the timeout and
   the immediate, so a real follow-up byte still wins.

Other polish:
   · `maxScrollRows = totalRows - viewportRows` (was `totalRows - 1`)
     so Home / max scroll lands on a fully-populated viewport showing
     the start of the log instead of one row visible and the rest
     empty.
   · `useEffect` clamp on `logScrollOffset` snaps it back to
     `scrollMaxRowsRef.current` when role-rendering height drifts
     mid-stream — keeps the thumb in sync with reality.

Tests: 1625/1625 pass. Lint clean. Typecheck clean.
2026-04-28 21:39:23 -07:00
esengine d82aa833c9 fix(tui): mouse wheel + bottom-anchor long events + 0.13.0 lint cleanup (0.13.1)
Three issues from 0.13.0:

  · Mouse wheel didn't scroll at all — `useAltScreen` enabled the alt
    buffer without enabling mouse tracking, so SGR wheel events from
    `stdin-reader` were never produced. The `mouseScrollUp/Down`
    handlers in App.tsx were dead.

  · A tall LATEST event clipped its bottom rows behind
    `overflow="hidden"`, so the user couldn't see the end of long
    assistant replies / big diffs. The earlier attempt used negative
    `marginTop` for row-granular scrolling, but Ink's overflow=hidden
    doesn't reliably clip negative-margin children — content bled up
    into the chrome region, hiding the cost / cache / balance pills.

  · 0.13.0 was pushed without `npm run lint`, so CI failed on 23
    Biome diagnostics (format / organizeImports / useImportType / a
    missing useCallback dep).

Mouse tracking:
  · `useAltScreen` now turns on mode 1000 + 1006 (basic button + SGR
    coords) on mount and disables on unmount / SIGINT / SIGTERM.
    Mode 1000 captures press/release only — wheel arrives as buttons
    64/65 — without intercepting drag, so terminals that honor
    `Shift + drag` for native cell selection (Windows Terminal,
    iTerm2, WezTerm, gnome-terminal, kitty, alacritty, VS Code) still
    let the user copy/paste cleanly. `/mouse off` is the escape hatch
    for terminals that don't bypass on shift.

Long-event bottom-anchoring:
  · The middle-region Box now sets `justifyContent="flex-end"` when
    `logScrollOffset === 0` so the latest event's BOTTOM aligns with
    the bottom of the viewport. A tall final entry's overflow then
    clips at the TOP — the user sees the END of the just-produced
    content, which is what they want at the "newest" anchor.
  · Scrolling up (offset > 0) flips back to `flex-start` (top-anchored)
    so reading older content starts from the slice's top edge —
    natural "scrolling back through history" mode.
  · Row-level scrolling within a single tall event is deferred — it
    needs every event role to expose a row-list representation, which
    is a larger refactor tracked separately. Until then, offset=0 +
    flex-end gives both ends of long content via offset-mode switching.

Lint/typecheck cleanup (none change behavior):
  · `import type React` reverted to `import React` (with biome-ignore)
    in `SplitDiff.tsx` and `char-bar.tsx` — JSX in classic-transform
    mode needs React in value scope.
  · `App.tsx` adds `touchedPaths` to handleSubmit's dep array.
  · `WelcomeBanner` drops a stale biome-ignore + uses `letter` as
    React.Fragment key on the wordmark (REASONIX letters are unique
    + array is fixed, so no array-index-key concern).
  · Test teardown for `process.env.HOME` keeps `delete` with a scoped
    biome-ignore — assigning `undefined` would set the literal string.
  · 16 files auto-fixed by `biome check --write` (format + import order).

Tests: 1625/1625 pass. Lint clean. Typecheck clean.
2026-04-28 21:05:51 -07:00
esengine 937b9797aa feat(tui): 0.13.0 redesign — alt-screen layout, sticky chrome, /checkpoint, side-by-side diff (0.13.0)
Breaking: TUI now takes over the alternate screen buffer (\x1b[?1049h),
which means session output is no longer captured in the user's terminal
scrollback after exit. The transcript file (~/.reasonix/sessions/<name>.jsonl)
is the durable record. Trade-off accepted in exchange for a real fixed-
header / scrollable-middle / fixed-footer layout.

Visual:
  · single-row chrome: brand + project crumb + pills (mode, cost, balance, cache)
  · WelcomeBanner: gradient REASONIX wordmark + 5 quick-start cards + live
    web-UI URL when the embedded dashboard is up
  · EventLog: ▎ accent bar on every role; ToolPill / ReasoningBlock /
    StreamingAssistant rebuilt as bracket text with phase verbs and a
    trailing ▌ blinking cursor while streaming
  · PlanStepList: tree-style ┣/┗ rows with status icons + char progress bar
  · ModalCard: full borderStyle="round" + header rule + footer slot;
    every confirm modal (Shell / Plan / Choice / Workspace / Walk / Refine)
    inherits the bordered card
  · /context now renders a 4-color stacked char-bar via a new
    ctx-breakdown DisplayRole

Behavior:
  · /checkpoint <name> + /restore — Cursor-style session-scoped snapshot
    store at ~/.reasonix/sessions/<root>/checkpoints/, replaces the
    rejected auto-commit feature
  · EditConfirm uses side-by-side diff (left old / right new)
  · /mouse [on|off] runtime toggle; mouse tracking OFF by default so
    native shift-drag selection still works
  · Idle ticker gate — when nothing is streaming or busy, the 8Hz/1Hz
    heartbeats pause so terminal text selection survives
  · Dashboard: auto-starts on launch (configurable via --no-dashboard);
    URL surfaces on the WelcomeBanner instead of a chrome pill that was
    unreliable across terminals; concurrent startDashboard() calls now
    de-dupe via an in-flight Promise ref so we don't leak listeners
  · /jobs: 5-col table with port detection from job stdout
  · /status enriched with cost / cache / budget / dashboard rows

New components:
  · SplitDiff.tsx — side-by-side diff renderer with paired cells
  · alt-screen.ts — useAltScreen hook with SIGINT/SIGTERM/exit restore
  · char-bar.tsx — CharBar / StackedCharBar reusable progress bars
  · src/code/checkpoints.ts — snapshot CRUD (15 tests)

Tests: 1625/1625 pass. Build + typecheck clean.
2026-04-28 20:14:06 -07:00
esengine 32cccfaeca feat: reasonix commit — draft commit messages from staged diff (0.12.22)
Reads `git diff --staged`, falls back to working-tree diff (with a
warning + refuses to actually commit when source is working tree),
samples the last 10 commits as a style reference, and asks DeepSeek
v4-flash to draft a message that matches the project's existing
voice. The diff IS the spec; the log is the voice.

UX:
- Print draft inside ─── separators
- [a]ccept / [r]egenerate / [e]dit (in $EDITOR) / [c]ancel prompt
- `-y / --yes` skips the prompt (CI / scripted use)
- Multi-line bodies survive: `git commit -F -` reads the message
  from stdin, no shell quoting concerns
- Pre-commit hook output / git's confirmation are inherited so the
  user sees the same final commit screen they'd see from `git commit`

Safety:
- Fails fast when not in a git repo
- Refuses to commit a working-tree-derived draft (staging area is
  empty so `git commit` would fail anyway) — prints draft for the
  user to copy after `git add`
- Caps diff at 80KB (head + tail with truncation marker) so a giant
  refactor doesn't blow the model's prompt budget; warns the user
  the resulting draft will likely be vague

Default model is v4-flash — drafting a commit message doesn't need
pro. `-m` overrides for cases where flash undercooks the message.
2026-04-28 08:45:37 -07:00
esengine c1288d3a66 feat: reasonix doctor — one-command health check (0.12.21)
When a user reports "Reasonix is broken", the support flow has been:
"check API key, try a chat, look at config.json, check Ollama if you
use semantic, …" — now `reasonix doctor` runs all of that in one go.

8 checks, run in parallel (api-reach has an 8s timeout, the rest are
local + sub-millisecond). Each returns ok / warn / fail; the summary
line counts them. Exit 1 on any fail so CI / install scripts can
fast-fail on misconfiguration; warn → exit 0.

Checks:
- api key       env DEEPSEEK_API_KEY → config.apiKey → fail
- config        ~/.reasonix/config.json present + parseable + key fields
- api reach     /user/balance reachable + balance reported
- tokenizer     data/deepseek-tokenizer.json.gz on disk + readable
- sessions      session count + total bytes + flag stale ≥90d
- hooks         global + project hook count, parse-clean
- ollama        skipped when no semantic index built; otherwise
                binary on PATH + daemon up + embed model pulled
- project       cwd has any of .git / REASONIX.md / package.json / pyproject.toml /
                Cargo.toml / go.mod — heuristic for "is this a project root?"

Plain text output (no Ink) so it works even when Ink can't mount —
the case this command is most useful in. ANSI color when stdout is
TTY, gracefully bare on TERM=dumb / piped.
2026-04-28 08:39:20 -07:00
esengine e0cdb7e7bb feat: session USD budget cap — opt-in soft circuit breaker (0.12.20)
Off by default — Reasonix's cost story is 'cheap by design,' adding a
silent cap at install would just confuse new users.

Opt in via:
- CLI flag: `reasonix chat --budget 5`, same on `code` / `run`
- Slash mid-session: `/budget 5` to set, `/budget off` to clear,
  `/budget` alone to show current spend / cap / percentage
- Config-file equivalent: not added yet; per-session override is the
  primary surface

Loop semantics (src/loop.ts):
- step() opens with a budget gate that runs BEFORE any state mutation,
  so a refusal leaves the loop unchanged — user corrects the cap and
  re-issues the same prompt cleanly.
- spent ≥ cap → yields an `error` event with a clear hint about
  /budget, returns immediately. Turn counter doesn't advance.
- spent crosses 80% of cap (one-shot, sticky via _budgetWarned) →
  yields a `warning` event noting how close the next turn is.
- setBudget(usd|null) is the mutator that resets the sticky flag so a
  user who bumps the cap mid-session sees a fresh threshold message.

UI (src/cli/ui/StatsPanel.tsx):
- One-row `budget  .XXXX / .YY  (Z%)` indicator below the metrics
  block, hidden when `budgetUsd === null`. Color: dim under 80%,
  amber 80-99%, red ≥100%.

Tests: 6 new cases in tests/loop.test.ts covering default off-state,
80% one-shot warn, no-repeat warn, refusal at cap, setBudget(null)
unblocks, setBudget(usd) re-arms warning. 1610 pass.
2026-04-28 08:24:04 -07:00
esengine bf1bb778aa fix: jobs O(N²) ready-detect + web_fetch body byte cap (0.12.19)
jobs.ts:
- ready-signal regex used to test against the FULL job.output buffer
  on every chunk, then ALSO against the chunk. With 9 regexes ×
  growing buffer × per-chunk dispatch, that's quadratic CPU during
  startup of a chatty dev server. Replace with a 1KB sliding window
  for cross-chunk matching — bounded cost regardless of total output.

web.ts:
- webFetch had no upper bound on response body size. `await resp.text()`
  pulls the entire body into memory before applying the 32K char cap;
  pointing the model at a 50MB changelog or a runaway server with no
  Content-Length pegged the heap. Now:
  - 10MB hard cap on raw body bytes
  - pre-flight check against Content-Length when the server provides it
  - streaming reader for chunked / undeclared-length responses, aborts
    cleanly once total bytes cross the cap

Tests: +2 web cases (declared-length refusal, mid-stream cap). 1604 pass.
2026-04-28 07:55:30 -07:00
esengine 0c1d80fec9 fix(hooks): cap stdout/stderr at 256KB so a runaway hook can't OOM the loop (0.12.18)
The default spawner appended every chunk into a JS string with no
upper bound. A buggy or runaway hook (`cat largefile`, infinite
`yes`, etc.) accumulated unbounded into Reasonix's heap until its
timeout fired — 5s for blocking events, 30s for logging hooks, plenty
to push the heap past comfortable limits.

Now:
- per-stream byte cap of 256KB (matches what hooks are actually for —
  short error messages, validator stderr, `git status --short`)
- raw Buffer collection + decode-once-at-close, mirroring shell.ts —
  protects against multi-byte UTF-8 sequences split across chunks
- HookSpawnResult / HookOutcome carry an optional `truncated` flag
- formatHookOutcomeMessage suffixes "(output truncated at 256KB)"
  so users know the loop didn't see the full output

Tests:
- truncation flag propagates from spawner → outcome
- format message surfaces the truncation tag
- existing 26 hook tests all pass unchanged

1602 tests pass (+3).
2026-04-28 07:47:54 -07:00
esengine 9ba7fbdf86 style: biome lint/format follow-up to 0.12.17
CI failed on lint after the 0.12.17 push:
- src/memory.ts: collapse multi-line string concat into one template
  literal (lint/style/useTemplate)
- src/usage.ts, tests/memory.test.ts, tests/session.test.ts: biome
  formatter line-width preferences (auto-fixed via npm run lint:fix)

No behavior change. 1599 tests still pass.
2026-04-28 07:43:17 -07:00
esengine 1e58cf3e4b chore: project-wide cleanup pass — MCP version, async FS walk, GC, prefix audit (0.12.17)
P0 — true bugs:
- mcp/client: clientInfo.version was hardcoded "0.3.0-dev"; now imports
  VERSION so MCP servers see the real client version

P1 — user-facing improvements:
- at-mentions: new listFilesWithStatsAsync — TUI mount no longer blocks
  on hundreds of synchronous statSync calls; picker fills in once the
  async walk completes (typically <200ms)
- usage.jsonl: auto-compaction past 5MB drops records older than 365d
  so heavy users don't accumulate unbounded telemetry on disk
- session: pruneStaleSessions() helper + new /prune-sessions slash
  command; /sessions listing flags entries idle ≥90d
- ImmutablePrefix: fingerprint is now cached + invalidated only by
  addTool. Cuts the per-render JSON.stringify+sha256 cost AND adds
  a verifyFingerprint() drift detector for catching future mutations
  that bypass addTool — Reasonix's prefix-cache hit ratio is the
  central KPI; silent prefix churn was the largest unguarded risk

UX polish:
- streaming row: "(no content)" → "(empty body — likely tool-call only)"

Tests:
- memory: fingerprint cache + dedup behavior + drift detection (5 new)
- at-mentions: listFilesWithStatsAsync mirrors sync contract (5 new)
- usage: compaction triggers past threshold, drops only old records
- session: pruneStaleSessions semantics + cutoff arg
- new tests/event-log-streaming.test.ts: lastLine bounded slicing

Total: 1599 tests pass (+20).
2026-04-28 06:59:40 -07:00
esengine 2dbf8bf723 perf(tui): streaming smoothness pass — 30Hz throttle, tick split, citation cache (0.12.16)
- FLUSH_INTERVAL_MS 100→33ms (≈30Hz) + REASONIX_FLUSH_MS env override
- lastLine bounded to tail*4 chars (was O(N) regex on full streaming buffer)
- phase pill padEnd(8) so WAITING/THINKING/DISPATCH/WRITING transitions
  don't reflow the row
- ticker: split fast(120ms) + slow(1000ms) contexts; useElapsedSeconds /
  UndoBanner countdown / ModeStatusBar jobs poller move to slow tick
- streaming row: drop the ◆/◇ pulse animation, single braille spinner
  carries the liveness signal — one less Text node + one less fast-tick
  subscriber
- citation validateCitation: mtime-keyed lineCount cache (256 LRU) so
  repeated cites of the same file skip readFileSync
2026-04-28 06:32:41 -07:00
esengine c225dad853 chore: rename preset vocabulary fast/smart/max → auto/flash/pro across user-facing surface (0.12.15)
Every user-facing string that still said fast/smart/max now says
auto/flash/pro — the canonical names presets have used since the
autoEscalate split. Touches CLI flag descriptions (chat/run/code),
/help's preset table, /preset's argHint/completer, the slash
handler's usage line.

Old config.json files keep working: resolvePreset still maps
fast → flash·effort=high, smart → auto, max → pro. What changed
is the interactive surface — /preset fast now prints usage instead
of silently doing the right thing, so the in-chat vocabulary
matches what's documented.
2026-04-28 05:55:39 -07:00
esengine a52f8facb4 feat: dashboard mirrors workspace/checkpoint/revision modals + parallel-tool deferral (0.12.14)
Three TUI confirmations the dashboard couldn't see — change_workspace,
plan checkpoints, plan revisions — now mirror to the web modal layer
with the same Switch/Deny/Continue/Revise/Stop/Accept/Reject choices
the terminal exposes.

Loop fix: when DeepSeek emitted change_workspace + write_file in one
parallel batch, the write was firing against the OLD sandbox before
the user could approve the modal — silent data loss into the wrong
project. Subsequent calls in the same batch now get a synthetic
"deferred — re-issue next turn" result; tool_call ↔ tool pairing stays
valid for DeepSeek's next-turn validator. Test in tests/loop.test.ts.

Dashboard polish:
- In-flight row shows the active tool + key args (path / command /
  char count) once tool_start fires, so write_file no longer feels hung.
- ErrorBoundary stops auto-recovering after 3 catches and renders a
  manual "Try again" button — no more silent flickering loop.
- .modal-cmd gets overflow + max-height + word-break so a pathological
  multi-kilobyte command can't push the rest of the panel offscreen.
2026-04-28 05:55:02 -07:00
esengine fed2a515be fix: scroll-up sticks during streaming (0.12.13)
Two stacked bugs let the auto-scroll keep yanking the user back
to bottom on every delta:

1. The "are they scrolled up?" listener attached via
   document.querySelector(".chat-feed") on mount — but the feed
   was conditionally rendered (only after the first message), so
   on a fresh session the listener never attached and the
   shouldAutoScroll flag was never flipped to false.

2. The auto-scroll's own scrollTop = scrollHeight write triggers
   a scroll event, which the listener was treating as a user
   scroll and snapping back to "at bottom".

Fixes:
- .chat-feed always rendered (empty state moved inside) + ref
  attaches the scroll listener on first paint.
- autoScrollInFlight ref gates the listener so only genuine
  user wheel/drag flips the guard.
2026-04-28 04:49:50 -07:00
esengine 067fcc21a4 feat: live semantic_search registration + chat banner (0.12.12)
Two questions from the user:
  - "after index ends, does it auto-register so chat can use it?"
  - "no index → put a dismissible warning at top of Chat?"

Both yes now.

Loop / prefix
- ImmutablePrefix.addTool(spec) appends to a (now-mutable) backing
  array, exposed through a readonly getter. Cost: one cache miss
  on the next turn after a tool's added; cheaper than restart.
- DashboardContext.addToolToPrefix wired from App.tsx.

Server
- runIndex on success: registerSemanticSearchTool + addToolToPrefix
- /api/overview returns semanticIndexExists (cheap stat)

Dashboard
- Top-of-Chat banner when no index, with "Build it →" (navigates
  to Semantic tab via appBus) + dismiss × (persists in localStorage)
2026-04-28 04:45:54 -07:00
esengine 957fc34c9b feat: Semantic panel guides users through missing Ollama (0.12.11)
Previously the panel just said "not reachable" with a copy-paste
command list. Now it distinguishes the three failure modes and
offers a one-click action for the two that we can resolve:

- binary missing  → Install Ollama card (macOS / Windows / Linux)
- daemon down     → "Start daemon" button (ollama serve, detached)
- model missing   → "Pull <model>" button with live progress
- all ready       → Index buttons enable

Server adds:
- GET /api/semantic returns the full checkOllamaStatus shape
- POST /api/semantic/ollama/start
- POST /api/semantic/ollama/pull (fire-and-forget; PULLS map
  carries status + last log line; SPA polls /api/semantic)
2026-04-28 04:34:06 -07:00
esengine e0e7bb91f2 feat: in-flight row at the bottom + live char counters (0.12.10)
The "turn in flight" row used to sit at the top of the chat panel,
far from the user's eyes (which are at the input). Move it to a
proper InFlightRow above the ChatStatusBar, and fill it with the
live signals the TUI showed but the web didn't:

  ⠋ thinking · 2.3s · reasoning 1,204 ch · out 0 ch · [Abort]

- Phase: thinking / streaming / waiting based on which streaming
  channel is growing
- Elapsed seconds tick every 500ms so motion is visible even
  through long deltas
- Character counts derived from the existing `streaming` state
2026-04-28 04:27:11 -07:00
esengine efd6d64176 feat: dashboard Semantic panel — index in background with live progress (0.12.9)
Previously building the index meant exiting the TUI to run
`reasonix index`. Now the dashboard has a Semantic tab that
kicks off `buildIndex` in-process and streams progress to the
SPA so users can keep coding while it runs.

Server
- src/server/api/semantic.ts — GET status / POST start / POST stop
- Per-root JobRecord captures BuildProgress via onProgress
- Wired into the /api router

Dashboard
- New Semantic sidebar tab; polls every 1.2s while running
- Shows Ollama reachability, index existence, live phase + counters
  + percentage bar + elapsed time
- Index / Rebuild / Stop buttons with appropriate disabled states
- Standalone (non-attached) dashboards explain why the panel is empty
2026-04-28 04:16:01 -07:00
esengine 44f309509e fix: split dashboard URL onto its own row (0.12.8)
0.12.7 put the URL + description on the same Ink row. On terminals
that hide the OSC 8 escape, Ink miscounts the escape bytes as visible
width — the description wrapped right through the middle of the URL.

Two stacked rows now:

  ◇ web   open the dashboard in a browser (chat · files · stats · settings)
          http://127.0.0.1:NNNN/?token=...

The URL is the only content on its line, so even a bad width
measurement can't collide with anything.
2026-04-28 04:08:18 -07:00
esengine 546e587a1e feat: auto-start dashboard + URL row in status panel (0.12.7)
Most users never discovered /dashboard existed. Now the URL is in the
status panel from the first turn, on its own row with a description.

- App auto-calls startDashboard() on mount; --no-dashboard opts out
- StatsPanel renders a dedicated row:
    ◇ web   http://127.0.0.1:NNNN/?token=...   open the dashboard
    in a browser (chat · files · stats · settings)
- URL wrapped in an OSC 8 hyperlink — clickable in iTerm2 / WezTerm /
  Windows Terminal / VS Code / recent gnome-terminal; copy-pasteable
  in older ones
- noDashboard prop threaded through App + chatCommand + codeCommand
2026-04-28 04:04:31 -07:00
esengine d58861e0d6 docs: refresh README + dynamic version on landing site
Site
- Hero badge + term-anim header now read the live npm version. i18n.js
  fetches https://registry.npmjs.org/reasonix/latest on init, caches
  it in localStorage, exposes Reasonix.version() / onVersionChange().
- term-anim subscribes and patches the .tw-ver pill in place when the
  fetch resolves, so we don't have to rerun the whole animation.
- Hardcoded "v0.6" / "v0.6.0" replaced with a {version} token in the
  translation strings; only fallback constant left to bump on major
  cuts (and the npm fetch overrides it on every visit).

README (en + zh)
- New Web dashboard section right after Quick start (0.12 headline).
- /preset and --preset references switched from the dropped legacy
  fast/smart/max vocabulary to the current auto/flash/pro.
- Stale `Reasonix v0.5.21 · ...` example refreshed to the 0.12-era
  panel header.
2026-04-28 03:52:54 -07:00
esengine c9369d7532 chore: add .gitattributes to force LF (unblocks publish on Windows)
Without this, a Windows checkout with autocrlf=true lands the working
tree with CRLF even though the repo stores LF. Biome rejects CRLF, so
prepublishOnly's `npm run lint` step fails on tests/resolve.test.ts.
Pinning eol=lf for all text files makes the working copy match what
Biome expects and what the repo stores, on every platform.
2026-04-28 03:38:19 -07:00
esengine 78e6df6a4d feat: editor polish + CI fixes + storm breaker via registry (0.12.6)
Editor
- Side-by-side diff in the edit-pending-review modal (red/green tint,
  hljs syntax highlighting, paired LCS rows). Modal payload gained
  `search`/`replace` fields (the truncated `preview` stays for old
  clients).
- Local CodeMirror bundle (`dashboard/codemirror.js`, ~937 KB) via
  scripts/bundle-codemirror.mjs — replaces 21 esm.sh imports. Server
  serves it through `serveAsset`.
- Markdown view modes: Edit / Split / Preview segmented control;
  separate Marked instance for preview so chat-renderer customizations
  don't run on user files.
- Sidebar collapses to icons (52px), persisted in localStorage.

CI / regression fixes
- Restore legacy preset migration (fast → flash+high, smart → auto,
  max → pro) so `tests/resolve.test.ts` passes again.
- Storm breaker no longer hardcodes a mutating-tools list. It accepts
  an `isMutating` predicate; `loop.ts` wires it from the existing
  ToolRegistry `readOnly` / `readOnlyCheck` flags. Buffer entries are
  tagged read-only vs mutating: a mutating call drops prior reads
  (read→edit→verify cycles no longer trip), but identical mutator
  calls still suppress on the threshold.

1571/1571 tests pass.
2026-04-28 03:26:53 -07:00
esengine 9f88f3b330 fix: highlighting + md preview (0.12.4)
- Pin @lezer/highlight and @lezer/common in esm.sh ?deps= so all
  CodeMirror packages share one copy. Previously each pack pulled
  its own, so highlight tags compared by identity stopped matching
  and oneDark silently produced no colors.
- Add markdown preview button (Edit/Preview toggle, only on .md tabs)
- Use a separate Marked instance for the preview so chat-specific
  diff/SEARCH-REPLACE code handling doesn't run on user files
2026-04-28 02:58:10 -07:00
esengine 72326254b6 feat: editor as a sidebar tab (0.12.3)
- New Editor tab in the sidebar, mounts full-width inside .main
- main-editor modifier strips panel padding so editor fills viewport
- Drawer entry still works for "click path in chat" deep-link
2026-04-28 02:45:20 -07:00
esengine baece15b65 feat: editor polish — top tabs, highlight, gutter, autocomplete (0.12.2)
- Tabs lifted out of editor-main into a full-width bar (VS Code style)
- oneDark + defaultHighlightStyle reorder so colors actually show
- Gutter restyled (dark bg, dim numbers, active-line highlight)
- foldGutter + highlightActiveLineGutter added
- autocompletion(activateOnTyping: true) + completionKeymap
- Autocomplete popup styled to dark theme
2026-04-28 02:43:11 -07:00
esengine fe9ad209eb feat: editor v2 — file tree + collapsible side (0.12.1)
- Recursive folder tree replaces flat path list (folders first, alpha)
- Collapsible side panel (◀ to hide, ▶ to restore)
- Drawer width 50% → 65% (min 360 → 420)
- Filter mode keeps the flat path list
2026-04-28 02:37:11 -07:00
esengine be7daa017c feat: web dashboard + auto/flash/pro preset rework (0.12.0)
Web dashboard at /dashboard slash — 12 panels, modal mirroring back to
the live TUI, bidirectional chat. 127.0.0.1 only, ephemeral token,
CSRF on every mutation. Preact + HTM SPA, no build step. Drawer-style
CodeMirror editor (click any path in chat tool cards).

- src/server/ — HTTP server, 16 endpoints, SSE event stream
- dashboard/ — embedded SPA (3 files, ~1600 LOC)
- src/cli/ui/slash/handlers/dashboard.ts — /dashboard slash entry
- src/cli/ui/App.tsx — broadcast hooks for events / modals / stats

Preset semantics rework: auto / flash / pro replaces fast / smart / max.
- auto: flash baseline + auto-escalate (current behavior, default)
- flash: lock to flash, no escalation
- pro: lock to pro, no downgrade
- loop.autoEscalate flag gates NEEDS_PRO marker + failure-threshold paths
- applyPresetLive callback flips loop.model + autoEscalate live (no
  session restart needed — closes the "switched to max but still on
  flash" gap the user reported)

Other:
- cacheSavingsUsd telemetry helper + UsageBucket field, surfaced in
  /stats dashboard + web Usage chart
- BUILTIN_ALLOWLIST exported, removeProjectShellAllowed +
  clearProjectShellAllowed in src/config.ts (powers Permissions panel)
- marked v12 renderer hardened (token-vs-positional + null text coerce)
- CodeMirror multi-instance bug fixed via esm.sh ?deps= pinning

1568 tests pass. Lint / typecheck / build clean.
2026-04-28 02:29:39 -07:00
esengine c594ad71f7 feat: /permissions slash + MCP Streamable HTTP transport
- /permissions list/add/remove/clear — per-project shell allowlist
  audit + edit from inside the TUI; surfaces edit-mode banner
  (yolo bypasses allowlist), refuses to clobber the read-only
  builtin list, alias /perms.
- removeProjectShellAllowed + clearProjectShellAllowed in config.ts
  for the slash to call (literal-only match, scoped per project).
- StreamableHttpTransport (MCP 2025-03-26): single endpoint, handles
  202 / application/json / text/event-stream responses, captures
  Mcp-Session-Id and echoes on subsequent POSTs, surfaces session
  expiry as a clear error.
- Spec parser: streamable+http(s):// prefix routes to the new
  transport; plain http(s):// stays SSE for back-compat. Wired
  through chat / run / mcp inspect.

1521 tests pass (+24). Lint / typecheck / build clean.
2026-04-27 22:02:18 -07:00
esengine 23c81e6f11 chore(release): 0.11.2
Split /init into its own patch release. /init landed after the
0.11.1 commit, and it's a small but distinct addition (no fix /
no behavioral change to existing flows), so a separate version
makes the changelog story cleaner: 0.11.1 is the workspace-switching
release, 0.11.2 is the project-init release.
2026-04-27 07:23:48 -07:00
esengine 0d0cdfc54a docs: fold /init into 0.11.1 changelog, restore missing 0.11.0 header
Two CHANGELOG fixes ahead of publishing 0.11.1:

1. Add a bullet for /init under 0.11.1 Added. /init was committed
   after the 0.11.1 version bump but before publication, so the
   shipped 0.11.1 actually includes it. Update the headline to
   acknowledge the addition.

2. Restore the '## [0.11.0] — 2026-04-27' header that was clobbered
   when the 0.11.1 entry was inserted earlier — the 0.11.0 content
   was orphaned without a heading.
2026-04-27 07:20:11 -07:00
esengine 60c598527d feat: /init — model-driven REASONIX.md generator
New slash command that asks the model to scan the project and write a
concise REASONIX.md baseline, removing the friction of having to
hand-author one. The file is auto-pinned into the system prompt every
launch, so a good baseline pays back on every subsequent turn.

Mechanism: handler emits a structured user-turn prompt via `resubmit`
that hard-constrains the model to a fact-only document with sections
for Stack / Layout / Commands / Conventions / Watch out for. The
"output ≤ 80 lines / 3KB" cap and "STOP after writing" line are
load-bearing — without the cap REASONIX.md would burn cache budget
every turn; without STOP flash chains follow-up suggestions and
wastes tokens.

Reuses existing filesystem tools (read_file / directory_tree /
edit_file / write_file) — no new tool, no new pipeline. The
generated content lands as a pending edit in the normal review queue,
so the user audits it via /apply before disk writes.

Edge cases:
- Outside code mode: handler returns "/init only works in code mode"
  with the `reasonix code` invocation hint.
- REASONIX.md already exists: refused, points at `/init force` to
  regenerate. Force matching is case-insensitive.

Five tests covering: refuse outside code mode, fresh-init resubmit
shape (verifies length cap + STOP marker survive future tightenings),
existing-file refusal, force override, force case-insensitivity.

1487 tests passing.
2026-04-27 06:55:20 -07:00
esengine 494c62ef60 docs: rebuild Claude-Code-on-DeepSeek section around cache_control
DeepSeek now ships an official Anthropic-compatible endpoint at
api.deepseek.com/anthropic, so the previous 'Claude Code can't run
DeepSeek' framing is factually wrong: Claude Code talks to it
unmodified.

The defense moves from 'protocol incompatible' to 'cache mechanic
incompatible':

- Anthropic native cache is marker-based: cache_control on a message
  caches up-to-this-marker as a content-addressed unit. Claude Code's
  loop is designed around this — markers compensate for an otherwise
  non-stable prefix.
- DeepSeek's auto-cache is byte-stable: it fingerprints the literal
  byte stream from 0. No markers.
- DeepSeek's compat endpoint IGNORES cache_control. Claude Code's
  main caching strategy disappears; auto-cache misses because the
  prefix wasn't byte-stable to begin with.

Reasonix's loop was designed around byte-stable prefix from line one
(append-only invariant). That's why 94.4% on the same workload
where a cache-hostile baseline lands at 46.6%.

Restructure the section into two subheaders:
- 'But DeepSeek now has an Anthropic-compatible API...' — handles
  the Claude Code case head-on with DeepSeek's compat table and the
  marker-vs-byte-stable contrast
- 'What about Aider / Cline / Continue?' — handles the natively-
  DeepSeek tools, keeps the existing 5-row DeepSeek-specific quirks
  table (R1 thinking leak, schema flatten, repair, effort, tail-only
  compaction)

Mirror everything in README.zh-CN.md.
2026-04-27 06:37:15 -07:00
esengine c43ada74e2 docs: handle 'just point Claude Code / Aider at DeepSeek' objection
The 'Why Reasonix?' section explained why we beat generic competitors,
but didn't cover the sharper rebuttal: 'I'll just point Claude Code
(or Aider, Cline, Continue) at DeepSeek and get the same economics
without your tool.' Without an answer prospects bounce silently.

Add a third subsection to 'Why Reasonix?' that handles it head-on:

- Claude Code: not really. It's hard-bound to Anthropic's API —
  auth, tool-schema shape, <thinking> parsing all assume Claude.
  A translation proxy (claude-code-router) gets you protocol
  compatibility but every Anthropic-tuning becomes overhead and
  every DeepSeek-tuning is unreachable.
- Aider / Cline / Continue: yes, they support DeepSeek and you get
  the cheap token price. What you don't get is the DeepSeek-
  specific loop work, captured in a 6-row table contrasting how
  each layer (cache markers, reasoning blocks, tool schemas,
  malformed JSON, reasoning-effort, compaction) differs between
  Anthropic/OpenAI assumptions and DeepSeek reality, with what
  Reasonix does about each.

Then drive the cache-stability claim home with concrete numbers:
generic harnesses land at 40-60% cache hit on DeepSeek vs 94.4% for
Reasonix on the same workload, which at DeepSeek's pricing is ~2.5×
on input cost alone.

Mirror in README.zh-CN.md.
2026-04-27 06:22:26 -07:00
esengine 18b8d0d8df docs: add 'Why Reasonix?' positioning section to README
The README read like a feature manual — "here's everything we have"
without ever telling a new visitor why they'd pick Reasonix over
Cursor / Claude Code / Cline / Aider. Most prospects bounce because
the unique value (DeepSeek's price × cache-first prefix engineering)
isn't visible above the fold.

Insert a "Why Reasonix?" section between Quick start and the code-
mode walkthrough, with three pieces:

1. Three short pitches: cost economics that actually land in your
   bill (~30× cheaper than Claude Sonnet, with 94% live cache hit
   verified in benchmarks/), terminal-native (no Electron / IDE
   plugin), MIT-licensed and hackable end-to-end.
2. A side-by-side comparison table — Reasonix vs the four
   alternatives, on backend / cost / runtime / license /
   cache-hit / MCP / plan mode / skills / edit review / workspace
   switch / cost dashboard / sandbox enforcement.
3. An honest "Pick something else when" section pointing at Aider,
   Cline, Cursor, and Claude Code's IDE mode for the cases where
   Reasonix's tradeoffs don't fit (multi-provider, IDE integration,
   PhD-level reasoning benchmarks, fully-local).

Also tighten the subtitle under # Reasonix to lead with the cost
angle instead of "no LangChain" (audience-correct, but doesn't
help conversion). Mirror everything in README.zh-CN.md. Bump the
test-count claim in Development from 1007 to 1482.
2026-04-27 04:37:38 -07:00
esengine 855b91c7ed feat: workspace switching (/cwd + change_workspace) + 4 fixes
Add two ways to pivot to another project mid-session:
- /cwd <path> — user-typed slash; validates target, applies via
  applyCwdChange (re-registers filesystem/shell/memory tools,
  reloads hooks, syncs loop.hookCwd, re-registers run_skill).
  MCP servers stay on the launch root (no reconnect handshake).
- change_workspace tool — model-callable, gated on a
  WorkspaceConfirm modal. Tool fn always throws
  WorkspaceConfirmationError; App detects the marker, mounts
  Switch/Deny modal; approval drives the same applyCwdChange path.
  No always-allow option — switches are per-target.

Fixes that surfaced from real-use workspace-switching attempts:
- loop: reset _turnAbort after Esc-abort branch returns. Prior
  carry-abort logic re-aborted at iter 0 on every subsequent
  step(), poisoning the session until restart.
- shell: collect Buffer chunks instead of decoding per-chunk;
  smartDecodeOutput tries strict UTF-8, falls back to GB18030 on
  Windows when invalid sequences detected. Fixes mojibake on
  Chinese-Windows cmd.exe error messages (chcp 65001 doesn't
  cover them — they come from a localized resource DLL).
- markdown: gate stripMath pipeline on a math-marker pre-check.
  The catch-all \[a-zA-Z]+ → "" had been wiping \TEST out of
  Windows paths like F:\TEST1, rendering them as F:1.
- prompt: tell the model to call change_workspace (or surface
  /cwd) when the user asks to change projects, instead of
  fumbling with cd /d / pushd / 2>&1 shell hacks.

Bump 0.11.0 → 0.11.1, CHANGELOG entry covers all four fixes plus
the two new entry points. 1482 tests passing.
2026-04-27 04:29:31 -07:00
esengine efcab7d141 chore(release): 0.11.0 2026-04-26 21:02:32 -07:00
esengine ca1406d864 feat: local semantic_search index + Ollama launcher + i18n; fix subagent abort races
Pillar 1 — semantic search (opt-in, local):
- src/index/semantic/{embedding,chunker,store,builder,tool,preflight,
  ollama-launcher,i18n}.ts — Ollama-backed local embedding index for
  the project. Cosine search over Float32 JSONL store, mtime-based
  incremental rebuild, fault-tolerant per-chunk embedding so a single
  oversized file doesn't kill the whole build.
- New CLI: `reasonix index [--rebuild --model --ollama-url --yes]`
  with TTY-aware Braille spinner + elapsed-time + phase labels (no
  more "stuck on building…"). Non-TTY path still emits one line per
  phase for CI logs.
- Preflight checks Ollama binary / daemon / model and prompts (or
  --yes auto) to fix what's missing. All user-facing strings route
  through src/index/semantic/i18n.ts (zh/en, system-locale auto-detect
  via REASONIX_LANG → LANG/LC_ALL → Intl.DateTimeFormat).
- `/semantic` slash inside reasonix code shows status + how to enable.
  No startup auto-prompt — opt-in via the explicit shell command,
  same pattern /setup and /update use.
- semantic_search tool registers only when an index exists.
- code-mode system prompt gets a routing fragment when the tool is
  registered, telling the model to prefer semantic_search for
  descriptive queries and fall back to grep for exact tokens.

Pillar 2 — fix subagent Esc race:
- DOM addEventListener("abort", …) doesn't fire for already-aborted
  signals. If the parent aborted before the listener attached, the
  child ran free until iter budget. Sync-check .aborted at attach.
- loop.ts step() reassigning _turnAbort lost prior aborted state.
  Forward the carry-over so abort() called before step() runs still
  kills it at iter 0.
- subagent treated forcedSummary assistant_final events as success,
  so /skill claimed an aborted run finished normally. Now surfaces
  forcedSummary as an error → success: false.

Tests (+27): chunker (incl. window-split + hard-truncate-overlong-line),
store roundtrip, embedAll null-slot fault tolerance, i18n locale
detection + EN/ZH dicts, /semantic slash status renderer, bootstrap
contract (no startup prompt), prompt routing fragment, and a regression
test for subagent already-aborted signal handling.
2026-04-26 20:56:53 -07:00
esengine 477e710ad6 docs: bilingual landing site + Chinese README
- docs/ landing page for GitHub Pages with i18n auto-switch (en/zh
  via navigator.language → localStorage), terminal-themed dark UI,
  hero animation that mirrors the real TUI rendering primitives
  (◇/◆ role glyphs, yellow tool pills, rounded cyan EditBlockRow
  with - red / + green diff lines, info-row pending/applied status)
- README.zh-CN.md mirroring the English README structure
- Language switcher header on README.md → zh-CN + website
2026-04-26 18:47:25 -07:00
esengine 30ee7cd818 feat: /loop interval auto-resubmit + /walk per-block edit walkthrough
- /loop <interval> <prompt> repeats the prompt every <interval> (5s..6h
  bounds, fractional + s/m/h units). One active loop per session — re-
  issuing replaces it. Cancellation: /loop stop, Esc, /clear, /new, exit,
  any user-typed prompt (loop-fired submits set a ref-flag so the timer's
  own re-submit doesn't self-cancel). LoopStatusRow ticks the countdown
  every second under the modeline. Skips a tick (re-arm in 1s) when busy
  rather than queueing duplicate submits.
- /walk steps through the pending-edits queue one block at a time using
  the existing EditConfirm modal (per-block scrollable diff). y apply ·
  n reject · a apply rest · A flip AUTO · Esc cancels (keeps remaining
  queued). Each pick mutates pendingEdits via the existing /apply [N]
  partial-apply path, then advances to the new "first" block.
2026-04-26 08:57:59 -07:00
esengine 72eb3a2a39 feat: more codex/cc/cursor parity — security-review, /test, #g, @url, yolo mode
- `/security-review` and `/test` ship as new built-in skills. Security-review
  is a subagent (read-only, severity-tagged); /test is INLINE (parent must
  see proposed edits) and runs npm/pnpm/yarn/pytest/go/cargo, fixes failures,
  re-runs, stops after 2 failed attempts on the same line.
- `#g <note>` writes to ~/.reasonix/REASONIX.md (global, never committed),
  symmetric to the existing project `#note`. New applyGlobalReasonixMemory
  loader pins the file into every session's prefix. `\#g foo` escape lets
  users send "#g foo" verbatim to the model.
- `@https://...` URL mentions: fetch via existing webFetch (HTML strip,
  truncate to fit), inject under [Referenced URLs]. In-memory per-session
  cache so the same URL twice fetches once. Trailing-punctuation strip
  preserves query strings while peeling off sentence dots and unmatched
  brackets.
- YOLO edit-mode (third stop on the Shift+Tab cycle): apply edits AND
  auto-approve every shell command. Wired via a getter on registerShellTools'
  allowAll so flipping the mode mid-session takes effect on the next dispatch
  with no re-registration. Red modeline pill warns the user it's hot.
2026-04-26 08:44:15 -07:00
esengine 8780dae388 chore(release): 0.8.0 2026-04-26 08:11:56 -07:00
esengine c9f3e733fa feat: codex/claudecode/cursor catch-up — #memory, -c, /review, per-hunk /apply
- `#note` prompt prefix appends a one-liner to <root>/REASONIX.md (auto-creates
  with header). `\#literal` escape passes a real `#text` to the model; `##`
  headings always pass through.
- `reasonix -c` / `reasonix chat -c` resume the most-recently-touched session
  without the picker. Falls back gracefully + warns when no sessions exist.
  Helper extracted to src/cli/resolve.ts so the lookup is testable without fs.
- Built-in `review` skill (subagent runAs) — reviews current branch diff,
  reports verdict + per-issue file:line citations, read-only contract.
- `/apply 1` / `/apply 1,3` / `/apply 1-4` (and `/discard` likewise) — pending
  preview labels each block `[N]` when 2+ are pending; partial apply leaves
  the rest in the queue. Pure parseEditIndices + partitionEdits helpers.
2026-04-26 08:11:45 -07:00
esengine bf9bed64e8 fix(ui): drop startup viewport clear too — VSCode wheel scroll dies on \x1b[2J
User confirmed wheel-up still doesn't scroll in VSCode integrated
terminal even after 0.7.11 dropped the resize listener and the
\x1b[3J scrollback erase. The startup \x1b[2J was the remaining
suspect: xterm.js (VSCode's terminal) implements 2J in a way that
appears to disrupt scrollback anchoring even when scrollback bytes
themselves are preserved.

Fix: don't write any clear escapes at all. Mount Ink directly. The
user's previous shell prompt stays visible above the launch point
and wheel-up scrolls naturally. Trade-off: the launch isn't a
'clean canvas' anymore. /clear inside the TUI still works for an
explicit reset.

This stacks on 0.7.10's Ctrl+P/N history-recall binding and 0.7.11's
resize-listener removal. Together: wheel scroll works, history
recall doesn't get clobbered by wheel-as-arrow events, and chat
history survives terminal resize.
2026-04-26 02:23:04 -07:00
esengine 02fcadf9e8 fix(ui): stop erasing scrollback on resize / startup so VSCode wheel-scroll works
User reported on VSCode integrated terminal: resizing the window
loses chat history and mouse wheel can no longer scroll up. Two
related symptoms, one cause:

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

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

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

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

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

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

Reverted to main-screen mode:

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

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

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

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

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

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

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

Real fix:

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

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

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

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

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

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

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

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

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

Fix:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Tests 1264 → 1267, lint + typecheck + build clean.
2026-04-25 08:00:30 -07:00
esengine 70e0ad1aba fix(replay): align multi-line user msg under the prefix in RecordView
Same fix as EventLog ate earlier. RecordView is the read-only viewer
shared by reasonix replay and reasonix diff — multi-line transcripts
were wrapping under col 0 instead of under the body text. Continuation
indent of 6 spaces matches the 'you › ' prefix width.
2026-04-25 06:44:11 -07:00
esengine 1de2349350 fix(ui): tool-summary suffix-match bridges MCP-prefixed names
LiveRows.tsx already used `name === s || name.endsWith("_" + s)` so MCP
tools like `filesystem_read_file` picked up the same per-tool argument
summary as the bare local `read_file`. tool-summary.ts used exact-name
match only, so bridged tools fell through to the generic "first line +
size hint" path in the compact scrollback row. Switch to the same
suffix predicate; add a write_file branch while there. +3 tests
covering the bridged path + a non-underscore-prefix non-match.
2026-04-25 06:21:57 -07:00
esengine 98f19d1d47 chore(ui): unify keybinding hints in Wizard + SessionPicker
Bracket-style `[↑↓] navigate · [Enter] X · [Esc] Y` matches the Confirm
modals; Wizard and SessionPicker were the last surfaces using the older
free-form `↑/↓ move · enter X · esc Y` style. Doc-comment examples in
Select.tsx updated to match.
2026-04-25 06:18:19 -07:00
esengine d6bb4054dc feat(ui): polish pickers, narrow-term reflow, multi-line indent
- ShellConfirm border yellow→red (highest-risk gate distinct from review)
- EditConfirm border cyan→yellow (decouple from PlanConfirm cyan)
- PromptInput: extract [Esc]-to-stop into separate dim row; narrow mode
  (≤90 cols) condenses prefix `you ›`→`›` with proportional indent
- EventLog: user/warning/error multi-line text now aligns under glyph
  via indentContinuationLines helper
- Slash/At/SlashArg suggestion overlays: marginTop separates from scrollback
2026-04-25 06:15:33 -07:00
esengine 9e3c62ed1e chore(release): 0.7.1 2026-04-25 04:47:34 -07:00
esengine ee274035c6 fix(loop,prompt): storm recovery, PYTHONUTF8, recency rule
Three runtime fixes that all surfaced from a single user trace
(model looped on a broken read_file, the chat ended without
explanation, embedded GBK encoding errors, plus a separate
"PDF report on global economy" turn that wrote a 2024 report
from training memory instead of searching).

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

New rendering: one line per tool call.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Two fixes, defense in depth:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Two changes shift us from reactive to preventive:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

tests: 1055 passing (+17 new)
2026-04-24 02:17:34 -07:00
301 changed files with 54184 additions and 7599 deletions

No files matched your search

+11
View File
@@ -0,0 +1,11 @@
# Force LF line endings on every checkout, regardless of platform.
# Biome's formatter is strict about CRLF — without this, a Windows clone
# with autocrlf=true will land with CRLF in the working tree even though
# the repo stores LF, and `npm run lint` (and prepublishOnly with it)
# fails. See docs/style.md if you ever add binary types here.
* text=auto eol=lf
# Lockfiles + the codemirror bundle are generated; treat them as
# auto-detected text but never coerce.
package-lock.json text eol=lf
dashboard/codemirror.js text eol=lf
+9
View File
@@ -24,3 +24,12 @@ sessions/
.turbo/
# Local-only Claude Code settings — personal overrides, never committed.
.claude/settings.local.json
# Per-user Reasonix state under .reasonix/ — committable team-level
# files (settings.json, skills/) stay tracked, but the user-private
# bits (semantic index, sessions, opt-out markers) never should.
.reasonix/semantic/
.reasonix/sessions/
.reasonix/semantic-skip
# Scratch entry regenerated each time scripts/bundle-codemirror.mjs runs.
scripts/.cm-entry.mjs
+1250
View File
File diff suppressed because it is too large. Load diff
+170 -11
View File
@@ -6,6 +6,10 @@
<em>Cache-first agent loop for DeepSeek V4 (flash + pro) — Ink TUI, MCP first-class, no LangChain.</em>
</p>
<p align="center">
<strong>English</strong> · <a href="./README.zh-CN.md">简体中文</a> · <a href="https://esengine.github.io/reasonix/">Website</a>
</p>
# Reasonix
[![npm version](https://img.shields.io/npm/v/reasonix.svg)](https://www.npmjs.com/package/reasonix)
@@ -14,9 +18,10 @@
[![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 agent in your terminal.** Edits files as
reviewable SEARCH/REPLACE blocks. Ink TUI. MCP first-class. No
LangChain.
**A DeepSeek-native AI coding agent in your terminal.** ~30× cheaper
per task than Claude Code, with a cache-first loop engineered for
DeepSeek's pricing model. Edits as reviewable SEARCH/REPLACE blocks.
MIT-licensed. No IDE lock-in. MCP first-class.
---
@@ -67,6 +72,159 @@ command list.
---
## Web dashboard *(new in 0.12)*
Type `/dashboard` inside any session and Reasonix prints a localhost
URL with a one-time token. Open it for a 13-tab control surface that
mirrors the running TUI — chat (with live streaming), the editor (file
tree + CodeMirror, syntax highlighting + autocomplete + side-by-side
diff for pending edits), Usage / Sessions / Plans / Tools /
Permissions / System / MCP / Skills / Memory / Hooks / Settings.
```
reasonix code › /dashboard
▸ http://127.0.0.1:54219/?token=… (open in browser)
```
127.0.0.1 only, ephemeral token expires when the session ends, every
mutation is CSRF-checked. The TUI keeps working — modals (shell
confirms, plan reviews, edit gates) mirror to whichever surface you
look at first. No build step, no Electron, no separate process to
keep alive.
---
## Why Reasonix? (vs Cursor / Claude Code / Cline / Aider)
Three things you'd come to Reasonix for, that nothing else combines:
- **The cost economics actually land in your bill.** DeepSeek V4 is
~30× cheaper than Claude Sonnet per token. Cheaper tokens alone
isn't the win — *cheap tokens with a 90%+ prefix-cache hit* is.
Reasonix's loop is engineered around append-only prompt growth so
the cache-stable prefix survives every tool call, which the
benchmarks section below verifies end-to-end (94.4% live, vs 46.6%
for a generic harness against the same workload). The `/stats`
panel tracks "vs Claude Sonnet 4.6" savings every turn so you can
watch your bill not happen.
- **It lives in your terminal.** Pure CLI — no Electron, no VS Code
extension, no IDE plugin to wedge into your editor. Sits next to
git, tmux, and your shell history. macOS / Linux / Windows
(PowerShell, Git Bash, Windows Terminal all tested). The only
network call is to the DeepSeek API itself; no vendor server in
the middle.
- **Open source and hackable, end to end.** MIT-licensed TypeScript.
The entire loop, tool registry, cache-stable prefix, TUI, MCP
bridge — all in `src/` under 30k lines. Fork it, ship a private
build, drop it into CI. No SaaS layer, no enterprise tier, no
feature gates.
| | Reasonix | Claude Code | Cursor | Cline | Aider |
|---|---|---|---|---|---|
| Backend | DeepSeek V4 only | Anthropic only | OpenAI / Anthropic | any (OpenRouter) | any (OpenRouter) |
| Cost / typical task | **~$0.001–$0.005** | ~$0.05–$0.50 | $20/mo + usage | varies | varies |
| Where it runs | terminal | terminal + IDE | IDE (Electron) | VS Code only | terminal |
| License | **MIT** | closed | closed | Apache 2 | Apache 2 |
| Cache-first prefix loop | **engineered (94% hit)** | basic | n/a | n/a | basic |
| MCP servers | **first-class** | first-class | — | beta | — |
| Plan mode (read-only audit gate) | **yes** | yes | — | yes | — |
| User-authored skills | **yes** | yes | — | — | — |
| Edit review (no auto-write) | **yes** (`/apply`) | yes | partial | yes | yes |
| Workspace switch (`/cwd`, `change_workspace`) | **yes** | — | n/a (per-window) | — | — |
| Cross-session cost dashboard | **yes** (`/stats`) | — | — | — | — |
| Sandbox boundary enforcement | **strict** (refuses `..` escape) | yes | partial | yes | partial |
### Pick something else when
- **You want multi-provider flexibility** (mix Claude / GPT / Gemini /
local Llama in one tool). Try [Aider](https://aider.chat) or
[Cline](https://cline.bot). Reasonix is DeepSeek-only on purpose —
every layer (cache-first loop, R1 harvesting, JSON-mode tool repair,
reasoning-effort cap) is tuned against DeepSeek-specific behavior
and economics. Coupling to one backend is the feature, not a
limitation we'll grow out of.
- **You want IDE integration** (inline diff in your gutter,
multi-cursor, ghost text, refactor previews). Try
[Cursor](https://cursor.com) or Claude Code's IDE mode. Reasonix
is terminal-first; the diff lives in `git diff`, the file tree
lives in `ls`, the chat lives in your shell.
- **You're chasing the hardest reasoning benchmarks.** Claude Opus
4.6 still wins some leaderboards. DeepSeek V4-pro is competitive
on most coding tasks but doesn't lead every benchmark. If your
task is "solve this PhD-level proof" rather than "fix this auth
bug," start with Claude.
- **You need fully-local / fully-free**. DeepSeek's API has free
credit on signup, but isn't free forever. For air-gapped or
always-free, look at Aider + Ollama or [Continue](https://continue.dev).
### "But DeepSeek now has an Anthropic-compatible API — can't I just point Claude Code at it?"
You can. DeepSeek ships an official Anthropic-compatible endpoint at
`https://api.deepseek.com/anthropic`, and Claude Code (or any Anthropic
SDK client) talks to it without modification. The protocol works. The
**caching economics** don't transfer, and that's the whole point.
Look at DeepSeek's [own compatibility table](https://api-docs.deepseek.com/guides/anthropic_api):
| Field | Status on DeepSeek's compat endpoint |
|---|---|
| `cache_control` markers | **Ignored** |
| `mcp_servers` (API-level) | Ignored |
| `thinking.budget_tokens` | Ignored |
| Images / documents / citations | Not supported |
`cache_control: Ignored` is the load-bearing line. Two completely
different cache mechanics are colliding here:
| | Anthropic native | DeepSeek auto-cache |
|---|---|---|
| Model | **Marker-based.** You put `cache_control` on a message; Anthropic caches "everything up to this marker" as a content-addressed unit. Multiple markers = multiple independent breakpoints. | **Byte-stable prefix.** The cache fingerprints the literal byte stream from byte 0. |
| Claude Code's design | Built around this. Markers on system prompt + tool defs let the loop reorder, compact, or insert metadata after the markers without losing the cache. | n/a — Claude Code wasn't designed for byte-stable prefixes. |
| What happens when Claude Code → DeepSeek compat | Markers stripped (ignored). Claude Code's main caching strategy disappears. | Falls back to auto-cache. But Claude Code's prefix isn't byte-stable (markers were the *substitute* for byte-stability), so auto-cache misses too. |
Net effect: **Claude Code's loop, redirected at DeepSeek, gets the
cheap tokens and loses the cache hit it depended on.** A loop running
at 80%+ cache hit on Anthropic's marker cache lands somewhere in the
40-60% range on DeepSeek's auto-cache (matches the generic-harness
baseline in our benchmarks). Same model, same API, same workload —
the loop's invariants don't fit the cache mechanic it's now talking
to.
Reasonix's loop was designed around byte-stable prefix from line one.
No markers, no breakpoints — append-only is the invariant. That's why
the same τ-bench workload lands at **94.4% cache hit** on Reasonix
and **46.6%** on a cache-hostile baseline (committed transcripts;
benchmarks section below). At DeepSeek's pricing — $0.07/Mtok
uncached, ~$0.014/Mtok cached — the difference between 50% and 94%
hit is **roughly 2.5× on input cost alone**.
### "What about Aider / Cline / Continue?"
They support DeepSeek natively (no compat layer needed) and you do
get the cheap token price. What you don't get is the DeepSeek-
specific loop work — those tools' loops support every backend
generically (OpenAI / Anthropic / local Llama / ...) and use
compaction + summarization patterns that destroy byte-stability. They
land in the same 40-60% cache-hit range as the baseline. Plus a
handful of DeepSeek-specific quirks generic loops don't handle:
| Generic loops assume | DeepSeek actually does | Reasonix's fix |
|---|---|---|
| Reasoning emitted as a structured `thinking` block | R1 sometimes leaks tool-call JSON inside `<think>` tags | a `scavenge` pass that pulls escaped tool calls back out, otherwise the model thinks it called and waits for output that never comes |
| Tool schemas validated strictly | DeepSeek silently drops deeply-nested object/array params | auto-flatten — nested params get rewritten to single-level prefixed names so the model sees them at all |
| Tool-call args are well-formed JSON | DeepSeek occasionally produces `string="false"` and other malformed fragments | dedicated `ToolCallRepair` heals the common shapes before they hit dispatch |
| Reasoning depth tuned via system-level switches | V4 exposes a `reasoning_effort` knob (`max` / `high`) | `/effort` slash + `--effort` flag, so users can step down for cheap turns |
| Old tool results kept in full forever | 1M context — don't compact pre-emptively, but most agents do | call-storm breaker + result token cap, but the prefix is *never* rewritten; compaction lands as new turns at the tail |
> Cache-stability isn't a feature you turn on; it's an invariant
> the loop is designed around. Reasonix isn't yet-another agent
> CLI — it's an agent CLI built around DeepSeek's specific cache
> mechanic and pricing model.
---
## `reasonix code` — pair programmer in your terminal
Scoped to the directory you launch from. The model has native
@@ -180,8 +338,9 @@ reasonix code › /commit "fix: findByEmail case-insensitive"
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 --preset pro` — v4-pro for the whole session,
no auto-downgrade to flash. Pair with `--branch 3` if you want
3-way self-consistency on gnarly refactors.
- `npx reasonix code src/` — narrower sandbox (only `src/` is
writable).
- `npx reasonix code --no-session` — ephemeral; nothing saved.
@@ -212,8 +371,8 @@ in the file. No prompts, no completions, no tool arguments.
### Staying current
The panel header shows the running version next to `Reasonix` (e.g.
`Reasonix v0.5.21 · deepseek-v4-pro · harvest · max …`, the trailing
`max` is the reasoning-effort badge — `/effort high` to step down).
`Reasonix 0.12.6 · v4-flash · AUTO · 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,
@@ -399,7 +558,7 @@ your own MCP servers. Sessions persist per name under
```bash
npx reasonix # uses saved config + wizard-selected MCP
npx reasonix --preset smart # reasoner + R1 harvest for this run
npx reasonix --preset pro # pin v4-pro for the whole run (no auto-downgrade)
npx reasonix --session design # named session — resume later with --session design
```
@@ -434,7 +593,7 @@ rendering, retries.
| command | what it does |
|---|---|
| `/preset <fast\|smart\|max>` | one-tap bundle (model + harvest + branch) |
| `/preset <auto\|flash\|pro>` | model commitment — `auto` = flash with escalation, `flash` = locked flash, `pro` = locked pro |
| `/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 |
@@ -614,7 +773,7 @@ npx reasonix sessions # list saved sessions
Common flags:
```bash
--preset <fast|smart|max> # bundle (model + harvest + branch)
--preset <auto|flash|pro> # model commitment (auto / locked-flash / locked-pro)
--model <id> # explicit model id
--harvest / --no-harvest # R1 plan-state extraction
--branch <N> # self-consistency budget
@@ -767,7 +926,7 @@ cd reasonix
npm install
npm run dev code # run CLI from source via tsx
npm run build # tsup to dist/
npm test # vitest (1007 tests)
npm test # vitest (1482 tests)
npm run lint # biome
npm run typecheck # tsc --noEmit
```
+855
View File
@@ -0,0 +1,855 @@
<p align="center">
<img src="docs/logo.svg" alt="Reasonix — DeepSeek 原生的 agent 框架" width="640"/>
</p>
<p align="center">
<em>为 DeepSeek V4(flash + pro)打造的缓存优先 agent 循环 — Ink TUI、原生 MCP、不依赖 LangChain。</em>
</p>
<p align="center">
<a href="./README.md">English</a> · <strong>简体中文</strong> · <a href="https://esengine.github.io/reasonix/">官方网站</a>
</p>
# Reasonix
[![npm version](https://img.shields.io/npm/v/reasonix.svg)](https://www.npmjs.com/package/reasonix)
[![CI](https://github.com/esengine/reasonix/actions/workflows/ci.yml/badge.svg)](https://github.com/esengine/reasonix/actions/workflows/ci.yml)
[![license](https://img.shields.io/npm/l/reasonix.svg)](./LICENSE)
[![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)
**DeepSeek 原生的终端 AI 编程代理。** 单次任务成本约为 Claude Code 的
1/30,缓存优先的循环是为 DeepSeek 的定价模型量身打造的。编辑以可审查的
SEARCH/REPLACE 块呈现,落盘前必须确认。MIT 许可、不绑 IDE、原生 MCP。
---
## 60 秒快速上手
**1. 获取 DeepSeek API Key。** 注册即送免费额度:
<https://platform.deepseek.com/api_keys>
**2. 切到项目目录运行。** 无需安装。
```bash
cd my-project
npx reasonix code
```
首次运行会走 30 秒向导(粘贴 API key → 选预设 → 多选 MCP 服务器)。
之后每次直接进入。
**3. 让它改代码。** 模型会以 SEARCH/REPLACE 块的形式提出编辑——
你不 `/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 处待应用编辑(1 个文件)— /apply 写入 · /discard 丢弃
reasonix code › /apply
▸ ✓ applied src/users.ts
```
要求 Node ≥ 20.10。支持 macOS、Linux、Windows(PowerShell · Git Bash ·
Windows Terminal)。任何时候按 `Esc` 中断;`/help` 查看完整命令列表。
---
## Web 控制台 *(0.12 新功能)*
会话内输入 `/dashboard`,Reasonix 会打印一个带一次性 token 的本地 URL。
浏览器打开后是一个 13 个面板的控制面 —— 与正在运行的 TUI 实时双向同步:
聊天(流式输出)、编辑器(文件树 + CodeMirror,语法高亮 + 自动补全 + 待
审编辑的左右对比 diff)、Usage / Sessions / Plans / Tools / Permissions /
System / MCP / Skills / Memory / Hooks / Settings。
```
reasonix code › /dashboard
▸ http://127.0.0.1:54219/?token=… (open in browser)
```
仅监听 127.0.0.1,会话结束 token 立即失效,所有改动都走 CSRF 校验。
TUI 继续可用 —— 弹窗(shell 确认、plan 审阅、edit 闸门)会同步到先看到
它的那一边,另一边自动消失。没有打包步骤,没有 Electron,没有额外进程。
---
## 为什么选 Reasonix?(vs Cursor / Claude Code / Cline / Aider)
三件事,别家不会同时都给你:
- **成本节省落到账单上。** DeepSeek V4 的 token 单价大约是 Claude Sonnet
的 1/30。光便宜还不够 —— *便宜的 token 配上 90%+ 的前缀缓存命中*才是关键。
Reasonix 的循环按 append-only 增长设计,缓存稳定的前缀在每次工具调用之间
都活着,下面的 benchmark 章节端到端验证过:实测 94.4% 缓存命中,对照组通用
框架只有 46.6%。`/stats` 面板每轮都跟踪 "vs Claude Sonnet 4.6" 的节省额,
你可以亲眼看着账单不涨。
- **它住在终端里。** 纯 CLI —— 没有 Electron,没有 VS Code 插件,没有要
塞进编辑器的 IDE 插件。和 git、tmux、shell 历史并排。macOS / Linux /
Windows(PowerShell、Git Bash、Windows Terminal 都测过)。唯一的网络
请求就是 DeepSeek API 本身,中间没有厂商服务器。
- **开源且彻底可改。** MIT 许可的 TypeScript。整个循环、工具注册表、
缓存稳定前缀、TUI、MCP 桥接 —— 全部在 `src/` 下,不到 3 万行。Fork
它、做私有构建、塞进 CI 都可以。没有 SaaS 层,没有企业版,没有功能闸门。
| | Reasonix | Claude Code | Cursor | Cline | Aider |
|---|---|---|---|---|---|
| 后端 | 仅 DeepSeek V4 | 仅 Anthropic | OpenAI / Anthropic | 任意(OpenRouter)| 任意(OpenRouter)|
| 单次任务成本 | **~$0.001–$0.005** | ~$0.05–$0.50 | $20/月 + 用量 | 视情况 | 视情况 |
| 运行环境 | 终端 | 终端 + IDE | IDE(Electron)| 仅 VS Code | 终端 |
| 开源协议 | **MIT** | 闭源 | 闭源 | Apache 2 | Apache 2 |
| 缓存优先前缀循环 | **工程化(94% 命中)** | 基础 | n/a | n/a | 基础 |
| MCP 服务器 | **原生支持** | 原生支持 | — | 测试中 | — |
| 计划模式(只读审计闸门)| **支持** | 支持 | — | 支持 | — |
| 用户编写的 skills | **支持** | 支持 | — | — | — |
| 编辑审阅(不自动落盘)| **支持**(`/apply`)| 支持 | 部分 | 支持 | 支持 |
| 工作区切换(`/cwd`、`change_workspace`)| **支持** | — | n/a(每窗一项目)| — | — |
| 跨会话成本面板 | **支持**(`/stats`)| — | — | — | — |
| 沙箱边界强制 | **严格**(拒绝 `..` 逃逸)| 支持 | 部分 | 支持 | 部分 |
### 这些情况下应该选别的
- **你想要多模型混用**(在一个工具里同时切 Claude / GPT / Gemini / 本地 Llama)。
试试 [Aider](https://aider.chat) 或 [Cline](https://cline.bot)。Reasonix
故意只绑 DeepSeek —— 每一层(缓存优先循环、R1 harvest、JSON 模式的工具
调用修复、reasoning_effort 上限)都是为 DeepSeek 的具体行为和经济模型
调出来的。绑死后端是设计选择,不是早晚要解决的限制。
- **你想要 IDE 集成**(编辑器侧边栏 inline diff、多光标、ghost text、重构
预览)。试试 [Cursor](https://cursor.com) 或 Claude Code 的 IDE 模式。
Reasonix 是终端优先的:diff 在 `git diff` 里、文件树在 `ls` 里、对话
在 shell 里。
- **你在追最难的推理 benchmark**。Claude Opus 4.6 还是赢一些榜单的。
DeepSeek V4-pro 在大多数编程任务上都很有竞争力,但不是每个 benchmark
都领先。如果你的任务是"证明这个 PhD 级别的数学命题"而不是"修这个
auth bug",从 Claude 起步更合适。
- **你需要完全本地 / 永远免费**。DeepSeek API 注册送额度,但不是永久
免费。要真正离线/永久免费,看看 Aider + Ollama 或者
[Continue](https://continue.dev)。
### "DeepSeek 现在有 Anthropic 兼容 API 了,我直接拿 Claude Code 接上不就行?"
可以接。DeepSeek 官方提供了 Anthropic 兼容端点
`https://api.deepseek.com/anthropic`,Claude Code(或任何 Anthropic SDK
客户端)不改一行代码就能连上去。**协议跑得通,缓存经济学跑不通** ——
而后者才是关键。
看 [DeepSeek 自己的兼容性表](https://api-docs.deepseek.com/guides/anthropic_api):
| 字段 | 在 DeepSeek 兼容端点上的状态 |
|---|---|
| `cache_control` 标记 | **Ignored(被忽略)** |
| `mcp_servers`(API 层)| Ignored |
| `thinking.budget_tokens` | Ignored |
| 图像 / 文档 / 引用 | 不支持 |
`cache_control: Ignored` 就是杀手级的那一行。这里有**两套完全不同的缓存
机制在打架**:
| | Anthropic 原生 | DeepSeek 自动缓存 |
|---|---|---|
| 模型 | **Marker 驱动。** 你在某条消息上打 `cache_control`,Anthropic 把"到此 marker 为止"的内容做内容寻址缓存。多个 marker = 多个独立断点。 | **Byte-stable prefix。** 缓存对字面字节流从第 0 字节起做指纹。 |
| Claude Code 的设计 | 围绕这个设计的。在 system prompt + tool 定义上插 marker,让 loop 在 marker 之后做重排、压缩、插元数据都不丢缓存。 | n/a —— Claude Code 不是为 byte-stable prefix 设计的。 |
| Claude Code 接 DeepSeek 兼容端点之后 | Marker 被 strip(忽略)。Claude Code 的主缓存策略消失。 | Fallback 到 auto-cache。但 Claude Code 的 prefix 不是 byte-stable 的(marker 本来就是 byte-stability 的*替代*),auto-cache 也命中不了。 |
净效果:**Claude Code 的 loop 重定向到 DeepSeek 之后,便宜 token 拿到了,
原本依赖的缓存命中没了**。一个在 Anthropic marker cache 上 80%+ 命中的
loop,到 DeepSeek 的 auto-cache 上大概率掉到 40-60%(跟我们 benchmark 里
通用 harness 的 baseline 同区间)。同一个模型、同一个 API、同一个负载 ——
loop 的 invariant 跟它现在对话的缓存机制不匹配。
Reasonix 的 loop 从第一行起就是按 byte-stable prefix 的不变量设计的。没有
marker、没有断点 —— append-only 就是 invariant。这就是为什么同一份 τ-bench
负载在 Reasonix 上是 **94.4% 缓存命中**、在 cache-hostile baseline 上是
**46.6%**(已 commit 的 transcript,见下面 benchmark 段)。按 DeepSeek 的
单价 —— $0.07/Mtok 非缓存、约 $0.014/Mtok 缓存命中 —— 50% 和 94% 命中之间
**仅 input 这一侧就大约是 2.5× 的差距**。
### "那 Aider / Cline / Continue 呢?"
它们原生支持 DeepSeek(不需要兼容层),便宜 token 单价你确实拿到了。
但你拿不到 DeepSeek-specific 的循环工程 —— 这些工具的 loop 是为**通用支持**
所有后端(OpenAI / Anthropic / 本地 Llama / ...)设计的,用的是那种会破坏
byte-stability 的通用压缩 / 摘要模式。命中率落在和 baseline 同样的 40-60%
区间。再加上一堆 DeepSeek 怪癖通用 loop 不处理:
| 通用 loop 假定 | DeepSeek 实际行为 | Reasonix 怎么处理 |
|---|---|---|
| 推理通过结构化 `thinking` 块产出 | R1 偶尔把 tool-call JSON 漏到 `<think>` 标签里 | `scavenge` 扫描把漏出的 tool call 拣回,否则模型以为自己已经调用,等不到结果 |
| tool schema 严格校验 | DeepSeek 静默丢弃深嵌套 object/array 参数 | auto-flatten:嵌套参数被重写成单层 prefixed name,模型才看得见 |
| tool-call args 是良构 JSON | DeepSeek 偶发 `string="false"` 之类的破碎片段 | 专用 `ToolCallRepair` 在 dispatch 之前修好常见形状 |
| 推理深度靠系统级开关 | V4 直接暴露 `reasoning_effort` 旋钮(`max` / `high`) | `/effort` slash + `--effort` flag,简单任务可以降到 high 省钱 |
| 老 tool result 永久保留 | 1M context 不需要主动 compact,但通用工具都会做 | call-storm breaker + 结果 token cap,但前缀**永不重写** —— 压缩作为新 turn 追加在尾部 |
> 缓存稳定性不是一个开关,是 loop 设计之初就要建立的不变量。Reasonix
> 不是"又一个 agent CLI",是**围绕 DeepSeek 具体的缓存机制和定价模型
> 设计的 agent CLI**。
---
## `reasonix code` — 终端里的结对编程
作用域为启动目录。模型自带 `read_file` / `write_file` / `edit_file` /
`list_directory` / `search_files` / `directory_tree` / `get_file_info` /
`create_directory` / `move_file`,全部在沙箱内 —— 任何解析后落到启动根目录之外
的路径(包括 `..` 或符号链接逃逸)都会被拒绝。再加上带只读白名单的
`run_command`;任何会修改状态的命令(`npm install`、`git commit` 等)都要走
确认弹窗。
### 流程演示:先看再改
对于"这段代码做什么用?"这类问题,模型会用读取类工具,然后用散文回答 ——
不会出 SEARCH/REPLACE 块、也不会写文件。只有你明确要求修改时它才动手:
```
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 写子路径,最后 …
```
`edit_file` 的 SEARCH 块如果没有按字节精确匹配文件内容,编辑会被显式拒绝
而不是模糊匹配。模型能看到错误并自行重试 —— 比起"静默改错","显式拒绝"
是更安全的失败方式。
### Plan 模式 —— 执行前先审阅
任何比"改个 typo"更大的改动,模型会被引导先提交一份 markdown 计划。
你会看到 **批准 / 重做 / 取消** 三选一:
```
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
```
**强制启用** 用 `/plan` —— 进入显式只读阶段:模型必须先提交计划,否则任何
编辑或非白名单 shell 调用都不会执行。适合那些你想先审一遍再让模型动手的
高风险改动。`/plan off` 或在弹窗里选 Approve/Cancel 退出。
### 输入前缀 —— `!cmd` 与 `@path`
两个不需要斜杠的内联快捷方式:
**`!<cmd>` —— 在沙箱里跑 shell 命令并把结果喂给模型。** 像 bash 一样在
prompt 里直接打。输出既会进入可见日志,也会进入会话 —— 模型下一轮会基于它
推理:
```
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
▸ …
```
无白名单门 —— 用户主动输入的 shell 命令就是显式同意。60 秒超时、32k 字符
上限,0.5.14 起会话恢复后依然保留。
**`@path/to/file` —— 内联一个文件作为 "Referenced files"。** 输入 `@`
弹出选择器(↑/↓ 切换、Tab/Enter 插入)。比让模型 `read_file` 后再问更省事:
"@src/users.ts 这个文件做什么用?"。沙箱限定:仅相对路径、不允许 `..`、单
文件 64KB 上限。最近用过的文件排在前面。
### `/commit` —— 一步暂存 + 提交
```
reasonix code › /commit "fix: findByEmail case-insensitive"
▸ git add -A && git commit -m "fix: findByEmail case-insensitive"
[main a1b2c3d] fix: findByEmail case-insensitive
```
### 一些值得试试的命令
- `/tool 1` —— 打印最后一次工具调用的完整输出(当 400 字内联剪辑不够看时)。
- `/think` —— 看上一轮模型的完整推理(思考模式:v4-flash / v4-pro / reasoner 别名)。
- `/undo` —— 回滚上一批已应用的编辑。
- `/new` —— 在同一目录开新会话,但不丢失旧会话文件。
- `/effort high` —— 从默认 `max` agent 推理强度降一档,简单任务更省更快。
- `npx reasonix code --preset pro` —— 整轮锁定 v4-pro,不再自动降级到
flash。如果想要 self-consistency 分支,加 `--branch 3` 跑三路投票。
- `npx reasonix code src/` —— 更窄的沙箱(只有 `src/` 可写)。
- `npx reasonix code --no-session` —— 临时会话,什么都不存。
### `reasonix stats` —— 你到底省了多少?
每次 `reasonix chat|code|run` 跑完都会往
`~/.reasonix/usage.jsonl` 追加一条精简记录(token + 成本 + Claude Sonnet
4.6 同负载下的等价价格)。`reasonix stats` 不带参数会把日志聚合成今日 /
本周 / 本月 / 历史 四个窗口:
```
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%
```
隐私:日志里只有 token、成本和你自己取的 session 名。没有 prompt、没有
completion、没有工具参数。`reasonix stats <transcript>` 仍兼容老用法
(按文件出 assistant turn + tool call 摘要)。
### 保持最新
面板顶栏在 `Reasonix` 旁边显示当前版本(如
`Reasonix 0.12.6 · v4-flash · AUTO · max …`,最后那个 `max` 是推理强度
徽章 —— `/effort high` 可降一档)。后台每 24 小时静默查询一次 npm
registry,发现新版会在同一行右侧显示黄色 `update: X.Y.Z`。不阻塞、不烦人,
每天最多查一次,离线 / 防火墙下静默失败。
```bash
reasonix update # 打印当前 vs 最新,并执行 `npm i -g reasonix@latest`
reasonix update --dry-run # 只打印计划,不实际安装
```
通过 `npx` 用?命令会识别这种情况并改为打印 cache 刷新提示 —— npx 在下次
调用时会自动取最新版本。
### 项目约定 —— `REASONIX.md`
把 `REASONIX.md` 放到项目根目录,每次启动都会被钉进 system prompt。可提交
的团队记忆 —— 房间约定、领域词表、模型老忘的事情:
```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
```
重启(或 `/new`)后生效;前缀每会话只哈希一次,让 DeepSeek 的缓存保持热。
`/memory` 打印当前已钉的内容。`REASONIX_MEMORY=off` 在 CI / 离线复现时关闭
所有记忆来源。
### 用户记忆 —— `~/.reasonix/memory/`
第二层 **私人按用户** 的记忆放在你的 home 目录。不像 `REASONIX.md` 会被
提交,模型自己也能通过 `remember` 工具往里写。两个作用域:
- `~/.reasonix/memory/global/` —— 跨项目(你的偏好、工具链)。
- `~/.reasonix/memory/<project-hash>/` —— 限定一个 `reasonix code` 沙箱
根目录(决策、本地事实、按仓库的快捷方式)。
每个作用域都维护一个总是加载的 `MEMORY.md` 索引(一行一条)+ 零或多个
`<name>.md` 详情文件(按需通过 `recall_memory` 加载)。写入立刻生效;钉进
system prompt 在下一次 `/new` 或重启时生效,以保证当前会话的缓存前缀稳定。
```
reasonix code › 我用 bun 而不是 npm,请以后都用 bun 跑构建
assistant
▸ tool<remember> → project/bun_build saved
"Build command on this machine is `bun run build`"
```
**斜杠**:`/memory` · `/memory list` · `/memory show <name>` ·
`/memory forget <name>` · `/memory clear <scope> confirm`。
**模型工具**:`remember(type, scope, name, description, content)` ·
`forget(scope, name)` · `recall_memory(scope, name)`。
项目作用域只在 `reasonix code` 里可用(需要真实的沙箱根来计算哈希);纯
`reasonix` 只有全局作用域。
### Skills —— 用户自定义的 prompt 包
Skill 就是你写在磁盘上的散文指令块。Reasonix 把它们的名字 + 一行描述钉
进 system prompt;模型可以在合适时机自动调 `run_skill({name: "..."})`,
你也可以打 `/skill <name> [args]` 手动触发。
两个作用域,与用户记忆同样的布局:
- `<project>/.reasonix/skills/` —— 按项目(提交进 git 给团队,或加入
`.gitignore` 做个人草稿)。
- `~/.reasonix/skills/` —— 全局,到处可用。
两种文件结构都行:`<name>/SKILL.md`(推荐 —— 可同时打包附带资源)或扁平
`<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.
```
用法:
```
reasonix code › /skill review
▸ running skill: review
assistant
▸ tool<run_command> → git diff --cached
▸ 3 改动,1 个需要回归测试 …
```
或者让模型自己挑 —— 因为 skill 名字 + 描述都在前缀里,问 "帮我看下未提交
的改动有没有风险" 就会触发 `run_skill({name: "review"})`,不用你打斜杠。
**斜杠**:`/skill`(列出) · `/skill show <name>` · `/skill <name>
[args]`(把 body 作为用户轮注入)。
**故意不绑死** 任何其他客户端的目录约定(`.claude/skills` 等等)——
Reasonix 在对话层是模型无关的。任何 SKILL.md 都能用;body 是散文,所以
为别的工具写的 skill 多半能直接用(Reasonix 工具名不同 —— `filesystem`
/ `shell` / `web` —— 但模型读到指令后会挑我们的等价工具)。
### Hooks —— 围绕工具调用与轮次自动化
在 `.reasonix/`(项目或 `~/`)放一个 `settings.json`,Reasonix 会在
循环里四个常见的点触发 shell 命令:工具运行前、工具返回后、prompt 到达
模型前、轮次结束后。
```json
// <project>/.reasonix/settings.json ← 可提交
// ~/.reasonix/settings.json ← 按用户
{
"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 }]
}
}
```
每个 hook 都是 shell 命令。Reasonix 调用时通过 stdin 传一份 JSON 信封,
描述事件:
```json
{ "event": "PreToolUse", "cwd": "/path/to/project",
"toolName": "edit_file", "toolArgs": { "path": "src/x.ts", "..." } }
```
退出码决定走向:
- **0** —— 通过;循环正常继续
- **2** —— 阻断(仅对 `PreToolUse` / `UserPromptSubmit` 生效);hook 的
stderr 会作为合成工具结果让模型看到,或者整条 prompt 直接被丢弃
- **其他** —— 警告;循环继续,stderr 渲染为黄色行内提示
`match` 是对工具名的锚定正则;`*` 或省略匹配所有工具。项目 hook 先于全局
hook 触发。默认超时:阻断类事件 5 秒,日志类事件 30 秒;可在每条 hook 里
用 `timeout` 覆盖。
**斜杠**:`/hooks`(列出当前生效的 hook)· `/hooks reload`(不丢会话从磁盘
重读 `settings.json`)。
### 在 TUI 里保持最新
`/update` 在运行中的会话里会显示当前版本、最近一次后台 24h 检查取到的最新
版本,以及实际安装命令。这条斜杠 **不会** 直接 spawn `npm install` ——
stdio:inherit 进入正在跑的 Ink 渲染器会把显示搞乱。要真正升级请退出会话,
在新 shell 里执行 `reasonix update`。
---
## `reasonix` —— 也能当通用聊天
同一套 TUI,没有文件系统工具(除非你通过 MCP 主动接入)。适合起草、问答、
schema 设计、架构讨论,或者驱动你自己的 MCP 服务器。会话按名字保存在
`~/.reasonix/sessions/`。
```bash
npx reasonix # 用已保存配置 + 向导选过的 MCP
npx reasonix --preset pro # 整轮锁定 v4-pro(不自动降级)
npx reasonix --session design # 命名会话 — 之后 --session design 续聊
```
临时挂 MCP 服务器:
```bash
npx reasonix \
--mcp "fs=npx -y @modelcontextprotocol/server-filesystem /tmp/safe" \
--mcp "kb=https://mcp.example.com/sse"
```
MCP 工具走和原生工具一样的 Cache-First + 修复 + 上下文安全管线 —— 32k
结果上限、实时进度通知渲染、自动重试。
---
## 会话内命令
**核心**
| 命令 | 作用 |
|---|---|
| `/help` · `/?` | 完整命令参考(带提示) |
| `/status` | 当前模型 · flag · 上下文 · 会话 |
| `/new` · `/reset` | 同会话内开新对话 |
| `/clear` | 仅清空可见 scrollback(日志保留) |
| `/retry` | 截断并重发上一条消息(重新采样) |
| `/exit` · `/quit` | 退出 |
**模型**
| 命令 | 作用 |
|---|---|
| `/preset <auto\|flash\|pro>` | 模型策略 —— `auto` = flash 自动升级、`flash` = 锁 flash、`pro` = 锁 pro |
| `/model <id>` | 切换 DeepSeek 模型(`deepseek-v4-flash`、`deepseek-v4-pro`,加上 `deepseek-chat` / `deepseek-reasoner` 兼容别名) |
| `/models` | 列出 DeepSeek `/models` 端点的可用模型 |
| `/harvest [on\|off]` | 切换 R1 plan-state 提取 |
| `/branch <N\|off>` | 每轮跑 N 路并行采样,挑最佳(N ≥ 2) |
| `/effort <high\|max>` | reasoning_effort 上限 —— `max` 是 agent 默认,`high` 更便宜更快 |
| `/think` | 打印上一轮的完整 thinking-mode 推理 |
**上下文与工具**
| 命令 | 作用 |
|---|---|
| `/mcp` | 列出已挂载的 MCP 服务器及其 tool / resource / prompt |
| `/resource [uri]` | 浏览 + 读取 MCP resource(无参 → 列 URI;`<uri>` → 拉取) |
| `/prompt [name]` | 浏览 + 拉取 MCP prompt |
| `/tool [N]` | 打印第 N 次工具调用的完整输出(1 = 最近) |
| `/compact [tokens]` | 压缩日志里超大的工具结果(默认每条结果 4000 tokens) |
| `/context` | 看上下文 token 都花在哪(system / tools / log) |
| `/stats` | 跨会话成本仪表盘(today / week / month / all-time) |
| `/keys` | 键盘快捷键 + 输入前缀(`!` / `@` / `/`)速查 |
**记忆与 Skill**
| 命令 | 作用 |
|---|---|
| `/memory` | 显示已钉记忆(REASONIX.md + ~/.reasonix/memory) |
| `/memory list` · `show <name>` · `forget <name>` · `clear <scope> confirm` | 管理记忆库 |
| `/skill` · `/skill list` | 列出已发现的 skill(项目 + 全局) |
| `/skill show <name>` | 打印某个 skill 的 body |
| `/skill <name> [args]` | 运行 skill(把 body 作为用户轮注入) |
**会话**
| 命令 | 作用 |
|---|---|
| `/sessions` | 列出已保存的会话(当前用 `▸` 标记) |
| `/forget` | 从磁盘删除当前会话 |
| `/setup` | 重新配置(退出后跑 `reasonix setup`) |
**只在 code 模式下** (`reasonix code`)
| 命令 | 作用 |
|---|---|
| `/apply` | 把待应用的 SEARCH/REPLACE 块写入磁盘 |
| `/discard` | 丢弃待应用的编辑块 |
| `/undo` | 回滚最后一批已应用的编辑 |
| `/commit "msg"` | `git add -A && git commit -m "msg"` |
| `/plan [on\|off]` | 切换只读 plan 模式 |
| `/apply-plan` | 强制批准当前待审计划 |
**键盘**
- `Enter` —— 提交
- `Shift+Enter` / `Ctrl+J` —— 换行(多行粘贴也行;
`\` + Enter 是跨平台兜底)
- `↑` / `↓` —— 空闲时翻 prompt 历史;在斜杠自动补全里上下选
- `/foo` 前缀下按 `Tab` / `Enter` —— 接受高亮的建议
- `Esc` —— 中断当前轮(停 API 调用、取消进行中的工具、拒绝待响应的 MCP 请求)
- 确认弹窗里的 `y` / `n` —— 快捷接受 / 拒绝
---
## 会话与安全网
- 会话以 JSONL 形式保存在 `~/.reasonix/sessions/<name>.jsonl`(`reasonix
code` 按目录分)。每条消息都原子追加;`Ctrl+C` 不会丢上下文。
- 工具结果每次调用最多 32k 字符。超大会话加载时自动自愈(缩小并重写文件)。
- 每次出站 API 调用前会校验 `assistant.tool_calls` / `tool` 的配对,损坏的
会话不会一直 400。
- 上下文仪表 50% 变黄、80% 变红并提示 `/compact`。接近 1M token 上限
(V4 flash + pro)会先尝试自动压缩,再退化为强制总结。
- `reasonix code` 沙箱拒绝任何解析后落到启动目录之外的路径(含符号链接
逃逸和 `..` 穿越)。
### 故障排查:重复行 / 鬼影渲染
有些 Windows 终端(Git Bash / MINTTY / winpty 包装的 shell)没完整实现
Ink 用的 ANSI cursor-up 转义。表现:spinner、流式预览、工具结果行不在原地
覆盖刷新,反而在 scrollback 里印出多份。
遇到了就用 plain 模式:
```bash
REASONIX_UI=plain npx reasonix code
```
Plain 模式抑制了实时 / 动画行,关掉了内部 tick 计时器。代价是失去流式预览
和 spinner,但 scrollback 稳定。Windows Terminal、Windows Terminal 里的
PowerShell 7、WezTerm 不需要这个开关。
---
## Web 搜索 —— 默认开
模型一启动就有两个 web 工具:`web_search` 和 `web_fetch`。无 flag、无 API
key、无注册。当你问到模型训练时没见过的事(新发布、最近事件、冷门 API),
它会自己决定调 `web_search`;snippet 不够就跟一个 `web_fetch`。
底层是 **Mojeek** 的公开搜索页 —— 独立 web 索引,bot 友好,无 cookie /
session。冷门或非常新的查询覆盖率比 Google/Bing 薄一些,但脚本里很可靠。
(DDG 是原始后端,但 2026 年开始上反机器人页。)
**关掉**(离线 / 隐私 / CI):
```json
// ~/.reasonix/config.json
{ "apiKey": "sk-…", "search": false }
```
```bash
REASONIX_SEARCH=off npx reasonix code
```
**接自己的**(Kagi、SearXNG、内部缓存):实现 `WebSearchProvider` 接口
然后自己调 `registerWebTools(registry, { provider })`,或通过 `--mcp`
桥接已有的 MCP 搜索服务器。
---
## MCP —— 自带工具
任意 [MCP](https://spec.modelcontextprotocol.io/) 服务器都能用。向导内置
目录可选,或用 flag 直接挂:
```bash
# stdio(本地子进程)
npx reasonix --mcp "fs=npx -y @modelcontextprotocol/server-filesystem /tmp/safe"
# 同时挂多个
npx reasonix \
--mcp "fs=npx -y @modelcontextprotocol/server-filesystem /tmp/safe" \
--mcp "demo=npx tsx examples/mcp-server-demo.ts"
# HTTP+SSE(远程 / 托管)
npx reasonix --mcp "kb=https://mcp.example.com/sse"
```
`reasonix mcp list` 显示精选目录。`reasonix mcp inspect <spec>` 不开聊天,
直接连一次并打印服务器的 tool / resource / prompt。长任务的进度通知
(2025-03-26 spec)会以进度条形式实时渲染在 spinner 里。
支持的传输:**stdio**(本地命令)和 **HTTP+SSE**(远程,MCP 2024-11-05
spec)。
---
## CLI 参考
```bash
npx reasonix code [path] # 编程模式,作用域 path(默认 cwd)
npx reasonix # 聊天(用已保存配置)
npx reasonix setup # 重跑配置向导
npx reasonix chat --session work # 命名会话
npx reasonix chat --no-session # 临时会话
npx reasonix run "ask anything" # 一次性运行,结果流到 stdout
npx reasonix stats session.jsonl # 总结一份 transcript
npx reasonix replay chat.jsonl # 从 transcript 重建成本/缓存视图
npx reasonix diff a.jsonl b.jsonl --md # 对比两份 transcript
npx reasonix mcp list # 精选 MCP 目录
npx reasonix mcp inspect <spec> # 探测单个 MCP 服务器
npx reasonix sessions # 列已保存会话
```
常用 flag:
```bash
--preset <auto|flash|pro> # 模型策略(auto / 锁 flash / 锁 pro)
--model <id> # 显式指定模型 ID
--harvest / --no-harvest # R1 plan-state 提取
--branch <N> # self-consistency 预算
--mcp "name=cmd args…" # 挂 MCP 服务器(可重复)
--transcript path.jsonl # 同时旁路写一份 JSONL transcript
--session <name> # 命名会话(code 模式默认按目录)
--no-session # 临时会话
--no-config # 忽略 ~/.reasonix/config.json(CI 友好)
```
环境变量(覆盖 config):
```bash
export DEEPSEEK_API_KEY=sk-...
export DEEPSEEK_BASE_URL=https://... # 可选的备用端点
export REASONIX_MEMORY=off # 关闭 REASONIX.md + 用户记忆
export REASONIX_SEARCH=off # 关闭 web_search / web_fetch
export REASONIX_UI=plain # 关闭实时行(鬼影绕开)
```
---
## 库用法
```ts
import {
CacheFirstLoop,
DeepSeekClient,
ImmutablePrefix,
ToolRegistry,
} from "reasonix";
const client = new DeepSeekClient(); // 从环境变量读 DEEPSEEK_API_KEY
const tools = new ToolRegistry();
tools.register({
name: "add",
description: "Add two integers",
parameters: {
type: "object",
properties: { a: { type: "integer" }, b: { type: "integer" } },
required: ["a", "b"],
},
fn: ({ a, b }: { a: number; b: number }) => a + b,
});
const loop = new CacheFirstLoop({
client,
tools,
prefix: new ImmutablePrefix({
system: "You are a math helper.",
toolSpecs: tools.specs(),
}),
harvest: true,
branch: 3,
});
for await (const ev of loop.step("What is 17 + 25?")) {
if (ev.role === "assistant_final") console.log(ev.content);
}
console.log(loop.stats.summary());
```
`ChatOptions.seedTools` 接受一个预置好的 `ToolRegistry`,如果你只想要
`reasonix code` 的 loop 接线、不要 CLI 包装。详见
[docs/ARCHITECTURE.md](docs/ARCHITECTURE.md)。
---
## 性能对比 —— 缓存命中率自己也能验证
这里每个抽象都对应 DeepSeek 的一个具体特性 —— 极低 token 价、R1 推理轨
迹、自动前缀缓存、JSON 模式。通用框架把这些机会全留在桌上。
| | Reasonix 默认 | 通用框架 |
|---|---|---|
| 前缀稳定的循环(→ 85–95% 缓存命中) | 是 | 否(每轮重建 prompt) |
| 自动展平深层 tool schema | 是 | 否(DeepSeek 会丢参数) |
| 带 jitter 退避的 429/503 重试 | 是 | 否(要自己写回调) |
| 抢救泄到 `<think>` 里的 tool call | 是 | 否 |
| 同参数重复爆发熔断 | 是 | 否 |
| 实时缓存命中 / 成本 / vs Claude 面板 | 是 | 否 |
同一 τ-bench-lite 负载(8 个多轮工具调用任务 × 3 次重复 = 每边 48 次运行),
实测 DeepSeek `deepseek-chat`,唯一变量是前缀稳定性:
| 指标 | 基线(缓存敌对) | Reasonix | 差值 |
|---|---:|---:|---:|
| 缓存命中 | 46.6% | **94.4%** | +47.7 pp |
| 单任务成本 | $0.002599 | $0.001579 | **−39%** |
| 通过率 | 96% (23/24) | **100% (24/24)** | — |
**无需消耗 API 额度即可复现:**
```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
```
提交进仓库的 JSONL 文件每轮带 `usage`、`cost`、`prefixHash`。Reasonix
的前缀哈希在每次模型调用时都字节稳定;基线则每轮都变。缓存差距是从日志稳
定性 **机械可推导** 的,不依赖于 prompt 写得不一样。
完整 48 次运行报告:
[`benchmarks/tau-bench/report.md`](./benchmarks/tau-bench/report.md)。
用自己的 API key 复现:`npx tsx benchmarks/tau-bench/runner.ts --repeats 3`。
MCP 参考运行(即使两个 MCP 子进程并发,整 5 轮也只有一个前缀哈希):
| 服务器 | 轮次 | 缓存命中 | 成本 | vs Claude |
|---|---:|---:|---:|---:|
| 内置 demo(`add` / `echo` / `get_time`) | 2 | **96.6%**(第 2 轮) | $0.000254 | −94.0% |
| 官方 `server-filesystem` | 5 | **96.7%** | $0.001235 | −97.0% |
| **两者并发** | 5 | **81.1%** | $0.001852 | −95.9% |
---
## Non-goals(明确不做)
- **多 agent 编排 / 子 agent**(用 LangGraph)。
- **工作流 DSL / DAG 调度 / 并行分支引擎** —— skill 是散文,模型靠正常的
tool-use 循环串起来。这样保住了单循环 + append-only + cache-first 三大
不变量。
- **多供应商抽象**(用 LiteLLM)。Reasonix 故意只做 DeepSeek —— 每个支柱
(cache-first 循环、R1 抢救、tool-call 修复)都针对 DeepSeek 的具体行为
和经济性做了调优。绑死一家后端是特性。
- **RAG / 向量库**(用 LlamaIndex)。
- **Web UI / SaaS。**
Reasonix 只做 DeepSeek,做到底。
---
## 开发
```bash
git clone https://github.com/esengine/reasonix.git
cd reasonix
npm install
npm run dev code # 用 tsx 直接从源码跑 CLI
npm run build # tsup 打包到 dist/
npm test # vitest(1482 个测试)
npm run lint # biome
npm run typecheck # tsc --noEmit
```
---
## License
MIT
+64
View File
@@ -0,0 +1,64 @@
# Reasonix — working knowledge
TypeScript project. DeepSeek-native coding agent, cache-first loop.
MIT-licensed. Node ≥20.10 required.
## Stack
- **Language** — TS 5.6+, ES2022, ESM (`"type": "module"`)
- **CLI** — Commander.js + Ink 5 (React 18) TUI
- **Test** — Vitest 2.x
- **Lint / Format** — Biome 1.9 (2-space, double quotes, semicolons always, 100 width)
- **Build** — tsup (bundle), `tsx` (dev runner)
- **MCP** — stdio + SSE transports, in-process fake in tests
## Layout
| Path | What |
|---|---|
| `src/` | All source — `mcp/`, `tools/`, `cli/`, `code/`, `repair/`, `index/` |
| `src/cli/` | CLI entry + commands (`chat.tsx`, `code.tsx`, `diff.ts`, etc.) + Ink TUI in `ui/` |
| `src/tools/` | Tool defs (filesystem, shell, MCP, plan, subagent, web, workspace) |
| `src/mcp/` | MCP client, transports (stdio, SSE), registry, spec |
| `src/repair/` | Tool-call repair pipeline (flatten, scavenge, storm, truncation) |
| `src/index/` | Semantic vector index |
| `tests/` | Vitest tests, flat `*.test.ts` |
| `examples/` | `basic-chat.ts`, `mcp-server-demo.ts`, etc. |
| `benchmarks/` | Harvest + tau-bench harnesses |
| `data/` | Tokenizer data (`deepseek-tokenizer.json.gz`) |
| `dist/` | Build output — **do not edit** |
| `.github/` | CI + issue templates |
## Commands
```sh
npm run build # tsup → dist/
npm run dev # tsx src/cli/index.ts
npm run chat # tsx src/cli/index.ts chat
npm run test # vitest run
npm run test:watch # vitest
npm run lint # biome check src tests
npm run lint:fix # biome check --write src tests
npm run format # biome format --write src tests
npm run typecheck # tsc --noEmit
```
`prepublishOnly`: lint → typecheck → test → build.
## Conventions
- **Imports** — explicit `import type` for type-only imports (Biome `useImportType: warn`). Direct relative imports within project, no barrel re-exports.
- **Exports** — named exports only; no `export default`. Entry: `src/index.ts`.
- **Tests** — vitest `describe`/`it`/`expect`, no globals. Naming: `<module>.test.ts` flat in `tests/`.
- **JSX** — `.tsx` for Ink components. `jsx: "react"` in tsconfig.
- **TypeScript** — `strict`, `noUncheckedIndexedAccess`, `noImplicitOverride`. Tools accept `ToolCallContext` (abort signal).
- **MCP** — All transports implement `McpTransport` interface. Tools registered via registry at startup.
- **Changelog** — Keep a Changelog format. Semver.
## Watch out for
- **This IS Reasonix** — edits to `src/loop.ts`, `src/repair/`, `src/tools/`, `src/mcp/` affect every session. Test before publishing.
- **SEARCH must match byte-for-byte** — the edit-gate in `src/code/edit-blocks.ts` enforces exact match. Trailing whitespace or wrong indent = mismatch.
- **`dist/`** is generated by `tsup`. Never hand-edit.
- **`.reasonix/semantic/`** is auto-generated vector index. Never hand-edit.
- **`sessions/` and `.reasonix/sessions/`** are user-private, git-ignored (per `.gitignore`).
+5 -1
View File
@@ -21,7 +21,11 @@ import {
claudeEquivalentCost,
loadDotenv,
} from "../../src/index.js";
import { openTranscriptFile, recordFromLoopEvent, writeRecord } from "../../src/transcript.js";
import {
openTranscriptFile,
recordFromLoopEvent,
writeRecord,
} from "../../src/transcript/log.js";
import { TASKS } from "./tasks.js";
import type {
HarvestBenchMeta,
+5 -1
View File
@@ -25,7 +25,11 @@ import {
costUsd,
loadDotenv,
} from "../../src/index.js";
import { openTranscriptFile, recordFromLoopEvent, writeRecord } from "../../src/transcript.js";
import {
openTranscriptFile,
recordFromLoopEvent,
writeRecord,
} from "../../src/transcript/log.js";
import { BaselineAgent } from "./baseline.js";
import { cloneDb } from "./db.js";
import { TASKS } from "./tasks.js";
+1 -1
View File
@@ -24,6 +24,6 @@
}
},
"files": {
"ignore": ["dist", "node_modules", "coverage", "*.d.ts"]
"ignore": ["dist", "node_modules", "coverage", "*.d.ts", "dashboard/codemirror.js"]
}
}
+2540
View File
File diff suppressed because it is too large. Load diff
+4542
View File
File diff suppressed because it is too large. Load diff
+36
View File
@@ -0,0 +1,36 @@
var A=class O{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,i){[e,t]=CO(this,e,t);let r=[];return this.decompose(0,e,r,2),i.length&&i.decompose(0,i.length,r,3),this.decompose(t,this.length,r,1),WO.from(r,this.length-(t-e)+i.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=CO(this,e,t);let i=[];return this.decompose(e,t,i,0),WO.from(i,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),i=this.length-this.scanIdentical(e,-1),r=new $O(this),n=new $O(e);for(let s=t,a=t;;){if(r.next(s),n.next(s),s=0,r.lineBreak!=n.lineBreak||r.done!=n.done||r.value!=n.value)return!1;if(a+=r.value.length,r.done||a>=i)return!0}}iter(e=1){return new $O(this,e)}iterRange(e,t=this.length){return new Zr(this,e,t)}iterLines(e,t){let i;if(e==null)i=this.iter();else{t==null&&(t=this.lines+1);let r=this.line(e).from;i=this.iterRange(r,Math.max(r,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new _r(i)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?O.empty:e.length<=32?new Ce(e):WO.from(Ce.split(e,[]))}},Ce=class O extends A{constructor(e,t=um(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,i,r){for(let n=0;;n++){let s=this.text[n],a=r+s.length;if((t?i:a)>=e)return new gs(r,a,i,s);r=a+1,i++}}decompose(e,t,i,r){let n=e<=0&&t>=this.length?this:new O(wc(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(r&1){let s=i.pop(),a=Yr(n.text,s.text.slice(),0,n.length);if(a.length<=32)i.push(new O(a,s.length+n.length));else{let o=a.length>>1;i.push(new O(a.slice(0,o)),new O(a.slice(o)))}}else i.push(n)}replace(e,t,i){if(!(i instanceof O))return super.replace(e,t,i);[e,t]=CO(this,e,t);let r=Yr(this.text,Yr(i.text,wc(this.text,0,e)),t),n=this.length+i.length-(t-e);return r.length<=32?new O(r,n):WO.from(O.split(r,[]),n)}sliceString(e,t=this.length,i=`
`){[e,t]=CO(this,e,t);let r="";for(let n=0,s=0;n<=t&&s<this.text.length;s++){let a=this.text[s],o=n+a.length;n>e&&s&&(r+=i),e<o&&t>n&&(r+=a.slice(Math.max(0,e-n),t-n)),n=o+1}return r}flatten(e){for(let t of this.text)e.push(t)}scanIdentical(){return 0}static split(e,t){let i=[],r=-1;for(let n of e)i.push(n),r+=n.length+1,i.length==32&&(t.push(new O(i,r)),i=[],r=-1);return r>-1&&t.push(new O(i,r)),t}},WO=class O extends A{constructor(e,t){super(),this.children=e,this.length=t,this.lines=0;for(let i of e)this.lines+=i.lines}lineInner(e,t,i,r){for(let n=0;;n++){let s=this.children[n],a=r+s.length,o=i+s.lines-1;if((t?o:a)>=e)return s.lineInner(e,t,i,r);r=a+1,i=o+1}}decompose(e,t,i,r){for(let n=0,s=0;s<=t&&n<this.children.length;n++){let a=this.children[n],o=s+a.length;if(e<=o&&t>=s){let l=r&((s<=e?1:0)|(o>=t?2:0));s>=e&&o<=t&&!l?i.push(a):a.decompose(e-s,t-s,i,l)}s=o+1}}replace(e,t,i){if([e,t]=CO(this,e,t),i.lines<this.lines)for(let r=0,n=0;r<this.children.length;r++){let s=this.children[r],a=n+s.length;if(e>=n&&t<=a){let o=s.replace(e-n,t-n,i),l=this.lines-s.lines+o.lines;if(o.lines<l>>4&&o.lines>l>>6){let c=this.children.slice();return c[r]=o,new O(c,this.length-(t-e)+i.length)}return super.replace(n,a,o)}n=a+1}return super.replace(e,t,i)}sliceString(e,t=this.length,i=`
`){[e,t]=CO(this,e,t);let r="";for(let n=0,s=0;n<this.children.length&&s<=t;n++){let a=this.children[n],o=s+a.length;s>e&&n&&(r+=i),e<o&&t>s&&(r+=a.sliceString(e-s,t-s,i)),s=o+1}return r}flatten(e){for(let t of this.children)t.flatten(e)}scanIdentical(e,t){if(!(e instanceof O))return 0;let i=0,[r,n,s,a]=t>0?[0,0,this.children.length,e.children.length]:[this.children.length-1,e.children.length-1,-1,-1];for(;;r+=t,n+=t){if(r==s||n==a)return i;let o=this.children[r],l=e.children[n];if(o!=l)return i+o.scanIdentical(l,t);i+=o.length+1}}static from(e,t=e.reduce((i,r)=>i+r.length+1,-1)){let i=0;for(let f of e)i+=f.lines;if(i<32){let f=[];for(let d of e)d.flatten(f);return new Ce(f,t)}let r=Math.max(32,i>>5),n=r<<1,s=r>>1,a=[],o=0,l=-1,c=[];function h(f){let d;if(f.lines>n&&f instanceof O)for(let u of f.children)h(u);else f.lines>s&&(o>s||!o)?($(),a.push(f)):f instanceof Ce&&o&&(d=c[c.length-1])instanceof Ce&&f.lines+d.lines<=32?(o+=f.lines,l+=f.length+1,c[c.length-1]=new Ce(d.text.concat(f.text),d.length+1+f.length)):(o+f.lines>r&&$(),o+=f.lines,l+=f.length+1,c.push(f))}function $(){o!=0&&(a.push(c.length==1?c[0]:O.from(c,l)),l=-1,o=c.length=0)}for(let f of e)h(f);return $(),a.length==1?a[0]:new O(a,t)}};A.empty=new Ce([""],0);function um(O){let e=-1;for(let t of O)e+=t.length+1;return e}function Yr(O,e,t=0,i=1e9){for(let r=0,n=0,s=!0;n<O.length&&r<=i;n++){let a=O[n],o=r+a.length;o>=t&&(o>i&&(a=a.slice(0,i-r)),r<t&&(a=a.slice(t-r)),s?(e[e.length-1]+=a,s=!1):e.push(a)),r=o+1}return e}function wc(O,e,t){return Yr(O,[""],e,t)}var $O=class{constructor(e,t=1){this.dir=t,this.done=!1,this.lineBreak=!1,this.value="",this.nodes=[e],this.offsets=[t>0?1:(e instanceof Ce?e.text.length:e.children.length)<<1]}nextInner(e,t){for(this.done=this.lineBreak=!1;;){let i=this.nodes.length-1,r=this.nodes[i],n=this.offsets[i],s=n>>1,a=r instanceof Ce?r.text.length:r.children.length;if(s==(t>0?a:0)){if(i==0)return this.done=!0,this.value="",this;t>0&&this.offsets[i-1]++,this.nodes.pop(),this.offsets.pop()}else if((n&1)==(t>0?0:1)){if(this.offsets[i]+=t,e==0)return this.lineBreak=!0,this.value=`
`,this;e--}else if(r instanceof Ce){let o=r.text[s+(t<0?-1:0)];if(this.offsets[i]+=t,o.length>Math.max(0,e))return this.value=e==0?o:t>0?o.slice(e):o.slice(0,o.length-e),this;e-=o.length}else{let o=r.children[s+(t<0?-1:0)];e>o.length?(e-=o.length,this.offsets[i]+=t):(t<0&&this.offsets[i]--,this.nodes.push(o),this.offsets.push(t>0?1:(o instanceof Ce?o.text.length:o.children.length)<<1))}}}next(e=0){return e<0&&(this.nextInner(-e,-this.dir),e=this.value.length),this.nextInner(e,this.dir)}},Zr=class{constructor(e,t,i){this.value="",this.done=!1,this.cursor=new $O(e,t>i?-1:1),this.pos=t>i?e.length:0,this.from=Math.min(t,i),this.to=Math.max(t,i)}nextInner(e,t){if(t<0?this.pos<=this.from:this.pos>=this.to)return this.value="",this.done=!0,this;e+=Math.max(0,t<0?this.pos-this.to:this.from-this.pos);let i=t<0?this.pos-this.from:this.to-this.pos;e>i&&(e=i),i-=e;let{value:r}=this.cursor.next(e);return this.pos+=(r.length+e)*t,this.value=r.length<=i?r:t<0?r.slice(r.length-i):r.slice(0,i),this.done=!this.value,this}next(e=0){return e<0?e=Math.max(e,this.from-this.pos):e>0&&(e=Math.min(e,this.to-this.pos)),this.nextInner(e,this.cursor.dir)}get lineBreak(){return this.cursor.lineBreak&&this.value!=""}},_r=class{constructor(e){this.inner=e,this.afterBreak=!0,this.value="",this.done=!1}next(e=0){let{done:t,lineBreak:i,value:r}=this.inner.next(e);return t&&this.afterBreak?(this.value="",this.afterBreak=!1):t?(this.done=!0,this.value=""):i?this.afterBreak?this.value="":(this.afterBreak=!0,this.next()):(this.value=r,this.afterBreak=!1),this}get lineBreak(){return!1}};typeof Symbol<"u"&&(A.prototype[Symbol.iterator]=function(){return this.iter()},$O.prototype[Symbol.iterator]=Zr.prototype[Symbol.iterator]=_r.prototype[Symbol.iterator]=function(){return this});var gs=class{constructor(e,t,i,r){this.from=e,this.to=t,this.number=i,this.text=r}get length(){return this.to-this.from}};function CO(O,e,t){return e=Math.max(0,Math.min(O.length,e)),[e,Math.max(e,Math.min(O.length,t))]}var UO="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,3b,f,,w,1j,,,,4,8,4,,3,7,a,2,t,,1m,,,,2,4,8,,9,,a,2,q,,2,2,1l,,4,2,4,2,2,3,3,,u,2,3,,b,2,1l,,4,5,,2,4,,k,2,m,6,,,1m,,,2,,4,8,,7,3,a,2,u,,1n,,,,c,,9,,14,,3,,1l,3,5,3,,4,7,2,b,2,t,,1m,,2,,2,,3,,5,2,7,2,b,2,s,2,1l,2,,,2,4,8,,9,,a,2,t,,20,,4,,2,3,,,8,,29,,2,7,c,8,2q,,2,9,b,6,22,2,r,,,,,,1j,e,,5,,2,5,b,,10,9,,2u,4,,6,,2,2,2,p,2,4,3,g,4,d,,2,2,6,,f,,jj,3,qa,3,t,3,t,2,u,2,1s,2,,7,8,,2,b,9,,19,3,3b,2,y,,3a,3,4,2,9,,6,3,63,2,2,,1m,,,7,,,,,2,8,6,a,2,,1c,h,1r,4,1c,7,,,5,,14,9,c,2,w,4,2,2,,3,1k,,,2,3,,,3,1m,8,2,2,48,3,,d,,7,4,,6,,3,2,5i,1m,,5,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,p,2,5,,47,2,q,i,d,,12,8,p,b,1a,3,1c,,2,4,2,2,13,,1v,6,2,2,2,2,c,,8,,1b,,1f,,,3,2,2,5,2,,,16,2,8,,6m,,2,,4,,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,ar,2,49,b,4w,,1i,f,1k,3,1d,4,2,2,1x,3,10,5,,8,1q,,c,2,1g,9,a,4,2,,2n,3,2,,,2,6,,4g,,3,8,l,2,1l,2,,,,,m,,e,7,3,5,5f,8,2,3,,,n,,29,,2,6,,,2,,,2,,2,6j,,2,4,6,2,,2,r,2,2d,8,2,,,2,2y,,,,2,6,,,2t,3,2,4,,5,77,9,,2,6t,,a,2,,,4,,40,4,2,2,4,,w,a,14,6,2,4,8,,9,6,2,3,1a,d,,2,ba,7,,6,,,2a,m,2,7,,2,,2,3e,6,3,,,2,,7,,,20,2,3,,,,9n,2,f0b,5,1n,7,t4,,1r,4,29,,f5k,2,43q,,,3,4,5,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,79,7,c5,4,15s,7,31,7,240,5,gx7k,2o,3k,6o".split(",").map(O=>O?parseInt(O,36):1);for(let O=1;O<UO.length;O++)UO[O]+=UO[O-1];function pm(O){for(let e=1;e<UO.length;e+=2)if(UO[e]>O)return UO[e-1]<=O;return!1}function bc(O){return O>=127462&&O<=127487}var xc=8205;function Qe(O,e,t=!0,i=!0){return(t?Rc:mm)(O,e,i)}function Rc(O,e,t){if(e==O.length)return e;e&&zc(O.charCodeAt(e))&&Vc(O.charCodeAt(e-1))&&e--;let i=de(O,e);for(e+=be(i);e<O.length;){let r=de(O,e);if(i==xc||r==xc||t&&pm(r))e+=be(r),i=r;else if(bc(r)){let n=0,s=e-2;for(;s>=0&&bc(de(O,s));)n++,s-=2;if(n%2==0)break;e+=2}else break}return e}function mm(O,e,t){for(;e>0;){let i=Rc(O,e-2,t);if(i<e)return i;e--}return 0}function zc(O){return O>=56320&&O<57344}function Vc(O){return O>=55296&&O<56320}function de(O,e){let t=O.charCodeAt(e);if(!Vc(t)||e+1==O.length)return t;let i=O.charCodeAt(e+1);return zc(i)?(t-55296<<10)+(i-56320)+65536:t}function Pi(O){return O<=65535?String.fromCharCode(O):(O-=65536,String.fromCharCode((O>>10)+55296,(O&1023)+56320))}function be(O){return O<65536?1:2}var Ps=/\r\n?|\n/,ue=function(O){return O[O.Simple=0]="Simple",O[O.TrackDel=1]="TrackDel",O[O.TrackBefore=2]="TrackBefore",O[O.TrackAfter=3]="TrackAfter",O}(ue||(ue={})),kt=class O{constructor(e){this.sections=e}get length(){let e=0;for(let t=0;t<this.sections.length;t+=2)e+=this.sections[t];return e}get newLength(){let e=0;for(let t=0;t<this.sections.length;t+=2){let i=this.sections[t+1];e+=i<0?this.sections[t]:i}return e}get empty(){return this.sections.length==0||this.sections.length==2&&this.sections[1]<0}iterGaps(e){for(let t=0,i=0,r=0;t<this.sections.length;){let n=this.sections[t++],s=this.sections[t++];s<0?(e(i,r,n),r+=n):r+=s,i+=n}}iterChangedRanges( Line truncated
`}get readOnly(){return this.facet(Ac)}phrase(e,...t){for(let i of this.facet(O.phrases))if(Object.prototype.hasOwnProperty.call(i,e)){e=i[e];break}return t.length&&(e=e.replace(/\$(\$|\d*)/g,(i,r)=>{if(r=="$")return"$";let n=+(r||1);return!n||n>t.length?i:t[n-1]})),e}languageDataAt(e,t,i=-1){let r=[];for(let n of this.facet(Uc))for(let s of n(this,t,i))Object.prototype.hasOwnProperty.call(s,e)&&r.push(s[e]);return r}charCategorizer(e){return xm(this.languageDataAt("wordChars",e).join(""))}wordAt(e){let{text:t,from:i,length:r}=this.doc.lineAt(e),n=this.charCategorizer(e),s=e-i,a=e-i;for(;s>0;){let o=Qe(t,s,!1);if(n(t.slice(o,s))!=H.Word)break;s=o}for(;a<r;){let o=Qe(t,a);if(n(t.slice(a,o))!=H.Word)break;a=o}return s==a?null:P.range(s+i,a+i)}};K.allowMultipleSelections=ys;K.tabSize=v.define({combine:O=>O.length?O[0]:4});K.lineSeparator=jc;K.readOnly=Ac;K.phrases=v.define({compare(O,e){let t=Object.keys(O),i=Object.keys(e);return t.length==i.length&&t.every(r=>O[r]==e[r])}});K.languageData=Uc;K.changeFilter=Gc;K.transactionFilter=Cc;K.transactionExtender=Ec;ui.reconfigure=j.define();function Ee(O,e,t={}){let i={};for(let r of O)for(let n of Object.keys(r)){let s=r[n],a=i[n];if(a===void 0)i[n]=s;else if(!(a===s||s===void 0))if(Object.hasOwnProperty.call(t,n))i[n]=t[n](a,s);else throw new Error("Config merge conflict for field "+n)}for(let r in e)i[r]===void 0&&(i[r]=e[r]);return i}var nt=class{eq(e){return this==e}range(e,t=e){return mi.create(e,t,this)}};nt.prototype.startSide=nt.prototype.endSide=0;nt.prototype.point=!1;nt.prototype.mapMode=ue.TrackDel;var mi=class O{constructor(e,t,i){this.from=e,this.to=t,this.value=i}static create(e,t,i){return new O(e,t,i)}};function vs(O,e){return O.from-e.from||O.value.startSide-e.value.startSide}var Ys=class O{constructor(e,t,i,r){this.from=e,this.to=t,this.value=i,this.maxPoint=r}get length(){return this.to[this.to.length-1]}findIndex(e,t,i,r=0){let n=i?this.to:this.from;for(let s=r,a=n.length;;){if(s==a)return s;let o=s+a>>1,l=n[o]-e||(i?this.value[o].endSide:this.value[o].startSide)-t;if(o==s)return l>=0?s:a;l>=0?a=o:s=o+1}}between(e,t,i,r){for(let n=this.findIndex(t,-1e9,!0),s=this.findIndex(i,1e9,!1,n);n<s;n++)if(r(this.from[n]+e,this.to[n]+e,this.value[n])===!1)return!1}map(e,t){let i=[],r=[],n=[],s=-1,a=-1;for(let o=0;o<this.value.length;o++){let l=this.value[o],c=this.from[o]+e,h=this.to[o]+e,$,f;if(c==h){let d=t.mapPos(c,l.startSide,l.mapMode);if(d==null||($=f=d,l.startSide!=l.endSide&&(f=t.mapPos(c,l.endSide),f<$)))continue}else if($=t.mapPos(c,l.startSide),f=t.mapPos(h,l.endSide),$>f||$==f&&l.startSide>0&&l.endSide<=0)continue;(f-$||l.endSide-l.startSide)<0||(s<0&&(s=$),l.point&&(a=Math.max(a,f-$)),i.push(l),r.push($-s),n.push(f-s))}return{mapped:i.length?new O(r,n,i,a):null,pos:s}}},N=class O{constructor(e,t,i,r){this.chunkPos=e,this.chunk=t,this.nextLayer=i,this.maxPoint=r}static create(e,t,i,r){return new O(e,t,i,r)}get length(){let e=this.chunk.length-1;return e<0?0:Math.max(this.chunkEnd(e),this.nextLayer.length)}get size(){if(this.isEmpty)return 0;let e=this.nextLayer.size;for(let t of this.chunk)e+=t.value.length;return e}chunkEnd(e){return this.chunkPos[e]+this.chunk[e].length}update(e){let{add:t=[],sort:i=!1,filterFrom:r=0,filterTo:n=this.length}=e,s=e.filter;if(t.length==0&&!s)return this;if(i&&(t=t.slice().sort(vs)),this.isEmpty)return t.length?O.of(t):this;let a=new qr(this,null,-1).goto(0),o=0,l=[],c=new ft;for(;a.value||o<t.length;)if(o<t.length&&(a.from-t[o].from||a.startSide-t[o].value.startSide)>=0){let h=t[o++];c.addInner(h.from,h.to,h.value)||l.push(h)}else a.rangeIndex==1&&a.chunkIndex<this.chunk.length&&(o==t.length||this.chunkEnd(a.chunkIndex)<t[o].from)&&(!s||r>this.chunkEnd(a.chunkIndex)||n<this.chunkPos[a.chunkIndex])&&c.addChunk(this.chunkPos[a.chunkIndex],this.chunk[a.chunkIndex])?a.nextChunk():((!s||r>a.to||n<a.from||s(a.from,a.to,a.value))&&(c.addInner(a.from,a.to,a.value)||l.push(mi.create(a.from,a.to,a.value))),a.next());return c.finishInner(this.nextLayer.isEmpty&&!l.length?O.empty:this.nextLayer.update({add:l,filter:s,filterFrom:r,filterTo:n}))}map(e){if(e.empty||this.isEmpty)return this;let t=[],i=[],r=-1;for(let s=0;s<this.chunk.length;s++){let a=this.chunkPos[s],o=this.chunk[s],l=e.touchesRange(a,a+o.length);if(l===!1)r=Math.max(r,o.maxPoint),t.push(o),i.push(e.mapPos(a));else if(l===!0){let{mapped:c,pos:h}=o.map(a,e);c&&(r=Math.max(r,c.maxPoint),t.push(c),i.push(h))}}let n=this.nextLayer.map(e);return t.length==0?n:new O(i,t,n||O.empty,r)}between(e,t,i){if(!this.isEmpty){for(let r=0;r<this.chunk.length;r++){let n=this.chunkPos[r],s=this.chunk[r];if(t>=n&&e<=n+s.length&&s.between(n,e-n,t-n,i)===!1)return}this.nextLayer.between(e,t,i)}}iter(e=0){return gi.from([this]).goto(e)}get isEmpty(){return this.nextLayer==this}static iter(e,t=0){return gi.from(e).goto(t)}static compare(e,t,i,r,n=-1){let s=e.filter(h=>h.maxPoint>0||!h.isEmpty&&h.maxPoint>=n),a=t.filter(h=>h.maxPoint>0||!h.isEmpty&&h.maxPoint>=n),o=Yc(s,a,i),l=new QO Line truncated
`)}static newName(){let e=Bc[Ic]||1;return Bc[Ic]=e+1,zs+e.toString(36)}static mount(e,t,i){let r=e[Vs],n=i&&i.nonce;r?n&&r.setNonce(n):r=new qs(e,n),r.mount(Array.isArray(t)?t:[t],e)}},Nc=new Map,qs=class{constructor(e,t){let i=e.ownerDocument||e,r=i.defaultView;if(!e.head&&e.adoptedStyleSheets&&r.CSSStyleSheet){let n=Nc.get(i);if(n)return e[Vs]=n;this.sheet=new r.CSSStyleSheet,Nc.set(i,this)}else this.styleTag=i.createElement("style"),t&&this.styleTag.setAttribute("nonce",t);this.modules=[],e[Vs]=this}mount(e,t){let i=this.sheet,r=0,n=0;for(let s=0;s<e.length;s++){let a=e[s],o=this.modules.indexOf(a);if(o<n&&o>-1&&(this.modules.splice(o,1),n--,o=-1),o==-1){if(this.modules.splice(n++,0,a),i)for(let l=0;l<a.rules.length;l++)i.insertRule(a.rules[l],r++)}else{for(;n<o;)r+=this.modules[n++].rules.length;r+=a.rules.length,n++}}if(i)t.adoptedStyleSheets.indexOf(this.sheet)<0&&(t.adoptedStyleSheets=[this.sheet,...t.adoptedStyleSheets]);else{let s="";for(let o=0;o<this.modules.length;o++)s+=this.modules[o].getRules()+`
`;this.styleTag.textContent=s;let a=t.head||t;this.styleTag.parentNode!=a&&a.insertBefore(this.styleTag,a.firstChild)}}setNonce(e){this.styleTag&&this.styleTag.getAttribute("nonce")!=e&&this.styleTag.setAttribute("nonce",e)}};var vt={8:"Backspace",9:"Tab",10:"Enter",12:"NumLock",13:"Enter",16:"Shift",17:"Control",18:"Alt",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",44:"PrintScreen",45:"Insert",46:"Delete",59:";",61:"=",91:"Meta",92:"Meta",106:"*",107:"+",108:",",109:"-",110:".",111:"/",144:"NumLock",145:"ScrollLock",160:"Shift",161:"Shift",162:"Control",163:"Control",164:"Alt",165:"Alt",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'"},EO={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},vm=typeof navigator<"u"&&/Mac/.test(navigator.platform),Ym=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);for(fe=0;fe<10;fe++)vt[48+fe]=vt[96+fe]=String(fe);var fe;for(fe=1;fe<=24;fe++)vt[fe+111]="F"+fe;var fe;for(fe=65;fe<=90;fe++)vt[fe]=String.fromCharCode(fe+32),EO[fe]=String.fromCharCode(fe);var fe;for(Wr in vt)EO.hasOwnProperty(Wr)||(EO[Wr]=vt[Wr]);var Wr;function Fc(O){var e=vm&&O.metaKey&&O.shiftKey&&!O.ctrlKey&&!O.altKey||Ym&&O.shiftKey&&O.key&&O.key.length==1||O.key=="Unidentified",t=!e&&O.key||(O.shiftKey?EO:vt)[O.keyCode]||O.key||"Unidentified";return t=="Esc"&&(t="Escape"),t=="Del"&&(t="Delete"),t=="Left"&&(t="ArrowLeft"),t=="Up"&&(t="ArrowUp"),t=="Right"&&(t="ArrowRight"),t=="Down"&&(t="ArrowDown"),t}function Hr(O){let e;return O.nodeType==11?e=O.getSelection?O:O.ownerDocument:e=O,e.getSelection()}function As(O,e){return e?O==e||O.contains(e.nodeType!=1?e.parentNode:e):!1}function Zm(O){let e=O.activeElement;for(;e&&e.shadowRoot;)e=e.shadowRoot.activeElement;return e}function Dr(O,e){if(!e.anchorNode)return!1;try{return As(O,e.anchorNode)}catch{return!1}}function Ri(O){return O.nodeType==3?dO(O,0,O.nodeValue.length).getClientRects():O.nodeType==1?O.getClientRects():[]}function bi(O,e,t,i){return t?Hc(O,e,t,i,-1)||Hc(O,e,t,i,1):!1}function zi(O){for(var e=0;;e++)if(O=O.previousSibling,!O)return e}function Hc(O,e,t,i,r){for(;;){if(O==t&&e==i)return!0;if(e==(r<0?0:Yt(O))){if(O.nodeName=="DIV")return!1;let n=O.parentNode;if(!n||n.nodeType!=1)return!1;e=zi(O)+(r<0?0:1),O=n}else if(O.nodeType==1){if(O=O.childNodes[e+(r<0?-1:0)],O.nodeType==1&&O.contentEditable=="false")return!1;e=r<0?Yt(O):0}else return!1}}function Yt(O){return O.nodeType==3?O.nodeValue.length:O.childNodes.length}function wa(O,e){let t=e?O.left:O.right;return{left:t,right:t,top:O.top,bottom:O.bottom}}function _m(O){let e=O.visualViewport;return e?{left:0,right:e.width,top:0,bottom:e.height}:{left:0,right:O.innerWidth,top:0,bottom:O.innerHeight}}function zh(O,e){let t=e.width/O.offsetWidth,i=e.height/O.offsetHeight;return(t>.995&&t<1.005||!isFinite(t)||Math.abs(e.width-O.offsetWidth)<1)&&(t=1),(i>.995&&i<1.005||!isFinite(i)||Math.abs(e.height-O.offsetHeight)<1)&&(i=1),{scaleX:t,scaleY:i}}function Rm(O,e,t,i,r,n,s,a){let o=O.ownerDocument,l=o.defaultView||window;for(let c=O,h=!1;c&&!h;)if(c.nodeType==1){let $,f=c==o.body,d=1,u=1;if(f)$=_m(l);else{if(/^(fixed|sticky)$/.test(getComputedStyle(c).position)&&(h=!0),c.scrollHeight<=c.clientHeight&&c.scrollWidth<=c.clientWidth){c=c.assignedSlot||c.parentNode;continue}let g=c.getBoundingClientRect();({scaleX:d,scaleY:u}=zh(c,g)),$={left:g.left,right:g.left+c.clientWidth*d,top:g.top,bottom:g.top+c.clientHeight*u}}let p=0,m=0;if(r=="nearest")e.top<$.top?(m=-($.top-e.top+s),t>0&&e.bottom>$.bottom+m&&(m=e.bottom-$.bottom+m+s)):e.bottom>$.bottom&&(m=e.bottom-$.bottom+s,t<0&&e.top-m<$.top&&(m=-($.top+m-e.top+s)));else{let g=e.bottom-e.top,X=$.bottom-$.top;m=(r=="center"&&g<=X?e.top+g/2-X/2:r=="start"||r=="center"&&t<0?e.top-s:e.bottom-X+s)-$.top}if(i=="nearest"?e.left<$.left?(p=-($.left-e.left+n),t>0&&e.right>$.right+p&&(p=e.right-$.right+p+n)):e.right>$.right&&(p=e.right-$.right+n,t<0&&e.left<$.left+p&&(p=-($.left+p-e.left+n))):p=(i=="center"?e.left+(e.right-e.left)/2-($.right-$.left)/2:i=="start"==a?e.left-n:e.right-($.right-$.left)+n)-$.left,p||m)if(f)l.scrollBy(p,m);else{let g=0,X=0;if(m){let T=c.scrollTop;c.scrollTop+=m/u,X=(c.scrollTop-T)*u}if(p){let T=c.scrollLeft;c.scrollLeft+=p/d,g=(c.scrollLeft-T)*d}e={left:e.left-g,top:e.top-X,right:e.right-g,bottom:e.bottom-X},g&&Math.abs(g-p)<1&&(i="nearest"),X&&Math.abs(X-m)<1&&(r="nearest")}if(f)break;c=c.assignedSlot||c.parentNode}else if(c.nodeType==11)c=c.host;else break}function zm(O){let e=O.ownerDocument;for(let t=O.parentNode;t&&t!=e.body;)if(t.nodeType==1){if(t.scrollHeight>t.clientHeight||t.scrollWidth>t.clientWidth)return t;t=t.assignedSlot||t.parentNode}else if(t.nodeType==11)t=t.host;else break;return null}var Ls=class{constructor(){this.aLine truncated
`,r=O.state.doc.line(r.number+(t?1:-1)),n=O.bidiSpans(r),l=O.visualLineSide(r,!t)}if(o){if(!o(c))return a}else{if(!i)return l;o=i(c)}a=l}}function Qg(O,e,t){let i=O.state.charCategorizer(e),r=i(t);return n=>{let s=i(n);return r==H.Space&&(r=s),r==s}}function $g(O,e,t,i){let r=e.head,n=t?1:-1;if(r==(t?O.state.doc.length:0))return P.cursor(r,e.assoc);let s=e.goalColumn,a,o=O.contentDOM.getBoundingClientRect(),l=O.coordsAtPos(r,e.assoc||-1),c=O.documentTop;if(l)s==null&&(s=l.left-o.left),a=n<0?l.top:l.bottom;else{let f=O.viewState.lineBlockAt(r);s==null&&(s=Math.min(o.right-o.left,O.defaultCharacterWidth*(r-f.from))),a=(n<0?f.top:f.bottom)+c}let h=o.left+s,$=i??O.viewState.heightOracle.textHeight>>1;for(let f=0;;f+=10){let d=a+($+f)*n,u=$Q(O,{x:h,y:d},!1,n);if(d<o.top||d>o.bottom||(n<0?u<r:u>r)){let p=O.docView.coordsForChar(u),m=!p||d<p.top?-1:1;return P.cursor(u,m,void 0,s)}}}function Ir(O,e,t){for(;;){let i=0;for(let r of O)r.between(e-1,e+1,(n,s,a)=>{if(e>n&&e<s){let o=i||t||(e-n<s-e?-1:1);e=o<0?n:s,i=o}});if(!i)return e}}function js(O,e,t){let i=Ir(O.state.facet(Ya).map(r=>r(O)),t.from,e.head>t.from?-1:1);return i==t.from?t:P.cursor(i,i<t.from?1:-1)}var ia=class{setSelectionOrigin(e){this.lastSelectionOrigin=e,this.lastSelectionTime=Date.now()}constructor(e){this.view=e,this.lastKeyCode=0,this.lastKeyTime=0,this.lastTouchTime=0,this.lastFocusTime=0,this.lastScrollTop=0,this.lastScrollLeft=0,this.pendingIOSKey=void 0,this.lastSelectionOrigin=null,this.lastSelectionTime=0,this.lastEscPress=0,this.lastContextMenu=0,this.scrollHandlers=[],this.handlers=Object.create(null),this.composing=-1,this.compositionFirstChange=null,this.compositionEndedAt=0,this.compositionPendingKey=!1,this.compositionPendingChange=!1,this.mouseSelection=null,this.draggedContent=null,this.handleEvent=this.handleEvent.bind(this),this.notifiedFocused=e.hasFocus,Y.safari&&e.contentDOM.addEventListener("input",()=>null),Y.gecko&&kg(e.contentDOM.ownerDocument)}handleEvent(e){!Pg(this.view,e)||this.ignoreDuringComposition(e)||e.type=="keydown"&&this.keydown(e)||this.runHandlers(e.type,e)}runHandlers(e,t){let i=this.handlers[e];if(i){for(let r of i.observers)r(this.view,t);for(let r of i.handlers){if(t.defaultPrevented)break;if(r(this.view,t)){t.preventDefault();break}}}}ensureHandlers(e){let t=fg(e),i=this.handlers,r=this.view.contentDOM;for(let n in t)if(n!="scroll"){let s=!t[n].handlers.length,a=i[n];a&&s!=!a.handlers.length&&(r.removeEventListener(n,this.handleEvent),a=null),a||r.addEventListener(n,this.handleEvent,{passive:s})}for(let n in i)n!="scroll"&&!t[n]&&r.removeEventListener(n,this.handleEvent);this.handlers=t}keydown(e){if(this.lastKeyCode=e.keyCode,this.lastKeyTime=Date.now(),e.keyCode==9&&Date.now()<this.lastEscPress+2e3)return!0;if(e.keyCode!=27&&dQ.indexOf(e.keyCode)<0&&(this.view.inputState.lastEscPress=0),Y.android&&Y.chrome&&!e.synthetic&&(e.keyCode==13||e.keyCode==8))return this.view.observer.delayAndroidKey(e.key,e.keyCode),!0;let t;return Y.ios&&!e.synthetic&&!e.altKey&&!e.metaKey&&((t=fQ.find(i=>i.keyCode==e.keyCode))&&!e.ctrlKey||dg.indexOf(e.key)>-1&&e.ctrlKey&&!e.shiftKey)?(this.pendingIOSKey=t||e,setTimeout(()=>this.flushIOSKey(),250),!0):(e.keyCode!=229&&this.view.observer.forceFlush(),!1)}flushIOSKey(e){let t=this.pendingIOSKey;return!t||t.key=="Enter"&&e&&e.from<e.to&&/^\S+$/.test(e.insert.toString())?!1:(this.pendingIOSKey=void 0,IO(this.view.contentDOM,t.key,t.keyCode,t instanceof KeyboardEvent?t:void 0))}ignoreDuringComposition(e){return/^key/.test(e.type)?this.composing>0?!0:Y.safari&&!Y.ios&&this.compositionPendingKey&&Date.now()-this.compositionEndedAt<100?(this.compositionPendingKey=!1,!0):!1:!1}startMouseSelection(e){this.mouseSelection&&this.mouseSelection.destroy(),this.mouseSelection=e}update(e){this.mouseSelection&&this.mouseSelection.update(e),this.draggedContent&&e.docChanged&&(this.draggedContent=this.draggedContent.map(e.changes)),e.transactions.length&&(this.lastKeyCode=this.lastSelectionTime=0)}destroy(){this.mouseSelection&&this.mouseSelection.destroy()}};function ch(O,e){return(t,i)=>{try{return e.call(O,i,t)}catch(r){ve(t.state,r)}}}function fg(O){let e=Object.create(null);function t(i){return e[i]||(e[i]={observers:[],handlers:[]})}for(let i of O){let r=i.spec;if(r&&r.domEventHandlers)for(let n in r.domEventHandlers){let s=r.domEventHandlers[n];s&&t(n).handlers.push(ch(i.value,s))}if(r&&r.domEventObservers)for(let n in r.domEventObservers){let s=r.domEventObservers[n];s&&t(n).observers.push(ch(i.value,s))}}for(let i in st)t(i).handlers.push(st[i]);for(let i in at)t(i).observers.push(at[i]);return e}var fQ=[{key:"Backspace",keyCode:8,inputType:"deleteContentBackward"},{key:"Enter",keyCode:13,inputType:"insertParagraph"},{key:"Enter",keyCode:13,inputType:"insertLineBreak"},{key:"Delete",keyCode:46,inputType:"deleteContentForward"}],dg="dthko",dQ=[16,17,18,20,91,92,224,225],Gr=6;function Cr(O){return Math.max(0,O)*.7+8}function ug(O,e){return Math.max(Math.abs(O.clientX-e.clientX),Math.abs( Line truncated
`&&O.lineWrapping&&(i&&(i=P.single(i.main.anchor-1,i.main.head-1)),t={from:r.from,to:r.to,insert:A.of([" "])}),t){if(Y.ios&&O.inputState.flushIOSKey(t)||Y.android&&(t.to==r.to&&(t.from==r.from||t.from==r.from-1&&O.state.sliceDoc(t.from,r.from)==" ")&&t.insert.length==1&&t.insert.lines==2&&IO(O.contentDOM,"Enter",13)||(t.from==r.from-1&&t.to==r.to&&t.insert.length==0||n==8&&t.insert.length<t.to-t.from&&t.to>r.head)&&IO(O.contentDOM,"Backspace",8)||t.from==r.from&&t.to==r.to+1&&t.insert.length==0&&IO(O.contentDOM,"Delete",46)))return!0;let s=t.insert.toString();O.inputState.composing>=0&&O.inputState.composing++;let a,o=()=>a||(a=Wg(O,t,i));return O.state.facet(tQ).some(l=>l(O,t.from,t.to,s,o))||O.dispatch(o()),!0}else if(i&&!i.main.eq(r)){let s=!1,a="select";return O.inputState.lastSelectionTime>Date.now()-50&&(O.inputState.lastSelectionOrigin=="select"&&(s=!0),a=O.inputState.lastSelectionOrigin),O.dispatch({selection:i,scrollIntoView:s,userEvent:a}),!0}else return!1}function Wg(O,e,t){let i,r=O.state,n=r.selection.main;if(e.from>=n.from&&e.to<=n.to&&e.to-e.from>=(n.to-n.from)/3&&(!t||t.main.empty&&t.main.from==e.from+e.insert.length)&&O.inputState.composing<0){let a=n.from<e.from?r.sliceDoc(n.from,e.from):"",o=n.to>e.to?r.sliceDoc(e.to,n.to):"";i=r.replaceSelection(O.state.toText(a+e.insert.sliceString(0,void 0,O.state.lineBreak)+o))}else{let a=r.changes(e),o=t&&t.main.to<=a.newLength?t.main:void 0;if(r.selection.ranges.length>1&&O.inputState.composing>=0&&e.to<=n.to&&e.to>=n.to-10){let l=O.state.sliceDoc(e.from,e.to),c,h=t&&hQ(O,t.main.head);if(h){let d=e.insert.length-(e.to-e.from);c={from:h.from,to:h.to-d}}else c=O.state.doc.lineAt(n.head);let $=n.to-e.to,f=n.to-n.from;i=r.changeByRange(d=>{if(d.from==n.from&&d.to==n.to)return{changes:a,range:o||d.map(a)};let u=d.to-$,p=u-l.length;if(d.to-d.from!=f||O.state.sliceDoc(p,u)!=l||d.to>=c.from&&d.from<=c.to)return{range:d};let m=r.changes({from:p,to:u,insert:e.insert}),g=d.to-n.to;return{changes:m,range:o?P.range(Math.max(0,o.anchor+g),Math.max(0,o.head+g)):d.map(m)}})}else i={changes:a,selection:o&&r.selection.replaceRange(o)}}let s="input.type";return(O.composing||O.inputState.compositionPendingChange&&O.inputState.compositionEndedAt>Date.now()-50)&&(O.inputState.compositionPendingChange=!1,s+=".compose",O.inputState.compositionFirstChange&&(s+=".start",O.inputState.compositionFirstChange=!1)),r.update(i,{userEvent:s,scrollIntoView:!0})}function Ug(O,e,t,i){let r=Math.min(O.length,e.length),n=0;for(;n<r&&O.charCodeAt(n)==e.charCodeAt(n);)n++;if(n==r&&O.length==e.length)return null;let s=O.length,a=e.length;for(;s>0&&a>0&&O.charCodeAt(s-1)==e.charCodeAt(a-1);)s--,a--;if(i=="end"){let o=Math.max(0,n-Math.min(s,a));t-=s+o-n}if(s<n&&O.length<e.length){let o=t<=n&&t>=s?n-t:0;n-=o,a=n+(a-s),s=n}else if(a<n){let o=t<=n&&t>=a?n-t:0;n-=o,s=n+(s-a),a=n}return{from:n,toA:s,toB:a}}function jg(O){let e=[];if(O.root.activeElement!=O.contentDOM)return e;let{anchorNode:t,anchorOffset:i,focusNode:r,focusOffset:n}=O.observer.selectionRange;return t&&(e.push(new sn(t,i)),(r!=t||n!=i)&&e.push(new sn(r,n))),e}function Gg(O,e){if(O.length==0)return null;let t=O[0].pos,i=O.length==2?O[1].pos:t;return t>-1&&i>-1?P.single(t+e,i+e):null}var Cg={childList:!0,characterData:!0,subtree:!0,attributes:!0,characterDataOldValue:!0},Gs=Y.ie&&Y.ie_version<=11,ma=class{constructor(e){this.view=e,this.active=!1,this.selectionRange=new Ls,this.selectionChanged=!1,this.delayedFlush=-1,this.resizeTimeout=-1,this.queue=[],this.delayedAndroidKey=null,this.flushingAndroidKey=-1,this.lastChange=0,this.scrollTargets=[],this.intersection=null,this.resizeScroll=null,this.intersecting=!1,this.gapIntersection=null,this.gaps=[],this.printQuery=null,this.parentCheck=-1,this.dom=e.contentDOM,this.observer=new MutationObserver(t=>{for(let i of t)this.queue.push(i);(Y.ie&&Y.ie_version<=11||Y.ios&&e.composing)&&t.some(i=>i.type=="childList"&&i.removedNodes.length||i.type=="characterData"&&i.oldValue.length>i.target.nodeValue.length)?this.flushSoon():this.flush()}),Gs&&(this.onCharData=t=>{this.queue.push({target:t.target,type:"characterData",oldValue:t.prevValue}),this.flushSoon()}),this.onSelectionChange=this.onSelectionChange.bind(this),this.onResize=this.onResize.bind(this),this.onPrint=this.onPrint.bind(this),this.onScroll=this.onScroll.bind(this),window.matchMedia&&(this.printQuery=window.matchMedia("print")),typeof ResizeObserver=="function"&&(this.resizeScroll=new ResizeObserver(()=>{var t;((t=this.view.docView)===null||t===void 0?void 0:t.lastUpdate)<Date.now()-75&&this.onResize()}),this.resizeScroll.observe(e.scrollDOM)),this.addWindowListeners(this.win=e.win),this.start(),typeof IntersectionObserver=="function"&&(this.intersection=new IntersectionObserver(t=>{this.parentCheck<0&&(this.parentCheck=setTimeout(this.listenForScroll.bind(this),1e3)),t.length>0&&t[t.length-1].intersectionRatio>0!=this.intersecting&&(this.intersecting=!this.intersecting,this.intersecting!=this.view.inView&&this.onScrollChang Line truncated
`:i=="r"?"\r":i=="t"?" ":"\\")}eq(e){return this.search==e.search&&this.replace==e.replace&&this.caseSensitive==e.caseSensitive&&this.regexp==e.regexp&&this.wholeWord==e.wholeWord}create(){return this.regexp?new qo(this):new Vo(this)}getCursor(e,t=0,i){let r=e.doc?e:K.create({doc:e});return i==null&&(i=r.doc.length),this.regexp?ii(this,r,t,i):Oi(this,r,t,i)}},Mn=class{constructor(e){this.spec=e}};function Oi(O,e,t,i){return new sO(e.doc,O.unquoted,t,i,O.caseSensitive?void 0:r=>r.toLowerCase(),O.wholeWord?w1(e.doc,e.charCategorizer(e.selection.main.head)):void 0)}function w1(O,e){return(t,i,r,n)=>((n>t||n+r.length<i)&&(n=Math.max(0,t-2),r=O.sliceString(n,Math.min(O.length,i+2))),(e(Dn(r,t-n))!=H.Word||e(In(r,t-n))!=H.Word)&&(e(In(r,i-n))!=H.Word||e(Dn(r,i-n))!=H.Word))}var Vo=class extends Mn{constructor(e){super(e)}nextMatch(e,t,i){let r=Oi(this.spec,e,i,e.doc.length).nextOverlapping();return r.done&&(r=Oi(this.spec,e,0,t).nextOverlapping()),r.done?null:r.value}prevMatchInRange(e,t,i){for(let r=i;;){let n=Math.max(t,r-1e4-this.spec.unquoted.length),s=Oi(this.spec,e,n,r),a=null;for(;!s.nextOverlapping().done;)a=s.value;if(a)return a;if(n==t)return null;r-=1e4}}prevMatch(e,t,i){return this.prevMatchInRange(e,0,t)||this.prevMatchInRange(e,i,e.doc.length)}getReplacement(e){return this.spec.unquote(this.spec.replace)}matchAll(e,t){let i=Oi(this.spec,e,0,e.doc.length),r=[];for(;!i.next().done;){if(r.length>=t)return null;r.push(i.value)}return r}highlight(e,t,i,r){let n=Oi(this.spec,e,Math.max(0,t-this.spec.unquoted.length),Math.min(i+this.spec.unquoted.length,e.doc.length));for(;!n.next().done;)r(n.value.from,n.value.to)}};function ii(O,e,t,i){return new jn(e.doc,O.search,{ignoreCase:!O.caseSensitive,test:O.wholeWord?b1(e.charCategorizer(e.selection.main.head)):void 0},t,i)}function Dn(O,e){return O.slice(Qe(O,e,!1),e)}function In(O,e){return O.slice(e,Qe(O,e))}function b1(O){return(e,t,i)=>!i[0].length||(O(Dn(i.input,i.index))!=H.Word||O(In(i.input,i.index))!=H.Word)&&(O(In(i.input,i.index+i[0].length))!=H.Word||O(Dn(i.input,i.index+i[0].length))!=H.Word)}var qo=class extends Mn{nextMatch(e,t,i){let r=ii(this.spec,e,i,e.doc.length).next();return r.done&&(r=ii(this.spec,e,0,t).next()),r.done?null:r.value}prevMatchInRange(e,t,i){for(let r=1;;r++){let n=Math.max(t,i-r*1e4),s=ii(this.spec,e,n,i),a=null;for(;!s.next().done;)a=s.value;if(a&&(n==t||a.from>n+10))return a;if(n==t)return null}}prevMatch(e,t,i){return this.prevMatchInRange(e,0,t)||this.prevMatchInRange(e,i,e.doc.length)}getReplacement(e){return this.spec.unquote(this.spec.replace).replace(/\$([$&\d+])/g,(t,i)=>i=="$"?"$":i=="&"?e.match[0]:i!="0"&&+i<e.match.length?e.match[i]:t)}matchAll(e,t){let i=ii(this.spec,e,0,e.doc.length),r=[];for(;!i.next().done;){if(r.length>=t)return null;r.push(i.value)}return r}highlight(e,t,i,r){let n=ii(this.spec,e,Math.max(0,t-250),Math.min(i+250,e.doc.length));for(;!n.next().done;)r(n.value.from,n.value.to)}},ar=j.define(),Go=j.define(),nO=$e.define({create(O){return new sr(Wo(O).create(),null)},update(O,e){for(let t of e.effects)t.is(ar)?O=new sr(t.value.create(),O.panel):t.is(Go)&&(O=new sr(O.query,t.value?Co:null));return O},provide:O=>Ci.from(O,e=>e.panel)});var sr=class{constructor(e,t){this.query=e,this.panel=t}},x1=R.mark({class:"cm-searchMatch"}),k1=R.mark({class:"cm-searchMatch cm-searchMatch-selected"}),v1=pe.fromClass(class{constructor(O){this.view=O,this.decorations=this.highlight(O.state.field(nO))}update(O){let e=O.state.field(nO);(e!=O.startState.field(nO)||O.docChanged||O.selectionSet||O.viewportChanged)&&(this.decorations=this.highlight(e))}highlight({query:O,panel:e}){if(!e||!O.spec.valid)return R.none;let{view:t}=this,i=new ft;for(let r=0,n=t.visibleRanges,s=n.length;r<s;r++){let{from:a,to:o}=n[r];for(;r<s-1&&o>n[r+1].from-2*250;)o=n[++r].to;O.highlight(t.state,a,o,(l,c)=>{let h=t.state.selection.ranges.some($=>$.from==l&&$.to==c);i.add(l,c,h?k1:x1)})}return i.finish()}},{decorations:O=>O.decorations});function or(O){return e=>{let t=e.state.field(nO,!1);return t&&t.query.spec.valid?O(e,t):vf(e)}}var Bn=or((O,{query:e})=>{let{to:t}=O.state.selection.main,i=e.nextMatch(O.state,t,t);if(!i)return!1;let r=P.single(i.from,i.to),n=O.state.facet(ri);return O.dispatch({selection:r,effects:[Eo(O,i),n.scrollToMatch(r.main,O)],userEvent:"select.search"}),kf(O),!0}),Nn=or((O,{query:e})=>{let{state:t}=O,{from:i}=t.selection.main,r=e.prevMatch(t,i,i);if(!r)return!1;let n=P.single(r.from,r.to),s=O.state.facet(ri);return O.dispatch({selection:n,effects:[Eo(O,r),s.scrollToMatch(n.main,O)],userEvent:"select.search"}),kf(O),!0}),Y1=or((O,{query:e})=>{let t=e.matchAll(O.state,1e3);return!t||!t.length?!1:(O.dispatch({selection:P.create(t.map(i=>P.range(i.from,i.to))),userEvent:"select.search.matches"}),!0)}),Z1=({state:O,dispatch:e})=>{let t=O.selection;if(t.ranges.length>1||t.main.empty)return!1;let{from:i,to:r}=t.main,n=[],s=0;for(let a=new sO(O.doc,O.sliceDoc(i,r));!a.next().done;){if(n.length>1e3)return!1;a.value.from==i Line truncated
\${}
} catch (\${error}) {
\${}
}`,{label:"try",detail:"/ catch block",type:"keyword"}),W("if (${}) {\n ${}\n}",{label:"if",detail:"block",type:"keyword"}),W(`if (\${}) {
\${}
} else {
\${}
}`,{label:"if",detail:"/ else block",type:"keyword"}),W(`class \${name} {
constructor(\${params}) {
\${}
}
}`,{label:"class",detail:"definition",type:"keyword"}),W('import {${names}} from "${module}"\n${}',{label:"import",detail:"named",type:"keyword"}),W('import ${name} from "${module}"\n${}',{label:"import",detail:"default",type:"keyword"})],bT=Bf.concat([W("interface ${name} {\n ${}\n}",{label:"interface",detail:"definition",type:"keyword"}),W("type ${name} = ${type}",{label:"type",detail:"definition",type:"keyword"}),W("enum ${name} {\n ${}\n}",{label:"enum",detail:"definition",type:"keyword"})]),Mf=new Pt,Nf=new Set(["Script","Block","FunctionExpression","FunctionDeclaration","ArrowFunction","MethodDeclaration","ForStatement"]);function cr(O){return(e,t)=>{let i=e.node.getChild("VariableDefinition");return i&&t(i,O),!0}}var xT=["FunctionDeclaration"],kT={FunctionDeclaration:cr("function"),ClassDeclaration:cr("class"),ClassExpression:()=>!0,EnumDeclaration:cr("constant"),TypeAliasDeclaration:cr("type"),NamespaceDeclaration:cr("namespace"),VariableDefinition(O,e){O.matchContext(xT)||e(O,"variable")},TypeDefinition(O,e){e(O,"type")},__proto__:null};function Ff(O,e){let t=Mf.get(e);if(t)return t;let i=[],r=!0;function n(s,a){let o=O.sliceString(s.from,s.to);i.push({label:o,type:a})}return e.cursor(C.IncludeAnonymous).iterate(s=>{if(r)r=!1;else if(s.name){let a=kT[s.name];if(a&&a(s,n)||Nf.has(s.name))return!1}else if(s.to-s.from>8192){for(let a of Ff(O,s.node))i.push(a);return!1}}),Mf.set(e,i),i}var Df=/^[\w$\xa1-\uffff][\w$\d\xa1-\uffff]*$/,Hf=["TemplateString","String","RegExp","LineComment","BlockComment","VariableDefinition","TypeDefinition","Label","PropertyDefinition","PropertyName","PrivatePropertyDefinition","PrivatePropertyName",".","?."];function vT(O){let e=q(O.state).resolveInner(O.pos,-1);if(Hf.indexOf(e.name)>-1)return null;let t=e.name=="VariableName"||e.to-e.from<20&&Df.test(O.state.sliceDoc(e.from,e.to));if(!t&&!O.explicit)return null;let i=[];for(let r=e;r;r=r.parent)Nf.has(r.name)&&(i=i.concat(Ff(O.state.doc,r)));return{options:i,from:t?e.from:O.pos,validFor:Df}}var ht=re.define({name:"javascript",parser:Lf.configure({props:[ne.add({IfStatement:oe({except:/^\s*({|else\b)/}),TryStatement:oe({except:/^\s*({|catch\b|finally\b)/}),LabeledStatement:KO,SwitchBody:O=>{let e=O.textAfter,t=/^\s*\}/.test(e),i=/^\s*(case|default)\b/.test(e);return O.baseIndent+(t?0:i?1:2)*O.unit},Block:_e({closing:"}"}),ArrowFunction:O=>O.baseIndent+O.unit,"TemplateString BlockComment":()=>null,"Statement Property":oe({except:/^{/}),JSXElement(O){let e=/^\s*<\//.test(O.textAfter);return O.lineIndent(O.node.from)+(e?0:O.unit)},JSXEscape(O){let e=/\s*\}/.test(O.textAfter);return O.lineIndent(O.node.from)+(e?0:O.unit)},"JSXOpenTag JSXSelfClosingTag"(O){return O.column(O.node.from)+O.unit}}),J.add({"Block ClassBody SwitchBody EnumBody ObjectExpression ArrayExpression ObjectType":me,BlockComment(O){return{from:O.from+2,to:O.to-2}}})]}),languageData:{closeBrackets:{brackets:["(","[","{","'",'"',"`"]},commentTokens:{line:"//",block:{open:"/*",close:"*/"}},indentOnInput:/^\s*(?:case |default:|\{|\}|<\/)$/,wordChars:"$"}}),Kf={test:O=>/^JSX/.test(O.name),facet:Fi({commentTokens:{block:{open:"{/*",close:"*/}"}}})},rl=ht.configure({dialect:"ts"},"typescript"),nl=ht.configure({dialect:"jsx",props:[Tn.add(O=>O.isTop?[Kf]:void 0)]}),sl=ht.configure({dialect:"jsx ts",props:[Tn.add(O=>O.isTop?[Kf]:void 0)]},"typescript"),Jf=O=>({label:O,type:"keyword"}),ed="break case const continue default delete export extends false finally in instanceof let new return static super switch this throw true typeof var yield".split(" ").map(Jf),YT=ed.concat(["declare","implements","private","protected","public"].map(Jf));function hr(O={}){let e=O.jsx?O.typescript?sl:nl:O.typescript?rl:ht,t=O.typescript?bT.concat(YT):Bf.concat(ed);return new F(e,[ht.data.of({autocomplete:rO(Hf,Rt(t))}),ht.data.of({autocomplete:vT}),O.jsx?RT:[]])}function ZT(O){for(;;){if(O.name=="JSXOpenTag"||O.name=="JSXSelfClosingTag"||O.name=="JSXFragmentTag")return O;if(O.name=="JSXEscape"||!O.parent)return null;O=O.parent}}function If(O,e,t=O.length){for(let i=e?.firstChild;i;i=i.nextSibling)if(i.name=="JSXIdentifier"||i.name=="JSXBuiltin"||i.name=="JSXNamespacedName"||i.name=="JSXMemberExpression")return O.sliceString(i.from,Math.min(i.to,t));return""}var _T=typeof navigator=="object"&&/Android\b/.test(navigator.userAgent),RT=x.inputHandler.of((O,e,t,i,r)=>{if((_T?O.composing:O.compositionStarted)||O.state.readOnly||e!=t||i!=">"&&i!="/"||!ht.isActiveAt(O.state,e,-1))return!1;let n=r(),{state:s}=n,a=s.changeByRange(o=>{var l;let{head:c}=o,h=q(s).resolveInner(c-1,-1),$;if(h.name=="JSXStartTag"&&(h=h.parent),!(s.doc.sliceString(c-1,c)!=i||h.name=="JSXAttributeValue"&&h.to>c)){if(i==">"&&h.name=="JSXFragmentTag")return{range:o,changes:{from:c,insert:"</>"}};if(i=="/"&&h.name=="JSXStartCloseTag"){let f=h.parent,d=f.parent;if(d&&f.from==c-2&&(($=If(s.doc,d.firstChild,c))||((l=d.firstChild)===null||l===void 0?void 0:l.name)=="JSXFragmentTag")){let u=`${$}>`;return{range:P.cursor(c+u.length Line truncated
`,{label:"if",detail:"block",type:"keyword"}),W("if ${}:\n ${}\nelse:\n ${}",{label:"if",detail:"/ else block",type:"keyword"}),W("class ${name}:\n def __init__(self, ${params}):\n ${}",{label:"class",detail:"definition",type:"keyword"}),W("import ${module}",{label:"import",detail:"statement",type:"keyword"}),W("from ${module} import ${names}",{label:"from",detail:"import",type:"keyword"})],Iy=rO(Pd,Rt(My.concat(Dy)));function ud(O){let{node:e,pos:t}=O,i=O.lineIndent(t,-1),r=null;for(;;){let n=e.childBefore(t);if(n)if(n.name=="Comment")t=n.from;else if(n.name=="Body")O.baseIndentFor(n)+O.unit<=i&&(r=n),e=n;else if(n.type.is("Statement"))e=n;else break;else break}return r}function pd(O,e){let t=O.baseIndentFor(e),i=O.lineAt(O.pos,-1),r=i.from+i.text.length;return/^\s*($|#)/.test(i.text)&&O.node.to<r+100&&!/\S/.test(O.state.sliceDoc(r,O.node.to))&&O.lineIndent(O.pos,-1)<=t||/^\s*(else:|elif |except |finally:)/.test(O.textAfter)&&O.lineIndent(O.pos,-1)>t?null:t+O.unit}var Ql=re.define({name:"python",parser:$d.configure({props:[ne.add({Body:O=>{var e;let t=ud(O);return(e=pd(O,t||O.node))!==null&&e!==void 0?e:O.continue()},IfStatement:O=>/^\s*(else:|elif )/.test(O.textAfter)?O.baseIndent:O.continue(),"ForStatement WhileStatement":O=>/^\s*else:/.test(O.textAfter)?O.baseIndent:O.continue(),TryStatement:O=>/^\s*(except |finally:|else:)/.test(O.textAfter)?O.baseIndent:O.continue(),"TupleExpression ComprehensionExpression ParamList ArgList ParenthesizedExpression":_e({closing:")"}),"DictionaryExpression DictionaryComprehensionExpression SetExpression SetComprehensionExpression":_e({closing:"}"}),"ArrayExpression ArrayComprehensionExpression":_e({closing:"]"}),"String FormatString":()=>null,Script:O=>{var e;let t=ud(O);return(e=t&&pd(O,t))!==null&&e!==void 0?e:O.continue()}}),J.add({"ArrayExpression DictionaryExpression SetExpression TupleExpression":me,Body:(O,e)=>({from:O.from+1,to:O.to-(O.to==e.doc.length?0:1)})})]}),languageData:{closeBrackets:{brackets:["(","[","{","'",'"',"'''",'"""'],stringPrefixes:["f","fr","rf","r","u","b","br","rb","F","FR","RF","R","U","B","BR","RB"]},commentTokens:{line:"#"},indentOnInput:/^\s*([\}\]\)]|else:|elif |except |finally:)$/}});function Sd(){return new F(Ql,[Ql.data.of({autocomplete:Ly}),Ql.data.of({autocomplete:Iy})])}var rs=class O{static create(e,t,i,r,n){let s=r+(r<<8)+e+(t<<4)|0;return new O(e,t,i,s,n,[],[])}constructor(e,t,i,r,n,s,a){this.type=e,this.value=t,this.from=i,this.hash=r,this.end=n,this.children=s,this.positions=a,this.hashProp=[[_.contextHash,r]]}addChild(e,t){e.prop(_.contextHash)!=this.hash&&(e=new M(e.type,e.children,e.positions,e.length,this.hashProp)),this.children.push(e),this.positions.push(t)}toTree(e,t=this.end){let i=this.children.length-1;return i>=0&&(t=Math.max(t,this.positions[i]+this.children[i].length+this.from)),new M(e.types[this.type],this.children,this.positions,t-this.from).balance({makeTree:(r,n,s)=>new M(ce.none,r,n,s,this.hashProp)})}},y;(function(O){O[O.Document=1]="Document",O[O.CodeBlock=2]="CodeBlock",O[O.FencedCode=3]="FencedCode",O[O.Blockquote=4]="Blockquote",O[O.HorizontalRule=5]="HorizontalRule",O[O.BulletList=6]="BulletList",O[O.OrderedList=7]="OrderedList",O[O.ListItem=8]="ListItem",O[O.ATXHeading1=9]="ATXHeading1",O[O.ATXHeading2=10]="ATXHeading2",O[O.ATXHeading3=11]="ATXHeading3",O[O.ATXHeading4=12]="ATXHeading4",O[O.ATXHeading5=13]="ATXHeading5",O[O.ATXHeading6=14]="ATXHeading6",O[O.SetextHeading1=15]="SetextHeading1",O[O.SetextHeading2=16]="SetextHeading2",O[O.HTMLBlock=17]="HTMLBlock",O[O.LinkReference=18]="LinkReference",O[O.Paragraph=19]="Paragraph",O[O.CommentBlock=20]="CommentBlock",O[O.ProcessingInstructionBlock=21]="ProcessingInstructionBlock",O[O.Escape=22]="Escape",O[O.Entity=23]="Entity",O[O.HardBreak=24]="HardBreak",O[O.Emphasis=25]="Emphasis",O[O.StrongEmphasis=26]="StrongEmphasis",O[O.Link=27]="Link",O[O.Image=28]="Image",O[O.InlineCode=29]="InlineCode",O[O.HTMLTag=30]="HTMLTag",O[O.Comment=31]="Comment",O[O.ProcessingInstruction=32]="ProcessingInstruction",O[O.Autolink=33]="Autolink",O[O.HeaderMark=34]="HeaderMark",O[O.QuoteMark=35]="QuoteMark",O[O.ListMark=36]="ListMark",O[O.LinkMark=37]="LinkMark",O[O.EmphasisMark=38]="EmphasisMark",O[O.CodeMark=39]="CodeMark",O[O.CodeText=40]="CodeText",O[O.CodeInfo=41]="CodeInfo",O[O.LinkTitle=42]="LinkTitle",O[O.LinkLabel=43]="LinkLabel",O[O.URL=44]="URL"})(y||(y={}));var dl=class{constructor(e,t){this.start=e,this.content=t,this.marks=[],this.parsers=[]}},ul=class{constructor(){this.text="",this.baseIndent=0,this.basePos=0,this.depth=0,this.markers=[],this.pos=0,this.indent=0,this.next=-1}forward(){this.basePos>this.pos&&this.forwardInner()}forwardInner(){let e=this.skipSpace(this.basePos);this.indent=this.countIndent(e,this.pos,this.indent),this.pos=e,this.next=e==this.text.length?-1:this.text.charCodeAt(e)}skipSpace(e){return fr(this.text,e)}reset(e){for(this.text=e,this.baseIndent=this.basePos=this.pos=this.indent=0,this.forwardInner(),this.depth=1;this.markers.len Line truncated
`+t.scrub(),n=this.advance(r);return n>-1&&n<r.length?this.complete(e,i,n):!1}finish(e,t){return(this.stage==2||this.stage==3)&&fr(t.content,this.pos)==t.content.length?this.complete(e,t,t.content.length):!1}complete(e,t,i){return e.addLeafElement(t,L(y.LinkReference,this.start,this.start+i,this.elts)),!0}nextStage(e){return e?(this.pos=e.to-this.start,this.elts.push(e),this.stage++,!0):(e===!1&&(this.stage=-1),!1)}advance(e){for(;;){if(this.stage==-1)return-1;if(this.stage==0){if(!this.nextStage(Nd(e,this.pos,this.start,!0)))return-1;if(e.charCodeAt(this.pos)!=58)return this.stage=-1;this.elts.push(L(y.LinkMark,this.pos+this.start,this.pos+this.start+1)),this.pos++}else if(this.stage==1){if(!this.nextStage(Id(e,fr(e,this.pos),this.start)))return-1}else if(this.stage==2){let t=fr(e,this.pos),i=0;if(t>this.pos){let r=Bd(e,t,this.start);if(r){let n=$l(e,r.to-this.start);n>0&&(this.nextStage(r),i=n)}}return i||(i=$l(e,this.pos)),i>0&&i<e.length?i:-1}else return $l(e,this.pos)}}};function $l(O,e){for(;e<O.length;e++){let t=O.charCodeAt(e);if(t==10)break;if(!rt(t))return-1}return e}var Pl=class{nextLine(e,t,i){let r=t.depth<e.stack.length?-1:Ud(t),n=t.next;if(r<0)return!1;let s=L(y.HeaderMark,e.lineStart+t.pos,e.lineStart+r);return e.nextLine(),e.addLeafElement(i,L(n==61?y.SetextHeading1:y.SetextHeading2,i.start,e.prevLineEnd(),[...e.parser.parseInline(i.content,i.start),s])),!0}finish(){return!1}},Ed={LinkReference(O,e){return e.content.charCodeAt(0)==91?new gl(e):null},SetextHeading(){return new Pl}},By=[(O,e)=>Wd(e)>=0,(O,e)=>zd(e)>=0,(O,e)=>Vd(e)>=0,(O,e)=>xl(e,O,!0)>=0,(O,e)=>kl(e,O,!0)>=0,(O,e)=>bl(e,O,!0)>=0,(O,e)=>Cd(e,O,!0)>=0],Ny={text:"",end:0},Sl=class{constructor(e,t,i,r){this.parser=e,this.input=t,this.ranges=r,this.line=new ul,this.atEnd=!1,this.reusePlaceholders=new Map,this.stoppedAt=null,this.rangeI=0,this.to=r[r.length-1].to,this.lineStart=this.absoluteLineStart=this.absoluteLineEnd=r[0].from,this.block=rs.create(y.Document,0,this.lineStart,0,0),this.stack=[this.block],this.fragments=i.length?new yl(i,t):null,this.readLine()}get parsedPos(){return this.absoluteLineStart}advance(){if(this.stoppedAt!=null&&this.absoluteLineStart>this.stoppedAt)return this.finish();let{line:e}=this;for(;;){for(let i=0;;){let r=e.depth<this.stack.length?this.stack[this.stack.length-1]:null;for(;i<e.markers.length&&(!r||e.markers[i].from<r.end);){let n=e.markers[i++];this.addNode(n.type,n.from,n.to)}if(!r)break;this.finishContext()}if(e.pos<e.text.length)break;if(!this.nextLine())return this.finish()}if(this.fragments&&this.reuseFragment(e.basePos))return null;e:for(;;){for(let i of this.parser.blockParsers)if(i){let r=i(this,e);if(r!=!1){if(r==!0)return null;e.forward();continue e}}break}let t=new dl(this.lineStart+e.pos,e.text.slice(e.pos));for(let i of this.parser.leafBlockParsers)if(i){let r=i(this,t);r&&t.parsers.push(r)}e:for(;this.nextLine()&&e.pos!=e.text.length;){if(e.indent<e.baseIndent+4){for(let i of this.parser.endLeafBlock)if(i(this,e,t))break e}for(let i of t.parsers)if(i.nextLine(this,e,t))return null;t.content+=`
`+e.scrub();for(let i of e.markers)t.marks.push(i)}return this.finishLeaf(t),null}stopAt(e){if(this.stoppedAt!=null&&this.stoppedAt<e)throw new RangeError("Can't move stoppedAt forward");this.stoppedAt=e}reuseFragment(e){if(!this.fragments.moveTo(this.absoluteLineStart+e,this.absoluteLineStart)||!this.fragments.matches(this.block.hash))return!1;let t=this.fragments.takeNodes(this);return t?(this.absoluteLineStart+=t,this.lineStart=Fd(this.absoluteLineStart,this.ranges),this.moveRangeI(),this.absoluteLineStart<this.to?(this.lineStart++,this.absoluteLineStart++,this.readLine()):(this.atEnd=!0,this.readLine()),!0):!1}get depth(){return this.stack.length}parentType(e=this.depth-1){return this.parser.nodeSet.types[this.stack[e].type]}nextLine(){return this.lineStart+=this.line.text.length,this.absoluteLineEnd>=this.to?(this.absoluteLineStart=this.absoluteLineEnd,this.atEnd=!0,this.readLine(),!1):(this.lineStart++,this.absoluteLineStart=this.absoluteLineEnd+1,this.moveRangeI(),this.readLine(),!0)}peekLine(){return this.scanLine(this.absoluteLineEnd+1).text}moveRangeI(){for(;this.rangeI<this.ranges.length-1&&this.absoluteLineStart>=this.ranges[this.rangeI].to;)this.rangeI++,this.absoluteLineStart=Math.max(this.absoluteLineStart,this.ranges[this.rangeI].from)}scanLine(e){let t=Ny;if(t.end=e,e>=this.to)t.text="";else if(t.text=this.lineChunkAt(e),t.end+=t.text.length,this.ranges.length>1){let i=this.absoluteLineStart,r=this.rangeI;for(;this.ranges[r].to<t.end;){r++;let n=this.ranges[r].from,s=this.lineChunkAt(n);t.end=n+s.length,t.text=t.text.slice(0,this.ranges[r-1].to-i)+s,i=t.end-t.text.length}}return t}readLine(){let{line:e}=this,{text:t,end:i}=this.scanLine(this.absoluteLineStart);for(this.absoluteLineEnd=i,e.reset(t);e.depth<this.stack.length;e.depth++){let r=this.stack[e.depth],n=this.parser.skipContextMarkup[r.type];if(!n)throw new Error("Unhandled block context "+y[r.type]);let s=this.line.markers.length;if(!n(r,this,e)){this.line.markers.length>s&&(r.end=this.line.markers[this.line.markers.length-1].to),e.forward();break}e.forward()}}lineChunkAt(e){let t=this.input.chunk(e),i;if(this.input.lineChunks)i=t==`
`?"":t;else{let r=t.indexOf(`
`);i=r<0?t:t.slice(0,r)}return e+i.length>this.to?i.slice(0,this.to-e):i}prevLineEnd(){return this.atEnd?this.lineStart:this.lineStart-1}startContext(e,t,i=0){this.block=rs.create(e,i,this.lineStart+t,this.block.hash,this.lineStart+this.line.text.length),this.stack.push(this.block)}startComposite(e,t,i=0){this.startContext(this.parser.getNodeType(e),t,i)}addNode(e,t,i){typeof e=="number"&&(e=new M(this.parser.nodeSet.types[e],si,si,(i??this.prevLineEnd())-t)),this.block.addChild(e,t-this.block.from)}addElement(e){this.block.addChild(e.toTree(this.parser.nodeSet),e.from-this.block.from)}addLeafElement(e,t){this.addNode(this.buffer.writeElements(Tl(t.children,e.marks),-t.from).finish(t.type,t.to-t.from),t.from)}finishContext(){let e=this.stack.pop(),t=this.stack[this.stack.length-1];t.addChild(e.toTree(this.parser.nodeSet),e.from-t.from),this.block=t}finish(){for(;this.stack.length>1;)this.finishContext();return this.addGaps(this.block.toTree(this.parser.nodeSet,this.lineStart))}addGaps(e){return this.ranges.length>1?Ad(this.ranges,0,e.topNode,this.ranges[0].from,this.reusePlaceholders):e}finishLeaf(e){for(let i of e.parsers)if(i.finish(this,e))return;let t=Tl(this.parser.parseInline(e.content,e.start),e.marks);this.addNode(this.buffer.writeElements(t,-e.start).finish(y.Paragraph,e.content.length),e.start)}elt(e,t,i,r){return typeof e=="string"?L(this.parser.getNodeType(e),t,i,r):new ss(e,t)}get buffer(){return new ns(this.parser.nodeSet)}};function Ad(O,e,t,i,r){let n=O[e].to,s=[],a=[],o=t.from+i;function l(c,h){for(;h?c>=n:c>n;){let $=O[e+1].from-n;i+=$,c+=$,e++,n=O[e].to}}for(let c=t.firstChild;c;c=c.nextSibling){l(c.from+i,!0);let h=c.from+i,$,f=r.get(c.tree);f?$=f:c.to+i>n?($=Ad(O,e,c,i,r),l(c.to+i,!1)):$=c.toTree(),s.push($),a.push(h-o)}return l(t.to+i,!1),new M(t.type,s,a,t.to+i-o,t.tree?t.tree.propValues:void 0)}var ur=class O extends Ft{constructor(e,t,i,r,n,s,a,o,l){super(),this.nodeSet=e,this.blockParsers=t,this.leafBlockParsers=i,this.blockNames=r,this.endLeafBlock=n,this.skipContextMarkup=s,this.inlineParsers=a,this.inlineNames=o,this.wrappers=l,this.nodeTypes=Object.create(null);for(let c of e.types)this.nodeTypes[c.name]=c.id}createParse(e,t,i){let r=new Sl(this,e,t,i);for(let n of this.wrappers)r=n(r,e,t,i);return r}configure(e){let t=Xl(e);if(!t)return this;let{nodeSet:i,skipContextMarkup:r}=this,n=this.blockParsers.slice(),s=this.leafBlockParsers.slice(),a=this.blockNames.slice(),o=this.inlineParsers.slice(),l=this.inlineNames.slice(),c=this.endLeafBlock.slice(),h=this.wrappers;if($r(t.defineNodes)){r=Object.assign({},r);let $=i.types.slice(),f;for(let d of t.defineNodes){let{name:u,block:p,composite:m,style:g}=typeof d=="string"?{name:d}:d;if($.some(S=>S.name==u))continue;m&&(r[$.length]=(S,k,b)=>m(k,b,S.value));let X=$.length,T=m?["Block","BlockContext"]:p?X>=y.ATXHeading1&&X<=y.SetextHeading2?["Block","LeafBlock","Heading"]:["Block","LeafBlock"]:void 0;$.push(ce.define({id:X,name:u,props:T&&[[_.group,T]]})),g&&(f||(f={}),Array.isArray(g)||g instanceof De?f[u]=g:Object.assign(f,g))}i=new Bt($),f&&(i=i.extend(I(f)))}if($r(t.props)&&(i=i.extend(...t.props)),$r(t.remove))for(let $ of t.remove){let f=this.blockNames.indexOf($),d=this.inlineNames.indexOf($);f>-1&&(n[f]=s[f]=void 0),d>-1&&(o[d]=void 0)}if($r(t.parseBlock))for(let $ of t.parseBlock){let f=a.indexOf($.name);if(f>-1)n[f]=$.parse,s[f]=$.leaf;else{let d=$.before?is(a,$.before):$.after?is(a,$.after)+1:a.length-1;n.splice(d,0,$.parse),s.splice(d,0,$.leaf),a.splice(d,0,$.name)}$.endLeaf&&c.push($.endLeaf)}if($r(t.parseInline))for(let $ of t.parseInline){let f=l.indexOf($.name);if(f>-1)o[f]=$.parse;else{let d=$.before?is(l,$.before):$.after?is(l,$.after)+1:l.length-1;o.splice(d,0,$.parse),l.splice(d,0,$.name)}}return t.wrap&&(h=h.concat(t.wrap)),new O(i,n,s,a,c,r,o,l,h)}getNodeType(e){let t=this.nodeTypes[e];if(t==null)throw new RangeError(`Unknown node type '${e}'`);return t}parseInline(e,t){let i=new mr(this,e,t);e:for(let r=t;r<i.end;){let n=i.char(r);for(let s of this.inlineParsers)if(s){let a=s(i,n,r);if(a>=0){r=a;continue e}}r++}return i.resolveMarkers(0)}};function $r(O){return O!=null&&O.length>0}function Xl(O){if(!Array.isArray(O))return O;if(O.length==0)return null;let e=Xl(O[0]);if(O.length==1)return e;let t=Xl(O.slice(1));if(!t||!e)return e||t;let i=(s,a)=>(s||si).concat(a||si),r=e.wrap,n=t.wrap;return{props:i(e.props,t.props),defineNodes:i(e.defineNodes,t.defineNodes),parseBlock:i(e.parseBlock,t.parseBlock),parseInline:i(e.parseInline,t.parseInline),remove:i(e.remove,t.remove),wrap:r?n?(s,a,o,l)=>r(n(s,a,o,l),a,o,l):r:n}}function is(O,e){let t=O.indexOf(e);if(t<0)throw new RangeError(`Position specified relative to unknown parser ${e}`);return t}var Ld=[ce.none];for(let O=1,e;e=y[O];O++)Ld[O]=ce.define({id:O,name:e,props:O>=y.Escape?[]:[[_.group,O in Rd?["Block","BlockContext"]:["Block","LeafBlock"]]],top:e=="Document"});var si=[],ns=class{constructor(e){this.nodeSet=e,this.content=[],this.nodes=[]}write(e,t,i,r=0){return t Line truncated
`;)n--;this.fragmentEnd=n?n-1:0}let i=this.cursor;i||(i=this.cursor=this.fragment.tree.cursor(),i.firstChild());let r=e+this.fragment.offset;for(;i.to<=r;)if(!i.parent())return!1;for(;;){if(i.from>=r)return this.fragment.from<=t;if(!i.childAfter(r))return!1}}matches(e){let t=this.cursor.tree;return t&&t.prop(_.contextHash)==e}takeNodes(e){let t=this.cursor,i=this.fragment.offset,r=this.fragmentEnd-(this.fragment.openEnd?1:0),n=e.absoluteLineStart,s=n,a=e.block.children.length,o=s,l=a;for(;;){if(t.to-i>r){if(t.type.isAnonymous&&t.firstChild())continue;break}let c=Fd(t.from-i,e.ranges);if(t.to-i<=e.ranges[e.rangeI].to)e.addNode(t.tree,c);else{let h=new M(e.parser.nodeSet.types[y.Paragraph],[],[],0,e.block.hashProp);e.reusePlaceholders.set(h,t.tree),e.addNode(h,c)}if(t.type.is("Block")&&(Hy.indexOf(t.type.id)<0?(s=t.to-i,a=e.block.children.length):(s=o,a=l),o=t.to-i,l=e.block.children.length),!t.nextSibling())break}for(;e.block.children.length>a;)e.block.children.pop(),e.block.positions.pop();return s-n}};function Fd(O,e){let t=O;for(let i=1;i<e.length;i++){let r=e[i-1].to,n=e[i].from;r<O&&(t-=n-r)}return t}var Ky=I({"Blockquote/...":Q.quote,HorizontalRule:Q.contentSeparator,"ATXHeading1/... SetextHeading1/...":Q.heading1,"ATXHeading2/... SetextHeading2/...":Q.heading2,"ATXHeading3/...":Q.heading3,"ATXHeading4/...":Q.heading4,"ATXHeading5/...":Q.heading5,"ATXHeading6/...":Q.heading6,"Comment CommentBlock":Q.comment,Escape:Q.escape,Entity:Q.character,"Emphasis/...":Q.emphasis,"StrongEmphasis/...":Q.strong,"Link/... Image/...":Q.link,"OrderedList/... BulletList/...":Q.list,"BlockQuote/...":Q.quote,"InlineCode CodeText":Q.monospace,"URL Autolink":Q.url,"HeaderMark HardBreak QuoteMark ListMark LinkMark EmphasisMark CodeMark":Q.processingInstruction,"CodeInfo LinkLabel":Q.labelName,LinkTitle:Q.string,Paragraph:Q.content}),Hd=new ur(new Bt(Ld).extend(Ky),Object.keys(Os).map(O=>Os[O]),Object.keys(Os).map(O=>Ed[O]),Object.keys(Os),By,Rd,Object.keys(fl).map(O=>fl[O]),Object.keys(fl),[]);function Jy(O,e,t){let i=[];for(let r=O.firstChild,n=e;;r=r.nextSibling){let s=r?r.from:t;if(s>n&&i.push({from:n,to:s}),!r)break;n=r.to}return i}function Kd(O){let{codeParser:e,htmlParser:t}=O;return{wrap:gO((r,n)=>{let s=r.type.id;if(e&&(s==y.CodeBlock||s==y.FencedCode)){let a="";if(s==y.FencedCode){let l=r.node.getChild(y.CodeInfo);l&&(a=n.read(l.from,l.to))}let o=e(a);if(o)return{parser:o,overlay:l=>l.type.id==y.CodeText,bracketed:s==y.FencedCode}}else if(t&&(s==y.HTMLBlock||s==y.HTMLTag||s==y.CommentBlock))return{parser:t,overlay:Jy(r.node,r.from,r.to)};return null})}}var ew={resolve:"Strikethrough",mark:"StrikethroughMark"},tw={defineNodes:[{name:"Strikethrough",style:{"Strikethrough/...":Q.strikethrough}},{name:"StrikethroughMark",style:Q.processingInstruction}],parseInline:[{name:"Strikethrough",parse(O,e,t){if(e!=126||O.char(t+1)!=126||O.char(t+2)==126)return-1;let i=O.slice(t-1,t),r=O.slice(t+2,t+3),n=/\s|^$/.test(i),s=/\s|^$/.test(r),a=pr.test(i),o=pr.test(r);return O.addDelimiter(ew,t,t+2,!s&&(!o||n||a),!n&&(!a||s||o))},after:"Emphasis"}]};function dr(O,e,t=0,i,r=0){let n=0,s=!0,a=-1,o=-1,l=!1,c=()=>{i.push(O.elt("TableCell",r+a,r+o,O.parser.parseInline(e.slice(a,o),r+a)))};for(let h=t;h<e.length;h++){let $=e.charCodeAt(h);$==124&&!l?((!s||a>-1)&&n++,s=!1,i&&(a>-1&&c(),i.push(O.elt("TableDelimiter",h+r,h+r+1))),a=o=-1):(l||$!=32&&$!=9)&&(a<0&&(a=h),o=h+1),l=!l&&$==92}return a>-1&&(n++,i&&c()),n}function bd(O,e){for(let t=e;t<O.length;t++){let i=O.charCodeAt(t);if(i==124)return!0;i==92&&t++}return!1}var Jd=/^\|?(\s*:?-+:?\s*\|)+(\s*:?-+:?\s*)?$/,os=class{constructor(){this.rows=null}nextLine(e,t,i){if(this.rows==null){this.rows=!1;let r;if((t.next==45||t.next==58||t.next==124)&&Jd.test(r=t.text.slice(t.pos))){let n=[];dr(e,i.content,0,n,i.start)==dr(e,r,t.pos)&&(this.rows=[e.elt("TableHeader",i.start,i.start+i.content.length,n),e.elt("TableDelimiter",e.lineStart+t.pos,e.lineStart+t.text.length)])}}else if(this.rows){let r=[];dr(e,t.text,t.pos,r,e.lineStart),this.rows.push(e.elt("TableRow",e.lineStart+t.pos,e.lineStart+t.text.length,r))}return!1}finish(e,t){return this.rows?(e.addLeafElement(t,e.elt("Table",t.start,t.start+t.content.length,this.rows)),!0):!1}},Ow={defineNodes:[{name:"Table",block:!0},{name:"TableHeader",style:{"TableHeader/...":Q.heading}},"TableRow",{name:"TableCell",style:Q.content},{name:"TableDelimiter",style:Q.processingInstruction}],parseBlock:[{name:"Table",leaf(O,e){return bd(e.content,0)?new os:null},endLeaf(O,e,t){if(t.parsers.some(r=>r instanceof os)||!bd(e.text,e.basePos))return!1;let i=O.peekLine();return Jd.test(i)&&dr(O,e.text,e.basePos)==dr(O,i,e.basePos)},before:"SetextHeading"}]},wl=class{nextLine(){return!1}finish(e,t){return e.addLeafElement(t,e.elt("Task",t.start,t.start+t.content.length,[e.elt("TaskMarker",t.start,t.start+3),...e.parser.parseInline(t.content.slice(3),t.start+3)])),!0}},iw={defineNodes:[{name:"Task",block:!0,style:Q.list},{name:"TaskMarker",style:Q.atom}],parseBlock:[{name Line truncated
\${}
}`,{label:"select",detail:"statement",type:"keyword"}),W("case ${}:\n${}",{label:"case",type:"keyword"}),W("switch ${} {\n ${}\n}",{label:"switch",detail:"statement",type:"keyword"}),W("switch ${}.(${type}) {\n ${}\n}",{label:"switch",detail:"type statement",type:"keyword"}),W("if ${} {\n ${}\n}",{label:"if",detail:"block",type:"keyword"}),W(`if \${} {
\${}
} else {
\${}
}`,{label:"if",detail:"/ else block",type:"keyword"}),W('import ${name} "${module}"\n${}',{label:"import",detail:"declaration",type:"keyword"})],Qp=new Pt,fp=new Set(["SourceFile","Block","FunctionDecl","MethodDecl","FunctionLiteral","ForStatement","SwitchStatement","TypeSwitchStatement","IfStatement"]);function hi(O,e){return(t,i)=>{e:for(let r=t.node.firstChild,n=0,s=null;;){for(;!r;){if(!n)break e;n--,r=s.nextSibling,s=s.parent}e&&r.name==e||r.name=="SpecList"?(n++,s=r,r=r.firstChild):(r.name=="DefName"&&i(r,O),r=r.nextSibling)}return!0}}var q0={FunctionDecl:hi("function"),VarDecl:hi("var","VarSpec"),ConstDecl:hi("constant","ConstSpec"),TypeDecl:hi("type","TypeSpec"),ImportDecl:hi("constant","ImportSpec"),Parameter:hi("var"),__proto__:null};function dp(O,e){let t=Qp.get(e);if(t)return t;let i=[],r=!0;function n(s,a){let o=O.sliceString(s.from,s.to);i.push({label:o,type:a})}return e.cursor(C.IncludeAnonymous).iterate(s=>{if(r)r=!1;else if(s.name){let a=q0[s.name];if(a&&a(s,n)||fp.has(s.name))return!1}else if(s.to-s.from>8192){for(let a of dp(O,s.node))i.push(a);return!1}}),Qp.set(e,i),i}var $p=/^[\w$\xa1-\uffff][\w$\d\xa1-\uffff]*$/,up=["String","LineComment","BlockComment","DefName","LabelName","FieldName",".","?."],W0=O=>{let e=q(O.state).resolveInner(O.pos,-1);if(up.indexOf(e.name)>-1)return null;let t=e.name=="VariableName"||e.to-e.from<20&&$p.test(O.state.sliceDoc(e.from,e.to));if(!t&&!O.explicit)return null;let i=[];for(let r=e;r;r=r.parent)fp.has(r.name)&&(i=i.concat(dp(O.state.doc,r)));return{options:i,from:t?e.from:O.pos,validFor:$p}},Hl=re.define({name:"go",parser:hp.configure({props:[ne.add({IfStatement:oe({except:/^\s*({|else\b)/}),LabeledStatement:KO,"SwitchBlock SelectBlock":O=>{let e=O.textAfter,t=/^\s*\}/.test(e),i=/^\s*(case|default)\b/.test(e);return O.baseIndent+(t||i?0:O.unit)},Block:_e({closing:"}"}),BlockComment:()=>null,Statement:oe({except:/^{/})}),J.add({"Block SwitchBlock SelectBlock LiteralValue InterfaceType StructType SpecList":me,BlockComment(O){return{from:O.from+2,to:O.to-2}}})]}),languageData:{closeBrackets:{brackets:["(","[","{","'",'"',"`"]},commentTokens:{line:"//",block:{open:"/*",close:"*/"}},indentOnInput:/^\s*(?:case\b|default\b|\})$/}}),U0=O=>({label:O,type:"keyword"}),j0="interface struct chan map package go return break continue goto fallthrough else defer range true false nil".split(" ").map(U0);function pp(){let O=V0.concat(j0);return new F(Hl,[Hl.data.of({autocomplete:rO(up,Rt(O))}),Hl.data.of({autocomplete:W0})])}var mp=1,G0=2,C0=3,E0=82,A0=76,L0=117,M0=85,D0=97,I0=122,B0=65,N0=90,F0=95,Kl=48,gp=34,H0=40,Pp=41,K0=32,Sp=62,J0=new V(O=>{if(O.next==A0||O.next==M0?O.advance():O.next==L0&&(O.advance(),O.next==Kl+8&&O.advance()),O.next!=E0||(O.advance(),O.next!=gp))return;O.advance();let e="";for(;O.next!=H0;){if(O.next==K0||O.next<=13||O.next==Pp)return;e+=String.fromCharCode(O.next),O.advance()}for(O.advance();;){if(O.next<0)return O.acceptToken(mp);if(O.next==Pp){let t=!0;for(let i=0;t&&i<e.length;i++)O.peek(i+1)!=e.charCodeAt(i)&&(t=!1);if(t&&O.peek(e.length+1)==gp)return O.acceptToken(mp,2+e.length)}O.advance()}}),ex=new V(O=>{if(O.next==Sp)O.peek(1)==Sp&&O.acceptToken(G0,1);else{let e=!1,t=0;for(;;t++){if(O.next>=B0&&O.next<=N0)e=!0;else{if(O.next>=D0&&O.next<=I0)return;if(O.next!=F0&&!(O.next>=Kl&&O.next<=Kl+9))break}O.advance()}e&&t>1&&O.acceptToken(C0)}},{extend:!0}),tx=I({"typedef struct union enum class typename decltype auto template operator friend noexcept namespace using requires concept import export module __attribute__ __declspec __based":Q.definitionKeyword,"extern MsCallModifier MsPointerModifier extern static register thread_local inline const volatile restrict _Atomic mutable constexpr constinit consteval virtual explicit VirtualSpecifier Access":Q.modifier,"if else switch for while do case default return break continue goto throw try catch":Q.controlKeyword,"co_return co_yield co_await":Q.controlKeyword,"new sizeof delete static_assert":Q.operatorKeyword,"NULL nullptr":Q.null,this:Q.self,"True False":Q.bool,"TypeSize PrimitiveType":Q.standard(Q.typeName),TypeIdentifier:Q.typeName,FieldIdentifier:Q.propertyName,"CallExpression/FieldExpression/FieldIdentifier":Q.function(Q.propertyName),"ModuleName/Identifier":Q.namespace,PartitionName:Q.labelName,StatementIdentifier:Q.labelName,"Identifier DestructorName":Q.variableName,"CallExpression/Identifier":Q.function(Q.variableName),"CallExpression/ScopedIdentifier/Identifier":Q.function(Q.variableName),"FunctionDeclarator/Identifier FunctionDeclarator/DestructorName":Q.function(Q.definition(Q.variableName)),NamespaceIdentifier:Q.namespace,OperatorName:Q.operator,ArithOp:Q.arithmeticOperator,LogicOp:Q.logicOperator,BitOp:Q.bitwiseOperator,CompareOp:Q.compareOperator,AssignOp:Q.definitionOperator,UpdateOp:Q.updateOperator,LineComment:Q.lineComment,BlockComment:Q.blockComment,Number:Q.number,String:Q.string,"RawString SystemLibString":Q.special(Q.string),CharLiteral:Q.character,EscapeSequence:Q.escape," Line truncated
`;function Ip(O,e,t){let i=Object.create(null);i.true=i.false=Ux,i.null=i.unknown=jx;for(let r of O.split(" "))r&&(i[r]=Mp);for(let r of e.split(" "))r&&(i[r]=Dp);for(let r of(t||"").split(" "))r&&(i[r]=Jx);return i}var RO="array binary bit boolean char character clob date decimal double float int integer interval large national nchar nclob numeric object precision real smallint time timestamp varchar varying ",zO="absolute action add after all allocate alter and any are as asc assertion at authorization before begin between both breadth by call cascade cascaded case cast catalog check close collate collation column commit condition connect connection constraint constraints constructor continue corresponding count create cross cube current current_date current_default_transform_group current_transform_group_for_type current_path current_role current_time current_timestamp current_user cursor cycle data day deallocate declare default deferrable deferred delete depth deref desc describe descriptor deterministic diagnostics disconnect distinct do domain drop dynamic each else elseif end end-exec equals escape except exception exec execute exists exit external fetch first for foreign found from free full function general get global go goto grant group grouping handle having hold hour identity if immediate in indicator initially inner inout input insert intersect into is isolation join key language last lateral leading leave left level like limit local localtime localtimestamp locator loop map match method minute modifies module month names natural nesting new next no none not of old on only open option or order ordinality out outer output overlaps pad parameter partial path prepare preserve primary prior privileges procedure public read reads recursive redo ref references referencing relative release repeat resignal restrict result return returns revoke right role rollback rollup routine row rows savepoint schema scroll search second section select session session_user set sets signal similar size some space specific specifictype sql sqlexception sqlstate sqlwarning start state static system_user table temporary then timezone_hour timezone_minute to trailing transaction translation treat trigger under undo union unique unnest until update usage user using value values view when whenever where while with without work write year zone ",cc={backslashEscapes:!1,hashComments:!1,spaceAfterDashes:!1,slashComments:!1,doubleQuotedStrings:!1,doubleDollarQuotedStrings:!1,unquotedBitLiterals:!1,treatBitsAsBytes:!1,charSetCasts:!1,plsqlQuotingMechanism:!1,operatorChars:"*+-%<>!=&|~^/",specialVar:"?",identifierQuotes:'"',words:Ip(zO,RO)};function rk(O,e,t,i){let r={};for(let n in cc)r[n]=(O.hasOwnProperty(n)?O:cc)[n];return e&&(r.words=Ip(e,t||"",i)),r}function Bp(O){return new V(e=>{var t;let{next:i}=e;if(e.advance(),ZO(i,ac)){for(;ZO(e.next,ac);)e.advance();e.acceptToken(qx)}else if(i==36&&O.doubleDollarQuotedStrings){let r=lc(e,"");e.next==36&&(e.advance(),tk(e,r),e.acceptToken(yr))}else if(i==39||i==34&&O.doubleQuotedStrings)_O(e,i,O.backslashEscapes),e.acceptToken(yr);else if(i==35&&O.hashComments||i==47&&e.next==47&&O.slashComments)Cp(e),e.acceptToken(qp);else if(i==45&&e.next==45&&(!O.spaceAfterDashes||e.peek(1)==32))Cp(e),e.acceptToken(qp);else if(i==47&&e.next==42){e.advance();for(let r=1;;){let n=e.next;if(e.next<0)break;if(e.advance(),n==42&&e.next==47){if(r--,e.advance(),!r)break}else n==47&&e.next==42&&(r++,e.advance())}e.acceptToken(Wx)}else if((i==101||i==69)&&e.next==39)e.advance(),_O(e,39,!0);else if((i==110||i==78)&&e.next==39&&O.charSetCasts)e.advance(),_O(e,39,O.backslashEscapes),e.acceptToken(yr);else if(i==95&&O.charSetCasts)for(let r=0;;r++){if(e.next==39&&r>1){e.advance(),_O(e,39,O.backslashEscapes),e.acceptToken(yr);break}if(!oc(e.next))break;e.advance()}else if(O.plsqlQuotingMechanism&&(i==113||i==81)&&e.next==39&&e.peek(1)>0&&!ZO(e.peek(1),ac)){let r=e.peek(1);e.advance(2),Ok(e,r),e.acceptToken(yr)}else if(i==40)e.acceptToken(Gx);else if(i==41)e.acceptToken(Cx);else if(i==123)e.acceptToken(Ex);else if(i==125)e.acceptToken(Ax);else if(i==91)e.acceptToken(Lx);else if(i==93)e.acceptToken(Mx);else if(i==59)e.acceptToken(Dx);else if(O.unquotedBitLiterals&&i==48&&e.next==98)e.advance(),jp(e),e.acceptToken(Up);else if((i==98||i==66)&&(e.next==39||e.next==34)){let r=e.next;e.advance(),O.treatBitsAsBytes?(_O(e,r,O.backslashEscapes),e.acceptToken(Kx)):(jp(e,r),e.acceptToken(Up))}else if(i==48&&(e.next==120||e.next==88)||(i==120||i==88)&&e.next==39){let r=e.next==39;for(e.advance();ek(e.next);)e.advance();r&&e.next==39&&e.advance(),e.acceptToken(sc)}else if(i==46&&e.next>=48&&e.next<=57)Gp(e,!0),e.acceptToken(sc);else if(i==46)e.acceptToken(Ix);else if(i>=48&&i<=57)Gp(e,!1),e.acceptToken(sc);else if(ZO(i,O.operatorChars)){for(;ZO(e.next,O.operatorChars);)e.advance();e.acceptToken(Bx)}else if(ZO(i,O.specialVar))e.next==i&&e.advance(),ik(e),e.acceptToken(Fx);else if(ZO(i,O.identifierQuotes))_O(e,i,!1),e.accept Line truncated
+19
View File
@@ -0,0 +1,19 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Reasonix</title>
<meta name="reasonix-token" content="__REASONIX_TOKEN__" />
<meta name="reasonix-mode" content="__REASONIX_MODE__" />
<link rel="stylesheet" href="/assets/app.css?token=__REASONIX_TOKEN__" />
<link rel="stylesheet" href="https://esm.sh/[email protected]/dist/uPlot.min.css" />
<link rel="stylesheet" href="https://esm.sh/[email protected]/styles/github-dark.min.css" />
</head>
<body>
<div id="root">
<div class="boot">loading…</div>
</div>
<script type="module" src="/assets/app.js?token=__REASONIX_TOKEN__"></script>
</body>
</html>
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
View File
Whitespace-only changes.
+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.
+12
View File
@@ -0,0 +1,12 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
<defs>
<linearGradient id="g" 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>
</defs>
<rect width="64" height="64" rx="12" fill="#0a0d14"/>
<path d="M 32,10 L 54,32 L 32,54 L 10,32 Z" fill="none" stroke="url(#g)" stroke-width="3" stroke-linejoin="round"/>
<path d="M 32,21 L 43,32 L 32,43 L 21,32 Z" fill="url(#g)" opacity="0.9"/>
</svg>

After

Width:  |  Height:  |  Size: 568 B

+462
View File
@@ -0,0 +1,462 @@
// Reasonix landing — i18n auto-switch (en / zh).
// Detection precedence: ?lang=xx → localStorage → navigator.language → "en".
// Falls back gracefully when localStorage is unavailable (private mode, etc).
(function () {
"use strict";
const STORAGE_KEY = "reasonix.lang";
const DEFAULT_LANG = "en";
const SUPPORTED = ["en", "zh"];
const translations = {
en: {
"nav.features": "Features",
"nav.quickstart": "Quick start",
"nav.benchmarks": "Benchmarks",
"nav.github": "GitHub",
"hero.badge": "v{version} · DeepSeek V4 · cache-first",
"hero.title.line1": "DeepSeek-native",
"hero.title.line2": "AI coding agent in your terminal",
"hero.sub":
"Cache-first agent loop for DeepSeek V4 (flash + pro). Edits files as reviewable SEARCH/REPLACE blocks. Ink TUI. MCP first-class. No LangChain.",
"hero.copy": "Copy",
"hero.copy.done": "Copied",
"hero.cta.start": "Get started →",
"hero.cta.star": "Star on GitHub",
"hero.stat.cache": "prefix cache hit rate",
"hero.stat.cost": "cheaper vs Claude Sonnet 4.6",
"hero.stat.pass": "τ-bench-lite pass rate",
"term.user":
"users.ts findByEmail is case-sensitive — login fails for users with uppercase emails",
"term.found":
"▸ Found it. findByEmail uses === directly. Switch to lowercase normalization.",
"term.pending": "▸ 1 pending edit · /apply to write · /discard to drop",
"why.title": "Why Reasonix",
"why.sub":
"Every abstraction earns its weight against a DeepSeek-specific property — dirt-cheap tokens, R1 traces, automatic prefix caching, JSON mode. Generic wrappers leave these on the table.",
"why.cache.title": "Cache-first loop",
"why.cache.body":
"Append-only conversation log keeps the prompt prefix byte-stable across turns, so DeepSeek's automatic cache hits 85–95% — not 40%.",
"why.cost.title": "Cost is a pillar",
"why.cost.body":
"Flash-first defaults, turn-end auto-compaction, model self-escalation when (and only when) needed. Per-turn cost badge in the TUI.",
"why.tui.title": "Ink TUI, no web",
"why.tui.body":
"Lives in your terminal. Streaming preview, slash commands, plan picker, edit-confirm modal. Plain mode for stubborn Windows shells.",
"why.mcp.title": "MCP first-class",
"why.mcp.body":
"Stdio + HTTP+SSE transports. Live progress notifications. Same cache-safety + repair plumbing as native tools.",
"why.safe.title": "Reviewable edits",
"why.safe.body":
"Edits arrive as SEARCH/REPLACE blocks; nothing hits disk until /apply. Per-file diff confirm modal, undo history, sandboxed paths.",
"why.ctx.title": "1M-token aware",
"why.ctx.body":
"Context gauge with proactive compaction, oversized tool-result repair, forced-summary fallback near the window edge.",
"qs.title": "Quick start (60 seconds)",
"qs.step1.title": "Get a DeepSeek API key",
"qs.step1.body":
'Free credit on signup at <a href="https://platform.deepseek.com/api_keys" target="_blank" rel="noopener">platform.deepseek.com</a>.',
"qs.step2.title": "Point it at a project",
"qs.step2.body": "No install needed.",
"qs.step2.note":
"First run walks you through a 30-second wizard (paste API key → pick preset → pick MCP servers).",
"qs.step3.title": "Ask it to edit",
"qs.step3.body":
"The model proposes edits as SEARCH/REPLACE blocks — nothing hits disk until you <code>/apply</code>.",
"qs.req":
"Requires Node ≥ 20.10. macOS, Linux, Windows (PowerShell · Git Bash · Windows Terminal). Press <kbd>Esc</kbd> anytime to abort; <code>/help</code> for the full command list.",
"feat.title": "In the box",
"feat.code.title": "Pair programmer mode",
"feat.code.body":
"<code>read_file</code> · <code>write_file</code> · <code>edit_file</code> · <code>search_files</code> · <code>directory_tree</code> · <code>run_command</code> with read-only allowlist. Sandboxed to the launch root — no path escapes. Plan mode and per-edit review modal.",
"feat.memory.title": "Two-layer memory",
"feat.memory.body":
"Committable <code>REASONIX.md</code> for team conventions plus a private per-user <code>~/.reasonix/memory/</code> with global and per-project scopes. The model can write to it via the <code>remember</code> tool.",
"feat.skills.title": "User-authored prompt packs",
"feat.skills.body":
"Drop <code>SKILL.md</code> files anywhere. Names + descriptions are pinned in the prefix; the model picks them autonomously, or you trigger with <code>/skill name</code>.",
"feat.hooks.title": "Lifecycle hooks",
"feat.hooks.body":
"Shell commands fire at <code>PreToolUse</code> · <code>PostToolUse</code> · <code>UserPromptSubmit</code> · <code>Stop</code>. Exit code drives pass / block / warn.",
"feat.mcp.title": "Bring your own tools",
"feat.mcp.body":
'Wizard catalog, or <code>--mcp "name=cmd"</code> to attach stdio / HTTP+SSE servers on the fly. Live progress bars on long calls.',
"feat.web.title": "Web search built-in",
"feat.web.body":
"<code>web_search</code> + <code>web_fetch</code> via Mojeek — no key, no signup, off-by-flag for offline / CI. Bring-your-own provider via the <code>WebSearchProvider</code> interface.",
"bench.title": "Verify the cache claim yourself",
"bench.sub":
"On the same τ-bench-lite workload (8 multi-turn tool-use tasks × 3 repeats = 48 runs per side), live DeepSeek <code>deepseek-chat</code>, sole variable prefix stability:",
"bench.col.metric": "metric",
"bench.col.baseline": "baseline (cache-hostile)",
"bench.col.reasonix": "Reasonix",
"bench.col.delta": "delta",
"bench.row.cache": "cache hit",
"bench.row.cost": "cost / task",
"bench.row.pass": "pass rate",
"bench.repro.intro": "Reproduce without spending an API credit:",
"bench.repro.note":
"The committed JSONL transcripts carry per-turn <code>usage</code>, <code>cost</code>, and <code>prefixHash</code>. Reasonix's prefix hash stays byte-stable across every model call.",
"cli.title": "CLI at a glance",
"cli.code": "coding mode scoped to path",
"cli.chat": "chat (uses saved config)",
"cli.setup": "reconfigure the wizard",
"cli.run": "one-shot, streams to stdout",
"cli.stats": "cross-session cost dashboard",
"cli.mcp": "probe a single MCP server",
"cli.flags.intro": "Common flags:",
"cli.f.preset": "model + harvest + branch bundle",
"cli.f.model": "explicit DeepSeek model id",
"cli.f.mcp": "attach an MCP server (repeatable)",
"cli.f.session": "named session",
"cli.f.noconf": "ignore ~/.reasonix/config.json (CI)",
"ctab.title": "Ready to try?",
"ctab.sub": "One <code>npx</code> away. Sandboxed. Reviewable. 96% cheaper.",
"ctab.gh": "GitHub repository →",
"ctab.npm": "npm package",
"foot.tag": "DeepSeek does deep, deeply.",
"foot.col.project": "Project",
"foot.col.docs": "Docs",
"foot.col.community": "Community",
"foot.changelog": "Changelog",
"foot.readme": "README",
"foot.readme.zh": "中文 README",
"foot.arch": "Architecture",
"foot.issues": "Issues",
"foot.discuss": "Discussions",
"foot.copyright": "© 2026 Reasonix · MIT License",
},
zh: {
"nav.features": "特性",
"nav.quickstart": "快速上手",
"nav.benchmarks": "性能对比",
"nav.github": "GitHub",
"hero.badge": "v{version} · DeepSeek V4 · 缓存优先",
"hero.title.line1": "DeepSeek 原生",
"hero.title.line2": "终端里的 AI 编程代理",
"hero.sub":
"为 DeepSeek V4(flash + pro)打造的缓存优先 agent 循环。编辑以可审查的 SEARCH/REPLACE 块呈现,落盘前必须确认。Ink TUI、原生支持 MCP,不依赖 LangChain。",
"hero.copy": "复制",
"hero.copy.done": "已复制",
"hero.cta.start": "开始使用 →",
"hero.cta.star": "在 GitHub 加星",
"hero.stat.cache": "前缀缓存命中率",
"hero.stat.cost": "相比 Claude Sonnet 4.6 节省",
"hero.stat.pass": "τ-bench-lite 通过率",
"term.user":
"users.ts 里 findByEmail 对大小写敏感导致登录失败,帮我改",
"term.found":
"▸ 找到了。findByEmail 直接用 === 比对。改成小写规范化并补一条测试。",
"term.pending": "▸ 1 处待应用编辑 · /apply 写入 · /discard 丢弃",
"why.title": "为什么选 Reasonix",
"why.sub":
"每个抽象都对应 DeepSeek 的一个具体特性——极低 token 价、R1 推理轨迹、自动前缀缓存、JSON 模式。通用框架把这些机会全留在桌上。",
"why.cache.title": "缓存优先的循环",
"why.cache.body":
"对话日志只追加不重写,前缀字节级稳定,DeepSeek 的自动前缀缓存命中能稳定打到 85–95%,而不是 40%。",
"why.cost.title": "成本是头等公民",
"why.cost.body":
"默认 flash 优先、turn 末尾自动压缩、必要时模型自我升级到 pro。TUI 有实时单轮成本徽章。",
"why.tui.title": "Ink TUI,不靠浏览器",
"why.tui.body":
"完全在终端里。流式预览、斜杠命令、计划审阅、编辑确认弹窗。Windows 顽固终端可启用 plain 模式。",
"why.mcp.title": "原生 MCP",
"why.mcp.body":
"stdio + HTTP+SSE 双传输。长任务有实时进度条。和原生工具一样走缓存安全 + 自动修复管线。",
"why.safe.title": "编辑可审阅",
"why.safe.body":
"编辑以 SEARCH/REPLACE 块呈现,/apply 之前不动磁盘。逐文件 diff 确认、撤销历史、路径沙箱。",
"why.ctx.title": "百万 token 感知",
"why.ctx.body":
"上下文仪表 + 主动压缩、超大工具结果自动修复、贴近上限自动总结兜底。",
"qs.title": "60 秒快速上手",
"qs.step1.title": "获取 DeepSeek API Key",
"qs.step1.body":
'在 <a href="https://platform.deepseek.com/api_keys" target="_blank" rel="noopener">platform.deepseek.com</a> 注册即送免费额度。',
"qs.step2.title": "切到项目目录运行",
"qs.step2.body": "无需安装。",
"qs.step2.note":
"首次运行会走 30 秒向导:粘贴 API key → 选预设 → 勾选 MCP 服务器。",
"qs.step3.title": "让它改代码",
"qs.step3.body":
"模型会以 SEARCH/REPLACE 块的形式提出编辑——你不 <code>/apply</code>,磁盘不会被改。",
"qs.req":
"需要 Node ≥ 20.10。支持 macOS、Linux、Windows(PowerShell · Git Bash · Windows Terminal)。任何时候按 <kbd>Esc</kbd> 中断;<code>/help</code> 查看完整命令。",
"feat.title": "开箱即用",
"feat.code.title": "结对编程模式",
"feat.code.body":
"<code>read_file</code> · <code>write_file</code> · <code>edit_file</code> · <code>search_files</code> · <code>directory_tree</code> · 带只读白名单的 <code>run_command</code>。沙箱限定在启动目录——路径逃逸一律拒绝。支持 plan 模式与逐次编辑确认弹窗。",
"feat.memory.title": "两层记忆系统",
"feat.memory.body":
"可提交的 <code>REASONIX.md</code> 承载团队约定,私人 <code>~/.reasonix/memory/</code> 分全局与按项目两个作用域。模型可通过 <code>remember</code> 工具自行写入。",
"feat.skills.title": "用户定义的 prompt 包",
"feat.skills.body":
"把 <code>SKILL.md</code> 丢进任意位置。名字 + 描述会被钉在前缀里,模型可自动调用,或你用 <code>/skill name</code> 手动触发。",
"feat.hooks.title": "生命周期钩子",
"feat.hooks.body":
"在 <code>PreToolUse</code> · <code>PostToolUse</code> · <code>UserPromptSubmit</code> · <code>Stop</code> 四个点触发 shell 命令,退出码决定放行 / 阻断 / 警告。",
"feat.mcp.title": "自带工具进来",
"feat.mcp.body":
'向导内置目录,或用 <code>--mcp "name=cmd"</code> 直接挂 stdio / HTTP+SSE 服务器。长任务渲染实时进度条。',
"feat.web.title": "内置联网搜索",
"feat.web.body":
"<code>web_search</code> + <code>web_fetch</code>,背靠 Mojeek——无需 key、无需注册,离线 / CI 可关闭。可通过 <code>WebSearchProvider</code> 接口接入自家搜索。",
"bench.title": "缓存命中率自己也能验证",
"bench.sub":
"同一 τ-bench-lite 负载(8 个多轮工具调用任务 × 3 次重复 = 每边 48 次运行),实测 DeepSeek <code>deepseek-chat</code>,唯一变量是前缀稳定性:",
"bench.col.metric": "指标",
"bench.col.baseline": "基线(缓存敌对)",
"bench.col.reasonix": "Reasonix",
"bench.col.delta": "差值",
"bench.row.cache": "缓存命中",
"bench.row.cost": "单任务成本",
"bench.row.pass": "通过率",
"bench.repro.intro": "无需消耗 API 额度即可复现:",
"bench.repro.note":
"提交进仓库的 JSONL 文件每轮带 <code>usage</code>、<code>cost</code>、<code>prefixHash</code>。Reasonix 的前缀哈希在每次模型调用时都字节稳定。",
"cli.title": "CLI 速览",
"cli.code": "针对指定路径的编程模式",
"cli.chat": "聊天模式(读取已保存配置)",
"cli.setup": "重新跑配置向导",
"cli.run": "一次性运行,结果流到 stdout",
"cli.stats": "跨会话的成本仪表盘",
"cli.mcp": "探测单个 MCP 服务器",
"cli.flags.intro": "常用 flag:",
"cli.f.preset": "模型 + harvest + 分支并行 一键组合",
"cli.f.model": "显式指定 DeepSeek 模型 ID",
"cli.f.mcp": "挂载 MCP 服务器(可重复)",
"cli.f.session": "命名会话",
"cli.f.noconf": "忽略 ~/.reasonix/config.json(CI 友好)",
"ctab.title": "准备好了吗?",
"ctab.sub": "一条 <code>npx</code> 即可开始。沙箱、可审阅、便宜 96%。",
"ctab.gh": "GitHub 仓库 →",
"ctab.npm": "npm 包",
"foot.tag": "Reasonix 只做 DeepSeek,做到底。",
"foot.col.project": "项目",
"foot.col.docs": "文档",
"foot.col.community": "社区",
"foot.changelog": "更新日志",
"foot.readme": "英文 README",
"foot.readme.zh": "中文 README",
"foot.arch": "架构文档",
"foot.issues": "问题反馈",
"foot.discuss": "讨论区",
"foot.copyright": "© 2026 Reasonix · MIT 协议",
},
};
function safeStorageGet(key) {
try {
return window.localStorage.getItem(key);
} catch (_) {
return null;
}
}
function safeStorageSet(key, value) {
try {
window.localStorage.setItem(key, value);
} catch (_) {
/* ignore */
}
}
function detectLang() {
const params = new URLSearchParams(window.location.search);
const queryLang = params.get("lang");
if (queryLang && SUPPORTED.includes(queryLang)) return queryLang;
const stored = safeStorageGet(STORAGE_KEY);
if (stored && SUPPORTED.includes(stored)) return stored;
const navLang = (navigator.language || navigator.userLanguage || "").toLowerCase();
if (navLang.startsWith("zh")) return "zh";
if (Array.isArray(navigator.languages)) {
for (const l of navigator.languages) {
if (l && l.toLowerCase().startsWith("zh")) return "zh";
}
}
return DEFAULT_LANG;
}
let currentLang = DEFAULT_LANG;
const langListeners = [];
// Version is rendered into translation strings via a `{version}` token
// (see hero.badge). Source of truth is npm — `loadVersion()` fetches
// it on page load and re-applies translations. Until that resolves
// we fall back to the most recently cached value, then to a baked-in
// default. Only places this constant matters: the user is offline AND
// visits the site for the first time. Bumping it occasionally on
// major version cuts is fine; the npm fetch handles everything else.
const VERSION_STORAGE_KEY = "reasonix.version";
const VERSION_FALLBACK = "0.12";
const versionListeners = [];
let currentVersion = VERSION_FALLBACK;
function applyVersion(v) {
if (typeof v !== "string" || !v || v === currentVersion) return;
currentVersion = v;
safeStorageSet(VERSION_STORAGE_KEY, v);
applyLang(currentLang); // re-render any `{version}` tokens
for (const fn of versionListeners) {
try {
fn(v);
} catch (_) {
/* ignore */
}
}
}
async function loadVersion() {
try {
const r = await fetch("https://registry.npmjs.org/reasonix/latest", {
cache: "no-cache",
});
if (!r.ok) return;
const data = await r.json();
if (data && typeof data.version === "string") applyVersion(data.version);
} catch (_) {
/* offline / firewall — keep cached or fallback */
}
}
function fillVersion(s) {
return typeof s === "string" ? s.replace(/\{version\}/g, currentVersion) : s;
}
function applyLang(lang) {
if (!SUPPORTED.includes(lang)) lang = DEFAULT_LANG;
const changed = lang !== currentLang;
currentLang = lang;
const dict = translations[lang];
document.documentElement.lang = lang === "zh" ? "zh-CN" : "en";
document.documentElement.setAttribute("data-lang", lang);
document.querySelectorAll("[data-i18n]").forEach((el) => {
const key = el.getAttribute("data-i18n");
if (dict[key] !== undefined) {
el.innerHTML = fillVersion(dict[key]);
}
});
document.querySelectorAll("[data-lang-btn]").forEach((btn) => {
const isActive = btn.getAttribute("data-lang-btn") === lang;
btn.setAttribute("aria-pressed", isActive ? "true" : "false");
});
safeStorageSet(STORAGE_KEY, lang);
if (changed) {
for (const fn of langListeners) {
try {
fn(lang);
} catch (_) {
/* ignore */
}
}
}
}
// Public API for sibling scripts (term-anim.js).
window.Reasonix = window.Reasonix || {};
window.Reasonix.t = function (key) {
const dict = translations[currentLang] || translations[DEFAULT_LANG];
return dict[key];
};
window.Reasonix.lang = function () {
return currentLang;
};
window.Reasonix.onLangChange = function (fn) {
if (typeof fn === "function") langListeners.push(fn);
};
window.Reasonix.version = function () {
return currentVersion;
};
window.Reasonix.onVersionChange = function (fn) {
if (typeof fn === "function") versionListeners.push(fn);
};
function wireLangButtons() {
document.querySelectorAll("[data-lang-btn]").forEach((btn) => {
btn.addEventListener("click", () => {
applyLang(btn.getAttribute("data-lang-btn"));
});
});
}
function wireCopyButtons() {
document.querySelectorAll("[data-copy]").forEach((btn) => {
btn.addEventListener("click", async () => {
const text = btn.getAttribute("data-copy");
try {
await navigator.clipboard.writeText(text);
} catch (_) {
const ta = document.createElement("textarea");
ta.value = text;
ta.style.position = "fixed";
ta.style.opacity = "0";
document.body.appendChild(ta);
ta.select();
try {
document.execCommand("copy");
} catch (_) {
/* ignore */
}
document.body.removeChild(ta);
}
const lang = document.documentElement.getAttribute("data-lang") || DEFAULT_LANG;
const original = translations[lang]["hero.copy"] || "Copy";
const done = translations[lang]["hero.copy.done"] || "Copied";
btn.textContent = done;
btn.classList.add("copied");
setTimeout(() => {
btn.textContent = original;
btn.classList.remove("copied");
}, 1600);
});
});
}
function init() {
// Use the cached npm version (if any) so the badge isn't visibly
// wrong on first paint; fall back to the baked-in default. Then
// fire off the live fetch — when it resolves, applyVersion()
// re-applies translations and notifies subscribers (term-anim).
const cached = safeStorageGet(VERSION_STORAGE_KEY);
if (typeof cached === "string" && /^\d+\.\d+/.test(cached)) currentVersion = cached;
applyLang(detectLang());
wireLangButtons();
wireCopyButtons();
loadVersion();
}
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", init);
} else {
init();
}
})();
+493
View File
@@ -0,0 +1,493 @@
<!doctype html>
<html lang="en" data-lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Reasonix — DeepSeek-native AI coding agent</title>
<meta
name="description"
content="Cache-first agent loop for DeepSeek V4. Ink TUI. MCP first-class. 94%+ prefix cache hit, ~96% cheaper than Claude on the same workload. No LangChain."
/>
<meta name="theme-color" content="#0b0f17" />
<meta property="og:title" content="Reasonix — DeepSeek-native AI coding agent" />
<meta
property="og:description"
content="Cache-first agent loop for DeepSeek V4 (flash + pro). Ink TUI. MCP first-class. No LangChain."
/>
<meta property="og:type" content="website" />
<meta property="og:url" content="https://esengine.github.io/reasonix/" />
<meta property="og:image" content="https://raw.githubusercontent.com/esengine/reasonix/main/docs/logo.svg" />
<meta name="twitter:card" content="summary_large_image" />
<link rel="icon" type="image/svg+xml" href="favicon.svg" />
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&family=JetBrains+Mono:wght@400;500;600;700&family=Noto+Sans+SC:wght@400;500;600;700;800&display=swap"
rel="stylesheet"
/>
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<div class="bg-grid" aria-hidden="true"></div>
<div class="bg-glow" aria-hidden="true"></div>
<header class="nav">
<a class="nav-brand" href="#top" aria-label="Reasonix">
<span class="brand-mark" aria-hidden="true">
<span class="diamond"></span>
<span class="diamond inner"></span>
</span>
<span class="brand-name">Reasonix</span>
</a>
<nav class="nav-links">
<a href="#features" data-i18n="nav.features">Features</a>
<a href="#quickstart" data-i18n="nav.quickstart">Quick start</a>
<a href="#benchmarks" data-i18n="nav.benchmarks">Benchmarks</a>
<a
href="https://github.com/esengine/reasonix"
target="_blank"
rel="noopener"
data-i18n="nav.github"
>GitHub</a
>
</nav>
<div class="nav-actions">
<div class="lang-switch" role="group" aria-label="Language">
<button data-lang-btn="en" type="button" aria-pressed="true">EN</button>
<button data-lang-btn="zh" type="button" aria-pressed="false">中文</button>
</div>
</div>
</header>
<main id="top">
<section class="hero">
<div class="hero-inner">
<div class="badge" data-i18n="hero.badge">v0.6 · DeepSeek V4 · cache-first</div>
<h1 class="hero-title">
<span class="grad-text" data-i18n="hero.title.line1">DeepSeek-native</span>
<br />
<span data-i18n="hero.title.line2">AI coding agent in your terminal</span>
</h1>
<p class="hero-sub" data-i18n="hero.sub">
Cache-first agent loop for DeepSeek V4 (flash + pro). Edits files as
reviewable SEARCH/REPLACE blocks. Ink TUI. MCP first-class. No LangChain.
</p>
<div class="hero-install">
<code class="install-cmd"
><span class="prompt">$</span> <span class="cmd">npx reasonix code</span></code
>
<button class="copy-btn" data-copy="npx reasonix code" data-i18n="hero.copy">
Copy
</button>
</div>
<div class="hero-ctas">
<a class="cta primary" href="#quickstart" data-i18n="hero.cta.start">
Get started →
</a>
<a
class="cta ghost"
href="https://github.com/esengine/reasonix"
target="_blank"
rel="noopener"
data-i18n="hero.cta.star"
>Star on GitHub</a
>
</div>
<div class="hero-stats">
<div class="stat">
<div class="stat-num grad-text">94.4%</div>
<div class="stat-label" data-i18n="hero.stat.cache">prefix cache hit rate</div>
</div>
<div class="stat">
<div class="stat-num grad-text">~96%</div>
<div class="stat-label" data-i18n="hero.stat.cost">cheaper vs Claude Sonnet 4.6</div>
</div>
<div class="stat">
<div class="stat-num grad-text">100%</div>
<div class="stat-label" data-i18n="hero.stat.pass">τ-bench-lite pass rate</div>
</div>
</div>
</div>
<div class="hero-terminal" aria-hidden="true">
<div class="term-bar">
<span class="dot r"></span><span class="dot y"></span><span class="dot g"></span>
<span class="term-title">reasonix code</span>
<button class="term-replay" type="button" data-replay aria-label="replay">↻</button>
</div>
<div class="term-body" id="term-body" data-anim-root></div>
</div>
</section>
<section class="why">
<div class="container">
<h2 class="section-title" data-i18n="why.title">Why Reasonix</h2>
<p class="section-sub" data-i18n="why.sub">
Every abstraction earns its weight against a DeepSeek-specific property —
dirt-cheap tokens, R1 traces, automatic prefix caching, JSON mode. Generic
wrappers leave these on the table.
</p>
<div class="why-grid">
<article class="why-card">
<div class="why-icon">◈</div>
<h3 data-i18n="why.cache.title">Cache-first loop</h3>
<p data-i18n="why.cache.body">
Append-only conversation log keeps the prompt prefix byte-stable across
turns, so DeepSeek's automatic cache hits 85–95% — not 40%.
</p>
</article>
<article class="why-card">
<div class="why-icon">¥</div>
<h3 data-i18n="why.cost.title">Cost is a pillar</h3>
<p data-i18n="why.cost.body">
Flash-first defaults, turn-end auto-compaction, model self-escalation
when (and only when) needed. Per-turn cost badge in the TUI.
</p>
</article>
<article class="why-card">
<div class="why-icon">⌨</div>
<h3 data-i18n="why.tui.title">Ink TUI, no web</h3>
<p data-i18n="why.tui.body">
Lives in your terminal. Streaming preview, slash commands, plan picker,
edit-confirm modal. Plain mode for stubborn Windows shells.
</p>
</article>
<article class="why-card">
<div class="why-icon">⊕</div>
<h3 data-i18n="why.mcp.title">MCP first-class</h3>
<p data-i18n="why.mcp.body">
Stdio + HTTP+SSE transports. Live progress notifications. Same
cache-safety + repair plumbing as native tools.
</p>
</article>
<article class="why-card">
<div class="why-icon">↶</div>
<h3 data-i18n="why.safe.title">Reviewable edits</h3>
<p data-i18n="why.safe.body">
Edits arrive as SEARCH/REPLACE blocks; nothing hits disk until /apply.
Per-file diff confirm modal, undo history, sandboxed paths.
</p>
</article>
<article class="why-card">
<div class="why-icon">∞</div>
<h3 data-i18n="why.ctx.title">1M-token aware</h3>
<p data-i18n="why.ctx.body">
Context gauge with proactive compaction, oversized tool-result repair,
forced-summary fallback near the window edge.
</p>
</article>
</div>
</div>
</section>
<section id="quickstart" class="quickstart">
<div class="container">
<h2 class="section-title" data-i18n="qs.title">Quick start (60 seconds)</h2>
<ol class="qs-steps">
<li>
<h3 data-i18n="qs.step1.title">Get a DeepSeek API key</h3>
<p data-i18n="qs.step1.body">
Free credit on signup at
<a href="https://platform.deepseek.com/api_keys" target="_blank" rel="noopener"
>platform.deepseek.com</a
>.
</p>
</li>
<li>
<h3 data-i18n="qs.step2.title">Point it at a project</h3>
<p data-i18n="qs.step2.body">No install needed.</p>
<pre class="code"><code>cd my-project
npx reasonix code</code></pre>
<p data-i18n="qs.step2.note">
First run walks you through a 30-second wizard (paste API key → pick
preset → pick MCP servers).
</p>
</li>
<li>
<h3 data-i18n="qs.step3.title">Ask it to edit</h3>
<p data-i18n="qs.step3.body">
The model proposes edits as SEARCH/REPLACE blocks — nothing hits disk
until you <code>/apply</code>.
</p>
</li>
</ol>
<p class="req" data-i18n="qs.req">
Requires Node ≥ 20.10. macOS, Linux, Windows (PowerShell · Git Bash · Windows
Terminal). Press <kbd>Esc</kbd> anytime to abort; <code>/help</code> for the
full command list.
</p>
</div>
</section>
<section id="features" class="features">
<div class="container">
<h2 class="section-title" data-i18n="feat.title">In the box</h2>
<div class="feat-grid">
<article class="feat">
<h3>
<span class="feat-tag">code</span>
<span data-i18n="feat.code.title">Pair programmer mode</span>
</h3>
<p data-i18n="feat.code.body">
<code>read_file</code> · <code>write_file</code> · <code>edit_file</code> ·
<code>search_files</code> · <code>directory_tree</code> ·
<code>run_command</code> with read-only allowlist. Sandboxed to the
launch root — no path escapes. Plan mode and per-edit review modal.
</p>
</article>
<article class="feat">
<h3>
<span class="feat-tag">memory</span>
<span data-i18n="feat.memory.title">Two-layer memory</span>
</h3>
<p data-i18n="feat.memory.body">
Committable <code>REASONIX.md</code> for team conventions plus a private
per-user <code>~/.reasonix/memory/</code> with global and per-project
scopes. The model can write to it via the <code>remember</code> tool.
</p>
</article>
<article class="feat">
<h3>
<span class="feat-tag">skills</span>
<span data-i18n="feat.skills.title">User-authored prompt packs</span>
</h3>
<p data-i18n="feat.skills.body">
Drop <code>SKILL.md</code> files anywhere. Names + descriptions are
pinned in the prefix; the model picks them autonomously, or you trigger
with <code>/skill name</code>.
</p>
</article>
<article class="feat">
<h3>
<span class="feat-tag">hooks</span>
<span data-i18n="feat.hooks.title">Lifecycle hooks</span>
</h3>
<p data-i18n="feat.hooks.body">
Shell commands fire at <code>PreToolUse</code> · <code>PostToolUse</code>
· <code>UserPromptSubmit</code> · <code>Stop</code>. Exit code drives
pass / block / warn.
</p>
</article>
<article class="feat">
<h3>
<span class="feat-tag">mcp</span>
<span data-i18n="feat.mcp.title">Bring your own tools</span>
</h3>
<p data-i18n="feat.mcp.body">
Wizard catalog, or <code>--mcp "name=cmd"</code> to attach stdio /
HTTP+SSE servers on the fly. Live progress bars on long calls.
</p>
</article>
<article class="feat">
<h3>
<span class="feat-tag">web</span>
<span data-i18n="feat.web.title">Web search built-in</span>
</h3>
<p data-i18n="feat.web.body">
<code>web_search</code> + <code>web_fetch</code> via Mojeek — no key, no
signup, off-by-flag for offline / CI. Bring-your-own provider via the
<code>WebSearchProvider</code> interface.
</p>
</article>
</div>
</div>
</section>
<section id="benchmarks" class="bench">
<div class="container">
<h2 class="section-title" data-i18n="bench.title">Verify the cache claim yourself</h2>
<p class="section-sub" data-i18n="bench.sub">
On the same τ-bench-lite workload (8 multi-turn tool-use tasks × 3 repeats =
48 runs per side), live DeepSeek <code>deepseek-chat</code>, sole variable
prefix stability:
</p>
<div class="bench-table-wrap">
<table class="bench-table">
<thead>
<tr>
<th data-i18n="bench.col.metric">metric</th>
<th data-i18n="bench.col.baseline">baseline (cache-hostile)</th>
<th data-i18n="bench.col.reasonix">Reasonix</th>
<th data-i18n="bench.col.delta">delta</th>
</tr>
</thead>
<tbody>
<tr>
<td data-i18n="bench.row.cache">cache hit</td>
<td>46.6%</td>
<td class="hi">94.4%</td>
<td>+47.7 pp</td>
</tr>
<tr>
<td data-i18n="bench.row.cost">cost / task</td>
<td>$0.002599</td>
<td class="hi">$0.001579</td>
<td><strong>−39%</strong></td>
</tr>
<tr>
<td data-i18n="bench.row.pass">pass rate</td>
<td>96% (23/24)</td>
<td class="hi">100% (24/24)</td>
<td>—</td>
</tr>
</tbody>
</table>
</div>
<p data-i18n="bench.repro.intro">Reproduce without spending an API credit:</p>
<pre class="code"><code>git clone https://github.com/esengine/reasonix.git &amp;&amp; cd reasonix &amp;&amp; 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</code></pre>
<p data-i18n="bench.repro.note">
The committed JSONL transcripts carry per-turn <code>usage</code>,
<code>cost</code>, and <code>prefixHash</code>. Reasonix's prefix hash stays
byte-stable across every model call.
</p>
</div>
</section>
<section class="cli">
<div class="container">
<h2 class="section-title" data-i18n="cli.title">CLI at a glance</h2>
<pre class="code"><code>npx reasonix code [path] <span class="hash"># <span data-i18n="cli.code">coding mode scoped to path</span></span>
npx reasonix <span class="hash"># <span data-i18n="cli.chat">chat (uses saved config)</span></span>
npx reasonix setup <span class="hash"># <span data-i18n="cli.setup">reconfigure the wizard</span></span>
npx reasonix run "ask anything" <span class="hash"># <span data-i18n="cli.run">one-shot, streams to stdout</span></span>
npx reasonix stats <span class="hash"># <span data-i18n="cli.stats">cross-session cost dashboard</span></span>
npx reasonix mcp inspect &lt;spec&gt; <span class="hash"># <span data-i18n="cli.mcp">probe a single MCP server</span></span></code></pre>
<p class="cli-flags" data-i18n="cli.flags.intro">Common flags:</p>
<pre class="code"><code>--preset &lt;fast|smart|max&gt; <span class="hash"># <span data-i18n="cli.f.preset">model + harvest + branch bundle</span></span>
--model &lt;id&gt; <span class="hash"># <span data-i18n="cli.f.model">explicit DeepSeek model id</span></span>
--mcp "name=cmd args…" <span class="hash"># <span data-i18n="cli.f.mcp">attach an MCP server (repeatable)</span></span>
--session &lt;name&gt; <span class="hash"># <span data-i18n="cli.f.session">named session</span></span>
--no-config <span class="hash"># <span data-i18n="cli.f.noconf">ignore ~/.reasonix/config.json (CI)</span></span></code></pre>
</div>
</section>
<section class="cta-band">
<div class="container">
<h2 data-i18n="ctab.title">Ready to try?</h2>
<p data-i18n="ctab.sub">
One <code>npx</code> away. Sandboxed. Reviewable. 96% cheaper.
</p>
<div class="hero-ctas center">
<a
class="cta primary"
href="https://github.com/esengine/reasonix"
target="_blank"
rel="noopener"
data-i18n="ctab.gh"
>GitHub repository →</a
>
<a
class="cta ghost"
href="https://www.npmjs.com/package/reasonix"
target="_blank"
rel="noopener"
data-i18n="ctab.npm"
>npm package</a
>
</div>
</div>
</section>
</main>
<footer class="foot">
<div class="container foot-inner">
<div>
<a href="#top" class="nav-brand">
<span class="brand-mark small" aria-hidden="true">
<span class="diamond"></span>
<span class="diamond inner"></span>
</span>
<span class="brand-name">Reasonix</span>
</a>
<p class="foot-tag" data-i18n="foot.tag">DeepSeek does deep, deeply.</p>
</div>
<div class="foot-cols">
<div>
<h4 data-i18n="foot.col.project">Project</h4>
<a href="https://github.com/esengine/reasonix" target="_blank" rel="noopener">GitHub</a>
<a href="https://www.npmjs.com/package/reasonix" target="_blank" rel="noopener">npm</a>
<a
href="https://github.com/esengine/reasonix/blob/main/CHANGELOG.md"
target="_blank"
rel="noopener"
data-i18n="foot.changelog"
>Changelog</a
>
<a
href="https://github.com/esengine/reasonix/blob/main/LICENSE"
target="_blank"
rel="noopener"
>MIT</a
>
</div>
<div>
<h4 data-i18n="foot.col.docs">Docs</h4>
<a
href="https://github.com/esengine/reasonix#readme"
target="_blank"
rel="noopener"
data-i18n="foot.readme"
>README</a
>
<a
href="https://github.com/esengine/reasonix/blob/main/README.zh-CN.md"
target="_blank"
rel="noopener"
data-i18n="foot.readme.zh"
>中文 README</a
>
<a
href="https://github.com/esengine/reasonix/blob/main/docs/ARCHITECTURE.md"
target="_blank"
rel="noopener"
data-i18n="foot.arch"
>Architecture</a
>
</div>
<div>
<h4 data-i18n="foot.col.community">Community</h4>
<a
href="https://github.com/esengine/reasonix/issues"
target="_blank"
rel="noopener"
data-i18n="foot.issues"
>Issues</a
>
<a
href="https://github.com/esengine/reasonix/discussions"
target="_blank"
rel="noopener"
data-i18n="foot.discuss"
>Discussions</a
>
</div>
</div>
</div>
<div class="foot-bottom">
<span data-i18n="foot.copyright">© 2026 Reasonix · MIT License</span>
</div>
</footer>
<script src="i18n.js"></script>
<script src="term-anim.js"></script>
</body>
</html>
+1189
View File
File diff suppressed because it is too large. Load diff
+420
View File
@@ -0,0 +1,420 @@
// Hero terminal animation — simulates a `reasonix code` session using
// the real TUI rendering primitives:
// ◇ / ◆ role glyphs + colored vertical accent bars
// ` ✓ tool_name ` pills (yellow bg, black text)
// EditBlockRow: rounded cyan border, filename, `- old` red / `+ new` green
// info rows: dim glyph + dim body (slate)
//
// Reads i18n strings via Reasonix.t(); restarts on language toggle.
(function () {
"use strict";
const ROOT_SEL = "[data-anim-root]";
const REPLAY_SEL = "[data-replay]";
const tr = (key, fallback) => {
if (window.Reasonix && typeof window.Reasonix.t === "function") {
const v = window.Reasonix.t(key);
if (v !== undefined && v !== null && v !== "") return v;
}
return fallback != null ? fallback : key;
};
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
function el(tag, cls, text) {
const n = document.createElement(tag);
if (cls) n.className = cls;
if (text != null) n.textContent = text;
return n;
}
// Brand gradient — same stops as src/cli/ui/theme.ts GRADIENT.
const GRADIENT = [
"#5eead4",
"#67e8f9",
"#7dd3fc",
"#93c5fd",
"#a5b4fc",
"#c4b5fd",
"#d8b4fe",
"#f0abfc",
];
// ──────────────────────────────────────────────────────────────────
// Header bar — `◈ REASONIX v0.12.x v4-flash REVIEW max … turn 1 · /help`
// Version comes from the i18n script (which fetched it from npm).
// Falls back to a baked-in default before the fetch lands.
// ──────────────────────────────────────────────────────────────────
function currentVersion() {
const r = window.Reasonix;
return (r && typeof r.version === "function" ? r.version() : null) || "0.12";
}
function buildHeader(turn) {
const h = el("div", "thead");
h.innerHTML =
'<span class="tw-mark">◈</span>' +
'<span class="tw-name">REASONIX</span>' +
`<span class="tw-ver">v${currentVersion()}</span>` +
'<span class="tw-model">v4-flash</span>' +
'<span class="tw-pill review">REVIEW</span>' +
'<span class="tw-effort">max</span>' +
'<span class="tw-spacer"></span>' +
'<span class="tw-turn">turn ' +
turn +
" · /help</span>";
return h;
}
// ──────────────────────────────────────────────────────────────────
// User row — ◇ glyph (cyan) + cyan vertical accent bar + text.
// Mirrors EventLog.tsx role="user" render.
// ──────────────────────────────────────────────────────────────────
function buildUserRow(text) {
const row = el("div", "trow trow-user");
row.innerHTML =
'<span class="trole role-user">◇</span>' +
'<span class="tbar-cyan">▎</span>' +
'<span class="trow-body"></span>';
row.querySelector(".trow-body").textContent = text;
return row;
}
// Same shape as a user row but the body content is built progressively
// by the animation. Returns the row + an `input` ref + a `caret` span.
function buildLiveUserRow() {
const row = el("div", "trow trow-user trow-live");
row.innerHTML =
'<span class="trole role-user">◇</span>' +
'<span class="tbar-cyan">▎</span>' +
'<span class="trow-body"><span class="tinput"></span><span class="tcaret">▍</span></span>';
row._input = row.querySelector(".tinput");
row._caret = row.querySelector(".tcaret");
return row;
}
// ──────────────────────────────────────────────────────────────────
// Tool pill row — ` ✓ tool_name ` duration dim summary /tool N
// Yellow bg pill (red bg for errors). Mirrors ToolPill in EventLog.tsx.
// ──────────────────────────────────────────────────────────────────
function buildToolRow(name, summary, durationLabel, indexHint) {
const row = el("div", "trow trow-tool");
const pill = el("span", "tpill tpill-ok");
pill.textContent = " ✓ " + name + " ";
row.appendChild(pill);
if (durationLabel) {
row.appendChild(el("span", "tdim", " " + durationLabel));
}
row.appendChild(el("span", "tdim", " " + summary));
if (indexHint) {
row.appendChild(el("span", "tdim tindex", " /tool " + indexHint));
}
return row;
}
// ──────────────────────────────────────────────────────────────────
// Assistant row — ◆ glyph + ` v4-flash ` pill, then a green-bordered
// body the caller fills with text + (optionally) an EditBlockRow.
// Returns { row, body } so the caller can append into body.
// ──────────────────────────────────────────────────────────────────
function buildAssistantRow() {
const row = el("div", "trow trow-asst");
row.innerHTML =
'<div class="trow-asst-head">' +
'<span class="trole role-asst">◆</span>' +
'<span class="tpill tpill-model"> v4-flash </span>' +
"</div>" +
'<div class="trow-asst-body">' +
'<span class="tbar-green">▎</span>' +
'<div class="trow-asst-content"></div>' +
"</div>";
return { row, body: row.querySelector(".trow-asst-content") };
}
// ──────────────────────────────────────────────────────────────────
// EditBlockRow — rounded cyan border, filename in cyan bold, then
// `- old` red and `+ new` green lines. NO literal SEARCH/REPLACE
// markers (the model's text format is parsed; only the diff is
// shown). Mirrors EditBlockRow in markdown.tsx.
// ──────────────────────────────────────────────────────────────────
function buildEditBlock(filename, oldLines, newLines) {
const box = el("div", "tedit");
const head = el("div", "tedit-head");
head.appendChild(el("span", "tedit-filename", filename));
box.appendChild(head);
const diff = el("div", "tedit-diff");
box.appendChild(diff);
return { box, diff, oldLines, newLines };
}
// ──────────────────────────────────────────────────────────────────
// Info row — colored glyph + dim body. Used for pending + applied
// status lines, mirrors EventLog.tsx role="info".
// ──────────────────────────────────────────────────────────────────
function buildInfoRow(glyph, glyphColor, body) {
const row = el("div", "trow trow-info");
const g = el("span", "tinfo-glyph", glyph);
g.style.color = glyphColor;
row.appendChild(g);
row.appendChild(el("span", "tdim", " " + body));
return row;
}
// ──────────────────────────────────────────────────────────────────
// Animate text into a target node, character by character.
// ──────────────────────────────────────────────────────────────────
async function typeInto(target, text, perChar, cancelled) {
for (let i = 0; i < text.length; i++) {
target.appendChild(document.createTextNode(text[i]));
const j = perChar * (0.85 + Math.random() * 0.3);
const ch = text[i];
const pause = /[,。、;:,.;:]/.test(ch) ? perChar * 4 : 0;
// eslint-disable-next-line no-await-in-loop
await sleep(j + pause);
if (cancelled && cancelled()) return;
}
}
// Cancellation token — interrupts in-flight cycles when the user
// toggles language or clicks replay so we don't double-render.
let token = 0;
async function runCycle(root) {
const myToken = ++token;
const cancelled = () => myToken !== token;
root.classList.remove("trun-fade");
root.innerHTML = "";
root.appendChild(buildHeader(1));
await sleep(400);
if (cancelled()) return;
// 1. Live user prompt — types the question, then converts to a
// permanent user row on submit.
const userMsg = tr(
"term.user",
"users.ts findByEmail is case-sensitive — login fails"
);
const live = buildLiveUserRow();
root.appendChild(live);
await sleep(400);
if (cancelled()) return;
await typeInto(live._input, userMsg, 32, cancelled);
if (cancelled()) return;
await sleep(550);
live._caret.remove();
live.classList.add("trow-sent");
// 2. Tool pills appear one by one. Real summaries come from
// summarizeToolResult() in summarize.ts — we hard-code the
// representative output for this scene.
await sleep(380);
if (cancelled()) return;
root.appendChild(
buildToolRow(
"search_files",
"matched 2 files: src/users.ts, src/users.test.ts",
"0.4s",
"1"
)
);
await sleep(560);
if (cancelled()) return;
root.appendChild(
buildToolRow("read_file", "read src/users.ts (412 chars)", "0.2s", "2")
);
await sleep(640);
if (cancelled()) return;
// 3. Assistant row — ◆ + model pill, then green-bordered body
// containing the streamed text and the EditBlockRow.
const a = buildAssistantRow();
root.appendChild(a.row);
await sleep(280);
if (cancelled()) return;
const replyP = el("p", "tmd-p");
a.body.appendChild(replyP);
const replyMsg = tr(
"term.found",
"Found it. findByEmail uses === directly. Switching to lowercase normalization."
);
await typeInto(replyP, replyMsg, 18, cancelled);
if (cancelled()) return;
await sleep(360);
// 4. EditBlockRow — rounded cyan border with filename + colored
// diff lines. No SEARCH/REPLACE markers.
const eb = buildEditBlock(
"src/users.ts",
[" return users.find(u => u.email === email);"],
[
" const needle = email.toLowerCase();",
" return users.find(u => u.email.toLowerCase() === needle);",
]
);
a.body.appendChild(eb.box);
await sleep(220);
if (cancelled()) return;
for (const line of eb.oldLines) {
const r = el("div", "tdiff tdiff-old", "- " + line);
eb.diff.appendChild(r);
// eslint-disable-next-line no-await-in-loop
await sleep(180);
if (cancelled()) return;
}
for (const line of eb.newLines) {
const r = el("div", "tdiff tdiff-new", "+ " + line);
eb.diff.appendChild(r);
// eslint-disable-next-line no-await-in-loop
await sleep(180);
if (cancelled()) return;
}
await sleep(420);
if (cancelled()) return;
// 5. Pending info row — slate `▸` + dim body. Real text from
// formatPendingPreview() in edit-history.ts.
root.appendChild(
buildInfoRow(
"▸",
"#94a3b8",
tr(
"term.pending",
"1 pending edit block(s) — /apply (or y) to commit · /discard (or n) to drop"
)
)
);
await sleep(1700);
if (cancelled()) return;
// 6. /apply — second user turn. Live row, types `/apply`, then
// transforms to a sent row. No tool pills (slash is local).
const apply = buildLiveUserRow();
root.appendChild(apply);
await sleep(420);
if (cancelled()) return;
await typeInto(apply._input, "/apply", 75, cancelled);
if (cancelled()) return;
await sleep(380);
apply._caret.remove();
apply.classList.add("trow-sent");
// 7. Applied info rows — first the header, then the per-file line.
// Mirrors formatEditResults() in edit-history.ts.
await sleep(420);
root.appendChild(
buildInfoRow(
"▸",
"#94a3b8",
"edit blocks: 1/1 applied — /undo to roll back, or `git diff` to review"
)
);
const ok = el("div", "trow trow-info trow-info-detail");
const gl = el("span", "tinfo-glyph", "✓");
gl.style.color = "#4ade80";
ok.appendChild(el("span", "tdim", " "));
ok.appendChild(gl);
ok.appendChild(el("span", "tdim", " applied src/users.ts"));
root.appendChild(ok);
await sleep(2800);
if (cancelled()) return;
// 8. Fade and loop.
root.classList.add("trun-fade");
await sleep(900);
if (cancelled()) return;
runCycle(root);
}
// Reduced-motion fallback — paint the final scene without typing.
function runStatic(root) {
root.innerHTML = "";
root.appendChild(buildHeader(1));
root.appendChild(buildUserRow(tr("term.user", "")));
root.appendChild(
buildToolRow(
"search_files",
"matched 2 files: src/users.ts, src/users.test.ts",
"0.4s",
"1"
)
);
root.appendChild(
buildToolRow("read_file", "read src/users.ts (412 chars)", "0.2s", "2")
);
const a = buildAssistantRow();
root.appendChild(a.row);
const p = el("p", "tmd-p");
p.textContent = tr("term.found", "");
a.body.appendChild(p);
const eb = buildEditBlock(
"src/users.ts",
[" return users.find(u => u.email === email);"],
[
" const needle = email.toLowerCase();",
" return users.find(u => u.email.toLowerCase() === needle);",
]
);
a.body.appendChild(eb.box);
eb.oldLines.forEach((l) =>
eb.diff.appendChild(el("div", "tdiff tdiff-old", "- " + l))
);
eb.newLines.forEach((l) =>
eb.diff.appendChild(el("div", "tdiff tdiff-new", "+ " + l))
);
root.appendChild(buildInfoRow("▸", "#94a3b8", tr("term.pending", "")));
}
function init() {
const root = document.querySelector(ROOT_SEL);
if (!root) return;
if (window.Reasonix && typeof window.Reasonix.onLangChange === "function") {
window.Reasonix.onLangChange(() => runCycle(root));
}
// npm version arrives async after first paint — patch the header's
// version pill in place so we don't have to re-run the whole
// animation just to update one number.
if (window.Reasonix && typeof window.Reasonix.onVersionChange === "function") {
window.Reasonix.onVersionChange((v) => {
const pill = root.querySelector(".tw-ver");
if (pill) pill.textContent = "v" + v;
});
}
document.querySelectorAll(REPLAY_SEL).forEach((btn) => {
btn.addEventListener("click", () => runCycle(root));
});
const prm = window.matchMedia
? window.matchMedia("(prefers-reduced-motion: reduce)")
: null;
if (prm && prm.matches) {
runStatic(root);
return;
}
runCycle(root);
}
window.Reasonix = window.Reasonix || {};
window.Reasonix.term = {
replay() {
const root = document.querySelector(ROOT_SEL);
if (root) runCycle(root);
},
};
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", init);
} else {
init();
}
})();
+1530 -555
View File
File diff suppressed because it is too large. Load diff
+37 -3
View File
@@ -1,7 +1,7 @@
{
"name": "reasonix",
"version": "0.5.23",
"description": "DeepSeek-native agent framework: cache-first loop, R1 thought harvesting, tool-call repair.",
"version": "0.16.0",
"description": "DeepSeek-native coding agent: cache-first loop, flash-first cost control, tool-call repair.",
"type": "module",
"bin": {
"reasonix": "dist/cli/index.js"
@@ -18,11 +18,16 @@
"files": [
"dist",
"data/deepseek-tokenizer.json.gz",
"dashboard/index.html",
"dashboard/app.js",
"dashboard/app.css",
"dashboard/codemirror.js",
"README.md",
"LICENSE"
],
"scripts": {
"build": "tsup",
"build:cm": "node scripts/bundle-codemirror.mjs",
"dev": "tsx src/cli/index.ts",
"chat": "tsx src/cli/index.ts chat",
"test": "vitest run",
@@ -31,8 +36,14 @@
"lint:fix": "biome check --write src tests",
"format": "biome format --write src tests",
"typecheck": "tsc --noEmit",
"verify": "npm run lint && npm run typecheck && npm run test --silent",
"prepare": "simple-git-hooks || true",
"prepublishOnly": "npm run lint && npm run typecheck && npm run test && npm run build"
},
"simple-git-hooks": {
"pre-commit": "npm run lint",
"pre-push": "npm run verify"
},
"keywords": [
"agent",
"llm",
@@ -62,12 +73,35 @@
"ink": "^5.1.0",
"ink-spinner": "^5.0.0",
"ink-text-input": "^6.0.0",
"react": "^18.3.1"
"react": "^18.3.1",
"string-width": "^7.2.0"
},
"devDependencies": {
"@biomejs/biome": "^1.9.4",
"@codemirror/autocomplete": "^6.16.0",
"@codemirror/commands": "^6.5.0",
"@codemirror/lang-cpp": "^6.0.2",
"@codemirror/lang-css": "^6.2.1",
"@codemirror/lang-go": "^6.0.1",
"@codemirror/lang-html": "^6.4.9",
"@codemirror/lang-javascript": "^6.2.2",
"@codemirror/lang-json": "^6.0.1",
"@codemirror/lang-markdown": "^6.2.5",
"@codemirror/lang-php": "^6.0.1",
"@codemirror/lang-python": "^6.1.6",
"@codemirror/lang-rust": "^6.0.1",
"@codemirror/lang-sql": "^6.6.4",
"@codemirror/lang-xml": "^6.1.0",
"@codemirror/lang-yaml": "^6.1.1",
"@codemirror/language": "^6.10.1",
"@codemirror/search": "^6.5.6",
"@codemirror/state": "^6.4.1",
"@codemirror/theme-one-dark": "^6.1.2",
"@codemirror/view": "^6.26.0",
"@types/node": "^22.9.0",
"@types/react": "^18.3.12",
"esbuild": "^0.21.5",
"simple-git-hooks": "^2.13.1",
"tsup": "^8.3.5",
"tsx": "^4.19.2",
"typescript": "^5.6.3",
+105
View File
@@ -0,0 +1,105 @@
#!/usr/bin/env node
/**
* Bundle every CodeMirror package the dashboard editor needs into one
* local ESM file at dashboard/codemirror.js. Replaces the runtime
* esm.sh imports — CDN multi-instance issues (different copies of
* @lezer/highlight breaking tag identity, etc.) just go away once
* everything ships in a single bundle.
*
* Run after bumping any @codemirror/* package version:
* node scripts/bundle-codemirror.mjs
*
* The output is committed to the repo and shipped in the npm tarball.
*/
import { build } from "esbuild";
import { mkdirSync, writeFileSync } from "node:fs";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const here = dirname(fileURLToPath(import.meta.url));
const repoRoot = resolve(here, "..");
const entryPath = resolve(repoRoot, "scripts/.cm-entry.mjs");
const outPath = resolve(repoRoot, "dashboard/codemirror.js");
// Re-export every symbol the editor needs as a single flat record.
// Same shape app.js's old loadCodeMirror() returned, so swapping the
// runtime fetch for `import * as cm from "./codemirror.js"` is a
// one-line change on the consumer side.
const entry = `
import { EditorState, Compartment } from "@codemirror/state";
import {
EditorView, keymap, lineNumbers, highlightActiveLine,
highlightActiveLineGutter, drawSelection,
} from "@codemirror/view";
import {
defaultKeymap, history, historyKeymap, indentWithTab,
} from "@codemirror/commands";
import {
syntaxHighlighting, defaultHighlightStyle, bracketMatching,
indentOnInput, foldGutter, foldKeymap,
} from "@codemirror/language";
import {
closeBrackets, closeBracketsKeymap, autocompletion, completionKeymap,
} from "@codemirror/autocomplete";
import { searchKeymap, highlightSelectionMatches } from "@codemirror/search";
import { oneDark } from "@codemirror/theme-one-dark";
import { javascript } from "@codemirror/lang-javascript";
import { python } from "@codemirror/lang-python";
import { markdown } from "@codemirror/lang-markdown";
import { json } from "@codemirror/lang-json";
import { html as htmlLang } from "@codemirror/lang-html";
import { css } from "@codemirror/lang-css";
import { rust } from "@codemirror/lang-rust";
import { go } from "@codemirror/lang-go";
import { cpp } from "@codemirror/lang-cpp";
import { yaml } from "@codemirror/lang-yaml";
import { sql } from "@codemirror/lang-sql";
import { xml } from "@codemirror/lang-xml";
import { php } from "@codemirror/lang-php";
export {
EditorState, Compartment,
EditorView, keymap, lineNumbers, highlightActiveLine,
highlightActiveLineGutter, drawSelection,
defaultKeymap, history, historyKeymap, indentWithTab,
syntaxHighlighting, defaultHighlightStyle, bracketMatching,
indentOnInput, foldGutter, foldKeymap,
closeBrackets, closeBracketsKeymap, autocompletion, completionKeymap,
searchKeymap, highlightSelectionMatches,
oneDark,
};
export const langs = {
javascript,
typescript: () => javascript({ typescript: true }),
python,
markdown,
json,
html: htmlLang,
css,
rust,
go,
cpp,
yaml,
sql,
xml,
php,
};
`;
mkdirSync(dirname(entryPath), { recursive: true });
writeFileSync(entryPath, entry);
await build({
entryPoints: [entryPath],
outfile: outPath,
bundle: true,
format: "esm",
target: "es2022",
minify: true,
legalComments: "none",
logLevel: "info",
});
console.log(`bundled → ${outPath}`);
+28
View File
@@ -0,0 +1,28 @@
// Minimal Ctrl+C probe. Usage: node scripts/ctrlc-probe.mjs
// Reproduces the exact stdin setup Reasonix uses, then logs every byte
// it sees and exits on \x03. Tells us whether the OS even delivers
// Ctrl+C to a Node child on this terminal.
process.stdin.setRawMode(true);
process.stdin.setEncoding("utf8");
process.stdin.resume();
console.log("ctrl+c probe armed. press keys; ctrl+c should exit.");
console.log("if ctrl+c does NOT exit, the byte never reaches Node on this terminal.\n");
process.stdin.on("data", (chunk) => {
const s = String(chunk);
for (const ch of s) {
const code = ch.charCodeAt(0);
process.stdout.write(`got byte: 0x${code.toString(16).padStart(2, "0")} (${JSON.stringify(ch)})\r\n`);
if (ch === "\x03") {
process.stdout.write("→ \\x03 detected, exiting.\r\n");
process.exit(0);
}
}
});
process.on("SIGINT", () => {
process.stdout.write("→ SIGINT received, exiting.\r\n");
process.exit(0);
});
+30
View File
@@ -0,0 +1,30 @@
// Shift+Enter probe. Usage: node scripts/shift-enter-probe.mjs
// Enables modifyOtherKeys + kitty keyboard protocol, then prints the
// raw bytes for every keypress. Press Shift+Enter and see what your
// terminal actually emits — if it's just "0x0d", the host doesn't
// support either protocol and there's nothing Reasonix can do at the
// raw-stdin layer.
process.stdout.write("\u001b[>4;2m"); // modifyOtherKeys level 2 (xterm)
process.stdout.write("\u001b[>1u"); // kitty keyboard protocol level 1
process.stdin.setRawMode(true);
process.stdin.setEncoding("utf8");
process.stdin.resume();
console.log("shift+enter probe armed. press keys; ctrl+c exits.");
console.log("expected for shift+enter:");
console.log(" modifyOtherKeys → 0x1b 0x5b 0x32 0x37 0x3b 0x32 0x3b 0x31 0x33 0x7e (\\x1b[27;2;13~)");
console.log(" kitty → 0x1b 0x5b 0x31 0x33 0x3b 0x32 0x75 (\\x1b[13;2u)");
console.log(" unsupported → 0x0d (just \\r — no way to distinguish)\n");
process.stdin.on("data", (chunk) => {
const s = String(chunk);
const bytes = [...s].map((c) => `0x${c.charCodeAt(0).toString(16).padStart(2, "0")}`).join(" ");
process.stdout.write(`got: ${bytes} (${JSON.stringify(s)})\r\n`);
if (s.includes("\x03")) {
process.stdout.write("\u001b[>4m"); // disable modifyOtherKeys
process.stdout.write("\u001b[<u"); // pop kitty level
process.exit(0);
}
});
+46
View File
@@ -0,0 +1,46 @@
import { type WriteStream, chmodSync, createWriteStream, mkdirSync } from "node:fs";
import { dirname, join } from "node:path";
import type { Event } from "../core/events.js";
import { sanitizeName, sessionsDir } from "../memory/session.js";
import type { EventSink } from "../ports/event-sink.js";
export function eventLogPath(sessionName: string): string {
return join(sessionsDir(), `${sanitizeName(sessionName)}.events.jsonl`);
}
export class JsonlEventSink implements EventSink {
private buffered = 0;
constructor(private readonly stream: WriteStream) {}
append(ev: Event): void {
this.stream.write(`${JSON.stringify(ev)}\n`);
this.buffered++;
}
flush(): Promise<void> {
return new Promise((resolve) => {
if (this.buffered === 0) return resolve();
this.stream.uncork();
this.buffered = 0;
resolve();
});
}
close(): Promise<void> {
return new Promise((resolve) => {
this.stream.end(() => resolve());
});
}
}
export function openEventSink(path: string): JsonlEventSink {
mkdirSync(dirname(path), { recursive: true });
const stream = createWriteStream(path, { flags: "a" });
try {
chmodSync(path, 0o600);
} catch {
/* chmod no-op on Windows */
}
return new JsonlEventSink(stream);
}
+30
View File
@@ -0,0 +1,30 @@
import { existsSync, readFileSync } from "node:fs";
import type { Event } from "../core/events.js";
import type { EventSource } from "../ports/event-sink.js";
import { eventLogPath } from "./event-sink-jsonl.js";
export function readEventLogFile(path: string): Event[] {
if (!existsSync(path)) return [];
const raw = readFileSync(path, "utf8");
const out: Event[] = [];
for (const line of raw.split(/\r?\n/)) {
const trimmed = line.trim();
if (!trimmed) continue;
try {
const ev = JSON.parse(trimmed) as Event;
if (ev && typeof ev === "object" && typeof (ev as { type?: unknown }).type === "string") {
out.push(ev);
}
} catch {
/* malformed mid-line write — best-effort skip */
}
}
return out;
}
export class JsonlEventSource implements EventSource {
async *read(sessionName: string): AsyncIterable<Event> {
const events = readEventLogFile(eventLogPath(sessionName));
for (const ev of events) yield ev;
}
}
+243 -109
View File
@@ -1,35 +1,12 @@
/**
* 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.
*/
/** Expand `@path` mentions inline. Paths must resolve inside rootDir; escapes / oversize get a skip note, not content. */
import { type Dirent, existsSync, readFileSync, readdirSync, statSync } from "node:fs";
import { readdir, stat } from "node:fs/promises";
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",
@@ -54,23 +31,7 @@ export interface ListFilesOptions {
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).
*/
/** Sync on purpose — fits the TUI's single-turn-per-tick model. Skips dot-DIRS but keeps dotfiles. */
export function listFilesSync(root: string, opts: ListFilesOptions = {}): string[] {
return listFilesWithStatsSync(root, opts).map((e) => e.path);
}
@@ -82,15 +43,7 @@ export interface FileWithStats {
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).
*/
/** Stat failures kept as `mtimeMs: 0` — entry still appears, sinks to bottom of 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);
@@ -128,24 +81,84 @@ export function listFilesWithStatsSync(root: string, opts: ListFilesOptions = {}
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.
*/
/** Parallel stat per directory — Windows stat syscalls are 3-5× slower than Linux. */
export async function listFilesWithStatsAsync(
root: string,
opts: ListFilesOptions = {},
): Promise<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 = async (dirAbs: string, dirRel: string): Promise<void> => {
if (out.length >= maxResults) return;
let entries: Dirent[];
try {
entries = await readdir(dirAbs, { withFileTypes: true });
} catch {
return;
}
entries.sort((a, b) => a.name.localeCompare(b.name));
// Pull file stats for THIS directory in parallel before
// recursing — readdir gave us all the names at once, may as
// well issue all the stats at once too. Recursion stays
// sequential so the alphabetical ordering of the merged list
// matches the sync walk's contract.
const fileEnts: Dirent[] = [];
for (const ent of entries) {
if (out.length >= maxResults) break;
if (ent.isDirectory()) {
if (ent.name.startsWith(".") || ignore.has(ent.name)) continue;
// Drain pending file stats from THIS directory before
// descending so the output order stays DFS-alphabetical.
if (fileEnts.length > 0) {
await statBatch(fileEnts, dirAbs, dirRel, out, maxResults);
fileEnts.length = 0;
if (out.length >= maxResults) return;
}
await walk(join(dirAbs, ent.name), dirRel ? `${dirRel}/${ent.name}` : ent.name);
} else if (ent.isFile()) {
fileEnts.push(ent);
}
}
if (fileEnts.length > 0 && out.length < maxResults) {
await statBatch(fileEnts, dirAbs, dirRel, out, maxResults);
}
};
await walk(rootAbs, "");
return out;
}
async function statBatch(
ents: readonly Dirent[],
dirAbs: string,
dirRel: string,
out: FileWithStats[],
maxResults: number,
): Promise<void> {
const remaining = Math.max(0, maxResults - out.length);
const batch = ents.slice(0, remaining);
const stats = await Promise.all(
batch.map((e) =>
stat(join(dirAbs, e.name))
.then((s) => s.mtimeMs)
.catch(() => 0),
),
);
for (let i = 0; i < batch.length; i++) {
const ent = batch[i]!;
out.push({
path: dirRel ? `${dirRel}/${ent.name}` : ent.name,
mtimeMs: stats[i] ?? 0,
});
}
}
/** Trailing-token only, anchored at end-of-input — distinct from `AT_MENTION_PATTERN` which scans all. */
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;
@@ -163,31 +176,9 @@ 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,
@@ -249,17 +240,7 @@ export function rankPickerCandidates(
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.
*/
/** Word-boundary anchor rejects `@` embedded in emails / social handles; trailing `.` stripped before lookup. */
export const AT_MENTION_PATTERN = /(?<=^|\s)@([a-zA-Z0-9_./\\-]+)/g;
export interface AtMentionExpansion {
@@ -278,10 +259,6 @@ export interface AtMentionExpansion {
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;
@@ -290,11 +267,6 @@ export interface AtMentionOptions {
};
}
/**
* 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,
@@ -395,3 +367,165 @@ const defaultFs: NonNullable<AtMentionOptions["fs"]> = {
},
read: (p) => readFileSync(p, "utf8"),
};
// @url mentions — async sibling of @path. Matches `@http(s)://...` after a
// word boundary, fetches each URL once per session (in-memory cache), and
// appends a "Referenced URLs" block under the prompt the model sees. Uses
// the same web-fetch + HTML-strip pipeline as the model's `web_fetch` tool
// so a `@url` reference and a model-issued fetch produce identical content.
/** Trailing punctuation stripped separately — URLs legitimately contain `,` `.` `)` in query strings. */
export const AT_URL_PATTERN = /(?<=^|\s)@(https?:\/\/\S+)/g;
/** Default cap on inlined URL body (chars). Matches DEFAULT_AT_MENTION_MAX_BYTES order-of-magnitude. */
export const DEFAULT_AT_URL_MAX_CHARS = 32_000;
export interface AtUrlExpansion {
/** The raw `@url` token as it appeared in the text. */
token: string;
/** Absolute URL (after trailing-punctuation strip). */
url: string;
/** True if content was inlined. False = skipped (reason in `skip`). */
ok: boolean;
/** Page title when extractable from `<title>`. */
title?: string;
/** Char count of the (post-truncation) inlined body. */
chars?: number;
/** True iff the original page exceeded `maxChars` and was clipped. */
truncated?: boolean;
/** Why the mention was skipped — set when ok=false. */
skip?: "fetch-error" | "non-text" | "timeout" | "blocked";
/** Free-form error message attached to skip outcomes. */
error?: string;
}
export interface AtUrlOptions {
/** Max chars of inlined body per URL. Default DEFAULT_AT_URL_MAX_CHARS. */
maxChars?: number;
/** Per-URL fetch timeout in ms. */
timeoutMs?: number;
fetcher?: (
url: string,
opts: { maxChars?: number; timeoutMs?: number; signal?: AbortSignal },
) => Promise<{ url: string; title?: string; text: string; truncated: boolean }>;
cache?: Map<string, AtUrlExpansion & { body?: string }>;
/** Forward Esc/abort to the fetcher. */
signal?: AbortSignal;
}
export async function expandAtUrls(
text: string,
opts: AtUrlOptions = {},
): Promise<{ text: string; expansions: AtUrlExpansion[] }> {
const maxChars = opts.maxChars ?? DEFAULT_AT_URL_MAX_CHARS;
const fetcher = opts.fetcher;
if (!fetcher) {
throw new Error("expandAtUrls: fetcher option is required (wire src/tools/web.ts:webFetch)");
}
// De-dupe by URL so the same `@https://x.com` referenced twice fetches once.
const seen = new Map<string, AtUrlExpansion>();
const bodies = new Map<string, string>();
const order: string[] = [];
for (const match of text.matchAll(AT_URL_PATTERN)) {
const rawUrl = match[1] ?? "";
const url = stripUrlTail(rawUrl);
if (!url) continue;
if (seen.has(url)) continue;
const cached = opts.cache?.get(url);
if (cached) {
seen.set(url, cached);
if (cached.body) bodies.set(url, cached.body);
order.push(url);
continue;
}
let expansion: AtUrlExpansion;
let body = "";
try {
const page = await fetcher(url, {
maxChars,
timeoutMs: opts.timeoutMs,
signal: opts.signal,
});
body = page.text;
expansion = {
token: `@${url}`,
url,
ok: true,
title: page.title,
chars: body.length,
truncated: page.truncated,
};
} catch (err) {
const message = (err as Error).message ?? String(err);
// Tag a few common shapes so the UI can hint at causes.
let skip: AtUrlExpansion["skip"] = "fetch-error";
if (/aborted|timeout/i.test(message)) skip = "timeout";
else if (/40\d|forbidden|access denied|captcha/i.test(message)) skip = "blocked";
expansion = {
token: `@${url}`,
url,
ok: false,
skip,
error: message,
};
}
seen.set(url, expansion);
if (body) bodies.set(url, body);
if (opts.cache) opts.cache.set(url, { ...expansion, body });
order.push(url);
}
if (seen.size === 0) return { text, expansions: [] };
const expansions = order.map((u) => seen.get(u)!).filter(Boolean);
const blocks: string[] = [];
for (const ex of expansions) {
if (ex.ok) {
const titleAttr = ex.title ? ` title="${escapeAttr(ex.title)}"` : "";
const truncTag = ex.truncated ? ' truncated="true"' : "";
const body = bodies.get(ex.url) ?? "";
blocks.push(`<url href="${ex.url}"${titleAttr}${truncTag}>\n${body}\n</url>`);
} else {
const reasonAttr = ex.skip ?? "fetch-error";
blocks.push(`<url href="${ex.url}" skipped="${reasonAttr}" />`);
}
}
const augmented = `${text}\n\n[Referenced URLs]\n${blocks.join("\n\n")}`;
return { text: augmented, expansions };
}
/** Only strips `.,;:!?` and unmatched close-brackets — internal path / query punctuation preserved. */
export function stripUrlTail(raw: string): string {
let s = raw;
while (s.length > 0) {
const last = s[s.length - 1]!;
if (".,;:!?".includes(last)) {
s = s.slice(0, -1);
continue;
}
if (")]}>".includes(last)) {
// Only strip if the matching open bracket isn't elsewhere in the
// URL — avoids butchering legitimate `(thing)` query fragments.
const open = ({ ")": "(", "]": "[", "}": "{", ">": "<" } as const)[
last as ")" | "]" | "}" | ">"
];
if (!s.includes(open)) {
s = s.slice(0, -1);
continue;
}
}
break;
}
return s;
}
function escapeAttr(s: string): string {
return s
.replace(/"/g, "&quot;")
.replace(/[\r\n]+/g, " ")
.trim();
}
+88 -31
View File
@@ -9,17 +9,20 @@ 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 { StreamableHttpTransport } from "../../mcp/streamable-http.js";
import {
loadSessionMessages,
rewriteSession,
sessionPath as sessionPathOf,
} from "../../session.js";
} from "../../memory/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 {
@@ -35,6 +38,13 @@ export interface ChatOptions {
transcript?: string;
harvest?: boolean;
branch?: number;
/**
* Soft USD cap on session spend. Undefined → no cap (default).
* The loop warns once at 80% and refuses to start a new turn at
* 100%. Users can bump or clear via `/budget <usd>` / `/budget off`
* mid-session.
*/
budgetUsd?: number;
session?: string;
/** Zero or more MCP server specs. Each: `"name=cmd args..."` or `"cmd args..."`. */
mcp?: string[];
@@ -51,11 +61,27 @@ 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;
/**
* `/cwd <path>` callback — re-registers every rootDir-dependent
* native tool against the new path. Optional so embedders that
* don't want live cwd switching can omit it (the slash command
* then falls back to non-tool updates only).
*/
reregisterTools?: (rootDir: string) => void;
};
/** 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;
/**
* When true, suppress auto-launch of the embedded web dashboard.
* Default behavior (false/undefined) is to boot it on mount so the
* URL is visible in the status bar.
*/
noDashboard?: boolean;
}
interface RootProps extends ChatOptions {
@@ -101,39 +127,51 @@ function Root({
}
process.env.DEEPSEEK_API_KEY = key;
// KeystrokeProvider must wrap App from OUTSIDE — App.tsx itself
// calls `useKeystroke` in its function body for global hotkeys
// (Ctrl+C, Esc abort, Shift+Tab edit-mode cycle, @-mention picker,
// slash-suggestion navigation). If the provider lives inside App's
// render, `useContext(KeystrokeContext)` returns `null` at hook
// call time and those handlers silently never subscribe.
if (pending && appProps.session) {
return (
<SessionPicker
sessionName={appProps.session}
messageCount={pending.messageCount}
lastActive={pending.lastActive}
onChoose={(choice) => {
if (choice === "new" || choice === "delete") {
// Wipe the session file. "new" and "delete" do the same thing
// at this step — the distinction is only in the picker's
// wording. A future enhancement could archive on "new".
rewriteSession(appProps.session!, []);
}
setPending(undefined);
}}
/>
<KeystrokeProvider>
<SessionPicker
sessionName={appProps.session}
messageCount={pending.messageCount}
lastActive={pending.lastActive}
onChoose={(choice) => {
if (choice === "new" || choice === "delete") {
// Wipe the session file. "new" and "delete" do the same thing
// at this step — the distinction is only in the picker's
// wording. A future enhancement could archive on "new".
rewriteSession(appProps.session!, []);
}
setPending(undefined);
}}
/>
</KeystrokeProvider>
);
}
return (
<App
model={appProps.model}
system={appProps.system}
transcript={appProps.transcript}
harvest={appProps.harvest}
branch={appProps.branch}
session={appProps.session}
tools={tools}
mcpSpecs={mcpSpecs}
mcpServers={mcpServers}
progressSink={progressSink}
codeMode={appProps.codeMode}
/>
<KeystrokeProvider>
<App
model={appProps.model}
system={appProps.system}
transcript={appProps.transcript}
harvest={appProps.harvest}
branch={appProps.branch}
budgetUsd={appProps.budgetUsd}
session={appProps.session}
tools={tools}
mcpSpecs={mcpSpecs}
mcpServers={mcpServers}
progressSink={progressSink}
codeMode={appProps.codeMode}
noDashboard={appProps.noDashboard}
/>
</KeystrokeProvider>
);
}
@@ -170,7 +208,9 @@ export async function chatCommand(opts: ChatOptions): Promise<void> {
const transport: McpTransport =
spec.transport === "sse"
? new SseTransport({ url: spec.url })
: new StdioTransport({ command: spec.command, args: spec.args });
: spec.transport === "streamable-http"
? new StreamableHttpTransport({ url: spec.url })
: new StdioTransport({ command: spec.command, args: spec.args });
const mcp = new McpClient({ transport });
await mcp.initialize();
const bridge = await bridgeMcpTools(mcp, {
@@ -200,7 +240,9 @@ export async function chatCommand(opts: ChatOptions): Promise<void> {
}
const label = spec.name ?? "anon";
const source =
spec.transport === "sse" ? spec.url : `${spec.command} ${spec.args.join(" ")}`;
spec.transport === "sse" || spec.transport === "streamable-http"
? spec.url
: `${spec.command} ${spec.args.join(" ")}`;
process.stderr.write(
`▸ MCP[${label}]: ${bridge.registeredNames.length} tool(s) from ${source}\n`,
);
@@ -255,6 +297,10 @@ export async function chatCommand(opts: ChatOptions): Promise<void> {
if (!opts.seedTools) {
if (!tools) tools = new ToolRegistry();
registerMemoryTools(tools, {});
// `ask_choice` — branching primitive, useful in chat too (stylistic
// preferences, doc language, library picks). Independent of plan
// mode, which chat doesn't have anyway.
registerChoiceTool(tools);
}
// Decide whether to show the session picker. It's gated on: session
@@ -274,6 +320,17 @@ export async function chatCommand(opts: ChatOptions): Promise<void> {
rewriteSession(opts.session, []);
}
// No startup clear, no resize listener. Earlier attempts wrote
// various combinations of \x1b[2J / \x1b[3J / cursor-home to
// present a 'clean canvas' on launch and to neutralize Ink's
// eraseLines miscount on resize, but on xterm.js-based terminals
// (VSCode integrated terminal in particular) those sequences
// interfere with scrollback in ways that make wheel-up scroll
// dead. Letting Ink mount directly leaves the user's previous
// shell prompt visible above (scrolling up just works) and
// accepts the resize-ghost / launch-noise tradeoffs as known
// limitations — `/clear` is the manual reset.
const { waitUntilExit } = render(
<Root
initialKey={initialKey}
+79 -20
View File
@@ -19,10 +19,13 @@
*/
import { basename, resolve } from "node:path";
import { loadProjectShellAllowed } from "../../config.js";
import { sanitizeName } from "../../session.js";
import { loadEditMode, loadProjectShellAllowed } from "../../config.js";
import { bootstrapSemanticSearchInCodeMode } from "../../index/semantic/tool.js";
import { sanitizeName } from "../../memory/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";
@@ -50,6 +53,14 @@ export interface CodeOptions {
* reasoning surfaced explicitly can pass `--harvest`.
*/
harvest?: boolean;
/**
* Soft USD spend cap. Off by default. Same semantics as `chat`:
* warns at 80%, refuses next turn at 100%. Mid-session adjustable
* via `/budget <usd>` slash command.
*/
budgetUsd?: number;
/** Suppress the auto-launched embedded web dashboard. */
noDashboard?: boolean;
}
export async function codeCommand(opts: CodeOptions = {}): Promise<void> {
@@ -65,44 +76,92 @@ export async function codeCommand(opts: CodeOptions = {}): Promise<void> {
// shape instead of the `string="false"` JSON-in-string array that
// triggered R1's DSML hallucinations all through 0.4.x.
const tools = new ToolRegistry();
registerFilesystemTools(tools, { rootDir });
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),
});
// 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();
// Bundled re-registration so `/cwd <path>` can swap every rootDir-
// dependent tool atomically. ToolRegistry.register is keyed by name
// and overwrites in-place, so re-calling these against the existing
// registry replaces the closures cleanly without disturbing tool
// specs (names/descriptions/params don't reference rootDir, so the
// prefix cache survives).
const registerRootedTools = (root: string): void => {
registerFilesystemTools(tools, { rootDir: root });
registerShellTools(tools, {
rootDir: root,
// 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(root),
// `yolo` edit-mode disables shell confirmations entirely. Re-read
// from config on each dispatch so /mode yolo (or Shift+Tab cycling
// through to it) flips the gate live without forcing a relaunch.
allowAll: () => loadEditMode() === "yolo",
jobs,
});
// `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: root });
};
registerRootedTools(rootDir);
// `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);
// `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 });
// `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);
// `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.
// Bootstrap semantic_search. Silent: registers the tool when an
// on-disk index already exists, skips entirely otherwise. Setup
// happens via the explicit `reasonix index` command — never
// by surprise on launch.
const semantic = await bootstrapSemanticSearchInCodeMode(tools, rootDir);
process.stderr.write(
`▸ reasonix code: rooted at ${rootDir}, session "${session ?? "(ephemeral)"}" · ${tools.size} native tool(s)\n`,
`▸ reasonix code: rooted at ${rootDir}, session "${session ?? "(ephemeral)"}" · ${tools.size} native tool(s)${
semantic.enabled ? " · semantic_search on" : ""
}\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-v4-pro",
model: opts.model ?? "deepseek-v4-flash",
harvest: opts.harvest ?? false,
system: codeSystemPrompt(rootDir),
budgetUsd: opts.budgetUsd,
system: codeSystemPrompt(rootDir, { hasSemanticSearch: semantic.enabled }),
transcript: opts.transcript,
session,
seedTools: tools,
codeMode: { rootDir },
codeMode: { rootDir, jobs, reregisterTools: registerRootedTools },
forceResume: opts.forceResume,
forceNew: opts.forceNew,
noDashboard: opts.noDashboard,
});
}
+333
View File
@@ -0,0 +1,333 @@
/** Drafts via diff + recent log (style mimicry); commit uses `-F -` so multi-line bodies survive shell quoting. */
import { spawn, spawnSync } from "node:child_process";
import { mkdtempSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { stdin, stdout } from "node:process";
import { createInterface } from "node:readline/promises";
import { DeepSeekClient } from "../../client.js";
import { loadApiKey } from "../../config.js";
import { loadDotenv } from "../../env.js";
export interface CommitOptions {
/** Override the default model (deepseek-v4-flash). */
model?: string;
/** Skip the confirmation step — useful in scripts where the diff has been pre-reviewed. */
yes?: boolean;
}
const DEFAULT_MODEL = "deepseek-v4-flash";
const DIFF_BYTE_CAP = 80 * 1024;
const LOG_COUNT = 10;
const SYSTEM_PROMPT = `You draft git commit messages.
Output ONLY the commit message — no preamble, no \`\`\` fences, no "Here's a commit message:" lead-in. The first line of your output IS the commit subject.
Match the project's existing style:
- Look at the recent commits provided. Mirror their voice, conventional-commit prefix usage (or absence), tense, length, body structure.
- If recent commits use a "type(scope): summary" prefix, use it. If they don't, don't invent one.
- Subject line: one line, ≤72 chars, imperative mood, no trailing period.
- Body (optional): explain WHY when the diff isn't self-evident. Wrap at ~72 chars. Skip the body for trivial changes — repeating the subject in the body is noise.
The diff is the source of truth for what changed; describe THAT, not your guesses about the broader project. If the diff includes a deletion you can't explain from the surrounding context, name it but don't speculate about why.
No emojis unless the recent commits use them.
No co-author trailers, no "Generated with X" footers.`;
function runGit(
args: string[],
opts: { input?: string } = {},
): { stdout: string; stderr: string; status: number | null } {
const result = spawnSync("git", args, {
encoding: "utf8",
stdio: ["pipe", "pipe", "pipe"],
input: opts.input,
maxBuffer: 32 * 1024 * 1024,
});
return {
stdout: result.stdout ?? "",
stderr: result.stderr ?? "",
status: result.status,
};
}
function dieIfNotGitRepo(): void {
const r = runGit(["rev-parse", "--is-inside-work-tree"]);
if (r.status !== 0) {
process.stderr.write("reasonix commit: not inside a git repository.\n");
process.exit(1);
}
}
interface DiffResult {
diff: string;
source: "staged" | "working-tree";
truncated: boolean;
}
function readDiff(): DiffResult | null {
const staged = runGit(["diff", "--staged", "--no-color"]);
if (staged.status !== 0) {
process.stderr.write(`reasonix commit: git diff --staged failed: ${staged.stderr.trim()}\n`);
process.exit(1);
}
if (staged.stdout.trim().length > 0) {
return capDiff(staged.stdout, "staged");
}
const wt = runGit(["diff", "--no-color"]);
if (wt.stdout.trim().length === 0) {
return null;
}
return capDiff(wt.stdout, "working-tree");
}
function capDiff(raw: string, source: "staged" | "working-tree"): DiffResult {
if (raw.length <= DIFF_BYTE_CAP) {
return { diff: raw, source, truncated: false };
}
const head = raw.slice(0, Math.floor(DIFF_BYTE_CAP * 0.7));
const tail = raw.slice(-Math.floor(DIFF_BYTE_CAP * 0.3));
return {
diff: `${head}\n\n[… ${raw.length - DIFF_BYTE_CAP} bytes of diff truncated …]\n\n${tail}`,
source,
truncated: true,
};
}
function readRecentCommits(): string {
const r = runGit(["log", `-${LOG_COUNT}`, "--no-merges", "--format=%s%n%b%n---END---"]);
if (r.status !== 0) {
// Repo may not have any commits yet (initial commit case). Don't
// fail — let the model work from the diff alone.
return "";
}
return r.stdout.trim();
}
async function draftMessage(
client: DeepSeekClient,
model: string,
diff: DiffResult,
recentCommits: string,
): Promise<string> {
const userParts: string[] = [];
if (recentCommits) {
userParts.push(`Recent commits (style reference):\n\n${recentCommits}`);
}
if (diff.source === "working-tree") {
userParts.push(
"(NOTE: diff is from the working tree, not the staging area — nothing is staged yet. The user will stage selectively after seeing the draft.)",
);
}
userParts.push(`Diff to summarize:\n\n${diff.diff}`);
const resp = await client.chat({
model,
messages: [
{ role: "system", content: SYSTEM_PROMPT },
{ role: "user", content: userParts.join("\n\n") },
],
temperature: 0.2,
});
return stripCodeFences(resp.content.trim());
}
function stripCodeFences(s: string): string {
// Some models still wrap output in ``` despite the system prompt
// telling them not to. Strip a single leading + trailing fence pair
// if present. Only operates on a wrapping pair — internal fences
// (a code block inside the body) stay.
const trimmed = s.trim();
const fenceOpen = /^```[a-zA-Z]*\n/;
const fenceClose = /\n?```$/;
if (fenceOpen.test(trimmed) && fenceClose.test(trimmed)) {
return trimmed.replace(fenceOpen, "").replace(fenceClose, "").trim();
}
return trimmed;
}
function printDraft(message: string): void {
const sep = "─".repeat(60);
process.stdout.write(`\n${sep}\n${message}\n${sep}\n\n`);
}
async function promptChoice(): Promise<"accept" | "regen" | "edit" | "cancel"> {
const rl = createInterface({ input: stdin, output: stdout });
try {
const answer = await rl.question("[a]ccept / [r]egenerate / [e]dit / [c]ancel: ");
const k = answer.trim().toLowerCase();
if (k === "" || k === "a" || k === "y" || k === "yes") return "accept";
if (k === "r" || k === "regen" || k === "regenerate") return "regen";
if (k === "e" || k === "edit") return "edit";
return "cancel";
} finally {
rl.close();
}
}
function editInExternal(initial: string): string | null {
const editor = process.env.GIT_EDITOR ?? process.env.VISUAL ?? process.env.EDITOR;
if (!editor) {
process.stderr.write(
"reasonix commit: no $EDITOR / $VISUAL / $GIT_EDITOR set — can't open editor. Pick [a]ccept and `git commit --amend` afterwards.\n",
);
return null;
}
const dir = mkdtempSync(join(tmpdir(), "reasonix-commit-"));
const path = join(dir, "COMMIT_EDITMSG");
writeFileSync(path, initial, "utf8");
// spawnSync with shell:true is required so $EDITOR strings like
// `code --wait` work — they're shell command lines, not argv tuples.
// The trust boundary is the user's own env var; matches how git
// itself launches editors.
const result = spawnSync(`${editor} "${path}"`, {
stdio: "inherit",
shell: true,
});
if (result.status !== 0) {
try {
unlinkSync(path);
} catch {
/* ignore */
}
process.stderr.write(
`reasonix commit: editor exited ${result.status} — keeping prior draft.\n`,
);
return null;
}
let edited: string;
try {
edited = readFileSync(path, "utf8");
} catch {
return null;
} finally {
try {
unlinkSync(path);
} catch {
/* ignore */
}
}
// Strip git's standard `# …` comment lines, even though we didn't
// emit any — a user habituated to `git commit` may add `#`-prefixed
// notes by reflex.
const cleaned = edited
.split(/\r?\n/)
.filter((line) => !/^\s*#/.test(line))
.join("\n")
.trim();
return cleaned || null;
}
function commitWithMessage(message: string): void {
// -F - reads the message from stdin, sidestepping shell quoting and
// letting multi-line bodies through cleanly. Inherit stdio so the
// user sees git's own confirmation / pre-commit hook output.
const child = spawn("git", ["commit", "-F", "-"], {
stdio: ["pipe", "inherit", "inherit"],
});
child.stdin.write(message);
child.stdin.end();
child.on("close", (code) => {
if (code !== 0) {
process.stderr.write(`reasonix commit: git commit exited ${code}.\n`);
process.exit(code ?? 1);
}
});
}
export async function commitCommand(opts: CommitOptions = {}): Promise<void> {
loadDotenv();
dieIfNotGitRepo();
const apiKey = loadApiKey() ?? process.env.DEEPSEEK_API_KEY;
if (!apiKey) {
process.stderr.write(
"reasonix commit: DEEPSEEK_API_KEY not set. Run `reasonix setup` to save one, or export it.\n",
);
process.exit(1);
}
const diff = readDiff();
if (!diff) {
process.stderr.write(
"reasonix commit: no staged changes and working tree is clean — nothing to commit.\n",
);
process.exit(1);
}
if (diff.source === "working-tree") {
process.stderr.write(
"reasonix commit: nothing staged — drafting from working-tree diff. Stage your changes and re-run, or use the draft as a starting point.\n",
);
}
if (diff.truncated) {
process.stderr.write(
"reasonix commit: diff exceeded 80KB; head + tail sent to the model. Large diffs often produce vague drafts — consider committing in smaller chunks.\n",
);
}
const client = new DeepSeekClient({ apiKey });
const model = opts.model ?? DEFAULT_MODEL;
const recentCommits = readRecentCommits();
let message = "";
let firstPass = true;
while (true) {
if (firstPass) {
process.stdout.write("Drafting commit message…\n");
} else {
process.stdout.write("Regenerating…\n");
}
firstPass = false;
try {
message = await draftMessage(client, model, diff, recentCommits);
} catch (err) {
process.stderr.write(`reasonix commit: model call failed — ${(err as Error).message}\n`);
process.exit(1);
}
if (!message) {
process.stderr.write("reasonix commit: model returned an empty draft. Try again.\n");
process.exit(1);
}
printDraft(message);
if (opts.yes) break;
if (diff.source === "working-tree") {
// Refuse to commit a working-tree-derived draft — the staging
// area is empty so `git commit` would fail anyway. Print the
// draft so the user can copy it; exit 0 because we did our job.
process.stdout.write(
"(no staged changes — draft printed above for you to copy. Stage with `git add` and re-run to commit.)\n",
);
return;
}
const choice = await promptChoice();
if (choice === "accept") break;
if (choice === "cancel") {
process.stderr.write("commit cancelled.\n");
return;
}
if (choice === "edit") {
const edited = editInExternal(message);
if (edited) {
message = edited;
printDraft(message);
// Re-prompt: the user may want to edit again, accept, etc.
const next = await promptChoice();
if (next === "accept") break;
if (next === "cancel") {
process.stderr.write("commit cancelled.\n");
return;
}
// next is "regen" or another "edit" — fall through to the
// loop top to re-draft (regen) or land back at this branch.
}
// editor returned no edit — loop top will regen by default.
}
// Anything else (regen, or unsuccessful edit) → loop top redraws.
}
commitWithMessage(message);
}
+2 -9
View File
@@ -2,8 +2,8 @@ import { writeFileSync } from "node:fs";
import { basename } from "node:path";
import { render } from "ink";
import React from "react";
import { diffTranscripts, renderMarkdown, renderSummaryTable } from "../../diff.js";
import { readTranscript } from "../../transcript.js";
import { diffTranscripts, renderMarkdown, renderSummaryTable } from "../../transcript/diff.js";
import { readTranscript } from "../../transcript/log.js";
import { DiffApp } from "../ui/DiffApp.js";
export interface DiffOptions {
@@ -18,13 +18,6 @@ export interface DiffOptions {
tui?: boolean;
}
/**
* Compare two transcripts. Three output paths, picked in order:
* - If --md is passed: write the markdown report. Also prints the stdout
* summary so the user sees what was exported.
* - If --print, no TTY, or --md (see above): stdout summary table.
* - Otherwise: interactive Ink TUI with split-pane + n/N divergence jump.
*/
export async function diffCommand(opts: DiffOptions): Promise<void> {
const aParsed = readTranscript(opts.a);
const bParsed = readTranscript(opts.b);
+358
View File
@@ -0,0 +1,358 @@
/** Plain-text (not Ink) — must work when everything else is broken. fail → exit 1; warn → exit 0. */
import { existsSync, statSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { DeepSeekClient } from "../../client.js";
import { defaultConfigPath, readConfig } from "../../config.js";
import { loadDotenv } from "../../env.js";
import { loadHooks } from "../../hooks.js";
import { indexExists } from "../../index/semantic/builder.js";
import { checkOllamaStatus } from "../../index/semantic/ollama-launcher.js";
import { listSessions } from "../../memory/session.js";
import { VERSION } from "../../version.js";
type Level = "ok" | "warn" | "fail";
interface Check {
label: string;
level: Level;
detail: string;
}
const TTY = process.stdout.isTTY && process.env.TERM !== "dumb";
function color(text: string, code: string): string {
if (!TTY) return text;
return `\x1b[${code}m${text}\x1b[0m`;
}
function badge(level: Level): string {
if (level === "ok") return color("✓", "32");
if (level === "warn") return color("⚠", "33");
return color("✗", "31");
}
function tail4(s: string): string {
return s.length <= 4 ? s : `…${s.slice(-4)}`;
}
function fmtBytes(n: number): string {
if (n < 1024) return `${n} B`;
if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
return `${(n / 1024 / 1024).toFixed(1)} MB`;
}
async function checkApiKey(): Promise<Check> {
const fromEnv = process.env.DEEPSEEK_API_KEY;
if (fromEnv) {
return {
label: "api key ",
level: "ok",
detail: `set via env DEEPSEEK_API_KEY (${tail4(fromEnv)})`,
};
}
try {
const cfg = readConfig();
if (cfg.apiKey) {
return {
label: "api key ",
level: "ok",
detail: `from ${defaultConfigPath()} (${tail4(cfg.apiKey)})`,
};
}
} catch {
/* fall through */
}
return {
label: "api key ",
level: "fail",
detail:
"not set — `reasonix setup` to save one, or export DEEPSEEK_API_KEY. Get a key at https://platform.deepseek.com/api_keys",
};
}
async function checkConfig(): Promise<Check> {
const path = defaultConfigPath();
if (!existsSync(path)) {
return {
label: "config ",
level: "warn",
detail: "missing — running with library defaults. `reasonix setup` writes one.",
};
}
try {
const cfg = readConfig(path);
const parts: string[] = [];
if (cfg.preset) parts.push(`preset=${cfg.preset}`);
if (cfg.editMode) parts.push(`editMode=${cfg.editMode}`);
if (cfg.mcp && cfg.mcp.length > 0) parts.push(`mcp=${cfg.mcp.length}`);
return {
label: "config ",
level: "ok",
detail: `${path}${parts.length ? ` (${parts.join(", ")})` : ""}`,
};
} catch (err) {
return {
label: "config ",
level: "fail",
detail: `${path} unreadable — ${(err as Error).message}`,
};
}
}
async function checkApiReach(): Promise<Check> {
const key = process.env.DEEPSEEK_API_KEY ?? readConfig().apiKey;
if (!key) {
return {
label: "api reach ",
level: "warn",
detail: "skipped — no api key to test with",
};
}
try {
const client = new DeepSeekClient({ apiKey: key });
const ctl = new AbortController();
const timer = setTimeout(() => ctl.abort(), 8_000);
let balance: Awaited<ReturnType<DeepSeekClient["getBalance"]>>;
try {
balance = await client.getBalance({ signal: ctl.signal });
} finally {
clearTimeout(timer);
}
if (!balance) {
return {
label: "api reach ",
level: "fail",
detail: "/user/balance returned null — auth failed or network blocked",
};
}
if (!balance.is_available) {
const info = balance.balance_infos[0];
return {
label: "api reach ",
level: "warn",
detail: `account flagged not-available${info ? ` (${info.total_balance} ${info.currency})` : ""} — top up or check your dashboard`,
};
}
const info = balance.balance_infos[0];
return {
label: "api reach ",
level: "ok",
detail: info
? `/user/balance ok — ${info.total_balance} ${info.currency}`
: "/user/balance ok",
};
} catch (err) {
return {
label: "api reach ",
level: "fail",
detail: `${(err as Error).message}`,
};
}
}
async function checkTokenizer(): Promise<Check> {
// The tokenizer file is the gzipped vocab shipped under data/. We
// resolve relative to the package's dist/ rather than process.cwd()
// — the same logic the runtime uses when loading on first count.
const candidates = [
join(
dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, "$1")),
"..",
"..",
"..",
"data",
"deepseek-tokenizer.json.gz",
),
join(process.cwd(), "data", "deepseek-tokenizer.json.gz"),
];
for (const p of candidates) {
if (existsSync(p)) {
try {
const stat = statSync(p);
return {
label: "tokenizer ",
level: "ok",
detail: `${p} (${fmtBytes(stat.size)})`,
};
} catch {
/* try next */
}
}
}
return {
label: "tokenizer ",
level: "warn",
detail:
"data/deepseek-tokenizer.json.gz not found — token counts will fall back to char heuristics",
};
}
async function checkSessions(): Promise<Check> {
try {
const list = listSessions();
if (list.length === 0) {
return {
label: "sessions ",
level: "ok",
detail: "0 saved",
};
}
const totalBytes = list.reduce((s, e) => s + e.size, 0);
const oldest = list[list.length - 1]!;
const ageDays = Math.floor((Date.now() - oldest.mtime.getTime()) / (24 * 60 * 60 * 1000));
const stale = list.filter(
(e) => Date.now() - e.mtime.getTime() >= 90 * 24 * 60 * 60 * 1000,
).length;
const detail = `${list.length} saved · ${fmtBytes(totalBytes)} · oldest ${ageDays}d`;
if (stale > 0) {
return {
label: "sessions ",
level: "warn",
detail: `${detail} · ${stale} idle ≥90d (run /prune-sessions)`,
};
}
return { label: "sessions ", level: "ok", detail };
} catch (err) {
return {
label: "sessions ",
level: "warn",
detail: `cannot list — ${(err as Error).message}`,
};
}
}
async function checkHooks(projectRoot: string): Promise<Check> {
try {
const all = loadHooks({ projectRoot });
const global = all.filter((h) => h.scope === "global").length;
const project = all.filter((h) => h.scope === "project").length;
return {
label: "hooks ",
level: "ok",
detail: `${global} global, ${project} project`,
};
} catch (err) {
return {
label: "hooks ",
level: "warn",
detail: `couldn't parse settings.json — ${(err as Error).message}`,
};
}
}
async function checkOllama(projectRoot: string): Promise<Check> {
// Ollama is only meaningful when an index has been built — otherwise
// the daemon being down is just noise. Skip the check entirely on
// projects that don't use semantic search.
let exists = false;
try {
exists = await indexExists(projectRoot);
} catch {
/* treat as no index */
}
if (!exists) {
return {
label: "ollama ",
level: "ok",
detail: "not in use (no semantic index built; `reasonix index` to enable)",
};
}
try {
const status = await checkOllamaStatus(process.env.REASONIX_EMBED_MODEL ?? "nomic-embed-text");
if (!status.binaryFound) {
return {
label: "ollama ",
level: "warn",
detail: "binary not on PATH — semantic_search will fail; install from https://ollama.com",
};
}
if (!status.daemonRunning) {
return {
label: "ollama ",
level: "warn",
detail: "daemon not running — `ollama serve` (or just call /semantic in TUI to auto-start)",
};
}
if (!status.modelPulled) {
return {
label: "ollama ",
level: "warn",
detail: `model ${status.modelName} not pulled — \`ollama pull ${status.modelName}\``,
};
}
return {
label: "ollama ",
level: "ok",
detail: `daemon up · model ${status.modelName} ready`,
};
} catch (err) {
return {
label: "ollama ",
level: "warn",
detail: `probe failed — ${(err as Error).message}`,
};
}
}
async function checkProject(projectRoot: string): Promise<Check> {
// Heuristic: a "real" project has either .git, REASONIX.md, or
// package.json. Lacking all three, `reasonix code` still works but
// @-mentions and the project-memory pin won't surface much.
const markers = [".git", "REASONIX.md", "package.json", "pyproject.toml", "Cargo.toml", "go.mod"];
const found = markers.filter((m) => existsSync(join(projectRoot, m)));
if (found.length === 0) {
return {
label: "project ",
level: "warn",
detail: `${projectRoot} has none of: ${markers.slice(0, 3).join(", ")} … — \`reasonix code\` will still run, but @-mentions and project memory have nothing to anchor`,
};
}
return {
label: "project ",
level: "ok",
detail: `${projectRoot} (${found.join(", ")})`,
};
}
export async function doctorCommand(): Promise<void> {
loadDotenv();
const projectRoot = resolve(process.cwd());
console.log(`${color(`reasonix ${VERSION} · doctor`, "1")} (cwd: ${projectRoot})`);
console.log(` home: ${homedir()}`);
console.log("");
// Run independent checks in parallel — saves ~5s when api-reach has
// to time out. Each handler swallows its own throws into a `fail`
// result so a thrown promise can't kill the whole report.
const checks = await Promise.all([
checkApiKey(),
checkConfig(),
checkApiReach(),
checkTokenizer(),
checkSessions(),
checkHooks(projectRoot),
checkOllama(projectRoot),
checkProject(projectRoot),
]);
for (const c of checks) {
console.log(` ${badge(c.level)} ${c.label} ${c.detail}`);
}
const ok = checks.filter((c) => c.level === "ok").length;
const warn = checks.filter((c) => c.level === "warn").length;
const fail = checks.filter((c) => c.level === "fail").length;
console.log("");
const summary = `${ok} ok · ${warn} warn · ${fail} fail`;
if (fail > 0) {
console.log(color(summary, "31"));
process.exit(1);
} else if (warn > 0) {
console.log(color(summary, "33"));
} else {
console.log(color(summary, "32"));
}
}
+134
View File
@@ -0,0 +1,134 @@
import { eventLogPath } from "../../adapters/event-sink-jsonl.js";
import { readEventLogFile } from "../../adapters/event-source-jsonl.js";
import type { Event } from "../../core/events.js";
import { replay as replayReducers } from "../../core/reducers.js";
export interface EventsOptions {
name: string;
type?: string;
since?: number;
tail?: number;
json?: boolean;
projection?: boolean;
}
export function eventsCommand(opts: EventsOptions): void {
const path = eventLogPath(opts.name);
let events = readEventLogFile(path);
if (events.length === 0) {
console.error(`no events for session "${opts.name}"`);
console.error(`looked at: ${path}`);
console.error("(sessions auto-create the sidecar on first turn — has this session run yet?)");
process.exit(1);
return;
}
if (opts.type) events = events.filter((e) => e.type === opts.type);
if (opts.since !== undefined && Number.isFinite(opts.since)) {
events = events.filter((e) => e.id >= opts.since!);
}
if (opts.tail !== undefined && Number.isFinite(opts.tail) && opts.tail > 0) {
events = events.slice(-opts.tail);
}
if (opts.projection) {
const p = replayReducers(events);
console.log(JSON.stringify(p, mapReplacer, 2));
return;
}
if (opts.json) {
for (const e of events) console.log(JSON.stringify(e));
return;
}
console.log(`[events] ${opts.name} ${events.length} event(s) ${path}`);
console.log("");
for (const e of events) console.log(formatEvent(e));
}
function formatEvent(e: Event): string {
const id = String(e.id).padStart(4);
const turn = `t${e.turn}`.padEnd(4);
const ts = e.ts.replace("T", " ").replace(/\.\d+Z$/, "");
const type = e.type.padEnd(22);
return `[${id}] ${turn} ${ts} ${type} ${detailsFor(e)}`;
}
function detailsFor(e: Event): string {
switch (e.type) {
case "user.message":
return quote(e.text, 80);
case "slash.invoked":
return `/${e.name} ${e.args}`.trim();
case "model.turn.started":
return `model=${e.model} effort=${e.reasoningEffort} prefix=${e.prefixHash.slice(0, 8)}`;
case "model.delta":
return `${e.channel} ${quote(e.text, 60)}`;
case "model.final": {
const u = e.usage;
const tokens = `in=${u.prompt_tokens ?? 0} out=${u.completion_tokens ?? 0}`;
const tail = e.forcedSummary ? " [forcedSummary]" : "";
return `cost=$${e.costUsd.toFixed(4)} ${tokens}${tail}`;
}
case "tool.intent":
return `${e.callId} ${e.name} args=${truncate(e.args, 60)}`;
case "tool.dispatched":
return e.callId;
case "tool.denied":
return `${e.callId} reason=${e.reason}`;
case "tool.result":
return `${e.callId} ${e.ok ? "ok" : "err"} ${e.output.length}B${e.truncated ? " [trunc]" : ""}`;
case "effect.file.touched":
return `${e.mode} ${e.path} (${e.bytes}B)`;
case "effect.memory.written":
return `${e.scope}:${e.key}`;
case "plan.submitted":
return `${e.steps.length} step(s)`;
case "plan.step.completed":
return `${e.stepId}${e.title ? ` — ${e.title}` : ""}`;
case "checkpoint.created":
return `${e.checkpointId} "${e.name}" ${e.fileCount} file(s) ${e.bytes}B`;
case "checkpoint.restored":
return `${e.checkpointId} restored=${e.restored} removed=${e.removed} skipped=${e.skipped}`;
case "hook.fired":
return `${e.phase} ${e.hookName} → ${e.outcome}`;
case "policy.budget.warning":
return `$${e.spentUsd.toFixed(4)} / $${e.capUsd.toFixed(2)}`;
case "policy.budget.blocked":
return `$${e.spentUsd.toFixed(4)} / $${e.capUsd.toFixed(2)} BLOCKED`;
case "policy.escalated":
return `${e.fromModel} → ${e.toModel} (${e.reason})${e.rationale ? ` "${e.rationale}"` : ""}`;
case "session.opened":
return `${e.name} resumed-from-turn=${e.resumedFromTurn}`;
case "session.compacted":
return `${e.beforeMessages} → ${e.afterMessages} msgs (${e.reason})`;
case "capability.registered":
return `${e.name} ${e.permission}`;
case "capability.removed":
return e.name;
case "status":
return quote(e.text, 80);
case "error":
return `${e.recoverable ? "[recoverable] " : ""}${quote(e.message, 80)}`;
default:
return "";
}
}
function quote(s: string, max: number): string {
const flat = s.replace(/\s+/g, " ").trim();
return flat.length <= max ? `"${flat}"` : `"${flat.slice(0, max - 1)}…"`;
}
function truncate(s: string, max: number): string {
return s.length <= max ? s : `${s.slice(0, max - 1)}…`;
}
/** WorkspaceView holds files in a Map; default JSON.stringify drops it. */
function mapReplacer(_key: string, value: unknown): unknown {
if (value instanceof Map) return Object.fromEntries(value);
if (value instanceof Set) return [...value];
return value;
}
+164
View File
@@ -0,0 +1,164 @@
/** `reasonix index` — progress writes go to stderr so stdout stays pipeable. */
import { resolve } from "node:path";
import { buildIndex } from "../../index/semantic/builder.js";
import type { BuildProgress, BuildResult } from "../../index/semantic/builder.js";
import { t } from "../../index/semantic/i18n.js";
import { ollamaPreflight } from "../../index/semantic/preflight.js";
export interface IndexCommandOptions {
rebuild?: boolean;
model?: string;
dir?: string;
/** Ollama base URL override. */
ollamaUrl?: string;
/** Skip preflight prompts (yes to all). For scripts that already
* know Ollama is set up. Default false. */
yes?: boolean;
}
export async function indexCommand(opts: IndexCommandOptions = {}): Promise<void> {
const root = resolve(opts.dir ?? process.cwd());
const tty = process.stderr.isTTY === true && process.stdin.isTTY === true;
const model = opts.model ?? process.env.REASONIX_EMBED_MODEL ?? "nomic-embed-text";
// Preflight: detect Ollama state and offer to fix what's missing.
// Runs before chunking so the user doesn't watch a scan finish only
// to hit "daemon not reachable" on the first embed call.
const preflightOk = await ollamaPreflight({
model,
baseUrl: opts.ollamaUrl,
interactive: tty && !opts.yes,
yesToAll: opts.yes ?? false,
});
if (!preflightOk) process.exit(1);
const writer = makeProgressWriter(tty);
const t0 = Date.now();
let result: BuildResult;
try {
result = await buildIndex(root, {
rebuild: opts.rebuild,
model,
baseUrl: opts.ollamaUrl,
onProgress: (p) => writer.update(p),
});
} catch (err) {
writer.clear();
const msg = err instanceof Error ? err.message : String(err);
process.stderr.write(t("indexFailed", { msg }));
process.exit(1);
}
writer.clear();
const seconds = ((Date.now() - t0) / 1000).toFixed(1);
const successKey = result.chunksSkipped > 0 ? "indexSuccessWithSkips" : "indexSuccess";
process.stderr.write(
t(successKey, {
scanned: result.filesScanned,
changed: result.filesChanged,
added: result.chunksAdded,
removed: result.chunksRemoved,
skipped: result.chunksSkipped,
seconds,
}),
);
if (result.filesChanged === 0 && !opts.rebuild) {
process.stderr.write(t("indexNothingToDo"));
}
}
interface ProgressWriter {
update(p: BuildProgress): void;
clear(): void;
}
const SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
const SPINNER_INTERVAL_MS = 120;
function makeProgressWriter(tty: boolean): ProgressWriter {
if (!tty) return makeNonTtyWriter();
return makeTtyWriter();
}
function makeNonTtyWriter(): ProgressWriter {
let lastPhase: BuildProgress["phase"] | null = null;
let lastChunks = 0;
return {
update(p) {
if (p.phase !== lastPhase) {
lastPhase = p.phase;
if (p.phase === "scan") {
process.stderr.write(t("progressScanLine"));
} else if (p.phase === "embed") {
process.stderr.write(
t("progressEmbedLine", {
total: p.chunksTotal ?? 0,
files: p.filesChanged ?? 0,
}),
);
}
}
if (p.phase === "embed" && p.chunksDone !== undefined && p.chunksDone - lastChunks >= 50) {
lastChunks = p.chunksDone;
process.stderr.write(
t("progressEmbedHeartbeat", {
done: p.chunksDone,
total: p.chunksTotal ?? "?",
}),
);
}
},
clear() {
/* non-TTY keeps its accumulated lines */
},
};
}
/** Spinner ticks on its own setInterval so a hung embedder still shows liveness. */
function makeTtyWriter(): ProgressWriter {
let status = t("progressStarting");
let lastLineLen = 0;
let frameIdx = 0;
const startTs = Date.now();
const repaint = () => {
const frame = SPINNER_FRAMES[frameIdx % SPINNER_FRAMES.length];
frameIdx++;
const elapsed = ((Date.now() - startTs) / 1000).toFixed(1);
const line = `${frame} ${status} ${elapsed}s`;
const padded = line + " ".repeat(Math.max(0, lastLineLen - line.length));
process.stderr.write(`\r${padded}`);
lastLineLen = line.length;
};
// Paint the initial frame immediately so the user sees text on
// line one — don't wait for the first interval tick.
repaint();
const interval = setInterval(repaint, SPINNER_INTERVAL_MS);
return {
update(p) {
if (p.phase === "scan") {
status = t("progressScan", { files: p.filesScanned ?? 0 });
} else if (p.phase === "embed") {
const done = p.chunksDone ?? 0;
const total = p.chunksTotal ?? 0;
const pct = total > 0 ? ((done / total) * 100).toFixed(0) : "0";
status = t("progressEmbed", { done, total, pct });
}
// Repaint immediately on event arrival so the new counter
// shows up before the next interval tick (avoids a 120ms lag
// on each progress update).
repaint();
},
clear() {
clearInterval(interval);
if (lastLineLen > 0) {
process.stderr.write(`\r${" ".repeat(lastLineLen)}\r`);
lastLineLen = 0;
}
},
};
}
+4 -12
View File
@@ -1,20 +1,10 @@
/**
* `reasonix mcp inspect <spec>` — connect to one MCP server, list
* everything it exposes (tools, resources, prompts), print a
* human-readable summary. Useful as:
* - a diagnostic tool for "does my MCP server even work?"
* - a discovery tool for "what can this server do?"
* - the only CLI surface for the resources+prompts methods added
* in 0.4.5 (chat mode consumes tools but hasn't wired up the
* other two families yet).
*/
import { McpClient } from "../../mcp/client.js";
import { inspectMcpServer } from "../../mcp/inspect.js";
import type { InspectionReport } from "../../mcp/inspect.js";
import { parseMcpSpec } from "../../mcp/spec.js";
import { SseTransport } from "../../mcp/sse.js";
import { type McpTransport, StdioTransport } from "../../mcp/stdio.js";
import { StreamableHttpTransport } from "../../mcp/streamable-http.js";
export interface McpInspectOptions {
/** The raw --mcp spec string (e.g. `fs=npx -y @modelcontextprotocol/server-filesystem .`). */
@@ -28,7 +18,9 @@ export async function mcpInspectCommand(opts: McpInspectOptions): Promise<void>
const transport: McpTransport =
spec.transport === "sse"
? new SseTransport({ url: spec.url })
: new StdioTransport({ command: spec.command, args: spec.args });
: spec.transport === "streamable-http"
? new StreamableHttpTransport({ url: spec.url })
: new StdioTransport({ command: spec.command, args: spec.args });
const client = new McpClient({ transport });
try {
await client.initialize();
-8
View File
@@ -1,11 +1,3 @@
/**
* `reasonix mcp <subcmd>` — the MCP discovery / helper surface.
*
* Currently one subcommand: `list`. Prints a curated catalog of popular
* MCP servers with their `--mcp` commands ready to copy-paste. More
* subcommands (`init`, `try`, etc.) may land in later alphas.
*/
import { MCP_CATALOG, mcpCommandFor } from "../../mcp/catalog.js";
export interface McpListOptions {
+2 -10
View File
@@ -1,7 +1,7 @@
import { render } from "ink";
import React from "react";
import { groupRecordsByTurn, replayFromFile } from "../../replay.js";
import type { TranscriptRecord } from "../../transcript.js";
import type { TranscriptRecord } from "../../transcript/log.js";
import { groupRecordsByTurn, replayFromFile } from "../../transcript/replay.js";
import { ReplayApp } from "../ui/ReplayApp.js";
export interface ReplayOptions {
@@ -12,13 +12,6 @@ export interface ReplayOptions {
print?: boolean;
}
/**
* Replay a transcript. Two modes:
* - Interactive TUI (default when stdout is a TTY): Ink-based j/k navigation.
* - Stdout pretty-print (--print, or when stdout is piped): one-shot text
* dump + summary. Kept working so shell pipes, CI logs, and `less`
* workflows still behave sensibly.
*/
export async function replayCommand(opts: ReplayOptions): Promise<void> {
const wantPrint =
opts.print || !process.stdout.isTTY || opts.head !== undefined || opts.tail !== undefined;
@@ -36,7 +29,6 @@ export async function replayCommand(opts: ReplayOptions): Promise<void> {
await waitUntilExit();
}
// ----------------------------------------------------------------------------
// stdout pretty-print path (original behavior, preserved for piping / CI)
function printReplay(opts: ReplayOptions): void {
+11 -4
View File
@@ -9,9 +9,10 @@ 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 { StreamableHttpTransport } from "../../mcp/streamable-http.js";
import { appendUsage } from "../../telemetry/usage.js";
import { ToolRegistry } from "../../tools.js";
import { openTranscriptFile, recordFromLoopEvent, writeRecord } from "../../transcript.js";
import { appendUsage } from "../../usage.js";
import { openTranscriptFile, recordFromLoopEvent, writeRecord } from "../../transcript/log.js";
export interface RunOptions {
task: string;
@@ -21,6 +22,7 @@ export interface RunOptions {
harvest?: boolean;
/** Self-consistency budget. > 1 runs N parallel samples and picks the best. */
branch?: number;
budgetUsd?: number;
/** JSONL transcript path — lets `reasonix replay` / `diff` audit this run. */
transcript?: string;
/** Zero or more MCP server specs. Each: `"name=cmd args..."` or `"cmd args..."`. */
@@ -86,12 +88,16 @@ export async function runCommand(opts: RunOptions): Promise<void> {
const transport: McpTransport =
spec.transport === "sse"
? new SseTransport({ url: spec.url })
: new StdioTransport({ command: spec.command, args: spec.args });
: spec.transport === "streamable-http"
? new StreamableHttpTransport({ url: spec.url })
: new StdioTransport({ command: spec.command, args: spec.args });
const mcp = new McpClient({ transport });
await mcp.initialize();
const bridge = await bridgeMcpTools(mcp, { registry: tools, namePrefix: prefix });
const source =
spec.transport === "sse" ? spec.url : `${spec.command} ${spec.args.join(" ")}`;
spec.transport === "sse" || spec.transport === "streamable-http"
? spec.url
: `${spec.command} ${spec.args.join(" ")}`;
process.stderr.write(
`▸ MCP[${spec.name ?? "anon"}]: ${bridge.registeredNames.length} tool(s) from ${source}\n`,
);
@@ -122,6 +128,7 @@ export async function runCommand(opts: RunOptions): Promise<void> {
model: opts.model,
harvest: opts.harvest,
branch: opts.branch,
budgetUsd: opts.budgetUsd,
});
const prefixHash = prefix.fingerprint;
-11
View File
@@ -1,14 +1,3 @@
/**
* `reasonix sessions` — CLI equivalent of the `/sessions` slash command.
*
* Two modes:
* - `reasonix sessions` list every session under ~/.reasonix/sessions/
* - `reasonix sessions <name>` dump one session's messages in readable form
*
* Neither needs an API key — pure filesystem reads of JSONL files written
* by previous chat runs.
*/
import { listSessions, loadSessionMessages, sessionPath } from "../../index.js";
import type { ChatMessage } from "../../index.js";
+11 -27
View File
@@ -1,20 +1,4 @@
/**
* `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."
*/
/** `reasonix stats [path]` — path arg switches to per-transcript mode; default is the cross-session dashboard. */
import { existsSync, readFileSync } from "node:fs";
import {
@@ -26,7 +10,7 @@ import {
defaultUsageLogPath,
formatLogSize,
readUsageLog,
} from "../../usage.js";
} from "../../telemetry/usage.js";
export interface StatsOptions {
/** Optional transcript path. Absent → dashboard mode. */
@@ -45,10 +29,6 @@ export function statsCommand(opts: StatsOptions): void {
dashboard(opts);
}
// ---------------------------------------------------------------------
// Transcript summary — legacy v0.1 behavior, preserved verbatim.
// ---------------------------------------------------------------------
function transcriptSummary(path: string): void {
if (!existsSync(path)) {
console.error(`no such transcript: ${path}`);
@@ -74,10 +54,6 @@ function transcriptSummary(path: string): void {
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);
@@ -154,18 +130,21 @@ function renderSubagentSection(sub: NonNullable<UsageAggregate["subagents"]>): s
function header(): string {
// Fixed column widths so alignment works in any TTY.
// `cache saved` reports DeepSeek's hit-vs-miss USD diff; the existing
// `saved` column is the % saved vs Claude-Sonnet equivalent.
return [
pad("", 10),
pad("turns", 8, "right"),
pad("cache hit", 10, "right"),
pad("cost (USD)", 14, "right"),
pad("cache saved", 14, "right"),
pad("vs Claude", 14, "right"),
pad("saved", 10, "right"),
].join(" ");
}
function divider(): string {
return "-".repeat(70);
return "-".repeat(86);
}
function bucketRow(b: UsageBucket): string {
@@ -176,6 +155,11 @@ function bucketRow(b: UsageBucket): string {
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.cacheSavingsUsd > 0 ? `$${b.cacheSavingsUsd.toFixed(4)}` : "—",
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(" ");
+1 -33
View File
@@ -1,17 +1,3 @@
/**
* `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";
@@ -21,11 +7,6 @@ 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[];
}
@@ -36,15 +17,7 @@ export interface PlanUpdateInput {
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
*/
/** Pure decision — split out so tests don't need to spawn child processes or hit the network. */
export function planUpdate(input: PlanUpdateInput): UpdatePlan {
const diff = compareVersions(input.current, input.latest);
if (diff > 0) {
@@ -105,11 +78,6 @@ function defaultSpawn(argv: string[]): Promise<number> {
});
}
/**
* 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));
+168 -15
View File
@@ -1,10 +1,16 @@
import { Command } from "commander";
import { readConfig } from "../config.js";
import { VERSION } from "../index.js";
import { applyMemoryStack } from "../user-memory.js";
import { listSessions } from "../memory/session.js";
import { applyMemoryStack } from "../memory/user.js";
import { ESCALATION_CONTRACT } from "../prompt-fragments.js";
import { chatCommand } from "./commands/chat.js";
import { codeCommand } from "./commands/code.js";
import { commitCommand } from "./commands/commit.js";
import { diffCommand } from "./commands/diff.js";
import { doctorCommand } from "./commands/doctor.js";
import { eventsCommand } from "./commands/events.js";
import { indexCommand } from "./commands/index.js";
import { mcpInspectCommand } from "./commands/mcp-inspect.js";
import { mcpListCommand } from "./commands/mcp.js";
import { replayCommand } from "./commands/replay.js";
@@ -14,7 +20,7 @@ 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";
import { resolveContinueFlag, resolveDefaults } from "./resolve.js";
const DEFAULT_SYSTEM = `You are Reasonix, a helpful DeepSeek-powered assistant. Be concise and accurate. Use tools when available.
@@ -28,33 +34,64 @@ Every factual claim about a codebase must be backed by evidence. Reasonix VALIDA
**Negative claims** ("X is missing", "Y isn't implemented", "lacks Z") are the #1 hallucination shape. STOP before writing them. If you have a search tool, call it first; if the search returns nothing, cite the search itself as evidence (\`No matches for "foo" in src/\`). If you have no tool, qualify hard: "I haven't verified — this is a guess."
Asserting absence without checking is how evaluative answers go wrong. Treat the urge to write "missing" as a red flag in your own reasoning.`;
Asserting absence without checking is how evaluative answers go wrong. Treat the urge to write "missing" as a red flag in your own reasoning.
# Don't invent what changes — search instead
Your training data has a cutoff. When an answer's correctness depends on something that changes over time (the user is asking what's happening, not what's true) and a search tool is available, search first. Inventing currently-correct values from training memory is the most common way these answers go wrong, and the user usually can't tell until much later.
The signal isn't a topic list — it's: "if I'm wrong about this, is it because reality moved on?". If yes, ground the answer in fresh evidence; if no (definitions, mechanisms, well-established APIs), answer from memory.
${ESCALATION_CONTRACT}`;
/** Lenient: malformed → undefined (no cap) so a bad flag doesn't abort launch. */
function parseBudgetFlag(raw: number | undefined): number | undefined {
if (raw === undefined) return undefined;
if (!Number.isFinite(raw) || raw <= 0) {
process.stderr.write(
`▲ ignoring --budget=${raw} (must be a positive number) — running with no cap\n`,
);
return undefined;
}
return raw;
}
const program = new Command();
program
.name("reasonix")
.description("DeepSeek-native agent framework — built for cache hits and cheap tokens.")
.version(VERSION);
.version(VERSION)
.option(
"-c, --continue",
"Resume the most recently used chat session without showing the picker.",
);
// `reasonix` with no subcommand → launch the friendliest flow.
// First run (no config yet) → interactive setup wizard.
// Otherwise → chat with saved defaults. This is the "one command to
// rule them all" entry for non-power-users: they don't need to learn
// `chat` / `setup` / `--mcp` — just type `reasonix`.
program.action(async () => {
program.action(async (opts: { continue?: boolean }) => {
const cfg = readConfig();
if (!cfg.setupCompleted) {
await setupCommand({});
return;
}
const defaults = resolveDefaults({});
const continueOpts = resolveContinueFlag(
opts.continue,
defaults.session,
() => listSessions()[0],
(msg) => process.stderr.write(`${msg}\n`),
);
await chatCommand({
model: defaults.model,
system: applyMemoryStack(DEFAULT_SYSTEM, process.cwd()),
harvest: defaults.harvest,
branch: defaults.branch,
session: defaults.session,
session: continueOpts.session,
mcp: defaults.mcp,
forceResume: continueOpts.forceResume,
});
});
@@ -68,16 +105,25 @@ program
program
.command("code [dir]")
.description(
"Code-editing chat — filesystem tools rooted at <dir> (default: cwd), coding system prompt, deepseek-reasoner. Model proposes SEARCH/REPLACE blocks; Reasonix applies them to disk.",
"Code-editing chat — filesystem tools rooted at <dir> (default: cwd), coding system prompt, v4-flash baseline. Model proposes SEARCH/REPLACE blocks; Reasonix applies them to disk. Use /preset pro or /pro to lock v4-pro on hard tasks.",
)
.option("-m, --model <id>", "Override default reasoner model")
.option("-m, --model <id>", "Override default model (v4-flash)")
.option("--no-session", "Disable session persistence for this run")
.option("-r, --resume", "Skip the session picker — always continue prior messages")
.option("-n, --new", "Skip the session picker — always wipe prior messages and start fresh")
.option("--transcript <path>", "Write a JSONL transcript to this path")
.option(
"--harvest",
"Extract typed plan state from R1 reasoning (Pillar 2). Adds ~10-15% cost per turn. Off by default in code mode.",
"Opt-in Pillar-2 plan-state extraction. Adds one flash call per turn; off by default (no preset enables it).",
)
.option(
"--budget <usd>",
"Soft USD cap on session spend. Off by default. Warns at 80%, refuses next turn at 100%. Mid-session: /budget <usd> or /budget off.",
(v) => Number.parseFloat(v),
)
.option(
"--no-dashboard",
"Suppress the auto-launched embedded web dashboard. Default behavior boots it on TUI mount and shows the URL in the status bar (clickable in OSC-8-aware terminals).",
)
.action(async (dir: string | undefined, opts) => {
await codeCommand({
@@ -88,6 +134,8 @@ program
forceResume: !!opts.resume,
forceNew: !!opts.new,
harvest: !!opts.harvest,
budgetUsd: parseBudgetFlag(opts.budget),
noDashboard: opts.dashboard === false,
});
});
@@ -99,20 +147,29 @@ 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 bundle. One of: auto (flash → pro on hard turns, default), flash (always flash), pro (always pro). 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(
"--budget <usd>",
"Soft USD cap on session spend. Off by default. Warns at 80%, refuses next turn at 100%. Mid-session: /budget <usd> or /budget off.",
(v) => Number.parseFloat(v),
)
.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(
"-c, --continue",
"Resume the most-recently-used session (any name) without showing the picker.",
)
.option("-n, --new", "Skip the session picker — always wipe prior messages and start fresh")
.option(
"--mcp <spec>",
@@ -125,6 +182,10 @@ program
"Global prefix applied to every MCP tool (only honored when no per-spec name is set; avoids collisions with a single anonymous server)",
)
.option("--no-config", "Ignore `~/.reasonix/config.json` — useful for CI or reproducing issues")
.option(
"--no-dashboard",
"Suppress the auto-launched embedded web dashboard. Default behavior boots it on TUI mount and shows the URL in the status bar (clickable in OSC-8-aware terminals).",
)
.action(async (opts) => {
const defaults = resolveDefaults({
model: opts.model,
@@ -135,17 +196,31 @@ program
preset: opts.preset,
noConfig: opts.config === false,
});
// `-c` is "newest-touched session" + auto-resume; `-r` is "this
// session's prior messages, even if you also passed --session".
// When both are set we prefer the explicit `--session` + `-r`
// (more specific input wins). `-c` only kicks in if `-r` wasn't.
const continueOpts = opts.resume
? { session: defaults.session, forceResume: true }
: resolveContinueFlag(
opts.continue,
defaults.session,
() => listSessions()[0],
(msg) => process.stderr.write(`${msg}\n`),
);
await chatCommand({
model: defaults.model,
system: applyMemoryStack(opts.system, process.cwd()),
transcript: opts.transcript,
harvest: defaults.harvest,
branch: defaults.branch,
session: defaults.session,
budgetUsd: parseBudgetFlag(opts.budget),
session: continueOpts.session,
mcp: defaults.mcp,
mcpPrefix: opts.mcpPrefix,
forceResume: !!opts.resume,
forceResume: continueOpts.forceResume,
forceNew: !!opts.new,
noDashboard: opts.dashboard === false,
});
});
@@ -154,13 +229,18 @@ program
.description("Run a single task non-interactively, streaming output.")
.option("-m, --model <id>", "DeepSeek model id (overrides preset)")
.option("-s, --system <prompt>", "System prompt", DEFAULT_SYSTEM)
.option("--preset <name>", "Bundle of model + harvest + branch: fast | smart | max")
.option("--preset <name>", "Model bundle: auto | flash | pro (default: auto)")
.option("--harvest", "Extract typed plan state from R1 reasoning (Pillar 2)")
.option(
"--branch <n>",
"Self-consistency: run N parallel samples per turn and pick the most confident",
(v) => Number.parseInt(v, 10),
)
.option(
"--budget <usd>",
"Soft USD cap on session spend. Off by default. Refuses to start a new turn once cumulative cost ≥ cap.",
(v) => Number.parseFloat(v),
)
.option("--transcript <path>", "Write a JSONL transcript to this path for replay/diff")
.option(
"--mcp <spec>",
@@ -188,6 +268,7 @@ program
system: applyMemoryStack(opts.system, process.cwd()),
harvest: defaults.harvest,
branch: defaults.branch,
budgetUsd: parseBudgetFlag(opts.budget),
transcript: opts.transcript,
mcp: defaults.mcp,
mcpPrefix: opts.mcpPrefix,
@@ -204,6 +285,29 @@ program
statsCommand({ transcript });
});
program
.command("doctor")
.description(
"One-command health check — API key, config, /user/balance reachability, tokenizer, sessions, hooks, Ollama (if used), project markers. Exit 1 on any fail; 0 on warn / clean.",
)
.action(async () => {
await doctorCommand();
});
program
.command("commit")
.description(
"Draft a commit message from the staged diff (or working tree, if nothing staged), matching your repo's recent commit style. Review interactively before it lands.",
)
.option("-m, --model <id>", "Override the default model (deepseek-v4-flash)")
.option(
"-y, --yes",
"Skip the [a]ccept / [r]egenerate prompt and commit the first draft. Useful in scripts.",
)
.action(async (opts) => {
await commitCommand({ model: opts.model, yes: !!opts.yes });
});
program
.command("sessions [name]")
.description("List saved chat sessions, or inspect one by name.")
@@ -212,6 +316,30 @@ program
sessionsCommand({ name, verbose: !!opts.verbose });
});
program
.command("events <name>")
.description(
"Pretty-print the kernel event-log sidecar (~/.reasonix/sessions/<name>.events.jsonl) — every typed Event the session produced.",
)
.option("--type <type>", "Show only events of this type (e.g., tool.intent)")
.option("--since <id>", "Show only events with id >= N", (v) => Number.parseInt(v, 10))
.option("--tail <n>", "Show only the last N events", (v) => Number.parseInt(v, 10))
.option("--json", "Emit raw JSONL passthrough instead of formatted lines (for jq pipelines)")
.option(
"--projection",
"Replace the listing with the final reduced ProjectionSet (conversation, budget, plan, …)",
)
.action((name: string, opts) => {
eventsCommand({
name,
type: opts.type,
since: Number.isFinite(opts.since) ? opts.since : undefined,
tail: Number.isFinite(opts.tail) ? opts.tail : undefined,
json: !!opts.json,
projection: !!opts.projection,
});
});
program
.command("replay <transcript>")
.description(
@@ -290,6 +418,31 @@ program
await updateCommand({ dryRun: !!opts.dryRun });
});
program
.command("index")
.description(
"Build (or incrementally refresh) a local semantic search index for the project so `reasonix code` can answer 'where do we…' questions by meaning, not just by token. Uses Ollama as the embedding backend; missing daemon / model is offered to the user with a confirm prompt.",
)
.option("--rebuild", "Wipe and rebuild from scratch")
.option("--model <name>", "Embedding model (default: nomic-embed-text)")
.option("--dir <path>", "Project root to index (default: cwd)")
.option("--ollama-url <url>", "Override Ollama base URL (default: http://localhost:11434)")
.option(
"-y, --yes",
"Skip preflight prompts — auto-start the daemon and pull the model if missing (use in scripts)",
)
.action(
async (opts: {
rebuild?: boolean;
model?: string;
dir?: string;
ollamaUrl?: string;
yes?: boolean;
}) => {
await indexCommand(opts);
},
);
program.parseAsync(process.argv).catch((err) => {
console.error(err);
process.exit(1);
+32 -19
View File
@@ -1,23 +1,11 @@
/**
* Merge config defaults with CLI flags into the concrete options that
* `chatCommand` / `runCommand` need.
*
* Precedence (highest wins):
* 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
*
* Keeping this logic in one place — rather than duplicating across
* `chat` and `run` — means the precedence rule only lives in one unit
* test and the shape of the merge is identical for both commands.
*/
/** Precedence: per-setting flag > --preset > config.preset > "auto" defaults. */
import { type PresetName, type ReasonixConfig, readConfig } from "../config.js";
import { PRESETS } from "./ui/presets.js";
import { resolvePreset } from "./ui/presets.js";
export interface ResolvedDefaults {
model: string;
reasoningEffort: "high" | "max";
harvest: boolean;
branch: number | undefined;
mcp: string[];
@@ -41,9 +29,10 @@ export interface RawCliFlags {
export function resolveDefaults(flags: RawCliFlags): ResolvedDefaults {
const cfg: ReasonixConfig = flags.noConfig ? {} : readConfig();
const preset = pickPreset(flags.preset, cfg.preset);
const presetSettings = PRESETS[preset];
const presetSettings = resolvePreset(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 +44,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,11 +53,20 @@ function pickPreset(
): PresetName {
if (flagPreset && isPresetName(flagPreset)) return flagPreset;
if (configPreset) return configPreset;
return "fast";
return "auto";
}
function isPresetName(s: string): s is PresetName {
return s === "fast" || s === "smart" || s === "max";
return (
s === "auto" ||
s === "flash" ||
s === "pro" ||
// Legacy names — kept callable so old `--preset smart` invocations
// and stale config.json entries don't error out.
s === "fast" ||
s === "smart" ||
s === "max"
);
}
function normalizeBranch(raw: number | undefined): number | undefined {
@@ -87,3 +85,18 @@ function resolveSession(
if (typeof configSession === "string" && configSession.length > 0) return configSession;
return "default";
}
export function resolveContinueFlag(
flag: boolean | undefined,
fallbackSession: string | undefined,
getLatestSession: () => { name: string } | undefined,
warn: (msg: string) => void = () => {},
): { session: string | undefined; forceResume: boolean } {
if (!flag) return { session: fallbackSession, forceResume: false };
const latest = getLatestSession();
if (!latest) {
warn("▸ -c/--continue: no saved sessions yet — starting a fresh one.");
return { session: fallbackSession, forceResume: false };
}
return { session: latest.name, forceResume: true };
}
+3499 -842
View File
File diff suppressed because it is too large. Load diff
+47 -29
View File
@@ -1,6 +1,7 @@
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 { COLOR, GLYPH } from "./theme.js";
export interface AtMentionSuggestionsProps {
/**
@@ -16,11 +17,21 @@ export interface AtMentionSuggestionsProps {
}
/**
* 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.
* `@`-mention picker. Rendered below the input box while the user is
* typing an `@…` prefix in code mode. Visual grammar matches the
* design's file picker:
*
* @ files matching "auth" esc
* ▸ login.ts src/auth/
* refresh.ts src/auth/
* validators.ts src/auth/
* auth.test.ts tests/
* [↑↓] navigate · Tab / ⏎ insert as @path · file content inlined
*
* Basename in primary cyan (the user's eye lands here first), dir
* suffix in dim info color. No solid-bg pill on the selected row —
* leading ▸ + bold + brighter color does the same job without the
* loud bg block. Mirrors {@link SlashSuggestions}.
*/
export function AtMentionSuggestions({
matches,
@@ -30,12 +41,13 @@ export function AtMentionSuggestions({
if (matches === null) return null;
if (matches.length === 0) {
return (
<Box paddingX={1}>
<Text color="yellow">no files match "@{query}"</Text>
<Text dimColor>
{" "}
— keep typing, or Backspace to edit. Paths resolve from the code root.
<Box paddingX={1} marginTop={1}>
<Text color={COLOR.warn} bold>
{GLYPH.warn}
</Text>
<Text> </Text>
<Text color={COLOR.warn}>{`no files match "@${query}"`}</Text>
<Text dimColor>{" — keep typing or Backspace; paths resolve from the code root"}</Text>
</Box>
);
}
@@ -47,40 +59,46 @@ export function AtMentionSuggestions({
const hiddenAbove = windowStart;
const hiddenBelow = total - windowStart - shown.length;
return (
<Box flexDirection="column" paddingX={1}>
{hiddenAbove > 0 ? <Text dimColor> ↑ {hiddenAbove} more above</Text> : null}
<Box flexDirection="column" paddingX={1} marginTop={1}>
<Box>
<Text color={COLOR.primary} bold>
{"@ "}
</Text>
<Text dimColor>
{query
? `${total} match${total === 1 ? "" : "es"} for "${query}"`
: `${total} file${total === 1 ? "" : "s"}`}
</Text>
{hiddenAbove > 0 ? <Text dimColor>{` ↑ ${hiddenAbove} above`}</Text> : null}
</Box>
{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>
{hiddenBelow > 0 ? <Text dimColor>{` ↓ ${hiddenBelow} below`}</Text> : null}
<Box marginTop={0}>
<Text dimColor>{" ↑↓ navigate · Tab / ⏎ insert as @path · esc cancel"}</Text>
</Box>
</Box>
);
}
function FileRow({ path, isSelected }: { path: string; isSelected: boolean }) {
const marker = isSelected ? "▸" : " ";
// Split the path so the basename visually pops — same dropdown
// affordance as VS Code's Quick Open.
// affordance as VS Code's Quick Open. Basename in primary cyan
// (selected: bold), dir suffix in dim info color so the eye lands
// on the filename first and uses the path only as a disambiguator.
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 bold color="cyan">
{marker} {base}
</Text>
<Text color="cyan">{dir ? ` ${dir}` : ""}</Text>
</Box>
);
}
return (
<Box>
<Text dimColor>
{marker} {base}
{dir ? ` ${dir}` : ""}
<Text color={isSelected ? COLOR.primary : COLOR.info} bold={isSelected}>
{isSelected ? `${GLYPH.cur} ` : " "}
</Text>
<Text color={COLOR.primary} bold={isSelected}>
{base.padEnd(20)}
</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);
+259
View File
@@ -0,0 +1,259 @@
import { Box, Text, useStdout } from "ink";
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React in value scope for JSX compilation
import React from "react";
import stringWidth from "string-width";
import type { SessionSummary } from "../../telemetry/stats.js";
import { ChromeRule } from "./primitives.js";
import { COLOR, GRADIENT } from "./theme.js";
const COLD_START_TURNS = 3;
const CACHE_BAR_CELLS = 10;
export type Preset = "auto" | "flash" | "pro";
export interface ChromeBarProps {
summary: SessionSummary;
rootDir?: string;
sessionName?: string | null;
preset?: Preset;
planMode?: boolean;
proArmed?: boolean;
escalated?: boolean;
updateAvailable?: string | null;
balance?: { currency: string; total: number } | null;
budgetUsd?: number | null;
/** Scroll progress: 0 = at latest, 1 = at oldest. Hides the pill at 0. */
scrollRatio?: number;
}
export function ChromeBar(props: ChromeBarProps): React.ReactElement {
const { stdout } = useStdout();
const cols = (stdout?.columns ?? 80) - 2; // subtract paddingX={1} on both sides
const cold = props.summary.turns <= COLD_START_TURNS;
const projectName = props.rootDir ? basename(props.rootDir) : null;
const mode = pickModePill(props.planMode, props.preset);
const proPill = props.escalated
? { label: "⇧ pro", color: COLOR.err }
: props.proArmed
? { label: "⇧ pro", color: COLOR.warn }
: null;
// Greedy width-aware fit. Layout (each gap is exactly ONE space — single
// suffix on update/mode/pro/scroll, single prefix on balance/cache):
// [brand][·project][›session]<spacer>[scroll][update][mode][pro]$cost w bal cache █▓▓▓
// Always-shown carve out the budget first; optional pieces are dropped
// by priority — balance > cache > session > update — until the row fits.
// (`flexGrow` spacer can shrink to 0, so no minimum reserve.) Cache is
// shown unconditionally now: pre-turn-4 it renders dim with a "—" so
// it's "default on" instead of materializing only after a few turns.
const SEP = 3; // " · " / " › "
const GAP = 1;
const scrollLabel =
props.scrollRatio !== undefined && props.scrollRatio > 0
? `[↑ ${Math.round(props.scrollRatio * 100)}%]`
: "";
const updateLabel = props.updateAvailable ? `↑ ${props.updateAvailable}` : "";
const balanceLabel = props.balance ? formatBalanceLabel(props.balance) : "";
const cachePct = Math.round(props.summary.cacheHitRatio * 100);
// Use the worst-case rendered cache string (3-digit pct, full bar) so the
// shed decision doesn't oscillate as the percentage changes turn-to-turn.
const cacheLabel = `cache ${"█".repeat(CACHE_BAR_CELLS)} 100%`;
const costLabel = `$${props.summary.totalCostUsd.toFixed(4)}${
props.budgetUsd && props.budgetUsd > 0 ? ` / $${props.budgetUsd.toFixed(2)}` : ""
}`;
const brandW = stringWidth("◈ reasonix");
const projectW = projectName ? SEP + stringWidth(projectName) : 0;
const fixedLeft = brandW + projectW;
const scrollW = scrollLabel ? stringWidth(scrollLabel) + GAP : 0;
const modeW = mode ? stringWidth(`[${mode.label}]`) + GAP : 0;
const proW = proPill ? stringWidth(`[${proPill.label}]`) + GAP : 0;
const costW = stringWidth(costLabel);
const fixedRight = scrollW + modeW + proW + costW;
let budget = cols - fixedLeft - fixedRight;
const balanceOptW = balanceLabel ? GAP + stringWidth(balanceLabel) : 0;
const cacheOptW = GAP + stringWidth(cacheLabel);
const sessionOptW = props.sessionName ? SEP + stringWidth(props.sessionName) : 0;
const updateOptW = updateLabel ? stringWidth(updateLabel) + GAP : 0;
const showBalance = balanceOptW > 0 && budget >= balanceOptW;
if (showBalance) budget -= balanceOptW;
const showCache = budget >= cacheOptW;
if (showCache) budget -= cacheOptW;
const showSession = sessionOptW > 0 && budget >= sessionOptW;
if (showSession) budget -= sessionOptW;
const showUpdate = updateOptW > 0 && budget >= updateOptW;
if (showUpdate) budget -= updateOptW;
return (
<Box flexDirection="column" paddingX={1}>
<Box>
<Text bold color={GRADIENT[0]}>
{"◈ "}
</Text>
<Text color={COLOR.brand} bold>
reasonix
</Text>
{projectName ? (
<>
<Text color={COLOR.info} dimColor>
{" · "}
</Text>
<Text>{projectName}</Text>
{showSession && props.sessionName ? (
<>
<Text color={COLOR.info} dimColor>
{" › "}
</Text>
<Text color={COLOR.info}>{props.sessionName}</Text>
</>
) : null}
</>
) : null}
<Box flexGrow={1} />
{scrollLabel ? (
<>
<Text color={COLOR.accent} bold>
{scrollLabel}
</Text>
<Text> </Text>
</>
) : null}
{showUpdate ? (
<>
<Text color={COLOR.warn} bold>
{updateLabel}
</Text>
<Text> </Text>
</>
) : null}
{mode ? (
<>
<Text color={mode.color} bold>
{`[${mode.label}]`}
</Text>
<Text> </Text>
</>
) : null}
{proPill ? (
<>
<Text color={proPill.color} bold>
{`[${proPill.label}]`}
</Text>
<Text> </Text>
</>
) : null}
<CostPill summary={props.summary} cold={cold} budgetUsd={props.budgetUsd} />
{showBalance && props.balance ? (
<>
<Text> </Text>
<BalancePill balance={props.balance} />
</>
) : null}
{showCache ? (
<>
<Text> </Text>
<CachePill ratio={props.summary.cacheHitRatio} cold={cold} pct={cachePct} />
</>
) : null}
</Box>
<ChromeRule />
</Box>
);
}
function formatBalanceLabel(balance: { currency: string; total: number }): string {
const sym = balance.currency === "USD" ? "$" : balance.currency === "CNY" ? "¥" : "";
const suf = sym ? "" : ` ${balance.currency}`;
return `w ${sym}${balance.total.toFixed(2)}${suf}`;
}
function CostPill({
summary,
cold,
budgetUsd,
}: {
summary: SessionSummary;
cold: boolean;
budgetUsd?: number | null;
}): React.ReactElement {
const cost = summary.totalCostUsd;
const color = cold ? COLOR.info : sessionCostColor(cost);
return (
<>
<Text color={color} bold={!cold} dimColor={cold}>
{`$${cost.toFixed(4)}`}
</Text>
{budgetUsd && budgetUsd > 0 ? (
<Text color={COLOR.info} dimColor>
{` / $${budgetUsd.toFixed(2)}`}
</Text>
) : null}
</>
);
}
function BalancePill({
balance,
}: {
balance: { currency: string; total: number };
}): React.ReactElement {
const { total } = balance;
const color = total < 1 ? COLOR.err : total < 5 ? COLOR.warn : COLOR.ok;
return <Text color={color}>{formatBalanceLabel(balance)}</Text>;
}
function CachePill({
ratio,
cold,
pct,
}: {
ratio: number;
cold: boolean;
pct: number;
}): React.ReactElement {
const color = ratio >= 0.7 ? COLOR.ok : ratio >= 0.4 ? COLOR.warn : COLOR.err;
const filled = Math.max(0, Math.min(CACHE_BAR_CELLS, Math.round(ratio * CACHE_BAR_CELLS)));
const empty = CACHE_BAR_CELLS - filled;
return (
<>
<Text color={COLOR.info} dimColor>
{"cache "}
</Text>
<Text color={cold ? COLOR.info : color} dimColor={cold}>
{"█".repeat(filled)}
</Text>
<Text dimColor>{"░".repeat(empty)}</Text>
<Text color={cold ? undefined : color} bold={!cold} dimColor={cold}>
{cold && pct === 0 ? " —" : ` ${pct}%`}
</Text>
</>
);
}
function pickModePill(
planMode: boolean | undefined,
preset: Preset | undefined,
): { label: string; color: string } | null {
if (planMode) return { label: "PLAN", color: COLOR.err };
if (!preset) return null;
if (preset === "pro") return { label: "pro", color: COLOR.accent };
if (preset === "flash") return { label: "flash", color: COLOR.info };
return { label: "auto", color: COLOR.primary };
}
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 basename(path: string): string {
const norm = path.replace(/\\/g, "/");
const i = norm.lastIndexOf("/");
return i === -1 ? norm : norm.slice(i + 1);
}
+88
View File
@@ -0,0 +1,88 @@
import { Box, Text, useStdout } from "ink";
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React in value scope for JSX compilation
import React, { useMemo } from "react";
import stringWidth from "string-width";
import type { CacheFirstLoop } from "../../loop.js";
import type { SessionSummary } from "../../telemetry/stats.js";
import { computeCtxBreakdown } from "./ctx-breakdown.js";
import { Bar, ChromeRule, formatTokens } from "./primitives.js";
import { COLOR } from "./theme.js";
interface CtxFooterProps {
loop: CacheFirstLoop;
summary: SessionSummary;
}
const BAR_CELLS = 14;
export function CtxFooter({ loop, summary }: CtxFooterProps): React.ReactElement {
// Memoize on turn boundary. `summary.turns` is a freshness key — its
// change forces recomputation when the loop's log appends a new turn.
// biome-ignore lint/correctness/useExhaustiveDependencies: summary.turns is a freshness key, not a value used in the body
const data = useMemo(() => computeCtxBreakdown(loop), [loop, summary.turns]);
const { stdout } = useStdout();
const cols = (stdout?.columns ?? 80) - 2;
const total = data.systemTokens + data.toolsTokens + data.logTokens + data.inputTokens;
const ratio = data.ctxMax > 0 ? Math.min(1, total / data.ctxMax) : 0;
const pct = Math.round(ratio * 100);
const severity = pct >= 80 ? COLOR.err : pct >= 60 ? COLOR.warn : COLOR.ok;
// Always-shown core: label + bar + total + pct + (compact warn when severe)
const labelStr = " ctx ";
const totalStr = `${formatTokens(total)}/${formatTokens(data.ctxMax)}`;
const pctStr = ` · ${pct}%`;
const warnStr = pct >= 80 ? " · /compact" : "";
const fixedW =
stringWidth(labelStr) +
BAR_CELLS +
1 + // space after bar
stringWidth(totalStr) +
stringWidth(pctStr) +
stringWidth(warnStr);
// Optional breakdown segments. Greedy fit by priority (drop first → drop last):
// input → log → tools → sys. Sys comes off the line LAST because it's
// the most stable number; users learn its size and read other segments
// relative to it.
let budget = cols - fixedW;
const sysSeg = ` · sys ${formatTokens(data.systemTokens)}`;
const toolsSeg = ` · tools ${formatTokens(data.toolsTokens)}`;
const logSeg = ` · log ${formatTokens(data.logTokens)}`;
const inputSeg = data.inputTokens > 0 ? ` · input ${formatTokens(data.inputTokens)}` : "";
const showSys = budget >= stringWidth(sysSeg);
if (showSys) budget -= stringWidth(sysSeg);
const showTools = budget >= stringWidth(toolsSeg);
if (showTools) budget -= stringWidth(toolsSeg);
const showLog = budget >= stringWidth(logSeg);
if (showLog) budget -= stringWidth(logSeg);
const showInput = inputSeg !== "" && budget >= stringWidth(inputSeg);
if (showInput) budget -= stringWidth(inputSeg);
return (
<Box flexDirection="column" paddingX={1}>
<ChromeRule />
<Text>
<Text color={COLOR.info} dimColor>
{labelStr}
</Text>
<Bar ratio={ratio} color={severity} cells={BAR_CELLS} />
<Text> </Text>
<Text color={severity} bold>
{totalStr}
</Text>
<Text dimColor>{pctStr}</Text>
{showSys ? <Text dimColor>{sysSeg}</Text> : null}
{showTools ? <Text dimColor>{toolsSeg}</Text> : null}
{showLog ? <Text dimColor>{logSeg}</Text> : null}
{showInput ? <Text dimColor>{inputSeg}</Text> : null}
{warnStr ? (
<Text color={COLOR.err} bold>
{warnStr}
</Text>
) : null}
</Text>
</Box>
);
}
+66
View File
@@ -0,0 +1,66 @@
/** Single-line text input for deny-with-reason — uses our KeystrokeContext, not ink-text-input. */
import { Box, Text } from "ink";
import React, { useState } from "react";
import { useKeystroke } from "./keystroke-context.js";
export interface DenyContextInputProps {
label?: string;
onSubmit: (context: string) => void;
onCancel: () => void;
}
export function DenyContextInput({
label = "Reason for denying:",
onSubmit,
onCancel,
}: DenyContextInputProps) {
const [value, setValue] = useState("");
useKeystroke((ev) => {
if (ev.paste) {
setValue((v) => v + ev.input);
return;
}
if (ev.escape) {
onCancel();
return;
}
if (ev.return) {
onSubmit(value);
return;
}
if (ev.backspace) {
setValue((v) => v.slice(0, -1));
return;
}
if (ev.input && !ev.tab && !ev.upArrow && !ev.downArrow && !ev.leftArrow && !ev.rightArrow) {
setValue((v) => v + ev.input);
}
});
return (
<Box flexDirection="column">
<Box>
<Text dimColor>{label} </Text>
<Text>{value}</Text>
<Text backgroundColor="#67e8f9" color="black">
{" "}
</Text>
</Box>
<Box marginTop={1}>
<Text dimColor>
{"["}
<Text color="#67e8f9" bold>
Enter
</Text>
{"] confirm · ["}
<Text color="#67e8f9" bold>
Esc
</Text>
{"] cancel"}
</Text>
</Box>
</Box>
);
}
+1 -1
View File
@@ -16,7 +16,7 @@ import {
type TurnPair,
findNextDivergence,
findPrevDivergence,
} from "../../diff.js";
} from "../../transcript/diff.js";
import { RecordView } from "./RecordView.js";
export interface DiffAppProps {
+228
View File
@@ -0,0 +1,228 @@
import { Box, Text, useStdout } from "ink";
import React, { useMemo, useState } from "react";
import { formatEditBlockSplit } from "../../code/diff-preview.js";
import type { EditBlock } from "../../code/edit-blocks.js";
import { DenyContextInput } from "./DenyContextInput.js";
import { ModalCard } from "./ModalCard.js";
import { SplitDiff } from "./SplitDiff.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, denyContext?: string) => 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);
// Side-by-side rows — maxLines pushed high so the split renderer
// never inserts its own truncation marker; we slice + scroll here.
// contextLines: 2 keeps the trim tight on each end.
const allRows = useMemo(
() => formatEditBlockSplit(block, { contextLines: 2, maxLines: 100_000 }),
[block],
);
const [scroll, setScroll] = useState(0);
const maxScroll = Math.max(0, allRows.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);
const [phase, setPhase] = useState<"review" | "context">("review");
useKeystroke((ev) => {
if (ev.paste) return;
if (phase === "context") 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") {
setPhase("context");
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 visibleRows = allRows.slice(effectiveScroll, effectiveScroll + budget);
const hiddenAbove = effectiveScroll;
const hiddenBelow = Math.max(0, allRows.length - effectiveScroll - budget);
const totalLines = allRows.length;
const showScrollHud = hiddenAbove + hiddenBelow > 0;
const subtitleParts = [`-${removed} +${added} lines`];
if (showScrollHud) {
subtitleParts.push(
`viewing ${effectiveScroll + 1}-${effectiveScroll + visibleRows.length}/${totalLines}`,
);
}
if (phase === "context") {
return (
<ModalCard
accent={isNew ? "#86efac" : "#fcd34d"}
icon={isNew ? "✚" : "✎"}
title={`${tag} ${block.path}`}
subtitle="rejecting — add context (optional)"
>
<DenyContextInput
label="Reason for rejecting (or Enter to reject without context): "
onSubmit={(context) => onChoose("reject", context)}
onCancel={() => setPhase("review")}
/>
</ModalCard>
);
}
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}
<SplitDiff rows={visibleRows} />
<Box>
<Text color="#fbc8c8" backgroundColor="#2a1212">
{" - old "}
</Text>
<Text>{" "}</Text>
<Text color="#bef0c8" backgroundColor="#0c2718">
{" + new "}
</Text>
<Text dimColor>
{" side-by-side · removed lines on the left, added on the right · paired by offset"}
</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 with reason · ["}
<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>
);
}
+644 -232
View File
File diff suppressed because it is too large. Load diff
+360
View File
@@ -0,0 +1,360 @@
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 { CharBar } from "./char-bar.js";
import { useElapsedSeconds, useSlowTick, 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 the slow tick so the jobs count stays live — the
// registry is mutated outside React, so we need a periodic repaint
// to catch it. 1Hz is enough for a count badge: a 1s lag for a job
// appearing/disappearing is imperceptible vs how long jobs run.
// No-op when there's no registry (chat mode / tests).
useSlowTick();
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 label = editMode === "yolo" ? "YOLO" : editMode === "auto" ? "AUTO" : "REVIEW";
const bg = editMode === "yolo" ? "red" : editMode === "auto" ? "magenta" : "cyan";
const mid =
editMode === "yolo"
? "edits + shell auto · /undo to roll back"
: editMode === "auto"
? "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 — bracket-text style matching the StatsPanel chrome at top
* (one canonical pill style across the whole TUI). `flash` inverts
* briefly after a mode flip so the user sees "yes, it changed"; once
* the flash fades it returns to its quiet bracket form.
*
* Why bracket and not solid bg: the mode is already shown in the top
* chrome's pill. Repeating the same info as a loud, padded block
* directly above the prompt was visual repetition, not reinforcement.
* Bracket here keeps the actionable hint readable while the flash
* still does its acknowledgement job.
*/
function ModePill({
label,
bg,
flash,
}: {
label: string;
bg: "magenta" | "cyan" | "red";
flash: boolean;
}) {
return (
<Text color={bg} 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.
* The countdown ticks once per second — slow tick is the right
* cadence here (faster re-renders just redraw the same digit).
* 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 };
}) {
// Fast tick so the char bar shrinks one cell at a time rather than
// jumping in 1s gulps. With FAST_TICK_MS=120 we get ~42 frames over
// a 5s window — smooth enough that the bar reads as a continuous
// countdown without looking like a stutter.
useTick();
const totalMs = 5000; // mirrors armUndoBanner's hard-coded window
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;
// 20-cell bar, 4 cells per second. Filled = remaining time.
const pct = (remainingMs / totalMs) * 100;
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>
<CharBar pct={pct} width={20} color={urgent ? "#f87171" : "#c4b5fd"} showLabel={false} />
<Text dimColor>{" "}</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);
// Bracket-text style — same vocabulary as the static ToolPill so a
// turn that contains both finished tools and a live subagent reads
// as a consistent column. The braille spinner + colored ⌬ + colored
// name carry enough weight without a solid-bg block.
return (
<Box paddingLeft={3}>
<Text color="#c4b5fd" bold>
{SPINNER_FRAMES[tick % SPINNER_FRAMES.length]}
</Text>
<Text>{" "}</Text>
<Text color="#c4b5fd" 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);
// Bracket-text style — matches the static ToolPill that lands once
// the call resolves, so a row of in-flight + finished tools reads
// as one continuous column instead of two visual languages.
return (
<Box marginY={1} flexDirection="column" paddingX={1}>
<Box>
<Text color="#fcd34d" bold>
{SPINNER_FRAMES[tick % SPINNER_FRAMES.length]}
</Text>
<Text>{" "}</Text>
<Text color="#fcd34d" bold>
{`▣ ${tool.name}`}
</Text>
<Text dimColor>{` running · ${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;
}
+115
View File
@@ -0,0 +1,115 @@
/**
* Shared visual frame for confirmation modals (ChoiceConfirm,
* PlanConfirm, ShellConfirm, EditConfirm, PlanCheckpointConfirm,
* PlanReviseConfirm). Renders as a true bordered card matching the
* design doc — full accent-colored Unicode box around header + body,
* with a horizontal rule separating the title row from the content
* area so the modal reads as a discrete interrupt, not just a few
* spaced lines in the live region.
*
* Layout:
*
* ╭───────────────────────────────────────────────╮
* │ ICON TITLE subtitle │
* ├───────────────────────────────────────────────┤
* │ │
* │ <children — body of the modal> │
* │ │
* ╰───────────────────────────────────────────────╯
*
* Color drives the accent (border + icon + title) so the user learns
* to recognize the modal type by glance: violet = choice, cyan = plan,
* amber = shell, green = edit review, red = budget exhausted.
*
* Why Ink `borderStyle="round"` is fine here despite the historical
* comment about eraseLines miscounts: the modals only render in
* single-instance positions (they replace the prompt area, never the
* scrollback), so the frame doesn't get re-painted every tick. The
* earlier bug class was about animated wide rows wrapping mid-render.
*/
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 — border + icon + title text. */
accent: string;
/** Section title — rendered bold in the accent color. */
title: string;
/** Optional dim subtitle next to the title. */
subtitle?: string;
/** Optional leading glyph (icon). Rendered in the accent color. */
icon?: string;
/**
* Optional footer slot — renders below a horizontal rule, after the
* body. Used for action-button rows like `[apply] [discard]` so they
* sit visually pinned to the bottom of the modal regardless of body
* scroll height. When absent, the modal ends right after the body.
*/
footer?: React.ReactNode;
children: React.ReactNode;
}
export function ModalCard({
accent,
title,
subtitle,
icon,
footer,
children,
}: ModalCardProps): React.ReactElement {
const { stdout } = useStdout();
const cols = stdout?.columns ?? 80;
// Subtract 4: 2 cells for the left+right border + 2 cells of paddingX.
// Min 28 keeps the rule visible even on absurdly narrow terminals.
const innerWidth = Math.min(76, Math.max(28, cols - 6));
return (
<Box flexDirection="column" borderStyle="round" borderColor={accent} paddingX={1} marginY={1}>
{/* Header row — icon + bold title in accent color, dim subtitle
right-aligned. The horizontal rule below it doubles as a
separator and a visual weight that says "this is the thing
to read". */}
<Box>
{icon ? (
<>
<Text color={accent} bold>
{icon}
</Text>
<Text>{" "}</Text>
</>
) : null}
<Text color={accent} bold>
{title}
</Text>
{subtitle ? (
<>
<Box flexGrow={1} />
<Text dimColor>{subtitle}</Text>
</>
) : null}
</Box>
<Box>
<Text color={accent} dimColor>
{"─".repeat(innerWidth)}
</Text>
</Box>
{/* Body — children render with no extra padding so the modal
body looks like one continuous content area inside the border. */}
<Box flexDirection="column">{children}</Box>
{/* Optional footer — divider rule + slot. Lets modals separate
actions from body without each one re-implementing the rule. */}
{footer ? (
<>
<Box>
<Text color={accent} dimColor>
{"─".repeat(innerWidth)}
</Text>
</Box>
<Box flexDirection="column">{footer}</Box>
</>
) : null}
</Box>
);
}
+118
View File
@@ -0,0 +1,118 @@
/**
* Modal-style picker shown when `mark_step_complete` pauses the loop
* via `PlanCheckpointError`. Three choices:
*
* 1. Continue — push "Step X done, proceed." so the model starts
* the next step on the next turn.
* 2. Revise — open a feedback input; whatever the user types
* becomes a synthetic "user feedback for remaining steps" message.
* The model can then adjust its approach without starting the
* whole plan over.
* 3. Stop — push "User stopped the plan. Summarize what was
* done." so the run ends cleanly rather than being abandoned.
*
* The ✓ step-progress scrollback row is pushed separately (by App.tsx
* at checkpoint detection time), so this modal stays a tight picker —
* no need to re-render the step body here.
*/
import { Box } from "ink";
import React from "react";
import type { PlanStep } from "../../tools/plan.js";
import { ModalCard } from "./ModalCard.js";
import { PlanStepList, type StepStatus } from "./PlanStepList.js";
import { SingleSelect } from "./Select.js";
export type CheckpointChoice = "continue" | "revise" | "stop";
export interface PlanCheckpointConfirmProps {
stepId: string;
title?: string;
completed: number;
total: number;
/** Full step list from the approved plan, when available. */
steps?: PlanStep[];
/** Set of stepIds the model has marked complete so far. */
completedStepIds?: Set<string>;
onChoose: (choice: CheckpointChoice) => void;
}
function PlanCheckpointConfirmInner({
stepId,
title,
completed,
total,
steps,
completedStepIds,
onChoose,
}: PlanCheckpointConfirmProps) {
const label = title ? `${stepId} · ${title}` : stepId;
const counter = total > 0 ? `${completed}/${total}` : "";
const isLast = total > 0 && completed >= total;
const statuses = buildStatusMap(steps, completedStepIds, stepId, isLast);
const subtitle = counter ? `${counter} · ${label}` : label;
return (
<ModalCard accent="#86efac" icon="✓" title="checkpoint — step done" subtitle={subtitle}>
{steps && steps.length > 0 ? (
<Box marginBottom={1} flexDirection="column">
<PlanStepList steps={steps} statuses={statuses} focusStepId={stepId} />
</Box>
) : null}
<SingleSelect
initialValue={isLast ? "stop" : "continue"}
items={[
{
value: "continue",
label: "Continue — run the next step",
hint: "Model resumes with the next step. Use this when the result looks right and you don't need to tweak the remaining plan.",
},
{
value: "revise",
label: "Revise — give feedback before the next step",
hint: "Stay paused, type guidance (scope changes, skip steps, alternative approach). The model adjusts the remaining plan based on your message.",
},
{
value: "stop",
label: "Stop — end the plan here",
hint: "Model summarizes what was done and ends. Remaining steps are skipped.",
},
]}
onSubmit={(v) => onChoose(v as CheckpointChoice)}
onCancel={() => onChoose("stop")}
footer="[↑↓] navigate · [Enter] select · [Esc] stop"
/>
</ModalCard>
);
}
export const PlanCheckpointConfirm = React.memo(PlanCheckpointConfirmInner);
/**
* Derive a status map from the plan + completion set + current step.
* The currently-just-finished step always renders as "done" even if
* completedStepIds hasn't been flushed yet (it gets added in the
* same render cycle, order not guaranteed). Steps ahead of the
* cursor are "pending"; the next step after the current one isn't
* marked "running" because nothing is actually running while the
* picker is up — that belongs to the post-continue state.
*/
function buildStatusMap(
steps: PlanStep[] | undefined,
completedStepIds: Set<string> | undefined,
currentStepId: string,
isLast: boolean,
): Map<string, StepStatus> {
const map = new Map<string, StepStatus>();
if (!steps) return map;
for (const step of steps) {
if (completedStepIds?.has(step.id) || step.id === currentStepId) {
map.set(step.id, "done");
} else {
map.set(step.id, "pending");
}
}
if (isLast) {
// Every step is done; leave as "done" — no "running" overlay.
}
return map;
}
+52 -122
View File
@@ -9,99 +9,34 @@
* 3. Cancel — exits plan mode, drops the plan, tells the model the
* user didn't want any of it.
*
* Mirrors ShellConfirm in structure (border, SingleSelect, three
* options, no y/n hotkey — mid-typing triggers would be painful).
* The plan body is rendered verbatim above the picker so the user can
* actually read what they're approving.
* The plan BODY is NOT rendered inside this modal — App.tsx pushes it
* into the Static scrollback as a `role: "plan"` display event the
* moment submit_plan fires. That's a one-time markdown render into
* permanent history, so the user reads the full proposal above and
* the modal below stays a tight picker. The previous design (body
* rendered inside the modal with an aggressive line clamp) left users
* staring at "(25 more lines truncated)" and unable to approve safely.
*/
import { Box, Text } from "ink";
import React from "react";
import type { PlanStep } from "../../tools/plan.js";
import { ModalCard } from "./ModalCard.js";
import { PlanStepList } from "./PlanStepList.js";
import { SingleSelect } from "./Select.js";
import { Markdown } from "./markdown.js";
export type PlanConfirmChoice = "approve" | "refine" | "cancel";
export interface PlanConfirmProps {
plan: string;
steps?: PlanStep[];
/** Optional human-friendly title from the model — surfaced in the header. */
summary?: string;
onChoose: (choice: PlanConfirmChoice) => void;
/**
* Cap on rendered plan length. A pathological 20-KB plan would push
* the picker off the bottom of the terminal; we show the head +
* "(…N chars truncated — /tool for full output)" instead. The picker
* itself gets the full plan (it's already been committed to the
* transcript via the tool result).
*/
maxRenderedChars?: number;
projectRoot?: string;
/**
* Override the terminal-row count used for vertical clamping. Tests
* pass this to avoid depending on `process.stdout.rows`; runtime
* callers leave it unset and we read the real TTY size.
*/
terminalRows?: number;
}
const DEFAULT_MAX_RENDERED = 2400;
/**
* Reserved terminal rows for the picker chrome (border + header +
* divider + open-questions hint + SingleSelect with three options +
* footer + the assistant-turn block Ink already printed above).
* Empirically ~16; we round up to 18 for safety.
*/
const PICKER_CHROME_ROWS = 18;
/**
* Rough markdown expansion factor. One source line commonly renders
* as 1–3 terminal rows: wrap on narrow terminals doubles long lines,
* code fences add top/bottom rules, list items get bullet indent,
* headings sometimes pick up blank rows. A factor of 2 is the
* conservative bet that lets us keep `bodyRowBudget` > 0 on a 24-row
* terminal while still guaranteeing the picker stays on-screen. If
* this is wrong in practice it's wrong in the "trim too aggressively"
* direction, which shows a truncation marker rather than flickering.
*/
const MARKDOWN_EXPANSION = 2;
const MIN_BODY_ROWS = 4;
/**
* Trim `text` to the first `maxLines` source lines, appending a
* truncation marker when it was cut. Source lines, NOT rendered rows
* — callers must divide their row budget by the expected markdown
* expansion factor before passing it here.
*/
export function clampBodyByLines(text: string, maxLines: number): string {
const lines = text.split("\n");
if (lines.length <= maxLines) return text;
const kept = lines.slice(0, maxLines).join("\n");
const dropped = lines.length - maxLines;
return `${kept}\n\n… (${dropped} more lines truncated — resize the terminal to see more, or /tool for the full proposal)`;
}
function PlanConfirmInner({
plan,
onChoose,
maxRenderedChars,
projectRoot,
terminalRows,
}: PlanConfirmProps) {
const cap = maxRenderedChars ?? DEFAULT_MAX_RENDERED;
const charTrunc = plan.length > cap;
const charCapped = charTrunc
? `${plan.slice(0, cap)}\n\n… (${plan.length - cap} chars truncated — use /tool to view the full proposal)`
: plan;
// Vertical clamp. Flicker root-cause: when rendered content exceeds
// the TTY row count Ink falls back to "clear + full redraw" each
// frame, and every parent re-render redraws the big Markdown subtree.
// Capping the body to (rows - picker chrome) keeps the whole modal
// inside the terminal so Ink uses incremental diffs and the picker
// stops thrashing. See Bug A in 0.5.14.
const rows = terminalRows ?? process.stdout?.rows ?? 24;
const renderedBudget = Math.max(MIN_BODY_ROWS * MARKDOWN_EXPANSION, rows - PICKER_CHROME_ROWS);
// Divide by the expansion factor so source-line clamp produces a
// rendered height that actually fits the terminal. Without this the
// rendered body overflows → Ink clears + redraws each frame → flicker.
const sourceLineBudget = Math.max(MIN_BODY_ROWS, Math.floor(renderedBudget / MARKDOWN_EXPANSION));
const visible = clampBodyByLines(charCapped, sourceLineBudget);
function PlanConfirmInner({ plan, steps, summary, onChoose }: PlanConfirmProps) {
// Crude signal for "the model left questions or risks for me" — the
// typical section headings. Triggers an extra hint toward the Refine
// option so users know where to answer them.
@@ -110,55 +45,50 @@ function PlanConfirmInner({
/^#{1,6}\s*(待确认|开放问题|风险|未知|假设|不确定)/im.test(plan);
return (
<Box flexDirection="column" borderStyle="round" borderColor="cyan" paddingX={1} marginY={1}>
<Box>
<Text bold color="cyan">
▸ plan submitted — awaiting your review
</Text>
</Box>
<Box>
<Text color="cyan" dimColor>
{"──────────────────────────────────────────"}
</Text>
</Box>
<Box marginTop={1} flexDirection="column">
<Markdown text={visible} projectRoot={projectRoot} />
</Box>
<ModalCard
accent="#67e8f9"
icon="📋"
title="plan proposed"
subtitle={summary ?? "approve / refine / cancel"}
>
{hasOpenQuestions ? (
<Box marginTop={1}>
<Text color="yellow">
▲ the plan has open questions or flagged risks — pick{" "}
<Box marginBottom={1}>
<Text color="#fbbf24">
▲ the plan flags open questions or risks — pick{" "}
<Text bold>Refine / answer questions</Text> to write concrete answers before the model
moves on.
</Text>
</Box>
) : null}
<Box marginTop={1}>
<SingleSelect
initialValue={hasOpenQuestions ? "refine" : "approve"}
items={[
{
value: "approve",
label: "Approve and implement",
hint: "Exit plan mode. The model starts executing. You'll get a text input to add any last instructions (or just press Enter to skip).",
},
{
value: "refine",
label: "Refine / answer questions",
hint: "Stay in plan mode. Write answers, modifications, or critiques; the model revises and re-submits.",
},
{
value: "cancel",
label: "Cancel",
hint: "Exit plan mode. Drop the plan; the model won't implement it.",
},
]}
onSubmit={(v) => onChoose(v as PlanConfirmChoice)}
onCancel={() => onChoose("cancel")}
footer="[↑↓] navigate · [Enter] select · [Esc] cancel"
/>
</Box>
</Box>
{steps && steps.length > 0 ? (
<Box marginBottom={1} flexDirection="column">
<PlanStepList steps={steps} />
</Box>
) : null}
<SingleSelect
initialValue={hasOpenQuestions ? "refine" : "approve"}
items={[
{
value: "approve",
label: "Approve and implement",
hint: "Exit plan mode. The model starts executing. You'll get a text input to add any last instructions (or just press Enter to skip).",
},
{
value: "refine",
label: "Refine / answer questions",
hint: "Stay in plan mode. Write answers, modifications, or critiques; the model revises and re-submits.",
},
{
value: "cancel",
label: "Cancel",
hint: "Exit plan mode. Drop the plan; the model won't implement it.",
},
]}
onSubmit={(v) => onChoose(v as PlanConfirmChoice)}
onCancel={() => onChoose("cancel")}
footer="[↑↓] navigate · [Enter] select · [Esc] cancel"
/>
</ModalCard>
);
}
+73 -30
View File
@@ -14,17 +14,24 @@
* the picker without resuming.
*/
import { Box, Text, useInput } from "ink";
import { Box, Text } from "ink";
import React, { useState } from "react";
import { ModalCard } from "./ModalCard.js";
import { useKeystroke } from "./keystroke-context.js";
import { COLOR } from "./theme.js";
import { useTick } from "./ticker.js";
export interface PlanRefineInputProps {
/**
* Which path the user is on. Approve = "implement with these last
* instructions"; refine = "revise the plan with this feedback".
* Drives the header + hint text so users know what kind of message
* they're writing.
* Which path the user is on. approve = "implement with these last
* instructions"; refine = "revise the plan with this feedback";
* checkpoint-revise = mid-execution pause, user is tweaking the
* remaining plan after seeing a step's result; choice-custom = user
* typed an off-list answer to an ask_choice branch. Drives the
* header + hint text so users know what kind of message they're
* writing.
*/
mode: "approve" | "refine";
mode: "approve" | "refine" | "checkpoint-revise" | "choice-custom";
/** Called with trimmed feedback. Empty string is allowed. */
onSubmit: (feedback: string) => void;
/** Called when the user presses Esc to return to the picker. */
@@ -34,58 +41,94 @@ export interface PlanRefineInputProps {
export function PlanRefineInput({ mode, onSubmit, onCancel }: PlanRefineInputProps) {
const [value, setValue] = useState("");
useInput((input, key) => {
if (key.escape) {
useKeystroke((ev) => {
if (ev.paste) {
// Insert paste content as-is. Multi-line pastes flatten via
// newlines becoming spaces because this is a single-line input.
setValue((v) => v + ev.input.replace(/\r?\n/g, " "));
return;
}
if (ev.escape) {
onCancel();
return;
}
if (key.return) {
if (ev.return) {
onSubmit(value.trim());
return;
}
if (key.backspace || key.delete) {
if (ev.backspace || ev.delete) {
setValue((v) => v.slice(0, -1));
return;
}
// Filter out non-printable chars; accept ordinary text + CJK.
if (input && !key.ctrl && !key.meta) {
setValue((v) => v + input);
if (ev.input && !ev.ctrl && !ev.meta) {
setValue((v) => v + ev.input);
}
});
const title =
const tick = useTick();
// Slow blink for the cursor block (~480 ms on/off). Same cadence
// as the wordmark's brand-mark pulse; reads as "input is alive".
const cursorOn = Math.floor(tick / 4) % 2 === 0;
const meta =
mode === "approve"
? "▸ approving — any last instructions or answers to open questions?"
: "▸ refining — what should the model change?";
? {
title: "approving — any last instructions?",
icon: "◇",
accent: COLOR.primary,
}
: mode === "checkpoint-revise"
? {
title: "revising — what should change before the next step?",
icon: "✎",
accent: COLOR.warn,
}
: mode === "choice-custom"
? {
title: "custom answer — type whatever fits",
icon: "⌥",
accent: COLOR.accent,
}
: {
title: "refining — what should the model change?",
icon: "✎",
accent: COLOR.warn,
};
const hint =
mode === "approve"
? "Answer questions the plan raised, add constraints, or just press Enter to approve as-is."
: "Describe what's wrong or missing, or answer questions the plan raised.";
: mode === "checkpoint-revise"
? "Scope change, skip steps, alternative approach — the model adjusts the remaining plan."
: mode === "choice-custom"
? "Free-form reply. The model reads it verbatim and proceeds — no need to match the listed options."
: "Describe what's wrong or missing, or answer questions the plan raised.";
const blankHint =
mode === "approve"
? " (Enter with blank = approve without extra instructions.)"
: " (Enter with blank = ask the model to list concrete questions.)";
: mode === "checkpoint-revise"
? " (Enter with blank = continue with the current plan.)"
: mode === "choice-custom"
? " (Enter with blank = ask the model what you actually want.)"
: " (Enter with blank = ask the model to list concrete questions.)";
return (
<Box flexDirection="column" borderStyle="round" borderColor="yellow" paddingX={1} marginY={1}>
<Box>
<Text bold color="yellow">
{title}
</Text>
</Box>
<Box marginTop={1}>
<ModalCard accent={meta.accent} icon={meta.icon} title={meta.title}>
<Box marginBottom={1}>
<Text dimColor>
{hint} Enter to send · Esc to return to the picker.
{value === "" ? blankHint : ""}
</Text>
</Box>
<Box marginTop={1}>
<Text>
<Text color="yellow">› </Text>
<Text>{value || " "}</Text>
<Text color="yellow">▍</Text>
<Box>
<Text color={meta.accent} bold>
{"› "}
</Text>
<Text>{value}</Text>
<Text color={meta.accent} bold>
{cursorOn ? "▍" : " "}
</Text>
</Box>
</Box>
</ModalCard>
);
}
+141
View File
@@ -0,0 +1,141 @@
/**
* Modal shown when the model proposes a plan revision via
* `revise_plan`. Renders a step-level diff between the old remaining
* tail and the new proposed tail:
*
* ●● ✓ step-2 · Wire middleware (kept, dim)
* − ●●● ✗ step-3 · Migrate session cookies (removed, red)
* + ●● ▶ step-3 · Skip cookie migration (added, green)
* + ●● ▶ step-4 · Update cookie tests (added, green)
*
* Two buttons: Accept / Reject. Accept replaces the in-memory plan's
* remaining steps with the new ones; Reject leaves the original plan
* intact and lets the model continue. The picker's border is amber
* to distinguish from the green checkpoint picker — revisions are a
* different decision point, deserve a different visual lane.
*/
import { Box, Text } from "ink";
import React from "react";
import type { PlanStep } from "../../tools/plan.js";
import { ModalCard } from "./ModalCard.js";
import { SingleSelect } from "./Select.js";
export type ReviseChoice = "accept" | "reject";
export interface PlanReviseConfirmProps {
reason: string;
/** Remaining steps from the current plan (before this revision). */
oldRemaining: PlanStep[];
/** Remaining steps the model is proposing as a replacement. */
newRemaining: PlanStep[];
/** Optional updated plan summary. */
summary?: string;
onChoose: (choice: ReviseChoice) => void;
}
interface DiffRow {
kind: "kept" | "removed" | "added";
step: PlanStep;
}
function computeDiff(oldSteps: PlanStep[], newSteps: PlanStep[]): DiffRow[] {
const oldIds = new Set(oldSteps.map((s) => s.id));
const newIds = new Set(newSteps.map((s) => s.id));
const rows: DiffRow[] = [];
// Show removed (in old, not in new) first — preserve original order.
for (const s of oldSteps) {
if (!newIds.has(s.id)) rows.push({ kind: "removed", step: s });
}
// Then walk new list. Steps in both lists render as kept; new-only as added.
for (const s of newSteps) {
rows.push({ kind: oldIds.has(s.id) ? "kept" : "added", step: s });
}
return rows;
}
function riskDots(risk: PlanStep["risk"]): { dots: string; color: string } {
switch (risk) {
case "high":
return { dots: "●●●", color: "#f87171" };
case "med":
return { dots: "●● ", color: "#fbbf24" };
case "low":
return { dots: "● ", color: "#4ade80" };
default:
return { dots: " ", color: "#94a3b8" };
}
}
function PlanReviseConfirmInner({
reason,
oldRemaining,
newRemaining,
summary,
onChoose,
}: PlanReviseConfirmProps) {
const rows = computeDiff(oldRemaining, newRemaining);
const removedCount = rows.filter((r) => r.kind === "removed").length;
const addedCount = rows.filter((r) => r.kind === "added").length;
const keptCount = rows.filter((r) => r.kind === "kept").length;
return (
<ModalCard
accent="#fbbf24"
icon="✏"
title="plan revision proposed"
subtitle={`−${removedCount} +${addedCount} · ${keptCount} kept`}
>
<Box marginBottom={1}>
<Text>{reason}</Text>
</Box>
{summary ? (
<Box marginBottom={1}>
<Text dimColor>{`updated summary: ${summary}`}</Text>
</Box>
) : null}
<Box marginBottom={1} flexDirection="column">
{rows.map((row) => {
const risk = riskDots(row.step.risk);
const prefix = row.kind === "removed" ? "−" : row.kind === "added" ? "+" : " ";
const prefixColor =
row.kind === "removed" ? "#f87171" : row.kind === "added" ? "#4ade80" : "#94a3b8";
const dim = row.kind === "kept";
const strike = row.kind === "removed";
return (
<Box key={`${row.kind}-${row.step.id}`}>
<Text color={prefixColor} bold>
{`${prefix} `}
</Text>
<Text color={risk.color} bold dimColor={dim}>
{risk.dots}
</Text>
<Text dimColor={dim} strikethrough={strike}>
{` ${row.step.id} · ${row.step.title}`}
</Text>
</Box>
);
})}
</Box>
<SingleSelect
initialValue="accept"
items={[
{
value: "accept",
label: "Accept revision — apply the new step list",
hint: "Replaces the remaining plan with the proposed steps. Done steps are untouched.",
},
{
value: "reject",
label: "Reject — keep the original plan",
hint: "Drops the proposal. Model continues with the original remaining steps.",
},
]}
onSubmit={(v) => onChoose(v as ReviseChoice)}
onCancel={() => onChoose("reject")}
footer="[↑↓] navigate · [Enter] select · [Esc] reject"
/>
</ModalCard>
);
}
export const PlanReviseConfirm = React.memo(PlanReviseConfirmInner);
+17 -12
View File
@@ -9,39 +9,44 @@
* - uncertainties: yellow — attention required (like tool)
* - rejected paths: red dim — ruled out (muted, like error-but-resolved)
*
* Only the label is colored + bold. The items themselves render in the
* terminal's default foreground, so they stay readable on any background —
* which is why the old single-magenta block was hard to see on dark themes.
* Visual: colored bold label + count, then dim items. No solid-bg pill
* — every assistant turn surfaces this block, so the bracket-text style
* keeps it from shouting four colored bg blocks at the user every turn.
* Color alone (the bold label) is enough to identify the field type.
*/
import { Box, Text } from "ink";
import React from "react";
import type { TypedPlanState } from "../../harvest.js";
import { COLOR } from "./theme.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, COLOR.primary, false]);
if (planState.hypotheses.length)
fields.push(["hypotheses", planState.hypotheses, "green", false]);
fields.push(["hypotheses", planState.hypotheses, COLOR.assistant, false]);
if (planState.uncertainties.length)
fields.push(["uncertainties", planState.uncertainties, "yellow", false]);
fields.push(["uncertainties", planState.uncertainties, COLOR.warn, false]);
if (planState.rejectedPaths.length)
fields.push(["rejected", planState.rejectedPaths, "red", true]);
fields.push(["rejected", planState.rejectedPaths, COLOR.info, true]);
if (fields.length === 0) return null;
return (
<Box flexDirection="column" marginBottom={1}>
{fields.map(([label, items, color, dim]) => (
<Text key={label}>
<Box key={label}>
<Text color={color} bold dimColor={dim}>
{"‹ "}
{label}
</Text>
<Text dimColor>{` (${items.length})`}</Text>
<Text>{`: ${items.join(" · ")}`}</Text>
</Text>
<Text dimColor>{" · "}</Text>
<Text dimColor={dim} color={dim ? undefined : COLOR.info}>
{items.join(" · ")}
</Text>
</Box>
))}
</Box>
);
+159
View File
@@ -0,0 +1,159 @@
/**
* Compact tree-style 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.
*
* Layout per step:
*
* 2/5 done (40%) · est. 5 steps
* ┣ ✓ step-1 · Extract tokens into a module
* ┣ ✓ step-2 · Migrate session cookies ⚠ med
* ┣ ▸ step-3 · Update tests ⚠ high
* ┣ ○ step-4 · Run regression suite
* ┗ ○ step-5 · Audit every callsite
* ████████░░░░░░░░░░░░ 40%
*
* Why this shape:
* - Status icons (✓ ▸ ○ ✗) read at a glance — color + glyph are
* redundant signals, useful for color-blind users and for
* terminals where a single bg-color cell is the only contrast.
* - Tree branch lines (┣ ┗) visually bind the steps as one group
* and mark "last step" with a corner — the eye finds the bottom
* without counting.
* - Risk only shown ≥medium. low risk on every line is noise (most
* steps are low-risk — that's the default). med + high are the
* ones that deserve attention before approve.
* - Bottom progress bar (24 cells of █ / ░) makes "how far in are
* we" answerable from the cursor's eye position alone.
*/
import { Box, Text } from "ink";
import React from "react";
import type { PlanStep, PlanStepRisk } from "../../tools/plan.js";
import { CharBar } from "./char-bar.js";
import { COLOR, GLYPH } from "./theme.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 the `cur` (▸) glyph in cyan
* even when its status is still "pending", so the user sees which
* one's about to run. If the step's status is "running" we always
* use the cur glyph regardless of focusStepId.
*/
focusStepId?: string;
}
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";
}
interface StatusGlyph {
glyph: string;
color: string;
}
/**
* Map (status, focus) → (glyph, color). Centralized so a future tweak
* (e.g. add a "queued for retry" state) lands in one switch instead of
* five render branches.
*/
function statusGlyph(status: StepStatus, isCur: boolean): StatusGlyph {
if (status === "done") return { glyph: GLYPH.done, color: COLOR.ok };
if (status === "running") return { glyph: GLYPH.cur, color: COLOR.primary };
if (status === "skipped") return { glyph: GLYPH.fail, color: COLOR.info };
// pending: focus override gets the cur glyph (▸) in primary color so
// the active row pops without us needing a separate column.
if (isCur) return { glyph: GLYPH.cur, color: COLOR.primary };
return { glyph: GLYPH.pending, color: COLOR.info };
}
function riskLabel(risk: PlanStepRisk | undefined): { text: string; color: string } | null {
if (risk === "med") return { text: `${GLYPH.warn} med`, color: COLOR.warn };
if (risk === "high") return { text: `${GLYPH.warn} high`, color: COLOR.err };
// low + undefined: omitted entirely (the default reading should be
// "low risk" — surfacing it on every line buries the med/high ones).
return null;
}
function PlanStepListInner({ steps, statuses, focusStepId }: PlanStepListProps) {
if (steps.length === 0) return null;
const statusList = steps.map((s) => getStatus(s.id, statuses));
const total = steps.length;
const doneCount = statusList.filter((s) => s === "done").length;
const pct = Math.round((doneCount / total) * 100);
// Show progress only when the plan has any motion. A freshly-submitted
// plan with 0/N done renders without the bar to avoid an empty
// "░░░░░░░░░░ 0%" rule that signals nothing.
const showProgress = doneCount > 0;
return (
<Box flexDirection="column">
<Box>
<Text dimColor>
{showProgress
? `${doneCount}/${total} done (${pct}%) · ${total} step${total === 1 ? "" : "s"}`
: `${total} step${total === 1 ? "" : "s"}`}
</Text>
</Box>
<Box flexDirection="column">
{steps.map((step, i) => {
const status = statusList[i]!;
const isLast = i === total - 1;
const isCur = focusStepId === step.id;
const sg = statusGlyph(status, isCur);
const risk = riskLabel(step.risk);
const titleDim = status === "done" || status === "skipped";
return (
<Box key={step.id}>
<Text color={COLOR.info} dimColor>
{isLast ? GLYPH.branchEnd : GLYPH.branch}
</Text>
<Text>{" "}</Text>
<Text color={sg.color} bold={status === "running" || isCur}>
{sg.glyph}
</Text>
<Text>{" "}</Text>
<Text
dimColor={titleDim}
bold={isCur || status === "running"}
strikethrough={status === "done" || status === "skipped"}
>
{`${step.id} · ${step.title}`}
</Text>
{risk ? (
<>
<Text>{" "}</Text>
<Text color={risk.color}>{risk.text}</Text>
</>
) : null}
</Box>
);
})}
</Box>
{showProgress ? (
<Box>
<Text>{" "}</Text>
<CharBar pct={pct} width={24} />
</Box>
) : null}
</Box>
);
}
export const PlanStepList = React.memo(PlanStepListInner);
export function riskOf(step: PlanStep): PlanStepRisk | undefined {
return step.risk;
}
+522 -117
View File
@@ -1,7 +1,52 @@
import { Box, Text, useInput } from "ink";
import { Box, Text, useStdout } from "ink";
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React as a runtime value (classic transform compiles JSX to React.createElement)
import React, { useRef, useState } from "react";
import { useKeystroke } from "./keystroke-context.js";
import { type MultilineKey, lineAndColumn, processMultilineKey } from "./multiline-keys.js";
import { useTick } from "./ticker.js";
import {
PASTE_SENTINEL_RANGE,
type PasteEntry,
encodePasteSentinel,
expandPasteSentinels,
listPasteIdsInBuffer,
makePasteEntry,
} from "./paste-sentinels.js";
import { type Segment, buildViewport, stringCells } from "./prompt-viewport.js";
import { GRADIENT } from "./theme.js";
/**
* Visual anchor: a left vertical rule (▎ + space) running down every
* line of the input. Colored with the accent color so disabled state
* dims it; gives the input area a clear "you type here" boundary
* without using bordered Boxes (those amplified Ink's eraseLines
* miscount on Windows). Length is fixed at 2 so the prefix-cell math
* stays trivial.
*/
const BAR = "▎ ";
/**
* Prompt input v2 — no Ink useInput, no Yoga text wrapping, no
* cursor blink. Replaces the bordered-Box / multi-Text approach
* that was driving the Windows ghost-row regressions.
*
* Pipeline:
* - Subscribes to the global keystroke bus (which is fed by our
* own raw stdin parser, NOT Ink's parse-keypress).
* - Pure events: `paste` events go to the paste registry; everything
* else flows through `processMultilineKey` (the existing reducer
* with all the cursor / submit / history-recall semantics).
* - Render: one logical line per <Box> row. Each row renders as
* EXACTLY one visual row — content longer than the visible cell
* budget is clipped via `buildViewport`, with `‹` / `›` markers
* where content is hidden. The cursor moves the viewport so it
* stays visible.
*
* Cursor blinks at ~480 ms half-period. The ticker that drives the
* blink also flows the left-bar gradient and the wordmark, so
* we're already paying for re-render every tick — the cursor blink
* is free on top of that. Disabled state freezes the cursor solid
* so the disabled prompt doesn't compete with the active spinner.
*/
export interface PromptInputProps {
value: string;
@@ -9,156 +54,516 @@ export interface PromptInputProps {
onSubmit: (v: string) => void;
disabled?: boolean;
placeholder?: string;
/**
* History recall. Fired when ↑/↓ hits a buffer boundary (empty
* buffer, or cursor already at the first/last line of a multi-line
* buffer). Parent walks its prompt history and swaps the value via
* `onChange`. Absent → keys are consumed silently.
*/
onHistoryPrev?: () => void;
onHistoryNext?: () => void;
}
/**
* Input box with real cursor support. ←/→ move one column, ↑/↓ move
* across lines in multi-line buffers, Ctrl+A / Ctrl+E jump to
* start/end of the current line. Backspace deletes before cursor,
* Delete deletes under cursor. Multi-line composition via Ctrl+J,
* Shift+Enter, or bash-style `\<Enter>`.
*
* Cursor state lives locally. When the parent replaces `value` out
* of band (history recall, slash completion, setup wizard) the
* cursor jumps to end; the `lastLocalValueRef` guards distinguishes
* that case from our own edits.
*/
export function PromptInput({
value,
onChange,
onSubmit,
disabled,
placeholder,
onHistoryPrev,
onHistoryNext,
}: PromptInputProps) {
const [cursor, setCursor] = useState(value.length);
// Tracks the last `value` we ourselves produced via onChange. If the
// incoming `value` prop diverges from this, the parent (or some other
// source) replaced the buffer — we reset the cursor to end.
// Paste registry — keyed by sentinel id, holds original content.
const pastesRef = useRef<Map<number, PasteEntry>>(new Map());
const nextPasteIdRef = useRef<number>(0);
// Track external value replacement (history recall, slash completion).
// When the parent swaps `value` we snap cursor to end.
const lastLocalValueRef = useRef(value);
if (value !== lastLocalValueRef.current) {
lastLocalValueRef.current = value;
if (cursor !== value.length) {
// Conditional setState during render is the "derived state" pattern;
// React schedules the re-render and the else branch of the `if`
// prevents infinite loops.
setCursor(value.length);
}
if (cursor !== value.length) setCursor(value.length);
}
// Shared ticker drives the cursor blink. Dividing the tick by 4 lands
// the visible on/off cycle around 480ms — standard cursor cadence.
const tick = useTick();
const showCursor = disabled ? false : Math.floor(tick / 4) % 2 === 0;
/**
* Register one paste blob and insert its sentinel at the current
* cursor. Used both by `paste` events from the stdin reader (the
* normal path on terminals that support DECSET 2004) and by the
* fallback path inside `processMultilineKey` for chunks that
* arrived without bracketed-paste markers.
*/
const registerPaste = (content: string) => {
const v = lastLocalValueRef.current;
const c = cursor;
const id = nextPasteIdRef.current % PASTE_SENTINEL_RANGE;
nextPasteIdRef.current = id + 1;
pastesRef.current.set(id, makePasteEntry(id, content));
const sentinel = encodePasteSentinel(id);
const next = v.slice(0, c) + sentinel + v.slice(c);
lastLocalValueRef.current = next;
onChange(next);
setCursor(c + 1);
};
useInput(
(input, key) => {
const ke: MultilineKey = {
input,
return: key.return,
shift: key.shift,
ctrl: key.ctrl,
meta: key.meta,
backspace: key.backspace,
delete: key.delete,
tab: key.tab,
upArrow: key.upArrow,
downArrow: key.downArrow,
leftArrow: key.leftArrow,
rightArrow: key.rightArrow,
escape: key.escape,
pageUp: key.pageUp,
pageDown: key.pageDown,
};
const action = processMultilineKey(value, cursor, ke);
if (action.next !== null) {
lastLocalValueRef.current = action.next;
onChange(action.next);
useKeystroke((ev) => {
if (disabled) return;
if (ev.paste) {
// Bracketed-paste content delivered by the stdin reader.
// Insert as one sentinel regardless of length.
if (ev.input.length > 0) registerPaste(ev.input);
return;
}
const key: MultilineKey = {
input: ev.input,
return: ev.return,
shift: ev.shift,
ctrl: ev.ctrl,
meta: ev.meta,
backspace: ev.backspace,
delete: ev.delete,
tab: ev.tab,
upArrow: ev.upArrow,
downArrow: ev.downArrow,
leftArrow: ev.leftArrow,
rightArrow: ev.rightArrow,
escape: ev.escape,
pageUp: ev.pageUp,
pageDown: ev.pageDown,
};
const action = processMultilineKey(value, cursor, key);
if (action.pasteRequest) {
registerPaste(action.pasteRequest.content);
return;
}
if (action.next !== null) {
lastLocalValueRef.current = action.next;
onChange(action.next);
}
if (action.cursor !== null) {
setCursor(action.cursor);
}
if (action.submit) {
const raw = action.submitValue ?? value;
const expanded = expandPasteSentinels(raw, pastesRef.current);
// GC unreachable paste entries — anything backspace'd out of
// the buffer before submit. Keeps the registry from growing
// unbounded across many turns.
const reachable = new Set(listPasteIdsInBuffer(raw));
for (const id of pastesRef.current.keys()) {
if (!reachable.has(id)) pastesRef.current.delete(id);
}
if (action.cursor !== null) {
setCursor(action.cursor);
}
if (action.submit) onSubmit(action.submitValue ?? value);
},
{ isActive: !disabled },
);
onSubmit(expanded);
}
if (action.historyHandoff === "prev") onHistoryPrev?.();
if (action.historyHandoff === "next") onHistoryNext?.();
}, !disabled);
// ── Render ──────────────────────────────────────────────────────
const { stdout } = useStdout();
const cols = stdout?.columns ?? 80;
const narrow = cols <= 90;
const promptBody = narrow ? "› " : "you › ";
const promptPrefix = BAR + promptBody;
const continuationIndent = BAR + " ".repeat(promptBody.length);
const prefixCells = promptPrefix.length;
// Reserve 2 cells for the surrounding `paddingX={1}` plus 1 cell
// for the cursor block when at end-of-line. Net visible budget per
// line.
const visibleCells = Math.max(8, cols - prefixCells - 3);
const placeholderActive = narrow
? "type a message, or /command"
: "type a message, or /command · [Ctrl+J] newline · [Ctrl+P/N] history";
const effectivePlaceholder = disabled
? (placeholder ?? "…waiting for response… · [Esc] to stop")
: (placeholder ?? "type a message, or /command · [Shift+Enter] / [Ctrl+J] newline");
? (placeholder ?? "…waiting for response…")
: (placeholder ?? placeholderActive);
const lines = value.length > 0 ? value.split("\n") : [""];
const borderColor = disabled ? "gray" : "cyan";
const accentColor = disabled ? "gray" : "cyan";
// Static bar + static cursor. Earlier versions flowed the bar
// gradient and blinked the cursor via the global ticker; both
// drove per-tick re-renders that interleaved badly with terminal
// resize (Ink's eraseLines miscounts logical vs visual rows on
// wrap, ghost frames stack). The bar still gets a gradient — just
// a fixed sweep based on row index, no time component.
const barColorAt = (rowIdx: number): string =>
disabled ? "gray" : GRADIENT[((rowIdx % GRADIENT.length) + GRADIENT.length) % GRADIENT.length]!;
const cursorVisible = true;
const { line: cursorLine, col: cursorCol } = lineAndColumn(value, cursor);
// Big-buffer mitigation: if the buffer has many logical lines,
// collapse middle rows so Ink isn't redrawing 500+ rows per
// keystroke.
const renderItems = collapseLinesForDisplay(lines, cursorLine);
const showHugeBufferHints = lines.length > 20;
return (
<Box borderStyle="round" borderColor={borderColor} paddingX={1} flexDirection="column">
{lines.map((line, i) => {
const isFirst = i === 0;
const showPlaceholder = isFirst && value.length === 0;
const isCursorLine = i === cursorLine;
return (
// biome-ignore lint/suspicious/noArrayIndexKey: stable by construction — lines are derived from `value.split("\n")` and never reordered
<Box key={i}>
{isFirst ? (
<Text bold color={borderColor}>
you ›{" "}
<Box flexDirection="column" paddingX={1}>
{renderItems.map((item, renderIdx) => {
if (item.kind === "skip") {
return (
// biome-ignore lint/suspicious/noArrayIndexKey: stable — collapse markers derive from a fixed sliding window
<Box key={`skip-${renderIdx}`}>
<Text color={barColorAt(renderIdx)}>{BAR}</Text>
<Text dimColor>{continuationIndent.slice(BAR.length)}</Text>
<Text dimColor>
{`[… ${item.linesHidden} line${item.linesHidden === 1 ? "" : "s"} hidden — full content kept, submitted on Enter …]`}
</Text>
) : (
<Text dimColor>{" "}</Text>
)}
{showPlaceholder ? (
<>
{isCursorLine && !disabled ? (
<Text color={borderColor}>{showCursor ? "▌" : " "}</Text>
) : null}
<Text dimColor>{effectivePlaceholder}</Text>
</>
) : isCursorLine && !disabled ? (
<LineWithCursor
line={line}
col={cursorCol}
showCursor={showCursor}
borderColor={borderColor}
/>
) : (
<Text>{line}</Text>
)}
</Box>
</Box>
);
}
const i = item.originalIndex;
const line = item.line;
const isFirst = i === 0;
const isCursorLine = i === cursorLine;
const showPlaceholder = isFirst && value.length === 0;
return (
<PromptLine
key={`ln-${i}`}
line={line}
isFirst={isFirst}
isCursorLine={isCursorLine && !disabled}
cursorCol={isCursorLine ? cursorCol : null}
cursorVisible={cursorVisible}
showPlaceholder={showPlaceholder}
placeholderText={effectivePlaceholder}
promptPrefix={promptPrefix}
continuationIndent={continuationIndent}
visibleCells={visibleCells}
accentColor={accentColor}
barColor={barColorAt(i)}
pastes={pastesRef.current}
disabled={disabled === true}
/>
);
})}
{showHugeBufferHints && !disabled ? (
<Box>
<Text color={barColorAt(0)}>{BAR}</Text>
<Text dimColor>{continuationIndent.slice(BAR.length)}</Text>
<Text dimColor>
{`[${lines.length} lines · PageUp/PageDown jump to top/bottom · Ctrl+U clear · Ctrl+W del word]`}
</Text>
</Box>
) : null}
{!disabled && !narrow && value.length > 0 && !value.includes("\n") ? (
<Box>
<Text color={barColorAt(0)}>{BAR}</Text>
<Text dimColor>{continuationIndent.slice(BAR.length)}</Text>
<Text dimColor>
[Ctrl+J] newline · [Enter] submit · ends with \ for line continuation
</Text>
</Box>
) : null}
{!disabled && !narrow && value.length === 0 ? (
<Box>
<Text color={barColorAt(0)}>{BAR}</Text>
<Text dimColor>{continuationIndent.slice(BAR.length)}</Text>
<Text dimColor>
[PgUp/PgDn] scroll log · [End] jump to latest · drag to select · auto-scrolls at edge
</Text>
</Box>
) : null}
{disabled ? (
<Box>
<Text color={barColorAt(0)}>{BAR}</Text>
<Text dimColor>{continuationIndent.slice(BAR.length)}</Text>
<Text dimColor>[Esc] to stop</Text>
</Box>
) : null}
</Box>
);
}
function LineWithCursor({
line,
col,
showCursor,
borderColor,
}: {
// ── PromptLine ────────────────────────────────────────────────────
interface PromptLineProps {
line: string;
col: number;
showCursor: boolean;
borderColor: "cyan" | "gray";
}) {
const before = line.slice(0, col);
const atCursor = line.slice(col, col + 1);
const after = line.slice(col + 1);
if (atCursor.length === 0) {
// Cursor sits past the last char of this line (end-of-line). Render
// a trailing block so the user sees where they're typing next.
isFirst: boolean;
isCursorLine: boolean;
cursorCol: number | null;
/** True when the cursor block / inverse char should be drawn this tick. */
cursorVisible: boolean;
showPlaceholder: boolean;
placeholderText: string;
promptPrefix: string;
continuationIndent: string;
visibleCells: number;
accentColor: "cyan" | "gray";
/** Animated gradient color for the leading ▎ bar. Differs per row + tick. */
barColor: string;
pastes: ReadonlyMap<number, PasteEntry>;
disabled: boolean;
}
function PromptLine({
line,
isFirst,
isCursorLine,
cursorCol,
cursorVisible,
showPlaceholder,
placeholderText,
promptPrefix,
continuationIndent,
visibleCells,
accentColor,
barColor,
pastes,
disabled,
}: PromptLineProps) {
// The leading BAR cells of every prefix/continuation are the left
// anchor bar — render them as a separate span colored by the
// animated gradient so the bar appears to flow vertically.
const barText = promptPrefix.slice(0, BAR.length);
const bodyPrefix = promptPrefix.slice(BAR.length);
const bodyContinuation = continuationIndent.slice(BAR.length);
if (showPlaceholder) {
return (
<>
<Text>{before}</Text>
<Text color={borderColor}>{showCursor ? "▌" : " "}</Text>
</>
<Box>
<Text color={barColor}>{barText}</Text>
<Text bold color={accentColor}>
{bodyPrefix}
</Text>
{!disabled ? <Text color={accentColor}>{cursorVisible ? "▌" : " "}</Text> : null}
<Text dimColor>{placeholderText}</Text>
</Box>
);
}
const viewport = buildViewport(line, isCursorLine ? cursorCol : null, visibleCells, pastes);
// Render: prefix + (left marker?) + segments-with-cursor + (right marker?)
return (
<>
<Text>{before}</Text>
<Text inverse={showCursor}>{atCursor}</Text>
<Text>{after}</Text>
</>
<Box>
<Text color={barColor}>{barText}</Text>
{isFirst ? (
<Text bold color={accentColor}>
{bodyPrefix}
</Text>
) : (
<Text dimColor>{bodyContinuation}</Text>
)}
{viewport.hiddenLeft ? (
<Text color="gray" dimColor>
‹
</Text>
) : null}
<ViewportContent
segments={viewport.segments}
cursorCell={isCursorLine ? viewport.cursorCell : null}
accentColor={accentColor}
cursorVisible={cursorVisible}
/>
{viewport.hiddenRight ? (
<Text color="gray" dimColor>
›
</Text>
) : null}
</Box>
);
}
// ── ViewportContent ────────────────────────────────────────────────
/**
* Render a viewport's segments with a cursor block at `cursorCell`.
* Walks segments in order; the cursor splits at most one segment
* (the one containing the cursor cell), producing an inverted char
* at that position.
*
* End-of-line cursor (cursorCell points past the last cell of the
* last segment): emit a trailing block.
*/
function ViewportContent({
segments,
cursorCell,
accentColor,
cursorVisible,
}: {
segments: Segment[];
cursorCell: number | null;
accentColor: "cyan" | "gray";
cursorVisible: boolean;
}) {
// No cursor on this line — straight render.
if (cursorCell === null) {
return <>{segments.map((seg, i) => renderSegment(seg, i, false))}</>;
}
// Walk segments tallying cells; once we reach `cursorCell`, split
// the segment to insert the cursor block.
const out: React.ReactNode[] = [];
let cells = 0;
let placed = false;
for (let i = 0; i < segments.length; i++) {
const seg = segments[i]!;
const segCells = segmentCells(seg);
if (placed) {
out.push(renderSegment(seg, i, false));
continue;
}
if (cursorCell >= cells + segCells) {
// Cursor isn't in this segment.
out.push(renderSegment(seg, i, false));
cells += segCells;
continue;
}
// Cursor lands inside this segment.
if (seg.kind === "paste") {
// The cursor is "on" the paste sentinel — render the paste
// block inversed so the user sees they're at it. Inverse
// toggles with the blink so the paste sentinel stays
// legible during the cursor's "off" half-cycle.
out.push(
<Text key={`p-${i}-cursor`} color="magenta" bold inverse={cursorVisible}>
{seg.label}
</Text>,
);
placed = true;
cells += segCells;
continue;
}
// text segment — split before/at-cursor/after by cell offset.
const offsetIntoSeg = cursorCell - cells;
const split = splitTextByCells(seg.text, offsetIntoSeg);
if (split.before.length > 0) {
out.push(<Text key={`t-${i}-b`}>{split.before}</Text>);
}
if (split.atCursor.length > 0) {
out.push(
<Text key={`t-${i}-c`} inverse={cursorVisible} color={accentColor}>
{split.atCursor}
</Text>,
);
} else {
// Cursor sits past the segment's last char (end-of-text in this
// segment). Render block here, blinking with the tick.
out.push(
<Text key={`t-${i}-c-eol`} color={accentColor}>
{cursorVisible ? "▌" : " "}
</Text>,
);
}
if (split.after.length > 0) {
out.push(<Text key={`t-${i}-a`}>{split.after}</Text>);
}
placed = true;
cells += segCells;
}
// Cursor sits past every segment (end of line).
if (!placed) {
out.push(
<Text key="cursor-eol" color={accentColor}>
{cursorVisible ? "▌" : " "}
</Text>,
);
}
return <>{out}</>;
}
function segmentCells(seg: Segment): number {
if (seg.kind === "paste") return seg.label.length;
return stringCells(seg.text);
}
/**
* Split a text string at a cell offset, returning the chars before
* the offset, the char AT the offset (the cursor block highlights
* it), and the chars after. A wide char that straddles the offset
* is treated as the cursor's char.
*/
function splitTextByCells(
text: string,
cellOffset: number,
): { before: string; atCursor: string; after: string } {
let cells = 0;
for (let i = 0; i < text.length; i++) {
const ch = text[i]!;
const cw = charCellsForText(ch);
if (cells === cellOffset) {
return { before: text.slice(0, i), atCursor: ch, after: text.slice(i + 1) };
}
if (cells + cw > cellOffset) {
// The wide char straddles the offset — show it as the cursor char.
return { before: text.slice(0, i), atCursor: ch, after: text.slice(i + 1) };
}
cells += cw;
}
// Cursor at end of text.
return { before: text, atCursor: "", after: "" };
}
/**
* Local cell-counting helper — duplicates `charCells` from
* prompt-viewport but inlined to avoid a back-and-forth import (this
* function is hot per-keystroke). Keep in sync.
*/
function charCellsForText(ch: string): number {
const code = ch.charCodeAt(0);
if (code < 0x20 || code === 0x7f) return 0;
if (code < 0x1100) return 1;
if (code >= 0x1100 && code <= 0x115f) return 2;
if (code >= 0x2e80 && code <= 0x303e) return 2;
if (code >= 0x3041 && code <= 0x33ff) return 2;
if (code >= 0x3400 && code <= 0x4dbf) return 2;
if (code >= 0x4e00 && code <= 0x9fff) return 2;
if (code >= 0xa000 && code <= 0xa4cf) return 2;
if (code >= 0xac00 && code <= 0xd7a3) return 2;
if (code >= 0xf900 && code <= 0xfaff) return 2;
if (code >= 0xfe30 && code <= 0xfe4f) return 2;
if (code >= 0xff00 && code <= 0xff60) return 2;
if (code >= 0xffe0 && code <= 0xffe6) return 2;
return 1;
}
function renderSegment(seg: Segment, key: number, _inverse: boolean): React.ReactNode {
if (seg.kind === "text") {
return <Text key={`s-${key}`}>{seg.text}</Text>;
}
// Paste sentinels render as a fuchsia bg-pill so they're visually
// distinct from typed text — the user can see "this is the
// collapsed paste, not 47 lines of code I typed". Matches the
// bg-pill idiom used elsewhere (mode bars, tool names).
return (
<Text key={`s-${key}`} backgroundColor="#f0abfc" color="black" bold>
{seg.label}
</Text>
);
}
// ── collapse helper (preserved from v1) ────────────────────────────
type RenderItem =
| { kind: "line"; line: string; originalIndex: number }
| { kind: "skip"; linesHidden: number };
const COLLAPSE_THRESHOLD = 20;
const COLLAPSE_HEAD_LINES = 3;
const COLLAPSE_TAIL_LINES = 2;
export function collapseLinesForDisplay(lines: string[], cursorLine: number): RenderItem[] {
if (lines.length <= COLLAPSE_THRESHOLD) {
return lines.map((line, i) => ({ kind: "line" as const, line, originalIndex: i }));
}
const keep = new Set<number>();
for (let i = 0; i < COLLAPSE_HEAD_LINES && i < lines.length; i++) keep.add(i);
for (let i = Math.max(0, lines.length - COLLAPSE_TAIL_LINES); i < lines.length; i++) keep.add(i);
if (cursorLine >= 0 && cursorLine < lines.length) keep.add(cursorLine);
const sorted = [...keep].sort((a, b) => a - b);
const out: RenderItem[] = [];
let prev = -1;
for (const idx of sorted) {
if (idx - prev > 1) {
out.push({ kind: "skip", linesHidden: idx - prev - 1 });
}
out.push({ kind: "line", line: lines[idx] ?? "", originalIndex: idx });
prev = idx;
}
return out;
}
+8 -2
View File
@@ -10,7 +10,7 @@
import { Box, Text } from "ink";
import React from "react";
import type { TranscriptRecord } from "../../transcript.js";
import type { TranscriptRecord } from "../../transcript/log.js";
import { PlanStateBlock } from "./PlanStateBlock.js";
export interface RecordViewProps {
@@ -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>
);
}
+4 -7
View File
@@ -10,8 +10,8 @@
import { Box, Static, Text, useApp, useInput } from "ink";
import React, { useMemo, useState } from "react";
import { type TurnPage, computeCumulativeStats } from "../../replay.js";
import type { TranscriptMeta } from "../../transcript.js";
import type { TranscriptMeta } from "../../transcript/log.js";
import { type TurnPage, computeCumulativeStats } from "../../transcript/replay.js";
import { RecordView } from "./RecordView.js";
import { StatsPanel } from "./StatsPanel.js";
@@ -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 =
@@ -74,11 +75,7 @@ export function ReplayApp({ meta, pages }: ReplayAppProps) {
return (
<Box flexDirection="column">
<StatsPanel
summary={summary}
model={cumStats.models[0] ?? meta?.model ?? "?"}
prefixHash={prefixHash}
/>
<StatsPanel summary={summary} />
<Box flexDirection="column" marginTop={1} paddingX={1}>
<Box justifyContent="space-between">
+92 -32
View File
@@ -9,8 +9,10 @@
* 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";
import { COLOR } from "./theme.js";
export interface SelectItem<V extends string = string> {
/** Stable identifier — returned to caller on submit. */
@@ -21,19 +23,16 @@ export interface SelectItem<V extends string = string> {
hint?: string;
/** If true, item is not selectable (rendered dimmed, skipped on nav). */
disabled?: boolean;
/** Tab on this item starts inline-edit; typed text is forwarded as `onSubmit`'s 2nd arg. */
denyWithContext?: boolean;
}
export interface SingleSelectProps<V extends string> {
items: SelectItem<V>[];
initialValue?: V;
onSubmit: (value: V) => void;
onSubmit: (value: V, context?: string) => 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.
*/
/** Optional dim footer beneath the list — e.g. "[↑↓] navigate · [Enter] select · [Esc] cancel". */
footer?: string;
}
@@ -49,33 +48,83 @@ export function SingleSelect<V extends string>({
items.findIndex((i) => i.value === initialValue && !i.disabled),
);
const [index, setIndex] = useState(initialIndex === -1 ? 0 : initialIndex);
const [editingContext, setEditingContext] = useState<string | null>(null);
const activeItem = items[index];
const isEditing = editingContext !== null;
useInput((_input, key) => {
if (key.upArrow) {
useKeystroke((ev) => {
if (isEditing) {
if (ev.paste) {
setEditingContext((v) => (v ?? "") + ev.input);
return;
}
if (ev.escape) {
setEditingContext(null);
} else if (ev.upArrow || ev.downArrow) {
setEditingContext(null);
setIndex((i) => findNextEnabled(items, i, ev.upArrow ? -1 : +1));
} else if (ev.return) {
const chosen = items[index];
if (chosen && !chosen.disabled) {
const ctx = editingContext || undefined;
setEditingContext(null);
onSubmit(chosen.value, ctx);
}
} else if (ev.backspace) {
setEditingContext((v) => (v ?? "").slice(0, -1));
} else if (ev.tab) {
setEditingContext((v) => `${v ?? ""}, `);
} else if (ev.input) {
setEditingContext((v) => (v ?? "") + ev.input);
}
return;
}
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.tab && activeItem?.denyWithContext) {
setEditingContext("");
} 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();
}
});
const canDenyWithContext = activeItem?.denyWithContext;
const resolvedFooter = (() => {
if (isEditing) return "[Enter] confirm · [Esc] cancel · [↑↓] change option";
return (
footer ??
(canDenyWithContext
? "[↑↓] navigate · [Enter] select · [Tab] add context · [Esc] cancel"
: undefined)
);
})();
return (
<Box flexDirection="column">
{items.map((item, i) => (
<SelectRow
key={item.value}
item={item}
active={i === index}
marker={i === index ? "▸" : " "}
/>
))}
{footer ? (
{items.map((item, i) => {
const showEditing = i === index && isEditing;
const displayLabel = showEditing ? `${item.label}, ${editingContext}` : item.label;
return (
<SelectRow
key={item.value}
item={{ ...item, label: displayLabel }}
active={i === index}
marker={i === index ? "▸" : " "}
showInlineCursor={showEditing}
/>
);
})}
{resolvedFooter ? (
<Box marginTop={1}>
<Text dimColor>{footer}</Text>
<Text dimColor>{resolvedFooter}</Text>
</Box>
) : null}
</Box>
@@ -87,7 +136,7 @@ export interface MultiSelectProps<V extends string> {
initialSelected?: V[];
onSubmit: (values: V[]) => void;
onCancel?: () => void;
/** Footer hint under the list — e.g. "space toggle · enter confirm". */
/** Footer hint under the list — e.g. "[Space] toggle · [Enter] confirm". */
footer?: string;
}
@@ -104,12 +153,13 @@ export function MultiSelect<V extends string>({
});
const [selected, setSelected] = useState<Set<V>>(new Set(initialSelected));
useInput((input, key) => {
if (key.upArrow) {
useKeystroke((ev) => {
if (ev.paste) return;
if (ev.upArrow) {
setIndex((i) => findNextEnabled(items, i, -1));
} else if (key.downArrow) {
} else if (ev.downArrow) {
setIndex((i) => findNextEnabled(items, i, +1));
} else if (input === " ") {
} else if (ev.input === " ") {
const item = items[index];
if (!item || item.disabled) return;
setSelected((prev) => {
@@ -118,13 +168,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();
}
});
@@ -158,18 +208,28 @@ function SelectRow<V extends string>({
item,
active,
marker,
showInlineCursor = false,
}: {
item: SelectItem<V>;
active: boolean;
marker: string;
showInlineCursor?: boolean;
}) {
const color = item.disabled ? "gray" : active ? "cyan" : undefined;
// Color: dim for disabled, primary cyan + bold for active, plain
// default for inactive. Keeps the active-row affordance consistent
// with the slash + at-mention pickers (▸ + colored text).
const color = item.disabled ? COLOR.info : active ? COLOR.primary : undefined;
return (
<Box flexDirection="column">
<Box>
<Text color={color}>
<Text color={color} bold={active} dimColor={item.disabled}>
{marker} {item.label}
</Text>
{showInlineCursor ? (
<Text backgroundColor="#67e8f9" color="black">
{" "}
</Text>
) : null}
</Box>
{item.hint ? (
<Box paddingLeft={marker.length + 1}>
+18 -3
View File
@@ -1,6 +1,7 @@
import { Box, Text } from "ink";
import React from "react";
import { SingleSelect } from "./Select.js";
import { COLOR, GLYPH } from "./theme.js";
export type SessionChoice = "resume" | "new" | "delete";
@@ -12,6 +13,15 @@ export interface SessionPickerProps {
onChoose: (choice: SessionChoice) => void;
}
/**
* Resume / new / delete picker shown at launch when a prior session
* file exists. Three lines of header (brand mark · session summary)
* then the selector, then a footer with key bindings.
*
* Visual grammar matches the design's session-resume modal: brand
* glyph in primary color, session name highlighted, the rest dim.
* No solid-bg pills — bracket-text style continues.
*/
export function SessionPicker({
sessionName,
messageCount,
@@ -21,9 +31,14 @@ export function SessionPicker({
return (
<Box flexDirection="column" marginY={1}>
<Box marginBottom={1}>
<Text bold color="cyan">
{`Session "${sessionName}" has ${messageCount} prior message${messageCount === 1 ? "" : "s"}`}
<Text color={COLOR.brand} bold>
{GLYPH.brand}
</Text>
<Text>{" "}</Text>
<Text color={COLOR.primary} bold>
{`"${sessionName}"`}
</Text>
<Text dimColor>{` has ${messageCount} prior message${messageCount === 1 ? "" : "s"}`}</Text>
<Text dimColor>{` · last active ${relativeTime(lastActive)}`}</Text>
</Box>
<SingleSelect
@@ -48,7 +63,7 @@ export function SessionPicker({
onSubmit={(v) => onChoose(v as SessionChoice)}
/>
<Box marginTop={1}>
<Text dimColor>↑↓ to move · Enter to pick</Text>
<Text dimColor>{" ↑↓ navigate · ⏎ select"}</Text>
</Box>
</Box>
);
+33 -13
View File
@@ -2,6 +2,7 @@ import { Box, Text, useApp } from "ink";
import TextInput from "ink-text-input";
import React, { useState } from "react";
import { defaultConfigPath, isPlausibleKey, redactKey, saveApiKey } from "../../config.js";
import { COLOR, GLYPH, GRADIENT } from "./theme.js";
export interface SetupProps {
onReady: (apiKey: string) => void;
@@ -33,18 +34,34 @@ export function Setup({ onReady }: SetupProps) {
};
return (
<Box flexDirection="column" borderStyle="round" borderColor="cyan" paddingX={1}>
<Text bold color="cyan">
Welcome to Reasonix.
</Text>
<Box marginTop={1}>
<Text>Paste your DeepSeek API key to get started.</Text>
<Box flexDirection="column" paddingX={1} marginY={1}>
<Box>
<Text bold color={GRADIENT[0]}>
{GLYPH.brand}
</Text>
<Text>{" "}</Text>
<Text bold>Welcome to </Text>
<Text bold color={GRADIENT[2]}>
REASONIX
</Text>
</Box>
<Text dimColor>Get one (free credit on signup): https://platform.deepseek.com/api_keys</Text>
<Text dimColor>Saved locally to {defaultConfigPath()}</Text>
<Box marginTop={1}>
<Text bold color="cyan">
{"key › "}
<Text color={COLOR.info}>Paste your DeepSeek API key to get started.</Text>
</Box>
<Box>
<Text dimColor>{" free credit on signup · "}</Text>
<Text color={COLOR.primary}>https://platform.deepseek.com/api_keys</Text>
</Box>
<Box>
<Text dimColor>{" saved to "}</Text>
<Text dimColor>{defaultConfigPath()}</Text>
</Box>
<Box marginTop={1}>
<Text bold color={COLOR.brand}>
{GLYPH.bar}
</Text>
<Text bold color={COLOR.primary}>
{" › "}
</Text>
<TextInput
value={value}
@@ -56,15 +73,18 @@ export function Setup({ onReady }: SetupProps) {
</Box>
{error ? (
<Box marginTop={1}>
<Text color="red">{error}</Text>
<Text color={COLOR.err} bold>
{GLYPH.err}
</Text>
<Text color={COLOR.err}>{` ${error}`}</Text>
</Box>
) : value ? (
<Box marginTop={1}>
<Text dimColor>preview: {redactKey(value)}</Text>
<Text dimColor>{` preview · ${redactKey(value)}`}</Text>
</Box>
) : null}
<Box marginTop={1}>
<Text dimColor>(Type /exit to abort.)</Text>
<Text dimColor>{" /exit to abort"}</Text>
</Box>
</Box>
);
+58 -44
View File
@@ -1,6 +1,8 @@
import { Box, Text } from "ink";
import React from "react";
import { ModalCard } from "./ModalCard.js";
import { SingleSelect } from "./Select.js";
import { COLOR } from "./theme.js";
export type ShellConfirmChoice = "run_once" | "always_allow" | "deny";
@@ -11,7 +13,14 @@ export interface ShellConfirmProps {
* "always allow". Typically the first 1-2 tokens of `command`.
*/
allowPrefix: string;
onChoose: (choice: ShellConfirmChoice) => void;
/**
* 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, denyContext?: string) => void;
}
/**
@@ -23,53 +32,58 @@ export interface ShellConfirmProps {
* 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.
* when the user was mid-typing a response. Tab on Deny opens inline
* context entry, returned as `onChoose`'s 2nd arg.
*/
export function ShellConfirm({ command, allowPrefix, onChoose }: ShellConfirmProps) {
export function ShellConfirm({ command, allowPrefix, kind, onChoose }: ShellConfirmProps) {
const isBackground = kind === "run_background";
const subtitle = isBackground
? "long-running process — keeps running after approval, /kill to stop"
: "model wants to run a shell command";
const denyItem = {
value: "deny" as const,
label: "Deny",
hint: "Not what you wanted? Press Tab to append `,` and tell the model what to do instead.",
denyWithContext: true as const,
};
return (
<Box flexDirection="column" borderStyle="round" borderColor="yellow" paddingX={1} marginY={1}>
<Box>
<Text bold color="yellow">
▸ model wants to run a shell command
<ModalCard
accent={COLOR.err}
icon={isBackground ? "⏱" : "⚡"}
title={isBackground ? "background process" : "shell command"}
subtitle={subtitle}
>
<Box marginBottom={1}>
<Text color={COLOR.primary} bold>
{"$ "}
</Text>
<Text bold>{command}</Text>
</Box>
<Box>
<Text color="yellow" dimColor>
{"──────────────────────────────────────────"}
</Text>
</Box>
<Box marginTop={1}>
<Text>
<Text dimColor>{"$ "}</Text>
<Text color="cyan">{command}</Text>
</Text>
</Box>
<Box marginTop={1}>
<SingleSelect
initialValue="run_once"
items={[
{
value: "run_once",
label: "Run once",
hint: "Execute this command, don't remember it.",
},
{
value: "always_allow",
label: `Always allow "${allowPrefix}" in this project`,
hint: "Save the prefix to ~/.reasonix/config.json; future matches auto-run.",
},
{
value: "deny",
label: "Deny",
hint: "Tell the model the user refused; it will continue without this command.",
},
]}
onSubmit={(v) => onChoose(v as ShellConfirmChoice)}
onCancel={() => onChoose("deny")}
footer="[↑↓] navigate · [Enter] select · [Esc] deny"
/>
</Box>
</Box>
<SingleSelect
initialValue="run_once"
items={[
{
value: "run_once",
label: "Run once",
hint: "Execute this command, don't remember it.",
},
{
value: "always_allow",
label: `Always allow "${allowPrefix}" in this project`,
hint: "Save the prefix to ~/.reasonix/config.json; future matches auto-run.",
},
denyItem,
]}
onSubmit={(v, ctx) => {
if (v === "deny") onChoose("deny", ctx);
else onChoose(v as ShellConfirmChoice);
}}
onCancel={() => onChoose("deny")}
footer="[↑↓] navigate · [Enter] select · [Tab] add context · [Esc] deny"
/>
</ModalCard>
);
}
+42 -35
View File
@@ -2,6 +2,7 @@ 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";
import { COLOR, GLYPH } from "./theme.js";
export interface SlashArgPickerProps {
/**
@@ -36,15 +37,28 @@ export function SlashArgPicker({
kind,
partial,
}: SlashArgPickerProps): React.ReactElement | null {
// Hint mode: a single dim row explaining the argsHint + summary.
// Header row shared by both hint and picker modes — same shape so
// the UI looks like the same affordance, just with or without rows
// beneath. cmd in accent violet (matches SlashSuggestions), argsHint
// in dim, summary in info.
const headerRow = (
<Box>
<Text color={COLOR.accent} bold>
{"/ "}
</Text>
<Text color={COLOR.accent} bold>
{`/${spec.cmd}`}
</Text>
{spec.argsHint ? <Text dimColor>{` ${spec.argsHint}`}</Text> : null}
<Text dimColor>{` ${spec.summary}`}</Text>
</Box>
);
// Hint mode: header only.
if (kind === "hint") {
return (
<Box paddingX={1}>
<Text dimColor>
{" "}
<Text bold>/{spec.cmd}</Text>
{spec.argsHint ? ` ${spec.argsHint}` : ""} — {spec.summary}
</Text>
<Box paddingX={1} marginTop={1}>
{headerRow}
</Box>
);
}
@@ -52,13 +66,15 @@ export function SlashArgPicker({
if (matches === null) return null;
if (matches.length === 0) {
return (
<Box flexDirection="column" paddingX={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 flexDirection="column" paddingX={1} marginTop={1}>
{headerRow}
<Box>
<Text color={COLOR.warn} bold>
{GLYPH.warn}
</Text>
<Text color={COLOR.warn}>{` no match for "${partial}"`}</Text>
<Text dimColor>{" — keep typing, or Backspace to edit"}</Text>
</Box>
</Box>
);
}
@@ -71,37 +87,28 @@ export function SlashArgPicker({
const hiddenAbove = windowStart;
const hiddenBelow = total - windowStart - shown.length;
return (
<Box flexDirection="column" paddingX={1}>
<Text dimColor>
{" "}
<Text bold>/{spec.cmd}</Text>
{spec.argsHint ? ` ${spec.argsHint}` : ""} — {spec.summary}
</Text>
{hiddenAbove > 0 ? <Text dimColor> ↑ {hiddenAbove} more above</Text> : null}
<Box flexDirection="column" paddingX={1} marginTop={1}>
{headerRow}
{hiddenAbove > 0 ? <Text dimColor>{` ↑ ${hiddenAbove} 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>
{hiddenBelow > 0 ? <Text dimColor>{` ↓ ${hiddenBelow} below`}</Text> : null}
<Box marginTop={0}>
<Text dimColor>{" ↑↓ navigate · Tab / ⏎ pick · esc cancel"}</Text>
</Box>
</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 color={isSelected ? COLOR.primary : COLOR.info} bold={isSelected}>
{isSelected ? `${GLYPH.cur} ` : " "}
</Text>
<Text color={isSelected ? COLOR.user : COLOR.info} bold={isSelected} dimColor={!isSelected}>
{value}
</Text>
</Box>
);
+46 -31
View File
@@ -2,6 +2,7 @@ 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";
import { COLOR, GLYPH } from "./theme.js";
export interface SlashSuggestionsProps {
/**
@@ -15,11 +16,21 @@ export interface SlashSuggestionsProps {
}
/**
* Floating slash-command panel. Rendered below the input box when
* the user is typing a `/…` prefix. Navigation state lives in the
* parent (App.tsx owns `slashSelected`) so ↑/↓/Tab/Enter stay
* consistent with the useInput handler. This component is pure
* display: `matches` and `selectedIndex` come in, rows go out.
* Slash-command palette. Rendered below the input box while the user
* is typing a `/…` prefix. Visual grammar matches the design doc's
* picker style:
*
* / suggestions esc cancel
* ▸ /checkpoint [name] snapshot the workspace
* /restore <name> roll back files to a checkpoint
* /diff cumulative diff vs session start
* [↑↓] navigate · [Tab/⏎] pick
*
* Cmd tokens render in accent violet (one consistent color for "this
* is a command"), descriptions in dim info color. The selected row
* gets a leading ▸ + bold cmd; non-selected rows get a 2-space pad in
* the same column so the cmd column stays aligned. No solid-bg pill —
* the bracket-text pattern from the chrome carries through here.
*/
export function SlashSuggestions({
matches,
@@ -28,9 +39,13 @@ export function SlashSuggestions({
if (matches === null) return null;
if (matches.length === 0) {
return (
<Box paddingX={1}>
<Text color="yellow">no slash command matches that prefix</Text>
<Text dimColor> — Backspace to edit, or /help for the full list</Text>
<Box paddingX={1} marginTop={1}>
<Text color={COLOR.warn} bold>
{GLYPH.warn}
</Text>
<Text> </Text>
<Text color={COLOR.warn}>no slash command matches that prefix</Text>
<Text dimColor>{" — Backspace to edit, or /help for the full list"}</Text>
</Box>
);
}
@@ -45,40 +60,40 @@ export function SlashSuggestions({
const hiddenAbove = windowStart;
const hiddenBelow = total - windowStart - shown.length;
return (
<Box flexDirection="column" paddingX={1}>
{hiddenAbove > 0 ? <Text dimColor> ↑ {hiddenAbove} more above</Text> : null}
<Box flexDirection="column" paddingX={1} marginTop={1}>
<Box>
<Text color={COLOR.accent} bold>
{"/ "}
</Text>
<Text dimColor>{`${total} command${total === 1 ? "" : "s"}`}</Text>
{hiddenAbove > 0 ? <Text dimColor>{` ↑ ${hiddenAbove} above`}</Text> : null}
</Box>
{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]/[Enter] pick</Text>
{hiddenBelow > 0 ? <Text dimColor>{` ↓ ${hiddenBelow} below`}</Text> : null}
<Box marginTop={0}>
<Text dimColor>{" ↑↓ navigate · Tab / ⏎ pick · esc cancel"}</Text>
</Box>
</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.
if (isSelected) {
return (
<Box>
<Text bold color="cyan">
{marker} {name.padEnd(12)}
{argsSuffix.padEnd(16)}
</Text>
<Text color="cyan"> {spec.summary}</Text>
</Box>
);
}
const argsSuffix = spec.argsHint ? spec.argsHint : "";
return (
<Box>
<Text dimColor>
{marker} {name.padEnd(12)}
{argsSuffix.padEnd(16)} {spec.summary}
<Text color={isSelected ? COLOR.primary : COLOR.info} bold={isSelected}>
{isSelected ? `${GLYPH.cur} ` : " "}
</Text>
<Text color={COLOR.accent} bold={isSelected}>
{name.padEnd(14)}
</Text>
<Text dimColor>{argsSuffix.padEnd(14)}</Text>
<Text>{" "}</Text>
<Text color={isSelected ? COLOR.user : COLOR.info} dimColor={!isSelected}>
{spec.summary}
</Text>
</Box>
);
+108
View File
@@ -0,0 +1,108 @@
/**
* Side-by-side diff renderer — git-difftool / delta-style "old | new"
* layout. Each row shows the same logical position on both sides;
* removed lines have content on the left only with a red wash, added
* lines on the right with a green wash, common context appears on
* both sides dim.
*
* Layout:
*
* 40 function loginUser(...) │ 40 function loginUser(...)
* 41 - if (!email) throw new Error… │ 41 + if (!email || typeof email…
* │ 42 + throw new TypeError(…)
* │ 43 + }
* 42 return verify(email, …) │ 44 return verify(email, …)
*
* Width is derived from the terminal — half each side minus a 3-cell
* separator (` │ `). Long lines truncate with `…` rather than wrap,
* so the row count stays predictable for the parent's height budget.
*/
import { Box, Text, useStdout } from "ink";
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React in value scope for React.Fragment
import React from "react";
import type { SplitDiffRow } from "../../code/diff-preview.js";
import { COLOR } from "./theme.js";
export interface SplitDiffProps {
rows: readonly SplitDiffRow[];
/**
* Total columns budget. Defaults to terminal width. Modal callers
* pass a smaller number so the diff fits inside the modal frame.
*/
totalCols?: number;
}
export function SplitDiff({ rows, totalCols }: SplitDiffProps): React.ReactElement {
const { stdout } = useStdout();
const cols = totalCols ?? stdout?.columns ?? 80;
// Reserve ~6 cells for outer border + padding on the modal/log side,
// 3 cells for the ` │ ` separator. Half the rest per column.
const innerCols = Math.max(40, cols - 6);
const halfCols = Math.floor((innerCols - 3) / 2);
return (
<Box flexDirection="column">
{rows.map((row, i) => (
<Box key={`r-${i}-${row.left.num ?? "p"}-${row.right.num ?? "p"}`}>
<Cell side={row.left} width={halfCols} which="left" />
<Text color={COLOR.info} dimColor>
{" │ "}
</Text>
<Cell side={row.right} width={halfCols} which="right" />
</Box>
))}
</Box>
);
}
function Cell({
side,
width,
which,
}: {
side: SplitDiffRow["left"] | SplitDiffRow["right"];
width: number;
which: "left" | "right";
}) {
const numPad = 4; // up to 9999 lines
const sgnPad = 1; // single-char sign
const inner = Math.max(8, width - numPad - sgnPad - 2 /* spaces */);
const numStr = side.num !== null ? String(side.num).padStart(numPad) : " ".repeat(numPad);
const sign =
side.kind === "del" ? "-" : side.kind === "add" ? "+" : side.kind === "pad" ? " " : " ";
const raw = side.text;
const truncated = raw.length > inner ? `${raw.slice(0, inner - 1)}…` : raw;
// Pad to fixed width so the bg color stretches across the whole
// column even when the text is short — without this the red/green
// wash would only cover the actual chars and the rest of the row
// would be terminal default, which looks broken.
const padded = truncated.padEnd(inner);
if (side.kind === "del") {
return (
<Text color="#fbc8c8" backgroundColor="#2a1212">
{`${numStr} ${sign} ${padded}`}
</Text>
);
}
if (side.kind === "add") {
return (
<Text color="#bef0c8" backgroundColor="#0c2718">
{`${numStr} ${sign} ${padded}`}
</Text>
);
}
if (side.kind === "pad") {
// Empty side — mute everything, no bg, no glyph. The "… more
// lines" capRows marker also rides this kind on the left side
// when present, so we render its text dim italic.
return (
<Text color={COLOR.info} dimColor italic={!!raw}>
{`${numStr} ${sign} ${padded}`}
</Text>
);
}
// ctx: same content both sides, dim
return <Text dimColor>{`${numStr} ${sign} ${padded}`}</Text>;
}
+210 -401
View File
@@ -1,445 +1,254 @@
import { basename } from "node:path";
import { Box, Text, useStdout } from "ink";
import React from "react";
import { DEEPSEEK_CONTEXT_TOKENS, DEFAULT_CONTEXT_TOKENS } from "../../telemetry.js";
import type { SessionSummary } from "../../telemetry.js";
import { VERSION } from "../../version.js";
import { useTick } from "./ticker.js";
import stringWidth from "string-width";
import type { EditMode } from "../../config.js";
import type { SessionSummary } from "../../telemetry/stats.js";
import { Bar, ChromeRule } from "./primitives.js";
import { COLOR, GRADIENT } from "./theme.js";
/**
* Cyan → blue → purple truecolor gradient for the REASONIX wordmark.
* Each char gets its own hex color — terminals that support 24-bit
* color (nearly all since 2016) render this as a smooth fade. Older
* 256-color terminals snap to nearest; 8-color fall all the way back
* to plain cyan via Ink's color pipeline, so the worst case is still
* legible.
*/
const WORDMARK_STYLES: ReadonlyArray<{ ch: string; color: string; isLogo: boolean }> = [
{ ch: "◈", color: "#5eead4", isLogo: true }, // teal — brand mark
{ ch: " ", color: "#5eead4", isLogo: false },
{ ch: "R", color: "#67e8f9", isLogo: false }, // cyan
{ ch: "E", color: "#7dd3fc", isLogo: false }, // sky
{ ch: "A", color: "#93c5fd", isLogo: false }, // blue
{ ch: "S", color: "#a5b4fc", isLogo: false }, // indigo
{ ch: "O", color: "#c4b5fd", isLogo: false }, // violet
{ ch: "N", color: "#d8b4fe", isLogo: false }, // purple
{ ch: "I", color: "#f0abfc", isLogo: false }, // fuchsia
{ ch: "X", color: "#f0abfc", isLogo: false }, // fuchsia
];
/**
* Gradient-filled, animated app wordmark. The `◈` brand mark breathes
* (bold on/off) once every ~1.6s when idle, ~600ms when the model is
* working, so a glance at the top of the screen tells you immediately
* whether the app is doing something. Letters' keys use the char+color
* pair (not an index) so React state attaches to the glyph itself;
* fine because WORDMARK_STYLES never reorders.
*/
function Wordmark({ busy }: { busy: boolean }) {
const tick = useTick();
// Slow pulse = 12 ticks (~1.4s). Busy pulse = 5 ticks (~600ms).
const period = busy ? 5 : 12;
const bright = Math.floor(tick / period) % 2 === 0;
return (
<Text>
{WORDMARK_STYLES.map((c) => (
<Text key={`${c.ch}-${c.color}`} color={c.color} bold={c.isLogo ? bright : true}>
{c.ch}
</Text>
))}
</Text>
);
}
const COLD_START_TURNS = 3;
export interface StatsPanelProps {
summary: SessionSummary;
model: string;
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;
/**
* Account balance fetched once at launch (and optionally refreshed
* per-turn by the TUI). `null` or absent hides the balance cell
* entirely — /user/balance failed or the user ran with `--no-config`.
* The top-up warning fires below 1.0 unit of whatever currency
* the endpoint reports so a Chinese user with CNY and a U.S. user
* with USD both see "getting low."
*/
editMode?: EditMode;
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;
proArmed?: boolean;
escalated?: boolean;
budgetUsd?: number | null;
rootDir?: string;
sessionName?: string | null;
}
/**
* 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,
budgetUsd,
rootDir,
sessionName,
}: StatsPanelProps) {
const branchOn = (branchBudget ?? 1) > 1;
const ctxMax = DEEPSEEK_CONTEXT_TOKENS[model] ?? DEFAULT_CONTEXT_TOKENS;
const ctxRatio = summary.lastPromptTokens / ctxMax;
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;
return (
<Box borderStyle="round" borderColor="cyan" flexDirection="column" paddingX={1}>
<Header
model={model}
prefixHash={prefixHash}
harvestOn={harvestOn}
branchOn={branchOn}
branchBudget={branchBudget ?? 1}
reasoningEffort={reasoningEffort}
<Box flexDirection="column" paddingX={1}>
<ChromeRow
editMode={editMode}
planMode={planMode}
turns={summary.turns}
proArmed={proArmed ?? false}
escalated={escalated ?? false}
summary={summary}
coldStart={coldStart}
rootDir={rootDir}
sessionName={sessionName ?? null}
updateAvailable={updateAvailable}
narrow={narrow}
busy={busy ?? false}
balance={balance ?? 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>
);
}
function Header({
model,
prefixHash,
harvestOn,
branchOn,
branchBudget,
reasoningEffort,
planMode,
turns,
updateAvailable,
narrow,
busy,
}: {
model: string;
prefixHash: string;
harvestOn?: boolean;
branchOn: boolean;
branchBudget: number;
reasoningEffort?: "high" | "max";
planMode?: boolean;
turns: number;
updateAvailable?: string | null;
narrow: boolean;
busy: boolean;
}) {
return (
<Box justifyContent="space-between">
<Box>
<Wordmark busy={busy} />
<Text dimColor>{` v${VERSION}`}</Text>
<Text dimColor> · </Text>
<Text color="yellow">{model}</Text>
{narrow ? null : (
<>
<Text dimColor> · </Text>
<Text dimColor>{prefixHash}</Text>
</>
)}
{harvestOn ? <Text color="magenta"> · harvest</Text> : null}
{branchOn ? <Text color="blue"> · branch{branchBudget}</Text> : null}
{reasoningEffort === "max" ? <Text color="green"> · max</Text> : null}
{reasoningEffort === "high" ? <Text color="yellow"> · high</Text> : null}
{planMode ? (
<Text color="red" bold>
{" · PLAN"}
</Text>
) : null}
</Box>
<Text>
{updateAvailable ? (
<Text color="yellow" bold>{`update: ${updateAvailable} · `}</Text>
) : null}
<Text dimColor>{narrow ? `turn ${turns}` : `turn ${turns} · /help`}</Text>
</Text>
</Box>
);
}
/**
* 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 dimColor>ctx </Text>
<Text dimColor>— (no turns yet)</Text>
</Text>
);
}
const color = ratio >= 0.8 ? "red" : ratio >= 0.6 ? "yellow" : "green";
const pct = Math.round(ratio * 100);
return (
<Text>
<Text dimColor>ctx </Text>
{showBar ? <Bar ratio={ratio} color={color} /> : null}
{showBar ? <Text> </Text> : null}
<Text color={color} bold>
{formatTokens(promptTokens)}/{formatTokens(ctxMax)}
</Text>
<Text dimColor> ({pct}%)</Text>
{ratio >= 0.8 ? (
<Text color="red" bold>
{" · /compact"}
</Text>
<ChromeRule />
{budgetUsd !== null && budgetUsd !== undefined ? (
<BudgetRow spent={summary.totalCostUsd} cap={budgetUsd} />
) : null}
</Text>
</Box>
);
}
function CacheCell({
hitRatio,
coldStart,
turns,
}: {
hitRatio: number;
coldStart: boolean;
turns: number;
}) {
const pct = (hitRatio * 100).toFixed(1);
if (turns === 0) {
return (
<Text>
<Text dimColor>cache </Text>
<Text dimColor>—</Text>
</Text>
);
}
if (coldStart) {
return (
<Text>
<Text dimColor>cache </Text>
<Text dimColor>{pct}% </Text>
<Text dimColor italic>
(cold start)
</Text>
</Text>
);
}
const color = hitRatio >= 0.7 ? "green" : hitRatio >= 0.4 ? "yellow" : "red";
return (
<Text>
<Text dimColor>cache </Text>
<Text color={color} bold>
{pct}%
</Text>
</Text>
);
}
function CostCell({
function ChromeRow({
editMode,
planMode,
proArmed,
escalated,
summary,
coldStart,
rootDir,
sessionName,
updateAvailable,
balance,
}: {
editMode?: EditMode;
planMode?: boolean;
proArmed: boolean;
escalated: boolean;
summary: SessionSummary;
coldStart: boolean;
rootDir?: string;
sessionName?: string | null;
updateAvailable?: string | null;
balance?: { currency: string; total: number } | null;
}) {
if (summary.turns === 0) {
return (
<Text>
<Text 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 primaryColor = coldStart ? undefined : "green";
const modePill = pickModePill(planMode, editMode);
const proPill = escalated
? { label: "⇧ pro", color: COLOR.err }
: proArmed
? { label: "⇧ pro", color: COLOR.warn }
: null;
const projectName = rootDir ? basename(rootDir) : null;
const cachePct = Math.round(summary.cacheHitRatio * 100);
const cacheColor =
summary.cacheHitRatio >= 0.7 ? COLOR.ok : summary.cacheHitRatio >= 0.4 ? COLOR.warn : COLOR.err;
const balanceLabel = balance
? `[w ${balance.currency === "USD" ? "$" : ""}${balance.total.toFixed(2)}${balance.currency !== "USD" ? ` ${balance.currency}` : ""}]`
: "";
const costLabel = `[$${summary.totalCostUsd.toFixed(4)}]`;
const cacheLabel = "[c ▰▰▰▰▰▰ 100%]";
const updateLabel = updateAvailable ? `↑ ${updateAvailable}` : "";
// Greedy width-aware fit. Layout (every gap = 2 cells, applied as suffix
// to update/mode/pro and as prefix to balance/cache):
// [brand][·project][›session]<spacer>[update][mode][pro][cost][balance][cache]
// Always shown: brand, project (if rootDir), mode (if set), pro (if armed),
// cost. These carve fixedLeft / fixedRight first.
// Optional, dropped greedy by priority: balance > cache > session > update.
// The flexbox spacer can shrink to 0, so no minimum reserve.
const { stdout } = useStdout();
const cols = (stdout?.columns ?? 80) - 2; // subtract paddingX={1} on both sides
const SEP_DOT = stringWidth(" · ");
const SEP_ARROW = stringWidth(" › ");
const GAP = 2;
const fixedLeft =
stringWidth("◈ reasonix") + (projectName ? SEP_DOT + stringWidth(projectName) : 0);
const modeW = modePill ? GAP + stringWidth(`[${modePill.label}]`) : 0;
const proW = proPill ? GAP + stringWidth(`[${proPill.label}]`) : 0;
const fixedRight = modeW + proW + stringWidth(costLabel);
let budget = cols - fixedLeft - fixedRight;
const balW = balance ? GAP + stringWidth(balanceLabel) : 0;
const cacheW = GAP + stringWidth(cacheLabel);
const sessionW = sessionName ? SEP_ARROW + stringWidth(sessionName) : 0;
const updateW = updateLabel ? GAP + stringWidth(updateLabel) : 0;
const showBalance = balW > 0 && budget >= balW;
if (showBalance) budget -= balW;
const showCache = budget >= cacheW;
if (showCache) budget -= cacheW;
const showSession = sessionW > 0 && budget >= sessionW;
if (showSession) budget -= sessionW;
const showUpdate = updateW > 0 && budget >= updateW;
if (showUpdate) budget -= updateW;
return (
<Text>
<Text dimColor>cost </Text>
<Text color={primaryColor} bold={!coldStart} dimColor={coldStart}>
${summary.totalCostUsd.toFixed(6)}
<Box>
<Text bold color={GRADIENT[0]}>
{"◈ "}
</Text>
<Text dimColor>
{" (in "}${summary.totalInputCostUsd.toFixed(6)}
{" · out "}${summary.totalOutputCostUsd.toFixed(6)}
{")"}
<Text color={COLOR.brand} bold>
reasonix
</Text>
</Text>
{projectName ? (
<>
<Text color={COLOR.info} dimColor>
{" · "}
</Text>
<Text>{projectName}</Text>
{showSession && sessionName ? (
<>
<Text color={COLOR.info} dimColor>
{" › "}
</Text>
<Text color={COLOR.info}>{sessionName}</Text>
</>
) : null}
</>
) : null}
<Box flexGrow={1} />
{showUpdate ? (
<>
<Text color={COLOR.warn} bold>
{updateLabel}
</Text>
<Text>{" "}</Text>
</>
) : null}
{modePill ? (
<>
<Text color={modePill.color} bold>
{`[${modePill.label}]`}
</Text>
<Text>{" "}</Text>
</>
) : null}
{proPill ? (
<>
<Text color={proPill.color} bold>
{`[${proPill.label}]`}
</Text>
<Text>{" "}</Text>
</>
) : null}
<Text
color={
summary.turns === 0 || coldStart ? COLOR.info : sessionCostColor(summary.totalCostUsd)
}
bold={summary.turns > 0 && !coldStart}
dimColor={summary.turns === 0 || coldStart}
>
{costLabel}
</Text>
{showBalance && balance ? (
<>
<Text>{" "}</Text>
<Text color={balance.total < 1 ? COLOR.err : balance.total < 5 ? COLOR.warn : COLOR.ok}>
{balanceLabel}
</Text>
</>
) : null}
{showCache ? (
<>
<Text>{" "}</Text>
<Text dimColor>{"["}</Text>
<Text dimColor>{"c "}</Text>
<Bar
ratio={summary.cacheHitRatio}
color={coldStart ? COLOR.info : cacheColor}
cells={6}
dim={coldStart}
/>
<Text> </Text>
<Text color={coldStart ? undefined : cacheColor} dimColor={coldStart}>
{coldStart && summary.turns === 0 ? "—" : `${cachePct}%`}
</Text>
<Text dimColor>{"]"}</Text>
</>
) : null}
</Box>
);
}
function BalanceCell({ balance }: { balance: { currency: string; total: number } }) {
const color = balance.total < 1 ? "red" : balance.total < 5 ? "yellow" : "green";
function pickModePill(
planMode: boolean | undefined,
editMode: EditMode | undefined,
): { label: string; color: string } | null {
if (planMode) return { label: "PLAN", color: COLOR.err };
if (editMode === "yolo") return { label: "yolo", color: COLOR.err };
if (editMode === "auto") return { label: "auto", color: COLOR.primary };
if (editMode === "review") return { label: "review", color: COLOR.info };
return null;
}
function BudgetRow({ spent, cap }: { spent: number; cap: number }) {
const pct = Math.max(0, (spent / cap) * 100);
const color = pct >= 100 ? "#f87171" : pct >= 80 ? "#fbbf24" : "#94a3b8";
return (
<Text>
<Text dimColor>balance </Text>
<Text color={color} bold>
{balance.currency === "USD" ? "$" : ""}
{balance.total.toFixed(2)}
{balance.currency !== "USD" ? ` ${balance.currency}` : ""}
<Box>
<Text dimColor>{" budget "}</Text>
<Text color={color}>
{`$${spent.toFixed(4)} / $${cap.toFixed(2)}`}
<Text dimColor>{` (${pct.toFixed(0)}%)`}</Text>
</Text>
</Text>
</Box>
);
}
/**
* Unicode progress bar for the narrow layout's context cell. 10 cells
* wide — narrow terminals are already cramped, and the bar is just a
* visual cue for the percentage next to it, not the primary readout.
*/
function Bar({ ratio, color }: { ratio: number; color: "green" | "yellow" | "red" }) {
const cells = 10;
const filled = Math.max(0, Math.min(cells, Math.round(ratio * cells)));
const bar = "█".repeat(filled) + "░".repeat(cells - filled);
return <Text color={color}>{bar}</Text>;
}
/**
* 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 < 1024) return String(n);
const k = n / 1024;
return k >= 100 ? `${k.toFixed(0)}K` : `${k.toFixed(1)}K`;
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;
}
+165
View File
@@ -0,0 +1,165 @@
/**
* Welcome card on the empty session. The FIRST thing every user sees
* after launching `reasonix code` — must communicate brand identity,
* what to type next, and how to escape, all in the ~5 seconds before
* the user starts typing.
*
* Layout (matches design/tui-redesign-ink.html welcome state):
*
* ◈ R E A S O N I X
*
* DeepSeek-native coding agent · cache-first · flash-first
*
* /skill invoke a stored playbook by name
* @file inline a file's contents in your message
* /checkpoint snapshot the workspace before a risky turn
* /help every slash command + keyboard shortcut
*
* tip · ctrl+j newline · trailing \ continues
*
* Why the redesign: the previous version was a left-aligned hint list
* with a tiny `◈ welcome` row — functional but invisible as brand. The
* gradient wordmark is the one chance per launch to plant identity, so
* we make it large + centered + colored across all 8 brand-gradient
* stops. The tagline below answers "what is this?" in one line. Cards
* answer "what do I type?" — the only three things a new user actually
* needs to know in the first 5 seconds.
*
* Why no animation: an animated gradient pan was tried, but Ink's
* eraseLines miscounts on resize when wide rows reflow, leaving
* stale frames stacked. Static gradient renders identically and
* costs zero ticker subscriptions.
*/
import { Box, Text, useStdout } from "ink";
import React from "react";
import { COLOR, GRADIENT } from "./theme.js";
export interface WelcomeBannerProps {
/** True when running `reasonix code`. Surfaces code-mode hints. */
inCodeMode?: boolean;
/**
* Live URL of the embedded dashboard, or null when it isn't running.
* Surfacing this in the welcome card is how users discover the web UI
* — the chrome pill version was unreliable across terminals, so the
* card became the canonical pointer.
*/
dashboardUrl?: string | null;
}
const WORDMARK = "REASONIX";
const TAGLINE_CHAT = "DeepSeek-native agent · cache-first · flash-first";
const TAGLINE_CODE = "DeepSeek-native coding agent · cache-first · flash-first";
interface QuickCard {
cmd: string;
desc: string;
}
const CARDS_CHAT: QuickCard[] = [
{ cmd: "/help", desc: "every slash command + keyboard shortcut" },
{ cmd: "/skill", desc: "invoke a stored playbook by name" },
{ cmd: "/dashboard", desc: "open the embedded web UI (chat · stats · settings)" },
{ cmd: "/preset pro", desc: "switch to v4-pro for hard reasoning tasks" },
{ cmd: "/exit", desc: "quit the TUI (Ctrl+C twice also works)" },
];
const CARDS_CODE: QuickCard[] = [
{ cmd: "@file", desc: "inline a file's contents in your message" },
{ cmd: "!cmd", desc: "run shell — output is captured for context" },
{ cmd: "/checkpoint", desc: "snapshot the workspace before a risky turn" },
{ cmd: "/dashboard", desc: "open the embedded web UI (chat · files · stats · settings)" },
{ cmd: "/help", desc: "every slash command + keyboard shortcut" },
];
export function WelcomeBanner({
inCodeMode,
dashboardUrl,
}: WelcomeBannerProps): React.ReactElement {
const { stdout } = useStdout();
const cols = stdout?.columns ?? 80;
// Wordmark width: each letter + space between letters. With letter-
// spacing of 1 cell, "R E A S O N I X" is 8*2-1 = 15 cells, plus the
// brand mark "◈ " = 2 cells, total 17 cells. We center on the term
// width, capped to a sane minimum so very narrow terminals don't
// produce negative pad.
const wordmarkText = `◈ ${WORDMARK.split("").join(" ")}`;
const wordmarkWidth = wordmarkText.length;
const tagline = inCodeMode ? TAGLINE_CODE : TAGLINE_CHAT;
const cards = inCodeMode ? CARDS_CODE : CARDS_CHAT;
// Center column 1: pad-left to put wordmark at terminal center
const wordmarkPad = Math.max(0, Math.floor((cols - wordmarkWidth) / 2));
const taglinePad = Math.max(0, Math.floor((cols - tagline.length) / 2));
// Cards left-margin: align to a comfortable indent rather than
// center each row (keeps the cmd column aligned).
const cardsIndent = Math.max(2, Math.floor((cols - 60) / 2));
const tipText = "tip · ctrl+j newline · trailing \\ also continues";
const tipPad = Math.max(0, Math.floor((cols - tipText.length) / 2));
return (
<Box flexDirection="column" marginY={1}>
{/* Wordmark — gradient across the 8 letters of REASONIX. The
brand mark `◈` sits in the brand teal as the first stop, then
each letter steps through the gradient. Bold throughout for
weight; spacing keeps it from reading as a single dense word. */}
<Box>
<Text>{" ".repeat(wordmarkPad)}</Text>
<Text bold color={GRADIENT[0]}>
{"◈ "}
</Text>
{WORDMARK.split("").map((letter, i) => (
// Wordmark is fixed-string ("REASONIX") — letters are unique
// and the array never reorders, so per-letter key is stable.
<React.Fragment key={letter}>
<Text bold color={GRADIENT[i % GRADIENT.length]}>
{letter}
</Text>
{i < WORDMARK.length - 1 ? <Text> </Text> : null}
</React.Fragment>
))}
</Box>
<Box marginTop={1}>
<Text>{" ".repeat(taglinePad)}</Text>
<Text color={COLOR.info}>{tagline}</Text>
</Box>
{/* Quick-start cards — cmd token in accent violet, desc dim.
Aligned in two columns so the eye can scan command names
without having to read each desc. */}
<Box flexDirection="column" marginTop={2}>
{cards.map((card) => (
<Box key={card.cmd}>
<Text>{" ".repeat(cardsIndent)}</Text>
<Text bold color={COLOR.accent}>
{card.cmd.padEnd(14)}
</Text>
<Text color={COLOR.info}>{card.desc}</Text>
</Box>
))}
</Box>
{/* Live dashboard URL — printed once, centered, when the embedded
server is up. This is the canonical pointer to the web UI; the
chrome pill version was unreliable across terminals so we
surface the URL here (one-shot at launch) and let the user
re-fetch via `/dashboard` whenever the welcome card has
scrolled away. */}
{dashboardUrl ? (
<Box marginTop={2}>
<Text>{" ".repeat(Math.max(0, Math.floor((cols - (dashboardUrl.length + 9)) / 2)))}</Text>
<Text color={COLOR.brand} bold>
{"▸ web · "}
</Text>
<Text color={COLOR.accent}>{dashboardUrl}</Text>
</Box>
) : null}
<Box marginTop={dashboardUrl ? 1 : 2}>
<Text>{" ".repeat(tipPad)}</Text>
<Text dimColor>{tipText}</Text>
</Box>
</Box>
);
}
+7 -7
View File
@@ -59,7 +59,7 @@ export function Wizard({ onComplete, onCancel, existingApiKey, initial }: Wizard
const [step, setStep] = useState<Step>(existingApiKey ? "preset" : "apiKey");
const [data, setData] = useState<WizardData>({
apiKey: existingApiKey ?? "",
preset: initial?.preset ?? "fast",
preset: initial?.preset ?? "auto",
selectedCatalog: deriveInitialCatalog(initial?.mcp ?? []),
catalogArgs: {},
});
@@ -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>
@@ -386,8 +386,8 @@ function SummaryLine({ label, value }: { label: string; value: string }) {
// ---------- data helpers ----------
function presetItems(): SelectItem<PresetName>[] {
return (["fast", "smart", "max"] as PresetName[]).map((name) => ({
value: name,
return (["auto", "flash", "pro"] as const).map((name) => ({
value: name as PresetName,
label: `${name} — ${PRESET_DESCRIPTIONS[name].headline}`,
hint: PRESET_DESCRIPTIONS[name].cost,
}));
+73
View File
@@ -0,0 +1,73 @@
import { Box, Text } from "ink";
import React from "react";
import { ModalCard } from "./ModalCard.js";
import { SingleSelect } from "./Select.js";
import { COLOR } from "./theme.js";
export type WorkspaceConfirmChoice = "switch" | "deny";
export interface WorkspaceConfirmProps {
/** Resolved absolute path the model wants to switch to. */
path: string;
/** Current session root, shown above the target so the user sees the diff. */
currentRoot: string;
/** Number of MCP servers still attached — surfaced so the user knows
* those won't follow the switch (their child processes were spawned
* with the original cwd). 0 means no warning. */
mcpServerCount: number;
onChoose: (choice: WorkspaceConfirmChoice, denyContext?: string) => void;
}
/**
* Modal-style approval for a `change_workspace` tool call. Two
* choices, Enter / Esc bindings. No "always allow" — workspace
* switches are per-target by nature. Tab on Deny opens inline
* context entry, returned as `onChoose`'s 2nd arg.
*/
export function WorkspaceConfirm({
path,
currentRoot,
mcpServerCount,
onChoose,
}: WorkspaceConfirmProps) {
const subtitle =
mcpServerCount > 0
? `MCP servers (${mcpServerCount}) stay anchored to the original launch root.`
: "Re-registers filesystem / shell / memory tools at the new path.";
return (
<ModalCard accent={COLOR.warn} icon="⇄" title="switch workspace" subtitle={subtitle}>
<Box flexDirection="column" marginBottom={1}>
<Box>
<Text dimColor>{"from "}</Text>
<Text color={COLOR.info}>{currentRoot}</Text>
</Box>
<Box>
<Text dimColor>{"to "}</Text>
<Text color={COLOR.primary} bold>
{path}
</Text>
</Box>
</Box>
<SingleSelect
initialValue="switch"
items={[
{
value: "switch",
label: "Switch",
hint: "Re-register filesystem / shell / memory tools against the new root.",
},
{
value: "deny",
label: "Deny",
hint: "Tell the model why you're refusing; it will continue without changing directories.",
denyWithContext: true,
},
]}
onSubmit={(v, ctx) => onChoose(v as WorkspaceConfirmChoice, ctx)}
onCancel={() => onChoose("deny")}
footer="[↑↓] navigate · [Enter] select · [Tab] add context · [Esc] deny"
/>
</ModalCard>
);
}
+39
View File
@@ -0,0 +1,39 @@
/** Alt-screen lifecycle — restore must be idempotent and run on SIGINT/SIGTERM/exit so the user's main buffer always comes back. */
import { useEffect } from "react";
function isInteractiveTty(): boolean {
return Boolean(process.stdout?.isTTY);
}
export function useAltScreen(): void {
useEffect(() => {
if (!isInteractiveTty()) return;
// 1002 = button-event tracking (press + drag + release); 1006 = SGR coords.
// Shift+drag bypasses tracking for native terminal selection.
process.stdout.write("\x1b[?1049h\x1b[2J\x1b[H\x1b[?1002h\x1b[?1006h");
let restored = false;
const restore = () => {
if (restored) return;
restored = true;
try {
process.stdout.write("\x1b[?1006l\x1b[?1002l\x1b[?1000l\x1b[?1049l");
} catch {
/* terminal closed */
}
};
process.once("exit", restore);
process.once("SIGINT", () => {
restore();
process.exit(130);
});
process.once("SIGTERM", () => {
restore();
process.exit(143);
});
return restore;
}, []);
}
+1 -28
View File
@@ -1,25 +1,5 @@
/**
* 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.
*/
/** User-typed `!cmd` skips the allowlist — that gate is for the MODEL, not the user. */
/**
* 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();
@@ -27,13 +7,6 @@ export function detectBangCommand(text: string): string | 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}`;
}
+118
View File
@@ -0,0 +1,118 @@
/**
* Character-cell progress bar — the visual primitive shared across:
* · cache hit ratio in the status bar
* · undo banner countdown
* · /context token-usage breakdown (stacked variant)
* · plan step progress
* · MCP progress notifications
* · walk-through "block N of M" position
*
* Why one helper: in a TUI you can only convey "fraction" by character
* fill, not by gradient bg. Doing it ad-hoc per call site led to five
* subtly different bar styles (some used `█/░`, some `■/-`, some
* inverted bg). Centralizing here means the visual cue is one
* consistent thing the user reads at-a-glance everywhere.
*
* All variants render in 1 row, 1 cell tall. Width defaults to 24
* which is wide enough for "10% increments are visible to the eye"
* but narrow enough to fit beside other status info.
*/
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 { COLOR, GLYPH } from "./theme.js";
export interface CharBarProps {
/** 0–100 (clamped). Negative or NaN → 0; >100 → 100. */
pct: number;
/** Cell count. Default 24. Min 4 enforced so the bar is at least readable. */
width?: number;
/** Filled-cell color. Defaults to brand cyan. */
color?: string;
/** Empty-cell color. Defaults to dim slate. */
emptyColor?: string;
/**
* Whether to render the percentage label after the bar. Off when the
* caller wants to put its own meta after (e.g. "12 of 30 done").
*/
showLabel?: boolean;
/** Optional label override (default: "{pct}%"). */
label?: string;
}
/**
* Single-color progress bar. Render shape:
* `████████████░░░░░░░░░░░░ 50%`
*
* Filled section is `█` in `color`, empty section is `░` in
* `emptyColor`. Label sits in the same row, dim by default.
*/
export function CharBar({
pct,
width = 24,
color = COLOR.primary,
emptyColor,
showLabel = true,
label,
}: CharBarProps): React.ReactElement {
const total = Math.max(4, width);
const clamped = Math.max(0, Math.min(100, Number.isFinite(pct) ? pct : 0));
const filled = Math.round((total * clamped) / 100);
return (
<Box>
<Text color={color}>{GLYPH.block.repeat(filled)}</Text>
<Text color={emptyColor ?? COLOR.info} dimColor>
{GLYPH.shade1.repeat(total - filled)}
</Text>
{showLabel ? <Text dimColor>{` ${label ?? `${Math.round(clamped)}%`}`}</Text> : null}
</Box>
);
}
export interface StackedSegment {
/** Percent of the total width this segment occupies. 0–100. */
pct: number;
color: string;
/** Optional label (used by legend renderer; not rendered in the bar). */
label?: string;
}
export interface StackedCharBarProps {
segments: readonly StackedSegment[];
width?: number;
/** Color of the trailing "free / unused" cells. */
emptyColor?: string;
}
/**
* Stacked progress bar. Multiple colored segments + a trailing empty
* region. Rendered left-to-right in segment order; if the segments'
* pcts sum >100 the trailing empty just becomes 0.
*
* Used by `/context` to break down system / tools / log / input
* occupancy across the prompt budget.
*/
export function StackedCharBar({
segments,
width = 32,
emptyColor,
}: StackedCharBarProps): React.ReactElement {
const total = Math.max(4, width);
const cells = segments.map((s) => Math.max(0, Math.round((total * s.pct) / 100)));
const used = cells.reduce((acc, n) => acc + n, 0);
const empty = Math.max(0, total - used);
return (
<Box>
{segments.map((seg, i) => (
// biome-ignore lint/suspicious/noArrayIndexKey: ordered, fixed-shape
<Text key={`seg-${i}`} color={seg.color}>
{GLYPH.block.repeat(cells[i] ?? 0)}
</Text>
))}
<Text color={emptyColor ?? COLOR.info} dimColor>
{GLYPH.shade1.repeat(empty)}
</Text>
</Box>
);
}
+31
View File
@@ -0,0 +1,31 @@
/** OSC 52 clipboard write + temp-file fallback. */
import { writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
const OSC_52_LIMIT = 75_000;
export interface ClipboardWrite {
osc52: boolean;
filePath: string | null;
size: number;
}
export function writeClipboard(text: string): ClipboardWrite {
const filePath = join(tmpdir(), `reasonix-clip-${Date.now()}.txt`);
let osc52 = false;
if (text.length <= OSC_52_LIMIT) {
const b64 = Buffer.from(text, "utf8").toString("base64");
process.stdout.write(`\x1b]52;c;${b64}\x1b\\`);
osc52 = true;
}
let writtenPath: string | null = null;
try {
writeFileSync(filePath, text, "utf8");
writtenPath = filePath;
} catch {
/* read-only fs */
}
return { osc52, filePath: writtenPath, size: text.length };
}
+152
View File
@@ -0,0 +1,152 @@
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 { CacheFirstLoop } from "../../loop.js";
import { DEEPSEEK_CONTEXT_TOKENS, DEFAULT_CONTEXT_TOKENS } from "../../telemetry/stats.js";
import { countTokens } from "../../tokenizer.js";
import { formatTokens } from "./primitives.js";
import { COLOR } from "./theme.js";
export interface CtxBreakdownData {
systemTokens: number;
toolsTokens: number;
logTokens: number;
inputTokens: number;
ctxMax: number;
toolsCount: number;
logMessages: number;
topTools: Array<{ name: string; tokens: number; turn: number }>;
}
/**
* Walk the loop's prefix + log and tally tokens per category. Cheap
* after the tokenizer warm-up (~100 ms first call, sub-ms after).
* Memoize at the call site if used inside a render path.
*/
export function computeCtxBreakdown(loop: CacheFirstLoop): CtxBreakdownData {
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 ctxMax = DEEPSEEK_CONTEXT_TOKENS[loop.model] ?? DEFAULT_CONTEXT_TOKENS;
const topTools = [...toolBreakdown].sort((a, b) => b.tokens - a.tokens).slice(0, 5);
return {
systemTokens,
toolsTokens,
logTokens,
inputTokens: 0,
ctxMax,
toolsCount: loop.prefix.toolSpecs.length,
logMessages: entries.length,
topTools,
};
}
/**
* 4-segment stacked bar with legend + top-tools list. Pushed to
* scrollback by the `/context` slash; the always-on bottom footer
* uses its own slim 1-row layout in `CtxFooter`.
*/
export function CtxBreakdownBlock({ data }: { data: CtxBreakdownData }): React.ReactElement {
const total = data.systemTokens + data.toolsTokens + data.logTokens + data.inputTokens;
const winPct = data.ctxMax > 0 ? Math.round((total / data.ctxMax) * 100) : 0;
const barWidth = 48;
const cellOf = (n: number) => (data.ctxMax > 0 ? Math.round((n / data.ctxMax) * barWidth) : 0);
const sysCells = cellOf(data.systemTokens);
const toolsCells = cellOf(data.toolsTokens);
const logCells = cellOf(data.logTokens);
const inputCells = cellOf(data.inputTokens);
const used = sysCells + toolsCells + logCells + inputCells;
const freeCells = Math.max(0, barWidth - used);
const sevColor = winPct >= 80 ? COLOR.err : winPct >= 60 ? COLOR.warn : COLOR.ok;
return (
<Box
flexDirection="column"
marginY={1}
borderStyle="single"
borderTop={false}
borderRight={false}
borderBottom={false}
borderColor={COLOR.brand}
paddingLeft={1}
>
<Box>
<Text color={COLOR.brand} bold>
▣ context
</Text>
<Text dimColor>{` ${formatTokens(total)} of ${formatTokens(data.ctxMax)}`}</Text>
<Text dimColor>{" · "}</Text>
<Text color={sevColor} bold>
{`${winPct}%`}
</Text>
{winPct >= 80 ? (
<Text color={COLOR.err} bold>
{" · /compact"}
</Text>
) : null}
</Box>
<Box>
<Text color={COLOR.brand}>{"█".repeat(sysCells)}</Text>
<Text color={COLOR.accent}>{"█".repeat(toolsCells)}</Text>
<Text color={COLOR.primary}>{"█".repeat(logCells)}</Text>
<Text color={COLOR.tool}>{"█".repeat(inputCells)}</Text>
<Text color={COLOR.info} dimColor>
{"░".repeat(freeCells)}
</Text>
</Box>
<Box>
<Text color={COLOR.brand}>■</Text>
<Text dimColor>{` system ${formatTokens(data.systemTokens)}`}</Text>
<Text>{" "}</Text>
<Text color={COLOR.accent}>■</Text>
<Text dimColor>{` tools ${formatTokens(data.toolsTokens)}`}</Text>
<Text dimColor>{` (${data.toolsCount})`}</Text>
<Text>{" "}</Text>
<Text color={COLOR.primary}>■</Text>
<Text dimColor>{` log ${formatTokens(data.logTokens)}`}</Text>
<Text dimColor>{` (${data.logMessages} msg)`}</Text>
<Text>{" "}</Text>
<Text color={COLOR.tool}>■</Text>
<Text dimColor>{` input ${formatTokens(data.inputTokens)}`}</Text>
</Box>
{data.topTools.length > 0 ? (
<Box marginTop={1} flexDirection="column">
<Text dimColor>{` top tool results by cost (${data.topTools.length}):`}</Text>
{data.topTools.map((t) => (
<Box key={`${t.turn}-${t.name}`}>
<Text dimColor>{` turn ${String(t.turn).padStart(3)} `}</Text>
<Text color={COLOR.info}>{t.name.padEnd(22)}</Text>
<Text dimColor>{` ${formatTokens(t.tokens).padStart(8)}`}</Text>
</Box>
))}
</Box>
) : null}
<Box marginTop={1}>
<Text dimColor>{" /compact shrinks oversized tool results · /new wipes log"}</Text>
</Box>
</Box>
);
}
+121
View File
@@ -0,0 +1,121 @@
import { formatAllBlockDiffs } from "../../code/diff-preview.js";
import type { ApplyResult, EditBlock, EditSnapshot } from "../../code/edit-blocks.js";
/** Session-only — restoring pre-apply content across restarts 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;
/** Tag for what produced the batch — "auto" / "auto-text" / "review-apply". */
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 — multi-edit turns roll back to pre-turn state. */
snapshots: EditSnapshot[];
/** Per-path so a multi-file batch can be partially undone. */
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";
}
/** Status prefix is `✓`/`✗` so the line reads without color (piped, screenshots). */
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");
}
/** `[N]` labels so users can `/apply 1,3-4` instead of all-or-nothing. */
export function formatPendingPreview(blocks: EditBlock[]): string {
const partial = blocks.length > 1 ? " · /apply N or 1,3-4 for partial" : "";
const header = `▸ ${blocks.length} pending edit block(s) — /apply (or y) to commit · /discard (or n) to drop${partial}`;
const diffLines = formatAllBlockDiffs(blocks, { numbered: blocks.length > 1 });
return [header, ...diffLines].join("\n");
}
/** Empty input → `{ ok: [] }` so callers detect "no indices" → default to all-blocks. */
export function parseEditIndices(raw: string, max: number): { ok: number[] } | { error: string } {
const trimmed = raw.trim();
if (!trimmed) return { ok: [] };
if (max <= 0) return { error: "no pending edits to address" };
const seen = new Set<number>();
const tokens = trimmed
.split(",")
.map((t) => t.trim())
.filter((t) => t.length > 0);
if (tokens.length === 0) return { ok: [] };
for (const tok of tokens) {
const range = tok.match(/^(\d+)-(\d+)$/);
if (range) {
const a = Number.parseInt(range[1] ?? "", 10);
const b = Number.parseInt(range[2] ?? "", 10);
if (!Number.isFinite(a) || !Number.isFinite(b) || a < 1 || b < 1) {
return { error: `invalid range: "${tok}"` };
}
const lo = Math.min(a, b);
const hi = Math.max(a, b);
if (hi > max) return { error: `index ${hi} out of range (max ${max})` };
for (let i = lo; i <= hi; i++) seen.add(i);
continue;
}
if (!/^\d+$/.test(tok)) return { error: `invalid index: "${tok}"` };
const n = Number.parseInt(tok, 10);
if (!Number.isFinite(n) || n < 1) return { error: `invalid index: "${tok}"` };
if (n > max) return { error: `index ${n} out of range (max ${max})` };
seen.add(n);
}
return { ok: [...seen].sort((a, b) => a - b) };
}
export function partitionEdits<T>(
edits: readonly T[],
indices1Based: readonly number[],
): { selected: T[]; remaining: T[] } {
const picked = new Set(indices1Based);
const selected: T[] = [];
const remaining: T[] = [];
for (let i = 0; i < edits.length; i++) {
if (picked.has(i + 1)) selected.push(edits[i] as T);
else remaining.push(edits[i] as T);
}
return { selected, remaining };
}
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(", ")}` : "";
}
+18
View File
@@ -0,0 +1,18 @@
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 Frame, frameToAnsi } from "../../frame/index.js";
/** Frame → JSX. One Box per row. */
export function renderFrame(f: Frame, keyPrefix: string): React.ReactElement {
return (
<>
{f.rows.map((row, i) => (
// biome-ignore lint/suspicious/noArrayIndexKey: row index is the row's identity
<Box key={`${keyPrefix}/${i}`} height={1} flexShrink={0}>
<Text>{frameToAnsi({ width: f.width, rows: [row] })}</Text>
</Box>
))}
</>
);
}
+96
View File
@@ -0,0 +1,96 @@
/** `#` writes project memory, `#g` global; `##+` stays a markdown heading; `\#` escapes and submits the literal `#`. */
import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join } from "node:path";
import { PROJECT_MEMORY_FILE } from "../../memory/project.js";
const PROJECT_HEADER = `# Reasonix project memory
Notes the user pinned via the \`#\` prompt prefix. The whole file is
loaded into the immutable system prefix every session — keep it terse.
`;
const GLOBAL_HEADER = `# Reasonix global memory
Cross-project notes the user pinned via the \`#g\` prompt prefix. Loaded
into every Reasonix session's prefix regardless of working directory.
Private to this machine — not committed anywhere.
`;
export type HashMemoryParse =
| { kind: "memory"; note: string }
| { kind: "memory-global"; note: string }
| { kind: "escape"; text: string };
/** Order: escape > `##` heading > `#g <body>` (mandatory space) > `#<body>` project. */
export function detectHashMemory(text: string): HashMemoryParse | null {
if (text.startsWith("\\#")) {
return { kind: "escape", text: text.slice(1) };
}
if (!text.startsWith("#")) return null;
// Markdown headings of level 2+ pass through to the model unchanged.
// Only a single leading `#` (level-1 heading shape) is ambiguous; we
// resolve that ambiguity in favor of memory write and document the
// `\#` escape for users who want a literal H1 in the prompt.
if (text.startsWith("##")) return null;
// `#g <note>` — global memory. The space after `g` is mandatory so
// notes like `#golang preference` route to project memory, not global.
// `#g` alone (or `#g` + only whitespace) is treated as null — the
// user clearly wanted the global form but typed no body, so we don't
// silently fall back to project memory with body=`g`.
if (/^#g\s*$/.test(text)) return null;
const globalMatch = /^#g\s+(.+)$/s.exec(text);
if (globalMatch) {
const body = globalMatch[1]!.trim();
if (!body) return null;
return { kind: "memory-global", note: body };
}
const body = text.slice(1).trim();
if (!body) return null;
return { kind: "memory", note: body };
}
export interface AppendMemoryResult {
/** Absolute path written to. */
path: string;
/** True iff the file did not exist before this call. */
created: boolean;
}
export function appendProjectMemory(rootDir: string, note: string): AppendMemoryResult {
return appendBulletToFile(join(rootDir, PROJECT_MEMORY_FILE), note, PROJECT_HEADER);
}
export const GLOBAL_MEMORY_DIR = ".reasonix";
export const GLOBAL_MEMORY_FILE = "REASONIX.md";
export function globalMemoryPath(homeDir: string = homedir()): string {
return join(homeDir, GLOBAL_MEMORY_DIR, GLOBAL_MEMORY_FILE);
}
export function appendGlobalMemory(note: string, homeDir?: string): AppendMemoryResult {
return appendBulletToFile(globalMemoryPath(homeDir), note, GLOBAL_HEADER);
}
function appendBulletToFile(path: string, note: string, newFileHeader: string): AppendMemoryResult {
const trimmed = note.trim();
if (!trimmed) throw new Error("note body cannot be empty");
const bullet = `- ${trimmed}\n`;
if (!existsSync(path)) {
mkdirSync(dirname(path), { recursive: true });
writeFileSync(path, `${newFileHeader}${bullet}`, "utf8");
return { path, created: true };
}
let prefix = "";
try {
const existing = readFileSync(path, "utf8");
if (existing.length > 0 && !existing.endsWith("\n")) prefix = "\n";
} catch {
// Unreadable but exists — let appendFileSync surface the real error.
}
appendFileSync(path, `${prefix}${bullet}`, "utf8");
return { path, created: false };
}
+73
View File
@@ -0,0 +1,73 @@
/** CSI tail recovery for Ink useInput — Windows ConPTY splits `\x1b[A` across reads; we re-merge. */
/** Only rewrites when no structured key flag is set AND input matches a known tail exactly. */
/** Structured-flag subset of Ink's Key — optional across Ink versions. */
export interface CsiKeyFlags {
upArrow?: boolean;
downArrow?: boolean;
leftArrow?: boolean;
rightArrow?: boolean;
pageUp?: boolean;
pageDown?: boolean;
delete?: boolean;
shift?: boolean;
tab?: boolean;
}
/** Bracketed-paste `[200~`/`[201~` excluded — handled by PromptInput's paste accumulator. */
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 } },
];
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),
);
}
/** Already-structured events short-circuit so a real arrow press isn't 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;
}
/** Includes paste `[200~`/`[201~` for the case where their markers chunked across reads. */
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;
}
+134
View File
@@ -0,0 +1,134 @@
/**
* 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`.
*/
import { useInput } from "ink";
// 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; falls back to Ink's useInput when no KeystrokeProvider is mounted. */
export function useKeystroke(handler: KeystrokeHandler, isActive = true): void {
const bus = useContext(KeystrokeContext);
const handlerRef = useRef(handler);
handlerRef.current = handler;
useEffect(() => {
if (!bus || !isActive) return undefined;
return bus.subscribe((ev) => handlerRef.current(ev));
}, [bus, isActive]);
useInput(
(input, key) => {
if (bus) return;
handlerRef.current({
input,
upArrow: key.upArrow,
downArrow: key.downArrow,
leftArrow: key.leftArrow,
rightArrow: key.rightArrow,
return: key.return,
escape: key.escape,
backspace: key.backspace,
delete: key.delete,
tab: key.tab,
shift: key.shift,
ctrl: key.ctrl,
meta: key.meta,
pageUp: key.pageUp,
pageDown: key.pageDown,
});
},
{ isActive: !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 };
}
File diff suppressed because it is too large. Load diff
+613
View File
@@ -0,0 +1,613 @@
/**
* Row-granular log rendering pipeline. Each `DisplayEvent` is
* decomposed into one or more {@link LogItem}s — either a 1-row
* inline `LogRow` (most chat noise: info / warn / error /
* step-progress) or a multi-row atomic `LogBlock` (complex
* components like plan / ctx-breakdown that we haven't broken
* down yet).
*
* Why this exists: Ink's `overflow="hidden"` does NOT reliably clip
* children with negative `marginTop` — content bleeds upward into
* sibling regions (the chrome pills disappeared at scroll=0 in 0.13.0
* because of exactly this). Clipping IS reliable for positive
* overflow at the BOTTOM of a fixed-height parent. So instead of
* fighting layout, we pre-flatten events into terminal-row units,
* slice the row list, and render the slice as a stack of `<Box
* height={1}>` items. Each item maps 1:1 to a terminal line, the
* parent's overflow=hidden naturally clips overflow at the bottom,
* and `justifyContent="flex-end"` (when at scroll=0) clips overflow
* at the top by the same mechanism.
*
* Migration plan:
* · 0.13.x : info / warn / error / step-progress → rows.
* Everything else falls back to a single `LogBlock`
* wrapping the existing `<EventRow>` component, so
* the pipeline works end-to-end while complex roles
* keep their old rendering.
* · later : user / assistant text bodies → rows (split on \n,
* one row per visual line).
* · later : tool / edit_file diff → rows.
* · later : plan / plan-replay / ctx-breakdown → rows.
*
* The slicer (`sliceLogItems`) treats `LogBlock`s as snap-points:
* a partially-visible block at the viewport's top edge gets either
* fully included or fully excluded, the user briefly "sticks" on
* boundaries when wheel-scrolling through one. Once everything is
* migrated to rows, scrolling is uniformly smooth.
*/
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 DisplayEvent, EventRow } from "./EventLog.js";
import { COLOR } from "./theme.js";
/**
* Greedy character-count wrap. Accurate for ASCII / Latin; CJK
* (where one char ≈ 2 cells) under-counts, but the parent's
* overflow="hidden" still clips the bleed — at worst a visually-
* tight row, not a layout break. Word-aware wrap is a future polish;
* for now we just need the row count to be close enough that the
* slicer's row arithmetic and the scrollbar thumb position aren't
* obviously off.
*/
function wrapToWidth(text: string, width: number): string[] {
if (width <= 0) return [text];
const out: string[] = [];
for (const line of text.split("\n")) {
if (line.length === 0) {
out.push("");
continue;
}
if (line.length <= width) {
out.push(line);
continue;
}
let i = 0;
while (i < line.length) {
out.push(line.slice(i, i + width));
i += width;
}
}
return out;
}
/**
* One terminal line. Always renders inside an outer `<Box height={1}
* flexShrink={0}>` so the slicer's row arithmetic stays exact —
* overlong content soft-wraps in Ink unless we constrain row height,
* which we don't here, but the parent's `overflow="hidden"` clips
* any wrap-induced overflow.
*/
export interface LogRow {
kind: "row";
/** Stable React key. Must be unique within the rendered slice. */
id: string;
content: React.ReactElement;
}
/**
* A multi-row atomic component. Used as the fall-back when an event
* role hasn't been broken down into individual rows yet. The slicer
* snaps to block boundaries — partially-visible blocks at the viewport
* top either render in full or get excluded.
*/
export interface LogBlock {
kind: "block";
id: string;
/** Estimated terminal row count. Used by the slicer for cumulative
* row arithmetic. Over-estimates are safer (reserve more rows
* than needed) than under-estimates (block crowds the viewport
* and content past the bottom clips silently). */
rows: number;
content: React.ReactElement;
}
export type LogItem = LogRow | LogBlock;
/**
* Row count for an item, used by the slicer.
* `LogRow` is always 1; `LogBlock` carries its own estimate.
*/
export function itemRows(item: LogItem): number {
return item.kind === "row" ? 1 : item.rows;
}
/**
* Detect the leading glyph in an info-row text and pick a color tone.
* Mirrors the existing dispatch in `EventLog.tsx` so migrated rows
* look identical to the legacy renderer for the same event payload.
*/
function detectInfoTone(text: string): { lead: string; color: string; body: string } {
const m = text.match(/^([▸▶▲⚠✓✗✖↻ⓘ])\s*(.*)$/s);
const lead = m?.[1] ?? "▸";
const body = m?.[2] ?? text;
let color: string = COLOR.info;
if (lead === "▲" || lead === "⚠") color = COLOR.warn;
else if (lead === "✓") color = COLOR.ok;
else if (lead === "✗" || lead === "✖") color = COLOR.err;
else if (lead === "↻") color = COLOR.primary;
return { lead, color, body };
}
/**
* Render a single accent-bar row. The bar is the left vertical
* border of the wrapper Box; subsequent rows of the same event share
* the bar's color so vertically-adjacent rows visually merge into one
* continuous bar (which is what users read as "this is one log entry").
*
* `prefix` is rendered inline before the line's body; pass `null` for
* continuation lines that should align under the body, not the glyph.
*/
function AccentRow({
color,
prefix,
body,
bodyColor,
bodyDim,
}: {
color: string;
prefix: React.ReactNode | null;
body: string;
bodyColor?: string;
bodyDim?: boolean;
}) {
return (
<Box
borderStyle="single"
borderTop={false}
borderRight={false}
borderBottom={false}
borderColor={color}
paddingLeft={1}
>
{prefix}
<Text color={bodyColor} dimColor={bodyDim}>
{body}
</Text>
</Box>
);
}
/**
* Decompose a plain "accent-bar + glyph + multiline text" event into
* one row per visual line, word-wrapping at `width`. The first line
* carries the glyph; continuation lines align under the body so they
* read as one entry.
*/
function accentRows(
baseId: string,
glyph: string,
glyphColor: string,
text: string,
bodyColor: string | undefined,
bodyDim: boolean,
width: number,
): LogRow[] {
// Reserve cells for the border (1) + paddingLeft (1) + glyph + 2-space
// gap so the wrap width matches the visual content column.
const indentCells = 1 + 1 + glyph.length + 2;
const inner = Math.max(8, width - indentCells);
const lines = wrapToWidth(text, inner);
return lines.map((line, i) => ({
kind: "row" as const,
id: `${baseId}/${i}`,
content:
i === 0 ? (
<AccentRow
color={glyphColor}
prefix={
<>
<Text color={glyphColor} bold>
{glyph}
</Text>
<Text>{" "}</Text>
</>
}
body={line}
bodyColor={bodyColor}
bodyDim={bodyDim}
/>
) : (
<AccentRow
color={glyphColor}
prefix={<Text>{" ".repeat(glyph.length + 2)}</Text>}
body={line}
bodyColor={bodyColor}
bodyDim={bodyDim}
/>
),
}));
}
/**
* Decompose a finished `assistant` event into rows so a long summary
* scrolls one terminal line at a time. Header (glyph + model badge)
* is its own row; body becomes one row per wrapped line under the
* assistant accent bar; stats / repair occupy dedicated trailing rows.
*
* **Fall-through:** events that carry branch / reasoning / non-empty
* planState fall back to the legacy `LogBlock` because those
* sub-components have their own internal layout we haven't row-split
* yet. This keeps every advanced-feature event readable; the dominant
* case (a plain summary turn) gets row-level scrolling.
*
* **Trade-off:** the row body bypasses the markdown renderer, so
* inline formatting (bold / italic / code spans) is rendered as plain
* text. Most assistant prose reads fine without it, and the original
* formatted text is still in `~/.reasonix/sessions/<name>.jsonl`. If
* code-block fidelity matters, users can /transcript or pipe the file
* to `bat`. Worth it for the scrolling win.
*/
function assistantToRows(event: DisplayEvent, projectRoot?: string, width = 80): LogItem[] {
// Skip row migration for events with branch / reasoning / planState —
// those sub-blocks have nested layout we'd lose by flattening, and
// they're uncommon enough that LogBlock fall-back is fine for v1.
const hasComplexSub =
event.branch || event.reasoning || (event.planState && Object.keys(event.planState).length > 0);
if (hasComplexSub) {
return [
{
kind: "block",
id: event.id,
rows: estimatedHeight(event),
content: <EventRow event={event} projectRoot={projectRoot} />,
},
];
}
const items: LogItem[] = [];
// Top spacer matches the legacy renderer's `marginTop={1}`.
items.push({
kind: "row",
id: `${event.id}/spacer-top`,
content: <Text> </Text>,
});
// Header: assistant glyph + (optional) model badge.
items.push({
kind: "row",
id: `${event.id}/head`,
content: (
<Box>
<Text color={COLOR.assistant} bold>
{"◆"}
</Text>
{event.stats ? (
<>
<Text>{" "}</Text>
<Text backgroundColor={COLOR.assistant} color="black" bold>
{` ${event.stats.model.replace(/^deepseek-/, "")} `}
</Text>
</>
) : null}
</Box>
),
});
// Body rows — one per wrapped line, all sharing the assistant
// accent bar on the left so they read as one entry visually even
// though they're independent rows for scroll arithmetic.
const body = event.text || "(empty body — likely tool-call only)";
const dim = !event.text;
items.push(...accentRows(event.id, "", COLOR.assistant, body, COLOR.assistant, dim, width));
// Repair note: single line, accent violet, indented under the body.
if (event.repair) {
items.push({
kind: "row",
id: `${event.id}/repair`,
content: (
<Box paddingLeft={2}>
<Text color={COLOR.accent}>{event.repair}</Text>
</Box>
),
});
}
// Stats line — inlined here (kept as a 1-row LogRow rather than a
// LogBlock) so the user can scroll past it cleanly.
if (event.stats) {
const hit = (event.stats.cacheHitRatio * 100).toFixed(1);
const hitColor =
event.stats.cacheHitRatio >= 0.7
? "#4ade80"
: event.stats.cacheHitRatio >= 0.4
? "#fcd34d"
: "#f87171";
items.push({
kind: "row",
id: `${event.id}/stats`,
content: (
<Box paddingLeft={2}>
<Text color={hitColor} bold>
{`⌬ ${hit}%`}
</Text>
<Text dimColor>{" · "}</Text>
<Text color="#94a3b8">{"in "}</Text>
<Text color="#67e8f9" bold>
{event.stats.usage.promptTokens}
</Text>
<Text color="#94a3b8">{" → out "}</Text>
<Text color="#c4b5fd" bold>
{event.stats.usage.completionTokens}
</Text>
<Text dimColor>{" · "}</Text>
<Text color="#86efac" bold>{`$${event.stats.cost.toFixed(6)}`}</Text>
</Box>
),
});
}
return items;
}
/**
* Convert a single `DisplayEvent` to its row-pipeline representation.
* Migrated roles return `LogRow[]` (one item per visual terminal line,
* word-wrapped to `width`); everything else falls back to a single
* `LogBlock` wrapping the legacy `<EventRow>` component.
*
* `projectRoot` is forwarded to the legacy renderer for fall-back
* blocks (used by the markdown renderer to resolve relative paths).
*
* `width` is the terminal column count. Used to word-wrap accent rows
* so a single long line decomposes into the right number of rows —
* this matters for the slicer's row arithmetic and for the scrollbar
* thumb position, both of which assume row count == visual lines.
*/
export function eventToItems(event: DisplayEvent, projectRoot?: string, width = 80): LogItem[] {
if (event.role === "info") {
const { lead, color, body } = detectInfoTone(event.text);
return accentRows(event.id, lead, color, body, undefined, true, width);
}
if (event.role === "warning") {
return accentRows(event.id, "▲ warn", COLOR.warn, event.text, COLOR.warn, false, width);
}
if (event.role === "error") {
return accentRows(event.id, "✦ error", COLOR.err, event.text, COLOR.err, false, width);
}
if (event.role === "assistant" && !event.streaming) {
return assistantToRows(event, projectRoot, width);
}
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 ?? "");
const rows: LogRow[] = [];
// marginTop={1} in the legacy renderer — emit one blank spacer row.
rows.push({
kind: "row",
id: `${event.id}/spacer`,
content: <Text> </Text>,
});
// Header row: green-on-black STEP pill + counter + label.
rows.push({
kind: "row",
id: `${event.id}/head`,
content: (
<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>
),
});
// Optional body lines (one per \n-split line).
if (event.text) {
for (const [i, line] of event.text.split("\n").entries()) {
rows.push({
kind: "row",
id: `${event.id}/body/${i}`,
content: (
<Box paddingLeft={2}>
<Text dimColor>{line}</Text>
</Box>
),
});
}
}
if (sp?.notes) {
rows.push({
kind: "row",
id: `${event.id}/notes`,
content: (
<Box paddingLeft={2}>
<Text color="#fbbf24" dimColor>
{`note: ${sp.notes}`}
</Text>
</Box>
),
});
}
return rows;
}
// Fallback: render the whole event as one atomic block via the
// legacy `EventRow`. Estimates row count via a copy of the slicer's
// heightOf logic. Once a role is migrated above, this branch stops
// running for that role.
return [
{
kind: "block",
id: event.id,
rows: estimatedHeight(event),
content: <EventRow event={event} projectRoot={projectRoot} />,
},
];
}
/**
* Mirror of the slicer's `heightOfEvent` from App.tsx — kept in sync
* by hand. Used only for fall-back `LogBlock`s; migrated roles
* compute their row count exactly via the row count itself.
*/
function estimatedHeight(e: DisplayEvent): number {
const text = e.text ?? "";
const wrapLines = Math.max(0, Math.floor(text.length / 80));
if (e.role === "user") return 3 + wrapLines;
if (e.role === "assistant") {
let h = 4 + wrapLines;
if (e.reasoning) h += 3;
if (e.branch) h += 4;
return h;
}
if (e.role === "tool") {
const isEditFile = e.toolName === "edit_file" || e.toolName?.endsWith("_edit_file");
if (isEditFile) {
const diffLines = (text.match(/\n/g)?.length ?? 0) + 1;
return 6 + Math.min(20, diffLines);
}
return 2;
}
if (e.role === "plan" || e.role === "plan-replay" || e.role === "plan-resumed") return 10;
if (e.role === "ctx-breakdown") return 7;
return 2;
}
export interface RowSlice {
items: LogItem[];
/** Highest valid scroll offset (rows). Caller clamps with this. */
maxScrollRows: number;
/** Total rows across all events (informational, e.g. for "↑ N rows above" hints). */
totalRows: number;
}
/**
* Slice the flat `LogItem` list to fit `available` viewport rows,
* scrolled up by `scrollOffsetRows` from the bottom.
*
* Snap behavior: if the viewport top edge would fall *inside* a
* `LogBlock`, the block is included in full (so it might extend
* partially above the viewport — clipped by the parent's flex-end
* + overflow=hidden). The same trick that makes the BOTTOM of a tall
* latest event readable is what makes block snap-rendering safe.
*/
export function sliceLogItems(
items: readonly LogItem[],
available: number,
scrollOffsetRows: number,
): RowSlice {
if (items.length === 0) {
return { items: [], maxScrollRows: 0, totalRows: 0 };
}
const heights = items.map(itemRows);
const totalRows = heights.reduce((a, b) => a + b, 0);
// Cap the scroll so the OLDEST viewport-full of rows (oldest line at
// the top of the viewport) is reachable but the user never scrolls
// past it into empty space. With `totalRows - 1` the user could
// scroll until only one row remained visible — scrollbar at the top
// and viewport mostly empty, which feels broken. Leaving a viewport-
// worth of rows below the absolute top means Home / max-scroll lands
// on a fully-populated viewport showing the start of the log.
const maxScrollRows = Math.max(0, totalRows - available);
const offset = Math.max(0, Math.min(scrollOffsetRows, maxScrollRows));
const viewportBottom = totalRows - offset;
const viewportTop = Math.max(0, viewportBottom - available);
// Walk forward, picking items whose row range overlaps the viewport.
// Items entirely above viewport are dropped; entirely below ends the
// walk early.
let cursor = 0;
let firstIdx = -1;
let lastIdx = -1;
for (let i = 0; i < items.length; i++) {
const eStart = cursor;
const eEnd = cursor + heights[i]!;
cursor = eEnd;
if (eEnd <= viewportTop) continue;
if (eStart >= viewportBottom) break;
if (firstIdx === -1) firstIdx = i;
lastIdx = i;
}
if (firstIdx === -1) {
// Should not happen with clamped offset + non-empty items, but
// fall back to "render the last item" so the user never sees a
// blank middle.
return { items: [items[items.length - 1]!], maxScrollRows, totalRows };
}
return {
items: items.slice(firstIdx, lastIdx + 1),
maxScrollRows,
totalRows,
};
}
/**
* Wrap a `LogItem` in the height-1 (or natural-height for blocks) Box
* that keeps the slicer's row arithmetic exact. `flexShrink={0}`
* prevents Ink from squashing rows when the parent's content overflows.
*/
export function renderLogItem(item: LogItem): React.ReactElement {
if (item.kind === "row") {
return (
<Box key={item.id} height={1} flexShrink={0}>
{item.content}
</Box>
);
}
return (
<Box key={item.id} flexShrink={0}>
{item.content}
</Box>
);
}
/**
* One-row hint pinned at the bottom of the log viewport when the user
* has scrolled up. Tells them how many rows of newer content sit
* below the visible window and how to jump back. Hidden when the user
* is at the bottom (offset === 0) since there's nothing to point to.
*
* `rowsBelow` is the same as the active `logScrollOffset` (rows from
* the bottom that aren't currently visible).
*/
export function BottomHint({
rowsBelow,
totalRows,
viewportRows,
}: {
rowsBelow: number;
totalRows: number;
viewportRows: number;
}) {
if (rowsBelow <= 0) return null;
const maxScroll = Math.max(1, totalRows - viewportRows);
const ratioFromTop = Math.max(0, Math.min(1, (totalRows - rowsBelow - viewportRows) / maxScroll));
const pct = Math.round((1 - ratioFromTop) * 100);
const rowsAbove = Math.max(0, totalRows - viewportRows - rowsBelow);
const barCells = 16;
const markerAt = Math.max(0, Math.min(barCells - 1, Math.round(ratioFromTop * (barCells - 1))));
const left = "─".repeat(markerAt);
const right = "─".repeat(barCells - 1 - markerAt);
return (
<Box height={1} flexShrink={0}>
<Text color={COLOR.primary} bold>
{`↑ ${rowsAbove}`}
</Text>
<Text>{" "}</Text>
<Text dimColor>▕</Text>
<Text color={COLOR.info} dimColor>
{left}
</Text>
<Text color={COLOR.brand} bold>
●
</Text>
<Text color={COLOR.info} dimColor>
{right}
</Text>
<Text dimColor>▏</Text>
<Text>{" "}</Text>
<Text color={COLOR.primary} bold>{`${pct}%`}</Text>
<Text>{" "}</Text>
<Text color={COLOR.primary}>{`↓ ${rowsBelow}`}</Text>
<Text dimColor>{" · End to jump · wheel to scroll"}</Text>
</Box>
);
}
+80
View File
@@ -0,0 +1,80 @@
/** Pure parsing for `/loop <interval> <prompt>`; cancellation contract is enforced in App.tsx. */
/** Lower bound on loop interval (ms). Faster than this would queue submits faster than turns finish. */
export const MIN_LOOP_INTERVAL_MS = 5_000;
/** Upper bound on loop interval (ms). Beyond a few hours, use cron. */
export const MAX_LOOP_INTERVAL_MS = 6 * 60 * 60_000;
/** Returns null on bad shape OR out-of-range; caller surfaces as usage hint. */
export function parseLoopInterval(raw: string): { ms: number } | null {
const s = raw.trim().toLowerCase();
if (!s) return null;
const m = /^([0-9]+(?:\.[0-9]+)?)(s|sec|secs|m|min|mins|h|hr|hrs)?$/.exec(s);
if (!m) return null;
const n = Number.parseFloat(m[1] ?? "");
if (!Number.isFinite(n) || n <= 0) return null;
const unit = m[2] ?? "s";
let ms: number;
if (unit === "s" || unit === "sec" || unit === "secs") ms = Math.round(n * 1000);
else if (unit === "m" || unit === "min" || unit === "mins") ms = Math.round(n * 60_000);
else if (unit === "h" || unit === "hr" || unit === "hrs") ms = Math.round(n * 60 * 60_000);
else return null;
if (ms < MIN_LOOP_INTERVAL_MS) return null;
if (ms > MAX_LOOP_INTERVAL_MS) return null;
return { ms };
}
export interface ParsedLoopArgs {
intervalMs: number;
prompt: string;
}
export type LoopCommand =
| { kind: "start"; intervalMs: number; prompt: string }
| { kind: "stop" }
| { kind: "status" }
| { kind: "error"; message: string };
export function parseLoopCommand(args: readonly string[]): LoopCommand {
if (args.length === 0) return { kind: "status" };
const first = (args[0] ?? "").toLowerCase();
if (args.length === 1 && (first === "stop" || first === "off" || first === "cancel")) {
return { kind: "stop" };
}
const interval = parseLoopInterval(args[0] ?? "");
if (!interval) {
return {
kind: "error",
message:
"usage: /loop <interval> <prompt> (interval = 5s..6h, e.g. 30s, 5m, 1h)\n" +
" /loop stop (cancel an active loop)\n" +
" /loop (show active-loop status)",
};
}
const prompt = args.slice(1).join(" ").trim();
if (!prompt) {
return {
kind: "error",
message: `usage: /loop ${args[0]} <prompt> — interval is fine but the prompt is missing.`,
};
}
return { kind: "start", intervalMs: interval.ms, prompt };
}
export function formatLoopStatus(prompt: string, nextFireMs: number, iter: number): string {
const preview = prompt.length > 36 ? `${prompt.slice(0, 33)}…` : prompt;
const when = nextFireMs <= 0 ? "firing now" : `next in ${formatDuration(nextFireMs)}`;
return `loop: \`${preview}\` · ${when} · iter ${iter}`;
}
export function formatDuration(ms: number): string {
if (ms < 1000) return `${ms}ms`;
const totalSec = Math.round(ms / 1000);
if (totalSec < 60) return `${totalSec}s`;
const m = Math.floor(totalSec / 60);
const s = totalSec % 60;
if (m < 60) return s === 0 ? `${m}m` : `${m}m${s}s`;
const h = Math.floor(m / 60);
const mm = m % 60;
return mm === 0 ? `${h}h` : `${h}h${mm}m`;
}
+310
View File
@@ -0,0 +1,310 @@
/** Markdown→Frame compiler reusing `parseBlocks` from markdown.tsx; tables / edit blocks / citations fall back to plain text. */
import {
type Cell,
type Frame,
type TextOpts,
borderLeft,
empty,
pad,
text,
vstack,
} from "../../frame/index.js";
import { type Block, parseBlocks } from "./markdown.js";
import { COLOR } from "./theme.js";
/** Mirrors `markdown.tsx` INLINE_RE — link/bold/italic/code/strike/escape. */
const INLINE_RE =
/(\[([^\]\n]+)\]\(([^)\n]+)\)|\*\*\*([^*\n]+?)\*\*\*|\*\*([^*\n]+?)\*\*|```([^\n]+?)```|`([^`\n]+?)`|~~([^~\n]+?)~~|(?<![*\w])\*([^*\n]+?)\*(?!\w)|\\([*_~`[\](){}#+\-.!\\]))/g;
interface InlineSegment {
text: string;
opts: Omit<TextOpts, "width">;
}
function parseInline(input: string, baseOpts: Omit<TextOpts, "width">): InlineSegment[] {
const out: InlineSegment[] = [];
let lastEnd = 0;
// The regex is /g so we must reset lastIndex when reusing it.
INLINE_RE.lastIndex = 0;
for (let m = INLINE_RE.exec(input); m !== null; m = INLINE_RE.exec(input)) {
if (m.index > lastEnd) {
out.push({ text: input.slice(lastEnd, m.index), opts: baseOpts });
}
const linkText = m[2];
const linkUrl = m[3];
const boldItalic = m[4];
const bold = m[5];
const code3 = m[6];
const code1 = m[7];
const strike = m[8];
const italic = m[9];
const escapeChar = m[10];
if (linkText !== undefined) {
out.push({
text: linkText,
opts: { ...baseOpts, fg: COLOR.accent, underline: true, href: linkUrl },
});
} else if (boldItalic !== undefined) {
out.push({ text: boldItalic, opts: { ...baseOpts, bold: true, italic: true } });
} else if (bold !== undefined) {
out.push({ text: bold, opts: { ...baseOpts, bold: true } });
} else if (code3 !== undefined) {
// Strip leading "lang " prefix (consistent with the legacy renderer)
const stripped = code3.replace(/^(\w+)\s+/, "");
out.push({ text: stripped, opts: { ...baseOpts, fg: "#67e8f9", bg: "#0f172a" } });
} else if (code1 !== undefined) {
out.push({ text: code1, opts: { ...baseOpts, fg: "#67e8f9", bg: "#0f172a" } });
} else if (strike !== undefined) {
out.push({ text: strike, opts: { ...baseOpts, dim: true } });
} else if (italic !== undefined) {
out.push({ text: italic, opts: { ...baseOpts, italic: true } });
} else if (escapeChar !== undefined) {
out.push({ text: escapeChar, opts: baseOpts });
}
lastEnd = m.index + m[0]!.length;
}
if (lastEnd < input.length) {
out.push({ text: input.slice(lastEnd), opts: baseOpts });
}
return out;
}
/** Single wrap loop over flattened (cell, style) atoms — keeps wrap logic in one place across styles. */
function segmentsToFrame(segs: readonly InlineSegment[], width: number): Frame {
if (width <= 0) return empty(0);
// Build a flat list of "atoms" — each atom is one grapheme + its
// style. We reuse Frame's text() to handle grapheme width / 2-wide
// chars correctly: rendering each segment to a 1-row Frame at a
// very wide budget gives back its cell array, which we splice
// together for the wrap.
const atoms: Cell[] = [];
for (const seg of segs) {
if (!seg.text) continue;
// Use a generous width so the segment doesn't pre-wrap inside text()
const f = text(seg.text, { ...seg.opts, width: Math.max(width, seg.text.length * 2 + 4) });
if (f.rows.length > 0) {
// Strip trailing space-padding the text() helper adds; the
// segment's actual cells are the leading non-space prefix.
let stop = f.rows[0]!.length;
while (
stop > 0 &&
f.rows[0]![stop - 1]!.char === " " &&
f.rows[0]![stop - 1]!.fg === undefined &&
f.rows[0]![stop - 1]!.bg === undefined
) {
stop--;
}
for (let i = 0; i < stop; i++) atoms.push(f.rows[0]![i]!);
}
// Multi-line segments (rare with inline markup, but possible if
// text contained \n) — append blank cells then continue.
for (let li = 1; li < f.rows.length; li++) {
// Insert a newline marker via a sentinel cell? Simpler: emit
// a hard-break row right now and continue with the next line.
// To keep `atoms` 1-D, we encode \n as a special cell char and
// handle in the wrap loop. Use a SOH sentinel char that won't
// appear in real text.
atoms.push({ char: "\n", width: 1 });
let stop = f.rows[li]!.length;
while (
stop > 0 &&
f.rows[li]![stop - 1]!.char === " " &&
f.rows[li]![stop - 1]!.fg === undefined
) {
stop--;
}
for (let i = 0; i < stop; i++) atoms.push(f.rows[li]![i]!);
}
}
// Greedy wrap: walk atoms, accumulate cells until current row width
// would exceed `width` (skipping tail cells from the count); on a
// newline atom, force a row break.
const SPACE: Cell = { char: " ", width: 1 };
const rows: Cell[][] = [];
let cur: Cell[] = [];
let curW = 0;
let lastSpaceIdx = -1;
const flushRow = (forceNewline = false): void => {
while (curW < width) {
cur.push(SPACE);
curW += 1;
}
rows.push(cur);
cur = [];
curW = 0;
lastSpaceIdx = -1;
if (forceNewline) return;
};
for (const a of atoms) {
if (a.char === "\n") {
flushRow(true);
continue;
}
const w = a.tail ? 0 : a.width;
if (curW + w > width) {
// Try to break at the last whitespace we saw — soft wrap.
if (lastSpaceIdx >= 0 && lastSpaceIdx > 0) {
// Cut the row at lastSpaceIdx; carry overflow atoms into the
// next row.
const overflow = cur.slice(lastSpaceIdx + 1);
cur = cur.slice(0, lastSpaceIdx);
let newW = 0;
for (const c of cur) newW += c.tail ? 0 : c.width;
// Pad current row to width
while (newW < width) {
cur.push(SPACE);
newW += 1;
}
rows.push(cur);
cur = overflow;
curW = 0;
for (const c of cur) curW += c.tail ? 0 : c.width;
lastSpaceIdx = -1;
} else {
// No whitespace to break at — hard wrap.
flushRow();
}
}
if (a.char === " ") lastSpaceIdx = cur.length;
cur.push(a);
curW += w;
}
if (cur.length > 0 || rows.length === 0) {
flushRow();
}
return { width, rows };
}
function paragraphFrame(p: { text: string }, width: number): Frame {
const segs = parseInline(p.text, {});
return segmentsToFrame(segs, width);
}
function headingFrame(h: { level: number; text: string }, width: number): Frame {
const isMajor = h.level <= 3;
const fg = isMajor ? COLOR.brand : COLOR.accent;
const segs = parseInline(h.text, { bold: true, fg, dim: !isMajor });
return vstack(segmentsToFrame(segs, width), text("", { width }));
}
/** Continuation lines align under the body, not under the bullet. */
function bulletListFrame(
b: { items: { text: string; task?: "done" | "todo" }[]; ordered?: boolean },
width: number,
): Frame {
const rows: Frame[] = [];
for (let i = 0; i < b.items.length; i++) {
const item = b.items[i]!;
let prefix: string;
let prefixOpts: Omit<TextOpts, "width">;
if (item.task === "done") {
prefix = "[x] ";
prefixOpts = { fg: COLOR.ok, bold: true };
} else if (item.task === "todo") {
prefix = "[ ] ";
prefixOpts = { fg: COLOR.warn, bold: true };
} else if (b.ordered) {
prefix = `${i + 1}. `;
prefixOpts = { fg: COLOR.info, bold: true };
} else {
prefix = "• ";
prefixOpts = { fg: COLOR.info, bold: true };
}
const prefixWidth = prefix.length;
const indentRow = " ".repeat(prefixWidth);
const innerSegs = parseInline(item.text, {});
const innerFrame = segmentsToFrame(innerSegs, Math.max(8, width - prefixWidth));
// Decorate first line with prefix, subsequent lines with spaces.
const decoratedRows: Frame[] = innerFrame.rows.map((r, li) => {
const indent =
li === 0
? text(prefix, { width: prefixWidth, ...prefixOpts })
: text(indentRow, { width: prefixWidth });
return {
width: prefixWidth + innerFrame.width,
rows: [[...indent.rows[0]!, ...r]],
};
});
rows.push(...decoratedRows);
}
return vstack(...rows);
}
function codeBlockFrame(c: { lang: string; text: string }, width: number): Frame {
const lines = c.text.split("\n");
const rows: Frame[] = [];
if (c.lang) {
rows.push(text(c.lang, { width, fg: COLOR.info, dim: true, italic: true }));
}
for (const line of lines) {
rows.push(text(line || " ", { width, fg: "#67e8f9", bg: "#0f172a" }));
}
return vstack(...rows);
}
function blockquoteFrame(bq: { children: Block[] }, width: number): Frame {
const inner = bq.children.map((child) => blockToFrame(child, Math.max(8, width - 2)));
const stacked = inner.length === 0 ? empty(Math.max(8, width - 2)) : vstack(...inner);
return borderLeft(pad(stacked, 0, 0, 0, 1), COLOR.info);
}
function hrFrame(width: number): Frame {
return text("─".repeat(width), { width, fg: COLOR.info, dim: true });
}
function blockToFrame(b: Block, width: number): Frame {
switch (b.kind) {
case "paragraph":
return paragraphFrame(b, width);
case "heading":
return headingFrame(b, width);
case "bullet":
return bulletListFrame(b, width);
case "code":
return codeBlockFrame(b, width);
case "quote":
return blockquoteFrame(b, width);
case "hr":
return hrFrame(width);
case "table":
// Tables: render as plain-text rows for now; full table layout
// is a future migration. Header gets bold, body rows dim.
return vstack(
text(b.header.join(" | "), { width, bold: true }),
text(b.header.map(() => "─").join("─┼─"), { width, dim: true }),
text(b.rows.map((r) => r.join(" | ")).join("\n"), { width, dim: true }),
);
case "edit-block":
// Aider edit blocks: render filename + SEARCH/REPLACE summaries
// as plain text. The full diff renderer lives in EditBlockRow
// which we keep on the legacy Ink path until migration.
return text(`${b.filename}\n<<< SEARCH\n${b.search}\n=======\n${b.replace}\n>>> REPLACE`, {
width,
dim: true,
});
default:
// Unknown block kind — should never happen given the parser's
// exhaustive Block union, but stay defensive.
return empty(width);
}
}
export function markdownToFrame(markdown: string, width: number): Frame {
if (!markdown) return empty(width);
const blocks = parseBlocks(markdown);
if (blocks.length === 0) return empty(width);
const frames: Frame[] = [];
for (let i = 0; i < blocks.length; i++) {
const b = blocks[i]!;
frames.push(blockToFrame(b, width));
// Inter-block separator. Skip after blocks that already include
// their own trailing spacer (headings) so we don't double-space.
const isLast = i === blocks.length - 1;
const carriesOwnSpacer = b.kind === "heading";
if (!isLast && !carriesOwnSpacer) {
frames.push(text("", { width }));
}
}
return vstack(...frames);
}
+765 -71
View File
File diff suppressed because it is too large. Load diff
+1 -32
View File
@@ -1,24 +1,4 @@
/**
* `/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.
*/
/** `/resource` + `/prompt` handlers — async (round-trip to MCP server), so App.tsx calls directly instead of `handleSlash`. */
import type { McpClient } from "../../mcp/client.js";
import type {
@@ -30,11 +10,6 @@ import type {
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 {
@@ -167,12 +142,6 @@ function formatOnePromptMessage(m: McpPromptMessage): string {
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,
+100 -35
View File
@@ -1,25 +1,4 @@
/**
* Pure keystroke → action reducer for PromptInput.
*
* 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.
*
* 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).
*/
/** Pure keystroke→action reducer; arrow keys at buffer boundary defer to the parent for history recall. */
export interface MultilineKey {
input: string;
@@ -47,8 +26,14 @@ export interface MultilineAction {
/** When `true`, fire `onSubmit(submitValue ?? value)`. */
submit: boolean;
submitValue?: string;
/** Set when ↑/↓ hits a buffer boundary — parent handles history recall. */
historyHandoff?: "prev" | "next";
/** Reducer is pure — hands raw paste to PromptInput which allocates a sentinel and inserts that. */
pasteRequest?: { content: string };
}
import { recoverCsiTail, stripCsiFragments } from "./key-normalize.js";
const BACKSLASH_SUFFIX = /\\$/;
const NOOP: MultilineAction = { next: null, cursor: null, submit: false };
@@ -56,19 +41,46 @@ const NOOP: MultilineAction = { next: null, cursor: null, submit: false };
export function processMultilineKey(
value: string,
cursor: number,
key: MultilineKey,
keyIn: MultilineKey,
): MultilineAction {
// Parent-owned keys: Tab (slash-complete), Esc (abort), PageUp/Down.
if (key.tab || key.escape || key.pageUp || key.pageDown) {
// CSI recovery — bare `[A` / `[C` / `[Z` / `[5~` / etc. that
// Windows ConPTY leaves in `input` after parse-keypress eats the
// leading `\x1b`. See key-normalize.ts for the long version.
const recovered = recoverCsiTail(keyIn.input, keyIn);
const key: MultilineKey = recovered ? { ...keyIn, ...recovered, input: "" } : keyIn;
// Parent-owned keys: Tab (slash-complete), Esc (abort).
if (key.tab || key.escape) {
return NOOP;
}
// Empty buffer + ↑/↓ → parent handles history recall.
if (value.length === 0 && (key.upArrow || key.downArrow)) {
return NOOP;
// Buffer-wide navigation. Per-line motion (↑/↓ / Ctrl+A / Ctrl+E)
// is already covered; PageUp/PageDown are the missing "jump to
// top / bottom of the WHOLE buffer" pair, useful after pasting a
// 500-line blob where ↑×500 is absurd. Repurposed from the
// previous NOOP behavior (PageUp/Down had no binding).
if (key.pageUp) {
return cursor === 0 ? NOOP : { next: null, cursor: 0, submit: false };
}
if (key.pageDown) {
return cursor === value.length ? NOOP : { next: null, cursor: value.length, submit: false };
}
// Cursor motion.
// History recall is bound to Ctrl+P / Ctrl+N (bash readline
// convention) rather than ↑/↓. Reason: Windows Terminal + ConPTY
// translates mouse wheel events to ↑/↓ keystrokes for raw-mode
// child processes — indistinguishable at the byte level. If ↑/↓
// recalled history, every wheel-scroll would corrupt the prompt
// with a prior message. Ctrl+P/N is wheel-immune.
if (key.ctrl && key.input === "p") {
return { ...NOOP, historyHandoff: "prev" };
}
if (key.ctrl && key.input === "n") {
return { ...NOOP, historyHandoff: "next" };
}
// Cursor motion. Empty single-line buffer + ↑/↓ is now a no-op
// (used to recall history; see Ctrl+P/N comment above).
if (key.leftArrow) {
return { next: null, cursor: Math.max(0, cursor - 1), submit: false };
}
@@ -92,8 +104,58 @@ export function processMultilineKey(
if (key.ctrl && key.input === "e") {
return { next: null, cursor: endOfLine(value, cursor), submit: false };
}
// Bash / readline conventions:
// Ctrl+U — clear the whole buffer (readline treats this as
// "clear from cursor to start"; for our text-area we treat it
// as "clear all" because there's no ergonomic way to clear a
// huge paste otherwise).
// Ctrl+W — delete the word before the cursor.
if (key.ctrl && key.input === "u") {
return value.length === 0 ? NOOP : { next: "", cursor: 0, submit: false };
}
if (key.ctrl && key.input === "w") {
if (cursor === 0) return NOOP;
const wordStart = previousWordStart(value, cursor);
return {
next: value.slice(0, wordStart) + value.slice(cursor),
cursor: wordStart,
submit: false,
};
}
// Newline: Ctrl+J (LF literal) or ctrl+'j' normalized form.
// Paste-burst detection. If `input` contains a newline (or
// bracketed-paste markers from a terminal that supports them),
// this is a paste — surface it as a `pasteRequest` so the parent
// can register the blob and insert ONE sentinel codepoint instead
// of the full content. The buffer stays small + readable; the
// user sees `[paste #N · M lines]` where the paste lives.
//
// Always overrides `key.return` for pastes: Ink occasionally sets
// key.return when a paste's trailing \n looks like Enter, which
// would submit the partial buffer mid-paste and silently truncate
// the content. Pastes always insert; Enter only submits typed
// content. We normalize \r\n and bare \r to \n so mixed-line-
// ending pastes (Windows clipboard, web copy) land cleanly.
// Strip every recognised CSI fragment (paste markers, arrow tails,
// etc.) defensively — if any leaked past structured-key recovery
// they shouldn't get inserted into the buffer as text.
const stripped = stripCsiFragments(key.input);
// Paste = newline-containing input with MORE than just the newline
// itself. A bare "\n" is Ctrl+J / one-keystroke newline (handled
// below); only multi-char input wrapped around a newline is a real
// paste burst that warrants a sentinel.
const looksLikePaste =
stripped.length > 1 && (stripped.includes("\n") || stripped.includes("\r"));
if (looksLikePaste) {
const normalized = stripped.replace(/\r\n?/g, "\n");
return {
next: null,
cursor: null,
submit: false,
pasteRequest: { content: normalized },
};
}
// Single-char Ctrl+J / LF: insert one newline.
if (key.input === "\n" || (key.ctrl && key.input === "j")) {
return insertAt(value, cursor, "\n");
}
@@ -148,11 +210,6 @@ function insertAt(value: string, cursor: number, insert: string): MultilineActio
};
}
/**
* 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;
@@ -172,6 +229,14 @@ function startOfLine(value: string, cursor: number): number {
return value.lastIndexOf("\n", cursor - 1) + 1;
}
/** Skips trailing whitespace first so Ctrl+W after a space still removes the previous word. */
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;
+1 -27
View File
@@ -1,18 +1,5 @@
/**
* 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).
*/
/** Display-only — the MODEL always receives full paste text. */
/** 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. */
@@ -35,19 +22,6 @@ export interface PasteCollapseResult {
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 = {},
+81
View File
@@ -0,0 +1,81 @@
/** PUA range U+E100..U+E1FF (BMP, no surrogate pairs) so each sentinel is one codepoint and cursor arithmetic stays trivial. */
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;
}
export function makePasteEntry(id: number, content: string): PasteEntry {
return {
id,
content,
lineCount: content.split("\n").length,
charCount: content.length,
};
}
/** Unknown sentinels drop to empty — never leak a PUA codepoint into the prompt. */
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;
}
export function bufferHasPaste(text: string): boolean {
for (let i = 0; i < text.length; i++) {
if (decodePasteSentinel(text[i]!) !== null) return true;
}
return false;
}
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;
}
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`;
}
+64 -31
View File
@@ -1,47 +1,80 @@
/**
* One place that defines what each preset means. Both `slash.ts`
* (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.
*/
/** Preset table — branch and harvest stay off here so users never get ambushed into N× cost without opting in. */
import type { PresetName } from "../../config.js";
export interface PresetSettings {
model: string;
reasoningEffort: "high" | "max";
autoEscalate: boolean;
/** Pillar-2 harvest. Always false in presets — opt-in via /harvest. */
harvest: boolean;
/** Branch budget. `1` means branching off. */
/** Branch budget. Always 1 in presets — opt-in via /branch. */
branch: number;
}
export const PRESETS: Record<PresetName, PresetSettings> = {
// `deepseek-chat` / `deepseek-reasoner` are retained as the fast /
// smart models because they're deprecated-but-working compat aliases
// for v4-flash's non-thinking and thinking modes respectively. Same
// billing, smaller config churn for existing users. `max` promotes
// to v4-pro — 12× flash on input/output, reserved for hard tasks.
fast: { model: "deepseek-chat", harvest: false, branch: 1 },
smart: { model: "deepseek-reasoner", harvest: true, branch: 1 },
max: { model: "deepseek-v4-pro", harvest: true, branch: 3 },
};
export const PRESET_DESCRIPTIONS: Record<PresetName, { headline: string; cost: string }> = {
fast: {
headline: "deepseek-chat (= v4-flash non-thinking), no harvest, no branching",
cost: "~1¢ per 100 turns · default",
/** Old names `fast`/`smart`/`max` aliased via `resolvePreset` so legacy configs still load. */
export const PRESETS: Record<"auto" | "flash" | "pro", PresetSettings> = {
// auto — flash baseline + auto-escalate to pro when the model emits
// <<<NEEDS_PRO>>> OR after 3+ tool failure signals in one turn.
// The default: cheap when easy, smart when hard.
auto: {
model: "deepseek-v4-flash",
reasoningEffort: "max",
autoEscalate: true,
harvest: false,
branch: 1,
},
smart: {
headline: "deepseek-reasoner (= v4-flash thinking) + Pillar 2 harvest",
cost: "same price as fast · slower · better on multi-step tasks",
// flash — always flash, never escalate. `/pro` still arms a single
// manual turn; auto-promotion is the thing this disables. Use when
// you want predictable cost per turn.
flash: {
model: "deepseek-v4-flash",
reasoningEffort: "max",
autoEscalate: false,
harvest: false,
branch: 1,
},
max: {
headline: "deepseek-v4-pro + harvest + self-consistency (3 branches)",
cost: "~30× cost vs fast · slowest · for hard single-shots",
// pro — always pro. Hard pin; the model never downgrades. Use for
// multi-turn architecture work where flash is just going to keep
// escalating anyway and the back-and-forth wastes turns.
pro: {
model: "deepseek-v4-pro",
reasoningEffort: "max",
autoEscalate: false,
harvest: false,
branch: 1,
},
};
export const PRESET_DESCRIPTIONS: Record<
"auto" | "flash" | "pro",
{ headline: string; cost: string }
> = {
auto: {
headline: "flash → pro on hard turns",
cost: "default · ~96% turns stay on flash · pro kicks in only when needed",
},
flash: {
headline: "v4-flash always",
cost: "cheapest · predictable · /pro still works for a one-turn bump",
},
pro: {
headline: "v4-pro always",
cost: "~3× flash (5/31 discount) / ~12× full price · for hard multi-turn work",
},
};
/** Legacy aliases: fast→flash+high, smart→auto, max→pro. Unknown names fall through to auto. */
export function resolvePreset(name: PresetName | undefined): PresetSettings {
return PRESETS[name ?? "fast"];
if (name === "auto" || name === "flash" || name === "pro") return PRESETS[name];
if (name === "fast") return { ...PRESETS.flash, reasoningEffort: "high" };
if (name === "smart") return PRESETS.auto;
if (name === "max") return PRESETS.pro;
return PRESETS.auto;
}
/** Canonical name for storage / display — unknown values become auto. */
export function canonicalPresetName(name: PresetName | undefined): "auto" | "flash" | "pro" {
if (name === "auto" || name === "flash" || name === "pro") return name;
return "auto";
}
+97
View File
@@ -0,0 +1,97 @@
import { Text, useStdout } from "ink";
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React in value scope for JSX compilation
import React from "react";
import { COLOR } from "./theme.js";
/**
* Faint full-width horizontal rule. Width tracks the terminal columns
* minus 2 cells so it lines up exactly under content rendered inside
* a `paddingX={1}` parent — the standard chrome layout. Used by the
* top chrome bar, the replay StatsPanel, and the bottom ctx footer.
*/
export function ChromeRule(): React.ReactElement {
const { stdout } = useStdout();
const cols = stdout?.columns ?? 80;
const w = Math.max(20, cols - 2);
return <Text dimColor>{"─".repeat(w)}</Text>;
}
/** Compact binary-K formatter — `1234 → "1.2K"`, `131072 → "128K"`. */
export function formatTokens(n: number): string {
if (n < 1024) return String(n);
const k = n / 1024;
return k >= 100 ? `${k.toFixed(0)}K` : `${k.toFixed(1)}K`;
}
/**
* Filled / empty progress bar. `▰▱` glyphs have distinct shapes so the
* boundary stays visible even when the terminal collapses to 8-color slots.
*/
export function Bar({
ratio,
color,
cells = 14,
dim,
}: {
ratio: number;
color: string;
cells?: number;
dim?: boolean;
}): React.ReactElement {
const filled = Math.max(0, Math.min(cells, Math.round(ratio * cells)));
return (
<Text>
<Text color={color} dimColor={dim}>
{"▰".repeat(filled)}
</Text>
<Text dimColor>{"▱".repeat(cells - filled)}</Text>
</Text>
);
}
/**
* `▣ ctx ▰▰▱▱… 14K/128K (11%)` — the canonical context-pressure cell.
* Used by the persistent footer (chat) and StatsPanel (replay). Color
* thresholds match the `/compact` warning policy in the loop:
* green <60% · amber 60-80% · red ≥80% (with `· /compact` hint).
*/
export function ContextCell({
ratio,
promptTokens,
ctxMax,
showBar,
}: {
ratio: number;
promptTokens: number;
ctxMax: number;
showBar?: boolean;
}): React.ReactElement {
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>
);
}
+243
View File
@@ -0,0 +1,243 @@
/** Slice each prompt line to a single visual row — Ink/Yoga wrap miscounts on CJK Windows terminals and leaks ghost rows. */
import { type PasteEntry, decodePasteSentinel, formatBytesShort } from "./paste-sentinels.js";
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[];
/** `null` when cursor is not on this 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;
}
/** Treats Ambiguous=1 to match Ink/Yoga's own miscount — agreement matters more than correctness here. */
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;
}
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 };
}
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);
}
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 -1574
View File
File diff suppressed because it is too large. Load diff
Loaded 100 of 301 files, more files were not shown because too many files have changed in this diff. Show more