Compare commits

...
263 Commits
Author SHA1 Message Date
YHH bb971bd403 chore(release): 0.34.0 (#484) 2026-05-09 11:39:14 +08:00
YHH 06204c760e fix(dashboard): stop pushing localStorage lang back to server on init (#483)
The dashboard's initLangFromServer() had two branches when localStorage
disagreed with the server config:

  1. If `rx.langExplicit` was set (user picked a language in dashboard
     panel at some point) → POST localStorage value back to server
  2. Otherwise → adopt the server value

Branch 1 silently clobbered CLI-side `/language` changes. Sequence:

  - User picks zh-CN in dashboard once → rx.langExplicit=1, rx.lang=en
    (or whichever)
  - User later runs `/language zh-CN` in the CLI → server config is
    now zh-CN
  - User opens dashboard tab (or browser restores it from a previous
    session) → init runs → POSTs localStorage's old value back, server
    flips to en, CLI's choice is lost on next launch

Server config is the single source of truth. localStorage is purely a
render-cache to avoid first-paint flicker — never push it back.

Removes EXPLICIT_KEY / isExplicit / markExplicit entirely; the stale
key in existing users' localStorage is harmless dead data.
2026-05-09 11:33:49 +08:00
YHH c504707af8 feat(ui): /keys reference + first-run mouse/clipboard tip (#481)
Two layers around the new TipCard:

1. /keys — make the slash command real
   It was already referenced in the edit-gate tip's footer ("Run /keys
   anytime for the full list") but no handler existed; typing /keys hit
   the unknown-command branch. Add the spec under "info", a handler
   that pushes a multi-section TipCard with the full reference, and a
   `postKeys` callback on SlashContext wired to log.pushTip.

   The reference is sectioned: keyboard / mouse / copy-paste /
   edit-gate. Each section has its own subtitle and aligned key column.

2. First-run mouse + clipboard tip
   SGR mouse tracking captures the wheel for chat scroll but also eats
   the terminal's native right-click-paste — without explanation users
   think the prompt is broken. Add a one-time tip mirroring the
   edit-gate pattern: pushed on first launch, suppressed thereafter via
   a `mouseClipboardHintShown` flag.

TipCard now supports multiple sections (single-section tips just have
one un-titled section). The previously-shipped tipEditBindings is
re-wrapped in a single section; behavior unchanged.

i18n: keysReference (4 sections, ~25 rows) + tipMouseClipboard (1
section, 3 rows) + handlers.basic.keysNeedsTui in EN.ts and zh-CN.ts;
matching shape in types.ts. The i18n /keys row already existed but its
description was outdated — refreshed in both languages.
2026-05-09 11:06:23 +08:00
YHH f0a552bed5 feat(ui): structured TipCard variant for onboarding hints (#480)
The edit-gate one-time tip currently renders as raw multi-line text
inside a stepProgress LiveCard — `✓` glyph (success semantic, wrong
for educational content) plus a manually-inlined `▸ TIP:` prefix,
columns aligned with hand-counted spaces that wrap badly on narrow
terminals, and the "shown once" disclaimer crammed into the body
parenthetical.

Replace it with a dedicated `TipCard` kind:
- Single `ⓘ` glyph in accent color, no duplicated prefix
- Topic + "shown once" badge in a header row (justified)
- Each row is its own `<Text>` with real column alignment driven by
  stringWidth (works for CJK widths too)
- Footer separated from body by a blank row, dim color
- No border — tips are scrollback content, not modal

i18n: `tipEditBindings` becomes a structured `{topic, rows, footer}`
object across types.ts / EN.ts / zh-CN.ts. New helper `tObj<T>(path)`
in i18n/index.ts for non-string entries; the existing `t()` is
unchanged. Adds a tiny `tipShownOnce` string for the badge.

Adds a `pushTip()` method on Scrollback alongside `pushInfo()`; the
new `tip.show` event flows through the same reducer / dispatch pipeline
as every other card kind.
2026-05-09 10:54:52 +08:00
YHH bb5b124817 @-picker rebuild + mouse-wheel chat scroll (#479)
* feat(at-picker): rebuild as file browser with streaming search

Empty / trailing-slash queries (`@`, `@src/`) browse one directory level
with a single readdir — folders selectable, drill via Tab. Any non-slash
filter (`@foo`, `@auth/log`) kicks off a cancelable streaming walk across
the full tree, batching matches into the popup as they're found, with a
`searching… N scanned` footer while in flight.

Replaces the upfront 500-file walk that was unusable on large repos —
on a 5k-file tree the cap evicted ~90% of paths before ranking, leaving
the picker effectively empty.

- walkFilesStream: cancelable streaming walker; powers search mode
- listDirectory: single-level browse, no recursion; powers browse mode
- parseAtQuery: splits `dir/filter` with trailing-slash awareness
- listFilesWithStatsAsync now delegates to walkFilesStream (no behavior
  change for existing callers)
- expandAtUrls + helpers split into at-mentions-url.ts to keep
  at-mentions.ts under the 800-line ceiling

Closes #478

* fix(scroll): route mouse wheel via SGR mouse tracking

Enable DECSET 1006 + 1000 at startup so the terminal reports wheel
events as `\x1b[<btn;col;row;M` mouse sequences instead of translating
them to ↑/↓ key presses. The chat-scroll handler routes the resulting
mouseScrollUp/Down events to scrollback, bypassing the arrow-key path
entirely — the wheel now scrolls chat regardless of buffer state, while
↑/↓ keys retain their existing PromptInput bindings (history recall on
empty buffer, cursor motion otherwise).

The SGR mouse parser already lived in stdin-reader.ts; this just
turns on the terminal-side feature so events actually flow.

Cost: terminal-native drag-to-select needs a modifier (Shift on Windows
Terminal / Alacritty / WezTerm, Option on iTerm2) — same trade-off as
tmux, Claude Code, Cursor's terminal.
2026-05-09 10:28:28 +08:00
J3y0r 636ad7e551 feat(ui): add theme manager support (#452)
Closes #449

- Theme runtime via useColor() hook + ThemeProvider context
- Built-in themes: default, dark, light, tokyo-night, github-dark, github-light, plus auto/high-contrast
- Persisted via config: theme.name, with auto resolving against terminal background
- /theme slash command (advanced group) with arg completer

Merged through #453 slash refactor (theme placed in advanced group) and #424 semantic config additions.
2026-05-08 18:19:22 -07:00
YHH 1c360ac81b chore(release): 0.33.2 (#476) 2026-05-09 09:02:01 +08:00
YHH c120ed3a39 fix: ↑/↓ on empty buffer recall history; doctor finds tokenizer (#468) (#475)
Two bugs in one issue.

1. **↑/↓ stopped recalling history.** 9254d3a unbound history from
   arrows because Windows Terminal + ConPTY can translate mouse-wheel
   events to ↑/↓ keystrokes — wheel-up was clobbering the prompt with
   a recalled message. The fix moved history to Ctrl+P / Ctrl+N.

   That was the right call for legacy ConPTY users but broke the
   universal CLI muscle memory for everyone else (bash / zsh / fish
   all bind ↑ to history). Linux / macOS / modern Windows Terminal
   users don't have the wheel-translation problem in the first place.

   Restore ↑/↓ on empty buffer = history; keep Ctrl+P / Ctrl+N as
   the wheel-immune fallback. The App-level keystroke handler still
   routes ↑/↓ to chat-scroll once the user is unpinned (subsequent
   wheel events keep scrolling), so the only regression for legacy
   ConPTY is the FIRST wheel-up from a pinned position recalls a
   prompt. Documented; ⌃P/N is one keystroke away.

   Drops the now-dead `chatScrollHandoff` plumbing.

2. **Doctor reported "tokenizer not found" when it was installed.**
   The tokenizer ships under `data/` in the npm tarball and the
   runtime resolver in tokenizer.ts has three candidates including a
   `createRequire("reasonix/package.json")` probe — finds it
   reliably. The doctor had its own resolver that walked
   `dist/cli/commands/doctor.js → ../../../data/`, which broke after
   the lazy-import refactor in #467 emitted the doctor at
   `dist/cli/doctor-HASH.js` (one level shallower). Walked above the
   package root and reported missing.

   Reuse the runtime resolver (now exported) so the two paths can
   never disagree.
2026-05-09 08:58:10 +08:00
YHH 42f75c7478 chore(release): 0.33.1 (#474) 2026-05-09 08:24:46 +08:00
YHH 34b8275f20 feat(ui): wallet pill on status row + tighter prompt hints (#473)
The status row was reading status.cost (turn) and status.cacheHit
but ignoring two fields the reducer already populates:
status.sessionCost (running USD total) and status.balance (DeepSeek
wallet, refreshed on every submit). balanceColor() with red/orange
thresholds even sat in tokens.ts unused.

New WalletPill segment renders right of the cache pill:
  ⛁ ¥1.20 spent  /  ¥45.32 left
with thresholded color on the balance number. Shown only when
the terminal is ≥90 cols and at least one of the two values is
known, so narrow sessions don't wrap.

PromptInput: friendlier placeholder copy ("ask anything") and the
hint footer now uses keycap/label spacing (⇧⏎ instead of
shift/alt+⏎) for a less command-line-jargon read.
2026-05-09 08:21:09 +08:00
YHH b40db0f469 chore(release): 0.33.0 (#472) 2026-05-09 08:06:19 +08:00
YHH 4029b7dc25 fix(ui): drop dead toolHistoryRef leak — every tool result retained for session lifetime (#465) (#471)
The /tool slash command was removed in #453 but its supporting
plumbing was left behind: every tool result was still being pushed
into a useRef array, with no consumer ever reading it. Long-running
sessions accumulated full Read/Grep/Bash output indefinitely and ran
out of heap.

#465 reports a JS heap OOM after ~2.6 hours on v0.31.0; this leak
matches the failure shape (mark-compacts ineffective, 4GB ceiling).
2026-05-09 07:59:25 +08:00
YHH 9c69513650 fix(/cwd): re-bootstrap semantic_search on workspace swap (#470)
#459 follow-up. When `/cwd` swaps the workspace root, FS/shell/memory
tools were re-registered against the new path but `semantic_search`
kept pointing at the OLD root — meaning queries silently searched
the previous project's index, or the tool stayed registered when
the new dir had no index at all.

Split semantic re-bootstrap from the sync `reregisterTools` callback:
- `reregisterTools` stays sync (FS/shell/memory must land before the
  next tool dispatch).
- New `reBootstrapSemantic(root) => Promise<{ enabled }>` reads disk
  to probe index compatibility, registers `semantic_search` if found,
  unregisters it otherwise.

App.tsx fires the async tail with `void ...then(postInfo)` so the
slash dispatch returns synchronously (matches the codebase's
fire-and-forget pattern documented in slash/dispatch.ts). User sees:

  ▸ workspace switched to /new/path
  ▸ semantic_search re-pointed at /new/path        ← if compatible
  ▸ semantic_search disabled (no compatible index in /new/path)
                                                   ← if not

Same machinery handles the launch path — `code.tsx` now calls
`reBootstrapSemantic(rootDir)` instead of bootstrap directly so
the unregister-on-skip behavior is exercised on every entry path.
2026-05-09 07:27:03 +08:00
YHH df8f146b79 perf(cli): lazy-import dashboard server + strategic App marks (#469)
Stage 2 follow-up to #464. Continuing the profile-driven trims.

The dashboard server module (src/server/index.ts plus its ~4200 LOC
of transitive dashboard code) was being eagerly imported into App.tsx
even when --no-dashboard was set or auto-start hadn't fired. Move it
to a dynamic import inside startDashboard's startup IIFE — it's
already async, so the await import() is free in the structural
sense.

Measurable hot-path delta is small (~4ms within noise) but it shaves
real bytes off the first-paint module graph and removes a synchronous
dependency on the entire server tree. Cold paths benefit too.

Also adds two strategic marks (`app_render_start`, `app_inner_start`)
for future profiling. They're harmless when the env var is off and
expose the React-component-body boundary in the dump, which makes
the existing `first_paint` delta self-explanatory.

Findings from the deeper investigation (now reverted as noisy diagnostics):
- App's disk-hitting useState initializers (loadHooks, loadSlashUsage,
  loadEditMode, hydrateCardsFromMessages) are all sub-ms each.
  Deferring them buys nothing measurable.
- The 280-300ms gap between `app_inner_start` and `first_paint` is
  React reconciliation + Ink's terminal commit + the first useEffect
  flushing. Trimming further requires reducing initial render
  complexity, not deferring side work.

Stage 3 (CI budget gate) remains deferred — the platform-dependent
nature of these numbers makes a hard threshold fragile. Profile
harness is already documented in-tree via the env-var hint
(`REASONIX_PROFILE_STARTUP=0 to silence`).
2026-05-09 07:17:26 +08:00
YHH e6b247939c perf(cli): lazy-import per-command modules (Stage 2 of #464) (#467)
Stage 1 (#466) showed module-load was 57% of cold-start cost (436ms
of 764ms total on this Windows box). Every `reasonix <subcommand>`
invocation was eagerly loading every other command's module —
including chat.tsx → App.tsx → React/Ink. `reasonix version` paid
for the chat UI it doesn't need.

Move every `import { fooCommand } from "./commands/foo.js"` into a
dynamic `await import()` inside the relevant `.action()`. tsup
splits these into separate chunks automatically; Node only loads
them when the user invokes that subcommand.

Measured impact:

  reasonix code (hot path, 5 runs avg): 778ms vs 764ms baseline
    → +14ms regression (within measurement noise; the 388ms that
      used to live in `cli_module_loaded` now lives in
      `code_command_enter` since code.tsx is dynamic-imported)

  reasonix version: ~140ms vs ~440ms baseline → 290ms saved
  reasonix --help:  ~140ms vs ~440ms baseline → 290ms saved

Cold-path commands (version, --help, doctor, commit, sessions,
events, replay, diff, mcp *, update, index) all benefit. They
no longer pay the ink/react/dashboard import cost.

Hot path (`code` / `chat`) is roughly neutral. Real wins on hot
path will come from trimming first_paint (316ms, 41% of total) —
follow-up.

Test fix: bundle-smoke.test.ts asserted `from "ink"` lived in
dist/cli/index.js specifically; with code-splitting the import
moves to a chunk file. Updated assertion to scan all dist/cli/*.js.
The semantics are preserved — ink stays external (not bundled),
just no longer in the entry chunk.
2026-05-09 01:07:57 +08:00
YHH 424a9301f4 perf(cli): startup-profile instrumentation (Stage 1 of #464) (#466)
#464 plan was profile-first; this lands Stage 1.

Adds src/cli/startup-profile.ts with markPhase/dumpStartupProfile
gated behind REASONIX_PROFILE_STARTUP=1. When unset (default), every
call is a no-op — zero cost in normal runs.

Marks placed at:
- cli_module_loaded — top of the bin entry, after all transitive imports
- chat_command_enter / config_loaded
- mcp_launch / mcp_connected_M_of_N (only when MCP specs exist)
- code_command_enter — top of `reasonix code`
- semantic_bootstrap_start / _done_(enabled|skipped)
- ink_render_call — just before `render(<Root/>)`
- first_paint — App's first useEffect after mount, also dumps the profile

Baseline collected on this Windows box (no MCP, semantic index already
built):

  436ms  cli_module_loaded             (+436)
    3ms  code_command_enter            (+3)
    2ms  semantic_bootstrap_start      (+2)
    2ms  semantic_bootstrap_done_enabled  (+2)
    3ms  chat_command_enter            (+2)
    0ms  config_loaded                 (+0)
    2ms  ink_render_call               (+1)
  316ms  first_paint                   (+316)
  ─── 764ms total

Read: module-load (Node + transitive imports) is 57% of total, first
paint (Ink render + React commit) is 41%. Everything else is noise.
Stage 2 should target lazy-loading heavy import dependencies that
land synchronously today (DeepSeek client, Ink, dashboard server,
embedding provider). MCP serial setup hypothesis from the issue
needs a real config to confirm — punted until we have a measured
multi-MCP run.

Stage 3 (CI budget assertion) deferred until Stage 2 trims have
landed and we have stable numbers to set thresholds against.
2026-05-09 00:55:08 +08:00
YHH b171848250 fix(ux): fuzzy at-mention ranking + /cwd slash for #459 parts 1+2 (#463)
#459 is a meta-issue with three first-five-minutes UX papercuts.
This lands two of them; startup-perf (part 3) needs profiling
first and gets a separate issue.

## Part 1: at-mention picker — subsequence fallback

The picker rejected anything that wasn't a substring match, so
typing `atmnt` for `at-mentions` returned nothing. Adds a fuzzy-
subsequence scorer as a fallback after substring lookup misses.
Substring hits still win — class 0/1/2 cap at 29_999, subseq
starts at 30_000. Fuzzy scoring rewards consecutive runs and
basename-anchored matches, penalizes total path length.

Files walking + cap-aware UI hints already existed (the audit
showed them at useCompletionPickers.ts:102 and
AtMentionSuggestions.tsx:55–77). The missing piece was ranking.

## Part 2: /cwd slash command

The plumbing was already there: `codeMode.reregisterTools(root)`
exists in code.tsx, App.tsx already comments "/cwd mutates this
state to swap the workspace mid-session". The slash command
itself was just never wired.

Wires it end-to-end:
- SlashContext gets a `switchCwd(path) => { ok, info }` hook.
- App.tsx implements switchCwd: stat + isDirectory check,
  reregisterTools(newPath), setCurrentRootDir, reload hooks.
- New `/cwd` (alias `/sandbox`) command in the code group.
- Handler in handlers/edits.ts.
- EN + zh-CN strings added.

Out of scope: semantic-index re-bootstrap on cwd swap (current
bootstrap runs once in code.tsx). Tracked as a follow-up.

## Part 3 (deferred)

Slow startup needs profiling before redesign. Will open a separate
issue with a concrete "mark phases, defer post-mount" plan.
2026-05-09 00:41:14 +08:00
YHH cf393f7f9e feat(tools): glob, search_content context lines, cross-file multi_edit (#462)
Three quality polishes to the filesystem toolbelt, all small, all
addressing real friction the model hits often.

glob — new tool. Mtime-sorted file walk with picomatch glob syntax
(**/, *.{ts,tsx}, etc.). Default sort=mtime desc so "what did I
touch lately" works out of the box; sort=name for deterministic
listings. Skips deps by default, capped at 200 results (1000 max)
with overflow notice. Different from search_files (substring on
basename) and search_content (greps file bodies).

search_content — new `context: N` param mirroring `grep -C N`.
Output uses ripgrep convention: `:` after the line number on hits,
`-` on context lines, `--` separating non-adjacent windows.
Adjacent windows merge automatically so a hit at line 42 and 44
with context:1 produces one continuous block. Capped at 20 lines
on each side to keep the maxListBytes budget intact.

multi_edit — reshape from single-file `{ path, edits: [...] }` to
cross-file `{ edits: [{ path, search, replace }, ...] }`. Reads
each touched file once, applies edits in array order against an
in-memory buffer (so a later edit can match text inserted by an
earlier one), validates everything, then writes all touched files.
ANY validation failure → ZERO writes (true atomicity at the
validation layer; sequential disk writes after that). Output
header now reports both "N edits across M files".

This is a hard schema break for multi_edit, but it shipped
unreleased six hours ago — no consumers to migrate.

Test coverage: 24 new cases (glob: 6, context: 4, multi_edit: 8
covering single + cross + atomic + missing-file). 2243 pass on
verify.
2026-05-09 00:29:28 +08:00
YHH 771443c670 feat(tools): todo_write — lightweight in-session task tracker (#460)
submit_plan is the heavy gate (user approval, per-step checkpoints,
plan-mode toggle); ask_choice is the branching primitive. Neither
covers "I have 4 things to do, let me record them and tick them off
as I go" — that's prose-list territory today, which means lost
context the moment the loop folds history.

todo_write fills the gap: replace-set semantics, no approval pause,
no file writes. Validated: at most one in_progress, status enum,
non-empty content+activeForm. readOnly=true so it stays callable in
/plan mode (recording intent during planning is exactly when it's
most useful).

Wired into reasonix code with an onTodosUpdated callback hook for
future TUI surfacing (live progress strip, etc.). System prompt
gains a "When to track multi-step intent" section telling the model
to reach for it on 3+ step tasks instead of inlining "1. ... 2. ..."
in prose.
2026-05-09 00:15:09 +08:00
YHH 747651e55d feat(tools): multi_edit — atomic batch SEARCH/REPLACE in one file (#458)
N edit_file calls for a single-file rename burns a tool round-trip
per site and isn't atomic — a mid-batch failure leaves the file half-
edited. multi_edit takes an array of {search, replace} entries,
applies them sequentially against an in-memory buffer, and only
writes once all succeed. Any failure (search not found, ambiguous
match, empty search) → no edits are written.

Per-edit rules match edit_file: exact whitespace-sensitive search,
must be unique at the moment that edit applies. Sequential semantics
mean edit N+1 can match text that edit N inserted.

Closes a concrete pain point flagged when surveying the toolbelt
against typical multi-site refactor flows.
2026-05-09 00:04:33 +08:00
YHH d4a4c599b5 chore(release): 0.32.0 (#456) 2026-05-08 23:22:24 +08:00
YHH 192a63b8d2 fix(at-mentions): expand @<dir> to a listing; recover symlink-to-file in picker (#455)
Closes #451

UI flicker (section 3 of #451) is already tracked in #412.

1. expandAtMentions treated `@<dir>` as a `not-file` skip — the model
   never saw what was in the directory. It now resolves the path, walks
   the project root with the existing gitignore layers, filters to
   entries under the directory, and inlines a `<directory>` block
   capped at DEFAULT_AT_DIR_MAX_ENTRIES (200). `@docs/` and `@docs`
   resolve to the same key, so trailing-slash typing doesn't double-fire.

2. listFilesWithStatsSync / listFilesWithStatsAsync called only
   ent.isFile(), which returns false for symlinks. Symlinked source
   files were silently dropped from the picker. Both walkers now stat
   through symlinks; symlinks-to-files come back, symlinks-to-dirs
   stay dropped (cycle risk), broken links stay dropped (nothing to
   point at).
2026-05-08 23:14:23 +08:00
YHH 58f4544d23 fix(plan): dock active plan card; auto/yolo skips per-step checkpoint (#454)
Two related plan-mode UX gaps.

1. PlanLiveRow had nothing to dock. `case "plan_proposed"` dropped the
   gate payload's steps/summary, and the approve path never dispatched
   plan.show — so no card with variant: "active" ever existed and the
   filter in isActivePlanInFlight returned null. Stash steps/summary in
   the existing refs on plan_proposed, materialize the active card on
   approve, and drop+re-show on revise-accept so the dock tracks tail
   rewrites instead of silently going stale.

2. "Checkpoint — step done" fired after every mark_step_complete even
   in auto/yolo, defeating the whole point of those modes (shell and
   edit-gate already self-skip). plan_checkpoint now checks editModeRef
   and, in auto/yolo, resolves the gate with "continue" without UI.
   Per-step rollback snapshot still runs so /restore granularity stays.
2026-05-08 23:01:08 +08:00
YHH 76e42ac665 slash: unified preset+model picker, grouped suggestions, kill 11 commands + harvest/branch (#453)
* slash: unified preset+model picker, grouped suggestions, kill 11 commands + harvest/branch

The slash surface was 58 commands deep with no organization, two confusable
options for "fresh start" (/clear vs /new), separate preset and model commands
that solved the same user question ("what AI am I using"), and two heavy
features that almost nobody opted into. Pulled all of that apart.

Picker

* ModelPicker now shows the 3 presets at the top with cost/headline copy and
  the model catalog below; auto-detects which preset the loop currently matches
  (model + effort + autoEscalate) so the cursor lands on the active row. Both
  /preset (no arg) and /model (no arg) open it.

SlashSuggestions

* SlashCommandSpec gains a `group` field (chat / setup / info / session /
  extend / code / jobs / advanced). Suggestion palette renders section headers
  on a bare /; advanced rows hide behind a "+ N advanced · type to search"
  footer until the user types a letter. /help walks the same registry, so
  there's one source of truth.

Telemetry

* New ~/.reasonix/slash-usage.json counter (read-modify-write, atomic rename)
  feeds suggestSlashCommands so frequent commands sort first within a prefix.
  emitSlashInvoked is now wired to the events.jsonl sidecar.

Removals (commands)

* /models, /keys, /resume, /semantic — redundant with picker / /help / /doctor.
* /clear merged into /new (now an alias) — the visual-only clear was the most
  common confusion source ("why does /clear keep my context?").
* /effort, /rename, /forget, /apply-plan, /think, /tool, /mcp browse — second
  pass; either covered by other UI (sessions picker has rename/delete; preset
  locks effort) or self-described as fallback / debug.

Removals (features)

* /harvest and the Pillar-2 plan-state extractor (src/harvest.ts).
* /branch and the parallel-sample selector (src/consistency.ts,
  src/loop/branch.ts). Streaming/branching coupling, BranchCard,
  branch_start/progress/done events, transcript planState/harvestedTurns,
  --harvest/--branch CLI flags, all gone.
* benchmarks/harvest/ deleted; ARCHITECTURE.md collapsed from four pillars
  to three; README + zh-CN + dashboard/PARITY updated.

i18n

* Cleared dead keys for every removed command (handlers.basic.helpHelp..helpExit,
  keys*, semantic, resume*, models*, harvest*, branch*, effort*, think*, tool*,
  apply-plan*, slash.harvest, slash.branch, ui.harvest*, ui.branch*).

Tests: 138 files / 2192 tests pass. Public API drops harvest, runBranches,
TypedPlanState, BranchSummary, etc.; consumers using those break intentionally.

* ci: drop harvest-bench dry-run step

Follows the harvest feature removal — benchmarks/harvest/ no longer exists,
so the CI step was breaking on ERR_MODULE_NOT_FOUND. τ-bench dry-run stays.
2026-05-08 22:31:52 +08:00
kabaka a9471ae8e1 feat(semantic): OpenAI-compatible embedding provider (#424)
Configurable API URL / key / model / request body for embeddings, replacing the Ollama-only setup. Adds a provider abstraction in src/index/semantic/embedding.ts, index identity check + abort wiring through the builder, API-key redaction in dashboard/status output, and en-US + zh-CN strings for the new provider UI.
2026-05-08 22:13:01 +08:00
YHH f9a1d0912d chore(release): 0.31.0 (#450) 2026-05-08 20:23:00 +08:00
YHH 3f3b5e2fe7 i18n(slash): localize 4 lagging slash handlers (#448)
Most handler files were already 80%+ i18n'd from prior work, but
four files had drift:

  - web-search-engine.ts — 0 t() calls, the entire help text plus
    switch confirmation was hardcoded English. Whole new
    handlers.webSearchEngine namespace (~12 keys).
  - mcp.ts — 5 hardcoded usage / unknown-server / "(none)" /
    reconnect-not-wired strings; added under handlers.mcp.
  - plans.ts — the archive row template ("✓ {when} {N} steps · …"),
    "complete" verb, and the /stop abort line. Added under
    handlers.plans.
  - semantic.ts — code-mode-only refusal + "checking…" status.
    Added under handlers.semantic. Note this file uses two t()
    instances side-by-side — the local @/index/semantic/i18n one
    stays for the existing slashHeader/slashEnabled keys, and the
    main @/i18n/index t (aliased as tMain) is added for the two new
    strings.

zh-CN translations included for all ~22 new keys.

Test plan: full suite 2301 pass, tsc + biome clean.
2026-05-08 20:14:24 +08:00
YHH 0990491584 i18n(app): localize ~26 user-facing strings in App.tsx (#447)
Two patterns rolled into one PR:

1. Wire seven existing ui.* keys that had been defined in EN.ts /
   zh-CN.ts but never actually called: ephemeralSession,
   resumedSession, newSession, restoredEdits, resumedPlan,
   tipEditBindings, dashboardAutoStartFailed. The keys had drifted
   into dead code — same pattern that bit the loop.* namespace
   before #445.

2. New app.* namespace (~24 keys) covering every other hardcoded
   user-facing string in App.tsx:
   - walk cancel (with / without remaining count)
   - edit-mode cycle (review / auto / yolo)
   - reject / auto-approve / flip-to-auto messages
   - dashboard stopped, /restore code-mode-only
   - hash-memory note (with translated scope + verb)
   - bash-mode + memory-write failures
   - hook headers (UserPromptSubmit, Stop)
   - @mentions / @url expansion + failure
   - shell confirm (deny / always-allow / running / starting)
   - checkpoint saved
   - plan continue / stop / revise

zh-CN translations for all 31 new keys.

Test plan: full suite 2301 pass, tsc + biome clean.
2026-05-08 20:01:27 +08:00
YHH 40628d0025 i18n(hooks/summary): localize hook outcome and force-summary text (#446)
Two small follow-on batches after #445:

1. hooks.formatHookOutcomeMessage — was hardcoded
   \`hook \${tag} \\`\${cmd}\\` \${decision}\${truncTag}\`. Pulls
   the structural words (\"hook\", decision verb, \" (output truncated
   at 256KB)\") into a new \`hooks.*\` namespace. The technical bits
   (tag, cmd) stay verbatim — they're identifiers, not prose.

2. loop/force-summary.ts — three user-visible strings:
   - \"summarizing what was gathered…\" (status during summary call)
   - the fallback when the model emits hallucinated tool-call markup
     instead of prose
   - the error template when the fallback summary itself crashes

New \`summary.*\` namespace covers all three. zh-CN translations included.

Decision verbs (block / warn / timeout / error) are translated via a
small \`hooks.decision\${Capitalize}\` lookup so the formatter still
takes \`outcome.decision\` (the typed enum) as input.

Test plan: full suite 2301 pass; tsc + biome clean.
2026-05-08 19:50:23 +08:00
YHH 346bb35cb8 i18n(loop): localize 14 user-facing yields in step() (#445)
Yields like 'session budget exhausted', 'aborted at iter X/Y',
'preflight: request ~X/Y tokens', and the post-turn fold/forcing-
summary status lines were all hardcoded English. The loop.* i18n
namespace had 7 keys defined but never wired — placeholders from a
previous attempt that drifted away from the actual call sites.

This PR replaces the dead namespace with 20 keys that match the
actual yield shapes, wires t() at every site, and adds zh-CN
translations.

Categories covered:
  - budget (exhausted / 80% warning)
  - /pro armed
  - aborted-at-iter / tool-budget-warning
  - preflight (status + folded / no-fold-left)
  - escalation (flash → pro / auto-escalation)
  - storm-broken (stuck retry loop / suppressed-N-times)
  - history compaction (status + folded / aggressively-folded)
  - forcing summary (context-guard exit)

Behavior preserved: tests pin runtime to EN, so existing assertions
on the English text still pass. The dead loop.* keys (budgetWarning,
budgetRefusal, contextWarning, escalationWarning, toolFailure,
interrupted, loopStopped) had zero callers across src/ and tests/
and are removed as part of the namespace cleanup.
2026-05-08 19:38:39 +08:00
YHH 97a93cf4f5 i18n(loop/errors): localize DeepSeek error messages (#444)
formatLoopError, reasonPrefixFor, and errorLabelFor were all
hardcoded English. A Chinese user hitting a 503 / 401 / context
overflow saw raw English (and on top of that, the new 5xx outage
notice from #440 was also English).

Move the strings to a new errors.* i18n namespace covering:
  - context overflow (with V4/legacy limit mention)
  - 401 auth / 402 balance / 422 param / 400 bad request
  - 5xx head + reachable / unreachable / two action variants
  - reason prefix and label for budget/aborted/context-guard/stuck
  - "(no message)" fallback for empty error bodies

zh-CN translations included. Existing tests still cover EN (vitest
setupFile pins runtime to EN); two new tests flip to zh-CN to confirm
runtime switch actually translates.

Stacked on #440 — merge that first.
2026-05-08 19:28:18 +08:00
YHH d837ddaf43 fix(loop): friendly DeepSeek 5xx error with reachability probe (#440)
* fix(loop): friendly DeepSeek 5xx error with reachability probe

Raw `DeepSeek 503: <body>` was bubbling straight to the UI. Users on
flaky DS days couldn't tell if it was DS-side (their service was
overloaded) or Reasonix-side (we crashed). The header comment in
loop/errors.ts even claimed retry.ts swallowed all 5xx — but retry.ts
returns the last response instead of swallowing, so 5xx did reach the
formatter and just fell through to a passthrough branch.

Now formatLoopError takes an optional probe result. The catch in
step() detects 5xx, fires a 1.5s `/user/balance` probe, and passes
the result back. Three message variants:
  - no probe         → DS-side outage notice + retry hints
  - probe reachable  → "main API answered, /chat/completions failing"
  - probe down       → "DS unreachable from your network — check net"

All three include "this is a DeepSeek-side problem, not Reasonix" and
a status-page link so users know where to look.

* test: avoid CodeQL js/regex/missing-regexp-anchor on URL substring match

Use toContain('status.deepseek.com') instead of /status\.deepseek\.com/
— same assertion semantics, dodges CodeQL's high-severity false positive
on unanchored URL regex.
2026-05-08 19:22:58 +08:00
YHH c56cd9d9a0 i18n(dashboard): translate the plan 'idle' status pill (#443)
Plans whose completionRatio is 0 (submitted but no steps marked
complete yet) showed a hardcoded English "idle" pill — surrounding
"active" / "done" pills already used t().

Add plans.idle to en.ts ("idle") and zh-CN.ts ("未开始"), and route
the idle branch of statusPill() through t().
2026-05-08 19:22:21 +08:00
YHH db194cb833 feat(wizard): first-launch language picker + i18n the wizard (#442)
Two related fixes for non-English first-runs:

1. Add a language step at the very start of the setup wizard.
   Cursor defaults to detectSystemLanguage() result. Selection saves
   immediately, so all later wizard steps render in the chosen
   language. Re-runs (`reasonix setup`) start there too — cursor
   defaults to currently saved language so Enter is a no-op for
   users who don't want to change it.

2. Localize every hardcoded string in the wizard via a new wizard.*
   i18n namespace (~30 keys, EN + zh-CN). Previously a Chinese user
   who hit /language partway through never saw zh-CN copy because
   the wizard rendered raw English. Now language → applies → review
   step renders in zh-CN.

Why this matters: Intl.DateTimeFormat().resolvedOptions().locale
isn't always correct (terminal env strips LANG, CI returns "C", etc.),
and the prior workflow only let users discover /language *after*
finishing setup in English.

Tests: ink-testing-library renders the Wizard and confirms the
language step is shown first with both options visible, in EN and
zh-CN. wizard.test.ts → wizard.test.tsx (now contains JSX).
2026-05-08 19:22:17 +08:00
YHH d817f1b965 docs(dashboard): PARITY.md audit — bucket E of #369 (#439)
Closing audit of the #369 split: every slash command tagged with how
the dashboard handles it (panel / chat-box / tui-only).

Findings after C + D:

* ~20 slashes have a dedicated panel or modal — Settings (presets,
  effort, model, /pro, budget gauge, loop control, language), MCP,
  Permissions, Hooks, Skills, Memory, Plans, Sessions, Usage, plus
  the C-bucket pickers (SessionPicker, CheckpointPicker, MCP
  marketplace, plan replay viewer).
* ~38 slashes work as-is via the chat box — short text outputs
  (/help, /keys, /status, /cost, /context, /think, /retry, /compact,
  /update, /doctor, /init, /semantic, …) plus admin / code-mode
  niches (/walk-around, /resource, /prompt, …). No structured-output
  gaps remain after C + D — the long-standing Memory / Permissions /
  Hooks / Skills / Plans / Usage panels already cover every command
  whose payload warranted a dedicated UI.
* Stays TUI-only by design: /exit (no live process to kill from web),
  the raw keyboard shortcuts (Esc / Shift+Tab / Ctrl-L / Ctrl-O / u
  / space).

Bucket A and B turned out empty after the C/D work — no commands
need a chat-box rendering tweak, and no commands need a new
structured-output panel. PARITY.md is the source of truth going
forward; add a row when a new slash lands.

This wraps up #369 — the umbrella issue closes with this PR.
2026-05-08 18:39:40 +08:00
YHH 9ea76a3ef9 feat(dashboard): loop control panel — start / stop / countdown (#433) (#438)
Final stage of #428. Adds a Loop section to SettingsPanel for the
auto-resubmit timer.

Design — two states from one component:

* Idle → 6 quick interval buttons (30s / 1m / 5m / 15m / 1h / 6h) plus
  a custom field with s/m/h unit selector, a multi-line prompt
  textarea, and a Start button. Cost hint reads "each iteration costs
  ~$X.XXXX (last turn)" pulled from /api/overview stats so the user
  knows what an unattended overnight loop will run.
* Running → live countdown ("fires in 1m 24s"), iter counter, the
  prompt verbatim (max 120px scroll for long prompts), and a Stop
  button.

Implementation:

* dashboard/src/lib/loop-control.ts — pure helpers: INTERVAL_PRESETS_MS
  table, parseCustomInterval (s/m/h → ms with 5s..6h clamp),
  formatRemaining (5m 12s / 2h 45m / 0s for races past zero).
* SettingsPanel polls /api/loop/status every 5s; a separate 1s tick
  interpolates the countdown locally between syncs (clamps to 0 if
  the next-fire moment passes between polls).
* Page-reload mid-loop reads /api/loop/status and re-renders the
  running panel from server state — no double-start risk because the
  Start button only renders in idle state.

Wraps up bucket D — all four targeted slashes (/pro, /budget, /model,
/loop) are now panel-driven.
2026-05-08 18:00:17 +08:00
YHH 136ed9ff58 feat(dashboard): editable model picker in settings (#432) (#437)
Fourth stage of #428. Replaces the read-only active-model code line
with a select driven by /api/models, plus an inline pricing line.

* New /api/models GET — returns the cached model catalog
  (string[] | null), the live current model, and the DEEPSEEK_PRICING
  table so the SPA can render input/output USD per 1M tok without a
  second source.
* DashboardContext.getModels callback; App.tsx ref-mirrors useSessionInfo's
  models so the dashboard server (frozen at boot time) sees fresh
  catalog without re-mint.
* SettingsPanel ModelRow component: graceful fallback to the existing
  read-only display when the catalog is null/empty (network failure
  or in-flight). Live model is always selectable, even if the catalog
  hasn't echoed it yet (preset overrides, custom IDs).
* Save flows through the existing D-1 applyModelLive path — same as
  /model <id> slash.

Closes #432
2026-05-08 17:56:18 +08:00
YHH 5dbcd1b73b feat(dashboard): budget gauge + cockpit tile (#431) (#436)
Third stage of #428. Replaces a typed-input form with a state-driven
budget gauge that reads at a glance and turns the common bumps into
single clicks.

Design:

* Off → quick-cap row ($1 / $5 / $10 / $25 / $50) + custom field. No
  number to type for the common case.
* Running (<80%) → spend / cap progress bar + bump suggestions
  (1.5× / 2× / 4× current cap, snapped to a "nice" round number per
  size bucket) + Clear.
* Approaching (≥80%) → amber tone + "loop will refuse past 100%" line
  + bump suggestions promoted to primary buttons.
* Exhausted (≥100%) → red tone + "next turn refused" line + same
  bumps.

Implementation:

* dashboard/src/lib/budget.ts — pure helpers: BudgetState union,
  deriveBudgetState, bumpSuggestions, budgetTone, QUICK_CAPS_USD.
  niceUp() subtracts an FP epsilon before ceil so 0.4 × 1.5 doesn't
  bump 0.6 to 0.7.
* SettingsPanel: BudgetSection consumes derived state and renders
  off / running / warn / exhausted variants. Same gauge shape across
  all three live states (just colour + helper text differ).
* Overview cockpit: budgetKpi reuses deriveBudgetState + budgetTone
  so threshold logic lives in one place.
* /api/settings GET adds sessionSpendUsd from ctx.getStats so the
  panel renders without a second /overview round-trip.
* 12 new unit tests for the derivation and bump rounding.
2026-05-08 17:52:12 +08:00
YHH 447d1d7049 feat(dashboard): compute panel section — /pro one-shot (#430) (#435)
* feat(dashboard): server surface for /pro / /budget / /model / /loop (#429)

First stage of #428 (bucket-D of #369). Server-side plumbing for the
slash-only knobs the web should drive directly: /pro arming, /budget,
/model, and /loop. No SPA UI yet — D-2..D-5 each ship a panel section
against this surface.

* /api/settings GET exposes proNext / budgetUsd / model from live
  loop state alongside the existing persisted fields.
* /api/settings POST validates and routes each new field to the
  matching ctx.*Live callback. budgetUsd accepts null for "off".
* /api/loop/{status,start,stop} (new endpoint) drives the auto-resubmit
  timer the same way the /loop slash does. start enforces 5s..6h range
  and a non-empty prompt.
* DashboardContext gets matching callbacks: applyModelLive,
  setProNextLive, setBudgetUsdLive, getLoopRunStatus, startAutoLoop,
  stopAutoLoop.
* App.tsx wires each callback against existing live methods on
  CacheFirstLoop and the useLoopMode hook. No new state.

/harvest and /branch are deletion-bound features and are deliberately
out of scope here — see #428 follow-up.

Closes #429

* feat(dashboard): compute panel section — /pro one-shot (#430)

Second stage of #428. Adds a Compute section to SettingsPanel for the
/pro one-shot toggle.

* Single-row section under the existing Defaults block: button toggles
  arm / disarm — same path as the slash; auto-disarms after the next
  turn fires.
* Section header lives even with one row so D-4 (model picker) and any
  future compute knobs cluster here naturally.
* i18n: en + zh-CN strings for the section + row + helper note.

/harvest and /branch were originally bundled into this stage but
dropped — both are deletion-bound features.

Closes #430
2026-05-08 17:47:05 +08:00
YHH 042d2c4f6a feat(dashboard): server surface for /pro / /budget / /model / /loop (#429) (#434)
First stage of #428 (bucket-D of #369). Server-side plumbing for the
slash-only knobs the web should drive directly: /pro arming, /budget,
/model, and /loop. No SPA UI yet — D-2..D-5 each ship a panel section
against this surface.

* /api/settings GET exposes proNext / budgetUsd / model from live
  loop state alongside the existing persisted fields.
* /api/settings POST validates and routes each new field to the
  matching ctx.*Live callback. budgetUsd accepts null for "off".
* /api/loop/{status,start,stop} (new endpoint) drives the auto-resubmit
  timer the same way the /loop slash does. start enforces 5s..6h range
  and a non-empty prompt.
* DashboardContext gets matching callbacks: applyModelLive,
  setProNextLive, setBudgetUsdLive, getLoopRunStatus, startAutoLoop,
  stopAutoLoop.
* App.tsx wires each callback against existing live methods on
  CacheFirstLoop and the useLoopMode hook. No new state.

/harvest and /branch are deletion-bound features and are deliberately
out of scope here — see #428 follow-up.

Closes #429
2026-05-08 17:46:31 +08:00
YHH f8143f7098 feat(dashboard): viewer modal kind for /replay (#421) (#427)
Final stage of #416. /replay [N] now broadcasts a read-only viewer
modal to the web dashboard so the plan archive (summary + steps +
markdown body) is visible alongside the existing TUI scrollback card.

* New `viewer` member on the ActiveModal discriminated union — sibling
  to `picker`, but read-only: only `close` flows back through
  /api/modal/resolve. Splitting them keeps the picker schema clean
  rather than carrying empty `actions: []` on every viewer payload.
* useViewerBroadcast helper alongside usePickerBroadcast.
* App.tsx intercepts result.replayPlan, packages a snapshot
  (title with #idx/total · relative time, structured steps with
  done/queued status, markdown body, archive basename as meta), and
  feeds it to the hook. The existing log.showPlan call is unchanged
  so the TUI scrollback card still renders.
* SPA ViewerModal renders the steps as a list (✓ for done, · for
  queued) plus the markdown body and a single Close button.
* Server tests cover the dispatcher: close happy path, rejection of
  non-close actions, 503 when the resolver is not wired.

Wraps up bucket-C of #369. All five originally TUI-only pickers
(/resume, /restore, /mcp browse) plus the read-only /replay viewer
are now drivable from the web with no TUI keyboard required.
2026-05-08 13:33:33 +08:00
YHH 6fcf3a6cba feat(dashboard): wire McpMarketplace through picker protocol (#420) (#426)
* feat(dashboard): picker modal kind for web parity (#417)

First stage of #416 (bucket-C of #369). Lays the protocol primitives so
the five existing TUI-only pickers (SessionPicker, MCP marketplace,
checkpoint restore, plan replay, edit walkthrough) can be driven from
the web in C-2..C-5 without redoing transport work.

* New `picker` member on the `ActiveModal` discriminated union plus
  `PickerResolution` / `PickerAction` / `PickerItem` types.
* `POST /api/modal/resolve` dispatches `picker` actions: pick / delete /
  rename / new / install / uninstall / load-more / refine / cancel.
  `refine` and `load-more` keep the picker open so the TUI's filter
  state stays in lockstep across surfaces.
* Generic `PickerModal` SPA component with filter input, scrollable
  rows, action buttons gated on `modal.actions`, and rename / new
  inline forms.
* `usePickerBroadcast` hook + App.tsx-owned resolver / snapshot refs so
  C-2..C-5 picker components only need the hook to participate.

No picker is migrated yet — that arrives in C-2 (#418).

* feat(dashboard): wire SessionPicker through picker modal protocol (#418)

Second stage of #416. SessionPicker (the simplest existing TUI picker —
no pagination, no async, ~5 actions) now broadcasts modal-up snapshots
to the web dashboard and resolves pick / delete / rename / new / cancel
from /api/modal/resolve.

* SessionPicker.tsx accepts an optional `pickerPorts` prop bundle and
  feeds usePickerBroadcast a snapshot mapped from the existing sessions
  list (id=name, badge=branch, meta=turns/cost).
* App.tsx wires a memoized pickerPorts (broadcast + resolver/snapshot
  refs from C-1) and passes it to the picker mount.
* TUI keystroke handling unchanged — broadcast is purely additive.

Validates the C-1 (#417) protocol foundation against a real picker with
no dashboard-side regressions.

* feat(dashboard): checkpoint picker for /restore (#419)

Third stage of #416. Bare /restore (no name argument) now opens an
interactive CheckpointPicker — covering both the TUI side (the command
was text-only before) and the web dashboard via the picker modal
protocol from C-1.

* New CheckpointPicker.tsx mirrors SessionPicker shape: arrow-key
  navigation, ⏎ to restore, [d] to forget, esc to quit. Rows show
  short id + name + relative age + file count / size.
* /restore handler returns openCheckpointPicker:true when called with
  no argument; /restore <name|id> still resolves directly to keep the
  one-shot path working.
* App.tsx mounts the picker, gates hotkeys behind it, and routes
  outcome → restoreCheckpoint / deleteCheckpoint with a summary line
  on success.
* usePickerBroadcast wires the same modal-up/down + resolvePicker
  pipeline as C-2; web sees pick / delete / cancel actions.

* feat(dashboard): wire McpMarketplace through picker protocol (#420)

Fourth stage of #416. /mcp browse now broadcasts a picker snapshot to
the web dashboard with installed/source-tagged badges, popularity
meta, and the full action set: install / uninstall / refine /
load-more / cancel.

* installOrToggle split into doInstall + doUninstall so the web's
  explicit `install` / `uninstall` actions don't accidentally toggle
  on the wrong button (TUI Enter still toggles for keyboard
  ergonomics).
* Snapshot builder extracted to a pure
  `buildMarketplacePickerSnapshot` so the entry-to-item mapping can
  be unit-tested without mounting Ink + the registry network call.
* refine and load-more keep the picker open (per C-1 design); cancel
  closes it via the existing onClose hook.
* hasMore wired from `state.handle.cache.pagination.nextCursor` so
  the dashboard's "Load more" button only shows when more pages exist.
* McpHub forwards pickerPorts from App.tsx to the marketplace tab;
  the live tab is unchanged.
2026-05-08 13:19:39 +08:00
YHH 1934e2598c feat(dashboard): checkpoint picker for /restore (#419) (#425)
* feat(dashboard): picker modal kind for web parity (#417)

First stage of #416 (bucket-C of #369). Lays the protocol primitives so
the five existing TUI-only pickers (SessionPicker, MCP marketplace,
checkpoint restore, plan replay, edit walkthrough) can be driven from
the web in C-2..C-5 without redoing transport work.

* New `picker` member on the `ActiveModal` discriminated union plus
  `PickerResolution` / `PickerAction` / `PickerItem` types.
* `POST /api/modal/resolve` dispatches `picker` actions: pick / delete /
  rename / new / install / uninstall / load-more / refine / cancel.
  `refine` and `load-more` keep the picker open so the TUI's filter
  state stays in lockstep across surfaces.
* Generic `PickerModal` SPA component with filter input, scrollable
  rows, action buttons gated on `modal.actions`, and rename / new
  inline forms.
* `usePickerBroadcast` hook + App.tsx-owned resolver / snapshot refs so
  C-2..C-5 picker components only need the hook to participate.

No picker is migrated yet — that arrives in C-2 (#418).

* feat(dashboard): wire SessionPicker through picker modal protocol (#418)

Second stage of #416. SessionPicker (the simplest existing TUI picker —
no pagination, no async, ~5 actions) now broadcasts modal-up snapshots
to the web dashboard and resolves pick / delete / rename / new / cancel
from /api/modal/resolve.

* SessionPicker.tsx accepts an optional `pickerPorts` prop bundle and
  feeds usePickerBroadcast a snapshot mapped from the existing sessions
  list (id=name, badge=branch, meta=turns/cost).
* App.tsx wires a memoized pickerPorts (broadcast + resolver/snapshot
  refs from C-1) and passes it to the picker mount.
* TUI keystroke handling unchanged — broadcast is purely additive.

Validates the C-1 (#417) protocol foundation against a real picker with
no dashboard-side regressions.

* feat(dashboard): checkpoint picker for /restore (#419)

Third stage of #416. Bare /restore (no name argument) now opens an
interactive CheckpointPicker — covering both the TUI side (the command
was text-only before) and the web dashboard via the picker modal
protocol from C-1.

* New CheckpointPicker.tsx mirrors SessionPicker shape: arrow-key
  navigation, ⏎ to restore, [d] to forget, esc to quit. Rows show
  short id + name + relative age + file count / size.
* /restore handler returns openCheckpointPicker:true when called with
  no argument; /restore <name|id> still resolves directly to keep the
  one-shot path working.
* App.tsx mounts the picker, gates hotkeys behind it, and routes
  outcome → restoreCheckpoint / deleteCheckpoint with a summary line
  on success.
* usePickerBroadcast wires the same modal-up/down + resolvePicker
  pipeline as C-2; web sees pick / delete / cancel actions.
2026-05-08 13:19:12 +08:00
YHH 03804e6170 feat(dashboard): wire SessionPicker through picker modal protocol (#418) (#423)
* feat(dashboard): picker modal kind for web parity (#417)

First stage of #416 (bucket-C of #369). Lays the protocol primitives so
the five existing TUI-only pickers (SessionPicker, MCP marketplace,
checkpoint restore, plan replay, edit walkthrough) can be driven from
the web in C-2..C-5 without redoing transport work.

* New `picker` member on the `ActiveModal` discriminated union plus
  `PickerResolution` / `PickerAction` / `PickerItem` types.
* `POST /api/modal/resolve` dispatches `picker` actions: pick / delete /
  rename / new / install / uninstall / load-more / refine / cancel.
  `refine` and `load-more` keep the picker open so the TUI's filter
  state stays in lockstep across surfaces.
* Generic `PickerModal` SPA component with filter input, scrollable
  rows, action buttons gated on `modal.actions`, and rename / new
  inline forms.
* `usePickerBroadcast` hook + App.tsx-owned resolver / snapshot refs so
  C-2..C-5 picker components only need the hook to participate.

No picker is migrated yet — that arrives in C-2 (#418).

* feat(dashboard): wire SessionPicker through picker modal protocol (#418)

Second stage of #416. SessionPicker (the simplest existing TUI picker —
no pagination, no async, ~5 actions) now broadcasts modal-up snapshots
to the web dashboard and resolves pick / delete / rename / new / cancel
from /api/modal/resolve.

* SessionPicker.tsx accepts an optional `pickerPorts` prop bundle and
  feeds usePickerBroadcast a snapshot mapped from the existing sessions
  list (id=name, badge=branch, meta=turns/cost).
* App.tsx wires a memoized pickerPorts (broadcast + resolver/snapshot
  refs from C-1) and passes it to the picker mount.
* TUI keystroke handling unchanged — broadcast is purely additive.

Validates the C-1 (#417) protocol foundation against a real picker with
no dashboard-side regressions.
2026-05-08 13:18:46 +08:00
YHH b3f0aee657 feat(dashboard): picker modal kind for web parity (#417) (#422)
First stage of #416 (bucket-C of #369). Lays the protocol primitives so
the five existing TUI-only pickers (SessionPicker, MCP marketplace,
checkpoint restore, plan replay, edit walkthrough) can be driven from
the web in C-2..C-5 without redoing transport work.

* New `picker` member on the `ActiveModal` discriminated union plus
  `PickerResolution` / `PickerAction` / `PickerItem` types.
* `POST /api/modal/resolve` dispatches `picker` actions: pick / delete /
  rename / new / install / uninstall / load-more / refine / cancel.
  `refine` and `load-more` keep the picker open so the TUI's filter
  state stays in lockstep across surfaces.
* Generic `PickerModal` SPA component with filter input, scrollable
  rows, action buttons gated on `modal.actions`, and rename / new
  inline forms.
* `usePickerBroadcast` hook + App.tsx-owned resolver / snapshot refs so
  C-2..C-5 picker components only need the hook to participate.

No picker is migrated yet — that arrives in C-2 (#418).
2026-05-08 13:17:58 +08:00
YHH 1ffa27975c docs(issues): split off display/rendering template, collect terminal host (#412) (#413)
Flicker reports keep landing without the one piece of info that
discriminates the bug — the terminal host (VSCode/Cursor xterm.js vs
standalone Windows Terminal / iTerm2 / etc.). The shell field on the
generic bug template was the wrong axis. New template asks for host +
version, env vars (TERM_PROGRAM/VSCODE_INJECTION/WT_SESSION), and ships
copy-paste diagnostic snippets so users do not have to know how to
introspect their own terminal.
2026-05-08 10:18:01 +08:00
YHH d63509ad85 refactor(ui): quiet chat-screen chrome (#411)
Two stacked rules + five-segment status row + per-card breathing room
made history scroll read as scattered fragments. Tighten three things:

- Settled cards drop the marginTop the active form keeps, so scrollback
  collapses to flat lines instead of one blank between every card.
- ModeStatusBar drops its dashed rule; StatusRow's solid rule already
  separates the chat from bottom chrome.
- StatusRow drops session-cost + wallet segments (StatsPanel and
  UsageCard already surface those); only turn cost + cache stay.
- Settled CardHeader filters faint string meta (1.2KB / 2.34s / exit N
  on OK cards) and drops the right slot so spinners don't linger in
  scrollback. Colored badges (rejected, retry) still render.

ui-status-row-balance reduced to the cells StatusRow now renders;
wallet/session currency coverage stays in ui-stats-panel-currency
and ui-usage-card-balance.
2026-05-08 09:45:50 +08:00
YHH 459a370b7c docs(readme): canonical install + subcommand cheatsheet (#408) (#409)
The Install block dropped readers at `npx reasonix code` with no
mention of the global-install path, and the README never named the
five subcommands a new user actually has to choose from. The website
already has a CLI panel but the section had no anchor, so the README
couldn't link to it.

- Name `npx` as the recommended path; point users at `reasonix update`
  if they want the global install.
- Add a five-row cheatsheet (code / chat / run / doctor / update) so
  newcomers don't have to guess. Defer the long tail (replay / diff /
  events / stats / index / mcp / prune-sessions) to `--help` and the
  CLI panel on the website.
- Mirror in zh-CN.
- Add `id="cli"` to the website's CLI section so the README link
  resolves.
2026-05-08 09:11:08 +08:00
Wesley Viana 39e69c2cab chore: improve loop.ts tests (#271)
* chore: improve loop.ts tests

* undo uncessary - change

* drive auto-escalation tests through step() instead of private-field access
2026-05-08 08:52:55 +08:00
ctharveyandCharles H 0d89ab84ef test(mcp): cover startup summary states (#396)
Co-authored-by: Charles H <[email protected]>
2026-05-08 08:43:47 +08:00
YHH ecb1bfb051 fix(prompt): inline short single-line pastes verbatim (#397) (#406)
Bracketed-paste content was always converted to a `[paste #N · …]`
sentinel chip, even when the user pasted a single word or a number.
That made the composer feel hostile to common one-shot paste usage —
copying an identifier or a URL out of another window and dropping it
mid-sentence shouldn't leave a chip in the buffer.

Inline the content verbatim when it has no newline AND fits under
INLINE_PASTE_THRESHOLD (200 chars); fall back to the sentinel chip
for anything longer or multi-line. The model still receives the full
paste text either way — this is display-only.
2026-05-08 08:40:34 +08:00
YHH db2ca97eb0 fix(permissions): match Windows project keys case-insensitively (#402) (#405)
projects[] is keyed by absolute rootDir, so on Windows two sessions
that resolve the same physical directory to different drive-letter or
component casing (PowerShell's `F:\Reasonix` vs bash/MINGW's
`f:\reasonix`) miss the persisted "always allow" entry from the prior
session and re-prompt every turn.

Add findProjectKey() that prefers the exact match and, on win32,
falls back to a case-insensitive scan. Use it in load / add / remove
/ clear so any-cased rootDir consolidates onto the existing key
instead of forking a duplicate. Non-Windows lookups remain
case-sensitive — Linux paths really are.
2026-05-08 08:40:15 +08:00
YHH 47f207119f fix(ui): refresh model badge on dashboard preset change and /pro turns (#403) (#404)
Two paths bypassed the cards' model snapshot:
- Dashboard preset change (POST /settings → applyPresetLive) reconfigured
  the loop but never dispatched session.model.change, so subsequent
  reasoning/streaming cards still rendered the old model badge.
- /pro consumed a single-turn escalation without telling the cards, so
  the armed turn ran on v4-pro but the badge stayed on the base model.

applyPresetLive now dispatches session.model.change. reasoning.start /
streaming.start carry an optional model id; the loop's currentCallModel
getter feeds it through TurnTranslator.flushBuffers so the badge tracks
the model that actually produced the output.
2026-05-08 08:39:51 +08:00
ctharveyandCharles H 6ccca2be0b fix(search): honor abort during recursive fs scans (#400)
Co-authored-by: Charles H <[email protected]>
2026-05-08 08:14:54 +08:00
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
esengine 7526167d32 fix(setup): replace ink-text-input with MaskedInput, strip leaked paste markers
Two bugs in the Setup screen on Windows / cell-diff renderer:

1. ink-text-input bakes chalk-styled output into the text it returns.
   Our renderer strips the ESC byte but keeps the rest, so users saw
   literal `[7ms[27m[90mk-...[39m` in the input field. MaskedInput uses
   the renderer's <Text inverse> / <Text dimColor> primitives instead.

2. Windows ConPTY splits bracketed-paste wrappers across stdin chunks,
   so Ink's parser sees `\x1b[200~` / `\x1b[201~` as printable `[`,
   `2`, `0`, `0`, `~` and they leak into the buffer. Strip them at
   the input boundary and again at submit.

Also fixes a stale-closure bug where rapid keystrokes from a paste
burst all read the initial empty value, so only the last char survived.
A ref synced on every render lets each keystroke append onto the
latest accumulated value.
2026-05-04 09:55:43 -07:00
esengine 32126dece4 release: 0.25.0 — plan auto-execution, kill flicker root cause, prune demos
Plan execution is continuous after approval — `mark_step_complete` no
longer throws PlanCheckpointError; the model runs all steps in one turn.
Plan card commits to scrollback as the approved snapshot AND renders as
a fixed-height live strip (PlanLiveRow) docked above prompt input via
the windowed-5 step view.

Flicker root cause was orphan unsettled cards (aborted streams that
never fired their .end event) trapping every subsequent card in the
live region — Yoga re-measured the whole live tree on every chunk.
CardStream now allows only the LAST card to be live; earlier orphans
are force-committed to scrollback.

Streaming cards switch to a left ▎ stripe (Card.tsx). Round borders'
top/bottom rows orphaned under the cell-diff renderer's row-promotion
logic when content height changed mid-stream. Stripe rows always carry
both ▎ and content, so promotion is always atomic.

Active-tone color set (TONE_ACTIVE) lifts streaming/running cards one
shade brighter; settled tones unchanged. DiffCard tone bug fixed
(was warn, registry says ok). PlanCard wraps any plan length to a
fixed 5-step window with `✓ ⋯ N done` / `⋯ N upcoming` elision.

API surface: PlanCheckpointError + PlanCheckpointConfirm removed.
mark_step_complete returns the step_completed payload directly.
/stop slash command added (typed alternative to Esc abort).

Cleanup: removed all 7 demo CLI commands (banner / card / flicker /
preview / renderer / select / stress) and their 5 test files. They
duplicated production card components and drifted out of sync.
2026-05-04 09:29:48 -07:00
ctharvey 73000ce388 refactor(mcp): hide host client reads from browse UI (#227)
Refs #196.
2026-05-04 08:55:46 -07:00
ctharvey c86279a493 refactor(mcp): extract healthBadge to mcp-health.ts (#226)
Refs #196.
2026-05-04 08:54:14 -07:00
ctharvey fbcd82096c refactor(mcp): extract healthBadge to mcp-health.ts (#226)
Refs #196.
2026-05-04 08:51:37 -07:00
esengine 37b4cca4f6 refactor(ui): SubagentRow uses Card+CardHeader; drop CardRenderer's marginTop
Two related fixes:

1. SubagentRow was a hand-rolled 9-row block with ▎ left bar drawn on
   every row. User reported it didn't match the rest of the card pass —
   because it predates the Card primitive entirely. Rewritten on top of
   <Card> with round border + violet tone + CardHeader (titleBg pill +
   model pill + spinner in `right`). Body collapses from the 9-row
   stack into 3 lines (task / last / phase) inside the card. Row count
   is still fixed (no per-event growth) so flicker behavior is preserved.

2. CardRenderer had marginTop=1 on its outer wrapper, doubling the
   marginTop=1 the Card primitive already adds. Every static-emitted
   card carried 2 leading blank rows, accumulating noticeable gaps in
   scrollback between cards. Drop CardRenderer's mt; Card primitive
   alone owns inter-card spacing.
2026-05-04 07:11:02 -07:00
esengine 3d692ead01 feat(cards): tinted reasoning title + model pill on reasoning/streaming + subagent demo-style children
Three card-header upgrades the user asked for:

1. CardHeader gains an optional `titleBg` that paints the title as a
   colored chip — used by ReasoningCard so `reasoning` reads as a
   muted-purple block instead of plain bold text. (Borrowed from
   PILL_SECTION.reason — already in the theme.)

2. ReasoningCard + StreamingCard surface the snapshotted `card.model`
   as a Pill in the header `right` slot. v4-flash / v4-pro / r1 each
   get their own color via PILL_MODEL.

3. SubAgentCard children now match card-demo's row format:
   ▎ [status spinner|✓|✖] [kind glyph] [summary]

   Previously the row only had the kind glyph + content; now per-child
   running cards spin a tone-colored circle while done ones get a green
   ✓. Header switches the meta from a static status text to "N running"
   when active, mirroring the demo's runningCount.
2026-05-04 06:57:43 -07:00
esengine a9024a8d31 refactor(ui): soften ThinkingRow — italic + dim instead of bold blue block
Original was bold brand-blue spinner + bold brand-blue text + faint
duration with hardcoded `· ` separators. All three fields competed for
attention even though the row is just a "model is busy" hint.

Restraint: drop bold from spinner + label, switch label color to FG.sub
italic (semantic "thinking" via type, not color), accent-purple spinner
for a slower visual pulse, gap={1} for spacing instead of inline `· `
chunks. Reads as one sentence instead of three competing pills.
2026-05-04 06:52:39 -07:00
esengine a8e7ebeb47 fix(renderer): keep promotedRows across resize so scrollback isn't duplicated
mount.ts resize() reset promotedRows=0, which made the next commit's
commitScrollback see split.skipped > promotedRows and serialize every
already-scrolled-out row a second time. Each terminal resize stacked
another full copy of the overflowed history into scrollback — visible
as duplicate chrome bars / mode bars climbing up the scroll buffer.

Promoted rows live in the terminal's own scrollback, which the renderer
can't access — so resetting our counter is structurally wrong. Keep
promotedRows; with pendingClear handling the visible repaint, the new
layout's skipped count drives an honest newPromote (often 0 on resize,
since the layout's overflow boundary moves by 1-2 rows max under width
change, not by the entire history).

Also dedup same-dimension resize events — terminals fire 2-3× per
drag and each fires a full commit otherwise.
2026-05-04 06:43:16 -07:00
esengine 88e5becf06 Revert "fix(cards): pin flexShrink=0 on Card so settled bodies aren't squashed"
This reverts commit 8685215e23.
2026-05-04 06:27:42 -07:00
esengine 8685215e23 fix(cards): pin flexShrink=0 on Card so settled bodies aren't squashed
In `npm run dev` real ink (not the cell-diff renderer) drives layout,
and yoga defaults flex-shrink to 1. When a settled card lands inside
real ink's <Static> column, the box can be shrunk to fit even though no
explicit height is bound — UserCard's Markdown body and ReasoningCard's
SettledPreview both collapsed to 0 rows while the headers survived.

flexShrink=0 on both active and settled wrappers anchors each card to
its content height. The streaming reply was unaffected because its body
alone is already taller than terminal/2 so shrink wouldn't fire.
2026-05-04 06:25:11 -07:00
esengine 7b108cc2c0 fix(cards): drop paddingLeft from settled Card so bodies render
Adding paddingLeft={2} to the settled-mode wrapper collapsed the layout
so card bodies (UserCard's Markdown, ReasoningCard's BodyLines, etc.)
rendered as 0 rows — only the headers were visible. Card-demo's
StaticRow doesn't apply outer padding either; it pads body sub-Boxes
individually, which is the pattern the live cards used pre-refactor.

Settled mode now mirrors the original outer wrapper shape exactly:
`<Box flexDirection="column" marginTop={1}>`. Bodies render. Active
mode keeps the round border + paddingX=1 + width="100%".
2026-05-04 06:11:01 -07:00
esengine 948f361849 fix(cards): propagate ActiveCardContext into Static's off-tree render
CardStream previously wrapped <Static> in an ActiveCardContext.Provider,
but Static emits its items via bridge.emitStatic which renders them in
an off-tree reconciler — context from the live tree doesn't travel.
Settled cards still rendered with active=true (default) and kept their
borders.

Move the Provider inside the Static children function so it captures
into the per-item subtree that emitStatic actually serializes. Live
path drops its (now redundant) Provider since Card primitive defaults
to active=true.
2026-05-04 06:01:09 -07:00
esengine d65eeddac6 fix(cards): drop border on settled cards + stretch active borders to full width
Two visual bugs after the e78112b border roll-out:

1. Settled cards (in scrollback) carried borders too, but card-demo only
   borders the live/active cards — settled rows in demo are flat history
   text. Live chat now mirrors that: ActiveCardContext threads
   active=false through CardStream's <Static> path, and Card primitive
   renders a paddingLeft=2 flat block when not active.

2. Active card width was content-fit, so a narrow reasoning card and a
   wide reply card had different border widths in the same column. Adds
   width="100%" so every active card stretches to the full available
   width and the column reads as a uniform stack.

Also resolves the "reply bottom border missing" symptom — settled reply
cards no longer have a border at all, so the question doesn't arise.
2026-05-04 05:53:40 -07:00
esengine e78112bf4f feat(cards): wrap 16 cards in round-border Card primitive — port the demo look to live chat
card-demo had a polished round-border + paddingX=1 wrapper around each
card, but the live chat path (src/cli/ui/cards/*.tsx) never adopted it,
so the demo and the actual chat looked completely different. New
primitive `Card({tone, children})` ports that wrapper to the real cards.

Refactored cards now flow through `<Card tone={...}>` with their content
flush left inside the border (paddingX=1 on the wrapper provides the gap;
removed the per-body `paddingLeft={2}` that would have stacked).

Border tone tracks status:
- ok / running / settled — TONE.ok / brand / accent
- error / warn / abort  — TONE.err / warn
- meta-info             — FG.meta (usage / memory)

LiveCard skipped — it's a one-line transient toast and a 3-row border
would defeat the point. CompactUsageRow path also stays flat.

DEC 2026 sync from 0.24.1 means the border resizing for streaming
content (reasoning/tool/streaming card body growing) lands atomically
per frame; no flicker layered on top of what we already had.
2026-05-04 05:44:00 -07:00
esengine 51a5f9dd8e refactor(cards): unify card header via CardHeader primitive — drop CardBox
Every card had been hand-rolling its first row with the same
Box/Text/gap=1 incantation, so spacing and color hierarchy drifted
between cards. New CardHeader primitive accepts (glyph, tone, title,
optional titleColor / subtitle / meta / right) and gives 12 cards a
single source of truth:

- glyph + bold title in tone color (titleColor overrides for demoted
  cards like usage/memory/user where the bold reads as muted FG.sub)
- subtitle in FG.body (e.g. tool args summary, search query, task
  title, subagent name)
- meta items prefixed with `·` separator, joined by ` · `, faint by
  default; colored MetaItem variant carries diff +/- counts and
  retry/rejected badges without inline JSX clutter
- right slot for ad-hoc inline elements (streaming/reasoning/tool
  spinners)

Drops CardBox — it had a ▎ left-bar API but no card actually wrapped in
it (grep returned zero call sites); the inline ▎ each card showed was
hardcoded, and the redesign has no leading bar at all.

Cards converted: User, Streaming, Reasoning, Tool, Task, Plan, Diff,
Usage, Memory, Search, Branch, SubAgent. 12 files, net -55 lines.

Zero flicker risk — pure single-row replacement, same column width per
field. No row count changes.
2026-05-04 05:30:34 -07:00
esengine b5fd33700e feat(cards): visual audit pass — disambiguate streaming/task, demote usage, branch+ctx+doctor enter token table
The CARD constant was the source of truth on paper but most cards
hardcoded glyphs in JSX, so the table drifted from what's rendered.
This pass aligns intent and fixes the worst clashes:

- streaming and task were both `▶` brand-blue and visually
  indistinguishable when both surfaced in the same turn. Streaming now
  paints `◈` (paired with reasoning's `◆` for the thinking→speaking
  arc); task keeps `▶` but moves to TONE.warn so "doing work" reads
  separately from "model replying".
- usage is a turn-end summary, not active output — header demoted to
  FG.meta; bars + balance keep brand for information density.
- doctor's fail glyph `✗` aligned to error's `✖` for consistency.
- branch in-progress was reusing CARD.streaming.color (brand-blue);
  branching is orchestration, paired with subagent under TONE.violet.
- ctx, doctor, branch were absent from CARD; added so future cards have
  a token to anchor against. (Existing cards still hardcode glyphs;
  consolidation is a follow-up.)

Zero row-count or column-width changes — every replacement is a
single-cell glyph. No flicker risk on top of 0.24.1's sync wrap.
2026-05-04 05:14:47 -07:00
esengine b24d2350ed release: 0.24.1 — DEC 2026 sync to suppress flicker + marked v15 2026-05-04 04:55:46 -07:00
esengine 9f8df4da6b fix(deps): bump marked to v15 — v12 pre-escapes inline text to HTML entities
Marked v12's tokenizer ran inline text through HTML escape (& → &amp;,
< → &lt;, " → &quot;), which is correct for HTML output but wrong for a
TUI — both the user-input echo and assistant markdown rendered the raw
entities. v15 keeps token.text literal and only escapes at the HTML
renderer layer, which matches our actual rendering path. Also avoids the
miswidth where a 1-cell `<` was measured as 4 cells (`&lt;`) and clipped
content past the wrap edge.
2026-05-04 04:49:47 -07:00
esengine 6e2e869aaa fix(renderer): wrap commit writes in DEC 2026 sync to suppress flicker
Commit/static/resize paths buffered bytes into one write but the terminal
could still paint the cleared-then-repainted intermediate state. Wrapping
each frame in BSU/ESU (\x1b[?2026h…l) lets supporting terminals (Windows
Terminal ≥1.18, iTerm2, Kitty, Wezterm, alacritty, foot) swap the frame
atomically; others ignore the unknown CSI. Also folds resize's screen
clear into the next commit so clear+repaint is one sync block.
2026-05-04 04:49:32 -07:00
esengine ff6edff2f6 0.24.0 2026-05-04 04:04:48 -07:00
YHH 213b4ec198 Merge pull request #224 from esengine/fix/inkcompat-stdout-flicker
feat(renderer): yoga + 17/17 card migration + UX overhaul (#160)
2026-05-04 03:41:49 -07:00
esengine 5b5ff09088 feat: WelcomeBanner redesign + plan reject reason + prompt cursor + App cleanup (#160)
Five small, related UX improvements riding the yoga + card-migration train:

WelcomeBanner — REASONIX × 🐋 DeepSeek brand row (cyan brand + violet accent
+ whale emoji), tagline, slash-command hints. Drops the hand-painted box-
drawing borders that broke under CJK fonts; uses borderStyle="round" with
yoga's alignItems="center" so layout is correct in any font.

PlanRefineInput — new "reject" mode (red ✗ tone, error palette). The plan-
confirm picker's cancel branch now opens this input so users can attach a
reason like approve / refine already do. Empty Enter = same cancel synthetic
as before; with text = synthetic includes the user's reason. Symmetric with
the "Tab to add reason" pattern on tool-deny.

PromptInput — call useCursor({visible:false}) so the renderer hides the OS
cursor. PromptInput paints its own ▌ block; without this, the OS cursor
showed at screen-bottom too, doubling up.

App.tsx cleanup — dropped 8 unused imports / destructured fields (ApplyResult,
archivePlanState, ReasoningEffort, saveReasoningEffort, writeClipboard,
renderFrame, COLOR, updateAvailable). Flattened currentRootDir to a state
without setter (no caller).

flicker-demo.tsx — committed the previously-untracked debug demo command
(referenced from src/cli/index.ts).
2026-05-04 03:38:17 -07:00
esengine a92b3c042a feat(cards): migrate remaining 9 cards to flat card-demo style (#160)
Finishes the card-stream migration (now 17/17 = 100%). Each card replaces
CardHeader + BarRow with a flat layout: a row Box for the header glyph +
title + faint metadata, and paddingLeft={2} child rows for the body.

Cards in this commit:
- DiffCard, SubAgentCard, UsageCard, MemoryCard
- SearchCard, LiveCard, CtxCard, BranchCard, DoctorCard

Visual: tighter, no left bar gutter, headers read like one line of status.
Behavior: identical — just different layout primitive.
2026-05-04 03:37:42 -07:00
esengine a5abd9ef94 chore: drop v2 prompt path + Ink-era card primitives (#160)
The chat-v2 / SimplePromptInput stack was the migration test bed for the
cell-diff renderer. With yoga + isPrimaryRenderer in place, the production
chat path on the v1 PromptInput is the only supported entry point, so v2
is now dead weight.

Card primitives (BarRow / CardHeader / Card.tsx / glyphs.ts) became
unreferenced once every card finished migrating to the flat card-demo
style — yoga handles the alignment they were emulating.

Removed:
- src/cli/commands/chat-v2.tsx, input-demo.tsx
- src/cli/ui/chat-v2-slash.ts, loop-bridge.ts, prompt-input-v2.tsx, use-prompt-history.ts
- src/cli/ui/cards/{Card.tsx,CardHeader.tsx,glyphs.ts}
- src/cli/ui/primitives/BarRow.tsx
- tests/renderer/{chat-v2,chat-v2-slash,loop-bridge,prompt-input-v2,use-prompt-history}.test.tsx
- chat-v2 / input-demo command registrations from src/cli/index.ts

Added: src/cli/ui/primitives/CursorBlock.tsx (the only piece of BarRow.tsx
still needed by ReasoningCard, lifted to its own file).
2026-05-04 03:37:15 -07:00
esengine 38867e5c92 feat(renderer): integrate yoga-layout as the flexbox engine (#160)
Replaces our hand-written column/row flex math with Meta's yoga-layout
(WASM, used by real Ink and most React-based TUIs). Layout is now full-spec
flexbox with alignItems/Self/Content, flexShrink/Basis, flexWrap, margin,
min/max, columnGap/rowGap, percent widths.

Why now: the old engine had no cross-axis alignment, so every "center this"
required a nested row+justifyContent hack. With yoga, components describe
intent directly; banner / modal / input layouts collapse to a fraction of
the markup.

Scope:
- Add yoga-layout 3.2.1 dep
- New src/renderer/layout/yoga-layout.ts adapter (LayoutNode -> YogaNode + measure func)
- Rewrite layout.ts: drop layoutBox/Column/Row/intrinsicWidth, walk yoga's
  computed positions to populate LayoutRows
- Extend BoxNode + RsxBox + inkCompat.Box prop surface with the new flex props
- BoxSizing.BorderBox; default flex-shrink=1 (CSS, not yoga's 0); root margins
  reflected in total render bounds
- isPrimaryRenderer=true: only React renderer in this process, so context-stack
  collisions on re-entrant updateContainer go away
- emitStatic via queueMicrotask + reset reservedRows after static bytes -
  fixes resume-path layout collision
- Pin Block Elements (U+2580..U+259F) to width=1 alongside Box Drawing
- Per-edge borderColor props now forwarded through inkCompat
- render-to-bytes header trimmed to satisfy comment-policy

Tests: 2187/2187 pass. Two existing border/padding tests updated for yoga's
content-row reservation behavior (more correct than the old engine).
2026-05-04 03:36:44 -07:00
ctharveyandCharles H 99754672af fix(mcp): close client on handshake failure; swallow kill() errors on Windows (#216)
When mcp.initialize() rejects (timeout, bad spec, etc.), the catch
blocks in chat.tsx and run.ts never called mcp.close() — the child
process leaked, readLoop kept running, and on Node 24 the orphaned
rejection fired as an unhandled rejection.

- Lift mcp declaration before try so it's accessible in catch
- Call mcp?.close().catch(() => undefined) in both catch blocks
  (guard prevents cleanup masking the original bootstrap failure)
- StdioTransport.close(): child.kill("SIGTERM") throws EINVAL on
  Windows; use platform-conditional signal and try/catch to swallow
  both EINVAL and failed-spawn errors

Co-authored-by: Charles H <[email protected]>
2026-05-03 23:34:41 -07:00
esengine d5c02bfae2 fix(renderer): atomic frame writes in mount commit paths (#160)
commitScrollback / commitVirtual / emitStatic all made up to four
sequential opts.write() calls per frame: clear-promote header, promoted
bytes, reserve-grow prelude, and the actual diff patches. Between
writes the terminal could flush, briefly showing blank rows where
content was about to be painted — visible as flicker when ChoiceConfirm
mounts on top of an actively-streaming card (each chunk + the modal
mount each emitting their own multi-write commit).

Now each commit buffers everything into one string and issues a single
opts.write at the end. One terminal flush per frame, no in-between
blank state.

This stacks on top of the previous useStdout fix; the two together
should land the modal-mount flicker.
2026-05-03 22:24:31 -07:00
esengine b140d1c1fb fix(renderer): inkCompat.useStdout returns stable proxy — eliminates modal-mount flicker (#160)
Root cause of the flicker user reported when ChoiceConfirm (and other
modals) appears while a streaming card is still writing:

`inkCompat.useStdout` was returning `{ stdout: { columns, rows } }`,
a fresh object literal on every render with no `.on/.off/.isTTY/.write`.
viewport-budget.tsx (the row allocator the modal claims rows from)
runs `useEffect([stdout])` to register a "resize" listener — every
render produced a new stdout reference, so the effect re-fired every
render. Inside the effect, `stdout.on("resize", ...)` threw because
`.on` was undefined; throw skipped cleanup; cleanup never landed; the
listener that should have detached on next render never did. The
re-fire + throw + dispatch dance manifested as the flicker.

Fix:

1. New `StdoutContext` carries the real NodeJS.WriteStream (passed in
   via mount({stdout})).
2. `useStdout()` now `useMemo`-s the returned wrapper on
   (viewport.columns, viewport.rows, real stdout). Stable identity →
   downstream `useEffect([stdout])` doesn't re-fire on benign renders.
3. The wrapper exposes viewport-driven `columns`/`rows` (so layout
   still reflects the renderer's mounted size, not the host terminal),
   plus `.on/.off/.write/.isTTY` proxied to the real WriteStream.
4. `inkCompat.render` threads `opts.stdout` through to mount() so the
   chain is wired end to end.

All existing tests still pass (the live-banner-via-shim narrow-viewport
test, useStdout viewport tests, etc.).
2026-05-03 22:16:24 -07:00
YHH 3b070dce9c feat(cards): migrate PlanCard + TaskCard (#160) (#220)
PlanCard:
- Header: ⊞ {title} · 3/7 done
- Step rows: glyph + numbered title; running step bold + ← in progress

TaskCard:
- Header: glyph + step N/M + title · elapsed · status
- Step rows: glyph + bold tool name + step title + detail + elapsed

Drops CardHeader / BarRow chrome; both adopt the same flat layout
established for the other cards.
2026-05-03 21:42:07 -07:00
YHH 08e5ddd1f0 feat(cards): migrate ToolCard to card-demo style (#160) (#219)
Drops CardHeader / BarRow / CardBox chrome. Header is one row:
status-glyph + bold tool name + faint args + retry / rejected badges +
faint meta trail (size · elapsed · exit-code).

Status glyphs:
- ▢ running (alongside ⠋ braille spinner)
- ✓ ok
- ✗ rejected
- ✖ error (exit ≠ 0)
- ⊘ aborted

Output preview indented 2; long output keeps the `⋮ N earlier lines`
elision. Exit-code-non-zero output stays in error red, OK output dims.
2026-05-03 21:42:03 -07:00
YHH c3ab3fcb52 feat(cards): migrate ReasoningCard + StreamingCard (#160) (#218)
* feat(cards): migrate ErrorCard + WarnCard to card-demo style (#160)

Drops CardHeader + BarRow primitives. Both cards collapse to the same
flat header-row + indented body pattern that UserCard adopted in #214.

Error retains its retry meta + truncated stack-trace block (unchanged
behavior, lighter visual chrome). Warn keeps the optional detail meta
on the header line.

* feat(cards): migrate ReasoningCard + StreamingCard (#160)

The two most-visible cards in every chat turn drop CardBox + Pill
chrome and adopt the card-demo glyph + bold-title pattern.

ReasoningCard:
- Streaming: ◇ reasoning… · 234 tok ⠋ + italic preview tail (4 lines)
- Settled:   ◆ reasoning · 234 tok · 3¶ · 2.1s + tail (2 lines) + elision
- Aborted:   ◇ reasoning (aborted) in red

StreamingCard:
- Streaming: ▸ writing… ⠋ + clipped preview tail (4 lines)
- Done:      ‹ reply + full markdown body
- Aborted:   ‹ aborted (red) + clipped tail + [truncated by esc]

Spinner stays — liveness signal during streaming is real UX value.
Pills + CardBox left-bar removed.
2026-05-03 21:41:59 -07:00
YHH 4556fb0f09 feat(cards): migrate ErrorCard + WarnCard to card-demo style (#160) (#217)
Drops CardHeader + BarRow primitives. Both cards collapse to the same
flat header-row + indented body pattern that UserCard adopted in #214.

Error retains its retry meta + truncated stack-trace block (unchanged
behavior, lighter visual chrome). Warn keeps the optional detail meta
on the header line.
2026-05-03 21:41:55 -07:00
YHH c80be26517 feat(cards): migrate UserCard to card-demo style (#160) (#214)
* chore(deps): drop ink from runtime dependencies (#160)

The CLI bundle now inlines ink + ink-text-input via tsup's noExternal +
alias chain, so neither package needs to ship at runtime. ink and
ink-text-input move to devDependencies (kept for source resolution
during build / test), and ink-spinner is dropped outright (only ever
referenced in a comment).

vitest gets the same ink → inkCompat alias as tsup so the test suite
runs through the same renderer shim production ships, removing the
last divergence between the two paths.

bundle-smoke already asserts no `from "ink"` literal survives in
dist/cli/; the noExternal extension to ink-text-input means the
bundle has zero `from "ink-text-input"` references too, so a future
regression that breaks either alias fails CI.

* feat(cards): migrate UserCard to card-demo style (#160)

Drops the CardBox left-bar wrapper. The new layout matches card-demo's
flat row aesthetic — accent ›, bold "you", faint relative-time meta,
followed by the user's markdown body indented under it. No more border
or marginLeft offset; cards align to the page's left margin.

This is the first card in the visual migration sweep. Pattern is:
* drop CardBox
* marginTop={1} between cards (was implicit via CardBox)
* header row: glyph + bold word + faint meta
* body indented paddingLeft={2}

Each remaining card (reasoning / streaming / tool / plan / ...) lands
in its own follow-up so before/after diffs stay reviewable.
2026-05-03 20:55:35 -07:00
YHH 252e1258bd chore(deps): drop ink from runtime dependencies (#160) (#213)
The CLI bundle now inlines ink + ink-text-input via tsup's noExternal +
alias chain, so neither package needs to ship at runtime. ink and
ink-text-input move to devDependencies (kept for source resolution
during build / test), and ink-spinner is dropped outright (only ever
referenced in a comment).

vitest gets the same ink → inkCompat alias as tsup so the test suite
runs through the same renderer shim production ships, removing the
last divergence between the two paths.

bundle-smoke already asserts no `from "ink"` literal survives in
dist/cli/; the noExternal extension to ink-text-input means the
bundle has zero `from "ink-text-input"` references too, so a future
regression that breaks either alias fails CI.
2026-05-03 20:55:31 -07:00
YHH 5bd2678d51 feat(build): tsup alias 'ink' → inkCompat — chat now runs on cell-diff (#160) (#212)
Adds an esbuild alias on the CLI bundle that resolves every `import …
from "ink"` to src/renderer/ink-compat. Combined with noExternal:
["ink"] this forces the bundle to inline the shim instead of leaving
"ink" as a runtime external. The 3496-line App.tsx and every UI file
that imports Box / Text / Static / useApp / useInput / useStdout /
render now flow through the cell-diff renderer with zero source
changes.

Library + dashboard bundles are unchanged — only the CLI alias.

bundle-smoke gains an assertion that no `from "ink"` literal survives
in dist/cli/, so a future regression that breaks the alias fails the
build pipeline. Doctor command runs end-to-end through the aliased
path; help / version / non-interactive subcommands work.

Tests still resolve the real "ink" package (vitest doesn't go through
tsup), so unit tests stay on the existing path; the bundle test is the
production-correctness check.
2026-05-03 19:32:09 -07:00
YHH f01f12d0ae feat(renderer): inkCompat.render — Ink-shaped runtime over the cell-diff renderer (#160) (#211)
New render(element, opts) → { rerender, unmount, waitUntilExit, cleanup,
clear } that mirrors Ink's render API while mounting through the
cell-diff renderer's mount(). Wires resize, Ctrl+C handling
(default-on, opt-out via exitOnCtrlC: false), and useApp().exit()
integration so existing Ink-shaped apps drop in cleanly.

Foundation for the next step: a tsup alias 'ink' → inkCompat that lets
the existing reasonix chat (and its full 3496-line App.tsx) render
through cell-diff without any source changes — replacing the parallel
chat-v2 rebuild track.

7 new tests cover initial mount, waitUntilExit gating, rerender,
Ctrl+C exit, exitOnCtrlC: false, useApp().exit(), and useInput wiring.
2026-05-03 19:20:55 -07:00
YHH b4b196ea3a feat(renderer): chat-v2 — slash commands (/help /clear /cost /new /exit) (#160) (#210)
handleSubmit detects a leading / and routes to a pure handler map in
src/cli/ui/chat-v2-slash.ts instead of running a turn. Each handler
returns events to dispatch (synthetic user + canned reply, or a
session.reset, or a live.show error) plus an optional exit flag.

/help renders the command list as a regular streaming card so the
markdown view picks up the formatting; /cost reads from agentStore
state and shows current usage; /clear and /new both fire session.reset
which the existing reducer already handles. Unknown commands surface
as an err live card with the offending name.

10 new tests (7 unit + 3 integration through the chat-v2 shell).
2026-05-03 19:16:13 -07:00
YHH ada301ffce feat(renderer): chat-v2 — session persistence + resume (#160) (#209)
runChatV2 accepts session / forceNew / forceResume options; resolveSession
picks the actual name (timestamp suffix on --new, latest prefix on
--resume); CacheFirstLoop({session}) handles persistence so the running
transcript carries across launches.

Resumed sessions replay user-side history as user cards on mount via
AgentStoreProvider's initialCards seed. Assistant content isn't replayed
(no event log on disk yet); fresh turns stream into place.

CLI: `reasonix chat-v2 --session foo` resumes; `--new` forks a fresh
suffix; `--resume` walks to the latest matching prefix. Header shows
the resolved session name when one is active.
2026-05-03 18:54:00 -07:00
YHH 8f6a12767c feat(renderer): chat-v2 — wire web / memory / ask_choice tools (#160) (#208)
The real-loop runTurn now builds a ToolRegistry mirroring chatCommand:
web search/fetch (when searchEnabled()), memory tools (remember /
recall / forget), and ask_choice. The loop is constructed once per
chat session and reused across turns so cache state and the running
transcript carry over.

Tool events flow through the existing makeLoopBridge into tool.start /
tool.end card pairs, so the chat-v2 surface now shows real tool
activity inline (when DEEPSEEK_API_KEY is set). MCP / sessions /
slash commands are still deferred to 5d-23c-e.
2026-05-03 18:43:56 -07:00
YHH fb80b9cb38 feat(renderer): chat-v2 — real DeepSeek loop when API key is set (#160) (#207)
New makeLoopBridge() translates LoopEvents into the AgentStore event
shape: assistant_delta opens reasoning / streaming cards and emits
chunks; tool_start + tool produce paired cards with elapsedMs;
assistant_final and done close everything and stamp turn.end with
usage; error closes any open card with aborted=true and fires
turn.abort.

ChatV2Shell takes an injectable runTurn callback. runChatV2 builds the
real one (DeepSeekClient + ImmutablePrefix + CacheFirstLoop) when
DEEPSEEK_API_KEY is set; otherwise the canned demo path still runs so
the UI is explorable without an account.

11 new bridge unit tests; existing chat-v2 tests rewired to the new
runTurn injection point.
2026-05-03 18:36:55 -07:00
YHH ce01092f9c feat(renderer): chat-v2 — settled cards flow through Static (#160) (#206)
chat-v2 splits its card list into settled (user, finished reasoning,
finished tool, completed streaming) and in-flight at every render.
Settled cards go through inkCompat.Static so they emit to scrollback
once and never re-render; only the actively-streaming card stays in
the live region. The viewport's live region is now bounded by the size
of the in-flight card, not by the whole conversation.

MarkdownView drops its useMemo: Static's renderToBytes path uses a
one-shot tree walker without a React dispatcher, so any hook call
inside a Static-promoted subtree throws. Recomputing markdown lines
each render is allocation-light enough that the cache wasn't load-bearing.
2026-05-03 18:25:52 -07:00
YHH 0bd11e1e63 feat(renderer): bracketed paste + sentinels in SimplePromptInput (#160) (#205)
The keystroke parser now recognises ESC[200~...ESC[201~ wrappers and
emits the entire payload as a single keystroke, so multi-line pastes
hit processMultilineKey's pasteRequest branch. SimplePromptInput keeps
a per-instance paste registry; each burst gets one PUA sentinel in the
buffer + an inline `[paste #N · Ml · Nb]` placeholder. Submit expands
sentinels back to original content via expandPasteSentinels.

chat-v2 + input-demo enable bracketed-paste mode (ESC[?2004h) on entry
and disable on exit so the wrapper actually arrives.
2026-05-03 18:06:30 -07:00
YHH 42dba23bf7 feat(renderer): chat-v2 — submit history with ↑/↓ recall (#160) (#204)
usePromptHistory hook holds a FIFO of submitted entries. Up arrow on a
boundary saves the current draft, then walks back; down arrow walks
forward and restores the saved draft past the newest entry.
Duplicate-of-latest submissions are coalesced; entries past the cap
(default 100) drop from the front.

chat-v2 wires it into SimplePromptInput's onHistoryPrev / onHistoryNext.
2026-05-03 17:51:07 -07:00
YHH ea3bdbed4d feat(renderer): SimplePromptInput goes multi-line (#160) (#203)
Reuses processMultilineKey from src/cli/ui/multiline-keys.ts so chat-v2's
prompt input shares behavior with the live chat input: backslash line
continuation, ↑/↓ between logical lines, Ctrl+W word delete, Meta+B/F
word jump, Alt+Enter for newline, Enter to submit, history hooks at
buffer boundaries.

Renders each logical line as its own row; cursor lands on the right
(line, col) via useCursor's rowFromBottom. The keystroke parser also
learns Alt+Enter (\x1b\r → meta+return) so the multi-line reducer can
distinguish it from a bare Enter.
2026-05-03 17:41:56 -07:00
YHH 7cd9456440 feat(renderer): chat-v2 — live input replaces canned playback (#160) (#202)
chat-v2 now opens an empty conversation with SimplePromptInput at the
bottom. Each Enter dispatches user.submit and plays a stock canned reply
turn (reasoning + streaming + turn.end) — no real model is wired up yet,
but the seam from keystroke → reducer → cards → cell-diff renderer is
fully exercised end-to-end.

Esc on an empty prompt exits; Esc on a non-empty prompt clears (handled
by SimplePromptInput's onCancel semantics).
2026-05-03 17:27:00 -07:00
ctharveyandCharles H 9bf23b49ca refactor(mcp): move McpServerSummary out of UI slash types into src/mcp/summary.ts (#201)
- New src/mcp/summary.ts: canonical McpServerSummary interface + buildMcpServerSummary() builder
- slash/types.ts: import+re-export McpServerSummary from MCP layer, remove inline interface and unused inspect/registry imports
- chat.tsx: use buildMcpServerSummary() instead of inline object literal

Addresses issue #196 first boundary: relocation + builder, zero behavior change.

Co-authored-by: Charles H <[email protected]>
2026-05-03 17:23:31 -07:00
YHH e931db397e feat(renderer): SimplePromptInput — single-line input on cell-diff renderer (#160) (#200)
New SimplePromptInput component built on useCursor + useKeystroke. Handles
printable chars, backspace, delete, enter, ←→, home/end, ctrl+a/e/u/k,
escape (clear when non-empty, cancel when empty). Caret position published
through useCursor so the terminal cursor sits where the user expects.

`reasonix input-demo` exercises the component standalone — submitted
entries land in a Static history list above the prompt.
2026-05-03 17:17:16 -07:00
YHH 184a4a0366 feat(renderer): useCursor hook — React-driven terminal cursor positioning (#160) (#199)
Adds CursorContext + useCursor() in the renderer. Components register a
target { col, rowFromBottom?, visible? }; mount() reads the latest target
on every frame commit and feeds it into next.cursor.

Also adds a "cursorVisible" patch type so visibility transitions emit
ESC[?25h / ESC[?25l on the diff stream. Foundation for the chat-v2
PromptInput migration — single-line input lands next.
2026-05-03 17:04:26 -07:00
YHH 4d58eef324 feat(renderer): markdown pipeline — marked → MdLine[] → inkCompat (#160) (#198)
Splits markdown rendering into a pure parser (markdown-lines.ts) and a
cell-diff-renderer view (markdown-view.tsx). chat-v2's reasoning and
streaming card bodies now render proper headings, lists, code blocks,
blockquotes, and inline bold/italic/code instead of a single flat line.

`markdownToLines` is streaming-safe — partial input parses gracefully,
so the same call on every chunk yields a stable line tree.
2026-05-03 16:55:10 -07:00
YHH c2603a897e feat(renderer): chat-v2 — stripped-down App tree on cell-diff renderer (#160) (#197)
Mounts AgentStoreProvider through `mount()` instead of Ink's `render()`.
A canned event script drives the real reducer; CardRows read state via
`useAgentState`. No PromptInput yet — Esc / Ctrl+C exits.

Lays the seam for the chat App migration: events → reducer → useState
→ inkCompat tree → cell-diff renderer all proven end-to-end.
2026-05-03 16:42:21 -07:00
ctharveyandCharles H d9684bbff5 fix(tui): bound Markdown table rendering to card width with fallback key/value layout (#195)
- MarkdownWidthCtx + useWidth() propagate available column width into
  nested block renderers; width prop is body-width (no double subtraction)
- tableLayout() pure function decides columnar vs fallback layout
- FallbackTable wraps long values under their label; labelPad clamped to
  availableWidth-1 so label+value never exceeds card width
- ColumnarTable for tables that fit; HorizontalRule width-bounded
- plainText() exported for test access
- 18 tests: smoke (11), tableLayout fallback decision (2),
  FallbackTable width invariants (5 including narrow-width sweep)

Co-authored-by: Charles H <[email protected]>
2026-05-03 16:25:53 -07:00
YHH 02ce601ef2 feat(renderer): card-demo — full chat lifecycle reference (#160) (#191)
* feat(renderer): card-demo — full chat lifecycle reference

Demonstrates the design pattern for streaming-TUI cards: every card
type (user, reasoning, tool, plan, response, diff, error) has an
active form that lives in the live region, animating, and a settled
form (typically 1 line) that commits to terminal scrollback once
the underlying work completes.

Auto-replays a fake chat session: user message → reasoning →
shell tool with rolling output → plan with stepwise spinner →
diff → streaming response → error notice. Each card animates
in the live region, then collapses to a single-line summary in
the Static history above. The live region is bounded — at most
ONE active card plus status + prompt — so it never overflows
the viewport, native mouse scroll/select keep working.

This is the pattern Reasonix's actual chat App.tsx should adopt
when migrating to the cell-diff renderer: track in-flight work
in live state, commit completed work to Static. Mirrors how
Claude Code structures its CLI streaming.

Refs #160.

* feat(card-demo): full Reasonix card vocabulary + variants

After surveying src/cli/ui's actual card stream, expanded card-demo
from 7 stages to 13 covering every real card type and lifecycle
variant we ship today:

  user  → reasoning (R1) → read_file → bash → bash retry/error
       → plan (4 steps with embedded tool ops)
       → write_file rejected → diff → subagent (nested children)
       → streaming response → usage → warn → error

Card behavior matches the live App's CardStream conventions:

- reasoning: active spinner + last 4 token-streamed lines; settled
  keeps last 2 lines + "⋯ N ¶ · M tok · /reasoning last"
- tool: tone-colored glyph (▤ read, ▥ write, ▶ bash, ⊙ search,
  ⌬ fetch, ⊕ mcp); active rolling 5-line tail + elapsed; settled
  shows "⋮ N earlier lines" + tail (2-5 lines per tool tone);
  rejected = badge replaces body; retry/error = red + ↻ retry X/Y
- plan: ◯/▶/✓/✗/!/s glyphs + "← in progress" marker; settled
  keeps full step list (per #160 Plan never collapses to 1 line)
- response: active "writing…" spinner + last 4 lines; settled
  keeps full markdown body (or "(truncated by esc)" if aborted)
- diff: file header + first-N hunk preview; +/- coloring
- subagent: ⌬ + nested children with ▎ indent; child cards are
  single-line summaries with their own tone/glyph
- usage / warn / error: single-row badges

Wrap helper added so streaming text wraps at ~70 cols and the tail
is computed against actual visual rows.

Refs #160.

* fix(renderer): wide-char width compensation for Ambiguous glyphs

User repro: card-demo in Windows Terminal showed residue chars next to
glyphs like ↻ ▶ ⊞ ◆. East Asian Ambiguous width disagreement —
stringWidth reports 1, the terminal renders 2 (or vice versa on
Western terminals), so the diff cursor model gets out of sync with
where the terminal actually advanced. Subsequent cells land in the
wrong column → leftover chars from the previous frame appear next to
the new content.

Two-part fix:

1. Layout (string-width call site): treat ambiguous chars as wide
   (width 2) by default, so the layout reserves enough cells either
   way. Box-drawing block U+2500..U+257F is pinned to width 1
   explicitly because terminals never render those wide and our
   borders depend on it.

2. writeCell, when emitting a Wide cell, runs a leading-space + CHA
   compensation:
     CHA col+1     ← jump to the right-neighbor cell
     stdout ' '    ← pre-write a blank there (covered by wide
                     glyph if the terminal renders 2-wide; visible
                     as a clean space if the terminal renders 1-wide)
     CHA col       ← jump back to the original column
     stdout char   ← write the actual glyph
     cursor.x += 2 ← model advances 2 cells regardless
     CHA col+2     ← force the terminal cursor to col+2 so the next
                     cell write lands in the right spot

   ~4 extra escape sequences + 1 leading space per Wide cell, only
   fires when cell.width === Wide. Empty / narrow cells unaffected.

This is what was making \`↻ retry 1/3\` and \`0.4s\` run together
with stray chars between them, and what made the Plan card render
\`││\` on the right edge.

Refs #160.

* feat(card-demo): real-world plan execution + concurrent active cards

Restructure to match how a real session actually drives cards:

- active state is now an array. Multiple cards can be live at once
  (plan stays live while a tool runs below it; subagent stays live
  while children animate inline).

- Plan no longer appears all-done in one shot. Steps progress one
  at a time: each step starts running, a tool card appears below the
  plan card, the tool animates, settles to history, plan step flips
  to done, next step starts. Plan card itself never leaves live area
  until every step is in a terminal state.

- The fix-failing-test scene now exercises:
  * search step (grep) — short tool with rolling output
  * write_file rejected mid-plan → step gets blocked → plan retries
    via patch tool
  * bash test with retry chain (1/3 fails, 2/3 succeeds)
  * bash deploy (npm publish)
  * full plan settles, diff card pushed, markdown response
    streams (header + code block + bullet list)

- Subagent scene: ⌬ card stays live while 4 child rows animate
  in sequence (reasoning, grep, read, diff). Each child flips
  from running spinner to ✓ in place. CJK streaming response
  follows.

- Edge cases scene: aborted reasoning (settles with red glyph +
  "(aborted)" badge), MCP tool, web_fetch, compaction warn, rate
  limit error, final usage card.

Tools now have per-tone tail length (read/search/fetch = 2 lines,
bash/mcp = 5 lines) matching the real CardStream conventions.
ToolActive carries a `retry` field rendered as `R 1/3` next to the
elapsed timer.

Refs #160.
2026-05-03 16:23:14 -07:00
YHH 4ee324b02e feat(renderer): virtual viewport — full layout stays live, PgUp/PgDn scrolls (#160) (#190)
* feat(renderer): virtual viewport — full layout stays live, PgUp/PgDn scrolls

Adds a scroll: "virtual" mode to mount(). Rather than promoting overflow
rows to scrollback (where they freeze), the entire layout lives in
memory and the visible viewport-1 window slides over it. All animations
keep running for the full layout, even when the user has scrolled away
from the bottom.

mount opts.scroll defaults to "scrollback" — the existing behavior is
unchanged for chat / preview / banner-demo et al. Apps that want
dashboard-style live regions opt in.

Implementation:
  - renderVirtual returns the full layout with a windowAt(offset, h)
    slicer.
  - mount tracks scrollOffset + stickyBottom + lastTotalRows.
  - Each commit picks a window: stickyBottom or shrink → snap to
    bottom; otherwise hold the user's offset (clamped).
  - PgUp / PgDown scroll by viewport-1 rows. Home / End jump to
    extremes. After any scroll, stickyBottom re-evaluates against
    the new offset so resuming at the bottom auto-follows growth.

stress-demo opts into "virtual" — its 4 concurrent regions can now
exceed the viewport without freezing anything; user scrolls the
viewport over a still-live layout.

Tests: tests/renderer/virtual-viewport.test.tsx (6) — initial bottom
pin, PgUp older rows visible, Home/End jumps, growth-while-sticky
follows latest, growth-after-user-scroll holds position. Uses an
inline virtual-terminal byte parser to read final screen state past
cell-diff fragmentation.

Refs #160.

* feat(renderer): mouse wheel scrolls the virtual viewport

Mouse wheel was being consumed by the terminal's own scrollback and
landed on empty pre-mount terminal output instead of scrolling our
virtual layout.

Fix: enable SGR mouse mode (\x1b[?1000h\x1b[?1006h) on mount when
scroll: "virtual", disable on destroy. Keystroke parser recognizes
button 64 → wheelUp, button 65 → wheelDown. mount's scroll handler
maps wheel events to scrollBy(±3 rows).

Mouse capture is only enabled in virtual mode; scrollback mode
leaves text selection / native scrollback alone for chat-style
apps where the user expects normal terminal behavior.

Tests: keystroke parser cases for SGR `<64;X;YM`, `<65;X;Ym`. Two
virtual-viewport tests cover wheel scrolling and the enable/disable
escape sequences at mount/destroy.

Refs #160.

* fix(renderer): disable mouse mode on any exit path

The bug: enabling SGR mouse mode (\x1b[?1000h\x1b[?1006h) at mount
without disabling it on every exit path leaves the terminal stuck —
mouse clicks and selection get swallowed by escape sequences for
the now-dead process. User has to close the terminal window or
manually emit the disable bytes.

Fix: register `process.on("exit", ...)` to write DISABLE_MOUSE on
ANY process exit (normal, crash, parent-killed). Also intercept
SIGINT/SIGTERM with `process.exit(130)` so Ctrl+C funnels through
the same exit handler. destroy() unregisters these handlers when
mount tears down cleanly.

Idempotent disable: writing DISABLE_MOUSE twice (once from
destroy, once from exit handler) is safe — the disable sequence
just sets a flag in the terminal.

Refs #160.

* feat(renderer): virtual mode enters alt-screen — like the live chat

Aligned mount's virtual mode with src/cli/ui/alt-screen.ts: enter the
terminal's alternate buffer (1049h) so the renderer owns its own
viewport without polluting the user's main shell history. Use button-
event mouse mode (1002, not 1000) for press/drag/release tracking;
SGR coords (1006). Shift+drag still bypasses for native selection.

The escape sequence on enter is now:
  \x1b[?1049h\x1b[2J\x1b[H\x1b[?1002h\x1b[?1006h

On any exit (destroy, process.exit, SIGINT/SIGTERM):
  \x1b[?1006l\x1b[?1002l\x1b[?1000l\x1b[?1049l

The alt-screen toggle (1049l) automatically restores the user's
pre-mount terminal contents — npm wrapper output, prior shell prompts,
all visible again. No more polluted scrollback after stress-demo
exits, no more stuck mouse mode if the process crashes.

This is what the user meant by "fullscreen": the chat command and
stress-demo now both behave like vim/htop/less — own the viewport,
restore on exit. The scrollback mode (default for chat preview etc.)
keeps the inline behavior where output streams to the user's main
terminal buffer.

Refs #160.

* fix(stress-demo): inline mode + rolling Shell — like Claude Code

After studying claude-code-sourcemap: their CLI runs **inline** for
streaming output (no alt-screen, no mouse capture). Native mouse
selection and terminal scrollback work the user's whole life.
AlternateScreen wrapping is opt-in for explicit modal UIs (plan
mode, etc.) — not the default.

Reasonix stress-demo was wrong to opt into virtual mode. Reverting:

  - scroll: "virtual" removed → uses default "scrollback"
  - SHELL_WINDOW=5 rolling window restored so the layout fits a
    typical viewport (~22 rows)
  - alt-screen takeover gone → user keeps native mouse selection
    and terminal scrollback

Now matches Claude Code's pattern: streaming dashboards stay inline,
trade-off is older content goes to terminal scrollback frozen (which
is fine, that's how every TUI streaming app works).

Virtual mode stays in the renderer for genuine modal/fullscreen UIs
that explicitly opt in. Not the default.

Refs #160.
2026-05-03 08:45:27 -07:00
YHH fd64c2f8e5 feat(renderer): stress-demo — 4 concurrent live regions (#160) (#189)
* feat(renderer): stress-demo — 4 concurrent live regions

The simple-streaming preview wasn't a real test of the renderer's
value. Plain text streaming on its own is something Ink doesn't
struggle with too much. The actual jitter that #155 reports comes
from STACKED dynamic regions all updating concurrently — Plan card
on top with a spinner, shell command appending output rows below,
streaming response card on top of that, status header ticking, etc.

This subcommand mounts that exact scene:

  - status row (ticks every 100ms — elapsed time + cost)
  - Plan card (4 steps, step 2 has a spinner ticking every 80ms)
  - Shell card (npm test, output rows append every 250ms)
  - Response card (text reveals 4 chars every 33ms, wraps mid-phrase)
  - hint bar at bottom

All five regions update at independent rates. On Ink, every state
change in any of them re-emits the entire 20-row tree. On the new
renderer, each tick produces patches only for the cells that
actually changed — typically 1-3 cells per tick.

Three tests cover initial paint, ticked state after 1s
(verifying multiple regions are advancing), and ESC-to-exit.

Refs #160. Run `reasonix stress-demo` to see whether the original
jitter problem is actually fixed in the live terminal.

* fix(renderer): re-reserve vertical space when layout grows mid-session

stress-demo exposed a hard correctness bug: live repro showed
spinner glyphs scattered down the left margin overwriting npm dev
output, multiple stacked top borders, scrambled text everywhere.

Root cause: reservation only ran on the first paint. stress-demo's
layout grows over time (Shell card appends rows every 250ms,
Response card text wraps onto new rows as it streams). When the
new layout height exceeded the originally-reserved rows, each
overflowing row triggered a terminal scroll. The diff cursor model
didn't track scrolls, so subsequent relative cursor moves landed
in completely wrong positions — overwriting whatever was at those
real terminal coordinates, including pre-mount scrollback content.

Fix: track reservedRows. On every commit, if the new layout's
height exceeds reservedRows, emit `\n * delta + CSI <delta> A` to
reserve more rows (scrolling once if needed) and bring cursor
back to its model position. Subsequent diffs then use relative
moves within the now-larger reserved region — never past it,
never into pre-mount territory.

Also corrects the off-by-one math from 5d-13: each commit can
extend the reserved area incrementally as content grows.

Refs #160.

* fix(renderer): clip layout to viewport-1 + ink-compat Box default = row

Two fixes from running stress-demo to actual chaos in PowerShell.

1. Layout taller than viewport caused overflow rows to write past
   the reserved area, triggering scrolls the diff cursor model
   didn't track. Subsequent relative cursor moves landed in
   pre-mount terminal territory — Plan spinner cells overwrote
   npm dev output, top borders got clobbered by glyphs from
   later commits.

   Fix: renderToScreen takes an optional maxHeight. mount passes
   viewportHeight - 1. When the layout produces more rows than
   that, the SKIP rows come off the TOP — so the most recent
   streaming content stays visible while the older static chrome
   scrolls off the top of the live region.

2. inkCompat.Box defaulted flexDirection to undefined (which our
   native Box treats as column). Ink defaults to row. Real
   components like the live WelcomeBanner used <Box> for hint
   lines expecting row flow; the shim was stacking each Text
   on its own line, blowing the layout up to 19 rows.

   Fix: ink-compat Box defaults flexDirection to "row" when
   not explicitly set.

Refs #160.

* feat(renderer): promote overflow rows to scrollback when layout > viewport

Last fix clipped layout to viewport-1 to stop the diff from corrupting
pre-mount terminal content, but it also meant scrolled-off rows were
never preserved — user couldn't scroll up to see the older state.

Now when layout exceeds viewport-1, the top rows that get clipped are
EMITTED to scrollback explicitly:

  1. Track promotedRows — how many top rows have been committed.
  2. Each commit, if the new clip count exceeds promotedRows, emit
     bytes for those new rows via serializePromoted: clear the live
     area, write the promoted rows (cursor advances, they go into
     scrollback), reset frame, then repaint the live region below.
  3. promotedRows monotonically increases — once a row is promoted,
     it stays in scrollback at the state it had when promoted (its
     last-known content before scrolling off).

renderViewport replaces the renderToScreen call inside mount: it
returns the visible Screen + a serializer for the promoted slice
of the same layout pass (no double-layouting).

For status / spinner rows whose content keeps changing: when they
overflow, the snapshot at the moment of overflow is what scrollback
keeps. Subsequent commits stop touching those rows. UX-wise this is
similar to how a real terminal scroll preserves output history.

Refs #160.

* fix(stress-demo): rolling Shell window — keep all 4 regions in viewport

Reframing: terminal scrollback is write-once. Once a row scrolls off
the live region, terminals can't update it anymore — animations on
that row are necessarily frozen. The promote-to-scrollback path
preserves the row so users can scroll back, but it'll never re-animate.

The fix isn't more renderer plumbing — it's keeping the demo's layout
inside the viewport so nothing has to scroll off in the first place.

Shell card now shows the last 5 output rows; older rows roll out with
a "(+N earlier)" indicator next to the title. The card stays a
constant ~7 rows tall regardless of how many test lines have arrived.
Status + Plan + Shell + Response + hint now total ~22 rows — fits in
a typical 24-row terminal with all four regions live and animating.

Real chat use cases will use Static for committed messages (which
DOES belong in scrollback) and live region for the in-flight reply
(which fits the viewport). The promote path stays for those cases.

* fix(renderer): full reset on resize — no double-paint

Live repro: shrink the terminal while stress-demo is running. The Plan
card appears stacked twice — one frozen copy above, one live below.

Cause: resize re-rendered through the normal onCommit path, which
saw layout > new viewport-1 and ran promote-to-scrollback. The old
live frame's height (from the bigger viewport) was used to compute
how far up to clear with CSI nA — but CSI A clamps at viewport top,
so the clear missed pre-resize content. Then promoted bytes wrote
visibly into the cleared area, and the diff repainted the live
region below. Net effect: duplicate cards.

Fix: resize is a special event, not a normal commit. Reset frame,
reservedRows, promotedRows; emit `\x1b[2J\x1b[H` to wipe the
visible viewport (scrollback above is preserved by terminals);
then re-render through the normal first-paint path. Pre-resize
content stays in scrollback; current frame paints fresh in the
new viewport size.

Refs #160.
2026-05-03 07:47:48 -07:00
YHH a9df67102b feat(renderer): preview — incremental text reveal on the streaming row (#188)
Builds on the spinner state machine: instead of just spinning then
echoing, the response now reveals 3 chars per 33ms, growing in place
in the live area. Spinner glyph keeps ticking (80ms) while text grows.
When fully revealed, a 200ms pause, then the user line + complete
echo land in Static and the prompt comes back.

This is the workload that breaks Ink (#155): a streaming card whose
content grows mid-frame. Each reveal here is ~3 cell writes; the diff
layer doesn't repaint anything else (spinner cell, user line, hint
bar all stay frozen across the reveal). Real LLM streaming, when we
wire it in, slots into the same state — just replace the setInterval
that advances `revealed` with the token-arrival callback.

Response wraps at 60-col viewport — exercises the reveal-across-wrap
case where adding chars at end of one row spills onto the next.

Refs #160.
2026-05-03 07:07:43 -07:00
YHH a3b346848f feat(renderer): preview — streaming spinner state machine (#187)
Enter on a non-slash submission no longer echoes immediately. Shell
enters a "streaming" state: the user line and a Braille spinner row
('thinking…') render in the live area below the Static history,
ticking 80ms/frame. After 1500ms the streaming row commits both the
user line and the echo to Static and the prompt becomes available
again.

This is the core value-prop test for the cell-diff renderer: the
spinner ticks 18-ish times during the stream, each tick is a single
cell change, and the diff emits ~1 patch per frame instead of
re-painting the whole live region the way Ink does. No row-count
churn during the stream → no jitter.

Input is paused while inflight (keystrokes are dropped). The slash
fast-path (/help, /clear, /exit, /unknown) still works because slash
commands return synchronously without entering streaming.

Two new e2e tests in preview.test.tsx assert the spinner appears,
the echo lands after the timeout, and keystrokes during streaming
are dropped. The /clear test was rewritten to use /help submissions
(slash-only) to avoid streaming interference.

Refs #160.
2026-05-03 06:56:35 -07:00
YHH 966ddeac3b fix(renderer): reserve vertical space + slash commands in preview (#160) (#186)
* fix(renderer): anchor cursor to col 0 before the first paint

Bug surfaced live: typing into the preview shell wrote characters at
the wrong screen position because the very first frame's diff started
emitting cells from wherever the terminal cursor happened to sit at
mount time (often mid-line, after the npm dev wrapper output). The
moveTo no-op for (0,0)→(0,0) meant no \r got emitted, so the first
row landed in the column the shell had left the cursor at.

Fix: emit \r CSI J before the first reconciler commit. \r anchors the
cursor at column 0 of the current row; CSI J clears below so any
straggler text isn't visible underneath the live area. Subsequent
diffs already use \r on every row transition, so only row 0 of the
initial paint was vulnerable.

Adds reasonix preview slash commands (/help / /clear / /exit) on top
of 5d-12 since the user was testing them and surfaced the cursor bug.
Also fixes Static so that shrinking items[] resets lastIndex (without
this, a /clear followed by new items wouldn't emit the new ones).

Refs #160.

* fix(renderer): treat OOB cells as EMPTY_CELL in diffEach

Live repro from running reasonix preview:

  > 123 ▏         1 dev    <-- our prompt landed on the npm wrapper line
  > tsx src/cli/index.ts preview
  Enter submit · / for commands · Esc exit

Initial paint mounted on a 24-tall emptyFrame against a 6-row layout.
diffEach iterates the union (24 rows). For y=6..23 prev had EMPTY_CELL
(allocated by emptyFrame), next.cellAt returned undefined (OOB on the
shorter screen). The early-skip required BOTH non-undefined for
cellsEqual, so the OOB case fell through and emitted clear-patches —
~18 rows × viewportWidth cells of cursor moves + spaces. On a 24-row
terminal that ran the cursor past the bottom, scrolling the npm
output up; the header scrolled out of view and the prompt landed
where "> [email protected].1 dev" used to sit.

Fix: coalesce undefined to EMPTY_CELL on both sides before the equality
check. OOB-vs-EMPTY is now a no-op; populated-vs-OOB still emits a
clear (which is correct — the row really shrank).

Two regression tests in tests/renderer/diff.test.ts pin both legs.

* fix(renderer): reserve vertical rows + revert OOB coalesce

User-visible repro: reasonix renderer-demo (and preview) only showed
the bottom row of the layout in PowerShell. Header / prompt rows
appeared to be missing.

Two interacting bugs:

1. mount painted rows top-down using CSI nB cursor moves. When the
   shell left the cursor near the bottom of the viewport, every row
   transition past the visible region scrolled the terminal up,
   pushing earlier-painted rows off-screen. Only the LAST row written
   ended up still visible.

   Fix: before the first paint, emit `\r \n*(N-1) CSI <N-1>A` to
   pre-reserve N rows below the cursor (scrolling up once if needed)
   and return to the start. Subsequent moves stay within the reserved
   block — no more scrolls.

2. The earlier OOB-coalesce attempt in diffEach treated
   prev=undefined / next=EMPTY_CELL as equal, which silently dropped
   patches for spaces inside text content (since space cells share
   charId/style with EMPTY_CELL). "(none yet)" rendered with cursor
   gaps where its space should have been.

   Reverted to the original diff predicate. Initial paint now emits
   patches for every cell in the new screen (verbose, but correct);
   subsequent diffs still coalesce identical cells.

Reservation regression test in mount.test.tsx asserts the
\r\n*8\x1b[8A prelude for a 9-row layout.

Refs #160.

* fix(renderer): reserve N+1 rows so the final cursor park doesn't scroll

Off-by-one in the reservation prelude caused values to drift one row
up after the first paint when the live region used the bottom of the
viewport. Trace: 9-row content + final cursor parks at frame y=9
(one past the last content row). Old reservation only covered 9 rows
(R..R+8); the cursor's final move to R+9 hit the viewport bottom and
scrolled, shifting all painted content up by 1. Subsequent diffs
targeted the now-shifted rows correctly in their own model, but the
already-rendered content had drifted, so visually new values landed
one row above the row where the label sat.

Bump reserve to screen.height (was screen.height - 1) so the parking
row is also pre-allocated. seven-key-trace test confirms the byte
stream produces the right cells; mount.test.tsx regression updated
to assert the new prelude shape.

Refs #160.
2026-05-03 06:48:08 -07:00
YHH 9e206a14ad feat(renderer): reasonix preview — minimal chat shell on the cell-diff renderer (#185)
First user-facing surface that runs entirely on the new pipeline. Echo
mode for now: header, Static-emitted history, single-line input,
Enter to submit, Esc to exit. Composes everything 5d-2..5d-11 added
(useKeystroke, useApp.exit, Static scrollback, gap, hex colors,
marginTop, useState-driven draft).

State held in refs so a single push("abc\r") that fires four
keystrokes synchronously commits the right text — closure-captured
state would otherwise read pre-update values.

Subsequent PRs grow this shell toward feature parity with the live
chat: model badge, streaming card, tool result rows, slash-commands.
Once it catches up, the existing Ink-based App becomes the legacy
backend.

Refs #160.
2026-05-03 05:46:21 -07:00
YHH c557b9726b test(renderer): the live WelcomeBanner renders end-to-end via the shim (#184)
Mounts the actual src/cli/ui/WelcomeBanner.tsx — the component the
running app uses today — through our cell-diff renderer with **zero
source changes**. vi.mock substitutes "ink" with the ink-compat shim
at test time, so the production import paths stay intact.

Asserts the frame glyphs, REASONIX brand line, slash hints, in-code
mode tagline swap, dashboardUrl link line, and a narrow viewport
(cols=40). This is the first time a real production component renders
under the new pipeline without being copied or rewritten.

Refs #160. The path forward for full migration: add a runtime
"ink" → ink-compat alias when the new renderer is selected, and
existing components keep working.
2026-05-03 05:29:22 -07:00
YHH 5e040ad2e5 feat(renderer): wire useApp().exit() to a mount-level onExit hook (#183)
Previously useApp() returned a default {exit: noop}. Components inside
a mount tree could call exit() but nothing happened — the host had to
read the user's intent some other way (a Promise resolved from a
keystroke handler, etc.).

mount() now provides AppContext.Provider with a real exit fn. The fn
defers via queueMicrotask so it never fires synchronously inside a
render or effect — that would unmount the tree mid-commit. After
destroy, exit() becomes a no-op, so a stale ref can't fire onExit
later.

mount opt: onExit?: (error?: Error) => void. The host owns the actual
teardown; onExit is just the signal.

Refs #160. Smaller surface than full lifecycle plumbing — covers the
Ink useApp() pattern that DiffApp/ReplayApp/Setup/Wizard rely on.
2026-05-03 05:22:24 -07:00
YHH 0e893e1c0a feat(renderer): select-demo — arrow-nav SingleSelect via ink-compat (#182)
Reasonix select-demo subcommand mounts a faithful single-select list
through the cell-diff renderer: arrow nav, Enter to submit, Esc to
cancel, disabled rows skip + dim. Real-world pattern that combines
useKeystroke, useState-driven highlight, hex/named-color theming, and
nested column Boxes.

Five end-to-end tests cover initial paint, ArrowDown skipping a
disabled row, Enter on the initial active row, Esc cancel, and
ArrowUp wrap-around.

Refs #160. Together with banner-demo, this proves both static-shaped
content (banner) and interactive-shaped content (select) ride the new
pipeline cleanly.
2026-05-03 05:15:21 -07:00
Matt Van HornandMatt Van Horn d6fde1786d test(gitignore): add unit tests for src/gitignore.ts (#139) (#180)
Adds tests/gitignore.test.ts covering ignoredByLayers (empty layers,
literal dir match, intra-file negation, isDir toggle, out-of-scope
layer skip, fall-through, no-match) and loadGitignoreAt /
loadGitignoreAtSync (missing-file null path, working Ignore from a
real .gitignore in a tmpdir).

11 tests; vitest, lint, typecheck, and full suite (2064 tests) pass
locally. No source changes; no new dependencies.

Closes #139

Co-authored-by: Matt Van Horn <[email protected]>
2026-05-03 05:07:23 -07:00
YHH ac3e4f1d56 test(renderer): wide-char + emoji end-to-end through mount (#181)
Locks in the diff pipeline's behavior with CJK and emoji content:
both glyphs of a 4-cell CJK string land, replacing wide content with
narrow leaves no ghost half-cells, narrow→wide growth writes the new
wide char, multiple emoji in a row each appear, a styled CJK char
wraps in the right SGR open/close pair, and wrapping at the viewport
edge keeps the wide glyph intact on the next row.

Refs #160. The renderer's main correctness risk in real Reasonix usage
is wide chars across diffs (Chinese UI strings change between frames
constantly). These tests catch the SpacerTail-not-cleared regression
class up front.
2026-05-03 05:02:21 -07:00
YHH e250afc007 feat(renderer): gap on Box — column rows + row columns (#179)
Adds gap to BoxNode with the obvious semantics: in column flow it
inserts N empty rows between siblings; in row flow it reserves N cells
between siblings before flexGrow distribution.

Plumbed through native BoxProps + ink-compat Box. intrinsicWidth now
counts gap*N-1 for row-flow boxes so flex distribution is correct.
gap composes with justifyContent — extra slack from space-between is
added on top of the configured gap.

Refs #160. Used by markdown.tsx, etc.
2026-05-03 04:54:39 -07:00
YHH f28c67fddd feat(renderer): Static — emit settled rows to scrollback (#178)
Implements the "rendered once and never updated" semantic for
inkCompat.Static. Previously the shim just wrapped items in a column
Box, which left them subject to re-diff every frame.

Pipeline: when Static's items array grows, the new items are rendered
offline via renderToBytes and handed to the mount Handle's emitStatic.
emitStatic clears the previous live area, writes the static bytes
(advancing scrollback), and resets the prev frame so the next paint
starts fresh below.

renderToBytes is exposed publicly so apps can stage scrollback content
without React (e.g., a one-shot welcome banner emitted before the live
loop starts).

Refs #160.
2026-05-03 04:48:19 -07:00
YHH 3f15d000e8 feat(renderer): banner-demo — first real-app component via ink-compat (#177)
Reasonix banner-demo subcommand mounts a structurally faithful version
of the welcome banner — nested Box + marginY + marginTop +
justifyContent="center" + hex colors, useStdout for centering, useKeystroke
for ESC — entirely through the ink-compat shim onto the cell-diff
renderer.

Three end-to-end tests assert frame glyphs, brand line, hint row, ESC
exit, and resize re-paint. The Ink-flavored banner used by the live App
is left untouched on this branch; this is the first concrete proof that
a non-trivial component renders end-to-end through the new pipeline.

Refs #160.
2026-05-03 04:39:21 -07:00
YHH 19c33d1a9a feat(renderer): fixed width / height on Box (#176)
Adds width and height props to BoxNode + BoxProps + ink-compat. Width
overrides intrinsic size for row-flow allocation and clamps to the
parent's available width. Height pads with empty rows when content is
shorter and truncates when content is taller.

Unblocks the height={1} spacer-row pattern (4 components in src/cli/ui
use it) and width-constrained columns (sidebar, picker lists) that
need to land before the main App can migrate off Ink.

Refs #160.
2026-05-03 04:33:18 -07:00
YHH 25240984cb feat(renderer): justifyContent in row flow — flex-end / center / space-between (#175)
Wires Yoga-style row distribution into the layout engine. Default
(flex-start) preserves current behavior. flex-end pushes children to
the right edge, center splits slack evenly, space-between distributes
the gap between siblings. flexGrow children consume slack first, so
justifyContent silently degrades to flex-start when grow is present —
which matches CSS flexbox.

Plumbed through BoxNode → BoxProps → ink-compat Box so existing Ink
code reading `<Box justifyContent="space-between">` migrates with no
source changes. Three of four uses in the codebase already match this
shape.

Refs #160.
2026-05-03 04:24:19 -07:00
YHH e8594a973f feat(renderer): ink-compat shim — Box / Text / Spacer / Static / hooks (#174)
Lets components written against Ink's API render under the cell-diff
renderer with no source changes for the props we cover.

Box: padding{X,Y,Top,Bottom,Left,Right} pass through; margin{X,Y,Top,
Bottom,Left,Right,} translate to a wrapper Box's padding so empty rows
sit above/around the inner box (works in both column and row flow,
since the wrapper carries flexGrow on row participation). borderStyle
takes the string presets, borderColor takes color names + hex.

Text: color, backgroundColor, bold, dimColor, italic, underline,
strikethrough, inverse all stack into the StylePool entry.

Spacer is just <Box flexGrow={1}/>. Static is a flexDirection=column
wrapper — it doesn't yet implement Ink's "settled content stays in
place" semantic; that needs row-level commit isolation, deferred.

Hooks: useStdout reads {columns,rows} from a ViewportContext that
mount() now provides and re-publishes on resize(). useApp returns
{exit} from AppContext (host wires its own exit). useInput translates
each Keystroke to Ink's (input, key) callback shape, with isActive
gating.

Out of scope: width/height (need fixed-size layout), justifyContent,
alignItems, gap, useFocus, Transform, measureElement.

Refs #160.
2026-05-03 04:16:19 -07:00
YHH 35637b15aa feat(renderer): reasonix renderer-demo subcommand — end-to-end on real TTY (#173)
Lets us exercise the cell-diff renderer against real stdin/stdout
without touching the main Ink-based App. Counter + last-key display,
ESC to exit. Component-level tests cover initial paint, key handling,
and ESC-to-exit through a fake stdin and the test writer.

Refs #160.
2026-05-03 04:01:43 -07:00
YHH d0ab2cbd42 feat(renderer): stdin keystroke parser + useKeystroke hook (#172)
Adds the input side of the renderer pipeline so React components can
react to user keystrokes through the same provider/hook idiom they
already use for state.

Architecture:

- parseKeystrokes(chunk) is a pure ANSI escape-sequence parser. Plain
  ASCII passes through; \x01..\x1a become ctrl+letter; \r / \n
  return; \x7f / \x08 backspace; \t tab; \x1b alone escape; ESC +
  printable is meta+char; CSI A/B/C/D arrows; CSI 1;modifier <X>
  surfaces shift/meta/ctrl modifiers; CSI 3~ delete, 5~ pageUp,
  6~ pageDown, 1~/H home, 4~/F end.
- KeystrokeReader wraps a stdin-like stream (anything with on/off
  'data') and emits parsed Keystroke events to subscribers. Sets raw
  mode on construction, drops it on destroy.
- useKeystroke(handler) hook subscribes the calling component to the
  reader provided via KeystrokeContext.
- mount({ stdin }) constructs the reader, wraps the React tree in
  KeystrokeContext.Provider, and tears the reader down on destroy.

Tracking issue: #160.
2026-05-03 03:43:35 -07:00
YHH ed1ad08615 feat(renderer): react-reconciler integration — useState drives paints (#171)
useState / useEffect / re-render-on-state now drive paints without
the caller manually calling update(). React's reconciler maintains
the host node tree; on every commit we walk it to a LayoutNode tree,
hand it to the diff layer, and write only the changed bytes.

Surface:

  const handle = mount(<App />, { viewportWidth, viewportHeight, pools, write });
  // setState in App triggers a paint automatically.
  handle.update(<NewApp />);   // explicit replace also works
  handle.resize(cols, rows);
  handle.destroy();

Box and Text are now thin wrappers that emit string-typed JSX
intrinsics ('rsx-box' / 'rsx-text'). The reconciler matches the
strings in createInstance and instantiates host nodes; the existing
no-reconciler walker in react/render.ts matches the same strings.
Both code paths converge.

Adds react-reconciler + @types/react-reconciler as direct deps.

Tracking issue: #160.
2026-05-03 03:34:29 -07:00
YHH 40fe1dc546 feat(renderer): Renderer runtime — frame state + diff + write to a sink (#170)
Closes the offline pipeline of #160. Caller pushes a React tree at
the Renderer; it lays out, diffs against the previous frame, writes
only the changed bytes to the configured sink, and stashes the new
frame for the next call.

  const r = new Renderer({ viewportWidth, viewportHeight, pools, write });
  r.update(<App />);              // first paint — full screen
  r.update(<App />);              // identical tree — zero bytes
  r.update(<AppMutated />);       // only the diff
  r.resize(cols, rows);           // next update full-resets via clearTerminal
  r.destroy();                    // SGR reset + OSC 8 close

Sink is injected (write: (bytes: string) => void), so tests run
purely in memory via makeTestWriter() — no real stdout, no real
terminal. The same shape will plug into process.stdout.write in
the runtime integration step.

Doesn't yet:
- Drive re-renders from React state (the caller still has to call
  update; Phase 5b adds reconciler-driven re-renders).
- Read keystrokes (Phase 5c).
- Replace Ink in Reasonix's CLI (Phase 5d, behind a feature flag).

Tracking issue: #160.
2026-05-03 03:02:29 -07:00
YHH 266a4d509e feat(renderer): serialize Patch[] to ANSI byte stream (#169)
Closes the second-to-last layer of #160. Takes the Patch[] that
diffFrames returns and produces the actual bytes a terminal
understands.

  cursorMove → CSI A/B/C/D (vertical first, then horizontal)
  cursorTo   → CSI <col+1> G (CHA is 1-based)
  hyperlink  → OSC 8;;<uri> ST  (empty uri = close)
  clear      → \r + CSI <count> A + CSI J  (move up N rows, erase to end)
  clearTerminal → CSI 2J + CSI H

stdout / styleStr / carriageReturn pass through verbatim — they are
already terminal bytes by the time the diff layer puts them in the
patch list.

dx=0 and dy=0 cursor moves serialize to the empty string (no wasted
escapes), and an empty Patch[] serializes to '' so emitting a frame
with no diff is a no-op.

Tracking issue: #160.
2026-05-03 02:57:24 -07:00
YHH aa87a6d88b feat(renderer): cell-level diff between two Frames → Patch[] (#168)
Core of #160 — the algorithm that takes two Screen snapshots and
emits the minimal set of (cursorMove + styleStr + stdout + hyperlink)
patches needed to bring the terminal from the old state to the new.
This is what replaces Ink's bulk eraseLines: unchanged cells produce
zero bytes.

diffFrames(prev, next, pools) → Patch[]:

- viewport size differs → emit clearTerminal + write the full new
  screen. Resize is rare; predicting wrap on a different width is
  not worth the layout machinery.
- otherwise walk every (x, y) where the cells differ:
  - move the cursor there (\r if pending-wrap, then \r + dy + dx)
  - transition style if changed (StylePool.transition cached)
  - transition hyperlink if changed (OSC 8 open / close)
  - skip SpacerTail (the wide glyph already advanced the cursor)
  - write the char
- after all changes, restore cursor to next.cursor and reset style /
  hyperlink to none so anything we don't own renders cleanly.

Adjacent same-style writes ride on the terminal's natural cursor
advance — no inter-cell cursor moves, no inter-cell style emits.

Tracking issue: #160.
2026-05-03 02:39:13 -07:00
kabaka a6fd807b49 feat(i18n): Implement front-end and back-end language setting synchronization feature (#167)
Add back-end language setting support, including initializing language settings from the server and bidirectional synchronization functionality
Expand the language registry to support more languages, and improve language storage and error handling
Fix issue of returning to the chat page after refreshing
2026-05-03 02:38:21 -07:00
YHH 3634bdeca5 feat(renderer): Box borders — preset styles + custom glyph object + per-side colors (#166)
Closes the layout side of the renderer feature surface for #160.

Borders compose with padding by sitting outside it:

  border-top
    padding-top
      content (width = inner - borders - padding)
    padding-bottom
  border-bottom

Five preset styles ('single', 'double', 'round', 'bold', 'ascii')
or a fully custom { topLeft, top, topRight, ... } glyph object —
the latter is what Reasonix's CardBox uses today (whitespace
corners + a single glyph on the left for the accent bar).

Each side toggles independently via borderTop / Bottom / Left /
Right; default-on when borderStyle is set, default-off otherwise.
borderColor sets all four; per-side overrides (borderLeftColor
etc.) win.

intrinsicWidth now accounts for border + padding so flexDirection
row in a parent allocates the correct slot width to bordered
children.

Tracking issue: #160.
2026-05-03 02:29:06 -07:00
YHH 933d01060f feat(renderer): flexDirection row + flexGrow (#165)
Refactors layout from a linear TextRow stream to a 2D structure
where each visual row holds a list of x-positioned fragments.
Necessary for row direction — sibling children need to share rows
at different x offsets, which the previous one-fragment-per-row
shape couldn't express.

flexDirection='row' lays children left-to-right. Each child gets
min(intrinsicWidth, remaining) of the available width. When the
sum of intrinsics exceeds the container, allocations scale
proportionally and children's text wraps inside its narrower slot.
Children with different heights align at the top.

flexGrow distributes leftover width after intrinsics are honored.
The common case — Box flexGrow=1 as a flex spacer between fixed
content — yields '<L> <pad> <R>' style headers without manual
column math.

Default direction stays column.

Tracking issue: #160.
2026-05-03 02:20:57 -07:00
YHH 4026baa28c feat(renderer): Box padding (top / bottom / left / right + X/Y/all shorthands) (#164)
Padding shifts content inward without changing the Box's own width.
paddingTop / Bottom emit blank rows above / below children;
paddingLeft / Right reduce the inner width children lay out into,
and every emitted row carries a leftPad offset that the blit step
honours so writes start at the correct x.

paddingX / paddingY / padding shorthands compose with the side-
specific props — explicit side wins (paddingLeft beats paddingX
beats padding).

Tracking issue: #160.
2026-05-03 02:14:07 -07:00
YHH af4e9e33ef feat(renderer): React JSX entry — Box / Text / function components → LayoutNode (#163)
Lets callers write the renderer surface in JSX instead of building
LayoutNode trees by hand. Box and Text are exported as host markers
(throw if invoked directly); the render() entry walks the React
element tree, recognizes those markers, calls stateless function
components inline, and unwraps Fragments. Output is a Screen.

No reconciler yet — stateful components / hooks / re-render-on-state
don't drive output. The walker is enough for static JSX rendering
and for tests to use familiar JSX syntax. The reconciler comes when
we wire the renderer to actually drive a live UI.

Tracking issue: #160.
2026-05-03 02:06:54 -07:00
YHH eacb4e56d3 feat(renderer): vertical-stack layout from Box / Text nodes (#162)
Walks a tree of Box and Text nodes and lays them out into a Screen
of the given width. Children stack vertically; nested boxes flatten
in source order. Long text lines wrap at the cell boundary using
grapheme-aware width via Intl.Segmenter + string-width, so CJK and
emoji ZWJ count as one rendered glyph occupying the right number
of cells.

Style and hyperlink on a Text node are interned through the pools
and propagated to every cell the node produces — sets up the diff
layer to compare cells purely by integer ids.

Tracking issue: #160.
2026-05-03 01:59:57 -07:00
YHH c222808985 feat(renderer): cell-buffer foundation — Screen, Cell, intern pools (#161)
Lays down the data structures the cell-diff renderer will read from.
Pure values, no terminal IO; the diff layer (next) reads two Screen
snapshots and emits patches per cell that actually differs.

Three pools collapse high-cardinality runtime values to integer ids
so cell comparison stays in int-vs-int and per-frame allocation
stops being a GC problem at 5K+ cells.

Tracking issue: #160.
2026-05-03 01:51:44 -07:00
YHH 0b0e19fc7a feat: remove plan sidebar / docking entirely (#159)
Plan card now lives only as a regular inline card in the stream.
No right-side panel, no above-input pinning, no Ctrl+\ toggle.
Layout stayed in 'either-or' / 'both' / 'sometimes-pinned' uncertainty
across PR #127 → #156, and the docking machinery itself was a steady
source of layout instability that no amount of width-conditional
gating fully closed.

Removes:
- src/cli/ui/layout/SidebarPanel.tsx (file)
- tests/sidebar-panel.test.ts (file)
- App.tsx: activePlanCard / rawActivePlanCard / sidebarVisible
  derivation, the sidebarOpen state + Ctrl+\ keybind, the
  <SidebarPanel> mount, the modal-active gating that only mattered
  to suppress the sidebar
- viewport-budget.tsx: 'plan-card' ZoneId entry (no claimers left),
  useIsModalActive() hook (only consumer was sidebar)
- CardStream.tsx: excludeId prop (no callers left)
- config.ts: sidebarOpen field + load/save helpers

The plan card itself is unchanged — it's already a settled card
once all steps complete and renders as a regular inline card via
CardStream's existing plan->Static path. Inline plan card has
stable height (no windowing), so it doesn't suffer the live-region
height-flutter issue the sidebar's windowed PlanSection had.
2026-05-03 01:27:51 -07:00
YHH 0da4c78ca0 fix(sidebar): stabilize windowed plan-section height across step transitions (#158)
Root-cause fix for the up-down screen jitter dududarochadev reported
in #155 (and the same class of bug we previously masked with
cols-based sidebar gating).

When a plan has more steps than fit in the window (>11), the windowed
plan-section conditionally rendered '(N earlier hidden)' / '(N more)'
hint rows only when N>0. As the running step crossed the window
boundaries those flipped on/off, changing the live region's row count
and triggering Ink's erase-then-reprint to leak the previous frame.

Always render both indicator rows in windowed mode; show the count
when N>0, an empty 1-row placeholder otherwise. Total rendered height
of the windowed plan-section is now stable regardless of how the
running step moves through the plan.

Fix lives on the plan card itself, not behind a width gate, so the
narrow-screen inline-plan path benefits the same way once the same
windowing pattern lands there (currently inline PlanCard doesn't
window, so it's already stable for now).

This is the start of the broader 'live-region row stability' work I'll
track in a follow-up issue — streaming/reasoning preview cards have
the same shape of bug during their initial output ramp.
2026-05-03 01:04:31 -07:00
YHH 161e36a461 fix(layout): plan card lives in EITHER sidebar OR card stream, never both (#156)
Per RFC #20 thread, lamyc's ask was "task list collapsed INTO a
sidebar" on portrait/narrow setups. PR #127 shipped a sidebar but
also kept a pinned PlanCard above the input — so on wide screens the
plan rendered twice (sidebar + pinned), and on narrow screens (where
the sidebar refuses to render below 88 cols) the plan was pulled out
of the card stream and pinned above input alone, leaving no inline
plan card at all.

Single rule now:

  sidebarVisible = !PLAIN_UI && sidebarOpen && cols ≥ 88 && activePlanCard

  - sidebarVisible       → CardStream excludes plan; sidebar renders it
  - !sidebarVisible      → CardStream keeps plan inline; nothing pinned

Drop the pinned PlanCard above input entirely. Drop the unconditional
`excludeId` on CardStream. `PlanCard` is no longer imported in App.

This implements interpretation B+C from the layout discussion:
B) plan fully in sidebar when room exists, no duplicate
C) narrow / portrait → plan stays inline in stream, no sidebar
2026-05-03 00:37:02 -07:00
YHH 559e684784 fix(plan): gate sidebar + pinned plan card on modal-active, not step transition (#153)
#147 used "at least one step has left queued" as the proxy for
"plan has been approved". That breaks the post-accept window: once
the user accepts, plan steps may sit in `queued` for several seconds
before the model issues its first tool call — during which the sidebar
should be visible but isn't.

Right discriminator is the approval modal itself. `useIsModalActive()`
is true exactly while PlanConfirm (or any other modal-priority claim)
is up. Drop the "non-queued" check from findActivePlan and gate at
the call site:

  - SidebarPanel: `isModalActive ? null : findActivePlan(cards)`
  - App.tsx activePlanCard: same shape

findActivePlan stays pure (no hook usage) so it remains unit-testable.
The test that previously locked in "all-queued returns null" now
locks in "all-queued returns plan" — modal-gating is the caller's
contract.
2026-05-02 23:57:13 -07:00
YHH ea66fb4bf1 feat(cards): tool card 'rejected' state + input-size meta (#154)
Closes #150 (the user-facing half — bounce wording itself stays as-is).

The plan-mode bounce error and silent write_file are both fundamentally
visual problems: the gate runs before fs writes, but the spinner-then-
JSON-error sequence reads as 'wrote, then failed'; large write_file
content gives no progress signal because formatArgsSummary picks the
short path field.

A. Plan-mode rejection visual

ToolRegistry now adds rejectedReason: 'plan-mode' to the bounce JSON.
The reducer parses tool.end output, sets card.rejected on the marker.
ToolCard swaps the spinner for a red ✗ rejected badge in the trailing
slot and hides the verbose error body — one quick visual cue replaces
a faux-write spinner followed by a wall of JSON.

B. Input size in meta

ToolCard.formatMeta gains a leading '1.2 KB in' fragment when any
string field on args is at or above 1 KB. Generic — no per-tool
special case — so write_file (content), edit_file (long replace),
run_command (long stdin) all benefit. Below 1 KB, nothing shows;
small writes don't get noisy meta.

Tests:
- ui-reducer: tool.end with plan-mode marker flips rejected=true,
  regular errors don't trigger.
- tool-card-meta: largestStringInputBytes thresholding + multi-field
  selection.
2026-05-02 23:45:22 -07:00
YHH edf4233a60 feat(i18n): default to system locale when no explicit config (#151)
First-run users with a Chinese OS locale saw English by default —
the only signal was config.lang, which doesn't exist on first launch.
Add a third tier between config and the EN fallback: detectSystemLanguage()
reads Intl.DateTimeFormat().resolvedOptions().locale (cross-platform,
no env-var spelunking) and prefix-maps zh* → zh-CN, en* → EN, anything
else → null (falls through).

Priority: user-set config > system locale > EN.

The detection function takes the locale string as a parameter (defaulting
to Intl) so it stays unit-testable without mocking globals.
2026-05-02 21:21:47 -07:00
kabaka 4b4d125987 feat(i18n): add multi-language support (#149)
Add internationalization support for the dashboard, including English and Simplified Chinese.
- Create i18n module to manage language switching and translations
- Replace hardcoded text with translation keys in all panels
- Add language switching functionality to the settings panel
- Implement dynamic loading of translation content
- Update all UI components to use translation functions
2026-05-02 21:07:33 -07:00
kabaka 5631dafdde feat(i18n): add multi-language support (#144)
Implement runtime language switching, including:
- Add /language command for language switching
- Add Chinese/English translation framework
- Modify state management to support language change events
- Update tests to ensure correct functionality
- Adjust UI components to support internationalized text
2026-05-02 21:07:29 -07:00
YHH e11fd6c848 fix(plan): only treat plan as 'active' once execution has started (#147)
User reported the right-side plan sidebar appears during the
PlanConfirm approval modal, before the user has accepted. Same bug
also pinned the plan card above the input prematurely.

Both selectors (App.tsx:297 + SidebarPanel.tsx:39) used the same
predicate: variant === "active" + at-least-one-step-not-done. But
fresh plans have every step in `queued` — the predicate matched
immediately on creation, before approval triggered any state
transition.

Tighten the predicate: "active" now means execution has actually
started — at least one step has left `queued` AND not all steps
are done/skipped. Approval-pending plans (every step queued) and
finished plans (every step done/skipped) both correctly return null.

Exported findActivePlan and added 5 tests covering the regression
plus the surrounding boundaries (variant guards, latest-of-many).
2026-05-02 20:59:31 -07:00
YHH 11c7150ed1 fix(cards): drop fake key hints + CtxCard CardHeader + TaskCard meta tidy (#145)
Plan + Error cards advertised inline keybinds in their footers
(`[r] revise` / `[r] retry` etc.) but no handler was ever wired
to scrollback cards — the actual revise/retry flow runs through
PlanConfirm modals via arrow + Enter. Pressing the advertised key
did nothing. Removed the misleading footers; the modal flows are
unchanged.

CtxCard hand-rolled its own header instead of using CardHeader,
breaking the visual contract every other card follows. Routed it
through CardHeader with the same tone/glyph/meta shape.

TaskCard's `meta` ended in a trailing space (`X.Xs · `) and
CardHeader inserts its own space before the trailing badge, so the
rendered output had a double space before the status word.

Also collapsed a dead ternary branch in PlanCard step-color logic
where two arms produced the same value.
2026-05-02 20:31:41 -07:00
YHH 4a3f5f035b feat(cards): UserCard gets CardBox accent + drop dead approval-card type (#143)
UserCard was the only Markdown-rendering card without a CardBox bar —
long pasted prompts wrapped without a continuing accent, breaking the
visual rhythm against the now-accented streaming/reasoning cards.

Audit also turned up the `approval` card kind in cards.ts: declared
in the Card union but with zero producers in src/ or tests/. The
CardRenderer case for it just routed to FallbackCard ("not yet
migrated"). Removed the interface, the union member, and the orphan
case — default branch already catches anything unexpected.
2026-05-02 19:45:11 -07:00
ctharveyandCharles H 2ed06d4213 fix(code): adapt LF model output to target file line endings for SEARCH/REPLACE matching (#142)
applyEditBlock and edit_file both detect the target file's line ending
(CRLF vs LF) and adapt the model's search/replace text before matching.
Duplicate-match checks, replacement, and diff rendering use the adapted
text. CRLF files are preserved as CRLF; LF files stay LF.

Adds tests for both paths: SEARCH/REPLACE blocks (edit-blocks) and the
native edit_file tool (filesystem-tools), covering LF→CRLF matching,
LF preservation, multi-line CRLF matching, and duplicate-match refusal.

Co-authored-by: Charles H <[email protected]>
2026-05-02 19:26:07 -07:00
YHH e625e01e2e fix(cards): restore brand accent on done-state assistant reply (#140)
PR #126 (0.23.0) gave done assistant Markdown a brand-toned
borderLeft per lamyc's RFC #20 readability ask. The #136 card
redesign extracted CardBox but flipped the done-state color to
FG.faint, defeating the contrast that lets long replies stand
out in scrollback. Now matches the streaming-state color so the
bar reads continuously across the streaming → done flip.
Aborted state stays on FG.faint (correctly de-emphasized).
2026-05-02 19:22:45 -07:00
YHH b2c9d416d2 test(slash): silence MCP reconnect spawn stderr leak (#138)
The /mcp reconnect <name> test fired kickOffMcpReconnect with spec
"node nope", spawning Node against a missing 'nope' module. The
test passed (lifecycle line is returned synchronously) but Node's
MODULE_NOT_FOUND error leaked to stderr in the test runner output.

"node -e 0" exits 0 silently and is cross-platform.
2026-05-02 09:23:17 -07:00
374 changed files with 36255 additions and 12261 deletions

No files matched your search

+1
View File
@@ -0,0 +1 @@
github: esengine
+12 -5
View File
@@ -4,6 +4,10 @@ about: Something is broken
labels: bug
---
> **Screen flicker, garbled output, leftover artifacts, cursor jumping?**
> Use the **Display / rendering issue** template instead — it asks for the
> terminal-specific info we need to diagnose those.
**What happened**
A clear and concise description.
@@ -14,10 +18,13 @@ What you expected to happen.
Steps or minimal code that reproduces it.
**Environment**
- Reasonix version:
- Node version:
- OS:
- DeepSeek model (e.g. `deepseek-chat`, `deepseek-reasoner`):
- Reasonix version (`reasonix --version`):
- Node version (`node --version`):
- OS (Windows 11 / macOS 14 / Ubuntu 24.04 / …):
- Shell (bash, zsh, fish, PowerShell 7, PowerShell 5.1, cmd, …):
- Terminal app (Windows Terminal, iTerm2, Alacritty, kitty, WezTerm, **VSCode integrated**, **Cursor integrated**, Hyper, …):
- DeepSeek model (e.g. `deepseek-v4-flash`, `deepseek-v4-pro`):
**Logs / transcript**
If using the CLI, attach the relevant chunk of `--transcript`.
If using the CLI, attach the relevant chunk of `--transcript`, or run
`reasonix doctor` and paste the output.
+109
View File
@@ -0,0 +1,109 @@
---
name: Display / rendering issue
about: Screen flicker, garbled output, leftover artifacts, cursor jumping
labels: bug, rendering
---
> Display problems almost always come from the **terminal emulator**, not
> the shell. Please fill the terminal section carefully — `bash vs PowerShell`
> tells us very little; `VSCode integrated terminal vs Windows Terminal`
> tells us everything.
**Symptom** (tick all that apply)
- [ ] Whole screen flickers / flashes during streaming response
- [ ] Lines tear or only half-redraw
- [ ] Stale output left behind after a frame updates
- [ ] Cursor jumps to wrong column or vanishes
- [ ] Mojibake / wrong-width characters (e.g. `□`, half-width emoji)
- [ ] Other (describe below)
**When it happens**
- [ ] During assistant streaming (token-by-token output)
- [ ] When tool cards expand / collapse
- [ ] During scroll-up / scrollback
- [ ] On terminal resize
- [ ] On launch / on quit
- [ ] Other (describe below)
**Terminal — the important part**
Where exactly are you running `reasonix`?
- [ ] **VSCode** integrated terminal — VSCode version: `?`
- [ ] **Cursor** integrated terminal — Cursor version: `?`
- [ ] **Windows Terminal** — version: `?`
- [ ] **cmd.exe** (legacy console host)
- [ ] **PowerShell ISE** (note: ISE doesn't support ANSI — most things will look broken)
- [ ] **iTerm2** / **Terminal.app** / **Alacritty** / **kitty** / **WezTerm** / **Hyper**
- [ ] tmux / screen / mosh — and inside which outer terminal? `?`
- [ ] Other:
> 💡 **How to find your VSCode / Cursor version**
> `Help → About` (Windows/Linux) or `Code → About Visual Studio Code` (macOS).
> Paste the whole panel — version + commit + Electron + xterm.js if shown.
**Diagnostic dump — copy/paste output**
Run **one** of the snippets below in the same terminal where you saw the
issue, and paste the output here:
<details><summary>PowerShell (Windows)</summary>
```powershell
reasonix --version; node --version
$PSVersionTable.PSVersion.ToString()
[System.Environment]::OSVersion.VersionString
"TERM=$env:TERM"
"TERM_PROGRAM=$env:TERM_PROGRAM"
"TERM_PROGRAM_VERSION=$env:TERM_PROGRAM_VERSION"
"COLORTERM=$env:COLORTERM"
"WT_SESSION=$env:WT_SESSION"
"VSCODE_INJECTION=$env:VSCODE_INJECTION"
"WSL_DISTRO_NAME=$env:WSL_DISTRO_NAME"
```
</details>
<details><summary>bash / zsh (macOS / Linux / WSL / Git Bash)</summary>
```bash
reasonix --version; node --version
uname -a
echo "TERM=$TERM"
echo "TERM_PROGRAM=$TERM_PROGRAM"
echo "TERM_PROGRAM_VERSION=$TERM_PROGRAM_VERSION"
echo "COLORTERM=$COLORTERM"
echo "WT_SESSION=$WT_SESSION"
echo "VSCODE_INJECTION=$VSCODE_INJECTION"
echo "WSL_DISTRO_NAME=$WSL_DISTRO_NAME"
```
</details>
```
<paste output here>
```
**VSCode / Cursor users only — terminal settings**
Open Settings (`Ctrl+,`), search `terminal.integrated.gpuAcceleration`,
report current value: `auto` / `on` / `canvas` / `off` — `?`
Already tried any of:
- [ ] Switching `gpuAcceleration` to a different value
- [ ] Detaching the terminal (drag tab into its own window)
- [ ] Running the same command in a non-VSCode terminal — did it still flicker? `yes / no`
**Reproduction**
Steps that reliably trigger it (commands run, files edited, was a tool
streaming a long response, was the window being resized, …):
1.
2.
3.
**Screen recording (strongly preferred)**
A 5–10s GIF or MP4 is worth 1000 words for rendering bugs. Drop it in
this comment box — GitHub uploads attachments inline.
+6 -5
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
@@ -44,6 +48,3 @@ jobs:
# DEEPSEEK_API_KEY in CI.
- name: τ-bench harness dry-run
run: npx tsx benchmarks/tau-bench/runner.ts --dry --out /tmp/tau-dry.json
- name: Harvest-bench harness dry-run
run: npx tsx benchmarks/harvest/runner.ts --dry --out /tmp/harvest-dry.json
+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
+1055
View File
File diff suppressed because it is too large. Load diff
+195 -74
View File
@@ -1,123 +1,244 @@
<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.
`npx` is the recommended path — no global install, always picks up the latest version. If you'll use Reasonix daily and want `reasonix` on your `PATH`, run `reasonix update` once and it'll do the `npm install -g` for you.
### Subcommand cheatsheet
| Command | When to use |
|---|---|
| `reasonix code [dir]` | Coding agent rooted at a project. **Start here.** |
| `reasonix chat` | Plain chat — no filesystem tools, just a conversation with persisted history. |
| `reasonix run "task"` | One-shot, streams the answer to stdout. Good for shell pipes. |
| `reasonix doctor` | Environment health check (Node version, API key, MCP wiring). |
| `reasonix update` | Upgrade Reasonix itself. |
Other subcommands (`replay` · `diff` · `events` · `stats` · `index` · `mcp` · `prune-sessions`) are listed in `reasonix --help` and on the [CLI reference](https://esengine.github.io/DeepSeek-Reasonix/#cli).
**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 three pillars. Each one solves a problem generic agent frameworks don't even see — because they were designed for a different cache mechanic.
<sub align="center">
Click through to the full architecture writeup → [Pillar 1 — Cache-first loop](./docs/ARCHITECTURE.md#pillar-1--cache-first-loop) · [Pillar 2 — Tool-call repair](./docs/ARCHITECTURE.md#pillar-2--tool-call-repair) · [Pillar 3 — Cost control](./docs/ARCHITECTURE.md#pillar-3--cost-control-v06)
</sub>
<br/>
## Capabilities
<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"/>
<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>
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.
---
<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) — three pillars: cache-first loop, tool-call repair, cost control
- [**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>
+149 -76
View File
@@ -1,123 +1,196 @@
<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`。
`npx` 是推荐路径 —— 不用全局安装,每次都拿到最新版本。如果你天天用、想把 `reasonix` 装到 `PATH` 上,跑一次 `reasonix update` 就行,它会替你跑 `npm install -g`。
### 子命令速查
| 命令 | 适用场景 |
|---|---|
| `reasonix code [dir]` | 锁在某个项目根目录的编码 agent。**先用这个。** |
| `reasonix chat` | 纯聊天 —— 不挂文件系统工具,只是带历史的对话。 |
| `reasonix run "task"` | 一次性,把答案直接流到 stdout。适合 shell 管道。 |
| `reasonix doctor` | 环境体检(Node 版本、API Key、MCP 接线)。 |
| `reasonix update` | 升级 Reasonix 本身。 |
其他子命令(`replay` · `diff` · `events` · `stats` · `index` · `mcp` · `prune-sessions`)见 `reasonix --help` 和 [CLI 参考](https://esengine.github.io/DeepSeek-Reasonix/#cli)。
**在其他目录工作:** 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 框架根本看不见的问题 —— 因为它们是为另一种缓存机制设计的。
<sub align="center">
各支柱完整说明 → [Pillar 1 — 缓存优先循环](./docs/ARCHITECTURE.md#pillar-1--cache-first-loop) · [Pillar 2 — 工具调用修复](./docs/ARCHITECTURE.md#pillar-2--tool-call-repair) · [Pillar 3 — 成本控制](./docs/ARCHITECTURE.md#pillar-3--cost-control-v06)
</sub>
<br/>
## 能力一览
<p align="center">
<img src="docs/assets/hero-terminal.zh-CN.svg" alt="Reasonix code 模式预览 — 助手提出 SEARCH/REPLACE 编辑,未 /apply 不落盘" width="860"/>
<img src="docs/assets/feature-grid.zh-CN.svg" alt="Reasonix 能力一览 — cell-diff 渲染器、MCP、计划模式、权限、仪表盘、持久化会话、Hooks/Skills/Memory、语义检索、自动 checkpoint、/effort 旋钮、transcript 重放、事件日志" width="880"/>
</p>
要求 Node ≥ 22。已在 macOS、Linux、Windows(PowerShell · Git Bash · Windows Terminal)测过。[去拿 DeepSeek API Key →](https://platform.deepseek.com/api_keys) · 完整 flag 看 `reasonix code --help`。
---
<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>
-106
View File
@@ -1,106 +0,0 @@
# Harvest eval harness (Pillar 2)
Measures Pillar 2 (R1 Thought Harvesting) the same way `tau-bench/`
measures Pillar 1 (Cache-First Loop): isolate one variable, produce
numbers anyone can reproduce.
## What's different from τ-bench-lite?
Deliberately different task shape:
| | τ-bench-lite | harvest-bench |
|---|---|---|
| task style | multi-turn tool-use | single-turn reasoning |
| user simulator | yes (LLM) | no |
| DB state | yes | no |
| checker | DB-predicate | regex + set/value compare |
| target | Pillar 1 | Pillar 2 |
| model | deepseek-chat (default) | deepseek-reasoner (only R1 has `reasoning_content` for harvest to work on) |
The two harnesses answer different questions:
- **τ-bench-lite**: *"Does Cache-First actually cut cost on real tool-use
workflows?"* (yes — 47.7pp cache, −39% cost on 48-run data.)
- **harvest-bench**: *"Does the extra V3 harvest call add measurable
value above plain R1?"* (TBD — run it to find out.)
## Modes
Three modes isolate one variable each:
| mode | model | harvest | what it measures |
|---|---|---|---|
| `baseline` | deepseek-chat | off | floor reference — V3 at its best |
| `reasoner` | deepseek-reasoner | off | raw R1 gain over V3 on reasoning |
| `reasoner-harvest` | deepseek-reasoner | on | R1 + the extra V3 harvest call |
Deltas:
- `baseline → reasoner` answers "is R1 worth the price on these
problems?"
- `reasoner → reasoner-harvest` answers "is the harvest call worth
its incremental cost?"
## Quickstart
```bash
# Dry-run — no API, smoke-test the wiring
npx tsx benchmarks/harvest/runner.ts --dry
# Full run (live DeepSeek, costs ~$0.20-0.60 for 6 tasks × 3 modes × 1 repeat)
export DEEPSEEK_API_KEY=sk-...
npx tsx benchmarks/harvest/runner.ts
# Tighter run with 3 repeats (~$0.60-2.00)
npx tsx benchmarks/harvest/runner.ts --repeats 3
# Only the hard tasks (skip the easy floor)
npx tsx benchmarks/harvest/runner.ts --task pseudoprime_base2
npx tsx benchmarks/harvest/runner.ts --task derangements_d7
npx tsx benchmarks/harvest/runner.ts --task euler_quadratic_break
# Bump per-call timeout (reasoner + harvest occasionally blow past the 120s default)
npx tsx benchmarks/harvest/runner.ts --timeout 600
# Per-run transcripts so you can reasonix replay / diff them
npx tsx benchmarks/harvest/runner.ts --repeats 3 --transcripts-dir transcripts/
# Render report
npx tsx benchmarks/harvest/report.ts benchmarks/harvest/results-*.json
```
## Tasks (v0.3 seed)
Split into two bands:
**Easy band** — V3 chat solves these, so baseline has a real pass rate and the bench has a reference floor.
| id | shape | why |
|---|---|---|
| `mod7_list` | number theory, 29-element list | R1 often tries enumeration first, then reaches for modular arithmetic — clean rejectedPaths signal |
| `flips_until_3heads` | probability, single integer | classic recurrence; R1 either derives or recalls, harvest should see hypotheses diverge |
| `three_hats` | logic puzzle, one-word answer | pure deduction chain, tests harvest's ability to extract the nested reasoning |
**Hard band** — picked specifically for known V3 failure modes. If R1 systematically beats V3 on these, and harvest further beats R1-only, we have our Pillar 2 story.
| id | shape | why V3 tends to fail |
|---|---|---|
| `pseudoprime_base2` | smallest Fermat pseudoprime to base 2 = **341** | V3 often answers 561 (Carmichael) or some other composite it remembers — R1 actually checks 2^n mod n |
| `derangements_d7` | D_7 = **1854** | V3 approximates via n!/e and rounds wrong, or recalls D_6/D_8; R1 uses the recurrence D_n=(n−1)(D_{n−1}+D_{n−2}) |
| `euler_quadratic_break` | smallest n where n²+n+41 is composite = **40** | V3 frequently confuses with n²−n+41 (first fails at 41); R1 checks small n systematically |
Adding a new task: see `tasks.ts`. Any checker that's deterministic is
fair game — extract numeric/list/text with regex, compare with set
equality or string matching.
## Non-goals
- **No LLM-as-judge.** Brittle and expensive; defeats the point of a
reproducible bench. If a checker is too hard to write deterministically,
the task doesn't belong here.
- **No tool-use tasks.** Those live in `tau-bench/`. Different story.
- **No multi-turn.** v0.3 harness is single-turn Q/A. Multi-turn reasoning
eval is separate scope.
- **No benchmark-data cherry-picking.** When results come in, we publish
them whether they validate Pillar 2 or not. "harvest didn't help on
these 3 tasks" is still useful information.
-82
View File
@@ -1,82 +0,0 @@
# Reasonix harvest eval (Pillar 2)
**Date:** 2026-04-21T16:44:21.011Z
**Tasks:** 6 · repeats × 1 · modes: baseline, reasoner, reasoner-harvest
**Reasonix version:** 0.2.2
## Summary by mode
| mode | runs | pass rate | cache hit | cost / run | harvest turns | subgoals | uncertainties |
|---|---:|---:|---:|---:|---:|---:|---:|
| baseline | 6 | 100% | 39.5% | $0.001371 | 0.0 | 0.0 | 0.0 |
| reasoner | 6 | 100% | 74.2% | $0.004170 | 0.0 | 0.0 | 0.0 |
| reasoner-harvest | 6 | 83% | 61.6% | $0.003304 | 0.8 | 2.8 | 1.3 |
## Deltas
- **baseline → reasoner**
- pass rate: 0pp
- cost: ×3.04 (each run costs more)
- harvest signal / run: 0.0 subgoals, 0.0 uncertainties
- **baseline → reasoner-harvest**
- pass rate: -17pp
- cost: ×2.41 (each run costs more)
- harvest signal / run: 2.8 subgoals, 1.3 uncertainties
## Per-task breakdown
| task | mode | rep | verdict | cache | cost | sg | un | note |
|---|---|---:|:---:|---:|---:|---:|---:|---|
| mod7_list | baseline | 1 | ✅ | 86.5% | $0.001361 | 0 | 0 | |
| mod7_list | reasoner | 1 | ✅ | 86.5% | $0.004797 | 0 | 0 | |
| mod7_list | reasoner-harvest | 1 | ✅ | 86.5% | $0.003045 | 4 | 2 | |
| flips_until_3heads | baseline | 1 | ✅ | 92.8% | $0.001198 | 0 | 0 | |
| flips_until_3heads | reasoner | 1 | ✅ | 92.8% | $0.002830 | 0 | 0 | |
| flips_until_3heads | reasoner-harvest | 1 | ✅ | 92.8% | $0.001691 | 4 | 0 | |
| three_hats | baseline | 1 | ✅ | 57.7% | $0.001514 | 0 | 0 | |
| three_hats | reasoner | 1 | ✅ | 57.7% | $0.009340 | 0 | 0 | |
| three_hats | reasoner-harvest | 1 | ✅ | 57.7% | $0.009651 | 3 | 2 | |
| pseudoprime_base2 | baseline | 1 | ✅ | 0.0% | $0.001894 | 0 | 0 | |
| pseudoprime_base2 | reasoner | 1 | ✅ | 75.3% | $0.003128 | 0 | 0 | |
| pseudoprime_base2 | reasoner-harvest | 1 | ❌ | 0.0% | $0.000000 | 0 | 0 | This operation was aborted |
| derangements_d7 | baseline | 1 | ✅ | 0.0% | $0.001273 | 0 | 0 | |
| derangements_d7 | reasoner | 1 | ✅ | 71.9% | $0.003492 | 0 | 0 | |
| derangements_d7 | reasoner-harvest | 1 | ✅ | 71.9% | $0.002843 | 3 | 2 | |
| euler_quadratic_break | baseline | 1 | ✅ | 0.0% | $0.000985 | 0 | 0 | |
| euler_quadratic_break | reasoner | 1 | ✅ | 61.0% | $0.001431 | 0 | 0 | |
| euler_quadratic_break | reasoner-harvest | 1 | ✅ | 61.0% | $0.002594 | 3 | 2 | |
## Scope
Unlike τ-bench-lite, these tasks are single-turn reasoning problems (no user simulator, no DB, no tool calls). Checkers are deterministic — regex + set / value compare, never an LLM judge. The point is to isolate whether the Pillar 2 harvest step adds measurable value above plain reasoner usage.
Interpretation: `baseline` (chat / V3) is a floor. `reasoner` shows the raw R1 gain. `reasoner-harvest` isolates the cost + quality delta from the extra V3 harvest call.
## Findings (v0.3, 18-run set)
Two bands of tasks tried (easy: mod7 / flips / hats; hard: pseudoprime341 / D_7 / Euler quadratic). The hard band was chosen for *known V3 failure modes*. Result:
1. **V3 chat passed all six tasks, including the three "hard" ones.** DeepSeek V3 knew 341 is the smallest base-2 pseudoprime, computed D_7=1854, and identified n=40 as the first Euler-polynomial failure. The tasks are well-known enough to be in training; the trap-answer variants (561, 265, 41) that the checkers specifically reject didn't fire.
2. **Reasoner cost 3.04× baseline for identical pass rates (6/6 both sides).** On this task set, R1 adds cost and latency without measurable quality. The cache-hit story *does* extend to reasoner (74.2% mean), so Pillar 1 generalizes to R1 — but that's not a Pillar 2 story.
3. **Harvest produced real signal** (mean 2.8 subgoals, 1.3 uncertainties per run where it fired) but didn't improve outcomes. One run hit the 300s timeout (bumped from 120s), suggesting reasoner-harvest latency is still unpredictable on some problems.
### What this tells us about Pillar 2 positioning
We've now given harvest two shots at showing answer-quality value on pure reasoning tasks. Both times V3 ate its lunch. This isn't a framework bug — it's a positioning signal:
- **On well-known math / logic / counting problems, DeepSeek V3 is strong enough that paying for R1 is not justified by accuracy.** Pillar 2's "smart preset" cost multiplier (10×) quoted in the README is real but for most single-question Q/A it buys nothing.
- **Harvest's plausible value surfaces are not "better math answers".** More likely: (a) transparency / auditability for developers, (b) planning support when tools are in the mix, (c) driving branch-sampling on cases where uncertainty correlates with wrongness. None of those are tested here.
### Recommendation
Don't ship v0.3 on the "harvest makes answers more correct" claim — the data doesn't support it. Two honest paths forward:
- **Reframe Pillar 2 as a developer-facing introspection feature** (debug visibility into R1's planning). Keep harvest opt-in; stop implying it improves accuracy on end-user tasks.
- **Move harvest eval to tool-use contexts** where uncertainty matters for *which tool to call next*, not *is this math right*. That's a new task shape — different harness, not a bigger task set here.
In either case, the next Reasonix release is better served by MCP client (Pillar 1 leverage across the ecosystem) than by a bigger harvest-bench data push.
### Notes
- Cache hit on baseline runs surprised me (39.5% mean). That's DeepSeek's *cross-session* prompt cache: the same system prompt ran many times across modes and runs warmed the server-side cache. Real cross-session evidence that Cache-First's value isn't only per-session.
- 5-subgoals cap still hit uniformly. `HarvestOptions.maxItems` default is 5; harvest is truncating. Moot unless we find a setting where that matters.
-229
View File
@@ -1,229 +0,0 @@
/** Render a harvest-bench results.json into a markdown report. CLI usage in README. */
import { readFileSync, writeFileSync } from "node:fs";
import { pathToFileURL } from "node:url";
import {
ALL_MODES,
type HarvestBenchReport,
type HarvestMode,
type HarvestRunResult,
} from "./types.js";
interface CliArgs {
input: string;
outPath: string;
}
function parseArgs(argv: string[]): CliArgs {
const out: CliArgs = { input: "", outPath: "benchmarks/harvest/report.md" };
const positional: string[] = [];
for (let i = 0; i < argv.length; i++) {
const a = argv[i];
if (a === "--out") out.outPath = argv[++i] ?? out.outPath;
else if (a && !a.startsWith("--")) positional.push(a);
}
out.input = positional[0] ?? "";
if (!out.input) {
throw new Error("usage: npx tsx benchmarks/harvest/report.ts <results.json> [--out report.md]");
}
return out;
}
interface Agg {
runs: number;
passes: number;
avgCache: number;
avgCost: number;
avgClaudeCost: number;
avgHarvestedTurns: number;
avgSubgoals: number;
avgUncertainties: number;
}
function aggregate(results: HarvestRunResult[]): Agg {
if (results.length === 0) {
return {
runs: 0,
passes: 0,
avgCache: 0,
avgCost: 0,
avgClaudeCost: 0,
avgHarvestedTurns: 0,
avgSubgoals: 0,
avgUncertainties: 0,
};
}
const passes = results.filter((r) => r.verdict === "pass").length;
const mean = (fn: (r: HarvestRunResult) => number) =>
results.reduce((s, r) => s + fn(r), 0) / results.length;
return {
runs: results.length,
passes,
avgCache: mean((r) => r.cacheHitRatio),
avgCost: mean((r) => r.costUsd),
avgClaudeCost: mean((r) => r.claudeEquivalentUsd),
avgHarvestedTurns: mean((r) => r.harvestedTurns),
avgSubgoals: mean((r) => r.totalSubgoals),
avgUncertainties: mean((r) => r.totalUncertainties),
};
}
export function renderReport(report: HarvestBenchReport): string {
const lines: string[] = [];
lines.push("# Reasonix harvest eval (Pillar 2)");
lines.push("");
lines.push(`**Date:** ${report.meta.date}`);
lines.push(
`**Tasks:** ${report.meta.taskCount} · repeats × ${report.meta.repeatsPerTask} · modes: ${report.meta.modesRun.join(", ")}`,
);
lines.push(`**Reasonix version:** ${report.meta.reasonixVersion}`);
lines.push("");
// Per-mode summary
lines.push("## Summary by mode");
lines.push("");
lines.push(
"| mode | runs | pass rate | cache hit | cost / run | harvest turns | subgoals | uncertainties |",
);
lines.push("|---|---:|---:|---:|---:|---:|---:|---:|");
for (const mode of ALL_MODES) {
const rs = report.results.filter((r) => r.mode === mode);
const a = aggregate(rs);
if (a.runs === 0) continue;
lines.push(
`| ${mode} | ${a.runs} | ${pct(a.passes, a.runs)} | ${pct1(a.avgCache)} | $${a.avgCost.toFixed(6)} | ${a.avgHarvestedTurns.toFixed(1)} | ${a.avgSubgoals.toFixed(1)} | ${a.avgUncertainties.toFixed(1)} |`,
);
}
lines.push("");
// Pairwise deltas that actually answer the question
lines.push("## Deltas");
lines.push("");
const modes = ALL_MODES.filter((m) => report.results.some((r) => r.mode === m));
if (modes.length >= 2) {
const baseline = aggregate(report.results.filter((r) => r.mode === modes[0]));
for (let i = 1; i < modes.length; i++) {
const mode = modes[i]!;
const agg = aggregate(report.results.filter((r) => r.mode === mode));
const passDelta =
agg.passes / Math.max(agg.runs, 1) - baseline.passes / Math.max(baseline.runs, 1);
const costRatio = baseline.avgCost > 0 ? agg.avgCost / baseline.avgCost : 0;
lines.push(`- **${modes[0]} → ${mode}**`);
lines.push(` - pass rate: ${(passDelta * 100).toFixed(0)}pp`);
lines.push(
` - cost: ×${costRatio.toFixed(2)} (each run costs ${costRatio > 1 ? "more" : "less"})`,
);
lines.push(
` - harvest signal / run: ${agg.avgSubgoals.toFixed(1)} subgoals, ${agg.avgUncertainties.toFixed(1)} uncertainties`,
);
lines.push("");
}
}
// Per-task breakdown
lines.push("## Per-task breakdown");
lines.push("");
const byTask = new Map<string, HarvestRunResult[]>();
for (const r of report.results) {
const list = byTask.get(r.taskId) ?? [];
list.push(r);
byTask.set(r.taskId, list);
}
lines.push("| task | mode | rep | verdict | cache | cost | sg | un | note |");
lines.push("|---|---|---:|:---:|---:|---:|---:|---:|---|");
for (const [taskId, runs] of byTask) {
for (const r of runs) {
const mark = r.verdict === "pass" ? "✅" : r.verdict === "fail" ? "❌" : "•";
lines.push(
`| ${taskId} | ${r.mode} | ${r.repeat} | ${mark} | ${pct1(r.cacheHitRatio)} | $${r.costUsd.toFixed(6)} | ${r.totalSubgoals} | ${r.totalUncertainties} | ${truncate(r.checkNote ?? "", 40)} |`,
);
}
}
lines.push("");
lines.push("## Scope");
lines.push("");
lines.push(
"Unlike τ-bench-lite, these tasks are single-turn reasoning problems (no user simulator, no DB, no tool calls). Checkers are deterministic — regex + set / value compare, never an LLM judge. The point is to isolate whether the Pillar 2 harvest step adds measurable value above plain reasoner usage.",
);
lines.push("");
lines.push(
"Interpretation: `baseline` (chat / V3) is a floor. `reasoner` shows the raw R1 gain. `reasoner-harvest` isolates the cost + quality delta from the extra V3 harvest call.",
);
return lines.join("\n");
}
/** Findings prose lives in report.md (hand-written after rendering); this stub keeps the function shape. */
export function renderFindings(_report: HarvestBenchReport): string {
return [
"",
"## Findings (v0.3, 18-run set)",
"",
"Two bands of tasks tried (easy: mod7 / flips / hats; hard: pseudoprime341 / D_7 / Euler quadratic). The hard band was chosen for *known V3 failure modes*. Result:",
"",
'1. **V3 chat passed all six tasks, including the three "hard" ones.** DeepSeek V3 knew 341 is the smallest base-2 pseudoprime, computed D_7=1854, and identified n=40 as the first Euler-polynomial failure. The tasks are well-known enough to be in training; the trap-answer variants (561, 265, 41) that the checkers specifically reject didn\'t fire.',
"2. **Reasoner cost 3.04× baseline for identical pass rates (6/6 both sides).** On this task set, R1 adds cost and latency without measurable quality. The cache-hit story *does* extend to reasoner (74.2% mean), so Pillar 1 generalizes to R1 — but that's not a Pillar 2 story.",
"3. **Harvest produced real signal** (mean 2.8 subgoals, 1.3 uncertainties per run where it fired) but didn't improve outcomes. One run hit the 300s timeout (bumped from 120s), suggesting reasoner-harvest latency is still unpredictable on some problems.",
"",
"### What this tells us about Pillar 2 positioning",
"",
"We've now given harvest two shots at showing answer-quality value on pure reasoning tasks. Both times V3 ate its lunch. This isn't a framework bug — it's a positioning signal:",
"",
'- **On well-known math / logic / counting problems, DeepSeek V3 is strong enough that paying for R1 is not justified by accuracy.** Pillar 2\'s "smart preset" cost multiplier (10×) quoted in the README is real but for most single-question Q/A it buys nothing.',
'- **Harvest\'s plausible value surfaces are not "better math answers".** More likely: (a) transparency / auditability for developers, (b) planning support when tools are in the mix, (c) driving branch-sampling on cases where uncertainty correlates with wrongness. None of those are tested here.',
"",
"### Recommendation",
"",
"Don't ship v0.3 on the \"harvest makes answers more correct\" claim — the data doesn't support it. Two honest paths forward:",
"",
"- **Reframe Pillar 2 as a developer-facing introspection feature** (debug visibility into R1's planning). Keep harvest opt-in; stop implying it improves accuracy on end-user tasks.",
"- **Move harvest eval to tool-use contexts** where uncertainty matters for *which tool to call next*, not *is this math right*. That's a new task shape — different harness, not a bigger task set here.",
"",
"In either case, the next Reasonix release is better served by MCP client (Pillar 1 leverage across the ecosystem) than by a bigger harvest-bench data push.",
"",
"### Notes",
"",
"- Cache hit on baseline runs surprised me (39.5% mean). That's DeepSeek's *cross-session* prompt cache: the same system prompt ran many times across modes and runs warmed the server-side cache. Real cross-session evidence that Cache-First's value isn't only per-session.",
"- 5-subgoals cap still hit uniformly. `HarvestOptions.maxItems` default is 5; harvest is truncating. Moot unless we find a setting where that matters.",
"",
].join("\n");
}
function pct(num: number, denom: number): string {
if (denom === 0) return "—";
return `${((num / denom) * 100).toFixed(0)}%`;
}
function pct1(x: number): string {
return `${(x * 100).toFixed(1)}%`;
}
function truncate(s: string, n: number): string {
return s.length > n ? `${s.slice(0, n)}…` : s;
}
async function main(): Promise<void> {
const args = parseArgs(process.argv.slice(2));
const raw = readFileSync(args.input, "utf8");
const report = JSON.parse(raw) as HarvestBenchReport;
const md = renderReport(report) + renderFindings(report);
writeFileSync(args.outPath, md, "utf8");
console.log(`wrote ${args.outPath} (${report.results.length} runs)`);
}
function isMain(): boolean {
const entry = process.argv[1];
if (!entry) return false;
return import.meta.url === pathToFileURL(entry).href;
}
if (isMain()) {
main().catch((err) => {
console.error(err);
process.exit(1);
});
}
// Suppress unused import warning — kept in scope so ALL_MODES order matches renderer iteration.
export type { HarvestMode };
-305
View File
@@ -1,305 +0,0 @@
{
"meta": {
"date": "2026-04-21T16:44:21.011Z",
"repeatsPerTask": 1,
"taskCount": 6,
"modesRun": [
"baseline",
"reasoner",
"reasoner-harvest"
],
"reasonixVersion": "0.2.2"
},
"results": [
{
"taskId": "mod7_list",
"mode": "baseline",
"repeat": 1,
"verdict": "pass",
"finalAgentMessage": "Alright, let's go step-by-step.\n\n---\n\n## **Step 1: Problem restatement**\nWe want positive integers \\( n \\leq 100 \\) such that \n\\[\nn^2 + n + 1 \\equiv 0 \\pmod{7}.\n\\]\n\n---\n\n## **Step 2: Try residues modulo 7**\nLet \\( n \\equiv r \\pmod{7} \\), where \\( r \\in \\{0, 1, 2, 3, 4, 5, 6\\} \\).\n\nWe compute \\( r^2 + r + 1 \\mod 7 \\):\n\n- \\( r = 0 \\): \\( 0 + 0 + 1 = 1 \\) → not divisible by 7.\n- \\( r = 1 \\): \\( 1 + 1 + 1 = 3 \\) → no.\n- \\( r = 2 \\): \\( 4 + 2 + 1 = 7 \\equiv 0 \\) → yes.\n- \\( r = 3 \\): \\( 9 + 3 + 1 = 13 \\equiv 6 \\) → no.\n- \\( r = 4 \\): \\( 16 + 4 + 1 = 21 \\equiv 0 \\) → yes.\n- \\( r = 5 \\): \\( 25 + 5 + 1 = 31 \\equiv 3 \\) → no.\n- \\( r = 6 \\): \\( 36 + 6 + 1 = 43 \\equiv 1 \\) → no.\n\nSo \\( n \\equiv 2 \\pmod{7} \\) or \\( n \\equiv 4 \\pmod{7} \\).\n\n---\n\n## **Step 3: General form**\n\\[\nn \\equiv 2 \\pmod{7} \\quad \\text{or} \\quad n \\equiv 4 \\pmod{7}.\n\\]\n\nThat means \\( n = 7k + 2 \\) or \\( n = 7k + 4 \\) for some integer \\( k \\ge 0 \\).\n\n---\n\n## **Step 4: Positive integers \\( n \\leq 100 \\)**\n**Case 1:** \\( n = 7k + 2 \\), \\( n \\leq 100 \\), \\( k \\ge 0 \\).\n\n\\( 7k + 2 \\leq 100 \\) → \\( 7k \\leq 98 \\) → \\( k \\leq 14 \\).\n\nSo \\( k = 0, 1, 2, \\dots, 14 \\) gives \\( n = 2, 9, 16, \\dots, 100 \\).\n\nCheck \\( n=100 \\): \\( 7 \\times 14 + 2 = 98 + 2 = 100 \\) okay.\n\n---\n\n**Case 2:** \\( n = 7k + 4 \\), \\( n \\leq 100 \\), \\( k \\ge 0 \\).\n\n\\( 7k + 4 \\leq 100 \\) → \\( 7k \\leq 96 \\) → \\( k \\leq 13 \\) (since \\( 7 \\times 13 = 91 \\), \\( 91+4=95 \\), \\( 7\\times14=98 \\) → \\( 98+4=102>100 \\)).\n\nSo \\( k = 0, 1, 2, \\dots, 13 \\) gives \\( n = 4, 11, 18, \\dots, 95 \\).\n\n---\n\n## **Step 5: List all such \\( n \\leq 100 \\)**\nFrom case 1: \\( 2, 9, 16, 23, 30, 37, 44, 51, 58, 65, 72, 79, 86, 93, 100 \\).\n\nFrom case 2: \\( 4, 11, 18, 25, 32, 39, 46, 53, 60, 67, 74, 81, 88, 95 \\).\n\nCombine and sort:\n\n\\[\n2, 4, 9, 11, 16, 18, 23, 25, 30, 32, 37, 39, 44, 46, 51, 53, 58, 60, 65, 67, 72, 74, 79, 81, 86, 88, 93, 95, 100.\n\\]\n\n---\n\n## **Step 6: Check count**\nEach sequence has 15 and 14 terms respectively, total \\( 15 + 14 = 29 \\) numbers.\n\nCheck: \\( n=2 \\) works? \\( 4+2+1=7 \\) yes. \\( n=4 \\) works? \\( 16+4+1=21 \\) yes. \\( n=100 \\) works? \\( 10000+100+1=10101 \\), divide by 7: \\( 10101/7 = 1443 \\) yes.\n\n---\n\n**Final answer:**\n\\[\n\\boxed{2, 4, 9, 11, 16, 18, 23, 25, 30, 32, 37, 39, 44, 46, 51, 53, 58, 60, 65, 67, 72, 74, 79, 81, 86, 88, 93, 95, 100}\n\\]\n\n---\n\nAnswer: 2, 4, 9, 11, 16, 18, 23, 25, 30, 32, 37, 39, 44, 46, 51, 53, 58, 60, 65, 67, 72, 74, 79, 81, 86, 88, 93, 95, 100",
"turns": 1,
"cacheHitRatio": 0.8648648648648649,
"costUsd": 0.0013612800000000003,
"claudeEquivalentUsd": 0.018687,
"harvestedTurns": 0,
"totalSubgoals": 0,
"totalUncertainties": 0,
"totalHypotheses": 0,
"totalRejectedPaths": 0
},
{
"taskId": "mod7_list",
"mode": "reasoner",
"repeat": 1,
"verdict": "pass",
"finalAgentMessage": "The condition \\(n^2 + n + 1\\) divisible by 7 is equivalent to \\(n^2 + n + 1 \\equiv 0 \\pmod{7}\\). Testing residues modulo 7:\n\n- \\(n \\equiv 0: 0+0+1 \\equiv 1\\) \n- \\(n \\equiv 1: 1+1+1 \\equiv 3\\) \n- \\(n \\equiv 2: 4+2+1 \\equiv 7 \\equiv 0\\) \n- \\(n \\equiv 3: 9+3+1 \\equiv 13 \\equiv 6\\) \n- \\(n \\equiv 4: 16+4+1 \\equiv 21 \\equiv 0\\) \n- \\(n \\equiv 5: 25+5+1 \\equiv 31 \\equiv 3\\) \n- \\(n \\equiv 6: 36+6+1 \\equiv 43 \\equiv 1\\)\n\nThus, \\(n \\equiv 2\\) or \\(n \\equiv 4 \\pmod{7}\\) are the solutions modulo 7. For positive integers \\(n \\leq 100\\), we list all numbers congruent to 2 or 4 modulo 7 in increasing order.\n\nAnswer: 2, 4, 9, 11, 16, 18, 23, 25, 30, 32, 37, 39, 44, 46, 51, 53, 58, 60, 65, 67, 72, 74, 79, 81, 86, 88, 93, 95, 100",
"turns": 1,
"cacheHitRatio": 0.8648648648648649,
"costUsd": 0.00479742,
"claudeEquivalentUsd": 0.032982,
"harvestedTurns": 0,
"totalSubgoals": 0,
"totalUncertainties": 0,
"totalHypotheses": 0,
"totalRejectedPaths": 0
},
{
"taskId": "mod7_list",
"mode": "reasoner-harvest",
"repeat": 1,
"verdict": "pass",
"finalAgentMessage": "The congruence \\(n^2 + n + 1 \\equiv 0 \\pmod{7}\\) is solved by testing residues modulo 7. The solutions are \\(n \\equiv 2\\) and \\(n \\equiv 4 \\pmod{7}\\). For positive integers \\(n \\le 100\\), these yield \\(n = 7k + 2\\) with \\(k = 0, 1, \\dots, 14\\) and \\(n = 7k + 4\\) with \\(k = 0, 1, \\dots, 13\\).\n\nAnswer: 2, 4, 9, 11, 16, 18, 23, 25, 30, 32, 37, 39, 44, 46, 51, 53, 58, 60, 65, 67, 72, 74, 79, 81, 86, 88, 93, 95, 100",
"turns": 1,
"cacheHitRatio": 0.8648648648648649,
"costUsd": 0.00304542,
"claudeEquivalentUsd": 0.020982,
"harvestedTurns": 1,
"totalSubgoals": 4,
"totalUncertainties": 2,
"totalHypotheses": 2,
"totalRejectedPaths": 2
},
{
"taskId": "flips_until_3heads",
"mode": "baseline",
"repeat": 1,
"verdict": "pass",
"finalAgentMessage": "Alright, let's reason through this step-by-step.\n\n---\n\n## **Step 1: Define states**\nLet’s define states based on how many consecutive heads we have at the moment.\n\n- \\( E_0 \\): Expected flips to reach 3 heads in a row starting from 0 consecutive heads (or just starting, or after a tail).\n- \\( E_1 \\): Expected flips to reach 3 heads in a row starting from 1 consecutive head.\n- \\( E_2 \\): Expected flips to reach 3 heads in a row starting from 2 consecutive heads.\n\nWe want \\( E_0 \\).\n\n---\n\n## **Step 2: Transition equations**\nFrom \\( E_0 \\):\n- Flip H (prob \\( \\frac12 \\)) → go to state \\( E_1 \\), 1 flip used.\n- Flip T (prob \\( \\frac12 \\)) → stay in \\( E_0 \\), 1 flip used.\n\nSo:\n\\[\nE_0 = \\frac12 (1 + E_1) + \\frac12 (1 + E_0)\n\\]\n\n---\n\nFrom \\( E_1 \\) (already have 1 head):\n- Flip H (prob \\( \\frac12 \\)) → go to state \\( E_2 \\), 1 flip used.\n- Flip T (prob \\( \\frac12 \\)) → go to state \\( E_0 \\), 1 flip used.\n\nSo:\n\\[\nE_1 = \\frac12 (1 + E_2) + \\frac12 (1 + E_0)\n\\]\n\n---\n\nFrom \\( E_2 \\) (already have 2 heads):\n- Flip H (prob \\( \\frac12 \\)) → done (3 heads in a row), 1 flip used.\n- Flip T (prob \\( \\frac12 \\)) → go to state \\( E_0 \\), 1 flip used.\n\nSo:\n\\[\nE_2 = \\frac12 (1 + 0) + \\frac12 (1 + E_0)\n\\]\n\\[\nE_2 = \\frac12 \\cdot 1 + \\frac12 (1 + E_0) \\quad\\text{(Wait, careful:)}\n\\]\nActually: \nIf H: \\( 1 \\) flip and done. \nIf T: \\( 1 \\) flip and then \\( E_0 \\) more.\n\nSo:\n\\[\nE_2 = \\frac12 \\cdot 1 + \\frac12 (1 + E_0)\n\\]\nCheck: \nH: 1 flip → total 1, done. Contribution: \\( \\frac12 \\times 1 \\). \nT: 1 flip + \\( E_0 \\) more → total \\( 1 + E_0 \\). Contribution: \\( \\frac12 \\times (1 + E_0) \\).\n\nYes:\n\\[\nE_2 = \\frac12 \\cdot 1 + \\frac12 (1 + E_0) = \\frac12 + \\frac12 + \\frac12 E_0 = 1 + \\frac{E_0}{2}.\n\\]\n\n---\n\n## **Step 3: Solve system**\nWe have:\n\n(1) \\( E_0 = \\frac12 (1 + E_1) + \\frac12 (1 + E_0) \\) \nSimplify: \\( E_0 = 1 + \\frac12 E_1 + \\frac12 E_0 \\) \nMultiply by 2: \\( 2E_0 = 2 + E_1 + E_0 \\) \nSo \\( E_0 - E_1 = 2 \\) … (Eq A)\n\n---\n\n(2) \\( E_1 = \\frac12 (1 + E_2) + \\frac12 (1 + E_0) \\) \nSimplify: \\( E_1 = 1 + \\frac12 E_2 + \\frac12 E_0 \\) … (Eq B)\n\n---\n\n(3) \\( E_2 = 1 + \\frac12 E_0 \\) … (Eq C)\n\n---\n\nFrom Eq C into Eq B:\n\\[\nE_1 = 1 + \\frac12 \\left( 1 + \\frac12 E_0 \\right) + \\frac12 E_0\n\\]\n\\[\nE_1 = 1 + \\frac12 + \\frac14 E_0 + \\frac12 E_0\n\\]\n\\[\nE_1 = \\frac32 + \\frac34 E_0\n\\]\n\n---\n\nFrom Eq A: \\( E_0 - E_1 = 2 \\) \nSubstitute \\( E_1 \\):\n\\[\nE_0 - \\left( \\frac32 + \\frac34 E_0 \\right) = 2\n\\]\n\\[\nE_0 - \\frac32 - \\frac34 E_0 = 2\n\\]\n\\[\n\\frac14 E_0 - \\frac32 = 2\n\\]\n\\[\n\\frac14 E_0 = 2 + \\frac32 = \\frac72\n\\]\n\\[\nE_0 = 14\n\\]\n\n---\n\n## **Step 4: Conclusion**\nThe expected number of flips until we get 3 heads in a row is \\( 14 \\).\n\n---\n\n**Answer:** 14",
"turns": 1,
"cacheHitRatio": 0.927536231884058,
"costUsd": 0.00119823,
"claudeEquivalentUsd": 0.016467,
"harvestedTurns": 0,
"totalSubgoals": 0,
"totalUncertainties": 0,
"totalHypotheses": 0,
"totalRejectedPaths": 0
},
{
"taskId": "flips_until_3heads",
"mode": "reasoner",
"repeat": 1,
"verdict": "pass",
"finalAgentMessage": "The expected number of flips required to get three consecutive heads is 14, derived from solving the system of linear equations for the Markov chain states representing the current streak of heads.\n\nAnswer: 14",
"turns": 1,
"cacheHitRatio": 0.927536231884058,
"costUsd": 0.00283024,
"claudeEquivalentUsd": 0.019512,
"harvestedTurns": 0,
"totalSubgoals": 0,
"totalUncertainties": 0,
"totalHypotheses": 0,
"totalRejectedPaths": 0
},
{
"taskId": "flips_until_3heads",
"mode": "reasoner-harvest",
"repeat": 1,
"verdict": "pass",
"finalAgentMessage": "The expected number of flips until three consecutive heads appear is 14.\n\nAnswer: 14",
"turns": 1,
"cacheHitRatio": 0.927536231884058,
"costUsd": 0.00169144,
"claudeEquivalentUsd": 0.011712,
"harvestedTurns": 1,
"totalSubgoals": 4,
"totalUncertainties": 0,
"totalHypotheses": 2,
"totalRejectedPaths": 0
},
{
"taskId": "three_hats",
"mode": "baseline",
"repeat": 1,
"verdict": "pass",
"finalAgentMessage": "Let's break this down step by step.\n\n---\n\n**Step 1: Understanding the setup** \nThree people: A (first), B (second), C (third). \nEach hat is red (R) or blue (B). \nThey know: at least one hat is red. \nEach sees the other two hats, not their own. \nThey are asked in order: \"Do you know your hat color?\" \nA answers no, B answers no, C answers yes. \nWe want C’s hat color.\n\n---\n\n**Step 2: From A’s perspective when asked** \nA sees B and C. \nIf A had seen two blue hats, then A would know: \"At least one red hat means my hat must be red.\" \nSo A says \"no\" → A did **not** see two blue hats. \nThus A sees at least one red hat on {B, C}.\n\nPossible cases for what A sees (B, C): \n(R, R), (R, B), (B, R) — all have at least one red.\n\n---\n\n**Step 3: B’s reasoning when asked** \nB hears A say \"no\". \nB sees A and C. \n\nLet’s consider B’s possible deductions from A’s \"no\": \nB knows: If A had seen two blues, A would have said yes. Since A said no, A saw at least one red among B and C. \nBut B sees A and C. \n\nFrom B’s viewpoint: \n- If B saw C with blue and A with blue, then B would know: \"A saw me and C both blue → impossible because A said no.\" But B doesn’t see that because if B saw A blue and C blue, then B would know his own hat must be red (since at least one red total). But then B would answer yes. \nSo B’s \"no\" means B did **not** see A and C both blue. \n\nAlso, B considers: Could my hat be blue? Let’s check: \nSuppose B sees A red, C blue. Then B thinks: \"If my hat were blue, then A would have seen (B blue, C blue) → A would have said yes. But A said no, so my hat cannot be blue.\" \nSo if B saw (A red, C blue), B would deduce: \"My hat must be red.\" Then B would answer yes. \nBut B said no → so B did **not** see (A red, C blue).\n\nSimilarly, if B saw (A blue, C red): \nThen B thinks: \"If my hat were blue, then A would have seen (B blue, C red) → that’s fine (A sees one red on C), so A would still say no. If my hat were red, then A would see (B red, C red) → A would still say no. So I don’t know.\" That’s consistent with B saying no. \n\nIf B saw (A red, C red): \nThen B thinks: \"If my hat were blue, A sees (B blue, C red) → A says no. If my hat were red, A sees (B red, C red) → A says no. So I don’t know.\" That’s also consistent with B saying no.\n\nSo B says no in cases: \nB sees (A blue, C red) or (A red, C red). \nB would say yes if B saw (A red, C blue) — but that didn’t happen. \n\n---\n\n**Step 4: C’s reasoning** \nC hears A says no, B says no. \nC sees A and B. \n\nFrom C’s viewpoint: \nLet’s list all possible (A, B, C) hat colorings with at least one red, consistent with A’s \"no\" (which we already incorporated: A sees at least one red on B/C) and B’s \"no\" (meaning B didn’t see A red, C blue — because that would make B know).\n\nPossible cases for (A, B) that C could see: \n\n1. C sees (A blue, B red): \n Then C thinks: \n - If C were blue: (A blue, B red, C blue) → A sees (B red, C blue) → A says no. B sees (A blue, C blue) → B sees two blues? Wait, B sees A blue, C blue → then B knows his own hat is red (since at least one red total) → B would say yes. But B said no → contradiction. So C cannot be blue. \n So C must be red. \n\n2. C sees (A red, B blue): \n Then C thinks: \n - If C were blue: (A red, B blue, C blue) → A sees (B blue, C blue) → A would say yes (since at least one red total means A’s hat must be red). But A said no → contradiction. So C cannot be blue. \n So C must be red. \n\n3. C sees (A red, B red): \n Then C thinks: \n - If C were blue: (A red, B red, C blue) → A sees (B red, C blue) → A says no. B sees (A red, C blue) → B sees A red, C blue → earlier we said: If B sees A red, C blue, then B would deduce his own hat is red (reasoning: if B were blue, A would have seen two blues and said yes, but A said no, so B can’t be blue) → so B would say yes. But B actually said no → contradiction. So C cannot be blue. \n - If C were red: (A red, B red, C red) → A sees (B red, C red) → A says no. B sees (A red, C red) → B says no. Works fine. \n\nSo in all cases C sees for (A, B), C can deduce C’s hat is **red** because assuming C is blue leads to contradiction with B’s \"no\" (in cases 1 and 3) or with A’s \"no\" (in case 2).\n\n---\n\n**Step 5: Conclusion** \nC answers yes, and C’s hat must be red.\n\n---\n\nAnswer: red",
"turns": 1,
"cacheHitRatio": 0.5765765765765766,
"costUsd": 0.0015142700000000003,
"claudeEquivalentUsd": 0.020748,
"harvestedTurns": 0,
"totalSubgoals": 0,
"totalUncertainties": 0,
"totalHypotheses": 0,
"totalRejectedPaths": 0
},
{
"taskId": "three_hats",
"mode": "reasoner",
"repeat": 1,
"verdict": "pass",
"finalAgentMessage": "Answer: red",
"turns": 1,
"cacheHitRatio": 0.5765765765765766,
"costUsd": 0.009340119999999999,
"claudeEquivalentUsd": 0.064068,
"harvestedTurns": 0,
"totalSubgoals": 0,
"totalUncertainties": 0,
"totalHypotheses": 0,
"totalRejectedPaths": 0
},
{
"taskId": "three_hats",
"mode": "reasoner-harvest",
"repeat": 1,
"verdict": "pass",
"finalAgentMessage": "The third person deduces their hat color based on the previous responses. Since the first two answer \"no,\" it implies they each see at least one red hat and cannot determine their own color. Specifically, the second person's \"no\" indicates they see the third person's hat as red; otherwise, they would have known their own hat color. Therefore, the third person's hat must be red.\n\nAnswer: red",
"turns": 1,
"cacheHitRatio": 0.5765765765765766,
"costUsd": 0.0096511,
"claudeEquivalentUsd": 0.066198,
"harvestedTurns": 1,
"totalSubgoals": 3,
"totalUncertainties": 2,
"totalHypotheses": 3,
"totalRejectedPaths": 3
},
{
"taskId": "pseudoprime_base2",
"mode": "baseline",
"repeat": 1,
"verdict": "pass",
"finalAgentMessage": "Alright, let's go step-by-step.\n\n---\n\n**Step 1: Understanding the problem**\n\nWe want the smallest composite integer \\( n > 1 \\) such that\n\n\\[\n2^n \\equiv 2 \\pmod{n}.\n\\]\n\nEquivalently, \\( 2^{n-1} \\equiv 1 \\pmod{n} \\) for composite \\( n \\).\n\nThis means \\( n \\) is a **Fermat pseudoprime to base 2**.\n\nWe check composite numbers starting from the smallest.\n\n---\n\n**Step 2: Check small composites**\n\n- \\( n = 4 \\): composite. \n\\( 2^4 = 16 \\), \\( 16 \\mod 4 = 0 \\), not \\( 2 \\). So \\( 2^4 \\equiv 0 \\not\\equiv 2 \\pmod{4} \\). Fails.\n\n- \\( n = 6 \\): composite. \n\\( 2^6 = 64 \\), \\( 64 \\mod 6 = 4 \\), not \\( 2 \\). Fails.\n\n- \\( n = 8 \\): composite. \n\\( 2^8 = 256 \\), \\( 256 \\mod 8 = 0 \\), not \\( 2 \\). Fails.\n\n- \\( n = 9 \\): composite. \n\\( 2^9 = 512 \\), \\( 512 \\mod 9 \\): \n\\( 512 \\div 9 \\), \\( 9 \\times 56 = 504 \\), remainder \\( 8 \\), not \\( 2 \\). Fails.\n\n- \\( n = 10 \\): composite. \n\\( 2^{10} = 1024 \\), \\( 1024 \\mod 10 = 4 \\), not \\( 2 \\). Fails.\n\n---\n\n**Step 3: Try n = 15**\n\n\\( n = 15 \\): composite. \n\\( 2^{15} = 32768 \\). \nCheck mod 15: \nWe can use mod arithmetic: \n\\( 2^4 = 16 \\equiv 1 \\pmod{15} \\)?? Wait, check: \\( 16 \\mod 15 = 1 \\), yes. \nSo \\( 2^{15} = (2^4)^3 \\times 2^3 = 1^3 \\times 8 = 8 \\pmod{15} \\). \nSo \\( 2^{15} \\equiv 8 \\not\\equiv 2 \\pmod{15} \\). Fails.\n\n---\n\n**Step 4: Try n = 21**\n\n\\( n = 21 \\): composite. \nMod 21: \n\\( 2^6 = 64 \\equiv 1 \\pmod{21} \\)? Check: \\( 64 \\div 21 = 3 \\times 21 = 63 \\), remainder 1, yes. \nSo \\( 2^{21} = (2^6)^3 \\times 2^3 \\equiv 1^3 \\times 8 = 8 \\pmod{21} \\). Not 2. Fails.\n\n---\n\n**Step 5: Try n = 22**\n\n\\( n = 22 \\): composite. \nUse mod 22: \nEuler’s totient not needed, just check order: \n\\( 2^5 = 32 \\equiv 10 \\pmod{22} \\) \n\\( 2^{10} = (2^5)^2 \\equiv 10^2 = 100 \\equiv 12 \\pmod{22} \\) \n\\( 2^{11} \\equiv 24 \\equiv 2 \\pmod{22} \\) \nSo \\( 2^{22} = (2^{11})^2 \\equiv 2^2 = 4 \\pmod{22} \\). Not 2. Fails.\n\n---\n\n**Step 6: Try n = 25**\n\n\\( n = 25 \\): composite. \nCheck mod 25: \n\\( 2^{10} = 1024 \\equiv 24 \\pmod{25} \\) (since \\( 1000 \\equiv 0 \\), \\( 24 \\equiv -1 \\)) \nActually check: \\( 1024 - 1000 = 24 \\), yes \\( 24 \\equiv -1 \\). \nSo \\( 2^{20} \\equiv 1 \\pmod{25} \\). \nThus \\( 2^{25} = 2^{20} \\times 2^5 \\equiv 1 \\times 32 = 7 \\pmod{25} \\). Not 2. Fails.\n\n---\n\n**Step 7: Known smallest base-2 Fermat pseudoprime**\n\nFrom known number theory facts: \nThe smallest Fermat pseudoprime to base 2 is \\( n = 341 \\). \nBut let's check smaller ones just in case I’m skipping one.\n\n---\n\n**Step 8: Try n = 91**\n\n91 = 7 × 13. \nCheck mod 7: \\( 2^{91} \\equiv (2^6)^{15} \\times 2^1 \\equiv 1^{15} \\times 2 = 2 \\pmod{7} \\). \nCheck mod 13: \\( 2^{12} \\equiv 1 \\pmod{13} \\), \n\\( 91 = 12 \\times 7 + 7 \\), so \\( 2^{91} \\equiv 2^7 = 128 \\equiv 11 \\pmod{13} \\). \nFor \\( 2^{91} \\equiv 2 \\pmod{91} \\), we need \\( 2^{91} \\equiv 2 \\) mod 7 and mod 13. \nMod 13 we got 11, not 2. So fails.\n\n---\n\n**Step 9: Try n = 341**\n\n341 = 11 × 31. \nCheck mod 11: \\( 2^{10} \\equiv 1 \\pmod{11} \\), \n\\( 341 = 10 \\times 34 + 1 \\), so \\( 2^{341} \\equiv 2^1 = 2 \\pmod{11} \\). Good. \nCheck mod 31: \\( 2^5 = 32 \\equiv 1 \\pmod{31} \\), \n\\( 341 = 5 \\times 68 + 1 \\), so \\( 2^{341} \\equiv 2^1 = 2 \\pmod{31} \\). \nSo \\( 2^{341} \\equiv 2 \\) mod 11 and mod 31, hence mod 341. \nThus \\( 341 \\) works.\n\n---\n\n**Step 10: Check smaller than 341**\n\nKnown list: 341 is smallest. Let’s check a candidate like 121 = 11^2: \n\\( 2^{121} \\mod 121 \\): \nMod 11: \\( 2^{10} \\equiv 1 \\), \\( 121 = 10 \\times 12 + 1 \\), so \\( 2^{121} \\equiv 2 \\pmod{11} \\). \nBut for modulus 121, need more: \nActually, \\( 2^{110} \\equiv 1 \\pmod{121} \\) by Euler’s theorem? Not exactly, but known: 121 is not a pseudoprime base 2. Quick check: \n\\( 2^{121} - 2 \\) divisible by 121? Probably not. Let’s skip detailed check; known fact is 341 is smallest.\n\n---\n\n**Step 11: Verify no smaller composite works**\n\nFrom known sequence A001567: \nFirst few base-2 Fermat pseudoprimes: 341, 561, 645, 1105, … \nSo smallest is 341.\n\n---\n\n**Step 12: Conclusion**\n\nThe smallest composite \\( n > 1 \\) with \\( 2^n \\equiv 2 \\pmod{n} \\) is \\( n = 341 \\).\n\n---\n\n**Answer:** 341",
"turns": 1,
"cacheHitRatio": 0,
"costUsd": 0.0018940500000000002,
"claudeEquivalentUsd": 0.02577,
"harvestedTurns": 0,
"totalSubgoals": 0,
"totalUncertainties": 0,
"totalHypotheses": 0,
"totalRejectedPaths": 0
},
{
"taskId": "pseudoprime_base2",
"mode": "reasoner",
"repeat": 1,
"verdict": "pass",
"finalAgentMessage": "The smallest composite integer \\(n > 1\\) satisfying \\(2^n \\equiv 2 \\pmod{n}\\) is \\(n = 341\\). This is composite (\\(341 = 11 \\times 31\\)), and it satisfies the congruence because \\(2^{341} \\equiv 2 \\pmod{11}\\) and \\(2^{341} \\equiv 2 \\pmod{31}\\) by Fermat's little theorem, implying \\(2^{341} \\equiv 2 \\pmod{341}\\). All smaller composite integers (e.g., 4, 6, 8, 9, 10, 15, 21) fail to satisfy the condition.\n\nAnswer: 341",
"turns": 1,
"cacheHitRatio": 0.7529411764705882,
"costUsd": 0.0031281200000000003,
"claudeEquivalentUsd": 0.02154,
"harvestedTurns": 0,
"totalSubgoals": 0,
"totalUncertainties": 0,
"totalHypotheses": 0,
"totalRejectedPaths": 0
},
{
"taskId": "pseudoprime_base2",
"mode": "reasoner-harvest",
"repeat": 1,
"verdict": "fail",
"checkNote": "This operation was aborted",
"finalAgentMessage": "",
"turns": 0,
"cacheHitRatio": 0,
"costUsd": 0,
"claudeEquivalentUsd": 0,
"harvestedTurns": 0,
"totalSubgoals": 0,
"totalUncertainties": 0,
"totalHypotheses": 0,
"totalRejectedPaths": 0,
"errorMessage": "This operation was aborted"
},
{
"taskId": "derangements_d7",
"mode": "baseline",
"repeat": 1,
"verdict": "pass",
"finalAgentMessage": "Alright, let's go step-by-step.\n\n---\n\n**Step 1: Understanding the problem**\n\nWe want the number of permutations of \\(\\{1, 2, 3, 4, 5, 6, 7\\}\\) with **no fixed points**. \nA fixed point means \\(\\pi(i) = i\\) for some \\(i\\). \nA permutation with no fixed points is called a **derangement**. \nThe number of derangements of \\(n\\) elements is denoted \\(D_n\\) or \\(!n\\).\n\n---\n\n**Step 2: Formula for derangements**\n\nThe formula for \\(D_n\\) is:\n\n\\[\nD_n = n! \\sum_{k=0}^{n} \\frac{(-1)^k}{k!}\n\\]\n\nFor \\(n=7\\):\n\n\\[\nD_7 = 7! \\left( \\frac{1}{0!} - \\frac{1}{1!} + \\frac{1}{2!} - \\frac{1}{3!} + \\frac{1}{4!} - \\frac{1}{5!} + \\frac{1}{6!} - \\frac{1}{7!} \\right)\n\\]\n\n---\n\n**Step 3: Compute step-by-step**\n\nFirst, \\(7! = 5040\\).\n\nNow compute the sum:\n\n\\[\n\\sum_{k=0}^{7} \\frac{(-1)^k}{k!} \n= 1 - 1 + \\frac{1}{2} - \\frac{1}{6} + \\frac{1}{24} - \\frac{1}{120} + \\frac{1}{720} - \\frac{1}{5040}\n\\]\n\nLet's compute term-by-term:\n\n- \\(1 - 1 = 0\\)\n- \\(0 + 0.5 = 0.5\\)\n- \\(0.5 - \\frac{1}{6} \\approx 0.5 - 0.1666667 = 0.3333333\\)\n- \\(0.3333333 + \\frac{1}{24} \\approx 0.3333333 + 0.0416667 = 0.375\\)\n- \\(0.375 - \\frac{1}{120} \\approx 0.375 - 0.0083333 = 0.3666667\\)\n- \\(0.3666667 + \\frac{1}{720} \\approx 0.3666667 + 0.0013889 = 0.3680556\\)\n- \\(0.3680556 - \\frac{1}{5040} \\approx 0.3680556 - 0.0001984 = 0.3678572\\)\n\nSo the sum is approximately \\(0.367857142857...\\)\n\n---\n\n**Step 4: Multiply by \\(7!\\)**\n\n\\[\nD_7 = 5040 \\times 0.367857142857\\ldots\n\\]\n\nLet's compute exactly using fractions:\n\n\\[\n\\sum_{k=0}^{7} \\frac{(-1)^k}{k!} \n= \\frac{1}{2!} - \\frac{1}{3!} + \\frac{1}{4!} - \\frac{1}{5!} + \\frac{1}{6!} - \\frac{1}{7!}\n\\]\n\nWrite with common denominator \\(7! = 5040\\):\n\n- \\(\\frac{1}{2!} = \\frac{2520}{5040}\\)\n- \\(\\frac{1}{3!} = \\frac{840}{5040}\\)\n- \\(\\frac{1}{4!} = \\frac{210}{5040}\\)\n- \\(\\frac{1}{5!} = \\frac{42}{5040}\\)\n- \\(\\frac{1}{6!} = \\frac{7}{5040}\\)\n- \\(\\frac{1}{7!} = \\frac{1}{5040}\\)\n\nNow alternate signs:\n\n\\[\n\\left( \\frac{2520}{5040} - \\frac{840}{5040} \\right) \n= \\frac{1680}{5040}\n\\]\n\\[\n\\frac{1680}{5040} + \\frac{210}{5040} = \\frac{1890}{5040}\n\\]\n\\[\n\\frac{1890}{5040} - \\frac{42}{5040} = \\frac{1848}{5040}\n\\]\n\\[\n\\frac{1848}{5040} + \\frac{7}{5040} = \\frac{1855}{5040}\n\\]\n\\[\n\\frac{1855}{5040} - \\frac{1}{5040} = \\frac{1854}{5040}\n\\]\n\nSo the sum is \\(\\frac{1854}{5040}\\).\n\n---\n\n**Step 5: Multiply by \\(7!\\)**\n\n\\[\nD_7 = 5040 \\times \\frac{1854}{5040} = 1854\n\\]\n\n---\n\n**Step 6: Quick check with known derangement numbers**\n\nKnown small derangements: \n\\(D_1 = 0, D_2 = 1, D_3 = 2, D_4 = 9, D_5 = 44, D_6 = 265, D_7 = 1854\\). \nYes, matches known sequence.\n\n---\n\n**Final answer:**\n\nAnswer: 1854",
"turns": 1,
"cacheHitRatio": 0,
"costUsd": 0.00127253,
"claudeEquivalentUsd": 0.017292,
"harvestedTurns": 0,
"totalSubgoals": 0,
"totalUncertainties": 0,
"totalHypotheses": 0,
"totalRejectedPaths": 0
},
{
"taskId": "derangements_d7",
"mode": "reasoner",
"repeat": 1,
"verdict": "pass",
"finalAgentMessage": "The number of derangements of \\(n\\) distinct objects, denoted \\(D_n\\), counts permutations with no fixed points. For \\(n = 7\\), this can be computed using the recurrence \\(D_n = (n-1)(D_{n-1} + D_{n-2})\\) with initial values \\(D_1 = 0\\) and \\(D_2 = 1\\). \nThus: \n\\(D_3 = 2(1+0) = 2\\), \n\\(D_4 = 3(2+1) = 9\\), \n\\(D_5 = 4(9+2) = 44\\), \n\\(D_6 = 5(44+9) = 265\\), \n\\(D_7 = 6(265+44) = 1854\\).\n\nAnswer: 1854",
"turns": 1,
"cacheHitRatio": 0.7191011235955056,
"costUsd": 0.00349167,
"claudeEquivalentUsd": 0.024027,
"harvestedTurns": 0,
"totalSubgoals": 0,
"totalUncertainties": 0,
"totalHypotheses": 0,
"totalRejectedPaths": 0
},
{
"taskId": "derangements_d7",
"mode": "reasoner-harvest",
"repeat": 1,
"verdict": "pass",
"finalAgentMessage": "The number of derangements of \\(n\\) elements, denoted \\(D_n\\), counts permutations with no fixed points. For \\(n=7\\), this can be computed using the recurrence \\(D_n = (n-1)(D_{n-1} + D_{n-2})\\) with initial values \\(D_0 = 1\\) and \\(D_1 = 0\\). Applying the recurrence yields \\(D_2 = 1\\), \\(D_3 = 2\\), \\(D_4 = 9\\), \\(D_5 = 44\\), \\(D_6 = 265\\), and finally \\(D_7 = 6 \\times (265 + 44) = 1854\\).\n\nAnswer: 1854",
"turns": 1,
"cacheHitRatio": 0.7191011235955056,
"costUsd": 0.0028434299999999997,
"claudeEquivalentUsd": 0.019587,
"harvestedTurns": 1,
"totalSubgoals": 3,
"totalUncertainties": 2,
"totalHypotheses": 2,
"totalRejectedPaths": 2
},
{
"taskId": "euler_quadratic_break",
"mode": "baseline",
"repeat": 1,
"verdict": "pass",
"finalAgentMessage": "Let’s check \\( f(n) = n^2 + n + 41 \\) for small \\( n \\):\n\n- \\( n = 0 \\): \\( f(0) = 41 \\) (prime) \n- \\( n = 1 \\): \\( f(1) = 1 + 1 + 41 = 43 \\) (prime) \n- \\( n = 2 \\): \\( f(2) = 4 + 2 + 41 = 47 \\) (prime) \n- \\( n = 3 \\): \\( f(3) = 9 + 3 + 41 = 53 \\) (prime) \n- \\( n = 4 \\): \\( f(4) = 16 + 4 + 41 = 61 \\) (prime) \n- \\( n = 5 \\): \\( f(5) = 25 + 5 + 41 = 71 \\) (prime) \n- \\( n = 6 \\): \\( f(6) = 36 + 6 + 41 = 83 \\) (prime) \n- \\( n = 7 \\): \\( f(7) = 49 + 7 + 41 = 97 \\) (prime) \n- \\( n = 8 \\): \\( f(8) = 64 + 8 + 41 = 113 \\) (prime) \n- \\( n = 9 \\): \\( f(9) = 81 + 9 + 41 = 131 \\) (prime) \n- \\( n = 10 \\): \\( f(10) = 100 + 10 + 41 = 151 \\) (prime) \n\nWe can keep going, but the first known counterexample for this famous Euler polynomial is \\( n = 40 \\), because \n\\[\nf(40) = 40^2 + 40 + 41 = 1600 + 40 + 41 = 1681.\n\\] \nCheck if \\( 1681 \\) is prime: \n\\( 1681 = 41^2 \\) (since \\( 41 \\times 41 = 1681 \\)), so it’s composite.\n\nBut wait — let’s check if there’s a smaller \\( n \\) where \\( f(n) \\) is composite. \nWe can test \\( n = 41 \\): \n\\( f(41) = 41^2 + 41 + 41 = 1681 + 82 = 1763 \\), which is \\( 41 \\times 43 \\) (since \\( 1763/41 = 43 \\)), so composite. But \\( n = 41 \\) is larger than \\( n = 40 \\).\n\nCheck \\( n = 39 \\): \\( f(39) = 1521 + 39 + 41 = 1601 \\). Test divisibility: not divisible by primes up to \\( \\sqrt{1601} \\approx 40 \\), seems prime. \n\nCheck \\( n = 40 \\) is indeed the first composite? Let’s check \\( n = 1 \\) to \\( 39 \\) quickly for a smaller counterexample: \nWe can note \\( f(n) = n(n+1) + 41 \\). If \\( 41 \\mid f(n) \\), then \\( 41 \\mid n(n+1) \\). \nThat happens when \\( n \\equiv 0 \\pmod{41} \\) or \\( n \\equiv 40 \\pmod{41} \\). \nThe smallest positive such \\( n \\) is \\( n = 40 \\) (since \\( n=41 \\) is larger). \nSo for \\( n = 40 \\), \\( f(40) = 40 \\times 41 + 41 = 41 \\times 41 \\) is composite. \n\nCheck \\( n = 0 \\) to \\( 39 \\): no multiple of 41 except \\( n=0 \\) (which gives 41, prime). So \\( n=40 \\) is indeed the first nonnegative integer where \\( f(n) \\) is composite.\n\nThus smallest \\( n \\) is \\( 40 \\), \\( f(40) = 1681 = 41^2 \\).\n\n**Answer:** 40",
"turns": 1,
"cacheHitRatio": 0,
"costUsd": 0.00098535,
"claudeEquivalentUsd": 0.013365,
"harvestedTurns": 0,
"totalSubgoals": 0,
"totalUncertainties": 0,
"totalHypotheses": 0,
"totalRejectedPaths": 0
},
{
"taskId": "euler_quadratic_break",
"mode": "reasoner",
"repeat": 1,
"verdict": "pass",
"finalAgentMessage": "The smallest nonnegative integer \\(n\\) for which \\(f(n) = n^2 + n + 41\\) is composite is \\(n = 40\\). At this value, \\(f(40) = 40^2 + 40 + 41 = 1681 = 41^2\\), which is not prime.\n\nAnswer: 40",
"turns": 1,
"cacheHitRatio": 0.6095238095238096,
"costUsd": 0.0014309199999999998,
"claudeEquivalentUsd": 0.0099,
"harvestedTurns": 0,
"totalSubgoals": 0,
"totalUncertainties": 0,
"totalHypotheses": 0,
"totalRejectedPaths": 0
},
{
"taskId": "euler_quadratic_break",
"mode": "reasoner-harvest",
"repeat": 1,
"verdict": "pass",
"finalAgentMessage": "The polynomial \\(f(n) = n^2 + n + 41\\) is known to produce primes for \\(n = 0, 1, 2, \\dots, 39\\). At \\(n = 40\\), we have \\(f(40) = 40^2 + 40 + 41 = 1681\\), and \\(1681 = 41^2\\), which is composite. Therefore, \\(n = 40\\) is the smallest nonnegative integer where \\(f(n)\\) fails to be prime.\n\nAnswer: 40",
"turns": 1,
"cacheHitRatio": 0.6095238095238096,
"costUsd": 0.0025938099999999998,
"claudeEquivalentUsd": 0.017865,
"harvestedTurns": 1,
"totalSubgoals": 3,
"totalUncertainties": 2,
"totalHypotheses": 3,
"totalRejectedPaths": 2
}
]
}
-291
View File
@@ -1,291 +0,0 @@
/** Harvest-bench runner — writes results.json. CLI flags + sample invocations in benchmarks/README.md. */
import { type WriteStream, mkdirSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { pathToFileURL } from "node:url";
import {
CacheFirstLoop,
DeepSeekClient,
ImmutablePrefix,
claudeEquivalentCost,
loadDotenv,
} from "../../src/index.js";
import { openTranscriptFile, recordFromLoopEvent, writeRecord } from "../../src/transcript/log.js";
import { TASKS } from "./tasks.js";
import type {
HarvestBenchMeta,
HarvestBenchReport,
HarvestMode,
HarvestRunResult,
HarvestTask,
} from "./types.js";
import { ALL_MODES } from "./types.js";
loadDotenv();
interface CliArgs {
taskFilter: string | null;
modes: HarvestMode[];
repeats: number;
outPath: string | null;
transcriptsDir: string | null;
/** Per-HTTP-call timeout in ms. Default 300_000 (5 min) — reasoner + harvest runs legitimately need this. */
timeoutMs: number;
dry: boolean;
verbose: boolean;
}
function parseArgs(argv: string[]): CliArgs {
const out: CliArgs = {
taskFilter: null,
modes: [...ALL_MODES],
repeats: 1,
outPath: null,
transcriptsDir: null,
timeoutMs: 300_000,
dry: false,
verbose: false,
};
for (let i = 0; i < argv.length; i++) {
const a = argv[i];
if (a === "--task") out.taskFilter = argv[++i] ?? null;
else if (a === "--mode") {
const v = (argv[++i] ?? "").toLowerCase() as HarvestMode;
if ((ALL_MODES as string[]).includes(v)) out.modes = [v];
} else if (a === "--repeats") out.repeats = Number.parseInt(argv[++i] ?? "1", 10);
else if (a === "--out") out.outPath = argv[++i] ?? null;
else if (a === "--transcripts-dir") out.transcriptsDir = argv[++i] ?? null;
else if (a === "--timeout") {
// Accept seconds for humans, convert to ms internally.
const secs = Number.parseInt(argv[++i] ?? "300", 10);
if (Number.isFinite(secs) && secs > 0) out.timeoutMs = secs * 1000;
} else if (a === "--dry") out.dry = true;
else if (a === "--verbose" || a === "-v") out.verbose = true;
}
return out;
}
function modelForMode(mode: HarvestMode): string {
if (mode === "baseline") return "deepseek-chat";
return "deepseek-reasoner";
}
function harvestForMode(mode: HarvestMode): boolean {
return mode === "reasoner-harvest";
}
async function runOnce(
task: HarvestTask,
mode: HarvestMode,
rep: number,
client: DeepSeekClient,
transcriptStream: WriteStream | null,
): Promise<HarvestRunResult> {
const model = modelForMode(mode);
const harvest = harvestForMode(mode);
const prefix = new ImmutablePrefix({ system: task.systemPrompt });
const loop = new CacheFirstLoop({
client,
prefix,
model,
harvest,
stream: false,
});
const prefixHash = prefix.fingerprint;
let harvestedTurns = 0;
let totalSubgoals = 0;
let totalUncertainties = 0;
let totalHypotheses = 0;
let totalRejectedPaths = 0;
let finalText = "";
let errorMessage: string | undefined;
if (transcriptStream) {
writeRecord(transcriptStream, {
ts: new Date().toISOString(),
turn: 1,
role: "user",
content: task.prompt,
});
}
try {
for await (const ev of loop.step(task.prompt)) {
if (transcriptStream && ev.role !== "assistant_delta") {
writeRecord(transcriptStream, recordFromLoopEvent(ev, { model, prefixHash }));
}
if (ev.role === "assistant_final") {
finalText = ev.content;
if (ev.planState) {
if (
ev.planState.subgoals.length +
ev.planState.hypotheses.length +
ev.planState.uncertainties.length +
ev.planState.rejectedPaths.length >
0
) {
harvestedTurns++;
totalSubgoals += ev.planState.subgoals.length;
totalHypotheses += ev.planState.hypotheses.length;
totalUncertainties += ev.planState.uncertainties.length;
totalRejectedPaths += ev.planState.rejectedPaths.length;
}
}
} else if (ev.role === "done") {
finalText = ev.content || finalText;
break;
} else if (ev.role === "error") {
throw new Error(ev.error ?? "loop error");
}
}
} catch (err) {
errorMessage = (err as Error).message;
}
const verdict = errorMessage
? { verdict: "fail" as const, note: errorMessage }
: task.check(finalText);
return {
taskId: task.id,
mode,
repeat: rep + 1,
verdict: verdict.verdict,
checkNote: verdict.note,
finalAgentMessage: finalText,
turns: loop.stats.turns.length,
cacheHitRatio: loop.stats.aggregateCacheHitRatio,
costUsd: loop.stats.totalCost,
claudeEquivalentUsd: loop.stats.turns.reduce((s, t) => s + claudeEquivalentCost(t.usage), 0),
harvestedTurns,
totalSubgoals,
totalUncertainties,
totalHypotheses,
totalRejectedPaths,
errorMessage,
};
}
function runDry(args: CliArgs): HarvestBenchReport {
const tasks = filterTasks(args.taskFilter);
const results: HarvestRunResult[] = [];
for (const task of tasks) {
// Exercise each checker with a deliberately wrong reply so we know
// the wiring is live — not a pass on empty.
const sanity = task.check("Answer: this is not the right answer at all");
console.log(`[${task.id}] checker exercises ok (sanity verdict=${sanity.verdict})`);
for (const mode of args.modes) {
results.push({
taskId: task.id,
mode,
repeat: 1,
verdict: "inconclusive",
checkNote: "dry-run (no model call)",
finalAgentMessage: "[dry-run]",
turns: 0,
cacheHitRatio: 0,
costUsd: 0,
claudeEquivalentUsd: 0,
harvestedTurns: 0,
totalSubgoals: 0,
totalUncertainties: 0,
totalHypotheses: 0,
totalRejectedPaths: 0,
});
}
}
return { meta: buildMeta(args, tasks.length), results };
}
function filterTasks(filter: string | null): HarvestTask[] {
if (!filter) return TASKS;
const t = TASKS.find((x) => x.id === filter);
if (!t) throw new Error(`unknown task: ${filter}`);
return [t];
}
function buildMeta(args: CliArgs, taskCount: number): HarvestBenchMeta {
return {
date: new Date().toISOString(),
repeatsPerTask: args.repeats,
taskCount,
modesRun: args.modes,
reasonixVersion: "0.2.2",
};
}
async function main(): Promise<void> {
const args = parseArgs(process.argv.slice(2));
if (args.dry) {
const report = runDry(args);
writeReport(report, args.outPath);
return;
}
const client = new DeepSeekClient({ timeoutMs: args.timeoutMs });
const tasks = filterTasks(args.taskFilter);
if (args.transcriptsDir) mkdirSync(args.transcriptsDir, { recursive: true });
const results: HarvestRunResult[] = [];
for (const task of tasks) {
for (let rep = 0; rep < args.repeats; rep++) {
for (const mode of args.modes) {
let stream: WriteStream | null = null;
if (args.transcriptsDir) {
const fname = `${task.id}.${mode}.r${rep + 1}.jsonl`;
stream = openTranscriptFile(join(args.transcriptsDir, fname), {
version: 1,
source: `harvest-bench/${mode}`,
model: modelForMode(mode),
task: task.id,
mode,
repeat: rep + 1,
startedAt: new Date().toISOString(),
});
}
const started = Date.now();
let result: HarvestRunResult;
try {
result = await runOnce(task, mode, rep, client, stream);
} finally {
stream?.end();
}
const elapsed = ((Date.now() - started) / 1000).toFixed(1);
const note = result.checkNote ? ` ${result.checkNote}` : "";
console.log(
`[${task.id}/${mode}/r${rep + 1}] verdict=${result.verdict} cache=${(result.cacheHitRatio * 100).toFixed(1)}% cost=$${result.costUsd.toFixed(6)} harvest=${result.harvestedTurns}:${result.totalSubgoals}s/${result.totalUncertainties}u (${elapsed}s)${note}`,
);
results.push(result);
}
}
}
const report: HarvestBenchReport = { meta: buildMeta(args, tasks.length), results };
writeReport(report, args.outPath);
}
function writeReport(report: HarvestBenchReport, outPath: string | null): void {
const path =
outPath ?? `benchmarks/harvest/results-${new Date().toISOString().replace(/[:.]/g, "-")}.json`;
writeFileSync(path, `${JSON.stringify(report, null, 2)}\n`, "utf8");
console.log(`wrote ${path}`);
}
function isMain(): boolean {
const entry = process.argv[1];
if (!entry) return false;
return import.meta.url === pathToFileURL(entry).href;
}
if (isMain()) {
main().catch((err) => {
console.error(err);
process.exit(1);
});
}
export { main as runHarvestBench };
-143
View File
@@ -1,143 +0,0 @@
/** Seed reasoning tasks for harvest-bench — single-turn Q/A with deterministic checkers. */
import type { HarvestTask } from "./types.js";
const CONCISE_SYSTEM = `You are a precise reasoner. Think carefully, then state your final answer on a clearly-labeled line starting with "Answer:".`;
/** Parse non-negative integers; expands "2-4" → 2,3,4; strips LaTeX decorations first. */
function extractIntegers(text: string): number[] {
// Strip LaTeX delimiters so n_1 / n^2 / \{ ... \} don't confuse us.
const cleaned = text
.replace(/\\[a-zA-Z]+/g, " ") // \frac, \mod etc.
.replace(/[{}\\]/g, " ")
.replace(/[_^]\d+/g, " "); // subscript/superscript numbers
// Expand ranges: "2-4" → "2,3,4" (only for small gaps)
const rangeExpanded = cleaned.replace(/(\d+)\s*[-–]\s*(\d+)/g, (_, a, b) => {
const lo = Number.parseInt(a, 10);
const hi = Number.parseInt(b, 10);
if (!Number.isFinite(lo) || !Number.isFinite(hi) || hi - lo > 50) return `${a} ${b}`;
const out: number[] = [];
for (let i = Math.min(lo, hi); i <= Math.max(lo, hi); i++) out.push(i);
return out.join(" ");
});
const matches = rangeExpanded.match(/-?\d+/g) ?? [];
return matches.map((m) => Number.parseInt(m, 10)).filter((n) => Number.isFinite(n));
}
/** Extract content after the last "Answer:" label (case-insensitive). */
function extractAnswerLine(text: string): string {
const matches = [...text.matchAll(/answer\s*[::]\s*([^\n]+)/gi)];
if (matches.length === 0) return text;
return matches[matches.length - 1]![1]!.trim();
}
/** Positive n ≤ 100 such that n^2 + n + 1 ≡ 0 (mod 7). */
const MOD7_EXPECTED: number[] = (() => {
const out: number[] = [];
for (let n = 1; n <= 100; n++) {
if ((n * n + n + 1) % 7 === 0) out.push(n);
}
return out;
})();
/** Single-integer checker — first plausible int from the last "Answer:" line, exact equality. */
function checkSingleInt(expected: number) {
return (reply: string) => {
const answerLine = extractAnswerLine(reply);
const nums = extractIntegers(answerLine);
if (nums.length === 0) return { verdict: "fail" as const, note: "no number in Answer line" };
const n = nums[0]!;
if (n === expected) return { verdict: "pass" as const };
return { verdict: "fail" as const, note: `got ${n}, expected ${expected}` };
};
}
export const TASKS: HarvestTask[] = [
{
id: "mod7_list",
description:
"Number theory — find all positive n ≤ 100 with n^2+n+1 ≡ 0 (mod 7). 29-element set. Classic R1 scratch-work territory.",
systemPrompt: CONCISE_SYSTEM,
prompt:
'Find all positive integers n with n ≤ 100 such that n^2 + n + 1 is divisible by 7. Briefly justify, then end with the full list on a line starting with "Answer:".',
check: (reply) => {
const answerLine = extractAnswerLine(reply);
const found = new Set(extractIntegers(answerLine).filter((n) => n >= 1 && n <= 100));
const expected = new Set(MOD7_EXPECTED);
if (found.size === 0) {
return { verdict: "fail", note: "no integers extracted from Answer line" };
}
// Exact set equality — both containment directions.
for (const n of expected)
if (!found.has(n)) return { verdict: "fail", note: `missing n=${n}` };
for (const n of found) if (!expected.has(n)) return { verdict: "fail", note: `extra n=${n}` };
return { verdict: "pass" };
},
},
{
id: "flips_until_3heads",
description:
"Probability — expected coin flips until 3 consecutive heads. Answer: 14. Tests whether R1 derives via recurrence or via memorized result.",
systemPrompt: CONCISE_SYSTEM,
prompt:
'A fair coin is flipped repeatedly until you see 3 heads in a row. What is the expected number of total flips? Give a single integer on a line starting with "Answer:".',
check: (reply) => {
const answerLine = extractAnswerLine(reply);
const nums = extractIntegers(answerLine);
if (nums.length === 0) return { verdict: "fail", note: "no number in Answer line" };
// Accept the first sensible number — sometimes agents write "Answer: 14 flips".
const n = nums[0]!;
if (n === 14) return { verdict: "pass" };
return { verdict: "fail", note: `got ${n}, expected 14` };
},
},
{
id: "three_hats",
description:
"Logic — three people wear red/blue hats, at least one red, they're asked in order. First two say no, third says yes. What color? Answer: red (deducible because if third were blue, the first two could see one red + one unknown and wouldn't have said no on their full first round, for most configurations the third can only be certain if red).",
systemPrompt: CONCISE_SYSTEM,
prompt:
'Three people wear hats that are each red or blue. They are told at least one hat is red. Each can see the other two hats but not their own. They are asked in order: "Do you know your hat color?" The first two answer no. The third answers yes. What color is the third person\'s hat? Give a one-word answer on a line starting with "Answer:".',
check: (reply) => {
const answerLine = extractAnswerLine(reply).toLowerCase();
// Accept "red" as a standalone word (not "redirected" etc).
if (/\bred\b/.test(answerLine) && !/\bblue\b/.test(answerLine)) {
return { verdict: "pass" };
}
if (/\bblue\b/.test(answerLine)) return { verdict: "fail", note: "answered blue" };
return { verdict: "fail", note: "no clear color in Answer line" };
},
},
{
id: "pseudoprime_base2",
description:
"Number theory — smallest composite n > 1 such that 2^n ≡ 2 (mod n). This is the smallest Fermat pseudoprime to base 2. Answer: 341 (= 11·31). V3 frequently answers 561 (Carmichael / wrong base-2 property) or 9 (not actually a pseudoprime to base 2, verifying the model isn't computing). R1 usually gets this right.",
systemPrompt: CONCISE_SYSTEM,
prompt:
'Find the smallest composite integer n > 1 such that 2^n is congruent to 2 modulo n (i.e., n is a Fermat pseudoprime to base 2). Briefly justify, then give a single integer on a line starting with "Answer:".',
check: checkSingleInt(341),
},
{
id: "derangements_d7",
description:
"Combinatorics — number of derangements of 7 elements. Answer: 1854 (D_7 = 7! · (1 − 1/1! + 1/2! − 1/3! + … ± 1/7!) = 5040 · 0.367857… = 1854). V3 sometimes approximates via n!/e and rounds wrong, or confuses with D_6=265 or D_8=14833. R1's explicit recurrence D_n = (n-1)(D_{n-1}+D_{n-2}) avoids the mistake.",
systemPrompt: CONCISE_SYSTEM,
prompt:
'How many permutations of {1, 2, 3, 4, 5, 6, 7} have no fixed points? (This is D_7, the derangement number.) Briefly justify, then give a single integer on a line starting with "Answer:".',
check: checkSingleInt(1854),
},
{
id: "euler_quadratic_break",
description:
"Number theory — smallest nonneg integer n where n^2 + n + 41 is NOT prime. Euler's prime-generating polynomial famously produces primes for n = 0..39 and first fails at n = 40 (40²+40+41 = 1681 = 41²). V3 often confuses this with the related n²-n+41 (first fails at 41) or cites the wrong threshold. R1 checks small n systematically.",
systemPrompt: CONCISE_SYSTEM,
prompt:
'Consider the polynomial f(n) = n^2 + n + 41 for n = 0, 1, 2, …. What is the smallest nonneg integer n at which f(n) fails to be prime? Briefly justify (including the value of f(n) at that point), then give just the integer n on a line starting with "Answer:".',
check: checkSingleInt(40),
},
];
-61
View File
@@ -1,61 +0,0 @@
/** Harvest-bench types — single-turn Q/A with deterministic checkers; isolates Pillar 2 the way τ-bench-lite isolates Pillar 1. */
export type HarvestMode =
/** deepseek-chat, no Reasonix tricks. Floor reference for answer quality on reasoning tasks (V3 at its best). */
| "baseline"
/** deepseek-reasoner, no harvest. Isolates "does reasoner help over chat on these problems?" */
| "reasoner"
/** deepseek-reasoner + harvest. Isolates "does the extra V3 harvest call add quality / change behavior?" */
| "reasoner-harvest";
export const ALL_MODES: HarvestMode[] = ["baseline", "reasoner", "reasoner-harvest"];
/** Checker verdict — `inconclusive` reserves room for "right shape, can't verify without running it". */
export type CheckVerdict = "pass" | "fail" | "inconclusive";
export interface HarvestTask {
id: string;
/** One-line human description, not shown to the model. */
description: string;
/** System prompt. Kept minimal so harvest signal can be attributed to the model, not to prompt engineering. */
systemPrompt: string;
/** The single question. */
prompt: string;
/** Pure + deterministic — no LLM calls, no file I/O. Verdict + optional one-line note. */
check: (agentReply: string) => { verdict: CheckVerdict; note?: string };
}
export interface HarvestRunResult {
taskId: string;
mode: HarvestMode;
repeat: number;
verdict: CheckVerdict;
checkNote?: string;
finalAgentMessage: string;
/** Turns the loop completed (usually 1 for a single-shot Q/A, > 1 if tool-calls happen). */
turns: number;
cacheHitRatio: number;
costUsd: number;
claudeEquivalentUsd: number;
/** Harvest-specific — only non-zero on reasoner-harvest mode. */
harvestedTurns: number;
totalSubgoals: number;
totalUncertainties: number;
totalHypotheses: number;
totalRejectedPaths: number;
/** Optional error message if the run crashed (model down, timeout, etc). */
errorMessage?: string;
}
export interface HarvestBenchMeta {
date: string;
repeatsPerTask: number;
taskCount: number;
modesRun: HarvestMode[];
reasonixVersion: string;
}
export interface HarvestBenchReport {
meta: HarvestBenchMeta;
results: HarvestRunResult[];
}
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." },
];
+139
View File
@@ -0,0 +1,139 @@
# Dashboard ↔ TUI parity
Closing audit of #369. Inventories every slash command and how the
web dashboard handles it.
## Coverage legend
- **panel** — has a dedicated SPA panel or modal beyond just typing the
slash in the chat box.
- **chat-box** — works by typing the slash into the web chat input.
Result text shows in the dashboard scrollback as an info row. No
dedicated UI; the chat box _is_ the UI.
- **tui-only** — keyboard binding or process-controlling action that
has no useful web equivalent. Stays a TUI affordance by design.
## Counts
Roughly **20 commands have a dedicated panel**, **38 work via the chat
box**, and **`/exit` plus 4 raw keyboard shortcuts** stay TUI-only.
Aliases (e.g. `/sessions` and `/resume` share one picker) collapse
into one row.
## Core / observability
| Slash | Purpose | Coverage |
|---|---|---|
| `/help` | command reference | chat-box |
| `/keys` | keyboard shortcuts + prompt prefixes | chat-box |
| `/status` | model + flags + ctx + session | chat-box |
| `/context` | context-window breakdown (stacked bar) | chat-box · `ctxBreakdown` payload |
| `/cost` | last turn / next turn estimate | chat-box · usage card |
| `/stats` | cross-session cost dashboard | **panel** · Usage tab |
| `/think` | last R1 reasoning dump | chat-box |
| `/tool [N]` | dump full output of Nth tool call | chat-box |
| `/clear` | wipe visible scrollback | chat-box |
| `/new` (`/reset`) | wipe context + scrollback | chat-box |
| `/exit` (`/quit`, `/q`) | quit the TUI | **tui-only** |
| `/stop` | abort current model turn | chat-box |
| `/retry` | resend last user message | chat-box |
| `/compact` | fold older turns into summary | chat-box |
| `/update` | show current vs latest version | chat-box |
| `/doctor` | health check card | chat-box · doctor card |
## Model & compute
| Slash | Purpose | Coverage |
|---|---|---|
| `/preset` | model bundle (auto / flash / pro) | **panel** · Settings → Defaults |
| `/effort` | reasoning cap (high / max) | **panel** · Settings → Defaults |
| `/model` | active model | **panel** · Settings → Runtime (D-4 #437) |
| `/models` | list available models | chat-box |
| `/pro` | arm v4-pro for next turn | **panel** · Settings → Compute (D-2 #435) |
| `/budget` | session USD cap | **panel** · Settings → Budget + cockpit tile (D-3 #436) |
| `/loop` | auto-resubmit on interval | **panel** · Settings → Loop (D-5 #438) |
## Memory & project
| Slash | Purpose | Coverage |
|---|---|---|
| `/memory [list / show / forget / clear]` | manage pinned memory | **panel** · Memory tab |
| `/init` | synthesize baseline REASONIX.md | chat-box |
| `/semantic` | semantic-search index status | chat-box |
| `/search-engine` (`/se`) | switch web search backend | chat-box |
| `/language` (`/lang`) | runtime language | **panel** · Settings → Language |
## Sessions
| Slash | Purpose | Coverage |
|---|---|---|
| `/sessions` | list saved sessions | **panel** · SessionPicker modal (C-2 #423) |
| `/resume` | open a session | **panel** · same picker |
| `/rename` | rename current session | chat-box |
| `/forget` | delete current session | chat-box |
| `/plans` | active + archived plans | **panel** · Plans tab |
| `/replay [N]` | read-only plan archive | **panel** · Viewer modal (C-5 #427) |
## MCP
| Slash | Purpose | Coverage |
|---|---|---|
| `/mcp` (list) | bridged servers + tools | **panel** · MCP tab |
| `/mcp browse` | marketplace + install | **panel** · MCP marketplace picker (C-4 #426) |
| `/mcp disable` / `enable` / `reconnect` / `text` | server admin | chat-box |
| `/resource [uri]` | browse / read MCP resources | chat-box |
| `/prompt [name]` | browse / fetch MCP prompts | chat-box |
## Permissions & admin
| Slash | Purpose | Coverage |
|---|---|---|
| `/permissions [list / add / remove / clear]` | shell allowlist | **panel** · Permissions tab |
| `/hooks [reload]` | active hooks | **panel** · Hooks tab |
| `/dashboard [stop]` | embedded dashboard lifecycle | chat-box · *intentional — admin command for the surface you're typing in* |
## Code-mode only
| Slash | Purpose | Coverage |
|---|---|---|
| `/init [force]` | scan + synthesize REASONIX.md | chat-box |
| `/apply [N]` | commit pending edits | chat-box |
| `/discard [N]` | drop pending edits | chat-box |
| `/walk` | step through pending edits | **panel** · edit-review modal already covered web pre-#369 |
| `/undo` | roll back last edit batch | chat-box |
| `/history` | edit batch list | chat-box |
| `/show [id]` | dump stored edit diff | chat-box |
| `/commit "msg"` | git commit | chat-box |
| `/checkpoint [name / list / forget]` | snapshot touched files | chat-box |
| `/restore` | roll back to checkpoint | **panel** · CheckpointPicker modal (C-3 #425) |
| `/plan [on / off]` | read-only plan mode | chat-box |
| `/apply-plan` | force-approve pending plan | chat-box |
| `/mode [review / auto / yolo]` | edit gate | **panel** · Chat header pill |
| `/jobs` | list background jobs | chat-box |
| `/kill <id>` | stop background job | chat-box |
| `/logs <id> [lines]` | tail job output | chat-box |
| `/skill [list / show / new / <name>]` | skill management | **panel** · Skills tab |
## Keyboard / TTY-native
These don't have slashes. They ride alongside the slash surface and
stay TUI-only:
- `Esc` — abort current model turn (web equivalent: Abort button in chat)
- `Shift+Tab` — cycle edit mode (web equivalent: mode pill in chat header)
- `Ctrl-L`, `Ctrl-O`, `space`, `u` — TTY scroll / undo banner / pause hotkeys
## Done
Buckets covered:
- **C** (#416, closed): pickers — `/sessions`, `/restore`, `/mcp browse`, `/replay` + `/walk` (already)
- **D** (#428, closed): settings — `/preset`, `/effort`, `/model`, `/pro`, `/budget`, `/loop`, `/language`
Bucket A (text outputs that stay chat-box) and bucket B (structured
outputs that already have panels) need no further work — the panels
shipped in C/D plus the long-standing Memory / Permissions / Hooks /
Skills / Plans / Usage tabs already cover every command whose output
warranted a dedicated UI.
This file is the source of truth for the audit. Add a row when a
new slash lands.
+166 -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; }
@@ -2005,6 +2019,155 @@ input:focus, textarea:focus, select:focus { border-color: var(--c-brand); }
max-height: 200px;
}
.modal-picker-search {
width: 100%;
background: var(--bg-elev-2);
border: 1px solid var(--bd);
border-radius: var(--r);
color: var(--fg-1);
padding: 6px 10px;
font-size: 13px;
margin-bottom: 8px;
}
.modal-picker-list {
display: flex;
flex-direction: column;
gap: 2px;
max-height: 320px;
overflow-y: auto;
border: 1px solid var(--bd);
border-radius: var(--r);
background: var(--bg-elev-2);
padding: 4px;
margin-bottom: 8px;
}
.modal-picker-row {
display: grid;
grid-template-columns: 1fr auto;
gap: 4px 8px;
align-items: baseline;
padding: 6px 8px;
background: transparent;
border: 1px solid transparent;
border-radius: var(--r-sm, 4px);
color: var(--fg-1);
text-align: left;
cursor: pointer;
}
.modal-picker-row:hover {
background: var(--bg-elev-3, var(--bg-elev-2));
}
.modal-picker-row.selected {
border-color: var(--accent, #fcd34d);
background: var(--bg-elev-3, var(--bg-elev-2));
}
.modal-picker-title {
grid-column: 1;
font-weight: 500;
}
.modal-picker-badge {
grid-column: 2;
font-size: 11px;
color: var(--fg-2);
padding: 1px 6px;
border-radius: 999px;
background: var(--bg-elev-1, var(--bg-elev-2));
}
.modal-picker-subtitle {
grid-column: 1 / 3;
font-size: 12px;
color: var(--fg-2);
}
.modal-picker-meta {
grid-column: 1 / 3;
font-size: 11px;
color: var(--fg-3, var(--fg-2));
}
.modal-picker-empty {
padding: 16px;
text-align: center;
color: var(--fg-2);
font-size: 12px;
}
.modal-picker-more {
align-self: center;
margin: 0 auto 8px;
font-size: 12px;
}
.modal-picker-form {
display: flex;
flex-direction: column;
gap: 8px;
margin-bottom: 8px;
}
.modal-picker-form input {
width: 100%;
background: var(--bg-elev-2);
border: 1px solid var(--bd);
border-radius: var(--r);
color: var(--fg-1);
padding: 6px 10px;
font-size: 13px;
}
.modal-viewer-steps {
list-style: none;
padding: 0;
margin: 0 0 8px;
display: flex;
flex-direction: column;
gap: 4px;
}
.modal-viewer-step {
display: grid;
grid-template-columns: 18px 1fr;
gap: 6px;
padding: 4px 8px;
border-radius: var(--r-sm, 4px);
background: var(--bg-elev-2);
align-items: baseline;
}
.modal-viewer-step-mark {
text-align: center;
font-weight: 600;
color: var(--fg-2);
}
.modal-viewer-step-done .modal-viewer-step-mark {
color: #86efac;
}
.modal-viewer-step-title {
color: var(--fg-1);
font-size: 13px;
}
.modal-viewer-step-done .modal-viewer-step-title {
color: var(--fg-2);
}
.modal-viewer-body {
margin-top: 4px;
font-size: 13px;
color: var(--fg-1);
max-height: 360px;
overflow-y: auto;
}
/* Side-by-side diff for the edit-review modal — left is "before" (red
* tint), right is "after" (green tint), context rows render unchanged.
* Lines hljs-highlight per the file's language. */
+56 -35
View File
@@ -6,6 +6,7 @@ import { useCallback, useEffect, useState } from "preact/hooks";
import { MODE } from "./src/lib/api";
import { ToastStack, appBus } from "./src/lib/bus";
import { ErrorBoundary, ErrorOverlay } from "./src/lib/error-boundary";
import { initLangFromServer, t, useLang } from "./src/i18n";
import { ChatPanel } from "./src/panels/chat";
import { HooksPanel } from "./src/panels/hooks";
import { McpPanel } from "./src/panels/mcp";
@@ -23,42 +24,50 @@ import { UsagePanel } from "./src/panels/usage";
const html = htm.bind(h);
const TAB_SECTIONS = [
{
label: "workspace",
tabs: [
{ id: "chat", name: "Chat", glyph: "◆", panel: () => html`<${ChatPanel} />` },
{ id: "plans", name: "Plans", glyph: "⊞", panel: () => html`<${PlansPanel} />` },
{ id: "sessions", name: "Sessions", glyph: "›", panel: () => html`<${SessionsPanel} />` },
],
},
{
label: "observe",
tabs: [
{ id: "overview", name: "Overview", glyph: "◈", panel: () => html`<${OverviewPanel} />` },
{ id: "usage", name: "Usage", glyph: "$", panel: () => html`<${UsagePanel} />` },
{ id: "health", name: "System", glyph: "+", panel: () => html`<${SystemPanel} />` },
{ id: "semantic", name: "Semantic", glyph: "≈", panel: () => html`<${SemanticPanel} />` },
],
},
{
label: "configure",
tabs: [
{ id: "tools", name: "Tools", glyph: "▣", panel: () => html`<${ToolsPanel} />` },
{ id: "permissions", name: "Permissions", glyph: "▎", panel: () => html`<${PermissionsPanel} />` },
{ id: "mcp", name: "MCP", glyph: "M", panel: () => html`<${McpPanel} />` },
{ id: "skills", name: "Skills", glyph: "S", panel: () => html`<${SkillsPanel} />` },
{ id: "memory", name: "Memory", glyph: "·", panel: () => html`<${MemoryPanel} />` },
{ id: "hooks", name: "Hooks", glyph: "H", panel: () => html`<${HooksPanel} />` },
{ id: "settings", name: "Settings", glyph: "⌘", panel: () => html`<${SettingsPanel} />` },
],
},
];
const ALL_TABS = TAB_SECTIONS.flatMap((s) => s.tabs);
function tabSections() {
return [
{
label: t("app.sectionWorkspace"),
tabs: [
{ id: "chat", name: t("app.tabChat"), glyph: "◆", panel: () => html`<${ChatPanel} />` },
{ id: "plans", name: t("app.tabPlans"), glyph: "⊞", panel: () => html`<${PlansPanel} />` },
{ id: "sessions", name: t("app.tabSessions"), glyph: "›", panel: () => html`<${SessionsPanel} />` },
],
},
{
label: t("app.sectionObserve"),
tabs: [
{ id: "overview", name: t("app.tabOverview"), glyph: "◈", panel: () => html`<${OverviewPanel} />` },
{ id: "usage", name: t("app.tabUsage"), glyph: "$", panel: () => html`<${UsagePanel} />` },
{ id: "health", name: t("app.tabSystem"), glyph: "+", panel: () => html`<${SystemPanel} />` },
{ id: "semantic", name: t("app.tabSemantic"), glyph: "≈", panel: () => html`<${SemanticPanel} />` },
],
},
{
label: t("app.sectionConfigure"),
tabs: [
{ id: "tools", name: t("app.tabTools"), glyph: "▣", panel: () => html`<${ToolsPanel} />` },
{ id: "permissions", name: t("app.tabPermissions"), glyph: "▎", panel: () => html`<${PermissionsPanel} />` },
{ id: "mcp", name: t("app.tabMcp"), glyph: "M", panel: () => html`<${McpPanel} />` },
{ id: "skills", name: t("app.tabSkills"), glyph: "S", panel: () => html`<${SkillsPanel} />` },
{ id: "memory", name: t("app.tabMemory"), glyph: "·", panel: () => html`<${MemoryPanel} />` },
{ id: "hooks", name: t("app.tabHooks"), glyph: "H", panel: () => html`<${HooksPanel} />` },
{ id: "settings", name: t("app.tabSettings"), glyph: "⌘", panel: () => html`<${SettingsPanel} />` },
],
},
];
}
function App() {
const [activeId, setActiveId] = useState("chat");
useLang();
useEffect(() => { initLangFromServer(); }, []);
const [activeId, setActiveId] = useState(() => {
try {
return localStorage.getItem("rx.activeTab") ?? "chat";
} catch {
return "chat";
}
});
const [sidebarCollapsed, setSidebarCollapsed] = useState(() => {
try {
return localStorage.getItem("rx.sidebarCollapsed") === "1";
@@ -73,7 +82,19 @@ function App() {
/* private mode / disabled storage — ignore */
}
}, [sidebarCollapsed]);
useEffect(() => {
try {
localStorage.setItem("rx.activeTab", activeId);
} catch {
/* private mode / disabled storage — ignore */
}
}, [activeId]);
const TAB_SECTIONS = tabSections();
const ALL_TABS = TAB_SECTIONS.flatMap((s) => s.tabs);
const active = ALL_TABS.find((t) => t.id === activeId) ?? ALL_TABS[0];
useEffect(() => {
if (active.id !== activeId) setActiveId(active.id);
}, [active.id, activeId]);
useEffect(() => {
const onNav = (ev) => {
@@ -135,7 +156,7 @@ function App() {
</div>
<footer class="app-status">
<span class="grow"></span>
<span class="item">127.0.0.1 only · token-gated</span>
<span class="item">${t("app.footer")}</span>
</footer>
</div>
<${ToastStack} />
+310 -44
View File
@@ -1,6 +1,7 @@
import { marked } from "marked";
import { useState } from "preact/hooks";
import { html } from "../lib/html.js";
import { t, useLang } from "../i18n/index.js";
import {
escapeHtml,
hlLine,
@@ -103,6 +104,49 @@ interface RevisionSpec {
remainingSteps: RevisionStep[];
}
export type PickerActionName =
| "pick"
| "delete"
| "rename"
| "new"
| "install"
| "uninstall"
| "load-more"
| "refine"
| "cancel";
export interface PickerItemSpec {
id: string;
title: string;
subtitle?: string;
badge?: string;
meta?: string;
}
export interface PickerModalSpec {
pickerKind: string;
title: string;
query?: string;
items: PickerItemSpec[];
actions: PickerActionName[];
hasMore?: boolean;
hint?: string;
}
export interface ViewerStep {
id: string;
title: string;
status: "done" | "queued";
}
export interface ViewerModalSpec {
viewerKind: string;
title: string;
body?: string;
steps?: ViewerStep[];
meta?: string;
}
interface DiffEntry {
kind: "context" | "ins" | "del";
text: string;
@@ -129,6 +173,7 @@ export function parseToolArgs(raw: string | null | undefined): Record<string, un
}
export function ToolCard({ msg }: ToolCardProps) {
useLang();
const args = parseToolArgs(msg.toolArgs);
const name = msg.toolName ?? "tool";
// Reasonix's filesystem tools emit the path in args.path; MCP-bridged
@@ -247,7 +292,7 @@ export function ToolCard({ msg }: ToolCardProps) {
</div>
${
args
? html`<details class="tool-card-args"><summary>arguments</summary><pre>${escapeHtml(JSON.stringify(args, null, 2))}</pre></details>`
? html`<details class="tool-card-args"><summary>${t("modal.arguments")}</summary><pre>${escapeHtml(JSON.stringify(args, null, 2))}</pre></details>`
: null
}
<pre class="tool-card-output">${msg.text}</pre>
@@ -301,31 +346,33 @@ export function ModalCard({ accent, icon, title, subtitle, children }: ModalCard
}
export function ShellModal({ modal, onResolve }: { modal: ShellModalSpec; onResolve: OnResolve }) {
useLang();
const isBg = modal.shellKind === "run_background";
return html`
<${ModalCard}
accent="#f87171"
icon=${isBg ? "⏱" : "⚡"}
title=${isBg ? "background process" : "shell command"}
title=${isBg ? t("modal.shellBgTitle") : t("modal.shellTitle")}
subtitle=${
isBg ? "long-running — keeps running after approval" : "model wants to run a shell command"
isBg ? t("modal.shellBgSubtitle") : t("modal.shellSubtitle")
}
>
<div class="modal-cmd"><span class="modal-cmd-prompt">$</span> <code>${modal.command}</code></div>
<div class="modal-actions">
<button class="primary" onClick=${() => onResolve("shell", "run_once")}>Run once</button>
<button onClick=${() => onResolve("shell", "always_allow")}>Always allow "${modal.allowPrefix}"</button>
<button class="danger" onClick=${() => onResolve("shell", "deny")}>Deny</button>
<button class="primary" onClick=${() => onResolve("shell", "run_once")}>${t("modal.runOnce")}</button>
<button onClick=${() => onResolve("shell", "always_allow")}>${t("modal.alwaysAllow", { prefix: modal.allowPrefix ?? "" })}</button>
<button class="danger" onClick=${() => onResolve("shell", "deny")}>${t("modal.deny")}</button>
</div>
<//>
`;
}
export function ChoiceModal({ modal, onResolve }: { modal: ChoiceModalSpec; onResolve: OnResolve }) {
useLang();
const [custom, setCustom] = useState("");
const [showCustom, setShowCustom] = useState(false);
return html`
<${ModalCard} accent="#f0abfc" icon="🔀" title="model wants you to pick" subtitle=${modal.question}>
<${ModalCard} accent="#f0abfc" icon="🔀" title=${t("modal.choiceTitle")} subtitle=${modal.question}>
${modal.options.map(
(opt: ChoiceOption) => html`
<button
@@ -345,44 +392,45 @@ export function ChoiceModal({ modal, onResolve }: { modal: ChoiceModalSpec; onRe
? html`
<div class="modal-custom">
<textarea
placeholder="Type a free-form answer…"
placeholder=${t("modal.typePlaceholder")}
rows="2"
value=${custom}
onInput=${(e: Event) => setCustom((e.target as HTMLTextAreaElement).value)}
></textarea>
<div class="modal-actions">
<button class="primary" onClick=${() => onResolve("choice", { kind: "custom", text: custom })} disabled=${!custom.trim()}>Send</button>
<button class="primary" onClick=${() => onResolve("choice", { kind: "custom", text: custom })} disabled=${!custom.trim()}>${t("modal.send")}</button>
<button onClick=${() => {
setShowCustom(false);
setCustom("");
}}>Back</button>
}}>${t("common.back")}</button>
</div>
</div>
`
: html`
<button class="modal-choice-row" onClick=${() => setShowCustom(true)}>
<span class="modal-choice-id">·</span>
<span class="modal-choice-title">Type my own answer</span>
<span class="modal-choice-summary">None of the above fits — write a free-form reply.</span>
<span class="modal-choice-title">${t("modal.typeOwn")}</span>
<span class="modal-choice-summary">${t("modal.typeOwnSummary")}</span>
</button>
`
: null
}
<button class="modal-choice-row modal-choice-cancel" onClick=${() => onResolve("choice", { kind: "cancel" })}>
<span class="modal-choice-id">×</span>
<span class="modal-choice-title">Cancel</span>
<span class="modal-choice-summary">Drop the question. Model will ask what you actually want.</span>
<span class="modal-choice-title">${t("modal.cancel")}</span>
<span class="modal-choice-summary">${t("modal.cancelSummary")}</span>
</button>
<//>
`;
}
export function PlanModal({ modal, onResolve }: { modal: PlanModalSpec; onResolve: OnResolve }) {
useLang();
const [feedback, setFeedback] = useState("");
const [stage, setStage] = useState<"approve" | "refine" | null>(null);
const send = () => onResolve("plan", stage, feedback);
return html`
<${ModalCard} accent="#67e8f9" icon="◆" title="plan submitted" subtitle="model proposed a plan; review then pick">
<${ModalCard} accent="#67e8f9" icon="◆" title=${t("modal.planTitle")} subtitle=${t("modal.planSubtitle")}>
<div class="md modal-plan-body" dangerouslySetInnerHTML=${{ __html: marked.parse(modal.body || "") }}></div>
${
stage
@@ -390,26 +438,26 @@ export function PlanModal({ modal, onResolve }: { modal: PlanModalSpec; onResolv
<textarea
placeholder=${
stage === "approve"
? "Optional last instructions / answers to open questions (Enter to send blank)"
: "What needs to change? Be specific."
? t("modal.approveInstructions")
: t("modal.refinePlaceholder")
}
rows="3"
value=${feedback}
onInput=${(e: Event) => setFeedback((e.target as HTMLTextAreaElement).value)}
></textarea>
<div class="modal-actions">
<button class="primary" onClick=${send}>${stage === "approve" ? "Approve" : "Send refinement"}</button>
<button class="primary" onClick=${send}>${stage === "approve" ? t("modal.approve") : t("modal.sendRefinement")}</button>
<button onClick=${() => {
setStage(null);
setFeedback("");
}}>Back</button>
}}>${t("common.back")}</button>
</div>
`
: html`
<div class="modal-actions">
<button class="primary" onClick=${() => setStage("approve")}>Approve</button>
<button onClick=${() => setStage("refine")}>Refine</button>
<button class="danger" onClick=${() => onResolve("plan", "cancel")}>Cancel</button>
<button class="primary" onClick=${() => setStage("approve")}>${t("modal.approve")}</button>
<button onClick=${() => setStage("refine")}>${t("modal.refine")}</button>
<button class="danger" onClick=${() => onResolve("plan", "cancel")}>${t("modal.cancel")}</button>
</div>
`
}
@@ -489,6 +537,7 @@ function pairDiffRows(diff: DiffEntry[]): DiffPair[] {
}
export function EditReviewModal({ modal, onResolve }: { modal: EditReviewSpec; onResolve: OnResolve }) {
useLang();
const search = modal.search ?? "";
const replace = modal.replace ?? "";
const lang = langFromPath(modal.path);
@@ -500,16 +549,16 @@ export function EditReviewModal({ modal, onResolve }: { modal: EditReviewSpec; o
<${ModalCard}
accent="#86efac"
icon="◆"
title="edit pending review"
subtitle=${`${modal.path} · ${modal.remaining} of ${modal.total} blocks remaining`}
title=${t("modal.editTitle")}
subtitle=${t("modal.editSubtitle", { path: modal.path ?? "", remaining: modal.remaining, total: modal.total })}
>
<div class="edit-diff-wrap">
<div class="edit-diff-head">
<div class="edit-diff-side edit-diff-side-old">
<span class="edit-diff-marker">−</span> before
<span class="edit-diff-marker">−</span> ${t("modal.before")}
</div>
<div class="edit-diff-side edit-diff-side-new">
<span class="edit-diff-marker">+</span> after
<span class="edit-diff-marker">+</span> ${t("modal.after")}
</div>
</div>
<div class="edit-diff-body">
@@ -542,33 +591,35 @@ export function EditReviewModal({ modal, onResolve }: { modal: EditReviewSpec; o
</div>
</div>
<div class="modal-actions">
<button class="primary" onClick=${() => onResolve("edit-review", "apply")}>Apply (y)</button>
<button onClick=${() => onResolve("edit-review", "reject")}>Reject (n)</button>
<button onClick=${() => onResolve("edit-review", "apply-rest-of-turn")}>Apply rest (a)</button>
<button onClick=${() => onResolve("edit-review", "flip-to-auto")}>Flip to AUTO (A)</button>
<button class="primary" onClick=${() => onResolve("edit-review", "apply")}>${t("chat.confirmBtn")}</button>
<button onClick=${() => onResolve("edit-review", "reject")}>${t("chat.rejectBtn")}</button>
<button onClick=${() => onResolve("edit-review", "apply-rest-of-turn")}>${t("chat.applyRestBtn")}</button>
<button onClick=${() => onResolve("edit-review", "flip-to-auto")}>${t("chat.flipAutoBtn")}</button>
</div>
<//>
`;
}
export function WorkspaceModal({ modal, onResolve }: { modal: WorkspaceSpec; onResolve: OnResolve }) {
useLang();
return html`
<${ModalCard}
accent="#fbbf24"
icon="◇"
title="model wants to switch workspace"
subtitle="every subsequent file / shell / memory tool resolves against the new root"
title=${t("modal.workspaceTitle")}
subtitle=${t("modal.workspaceSubtitle")}
>
<div class="modal-cmd"><span class="modal-cmd-prompt">→</span> <code>${modal.path}</code></div>
<div class="modal-actions">
<button class="primary" onClick=${() => onResolve("workspace", "switch")}>Switch (Enter)</button>
<button class="danger" onClick=${() => onResolve("workspace", "deny")}>Deny (Esc)</button>
<button class="primary" onClick=${() => onResolve("workspace", "switch")}>${t("modal.switchBtn")}</button>
<button class="danger" onClick=${() => onResolve("workspace", "deny")}>${t("modal.denyBtn")}</button>
</div>
<//>
`;
}
export function CheckpointModal({ modal, onResolve }: { modal: CheckpointSpec; onResolve: OnResolve }) {
useLang();
const [reviseText, setReviseText] = useState("");
const [staged, setStaged] = useState(false);
const label = modal.title ? `${modal.stepId} · ${modal.title}` : modal.stepId;
@@ -577,31 +628,31 @@ export function CheckpointModal({ modal, onResolve }: { modal: CheckpointSpec; o
<${ModalCard}
accent="#a5f3fc"
icon="✓"
title=${`step complete${counter}`}
title=${t("modal.stepComplete", { counter })}
subtitle=${label}
>
${
staged
? html`
<textarea
placeholder="What needs to change before the next step? Leave blank to just continue."
placeholder=${t("modal.revisePlaceholder")}
rows="3"
value=${reviseText}
onInput=${(e: Event) => setReviseText((e.target as HTMLTextAreaElement).value)}
></textarea>
<div class="modal-actions">
<button class="primary" onClick=${() => onResolve("checkpoint", "revise", reviseText)}>Send revision</button>
<button class="primary" onClick=${() => onResolve("checkpoint", "revise", reviseText)}>${t("modal.sendRevision")}</button>
<button onClick=${() => {
setStaged(false);
setReviseText("");
}}>Back</button>
}}>${t("common.back")}</button>
</div>
`
: html`
<div class="modal-actions">
<button class="primary" onClick=${() => onResolve("checkpoint", "continue")}>Continue</button>
<button onClick=${() => setStaged(true)}>Revise…</button>
<button class="danger" onClick=${() => onResolve("checkpoint", "stop")}>Stop</button>
<button class="primary" onClick=${() => onResolve("checkpoint", "continue")}>${t("modal.continueBtn")}</button>
<button onClick=${() => setStaged(true)}>${t("modal.reviseBtn")}</button>
<button class="danger" onClick=${() => onResolve("checkpoint", "stop")}>${t("modal.stopBtn")}</button>
</div>
`
}
@@ -609,14 +660,229 @@ export function CheckpointModal({ modal, onResolve }: { modal: CheckpointSpec; o
`;
}
export function PickerModal({
modal,
onResolve,
}: {
modal: PickerModalSpec;
onResolve: OnResolve;
}) {
useLang();
const [selectedId, setSelectedId] = useState<string | null>(modal.items[0]?.id ?? null);
const [query, setQuery] = useState(modal.query ?? "");
const [renameTarget, setRenameTarget] = useState<string | null>(null);
const [renameText, setRenameText] = useState("");
const [showNew, setShowNew] = useState(false);
const [newText, setNewText] = useState("");
const has = (a: PickerActionName) => modal.actions.includes(a);
const selected = modal.items.find((i) => i.id === selectedId) ?? null;
const submitRefine = (next: string) => {
setQuery(next);
if (has("refine")) onResolve("picker", { action: "refine", query: next });
};
const startRename = (id: string) => {
const item = modal.items.find((i) => i.id === id);
if (!item) return;
setRenameTarget(id);
setRenameText(item.title);
};
const sendRename = () => {
if (!renameTarget || !renameText.trim()) return;
onResolve("picker", { action: "rename", id: renameTarget, text: renameText });
setRenameTarget(null);
setRenameText("");
};
const sendNew = () => {
onResolve("picker", newText.trim() ? { action: "new", text: newText } : { action: "new" });
setShowNew(false);
setNewText("");
};
return html`
<${ModalCard}
accent="#fcd34d"
icon="≡"
title=${modal.title}
subtitle=${modal.hint}
>
${
has("refine")
? html`<input
class="modal-picker-search"
type="search"
placeholder=${t("modal.pickerFilter")}
value=${query}
onInput=${(e: Event) => submitRefine((e.target as HTMLInputElement).value)}
/>`
: null
}
<div class="modal-picker-list">
${
modal.items.length === 0
? html`<div class="modal-picker-empty">${t("modal.pickerEmpty")}</div>`
: modal.items.map(
(it) => html`
<button
key=${it.id}
class=${`modal-picker-row${it.id === selectedId ? " selected" : ""}`}
onClick=${() => setSelectedId(it.id)}
onDblClick=${() => has("pick") && onResolve("picker", { action: "pick", id: it.id })}
>
<span class="modal-picker-title">${it.title}</span>
${it.badge ? html`<span class="modal-picker-badge">${it.badge}</span>` : null}
${it.subtitle ? html`<span class="modal-picker-subtitle">${it.subtitle}</span>` : null}
${it.meta ? html`<span class="modal-picker-meta">${it.meta}</span>` : null}
</button>
`,
)
}
</div>
${
modal.hasMore && has("load-more")
? html`<button
class="modal-picker-more"
onClick=${() => onResolve("picker", { action: "load-more" })}
>${t("modal.pickerLoadMore")}</button>`
: null
}
${
renameTarget
? html`
<div class="modal-picker-form">
<input
type="text"
value=${renameText}
onInput=${(e: Event) => setRenameText((e.target as HTMLInputElement).value)}
/>
<div class="modal-actions">
<button class="primary" onClick=${sendRename} disabled=${!renameText.trim()}>${t("common.save")}</button>
<button onClick=${() => setRenameTarget(null)}>${t("common.back")}</button>
</div>
</div>
`
: showNew
? html`
<div class="modal-picker-form">
<input
type="text"
placeholder=${t("modal.pickerNewPlaceholder")}
value=${newText}
onInput=${(e: Event) => setNewText((e.target as HTMLInputElement).value)}
/>
<div class="modal-actions">
<button class="primary" onClick=${sendNew}>${t("common.add")}</button>
<button onClick=${() => setShowNew(false)}>${t("common.back")}</button>
</div>
</div>
`
: html`
<div class="modal-actions">
${
has("pick") && selected
? html`<button
class="primary"
onClick=${() => onResolve("picker", { action: "pick", id: selected.id })}
>${t("modal.pickerPick")}</button>`
: null
}
${
has("install") && selected
? html`<button
class="primary"
onClick=${() => onResolve("picker", { action: "install", id: selected.id })}
>${t("modal.pickerInstall")}</button>`
: null
}
${
has("uninstall") && selected
? html`<button
onClick=${() => onResolve("picker", { action: "uninstall", id: selected.id })}
>${t("modal.pickerUninstall")}</button>`
: null
}
${
has("rename") && selected
? html`<button onClick=${() => startRename(selected.id)}>${t("modal.pickerRename")}</button>`
: null
}
${
has("delete") && selected
? html`<button
class="danger"
onClick=${() => onResolve("picker", { action: "delete", id: selected.id })}
>${t("common.delete")}</button>`
: null
}
${
has("new")
? html`<button onClick=${() => setShowNew(true)}>${t("modal.pickerNew")}</button>`
: null
}
<button onClick=${() => onResolve("picker", { action: "cancel" })}>${t("modal.cancel")}</button>
</div>
`
}
<//>
`;
}
export function ViewerModal({
modal,
onResolve,
}: {
modal: ViewerModalSpec;
onResolve: OnResolve;
}) {
useLang();
return html`
<${ModalCard}
accent="#67e8f9"
icon="◇"
title=${modal.title}
subtitle=${modal.meta}
>
${
modal.steps && modal.steps.length > 0
? html`
<ol class="modal-viewer-steps">
${modal.steps.map(
(s: ViewerStep) => html`
<li key=${s.id} class=${`modal-viewer-step modal-viewer-step-${s.status}`}>
<span class="modal-viewer-step-mark">${s.status === "done" ? "✓" : "·"}</span>
<span class="modal-viewer-step-title">${s.title}</span>
</li>
`,
)}
</ol>
`
: null
}
${
modal.body
? html`<div class="md modal-viewer-body" dangerouslySetInnerHTML=${{ __html: marked.parse(modal.body) }}></div>`
: null
}
<div class="modal-actions">
<button onClick=${() => onResolve("viewer", { action: "close" })}>${t("modal.viewerClose")}</button>
</div>
<//>
`;
}
export function RevisionModal({ modal, onResolve }: { modal: RevisionSpec; onResolve: OnResolve }) {
useLang();
const riskColor = (r: string | undefined) =>
r === "high" ? "#f87171" : r === "med" ? "#fbbf24" : r === "low" ? "#86efac" : "#9ca3af";
return html`
<${ModalCard}
accent="#c4b5fd"
icon="✎"
title="model proposed a plan revision"
title=${t("modal.revisionTitle")}
subtitle=${modal.summary || modal.reason}
>
<div class="modal-revise-reason">${modal.reason}</div>
@@ -633,8 +899,8 @@ export function RevisionModal({ modal, onResolve }: { modal: RevisionSpec; onRes
)}
</ol>
<div class="modal-actions">
<button class="primary" onClick=${() => onResolve("revision", "accept")}>Accept</button>
<button class="danger" onClick=${() => onResolve("revision", "reject")}>Reject</button>
<button class="primary" onClick=${() => onResolve("revision", "accept")}>${t("modal.accept")}</button>
<button class="danger" onClick=${() => onResolve("revision", "reject")}>${t("modal.reject")}</button>
</div>
<//>
`;
+590
View File
@@ -0,0 +1,590 @@
export const en = {
app: {
sectionWorkspace: "workspace",
sectionObserve: "observe",
sectionConfigure: "configure",
tabChat: "Chat",
tabPlans: "Plans",
tabSessions: "Sessions",
tabOverview: "Overview",
tabUsage: "Usage",
tabSystem: "System",
tabSemantic: "Semantic",
tabTools: "Tools",
tabPermissions: "Permissions",
tabMcp: "MCP",
tabSkills: "Skills",
tabMemory: "Memory",
tabHooks: "Hooks",
tabSettings: "Settings",
footer: "127.0.0.1 only · token-gated",
},
common: {
loading: "loading…",
loadingFailed: "{name} failed: {error}",
back: "← back",
save: "Save",
remove: "remove",
cancel: "Cancel",
delete: "Delete",
add: "Add",
confirm: "Confirm",
noData: "No {name} yet.",
all: "all",
yes: "yes",
no: "no",
on: "ON",
off: "off",
enabled: "enabled",
disabled: "disabled",
},
settings: {
title: "Settings",
loading: "loading settings…",
saved: "saved: {fields}",
sectionApi: "DeepSeek API",
apiKey: "API key",
notSet: "(not set)",
replace: "replace",
pasteKey: "paste a fresh sk-… token",
saveKey: "Save key",
baseUrl: "base url",
baseUrlPlaceholder: "https://api.deepseek.com (default)",
sectionDefaults: "Defaults",
preset: "preset",
presetAuto: "auto — flash → pro on hard turns",
presetFlash: "flash — always flash, no auto-escalate",
presetPro: "pro — always pro",
appliesNextTurn: "applies next turn",
effort: "effort",
effortMax: "max (default — best)",
effortHigh: "high (cheaper / faster)",
webSearch: "web search",
webSearchNote: "web_fetch + web_search tools",
sectionCompute: "Compute",
proNext: "/pro one-shot",
proArm: "Arm for next turn",
proArmed: "Armed — disarms after next turn",
proNextNote: "next turn runs on deepseek-v4-pro, then auto-disarms",
sectionBudget: "Budget",
budgetOf: "of",
budgetSetCap: "set a cap",
budgetCustom: "custom",
budgetBumpHint: "bump the cap to keep going",
budgetClear: "Clear cap",
budgetIdleLine: "warns at 80% · refuses past 100%",
budgetWarnLine: "approaching cap — loop will refuse past 100%",
budgetRefusing: "cap exhausted — next turn refused until bumped or cleared",
sectionLoop: "Loop",
loopIdleHint: "Auto-resubmit a prompt on a fixed interval.",
loopCostHint: "Each iteration costs ~{cost} (last turn).",
loopInterval: "interval",
loopCustom: "custom",
loopRangeError: "interval must fall in 5s..6h",
loopPrompt: "prompt",
loopPromptPlaceholder: "e.g. check the deploy status and report any errors",
loopStart: "Start loop",
loopStop: "Stop",
loopRunning: "running",
loopIter: "iter {iter}",
loopFiresIn: "fires in {remaining}",
sectionRuntime: "Runtime",
activeModel: "active model",
modelPricingLine: "${hit} hit · ${miss} miss · ${out} out per 1M tok",
editMode: "edit mode",
editModeNote: "switch from the Chat tab header",
sectionLanguage: "Language",
language: "language",
langEn: "English",
langZhCn: "简体中文",
},
chat: {
modeMirror: "TUI mirror",
modeView: "session view",
placeholder: "Type a prompt — Enter sends, Shift+Enter for a newline · / @ for pickers",
placeholderBusy: "wait for the current turn to finish…",
send: "Send",
new: "New",
clear: "Clear",
newTitle: "/new — wipe conversation context (loop log + scrollback)",
clearTitle: "/clear — wipe just visible scrollback (context kept)",
noConversation: "No conversation yet. Send a prompt below to begin.",
newConfirmBusy: "A turn is in flight. Abort and start a new conversation?",
newConfirm: "Clear current conversation and start fresh?",
newToast: "new conversation",
clearToast: "scrollback cleared",
newFailed: "/new failed: {error}",
clearFailed: "/clear failed: {error}",
eventStreamError: "event stream interrupted — reconnecting…",
semanticBanner: "Semantic search isn't enabled for this project.",
semanticBannerDesc:
'Build the index once and the model can find code by meaning ("where do we handle auth failures?") instead of grep on exact strings.',
semanticBannerBtn: "Build it →",
semanticBannerDismiss: "dismiss (don't show again)",
slashCommands: "slash commands",
projectFiles: "project files",
effortTitle: "reasoning_effort — applies next turn",
effortMaxTitle: "max (default — best quality)",
effortHighTitle: "high (cheaper / faster)",
presetTitle: "preset — model commitment",
presetAutoTitle:
"auto — flash baseline; auto-escalates to pro on hard turns (NEEDS_PRO / failure threshold)",
presetFlashTitle:
"flash — always flash; no auto-escalate. /pro still works for one-shot manual",
presetProTitle:
"pro — always pro; ~3× flash cost (5/31 discount). Locks in on hard architecture work.",
editGateTitle: "edit gate — Shift+Tab cycles in TUI",
editReviewTitle: "review — both edits and non-allowlisted shell ask first",
editAutoTitle: "auto — edits auto-apply, shell still asks",
editYoloTitle: "yolo — edits AND shell auto-run, allowlist bypassed",
railSession: "Session",
railTurns: "turns",
railPromptTok: "prompt tok",
railCost: "cost",
railCacheHit: "cache hit",
railToolBudget: "Tool budget",
railSpend: "spend",
railActivePlan: "Active plan",
railProgress: "progress",
statusModel: "model",
statusCtx: "ctx",
statusCache: "cache",
statusTurn: "turn",
statusSession: "session",
statusBalance: "balance",
statusTurns: "{count} turn{s}",
waitingStats: "· · · waiting for live stats",
inflightPhase: "{phase}",
inflightRunning: "running",
inflightThinking: "thinking",
inflightStreaming: "streaming",
inflightWaiting: "waiting",
inflightReasoning: "reasoning {count} ch",
inflightOut: "out {count} ch",
abortBtn: "Abort (Esc)",
confirmBtn: "Apply (y)",
rejectBtn: "Reject (n)",
applyRestBtn: "Apply rest (a)",
flipAutoBtn: "Flip to AUTO (A)",
},
overview: {
loading: "loading overview…",
failed: "overview failed: {error}",
standaloneTitle: "Standalone mode",
standaloneDesc:
"Read-only disk view. Start /dashboard from inside reasonix code for live session state, MCP, and tools.",
cockpit: "Cockpit",
balance: "balance",
tokens7d: "tokens · 7d",
cacheHit: "cache hit",
toolCalls24h: "tool calls · 24h",
budget: "budget",
currentSession: "current session",
noSession: "No live session — /dashboard from inside reasonix code to attach.",
promptTok: "prompt tok",
completionTok: "completion tok",
cost: "cost",
costTrend: "cost · 14 day",
noUsageYet: "no usage yet",
dayAvg: "/day avg",
recentPlans: "recent plans",
noPlans: "No plans yet — submit one with submit_plan.",
toolActivity: "tool activity",
noToolCalls: "No tool calls yet.",
toolsLoaded: "tools loaded",
mcpServers: "mcp servers",
editMode: "edit mode",
version: "Reasonix",
workingDir: "Working directory",
projectRoot: "project root",
noPriorData: "no prior data",
stable: "— stable",
vsPrior: "{arrow} {pct}% vs prior",
active: "active",
allUp: "all up",
yoloWarning: "all prompts bypassed",
checking: "checking",
latest: "latest",
},
usage: {
loading: "loading usage…",
failed: "usage failed: {error}",
records: "{count} records",
dailyUsage: "Daily usage",
dailyMeta: "cost · cache saved · turns",
noData: "No usage data yet — run a turn in reasonix chat / code / run and refresh.",
windows: "Rolling windows",
colTurns: "turns",
colCacheHit: "cache hit",
colCost: "cost (USD)",
colCacheSaved: "cache saved",
colVsClaude: "vs Claude",
colSaved: "saved",
mostUsed: "Most used models",
colModel: "model",
},
sessions: {
loading: "loading sessions…",
failed: "sessions failed: {error}",
noSessions: "No saved sessions yet.",
filterPlaceholder: "filter sessions",
msgs: "msgs",
pickHint: "Pick a session on the left to read its transcript.",
resumeTitle: "Resume in TUI",
resumeDesc:
"Mid-session swap requires a restart so the message log can rewind cleanly. Quit your current session, then run:",
loadingTranscript: "loading transcript…",
emptyTranscript: "empty transcript.",
messages: "{count} message{s}",
},
tools: {
loading: "loading tools…",
failed: "tools failed: {error}",
noTools: "No tools registered.",
planMode: "plan mode — writes gated",
colTool: "tool",
colFlags: "flags",
colDesc: "description",
readOnly: "read-only",
write: "write",
flat: "flat",
},
permissions: {
loading: "loading permissions…",
failed: "permissions failed: {error}",
yoloTitle: "YOLO mode",
yoloDesc:
"Every shell command auto-runs, allowlist bypassed. Switch back with /mode review in the TUI.",
project: "project",
builtin: "builtin",
addPrefix: "add a prefix",
addPlaceholder: 'e.g. "npm run build" or "deploy.sh"',
clearAll: "Clear all",
alreadyIn: "{prefix} already in list",
added: "added: {prefix}",
removed: "removed: {prefix}",
cleared: "cleared {count} entr{y}",
removeConfirm: 'Remove "{prefix}" from this project\'s allowlist?',
clearConfirm: "Wipe every project allowlist entry? Builtin entries are unaffected.",
projectAllowlist: "Project allowlist · {count}",
nothingStored: "Nothing stored yet for this project.",
colNum: "#",
colPrefix: "prefix",
builtinTitle: "Builtin · {count} · read-only",
standaloneWarning:
"Mutations require /dashboard from inside an active reasonix code session — standalone reasonix dashboard can't tell which project's allowlist to edit.",
},
mcp: {
loading: "loading MCP…",
servers: "MCP servers · {count} bridged",
all: "all",
live: "live",
unbridged: "unbridged",
specPlaceholder: "spec — e.g. fs=npx -y @modelcontextprotocol/...",
saved: "saved",
savedRestart: "saved — restart reasonix code to bridge this server",
removed: "removed — restart to drop the live bridge",
removeConfirm: "Remove MCP spec from config?\n\n{spec}",
noServers: "No MCP servers in this session.",
tools: "tools",
inConfig: "in config · not loaded",
unbridgedTitle: "unbridged · in config",
removeBtn: "Remove",
spec: "spec",
whyUnbridged: "Why unbridged?",
whyUnbridgedDesc:
"This spec lives in your config.json but isn't bridged into the live session. MCP servers attach when reasonix code starts; the dashboard alone can't spawn the child process.",
whyUnbridgedHint: "To activate: restart reasonix code, then refresh this dashboard.",
pickHint: "Pick an MCP server on the left to inspect tools / resources / prompts.",
toolsTitle: "Tools · {count}",
resourcesTitle: "Resources · {count}",
promptsTitle: "Prompts · {count}",
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…",
files: "memory · {count} files",
exists: "exists",
create: "create",
noFiles: "No memory files yet.",
pickHint: "Pick a memory file on the left.",
pickDesc: "Project REASONIX.md is committable; global notes live in ~/.reasonix/memory/.",
chars: "{count} chars",
saved: "saved {scope}",
reloadHint: "re-applied on next /new or session restart",
},
hooks: {
loading: "loading hooks…",
resolved: "resolved",
eventMatrix: "Event matrix",
matrixSub: "{scripts} script{s} × {events} event{s}",
noHooks: "No hooks configured. Edit the JSON below to add some.",
colScript: "script",
noProject: "No active project — open /dashboard from reasonix code to edit project hooks.",
saveReload: "Save + Reload",
discard: "Discard changes",
savedReloaded: "saved + reloaded {scope}",
recentRuns: "Recent runs",
noRuns: "No hook runs in the recent session log.",
colWhen: "when",
colPhase: "phase",
colHook: "hook",
colOutcome: "outcome",
},
skills: {
loading: "loading skills…",
filterPlaceholder: "filter skills",
project: "project",
global: "global",
builtin: "builtin",
newSkill: "new skill",
noDescription: "(no description)",
runs7d: "runs · 7d",
pickHint: "Pick a skill on the left, or create a new one above.",
readOnlyBuiltin: "read-only · builtin",
builtinDesc:
"Built-in skills ship with Reasonix; the model picks them up automatically. To customize, create a project- or global-scoped skill with the same name.",
saved: "saved {scope}/{name}",
deleteConfirm: "Delete skill {scope}/{name}?",
reloadHint: "re-loaded on next /new or session restart",
},
system: {
loading: "loading health…",
failed: "health failed: {error}",
healthChecks: "Health checks",
version: "version",
checking: "checking",
latest: "● latest",
outOfDate: "● out of date",
versionPending: "version check pending",
upToDate: "up to date",
latestVer: "latest: {version}",
sessions: "sessions",
ok: "● ok",
memory: "memory",
semanticIndex: "semantic index",
built: "● built",
none: "— none",
runIndex: "run reasonix index to build",
usageLog: "usage log",
backgroundJobs: "background jobs",
noSession: "— no session",
running: "{count} running",
attachHint: "attach a session to see jobs",
shellSpawn: "shell + spawn",
paths: "paths",
home: "home",
sessionsPath: "sessions",
memoryPath: "memory",
semanticPath: "semantic",
usagePath: "usage",
},
plans: {
loading: "loading plans…",
failed: "plans failed: {error}",
noPlans: "No archived plans yet — run a turn that calls submit_plan and mark_step_complete.",
filterPlaceholder: "filter plans",
active: "active",
done: "done",
idle: "idle",
steps: "steps",
pickHint: "Pick a plan on the left.",
noTitle: "(no title)",
stepTimeline: "Step timeline · {done} / {total}",
step: "step {n}",
},
semantic: {
codeRequired: "Semantic — code-mode required",
indexBuilt: "index built",
noIndex: "no index yet",
ready: "ready",
setupNeeded: "setup needed",
installOllama: "Install Ollama",
installOllamaDesc:
"Reasonix doesn't run package managers for you. Install Ollama first, then come back:",
macWindows: "macOS / Windows:",
download: "download from ollama.com/download",
linux: "Linux:",
refreshHint:
"Refresh after install — this panel will offer to start the daemon and pull {model}.",
daemon: "Daemon",
daemonDesc: "ollama is on your PATH but the HTTP daemon isn't reachable.",
startDaemon: "Start daemon",
runsOllama: "runs ollama serve detached",
model: "Model",
modelMissing: "{model} isn't installed yet.",
modelSize: "~270 MB on first pull.",
pulling: "pulling…",
pullModel: "Pull {model}",
indexStatus: "index status",
builtStatus: "● built",
incompatibleStatus: "● incompatible",
chunks: "chunks",
files: "files",
dim: "dim",
size: "size",
lastBuild: "last build",
builtWith: "built with",
currentTarget: "current target",
incompatibleHint: "This on-disk index was built for a different provider or model. Run Rebuild to replace it.",
runIndexHint: "Run an index to enable semantic_search.",
reIndex: "Re-index",
build: "Build",
rebuild: "Rebuild",
stop: "Stop",
provider: "provider",
providerType: "service type",
openaiCompat: "openai-compatible",
apiUrl: "API URL",
apiKey: "API key",
apiKeyStoredNote: "API key is stored in ~/.reasonix/config.json — do not share that file.",
customRequestBody: "custom request body",
invalidCustomRequestBody: "Custom request body must be valid JSON: {error}",
customRequestBodyMustBeObject: "Custom request body must be a JSON object.",
saveBeforeIndex: "Save semantic settings before starting an index.",
extraBody: "extra body",
keepExistingKey: "leave blank to keep existing key",
remoteProvider: "Remote embedding provider",
remoteProviderDesc:
"Configure the full OpenAI-compatible embeddings URL here. Reasonix will send requests exactly to the URL you provide.",
ollama: "ollama",
binary: "binary",
found: "found",
missing: "missing",
daemonStatus: "daemon",
up: "up",
down: "down",
pulled: "pulled",
indexConfig: "index config",
reset: "reset",
excludeDirs: "exclude dirs",
excludeFiles: "exclude files",
excludeExts: "exclude exts",
excludePatterns: "exclude patterns",
glob: "glob",
respectGitignore: "respect .gitignore",
maxFileBytes: "max file bytes",
skipLarger: "skip files larger than ~{size} MiB",
preview: "Preview",
searchPlaceholder: "describe what to find — 'where do we handle abort signals'",
searching: "searching…",
results: "{count} result{s} · {ms}ms · {model}",
noMatches: "No matches above the score threshold.",
previewSummary: "Preview — would index {included} file(s), skip {skipped}",
nothingSkipped: "nothing skipped — all walked files would be indexed.",
firstIncluded: "first {count} included file(s)",
job: "Job",
phaseSetup: "preparing",
phaseScan: "scanning files",
phaseEmbed: "embedding chunks",
phaseWrite: "writing index",
phaseDone: "done",
phaseError: "error",
phaseCancelled: "cancelled",
setupFailed: "setup failed",
stopping: "stopping",
scanned: "scanned {count}",
changed: "changed {count}",
skipped: "skipped {count}",
chunksProgress: "{done} / {total} ({pct}%)",
result: "result",
added: "added {count}",
removed: "removed {count}",
failed: "failed {count}",
skippedFiles: "{total} files ({details})",
rebuildStarted: "rebuild started",
incrementalStarted: "incremental index started",
stopRequested: "stopping requested — current chunk batch will finish first",
startingDaemon: "starting ollama daemon (15s timeout)…",
daemonUp: "daemon is up",
daemonTimeout: "daemon didn't come up in time — check ollama serve manually",
pullingModel: "pulling {model} — this may take a few minutes on first install",
savedConfig: "saved · {count} fields updated · re-run index to apply",
runningPreview: "running dry walk against project root…",
exclude: "exclude",
},
modal: {
shellTitle: "shell command",
shellBgTitle: "background process",
shellSubtitle: "model wants to run a shell command",
shellBgSubtitle: "long-running — keeps running after approval",
runOnce: "Run once",
alwaysAllow: 'Always allow "{prefix}"',
deny: "Deny",
choiceTitle: "model wants you to pick",
typeOwn: "Type my own answer",
typeOwnSummary: "None of the above fits — write a free-form reply.",
typePlaceholder: "Type a free-form answer…",
send: "Send",
cancel: "Cancel",
cancelSummary: "Drop the question. Model will ask what you actually want.",
planTitle: "plan submitted",
planSubtitle: "model proposed a plan; review then pick",
approveInstructions:
"Optional last instructions / answers to open questions (Enter to send blank)",
refinePlaceholder: "What needs to change? Be specific.",
approve: "Approve",
refine: "Refine",
sendRefinement: "Send refinement",
editTitle: "edit pending review",
editSubtitle: "{path} · {remaining} of {total} blocks remaining",
before: "before",
after: "after",
workspaceTitle: "model wants to switch workspace",
workspaceSubtitle: "every subsequent file / shell / memory tool resolves against the new root",
switchBtn: "Switch (Enter)",
denyBtn: "Deny (Esc)",
stepComplete: "step complete{counter}",
continueBtn: "Continue",
reviseBtn: "Revise…",
stopBtn: "Stop",
revisionTitle: "model proposed a plan revision",
sendRevision: "Send revision",
accept: "Accept",
reject: "Reject",
arguments: "arguments",
revisePlaceholder: "What needs to change before the next step? Leave blank to just continue.",
pickerFilter: "Filter…",
pickerEmpty: "Nothing to show.",
pickerLoadMore: "Load more",
pickerPick: "Open",
pickerInstall: "Install",
pickerUninstall: "Uninstall",
pickerRename: "Rename…",
pickerNew: "New…",
pickerNewPlaceholder: "Name (leave blank for default)",
viewerClose: "Close",
},
};
+8
View File
@@ -0,0 +1,8 @@
import { createT } from "../lib/i18n.js";
import { en } from "./en.js";
import { zhCN } from "./zh-CN.js";
export { getLang, initLangFromServer, setLang, useLang, onLangChange } from "../lib/i18n.js";
export type { DashboardLang } from "../lib/i18n.js";
export const t = createT({ en, "zh-CN": zhCN });
+580
View File
@@ -0,0 +1,580 @@
export const zhCN = {
app: {
sectionWorkspace: "工作区",
sectionObserve: "监控",
sectionConfigure: "配置",
tabChat: "对话",
tabPlans: "计划",
tabSessions: "会话",
tabOverview: "概览",
tabUsage: "用量",
tabSystem: "系统",
tabSemantic: "语义",
tabTools: "工具",
tabPermissions: "权限",
tabMcp: "MCP",
tabSkills: "技能",
tabMemory: "记忆",
tabHooks: "钩子",
tabSettings: "设置",
footer: "仅 127.0.0.1 · Token 保护",
},
common: {
loading: "加载中…",
loadingFailed: "{name}失败:{error}",
back: "← 返回",
save: "保存",
remove: "移除",
cancel: "取消",
delete: "删除",
add: "添加",
confirm: "确认",
noData: "暂无{name}。",
all: "全部",
yes: "是",
no: "否",
on: "开启",
off: "关闭",
enabled: "已启用",
disabled: "已禁用",
},
settings: {
title: "设置",
loading: "加载设置…",
saved: "已保存:{fields}",
sectionApi: "DeepSeek API",
apiKey: "API 密钥",
notSet: "(未设置)",
replace: "替换",
pasteKey: "粘贴新的 sk-… 令牌",
saveKey: "保存密钥",
baseUrl: "基础 URL",
baseUrlPlaceholder: "https://api.deepseek.com(默认)",
sectionDefaults: "默认设置",
preset: "预设",
presetAuto: "auto — flash 基线,困难时自动升级为 pro",
presetFlash: "flash — 始终使用 flash,不自动升级",
presetPro: "pro — 始终使用 pro",
appliesNextTurn: "下一轮生效",
effort: "推理强度",
effortMax: "max(默认 — 最佳质量)",
effortHigh: "high(更便宜 / 更快)",
webSearch: "网页搜索",
webSearchNote: "web_fetch + web_search 工具",
sectionCompute: "计算",
proNext: "/pro 单轮",
proArm: "为下一轮装备",
proArmed: "已装备 — 下一轮后自动解除",
proNextNote: "下一轮使用 deepseek-v4-pro,之后自动解除",
sectionBudget: "预算",
budgetOf: "/",
budgetSetCap: "设置上限",
budgetCustom: "自定义",
budgetBumpHint: "提高上限以继续",
budgetClear: "清除上限",
budgetIdleLine: "80% 时提醒 · 100% 后拒绝执行",
budgetWarnLine: "接近上限 — 超过 100% 将拒绝执行",
budgetRefusing: "已超出上限 — 提高或清除后才会继续",
sectionLoop: "循环",
loopIdleHint: "按固定间隔自动重新提交一段提示词。",
loopCostHint: "每次迭代约 {cost}(上一轮成本)。",
loopInterval: "间隔",
loopCustom: "自定义",
loopRangeError: "间隔需在 5s..6h 之间",
loopPrompt: "提示词",
loopPromptPlaceholder: "例如:检查部署状态并汇报任何错误",
loopStart: "启动循环",
loopStop: "停止",
loopRunning: "运行中",
loopIter: "第 {iter} 次",
loopFiresIn: "{remaining} 后触发",
sectionRuntime: "运行时",
activeModel: "当前模型",
modelPricingLine: "${hit} 命中 · ${miss} 未命中 · ${out} 输出 / 100 万 tok",
editMode: "编辑模式",
editModeNote: "在对话标签页头部切换",
sectionLanguage: "语言",
language: "语言",
langEn: "English",
langZhCn: "简体中文",
},
chat: {
modeMirror: "TUI 镜像",
modeView: "会话视图",
placeholder: "输入提示词 — Enter 发送,Shift+Enter 换行 · / @ 打开选择器",
placeholderBusy: "请等待当前轮次完成…",
send: "发送",
new: "新建",
clear: "清除",
newTitle: "/new — 清除对话上下文(循环日志 + 滚动回放)",
clearTitle: "/clear — 仅清除可见的滚动回放(上下文保留)",
noConversation: "暂无对话。在下方发送提示词开始。",
newConfirmBusy: "有轮次正在执行。中止并开始新对话?",
newConfirm: "清除当前对话并重新开始?",
newToast: "新对话",
clearToast: "滚动回放已清除",
newFailed: "/new 失败:{error}",
clearFailed: "/clear 失败:{error}",
eventStreamError: "事件流中断 — 正在重连…",
semanticBanner: "此项目未启用语义搜索。",
semanticBannerDesc:
"构建一次索引,模型即可按含义查找代码(“哪里处理认证失败?”),而不仅依赖精确字符串的 grep。",
semanticBannerBtn: "构建 →",
semanticBannerDismiss: "关闭(不再显示)",
slashCommands: "斜杠命令",
projectFiles: "项目文件",
effortTitle: "reasoning_effort — 下一轮生效",
effortMaxTitle: "max(默认 — 最佳质量)",
effortHighTitle: "high(更便宜 / 更快)",
presetTitle: "预设 — 模型承诺",
presetAutoTitle: "auto — flash 基线;困难轮次自动升级为 pro(NEEDS_PRO / 失败阈值)",
presetFlashTitle: "flash — 始终 flash;不自动升级。/pro 仍可用于一次性手动提升",
presetProTitle: "pro — 始终 pro;约 3 倍 flash 成本(5/31 折扣)。锁定困难的架构工作。",
editGateTitle: "编辑门控 — Shift+Tab 在 TUI 中循环",
editReviewTitle: "review — 编辑和非允许列表的 shell 命令都会先询问",
editAutoTitle: "auto — 编辑自动应用,shell 仍会询问",
editYoloTitle: "yolo — 编辑和 shell 都自动运行,绕过允许列表",
railSession: "会话",
railTurns: "轮次",
railPromptTok: "提示 tokens",
railCost: "费用",
railCacheHit: "缓存命中",
railToolBudget: "工具预算",
railSpend: "已用",
railActivePlan: "活跃计划",
railProgress: "进度",
statusModel: "模型",
statusCtx: "上下文",
statusCache: "缓存",
statusTurn: "轮次",
statusSession: "会话",
statusBalance: "余额",
statusTurns: "{count} 轮",
waitingStats: "· · · 等待实时统计",
inflightPhase: "{phase}",
inflightRunning: "运行中",
inflightThinking: "思考中",
inflightStreaming: "输出中",
inflightWaiting: "等待中",
inflightReasoning: "推理 {count} 字符",
inflightOut: "输出 {count} 字符",
abortBtn: "中止 (Esc)",
confirmBtn: "应用 (y)",
rejectBtn: "拒绝 (n)",
applyRestBtn: "应用剩余 (a)",
flipAutoBtn: "切换为 AUTO (A)",
},
overview: {
loading: "加载概览…",
failed: "概览失败:{error}",
standaloneTitle: "独立模式",
standaloneDesc:
"只读磁盘视图。在 reasonix code 内启动 /dashboard 以获取实时会话状态、MCP 和工具。",
cockpit: "驾驶舱",
balance: "余额",
tokens7d: "tokens · 7 天",
cacheHit: "缓存命中",
toolCalls24h: "工具调用 · 24 小时",
budget: "预算",
currentSession: "当前会话",
noSession: "无活跃会话 — 在 reasonix code 内执行 /dashboard 进行连接。",
promptTok: "提示 tokens",
completionTok: "补全 tokens",
cost: "费用",
costTrend: "费用 · 14 天",
noUsageYet: "暂无用量",
dayAvg: "/天 均值",
recentPlans: "近期计划",
noPlans: "暂无计划 — 使用 submit_plan 提交一个。",
toolActivity: "工具活动",
noToolCalls: "暂无工具调用。",
toolsLoaded: "已加载工具",
mcpServers: "MCP 服务器",
editMode: "编辑模式",
version: "Reasonix",
workingDir: "工作目录",
projectRoot: "项目根目录",
noPriorData: "无历史数据",
stable: "— 稳定",
vsPrior: "{arrow} {pct}% 较上期",
active: "活跃",
allUp: "全部在线",
yoloWarning: "所有提示被绕过",
checking: "检查中",
latest: "最新",
},
usage: {
loading: "加载用量…",
failed: "用量失败:{error}",
records: "{count} 条记录",
dailyUsage: "每日用量",
dailyMeta: "费用 · 缓存节省 · 轮次",
noData: "暂无用量数据 — 在 reasonix chat / code / run 中执行一轮,然后刷新。",
windows: "滚动窗口",
colTurns: "轮次",
colCacheHit: "缓存命中",
colCost: "费用 (USD)",
colCacheSaved: "缓存节省",
colVsClaude: "对比 Claude",
colSaved: "节省",
mostUsed: "最常用模型",
colModel: "模型",
},
sessions: {
loading: "加载会话…",
failed: "会话失败:{error}",
noSessions: "暂无已保存的会话。",
filterPlaceholder: "筛选会话",
msgs: "条消息",
pickHint: "选择左侧的会话以查看其转录稿。",
resumeTitle: "在 TUI 中恢复",
resumeDesc: "会话中途切换需要重启,以便消息日志可以干净地回退。请退出当前会话,然后运行:",
loadingTranscript: "加载转录稿…",
emptyTranscript: "空的转录稿。",
messages: "{count} 条消息",
},
tools: {
loading: "加载工具…",
failed: "工具失败:{error}",
noTools: "未注册任何工具。",
planMode: "计划模式 — 写入受限",
colTool: "工具",
colFlags: "标志",
colDesc: "描述",
readOnly: "只读",
write: "写入",
flat: "扁平",
},
permissions: {
loading: "加载权限…",
failed: "权限失败:{error}",
yoloTitle: "YOLO 模式",
yoloDesc: "所有 shell 命令自动运行,允许列表被绕过。在 TUI 中使用 /mode review 切换回来。",
project: "项目",
builtin: "内置",
addPrefix: "添加前缀",
addPlaceholder: '例如 "npm run build" 或 "deploy.sh"',
clearAll: "清除全部",
alreadyIn: "{prefix} 已在列表中",
added: "已添加:{prefix}",
removed: "已移除:{prefix}",
cleared: "已清除 {count} 条",
removeConfirm: '从此项目的允许列表中移除 "{prefix}"?',
clearConfirm: "清除所有项目允许列表条目?内置条目不受影响。",
projectAllowlist: "项目允许列表 · {count}",
nothingStored: "此项目暂无存储的条目。",
colNum: "#",
colPrefix: "前缀",
builtinTitle: "内置 · {count} · 只读",
standaloneWarning:
"修改操作需要在活跃的 reasonix code 会话内执行 /dashboard — 独立模式的 reasonix dashboard 无法确定要编辑哪个项目的允许列表。",
},
mcp: {
loading: "加载 MCP…",
servers: "MCP 服务器 · {count} 个已桥接",
all: "全部",
live: "在线",
unbridged: "未桥接",
specPlaceholder: "规格 — 例如 fs=npx -y @modelcontextprotocol/...",
saved: "已保存",
savedRestart: "已保存 — 重启 reasonix code 以桥接此服务器",
removed: "已移除 — 重启以断开实时桥接",
removeConfirm: "从配置中移除 MCP 规格?\n\n{spec}",
noServers: "此会话中无 MCP 服务器。",
tools: "个工具",
inConfig: "在配置中 · 未加载",
unbridgedTitle: "未桥接 · 在配置中",
removeBtn: "移除",
spec: "规格",
whyUnbridged: "为什么未桥接?",
whyUnbridgedDesc:
"此规格存在于您的 config.json 中,但未桥接到实时会话。MCP 服务器在 reasonix code 启动时连接;仪表盘本身无法生成子进程。",
whyUnbridgedHint: "激活方法:重启 reasonix code,然后刷新此仪表盘。",
pickHint: "选择左侧的 MCP 服务器以检查工具 / 资源 / 提示。",
toolsTitle: "工具 · {count}",
resourcesTitle: "资源 · {count}",
promptsTitle: "提示 · {count}",
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: "加载记忆…",
files: "记忆 · {count} 个文件",
exists: "已存在",
create: "创建",
noFiles: "暂无记忆文件。",
pickHint: "选择左侧的记忆文件。",
pickDesc: "项目 REASONIX.md 可提交;全局笔记存储在 ~/.reasonix/memory/。",
chars: "{count} 个字符",
saved: "已保存 {scope}",
reloadHint: "在下次 /new 或会话重启时重新加载",
},
hooks: {
loading: "加载钩子…",
resolved: "已解析",
eventMatrix: "事件矩阵",
matrixSub: "{scripts} 个脚本 × {events} 个事件",
noHooks: "未配置钩子。编辑下方的 JSON 以添加。",
colScript: "脚本",
noProject: "无活跃项目 — 在 reasonix code 中打开 /dashboard 以编辑项目钩子。",
saveReload: "保存并重载",
discard: "放弃更改",
savedReloaded: "已保存并重载 {scope}",
recentRuns: "近期运行",
noRuns: "近期会话日志中无钩子运行记录。",
colWhen: "时间",
colPhase: "阶段",
colHook: "钩子",
colOutcome: "结果",
},
skills: {
loading: "加载技能…",
filterPlaceholder: "筛选技能",
project: "项目",
global: "全局",
builtin: "内置",
newSkill: "新技能",
noDescription: "(无描述)",
runs7d: "次运行 · 7 天",
pickHint: "选择左侧的技能,或在上方创建新技能。",
readOnlyBuiltin: "只读 · 内置",
builtinDesc:
"内置技能随 Reasonix 一起发布;模型会自动识别。如需自定义,请创建同名的项目或全局技能。",
saved: "已保存 {scope}/{name}",
deleteConfirm: "删除技能 {scope}/{name}?",
reloadHint: "在下次 /new 或会话重启时重新加载",
},
system: {
loading: "加载健康状态…",
failed: "健康检查失败:{error}",
healthChecks: "健康检查",
version: "版本",
checking: "检查中",
latest: "● 最新",
outOfDate: "● 需要更新",
versionPending: "版本检查中",
upToDate: "已是最新",
latestVer: "最新:{version}",
sessions: "会话",
ok: "● 正常",
memory: "记忆",
semanticIndex: "语义索引",
built: "● 已构建",
none: "— 无",
runIndex: "运行 reasonix index 以构建",
usageLog: "用量日志",
backgroundJobs: "后台任务",
noSession: "— 无会话",
running: "{count} 个运行中",
attachHint: "连接会话以查看任务",
shellSpawn: "Shell + 生成",
paths: "路径",
home: "主目录",
sessionsPath: "会话",
memoryPath: "记忆",
semanticPath: "语义",
usagePath: "用量",
},
plans: {
loading: "加载计划…",
failed: "计划失败:{error}",
noPlans: "暂无归档计划 — 运行调用 submit_plan 和 mark_step_complete 的轮次。",
filterPlaceholder: "筛选计划",
active: "进行中",
done: "已完成",
idle: "未开始",
steps: "步骤",
pickHint: "选择左侧的计划。",
noTitle: "(无标题)",
stepTimeline: "步骤时间线 · {done} / {total}",
step: "步骤 {n}",
},
semantic: {
codeRequired: "语义 — 需要代码模式",
indexBuilt: "索引已构建",
noIndex: "尚无索引",
ready: "就绪",
setupNeeded: "需要设置",
installOllama: "安装 Ollama",
installOllamaDesc: "Reasonix 不会为您运行包管理器。请先安装 Ollama,然后返回:",
macWindows: "macOS / Windows:",
download: "从 ollama.com/download 下载",
linux: "Linux:",
refreshHint: "安装后刷新 — 此面板将提供启动守护进程和拉取 {model} 的选项。",
daemon: "守护进程",
daemonDesc: "ollama 在您的 PATH 中,但 HTTP 守护进程不可达。",
startDaemon: "启动守护进程",
runsOllama: "以分离模式运行 ollama serve",
model: "模型",
modelMissing: "{model} 尚未安装。",
modelSize: "首次拉取约 270 MB。",
pulling: "拉取中…",
pullModel: "拉取 {model}",
indexStatus: "索引状态",
builtStatus: "● 已构建",
incompatibleStatus: "● 不兼容",
chunks: "分块",
files: "文件",
dim: "维度",
size: "大小",
lastBuild: "上次构建",
builtWith: "构建来源",
currentTarget: "当前目标",
incompatibleHint: "磁盘上的这个索引是为不同的 provider 或 model 构建的。运行“完全重建”即可替换。",
runIndexHint: "运行索引以启用 semantic_search。",
reIndex: "重建索引",
build: "构建",
rebuild: "完全重建",
stop: "停止",
provider: "提供方",
providerType: "服务类型",
openaiCompat: "OpenAI-Compatible",
apiUrl: "API URL",
apiKey: "API Key",
customRequestBody: "自定义请求体",
invalidCustomRequestBody: "自定义请求体必须是合法 JSON:{error}",
customRequestBodyMustBeObject: "自定义请求体必须是 JSON 对象。",
saveBeforeIndex: "请先保存语义设置,再启动索引。",
extraBody: "扩展请求体",
keepExistingKey: "留空则保留现有 Key",
remoteProvider: "远程向量服务",
remoteProviderDesc:
"在这里配置 OpenAI-Compatible embeddings 的完整 URL。Reasonix 会严格使用你提供的 URL 发起请求。",
ollama: "Ollama",
binary: "二进制",
found: "已找到",
missing: "缺失",
daemonStatus: "守护进程",
up: "运行中",
down: "已停止",
pulled: "已拉取",
indexConfig: "索引配置",
reset: "重置",
excludeDirs: "排除目录",
excludeFiles: "排除文件",
excludeExts: "排除扩展名",
excludePatterns: "排除模式",
glob: "glob",
respectGitignore: "遵循 .gitignore",
maxFileBytes: "最大文件字节数",
skipLarger: "跳过大于 ~{size} MiB 的文件",
preview: "预览",
searchPlaceholder: "描述要查找的内容 — '哪里处理中止信号'",
searching: "搜索中…",
results: "{count} 个结果 · {ms}ms · {model}",
noMatches: "没有超过分数阈值的匹配。",
previewSummary: "预览 — 将索引 {included} 个文件,跳过 {skipped} 个",
nothingSkipped: "无跳过 — 所有遍历的文件都将被索引。",
firstIncluded: "前 {count} 个包含的文件",
job: "任务",
phaseSetup: "初始化中",
phaseScan: "扫描文件",
phaseEmbed: "嵌入分块",
phaseWrite: "写入索引",
phaseDone: "完成",
phaseError: "错误",
phaseCancelled: "已停止",
setupFailed: "初始化失败",
stopping: "停止中",
scanned: "已扫描 {count}",
changed: "已变更 {count}",
skipped: "已跳过 {count}",
chunksProgress: "{done} / {total}({pct}%)",
result: "结果",
added: "已添加 {count}",
removed: "已移除 {count}",
failed: "失败 {count}",
skippedFiles: "{total} 个文件({details})",
rebuildStarted: "已启动完全重建",
incrementalStarted: "已启动增量索引",
stopRequested: "已请求停止 — 当前分块批次将首先完成",
startingDaemon: "正在启动 ollama 守护进程(15 秒超时)…",
daemonUp: "守护进程已启动",
daemonTimeout: "守护进程未在规定时间内启动 — 请手动检查 ollama serve",
pullingModel: "正在拉取 {model} — 首次安装可能需要几分钟",
savedConfig: "已保存 · {count} 个字段已更新 · 重新运行索引以应用",
runningPreview: "正在对项目根目录执行干运行…",
exclude: "排除",
},
modal: {
shellTitle: "Shell 命令",
shellBgTitle: "后台进程",
shellSubtitle: "模型想要运行一条 Shell 命令",
shellBgSubtitle: "长时间运行 — 批准后继续运行",
runOnce: "运行一次",
alwaysAllow: '始终允许 "{prefix}"',
deny: "拒绝",
choiceTitle: "模型需要您选择",
typeOwn: "输入自定义回答",
typeOwnSummary: "以上选项都不合适 — 写一个自由格式的回复。",
typePlaceholder: "输入自由格式的回答…",
send: "发送",
cancel: "取消",
cancelSummary: "放弃此问题。模型将询问您实际想要什么。",
planTitle: "计划已提交",
planSubtitle: "模型提出了一项计划;请审阅后选择",
approveInstructions: "可选的最后指示 / 对开放问题的回答(Enter 发送空白)",
refinePlaceholder: "需要更改什么?请具体说明。",
approve: "批准",
refine: "优化",
sendRefinement: "发送优化",
editTitle: "编辑待审阅",
editSubtitle: "{path} · {remaining} / {total} 个块剩余",
before: "修改前",
after: "修改后",
workspaceTitle: "模型想要切换工作区",
workspaceSubtitle: "后续所有文件 / Shell / 记忆工具将针对新根目录解析",
switchBtn: "切换 (Enter)",
denyBtn: "拒绝 (Esc)",
stepComplete: "步骤完成{counter}",
continueBtn: "继续",
reviseBtn: "修订…",
stopBtn: "停止",
revisionTitle: "模型提出了计划修订",
sendRevision: "发送修订",
accept: "接受",
reject: "拒绝",
arguments: "参数",
revisePlaceholder: "下一步之前需要更改什么?留空则直接继续。",
pickerFilter: "过滤…",
pickerEmpty: "暂无内容。",
pickerLoadMore: "加载更多",
pickerPick: "打开",
pickerInstall: "安装",
pickerUninstall: "卸载",
pickerRename: "重命名…",
pickerNew: "新建…",
pickerNewPlaceholder: "名称(留空使用默认)",
viewerClose: "关闭",
},
};
+45
View File
@@ -0,0 +1,45 @@
export type BudgetState =
| { kind: "off"; spent: number }
| { kind: "running"; cap: number; spent: number; pct: number }
| { kind: "warn"; cap: number; spent: number; pct: number }
| { kind: "exhausted"; cap: number; spent: number; pct: number };
export function deriveBudgetState(
cap: number | null | undefined,
spent: number | null | undefined,
): BudgetState {
const safeSpent = typeof spent === "number" && spent >= 0 ? spent : 0;
if (typeof cap !== "number" || cap <= 0) {
return { kind: "off", spent: safeSpent };
}
const pct = (safeSpent / cap) * 100;
if (pct >= 100) return { kind: "exhausted", cap, spent: safeSpent, pct };
if (pct >= 80) return { kind: "warn", cap, spent: safeSpent, pct };
return { kind: "running", cap, spent: safeSpent, pct };
}
/** Default quick-cap menu — round dollar amounts users actually pick. */
export const QUICK_CAPS_USD: ReadonlyArray<number> = [1, 5, 10, 25, 50];
/** 1.5× / 2× / 4× the current cap, snapped to a "nice" round number per bucket. */
export function bumpSuggestions(currentCap: number): number[] {
if (currentCap <= 0) return [];
return [niceUp(currentCap * 1.5), niceUp(currentCap * 2), niceUp(currentCap * 4)];
}
function niceUp(n: number): number {
// Subtract a tiny epsilon before ceil so FP noise (0.4 * 1.5 = 0.6000…01)
// doesn't bump a value to the next bucket.
const eps = 1e-9;
if (n < 1) return Math.ceil((n - eps) * 10) / 10;
if (n < 10) return Math.ceil((n - eps) * 2) / 2;
if (n < 100) return Math.ceil(n - eps);
return Math.ceil((n - eps) / 5) * 5;
}
/** Tone class shared between the cockpit tile and the settings gauge. */
export function budgetTone(state: BudgetState): "" | "warn" | "err" {
if (state.kind === "exhausted") return "err";
if (state.kind === "warn") return "warn";
return "";
}
+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)}%`;
+117
View File
@@ -0,0 +1,117 @@
import { useEffect, useState } from "preact/hooks";
import { TOKEN, api } from "./api.js";
type Listener = () => void;
export type DashboardLang = "en" | "zh-CN";
// [dashboardCode, backendCode] — add new languages here.
const LANG_REGISTRY: [DashboardLang, string][] = [
["en", "EN"],
["zh-CN", "zh-CN"],
];
const SUPPORTED = new Set(LANG_REGISTRY.map(([d]) => d));
const TO_BACKEND = new Map(LANG_REGISTRY);
const FROM_BACKEND = new Map(LANG_REGISTRY.map(([d, b]) => [b, d]));
const STORAGE_KEY = "rx.lang";
const listeners: Listener[] = [];
let currentLang: DashboardLang = loadFromStorage() ?? "en";
function loadFromStorage(): DashboardLang | null {
try {
const v = localStorage.getItem(STORAGE_KEY);
if (v !== null && SUPPORTED.has(v as DashboardLang)) return v as DashboardLang;
} catch {
/* private mode */
}
return null;
}
function toBackendLang(lang: DashboardLang): string {
return TO_BACKEND.get(lang) ?? lang;
}
function fromBackendLang(raw: string): DashboardLang {
return (FROM_BACKEND.get(raw) as DashboardLang) ?? "en";
}
/** Adopt server lang on startup; localStorage is render-cache only, never pushed back. */
export async function initLangFromServer(): Promise<void> {
try {
const res = await api<{ lang?: string }>("/settings");
const serverLang = res.lang ? fromBackendLang(res.lang) : null;
if (!serverLang || serverLang === currentLang) return;
currentLang = serverLang;
try {
localStorage.setItem(STORAGE_KEY, serverLang);
} catch {
/* ignore */
}
for (const cb of listeners) cb();
} catch {
/* offline — keep last-known value rendering */
}
}
export function getLang(): DashboardLang {
return currentLang;
}
export function setLang(lang: DashboardLang): void {
if (!SUPPORTED.has(lang)) return;
currentLang = lang;
try {
localStorage.setItem(STORAGE_KEY, lang);
} catch {
/* ignore */
}
for (const cb of listeners) cb();
// keepalive ensures the request completes even during page unload (refresh).
fetch(`/api/settings?token=${TOKEN}`, {
method: "POST",
headers: { "Content-Type": "application/json", "X-Reasonix-Token": TOKEN },
body: JSON.stringify({ lang: toBackendLang(lang) }),
keepalive: true,
}).catch((err) => console.error("[reasonix dashboard] lang persist:", err));
}
export function onLangChange(cb: Listener): () => void {
listeners.push(cb);
return () => {
const i = listeners.indexOf(cb);
if (i >= 0) listeners.splice(i, 1);
};
}
export function useLang(): DashboardLang {
const [lang, setLangState] = useState<DashboardLang>(currentLang);
useEffect(() => onLangChange(() => setLangState(currentLang)), []);
return lang;
}
type Nested = { [k: string]: string | Nested };
function get(translations: Nested | undefined, path: string): string | undefined {
let val: string | Nested | undefined = translations;
for (const part of path.split(".")) {
if (val === undefined || typeof val === "string") return undefined;
val = val[part];
}
return typeof val === "string" ? val : undefined;
}
export function createT(translations: Record<string, Nested>) {
return function t(path: string, params?: Record<string, string | number>): string {
let val = get(translations[currentLang] ?? translations.en, path);
if (val === undefined) val = get(translations.en, path);
if (val === undefined) return path;
if (!params) return val;
let result = val;
for (const [k, v] of Object.entries(params)) {
result = result.replaceAll(`{${k}}`, String(v));
}
return result;
};
}
+48
View File
@@ -0,0 +1,48 @@
export type IntervalUnit = "s" | "m" | "h";
export interface LoopRunStatus {
prompt: string;
intervalMs: number;
iter: number;
/** Wall-clock ms until the next fire — server reports a remaining duration, not an absolute. */
nextFireMs: number;
}
/** Quick-pick intervals in ms — covers the 95% of cases users actually run. */
export const INTERVAL_PRESETS_MS: ReadonlyArray<{ ms: number; label: string }> = [
{ ms: 30_000, label: "30s" },
{ ms: 60_000, label: "1m" },
{ ms: 5 * 60_000, label: "5m" },
{ ms: 15 * 60_000, label: "15m" },
{ ms: 60 * 60_000, label: "1h" },
{ ms: 6 * 60 * 60_000, label: "6h" },
];
const UNIT_TO_MS: Record<IntervalUnit, number> = {
s: 1_000,
m: 60_000,
h: 60 * 60_000,
};
const MIN_INTERVAL_MS = 5_000;
const MAX_INTERVAL_MS = 6 * 60 * 60_000;
/** Convert a "30" + "s" pair to ms, returning null if out of [5s, 6h]. */
export function parseCustomInterval(value: string, unit: IntervalUnit): number | null {
const n = Number.parseFloat(value);
if (!Number.isFinite(n) || n <= 0) return null;
const ms = Math.round(n * UNIT_TO_MS[unit]);
if (ms < MIN_INTERVAL_MS || ms > MAX_INTERVAL_MS) return null;
return ms;
}
/** Human-friendly "5m 12s" / "12s" / "2h 45m" — shows two largest non-zero units. */
export function formatRemaining(ms: number): string {
const safe = Math.max(0, Math.floor(ms / 1000));
const h = Math.floor(safe / 3600);
const m = Math.floor((safe % 3600) / 60);
const s = safe % 60;
if (h > 0) return m > 0 ? `${h}h ${m}m` : `${h}h`;
if (m > 0) return s > 0 ? `${m}m ${s}s` : `${m}m`;
return `${s}s`;
}
+71 -58
View File
@@ -6,16 +6,19 @@ import {
ChoiceModal,
EditReviewModal,
type OnResolve,
PickerModal,
PlanModal,
RevisionModal,
ShellModal,
ViewerModal,
WorkspaceModal,
parseToolArgs,
} 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";
interface StreamingState {
id: string;
@@ -100,6 +103,7 @@ interface SettingsPatch {
}
export function ChatPanel() {
useLang();
const [messages, setMessages] = useState<ChatMsg[]>([]);
const [streaming, setStreaming] = useState<StreamingState | null>(null);
const [activeTool, setActiveTool] = useState<ActiveToolState | null>(null);
@@ -263,7 +267,7 @@ export function ChatPanel() {
es.onerror = () => {
// Auto-reconnect by default; surface a brief banner on persistent
// failure but don't tear down — EventSource retries in the background.
setError("event stream interrupted — reconnecting…");
setError(t("chat.eventStreamError"));
setTimeout(() => setError(null), 3000);
};
return () => es.close();
@@ -298,8 +302,8 @@ export function ChatPanel() {
const newConversation = useCallback(async () => {
if (busy) {
if (!confirm("A turn is in flight. Abort and start a new conversation?")) return;
} else if (messages.length > 0 && !confirm("Clear current conversation and start fresh?")) {
if (!confirm(t("chat.newConfirmBusy"))) return;
} else if (messages.length > 0 && !confirm(t("chat.newConfirm"))) {
return;
}
try {
@@ -307,7 +311,7 @@ export function ChatPanel() {
setMessages([]);
setStreaming(null);
setActiveTool(null);
showToast("new conversation", "info");
showToast(t("chat.newToast"), "info");
setTimeout(async () => {
try {
const r = await api<MessagesResponse>("/messages");
@@ -317,7 +321,7 @@ export function ChatPanel() {
}
}, 200);
} catch (err) {
setError(`/new failed: ${(err as Error).message}`);
setError(t("chat.newFailed", { error: (err as Error).message }));
}
}, [busy, messages.length]);
@@ -327,7 +331,7 @@ export function ChatPanel() {
setMessages([]);
setStreaming(null);
setActiveTool(null);
showToast("scrollback cleared", "info");
showToast(t("chat.clearToast"), "info");
setTimeout(async () => {
try {
const r = await api<MessagesResponse>("/messages");
@@ -337,7 +341,7 @@ export function ChatPanel() {
}
}, 200);
} catch (err) {
setError(`/clear failed: ${(err as Error).message}`);
setError(t("chat.clearFailed", { error: (err as Error).message }));
}
}, []);
@@ -443,7 +447,7 @@ export function ChatPanel() {
);
if (bootError) {
return html`<div class="notice err">chat unavailable: ${bootError}</div>`;
return html`<div class="notice err">${t("common.loadingFailed", { name: "chat", error: bootError })}</div>`;
}
/** Suppresses scroll listener during programmatic auto-snap so it doesn't re-arm shouldAutoScroll. */
@@ -557,20 +561,20 @@ 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" ? "TUI mirror" : "session view"}</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">
${
effort
? html`
<div class="mode-picker" title="reasoning_effort — applies next turn">
<div class="mode-picker" title=${t("chat.effortTitle")}>
${["high", "max"].map(
(e) => html`
<button
key=${e}
class="mode-btn ${effort === e ? "active accent" : ""}"
onClick=${() => setSetting("reasoningEffort", e)}
title=${e === "max" ? "max (default — best quality)" : "high (cheaper / faster)"}
title=${e === "max" ? t("chat.effortMaxTitle") : t("chat.effortHighTitle")}
>${e}</button>
`,
)}
@@ -581,7 +585,7 @@ export function ChatPanel() {
${
preset
? html`
<div class="mode-picker" title="preset — model commitment">
<div class="mode-picker" title=${t("chat.presetTitle")}>
${(() => {
// Anything that isn't one of the three new presets
// (including legacy fast/smart/max from old configs)
@@ -597,10 +601,10 @@ export function ChatPanel() {
onClick=${() => setSetting("preset", p)}
title=${
p === "auto"
? "auto — flash baseline; auto-escalates to pro on hard turns (NEEDS_PRO / failure threshold)"
? t("chat.presetAutoTitle")
: p === "flash"
? "flash — always flash; no auto-escalate. /pro still works for one-shot manual"
: "pro — always pro; ~3× flash cost (5/31 discount). Locks in on hard architecture work."
? t("chat.presetFlashTitle")
: t("chat.presetProTitle")
}
>${p}</button>
`,
@@ -613,7 +617,7 @@ export function ChatPanel() {
${
editMode
? html`
<div class="mode-picker" title="edit gate — Shift+Tab cycles in TUI">
<div class="mode-picker" title=${t("chat.editGateTitle")}>
${["review", "auto", "yolo"].map(
(m) => html`
<button
@@ -622,10 +626,10 @@ export function ChatPanel() {
onClick=${() => setEditMode(m)}
title=${
m === "review"
? "review — both edits and non-allowlisted shell ask first"
? t("chat.editReviewTitle")
: m === "auto"
? "auto — edits auto-apply, shell still asks"
: "yolo — edits AND shell auto-run, allowlist bypassed"
? t("chat.editAutoTitle")
: t("chat.editYoloTitle")
}
>${m}</button>
`,
@@ -647,19 +651,19 @@ export function ChatPanel() {
? html`<div class="chat-banner">
<span class="chat-banner-icon">≈</span>
<span class="chat-banner-text">
<strong>Semantic search isn't enabled for this project.</strong>
<strong>${t("chat.semanticBanner")}</strong>
<span class="muted">
Build the index once and the model can find code by meaning ("where do we handle auth failures?") instead of grep on exact strings.
${t("chat.semanticBannerDesc")}
</span>
</span>
<button
class="primary"
onClick=${() => appBus.dispatchEvent(new CustomEvent("navigate-tab", { detail: { tabId: "semantic" } }))}
>Build it →</button>
>${t("chat.semanticBannerBtn")}</button>
<button
class="chat-banner-close"
onClick=${() => setSemanticBannerDismissed(true)}
title="dismiss (don't show again)"
title=${t("chat.semanticBannerDismiss")}
>×</button>
</div>`
: null
@@ -682,7 +686,11 @@ export function ChatPanel() {
? html`<${CheckpointModal} modal=${modal} onResolve=${resolveModal} />`
: modal.kind === "revision"
? html`<${RevisionModal} modal=${modal} onResolve=${resolveModal} />`
: null
: modal.kind === "picker"
? html`<${PickerModal} modal=${modal} onResolve=${resolveModal} />`
: modal.kind === "viewer"
? html`<${ViewerModal} modal=${modal} onResolve=${resolveModal} />`
: null
: null
}
@@ -692,7 +700,7 @@ export function ChatPanel() {
${
allMessages.length === 0
? html`<div class="chat-empty">
No conversation yet. Send a prompt below to begin.
${t("chat.noConversation")}
</div>`
: allMessages.map(
(m) => html`
@@ -711,7 +719,7 @@ export function ChatPanel() {
popoverKind && popoverItems.length > 0
? html`
<div class="popover" style="position:absolute;bottom:calc(100% + 6px);left:0;width:380px;max-height:280px;overflow-y:auto;z-index:10">
<div class="popover-h">${popoverKind === "slash" ? "slash commands" : "project files"}</div>
<div class="popover-h">${popoverKind === "slash" ? t("chat.slashCommands") : t("chat.projectFiles")}</div>
${popoverItems.map(
(it, i) => html`
<div
@@ -733,7 +741,7 @@ export function ChatPanel() {
: null
}
<textarea
placeholder=${busy ? "wait for the current turn to finish…" : "Type a prompt — Enter sends, Shift+Enter for a newline · / @ for pickers"}
placeholder=${busy ? t("chat.placeholderBusy") : t("chat.placeholder")}
value=${input}
onInput=${onInput}
onKeyDown=${onKeyDown}
@@ -746,10 +754,10 @@ export function ChatPanel() {
class="primary"
onClick=${send}
disabled=${busy || !input.trim()}
>Send</button>
>${t("chat.send")}</button>
<div style="display: flex; gap: 6px;">
<button onClick=${newConversation} title="/new — wipe conversation context (loop log + scrollback)">New</button>
<button onClick=${clearScrollback} title="/clear — wipe just visible scrollback (context kept)">Clear</button>
<button onClick=${newConversation} title=${t("chat.newTitle")}>${t("chat.new")}</button>
<button onClick=${clearScrollback} title=${t("chat.clearTitle")}>${t("chat.clear")}</button>
</div>
</div>
</div>
@@ -782,12 +790,14 @@ interface SideRailProps {
}
function SideRail({ stats, budgetUsd, activePlan }: SideRailProps) {
useLang();
if (!stats && !activePlan) return html`<aside class="chat-rail"></aside>`;
const cachePct = stats ? Math.round(stats.cacheHitRatio * 100) : 0;
const cacheTone = cachePct >= 80 ? "ok" : cachePct >= 50 ? "" : "warn";
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}
@@ -795,12 +805,12 @@ function SideRail({ stats, budgetUsd, activePlan }: SideRailProps) {
stats
? html`
<div class="rail-card">
<div class="rh">Session</div>
<div class="rail-kv"><span class="k">turns</span><span class="v">${stats.turns.toLocaleString()}</span></div>
<div class="rail-kv"><span class="k">prompt tok</span><span class="v">${stats.lastPromptTokens.toLocaleString()}</span></div>
<div class="rail-kv"><span class="k">cost</span><span class="v">${fmtUsd(stats.totalCostUsd)}</span></div>
<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">${fmtCost(stats.totalCostUsd, walletCurrency)}</span></div>
<div class="progress-row" style="margin-top:8px">
<span class="lbl">cache hit</span>
<span class="lbl">${t("chat.railCacheHit")}</span>
<div class=${`progress ${cacheTone}`}><div class="progress-fill" style=${`width:${cachePct}%`}></div></div>
<span class="v">${cachePct}%</span>
</div>
@@ -812,11 +822,11 @@ function SideRail({ stats, budgetUsd, activePlan }: SideRailProps) {
showBudget
? html`
<div class="rail-card">
<div class="rh">Tool budget</div>
<div class="rh">${t("chat.railToolBudget")}</div>
<div class="progress-row">
<span class="lbl">spend</span>
<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>
`
@@ -827,6 +837,7 @@ function SideRail({ stats, budgetUsd, activePlan }: SideRailProps) {
}
function ActivePlanCard({ plan }: { plan: RailPlan }) {
useLang();
const dots = [];
for (let i = 0; i < plan.totalSteps; i++) {
const done = i < plan.completedSteps;
@@ -840,10 +851,10 @@ function ActivePlanCard({ plan }: { plan: RailPlan }) {
}
return html`
<div class="rail-card">
<div class="rh">Active plan</div>
<div class="rh">${t("chat.railActivePlan")}</div>
<div class="steps" style="margin-bottom:8px">${dots}</div>
<div class="rail-kv"><span class="k" style="font-family:var(--font-sans);color:var(--fg-1);font-size:12.5px">${plan.title}</span></div>
<div class="rail-kv"><span class="k">progress</span><span class="v">${plan.completedSteps} / ${plan.totalSteps}</span></div>
<div class="rail-kv"><span class="k">${t("chat.railProgress")}</span><span class="v">${plan.completedSteps} / ${plan.totalSteps}</span></div>
</div>
`;
}
@@ -894,6 +905,7 @@ function InFlightRow({
onAbort,
tick: _tick,
}: InFlightRowProps) {
useLang();
const elapsedMs = startedAt ? Date.now() - startedAt : 0;
const elapsed = (elapsedMs / 1000).toFixed(1);
const reasoningLen = streaming?.reasoning?.length ?? 0;
@@ -901,12 +913,12 @@ function InFlightRow({
/** Tool dispatch wins over text/reasoning — model is blocked on the tool, show that. */
const toolSummary = summarizeActiveTool(activeTool);
const phase = toolSummary
? "running"
? t("chat.inflightRunning")
: reasoningLen > 0 && textLen === 0
? "thinking"
? t("chat.inflightThinking")
: textLen > 0
? "streaming"
: "waiting";
? t("chat.inflightStreaming")
: t("chat.inflightWaiting");
return html`
<div class="chat-inflight">
<span class="spinner"></span>
@@ -926,9 +938,9 @@ function InFlightRow({
? html`
<span class="chat-inflight-sep">·</span>
<span class="muted">
${reasoningLen > 0 ? html`reasoning ${reasoningLen.toLocaleString()} ch` : null}
${reasoningLen > 0 ? html`${t("chat.inflightReasoning", { count: reasoningLen.toLocaleString() })}` : null}
${reasoningLen > 0 && textLen > 0 ? html`<span> · </span>` : null}
${textLen > 0 ? html`out ${textLen.toLocaleString()} ch` : null}
${textLen > 0 ? html`${t("chat.inflightOut", { count: textLen.toLocaleString() })}` : null}
</span>
`
: null
@@ -941,7 +953,7 @@ function InFlightRow({
`
: null
}
<button class="chat-inflight-abort" onClick=${onAbort}>Abort (Esc)</button>
<button class="chat-inflight-abort" onClick=${onAbort}>${t("chat.abortBtn")}</button>
</div>
`;
}
@@ -952,10 +964,11 @@ interface ChatStatusBarProps {
}
function ChatStatusBar({ stats, model }: ChatStatusBarProps) {
useLang();
if (!stats) {
return html`
<div class="chat-statusbar">
<span class="muted">· · · waiting for live stats</span>
<span class="muted">${t("chat.waitingStats")}</span>
</div>
`;
}
@@ -965,38 +978,38 @@ function ChatStatusBar({ stats, model }: ChatStatusBarProps) {
return html`
<div class="chat-statusbar">
<span class="status-item">
<span class="status-label">model</span>
<span class="status-label">${t("chat.statusModel")}</span>
<code>${model ?? "—"}</code>
</span>
<span class="status-item">
<span class="status-label">ctx</span>
<span class="status-label">${t("chat.statusCtx")}</span>
<span class="status-bar-mini">
<span class="status-bar-mini-fill" style=${`width: ${Math.min(100, ctxPct).toFixed(1)}%;`}></span>
</span>
<span class="muted">${stats.lastPromptTokens.toLocaleString()} / ${(stats.contextCapTokens / 1000).toFixed(0)}K</span>
</span>
<span class="status-item">
<span class="status-label">cache</span>
<span class="status-label">${t("chat.statusCache")}</span>
<span class=${stats.cacheHitRatio >= 0.9 ? "status-ok" : stats.cacheHitRatio >= 0.6 ? "status-warn" : "status-err"}>
${(stats.cacheHitRatio * 100).toFixed(1)}%
</span>
</span>
<span class="status-item">
<span class="status-label">turn</span>
<code>${fmtUsd(stats.lastTurnCostUsd)}</code>
<span class="status-label">${t("chat.statusTurn")}</span>
<code>${fmtCost(stats.lastTurnCostUsd, balance?.currency)}</code>
</span>
<span class="status-item">
<span class="status-label">session</span>
<code>${fmtUsd(stats.totalCostUsd)}</code>
<span class="status-label">${t("chat.statusSession")}</span>
<code>${fmtCost(stats.totalCostUsd, balance?.currency)}</code>
<span class="muted" style="font-size: 10px;">
(${stats.turns} turn${stats.turns === 1 ? "" : "s"})
${t("chat.statusTurns", { count: stats.turns, s: stats.turns === 1 ? "" : "s" })}
</span>
</span>
${
balance
? html`
<span class="status-item">
<span class="status-label">balance</span>
<span class="status-label">${t("chat.statusBalance")}</span>
<code>${balance.total_balance} ${balance.currency}</code>
</span>
`
+33 -20
View File
@@ -2,6 +2,7 @@ import { useCallback, useEffect, useState } from "preact/hooks";
import { api } from "../lib/api.js";
import { fmtRelativeTime } from "../lib/format.js";
import { html } from "../lib/html.js";
import { t, useLang } from "../i18n/index.js";
interface HookHandler {
command?: string;
@@ -61,11 +62,13 @@ interface HooksData {
}
export function HooksPanel() {
useLang();
const [data, setData] = useState<HooksData | null>(null);
const [error, setError] = useState<string | null>(null);
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 {
@@ -99,7 +102,7 @@ export function HooksPanel() {
try {
await api("/hooks/save", { method: "POST", body: { scope, hooks: parsed } });
await api("/hooks/reload", { method: "POST", body: {} });
setInfo(`saved + reloaded ${scope}`);
setInfo(t("hooks.savedReloaded", { scope }));
setTimeout(() => setInfo(null), 3000);
await load();
} catch (err) {
@@ -112,7 +115,7 @@ export function HooksPanel() {
);
if (!data && !error)
return html`<div class="card" style="color:var(--fg-3)">loading hooks…</div>`;
return html`<div class="card" style="color:var(--fg-3)">${t("hooks.loading")}</div>`;
if (error && !data) return html`<div class="card accent-err">${error}</div>`;
if (!data) return null;
@@ -127,31 +130,42 @@ 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">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("Event matrix", `${matrixRows.length} script${matrixRows.length === 1 ? "" : "s"} × ${events.length} event${events.length === 1 ? "" : "s"}`)}
${
matrixRows.length === 0
${sectionH3(t("hooks.eventMatrix"), t("hooks.matrixSub", { scripts: matrixRows.length, s: matrixRows.length === 1 ? "" : "s", events: events.length }))}${
visibleRows.length === 0
? html`<div class="card" style="color:var(--fg-3)">
No hooks configured. Edit the JSON below to add some.
${t("hooks.noHooks")}
</div>`
: html`
<div class="card" style="padding:10px 14px;overflow-x:auto">
<div class="matrix" style=${`min-width:fit-content`}>
<div class="row h" style=${`grid-template-columns:${gridCols}`}>
<div>script</div>
<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}>
@@ -182,8 +196,7 @@ export function HooksPanel() {
${
scope === "project" && !meta.path
? html`<div class="card" style="color:var(--fg-3)">
No active project — open <code class="mono">/dashboard</code> from
<code class="mono">reasonix code</code> to edit project hooks.
${t("hooks.noProject")}
</div>`
: html`
<div class="card">
@@ -196,9 +209,9 @@ export function HooksPanel() {
></textarea>
<div style="display:flex;gap:6px;margin-top:8px">
<button class="btn primary" disabled=${busy} onClick=${() => saveScope(scope)}>
Save + Reload
${t("hooks.saveReload")}
</button>
<button class="btn ghost" disabled=${busy} onClick=${load}>Discard changes</button>
<button class="btn ghost" disabled=${busy} onClick=${load}>${t("hooks.discard")}</button>
</div>
</div>
`
@@ -206,21 +219,21 @@ export function HooksPanel() {
`;
})}
${sectionH3("Recent runs", `${data.recentRuns?.length ?? 0}`)}
${sectionH3(t("hooks.recentRuns"), `${data.recentRuns?.length ?? 0}`)}
${
!data.recentRuns || data.recentRuns.length === 0
? html`<div class="card" style="color:var(--fg-3)">
No hook runs in the recent session log.
${t("hooks.noRuns")}
</div>`
: html`
<div class="card" style="padding:0;overflow-x:auto">
<table class="tbl" style="width:100%;font-family:var(--font-mono);font-size:11.5px">
<thead>
<tr>
<th style="text-align:left;padding:8px 12px">when</th>
<th style="text-align:left;padding:8px 12px">phase</th>
<th style="text-align:left;padding:8px 12px">hook</th>
<th style="text-align:left;padding:8px 12px">outcome</th>
<th style="text-align:left;padding:8px 12px">${t("hooks.colWhen")}</th>
<th style="text-align:left;padding:8px 12px">${t("hooks.colPhase")}</th>
<th style="text-align:left;padding:8px 12px">${t("hooks.colHook")}</th>
<th style="text-align:left;padding:8px 12px">${t("hooks.colOutcome")}</th>
</tr>
</thead>
<tbody>
+432 -54
View File
@@ -1,4 +1,5 @@
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";
@@ -19,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;
@@ -29,9 +84,10 @@ 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();
const [data, setData] = useState<McpData | null>(null);
const [specs, setSpecs] = useState<string[] | null>(null);
const [error, setError] = useState<string | null>(null);
@@ -41,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 {
@@ -62,9 +182,7 @@ export function McpPanel() {
method: "POST",
body: { spec: newSpec.trim() },
});
setInfo(
r.requiresRestart ? "saved — restart `reasonix code` to bridge this server" : "saved",
);
setInfo(r.requiresRestart ? t("mcp.savedRestart") : t("mcp.saved"));
setTimeout(() => setInfo(null), 4000);
setNewSpec("");
await load();
@@ -77,11 +195,11 @@ export function McpPanel() {
const removeSpec = useCallback(
async (spec: string) => {
if (!confirm(`Remove MCP spec from config?\n\n${spec}`)) return;
if (!confirm(t("mcp.removeConfirm", { spec }))) return;
setBusy(true);
try {
await api("/mcp/specs", { method: "DELETE", body: { spec } });
setInfo("removed — restart to drop the live bridge");
setInfo(t("mcp.removed"));
setTimeout(() => setInfo(null), 4000);
await load();
} catch (err) {
@@ -93,50 +211,105 @@ export function McpPanel() {
[load],
);
if (!data && !error) return html`<div class="card" style="color:var(--fg-3)">loading MCP…</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">
<div class="sessions-list">
<div class="ssl-h" style="font-family:var(--font-mono);font-size:11px;color:var(--fg-3);text-transform:uppercase;letter-spacing:.1em">
MCP servers · ${liveCount} bridged
${t("mcp.servers", { count: liveCount })}
</div>
<div style="padding:8px 12px 4px">
<div class="chips">
<span class=${`chip-f ${filter === "all" ? "active" : ""}`} onClick=${() => setFilter("all")}>all <span class="ct">${liveCount + unbridgedCount}</span></span>
<span class=${`chip-f ${filter === "live" ? "active" : ""}`} onClick=${() => setFilter("live")}>live <span class="ct">${liveCount}</span></span>
<span class=${`chip-f ${filter === "unbridged" ? "active" : ""}`} onClick=${() => setFilter("unbridged")}>unbridged <span class="ct">${unbridgedCount}</span></span>
<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='spec — e.g. fs=npx -y @modelcontextprotocol/...'
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">
No MCP servers in this session.
${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(
@@ -148,9 +321,9 @@ export function McpPanel() {
setOpenUnbridged(null);
}}
>
<span class="name">${s.label} <span class="pill ok">live</span></span>
<span class="name">${s.label} <span class="pill ok">${t("mcp.live")}</span></span>
<span class="preview">${specCommand(s.spec)}</span>
<span class="meta"><span><span class="v">${fmtNum(s.toolCount)}</span> tools</span></span>
<span class="meta"><span><span class="v">${fmtNum(s.toolCount)}</span> ${t("mcp.tools")}</span></span>
</div>
`,
)
@@ -167,9 +340,9 @@ export function McpPanel() {
setOpen(null);
}}
>
<span class="name">${specLabel(spec)} <span class="pill">unbridged</span></span>
<span class="name">${specLabel(spec)} <span class="pill">${t("mcp.unbridged")}</span></span>
<span class="preview">${specCommand(spec)}</span>
<span class="meta"><span class="dim">in config · not loaded</span></span>
<span class="meta"><span class="dim">${t("mcp.inConfig")}</span></span>
</div>
`,
)
@@ -180,48 +353,58 @@ 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">unbridged · in config</span></span>
<span class="ws"><span class="pill">${t("mcp.unbridgedTitle")}</span></span>
<span class="actions">
<button class="btn" disabled=${busy} onClick=${() => removeSpec(openUnbridged)}
style="border-color:var(--c-err);color:var(--c-err)">Remove</button>
<button class="btn ghost" onClick=${() => setOpenUnbridged(null)}>← back</button>
style="border-color:var(--c-err);color:var(--c-err)">${t("mcp.removeBtn")}</button>
<button class="btn ghost" onClick=${() => setOpenUnbridged(null)}>${t("common.back")}</button>
</span>
</div>
<div class="card" style="margin-bottom:12px">
<div class="card-h"><span class="title">spec</span></div>
<div class="card-h"><span class="title">${t("mcp.spec")}</span></div>
<code class="mono" style="font-size:11.5px;color:var(--fg-2);word-break:break-all">${openUnbridged}</code>
</div>
<div class="card accent-warn">
<div class="card-h"><span class="title" style="color:var(--c-warn)">Why unbridged?</span></div>
<div class="card-h"><span class="title" style="color:var(--c-warn)">${t("mcp.whyUnbridged")}</span></div>
<div class="card-b" style="font-size:13px;line-height:1.6">
This spec lives in your <code class="mono">config.json</code> but isn't bridged into the live session.
MCP servers attach when <code class="mono">reasonix code</code> starts; the dashboard alone can't
spawn the child process.
${t("mcp.whyUnbridgedDesc")}
<div style="margin-top:10px;color:var(--fg-3);font-size:12px">
To activate: restart <code class="mono">reasonix code</code>, then refresh this dashboard.
${t("mcp.whyUnbridgedHint")}
</div>
</div>
</div>
`
: open == null
? html`<div style="color:var(--fg-3);font-size:13px;text-align:center;padding:60px 20px">
Pick an MCP server on the left to inspect tools / resources / prompts.
: 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>
<span class="actions">
<button class="btn ghost" onClick=${() => setOpen(null)}>← back</button>
<button class="btn ghost" onClick=${() => setOpen(null)}>${t("common.back")}</button>
</span>
</div>
<div class="card" style="margin-bottom:12px">
<div class="card-h"><span class="title">spec</span></div>
<div class="card-h"><span class="title">${t("mcp.spec")}</span></div>
<code class="mono" style="font-size:11.5px;color:var(--fg-2)">${open.spec}</code>
</div>
@@ -234,15 +417,15 @@ export function McpPanel() {
}
<h3 style="margin:18px 0 6px;font-family:var(--font-mono);font-size:11px;color:var(--fg-3);text-transform:uppercase;letter-spacing:.1em">
Tools · ${open.tools.length}
${t("mcp.toolsTitle", { count: open.tools.length })}
</h3>
<div class="card" style="padding:0;overflow:hidden">
<table class="tbl">
<thead><tr><th>name</th><th>description</th></tr></thead>
<thead><tr><th>${t("mcp.colName")}</th><th>${t("mcp.colDesc")}</th></tr></thead>
<tbody>
${open.tools.map(
(t) =>
html`<tr><td><code class="mono">${t.name}</code></td><td class="dim">${t.description ?? ""}</td></tr>`,
(tool) =>
html`<tr><td><code class="mono">${tool.name}</code></td><td class="dim">${tool.description ?? ""}</td></tr>`,
)}
</tbody>
</table>
@@ -252,11 +435,11 @@ export function McpPanel() {
open.resources.length > 0
? html`
<h3 style="margin:18px 0 6px;font-family:var(--font-mono);font-size:11px;color:var(--fg-3);text-transform:uppercase;letter-spacing:.1em">
Resources · ${open.resources.length}
${t("mcp.resourcesTitle", { count: open.resources.length })}
</h3>
<div class="card" style="padding:0;overflow:hidden">
<table class="tbl">
<thead><tr><th>name</th><th>uri</th></tr></thead>
<thead><tr><th>${t("mcp.colName")}</th><th>${t("mcp.colUri")}</th></tr></thead>
<tbody>
${open.resources.map(
(r) =>
@@ -273,11 +456,11 @@ export function McpPanel() {
open.prompts.length > 0
? html`
<h3 style="margin:18px 0 6px;font-family:var(--font-mono);font-size:11px;color:var(--fg-3);text-transform:uppercase;letter-spacing:.1em">
Prompts · ${open.prompts.length}
${t("mcp.promptsTitle", { count: open.prompts.length })}
</h3>
<div class="card" style="padding:0;overflow:hidden">
<table class="tbl">
<thead><tr><th>name</th><th>description</th></tr></thead>
<thead><tr><th>${t("mcp.colName")}</th><th>${t("mcp.colDesc")}</th></tr></thead>
<tbody>
${open.prompts.map(
(p) =>
@@ -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
}
`;
}
+19 -17
View File
@@ -2,6 +2,7 @@ import { useCallback, useEffect, useState } from "preact/hooks";
import { api } from "../lib/api.js";
import { fmtBytes, fmtRelativeTime } from "../lib/format.js";
import { html } from "../lib/html.js";
import { t, useLang } from "../i18n/index.js";
interface MemoryFile {
name: string;
@@ -18,6 +19,7 @@ interface MemoryTree {
type Scope = "project" | "global" | "project-mem";
export function MemoryPanel() {
useLang();
const [tree, setTree] = useState<MemoryTree | null>(null);
const [error, setError] = useState<string | null>(null);
const [open, setOpen] = useState<{ scope: Scope; name?: string } | null>(null);
@@ -63,7 +65,7 @@ export function MemoryPanel() {
? "/memory/project"
: `/memory/${open.scope}/${encodeURIComponent(open.name ?? "")}`;
await api(path, { method: "POST", body: { body } });
setInfo(`saved ${open.scope}${open.name ? `/${open.name}` : ""}`);
setInfo(t("memory.saved", { scope: open.scope + (open.name ? `/${open.name}` : "") }));
setTimeout(() => setInfo(null), 3000);
await load();
} catch (err) {
@@ -74,7 +76,7 @@ export function MemoryPanel() {
}, [open, body, load]);
if (!tree && !error)
return html`<div class="card" style="color:var(--fg-3)">loading memory…</div>`;
return html`<div class="card" style="color:var(--fg-3)">${t("memory.loading")}</div>`;
if (error && !tree) return html`<div class="card accent-err">${error}</div>`;
if (!tree) return null;
@@ -95,15 +97,16 @@ export function MemoryPanel() {
`;
};
const totalFiles =
(tree.project.path ? 1 : 0) +
tree.global.files.length +
tree.projectMem.files.length;
return html`
<div class="sessions-grid">
<div class="sessions-list">
<div class="ssl-h" style="font-family:var(--font-mono);font-size:11px;color:var(--fg-3);text-transform:uppercase;letter-spacing:.1em">
memory · ${
(tree.project.path ? 1 : 0) +
tree.global.files.length +
tree.projectMem.files.length
} files
${t("memory.files", { count: totalFiles })}
</div>
<div class="ssl-rows">
${
@@ -117,8 +120,8 @@ export function MemoryPanel() {
REASONIX.md
${
tree.project.exists
? html`<span class="pill ok">exists</span>`
: html`<span class="pill">create</span>`
? html`<span class="pill ok">${t("memory.exists")}</span>`
: html`<span class="pill">${t("memory.create")}</span>`
}
</span>
<span class="preview">${tree.project.path}</span>
@@ -134,7 +137,7 @@ export function MemoryPanel() {
tree.projectMem.files.length === 0 &&
!tree.project.path)
? html`<div style="color:var(--fg-3);padding:14px;font-size:12px">
No memory files yet.
${t("memory.noFiles")}
</div>`
: null
}
@@ -145,10 +148,9 @@ export function MemoryPanel() {
${
open == null
? html`<div style="color:var(--fg-3);font-size:13px;text-align:center;padding:60px 20px">
Pick a memory file on the left.
${t("memory.pickHint")}
<div style="margin-top:12px;font-size:11.5px">
Project REASONIX.md is committable; global notes live in
<code class="mono">~/.reasonix/memory/</code>.
${t("memory.pickDesc")}
</div>
</div>`
: html`
@@ -156,10 +158,10 @@ export function MemoryPanel() {
<span class="name">
${open.scope}${open.name ? `/${open.name}` : ""}
</span>
<span class="ws">${body.length.toLocaleString()} chars</span>
<span class="ws">${t("memory.chars", { count: body.length.toLocaleString() })}</span>
<span class="actions">
<button class="btn primary" disabled=${busy} onClick=${save}>Save</button>
<button class="btn ghost" onClick=${() => setOpen(null)}>← back</button>
<button class="btn primary" disabled=${busy} onClick=${save}>${t("common.save")}</button>
<button class="btn ghost" onClick=${() => setOpen(null)}>${t("common.back")}</button>
</span>
</div>
${info ? html`<div style="margin-bottom:8px"><span class="pill ok">${info}</span></div>` : null}
@@ -171,7 +173,7 @@ export function MemoryPanel() {
disabled=${busy}
></textarea>
<div style="margin-top:8px;color:var(--fg-3);font-size:11.5px">
re-applied on next <code class="mono">/new</code> or session restart
${t("memory.reloadHint")}
</div>
`
}
+68 -42
View File
@@ -1,6 +1,8 @@
import { fmtCompactNum, fmtNum, fmtRelativeTime, fmtUsd } from "../lib/format.js";
import { budgetTone, deriveBudgetState } from "../lib/budget.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";
interface CockpitKpi {
total: number;
@@ -64,6 +66,9 @@ interface OverviewData {
toolCount?: number;
cwd?: string;
cockpit?: CockpitData;
budgetUsd?: number | null;
/** Cumulative session spend in USD — set when a session is attached. */
sessionSpendUsd?: number | null;
}
function kpi(label: string, value: unknown, delta?: unknown, deltaTone?: "up" | "down" | "flat") {
@@ -78,47 +83,66 @@ function kpi(label: string, value: unknown, delta?: unknown, deltaTone?: "up" |
}
function deltaPctText(deltaPct: number | null): { text: string; tone: "up" | "down" | "flat" } {
if (deltaPct === null) return { text: "no prior data", tone: "flat" };
if (Math.abs(deltaPct) < 1) return { text: "— stable", tone: "flat" };
if (deltaPct === null) return { text: t("overview.noPriorData"), tone: "flat" };
if (Math.abs(deltaPct) < 1) return { text: t("overview.stable"), tone: "flat" };
const arrow = deltaPct > 0 ? "▲" : "▼";
return {
text: `${arrow} ${Math.abs(deltaPct).toFixed(0)}% vs prior`,
text: t("overview.vsPrior", { arrow, pct: Math.abs(deltaPct).toFixed(0) }),
tone: deltaPct > 0 ? "up" : "down",
};
}
function deltaPpText(deltaPp: number | null): { text: string; tone: "up" | "down" | "flat" } {
if (deltaPp === null) return { text: "no prior data", tone: "flat" };
if (Math.abs(deltaPp) < 0.5) return { text: "— stable", tone: "flat" };
if (deltaPp === null) return { text: t("overview.noPriorData"), tone: "flat" };
if (Math.abs(deltaPp) < 0.5) return { text: t("overview.stable"), tone: "flat" };
const arrow = deltaPp > 0 ? "▲" : "▼";
return { text: `${arrow} ${Math.abs(deltaPp).toFixed(1)}pp`, tone: deltaPp > 0 ? "up" : "down" };
}
function deltaCountText(delta: number | null): { text: string; tone: "up" | "down" | "flat" } {
if (delta === null || delta === 0) return { text: "— stable", tone: "flat" };
if (delta === null || delta === 0) return { text: t("overview.stable"), tone: "flat" };
const arrow = delta > 0 ? "▲" : "▼";
return { text: `${arrow} ${Math.abs(delta)}`, tone: delta > 0 ? "up" : "down" };
}
function balanceKpi(c: CockpitData) {
if (!c.balance) return kpi("balance", "—", "open in TUI", "flat");
if (!c.balance) return kpi(t("overview.balance"), "—", "open in TUI", "flat");
const symbol = c.balance.currency === "CNY" ? "¥" : c.balance.currency === "USD" ? "$" : "";
return kpi("balance", `${symbol}${c.balance.total}`, c.balance.currency, "flat");
return kpi(t("overview.balance"), `${symbol}${c.balance.total}`, c.balance.currency, "flat");
}
function budgetKpi(o: OverviewData) {
const state = deriveBudgetState(o.budgetUsd, o.cockpit?.currentSession?.totalCostUsd ?? null);
if (state.kind === "off") return null;
const tone = budgetTone(state);
const valueColor =
tone === "err"
? "color:var(--c-err)"
: tone === "warn"
? "color:var(--c-warn)"
: "";
return html`
<div class="kpi cock-w-1">
<div class="label">${t("overview.budget")}</div>
<div class="value" style=${valueColor}>${fmtUsd(state.spent)} / ${fmtUsd(state.cap)}</div>
<div class=${`progress ${tone}`} style="margin-top:4px"><div class="progress-fill" style=${`width:${Math.min(100, state.pct)}%`}></div></div>
</div>
`;
}
function tokens7dKpi(c: CockpitData) {
if (!c.tokens7d) return kpi("tokens · 7d", "—", "no usage yet", "flat");
if (!c.tokens7d) return kpi(t("overview.tokens7d"), "—", t("overview.noUsageYet"), "flat");
const d = deltaPctText(c.tokens7d.deltaPct);
return kpi("tokens · 7d", fmtCompactNum(c.tokens7d.total), d.text, d.tone);
return kpi(t("overview.tokens7d"), fmtCompactNum(c.tokens7d.total), d.text, d.tone);
}
function cacheHitKpi(c: CockpitData) {
if (!c.cacheHit7d) return kpi("cache hit", "—", "no usage yet", "flat");
if (!c.cacheHit7d) return kpi(t("overview.cacheHit"), "—", t("overview.noUsageYet"), "flat");
const pct = (c.cacheHit7d.ratio * 100).toFixed(0);
const d = deltaPpText(c.cacheHit7d.deltaPp);
return html`
<div class="kpi cock-w-1">
<div class="label">cache hit</div>
<div class="label">${t("overview.cacheHit")}</div>
<div class="value">${pct}<span class="unit">%</span></div>
<div class=${`delta ${d.tone}`}>${d.text}</div>
</div>
@@ -126,33 +150,34 @@ function cacheHitKpi(c: CockpitData) {
}
function toolCallsKpi(c: CockpitData) {
if (!c.toolCalls24h) return kpi("tool calls · 24h", "—", "no events", "flat");
if (!c.toolCalls24h) return kpi(t("overview.toolCalls24h"), "—", t("overview.noToolCalls"), "flat");
const d = deltaCountText(c.toolCalls24h.delta);
return kpi("tool calls · 24h", fmtNum(c.toolCalls24h.total), d.text, d.tone);
return kpi(t("overview.toolCalls24h"), fmtNum(c.toolCalls24h.total), d.text, d.tone);
}
function currentSessionBlock(c: CockpitData) {
if (!c.currentSession) {
return html`
<div class="cock-list cock-w-2">
<div class="ch"><span class="ttl">current session</span></div>
<div class="ch"><span class="ttl">${t("overview.currentSession")}</span></div>
<div style="color:var(--fg-3);font-size:12.5px;padding:8px 0">
No live session — <code class="mono">/dashboard</code> from inside <code class="mono">reasonix code</code> to attach.
${t("overview.noSession")}
</div>
</div>
`;
}
const s = c.currentSession;
const currency = c.balance?.currency;
return html`
<div class="cock-list cock-w-2">
<div class="ch"><span class="ttl">current session</span></div>
<div class="ch"><span class="ttl">${t("overview.currentSession")}</span></div>
<div class="card accent-brand" style="margin:0 0 8px;background:transparent;border:none;padding:0">
<div class="card-h"><span class="glyph">◆</span><span class="title">${s.id}</span><span class="meta">${s.turns} turn${s.turns === 1 ? "" : "s"}</span></div>
</div>
<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)">prompt tok</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)">completion tok</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)">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.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">${fmtCost(s.totalCostUsd, currency)}</div></div>
</div>
</div>
`;
@@ -162,8 +187,8 @@ function costTrendSpark(c: CockpitData) {
if (!c.costTrend14d || c.costTrend14d.length === 0) {
return html`
<div class="chart cock-w-2">
<div class="chart-h"><span class="title">cost · 14 day</span></div>
<div class="chart-v" style="color:var(--fg-4)">—<span class="unit">no usage yet</span></div>
<div class="chart-h"><span class="title">${t("overview.costTrend")}</span></div>
<div class="chart-v" style="color:var(--fg-4)">—<span class="unit">${t("overview.noUsageYet")}</span></div>
</div>
`;
}
@@ -183,8 +208,8 @@ function costTrendSpark(c: CockpitData) {
const avg = total / days.length;
return html`
<div class="chart cock-w-2">
<div class="chart-h"><span class="title">cost · 14 day</span></div>
<div class="chart-v">${fmtUsd(avg)}<span class="unit">/day avg</span></div>
<div class="chart-h"><span class="title">${t("overview.costTrend")}</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} />
@@ -198,10 +223,10 @@ function costTrendSpark(c: CockpitData) {
function recentPlansRail(c: CockpitData) {
return html`
<div class="cock-list cock-w-2">
<div class="ch"><span class="ttl">recent plans</span></div>
<div class="ch"><span class="ttl">${t("overview.recentPlans")}</span></div>
${
!c.recentPlans || c.recentPlans.length === 0
? html`<div style="color:var(--fg-3);font-size:12.5px;padding:8px 0">No plans yet — submit one with <code class="mono">submit_plan</code>.</div>`
? html`<div style="color:var(--fg-3);font-size:12.5px;padding:8px 0">${t("overview.noPlans")}</div>`
: c.recentPlans.map(
(p) => html`
<div class=${`rail-step ${p.status === "done" ? "done" : "active"}`}>
@@ -219,10 +244,10 @@ function recentPlansRail(c: CockpitData) {
function toolActivityFeed(c: CockpitData) {
return html`
<div class="cock-list cock-w-2">
<div class="ch"><span class="ttl">tool activity</span></div>
<div class="ch"><span class="ttl">${t("overview.toolActivity")}</span></div>
${
!c.toolActivity || c.toolActivity.length === 0
? html`<div style="color:var(--fg-3);font-size:12.5px;padding:8px 0">No tool calls yet.</div>`
? html`<div style="color:var(--fg-3);font-size:12.5px;padding:8px 0">${t("overview.noToolCalls")}</div>`
: c.toolActivity.map(
(r) => html`
<div class=${`feed-row ${r.level}`}>
@@ -238,10 +263,11 @@ function toolActivityFeed(c: CockpitData) {
}
export function OverviewPanel() {
useLang();
const { data, error, loading } = usePoll<OverviewData>("/overview", 2500);
if (loading && !data)
return html`<div class="card" style="color:var(--fg-3)">loading overview…</div>`;
if (error) return html`<div class="card accent-err">overview failed: ${error.message}</div>`;
return html`<div class="card" style="color:var(--fg-3)">${t("overview.loading")}</div>`;
if (error) return html`<div class="card accent-err">${t("overview.failed", { error: error.message })}</div>`;
if (!data) return null;
const o = data;
const c: CockpitData = o.cockpit ?? {
@@ -256,7 +282,7 @@ export function OverviewPanel() {
};
const upToDate = o.latestVersion ? o.latestVersion === o.version : null;
const versionDelta =
upToDate === null ? "checking" : upToDate ? "latest" : `latest: ${o.latestVersion}`;
upToDate === null ? t("overview.checking") : upToDate ? t("overview.latest") : `latest: ${o.latestVersion}`;
const versionTone: "up" | "down" | "flat" = upToDate === false ? "down" : "flat";
return html`
@@ -265,24 +291,24 @@ export function OverviewPanel() {
o.mode === "standalone"
? html`<div class="card accent-warn">
<div class="card-h">
<span class="title" style="color:var(--c-warn)">Standalone mode</span>
<span class="title" style="color:var(--c-warn)">${t("overview.standaloneTitle")}</span>
</div>
<div class="card-b">
Read-only disk view. Start <code class="mono">/dashboard</code> from inside
<code class="mono">reasonix code</code> for live session state, MCP, and tools.
${t("overview.standaloneDesc")}
</div>
</div>`
: null
}
<h3 style="margin:0;font-family:var(--font-mono);font-size:11px;color:var(--fg-3);text-transform:uppercase;letter-spacing:.1em">
Cockpit
${t("overview.cockpit")}
</h3>
<div class="cockpit">
${balanceKpi(c)}
${tokens7dKpi(c)}
${cacheHitKpi(c)}
${toolCallsKpi(c)}
${budgetKpi(o)}
${currentSessionBlock(c)}
${costTrendSpark(c)}
@@ -290,17 +316,17 @@ export function OverviewPanel() {
${recentPlansRail(c)}
${toolActivityFeed(c)}
${kpi("tools loaded", fmtNum(o.toolCount), o.toolCount ? "active" : "—", "flat")}
${kpi("mcp servers", fmtNum(o.mcpServerCount), o.mcpServerCount ? "all up" : "—", o.mcpServerCount ? "up" : "flat")}
${kpi("edit mode", o.editMode ?? "—", o.editMode === "yolo" ? "all prompts bypassed" : null, o.editMode === "yolo" ? "down" : "flat")}
${kpi("Reasonix", o.version ?? "—", versionDelta, versionTone)}
${kpi(t("overview.toolsLoaded"), fmtNum(o.toolCount), o.toolCount ? t("overview.active") : "—", "flat")}
${kpi(t("overview.mcpServers"), fmtNum(o.mcpServerCount), o.mcpServerCount ? t("overview.allUp") : "—", o.mcpServerCount ? "up" : "flat")}
${kpi(t("overview.editMode"), o.editMode ?? "—", o.editMode === "yolo" ? t("overview.yoloWarning") : null, o.editMode === "yolo" ? "down" : "flat")}
${kpi(t("overview.version"), o.version ?? "—", versionDelta, versionTone)}
</div>
<h3 style="margin:0;font-family:var(--font-mono);font-size:11px;color:var(--fg-3);text-transform:uppercase;letter-spacing:.1em">
Working directory
${t("overview.workingDir")}
</h3>
<div class="card">
<div class="card-h"><span class="title">project root</span></div>
<div class="card-h"><span class="title">${t("overview.projectRoot")}</span></div>
<code class="mono" style="color:var(--fg-2);font-size:12px">${o.cwd ?? "—"}</code>
</div>
</div>
+25 -26
View File
@@ -2,6 +2,7 @@ import { useCallback, useState } from "preact/hooks";
import { api } from "../lib/api.js";
import { html } from "../lib/html.js";
import { usePoll } from "../lib/use-poll.js";
import { t, useLang } from "../i18n/index.js";
interface PermissionsData {
editMode?: string;
@@ -29,6 +30,7 @@ function groupByVerb(list: string[]): [string, string[]][] {
}
export function PermissionsPanel() {
useLang();
const { data, error, loading, refresh } = usePoll<PermissionsData>("/permissions", 5000);
const [draft, setDraft] = useState("");
const [busy, setBusy] = useState(false);
@@ -44,8 +46,8 @@ export function PermissionsPanel() {
method: "POST",
body: { prefix },
});
if (res.alreadyPresent) setFeedback({ kind: "info", text: `${prefix} already in list` });
else setFeedback({ kind: "ok", text: `added: ${prefix}` });
if (res.alreadyPresent) setFeedback({ kind: "info", text: t("permissions.alreadyIn", { prefix }) });
else setFeedback({ kind: "ok", text: t("permissions.added", { prefix }) });
setDraft("");
await refresh();
} catch (err) {
@@ -57,12 +59,12 @@ export function PermissionsPanel() {
const remove = useCallback(
async (prefix: string) => {
if (!confirm(`Remove "${prefix}" from this project's allowlist?`)) return;
if (!confirm(t("permissions.removeConfirm", { prefix }))) return;
setBusy(true);
setFeedback(null);
try {
await api("/permissions", { method: "DELETE", body: { prefix } });
setFeedback({ kind: "ok", text: `removed: ${prefix}` });
setFeedback({ kind: "ok", text: t("permissions.removed", { prefix }) });
await refresh();
} catch (err) {
setFeedback({ kind: "err", text: (err as Error).message });
@@ -74,7 +76,7 @@ export function PermissionsPanel() {
);
const clearAll = useCallback(async () => {
if (!confirm("Wipe every project allowlist entry? Builtin entries are unaffected.")) return;
if (!confirm(t("permissions.clearConfirm"))) return;
setBusy(true);
setFeedback(null);
try {
@@ -84,7 +86,7 @@ export function PermissionsPanel() {
});
setFeedback({
kind: "ok",
text: `cleared ${res.dropped} entr${res.dropped === 1 ? "y" : "ies"}`,
text: t("permissions.cleared", { count: res.dropped, y: res.dropped === 1 ? "y" : "ies" }),
});
await refresh();
} catch (err) {
@@ -95,8 +97,8 @@ export function PermissionsPanel() {
}, [refresh]);
if (loading && !data)
return html`<div class="card" style="color:var(--fg-3)">loading permissions…</div>`;
if (error) return html`<div class="card accent-err">permissions failed: ${error.message}</div>`;
return html`<div class="card" style="color:var(--fg-3)">${t("permissions.loading")}</div>`;
if (error) return html`<div class="card accent-err">${t("common.loadingFailed", { name: "permissions", error: error.message })}</div>`;
if (!data) return null;
const p = data;
@@ -111,18 +113,17 @@ export function PermissionsPanel() {
${
p.editMode === "yolo"
? html`<div class="card accent-warn">
<div class="card-h"><span class="title" style="color:var(--c-warn)">YOLO mode</span></div>
<div class="card-h"><span class="title" style="color:var(--c-warn)">${t("permissions.yoloTitle")}</span></div>
<div class="card-b">
Every shell command auto-runs, allowlist bypassed.
Switch back with <code class="mono">/mode review</code> in the TUI.
${t("permissions.yoloDesc")}
</div>
</div>`
: null
}
<div class="chips">
<span class="chip-f active">project <span class="ct">${p.project.length}</span></span>
<span class="chip-f">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>
${
@@ -130,13 +131,13 @@ export function PermissionsPanel() {
? html`
<div class="card">
<div class="card-h">
<span class="title">add a prefix</span>
<span class="title">${t("permissions.addPrefix")}</span>
<span class="meta">${p.currentCwd}</span>
</div>
<div style="display:flex;gap:8px;align-items:center">
<input
type="text"
placeholder='e.g. "npm run build" or "deploy.sh"'
placeholder=${t("permissions.addPlaceholder")}
value=${draft}
onInput=${(e: Event) => setDraft((e.target as HTMLInputElement).value)}
onKeyDown=${(e: KeyboardEvent) => {
@@ -145,12 +146,12 @@ export function PermissionsPanel() {
disabled=${busy}
style="flex:1"
/>
<button class="primary" onClick=${add} disabled=${busy || !draft.trim()}>Add</button>
<button class="primary" onClick=${add} disabled=${busy || !draft.trim()}>${t("common.add")}</button>
<button
class="danger"
onClick=${clearAll}
disabled=${busy || p.project.length === 0}
>Clear all</button>
>${t("permissions.clearAll")}</button>
</div>
${feedbackPill ? html`<div style="margin-top:8px">${feedbackPill}</div>` : null}
</div>
@@ -158,27 +159,25 @@ export function PermissionsPanel() {
: html`
<div class="card accent-warn">
<div class="card-b">
Mutations require <code class="mono">/dashboard</code> from inside an active
<code class="mono">reasonix code</code> session — standalone
<code class="mono">reasonix dashboard</code> can't tell which project's allowlist to edit.
${t("permissions.standaloneWarning")}
</div>
</div>
`
}
<h3 style="margin:6px 0 0;font-family:var(--font-mono);font-size:11px;color:var(--fg-3);text-transform:uppercase;letter-spacing:.1em">
Project allowlist · ${p.project.length}
${t("permissions.projectAllowlist", { count: p.project.length })}
</h3>
${
p.project.length === 0
? html`<div class="card" style="color:var(--fg-3)">Nothing stored yet for this project.</div>`
? html`<div class="card" style="color:var(--fg-3)">${t("permissions.nothingStored")}</div>`
: html`
<div class="card" style="padding:0;overflow:hidden">
<table class="tbl">
<thead>
<tr>
<th style="width:48px">#</th>
<th>prefix</th>
<th style="width:48px">${t("permissions.colNum")}</th>
<th>${t("permissions.colPrefix")}</th>
<th style="width:120px"></th>
</tr>
</thead>
@@ -195,7 +194,7 @@ export function PermissionsPanel() {
class="danger"
onClick=${() => remove(prefix)}
disabled=${busy}
>remove</button>`
>${t("common.remove")}</button>`
: null
}
</td>
@@ -209,7 +208,7 @@ export function PermissionsPanel() {
}
<h3 style="margin:6px 0 0;font-family:var(--font-mono);font-size:11px;color:var(--fg-3);text-transform:uppercase;letter-spacing:.1em">
Builtin · ${p.builtin.length} · read-only
${t("permissions.builtinTitle", { count: p.builtin.length })}
</h3>
<div class="card" style="font-family:var(--font-mono);font-size:11.5px;line-height:1.8">
${groupByVerb(p.builtin).map(
+38 -21
View File
@@ -2,6 +2,7 @@ import { useState } from "preact/hooks";
import { fmtPct, fmtRelativeTime } from "../lib/format.js";
import { html } from "../lib/html.js";
import { usePoll } from "../lib/use-poll.js";
import { t, useLang } from "../i18n/index.js";
interface PlanStep {
id: string;
@@ -26,34 +27,41 @@ interface PlansData {
}
function statusPill(p: ArchivedPlan) {
if (p.completionRatio >= 1) return html`<span class="pill ok">done</span>`;
if (p.completionRatio > 0) return html`<span class="pill info">active</span>`;
return html`<span class="pill">idle</span>`;
if (p.completionRatio >= 1) return html`<span class="pill ok">${t("plans.done")}</span>`;
if (p.completionRatio > 0) return html`<span class="pill info">${t("plans.active")}</span>`;
return html`<span class="pill">${t("plans.idle")}</span>`;
}
export function PlansPanel() {
useLang();
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)">loading plans…</div>`;
if (error) return html`<div class="card accent-err">plans failed: ${error.message}</div>`;
return html`<div class="card" style="color:var(--fg-3)">${t("plans.loading")}</div>`;
if (error) return html`<div class="card accent-err">${t("common.loadingFailed", { name: "plans", error: error.message })}</div>`;
const plans = data?.plans ?? [];
if (plans.length === 0)
return html`<div class="card" style="color:var(--fg-3)">
No archived plans yet — run a turn that calls <code class="mono">submit_plan</code>
and <code class="mono">mark_step_complete</code>.
${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;
@@ -63,20 +71,29 @@ export function PlansPanel() {
<div class="ssl-h">
<input
type="text"
placeholder="filter plans"
placeholder=${t("plans.filterPlaceholder")}
value=${filter}
onInput=${(e: Event) => setFilter((e.target as HTMLInputElement).value)}
style="flex:1"
/>
</div>
<div class="chips" style="padding:0 12px 8px">
<span class="chip-f active">all <span class="ct">${plans.length}</span></span>
<span class="chip-f">
active
<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">
done <span class="ct">${plans.filter((p) => p.completionRatio >= 1).length}</span>
<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>
<div class="ssl-rows">
@@ -92,7 +109,7 @@ export function PlansPanel() {
: null
}
<span class="meta">
<span><span class="v">${p.totalSteps}</span> steps</span>
<span><span class="v">${p.totalSteps}</span> ${t("plans.steps")}</span>
<span><span class="v">${p.completedSteps} / ${p.totalSteps}</span> · ${fmtPct(p.completionRatio)}</span>
<span>${fmtRelativeTime(p.completedAt)}</span>
</span>
@@ -106,19 +123,19 @@ export function PlansPanel() {
${
open == null
? html`<div style="color:var(--fg-3);font-size:13px;text-align:center;padding:60px 20px">
Pick a plan on the left.
${t("plans.pickHint")}
</div>`
: html`
<div class="sessions-detail-h">
<span class="name">${open.summary ?? "(no title)"}</span>
<span class="name">${open.summary ?? t("plans.noTitle")}</span>
<span class="ws">${open.session} · ${fmtRelativeTime(open.completedAt)}</span>
<span class="actions">
<button class="btn ghost" onClick=${() => setOpenIdx(null)}>← back</button>
<button class="btn ghost" onClick=${() => setOpenIdx(null)}>${t("common.back")}</button>
</span>
</div>
<h3 style="margin:0 0 6px;font-family:var(--font-mono);font-size:11px;color:var(--fg-3);text-transform:uppercase;letter-spacing:.1em">
Step timeline · ${open.completedSteps} / ${open.totalSteps}
${t("plans.stepTimeline", { done: open.completedSteps, total: open.totalSteps })}
</h3>
<div class="plan-timeline" style="margin-bottom:14px">
${open.steps.map((step, i) => {
@@ -126,7 +143,7 @@ export function PlansPanel() {
const cls = done ? "done" : i === open.completedSteps ? "active" : "";
return html`
<div class=${`plan-step ${cls}`}>
<span class="lbl">step ${i + 1}</span>
<span class="lbl">${t("plans.step", { n: i + 1 })}</span>
<span class="name">${step.title}</span>
${step.action ? html`<span class="meta">${step.action}</span>` : null}
${
File diff suppressed because it is too large. Load diff
+16 -14
View File
@@ -4,6 +4,7 @@ import { api } from "../lib/api.js";
import { fmtBytes, fmtNum, fmtRelativeTime } from "../lib/format.js";
import { html } from "../lib/html.js";
import { usePoll } from "../lib/use-poll.js";
import { t, useLang } from "../i18n/index.js";
interface SessionEntry {
name: string;
@@ -23,6 +24,7 @@ interface OpenSession {
}
export function SessionsPanel() {
useLang();
const { data, error, loading } = usePoll<SessionsData>("/sessions", 5000);
const [open, setOpen] = useState<OpenSession | null>(null);
const [openLoading, setOpenLoading] = useState(false);
@@ -42,12 +44,12 @@ export function SessionsPanel() {
}, []);
if (loading && !data)
return html`<div class="card" style="color:var(--fg-3)">loading sessions…</div>`;
if (error) return html`<div class="card accent-err">sessions failed: ${error.message}</div>`;
return html`<div class="card" style="color:var(--fg-3)">${t("sessions.loading")}</div>`;
if (error) return html`<div class="card accent-err">${t("common.loadingFailed", { name: "sessions", error: error.message })}</div>`;
const sessions = data?.sessions ?? [];
if (sessions.length === 0)
return html`<div class="card" style="color:var(--fg-3)">No saved sessions yet.</div>`;
return html`<div class="card" style="color:var(--fg-3)">${t("sessions.noSessions")}</div>`;
const filtered = filter.trim()
? sessions.filter((s) => s.name.toLowerCase().includes(filter.toLowerCase()))
@@ -59,14 +61,14 @@ export function SessionsPanel() {
<div class="ssl-h">
<input
type="text"
placeholder="filter sessions"
placeholder=${t("sessions.filterPlaceholder")}
value=${filter}
onInput=${(e: Event) => setFilter((e.target as HTMLInputElement).value)}
style="flex:1"
/>
</div>
<div class="chips" style="padding:0 12px 8px">
<span class="chip-f active">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(
@@ -77,7 +79,7 @@ export function SessionsPanel() {
>
<span class="name">${s.name}</span>
<span class="meta">
<span><span class="v">${fmtNum(s.messageCount)}</span> msgs</span>
<span><span class="v">${fmtNum(s.messageCount)}</span> ${t("sessions.msgs")}</span>
<span><span class="v">${fmtBytes(s.size)}</span></span>
<span>${fmtRelativeTime(s.mtime)}</span>
</span>
@@ -91,7 +93,7 @@ export function SessionsPanel() {
${
open == null
? html`<div style="color:var(--fg-3);font-size:13px;text-align:center;padding:60px 20px">
Pick a session on the left to read its transcript.
${t("sessions.pickHint")}
</div>`
: html`
<div class="sessions-detail-h">
@@ -99,24 +101,24 @@ export function SessionsPanel() {
<span class="ws">
${
open.messages
? `${open.messages.length} message${open.messages.length === 1 ? "" : "s"}`
: "loading…"
? t("sessions.messages", { count: open.messages.length, s: open.messages.length === 1 ? "" : "s" })
: t("common.loading")
}
</span>
<span class="actions">
<button class="btn ghost" onClick=${() => setOpen(null)}>← back</button>
<button class="btn ghost" onClick=${() => setOpen(null)}>${t("common.back")}</button>
</span>
</div>
<div class="card accent-brand" style="margin-bottom:10px">
<div class="card-h"><span class="title">Resume in TUI</span></div>
<div class="card-h"><span class="title">${t("sessions.resumeTitle")}</span></div>
<div class="card-b" style="font-size:12.5px;color:var(--fg-2)">
Mid-session swap requires a restart so the message log can rewind cleanly. Quit your current session, then run:
${t("sessions.resumeDesc")}
<code class="mono" style="display:block;margin-top:8px;padding:8px 10px;background:var(--bg-input);border-radius:var(--r);color:var(--fg-0);font-size:12px;user-select:all">reasonix chat --session ${open.name}</code>
</div>
</div>
${
openLoading
? html`<div style="color:var(--fg-3)">loading transcript…</div>`
? html`<div style="color:var(--fg-3)">${t("sessions.loadingTranscript")}</div>`
: open.error
? html`<div class="card accent-err">${open.error}</div>`
: open.messages && open.messages.length > 0
@@ -143,7 +145,7 @@ export function SessionsPanel() {
`,
)}
</div>`
: html`<div style="color:var(--fg-3)">empty transcript.</div>`
: html`<div style="color:var(--fg-3)">${t("sessions.emptyTranscript")}</div>`
}
`
}
+538 -30
View File
@@ -1,6 +1,21 @@
import { useCallback, useEffect, useState } from "preact/hooks";
import { useCallback, useEffect, useRef, useState } from "preact/hooks";
import { api } from "../lib/api.js";
import {
type BudgetState,
QUICK_CAPS_USD,
budgetTone,
bumpSuggestions,
deriveBudgetState,
} from "../lib/budget.js";
import { html } from "../lib/html.js";
import {
INTERVAL_PRESETS_MS,
type IntervalUnit,
type LoopRunStatus,
formatRemaining,
parseCustomInterval,
} from "../lib/loop-control.js";
import { type DashboardLang, getLang, setLang, t, useLang } from "../i18n/index.js";
interface SettingsData {
apiKey?: string | null;
@@ -10,14 +25,380 @@ interface SettingsData {
search?: boolean;
model?: string;
editMode?: string;
proNext?: boolean;
budgetUsd?: number | null;
/** Cumulative session spend (USD); null when no session is attached. */
sessionSpendUsd?: number | null;
}
function fmtUsd2(n: number): string {
return `$${n.toFixed(n < 1 ? 4 : 2)}`;
}
interface ModelPriceEntry {
inputCacheHit: number;
inputCacheMiss: number;
output: number;
}
interface ModelCatalog {
models: string[] | null;
current: string | null;
pricing: Record<string, ModelPriceEntry>;
}
function formatPricing(p: ModelPriceEntry | undefined): string | null {
if (!p) return null;
return t("settings.modelPricingLine", {
hit: p.inputCacheHit.toFixed(3),
miss: p.inputCacheMiss.toFixed(3),
out: p.output.toFixed(3),
});
}
function ModelRow({
current,
catalog,
saving,
onPick,
}: {
current: string;
catalog: ModelCatalog | null;
saving: boolean;
onPick: (model: string) => void;
}) {
const list = catalog?.models ?? null;
const ready = list && list.length > 0;
if (!ready) {
// Fallback: catalog hasn't loaded (or API failed). Read-only — same as before D-4.
return html`<code class="mono">${current ?? "—"}</code>`;
}
// Ensure the live model is selectable even if the catalog hasn't reported it
// yet (preset overrides, custom IDs).
const options = list.includes(current) ? list : [current, ...list];
const price = catalog?.pricing[current];
return html`
<span style="display:inline-flex;flex-direction:column;gap:4px">
<select
value=${current}
onChange=${(e: Event) => {
const next = (e.target as HTMLSelectElement).value;
if (next && next !== current) onPick(next);
}}
disabled=${saving}
style="font-family:var(--font-mono);min-width:200px"
>
${options.map((m) => html`<option key=${m} value=${m}>${m}</option>`)}
</select>
${
price
? html`<span style="color:var(--fg-3);font-size:11px;font-family:var(--font-mono)">${formatPricing(price)}</span>`
: null
}
</span>
`;
}
function BudgetGauge({ state }: { state: BudgetState }) {
if (state.kind === "off") return null;
const tone = budgetTone(state);
const fill = Math.min(100, state.pct);
const valueColor =
tone === "err"
? "color:var(--c-err)"
: tone === "warn"
? "color:var(--c-warn)"
: "color:var(--fg-1)";
return html`
<div style="display:flex;flex-direction:column;gap:6px">
<div style="display:flex;justify-content:space-between;align-items:baseline;font-size:13px">
<span style=${valueColor}>
<strong style="font-family:var(--font-mono)">${fmtUsd2(state.spent)}</strong>
<span style="color:var(--fg-3)"> ${t("settings.budgetOf")} </span>
<strong style="font-family:var(--font-mono)">${fmtUsd2(state.cap)}</strong>
</span>
<span style=${`font-family:var(--font-mono);font-size:11px;${valueColor}`}>${state.pct.toFixed(1)}%</span>
</div>
<div class=${`progress ${tone}`}><div class="progress-fill" style=${`width:${fill}%`}></div></div>
<span style="color:var(--fg-3);font-size:11px">
${
state.kind === "exhausted"
? t("settings.budgetRefusing")
: state.kind === "warn"
? t("settings.budgetWarnLine")
: t("settings.budgetIdleLine")
}
</span>
</div>
`;
}
interface BudgetSectionProps {
state: BudgetState;
saving: boolean;
onSetCap: (usd: number) => void;
onClear: () => void;
}
function BudgetSection({ state, saving, onSetCap, onClear }: BudgetSectionProps) {
const [custom, setCustom] = useState("");
const submitCustom = () => {
const n = Number.parseFloat(custom);
if (Number.isFinite(n) && n > 0) {
onSetCap(n);
setCustom("");
}
};
const quickButtons = (caps: ReadonlyArray<number>) =>
caps.map(
(c) => html`
<button
key=${c}
class="btn"
style="font-family:var(--font-mono)"
disabled=${saving}
onClick=${() => onSetCap(c)}
>$${c}</button>
`,
);
const customField = html`
<span style="display:inline-flex;align-items:center;gap:4px;margin-left:auto">
<span style="color:var(--fg-3);font-size:11px">${t("settings.budgetCustom")}</span>
<input
type="number"
min="0.01"
step="0.01"
value=${custom}
placeholder="0.00"
onInput=${(e: Event) => setCustom((e.target as HTMLInputElement).value)}
onKeyDown=${(e: KeyboardEvent) => {
if (e.key === "Enter") submitCustom();
}}
style="width:72px;font-family:var(--font-mono)"
disabled=${saving}
/>
<button
class="btn primary"
disabled=${saving || !(Number.parseFloat(custom) > 0)}
onClick=${submitCustom}
>→</button>
</span>
`;
return html`
<div class="card" style="display:flex;flex-direction:column;gap:12px">
<${BudgetGauge} state=${state} />
${
state.kind === "off"
? html`
<div>
<div style="color:var(--fg-3);font-size:11px;margin-bottom:6px">${t("settings.budgetSetCap")}</div>
<div style="display:flex;gap:6px;align-items:center;flex-wrap:wrap">
${quickButtons(QUICK_CAPS_USD)}
${customField}
</div>
</div>
`
: state.kind === "warn" || state.kind === "exhausted"
? html`
<div>
<div style="color:var(--fg-3);font-size:11px;margin-bottom:6px">${t("settings.budgetBumpHint")}</div>
<div style="display:flex;gap:6px;align-items:center;flex-wrap:wrap">
${bumpSuggestions(state.cap).map(
(next) => html`
<button
key=${next}
class="btn primary"
style="font-family:var(--font-mono)"
disabled=${saving}
onClick=${() => onSetCap(next)}
>→ $${next % 1 === 0 ? next : next.toFixed(2)}</button>
`,
)}
${customField}
</div>
<div style="margin-top:8px">
<button class="btn" disabled=${saving} onClick=${onClear}>${t("settings.budgetClear")}</button>
</div>
</div>
`
: html`
<div style="display:flex;gap:6px;align-items:center;flex-wrap:wrap">
${bumpSuggestions(state.cap).map(
(next) => html`
<button
key=${next}
class="btn"
style="font-family:var(--font-mono)"
disabled=${saving}
onClick=${() => onSetCap(next)}
>→ $${next % 1 === 0 ? next : next.toFixed(2)}</button>
`,
)}
${customField}
<button
class="btn"
style="margin-left:8px"
disabled=${saving}
onClick=${onClear}
>${t("settings.budgetClear")}</button>
</div>
`
}
</div>
`;
}
interface LoopSectionProps {
status: LoopRunStatus | null;
/** ms remaining until next fire — ticks down client-side between status polls. */
remainingMs: number;
/** Last-turn cost in USD; used as a hint for "each iteration costs ~". */
avgIterCostUsd: number | null;
busy: boolean;
onStart: (intervalMs: number, prompt: string) => void;
onStop: () => void;
}
function LoopSection({
status,
remainingMs,
avgIterCostUsd,
busy,
onStart,
onStop,
}: LoopSectionProps) {
const [intervalMs, setIntervalMs] = useState<number>(INTERVAL_PRESETS_MS[1]!.ms);
const [prompt, setPrompt] = useState("");
const [customValue, setCustomValue] = useState("");
const [customUnit, setCustomUnit] = useState<IntervalUnit>("m");
if (status) {
return html`
<div class="card" style="display:flex;flex-direction:column;gap:10px">
<div style="display:flex;justify-content:space-between;align-items:baseline">
<span style="color:var(--c-warn);font-family:var(--font-mono);font-size:11px">⟳ ${t("settings.loopRunning")}</span>
<span style="color:var(--fg-3);font-size:11px">
${t("settings.loopIter", { iter: status.iter })} · ${t("settings.loopFiresIn", { remaining: formatRemaining(remainingMs) })}
</span>
</div>
<div style="background:var(--bg-elev-2);border:1px solid var(--bd);border-radius:var(--r);padding:8px 10px;font-family:var(--font-mono);font-size:12px;color:var(--fg-1);white-space:pre-wrap;max-height:120px;overflow-y:auto">${status.prompt}</div>
<div>
<button class="btn danger" disabled=${busy} onClick=${onStop}>${t("settings.loopStop")}</button>
</div>
</div>
`;
}
const customMs = parseCustomInterval(customValue, customUnit);
const canStart = !busy && intervalMs > 0 && prompt.trim().length > 0;
return html`
<div class="card" style="display:flex;flex-direction:column;gap:10px">
<div style="color:var(--fg-3);font-size:11px">
${t("settings.loopIdleHint")}
${
typeof avgIterCostUsd === "number" && avgIterCostUsd > 0
? html` ${t("settings.loopCostHint", { cost: `$${avgIterCostUsd.toFixed(4)}` })}`
: null
}
</div>
<div style="display:flex;flex-direction:column;gap:6px">
<span style="color:var(--fg-3);font-size:11px">${t("settings.loopInterval")}</span>
<div style="display:flex;gap:6px;align-items:center;flex-wrap:wrap">
${INTERVAL_PRESETS_MS.map(
(p) => html`
<button
key=${p.ms}
class=${`btn ${intervalMs === p.ms && customValue === "" ? "primary" : ""}`}
style="font-family:var(--font-mono)"
disabled=${busy}
onClick=${() => {
setIntervalMs(p.ms);
setCustomValue("");
}}
>${p.label}</button>
`,
)}
<span style="display:inline-flex;align-items:center;gap:4px;margin-left:auto">
<span style="color:var(--fg-3);font-size:11px">${t("settings.loopCustom")}</span>
<input
type="number"
min="1"
step="1"
value=${customValue}
onInput=${(e: Event) => {
const raw = (e.target as HTMLInputElement).value;
setCustomValue(raw);
const ms = parseCustomInterval(raw, customUnit);
if (ms !== null) setIntervalMs(ms);
}}
style="width:64px;font-family:var(--font-mono)"
disabled=${busy}
/>
<select
value=${customUnit}
onChange=${(e: Event) => {
const next = (e.target as HTMLSelectElement).value as IntervalUnit;
setCustomUnit(next);
if (customValue) {
const ms = parseCustomInterval(customValue, next);
if (ms !== null) setIntervalMs(ms);
}
}}
disabled=${busy}
>
<option value="s">s</option>
<option value="m">m</option>
<option value="h">h</option>
</select>
</span>
</div>
${
customValue && customMs === null
? html`<span style="color:var(--c-err);font-size:11px">${t("settings.loopRangeError")}</span>`
: null
}
</div>
<div style="display:flex;flex-direction:column;gap:6px">
<span style="color:var(--fg-3);font-size:11px">${t("settings.loopPrompt")}</span>
<textarea
rows="3"
placeholder=${t("settings.loopPromptPlaceholder")}
value=${prompt}
onInput=${(e: Event) => setPrompt((e.target as HTMLTextAreaElement).value)}
style="width:100%;font-family:var(--font-mono);resize:vertical"
disabled=${busy}
></textarea>
</div>
<div>
<button
class="btn primary"
disabled=${!canStart}
onClick=${() => onStart(intervalMs, prompt.trim())}
>${t("settings.loopStart")}</button>
</div>
</div>
`;
}
export function SettingsPanel() {
useLang();
const [data, setData] = useState<SettingsData | null>(null);
const [error, setError] = useState<string | null>(null);
const [saving, setSaving] = useState(false);
const [saved, setSaved] = useState<string | null>(null);
const [draft, setDraft] = useState<Partial<SettingsData>>({});
const [catalog, setCatalog] = useState<ModelCatalog | null>(null);
const [loopStatus, setLoopStatus] = useState<LoopRunStatus | null>(null);
const [loopAvgCost, setLoopAvgCost] = useState<number | null>(null);
const [loopBusy, setLoopBusy] = useState(false);
/** Wall-clock time of the last status sync — used to interpolate the countdown. */
const lastStatusSyncRef = useRef<number>(0);
const [now, setNow] = useState<number>(() => Date.now());
const load = useCallback(async () => {
try {
@@ -31,6 +412,73 @@ export function SettingsPanel() {
useEffect(() => {
load();
}, [load]);
useEffect(() => {
api<ModelCatalog>("/models")
.then(setCatalog)
.catch(() => undefined);
}, []);
const refreshLoop = useCallback(async () => {
try {
const r = await api<{ status: LoopRunStatus | null }>("/loop/status");
setLoopStatus(r.status);
lastStatusSyncRef.current = Date.now();
} catch {
/* ignore — status is best-effort */
}
try {
const r = await api<{ stats?: { lastTurnCostUsd?: number } }>("/overview");
setLoopAvgCost(r.stats?.lastTurnCostUsd ?? null);
} catch {
/* ignore */
}
}, []);
useEffect(() => {
let cancelled = false;
refreshLoop();
const id = setInterval(() => {
if (!cancelled) refreshLoop();
}, 5_000);
return () => {
cancelled = true;
clearInterval(id);
};
}, [refreshLoop]);
useEffect(() => {
if (!loopStatus) return;
const id = setInterval(() => setNow(Date.now()), 1_000);
return () => clearInterval(id);
}, [loopStatus]);
const remainingMs = loopStatus
? Math.max(0, loopStatus.nextFireMs - (now - lastStatusSyncRef.current))
: 0;
const startLoop = useCallback(
async (intervalMs: number, prompt: string) => {
setLoopBusy(true);
try {
await api("/loop/start", { method: "POST", body: { intervalMs, prompt } });
await refreshLoop();
} catch (err) {
setError((err as Error).message);
} finally {
setLoopBusy(false);
}
},
[refreshLoop],
);
const stopLoop = useCallback(async () => {
setLoopBusy(true);
try {
await api("/loop/stop", { method: "POST" });
await refreshLoop();
} catch (err) {
setError((err as Error).message);
} finally {
setLoopBusy(false);
}
}, [refreshLoop]);
const save = useCallback(
async (fields: Partial<SettingsData>) => {
@@ -39,7 +487,7 @@ export function SettingsPanel() {
try {
await api("/settings", { method: "POST", body: fields });
await load();
setSaved(`saved: ${Object.keys(fields).join(", ")}`);
setSaved(t("settings.saved", { fields: Object.keys(fields).join(", ") }));
setTimeout(() => setSaved(null), 3000);
} catch (err) {
setError((err as Error).message);
@@ -51,7 +499,7 @@ export function SettingsPanel() {
);
if (!data && !error)
return html`<div class="card" style="color:var(--fg-3)">loading settings…</div>`;
return html`<div class="card" style="color:var(--fg-3)">${t("settings.loading")}</div>`;
if (error && !data) return html`<div class="card accent-err">${error}</div>`;
if (!data) return null;
const v = data;
@@ -71,6 +519,8 @@ export function SettingsPanel() {
</div>
`;
const currentLang = getLang();
return html`
<div style="max-width:760px;display:flex;flex-direction:column;gap:6px">
${
@@ -80,18 +530,37 @@ export function SettingsPanel() {
error ? html`<div class="card accent-err">${error}</div>` : null
}
${sectionH3("DeepSeek API")}
${sectionH3(t("settings.sectionLanguage"))}
<div class="card">
${fieldRow(
"API key",
html`<code class="mono" style="color:var(--fg-2);font-size:11.5px">${v.apiKey ?? "(not set)"}</code>`,
t("settings.language"),
html`
<select
value=${currentLang}
onChange=${(e: Event) => {
const lang = (e.target as HTMLSelectElement).value as DashboardLang;
setLang(lang);
}}
>
<option value="en">${t("settings.langEn")}</option>
<option value="zh-CN">${t("settings.langZhCn")}</option>
</select>
`,
)}
</div>
${sectionH3(t("settings.sectionApi"))}
<div class="card">
${fieldRow(
t("settings.apiKey"),
html`<code class="mono" style="color:var(--fg-2);font-size:11.5px">${v.apiKey ?? t("settings.notSet")}</code>`,
)}
${fieldRow(
"replace",
t("settings.replace"),
html`
<input
type="password"
placeholder="paste a fresh sk-… token"
placeholder=${t("settings.pasteKey")}
value=${draft.apiKey ?? ""}
onInput=${(e: Event) => setDraft({ ...draft, apiKey: (e.target as HTMLInputElement).value })}
style="flex:1"
@@ -100,16 +569,16 @@ export function SettingsPanel() {
class="btn primary"
disabled=${saving || !(draft.apiKey ?? "").trim()}
onClick=${() => save({ apiKey: draft.apiKey })}
>Save key</button>
>${t("settings.saveKey")}</button>
`,
)}
${fieldRow(
"base url",
t("settings.baseUrl"),
html`
<input
type="text"
value=${draft.baseUrl ?? v.baseUrl ?? ""}
placeholder="https://api.deepseek.com (default)"
placeholder=${t("settings.baseUrlPlaceholder")}
onInput=${(e: Event) => setDraft({ ...draft, baseUrl: (e.target as HTMLInputElement).value })}
style="flex:1"
/>
@@ -117,65 +586,104 @@ export function SettingsPanel() {
class="btn"
disabled=${saving || (draft.baseUrl ?? v.baseUrl ?? "") === (v.baseUrl ?? "")}
onClick=${() => save({ baseUrl: draft.baseUrl })}
>Save</button>
>${t("common.save")}</button>
`,
)}
</div>
${sectionH3("Defaults")}
${sectionH3(t("settings.sectionDefaults"))}
<div class="card">
${fieldRow(
"preset",
t("settings.preset"),
html`
<select
value=${["auto", "flash", "pro"].includes(v.preset ?? "") ? v.preset : "auto"}
onChange=${(e: Event) => save({ preset: (e.target as HTMLSelectElement).value })}
disabled=${saving}
>
<option value="auto">auto — flash → pro on hard turns</option>
<option value="flash">flash — always flash, no auto-escalate</option>
<option value="pro">pro — always pro</option>
<option value="auto">${t("settings.presetAuto")}</option>
<option value="flash">${t("settings.presetFlash")}</option>
<option value="pro">${t("settings.presetPro")}</option>
</select>
`,
"applies next turn",
t("settings.appliesNextTurn"),
)}
${fieldRow(
"effort",
t("settings.effort"),
html`
<select
value=${v.reasoningEffort}
onChange=${(e: Event) => save({ reasoningEffort: (e.target as HTMLSelectElement).value })}
disabled=${saving}
>
<option value="max">max (default — best)</option>
<option value="high">high (cheaper / faster)</option>
<option value="max">${t("settings.effortMax")}</option>
<option value="high">${t("settings.effortHigh")}</option>
</select>
`,
"applies next turn",
t("settings.appliesNextTurn"),
)}
${fieldRow(
"web search",
t("settings.webSearch"),
html`
<button
class=${`btn ${v.search ? "primary" : ""}`}
onClick=${() => save({ search: !v.search })}
disabled=${saving}
>${v.search ? "ON" : "off"}</button>
>${v.search ? t("common.on") : t("common.off")}</button>
`,
"web_fetch + web_search tools",
t("settings.webSearchNote"),
)}
</div>
${sectionH3("Runtime")}
${sectionH3(t("settings.sectionCompute"))}
<div class="card">
${fieldRow(
"active model",
html`<code class="mono">${v.model ?? "—"}</code>`,
t("settings.proNext"),
html`
<button
class=${`btn ${v.proNext ? "primary" : ""}`}
onClick=${() => save({ proNext: !v.proNext })}
disabled=${saving}
>${v.proNext ? t("settings.proArmed") : t("settings.proArm")}</button>
`,
t("settings.proNextNote"),
)}
</div>
${sectionH3(t("settings.sectionBudget"))}
<${BudgetSection}
state=${deriveBudgetState(v.budgetUsd, v.sessionSpendUsd)}
saving=${saving}
onSetCap=${(usd: number) => save({ budgetUsd: usd })}
onClear=${() => save({ budgetUsd: null })}
/>
${sectionH3(t("settings.sectionLoop"))}
<${LoopSection}
status=${loopStatus}
remainingMs=${remainingMs}
avgIterCostUsd=${loopAvgCost}
busy=${loopBusy}
onStart=${startLoop}
onStop=${stopLoop}
/>
${sectionH3(t("settings.sectionRuntime"))}
<div class="card">
${fieldRow(
t("settings.activeModel"),
html`<${ModelRow}
current=${v.model ?? "—"}
catalog=${catalog}
saving=${saving}
onPick=${(m: string) => save({ model: m })}
/>`,
t("settings.appliesNextTurn"),
)}
${fieldRow(
"edit mode",
t("settings.editMode"),
html`<code class="mono">${v.editMode}</code>`,
"switch from the Chat tab header",
t("settings.editModeNote"),
)}
</div>
</div>
+42 -25
View File
@@ -1,6 +1,7 @@
import { useCallback, useEffect, useState } from "preact/hooks";
import { api } from "../lib/api.js";
import { html } from "../lib/html.js";
import { t, useLang } from "../i18n/index.js";
interface SkillEntry {
name: string;
@@ -18,6 +19,7 @@ interface SkillsData {
type Scope = "project" | "global" | "builtin";
export function SkillsPanel() {
useLang();
const [data, setData] = useState<SkillsData | null>(null);
const [error, setError] = useState<string | null>(null);
const [open, setOpen] = useState<{ scope: Scope; name: string } | null>(null);
@@ -27,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 {
@@ -64,7 +67,7 @@ export function SkillsPanel() {
method: "POST",
body: { body },
});
setInfo(`saved ${open.scope}/${open.name}`);
setInfo(t("skills.saved", { scope: open.scope, name: open.name }));
setTimeout(() => setInfo(null), 3000);
await load();
} catch (err) {
@@ -76,7 +79,7 @@ export function SkillsPanel() {
const remove = useCallback(async () => {
if (!open) return;
if (!confirm(`Delete skill ${open.scope}/${open.name}?`)) return;
if (!confirm(t("skills.deleteConfirm", { scope: open.scope, name: open.name }))) return;
setBusy(true);
try {
await api(`/skills/${open.scope}/${encodeURIComponent(open.name)}`, { method: "DELETE" });
@@ -109,7 +112,7 @@ export function SkillsPanel() {
}, [newName, newScope, load, openSkill]);
if (!data && !error)
return html`<div class="card" style="color:var(--fg-3)">loading skills…</div>`;
return html`<div class="card" style="color:var(--fg-3)">${t("skills.loading")}</div>`;
if (error && !data) return html`<div class="card accent-err">${error}</div>`;
if (!data) return null;
@@ -118,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">
@@ -132,17 +137,29 @@ export function SkillsPanel() {
<div class="ssl-h">
<input
type="text"
placeholder="filter skills"
placeholder=${t("skills.filterPlaceholder")}
value=${filter}
onInput=${(e: Event) => setFilter((e.target as HTMLInputElement).value)}
style="flex:1"
/>
</div>
<div class="chips" style="padding:0 12px 8px">
<span class="chip-f active">all <span class="ct">${allWith.length}</span></span>
<span class="chip-f">project <span class="ct">${data.project.length}</span></span>
<span class="chip-f">global <span class="ct">${data.global.length}</span></span>
<span class="chip-f">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">
@@ -151,12 +168,12 @@ export function SkillsPanel() {
onChange=${(e: Event) => setNewScope((e.target as HTMLSelectElement).value as "global" | "project")}
style="flex:0 0 auto;font-size:11.5px;padding:5px 6px"
>
<option value="global">global</option>
${data.paths.project ? html`<option value="project">project</option>` : null}
<option value="global">${t("skills.global")}</option>
${data.paths.project ? html`<option value="project">${t("skills.project")}</option>` : null}
</select>
<input
type="text"
placeholder="new skill"
placeholder=${t("skills.newSkill")}
value=${newName}
onInput=${(e: Event) => setNewName((e.target as HTMLInputElement).value)}
style="flex:1;min-width:0"
@@ -174,13 +191,13 @@ export function SkillsPanel() {
>
<span class="name">
${s.name}
${s.scope === "builtin" ? html`<span class="pill">builtin</span>` : null}
${s.scope === "builtin" ? html`<span class="pill">${t("skills.builtin")}</span>` : null}
</span>
<span class="preview">${s.description ?? "(no description)"}</span>
<span class="preview">${s.description ?? t("skills.noDescription")}</span>
<span class="meta">
${
typeof s.runs7d === "number" && s.runs7d > 0
? html`<span><span class="v">${s.runs7d}</span> runs · 7d</span>`
? html`<span><span class="v">${s.runs7d}</span> ${t("skills.runs7d")}</span>`
: null
}
<span class="dim">${s.scope}</span>
@@ -195,7 +212,7 @@ export function SkillsPanel() {
${
open == null
? html`<div style="color:var(--fg-3);font-size:13px;text-align:center;padding:60px 20px">
Pick a skill on the left, or create a new one above.
${t("skills.pickHint")}
</div>`
: open.scope === "builtin"
? (() => {
@@ -203,16 +220,16 @@ export function SkillsPanel() {
return html`
<div class="sessions-detail-h">
<span class="name">${open.scope}/${open.name}</span>
<span class="ws"><span class="pill">read-only · builtin</span></span>
<span class="ws"><span class="pill">${t("skills.readOnlyBuiltin")}</span></span>
<span class="actions">
<button class="btn ghost" onClick=${() => setOpen(null)}>← back</button>
<button class="btn ghost" onClick=${() => setOpen(null)}>${t("common.back")}</button>
</span>
</div>
<div style="color:var(--fg-2);font-size:13px;line-height:1.6">
${builtin?.description ?? "(no description)"}
${builtin?.description ?? t("skills.noDescription")}
</div>
<div style="margin-top:14px;color:var(--fg-3);font-size:11.5px">
Built-in skills ship with Reasonix; the model picks them up automatically. To customize, create a project- or global-scoped skill with the same name.
${t("skills.builtinDesc")}
</div>
`;
})()
@@ -221,10 +238,10 @@ export function SkillsPanel() {
<span class="name">${open.scope}/${open.name}</span>
<span class="ws">${body.length.toLocaleString()} chars</span>
<span class="actions">
<button class="btn primary" disabled=${busy} onClick=${save}>Save</button>
<button class="btn primary" disabled=${busy} onClick=${save}>${t("common.save")}</button>
<button class="btn" disabled=${busy} onClick=${remove}
style="border-color:var(--c-err);color:var(--c-err)">Delete</button>
<button class="btn ghost" onClick=${() => setOpen(null)}>← back</button>
style="border-color:var(--c-err);color:var(--c-err)">${t("common.delete")}</button>
<button class="btn ghost" onClick=${() => setOpen(null)}>${t("common.back")}</button>
</span>
</div>
${info ? html`<div style="margin-bottom:8px"><span class="pill ok">${info}</span></div>` : null}
@@ -236,7 +253,7 @@ export function SkillsPanel() {
disabled=${busy}
></textarea>
<div style="margin-top:8px;color:var(--fg-3);font-size:11.5px">
re-loaded on next <code class="mono">/new</code> or session restart
${t("skills.reloadHint")}
</div>
`
}
+31 -29
View File
@@ -1,6 +1,7 @@
import { fmtBytes, fmtNum } from "../lib/format.js";
import { html } from "../lib/html.js";
import { usePoll } from "../lib/use-poll.js";
import { t, useLang } from "../i18n/index.js";
interface HealthData {
version: string;
@@ -14,97 +15,98 @@ interface HealthData {
}
export function SystemPanel() {
useLang();
const { data, error, loading } = usePoll<HealthData>("/health", 5000);
if (loading && !data)
return html`<div class="card" style="color:var(--fg-3)">loading health…</div>`;
if (error) return html`<div class="card accent-err">health failed: ${error.message}</div>`;
return html`<div class="card" style="color:var(--fg-3)">${t("system.loading")}</div>`;
if (error) return html`<div class="card accent-err">${t("common.loadingFailed", { name: "health", error: error.message })}</div>`;
if (!data) return null;
const h = data;
const upToDate = h.latestVersion ? h.latestVersion === h.version : null;
return html`
<div style="display:flex;flex-direction:column;gap:14px">
<h3 style="margin:0;font-family:var(--font-mono);font-size:11px;color:var(--fg-3);text-transform:uppercase;letter-spacing:.1em">Health checks</h3>
<h3 style="margin:0;font-family:var(--font-mono);font-size:11px;color:var(--fg-3);text-transform:uppercase;letter-spacing:.1em">${t("system.healthChecks")}</h3>
<div class="health-grid">
<div class=${`health-item ${upToDate === false ? "warn" : ""}`}>
<div class="lbl">
version
${t("system.version")}
${
upToDate === null
? html`<span class="pill">checking</span>`
? html`<span class="pill">${t("system.checking")}</span>`
: upToDate
? html`<span class="pill ok">● latest</span>`
: html`<span class="pill warn">● out of date</span>`
? html`<span class="pill ok">${t("system.latest")}</span>`
: html`<span class="pill warn">${t("system.outOfDate")}</span>`
}
</div>
<div class="v">${h.version}</div>
<div class="meta">${
upToDate === null
? "version check pending"
? t("system.versionPending")
: upToDate
? "up to date"
: `latest: ${h.latestVersion}`
? t("system.upToDate")
: t("system.latestVer", { version: h.latestVersion ?? "" })
}</div>
</div>
<div class="health-item">
<div class="lbl">sessions <span class="pill ok">● ok</span></div>
<div class="lbl">${t("system.sessions")} <span class="pill ok">${t("system.ok")}</span></div>
<div class="v">${fmtBytes(h.sessions.totalBytes)}</div>
<div class="meta">${fmtNum(h.sessions.count)} files</div>
<div class="meta">${fmtNum(h.sessions.count)} ${t("system.files")}</div>
</div>
<div class="health-item">
<div class="lbl">memory <span class="pill ok">● ok</span></div>
<div class="lbl">${t("system.memory")} <span class="pill ok">${t("system.ok")}</span></div>
<div class="v">${fmtBytes(h.memory.totalBytes)}</div>
<div class="meta">${fmtNum(h.memory.fileCount)} files</div>
<div class="meta">${fmtNum(h.memory.fileCount)} ${t("system.files")}</div>
</div>
<div class="health-item">
<div class="lbl">
semantic index
${t("system.semanticIndex")}
${
h.semantic.exists
? html`<span class="pill ok">● built</span>`
: html`<span class="pill">— none</span>`
? html`<span class="pill ok">${t("system.built")}</span>`
: html`<span class="pill">${t("system.none")}</span>`
}
</div>
<div class="v">${h.semantic.exists ? fmtBytes(h.semantic.totalBytes) : "—"}</div>
<div class="meta">
${h.semantic.exists ? `${fmtNum(h.semantic.fileCount)} files` : "run reasonix index to build"}
${h.semantic.exists ? `${fmtNum(h.semantic.fileCount)} ${t("system.files")}` : t("system.runIndex")}
</div>
</div>
<div class="health-item">
<div class="lbl">usage log <span class="pill ok">● ok</span></div>
<div class="lbl">${t("system.usageLog")} <span class="pill ok">${t("system.ok")}</span></div>
<div class="v">${fmtBytes(h.usageLog.bytes)}</div>
<div class="meta">~/.reasonix/usage.jsonl</div>
</div>
<div class="health-item">
<div class="lbl">
background jobs
${t("system.backgroundJobs")}
${
h.jobs === null
? html`<span class="pill">— no session</span>`
? html`<span class="pill">${t("system.noSession")}</span>`
: html`<span class="pill ok">● ${fmtNum(h.jobs)}</span>`
}
</div>
<div class="v">${h.jobs === null ? "—" : `${fmtNum(h.jobs)} running`}</div>
<div class="meta">${h.jobs === null ? "attach a session to see jobs" : "shell + spawn"}</div>
<div class="v">${h.jobs === null ? "—" : t("system.running", { count: fmtNum(h.jobs) })}</div>
<div class="meta">${h.jobs === null ? t("system.attachHint") : t("system.shellSpawn")}</div>
</div>
</div>
<div class="card" style="padding:0">
<div class="card-h" style="padding:12px 14px 6px">
<span class="title">paths</span>
<span class="title">${t("system.paths")}</span>
</div>
<table class="tbl">
<tbody style="font-size:11.5px">
<tr><td class="dim" style="padding:5px 14px">home</td><td class="path">${h.reasonixHome}</td></tr>
<tr><td class="dim" style="padding:5px 14px">sessions</td><td class="path">${h.sessions.path}</td></tr>
<tr><td class="dim" style="padding:5px 14px">memory</td><td class="path">${h.memory.path}</td></tr>
<tr><td class="dim" style="padding:5px 14px">semantic</td><td class="path">${h.semantic.path}</td></tr>
<tr><td class="dim" style="padding:5px 14px">usage</td><td class="path">${h.usageLog.path}</td></tr>
<tr><td class="dim" style="padding:5px 14px">${t("system.home")}</td><td class="path">${h.reasonixHome}</td></tr>
<tr><td class="dim" style="padding:5px 14px">${t("system.sessionsPath")}</td><td class="path">${h.sessions.path}</td></tr>
<tr><td class="dim" style="padding:5px 14px">${t("system.memoryPath")}</td><td class="path">${h.memory.path}</td></tr>
<tr><td class="dim" style="padding:5px 14px">${t("system.semanticPath")}</td><td class="path">${h.semantic.path}</td></tr>
<tr><td class="dim" style="padding:5px 14px">${t("system.usagePath")}</td><td class="path">${h.usageLog.path}</td></tr>
</tbody>
</table>
</div>
+17 -15
View File
@@ -1,5 +1,6 @@
import { html } from "../lib/html.js";
import { usePoll } from "../lib/use-poll.js";
import { t, useLang } from "../i18n/index.js";
interface ToolEntry {
name: string;
@@ -21,47 +22,48 @@ interface ToolsError {
}
export function ToolsPanel() {
useLang();
const { data, error, loading } = usePoll<ToolsData>("/tools", 4000);
if (loading && !data)
return html`<div class="card" style="color:var(--fg-3)">loading tools…</div>`;
return html`<div class="card" style="color:var(--fg-3)">${t("tools.loading")}</div>`;
const e = error as ToolsError | null;
if (e?.status === 503) {
return html`<div class="card accent-warn">${e.body?.error ?? "live tools view requires an attached session"}</div>`;
return html`<div class="card accent-warn">${e.body?.error ?? t("common.loadingFailed", { name: "tools", error: "" })}</div>`;
}
if (e) return html`<div class="card accent-err">tools failed: ${e.message}</div>`;
if (e) return html`<div class="card accent-err">${t("common.loadingFailed", { name: "tools", error: e.message })}</div>`;
if (!data) return null;
const t = data;
const d = data;
return html`
<div style="display:flex;flex-direction:column;gap:14px">
<div class="chips">
<span class="chip-f active">all <span class="ct">${t.total}</span></span>
${t.planMode ? html`<span class="chip-f" style="border-color:var(--c-warn);color:var(--c-warn)">plan mode — writes gated</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>
${
t.tools.length === 0
? html`<div class="card" style="color:var(--fg-3)">No tools registered.</div>`
d.tools.length === 0
? html`<div class="card" style="color:var(--fg-3)">${t("tools.noTools")}</div>`
: html`
<div class="card" style="padding:0;overflow:hidden">
<table class="tbl">
<thead>
<tr>
<th>tool</th>
<th>flags</th>
<th>description</th>
<th>${t("tools.colTool")}</th>
<th>${t("tools.colFlags")}</th>
<th>${t("tools.colDesc")}</th>
</tr>
</thead>
<tbody>
${t.tools.map(
${d.tools.map(
(tool) => html`
<tr>
<td><code class="mono">${tool.name}</code></td>
<td>
${tool.readOnly
? html`<span class="pill ok">read-only</span>`
: html`<span class="pill acc">write</span>`}
${tool.flattened ? html` <span class="pill">flat</span>` : null}
? html`<span class="pill ok">${t("tools.readOnly")}</span>`
: html`<span class="pill acc">${t("tools.write")}</span>`}
${tool.flattened ? html` <span class="pill">${t("tools.flat")}</span>` : null}
</td>
<td class="dim">${tool.description ?? ""}</td>
</tr>
+21 -20
View File
@@ -3,6 +3,7 @@ import { api } from "../lib/api.js";
import { fmtNum, fmtPct, 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";
type UPlotInstance = {
destroy(): void;
@@ -132,6 +133,7 @@ interface UsageSummary {
}
export function UsagePanel() {
useLang();
const { data: summary, error, loading } = usePoll<UsageSummary>("/usage", 5000);
const [series, setSeries] = useState<UsageDay[] | null>(null);
@@ -145,7 +147,7 @@ export function UsagePanel() {
/* keep null; chart hides */
}
})();
const t = setInterval(async () => {
const interval = setInterval(async () => {
try {
const s = await api<{ days?: UsageDay[] }>("/usage/series");
if (!cancelled) setSeries(s.days ?? []);
@@ -155,13 +157,13 @@ export function UsagePanel() {
}, 30_000);
return () => {
cancelled = true;
clearInterval(t);
clearInterval(interval);
};
}, []);
if (loading && !summary)
return html`<div class="card" style="color:var(--fg-3)">loading usage…</div>`;
if (error) return html`<div class="card accent-err">usage failed: ${error.message}</div>`;
return html`<div class="card" style="color:var(--fg-3)">${t("usage.loading")}</div>`;
if (error) return html`<div class="card accent-err">${t("common.loadingFailed", { name: "usage", error: error.message })}</div>`;
if (!summary) return null;
const u = summary;
@@ -172,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">${u.recordCount.toLocaleString()} records</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>
${
@@ -181,8 +183,8 @@ export function UsagePanel() {
? html`
<div class="card" style="padding:18px">
<div class="card-h">
<span class="title">Daily usage</span>
<span class="meta">cost · cache saved · turns</span>
<span class="title">${t("usage.dailyUsage")}</span>
<span class="meta">${t("usage.dailyMeta")}</span>
</div>
<${UsageChart} days=${series} />
</div>
@@ -193,22 +195,21 @@ export function UsagePanel() {
${
u.recordCount === 0
? html`<div class="card" style="color:var(--fg-3);margin-top:8px">
No usage data yet — run a turn in <code class="mono">reasonix chat</code> /
<code class="mono">code</code> / <code class="mono">run</code> and refresh.
${t("usage.noData")}
</div>`
: html`
${sectionH3("Rolling windows")}
${sectionH3(t("usage.windows"))}
<div class="card" style="padding:0;overflow:hidden">
<table class="tbl">
<thead>
<tr>
<th></th>
<th>turns</th>
<th>cache hit</th>
<th>cost (USD)</th>
<th>cache saved</th>
<th>vs Claude</th>
<th>saved</th>
<th>${t("usage.colTurns")}</th>
<th>${t("usage.colCacheHit")}</th>
<th>${t("usage.colCost")}</th>
<th>${t("usage.colCacheSaved")}</th>
<th>${t("usage.colVsClaude")}</th>
<th>${t("usage.colSaved")}</th>
</tr>
</thead>
<tbody>
@@ -240,13 +241,13 @@ export function UsagePanel() {
${
u.byModel.length > 0
? html`
${sectionH3("Most used models")}
${sectionH3(t("usage.mostUsed"))}
<div class="card" style="padding:0;overflow:hidden">
<table class="tbl">
<thead>
<tr>
<th>model</th>
<th>turns</th>
<th>${t("usage.colModel")}</th>
<th>${t("usage.colTurns")}</th>
</tr>
</thead>
<tbody>
+37 -38
View File
@@ -43,27 +43,30 @@ 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.
### Pillar 2 — R1 Thought Harvesting *(opt-in)*
#### Parallel tool dispatch
**Problem.** R1 / V4-thinking emits extensive `reasoning_content`. DeepSeek's
own docs recommend *not* feeding it back to the next turn. Most frameworks
display it to the user and discard. The planning signal inside is lost.
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.
**Solution.** A two-stage process:
| Env var | Default | Effect |
|---|---|---|
| `REASONIX_PARALLEL_MAX` | `3` (hard cap `16`) | Max chunk size. |
| `REASONIX_TOOL_DISPATCH=serial` | unset | Forces serial dispatch — escape hatch. |
```
R1 output → Harvester (v4-flash, thinking off) → TypedPlanState
├─ subgoals: string[]
├─ hypotheses: string[]
├─ uncertainties: string[]
└─ rejectedPaths: string[]
```
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.
The harvester is a cheap flash call with a strict JSON schema. Output is
validated at runtime. **Not enabled in any preset** (see Pillar 4) — the
additional round-trip rarely pays back, so it's `/harvest on` opt-in.
### Pillar 3 — Tool-Call Repair
### Pillar 2 — Tool-Call Repair
**Problem.** Empirical DeepSeek failure modes:
- Tool-call JSON emitted inside `<think>`, missing from the final message.
@@ -83,7 +86,7 @@ additional round-trip rarely pays back, so it's `/harvest on` opt-in.
4. **`storm`** — identical `(tool, args)` tuple within a sliding window →
suppress the call, inject a reflection turn.
### Pillar 4 — Cost Control *(v0.6)*
### Pillar 3 — Cost Control *(v0.6)*
**Problem.** Coding agents that default to the frontier model (v4-pro, ~12×
flash cost) and accumulate full tool results in context are $150-$250/month
@@ -95,17 +98,13 @@ tuning in the common case:
#### 4.1 Tiered defaults (flash-first)
The three presets now trade only **model tier** and **reasoning effort**:
The three presets trade **model tier** and **reasoning effort**:
| Preset | Model | Effort | Harvest | Branch | Cost |
|---|---|---|---|---|---:|
| `fast` | `v4-flash` | `high` | off | 1 | 1× |
| `smart` (default) | `v4-flash` | `max` | off | 1 | ~1.5× |
| `max` | `v4-pro` | `max` | off | 1 | ~12× |
**Branching and harvest are never in a preset.** Both multiply cost and
rarely pay back; `/branch N` and `/harvest on` are pure opt-ins. A user can
run for weeks without ever touching them.
| Preset | Model | Effort | Cost |
|---|---|---|---:|
| `flash` | `v4-flash` | `max` | 1× |
| `auto` (default) | `v4-flash` → `v4-pro` on hard turns | `max` | 1–3× |
| `pro` | `v4-pro` | `max` | ~12× |
All auxiliary calls — `forceSummaryAfterIterLimit`, subagent spawns,
truncation repair retries — hard-code `v4-flash + effort=high` regardless
@@ -153,9 +152,8 @@ Per-turn and session cost are colored in the StatsPanel:
```
src/
├── client.ts # DeepSeek client (fetch + SSE)
├── loop.ts # Pillar 1 + 4 — CacheFirstLoop
├── harvest.ts # Pillar 2 — flash-backed plan-state extraction
├── repair/ # Pillar 3 pipeline
├── loop.ts # Pillar 1 + 3 — CacheFirstLoop
├── repair/ # Pillar 2 pipeline
│ ├── index.ts
│ ├── scavenge.ts
│ ├── flatten.ts
@@ -172,7 +170,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
@@ -220,23 +218,24 @@ means editing one handler file and one registry line.
## Design evolution
- **v0.0.x** — Pillar 1 end-to-end, Pillar 3 complete, Ink TUI scaffold.
- **v0.0.x** — Pillar 1 end-to-end, repair pipeline complete, Ink TUI scaffold.
- **v0.1** — τ-bench numbers published, streaming polish, transcript replay.
- **v0.2** — Self-consistency / branch-budget sampling driven by plan state.
- **v0.3** — MCP client (stdio + SSE), session persistence.
- **v0.4.x** — `reasonix code` with SEARCH/REPLACE edits, review/auto
gate, background jobs, hooks.
- **v0.5.x** — V4 model support, skills, memory, subagents, actionable
error messages.
- **v0.6** *(current)* —
- **Pillar 4 cost control** (flash-first defaults, auto-compaction,
`/pro` one-shot, failure-triggered escalation, cost badges).
- **v0.6** —
- **Cost control** (flash-first defaults, auto-compaction, `/pro` one-shot,
failure-triggered escalation, cost badges).
- `deepseek-chat` / `deepseek-reasoner` scheduled for deprecation —
all user-facing surfaces updated to `v4-flash` / `v4-pro`.
- `branch` + `harvest` removed from every preset; manual opt-in only.
- Shared prompt fragments (`TUI_FORMATTING_RULES`, `NEGATIVE_CLAIM_RULE`).
- UI refactor: App.tsx split into 6 hooks/components, slash.ts split
into 13 per-topic modules.
- **v0.31** *(current)* — `branch` + `harvest` features removed entirely
(the parallel-sample selector and Pillar 2 plan-state extractor); both
rarely paid for themselves and bloated the slash surface.
## Explicit non-goals
+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;
+270 -156
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,29 +386,98 @@ 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>
<section class="cli">
<section id="cli" class="cli">
<div class="container">
<h2 class="section-title" data-i18n="cli.title">CLI at a glance</h2>
<pre class="code"><code>npx reasonix code [path] <span class="hash"># <span data-i18n="cli.code">coding mode scoped to path</span></span>
npx reasonix <span class="hash"># <span data-i18n="cli.chat">chat (uses saved config)</span></span>
npx reasonix setup <span class="hash"># <span data-i18n="cli.setup">reconfigure the wizard</span></span>
npx reasonix 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 {
+3160 -296
View File
File diff suppressed because it is too large. Load diff
+12 -6
View File
@@ -1,6 +1,6 @@
{
"name": "reasonix",
"version": "0.23.1",
"version": "0.34.0",
"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,23 +72,27 @@
"commander": "^12.1.0",
"eventsource-parser": "^3.0.0",
"ignore": "^7.0.5",
"ink": "^5.1.0",
"ink-spinner": "^5.0.0",
"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": "^19.2.6",
"string-width": "^7.2.0",
"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": "^19.2.14",
"@vitest/coverage-v8": "^2.1.5",
"esbuild": "^0.21.5",
"highlight.js": "^11.10.0",
"htm": "^3.1.1",
"marked": "^12.0.2",
"ink-testing-library": "^4.0.0",
"marked": "^15.0.12",
"preact": "^10.22.0",
"simple-git-hooks": "^2.13.1",
"tsup": "^8.3.5",
+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);
});
+153
View File
@@ -0,0 +1,153 @@
/** @url mentions — async sibling of @path. Fetches each URL once and inlines under "Referenced URLs". */
/** Trailing punctuation stripped separately — URLs legitimately contain `,` `.` `)` in query strings. */
export const AT_URL_PATTERN = /(?<=^|\s)@(https?:\/\/\S+)/g;
/** Default cap on inlined URL body (chars). */
export const DEFAULT_AT_URL_MAX_CHARS = 32_000;
export interface AtUrlExpansion {
/** The raw `@url` token as it appeared in the text. */
token: string;
/** Absolute URL (after trailing-punctuation strip). */
url: string;
/** True if content was inlined. False = skipped (reason in `skip`). */
ok: boolean;
/** Page title when extractable from `<title>`. */
title?: string;
/** Char count of the (post-truncation) inlined body. */
chars?: number;
/** True iff the original page exceeded `maxChars` and was clipped. */
truncated?: boolean;
/** Why the mention was skipped — set when ok=false. */
skip?: "fetch-error" | "non-text" | "timeout" | "blocked";
/** Free-form error message attached to skip outcomes. */
error?: string;
}
export interface AtUrlOptions {
/** Max chars of inlined body per URL. */
maxChars?: number;
/** Per-URL fetch timeout in ms. */
timeoutMs?: number;
fetcher?: (
url: string,
opts: { maxChars?: number; timeoutMs?: number; signal?: AbortSignal },
) => Promise<{ url: string; title?: string; text: string; truncated: boolean }>;
cache?: Map<string, AtUrlExpansion & { body?: string }>;
/** Forward Esc/abort to the fetcher. */
signal?: AbortSignal;
}
export async function expandAtUrls(
text: string,
opts: AtUrlOptions = {},
): Promise<{ text: string; expansions: AtUrlExpansion[] }> {
const maxChars = opts.maxChars ?? DEFAULT_AT_URL_MAX_CHARS;
const fetcher = opts.fetcher;
if (!fetcher) {
throw new Error("expandAtUrls: fetcher option is required (wire src/tools/web.ts:webFetch)");
}
const seen = new Map<string, AtUrlExpansion>();
const bodies = new Map<string, string>();
const order: string[] = [];
for (const match of text.matchAll(AT_URL_PATTERN)) {
const rawUrl = match[1] ?? "";
const url = stripUrlTail(rawUrl);
if (!url) continue;
if (seen.has(url)) continue;
const cached = opts.cache?.get(url);
if (cached) {
seen.set(url, cached);
if (cached.body) bodies.set(url, cached.body);
order.push(url);
continue;
}
let expansion: AtUrlExpansion;
let body = "";
try {
const page = await fetcher(url, {
maxChars,
timeoutMs: opts.timeoutMs,
signal: opts.signal,
});
body = page.text;
expansion = {
token: `@${url}`,
url,
ok: true,
title: page.title,
chars: body.length,
truncated: page.truncated,
};
} catch (err) {
const message = (err as Error).message ?? String(err);
let skip: AtUrlExpansion["skip"] = "fetch-error";
if (/aborted|timeout/i.test(message)) skip = "timeout";
else if (/40\d|forbidden|access denied|captcha/i.test(message)) skip = "blocked";
expansion = {
token: `@${url}`,
url,
ok: false,
skip,
error: message,
};
}
seen.set(url, expansion);
if (body) bodies.set(url, body);
if (opts.cache) opts.cache.set(url, { ...expansion, body });
order.push(url);
}
if (seen.size === 0) return { text, expansions: [] };
const expansions = order.map((u) => seen.get(u)!).filter(Boolean);
const blocks: string[] = [];
for (const ex of expansions) {
if (ex.ok) {
const titleAttr = ex.title ? ` title="${escapeAttr(ex.title)}"` : "";
const truncTag = ex.truncated ? ' truncated="true"' : "";
const body = bodies.get(ex.url) ?? "";
blocks.push(`<url href="${ex.url}"${titleAttr}${truncTag}>\n${body}\n</url>`);
} else {
const reasonAttr = ex.skip ?? "fetch-error";
blocks.push(`<url href="${ex.url}" skipped="${reasonAttr}" />`);
}
}
const augmented = `${text}\n\n[Referenced URLs]\n${blocks.join("\n\n")}`;
return { text: augmented, expansions };
}
/** Only strips `.,;:!?` and unmatched close-brackets — internal path / query punctuation preserved. */
export function stripUrlTail(raw: string): string {
let s = raw;
while (s.length > 0) {
const last = s[s.length - 1]!;
if (".,;:!?".includes(last)) {
s = s.slice(0, -1);
continue;
}
if (")]}>".includes(last)) {
const open = ({ ")": "(", "]": "[", "}": "{", ">": "<" } as const)[
last as ")" | "]" | "}" | ">"
];
if (!s.includes(open)) {
s = s.slice(0, -1);
continue;
}
}
break;
}
return s;
}
function escapeAttr(s: string): string {
return s
.replace(/"/g, "&quot;")
.replace(/[\r\n]+/g, " ")
.trim();
}
+323 -210
View File
@@ -13,6 +13,9 @@ import {
/** Caps match tool-result dispatch truncation (0.5.2). */
export const DEFAULT_AT_MENTION_MAX_BYTES = 64 * 1024;
/** Cap on entries returned for a `@<dir>` listing. ~200 paths × ~50 chars ≈ 10 KB — fits inside DEFAULT_AT_MENTION_MAX_BYTES with room for the rest of the prompt. */
export const DEFAULT_AT_DIR_MAX_ENTRIES = 200;
/** Universally-uninteresting build / VCS dirs. Framework-specific dirs (Pods, target, …) live in .gitignore. */
export const DEFAULT_PICKER_IGNORE_DIRS: readonly string[] = [
"node_modules",
@@ -91,6 +94,19 @@ export function listFilesWithStatsSync(root: string, opts: ListFilesOptions = {}
/* stat failed (permission / EAGAIN) — keep the entry with mtime=0 */
}
out.push({ path: relPath, mtimeMs });
} else if (ent.isSymbolicLink()) {
// Dirent.isFile() returns false for symlinks even when they point at
// regular files — stat the target to recover them. Symlinks-to-dirs
// are not followed (cycle risk).
let target: ReturnType<typeof statSync> | null = null;
try {
target = statSync(absPath);
} catch {
continue;
}
if (!target.isFile()) continue;
if (ignoredByLayers(effectiveLayers, absPath, false)) continue;
out.push({ path: relPath, mtimeMs: target.mtimeMs });
}
}
};
@@ -104,18 +120,65 @@ export async function listFilesWithStatsAsync(
root: string,
opts: ListFilesOptions = {},
): Promise<FileWithStats[]> {
const maxResults = Math.max(1, opts.maxResults ?? 2000);
const ignoreDirs = new Set(opts.ignoreDirs ?? DEFAULT_PICKER_IGNORE_DIRS);
const rootAbs = resolve(root);
const respectGi = opts.respectGitignore !== false;
const out: FileWithStats[] = [];
const maxResults = Math.max(1, opts.maxResults ?? 2000);
await walkFilesStream(root, {
...opts,
onEntry: (e) => {
out.push(e);
return out.length < maxResults;
},
});
return out;
}
export interface StreamWalkOptions {
ignoreDirs?: readonly string[];
respectGitignore?: boolean;
signal?: AbortSignal;
/** Called per file entry. Return false to halt the walk. */
onEntry: (entry: FileWithStats) => boolean | undefined;
/** Called periodically with the running file-count. */
onProgress?: (scanned: number) => void;
/** Default 100ms — minimum gap between onProgress calls. */
progressIntervalMs?: number;
}
/** Cancelable, streaming walker. Drives `listFilesWithStatsAsync` and the picker's search-mode walk. */
export async function walkFilesStream(
root: string,
opts: StreamWalkOptions,
): Promise<{ scanned: number; cancelled: boolean }> {
const ignoreDirs = new Set(opts.ignoreDirs ?? DEFAULT_PICKER_IGNORE_DIRS);
const respectGi = opts.respectGitignore !== false;
const rootAbs = resolve(root);
const progressGap = Math.max(0, opts.progressIntervalMs ?? 100);
let scanned = 0;
let halted = false;
let lastProgress = 0;
const reportProgress = (force: boolean) => {
if (!opts.onProgress) return;
const now = Date.now();
if (force || now - lastProgress >= progressGap) {
lastProgress = now;
opts.onProgress(scanned);
}
};
const emit = (entry: FileWithStats) => {
scanned++;
if (halted) return;
if (opts.onEntry(entry) === false) halted = true;
reportProgress(false);
};
const walk = async (
dirAbs: string,
dirRel: string,
layers: readonly GitignoreLayer[],
): Promise<void> => {
if (out.length >= maxResults) return;
if (halted || opts.signal?.aborted) return;
let effectiveLayers = layers;
if (respectGi) {
const ig = await loadGitignoreAt(dirAbs);
@@ -128,67 +191,172 @@ export async function listFilesWithStatsAsync(
return;
}
entries.sort((a, b) => a.name.localeCompare(b.name));
// Stats batched per directory to amortize syscall overhead. Recursion stays
// sequential so the merged DFS order matches the sync walker's contract.
const fileEnts: Dirent[] = [];
for (const ent of entries) {
if (out.length >= maxResults) break;
const relPath = dirRel ? `${dirRel}/${ent.name}` : ent.name;
if (halted || opts.signal?.aborted) break;
const absPath = join(dirAbs, ent.name);
if (ent.isDirectory()) {
if (ent.name.startsWith(".") || ignoreDirs.has(ent.name)) continue;
if (ignoredByLayers(effectiveLayers, absPath, true)) continue;
// Drain pending file stats from THIS directory before
// descending so the output order stays DFS-alphabetical.
if (fileEnts.length > 0) {
await statBatch(fileEnts, dirAbs, dirRel, out, maxResults, effectiveLayers);
await flushFiles(fileEnts, dirAbs, dirRel, effectiveLayers, emit);
fileEnts.length = 0;
if (out.length >= maxResults) return;
if (halted || opts.signal?.aborted) return;
}
await walk(absPath, relPath, effectiveLayers);
} else if (ent.isFile()) {
await walk(absPath, dirRel ? `${dirRel}/${ent.name}` : ent.name, effectiveLayers);
} else if (ent.isFile() || ent.isSymbolicLink()) {
fileEnts.push(ent);
}
}
if (fileEnts.length > 0 && out.length < maxResults) {
await statBatch(fileEnts, dirAbs, dirRel, out, maxResults, effectiveLayers);
if (fileEnts.length > 0 && !halted && !opts.signal?.aborted) {
await flushFiles(fileEnts, dirAbs, dirRel, effectiveLayers, emit);
}
};
await walk(rootAbs, "", []);
return out;
reportProgress(true);
return { scanned, cancelled: !!opts.signal?.aborted };
}
async function statBatch(
async function flushFiles(
ents: readonly Dirent[],
dirAbs: string,
dirRel: string,
out: FileWithStats[],
maxResults: number,
layers: readonly GitignoreLayer[],
emit: (e: FileWithStats) => void,
): Promise<void> {
const accepted: Dirent[] = [];
for (const e of ents) {
if (out.length + accepted.length >= maxResults) break;
if (ignoredByLayers(layers, join(dirAbs, e.name), false)) continue;
accepted.push(e);
}
const accepted = ents.filter((e) => !ignoredByLayers(layers, join(dirAbs, e.name), false));
const stats = await Promise.all(
accepted.map((e) =>
stat(join(dirAbs, e.name))
.then((s) => s.mtimeMs)
.catch(() => 0),
.then((s) => ({ mtimeMs: s.mtimeMs, isFile: s.isFile() }))
.catch(() => null),
),
);
for (let i = 0; i < accepted.length; i++) {
const ent = accepted[i]!;
out.push({
const s = stats[i];
if (ent.isSymbolicLink() && (!s || !s.isFile)) continue;
emit({
path: dirRel ? `${dirRel}/${ent.name}` : ent.name,
mtimeMs: stats[i] ?? 0,
mtimeMs: s?.mtimeMs ?? 0,
});
}
}
export interface DirEntry {
name: string;
/** Relative-to-root path (forward slashes). For dirs, no trailing slash. */
path: string;
isDir: boolean;
/** 0 for directories (no stat), real mtime for files. */
mtimeMs: number;
}
export interface ListDirectoryOptions {
ignoreDirs?: readonly string[];
respectGitignore?: boolean;
}
/** One-level browse for the @-picker. Folders first then files, alpha within each group. Resolves outside-root to []. */
export async function listDirectory(
root: string,
relDir: string,
opts: ListDirectoryOptions = {},
): Promise<DirEntry[]> {
const ignoreDirs = new Set(opts.ignoreDirs ?? DEFAULT_PICKER_IGNORE_DIRS);
const respectGi = opts.respectGitignore !== false;
const rootAbs = resolve(root);
const dirAbs = resolve(rootAbs, relDir);
const rel = relative(rootAbs, dirAbs);
if (rel.startsWith("..") || isAbsolute(rel)) return [];
const layers: GitignoreLayer[] = [];
if (respectGi) {
const segs = rel ? rel.split(/[\\/]/) : [];
let cursor = rootAbs;
const ig = await loadGitignoreAt(cursor);
if (ig) layers.push({ dirAbs: cursor, ig });
for (const seg of segs) {
cursor = join(cursor, seg);
const igSeg = await loadGitignoreAt(cursor);
if (igSeg) layers.push({ dirAbs: cursor, ig: igSeg });
}
}
let raw: Dirent[];
try {
raw = await readdir(dirAbs, { withFileTypes: true });
} catch {
return [];
}
const dirRel = rel.split(/[\\/]/).join("/");
const dirs: DirEntry[] = [];
const files: Dirent[] = [];
for (const ent of raw) {
const absPath = join(dirAbs, ent.name);
if (ent.isDirectory()) {
if (ent.name.startsWith(".") || ignoreDirs.has(ent.name)) continue;
if (ignoredByLayers(layers, absPath, true)) continue;
dirs.push({
name: ent.name,
path: dirRel ? `${dirRel}/${ent.name}` : ent.name,
isDir: true,
mtimeMs: 0,
});
} else if (ent.isFile() || ent.isSymbolicLink()) {
if (ignoredByLayers(layers, absPath, false)) continue;
files.push(ent);
}
}
const stats = await Promise.all(
files.map((e) =>
stat(join(dirAbs, e.name))
.then((s) => ({ mtimeMs: s.mtimeMs, isFile: s.isFile() }))
.catch(() => null),
),
);
const fileEntries: DirEntry[] = [];
for (let i = 0; i < files.length; i++) {
const ent = files[i]!;
const s = stats[i];
if (ent.isSymbolicLink() && (!s || !s.isFile)) continue;
fileEntries.push({
name: ent.name,
path: dirRel ? `${dirRel}/${ent.name}` : ent.name,
isDir: false,
mtimeMs: s?.mtimeMs ?? 0,
});
}
dirs.sort((a, b) => a.name.localeCompare(b.name));
fileEntries.sort((a, b) => a.name.localeCompare(b.name));
return [...dirs, ...fileEntries];
}
export interface ParsedAtQuery {
/** Directory portion (rel from root, no trailing slash). Empty = root. */
dir: string;
/** Filter portion — chars after the last slash. Empty if query ended in `/`. */
filter: string;
/** True if the query ended in `/` — caller knows to browse `dir`. */
trailingSlash: boolean;
}
/** Split `src/auth/log` → `{dir: "src/auth", filter: "log"}`; trailing slash sets `trailingSlash` and clears filter. */
export function parseAtQuery(query: string): ParsedAtQuery {
const normalized = query.replace(/\\/g, "/");
const trailingSlash = normalized.endsWith("/");
const trimmed = trailingSlash ? normalized.slice(0, -1) : normalized;
const lastSlash = trimmed.lastIndexOf("/");
if (trailingSlash) return { dir: trimmed, filter: "", trailingSlash: true };
if (lastSlash < 0) return { dir: "", filter: trimmed, trailingSlash: false };
return {
dir: trimmed.slice(0, lastSlash),
filter: trimmed.slice(lastSlash + 1),
trailingSlash: false,
};
}
/** Trailing-token only, anchored at end-of-input — distinct from `AT_MENTION_PATTERN` which scans all. */
export const AT_PICKER_PREFIX = /(?:^|\s)@([a-zA-Z0-9_./\\-]*)$/;
@@ -251,15 +419,25 @@ export function rankPickerCandidates(
for (const e of entries) {
const lower = e.path.toLowerCase();
const hit = lower.indexOf(needle);
if (hit < 0) continue;
const slash = lower.lastIndexOf("/");
const base = slash >= 0 ? lower.slice(slash + 1) : lower;
let score = 2;
if (base.startsWith(needle)) score = 0;
else if (lower.startsWith(needle)) score = 1;
if (hit >= 0) {
const slash = lower.lastIndexOf("/");
const base = slash >= 0 ? lower.slice(slash + 1) : lower;
let cls = 2;
if (base.startsWith(needle)) cls = 0;
else if (lower.startsWith(needle)) cls = 1;
scored.push({
path: e.path,
score: cls * 10_000 + Math.min(hit, 9999),
mtimeMs: e.mtimeMs,
recent: recent.has(e.path),
});
continue;
}
const fuzzy = fuzzySubseqScore(needle, lower);
if (fuzzy === null) continue;
scored.push({
path: e.path,
score: score * 10_000 + hit,
score: 30_000 + fuzzy,
mtimeMs: e.mtimeMs,
recent: recent.has(e.path),
});
@@ -273,6 +451,29 @@ export function rankPickerCandidates(
return scored.slice(0, limit).map((s) => s.path);
}
function fuzzySubseqScore(needle: string, target: string): number | null {
if (needle.length === 0) return 0;
const slashIdx = target.lastIndexOf("/");
const basenameStart = slashIdx >= 0 ? slashIdx + 1 : 0;
let qi = 0;
let lastMatchIdx = -2;
let consecutive = 0;
let basenameMatches = 0;
let totalGap = 0;
for (let ti = 0; ti < target.length && qi < needle.length; ti++) {
if (target[ti] !== needle[qi]) continue;
if (ti === lastMatchIdx + 1) consecutive++;
else if (lastMatchIdx >= 0) totalGap += ti - lastMatchIdx - 1;
if (ti >= basenameStart) basenameMatches++;
lastMatchIdx = ti;
qi++;
}
if (qi < needle.length) return null;
const quality = Math.max(0, totalGap - consecutive * 10 - basenameMatches * 5);
const lengthPenalty = Math.floor(target.length / 4);
return quality + lengthPenalty;
}
/** Word-boundary anchor rejects `@` embedded in emails / social handles; trailing `.` stripped before lookup. */
export const AT_MENTION_PATTERN = /(?<=^|\s)@([a-zA-Z0-9_./\\-]+)/g;
@@ -283,8 +484,14 @@ export interface AtMentionExpansion {
path: string;
/** True if the content was inlined. False = skipped (reason in `skip`). */
ok: boolean;
/** Bytes read (only for ok=true). */
/** Bytes read (only for ok=true and isDirectory=false). */
bytes?: number;
/** True when the mention resolved to a directory (ok=true). Block uses `<directory>` instead of `<file>`. */
isDirectory?: boolean;
/** Number of files listed when isDirectory=true. */
entries?: number;
/** True iff the directory listing was clipped at maxDirEntries. */
truncated?: boolean;
/** Why the mention was skipped. Set when ok=false. */
skip?: "missing" | "not-file" | "too-large" | "escape" | "read-error";
}
@@ -292,9 +499,19 @@ export interface AtMentionExpansion {
export interface AtMentionOptions {
/** Max file size in bytes before a mention is skipped. */
maxBytes?: number;
/** Cap on entries returned for a `@<dir>` listing. Default {@link DEFAULT_AT_DIR_MAX_ENTRIES}. */
maxDirEntries?: number;
fs?: {
exists: (path: string) => boolean;
isFile: (path: string) => boolean;
/** Optional — when omitted, directories are skipped as `not-file`. */
isDir?: (path: string) => boolean;
/** Optional — receives the directory's absolute path and the project root, returns relative paths and a truncated flag. */
listDir?: (
dirAbs: string,
root: string,
max: number,
) => { files: string[]; truncated: boolean };
size: (path: string) => number;
read: (path: string) => string;
};
@@ -306,22 +523,28 @@ export function expandAtMentions(
opts: AtMentionOptions = {},
): { text: string; expansions: AtMentionExpansion[] } {
const maxBytes = opts.maxBytes ?? DEFAULT_AT_MENTION_MAX_BYTES;
const maxDirEntries = Math.max(1, opts.maxDirEntries ?? DEFAULT_AT_DIR_MAX_ENTRIES);
const fs = opts.fs ?? defaultFs;
const root = resolve(rootDir);
// De-dupe by token so `@file.ts` referenced twice inlines once.
const seen = new Map<string, AtMentionExpansion>();
const expansions: AtMentionExpansion[] = [];
const dirListings = new Map<string, string[]>();
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);
// Strip a single trailing slash so `@docs/` and `@docs` resolve identically.
if (cleaned.endsWith("/") || cleaned.endsWith("\\")) cleaned = cleaned.slice(0, -1);
if (!cleaned) continue;
const token = `@${cleaned}`;
if (seen.has(token)) continue;
const expansion = resolveMention(cleaned, root, maxBytes, fs);
const expansion = resolveMention(cleaned, root, maxBytes, maxDirEntries, fs, dirListings);
seen.set(token, expansion);
expansions.push(expansion);
}
@@ -333,7 +556,14 @@ export function expandAtMentions(
// both what's here and what's missing.
const blocks: string[] = [];
for (const ex of expansions) {
if (ex.ok) {
if (ex.ok && ex.isDirectory) {
const files = dirListings.get(ex.path) ?? [];
const truncAttr = ex.truncated ? ' truncated="true"' : "";
const body = files.length > 0 ? `\n${files.join("\n")}\n` : "\n";
blocks.push(
`<directory path="${ex.path}" entries="${ex.entries ?? files.length}"${truncAttr}>${body}</directory>`,
);
} else if (ex.ok) {
const content = readSafe(root, ex.path, fs);
blocks.push(`<file path="${ex.path}">\n${content}\n</file>`);
} else {
@@ -348,7 +578,9 @@ function resolveMention(
rawPath: string,
root: string,
maxBytes: number,
maxDirEntries: number,
fs: NonNullable<AtMentionOptions["fs"]>,
dirListings: Map<string, string[]>,
): AtMentionExpansion {
// Reject absolute paths — `@/etc/passwd` should not inline.
if (isAbsolute(rawPath)) {
@@ -363,14 +595,28 @@ function resolveMention(
if (!fs.exists(resolved)) {
return { token: `@${rawPath}`, path: rawPath, ok: false, skip: "missing" };
}
if (!fs.isFile(resolved)) {
return { token: `@${rawPath}`, path: rawPath, ok: false, skip: "not-file" };
if (fs.isFile(resolved)) {
const size = fs.size(resolved);
if (size > maxBytes) {
return { token: `@${rawPath}`, path: rawPath, ok: false, skip: "too-large", bytes: size };
}
return { token: `@${rawPath}`, path: rawPath, ok: true, bytes: size };
}
const size = fs.size(resolved);
if (size > maxBytes) {
return { token: `@${rawPath}`, path: rawPath, ok: false, skip: "too-large", bytes: size };
// Not a file — try the directory branch. listDir is optional; without it,
// fall back to the legacy not-file skip so test fixtures don't break.
if (fs.isDir?.(resolved) && fs.listDir) {
const { files, truncated } = fs.listDir(resolved, root, maxDirEntries);
dirListings.set(rawPath, files);
return {
token: `@${rawPath}`,
path: rawPath,
ok: true,
isDirectory: true,
entries: files.length,
truncated,
};
}
return { token: `@${rawPath}`, path: rawPath, ok: true, bytes: size };
return { token: `@${rawPath}`, path: rawPath, ok: false, skip: "not-file" };
}
function readSafe(root: string, rawPath: string, fs: NonNullable<AtMentionOptions["fs"]>): string {
@@ -391,6 +637,27 @@ const defaultFs: NonNullable<AtMentionOptions["fs"]> = {
return false;
}
},
isDir: (p) => {
try {
return statSync(p).isDirectory();
} catch {
return false;
}
},
listDir: (dirAbs, root, max) => {
// Walk from project root and filter to entries under dirAbs so the
// listing inherits the parent .gitignore layers. Walking dirAbs alone
// would miss the project-root rules above it.
const dirRel = relative(root, dirAbs).split(/[\\/]/).join("/");
const walkCap = Math.max(max * 4, 5000);
const all = listFilesSync(root, { maxResults: walkCap });
const prefix = dirRel ? `${dirRel}/` : "";
const filtered = dirRel ? all.filter((f) => f === dirRel || f.startsWith(prefix)) : all;
return {
files: filtered.slice(0, max),
truncated: filtered.length > max,
};
},
size: (p) => {
try {
return statSync(p).size;
@@ -401,164 +668,10 @@ const defaultFs: NonNullable<AtMentionOptions["fs"]> = {
read: (p) => readFileSync(p, "utf8"),
};
// @url mentions — async sibling of @path. Matches `@http(s)://...` after a
// word boundary, fetches each URL once per session (in-memory cache), and
// appends a "Referenced URLs" block under the prompt the model sees. Uses
// the same web-fetch + HTML-strip pipeline as the model's `web_fetch` tool
// so a `@url` reference and a model-issued fetch produce identical content.
/** Trailing punctuation stripped separately — URLs legitimately contain `,` `.` `)` in query strings. */
export const AT_URL_PATTERN = /(?<=^|\s)@(https?:\/\/\S+)/g;
/** Default cap on inlined URL body (chars). Matches DEFAULT_AT_MENTION_MAX_BYTES order-of-magnitude. */
export const DEFAULT_AT_URL_MAX_CHARS = 32_000;
export interface AtUrlExpansion {
/** The raw `@url` token as it appeared in the text. */
token: string;
/** Absolute URL (after trailing-punctuation strip). */
url: string;
/** True if content was inlined. False = skipped (reason in `skip`). */
ok: boolean;
/** Page title when extractable from `<title>`. */
title?: string;
/** Char count of the (post-truncation) inlined body. */
chars?: number;
/** True iff the original page exceeded `maxChars` and was clipped. */
truncated?: boolean;
/** Why the mention was skipped — set when ok=false. */
skip?: "fetch-error" | "non-text" | "timeout" | "blocked";
/** Free-form error message attached to skip outcomes. */
error?: string;
}
export interface AtUrlOptions {
/** Max chars of inlined body per URL. Default DEFAULT_AT_URL_MAX_CHARS. */
maxChars?: number;
/** Per-URL fetch timeout in ms. */
timeoutMs?: number;
fetcher?: (
url: string,
opts: { maxChars?: number; timeoutMs?: number; signal?: AbortSignal },
) => Promise<{ url: string; title?: string; text: string; truncated: boolean }>;
cache?: Map<string, AtUrlExpansion & { body?: string }>;
/** Forward Esc/abort to the fetcher. */
signal?: AbortSignal;
}
export async function expandAtUrls(
text: string,
opts: AtUrlOptions = {},
): Promise<{ text: string; expansions: AtUrlExpansion[] }> {
const maxChars = opts.maxChars ?? DEFAULT_AT_URL_MAX_CHARS;
const fetcher = opts.fetcher;
if (!fetcher) {
throw new Error("expandAtUrls: fetcher option is required (wire src/tools/web.ts:webFetch)");
}
// De-dupe by URL so the same `@https://x.com` referenced twice fetches once.
const seen = new Map<string, AtUrlExpansion>();
const bodies = new Map<string, string>();
const order: string[] = [];
for (const match of text.matchAll(AT_URL_PATTERN)) {
const rawUrl = match[1] ?? "";
const url = stripUrlTail(rawUrl);
if (!url) continue;
if (seen.has(url)) continue;
const cached = opts.cache?.get(url);
if (cached) {
seen.set(url, cached);
if (cached.body) bodies.set(url, cached.body);
order.push(url);
continue;
}
let expansion: AtUrlExpansion;
let body = "";
try {
const page = await fetcher(url, {
maxChars,
timeoutMs: opts.timeoutMs,
signal: opts.signal,
});
body = page.text;
expansion = {
token: `@${url}`,
url,
ok: true,
title: page.title,
chars: body.length,
truncated: page.truncated,
};
} catch (err) {
const message = (err as Error).message ?? String(err);
// Tag a few common shapes so the UI can hint at causes.
let skip: AtUrlExpansion["skip"] = "fetch-error";
if (/aborted|timeout/i.test(message)) skip = "timeout";
else if (/40\d|forbidden|access denied|captcha/i.test(message)) skip = "blocked";
expansion = {
token: `@${url}`,
url,
ok: false,
skip,
error: message,
};
}
seen.set(url, expansion);
if (body) bodies.set(url, body);
if (opts.cache) opts.cache.set(url, { ...expansion, body });
order.push(url);
}
if (seen.size === 0) return { text, expansions: [] };
const expansions = order.map((u) => seen.get(u)!).filter(Boolean);
const blocks: string[] = [];
for (const ex of expansions) {
if (ex.ok) {
const titleAttr = ex.title ? ` title="${escapeAttr(ex.title)}"` : "";
const truncTag = ex.truncated ? ' truncated="true"' : "";
const body = bodies.get(ex.url) ?? "";
blocks.push(`<url href="${ex.url}"${titleAttr}${truncTag}>\n${body}\n</url>`);
} else {
const reasonAttr = ex.skip ?? "fetch-error";
blocks.push(`<url href="${ex.url}" skipped="${reasonAttr}" />`);
}
}
const augmented = `${text}\n\n[Referenced URLs]\n${blocks.join("\n\n")}`;
return { text: augmented, expansions };
}
/** Only strips `.,;:!?` and unmatched close-brackets — internal path / query punctuation preserved. */
export function stripUrlTail(raw: string): string {
let s = raw;
while (s.length > 0) {
const last = s[s.length - 1]!;
if (".,;:!?".includes(last)) {
s = s.slice(0, -1);
continue;
}
if (")]}>".includes(last)) {
// Only strip if the matching open bracket isn't elsewhere in the
// URL — avoids butchering legitimate `(thing)` query fragments.
const open = ({ ")": "(", "]": "[", "}": "{", ">": "<" } as const)[
last as ")" | "]" | "}" | ">"
];
if (!s.includes(open)) {
s = s.slice(0, -1);
continue;
}
}
break;
}
return s;
}
function escapeAttr(s: string): string {
return s
.replace(/"/g, "&quot;")
.replace(/[\r\n]+/g, " ")
.trim();
}
export {
AT_URL_PATTERN,
DEFAULT_AT_URL_MAX_CHARS,
expandAtUrls,
stripUrlTail,
} from "./at-mentions-url.js";
export type { AtUrlExpansion, AtUrlOptions } from "./at-mentions-url.js";
+287 -127
View File
@@ -1,14 +1,23 @@
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";
import { type McpTransport, StdioTransport } from "../../mcp/stdio.js";
import { StreamableHttpTransport } from "../../mcp/streamable-http.js";
import { buildMcpServerSummary } from "../../mcp/summary.js";
import {
deleteSession,
listSessionsForWorkspace,
@@ -19,9 +28,11 @@ import { ToolRegistry } from "../../tools.js";
import { registerChoiceTool } from "../../tools/choice.js";
import { registerMemoryTools } from "../../tools/memory.js";
import { registerWebTools } from "../../tools/web.js";
import { markPhase } from "../startup-profile.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";
@@ -34,12 +45,225 @@ 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;
transcript?: string;
harvest?: boolean;
branch?: number;
/**
* Soft USD cap on session spend. Undefined → no cap (default).
* The loop warns once at 80% and refuses to start a new turn at
@@ -73,6 +297,8 @@ export interface ChatOptions {
* then falls back to non-tool updates only).
*/
reregisterTools?: (rootDir: string) => void;
/** Async tail of `/cwd` — re-probe the new dir for a semantic index. */
reBootstrapSemantic?: (rootDir: string) => Promise<{ enabled: boolean }>;
};
/** Skip the session picker — assume "Resume" (backwards-compatible auto-continue). */
forceResume?: boolean;
@@ -84,6 +310,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 {
@@ -95,6 +328,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({
@@ -104,6 +339,7 @@ function Root({
mcpServers,
progressSink,
showPicker,
mcpRuntime,
...appProps
}: RootProps) {
const [key, setKey] = useState<string | undefined>(initialKey);
@@ -168,13 +404,12 @@ function Root({
model={appProps.model}
system={appProps.system}
transcript={appProps.transcript}
harvest={appProps.harvest}
branch={appProps.branch}
budgetUsd={appProps.budgetUsd}
session={activeSession}
tools={tools}
mcpSpecs={mcpSpecs}
mcpServers={mcpServers}
mcpRuntime={mcpRuntime}
progressSink={progressSink}
codeMode={appProps.codeMode}
noDashboard={appProps.noDashboard}
@@ -185,14 +420,12 @@ function Root({
}
export async function chatCommand(opts: ChatOptions): Promise<void> {
markPhase("chat_command_enter");
loadDotenv();
const initialKey = loadApiKey();
markPhase("config_loaded");
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
@@ -203,118 +436,43 @@ 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";
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 });
const 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({
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.
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 }> = [];
if (requestedSpecs.length > 0) markPhase("mcp_launch");
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 (requestedSpecs.length > 0) {
markPhase(
`mcp_connected_${requestedSpecs.length - failedSpecs.length}_of_${requestedSpecs.length}`,
);
}
if (runtime.size() === 0 && !opts.seedTools) {
tools = undefined;
}
// Preserve configured specs even when startup leaves them unbridged
// so `/mcp` can still surface the configured-but-offline set.
const mcpSpecs = [...requestedSpecs];
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.
@@ -345,34 +503,36 @@ 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.
markPhase("ink_render_call");
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();
}
}
+30 -12
View File
@@ -30,6 +30,8 @@ import { JobRegistry } from "../../tools/jobs.js";
import { registerMemoryTools } from "../../tools/memory.js";
import { registerPlanTool } from "../../tools/plan.js";
import { registerShellTools } from "../../tools/shell.js";
import { registerTodoTool } from "../../tools/todo.js";
import { markPhase } from "../startup-profile.js";
import { chatCommand } from "./chat.js";
export interface CodeOptions {
@@ -45,15 +47,6 @@ export interface CodeOptions {
forceResume?: boolean;
/** Skip the session picker — always wipe prior messages and start fresh. */
forceNew?: boolean;
/**
* Opt into Pillar 2 harvesting (extracts a typed plan state from R1
* reasoning via an extra V3 call). Default OFF in code mode — the
* displayed subgoals/hypotheses/rejectedPaths have no programmatic
* consumer, only `uncertainties.length` feeds branching, and the
* extra V3 call adds ~10-15% per-turn cost. Users who want the
* reasoning surfaced explicitly can pass `--harvest`.
*/
harvest?: boolean;
/**
* Soft USD spend cap. Off by default. Same semantics as `chat`:
* warns at 80%, refuses next turn at 100%. Mid-session adjustable
@@ -66,9 +59,12 @@ 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> {
markPhase("code_command_enter");
const { codeSystemPrompt } = await import("../../code/prompt.js");
const rootDir = resolve(opts.dir ?? process.cwd());
// Per-directory session so switching projects doesn't mix histories.
@@ -113,6 +109,16 @@ export async function codeCommand(opts: CodeOptions = {}): Promise<void> {
// per-project memory store; the global scope is shared across runs.
registerMemoryTools(tools, { projectRoot: root });
};
// Async tail to `registerRootedTools`. Kept separate because the FS /
// shell / memory re-registration above is sync and must happen before
// the next tool dispatch, while semantic-index probing reads disk and
// can race ahead in the background. On `/cwd`, App.tsx fires this
// after the sync swap and surfaces the result via postInfo.
const reBootstrapSemantic = async (root: string): Promise<{ enabled: boolean }> => {
const result = await bootstrapSemanticSearchInCodeMode(tools, root);
if (!result.enabled) tools.unregister("semantic_search");
return result;
};
registerRootedTools(rootDir);
// `submit_plan` is always in the spec list so the prefix cache stays
// stable across plan-mode toggles (Pillar 1). The tool itself is a
@@ -125,6 +131,9 @@ export async function codeCommand(opts: CodeOptions = {}): Promise<void> {
// menu into a submit_plan body. Keeping it always-registered
// preserves the prefix cache across plan-mode toggles.
registerChoiceTool(tools);
// `todo_write` — lightweight in-session task tracker, no approval gate.
// Independent of plan mode (readOnly=true so it stays callable in /plan).
registerTodoTool(tools);
// `run_skill` is intentionally NOT registered here — App.tsx wires it
// up with the subagent runner attached, so `runAs: subagent` skills
// can spawn isolated child loops. Doing it here would mean the App's
@@ -135,7 +144,11 @@ export async function codeCommand(opts: CodeOptions = {}): Promise<void> {
// on-disk index already exists, skips entirely otherwise. Setup
// happens via the explicit `reasonix index` command — never
// by surprise on launch.
const semantic = await bootstrapSemanticSearchInCodeMode(tools, rootDir);
markPhase("semantic_bootstrap_start");
const semantic = await reBootstrapSemantic(rootDir);
markPhase(
semantic.enabled ? "semantic_bootstrap_done_enabled" : "semantic_bootstrap_done_skipped",
);
process.stderr.write(
`▸ reasonix code: rooted at ${rootDir}, session "${session ?? "(ephemeral)"}" · ${tools.size} native tool(s)${
@@ -175,7 +188,6 @@ export async function codeCommand(opts: CodeOptions = {}): Promise<void> {
await chatCommand({
model: opts.model ?? "deepseek-v4-flash",
harvest: opts.harvest ?? false,
budgetUsd: opts.budgetUsd,
system: codeSystemPrompt(rootDir, {
hasSemanticSearch: semantic.enabled,
@@ -185,10 +197,16 @@ export async function codeCommand(opts: CodeOptions = {}): Promise<void> {
transcript: opts.transcript,
session,
seedTools: tools,
codeMode: { rootDir, jobs, reregisterTools: registerRootedTools },
codeMode: {
rootDir,
jobs,
reregisterTools: registerRootedTools,
reBootstrapSemantic,
},
mcp: readConfig().mcp,
forceResume: opts.forceResume,
forceNew: opts.forceNew,
noDashboard: opts.noDashboard,
altScreen: opts.altScreen,
});
}
+63 -43
View File
@@ -1,15 +1,16 @@
/** Plain-text (not Ink) — must work when everything else is broken. fail → exit 1; warn → exit 0. */
import { existsSync, statSync } from "node:fs";
import { existsSync, readFileSync, statSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { join, resolve } from "node:path";
import { DeepSeekClient } from "../../client.js";
import { defaultConfigPath, readConfig } from "../../config.js";
import { defaultConfigPath, readConfig, resolveSemanticEmbeddingConfig } from "../../config.js";
import { loadDotenv } from "../../env.js";
import { loadHooks } from "../../hooks.js";
import { indexExists } from "../../index/semantic/builder.js";
import { checkOllamaStatus } from "../../index/semantic/ollama-launcher.js";
import { listSessions } from "../../memory/session.js";
import { resolveDataPath } from "../../tokenizer.js";
import { VERSION } from "../../version.js";
export type DoctorLevel = "ok" | "warn" | "fail";
@@ -169,32 +170,20 @@ async function checkApiReach(): Promise<Check> {
}
async function checkTokenizer(): Promise<Check> {
// The tokenizer file is the gzipped vocab shipped under data/. We
// resolve relative to the package's dist/ rather than process.cwd()
// — the same logic the runtime uses when loading on first count.
const candidates = [
join(
dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, "$1")),
"..",
"..",
"..",
"data",
"deepseek-tokenizer.json.gz",
),
join(process.cwd(), "data", "deepseek-tokenizer.json.gz"),
];
for (const p of candidates) {
if (existsSync(p)) {
try {
const stat = statSync(p);
return {
label: "tokenizer ",
level: "ok",
detail: `${p} (${fmtBytes(stat.size)})`,
};
} catch {
/* try next */
}
// Reuse the runtime's resolver so the doctor never disagrees with what
// the tokenizer actually loads — three candidates including a global
// npm install probe via createRequire.
const path = resolveDataPath();
if (existsSync(path)) {
try {
const stat = statSync(path);
return {
label: "tokenizer ",
level: "ok",
detail: `${path} (${fmtBytes(stat.size)})`,
};
} catch {
/* fall through to warn */
}
}
return {
@@ -226,7 +215,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 };
@@ -259,9 +248,6 @@ async function checkHooks(projectRoot: string): Promise<Check> {
}
async function checkOllama(projectRoot: string): Promise<Check> {
// Ollama is only meaningful when an index has been built — otherwise
// the daemon being down is just noise. Skip the check entirely on
// projects that don't use semantic search.
let exists = false;
try {
exists = await indexExists(projectRoot);
@@ -270,48 +256,82 @@ async function checkOllama(projectRoot: string): Promise<Check> {
}
if (!exists) {
return {
label: "ollama ",
label: "semantic ",
level: "ok",
detail: "not in use (no semantic index built; `reasonix index` to enable)",
};
}
const meta = readSemanticMeta(projectRoot);
if (meta?.provider === "openai-compat") {
const resolved = resolveSemanticEmbeddingConfig();
if (resolved.provider !== "openai-compat") {
return {
label: "semantic ",
level: "warn",
detail: `index uses openai-compat/${meta.model} but current config resolves to ${resolved.provider}/${resolved.model} — rebuild before searching`,
};
}
return {
label: "semantic ",
level: "ok",
detail: `openai-compat · ${resolved.baseUrl} · model ${resolved.model} · api key configured`,
};
}
try {
const status = await checkOllamaStatus(process.env.REASONIX_EMBED_MODEL ?? "nomic-embed-text");
const model = meta?.model || process.env.REASONIX_EMBED_MODEL || "nomic-embed-text";
const status = await checkOllamaStatus(model);
if (!status.binaryFound) {
return {
label: "ollama ",
label: "semantic ",
level: "warn",
detail: "binary not on PATH — semantic_search will fail; install from https://ollama.com",
detail:
"ollama binary not on PATH — semantic_search will fail; install from https://ollama.com",
};
}
if (!status.daemonRunning) {
return {
label: "ollama ",
label: "semantic ",
level: "warn",
detail: "daemon not running — `ollama serve` (or just call /semantic in TUI to auto-start)",
detail:
"ollama daemon not running — `ollama serve` (or call /semantic in TUI to auto-start)",
};
}
if (!status.modelPulled) {
return {
label: "ollama ",
label: "semantic ",
level: "warn",
detail: `model ${status.modelName} not pulled — \`ollama pull ${status.modelName}\``,
};
}
return {
label: "ollama ",
label: "semantic ",
level: "ok",
detail: `daemon up · model ${status.modelName} ready`,
detail: `ollama daemon up · model ${status.modelName} ready`,
};
} catch (err) {
return {
label: "ollama ",
label: "semantic ",
level: "warn",
detail: `probe failed — ${(err as Error).message}`,
};
}
}
function readSemanticMeta(
projectRoot: string,
): { provider: "ollama" | "openai-compat"; model: string } | null {
try {
const raw = readFileSync(join(projectRoot, ".reasonix", "semantic", "index.meta.json"), "utf8");
const parsed = JSON.parse(raw) as { provider?: string; model?: string };
return {
provider: parsed.provider === "openai-compat" ? "openai-compat" : "ollama",
model: typeof parsed.model === "string" ? parsed.model : "",
};
} catch {
return null;
}
}
async function checkProject(projectRoot: string): Promise<Check> {
// Heuristic: a "real" project has either .git, REASONIX.md, or
// package.json. Lacking all three, `reasonix code` still works but
+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":
+16 -20
View File
@@ -1,34 +1,37 @@
/** `reasonix index` — progress writes go to stderr so stdout stays pipeable. */
import { resolve } from "node:path";
import { loadIndexConfig } from "../../config.js";
import { loadIndexConfig, resolveSemanticEmbeddingConfig } from "../../config.js";
import { buildIndex } from "../../index/semantic/builder.js";
import type { BuildProgress, BuildResult, SkipBuckets } from "../../index/semantic/builder.js";
import { t } from "../../index/semantic/i18n.js";
import { ollamaPreflight } from "../../index/semantic/preflight.js";
import { semanticPreflight } from "../../index/semantic/preflight.js";
export interface IndexCommandOptions {
rebuild?: boolean;
model?: string;
dir?: string;
/** Ollama base URL override. */
ollamaUrl?: string;
/** Skip preflight prompts (yes to all). For scripts that already
* know Ollama is set up. Default false. */
yes?: boolean;
}
export async function indexCommand(opts: IndexCommandOptions = {}): Promise<void> {
const root = resolve(opts.dir ?? process.cwd());
const tty = process.stderr.isTTY === true && process.stdin.isTTY === true;
const model = opts.model ?? process.env.REASONIX_EMBED_MODEL ?? "nomic-embed-text";
const resolved = resolveSemanticEmbeddingConfig();
const embedding =
resolved.provider === "ollama"
? {
...resolved,
model: opts.model ?? resolved.model,
baseUrl: opts.ollamaUrl ?? resolved.baseUrl,
}
: {
...resolved,
model: opts.model ?? resolved.model,
};
// Preflight: detect Ollama state and offer to fix what's missing.
// Runs before chunking so the user doesn't watch a scan finish only
// to hit "daemon not reachable" on the first embed call.
const preflightOk = await ollamaPreflight({
model,
baseUrl: opts.ollamaUrl,
const preflightOk = await semanticPreflight(embedding, {
interactive: tty && !opts.yes,
yesToAll: opts.yes ?? false,
});
@@ -40,9 +43,8 @@ export async function indexCommand(opts: IndexCommandOptions = {}): Promise<void
let result: BuildResult;
try {
result = await buildIndex(root, {
...embedding,
rebuild: opts.rebuild,
model,
baseUrl: opts.ollamaUrl,
indexConfig: loadIndexConfig(),
onProgress: (p) => writer.update(p),
});
@@ -135,7 +137,6 @@ function makeNonTtyWriter(): ProgressWriter {
};
}
/** Spinner ticks on its own setInterval so a hung embedder still shows liveness. */
function makeTtyWriter(): ProgressWriter {
let status = t("progressStarting");
let lastLineLen = 0;
@@ -152,8 +153,6 @@ function makeTtyWriter(): ProgressWriter {
lastLineLen = line.length;
};
// Paint the initial frame immediately so the user sees text on
// line one — don't wait for the first interval tick.
repaint();
const interval = setInterval(repaint, SPINNER_INTERVAL_MS);
@@ -167,9 +166,6 @@ function makeTtyWriter(): ProgressWriter {
const pct = total > 0 ? ((done / total) * 100).toFixed(0) : "0";
status = t("progressEmbed", { done, total, pct });
}
// Repaint immediately on event arrival so the new counter
// shows up before the next interval tick (avoids a 120ms lag
// on each progress update).
repaint();
},
clear() {
+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}`);
}
}
-20
View File
@@ -67,11 +67,6 @@ function printReplay(opts: ReplayOptions): void {
} else if (stats.prefixHashes.length > 1) {
console.log(" (prefix churned — cache-hostile session)");
}
if (stats.harvestedTurns > 0) {
console.log(`harvest (Pillar 2): ${stats.harvestedTurns} turn(s) produced plan state`);
console.log(` subgoals: ${stats.totalSubgoals}`);
console.log(` uncertainties: ${stats.totalUncertainties}`);
}
}
function sliceRecords(records: TranscriptRecord[], opts: ReplayOptions): TranscriptRecord[] {
@@ -98,21 +93,6 @@ function renderRecord(rec: TranscriptRecord): void {
})()
: "";
console.log(`${turn} AGENT:${cost}${cache} ${oneLine(rec.content)}`);
if (rec.planState) {
const ps = rec.planState;
if (ps.subgoals.length)
console.log(` ‹ subgoals (${ps.subgoals.length}): ${ps.subgoals.join(" · ")}`);
if (ps.hypotheses.length)
console.log(` ‹ hypotheses (${ps.hypotheses.length}): ${ps.hypotheses.join(" · ")}`);
if (ps.uncertainties.length)
console.log(
` ‹ uncertainties(${ps.uncertainties.length}): ${ps.uncertainties.join(" · ")}`,
);
if (ps.rejectedPaths.length)
console.log(
` ‹ rejected (${ps.rejectedPaths.length}): ${ps.rejectedPaths.join(" · ")}`,
);
}
} else if (rec.role === "tool") {
const args = rec.args ? ` args=${oneLine(rec.args, 80)}` : "";
console.log(`${turn} TOOL ${rec.tool ?? "?"}:${args} → ${oneLine(rec.content, 120)}`);
+5 -7
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";
@@ -26,10 +27,6 @@ export interface RunOptions {
task: string;
model: string;
system: string;
/** Opt into Pillar 2 plan-state harvesting. Adds a cheap V3 call per turn. */
harvest?: boolean;
/** Self-consistency budget. > 1 runs N parallel samples and picks the best. */
branch?: number;
budgetUsd?: number;
/** JSONL transcript path — lets `reasonix replay` / `diff` audit this run. */
transcript?: string;
@@ -88,6 +85,7 @@ export async function runCommand(opts: RunOptions): Promise<void> {
tools = new ToolRegistry();
for (const raw of requestedSpecs) {
let label = "anon";
let mcp: McpClient | undefined;
try {
const spec = parseMcpSpec(raw);
label = spec.name ?? "anon";
@@ -102,13 +100,14 @@ 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 })
: spec.transport === "streamable-http"
? new StreamableHttpTransport({ url: spec.url })
: new StdioTransport({ command: spec.command, args: spec.args });
const mcp = new McpClient({ transport });
mcp = new McpClient({ transport });
await mcp.initialize();
const bridge = await bridgeMcpTools(mcp, {
registry: tools,
@@ -134,6 +133,7 @@ export async function runCommand(opts: RunOptions): Promise<void> {
// one-shot `run` invocation with a broken MCP server otherwise
// fails the whole run over a side-concern tool the task might
// not even touch.
await mcp?.close().catch(() => undefined);
process.stderr.write(
`${formatMcpLifecycleEvent({ state: "failed", name: label, reason: (err as Error).message })}\n → run \`reasonix setup\` to remove broken entries from your saved config.\n`,
);
@@ -152,8 +152,6 @@ export async function runCommand(opts: RunOptions): Promise<void> {
prefix,
tools,
model: opts.model,
harvest: opts.harvest,
branch: opts.branch,
budgetUsd: opts.budgetUsd,
});
const prefixHash = prefix.fingerprint;
+201 -203
View File
@@ -1,26 +1,14 @@
import { Command } from "commander";
import { readConfig } from "../config.js";
import { t } from "../i18n/index.js";
import { VERSION } from "../index.js";
import { listSessions } from "../memory/session.js";
import { applyMemoryStack } from "../memory/user.js";
import { ESCALATION_CONTRACT } from "../prompt-fragments.js";
import { chatCommand } from "./commands/chat.js";
import { codeCommand } from "./commands/code.js";
import { commitCommand } from "./commands/commit.js";
import { diffCommand } from "./commands/diff.js";
import { doctorCommand } from "./commands/doctor.js";
import { eventsCommand } from "./commands/events.js";
import { indexCommand } from "./commands/index.js";
import { mcpInspectCommand } from "./commands/mcp-inspect.js";
import { mcpListCommand } from "./commands/mcp.js";
import { replayCommand } from "./commands/replay.js";
import { runCommand } from "./commands/run.js";
import { sessionsCommand } from "./commands/sessions.js";
import { setupCommand } from "./commands/setup.js";
import { statsCommand } from "./commands/stats.js";
import { updateCommand } from "./commands/update.js";
import { versionCommand } from "./commands/version.js";
import { resolveContinueFlag, resolveDefaults } from "./resolve.js";
import { markPhase } from "./startup-profile.js";
markPhase("cli_module_loaded");
const DEFAULT_SYSTEM = `You are Reasonix, a helpful DeepSeek-powered assistant. Be concise and accurate. Use tools when available.
@@ -59,12 +47,9 @@ function parseBudgetFlag(raw: number | undefined): number | undefined {
const program = new Command();
program
.name("reasonix")
.description("DeepSeek-native agent framework — built for cache hits and cheap tokens.")
.description(t("cli.description"))
.version(VERSION)
.option(
"-c, --continue",
"Resume the most recently used chat session without showing the picker.",
);
.option("-c, --continue", t("cli.continue"));
// `reasonix` with no subcommand → launch the friendliest flow.
// First run (no config yet) → interactive setup wizard.
@@ -74,6 +59,7 @@ program
program.action(async (opts: { continue?: boolean }) => {
const cfg = readConfig();
if (!cfg.setupCompleted) {
const { setupCommand } = await import("./commands/setup.js");
await setupCommand({});
return;
}
@@ -84,11 +70,10 @@ program.action(async (opts: { continue?: boolean }) => {
() => listSessions()[0],
(msg) => process.stderr.write(`${msg}\n`),
);
const { chatCommand } = await import("./commands/chat.js");
await chatCommand({
model: defaults.model,
system: applyMemoryStack(DEFAULT_SYSTEM, process.cwd()),
harvest: defaults.harvest,
branch: defaults.branch,
session: continueOpts.session,
mcp: defaults.mcp,
forceResume: continueOpts.forceResume,
@@ -97,43 +82,27 @@ program.action(async (opts: { continue?: boolean }) => {
program
.command("setup")
.description("Interactive wizard — API key, preset, MCP servers. Re-run any time to reconfigure.")
.description(t("cli.setup"))
.action(async () => {
const { setupCommand } = await import("./commands/setup.js");
await setupCommand({});
});
program
.command("code [dir]")
.description(
"Code-editing chat — filesystem tools rooted at <dir> (default: cwd), coding system prompt, v4-flash baseline. Model proposes SEARCH/REPLACE blocks; Reasonix applies them to disk. Use /preset pro or /pro to lock v4-pro on hard tasks.",
)
.option("-m, --model <id>", "Override default model (v4-flash)")
.option("--no-session", "Disable session persistence for this run")
.option("-r, --resume", "Skip the session picker — always continue prior messages")
.option("-n, --new", "Skip the session picker — always wipe prior messages and start fresh")
.option("--transcript <path>", "Write a JSONL transcript to this path")
.option(
"--harvest",
"Opt-in Pillar-2 plan-state extraction. Adds one flash call per turn; off by default (no preset enables it).",
)
.option(
"--budget <usd>",
"Soft USD cap on session spend. Off by default. Warns at 80%, refuses next turn at 100%. Mid-session: /budget <usd> or /budget off.",
(v) => Number.parseFloat(v),
)
.option(
"--no-dashboard",
"Suppress the auto-launched embedded web dashboard. Default behavior boots it on TUI mount and shows the URL in the status bar (clickable in OSC-8-aware terminals).",
)
.option(
"--system-append <prompt>",
"Append instructions to the code system prompt. Does NOT replace the default prompt — adds after it.",
)
.option(
"--system-append-file <path>",
"Append file contents to the code system prompt. Does NOT replace the default prompt. UTF-8, relative to cwd or absolute.",
)
.description(t("cli.code"))
.option("-m, --model <id>", t("ui.modelOverride"))
.option("--no-session", t("ui.noSession"))
.option("-r, --resume", t("ui.resumeHint"))
.option("-n, --new", t("ui.newHint"))
.option("--transcript <path>", t("ui.transcriptHint"))
.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) => {
const { codeCommand } = await import("./commands/code.js");
await codeCommand({
dir,
model: opts.model,
@@ -141,66 +110,40 @@ program
transcript: opts.transcript,
forceResume: !!opts.resume,
forceNew: !!opts.new,
harvest: !!opts.harvest,
budgetUsd: parseBudgetFlag(opts.budget),
noDashboard: opts.dashboard === false,
systemAppend: opts.systemAppend,
systemAppendFile: opts.systemAppendFile,
altScreen: opts.altScreen !== false,
});
});
program
.command("chat")
.description("Interactive Ink TUI with live cache/cost panel.")
.option("-m, --model <id>", "DeepSeek model id (overrides preset)")
.option("-s, --system <prompt>", "System prompt (pinned in the immutable prefix)", DEFAULT_SYSTEM)
.option("--transcript <path>", "Write a JSONL transcript to this path")
.option(
"--preset <name>",
"Model bundle. One of: auto (flash → pro on hard turns, default), flash (always flash), pro (always pro). Overrides config.preset.",
)
.option(
"--harvest",
"Opt-in Pillar-2 plan-state extraction. Off by default — no preset enables it.",
)
.option(
"--branch <n>",
"Self-consistency: run N parallel samples per turn (N× cost). Manual only — never auto-enabled.",
(v) => Number.parseInt(v, 10),
)
.option(
"--budget <usd>",
"Soft USD cap on session spend. Off by default. Warns at 80%, refuses next turn at 100%. Mid-session: /budget <usd> or /budget off.",
(v) => Number.parseFloat(v),
)
.option("--session <name>", "Use a named session (default: from config, usually 'default').")
.option("--no-session", "Disable session persistence for this run (ephemeral chat)")
.option("-r, --resume", "Skip the session picker — always continue prior messages")
.option(
"-c, --continue",
"Resume the most-recently-used session (any name) without showing the picker.",
)
.option("-n, --new", "Skip the session picker — always wipe prior messages and start fresh")
.description(t("cli.chat"))
.option("-m, --model <id>", t("ui.modelIdHint"))
.option("-s, --system <prompt>", t("ui.systemPromptHint"), DEFAULT_SYSTEM)
.option("--transcript <path>", t("ui.transcriptHint"))
.option("--preset <name>", t("ui.presetHint"))
.option("--budget <usd>", t("ui.budgetHint"), (v) => Number.parseFloat(v))
.option("--session <name>", t("ui.sessionNameHint"))
.option("--no-session", t("ui.ephemeralHint"))
.option("-r, --resume", t("ui.resumeHint"))
.option("-c, --continue", t("cli.continue"))
.option("-n, --new", t("ui.newHint"))
.option(
"--mcp <spec>",
'MCP server spec; repeatable. "name=cmd args...", "cmd args...", or a URL (http/https → SSE transport). Overrides config.mcp when provided.',
t("ui.mcpSpecHint"),
(value: string, previous: string[] = []) => [...previous, value],
[] as string[],
)
.option(
"--mcp-prefix <str>",
"Global prefix applied to every MCP tool (only honored when no per-spec name is set; avoids collisions with a single anonymous server)",
)
.option("--no-config", "Ignore `~/.reasonix/config.json` — useful for CI or reproducing issues")
.option(
"--no-dashboard",
"Suppress the auto-launched embedded web dashboard. Default behavior boots it on TUI mount and shows the URL in the status bar (clickable in OSC-8-aware terminals).",
)
.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,
harvest: opts.harvest,
branch: opts.branch,
mcp: opts.mcp as string[],
session: opts.session,
preset: opts.preset,
@@ -218,12 +161,11 @@ program
() => listSessions()[0],
(msg) => process.stderr.write(`${msg}\n`),
);
const { chatCommand } = await import("./commands/chat.js");
await chatCommand({
model: defaults.model,
system: applyMemoryStack(opts.system, process.cwd()),
transcript: opts.transcript,
harvest: defaults.harvest,
branch: defaults.branch,
budgetUsd: parseBudgetFlag(opts.budget),
session: continueOpts.session,
mcp: defaults.mcp,
@@ -231,53 +173,38 @@ program
forceResume: continueOpts.forceResume,
forceNew: !!opts.new,
noDashboard: opts.dashboard === false,
altScreen: opts.altScreen !== false,
});
});
program
.command("run <task>")
.description("Run a single task non-interactively, streaming output.")
.option("-m, --model <id>", "DeepSeek model id (overrides preset)")
.option("-s, --system <prompt>", "System prompt", DEFAULT_SYSTEM)
.option("--preset <name>", "Model bundle: auto | flash | pro (default: auto)")
.option("--harvest", "Extract typed plan state from R1 reasoning (Pillar 2)")
.option(
"--branch <n>",
"Self-consistency: run N parallel samples per turn and pick the most confident",
(v) => Number.parseInt(v, 10),
)
.option(
"--budget <usd>",
"Soft USD cap on session spend. Off by default. Refuses to start a new turn once cumulative cost ≥ cap.",
(v) => Number.parseFloat(v),
)
.option("--transcript <path>", "Write a JSONL transcript to this path for replay/diff")
.description(t("cli.run"))
.option("-m, --model <id>", t("ui.modelIdHint"))
.option("-s, --system <prompt>", t("ui.systemPromptHint"), DEFAULT_SYSTEM)
.option("--preset <name>", t("ui.presetHintShort"))
.option("--budget <usd>", t("ui.budgetHintShort"), (v) => Number.parseFloat(v))
.option("--transcript <path>", t("ui.transcriptHintShort"))
.option(
"--mcp <spec>",
'MCP server spec; repeatable. "name=cmd args...", "cmd args...", or a URL (http/https → SSE).',
t("ui.mcpSpecHintShort"),
(value: string, previous: string[] = []) => [...previous, value],
[] as string[],
)
.option(
"--mcp-prefix <str>",
"Global prefix (only honored when no per-spec name is set; for a single anonymous server)",
)
.option("--no-config", "Ignore `~/.reasonix/config.json` — useful for CI or reproducing issues")
.option("--mcp-prefix <str>", t("ui.mcpPrefixHintShort"))
.option("--no-config", t("ui.noConfigHint"))
.action(async (task: string, opts) => {
const defaults = resolveDefaults({
model: opts.model,
harvest: opts.harvest,
branch: opts.branch,
mcp: opts.mcp as string[],
preset: opts.preset,
noConfig: opts.config === false,
});
const { runCommand } = await import("./commands/run.js");
await runCommand({
task,
model: defaults.model,
system: applyMemoryStack(opts.system, process.cwd()),
harvest: defaults.harvest,
branch: defaults.branch,
budgetUsd: parseBudgetFlag(opts.budget),
transcript: opts.transcript,
mcp: defaults.mcp,
@@ -287,59 +214,59 @@ program
program
.command("stats [transcript]")
.description(
"Show usage dashboard (today / week / month / all-time · turns · cache hit · cost · savings vs Claude). " +
"Pass a transcript path to fall back to the per-file summary (assistant turns + tool calls).",
)
.action((transcript: string | undefined) => {
.description(t("cli.stats"))
.action(async (transcript: string | undefined) => {
const { statsCommand } = await import("./commands/stats.js");
statsCommand({ transcript });
});
program
.command("doctor")
.description(
"One-command health check — API key, config, /user/balance reachability, tokenizer, sessions, hooks, Ollama (if used), project markers. Exit 1 on any fail; 0 on warn / clean.",
)
.description(t("cli.doctor"))
.action(async () => {
const { doctorCommand } = await import("./commands/doctor.js");
await doctorCommand();
});
program
.command("commit")
.description(
"Draft a commit message from the staged diff (or working tree, if nothing staged), matching your repo's recent commit style. Review interactively before it lands.",
)
.option("-m, --model <id>", "Override the default model (deepseek-v4-flash)")
.option(
"-y, --yes",
"Skip the [a]ccept / [r]egenerate prompt and commit the first draft. Useful in scripts.",
)
.description(t("cli.commit"))
.option("-m, --model <id>", t("ui.modelOverrideFlash"))
.option("-y, --yes", t("ui.skipConfirmHint"))
.action(async (opts) => {
const { commitCommand } = await import("./commands/commit.js");
await commitCommand({ model: opts.model, yes: !!opts.yes });
});
program
.command("sessions [name]")
.description("List saved chat sessions, or inspect one by name.")
.option("-v, --verbose", "Include system prompts + tool-call metadata when inspecting")
.action((name: string | undefined, opts) => {
.description(t("cli.sessions"))
.option("-v, --verbose", t("ui.verboseHint"))
.action(async (name: string | undefined, opts) => {
const { sessionsCommand } = await import("./commands/sessions.js");
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(async (opts) => {
const { pruneSessionsCommand } = await import("./commands/prune-sessions.js");
pruneSessionsCommand({ days: opts.days, dryRun: !!opts.dryRun });
});
program
.command("events <name>")
.description(
"Pretty-print the kernel event-log sidecar (~/.reasonix/sessions/<name>.events.jsonl) — every typed Event the session produced.",
)
.option("--type <type>", "Show only events of this type (e.g., tool.intent)")
.option("--since <id>", "Show only events with id >= N", (v) => Number.parseInt(v, 10))
.option("--tail <n>", "Show only the last N events", (v) => Number.parseInt(v, 10))
.option("--json", "Emit raw JSONL passthrough instead of formatted lines (for jq pipelines)")
.option(
"--projection",
"Replace the listing with the final reduced ProjectionSet (conversation, budget, plan, …)",
)
.action((name: string, opts) => {
.description(t("cli.events"))
.option("--type <type>", t("ui.eventTypeHint"))
.option("--since <id>", t("ui.eventSinceHint"), (v) => Number.parseInt(v, 10))
.option("--tail <n>", t("ui.eventTailHint"), (v) => Number.parseInt(v, 10))
.option("--json", t("ui.jsonHint"))
.option("--projection", t("ui.projectionHint"))
.action(async (name: string, opts) => {
const { eventsCommand } = await import("./commands/events.js");
eventsCommand({
name,
type: opts.type,
@@ -352,13 +279,12 @@ program
program
.command("replay <transcript>")
.description(
"Interactive Ink TUI to scrub through a transcript + rebuild its session summary (cost, cache, prefix stability). No API calls.",
)
.option("--print", "Dump to stdout instead of mounting the TUI (auto when piped)")
.option("--head <n>", "stdout mode only — show first N records", (v) => Number.parseInt(v, 10))
.option("--tail <n>", "stdout mode only — show last N records", (v) => Number.parseInt(v, 10))
.description(t("cli.replay"))
.option("--print", t("ui.printHint"))
.option("--head <n>", t("ui.headHint"), (v) => Number.parseInt(v, 10))
.option("--tail <n>", t("ui.tailHint"), (v) => Number.parseInt(v, 10))
.action(async (transcript: string, opts) => {
const { replayCommand } = await import("./commands/replay.js");
await replayCommand({
path: transcript,
print: !!opts.print,
@@ -369,15 +295,14 @@ program
program
.command("diff <a> <b>")
.description(
"Compare two transcripts in a split-pane Ink TUI (default) or stdout table. Use n/N to jump across divergences.",
)
.option("--md <path>", "Write a markdown report (blog-ready) to this path")
.option("--print", "Force stdout table instead of the TUI (auto when piped)")
.option("--tui", "Force the TUI even when piped (rare)")
.option("--label-a <label>", "Display label for transcript A (default: filename)")
.option("--label-b <label>", "Display label for transcript B (default: filename)")
.description(t("cli.diff"))
.option("--md <path>", t("ui.mdReportHint"))
.option("--print", t("ui.printHintTable"))
.option("--tui", t("ui.tuiHint"))
.option("--label-a <label>", t("ui.labelAHint"))
.option("--label-b <label>", t("ui.labelBHint"))
.action(async (a: string, b: string, opts) => {
const { diffCommand } = await import("./commands/diff.js");
await diffCommand({
a,
b,
@@ -389,58 +314,130 @@ program
});
});
const mcp = program
.command("mcp")
.description("Model Context Protocol helpers — discover servers, test your setup.");
const mcp = program.command("mcp").description(t("cli.mcp"));
mcp
.command("list")
.description("Show a curated catalog of popular MCP servers with ready-to-use --mcp commands.")
.option("--json", "Emit the catalog as JSON instead of the human-readable table")
.action((opts) => {
mcpListCommand({ json: !!opts.json });
});
mcp
.command("inspect <spec>")
.description(
'Connect to one MCP server and print its server info + tools/resources/prompts. <spec> takes the same forms as --mcp ("name=cmd args", "cmd args", or an SSE URL).',
)
.option("--json", "Emit the full inspection report as JSON instead of the human-readable summary")
.action(async (spec: string, opts) => {
.description(t("ui.mcpListDescription"))
.option("--json", t("ui.jsonHintCatalog"))
.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 mcpInspectCommand({ spec, json: !!opts.json });
const { mcpListCommand } = await import("./commands/mcp.js");
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 inspect failed: ${(err as Error).message}\n`);
process.stderr.write(`mcp list failed: ${(err as Error).message}\n`);
process.exit(1);
}
});
program.command("version").description("Print Reasonix version.").action(versionCommand);
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 {
const { mcpSearchCommand } = await import("./commands/mcp.js");
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 {
const { mcpInstallCommand } = await import("./commands/mcp.js");
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 {
const { mcpBrowseCommand } = await import("./commands/mcp-browse.js");
await mcpBrowseCommand();
} catch (err) {
process.stderr.write(`mcp browse failed: ${(err as Error).message}\n`);
process.exit(1);
}
});
mcp
.command("inspect <spec>")
.description(t("ui.mcpInspectDescription"))
.option("--json", t("ui.jsonHintReport"))
.action(async (spec: string, opts) => {
const { formatMcpInspectFailure, mcpInspectCommand } = await import(
"./commands/mcp-inspect.js"
);
try {
await mcpInspectCommand({ spec, json: !!opts.json });
} catch (err) {
process.stderr.write(`mcp inspect failed: ${formatMcpInspectFailure(err)}\n`);
process.exit(1);
}
});
program
.command("version")
.description(t("cli.version"))
.action(async () => {
const { versionCommand } = await import("./commands/version.js");
versionCommand();
});
program
.command("update")
.description(
"Check the npm registry for a newer Reasonix and install it. Detects npx vs global install; for npx users, prints a cache-refresh hint instead of running `npm i -g`.",
)
.option("--dry-run", "Print the plan without executing the install")
.description(t("cli.update"))
.option("--dry-run", t("ui.dryRunHint"))
.action(async (opts: { dryRun?: boolean }) => {
const { updateCommand } = await import("./commands/update.js");
await updateCommand({ dryRun: !!opts.dryRun });
});
program
.command("index")
.description(
"Build (or incrementally refresh) a local semantic search index for the project so `reasonix code` can answer 'where do we…' questions by meaning, not just by token. Uses Ollama as the embedding backend; missing daemon / model is offered to the user with a confirm prompt.",
)
.option("--rebuild", "Wipe and rebuild from scratch")
.option("--model <name>", "Embedding model (default: nomic-embed-text)")
.option("--dir <path>", "Project root to index (default: cwd)")
.option("--ollama-url <url>", "Override Ollama base URL (default: http://localhost:11434)")
.option(
"-y, --yes",
"Skip preflight prompts — auto-start the daemon and pull the model if missing (use in scripts)",
)
.description(t("cli.index"))
.option("--rebuild", t("ui.rebuildHint"))
.option("--model <name>", t("ui.embedModelHint"))
.option("--dir <path>", t("ui.projectDirHint"))
.option("--ollama-url <url>", t("ui.ollamaUrlHint"))
.option("-y, --yes", t("ui.skipPromptsHint"))
.action(
async (opts: {
rebuild?: boolean;
@@ -449,6 +446,7 @@ program
ollamaUrl?: string;
yes?: boolean;
}) => {
const { indexCommand } = await import("./commands/index.js");
await indexCommand(opts);
},
);
+1 -15
View File
@@ -6,17 +6,12 @@ import { resolvePreset } from "./ui/presets.js";
export interface ResolvedDefaults {
model: string;
reasoningEffort: "high" | "max";
harvest: boolean;
branch: number | undefined;
mcp: string[];
session: string | undefined;
}
export interface RawCliFlags {
model?: string;
harvest?: boolean;
/** From `commander`; already parseInt'd. */
branch?: number;
mcp?: string[];
/** Commander's `--no-session` surfaces as `false`; `--session X` as a string. */
session?: string | false;
@@ -33,9 +28,6 @@ export function resolveDefaults(flags: RawCliFlags): ResolvedDefaults {
const model = flags.model ?? presetSettings.model;
const reasoningEffort = presetSettings.reasoningEffort;
const harvest = flags.harvest === true ? true : presetSettings.harvest;
const branchFromFlag = normalizeBranch(flags.branch);
const branch = branchFromFlag ?? (presetSettings.branch > 1 ? presetSettings.branch : undefined);
// `--mcp` accumulator is [] when absent. Treat empty from flags as
// "user didn't pass" → fall through to config. Users who explicitly
@@ -44,7 +36,7 @@ export function resolveDefaults(flags: RawCliFlags): ResolvedDefaults {
const session = resolveSession(flags.session, cfg.session);
return { model, reasoningEffort, harvest, branch, mcp, session };
return { model, reasoningEffort, mcp, session };
}
function pickPreset(
@@ -69,12 +61,6 @@ function isPresetName(s: string): s is PresetName {
);
}
function normalizeBranch(raw: number | undefined): number | undefined {
if (raw === undefined) return undefined;
if (!Number.isFinite(raw) || raw <= 1) return undefined;
return Math.min(raw, 8);
}
function resolveSession(
flag: string | false | undefined,
configSession: string | null | undefined,
+47
View File
@@ -0,0 +1,47 @@
import { performance } from "node:perf_hooks";
interface PhaseMark {
name: string;
t: number;
}
const marks: PhaseMark[] = [];
let dumped = false;
function envFlag(): boolean {
const v = process.env.REASONIX_PROFILE_STARTUP;
return v === "1" || v === "true" || v === "yes";
}
export function isStartupProfileEnabled(): boolean {
return envFlag();
}
export function markPhase(name: string): void {
if (!envFlag()) return;
marks.push({ name, t: performance.now() });
}
export function dumpStartupProfile(stream: NodeJS.WriteStream = process.stderr): void {
if (!envFlag() || dumped || marks.length === 0) return;
dumped = true;
const totalMs = marks[marks.length - 1]!.t;
const widest = String(Math.round(totalMs)).length;
const lines: string[] = ["[startup-profile]"];
let prev = 0;
for (const m of marks) {
const cum = Math.round(m.t).toString().padStart(widest);
const delta = Math.round(m.t - prev);
lines.push(` ${cum}ms ${m.name.padEnd(28)} (+${delta})`);
prev = m.t;
}
lines.push(
`─── ${Math.round(totalMs)}ms total · last phase ${marks[marks.length - 1]!.name} · set REASONIX_PROFILE_STARTUP=0 to silence`,
);
stream.write(`${lines.join("\n")}\n`);
}
export function _resetForTests(): void {
marks.length = 0;
dumped = false;
}
+1056 -829
View File
File diff suppressed because it is too large. Load diff
+119 -77
View File
@@ -1,104 +1,146 @@
import { Box, Text } from "ink";
// biome-ignore lint/style/useImportType: tsconfig.jsx = "react" needs React in value scope for JSX compilation
import React from "react";
import { COLOR, GLYPH } from "./theme.js";
import { GLYPH, useColor } from "./theme.js";
import type { AtPickerEntry, AtPickerState } from "./useCompletionPickers.js";
export interface AtMentionSuggestionsProps {
/**
* Current matching file paths, ranked by the picker. `null` means
* "not in @-prefix mode" — render nothing. Empty array means "in @
* mode but no files match that partial" — render a hint.
*/
matches: readonly string[] | null;
/** Index (within `matches`) of the currently highlighted row. */
state: AtPickerState | null;
selectedIndex: number;
/** The partial query the user typed after `@`. Shown in the hint row. */
query: string;
}
/**
* `@`-mention picker. Rendered below the input box while the user is
* typing an `@…` prefix in code mode. Visual grammar matches the
* design's file picker:
*
* @ files matching "auth" esc
* ▸ login.ts src/auth/
* refresh.ts src/auth/
* validators.ts src/auth/
* auth.test.ts tests/
* [↑↓] navigate · Tab / ⏎ insert as @path · file content inlined
*
* Basename in primary cyan (the user's eye lands here first), dir
* suffix in dim info color. No solid-bg pill on the selected row —
* leading ▸ + bold + brighter color does the same job without the
* loud bg block. Mirrors {@link SlashSuggestions}.
*/
const ROW_WINDOW = 8;
export function AtMentionSuggestions({
matches,
state,
selectedIndex,
query,
}: AtMentionSuggestionsProps): React.ReactElement | null {
if (matches === null) return null;
if (matches.length === 0) {
const color = useColor();
if (!state) return null;
const isBrowse = state.kind === "browse";
const entries = state.entries;
const total = entries.length;
const windowStart =
total <= ROW_WINDOW
? 0
: Math.max(0, Math.min(selectedIndex - Math.floor(ROW_WINDOW / 2), total - ROW_WINDOW));
const shown = entries.slice(windowStart, windowStart + ROW_WINDOW);
const hiddenAbove = windowStart;
const hiddenBelow = total - windowStart - shown.length;
return (
<Box flexDirection="column" paddingX={1} marginTop={1}>
<HeaderRow state={state} hiddenAbove={hiddenAbove} />
{total === 0 ? <EmptyRow state={state} color={color} /> : null}
{shown.map((entry, i) => (
<EntryRow
key={`${entry.insertPath}:${entry.isDir ? "d" : "f"}`}
entry={entry}
isSelected={windowStart + i === selectedIndex}
/>
))}
{hiddenBelow > 0 ? <Text dimColor>{` ↓ ${hiddenBelow} below`}</Text> : null}
<FooterRow isBrowse={isBrowse} hasFolder={shown.some((e) => e.isDir)} />
</Box>
);
}
function HeaderRow({
state,
hiddenAbove,
}: {
state: AtPickerState;
hiddenAbove: number;
}) {
const color = useColor();
const total = state.entries.length;
const lead = (
<Text color={color.primary} bold>
{"@ "}
</Text>
);
if (state.kind === "browse") {
const where = state.baseDir === "" ? "/" : `${state.baseDir}/`;
const counter = state.loading ? "loading…" : `${total} ${total === 1 ? "entry" : "entries"}`;
return (
<Box paddingX={1} marginTop={1}>
<Text color={COLOR.warn} bold>
{GLYPH.warn}
</Text>
<Text> </Text>
<Text color={COLOR.warn}>{`no files match "@${query}"`}</Text>
<Text dimColor>{" — keep typing or Backspace; paths resolve from the code root"}</Text>
<Box>
{lead}
<Text dimColor>{`${where} ${counter}`}</Text>
{hiddenAbove > 0 ? <Text dimColor>{` ↑ ${hiddenAbove} above`}</Text> : null}
</Box>
);
}
const MAX = 8;
const total = matches.length;
const windowStart =
total <= MAX ? 0 : Math.max(0, Math.min(selectedIndex - Math.floor(MAX / 2), total - MAX));
const shown = matches.slice(windowStart, windowStart + MAX);
const hiddenAbove = windowStart;
const hiddenBelow = total - windowStart - shown.length;
const status = state.searching
? `searching… ${state.scanned} scanned · ${total} ${total === 1 ? "match" : "matches"}`
: `${total} ${total === 1 ? "match" : "matches"} for "${state.filter}"`;
return (
<Box flexDirection="column" paddingX={1} marginTop={1}>
<Box>
<Text color={COLOR.primary} bold>
{"@ "}
</Text>
<Text dimColor>
{query
? `${total} match${total === 1 ? "" : "es"} for "${query}"`
: `${total} file${total === 1 ? "" : "s"}`}
</Text>
{hiddenAbove > 0 ? <Text dimColor>{` ↑ ${hiddenAbove} above`}</Text> : null}
</Box>
{shown.map((path, i) => (
<FileRow key={path} path={path} isSelected={windowStart + i === selectedIndex} />
))}
{hiddenBelow > 0 ? <Text dimColor>{` ↓ ${hiddenBelow} below`}</Text> : null}
<Box marginTop={0}>
<Text dimColor>{" ↑↓ navigate · Tab / ⏎ insert as @path · esc cancel"}</Text>
</Box>
<Box>
{lead}
<Text dimColor>{status}</Text>
{hiddenAbove > 0 ? <Text dimColor>{` ↑ ${hiddenAbove} above`}</Text> : null}
</Box>
);
}
function FileRow({ path, isSelected }: { path: string; isSelected: boolean }) {
// Split the path so the basename visually pops — same dropdown
// affordance as VS Code's Quick Open. Basename in primary cyan
// (selected: bold), dir suffix in dim info color so the eye lands
// on the filename first and uses the path only as a disambiguator.
const slash = path.lastIndexOf("/");
const dir = slash >= 0 ? `${path.slice(0, slash)}/` : "";
const base = slash >= 0 ? path.slice(slash + 1) : path;
function EmptyRow({ state, color }: { state: AtPickerState; color: ReturnType<typeof useColor> }) {
if (state.kind === "browse") {
if (state.loading) return null;
return (
<Box>
<Text color={color.warn} bold>
{GLYPH.warn}
</Text>
<Text> </Text>
<Text color={color.warn}>empty directory</Text>
</Box>
);
}
if (state.searching) {
return (
<Box>
<Text dimColor>scanning the tree…</Text>
</Box>
);
}
return (
<Box>
<Text color={isSelected ? COLOR.primary : COLOR.info} bold={isSelected}>
{isSelected ? `${GLYPH.cur} ` : " "}
<Text color={color.warn} bold>
{GLYPH.warn}
</Text>
<Text color={COLOR.primary} bold={isSelected}>
{base.padEnd(20)}
<Text> </Text>
<Text color={color.warn}>{`no files match "${state.filter}"`}</Text>
</Box>
);
}
function EntryRow({ entry, isSelected }: { entry: AtPickerEntry; isSelected: boolean }) {
const color = useColor();
const cursor = isSelected ? `${GLYPH.cur} ` : " ";
const labelColor = entry.isDir ? color.accent : color.primary;
const labelText = entry.isDir ? `${entry.label}/` : entry.label;
return (
<Box>
<Text color={isSelected ? color.primary : color.info} bold={isSelected}>
{cursor}
</Text>
{dir ? <Text dimColor>{` ${dir}`}</Text> : null}
<Text color={labelColor} bold={isSelected}>
{labelText.padEnd(20)}
</Text>
{entry.dirSuffix ? <Text dimColor>{` ${entry.dirSuffix}`}</Text> : null}
</Box>
);
}
function FooterRow({ isBrowse, hasFolder }: { isBrowse: boolean; hasFolder: boolean }) {
const hint = isBrowse
? hasFolder
? "↑↓ navigate · Tab drill into folder · ⏎ insert · esc cancel"
: "↑↓ navigate · Tab / ⏎ insert as @path · esc cancel"
: "↑↓ navigate · Tab / ⏎ insert as @path · esc cancel";
return (
<Box marginTop={0}>
<Text dimColor>{` ${hint}`}</Text>
</Box>
);
}
+156
View File
@@ -0,0 +1,156 @@
import { Box, Text, useStdout } from "ink";
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React in value scope for JSX compilation
import React, { useMemo, useState } from "react";
import type { CheckpointMeta } from "../../code/checkpoints.js";
import { fmtAgo } from "../../code/checkpoints.js";
import { type PickerBroadcastPorts, usePickerBroadcast } from "./dashboard/use-picker-broadcast.js";
import { useKeystroke } from "./keystroke-context.js";
import { FG, TONE } from "./theme/tokens.js";
export type CheckpointPickerOutcome =
| { kind: "restore"; id: string }
| { kind: "delete"; id: string }
| { kind: "quit" };
export interface CheckpointPickerProps {
checkpoints: ReadonlyArray<CheckpointMeta>;
workspace: string;
onChoose: (outcome: CheckpointPickerOutcome) => void;
pickerPorts?: PickerBroadcastPorts;
}
const PAGE_MARGIN = 6;
export function CheckpointPicker({
checkpoints,
workspace,
onChoose,
pickerPorts,
}: CheckpointPickerProps): React.ReactElement {
const [focus, setFocus] = useState(0);
const { stdout } = useStdout();
const rows = stdout?.rows ?? 40;
const visibleCount = Math.max(3, rows - PAGE_MARGIN);
const snapshot = useMemo(
() => ({
pickerKind: "checkpoints",
title: `restore a checkpoint — ${workspace}`,
items: checkpoints.map((c) => {
const sizeKb = (c.bytes / 1024).toFixed(1);
const tag = c.source === "manual" ? "" : ` (${c.source})`;
return {
id: c.id,
title: `${c.name}${tag}`,
subtitle: `${c.fileCount} file${c.fileCount === 1 ? "" : "s"} · ${sizeKb} KB`,
badge: c.id.slice(0, 7),
meta: fmtAgo(c.createdAt),
};
}),
actions: ["pick", "delete", "cancel"] as const,
hint: "↑↓ pick · ⏎ restore · [d] forget · esc quit",
}),
[checkpoints, workspace],
);
usePickerBroadcast(
!!pickerPorts,
{
...snapshot,
actions: [...snapshot.actions],
},
(res) => {
if (res.action === "pick") return onChoose({ kind: "restore", id: res.id });
if (res.action === "delete") return onChoose({ kind: "delete", id: res.id });
if (res.action === "cancel") return onChoose({ kind: "quit" });
},
pickerPorts ?? {
broadcast: () => undefined,
resolverRef: { current: null },
snapshotRef: { current: null },
},
);
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(checkpoints.length - 1, f + 1));
if (checkpoints.length === 0) {
if (ev.return) return onChoose({ kind: "quit" });
return;
}
const target = checkpoints[focus];
if (!target) return;
if (ev.return) return onChoose({ kind: "restore", id: target.id });
if (ev.input === "q") return onChoose({ kind: "quit" });
if (ev.input === "d") return onChoose({ kind: "delete", id: target.id });
});
const start = Math.max(
0,
Math.min(focus - Math.floor(visibleCount / 2), checkpoints.length - visibleCount),
);
const end = Math.min(checkpoints.length, start + visibleCount);
const shown = checkpoints.slice(start, end);
const hiddenBelow = checkpoints.length - end;
return (
<Box flexDirection="column" marginY={1}>
<Box>
<Text bold color={TONE.brand}>
{" ◈ REASONIX · pick a checkpoint "}
</Text>
<Text color={FG.meta}>{` · ${workspace}`}</Text>
</Box>
<Box height={1} />
{checkpoints.length === 0 ? (
<Box>
<Text color={FG.faint}>
{" no checkpoints in this workspace yet — see /checkpoint to make one"}
</Text>
</Box>
) : (
shown.map((c, i) => <CheckpointRow key={c.id} info={c} focused={start + i === focus} />)
)}
{hiddenBelow > 0 ? (
<Box>
<Text color={FG.faint}>{` … ${hiddenBelow} more`}</Text>
</Box>
) : null}
<Box marginTop={1}>
<Text color={FG.faint}>
{checkpoints.length === 0
? " esc quit"
: " ↑↓ pick · ⏎ restore · [d] forget · esc quit"}
</Text>
</Box>
</Box>
);
}
function CheckpointRow({
info,
focused,
}: {
info: CheckpointMeta;
focused: boolean;
}): React.ReactElement {
const tag = info.source === "manual" ? "" : ` (${info.source})`;
const sizeKb = (info.bytes / 1024).toFixed(1);
const time = fmtAgo(info.createdAt);
return (
<Box>
<Text color={focused ? TONE.brand : FG.faint}>{focused ? " ▸ " : " "}</Text>
<Text color={FG.meta}>{info.id.slice(0, 7).padEnd(8)}</Text>
<Text bold={focused} color={focused ? FG.strong : FG.sub}>
{info.name}
</Text>
<Text color={FG.faint}>{tag}</Text>
<Box flexGrow={1} />
<Text color={FG.faint}>{`${time.padStart(8)} · `}</Text>
<Text
color={FG.faint}
>{`${info.fileCount} file${info.fileCount === 1 ? "" : "s"}, ${sizeKb} KB`}</Text>
</Box>
);
}
-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);
}
+69
View File
@@ -0,0 +1,69 @@
import { Text, useInput } from "ink";
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React in value scope for JSX compilation
import React, { useRef } from "react";
import { FG } from "./theme/tokens.js";
export interface MaskedInputProps {
value: string;
onChange: (next: string) => void;
onSubmit: (final: string) => void;
mask?: string;
placeholder?: string;
}
/** Windows ConPTY splits bracketed-paste wrappers across stdin chunks; Ink's parser sees them as printable `[`, `2`, `0`, `0`, `~` and they leak into the buffer. Strip them at the input boundary and again at submit. */
function stripPasteMarkers(s: string): string {
// biome-ignore lint/suspicious/noControlCharactersInRegex: ESC (0x1b) is exactly what we're stripping — bracketed-paste wrappers and stray escape bytes leaked from Ink's parser.
return s.replace(/\u001b?\[20[01]~/g, "").replace(/\u001b/g, "");
}
export function MaskedInput({
value,
onChange,
onSubmit,
mask = "•",
placeholder = "",
}: MaskedInputProps): React.ReactElement {
const valueRef = useRef(value);
valueRef.current = value;
useInput((input, key) => {
if (key.return) {
onSubmit(stripPasteMarkers(valueRef.current));
return;
}
if (key.backspace || key.delete) {
if (valueRef.current.length === 0) return;
const next = valueRef.current.slice(0, -1);
valueRef.current = next;
onChange(next);
return;
}
if (input && !key.ctrl && !key.meta && !key.escape) {
const cleaned = stripPasteMarkers(input);
if (cleaned.length === 0) return;
const next = stripPasteMarkers(valueRef.current + cleaned);
valueRef.current = next;
onChange(next);
}
});
if (value.length === 0) {
if (placeholder.length === 0) {
return <Text inverse> </Text>;
}
return (
<>
<Text inverse>{placeholder[0]}</Text>
<Text color={FG.faint}>{placeholder.slice(1)}</Text>
</>
);
}
return (
<>
<Text>{mask.repeat(value.length)}</Text>
<Text inverse> </Text>
</>
);
}
+1 -8
View File
@@ -1,10 +1,10 @@
/** `/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";
import { healthBadge } from "./mcp-health.js";
import { type ApplyAppend, kickOffMcpReconnect } from "./mcp-reconnect-kickoff.js";
import type { McpServerSummary } from "./slash/types.js";
import { COLOR } from "./theme.js";
@@ -106,13 +106,6 @@ function ServerRow({ server, active }: { server: McpServerSummary; active: boole
);
}
function healthBadge(elapsedMs: number): { glyph: string; label: string; color: string } {
if (elapsedMs === 0) return { glyph: "✗", label: "no inspect data", color: COLOR.err };
if (elapsedMs < 500) return { glyph: "●", label: `healthy · ${elapsedMs}ms`, color: COLOR.ok };
if (elapsedMs < 3000) return { glyph: "◌", label: `slow · ${elapsedMs}ms`, color: COLOR.warn };
return { glyph: "✗", label: `very slow · ${elapsedMs}ms`, color: COLOR.err };
}
function capabilityList(s: McpServerSummary): string {
const caps: string[] = ["tools/list", "tools/call"];
if (s.report.resources.supported) caps.push("resources/list");
+92
View File
@@ -0,0 +1,92 @@
/** `/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 type { PickerBroadcastPorts } from "./dashboard/use-picker-broadcast.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 }>;
}>;
/** Forwarded to the marketplace tab so the web dashboard can drive install / uninstall / refine / load-more. */
pickerPorts?: PickerBroadcastPorts;
}
export function McpHub({
initialTab,
liveServers,
configPath,
onClose,
postInfo,
applyAppend,
reloadMcp,
pickerPorts,
}: 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}
pickerPorts={pickerPorts}
/>
)}
</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>;
}
+411
View File
@@ -0,0 +1,411 @@
/** `/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 { type PickerBroadcastPorts, usePickerBroadcast } from "./dashboard/use-picker-broadcast.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 }>;
}>;
pickerPorts?: PickerBroadcastPorts;
}
interface State {
handle: RegistryHandle | null;
loading: boolean;
query: string;
selected: number;
status: string;
/** specs currently in config.mcp[] — refreshed after install/uninstall. */
installedSpecs: string[];
}
export function buildMarketplacePickerSnapshot(args: {
filtered: RegistryEntry[];
installedSpecs: string[];
query: string;
status: string;
hasMore: boolean;
}) {
return {
pickerKind: "mcp-marketplace" as const,
title: `MCP marketplace · ${args.status}`,
query: args.query,
items: args.filtered.map((e) => {
const installedSpec = isInstalled(args.installedSpecs, e);
return {
id: e.name,
title: e.title || e.name,
subtitle: e.description?.slice(0, 200) ?? undefined,
badge: installedSpec
? "installed"
: e.source === "official"
? "official"
: e.source === "smithery"
? "smithery"
: "local",
meta: e.popularity !== undefined ? `★ ${e.popularity.toLocaleString()}` : undefined,
};
}),
actions: ["install", "uninstall", "refine", "load-more", "cancel"] as const,
hasMore: args.hasMore,
hint: "type filter · ↑↓ pick · ⏎ install/toggle · PgDn load more · esc close",
};
}
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, pickerPorts }: 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 doUninstall = useCallback(
async (entry: RegistryEntry, installed: string) => {
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`);
}
},
[postInfo, reloadMcp],
);
const doInstall = useCallback(
async (entry: RegistryEntry) => {
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}` }));
}
},
[postInfo, reloadMcp],
);
const installOrToggle = useCallback(
async (entry: RegistryEntry) => {
const installed = isInstalled(state.installedSpecs, entry);
if (installed) await doUninstall(entry, installed);
else await doInstall(entry);
},
[state.installedSpecs, doInstall, doUninstall],
);
const pickerSnapshot = useMemo(
() =>
buildMarketplacePickerSnapshot({
filtered,
installedSpecs: state.installedSpecs,
query: state.query,
status: state.status,
hasMore: state.handle?.cache.pagination.nextCursor != null,
}),
[filtered, state.installedSpecs, state.handle, state.query, state.status],
);
usePickerBroadcast(
!!pickerPorts,
{ ...pickerSnapshot, actions: [...pickerSnapshot.actions] },
(res) => {
if (res.action === "cancel") return onClose();
if (res.action === "refine") {
setState((s) => ({ ...s, query: res.query, selected: 0 }));
return;
}
if (res.action === "load-more") {
void fetchMore();
return;
}
if (res.action === "install") {
const entry = state.handle?.cache.entries.find((e) => e.name === res.id);
if (!entry) return;
if (isInstalled(state.installedSpecs, entry)) {
setState((s) => ({ ...s, status: `already installed: ${entry.name}` }));
return;
}
void doInstall(entry);
return;
}
if (res.action === "uninstall") {
const entry = state.handle?.cache.entries.find((e) => e.name === res.id);
if (!entry) return;
const installed = isInstalled(state.installedSpecs, entry);
if (!installed) {
setState((s) => ({ ...s, status: `not installed: ${entry.name}` }));
return;
}
void doUninstall(entry, installed);
}
},
pickerPorts ?? {
broadcast: () => undefined,
resolverRef: { current: null },
snapshotRef: { current: null },
},
);
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>
);
}
+219
View File
@@ -0,0 +1,219 @@
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 { PRESETS, PRESET_DESCRIPTIONS } from "./presets.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: "preset"; name: "auto" | "flash" | "pro" }
| { 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;
/** Used to detect which preset (if any) the loop currently matches. */
currentEffort: "high" | "max";
currentAutoEscalate: boolean;
onChoose: (outcome: ModelPickerOutcome) => void;
/** Triggers a refetch when the catalog is null/empty and the user presses [r]. */
onRefresh?: () => void;
}
const PAGE_MARGIN = 8;
const PRESET_NAMES = ["auto", "flash", "pro"] as const;
type PresetName = (typeof PRESET_NAMES)[number];
type Row = { kind: "preset"; name: PresetName } | { kind: "model"; id: string };
export function ModelPicker({
models,
current,
currentEffort,
currentAutoEscalate,
onChoose,
onRefresh,
}: ModelPickerProps): React.ReactElement {
const modelList = (models && models.length > 0 ? models : FALLBACK_MODELS).slice();
if (!modelList.includes(current)) modelList.unshift(current);
const presetRows: Row[] = PRESET_NAMES.map((name) => ({ kind: "preset", name }));
const modelRows: Row[] = modelList.map((id) => ({ kind: "model", id }));
const rows: Row[] = [...presetRows, ...modelRows];
const activePreset = detectActivePreset(current, currentEffort, currentAutoEscalate);
const initialIndex = activePreset
? PRESET_NAMES.indexOf(activePreset)
: presetRows.length + Math.max(0, modelList.indexOf(current));
const [focus, setFocus] = useState(initialIndex);
const { stdout } = useStdout();
const termRows = stdout?.rows ?? 40;
const visibleCount = Math.max(6, termRows - 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(rows.length - 1, f + 1));
if (ev.return) {
const target = rows[focus];
if (!target) return;
if (target.kind === "preset") return onChoose({ kind: "preset", name: target.name });
return onChoose({ kind: "select", id: target.id });
}
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), rows.length - visibleCount),
);
const end = Math.min(rows.length, start + visibleCount);
const shown = rows.slice(start, end);
const hiddenAbove = start;
const hiddenBelow = rows.length - end;
const loading = models === null;
const empty = models !== null && models.length === 0;
let lastSection: "preset" | "model" | null = null;
return (
<Box flexDirection="column" marginY={1}>
<Box>
<Text bold color={TONE.brand}>
{" ◈ REASONIX · pick a setup "}
</Text>
<Text color={FG.meta}>
{loading
? " · loading catalog…"
: empty
? " · catalog empty — using known fallbacks"
: ` · ${modelList.length} models available`}
</Text>
</Box>
<Box height={1} />
{hiddenAbove > 0 ? (
<Box>
<Text color={FG.faint}>{` … ${hiddenAbove} earlier`}</Text>
</Box>
) : null}
{shown.map((row, i) => {
const idx = start + i;
const focused = idx === focus;
const showHeader = row.kind !== lastSection;
lastSection = row.kind;
const header = showHeader ? (
<Box key={`hdr-${row.kind}`} marginTop={idx === 0 ? 0 : 1}>
<Text color={FG.meta}>
{row.kind === "preset"
? " PRESETS · recommended — model + effort + auto-escalate"
: " MODELS · raw pick — auto-escalate stays as-is"}
</Text>
</Box>
) : null;
const body =
row.kind === "preset" ? (
<PresetRow
key={`p-${row.name}`}
name={row.name}
focused={focused}
active={activePreset === row.name}
/>
) : (
<ModelRow
key={`m-${row.id}`}
id={row.id}
focused={focused}
active={!activePreset && row.id === current}
/>
);
return (
<React.Fragment key={`row-${idx}`}>
{header}
{body}
</React.Fragment>
);
})}
{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 PresetRow({
name,
focused,
active,
}: {
name: PresetName;
focused: boolean;
active: boolean;
}): React.ReactElement {
const desc = PRESET_DESCRIPTIONS[name];
return (
<Box>
<Text color={focused ? TONE.brand : FG.faint}>{focused ? " ▸ " : " "}</Text>
<Text bold={focused} color={focused ? FG.strong : FG.sub}>
{name.padEnd(8)}
</Text>
<Text color={focused ? FG.body : FG.meta}>{desc.headline.padEnd(28)}</Text>
<Text color={FG.meta}>{` ${desc.cost}`}</Text>
{active ? <Text color={TONE.brand}>{" · current"}</Text> : null}
</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>
);
}
function detectActivePreset(
model: string,
effort: "high" | "max",
autoEscalate: boolean,
): PresetName | null {
for (const name of PRESET_NAMES) {
const p = PRESETS[name];
if (p.model === model && p.reasoningEffort === effort && p.autoEscalate === autoEscalate) {
return name;
}
}
return null;
}
/** 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",
];
-1
View File
@@ -1,7 +1,6 @@
/** Modal picker for `PlanCheckpointError`: continue / revise / stop. */
import { Box } 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, type StepStatus } from "./PlanStepList.js";
+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
+10 -1
View File
@@ -6,7 +6,7 @@ import { CARD, FG } from "./theme/tokens.js";
import { useTick } from "./ticker.js";
export interface PlanRefineInputProps {
mode: "approve" | "refine" | "checkpoint-revise" | "choice-custom";
mode: "approve" | "refine" | "reject" | "checkpoint-revise" | "choice-custom";
onSubmit: (feedback: string) => void;
onCancel: () => void;
}
@@ -37,6 +37,15 @@ const MODES: Record<PlanRefineInputProps["mode"], ModeMeta> = {
hint: "Describe what's wrong or missing, or answer questions the plan raised.",
blankHint: " (Enter with blank = ask the model to list concrete questions.)",
},
reject: {
title: "rejecting — tell the model why (optional)",
glyph: "✗",
tone: "error",
cursorColor: CARD.error.color,
hint: "Say what the model got wrong about your goal, or what you actually want instead.",
blankHint:
" (Enter with blank = cancel without explanation; the model will ask what you want.)",
},
"checkpoint-revise": {
title: "revising — what should change before the next step?",
glyph: "✎",
-52
View File
@@ -1,52 +0,0 @@
/**
* Shared Ink block that renders a TypedPlanState. Used by RecordView in
* replay/diff TUIs.
*
* Colors are semantic (not decorative):
* - subgoals: cyan — structure / plan
* - hypotheses: green — current beliefs (like assistant)
* - uncertainties: yellow — attention required (like tool)
* - rejected paths: red dim — ruled out (muted, like error-but-resolved)
*
* Visual: colored bold label + count, then dim items. No solid-bg pill
* — every assistant turn surfaces this block, so the bracket-text style
* keeps it from shouting four colored bg blocks at the user every turn.
* Color alone (the bold label) is enough to identify the field type.
*/
import { Box, Text } from "ink";
import React from "react";
import type { TypedPlanState } from "../../harvest.js";
import { COLOR } from "./theme.js";
type FieldColor = string;
export function PlanStateBlock({ planState }: { planState: TypedPlanState }) {
const fields: Array<[string, string[], FieldColor, boolean]> = [];
if (planState.subgoals.length)
fields.push(["subgoals", planState.subgoals, COLOR.primary, false]);
if (planState.hypotheses.length)
fields.push(["hypotheses", planState.hypotheses, COLOR.assistant, false]);
if (planState.uncertainties.length)
fields.push(["uncertainties", planState.uncertainties, COLOR.warn, false]);
if (planState.rejectedPaths.length)
fields.push(["rejected", planState.rejectedPaths, COLOR.info, true]);
if (fields.length === 0) return null;
return (
<Box flexDirection="column" marginBottom={1}>
{fields.map(([label, items, color, dim]) => (
<Box key={label}>
<Text color={color} bold dimColor={dim}>
{label}
</Text>
<Text dimColor>{` (${items.length})`}</Text>
<Text dimColor>{" · "}</Text>
<Text dimColor={dim} color={dim ? undefined : COLOR.info}>
{items.join(" · ")}
</Text>
</Box>
))}
</Box>
);
}
+48 -18
View File
@@ -19,18 +19,20 @@ import { FG, SURFACE, TONE } from "./theme/tokens.js";
/** Raw-stdin keystroke bus → multiline reducer; one logical line per Box row, viewport-clipped. */
/** Pastes shorter than this AND single-line render verbatim; longer ones become a `[paste #N · …]` sentinel chip (#397). */
export const INLINE_PASTE_THRESHOLD = 200;
export function shouldInlinePaste(content: string): boolean {
return !content.includes("\n") && content.length <= INLINE_PASTE_THRESHOLD;
}
export interface PromptInputProps {
value: string;
onChange: (v: string) => void;
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.
*/
/** ↑/↓ on an empty buffer or Ctrl+P / Ctrl+N — parent walks history and swaps `value` via `onChange`. */
onHistoryPrev?: () => void;
onHistoryNext?: () => void;
}
@@ -45,8 +47,12 @@ export function PromptInput({
onHistoryNext,
}: 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);
@@ -70,15 +76,19 @@ export function PromptInput({
const registerPaste = (content: string) => {
const v = lastLocalValueRef.current;
const c = cursorRef.current;
const id = nextPasteIdRef.current % PASTE_SENTINEL_RANGE;
nextPasteIdRef.current = id + 1;
pastesRef.current.set(id, makePasteEntry(id, content));
const sentinel = encodePasteSentinel(id);
const next = v.slice(0, c) + sentinel + v.slice(c);
const insertion = shouldInlinePaste(content)
? content
: (() => {
const id = nextPasteIdRef.current % PASTE_SENTINEL_RANGE;
nextPasteIdRef.current = id + 1;
pastesRef.current.set(id, makePasteEntry(id, content));
return encodePasteSentinel(id);
})();
const next = v.slice(0, c) + insertion + v.slice(c);
lastLocalValueRef.current = next;
cursorRef.current = c + 1;
cursorRef.current = c + insertion.length;
onChange(next);
setCursor(c + 1);
setCursor(c + insertion.length);
};
useKeystroke((ev) => {
@@ -146,7 +156,7 @@ export function PromptInput({
// a just-cleared buffer and read as residual typed input on dim-poor terminals.
const effectivePlaceholder = disabled
? (placeholder ?? "…waiting for response…")
: (placeholder ?? "type a message · slash for commands · at-sign for files");
: (placeholder ?? "ask anything · slash for commands · at-sign for files");
const lines = value.length > 0 ? value.split("\n") : [""];
const accentColor = disabled ? FG.faint : TONE.brand;
@@ -278,9 +288,7 @@ export function PromptInput({
) : null}
{!disabled ? (
<Box marginTop={1}>
<Text color={FG.faint}>
{" ⏎ send · shift/alt+⏎ newline · ↑↓ history · esc abort · ctrl-c quit"}
</Text>
<HintRow />
</Box>
) : (
<Box marginTop={1}>
@@ -291,6 +299,28 @@ export function PromptInput({
);
}
function HintRow(): React.ReactElement {
const items: Array<{ key: string; sep: string }> = [
{ key: "⏎", sep: "send" },
{ key: "⇧⏎", sep: "newline" },
{ key: "↑↓", sep: "history" },
{ key: "esc", sep: "abort" },
{ key: "^C", sep: "quit" },
];
return (
<Box flexDirection="row">
<Text>{" "}</Text>
{items.map((item, i) => (
<React.Fragment key={item.key}>
{i > 0 && <Text color={FG.faint}>{" · "}</Text>}
<Text color={FG.meta}>{item.key}</Text>
<Text color={FG.faint}>{` ${item.sep}`}</Text>
</React.Fragment>
))}
</Box>
);
}
type LineSegment =
| { kind: "text"; text: string; startOffset: number }
| { kind: "paste"; id: number; startOffset: number };
+1 -11
View File
@@ -1,17 +1,8 @@
/**
* Shared renderer for a single TranscriptRecord. Used by ReplayApp and
* DiffApp — both need the same visual grammar (user cyan, assistant green,
* tool yellow, error red, cache badge colored by threshold) so transcripts
* look consistent wherever they're displayed.
*
* Kept small on purpose: no streaming/branch/planState paths (those are
* live-chat concerns and never appear in replayed transcripts).
*/
/** Shared renderer for a single TranscriptRecord — used by ReplayApp and DiffApp. */
import { Box, Text } from "ink";
import React from "react";
import type { TranscriptRecord } from "../../transcript/log.js";
import { PlanStateBlock } from "./PlanStateBlock.js";
export interface RecordViewProps {
rec: TranscriptRecord;
@@ -58,7 +49,6 @@ export function RecordView({ rec, compact = false }: RecordViewProps) {
) : null}
{rec.usage ? <CacheBadge usage={rec.usage} /> : null}
</Box>
{rec.planState ? <PlanStateBlock planState={rec.planState} /> : null}
{rec.content ? (
<Text>{rec.content}</Text>
) : (
+15 -4
View File
@@ -3,7 +3,7 @@
import { Box, Text } from "ink";
import React, { useState } from "react";
import { useKeystroke } from "./keystroke-context.js";
import { COLOR } from "./theme.js";
import { type UiColor, useColor } from "./theme.js";
export interface SelectItem<V extends string = string> {
value: V;
@@ -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,9 +29,11 @@ export function SingleSelect<V extends string>({
items,
initialValue,
onSubmit,
onTab,
onCancel,
footer,
}: SingleSelectProps<V>) {
const color = useColor();
const initialIndex = Math.max(
0,
items.findIndex((i) => i.value === initialValue && !i.disabled),
@@ -45,6 +49,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();
}
@@ -58,6 +65,7 @@ export function SingleSelect<V extends string>({
item={item}
active={i === index}
marker={i === index ? "▸" : " "}
color={color}
/>
))}
{footer ? (
@@ -85,6 +93,7 @@ export function MultiSelect<V extends string>({
onCancel,
footer,
}: MultiSelectProps<V>) {
const color = useColor();
const [index, setIndex] = useState(() => {
const first = items.findIndex((i) => !i.disabled);
return first === -1 ? 0 : first;
@@ -107,7 +116,6 @@ export function MultiSelect<V extends string>({
return next;
});
} else if (ev.return) {
// Catalog order keeps the resulting config.json diff stable across reruns.
const ordered = items.filter((i) => selected.has(i.value)).map((i) => i.value);
onSubmit(ordered);
} else if (ev.escape && onCancel) {
@@ -126,6 +134,7 @@ export function MultiSelect<V extends string>({
item={item}
active={i === index}
marker={`${i === index ? "▸" : " "} ${marker}`}
color={color}
/>
);
})}
@@ -142,16 +151,18 @@ function SelectRow<V extends string>({
item,
active,
marker,
color,
}: {
item: SelectItem<V>;
active: boolean;
marker: string;
color: UiColor;
}) {
const color = item.disabled ? COLOR.info : active ? COLOR.primary : undefined;
const rowColor = item.disabled ? color.info : active ? color.primary : undefined;
return (
<Box flexDirection="column">
<Box>
<Text color={color} bold={active} dimColor={item.disabled}>
<Text color={rowColor} bold={active} dimColor={item.disabled}>
{marker} {item.label}
</Text>
</Box>
+74 -9
View File
@@ -1,9 +1,10 @@
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 React, { useMemo, useState } from "react";
import type { SessionInfo } from "../../memory/session.js";
import { type PickerBroadcastPorts, usePickerBroadcast } from "./dashboard/use-picker-broadcast.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 +17,10 @@ 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;
/** When provided, broadcasts to the web dashboard so it can resolve via `/api/modal/resolve`. */
pickerPorts?: PickerBroadcastPorts;
}
const PAGE_MARGIN = 6;
@@ -24,6 +29,8 @@ export function SessionPicker({
sessions,
workspace,
onChoose,
walletCurrency,
pickerPorts,
}: SessionPickerProps): React.ReactElement {
const [focus, setFocus] = useState(0);
const [renaming, setRenaming] = useState<{ from: string; buf: string } | null>(null);
@@ -31,6 +38,53 @@ export function SessionPicker({
const rows = stdout?.rows ?? 40;
const visibleCount = Math.max(3, rows - PAGE_MARGIN);
const snapshot = useMemo(
() => ({
pickerKind: "sessions",
title: `pick a session — ${workspace}`,
items: sessions.map((s) => {
const branch = s.meta.branch ?? "main";
const summary =
s.meta.summary ?? `${s.messageCount} message${s.messageCount === 1 ? "" : "s"}`;
const turns = s.meta.turnCount ?? Math.ceil(s.messageCount / 2);
const currency = walletCurrency ?? s.meta.balanceCurrency;
const costLabel =
s.meta.totalCostUsd !== undefined ? formatCost(s.meta.totalCostUsd, currency, 2) : "";
return {
id: s.name,
title: s.name,
subtitle: summary,
badge: branch,
meta: costLabel ? `${turns} turns · ${costLabel}` : `${turns} turns`,
};
}),
actions: ["pick", "delete", "rename", "new", "cancel"] as const,
hint: "↑↓ pick · ⏎ open · [n] new · [d] delete · [r] rename · esc quit",
}),
[sessions, workspace, walletCurrency],
);
usePickerBroadcast(
!!pickerPorts,
{
...snapshot,
actions: [...snapshot.actions],
},
(res) => {
if (res.action === "pick") return onChoose({ kind: "open", name: res.id });
if (res.action === "delete") return onChoose({ kind: "delete", name: res.id });
if (res.action === "rename")
return onChoose({ kind: "rename", name: res.id, newName: res.text });
if (res.action === "new") return onChoose({ kind: "new" });
if (res.action === "cancel") return onChoose({ kind: "quit" });
},
pickerPorts ?? {
broadcast: () => undefined,
resolverRef: { current: null },
snapshotRef: { current: null },
},
);
useKeystroke((ev) => {
if (ev.paste) {
if (renaming) setRenaming({ ...renaming, buf: renaming.buf + ev.input });
@@ -101,7 +155,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 +196,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 +221,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>
);
}
+2 -2
View File
@@ -1,7 +1,7 @@
import { Box, Text, useApp } from "ink";
import TextInput from "ink-text-input";
import React, { useState } from "react";
import { defaultConfigPath, isPlausibleKey, redactKey, saveApiKey } from "../../config.js";
import { MaskedInput } from "./MaskedInput.js";
import { COLOR, GLYPH, GRADIENT } from "./theme.js";
export interface SetupProps {
@@ -63,7 +63,7 @@ export function Setup({ onReady }: SetupProps) {
<Text bold color={COLOR.primary}>
{" › "}
</Text>
<TextInput
<MaskedInput
value={value}
onChange={setValue}
onSubmit={handleSubmit}
+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>
+9 -12
View File
@@ -2,7 +2,7 @@ import { Box, Text } from "ink";
// biome-ignore lint/style/useImportType: tsconfig.jsx = "react" needs React in value scope for JSX compilation
import React from "react";
import type { SlashCommandSpec } from "./slash.js";
import { COLOR, GLYPH } from "./theme.js";
import { GLYPH, useColor } from "./theme.js";
export interface SlashArgPickerProps {
/**
@@ -37,16 +37,13 @@ export function SlashArgPicker({
kind,
partial,
}: SlashArgPickerProps): React.ReactElement | null {
// Header row shared by both hint and picker modes — same shape so
// the UI looks like the same affordance, just with or without rows
// beneath. cmd in accent violet (matches SlashSuggestions), argsHint
// in dim, summary in info.
const color = useColor();
const headerRow = (
<Box>
<Text color={COLOR.accent} bold>
<Text color={color.accent} bold>
{"/ "}
</Text>
<Text color={COLOR.accent} bold>
<Text color={color.accent} bold>
{`/${spec.cmd}`}
</Text>
{spec.argsHint ? <Text dimColor>{` ${spec.argsHint}`}</Text> : null}
@@ -54,7 +51,6 @@ export function SlashArgPicker({
</Box>
);
// Hint mode: header only.
if (kind === "hint") {
return (
<Box paddingX={1} marginTop={1}>
@@ -69,10 +65,10 @@ export function SlashArgPicker({
<Box flexDirection="column" paddingX={1} marginTop={1}>
{headerRow}
<Box>
<Text color={COLOR.warn} bold>
<Text color={color.warn} bold>
{GLYPH.warn}
</Text>
<Text color={COLOR.warn}>{` no match for "${partial}"`}</Text>
<Text color={color.warn}>{` no match for "${partial}"`}</Text>
<Text dimColor>{" — keep typing, or Backspace to edit"}</Text>
</Box>
</Box>
@@ -102,12 +98,13 @@ export function SlashArgPicker({
}
function ArgRow({ value, isSelected }: { value: string; isSelected: boolean }) {
const color = useColor();
return (
<Box>
<Text color={isSelected ? COLOR.primary : COLOR.info} bold={isSelected}>
<Text color={isSelected ? color.primary : color.info} bold={isSelected}>
{isSelected ? `${GLYPH.cur} ` : " "}
</Text>
<Text color={isSelected ? COLOR.user : COLOR.info} bold={isSelected} dimColor={!isSelected}>
<Text color={isSelected ? color.user : color.info} bold={isSelected} dimColor={!isSelected}>
{value}
</Text>
</Box>
+58 -39
View File
@@ -1,77 +1,90 @@
import { Box, Text } from "ink";
// biome-ignore lint/style/useImportType: tsconfig.jsx = "react" needs React in value scope for JSX compilation
import React from "react";
import type { SlashCommandSpec } from "./slash.js";
import { COLOR, GLYPH } from "./theme.js";
import { t } from "../../i18n/index.js";
import type { SlashCommandSpec, SlashGroup } from "./slash.js";
import { GLYPH, useColor } from "./theme.js";
export interface SlashSuggestionsProps {
/**
* Current matching suggestions, computed by the parent. `null` means
* "not in slash-prefix mode" — render nothing. Empty array means "in
* slash mode but no matches" — render the "no matches" hint.
*/
matches: SlashCommandSpec[] | null;
/** Index (within `matches`) of the currently highlighted row. */
selectedIndex: number;
/** True when input is a bare `/` — render section headers + advanced footer. */
groupMode?: boolean;
/** Count of hidden `advanced` commands; rendered as a footer hint when groupMode is true. */
advancedHidden?: number;
}
/**
* Slash-command palette. Rendered below the input box while the user
* is typing a `/…` prefix. Visual grammar matches the design doc's
* picker style:
*
* / suggestions esc cancel
* ▸ /checkpoint [name] snapshot the workspace
* /restore <name> roll back files to a checkpoint
* /diff cumulative diff vs session start
* [↑↓] navigate · [Tab/⏎] pick
*
* Cmd tokens render in accent violet (one consistent color for "this
* is a command"), descriptions in dim info color. The selected row
* gets a leading ▸ + bold cmd; non-selected rows get a 2-space pad in
* the same column so the cmd column stays aligned. No solid-bg pill —
* the bracket-text pattern from the chrome carries through here.
*/
const GROUP_LABEL: Record<SlashGroup, string> = {
chat: "CHAT",
setup: "SETUP",
info: "INFO",
session: "SESSION",
extend: "EXTEND",
code: "CODE",
jobs: "JOBS",
advanced: "ADVANCED",
};
export function SlashSuggestions({
matches,
selectedIndex,
groupMode,
advancedHidden,
}: SlashSuggestionsProps): React.ReactElement | null {
const color = useColor();
if (matches === null) return null;
if (matches.length === 0) {
return (
<Box paddingX={1} marginTop={1}>
<Text color={COLOR.warn} bold>
<Text color={color.warn} bold>
{GLYPH.warn}
</Text>
<Text> </Text>
<Text color={COLOR.warn}>no slash command matches that prefix</Text>
<Text color={color.warn}>no slash command matches that prefix</Text>
<Text dimColor>{" — Backspace to edit, or /help for the full list"}</Text>
</Box>
);
}
// Limit rows so the suggestion list never dwarfs the rest of the
// UI. Keep the currently-selected row in view by sliding the
// window when the selection is near either edge.
const MAX = 8;
const MAX = groupMode ? 24 : 8;
const total = matches.length;
const windowStart =
total <= MAX ? 0 : Math.max(0, Math.min(selectedIndex - Math.floor(MAX / 2), total - MAX));
const shown = matches.slice(windowStart, windowStart + MAX);
const hiddenAbove = windowStart;
const hiddenBelow = total - windowStart - shown.length;
let lastGroup: SlashGroup | null = null;
if (windowStart > 0) lastGroup = matches[windowStart - 1]?.group ?? null;
return (
<Box flexDirection="column" paddingX={1} marginTop={1}>
<Box>
<Text color={COLOR.accent} bold>
<Text color={color.accent} bold>
{"/ "}
</Text>
<Text dimColor>{`${total} command${total === 1 ? "" : "s"}`}</Text>
{hiddenAbove > 0 ? <Text dimColor>{` ↑ ${hiddenAbove} above`}</Text> : null}
</Box>
{shown.map((spec, i) => (
<SuggestionRow key={spec.cmd} spec={spec} isSelected={windowStart + i === selectedIndex} />
))}
{shown.map((spec, i) => {
const idx = windowStart + i;
const showHeader = groupMode && spec.group !== lastGroup;
lastGroup = spec.group;
return (
<React.Fragment key={spec.cmd}>
{showHeader ? (
<Box marginTop={idx === 0 ? 0 : 1}>
<Text dimColor>{` ${GROUP_LABEL[spec.group]}`}</Text>
</Box>
) : null}
<SuggestionRow spec={spec} isSelected={idx === selectedIndex} />
</React.Fragment>
);
})}
{hiddenBelow > 0 ? <Text dimColor>{` ↓ ${hiddenBelow} below`}</Text> : null}
{groupMode && advancedHidden && advancedHidden > 0 ? (
<Box marginTop={1}>
<Text dimColor>{` + ${advancedHidden} advanced · type a letter to search`}</Text>
</Box>
) : null}
<Box marginTop={0}>
<Text dimColor>{" ↑↓ navigate · Tab / ⏎ pick · esc cancel"}</Text>
</Box>
@@ -80,21 +93,27 @@ export function SlashSuggestions({
}
function SuggestionRow({ spec, isSelected }: { spec: SlashCommandSpec; isSelected: boolean }) {
const color = useColor();
const name = `/${spec.cmd}`;
const argsSuffix = spec.argsHint ? spec.argsHint : "";
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}>
<Text color={isSelected ? color.primary : color.info} bold={isSelected}>
{isSelected ? `${GLYPH.cur} ` : " "}
</Text>
<Text color={COLOR.accent} bold={isSelected}>
<Text color={color.accent} bold={isSelected}>
{name.padEnd(14)}
</Text>
<Text dimColor>{argsSuffix.padEnd(14)}</Text>
<Text>{" "}</Text>
<Text color={isSelected ? COLOR.user : COLOR.info} dimColor={!isSelected}>
{spec.summary}
<Text 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}` : "";
+54 -106
View File
@@ -1,144 +1,92 @@
/** Empty-session welcome card — sharp ASCII box + tagline + 4 starter slash commands. */
/** Empty-session welcome card — REASONIX × 🐋 DeepSeek brand row + tagline + starter slash commands. */
import { Box, Text, useStdout } from "ink";
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 { t } from "../../i18n/index.js";
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. */
languageVersion?: number;
}
const TAGLINE_CHAT = "DeepSeek-native agent";
const TAGLINE_CODE = "DeepSeek-native coding agent";
const TAGLINE_SUB = "cache-first · flash-first";
const HINTS = ["/help", "/init", "/memory", "/cost"] as const;
const BOX_INNER_WIDTH = 35;
export function WelcomeBanner({
inCodeMode,
workspaceRoot,
dashboardUrl,
}: WelcomeBannerProps): React.ReactElement {
const { stdout } = useStdout();
const cols = stdout?.columns ?? 80;
const tagline = inCodeMode ? TAGLINE_CODE : TAGLINE_CHAT;
const boxWidth = BOX_INNER_WIDTH + 2;
const boxIndent = Math.max(2, Math.floor((cols - boxWidth) / 2));
const top = `╔${"═".repeat(BOX_INNER_WIDTH)}╗`;
const bot = `╚${"═".repeat(BOX_INNER_WIDTH)}╝`;
const hintsRow = HINTS.join(" · ");
const hintsIndent = Math.max(2, Math.floor((cols - hintsRow.length) / 2));
const startTextRaw = "type a message to start your session";
const startIndent = Math.max(2, Math.floor((cols - startTextRaw.length) / 2));
const tagline = inCodeMode ? t("ui.taglineCode") : t("ui.taglineChat");
const taglineSub = t("ui.taglineSub");
const startTextRaw = t("ui.startSessionHint");
return (
<Box flexDirection="column" marginY={1}>
<BoxRow indent={boxIndent}>
<Text color={TONE.brand}>{top}</Text>
</BoxRow>
<BoxRow indent={boxIndent}>
<BoxLine pad={BOX_INNER_WIDTH}>{""}</BoxLine>
</BoxRow>
<BoxRow indent={boxIndent}>
<BoxLine pad={BOX_INNER_WIDTH}>
<Text bold color={TONE.brand}>
{centerInside("◈ REASONIX", BOX_INNER_WIDTH)}
<Box flexDirection="column" alignItems="center" marginY={1}>
<Box
flexDirection="column"
alignItems="center"
borderStyle="round"
borderColor={TONE.brand}
paddingX={4}
paddingY={1}
>
<Box flexDirection="row" gap={2}>
<Text color={TONE.brand} bold>
{"REASONIX"}
</Text>
</BoxLine>
</BoxRow>
<BoxRow indent={boxIndent}>
<BoxLine pad={BOX_INNER_WIDTH}>{""}</BoxLine>
</BoxRow>
<BoxRow indent={boxIndent}>
<BoxLine pad={BOX_INNER_WIDTH}>
<Text color={FG.sub}>{centerInside(tagline, BOX_INNER_WIDTH)}</Text>
</BoxLine>
</BoxRow>
<BoxRow indent={boxIndent}>
<BoxLine pad={BOX_INNER_WIDTH}>
<Text color={FG.meta}>{centerInside(TAGLINE_SUB, BOX_INNER_WIDTH)}</Text>
</BoxLine>
</BoxRow>
<BoxRow indent={boxIndent}>
<BoxLine pad={BOX_INNER_WIDTH}>{""}</BoxLine>
</BoxRow>
<BoxRow indent={boxIndent}>
<Text color={TONE.brand}>{bot}</Text>
</BoxRow>
<Text color={FG.faint}>{"×"}</Text>
<Box flexDirection="row" gap={1}>
<Text>{"🐋"}</Text>
<Text color={TONE.accent} bold>
{"DeepSeek"}
</Text>
</Box>
</Box>
<Box marginTop={1} flexDirection="column" alignItems="center">
<Text color={FG.body}>{tagline}</Text>
<Text color={FG.meta}>{taglineSub}</Text>
</Box>
</Box>
<Box marginTop={1}>
<Text>{" ".repeat(startIndent)}</Text>
<Text color={FG.sub}>{startTextRaw}</Text>
</Box>
<Box marginTop={1}>
<Text>{" ".repeat(hintsIndent)}</Text>
{HINTS.map((cmd, i) => (
<React.Fragment key={cmd}>
<Text color={FG.meta}>{cmd}</Text>
{i < HINTS.length - 1 && <Text color={FG.faint}>{" · "}</Text>}
</React.Fragment>
<Box marginTop={1} flexDirection="row" gap={3}>
{HINTS.map((cmd) => (
<Text key={cmd} color={FG.meta}>
{cmd}
</Text>
))}
</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" justifyContent="center">
<Box marginTop={1} flexDirection="row" gap={1}>
<Text color={TONE.brand} bold>
{"▸ web · "}
{"▸ web"}
</Text>
<Text color={FG.faint}>{"·"}</Text>
<Text color={TONE.accent}>{dashboardUrl}</Text>
</Box>
) : null}
</Box>
);
}
function BoxRow({
indent,
children,
}: {
indent: number;
children: React.ReactNode;
}): React.ReactElement {
return (
<Box>
<Text>{" ".repeat(indent)}</Text>
{children}
</Box>
);
}
function BoxLine({
pad,
children,
}: {
pad: number;
children?: React.ReactNode;
}): React.ReactElement {
if (children === "" || children === undefined) {
return (
<>
<Text color={TONE.brand}>{"║"}</Text>
<Text>{" ".repeat(pad)}</Text>
<Text color={TONE.brand}>{"║"}</Text>
</>
);
}
return (
<>
<Text color={TONE.brand}>{"║"}</Text>
{children}
<Text color={TONE.brand}>{"║"}</Text>
</>
);
}
function centerInside(text: string, pad: number): string {
if (text.length >= pad) return text.slice(0, pad);
const left = Math.floor((pad - text.length) / 2);
const right = pad - text.length - left;
return `${" ".repeat(left)}${text}${" ".repeat(right)}`;
}
Loaded 100 of 374 files, more files were not shown because too many files have changed in this diff. Show more