Compare commits

...
112 Commits
Author SHA1 Message Date
YHH f422a94dfa chore(release): 0.30.5 (#395)
Three contributor-led follow-ups: storm guard exempts safe inspector
reads (#388 by @ctharvey), wait_for_job replaces polling loops with
one blocking call (#390 by @ctharvey), and /skill new finally
provides the missing scaffold for user skills (#394).
2026-05-08 00:51:13 +08:00
YHH ee5961fe70 feat(skills): /skill new scaffolds a stub + README walkthrough (#394)
* feat(skills): /skill new scaffolds a stub + README walkthrough (#366)

User feedback: wanted to install a frontend-writing skill, "no
discoverable entry point". The /skill list empty state told users
WHERE skills live but not HOW to author one — and there's no remote
registry to install from.

Adds the missing creation step:

- /skill new <name>          → writes <project>/.reasonix/skills/<name>.md
- /skill new <name> --global → writes ~/.reasonix/skills/<name>.md

The stub carries the minimal frontmatter (name + description) plus
a comment block listing the optional knobs (runAs, allowed-tools,
model). Refuses to overwrite existing files; rejects invalid names
via the existing isValidSkillName regex.

Empty /skill list now surfaces the new scaffold + an explicit "no
remote registry yet" line so users don't keep hunting for a
marketplace that doesn't exist. Catalog + README in EN + zh-CN
gain the "author your first skill" path. The /skill list footer
mentions /skill new alongside show / run.

* fix(skills): atomic create with wx flag — close TOCTOU race CodeQL flagged

CodeQL flagged the existsSync→writeFileSync sequence as a potential
file-system race. Switch to writeFileSync with `flag: "wx"` so the
existence check IS the atomic write — if a parallel process landed
the file between our check and write, EEXIST surfaces and we report
the conflict instead of silently overwriting.

Keep the folder-form pre-check for a cleaner error message when the
collision is on the dir-style skill (`<name>/SKILL.md`).
2026-05-08 00:31:22 +08:00
ctharveyandCharles H 15b4060e68 feat(jobs): add wait_for_job tool for background jobs (#390)
Co-authored-by: Charles H <[email protected]>
2026-05-08 00:10:09 +08:00
ctharveyandCharles H 9ec5b99e07 feat(storm): add stormExempt flag to exempt obvious reads from the loop guard (#388)
Co-authored-by: Charles H <[email protected]>
2026-05-08 00:09:21 +08:00
YHH e93c4ffde3 chore(release): 0.30.4 (#392)
Sweep of the 0.30.2 / 0.30.3 launch-day bug + onboarding queue:
resume now restores cache+context+cost (#364), model pill follows
/model + /preset switches (#372), bare /model opens an interactive
picker (#371), three more Shift+Tab encodings for PowerShell /
modifyOtherKeys / Kitty (#373), defensive stdin drain on exit kills
the fish/bash escape-leak (#365), and --dir / pinned workspace get
surfaced in the welcome banner, /status, sandbox errors, and the
README (#370).
2026-05-08 00:04:33 +08:00
YHH 0e4cba3670 fix(tty): drain pending feature-detection replies on exit (#365) (#391)
Reporter saw `^[]11;rgb:...^[\^[[33;1R^[[?62;1;4c` printed by fish /
bash right after exiting reasonix. Those bytes are RESPONSES — OSC 11
bg-color, CPR cursor-position, DA1 device-attributes — sent by the
terminal in reply to queries the runtime / a dep emitted during
session startup. The dist bundle has none of those query bytes
itself, so the source is bun's tty feature-detection path or a
transitive dep doing color-scheme detection.

Whoever sent them, the responses sat in stdin's queue until reasonix
exited. The parent shell then read them and rendered the bytes as
input.

Add `drainTtyResponses(50ms)` and call it in chat.tsx's exit finally,
after `runtime.closeAll()`. Best-effort: sets raw mode, reads-and-
discards anything still queued for 50ms, restores cooked. No-op when
stdin isn't a TTY or raw mode isn't available.

0.30.3's alt-screen default is the upstream mitigation (DECSET 1049
flushes the input queue on most terminals); this is the program-side
mitigation that's independent of which terminal the user is in.
2026-05-07 23:53:35 +08:00
YHH d0b251d43a feat(ui): surface --dir / pinned workspace for first-time users (#370) (#389)
User feedback (multiple data points): beginners hit the default
cwd-scoped behavior and conclude Reasonix can't read folders other
than where they launched it. The capability already exists via
`reasonix code --dir <path>`, but nothing in the UI tells you so
until you read --help.

Three onboarding surfaces now make it discoverable:

- WelcomeBanner shows a "▸ workspace · /path  (relaunch with --dir
  <path> to switch)" line in code mode. Visible only on the empty
  state, so it doesn't survive past the first turn.

- `/status` includes a workspace line:
    workspace /path · pinned at launch (relaunch with --dir <path>
    to switch)

- The filesystem sandbox-escape error now points the user at --dir
  instead of just dropping a raw "path escapes sandbox root":
    path escapes sandbox root (X): Y — workspace is pinned at
    launch; quit and relaunch with `reasonix code --dir <path>` to
    work in a different folder

Plus a Getting Started callout in both READMEs explaining --dir and
why mid-session switching isn't a thing (message log + memory paths
get tangled with stale roots, so the design pins at launch).

No new slash command, no /cwd. The agent's system prompt already
says mid-session switching was removed by design.
2026-05-07 23:37:39 +08:00
YHH daebf3d571 feat(ui): /model with no arg opens an interactive picker (#371) (#387)
`/model <id>` required typing the model id by hand and `/models` was
a separate read-only listing. New users had no obvious way to switch
without prior knowledge of the catalog.

Bare `/model` now opens a modal picker that mirrors SessionPicker's
shape: arrow-key list, ⏎ confirm, [r] refresh the API catalog, esc
cancel, current model marked. The list seeds from the live DeepSeek
catalog (`useSessionInfo` already fetches it on mount); when the
catalog hasn't loaded yet the picker falls back to the four known
DeepSeek ids so it's never empty on first open. The current model
is always included even when the API didn't return it.

Confirming a row routes through `loop.configure({ model })` AND the
`session.model.change` event added in #372 — so the badge on the
NEXT card pill reflects the new selection.

`/model <id>` typed entry continues to work for power users.
2026-05-07 22:54:33 +08:00
YHH 28119cad01 fix(input): recognize PowerShell / modifyOtherKeys / Kitty Shift+Tab variants (#373) (#386)
Recognized only the bare xterm `\x1b[Z` back-tab. PowerShell 7.x on
some Windows hosts emits the modifier-encoded `\x1b[1;2Z`; modern
Windows Terminal in modifyOtherKeys mode (which we enable on
startup) emits `\x1b[27;2;9~`; the Kitty keyboard envelope is
`\x1b[9;2u`. None of these matched, so the edit-mode cycle was
silently dropped on PowerShell.

Add all three variants to `stdin-reader.ts` CSI_TAIL_MAP and to the
Ink-fallback `key-normalize.ts` recovery table. `/mode` slash command
remains as a typed fallback for any future terminal that emits a
form we haven't seen yet.
2026-05-07 07:10:06 -07:00
YHH 3c24c0f1e1 fix(ui): /model + /preset update active model so the next card pill is fresh (#372) (#385)
`state.session.model` was set once in `initialState()` and never
mutated. `/model <id>` and `/preset {auto,flash,pro}` only routed
through `loop.configure({ model })`, never into the agent store —
so the next `streaming.start` / `reasoning.start` / "thinking · X"
card snapshotted the launch-time model id, even when the model that
actually answered the turn was different.

Add a typed `session.model.change` event the model handlers dispatch
through `ctx.dispatch`. Reducer mutates `state.session.model` (with
referential identity preserved when the id is unchanged) and the
existing snapshot logic in `makeReasoningCard` / `makeStreamingCard`
picks up the new value automatically. Cards already opened keep
their captured model — that snapshot is intentional so mid-turn
escalation doesn't relabel completed reasoning.
2026-05-07 07:04:04 -07:00
YHH 7edcb07465 fix(stats): persist cache totals + lastPromptTokens across resume (#364) (#384)
`SessionMeta` only carried `totalCostUsd` and `turnCount`, so on every
resume `/status` showed:

- 0 context — `lastPromptTokens` came from `turns[0]?.usage`, and
  `turns` is empty before the first live turn fires
- 0% cache hit — `aggregateCacheHitRatio` summed `turns[]` only

The next API call would still read the cached prefix and answer
correctly (turn 1 in the user's log shows 366,976 / 367,085 cache
hits), but the panel reported "no context" until that call landed.

Persist the missing fields after each turn (`patchSessionMeta`) and
seed them on resume (`stats.seedCarryover`). `aggregateCacheHitRatio`
and `summary().lastPromptTokens` now fall through to the carryover
when no live turn has run yet.
2026-05-07 06:46:18 -07:00
YHH 04b12e9f2d chore(release): 0.30.3 (#382)
Ink 7 + React 19 chat scroll rewrite (#380), configurable web_search
backend with SearXNG (#338), MCP filesystem sandbox preflight + wizard
mkdir confirm (#362, PR #379), README URL fix (#375), bug template
update (#378).
2026-05-07 06:29:05 -07:00
YHH b07b86ee2f feat(ui): row-precision virtual scroll on Ink 7 + React 19 (#380)
* feat(ui): row-precision virtual scroll on Ink 7 + React 19

Bump ink 5.2→7.0.2 + react 18.3→19.2; drop react-reconciler/yoga-layout.
Retire src/renderer/ (cell-diff + ink-compat shim) — Ink 7 ships native
equivalents for every motivation: alternateScreen, useAnimation,
useWindowSize, useBoxMetrics, synchronized output, incrementalRendering.

Default to alt-screen so the resize-ghost / scroll-yank class of bugs
disappears. `--no-alt-screen` opts back into scrollback for users who
need chat output preserved in shell history on exit.

Row-precision virtual scroll with reading mode: scrolling away from
bottom hides PromptInput and replaces it with a "📖 reading history —
End / PgDn to return" indicator. PgUp/PgDn/End owned by App; ↑/↓ on
an empty buffer hand off to chat scroll via PromptInput; App takes ↑/↓
directly when busy or in reading mode (PromptInput can't process them).
Wheel events translate to ↑/↓ in raw mode, so the same paths cover wheel.
Ctrl+P/N keeps the prompt-history binding (wheel-immune).

Drop <Static> — incompatible with alt-screen (no scrollback to shelter
committed cards across resize-reflow). React.memo on CardRenderer plus
the reducer's reference-stable card array skips reconciler cost on
unchanged cards. CardStream renders all cards inside an overflow:hidden
Box; inner Box's marginTop=-scrollRows shifts content; useBoxMetrics
reports inner/outer heights so App can clamp scroll bounds.

CardStream.isSettled covers task / plan / subagent kinds. PromptInput's
useReserveRows quantizes to 4-row buckets so per-keystroke layout doesn't
churn. TickerProvider migrated to Ink 7's useAnimation. Modal-open
condition collapsed from 14 OR'd checks into one reused boolean.

Migrate inline tests (markdown, plan-confirm) off the cell-diff renderer
to ink-testing-library. Remove dead alt-screen.ts; strip stale comments
referencing removed scrollback-mode workarounds.

* test(ui): provide fake stdin for Ink 7 raw-mode check in CI

Ink 7 calls setRawMode on stdin during render(); CI's process.stdin
isn't a TTY so it throws "Raw mode is not supported". Pass a minimal
EventEmitter-based fake stdin (setRawMode no-op, isTTY=true) alongside
the existing fake stdout. Affects four tests that import render directly
from ink for in-process render-and-assert: ui-session-picker-currency,
ui-stats-panel-currency, ui-usage-card-balance, ui-status-row-balance.

* test(ui): extract makeFakeStdin/Stdout to shared tests/helpers/ink-stdio
2026-05-07 06:14:37 -07:00
dacec354 7ba3d086ff chore(issue-template): add shell/terminal fields, update model examples (#378) 2026-05-07 05:33:20 -07:00
YHH 1a7d74f3f0 fix(mcp): preflight filesystem sandbox dir + offer mkdir in wizard (#362) (#379)
The official @modelcontextprotocol/server-filesystem refuses to start
when its sandbox directory is missing and prints a raw Node stack
trace, leaving the user without an actionable next step.

- preflightStdioSpec validates every positional path arg before
  spawn and throws a one-line error: "create it with: mkdir -p '<path>'"
- The first-run / reconfigure wizard now stat()s the directory the
  user typed for filesystem MCP and offers Y/Enter to mkdir -p,
  N/Esc to enter a different path.
2026-05-07 05:31:09 -07:00
dacec354 0f7dcd026a fix(readme): correct website URLs — /reasonix/ → /DeepSeek-Reasonix/ (#375) 2026-05-07 04:43:08 -07:00
dacec354 12998d246d feat(web): configurable web_search backend with SearXNG support (#338)
Adds SearXNG as an alternative web_search engine, switchable via /search-engine slash command or ~/.reasonix/config.json. Mojeek stays the default — zero risk for existing users.
2026-05-07 02:02:06 -07:00
YHH 43d437fd38 chore(release): 0.30.2 (#361) 2026-05-06 23:06:55 -07:00
YHH 62813e3d6d fix(dashboard): cost displays follow wallet currency, not hardcoded USD (#360)
CLI shows session cost in the wallet's currency (¥ for CNY wallets,
$ for USD), but the dashboard always used `fmtUsd()` which prints
the raw stored USD with a `$`. CNY users saw `$0.5190` in the
dashboard for the same session that read `¥0.024` in the CLI — both
the symbol AND the magnitude diverged because no conversion happened.

- New `fmtCost(usd, currency, fractionDigits?)` helper in
  `dashboard/src/lib/format.ts`. Mirrors the CLI's `formatCost()` —
  CNY converts via `USD_TO_CNY = 7.2`, USD passes through, undefined
  defaults to CNY.
- `overview.ts` current-session cost + cost-trend day average now
  thread `c.balance?.currency` into `fmtCost()`.
- `chat.ts` SideRail cost / budget rows and ChatStatusBar
  turn / session cost rows pull currency from `stats.balance[0]`.
- Existing `fmtUsd()` kept as-is for places where USD is intentional
  (Claude-equivalent comparisons in usage.ts) — those stay USD because
  Claude's API is USD-priced regardless of the user's wallet.
2026-05-06 23:00:56 -07:00
YHH a29a0ac157 feat(ui): ctrl-o expands the live streaming card to full tail (#335, #337) (#359)
Pain point @dacec354 raised twice: while the model writes a long plan
or todo list, the streaming card only shows the last 4 lines, so the
content scrolls past before you can read it. And once a long reply
settles, you may want to fold it back down — but `<Static>` already
flushed the bytes to scrollback so that half can't be unwound.

This collapses both requests into one keystroke: `ctrl-o` toggles
"expanded" mode on the live streaming card. Expanded shows the last
60 visual lines (capped so the card can't swallow the whole viewport)
plus a `⋯ N earlier lines above` hint when content overflows.
Collapses back to the 4-line preview. Auto-resets to collapsed at the
end of every turn so each new reply starts compact.

The same `(LIVE)` constraint covers #337's fold-toggle ask: only
not-yet-committed cards are addressable. Settled cards live in Ink's
`<Static>` which writes terminal scrollback once, no take-backs.

The `expanded ⌃o` / `preview ⌃o` pill in the card header advertises
the keybind so users discover it without reading docs.
2026-05-06 22:48:35 -07:00
YHH ccdbfb3a28 fix(ui): reasoning spinner survived reasoning.end when a later card existed (#358)
`splitCardStream` only treated the LAST card as live; everything before
it was committed to Ink's `<Static>`. When the model streamed reasoning
THEN content (or kicked off a tool card), the reasoning card was
no longer last — so it got frozen into `<Static>` while still
`streaming: true`. `reasoning.end` later set `streaming: false` on
the cards array, but `<Static>` doesn't re-render frozen items, so the
"reasoning…" header kept its spinner indefinitely.

Fix: live-vs-committed split now scans for the FIRST unsettled card
and keeps everything from there onward in the live tree. Cards only
move into `<Static>` once they're settled AND every earlier card is
too — preserving the in-order append contract `<Static>` requires.

`suppressLive` semantic preserved: still hides the trailing live card
when the modal owns the screen.

Two new regression tests cover the reasoning + streaming case (must
stay live) and the all-settled case (must commit in order).
2026-05-06 22:33:06 -07:00
YHH 1805b0c647 fix(ui): SessionPicker honors wallet currency instead of hardcoded ¥ (#312) (#357)
Same bug shape as the StatusRow / UsageCard / StatsPanel set that #272
already fixed — `SessionPicker` was still doing
`¥${totalCostUsd * USD_TO_CNY}` so USD-wallet users saw ¥-formatted
costs in the session list.

- `SessionMeta` gains `balanceCurrency?: string`. App.tsx writes the
  live wallet currency alongside `totalCostUsd` on each turn save, so
  every persisted session knows what currency its cost is denominated
  in.
- `SessionPicker` accepts a `walletCurrency` prop and falls back to
  each row's `meta.balanceCurrency`. Prop wins (live value > stored).
  In-app picker (`/sessions`) gets the live ref from App; pre-mount
  picker in `chat.tsx` doesn't have a balance fetched yet, so it
  relies on the stored per-session value.
- Cost rendering routes through the shared `formatCost()` helper that
  the rest of the cost UI already uses.
- Regression test asserts USD wallet → `$0.05`, CNY wallet → `¥0.36`,
  no-prop + stored-USD → `$0.05`, neither → unchanged `¥0.36`.
2026-05-06 22:22:11 -07:00
YHH 4032930fed feat(ui): live tokens/s on streaming reply + space pauses 5s undo (#334, #337) (#356)
- StreamingCard renders a `42 t/s` pill in the live header and a
  `1.2k tok · 42 t/s` summary on the settled card. Computed via the
  bundled DeepSeek tokenizer; gated below 4 tokens / 500 ms so the
  pill never shows obviously-bogus rates while the first chunk lands.
  Re-renders piggyback on the slow tick so the rate keeps updating
  even when chunks stall briefly.
- The auto-mode undo banner now accepts a `space` keystroke to pause
  the 5-second countdown indefinitely. While paused the bar freezes
  at the captured fraction, the badge swaps to "Ns · paused", and
  pressing space again resumes from where it stopped. The hint row
  on edit-mode entry mentions both `u` and `space`.

The `u` and `space` keybinds share the same modal-and-prompt-empty
gating, so neither steals input while the user is typing.
2026-05-06 22:08:19 -07:00
YHH b03e11bf41 chore(release): 0.30.1 (#355) 2026-05-06 21:15:07 -07:00
ctharveyandCharles H 0b91250c44 fix(ui): suppress live card redraw while picker modal is open (#353)
Co-authored-by: Charles H <[email protected]>
2026-05-06 21:09:55 -07:00
YHH 5bcc3b6389 fix(renderer): drop cell-diff aliasing, run prod on real Ink (#346) (#354)
Aliasing `from "ink"` → ink-compat in the CLI bundle made every
TUI bug invisible to `npx tsx` repros and forced cell-diff regressions
onto users only. Issue #346 (ShellConfirm ghost rendering) was a pure
cell-diff bug; the cleanest fix is to remove the alias and let
production take real Ink the same way source mode does.

- tsup: drop the `ink` alias and `noExternal` for ink/ink-text-input;
  bundle keeps `from "ink"` external
- package.json: ink + ink-text-input move to runtime dependencies
- markdown-view: switch the only `inkCompat.*` namespace user back to
  `import { Box, Text } from "ink"`
- bundle-smoke: invert the alias assertion to expect ink stays external

useCursor() in PromptInput keeps its cell-diff import; without a
CursorContext provider it no-ops, so it's harmless under real Ink.
2026-05-06 21:01:59 -07:00
YHH 0f7f7c24c2 docs(benchmarks): real-world cache-hit case study (#351)
Anonymized DeepSeek dashboard from a real Reasonix user
(2026-05-01, used with permission): 435M input tokens, 99.82%
cache hit, ~$12/day on v4-flash vs ~$61 the same workload would
cost without the cache.

Lives at benchmarks/real-world-cache/ alongside an explanation of
the four mechanisms (ImmutablePrefix + AppendOnlyLog +
VolatileScratch + auto-compact) that produce the hit rate. README
gets a NOTE callout pointing at it — answers the recurring "isn't
this just DeepSeek's prefix cache?" pushback with concrete numbers
instead of a re-derived napkin.
2026-05-06 18:54:57 -07:00
YHH 6379bc0628 chore(release): 0.30.0 (#349) 2026-05-06 18:06:28 -07:00
YHH 82c5627123 fix(renderer): use CHA absolute for column moves in cell-diff (#346) (#348)
Switch the X-axis branch of `moveTo()` from CUF (relative cursor right,
`\x1b[NC`) to CHA (absolute column, `\x1b[N+1G`). Y-axis stays on
CUU/CUD since we don't track absolute terminal rows.

Relative column moves accumulate drift across frames: if any earlier
write miscounted cell width — wide-char disagreement (`▸` U+25B8 in
"narrow" fonts that render 2-cell), `▎` ambiguous-width on terminals
that font-detect East Asian width, OSC8 hyperlinks parsed as visible
chars, etc. — the cursor's actual column desyncs from what the
renderer thinks. The next CUF lands at the wrong column, ghost-rows
get written into hint lines, and the modal "shifts" as users navigate
(symptom in #346 issue screenshots).

Anthropic's Claude Code TUI hit the same class of bug
(anthropics/claude-code#14208) and the fix was the same: prefer CHA
over CUF/CUB so column targeting is immune to per-cell width
miscounts. Fix is invisible on terminals where our width math was
already correct; on terminals where it wasn't, no more accumulating
drift.
2026-05-06 18:02:08 -07:00
YHH e991644416 feat(slash): first-class command aliases (#332) (#347)
Add `aliases?: readonly string[]` to SlashCommandSpec so /quit + /q
resolve to /exit, /? to /help, /reset to /new, /lang to /language —
all from a single declaration on the spec instead of ad-hoc handler
mirrors scattered across handlers/basic.ts + handlers/language.ts.

dispatch, suggestSlashCommands and detectSlashArgContext all route
through one resolveSlashAlias() built from SLASH_COMMANDS at module
init. Suggestion rows surface aliases dimly (` · /quit /q`) so they
stay discoverable without polluting the autocomplete list with
duplicates. Dashboard /api/slash response now exposes the field too.
2026-05-06 18:01:54 -07:00
YHH 39dbe19bcd chore(release): 0.29.1 (#345) 2026-05-06 17:07:23 -07:00
YHH c1e8a933d3 fix(markdown): row-group the table fallback layout (#340) (#344)
When a markdown table is too wide for the viewport, FallbackTable
flattens it into key/value lines. The previous implementation
iterated headers first, then rows-within-each-header — so a 3×N
table came out as N "Component:" lines, then N "What:" lines,
then N "Manual TCs:" lines. The user couldn't tell which value
belonged to which row.

Reproduction (issue #340): a planning table for 9 components
rendered as 9 grouped Component lines, 9 grouped What lines,
9 grouped Manual TCs lines — visually a list, not a table.

Swap loop order: iterate rows first, then write all columns
inside each row block, separated by a blank row between rows.
Output now reads top-to-bottom as one logical row at a time.
2026-05-06 16:55:20 -07:00
YHH b401913910 fix(plan): show plan body in PlanConfirm modal (#336) (#343)
When the model called submit_plan with a markdown body but no
structured steps, the Approve plan modal showed only the
warning banner + the choice list — the actual plan content
was hidden behind the collapsed tool-call card in scrollback.
Users had no way to see what they were approving without
hunting up through the transcript.

- Render the plan body via MarkdownView when no steps are
  supplied. Steps still take precedence when present (they
  are the canonical structured view).
- Cap inline preview at 24 lines; surface "… N more lines
  above in scrollback" when the body exceeds that. Reserve
  budget grows with whichever body section is being shown.

Tests cover the three branches: body-only, steps-present,
and truncated-body-with-overflow-hint.
2026-05-06 16:44:59 -07:00
YHH 5662b57a4b fix(stats): carry session cost / turn count across resume (#333) (#342)
The TUI's session-cost figure ($X session) reset to $0 on every
resume because SessionStats was rebuilt empty even when the disk
meta still held the cumulative totalCostUsd from prior runs.

Reproduction (issue #333): hello → exit → resume → expense
accumulator displays 0 instead of the prior session total.

The persistence path was already correct — App.tsx writes
`{ totalCostUsd, turnCount }` into the session meta after every
turn. Only the read-back was missing.

- SessionStats gains a `seedCarryover()` once-at-construction hook
  that adds prior totals to the in-memory totalCost / summary.turns
  without polluting the live `turns[]` array (which intentionally
  holds only this run's per-turn records).
- CacheFirstLoop now calls `loadSessionMeta()` on resume and seeds
  the carryover when prior messages exist. Fresh sessions are
  unaffected — undefined meta fields short-circuit the seed.

Tests cover the carryover math (telemetry.test.ts) and the
end-to-end loop wiring (session.test.ts).
2026-05-06 16:38:13 -07:00
YHH e40e1911cc fix: issue #330 — markdown osc8 garbage + cell-diff shrink-row leak (#341)
* fix(markdown): stop linkifying "e.g" / "i.e" / drop OSC 8 garbage (#330)

Two coupled bugs in the markdown file-ref linkifier:

1. FILE_REF_RE matched English abbreviations because the extension
   class was `{1,6}` — `e.g`, `i.e`, `a.m` all qualified.
2. `osc8()` baked OSC 8 escape bytes (\x1b]8;;...\x07) into Text
   content. The cell-diff renderer's wrapLine strips zero-width chars
   (ESC, BEL) but keeps the printable body, so terminals received
   plain `]8;;file://e.ge.g]8;;` characters — visible garbage on
   any terminal, with no working hyperlink anywhere.

The fix:

- Tighten FILE_REF_RE post-match: require either path-shape (slash),
  line-number suffix, or extension >= 2 chars. `src/foo.ts`,
  `package.json`, `util.c:42` still match; bare `util.c` no longer
  does (acceptable — rare in prose).
- Strip the OSC 8 escape from `osc8()` — keep color + underline
  styling so file refs stand out, but do not emit hyperlink bytes.
  The renderer would need per-span hyperlink propagation through
  nested HostText flattening to support real OSC 8; that's a
  separate refactor. Until then, no link beats broken link.
- Plumb a `hyperlink` prop on ink-compat Text so the future
  per-span fix has a place to land.

Regression test mounts Markdown through the reconciler and asserts
the byte stream never contains `]8;;` for `e.g` / `i.e` samples.

* fix(renderer): trail-clear shrunk rows in cell-diff (#330)

Defensive against terminal-state desync. The cell-diff renderer
skips cells where prev and next are byte-equal — including the
trailing EMPTY cells of a row that shrank. If the terminal's
actual state diverged from prev (e.g. a stray ESC body slipped
through earlier rendering), those skipped trailing cells retain
stale chars from prior frames.

This was the second half of issue #330: with the markdown OSC 8
garbage previously sourcing the desync, the option-list modal
rendered "allow always" + "mand, ask again next time" leftover
on rows that originally held a longer hint.

- New `clearToEOL` patch type → serializes to `\x1b[K`
- After diffEach, sweep rows: if next's row ends earlier than
  prev's content extent, emit clearToEOL past the last visible
  cell. Bounded — at most one clearToEOL per row that shrank.
- Two regression tests cover the modal-shrink case and verify
  no clearToEOL is emitted for same-width swaps.
2026-05-06 16:32:00 -07:00
YHH fdea3bb837 fix(dashboard): wire up filter chips + mark static indicators (#331)
The .chip-f class has cursor:pointer + a hover style, so every chip
looked clickable. In skills, plans, and hooks the chips were laid out
as filter buttons (one hardcoded "active") but had no onClick — clicks
did nothing. Other panels reused chip-f for non-interactive count
indicators, which had the same misleading hover affordance.

Real filters wired:

- skills: All / Project / Global / Builtin filters the list by scope
- plans: All / Active / Done filters by completion status
- hooks: Resolved + each event filters the matrix to rows whose hooks
  fire on the selected event (matrix columns still show all events)

Static indicators marked with the new `chip-f.static` modifier (cursor
default, no hover lift). Sessions count, permissions Project/Builtin
counts, usage records/log size, tools total + plan-mode flag, chat
mode label, semantic index status, and semantic config-tag chips all
no longer pretend to be clickable.

CSS: new `.chip-f.static` + `.chip-f.static:hover` rules disable the
interactive affordances without duplicating the chip styling.
2026-05-06 08:58:58 -07:00
YHH 3efa4cc374 chore(release): 0.29.0 (#329) 2026-05-06 08:35:38 -07:00
YHH 26ca84dd8f docs(architecture): parallel tool dispatch + env knobs (#325) (#328)
Document the chunked-parallel dispatcher and the two knobs that govern
it (REASONIX_PARALLEL_MAX, REASONIX_TOOL_DISPATCH=serial), plus the
list of built-in tools that opt in via parallelSafe.

Closes the docs portion of #325. Observability-event work (chunk-start
in events.jsonl) is deferred — the existing test suite already validates
the timing, ordering, and barrier guarantees, and the kernel event log
is a heavier surface that can wait until a real ops need surfaces.
2026-05-06 08:18:59 -07:00
YHH e91d136dbc feat(loop): chunked parallel tool dispatch + multi-subagent UI (#325) (#327)
Replace the serial `for...of + await` tool dispatch with chunked
parallel scheduling: consecutive `parallelSafe` calls race together;
unsafe calls form serial barriers. Tool yields and history append
preserve declared order regardless of which call settles first.

- Loop dispatch chunks consecutive parallelSafe calls; unsafe call
  ends the current chunk and runs alone
- runOneToolCall extracts per-call lifecycle (PreToolUse + dispatch +
  PostToolUse) so chunks can fan out via Promise.allSettled while the
  loop body keeps yielding events in declared order
- New env knobs: REASONIX_PARALLEL_MAX (cap, default 3, hard max 16)
  and REASONIX_TOOL_DISPATCH=serial (escape hatch)
- SubagentEvent gains a stable runId per spawn; useSubagent keeps an
  array of in-flight activities; SubagentLiveStack renders 1 → rich
  card, 2..max → compact rows, >max → "+N more" fold

Tests cover the four guarantees: parallel timing, serial barrier on
mixed safe/unsafe, declared-order yields under racey completion, and
both env-knob overrides.
2026-05-06 08:15:24 -07:00
YHH 12a3dab7e9 feat(tools): parallelSafe annotation on ToolDefinition (#325) (#326)
Plumbing for chunked parallel dispatch. No behavior change.

- ToolDefinition.parallelSafe?: boolean (default false; opt-in only)
- ToolRegistry.isParallelSafe(name): unknown / unannotated → false
- Built-in opt-ins: read-only filesystem (read_file, list_directory,
  directory_tree, search_files, search_content, get_file_info), web
  (web_search, web_fetch), memory recall, semantic_search, isolated
  child loops (run_skill, spawn_subagent), in-memory job queries
  (job_output, list_jobs)
- Mutating / side-effecting tools stay default (write_file, edit_file,
  shell, plan state, memory writes, ask_choice)
- MCP-bridged tools default false; safe surface only ships when an MCP
  server explicitly declares its tools parallel-safe
2026-05-06 08:07:04 -07:00
YHH deefafed10 chore(release): 0.28.0 (#323) 2026-05-06 03:16:17 -07:00
YHH 882a7ad2d9 feat(subagent): built-in subagent types (explore, verify) via the type arg (#322)
Two task shapes repeat often enough to warrant first-class support
without needing a skill:

- explore — wide-net read-only investigation (20-iter budget)
- verify — narrow yes/no check with evidence (8-iter budget)

Add an optional `type` field to the spawn_subagent schema. When set,
the type supplies the system prompt and default iter budget. Caller-
supplied `system` / `max_iters` override the type's defaults.

Prompts live in src/tools/subagent-types.ts so subagent.ts stays under
the 500-line target.

Closes #319
2026-05-06 01:59:01 -07:00
YHH b248a87455 feat(subagent): expose max_iters on spawn_subagent tool schema (#321)
Subagents have always had a configurable maxToolIters internally, but
the public spawn_subagent schema exposed only task/system/model. Every
spawn paid the 16-iter default, even narrow verify-style tasks that
want fewer or broad explore tasks that want more.

Add an optional `max_iters` integer field to the schema, clamp at the
boundary to 1-32 so a stray prompt can't request thousands, and pipe
through to spawnSubagent. Non-numeric / missing values fall back to
the registration-time default (still 16).

Closes #318
2026-05-06 01:55:12 -07:00
YHH ff858ed744 feat(subagent): honor skill allowed-tools frontmatter when forking child registry (#320)
Skill frontmatter `allowed-tools` was parsed but ignored — every subagent
inherited the parent's full registry minus spawn_subagent / submit_plan,
which gave skill authors no way to scope a child to read-only or
task-specific tools.

Plumb the parsed list through SpawnSubagentOptions; when present, fork
via new forkRegistryWithAllowList helper instead of forkRegistryExcluding.
NEVER_INHERITED still wins so spawn_subagent stays out even if the
skill's allow-list names it. Validate at spawn time — if the allow-list
names a tool the parent doesn't have, return a structured error result
naming the missing tool, no API call burned.

Direct (non-skill) spawn_subagent calls still see full inheritance —
the tool schema is unchanged.

Closes #317
2026-05-06 01:50:08 -07:00
YHH a5adca41ac chore(release): 0.27.3 (#315) 2026-05-06 01:12:27 -07:00
YHH aed4d431cb chore(ui): remove orphan ChromeBar.tsx (#314)
No live render path — `App.tsx` mounts `StatsPanel`, which has its own
`ChromeRow` that diverged from `ChromeBar` and is the bar users actually
see. Only references are a CHANGELOG history line and one test
description string ("'w \$0.91' style").

The two formatter helpers `ChromeBar` once owned (`formatBalance` /
`formatBalanceLabel`) already live in `theme/tokens.ts` after #272 / #313.
2026-05-06 01:06:20 -07:00
YHH 0acfcefb89 fix(ui): top bar cost + subagent end-cost follow wallet currency (#313)
After #272 fixed StatusRow / UsageCard / ChromeBar BalancePill, three
display sites still hardcoded `$` and ignored the wallet currency:

- StatsPanel.ChromeRow (the live top bar) — cost label `[$0.0058]`
- StatsPanel.ChromeRow — balance label inline-formatted, bypassing the
  shared formatBalance helper from #272
- useSubagent end-event summary — ` · $0.0123` cost suffix

Now all three route through formatCost / formatBalance and follow the
live wallet symbol. Render tests added in ui-stats-panel-currency.test.tsx
covering USD / CNY / no-wallet variants.

useSubagent gets a `getWalletCurrency` thunk (not a snapshot value)
because subagent runs can outlive a balance refresh — the thunk reads
the latest currency at end-event time.

Out of scope: ChromeBar.tsx (orphan, no live render path), DiffApp.tsx
(dev tool comparing historical USD numbers), BudgetRow (USD by definition,
user sets `--budget` in USD). SessionPicker tracked separately in #312.
2026-05-06 00:58:47 -07:00
Wesley Vianaandesengine 9cb0bdbc5f Fix: usd currency on status bar (#272)
* fix: Currency for USD wrong afeter TUI redesign.

* red: tests for the currency bug

* Fix implementation

* fixup: collapse tokens helpers + fix UsageCard cost bug

Addresses the two review comments on this PR:

1. Undefined-currency fallback now defaults to CNY for all three helpers
   (formatBalance, formatCost, balanceColor) — matches pre-fix unconditional ¥.
2. Seven helpers (formatCNY, formatBalance, formatBalanceLabel,
   formatWalletDisplay, formatCost, balanceColorCny, balanceColorForBalance)
   collapsed to three: formatBalance, formatCost, balanceColor.

Also fixes a separate bug surfaced while collapsing: UsageCard turn cost
(header) and session cost (body) used formatCNY, which was unconditional ¥
regardless of wallet currency. They now use formatCost(…, balanceCurrency)
and follow the wallet symbol like StatusRow does.

Render tests added for UsageCard turn/session cost in USD wallet mode.

---------

Co-authored-by: esengine <[email protected]>
2026-05-06 00:44:35 -07:00
YHH 2ca403670d refactor(loop): extract message builders, failure tracker, forced-summary helper (#311)
loop.ts 1331 → 1219 (−112). Three sibling files under src/loop/:
- messages.ts: pure ChatMessage builders (assistant + synthetic)
- turn-failure-tracker.ts: per-turn count/types + threshold tipping
- force-summary.ts: forced-summary generator behind a small DI context

Drops two now-unused imports (errorLabelFor, reasonPrefixFor) from loop.ts.
2026-05-06 00:06:31 -07:00
YHH c6e5bf4b02 refactor(loop): move LoopEvent / BranchSummary types + hook helpers out (#309)
PR2 under #307. Three more pieces that didn't depend on `this`:

- new `src/loop/types.ts` — `EventRole`, `BranchSummary`, `BranchProgress`,
  `LoopEvent`. The public-API re-export from `loop.ts` is preserved
  (`export type { ... } from "./loop/types.js"`), so consumers importing
  from `reasonix` see no change.
- new `src/loop/branch.ts` — `summarizeBranch` lives next to the types
  it produces.
- new `src/loop/hook-events.ts` — `safeParseToolArgs` + `hookWarnings`.
  These format hook outcomes as `LoopEvent`s and were the only callers
  of `formatHookOutcomeMessage` / `HookOutcome` from `./hooks.js`, so
  those imports leave `loop.ts` too.

`loop.ts`: 1414 → 1332 lines. No public API change. `npm run verify`
green (2336 pass / 1 skip).
2026-05-05 21:07:20 -07:00
YHH 08c7f2be81 refactor(loop): extract escalation marker + summary-reason helpers (#308)
PR1 under #307. Six functions and three constants that don't touch
`this` had no business living inside the `CacheFirstLoop` class file.

- new `src/loop/escalation.ts` — `parseEscalationMarker`,
  `isEscalationRequest`, `looksLikePartialEscalationMarker` plus
  `NEEDS_PRO_MARKER_PREFIX` / `NEEDS_PRO_MARKER_RE` /
  `NEEDS_PRO_BUFFER_CHARS`. The streaming chunk consumer + post-call
  retry path call these as plain functions now.
- `src/loop/errors.ts` gains `reasonPrefixFor` + `errorLabelFor` next
  to `formatLoopError`. They share the same `"budget" | "aborted" |
  "context-guard" | "stuck"` reason union and were the only callers.

`loop.ts`: 1463 → 1414 lines. No public API change — these were all
private / file-local. `npm run verify` green (2336 pass / 1 skip).
2026-05-05 21:02:53 -07:00
YHH 8befb44e5e fix(web): rewrite htmlToText with a real HTML parser (#306)
The chain-of-regex approach was tripping CodeQL across three rules
(bad-tag-filter, incomplete-multi-character-sanitization,
polynomial-redos) on the same set of patterns:

- `<tag[\s\S]*?</tag>` misses `</tag >` (whitespace before `>`) and
  re-exposes `<tag` after one removal pass on `<scr<tag>ipt>`-shaped
  input.
- `<[^>]+>` doesn't handle attribute values containing `>` (rare but
  legal in unquoted contexts) and is the canonical "incomplete
  sanitization" footgun.

Replaces both with a `node-html-parser` walk:

- `htmlToText` parses the input, removes `script / style / noscript /
  nav / footer / aside / svg` blocks via `querySelectorAll`, then
  walks the surviving tree and emits text with `\n` breaks at the
  block-level tags we care about (`p`, `div`, `br`, `h1-6`, `li`,
  `tr`, `section`, `article`).
- `stripHtml` (used by `parseMojeekResults`) becomes `parseHtml(s).text`.
- `decodeHtmlEntities` stays — kept for the post-parser pass since
  parser-decoded text can still contain numeric entities in edge
  attribute contexts.
- 5 MB input cap retained.

`node-html-parser` 7.x: 25 KB gzip, zero deps, ~30k packages
depend on it, active maintenance. Lighter than `parse5` for our
use case (we don't need full HTML5 conformance — just the tree).

21 web-tools tests pass unchanged; 2336 total tests green.
2026-05-05 20:38:23 -07:00
zerone0x b65ed747c9 fix(events): emit tool audit trail events (#260) (#304) 2026-05-05 20:28:24 -07:00
zerone0x 86be00299e fix(mcp): make inspect errors actionable (#101) (#303) 2026-05-05 20:24:10 -07:00
YHH b634b5e171 fix(codeql): drain 3 real bugs flagged by CodeQL (#305)
- src/cli/ui/Wizard.tsx — quoteIfNeeded escaped `"` but not `\`. A
  trailing backslash on the input would consume the closing quote
  when a downstream parser un-escaped the result. Escape `\` first
  (CodeQL js/incomplete-sanitization).
- src/cli/ui/clipboard.ts — temp filename was `reasonix-clip-${Date.now()}.txt`,
  predictable + collides under sub-millisecond bursts. Switched to
  `randomUUID()` (CodeQL js/insecure-temporary-file).
- tests/slash.test.ts — `/kb.example.com/` matched too broadly (`.`
  matched any char, no anchors). Tightened to
  `/\bkb\.example\.com\b/` (CodeQL js/incomplete-hostname-regexp +
  js/regex/missing-regexp-anchor).

136 wizard + slash tests pass unchanged.
2026-05-05 20:13:59 -07:00
YHH 3e91082456 fix(edit-blocks): close exists→write and read→write races (CodeQL) (#301)
Drains the last 2 file-system-race warnings in code/edit-blocks.ts.
Replaces the existsSync precheck + separate read/write pair with a
single fd-scoped flow:

- Try `openSync(path, "r+")` first. ENOENT → file doesn't exist:
  bail with `file-missing` (when SEARCH is non-empty) or fall through
  to atomic create.
- Atomic create is `openSync(path, "wx")` — fails on EEXIST so a
  concurrent writer that filled the slot between our `r+` ENOENT and
  our create can't be silently clobbered.
- Modify path keeps one fd open through fstat → read → ftruncate →
  write. ftruncate sets the new length first (so a shorter result
  doesn't leave stale tail bytes), then we overwrite from offset 0.

The 22 edit-blocks tests pass unchanged.

1 file-system-race warning still open (`usage.ts:103` compaction);
needs temp-file + rename, separate PR.
2026-05-05 20:01:04 -07:00
YHH 638eaeeb46 fix(memory): close exists→write race in hash-memory append (CodeQL) (#300)
Drains the last 2 file-system-race warnings in cli/ui that were
exists→write rather than stat→read.

The original `appendBulletToFile` had two races:

1. `existsSync(path)` then `writeFileSync(path, header)` — between the
   check and the write a concurrent appender could create the file,
   and our writeFileSync would clobber it with a fresh header (losing
   their bullet).
2. `readFileSync(path)` then `appendFileSync(path, …)` — peeking the
   trailing byte to decide whether we need a leading `\n`, then a
   separate append. A concurrent writer that added their own newline
   in between would cause us to insert a redundant blank line.

Fix:

- Atomic create-or-fail via `openSync(path, "ax")`. EEXIST means
  another process won the race; we fall through to the append branch
  rather than clobbering.
- For the append branch, open with `a+` once and do the trailing-byte
  peek + write on the same fd. `O_APPEND` means each `writeSync`
  atomically lands at end-of-file regardless of concurrent appenders.

20 hash-memory tests pass unchanged.

3 file-system-race warnings still open: edit-blocks.ts (×2) and
usage.ts:103. They need different surgery (`r+` + ftruncate /
read-modify-write or temp-file + rename); separate PR.
2026-05-05 20:01:00 -07:00
YHH 1a7b88c72f fix(fs): close 4 more stat→read TOCTOU races (CodeQL js/file-system-race) (#299)
Same fix shape as #298 — open once, do the size check and the read
against the same fd. The read on filtered semantic indexes also gets
to enforce its size threshold against the actual bytes we're about
to load, not a stat result that could be stale by the time we look.

- src/index/semantic/chunker.ts:209  per-file read in the indexer —
  re-checks `maxFileBytes` against `fh.stat()` before reading
- src/server/api/semantic.ts:200    `/api/semantic/status` index
  summariser — was `statSync().size` then `readFileSync`
- src/cli/ui/slash/handlers/semantic.ts:78  `/semantic` slash status —
  was `fs.stat` then `fs.readFile`; estimate fallback for >10MB stays
  the same, just bound to the fd's stat
- src/telemetry/usage.ts:74        compactUsageLogIfLarge — folds the
  separate stat / read try-blocks into one fd-scoped sequence

5 file-system-race warnings remain — those are exists→write or
read→write patterns (`hash-memory.ts`, `edit-blocks.ts`,
`usage.ts:103`); separate PR with `openSync(path, "ax" | "r+")`.
2026-05-05 20:00:55 -07:00
YHH 6ee2428802 fix(fs): close 3 stat→read TOCTOU races (CodeQL js/file-system-race) (#298)
Same fix shape across three files: open once, use fstat + read against
the same fd. The fd binding pins the inode for the lifetime of the
operation so a concurrent rename / replace / unlink during the call
can't desync the size or mtime we just observed from the bytes we're
about to read.

- src/tools/filesystem.ts:127  read_file body — was `fs.stat` then
  `fs.readFile`; switches to async `fs.open` + `fh.stat` + `fh.readFile`
- src/server/assets.ts:36      mtime-keyed asset cache — was `statSync`
  then `readFileSync`; switches to `openSync` + `fstatSync` + chunked
  `readSync`
- src/server/api/skills.ts:72  per-skill listing — same shape; also
  drops the redundant `existsSync` precheck that was a separate race
  in the same chain

9 file-system-race warnings remain — those are exists→write or
read→write patterns that need a different fix (open with `ax` / `r+`
flags); separate PR.
2026-05-05 19:28:21 -07:00
YHH febecb3d6f refactor(app): extract codeApply / codeDiscard into useCodeMode hook (#290) (#296)
Phase-2 PR under #290 (start of the feature-cluster phase). The
/apply and /discard slash callbacks move into one hook (93 lines).
The hook owns the partition / snapshot / save / sync sequence and
returns thin string-builders that AppInner forwards to its log.

Drops `partitionEdits` (unused after extraction) and `savePendingEdits`
(only used by the extracted callbacks) from App.tsx's imports.

App.tsx: 3361 → 3304 lines.
2026-05-05 19:18:08 -07:00
YHH 795a1e2f35 refactor(app): extract /loop machinery into useLoopMode hook (#290) (#295)
Phase-1 PR under #290 — biggest single extraction so far. The /loop
slash command's entire lifecycle moves into one hook:

- the activeLoop state + the four refs (mirror, timer handle, firing
  flag, and the timer scheduler effect itself)
- startLoop / stopLoop / getLoopStatus
- the timer scheduler useEffect (35 lines)

External consumers no longer poke at refs directly. The hook exposes:

- startLoop / stopLoop / getLoopStatus (forwarded to slash handlers)
- isLoopActive() — replaces all `activeLoopRef.current` checks (Esc
  handlers, apply-slash-result)
- isLoopFiring() / clearFiringFlag() — replace the cross-component
  `loopFiringRef.current` reads in handleSubmit's cancel guard
- activeLoop — reactive state for the LoopStatusRow render

apply-slash-result.ts's context shape switches `activeLoopRef:
MutableRefObject<...>` to `isLoopActive: () => boolean`. Cleaner —
slash handlers don't need to know about the ref shape.

App.tsx: 3499 → 3400 lines.
2026-05-05 19:07:11 -07:00
YHH 77cd4f7f66 refactor(app): extract quitProcess into useQuit hook (#290) (#293)
Phase-1 PR under #290. The Ctrl+C / SIGINT exit handler now lives in
its own hook: it returns the `quitProcess` callback and registers /
deregisters the SIGINT listener on its own. AppInner just calls
`useQuit(transcriptRef)` and forwards the returned function to the
slash dispatcher and Ctrl+C interceptor.

The "why process.exit, not Ink exit" rationale moves with the code
into the hook's docstring — that's the only place future callers
need to read it.

App.tsx: 3499 → 3483 lines.
2026-05-05 19:01:13 -07:00
YHH 3ec46356f5 refactor(app): extract writeTranscript into useTranscriptWriter hook (#290) (#294)
Phase-1 PR under #290. The transcript writer becomes its own hook —
takes the transcript ref + the model/prefix metadata it needs to
stamp on each record, returns the LoopEvent writer that AppInner
forwards into stream subscribers and slash handlers.

Drops `recordFromLoopEvent` + `writeRecord` from App.tsx's import
block since the hook now owns those.

App.tsx: 3499 → 3493 lines.
2026-05-05 18:58:53 -07:00
YHH 825c6e9608 refactor(app): extract input-recall into useInputRecall hook (#290) (#292)
First Phase-1 PR under #290. Lifts the bash-style ↑/↓ history recall
out of AppInner: the two `useRef`s (`promptHistory`, `historyCursor`)
and the two `useCallback`s (`recallPrev`, `recallNext`) are now
co-located in `src/cli/ui/hooks/useInputRecall.ts`.

The hook returns four functions — `recallPrev` / `recallNext` for
PromptInput, plus `pushHistory` (called on every successful turn) and
`resetCursor` (called once on submit). Existing callers that wrote
`promptHistory.current.push(text)` switch to `pushHistory(text)`;
`historyCursor.current = -1` becomes `resetCursor()`.

`apply-slash-result.ts` had the only out-of-component reference to
the ref — its context shape now accepts `pushHistory: (s: string)
=> void` instead of the raw `MutableRefObject`. Cleaner contract.

App.tsx: 3499 → 3479 lines.
2026-05-05 18:58:47 -07:00
YHH affa03b235 fix: drain CodeQL warnings — polynomial redos + web.ts htmlToText (#291)
* fix(redos): close polynomial backtracking in 4 regexes

CodeQL js/polynomial-redos flagged four regexes whose backtracking
shape is O(n²) on adversarial input. None are reachable from a real
attacker today (the inputs are model output / our own URL constants),
but the patterns are easy to fix and the alerts were noise.

- at-mentions.ts:319 — `/\.+$/` on path-like tokens. Loop-slice instead.
- client.ts:95 — `/\/+$/` on baseUrl. Loop-slice instead.
- scavenge.ts:67/75/86 — three DSML matchers (`<X>[\s\S]*?</X>` shape)
  on reasoning_content. Adds a 100 KB input cap with an early-bail
  note; the matchers themselves stay readable.

Per CodeQL's third remediation example, bounding the input length is
a valid fix when the regex is hard to rewrite — scavenge is best-effort
and the cap is well above any plausible legitimate reasoning_content.

* fix(web): drain CodeQL warnings on htmlToText

htmlToText leaned on a chain of regex replacements that CodeQL flagged
across six rules — bad-tag-filter, incomplete-multi-character-
sanitization, polynomial-redos (×2), double-escaping. None were
exploitable in our pipeline (output goes to the LLM, not a browser),
but the patterns had real correctness bugs visible to the model:

- `<script[\s\S]*?</script>` missed `</script >` (whitespace before
  `>`) and could leave `<script` behind on the second pass when an
  outer match revealed a previously-hidden inner opening.
- Chained `decodeHtmlEntities` replacements ran `&amp;` before `&lt;`,
  so `&amp;lt;` decoded to `<` instead of literal `&lt;`.

Rewrites both:

- `stripTagBlock(s, tag)` — indexOf-based scan with explicit tag-
  boundary check (avoids matching `<scriptfoo>`) and tolerant close
  matching (`</tag …>` with whitespace).
- `decodeHtmlEntities` — single regex pass with an entity map plus
  `&#nnn;` / `&#xHH;` numeric-entity handling. No more order bugs.
- 5 MB input cap on htmlToText so any residual quadratic patterns
  (e.g. the kept `<[^>]+>` strip) stay bounded.

21 web-tools tests still pass.
2026-05-05 18:58:43 -07:00
YHH 4ba0199c42 chore(tsconfig): add @/* path alias for src; migrate slash handlers (#289)
* chore(tsconfig): add @/* path alias for src; migrate slash handlers

The 16 files under src/cli/ui/slash/handlers/ sit four levels deep, so
every import to a top-level module read "../../../../i18n/index.js" or
the equivalent. The depth was load-bearing for nothing — it just made
moves and reviews painful. Adds a single \`@/* → src/*\` alias to
tsconfig.json and mirrors it in vitest.config.ts (esbuild via tsup
already picks up tsconfig paths transparently).

Migrates only the four-level offenders for now. Three-level imports
(siblings within cli/ that resolve to "@/cli/...") are left alone —
the relative form is arguably clearer when the import target is a
neighbour. A follow-up can tighten that if it's worth the churn.

Build, typecheck, and full test suite all pass on the migrated paths.

* fix(jobs): wait for actual close event after SIGKILL, not a fixed timer

stop() had two timing races. Both manifested as the same flake — the
returned snapshot's `running` flag could still be true even though the
test (and the user) just told us to stop the job.

1. SIGKILL phase used a fixed 800ms timer, then returned regardless of
   whether the OS had reaped the process tree. Under Windows scheduler
   load, taskkill /T /F on a 3-level tree (npm → node → vite) can take
   over a second to propagate before Node's `close` event fires.
2. SIGTERM phase awaited `readyPromise`, which is dual-purpose: it
   fires on either a startup ready-signal regex match OR child exit.
   If the job had already matched a ready signal, `readyPromise` was
   already resolved, so the SIGTERM grace race short-circuited
   immediately and we'd jump to SIGKILL with zero pause.

Adds `closedPromise` — fires only on close/error, never on ready
signal — and uses it for both the SIGTERM grace race and the post-
SIGKILL wait, with a 5s ceiling on the latter so a wedged kernel
can't hang us indefinitely.
2026-05-05 18:25:09 -07:00
YHH 5f80b252e8 refactor(filesystem): extract edit + search bodies into src/tools/fs/ (#287)
* refactor(filesystem): extract edit + search bodies into src/tools/fs/

filesystem.ts had grown to 681 lines, with three of the registered
tools — edit_file, search_files, search_content — carrying most of
the weight in their inline `fn:` bodies. The diff helpers (renderEditDiff,
lineDiff) were also trailing the registration code with no good reason
to live in the same file.

- src/tools/fs/edit.ts — applyEdit + lineDiff + renderEditDiff (the LCS-based diff renderer is now in the same file as its only caller).
- src/tools/fs/search.ts — searchFiles + searchContent share a SearchContext shape so each tool's `fn:` becomes a one-line dispatch.
- src/tools/filesystem.ts — registration entries kept; bodies are now thin pass-throughs.

`lineDiff` is re-exported from filesystem.ts so the existing test import
(`tests/filesystem-tools.test.ts`) doesn't move.

No public API change. No behavior change. filesystem.ts: 681 → 486 lines.

* fix(filesystem): close stat→read race in search_content (CodeQL)

Replaces the separate `fs.stat(full)` + `fs.readFile(full)` pair with a
single `fs.open` → `fh.stat` → `fh.readFile` sequence so the size check
and the actual read bind to the same fd / inode. No TOCTOU window.

Functionally equivalent: oversized files still skip cheaply (we never
read past the size check), small files still read in one shot.
2026-05-05 18:24:51 -07:00
YHH 4b77671103 refactor(shell): split tools/shell.ts into parse + exec submodules (#286)
shell.ts had grown to 847 lines, mixing three unrelated concerns:
allowlist parsing (which is pure string work and the security gate),
process spawning (which carries all the Windows / PowerShell / GBK
workarounds), and tool registration with the ToolRegistry. Each lives
in its own file now:

- src/tools/shell/parse.ts — tokenizer, allowlist, RISKY_ARGS demotion
- src/tools/shell/exec.ts — runCommand, prepareSpawn, killProcessTree, all the Windows quirks
- src/tools/shell.ts — registerShellTools, NeedsConfirmationError, format helpers, plus re-exports

No public API change — every name still importable from ./shell.js.
No behavior change. shell.ts: 847 → 304 lines.
2026-05-05 18:24:46 -07:00
YHH 900eae2a3a refactor(loop): extract heal/shrink/thinking/errors helpers into src/loop/ (#284)
loop.ts had grown to 1724 lines, mixing the CacheFirstLoop streaming
class with a dozen helper functions across four unrelated concerns:
message healing, oversized-result shrinking, thinking-mode flags, and
DeepSeek error formatting. Each concern now lives in its own module
under src/loop/, and loop.ts re-exports every public name so external
callers don't move.

No behavior change. loop.ts: 1724 → 1459 lines.
2026-05-05 18:24:42 -07:00
YHH 94047eadf3 fix(jobs): close stop() race condition; drop useless \$ escapes (#288)
* fix(benchmark): drop useless \$ escapes in tdd-eval prompt string

The h1 task description string used `\${file}::\${fullName}` inside a
regular `"..."` literal. The backslashes are no-ops (JS quietly drops
unrecognized escapes in regular strings) but trip CodeQL's
js/useless-regexp-character-escape rule. Identical resulting string,
cleaner source.

* fix(jobs): wait for actual close event after SIGKILL, not a fixed timer

stop() had two timing races. Both manifested as the same flake — the
returned snapshot's `running` flag could still be true even though the
test (and the user) just told us to stop the job.

1. SIGKILL phase used a fixed 800ms timer, then returned regardless of
   whether the OS had reaped the process tree. Under Windows scheduler
   load, taskkill /T /F on a 3-level tree (npm → node → vite) can take
   over a second to propagate before Node's `close` event fires.
2. SIGTERM phase awaited `readyPromise`, which is dual-purpose: it
   fires on either a startup ready-signal regex match OR child exit.
   If the job had already matched a ready signal, `readyPromise` was
   already resolved, so the SIGTERM grace race short-circuited
   immediately and we'd jump to SIGKILL with zero pause.

Adds `closedPromise` — fires only on close/error, never on ready
signal — and uses it for both the SIGTERM grace race and the post-
SIGKILL wait, with a 5s ceiling on the latter so a wedged kernel
can't hang us indefinitely.
2026-05-05 18:24:17 -07:00
YHH 0945a1189e test(comment-policy): ban bare TODO, FIXME, and translator notes (#285)
TODO/HACK markers without a (#nnn) issue anchor are debt leakage —
they accumulate without ever being tracked. Require the anchor; bare
markers fail the comment-policy gate.

FIXME is banned outright: either fix it now or open an issue and turn
it into a TODO(#nnn). The marker without follow-through is just noise.

Translator-note comments in i18n files ("english version", "中文版",
etc.) restate what the strings already say — i18n entries are
self-documenting.

src/ currently has zero violations of any of these rules, so this is a
floor-keeper, not a cleanup.
2026-05-05 18:24:13 -07:00
YHH bba8199ba4 chore(test): retry once on flaky tests (#282)
jobs.test.ts / loop.test.ts / bundle-smoke spawn real processes and
load the tokenizer cold; on Windows under load these intermittently
miss their wall-clock budget. One retry absorbs the scheduler
hiccup; a real failure still re-fails on the second run.
2026-05-05 16:05:58 -07:00
esengine fc8639a697 chore(release): 0.27.2 2026-05-05 15:51:25 -07:00
YHH 8c51dd6f0f fix(settings): preserve fields when settings POST writes more than one (#281)
handleSettings read cfg once up front, then per-field either called a
self-contained helper (setLanguage / saveApiKey / saveReasoningEffort)
or mutated the snapshot and called writeConfig — so a combined POST
like { lang, baseUrl } would write lang via the helper, then clobber
it with the stale snapshot in the writeConfig branch.

Single read up top, all field updates accumulate into one cfg, single
writeConfig at the end. Runtime side-effects (setLanguage,
applyPresetLive, applyEffortLive) fire after the disk write succeeds
so disk + runtime state can't diverge mid-request.

Closes #274
2026-05-05 15:48:51 -07:00
YHH 56f1cbb835 fix(filesystem): search_content.glob accepts real glob patterns (#280)
The `glob` arg was always a `name.toLowerCase().includes(...)` substring
filter, so `*.ts` matched the literal three-char filename instead of
TypeScript files. Param name advertised glob, behavior didn't.

Now glob via picomatch when the value contains `*`, `?`, `{`, or `[`;
case-insensitive substring otherwise so existing `.ts` / `test` callers
keep working. Patterns containing `/` match against the rel-path
(enabling `src/**/*.tsx`), basename otherwise.

Closes #273
2026-05-05 15:42:25 -07:00
YHH abb1b1ec7a fix(filesystem): search_files skips dependency/build dirs by default (#279)
Aligns search_files with search_content + directory_tree: skip the
existing SKIP_DIR_NAMES set (node_modules / .git / dist / build /
.next / target / .venv) by default, accept include_deps:true to opt
back into walking them. Fixes the surprising mismatch where
search_content("foo") and search_files("foo") had different default
scopes.

Closes #267
2026-05-05 15:32:18 -07:00
ctharveyandCharles H 4f1e65a629 fix(filesystem): slash-normalize tool output paths (#270)
Co-authored-by: Charles H <[email protected]>
2026-05-05 14:54:57 -07:00
ctharveyandCharles H 7096e43895 fix(shell): reject cd in parsed chains (#277)
Co-authored-by: Charles H <[email protected]>
2026-05-05 14:54:45 -07:00
esengine 8543c88034 chore(release): 0.27.1 2026-05-05 09:05:19 -07:00
YHH bdfb04c52b fix(shell): preserve Windows path backslashes inside quoted args (#266)
Inside `"..."` the parser treated any `\X` as a generic escape and
dropped the backslash, so `dir /b "C:\Users\foo\.bar"` ran against
`C:\Users\foo.bar`. Restrict the escape to `\"` and `\` only —
everything else stays literal so Windows path separators survive.

Single `isDqEscape` helper now shared by `tokenizeCommand`,
`detectShellOperator`, `splitOnChainOps`, and `parseSegment`.

Closes #265
2026-05-05 09:04:23 -07:00
esengine 207d55be52 chore(release): 0.27.0 2026-05-05 08:48:57 -07:00
YHH 1ab4ebe971 feat(mcp): registry-backed marketplace + CLI/Ink/dashboard surfaces (#264)
* feat(mcp): registry-backed marketplace + CLI/Ink/dashboard surfaces

Was: 5-entry hardcoded catalog. Now: live marketplace pulling from
registry.modelcontextprotocol.io (primary), smithery.ai (fallback),
bundled catalog (offline last-resort). 24h cache, schema v2, lazy
per-page loading so first list returns ~30 entries in ~1s.

CLI: `reasonix mcp {list,search,install,browse}` — browse is an Ink
TUI (type-to-filter, ↑↓ pick, Enter install, Tab load 5 more pages,
Esc quit).

Dashboard: MCP panel grows a "marketplace" chip beside all/live/
unbridged. New endpoints: GET /mcp/registry, POST /mcp/registry/install.
Install writes the spec to config.json (same path as manual /mcp/specs
POST).

Cache file moves to ~/.reasonix/mcp-registry-cache.json with a
schemaVersion gate; older blobs are silently rejected and refetched.
MCP_REGISTRY_PAGE_LIMIT env var caps how far an eager load walks
(rarely needed since pagination is now on demand).

* feat(mcp): smithery detail-fetch — install Smithery-only entries

Smithery's listing endpoint omits install metadata, so previously any
Smithery-sourced entry surfaced a "not yet supported" hint. Now `mcp install`
(CLI + dashboard) lazily fetches `/servers/<qualifiedName>` detail and
maps the connection to a runnable spec:

  http  → remote streamable-http with deploymentUrl
  stdio → npx -y @smithery/cli run <qualifiedName> (via new extraArgs
          field on RegistryInstall, threaded through specStringFor)

Verified live: `exa` → `exa=streamable+https://exa.run.tools`,
`hugeicons/mcp-server` → `mcp-server=npx -y @smithery/cli run hugeicons/mcp-server`.

Both CLI and dashboard install paths share the same lazy-detail fall-
through. 6 new tests cover http/stdio mapping, 404 fallback, and
extraArgs spec generation.

* test(shell): SpyGate denies instead of approving — kills 5s flake

The "passes the correct kind to the gate" test only asserts what the
gate received; it doesn't care whether the command runs. The old
SpyGate returned `run_once`, so the dispatch went on to spawn `npm i`
in an empty tmp dir. On Windows under concurrent load (full suite +
antivirus + npm cold start) the spawn could exceed the 5s test
timeout, then the afterEach `rmSync` hit EPERM because npm still had
the dir open.

Switching the gate's response to `deny` short-circuits the dispatch
before any spawn. Test runs in ~50ms instead of 1-5s, and the EPERM
failure mode goes away. The assertion (kind + payload were forwarded
correctly) is unchanged.

* test(mcp): anchor mock-URL prefixes with trailing slash

CodeQL flagged `url.startsWith("https://registry.modelcontextprotocol.io")`
in the test's inline fetch mock — without a trailing `/`, an attacker-
controlled URL like `https://registry.modelcontextprotocol.io.evil/`
would also match. Not actually exploitable since the URL is generated
by our own fetcher (the test mock just routes calls), but the rule is
correct in principle and trivial to satisfy.

Adds the trailing slash to every mockFetch host key plus the inline
matcher. All 34 tests still pass.

* feat(mcp): /mcp browse slash + dashboard cards/uninstall + iconUrl

Three improvements driven by user feedback after the marketplace v1:

1. **/mcp browse slash command** — opens an Ink marketplace modal inside
   the chat session. Type to filter, ↑↓ pick, Enter installs (or
   uninstalls if already present), Tab loads 5 more pages, Esc closes.
   No more "exit chat to run external `reasonix mcp` command" friction.

2. **Dashboard cards now show icons + installed-state badge**, and the
   detail pane gets: full description (no truncation), runtime/transport
   meta line + actual on-disk spec when installed, required-env card,
   homepage link, and an explicit "restart required" hint. Lift iconUrl
   out of the official registry's `icons[]` and Smithery's `iconUrl`.

3. **Uninstall button** — a marketplace entry whose spec already lives
   in config.mcp[] swaps Install → Uninstall (calls existing DELETE
   /mcp/specs). Detail pane carries the matching badge.

NOT in this PR: live hot-reload after install. `ctx.reloadMcp` was
declared but never wired in `chat.tsx`, so install/uninstall still
needs a `reasonix code` restart. Both UIs say so honestly. Real
hot-reload is a separate refactor.

* feat(mcp): hot-reload — install / uninstall now bridges live without restart

Closes the last gap in the marketplace flow: previously the user
installed an MCP server through the slash modal or dashboard, the spec
got written to config.json, and we had to tell them "restart `reasonix
code`". `ctx.reloadMcp` was declared on DashboardContext but never
wired in chat.tsx, so it was always undefined.

Refactor: chatCommand's inline MCP-init loop becomes an `McpRuntime`
object (createMcpRuntime in chat.tsx) with addSpec/removeSpec/
reloadFromConfig methods. The runtime owns:
  - clients, summaries, registered-tool-names per spec
  - hot-add path that calls loop.prefix.addTool for every newly
    bridged tool
  - hot-remove path that closes the client + unregisters tools +
    calls loop.prefix.removeTool

New on the supporting types:
  - ToolRegistry.unregister(name)
  - ImmutablePrefix.removeTool(name) — same cache-miss cost as addTool

Wiring:
  - chat.tsx passes runtime → Root → App → both modal/dashboard surfaces
  - SlashContext gets a `reloadMcp` field (for future slash handlers)
  - DashboardContext.reloadMcp is set by App.tsx
  - /mcp browse modal calls reloadMcp after install/uninstall;
    failure falls back to the old "restart required" message
  - POST /mcp/registry/install and POST/DELETE /mcp/specs all call
    ctx.reloadMcp() and surface bridged: true/false in the response
  - Dashboard panel shows "installed + bridged → spec" when hot-reload
    succeeded, falls back to plain "installed" otherwise

CLI `reasonix mcp install` still says "restart required" — it runs
in a separate process from any active chat session, so it can't reach
into a different process's runtime. The slash + dashboard surfaces
inside the same session do hot-reload.

* feat(mcp): unify /mcp into a single tabbed hub + cap dashboard list height

User feedback after the marketplace landed: the McpBrowser ("/mcp")
and the new McpMarketplace ("/mcp browse") felt like the same feature
because the visual style overlapped and the verb "browse" collided
with the existing component name "Browser".

Fix: wrap both in a single McpHub modal with two tabs.

  - `/mcp` → opens the hub on Live (or Marketplace if no servers attached)
  - `/mcp browse` (also `/mcp install`, `/mcp marketplace`) → opens on Marketplace
  - Tab key cycles tabs; the previously Tab-bound load-more in
    Marketplace moves to PgDn so the wrapper owns Tab cleanly
  - Slash result loses openMcpBrowser/openMcpMarketplace; gains
    openMcpHub: { tab: "live" | "marketplace" }
  - Tests in tests/slash.test.ts updated to match the new shape

Dashboard list height: `.sessions-grid` had `min-height: 540px` but
no ceiling, so a long marketplace list pushed the right detail pane
off-screen. Adds `max-height: calc(100vh - 140px)` so the list scrolls
internally (`.ssl-rows` already has overflow-y: auto). Affects all
panels using the grid (sessions, mcp, etc.); same UX win for any
long left-column list.

* fix(mcp): /mcp opens hub even with native tools (code mode)

In `reasonix code` mode, `tools` is seeded with native filesystem /
shell / memory / plan / choice tools, so `loop.prefix.toolSpecs` is
never empty. My earlier guard required all three (servers + specs +
toolSpecs) to be empty before opening the hub on the marketplace tab,
which meant `/mcp` in code mode silently fell through to the printed
fallback text dump — exactly what the user reported.

Simplified: interactive `/mcp` always opens the hub. Live tab when at
least one server is bridged, Marketplace tab otherwise. The text dump
is only reachable via `/mcp text` (replay / non-TTY scenarios).

Tests: renamed two assertions to `/mcp text`, added a new case that
exercises the code-mode regression directly (mcpSpecs present but
servers empty → opens hub on marketplace).

* fix(dashboard): cap marketplace list height — was still scrolling the page

The previous attempt added `max-height: calc(100vh - 140px)` to the
grid container, but CSS Grid items default to `min-height: auto` (which
means "content size"), so the children — `.sessions-list` (with the long
registry list) and `.sessions-detail` — grew past the grid's max-height
and dragged `.app-body`'s overflow-y along, pushing the right detail
pane below the fold. Symptom user reported: "I scroll to the bottom
and the right detail pane is gone."

Fix is the standard CSS Grid + inner-overflow recipe:

  - Add `grid-template-rows: minmax(0, 1fr)` so the row resolves to the
    grid's available height (capped by max-height) rather than to
    children's content size.
  - Add `min-height: 0; min-width: 0` to both grid items so they
    actually shrink to fit the track. With min-height: 0, their inner
    `.ssl-rows { overflow-y: auto }` and `.sessions-detail { overflow:
    auto }` rules finally take effect — list scrolls internally, detail
    pane stays visible at all viewport sizes.

Affects every panel using `.sessions-grid` (sessions, mcp, …) — same
UX win for any long left-column list.

* fix(mcp): load-more button — distinct exhausted state + lift hardcoded caps

Two bugs the user reported in the dashboard marketplace:

1. Click "load more" → no visible response. Cause: dashboard sent
   `limit=50` hardcoded, so even after the server walked more registry
   pages the response was sliced to the same top 50. Fix: track
   `displayLimit` in panel state, bump by 50 on each click, send as
   query param.

2. Server-side hardcoded caps (`pages` / `maxPages` clamped to 50,
   `limit` clamped to 200) hit a wall after a few clicks regardless
   of cache depth. Lifted to 200 / 200 / 1000.

3. When the registry is genuinely exhausted, the old footer just
   showed dim "all pages loaded" text — visually indistinguishable
   from a disabled button, so the user thought clicks weren't
   registering. New footer:
     - active: primary button with "load 50 more · showing X / Y"
       label so the count visibly grows after each click
     - exhausted: distinct success-tinted card with ✓ marker

Side effect: `q`-search now also benefits from raised caps. With
matchTarget early-stop the server still returns fast even when caps
are higher.

* fix(server): asset cache uses mtime, not "once per process"

Caused real friction during dashboard development: change panels source,
run `npm run build`, refresh browser → still see old UI because the
running reasonix server cached `dashboard/dist/app.js` in memory at
first read and never re-reads. Required a full restart to pick up any
dashboard rebuild.

Switched to mtime-keyed cache: re-stat each request, re-read body if
mtime advanced. `dashboard/dist/app.js` is ~800KB so the stat-then-
hit-cache path is microseconds. The previous "ONE read per process"
optimisation was guarding against ~zero cost.
2026-05-05 08:47:16 -07:00
esengine 767633d00e docs(readme): preview Reasonix Advocate badge in Community section
Show what the badge looks like before anyone has earned it, so
prospective advocates can see the target. Uses the for-the-badge
shields.io style in the project's lavender brand colour; metadata
badges at the top stay flat-square for information density.
2026-05-05 06:20:20 -07:00
esengine 10c7d45ac3 docs(readme): invite users to share advocacy in Show and tell
Point active users at the Show and tell discussion category and
preview a forthcoming Reasonix Advocate badge for sustained advocates.
Word of mouth is the only growth channel for a zero-marketing-budget
project, so make the ask explicit.
2026-05-05 06:05:02 -07:00
esengine b5f6e1e54c chore(release): 0.26.1 2026-05-05 04:26:11 -07:00
YHH 4e16baaa66 fix(shell): demote destructive flags on allowlisted commands (#258)
* fix(shell): demote destructive flags on allowlisted commands (#257)

Allowlist matched on leading tokens only, so `git branch -D`,
`find -delete`, `git diff --output=...`, `npx eslint --fix`, etc.
flowed through without confirmation. Add a per-prefix RISKY_ARGS
table that demotes specific tail tokens back to the confirm gate;
both `--flag value` and `--flag=value` forms are caught. Chains
inherit via the existing per-segment isAllowed call.

* fix(shell): also demote tree -o and find -fprint0 (#257)

Follow-up audit caught two more write-anywhere paths on otherwise-
allowlisted inspection tools: `tree -o FILE` writes the tree output,
and `find -fprint0 FILE` writes NUL-separated paths. Same risk class
as the `git diff --output=` family already covered.
2026-05-05 04:25:27 -07:00
esengine b85f1de3b1 docs(readme): switch star-history to /chart timeline + log-scale
The /svg?type=Date endpoint was returning empty for this repo (likely
because the cumulative-by-day shape needs more data points). /chart with
type=timeline + logscale renders correctly from day one and reads better
when the y-axis range is small.
2026-05-05 01:11:16 -07:00
esengine d35e27d193 test(jobs): poll runningCount after stop/shutdown to absorb taskkill async
The post-stop/shutdown asserts were racing Windows taskkill /T tree
propagation, occasionally catching a transient `runningCount === 1`
right after the stop promise resolved. Poll up to 2s for the value to
settle to 0 — distinguishes "persistently wrong" (real bug) from
"momentary race during reap" (not a bug).
2026-05-05 01:00:58 -07:00
esengine 835c6b8f23 docs(repo): improve passive-discovery surface
Add custom OG social card (1280×640), star-history chart in both READMEs,
FUNDING.yml so the Sponsor button shows up. Goal: when someone lands here
from a shared link or GitHub explore, the first impression and signal of
seriousness should be higher than a default-rendered repo page.
2026-05-05 00:37:56 -07:00
esengine 9b23390605 docs(web): full landing-page refresh — drop hardcoded numbers, refresh capabilities, add community section
The marketing site had drifted from the project. Bring it back in line with
the post-0.26 README:

- Hero: drop "Ink TUI" / "No LangChain" / "DeepSeek V4" pin; replace the
  three hardcoded-number stats (90.2% / ~98% / 100%) with qualitative tags
- Why Reasonix: reorganize the six cards as four architectural pillars
  (matching ARCHITECTURE.md) plus two community/positioning cards
- In the box: expand from six to twelve capabilities, matching the README's
  feature-grid.svg — adds plan mode, permissions, dashboard, sessions,
  semantic search, auto-checkpoints, /effort, replay, event log
- Benchmarks: remove the hardcoded-numbers table; keep methodology + repro
  command + link to the harness directory
- CLI: refresh command list and flags to current 0.26 surface
- New Community section with contrib.rocks wall + good-first-issue /
  discussions / contributing links
- Footer: drop Changelog (we don't keep one), add Releases / Benchmarks /
  Contributors links

i18n.js: rewrite both dicts; 118 keys × 2 with verified 1:1 parity. CSS:
new .community styles, .stat-num resized for qualitative tags, .feat-grid
responsive breakpoints expanded for the wider 12-card layout.
2026-05-05 00:14:32 -07:00
esengine ba58eceb3c docs(readme): SVG-rendered pillar + capability cards for proper visual hierarchy
GitHub strips CSS from HTML tables, so the previous <table>-based pillar
and capability sections rendered as plain rows. Move both to custom SVG
assets that match the existing hero-terminal.svg design language —
dark cards (#0a0c10), gradient icons (teal/blue/purple), Inter + JetBrains
Mono typography.

- pillars.svg / pillars.zh-CN.svg: new 2x2 grid of the four architectural
  pillars from ARCHITECTURE.md, with deep-link anchors below
- feature-grid.svg / feature-grid.zh-CN.svg: rewritten as a 3x4 grid of
  twelve concrete capabilities (was 6 cards with hardcoded "94% live cache
  hit" copy that violated the no-hardcoded-numbers rule)

README drops the HTML <table> markup, halving its line count.
2026-05-04 23:38:00 -07:00
esengine 18860ac28e docs(readme): redesign — terminal-aesthetic, four-pillar grid, capability list
Visual identity:
- Dark-themed shield badges matching terminal color palette
- <h3>-driven hero hierarchy in place of bold-paragraph tagline
- GitHub callouts (TIP / NOTE / IMPORTANT) as visual anchors

Information architecture:
- Four numbered pillar cards (2x2) mirroring ARCHITECTURE.md sections,
  each deep-linking into the relevant pillar
- Capability grid (3x4) surfacing twelve concrete features the previous
  README hid: cell-diff renderer, MCP, plan mode, permissions, dashboard,
  persistent sessions, hooks/skills/memory, semantic search, auto-checkpoints,
  /effort, transcript replay, event log
- Comparison table gains an "Open community development" row

EN and zh-CN kept structurally identical (same sections, same headings).
2026-05-04 23:02:26 -07:00
esengine 07a5f34d16 chore: sync package-lock to 0.26.0 2026-05-04 23:02:24 -07:00
esengine ee3f8c676c chore(release): 0.26.0 2026-05-04 22:38:51 -07:00
YHH cebe2c3ba8 fix(renderer): avoid \x1b[2J on resize so input bar stops duplicating on conhost (#249) (#255)
\x1b[2J on Windows PowerShell 5.1's legacy conhost scrolls the visible
viewport into scrollback rather than truly erasing it. Each terminal
resize was pushing the current input/toolbar into scrollback, and a
later grow-resize pulled those rows back into the viewport — visible
to the user as duplicated input bars.

Use the same rewind-and-clear pattern (\r\x1b[<N>A\x1b[J) already
used by commitScrollback / emitStatic. \x1b[J fills with spaces in
place, no scrollback push. Platform-neutral, no Windows branch.
2026-05-04 22:34:41 -07:00
YHH d24a6b5b38 refactor(cli): move /prune-sessions to reasonix prune-sessions CLI (#254)
The slash form didn't need any chat state — it just deleted idle session
files from disk. Belongs as a CLI subcommand. Adds --days and --dry-run
flags (the slash form had neither).

  reasonix prune-sessions               # default 90d, deletes
  reasonix prune-sessions --days 30
  reasonix prune-sessions --dry-run     # preview, no delete

Removed:
  - /prune-sessions slash handler + registry entry
  - pruneUsage / pruneNone / pruneInfo i18n strings (EN + zh-CN)
  - slash schema entries for "prune-sessions"
  - tests covering the slash form

Updated:
  - /doctor's stale-session warning now points at `reasonix prune-sessions`
  - i18n schema gains cli.pruneSessions, ui.pruneDaysHint, ui.pruneDryRunHint

Part of #243. /init stays slash (it leverages the live edit-gate;
not actually a CLI shape on closer look). /dashboard stays dual.
/clear rename pending RFC.

Tests: 2254 pass.
2026-05-04 22:09:43 -07:00
YHH 8c49b38732 refactor(slash): drop /setup — handler did nothing useful (#253)
/setup just printed a static "exit and run reasonix setup" reminder.
The actual `reasonix setup` CLI subcommand is unchanged; we just
removed the slash command that pointed at it.

Part of the #243 inventory cleanup. Net -5 LOC across handlers,
commands, i18n (EN + zh-CN), and tests.

Tests: 2254 pass.
2026-05-04 20:55:57 -07:00
Wesley Viana 32a4818d76 chore: test coverage and mutation test (#247)
* chore: test coverage and mutation test

* Increase mutation scope
2026-05-04 20:46:48 -07:00
Wesley Viana fe074942f4 fix: Model was still doing things while pending to approve (#237)
* fix: Model was still doing things while user was being prompt to accept tool call.

* Checkpoint feedback, remove dead code
2026-05-04 20:43:07 -07:00
YHH eb6291843a feat(loop): aggressive fold tier between 70% and 80% of ctxMax (#252)
PR-D from #244. Closes the gap between the normal-fold threshold (50%)
and the force-summary cliff (80%): when a turn lands in 70-85%, the
recent K turns alone are already big enough that a normal fold (tail =
20% of ctxMax) wouldn't buy meaningful headroom. The aggressive tier
shrinks the tail to 10% of ctxMax — sacrifices some recent context
for a real reset.

Decision matrix now:

  ratio > 0.8  → exit-with-summary
  ratio > 0.7  → fold (tail = 10% ctxMax)  [aggressive]
  ratio > 0.5  → fold (tail = 20% ctxMax)  [normal]
  else         → none

The status line and warning text both surface "aggressive" when that
tier fires, so users know why recent turns were trimmed harder than
usual.

Implementation:

  - PostUsageDecision now carries `tailBudget` and `aggressive` fields
    when kind === "fold". loop.ts passes tailBudget through to
    compactHistory (which already accepted keepRecentTokens).
  - decideAfterUsage hoists the alreadyFolded short-circuit above the
    fold-band checks so neither tier re-fires within a turn.

Tests: 2243 pass (was 2242; +1 covering the aggressive band yields a
warning matching `aggressively folded` and a status with `aggressive`).
2026-05-04 20:36:55 -07:00
ctharveyandCharles H 305bc641a2 refactor(mcp): extract server summary matching + replacement helpers (#250)
- Add sameMcpServerSummary(a, b) for logical identity (ref or label+spec).
- Add replaceMcpServerSummary(servers, target, updated) for immutable list update.
- Replace inline prev.map(...) in App.tsx with the helper call.

Co-authored-by: Charles H <[email protected]>
2026-05-04 20:19:20 -07:00
YHH 557cfc12c7 refactor(loop): /compact now folds (cache-safe), drop in-place mutation (#251)
PR-B from #244: closes the foot-gun left over from #238 / #241.

Before this PR, /compact called loop.compact() → ContextManager.inPlaceCompact(),
which mutated mid-history tool result bodies. Cache-aware analysis (#238) showed
that path costs more than it saves: shrinking 50% of prompt size while
invalidating 100% of cache from the mutation point on. The 95% preflight valve
was the second caller of the same path.

What changed:
  - /compact handler now calls loop.compactHistory() (the cache-safe fold from
    #241) via the existing async-via-postInfo pattern (mirrors /dashboard).
    Sync return is "folding…"; result lands as a follow-up info line.
  - 95% preflight: tries fold first (one summary call, append-only) instead of
    in-place compact. If fold can't shrink anything, surfaces the warning and
    lets the request go (the user can /clear).
  - loop.compact() public method removed. ContextManager.inPlaceCompact()
    removed. shrinkOversizedTool* helpers stay (still used by session
    heal-on-load and tests).
  - 80% force-summary warning text updated: now mentions /compact since the
    name is safe to recommend.

User-visible:
  - /compact name kept (muscle memory + short to type), behavior is now
    cache-safe fold. Old behavior is gone.
  - /help text updated to reflect the new semantics.
  - tests/preflight.test.ts: warnings now report fold result instead of
    pre-compacted tool count; the "nothing to fold" path replaces the old
    "nothing to auto-compact".

Tests: 2233 pass. Typecheck clean.

Closes #243's foot-gun deletion concerns.
2026-05-04 20:18:20 -07:00
ctharveyandCharles H 10f1866c02 refactor: make applyMcpAppend immutable — returns new McpServerSummary instead of mutating input (#248)
- applyMcpAppend() now returns a new McpServerSummary with updated
  report.tools.items and toolCount, built via object/array spreads.
- Original target object is never mutated.
- ApplyAppend type returns McpServerSummary instead of void.
- kickOffMcpReconnect captures the return value and updates its local target.
- App.tsx stores MCP servers in local state and immutably replaces the
  matching summary after append-drift.
- Both biome-ignore/noExplicitAny suppressions removed.

Co-authored-by: Charles H <[email protected]>
2026-05-04 19:45:32 -07:00
YHH d632755f43 refactor(loop): extract ContextManager — zero behavior change (#245)
Pulls the four ad-hoc compaction mechanisms behind one component
(see #244 for the full architectural rationale):

  - decideAfterUsage(usage, model, alreadyFoldedThisTurn) returns
    "fold" / "exit-with-summary" / "none" — the policy that used to
    live as inline if-blocks in step()
  - decidePreflight(messages, toolSpecs, model) is the local outgoing
    estimate gate (>95% of ctxMax)
  - fold(model, opts) replaces compactHistory's body
  - inPlaceCompact(maxTokens) replaces compact's body and is also
    what the 95% preflight calls — the one remaining cache-breaking
    path, marked for removal in PR-B
  - trimTrailingToolCalls() factors out the in-flight tool_calls tail
    drop used before forced-summary

loop.ts methods become thin delegators: compact / compactHistory keep
their public signatures (slash handlers and tests untouched);
forceSummaryAfterIterLimit stays in loop.ts because it's tightly
coupled to LoopEvent yielding.

All thresholds and the summary-marker constant moved to
context-manager.ts. No values changed.

Tests: 2235 pass (no test changes). Typecheck clean.
2026-05-04 19:38:29 -07:00
YHH ea37106e03 ci: add CodeQL security scanning workflow (#246)
Runs on push to main, every PR, and weekly cron. Uses the
javascript-typescript analyzer with security-extended queries.
2026-05-04 19:33:57 -07:00
ctharveyandCharles H eb7c9b5425 fix(mcp): prevent unhandled rejection during hung send timeout (#240)
Co-authored-by: Charles H <[email protected]>
2026-05-04 19:15:56 -07:00
YHH 8681d158aa feat(loop): append-only history fold at 50% of ctxMax (#241)
When a turn's response shows promptTokens > 50% of the model's context
window, replace the older portion of the log with a single synthesized
assistant summary and keep the trailing turns whose token weight fits
in 20% of ctxMax. One cache break per fold; cache rebuilds in ~1 turn,
then the conversation continues under the cap until the next fold.

Without this, append-only sessions grow unbounded — by the time
prompt > 80% of ctxMax, the existing force-summary path fires every
turn ($0.07/turn purgatory until /clear or /compact). Fold prevents
ever reaching that cliff.

Sized so:
  - tail budget = 0.2 * ctxMax → ~30% headroom before next fold
  - min savings fraction = 0.3 → no fold if head wouldn't shrink the
    log meaningfully (avoids re-fold thrash on stable post-fold logs)
  - summary call uses deepseek-v4-flash + high effort, ~$0.07 each

Validated on a real 20-turn DeepSeek session with ctxMax pinned at 50k
(scripts/probe-long-session.mts):
  turn 10: 52% trips → fold fires → 42 msgs → 19, prompt 25k → 13k
  turn 11: cache rebuilds to 84% within one turn
  turn 16: 51% trips again, fold fires
  total cost across 20 turns: $0.0381 (vs $0.0493 without fold)
  total mutations: 2 (= the 2 folds, nothing else)

Closes #236.
2026-05-04 19:03:32 -07:00
YHH a621f17294 perf(loop): drop in-place auto-compaction — was destroying prompt cache (#238)
* perf(loop): drop in-place auto-compaction — was destroying prompt cache

DeepSeek prompt cache is prefix-exact: mutating any byte of an old
message invalidates every cached token after that point. We were
calling compactInPlace() in five places (turn-end, post-tool-args,
40-80% proactive, 80% reactive, plus the slash command), which meant
long sessions repeatedly traded "smaller prompt" for "0% cache hit
on the rest" — net negative against DeepSeek's 4× cache discount.

Probed empirically (scripts/probe-cache.mjs):
  append-only:    98.6% cache hit
  one mutation:    0.0% cache hit, lost 4480 cached tokens
  long session:   ~91% sustained across turns after warmup

Removed the auto-trigger paths entirely. The 80% reactive block now
goes straight to forced-summary instead of trying to mutate-then-bail
(it was already falling through to summary in the common case). The
95% preflight emergency valve and the manual /compact slash command
are kept — they're explicit/last-resort and expected to break cache.

Refs #236

* test(loop): add end-to-end cache-hit probe driving real CacheFirstLoop

Complements scripts/probe-cache.mjs (which probes the API primitive).
This drives the actual loop through 6 real turns and asserts:
  - log.compactInPlace() is never called (append-only invariant)
  - warm-turn cache hit % stays above 80%

Measured against the live API after the auto-compaction removal:
  turn 0:  0.0% (cold cache, expected)
  turns 1-5: 99.0, 98.5, 98.0, 97.6, 97.1 — ~98% sustained
  total mutations: 0
2026-05-04 18:35:08 -07:00
esengine 4b446e8640 release: 0.25.1 — chain operators + file redirects in run_command
`run_command` learns the four common shell chain operators (`|`, `||`,
`&&`, `;`) and the seven file redirect operators (`>`, `>>`, `<`, `2>`,
`2>>`, `2>&1`, `&>`). Parsed and spawned natively — no shell is invoked,
so semantics are identical on Windows / macOS / Linux; PowerShell 5.1's
`&&` parse error and the object-vs-bytes pipe gap are sidestepped.

Each chain segment is allowlist-checked independently: `git status |
grep main` now auto-runs when both halves are individually allowed, the
granular-approval behaviour wviana asked for in discussion #231.

The chain parser stays consistent with the project's long-standing
lenient tokenizer — `cargo run -- --flag=1&2` and similar embedded-
operator args stay literal instead of getting POSIX-strict-rejected.
shell-quote is no longer a dependency; `splitOnChainOps` is whitespace-
bounded like the existing `detectShellOperator`.

Mid-pipe `2>&1` correctly merges stderr into the next segment's stdin
without truncating on stdout-end (counter-based close-when-both-ended).

Targets resolve relative to the project root. Heredoc `<<` and
background `&` remain explicitly rejected with clear errors. `\$VAR`
and `\$(...)` pass through as literal characters — no shell expansion.

Closes #232. Driven by discussion #231. PRs: #233 (chain ops), #234
(lenient-tokenizer regression fix), #235 (redirects + mid-pipe `2>&1`).
2026-05-04 17:56:30 -07:00
YHH 9443f50955 feat(shell): support file redirects in run_command (#235)
* feat(shell): support file redirects in run_command (`>`, `>>`, `<`, `2>`, `2>>`, `2>&1`, `&>`)

Phase 2 of the chain-aware run_command rewrite. Each segment now parses
trailing redirects via a single-pass walker (no shell), opens files with
fs.openSync, and hands the resulting fds to spawn's stdio array. Pipe
wiring still applies — `<` overrides pipe-stdin only when explicitly
present; `>`/`>>`/`&>` override the pipe-out / capture-buffer wiring.

Supported per segment (max one per fd):

- `>`   stdout truncate
- `>>`  stdout append
- `<`   stdin from file
- `2>`  stderr truncate
- `2>>` stderr append
- `2>&1` merge stderr → stdout (file fd, pipe, or our buffer, whatever stdout points to)
- `&>`  both → file (truncate)

Targets resolve relative to the chain's cwd. Multiple redirects to the
same fd are rejected with a clear conflict message.

ChainSegment now carries `redirects: Redirect[]` alongside `argv`. The
old `tokenizeCommand + detectShellOperator` per-segment combo is
replaced with `parseSegment`, a quote-aware single-pass walker that
emits both argv tokens and redirects at the same level — keeps the
lenient embedded-`&`/`|` handling intact (the `cmd1 ; cmd2 -flag=1&2`
regression fix from #234 still passes).

Heredoc `<<` is rejected explicitly. Background `&` is rejected
explicitly (use run_background, not run_command). `$VAR` and `$(…)`
pass through as literal characters — no shell expansion, matching the
existing single-command tokenizer.

Adds 30 new tests in tests/shell-redirects.test.ts covering parser
output and execution; updates the obsolete redirect-rejection tests
in tests/shell-tools.test.ts to cover the new rejection set
(background `&`, heredoc `<<`, missing target, multi-redirect-per-fd).

* fix(shell): hold child.stdin open until both prev streams end on mid-pipe `2>&1`

`cmd1 2>&1 | cmd2` was wiring prev.stdout into child.stdin with default
end-on-source-end, then piping prev.stderr in with `end: false`. When
stdout finished first, child.stdin closed and any subsequent stderr
writes hit a closed stream — output got truncated.

Both branches now pipe with `end: false` and a 2-counter closes stdin
only after both source streams emit `end`. Adds a test that pipes
stderr through to a downstream cat-like process and asserts both
streams reach the destination.
2026-05-04 17:29:08 -07:00
YHH 56b94d0677 fix(shell): drop shell-quote, hand-roll chain splitter to keep lenient tokenization (#234)
Phase 1 (#233) used shell-quote for chain segmentation, but its strict
POSIX tokenization split `--flag=1&2` into three tokens with `&` as a
background operator — a regression vs. pre-Phase-1 behavior, where the
existing lenient `tokenizeCommand` left embedded `&`/`|`/`;` chars as
literal bytes inside larger tokens.

Replace with a small whitespace-bounded chain splitter that matches the
existing `detectShellOperator` convention: chain ops only count when
they begin a whitespace-separated token. Each segment then runs through
the existing `tokenizeCommand` (lenient) and `detectShellOperator`
(rejects `>`, `<`, `&`, `2>&1`, `&>`).

Recovers:
- `cargo run -- --flag=1&2`           — runs (was rejected post-#233)
- `git status ; cargo run -- --flag=1&2` — chain runs, second segment keeps `&`

Drops:
- `git status|grep main` (no spaces) — never worked pre-Phase-1, was a
  shell-quote-only side effect; align with the project's
  whitespace-bounded operator convention.

Also drops `$VAR` / `$(...)` rejection — these now pass through as
literal arguments, matching the existing single-command tokenizer's
behavior. Models see the literal `$HOME` in echo's output and learn.
2026-05-04 17:10:13 -07:00
YHH 5ea5f76de6 feat(shell): support |, &&, ||, ; in run_command via split-and-spawn (#233)
Parse chain operators ourselves with shell-quote and spawn each segment
as a separate process — never invoke a system shell. Sidesteps PowerShell
5.1's `&&` parse error and the object-vs-bytes pipe semantics gap on
Windows. Each segment is allowlist-checked independently, so
`git status | grep main` runs when both halves are individually allowed.

Redirects (`>`, `<`, `2>&1`), background `&`, env-var expansion `$VAR`,
command substitution `$(…)`, and subshells `(…)` remain rejected up-front
with clear errors.

Tracks #232, addresses #231.
2026-05-04 16:56:38 -07:00
310 changed files with 18969 additions and 12592 deletions

No files matched your search

+1
View File
@@ -0,0 +1 @@
github: esengine
+3 -1
View File
@@ -17,7 +17,9 @@ Steps or minimal code that reproduces it.
- Reasonix version:
- Node version:
- OS:
- DeepSeek model (e.g. `deepseek-chat`, `deepseek-reasoner`):
- Shell (bash, zsh, fish, PowerShell, etc.):
- Terminal emulator (kitty, WezTerm, Windows Terminal, etc.):
- DeepSeek model (e.g. `deepseek-v4-flash`, `deepseek-v4-pro`):
**Logs / transcript**
If using the CLI, attach the relevant chunk of `--transcript`.
+6 -2
View File
@@ -32,8 +32,12 @@ jobs:
- name: Typecheck
run: npm run typecheck
- name: Test (vitest)
run: npm test
- name: Test (vitest + coverage)
run: npm run test:coverage
- name: Coverage job summary
if: always()
run: node scripts/coverage-summary.mjs
- name: Build (tsup)
run: npm run build
+38
View File
@@ -0,0 +1,38 @@
name: CodeQL
on:
push:
branches: [main]
pull_request:
branches: [main]
schedule:
- cron: "0 6 * * 1"
jobs:
analyze:
name: analyze (${{ matrix.language }})
runs-on: ubuntu-latest
permissions:
actions: read
contents: read
security-events: write
strategy:
fail-fast: false
matrix:
language: [javascript-typescript]
steps:
- uses: actions/checkout@v4
- name: Initialize CodeQL
uses: github/codeql-action/init@v3
with:
languages: ${{ matrix.language }}
queries: security-extended
- name: Autobuild
uses: github/codeql-action/autobuild@v3
- name: Analyze
uses: github/codeql-action/analyze@v3
with:
category: "/language:${{ matrix.language }}"
+3
View File
@@ -1,6 +1,7 @@
node_modules/
dist/
coverage/
.stryker-tmp/
.env
.env.local
*.log
@@ -32,4 +33,6 @@ sessions/
.reasonix/semantic-skip
# Scratch entry regenerated each time scripts/bundle-codemirror.mjs runs.
scripts/.cm-entry.mjs
# Personal bun lockfile — project uses npm officially.
bun.lock
+533
View File
@@ -3,6 +3,539 @@
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.30.5] — 2026-05-07
**Headline:** three contributor-led follow-ups from the #350 RFC plus
the #366 onboarding piece. The repeat-loop storm guard now exempts
obviously-safe inspector tools (`read_file`, `list_directory`,
`job_output`, `list_jobs`) so a model intentionally re-reading state
isn't flagged as stuck. A new `wait_for_job(jobId, timeoutMs?)` tool
replaces N-iteration polling loops with a single blocking call —
returns the moment the job exits or emits new output. And `/skill
new <name>` finally provides the missing creation entry-point for
user skills, scaffolding a stub with the right frontmatter so
first-time users don't have to read the source to author a skill.
**Features:**
- feat(storm): add `stormExempt` flag on `ToolDefinition`, set on
`read_file`, `list_directory`, `job_output`, `list_jobs`. Cheap
state-inspection no longer trips the repeat-loop guard. Mutating
tools and unknown tools still go through the existing window-and-
threshold check. (#350, PR #388 by @ctharvey)
- feat(jobs): new `wait_for_job(jobId, timeoutMs?)` shell tool —
blocks until the job exits or emits new output, bounded by
`timeoutMs` (default 5000, clamped to 0..30000). Returns
`{ exited, exitCode, latestOutput }`; `latestOutput` is the
delta since the call started, not the full buffer. Rides the
existing job registry's exit + output events; one call replaces
N polling iterations and is token-cheaper than the prior
re-call-job_output loop. (#350, PR #390 by @ctharvey)
- feat(skills): `/skill new <name>` scaffolds a stub at
`<project>/.reasonix/skills/<name>.md` with minimal frontmatter
+ a comment block listing the optional knobs (`runAs`,
`allowed-tools`, `model`). `/skill new <name> --global` writes
under `~/.reasonix/skills/` for cross-project use; auto-falls-
back to global when there's no project root. The empty
`/skill list` now ends with an explicit "no remote registry yet
— scaffold one with `/skill new <name>`" line so users don't
hunt for a marketplace that doesn't exist. (#366, PR #394)
**Bug fixes:**
- fix(skills): atomic create with `wx` flag — close the TOCTOU
race between `existsSync(...)` and `writeFileSync(...)` that
CodeQL flagged. The existence check IS the atomic write now;
`EEXIST` from a parallel writer surfaces as the same "skill
already exists" error instead of silently overwriting. (PR #394)
## [0.30.4] — 2026-05-07
**Headline:** sweep of the user-reported bug + onboarding queue from
the 0.30.2 / 0.30.3 launch day. Resume now restores the full session
state (cache hit %, cost, last context bar — previously they all
showed zero on a fresh boot until the first turn landed). The model
pill on assistant cards reflects the model that actually answered
after `/model` or `/preset` switches it. Bare `/model` opens an
interactive picker — typed-id entry stays for power users.
PowerShell users get Shift+Tab back via three additional encodings
(modifier-encoded back-tab, modifyOtherKeys, Kitty keyboard). And a
class of "junk text after exit" on Linux/fish (terminal-feature
replies leaking into the parent shell) gets a defensive stdin drain
in the exit path.
`--dir` is now discoverable for beginners — surfaced in the welcome
banner, the `/status` panel, the filesystem sandbox-escape error,
and a Getting Started callout in both READMEs.
**Bug fixes:**
- fix(stats): persist cache totals + `lastPromptTokens` across
resume. `SessionMeta` only carried `totalCostUsd` / `turnCount`,
so on every resume `/status` showed 0 context + 0% cache hit until
the first turn actually fired (even though the prefix was already
cached, costing $0.01 per turn). Three new fields are persisted
per-turn and seeded into `SessionStats` on resume; the existing
carryover plumbing now covers cache + last context.
(#364, PR #384)
- fix(ui): `/model <id>` and `/preset {auto,flash,pro}` now update
the active model in the agent store so the next assistant card
pill reflects the new selection. Previously `state.session.model`
was set once in `initialState()` and never mutated, so the pill
showed the launch-time model regardless of what actually answered
the turn. New `session.model.change` event; cards already opened
keep their captured model so mid-turn auto-escalation doesn't
retroactively relabel. (#372, PR #385)
- fix(input): recognize three additional Shift+Tab encodings for
PowerShell hosts and modern terminals — `\x1b[1;2Z` (modifier-
encoded back-tab some PowerShell hosts emit), `\x1b[27;2;9~`
(modifyOtherKeys level 2, which we already enable on startup),
`\x1b[9;2u` (Kitty keyboard envelope). Without these the edit-
mode cycle was silently dropped on PowerShell.
`/mode` typed fallback continues to work. (#373, PR #386)
- fix(tty): drain pending feature-detection replies on exit. Linux
reporters saw `^[]11;rgb:...^[\^[[33;1R^[[?62;1;4c` printed by
fish / bash after exiting reasonix — those bytes are responses to
OSC 11 / CPR / DA1 queries the runtime emits during startup that
sit in stdin's queue until exit. New `drainTtyResponses(50ms)`
reads-and-discards anything queued before control returns to the
parent shell. Layered on top of 0.30.3's alt-screen mitigation
(`--no-alt-screen` users get the fix too). (#365, PR #391)
**Features:**
- feat(ui): bare `/model` opens an interactive model picker — arrow-
key list, current model marked, `[r]` refreshes the catalog, esc
cancels. Seeds from the live DeepSeek catalog
(`useSessionInfo.listModels()`); falls back to the four known
DeepSeek ids when the catalog hasn't loaded yet so the picker
isn't empty on first open. The current id is always included even
when the API didn't return it. `/model <id>` typed entry stays
for power users. (#371, PR #387)
- feat(ui): surface `--dir` / pinned workspace for first-time users.
WelcomeBanner shows the workspace + relaunch hint in code mode;
`/status` adds a `workspace <path> · pinned at launch` line; the
filesystem sandbox-escape error points at `reasonix code --dir
<path>` instead of just dropping a raw error; both READMEs gain a
Getting Started subsection on `--dir`. No new slash command —
mid-session retargeting is intentionally not supported (the
message log + memory paths get tangled with stale roots).
(#370, PR #389)
## [0.30.3] — 2026-05-07
**Headline:** the chat scroll rewrite lands. Ink 5.2 → 7.0.2 / React
18.3 → 19.2, the cell-diff renderer is retired, and `reasonix code` /
`reasonix chat` default to alt-screen with row-precision virtual
scroll. PgUp / PgDn / mouse wheel scroll history; an empty prompt + ↑
also scrolls (Ctrl+P / Ctrl+N still recalls prompt history). When
scrolled away from bottom, the prompt hides and a `📖 reading
history — End / PgDn to return` hint appears. Resize-ghost dividers
and `<Static>`-related scroll-yank artifacts are gone with the
renderer that produced them. `--no-alt-screen` keeps the legacy
in-shell-scrollback behavior.
`web_search` gains a configurable backend — Mojeek stays the default,
but `/web-search-engine searxng <url>` switches to a self-hosted
SearXNG instance for users whose network blocks Mojeek. And the MCP
filesystem sandbox now fails with an actionable
`mkdir -p '<path>'` hint instead of a raw Node stack when the
configured directory doesn't exist; the wizard offers to create it
inline at config time.
**Features:**
- feat(ui): row-precision virtual scroll on Ink 7 + React 19.
`<Static>` retired (incompatible with alt-screen reflow);
`React.memo(CardRenderer)` plus reference-stable cards in the
reducer skip the reconciler on unchanged history. `useChatScroll`
drives an outer `overflow=hidden` clip + inner `marginTop=-N`
slide; `useBoxMetrics` reports inner / outer heights so bounds
clamp and auto-pin to bottom on new content. `App` owns
PgUp/PgDn/End/wheel; PromptInput hands off ↑/↓ on empty buffer
when pinned + idle. Ticker migrated to Ink 7's shared
`useAnimation`. (PR #380)
- feat(web): configurable `web_search` backend with SearXNG support.
`/web-search-engine` shows / switches the active engine; URL is
persisted to `~/.reasonix/config.json`. Mojeek remains the default;
the original Mojeek path is preserved as `searchMojeek()`. Protocol
auto-normalizes (`localhost:8080` → `http://...`); an unreachable
SearXNG endpoint surfaces an install hint instead of a raw fetch
error. (PR #338)
**Bug fixes:**
- fix(mcp): preflight the filesystem sandbox directory before
spawning `@modelcontextprotocol/server-filesystem`. Missing
directories now throw `MCP filesystem sandbox '<path>' does not
exist — create it with: mkdir -p '<path>'` instead of a raw Node
stack from inside `npx`'s child. The init wizard adds an inline
`[Y] create it (mkdir -p) / [N] enter a different path` confirm
step when the user types a path that doesn't exist, so bad config
never reaches disk. Spawn-time path deliberately does not
auto-mkdir — by then the user may not remember writing the
config. (#362, PR #379)
- fix(readme): website URLs corrected from `/reasonix/` to
`/DeepSeek-Reasonix/`. (PR #375)
**Chores:**
- chore(issue-template): bug template now asks for shell + terminal,
and the model-id examples track the current DeepSeek model
lineup. (PR #378)
## [0.30.2] — 2026-05-07
**Headline:** five user-visible polish items from the @dacec354 triage
batch. The streaming reply now carries a live `42 t/s` throughput pill
(plus a `1.2k tok · 42 t/s` summary on settled), and `ctrl-o` toggles a
full-tail view so a long plan / todo can be read while it's still
being written. The auto-mode undo banner gains a `space`-to-pause
keybind for users who want a beat to think before the 5-second window
expires. SessionPicker and the dashboard's session-cost displays both
respect the user's wallet currency now — USD wallets see `$0.05`, CNY
wallets see `¥0.36` end-to-end. And a long-standing scrollback bug
that left the "reasoning…" spinner spinning forever after reasoning
ended is fixed.
**Features:**
- feat(ui): live `42 t/s` pill on the streaming reply card; settled
card shows `1.2k tok · 42 t/s` summary. Computed via the bundled
DeepSeek tokenizer; gated below 4 tokens / 500 ms so the first
chunk doesn't print bogus rates. Re-renders ride the slow tick so
the rate keeps updating during chunk silence. (#334, PR #356)
- feat(ui): `space` toggles pause / resume on the auto-mode 5-second
undo countdown. While paused the bar freezes at the captured
fraction, the badge swaps to `Ns · paused`, and pressing `space`
again resumes from where it stopped. The `u` and `space` keybinds
share the same modal-and-prompt-empty gating. (#337, PR #356)
- feat(ui): `ctrl-o` toggles "expanded" mode on the live streaming
card. Expanded shows up to 60 visual lines (capped so the card
can't swallow the whole viewport) plus a `⋯ N earlier lines above`
hint when content overflows. Auto-resets to collapsed at turn end.
A `expanded ⌃o` / `preview ⌃o` pill in the card header advertises
the keybind. (#335, #337, PR #359)
**Bug fixes:**
- fix(ui): `splitCardStream` only treated the LAST card as live,
committing every earlier card to Ink's `<Static>`. When the model
streamed reasoning then content (or kicked off a tool card), the
reasoning card was no longer last — it got frozen into `<Static>`
while still `streaming: true`. `<Static>` doesn't re-render frozen
items, so when `reasoning.end` later set `streaming: false`, the
spinner kept spinning forever. The split now scans for the first
unsettled card and keeps everything from that index onward live;
a card only commits to `<Static>` once it's settled AND every
earlier card is too. (PR #358)
- fix(ui): SessionPicker hardcoded `¥` and ran USD → CNY itself, so
USD-wallet users saw `¥X.XX` in the session list. `SessionMeta`
gains `balanceCurrency`; App.tsx writes the live wallet currency
alongside `totalCostUsd` on each turn save. Picker accepts a
`walletCurrency` prop and falls back to each row's stored
currency. Cost rendering routes through the shared `formatCost()`
helper. (#312, PR #357)
- fix(dashboard): cost displays were hardcoded to `$` via `fmtUsd()`,
so a CNY-wallet user saw `session $0.5190` in the dashboard while
the same session read `¥0.024` in the CLI — both the symbol AND
the magnitude diverged because no conversion happened. Dashboard
now has its own `fmtCost(usd, currency)` mirroring the CLI's
conversion (CNY × 7.2). Overview current-session cost, cost-trend
day average, and the chat panel rail / status-bar costs all
thread the wallet currency from the cockpit balance. Claude-
equivalent comparisons in `usage.ts` stay USD by design — Claude's
API is USD-priced regardless of the user's wallet. (PR #360)
## [0.30.1] — 2026-05-07
**Headline:** two TUI ghost-rendering fixes for issues that only showed
up on the published binary. The CLI bundle now uses real Ink in
production instead of the cell-diff renderer that source mode never
exercised, eliminating a whole class of bugs invisible to `npx tsx`
repros. The `submit_plan` approval picker no longer leaves a
duplicated row behind when arrow-navigating choices — the live tool
card above the modal is suppressed while the picker owns the screen.
**Bug fixes:**
- fix(renderer): drop the `tsup` `ink → ink-compat` alias and the
`noExternal` for `ink` / `ink-text-input`. The CLI bundle keeps
`from "ink"` external; `ink` and `ink-text-input` move to runtime
`dependencies` so npm install pulls the real package. The
cell-diff renderer is no longer on the user-facing path; it's
retained only for direct test imports. Same behavior as `npx tsx
src/cli/index.ts` mode — TUI bug repros from source mode are now
valid for the published binary again. (#346, PR #354)
- fix(ui): `CardStream` accepts a `suppressLive` flag; `App.tsx`
computes a `modalOpen` flag from the union of pending modal states
and passes it through. While any picker / confirm modal owns the
screen, the unsettled live tool card above it stops repainting,
removing the rerender competition that left stale rows during
arrow-key navigation. (#352, PR #353 — thanks @ctharvey)
## [0.30.0] — 2026-05-06
**Headline:** slash commands grow first-class aliases, and the
cell-diff renderer hardens column targeting against per-cell width
miscounts. `/quit` and `/q` now resolve to `/exit` from a single
declaration on the spec instead of ad-hoc handler mirrors; `/?` →
`/help`, `/reset` → `/new`, `/lang` → `/language` follow the same
path. The renderer's `moveTo()` now uses CHA absolute (`\x1b[N+1G`)
for column targeting instead of CUF relative (`\x1b[NC`), making the
diff stream immune to the cursor-drift class of bug Anthropic
documented in `claude-code#14208`.
**Features:**
- feat(slash): `aliases?: readonly string[]` on `SlashCommandSpec`.
Adding a new alias is now a one-line edit to the canonical command
— dispatch, autocomplete, arg-context resolution, and the
dashboard `/api/slash` response all route through one
`resolveSlashAlias()` map built from `SLASH_COMMANDS` at module
init. Suggestion rows display aliases dimly (` · /quit /q`) so
they stay discoverable without doubling the autocomplete list.
Removes the per-handler alias mirrors that used to live in
`handlers/basic.ts` and `handlers/language.ts`. (#332, PR #347)
**Bug fixes:**
- fix(renderer): switch the X-axis branch of `moveTo()` from CUF
relative (`\x1b[NC`) to CHA absolute (`\x1b[N+1G`). Y-axis stays
on CUU/CUD since we don't track absolute terminal rows. Relative
column moves accumulate drift across frames whenever an earlier
write miscounts cell width — `▸` (U+25B8) rendered 2-cell on
fonts with East Asian fallback, ambiguous-width chars on
terminals that font-detect width, OSC8 hyperlinks parsed as
visible chars, etc. The next CUF lands at the wrong column,
ghost rows leak into adjacent hint lines, and the modal "shifts"
as users navigate. CHA targets the absolute column regardless of
what the terminal thinks — immune to the desync chain. Same fix
Anthropic shipped in claude-code per their issue #14208
post-mortem. (#346, PR #348)
## [0.29.1] — 2026-05-06
**Headline:** four user-reported bugs from the 0.29.0 release window.
The markdown renderer no longer turns English abbreviations like
`e.g.` into broken hyperlinks (which on cmd.exe / non-OSC-8 terminals
showed up as visible `]8;;file://e.g…` garbage and on the cell-diff
side desynced the renderer's prev-frame model). The cell-diff
renderer now defensively trail-clears any row whose content shrank
between frames. Resumed sessions keep their cumulative session cost
instead of resetting to `$0`. The Approve plan modal now shows the
plan body inline when the model didn't supply structured steps.
Wide markdown tables fall back to row-grouped key/value lines
instead of the previous column-grouped output.
**Bug fixes:**
- fix(markdown): stop linkifying English abbreviations + drop OSC 8
escape emission. The `FILE_REF_RE` extension class was too loose
(`{1,6}`), so `e.g`, `i.e`, `a.m` matched as file paths; `osc8()`
baked OSC 8 escape bytes into Text content, which the cell-diff
renderer's wrapLine stripped of zero-width chars but kept the
printable body — producing visible `]8;;file://e.ge.g]8;;` garbage
on every terminal. Tightened the regex (now requires path-shape,
line-number suffix, or extension >= 2 chars) and removed the OSC 8
escape — file refs still stand out via color + underline. (#330,
PR #341)
- fix(renderer): trail-clear rows that shrank between frames in the
cell-diff diff. The diff skipped cells where prev and next were
byte-equal (including trailing EMPTY cells), so any earlier ANSI
desync left stale chars in shrunken rows — manifested as the
shell-confirm modal showing `allow always` + `mand, ask again next
time` after Up/Down navigation. New `clearToEOL` patch type and a
per-row sweep after `diffEach`. (#330, PR #341)
- fix(stats): carry session cost / turn count across resume. The
TUI's `$X session` figure reset to `$0` on every resume even
though the disk meta still held the cumulative `totalCostUsd`.
`SessionStats` gains `seedCarryover()`; `CacheFirstLoop` reads the
meta on resume and seeds the carryover when prior messages exist.
(#333, PR #342)
- fix(plan): show the plan body in the Approve plan modal. When the
model called `submit_plan` with a markdown body but no structured
`steps`, the modal showed only the choice list — users had no way
to see what they were approving without scrolling back. The modal
now renders the body via `MarkdownView`, capped at 24 lines with
an overflow hint. (#336, PR #343)
- fix(markdown): row-group the table fallback layout. When a table
was too wide for the viewport, the fallback flattened it as N
"Component:" lines, then N "What:" lines, then N "Manual TCs:"
lines — the reader couldn't tell which value belonged to which
row. Swapped to row-first iteration with a blank separator
between rows. (#340, PR #344)
## [0.29.0] — 2026-05-06
**Headline:** tool dispatch is no longer strictly serial. When the model
emits multiple `parallelSafe`-annotated tool calls in one turn (multiple
`read_file`, multiple `spawn_subagent`, etc.), the loop now races them
together via `Promise.allSettled`; a non-`parallelSafe` call ends the
chunk and runs alone, so read-after-write ordering still holds. Tool
yields and history append still land in declared order regardless of
which call settles first — the model and UI see the same shape they
would under serial dispatch. The TUI's `SubagentRow` becomes
`SubagentLiveStack`, rendering 1 → rich card, 2..max → compact rows,
> max → "+N more running…" fold. Closes umbrella #325.
**Tool dispatch:**
- feat(tools): `ToolDefinition.parallelSafe?: boolean` — opt-in
annotation, default `false`. `ToolRegistry.isParallelSafe(name)` for
the dispatcher to query; unknown / unannotated tools resolve to
`false` so third-party MCP tools must explicitly opt in. Built-in
read-only filesystem (`read_file`, `list_directory`,
`directory_tree`, `search_files`, `search_content`,
`get_file_info`), web (`web_search`, `web_fetch`), `recall_memory`,
`semantic_search`, isolated child loops (`run_skill`,
`spawn_subagent`), and in-memory job queries (`job_output`,
`list_jobs`) are annotated. Mutating tools stay default. (PR #326)
- feat(loop): chunked parallel tool dispatch. Replaces `for...of +
await` in the dispatch loop with a chunking loop that groups
consecutive `parallelSafe` calls and races them; unsafe calls form
serial barriers. `runOneToolCall` extracts per-call lifecycle
(PreToolUse + dispatch + PostToolUse) so the chunk can fan out via
`Promise.allSettled` while the loop body keeps yielding events in
declared order. Two new env knobs: `REASONIX_PARALLEL_MAX` (chunk
size cap, default 3, hard max 16) and `REASONIX_TOOL_DISPATCH=serial`
(escape hatch). Tests cover parallel timing, serial barrier on mixed
safe/unsafe, declared-order yields under racey completion, and both
env-knob overrides. (PR #327)
**TUI:**
- feat(ui): `SubagentEvent` carries a stable `runId` per spawn so the
sink can key concurrent runs apart instead of overwriting one shared
row. `useSubagent` keeps an array of in-flight activities;
`SubagentLiveStack` renders 1 → rich card (unchanged), 2..max →
compact rows with per-row spinner + iter + last tool, > max →
compact rows + "+N more running…" fold. (PR #327)
**Docs:**
- docs(architecture): `docs/ARCHITECTURE.md` Pillar 1 gains a
"Parallel tool dispatch" section explaining the chunking rule, both
env knobs, and the list of built-in tools that opt in. (PR #328)
## [0.28.0] — 2026-05-06
**Headline:** subagent capability sharpened on three axes — skills can
now scope a child to a specific tool subset via `allowed-tools`
frontmatter, callers can request a per-spawn iter budget via the new
`max_iters` arg (clamped 1-32), and two built-in personas (`explore`,
`verify`) are selectable inline via a `type` arg without writing a
skill. Closes umbrella #316.
**Subagent:**
- feat(subagent): honor skill `allowed-tools` frontmatter when forking
the child registry. The field was parsed but ignored ("Unused in v1");
now it scopes the subagent to the named tools only. New
`forkRegistryWithAllowList` helper alongside `forkRegistryExcluding`;
`NEVER_INHERITED` (`spawn_subagent` / `submit_plan`) still wins so
depth=1 + plan-mode guarantees hold even if a skill names them. An
allow-list naming a tool the parent doesn't have returns a structured
error result (no API call burned). (#317, PR #320)
- feat(subagent): expose `max_iters` on the `spawn_subagent` tool
schema. Clamped to 1-32 at the boundary; floats round down; non-numeric
/ missing falls back to the registration-time default (still 16).
Verify-style tasks can ask for 6-8, explore-style can ask for 24+.
(#318, PR #321)
- feat(subagent): two built-in personas selectable via `type` arg —
`explore` (wide-net read-only investigation, 20-iter budget) and
`verify` (narrow yes/no with evidence, 8-iter budget). Caller's
explicit `system` / `max_iters` override the type's defaults. Prompts
live in new `src/tools/subagent-types.ts` so `subagent.ts` stays
under the 500-line target. (#319, PR #322)
## [0.27.3] — 2026-05-06
**Headline:** USD-account users now see `$` instead of `¥` everywhere
money is shown in the TUI — wallet balance, turn cost, session cost,
top-bar cost label, subagent end-event cost suffix, and the UsageCard
header / body / wallet line. Pre-fix a USD wallet rendered
`¥0.0352 turn · ¥0.461 session · wallet ¥0.91`; now it renders
`$0.0308 turn · $0.064 session · wallet $0.91`. The display follows
the wallet currency reported by the DeepSeek API (`currency: "USD"|"CNY"`),
not the UI language — a CNY account on an English UI still sees `¥`,
and vice versa. Originally reported in #278 by @Explosion-Scratch.
**UI / currency:**
- fix(ui): USD wallets render `$` for wallet balance, turn cost, and
session cost. State + event schemas now carry `balanceCurrency`
through `App.tsx → reducer → StatusBar` so every render site sees
the wallet symbol the API reported. Originally drafted by @wviana
in #272; the TUI plumbing through state.ts / cards.ts / events.ts /
reducer.ts / useScrollback.ts / slash/types.ts was the bulk of the
fix.
- fix(ui): balance color threshold checks USD against the CNY scale
(`$0.91 ≈ ¥6.55`) rather than treating `0.91` as `< ¥5 → red`. USD
wallets now correctly show yellow at low-but-not-empty balances.
- fix(ui): `StatsPanel.ChromeRow` cost label and `useSubagent`
end-event cost suffix follow the wallet currency too — pre-fix
these always rendered `$`. (#313)
- refactor(ui): seven currency helpers in `theme/tokens.ts`
(`formatCNY` / `formatBalance` / `formatBalanceLabel` /
`formatWalletDisplay` / `formatCost` / `balanceColorCny` /
`balanceColorForBalance`) collapsed to three: `formatBalance`,
`formatCost`, `balanceColor`. Undefined currency defaults to CNY
(matches pre-fix unconditional `¥`) so the transient first-turn
case where balance arrived but currency hasn't is consistent.
- chore(ui): remove orphan `ChromeBar.tsx` (258 lines). `App.tsx`
mounts `StatsPanel`'s diverged `ChromeRow`, which is the bar users
actually see. The two formatter helpers ChromeBar once owned now
live in `theme/tokens.ts`. (#314)
**Loop:**
- refactor(loop): `loop.ts` 1331 → 1219 (−112). Three sibling files
under `src/loop/`: `messages.ts` (pure ChatMessage builders),
`turn-failure-tracker.ts` (per-turn failure count + threshold
tipping), `force-summary.ts` (forced-summary generator behind a
small DI context). Continues the #308 / #309 cadence — small
per-helper extractions, no behavior change. (#311)
**Known follow-up:** `SessionPicker` still hardcodes `¥` for
per-session cost in the session-history list, tracked in #312
(good-first-issue).
## [0.25.1] — 2026-05-05
**Headline:** `run_command` learns the four common shell chain
operators (`|`, `||`, `&&`, `;`) and the seven file redirect
operators (`>`, `>>`, `<`, `2>`, `2>>`, `2>&1`, `&>`). Parsed and
spawned natively — no shell is invoked, so semantics are identical
on Windows / macOS / Linux; PowerShell 5.1's `&&` parse error and
the object-vs-bytes pipe gap are sidestepped. Each chain segment is
allowlist-checked independently, so `git status | grep main` now
auto-runs when both halves are individually allowed. Driven by
discussion #231.
**Shell:**
- feat(shell): support `|`, `||`, `&&`, `;` chain operators in
`run_command` via split-and-spawn. The chain is segmented at
whitespace-bounded operators (preserves embedded `&` / `|` inside
arg values like `--flag=1&2`), each segment runs through the
existing lenient tokenizer, and segments are executed with proper
short-circuit semantics for `&&` / `||`. Each segment hits the
allowlist independently — `git status | grep main` runs when both
halves are allowed individually. (#233, #234)
- feat(shell): support file redirects in `run_command` — `>` (truncate),
`>>` (append), `<` (stdin from file), `2>` (stderr truncate), `2>>`
(stderr append), `2>&1` (merge stderr into wherever stdout points),
`&>` (both → file). Targets resolve relative to the project root.
Mid-pipe `2>&1` correctly merges stderr into the next segment's
stdin without truncating on stdout-end. (#235)
- fix(shell): chain parser stays consistent with the project's
long-standing lenient tokenizer — `cargo run -- --flag=1&2` and
similar embedded-operator args stay literal instead of getting
POSIX-strict-rejected. shell-quote dependency dropped;
`splitOnChainOps` is whitespace-bounded like the existing
`detectShellOperator`. (#234)
## [0.24.1] — 2026-05-04
**Headline:** Two TUI fixes on top of the 0.24.0 cell-diff renderer.
+184 -73
View File
@@ -1,123 +1,234 @@
<p align="center">
<img src="docs/logo.svg" alt="Reasonix — DeepSeek-native agent framework" width="640"/>
<img src="docs/logo.svg" alt="Reasonix" width="640"/>
</p>
<p align="center">
<strong>English</strong> · <a href="./README.zh-CN.md">简体中文</a> · <a href="https://esengine.github.io/reasonix/">Website</a>
<strong>English</strong>
&nbsp;·&nbsp;
<a href="./README.zh-CN.md">简体中文</a>
&nbsp;·&nbsp;
<a href="https://esengine.github.io/DeepSeek-Reasonix/">Website</a>
&nbsp;·&nbsp;
<a href="./docs/ARCHITECTURE.md">Architecture</a>
&nbsp;·&nbsp;
<a href="./benchmarks/">Benchmarks</a>
</p>
<p align="center">
<a href="https://www.npmjs.com/package/reasonix"><img src="https://img.shields.io/npm/v/reasonix.svg" alt="npm version"/></a>
<a href="https://github.com/esengine/reasonix/actions/workflows/ci.yml"><img src="https://github.com/esengine/reasonix/actions/workflows/ci.yml/badge.svg" alt="CI"/></a>
<a href="./LICENSE"><img src="https://img.shields.io/npm/l/reasonix.svg" alt="license"/></a>
<a href="https://www.npmjs.com/package/reasonix"><img src="https://img.shields.io/npm/dm/reasonix.svg" alt="downloads"/></a>
<a href="./package.json"><img src="https://img.shields.io/node/v/reasonix.svg" alt="node"/></a>
<a href="https://github.com/esengine/reasonix/stargazers"><img src="https://img.shields.io/github/stars/esengine/reasonix.svg?style=flat&logo=github&label=stars" alt="GitHub stars"/></a>
<a href="https://github.com/esengine/reasonix/discussions"><img src="https://img.shields.io/github/discussions/esengine/reasonix.svg?logo=github&label=discussions" alt="Discussions"/></a>
<a href="https://www.npmjs.com/package/reasonix"><img src="https://img.shields.io/npm/v/reasonix.svg?style=flat-square&color=0d1117&labelColor=161b22" alt="npm version"/></a>
<a href="https://github.com/esengine/reasonix/actions/workflows/ci.yml"><img src="https://img.shields.io/github/actions/workflow/status/esengine/reasonix/ci.yml?style=flat-square&label=ci&color=0d1117&labelColor=161b22" alt="CI"/></a>
<a href="./LICENSE"><img src="https://img.shields.io/npm/l/reasonix.svg?style=flat-square&color=0d1117&labelColor=161b22" alt="license"/></a>
<a href="https://www.npmjs.com/package/reasonix"><img src="https://img.shields.io/npm/dm/reasonix.svg?style=flat-square&color=0d1117&labelColor=161b22" alt="downloads"/></a>
<a href="./package.json"><img src="https://img.shields.io/node/v/reasonix.svg?style=flat-square&color=0d1117&labelColor=161b22" alt="node"/></a>
<a href="https://github.com/esengine/reasonix/stargazers"><img src="https://img.shields.io/github/stars/esengine/reasonix.svg?style=flat-square&color=0d1117&labelColor=161b22&logo=github" alt="GitHub stars"/></a>
<a href="https://github.com/esengine/reasonix/graphs/contributors"><img src="https://img.shields.io/github/contributors/esengine/reasonix.svg?style=flat-square&color=0d1117&labelColor=161b22&logo=github" alt="contributors"/></a>
<a href="https://github.com/esengine/reasonix/discussions"><img src="https://img.shields.io/github/discussions/esengine/reasonix.svg?style=flat-square&color=0d1117&labelColor=161b22&logo=github" alt="Discussions"/></a>
</p>
<br/>
<h3 align="center">A DeepSeek-native AI coding agent for your terminal.</h3>
<p align="center">Engineered around prefix-cache stability — so token costs stay low across long sessions, and you can leave it running.</p>
<br/>
<p align="center">
<strong>A DeepSeek-native AI coding agent for your terminal.</strong> Engineered around DeepSeek's prefix-cache, so the savings are real and the loop stays cheap enough to leave on.
<img src="docs/assets/hero-terminal.svg" alt="Reasonix code mode — assistant proposes a SEARCH/REPLACE edit; nothing on disk until /apply" width="860"/>
</p>
<p align="center">
<img src="docs/assets/hero-stats.svg" alt="94% live prefix-cache hit · ~30× cheaper per task vs Claude Code · MIT terminal-native" width="860"/>
</p>
<br/>
---
> [!TIP]
> **Cache stability isn't a feature you turn on; it's an invariant the loop is designed around.** That's the whole reason Reasonix is DeepSeek-only — every layer is tuned to the byte-stable prefix-cache mechanic.
## Quick start
> [!NOTE]
> **Real user, single day (2026-05-01):** 435M input tokens, **99.82% cache hit**, ~$12 instead of the ~$61 the same workload would cost with no cache on `v4-flash` — see the [case study](./benchmarks/real-world-cache/README.md). DeepSeek provides the cacheable bytes; the four mechanisms in [Pillar 1](./docs/ARCHITECTURE.md#pillar-1--cache-first-loop) are how Reasonix keeps them cacheable across long sessions.
<br/>
## Web search
Reasonix includes `web_search` and `web_fetch` tools. By default it uses **Mojeek** (no setup required). You can switch to a **self-hosted SearXNG** instance — a metasearch engine that aggregates whatever upstream engines your instance is configured for.
### Switching engines (persists to disk)
The `/search-engine` slash command (alias `/se`) writes your choice to `~/.reasonix/config.json` immediately — it survives restarts:
```
/search-engine mojeek # default, no external deps
/search-engine searxng # SearXNG at http://localhost:8080
/search-engine searxng http://192.168.1.100:8888 # custom endpoint
```
Equivalent `~/.reasonix/config.json`:
```json
{
"webSearchEngine": "searxng",
"webSearchEndpoint": "http://localhost:8080"
}
```
The tool picks up the change on the next call — no restart needed.
### Starting SearXNG
```sh
podman run -d --replace --name searxng -p 8080:8080 docker.io/searxng/searxng
# or: docker run -d -p 8080:8080 searxng/searxng
```
Verify it's running:
```sh
curl http://localhost:8080/search?q=test
# → HTML search results page
```
> **Note:** The endpoint must include the protocol (`http://`). `localhost:8080` alone will fail — the tool will show a clear error telling you to install SearXNG if the server is unreachable.
<br/>
## Install
```bash
cd my-project
npx reasonix code # paste a DeepSeek API key on first run; persists after
```
Requires Node ≥ 22. Tested on macOS · Linux · Windows (PowerShell · Git Bash · Windows Terminal). Get a [DeepSeek API key →](https://platform.deepseek.com/api_keys) · `reasonix code --help` for flags.
**Working in a different folder:** Reasonix scopes filesystem tools to the launch directory. To work elsewhere, pass `--dir`:
```bash
npx reasonix code --dir /path/to/project # or use a relative path
```
Mid-session switching isn't supported by design (the message log + memory paths get tangled with stale roots). Quit and relaunch with a new `--dir` to retarget. `/status` always shows the current pinned workspace.
**Author your first skill:** Skills are markdown playbooks the model can invoke (`/skill <name>`). There's no remote registry yet — you author them directly:
```bash
/skill new my-skill # scaffolds <project>/.reasonix/skills/my-skill.md
/skill new my-skill --global # or under ~/.reasonix/skills for cross-project use
```
Edit the file (`description:` frontmatter + body), then `/skill list` to see it. Add `runAs: subagent` to the frontmatter to spawn an isolated subagent loop instead of inlining the body.
<br/>
## What makes Reasonix different
The loop is organized around four pillars. Each one solves a problem generic agent frameworks don't even see — because they were designed for a different cache mechanic.
<p align="center">
<img src="docs/assets/hero-terminal.svg" alt="Reasonix code mode — assistant proposes a SEARCH/REPLACE edit; nothing on disk until /apply" width="860"/>
<a href="./docs/ARCHITECTURE.md"><img src="docs/assets/pillars.svg" alt="Reasonix four pillars — Cache-first loop, R1 thought harvesting, Tool-call repair, Cost control" width="880"/></a>
</p>
Requires Node ≥ 22. Tested on macOS, Linux, and Windows (PowerShell, Git Bash, Windows Terminal). Get a [DeepSeek API key →](https://platform.deepseek.com/api_keys) · `reasonix code --help` for flags.
<sub align="center">
---
Click any card to read the full architecture writeup → [Pillar 1](./docs/ARCHITECTURE.md#pillar-1--cache-first-loop) · [Pillar 2](./docs/ARCHITECTURE.md#pillar-2--r1-thought-harvesting-opt-in) · [Pillar 3](./docs/ARCHITECTURE.md#pillar-3--tool-call-repair) · [Pillar 4](./docs/ARCHITECTURE.md#pillar-4--cost-control-v06)
</sub>
<br/>
## Capabilities
<p align="center">
<img src="docs/assets/feature-grid.svg" alt="Reasonix capabilities — cell-diff renderer, MCP, plan mode, permissions, dashboard, persistent sessions, hooks/skills/memory, semantic search, auto-checkpoints, /effort knob, transcript replay, event log" width="880"/>
</p>
<br/>
## How it compares
| | Reasonix | Claude Code | Cursor | Aider |
|-----------------------------------|------------------|-----------------|--------------------|------------------|
| Backend | DeepSeek V4 | Anthropic | OpenAI / Anthropic | any (OpenRouter) |
| **Cost / typical task** | **~¥0.01–0.04** | ~¥0.40–4 | ¥150/mo + usage | varies |
| License | **MIT** | closed | closed | Apache 2 |
| **DeepSeek prefix-cache hit** | **94%** (live) | n/a | n/a | ~33% (baseline) |
| Embedded web dashboard | yes | — | n/a (IDE) | — |
| Persistent per-workspace sessions | yes | partial | n/a | — |
| | Reasonix | Claude Code | Cursor | Aider |
|-----------------------------------|------------------|-------------------|---------------------|--------------------|
| Backend | DeepSeek | Anthropic | OpenAI / Anthropic | any (OpenRouter) |
| License | **MIT** | closed | closed | Apache 2 |
| Cost profile | **low per task** | premium | subscription + use | varies |
| DeepSeek prefix-cache | **engineered** | not applicable | not applicable | incidental |
| Embedded web dashboard | yes | — | n/a (IDE) | — |
| Configurable web search engine | `/search-engine` | — | — | — |
| Persistent per-workspace sessions | yes | partial | n/a | — |
| Plan mode · MCP · hooks · skills | yes | yes | yes | partial |
| Web search (Mojeek + SearXNG) | yes | yes | yes | yes |
| Open community development | yes | — | — | yes |
Plan mode, edit review, MCP, skills, hooks, and sandboxing are all `yes` for Reasonix and most peers — see the feature grid below for what they actually do here.
For live cache-hit rates, costs, and methodology, see [`benchmarks/`](./benchmarks/) — the numbers move with model pricing, so they live with the harness, not in the README.
Numbers from `benchmarks/tau-bench-lite` (8 multi-turn tasks × 3 repeats, live `deepseek-chat`). [Committed transcripts →](./benchmarks/)
<br/>
<details>
<summary><strong>Why DeepSeek-only? — the cache economics</strong></summary>
## Documentation
Cheap tokens alone is half the story. DeepSeek's prefix-cache is **byte-stable**: the cache fingerprints from byte 0 of the prompt. Reasonix's loop is engineered around that — append-only growth, no re-ordering, no marker-based compaction — so the cache prefix survives every tool call.
- [**Architecture**](./docs/ARCHITECTURE.md) — the four pillars, cache-first loop, harvesting, scaffolds
- [**Benchmarks**](./benchmarks/) — τ-bench-lite harness, transcripts, cost methodology
- [**Website**](https://esengine.github.io/DeepSeek-Reasonix/) — getting started, dashboard mockup, TUI mockup
- [**Contributing**](./CONTRIBUTING.md) — comment policy, error-handling rules, library-over-hand-rolled
- [**Code of Conduct**](./CODE_OF_CONDUCT.md) · [**Security policy**](./SECURITY.md)
By comparison, Claude Code is built around Anthropic's `cache_control` markers (a fundamentally different mechanic). Pointing it at DeepSeek's Anthropic-compat endpoint keeps the cheap tokens but loses the cache hits — markers are ignored, and the underlying prefix isn't byte-stable. Generic-backend tools (Aider / Cline / Continue) hit the same wall from the other direction: their compaction patterns destroy byte stability.
<br/>
At DeepSeek's pricing — $0.07/Mtok uncached, $0.014/Mtok cached — **the difference between 50% and 94% hit is roughly 2.5× on input cost alone.** Same model, same API; the loop's invariants are what changed.
## Community
A few DeepSeek-specific fixes generic loops miss:
> [!NOTE]
> Reasonix is open source and community-developed. The contributors wall below isn't decoration — every avatar is a real PR that shipped.
| Generic loops assume | DeepSeek actually does | Reasonix's fix |
|---|---|---|
| Reasoning emitted as a structured `thinking` block | R1 sometimes leaks tool-call JSON inside `<think>` tags | a `scavenge` pass that pulls escaped tool calls back out |
| Tool schemas validated strictly | DeepSeek silently drops deeply-nested object/array params | auto-flatten — nested params get rewritten to single-level prefixed names |
| Tool-call args are well-formed JSON | DeepSeek occasionally produces `string="false"` and other malformed fragments | dedicated `ToolCallRepair` heals the common shapes before dispatch |
| Reasoning depth tuned via system-level switches | V4 exposes a `reasoning_effort` knob (`max` / `high`) | `/effort` slash + `--effort` flag for cheap turns |
Scoped starter tickets — each with background, code pointers, acceptance criteria, and hints — live under the [`good first issue`](https://github.com/esengine/reasonix/labels/good%20first%20issue) label. Pick anything open.
Cache stability isn't a feature you turn on; it's an invariant the loop is designed around. That's the entire reason Reasonix is DeepSeek-only.
**Open Discussions — opinions wanted:**
</details>
---
## What's in the box
<p align="center">
<img src="docs/assets/feature-grid.svg" alt="Feature grid — cache-first loop, plan mode, MCP first-class, sessions and dashboard, hooks, memory and skills" width="860"/>
</p>
Permissions (`allow` / `ask` / `deny`), tool-call repair (flatten · scavenge · truncation · storm), and `/effort` for cheap turns round out the loop. [Architecture →](./docs/ARCHITECTURE.md) · [Dashboard mockup →](https://esengine.github.io/reasonix/design/agent-dashboard.html) · [TUI mockup →](https://esengine.github.io/reasonix/design/agent-tui-terminal.html) · [Website →](https://esengine.github.io/reasonix/)
---
## Contributing
Reasonix is solo-maintained but designed to grow. Scoped starter tickets — each with background, code pointers, acceptance criteria, and hints — live under the [`good first issue`](https://github.com/esengine/reasonix/labels/good%20first%20issue) label. Pick anything open.
**Open Discussions** — opinions wanted:
- [#20 · CLI / TUI design](https://github.com/esengine/reasonix/discussions/20) — what's broken, what's missing, what would you change?
- [#21 · Dashboard design](https://github.com/esengine/reasonix/discussions/21) — react against the [proposed mockup](https://esengine.github.io/reasonix/design/agent-dashboard.html)
- [#21 · Dashboard design](https://github.com/esengine/reasonix/discussions/21) — react against the [proposed mockup](https://esengine.github.io/DeepSeek-Reasonix/design/agent-dashboard.html)
- [#22 · Future feature wishlist](https://github.com/esengine/reasonix/discussions/22) — what would you build into Reasonix next?
**Before your first PR**: read [`CONTRIBUTING.md`](./CONTRIBUTING.md) — short, strict project rules (comments, errors, libraries-over-hand-rolled). `tests/comment-policy.test.ts` enforces the comment ones; `npm run verify` is the pre-push gate. By participating you agree to the [Code of Conduct](./CODE_OF_CONDUCT.md). Security issues → [SECURITY.md](./SECURITY.md).
**Already using Reasonix and willing to help others discover it?** Publish blog posts, articles, screenshots, talks, or videos to [**Show and tell**](https://github.com/esengine/reasonix/discussions/categories/show-and-tell). The project has no marketing budget — community word of mouth is how new users find it. Sustained advocates earn the badge below, displayed next to the contributors wall once awarded:
### Contributors
<p align="center">
<a href="https://github.com/esengine/reasonix/discussions/categories/show-and-tell">
<img src="https://img.shields.io/badge/REASONIX-📣%20ADVOCATE-c4b5fd?style=for-the-badge&labelColor=0d1117" alt="Reasonix Advocate badge — earned by sustained advocates"/>
</a>
</p>
<a href="https://github.com/esengine/reasonix/graphs/contributors">
<img src="https://contrib.rocks/image?repo=esengine/reasonix" alt="Contributors to esengine/reasonix"/>
</a>
**Before your first PR**: read [`CONTRIBUTING.md`](./CONTRIBUTING.md) — short, strict rules (comments, errors, libraries-over-hand-rolled). `tests/comment-policy.test.ts` enforces the comment ones; `npm run verify` is the pre-push gate. By participating you agree to the [Code of Conduct](./CODE_OF_CONDUCT.md). Security issues → [SECURITY.md](./SECURITY.md).
---
<p align="center">
<a href="https://github.com/esengine/reasonix/graphs/contributors">
<img src="https://contrib.rocks/image?repo=esengine/reasonix&max=100&columns=12" alt="Contributors to esengine/reasonix" width="860"/>
</a>
</p>
<br/>
## Non-goals
- **Multi-provider flexibility.** DeepSeek-only on purpose — every layer is tuned around DeepSeek's specific cache mechanic and pricing. Coupling to one backend is the feature.
- **IDE integration.** Terminal-first; the diff lives in `git diff`, the file tree in `ls`. The dashboard is a companion, not a Cursor replacement.
- **Hardest-leaderboard reasoning.** Claude Opus still wins some benchmarks. DeepSeek V4 is competitive on coding; if your work is "solve this PhD proof" rather than "fix this auth bug," start with Claude.
> [!IMPORTANT]
> Reasonix is opinionated. Some things it deliberately *doesn't* do — listed here so you can pick the right tool for your work.
- **Multi-provider flexibility.** DeepSeek-only on purpose. Coupling to one backend is the feature, not a limitation.
- **IDE integration.** Terminal-first. The diff lives in `git diff`, the file tree in `ls`. The dashboard is a companion, not a Cursor replacement.
- **Hardest-leaderboard reasoning.** Claude Opus still wins some benchmarks. DeepSeek is competitive on coding; if your work is "solve this PhD proof" rather than "fix this auth bug," start with Claude.
- **Air-gapped / fully-free.** Reasonix needs a paid DeepSeek API key. For air-gapped or zero-cost runs see Aider + Ollama or [Continue](https://continue.dev).
<br/>
## Star History
<a href="https://www.star-history.com/?repos=esengine%2Freasonix&type=timeline&logscale=&legend=top-left">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/chart?repos=esengine/reasonix&type=timeline&theme=dark&logscale&legend=top-left" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/chart?repos=esengine/reasonix&type=timeline&logscale&legend=top-left" />
<img alt="Star History Chart" src="https://api.star-history.com/chart?repos=esengine/reasonix&type=timeline&logscale&legend=top-left" />
</picture>
</a>
<br/>
---
## License
MIT — see [LICENSE](./LICENSE).
<p align="center">
<sub>MIT — see <a href="./LICENSE">LICENSE</a></sub>
<br/>
<sub>Built by the community at <a href="https://github.com/esengine/reasonix/graphs/contributors">esengine/reasonix</a></sub>
</p>
+138 -75
View File
@@ -1,123 +1,186 @@
<p align="center">
<img src="docs/logo.svg" alt="Reasonix — DeepSeek 原生的 agent 框架" width="640"/>
<img src="docs/logo.svg" alt="Reasonix" width="640"/>
</p>
<p align="center">
<a href="./README.md">English</a> · <strong>简体中文</strong> · <a href="https://esengine.github.io/reasonix/">官方网站</a>
<a href="./README.md">English</a>
&nbsp;·&nbsp;
<strong>简体中文</strong>
&nbsp;·&nbsp;
<a href="https://esengine.github.io/DeepSeek-Reasonix/">官方网站</a>
&nbsp;·&nbsp;
<a href="./docs/ARCHITECTURE.md">架构文档</a>
&nbsp;·&nbsp;
<a href="./benchmarks/">基准测试</a>
</p>
<p align="center">
<a href="https://www.npmjs.com/package/reasonix"><img src="https://img.shields.io/npm/v/reasonix.svg" alt="npm version"/></a>
<a href="https://github.com/esengine/reasonix/actions/workflows/ci.yml"><img src="https://github.com/esengine/reasonix/actions/workflows/ci.yml/badge.svg" alt="CI"/></a>
<a href="./LICENSE"><img src="https://img.shields.io/npm/l/reasonix.svg" alt="license"/></a>
<a href="https://www.npmjs.com/package/reasonix"><img src="https://img.shields.io/npm/dm/reasonix.svg" alt="downloads"/></a>
<a href="./package.json"><img src="https://img.shields.io/node/v/reasonix.svg" alt="node"/></a>
<a href="https://github.com/esengine/reasonix/stargazers"><img src="https://img.shields.io/github/stars/esengine/reasonix.svg?style=flat&logo=github&label=stars" alt="GitHub stars"/></a>
<a href="https://github.com/esengine/reasonix/discussions"><img src="https://img.shields.io/github/discussions/esengine/reasonix.svg?logo=github&label=discussions" alt="Discussions"/></a>
<a href="https://www.npmjs.com/package/reasonix"><img src="https://img.shields.io/npm/v/reasonix.svg?style=flat-square&color=0d1117&labelColor=161b22" alt="npm version"/></a>
<a href="https://github.com/esengine/reasonix/actions/workflows/ci.yml"><img src="https://img.shields.io/github/actions/workflow/status/esengine/reasonix/ci.yml?style=flat-square&label=ci&color=0d1117&labelColor=161b22" alt="CI"/></a>
<a href="./LICENSE"><img src="https://img.shields.io/npm/l/reasonix.svg?style=flat-square&color=0d1117&labelColor=161b22" alt="license"/></a>
<a href="https://www.npmjs.com/package/reasonix"><img src="https://img.shields.io/npm/dm/reasonix.svg?style=flat-square&color=0d1117&labelColor=161b22" alt="downloads"/></a>
<a href="./package.json"><img src="https://img.shields.io/node/v/reasonix.svg?style=flat-square&color=0d1117&labelColor=161b22" alt="node"/></a>
<a href="https://github.com/esengine/reasonix/stargazers"><img src="https://img.shields.io/github/stars/esengine/reasonix.svg?style=flat-square&color=0d1117&labelColor=161b22&logo=github" alt="GitHub stars"/></a>
<a href="https://github.com/esengine/reasonix/graphs/contributors"><img src="https://img.shields.io/github/contributors/esengine/reasonix.svg?style=flat-square&color=0d1117&labelColor=161b22&logo=github" alt="contributors"/></a>
<a href="https://github.com/esengine/reasonix/discussions"><img src="https://img.shields.io/github/discussions/esengine/reasonix.svg?style=flat-square&color=0d1117&labelColor=161b22&logo=github" alt="Discussions"/></a>
</p>
<br/>
<h3 align="center">DeepSeek 原生的终端 AI 编程代理。</h3>
<p align="center">围绕前缀缓存稳定性设计 —— 长会话下 token 成本始终低位运行,可以一直开着。</p>
<br/>
<p align="center">
<strong>DeepSeek 原生的终端 AI 编程代理。</strong> 围绕 DeepSeek 的前缀缓存机制打造——省钱是真省,loop 便宜到可以一直开着。
<img src="docs/assets/hero-terminal.zh-CN.svg" alt="Reasonix code 模式预览 — 助手提出 SEARCH/REPLACE 编辑,未 /apply 不落盘" width="860"/>
</p>
<p align="center">
<img src="docs/assets/hero-stats.zh-CN.svg" alt="94% 实测前缀缓存命中 · 单任务比 Claude Code 便宜 ~30 倍 · MIT 终端原生" width="860"/>
</p>
<br/>
---
> [!TIP]
> **缓存稳定不是开关,而是循环要围绕设计的不变量。** 这就是 Reasonix 只支持 DeepSeek 的根本原因 —— 每一层都为 DeepSeek 字节稳定的前缀缓存机制调过。
## 快速上手
<br/>
## 安装
```bash
cd my-project
npx reasonix code # 首次运行粘贴 DeepSeek API Key,之后会记住
```
要求 Node ≥ 22。已在 macOS · Linux · Windows(PowerShell · Git Bash · Windows Terminal)测过。[去拿 DeepSeek API Key →](https://platform.deepseek.com/api_keys) · 完整 flag 看 `reasonix code --help`。
**在其他目录工作:** Reasonix 把文件系统工具作用域绑定在启动目录。要在别的目录工作,传 `--dir`:
```bash
npx reasonix code --dir /path/to/project # 也可以用相对路径
```
中途切换工作区是有意不支持的(消息日志和 memory 路径会和旧的根目录混在一起,状态错乱)。退出后用新的 `--dir` 重新启动来切换。`/status` 始终显示当前锁定的工作区。
**写第一个 Skill:** Skills 是模型可以调用的 markdown 剧本(`/skill <name>`)。暂无在线市场 —— 自己写:
```bash
/skill new my-skill # 在 <project>/.reasonix/skills/my-skill.md 生成模板
/skill new my-skill --global # 或者放到 ~/.reasonix/skills,跨项目共用
```
编辑文件(`description:` frontmatter + 正文),然后 `/skill list` 就能看到。frontmatter 里加 `runAs: subagent` 会以独立 subagent 跑,而不是把正文内联进父 prompt。
<br/>
## Reasonix 的不同之处
整个循环围绕四根支柱组织。每一根解决的都是通用 agent 框架根本看不见的问题 —— 因为它们是为另一种缓存机制设计的。
<p align="center">
<img src="docs/assets/hero-terminal.zh-CN.svg" alt="Reasonix code 模式预览 — 助手提出 SEARCH/REPLACE 编辑,未 /apply 不落盘" width="860"/>
<a href="./docs/ARCHITECTURE.md"><img src="docs/assets/pillars.zh-CN.svg" alt="Reasonix 四大支柱 — 缓存优先循环、R1 思维提取、工具调用修复、成本控制" width="880"/></a>
</p>
要求 Node ≥ 22。已在 macOS、Linux、Windows(PowerShell · Git Bash · Windows Terminal)测过。[去拿 DeepSeek API Key →](https://platform.deepseek.com/api_keys) · 完整 flag 看 `reasonix code --help`。
<sub align="center">
---
各支柱完整说明 → [Pillar 1](./docs/ARCHITECTURE.md#pillar-1--cache-first-loop) · [Pillar 2](./docs/ARCHITECTURE.md#pillar-2--r1-thought-harvesting-opt-in) · [Pillar 3](./docs/ARCHITECTURE.md#pillar-3--tool-call-repair) · [Pillar 4](./docs/ARCHITECTURE.md#pillar-4--cost-control-v06)
</sub>
<br/>
## 能力一览
<p align="center">
<img src="docs/assets/feature-grid.zh-CN.svg" alt="Reasonix 能力一览 — cell-diff 渲染器、MCP、计划模式、权限、仪表盘、持久化会话、Hooks/Skills/Memory、语义检索、自动 checkpoint、/effort 旋钮、transcript 重放、事件日志" width="880"/>
</p>
<br/>
## 横向对比
| | Reasonix | Claude Code | Cursor | Aider |
|----------------------------|-------------------|-----------------|--------------------|-------------------|
| 后端 | DeepSeek V4 | Anthropic | OpenAI / Anthropic | 任意(OpenRouter)|
| **单任务成本** | **~¥0.01–0.04** | ~¥0.40–4 | ¥150/月 + 用量 | 不一 |
| 协议 | **MIT** | 闭源 | 闭源 | Apache 2 |
| **DeepSeek 前缀缓存命中** | **94%**(实测) | 不适用 | 不适用 | ~33%(基线) |
| 内嵌 web 仪表盘 | 支持 | — | 不适用 (IDE) | — |
| 持久化的工作区会话 | 支持 | 部分 | 不适用 | — |
| | Reasonix | Claude Code | Cursor | Aider |
|----------------------------|-------------------|-------------------|---------------------|--------------------|
| 后端 | DeepSeek | Anthropic | OpenAI / Anthropic | 任意(OpenRouter) |
| 协议 | **MIT** | 闭源 | 闭源 | Apache 2 |
| 单任务成本 | **低** | 高 | 订阅 + 用量 | 不一 |
| DeepSeek 前缀缓存 | **专门工程化** | 不适用 | 不适用 | 偶发命中 |
| 内嵌 web 仪表盘 | 支持 | — | 不适用 (IDE) | — |
| 持久化的工作区会话 | 支持 | 部分 | 不适用 | — |
| 计划模式 · MCP · Hooks | 支持 | 支持 | 支持 | 部分 |
| 开放社区共建 | 支持 | — | — | 支持 |
计划模式、编辑审查、MCP、skill、Hooks、沙箱在 Reasonix 和大多数同类里都是"支持"——具体怎么做的看下面的功能一览。
实测缓存命中率、成本、方法论看 [`benchmarks/`](./benchmarks/) —— 这些数会随模型定价变化,所以归在 harness 里,不进 README。
数据来自 `benchmarks/tau-bench-lite`(8 个多轮任务 × 3 次重放,真实 `deepseek-chat`)。[完整 transcript →](./benchmarks/)
<br/>
<details>
<summary><strong>为什么只支持 DeepSeek?— 缓存经济学</strong></summary>
## 文档
便宜的 token 只是故事的一半。DeepSeek 的前缀缓存是**字节稳定**的:缓存指纹从 prompt 第 0 字节开始算。Reasonix 整个循环都围绕这一点设计——只追加、不重排、不做基于标记的 compaction,所以缓存前缀能跨过每一次工具调用存活下来。
- [**架构**](./docs/ARCHITECTURE.md) —— 四大支柱、缓存优先循环、思维提取、脚手架
- [**基准测试**](./benchmarks/) —— τ-bench-lite harness、transcript、成本方法论
- [**官方网站**](https://esengine.github.io/DeepSeek-Reasonix/) —— 入门、Dashboard 设计稿、TUI 设计稿
- [**贡献指南**](./CONTRIBUTING.md) —— 注释规则、错误处理、用现成库不手写
- [**行为准则**](./CODE_OF_CONDUCT.md) · [**安全策略**](./SECURITY.md)
对比一下:Claude Code 是围绕 Anthropic 的 `cache_control` 标记构建的(完全不同的机制)。把 Claude Code 指向 DeepSeek 的 Anthropic 兼容端点,能拿到便宜的 token,但缓存命中没了——标记被忽略,底下的前缀本来就不字节稳定。通用后端工具(Aider / Cline / Continue)从另一个方向撞上同一堵墙:它们的 compaction 模式会破坏字节稳定。
<br/>
按 DeepSeek 的定价 —— $0.07/Mtok 未命中、$0.014/Mtok 命中 —— **50% 命中和 94% 命中之间的差距,光是输入成本就大约 2.5 倍。** 同模型、同 API;变的只是循环本身的不变量。
## 社区
通用循环漏掉的几个 DeepSeek 专属修复:
> [!NOTE]
> Reasonix 是开源、社区共建的项目。下面贡献者墙不是装饰 —— 每一个头像都对应一次真实合并的 PR。
| 通用循环假设的 | DeepSeek 实际表现 | Reasonix 的处理 |
|---|---|---|
| reasoning 在结构化的 `thinking` 块里 | R1 偶尔把 tool-call JSON 漏在 `<think>` 标签里 | 一个 `scavenge` pass 把逃逸的 tool call 拉回来 |
| 工具 schema 严格校验 | DeepSeek 会静默丢掉深层嵌套的 object/array 参数 | 自动 flatten——嵌套参数被改写成单层带前缀的名字 |
| tool-call 参数是合法 JSON | DeepSeek 偶尔吐 `string="false"` 之类的破碎片段 | 专门的 `ToolCallRepair` 在 dispatch 前把常见形状修好 |
| reasoning 深度靠系统级开关调 | V4 暴露了 `reasoning_effort` 旋钮(`max` / `high`) | `/effort` 斜杠 + `--effort` flag,便宜回合可以降档 |
缓存稳定不是个开关,是循环要围绕设计的不变量。这就是 Reasonix 只支持 DeepSeek 的根本原因。
</details>
---
## 功能一览
<p align="center">
<img src="docs/assets/feature-grid.zh-CN.svg" alt="功能一览 — 缓存优先循环、计划模式、MCP 一等公民、会话与仪表盘、Hooks、Memory 与 Skills" width="860"/>
</p>
权限系统(`allow` / `ask` / `deny`)、tool-call repair(flatten · scavenge · truncation · storm)、`/effort` 给便宜回合降档——一起把整个 loop 兜起来。[架构文档 →](./docs/ARCHITECTURE.md) · [Dashboard 设计稿 →](https://esengine.github.io/reasonix/design/agent-dashboard.html) · [TUI 设计稿 →](https://esengine.github.io/reasonix/design/agent-tui-terminal.html) · [官网 →](https://esengine.github.io/reasonix/)
---
## 参与贡献
Reasonix 现在主要是单人维护,但是为协作设计的。给新手准备的入门 issue —— 每个都带背景说明、代码定位、验收标准、提示 —— 全部挂在 [`good first issue`](https://github.com/esengine/reasonix/labels/good%20first%20issue) 标签下。挑任意一个还没人认领的就行。
给新手准备的入门 issue —— 每个都带背景说明、代码定位、验收标准、提示 —— 全部挂在 [`good first issue`](https://github.com/esengine/reasonix/labels/good%20first%20issue) 标签下。挑任意一个还没人认领的就行。
**正在征集意见的 Discussions:**
- [#20 · CLI / TUI 设计](https://github.com/esengine/reasonix/discussions/20) — 哪里坏了、哪里少东西、哪里你会怎么改?
- [#21 · Dashboard 设计](https://github.com/esengine/reasonix/discussions/21) — 对着[设计稿](https://esengine.github.io/reasonix/design/agent-dashboard.html)拍砖
- [#22 · 未来功能愿望单](https://github.com/esengine/reasonix/discussions/22) — 你希望 Reasonix 长出什么功能?
- [#20 · CLI / TUI 设计](https://github.com/esengine/reasonix/discussions/20) —— 哪里坏了、哪里少东西、哪里你会怎么改?
- [#21 · Dashboard 设计](https://github.com/esengine/reasonix/discussions/21) —— 对着[设计稿](https://esengine.github.io/DeepSeek-Reasonix/design/agent-dashboard.html)拍砖
- [#22 · 未来功能愿望单](https://github.com/esengine/reasonix/discussions/22) —— 你希望 Reasonix 长出什么功能?
**正在使用 Reasonix,愿意让更多人了解它?** 欢迎将相关博客、文章、截图、演讲或视频发布到 [**Show and tell**](https://github.com/esengine/reasonix/discussions/categories/show-and-tell)。项目没有营销预算,新用户主要通过社区口碑找到这里。持续参与传播的用户将获得下方这枚徽章,颁发后会展示在贡献者墙旁:
<p align="center">
<a href="https://github.com/esengine/reasonix/discussions/categories/show-and-tell">
<img src="https://img.shields.io/badge/REASONIX-📣%20ADVOCATE-c4b5fd?style=for-the-badge&labelColor=0d1117" alt="Reasonix Advocate 徽章 —— 授予持续参与传播的用户"/>
</a>
</p>
**第一次提 PR 之前**:先读 [`CONTRIBUTING.md`](./CONTRIBUTING.md) —— 短小、严格的项目规则(注释、错误处理、用现成库不手写)。`tests/comment-policy.test.ts` 静态强制执行注释那部分,`npm run verify` 是 push 前的闸。参与本项目即同意 [行为准则](./CODE_OF_CONDUCT.md)。安全相关问题请走 [SECURITY.md](./SECURITY.md)。
### 贡献者
<p align="center">
<a href="https://github.com/esengine/reasonix/graphs/contributors">
<img src="https://contrib.rocks/image?repo=esengine/reasonix&max=100&columns=12" alt="esengine/reasonix 贡献者" width="860"/>
</a>
</p>
<a href="https://github.com/esengine/reasonix/graphs/contributors">
<img src="https://contrib.rocks/image?repo=esengine/reasonix" alt="esengine/reasonix 贡献者"/>
</a>
---
<br/>
## 不做的事
- **多供应商灵活性。** 故意只做 DeepSeek —— 每一层都为 DeepSeek 特定的缓存机制和定价调过。绑死一个后端是 feature,不是要克服的限制。
- **IDE 集成。** 终端优先;diff 在 `git diff`,文件树在 `ls`。仪表盘是 TUI 的伴生,不是 Cursor 的替代。
- **追最难的 reasoning 榜单。** Claude Opus 在某些榜单上还是赢家。DeepSeek V4 在编程任务上有竞争力;如果你的工作是"解一个 PhD 级证明"而不是"修个 auth bug",先用 Claude。
> [!IMPORTANT]
> Reasonix 是有立场的。有些事它故意 *不做* —— 列在这里方便你为自己的工作挑对工具。
- **多供应商灵活性。** 故意只做 DeepSeek。绑死一个后端是 feature,不是限制。
- **IDE 集成。** 终端优先。diff 在 `git diff`,文件树在 `ls`。仪表盘是 TUI 的伴生,不是 Cursor 的替代。
- **追最难的 reasoning 榜单。** Claude Opus 在某些榜单上还是赢家。DeepSeek 在编程任务上有竞争力;如果你的工作是"解一个 PhD 级证明"而不是"修个 auth bug",先用 Claude。
- **完全离线 / 永远免费。** Reasonix 需要付费的 DeepSeek API Key。要离线 / 零成本,看 Aider + Ollama 或 [Continue](https://continue.dev)。
<br/>
## Star 趋势
<a href="https://www.star-history.com/?repos=esengine%2Freasonix&type=timeline&logscale=&legend=top-left">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/chart?repos=esengine/reasonix&type=timeline&theme=dark&logscale&legend=top-left" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/chart?repos=esengine/reasonix&type=timeline&logscale&legend=top-left" />
<img alt="Star History Chart" src="https://api.star-history.com/chart?repos=esengine/reasonix&type=timeline&logscale&legend=top-left" />
</picture>
</a>
<br/>
---
## 协议
MIT —— 见 [LICENSE](./LICENSE)。
<p align="center">
<sub>MIT —— 见 <a href="./LICENSE">LICENSE</a></sub>
<br/>
<sub>由 <a href="https://github.com/esengine/reasonix/graphs/contributors">esengine/reasonix</a> 社区共建</sub>
</p>
Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

+76
View File
@@ -0,0 +1,76 @@
# Real-world cache hit — single user, single day
A real Reasonix user shared their DeepSeek dashboard for **2026-05-01**.
Used with permission, anonymized.
![DeepSeek usage dashboard, 2026-05-01](2026-05-01-deepseek-dashboard.png)
## The numbers
| | Tokens |
|---|---:|
| Input — cache hit | 435,033,856 |
| Input — cache miss | 767,616 |
| Output | 179,763 |
| **Day total** | **435,981,235** |
**Cache hit ratio (input):**
`435,033,856 / (435,033,856 + 767,616)` = **99.82%**
## Cost — using the prices Reasonix bills against (`src/telemetry/stats.ts`)
USD per 1M tokens — `inputCacheHit / inputCacheMiss / output`:
- `deepseek-v4-flash` — `0.028 / 0.139 / 0.278`
- `deepseek-v4-pro` — `0.139 / 1.667 / 3.333`
Assuming **v4-flash** (the project default):
| | This user (99.82% hit) | Same workload, **0% cache** |
|---|---:|---:|
| Cache-hit input | $12.18 | — |
| Cache-miss input | $0.11 | $60.58 |
| Output | $0.05 | $0.05 |
| **Total / day** | **$12.34** | **$60.63** |
→ Cache saved this user **$48.29**, or **~80%** off the un-cached baseline, on a single day.
On **v4-pro** (5× the prefix-cache discount) the same workload would cost
**~$62.35** vs **~$727.08** without cache — a **~91% saving**.
## "Isn't that just DeepSeek's prefix cache?"
DeepSeek's API ships prefix caching enabled by default; the *cache* is theirs,
the *hit rate* is the client's. Same API, different clients, very different
hit rates:
- DeepSeek's own web chat: 60–80% within a single conversation, drops to 0%
on a new session (system prompt may differ).
- Cherry Studio / Open WebUI / generic OpenAI-shape SDKs: typically 30–60%
on long sessions — history gets reordered, tool specs get re-serialized,
every drift breaks the prefix.
- Cline / Continue and other XML-tool-call clients: lower still — every tool
result inlines into the conversation, shifting bytes the cache keys on.
99.82% is what falls out of these four design choices in Reasonix:
1. **`ImmutablePrefix`** (`src/memory.ts`) — system prompt + tool specs are
frozen at session start. Same byte sequence every turn.
2. **`AppendOnlyLog`** — turns only append. No reorder, no edit-in-place.
3. **`VolatileScratch`** — chain-of-thought / per-turn scratch lives outside
the cached prefix so it never poisons the next hit.
4. **Auto-compact** — when context approaches the cap, older turns fold into
a summary message *appended* to the prefix; the prefix itself isn't
rewritten, so the cache survives the fold.
DeepSeek gave us cacheable bytes. The four mechanisms above are how we keep
the bytes cacheable.
## Reproduce
The synthetic side of this lives in `benchmarks/tau-bench/` — same task set
run through `CacheFirstLoop` vs a deliberately cache-hostile baseline. The
real-world data above is what the synthetic numbers look like once a user
runs the harness in anger.
Submit your own dashboard screenshot if you want it anonymized and added
here — open an issue.
+1 -1
View File
@@ -45,7 +45,7 @@ const PROMPTS = [
{ id: "m3", level: "medium", task: "A function \`debounceAsync<T extends any[], R>(fn: (...args: T) => Promise<R>, ms: number): (...args: T) => Promise<R>\` in src/util/debounce.ts. Resolves only the latest call's promise; earlier callers reject with an AbortError-like." },
// hard (2) — these touch domain types from the repo
{ id: "h1", level: "hard", task: "A function \`extractTestId(file: string, fullName: string, source: string): { id: string, source: 'native' | 'annotation' }\` in src/repair/test-id.ts. If \`source\` contains a '// @reasonix-test-id: <slug>' comment within 3 lines above an it()/test() whose name matches \`fullName\`, return that slug with source='annotation'. Otherwise return \`\${file}::\${fullName}\` with source='native'." },
{ id: "h1", level: "hard", task: "A function \`extractTestId(file: string, fullName: string, source: string): { id: string, source: 'native' | 'annotation' }\` in src/repair/test-id.ts. If \`source\` contains a '// @reasonix-test-id: <slug>' comment within 3 lines above an it()/test() whose name matches \`fullName\`, return that slug with source='annotation'. Otherwise return \`${file}::${fullName}\` with source='native'." },
{ id: "h2", level: "hard", task: "A function \`pairRedGreen(events: Array<{type:string, test_id?:string, status?:string, ts:number}>): Array<{ test_id: string, red_ts: number, green_ts: number }>\` in src/events/pair.ts. For each test_id, find the most recent fail→pass transition and return one entry per test_id. Ignore test_ids that never went green." },
];
+17 -3
View File
@@ -690,8 +690,19 @@ main { padding: 32px 40px 60px 32px; min-width: 0; }
.crumbs .sep { color: var(--fg-4); }
/* ── Sessions panel ──────────────────────────────────────────────────── */
.sessions-grid { display: grid; grid-template-columns: 320px minmax(0, 1fr); gap: 14px; min-height: 540px; }
.sessions-list { background: var(--bg-elev); border: 1px solid var(--bd); border-radius: var(--r); display: flex; flex-direction: column; overflow: hidden; }
.sessions-grid {
display: grid;
grid-template-columns: 320px minmax(0, 1fr);
/* `minmax(0, 1fr)` on the row + `min-height: 0` on the children is the
standard recipe for "let the inner overflow:auto take effect" — without
it the grid items default to min-height: auto (= content size) and
grow past the parent's max-height, dragging .app-body along. */
grid-template-rows: minmax(0, 1fr);
gap: 14px;
min-height: 540px;
max-height: calc(100vh - 140px);
}
.sessions-list { background: var(--bg-elev); border: 1px solid var(--bd); border-radius: var(--r); display: flex; flex-direction: column; overflow: hidden; min-height: 0; min-width: 0; }
.sessions-list .ssl-h { padding: 10px 12px; border-bottom: 1px solid var(--bd); display: flex; align-items: center; gap: 8px; }
.sessions-list .ssl-h input {
flex: 1; background: var(--bg-input); border: 1px solid var(--bd); border-radius: var(--r);
@@ -710,7 +721,7 @@ main { padding: 32px 40px 60px 32px; min-width: 0; }
.ssl-row .meta { display: flex; gap: 10px; font-family: var(--font-mono); font-size: 10.5px; color: var(--fg-4); margin-top: 2px; }
.ssl-row .meta .v { color: var(--fg-2); }
.sessions-detail { background: var(--bg-elev); border: 1px solid var(--bd); border-radius: var(--r); padding: 14px 16px; overflow: auto; }
.sessions-detail { background: var(--bg-elev); border: 1px solid var(--bd); border-radius: var(--r); padding: 14px 16px; overflow: auto; min-height: 0; min-width: 0; }
.sessions-detail-h { display: flex; align-items: baseline; gap: 12px; margin-bottom: 12px; padding-bottom: 12px; border-bottom: 1px solid var(--bd); }
.sessions-detail-h .name { font-family: var(--font-mono); font-size: 14px; color: var(--fg-0); font-weight: 600; }
.sessions-detail-h .ws { font-family: var(--font-mono); font-size: 11px; color: var(--fg-3); }
@@ -801,6 +812,9 @@ main { padding: 32px 40px 60px 32px; min-width: 0; }
}
.chip-f:hover { background: var(--bg-hover); color: var(--fg-1); }
.chip-f.active { color: var(--c-brand); border-color: var(--c-brand); background: rgba(121,192,255,.08); }
.chip-f.static { cursor: default; }
.chip-f.static:hover { background: var(--bg-elev); color: var(--fg-2); }
.chip-f.static.active:hover { color: var(--c-brand); background: rgba(121,192,255,.08); }
.chip-f .ct { color: var(--fg-4); font-size: 10px; }
.chip-f.active .ct { color: var(--c-brand); }
.chip-f .x { color: var(--fg-4); padding: 0 2px; }
+26
View File
@@ -264,6 +264,32 @@ export const en = {
colName: "name",
colDesc: "description",
colUri: "uri",
marketplace: "marketplace",
marketplaceSearch: "search the registry…",
marketplaceLoading: "loading registry…",
marketplaceMore: "load 5 more pages",
marketplaceMoreLabel: "load 50 more · showing {shown} / {total}",
marketplaceMoreHint: "fetches more pages from the registry",
marketplaceMoreCachedHint: "more entries already cached locally",
marketplaceExhausted: "all pages loaded",
marketplaceExhaustedFull: "showing all {total} entries — registry exhausted",
marketplaceCount: "{loaded} loaded · {matched} match · source: {source}{cached}",
marketplaceCachedSuffix: " · cached",
marketplaceNoMatches: "No matches. Try different terms or load more pages.",
marketplaceInstall: "Install",
marketplacePickHint: "Pick a server on the left, then Install.",
marketplaceInstalled: "installed → {spec}",
marketplaceInstalledBridged: "installed + bridged → {spec}",
marketplaceAlready: "already installed",
marketplaceNeedsEnv: "needs env: {names}",
marketplaceSourceTag: "[{source}]",
marketplaceNoInstall: "smithery listing — install metadata not exposed; use `npx -y @smithery/cli install {name}` directly",
marketplaceFetchOnInstall: "Smithery listing — install detail fetched on Install. http servers map to streamable-http remotes; stdio servers run via @smithery/cli.",
marketplaceInstalledBadge: "installed",
marketplaceUninstall: "Uninstall",
marketplaceEnvTitle: "Required environment variables",
marketplaceEnvHint: "Set these in your shell before next `reasonix code` so the bridged server can authenticate.",
marketplaceRestartHint: "Spec written to ~/.reasonix/config.json. Restart `reasonix code` to bridge the server (live hot-reload is on the roadmap).",
},
memory: {
loading: "loading memory…",
+26
View File
@@ -264,6 +264,32 @@ export const zhCN = {
colName: "名称",
colDesc: "描述",
colUri: "URI",
marketplace: "市场",
marketplaceSearch: "搜索注册表…",
marketplaceLoading: "加载注册表…",
marketplaceMore: "再加载 5 页",
marketplaceMoreLabel: "再加载 50 条 · 当前 {shown} / {total}",
marketplaceMoreHint: "需要从远端注册表再拉几页",
marketplaceMoreCachedHint: "本地缓存已有更多条目",
marketplaceExhausted: "已加载全部页",
marketplaceExhaustedFull: "已展示全部 {total} 条 — 注册表耗尽",
marketplaceCount: "已载入 {loaded} · 匹配 {matched} · 来源:{source}{cached}",
marketplaceCachedSuffix: " · 缓存中",
marketplaceNoMatches: "无匹配结果。换关键词或加载更多页。",
marketplaceInstall: "安装",
marketplacePickHint: "在左侧选择服务器,然后点安装。",
marketplaceInstalled: "已安装 → {spec}",
marketplaceInstalledBridged: "已安装并桥接 → {spec}",
marketplaceAlready: "已安装过",
marketplaceNeedsEnv: "需设置环境变量:{names}",
marketplaceSourceTag: "[{source}]",
marketplaceNoInstall: "Smithery 列表项 — 不暴露安装元数据;请直接 `npx -y @smithery/cli install {name}`",
marketplaceFetchOnInstall: "Smithery 列表 — 安装时再拉详情。HTTP 服务映射为 streamable-http 远端;stdio 服务通过 @smithery/cli 运行。",
marketplaceInstalledBadge: "已安装",
marketplaceUninstall: "卸载",
marketplaceEnvTitle: "必需的环境变量",
marketplaceEnvHint: "下次启动 `reasonix code` 之前在 shell 里设好,桥接的服务器才能正常鉴权。",
marketplaceRestartHint: "已写入 ~/.reasonix/config.json。重启 `reasonix code` 后服务器才会真正桥接(热重载在路线图上)。",
},
memory: {
loading: "加载记忆…",
+18
View File
@@ -4,6 +4,24 @@ export function fmtUsd(n: number | null | undefined): string {
return `$${n.toFixed(n < 0.01 ? 6 : 4)}`;
}
/** Keep in sync with src/cli/ui/theme/tokens.ts USD_TO_CNY. */
const USD_TO_CNY = 7.2;
/** USD-internal cost rendered in the wallet's display currency. Undefined currency → CNY (matches CLI default). */
export function fmtCost(
usd: number | null | undefined,
currency: string | null | undefined,
fractionDigits?: number,
): string {
if (usd === null || usd === undefined) return "—";
const cur = currency ?? "CNY";
const amount = cur === "CNY" ? usd * USD_TO_CNY : usd;
if (amount === 0) return cur === "CNY" ? "¥0" : "$0";
const sym = cur === "CNY" ? "¥" : cur === "USD" ? "$" : `${cur} `;
const digits = fractionDigits ?? (Math.abs(amount) < 0.01 ? 6 : 4);
return `${sym}${amount.toFixed(digits)}`;
}
export function fmtPct(n: number | null | undefined): string {
if (n === null || n === undefined) return "—";
return `${(n * 100).toFixed(1)}%`;
+7 -6
View File
@@ -14,7 +14,7 @@ import {
} from "../components/chat-internals.js";
import { MODE, TOKEN, api } from "../lib/api.js";
import { appBus, showToast } from "../lib/bus.js";
import { fmtUsd } from "../lib/format.js";
import { fmtCost, fmtUsd } from "../lib/format.js";
import { html } from "../lib/html.js";
import { t, useLang } from "../i18n/index.js";
@@ -559,7 +559,7 @@ export function ChatPanel() {
<div class="chat-shell">
<div style="display:flex;align-items:center;gap:12px;margin-bottom:10px">
<div class="chips" style="padding:0">
<span class="chip-f active">${MODE === "attached" ? t("chat.modeMirror") : t("chat.modeView")}</span>
<span class="chip-f static active">${MODE === "attached" ? t("chat.modeMirror") : t("chat.modeView")}</span>
</div>
<div class="header-pickers" style="margin-left:auto">
${
@@ -791,6 +791,7 @@ function SideRail({ stats, budgetUsd, activePlan }: SideRailProps) {
const showBudget = stats != null && typeof budgetUsd === "number" && budgetUsd > 0;
const budgetPct = showBudget ? Math.min(120, (stats.totalCostUsd / budgetUsd) * 100) : 0;
const budgetTone = budgetPct >= 100 ? "err" : budgetPct >= 80 ? "warn" : "";
const walletCurrency = stats?.balance?.[0]?.currency;
return html`
<aside class="chat-rail">
${activePlan ? html`<${ActivePlanCard} plan=${activePlan} />` : null}
@@ -801,7 +802,7 @@ function SideRail({ stats, budgetUsd, activePlan }: SideRailProps) {
<div class="rh">${t("chat.railSession")}</div>
<div class="rail-kv"><span class="k">${t("chat.railTurns")}</span><span class="v">${stats.turns.toLocaleString()}</span></div>
<div class="rail-kv"><span class="k">${t("chat.railPromptTok")}</span><span class="v">${stats.lastPromptTokens.toLocaleString()}</span></div>
<div class="rail-kv"><span class="k">${t("chat.railCost")}</span><span class="v">${fmtUsd(stats.totalCostUsd)}</span></div>
<div class="rail-kv"><span class="k">${t("chat.railCost")}</span><span class="v">${fmtCost(stats.totalCostUsd, walletCurrency)}</span></div>
<div class="progress-row" style="margin-top:8px">
<span class="lbl">${t("chat.railCacheHit")}</span>
<div class=${`progress ${cacheTone}`}><div class="progress-fill" style=${`width:${cachePct}%`}></div></div>
@@ -819,7 +820,7 @@ function SideRail({ stats, budgetUsd, activePlan }: SideRailProps) {
<div class="progress-row">
<span class="lbl">${t("chat.railSpend")}</span>
<div class=${`progress ${budgetTone}`}><div class="progress-fill" style=${`width:${Math.min(100, budgetPct)}%`}></div></div>
<span class="v" style=${budgetTone === "err" ? "color:var(--c-err)" : budgetTone === "warn" ? "color:var(--c-warn)" : ""}>${fmtUsd(stats.totalCostUsd)} / ${fmtUsd(budgetUsd)}</span>
<span class="v" style=${budgetTone === "err" ? "color:var(--c-err)" : budgetTone === "warn" ? "color:var(--c-warn)" : ""}>${fmtCost(stats.totalCostUsd, walletCurrency)} / ${fmtCost(budgetUsd, walletCurrency)}</span>
</div>
</div>
`
@@ -989,11 +990,11 @@ function ChatStatusBar({ stats, model }: ChatStatusBarProps) {
</span>
<span class="status-item">
<span class="status-label">${t("chat.statusTurn")}</span>
<code>${fmtUsd(stats.lastTurnCostUsd)}</code>
<code>${fmtCost(stats.lastTurnCostUsd, balance?.currency)}</code>
</span>
<span class="status-item">
<span class="status-label">${t("chat.statusSession")}</span>
<code>${fmtUsd(stats.totalCostUsd)}</code>
<code>${fmtCost(stats.totalCostUsd, balance?.currency)}</code>
<span class="muted" style="font-size: 10px;">
${t("chat.statusTurns", { count: stats.turns, s: stats.turns === 1 ? "" : "s" })}
</span>
+17 -4
View File
@@ -68,6 +68,7 @@ export function HooksPanel() {
const [drafts, setDrafts] = useState<Record<string, string>>({});
const [busy, setBusy] = useState(false);
const [info, setInfo] = useState<string | null>(null);
const [eventFilter, setEventFilter] = useState<string>("all");
const load = useCallback(async () => {
try {
@@ -129,19 +130,31 @@ export function HooksPanel() {
data.events.length > 0
? data.events
: Array.from(new Set(matrixRows.flatMap((r) => Object.keys(r.cells))));
const visibleRows =
eventFilter === "all"
? matrixRows
: matrixRows.filter((r) => r.cells[eventFilter]?.on);
const gridCols = `220px repeat(${Math.max(events.length, 1)}, minmax(0, 1fr))`;
return html`
<div style="display:flex;flex-direction:column;gap:6px">
<div class="chips">
<span class="chip-f active">${t("hooks.resolved")} <span class="ct">${data.resolved.length}</span></span>
${data.events.map((ev) => html`<span class="chip-f">${ev}</span>`)}
<span
class=${`chip-f ${eventFilter === "all" ? "active" : ""}`}
onClick=${() => setEventFilter("all")}
>${t("hooks.resolved")} <span class="ct">${data.resolved.length}</span></span>
${data.events.map(
(ev) => html`<span
class=${`chip-f ${eventFilter === ev ? "active" : ""}`}
onClick=${() => setEventFilter(ev)}
>${ev}</span>`,
)}
</div>
${info ? html`<div><span class="pill ok">${info}</span></div>` : null}
${error ? html`<div class="card accent-err">${error}</div>` : null}
${sectionH3(t("hooks.eventMatrix"), t("hooks.matrixSub", { scripts: matrixRows.length, s: matrixRows.length === 1 ? "" : "s", events: events.length }))}${
matrixRows.length === 0
visibleRows.length === 0
? html`<div class="card" style="color:var(--fg-3)">
${t("hooks.noHooks")}
</div>`
@@ -152,7 +165,7 @@ export function HooksPanel() {
<div>${t("hooks.colScript")}</div>
${events.map((ev) => html`<div>${ev}</div>`)}
</div>
${matrixRows.map(
${visibleRows.map(
(r) => html`
<div class="row" style=${`grid-template-columns:${gridCols}`}>
<div class="cell" title=${r.command}>
+403 -25
View File
@@ -1,8 +1,8 @@
import { useCallback, useEffect, useState } from "preact/hooks";
import { t, useLang } from "../i18n/index.js";
import { api } from "../lib/api.js";
import { fmtNum } from "../lib/format.js";
import { html } from "../lib/html.js";
import { t, useLang } from "../i18n/index.js";
interface McpServer {
label: string;
@@ -20,6 +20,60 @@ interface McpData {
servers: McpServer[];
}
interface RegistryInstall {
runtime: string;
packageId?: string;
version?: string;
transport: string;
url?: string;
requiredEnv?: string[];
extraArgs?: string[];
}
interface RegistryEntryDto {
name: string;
title: string;
description: string;
source: "official" | "smithery" | "local";
install?: RegistryInstall;
popularity?: number;
homepage?: string;
iconUrl?: string;
}
/** Mirror of src/mcp/registry-fetch.ts:specStringFor — kept in sync to detect already-installed state without an extra round-trip. */
function specForEntry(e: RegistryEntryDto): string | null {
if (!e.install) return null;
const localName = e.name.split("/").pop() ?? e.name;
const safe = localName.replace(/[^a-zA-Z0-9_-]/g, "-").replace(/^-+|-+$/g, "") || "mcp";
const trail = e.install.extraArgs?.length ? ` ${e.install.extraArgs.join(" ")}` : "";
if (e.install.runtime === "remote" && e.install.url) {
if (e.install.transport === "streamable-http") return `${safe}=streamable+${e.install.url}`;
return `${safe}=${e.install.url}`;
}
if (e.install.runtime === "npm" && e.install.packageId) {
const pinned = e.install.version
? `${e.install.packageId}@${e.install.version}`
: e.install.packageId;
return `${safe}=npx -y ${pinned}${trail}`;
}
if (e.install.runtime === "pypi" && e.install.packageId) {
return `${safe}=uvx ${e.install.packageId}${trail}`;
}
return null;
}
interface RegistryListResponse {
source: "official" | "smithery" | "local";
fromCache: boolean;
fetchedAt: number;
loaded: number;
hasMore: boolean;
matched: number;
entries: RegistryEntryDto[];
errors: string[];
}
function specLabel(spec: string): string {
const eq = spec.indexOf("=");
return eq > 0 ? spec.slice(0, eq) : spec;
@@ -30,7 +84,7 @@ function specCommand(spec: string): string {
return eq > 0 ? spec.slice(eq + 1) : spec;
}
type McpFilter = "all" | "live" | "unbridged";
type McpFilter = "all" | "live" | "unbridged" | "marketplace";
export function McpPanel() {
useLang();
@@ -43,6 +97,70 @@ export function McpPanel() {
const [open, setOpen] = useState<McpServer | null>(null);
const [openUnbridged, setOpenUnbridged] = useState<string | null>(null);
const [filter, setFilter] = useState<McpFilter>("all");
const [registry, setRegistry] = useState<RegistryListResponse | null>(null);
const [registryQuery, setRegistryQuery] = useState("");
const [registryLoading, setRegistryLoading] = useState(false);
const [openRegistry, setOpenRegistry] = useState<RegistryEntryDto | null>(null);
/** Display cap — grows by 50 each "load more" click. Server caps response size at this. */
const [displayLimit, setDisplayLimit] = useState(50);
const loadRegistry = useCallback(async (q: string, pages: number, limit: number) => {
setRegistryLoading(true);
try {
const params = new URLSearchParams();
if (q.trim()) params.set("q", q.trim());
params.set("pages", String(pages));
params.set("maxPages", String(Math.max(20, pages)));
params.set("limit", String(limit));
const r = await api<RegistryListResponse>(`/mcp/registry?${params.toString()}`);
setRegistry(r);
} catch (err) {
setError((err as Error).message);
} finally {
setRegistryLoading(false);
}
}, []);
useEffect(() => {
if (filter !== "marketplace") return;
if (registry) return;
void loadRegistry("", 1, displayLimit);
}, [filter, registry, loadRegistry, displayLimit]);
useEffect(() => {
if (filter !== "marketplace") return;
// Reset the display cap whenever the user retypes; new query = fresh top-50.
setDisplayLimit(50);
const handle = setTimeout(() => void loadRegistry(registryQuery, 1, 50), 300);
return () => clearTimeout(handle);
}, [registryQuery, filter, loadRegistry]);
const installFromRegistry = useCallback(async (entry: RegistryEntryDto) => {
setBusy(true);
try {
const r = await api<{
added: boolean;
alreadyPresent?: boolean;
bridged?: boolean;
spec: string;
}>("/mcp/registry/install", { method: "POST", body: { name: entry.name } });
if (r.alreadyPresent) {
setInfo(t("mcp.marketplaceAlready"));
} else if (r.bridged) {
setInfo(t("mcp.marketplaceInstalledBridged", { spec: r.spec }));
} else {
setInfo(t("mcp.marketplaceInstalled", { spec: r.spec }));
}
setTimeout(() => setInfo(null), 5000);
// Reload BOTH live + spec lists since hot-reload should have
// attached the new bridge.
await load();
} catch (err) {
setError((err as Error).message);
} finally {
setBusy(false);
}
}, []);
const load = useCallback(async () => {
try {
@@ -64,9 +182,7 @@ export function McpPanel() {
method: "POST",
body: { spec: newSpec.trim() },
});
setInfo(
r.requiresRestart ? t("mcp.savedRestart") : t("mcp.saved"),
);
setInfo(r.requiresRestart ? t("mcp.savedRestart") : t("mcp.saved"));
setTimeout(() => setInfo(null), 4000);
setNewSpec("");
await load();
@@ -95,15 +211,17 @@ export function McpPanel() {
[load],
);
if (!data && !error) return html`<div class="card" style="color:var(--fg-3)">${t("mcp.loading")}</div>`;
if (!data && !error)
return html`<div class="card" style="color:var(--fg-3)">${t("mcp.loading")}</div>`;
if (error && !data) return html`<div class="card accent-err">${error}</div>`;
if (!data) return null;
const liveCount = data.servers.length;
const unbridgedSpecs = (specs ?? []).filter((spec) => !data.servers.some((s) => s.spec === spec));
const unbridgedCount = unbridgedSpecs.length;
const showLive = filter !== "unbridged";
const showUnbridged = filter !== "live";
const showLive = filter === "all" || filter === "live";
const showUnbridged = filter === "all" || filter === "unbridged";
const showMarketplace = filter === "marketplace";
return html`
<div class="sessions-grid">
@@ -116,29 +234,82 @@ export function McpPanel() {
<span class=${`chip-f ${filter === "all" ? "active" : ""}`} onClick=${() => setFilter("all")}>${t("mcp.all")} <span class="ct">${liveCount + unbridgedCount}</span></span>
<span class=${`chip-f ${filter === "live" ? "active" : ""}`} onClick=${() => setFilter("live")}>${t("mcp.live")} <span class="ct">${liveCount}</span></span>
<span class=${`chip-f ${filter === "unbridged" ? "active" : ""}`} onClick=${() => setFilter("unbridged")}>${t("mcp.unbridged")} <span class="ct">${unbridgedCount}</span></span>
<span class=${`chip-f ${filter === "marketplace" ? "active" : ""}`} onClick=${() => setFilter("marketplace")}>${t("mcp.marketplace")}</span>
</div>
</div>
<div style="padding:8px 12px;display:flex;gap:6px">
<input
type="text"
placeholder=${t("mcp.specPlaceholder")}
value=${newSpec}
onInput=${(e: Event) => setNewSpec((e.target as HTMLInputElement).value)}
style="flex:1;font-size:11px"
/>
<button class="btn primary" disabled=${busy || !newSpec.trim()} onClick=${addSpec}>+</button>
</div>
${
showMarketplace
? html`
<div style="padding:8px 12px;display:flex;gap:6px">
<input
type="text"
placeholder=${t("mcp.marketplaceSearch")}
value=${registryQuery}
onInput=${(e: Event) => setRegistryQuery((e.target as HTMLInputElement).value)}
style="flex:1;font-size:11px"
/>
</div>
${
registry
? html`<div style="padding:0 12px 6px;font-size:11px;color:var(--fg-3)">
${t("mcp.marketplaceCount", {
loaded: registry.loaded,
matched: registry.matched,
source: registry.source,
cached: registry.fromCache ? t("mcp.marketplaceCachedSuffix") : "",
})}
</div>`
: null
}
`
: html`
<div style="padding:8px 12px;display:flex;gap:6px">
<input
type="text"
placeholder=${t("mcp.specPlaceholder")}
value=${newSpec}
onInput=${(e: Event) => setNewSpec((e.target as HTMLInputElement).value)}
style="flex:1;font-size:11px"
/>
<button class="btn primary" disabled=${busy || !newSpec.trim()} onClick=${addSpec}>+</button>
</div>
`
}
${info ? html`<div style="padding:0 12px 8px"><span class="pill ok">${info}</span></div>` : null}
${error ? html`<div class="card accent-err" style="margin:0 12px 8px">${error}</div>` : null}
<div class="ssl-rows">
${
liveCount === 0 && unbridgedCount === 0
!showMarketplace && liveCount === 0 && unbridgedCount === 0
? html`<div style="color:var(--fg-3);padding:14px;font-size:12px">
${t("mcp.noServers")}
</div>`
: null
}
${
showMarketplace
? renderMarketplaceRows({
registry,
registryLoading,
openRegistry,
setOpenRegistry: (e) => {
setOpenRegistry(e);
setOpen(null);
setOpenUnbridged(null);
},
loadMore: () => {
const nextLimit = displayLimit + 50;
setDisplayLimit(nextLimit);
// Pages: walk far enough to fill the new cap (each page ≈ 30
// entries) plus a few-page lookahead so the next click also
// has fresh data.
const pagesNeeded = Math.ceil(nextLimit / 30) + 3;
void loadRegistry(registryQuery, pagesNeeded, nextLimit);
},
installedSpecs: new Set(specs ?? []),
})
: null
}
${
showLive
? data.servers.map(
@@ -182,8 +353,20 @@ export function McpPanel() {
<div class="sessions-detail">
${
openUnbridged != null
? html`
openRegistry != null
? renderRegistryDetail({
entry: openRegistry,
busy,
installedSpec: (() => {
const spec = specForEntry(openRegistry);
return spec && (specs ?? []).includes(spec) ? spec : null;
})(),
onInstall: () => installFromRegistry(openRegistry),
onUninstall: (spec: string) => removeSpec(spec),
onClose: () => setOpenRegistry(null),
})
: openUnbridged != null
? html`
<div class="sessions-detail-h">
<span class="name">${specLabel(openUnbridged)}</span>
<span class="ws"><span class="pill">${t("mcp.unbridgedTitle")}</span></span>
@@ -207,11 +390,11 @@ export function McpPanel() {
</div>
</div>
`
: open == null
? html`<div style="color:var(--fg-3);font-size:13px;text-align:center;padding:60px 20px">
${t("mcp.pickHint")}
: open == null
? html`<div style="color:var(--fg-3);font-size:13px;text-align:center;padding:60px 20px">
${showMarketplace ? t("mcp.marketplacePickHint") : t("mcp.pickHint")}
</div>`
: html`
: html`
<div class="sessions-detail-h">
<span class="name">${open.label}</span>
<span class="ws">${open.serverInfo?.name ?? "—"} ${open.serverInfo?.version ? `v${open.serverInfo.version}` : ""} · ${open.protocolVersion ?? "—"}</span>
@@ -295,3 +478,198 @@ export function McpPanel() {
</div>
`;
}
interface MarketplaceRowsArgs {
registry: RegistryListResponse | null;
registryLoading: boolean;
openRegistry: RegistryEntryDto | null;
setOpenRegistry: (entry: RegistryEntryDto) => void;
loadMore: () => void;
installedSpecs: Set<string>;
}
function renderLoadMoreFooter({
registry,
registryLoading,
loadMore,
}: Pick<MarketplaceRowsArgs, "registry" | "registryLoading" | "loadMore">) {
if (!registry) return null;
const shown = registry.entries.length;
const total = registry.matched;
const moreCached = total > shown;
const moreOnNetwork = registry.hasMore;
const canDoSomething = moreCached || moreOnNetwork;
// Three states:
// 1. Loading — disabled button + spinner-ish label
// 2. More available — primary button + count of what's loaded
// 3. Exhausted — distinct success-tinted card so the user
// doesn't think the button stopped responding
if (canDoSomething) {
const label = registryLoading
? t("mcp.marketplaceLoading")
: t("mcp.marketplaceMoreLabel", {
shown,
total: moreOnNetwork ? `${total}+` : `${total}`,
});
return html`<div style="padding:10px 12px;display:flex;align-items:center;gap:10px">
<button class="btn primary" disabled=${registryLoading} onClick=${loadMore}>${label}</button>
<span style="font-size:11px;color:var(--fg-3)">
${moreOnNetwork ? t("mcp.marketplaceMoreHint") : t("mcp.marketplaceMoreCachedHint")}
</span>
</div>`;
}
return html`<div style="padding:12px;background:var(--bg-elev-2,rgba(36,143,242,0.07));border-top:1px solid var(--bd);display:flex;align-items:center;gap:8px;font-size:12px;color:var(--fg-2)">
<span style="color:var(--c-ok)">✓</span>
<span>${t("mcp.marketplaceExhaustedFull", { total })}</span>
</div>`;
}
function renderMarketplaceRows({
registry,
registryLoading,
openRegistry,
setOpenRegistry,
loadMore,
installedSpecs,
}: MarketplaceRowsArgs) {
if (!registry && registryLoading) {
return html`<div style="color:var(--fg-3);padding:14px;font-size:12px">${t("mcp.marketplaceLoading")}</div>`;
}
if (!registry || registry.entries.length === 0) {
return html`<div style="color:var(--fg-3);padding:14px;font-size:12px">${t("mcp.marketplaceNoMatches")}</div>`;
}
return html`
${registry.entries.map((e) => {
const sel = openRegistry?.name === e.name;
const tag = t("mcp.marketplaceSourceTag", { source: e.source });
const spec = specForEntry(e);
const installed = spec !== null && installedSpecs.has(spec);
const pop =
e.popularity !== undefined
? html` <span class="dim">· ${fmtNum(e.popularity)}</span>`
: null;
const icon = e.iconUrl
? html`<img src=${e.iconUrl} alt="" style="width:16px;height:16px;border-radius:3px;margin-right:6px;vertical-align:middle;object-fit:cover" loading="lazy" referrerpolicy="no-referrer" onError=${(ev: Event) => ((ev.target as HTMLImageElement).style.display = "none")} />`
: null;
return html`
<div class=${`ssl-row ${sel ? "sel" : ""}`} onClick=${() => setOpenRegistry(e)}>
<span class="name">${icon}${e.name} <span class="pill">${tag}</span>${installed ? html` <span class="pill ok">${t("mcp.marketplaceInstalledBadge")}</span>` : null}</span>
<span class="preview">${e.description}</span>
<span class="meta">${pop}</span>
</div>
`;
})}
${renderLoadMoreFooter({ registry, registryLoading, loadMore })}
`;
}
interface RegistryDetailArgs {
entry: RegistryEntryDto;
busy: boolean;
installedSpec: string | null;
onInstall: () => void;
onUninstall: (spec: string) => void;
onClose: () => void;
}
function renderRegistryDetail({
entry,
busy,
installedSpec,
onInstall,
onUninstall,
onClose,
}: RegistryDetailArgs) {
const installable = !!entry.install || entry.source === "smithery";
const installed = installedSpec !== null;
const specPreview = entry.install
? `${entry.install.runtime} · ${entry.install.transport}${
entry.install.packageId
? ` · ${entry.install.packageId}`
: entry.install.url
? ` · ${entry.install.url}`
: ""
}${entry.install.version ? `@${entry.install.version}` : ""}`
: "";
const icon = entry.iconUrl
? html`<img src=${entry.iconUrl} alt="" style="width:24px;height:24px;border-radius:4px;margin-right:8px;vertical-align:middle;object-fit:cover" loading="lazy" referrerpolicy="no-referrer" onError=${(ev: Event) => ((ev.target as HTMLImageElement).style.display = "none")} />`
: null;
return html`
<div class="sessions-detail-h">
<span class="name">${icon}${entry.name}${installed ? html` <span class="pill ok">${t("mcp.marketplaceInstalledBadge")}</span>` : null}</span>
<span class="ws">${t("mcp.marketplaceSourceTag", { source: entry.source })}${
entry.popularity !== undefined ? ` · ${fmtNum(entry.popularity)} uses` : ""
}${entry.homepage ? html` · <a href=${entry.homepage} target="_blank" rel="noopener noreferrer">homepage</a>` : ""}</span>
<span class="actions">
${
installed
? html`<button
class="btn"
disabled=${busy}
onClick=${() => onUninstall(installedSpec)}
style="border-color:var(--c-err);color:var(--c-err)"
>${t("mcp.marketplaceUninstall")}</button>`
: html`<button class="btn primary" disabled=${busy || !installable} onClick=${onInstall}>${t("mcp.marketplaceInstall")}</button>`
}
<button class="btn ghost" onClick=${onClose}>${t("common.back")}</button>
</span>
</div>
<div class="card" style="margin-bottom:12px">
<div class="card-b" style="font-size:13px;line-height:1.6">${entry.description || "—"}</div>
</div>
${
entry.install
? html`<div class="card" style="margin-bottom:12px">
<div class="card-h"><span class="title">${t("mcp.spec")}</span></div>
<div class="card-b">
<code class="mono" style="font-size:11.5px;color:var(--fg-2);word-break:break-all;display:block">${specPreview}</code>
${
installedSpec
? html`<div style="margin-top:8px;font-size:11px;color:var(--fg-3)">
<span class="dim">on disk:</span> <code class="mono">${installedSpec}</code>
</div>`
: null
}
</div>
</div>`
: entry.source === "smithery"
? html`<div class="card" style="margin-bottom:12px">
<div class="card-b" style="font-size:13px;line-height:1.6;color:var(--fg-3)">
${t("mcp.marketplaceFetchOnInstall")}
</div>
</div>`
: null
}
${
entry.install?.requiredEnv?.length
? html`<div class="card accent-brand" style="margin-bottom:12px">
<div class="card-h"><span class="title">${t("mcp.marketplaceEnvTitle")}</span></div>
<div class="card-b" style="font-size:13px">
${entry.install.requiredEnv.map(
(name) =>
html`<div><code class="mono" style="color:var(--c-warn)">${name}</code></div>`,
)}
<div style="margin-top:6px;color:var(--fg-3);font-size:12px">
${t("mcp.marketplaceEnvHint")}
</div>
</div>
</div>`
: null
}
${
installed
? html`<div class="card accent-warn">
<div class="card-b" style="font-size:12.5px;line-height:1.6">
${t("mcp.marketplaceRestartHint")}
</div>
</div>`
: null
}
`;
}
+4 -3
View File
@@ -1,4 +1,4 @@
import { fmtCompactNum, fmtNum, fmtRelativeTime, fmtUsd } from "../lib/format.js";
import { fmtCompactNum, fmtCost, fmtNum, fmtRelativeTime, fmtUsd } from "../lib/format.js";
import { html } from "../lib/html.js";
import { usePoll } from "../lib/use-poll.js";
import { t, useLang } from "../i18n/index.js";
@@ -144,6 +144,7 @@ function currentSessionBlock(c: CockpitData) {
`;
}
const s = c.currentSession;
const currency = c.balance?.currency;
return html`
<div class="cock-list cock-w-2">
<div class="ch"><span class="ttl">${t("overview.currentSession")}</span></div>
@@ -153,7 +154,7 @@ function currentSessionBlock(c: CockpitData) {
<div style="display:grid;grid-template-columns:repeat(3, 1fr);gap:8px;font-family:var(--font-mono);font-size:11px">
<div><span style="color:var(--fg-3)">${t("overview.promptTok")}</span><div style="color:var(--fg-0);font-size:13px;font-weight:600">${fmtNum(s.lastPromptTokens)}</div></div>
<div><span style="color:var(--fg-3)">${t("overview.completionTok")}</span><div style="color:var(--fg-0);font-size:13px;font-weight:600">${fmtNum(s.completionTokens)}</div></div>
<div><span style="color:var(--fg-3)">${t("overview.cost")}</span><div style="color:var(--fg-0);font-size:13px;font-weight:600">${fmtUsd(s.totalCostUsd)}</div></div>
<div><span style="color:var(--fg-3)">${t("overview.cost")}</span><div style="color:var(--fg-0);font-size:13px;font-weight:600">${fmtCost(s.totalCostUsd, currency)}</div></div>
</div>
</div>
`;
@@ -185,7 +186,7 @@ function costTrendSpark(c: CockpitData) {
return html`
<div class="chart cock-w-2">
<div class="chart-h"><span class="title">${t("overview.costTrend")}</span></div>
<div class="chart-v">${fmtUsd(avg)}<span class="unit">${t("overview.dayAvg")}</span></div>
<div class="chart-v">${fmtCost(avg, c.balance?.currency)}<span class="unit">${t("overview.dayAvg")}</span></div>
<div class="chart-spark">
<svg viewBox=${`0 0 ${w} ${h}`} preserveAspectRatio="none">
<polyline fill="none" stroke="var(--c-brand)" stroke-width="1.5" points=${points} />
+2 -2
View File
@@ -122,8 +122,8 @@ export function PermissionsPanel() {
}
<div class="chips">
<span class="chip-f active">${t("permissions.project")} <span class="ct">${p.project.length}</span></span>
<span class="chip-f">${t("permissions.builtin")} <span class="ct">${p.builtin.length}</span></span>
<span class="chip-f static active">${t("permissions.project")} <span class="ct">${p.project.length}</span></span>
<span class="chip-f static">${t("permissions.builtin")} <span class="ct">${p.builtin.length}</span></span>
</div>
${
+21 -5
View File
@@ -37,6 +37,7 @@ export function PlansPanel() {
const { data, error, loading } = usePoll<PlansData>("/plans", 8000);
const [openIdx, setOpenIdx] = useState<number | null>(null);
const [filter, setFilter] = useState("");
const [statusFilter, setStatusFilter] = useState<"all" | "active" | "done">("all");
if (loading && !data)
return html`<div class="card" style="color:var(--fg-3)">${t("plans.loading")}</div>`;
@@ -48,13 +49,19 @@ export function PlansPanel() {
${t("plans.noPlans")}
</div>`;
const statusFiltered =
statusFilter === "all"
? plans
: statusFilter === "active"
? plans.filter((p) => p.completionRatio > 0 && p.completionRatio < 1)
: plans.filter((p) => p.completionRatio >= 1);
const filtered = filter.trim()
? plans.filter(
? statusFiltered.filter(
(p) =>
p.session.toLowerCase().includes(filter.toLowerCase()) ||
(p.summary ?? "").toLowerCase().includes(filter.toLowerCase()),
)
: plans;
: statusFiltered;
const open = openIdx !== null ? plans[openIdx] : null;
@@ -71,12 +78,21 @@ export function PlansPanel() {
/>
</div>
<div class="chips" style="padding:0 12px 8px">
<span class="chip-f active">${t("common.all")} <span class="ct">${plans.length}</span></span>
<span class="chip-f">
<span
class=${`chip-f ${statusFilter === "all" ? "active" : ""}`}
onClick=${() => setStatusFilter("all")}
>${t("common.all")} <span class="ct">${plans.length}</span></span>
<span
class=${`chip-f ${statusFilter === "active" ? "active" : ""}`}
onClick=${() => setStatusFilter("active")}
>
${t("plans.active")}
<span class="ct">${plans.filter((p) => p.completionRatio > 0 && p.completionRatio < 1).length}</span>
</span>
<span class="chip-f">
<span
class=${`chip-f ${statusFilter === "done" ? "active" : ""}`}
onClick=${() => setStatusFilter("done")}
>
${t("plans.done")} <span class="ct">${plans.filter((p) => p.completionRatio >= 1).length}</span>
</span>
</div>
+4 -4
View File
@@ -179,13 +179,13 @@ export function SemanticPanel() {
<div style="display:grid;grid-template-columns:minmax(0,1fr) 280px;gap:14px;align-items:start">
<div style="display:flex;flex-direction:column;gap:10px;min-width:0">
<div class="chips">
<span class=${`chip-f ${idx?.exists ? "active" : ""}`}>
<span class=${`chip-f static ${idx?.exists ? "active" : ""}`}>
${idx?.exists ? t("semantic.indexBuilt") : t("semantic.noIndex")}
</span>
${
ready
? html`<span class="chip-f" style="border-color:var(--c-ok);color:var(--c-ok)">${t("semantic.ready")}</span>`
: html`<span class="chip-f" style="border-color:var(--c-warn);color:var(--c-warn)">${t("semantic.setupNeeded")}</span>`
? html`<span class="chip-f static" style="border-color:var(--c-ok);color:var(--c-ok)">${t("semantic.ready")}</span>`
: html`<span class="chip-f static" style="border-color:var(--c-warn);color:var(--c-warn)">${t("semantic.setupNeeded")}</span>`
}
</div>
${info ? html`<div><span class="pill info">${info}</span></div>` : null}
@@ -730,7 +730,7 @@ function ChipFormRow({
<div style="display:flex;flex-wrap:wrap;gap:4px">
${value.map(
(e) => html`
<span class="chip-f">
<span class="chip-f static">
<span>${e}</span>
<span class="x" style="cursor:pointer" onClick=${() => remove(e)} title="remove">×</span>
</span>
+1 -1
View File
@@ -68,7 +68,7 @@ export function SessionsPanel() {
/>
</div>
<div class="chips" style="padding:0 12px 8px">
<span class="chip-f active">${t("common.all")} <span class="ct">${sessions.length}</span></span>
<span class="chip-f static active">${t("common.all")} <span class="ct">${sessions.length}</span></span>
</div>
<div class="ssl-rows">
${filtered.map(
+21 -6
View File
@@ -29,6 +29,7 @@ export function SkillsPanel() {
const [newName, setNewName] = useState("");
const [newScope, setNewScope] = useState<"global" | "project">("global");
const [filter, setFilter] = useState("");
const [scopeFilter, setScopeFilter] = useState<"all" | Scope>("all");
const load = useCallback(async () => {
try {
@@ -120,13 +121,15 @@ export function SkillsPanel() {
...data.global.map((s) => ({ scope: "global" as Scope, ...s })),
...data.builtin.map((s) => ({ scope: "builtin" as Scope, ...s })),
];
const scopeFiltered =
scopeFilter === "all" ? allWith : allWith.filter((s) => s.scope === scopeFilter);
const filtered = filter.trim()
? allWith.filter(
? scopeFiltered.filter(
(s) =>
s.name.toLowerCase().includes(filter.toLowerCase()) ||
(s.description ?? "").toLowerCase().includes(filter.toLowerCase()),
)
: allWith;
: scopeFiltered;
return html`
<div class="sessions-grid">
@@ -141,10 +144,22 @@ export function SkillsPanel() {
/>
</div>
<div class="chips" style="padding:0 12px 8px">
<span class="chip-f active">${t("common.all")} <span class="ct">${allWith.length}</span></span>
<span class="chip-f">${t("skills.project")} <span class="ct">${data.project.length}</span></span>
<span class="chip-f">${t("skills.global")} <span class="ct">${data.global.length}</span></span>
<span class="chip-f">${t("skills.builtin")} <span class="ct">${data.builtin.length}</span></span>
<span
class=${`chip-f ${scopeFilter === "all" ? "active" : ""}`}
onClick=${() => setScopeFilter("all")}
>${t("common.all")} <span class="ct">${allWith.length}</span></span>
<span
class=${`chip-f ${scopeFilter === "project" ? "active" : ""}`}
onClick=${() => setScopeFilter("project")}
>${t("skills.project")} <span class="ct">${data.project.length}</span></span>
<span
class=${`chip-f ${scopeFilter === "global" ? "active" : ""}`}
onClick=${() => setScopeFilter("global")}
>${t("skills.global")} <span class="ct">${data.global.length}</span></span>
<span
class=${`chip-f ${scopeFilter === "builtin" ? "active" : ""}`}
onClick=${() => setScopeFilter("builtin")}
>${t("skills.builtin")} <span class="ct">${data.builtin.length}</span></span>
</div>
<div style="padding:0 12px 8px;display:flex;gap:6px;flex-wrap:wrap">
+2 -2
View File
@@ -37,8 +37,8 @@ export function ToolsPanel() {
return html`
<div style="display:flex;flex-direction:column;gap:14px">
<div class="chips">
<span class="chip-f active">${t("common.all")} <span class="ct">${d.total}</span></span>
${d.planMode ? html`<span class="chip-f" style="border-color:var(--c-warn);color:var(--c-warn)">${t("tools.planMode")}</span>` : null}
<span class="chip-f static active">${t("common.all")} <span class="ct">${d.total}</span></span>
${d.planMode ? html`<span class="chip-f static" style="border-color:var(--c-warn);color:var(--c-warn)">${t("tools.planMode")}</span>` : null}
</div>
${
+2 -2
View File
@@ -174,8 +174,8 @@ export function UsagePanel() {
return html`
<div style="display:flex;flex-direction:column;gap:6px">
<div class="chips">
<span class="chip-f active">${t("usage.records", { count: u.recordCount.toLocaleString() })}</span>
<span class="chip-f">${u.logSize}</span>
<span class="chip-f static active">${t("usage.records", { count: u.recordCount.toLocaleString() })}</span>
<span class="chip-f static">${u.logSize}</span>
</div>
${
+24 -1
View File
@@ -43,6 +43,29 @@ timestamps each turn — cache hit rate in practice: <20%.
**Metric.** `prompt_cache_hit_tokens / (hit + miss)` exposed per-turn and
aggregated per-session. Visible in the TUI's top-bar cache cell.
#### Parallel tool dispatch
Each tool declares `parallelSafe?: boolean` (default `false`). The loop
dispatcher groups consecutive parallel-safe calls into chunks and races
them via `Promise.allSettled`; the first non-parallel-safe call ends the
chunk and runs alone (serial barrier — read-after-write order
preserved). Tool-result yields and history append still land in declared
order regardless of which call settles first, so the model sees the
same shape it would under a fully serial dispatch.
| Env var | Default | Effect |
|---|---|---|
| `REASONIX_PARALLEL_MAX` | `3` (hard cap `16`) | Max chunk size. |
| `REASONIX_TOOL_DISPATCH=serial` | unset | Forces serial dispatch — escape hatch. |
Built-in opt-ins: read-only filesystem (`read_file`, `list_directory`,
`directory_tree`, `search_files`, `search_content`, `get_file_info`),
web (`web_search`, `web_fetch`), `recall_memory`, `semantic_search`,
isolated child loops (`run_skill`, `spawn_subagent`), in-memory job
queries (`job_output`, `list_jobs`). Mutating / side-effecting tools
stay default. MCP-bridged tools default `false` — third-party tools
opt in only when the server explicitly declares parallel safety.
### Pillar 2 — R1 Thought Harvesting *(opt-in)*
**Problem.** R1 / V4-thinking emits extensive `reasoning_content`. DeepSeek's
@@ -172,7 +195,7 @@ src/
│ ├── skills.ts # list + invoke SKILL.md playbooks
│ ├── subagent.ts # spawn_subagent — flash+high by default
│ ├── plan.ts # submit_plan (review gate)
│ └── web.ts # web_search, web_fetch
│ └── web.ts # web_search, web_fetch (multi-engine: Mojeek or SearXNG)
├── mcp/ # MCP client + bridge (stdio + SSE)
├── memory.ts # ImmutablePrefix / AppendOnlyLog / VolatileScratch
├── project-memory.ts # REASONIX.md loader
+80 -40
View File
@@ -1,10 +1,10 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 880 320" role="img" aria-label="Reasonix feature grid — six cards covering cache-first loop, plan mode, MCP, sessions, hooks, memory and skills">
<title>Reasonix feature grid</title>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 880 570" role="img" aria-label="Reasonix capability grid — twelve features covering renderer, MCP, plan mode, permissions, dashboard, sessions, hooks, semantic search, checkpoints, effort knob, replay, event log">
<title>Reasonix capabilities</title>
<defs>
<style>
.sans { font-family: "Inter", -apple-system, BlinkMacSystemFont, "Segoe UI", "Noto Sans SC", "Microsoft YaHei", sans-serif; }
.ic { font-family: "JetBrains Mono", ui-monospace, "Cascadia Code", Menlo, Consolas, monospace; }
.ttl { font-weight: 700; }
.sans { font-family: "Inter", -apple-system, BlinkMacSystemFont, "Segoe UI", "Noto Sans SC", "Microsoft YaHei", sans-serif; }
.mono { font-family: "JetBrains Mono", ui-monospace, "Cascadia Code", Menlo, Consolas, monospace; }
.ttl { font-weight: 700; }
</style>
<linearGradient id="ig" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" stop-color="#5eead4"/>
@@ -14,50 +14,90 @@
</defs>
<g transform="translate(10, 10)">
<rect width="280" height="140" rx="10" ry="10" fill="#0a0c10" stroke="#1e2436"/>
<text x="22" y="44" class="ic" font-size="24" fill="url(#ig)">◈</text>
<text x="56" y="42" class="sans ttl" font-size="15" fill="#e6edf3">Cache-first loop</text>
<text x="22" y="78" class="sans" font-size="13" fill="#8b949e">Byte-stable prompt prefix.</text>
<text x="22" y="98" class="sans" font-size="13" fill="#8b949e">94% live cache hit on tau-bench.</text>
<rect width="280" height="130" rx="10" ry="10" fill="#0a0c10" stroke="#1e2436"/>
<text x="22" y="42" class="mono" font-size="22" fill="url(#ig)">◈</text>
<text x="54" y="40" class="sans ttl" font-size="14" fill="#e6edf3">Cell-diff renderer</text>
<text x="22" y="72" class="sans" font-size="12" fill="#8b949e">Custom TUI on Yoga, no Ink.</text>
<text x="22" y="92" class="sans" font-size="12" fill="#8b949e">Wide-char · emoji · paste · resize-clean.</text>
</g>
<g transform="translate(300, 10)">
<rect width="280" height="140" rx="10" ry="10" fill="#0a0c10" stroke="#1e2436"/>
<text x="22" y="44" class="ic" font-size="24" fill="url(#ig)">✎</text>
<text x="56" y="42" class="sans ttl" font-size="15" fill="#e6edf3">Plan mode · edit review</text>
<text x="22" y="78" class="sans" font-size="13" fill="#8b949e">Read-only audit gate before</text>
<text x="22" y="98" class="sans" font-size="13" fill="#8b949e">writes. Nothing on disk until /apply.</text>
<rect width="280" height="130" rx="10" ry="10" fill="#0a0c10" stroke="#1e2436"/>
<text x="22" y="42" class="mono" font-size="22" fill="url(#ig)">⊕</text>
<text x="54" y="40" class="sans ttl" font-size="14" fill="#e6edf3">MCP first-class</text>
<text x="22" y="72" class="sans" font-size="12" fill="#8b949e">stdio · Streamable HTTP transports.</text>
<text x="22" y="92" class="sans" font-size="12" fill="#8b949e">Tools, resources, prompts.</text>
</g>
<g transform="translate(590, 10)">
<rect width="280" height="140" rx="10" ry="10" fill="#0a0c10" stroke="#1e2436"/>
<text x="22" y="44" class="ic" font-size="24" fill="url(#ig)">⊕</text>
<text x="56" y="42" class="sans ttl" font-size="15" fill="#e6edf3">MCP first-class</text>
<text x="22" y="78" class="sans" font-size="13" fill="#8b949e">stdio · SSE · Streamable HTTP.</text>
<text x="22" y="98" class="sans" font-size="13" fill="#8b949e">Same cache-safety as native tools.</text>
<rect width="280" height="130" rx="10" ry="10" fill="#0a0c10" stroke="#1e2436"/>
<text x="22" y="42" class="mono" font-size="22" fill="url(#ig)">✎</text>
<text x="54" y="40" class="sans ttl" font-size="14" fill="#e6edf3">Plan mode</text>
<text x="22" y="72" class="sans" font-size="12" fill="#8b949e">Review proposed edits before writes.</text>
<text x="22" y="92" class="sans" font-size="12" fill="#8b949e">Plan checkpoints persist across runs.</text>
</g>
<g transform="translate(10, 170)">
<rect width="280" height="140" rx="10" ry="10" fill="#0a0c10" stroke="#1e2436"/>
<text x="22" y="44" class="ic" font-size="24" fill="url(#ig)">⌨</text>
<text x="56" y="42" class="sans ttl" font-size="15" fill="#e6edf3">Sessions · dashboard</text>
<text x="22" y="78" class="sans" font-size="13" fill="#8b949e">Per-workspace persistent log.</text>
<text x="22" y="98" class="sans" font-size="13" fill="#8b949e">/dashboard opens a TUI mirror.</text>
<g transform="translate(10, 150)">
<rect width="280" height="130" rx="10" ry="10" fill="#0a0c10" stroke="#1e2436"/>
<text x="22" y="42" class="mono" font-size="22" fill="url(#ig)">⊞</text>
<text x="54" y="40" class="sans ttl" font-size="14" fill="#e6edf3">Permissions</text>
<text x="22" y="72" class="sans" font-size="12" fill="#8b949e">allow · ask · deny per tool.</text>
<text x="22" y="92" class="sans" font-size="12" fill="#8b949e">Granular shell rules. Teachable.</text>
</g>
<g transform="translate(300, 150)">
<rect width="280" height="130" rx="10" ry="10" fill="#0a0c10" stroke="#1e2436"/>
<text x="22" y="42" class="mono" font-size="22" fill="url(#ig)">▣</text>
<text x="54" y="40" class="sans ttl" font-size="14" fill="#e6edf3">Embedded dashboard</text>
<text x="22" y="72" class="sans" font-size="12" fill="#8b949e">Live cache hit · cost · session timeline</text>
<text x="22" y="92" class="sans" font-size="12" fill="#8b949e">· MCP health. localhost companion.</text>
</g>
<g transform="translate(590, 150)">
<rect width="280" height="130" rx="10" ry="10" fill="#0a0c10" stroke="#1e2436"/>
<text x="22" y="42" class="mono" font-size="22" fill="url(#ig)">⌨</text>
<text x="54" y="40" class="sans ttl" font-size="14" fill="#e6edf3">Persistent sessions</text>
<text x="22" y="72" class="sans" font-size="12" fill="#8b949e">Per-workspace, named, resumable.</text>
<text x="22" y="92" class="sans" font-size="12" fill="#8b949e">--resume restores state fully.</text>
</g>
<g transform="translate(300, 170)">
<rect width="280" height="140" rx="10" ry="10" fill="#0a0c10" stroke="#1e2436"/>
<text x="22" y="44" class="ic" font-size="24" fill="url(#ig)">⚙</text>
<text x="56" y="42" class="sans ttl" font-size="15" fill="#e6edf3">Hooks</text>
<text x="22" y="78" class="sans" font-size="13" fill="#8b949e">Shell scripts on Pre/Post tool.</text>
<text x="22" y="98" class="sans" font-size="13" fill="#8b949e">6 lifecycle events, harness-run.</text>
<g transform="translate(10, 290)">
<rect width="280" height="130" rx="10" ry="10" fill="#0a0c10" stroke="#1e2436"/>
<text x="22" y="42" class="mono" font-size="22" fill="url(#ig)">⚙</text>
<text x="54" y="40" class="sans ttl" font-size="14" fill="#e6edf3">Hooks · skills · memory</text>
<text x="22" y="72" class="sans" font-size="12" fill="#8b949e">Shell on lifecycle events.</text>
<text x="22" y="92" class="sans" font-size="12" fill="#8b949e">Skill packs + project memory.</text>
</g>
<g transform="translate(300, 290)">
<rect width="280" height="130" rx="10" ry="10" fill="#0a0c10" stroke="#1e2436"/>
<text x="22" y="42" class="mono" font-size="22" fill="url(#ig)">◎</text>
<text x="54" y="40" class="sans ttl" font-size="14" fill="#e6edf3">Semantic search</text>
<text x="22" y="72" class="sans" font-size="12" fill="#8b949e">reasonix index builds embeddings.</text>
<text x="22" y="92" class="sans" font-size="12" fill="#8b949e">Local Ollama or DeepSeek-hosted.</text>
</g>
<g transform="translate(590, 290)">
<rect width="280" height="130" rx="10" ry="10" fill="#0a0c10" stroke="#1e2436"/>
<text x="22" y="42" class="mono" font-size="22" fill="url(#ig)">↺</text>
<text x="54" y="40" class="sans ttl" font-size="14" fill="#e6edf3">Auto-checkpoints</text>
<text x="22" y="72" class="sans" font-size="12" fill="#8b949e">Cursor-style session-scoped rollback.</text>
<text x="22" y="92" class="sans" font-size="12" fill="#8b949e">Never pollutes git history.</text>
</g>
<g transform="translate(590, 170)">
<rect width="280" height="140" rx="10" ry="10" fill="#0a0c10" stroke="#1e2436"/>
<text x="22" y="44" class="ic" font-size="24" fill="url(#ig)"></text>
<text x="56" y="42" class="sans ttl" font-size="15" fill="#e6edf3">Memory · skills</text>
<text x="22" y="78" class="sans" font-size="13" fill="#8b949e">REASONIX.md + private user mem.</text>
<text x="22" y="98" class="sans" font-size="13" fill="#8b949e">Skill packs spawn sub-agents.</text>
<g transform="translate(10, 430)">
<rect width="280" height="130" rx="10" ry="10" fill="#0a0c10" stroke="#1e2436"/>
<text x="22" y="42" class="mono" font-size="22" fill="url(#ig)">◐</text>
<text x="54" y="40" class="sans ttl" font-size="14" fill="#e6edf3">/effort knob</text>
<text x="22" y="72" class="sans" font-size="12" fill="#8b949e">Switch reasoning depth per turn.</text>
<text x="22" y="92" class="sans" font-size="12" fill="#8b949e">Slash command and CLI flag.</text>
</g>
<g transform="translate(300, 430)">
<rect width="280" height="130" rx="10" ry="10" fill="#0a0c10" stroke="#1e2436"/>
<text x="22" y="42" class="mono" font-size="22" fill="url(#ig)">▶</text>
<text x="54" y="40" class="sans ttl" font-size="14" fill="#e6edf3">Transcript replay</text>
<text x="22" y="72" class="sans" font-size="12" fill="#8b949e">reasonix replay re-renders sessions.</text>
<text x="22" y="92" class="sans" font-size="12" fill="#8b949e">Bug reports, demos, audits.</text>
</g>
<g transform="translate(590, 430)">
<rect width="280" height="130" rx="10" ry="10" fill="#0a0c10" stroke="#1e2436"/>
<text x="22" y="42" class="mono" font-size="22" fill="url(#ig)"></text>
<text x="54" y="40" class="sans ttl" font-size="14" fill="#e6edf3">Event log</text>
<text x="22" y="72" class="sans" font-size="12" fill="#8b949e">events.jsonl sidecar + reducers.</text>
<text x="22" y="92" class="sans" font-size="12" fill="#8b949e">Build dashboards or analytics.</text>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 3.8 KiB

After

Width:  |  Height:  |  Size: 6.9 KiB

+80 -40
View File
@@ -1,10 +1,10 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 880 320" role="img" aria-label="Reasonix 功能一览 — 缓存优先循环、计划模式、MCP、会话、Hooks、Memory 与 Skills">
<title>Reasonix 功能一览</title>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 880 570" role="img" aria-label="Reasonix 能力一览 — 12 张卡片:渲染器、MCP、计划模式、权限、仪表盘、会话、Hooks、语义检索、checkpoint、effort 旋钮、重放、事件日志">
<title>Reasonix 能力一览</title>
<defs>
<style>
.sans { font-family: "Inter", -apple-system, BlinkMacSystemFont, "Segoe UI", "Noto Sans SC", "Microsoft YaHei", sans-serif; }
.ic { font-family: "JetBrains Mono", ui-monospace, "Cascadia Code", Menlo, Consolas, monospace; }
.ttl { font-weight: 700; }
.sans { font-family: "Inter", -apple-system, BlinkMacSystemFont, "Segoe UI", "Noto Sans SC", "Microsoft YaHei", sans-serif; }
.mono { font-family: "JetBrains Mono", ui-monospace, "Cascadia Code", Menlo, Consolas, monospace; }
.ttl { font-weight: 700; }
</style>
<linearGradient id="ig" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" stop-color="#5eead4"/>
@@ -14,50 +14,90 @@
</defs>
<g transform="translate(10, 10)">
<rect width="280" height="140" rx="10" ry="10" fill="#0a0c10" stroke="#1e2436"/>
<text x="22" y="44" class="ic" font-size="24" fill="url(#ig)">◈</text>
<text x="56" y="42" class="sans ttl" font-size="15" fill="#e6edf3">缓存优先的循环</text>
<text x="22" y="78" class="sans" font-size="13" fill="#8b949e">prompt 前缀字节稳定。</text>
<text x="22" y="98" class="sans" font-size="13" fill="#8b949e">tau-bench 上 94% 实测命中。</text>
<rect width="280" height="130" rx="10" ry="10" fill="#0a0c10" stroke="#1e2436"/>
<text x="22" y="42" class="mono" font-size="22" fill="url(#ig)">◈</text>
<text x="54" y="40" class="sans ttl" font-size="14" fill="#e6edf3">自研 cell-diff 渲染器</text>
<text x="22" y="72" class="sans" font-size="12" fill="#8b949e">基于 Yoga,不依赖 Ink。</text>
<text x="22" y="92" class="sans" font-size="12" fill="#8b949e">宽字符 · emoji · 粘贴 · resize 全干净。</text>
</g>
<g transform="translate(300, 10)">
<rect width="280" height="140" rx="10" ry="10" fill="#0a0c10" stroke="#1e2436"/>
<text x="22" y="44" class="ic" font-size="24" fill="url(#ig)">✎</text>
<text x="56" y="42" class="sans ttl" font-size="15" fill="#e6edf3">计划模式 · 编辑审查</text>
<text x="22" y="78" class="sans" font-size="13" fill="#8b949e">写盘前先过只读审计闸。</text>
<text x="22" y="98" class="sans" font-size="13" fill="#8b949e">不 /apply 一行都不改。</text>
<rect width="280" height="130" rx="10" ry="10" fill="#0a0c10" stroke="#1e2436"/>
<text x="22" y="42" class="mono" font-size="22" fill="url(#ig)">⊕</text>
<text x="54" y="40" class="sans ttl" font-size="14" fill="#e6edf3">MCP 一等公民</text>
<text x="22" y="72" class="sans" font-size="12" fill="#8b949e">stdio · Streamable HTTP 双传输。</text>
<text x="22" y="92" class="sans" font-size="12" fill="#8b949e">工具 / 资源 / 提示词全套。</text>
</g>
<g transform="translate(590, 10)">
<rect width="280" height="140" rx="10" ry="10" fill="#0a0c10" stroke="#1e2436"/>
<text x="22" y="44" class="ic" font-size="24" fill="url(#ig)">⊕</text>
<text x="56" y="42" class="sans ttl" font-size="15" fill="#e6edf3">MCP 一等公民</text>
<text x="22" y="78" class="sans" font-size="13" fill="#8b949e">stdio · SSE · Streamable HTTP。</text>
<text x="22" y="98" class="sans" font-size="13" fill="#8b949e">和原生工具一样保缓存。</text>
<rect width="280" height="130" rx="10" ry="10" fill="#0a0c10" stroke="#1e2436"/>
<text x="22" y="42" class="mono" font-size="22" fill="url(#ig)">✎</text>
<text x="54" y="40" class="sans ttl" font-size="14" fill="#e6edf3">计划模式</text>
<text x="22" y="72" class="sans" font-size="12" fill="#8b949e">修改在落盘前先 review。</text>
<text x="22" y="92" class="sans" font-size="12" fill="#8b949e">Plan checkpoint 跨运行持久化。</text>
</g>
<g transform="translate(10, 170)">
<rect width="280" height="140" rx="10" ry="10" fill="#0a0c10" stroke="#1e2436"/>
<text x="22" y="44" class="ic" font-size="24" fill="url(#ig)">⌨</text>
<text x="56" y="42" class="sans ttl" font-size="15" fill="#e6edf3">会话 · 仪表盘</text>
<text x="22" y="78" class="sans" font-size="13" fill="#8b949e">按工作区持久化日志。</text>
<text x="22" y="98" class="sans" font-size="13" fill="#8b949e">/dashboard 开浏览器镜像 TUI。</text>
<g transform="translate(10, 150)">
<rect width="280" height="130" rx="10" ry="10" fill="#0a0c10" stroke="#1e2436"/>
<text x="22" y="42" class="mono" font-size="22" fill="url(#ig)">⊞</text>
<text x="54" y="40" class="sans ttl" font-size="14" fill="#e6edf3">权限系统</text>
<text x="22" y="72" class="sans" font-size="12" fill="#8b949e">每个工具 allow / ask / deny。</text>
<text x="22" y="92" class="sans" font-size="12" fill="#8b949e">shell 命令粒度规则,可教。</text>
</g>
<g transform="translate(300, 150)">
<rect width="280" height="130" rx="10" ry="10" fill="#0a0c10" stroke="#1e2436"/>
<text x="22" y="42" class="mono" font-size="22" fill="url(#ig)">▣</text>
<text x="54" y="40" class="sans ttl" font-size="14" fill="#e6edf3">内嵌仪表盘</text>
<text x="22" y="72" class="sans" font-size="12" fill="#8b949e">实时缓存命中、成本、会话时间线、</text>
<text x="22" y="92" class="sans" font-size="12" fill="#8b949e">MCP 健康。localhost 伴生面板。</text>
</g>
<g transform="translate(590, 150)">
<rect width="280" height="130" rx="10" ry="10" fill="#0a0c10" stroke="#1e2436"/>
<text x="22" y="42" class="mono" font-size="22" fill="url(#ig)">⌨</text>
<text x="54" y="40" class="sans ttl" font-size="14" fill="#e6edf3">持久化会话</text>
<text x="22" y="72" class="sans" font-size="12" fill="#8b949e">按工作区组织、命名、可恢复。</text>
<text x="22" y="92" class="sans" font-size="12" fill="#8b949e">--resume 完全还原状态。</text>
</g>
<g transform="translate(300, 170)">
<rect width="280" height="140" rx="10" ry="10" fill="#0a0c10" stroke="#1e2436"/>
<text x="22" y="44" class="ic" font-size="24" fill="url(#ig)">⚙</text>
<text x="56" y="42" class="sans ttl" font-size="15" fill="#e6edf3">Hooks</text>
<text x="22" y="78" class="sans" font-size="13" fill="#8b949e">Pre/Post tool 时跑 shell 脚本。</text>
<text x="22" y="98" class="sans" font-size="13" fill="#8b949e">6 个生命周期事件,由 harness 触发。</text>
<g transform="translate(10, 290)">
<rect width="280" height="130" rx="10" ry="10" fill="#0a0c10" stroke="#1e2436"/>
<text x="22" y="42" class="mono" font-size="22" fill="url(#ig)">⚙</text>
<text x="54" y="40" class="sans ttl" font-size="14" fill="#e6edf3">Hooks · Skills · Memory</text>
<text x="22" y="72" class="sans" font-size="12" fill="#8b949e">生命周期事件触发 shell。</text>
<text x="22" y="92" class="sans" font-size="12" fill="#8b949e">Skill 包 + 项目级 memory。</text>
</g>
<g transform="translate(300, 290)">
<rect width="280" height="130" rx="10" ry="10" fill="#0a0c10" stroke="#1e2436"/>
<text x="22" y="42" class="mono" font-size="22" fill="url(#ig)">◎</text>
<text x="54" y="40" class="sans ttl" font-size="14" fill="#e6edf3">语义检索</text>
<text x="22" y="72" class="sans" font-size="12" fill="#8b949e">reasonix index 构建 embedding 索引。</text>
<text x="22" y="92" class="sans" font-size="12" fill="#8b949e">本地 Ollama 或 DeepSeek 托管。</text>
</g>
<g transform="translate(590, 290)">
<rect width="280" height="130" rx="10" ry="10" fill="#0a0c10" stroke="#1e2436"/>
<text x="22" y="42" class="mono" font-size="22" fill="url(#ig)">↺</text>
<text x="54" y="40" class="sans ttl" font-size="14" fill="#e6edf3">自动 checkpoint</text>
<text x="22" y="72" class="sans" font-size="12" fill="#8b949e">Cursor 风格会话级 AI 编辑回滚。</text>
<text x="22" y="92" class="sans" font-size="12" fill="#8b949e">不污染 git 历史。</text>
</g>
<g transform="translate(590, 170)">
<rect width="280" height="140" rx="10" ry="10" fill="#0a0c10" stroke="#1e2436"/>
<text x="22" y="44" class="ic" font-size="24" fill="url(#ig)"></text>
<text x="56" y="42" class="sans ttl" font-size="15" fill="#e6edf3">Memory · Skills</text>
<text x="22" y="78" class="sans" font-size="13" fill="#8b949e">REASONIX.md 加用户私有 memory。</text>
<text x="22" y="98" class="sans" font-size="13" fill="#8b949e">Skill 包可起 sub-agent 执行。</text>
<g transform="translate(10, 430)">
<rect width="280" height="130" rx="10" ry="10" fill="#0a0c10" stroke="#1e2436"/>
<text x="22" y="42" class="mono" font-size="22" fill="url(#ig)">◐</text>
<text x="54" y="40" class="sans ttl" font-size="14" fill="#e6edf3">/effort 旋钮</text>
<text x="22" y="72" class="sans" font-size="12" fill="#8b949e">每回合切换 reasoning 深度。</text>
<text x="22" y="92" class="sans" font-size="12" fill="#8b949e">斜杠命令 + CLI flag 双入口。</text>
</g>
<g transform="translate(300, 430)">
<rect width="280" height="130" rx="10" ry="10" fill="#0a0c10" stroke="#1e2436"/>
<text x="22" y="42" class="mono" font-size="22" fill="url(#ig)">▶</text>
<text x="54" y="40" class="sans ttl" font-size="14" fill="#e6edf3">Transcript 重放</text>
<text x="22" y="72" class="sans" font-size="12" fill="#8b949e">reasonix replay 重渲染会话。</text>
<text x="22" y="92" class="sans" font-size="12" fill="#8b949e">bug 复现、演示、审计。</text>
</g>
<g transform="translate(590, 430)">
<rect width="280" height="130" rx="10" ry="10" fill="#0a0c10" stroke="#1e2436"/>
<text x="22" y="42" class="mono" font-size="22" fill="url(#ig)"></text>
<text x="54" y="40" class="sans ttl" font-size="14" fill="#e6edf3">事件日志</text>
<text x="22" y="72" class="sans" font-size="12" fill="#8b949e">events.jsonl 旁路日志 + reducer。</text>
<text x="22" y="92" class="sans" font-size="12" fill="#8b949e">自建仪表盘或分析。</text>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 3.8 KiB

After

Width:  |  Height:  |  Size: 7.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 430 KiB

+54
View File
@@ -0,0 +1,54 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1280 640" role="img" aria-label="Reasonix — DeepSeek-native AI coding agent for your terminal">
<title>Reasonix social card</title>
<defs>
<style>
.mono { font-family: Consolas, "Courier New", monospace; font-weight: 500; }
.sans { font-family: "Segoe UI", Arial, sans-serif; }
</style>
<linearGradient id="brand" x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0%" stop-color="#5eead4"/>
<stop offset="50%" stop-color="#93c5fd"/>
<stop offset="100%" stop-color="#c4b5fd"/>
</linearGradient>
<linearGradient id="bgfade" x1="0%" y1="0%" x2="0%" y2="100%">
<stop offset="0%" stop-color="#0a0c10"/>
<stop offset="100%" stop-color="#11141a"/>
</linearGradient>
<pattern id="grid" width="32" height="32" patternUnits="userSpaceOnUse">
<path d="M 32 0 L 0 0 0 32" fill="none" stroke="#1e2436" stroke-width="0.5"/>
</pattern>
</defs>
<rect width="1280" height="640" fill="url(#bgfade)"/>
<rect width="1280" height="640" fill="url(#grid)" opacity="0.4"/>
<g transform="translate(80, 96)">
<text class="sans" font-size="22" font-weight="600" letter-spacing="6" fill="#5eead4" opacity="0.85">REASONIX</text>
<text y="100" class="sans" font-size="84" font-weight="800" fill="#e6edf3" letter-spacing="-2">DeepSeek-native</text>
<text y="184" class="sans" font-size="84" font-weight="800" fill="url(#brand)" letter-spacing="-2">AI coding agent.</text>
<text y="244" class="sans" font-size="26" fill="#8b949e">Engineered around prefix-cache stability — leave it running.</text>
</g>
<g transform="translate(80, 432)">
<rect x="0" y="0" width="1120" height="128" rx="10" fill="#0d1117" stroke="#1e2436"/>
<circle cx="22" cy="20" r="6" fill="#ff8b81"/>
<circle cx="42" cy="20" r="6" fill="#f0b07d"/>
<circle cx="62" cy="20" r="6" fill="#7ee787"/>
<text x="560" y="25" text-anchor="middle" class="mono" font-size="12" fill="url(#brand)">reasonix code</text>
<line x1="0" y1="40" x2="1120" y2="40" stroke="#1e2436"/>
<g class="mono" font-size="18">
<text x="20" y="74"><tspan fill="#79c0ff">›</tspan><tspan fill="#c9d1d9" xml:space="preserve"> fix the case-sensitivity bug in findByEmail</tspan></text>
<text x="20" y="106"><tspan fill="#7ee787">+</tspan><tspan fill="#8b949e" xml:space="preserve"> queued: src/users.ts (1 edit) · </tspan><tspan fill="#d2a8ff">/apply</tspan><tspan fill="#8b949e" xml:space="preserve"> to commit</tspan></text>
</g>
</g>
<g transform="translate(80, 360)" class="sans" font-size="16" fill="#8b949e">
<text>
<tspan fill="#5eead4">●</tspan> Cache-First Loop
<tspan dx="24" fill="#93c5fd">●</tspan> R1 Thought Harvesting
<tspan dx="24" fill="#c4b5fd">●</tspan> Tool-Call Repair
</text>
</g>
<text x="1200" y="600" text-anchor="end" class="mono" font-size="14" fill="#484f58">github.com/esengine/reasonix</text>
</svg>

After

Width:  |  Height:  |  Size: 2.9 KiB

+52
View File
@@ -0,0 +1,52 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 880 360" role="img" aria-label="Reasonix four pillars — cache-first loop, R1 thought harvesting, tool-call repair, cost control">
<title>Reasonix four pillars</title>
<defs>
<style>
.sans { font-family: "Inter", -apple-system, BlinkMacSystemFont, "Segoe UI", "Noto Sans SC", "Microsoft YaHei", sans-serif; }
.mono { font-family: "JetBrains Mono", ui-monospace, "Cascadia Code", Menlo, Consolas, monospace; }
.ttl { font-weight: 700; }
.num { font-weight: 800; letter-spacing: 0.08em; }
</style>
<linearGradient id="ig" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" stop-color="#5eead4"/>
<stop offset="50%" stop-color="#93c5fd"/>
<stop offset="100%" stop-color="#c4b5fd"/>
</linearGradient>
</defs>
<g transform="translate(10, 10)">
<rect width="420" height="160" rx="12" ry="12" fill="#0a0c10" stroke="#1e2436"/>
<text x="24" y="42" class="mono num" font-size="13" fill="url(#ig)">01 /</text>
<text x="24" y="74" class="sans ttl" font-size="20" fill="#e6edf3">Cache-first loop</text>
<text x="24" y="106" class="sans" font-size="13" fill="#8b949e">Append-only history with no in-place</text>
<text x="24" y="124" class="sans" font-size="13" fill="#8b949e">mutation. Byte prefix survives every tool</text>
<text x="24" y="142" class="sans" font-size="13" fill="#8b949e">call — the cache keeps hitting.</text>
</g>
<g transform="translate(450, 10)">
<rect width="420" height="160" rx="12" ry="12" fill="#0a0c10" stroke="#1e2436"/>
<text x="24" y="42" class="mono num" font-size="13" fill="url(#ig)">02 /</text>
<text x="24" y="74" class="sans ttl" font-size="20" fill="#e6edf3">R1 thought harvesting</text>
<text x="24" y="106" class="sans" font-size="13" fill="#8b949e">Distills reasoning_content into typed plan</text>
<text x="24" y="124" class="sans" font-size="13" fill="#8b949e">state — subgoals, hypotheses, rejected paths.</text>
<text x="24" y="142" class="sans" font-size="13" fill="#8b949e">Signal kept, noise dropped.</text>
</g>
<g transform="translate(10, 190)">
<rect width="420" height="160" rx="12" ry="12" fill="#0a0c10" stroke="#1e2436"/>
<text x="24" y="42" class="mono num" font-size="13" fill="url(#ig)">03 /</text>
<text x="24" y="74" class="sans ttl" font-size="20" fill="#e6edf3">Tool-call repair</text>
<text x="24" y="106" class="sans" font-size="13" fill="#8b949e">Schema flatten · JSON repair · scavenge from</text>
<text x="24" y="124" class="sans" font-size="13" fill="#8b949e">&lt;think&gt; · truncation. Four strategies for</text>
<text x="24" y="142" class="sans" font-size="13" fill="#8b949e">DeepSeek-specific quirks.</text>
</g>
<g transform="translate(450, 190)">
<rect width="420" height="160" rx="12" ry="12" fill="#0a0c10" stroke="#1e2436"/>
<text x="24" y="42" class="mono num" font-size="13" fill="url(#ig)">04 /</text>
<text x="24" y="74" class="sans ttl" font-size="20" fill="#e6edf3">Cost control</text>
<text x="24" y="106" class="sans" font-size="13" fill="#8b949e">Cache-safe folding · aggressive-fold tier ·</text>
<text x="24" y="124" class="sans" font-size="13" fill="#8b949e">model-aware budgets. Context size managed</text>
<text x="24" y="142" class="sans" font-size="13" fill="#8b949e">without breaking prefix.</text>
</g>
</svg>

After

Width:  |  Height:  |  Size: 3.4 KiB

+52
View File
@@ -0,0 +1,52 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 880 360" role="img" aria-label="Reasonix 四大支柱 — 缓存优先循环、R1 思维提取、工具调用修复、成本控制">
<title>Reasonix 四大支柱</title>
<defs>
<style>
.sans { font-family: "Inter", -apple-system, BlinkMacSystemFont, "Segoe UI", "Noto Sans SC", "Microsoft YaHei", sans-serif; }
.mono { font-family: "JetBrains Mono", ui-monospace, "Cascadia Code", Menlo, Consolas, monospace; }
.ttl { font-weight: 700; }
.num { font-weight: 800; letter-spacing: 0.08em; }
</style>
<linearGradient id="ig" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" stop-color="#5eead4"/>
<stop offset="50%" stop-color="#93c5fd"/>
<stop offset="100%" stop-color="#c4b5fd"/>
</linearGradient>
</defs>
<g transform="translate(10, 10)">
<rect width="420" height="160" rx="12" ry="12" fill="#0a0c10" stroke="#1e2436"/>
<text x="24" y="42" class="mono num" font-size="13" fill="url(#ig)">01 /</text>
<text x="24" y="74" class="sans ttl" font-size="20" fill="#e6edf3">缓存优先循环</text>
<text x="24" y="106" class="sans" font-size="13" fill="#8b949e">只追加历史,不就地修改。字节前缀</text>
<text x="24" y="124" class="sans" font-size="13" fill="#8b949e">跨过每一次工具调用都活着 ——</text>
<text x="24" y="142" class="sans" font-size="13" fill="#8b949e">命中率持续。</text>
</g>
<g transform="translate(450, 10)">
<rect width="420" height="160" rx="12" ry="12" fill="#0a0c10" stroke="#1e2436"/>
<text x="24" y="42" class="mono num" font-size="13" fill="url(#ig)">02 /</text>
<text x="24" y="74" class="sans ttl" font-size="20" fill="#e6edf3">R1 思维提取</text>
<text x="24" y="106" class="sans" font-size="13" fill="#8b949e">把 reasoning_content 蒸馏成结构化</text>
<text x="24" y="124" class="sans" font-size="13" fill="#8b949e">plan state —— 子目标、假设、被否决</text>
<text x="24" y="142" class="sans" font-size="13" fill="#8b949e">的路径。留信号,去噪声。</text>
</g>
<g transform="translate(10, 190)">
<rect width="420" height="160" rx="12" ry="12" fill="#0a0c10" stroke="#1e2436"/>
<text x="24" y="42" class="mono num" font-size="13" fill="url(#ig)">03 /</text>
<text x="24" y="74" class="sans ttl" font-size="20" fill="#e6edf3">工具调用修复</text>
<text x="24" y="106" class="sans" font-size="13" fill="#8b949e">Schema 扁平化 · JSON 修复 · &lt;think&gt;</text>
<text x="24" y="124" class="sans" font-size="13" fill="#8b949e">内 scavenge · 截断处理。四种策略</text>
<text x="24" y="142" class="sans" font-size="13" fill="#8b949e">对付 DeepSeek 专属怪癖。</text>
</g>
<g transform="translate(450, 190)">
<rect width="420" height="160" rx="12" ry="12" fill="#0a0c10" stroke="#1e2436"/>
<text x="24" y="42" class="mono num" font-size="13" fill="url(#ig)">04 /</text>
<text x="24" y="74" class="sans ttl" font-size="20" fill="#e6edf3">成本控制</text>
<text x="24" y="106" class="sans" font-size="13" fill="#8b949e">缓存安全 fold · 激进 fold 层 ·</text>
<text x="24" y="124" class="sans" font-size="13" fill="#8b949e">模型感知预算。管上下文规模</text>
<text x="24" y="142" class="sans" font-size="13" fill="#8b949e">不破坏前缀。</text>
</g>
</svg>

After

Width:  |  Height:  |  Size: 3.4 KiB

+190 -122
View File
@@ -11,23 +11,27 @@
const translations = {
en: {
"nav.why": "Why",
"nav.features": "Features",
"nav.quickstart": "Quick start",
"nav.benchmarks": "Benchmarks",
"nav.community": "Community",
"nav.github": "GitHub",
"hero.badge": "v{version} · DeepSeek V4 · cache-first",
"hero.badge": "v{version} · DeepSeek · cache-first · MIT",
"hero.title.line1": "DeepSeek-native",
"hero.title.line2": "AI coding agent in your terminal",
"hero.sub":
"Cache-first agent loop for DeepSeek V4 (flash + pro). Edits files as reviewable SEARCH/REPLACE blocks. Ink TUI. MCP first-class. No LangChain.",
"Engineered around DeepSeek's prefix-cache so token costs stay low across long sessions. Custom cell-diff renderer. MCP first-class. Open source.",
"hero.copy": "Copy",
"hero.copy.done": "Copied",
"hero.cta.start": "Get started →",
"hero.cta.star": "Star on GitHub",
"hero.stat.cache": "prefix cache hit rate",
"hero.stat.cost": "cheaper vs Claude Sonnet 4.6",
"hero.stat.pass": "τ-bench-lite pass rate",
"hero.stat.cache.num": "Cache-engineered",
"hero.stat.cache": "Byte-stable prefix loop",
"hero.stat.lic.num": "Open source",
"hero.stat.lic": "MIT, community-developed",
"hero.stat.tui.num": "Terminal-native",
"hero.stat.tui": "Plus embedded dashboard",
"term.user":
"users.ts findByEmail is case-sensitive — login fails for users with uppercase emails",
@@ -37,25 +41,25 @@
"why.title": "Why Reasonix",
"why.sub":
"Every abstraction earns its weight against a DeepSeek-specific property — dirt-cheap tokens, R1 traces, automatic prefix caching, JSON mode. Generic wrappers leave these on the table.",
"The loop is organized around four architectural pillars. Each one solves a problem generic agent frameworks don't even see — because they were designed for a different cache mechanic.",
"why.cache.title": "Cache-first loop",
"why.cache.body":
"Append-only conversation log keeps the prompt prefix byte-stable across turns, so DeepSeek's automatic cache hits 85–95% — not 40%.",
"why.cost.title": "Cost is a pillar",
"Append-only history. No in-place mutation, no marker-based compaction. The byte prefix survives every tool call — DeepSeek's prefix-cache keeps hitting turn after turn.",
"why.r1.title": "R1 thought harvesting",
"why.r1.body":
"Distills <code>reasoning_content</code> into a typed plan state — subgoals, hypotheses, uncertainties, rejected paths. Signal kept, noise dropped.",
"why.repair.title": "Tool-call repair",
"why.repair.body":
"Schema flatten · JSON repair · scavenge from <code>&lt;think&gt;</code> · truncation. Four strategies that handle DeepSeek-specific quirks generic loops mistake for model errors.",
"why.cost.title": "Cost control",
"why.cost.body":
"Flash-first defaults, turn-end auto-compaction, model self-escalation when (and only when) needed. Per-turn cost badge in the TUI.",
"why.tui.title": "Ink TUI, no web",
"why.tui.body":
"Lives in your terminal. Streaming preview, slash commands, plan picker, edit-confirm modal. Plain mode for stubborn Windows shells.",
"why.mcp.title": "MCP first-class",
"why.mcp.body":
"Stdio + HTTP+SSE transports. Live progress notifications. Same cache-safety + repair plumbing as native tools.",
"why.safe.title": "Reviewable edits",
"why.safe.body":
"Edits arrive as SEARCH/REPLACE blocks; nothing hits disk until /apply. Per-file diff confirm modal, undo history, sandboxed paths.",
"why.ctx.title": "1M-token aware",
"why.ctx.body":
"Context gauge with proactive compaction, oversized tool-result repair, forced-summary fallback near the window edge.",
"Cache-safe folding · aggressive-fold tier · summary-on-exit · model-aware budgets. The loop manages context size without breaking prefix stability.",
"why.deepseek.title": "DeepSeek-only by design",
"why.deepseek.body":
"Every layer is tuned around DeepSeek's specific cache mechanic and pricing. Coupling to one backend is the feature, not a limitation.",
"why.oss.title": "Open community",
"why.oss.body":
"MIT licensed and community-developed. Scoped <code>good first issue</code> tickets with code pointers and acceptance criteria. Real PRs from real contributors.",
"qs.title": "Quick start (60 seconds)",
"qs.step1.title": "Get a DeepSeek API key",
@@ -64,63 +68,91 @@
"qs.step2.title": "Point it at a project",
"qs.step2.body": "No install needed.",
"qs.step2.note":
"First run walks you through a 30-second wizard (paste API key → pick preset → pick MCP servers).",
"qs.step3.title": "Ask it to edit",
"First run walks you through a short wizard — paste API key, pick a preset, optionally attach MCP servers.",
"qs.step3.title": "Review and apply",
"qs.step3.body":
"The model proposes edits as SEARCH/REPLACE blocks — nothing hits disk until you <code>/apply</code>.",
"The agent proposes edits as reviewable blocks — nothing hits disk until you <code>/apply</code>. Plan mode lets you stage multi-file changes before committing any.",
"qs.req":
"Requires Node ≥ 22. macOS, Linux, Windows (PowerShell · Git Bash · Windows Terminal). Press <kbd>Esc</kbd> anytime to abort; <code>/help</code> for the full command list.",
"Requires Node ≥ 22. macOS, Linux, Windows (PowerShell · Git Bash · Windows Terminal). Press <kbd>Esc</kbd> anytime to abort; <code>/help</code> for the full slash-command list.",
"feat.title": "In the box",
"feat.code.title": "Pair programmer mode",
"feat.code.body":
"<code>read_file</code> · <code>write_file</code> · <code>edit_file</code> · <code>search_files</code> · <code>directory_tree</code> · <code>run_command</code> with read-only allowlist. Sandboxed to the launch root — no path escapes. Plan mode and per-edit review modal.",
"feat.memory.title": "Two-layer memory",
"feat.memory.body":
"Committable <code>REASONIX.md</code> for team conventions plus a private per-user <code>~/.reasonix/memory/</code> with global and per-project scopes. The model can write to it via the <code>remember</code> tool.",
"feat.skills.title": "User-authored prompt packs",
"feat.skills.body":
"Drop <code>SKILL.md</code> files anywhere. Names + descriptions are pinned in the prefix; the model picks them autonomously, or you trigger with <code>/skill name</code>.",
"feat.hooks.title": "Lifecycle hooks",
"feat.hooks.body":
"Shell commands fire at <code>PreToolUse</code> · <code>PostToolUse</code> · <code>UserPromptSubmit</code> · <code>Stop</code>. Exit code drives pass / block / warn.",
"feat.mcp.title": "Bring your own tools",
"feat.sub":
"Twelve concrete capabilities. The loop is the foundation; everything below is what you get on top of it.",
"feat.renderer.title": "Cell-diff renderer",
"feat.renderer.body":
"Custom TUI runtime built on Yoga. No Ink dependency. Wide-char, emoji, bracketed paste, and resize handled cleanly across platforms.",
"feat.mcp.title": "MCP first-class",
"feat.mcp.body":
'Wizard catalog, or <code>--mcp "name=cmd"</code> to attach stdio / HTTP+SSE servers on the fly. Live progress bars on long calls.',
"feat.web.title": "Web search built-in",
"feat.web.body":
"<code>web_search</code> + <code>web_fetch</code> via Mojeek — no key, no signup, off-by-flag for offline / CI. Bring-your-own provider via the <code>WebSearchProvider</code> interface.",
'Stdio and Streamable HTTP transports. Tools, resources, and prompts. In-app browser to inspect any server\'s surface, plus <code>--mcp "name=cmd"</code> on the fly.',
"feat.plan.title": "Plan mode",
"feat.plan.body":
"Review proposed edits before they touch disk. Approve, refine, or reject. Plan checkpoints persist across runs so you can resume mid-review.",
"feat.perm.title": "Permissions",
"feat.perm.body":
"<code>allow</code> · <code>ask</code> · <code>deny</code> per-tool. Granular shell command rules. Interactive prompts you can teach.",
"feat.dash.title": "Embedded dashboard",
"feat.dash.body":
"Companion web view at <code>localhost</code>. Live cache hit rate, cost ticker, session timeline, MCP health — all in one place.",
"feat.sess.title": "Persistent sessions",
"feat.sess.body":
"Per-workspace, named, resumable. <code>--resume</code> picks up exactly where you left off — system prompt, history, plan state.",
"feat.hooks.title": "Hooks · skills · memory",
"feat.hooks.body":
"Shell commands fire on lifecycle events. Drop-in skill packs spawn sub-agents. Project memory the agent reads on every turn.",
"feat.search.title": "Semantic search",
"feat.search.body":
"<code>reasonix index</code> builds an embedding index your agent can query. Local Ollama or DeepSeek-hosted embeddings.",
"feat.ckpt.title": "Auto-checkpoints",
"feat.ckpt.body":
"Cursor-style session-scoped rollback for AI edits. Never pollutes git history; the checkpoint stack is yours alone.",
"feat.effort.title": "<code>/effort</code> knob",
"feat.effort.body":
"Switch reasoning depth per turn. <code>max</code> for the gnarly, <code>low</code> for routine. Slash command and CLI flag.",
"feat.replay.title": "Transcript replay",
"feat.replay.body":
"<code>reasonix replay</code> plays a recorded session back through the renderer — useful for bug reports, demos, and audits.",
"feat.events.title": "Event log",
"feat.events.body":
"<code>events.jsonl</code> sidecar with reducers and a <code>reasonix events</code> CLI. Build dashboards, audits, or your own analytics.",
"bench.title": "Verify the cache claim yourself",
"bench.sub":
"On the same τ-bench-lite workload (8 multi-turn tool-use tasks × 3 repeats = 48 runs per side), live DeepSeek <code>deepseek-chat</code>, sole variable prefix stability:",
"bench.col.metric": "metric",
"bench.col.baseline": "baseline (cache-hostile)",
"bench.col.reasonix": "Reasonix",
"bench.col.delta": "delta",
"bench.row.cache": "cache hit",
"bench.row.cost": "cost / task",
"bench.row.pass": "pass rate",
"bench.repro.intro": "Reproduce without spending an API credit:",
"We don't ship benchmark numbers in marketing copy — they move with model pricing and harness changes, so they live with the harness instead of the README. Reproduce on your own machine:",
"bench.repro.note":
"The committed JSONL transcripts carry per-turn <code>usage</code>, <code>cost</code>, and <code>prefixHash</code>. Reasonix's prefix hash stays byte-stable across every model call.",
"Each committed JSONL transcript carries per-turn <code>usage</code>, <code>cost</code>, and <code>prefixHash</code>. Reasonix's prefix hash stays byte-stable across every model call — that's the whole game.",
"bench.link": "Read the τ-bench-lite harness →",
"cli.title": "CLI at a glance",
"cli.code": "coding mode scoped to path",
"cli.chat": "chat (uses saved config)",
"cli.setup": "reconfigure the wizard",
"cli.chat": "interactive chat (saved config)",
"cli.run": "one-shot, streams to stdout",
"cli.stats": "cross-session cost dashboard",
"cli.mcp": "probe a single MCP server",
"cli.doctor": "environment health check",
"cli.replay": "re-render a recorded session",
"cli.diff": "compare two transcripts",
"cli.events": "query the event log",
"cli.stats": "cross-session usage",
"cli.index": "build semantic embedding index",
"cli.mcp": "probe one MCP server",
"cli.mcplist": "list configured MCP servers",
"cli.prune": "clean up old sessions",
"cli.flags.intro": "Common flags:",
"cli.f.preset": "model + harvest + branch bundle",
"cli.f.effort": "reasoning depth for the run",
"cli.f.model": "explicit DeepSeek model id",
"cli.f.mcp": "attach an MCP server (repeatable)",
"cli.f.session": "named session",
"cli.f.resume": "pick up the latest session for this workspace",
"cli.f.new": "force a fresh session, preserve old",
"cli.f.noconf": "ignore ~/.reasonix/config.json (CI)",
"comm.title": "Built by the community",
"comm.sub":
"Reasonix is open source and community-developed. Every avatar on the wall below is a real PR that shipped — not a sponsorship slot.",
"comm.gfi": "good first issue →",
"comm.disc": "Discussions",
"comm.contrib": "Contributing guide",
"ctab.title": "Ready to try?",
"ctab.sub": "One <code>npx</code> away. Sandboxed. Reviewable. 98% cheaper.",
"ctab.sub": "One <code>npx</code> away. Sandboxed. Reviewable. Open source.",
"ctab.gh": "GitHub repository →",
"ctab.npm": "npm package",
@@ -128,33 +160,39 @@
"foot.col.project": "Project",
"foot.col.docs": "Docs",
"foot.col.community": "Community",
"foot.changelog": "Changelog",
"foot.releases": "Releases",
"foot.readme": "README",
"foot.readme.zh": "中文 README",
"foot.arch": "Architecture",
"foot.bench": "Benchmarks",
"foot.issues": "Issues",
"foot.discuss": "Discussions",
"foot.contributors": "Contributors",
"foot.copyright": "© 2026 Reasonix · MIT License",
},
zh: {
"nav.why": "为什么",
"nav.features": "特性",
"nav.quickstart": "快速上手",
"nav.benchmarks": "性能对比",
"nav.community": "社区",
"nav.github": "GitHub",
"hero.badge": "v{version} · DeepSeek V4 · 缓存优先",
"hero.badge": "v{version} · DeepSeek · 缓存优先 · MIT",
"hero.title.line1": "DeepSeek 原生",
"hero.title.line2": "终端里的 AI 编程代理",
"hero.sub":
"为 DeepSeek V4(flash + pro)打造的缓存优先 agent 循环。编辑以可审查的 SEARCH/REPLACE 块呈现,落盘前必须确认。Ink TUI、原生支持 MCP,不依赖 LangChain。",
"围绕 DeepSeek 前缀缓存设计,长会话下 token 成本始终维持在低位。自研 cell-diff 渲染器,MCP 一等公民,完全开源。",
"hero.copy": "复制",
"hero.copy.done": "已复制",
"hero.cta.start": "开始使用 →",
"hero.cta.star": "在 GitHub 加星",
"hero.stat.cache": "前缀缓存命中率",
"hero.stat.cost": "相比 Claude Sonnet 4.6 节省",
"hero.stat.pass": "τ-bench-lite 通过率",
"hero.stat.cache.num": "缓存工程化",
"hero.stat.cache": "字节稳定的前缀循环",
"hero.stat.lic.num": "开源",
"hero.stat.lic": "MIT 协议,社区共建",
"hero.stat.tui.num": "终端原生",
"hero.stat.tui": "外加内嵌仪表盘",
"term.user":
"users.ts 里 findByEmail 对大小写敏感导致登录失败,帮我改",
@@ -164,25 +202,25 @@
"why.title": "为什么选 Reasonix",
"why.sub":
"每个抽象都对应 DeepSeek 的一个具体特性——极低 token 价、R1 推理轨迹、自动前缀缓存、JSON 模式。通用框架把这些机会全留在桌上。",
"why.cache.title": "缓存优先的循环",
"整个循环围绕四根架构支柱组织。每一根解决的都是通用 agent 框架根本看不见的问题——因为它们是为另一种缓存机制设计的。",
"why.cache.title": "缓存优先循环",
"why.cache.body":
"对话日志只追加不重写,前缀字节级稳定,DeepSeek 的自动前缀缓存命中能稳定打到 85–95%,而不是 40%。",
"why.cost.title": "成本是头等公民",
"只追加历史。不就地修改,不依赖标记的 compaction。字节前缀跨过每一次工具调用都活着——DeepSeek 的前缀缓存一轮一轮持续命中。",
"why.r1.title": "R1 思维提取",
"why.r1.body":
"把 <code>reasoning_content</code> 蒸馏成结构化 plan state——子目标、假设、不确定性、被否决的路径。留信号,去噪声。",
"why.repair.title": "工具调用修复",
"why.repair.body":
"Schema 扁平化 · JSON 修复 · <code>&lt;think&gt;</code> 内 scavenge · 截断处理。四种策略对付 DeepSeek 专属怪癖——通用循环会把这些当模型错误。",
"why.cost.title": "成本控制",
"why.cost.body":
"默认 flash 优先、turn 末尾自动压缩、必要时模型自我升级到 pro。TUI 有实时单轮成本徽章。",
"why.tui.title": "Ink TUI,不靠浏览器",
"why.tui.body":
"完全在终端里。流式预览、斜杠命令、计划审阅、编辑确认弹窗。Windows 顽固终端可启用 plain 模式。",
"why.mcp.title": "原生 MCP",
"why.mcp.body":
"stdio + HTTP+SSE 双传输。长任务有实时进度条。和原生工具一样走缓存安全 + 自动修复管线。",
"why.safe.title": "编辑可审阅",
"why.safe.body":
"编辑以 SEARCH/REPLACE 块呈现,/apply 之前不动磁盘。逐文件 diff 确认、撤销历史、路径沙箱。",
"why.ctx.title": "百万 token 感知",
"why.ctx.body":
"上下文仪表 + 主动压缩、超大工具结果自动修复、贴近上限自动总结兜底。",
"缓存安全 fold · 激进 fold 层 · 退出时摘要 · 模型感知预算。循环管理上下文规模时不破坏前缀稳定。",
"why.deepseek.title": "故意只做 DeepSeek",
"why.deepseek.body":
"每一层都为 DeepSeek 特定的缓存机制和定价调过。绑死一个后端是 feature,不是限制。",
"why.oss.title": "开放社区",
"why.oss.body":
"MIT 协议,社区共建。<code>good first issue</code> 入门 issue 都带代码定位和验收标准。真实贡献者的真实 PR。",
"qs.title": "60 秒快速上手",
"qs.step1.title": "获取 DeepSeek API Key",
@@ -191,63 +229,91 @@
"qs.step2.title": "切到项目目录运行",
"qs.step2.body": "无需安装。",
"qs.step2.note":
"首次运行会走 30 秒向导:粘贴 API key → 选预设 → 勾选 MCP 服务器。",
"qs.step3.title": "让它改代码",
"首次运行会走一个短向导:粘贴 API key、选预设、可选挂载 MCP 服务器。",
"qs.step3.title": "审阅再应用",
"qs.step3.body":
"模型会以 SEARCH/REPLACE 块的形式提出编辑——你不 <code>/apply</code>,磁盘不会被改。",
"代理会把改动以可审阅的块呈现——你不 <code>/apply</code>,磁盘不会被改。Plan 模式可以让你先把多文件改动整理好,再统一落盘。",
"qs.req":
"需要 Node ≥ 22。支持 macOS、Linux、Windows(PowerShell · Git Bash · Windows Terminal)。任何时候按 <kbd>Esc</kbd> 中断;<code>/help</code> 查看完整命令。",
"需要 Node ≥ 22。支持 macOS、Linux、Windows(PowerShell · Git Bash · Windows Terminal)。任何时候按 <kbd>Esc</kbd> 中断;<code>/help</code> 查看完整斜杠命令。",
"feat.title": "开箱即用",
"feat.code.title": "结对编程模式",
"feat.code.body":
"<code>read_file</code> · <code>write_file</code> · <code>edit_file</code> · <code>search_files</code> · <code>directory_tree</code> · 带只读白名单的 <code>run_command</code>。沙箱限定在启动目录——路径逃逸一律拒绝。支持 plan 模式与逐次编辑确认弹窗。",
"feat.memory.title": "两层记忆系统",
"feat.memory.body":
"可提交的 <code>REASONIX.md</code> 承载团队约定,私人 <code>~/.reasonix/memory/</code> 分全局与按项目两个作用域。模型可通过 <code>remember</code> 工具自行写入。",
"feat.skills.title": "用户定义的 prompt 包",
"feat.skills.body":
"把 <code>SKILL.md</code> 丢进任意位置。名字 + 描述会被钉在前缀里,模型可自动调用,或你用 <code>/skill name</code> 手动触发。",
"feat.hooks.title": "生命周期钩子",
"feat.hooks.body":
"在 <code>PreToolUse</code> · <code>PostToolUse</code> · <code>UserPromptSubmit</code> · <code>Stop</code> 四个点触发 shell 命令,退出码决定放行 / 阻断 / 警告。",
"feat.mcp.title": "自带工具进来",
"feat.sub":
"12 个具体能力。循环是地基,下面是地基之上你能直接拿来用的东西。",
"feat.renderer.title": "自研 cell-diff 渲染器",
"feat.renderer.body":
"基于 Yoga 的 TUI 运行时,不依赖 Ink。宽字符、emoji、bracketed paste、resize 跨平台都干净。",
"feat.mcp.title": "MCP 一等公民",
"feat.mcp.body":
'向导内置目录,或用 <code>--mcp "name=cmd"</code> 直接挂 stdio / HTTP+SSE 服务器。长任务渲染实时进度条。',
"feat.web.title": "内置联网搜索",
"feat.web.body":
"<code>web_search</code> + <code>web_fetch</code>,背靠 Mojeek——无需 key、无需注册,离线 / CI 可关闭。可通过 <code>WebSearchProvider</code> 接口接入自家搜索。",
'stdio 与 Streamable HTTP 双传输。工具、资源、提示词全套。内置浏览器查看任意服务器的接口,也能用 <code>--mcp "name=cmd"</code> 现挂。',
"feat.plan.title": "计划模式",
"feat.plan.body":
"改动落盘前先 review。批准、调整、拒绝。Plan checkpoint 跨运行持久化,中途中断也能续。",
"feat.perm.title": "权限系统",
"feat.perm.body":
"每个工具 <code>allow</code> · <code>ask</code> · <code>deny</code>。shell 命令粒度规则。交互式提示,可以教它。",
"feat.dash.title": "内嵌仪表盘",
"feat.dash.body":
"<code>localhost</code> 的伴生 web 面板。实时缓存命中、成本计数、会话时间线、MCP 健康,一处看全。",
"feat.sess.title": "持久化会话",
"feat.sess.body":
"按工作区组织,命名、可恢复。<code>--resume</code> 完全还原——系统提示、历史、plan state。",
"feat.hooks.title": "Hooks · Skills · Memory",
"feat.hooks.body":
"生命周期事件触发 shell 命令。drop-in 的 skill 包能拉子代理。每回合自动读入的项目级 memory。",
"feat.search.title": "语义检索",
"feat.search.body":
"<code>reasonix index</code> 构建 embedding 索引供 agent 查询。本地 Ollama 或 DeepSeek 托管 embedding 任选。",
"feat.ckpt.title": "自动 checkpoint",
"feat.ckpt.body":
"Cursor 风格的会话级 AI 编辑回滚。不污染 git 历史;checkpoint 栈完全是你自己的。",
"feat.effort.title": "<code>/effort</code> 旋钮",
"feat.effort.body":
"每回合切换 reasoning 深度。难活 <code>max</code>、日常 <code>low</code>。斜杠命令 + CLI flag 双入口。",
"feat.replay.title": "Transcript 重放",
"feat.replay.body":
"<code>reasonix replay</code> 把录制好的会话用渲染器重放一遍——bug 复现、演示、审计都好用。",
"feat.events.title": "事件日志",
"feat.events.body":
"<code>events.jsonl</code> 旁路日志,附带 reducer 和 <code>reasonix events</code> CLI。自己搭仪表盘、审计、分析都行。",
"bench.title": "缓存命中率自己也能验证",
"bench.title": "缓存命中自己也能验证",
"bench.sub":
"同一 τ-bench-lite 负载(8 个多轮工具调用任务 × 3 次重复 = 每边 48 次运行),实测 DeepSeek <code>deepseek-chat</code>,唯一变量是前缀稳定性:",
"bench.col.metric": "指标",
"bench.col.baseline": "基线(缓存敌对)",
"bench.col.reasonix": "Reasonix",
"bench.col.delta": "差值",
"bench.row.cache": "缓存命中",
"bench.row.cost": "单任务成本",
"bench.row.pass": "通过率",
"bench.repro.intro": "无需消耗 API 额度即可复现:",
"营销文案里我们不放具体 benchmark 数字——这些数会随模型定价和测试集变化,所以归在 harness 里,不进 README。在自己机器上复现:",
"bench.repro.note":
"提交进仓库的 JSONL 文件每轮带 <code>usage</code>、<code>cost</code>、<code>prefixHash</code>。Reasonix 的前缀哈希在每次模型调用时都字节稳定。",
"提交进仓库的每个 JSONL transcript 都带逐轮 <code>usage</code>、<code>cost</code> 和 <code>prefixHash</code>。Reasonix 的前缀哈希在每次模型调用中都字节稳定——这就是全部把戏。",
"bench.link": "查看 τ-bench-lite harness →",
"cli.title": "CLI 速览",
"cli.code": "针对指定路径的编程模式",
"cli.chat": "聊天模式(读取已保存配置)",
"cli.setup": "重新跑配置向导",
"cli.chat": "交互式聊天(读取已保存配置)",
"cli.run": "一次性运行,结果流到 stdout",
"cli.stats": "跨会话的成本仪表盘",
"cli.doctor": "环境健康检查",
"cli.replay": "重渲染一段录制的会话",
"cli.diff": "比较两段 transcript",
"cli.events": "查询事件日志",
"cli.stats": "跨会话用量统计",
"cli.index": "构建语义 embedding 索引",
"cli.mcp": "探测单个 MCP 服务器",
"cli.mcplist": "列出已配置的 MCP 服务器",
"cli.prune": "清理旧会话",
"cli.flags.intro": "常用 flag:",
"cli.f.preset": "模型 + harvest + 分支并行 一键组合",
"cli.f.effort": "本次运行的 reasoning 深度",
"cli.f.model": "显式指定 DeepSeek 模型 ID",
"cli.f.mcp": "挂载 MCP 服务器(可重复)",
"cli.f.session": "命名会话",
"cli.f.resume": "恢复本工作区的最近一个会话",
"cli.f.new": "强制开新会话,旧会话保留",
"cli.f.noconf": "忽略 ~/.reasonix/config.json(CI 友好)",
"comm.title": "由社区共建",
"comm.sub":
"Reasonix 是开源、社区共建的项目。下面墙上每一个头像都对应一次真实合并的 PR——不是赞助位。",
"comm.gfi": "good first issue →",
"comm.disc": "Discussions",
"comm.contrib": "贡献指南",
"ctab.title": "准备好了吗?",
"ctab.sub": "一条 <code>npx</code> 即可开始。沙箱、可审阅、便宜 98%。",
"ctab.sub": "一条 <code>npx</code> 即可开始。沙箱、可审阅、完全开源。",
"ctab.gh": "GitHub 仓库 →",
"ctab.npm": "npm 包",
@@ -255,12 +321,14 @@
"foot.col.project": "项目",
"foot.col.docs": "文档",
"foot.col.community": "社区",
"foot.changelog": "更新日志",
"foot.releases": "Releases",
"foot.readme": "英文 README",
"foot.readme.zh": "中文 README",
"foot.arch": "架构文档",
"foot.bench": "Benchmarks",
"foot.issues": "问题反馈",
"foot.discuss": "讨论区",
"foot.contributors": "贡献者",
"foot.copyright": "© 2026 Reasonix · MIT 协议",
},
};
@@ -312,7 +380,7 @@
// 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.16";
const VERSION_FALLBACK = "0.26";
const versionListeners = [];
let currentVersion = VERSION_FALLBACK;
+269 -155
View File
@@ -6,14 +6,14 @@
<title>Reasonix — DeepSeek-native AI coding agent</title>
<meta
name="description"
content="Cache-first agent loop for DeepSeek V4. Ink TUI. MCP first-class. 90%+ prefix cache hit, ~98% cheaper than Claude on the same workload. No LangChain."
content="Open-source AI coding agent for your terminal, engineered around DeepSeek's prefix-cache so token costs stay low across long sessions. MCP first-class · plan mode · custom cell-diff renderer."
/>
<meta name="theme-color" content="#0b0f17" />
<meta property="og:title" content="Reasonix — DeepSeek-native AI coding agent" />
<meta
property="og:description"
content="Cache-first agent loop for DeepSeek V4 (flash + pro). Ink TUI. MCP first-class. No LangChain."
content="Open-source AI coding agent for your terminal. Engineered around DeepSeek's prefix-cache. MCP first-class · plan mode · embedded dashboard · MIT."
/>
<meta property="og:type" content="website" />
<meta property="og:url" content="https://esengine.github.io/reasonix/" />
@@ -44,9 +44,10 @@
</a>
<nav class="nav-links">
<a href="#why" data-i18n="nav.why">Why</a>
<a href="#features" data-i18n="nav.features">Features</a>
<a href="#quickstart" data-i18n="nav.quickstart">Quick start</a>
<a href="#benchmarks" data-i18n="nav.benchmarks">Benchmarks</a>
<a href="#community" data-i18n="nav.community">Community</a>
<a
href="https://github.com/esengine/reasonix"
target="_blank"
@@ -67,15 +68,15 @@
<main id="top">
<section class="hero">
<div class="hero-inner">
<div class="badge" data-i18n="hero.badge">v0.16 · DeepSeek V4 · cache-first</div>
<div class="badge" data-i18n="hero.badge">v{version} · DeepSeek · cache-first · MIT</div>
<h1 class="hero-title">
<span class="grad-text" data-i18n="hero.title.line1">DeepSeek-native</span>
<br />
<span data-i18n="hero.title.line2">AI coding agent in your terminal</span>
</h1>
<p class="hero-sub" data-i18n="hero.sub">
Cache-first agent loop for DeepSeek V4 (flash + pro). Edits files as
reviewable SEARCH/REPLACE blocks. Ink TUI. MCP first-class. No LangChain.
Engineered around DeepSeek's prefix-cache so token costs stay low across long
sessions. Custom cell-diff renderer. MCP first-class. Open source.
</p>
<div class="hero-install">
@@ -103,16 +104,16 @@
<div class="hero-stats">
<div class="stat">
<div class="stat-num grad-text">90.2%</div>
<div class="stat-label" data-i18n="hero.stat.cache">prefix cache hit rate</div>
<div class="stat-num grad-text" data-i18n="hero.stat.cache.num">Cache-engineered</div>
<div class="stat-label" data-i18n="hero.stat.cache">Byte-stable prefix loop</div>
</div>
<div class="stat">
<div class="stat-num grad-text">~98%</div>
<div class="stat-label" data-i18n="hero.stat.cost">cheaper vs Claude Sonnet 4.6</div>
<div class="stat-num grad-text" data-i18n="hero.stat.lic.num">Open source</div>
<div class="stat-label" data-i18n="hero.stat.lic">MIT, community-developed</div>
</div>
<div class="stat">
<div class="stat-num grad-text">100%</div>
<div class="stat-label" data-i18n="hero.stat.pass">τ-bench-lite pass rate</div>
<div class="stat-num grad-text" data-i18n="hero.stat.tui.num">Terminal-native</div>
<div class="stat-label" data-i18n="hero.stat.tui">Plus embedded dashboard</div>
</div>
</div>
</div>
@@ -127,13 +128,13 @@
</div>
</section>
<section class="why">
<section id="why" class="why">
<div class="container">
<h2 class="section-title" data-i18n="why.title">Why Reasonix</h2>
<p class="section-sub" data-i18n="why.sub">
Every abstraction earns its weight against a DeepSeek-specific property —
dirt-cheap tokens, R1 traces, automatic prefix caching, JSON mode. Generic
wrappers leave these on the table.
The loop is organized around four architectural pillars. Each one solves a
problem generic agent frameworks don't even see — because they were designed
for a different cache mechanic.
</p>
<div class="why-grid">
@@ -141,48 +142,51 @@
<div class="why-icon">◈</div>
<h3 data-i18n="why.cache.title">Cache-first loop</h3>
<p data-i18n="why.cache.body">
Append-only conversation log keeps the prompt prefix byte-stable across
turns, so DeepSeek's automatic cache hits 85–95% — not 40%.
Append-only history. No in-place mutation, no marker-based compaction.
The byte prefix survives every tool call — DeepSeek's prefix-cache keeps
hitting turn after turn.
</p>
</article>
<article class="why-card">
<div class="why-icon">⌥</div>
<h3 data-i18n="why.r1.title">R1 thought harvesting</h3>
<p data-i18n="why.r1.body">
Distills <code>reasoning_content</code> into a typed plan state — subgoals,
hypotheses, uncertainties, rejected paths. Signal kept, noise dropped.
</p>
</article>
<article class="why-card">
<div class="why-icon">⚒</div>
<h3 data-i18n="why.repair.title">Tool-call repair</h3>
<p data-i18n="why.repair.body">
Schema flatten · JSON repair · scavenge from <code>&lt;think&gt;</code> ·
truncation. Four strategies that handle DeepSeek-specific quirks generic
loops mistake for model errors.
</p>
</article>
<article class="why-card">
<div class="why-icon">¥</div>
<h3 data-i18n="why.cost.title">Cost is a pillar</h3>
<h3 data-i18n="why.cost.title">Cost control</h3>
<p data-i18n="why.cost.body">
Flash-first defaults, turn-end auto-compaction, model self-escalation
when (and only when) needed. Per-turn cost badge in the TUI.
Cache-safe folding · aggressive-fold tier · summary-on-exit · model-aware
budgets. The loop manages context size without breaking prefix stability.
</p>
</article>
<article class="why-card">
<div class="why-icon">⌨</div>
<h3 data-i18n="why.tui.title">Ink TUI, no web</h3>
<p data-i18n="why.tui.body">
Lives in your terminal. Streaming preview, slash commands, plan picker,
edit-confirm modal. Plain mode for stubborn Windows shells.
<div class="why-icon">∂</div>
<h3 data-i18n="why.deepseek.title">DeepSeek-only by design</h3>
<p data-i18n="why.deepseek.body">
Every layer is tuned around DeepSeek's specific cache mechanic and pricing.
Coupling to one backend is the feature, not a limitation.
</p>
</article>
<article class="why-card">
<div class="why-icon">⊕</div>
<h3 data-i18n="why.mcp.title">MCP first-class</h3>
<p data-i18n="why.mcp.body">
Stdio + HTTP+SSE transports. Live progress notifications. Same
cache-safety + repair plumbing as native tools.
</p>
</article>
<article class="why-card">
<div class="why-icon">↶</div>
<h3 data-i18n="why.safe.title">Reviewable edits</h3>
<p data-i18n="why.safe.body">
Edits arrive as SEARCH/REPLACE blocks; nothing hits disk until /apply.
Per-file diff confirm modal, undo history, sandboxed paths.
</p>
</article>
<article class="why-card">
<div class="why-icon">∞</div>
<h3 data-i18n="why.ctx.title">1M-token aware</h3>
<p data-i18n="why.ctx.body">
Context gauge with proactive compaction, oversized tool-result repair,
forced-summary fallback near the window edge.
<div class="why-icon">⊜</div>
<h3 data-i18n="why.oss.title">Open community</h3>
<p data-i18n="why.oss.body">
MIT licensed and community-developed. Scoped <code>good first issue</code>
tickets with code pointers and acceptance criteria. Real PRs from real
contributors.
</p>
</article>
</div>
@@ -209,15 +213,16 @@
<pre class="code"><code>cd my-project
npx reasonix code</code></pre>
<p data-i18n="qs.step2.note">
First run walks you through a 30-second wizard (paste API key → pick
preset → pick MCP servers).
First run walks you through a short wizard — paste API key, pick a
preset, optionally attach MCP servers.
</p>
</li>
<li>
<h3 data-i18n="qs.step3.title">Ask it to edit</h3>
<h3 data-i18n="qs.step3.title">Review and apply</h3>
<p data-i18n="qs.step3.body">
The model proposes edits as SEARCH/REPLACE blocks — nothing hits disk
until you <code>/apply</code>.
The agent proposes edits as reviewable blocks — nothing hits disk until
you <code>/apply</code>. Plan mode lets you stage multi-file changes
before committing any.
</p>
</li>
</ol>
@@ -225,7 +230,7 @@ npx reasonix code</code></pre>
<p class="req" data-i18n="qs.req">
Requires Node ≥ 22. macOS, Linux, Windows (PowerShell · Git Bash · Windows
Terminal). Press <kbd>Esc</kbd> anytime to abort; <code>/help</code> for the
full command list.
full slash-command list.
</p>
</div>
</section>
@@ -233,121 +238,147 @@ npx reasonix code</code></pre>
<section id="features" class="features">
<div class="container">
<h2 class="section-title" data-i18n="feat.title">In the box</h2>
<p class="section-sub" data-i18n="feat.sub">
Twelve concrete capabilities. The loop is the foundation; everything below
is what you get on top of it.
</p>
<div class="feat-grid">
<article class="feat">
<h3>
<span class="feat-tag">code</span>
<span data-i18n="feat.code.title">Pair programmer mode</span>
<span class="feat-tag">renderer</span>
<span data-i18n="feat.renderer.title">Cell-diff renderer</span>
</h3>
<p data-i18n="feat.code.body">
<code>read_file</code> · <code>write_file</code> · <code>edit_file</code> ·
<code>search_files</code> · <code>directory_tree</code> ·
<code>run_command</code> with read-only allowlist. Sandboxed to the
launch root — no path escapes. Plan mode and per-edit review modal.
</p>
</article>
<article class="feat">
<h3>
<span class="feat-tag">memory</span>
<span data-i18n="feat.memory.title">Two-layer memory</span>
</h3>
<p data-i18n="feat.memory.body">
Committable <code>REASONIX.md</code> for team conventions plus a private
per-user <code>~/.reasonix/memory/</code> with global and per-project
scopes. The model can write to it via the <code>remember</code> tool.
</p>
</article>
<article class="feat">
<h3>
<span class="feat-tag">skills</span>
<span data-i18n="feat.skills.title">User-authored prompt packs</span>
</h3>
<p data-i18n="feat.skills.body">
Drop <code>SKILL.md</code> files anywhere. Names + descriptions are
pinned in the prefix; the model picks them autonomously, or you trigger
with <code>/skill name</code>.
</p>
</article>
<article class="feat">
<h3>
<span class="feat-tag">hooks</span>
<span data-i18n="feat.hooks.title">Lifecycle hooks</span>
</h3>
<p data-i18n="feat.hooks.body">
Shell commands fire at <code>PreToolUse</code> · <code>PostToolUse</code>
· <code>UserPromptSubmit</code> · <code>Stop</code>. Exit code drives
pass / block / warn.
<p data-i18n="feat.renderer.body">
Custom TUI runtime built on Yoga. No Ink dependency. Wide-char, emoji,
bracketed paste, and resize handled cleanly across platforms.
</p>
</article>
<article class="feat">
<h3>
<span class="feat-tag">mcp</span>
<span data-i18n="feat.mcp.title">Bring your own tools</span>
<span data-i18n="feat.mcp.title">MCP first-class</span>
</h3>
<p data-i18n="feat.mcp.body">
Wizard catalog, or <code>--mcp "name=cmd"</code> to attach stdio /
HTTP+SSE servers on the fly. Live progress bars on long calls.
Stdio and Streamable HTTP transports. Tools, resources, and prompts.
In-app browser to inspect any server's surface, plus
<code>--mcp "name=cmd"</code> on the fly.
</p>
</article>
<article class="feat">
<h3>
<span class="feat-tag">web</span>
<span data-i18n="feat.web.title">Web search built-in</span>
<span class="feat-tag">plan</span>
<span data-i18n="feat.plan.title">Plan mode</span>
</h3>
<p data-i18n="feat.web.body">
<code>web_search</code> + <code>web_fetch</code> via Mojeek — no key, no
signup, off-by-flag for offline / CI. Bring-your-own provider via the
<code>WebSearchProvider</code> interface.
<p data-i18n="feat.plan.body">
Review proposed edits before they touch disk. Approve, refine, or reject.
Plan checkpoints persist across runs so you can resume mid-review.
</p>
</article>
<article class="feat">
<h3>
<span class="feat-tag">perms</span>
<span data-i18n="feat.perm.title">Permissions</span>
</h3>
<p data-i18n="feat.perm.body">
<code>allow</code> · <code>ask</code> · <code>deny</code> per-tool.
Granular shell command rules. Interactive prompts you can teach.
</p>
</article>
<article class="feat">
<h3>
<span class="feat-tag">dashboard</span>
<span data-i18n="feat.dash.title">Embedded dashboard</span>
</h3>
<p data-i18n="feat.dash.body">
Companion web view at <code>localhost</code>. Live cache hit rate, cost
ticker, session timeline, MCP health — all in one place.
</p>
</article>
<article class="feat">
<h3>
<span class="feat-tag">sessions</span>
<span data-i18n="feat.sess.title">Persistent sessions</span>
</h3>
<p data-i18n="feat.sess.body">
Per-workspace, named, resumable. <code>--resume</code> picks up exactly
where you left off — system prompt, history, plan state.
</p>
</article>
<article class="feat">
<h3>
<span class="feat-tag">hooks</span>
<span data-i18n="feat.hooks.title">Hooks · skills · memory</span>
</h3>
<p data-i18n="feat.hooks.body">
Shell commands fire on lifecycle events. Drop-in skill packs spawn
sub-agents. Project memory the agent reads on every turn.
</p>
</article>
<article class="feat">
<h3>
<span class="feat-tag">search</span>
<span data-i18n="feat.search.title">Semantic search</span>
</h3>
<p data-i18n="feat.search.body">
<code>reasonix index</code> builds an embedding index your agent can
query. Local Ollama or DeepSeek-hosted embeddings.
</p>
</article>
<article class="feat">
<h3>
<span class="feat-tag">checkpoint</span>
<span data-i18n="feat.ckpt.title">Auto-checkpoints</span>
</h3>
<p data-i18n="feat.ckpt.body">
Cursor-style session-scoped rollback for AI edits. Never pollutes git
history; the checkpoint stack is yours alone.
</p>
</article>
<article class="feat">
<h3>
<span class="feat-tag">effort</span>
<span data-i18n="feat.effort.title"><code>/effort</code> knob</span>
</h3>
<p data-i18n="feat.effort.body">
Switch reasoning depth per turn. <code>max</code> for the gnarly,
<code>low</code> for routine. Slash command and CLI flag.
</p>
</article>
<article class="feat">
<h3>
<span class="feat-tag">replay</span>
<span data-i18n="feat.replay.title">Transcript replay</span>
</h3>
<p data-i18n="feat.replay.body">
<code>reasonix replay</code> plays a recorded session back through the
renderer — useful for bug reports, demos, and audits.
</p>
</article>
<article class="feat">
<h3>
<span class="feat-tag">events</span>
<span data-i18n="feat.events.title">Event log</span>
</h3>
<p data-i18n="feat.events.body">
<code>events.jsonl</code> sidecar with reducers and a
<code>reasonix events</code> CLI. Build dashboards, audits, or your own
analytics.
</p>
</article>
</div>
</div>
</section>
<section id="benchmarks" class="bench">
<section class="bench">
<div class="container">
<h2 class="section-title" data-i18n="bench.title">Verify the cache claim yourself</h2>
<p class="section-sub" data-i18n="bench.sub">
On the same τ-bench-lite workload (8 multi-turn tool-use tasks × 3 repeats =
48 runs per side), live DeepSeek <code>deepseek-chat</code>, sole variable
prefix stability:
We don't ship benchmark numbers in marketing copy — they move with model
pricing and harness changes, so they live with the harness instead of the
README. Reproduce on your own machine:
</p>
<div class="bench-table-wrap">
<table class="bench-table">
<thead>
<tr>
<th data-i18n="bench.col.metric">metric</th>
<th data-i18n="bench.col.baseline">baseline (cache-hostile)</th>
<th data-i18n="bench.col.reasonix">Reasonix</th>
<th data-i18n="bench.col.delta">delta</th>
</tr>
</thead>
<tbody>
<tr>
<td data-i18n="bench.row.cache">cache hit</td>
<td>32.8%</td>
<td class="hi">90.2%</td>
<td>+57.4 pp</td>
</tr>
<tr>
<td data-i18n="bench.row.cost">cost / task</td>
<td>$0.000992</td>
<td class="hi">$0.000593</td>
<td><strong>−40%</strong></td>
</tr>
<tr>
<td data-i18n="bench.row.pass">pass rate</td>
<td>100% (24/24)</td>
<td class="hi">100% (24/24)</td>
<td>—</td>
</tr>
</tbody>
</table>
</div>
<p data-i18n="bench.repro.intro">Reproduce without spending an API credit:</p>
<pre class="code"><code>git clone https://github.com/esengine/reasonix.git &amp;&amp; cd reasonix &amp;&amp; npm install
npx reasonix replay benchmarks/tau-bench/transcripts/t01_address_happy.reasonix.r1.jsonl
npx reasonix diff \
@@ -355,9 +386,19 @@ npx reasonix diff \
benchmarks/tau-bench/transcripts/t01_address_happy.reasonix.r1.jsonl</code></pre>
<p data-i18n="bench.repro.note">
The committed JSONL transcripts carry per-turn <code>usage</code>,
Each committed JSONL transcript carries per-turn <code>usage</code>,
<code>cost</code>, and <code>prefixHash</code>. Reasonix's prefix hash stays
byte-stable across every model call.
byte-stable across every model call — that's the whole game.
</p>
<p>
<a
class="cta ghost"
href="https://github.com/esengine/reasonix/tree/main/benchmarks"
target="_blank"
rel="noopener"
data-i18n="bench.link"
>Read the τ-bench-lite harness →</a
>
</p>
</div>
</section>
@@ -366,18 +407,77 @@ npx reasonix diff \
<div class="container">
<h2 class="section-title" data-i18n="cli.title">CLI at a glance</h2>
<pre class="code"><code>npx reasonix code [path] <span class="hash"># <span data-i18n="cli.code">coding mode scoped to path</span></span>
npx reasonix <span class="hash"># <span data-i18n="cli.chat">chat (uses saved config)</span></span>
npx reasonix setup <span class="hash"># <span data-i18n="cli.setup">reconfigure the wizard</span></span>
npx reasonix chat <span class="hash"># <span data-i18n="cli.chat">interactive chat (saved config)</span></span>
npx reasonix run "ask anything" <span class="hash"># <span data-i18n="cli.run">one-shot, streams to stdout</span></span>
npx reasonix stats <span class="hash"># <span data-i18n="cli.stats">cross-session cost dashboard</span></span>
npx reasonix mcp inspect &lt;spec&gt; <span class="hash"># <span data-i18n="cli.mcp">probe a single MCP server</span></span></code></pre>
npx reasonix doctor <span class="hash"># <span data-i18n="cli.doctor">environment health check</span></span>
npx reasonix replay &lt;file.jsonl&gt; <span class="hash"># <span data-i18n="cli.replay">re-render a recorded session</span></span>
npx reasonix diff a.jsonl b.jsonl <span class="hash"># <span data-i18n="cli.diff">compare two transcripts</span></span>
npx reasonix events &lt;name&gt; <span class="hash"># <span data-i18n="cli.events">query the event log</span></span>
npx reasonix stats <span class="hash"># <span data-i18n="cli.stats">cross-session usage</span></span>
npx reasonix index <span class="hash"># <span data-i18n="cli.index">build semantic embedding index</span></span>
npx reasonix mcp inspect &lt;spec&gt; <span class="hash"># <span data-i18n="cli.mcp">probe one MCP server</span></span>
npx reasonix mcp list <span class="hash"># <span data-i18n="cli.mcplist">list configured MCP servers</span></span>
npx reasonix prune-sessions <span class="hash"># <span data-i18n="cli.prune">clean up old sessions</span></span></code></pre>
<p class="cli-flags" data-i18n="cli.flags.intro">Common flags:</p>
<pre class="code"><code>--preset &lt;fast|smart|max&gt; <span class="hash"># <span data-i18n="cli.f.preset">model + harvest + branch bundle</span></span>
--model &lt;id&gt; <span class="hash"># <span data-i18n="cli.f.model">explicit DeepSeek model id</span></span>
--mcp "name=cmd args…" <span class="hash"># <span data-i18n="cli.f.mcp">attach an MCP server (repeatable)</span></span>
--session &lt;name&gt; <span class="hash"># <span data-i18n="cli.f.session">named session</span></span>
--no-config <span class="hash"># <span data-i18n="cli.f.noconf">ignore ~/.reasonix/config.json (CI)</span></span></code></pre>
<pre class="code"><code>--effort &lt;max|high|medium|low&gt; <span class="hash"># <span data-i18n="cli.f.effort">reasoning depth for the run</span></span>
--model &lt;id&gt; <span class="hash"># <span data-i18n="cli.f.model">explicit DeepSeek model id</span></span>
--mcp "name=cmd args…" <span class="hash"># <span data-i18n="cli.f.mcp">attach an MCP server (repeatable)</span></span>
--session &lt;name&gt; <span class="hash"># <span data-i18n="cli.f.session">named session</span></span>
--resume <span class="hash"># <span data-i18n="cli.f.resume">pick up the latest session for this workspace</span></span>
--new <span class="hash"># <span data-i18n="cli.f.new">force a fresh session, preserve old</span></span>
--no-config <span class="hash"># <span data-i18n="cli.f.noconf">ignore ~/.reasonix/config.json (CI)</span></span></code></pre>
</div>
</section>
<section id="community" class="community">
<div class="container">
<h2 class="section-title" data-i18n="comm.title">Built by the community</h2>
<p class="section-sub" data-i18n="comm.sub">
Reasonix is open source and community-developed. Every avatar on the wall
below is a real PR that shipped — not a sponsorship slot.
</p>
<p align="center">
<a
href="https://github.com/esengine/reasonix/graphs/contributors"
target="_blank"
rel="noopener"
>
<img
src="https://contrib.rocks/image?repo=esengine/reasonix&max=100&columns=12"
alt="Contributors to esengine/reasonix"
style="max-width: 100%; border-radius: 8px;"
/>
</a>
</p>
<div class="comm-links">
<a
class="cta ghost"
href="https://github.com/esengine/reasonix/labels/good%20first%20issue"
target="_blank"
rel="noopener"
data-i18n="comm.gfi"
>good first issue →</a
>
<a
class="cta ghost"
href="https://github.com/esengine/reasonix/discussions"
target="_blank"
rel="noopener"
data-i18n="comm.disc"
>Discussions</a
>
<a
class="cta ghost"
href="https://github.com/esengine/reasonix/blob/main/CONTRIBUTING.md"
target="_blank"
rel="noopener"
data-i18n="comm.contrib"
>Contributing guide</a
>
</div>
</div>
</section>
@@ -385,7 +485,7 @@ npx reasonix mcp inspect &lt;spec&gt; <span class="hash"># <span data-i
<div class="container">
<h2 data-i18n="ctab.title">Ready to try?</h2>
<p data-i18n="ctab.sub">
One <code>npx</code> away. Sandboxed. Reviewable. 98% cheaper.
One <code>npx</code> away. Sandboxed. Reviewable. Open source.
</p>
<div class="hero-ctas center">
<a
@@ -427,11 +527,11 @@ npx reasonix mcp inspect &lt;spec&gt; <span class="hash"># <span data-i
<a href="https://github.com/esengine/reasonix" target="_blank" rel="noopener">GitHub</a>
<a href="https://www.npmjs.com/package/reasonix" target="_blank" rel="noopener">npm</a>
<a
href="https://github.com/esengine/reasonix/blob/main/CHANGELOG.md"
href="https://github.com/esengine/reasonix/releases"
target="_blank"
rel="noopener"
data-i18n="foot.changelog"
>Changelog</a
data-i18n="foot.releases"
>Releases</a
>
<a
href="https://github.com/esengine/reasonix/blob/main/LICENSE"
@@ -463,6 +563,13 @@ npx reasonix mcp inspect &lt;spec&gt; <span class="hash"># <span data-i
data-i18n="foot.arch"
>Architecture</a
>
<a
href="https://github.com/esengine/reasonix/tree/main/benchmarks"
target="_blank"
rel="noopener"
data-i18n="foot.bench"
>Benchmarks</a
>
</div>
<div>
<h4 data-i18n="foot.col.community">Community</h4>
@@ -480,6 +587,13 @@ npx reasonix mcp inspect &lt;spec&gt; <span class="hash"># <span data-i
data-i18n="foot.discuss"
>Discussions</a
>
<a
href="https://github.com/esengine/reasonix/graphs/contributors"
target="_blank"
rel="noopener"
data-i18n="foot.contributors"
>Contributors</a
>
</div>
</div>
</div>
+29 -7
View File
@@ -417,9 +417,9 @@ main,
}
.stat-num {
font-family: var(--font-mono);
font-size: 28px;
font-size: 18px;
font-weight: 700;
letter-spacing: -0.02em;
letter-spacing: -0.01em;
margin-bottom: 4px;
}
.stat-label {
@@ -941,9 +941,9 @@ main,
.feat-grid {
display: grid;
grid-template-columns: repeat(2, 1fr);
grid-template-columns: repeat(3, 1fr);
gap: 18px;
max-width: 980px;
max-width: 1100px;
margin: 0 auto;
}
@@ -1057,6 +1057,27 @@ main,
margin: 24px 0 0;
}
/* Community */
.community {
padding: 80px 0;
}
.community .container > p[align="center"] {
margin: 24px auto 32px;
max-width: 880px;
text-align: center;
}
.community .container > p[align="center"] img {
max-width: 100%;
border-radius: 8px;
}
.comm-links {
display: flex;
flex-wrap: wrap;
justify-content: center;
gap: 12px;
margin-top: 8px;
}
/* CTA band */
.cta-band {
padding: 80px 0;
@@ -1128,10 +1149,10 @@ main,
grid-template-columns: 1fr;
gap: 40px;
}
.why-grid {
.why-grid,
.feat-grid {
grid-template-columns: repeat(2, 1fr);
}
.feat-grid,
.foot-inner {
grid-template-columns: 1fr;
}
@@ -1148,7 +1169,8 @@ main,
margin: 24px auto 60px;
padding: 0 20px;
}
.why-grid {
.why-grid,
.feat-grid {
grid-template-columns: 1fr;
}
.hero-stats {
+3155 -306
View File
File diff suppressed because it is too large. Load diff
+12 -8
View File
@@ -1,6 +1,6 @@
{
"name": "reasonix",
"version": "0.25.0",
"version": "0.30.5",
"description": "DeepSeek-native coding agent: cache-first loop, flash-first cost control, tool-call repair.",
"type": "module",
"bin": {
@@ -30,6 +30,8 @@
"chat": "tsx src/cli/index.ts chat",
"test": "vitest run",
"test:watch": "vitest",
"test:coverage": "vitest run --coverage",
"test:mutation": "stryker run",
"lint": "biome check src tests",
"lint:fix": "biome check --write src tests",
"format": "biome format --write src tests",
@@ -70,24 +72,26 @@
"commander": "^12.1.0",
"eventsource-parser": "^3.0.0",
"ignore": "^7.0.5",
"ink": "^7.0.2",
"ink-text-input": "^6.0.0",
"node-html-parser": "^7.1.0",
"picomatch": "^4.0.4",
"react": "^18.3.1",
"react-reconciler": "^0.29.2",
"react": "^19.2.6",
"string-width": "^7.2.0",
"yoga-layout": "^3.2.1",
"zod": "^4.4.1"
},
"devDependencies": {
"@biomejs/biome": "^1.9.4",
"@stryker-mutator/core": "^9.6.1",
"@stryker-mutator/vitest-runner": "^9.6.1",
"@types/node": "^22.9.0",
"@types/picomatch": "^4.0.3",
"@types/react": "^18.3.12",
"@types/react-reconciler": "^0.28.9",
"@types/react": "^19.2.14",
"@vitest/coverage-v8": "^2.1.5",
"esbuild": "^0.21.5",
"highlight.js": "^11.10.0",
"htm": "^3.1.1",
"ink": "^5.1.0",
"ink-text-input": "^6.0.0",
"ink-testing-library": "^4.0.0",
"marked": "^15.0.12",
"preact": "^10.22.0",
"simple-git-hooks": "^2.13.1",
+44
View File
@@ -0,0 +1,44 @@
import { readFileSync, appendFileSync } from "node:fs";
import { join } from "node:path";
const ROOT = new URL("..", import.meta.url).pathname;
const SUMMARY_PATH = join(ROOT, "coverage", "coverage-summary.json");
const GITHUB_STEP_SUMMARY = process.env.GITHUB_STEP_SUMMARY;
if (!GITHUB_STEP_SUMMARY) {
console.log("Not running in GitHub Actions (no GITHUB_STEP_SUMMARY). Skipping.");
process.exit(0);
}
let data;
try {
data = JSON.parse(readFileSync(SUMMARY_PATH, "utf-8"));
} catch (err) {
console.error("Failed to read coverage summary:", err.message);
process.exit(0); // don't fail the build if coverage report is missing
}
const { total } = data;
if (!total) {
console.error("No 'total' key in coverage summary. Skipping.");
process.exit(0);
}
const pct = (metric) => {
const m = total[metric];
if (!m) return "-";
return `${m.pct.toFixed(1)}%`;
};
const rows = [
"| Metric | Coverage |",
"| ------ | -------- |",
`| Statements | ${pct("statements")} |`,
`| Branches | ${pct("branches")} |`,
`| Functions | ${pct("functions")} |`,
`| Lines | ${pct("lines")} |`,
];
const md = `## Coverage\n\n${rows.join("\n")}\n`;
appendFileSync(GITHUB_STEP_SUMMARY, md + "\n");
console.log("Coverage summary written to job summary.");
+156
View File
@@ -0,0 +1,156 @@
/**
* Probes whether mutating a mid-history message destroys DeepSeek's prompt
* cache for everything after the mutation point.
*
* Hypothesis: our compactInPlace() rewrites old tool results, which shifts
* the byte offsets of every subsequent message. DeepSeek caches by exact
* prefix, so the next request would cache-hit only up to the mutation
* point, even though most of the conversation is unchanged.
*
* Run: node scripts/probe-cache.mjs
* Reads DEEPSEEK_API_KEY / DEEPSEEK_BASE_URL from .env.testbak.
*/
import { readFileSync } from "node:fs";
function loadDotenv(path) {
const txt = readFileSync(path, "utf8");
for (const line of txt.split(/\r?\n/)) {
const m = line.match(/^([A-Z_][A-Z0-9_]*)=(.*)$/);
if (m) process.env[m[1]] ??= m[2];
}
}
loadDotenv("./.env.testbak");
const KEY = process.env.DEEPSEEK_API_KEY;
const BASE = process.env.DEEPSEEK_BASE_URL ?? "https://api.deepseek.com";
if (!KEY) throw new Error("DEEPSEEK_API_KEY missing");
const filler = (label, n) =>
Array.from({ length: n }, (_, i) => `${label} line ${i}: lorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.`).join("\n");
const SYS = "You are a terse echo bot. Reply with a single short sentence.";
const MSG_A_FULL = `Long context block A. Detail follows:\n${filler("A", 80)}`;
const MSG_A_TRUNCATED = `Long context block A. Detail follows:\n${filler("A", 8)}\n[truncated]`;
const MSG_B = `Block B reference: ${filler("B", 30)}`;
const MSG_C = `Block C reference: ${filler("C", 30)}`;
async function call(label, messages) {
const t0 = Date.now();
const res = await fetch(`${BASE}/chat/completions`, {
method: "POST",
headers: {
"content-type": "application/json",
authorization: `Bearer ${KEY}`,
},
body: JSON.stringify({
model: "deepseek-chat",
messages,
temperature: 0,
max_tokens: 16,
stream: false,
}),
});
const ms = Date.now() - t0;
if (!res.ok) {
const text = await res.text();
throw new Error(`${label} http ${res.status}: ${text.slice(0, 300)}`);
}
const j = await res.json();
const u = j.usage ?? {};
const hit = u.prompt_cache_hit_tokens ?? 0;
const miss = u.prompt_cache_miss_tokens ?? 0;
const prompt = u.prompt_tokens ?? 0;
const ratio = hit + miss > 0 ? (hit / (hit + miss)) * 100 : 0;
console.log(
`[${label}] prompt=${prompt} hit=${hit} miss=${miss} hit%=${ratio.toFixed(1)} ${ms}ms`,
);
return { hit, miss, prompt };
}
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
async function main() {
console.log("=== Phase 1: warm cache with full conversation ===");
const warm = [
{ role: "system", content: SYS },
{ role: "user", content: MSG_A_FULL },
{ role: "assistant", content: "ack A" },
{ role: "user", content: MSG_B },
{ role: "assistant", content: "ack B" },
{ role: "user", content: MSG_C },
{ role: "assistant", content: "ack C" },
{ role: "user", content: "say hi" },
];
await call("warm-1", warm);
await sleep(1500);
await call("warm-2", warm);
console.log("\n=== Phase 2: append a new turn (cache should hit on prefix) ===");
const appended = [
...warm,
{ role: "assistant", content: "hi" },
{ role: "user", content: "say bye" },
];
await sleep(1500);
const appendResult = await call("append", appended);
console.log("\n=== Phase 3: mutate MSG_A in place + append same new turn ===");
const mutated = [
{ role: "system", content: SYS },
{ role: "user", content: MSG_A_TRUNCATED },
{ role: "assistant", content: "ack A" },
{ role: "user", content: MSG_B },
{ role: "assistant", content: "ack B" },
{ role: "user", content: MSG_C },
{ role: "assistant", content: "ack C" },
{ role: "user", content: "say hi" },
{ role: "assistant", content: "hi" },
{ role: "user", content: "say bye" },
];
await sleep(1500);
const mutateResult = await call("mutate", mutated);
console.log("\n=== Result (Phases 1-3) ===");
const lostHit = appendResult.hit - mutateResult.hit;
console.log(
`append: hit=${appendResult.hit}/${appendResult.prompt} mutate: hit=${mutateResult.hit}/${mutateResult.prompt}`,
);
console.log(`cache tokens lost to in-place mutation: ${lostHit}`);
if (lostHit > 100) {
console.log("VERDICT: in-place mutation destroys cache. Hypothesis confirmed.");
} else {
console.log("VERDICT: cache survived mutation. Hypothesis rejected.");
}
console.log("\n=== Phase 4: append-only across many turns (the new code's behavior) ===");
const session = [
{ role: "system", content: SYS },
{ role: "user", content: MSG_A_FULL },
{ role: "assistant", content: "ack A" },
{ role: "user", content: MSG_B },
{ role: "assistant", content: "ack B" },
];
const ratios = [];
for (let i = 0; i < 5; i++) {
session.push({ role: "user", content: `turn ${i}: ${filler(`Q${i}`, 10)}` });
await sleep(1200);
const r = await call(`turn-${i}`, session);
session.push({ role: "assistant", content: `reply ${i}` });
const total = r.hit + r.miss;
ratios.push(total > 0 ? (r.hit / total) * 100 : 0);
}
const avg = ratios.reduce((a, b) => a + b, 0) / ratios.length;
console.log(`\nappend-only cache hit % across 5 turns: ${ratios.map((x) => x.toFixed(1)).join(", ")}`);
console.log(`average: ${avg.toFixed(1)}%`);
if (avg > 80) {
console.log("VERDICT: append-only keeps cache warm across turns. New strategy validated.");
} else {
console.log("VERDICT: cache hit lower than expected — investigate.");
}
}
main().catch((e) => {
console.error(e);
process.exit(1);
});
+167
View File
@@ -0,0 +1,167 @@
/**
* Long-session probe — drives CacheFirstLoop through 20 real turns
* with oversized tool results (each ~4k tokens, the size that USED to
* trigger the old turn-end auto-compaction every turn).
*
* Reports per-turn: prompt size, cache hit %, miss tokens, USD cost.
* Surfaces: cache trajectory, cost shape, anything degrading over time.
*
* Run: REASONIX_LOG_LEVEL=ERROR npx tsx scripts/probe-long-session.mts
*/
import { readFileSync } from "node:fs";
import { DeepSeekClient } from "../src/client.js";
import { CacheFirstLoop } from "../src/loop.js";
import { ImmutablePrefix } from "../src/memory/runtime.js";
import { DEEPSEEK_CONTEXT_TOKENS } from "../src/telemetry/stats.js";
import { ToolRegistry } from "../src/tools.js";
// Force a small ctx window so the 50% fold threshold trips in a few
// turns instead of needing 200+ turns at the real 1M cap. Same model
// id, real API call, just the local gauge is shrunk.
DEEPSEEK_CONTEXT_TOKENS["deepseek-chat"] = 50_000;
function loadDotenv(path: string) {
const txt = readFileSync(path, "utf8");
for (const line of txt.split(/\r?\n/)) {
const m = line.match(/^([A-Z_][A-Z0-9_]*)=(.*)$/);
if (m && !process.env[m[1]]) process.env[m[1]] = m[2];
}
}
loadDotenv("./.env.testbak");
const PRICE_HIT_PER_M = 0.07;
const PRICE_MISS_PER_M = 0.27;
const PRICE_COMPLETION_PER_M = 1.1;
const docLine = (i: number, sec: string) =>
`[${sec}#${i}] section ${sec} entry ${i}: requirement traces to constraint ${(i % 7) + 1}, status ${i % 3 === 0 ? "open" : "closed"}, owner team-${(i % 5) + 1}, last touched 2026-04-${(i % 28) + 1}.`;
async function main() {
const reg = new ToolRegistry();
reg.register({
name: "read_doc",
description: "Read a section of a project document.",
parameters: {
type: "object",
properties: { section: { type: "string" } },
required: ["section"],
},
fn: async (args: Record<string, unknown>) => {
const sec = String(args.section ?? "default");
const lines = Array.from({ length: 65 }, (_, i) => docLine(i, sec));
return lines.join("\n");
},
});
const client = new DeepSeekClient();
const model = "deepseek-chat";
const loop = new CacheFirstLoop({
client,
prefix: new ImmutablePrefix({
system:
"You are a documentation triage agent. For each turn, call read_doc with the section the user asks about, then reply with one short sentence summarizing what you found.",
toolSpecs: reg.specs(),
}),
tools: reg,
stream: false,
model,
maxToolIters: 4,
});
let mutations = 0;
let folds = 0;
const origCompactInPlace = loop.log.compactInPlace.bind(loop.log);
loop.log.compactInPlace = (...args) => {
mutations++;
return origCompactInPlace(...args);
};
const sections = [
"auth",
"billing",
"telemetry",
"rate-limit",
"webhooks",
"search",
"indexing",
"permissions",
"audit",
"exports",
"imports",
"cdn",
"analytics",
"rbac",
"sso",
"scheduler",
"workflows",
"notifications",
"reports",
"api-v2",
];
console.log("turn | prompt | hit | miss | hit% | $/turn | $cum");
console.log("-----+----------+---------+---------+------+----------+--------");
let cumCost = 0;
let forceSummaryHit = false;
for (let i = 0; i < sections.length; i++) {
const t0 = Date.now();
let usage: {
promptTokens: number;
completionTokens: number;
promptCacheHitTokens: number;
promptCacheMissTokens: number;
} | null = null;
let warning = "";
for await (const ev of loop.step(`Read the "${sections[i]}" section.`)) {
if (ev.role === "assistant_final" && ev.stats?.usage) {
usage = ev.stats.usage as typeof usage;
}
if (ev.role === "warning" && ev.content) {
warning = ev.content;
if (/folded \d+ messages/.test(ev.content)) folds++;
}
if (ev.forcedSummary) forceSummaryHit = true;
}
const ms = Date.now() - t0;
if (!usage) {
console.log(
`${String(i).padStart(3)} | (no usage) -- ${warning ? `warning: ${warning}` : ""}`,
);
continue;
}
const total = usage.promptCacheHitTokens + usage.promptCacheMissTokens;
const ratio = total > 0 ? (usage.promptCacheHitTokens / total) * 100 : 0;
const cost =
(usage.promptCacheHitTokens * PRICE_HIT_PER_M +
usage.promptCacheMissTokens * PRICE_MISS_PER_M +
usage.completionTokens * PRICE_COMPLETION_PER_M) /
1_000_000;
cumCost += cost;
console.log(
`${String(i).padStart(3)} | ${String(usage.promptTokens).padStart(7)} | ${String(usage.promptCacheHitTokens).padStart(7)} | ${String(usage.promptCacheMissTokens).padStart(7)} | ${ratio.toFixed(1).padStart(4)} | $${cost.toFixed(5)} | $${cumCost.toFixed(4)} ${ms}ms${warning ? ` (${warning.slice(0, 60)}…)` : ""}`,
);
if (forceSummaryHit) {
console.log(
`\n>> force-summary triggered at turn ${i} (${ratio.toFixed(1)}% cache hit, ${usage.promptTokens} tokens)`,
);
break;
}
}
console.log(`\ntotal log.compactInPlace() calls: ${mutations} (expected: ${folds} folds)`);
console.log(`total cost across session: $${cumCost.toFixed(4)}`);
if (mutations !== folds) {
console.log(`FAIL: ${mutations} mutations but only ${folds} fold events — unexpected mutation`);
process.exit(1);
}
console.log(`\nVERDICT: ${folds} fold(s) fired, no other mutations.`);
}
main().catch((e) => {
console.error(e);
process.exit(1);
});
+118
View File
@@ -0,0 +1,118 @@
/**
* End-to-end cache probe — drives CacheFirstLoop through real turns
* against the live DeepSeek API and reports cache hit % per turn.
*
* The point: validate that the post-PR code (no auto-compaction)
* actually sustains high cache hit on a long-ish session, not just
* that the API-level append-vs-mutate primitive behaves as expected.
*
* Run: REASONIX_LOG_LEVEL=ERROR npx tsx scripts/probe-loop-cache.mts
* Reads DEEPSEEK_API_KEY from .env.testbak.
*/
import { readFileSync } from "node:fs";
import { CacheFirstLoop } from "../src/loop.js";
import { DeepSeekClient } from "../src/client.js";
import { ImmutablePrefix } from "../src/memory/runtime.js";
import { ToolRegistry } from "../src/tools.js";
function loadDotenv(path: string) {
const txt = readFileSync(path, "utf8");
for (const line of txt.split(/\r?\n/)) {
const m = line.match(/^([A-Z_][A-Z0-9_]*)=(.*)$/);
if (m && !process.env[m[1]]) process.env[m[1]] = m[2];
}
}
loadDotenv("./.env.testbak");
const filler = (label: string, n: number): string =>
Array.from(
{ length: n },
(_, i) =>
`${label} line ${i}: lorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.`,
).join("\n");
async function main() {
const reg = new ToolRegistry();
reg.register({
name: "echo",
description: "echo the input back",
parameters: {
type: "object",
properties: { msg: { type: "string" } },
required: ["msg"],
},
fn: async (args: Record<string, unknown>) => `echoed: ${String(args.msg ?? "")}`,
});
const client = new DeepSeekClient();
const loop = new CacheFirstLoop({
client,
prefix: new ImmutablePrefix({
system:
"You are a terse echo bot. Reply with one short sentence. Do not call any tools unless explicitly asked.",
toolSpecs: reg.specs(),
}),
tools: reg,
stream: false,
maxToolIters: 4,
});
// Pre-seed log with a moderate prior conversation (~6k tokens of
// user/assistant turns) so the cache has something substantial to
// hit across subsequent turns.
loop.log.append({ role: "user", content: `prior context: ${filler("ctx", 60)}` });
loop.log.append({ role: "assistant", content: "noted." });
loop.log.append({ role: "user", content: `more context: ${filler("more", 40)}` });
loop.log.append({ role: "assistant", content: "noted." });
const ratios: number[] = [];
let mutations = 0;
const origCompactInPlace = loop.log.compactInPlace.bind(loop.log);
loop.log.compactInPlace = (...args: Parameters<typeof origCompactInPlace>) => {
mutations++;
return origCompactInPlace(...args);
};
for (let i = 0; i < 6; i++) {
let usage: { promptTokens: number; promptCacheHitTokens: number; promptCacheMissTokens: number } | null = null;
for await (const ev of loop.step(`Turn ${i}: just say "ok ${i}".`)) {
if (ev.role === "assistant_final" && ev.stats?.usage) {
usage = ev.stats.usage as typeof usage;
}
}
if (!usage) {
console.log(`turn-${i}: no usage captured`);
ratios.push(0);
continue;
}
const total = usage.promptCacheHitTokens + usage.promptCacheMissTokens;
const ratio = total > 0 ? (usage.promptCacheHitTokens / total) * 100 : 0;
console.log(
`turn-${i}: prompt=${usage.promptTokens} hit=${usage.promptCacheHitTokens} miss=${usage.promptCacheMissTokens} hit%=${ratio.toFixed(1)}`,
);
ratios.push(ratio);
}
console.log(`\ntotal log.compactInPlace() calls: ${mutations}`);
console.log(`cache hit % per turn: ${ratios.map((x) => x.toFixed(1)).join(", ")}`);
const warmRatios = ratios.slice(1);
const avgWarm = warmRatios.reduce((a, b) => a + b, 0) / warmRatios.length;
console.log(`warm-turn average (excluding cold start): ${avgWarm.toFixed(1)}%`);
if (mutations > 0) {
console.log(`\nFAIL: log was mutated ${mutations} time(s) — append-only invariant broken`);
process.exit(1);
}
if (avgWarm < 80) {
console.log(`\nFAIL: warm-turn average ${avgWarm.toFixed(1)}% below 80% threshold`);
process.exit(1);
}
console.log(`\nPASS: append-only sustained, cache hit avg ${avgWarm.toFixed(1)}%`);
}
main().catch((e) => {
console.error(e);
process.exit(1);
});
+4 -2
View File
@@ -315,8 +315,10 @@ export function expandAtMentions(
for (const match of text.matchAll(AT_MENTION_PATTERN)) {
const rawPath = match[1] ?? "";
// Strip trailing dot (sentence terminator): `@foo.ts.` → `@foo.ts`.
// Keep internal dots intact.
const cleaned = rawPath.replace(/\.+$/, "");
// Keep internal dots intact. Manual loop instead of `/\.+$/` — the
// regex is O(n²) on dot-heavy non-matches per CodeQL js/polynomial-redos.
let cleaned = rawPath;
while (cleaned.endsWith(".")) cleaned = cleaned.slice(0, -1);
if (!cleaned) continue;
const token = `@${cleaned}`;
if (seen.has(token)) continue;
+272 -127
View File
@@ -1,9 +1,17 @@
import { render } from "ink";
import React, { useState } from "react";
import { loadApiKey, readConfig, searchEnabled } from "../../config.js";
import {
loadApiKey,
readConfig,
searchEnabled,
webSearchEndpoint,
webSearchEngine,
} from "../../config.js";
import { loadDotenv } from "../../env.js";
import type { CacheFirstLoop } from "../../loop.js";
import { McpClient } from "../../mcp/client.js";
import { type InspectionReport, inspectMcpServer } from "../../mcp/inspect.js";
import { preflightStdioSpec } from "../../mcp/preflight.js";
import { type McpClientHost, bridgeMcpTools } from "../../mcp/registry.js";
import { parseMcpSpec } from "../../mcp/spec.js";
import { SseTransport } from "../../mcp/sse.js";
@@ -23,6 +31,7 @@ import { registerWebTools } from "../../tools/web.js";
import { App } from "../ui/App.js";
import { SessionPicker } from "../ui/SessionPicker.js";
import { Setup } from "../ui/Setup.js";
import { drainTtyResponses } from "../ui/drain-tty.js";
import { KeystrokeProvider } from "../ui/keystroke-context.js";
import { formatMcpLifecycleEvent } from "../ui/mcp-lifecycle.js";
import { formatMcpSlowToast } from "../ui/mcp-toast.js";
@@ -35,6 +44,221 @@ export interface ProgressInfo {
message?: string;
}
interface SpecRecord {
spec: string;
client: McpClient;
summary: McpServerSummary;
/** Names of bridged tools — used for hot-unbridge. */
registeredNames: string[];
/** ToolSpec snapshots captured AFTER bridge — handed to loop.prefix.addTool on hot-add. */
registeredSpecs: import("../../types.js").ToolSpec[];
}
interface RuntimeContext {
getTools: () => ToolRegistry | undefined;
getMcpPrefix: () => string | undefined;
getRequestedCount: () => number;
progressSink: { current: ((info: ProgressInfo) => void) | null };
}
export interface McpRuntime {
size(): number;
specs(): string[];
summaries(): McpServerSummary[];
addSpec(
raw: string,
loop?: CacheFirstLoop,
): Promise<{ ok: true; summary: McpServerSummary } | { ok: false; reason: string }>;
removeSpec(raw: string, loop?: CacheFirstLoop): Promise<boolean>;
reloadFromConfig(loop?: CacheFirstLoop): Promise<{
added: string[];
removed: string[];
failed: Array<{ spec: string; reason: string }>;
summaries: McpServerSummary[];
}>;
closeAll(): Promise<void>;
}
function createMcpRuntime(ctx: RuntimeContext): McpRuntime {
const records = new Map<string, SpecRecord>();
const insertionOrder: string[] = [];
async function addSpec(
raw: string,
loop?: CacheFirstLoop,
): Promise<{ ok: true; summary: McpServerSummary } | { ok: false; reason: string }> {
if (records.has(raw)) {
return { ok: true, summary: records.get(raw)!.summary };
}
const tools = ctx.getTools();
if (!tools) return { ok: false, reason: "no tool registry available" };
const disabledNames = new Set(readConfig().mcpDisabled ?? []);
let label = "anon";
let mcp: McpClient | undefined;
try {
const spec = parseMcpSpec(raw);
label = spec.name ?? "anon";
if (spec.name && disabledNames.has(spec.name)) {
process.stderr.write(`${formatMcpLifecycleEvent({ state: "disabled", name: label })}\n`);
return { ok: false, reason: "disabled by user" };
}
process.stderr.write(`${formatMcpLifecycleEvent({ state: "handshake", name: label })}\n`);
const t0 = Date.now();
const namePrefix = spec.name
? `${spec.name}_`
: ctx.getRequestedCount() === 1 && ctx.getMcpPrefix()
? (ctx.getMcpPrefix() as string)
: "";
if (spec.transport === "stdio") preflightStdioSpec(spec);
const transport: McpTransport =
spec.transport === "sse"
? new SseTransport({ url: spec.url })
: spec.transport === "streamable-http"
? new StreamableHttpTransport({ url: spec.url })
: new StdioTransport({ command: spec.command, args: spec.args });
mcp = new McpClient({ transport });
await mcp.initialize();
const host: McpClientHost = { client: mcp };
const bridge = await bridgeMcpTools(mcp, {
registry: tools,
namePrefix,
serverName: label,
host,
onProgress: (info) => ctx.progressSink.current?.(info),
onSlow: (info) =>
process.stderr.write(
`${formatMcpSlowToast({ name: info.serverName, p95Ms: info.p95Ms, sampleSize: info.sampleSize })}\n`,
),
});
let report: InspectionReport;
try {
report = await inspectMcpServer(mcp);
} catch {
report = {
protocolVersion: mcp.protocolVersion,
serverInfo: mcp.serverInfo,
capabilities: mcp.serverCapabilities ?? {},
tools: { supported: true, items: [] },
resources: { supported: false, reason: "inspect failed" },
prompts: { supported: false, reason: "inspect failed" },
elapsedMs: 0,
};
}
const ms = Date.now() - t0;
const resourceCount = report.resources.supported ? report.resources.items.length : 0;
const promptCount = report.prompts.supported ? report.prompts.items.length : 0;
process.stderr.write(
`${formatMcpLifecycleEvent({
state: "connected",
name: label,
tools: bridge.registeredNames.length,
resources: resourceCount,
prompts: promptCount,
ms,
})}\n`,
);
const summary = buildMcpServerSummary({
label,
spec: raw,
toolCount: bridge.registeredNames.length,
report,
host,
bridgeEnv: bridge.env,
});
// Snapshot tool specs AFTER bridge so hot-add can replay them into loop.prefix.
const allSpecs = tools.specs();
const registeredSpecs = allSpecs.filter((s) =>
bridge.registeredNames.includes(s.function.name),
);
records.set(raw, {
spec: raw,
client: mcp,
summary,
registeredNames: bridge.registeredNames,
registeredSpecs,
});
insertionOrder.push(raw);
// Hot-add: shift the prefix so the live loop sees the new tools
// on the very next turn. Each addTool is one cache-miss turn.
if (loop) for (const s of registeredSpecs) loop.prefix.addTool(s);
return { ok: true, summary };
} catch (err) {
await mcp?.close().catch(() => undefined);
const reason = (err as Error).message;
process.stderr.write(
`${formatMcpLifecycleEvent({ state: "failed", name: label, reason })}\n → run \`reasonix setup\` to remove this entry, or fix the underlying issue (missing npm package, network, etc.).\n`,
);
return { ok: false, reason };
}
}
async function removeSpec(raw: string, loop?: CacheFirstLoop): Promise<boolean> {
const record = records.get(raw);
if (!record) return false;
await record.client.close().catch(() => undefined);
const tools = ctx.getTools();
for (const name of record.registeredNames) {
tools?.unregister(name);
loop?.prefix.removeTool(name);
}
records.delete(raw);
const idx = insertionOrder.indexOf(raw);
if (idx >= 0) insertionOrder.splice(idx, 1);
return true;
}
async function reloadFromConfig(loop?: CacheFirstLoop): Promise<{
added: string[];
removed: string[];
failed: Array<{ spec: string; reason: string }>;
summaries: McpServerSummary[];
}> {
const desired = readConfig().mcp ?? [];
const desiredSet = new Set(desired);
const currentSet = new Set(records.keys());
const added: string[] = [];
const removed: string[] = [];
const failed: Array<{ spec: string; reason: string }> = [];
for (const spec of [...currentSet]) {
if (!desiredSet.has(spec)) {
await removeSpec(spec, loop);
removed.push(spec);
}
}
for (const spec of desired) {
if (currentSet.has(spec)) continue;
const result = await addSpec(spec, loop);
if (result.ok) added.push(spec);
else failed.push({ spec, reason: result.reason });
}
return { added, removed, failed, summaries: summaries() };
}
function specs(): string[] {
return [...insertionOrder];
}
function summaries(): McpServerSummary[] {
return insertionOrder
.map((s) => records.get(s)?.summary)
.filter((s): s is McpServerSummary => Boolean(s));
}
async function closeAll(): Promise<void> {
for (const r of records.values()) await r.client.close().catch(() => undefined);
records.clear();
insertionOrder.length = 0;
}
return {
size: () => records.size,
specs,
summaries,
addSpec,
removeSpec,
reloadFromConfig,
closeAll,
};
}
export interface ChatOptions {
model: string;
system: string;
@@ -85,6 +309,13 @@ export interface ChatOptions {
* URL is visible in the status bar.
*/
noDashboard?: boolean;
/**
* Render into the terminal's alternate screen buffer. Default true —
* alt-screen avoids the scrollback-mode resize/wrap ghost class. Pass
* false (CLI: `--no-alt-screen`) when the chat output needs to remain
* in shell scrollback after exit.
*/
altScreen?: boolean;
}
interface RootProps extends ChatOptions {
@@ -96,6 +327,8 @@ interface RootProps extends ChatOptions {
progressSink: { current: ((info: ProgressInfo) => void) | null };
/** Show the SessionPicker (full list) when no --session was specified and saved sessions exist. */
showPicker: boolean;
/** Hot-reload runtime — passed through to App so /mcp browse + dashboard can bridge after install. */
mcpRuntime: McpRuntime;
}
function Root({
@@ -105,6 +338,7 @@ function Root({
mcpServers,
progressSink,
showPicker,
mcpRuntime,
...appProps
}: RootProps) {
const [key, setKey] = useState<string | undefined>(initialKey);
@@ -176,6 +410,7 @@ function Root({
tools={tools}
mcpSpecs={mcpSpecs}
mcpServers={mcpServers}
mcpRuntime={mcpRuntime}
progressSink={progressSink}
codeMode={appProps.codeMode}
noDashboard={appProps.noDashboard}
@@ -190,10 +425,6 @@ export async function chatCommand(opts: ChatOptions): Promise<void> {
const initialKey = loadApiKey();
const requestedSpecs = opts.mcp ?? [];
const clients: McpClient[] = [];
const successfulSpecs: string[] = [];
const failedSpecs: Array<{ spec: string; reason: string }> = [];
const mcpServers: McpServerSummary[] = [];
// Shared progress sink: the bridge's onProgress callback writes
// through `progressSink.current`, which App.tsx sets to its UI
// updater on mount. Started null so early progress frames (before
@@ -204,122 +435,35 @@ export async function chatCommand(opts: ChatOptions): Promise<void> {
// replacing. When no seed AND no MCP, tools stays undefined and
// the loop runs as a bare chat.
let tools: ToolRegistry | undefined = opts.seedTools;
if (requestedSpecs.length > 0 && !tools) tools = new ToolRegistry();
const disabledNames = new Set(readConfig().mcpDisabled ?? []);
if (requestedSpecs.length > 0) {
if (!tools) tools = new ToolRegistry();
for (const raw of requestedSpecs) {
let label = "anon";
let mcp: McpClient | undefined;
try {
const spec = parseMcpSpec(raw);
label = spec.name ?? "anon";
if (spec.name && disabledNames.has(spec.name)) {
process.stderr.write(`${formatMcpLifecycleEvent({ state: "disabled", name: label })}\n`);
continue;
}
process.stderr.write(`${formatMcpLifecycleEvent({ state: "handshake", name: label })}\n`);
const t0 = Date.now();
const prefix = spec.name
? `${spec.name}_`
: requestedSpecs.length === 1 && opts.mcpPrefix
? opts.mcpPrefix
: "";
const transport: McpTransport =
spec.transport === "sse"
? new SseTransport({ url: spec.url })
: spec.transport === "streamable-http"
? new StreamableHttpTransport({ url: spec.url })
: new StdioTransport({ command: spec.command, args: spec.args });
mcp = new McpClient({ transport });
await mcp.initialize();
// Host indirection lets `/mcp reconnect` swap the underlying client
// without re-bridging the registered tools (closures resolve via
// host.client at call time).
const host: McpClientHost = { client: mcp };
const bridge = await bridgeMcpTools(mcp, {
registry: tools,
namePrefix: prefix,
serverName: label,
host,
onProgress: (info) => progressSink.current?.(info),
onSlow: (info) =>
process.stderr.write(
`${formatMcpSlowToast({ name: info.serverName, p95Ms: info.p95Ms, sampleSize: info.sampleSize })}\n`,
),
});
// Inspect collects resources + prompts once so `/mcp` can render them
// synchronously. Servers that don't support these fall through as
// `{supported: false}` instead of throwing.
let report: InspectionReport;
try {
report = await inspectMcpServer(mcp);
} catch {
report = {
protocolVersion: mcp.protocolVersion,
serverInfo: mcp.serverInfo,
capabilities: mcp.serverCapabilities ?? {},
tools: { supported: true, items: [] },
resources: { supported: false, reason: "inspect failed" },
prompts: { supported: false, reason: "inspect failed" },
elapsedMs: 0,
};
}
const ms = Date.now() - t0;
const resourceCount = report.resources.supported ? report.resources.items.length : 0;
const promptCount = report.prompts.supported ? report.prompts.items.length : 0;
process.stderr.write(
`${formatMcpLifecycleEvent({
state: "connected",
name: label,
tools: bridge.registeredNames.length,
resources: resourceCount,
prompts: promptCount,
ms,
})}\n`,
);
clients.push(mcp);
successfulSpecs.push(raw);
mcpServers.push(
buildMcpServerSummary({
label,
spec: raw,
toolCount: bridge.registeredNames.length,
report,
host,
bridgeEnv: bridge.env,
}),
);
} catch (err) {
// Per-server failure is non-fatal: one broken server shouldn't
// kill a chat that has working servers configured. Recover by
// recording the failure and continuing; user fixes via `reasonix
// setup` without losing their other servers.
await mcp?.close().catch(() => undefined);
const reason = (err as Error).message;
failedSpecs.push({ spec: raw, reason });
process.stderr.write(
`${formatMcpLifecycleEvent({ state: "failed", name: label, reason })}\n → run \`reasonix setup\` to remove this entry, or fix the underlying issue (missing npm package, network, etc.).\n`,
);
}
}
// If every requested server failed AND no seed registry was
// provided, drop the empty registry so the loop still runs as a
// bare chat instead of advertising zero tools. If the caller
// passed seedTools we keep the registry — the seed tools are
// still there and usable.
if (successfulSpecs.length === 0 && !opts.seedTools) {
tools = undefined;
}
const runtime = createMcpRuntime({
getTools: () => tools,
getMcpPrefix: () => opts.mcpPrefix,
getRequestedCount: () => requestedSpecs.length,
progressSink,
});
const failedSpecs: Array<{ spec: string; reason: string }> = [];
for (const raw of requestedSpecs) {
const result = await runtime.addSpec(raw);
if (!result.ok) failedSpecs.push({ spec: raw, reason: result.reason });
}
const mcpSpecs = successfulSpecs;
if (runtime.size() === 0 && !opts.seedTools) {
tools = undefined;
}
const mcpSpecs = runtime.specs();
const mcpServers = runtime.summaries();
// Register web search/fetch tools unless explicitly disabled. DDG
// backs them with no key required; the model invokes them whenever
// a question needs info fresher than its training data.
if (searchEnabled()) {
if (!tools) tools = new ToolRegistry();
registerWebTools(tools);
registerWebTools(tools, {
webSearchEngine: webSearchEngine(),
webSearchEndpoint: webSearchEndpoint(),
});
}
// Memory tools — available in every session, not just code mode.
@@ -350,34 +494,35 @@ export async function chatCommand(opts: ChatOptions): Promise<void> {
const showPicker =
!opts.session && !opts.forceResume && listSessionsForWorkspace(launchWorkspace).length > 0;
// No startup clear, no resize listener. Earlier attempts wrote
// various combinations of \x1b[2J / \x1b[3J / cursor-home to
// present a 'clean canvas' on launch and to neutralize Ink's
// eraseLines miscount on resize, but on xterm.js-based terminals
// (VSCode integrated terminal in particular) those sequences
// interfere with scrollback in ways that make wheel-up scroll
// dead. Letting Ink mount directly leaves the user's previous
// shell prompt visible above (scrolling up just works) and
// accepts the resize-ghost / launch-noise tradeoffs as known
// limitations — `/clear` is the manual reset.
const { waitUntilExit } = render(
<Root
initialKey={initialKey}
tools={tools}
mcpSpecs={mcpSpecs}
mcpServers={mcpServers}
mcpRuntime={runtime}
progressSink={progressSink}
showPicker={showPicker}
{...opts}
session={resolvedSession}
/>,
// patchConsole:false — winpty/MINTTY redraw-glitch source.
{ exitOnCtrlC: true, patchConsole: false },
{
exitOnCtrlC: true,
// patchConsole:false — winpty/MINTTY redraw-glitch source.
patchConsole: false,
incrementalRendering: true,
// Default true — alt-screen is the only mode without scrollback-
// reflow ghosting. `--no-alt-screen` opts back into scrollback mode
// for users who need chat output preserved in shell history on exit.
alternateScreen: opts.altScreen !== false,
},
);
try {
await waitUntilExit();
} finally {
for (const c of clients) await c.close();
await runtime.closeAll();
// Eat any pending terminal-feature-detection responses (#365) so the
// parent shell doesn't print them as junk after exit.
await drainTtyResponses();
}
}
+3
View File
@@ -66,6 +66,8 @@ export interface CodeOptions {
systemAppend?: string;
/** Path to a UTF-8 text file whose contents are appended to the code system prompt. */
systemAppendFile?: string;
/** Default true. Pass false (CLI: `--no-alt-screen`) to keep chat output in shell scrollback. */
altScreen?: boolean;
}
export async function codeCommand(opts: CodeOptions = {}): Promise<void> {
@@ -190,5 +192,6 @@ export async function codeCommand(opts: CodeOptions = {}): Promise<void> {
forceResume: opts.forceResume,
forceNew: opts.forceNew,
noDashboard: opts.noDashboard,
altScreen: opts.altScreen,
});
}
+1 -1
View File
@@ -226,7 +226,7 @@ async function checkSessions(): Promise<Check> {
return {
label: "sessions ",
level: "warn",
detail: `${detail} · ${stale} idle ≥90d (run /prune-sessions)`,
detail: `${detail} · ${stale} idle ≥90d (run \`reasonix prune-sessions\`)`,
};
}
return { label: "sessions ", level: "ok", detail };
+8
View File
@@ -80,6 +80,14 @@ function detailsFor(e: Event): string {
return `${e.callId} reason=${e.reason}`;
case "tool.result":
return `${e.callId} ${e.ok ? "ok" : "err"} ${e.output.length}B${e.truncated ? " [trunc]" : ""}`;
case "tool.call":
return `${e.name} args=${truncate(JSON.stringify(e.args), 60)}`;
case "tool.confirm.allow":
return `${e.kind} ${quote(e.payload.command, 60)}`;
case "tool.confirm.deny":
return `${e.kind} ${quote(e.payload.command, 60)}${e.denyContext ? ` — ${truncate(e.denyContext, 40)}` : ""}`;
case "tool.confirm.always_allow":
return `${e.kind} ${quote(e.payload.command, 60)} prefix=${truncate(e.prefix, 30)}`;
case "effect.file.touched":
return `${e.mode} ${e.path} (${e.bytes}B)`;
case "effect.memory.written":
+236
View File
@@ -0,0 +1,236 @@
/** `reasonix mcp browse` — Ink TUI for the MCP marketplace. Lazy-loads pages on scroll. */
import { Box, Text, render, useApp, useInput } from "ink";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { readConfig, writeConfig } from "../../config.js";
import { loadDotenv } from "../../env.js";
import {
type RegistryHandle,
loadMorePages,
openRegistry,
specStringFor,
} from "../../mcp/registry-fetch.js";
import type { RegistryEntry } from "../../mcp/registry-types.js";
const VISIBLE_ROWS = 12;
interface State {
handle: RegistryHandle | null;
loading: boolean;
query: string;
selected: number;
status: string;
}
function rankAndFilter(entries: RegistryEntry[], query: string): RegistryEntry[] {
const q = query.trim().toLowerCase();
const list = q
? entries.filter((e) => `${e.name} ${e.title} ${e.description}`.toLowerCase().includes(q))
: entries;
return [...list].sort((a, b) => {
const ap = a.popularity ?? -1;
const bp = b.popularity ?? -1;
if (ap !== bp) return bp - ap;
return a.name.localeCompare(b.name);
});
}
function McpBrowseApp() {
const app = useApp();
const [state, setState] = useState<State>({
handle: null,
loading: true,
query: "",
selected: 0,
status: "opening registry…",
});
const setStatus = useCallback((status: string) => {
setState((s) => ({ ...s, status }));
}, []);
useEffect(() => {
let cancelled = false;
(async () => {
try {
const handle = await openRegistry({});
if (cancelled) return;
const ageMs = Date.now() - handle.fetchedAt;
const ageStr =
ageMs < 60_000 ? `${Math.floor(ageMs / 1000)}s` : `${Math.floor(ageMs / 60_000)}m`;
setState((s) => ({
...s,
handle,
loading: false,
status: `${handle.source} · ${handle.cache.entries.length} entries${
handle.fromCache ? ` · cached ${ageStr} ago` : ""
}`,
}));
} catch (err) {
if (cancelled) return;
setState((s) => ({ ...s, loading: false, status: `error: ${(err as Error).message}` }));
}
})();
return () => {
cancelled = true;
};
}, []);
const filtered = useMemo(() => {
if (!state.handle) return [];
return rankAndFilter(state.handle.cache.entries, state.query);
}, [state.handle, state.query]);
const selected = filtered[state.selected];
const fetchMore = useCallback(async () => {
if (!state.handle || state.loading) return;
if (state.handle.cache.pagination.nextCursor === null) {
setStatus("no more pages — registry exhausted");
return;
}
setState((s) => ({ ...s, loading: true, status: "loading more…" }));
try {
const r = await loadMorePages(state.handle, { pages: 5 });
setState((s) => ({
...s,
loading: false,
status: `+${r.newEntries} entries (${state.handle?.cache.entries.length ?? 0} total)${
r.exhausted ? " · exhausted" : ""
}`,
}));
} catch (err) {
setState((s) => ({ ...s, loading: false, status: `error: ${(err as Error).message}` }));
}
}, [state.handle, state.loading, setStatus]);
const install = useCallback(
(entry: RegistryEntry) => {
if (!entry.install) {
setStatus(`${entry.name} has no install info (smithery listing)`);
return;
}
try {
const spec = specStringFor(entry.name, entry.install);
const cfg = readConfig();
const existing = cfg.mcp ?? [];
if (existing.includes(spec)) {
setStatus(`already installed: ${spec}`);
return;
}
writeConfig({ ...cfg, mcp: [...existing, spec] });
setStatus(`installed → ${spec}`);
} catch (err) {
setStatus(`install failed: ${(err as Error).message}`);
}
},
[setStatus],
);
useInput((input, key) => {
if (key.escape || (key.ctrl && input === "c")) {
app.exit();
return;
}
if (key.upArrow) {
setState((s) => ({ ...s, selected: Math.max(0, s.selected - 1) }));
return;
}
if (key.downArrow) {
setState((s) => ({ ...s, selected: Math.min(filtered.length - 1, s.selected + 1) }));
return;
}
if (key.return) {
if (selected) install(selected);
return;
}
if (key.tab || (key.ctrl && input === "n")) {
void fetchMore();
return;
}
if (key.backspace || key.delete) {
setState((s) => ({ ...s, query: s.query.slice(0, -1), selected: 0 }));
return;
}
if (input && !key.ctrl && !key.meta) {
setState((s) => ({ ...s, query: s.query + input, selected: 0 }));
}
});
const start = Math.max(
0,
Math.min(state.selected - Math.floor(VISIBLE_ROWS / 2), filtered.length - VISIBLE_ROWS),
);
const window = filtered.slice(Math.max(0, start), Math.max(0, start) + VISIBLE_ROWS);
return (
<Box flexDirection="column" paddingX={1}>
<Box>
<Text bold color="cyan">
◈ MCP marketplace
</Text>
<Text dimColor>{` · ${state.status}`}</Text>
</Box>
<Box marginTop={1}>
<Text>search: </Text>
<Text color="white">{state.query || "(type to filter)"}</Text>
<Text dimColor>{` ${filtered.length} match${filtered.length === 1 ? "" : "es"}`}</Text>
</Box>
<Box marginTop={1} flexDirection="column">
{window.length === 0 ? (
<Text dimColor>{state.loading ? "loading…" : "no entries"}</Text>
) : (
window.map((e, i) => {
const idx = (start || 0) + i;
const active = idx === state.selected;
const tag =
e.source === "official" ? "[off]" : e.source === "smithery" ? "[smt]" : "[loc]";
const pop = e.popularity !== undefined ? ` · ${e.popularity.toLocaleString()}` : "";
return (
<Box key={e.name}>
<Text color={active ? "cyan" : undefined}>{active ? "▸ " : " "}</Text>
<Text bold={active}>{e.name.padEnd(40).slice(0, 40)}</Text>
<Text dimColor>{` ${tag}${pop}`}</Text>
</Box>
);
})
)}
</Box>
{selected ? (
<Box marginTop={1} flexDirection="column">
<Text bold color="white">
{selected.title}
</Text>
{selected.description ? <Text dimColor>{selected.description.slice(0, 160)}</Text> : null}
{selected.install ? (
<Text dimColor>
{`spec: ${selected.install.runtime} ${selected.install.packageId ?? selected.install.url ?? "—"} · ${selected.install.transport}`}
</Text>
) : (
<Text dimColor>(smithery listing — install info not exposed)</Text>
)}
{selected.install?.requiredEnv?.length ? (
<Text color="yellow">{`needs: ${selected.install.requiredEnv.join(", ")}`}</Text>
) : null}
</Box>
) : null}
<Box marginTop={1}>
<Text dimColor>type to filter · ↑↓ pick · enter install · tab load more · esc quit</Text>
</Box>
</Box>
);
}
export interface McpBrowseOptions {
/** Reserved — currently unused, kept for symmetry with other commands. */
_unused?: never;
}
export async function mcpBrowseCommand(_opts: McpBrowseOptions = {}): Promise<void> {
loadDotenv();
const { waitUntilExit } = render(<McpBrowseApp />, {
exitOnCtrlC: true,
patchConsole: false,
});
await waitUntilExit();
}
+28
View File
@@ -1,6 +1,7 @@
import { McpClient } from "../../mcp/client.js";
import { inspectMcpServer } from "../../mcp/inspect.js";
import type { InspectionReport } from "../../mcp/inspect.js";
import { preflightStdioSpec } from "../../mcp/preflight.js";
import { parseMcpSpec } from "../../mcp/spec.js";
import { SseTransport } from "../../mcp/sse.js";
import { type McpTransport, StdioTransport } from "../../mcp/stdio.js";
@@ -15,6 +16,7 @@ export interface McpInspectOptions {
export async function mcpInspectCommand(opts: McpInspectOptions): Promise<void> {
const spec = parseMcpSpec(opts.spec);
if (spec.transport === "stdio") preflightStdioSpec(spec);
const transport: McpTransport =
spec.transport === "sse"
? new SseTransport({ url: spec.url })
@@ -35,6 +37,32 @@ export async function mcpInspectCommand(opts: McpInspectOptions): Promise<void>
}
}
export function formatMcpInspectFailure(err: unknown): string {
const error = err instanceof Error ? err : new Error(String(err));
const message = error.message;
const code = (error as NodeJS.ErrnoException).code;
if (code === "ENOENT") {
const command = message.match(/^spawn\s+([^\s]+)\s+ENOENT$/)?.[1] ?? "the command";
return `${message} — try: install or verify \`${command}\`, then check the MCP spec's command spelling`;
}
if (code === "ECONNREFUSED") {
const target = message.match(/\b(https?:\/\/\S+|\d+\.\d+\.\d+\.\d+:\d+|localhost:\d+)\b/i)?.[1];
return `${message} — try: confirm ${target ?? "the MCP server"} is running and the host/port match the spec`;
}
if (/^MCP request initialize \(id=\d+\) timed out after \d+ms$/.test(message)) {
return `${message} — try: confirm the target speaks MCP and completes the handshake before the request timeout`;
}
if (/^(empty MCP spec|MCP spec ".*" has name but no command)/.test(message)) {
return `${message} — try: pass \`name=command args\` or an http(s):// URL`;
}
return message;
}
function formatReport(nsName: string, r: InspectionReport): string {
const lines: string[] = [];
lines.push(`MCP server [${nsName}]`);
+305 -23
View File
@@ -1,33 +1,315 @@
import { readConfig, writeConfig } from "../../config.js";
import { MCP_CATALOG, mcpCommandFor } from "../../mcp/catalog.js";
import {
type FetchProgress,
fetchSmitheryDetail,
handleToFetchResult,
loadMorePages,
openRegistry,
specStringFor,
} from "../../mcp/registry-fetch.js";
import type { RegistryEntry } from "../../mcp/registry-types.js";
export interface McpListOptions {
/** Emit JSON on stdout instead of the human-readable table. */
json?: boolean;
const DEFAULT_LIST_LIMIT = 30;
/** Soft cap on how far `search` walks the registry on first run. */
const SEARCH_PAGE_CAP = 20;
/** Soft cap on how far `install` walks looking for a name. */
const INSTALL_PAGE_CAP = 30;
const progressToStderr: FetchProgress = ({ source, page, entries }) => {
if (page === 1 || page % 5 === 0) {
process.stderr.write(`\r▸ fetching ${source} registry · page ${page} · ${entries} entries`);
}
};
function finishProgressLine(): void {
if (process.stderr.isTTY) process.stderr.write("\r\x1b[K");
else process.stderr.write("\n");
}
export function mcpListCommand(opts: McpListOptions): void {
if (opts.json) {
console.log(JSON.stringify(MCP_CATALOG, null, 2));
return;
}
export interface McpListOptions {
json?: boolean;
/** Skip network — only show the bundled MCP_CATALOG entries. */
local?: boolean;
/** Bypass cache TTL. */
refresh?: boolean;
/** How many entries to show. Default 30. */
limit?: number;
/** Eagerly load this many pages before showing. Default 1. */
pages?: number;
/** Walk all pages of the registry (slow on first run). */
all?: boolean;
}
console.log("Popular MCP servers you can bridge into Reasonix:");
console.log("");
for (const entry of MCP_CATALOG) {
console.log(` ${pad(entry.name, 12)} ${entry.summary}`);
console.log(` ${mcpCommandFor(entry)}`);
if (entry.note) console.log(` · ${entry.note}`);
console.log("");
}
console.log("Usage: reasonix chat <one-of-the---mcp-lines-above>");
console.log(
"Docs: https://github.com/modelcontextprotocol/servers — Anthropic's official server repo",
);
console.log(
" https://mcp.so — community-maintained catalog",
);
export interface McpSearchOptions {
json?: boolean;
refresh?: boolean;
limit?: number;
/** Cap how many pages to walk while searching. Default 20. */
maxPages?: number;
}
export interface McpInstallOptions {
refresh?: boolean;
/** Cap how many pages to walk while looking for the name. Default 30. */
maxPages?: number;
}
function rankEntries(entries: RegistryEntry[]): RegistryEntry[] {
return [...entries].sort((a, b) => {
const ap = a.popularity ?? -1;
const bp = b.popularity ?? -1;
if (ap !== bp) return bp - ap;
return a.name.localeCompare(b.name);
});
}
function pad(s: string, width: number): string {
return s.length >= width ? s : s + " ".repeat(width - s.length);
}
function fmtAge(ms: number): string {
const sec = Math.floor(ms / 1000);
if (sec < 60) return `${sec}s ago`;
if (sec < 3600) return `${Math.floor(sec / 60)}m ago`;
if (sec < 86400) return `${Math.floor(sec / 3600)}h ago`;
return `${Math.floor(sec / 86400)}d ago`;
}
function printEntry(e: RegistryEntry, indent = " "): void {
const tag =
e.source === "official" ? "[official]" : e.source === "smithery" ? "[smithery]" : "[local]";
const pop = e.popularity !== undefined ? ` · ${e.popularity.toLocaleString()} uses` : "";
console.log(`${indent}${pad(e.name, 36)} ${tag}${pop}`);
if (e.description) console.log(`${indent} ${e.description}`);
if (e.install?.requiredEnv?.length) {
console.log(`${indent} needs: ${e.install.requiredEnv.join(", ")}`);
} else if (!e.install) {
console.log(`${indent} (smithery listing — install detail fetched lazily on install)`);
}
}
export async function mcpListCommand(opts: McpListOptions = {}): Promise<void> {
if (opts.local) {
if (opts.json) {
console.log(JSON.stringify(MCP_CATALOG, null, 2));
return;
}
console.log("Bundled MCP servers (offline catalog):");
console.log("");
for (const entry of MCP_CATALOG) {
console.log(` ${pad(entry.name, 12)} ${entry.summary}`);
console.log(` ${mcpCommandFor(entry)}`);
if (entry.note) console.log(` · ${entry.note}`);
console.log("");
}
return;
}
const handle = await openRegistry({ noCache: opts.refresh, onProgress: progressToStderr });
const wantedPages = opts.all ? Number.POSITIVE_INFINITY : (opts.pages ?? 1);
const additional = Math.max(0, wantedPages - handle.cache.pagination.pagesLoaded);
if (additional > 0) {
await loadMorePages(handle, {
pages: additional,
onProgress: progressToStderr,
});
}
finishProgressLine();
const result = handleToFetchResult(handle);
const ranked = rankEntries(result.entries);
const limit = opts.limit ?? DEFAULT_LIST_LIMIT;
const shown = ranked.slice(0, limit);
if (opts.json) {
console.log(
JSON.stringify(
{
source: result.source,
fromCache: result.fromCache,
fetchedAt: result.fetchedAt,
loaded: result.entries.length,
hasMore: result.hasMore,
entries: shown,
},
null,
2,
),
);
return;
}
const ageStr = result.fromCache
? `cached, ${fmtAge(Date.now() - result.fetchedAt)}`
: "just fetched";
const moreStr = result.hasMore ? "more available" : "all loaded";
console.log(
`MCP servers from ${result.source} registry (${result.entries.length} loaded, ${moreStr}, ${ageStr}):`,
);
if (result.errors.length > 0) {
for (const e of result.errors) console.error(` warn: ${e}`);
}
console.log("");
for (const e of shown) printEntry(e);
if (ranked.length > limit) {
console.log(
` … ${ranked.length - limit} more loaded — use \`reasonix mcp search <query>\` to filter`,
);
}
if (result.hasMore) {
console.log(" ▸ more pages available — `reasonix mcp list --pages <n>` or --all");
}
console.log("");
console.log("Install: reasonix mcp install <name>");
}
function matchFilter(query: string): (e: RegistryEntry) => boolean {
const q = query.toLowerCase();
return (e) => `${e.name} ${e.title} ${e.description}`.toLowerCase().includes(q);
}
export async function mcpSearchCommand(query: string, opts: McpSearchOptions = {}): Promise<void> {
const q = query.trim();
if (!q) {
console.error("usage: reasonix mcp search <query>");
process.exit(1);
}
const handle = await openRegistry({ noCache: opts.refresh, onProgress: progressToStderr });
const filter = matchFilter(q);
const limit = opts.limit ?? DEFAULT_LIST_LIMIT;
const cap = opts.maxPages ?? SEARCH_PAGE_CAP;
await loadMorePages(handle, {
pages: Math.max(0, cap - handle.cache.pagination.pagesLoaded),
matchTarget: limit,
filter,
onProgress: progressToStderr,
});
finishProgressLine();
const result = handleToFetchResult(handle);
const matches = rankEntries(result.entries.filter(filter));
const shown = matches.slice(0, limit);
if (opts.json) {
console.log(
JSON.stringify(
{
query: q,
source: result.source,
loaded: result.entries.length,
hasMore: result.hasMore,
matches: matches.length,
entries: shown,
},
null,
2,
),
);
return;
}
if (shown.length === 0) {
console.log(
`No matches for "${q}" across ${result.entries.length} loaded entries (${result.source}${
result.hasMore ? ", more pages exist — try --refresh or `mcp list --all`" : ""
}).`,
);
return;
}
console.log(
`${matches.length} match(es) for "${q}" in ${result.source} registry (${result.entries.length} entries scanned):`,
);
console.log("");
for (const e of shown) printEntry(e);
if (matches.length > limit) console.log(` … ${matches.length - limit} more matches`);
}
function findEntry(entries: RegistryEntry[], name: string): RegistryEntry | null {
const exact = entries.find((e) => e.name === name);
if (exact) return exact;
const lower = name.toLowerCase();
const ci = entries.find((e) => e.name.toLowerCase() === lower);
if (ci) return ci;
const tail = entries.find((e) => e.name.toLowerCase().endsWith(`/${lower}`));
if (tail) return tail;
return null;
}
export async function mcpInstallCommand(name: string, opts: McpInstallOptions = {}): Promise<void> {
const target = name.trim();
if (!target) {
console.error("usage: reasonix mcp install <name>");
process.exit(1);
}
const handle = await openRegistry({ noCache: opts.refresh, onProgress: progressToStderr });
const lower = target.toLowerCase();
const filter = (e: RegistryEntry): boolean => {
const n = e.name.toLowerCase();
return n === lower || n.endsWith(`/${lower}`) || n.includes(lower);
};
const cap = opts.maxPages ?? INSTALL_PAGE_CAP;
await loadMorePages(handle, {
pages: Math.max(0, cap - handle.cache.pagination.pagesLoaded),
matchTarget: 1,
filter,
onProgress: progressToStderr,
});
finishProgressLine();
const entry = findEntry(handle.cache.entries, target);
if (!entry) {
console.error(
`No MCP server named "${target}" found after walking ${handle.cache.pagination.pagesLoaded} page(s) of the ${handle.source} registry.`,
);
if (handle.cache.pagination.nextCursor !== null) {
console.error(`Try: reasonix mcp install ${target} --max-pages 100`);
}
process.exit(1);
}
if (!entry.install && entry.source === "smithery") {
process.stderr.write(`▸ fetching smithery install detail for ${entry.name}…\n`);
const fetched = await fetchSmitheryDetail(entry.name);
if (fetched) entry.install = fetched;
}
if (!entry.install) {
console.error(
`Could not derive install metadata for "${entry.name}" — try \`npx -y @smithery/cli install ${entry.name}\` directly.`,
);
process.exit(1);
}
let spec: string;
try {
spec = specStringFor(entry.name, entry.install);
} catch (err) {
console.error(`Cannot build install spec for ${entry.name}: ${(err as Error).message}`);
process.exit(1);
}
const cfg = readConfig();
const existing = cfg.mcp ?? [];
if (existing.includes(spec)) {
console.log(`Already installed: ${spec}`);
return;
}
const next = { ...cfg, mcp: [...existing, spec] };
writeConfig(next);
console.log(`Installed: ${entry.name}`);
console.log(` spec: ${spec}`);
if (entry.install.requiredEnv?.length) {
console.log(
` needs: ${entry.install.requiredEnv.join(", ")} (set these in your env before next chat)`,
);
}
console.log("");
console.log(
"Use it: reasonix chat (or `reasonix code`) — the server will be bridged automatically.",
);
}
+38
View File
@@ -0,0 +1,38 @@
import { listSessions, pruneStaleSessions } from "../../memory/session.js";
export interface PruneSessionsOptions {
days?: number;
dryRun?: boolean;
}
export function pruneSessionsCommand(opts: PruneSessionsOptions): void {
const days = opts.days ?? 90;
if (!Number.isFinite(days) || days < 1) {
console.error(`--days must be a positive integer (got ${days}).`);
process.exit(1);
}
if (opts.dryRun) {
const cutoff = Date.now() - days * 24 * 60 * 60 * 1000;
const stale = listSessions().filter((s) => s.mtime.getTime() < cutoff);
if (stale.length === 0) {
console.log(`no sessions idle ≥${days} days. Nothing would be pruned.`);
return;
}
console.log(`would prune ${stale.length} session(s) idle ≥${days} days:`);
for (const s of stale) {
console.log(` ${s.name}`);
}
console.log("");
console.log("re-run without --dry-run to actually delete.");
return;
}
const removed = pruneStaleSessions(days);
if (removed.length === 0) {
console.log(`no sessions idle ≥${days} days. Nothing pruned.`);
return;
}
console.log(`pruned ${removed.length} session(s) idle ≥${days} days:`);
for (const name of removed) {
console.log(` ${name}`);
}
}
+2
View File
@@ -11,6 +11,7 @@ import {
import { loadDotenv } from "../../env.js";
import { CacheFirstLoop, DeepSeekClient, ImmutablePrefix } from "../../index.js";
import { McpClient } from "../../mcp/client.js";
import { preflightStdioSpec } from "../../mcp/preflight.js";
import { bridgeMcpTools } from "../../mcp/registry.js";
import { parseMcpSpec } from "../../mcp/spec.js";
import { SseTransport } from "../../mcp/sse.js";
@@ -103,6 +104,7 @@ export async function runCommand(opts: RunOptions): Promise<void> {
: requestedSpecs.length === 1 && opts.mcpPrefix
? opts.mcpPrefix
: "";
if (spec.transport === "stdio") preflightStdioSpec(spec);
const transport: McpTransport =
spec.transport === "sse"
? new SseTransport({ url: spec.url })
+89 -5
View File
@@ -34,8 +34,10 @@ import { diffCommand } from "./commands/diff.js";
import { doctorCommand } from "./commands/doctor.js";
import { eventsCommand } from "./commands/events.js";
import { indexCommand } from "./commands/index.js";
import { mcpInspectCommand } from "./commands/mcp-inspect.js";
import { mcpListCommand } from "./commands/mcp.js";
import { mcpBrowseCommand } from "./commands/mcp-browse.js";
import { formatMcpInspectFailure, mcpInspectCommand } from "./commands/mcp-inspect.js";
import { mcpInstallCommand, mcpListCommand, mcpSearchCommand } from "./commands/mcp.js";
import { pruneSessionsCommand } from "./commands/prune-sessions.js";
import { replayCommand } from "./commands/replay.js";
import { runCommand } from "./commands/run.js";
import { sessionsCommand } from "./commands/sessions.js";
@@ -111,6 +113,7 @@ program
.option("--harvest", t("ui.harvestHint"))
.option("--budget <usd>", t("ui.budgetHint"), (v) => Number.parseFloat(v))
.option("--no-dashboard", t("ui.noDashboard"))
.option("--no-alt-screen", "keep chat output in shell scrollback (legacy mode, ghost-prone)")
.option("--system-append <prompt>", t("ui.systemAppendHint"))
.option("--system-append-file <path>", t("ui.systemAppendFileHint"))
.action(async (dir: string | undefined, opts) => {
@@ -126,6 +129,7 @@ program
noDashboard: opts.dashboard === false,
systemAppend: opts.systemAppend,
systemAppendFile: opts.systemAppendFile,
altScreen: opts.altScreen !== false,
});
});
@@ -153,6 +157,7 @@ program
.option("--mcp-prefix <str>", t("ui.mcpPrefixHint"))
.option("--no-config", t("ui.noConfigHint"))
.option("--no-dashboard", t("ui.noDashboard"))
.option("--no-alt-screen", "keep chat output in shell scrollback (legacy mode, ghost-prone)")
.action(async (opts) => {
const defaults = resolveDefaults({
model: opts.model,
@@ -188,6 +193,7 @@ program
forceResume: continueOpts.forceResume,
forceNew: !!opts.new,
noDashboard: opts.dashboard === false,
altScreen: opts.altScreen !== false,
});
});
@@ -262,6 +268,15 @@ program
sessionsCommand({ name, verbose: !!opts.verbose });
});
program
.command("prune-sessions")
.description(t("cli.pruneSessions"))
.option("--days <n>", t("ui.pruneDaysHint"), (v) => Number.parseInt(v, 10))
.option("--dry-run", t("ui.pruneDryRunHint"))
.action((opts) => {
pruneSessionsCommand({ days: opts.days, dryRun: !!opts.dryRun });
});
program
.command("events <name>")
.description(t("cli.events"))
@@ -322,8 +337,77 @@ mcp
.command("list")
.description(t("ui.mcpListDescription"))
.option("--json", t("ui.jsonHintCatalog"))
.action((opts) => {
mcpListCommand({ json: !!opts.json });
.option("--local", t("ui.mcpLocalHint"))
.option("--refresh", t("ui.mcpRefreshHint"))
.option("--limit <n>", t("ui.mcpLimitHint"), (v) => Number.parseInt(v, 10))
.option("--pages <n>", t("ui.mcpPagesHint"), (v) => Number.parseInt(v, 10))
.option("--all", t("ui.mcpAllHint"))
.action(async (opts) => {
try {
await mcpListCommand({
json: !!opts.json,
local: !!opts.local,
refresh: !!opts.refresh,
limit: typeof opts.limit === "number" && opts.limit > 0 ? opts.limit : undefined,
pages: typeof opts.pages === "number" && opts.pages > 0 ? opts.pages : undefined,
all: !!opts.all,
});
} catch (err) {
process.stderr.write(`mcp list failed: ${(err as Error).message}\n`);
process.exit(1);
}
});
mcp
.command("search <query>")
.description(t("ui.mcpSearchDescription"))
.option("--json", t("ui.jsonHintCatalog"))
.option("--refresh", t("ui.mcpRefreshHint"))
.option("--limit <n>", t("ui.mcpLimitHint"), (v) => Number.parseInt(v, 10))
.option("--max-pages <n>", t("ui.mcpMaxPagesHint"), (v) => Number.parseInt(v, 10))
.action(async (query: string, opts) => {
try {
await mcpSearchCommand(query, {
json: !!opts.json,
refresh: !!opts.refresh,
limit: typeof opts.limit === "number" && opts.limit > 0 ? opts.limit : undefined,
maxPages:
typeof opts.maxPages === "number" && opts.maxPages > 0 ? opts.maxPages : undefined,
});
} catch (err) {
process.stderr.write(`mcp search failed: ${(err as Error).message}\n`);
process.exit(1);
}
});
mcp
.command("install <name>")
.description(t("ui.mcpInstallDescription"))
.option("--refresh", t("ui.mcpRefreshHint"))
.option("--max-pages <n>", t("ui.mcpMaxPagesHint"), (v) => Number.parseInt(v, 10))
.action(async (name: string, opts) => {
try {
await mcpInstallCommand(name, {
refresh: !!opts.refresh,
maxPages:
typeof opts.maxPages === "number" && opts.maxPages > 0 ? opts.maxPages : undefined,
});
} catch (err) {
process.stderr.write(`mcp install failed: ${(err as Error).message}\n`);
process.exit(1);
}
});
mcp
.command("browse")
.description(t("ui.mcpBrowseDescription"))
.action(async () => {
try {
await mcpBrowseCommand();
} catch (err) {
process.stderr.write(`mcp browse failed: ${(err as Error).message}\n`);
process.exit(1);
}
});
mcp
@@ -334,7 +418,7 @@ mcp
try {
await mcpInspectCommand({ spec, json: !!opts.json });
} catch (err) {
process.stderr.write(`mcp inspect failed: ${(err as Error).message}\n`);
process.stderr.write(`mcp inspect failed: ${formatMcpInspectFailure(err)}\n`);
process.exit(1);
}
});
+589 -457
View File
File diff suppressed because it is too large. Load diff
-1
View File
@@ -1,6 +1,5 @@
/** Modal picker for `ask_choice` — options + optional "type my own" escape hatch. */
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React in value scope for JSX compilation
import React from "react";
import type { ChoiceOption } from "../../tools/choice.js";
import { SingleSelect } from "./Select.js";
-259
View File
@@ -1,259 +0,0 @@
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);
}
-1
View File
@@ -1,7 +1,6 @@
/** `/mcp` browser modal — keyboard-driven server list per design §24. */
import { Box, Text } from "ink";
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React in value scope for JSX compilation
import React, { useState } from "react";
import { useKeystroke } from "./keystroke-context.js";
import { toggleMcpDisabled } from "./mcp-disable.js";
+83
View File
@@ -0,0 +1,83 @@
/** `/mcp` slash modal — single hub with two tabs: Live (attached servers) + Marketplace (registry). */
import { Box, Text } from "ink";
import React, { useState } from "react";
import { McpBrowser } from "./McpBrowser.js";
import { McpMarketplace } from "./McpMarketplace.js";
import { useKeystroke } from "./keystroke-context.js";
import type { ApplyAppend } from "./mcp-reconnect-kickoff.js";
import type { McpServerSummary } from "./slash/types.js";
import { COLOR } from "./theme.js";
export type McpHubTab = "live" | "marketplace";
export interface McpHubProps {
initialTab: McpHubTab;
liveServers: McpServerSummary[];
configPath: string;
onClose: () => void;
postInfo: (text: string) => void;
applyAppend?: ApplyAppend;
reloadMcp?: () => Promise<{
added: string[];
removed: string[];
failed: Array<{ spec: string; reason: string }>;
}>;
}
export function McpHub({
initialTab,
liveServers,
configPath,
onClose,
postInfo,
applyAppend,
reloadMcp,
}: McpHubProps) {
const [tab, setTab] = useState<McpHubTab>(initialTab);
// Hub-level: Tab key cycles tabs. Inner components don't bind Tab
// (Marketplace rebound to PgDn for load-more) so no conflict.
useKeystroke((ev) => {
if (ev.paste) return;
if (ev.tab) setTab((t) => (t === "live" ? "marketplace" : "live"));
});
return (
<Box flexDirection="column">
<Box paddingX={1}>
<Text bold color={COLOR.brand}>
◈ MCP
</Text>
<Text>{" "}</Text>
<TabPill label="Live" count={liveServers.length} active={tab === "live"} />
<Text>{" "}</Text>
<TabPill label="Marketplace" active={tab === "marketplace"} />
<Text dimColor>{" tab to switch"}</Text>
</Box>
{tab === "live" ? (
<McpBrowser
servers={liveServers}
configPath={configPath}
onClose={onClose}
postInfo={postInfo}
applyAppend={applyAppend}
/>
) : (
<McpMarketplace onClose={onClose} postInfo={postInfo} reloadMcp={reloadMcp} />
)}
</Box>
);
}
function TabPill({ label, count, active }: { label: string; count?: number; active: boolean }) {
const text = count !== undefined ? `${label} (${count})` : label;
if (active) {
return (
<Text bold color={COLOR.brand}>
[{text}]
</Text>
);
}
return <Text dimColor>{` ${text} `}</Text>;
}
+318
View File
@@ -0,0 +1,318 @@
/** `/mcp browse` modal — registry marketplace inside the chat session. */
import { Box, Text } from "ink";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { readConfig, writeConfig } from "../../config.js";
import {
type RegistryHandle,
fetchSmitheryDetail,
loadMorePages,
openRegistry,
specStringFor,
} from "../../mcp/registry-fetch.js";
import type { RegistryEntry } from "../../mcp/registry-types.js";
import { useKeystroke } from "./keystroke-context.js";
import { COLOR } from "./theme.js";
const VISIBLE_ROWS = 10;
export interface McpMarketplaceProps {
onClose: () => void;
/** Pushed back into the chat scrollback after install/uninstall. */
postInfo: (text: string) => void;
/** Optional hot-reload — present in chat session, absent in standalone CLI use. */
reloadMcp?: () => Promise<{
added: string[];
removed: string[];
failed: Array<{ spec: string; reason: string }>;
}>;
}
interface State {
handle: RegistryHandle | null;
loading: boolean;
query: string;
selected: number;
status: string;
/** specs currently in config.mcp[] — refreshed after install/uninstall. */
installedSpecs: string[];
}
function rankAndFilter(entries: RegistryEntry[], query: string): RegistryEntry[] {
const q = query.trim().toLowerCase();
const list = q
? entries.filter((e) => `${e.name} ${e.title} ${e.description}`.toLowerCase().includes(q))
: entries;
return [...list].sort((a, b) => {
const ap = a.popularity ?? -1;
const bp = b.popularity ?? -1;
if (ap !== bp) return bp - ap;
return a.name.localeCompare(b.name);
});
}
function readInstalledSpecs(): string[] {
return readConfig().mcp ?? [];
}
function isInstalled(installedSpecs: string[], entry: RegistryEntry): string | null {
if (!entry.install) return null;
try {
const spec = specStringFor(entry.name, entry.install);
return installedSpecs.includes(spec) ? spec : null;
} catch {
return null;
}
}
export function McpMarketplace({ onClose, postInfo, reloadMcp }: McpMarketplaceProps) {
const [state, setState] = useState<State>({
handle: null,
loading: true,
query: "",
selected: 0,
status: "opening registry…",
installedSpecs: readInstalledSpecs(),
});
useEffect(() => {
let cancelled = false;
(async () => {
try {
const handle = await openRegistry({});
if (cancelled) return;
setState((s) => ({
...s,
handle,
loading: false,
status: `${handle.source} · ${handle.cache.entries.length} entries${
handle.fromCache ? " · cached" : ""
}`,
}));
} catch (err) {
if (cancelled) return;
setState((s) => ({ ...s, loading: false, status: `error: ${(err as Error).message}` }));
}
})();
return () => {
cancelled = true;
};
}, []);
const filtered = useMemo(() => {
if (!state.handle) return [];
return rankAndFilter(state.handle.cache.entries, state.query);
}, [state.handle, state.query]);
const selected = filtered[state.selected];
const fetchMore = useCallback(async () => {
if (!state.handle || state.loading) return;
if (state.handle.cache.pagination.nextCursor === null) {
setState((s) => ({ ...s, status: "all pages loaded" }));
return;
}
setState((s) => ({ ...s, loading: true, status: "loading more…" }));
try {
const r = await loadMorePages(state.handle, { pages: 5 });
setState((s) => ({
...s,
loading: false,
status: `+${r.newEntries} · ${state.handle?.cache.entries.length ?? 0} total${
r.exhausted ? " · exhausted" : ""
}`,
}));
} catch (err) {
setState((s) => ({ ...s, loading: false, status: `error: ${(err as Error).message}` }));
}
}, [state.handle, state.loading]);
const installOrToggle = useCallback(
async (entry: RegistryEntry) => {
const installed = isInstalled(state.installedSpecs, entry);
if (installed) {
const cfg = readConfig();
const next = (cfg.mcp ?? []).filter((s) => s !== installed);
writeConfig({ ...cfg, mcp: next });
setState((s) => ({
...s,
installedSpecs: next,
status: `uninstalled ${entry.name}`,
}));
if (reloadMcp) {
try {
await reloadMcp();
postInfo(`✓ uninstalled ${entry.name} — bridge dropped`);
} catch (err) {
postInfo(
`✓ uninstalled ${entry.name} — restart \`reasonix code\` to drop the bridge (reload failed: ${(err as Error).message})`,
);
}
} else {
postInfo(`✓ uninstalled ${entry.name} — restart \`reasonix code\` to drop the bridge`);
}
return;
}
let install = entry.install;
if (!install && entry.source === "smithery") {
setState((s) => ({ ...s, loading: true, status: "fetching smithery detail…" }));
try {
const detail = await fetchSmitheryDetail(entry.name);
if (detail) {
install = detail;
entry.install = detail;
}
} catch {
/* fall through to error below */
}
setState((s) => ({ ...s, loading: false }));
}
if (!install) {
setState((s) => ({
...s,
status: `no install info for ${entry.name} — try \`npx -y @smithery/cli install ${entry.name}\``,
}));
return;
}
try {
const spec = specStringFor(entry.name, install);
const cfg = readConfig();
const existing = cfg.mcp ?? [];
if (existing.includes(spec)) {
setState((s) => ({
...s,
installedSpecs: existing,
status: `already installed: ${spec}`,
}));
return;
}
const next = [...existing, spec];
writeConfig({ ...cfg, mcp: next });
setState((s) => ({ ...s, installedSpecs: next, status: `installed → ${spec}` }));
const envHint = install.requiredEnv?.length
? ` · needs env: ${install.requiredEnv.join(", ")}`
: "";
if (reloadMcp) {
try {
const r = await reloadMcp();
const failedHere = r.failed.find((f) => f.spec === spec);
if (failedHere) {
postInfo(`▲ installed ${entry.name} — bridge failed: ${failedHere.reason}${envHint}`);
} else {
postInfo(`✓ installed ${entry.name} — bridged${envHint}`);
}
} catch (err) {
postInfo(
`✓ installed ${entry.name} — restart \`reasonix code\` to bridge (reload failed: ${(err as Error).message})${envHint}`,
);
}
} else {
postInfo(`✓ installed ${entry.name} — restart \`reasonix code\` to bridge${envHint}`);
}
} catch (err) {
setState((s) => ({ ...s, status: `install failed: ${(err as Error).message}` }));
}
},
[state.installedSpecs, postInfo, reloadMcp],
);
useKeystroke((ev) => {
if (ev.paste) return;
if (ev.escape) {
onClose();
return;
}
if (ev.upArrow) {
setState((s) => ({ ...s, selected: Math.max(0, s.selected - 1) }));
return;
}
if (ev.downArrow) {
setState((s) => ({ ...s, selected: Math.min(filtered.length - 1, s.selected + 1) }));
return;
}
if (ev.return) {
if (selected) void installOrToggle(selected);
return;
}
if (ev.pageDown) {
void fetchMore();
return;
}
if (ev.backspace || ev.delete) {
setState((s) => ({ ...s, query: s.query.slice(0, -1), selected: 0 }));
return;
}
if (ev.input && !ev.ctrl && !ev.meta) {
setState((s) => ({ ...s, query: s.query + ev.input, selected: 0 }));
}
});
const start = Math.max(
0,
Math.min(state.selected - Math.floor(VISIBLE_ROWS / 2), filtered.length - VISIBLE_ROWS),
);
const window = filtered.slice(Math.max(0, start), Math.max(0, start) + VISIBLE_ROWS);
return (
<Box flexDirection="column" paddingX={1}>
<Box>
<Text bold color={COLOR.brand}>
◈ MCP marketplace
</Text>
<Text dimColor>{` · ${state.status}`}</Text>
</Box>
<Box marginTop={1}>
<Text>filter: </Text>
<Text>{state.query || "(type to filter)"}</Text>
<Text dimColor>{` ${filtered.length} match${filtered.length === 1 ? "" : "es"}`}</Text>
</Box>
<Box marginTop={1} flexDirection="column">
{window.length === 0 ? (
<Text dimColor>{state.loading ? "loading…" : "no entries"}</Text>
) : (
window.map((e, i) => {
const idx = (start || 0) + i;
const active = idx === state.selected;
const tag =
e.source === "official" ? "[off]" : e.source === "smithery" ? "[smt]" : "[loc]";
const installedSpec = isInstalled(state.installedSpecs, e);
const installedBadge = installedSpec ? " ✓" : "";
const pop = e.popularity !== undefined ? ` · ${e.popularity.toLocaleString()}` : "";
return (
<Box key={e.name}>
<Text color={active ? COLOR.brand : undefined}>{active ? "▸ " : " "}</Text>
<Text bold={active}>{e.name.padEnd(38).slice(0, 38)}</Text>
<Text dimColor>{` ${tag}${pop}${installedBadge}`}</Text>
</Box>
);
})
)}
</Box>
{selected ? (
<Box marginTop={1} flexDirection="column">
<Text bold>{selected.title}</Text>
{selected.description ? <Text dimColor>{selected.description.slice(0, 200)}</Text> : null}
{selected.install ? (
<Text dimColor>
{`spec: ${selected.install.runtime} ${selected.install.packageId ?? selected.install.url ?? "—"} · ${selected.install.transport}`}
</Text>
) : (
<Text dimColor>(smithery listing — install detail fetched on Enter)</Text>
)}
{selected.install?.requiredEnv?.length ? (
<Text color="yellow">{`needs: ${selected.install.requiredEnv.join(", ")}`}</Text>
) : null}
</Box>
) : null}
<Box marginTop={1}>
<Text dimColor>
type filter · ↑↓ pick · enter{" "}
{selected && isInstalled(state.installedSpecs, selected) ? "uninstall" : "install"} · PgDn
load more · esc close
</Text>
</Box>
</Box>
);
}
+125
View File
@@ -0,0 +1,125 @@
import { Box, Text, useStdout } from "ink";
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React in value scope for JSX compilation
import React, { useState } from "react";
import { useKeystroke } from "./keystroke-context.js";
import { PILL_MODEL, Pill, modelBadgeFor } from "./primitives/Pill.js";
import { FG, TONE } from "./theme/tokens.js";
export type ModelPickerOutcome = { kind: "select"; id: string } | { kind: "quit" };
export interface ModelPickerProps {
/** API-fetched ids; null means "still loading / offline". */
models: ReadonlyArray<string> | null;
/** Model id currently active in the loop — marked with the cursor on open. */
current: string;
onChoose: (outcome: ModelPickerOutcome) => void;
/** Triggers a refetch when the catalog is null/empty and the user presses [r]. */
onRefresh?: () => void;
}
const PAGE_MARGIN = 6;
export function ModelPicker({
models,
current,
onChoose,
onRefresh,
}: ModelPickerProps): React.ReactElement {
const list = (models && models.length > 0 ? models : FALLBACK_MODELS).slice();
if (!list.includes(current)) list.unshift(current);
const initialIndex = Math.max(0, list.indexOf(current));
const [focus, setFocus] = useState(initialIndex);
const { stdout } = useStdout();
const rows = stdout?.rows ?? 40;
const visibleCount = Math.max(3, rows - PAGE_MARGIN);
useKeystroke((ev) => {
if (ev.escape) return onChoose({ kind: "quit" });
if (ev.upArrow) return setFocus((f) => Math.max(0, f - 1));
if (ev.downArrow) return setFocus((f) => Math.min(list.length - 1, f + 1));
if (ev.return) {
const target = list[focus];
if (target) onChoose({ kind: "select", id: target });
return;
}
if (!ev.input) return;
if (ev.input === "q") return onChoose({ kind: "quit" });
if (ev.input === "r") onRefresh?.();
});
const start = Math.max(
0,
Math.min(focus - Math.floor(visibleCount / 2), list.length - visibleCount),
);
const end = Math.min(list.length, start + visibleCount);
const shown = list.slice(start, end);
const hiddenAbove = start;
const hiddenBelow = list.length - end;
const loading = models === null;
const empty = models !== null && models.length === 0;
return (
<Box flexDirection="column" marginY={1}>
<Box>
<Text bold color={TONE.brand}>
{" ◈ REASONIX · pick a model "}
</Text>
<Text color={FG.meta}>
{loading
? " · loading catalog…"
: empty
? " · catalog empty — using known fallbacks"
: ` · ${list.length} available`}
</Text>
</Box>
<Box height={1} />
{hiddenAbove > 0 ? (
<Box>
<Text color={FG.faint}>{` … ${hiddenAbove} earlier`}</Text>
</Box>
) : null}
{shown.map((id, i) => (
<ModelRow key={id} id={id} focused={start + i === focus} active={id === current} />
))}
{hiddenBelow > 0 ? (
<Box>
<Text color={FG.faint}>{` … ${hiddenBelow} more`}</Text>
</Box>
) : null}
<Box marginTop={1}>
<Text color={FG.faint}>{" ↑↓ pick · ⏎ confirm · [r] refresh · esc cancel"}</Text>
</Box>
</Box>
);
}
function ModelRow({
id,
focused,
active,
}: {
id: string;
focused: boolean;
active: boolean;
}): React.ReactElement {
const badge = modelBadgeFor(id);
return (
<Box>
<Text color={focused ? TONE.brand : FG.faint}>{focused ? " ▸ " : " "}</Text>
<Text bold={focused} color={focused ? FG.strong : FG.sub}>
{id.padEnd(24)}
</Text>
<Text> </Text>
<Pill label={badge.label} {...PILL_MODEL[badge.kind]} bold={false} />
{active ? <Text color={TONE.brand}>{" · current"}</Text> : null}
</Box>
);
}
/** Hard-coded known DeepSeek ids — used when the API catalog hasn't loaded yet so the picker isn't empty on first open. */
const FALLBACK_MODELS: ReadonlyArray<string> = [
"deepseek-v4-flash",
"deepseek-v4-pro",
"deepseek-chat",
"deepseek-reasoner",
];
+95
View File
@@ -0,0 +1,95 @@
/** Modal picker for `PlanCheckpointError`: continue / revise / stop. */
import { Box } from "ink";
import React from "react";
import type { PlanStep } from "../../tools/plan.js";
import { PlanStepList, type StepStatus } from "./PlanStepList.js";
import { SingleSelect } from "./Select.js";
import { ApprovalCard } from "./cards/ApprovalCard.js";
import { useReserveRows } from "./layout/viewport-budget.js";
export type CheckpointChoice = "continue" | "revise" | "stop";
export interface PlanCheckpointConfirmProps {
stepId: string;
title?: string;
completed: number;
total: number;
/** Full step list from the approved plan, when available. */
steps?: PlanStep[];
/** Set of stepIds the model has marked complete so far. */
completedStepIds?: Set<string>;
onChoose: (choice: CheckpointChoice) => void;
}
function PlanCheckpointConfirmInner({
stepId,
title,
completed,
total,
steps,
completedStepIds,
onChoose,
}: PlanCheckpointConfirmProps) {
const stepRows = steps?.length ?? 0;
useReserveRows("modal", { min: 10, max: Math.max(14, stepRows + 12) });
const label = title ? `${stepId} · ${title}` : stepId;
const counter = total > 0 ? `${completed}/${total}` : "";
const isLast = total > 0 && completed >= total;
const statuses = buildStatusMap(steps, completedStepIds, stepId, isLast);
const subtitle = counter ? `${counter} · ${label}` : label;
return (
<ApprovalCard tone="ok" glyph="⛁" title="Checkpoint — step done" metaRight={subtitle}>
{steps && steps.length > 0 ? (
<Box marginBottom={1} flexDirection="column">
<PlanStepList steps={steps} statuses={statuses} focusStepId={stepId} />
</Box>
) : null}
<SingleSelect
initialValue={isLast ? "stop" : "continue"}
items={[
{
value: "continue",
label: "Continue — run the next step",
hint: "Model resumes with the next step.",
},
{
value: "revise",
label: "Revise — give feedback before the next step",
hint: "Stay paused, type guidance; model adjusts the remaining plan.",
},
{
value: "stop",
label: "Stop — end the plan here",
hint: "Model summarizes what was done and ends.",
},
]}
onSubmit={(v) => onChoose(v as CheckpointChoice)}
onCancel={() => onChoose("stop")}
/>
</ApprovalCard>
);
}
export const PlanCheckpointConfirm = React.memo(PlanCheckpointConfirmInner);
/** Current step renders as "done" — flush order isn't guaranteed at picker time. */
function buildStatusMap(
steps: PlanStep[] | undefined,
completedStepIds: Set<string> | undefined,
currentStepId: string,
isLast: boolean,
): Map<string, StepStatus> {
const map = new Map<string, StepStatus>();
if (!steps) return map;
for (const step of steps) {
if (completedStepIds?.has(step.id) || step.id === currentStepId) {
map.set(step.id, "done");
} else {
map.set(step.id, "pending");
}
}
void isLast;
return map;
}
+26 -5
View File
@@ -1,14 +1,14 @@
/** Modal-style picker for `submit_plan`: accept / refine / cancel. */
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 { PlanStep } from "../../tools/plan.js";
import { PlanStepList } from "./PlanStepList.js";
import { SingleSelect } from "./Select.js";
import { ApprovalCard } from "./cards/ApprovalCard.js";
import { useReserveRows } from "./layout/viewport-budget.js";
import { CARD, TONE } from "./theme/tokens.js";
import { MarkdownView } from "./markdown-view.js";
import { CARD, FG, TONE } from "./theme/tokens.js";
export type PlanConfirmChoice = "approve" | "refine" | "revise" | "cancel";
@@ -21,9 +21,19 @@ export interface PlanConfirmProps {
projectRoot?: string;
}
const PLAN_BODY_PREVIEW_LINES = 24;
function PlanConfirmInner({ plan, steps, onChoose }: PlanConfirmProps) {
const stepRows = steps?.length ?? 0;
useReserveRows("modal", { min: 10, max: Math.max(16, stepRows + 14) });
const hasSteps = stepRows > 0;
const planLines = plan.split("\n");
const truncatedBody = planLines.length > PLAN_BODY_PREVIEW_LINES;
const previewBody = truncatedBody ? planLines.slice(0, PLAN_BODY_PREVIEW_LINES).join("\n") : plan;
const previewRows = truncatedBody
? PLAN_BODY_PREVIEW_LINES
: Math.min(planLines.length, PLAN_BODY_PREVIEW_LINES);
const reservedFor = hasSteps ? stepRows : previewRows;
useReserveRows("modal", { min: 10, max: Math.max(16, reservedFor + 14) });
const hasOpenQuestions =
/^#{1,6}\s*(open[-\s]?questions?|risks?|unknowns?|assumptions?|unclear)/im.test(plan) ||
@@ -45,9 +55,20 @@ function PlanConfirmInner({ plan, steps, onChoose }: PlanConfirmProps) {
</Text>
</Box>
) : null}
{steps && steps.length > 0 ? (
{hasSteps ? (
<Box marginBottom={1} flexDirection="column">
<PlanStepList steps={steps} />
<PlanStepList steps={steps!} />
</Box>
) : plan.trim().length > 0 ? (
<Box marginBottom={1} flexDirection="column">
<MarkdownView text={previewBody} />
{truncatedBody ? (
<Text color={FG.faint}>
{`… ${planLines.length - PLAN_BODY_PREVIEW_LINES} more line${
planLines.length - PLAN_BODY_PREVIEW_LINES === 1 ? "" : "s"
} above in scrollback`}
</Text>
) : null}
</Box>
) : null}
<SingleSelect
+13 -10
View File
@@ -1,7 +1,6 @@
import { Box, Text, useStdout } from "ink";
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React as a runtime value (classic transform compiles JSX to React.createElement)
import React, { useRef, useState } from "react";
import { useCursor } from "../../renderer/index.js";
import { useKeystroke } from "./keystroke-context.js";
import { useReserveRows } from "./layout/viewport-budget.js";
import { type MultilineKey, lineAndColumn, processMultilineKey } from "./multiline-keys.js";
@@ -26,14 +25,12 @@ export interface PromptInputProps {
onSubmit: (v: string) => void;
disabled?: boolean;
placeholder?: string;
/**
* History recall. Fired when ↑/↓ hits a buffer boundary (empty
* buffer, or cursor already at the first/last line of a multi-line
* buffer). Parent walks its prompt history and swaps the value via
* `onChange`. Absent → keys are consumed silently.
*/
/** Ctrl+P / Ctrl+N — parent walks its prompt history and swaps `value` via `onChange`. */
onHistoryPrev?: () => void;
onHistoryNext?: () => void;
/** ↑/↓ on an empty buffer — parent scrolls chat history. */
onChatScrollUp?: () => void;
onChatScrollDown?: () => void;
}
export function PromptInput({
@@ -44,10 +41,16 @@ export function PromptInput({
placeholder,
onHistoryPrev,
onHistoryNext,
onChatScrollUp,
onChatScrollDown,
}: PromptInputProps) {
// Cap at 24 — collapseLinesForDisplay hides content past ~20 logical lines.
// Quantize spec.max to 4-row buckets so per-keystroke line-count changes
// don't churn viewport-budget; without this every single character that
// adds/removes a newline re-dispatches the allocator and reflows layout.
const inputLineCount = value.length > 0 ? value.split("\n").length : 1;
useReserveRows("input", { min: 1, max: Math.min(inputLineCount + 3, 24) });
const reserveMax = Math.min(Math.ceil(inputLineCount / 4) * 4 + 3, 24);
useReserveRows("input", { min: 1, max: reserveMax });
const [cursor, setCursor] = useState(value.length);
@@ -132,6 +135,8 @@ export function PromptInput({
}
if (action.historyHandoff === "prev") onHistoryPrev?.();
if (action.historyHandoff === "next") onHistoryNext?.();
if (action.chatScrollHandoff === "up") onChatScrollUp?.();
if (action.chatScrollHandoff === "down") onChatScrollDown?.();
}, !disabled);
// ── Render ──────────────────────────────────────────────────────
@@ -153,8 +158,6 @@ export function PromptInput({
const accentColor = disabled ? FG.faint : TONE.brand;
const cursorVisible = true;
const { line: cursorLine, col: cursorCol } = lineAndColumn(value, cursor);
// PromptInput paints its own cursor (`▌` / inverse char) — hide the real terminal cursor so it doesn't double up at the bottom of the screen.
useCursor({ col: 0, rowFromBottom: 0, visible: false });
const renderItems = collapseLinesForDisplay(lines, cursorLine);
const showHugeBufferHints = lines.length > 20;
+6
View File
@@ -19,6 +19,8 @@ export interface SingleSelectProps<V extends string> {
initialValue?: V;
onSubmit: (value: V) => void;
onCancel?: () => void;
/** Fired when Tab is pressed on the currently highlighted item. */
onTab?: (value: V) => void;
/** Optional dim footer beneath the list. */
footer?: string;
}
@@ -27,6 +29,7 @@ export function SingleSelect<V extends string>({
items,
initialValue,
onSubmit,
onTab,
onCancel,
footer,
}: SingleSelectProps<V>) {
@@ -45,6 +48,9 @@ export function SingleSelect<V extends string>({
} else if (ev.return) {
const chosen = items[index];
if (chosen && !chosen.disabled) onSubmit(chosen.value);
} else if (ev.tab) {
const chosen = items[index];
if (chosen && !chosen.disabled) onTab?.(chosen.value);
} else if (ev.escape && onCancel) {
onCancel();
}
+22 -8
View File
@@ -3,7 +3,7 @@ import { Box, Text, useStdout } from "ink";
import React, { useState } from "react";
import type { SessionInfo } from "../../memory/session.js";
import { useKeystroke } from "./keystroke-context.js";
import { FG, TONE, USD_TO_CNY } from "./theme/tokens.js";
import { FG, TONE, formatCost } from "./theme/tokens.js";
export type SessionPickerOutcome =
| { kind: "open"; name: string }
@@ -16,6 +16,8 @@ export interface SessionPickerProps {
sessions: ReadonlyArray<SessionInfo>;
workspace: string;
onChoose: (outcome: SessionPickerOutcome) => void;
/** Live wallet currency from App.tsx; falls back to each session's stored `meta.balanceCurrency` per row. */
walletCurrency?: string;
}
const PAGE_MARGIN = 6;
@@ -24,6 +26,7 @@ export function SessionPicker({
sessions,
workspace,
onChoose,
walletCurrency,
}: SessionPickerProps): React.ReactElement {
const [focus, setFocus] = useState(0);
const [renaming, setRenaming] = useState<{ from: string; buf: string } | null>(null);
@@ -101,7 +104,14 @@ export function SessionPicker({
<Text color={FG.faint}>{" to start a new one"}</Text>
</Box>
) : (
shown.map((s, i) => <SessionRow key={s.name} info={s} focused={start + i === focus} />)
shown.map((s, i) => (
<SessionRow
key={s.name}
info={s}
focused={start + i === focus}
walletCurrency={walletCurrency}
/>
))
)}
{hiddenBelow > 0 ? (
<Box>
@@ -135,15 +145,19 @@ export function SessionPicker({
function SessionRow({
info,
focused,
}: { info: SessionInfo; focused: boolean }): React.ReactElement {
walletCurrency,
}: {
info: SessionInfo;
focused: boolean;
walletCurrency?: string;
}): React.ReactElement {
const branch = info.meta.branch ?? "main";
const summary =
info.meta.summary ?? `${info.messageCount} message${info.messageCount === 1 ? "" : "s"}`;
const turns = info.meta.turnCount ?? Math.ceil(info.messageCount / 2);
const costCny =
info.meta.totalCostUsd !== undefined
? `¥${(info.meta.totalCostUsd * USD_TO_CNY).toFixed(2)}`
: "";
const currency = walletCurrency ?? info.meta.balanceCurrency;
const costLabel =
info.meta.totalCostUsd !== undefined ? formatCost(info.meta.totalCostUsd, currency, 2) : "";
const time = relativeTime(info.mtime);
return (
<Box>
@@ -156,7 +170,7 @@ function SessionRow({
<Box flexGrow={1} />
<Text color={FG.faint}>{`${time.padStart(11)} `}</Text>
<Text color={FG.faint}>{`${turns} turns`}</Text>
{costCny ? <Text color={FG.faint}>{` · ${costCny}`}</Text> : null}
{costLabel ? <Text color={FG.faint}>{` · ${costLabel}`}</Text> : null}
</Box>
);
}
+6 -4
View File
@@ -1,5 +1,4 @@
import { Box, Text } from "ink";
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React in value scope for JSX compilation
import React, { useState } from "react";
import { DenyContextInput } from "./DenyContextInput.js";
import { SingleSelect } from "./Select.js";
@@ -35,7 +34,7 @@ export function ShellConfirm({ command, allowPrefix, kind, onChoose }: ShellConf
glyph="✗"
title="Deny — provide context"
metaRight="optional"
footerHint="⏎ submit · esc skip (deny without reason)"
footerHint="type context · ⏎ submit with reason · esc skip (deny without reason)"
>
<DenyContextInput
onSubmit={(context) => onChoose("deny", context || undefined)}
@@ -51,7 +50,7 @@ export function ShellConfirm({ command, allowPrefix, kind, onChoose }: ShellConf
glyph={isBackground ? "⏱" : "?"}
title={isBackground ? "Background process" : "Shell command"}
metaRight="awaiting"
footerHint="↑↓ pick · ⏎ confirm · esc cancel"
footerHint="↑↓ pick · ⏎ confirm · Tab add context · esc cancel"
>
<Box marginBottom={1}>
<Text color={FG.faint}>{subtitle}</Text>
@@ -80,13 +79,16 @@ export function ShellConfirm({ command, allowPrefix, kind, onChoose }: ShellConf
{
value: "deny",
label: "deny",
hint: "skip; agent will pick an alternative",
hint: "press Tab to add context telling the model why",
},
]}
onSubmit={(v) => {
if (v === "deny") setPhase("deny");
else onChoose(v as ShellConfirmChoice);
}}
onTab={(v) => {
if (v === "deny") setPhase("deny");
}}
onCancel={() => onChoose("deny")}
/>
</ApprovalCard>
+2
View File
@@ -86,6 +86,7 @@ function SuggestionRow({ spec, isSelected }: { spec: SlashCommandSpec; isSelecte
const key = `slash.${spec.cmd}.description`;
const translated = t(key);
const summary = translated === key ? spec.summary : translated;
const aliasHint = spec.aliases?.length ? ` · /${spec.aliases.join(" /")}` : "";
return (
<Box>
<Text color={isSelected ? COLOR.primary : COLOR.info} bold={isSelected}>
@@ -99,6 +100,7 @@ function SuggestionRow({ spec, isSelected }: { spec: SlashCommandSpec; isSelecte
<Text color={isSelected ? COLOR.user : COLOR.info} dimColor={!isSelected}>
{summary}
</Text>
{aliasHint ? <Text dimColor>{aliasHint}</Text> : null}
</Box>
);
}
+3 -2
View File
@@ -6,6 +6,7 @@ import type { EditMode } from "../../config.js";
import type { SessionSummary } from "../../telemetry/stats.js";
import { Bar, ChromeRule } from "./primitives.js";
import { COLOR, GRADIENT } from "./theme.js";
import { formatBalance, formatCost } from "./theme/tokens.js";
const COLD_START_TURNS = 3;
@@ -91,9 +92,9 @@ function ChromeRow({
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}` : ""}]`
? `[${formatBalance(balance.total, balance.currency, { label: true })}]`
: "";
const costLabel = `[$${summary.totalCostUsd.toFixed(4)}]`;
const costLabel = `[${formatCost(summary.totalCostUsd, balance?.currency)}]`;
const cacheLabel = "[c ▰▰▰▰▰▰ 100%]";
const updateLabel = updateAvailable ? `↑ ${updateAvailable}` : "";
+12
View File
@@ -9,6 +9,8 @@ import { FG, TONE } from "./theme/tokens.js";
export interface WelcomeBannerProps {
/** True when running `reasonix code`. Surfaces code-mode hints. */
inCodeMode?: boolean;
/** Pinned workspace root — only meaningful in code mode. Surfaced so first-time users see they can pass --dir at next launch. */
workspaceRoot?: string;
/** Live URL of the embedded dashboard, or null when it isn't running. */
dashboardUrl?: string | null;
/** Bumped on language change; forces re-render so t() picks up new locale. */
@@ -19,6 +21,7 @@ const HINTS = ["/help", "/init", "/memory", "/cost"] as const;
export function WelcomeBanner({
inCodeMode,
workspaceRoot,
dashboardUrl,
}: WelcomeBannerProps): React.ReactElement {
const tagline = inCodeMode ? t("ui.taglineCode") : t("ui.taglineChat");
@@ -66,6 +69,15 @@ export function WelcomeBanner({
))}
</Box>
{inCodeMode && workspaceRoot ? (
<Box marginTop={1} flexDirection="row" gap={1}>
<Text color={TONE.brand}>{"▸ workspace"}</Text>
<Text color={FG.faint}>{"·"}</Text>
<Text color={FG.body}>{workspaceRoot}</Text>
<Text color={FG.faint}>{" (relaunch with --dir <path> to switch)"}</Text>
</Box>
) : null}
{dashboardUrl ? (
<Box marginTop={1} flexDirection="row" gap={1}>
<Text color={TONE.brand} bold>
+67 -1
View File
@@ -11,6 +11,7 @@
* `--branch`, etc. can be picked here in a few arrow-key presses.
*/
import { mkdirSync, statSync } from "node:fs";
import { Box, Text, useApp, useInput } from "ink";
import TextInput from "ink-text-input";
// biome-ignore lint/style/useImportType: JSX (jsx: "react") needs React as a value at runtime
@@ -287,6 +288,49 @@ function McpArgsStep({
onError: (e: string | null) => void;
}) {
const [value, setValue] = useState("");
const [pendingCreate, setPendingCreate] = useState<string | null>(null);
useInput((input, key) => {
if (!pendingCreate) return;
const ch = input.toLowerCase();
if (ch === "y" || key.return) {
try {
mkdirSync(pendingCreate, { recursive: true });
const created = pendingCreate;
setPendingCreate(null);
setValue("");
onError(null);
onSubmit(created);
} catch (e) {
onError(`Couldn't create ${pendingCreate}: ${(e as Error).message}`);
setPendingCreate(null);
}
} else if (ch === "n" || key.escape) {
setPendingCreate(null);
onError(null);
}
});
if (pendingCreate) {
return (
<StepFrame title={`Configure ${entry.name}`} step={2} total={3}>
<Box flexDirection="column">
<Text>
Directory <Text bold>{pendingCreate}</Text> doesn't exist.
</Text>
<Box marginTop={1}>
<Text dimColor>[Y/Enter] create it (mkdir -p) · [N/Esc] enter a different path</Text>
</Box>
{error ? (
<Box marginTop={1}>
<Text color="red">{error}</Text>
</Box>
) : null}
</Box>
</StepFrame>
);
}
return (
<StepFrame title={`Configure ${entry.name}`} step={2} total={3}>
<Box flexDirection="column">
@@ -314,6 +358,17 @@ function McpArgsStep({
onError(`${entry.name} needs a value — got an empty string.`);
return;
}
if (entry.name === "filesystem") {
const check = checkFilesystemPath(trimmed);
if (check.kind === "missing") {
setPendingCreate(trimmed);
return;
}
if (check.kind === "not-a-dir") {
onError(`${trimmed} exists but is not a directory.`);
return;
}
}
onSubmit(trimmed);
setValue("");
}}
@@ -330,6 +385,14 @@ function McpArgsStep({
);
}
function checkFilesystemPath(p: string): { kind: "ok" | "missing" | "not-a-dir" } {
try {
return { kind: statSync(p).isDirectory() ? "ok" : "not-a-dir" };
} catch {
return { kind: "missing" };
}
}
function ReviewConfirm({ onConfirm }: { onConfirm: () => void }) {
useInput((_i, key) => {
if (key.return) onConfirm();
@@ -443,5 +506,8 @@ export function buildSpec(name: string, argsByName: Record<string, string>): str
}
function quoteIfNeeded(s: string): string {
return /\s|"/.test(s) ? `"${s.replace(/"/g, '\\"')}"` : s;
// Escape backslashes BEFORE quotes — otherwise a trailing `\` in the
// input would consume the closing quote when a downstream parser
// un-escapes the output (CodeQL js/incomplete-sanitization).
return /\s|"/.test(s) ? `"${s.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"` : s;
}
-39
View File
@@ -1,39 +0,0 @@
/** 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;
}, []);
}
+7 -5
View File
@@ -1,5 +1,4 @@
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 { Card } from "../state/cards.js";
import { FG } from "../theme/tokens.js";
@@ -21,11 +20,14 @@ import { UsageCard } from "./UsageCard.js";
import { UserCard } from "./UserCard.js";
import { WarnCard } from "./WarnCard.js";
export function CardRenderer({ card }: { card: Card }): React.ReactElement {
// No marginTop here — Card primitive owns inter-card spacing. Doubling it
// bakes 2 blank rows into every static-emitted block of bytes.
// Memoized so the cards array re-rendering (every store update) only
// reconciles cards whose object identity actually changed — the reducer
// keeps prior cards reference-stable, so unchanged history skips work.
export const CardRenderer = React.memo(function CardRenderer({
card,
}: { card: Card }): React.ReactElement {
return <Box flexDirection="column">{renderCard(card)}</Box>;
}
});
function renderCard(card: Card): React.ReactElement {
switch (card.kind) {
+72 -5
View File
@@ -1,7 +1,9 @@
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 React, { useContext } from "react";
import { clipToCells, wrapToCells } from "../../../frame/width.js";
import { countTokens } from "../../../tokenizer.js";
import { LiveExpandContext } from "../layout/LiveExpandContext.js";
import { useReserveRows } from "../layout/viewport-budget.js";
import { Markdown } from "../markdown.js";
import { Card } from "../primitives/Card.js";
@@ -10,17 +12,49 @@ import { PILL_MODEL, Pill, modelBadgeFor } from "../primitives/Pill.js";
import { Spinner } from "../primitives/Spinner.js";
import type { StreamingCard as StreamingCardData } from "../state/cards.js";
import { FG, TONE, TONE_ACTIVE } from "../theme/tokens.js";
import { useSlowTick } from "../ticker.js";
/** Streaming preview tail length — bounded live region so chunks don't thrash whole-card layout. */
const STREAMING_PREVIEW_LINES = 4;
/** Expanded mode shows up to this many lines so the card can't swallow the whole viewport. */
const EXPANDED_MAX_LINES = 60;
const MIN_ELAPSED_MS_FOR_RATE = 500;
const MIN_TOKENS_FOR_RATE = 4;
function formatTokenCount(n: number): string {
if (n >= 10000) return `${(n / 1000).toFixed(1)}k`;
if (n >= 1000) return `${(n / 1000).toFixed(2)}k`;
return String(n);
}
function tokenRate(
text: string,
startTs: number,
endTs: number,
): { tokens: number; tps: number | null } {
const tokens = countTokens(text);
const elapsedMs = endTs - startTs;
if (elapsedMs < MIN_ELAPSED_MS_FOR_RATE || tokens < MIN_TOKENS_FOR_RATE) {
return { tokens, tps: null };
}
return { tokens, tps: Math.round((tokens * 1000) / elapsedMs) };
}
const PILL_RATE = { bg: "#11141a", fg: "#8b949e" } as const;
export function StreamingCard({ card }: { card: StreamingCardData }): React.ReactElement {
const { stdout } = useStdout();
const cols = stdout?.columns ?? 80;
const expanded = useContext(LiveExpandContext);
const reserveCap = expanded ? EXPANDED_MAX_LINES + 2 : STREAMING_PREVIEW_LINES + 2;
useReserveRows("stream", {
min: STREAMING_PREVIEW_LINES + 1,
max: STREAMING_PREVIEW_LINES + 2,
max: reserveCap,
});
// Re-render at 1Hz so the rate keeps updating even when chunks stall.
// Frozen once `card.done` is true — settled cards render via Static.
useSlowTick();
const modelBadge = card.model ? modelBadgeFor(card.model) : null;
const modelPill = modelBadge ? (
@@ -28,9 +62,24 @@ export function StreamingCard({ card }: { card: StreamingCardData }): React.Reac
) : null;
if (card.done && !card.aborted) {
const { tokens, tps } = tokenRate(card.text, card.ts, card.endedAt ?? Date.now());
const ratePill =
tokens >= MIN_TOKENS_FOR_RATE && tps !== null ? (
<Pill label={`${formatTokenCount(tokens)} tok · ${tps} t/s`} {...PILL_RATE} bold={false} />
) : null;
return (
<Card tone={TONE.ok}>
<CardHeader glyph="‹" tone={TONE.ok} title="reply" right={modelPill} />
<CardHeader
glyph="‹"
tone={TONE.ok}
title="reply"
right={
<>
{ratePill}
{modelPill}
</>
}
/>
<Markdown text={card.text} />
</Card>
);
@@ -39,12 +88,23 @@ export function StreamingCard({ card }: { card: StreamingCardData }): React.Reac
const lineCells = Math.max(20, cols - 4);
const allLines = card.text.length > 0 ? card.text.split("\n") : [""];
const visualLines = allLines.flatMap((l) => wrapToCells(l, lineCells));
const visible = visualLines.slice(-STREAMING_PREVIEW_LINES);
const cap = expanded ? EXPANDED_MAX_LINES : STREAMING_PREVIEW_LINES;
const visible = visualLines.slice(-cap);
const droppedAbove = Math.max(0, visualLines.length - visible.length);
const aborted = !!card.aborted;
const headColor = aborted ? TONE.err : TONE_ACTIVE.brand;
const glyph = aborted ? "‹" : "◈";
const headLabel = aborted ? "aborted" : "writing…";
const { tokens: liveTokens, tps: liveTps } = tokenRate(card.text, card.ts, Date.now());
const liveRatePill =
!aborted && liveTokens >= MIN_TOKENS_FOR_RATE && liveTps !== null ? (
<Pill label={`${liveTps} t/s`} {...PILL_RATE} bold={false} />
) : null;
const expandPill = !aborted ? (
<Pill label={expanded ? "expanded ⌃o" : "preview ⌃o"} {...PILL_RATE} bold={false} />
) : null;
return (
<Card tone={headColor}>
<CardHeader
@@ -53,13 +113,20 @@ export function StreamingCard({ card }: { card: StreamingCardData }): React.Reac
title={headLabel}
right={
<>
{liveRatePill}
{expandPill}
{aborted ? null : <Spinner kind="braille" color={TONE_ACTIVE.brand} />}
{modelPill}
</>
}
/>
{expanded && droppedAbove > 0 ? (
<Text
color={FG.faint}
>{`⋯ ${droppedAbove} earlier line${droppedAbove === 1 ? "" : "s"} above`}</Text>
) : null}
{visible.map((line, i) => (
<Box key={`${card.id}:${allLines.length - visible.length + i}`} flexDirection="row">
<Box key={`${card.id}:${visualLines.length - visible.length + i}`} flexDirection="row">
<Text color={aborted ? FG.meta : FG.body}>{clipToCells(line, lineCells)}</Text>
</Box>
))}
+10 -6
View File
@@ -4,7 +4,7 @@ import React from "react";
import { Card } from "../primitives/Card.js";
import { CardHeader } from "../primitives/CardHeader.js";
import type { UsageCard as UsageCardData } from "../state/cards.js";
import { FG, TONE, formatCNY } from "../theme/tokens.js";
import { FG, TONE, formatBalance, formatCost } from "../theme/tokens.js";
const BAR_CELLS = 30;
@@ -32,7 +32,7 @@ export function UsageCard({ card }: { card: UsageCardData }): React.ReactElement
const reasonRatio = card.tokens.reason / cap;
const outputRatio = card.tokens.output / cap;
const headerMeta: string[] = [`turn ${card.turn}`, formatCNY(card.cost)];
const headerMeta: string[] = [`turn ${card.turn}`, formatCost(card.cost, card.balanceCurrency)];
if (card.elapsedMs !== undefined) headerMeta.push(`${(card.elapsedMs / 1000).toFixed(1)}s`);
return (
<Card tone={FG.meta}>
@@ -66,11 +66,15 @@ export function UsageCard({ card }: { card: UsageCardData }): React.ReactElement
</Box>
<Box flexDirection="row" gap={1}>
<Text color={FG.faint}>session</Text>
<Text bold color={FG.body}>{`⛁ ${formatCNY(card.sessionCost, 3)}`}</Text>
<Text bold color={FG.body}>
{`⛁ ${formatCost(card.sessionCost, card.balanceCurrency, 3)}`}
</Text>
{card.balance !== undefined ? (
<>
<Text color={FG.faint}>· balance</Text>
<Text bold color={TONE.brand}>{`¥${card.balance.toFixed(2)}`}</Text>
<Text bold color={TONE.brand}>
{formatBalance(card.balance, card.balanceCurrency)}
</Text>
</>
) : null}
</Box>
@@ -89,9 +93,9 @@ function CompactUsageRow({ card }: { card: UsageCardData }): React.ReactElement
</Text>
<Text color={FG.faint}>· cache</Text>
<Text color={TONE.ok}>{`${(card.cacheHit * 100).toFixed(0)}%`}</Text>
<Text color={FG.faint}>{`· ${formatCNY(card.cost)}${elapsed}`}</Text>
<Text color={FG.faint}>{`· ${formatCost(card.cost, card.balanceCurrency)}${elapsed}`}</Text>
{card.balance !== undefined ? (
<Text color={TONE.brand}>{`· ¥${card.balance.toFixed(2)}`}</Text>
<Text color={TONE.brand}>{`· ${formatBalance(card.balance, card.balanceCurrency)}`}</Text>
) : null}
</Box>
);
+6 -2
View File
@@ -1,6 +1,6 @@
/** OSC 52 clipboard write + temp-file fallback. */
import { writeFileSync } from "node:fs";
import { mkdtempSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
@@ -13,7 +13,11 @@ export interface ClipboardWrite {
}
export function writeClipboard(text: string): ClipboardWrite {
const filePath = join(tmpdir(), `reasonix-clip-${Date.now()}.txt`);
// mkdtemp creates a private 0700 directory atomically — keeps the
// file out of the shared tmp namespace where a sibling process can
// race or read it (CodeQL js/insecure-temporary-file).
const dir = mkdtempSync(join(tmpdir(), "reasonix-clip-"));
const filePath = join(dir, "clip.txt");
let osc52 = false;
if (text.length <= OSC_52_LIMIT) {
const b64 = Buffer.from(text, "utf8").toString("base64");
+1 -1
View File
@@ -145,7 +145,7 @@ export function CtxBreakdownBlock({ data }: { data: CtxBreakdownData }): React.R
</Box>
) : null}
<Box marginTop={1}>
<Text dimColor>{" /compact shrinks oversized tool results · /new wipes log"}</Text>
<Text dimColor>{" /compact folds (auto at 50%) · /new wipes log"}</Text>
</Box>
</Box>
);
+39
View File
@@ -0,0 +1,39 @@
/** stdin-queue drain on exit — eats stuck terminal-feature-detection responses (#365). */
import process from "node:process";
/** Eats stuck OSC/CPR/DA replies on exit so fish/bash don't print them as input (#365). */
export async function drainTtyResponses(timeoutMs = 50): Promise<void> {
const stdin = process.stdin;
if (!stdin.isTTY && typeof (stdin as { setRawMode?: unknown }).setRawMode !== "function") {
return;
}
let raised = false;
try {
stdin.setRawMode(true);
raised = true;
} catch {
return;
}
stdin.resume();
await new Promise<void>((resolve) => {
const onData = (_chunk: Buffer | string): void => {
// Discard — anything pending here is a terminal-feature reply.
};
stdin.on("data", onData);
const timer = setTimeout(() => {
stdin.off("data", onData);
stdin.pause();
if (raised) {
try {
stdin.setRawMode(false);
} catch {
/* stdin may already be closed; ignore */
}
}
resolve();
}, timeoutMs);
timer.unref();
});
}
+23 -13
View File
@@ -1,6 +1,6 @@
/** `#` writes project memory, `#g` global; `##+` stays a markdown heading; `\#` escapes and submits the literal `#`. */
import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { closeSync, fstatSync, mkdirSync, openSync, readSync, writeSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join } from "node:path";
import { PROJECT_MEMORY_FILE } from "../../memory/project.js";
@@ -79,18 +79,28 @@ function appendBulletToFile(path: string, note: string, newFileHeader: string):
const trimmed = note.trim();
if (!trimmed) throw new Error("note body cannot be empty");
const bullet = `- ${trimmed}\n`;
if (!existsSync(path)) {
mkdirSync(dirname(path), { recursive: true });
writeFileSync(path, `${newFileHeader}${bullet}`, "utf8");
return { path, created: true };
}
let prefix = "";
mkdirSync(dirname(path), { recursive: true });
// One `a+` open covers both branches: O_APPEND lands every write
// atomically at end-of-file (concurrent appenders interleave whole
// bullets), O_CREAT creates the file when it's missing, and we use
// `fstat().size === 0` as the "we just created it" signal to decide
// whether to emit the file header. Single fd from open through
// write — no path-based check between (CodeQL js/file-system-race).
const fd = openSync(path, "a+");
try {
const existing = readFileSync(path, "utf8");
if (existing.length > 0 && !existing.endsWith("\n")) prefix = "\n";
} catch {
// Unreadable but exists — let appendFileSync surface the real error.
const stat = fstatSync(fd);
if (stat.size === 0) {
writeSync(fd, `${newFileHeader}${bullet}`);
return { path, created: true };
}
// Existing file — peek the trailing byte to decide whether to
// insert a leading newline. Same fd → no separate stat→read race.
const tail = Buffer.alloc(1);
readSync(fd, tail, 0, 1, stat.size - 1);
const prefix = tail[0] !== 0x0a ? "\n" : "";
writeSync(fd, `${prefix}${bullet}`);
return { path, created: false };
} finally {
closeSync(fd);
}
appendFileSync(path, `${prefix}${bullet}`, "utf8");
return { path, created: false };
}
+6 -15
View File
@@ -6,13 +6,6 @@ import type { Scrollback } from "./useScrollback.js";
export type SlashOutcome = { kind: "consumed" } | { kind: "resubmit"; text: string };
interface ActiveLoopShape {
prompt: string;
intervalMs: number;
nextFireAt: number;
iter: number;
}
export interface ApplySlashResultContext {
log: Scrollback;
stdoutWrite: (chunk: string) => void;
@@ -20,10 +13,10 @@ export interface ApplySlashResultContext {
syncPendingCount: () => void;
session: string | null;
codeModeOn: boolean;
activeLoopRef: MutableRefObject<ActiveLoopShape | null>;
isLoopActive: () => boolean;
stopLoop: () => void;
quitProcess: () => void;
promptHistory: MutableRefObject<string[]>;
pushHistory: (text: string) => void;
/** The verbatim text the user typed; used for promptHistory bookkeeping. */
text: string;
}
@@ -34,14 +27,12 @@ export function applySlashResult(result: SlashResult, ctx: ApplySlashResultConte
// the process is exiting. Use quitProcess (process.exit) rather than
// Ink's exit(): the singleton stdin reader keeps a `data` listener
// attached, so exit() unmounts React but leaves the event loop alive.
if (ctx.activeLoopRef.current) ctx.stopLoop();
if (ctx.isLoopActive()) ctx.stopLoop();
ctx.quitProcess();
return { kind: "consumed" };
}
if (result.clear) {
// 2J + 3J + H: nuke viewport AND scrollback (visible buffer + the
// off-screen lines). Then reset state.cards so React doesn't
// immediately repaint everything that was just wiped.
// 2J + 3J + H: visible buffer + scrollback + cursor home.
ctx.stdoutWrite("\x1b[2J\x1b[3J\x1b[H");
ctx.log.reset();
if (result.info) ctx.log.pushInfo(result.info);
@@ -50,7 +41,7 @@ export function applySlashResult(result: SlashResult, ctx: ApplySlashResultConte
clearPendingEdits(ctx.session);
ctx.syncPendingCount();
}
if (ctx.activeLoopRef.current) ctx.stopLoop();
if (ctx.isLoopActive()) ctx.stopLoop();
return { kind: "consumed" };
}
if (result.info) {
@@ -77,6 +68,6 @@ export function applySlashResult(result: SlashResult, ctx: ApplySlashResultConte
if (result.resubmit) {
return { kind: "resubmit", text: result.resubmit };
}
ctx.promptHistory.current.push(ctx.text);
ctx.pushHistory(ctx.text);
return { kind: "consumed" };
}
+1 -117
View File
@@ -16,7 +16,7 @@ export interface ToolEventContext {
toolStartedAtRef: MutableRefObject<number | null>;
toolHistoryRef: MutableRefObject<Array<{ toolName: string; text: string }>>;
setPendingShell: Dispatch<
SetStateAction<{ command: string; kind: "run_command" | "run_background" } | null>
SetStateAction<{ id: number; command: string; kind: "run_command" | "run_background" } | null>
>;
setPendingPlan: Dispatch<SetStateAction<string | null>>;
setPendingRevision: Dispatch<
@@ -52,122 +52,6 @@ export function handleToolEvent(ev: LoopEvent, ctx: ToolEventContext): void {
});
}
if (
ctx.codeModeOn &&
(ev.toolName === "run_command" || ev.toolName === "run_background") &&
ev.content.includes('"NeedsConfirmationError:') &&
ev.toolArgs
) {
try {
const parsed = JSON.parse(ev.toolArgs) as { command?: unknown };
if (typeof parsed.command === "string" && parsed.command.trim()) {
ctx.setPendingShell({
command: parsed.command.trim(),
kind: ev.toolName as "run_command" | "run_background",
});
}
} catch {
/* malformed args — skip the prompt */
}
}
if (
ctx.codeModeOn &&
ev.toolName === "submit_plan" &&
ev.content.includes('"PlanProposedError:')
) {
try {
const parsed = JSON.parse(ev.content) as {
plan?: unknown;
steps?: unknown;
summary?: unknown;
};
if (typeof parsed.plan === "string" && parsed.plan.trim()) {
const planText = parsed.plan.trim();
ctx.setPendingPlan(planText);
const steps = Array.isArray(parsed.steps) ? (parsed.steps as PlanStep[]) : null;
ctx.planStepsRef.current = steps;
ctx.completedStepIdsRef.current = new Set();
ctx.planBodyRef.current = planText;
ctx.planSummaryRef.current =
typeof parsed.summary === "string" && parsed.summary.trim()
? parsed.summary.trim()
: null;
ctx.persistPlanState();
const summary =
typeof parsed.summary === "string" && parsed.summary.trim() ? parsed.summary.trim() : "";
const title = summary ? `Plan · ${summary}` : "Plan submitted";
ctx.log.showPlan({
title,
steps: (steps ?? []).map((s) => ({ id: s.id, title: s.title, status: "queued" })),
variant: "active",
});
}
} catch {
/* malformed payload — skip the picker */
}
}
if (ev.toolName === "revise_plan" && ev.content.includes('"PlanRevisionProposedError:')) {
try {
const parsed = JSON.parse(ev.content) as {
reason?: unknown;
remainingSteps?: unknown;
summary?: unknown;
};
const reason = typeof parsed.reason === "string" ? parsed.reason.trim() : "";
const remainingSteps = Array.isArray(parsed.remainingSteps)
? (parsed.remainingSteps as PlanStep[]).filter(
(s) =>
s &&
typeof s.id === "string" &&
s.id.trim() &&
typeof s.title === "string" &&
s.title.trim() &&
typeof s.action === "string" &&
s.action.trim(),
)
: [];
if (reason && remainingSteps.length > 0) {
const summary =
typeof parsed.summary === "string" ? parsed.summary.trim() || undefined : undefined;
ctx.setPendingRevision({ reason, remainingSteps, summary });
}
} catch {
/* malformed payload — skip the picker */
}
}
if (ev.toolName === "ask_choice" && ev.content.includes('"ChoiceRequestedError:')) {
try {
const parsed = JSON.parse(ev.content) as {
question?: unknown;
options?: unknown;
allowCustom?: unknown;
};
const question = typeof parsed.question === "string" ? parsed.question.trim() : "";
const options = Array.isArray(parsed.options)
? (parsed.options as ChoiceOption[]).filter(
(o) =>
o &&
typeof o.id === "string" &&
o.id.trim() &&
typeof o.title === "string" &&
o.title.trim(),
)
: [];
if (question && options.length >= 2) {
ctx.setPendingChoice({
question,
options,
allowCustom: parsed.allowCustom === true,
});
}
} catch {
/* malformed payload — skip the picker */
}
}
if (ev.toolName === "mark_step_complete") {
try {
const parsed = JSON.parse(ev.content) as Partial<StepCompletion>;
+51
View File
@@ -0,0 +1,51 @@
import { useCallback, useEffect, useState } from "react";
/** Rows advanced per PgUp / PgDn / arrow / wheel — small for smooth feel. */
export const SCROLL_PAGE_ROWS = 3;
export interface ChatScrollState {
/** How many rows of content are above the visible viewport. */
scrollRows: number;
/** True when the user is following the bottom (auto-advances on new content). */
pinned: boolean;
scrollUp: () => void;
scrollDown: () => void;
/** Jump straight to the latest content and resume auto-follow (End key). */
jumpToBottom: () => void;
/** CardStream calls this once it has measured inner/outer Box heights. */
setMaxScroll: (rows: number) => void;
}
/** Row-precision scroll state. CardStream reports maxScroll back via setMaxScroll once Ink has laid out the inner column. */
export function useChatScroll(): ChatScrollState {
const [scrollRows, setScrollRows] = useState(0);
const [pinned, setPinned] = useState(true);
const [maxScroll, setMaxScrollState] = useState(0);
useEffect(() => {
if (pinned) setScrollRows(maxScroll);
}, [pinned, maxScroll]);
useEffect(() => {
if (scrollRows > maxScroll) setScrollRows(maxScroll);
}, [scrollRows, maxScroll]);
const scrollUp = useCallback(() => {
setPinned(false);
setScrollRows((o) => Math.max(0, o - SCROLL_PAGE_ROWS));
}, []);
const scrollDown = useCallback(() => {
setScrollRows((o) => {
const next = Math.min(maxScroll, o + SCROLL_PAGE_ROWS);
if (next >= maxScroll) setPinned(true);
return next;
});
}, [maxScroll]);
const jumpToBottom = useCallback(() => setPinned(true), []);
const setMaxScroll = useCallback((rows: number) => setMaxScrollState(rows), []);
return { scrollRows, pinned, scrollUp, scrollDown, jumpToBottom, setMaxScroll };
}
+93
View File
@@ -0,0 +1,93 @@
import { type MutableRefObject, useCallback } from "react";
import {
type ApplyResult,
type EditBlock,
type EditSnapshot,
applyEditBlocks,
snapshotBeforeEdits,
} from "../../../code/edit-blocks.js";
import { clearPendingEdits, savePendingEdits } from "../../../code/pending-edits.js";
import { formatEditResults, partitionEdits } from "../edit-history.js";
export interface UseCodeModeResult {
/** /apply callback. Empty `indices` means "all"; specific 1-based indices apply only those. */
codeApply: (indices?: readonly number[]) => string;
/** /discard callback. Same indices semantics as codeApply. */
codeDiscard: (indices?: readonly number[]) => string;
}
export interface UseCodeModeOptions {
codeMode: boolean;
pendingEdits: MutableRefObject<EditBlock[]>;
currentRootDir: string;
session: string | null;
syncPendingCount: () => void;
recordEdit: (
source: string,
blocks: readonly EditBlock[],
results: readonly ApplyResult[],
snaps: readonly EditSnapshot[],
) => void;
}
/** Slash-command callbacks for `/apply` and `/discard` over the pending-edits queue. Owns the partition / snapshot / save / sync sequence; AppInner just forwards the strings to its log. */
export function useCodeMode(opts: UseCodeModeOptions): UseCodeModeResult {
const { codeMode, pendingEdits, currentRootDir, session, syncPendingCount, recordEdit } = opts;
const codeApply = useCallback(
(indices?: readonly number[]): string => {
if (!codeMode) return "not in code mode";
const blocks = pendingEdits.current;
if (blocks.length === 0) {
return "nothing pending — the model hasn't proposed edits since the last /apply or /discard.";
}
const useSubset = indices !== undefined && indices.length > 0;
const { selected, remaining } = useSubset
? partitionEdits(blocks, indices)
: { selected: blocks, remaining: [] as EditBlock[] };
if (selected.length === 0) {
return "▸ no edits matched those indices — nothing applied. Use /apply with no args to commit them all.";
}
const snaps = snapshotBeforeEdits(selected, currentRootDir);
const results = applyEditBlocks(selected, currentRootDir);
const anyApplied = results.some((r) => r.status === "applied" || r.status === "created");
if (anyApplied) recordEdit("review-apply", selected, results, snaps);
pendingEdits.current = remaining;
if (remaining.length === 0) clearPendingEdits(session ?? null);
else savePendingEdits(session ?? null, remaining);
syncPendingCount();
const tail =
remaining.length > 0
? `\n▸ ${remaining.length} edit block(s) still pending — /apply or /discard to clear them.`
: "";
return formatEditResults(results) + tail;
},
[codeMode, currentRootDir, session, syncPendingCount, recordEdit, pendingEdits],
);
const codeDiscard = useCallback(
(indices?: readonly number[]): string => {
const blocks = pendingEdits.current;
if (blocks.length === 0) return "nothing pending to discard.";
const useSubset = indices !== undefined && indices.length > 0;
const { selected, remaining } = useSubset
? partitionEdits(blocks, indices)
: { selected: blocks, remaining: [] as EditBlock[] };
if (selected.length === 0) {
return "▸ no edits matched those indices — nothing discarded.";
}
pendingEdits.current = remaining;
if (remaining.length === 0) clearPendingEdits(session ?? null);
else savePendingEdits(session ?? null, remaining);
syncPendingCount();
const tail =
remaining.length > 0
? ` (${remaining.length} block(s) still pending)`
: ". Nothing was written to disk.";
return `▸ discarded ${selected.length} pending edit block(s)${tail}`;
},
[session, syncPendingCount, pendingEdits],
);
return { codeApply, codeDiscard };
}
+41
View File
@@ -0,0 +1,41 @@
import { useCallback, useRef } from "react";
export interface UseInputRecallResult {
recallPrev: () => void;
recallNext: () => void;
pushHistory: (text: string) => void;
/** Reset cursor to the "fresh input" position — call after a successful submit. */
resetCursor: () => void;
}
/** Bash-style ↑/↓ recall over a turn-local prompt history. Cursor is `useRef` so toggles don't re-render. */
export function useInputRecall(setInput: (s: string) => void): UseInputRecallResult {
const promptHistory = useRef<string[]>([]);
const historyCursor = useRef<number>(-1);
const recallPrev = useCallback(() => {
const hist = promptHistory.current;
if (hist.length === 0) return;
const nextCursor = Math.min(historyCursor.current + 1, hist.length - 1);
historyCursor.current = nextCursor;
setInput(hist[hist.length - 1 - nextCursor] ?? "");
}, [setInput]);
const recallNext = useCallback(() => {
if (historyCursor.current < 0) return;
const hist = promptHistory.current;
const nextCursor = historyCursor.current - 1;
historyCursor.current = nextCursor;
setInput(nextCursor < 0 ? "" : (hist[hist.length - 1 - nextCursor] ?? ""));
}, [setInput]);
const pushHistory = useCallback((text: string) => {
promptHistory.current.push(text);
}, []);
const resetCursor = useCallback(() => {
historyCursor.current = -1;
}, []);
return { recallPrev, recallNext, pushHistory, resetCursor };
}
+143
View File
@@ -0,0 +1,143 @@
import { type MutableRefObject, useCallback, useEffect, useRef, useState } from "react";
import type { Scrollback } from "./useScrollback.js";
interface ActiveLoop {
prompt: string;
intervalMs: number;
nextFireAt: number;
iter: number;
}
export interface ActiveLoopSnapshot {
prompt: string;
intervalMs: number;
iter: number;
nextFireMs: number;
}
export interface UseLoopModeResult {
startLoop: (intervalMs: number, prompt: string) => void;
stopLoop: () => void;
/** Snapshot for the `/loop` (no-arg) status branch. Returns null when no loop is active. */
getLoopStatus: () => ActiveLoopSnapshot | null;
/** Cheap predicate — used by handleSubmit's cancel-on-user-input guard and by apply-slash-result. */
isLoopActive: () => boolean;
/** True only during the timer's `handleSubmit` invocation — tells handleSubmit's cancel guard to skip itself so the loop's own re-submit doesn't kill the loop. */
isLoopFiring: () => boolean;
/** Reset by handleSubmit at the top of every call so the firing flag is one-shot. */
clearFiringFlag: () => void;
/** Reactive state for the LoopStatusRow render — null when no loop is active. */
activeLoop: ActiveLoop | null;
}
export interface UseLoopModeOptions {
log: Scrollback;
busyRef: MutableRefObject<boolean>;
/** Forward-ref to the latest `handleSubmit` — the closure shifts as state changes, so the timer dereferences fresh on each fire. */
handleSubmitRef: MutableRefObject<((raw: string) => Promise<void>) | null>;
}
/** Owns the active /loop config + its setTimeout-based scheduler. Re-issuing /loop replaces the slot; cancellation is centralized in stopLoop. */
export function useLoopMode(opts: UseLoopModeOptions): UseLoopModeResult {
const { log, busyRef, handleSubmitRef } = opts;
const [activeLoop, setActiveLoop] = useState<ActiveLoop | null>(null);
const activeLoopRef = useRef<ActiveLoop | null>(null);
const loopTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const loopFiringRef = useRef<boolean>(false);
useEffect(() => {
activeLoopRef.current = activeLoop;
}, [activeLoop]);
const stopLoop = useCallback(() => {
if (loopTimerRef.current) {
clearTimeout(loopTimerRef.current);
loopTimerRef.current = null;
}
const cur = activeLoopRef.current;
if (!cur) return;
setActiveLoop(null);
log.pushInfo(`▸ loop stopped (after ${cur.iter} iter${cur.iter === 1 ? "" : "s"}).`);
}, [log]);
const startLoop = useCallback((intervalMs: number, prompt: string) => {
if (loopTimerRef.current) {
clearTimeout(loopTimerRef.current);
loopTimerRef.current = null;
}
setActiveLoop({
prompt,
intervalMs,
nextFireAt: Date.now() + intervalMs,
iter: 0,
});
}, []);
const getLoopStatus = useCallback((): ActiveLoopSnapshot | null => {
const cur = activeLoopRef.current;
if (!cur) return null;
return {
prompt: cur.prompt,
intervalMs: cur.intervalMs,
iter: cur.iter,
nextFireMs: Math.max(0, cur.nextFireAt - Date.now()),
};
}, []);
const isLoopActive = useCallback(() => activeLoopRef.current !== null, []);
const isLoopFiring = useCallback(() => loopFiringRef.current, []);
const clearFiringFlag = useCallback(() => {
loopFiringRef.current = false;
}, []);
// /loop scheduler. Re-runs whenever activeLoop's `nextFireAt` shifts —
// either because startLoop set a fresh schedule or because a previous
// firing bumped the next-fire time. Cleanup clears the in-flight
// timer so a stopLoop / replacement doesn't leak a fire after cancel.
useEffect(() => {
if (!activeLoop) return;
const delay = Math.max(0, activeLoop.nextFireAt - Date.now());
const timer = setTimeout(async () => {
loopTimerRef.current = null;
// Skip the firing entirely when a prior turn is still running.
// Re-arm in 1s so the loop catches up the moment busy clears,
// rather than waiting a full interval after a slow turn.
if (busyRef.current) {
setActiveLoop((cur) => (cur ? { ...cur, nextFireAt: Date.now() + 1000 } : cur));
return;
}
const cur = activeLoopRef.current;
if (!cur) return;
const nextIter = cur.iter + 1;
// Schedule the NEXT firing now (independent of how long this turn
// takes). Keeps the cadence honest even when individual turns run
// long.
setActiveLoop((c) =>
c ? { ...c, iter: nextIter, nextFireAt: Date.now() + cur.intervalMs } : c,
);
log.pushInfo(`▸ /loop iter ${nextIter} → ${cur.prompt}`);
loopFiringRef.current = true;
try {
await handleSubmitRef.current?.(cur.prompt);
} catch {
// Persistent submission errors → kill the loop rather than spam
// the screen. User can re-issue /loop once they fix the cause.
stopLoop();
} finally {
loopFiringRef.current = false;
}
}, delay);
loopTimerRef.current = timer;
return () => clearTimeout(timer);
}, [activeLoop, stopLoop, log, busyRef, handleSubmitRef]);
return {
startLoop,
stopLoop,
getLoopStatus,
isLoopActive,
isLoopFiring,
clearFiringFlag,
activeLoop,
};
}
+19
View File
@@ -0,0 +1,19 @@
import type { WriteStream } from "node:fs";
import { type MutableRefObject, useCallback, useEffect } from "react";
/** Ctrl+C / SIGINT → flush transcript + `process.exit(0)`. We call `process.exit` directly rather than Ink's `exit()` because the singleton stdin reader keeps a `data` listener attached — `exit()` would unmount the React tree but leave the event loop alive and the terminal would hang. */
export function useQuit(transcriptRef: MutableRefObject<WriteStream | null>): () => void {
const quitProcess = useCallback(() => {
transcriptRef.current?.end();
process.exit(0);
}, [transcriptRef]);
useEffect(() => {
process.on("SIGINT", quitProcess);
return () => {
process.off("SIGINT", quitProcess);
};
}, [quitProcess]);
return quitProcess;
}
+2
View File
@@ -38,6 +38,7 @@ export interface Scrollback {
cost: number;
sessionCost: number;
balance?: number;
balanceCurrency?: string;
elapsedMs?: number;
}): string;
showPlan(args: {
@@ -219,6 +220,7 @@ export function useScrollback(): Scrollback {
cost: args.cost,
sessionCost: args.sessionCost,
balance: args.balance,
balanceCurrency: args.balanceCurrency,
elapsedMs: args.elapsedMs,
});
return id;
+20
View File
@@ -0,0 +1,20 @@
import type { WriteStream } from "node:fs";
import { type MutableRefObject, useCallback } from "react";
import type { LoopEvent } from "../../../loop.js";
import { recordFromLoopEvent, writeRecord } from "../../../transcript/log.js";
/** Returns a `LoopEvent` writer that no-ops when no transcript was opened. Wraps `recordFromLoopEvent` + `writeRecord` so callers don't carry the model/prefix metadata. */
export function useTranscriptWriter(
transcriptRef: MutableRefObject<WriteStream | null>,
model: string,
prefixHash: string,
): (ev: LoopEvent) => void {
return useCallback(
(ev: LoopEvent) => {
const stream = transcriptRef.current;
if (!stream) return;
writeRecord(stream, recordFromLoopEvent(ev, { model, prefixHash }));
},
[transcriptRef, model, prefixHash],
);
}
+6
View File
@@ -27,7 +27,13 @@ const CSI_TAIL_TO_FLAGS: ReadonlyArray<{ tail: string; flags: CsiKeyFlags }> = [
// Forward-delete (the key labelled Delete on most keyboards).
{ tail: "[3~", flags: { delete: true } },
// Shift+Tab — terminal sends `\x1b[Z` rather than tab-with-shift.
// `[1;2Z` is the modifier-encoded variant some Windows PowerShell
// hosts emit; `[27;2;9~` and `[9;2u` cover modifyOtherKeys / Kitty
// forms. Issue #373.
{ tail: "[Z", flags: { shift: true, tab: true } },
{ tail: "[1;2Z", flags: { shift: true, tab: true } },
{ tail: "[27;2;9~", flags: { shift: true, tab: true } },
{ tail: "[9;2u", flags: { shift: true, tab: true } },
];
function alreadyStructured(flags: CsiKeyFlags): boolean {
+59 -32
View File
@@ -1,13 +1,62 @@
import { Static } from "ink";
import { Box, type DOMElement, Text, useBoxMetrics } from "ink";
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React in value scope for JSX compilation
import React from "react";
import React, { useEffect, useRef } from "react";
import { CardRenderer } from "../cards/CardRenderer.js";
import { ActiveCardContext } from "../primitives/Card.js";
import type { Card } from "../state/cards.js";
import { useAgentState } from "../state/provider.js";
import { FG } from "../theme/tokens.js";
/** Settled = no future event can mutate it; safe to commit via Ink's Static. */
function isSettled(card: Card): boolean {
/**
* Row-precision virtual scroll: outer Box clips with overflow="hidden",
* inner Box holds all cards and slides up via negative marginTop. Yoga
* computes inner height from card layout; useBoxMetrics reports it back
* so App can clamp scroll bounds. New cards arriving while the user is
* scrolled up sit below the visible window — bytes outside outer bounds
* aren't written, so terminal text selection survives streaming activity.
*/
export function CardStream({
scrollRows,
onMaxScrollChange,
suppressLive = false,
}: {
scrollRows: number;
onMaxScrollChange: (rows: number) => void;
suppressLive?: boolean;
}): React.ReactElement {
const cards = useAgentState((s) => s.cards);
// useBoxMetrics types its ref as RefObject<DOMElement> (non-null); the
// null! assertion satisfies the signature — Ink populates the ref on
// mount before the metrics hook reads it.
const outerRef = useRef<DOMElement>(null!);
const innerRef = useRef<DOMElement>(null!);
const outer = useBoxMetrics(outerRef);
const inner = useBoxMetrics(innerRef);
const maxScroll = Math.max(0, inner.height - outer.height);
useEffect(() => {
onMaxScrollChange(maxScroll);
}, [maxScroll, onMaxScrollChange]);
let visible = cards;
if (suppressLive && cards.length > 0 && !isFullySettled(cards[cards.length - 1]!)) {
visible = cards.slice(0, -1);
}
return (
<>
{scrollRows > 0 ? <Text color={FG.faint}>{" ↑ earlier — PgUp / wheel / ↑"}</Text> : null}
<Box ref={outerRef} flexDirection="column" flexGrow={1} overflow="hidden">
<Box ref={innerRef} flexDirection="column" marginTop={-scrollRows} flexShrink={0}>
{visible.map((card) => (
<CardRenderer key={card.id} card={card} />
))}
</Box>
</Box>
</>
);
}
function isFullySettled(card: Card): boolean {
switch (card.kind) {
case "streaming":
case "tool":
@@ -15,34 +64,12 @@ function isSettled(card: Card): boolean {
return card.done || !!card.aborted;
case "reasoning":
return !card.streaming || !!card.aborted;
case "task":
case "subagent":
return card.status !== "running";
case "plan":
return card.steps.every((s) => s.status === "done" || s.status === "skipped");
default:
return true;
}
}
export function CardStream(): React.ReactElement {
const cards = useAgentState((s) => s.cards);
const lastIdx = cards.length - 1;
const lastCard = lastIdx >= 0 ? (cards[lastIdx] as Card) : null;
const lastIsLive = !!lastCard && !isSettled(lastCard);
const committed: Card[] = lastIsLive ? cards.slice(0, lastIdx) : cards.slice();
const live: Card[] = lastIsLive && lastCard ? [lastCard] : [];
// Static items are emitted via bridge.emitStatic, which renders them in an
// off-tree React reconciler — context from the live tree does NOT propagate.
// The ActiveCardContext.Provider must therefore live inside the children
// function so it travels with the rendered subtree.
return (
<>
<Static items={committed}>
{(card) => (
<ActiveCardContext.Provider value={false} key={card.id}>
<CardRenderer card={card} />
</ActiveCardContext.Provider>
)}
</Static>
{live.map((card) => (
<CardRenderer key={card.id} card={card} />
))}
</>
);
}
+4
View File
@@ -0,0 +1,4 @@
import { createContext } from "react";
/** ctrl-o toggles this; live streaming card swaps 4-line tail for full-tail view. */
export const LiveExpandContext = createContext<boolean>(false);
+89 -21
View File
@@ -11,6 +11,7 @@ import { PILL_MODEL, PILL_SECTION, Pill, modelBadgeFor } from "../primitives/Pil
import { Spinner } from "../primitives/Spinner.js";
import { CARD, FG, TONE } from "../theme/tokens.js";
import { useElapsedSeconds, useSlowTick, useTick } from "../ticker.js";
import type { SubagentActivity } from "../useSubagent.js";
export const SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
@@ -112,17 +113,20 @@ function ModePill({
export function UndoBanner({
banner,
}: {
banner: { results: ApplyResult[]; expiresAt: number };
banner: { results: ApplyResult[]; expiresAt: number; pausedRemainingMs: number | null };
}) {
useTick();
const totalMs = 5000;
const remainingMs = Math.max(0, banner.expiresAt - Date.now());
const paused = banner.pausedRemainingMs !== null;
const remainingMs = paused
? (banner.pausedRemainingMs ?? 0)
: 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;
const urgent = !paused && remainingSec <= 1;
const pct = (remainingMs / totalMs) * 100;
const tone = urgent ? TONE.err : TONE.accent;
const tone = paused ? TONE.warn : urgent ? TONE.err : TONE.accent;
return (
<Box marginY={1} paddingX={1}>
<Text backgroundColor={TONE.accent} color="black" bold>
@@ -132,11 +136,15 @@ export function UndoBanner({
<Text backgroundColor={TONE.brand} color="black" bold>
{" u "}
</Text>
<Text color={FG.faint}>{" to undo "}</Text>
<Text color={FG.faint}>{paused ? " to undo · " : " to undo · "}</Text>
<Text backgroundColor={paused ? TONE.warn : FG.faint} color="black" bold>
{" space "}
</Text>
<Text color={FG.faint}>{paused ? " to resume " : " to pause "}</Text>
<CharBar pct={pct} width={20} color={tone} showLabel={false} />
<Text color={FG.faint}>{" "}</Text>
<Text color={tone} bold={urgent}>
{`${remainingSec}s`}
<Text color={tone} bold={urgent || paused}>
{paused ? `${remainingSec}s · paused` : `${remainingSec}s`}
</Text>
</Box>
);
@@ -159,20 +167,8 @@ function subagentTitle(skillName: string | undefined, task: string): string {
return `Sub-agent · ${short || "anonymous"}`;
}
/** Live block for a running subagent — Card-styled, fixed row count for flicker-safety. */
export function SubagentRow({
activity,
}: {
activity: {
task: string;
iter: number;
elapsedMs: number;
skillName?: string;
model?: string;
phase?: "exploring" | "summarising";
lastInner: { glyph: string; color: string; label: string; meta?: string } | null;
};
}) {
/** Live block for a single in-flight subagent — rich layout, used when only one is running. */
export function SubagentRow({ activity }: { activity: SubagentActivity }) {
useTick();
const seconds = (activity.elapsedMs / 1000).toFixed(1);
const phase = subagentPhaseLabel(activity.phase, activity.iter, activity.elapsedMs);
@@ -222,6 +218,78 @@ export function SubagentRow({
);
}
/** 1 → rich; 2-max → compact rows; >max → compact + "+N more" fold. */
export function SubagentLiveStack({
activities,
max = 3,
}: {
activities: ReadonlyArray<SubagentActivity>;
max?: number;
}) {
const tick = useTick();
if (activities.length === 0) return null;
if (activities.length === 1) return <SubagentRow activity={activities[0]!} />;
const visible = activities.slice(0, max);
const overflow = activities.length - visible.length;
const summarising = activities.filter((a) => a.phase === "summarising").length;
const metaParts = [`${activities.length} running`];
if (summarising > 0) metaParts.push(`${summarising} summarising`);
return (
<Card tone={CARD.subagent.color}>
<CardHeader
glyph="⌬"
tone={CARD.subagent.color}
title="subagents"
titleColor={PILL_SECTION.plan.fg}
titleBg={PILL_SECTION.plan.bg}
subtitle={metaParts.join(" · ")}
right={<Spinner kind="braille" color={CARD.subagent.color} />}
/>
{visible.map((a, i) => (
<CompactSubagentLine key={a.runId} activity={a} tick={tick} index={i} />
))}
{overflow > 0 ? <Text color={FG.faint}>{` +${overflow} more running…`}</Text> : null}
</Card>
);
}
function CompactSubagentLine({
activity,
tick,
index,
}: {
activity: SubagentActivity;
tick: number;
index: number;
}) {
const summarising = activity.phase === "summarising";
const spinnerFrame = SPINNER_FRAMES[(tick + index) % SPINNER_FRAMES.length] ?? "·";
const glyph = summarising ? "▶" : spinnerFrame;
const glyphColor = summarising ? TONE.brand : CARD.subagent.color;
const seconds = (activity.elapsedMs / 1000).toFixed(1).padStart(5);
const title = activity.skillName ?? truncate(activity.task, 28);
const titlePadded = title.padEnd(28);
const last = activity.lastInner;
return (
<Box flexDirection="row">
<Text color={glyphColor} bold>
{` ${glyph} `}
</Text>
<Text color={FG.body}>{titlePadded}</Text>
<Text color={FG.faint}>{` iter ${String(activity.iter).padStart(2)} · ${seconds}s · `}</Text>
{last ? (
<>
<Text color={last.color}>{`${last.glyph} `}</Text>
<Text color={FG.body}>{truncate(last.label, 18)}</Text>
{last.meta ? <Text color={FG.faint}>{` ${last.meta}`}</Text> : null}
</>
) : (
<Text color={FG.faint}>queued…</Text>
)}
</Box>
);
}
function truncate(text: string, max: number): string {
return text.length > max ? `${text.slice(0, max)}…` : text;
}
+10 -12
View File
@@ -4,25 +4,17 @@ import React from "react";
import { Countdown } from "../primitives/Countdown.js";
import { useAgentState } from "../state/provider.js";
import type { Mode, NetworkState, StatusBar } from "../state/state.js";
import { FG, TONE, USD_TO_CNY } from "../theme/tokens.js";
import { FG, TONE, balanceColor, formatBalance, formatCost } from "../theme/tokens.js";
const RULE_PAD = 4;
const RULE_MIN = 20;
function balanceColor(cny: number): string {
if (cny < 5) return TONE.err;
if (cny < 20) return TONE.warn;
return TONE.brand;
}
export function StatusRow(): React.ReactElement {
const status = useAgentState((s) => s.status);
const session = useAgentState((s) => s.session);
const { stdout } = useStdout();
const cols = stdout?.columns ?? 80;
const ruleWidth = Math.max(RULE_MIN, cols - RULE_PAD);
const turnCny = status.cost * USD_TO_CNY;
const sessionCny = status.sessionCost * USD_TO_CNY;
const hasTurn = status.cost > 0;
return (
@@ -48,16 +40,22 @@ export function StatusRow(): React.ReactElement {
<Text bold color={TONE.brand}>
{"▸ "}
</Text>
<Text bold color={FG.body}>{`¥${turnCny.toFixed(4)} turn`}</Text>
<Text bold color={FG.body}>
{`${formatCost(status.cost, status.balanceCurrency)} turn`}
</Text>
</>
)}
<Sep />
<Text color={FG.sub}>{`¥${sessionCny.toFixed(3)} session`}</Text>
<Text
color={FG.sub}
>{`${formatCost(status.sessionCost, status.balanceCurrency, 3)} session`}</Text>
{status.balance !== undefined && (
<>
<Sep />
<Text color={FG.faint}>{"wallet "}</Text>
<Text bold color={balanceColor(status.balance)}>{`¥${status.balance.toFixed(2)}`}</Text>
<Text bold color={balanceColor(status.balance, status.balanceCurrency)}>
{formatBalance(status.balance, status.balanceCurrency)}
</Text>
</>
)}
<Sep />
+27 -31
View File
@@ -1,6 +1,6 @@
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 { inkCompat } from "../../renderer/index.js";
import { type InlineSpan, type MdLine, markdownToLines } from "./markdown-lines.js";
const FG_BODY = "#c9d1d9";
@@ -13,9 +13,6 @@ const TONE_WARN = "#f0b07d";
const SURFACE_ELEV = "#161b22";
export function MarkdownView({ text }: { text: string }): React.ReactElement {
// No useMemo: the renderer's Static-path uses a one-shot tree walker that
// doesn't set up a React dispatcher, so hook calls would throw. Parsing on
// every render is cheap (marked.lexer is allocation-light).
return <MarkdownLines lines={markdownToLines(text)} />;
}
@@ -25,35 +22,34 @@ export function MarkdownLines({
lines: ReadonlyArray<MdLine>;
}): React.ReactElement {
return (
<inkCompat.Box flexDirection="column">
<Box flexDirection="column">
{lines.map((line, i) => (
// biome-ignore lint/suspicious/noArrayIndexKey: lines are positional + stable per render
<LineRow key={`md-${i}-${line.kind}`} line={line} />
))}
</inkCompat.Box>
</Box>
);
}
function LineRow({ line }: { line: MdLine }): React.ReactElement | null {
switch (line.kind) {
case "blank":
return <inkCompat.Text> </inkCompat.Text>;
return <Text> </Text>;
case "hr":
return <inkCompat.Text color={FG_FAINT}>──────</inkCompat.Text>;
return <Text color={FG_FAINT}>──────</Text>;
case "heading":
return (
<inkCompat.Box>
<inkCompat.Text bold color={FG_STRONG}>
<Box>
<Text bold color={FG_STRONG}>
{`${"#".repeat(line.level)} `}
</inkCompat.Text>
</Text>
<Spans spans={line.spans} bold strongColor />
</inkCompat.Box>
</Box>
);
case "paragraph":
return (
<inkCompat.Box>
<Box>
<Spans spans={line.spans} />
</inkCompat.Box>
</Box>
);
case "list": {
const indent = " ".repeat(line.depth * 2);
@@ -68,20 +64,20 @@ function LineRow({ line }: { line: MdLine }): React.ReactElement | null {
const markerColor =
line.task === "done" ? TONE_OK : line.task === "todo" ? FG_FAINT : FG_META;
return (
<inkCompat.Box>
<inkCompat.Text color={markerColor}>{`${indent}${marker} `}</inkCompat.Text>
<Box>
<Text color={markerColor}>{`${indent}${marker} `}</Text>
<Spans spans={line.spans} dim={line.task === "done"} strike={line.task === "done"} />
</inkCompat.Box>
</Box>
);
}
case "code":
return <CodeBlock lang={line.lang} text={line.text} />;
case "blockquote":
return (
<inkCompat.Box>
<inkCompat.Text color={TONE_BRAND}>{"▎ "}</inkCompat.Text>
<Box>
<Text color={TONE_BRAND}>{"▎ "}</Text>
<Spans spans={line.spans} italic />
</inkCompat.Box>
</Box>
);
}
}
@@ -93,15 +89,15 @@ function spanKey(span: InlineSpan, i: number): string {
function CodeBlock({ lang, text }: { lang: string; text: string }): React.ReactElement {
const lines = text.split("\n");
return (
<inkCompat.Box flexDirection="column">
{lang.length > 0 ? <inkCompat.Text color={FG_META}>{` ${lang}`}</inkCompat.Text> : null}
<Box flexDirection="column">
{lang.length > 0 ? <Text color={FG_META}>{` ${lang}`}</Text> : null}
{lines.map((ln, i) => (
// biome-ignore lint/suspicious/noArrayIndexKey: code lines are positional + stable per render
<inkCompat.Text key={`code-${i}`} backgroundColor={SURFACE_ELEV}>
<Text key={`code-${i}`} backgroundColor={SURFACE_ELEV}>
{` ${ln} `}
</inkCompat.Text>
</Text>
))}
</inkCompat.Box>
</Box>
);
}
@@ -115,7 +111,7 @@ interface SpansProps {
}
function Spans({ spans, bold, italic, dim, strike, strongColor }: SpansProps): React.ReactElement {
if (spans.length === 0) return <inkCompat.Text> </inkCompat.Text>;
if (spans.length === 0) return <Text> </Text>;
return (
<>
{spans.map((span, i) => (
@@ -150,9 +146,9 @@ function SpanText({
}): React.ReactElement {
if (span.code) {
return (
<inkCompat.Text color={FG_STRONG} backgroundColor={SURFACE_ELEV}>
<Text color={FG_STRONG} backgroundColor={SURFACE_ELEV}>
{` ${span.text} `}
</inkCompat.Text>
</Text>
);
}
const color = span.fileRef
@@ -163,7 +159,7 @@ function SpanText({
? FG_STRONG
: FG_BODY;
return (
<inkCompat.Text
<Text
color={color}
bold={!!(span.bold || ambientBold)}
italic={!!(span.italic || ambientItalic)}
@@ -172,6 +168,6 @@ function SpanText({
underline={!!(span.link || span.fileRef)}
>
{span.text}
</inkCompat.Text>
</Text>
);
}
+33 -30
View File
@@ -127,7 +127,6 @@ function ListItem({
// biome-ignore lint/suspicious/noArrayIndexKey: list-item children are positional and stable per render
return <List key={`l-${i}`} token={tok as Tokens.List} depth={depth + 1} />;
}
// biome-ignore lint/suspicious/noArrayIndexKey: list-item children are positional and stable per render
return <BlockToken key={`b-${i}-${tok.type}`} token={tok} />;
})}
</Box>
@@ -328,31 +327,29 @@ function FallbackTable({
}): React.ReactElement {
return (
<Box flexDirection="column">
{headerCells.map((h, ci) => {
const label = `${padToCells(h, labelPad - 2)}: `;
const values = bodyCells.map((r) => r[ci] ?? "");
return (
// biome-ignore lint/suspicious/noArrayIndexKey: header cells positional
<Box key={`fk-${ci}`} flexDirection="column">
{values.map((v, ri) => {
const lines = wrapToCells(v, valueCells);
return lines.map((line, li) => (
// biome-ignore lint/suspicious/noArrayIndexKey: fallback table lines are positional
<Box key={`fv-${ri}-${li}`}>
{li === 0 ? (
<Text bold color={FG.sub}>
{label}
</Text>
) : (
<Text>{padToCells("", labelPad)}</Text>
)}
<Text color={FG.body}>{line}</Text>
</Box>
));
})}
</Box>
);
})}
{bodyCells.map((row, ri) => (
// biome-ignore lint/suspicious/noArrayIndexKey: body rows positional
<Box key={`fr-${ri}`} flexDirection="column">
{ri > 0 ? <Text> </Text> : null}
{headerCells.map((h, ci) => {
const label = `${padToCells(h, labelPad - 2)}: `;
const lines = wrapToCells(row[ci] ?? "", valueCells);
return lines.map((line, li) => (
// biome-ignore lint/suspicious/noArrayIndexKey: fallback table lines are positional
<Box key={`fc-${ri}-${ci}-${li}`}>
{li === 0 ? (
<Text bold color={FG.sub}>
{label}
</Text>
) : (
<Text>{padToCells("", labelPad)}</Text>
)}
<Text color={FG.body}>{line}</Text>
</Box>
));
})}
</Box>
))}
</Box>
);
}
@@ -370,12 +367,17 @@ function Inline({ tokens }: { tokens: Token[] }): React.ReactElement {
const FILE_REF_RE = /\b([A-Za-z0-9_./@\-]+\.[A-Za-z0-9]{1,6})(?::(\d+)(?:-(\d+))?)?\b/g;
const MENTION_RE = /(?<![A-Za-z0-9_])@([A-Za-z0-9_./\-]+\.[A-Za-z0-9]{1,6})/g;
function osc8(label: string, target: string, color: string): React.ReactElement {
const open = `\x1b]8;;${target}\x07`;
const close = "\x1b]8;;\x07";
function looksLikeFileRef(path: string, hasLine: boolean): boolean {
if (hasLine) return true;
if (path.includes("/")) return true;
const ext = path.split(".").pop() ?? "";
return ext.length >= 2;
}
function osc8(label: string, _target: string, color: string): React.ReactElement {
return (
<Text color={color} underline>
{`${open}${label}${close}`}
{label}
</Text>
);
}
@@ -402,6 +404,7 @@ function renderInlineText(raw: string): React.ReactElement {
if (hits.some((h) => start < h.end && end > h.start)) continue;
const path = m[1]!;
const line = m[2];
if (!looksLikeFileRef(path, line !== undefined)) continue;
const target = line ? `file://${path}:${line}` : `file://${path}`;
hits.push({ start, end, node: osc8(m[0], target, TONE.brand) });
}
+16 -12
View File
@@ -1,4 +1,4 @@
/** Applies an MCP append-drift mid-session: registers each new tool in the loop's registry + prefix, and updates the summary's report. */
/** Applies an MCP append-drift mid-session: registers each new tool in the loop's registry + prefix, and returns an updated summary. Immutable — does not mutate the input `target`. */
import type { CacheFirstLoop } from "../../loop.js";
import { registerSingleMcpTool } from "../../mcp/registry.js";
@@ -10,7 +10,7 @@ export function applyMcpAppend(
loop: CacheFirstLoop,
target: McpServerSummary,
addedTools: McpTool[],
): void {
): McpServerSummary {
const accepted: McpTool[] = [];
for (const mcpTool of addedTools) {
if (!mcpTool.name) continue;
@@ -27,14 +27,18 @@ export function applyMcpAppend(
loop.prefix.addTool(spec);
accepted.push(mcpTool);
}
if (accepted.length === 0) return;
// Refresh the summary's snapshot so `/mcp` and the browser modal show the
// new shape on their next render.
if (target.report.tools.supported) {
const merged = [...target.report.tools.items, ...accepted];
// biome-ignore lint/suspicious/noExplicitAny: report is a typed snapshot we mutate in place; deeper refactor isn't worth it here
(target.report.tools as any).items = merged;
// biome-ignore lint/suspicious/noExplicitAny: same — toolCount mirrors items.length post-append
(target as any).toolCount = merged.length;
}
if (accepted.length === 0 || !target.report.tools.supported) return target;
const merged = [...target.report.tools.items, ...accepted];
return {
...target,
toolCount: merged.length,
report: {
...target.report,
tools: {
supported: true as const,
items: merged,
},
},
};
}
+8 -5
View File
@@ -5,8 +5,8 @@ import type { McpTool } from "../../mcp/types.js";
import { formatMcpLifecycleEvent } from "./mcp-lifecycle.js";
import type { McpServerSummary } from "./slash/types.js";
/** Applies append-drift mid-session: registers each new MCP tool in the registry + prefix. */
export type ApplyAppend = (target: McpServerSummary, addedTools: McpTool[]) => void;
/** Applies append-drift mid-session: registers each new MCP tool in the registry + prefix. Returns the updated summary. */
export type ApplyAppend = (target: McpServerSummary, addedTools: McpTool[]) => McpServerSummary;
/** Kicks off async reconnect; returns the start-line, schedules result via postInfo. */
export function kickOffMcpReconnect(
@@ -18,17 +18,20 @@ export function kickOffMcpReconnect(
// Only opt into "append" when the caller wired an applyAppend handler;
// otherwise the reconnect refuses append-drift with a "restart" message.
const accept = applyAppend ? (["identity", "append"] as const) : (["identity"] as const);
// Use a mutable local so the async closure can update it after applyAppend
// without reassigning the function parameter (linter: noParameterAssign).
let liveTarget = target;
void (async () => {
try {
const result = await reconnectMcpServer({
host: target.host,
spec: target.spec,
host: liveTarget.host,
spec: liveTarget.spec,
beforeTools,
accept,
});
if (result.ok) {
if (result.kind === "append" && applyAppend) {
applyAppend(target, result.addedTools);
liveTarget = applyAppend(liveTarget, result.addedTools);
}
postInfo(
formatMcpLifecycleEvent({
+13
View File
@@ -0,0 +1,13 @@
import type { McpServerSummary } from "./slash/types.js";
export function sameMcpServerSummary(a: McpServerSummary, b: McpServerSummary): boolean {
return a === b || (a.label === b.label && a.spec === b.spec);
}
export function replaceMcpServerSummary(
servers: McpServerSummary[],
target: McpServerSummary,
updated: McpServerSummary,
): McpServerSummary[] {
return servers.map((server) => (sameMcpServerSummary(server, target) ? updated : server));
}
+10 -9
View File
@@ -28,8 +28,10 @@ export interface MultilineAction {
/** When `true`, fire `onSubmit(submitValue ?? value)`. */
submit: boolean;
submitValue?: string;
/** Set when ↑/↓ hits a buffer boundary — parent handles history recall. */
/** Set on Ctrl+P / Ctrl+N — parent handles prompt-history recall. */
historyHandoff?: "prev" | "next";
/** Set when ↑/↓ fires on an empty buffer — parent scrolls the chat history. */
chatScrollHandoff?: "up" | "down";
/** Reducer is pure — hands raw paste to PromptInput which allocates a sentinel and inserts that. */
pasteRequest?: { content: string };
}
@@ -68,12 +70,11 @@ export function processMultilineKey(
return cursor === value.length ? NOOP : { next: null, cursor: value.length, submit: false };
}
// History recall is bound to Ctrl+P / Ctrl+N (bash readline
// convention) rather than ↑/↓. Reason: Windows Terminal + ConPTY
// translates mouse wheel events to ↑/↓ keystrokes for raw-mode
// child processes — indistinguishable at the byte level. If ↑/↓
// recalled history, every wheel-scroll would corrupt the prompt
// with a prior message. Ctrl+P/N is wheel-immune.
// Prompt-history recall is on Ctrl+P / Ctrl+N (bash readline
// convention). ↑/↓ on an empty buffer scrolls chat history because
// Windows Terminal + ConPTY translates mouse wheel events to ↑/↓ in
// raw mode — the only way to make wheel-up scroll chat is to map ↑
// to chat-scroll. Ctrl+P/N is wheel-immune.
if (key.ctrl && key.input === "p") {
return { ...NOOP, historyHandoff: "prev" };
}
@@ -90,12 +91,12 @@ export function processMultilineKey(
return { next: null, cursor: Math.min(value.length, cursor + 1), submit: false };
}
if (key.upArrow) {
if (value.length === 0) return { ...NOOP, historyHandoff: "prev" };
if (value.length === 0) return { ...NOOP, chatScrollHandoff: "up" };
const moved = moveCursorUp(value, cursor);
return moved === cursor ? NOOP : { next: null, cursor: moved, submit: false };
}
if (key.downArrow) {
if (value.length === 0) return { ...NOOP, historyHandoff: "next" };
if (value.length === 0) return { ...NOOP, chatScrollHandoff: "down" };
const moved = moveCursorDown(value, cursor);
return moved === cursor ? NOOP : { next: null, cursor: moved, submit: false };
}
-1
View File
@@ -1,5 +1,4 @@
import { Box } from "ink";
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React in value scope for JSX compilation
import React, { useContext } from "react";
/** Settled cards (in scrollback) drop the border + paddingX so history reads as flat lines. */
-1
View File
@@ -1,5 +1,4 @@
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 { FG } from "../theme/tokens.js";
Loaded 100 of 310 files, more files were not shown because too many files have changed in this diff. Show more