Compare commits

...
65 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
272 changed files with 38254 additions and 6951 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
+1050
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.
+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
+36 -2
View File
@@ -1,6 +1,6 @@
{
"name": "reasonix",
"version": "0.10.0",
"version": "0.16.0",
"description": "DeepSeek-native coding agent: cache-first loop, flash-first cost control, tool-call repair.",
"type": "module",
"bin": {
@@ -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}`);
+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;
}
}
+83 -150
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,
@@ -396,19 +368,13 @@ 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.
/**
* Matches `@http://...` or `@https://...` at a word boundary. Captures the
* URL minus the leading `@`. Trailing sentence punctuation is stripped
* separately because URLs can legitimately contain `,` `.` `)` etc., and a
* blanket trim would butcher real query strings.
*/
/** 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. */
@@ -438,40 +404,15 @@ export interface AtUrlOptions {
maxChars?: number;
/** Per-URL fetch timeout in ms. */
timeoutMs?: number;
/**
* Override the fetcher — production wires `webFetch` from src/tools/web.ts.
* Tests inject a stub so the suite stays offline.
*/
fetcher?: (
url: string,
opts: { maxChars?: number; timeoutMs?: number; signal?: AbortSignal },
) => Promise<{ url: string; title?: string; text: string; truncated: boolean }>;
/**
* Optional cache the caller persists across calls (e.g. one map per
* session). Hit-on-URL skips the fetch entirely. Omit for one-shot
* tests that don't care about reuse.
*/
cache?: Map<string, AtUrlExpansion & { body?: string }>;
/** Forward Esc/abort to the fetcher. */
signal?: AbortSignal;
}
/**
* Expand `@http(s)://…` mentions in `text`. Returns the (possibly augmented)
* text plus a per-URL report so the caller can surface fetched URLs in the
* UI. Async because each URL hits the network; the file-mention sibling
* (`expandAtMentions`) stays sync.
*
* Caching: when `opts.cache` is provided, a hit skips the network and
* reuses the prior expansion (including its body). One Map per session is
* the intended use — a long conversation that references the same URL
* twice doesn't pay twice.
*
* Trailing-punctuation handling: a sentence like "see @https://x.com." has
* the period stripped so the actual fetched URL is `https://x.com`. We
* conservatively strip only `.,;:!?` and `)]}>` from the tail; anything
* else is preserved so query strings survive intact.
*/
export async function expandAtUrls(
text: string,
opts: AtUrlOptions = {},
@@ -557,15 +498,7 @@ export async function expandAtUrls(
return { text: augmented, expansions };
}
/**
* Strip trailing sentence punctuation from a URL captured at a word
* boundary. `https://x.com.` → `https://x.com`; `https://x.com/?q=a)` →
* `https://x.com/?q=a`. Conservative: only strips `.,;:!?` and unmatched
* close-brackets `)]}>` from the very end. Internal punctuation in path /
* query is preserved.
*
* Returns empty string if everything stripped — caller treats as "no URL."
*/
/** Only strips `.,;:!?` and unmatched close-brackets — internal path / query punctuation preserved. */
export function stripUrlTail(raw: string): string {
let s = raw;
while (s.length > 0) {
+34 -4
View File
@@ -9,11 +9,12 @@ 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";
@@ -37,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[];
@@ -53,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; jobs?: import("../../tools/jobs.js").JobRegistry };
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 {
@@ -138,12 +162,14 @@ function Root({
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>
);
@@ -182,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, {
@@ -212,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`,
);
+51 -23
View File
@@ -20,7 +20,8 @@
import { basename, resolve } from "node:path";
import { loadEditMode, loadProjectShellAllowed } from "../../config.js";
import { sanitizeName } from "../../session.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";
@@ -52,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> {
@@ -67,26 +76,39 @@ 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 });
// Background-process registry shared between the shell tools and the
// TUI's /jobs + /kill slashes + exit cleanup. One per `reasonix code`
// run — orphan prevention on SIGINT / process exit kills everything
// it owns, so dev servers don't outlive the Reasonix process.
const jobs = new JobRegistry();
registerShellTools(tools, {
rootDir,
// Per-project "always allow" list persisted from prior ShellConfirm
// choices; merged on top of the built-in allowlist in shell.ts.
// GETTER form — re-read every dispatch so a prefix the user adds
// via ShellConfirm mid-session takes effect on the next shell call
// instead of waiting for `/new` or a relaunch.
extraAllowed: () => loadProjectShellAllowed(rootDir),
// `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,
});
// 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
@@ -98,18 +120,22 @@ export async function codeCommand(opts: CodeOptions = {}): Promise<void> {
// menu into a submit_plan body. Keeping it always-registered
// preserves the prefix cache across plan-mode toggles.
registerChoiceTool(tools);
// `remember` / `forget` / `recall_memory` — cross-session user memory.
// Project scope hashes off rootDir so switching projects gets a fresh
// per-project memory store; the global scope is shared across runs.
registerMemoryTools(tools, { projectRoot: rootDir });
// `run_skill` is intentionally NOT registered here — App.tsx wires it
// up with the subagent runner attached, so `runAs: subagent` skills
// can spawn isolated child loops. Doing it here would mean the App's
// re-registration would shadow the no-runner version, which works
// (last write wins) but obscures the wiring.
// 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)
@@ -128,12 +154,14 @@ export async function codeCommand(opts: CodeOptions = {}): Promise<void> {
await chatCommand({
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, jobs },
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));
+121 -5
View File
@@ -1,12 +1,16 @@
import { Command } from "commander";
import { readConfig } from "../config.js";
import { VERSION } from "../index.js";
import { listSessions } from "../memory/session.js";
import { applyMemoryStack } from "../memory/user.js";
import { ESCALATION_CONTRACT } from "../prompt-fragments.js";
import { listSessions } from "../session.js";
import { applyMemoryStack } from "../user-memory.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";
@@ -40,6 +44,18 @@ The signal isn't a topic list — it's: "if I'm wrong about this, is it because
${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")
@@ -89,7 +105,7 @@ program
program
.command("code [dir]")
.description(
"Code-editing chat — filesystem tools rooted at <dir> (default: cwd), coding system prompt, v4-flash. Model proposes SEARCH/REPLACE blocks; Reasonix applies them to disk. Use /preset max or /pro to escalate to v4-pro on hard tasks.",
"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 model (v4-flash)")
.option("--no-session", "Disable session persistence for this run")
@@ -100,6 +116,15 @@ program
"--harvest",
"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({
dir,
@@ -109,6 +134,8 @@ program
forceResume: !!opts.resume,
forceNew: !!opts.new,
harvest: !!opts.harvest,
budgetUsd: parseBudgetFlag(opts.budget),
noDashboard: opts.dashboard === false,
});
});
@@ -120,7 +147,7 @@ program
.option("--transcript <path>", "Write a JSONL transcript to this path")
.option(
"--preset <name>",
"Model + effort bundle. One of: fast (flash·high), smart (flash·max, default), max (pro·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",
@@ -131,6 +158,11 @@ program
"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")
@@ -150,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,
@@ -178,11 +214,13 @@ program
transcript: opts.transcript,
harvest: defaults.harvest,
branch: defaults.branch,
budgetUsd: parseBudgetFlag(opts.budget),
session: continueOpts.session,
mcp: defaults.mcp,
mcpPrefix: opts.mcpPrefix,
forceResume: continueOpts.forceResume,
forceNew: !!opts.new,
noDashboard: opts.dashboard === false,
});
});
@@ -191,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>",
@@ -225,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,
@@ -241,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.")
@@ -249,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(
@@ -327,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);
+14 -28
View File
@@ -1,20 +1,7 @@
/**
* 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 "smart" preset defaults (flash + effort=max)
*
* Keeping this logic in one place — rather than duplicating across
* `chat` and `run` — means the precedence rule only lives in one unit
* 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;
@@ -42,7 +29,7 @@ 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;
@@ -66,11 +53,20 @@ function pickPreset(
): PresetName {
if (flagPreset && isPresetName(flagPreset)) return flagPreset;
if (configPreset) return configPreset;
return "smart";
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 {
@@ -90,16 +86,6 @@ function resolveSession(
return "default";
}
/**
* Resolve the `-c/--continue` flag into a concrete `(session, forceResume)`
* pair. When the flag is set we ask `getLatestSession` for the most-recently-
* touched saved session and skip the picker; if nothing is on disk we
* fall back silently to `fallbackSession` after emitting a single warning
* line via `warn`.
*
* Pure & testable: callers inject the fs lookup. `cli/index.ts` plugs in
* `() => listSessions()[0]`; tests pass a deterministic stub.
*/
export function resolveContinueFlag(
flag: boolean | undefined,
fallbackSession: string | undefined,
+1615 -169
View File
File diff suppressed because it is too large. Load diff
+45 -23
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,
@@ -31,11 +42,12 @@ export function AtMentionSuggestions({
if (matches.length === 0) {
return (
<Box paddingX={1} marginTop={1}>
<Text color="yellow">no files match "@{query}"</Text>
<Text dimColor>
{" "}
— keep typing, or Backspace to edit. Paths resolve from the code root.
<Text 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>
);
}
@@ -48,34 +60,44 @@ export function AtMentionSuggestions({
const hiddenBelow = total - windowStart - shown.length;
return (
<Box flexDirection="column" paddingX={1} marginTop={1}>
{hiddenAbove > 0 ? <Text dimColor> ↑ {hiddenAbove} more above</Text> : null}
<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 }) {
// 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 backgroundColor="#67e8f9" color="black" bold>
{` ▸ ${base}${dir ? ` ${dir}` : ""} `}
</Text>
</Box>
);
}
return (
<Box>
<Text color="#94a3b8">{` ${base}`}</Text>
<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>
);
+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 {
+50 -36
View File
@@ -1,8 +1,10 @@
import { Box, Text, useStdout } from "ink";
import React, { useMemo, useState } from "react";
import { formatEditBlockDiff } from "../../code/diff-preview.js";
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";
/**
@@ -20,7 +22,7 @@ export type EditReviewChoice = "apply" | "reject" | "apply-rest-of-turn" | "flip
export interface EditConfirmProps {
block: EditBlock;
onChoose: (choice: EditReviewChoice) => void;
onChoose: (choice: EditReviewChoice, denyContext?: string) => void;
}
/**
@@ -61,22 +63,26 @@ export function EditConfirm({ block, onChoose }: EditConfirmProps) {
const rows = stdout?.rows ?? 40;
const budget = Math.max(MIN_DIFF_ROWS, rows - MODAL_OVERHEAD_ROWS);
// Full diff — maxLines pushed high enough that the diff-preview
// renderer never inserts its own truncation marker. Context trimming
// (contextLines) still applies for tight scan.
const allLines = useMemo(
() => formatEditBlockDiff(block, { contextLines: 2, maxLines: 100_000, indent: " " }),
// 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, allLines.length - budget);
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
@@ -87,7 +93,7 @@ export function EditConfirm({ block, onChoose }: EditConfirmProps) {
return;
}
if (input === "n") {
onChoose("reject");
setPhase("context");
return;
}
if (input === "a") {
@@ -132,18 +138,36 @@ export function EditConfirm({ block, onChoose }: EditConfirmProps) {
const added = block.replace === "" ? 0 : (block.replace.match(/\n/g)?.length ?? 0) + 1;
const tag = isNew ? "NEW" : "EDIT";
const visibleLines = allLines.slice(effectiveScroll, effectiveScroll + budget);
const visibleRows = allRows.slice(effectiveScroll, effectiveScroll + budget);
const hiddenAbove = effectiveScroll;
const hiddenBelow = Math.max(0, allLines.length - effectiveScroll - budget);
const totalLines = allLines.length;
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 + visibleLines.length}/${totalLines}`,
`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"}
@@ -156,28 +180,18 @@ export function EditConfirm({ block, onChoose }: EditConfirmProps) {
dimColor
>{` ↑ ${hiddenAbove} line${hiddenAbove === 1 ? "" : "s"} above (↑/k or PgUp)`}</Text>
) : null}
<Box flexDirection="column">
{visibleLines.map((line, i) => {
const trimmed = line.trimStart();
const color = trimmed.startsWith("+")
? "#4ade80"
: trimmed.startsWith("-")
? "#f87171"
: undefined;
const dim = !color;
return (
<Text
// Stable-enough: slice only shifts by scroll; React keys only
// need to be unique within the current render.
// biome-ignore lint/suspicious/noArrayIndexKey: list is static per render
key={`diff-${effectiveScroll}-${i}`}
color={color}
dimColor={dim}
>
{line}
</Text>
);
})}
<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
@@ -194,7 +208,7 @@ export function EditConfirm({ block, onChoose }: EditConfirmProps) {
<Text color="#67e8f9" bold>
n
</Text>
{"] reject · ["}
{"] reject with reason · ["}
<Text color="#67e8f9" bold>
a
</Text>
+199 -139
View File
@@ -2,12 +2,14 @@ import { Box, Text, useStdout } from "ink";
import React from "react";
import { type TypedPlanState, isPlanStateEmpty } from "../../harvest.js";
import type { BranchProgress, BranchSummary } from "../../loop.js";
import type { TurnStats } from "../../telemetry.js";
import type { TurnStats } from "../../telemetry/stats.js";
import type { PlanStep } from "../../tools/plan.js";
import { PlanStateBlock } from "./PlanStateBlock.js";
import { PlanStepList } from "./PlanStepList.js";
import { CtxBreakdownBlock, type CtxBreakdownData } from "./ctx-breakdown.js";
import { Markdown } from "./markdown.js";
import { COLOR, gradientCells } from "./theme.js";
import { formatTokens } from "./primitives.js";
import { COLOR, GLYPH, gradientCells } from "./theme.js";
import { useElapsedSeconds, useTick } from "./ticker.js";
import { formatDuration, summarizeToolResult } from "./tool-summary.js";
@@ -46,7 +48,15 @@ export type DisplayRole =
* dim border + ⏪ icon — so the user immediately sees this is
* historical, not the active plan.
*/
| "plan-replay";
| "plan-replay"
/**
* Token-usage breakdown rendered by the `/context` slash. Carries
* a structured `ctxBreakdown` payload so EventLog can render the
* stacked colored char-bar with proper Box+Text layout — slash
* info text can't carry per-segment color, so /context pushes this
* specialized event role instead of plain "info".
*/
| "ctx-breakdown";
export interface DisplayEvent {
id: string;
@@ -57,6 +67,14 @@ export interface DisplayEvent {
branch?: BranchSummary;
branchProgress?: BranchProgress;
toolName?: string;
/**
* Raw JSON args the model passed to the tool. Carried through so the
* web dashboard's snapshot endpoint can reconstruct the same
* tool-specific rendering (edit_file diff, write_file content, etc)
* the live SSE channel already provides. Not used by the Ink TUI
* directly — it shows the args via OngoingToolRow / tool-summary.
*/
toolArgs?: string;
/**
* 1-based position in the session's tool-call history. Rendered as a
* dim `/tool N` suffix on compact rows so the user can quickly jump
@@ -117,6 +135,11 @@ export interface DisplayEvent {
* this off; App.tsx sets it based on whether history is empty.
*/
leadSeparator?: boolean;
/**
* Populated on `ctx-breakdown` rows. Token counts per category +
* the context window cap; rendered via `<CtxBreakdownBlock>`.
*/
ctxBreakdown?: CtxBreakdownData;
}
/**
@@ -151,18 +174,24 @@ function RoleGlyph({
}
/**
* Solid-background pill for tool names. Mirrors the StatsPanel's mode
* pills so the visual language stays consistent across the screen:
* status (auto/review/plan), tool name, model. Status drives the
* background color — yellow for ok/in-flight, red for errors — so a
* scrollback full of tool dispatches reads at a glance.
* Tool name + status indicator. Bracket-text style (not solid-bg pill)
* because tool calls cluster — a turn with 6 reads + 2 edits + a grep
* would mean 9 high-contrast color blocks fighting for attention.
* Bracket text + colored glyph + colored name gives the eye a clear
* landmark per row without making every row shout.
*
* ▣ read_file → ok
* ▥ run_command → err (rose)
*
* Visual grammar matches the design doc: status icon first, name in
* the matching color, no padded-bg block.
*/
function ToolPill({ label, status }: { label: string; status: "ok" | "err" }) {
const bg = status === "err" ? "red" : "yellow";
const symbol = status === "err" ? "✗" : "✓";
const color = status === "err" ? COLOR.toolErr : COLOR.tool;
const symbol = status === "err" ? GLYPH.toolErr : GLYPH.toolOk;
return (
<Text backgroundColor={bg} color="black" bold>
{` ${symbol} ${label} `}
<Text color={color} bold>
{`${symbol} ${label}`}
</Text>
);
}
@@ -240,7 +269,7 @@ export const EventRow = React.memo(function EventRow({
{event.text ? (
<Markdown text={event.text} projectRoot={projectRoot} />
) : (
<Text dimColor>(no content)</Text>
<Text dimColor>(empty body — likely tool-call only)</Text>
)}
{event.stats ? <StatsLine stats={event.stats} /> : null}
{event.repair ? <Text color={COLOR.accent}>{event.repair}</Text> : null}
@@ -279,10 +308,11 @@ export const EventRow = React.memo(function EventRow({
</Box>
);
}
// Compact one-line render for everything else. The summarizer
// produces a tool-aware one-liner (exit code for shell, line
// count for read_file, error tag for failures, ...). Full content
// remains accessible via `/tool N`, hinted as a dim suffix.
// Compact one-line render for everything else. Wrapped in a
// yellow-left-bar Box so it shares the same "card column" visual
// language as user/assistant turns — the eye reads the conversation
// log as one continuous column with role-coded accents, not as a
// mix of bordered turns and disconnected naked rows.
const summary = summarizeToolResult(event.toolName ?? "?", event.text);
const status: "ok" | "err" = summary.isError ? "err" : "ok";
const durationLabel =
@@ -291,7 +321,14 @@ export const EventRow = React.memo(function EventRow({
: "";
const indexHint = event.toolIndex !== undefined ? ` /tool ${event.toolIndex}` : "";
return (
<Box>
<Box
borderStyle="single"
borderTop={false}
borderRight={false}
borderBottom={false}
borderColor={status === "err" ? COLOR.toolErr : COLOR.tool}
paddingLeft={1}
>
<ToolPill label={event.toolName ?? "?"} status={status} />
{durationLabel ? <Text dimColor>{` ${durationLabel}`}</Text> : null}
<Text dimColor>{" "}</Text>
@@ -304,12 +341,20 @@ export const EventRow = React.memo(function EventRow({
}
if (event.role === "error") {
return (
<Box marginTop={1}>
<Text backgroundColor="#f87171" color="black" bold>
{" ✦ ERROR "}
<Box
marginTop={1}
borderStyle="single"
borderTop={false}
borderRight={false}
borderBottom={false}
borderColor={COLOR.err}
paddingLeft={1}
>
<Text color={COLOR.err} bold>
✦ error
</Text>
<Text>{" "}</Text>
<Text color="#f87171">{indentContinuationLines(event.text)}</Text>
<Text color={COLOR.err}>{indentContinuationLines(event.text)}</Text>
</Box>
);
}
@@ -326,8 +371,18 @@ export const EventRow = React.memo(function EventRow({
else if (lead === "✓") leadColor = COLOR.ok;
else if (lead === "✗" || lead === "✖") leadColor = COLOR.err;
else if (lead === "↻") leadColor = COLOR.primary;
// Same conversation-column visual: left bar in the lead's color,
// glyph + body indented under it. Without the bar, info rows looked
// like floating debug text rather than a coherent log entry.
return (
<Box>
<Box
borderStyle="single"
borderTop={false}
borderRight={false}
borderBottom={false}
borderColor={leadColor}
paddingLeft={1}
>
<Text color={leadColor} bold>
{lead}
</Text>
@@ -474,15 +529,25 @@ export const EventRow = React.memo(function EventRow({
}
if (event.role === "warning") {
return (
<Box>
<Text backgroundColor="#fbbf24" color="black" bold>
{" ▲ WARN "}
<Box
borderStyle="single"
borderTop={false}
borderRight={false}
borderBottom={false}
borderColor={COLOR.warn}
paddingLeft={1}
>
<Text color={COLOR.warn} bold>
▲ warn
</Text>
<Text>{" "}</Text>
<Text color="#fbbf24">{indentContinuationLines(event.text)}</Text>
<Text color={COLOR.warn}>{indentContinuationLines(event.text)}</Text>
</Box>
);
}
if (event.role === "ctx-breakdown" && event.ctxBreakdown) {
return <CtxBreakdownBlock data={event.ctxBreakdown} />;
}
return (
<Box>
<Text>{event.text}</Text>
@@ -642,15 +707,39 @@ function ReasoningBlock({ reasoning }: { reasoning: string }) {
// Users can dump the full reasoning with `/think` if needed.
const preview =
flat.length <= max ? flat : `… (+${flat.length - max} earlier chars) ${flat.slice(-max)}`;
// Approximate tokens for the meta line — R1 reasoning_content runs
// 4-6 chars/token in English, which is what /think also uses for
// its summary header. Rough is fine; the user reads "ballpark size"
// not "exact bill".
const tokensApprox = Math.max(1, Math.round(flat.length / 4.5));
const tokLabel =
tokensApprox >= 1000 ? `${(tokensApprox / 1000).toFixed(1)}k` : `${tokensApprox}`;
// Layout (matches design/tui-redesign-ink.html R1 reasoning state):
// R1 ↯ reasoning · ~Nk tok
// │ <preview text — dim violet italic, left-bordered>
// The left border is a Box `borderStyle="single" borderLeft` colored
// violet — same idiom user/assistant turns use, just dimmer to mark
// this as supplementary thought rather than primary content.
return (
<Box marginBottom={1}>
<Text backgroundColor={COLOR.accent} color="black" bold>
{" ⋯ thinking "}
</Text>
<Text> </Text>
<Text color={COLOR.accent} italic dimColor>
{preview}
</Text>
<Box flexDirection="column" marginBottom={1}>
<Box>
<Text color={COLOR.accent} bold>
R1 ↯
</Text>
<Text dimColor>{` reasoning · ~${tokLabel} tok · /think for full`}</Text>
</Box>
<Box
borderStyle="single"
borderTop={false}
borderRight={false}
borderBottom={false}
borderColor={COLOR.accent}
paddingLeft={1}
>
<Text color={COLOR.accent} italic dimColor>
{preview}
</Text>
</Box>
</Box>
);
}
@@ -668,17 +757,16 @@ function Elapsed() {
}
/**
* Animated role glyph for the actively-streaming assistant. Alternates
* ◆ ↔ ◇ every ~480ms so the user can see the model is alive even
* during R1's long pre-first-byte silence. Settles back to a static
* ◆ once the turn ends (StreamingAssistant is unmounted).
* Role glyph for the actively-streaming assistant. The braille
* spinner sitting next to it (`Pulse`) already conveys "alive" — a
* second animated indicator on the same row was visually noisy AND
* doubled the fast-tick subscriber count for the streaming row. The
* glyph stays static; the spinner does the liveness signaling.
*/
function PulsingAssistantGlyph() {
const tick = useTick();
const on = Math.floor(tick / 4) % 2 === 0;
return (
<Text color="green" bold>
{on ? ROLE_GLYPH.assistant : ROLE_GLYPH.assistantPulse}
{ROLE_GLYPH.assistant}
</Text>
);
}
@@ -732,117 +820,95 @@ function StreamingAssistant({ event }: { event: DisplayEvent }) {
);
}
const tail = lastLine(event.text, 140);
const reasoningTail = event.reasoning ? lastLine(event.reasoning, 120) : "";
const toolCallBuild = event.toolCallBuild;
// Four distinct phases a turn can be in — label them plainly so
// the user doesn't have to decode "streaming · 391 + think 4506
// chars" to figure out what's happening:
// pre-first-byte: request in flight, no bytes back yet
// reasoning-only: R1 thinking, no visible content yet
// tool-call-only: tool_call arguments streaming, no content/reasoning bytes
// writing: content streaming (R1 has already produced its thought)
// both: rare — content present AND reasoning still growing
// We can't cheaply distinguish "reasoning still growing" from
// "reasoning finished but we already saw it", so when content is
// present we just say "writing response" and surface both counts.
const preFirstByte = !event.text && !event.reasoning && !toolCallBuild;
const reasoningOnly = !event.text && !!event.reasoning && !toolCallBuild;
const toolCallOnly = !event.text && !event.reasoning && !!toolCallBuild;
// Phase pill — solid bg color per phase so the user reads
// "what's happening" at a glance from across the screen.
let pillBg: string;
let pillText: string;
let label: string;
const text = event.text;
const reasoning = event.reasoning;
const preFirstByte = !text && !reasoning && !toolCallBuild;
const reasoningOnly = !text && !!reasoning && !toolCallBuild;
const toolCallOnly = !text && !reasoning && !!toolCallBuild;
let phaseVerb: string | null = null;
let phaseColor: string = COLOR.assistant;
if (preFirstByte) {
pillBg = "#fbbf24"; // amber
pillText = "WAITING";
label = "request sent · waiting for server";
phaseVerb = "waiting";
phaseColor = COLOR.warn;
} else if (reasoningOnly) {
pillBg = "#c4b5fd"; // violet
pillText = "THINKING";
label = `${event.reasoning?.length ?? 0} chars of thought`;
phaseVerb = "thinking";
phaseColor = COLOR.accent;
} else if (toolCallOnly) {
pillBg = "#f0abfc"; // fuchsia
pillText = "DISPATCH";
label = `assembling${formatToolCallIndex(toolCallBuild)} <${toolCallBuild.name}> · ${toolCallBuild.chars} chars${formatReadyTail(toolCallBuild)}`;
} else {
pillBg = "#86efac"; // green
pillText = "WRITING";
const parts: string[] = [`${event.text.length} chars`];
if (event.reasoning) parts.push(`after ${event.reasoning.length} reasoning`);
if (toolCallBuild) {
parts.push(
`tool${formatToolCallIndex(toolCallBuild)} <${toolCallBuild.name}> ${toolCallBuild.chars}c${formatReadyTail(toolCallBuild)}`,
);
}
label = parts.join(" · ");
phaseVerb = `dispatching ${toolCallBuild.name}`;
phaseColor = COLOR.accent;
}
const verb = phaseVerb ?? "responding";
const verbColor = phaseVerb ? phaseColor : COLOR.info;
return (
<Box flexDirection="column" marginTop={1}>
<Box>
<PulsingAssistantGlyph />
<Text>{" "}</Text>
<Pulse />
<Text> </Text>
<Text backgroundColor={pillBg} color="black" bold>
{` ${pillText} `}
<Text color={verbColor} dimColor={!phaseVerb}>
{verb}
</Text>
<Text dimColor>{` ${label} `}</Text>
<Text> </Text>
<Marquee />
<Text> </Text>
<Elapsed />
</Box>
{reasoningTail ? (
<Box paddingLeft={3}>
<Text color="#c4b5fd" italic dimColor>
↳ {reasoningTail}
<Box
marginTop={1}
borderStyle="single"
borderTop={false}
borderRight={false}
borderBottom={false}
borderColor={COLOR.assistant}
paddingLeft={1}
flexDirection="column"
>
{reasoning ? <ReasoningBlock reasoning={reasoning} /> : null}
{text ? (
<Text>
{text}
<BlinkingCursor />
</Text>
</Box>
) : null}
{tail ? (
<Box paddingLeft={3}>
<Text dimColor>▸ {tail}</Text>
</Box>
) : preFirstByte ? (
// Non-dim amber: first-time users misread the dim version as
// "app frozen". The reassurance has to be VISIBLE to do its job.
<Box paddingLeft={3}>
<Text color="#fbbf24" italic>
{"waiting for first byte — typical 5–60s depending on model + load"}
) : (
<Text dimColor>
{preFirstByte
? "waiting for first byte — 5-60s typical"
: reasoningOnly
? `R1 thinking · ~${Math.round((reasoning?.length ?? 0) / 4)} tok so far`
: toolCallOnly
? `assembling ${toolCallBuild.name}${formatToolCallIndex(toolCallBuild)} · ${toolCallBuild.chars} chars${formatReadyTail(toolCallBuild)}`
: ""}
<Text> </Text>
<BlinkingCursor />
</Text>
</Box>
) : reasoningOnly ? (
<Box paddingLeft={3}>
<Text color="#c4b5fd" italic>
{"R1 thinks before it speaks — body text arrives when reasoning finishes (20–90s)"}
</Text>
</Box>
) : toolCallOnly ? (
<Box paddingLeft={3}>
<Text color="#f0abfc" italic>
{"tool-call arguments streaming — about to dispatch"}
</Text>
</Box>
) : event.reasoning ? (
<Box paddingLeft={3}>
<Text color="#fbbf24" italic>
{"R1 still reasoning — body text or tool call arrives when thinking finishes"}
</Text>
</Box>
) : null}
)}
</Box>
</Box>
);
}
/**
* Blinking indicator so the user can tell the stream is alive even
* when the reasoner hasn't produced body text yet. Uses the shared
* tick (TICK_MS ≈ 120ms) scaled down 4× so the visible blink rate
* lands around 500ms — feels like a heartbeat, not a progress bar.
*/
function Pulse() {
/** Blinking ▌ at the end of the streaming body. ~960ms cycle (matches the
* design's 900ms steps(2) blink; integer-tick approximation). */
function BlinkingCursor() {
const tick = useTick();
const frames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
return <Text color="cyan">{frames[Math.floor(tick / 4) % frames.length]}</Text>;
const visible = Math.floor(tick / 4) % 2 === 0;
return <Text color={COLOR.primary}>{visible ? "▌" : " "}</Text>;
}
/** Char-marching responding indicator. 12-cell track; a 5-char wave
* (▒▓█▓▒) shifts one cell per fast tick (120ms). Matches the design
* HTML's `.thinking .marquee` exactly. */
const MARQUEE_W = 12;
const MARQUEE_WAVE = ["▒", "▓", "█", "▓", "▒"] as const;
function Marquee() {
const tick = useTick();
const cells = new Array(MARQUEE_W).fill("░");
for (let i = 0; i < MARQUEE_WAVE.length; i++) {
cells[(tick + i) % MARQUEE_W] = MARQUEE_WAVE[i]!;
}
return <Text color={COLOR.primary}>{cells.join("")}</Text>;
}
/**
@@ -868,12 +934,6 @@ function formatReadyTail(tb: { readyCount?: number } | undefined): string {
return ` · ${n} ready`;
}
function lastLine(s: string, maxChars: number): string {
const flat = s.replace(/\s+/g, " ").trim();
if (!flat) return "";
return flat.length <= maxChars ? flat : `…${flat.slice(-maxChars)}`;
}
function StatsLine({ stats }: { stats: TurnStats }) {
const hit = (stats.cacheHitRatio * 100).toFixed(1);
const hitColor =
+45 -20
View File
@@ -4,7 +4,8 @@ import React from "react";
import type { ApplyResult } from "../../code/edit-blocks.js";
import type { EditMode } from "../../config.js";
import type { JobRegistry } from "../../tools/jobs.js";
import { useElapsedSeconds, useTick } from "./ticker.js";
import { CharBar } from "./char-bar.js";
import { useElapsedSeconds, useSlowTick, useTick } from "./ticker.js";
export const SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
@@ -58,10 +59,12 @@ export function ModeStatusBar({
undoArmed: boolean;
jobs?: JobRegistry;
}) {
// Subscribe to tick so the jobs count stays live — the registry is
// mutated outside React, so we need a periodic repaint to catch it.
// 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).
useTick();
useSlowTick();
const running = jobs?.runningCount() ?? 0;
const jobsTag =
running > 0 ? (
@@ -124,10 +127,16 @@ function ModeBarFrame({ children }: { children: React.ReactNode }) {
/**
* Solid-background mode badge so the bottom status bar reads at a
* glance like a real editor's modeline (vim/helix style) instead of a
* dim text label that blends into the prompt above. `flash` inverts
* briefly after a mode flip — the existing modeFlash signal — for a
* "yes, it changed" acknowledgement.
* 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,
@@ -139,8 +148,8 @@ function ModePill({
flash: boolean;
}) {
return (
<Text backgroundColor={bg} color="white" bold inverse={flash}>
{` ${label} `}
<Text color={bg} bold inverse={flash}>
{`[${label}]`}
</Text>
);
}
@@ -148,21 +157,29 @@ function ModePill({
/**
* "Just auto-applied N edits — press u to undo" banner. Rendered below
* the live rows after an auto-mode edit batch lands, visible for 5s.
* `useTick` drives a crude live countdown so the user sees the window
* shrinking. State cleanup (the banner disappearing) happens in the
* parent's setTimeout — the component is purely display.
* 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>
@@ -172,7 +189,9 @@ export function UndoBanner({
<Text backgroundColor="#67e8f9" color="black" bold>
{" u "}
</Text>
<Text dimColor>{" to undo "}</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>
@@ -194,14 +213,18 @@ export function SubagentRow({
}) {
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 backgroundColor="#c4b5fd" color="black" bold>
{" ⌬ subagent "}
<Text color="#c4b5fd" bold>
⌬ subagent
</Text>
<Text color="#c4b5fd">{` ${activity.task}`}</Text>
<Text dimColor>{` iter ${activity.iter} · ${seconds}s`}</Text>
@@ -234,6 +257,9 @@ export function OngoingToolRow({
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>
@@ -241,11 +267,10 @@ export function OngoingToolRow({
{SPINNER_FRAMES[tick % SPINNER_FRAMES.length]}
</Text>
<Text>{" "}</Text>
<Text backgroundColor="#fcd34d" color="black" bold>
{` ⏵ ${tool.name} `}
<Text color="#fcd34d" bold>
{`▣ ${tool.name}`}
</Text>
<Text color="#fcd34d">{" running"}</Text>
<Text dimColor>{` · ${elapsed}s`}</Text>
<Text dimColor>{` running · ${elapsed}s`}</Text>
</Box>
{progress ? (
<Box paddingLeft={3}>
+73 -28
View File
@@ -1,22 +1,31 @@
/**
* Shared visual frame for confirmation modals (ChoiceConfirm,
* PlanConfirm, ShellConfirm, EditConfirm, PlanCheckpointConfirm,
* PlanReviseConfirm). Each modal opens inside the live region — so
* we keep the frame to plain Text rules and bg-pill headers, no
* Ink `borderStyle` (that's the eraseLines miscount class of bug).
* 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 ] optional subtitle
* ╭───────────────────────────────────────────────╮
* │ ICON TITLE subtitle │
* ├───────────────────────────────────────────────┤
* │ │
* │ <children — body of the modal> │
* │ │
* ╰───────────────────────────────────────────────╯
*
* <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.
*
* ▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁
*
* Color drives the accent (top + bottom rules + title pill bg)
* so the user learns to recognize "magenta = choice", "cyan =
* plan", "red = shell", "yellow = edit review" by sight.
* 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";
@@ -24,14 +33,21 @@ import { Box, Text, useStdout } from "ink";
import React from "react";
export interface ModalCardProps {
/** Accent color — title pill bg + top/bottom rule color. */
/** Accent color — border + icon + title text. */
accent: string;
/** Section title shown in the bg-pill header. */
/** Section title — rendered bold in the accent color. */
title: string;
/** Optional dim subtitle next to the title. */
subtitle?: string;
/** Optional leading glyph inside the title pill (icon). */
/** 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;
}
@@ -40,31 +56,60 @@ export function ModalCard({
title,
subtitle,
icon,
footer,
children,
}: ModalCardProps): React.ReactElement {
const { stdout } = useStdout();
const cols = stdout?.columns ?? 80;
const ruleWidth = Math.min(80, Math.max(28, cols - 4));
const titleText = icon ? ` ${icon} ${title} ` : ` ${title} `;
// 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" paddingX={1} marginY={1}>
<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>
<Text color={accent}>{"▔".repeat(ruleWidth)}</Text>
</Box>
<Box marginTop={1}>
<Text backgroundColor={accent} color="black" bold>
{titleText}
{icon ? (
<>
<Text color={accent} bold>
{icon}
</Text>
<Text>{" "}</Text>
</>
) : null}
<Text color={accent} bold>
{title}
</Text>
{subtitle ? <Text dimColor>{` ${subtitle}`}</Text> : null}
{subtitle ? (
<>
<Box flexGrow={1} />
<Text dimColor>{subtitle}</Text>
</>
) : null}
</Box>
<Box marginTop={1} flexDirection="column">
{children}
</Box>
<Box marginTop={1}>
<Box>
<Text color={accent} dimColor>
{"▁".repeat(ruleWidth)}
{"─".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>
);
}
+9 -8
View File
@@ -18,6 +18,7 @@ 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 {
@@ -74,25 +75,25 @@ export function PlanRefineInput({ mode, onSubmit, onCancel }: PlanRefineInputPro
mode === "approve"
? {
title: "approving — any last instructions?",
icon: "📋",
accent: "#67e8f9",
icon: "◇",
accent: COLOR.primary,
}
: mode === "checkpoint-revise"
? {
title: "revising — what should change before the next step?",
icon: "✏",
accent: "#fbbf24",
icon: "✎",
accent: COLOR.warn,
}
: mode === "choice-custom"
? {
title: "custom answer — type whatever fits",
icon: "🔀",
accent: "#f0abfc",
icon: "⌥",
accent: COLOR.accent,
}
: {
title: "refining — what should the model change?",
icon: "✏",
accent: "#fbbf24",
icon: "✎",
accent: COLOR.warn,
};
const hint =
mode === "approve"
+17 -11
View File
@@ -9,37 +9,43 @@
* - 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 = string;
export function PlanStateBlock({ planState }: { planState: TypedPlanState }) {
const fields: Array<[string, string[], FieldColor, boolean]> = [];
if (planState.subgoals.length) fields.push(["subgoals", planState.subgoals, "#67e8f9", false]);
if (planState.subgoals.length)
fields.push(["subgoals", planState.subgoals, COLOR.primary, false]);
if (planState.hypotheses.length)
fields.push(["hypotheses", planState.hypotheses, "#86efac", false]);
fields.push(["hypotheses", planState.hypotheses, COLOR.assistant, false]);
if (planState.uncertainties.length)
fields.push(["uncertainties", planState.uncertainties, "#fcd34d", false]);
fields.push(["uncertainties", planState.uncertainties, COLOR.warn, false]);
if (planState.rejectedPaths.length)
fields.push(["rejected", planState.rejectedPaths, "#94a3b8", 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]) => (
<Box key={label}>
<Text backgroundColor={color} color="black" bold dimColor={dim}>
{` ${label} ${items.length} `}
<Text color={color} bold dimColor={dim}>
{label}
</Text>
<Text dimColor>{` (${items.length})`}</Text>
<Text dimColor>{" · "}</Text>
<Text dimColor={dim} color={dim ? undefined : COLOR.info}>
{items.join(" · ")}
</Text>
<Text>{" "}</Text>
<Text dimColor={dim}>{items.join(" · ")}</Text>
</Box>
))}
</Box>
+97 -97
View File
@@ -1,22 +1,37 @@
/**
* Shared compact renderer for a plan's structured step list. Used by
* PlanConfirm (on approval) and PlanCheckpointConfirm (mid-execution)
* so the user always sees the same visual representation of the plan.
* 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:
*
* ● ✓ step-1 · Extract tokens into a module
* ●●▶ step-2 · Migrate session cookies
* ●●● step-3 · Update tests
* 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%
*
* The risk gutter (1–3 dots, green/yellow/red) is the signal the user
* learns to scan: high-risk steps are what deserves review before
* approve; low-risk is noise.
* 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";
@@ -28,28 +43,14 @@ export interface PlanStepListProps {
*/
statuses?: Map<string, StepStatus> | Record<string, StepStatus>;
/**
* Optional current step — rendered with a `›` gutter mark so the
* user sees which one just completed / is about to run.
* 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 riskDots(risk: PlanStep["risk"]): {
dots: string;
color: "green" | "yellow" | "red" | "gray";
} {
switch (risk) {
case "high":
return { dots: "●●●", color: "red" };
case "med":
return { dots: "●● ", color: "yellow" };
case "low":
return { dots: "● ", color: "green" };
default:
return { dots: " ", color: "gray" };
}
}
function getStatus(stepId: string, statuses: PlanStepListProps["statuses"]): StepStatus {
if (!statuses) return "pending";
if (statuses instanceof Map) {
@@ -58,96 +59,95 @@ function getStatus(stepId: string, statuses: PlanStepListProps["statuses"]): Ste
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 hasAnyRisk = steps.some((s) => s.risk !== undefined);
const doneCount = Array.from({ length: steps.length }, (_, i) =>
getStatus(steps[i]!.id, statuses),
).filter((s) => s === "done").length;
const pct = Math.round((doneCount / steps.length) * 100);
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>
{`${steps.length} step${steps.length === 1 ? "" : "s"}`}
{doneCount > 0 ? ` · ${doneCount}/${steps.length} done (${pct}%)` : ""}
{hasAnyRisk ? " · risk: " : ""}
{showProgress
? `${doneCount}/${total} done (${pct}%) · ${total} step${total === 1 ? "" : "s"}`
: `${total} step${total === 1 ? "" : "s"}`}
</Text>
{hasAnyRisk ? <RiskLegend /> : null}
</Box>
<Box flexDirection="column" marginTop={1}>
{steps.map((step) => {
const status = getStatus(step.id, statuses);
const focus = focusStepId === step.id;
const risk = riskDots(step.risk);
<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={focus ? "#67e8f9" : "gray"} bold={focus}>
{focus ? "▸ " : " "}
<Text color={COLOR.info} dimColor>
{isLast ? GLYPH.branchEnd : GLYPH.branch}
</Text>
<Text color={risk.color} bold>
{risk.dots}
<Text>{" "}</Text>
<Text color={sg.color} bold={status === "running" || isCur}>
{sg.glyph}
</Text>
<Text> </Text>
<StatusBadge status={status} />
<Text> </Text>
<Text dimColor={titleDim} bold={focus}>
<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>
</Box>
);
}
/**
* Status pill — solid-bg badge per step state. Reads at a glance
* better than a glyph + color text: ` DONE `, ` RUN `, ` SKIP `,
* ` PEND `. The label widths are normalized so the column under
* the badge stays aligned even when statuses mix.
*/
function StatusBadge({ status }: { status: StepStatus }) {
switch (status) {
case "done":
return (
<Text backgroundColor="#4ade80" color="black" bold>
{" ✓ DONE "}
</Text>
);
case "running":
return (
<Text backgroundColor="#67e8f9" color="black" bold>
{" ▶ RUN "}
</Text>
);
case "skipped":
return (
<Text backgroundColor="#94a3b8" color="black" bold>
{" — SKIP "}
</Text>
);
default:
return (
<Text color="#94a3b8" dimColor>
{" ☐ PEND "}
</Text>
);
}
}
function RiskLegend() {
return (
<Box>
<Text color="green">●</Text>
<Text dimColor> low </Text>
<Text color="yellow">●●</Text>
<Text dimColor> med </Text>
<Text color="red">●●●</Text>
<Text dimColor> high</Text>
{showProgress ? (
<Box>
<Text>{" "}</Text>
<CharBar pct={pct} width={24} />
</Box>
) : null}
</Box>
);
}
+9
View File
@@ -258,6 +258,15 @@ export function PromptInput({
</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>
+1 -1
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 {
+3 -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";
@@ -75,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">
+76 -19
View File
@@ -12,6 +12,7 @@
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. */
@@ -22,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;
}
@@ -50,13 +48,46 @@ 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;
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 (ev.downArrow) {
setIndex((i) => findNextEnabled(items, i, +1));
} else if (ev.tab && activeItem?.denyWithContext) {
setEditingContext("");
} else if (ev.return) {
const chosen = items[index];
if (chosen && !chosen.disabled) onSubmit(chosen.value);
@@ -65,19 +96,35 @@ export function SingleSelect<V extends string>({
}
});
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>
@@ -161,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>[↑↓] navigate · [Enter] select</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>
);
+22 -13
View File
@@ -2,6 +2,7 @@ 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";
@@ -19,7 +20,7 @@ export interface ShellConfirmProps {
* approving will block the TUI or not.
*/
kind?: "run_command" | "run_background";
onChoose: (choice: ShellConfirmChoice) => void;
onChoose: (choice: ShellConfirmChoice, denyContext?: string) => void;
}
/**
@@ -31,25 +32,34 @@ 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, 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 (
<ModalCard
accent="#f87171"
accent={COLOR.err}
icon={isBackground ? "⏱" : "⚡"}
title={isBackground ? "background process" : "shell command"}
subtitle={subtitle}
>
<Box marginBottom={1}>
<Text dimColor>{"$ "}</Text>
<Text color="#67e8f9" bold>
{command}
<Text color={COLOR.primary} bold>
{"$ "}
</Text>
<Text bold>{command}</Text>
</Box>
<SingleSelect
initialValue="run_once"
@@ -64,15 +74,14 @@ export function ShellConfirm({ command, allowPrefix, kind, onChoose }: ShellConf
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.",
},
denyItem,
]}
onSubmit={(v) => onChoose(v as ShellConfirmChoice)}
onSubmit={(v, ctx) => {
if (v === "deny") onChoose("deny", ctx);
else onChoose(v as ShellConfirmChoice);
}}
onCancel={() => onChoose("deny")}
footer="[↑↓] navigate · [Enter] select · [Esc] deny"
footer="[↑↓] navigate · [Enter] select · [Tab] add context · [Esc] deny"
/>
</ModalCard>
);
+39 -32
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} marginTop={1}>
<Text dimColor>
{" "}
<Text bold>/{spec.cmd}</Text>
{spec.argsHint ? ` ${spec.argsHint}` : ""} — {spec.summary}
</Text>
{headerRow}
</Box>
);
}
@@ -53,12 +67,14 @@ export function SlashArgPicker({
if (matches.length === 0) {
return (
<Box flexDirection="column" paddingX={1} marginTop={1}>
<Text dimColor>
{" "}
<Text bold>/{spec.cmd}</Text>
{spec.argsHint ? ` ${spec.argsHint}` : ""} — {spec.summary}
</Text>
<Text color="yellow"> no match for "{partial}" — keep typing, or Backspace to edit</Text>
{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>
);
}
@@ -72,36 +88,27 @@ export function SlashArgPicker({
const hiddenBelow = total - windowStart - shown.length;
return (
<Box flexDirection="column" paddingX={1} marginTop={1}>
<Text dimColor>
{" "}
<Text bold>/{spec.cmd}</Text>
{spec.argsHint ? ` ${spec.argsHint}` : ""} — {spec.summary}
</Text>
{hiddenAbove > 0 ? <Text dimColor> ↑ {hiddenAbove} more above</Text> : null}
{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>
);
+45 -24
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,
@@ -29,8 +40,12 @@ export function SlashSuggestions({
if (matches.length === 0) {
return (
<Box paddingX={1} marginTop={1}>
<Text color="yellow">no slash command matches that prefix</Text>
<Text dimColor> — Backspace to edit, or /help for the full list</Text>
<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>
);
}
@@ -46,34 +61,40 @@ export function SlashSuggestions({
const hiddenBelow = total - windowStart - shown.length;
return (
<Box flexDirection="column" paddingX={1} marginTop={1}>
{hiddenAbove > 0 ? <Text dimColor> ↑ {hiddenAbove} more above</Text> : null}
<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 name = `/${spec.cmd}`;
const argsSuffix = spec.argsHint ? ` ${spec.argsHint}` : "";
// Selected row gets a solid-bg highlight (cyan) so it pops like
// an editor's focused autocomplete entry. Non-selected rows stay
// dim with a leading bullet for vertical rhythm.
if (isSelected) {
return (
<Box>
<Text backgroundColor="#67e8f9" color="black" bold>
{` ▸ ${name.padEnd(12)}${argsSuffix.padEnd(16)} ${spec.summary} `}
</Text>
</Box>
);
}
const argsSuffix = spec.argsHint ? spec.argsHint : "";
return (
<Box>
<Text color="#94a3b8">{` ${name.padEnd(12)}${argsSuffix.padEnd(16)} ${spec.summary}`}</Text>
<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>;
}
+191 -519
View File
@@ -1,582 +1,254 @@
import { basename } from "node:path";
import { Box, Text, useStdout } from "ink";
import React from "react";
import stringWidth from "string-width";
import type { EditMode } from "../../config.js";
import { DEEPSEEK_CONTEXT_TOKENS, DEFAULT_CONTEXT_TOKENS } from "../../telemetry.js";
import type { SessionSummary } from "../../telemetry.js";
import { VERSION } from "../../version.js";
import type { SessionSummary } from "../../telemetry/stats.js";
import { Bar, ChromeRule } from "./primitives.js";
import { COLOR, GRADIENT } from "./theme.js";
const WORDMARK_LETTERS: ReadonlyArray<string> = ["R", "E", "A", "S", "O", "N", "I", "X"];
/**
* Gradient-flowing wordmark. Every tick the gradient shifts one
* position so the colors visibly travel across the letters — like
* a neon sign. Brand mark `◈` rides the same flow but also pulses
* bold on/off (slow when idle, fast when busy) so a glance at the
* top of the screen tells you whether the app is thinking.
*
* Tick is ~120 ms. `rotateEvery=4` ticks → one shift every ~480 ms
* idle, ~240 ms when busy. Slow enough to be ambient, fast enough
* to feel alive. Truecolor terminals get the smooth flow; 8-color
* fallbacks just see all-cyan, which is still legible.
*/
function Wordmark({
busy: _busy,
animate: _animate,
}: {
busy: boolean;
animate: boolean;
}) {
// Static gradient. The brand sweep teal → fuchsia is precomputed
// once per render — no useTick subscription, no per-tick
// re-render. Earlier versions flowed the colors over time, but
// the per-tick re-render interleaved badly with terminal resize
// (Ink's eraseLines misjudges row count when bars / wide text
// wrap, ghost frames stack). Keeping this static eliminates the
// multiplier; resize artifacts at most leave a single stale
// frame instead of N.
return (
<Text>
<Text color={GRADIENT[0]} bold>
◈
</Text>
<Text> </Text>
{WORDMARK_LETTERS.map((letter, i) => (
<Text key={letter} color={GRADIENT[i % GRADIENT.length]} bold>
{letter}
</Text>
))}
</Text>
);
}
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;
/**
* Edit-gate mode. Surfaced as a small pill in the header so the user
* can see at a glance whether edits will be queued for review or
* applied immediately. Omitted in chat (non-code) mode.
*/
editMode?: EditMode;
/**
* Account balance fetched once at launch (and optionally refreshed
* per-turn by the TUI). `null` or absent hides the balance cell
* 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."
*/
balance?: { currency: string; total: number } | null;
/**
* Published npm version newer than VERSION. Rendered as a yellow
* "· update: X" nudge in the panel header. `null` / `undefined`
* hides the nudge (offline launch, already up to date, or check
* still in flight).
*/
updateAvailable?: string | null;
/**
* True when the loop is currently mid-turn — drives the wordmark's
* "busy breathing" animation. Visual signal that the app is thinking,
* visible at a glance from anywhere on screen.
*/
busy?: boolean;
/**
* /pro is queued — the next turn will run on v4-pro regardless of
* `model`. Rendered as a yellow `⇧ pro armed` pill in the header so
* the user has a clear "this turn will be expensive" signal before
* submitting their message.
*/
proArmed?: boolean;
/**
* The CURRENT turn is running on v4-pro because the failure-
* escalation threshold fired mid-turn. Rendered as a red `⇧ pro
* escalated` pill. Clears at turn end.
*/
escalated?: boolean;
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;
// No gradient bars, no animation. Earlier versions had truecolor
// gradient rules top+bottom and a tick-driven wordmark/bar flow,
// but those are exactly the elements Ink's eraseLines miscounts
// on resize: ~100-char gradient strings wrap 2-3 visual rows at
// narrow widths, the per-tick re-render writes new frames before
// the stale rows are erased, and ghost panels stack vertically
// (the user-reported "刷屏" / multi-frame artifact). Fixed-row
// panel + no per-tick churn keeps Ink's row math honest.
return (
<Box flexDirection="column" paddingX={1} marginBottom={1}>
<Header
model={model}
prefixHash={prefixHash}
harvestOn={harvestOn}
branchOn={branchOn}
branchBudget={branchBudget ?? 1}
reasoningEffort={reasoningEffort}
planMode={planMode}
<Box flexDirection="column" paddingX={1}>
<ChromeRow
editMode={editMode}
turns={summary.turns}
updateAvailable={updateAvailable}
narrow={narrow}
busy={busy ?? false}
planMode={planMode}
proArmed={proArmed ?? false}
escalated={escalated ?? false}
animate={false}
summary={summary}
coldStart={coldStart}
rootDir={rootDir}
sessionName={sessionName ?? null}
updateAvailable={updateAvailable}
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}
/>
)}
<ChromeRule />
{budgetUsd !== null && budgetUsd !== undefined ? (
<BudgetRow spent={summary.totalCostUsd} cap={budgetUsd} />
) : null}
</Box>
);
}
function Header({
model,
prefixHash,
harvestOn,
branchOn,
branchBudget,
reasoningEffort,
planMode,
function ChromeRow({
editMode,
turns,
updateAvailable,
narrow,
busy,
planMode,
proArmed,
escalated,
animate,
summary,
coldStart,
rootDir,
sessionName,
updateAvailable,
balance,
}: {
model: string;
prefixHash: string;
harvestOn?: boolean;
branchOn: boolean;
branchBudget: number;
reasoningEffort?: "high" | "max";
planMode?: boolean;
editMode?: EditMode;
turns: number;
updateAvailable?: string | null;
narrow: boolean;
busy: boolean;
planMode?: boolean;
proArmed: boolean;
escalated: boolean;
/** When false, suppress optional pills + animation to avoid wraps. */
animate: boolean;
summary: SessionSummary;
coldStart: boolean;
rootDir?: string;
sessionName?: string | null;
updateAvailable?: string | null;
balance?: { currency: string; total: number } | null;
}) {
// Mode pill — pick the most informative one to surface in the
// header. PLAN beats AUTO/review beats nothing. Pro armed/escalated
// gets its own pill alongside.
const modePill = planMode
? { label: "PLAN", bg: "red" as const }
: editMode === "auto"
? { label: "AUTO", bg: "magenta" as const }
: editMode === "review"
? { label: "REVIEW", bg: "cyan" as const }
: null;
const modePill = pickModePill(planMode, editMode);
const proPill = escalated
? { label: "⇧ PRO", bg: "red" as const }
? { label: "⇧ pro", color: COLOR.err }
: proArmed
? { label: "⇧ PRO", bg: "yellow" as const }
? { label: "⇧ pro", color: COLOR.warn }
: null;
// Narrow / non-animate mode hides the secondary pills (harvest,
// branch, reasoning effort) so the header always fits on one
// visual row. Wrapping the header is the main amplifier of the
// eraseLines miscount that produces the "screen flashing" effect.
const showSecondary = animate && !narrow;
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 (
<Box justifyContent="space-between">
<Box>
<Wordmark busy={busy} animate={animate} />
<Text dimColor>{` ${VERSION}`}</Text>
<Text dimColor>{" "}</Text>
<Text color="yellow" bold>
{model.replace(/^deepseek-/, "")}
</Text>
{modePill ? (
<>
<Text>{" "}</Text>
<Pill label={modePill.label} bg={modePill.bg} />
</>
) : null}
{proPill ? (
<>
<Text>{" "}</Text>
<Pill label={proPill.label} bg={proPill.bg} />
</>
) : null}
{showSecondary && harvestOn ? (
<Text dimColor>
<Text>{" "}</Text>
<Text color="magenta">harvest</Text>
<Box>
<Text bold color={GRADIENT[0]}>
{"◈ "}
</Text>
<Text color={COLOR.brand} bold>
reasonix
</Text>
{projectName ? (
<>
<Text color={COLOR.info} dimColor>
{" · "}
</Text>
) : null}
{showSecondary && branchOn ? (
<Text dimColor>
<Text>{" "}</Text>
<Text color="blue">{`branch×${branchBudget}`}</Text>
</Text>
) : null}
{showSecondary && reasoningEffort === "max" ? (
<>
<Text>{" "}</Text>
<Text color="green" dimColor>
max
</Text>
</>
) : null}
{showSecondary && reasoningEffort === "high" ? (
<>
<Text>{" "}</Text>
<Text color="yellow" dimColor>
high
</Text>
</>
) : null}
</Box>
<Text>
{updateAvailable ? <Text color="yellow" bold>{`↑ ${updateAvailable} `}</Text> : null}
<Text dimColor>{narrow ? `t${turns}` : `turn ${turns} · /help`}</Text>
</Text>
</Box>
);
}
/** Solid-background tag, used for primary mode + pro indicators. */
function Pill({ label, bg }: { label: string; bg: "red" | "magenta" | "cyan" | "yellow" }) {
return (
<Text backgroundColor={bg} color="white" bold>
{` ${label} `}
</Text>
);
}
/**
* Wide-terminal layout (≥120 cols): single metrics row. Matches the
* original panel, just with calmer spacing and the cold-start
* treatment folded in.
*/
function InlineMetrics({
summary,
ctxRatio,
ctxMax,
balance,
coldStart,
}: {
summary: SessionSummary;
ctxRatio: number;
ctxMax: number;
balance?: { currency: string; total: number } | null;
coldStart: boolean;
}) {
return (
<Box marginTop={1} gap={3}>
<ContextCell ratio={ctxRatio} promptTokens={summary.lastPromptTokens} ctxMax={ctxMax} />
<CacheCell hitRatio={summary.cacheHitRatio} coldStart={coldStart} turns={summary.turns} />
<CostCell summary={summary} coldStart={coldStart} />
{balance ? <BalanceCell balance={balance} /> : null}
</Box>
);
}
/**
* Narrow-terminal layout (<120 cols): one metric per line, in priority
* order (ctx → balance → cache → cost). Order matters because users
* scanning a cramped terminal want "am I about to hit a wall?" answered
* first; dollars spent comes later.
*/
function StackedMetrics({
summary,
ctxRatio,
ctxMax,
balance,
coldStart,
}: {
summary: SessionSummary;
ctxRatio: number;
ctxMax: number;
balance?: { currency: string; total: number } | null;
coldStart: boolean;
}) {
return (
<Box marginTop={1} flexDirection="column">
<ContextCell
ratio={ctxRatio}
promptTokens={summary.lastPromptTokens}
ctxMax={ctxMax}
showBar
/>
{balance ? <BalanceCell balance={balance} /> : null}
<CacheCell hitRatio={summary.cacheHitRatio} coldStart={coldStart} turns={summary.turns} />
<CostCell summary={summary} coldStart={coldStart} />
</Box>
);
}
function ContextCell({
ratio,
promptTokens,
ctxMax,
showBar,
}: {
ratio: number;
promptTokens: number;
ctxMax: number;
showBar?: boolean;
}) {
if (promptTokens === 0) {
return (
<Text>
<Text color={COLOR.info} dimColor>
{"▣ ctx "}
</Text>
<Text dimColor>— (no turns yet)</Text>
</Text>
);
}
const color = ratio >= 0.8 ? COLOR.err : ratio >= 0.6 ? COLOR.warn : COLOR.ok;
const pct = Math.round(ratio * 100);
return (
<Text>
<Text color={COLOR.info}>{"▣ ctx "}</Text>
<Bar ratio={ratio} color={color} cells={showBar ? 14 : 10} />
<Text> </Text>
<Text color={color} bold>
{formatTokens(promptTokens)}/{formatTokens(ctxMax)}
</Text>
<Text dimColor> ({pct}%)</Text>
{ratio >= 0.8 ? (
<Text color={COLOR.err} bold>
{" · /compact"}
</Text>
<Text>{projectName}</Text>
{showSession && sessionName ? (
<>
<Text color={COLOR.info} dimColor>
{" › "}
</Text>
<Text color={COLOR.info}>{sessionName}</Text>
</>
) : null}
</>
) : null}
</Text>
<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 CacheCell({
hitRatio,
coldStart,
turns,
}: {
hitRatio: number;
coldStart: boolean;
turns: number;
}) {
const pct = (hitRatio * 100).toFixed(1);
if (turns === 0) {
return (
<Text>
<Text color={COLOR.info} dimColor>
{"⌬ cache "}
</Text>
<Text dimColor>—</Text>
</Text>
);
}
if (coldStart) {
return (
<Text>
<Text color={COLOR.info} dimColor>
{"⌬ cache "}
</Text>
<Text dimColor>{pct}% </Text>
<Text dimColor italic>
(cold start)
</Text>
</Text>
);
}
const color = hitRatio >= 0.7 ? COLOR.ok : hitRatio >= 0.4 ? COLOR.warn : COLOR.err;
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 color={COLOR.info}>{"⌬ cache "}</Text>
<Text color={color} bold>
{pct}%
<Box>
<Text dimColor>{" budget "}</Text>
<Text color={color}>
{`$${spent.toFixed(4)} / $${cap.toFixed(2)}`}
<Text dimColor>{` (${pct.toFixed(0)}%)`}</Text>
</Text>
</Text>
</Box>
);
}
/**
* Color thresholds. Per-turn and session cumulative scale roughly 10×
* apart — a $0.20 single turn should feel just as warn-worthy as a $2
* session total. Values are rough "notice this" points, not hard caps.
*/
function turnCostColor(cost: number): string | undefined {
if (cost <= 0) return undefined;
if (cost >= 0.2) return COLOR.err;
if (cost >= 0.05) return COLOR.warn;
return COLOR.ok;
}
function sessionCostColor(cost: number): string | undefined {
if (cost <= 0) return undefined;
if (cost >= 5) return COLOR.err;
if (cost >= 0.5) return COLOR.warn;
return COLOR.ok;
}
function CostCell({
summary,
coldStart,
}: {
summary: SessionSummary;
coldStart: boolean;
}) {
if (summary.turns === 0) {
return (
<Text>
<Text color={COLOR.info} dimColor>
{"◴ cost "}
</Text>
<Text dimColor>—</Text>
</Text>
);
}
// The first turn is unavoidably a cache-miss (nothing to hit),
// so the dollar figure is front-loaded. Muting it during the
// cold-start window keeps the "expensive first turn" from
// reading as "something is wrong."
const turnColor = coldStart ? undefined : turnCostColor(summary.lastTurnCostUsd);
const sessionColor = coldStart ? undefined : sessionCostColor(summary.totalCostUsd);
return (
<Text>
<Text color={COLOR.info}>{"◴ turn "}</Text>
<Text color={turnColor} bold={!coldStart} dimColor={coldStart}>
${summary.lastTurnCostUsd.toFixed(4)}
</Text>
<Text dimColor>{" · session "}</Text>
<Text color={sessionColor} bold={!coldStart} dimColor={coldStart}>
${summary.totalCostUsd.toFixed(4)}
</Text>
</Text>
);
}
function BalanceCell({ balance }: { balance: { currency: string; total: number } }) {
const color = balance.total < 1 ? COLOR.err : balance.total < 5 ? COLOR.warn : COLOR.ok;
return (
<Text>
<Text color={COLOR.info}>{"◐ balance "}</Text>
<Text color={color} bold>
{balance.currency === "USD" ? "$" : ""}
{balance.total.toFixed(2)}
{balance.currency !== "USD" ? ` ${balance.currency}` : ""}
</Text>
</Text>
);
}
/**
* Truecolor progress bar. Filled cells use the threshold color (green
* → amber → rose) so the bar communicates pressure at a glance;
* empty cells use a dim shade so the empty portion is visible
* without dominating. ▰/▱ have distinct shapes (filled vs hollow)
* so the boundary is clear even when colors snap to 8-color slots
* on legacy terminals.
*/
function Bar({
ratio,
color,
cells = 14,
}: {
ratio: number;
color: string;
cells?: number;
}) {
const filled = Math.max(0, Math.min(cells, Math.round(ratio * cells)));
return (
<Text>
<Text color={color}>{"▰".repeat(filled)}</Text>
<Text dimColor>{"▱".repeat(cells - filled)}</Text>
</Text>
);
}
/**
* Compact token formatter using binary K (÷1024): 1234 → "1.2K",
* 131072 → "128K". Matches DeepSeek's marketing label of "128K context
* length" — showing "131k" confused users (the actual limit is
* 128×1024 = 131,072 tokens, but the doc consistently says "128K").
* Uppercase K signals binary-K to anyone who notices.
*/
function formatTokens(n: number): string {
if (n < 1024) return String(n);
const k = n / 1024;
return k >= 100 ? `${k.toFixed(0)}K` : `${k.toFixed(1)}K`;
}
+145 -93
View File
@@ -1,113 +1,165 @@
/**
* Welcome card on the empty session. The first thing a user sees
* after launching `reasonix code` — needs to communicate, in the
* ~5 seconds before they type, three things: brand, what to type,
* how to escape. Card framing uses a gradient top rule + left-side
* accent bar + sectioned hints so it reads as a designed surface
* rather than a bare list. No bordered Boxes — those amplified
* Ink's Windows eraseLines miscount.
* 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";
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React in value scope
import React from "react";
import { COLOR, gradientCells } from "./theme.js";
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;
}
export function WelcomeBanner({ inCodeMode }: WelcomeBannerProps): React.ReactElement {
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;
const ruleWidth = Math.min(60, Math.max(28, cols - 4));
// 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" paddingX={1} marginY={1}>
<GradientRule width={ruleWidth} />
<BarRow>
<Text bold color={COLOR.brand}>
◈ welcome
<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>
<Text dimColor>{" · type a message to start"}</Text>
</BarRow>
<BarRow />
<BarRow>
<Text bold color={COLOR.primary}>
quick start
</Text>
</BarRow>
<Hint cmd="/help" desc="every command + keyboard shortcut" />
<Hint cmd="/skill" desc="invoke a stored playbook" />
{inCodeMode ? (
<>
<Hint cmd="@path" desc="inline a file in your message" />
<Hint cmd="!cmd" desc="run a shell command, output goes to context" />
</>
) : null}
<Hint cmd="/exit" desc="quit (Ctrl+C also works)" />
<BarRow />
<BarRow>
<Text dimColor italic>
tip:
</Text>
<Text dimColor>{" Ctrl+J inserts a newline · trailing \\ also continues"}</Text>
</BarRow>
{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}>
<GradientRule width={ruleWidth} thin />
<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>
);
}
/**
* One-line gradient rule. `thin` swaps the half-block top/bottom so
* the top of the card reads as a "header band" (▄ — bottom-half
* filled) and the bottom as "section close" (▁ — minimal pixel
* row). Same primitive the StatsPanel uses, kept consistent.
*/
function GradientRule({ width, thin }: { width: number; thin?: boolean }) {
const cells = gradientCells(width, thin ? "▁" : "▄");
return (
<Box>
{cells.map((c, i) => (
// biome-ignore lint/suspicious/noArrayIndexKey: fixed-width gradient row, never reordered
<Text key={`wrule-${i}`} color={c.color}>
{c.ch}
</Text>
))}
</Box>
);
}
/**
* Card row — left-side accent bar followed by content. Children
* optional so we can use this for blank spacer rows (bar only).
*/
function BarRow({ children }: { children?: React.ReactNode }) {
return (
<Box>
<Text color={COLOR.brand} bold>
▎
</Text>
<Text> </Text>
{children}
</Box>
);
}
/**
* Single hint row — bold accent cmd token + dim description.
* Padded so all cmd tokens line up regardless of length, like a
* man-page synopsis.
*/
function Hint({ cmd, desc }: { cmd: string; desc: string }) {
return (
<BarRow>
<Text bold color={COLOR.accent}>
{cmd.padEnd(8)}
</Text>
<Text dimColor>{` ${desc}`}</Text>
</BarRow>
);
}
+3 -3
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: {},
});
@@ -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>
);
}
+7 -68
View File
@@ -1,39 +1,21 @@
import { formatAllBlockDiffs } from "../../code/diff-preview.js";
import type { ApplyResult, EditBlock, EditSnapshot } from "../../code/edit-blocks.js";
/**
* One batch of edits that actually landed on disk — durable enough for
* `/undo`, `/history`, and `/show` within a session. Not persisted
* across restarts: restoring pre-apply content from a process that
* crashed last week is git's job, not ours.
*/
/** 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;
/**
* Short tag for what produced the batch — "auto" (auto-mode tool
* call), "auto-text" (auto-mode text SEARCH/REPLACE at turn end),
* "review-apply" (user-approved modal edit or /apply flush).
*/
/** 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: this is what `/undo` restores to.
* Deduped so multi-edit turns still roll back to pre-turn state.
*/
/** First-snapshot-per-path wins — multi-edit turns roll back to pre-turn state. */
snapshots: EditSnapshot[];
/**
* Paths within this entry that have already been reverted (via
* `/undo <id>`, `/undo <id> <path>`, or the newest-non-undone /undo
* shortcut). Per-path instead of entry-level so a batch can be
* partially undone — user reverts src/foo.ts out of a 3-file batch
* without rolling back the other two.
*/
/** Per-path so a multi-file batch can be partially undone. */
undoneFiles: Set<string>;
}
@@ -49,15 +31,7 @@ export function entryStatus(e: EditHistoryEntry): "applied" | "UNDONE" | "PARTIA
return "PARTIAL";
}
/**
* Render a batch of SEARCH/REPLACE application results as one
* human-scannable info line per edit. Prefixes denote status so the
* line reads well even without color (e.g. when piped to a log file
* or stripped for screenshots):
* ✓ applied src/foo.ts
* ✓ created src/new.ts
* ✗ not-found src/bar.ts (SEARCH text does not match…)
*/
/** 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" ? "✓" : "✗";
@@ -70,18 +44,7 @@ export function formatEditResults(results: ApplyResult[]): string {
return [header, ...lines].join("\n");
}
/**
* Pending-edits preview shown after each assistant turn that proposed
* changes. Per-block path header + ±line-count, then a unified-diff-
* style preview (context trimmed to 2 lines each side, total capped
* at 20 lines per block). Users can eyeball what's about to land
* BEFORE pressing `y` — the old summary-only view was a common
* mistake surface.
*
* Each block gets a `[N]` label so users can target a subset via
* `/apply 1` / `/apply 1,3-4` / `/discard 2` instead of being forced
* into all-or-nothing.
*/
/** `[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}`;
@@ -89,21 +52,7 @@ export function formatPendingPreview(blocks: EditBlock[]): string {
return [header, ...diffLines].join("\n");
}
/**
* Parse a `/apply <N>` / `/discard <N>` argument into a deduplicated,
* sorted list of 1-based indices. Accepts:
* - single value: `"3"` → [3]
* - comma list: `"1,3,5"` → [1, 3, 5]
* - range: `"2-4"` → [2, 3, 4]
* - mixed: `"1,3-5,7"` → [1, 3, 4, 5, 7]
* - whitespace + trailing commas tolerated.
*
* Bounds-checked against `max` (the count of pending blocks); any
* out-of-range or malformed token returns `{ error }` so the caller
* can surface a usage hint instead of silently applying the wrong
* subset. Empty input returns `{ ok: [] }` so callers can detect
* "user passed no indices" and treat that as the all-blocks default.
*/
/** 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: [] };
@@ -137,12 +86,6 @@ export function parseEditIndices(raw: string, max: number): { ok: number[] } | {
return { ok: [...seen].sort((a, b) => a - b) };
}
/**
* Partition `edits` into the subset addressed by `indices1Based` and
* everything else (preserves original order). Pure helper so the
* pending-edits queue can be sliced from the slash handler in App.tsx
* without any React-state plumbing in the test path.
*/
export function partitionEdits<T>(
edits: readonly T[],
indices1Based: readonly number[],
@@ -157,10 +100,6 @@ export function partitionEdits<T>(
return { selected, remaining };
}
/**
* Per-file rows for the multi-level `/undo` output, without the
* single-batch header (the caller prepends its own).
*/
export function formatUndoRows(results: ApplyResult[]): string[] {
return results.map((r) => {
const mark = r.status === "applied" ? "✓" : "✗";
+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>
))}
</>
);
}
+3 -61
View File
@@ -1,32 +1,9 @@
/**
* Hash-mode (`#note` / `#g note`) prefix parsing — instant memory write.
*
* A `#` at the start of the user's input writes a one-liner to memory
* pinned in the prefix from now on. Two scopes:
*
* - `#<note>` → project memory `<rootDir>/REASONIX.md`
* (committable, team-shared)
* - `#g <note>` → global memory `~/.reasonix/REASONIX.md`
* (private, cross-project — never committed)
*
* Same idea as Claude Code's `#` prefix — faster than going through
* a `/memory remember ...` slash for a one-liner like "always use pnpm".
*
* Trigger shape:
* - `#` followed by zero-or-more spaces, then a non-empty body
* - NOT `##` / `###` / etc. — those stay markdown headings to the model
* - `\#foo` escape → not a memory write, leading backslash stripped before
* submission so the model sees `#foo` literally
*
* Each call appends one bullet at the bottom; we don't try to parse
* section structure. The user can reorganize manually whenever they
* want.
*/
/** `#` 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 "../../project-memory.js";
import { PROJECT_MEMORY_FILE } from "../../memory/project.js";
const PROJECT_HEADER = `# Reasonix project memory
@@ -43,32 +20,12 @@ Private to this machine — not committed anywhere.
`;
/**
* Result of `detectHashMemory`.
*
* - `kind: "memory"` — input is `#<note>`; write to project REASONIX.md.
* - `kind: "memory-global"` — input is `#g <note>`; write to global file.
* - `kind: "escape"` — input started with `\#`; submit `#foo` literally.
* - returning `null` — input is unrelated to hash mode.
*/
export type HashMemoryParse =
| { kind: "memory"; note: string }
| { kind: "memory-global"; note: string }
| { kind: "escape"; text: string };
/**
* Classify a hash-prefixed input. Pure — no filesystem touch — so it's
* trivially testable and can run before any I/O decision in handleSubmit.
*
* Order of checks matters:
* 1. `\#…` escape (so `\#g foo` ALSO escapes — user can send `#g foo`
* to the model verbatim).
* 2. `##…` markdown heading (level-2+ passes through unchanged).
* 3. `#g <body>` — global memory. Requires whitespace after the `g` so
* a note that happens to start with `g` (e.g. `#good idea`) doesn't
* route to global by accident.
* 4. `#<body>` — project memory.
*/
/** 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) };
@@ -103,12 +60,6 @@ export interface AppendMemoryResult {
created: boolean;
}
/**
* Append `note` as a single bullet to `<rootDir>/REASONIX.md`. Creates
* the file with a short header when absent. Inserts a leading newline
* if the existing file doesn't end with one, so bullets don't collide
* with the previous section's last line.
*/
export function appendProjectMemory(rootDir: string, note: string): AppendMemoryResult {
return appendBulletToFile(join(rootDir, PROJECT_MEMORY_FILE), note, PROJECT_HEADER);
}
@@ -116,19 +67,10 @@ export function appendProjectMemory(rootDir: string, note: string): AppendMemory
export const GLOBAL_MEMORY_DIR = ".reasonix";
export const GLOBAL_MEMORY_FILE = "REASONIX.md";
/**
* Resolve the path to the global memory file. Defaults to
* `~/.reasonix/REASONIX.md`; callers (mainly tests) can override the
* home dir to point at a tmpdir.
*/
export function globalMemoryPath(homeDir: string = homedir()): string {
return join(homeDir, GLOBAL_MEMORY_DIR, GLOBAL_MEMORY_FILE);
}
/**
* Append `note` to `~/.reasonix/REASONIX.md`. Creates the parent
* directory + file if either is missing.
*/
export function appendGlobalMemory(note: string, homeDir?: string): AppendMemoryResult {
return appendBulletToFile(globalMemoryPath(homeDir), note, GLOBAL_HEADER);
}
+6 -77
View File
@@ -1,47 +1,7 @@
/**
* CSI sequence recovery for Ink's `useInput`.
*
* Why this exists. Ink delivers keyboard events through `parse-keypress`,
* which reads stdin and recognises ANSI control-sequence-introducer
* (CSI) sequences with a state machine plus a short timeout. On most
* terminals this works: the byte stream `\x1b [ A` arrives in one
* read, parse-keypress emits `{key.upArrow:true, input:""}`, life is
* good.
*
* On Windows PowerShell + ConPTY (and a handful of embedded shells)
* the bytes don't always arrive together. parse-keypress's timeout
* expires between chunks, so it dispatches the lone `\x1b` as
* `key.escape:true` and then dispatches the trailing `[A` as a
* regular character event — `input:"[A", key.upArrow:undefined`. The
* useInput consumer sees `[A` as plain text, inserts it into the
* buffer, and the cursor never moves. Same shape on `[C` (right
* arrow), `[Z` (Shift+Tab), `[5~` (PgUp), `[201~` (bracketed-paste
* end), etc.
*
* Every Reasonix UI component that calls `useInput` is exposed to
* this. Patching each one to re-recognise the bare CSI tail was
* fragile — every release a new symptom appeared (cursor stuck,
* paste markers leaking, Shift+Tab not toggling). So this module is
* the single source of truth for CSI recovery: every input handler
* runs the raw event through `recoverCsiTail` before reading
* structured key flags.
*
* Recovery is conservative. We only rewrite when:
* 1. None of the structured key flags Ink already populated for
* this event is set (so a real upArrow press isn't second-
* guessed).
* 2. `input` exactly matches a recognised tail in either form —
* the full `\x1b[X` sequence (in case the timeout merged it)
* or the bare `[X` ConPTY-stripped variant.
*
* Anything else passes through unchanged.
*/
/** 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. */
/**
* Subset of Ink's `Key` interface that contains the structured flags
* we know how to recover. Optional everywhere because callers from
* different Ink versions may not populate every field.
*/
/** Structured-flag subset of Ink's Key — optional across Ink versions. */
export interface CsiKeyFlags {
upArrow?: boolean;
downArrow?: boolean;
@@ -54,14 +14,7 @@ export interface CsiKeyFlags {
tab?: boolean;
}
/**
* CSI tails we recognise. Each maps the printable bytes of a CSI
* tail (the part after the `\x1b`) to the structured key flags they
* should set. Bracketed-paste markers `[200~` / `[201~` are
* intentionally absent — they're handled by PromptInput's paste
* accumulator, which has different semantics (collect content
* between markers rather than emit one keystroke).
*/
/** 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 } },
@@ -77,11 +30,6 @@ const CSI_TAIL_TO_FLAGS: ReadonlyArray<{ tail: string; flags: CsiKeyFlags }> = [
{ tail: "[Z", flags: { shift: true, tab: true } },
];
/**
* Did Ink already give us a structured key for this event? When
* `true`, recovery is unnecessary and would risk overriding a real
* keypress that happens to share `input` with a CSI tail.
*/
function alreadyStructured(flags: CsiKeyFlags): boolean {
return Boolean(
flags.upArrow ||
@@ -95,15 +43,7 @@ function alreadyStructured(flags: CsiKeyFlags): boolean {
);
}
/**
* If `input` is a recognisable CSI tail (with or without the leading
* `\x1b`), return the structured flags it should produce. Otherwise
* `null`. Bracketed-paste markers always return `null` here — those
* are handled by their own accumulator.
*
* Pure function. Pass already-structured events through (they
* short-circuit) so a real arrow press doesn't get rewritten.
*/
/** 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) {
@@ -114,18 +54,7 @@ export function recoverCsiTail(input: string, existing: CsiKeyFlags = {}): CsiKe
return null;
}
/**
* Tail forms (with and without the leading `\x1b`) that should never
* end up as literal text in a user's prompt buffer. Used as a final
* defensive pass before treating input as printable — if a CSI
* fragment slipped past structured-key recovery (e.g. arrived
* embedded inside a paste burst), at least drop the raw bytes
* rather than insert them as garbage text.
*
* Includes the bracketed-paste markers `[200~` / `[201~` because a
* paste whose start/end markers got chunked across reads can leave
* those bytes in the printable input.
*/
/** Includes paste `[200~`/`[201~` for the case where their markers chunked across reads. */
export const STRIPPABLE_CSI_FRAGMENTS: readonly string[] = [
"\u001b[200~",
"\u001b[201~",
+26 -12
View File
@@ -20,6 +20,7 @@
* — 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";
@@ -82,20 +83,9 @@ export function KeystrokeProvider({
return <KeystrokeContext.Provider value={busRef.current}>{children}</KeystrokeContext.Provider>;
}
/**
* Subscribe to keystroke events. Mirrors Ink's `useInput` shape —
* `handler(ev)` runs on every event while `isActive` is truthy
* (default true). Set `isActive=false` to suspend the handler
* (e.g. while a modal is up and shouldn't respond to global keys).
*
* Handler identity changes are tolerated — we re-subscribe via
* useEffect on every render. Wrap your handler in `useCallback` if
* you want to avoid that.
*/
/** 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);
// Latest-handler ref so we can subscribe ONCE per active toggle
// and still call the freshest closure on each event.
const handlerRef = useRef(handler);
handlerRef.current = handler;
@@ -103,6 +93,30 @@ export function useKeystroke(handler: KeystrokeHandler, isActive = true): void {
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 },
);
}
/**
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>
);
}
+2 -70
View File
@@ -1,50 +1,11 @@
/**
* `/loop <interval> <prompt>` parsing + status formatting.
*
* Claude-Code-style recurring prompt: at every `<interval>` tick, the
* App auto-submits `<prompt>` as if the user typed it. Useful for "keep
* checking the deploy" / "rerun tests" / "watch the build status until
* green" — anything the user wants probed periodically without holding
* the keyboard.
*
* Cancellation contract (enforced in App.tsx, not here — this file is
* pure):
* - `/loop stop` → explicit stop slash
* - user types anything else → loop dies, user takes over
* - Esc / /new / /clear / exit → loop dies
* - one loop per session → re-issuing /loop replaces the prior
*
* Interval bounds:
* - Minimum: 5 seconds (anything tighter and the model couldn't even
* finish a turn before the next firing — we'd queue submits and
* drift forever).
* - Maximum: 6 hours (the upper end of "let it run while I sleep";
* beyond that you should be writing a cron, not a TUI loop).
*/
/** 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;
/**
* Parse a duration string into milliseconds.
*
* Accepted forms (case-insensitive on the unit):
* - `45` → 45_000 (bare number = seconds)
* - `30s` → 30_000
* - `5m` → 300_000
* - `2h` → 7_200_000
* - `1.5m` → 90_000 (fractional supported)
*
* Returns `null` on:
* - empty input
* - non-numeric / unknown unit
* - negative or zero values
* - values outside [MIN_LOOP_INTERVAL_MS, MAX_LOOP_INTERVAL_MS]
*
* Caller surfaces `null` as a usage hint to the user. Pure.
*/
/** 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;
@@ -68,22 +29,6 @@ export interface ParsedLoopArgs {
prompt: string;
}
/**
* Parse the full `/loop <interval> <prompt>` invocation. Args is the
* commander-style tail (already split on whitespace, slash command
* stripped). Returns `null` when the shape is wrong; caller emits a
* usage hint.
*
* Special tokens:
* - `stop` (case-insensitive) as the only arg → caller should stop
* the active loop. Returns a sentinel: `{ stop: true }`.
* - empty args → returns `{ status: true }` so the caller can print
* the active-loop status (or "no loop active").
*
* Otherwise the first token is the interval, the rest is the prompt.
* The prompt may itself be a slash command (`/loop 30s /status` is a
* valid way to keep refreshing the status panel).
*/
export type LoopCommand =
| { kind: "start"; intervalMs: number; prompt: string }
| { kind: "stop" }
@@ -116,25 +61,12 @@ export function parseLoopCommand(args: readonly string[]): LoopCommand {
return { kind: "start", intervalMs: interval.ms, prompt };
}
/**
* Format the active loop into a single-line status pill for the
* modeline. `nextFireMs` is wall-clock ms until next firing; the
* caller computes it from the stored `nextFireAt - Date.now()`.
*
* Examples:
* "loop: `npm test` · next in 28s · iter 3"
* "loop: `check deploy status` · firing now · iter 1"
*/
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}`;
}
/**
* Human-friendly duration. Used by the loop status pill so a 4-minute
* 23-second wait reads as "4m23s" instead of "263000".
*/
export function formatDuration(ms: number): string {
if (ms < 1000) return `${ms}ms`;
const totalSec = Math.round(ms / 1000);
+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);
}
+87 -6
View File
@@ -63,7 +63,39 @@ function toSubscript(s: string): string {
return out;
}
/**
* Math indicator regex — gates the LaTeX-stripping pipeline so plain
* prose with literal backslashes (Windows paths, escape sequences in
* code prose) doesn't get mauled by the catch-all `\[a-zA-Z]+ → ""`
* fallback at the bottom of stripMath.
*
* Without this guard, "F:\TEST1" got rendered as "F:1" because the
* catch-all interpreted `\TEST` as an unknown LaTeX command and
* deleted it. We only run the pipeline when the text actually
* contains math markers we recognize: $-delimited spans, `\(`/`\[`
* paren-delimiters, or one of the explicit LaTeX command names the
* pipeline knows how to translate. Anything else passes through
* untouched.
*/
const HAS_MATH_RE = new RegExp(
[
"\\$", // dollar-delimited (block or inline)
"\\\\[([]", // \( or \[
"\\\\[a-zA-Z]+\\s*\\{", // \anyCommand{...} — covers catch-all braced transforms
// Bare (no-brace) LaTeX commands the pipeline knows how to handle.
// Listed explicitly because a generic `\\[a-zA-Z]+` would also match
// Windows paths (`F:\TEST1`) and re-introduce the bug we're fixing.
"\\\\(?:cdot|times|div|pm|mp|leq|geq|neq|approx|in|notin|infty|sum|prod|int|alpha|beta|gamma|delta|theta|lambda|mu|pi|sigma|phi|omega|implies|iff|to|rightarrow|leftarrow|Rightarrow|Leftarrow|ldots|cdots|quad|qquad)(?![a-zA-Z])",
"[\\^_]\\{", // LaTeX braced super/subscript: ^{2}, _{ij}
"\\^[0-9+\\-n](?![A-Za-z])", // LaTeX single-char super: ^2, ^-, ^n
"_[0-9+\\-](?![A-Za-z])", // LaTeX single-char sub: _1, _+, _-
"\\^[A-Za-z0-9+\\-]+\\^", // Pandoc super: ^2^, ^abc^
"(?<!~)~[A-Za-z0-9+\\-]+~(?!~)", // Pandoc sub: ~2~ (lookarounds avoid ~~strike~~)
].join("|"),
);
export function stripMath(s: string): string {
if (!HAS_MATH_RE.test(s)) return s;
return (
s
// Dollar-delimited math (KaTeX / MathJax convention). Block
@@ -407,6 +439,42 @@ function extOf(p: string): string {
return m ? m[0] : "";
}
/**
* mtime-keyed line-count cache. The expensive part of validating a
* citation with a line number is reading the entire file just to
* count newlines — for a 5k-line source file, that's a real
* synchronous read on every assistant_final commit that cites it.
* Across a session, the model often cites the same file repeatedly
* (the file it's currently editing), so the same read happens N
* times for the same file content.
*
* We cache `lineCount` keyed by absolute path, and invalidate by
* comparing `mtimeMs` against the latest `statSync` (which we're
* already calling for the file-exists check, so the cache hit is
* free). Cap entries to 256 to avoid unbounded growth across long
* sessions; LRU-evict on overflow with a simple FIFO since hot
* citations get re-inserted on use anyway.
*/
const lineCountCache = new Map<string, { mtimeMs: number; lineCount: number }>();
const LINE_COUNT_CACHE_LIMIT = 256;
function getCachedLineCount(fullPath: string, mtimeMs: number): number | null {
const hit = lineCountCache.get(fullPath);
if (!hit || hit.mtimeMs !== mtimeMs) return null;
// Refresh insertion order so this entry is "hot" for FIFO eviction.
lineCountCache.delete(fullPath);
lineCountCache.set(fullPath, hit);
return hit.lineCount;
}
function setCachedLineCount(fullPath: string, mtimeMs: number, lineCount: number): void {
if (lineCountCache.size >= LINE_COUNT_CACHE_LIMIT) {
const oldest = lineCountCache.keys().next().value;
if (oldest !== undefined) lineCountCache.delete(oldest);
}
lineCountCache.set(fullPath, { mtimeMs, lineCount });
}
export function validateCitation(url: string, projectRoot: string): CitationStatus {
const parts = parseCitationUrl(url);
if (!parts || !parts.path) return { ok: false, reason: "empty path" };
@@ -444,11 +512,14 @@ export function validateCitation(url: string, projectRoot: string): CitationStat
if (!stat) return { ok: false, reason: "file not found" };
if (!stat.isFile()) return { ok: false, reason: "not a file" };
if (parts.startLine === undefined) return { ok: true };
let lineCount: number;
try {
lineCount = readFileSync(fullPath, "utf8").split("\n").length;
} catch {
return { ok: false, reason: "unreadable" };
let lineCount = getCachedLineCount(fullPath, stat.mtimeMs);
if (lineCount === null) {
try {
lineCount = readFileSync(fullPath, "utf8").split("\n").length;
} catch {
return { ok: false, reason: "unreadable" };
}
setCachedLineCount(fullPath, stat.mtimeMs, lineCount);
}
if (parts.startLine < 1 || parts.startLine > lineCount) {
return { ok: false, reason: `line ${parts.startLine} > ${lineCount}` };
@@ -759,7 +830,7 @@ interface TableBlock {
rows: string[][];
}
type Block =
export type Block =
| ParagraphBlock
| HeadingBlock
| BulletBlock
@@ -768,6 +839,16 @@ type Block =
| HrBlock
| EditBlockView
| TableBlock;
export type {
ParagraphBlock,
HeadingBlock,
BulletBlock,
BlockquoteBlock,
CodeBlock,
HrBlock,
EditBlockView,
TableBlock,
};
export function parseBlocks(raw: string): Block[] {
const lines = raw.split(/\r?\n/);
+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,
+4 -58
View File
@@ -1,31 +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).
*
* CSI recovery is delegated to `key-normalize.ts` — see there for
* the rationale. Every event flows through `recoverCsiTail` first,
* which is the single source of truth for the Windows ConPTY case
* (parse-keypress eats the leading `\x1b` and routes the bare
* `[A`/`[C`/`[201~`/etc. through useInput as plain text).
*/
/** Pure keystroke→action reducer; arrow keys at buffer boundary defer to the parent for history recall. */
export interface MultilineKey {
input: string;
@@ -53,23 +26,9 @@ export interface MultilineAction {
/** When `true`, fire `onSubmit(submitValue ?? value)`. */
submit: boolean;
submitValue?: string;
/**
* When set, the key was ↑/↓ at a buffer boundary (empty buffer, or
* cursor already at first/last line) and the component should hand
* off to the parent's history-recall handler. The child's cursor
* didn't move; the parent decides whether to swap in a prior
* prompt. Lets users escape out of a multi-line buffer into
* history without first emptying it — previously NOOP felt stuck.
*/
/** Set when ↑/↓ hits a buffer boundary — parent handles history recall. */
historyHandoff?: "prev" | "next";
/**
* Multi-char paste detected. The reducer is pure so it can't
* allocate a sentinel id or write to the registry — it hands the
* raw normalized payload up to PromptInput, which registers the
* paste, picks a sentinel codepoint, and inserts THAT (one char)
* into the buffer. Result: the user sees a `[paste #N · M lines]`
* placeholder instead of the full content drowning the typed text.
*/
/** Reducer is pure — hands raw paste to PromptInput which allocates a sentinel and inserts that. */
pasteRequest?: { content: string };
}
@@ -251,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;
@@ -275,15 +229,7 @@ function startOfLine(value: string, cursor: number): number {
return value.lastIndexOf("\n", cursor - 1) + 1;
}
/**
* Find the start of the word immediately to the left of the cursor.
* Skips trailing whitespace first (so Ctrl+W after typing space
* still removes the previous word, not just the space), then walks
* back over the word characters until a whitespace boundary or
* start-of-buffer. Newlines count as whitespace, so Ctrl+W at the
* start of a line deletes the preceding line's last word — same
* behavior as bash/readline.
*/
/** 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--;
+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 = {},
+2 -54
View File
@@ -1,29 +1,4 @@
/**
* Paste sentinels — represent a pasted blob as a single codepoint in
* the input buffer instead of inlining its full contents.
*
* Why: a 3000-line paste shoved verbatim into the buffer drowns the
* surrounding typed text, costs a lot to render per keystroke, and
* makes navigation/clear awkward. Replace it with one PUA char (a
* "sentinel") and store the real content in a side registry. The
* buffer string stays small, the user types around the sentinel as
* if it were a single character, and a Backspace at the sentinel
* deletes the whole paste in one stroke. On submit we expand the
* sentinels back to real content.
*
* Encoding:
* - One codepoint per paste, in PUA range U+E100..U+E1FF (256 slots).
* - The codepoint's offset within that range is the paste id.
* - That gives us 256 distinct paste blobs per session before ids
* wrap. In practice users paste a handful per session — wrap is
* a non-issue, but if it happens, the new paste overwrites the
* oldest registry entry; any stale sentinels still in the buffer
* will render with a "(missing)" badge so the user can clean up.
*
* Range chosen from the Supplementary PUA-A region's neighbor (BMP
* PUA) so a single `String.fromCharCode` works — no surrogate pairs,
* no `length === 2` weirdness for cursor arithmetic.
*/
/** 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;
@@ -55,11 +30,6 @@ export function isPasteSentinel(ch: string): boolean {
return decodePasteSentinel(ch) !== null;
}
/**
* Build a PasteEntry from raw paste content. Computes line + char
* counts once at registration time so the renderer doesn't re-count
* on every keystroke.
*/
export function makePasteEntry(id: number, content: string): PasteEntry {
return {
id,
@@ -69,14 +39,7 @@ export function makePasteEntry(id: number, content: string): PasteEntry {
};
}
/**
* Expand every sentinel in `text` back to its registered paste
* content. Unknown sentinels (entry missing — registry was wiped, or
* id wrap collision) drop to empty string so the resulting prompt
* doesn't carry a literal PUA codepoint to the model.
*
* Used at submit time to recover the full prompt the user composed.
*/
/** Unknown sentinels drop to empty — never leak a PUA codepoint into the prompt. */
export function expandPasteSentinels(
text: string,
pastes: ReadonlyMap<number, PasteEntry>,
@@ -95,11 +58,6 @@ export function expandPasteSentinels(
return out;
}
/**
* Quick check: does the buffer contain ANY sentinel? Used to gate
* UI hints (the "paste #N" listing in the prompt-box footer) without
* walking the whole buffer twice.
*/
export function bufferHasPaste(text: string): boolean {
for (let i = 0; i < text.length; i++) {
if (decodePasteSentinel(text[i]!) !== null) return true;
@@ -107,12 +65,6 @@ export function bufferHasPaste(text: string): boolean {
return false;
}
/**
* Walk the buffer and return the ids of every sentinel still
* present, in source order. Used by the registry's GC pass at
* submit time so unreachable paste entries don't accumulate.
* (No-op when the buffer is sentinel-free.)
*/
export function listPasteIdsInBuffer(text: string): number[] {
const ids: number[] = [];
for (let i = 0; i < text.length; i++) {
@@ -122,10 +74,6 @@ export function listPasteIdsInBuffer(text: string): number[] {
return ids;
}
/**
* Format `1234` chars as `1.2KB` etc. Tiny helper used in placeholder
* labels — kept here so paste-related display logic is co-located.
*/
export function formatBytesShort(n: number): string {
if (n < 1024) return `${n}B`;
if (n < 1024 * 1024) return `${(n / 1024).toFixed(n < 1024 * 10 ? 1 : 0)}KB`;
+63 -62
View File
@@ -1,79 +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, reasoning effort, or thinking mode independently
* — they pick "fast / smart / max" and we translate.
*
* Design rules (v0.6+):
* - Branching (`branch >= 2`) is NEVER in a preset. Self-consistency
* sampling is `N×` cost; auto-enabling it would ambush users into
* multi-dollar turns without asking. Opt-in only via `/branch N`.
* - Harvest (Pillar-2 plan-state extraction) is NEVER in a preset.
* In practice it's display sugar — the typed plan state hasn't
* fed back into orchestration decisions (branch trigger) often
* enough to pay for the extra round-trip. Opt-in only via
* `/harvest on`.
* - The three tiers differ on only TWO knobs: model (flash/pro) and
* reasoning effort (high/max). Same on-the-wire billing axis,
* easy to reason about, easy to budget.
*/
/** 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;
/**
* Reasoning-effort cap sent per turn. `high` = shorter chain of
* thought (cheaper, faster); `max` = agent-class default (deeper,
* more output tokens). DeepSeek ignores this field on non-thinking
* calls, so it's safe to pin across models.
*/
reasoningEffort: "high" | "max";
/**
* Pillar-2 plan-state extraction. Every preset ships `false` (see
* module header); kept in the shape so a user who later flips it on
* at runtime still round-trips cleanly. `/harvest on` toggles it.
*/
autoEscalate: boolean;
/** Pillar-2 harvest. Always false in presets — opt-in via /harvest. */
harvest: boolean;
/**
* Branch budget. Every preset ships `1` (off). `/branch N` with
* N>=2 is the only way to enable self-consistency sampling.
*/
/** Branch budget. Always 1 in presets — opt-in via /branch. */
branch: number;
}
export const PRESETS: Record<PresetName, PresetSettings> = {
// fast — flash + effort=high. Quick Q&A, one-line tweaks, anything
// where shallow reasoning is enough. Cheapest turn possible.
fast: { model: "deepseek-v4-flash", reasoningEffort: "high", harvest: false, branch: 1 },
// smart — flash + effort=max. Full thinking budget on the cheap
// model. The default: handles 90%+ of coding work at a fraction
// of pro's cost.
smart: { model: "deepseek-v4-flash", reasoningEffort: "max", harvest: false, branch: 1 },
// max — pro + effort=max. Frontier model for hard tasks: cross-
// file architecture, subtle bug hunts, anything where flash's
// reasoning has measurably failed. ~12× per-token vs flash; save
// for when you need it, or use `/pro` to escalate a single turn.
max: { model: "deepseek-v4-pro", reasoningEffort: "max", harvest: false, branch: 1 },
};
export const PRESET_DESCRIPTIONS: Record<PresetName, { headline: string; cost: string }> = {
fast: {
headline: "v4-flash · effort=high",
cost: "cheapest · quick Q&A, one-line edits",
/** 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: "v4-flash · effort=max",
cost: "~1.5× fast · default · day-to-day coding",
// 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: "v4-pro · effort=max",
cost: "~12× fast · hard single-shots · use /pro for a single-turn bump",
// 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 ?? "smart"];
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>
);
}
+3 -78
View File
@@ -1,44 +1,13 @@
/**
* Pure helpers for rendering one logical line of the prompt input as
* exactly one visual row, regardless of how wide the line's content
* is. Splitting this out from PromptInput so the math is testable
* without React/Ink.
*
* Why we can't trust Ink/Yoga's text wrap: Ink uses `string-width` to
* measure cells, but on CJK Windows terminals some glyphs render at
* a different cell count than `string-width` reports. The terminal
* wraps to a 2nd visual row, Ink's eraseLines miscounts, and the
* scrollback fills with ghost rows from the previous frame's leak.
*
* Our fix is to never let the line wrap. We slice the text down to
* the visible-cell budget ourselves and feed Ink a single Text whose
* width is known to fit.
*
* Cursor visibility: when the user types past the visible width the
* window slides so the cursor stays in view. `‹` and `›` markers
* appear at the trimmed edges so the user can see content is hidden
* to one side.
*/
/** 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";
/**
* One renderable atom of a viewport. The line's content is broken
* into a sequence of these so a paste sentinel becomes a magenta
* `[paste #N · Ml · KKB]` block while the surrounding text stays
* normal.
*/
export type Segment = { kind: "text"; text: string } | { kind: "paste"; id: number; label: string };
export interface Viewport {
/** Segments to render left-to-right. Sum of cells <= visibleCells. */
segments: Segment[];
/**
* Visual cell column at which to draw the cursor block, measured
* from the start of the viewport (0 = leftmost cell after the
* prompt prefix). `null` means cursor is not on this line — the
* caller renders a static line.
*/
/** `null` when cursor is not on this line. */
cursorCell: number | null;
/** True when content was clipped on the left side. */
hiddenLeft: boolean;
@@ -46,23 +15,7 @@ export interface Viewport {
hiddenRight: boolean;
}
/**
* Cell width of a single character in a typical terminal grid.
*
* Approximation of Unicode East Asian Width=Wide / W treatment.
* Range table is intentionally compact — covers the codepoints we
* see in practice (CJK ideographs, fullwidth forms, Hangul syllables,
* Hiragana / Katakana). Anything outside the wide ranges counts as
* one cell. Control characters count as zero so we don't over-budget
* for them.
*
* Not a full `string-width` clone. We deliberately don't honour the
* "Ambiguous=2 in CJK locale" rule because it produces inconsistent
* results across terminals and is the very source of Ink's wrap
* miscount. Treating ambiguous chars as 1 cell here matches what
* Ink/Yoga also does, so our slice math agrees with what Ink would
* have rendered (had it not wrapped).
*/
/** 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);
@@ -119,17 +72,6 @@ function pasteSentinelCells(id: number, pastes?: ReadonlyMap<number, PasteEntry>
return pasteSentinelLabel(id, entry).length;
}
/**
* Compute the viewport for a line, keeping the cursor visible. When
* the line's total cells fit in `visibleCells`, return the whole
* line. Otherwise slice a window centred on the cursor with `‹` /
* `›` markers indicating clipped sides.
*
* `cursorCol` is the cursor's char index within `line` (0 = before
* first char; `line.length` = past last char). Pass `null` for
* lines that don't host the cursor — the function returns a left-
* aligned static viewport with truncation on the right.
*/
export function buildViewport(
line: string,
cursorCol: number | null,
@@ -187,18 +129,6 @@ function clipFromLeft(
return { segments, cursorCell: null, hiddenLeft: false, hiddenRight: end < line.length };
}
/**
* Sliding window around the cursor. Algorithm:
*
* 1. Start with `start` and `end` both at the cursor index.
* 2. Expand `end` rightward while there's budget, until cursor cell
* visible or we hit end-of-line.
* 3. Expand `start` leftward to fill remaining budget.
* 4. Reserve 1 cell on each clipped side for the `‹`/`›` marker.
*
* The cursor cell is computed AFTER the slice is fixed, by counting
* cells from `start` up to `cursorCol`.
*/
function clipAroundCursor(
line: string,
cursorCol: number,
@@ -288,11 +218,6 @@ function charCellsAt(line: string, idx: number, pastes?: ReadonlyMap<number, Pas
return charCells(ch);
}
/**
* Walk the string and split it into text/paste segments. Pure —
* doesn't allocate per-character objects (text runs accumulate in a
* single segment). Used by both the fast and clipped paths.
*/
export function textToSegments(line: string, pastes?: ReadonlyMap<number, PasteEntry>): Segment[] {
const out: Segment[] = [];
let buf = "";
+65 -20
View File
@@ -5,9 +5,9 @@ export const SLASH_COMMANDS: readonly SlashCommandSpec[] = [
{ cmd: "status", summary: "current model, flags, context, session" },
{
cmd: "preset",
argsHint: "<fast|smart|max>",
summary: "one-tap model + harvest + branch bundle",
argCompleter: ["fast", "smart", "max"],
argsHint: "<auto|flash|pro>",
summary: "model bundle — auto escalates flash → pro, flash/pro lock",
argCompleter: ["auto", "flash", "pro"],
},
{
cmd: "model",
@@ -40,6 +40,13 @@ export const SLASH_COMMANDS: readonly SlashCommandSpec[] = [
summary: "arm v4-pro for the NEXT turn only (one-shot · auto-disarms after turn)",
argCompleter: ["off"],
},
{
cmd: "budget",
argsHint: "[usd|off]",
summary:
"session USD cap — warns at 80%, refuses next turn at 100%. Off by default. /budget alone shows status",
argCompleter: ["off", "1", "5", "10", "20", "50"],
},
{ cmd: "mcp", summary: "list MCP servers + tools attached to this session" },
{
cmd: "resource",
@@ -69,6 +76,25 @@ export const SLASH_COMMANDS: readonly SlashCommandSpec[] = [
argsHint: "[reload]",
summary: "list active hooks (settings.json under .reasonix/) · reload re-reads from disk",
},
{
cmd: "permissions",
argsHint: "[list|add <prefix>|remove <prefix|N>|clear confirm]",
summary:
"show / edit shell allowlist (builtin read-only · per-project: ~/.reasonix/config.json)",
argCompleter: ["list", "add", "remove", "clear"],
},
{
cmd: "dashboard",
argsHint: "[stop]",
summary: "launch the embedded web dashboard (127.0.0.1, token-gated)",
argCompleter: ["stop"],
},
{
cmd: "cwd",
argsHint: "<path>",
summary:
"switch session working directory (re-registers code tools, reloads hooks; MCP servers stay)",
},
{
cmd: "update",
summary: "show current vs latest version + the shell command to upgrade",
@@ -81,7 +107,10 @@ export const SLASH_COMMANDS: readonly SlashCommandSpec[] = [
{ cmd: "think", summary: "dump the last turn's full R1 reasoning (reasoner only)" },
{
cmd: "context",
summary: "break down where context tokens are going: system / tools / per-turn log",
argsHint: "[on|off]",
summary:
"toggle the always-on context-breakdown footer (system / tools / log / input). no arg → flip; on/off → force",
argCompleter: ["on", "off"],
},
{ cmd: "retry", summary: "truncate & resend your last message (fresh sample)" },
{
@@ -99,7 +128,16 @@ export const SLASH_COMMANDS: readonly SlashCommandSpec[] = [
},
{ cmd: "sessions", summary: "list saved sessions (current marked with ▸)" },
{ cmd: "forget", summary: "delete the current session from disk" },
{
cmd: "prune-sessions",
summary: "delete sessions idle ≥N days (default 90) — frees disk on long-time installs",
argsHint: "[days]",
},
{ cmd: "setup", summary: "reminds you to exit and run `reasonix setup`" },
{
cmd: "semantic",
summary: "show semantic_search status — built? Ollama installed? how to enable",
},
{ cmd: "clear", summary: "clear visible scrollback only (log/context kept)" },
{ cmd: "new", summary: "start a fresh conversation (clear context + scrollback)" },
{
@@ -109,6 +147,14 @@ export const SLASH_COMMANDS: readonly SlashCommandSpec[] = [
},
{ cmd: "exit", summary: "quit the TUI" },
// Code-mode only
{
cmd: "init",
argsHint: "[force]",
summary:
"scan the project and synthesize a baseline REASONIX.md (model writes; review with /apply). `force` overwrites an existing file.",
contextual: "code",
argCompleter: ["force"],
},
{
cmd: "apply",
argsHint: "[N|N,M|N-M]",
@@ -146,6 +192,20 @@ export const SLASH_COMMANDS: readonly SlashCommandSpec[] = [
summary: "git add -A && git commit -m ...",
contextual: "code",
},
{
cmd: "checkpoint",
argsHint: "[name|list|forget <id>]",
summary:
"snapshot every file the session has touched (Cursor-style internal store, not git). /checkpoint alone lists.",
contextual: "code",
argCompleter: ["list", "forget"],
},
{
cmd: "restore",
argsHint: "<name|id>",
summary: "roll back files to a named checkpoint (see /checkpoint list)",
contextual: "code",
},
{
cmd: "plan",
argsHint: "[on|off]",
@@ -181,11 +241,6 @@ export const SLASH_COMMANDS: readonly SlashCommandSpec[] = [
},
];
/**
* Filter the registry by a prefix string (without the leading `/`).
* Empty prefix returns the full non-contextual list (plus code-mode
* entries when `codeMode` is true). Case-insensitive.
*/
export function suggestSlashCommands(prefix: string, codeMode = false): SlashCommandSpec[] {
const p = prefix.toLowerCase();
return SLASH_COMMANDS.filter((c) => {
@@ -194,17 +249,7 @@ export function suggestSlashCommands(prefix: string, codeMode = false): SlashCom
});
}
/**
* Classify the prompt buffer for argument completion. Returns `null`
* when the buffer isn't in a slash-with-args state.
*
* Firing shape: input must start with `/<cmd> ` (space after a known
* command). The character right after the space through end-of-buffer
* is the "arg tail"; if the tail has NO internal whitespace the
* picker is live (tail is the partial). If the tail has whitespace,
* the user has moved past the first argument position and we surface
* the usage hint only.
*/
/** Picker fires only when arg tail has no internal whitespace; past that it's a usage hint. */
export function detectSlashArgContext(input: string, codeMode = false): SlashArgContext | null {
// `/cmd <rest>` — one space, rest captured up to end-of-buffer.
const m = /^\/(\S+) ([\s\S]*)$/.exec(input);
+9 -14
View File
@@ -1,43 +1,38 @@
import type { CacheFirstLoop } from "../../../loop.js";
import { handlers as adminHandlers } from "./handlers/admin.js";
import { handlers as basicHandlers } from "./handlers/basic.js";
import { handlers as dashboardHandlers } from "./handlers/dashboard.js";
import { handlers as editsHandlers } from "./handlers/edits.js";
import { handlers as initHandlers } from "./handlers/init.js";
import { handlers as jobsHandlers } from "./handlers/jobs.js";
import { handlers as mcpHandlers } from "./handlers/mcp.js";
import { handlers as memoryHandlers } from "./handlers/memory.js";
import { handlers as modelHandlers } from "./handlers/model.js";
import { handlers as observabilityHandlers } from "./handlers/observability.js";
import { handlers as permissionsHandlers } from "./handlers/permissions.js";
import { handlers as plansHandlers } from "./handlers/plans.js";
import { handlers as semanticHandlers } from "./handlers/semantic.js";
import { handlers as sessionsHandlers } from "./handlers/sessions.js";
import { handlers as skillHandlers } from "./handlers/skill.js";
import type { SlashContext, SlashResult } from "./types.js";
/**
* A slash handler receives the command's args + the loop + shared
* runtime context, and returns a synchronous SlashResult. Async work
* (balance fetches, stop_job) fires-and-forgets via `ctx.postInfo`
* instead — keeps the TUI input non-blocking.
*/
/** Synchronous return — async work fires-and-forgets via `ctx.postInfo` to keep input non-blocking. */
export type SlashHandler = (args: string[], loop: CacheFirstLoop, ctx: SlashContext) => SlashResult;
/**
* Flat map of cmd → handler. Composed from per-topic modules so each
* feature's logic stays local; aliases (e.g. `exit` / `quit`) are just
* extra keys in the per-module handlers bag pointing at the same fn.
*
* Ordering of the spread matters only for duplicate keys; there are
* none. Keep alphabetical for diff sanity when adding modules.
*/
const HANDLERS: Record<string, SlashHandler> = {
...adminHandlers,
...basicHandlers,
...dashboardHandlers,
...editsHandlers,
...initHandlers,
...jobsHandlers,
...mcpHandlers,
...memoryHandlers,
...modelHandlers,
...observabilityHandlers,
...permissionsHandlers,
...plansHandlers,
...semanticHandlers,
...sessionsHandlers,
...skillHandlers,
};
+50 -24
View File
@@ -1,3 +1,5 @@
import { existsSync, statSync } from "node:fs";
import * as pathMod from "node:path";
import {
HOOK_EVENTS,
type HookEvent,
@@ -5,7 +7,7 @@ import {
globalSettingsPath,
projectSettingsPath,
} from "../../../../hooks.js";
import { aggregateUsage, defaultUsageLogPath, readUsageLog } from "../../../../usage.js";
import { aggregateUsage, defaultUsageLogPath, readUsageLog } from "../../../../telemetry/usage.js";
import { VERSION, compareVersions, isNpxInstall } from "../../../../version.js";
import { renderDashboard } from "../../../commands/stats.js";
import type { SlashHandler } from "../dispatch.js";
@@ -67,19 +69,7 @@ const hooks: SlashHandler = (args, loop, ctx) => {
return { info: lines.join("\n") };
};
/**
* `/update` — inside the TUI we deliberately do NOT spawn `npm install`.
* stdio:inherit into a running Ink renderer corrupts the display, and
* the process being upgraded is the same process that's still reading
* its own binaries (messy on Windows). Instead we surface what we
* already know from the App's background registry check and print the
* exact shell command the user should run after exiting.
*
* The `latestVersion` ctx field is populated by App.tsx's mount-time
* `getLatestVersion()` effect. When it's `null` we report the check
* as pending/offline — still a useful output (current version + how
* to force a fresh check from another terminal).
*/
/** No in-TUI npm spawn — stdio:inherit corrupts Ink and Windows locks the running binary. */
const update: SlashHandler = (_args, _loop, ctx) => {
const latest = ctx.latestVersion ?? null;
const lines: string[] = [`current: reasonix ${VERSION}`];
@@ -121,16 +111,6 @@ const update: SlashHandler = (_args, _loop, ctx) => {
return { info: lines.join("\n") };
};
/**
* `/stats` — dashboard view of `~/.reasonix/usage.jsonl`, the same
* roll-up `reasonix stats` (no arg) prints at the shell. Synchronous
* disk read; cheap enough that we don't bother caching between slash
* invocations.
*
* No transcript-path variant in-TUI: the per-file summary is scripty
* and rarely wanted mid-session. If someone needs it they have the
* CLI form (`reasonix stats <path>`).
*/
const stats: SlashHandler = () => {
const path = defaultUsageLogPath();
const records = readUsageLog(path);
@@ -150,9 +130,55 @@ const stats: SlashHandler = () => {
return { info: renderDashboard(agg, path) };
};
/** MCP servers don't follow the switch — their stdio child anchored to original cwd at spawn. */
const cwd: SlashHandler = (args, _loop, ctx) => {
if (!ctx.setCwd) {
return {
info: "/cwd is not available in this context (no setCwd callback wired).",
};
}
const raw = (args[0] ?? "").trim();
if (!raw) {
return {
info: "usage: /cwd <path> (absolute or relative, ~ expands to home)",
};
}
const home = process.env.HOME ?? process.env.USERPROFILE ?? "";
const expanded = raw.startsWith("~") && home ? pathMod.join(home, raw.slice(1)) : raw;
const abs = pathMod.resolve(expanded);
if (!existsSync(abs)) {
return { info: `▸ /cwd: path does not exist — ${abs}` };
}
let isDir = false;
try {
isDir = statSync(abs).isDirectory();
} catch {
// Permission denied or transient FS error — treat as not-a-dir
// and let the user see the exact path so they can investigate.
}
if (!isDir) {
return { info: `▸ /cwd: not a directory — ${abs}` };
}
let info: string;
try {
info = ctx.setCwd(abs);
} catch (err) {
return { info: `▸ /cwd failed: ${(err as Error).message}` };
}
const lines = [info];
if (ctx.mcpServers && ctx.mcpServers.length > 0) {
lines.push(
` note: ${ctx.mcpServers.length} MCP server(s) still anchored to the original cwd —`,
" their tools won't follow this switch. Restart the session for full reset.",
);
}
return { info: lines.join("\n") };
};
export const handlers: Record<string, SlashHandler> = {
hook: hooks,
hooks,
cwd,
update,
stats,
};
+4 -4
View File
@@ -70,7 +70,7 @@ const help: SlashHandler = () => ({
" /help this message",
" /keys keyboard shortcuts + prompt prefixes (!, @, /)",
" /status show current settings",
" /preset <fast|smart|max> one-tap presets — see below",
" /preset <auto|flash|pro> model bundle — see below",
" /model <id> deepseek-v4-flash or deepseek-v4-pro",
" /pro [off] arm v4-pro for NEXT turn only (one-shot, auto-disarms)",
" /harvest [on|off] Pillar 2: structured plan-state extraction (OPT-IN — costs extra)",
@@ -132,9 +132,9 @@ const help: SlashHandler = () => ({
" Trailing sentence punctuation (./,/)) is stripped automatically.",
"",
"Presets (branch + harvest are NEVER auto-enabled — opt-in only):",
" fast v4-flash · effort=high cheapest · quick Q&A, one-line edits",
" smart v4-flash · effort=max ← default · day-to-day coding",
" max v4-pro · effort=max ~12× fast · hard single-shots",
" auto v4-flash → v4-pro on hard turns ← default · cheap when easy, smart when hard",
" flash v4-flash always cheapest · predictable per-turn cost",
" pro v4-pro always ~3× flash (5/31) · hard multi-turn work",
"",
"Sessions (auto-enabled by default, named 'default'):",
" reasonix chat --session <name> use a different named session",
+58
View File
@@ -0,0 +1,58 @@
import type { SlashHandler } from "../dispatch.js";
const dashboard: SlashHandler = (args, _loop, ctx) => {
if (!ctx.startDashboard || !ctx.getDashboardUrl) {
return {
info: "/dashboard is not available in this context (no startDashboard callback wired).",
};
}
const sub = (args[0] ?? "").toLowerCase();
if (sub === "stop" || sub === "off") {
if (!ctx.stopDashboard) {
return { info: "/dashboard stop: no stop callback wired." };
}
const url = ctx.getDashboardUrl();
if (!url) return { info: "▸ dashboard is not running." };
// Fire-and-forget the async stop. Caller (App.tsx) handles errors
// by posting to historical.
ctx.stopDashboard();
return { info: "▸ dashboard stopping…" };
}
const existing = ctx.getDashboardUrl();
if (existing) {
return {
info: [
"▸ dashboard is already running:",
` ${existing}`,
"",
"Open it in any browser. Type `/dashboard stop` to tear it down.",
].join("\n"),
};
}
// Boot. Slash handlers are sync; we kick the start asynchronously
// and let App.tsx's `postInfo` deliver the URL when the server is
// listening.
ctx
.startDashboard()
.then((url) => {
ctx.postInfo?.(
[
"▸ dashboard ready:",
` ${url}`,
"",
"127.0.0.1 only · token-gated. Type `/dashboard stop` to shut down.",
].join("\n"),
);
})
.catch((err: Error) => {
ctx.postInfo?.(`▸ dashboard failed to start: ${err.message}`);
});
return { info: "▸ starting dashboard server…" };
};
export const handlers: Record<string, SlashHandler> = { dashboard };
+118 -9
View File
@@ -1,3 +1,11 @@
import {
createCheckpoint,
deleteCheckpoint,
findCheckpoint,
fmtAgo,
listCheckpoints,
restoreCheckpoint,
} from "../../../../code/checkpoints.js";
import type { EditMode } from "../../../../config.js";
import { parseEditIndices } from "../../edit-history.js";
import type { SlashHandler } from "../dispatch.js";
@@ -48,15 +56,7 @@ const discard: SlashHandler = (args, _loop, ctx) => {
return { info: ctx.codeDiscard(parsed.indices) };
};
/**
* Bridge between the `args: string[]` shape commander gives us and the
* comma-separated index syntax users actually type ("/apply 1,3-4").
* The TUI's slash parser splits on whitespace, so `1,3-4` arrives as
* `["1,3-4"]` and `1, 3, 4` arrives as `["1,", "3,", "4"]`. Re-joining
* with commas + delegating to `parseEditIndices` handles both shapes.
*
* Empty `args` → `{ indices: [] }` (caller treats as "all").
*/
/** Re-joins on `,` to handle both `1,3-4` and `1, 3, 4` shapes from the whitespace-split parser. */
function parseIndicesArg(
args: readonly string[],
max: number,
@@ -167,6 +167,113 @@ const walk: SlashHandler = (_args, _loop, ctx) => {
return { info: ctx.startWalkthrough() };
};
const checkpoint: SlashHandler = (args, _loop, ctx) => {
if (!ctx.codeRoot || !ctx.touchedFiles) {
return {
info: "/checkpoint is only available inside `reasonix code` — chat mode doesn't apply edits.",
};
}
const sub = (args[0] ?? "").toLowerCase();
const rest = args.slice(1).join(" ").trim();
if (sub === "" || sub === "list") {
const items = [...listCheckpoints(ctx.codeRoot)].reverse();
if (items.length === 0) {
return {
info: "no checkpoints yet — `/checkpoint <name>` snapshots every file the session has touched. Restore later with `/restore <name>`.",
};
}
const lines = [`◈ checkpoints · ${items.length} stored`, ""];
for (const m of items) {
const sizeKb = (m.bytes / 1024).toFixed(1);
const tag = m.source === "manual" ? "" : ` (${m.source})`;
lines.push(
` ${m.id} ${fmtAgo(m.createdAt).padEnd(8)} ${m.name}${tag} · ${m.fileCount} file${m.fileCount === 1 ? "" : "s"}, ${sizeKb} KB`,
);
}
lines.push("");
lines.push(" /restore <name|id> · /checkpoint forget <id> · /checkpoint <name> to add");
return { info: lines.join("\n") };
}
if (sub === "forget" || sub === "rm" || sub === "delete") {
if (!rest) return { info: "usage: /checkpoint forget <id|name>" };
const found = findCheckpoint(ctx.codeRoot, rest);
if (!found) return { info: `▸ no checkpoint matching "${rest}" — see /checkpoint list` };
const ok = deleteCheckpoint(ctx.codeRoot, found.id);
return {
info: ok
? `▸ deleted checkpoint ${found.id} (${found.name})`
: `▸ failed to delete ${found.id} (already gone?)`,
};
}
// `/checkpoint <name>` (any free-form name) → save
const name = args.join(" ").trim();
if (!name) {
return {
info: "usage: /checkpoint <name> (or /checkpoint list to see existing)",
};
}
const paths = ctx.touchedFiles();
const meta = createCheckpoint({
rootDir: ctx.codeRoot,
name,
paths,
source: "manual",
});
if (paths.length === 0) {
return {
info: `▸ checkpoint "${name}" saved (${meta.id}) — but no files have been touched yet, so it's an empty baseline. Edits made after this point will be revertable.`,
};
}
return {
info: `▸ checkpoint "${name}" saved (${meta.id}) — ${meta.fileCount} file${meta.fileCount === 1 ? "" : "s"}, ${(meta.bytes / 1024).toFixed(1)} KB. Restore: /restore ${name}`,
};
};
const restore: SlashHandler = (args, _loop, ctx) => {
if (!ctx.codeRoot) {
return {
info: "/restore is only available inside `reasonix code`.",
};
}
const target = args.join(" ").trim();
if (!target) {
return {
info: "usage: /restore <name|id> (see /checkpoint list for ids)",
};
}
const found = findCheckpoint(ctx.codeRoot, target);
if (!found) {
return { info: `▸ no checkpoint matching "${target}" — try /checkpoint list` };
}
const result = restoreCheckpoint(ctx.codeRoot, found.id);
const lines = [`▸ restored "${found.name}" (${found.id}) from ${fmtAgo(found.createdAt)}`];
if (result.restored.length > 0) {
lines.push(
` · wrote back ${result.restored.length} file${result.restored.length === 1 ? "" : "s"}`,
);
}
if (result.removed.length > 0) {
lines.push(
` · removed ${result.removed.length} file${result.removed.length === 1 ? "" : "s"} (didn't exist at checkpoint time)`,
);
}
if (result.skipped.length > 0) {
lines.push(
` ✗ ${result.skipped.length} file${result.skipped.length === 1 ? "" : "s"} skipped:`,
);
for (const s of result.skipped.slice(0, 5)) {
lines.push(` ${s.path} — ${s.reason}`);
}
if (result.skipped.length > 5) {
lines.push(` … ${result.skipped.length - 5} more`);
}
}
return { info: lines.join("\n") };
};
export const handlers: Record<string, SlashHandler> = {
undo,
history,
@@ -179,4 +286,6 @@ export const handlers: Record<string, SlashHandler> = {
mode,
commit,
walk,
checkpoint,
restore,
};
+102
View File
@@ -0,0 +1,102 @@
/** `/init` — resubmits a constrained brief; output flows through the normal edit-review gate. */
import { existsSync } from "node:fs";
import * as pathMod from "node:path";
import type { SlashHandler } from "../dispatch.js";
/** "STOP after writing" is load-bearing — without it the model burns extra turns on follow-up offers. */
const INIT_PROMPT = [
"# Task: Initialize REASONIX.md",
"",
"I want you to generate a REASONIX.md at the project root that captures",
"the working knowledge a future Reasonix session needs to be productive",
"here. This file is auto-pinned into your system prompt every launch,",
"so its size and accuracy matter.",
"",
"## Hard constraints (do NOT relax these)",
"",
"- **Length cap: ≤ 80 lines / 3KB total.** Be concise. If you can't fit a",
" section, drop it.",
"- **Only document things you can verify by reading files.** Do NOT",
" speculate about architectural intent, future roadmap, or design",
" rationale. If it isn't obvious from the code, leave it out.",
"- **No placeholder text.** No 'TODO: describe X', no 'Add more here'.",
" Either state a fact or omit the section.",
"",
"## Procedure",
"",
"1. Read the top of any existing README* file.",
"2. Read the manifest (package.json / Cargo.toml / pyproject.toml /",
" go.mod / etc.) — pick whichever exists.",
"3. `directory_tree` 1-2 levels deep on the project root, skipping",
" common build/dependency dirs (node_modules, dist, target, .git,",
" venv, __pycache__).",
"4. Identify: primary language + framework, top-level layout, test",
" runner, lint/format setup, build/run/test scripts, any non-obvious",
" convention with visible evidence (commit message format, import",
" order, naming pattern).",
"5. Write REASONIX.md with the sections below, skipping any you can't",
" fill from evidence.",
"",
"## Sections to use (skip ones with no evidence)",
"",
"- **Stack** — language + framework + 3-5 key deps. One line each.",
"- **Layout** — top-level dirs and what lives in each. One line each.",
"- **Commands** — verbatim from `scripts` block (or equivalent):",
" build / test / lint / typecheck / dev / format. Whatever exists.",
"- **Conventions** — only things visible in the code. Examples:",
" '*.test.ts colocated with source', 'named exports only',",
" 'commits use Conventional Commits prefix'. If you can't find any",
" CONVENTION evidence, omit the whole section.",
"- **Watch out for** — gotchas a new contributor would benefit from",
" knowing BEFORE editing. Examples: 'edit_file SEARCH must match",
" byte-for-byte', 'this dir is generated, don't edit by hand'.",
" Omit if you find nothing concrete.",
"",
"## Output",
"",
"Write the result to `REASONIX.md` in the project root using the",
"filesystem tools (edit_file with empty SEARCH if creating new,",
"write_file if overwriting). After writing, STOP — do not summarize",
"what you did, do not propose follow-up tasks. The user will review",
"the pending edit via /apply.",
"",
"Start now.",
].join("\n");
const init: SlashHandler = (args, _loop, ctx) => {
if (!ctx.codeRoot) {
return {
info: [
"/init only works in code mode (it needs filesystem tools).",
"Run `reasonix code [path]` to start a session rooted at the",
"project you want to initialize, then run /init.",
].join("\n"),
};
}
const force = (args[0] ?? "").toLowerCase() === "force";
const target = pathMod.join(ctx.codeRoot, "REASONIX.md");
if (existsSync(target) && !force) {
return {
info: [
`▸ REASONIX.md already exists at ${target}`,
"",
" /init force regenerate from scratch (overwrites)",
"",
" Or edit it by hand — it's just markdown. The current file is",
" pinned into the system prompt every launch as-is.",
].join("\n"),
};
}
return {
info: [
"▸ /init — model will scan the project and synthesize REASONIX.md.",
" The result lands as a pending edit; review with /apply or /walk.",
].join("\n"),
resubmit: INIT_PROMPT,
};
};
export const handlers: Record<string, SlashHandler> = {
init,
};
+74 -14
View File
@@ -1,29 +1,89 @@
import type { JobRecord } from "../../../../tools/jobs.js";
import type { SlashHandler } from "../dispatch.js";
function statusIcon(r: JobRecord): string {
if (r.running) return "●";
if (r.spawnError) return "✗";
if (r.exitCode === 0) return "✓";
if (r.exitCode !== null) return "✗";
return "○";
}
function fmtAge(ms: number): string {
const s = Math.floor(ms / 1000);
if (s < 60) return `${s}s`;
const m = Math.floor(s / 60);
if (m < 60) return `${m}m`;
const h = Math.floor(m / 60);
if (h < 24) return `${h}h`;
return `${Math.floor(h / 24)}d`;
}
/** Caps at 3 unique ports for compose-style multi-service boots; never guesses from command name. */
function detectPorts(output: string): number[] {
if (!output) return [];
const found = new Set<number>();
const patterns = [
/(?:localhost|127\.0\.0\.1|0\.0\.0\.0):(\d{2,5})\b/g,
/(?:listening|listening on|bound to|port|on port)[\s:=]+(\d{2,5})\b/gi,
];
for (const re of patterns) {
let m: RegExpExecArray | null;
// biome-ignore lint/suspicious/noAssignInExpressions: standard regex iteration pattern
while ((m = re.exec(output)) !== null) {
const port = Number.parseInt(m[1] ?? "", 10);
if (port >= 80 && port <= 65535) found.add(port);
if (found.size >= 3) break;
}
if (found.size >= 3) break;
}
return [...found];
}
function fmtMeta(r: JobRecord): string {
if (r.running) {
const ports = detectPorts(r.output);
if (ports.length > 0) return ports.map((p) => `:${p}`).join(" ");
return r.pid !== null ? `pid ${r.pid}` : "";
}
if (r.spawnError) return r.spawnError;
if (r.exitCode !== null) return `exit ${r.exitCode}`;
return "stopped";
}
const jobs: SlashHandler = (_args, _loop, ctx) => {
if (!ctx.jobs) {
return { info: "/jobs is only available inside `reasonix code`." };
}
const rows = ctx.jobs.list();
if (rows.length === 0) {
return { info: "no background jobs yet — use run_background to start one" };
return {
info: "◈ jobs · 0 running · 0 total\n (run_background spawns one — dev servers, watchers, long-running scripts)",
};
}
const lines = ["Background jobs:"];
const running = rows.filter((r) => r.running).length;
// Layout: ICO (1) · ID (right-pad 4) · CMD (flex) · META (auto) · AGE (right-pad 5)
// Plain text from a slash, so we can't apply per-cell color the way
// the React tree could; the icons + indentation already give the eye
// strong landmarks. The chrome layer (when this lands in the TUI
// directly) will color the icons via chalk.
const lines: string[] = [`◈ jobs · ${running} running · ${rows.length} total`, ""];
// Compute the max command width so cmds line up; cap at 44 so a long
// docker-compose invocation doesn't push the meta column off-screen.
const cmdWidth = Math.min(44, Math.max(8, ...rows.map((r) => r.command.length)));
for (const r of rows) {
const age = ((Date.now() - r.startedAt) / 1000).toFixed(1);
const state = r.running
? `running · pid ${r.pid ?? "?"}`
: r.exitCode !== null
? `exit ${r.exitCode}`
: r.spawnError
? "failed"
: "stopped";
lines.push(
` ${String(r.id).padStart(3)} ${state.padEnd(20)} ${age.padStart(6)}s ago $ ${r.command}`,
);
const ico = statusIcon(r);
const id = `#${String(r.id).padEnd(3)}`;
const cmd =
r.command.length > cmdWidth
? `${r.command.slice(0, cmdWidth - 1)}…`
: r.command.padEnd(cmdWidth);
const meta = fmtMeta(r).padEnd(20);
const age = fmtAge(Date.now() - r.startedAt).padStart(4);
lines.push(` ${ico} ${id} ${cmd} ${meta} ${age}`);
}
lines.push("");
lines.push("/kill <id> to stop one · /logs <id> [lines] to tail output");
lines.push(" /logs <id> tail · /kill <id> SIGTERM → SIGKILL");
return { info: lines.join("\n") };
};
Loaded 100 of 272 files, more files were not shown because too many files have changed in this diff. Show more