Compare commits

...
53 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
250 changed files with 21086 additions and 8562 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
+3
View File
@@ -30,3 +30,6 @@ sessions/
.reasonix/semantic/
.reasonix/sessions/
.reasonix/semantic-skip
# Scratch entry regenerated each time scripts/bundle-codemirror.mjs runs.
scripts/.cm-entry.mjs
+643
View File
@@ -3,6 +3,649 @@
All notable changes to Reasonix. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/);
this project uses [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [0.16.0] — 2026-04-29
**Headline:** Mouse drag in the log now selects text directly, with the
log auto-scrolling when the drag hits the viewport edge. Releasing the
button copies the selection to the system clipboard via OSC 52 plus a
tempfile fallback for terminals that don't honor it. The whole flow
stays inside the alt-screen TUI — no more `/copy` dance to dump the
log to main buffer.
- feat(ui): app-owned mouse selection. Plain drag paints a reverse-
video highlight across the selected rows; the selection follows
scroll naturally because rows are tracked in absolute log-row
coordinates, not viewport-relative. Dragging past the top or bottom
edge of the content area starts a 60ms-tick auto-scroll that keeps
extending the selection while the cursor stays at the edge.
Releasing copies the plain-text rendering via OSC 52 (system
clipboard) plus a `<tmpdir>/reasonix-clip-<ts>.txt` fallback for
terminals or remote sessions that drop OSC 52. Shift+drag still
bypasses tracking so the terminal's native selection remains
available for visible-only copies.
- feat(infra): `stdin-reader` now surfaces `mouseDrag` (SGR button 32)
and `mouseRelease` (tail `m`) events; previously dropped silently.
`alt-screen` switches from mode 1000 (press/release only) to mode
1002 (button-event tracking with drag motion).
- feat(ui): `log-frame` extends `AtomViewport` with `firstRowAbs` so
the keystroke layer can map mouse coordinates back to absolute log
rows. New `extractSelection(atoms, sel)` walks the cell grid and
produces UTF-8 text honoring 2-wide chars (CJK / emoji) with ANSI
styling stripped.
- chore(ui): `/copy` slash command, the `copyMode` lifecycle, the
alt-screen exit + main-buffer dump, and the `setMouseTracking` /
`isMouseTrackingOn` helpers all removed. The new flow doesn't need
to leave alt-screen, doesn't pollute main scrollback, and doesn't
have the "two histories stacked" bug the dump approach kept hitting.
## [0.15.0] — 2026-04-29
**Headline:** Event-log sidecar lands as a real kernel artifact and
gets its first consumer — `replay()` reads `events.jsonl` and runs
the same pure reducers `apply()` does in-process. First external
PR merged: deny-with-context, pressing Tab on a tool-confirm modal
lets the user type *why* they're refusing, forwarded to the model
verbatim. Comment policy now enforced by `tests/comment-policy.test.ts`
under `npm run verify`; companion sweep dropped 6.3k LoC of
module-essay docstrings, banner separators, and incident-history
narrative across 148 source files.
- feat(core): `events.jsonl` sidecar — every kernel `Event` is
appended to `<session>.events.jsonl` next to the legacy
`LoopEvent` log. Append-only, durable, no behavior change for
in-process consumers. Unblocks the v0.14 architecture migration:
any view (CLI, dashboard, replay) can now reconstruct state from
the sidecar without the loop running.
- feat(core): `replay()` reads the sidecar and runs the same pure
reducers as in-process `apply()`. First proof that the projection
layer is genuinely deterministic — `replay(events)` matches
`apply(...)` for the conversation / budget / plan / workspace /
capabilities / status / session-meta views.
- feat(cli): `reasonix events <name>` — inspect any session's event
stream from the command line. Filters by event variant
(`reasonix events ToolCallStarted`), tail mode, JSON output for
piping into `jq`. Plus a kernel sweep removing the dead-comment
layer that accumulated during the LoopEvent → Event transition.
- feat(ui): deny-with-context (PR #1, by @wviana). On any tool-confirm
modal (`ShellConfirm`, `WorkspaceConfirm`, edit review), pressing
Tab on the Deny option opens inline editing — type a reason, Enter
submits. The reason is appended to the synthetic `I denied
running …` message so the model knows *why* and can adjust course
instead of plowing ahead. Edit-review path uses a dedicated
`DenyContextInput` modal (n hotkey opens the reason input, Esc
returns to the diff). Bracketed-paste support in the inline editor
so multi-line context can be pasted in one go.
- chore(ui): removed obsolete `/mouse` slash command and the
misleading "drag to select & copy" prompt hint — both predated
`/copy` and gave wrong guidance now that the proper flow is
alt-screen-exit + scrollback dump.
- chore(comments): `tests/comment-policy.test.ts` pins six rules
derived from `CLAUDE.md`: ≤2-line module headers, no Phase-N
narrative, no version refs in comments, no incident history
(`user reported`, `screenshot showed`, `fix for #N`), no banner
separators (`// ─── helpers ───`), ≤3-line block comments. Runs
under `npm run verify`, which is the pre-push gate. Companion
sweep: 116 module-essay headers compressed to one line, 577
over-long block comments distilled or deleted, 44 banner separators
stripped. Net −6,367 LoC of dead-weight comments across 148 files;
zero behavior change, full lint/typecheck/test green.
## [0.14.0] — 2026-04-29
**Headline:** Two real bug fixes (post-shell-confirm session lockup,
post-workspace-switch ENOENT on edit_file), a new `/copy` mode for
copying across multi-screen log content, an always-on context-pressure
footer above the prompt, and width-aware chrome that stops dropping
pills when there's clearly room. Plus a quiet refactor: shared UI
primitives, dead-code purge in StatsPanel.
- fix(loop): streaming-abort path now resets `_turnAbort` before
returning. Without this, a queued-submit triggered by App.tsx
(ShellConfirm "run once" → `loop.abort()` + `setQueuedSubmit`)
produced a spurious `aborted at iter 0/64 — stopped without
producing a summary` the moment the synthetic message reached
the loop, locking the session until the user `/retry`'d.
- fix(tui): `edit_file` interceptor now reads the workspace root via
`currentRootDirRef` instead of capturing `currentRootDir` in a
stale closure. Workspace switch (`change_workspace` → modal approve)
rebound `read_file` / `run_command` to the new root but left the
interceptor pointing at the old one — `edit_file` wrote to the
old path while `read_file` looked in the new one, surfacing as a
mysterious ENOENT for a file the model had just successfully edited.
- feat(tui): `/copy` exits the alt-screen, dumps the rendered log to
the main screen, and listens for any keystroke to restore. Native
terminal scrollback + drag-select work on the dump — solves the
"can't copy text that scrolled past the viewport" problem alt-screen
introduced. Re-entering alt-screen and bumping React state forces
Ink to redraw the TUI cleanly. Multiple enter/exit cycles per
session; React tree, event log, model session, prompt draft all
preserved across the toggle.
- feat(tui): always-on context-pressure footer above the prompt —
`ctx ▰▰▰▱▱▱▱▱▱▱▱▱▱▱ 14K/977K · 1% · sys 5.8K · tools 6.1K · log 0`.
Single-row layout matches the chrome bar's `▰▱` visual language.
Width-aware shed for the breakdown segments (input → log → tools →
sys). `/context` toggles visibility (default on); the rich
4-color stacked breakdown is still pushed to scrollback for
headless / replay surfaces that don't carry the toggle callback.
- feat(tui): chrome bar pill rendering switches from preemptive
`narrow = cols < 120` to width-aware greedy shed. Optional pills
(balance > cache > session > update) drop in priority order only
when `string-width` math says they won't fit — at 100 cols all
five render where the old code dropped three. Cache pill is now
default-on (cold-start dim treatment instead of hiding).
- refactor(ui): `Bar`, `formatTokens`, `ChromeRule`, `ContextCell`
promoted to `src/cli/ui/primitives.tsx` (were duplicated 2-3× across
`StatsPanel` / `ChromeBar` / `EventLog` / `log-frame`). `CtxBreakdownBlock`
+ `computeCtxBreakdown` extracted to `src/cli/ui/ctx-breakdown.tsx`
so `/context` and the footer share the same compute path. `StatsPanel`
shrunk from 769 → ~280 lines (dead helpers from the chrome
redesign era removed).
- feat(core): v0.14 architecture scaffold — `src/core/events.ts`
(25-variant Event union + 7 view types), `src/core/reducers.ts`
(pure projections + `apply` / `replay` combinators), `src/ports/*.ts`
(6 ports: ModelClient, ToolHost, EventSink, MemoryStore, HookRunner,
CheckpointStore). Types only; zero behavior change. 19 reducer tests
pin the conversation / budget / plan / workspace / capabilities /
status / session-meta projections and prove `replay()` determinism.
## [0.13.5] — 2026-04-29
**Headline:** TUI overhaul. Chrome reverts to native Ink Box +
flexGrow (Phase 6a's Frame-compiler chrome was clipping pills on
Windows Terminal / ConPTY). Vertical scrollbar replaced with a
`[↑ N%]` chrome pill + horizontal mini-bar in the bottom hint —
column-aligned scrollbars are unreliable while some log atoms
still render through legacy ReactElements. Streaming gains the
design's `responding ░▒▓█▓▒░░░░` marquee and a `▌` cursor blink
at end-of-body.
- chrome: `ChromeBar` uses native flex; preset pill (`[auto]` /
`[flash]` / `[pro]`) replaces edit-mode pill (edit mode still
surfaces via `ModeStatusBar`); CNY balance renders as `w ¥8.50`;
cost pill includes inline budget when set.
- streaming: full body text streams in (was 140-char tail) with a
blinking primary-color cursor; `responding` row shows a 12-cell
marching wave (`░▒▓█▓▒`) at 120ms ticks. Matches
`design/tui-redesign-ink.html`.
- scroll: vertical `ScrollBar` removed; chrome shows `[↑ N%]` when
scrolled, `BottomHint` shows `↑ N · ▕──●──▏ X% · ↓ M · End`.
- frame: `src/frame/width.ts` delegates to the `string-width`
package; hand-rolled width tables removed.
- chore: project `CLAUDE.md` codifies code/comment conventions
(terse comments, no Phase-N essays, libraries over hand-rolled
unicode math).
## [0.12.15] — 2026-04-28
**Headline:** Every user-facing string that still said
`fast / smart / max` is now `auto / flash / pro` — the canonical
names presets have used since the autoEscalate split. CLI flags
(`chat --preset`, `run --preset`), `/help`'s preset table,
`/preset`'s argHint and completer, the slash handler's `usage:`
line, and the `code` command description all updated.
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.
## [0.12.14] — 2026-04-28
**Headline:** 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. Plus: a deferred-dispatch
fix for parallel tool calls that was silently writing files into the
old workspace, and the in-flight row finally tells you _what tool_ is
running, not just "waiting".
### Loop — workspace-switch parallel-batch fix
When DeepSeek emits `change_workspace + write_file` in one assistant
message, every call dispatched in sequence — write_file fired against
the OLD sandbox before the user had a chance to approve the modal,
silently dropping the new file in the wrong project. Every subsequent
call in the same batch now gets a synthetic "deferred — re-issue on
your next turn" result; tool_call ↔ tool pairing stays valid for
DeepSeek's next-turn validator. Test in `tests/loop.test.ts` locks it.
### Server / context
- `ActiveModal` gains three new shapes: `workspace`, `checkpoint`,
`revision`. `getActiveModal` returns them so a freshly-connected
client paints the right modal mid-prompt.
- `DashboardContext` adds `resolveWorkspaceConfirm`,
`resolveCheckpointConfirm` (with optional `text` for revise-with-
feedback in one shot), and `resolveReviseConfirm`.
- `/api/modal/resolve` accepts the three new `kind`s with their
per-shape choice validation. 503 when a resolver isn't wired.
### App.tsx wiring
- `pendingWorkspace`, `pendingCheckpoint`, `pendingRevision` each
broadcast `modal-up`/`modal-down` SSE events.
- Web's "revise + feedback in one shot" path bypasses the TUI's
staged-input two-step by accepting an explicit snap override on
`handleCheckpointReviseSubmit` — no more setStagedX → re-render →
ref-mirror microtask race.
### Dashboard SPA
- New `WorkspaceModal`, `CheckpointModal`, `RevisionModal` Preact
components. Modal switch dispatches them by `modal.kind`.
- In-flight row now shows the active tool + key args (path / command
truncated to 80 chars / char count) once `tool_start` fires —
`write_file → /path/to/foo (12,345 ch)` instead of "waiting…".
- Tool-start no longer pushes a placeholder info row. The InFlightRow
carries the live state; the result card replaces it on `tool`.
- ErrorBoundary stops auto-recovering after 3 catches and renders a
manual "Try again" button — no more silent flickering loop.
- `.modal-cmd` gets `overflow-x: auto` + `max-height: 240px` so a
pathological multi-kilobyte command can't push the rest of the
panel offscreen.
## [0.12.13] — 2026-04-28
**Fix:** the chat feed kept yanking the user back to the bottom
during streaming — wheel-up didn't stick. Two bugs stacked:
1. The scroll listener attached to `document.querySelector(".chat-feed")`
on first mount, but the `.chat-feed` div was conditionally
rendered (only when at least one message existed). On a fresh
session the listener never attached, so the "is the user
scrolled away?" flag was never flipped to `false`.
2. Even after the listener attached, the auto-scroll effect's
own `el.scrollTop = el.scrollHeight` write fires a `scroll`
event that re-snaps the flag back to `true`. Manual wheel
scrolls were racing the next streaming delta's auto-snap.
Both fixed:
- `.chat-feed` is now always rendered (the empty-state copy
moved inside it). A `feedRef` ref attaches the scroll
listener on first paint.
- A new `autoScrollInFlight` ref gates the listener: events
observed during a programmatic scroll write are ignored, so
only genuine user wheel/drag flips the auto-scroll guard.
## [0.12.12] — 2026-04-28
**Headline:** Indexing from the dashboard now actually wires up
`semantic_search` for the running session — no more "build the
index, restart, build again" dance — and a dismissible Chat
banner steers users to the Semantic panel when no index exists.
### Loop / prefix
- `ImmutablePrefix` gains an `addTool(spec)` method that pushes a
new tool spec onto the live prefix. The class name is now a
half-truth (toolSpecs is exposed via getter, backed by a mutable
array) but the rationale is documented inline: a one-time cache
miss is cheaper than asking users to restart the session.
- New `DashboardContext.addToolToPrefix(spec)` callback. Wired
from `App.tsx` to `loop.prefix.addTool`.
### Server
- `runIndex` (the dashboard's buildIndex wrapper) calls
`registerSemanticSearchTool(ctx.tools, …)` after a successful
build, then `ctx.addToolToPrefix(spec)` so the model sees
`semantic_search` from the next turn. Failures are non-fatal —
the index is still on disk, the next session bootstrap picks
it up.
- `/api/overview` returns `semanticIndexExists` (`true`/`false`/
`null`) so the Chat panel can render the banner without an
extra round-trip.
### Dashboard — Chat panel
- New top-of-Chat banner: `≈ Semantic search isn't enabled for
this project — Build it →` with a dismiss `×`. Visible only
when `semanticIndexExists === false` and not previously
dismissed (state in `localStorage` as `rx.semanticBannerDismissed`).
- Click "Build it →" fires `appBus.dispatchEvent("navigate-tab")`
with `tabId: "semantic"` — the existing nav handler picks it up.
## [0.12.11] — 2026-04-28
**Headline:** Tell users what to do when Ollama isn't installed
yet. The 0.12.9 Semantic panel just said "not reachable" with a
generic copy-this-command blurb — the new flow distinguishes
"binary missing" from "daemon down" from "model not pulled" and
offers a one-click action for each level it can resolve.
### Server
- `GET /api/semantic` now returns the full `checkOllamaStatus`
payload — `binaryFound`, `daemonRunning`, `modelPulled`,
`modelName`, `installedModels` — instead of the raw probe.
- New endpoints:
- `POST /api/semantic/ollama/start` — runs `startOllamaDaemon`
(15s timeout). Returns `{ ready, pid }`.
- `POST /api/semantic/ollama/pull` — fire-and-forget
`pullOllamaModel`. Per-model `PULLS` map tracks status +
last log line; `/api/semantic` includes it as `pull`.
### Dashboard — Semantic panel
Tri-state Ollama section:
- **No binary** → red "not installed" pill + Install Ollama
card with macOS / Windows / Linux install instructions. We
deliberately don't run package managers for the user.
- **Binary, daemon down** → yellow "daemon down" pill + "Start
daemon" button (calls `ollama/start`).
- **Daemon up, model missing** → "not pulled" pill + "Pull
<model>" button. Live status row during the pull (latest
ollama output line, elapsed seconds, success/error pill).
- **Everything ready** → green pill, Index buttons enable.
Polling speeds up to 1.2s while a pull or build job is running.
## [0.12.10] — 2026-04-28
**Headline:** Move the in-flight indicator out of the top-left
corner and put the live counters next to it. Previously the
spinner appeared above the message stream — far from where the
user's eyes already were (input + status bar) — and the only
moving signal during a turn was the streaming text itself.
### Chat panel
- New **InFlightRow** rendered just above the ChatStatusBar
whenever a turn is in flight. Format:
`⠋ thinking · 2.3s · reasoning 1,204 ch · out 0 ch · [Abort]`
- Phase auto-flips between `thinking` (only reasoning growing),
`streaming` (text growing), and `waiting` (neither — model is
thinking with no token output yet, e.g. before the first
delta arrives).
- Elapsed seconds tick every 500ms via a per-turn interval so
the user sees motion even when the model is in a long pause
between deltas.
- Character counts come from the existing `streaming` state — no
new wire fields, just rendering data we already have.
- Top "turn in flight" row is gone; only `statusLine` notices
still render up there when not busy.
## [0.12.9] — 2026-04-28
**Headline:** Semantic indexing without leaving the session.
Previously you had to exit the TUI, run `reasonix index`, wait,
then re-enter — every change. Now there's a Semantic panel in
the dashboard that drives `buildIndex` in the background and
shows live progress.
### Server
- `src/server/api/semantic.ts` — new endpoint set:
- `GET /api/semantic` → Ollama probe + index existence
+ current job snapshot
- `POST /api/semantic/start` → kick off `buildIndex({ rebuild })`
fire-and-forget, returns 202
- `POST /api/semantic/stop` → flag job as aborting (advisory;
`buildIndex` doesn't honor a
signal yet, lands when it does)
- Per-root `JobRecord` map (module-scoped) tracks phase
(scan/embed/write/done/error) + counters (filesScanned,
chunksTotal, chunksDone, …) updated via `onProgress`.
### Dashboard
- New **Semantic** sidebar tab. Polls `/api/semantic` every 1.2s
while a job is running, every 5s when idle.
- Surfaces Ollama daemon reachability + listed models, current
index existence, and the live job: phase pill, file/chunk
counters, percentage progress bar, elapsed seconds, last
result on completion, error text on failure.
- Buttons: **Index (incremental)**, **Rebuild (wipe + full)**,
**Stop**. Disabled appropriately when Ollama isn't reachable
or another job is running. Inline guidance on missing daemon.
- Standalone `reasonix dashboard` mode shows a polite "code-mode
required" empty state — no project root, nothing to index.
## [0.12.8] — 2026-04-28
**Fix:** the dashboard row in 0.12.7 collapsed the URL and
description onto one Box; on terminals that hide the OSC 8
escape, Ink's text-width measurement counted the escape bytes
as visible characters and the description wrapped through the
middle of the URL. Split into two stacked rows:
```
◇ web open the dashboard in a browser (chat · files · stats · settings)
http://127.0.0.1:NNNN/?token=…
```
URL still wrapped in the OSC 8 hyperlink — but it's the only
content on its row, so a width miscount can't clobber anything.
## [0.12.7] — 2026-04-28
**Headline:** Dashboard discoverability. Most users had no idea
`/dashboard` existed — the URL is now visible from the first turn,
on its own row in the status panel, with a one-line description of
what the dashboard actually offers. Clickable in OSC-8-aware
terminals (iTerm2, WezTerm, Windows Terminal, VS Code, recent
gnome-terminal); copy-pasteable everywhere else.
### TUI
- Auto-launch the embedded dashboard when `reasonix code` /
`reasonix chat` mount. Failures are silent (a missing dashboard
never blocks the TUI), tear-down still happens on unmount /
`/dashboard stop`.
- `--no-dashboard` opts out per-session (CI, hardened
environments, anyone allergic to a localhost listener).
- New status-panel row:
`◇ web http://127.0.0.1:NNNN/?token=… open the dashboard
in a browser (chat · files · stats · settings)`
rendered between the header and the metrics so it never fights
for space.
- URL wrapped in an OSC 8 hyperlink — Cmd/Ctrl-click in any
terminal that supports the escape; bare text otherwise.
- `App` gains a `noDashboard` prop, `StatsPanel` a `dashboardUrl`
prop. Both threaded through `chatCommand` / `codeCommand`.
## [0.12.6] — 2026-04-28
**Headline:** Bigger fixes for the things you actually look at:
the edit-review modal is now a real side-by-side diff, the
sidebar collapses to icons, and the call-storm breaker stops
mistaking legitimate read → edit → verify cycles for storms.
### Edit review modal
- Two-column **side-by-side diff** ("before" left, "after" right)
with hljs syntax highlighting per the file's language. Adjacent
removed/added line runs pair into rows so the change reads
cleanly across the gutter.
- Red tint + `−` marker on the removed side; green tint + `+` on
the added side; context lines render unchanged.
- Modal payload (`{ kind: "edit-review" }`) gained `search` and
`replace` fields holding the full block contents — the old
truncated `preview` string stays alongside for older clients.
`src/cli/ui/App.tsx` and `src/server/context.ts` updated.
### Sidebar — icon-only collapse
- New `◀ collapse` button at the bottom of the sidebar shrinks
it from 220px → 52px and hides every label, leaving just the
glyphs. `▶ expand` brings labels back. Choice persists in
`localStorage` (`rx.sidebarCollapsed`).
- Tabs in the collapsed state center the glyph and keep the
primary-color active indicator.
### Call-storm breaker — false-positive fix
The `read → edit → verify → edit → verify` pattern was tripping
the storm protection (3 identical `read_file` calls within the
window). The fix sources its "did this call mutate state?"
signal from the existing ToolRegistry — each tool already
declares `readOnly` / `readOnlyCheck` for plan-mode gating, so
no new flag was added. The breaker now:
- Tags every buffer entry as read-only or mutating based on the
predicate the loop wires in (`def.readOnly === true`, with
`readOnlyCheck` taking precedence on the actual args).
- On a mutating call, drops prior read-only entries from the
window — a re-read after `edit_file` is fresh, not a repeat.
- Keeps mutator entries alongside, so a model looping on
identical `edit_file` calls still trips on the threshold.
`StormBreaker(window, threshold, isMutating?)` is the public
shape; `ToolCallRepair` accepts an `isMutating` predicate.
Without one (older callers, isolated tests) every call counts —
back-compat preserved. Three new storm tests cover the cases.
## [0.12.5] — 2026-04-28
**Headline:** Stop loading CodeMirror from a CDN, fix the legacy
preset migration that broke 2 CI tests, and replace the markdown
preview toggle with a proper Edit / Split / Preview tri-state.
### Editor — local CodeMirror bundle
- `scripts/bundle-codemirror.mjs` — esbuild-based bundler that
pulls every `@codemirror/*` package from `node_modules` and
produces `dashboard/codemirror.js` (~937 KB minified ESM).
- `npm run build:cm` rebuilds it. Output is committed so a fresh
`npm install` doesn't have to run esbuild.
- `dashboard/app.js` now does `import("/assets/codemirror.js")`
instead of 21 `import("https://esm.sh/...")` calls. One copy of
every package = no Tag identity issues, no transitive-version
drift between cold loads.
- `serveAsset` learns to serve `codemirror.js`. `package.json`
ships the bundle in `files`. Biome ignores the minified file.
- `@codemirror/*` + `esbuild` added to devDependencies — they
feed the bundler, they don't end up in the runtime install.
### Editor — markdown view modes
- Replaced the `Preview`/`Edit` boolean with a three-state
segmented control: **Edit** (source only, default), **Split**
(source on the left, rendered on the right, with a divider),
**Preview** (rendered only). Buttons live in the editor bar
and are markdown-only — non-md tabs hide the group entirely.
- The CodeMirror remount effect now keys on `viewMode`, so
flipping between Edit and Split doesn't leave a stale view.
### Preset rework — CI fix
`resolvePreset` was collapsing every legacy name (`fast`, `smart`,
`max`) to `auto`, which made two `tests/resolve.test.ts` cases
fail because they assert the legacy mapping that older config
files depend on. Restored the original semantics:
- `fast` → flash with `effort: high` (no auto-escalate)
- `smart` → auto (flash + max + auto-escalate)
- `max` → pro
Anything else still collapses to auto. Suite back to 1568 / 1568.
## [0.12.4] — 2026-04-28
**Headline:** The two real editor problems that 0.12.2/3 didn't
actually fix: highlighting was still missing for every language,
and the new markdown preview produced a half-rendered page where
the bottom got dumped into a `<pre>`.
### Editor
- **Pin `@lezer/highlight` + `@lezer/common` in the esm.sh
`?deps=` list.** The silent-no-highlights failure was caused by
duplicated `@lezer/highlight` instances across CodeMirror
packages: `tags.keyword` etc. are JS objects compared by
identity, so when the language pack and the theme each loaded
their own copy, the parser produced tags the theme didn't
recognize, and all coloring quietly went away. Pinning common
+ highlight forces every package to share one set.
- **Separate `Marked` instance for the markdown preview
(`previewMarked`).** The chat renderer is loaded with custom
`code` handling for SEARCH/REPLACE diffs and edit:foo/path
fence syntax — that ran on every preview too, occasionally
swallowing the rest of the document into one `<pre>` block on
certain inputs. Preview now uses a vanilla marked + a slim
hljs-only `code` override.
## [0.12.3] — 2026-04-28
**Headline:** Editor as a first-class sidebar tab. The drawer was
the only way in, which meant you had to start a chat and click a
file path before you could browse anything. Now there's a sidebar
entry that opens the file tree directly.
### Editor
- New **Editor** tab in the sidebar (after Chat). Mounts the
`EditorPanel` full-width inside `.main` — same file tree,
tabs, CodeMirror — no drawer chrome.
- `.main` gets a `main-editor` modifier when the editor tab is
active, dropping the 28×36 panel padding and letting the
editor fill the viewport.
- The chat drawer entry point still works (clicking a path in a
tool card slides the drawer in over the current tab). Drawer
and sidebar Editor are separate instances; their tab state
doesn't share yet — revisit if it becomes annoying.
## [0.12.2] — 2026-04-28
**Headline:** Editor polish pass. Tabs at the top span the full
editor width like VS Code, syntax highlighting actually shows up,
the gutter/line numbers match the dark theme, autocomplete pops
on every keystroke instead of waiting for a manual trigger.
### Editor
- **Tabs on top, full width** — moved out of `.editor-main` and
into a sibling `.editor-tabs` that sits above the side+main
body row. Active tab gets a primary-color top border and the
editor's own background, so it visually merges into the code
surface (VS Code pattern). The file panel can collapse and the
tab bar stays put.
- **Highlighting works** — `oneDark` already ships its own
HighlightStyle; the existing `defaultHighlightStyle` wrap was
fine but ordered before `oneDark`, so it didn't cover languages
oneDark misses. Reordered to fall back AFTER oneDark and added
`highlightActiveLineGutter` so the active row stands out in the
gutter too.
- **Gutter restyled** — `.cm-gutters` gets a darker `#21252b`
background, line numbers use the muted `#495162` for inactive
rows and `#abb2bf` for the active row, with a 40px min-width
and 16px right-padding. Fold gutter ships alongside (click the
arrow next to a brace to fold).
- **Autocomplete** — `autocompletion({ activateOnTyping: true,
closeOnBlur: true, maxRenderedOptions: 30 })` so suggestions
pop while you type. Added `completionKeymap` so Tab/Enter pick
the highlighted entry. Popup styled to the dark palette.
- **Tab close ergonomics** — close button has a fixed 18px box
so the tab doesn't jump width when the dirty dot toggles.
All edits in `dashboard/app.js` `EditorPanel` + `dashboard/app.css`.
## [0.12.1] — 2026-04-28
**Headline:** Editor v2 — VS Code-style file tree, collapsible file
panel, wider drawer. The 0.12.0 editor opened on the right at 50%
with a flat alphabetical file list; on a normal-width window that
felt cramped and the file list scrolled forever.
### Editor
- **File tree** — flat path list collapses into a recursive folder
tree. Folders sort first, files alphabetically; click `▶` to
expand, `▼` to collapse. The expanded set lives in panel state so
it survives drawer close/reopen within a session.
- **Collapsible side panel** — `◀` button at the top of the file
panel hides everything except a thin `▶` button that brings it
back. Editor area gets the full drawer width when files are out
of the way.
- **Wider drawer** — `.editor-drawer-host.open` bumped from 50% →
65% (min-width 360 → 420) so the editor breathes.
- **Filter still flat** — when the search box has text, the tree
view collapses to the existing flat filtered list (paths are
more useful than indented names when you're searching).
No backend changes. All edits in `dashboard/app.js` `EditorPanel`
+ `dashboard/app.css`.
## [0.12.0] — 2026-04-28
**Headline:** Web dashboard. A top-tier local control plane that lives
+30 -7
View File
@@ -72,6 +72,28 @@ 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:
@@ -316,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.
@@ -348,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,
@@ -535,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
```
@@ -570,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 |
@@ -750,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
+26 -7
View File
@@ -69,6 +69,25 @@ 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)
三件事,别家不会同时都给你:
@@ -284,8 +303,8 @@ reasonix code › /commit "fix: findByEmail case-insensitive"
- `/undo` —— 回滚上一批已应用的编辑。
- `/new` —— 在同一目录开新会话,但不丢失旧会话文件。
- `/effort high` —— 从默认 `max` agent 推理强度降一档,简单任务更省更快。
- `npx reasonix code --preset max` —— v4-pro + 三路 self-consistency 分支,
适合疑难重构。
- `npx reasonix code --preset pro` —— 整轮锁定 v4-pro,不再自动降级到
flash。如果想要 self-consistency 分支,加 `--branch 3` 跑三路投票。
- `npx reasonix code src/` —— 更窄的沙箱(只有 `src/` 可写)。
- `npx reasonix code --no-session` —— 临时会话,什么都不存。
@@ -314,8 +333,8 @@ completion、没有工具参数。`reasonix stats <transcript>` 仍兼容老用
### 保持最新
面板顶栏在 `Reasonix` 旁边显示当前版本(如
`Reasonix v0.5.21 · deepseek-v4-pro · harvest · max …`,最后那个 `max` 是
推理强度徽章 —— `/effort high` 可降一档)。后台每 24 小时静默查询一次 npm
`Reasonix 0.12.6 · v4-flash · AUTO · max …`,最后那个 `max` 是推理强度
徽章 —— `/effort high` 可降一档)。后台每 24 小时静默查询一次 npm
registry,发现新版会在同一行右侧显示黄色 `update: X.Y.Z`。不阻塞、不烦人,
每天最多查一次,离线 / 防火墙下静默失败。
@@ -479,7 +498,7 @@ schema 设计、架构讨论,或者驱动你自己的 MCP 服务器。会话
```bash
npx reasonix # 用已保存配置 + 向导选过的 MCP
npx reasonix --preset smart # 这次跑用 reasoner + R1 harvest
npx reasonix --preset pro # 整轮锁定 v4-pro(不自动降级)
npx reasonix --session design # 命名会话 — 之后 --session design 续聊
```
@@ -513,7 +532,7 @@ MCP 工具走和原生工具一样的 Cache-First + 修复 + 上下文安全管
| 命令 | 作用 |
|---|---|
| `/preset <fast\|smart\|max>` | 一键预设(model + harvest + branch) |
| `/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 提取 |
@@ -679,7 +698,7 @@ npx reasonix sessions # 列已保存会话
常用 flag:
```bash
--preset <fast|smart|max> # 预设组合(model + harvest + branch)
--preset <auto|flash|pro> # 模型策略(auto / 锁 flash / 锁 pro)
--model <id> # 显式指定模型 ID
--harvest / --no-harvest # R1 plan-state 提取
--branch <N> # self-consistency 预算
+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"]
}
}
+732 -29
View File
@@ -189,6 +189,63 @@ body {
border-right: 1px solid var(--border);
display: flex;
flex-direction: column;
transition: width 0.18s ease-out;
}
.sidebar.collapsed {
width: 52px;
}
.sidebar.collapsed .sidebar-label {
display: none;
}
.sidebar.collapsed .sidebar-header {
padding: 14px 8px 10px;
text-align: center;
}
.sidebar.collapsed .sidebar-brand {
font-size: 0;
}
.sidebar.collapsed .sidebar-brand .glyph {
font-size: 18px;
margin: 0;
}
.sidebar.collapsed .tab {
padding: 9px 0;
justify-content: center;
border-left: 2px solid transparent;
}
.sidebar.collapsed .tab.active {
border-left-color: var(--primary);
}
.sidebar.collapsed .tab .glyph {
width: auto;
font-size: 14px;
}
.sidebar.collapsed .sidebar-collapse-toggle {
padding: 8px 0;
justify-content: center;
}
.sidebar.collapsed .sidebar-footer {
display: none;
}
.sidebar-collapse-toggle {
display: flex;
align-items: center;
gap: 8px;
background: transparent;
border: none;
border-top: 1px solid var(--border);
padding: 8px 20px;
font-family: var(--mono);
font-size: 11px;
color: var(--fg-3);
cursor: pointer;
width: 100%;
text-align: left;
}
.sidebar-collapse-toggle:hover {
background: var(--bg-hover);
color: var(--primary);
}
.sidebar-header {
@@ -374,6 +431,18 @@ body {
flex: 1;
overflow-y: auto;
padding: 28px 36px;
min-width: 0;
}
.main-editor {
padding: 0;
overflow: hidden;
display: flex;
flex-direction: column;
}
.main-editor .editor-shell {
flex: 1;
height: auto;
min-height: 0;
}
.panel-header {
@@ -474,6 +543,34 @@ body {
background: var(--bg-3);
color: var(--fg-2);
}
.pill-active {
background: rgba(103, 232, 249, 0.22);
color: var(--primary);
}
/* ---------- Key/value rows (compact metadata layout) ---------- */
.kv {
display: flex;
flex-direction: column;
gap: 6px;
font-size: 13px;
color: var(--fg-1);
font-family: var(--mono);
}
.kv > div {
display: flex;
flex-wrap: wrap;
align-items: baseline;
gap: 8px;
}
.kv-key {
display: inline-block;
min-width: 84px;
font-size: 11px;
letter-spacing: 0.06em;
text-transform: uppercase;
color: var(--fg-3);
}
/* ---------- Tables ---------- */
@@ -1124,6 +1221,108 @@ textarea:focus {
color: var(--fg-2);
}
/* Onboarding banner that nudges new users to the Semantic panel.
* Only shown when the project has no built index AND the user hasn't
* explicitly dismissed it (state in localStorage). The "Build it →"
* action navigates the sidebar via the appBus so the rest of the
* panel state isn't disturbed. */
.chat-banner {
display: flex;
align-items: center;
gap: 12px;
margin-bottom: 14px;
padding: 10px 14px;
background: var(--bg-1);
border: 1px solid var(--border);
border-left: 3px solid var(--accent);
border-radius: var(--radius-md);
font-size: 13px;
}
.chat-banner-icon {
font-family: var(--mono);
color: var(--accent);
font-size: 18px;
}
.chat-banner-text {
flex: 1;
display: flex;
flex-direction: column;
gap: 2px;
font-size: 13px;
}
.chat-banner-text strong {
color: var(--fg-0);
font-weight: 600;
}
.chat-banner-text .muted {
font-size: 12px;
line-height: 1.45;
}
.chat-banner-close {
background: transparent;
border: none;
color: var(--fg-3);
font-size: 20px;
line-height: 1;
padding: 0 6px;
cursor: pointer;
border-radius: var(--radius-sm);
}
.chat-banner-close:hover {
background: var(--bg-3);
color: var(--fg-0);
}
/* In-flight row sits just above ChatStatusBar — the user's eyes are
* already at the input; this puts the spinner + elapsed + token
* stream in the same visual neighborhood instead of pushing them up
* to the top of the panel. Border on the bottom only so it shares the
* statusbar's top divider. */
.chat-inflight {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
padding: 7px 8px;
margin-top: 6px;
background: var(--bg-1);
border: 1px solid var(--border);
border-radius: var(--radius-sm);
font-family: var(--mono);
font-size: 12px;
color: var(--fg-1);
flex-shrink: 0;
}
.chat-inflight-phase {
color: var(--accent);
font-weight: 600;
}
.chat-inflight-sep {
color: var(--fg-3);
}
.chat-inflight-tool {
color: var(--fg-1);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 480px;
}
.chat-inflight-abort {
margin-left: auto;
background: transparent;
border: 1px solid var(--border);
color: var(--fg-2);
padding: 3px 10px;
border-radius: var(--radius-sm);
font-family: inherit;
font-size: 11px;
cursor: pointer;
}
.chat-inflight-abort:hover {
border-color: var(--err);
color: var(--err);
}
/* ---------- Chat status bar ----------
*
* Compact metric strip below the input area. Mirrors the TUI's
@@ -1283,6 +1482,11 @@ textarea:focus {
padding: 8px 12px;
font-family: var(--mono);
font-size: 13px;
overflow-x: auto;
max-height: 240px;
overflow-y: auto;
white-space: pre-wrap;
word-break: break-all;
}
.modal-cmd-prompt {
color: var(--fg-3);
@@ -1292,6 +1496,7 @@ textarea:focus {
color: var(--primary);
background: transparent;
padding: 0;
word-break: break-all;
}
.modal-actions {
@@ -1362,6 +1567,64 @@ textarea:focus {
overflow-y: auto;
}
/* Plan-revision modal — list of remaining steps with risk dots. */
.modal-revise-reason {
background: var(--bg-2);
border-left: 3px solid #c4b5fd;
border-radius: 0 var(--radius-sm) var(--radius-sm) 0;
padding: 8px 12px;
color: var(--fg-1);
font-size: 13px;
white-space: pre-wrap;
}
.modal-revise-steps {
list-style: none;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
gap: 6px;
max-height: 280px;
overflow-y: auto;
}
.modal-revise-steps li {
display: grid;
grid-template-columns: 12px 64px 1fr;
grid-template-rows: auto auto;
gap: 2px 10px;
background: var(--bg-2);
border: 1px solid var(--border);
border-radius: var(--radius-sm);
padding: 8px 12px;
align-items: center;
}
.modal-revise-dot {
grid-row: 1 / 3;
width: 8px;
height: 8px;
border-radius: 50%;
align-self: center;
}
.modal-revise-id {
grid-row: 1;
font-family: var(--mono);
font-size: 12px;
color: var(--fg-2);
}
.modal-revise-title {
grid-row: 1;
color: var(--fg-0);
font-size: 13px;
font-weight: 500;
}
.modal-revise-action {
grid-column: 2 / 4;
grid-row: 2;
color: var(--fg-2);
font-size: 12px;
white-space: pre-wrap;
}
.modal-edit-preview {
background: var(--bg-2);
border: 1px solid var(--border);
@@ -1376,6 +1639,117 @@ textarea:focus {
max-height: 200px;
}
/* Side-by-side diff for the edit-review modal — left is "before" (red
* tint), right is "after" (green tint), context rows render unchanged.
* Lines hljs-highlight per the file's language. */
.edit-diff-wrap {
border: 1px solid var(--border);
border-radius: var(--radius-sm);
background: var(--bg-2);
font-family: var(--mono);
font-size: 12px;
overflow: hidden;
max-height: 60vh;
display: flex;
flex-direction: column;
}
.edit-diff-head {
display: flex;
background: var(--bg-1);
border-bottom: 1px solid var(--border);
font-size: 11px;
text-transform: uppercase;
letter-spacing: 0.06em;
color: var(--fg-3);
flex-shrink: 0;
}
.edit-diff-side {
flex: 1;
padding: 6px 12px;
}
.edit-diff-side + .edit-diff-side {
border-left: 1px solid var(--border);
}
.edit-diff-side-old .edit-diff-marker {
color: #f87171;
font-weight: 700;
margin-right: 4px;
}
.edit-diff-side-new .edit-diff-marker {
color: #86efac;
font-weight: 700;
margin-right: 4px;
}
.edit-diff-body {
flex: 1;
overflow-y: auto;
overflow-x: auto;
}
.edit-diff-row {
display: flex;
width: 100%;
align-items: stretch;
min-height: 19px;
}
.edit-diff-cell {
flex: 1;
padding: 1px 12px;
white-space: pre;
overflow-x: auto;
border-right: 1px solid var(--border);
color: var(--fg-1);
line-height: 1.55;
}
.edit-diff-cell:last-child {
border-right: none;
}
.edit-diff-row-context .edit-diff-cell {
background: transparent;
color: var(--fg-2);
}
.edit-diff-row-del .edit-diff-cell-old,
.edit-diff-row-change .edit-diff-cell-old {
background: rgba(248, 113, 113, 0.12);
border-left: 2px solid #f87171;
padding-left: 10px;
}
.edit-diff-row-ins .edit-diff-cell-new,
.edit-diff-row-change .edit-diff-cell-new {
background: rgba(134, 239, 172, 0.12);
border-left: 2px solid #86efac;
padding-left: 10px;
}
.edit-diff-cell-old .edit-diff-empty,
.edit-diff-cell-new .edit-diff-empty {
display: inline-block;
width: 1px;
}
.edit-diff-row-del .edit-diff-cell-new,
.edit-diff-row-ins .edit-diff-cell-old {
background: var(--bg-3);
opacity: 0.5;
}
.edit-diff-line {
font-family: var(--mono);
}
@media (max-width: 800px) {
.edit-diff-row {
flex-direction: column;
}
.edit-diff-cell {
border-right: none;
border-bottom: 1px solid var(--border);
}
.edit-diff-head {
flex-direction: column;
}
.edit-diff-side + .edit-diff-side {
border-left: none;
border-top: 1px solid var(--border);
}
}
.muted {
color: var(--fg-3);
}
@@ -1538,8 +1912,8 @@ textarea:focus {
transition: width 0.2s ease-out;
}
.editor-drawer-host.open {
width: 50%;
min-width: 360px;
width: 65%;
min-width: 420px;
}
.editor-drawer-head {
@@ -1593,9 +1967,10 @@ textarea:focus {
.editor-shell {
display: flex;
flex-direction: column;
height: calc(100vh - 56px);
gap: 12px;
padding: 12px;
padding: 0;
background: var(--bg-0);
}
/* When the editor renders inside the right-side drawer, it follows
@@ -1611,18 +1986,64 @@ textarea:focus {
height: auto;
min-height: 0;
}
.editor-body {
display: flex;
flex: 1;
min-height: 0;
gap: 0;
}
.editor-side {
width: 280px;
width: 260px;
flex-shrink: 0;
display: flex;
flex-direction: column;
background: var(--bg-1);
border-right: 1px solid var(--border);
padding: 8px 8px 8px 10px;
transition: width 0.15s ease-out;
}
.editor-side.collapsed {
width: 28px;
}
.editor-side-head {
display: flex;
align-items: center;
gap: 6px;
margin-bottom: 8px;
padding: 0 2px;
}
.editor-side-label {
font-family: var(--mono);
font-size: 10px;
letter-spacing: 0.08em;
color: var(--fg-3);
text-transform: uppercase;
}
.editor-side-toggle {
margin-left: auto;
background: transparent;
border: 1px solid var(--border);
color: var(--fg-3);
font-size: 10px;
line-height: 1;
padding: 3px 6px;
border-radius: var(--radius-sm);
cursor: pointer;
}
.editor-side-toggle:hover {
border-color: var(--primary);
color: var(--primary);
}
.editor-side.collapsed .editor-side-toggle {
margin: 8px auto 0;
width: 100%;
}
.editor-files {
flex: 1;
overflow-y: auto;
border: 1px solid var(--border);
border-radius: var(--radius-md);
background: var(--bg-1);
border-radius: var(--radius-sm);
background: var(--bg-0);
}
.editor-file {
padding: 5px 10px;
@@ -1643,23 +2064,75 @@ textarea:focus {
color: var(--primary);
border-left-color: var(--primary);
}
.editor-tree-folder,
.editor-tree-file {
display: flex;
align-items: center;
gap: 4px;
font-family: var(--mono);
font-size: 11.5px;
color: var(--fg-2);
cursor: pointer;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
user-select: none;
border-left: 2px solid transparent;
padding-top: 3px;
padding-bottom: 3px;
padding-right: 8px;
}
.editor-tree-folder:hover,
.editor-tree-file:hover {
background: var(--bg-hover);
color: var(--fg-0);
}
.editor-tree-caret {
display: inline-block;
width: 12px;
font-size: 9px;
color: var(--fg-3);
flex-shrink: 0;
}
.editor-tree-name {
overflow: hidden;
text-overflow: ellipsis;
}
.editor-tree-folder {
color: var(--fg-1);
}
.editor-tree-file.open {
color: var(--primary);
border-left-color: var(--primary);
}
.editor-main {
flex: 1;
display: flex;
flex-direction: column;
min-width: 0;
background: #282c34;
}
.editor-tabs {
display: flex;
gap: 2px;
align-items: stretch;
gap: 0;
background: var(--bg-1);
border-bottom: 1px solid var(--border);
overflow-x: auto;
flex-wrap: nowrap;
flex-shrink: 0;
height: 34px;
scrollbar-width: thin;
}
.editor-tabs::-webkit-scrollbar {
height: 3px;
}
.editor-tabs::-webkit-scrollbar-thumb {
background: var(--border);
}
.editor-no-tabs {
padding: 10px 14px;
padding: 9px 14px;
color: var(--fg-3);
font-size: 12px;
font-family: var(--mono);
@@ -1668,26 +2141,31 @@ textarea:focus {
display: flex;
align-items: center;
gap: 6px;
padding: 6px 12px;
padding: 0 10px 0 12px;
background: var(--bg-1);
border: 1px solid var(--border);
border-bottom: none;
border-top-left-radius: var(--radius-sm);
border-top-right-radius: var(--radius-sm);
border: none;
border-right: 1px solid var(--border);
border-top: 2px solid transparent;
border-bottom: 1px solid var(--border);
margin-bottom: -1px;
font-family: var(--mono);
font-size: 12px;
color: var(--fg-2);
color: var(--fg-3);
cursor: pointer;
white-space: nowrap;
user-select: none;
height: 34px;
position: relative;
}
.editor-tab:hover {
color: var(--fg-0);
color: var(--fg-1);
background: var(--bg-2);
}
.editor-tab.active {
background: var(--bg-2);
color: var(--primary);
border-bottom-color: var(--bg-2);
background: #282c34;
color: var(--fg-0);
border-top-color: var(--primary);
border-bottom-color: #282c34;
}
.editor-tab-name {
max-width: 200px;
@@ -1698,14 +2176,21 @@ textarea:focus {
color: var(--accent);
font-size: 14px;
line-height: 1;
width: 12px;
text-align: center;
}
.editor-tab-close {
margin-left: 4px;
margin-left: 2px;
color: var(--fg-3);
font-size: 16px;
font-size: 14px;
line-height: 1;
padding: 0 4px;
padding: 1px 5px;
border-radius: var(--radius-sm);
width: 18px;
height: 18px;
display: inline-flex;
align-items: center;
justify-content: center;
}
.editor-tab-close:hover {
background: var(--bg-3);
@@ -1715,27 +2200,97 @@ textarea:focus {
display: flex;
align-items: center;
gap: 12px;
padding: 8px 12px;
padding: 6px 12px;
background: var(--bg-1);
border-bottom: 1px solid var(--border);
flex-shrink: 0;
}
.editor-host {
flex: 1;
overflow: hidden;
background: var(--bg-1);
border: 1px solid var(--border);
border-top: none;
border-bottom-left-radius: var(--radius-md);
border-bottom-right-radius: var(--radius-md);
background: #282c34;
border: none;
border-radius: 0;
min-height: 0;
}
.editor-host .cm-editor {
height: 100%;
font-family: var(--mono);
font-size: 13px;
outline: none;
}
.editor-host .cm-editor.cm-focused {
outline: none;
}
.editor-host .cm-scroller {
font-family: inherit;
line-height: 1.55;
}
/* VS Code-style gutter — darker bg, dim line numbers, accent on active */
.editor-host .cm-gutters {
background: #21252b;
border-right: 1px solid #181a1f;
color: #495162;
}
.editor-host .cm-lineNumbers {
font-family: var(--mono);
font-size: 12px;
min-width: 40px;
}
.editor-host .cm-lineNumbers .cm-gutterElement {
padding: 0 12px 0 16px;
color: #495162;
}
.editor-host .cm-activeLineGutter {
background: #2c313a;
color: #abb2bf;
}
.editor-host .cm-foldGutter {
color: #5c6370;
}
.editor-host .cm-foldGutter .cm-gutterElement {
padding: 0 4px;
cursor: pointer;
}
.editor-host .cm-activeLine {
background: rgba(99, 110, 123, 0.1);
}
.editor-host .cm-selectionBackground,
.editor-host .cm-content ::selection {
background: #3e4451 !important;
}
.editor-host .cm-cursor {
border-left-color: #61afef;
border-left-width: 2px;
}
/* Autocomplete popup — match the dark theme */
.cm-tooltip.cm-tooltip-autocomplete {
background: #21252b;
border: 1px solid #181a1f;
border-radius: var(--radius-sm);
font-family: var(--mono);
font-size: 12px;
box-shadow: 0 6px 16px rgba(0, 0, 0, 0.4);
}
.cm-tooltip.cm-tooltip-autocomplete > ul > li {
padding: 3px 10px;
color: #abb2bf;
}
.cm-tooltip.cm-tooltip-autocomplete > ul > li[aria-selected] {
background: var(--primary);
color: #1e2127;
}
.cm-completionLabel {
font-family: var(--mono);
}
.cm-completionDetail {
color: #5c6370;
font-style: normal;
margin-left: 8px;
}
.editor-empty {
flex: 1;
display: flex;
@@ -1744,16 +2299,164 @@ textarea:focus {
color: var(--fg-3);
font-family: var(--mono);
font-size: 13px;
background: #282c34;
}
/* Split view — left half source (CodeMirror), right half preview. */
.editor-split {
flex: 1;
display: flex;
min-height: 0;
overflow: hidden;
}
.editor-split-pane {
flex: 1;
min-width: 0;
border: none;
border-radius: 0;
}
.editor-split .editor-split-pane + .editor-split-pane {
border-left: 1px solid #181a1f;
}
/* Segmented control for Edit / Split / Preview */
.view-mode-group {
display: inline-flex;
background: var(--bg-2);
border: 1px solid var(--border);
border-radius: var(--radius-sm);
overflow: hidden;
padding: 0;
}
.view-mode-group .view-mode {
background: transparent;
border: none;
padding: 3px 10px;
font-size: 11px;
font-family: var(--mono);
color: var(--fg-3);
cursor: pointer;
border-radius: 0;
}
.view-mode-group .view-mode:hover {
color: var(--fg-1);
background: var(--bg-hover);
}
.view-mode-group .view-mode.active {
background: var(--primary);
color: #1e2127;
}
/* Markdown preview — render the same .md styles used in chat,
* but with scroll and a comfortable max-width so prose doesn't
* stretch across the full editor width. */
.editor-md-preview {
overflow-y: auto;
padding: 24px 36px;
background: #282c34;
color: #abb2bf;
font-family: var(--font-sans, system-ui, sans-serif);
font-size: 14px;
line-height: 1.65;
}
.editor-md-preview > *:first-child {
margin-top: 0;
}
.editor-md-preview h1,
.editor-md-preview h2,
.editor-md-preview h3,
.editor-md-preview h4 {
color: #e5e9f0;
margin: 1.4em 0 0.6em;
line-height: 1.3;
}
.editor-md-preview h1 {
font-size: 1.8em;
border-bottom: 1px solid #3e4451;
padding-bottom: 0.3em;
}
.editor-md-preview h2 {
font-size: 1.4em;
border-bottom: 1px solid #3e4451;
padding-bottom: 0.3em;
}
.editor-md-preview h3 {
font-size: 1.15em;
}
.editor-md-preview a {
color: #61afef;
text-decoration: none;
}
.editor-md-preview a:hover {
text-decoration: underline;
}
.editor-md-preview code {
background: #21252b;
color: #e06c75;
padding: 1px 6px;
border-radius: 3px;
font-family: var(--mono);
font-size: 0.92em;
}
.editor-md-preview pre {
background: #21252b;
border: 1px solid #181a1f;
border-radius: 4px;
padding: 12px 14px;
overflow-x: auto;
}
.editor-md-preview pre code {
background: transparent;
color: #abb2bf;
padding: 0;
}
.editor-md-preview blockquote {
border-left: 3px solid #5c6370;
margin: 0.8em 0;
padding: 0.2em 0.9em;
color: #828997;
}
.editor-md-preview table {
border-collapse: collapse;
margin: 0.8em 0;
}
.editor-md-preview th,
.editor-md-preview td {
border: 1px solid #3e4451;
padding: 5px 10px;
}
.editor-md-preview th {
background: #21252b;
}
.editor-md-preview hr {
border: none;
border-top: 1px solid #3e4451;
margin: 1.5em 0;
}
.editor-md-preview ul,
.editor-md-preview ol {
padding-left: 1.6em;
}
.editor-md-preview img {
max-width: 100%;
}
@media (max-width: 800px) {
.editor-shell {
flex-direction: column;
height: calc(100vh - 100px);
}
.editor-body {
flex-direction: column;
}
.editor-side {
width: 100%;
max-height: 200px;
border-right: none;
border-bottom: 1px solid var(--border);
}
.editor-side.collapsed {
width: 100%;
max-height: 32px;
}
}
+1117 -211
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
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+59 -3
View File
@@ -16,7 +16,7 @@
"nav.benchmarks": "Benchmarks",
"nav.github": "GitHub",
"hero.badge": "v0.6 · DeepSeek V4 · cache-first",
"hero.badge": "v{version} · DeepSeek V4 · cache-first",
"hero.title.line1": "DeepSeek-native",
"hero.title.line2": "AI coding agent in your terminal",
"hero.sub":
@@ -143,7 +143,7 @@
"nav.benchmarks": "性能对比",
"nav.github": "GitHub",
"hero.badge": "v0.6 · DeepSeek V4 · 缓存优先",
"hero.badge": "v{version} · DeepSeek V4 · 缓存优先",
"hero.title.line1": "DeepSeek 原生",
"hero.title.line2": "终端里的 AI 编程代理",
"hero.sub":
@@ -304,6 +304,49 @@
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;
@@ -316,7 +359,7 @@
document.querySelectorAll("[data-i18n]").forEach((el) => {
const key = el.getAttribute("data-i18n");
if (dict[key] !== undefined) {
el.innerHTML = dict[key];
el.innerHTML = fillVersion(dict[key]);
}
});
@@ -350,6 +393,12 @@
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) => {
@@ -393,9 +442,16 @@
}
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") {
+18 -2
View File
@@ -43,14 +43,21 @@
];
// ──────────────────────────────────────────────────────────────────
// Header bar — `◈ REASONIX v0.6.0 v4-flash REVIEW max … turn 1 · /help`
// 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">v0.6.0</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>' +
@@ -372,6 +379,15 @@
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));
+1530 -555
View File
File diff suppressed because it is too large. Load diff
+33 -2
View File
@@ -1,6 +1,6 @@
{
"name": "reasonix",
"version": "0.12.0",
"version": "0.16.0",
"description": "DeepSeek-native coding agent: cache-first loop, flash-first cost control, tool-call repair.",
"type": "module",
"bin": {
@@ -21,11 +21,13 @@
"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",
@@ -34,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",
@@ -65,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) {
+16 -1
View File
@@ -14,7 +14,7 @@ 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";
@@ -38,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[];
@@ -69,6 +76,12 @@ export interface ChatOptions {
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 {
@@ -149,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>
);
+11 -1
View File
@@ -21,7 +21,7 @@
import { basename, resolve } from "node:path";
import { loadEditMode, loadProjectShellAllowed } from "../../config.js";
import { bootstrapSemanticSearchInCodeMode } from "../../index/semantic/tool.js";
import { sanitizeName } from "../../session.js";
import { sanitizeName } from "../../memory/session.js";
import { ToolRegistry } from "../../tools.js";
import { registerChoiceTool } from "../../tools/choice.js";
import { registerFilesystemTools } from "../../tools/filesystem.js";
@@ -53,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> {
@@ -146,6 +154,7 @@ export async function codeCommand(opts: CodeOptions = {}): Promise<void> {
await chatCommand({
model: opts.model ?? "deepseek-v4-flash",
harvest: opts.harvest ?? false,
budgetUsd: opts.budgetUsd,
system: codeSystemPrompt(rootDir, { hasSemanticSearch: semantic.enabled }),
transcript: opts.transcript,
session,
@@ -153,5 +162,6 @@ export async function codeCommand(opts: CodeOptions = {}): Promise<void> {
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;
}
+2 -40
View File
@@ -1,25 +1,4 @@
/**
* `reasonix index` — build (or incrementally refresh) the project's
* semantic search index.
*
* Usage:
* reasonix index # incremental: only re-embeds changed files
* reasonix index --rebuild # wipe + rebuild from scratch
* reasonix index --model MODEL # override embedding model
* reasonix index --dir PATH # index a different directory
*
* Output is rendered to stderr so piping the index to a script
* (which we don't actually do today, but might) keeps stdout clean.
*
* On a TTY the progress writer paints `<spinner> <status> <elapsed>s`
* on a single line, ticking every 120ms via setInterval — so the
* line keeps animating even between onProgress events. That's the
* load-bearing UX guarantee: builds that take 30+ seconds never
* leave the user wondering whether the process is hung.
*
* On non-TTY (CI, piped logs) we emit one line per phase + a
* periodic heartbeat. No \r tricks because they make logs unreadable.
*/
/** `reasonix index` — progress writes go to stderr so stdout stays pipeable. */
import { resolve } from "node:path";
import { buildIndex } from "../../index/semantic/builder.js";
@@ -95,12 +74,6 @@ interface ProgressWriter {
clear(): void;
}
/**
* Braille spinner — same alphabet most CLI spinners use. Ten frames,
* cycled at ~120ms each. Visually clear that the process is alive
* even when no progress events fire (e.g. during phase transitions
* or while waiting on Ollama's first model-load latency).
*/
const SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
const SPINNER_INTERVAL_MS = 120;
@@ -109,11 +82,6 @@ function makeProgressWriter(tty: boolean): ProgressWriter {
return makeTtyWriter();
}
/**
* Non-TTY writer — one line per phase transition + a heartbeat every
* 50 embedded chunks. Keeps logs short and parseable while still
* proving forward motion.
*/
function makeNonTtyWriter(): ProgressWriter {
let lastPhase: BuildProgress["phase"] | null = null;
let lastChunks = 0;
@@ -148,13 +116,7 @@ function makeNonTtyWriter(): ProgressWriter {
};
}
/**
* TTY writer — paints `<spinner> <status> <elapsed>s` on a single
* line via \r. The spinner ticks on a setInterval, INDEPENDENT of
* onProgress events: even if the embedder hangs for 5 seconds on
* the first model-load, the spinner keeps spinning so the user sees
* the process is alive.
*/
/** Spinner ticks on its own setInterval so a hung embedder still shows liveness. */
function makeTtyWriter(): ProgressWriter {
let status = t("progressStarting");
let lastLineLen = 0;
-11
View File
@@ -1,14 +1,3 @@
/**
* `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";
-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 {
+4 -2
View File
@@ -10,9 +10,9 @@ 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;
@@ -22,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..."`. */
@@ -127,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";
+2 -26
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);
+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));
+95 -5
View File
@@ -1,12 +1,15 @@
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";
@@ -41,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")
@@ -90,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")
@@ -101,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,
@@ -110,6 +134,8 @@ program
forceResume: !!opts.resume,
forceNew: !!opts.new,
harvest: !!opts.harvest,
budgetUsd: parseBudgetFlag(opts.budget),
noDashboard: opts.dashboard === false,
});
});
@@ -121,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",
@@ -132,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")
@@ -151,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,
@@ -179,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,
});
});
@@ -192,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>",
@@ -226,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,
@@ -242,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.")
@@ -250,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(
+1 -24
View File
@@ -1,17 +1,4 @@
/**
* 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 { resolvePreset } from "./ui/presets.js";
@@ -99,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,
+1072 -326
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>
+191 -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;
@@ -125,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;
}
/**
@@ -159,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>
);
}
@@ -248,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}
@@ -287,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 =
@@ -299,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>
@@ -312,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>
);
}
@@ -334,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>
@@ -482,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>
@@ -650,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>
);
}
@@ -676,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>
);
}
@@ -740,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>;
}
/**
@@ -876,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>
);
}
+1 -1
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: {},
});
+14 -10
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 WorkspaceConfirmChoice = "switch" | "deny";
@@ -14,13 +15,14 @@ export interface WorkspaceConfirmProps {
* those won't follow the switch (their child processes were spawned
* with the original cwd). 0 means no warning. */
mcpServerCount: number;
onChoose: (choice: WorkspaceConfirmChoice) => void;
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.
* switches are per-target by nature. Tab on Deny opens inline
* context entry, returned as `onChoose`'s 2nd arg.
*/
export function WorkspaceConfirm({
path,
@@ -32,16 +34,17 @@ export function WorkspaceConfirm({
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="#f59e0b" icon="⇄" title="switch workspace" subtitle={subtitle}>
<ModalCard accent={COLOR.warn} icon="⇄" title="switch workspace" subtitle={subtitle}>
<Box flexDirection="column" marginBottom={1}>
<Box>
<Text dimColor>{"from "}</Text>
<Text color="#a3a3a3">{currentRoot}</Text>
<Text dimColor>{"from "}</Text>
<Text color={COLOR.info}>{currentRoot}</Text>
</Box>
<Box>
<Text dimColor>{"to "}</Text>
<Text color="#67e8f9" bold>
<Text dimColor>{"to "}</Text>
<Text color={COLOR.primary} bold>
{path}
</Text>
</Box>
@@ -57,12 +60,13 @@ export function WorkspaceConfirm({
{
value: "deny",
label: "Deny",
hint: "Tell the model the user refused; it will continue without changing directories.",
hint: "Tell the model why you're refusing; it will continue without changing directories.",
denyWithContext: true,
},
]}
onSubmit={(v) => onChoose(v as WorkspaceConfirmChoice)}
onSubmit={(v, ctx) => onChoose(v as WorkspaceConfirmChoice, ctx)}
onCancel={() => onChoose("deny")}
footer="[↑↓] navigate · [Enter] select · [Esc] 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);
}
+55 -6
View File
@@ -439,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" };
@@ -476,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}` };
@@ -791,7 +830,7 @@ interface TableBlock {
rows: string[][];
}
type Block =
export type Block =
| ParagraphBlock
| HeadingBlock
| BulletBlock
@@ -800,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`;
+6 -44
View File
@@ -1,40 +1,10 @@
/**
* 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. `high` = shorter chain of thought; `max` =
* agent-class default (deeper, more output). Effort is now decoupled
* from preset — a separate `/effort` knob lets users tune it
* orthogonally. The PRESETS table just picks the safest default.
*/
reasoningEffort: "high" | "max";
/**
* Auto-escalation switch. `auto` keeps the legacy NEEDS_PRO + failure
* threshold behavior; `flash` and `pro` lock to the chosen model.
*/
autoEscalate: boolean;
/** Pillar-2 harvest. Always false in presets — opt-in via /harvest. */
harvest: boolean;
@@ -42,11 +12,7 @@ export interface PresetSettings {
branch: number;
}
/**
* The three real presets. Old names (`fast / smart / max`) stay alive
* as aliases mapped through `resolvePreset` so a config.json that
* predates this rename still works without a migration script.
*/
/** 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.
@@ -98,16 +64,12 @@ export const PRESET_DESCRIPTIONS: Record<
},
};
/**
* Resolve a preset name (canonical or unknown) to its settings.
* Anything that isn't `auto | flash | pro` — including the dropped
* legacy `fast / smart / max` aliases — collapses to `auto`. Simpler
* than mapping legacy values (each legacy name had its own semantics
* that don't 1:1 onto the new model-commitment vocabulary); auto is
* the safe default and the user can re-pick explicitly.
*/
/** Legacy aliases: fast→flash+high, smart→auto, max→pro. Unknown names fall through to auto. */
export function resolvePreset(name: PresetName | undefined): PresetSettings {
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;
}
+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 = "";
+34 -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",
@@ -100,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)" },
{
@@ -118,6 +128,11 @@ 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",
@@ -177,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]",
@@ -212,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) => {
@@ -225,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);
+1 -14
View File
@@ -16,22 +16,9 @@ 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,
+3 -39
View File
@@ -7,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";
@@ -69,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}`];
@@ -123,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);
@@ -152,21 +130,7 @@ const stats: SlashHandler = () => {
return { info: renderDashboard(agg, path) };
};
/**
* `/cwd <path>` — switch the session working directory mid-session.
* Validates the target (must exist, must be a directory), normalizes
* to an absolute path with `~` expansion, then defers the actual swap
* to the App-supplied `setCwd` callback. The callback updates hook
* cwd, memory root, project shell allowlist root, `@file` mention
* root, and (in code mode) re-registers filesystem / shell / memory /
* skill tools — see App.tsx for the wiring.
*
* MCP servers do NOT follow the cwd switch — their stdio child was
* spawned with the original cwd at session start, and there's no
* standard "reconnect with new cwd" handshake. The handler surfaces
* a one-line warning when MCP servers are present so users aren't
* surprised by tools still resolving paths against the old root.
*/
/** 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 {
+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",
-11
View File
@@ -1,16 +1,5 @@
import type { SlashHandler } from "../dispatch.js";
/**
* `/dashboard [stop]` — boot the embedded web dashboard attached to
* the current session. The actual server start / state capture lives
* in App.tsx (`startDashboard` callback), which has direct refs to
* the live loop, tool registry, MCP servers, and edit-mode state.
* The slash handler is just the user-facing input + output bridge.
*
* Sub-commands:
* /dashboard → boot if not running, print URL; if running, print existing URL
* /dashboard stop → tear down the server
*/
const dashboard: SlashHandler = (args, _loop, ctx) => {
if (!ctx.startDashboard || !ctx.getDashboardUrl) {
return {
+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,
};
+2 -26
View File
@@ -1,34 +1,10 @@
/**
* `/init` — auto-generate a baseline REASONIX.md by asking the model
* to scan the project and synthesize a concise summary.
*
* Mechanism: the slash handler injects a structured user-turn prompt
* (via `resubmit`) that hard-constrains the model to write a short,
* fact-only document and stop. It uses the same filesystem tools the
* model already has — no new tool, no new pipeline. The model's output
* lands as an `edit_file` (empty SEARCH = create new) or `write_file`
* SEARCH/REPLACE block, which goes through the normal /apply review
* gate so the user can audit before the file hits disk.
*
* Why this shape rather than a CLI command: REASONIX.md goes into
* the system prompt every session, so its content has to fit. A
* model-driven generator that runs inside the same loop the user
* will use later gives the most consistent output, and reusing the
* existing edit-review flow means we don't have to invent a
* separate "review the generated doc" UI.
*/
/** `/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";
/**
* The init brief. Sent verbatim as a user turn (via resubmit). Hard
* constraints up top because flash will skim and the structure of
* the document matters for system-prompt budget. The "STOP after
* writing" line is load-bearing — without it the model will follow
* up with "want me to also …" and burn turns on noise.
*/
/** "STOP after writing" is load-bearing — without it the model burns extra turns on follow-up offers. */
const INIT_PROMPT = [
"# Task: Initialize REASONIX.md",
"",
+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") };
};
+2 -11
View File
@@ -2,20 +2,11 @@ import {
PROJECT_MEMORY_FILE,
memoryEnabled,
readProjectMemory,
} from "../../../../project-memory.js";
import { type MemoryScope, MemoryStore } from "../../../../user-memory.js";
} from "../../../../memory/project.js";
import { type MemoryScope, MemoryStore } from "../../../../memory/user.js";
import type { SlashHandler } from "../dispatch.js";
import { resolveMemoryTarget } from "../helpers.js";
/**
* `/memory` family. Bare `/memory` shows what's pinned (REASONIX.md +
* both MEMORY.md blocks). Subcommands manage the user-memory store:
* list — every memory file, both scopes
* show <name> — dump one file's body
* show <scope>/<name> — disambiguate when name exists in both scopes
* forget <name> — delete (same scope resolution as show)
* clear <scope> confirm — wipe a scope (typed literal "confirm" required)
*/
const memory: SlashHandler = (args, _loop, ctx) => {
if (!memoryEnabled()) {
return {
+72 -24
View File
@@ -1,4 +1,5 @@
import { saveReasoningEffort } from "../../../../config.js";
import { PRESETS } from "../../presets.js";
import type { SlashHandler } from "../dispatch.js";
const model: SlashHandler = (args, loop, ctx) => {
@@ -73,39 +74,43 @@ const preset: SlashHandler = (args, loop) => {
/* disk full / perms — runtime change still took effect */
}
};
if (name === "fast" || name === "default") {
if (name === "auto") {
const p = PRESETS.auto;
loop.configure({
model: "deepseek-v4-flash",
reasoningEffort: "high",
harvest: false,
branch: 1,
model: p.model,
autoEscalate: p.autoEscalate,
reasoningEffort: p.reasoningEffort,
harvest: p.harvest,
branch: p.branch,
});
applyAndPersist("high");
return { info: "preset → fast (v4-flash · effort=high · cheapest)" };
applyAndPersist(p.reasoningEffort);
return { info: "preset → auto (v4-flash → v4-pro on hard turns · default)" };
}
if (name === "smart") {
if (name === "flash") {
const p = PRESETS.flash;
loop.configure({
model: "deepseek-v4-flash",
reasoningEffort: "max",
harvest: false,
branch: 1,
model: p.model,
autoEscalate: p.autoEscalate,
reasoningEffort: p.reasoningEffort,
harvest: p.harvest,
branch: p.branch,
});
applyAndPersist("max");
return { info: "preset → smart (v4-flash · effort=max · default · ~1.5× fast)" };
applyAndPersist(p.reasoningEffort);
return { info: "preset → flash (v4-flash always · cheapest · /pro still bumps one turn)" };
}
if (name === "max" || name === "best") {
if (name === "pro") {
const p = PRESETS.pro;
loop.configure({
model: "deepseek-v4-pro",
reasoningEffort: "max",
harvest: false,
branch: 1,
model: p.model,
autoEscalate: p.autoEscalate,
reasoningEffort: p.reasoningEffort,
harvest: p.harvest,
branch: p.branch,
});
applyAndPersist("max");
return {
info: "preset → max (v4-pro · effort=max · ~12× fast · save for hard tasks, or use /pro for a single-turn bump)",
};
applyAndPersist(p.reasoningEffort);
return { info: "preset → pro (v4-pro always · ~3× flash · for hard multi-turn work)" };
}
return { info: "usage: /preset <fast|smart|max>" };
return { info: "usage: /preset <auto|flash|pro>" };
};
const branch: SlashHandler = (args, loop) => {
@@ -176,6 +181,48 @@ const pro: SlashHandler = (args, loop, ctx) => {
// internal constant renames).
const ESCALATION_MODEL_ID = "deepseek-v4-pro";
const budget: SlashHandler = (args, loop) => {
const arg = args[0]?.trim() ?? "";
// Bare /budget → status. No-cap state is the default Reasonix ships
// with, so the message stays calm rather than making it sound like
// a missing config.
if (arg === "") {
if (loop.budgetUsd === null) {
return {
info: "no session budget set — Reasonix will keep going until you stop it. Set one with: /budget <usd> (e.g. /budget 5)",
};
}
const spent = loop.stats.totalCost;
const pct = (spent / loop.budgetUsd) * 100;
return {
info: `budget: $${spent.toFixed(4)} of $${loop.budgetUsd.toFixed(2)} (${pct.toFixed(1)}%) · /budget off to clear, /budget <usd> to change`,
};
}
// Explicit clear.
if (arg === "off" || arg === "none" || arg === "0") {
loop.setBudget(null);
return { info: "budget → off (no cap)" };
}
// Strip a leading $ since users will type it half the time.
const cleaned = arg.replace(/^\$/, "");
const usd = Number(cleaned);
if (!Number.isFinite(usd) || usd <= 0) {
return {
info: `usage: /budget <usd> (got "${arg}" — must be a positive number, e.g. /budget 5 or /budget 12.50)`,
};
}
loop.setBudget(usd);
const spent = loop.stats.totalCost;
if (spent >= usd) {
return {
info: `▲ budget → $${usd.toFixed(2)} but already spent $${spent.toFixed(4)}. Next turn will be refused — bump the cap higher to keep going, or end the session.`,
};
}
return {
info: `budget → $${usd.toFixed(2)} (so far: $${spent.toFixed(4)} · warns at 80%, refuses next turn at 100% · /budget off to clear)`,
};
};
export const handlers: Record<string, SlashHandler> = {
model,
models,
@@ -184,4 +231,5 @@ export const handlers: Record<string, SlashHandler> = {
branch,
effort,
pro,
budget,
};
+61 -74
View File
@@ -1,5 +1,5 @@
import { DEEPSEEK_CONTEXT_TOKENS, DEFAULT_CONTEXT_TOKENS } from "../../../../telemetry.js";
import { countTokens } from "../../../../tokenizer.js";
import { DEEPSEEK_CONTEXT_TOKENS, DEFAULT_CONTEXT_TOKENS } from "../../../../telemetry/stats.js";
import { computeCtxBreakdown } from "../../ctx-breakdown.js";
import type { SlashHandler } from "../dispatch.js";
import { compactNum, formatToolList } from "../helpers.js";
@@ -53,87 +53,61 @@ const tool: SlashHandler = (args, _loop, ctx) => {
};
};
const context: SlashHandler = (_args, loop) => {
// Measure each slice of the next request locally so the user can see
// *where* context is being spent — a much more useful number than
// the "last turn's total" the gauge shows. Tokenization is lazy so
// the first /context call carries the data-file load cost (~100ms);
// subsequent calls are pure compute.
const systemTokens = countTokens(loop.prefix.system);
const toolsTokens = countTokens(JSON.stringify(loop.prefix.toolSpecs));
const entries = loop.log.toMessages();
let userTokens = 0;
let assistantTokens = 0;
let toolResultTokens = 0;
let toolCallTokens = 0;
const toolBreakdown: Array<{ name: string; tokens: number; turn: number }> = [];
let logTurn = 0;
for (const e of entries) {
const content = typeof e.content === "string" ? e.content : "";
if (e.role === "user") {
userTokens += countTokens(content);
logTurn += 1;
} else if (e.role === "assistant") {
assistantTokens += countTokens(content);
if (Array.isArray(e.tool_calls) && e.tool_calls.length > 0) {
toolCallTokens += countTokens(JSON.stringify(e.tool_calls));
}
} else if (e.role === "tool") {
const n = countTokens(content);
toolResultTokens += n;
toolBreakdown.push({ name: e.name ?? "?", tokens: n, turn: logTurn });
}
const context: SlashHandler = (args, loop, ctx) => {
// Toggle the persistent footer when wired (TUI). Falls back to a
// one-shot scrollback breakdown push for headless / replay surfaces
// that don't carry the toggle callback.
if (ctx.toggleCtxFooter) {
const arg = (args[0] ?? "").toLowerCase();
const force = arg === "on" ? true : arg === "off" ? false : undefined;
const next = ctx.toggleCtxFooter(force);
return { info: `▸ context footer: ${next ? "on" : "off"}` };
}
const logTokens = userTokens + assistantTokens + toolResultTokens + toolCallTokens;
const total = systemTokens + toolsTokens + logTokens;
const ctxMax = DEEPSEEK_CONTEXT_TOKENS[loop.model] ?? DEFAULT_CONTEXT_TOKENS;
const pct = (n: number) => (total > 0 ? `${Math.round((n / total) * 100)}%`.padStart(4) : " 0%");
const row = (label: string, n: number, note = "") =>
` ${label.padEnd(20)}${compactNum(n).padStart(8)} tokens ${pct(n)}${note ? ` ${note}` : ""}`;
const lines = [
`Next-request estimate: ~${compactNum(total)} tokens of ${compactNum(ctxMax)} (${Math.round(
(total / ctxMax) * 100,
)}% of window)`,
"",
row("system prompt", systemTokens),
row("tool specs", toolsTokens, `(${loop.prefix.toolSpecs.length} tools)`),
row("log (all turns)", logTokens, `(${entries.length} messages)`),
` user ${compactNum(userTokens).padStart(8)} tokens`,
` assistant ${compactNum(assistantTokens).padStart(8)} tokens`,
` tool-call args ${compactNum(toolCallTokens).padStart(8)} tokens`,
` tool results ${compactNum(toolResultTokens).padStart(8)} tokens`,
];
// Top 5 heaviest tool results — usually where unexpected bloat
// lives (a big read_file, an unfiltered search_content).
if (toolBreakdown.length > 0) {
const top = [...toolBreakdown].sort((a, b) => b.tokens - a.tokens).slice(0, 5);
lines.push("");
lines.push(`Top tool results by cost (of ${toolBreakdown.length} total):`);
for (const t of top) {
lines.push(
` turn ${String(t.turn).padStart(3)} ${t.name.padEnd(22)} ${compactNum(t.tokens).padStart(8)} tokens`,
);
}
}
lines.push("");
lines.push(
"Count is a local estimate (DeepSeek V3 tokenizer, pure-TS port); server prompt_tokens may add ~3-6% for chat-template role markers.",
);
return { info: lines.join("\n") };
const breakdown = computeCtxBreakdown(loop);
const total =
breakdown.systemTokens + breakdown.toolsTokens + breakdown.logTokens + breakdown.inputTokens;
const winPct = breakdown.ctxMax > 0 ? Math.round((total / breakdown.ctxMax) * 100) : 0;
const fallbackInfo = `context: ~${compactNum(total)} of ${compactNum(breakdown.ctxMax)} (${winPct}%) · system ${compactNum(breakdown.systemTokens)} · tools ${compactNum(breakdown.toolsTokens)} · log ${compactNum(breakdown.logTokens)}`;
return { info: fallbackInfo, ctxBreakdown: breakdown };
};
const status: SlashHandler = (_args, loop, ctx) => {
const branchBudget = loop.branchOptions.budget ?? 1;
const ctxMax = DEEPSEEK_CONTEXT_TOKENS[loop.model] ?? DEFAULT_CONTEXT_TOKENS;
const lastPromptTokens = loop.stats.summary().lastPromptTokens;
const summary = loop.stats.summary();
const lastPromptTokens = summary.lastPromptTokens;
const ctxPct = ctxMax > 0 ? Math.round((lastPromptTokens / ctxMax) * 100) : 0;
// 16-cell context bar — narrower than /context's 48 since /status is
// a quick glance, not the deep dive. Same `█/░` characters so the
// visual grammar stays consistent across slashes.
const ctxBar = lastPromptTokens > 0 ? renderTinyBar(ctxPct, 16) : "";
const ctxLine =
lastPromptTokens > 0
? ` ctx ${compactNum(lastPromptTokens)}/${compactNum(ctxMax)} (${ctxPct}%)`
: " ctx no turns yet";
? ` ctx ${ctxBar} ${compactNum(lastPromptTokens)}/${compactNum(ctxMax)} (${ctxPct}%)`
: " ctx no turns yet";
// Cost / cache hit row — the high-signal numbers from StatsPanel.
// Cache pct only shown after the cold-start window so a 0.0% on
// turn 1 doesn't read as broken.
const cost = summary.totalCostUsd;
const cacheLine =
summary.turns > 3
? (() => {
const cachePct = Math.round(summary.cacheHitRatio * 100);
return ` cost $${cost.toFixed(4)} · cache ${renderTinyBar(cachePct, 12)} ${cachePct}% · turns ${summary.turns}`;
})()
: ` cost $${cost.toFixed(4)} · turns ${summary.turns} (cache warming up)`;
// Budget row — only when a cap is set
const budgetLine =
typeof loop.budgetUsd === "number"
? (() => {
const pct = Math.round((cost / loop.budgetUsd!) * 100);
const tag = pct >= 100 ? " ▲ EXHAUSTED" : pct >= 80 ? " ▲ 80%+" : "";
return ` budget $${cost.toFixed(4)} / $${loop.budgetUsd!.toFixed(2)} (${pct}%)${tag}`;
})()
: "";
const pending = ctx.pendingEditCount ?? 0;
const sessionLine = loop.sessionName
? ` session "${loop.sessionName}" · ${loop.log.length} messages in log (resumed ${loop.resumedMessageCount})`
@@ -152,19 +126,32 @@ const status: SlashHandler = (_args, loop, ctx) => {
: ctx.editMode === "review"
? " mode review — edits queue for /apply or y (Shift+Tab to flip)"
: "";
const dashLine = ctx.getDashboardUrl?.()
? ` dash ${ctx.getDashboardUrl?.()} (open in browser · /dashboard stop)`
: "";
const lines = [
` model ${loop.model}`,
` flags harvest=${loop.harvestEnabled ? "on" : "off"} · branch=${branchBudget > 1 ? branchBudget : "off"} · stream=${loop.stream ? "on" : "off"} · effort=${loop.reasoningEffort}`,
cacheLine,
ctxLine,
mcpLine,
sessionLine,
];
if (budgetLine) lines.push(budgetLine);
if (pendingLine) lines.push(pendingLine);
if (planLine) lines.push(planLine);
if (modeLine) lines.push(modeLine);
if (dashLine) lines.push(dashLine);
return { info: lines.join("\n") };
};
function renderTinyBar(pct: number, width: number): string {
const w = Math.max(4, width);
const clamped = Math.max(0, Math.min(100, pct));
const filled = Math.round((w * clamped) / 100);
return `[${"█".repeat(filled)}${"░".repeat(w - filled)}]`;
}
const compact: SlashHandler = (args, loop) => {
// Manual companion to the automatic 60%/80% auto-compact. Re-applies
// token-aware truncation with a tighter cap (default 4000 tokens per
-17
View File
@@ -7,23 +7,6 @@ import {
import { BUILTIN_ALLOWLIST } from "../../../../tools/shell.js";
import type { SlashHandler } from "../dispatch.js";
/**
* `/permissions` family. Mirrors /memory's shape — bare lists state,
* subcommands manage it. Two layers exist:
*
* 1. Builtin allowlist — baked into shell.ts (`BUILTIN_ALLOWLIST`),
* always on. Read-only here.
* 2. Per-project allowlist — `~/.reasonix/config.json`, populated by
* "always allow" picks on ShellConfirm. Add / remove / clear here.
*
* Edit-mode (review / auto / yolo) is also surfaced at the top so users
* see "yolo skips all of this" without having to re-derive it from /mode.
*
* Subcommands:
* add <prefix...> — append a prefix (multi-token OK: "git push origin")
* remove <prefix|N> — drop by exact prefix or 1-based project index
* clear confirm — wipe every project entry (typed literal "confirm")
*/
const permissions: SlashHandler = (args, _loop, ctx) => {
const sub = (args[0] ?? "").toLowerCase();
const root = ctx.codeRoot;
-17
View File
@@ -1,10 +1,3 @@
/**
* `/plans` — show this session's plan history. Both the live in-flight
* plan (if any) and the archive of completed `.done.json` files. Local
* to the current session by design — a plan lives with its project,
* and resuming one just means cd'ing back to that project directory.
*/
import { basename } from "node:path";
import { listPlanArchives, loadPlanState, relativeTime } from "../../../../code/plan-store.js";
import type { SlashHandler } from "../dispatch.js";
@@ -59,16 +52,6 @@ const plans: SlashHandler = (_args, loop) => {
return { info: lines.join("\n") };
};
/**
* `/replay [N]` — Time Travel. Loads archive #N (1-based, newest
* first; defaults to 1) and asks the TUI to render it as a read-only
* snapshot. Pure display — no execution, no plan state changes.
*
* The structured payload (steps + completedStepIds + body + summary)
* goes back through SlashResult.replayPlan so EventLog can apply the
* same step-list rendering used elsewhere, complete with risk gutter
* and ✓ status.
*/
const replay: SlashHandler = (args, loop) => {
const sessionName = loop.sessionName;
if (!sessionName) {
Loaded 100 of 250 files, more files were not shown because too many files have changed in this diff. Show more