Compare commits

...
27 Commits
Author SHA1 Message Date
esengine 3fee4e6883 feat: reasonix stats — cross-session cost dashboard + /stats slash (0.4.24)
Every turn run through `reasonix chat|code|run` now appends one line
to ~/.reasonix/usage.jsonl carrying tokens + cost + the equivalent
Claude Sonnet 4.6 cost. `reasonix stats` (no arg) rolls that log up
into today / week / month / all-time windows with a "saved vs
Claude" column. Pillar 1's pitch (94–97% cost reduction) becomes a
fact users can check on their own machine.

Same dashboard is available in-session via the new /stats slash,
reading from the same file and rendering through a shared pure
renderer. reasonix stats <transcript> keeps the old per-file
summary (assistant turns + tool calls) for scripts.

Privacy: only tokens, costs, session name. No prompts, completions,
or tool args. Log append is best-effort — disk failure never blocks
a turn.

New files:
  src/usage.ts                 — appendUsage, readUsageLog, aggregateUsage,
                                  bucketCacheHitRatio / SavingsFraction
  tests/usage.test.ts          — 15 tests (round-trip, malformed line,
                                  rolling windows, renderer, zero denom)

Modified:
  src/cli/commands/stats.ts    — dashboard mode + extracted renderDashboard
  src/cli/commands/run.ts      — appendUsage on assistant_final (for CI)
  src/cli/ui/App.tsx           — appendUsage on assistant_final (TUI)
  src/cli/ui/slash.ts          — /stats slash (shared renderer)
  src/cli/index.ts             — `stats <transcript>` → `stats [transcript]`
  src/index.ts                 — re-export usage module

+17 tests (suite 708 → 725). Lint + typecheck + build clean.
2026-04-22 22:24:59 -07:00
esengine 41d21f7cea feat(slash): /update shows current vs latest + shell command (0.4.23)
Adds an in-session `/update` slash that reports the running version
and the last-resolved latest from the App's background npm-registry
check. Deliberately does NOT spawn `npm install` — stdio:inherit
into a running Ink renderer corrupts the display, and on Windows
the currently-running binary can be locked. Users exit and run
`reasonix update` in a fresh shell when they actually want to
install.

Also splits App state: we now track `latestVersion` regardless of
whether it's newer (so the slash can tell "on the latest" apart
from "still fetching") and derive the yellow header badge from
that. Before this, `updateAvailable` was only set on strictly-
newer, so `/update` saw null when the user was already on the
latest — the message misleadingly said "background check in
flight or offline".

`/update` also triggers a fresh `getLatestVersion({force:true})`
when latestVersion is null, so a retry a few seconds later sees
a concrete answer.

4 new tests (suite 704 → 708). All green; lint / typecheck / build
clean.
2026-04-22 22:13:32 -07:00
esengine 715d8b5950 feat: hooks — user-defined automation at PreToolUse / PostToolUse / UserPromptSubmit / Stop (0.4.23)
Same two-scope layout as memory and skills:
  - <project>/.reasonix/settings.json (committable per-project)
  - ~/.reasonix/settings.json         (per-user)

A hook is a shell command. Reasonix invokes it with stdin = a JSON
envelope carrying the event, tool name, tool args, etc. Exit code
drives the decision:
  - 0 = pass; loop continues normally
  - 2 = block (only on PreToolUse / UserPromptSubmit); hook's stderr
    becomes the synthetic tool result the model sees, or the prompt
    is dropped entirely
  - anything else = warn; loop continues, stderr renders inline as a
    yellow row

Project hooks fire before global hooks. `match` is anchored regex on
the tool name (ignored for prompt / Stop events). Default timeouts:
5s for blocking events, 30s for logging events; per-hook `timeout`
overrides. Settings malformed? loadHooks swallows it so a typo
doesn't bring down the whole CLI.

Deliberate non-goals: no workflow DSL, no conditional chaining, no
hook templates. Hooks are shell commands — the user already has a
programming language.

New files:
  - src/hooks.ts                      (loadHooks, runHooks, decideOutcome, matchesTool, formatHookOutcomeMessage)
  - tests/hooks.test.ts               (26 unit tests)
  - tests/loop-hooks.test.ts          (6 smoke tests — loop wiring)

Modified:
  - src/loop.ts          — PreToolUse + PostToolUse dispatch around tool.dispatch
  - src/cli/ui/App.tsx   — load settings on mount, UserPromptSubmit before handleSubmit, Stop after loop.step
  - src/cli/ui/slash.ts  — /hooks list + /hooks reload
  - src/index.ts         — re-exports

+32 tests (suite 672 → 704). Lint / typecheck / build clean.
2026-04-22 22:06:29 -07:00
esengine 911f043db8 feat: version display in TUI header + reasonix update self-upgrade (0.4.22)
Two small quality-of-life additions.

The stats panel now carries the running version (`Reasonix v0.4.22 ·
model …`) so users can tell at a glance whether they're on the latest
build. A 24-hour background check against the npm registry surfaces a
yellow `update: X.Y.Z` nudge on the right side of the same row when a
newer version has been published — 2s timeout, cache at
`~/.reasonix/version-cache.json`, silent on failure.

`reasonix update` is the command form: detects global install vs npx,
spawns `npm install -g reasonix@latest` for the former or prints a
cache-refresh hint for the latter. `--dry-run` prints the plan.

Also fixes a drifted VERSION constant: `src/index.ts` hard-coded
"0.4.20" while package.json was on 0.4.21. Now re-exports from
`src/version.ts`, which walks up from import.meta.url to the
manifest on first access. A regression test pins them together.

New files: `src/version.ts`, `src/cli/commands/update.ts`,
`tests/version.test.ts`, `tests/update-command.test.ts`. +24 tests
(suite 648 → 672). Lint/typecheck/build clean.
2026-04-22 21:34:11 -07:00
esengine ce85319c9b docs(readme): promote reasonix code to the hero section, document skills
- Quick start now leads with `reasonix code` and a real SEARCH/REPLACE
  walkthrough — nobody enters through plain chat.
- New Skills section covers the SKILL.md format, project vs global
  scopes, /skill slash family, autonomous run_skill invocation, and
  the 'not tied to .claude/' stance.
- chat mode demoted to a brief 'also works as' section pointing at MCP.
- Commands table grouped by category (Core / Model / Context & tools /
  Memory & skills / Sessions / Code-mode only) instead of one flat list.
- Benchmarks promoted into their own 'verify yourself' section.
- Non-goals now names workflow DSL / DAG engine and DeepSeek-only
  positioning explicitly.
- Test count 444 → 648, Node requirement 18 → 20.10, added
  REASONIX_UI=plain to the env-var list.
2026-04-22 19:07:44 -07:00
esengine 2a9a9b386b feat: skills — project/global SKILL.md packs pinned into the prefix + shell fixes (0.4.21)
Skills are user-authored prompt packs read from `<project>/.reasonix/skills/`
and `~/.reasonix/skills/`. Pinned index (names + one-liners) lives in
the immutable prefix; bodies load lazily via the new `run_skill` tool
or `/skill <name> [args]`. Project scope wins on name collisions.
Deliberately NOT tied to any other client's dir (.claude/, .glm/) —
Reasonix is model-agnostic at the conversation layer.

No workflow DSL or DAG engine: skills are prose, the model sequences
via the existing tool-use loop. Preserves single-loop + append-only +
cache-first invariants; "no multi-agent orchestration" non-goal stands.

Shell fixes bundled in:
- ShellConfirm "always allow" now takes effect mid-session.
  extraAllowed is re-read on every dispatch via a getter, so a prefix
  saved to ~/.reasonix/config.json applies to the running tool
  without needing /new or a relaunch.
- Windows cmd.exe built-ins (dir, echo, type, ver, ...) no longer
  crash with ENOENT. prepareSpawn routes bare unresolved Windows
  commands through `cmd.exe /d /s /c` with verbatim-args quoting,
  matching the wrapping strategy for .cmd/.bat files.
2026-04-22 18:58:48 -07:00
esengine e3cfbb58dd feat: user memory — ~/.reasonix/memory/ pinned into the immutable prefix · remember/forget/recall tools · prompt cleanup (0.4.20)
- MemoryStore + applyUserMemory + applyMemoryStack (src/user-memory.ts):
  two scopes — global (cross-project) and project (per sandbox-root sha1).
  Each scope keeps a MEMORY.md index pinned into ImmutablePrefix.system;
  detail files loaded on demand via recall_memory. Byte-stable rewrite
  so identical file sets produce identical prefix hashes.
- remember / forget / recall_memory tools (src/tools/memory.ts) — chat
  mode gets global-only; reasonix code gets both scopes. remember's
  return text is imperative so R1 treats the fact as authoritative on
  the same turn.
- /memory slash extended: list | show <name> | forget <name> |
  clear <scope> confirm. Bare /memory renders REASONIX.md + both
  MEMORY.md blocks together.
- Prompt cleanup: dropped hardcoded dir enumerations, bun/npm examples,
  "待确认" CJK fallback, DSML-hallucination historical note, and
  Linear/Slack type-hint specifics. Principle-only wording + reference
  to the pinned .gitignore block. Net -tokens on every turn.
- README: new "User memory" subsection under REASONIX.md.
- scripts/smoke-memory.mts: 30-assertion end-to-end regression script.
- REASONIX_MEMORY=off now disables every memory source (REASONIX.md +
  user memory) — previous semantics was REASONIX.md only.

Tests: 542 → 624 (+82 incl. 36 memory-layer unit tests). Lint / tsc /
build clean.
2026-04-22 17:30:26 -07:00
esengine becaf487e8 fix(shell): use path.win32.join so CI tests with platform:win32 pass on Linux
CI runs on Linux, where pathMod.join defaults to POSIX (`/`). The
PATHEXT resolver mocks its isFile predicate with back-slashed keys
(`C:\tools\npm.CMD`), so join with POSIX produced `C:\tools/npm.CMD`
and lookups missed, failing 8 tests at origin. The runtime call path
is unaffected either way since the win32 branch is only active when
platform === "win32" anyway — but making the join explicitly win32
also hardens against weird PATHs on Windows where forward slashes
have historically crept in.
2026-04-22 06:38:41 -07:00
esengine 6111d8f621 fix(loop): surface StormBreaker suppression as a visible warning + reset on user turn
A silent storm-break was indistinguishable from a stalled turn — the
model would look like it gave up when really we'd suppressed its
repeat tool call. Now `step()` emits a dedicated warning event when
`report.stormsBroken > 0`, with distinct messages for the two cases:

- All calls suppressed (stuck retry): tell the user the model is
  looping on the same (tool, args) and point them at /retry or
  rewording the instruction. This is the case that used to dead-end
  the turn with nothing on screen.
- Some calls suppressed (one redundant): the rest of the turn
  proceeds; the warning is informational.

Also reset the StormBreaker's sliding window at the top of every
`step()` so a new user message doesn't inherit last turn's repeat
patterns (false-positive blocks on legitimate "try again" flows).

Part of the 0.4.19 batch — tag will be moved to this commit.
2026-04-22 06:35:13 -07:00
esengine d8ba9f9669 fix(shell): Windows — PATHEXT resolution + cmd.exe wrapping for .cmd/.bat (0.4.19)
Two layered fixes so `run_command` actually runs npm/npx/tsc/yarn/
pnpm/bun/pytest and every other Node-ecosystem wrapper on Windows:

1. resolveExecutable() walks PATH × PATHEXT manually — spawn
   with shell:false uses CreateProcess, which ignores PATHEXT, so
   bare `npm` missed `npm.cmd` and ENOENT'd.

2. prepareSpawn() wraps .cmd/.bat via `cmd.exe /d /s /c` with
   windowsVerbatimArguments + per-arg quoteForCmdExe — Node 21.7.3+/
   24 (CVE-2024-27980) refuses direct spawn of .cmd/.bat even with
   shell:false, throwing EINVAL. cmd.exe wrapping with manual
   safe-quoting keeps shell metacharacters (&, |, <, >, etc.) in
   arguments literal so the previous security posture holds.

Unix path unchanged. Suite 566 → 587.
2026-04-22 06:09:11 -07:00
esengine e409e9d8d9 feat: Plan Mode — autonomous plan proposals + /plan gate + answer-questions flow (0.4.18)
submit_plan tool: model proposes a markdown plan for large tasks
(multi-file refactors, ambiguous requests, risky changes). Picker
shows Approve / Refine / Cancel with the plan rendered as live
Markdown, not raw text. Open-questions sections ("Open questions",
"待确认", "Risks", etc.) are detected; default selection flips to
Refine and a yellow hint surfaces.

Both Approve and Refine take an inline text input afterward so the
user can answer the model's open questions or attach last-minute
instructions before the loop resumes. Empty Enter on Approve skips
the extras; empty Enter on Refine tells the model to ask concrete
clarifying questions.

/plan slash flips a dispatch-level read-only gate on the
ToolRegistry — writes + non-allowlisted shell bounce with a refusal
the model reads. Read tools, web_search/fetch, and allowlisted shell
(git status / cargo check / npm test etc.) still work during
exploration. Tool specs stay pinned across the toggle so the DeepSeek
prefix cache doesn't break.

/apply-plan is a fallback that force-approves without the picker,
for cases where the model wrote the plan in assistant text instead
of calling submit_plan.

Suite 542 → 566.
2026-04-22 05:50:28 -07:00
esengine 4d21ca4c4c feat: project memory — REASONIX.md pinned into the immutable prefix (0.4.17)
Drop a REASONIX.md in the project root and its contents are pinned
into the system prompt every session that opens there. Cache-first:
read once, hashed into the prefix fingerprint, no per-turn budget.
/memory prints what's currently pinned; REASONIX_MEMORY=off opts out.

Suite 517 → 542. Re-exported applyProjectMemory / readProjectMemory /
memoryEnabled + PROJECT_MEMORY_FILE / PROJECT_MEMORY_MAX_CHARS for
library consumers that build their own system prompt.
2026-04-22 04:55:06 -07:00
esengine 1ccc1d7e67 feat: run_command shell tool · session picker · ShellConfirm picker · backspace/markdown fixes (0.4.16) 2026-04-22 04:43:17 -07:00
esengine fd344986e8 feat: web_search via Mojeek · cursor editing in prompt · REASONIX_UI=plain · ticker consolidation (0.4.15) 2026-04-22 04:05:25 -07:00
esengine 6ceb73d367 fix(ui): consolidate timers · patchConsole:false · REASONIX_UI=plain opt-out (0.4.14) 2026-04-22 02:35:02 -07:00
esengine dee96f66a2 fix(ui): tool_call_delta progress · reset streamRef per iter · expanded README (0.4.13) 2026-04-22 01:59:44 -07:00
esengine 6b4d8652e4 fix(loop): full tool_calls↔tool pairing validator + auto-compact on context-guard (0.4.12)
Two DeepSeek 400s users hit in succession:
- "insufficient tool messages following tool_calls" on forced
  summary: context-guard appended assistant.tool_calls then bailed
  before dispatching. Fix: strip the tail before forceSummary.
- "tool must be a response to a preceding tool_calls" on the next
  message: partial heals left stray tool messages in the log.

Root fix: healLoadedMessages now runs a full tool_calls↔tool pairing
validator. Any assistant.tool_calls with an incomplete response set
is dropped (with its partial responses); any stray tool message is
dropped. Runs on session load (rewrites the file so damage doesn't
re-surface) AND on every buildMessages call (defensive).

Context-guard now auto-compacts before forcing summary. Previously
80% context meant you lost a turn immediately. Now: try shrinking
oversized tool payloads first; only fall back to forced summary
when nothing's compactable.

Split shrinkOversizedToolResults from healLoadedMessages so
`/compact` (mid-turn) doesn't strip legitimate structural state.

443 tests (+5 new, 4 reshaped).
2026-04-22 01:07:07 -07:00
esengine 5f7d8f238a feat: git-diff edit_file · /new clears context · clearer phase labels (0.4.11)
edit_file now produces a real git-diff-style output:
- LCS line-level diff (unchanged lines as ` ` context, `-/+` only
  for actual changes). Fixes the user-reported case where a one-line
  search with a multi-line replace showed the unchanged line as both
  `-` and `+`.
- Git-style @@ -start,count +start,count @@ hunk header pointing at
  the real starting line in the file.
- EventLog no longer truncates edit_file results — other tools keep
  the 400-char clip, but edit diffs always show full.

Context management:
- /new (alias /reset) drops the in-memory log AND empties the
  session file. Fresh conversation, same session/model/config.
- /clear now advertises that it only clears visible scrollback;
  users kept expecting it to clear context. Info line points at
  /new for the real clear.
- CacheFirstLoop.clearLog() is the public API.

Streaming row:
- Replaced "streaming · 391 + think 4506 chars" with explicit
  phase labels: yellow "request sent · waiting for server" pre-
  first-byte, cyan "R1 reasoning · N chars of thought" during
  reasoning-only, green "writing response · N chars · after M
  chars of reasoning" in content phase.

436 tests (+8).
2026-04-22 00:52:13 -07:00
esengine dc38c765e8 feat: status indicators · live stats · balance · in/out cost split · edit_file diff · GFM tables (0.4.10)
Major batch of UX fixes based on user reports:

Silent-wait elimination:
- New "status" loop event + StatusRow component. Fills silent
  phases with explicit magenta spinner text: "tool result uploaded
  · model thinking before next response…" between iters,
  "extracting plan state from reasoning…" before harvest,
  "summarizing what was gathered…" before forced summary. Auto-
  clears on the next primary event.
- Belt-and-suspenders "processing…" fallback when busy but none of
  streaming/ongoingTool/statusLine is visible — catches any
  micro-gap the targeted statuses don't cover.
- Strengthened pre-first-byte messaging: "(request sent · waiting
  for server)" instead of "(streaming · 0 chars)".

Stats panel:
- Live per-iter refresh — previously frozen at prior turn's
  numbers for 30-60s during multi-iter chains.
- Account balance cell. New DeepSeekClient.getBalance() hits
  /user/balance (separate endpoint, no billing impact). Refreshed
  after each turn, hidden on failure.
- In/out cost split. Panel now shows "cost $X (in $Y · out $Z)"
  so users can see where spend lands. SessionSummary gains
  totalInputCostUsd + totalOutputCostUsd; inputCostUsd() and
  outputCostUsd() exposed as library utilities.
- Dropped "vs Claude / saving" cells — the synthetic ratio looked
  like marketing, not measurement. Fields kept in summary for
  benchmark/replay compat but deprecated.

Esc coverage:
- harvest() now takes an AbortSignal and fast-paths to emptyPlanState
  when already aborted. Was the last un-signaled API call path.

edit_file visibility:
- Tool result now returns a unified-style `- search / + replace`
  inline diff in addition to the header. Long blocks are truncated
  with "… (N more lines)" marker in the middle; /tool N still shows
  the full thing.

Markdown:
- GFM tables (|col|col| + separator) render as aligned columns
  with │ dividers. CJK-width-aware padding for mixed-lang tables.
  Alignment colons, pipe-less headers, escaped \| in cells all
  handled. Stray | in prose no longer false-triggers the table
  path.

427 tests (+11).
2026-04-22 00:39:07 -07:00
esengine 59bd38b1aa feat: Esc cancels immediately · native fs tools · cursor fix · slow_count demo (0.4.9)
Three reported issues rolled into one release:

1. Esc now truly cancels in-flight work. AbortController threaded
   through every I/O path:
   - DeepSeekClient.chat/.stream signal wired at every call site
   - ToolRegistry.dispatch gets a ToolCallContext { signal }
   - McpClient.callTool({ signal }) fires notifications/cancelled
     AND rejects the pending promise immediately — no waiting on
     subprocess for a graceful finish
   - bridgeMcpTools forwards ctx.signal down

2. Built-in filesystem tools replace the
   @modelcontextprotocol/server-filesystem subprocess inside
   `reasonix code`. 10 native tools, sandboxed, R1-friendly schemas.
   The new edit_file takes a flat SEARCH/REPLACE shape instead of
   the JSON-in-string array that was the single biggest driver of
   R1 DSML hallucinations in 0.4.x. Per-call latency drops from
   ~500ms–2s (Windows subprocess IPC) to <10ms (direct fs).

3. PromptInput placeholder cursor now renders at position 0
   (before the hint text), not after it.

4. Bonus: slow_count demo tool in examples/mcp-server-demo.ts
   emits real notifications/progress frames so the progress-bar
   plumbing from 0.4.8 is testable end-to-end.

ChatOptions grows `seedTools: ToolRegistry` so callers can
pre-register tools and still layer MCP on top. ToolCallContext
is re-exported for library users writing abortable tools.

416 tests (+29: filesystem-tools +26, mcp abort +3).
2026-04-22 00:14:56 -07:00
esengine 3484c04133 feat(mcp): progress notifications — live progress bar in spinner (0.4.8)
MCP notifications/progress now route to per-call onProgress handlers.
Long-running tool calls can stream incremental progress; the spinner
row renders an ASCII bar + n/total + pct when the server reports a
total, or free-form progress+message otherwise.

- McpClient.callTool(name, args, { onProgress }) mints a fresh
  _meta.progressToken and routes progress frames back. Handler is
  dropped on completion — late frames are swallowed silently.
- bridgeMcpTools({ onProgress }) pipes per-call progress through
  with the registered (prefix-applied) tool name.
- chatCommand creates a shared progressSink ref; App.tsx wires its
  setState handler through on mount.

Other server-initiated notifications (list_changed) still dropped
— no use case yet.

387 tests (+5).
2026-04-21 23:54:11 -07:00
esengine 7075608ddc feat(ux): multi-line prompt input — Ctrl+J · Shift+Enter · '\<Enter>' (0.4.7)
Replaces ink-text-input in the main chat prompt with a custom
multi-line composer. Three newline-insertion paths in reliability
order: Ctrl+J (universal), Shift+Enter (modern terminals), trailing
"\" + Enter (portable fallback). Pasted multi-line content lands
intact instead of submitting on the first '\r'.

Pure processMultilineKey reducer keeps the keyboard semantics
testable; the React component is a thin wrapper. Parent-owned keys
(Tab, arrows, Esc) are no-ops in the reducer so the buffer never
eats a stray control sequence when both useInput listeners fire on
the same event.

Cursor-at-end model (no mid-string edits) — simple, predictable,
and doesn't collide with parent's arrow-key slash-nav + history.
ink-text-input still used by Wizard/Select/Setup — fine for
single-line forms.

382 tests (+18).
2026-04-21 23:47:04 -07:00
esengine 27a32b7b94 feat(ux+mcp): slash autocomplete · drop footer · /mcp rich view · mcp inspect CLI (0.4.6)
UX overhaul:
- Typing `/` pops an IntelliSense-style suggestion list with name +
  args hint + summary. ↑/↓ navigate, Tab completes, Enter picks +
  runs. Registry-driven (SLASH_COMMANDS) with code-mode gating.
- Static command-strip footer under the input is gone — superseded
  by the on-demand slash popup.

MCP discovery:
- /mcp in chat is now a rich per-server view: server info + spec +
  tool count + resources list + prompts list. Unsupported sections
  render "(not supported)" cleanly. Inspection runs once at
  startup and flows through SlashContext.mcpServers.
- New `reasonix mcp inspect <spec>` CLI for running the same
  discovery outside chat (CI, scripting, "does this work?"). --json
  emits the full InspectionReport.
- inspectMcpServer() + InspectionReport are public APIs; McpClient
  gains serverInfo / protocolVersion / serverInstructions getters.

364 tests (+11).
2026-04-21 23:39:48 -07:00
esengine 1391534f6c feat(repair+mcp): DSML scavenge + MCP resources/prompts (0.4.5)
Two protocol-level completions bundled:

1. DSML tool-call recovery. scavengeToolCalls gains a DSML invoke
   parser (<|DSML|invoke>/<|DSML|parameter string="true|false">).
   ToolCallRepair.process now scans both reasoning AND content
   channels — before, DSML in a regular turn was stripped from
   display but the tool never actually ran.

2. MCP resources + prompts. McpClient gains resources/list,
   resources/read, prompts/list, prompts/get with full types and
   cursor pagination. Initialize now advertises all three
   capability families.

353 tests (+13: scavenge +5, pipeline +2, mcp +6).
2026-04-21 22:13:43 -07:00
esengine 169d66d46a feat(ux): /tool slash — inspect untruncated tool output (0.4.4)
EventLog clips tool results at 400 chars for display; /tool [N]
now lets users read the full text. `/tool` lists the 10 most
recent with previews and char counts; `/tool N` dumps the
Nth-most-recent in full. Wired via new SlashContext.toolHistory
callback — pure handleSlash stays stateless.

340 tests (+8 /tool cases).
2026-04-21 21:41:30 -07:00
esengine 2836b5d406 fix(loop): Esc abort no longer blocks for 30-90s + bump to 0.4.3
User feedback: after pressing Esc, the warning fired instantly but
then the TUI blocked for the duration of a full reasoner call
(30-90s) to produce a "summary" the user hadn't asked for. Esc in a
terminal means stop. Stopping and then forcing the expensive
reasoner to wrap up is the opposite of what the user signaled.

Abort path now:
  - Emits a short warning "aborted at iter N/M — stopped without
    producing a summary (press ↑ + Enter or /retry to resume)"
  - Appends a synthetic assistant message "[aborted by user (Esc)
    — no summary produced. Ask again or /retry when ready; prior
    tool output is still in the log.]"
  - Yields assistant_final (tagged forcedSummary so edit applier
    ignores) + done
  - No API call. Takes milliseconds.

Budget and context-guard paths still call forceSummaryAfterIterLimit
because in those cases the loop stopped, not the user — leaving
them staring at nothing would be worse than one extra call. Only
user-initiated abort gets the fast path.

Test rewritten to confirm no extra API call is made (previously
asserted a "partial findings" summary from the never-needed
follow-up). Suite: 332 still passing.

Also bumps to 0.4.3 because v0.4.2 tag is already on origin at
cb2f2a5 with partial content. This release consolidates the full
0.4.2 batch + the Esc fix under one tag.
2026-04-21 21:31:59 -07:00
esengine d0bd6852c1 feat(ux): /retry · /status rich · /think · ↑↓ history · y/n · red errors · tool-row elapsed · reasoning tail · DSML strip (0.4.2)
Nine UX improvements in one batch, all surfaced from real-session
feedback while testing reasonix code against a live filesystem
project.

Added slash commands:
  - /retry — truncate log back before the last user message, resend
    it, get a fresh sample from the model. SlashResult gains a
    resubmit field the TUI honors after displaying info.
  - /status — now a labeled situation-report: model, flags
    (harvest/branch/stream), ctx ratio (42k/131k (32%)) from last
    turn's promptTokens, MCP server + tool counts, session name +
    log length + resumed count, pending edits count. One command
    shows everything.
  - /think (alias /reasoning) — dumps full R1 reasoning from
    loop.scratch.reasoning. For when the 260-char tail preview
    isn't enough. Graceful "no reasoning cached" when using
    deepseek-chat.

Added interactions:
  - ↑/↓ shell-style prompt history. App.tsx owns a ref array, cursor
    advances on arrow keys while idle. Process-scoped, no cross-run
    persistence.
  - y/n fast-path when edits are pending. Typing 'y'+Enter = /apply,
    'n'+Enter = /discard. Scoped: only when pendingEdits.length > 0,
    so plain "y" as a normal message still works when nothing's
    waiting. Preview line advertises the shortcut.

Changed:
  - Tool-running row surfaces elapsed seconds + per-tool argument
    summary. Before: ⠋ tool<filesystem_edit_file> running… {raw
    JSON}. Now: ⠋ tool<filesystem_edit_file> running… 3s / path:
    F:\... (2 edits). Summarizers for read_file, write_file,
    edit_file, list_directory, directory_tree, search_files,
    move_file, get_file_info. Matches suffix so namespaced and
    anonymous servers both work.
  - Reasoning preview shows tail (~260 chars), not head. R1 opens
    every turn with the same scaffolding that hid the actual
    decision in the (+N chars) elision; users reported reasoning
    looked identical across turns. The tail is where the model
    commits to an action.
  - Tool errors render red with ✗ marker instead of yellow with →.
    ERROR: prefix from flattenMcpResult (on isError) is detected.
    A failure needs different attention than a listing.

Fixed:
  - Forced-summary path no longer leaks DSML tool-call markup as
    prose. Passing tools: undefined wasn't enough — R1 primed for
    tool use would still emit <|DSML|function_calls>...</|DSML|
    function_calls> as plain text in content. Two layers: (1)
    inject an explicit user-role instruction at the end of the
    forced-summary message list telling the model to produce prose
    with no tool markup; (2) post-hoc strip known envelopes (DSML
    full-width/ASCII, Anthropic <function_calls>, and truncated
    un-closed DSML openers) from the model's response before
    yielding. stripHallucinatedToolMarkup exported for library
    callers. Fallback message when stripping leaves nothing points
    at /retry and /think.

Tests: +13, suite 319 -> 332.
  - tests/slash.test.ts (+8): /think empty/populated/help,
    /retry happy/empty-log/help, /status new format, /status
    pending-edit suppression at 0.
  - tests/loop-error.test.ts (+5): stripHallucinatedToolMarkup
    against live R1 DSML shape, Anthropic-style, truncated
    un-closed opener, plain prose, all-markup edge case.

Bumps to 0.4.2.
2026-04-21 21:26:42 -07:00
84 changed files with 16523 additions and 541 deletions

No files matched your search

+1468 -4
View File
File diff suppressed because it is too large. Load diff
+631 -219
View File
@@ -6,230 +6,591 @@
[![downloads](https://img.shields.io/npm/dm/reasonix.svg)](https://www.npmjs.com/package/reasonix)
[![node](https://img.shields.io/node/v/reasonix.svg)](./package.json)
**A DeepSeek-native AI coding assistant in your terminal.** Ink TUI. MCP
first-class. No LangChain.
```bash
npx reasonix
```
One command. First run walks you through a 30-second wizard (API key →
preset → pick MCP servers from a checklist); every run after that drops
straight into chat with your tools wired up. Inside the chat, type `/help`.
Why bother with yet another agent framework? Because every abstraction
here earns its weight against a DeepSeek-specific property — dirt-cheap
tokens, R1 reasoning traces, automatic prefix caching, JSON mode.
Generic wrappers treat DeepSeek as "OpenAI with a different base URL"
and leave these advantages on the table. Reasonix leans into them:
on the same τ-bench-lite workload,
[**94.4% cache hit, ~40% cheaper tokens, 100% pass rate**](#validated-numbers)
vs. a cache-hostile baseline.
**A DeepSeek-native AI coding agent in your terminal.** Edits files as
reviewable SEARCH/REPLACE blocks. Ink TUI. MCP first-class. No
LangChain.
---
## What you get
## Quick start (60 seconds)
| Feature | How it works | Opt in |
|---|---|---|
| **Setup wizard** | First run of `npx reasonix`: pick preset, multi-select MCP servers from a curated catalog, saved to config so the next run just launches chat | always on (first run) |
| **MCP (stdio + SSE)** | Multi-server bridge — every MCP tool inherits Cache-First + repair + context-safety automatically. `reasonix mcp list` shows the catalog | always on |
| **Cache-First Loop** | Immutable prefix + append-only log = prefix byte-stable across turns → DeepSeek's automatic prefix cache hits at 70–95% | always on |
| **Context safety net** | Tool results capped at 32k chars · oversized sessions auto-heal on load · `/compact` to shrink further · ctx gauge in the status bar · Esc to abort exploration and get a forced summary | always on |
| **R1 Thought Harvesting** | Parses `reasoning_content` into typed `{ subgoals, hypotheses, uncertainties, rejectedPaths }` via a cheap V3 call | `/preset smart` |
| **Self-Consistency Branching** | Runs N parallel samples at spread temperatures; picks the one with the fewest flagged uncertainties | `/preset max` / `/branch N` |
| **Tool-Call Repair** | Auto-flattens deep/wide schemas, scavenges tool calls leaked into `<think>`, repairs truncated JSON, breaks call-storms | always on |
| **Retry layer** | Exponential backoff + jitter on 408/429/500/502/503/504 and network errors. 4xx auth errors don't retry | always on |
| **Ink TUI** | Live cache-hit / cost / context panel. Streams R1 thinking to a compact preview. Renders Markdown (bold / lists / code / stripped LaTeX) | always on |
**1. Get a DeepSeek API key.** Free credit on signup:
<https://platform.deepseek.com/api_keys>
---
## Why not just use LangChain?
Even on the default `fast` preset (no harvest, no branching), Reasonix bakes
in five DeepSeek-specific defences that generic agent frameworks leave to you:
| | Reasonix default | generic frameworks |
|---|---|---|
| Prefix-stable loop (→ 85–95% cache hit) | ✅ | ❌ prompts rebuilt each turn |
| Auto-flatten deep tool schemas | ✅ | ❌ DeepSeek drops args |
| Retry with jittered backoff (429/503) | ✅ | ❌ custom callbacks |
| Scavenge tool calls leaked into `<think>` | ✅ | ❌ |
| Call-storm breaker on identical-arg repeats | ✅ | ❌ |
| Live cache-hit / cost / vs-Claude panel | ✅ | ❌ |
| First-run config prompt + Markdown TUI | ✅ | ❌ |
Harvest and self-consistency branching are bonuses on top. The everyday
win is that **a plain chat with Reasonix already pays for ~40% less tokens
than the same chat through a naive LangChain setup**, because the prefix
actually stays byte-stable.
## Validated numbers
**τ-bench-lite** — 8 multi-turn tool-use tasks × 3 repeats = 48 runs per
side. Same tools / same prompt / same client on both sides, sole variable
is prefix stability. Measured on live DeepSeek `deepseek-chat`:
| metric | baseline (cache-hostile) | Reasonix | delta |
|---|---:|---:|---:|
| runs | 24 | 24 | — |
| **cache hit** | 46.6% | **94.4%** | **+47.7pp** |
| cost / task | $0.002599 | $0.001579 | **−39% (×0.61)** |
| vs Claude Sonnet 4.6 (token-count estimate) | — | — | **~96% cheaper** |
| pass rate | 96% (23/24) | **100% (24/24)** | Reasonix held the guardrail on every run |
**Verify it yourself — no API key, zero cost:**
```bash
git clone https://github.com/esengine/reasonix.git && cd reasonix && npm install
npx reasonix replay benchmarks/tau-bench/transcripts/t01_address_happy.reasonix.r1.jsonl
npx reasonix diff \
benchmarks/tau-bench/transcripts/t01_address_happy.baseline.r1.jsonl \
benchmarks/tau-bench/transcripts/t01_address_happy.reasonix.r1.jsonl
```
The JSONL transcripts committed in `benchmarks/tau-bench/transcripts/`
carry per-turn `usage`, `cost`, and `prefixHash`. Reasonix's prefix hash
stays byte-stable across every model call; baseline's prefix churns on
every turn. The cache delta is *mechanically* attributable to log
stability, not to a different system prompt.
Full 48-run report: [`benchmarks/tau-bench/report.md`][r]. Reproduce
with your own API key: `npx tsx benchmarks/tau-bench/runner.ts --repeats 3`.
[r]: ./benchmarks/tau-bench/report.md
### MCP — works out of the box
Any [MCP](https://spec.modelcontextprotocol.io/) server's tools inherit
Cache-First + repair + context-safety automatically. The wizard (`npx
reasonix`) lets you multi-select from a curated catalog — no flags, no
JSON-by-hand. Three live reference runs:
| server | turns | tool calls | cache hit | cost | vs Claude |
|---|---:|---:|---:|---:|---:|
| bundled demo (`add` / `echo` / `get_time`) | 2 | 1 | **96.6%** (turn 2) | $0.000254 | −94.0% |
| official `@modelcontextprotocol/server-filesystem` | 5 | 4 | **96.7%** overall | $0.001235 | −97.0% |
| **both concurrently** (`demo_add` + `fs_write_file`) | 5 | 4 | **81.1%** | $0.001852 | −95.9% |
The third row is the ecosystem proof: two MCP servers running as
separate subprocesses, tools from both exercised in one conversation.
**One single prefix hash across all 5 turns** — byte-stability survives
concurrent MCP subprocesses.
Reproduce without an API key (replay the committed transcripts):
```bash
npx reasonix replay benchmarks/tau-bench/transcripts/mcp-demo.add.jsonl
npx reasonix replay benchmarks/tau-bench/transcripts/mcp-filesystem.jsonl
```
Supported transports: **stdio** (local `npx` or binary) and **HTTP+SSE**
(remote / hosted servers, MCP 2024-11-05 spec). Pass an `http(s)://`
URL to `--mcp` and Reasonix opens the SSE stream and POSTs JSON-RPC
to the endpoint the server advertises.
[mcp]: ./benchmarks/tau-bench/transcripts/mcp-demo.add.jsonl
---
## Usage
### One command
```bash
npx reasonix
```
First run: a wizard asks for your API key, lets you pick a preset
(fast / smart / max), then offers a multi-select checklist of MCP
servers — filesystem, memory, github, puppeteer, everything. Everything
is saved to `~/.reasonix/config.json`. Subsequent runs drop straight
into chat.
### Inside the chat
A status bar at the top shows cache hit %, cost, Claude-equivalent, and
the **context gauge** (`ctx 42k/131k (32%)` — yellow at 50%, red + a
`/compact` nudge at 80%). A command strip under the input lists the
slash commands:
```
/help full list + hints
/preset <fast|smart|max> one-tap bundles (model + harvest + branch)
/mcp list attached MCP servers and tools
/compact [cap] shrink oversized tool results in history
/sessions · /forget list / delete saved sessions
/setup reconfigure (exits and tells you to run `reasonix setup`)
/clear · /exit
```
**Esc while thinking** — abort the current exploration and force the
model to summarize what it already found. No more "model ran 24 tool
calls and gave up" — you get an answer every time.
Sessions live as JSONL under `~/.reasonix/sessions/<name>.jsonl` —
every message appended atomically, so killing the CLI never loses
context. Oversized tool results auto-heal on load, so poisoning a
session with one giant `read_file` doesn't brick your history.
### Code mode — `npx reasonix code`
A thin opinionated layer on top of chat: filesystem MCP bridged at
`cwd`, coding system prompt, reasoner preset, per-directory session.
The model proposes edits as **SEARCH/REPLACE blocks**:
```
src/foo.ts
<<<<<<< SEARCH
const x = 1;
=======
const x = 2;
>>>>>>> REPLACE
```
Reasonix parses them out of each turn, applies them to disk, reports
`✓ applied src/foo.ts` in the TUI. SEARCH must match byte-for-byte;
we never fuzzy-match (silent wrong edits are worse than loud
rejections). Run `git diff` to review, `git checkout .` to undo.
**2. Point it at a project.** No install needed.
```bash
cd my-project
npx reasonix code # default: cwd, reasoner, per-dir session
npx reasonix code src/ # scope the filesystem sandbox tighter
npx reasonix code --no-session # ephemeral
npx reasonix code
```
First-run sandbox: because code mode uses the filesystem MCP from
`@modelcontextprotocol/server-filesystem`, the model can only read
and write inside the directory you pointed at. It literally can't
touch files above that root.
First run walks you through a 30-second wizard (paste API key → pick
preset → multi-select MCP servers). Every run after that drops you
straight in.
### Advanced — CLI subcommands and flags
**3. Ask it to edit.** The model proposes edits as SEARCH/REPLACE
blocks — nothing hits disk until you `/apply`.
```
reasonix code › users.ts 里 findByEmail 对大小写敏感导致登录失败,帮我改
assistant
▸ tool<search_files> → src/users.ts, src/users.test.ts
▸ tool<read_file> → (src/users.ts, 412 chars)
▸ 找到了。findByEmail 直接用 === 比对。改成小写规范化并补一条测试。
src/users.ts
<<<<<<< SEARCH
return users.find(u => u.email === email);
=======
const needle = email.toLowerCase();
return users.find(u => u.email.toLowerCase() === needle);
>>>>>>> REPLACE
▸ 1 pending edit across 1 file — /apply to write · /discard to drop
reasonix code › /apply
▸ ✓ applied src/users.ts
```
Requires Node ≥ 20.10. macOS, Linux, Windows (PowerShell / Git Bash /
Windows Terminal). Press `Esc` anytime to abort; `/help` for the full
command list.
---
## `reasonix code` — pair programmer in your terminal
Scoped to the directory you launch from. The model has native
`read_file` / `write_file` / `edit_file` / `list_directory` /
`search_files` / `directory_tree` / `get_file_info` /
`create_directory` / `move_file` tools, all sandboxed — any path that
resolves outside the launch root (including `..` and symlink escapes)
is refused. Plus `run_command` with a read-only allowlist; anything
state-mutating (`npm install`, `git commit`, …) is gated behind a
confirmation picker.
### Walkthrough: explore before editing
For "what does this code do?" questions the model uses the read-side
tools and replies in prose — no SEARCH/REPLACE blocks, no file
writes. Ask to change something only when you mean it:
```
reasonix code › 这个项目的路由是怎么组织的?
assistant
▸ tool<directory_tree> → (src/ tree, 47 entries)
▸ tool<read_file> → (src/router.ts, 1.2 KB)
▸ 路由分三层:顶层 AppRouter 注册 tab,每个 tab 用 React Router 的
nested routes 写子路径,最后 …
```
If an `edit_file` SEARCH block doesn't match the file byte-for-byte,
the edit is refused loudly rather than fuzzy-matched. The model sees
the error and retries — silent wrong edits are worse than visible
rejections.
### Plan mode — review before executing
For anything bigger than a typo, the model is encouraged to propose a
markdown plan first. You'll see a picker with **Approve / Refine /
Cancel**:
```
reasonix code › 把 auth 从 JWT 迁移到 session cookies
▸ plan submitted — awaiting your review
────────────────────────────────────────
## Summary
Swap JWT middleware for session cookies, keep user table intact.
## Files
- src/auth/middleware.ts — replace `verifyJwt` with `readSession`
- src/auth/session.ts — new file, in-memory store + signed cookie
- src/routes/login.ts — return Set-Cookie instead of a token
- tests/auth/*.test.ts — update fixtures
## Risks
- Existing logged-in users get logged out (no migration).
- Session store is in-memory; restart clears sessions.
────────────────────────────────────────
▸ Approve and implement
Refine — explore more
Cancel
```
**Force it** with `/plan` — enters an explicit read-only phase where
the model *must* submit a plan before any edit or non-allowlisted
shell call will execute. Use for high-stakes changes you want to
audit before the model touches disk. `/plan off` or picker
Approve/Cancel exits.
### `/commit` — stage + commit in one step
```
reasonix code › /commit "fix: findByEmail case-insensitive"
▸ git add -A && git commit -m "fix: findByEmail case-insensitive"
[main a1b2c3d] fix: findByEmail case-insensitive
```
### Things to try
- `/tool 1` — dump the last tool call's full output (when the 400-char
inline clip isn't enough).
- `/think` — see the model's full R1 reasoning for the last turn
(reasoner preset only).
- `/undo` — roll back the last applied edit batch.
- `/new` — start fresh in the same directory without losing the
session file.
- `npx reasonix code --preset max` — R1 + 3-way self-consistency
branching for gnarly refactors.
- `npx reasonix code src/` — narrower sandbox (only `src/` is
writable).
- `npx reasonix code --no-session` — ephemeral; nothing saved.
### `reasonix stats` — how much did you actually save?
Every turn `reasonix chat|code|run` runs appends a compact record
(tokens + cost + what Claude Sonnet 4.6 would have charged) to
`~/.reasonix/usage.jsonl`. `reasonix stats` with no args rolls that
log into today / week / month / all-time windows:
```
Reasonix usage — /Users/you/.reasonix/usage.jsonl
turns cache hit cost (USD) vs Claude saved
----------------------------------------------------------------------
today 8 95.1% $0.004821 $0.1348 96.4%
week 34 93.8% $0.023104 $0.6081 96.2%
month 127 94.2% $0.081530 $2.1452 96.2%
all-time 342 94.0% $0.210881 $5.8934 96.4%
```
Privacy: only tokens, costs, and the session name you chose land
in the file. No prompts, no completions, no tool arguments.
`reasonix stats <transcript>` keeps the old per-file summary
(assistant turns + tool calls) for scripts that already use it.
### Staying current
The panel header shows the running version next to `Reasonix` (e.g.
`Reasonix v0.4.22 · model …`). A quiet 24-hour background check against
the npm registry surfaces a yellow `update: X.Y.Z` on the right side
of the same row when a newer version has been published. No blocking,
no nagging — the check runs once per day max and is silent on failure
(offline, firewall, etc.).
```bash
npx reasonix setup # reconfigure any time
npx reasonix chat --session work # a different named session
npx reasonix chat --no-session # ephemeral — nothing persisted
reasonix update # print current vs latest, run `npm i -g reasonix@latest`
reasonix update --dry-run # print the plan without running anything
```
Running via `npx`? The command detects that and prints a
cache-refresh hint instead — npx picks up the newest version on
its next invocation automatically.
### Project conventions — `REASONIX.md`
Drop a `REASONIX.md` in the project root and its contents are pinned
into the system prompt every launch. Committable team memory — house
conventions, domain glossary, things the model keeps forgetting:
```bash
cat > REASONIX.md <<'EOF'
# Notes for Reasonix
- Use snake_case for new Python modules; legacy camelCase modules keep their style.
- `cargo check` is in the auto-run allowlist; full `cargo test` needs confirmation.
- The `api/` dir mirrors `backend/` — keep schemas in sync.
EOF
```
Re-launch (or `/new`) to pick it up; the prefix is hashed once per
session to keep the DeepSeek cache warm. `/memory` prints what's
currently pinned. `REASONIX_MEMORY=off` disables every memory source
for CI / offline repro.
### User memory — `~/.reasonix/memory/`
A second, **private per-user** memory layer lives under your home
directory. Unlike `REASONIX.md` it's never committed, and the model
can write to it itself via the `remember` tool. Two scopes:
- `~/.reasonix/memory/global/` — cross-project (your preferences,
tooling).
- `~/.reasonix/memory/<project-hash>/` — scoped to one sandbox root
in `reasonix code` (decisions, local facts, per-repo shortcuts).
Each scope keeps an always-loaded `MEMORY.md` index of one-liners
plus zero or more `<name>.md` detail files (loaded on demand via
`recall_memory`). Writes land immediately; pinning into the system
prompt takes effect on next `/new` or launch so the cache prefix
stays stable for the current session.
```
reasonix code › 我用 bun 而不是 npm,请以后都用 bun 跑构建
assistant
▸ tool<remember> → project/bun_build saved
"Build command on this machine is `bun run build`"
```
**Slash**: `/memory` · `/memory list` · `/memory show <name>` ·
`/memory forget <name>` · `/memory clear <scope> confirm`.
**Model tools**: `remember(type, scope, name, description, content)` ·
`forget(scope, name)` · `recall_memory(scope, name)`.
Project scope is only available inside `reasonix code` (needs a real
sandbox root to hash); plain `reasonix` gets the global scope only.
### Skills — user-authored prompt packs
Skills are prose instruction blocks you drop on disk. Reasonix pins
their names + one-line descriptions into the system prompt; the
model can call `run_skill({name: "..."})` on its own when a match
fits, or you can type `/skill <name> [args]` to run one manually.
Two scopes, same layout as user memory:
- `<project>/.reasonix/skills/` — per-project skills (commit them to
share with your team, or add to `.gitignore` for personal drafts).
- `~/.reasonix/skills/` — global skills available everywhere.
Either layout works: `<name>/SKILL.md` (preferred — can bundle
additional assets alongside) or flat `<name>.md`.
```markdown
---
name: review
description: Review uncommitted changes and flag risks
---
Run `git diff` on staged and unstaged changes. Summarize what each
hunk does, call out potential regressions, and list files that might
need additional tests. Don't propose edits unless I ask.
```
Use it:
```
reasonix code › /skill review
▸ running skill: review
assistant
▸ tool<run_command> → git diff --cached
▸ 3 改动,1 个需要回归测试 …
```
Or let the model pick autonomously — because the skill's name +
description are pinned in the prefix, asking "帮我看下未提交的改动有没
有风险" triggers `run_skill({name: "review"})` without you typing the
slash command.
**Slash**: `/skill` (list) · `/skill show <name>` · `/skill <name>
[args]` (inject body as user turn).
**Deliberately not tied** to any other client's directory convention
(`.claude/skills`, etc.) — Reasonix is model-agnostic at the
conversation layer. Any SKILL.md you author works; the body is
prose, so skills authored for other tools usually port over unchanged
(Reasonix's tool names differ — `filesystem` / `shell` / `web` — but
the model reads the instructions and picks our equivalents).
### Hooks — automate around tool calls and turns
Drop a `settings.json` under `.reasonix/` (project or `~/`) and
Reasonix will fire shell commands at four well-known points in
the loop: before a tool runs, after a tool returns, before your
prompt reaches the model, and after the turn ends.
```json
// <project>/.reasonix/settings.json ← committable
// ~/.reasonix/settings.json ← per-user
{
"hooks": {
"PreToolUse": [{ "match": "edit_file|write_file", "command": "bun scripts/guard.ts" }],
"PostToolUse": [{ "match": "edit_file", "command": "biome format --write" }],
"UserPromptSubmit": [{ "command": "echo $(date +%s) >> ~/.reasonix/prompts.log" }],
"Stop": [{ "command": "bun test --run", "timeout": 60000 }]
}
}
```
Each hook is a shell command. Reasonix invokes it with stdin = a
JSON envelope describing the event:
```json
{ "event": "PreToolUse", "cwd": "/path/to/project",
"toolName": "edit_file", "toolArgs": { "path": "src/x.ts", "..." } }
```
Exit code drives the decision:
- **0** — pass; loop continues normally
- **2** — block (only on `PreToolUse` / `UserPromptSubmit`); the
hook's stderr becomes the synthetic tool result the model sees,
or the prompt is dropped entirely
- **anything else** — warn; loop continues, stderr renders as a
yellow row inline
`match` is anchored regex on the tool name; `*` or omitted matches
every tool. Project hooks fire before global hooks. Default
timeouts: 5s for blocking events, 30s for logging events; per-hook
`timeout` overrides.
**Slash**: `/hooks` (list active hooks) · `/hooks reload` (re-read
`settings.json` from disk without losing your session).
### Staying current from inside the TUI
`/update` inside a running session shows your current version, the
last-resolved latest version (from the quiet 24h background check),
and the shell command to run. The slash does *not* spawn
`npm install` — stdio:inherit into a running Ink renderer corrupts
the display. Exit the session and run `reasonix update` in a
fresh shell when you actually want to install.
---
## `reasonix` — also works as general chat
Same TUI, no filesystem tools unless you opt in via MCP. Good for
drafting, Q&A, schema design, architecture discussions, or driving
your own MCP servers. Sessions persist per name under
`~/.reasonix/sessions/`.
```bash
npx reasonix # uses saved config + wizard-selected MCP
npx reasonix --preset smart # reasoner + R1 harvest for this run
npx reasonix --session design # named session — resume later with --session design
```
Bridge your own MCP servers on the fly:
```bash
npx reasonix \
--mcp "fs=npx -y @modelcontextprotocol/server-filesystem /tmp/safe" \
--mcp "kb=https://mcp.example.com/sse"
```
MCP tools go through the same Cache-First + repair + context-safety
plumbing as native tools — 32k result cap, live progress-notification
rendering, retries.
---
## Commands inside the session
**Core**
| command | what it does |
|---|---|
| `/help` · `/?` | full command reference with hints |
| `/status` | current model · flags · context · session |
| `/new` · `/reset` | fresh conversation in the same session |
| `/clear` | clear visible scrollback only (log kept) |
| `/retry` | truncate and resend your last message (fresh sample) |
| `/exit` · `/quit` | quit |
**Model**
| command | what it does |
|---|---|
| `/preset <fast\|smart\|max>` | one-tap bundle (model + harvest + branch) |
| `/model <id>` | switch DeepSeek model (`deepseek-chat`, `deepseek-reasoner`) |
| `/harvest [on\|off]` | toggle R1 plan-state extraction |
| `/branch <N\|off>` | run N parallel samples per turn, pick best (N ≥ 2) |
| `/think` | dump the last turn's full R1 reasoning |
**Context & tools**
| command | what it does |
|---|---|
| `/mcp` | list attached MCP servers and their tools |
| `/tool [N]` | dump the Nth tool call's full output (1 = latest) |
| `/compact [cap]` | shrink oversized tool results in the log |
**Memory & skills**
| command | what it does |
|---|---|
| `/memory` | show pinned memory (REASONIX.md + ~/.reasonix/memory) |
| `/memory list` · `show <name>` · `forget <name>` · `clear <scope> confirm` | manage the store |
| `/skill` · `/skill list` | list discovered skills (project + global) |
| `/skill show <name>` | dump one skill's body |
| `/skill <name> [args]` | run a skill (inject body as user turn) |
**Sessions**
| command | what it does |
|---|---|
| `/sessions` | list saved sessions (current marked with `▸`) |
| `/forget` | delete the current session from disk |
| `/setup` | reconfigure (exit and run `reasonix setup`) |
**Code mode only** (`reasonix code`)
| command | what it does |
|---|---|
| `/apply` | commit the pending SEARCH/REPLACE blocks to disk |
| `/discard` | drop the pending edit blocks without writing |
| `/undo` | roll back the last applied edit batch |
| `/commit "msg"` | `git add -A && git commit -m "msg"` |
| `/plan [on\|off]` | toggle read-only plan mode |
| `/apply-plan` | force-approve a pending plan |
**Keyboard**
- `Enter` — submit
- `Shift+Enter` / `Ctrl+J` — newline (multi-line paste also supported;
`\` + Enter as a portable fallback)
- `↑` / `↓` — walk prompt history while idle; navigate slash-autocomplete
- `Tab` / `Enter` on a `/foo` prefix — accept the highlighted suggestion
- `Esc` — abort the current turn (stops the API call, cancels any
in-flight tool, rejects pending MCP requests)
- `y` / `n` on confirm prompts — hotkey accept / reject
---
## Sessions and safety nets
- Sessions live as JSONL under `~/.reasonix/sessions/<name>.jsonl`
(per directory for `reasonix code`). Every message appended
atomically; `Ctrl+C` never loses context.
- Tool results are capped at 32k chars per call. Oversized sessions
self-heal on load (shrinks + rewrites the file).
- Malformed `assistant.tool_calls` / `tool` pairing is validated on
every outgoing API call so a corrupted session can't keep 400ing.
- Context gauge turns yellow at 50%, red at 80% with a `/compact`
nudge. Approaching the 131k window triggers an automatic
compaction attempt before falling back to a forced summary.
- The `reasonix code` sandbox refuses any path that resolves outside
the launch directory, including symlink escape and `..` traversal.
### Troubleshooting: duplicate rows / ghost rendering
Some Windows terminals (Git Bash / MINTTY / winpty-wrapped shells)
don't fully implement the ANSI cursor-up escapes Ink uses to repaint
the live spinner region. Symptom: spinners, streaming previews, or
tool-result rows print multiple copies into scrollback instead of
overwriting in place.
If you hit this, run with plain mode:
```bash
REASONIX_UI=plain npx reasonix code
```
Plain mode suppresses live/animated rows and disables the internal
tick timer. You lose the streaming preview and spinners but gain
stable scrollback. Windows Terminal, PowerShell 7 in Windows
Terminal, and WezTerm don't need this opt-out.
---
## Web search — on by default
The model has two web tools the moment you launch: `web_search` and
`web_fetch`. No flag, no API key, no signup. When you ask about
something the model wasn't trained on (new releases, current events,
obscure APIs), it decides to call `web_search` on its own; if a
snippet isn't enough it follows up with `web_fetch`.
Backed by **Mojeek**'s public search page — an independent web
index, bot-friendly, no cookies/sessions. Coverage on niche or very
recent queries can be thinner than Google/Bing, but it's reliable
from scripts. (DDG was the original backend but started serving
anti-bot pages in 2026.)
**Turn it off** (offline mode / privacy / CI):
```json
// ~/.reasonix/config.json
{ "apiKey": "sk-…", "search": false }
```
```bash
REASONIX_SEARCH=off npx reasonix code
```
**Bring your own** (Kagi, SearXNG, internal caches): implement the
`WebSearchProvider` interface and call
`registerWebTools(registry, { provider })` yourself, or bridge an
existing MCP search server via `--mcp`.
---
## MCP — bring your own tools
Any [MCP](https://spec.modelcontextprotocol.io/) server works. The
wizard lets you pick from a catalog, or drive it by flag:
```bash
# stdio (local subprocess)
npx reasonix --mcp "fs=npx -y @modelcontextprotocol/server-filesystem /tmp/safe"
# multiple at once
npx reasonix \
--mcp "fs=npx -y @modelcontextprotocol/server-filesystem /tmp/safe" \
--mcp "demo=npx tsx examples/mcp-server-demo.ts"
# HTTP+SSE (remote / hosted)
npx reasonix --mcp "kb=https://mcp.example.com/sse"
```
`reasonix mcp list` shows the curated catalog. `reasonix mcp inspect
<spec>` connects once and dumps the server's tools / resources /
prompts without starting a chat. Progress notifications from
long-running tools (2025-03-26 spec) render live as a progress bar
in the spinner.
Supported transports: **stdio** (local command) and **HTTP+SSE**
(remote, MCP 2024-11-05 spec).
---
## CLI reference
```bash
npx reasonix code [path] # coding mode scoped to path (default: cwd)
npx reasonix # chat (uses saved config)
npx reasonix setup # reconfigure the wizard
npx reasonix chat --session work # named session
npx reasonix chat --no-session # ephemeral
npx reasonix run "ask anything" # one-shot, streams to stdout
npx reasonix stats session.jsonl # summarize a transcript
npx reasonix replay chat.jsonl # scrub a transcript + rebuild cost/cache
npx reasonix replay chat.jsonl # rebuild cost/cache from a transcript
npx reasonix diff a.jsonl b.jsonl --md # compare two transcripts
npx reasonix mcp list # curated MCP server catalog
npx reasonix mcp list # curated MCP catalog
npx reasonix mcp inspect <spec> # probe a single MCP server
npx reasonix sessions # list saved sessions
```
Power users can still bypass config and drive Reasonix with flags:
Common flags:
```bash
npx reasonix chat \
--preset max \
--mcp "filesystem=npx -y @modelcontextprotocol/server-filesystem /tmp/safe" \
--mcp "kb=https://mcp.example.com/sse" \
--transcript session.jsonl \
--no-config # ignore ~/.reasonix/config.json (for CI / reproducing issues)
--preset <fast|smart|max> # bundle (model + harvest + branch)
--model <id> # explicit model id
--harvest / --no-harvest # R1 plan-state extraction
--branch <N> # self-consistency budget
--mcp "name=cmd args…" # attach an MCP server (repeatable)
--transcript path.jsonl # write a JSONL transcript on the side
--session <name> # named session (default: per-dir for code mode)
--no-session # ephemeral
--no-config # ignore ~/.reasonix/config.json (CI-friendly)
```
### Library
Env vars (win over config):
```bash
export DEEPSEEK_API_KEY=sk-...
export DEEPSEEK_BASE_URL=https://... # optional alternate endpoint
export REASONIX_MEMORY=off # disable REASONIX.md + user memory
export REASONIX_SEARCH=off # disable web_search / web_fetch
export REASONIX_UI=plain # disable live rows (ghosting workaround)
```
---
## Library usage
```ts
import {
@@ -261,7 +622,7 @@ const loop = new CacheFirstLoop({
toolSpecs: tools.specs(),
}),
harvest: true,
branch: 3, // self-consistency budget
branch: 3,
});
for await (const ev of loop.step("What is 17 + 25?")) {
@@ -270,29 +631,82 @@ for await (const ev of loop.step("What is 17 + 25?")) {
console.log(loop.stats.summary());
```
### Configuration
`ChatOptions.seedTools` accepts a pre-built `ToolRegistry` for
callers who want the `reasonix code` loop wiring without the CLI
wrapper. See [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) for
internals.
The wizard handles everything on first run. If you'd rather use env vars
(CI, shared boxes, etc.):
---
## Benchmarks — verify the cache-hit claim yourself
Every abstraction here earns its weight against a DeepSeek-specific
property — dirt-cheap tokens, R1 reasoning traces, automatic prefix
caching, JSON mode. Generic wrappers leave these on the table.
| | Reasonix default | generic frameworks |
|---|---|---|
| Prefix-stable loop (→ 85–95% cache hit) | yes | no (prompts rebuilt each turn) |
| Auto-flatten deep tool schemas | yes | no (DeepSeek drops args) |
| Retry with jittered backoff (429/503) | yes | no (custom callbacks) |
| Scavenge tool calls leaked into `<think>` | yes | no |
| Call-storm breaker on identical-arg repeats | yes | no |
| Live cache-hit / cost / vs-Claude panel | yes | no |
On the same τ-bench-lite workload — 8 multi-turn tool-use tasks × 3
repeats = 48 runs per side, live DeepSeek `deepseek-chat`, sole
variable prefix stability:
| metric | baseline (cache-hostile) | Reasonix | delta |
|---|---:|---:|---:|
| cache hit | 46.6% | **94.4%** | +47.7 pp |
| cost / task | $0.002599 | $0.001579 | **−39%** |
| pass rate | 96% (23/24) | **100% (24/24)** | — |
**Reproduce without spending an API credit:**
```bash
export DEEPSEEK_API_KEY=sk-... # wins over ~/.reasonix/config.json
export DEEPSEEK_BASE_URL=https://... # optional alternate endpoint
git clone https://github.com/esengine/reasonix.git && cd reasonix && npm install
npx reasonix replay benchmarks/tau-bench/transcripts/t01_address_happy.reasonix.r1.jsonl
npx reasonix diff \
benchmarks/tau-bench/transcripts/t01_address_happy.baseline.r1.jsonl \
benchmarks/tau-bench/transcripts/t01_address_happy.reasonix.r1.jsonl
```
Get a key (free credit on signup): <https://platform.deepseek.com/api_keys>
The committed JSONL transcripts carry per-turn `usage`, `cost`, and
`prefixHash`. Reasonix's prefix hash stays byte-stable across every
model call; baseline's churns on every turn. The cache delta is
*mechanically* attributable to log stability, not to a different
system prompt.
Re-run `npx reasonix setup` any time to add/remove MCP servers or switch
preset — your existing selections are pre-checked.
Full 48-run report:
[`benchmarks/tau-bench/report.md`](./benchmarks/tau-bench/report.md).
Reproduce with your own API key: `npx tsx
benchmarks/tau-bench/runner.ts --repeats 3`.
MCP reference runs (one single prefix hash across all 5 turns even
with two concurrent MCP subprocesses):
| server | turns | cache hit | cost | vs Claude |
|---|---:|---:|---:|---:|
| bundled demo (`add` / `echo` / `get_time`) | 2 | **96.6%** (turn 2) | $0.000254 | −94.0% |
| official `server-filesystem` | 5 | **96.7%** | $0.001235 | −97.0% |
| **both concurrently** | 5 | **81.1%** | $0.001852 | −95.9% |
---
## Non-goals
- Multi-agent orchestration (use LangGraph).
- RAG / vector stores (use LlamaIndex or do it yourself).
- Multi-provider abstraction (use LiteLLM).
- Web UI / SaaS.
- **Multi-agent orchestration / sub-agents** (use LangGraph).
- **Workflow DSL / DAG scheduler / parallel-branch engine** — skills
are prose; the model sequences via the normal tool-use loop.
Keeps single-loop + append-only + cache-first invariants intact.
- **Multi-provider abstraction** (use LiteLLM). Reasonix is
DeepSeek-only on purpose — every pillar (cache-first loop, R1
harvesting, tool-call repair) is tuned against DeepSeek-specific
behavior and economics. Coupling to one backend is the feature.
- **RAG / vector stores** (use LlamaIndex).
- **Web UI / SaaS.**
Reasonix does DeepSeek, deeply.
@@ -304,15 +718,13 @@ Reasonix does DeepSeek, deeply.
git clone https://github.com/esengine/reasonix.git
cd reasonix
npm install
npm run dev chat # run CLI from source via tsx
npm run dev code # run CLI from source via tsx
npm run build # tsup to dist/
npm test # vitest (279 tests)
npm test # vitest (648 tests)
npm run lint # biome
npm run typecheck # tsc --noEmit
```
See [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) for internals.
---
## License
+69 -8
View File
@@ -67,14 +67,33 @@ const TOOLS = [
description: "Returns the server's current ISO-8601 timestamp.",
inputSchema: { type: "object", properties: {} },
},
{
name: "slow_count",
description:
"Counts from 1 to n with a ~300 ms pause between steps, emitting notifications/progress frames along the way. Useful for demonstrating Reasonix's progress-bar UI.",
inputSchema: {
type: "object",
properties: {
n: { type: "integer", description: "Final number to count to (default 5, max 20)" },
},
},
},
];
function send(msg: JsonRpcSuccess | JsonRpcError): void {
interface JsonRpcNotification {
jsonrpc: "2.0";
method: string;
params?: unknown;
}
function send(msg: JsonRpcSuccess | JsonRpcError | JsonRpcNotification): void {
// Stdio MCP framing: one JSON per line.
process.stdout.write(`${JSON.stringify(msg)}\n`);
}
function handleRequest(req: JsonRpcRequest): JsonRpcSuccess | JsonRpcError | null {
async function handleRequest(
req: JsonRpcRequest,
): Promise<JsonRpcSuccess | JsonRpcError | null> {
const id = req.id ?? null;
switch (req.method) {
@@ -99,10 +118,15 @@ function handleRequest(req: JsonRpcRequest): JsonRpcSuccess | JsonRpcError | nul
}
case "tools/call": {
const params = (req.params ?? {}) as { name?: string; arguments?: Record<string, unknown> };
const params = (req.params ?? {}) as {
name?: string;
arguments?: Record<string, unknown>;
_meta?: { progressToken?: string | number };
};
const name = params.name ?? "";
const args = params.arguments ?? {};
const out = callTool(name, args);
const progressToken = params._meta?.progressToken;
const out = await callTool(name, args, progressToken);
if (out.error) {
return {
jsonrpc: "2.0",
@@ -129,10 +153,11 @@ function handleRequest(req: JsonRpcRequest): JsonRpcSuccess | JsonRpcError | nul
}
}
function callTool(
async function callTool(
name: string,
args: Record<string, unknown>,
): { text: string; error?: string } {
progressToken: string | number | undefined,
): Promise<{ text: string; error?: string }> {
if (name === "echo") {
const msg = typeof args.msg === "string" ? args.msg : "";
return { text: `echo: ${msg}` };
@@ -148,6 +173,28 @@ function callTool(
if (name === "get_time") {
return { text: new Date().toISOString() };
}
if (name === "slow_count") {
// Cap at 20 so an over-eager model can't make the demo run for
// minutes. Default 5 gives ~1.5s which is plenty to see the bar.
const raw = typeof args.n === "number" ? args.n : Number(args.n);
const n = Number.isFinite(raw) && raw >= 1 ? Math.min(Math.floor(raw), 20) : 5;
for (let i = 1; i <= n; i++) {
await new Promise((r) => setTimeout(r, 300));
if (progressToken !== undefined) {
send({
jsonrpc: "2.0",
method: "notifications/progress",
params: {
progressToken,
progress: i,
total: n,
message: `counting ${i} of ${n}`,
},
});
}
}
return { text: `counted to ${n}` };
}
return { text: "", error: `unknown tool: ${name}` };
}
@@ -168,8 +215,22 @@ function main(): void {
});
return;
}
const resp = handleRequest(req);
if (resp) send(resp);
// Fire-and-forget: handleRequest is async so slow tools (slow_count
// and any future streamed-progress tools) can emit notifications
// between in-flight requests without blocking the reader loop. Any
// unexpected throw lands as an internal-error response so malformed
// tool logic doesn't silently hang the client.
handleRequest(req)
.then((resp) => {
if (resp) send(resp);
})
.catch((err) => {
send({
jsonrpc: "2.0",
id: req.id ?? null,
error: { code: -32603, message: `internal: ${(err as Error).message}` },
});
});
});
rl.on("close", () => process.exit(0));
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "reasonix",
"version": "0.4.2",
"version": "0.4.24",
"description": "DeepSeek-native agent framework: cache-first loop, R1 thought harvesting, tool-call repair.",
"type": "module",
"bin": {
+192
View File
@@ -0,0 +1,192 @@
/**
* End-to-end smoke test for the memory layer. Runs against a temp
* homeDir so the developer's real ~/.reasonix/memory/ is never touched.
* Exercises: write → index regeneration → prefix assembly →
* recall → delete → REASONIX_MEMORY=off short-circuit.
*
* Run: npx tsx scripts/smoke-memory.mts
* Exit code 0 on success, 1 on any assertion failure.
*/
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { ToolRegistry } from "../src/tools.js";
import { registerMemoryTools } from "../src/tools/memory.js";
import {
MemoryStore,
applyMemoryStack,
applyUserMemory,
projectHash,
} from "../src/user-memory.js";
let failures = 0;
function check(label: string, cond: unknown, detail?: string) {
if (cond) {
process.stdout.write(` ✓ ${label}\n`);
} else {
failures++;
process.stdout.write(` ✗ ${label}${detail ? ` — ${detail}` : ""}\n`);
}
}
async function main() {
const home = mkdtempSync(join(tmpdir(), "reasonix-smoke-home-"));
const projectRoot = mkdtempSync(join(tmpdir(), "reasonix-smoke-proj-"));
process.stdout.write(`home: ${home}\nproject: ${projectRoot}\n\n`);
try {
// ── 1. MemoryStore write + index regeneration ────────────────────
process.stdout.write("1. MemoryStore write → index regen\n");
const store = new MemoryStore({ homeDir: home, projectRoot });
store.write({
name: "bun_build",
type: "project",
scope: "project",
description: "Build command on this machine is `bun run build`",
body: "On this machine, no npm — always `bun run build` / `bun run test`.",
});
store.write({
name: "tabs_not_spaces",
type: "user",
scope: "global",
description: "Use tabs for indentation across all projects",
body: "Rule.\n\n**Why:** muscle memory, editor config across machines.\n\n**How to apply:** always tabs.",
});
const hash = projectHash(projectRoot);
const projectFile = join(home, "memory", hash, "bun_build.md");
const globalFile = join(home, "memory", "global", "tabs_not_spaces.md");
check("project-scoped file landed in <hash>/ dir", existsSync(projectFile));
check("global-scoped file landed in global/ dir", existsSync(globalFile));
check("no cross-contamination project ⇒ global", !existsSync(join(home, "memory", "global", "bun_build.md")));
const projectIndex = readFileSync(join(home, "memory", hash, "MEMORY.md"), "utf8");
check("project MEMORY.md points at bun_build.md", projectIndex.includes("[bun_build](bun_build.md)"));
const globalIndex = readFileSync(join(home, "memory", "global", "MEMORY.md"), "utf8");
check("global MEMORY.md points at tabs_not_spaces.md", globalIndex.includes("[tabs_not_spaces](tabs_not_spaces.md)"));
const raw = readFileSync(projectFile, "utf8");
check("frontmatter has name/type/scope/created", /^---\nname: bun_build\n/.test(raw) && /type: project/.test(raw) && /scope: project/.test(raw) && /created: \d{4}-\d{2}-\d{2}/.test(raw));
// ── 2. Prefix assembly via applyMemoryStack (+ REASONIX.md) ────────
process.stdout.write("\n2. Prefix assembly (REASONIX.md + user memory)\n");
writeFileSync(join(projectRoot, "REASONIX.md"), "# Project notes\nPrefer explicit types over inference.\n", "utf8");
const BASE = "You are a test assistant.";
const withProjOnly = applyUserMemory(BASE, { homeDir: home, projectRoot });
check("applyUserMemory contains global block", withProjOnly.includes("# User memory — global"));
check("applyUserMemory contains project block", withProjOnly.includes("# User memory — this project"));
check("bun_build description present in prefix", withProjOnly.includes("bun run build"));
check("tabs_not_spaces description present in prefix", withProjOnly.includes("Use tabs for indentation"));
// Order: base → (REASONIX.md would go first via applyMemoryStack) → global → project
const ordered = applyUserMemory(BASE, { homeDir: home, projectRoot });
const iGlobalBlock = ordered.indexOf("# User memory — global");
const iProjBlock = ordered.indexOf("# User memory — this project");
check("global block precedes project block (stable for cache)", iGlobalBlock > 0 && iGlobalBlock < iProjBlock);
// Determinism — two calls with same state produce byte-identical prompts.
const a = applyUserMemory(BASE, { homeDir: home, projectRoot });
const b = applyUserMemory(BASE, { homeDir: home, projectRoot });
check("applyUserMemory is deterministic (byte-stable)", a === b);
// ── 3. The `remember` / `recall_memory` / `forget` tools ───────────
process.stdout.write("\n3. Tool dispatch (remember / recall / forget)\n");
const reg = new ToolRegistry();
registerMemoryTools(reg, { homeDir: home, projectRoot });
check("remember tool registered", reg.has("remember"));
check("forget tool registered", reg.has("forget"));
check("recall_memory tool registered", reg.has("recall_memory"));
check("recall_memory is readOnly (plan-mode safe)", reg.get("recall_memory")?.readOnly === true);
check("remember is NOT readOnly (plan-mode blocked)", reg.get("remember")?.readOnly !== true);
const remOut = await reg.dispatch("remember", {
type: "feedback",
scope: "global",
name: "prefers_short_replies",
description: "User wants terse answers, no trailing summaries",
content: "Default to terse. If the user wants detail they'll ask.",
});
check("remember returns a confirmation (not an error)", remOut.includes("REMEMBERED (global/prefers_short_replies)"), remOut);
const recallOut = await reg.dispatch("recall_memory", {
scope: "global",
name: "prefers_short_replies",
});
check("recall_memory returns the body", recallOut.includes("Default to terse"));
const forgetOut = await reg.dispatch("forget", {
scope: "global",
name: "prefers_short_replies",
});
check("forget returns a confirmation", forgetOut.includes("forgot (global/prefers_short_replies)"));
check("recall_memory after forget returns an error", (await reg.dispatch("recall_memory", { scope: "global", name: "prefers_short_replies" })).includes("error"));
// ── 4. Project scope refused when projectRoot is absent ────────────
process.stdout.write("\n4. Chat-mode (no projectRoot) refuses project scope\n");
const chatReg = new ToolRegistry();
registerMemoryTools(chatReg, { homeDir: home });
const projInChat = await chatReg.dispatch("remember", {
type: "project",
scope: "project",
name: "should_fail",
description: "d",
content: "c",
});
check("scope='project' in chat mode → error payload", projInChat.includes("error") && projInChat.includes("project"));
const globalInChat = await chatReg.dispatch("remember", {
type: "user",
scope: "global",
name: "global_from_chat",
description: "works across projects",
content: "body",
});
check("scope='global' in chat mode → writes successfully", globalInChat.includes("REMEMBERED (global/"));
// ── 5. REASONIX_MEMORY=off short-circuit ───────────────────────────
process.stdout.write("\n5. REASONIX_MEMORY=off opt-out\n");
process.env.REASONIX_MEMORY = "off";
try {
const silenced = applyUserMemory(BASE, { homeDir: home, projectRoot });
check("applyUserMemory returns BASE unchanged when off", silenced === BASE);
const fullStack = applyMemoryStack(BASE, projectRoot);
check("applyMemoryStack returns BASE unchanged when off (REASONIX.md also skipped)", fullStack === BASE);
} finally {
delete process.env.REASONIX_MEMORY;
}
// ── 6. Delete regeneration: MEMORY.md matches current file set ─────
process.stdout.write("\n6. Delete + index regeneration\n");
store.delete("global", "tabs_not_spaces");
store.delete("global", "global_from_chat");
const globalIdxAfter = join(home, "memory", "global", "MEMORY.md");
check("global MEMORY.md removed when last file deleted", !existsSync(globalIdxAfter));
const projectIdxStill = readFileSync(join(home, "memory", hash, "MEMORY.md"), "utf8");
check("project MEMORY.md untouched (different scope)", projectIdxStill.includes("bun_build"));
// ── 7. Name-sanitization boundary ──────────────────────────────────
process.stdout.write("\n7. Name sanitization (path-traversal refused)\n");
const badOut = await reg.dispatch("remember", {
type: "user",
scope: "global",
name: "../../etc/passwd",
description: "d",
content: "c",
});
check("remember refuses path-traversal name", badOut.includes("invalid memory name"));
const outsideFile = join(home, "etc", "passwd.md");
check("no file written outside the memory dir", !existsSync(outsideFile));
process.stdout.write(`\n${failures === 0 ? "✅ all smoke checks passed" : `❌ ${failures} failure(s)`}\n`);
} finally {
rmSync(home, { recursive: true, force: true });
rmSync(projectRoot, { recursive: true, force: true });
}
process.exit(failures === 0 ? 0 : 1);
}
main().catch((err) => {
console.error(err);
process.exit(1);
});
+176 -10
View File
@@ -1,15 +1,34 @@
import { existsSync, statSync } from "node:fs";
import { render } from "ink";
import React, { useState } from "react";
import { loadApiKey } from "../../config.js";
import { loadApiKey, searchEnabled } from "../../config.js";
import { loadDotenv } from "../../env.js";
import { McpClient } from "../../mcp/client.js";
import { type InspectionReport, inspectMcpServer } from "../../mcp/inspect.js";
import { bridgeMcpTools } from "../../mcp/registry.js";
import { parseMcpSpec } from "../../mcp/spec.js";
import { SseTransport } from "../../mcp/sse.js";
import { type McpTransport, StdioTransport } from "../../mcp/stdio.js";
import {
loadSessionMessages,
rewriteSession,
sessionPath as sessionPathOf,
} from "../../session.js";
import { ToolRegistry } from "../../tools.js";
import { registerMemoryTools } from "../../tools/memory.js";
import { registerSkillTools } from "../../tools/skills.js";
import { registerWebTools } from "../../tools/web.js";
import { App } from "../ui/App.js";
import { SessionPicker } from "../ui/SessionPicker.js";
import { Setup } from "../ui/Setup.js";
import type { McpServerSummary } from "../ui/slash.js";
export interface ProgressInfo {
toolName: string;
progress: number;
total?: number;
message?: string;
}
export interface ChatOptions {
model: string;
@@ -22,21 +41,55 @@ export interface ChatOptions {
mcp?: string[];
/** Global prefix — only used when a single anonymous server is given. */
mcpPrefix?: string;
/**
* Pre-built ToolRegistry used as a seed. MCP bridges (if any) are
* layered on top of whatever's already registered. Used by
* `reasonix code` to register native filesystem tools in place of
* the old `npx -y @modelcontextprotocol/server-filesystem` subprocess.
*/
seedTools?: ToolRegistry;
/**
* Enable SEARCH/REPLACE edit-block processing after each assistant turn.
* Set by `reasonix code`; plain `reasonix chat` leaves this off.
*/
codeMode?: { rootDir: string };
/** Skip the session picker — assume "Resume" (backwards-compatible auto-continue). */
forceResume?: boolean;
/** Skip the session picker — assume "New" (wipe the session file and start fresh). */
forceNew?: boolean;
}
interface RootProps extends ChatOptions {
initialKey: string | undefined;
tools: ToolRegistry | undefined;
mcpSpecs: string[];
mcpServers: McpServerSummary[];
/**
* Shared ref the bridge's `onProgress` callback writes through.
* App sets `.current` to its own handler on mount so every
* progress frame from any bridged tool lands in the UI's
* `OngoingToolRow`. Ref keeps the wire-up synchronous with
* React reconciliation (no effect-timing surprises).
*/
progressSink: { current: ((info: ProgressInfo) => void) | null };
/** Present when the session has prior messages; drives the picker. */
sessionPreview?: { messageCount: number; lastActive: Date };
}
function Root({ initialKey, tools, mcpSpecs, ...appProps }: RootProps) {
function Root({
initialKey,
tools,
mcpSpecs,
mcpServers,
progressSink,
sessionPreview,
...appProps
}: RootProps) {
const [key, setKey] = useState<string | undefined>(initialKey);
// `null` once the picker is resolved (or was never needed). Starts as
// the preview so we can render the picker once before mounting App.
const [pending, setPending] = useState<typeof sessionPreview>(sessionPreview);
if (!key) {
return (
<Setup
@@ -48,6 +101,26 @@ function Root({ initialKey, tools, mcpSpecs, ...appProps }: RootProps) {
);
}
process.env.DEEPSEEK_API_KEY = key;
if (pending && appProps.session) {
return (
<SessionPicker
sessionName={appProps.session}
messageCount={pending.messageCount}
lastActive={pending.lastActive}
onChoose={(choice) => {
if (choice === "new" || choice === "delete") {
// Wipe the session file. "new" and "delete" do the same thing
// at this step — the distinction is only in the picker's
// wording. A future enhancement could archive on "new".
rewriteSession(appProps.session!, []);
}
setPending(undefined);
}}
/>
);
}
return (
<App
model={appProps.model}
@@ -58,6 +131,8 @@ function Root({ initialKey, tools, mcpSpecs, ...appProps }: RootProps) {
session={appProps.session}
tools={tools}
mcpSpecs={mcpSpecs}
mcpServers={mcpServers}
progressSink={progressSink}
codeMode={appProps.codeMode}
/>
);
@@ -71,10 +146,20 @@ export async function chatCommand(opts: ChatOptions): Promise<void> {
const clients: McpClient[] = [];
const successfulSpecs: string[] = [];
const failedSpecs: Array<{ spec: string; reason: string }> = [];
let tools: ToolRegistry | undefined;
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
// the App has mounted) are dropped rather than buffered.
const progressSink: { current: ((info: ProgressInfo) => void) | null } = { current: null };
// Seed registry from the caller (e.g. reasonix code's native
// filesystem tools) — MCP bridges layer on top rather than
// 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 = new ToolRegistry();
if (!tools) tools = new ToolRegistry();
for (const raw of requestedSpecs) {
try {
const spec = parseMcpSpec(raw);
@@ -89,7 +174,31 @@ export async function chatCommand(opts: ChatOptions): Promise<void> {
: new StdioTransport({ command: spec.command, args: spec.args });
const mcp = new McpClient({ transport });
await mcp.initialize();
const bridge = await bridgeMcpTools(mcp, { registry: tools, namePrefix: prefix });
const bridge = await bridgeMcpTools(mcp, {
registry: tools,
namePrefix: prefix,
onProgress: (info) => progressSink.current?.(info),
});
// Collect resources + prompts once at startup so the /mcp
// slash can render them synchronously. Servers that don't
// support these fall through as `{supported: false}` instead
// of throwing — see inspectMcpServer.
let report: InspectionReport;
try {
report = await inspectMcpServer(mcp);
} catch {
// If the inspect call itself fails (rare — shouldn't happen
// since inspectMcpServer swallows -32601), synthesize a
// minimal report so `/mcp` still has something to render.
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" },
};
}
const label = spec.name ?? "anon";
const source =
spec.transport === "sse" ? spec.url : `${spec.command} ${spec.args.join(" ")}`;
@@ -98,6 +207,12 @@ export async function chatCommand(opts: ChatOptions): Promise<void> {
);
clients.push(mcp);
successfulSpecs.push(raw);
mcpServers.push({
label,
spec: raw,
toolCount: bridge.registeredNames.length,
report,
});
} catch (err) {
// Per-server failure is non-fatal: one broken server shouldn't
// kill a chat that has working servers configured. We record
@@ -111,17 +226,68 @@ export async function chatCommand(opts: ChatOptions): Promise<void> {
);
}
}
// If every requested server failed, drop the empty registry so the
// loop still runs as a bare chat instead of advertising zero tools.
if (successfulSpecs.length === 0) {
// 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 mcpSpecs = successfulSpecs;
// 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);
}
// Memory tools — available in every session, not just code mode.
// Chat-mode callers get global scope only; project scope requires
// the seedTools path from `reasonix code` (which registers its own
// MemoryStore bound to rootDir before chatCommand runs).
if (!opts.seedTools) {
if (!tools) tools = new ToolRegistry();
registerMemoryTools(tools, {});
// Skills are a chat-mode concept too — load them here so plain
// `reasonix chat` users can invoke user-defined skills. Code mode
// registers its own copy alongside its other seed tools.
registerSkillTools(tools);
}
// Decide whether to show the session picker. It's gated on: session
// persistence is on, the session file already has prior messages, and
// the caller didn't pre-commit to one of the choices via --resume /
// --new flags. `--new` wipes the file now (before the loop opens),
// so the App mounts against a fresh log.
let sessionPreview: { messageCount: number; lastActive: Date } | undefined;
if (opts.session && !opts.forceResume && !opts.forceNew) {
const prior = loadSessionMessages(opts.session);
if (prior.length > 0) {
const p = sessionPathOf(opts.session);
const mtime = existsSync(p) ? statSync(p).mtime : new Date();
sessionPreview = { messageCount: prior.length, lastActive: mtime };
}
} else if (opts.session && opts.forceNew) {
rewriteSession(opts.session, []);
}
const { waitUntilExit } = render(
<Root initialKey={initialKey} tools={tools} mcpSpecs={mcpSpecs} {...opts} />,
{ exitOnCtrlC: true },
<Root
initialKey={initialKey}
tools={tools}
mcpSpecs={mcpSpecs}
mcpServers={mcpServers}
progressSink={progressSink}
sessionPreview={sessionPreview}
{...opts}
/>,
// patchConsole:false — we never log to console during the TUI, and the
// patch is a known redraw-glitch source on winpty/MINTTY terminals.
{ exitOnCtrlC: true, patchConsole: false },
);
try {
await waitUntilExit();
+52 -17
View File
@@ -3,8 +3,11 @@
* code-editing workflows.
*
* What it does differently from plain chat:
* - Auto-bridges the official filesystem MCP server rooted at the
* given directory (CWD by default). No wizard, no config merge.
* - Registers native filesystem tools rooted at the given directory
* (CWD by default). No subprocess, no `npx install` step, R1-
* friendly schemas. Replaced the old `@modelcontextprotocol/server-filesystem`
* subprocess in 0.4.9 because its `edit_file` argv shape was the
* biggest driver of R1 DSML hallucinations.
* - Uses a coding-focused system prompt (src/code/prompt.ts) that
* teaches the model to propose edits as SEARCH/REPLACE blocks.
* - Defaults to the `smart` preset (reasoner + harvest) because
@@ -13,18 +16,21 @@
* conversation history.
* - Hooks `codeMode` into the TUI so assistant replies get parsed
* for SEARCH/REPLACE blocks and applied on disk after each turn.
*
* Out of scope for v1: /commit, /undo, diff preview, .gitignore
* filtering. The user's own `git diff` + `git checkout` is the review
* / undo surface for now.
*/
import { basename, resolve } from "node:path";
import { loadProjectShellAllowed } from "../../config.js";
import { sanitizeName } from "../../session.js";
import { ToolRegistry } from "../../tools.js";
import { registerFilesystemTools } from "../../tools/filesystem.js";
import { registerMemoryTools } from "../../tools/memory.js";
import { registerPlanTool } from "../../tools/plan.js";
import { registerShellTools } from "../../tools/shell.js";
import { registerSkillTools } from "../../tools/skills.js";
import { chatCommand } from "./chat.js";
export interface CodeOptions {
/** Directory to root the filesystem MCP at. Defaults to process.cwd(). */
/** Directory to root the filesystem tools at. Defaults to process.cwd(). */
dir?: string;
/** Override the default `smart` model. */
model?: string;
@@ -32,6 +38,10 @@ export interface CodeOptions {
noSession?: boolean;
/** Transcript file for replay/diff. */
transcript?: string;
/** Skip the session picker — always resume prior messages. */
forceResume?: boolean;
/** Skip the session picker — always wipe prior messages and start fresh. */
forceNew?: boolean;
}
export async function codeCommand(opts: CodeOptions = {}): Promise<void> {
@@ -41,13 +51,40 @@ export async function codeCommand(opts: CodeOptions = {}): Promise<void> {
// `code-<sanitized-basename>` fits the session name rules without
// truncating most project names.
const session = opts.noSession ? undefined : `code-${sanitizeName(basename(rootDir))}`;
// Filesystem MCP spec pointing at rootDir. Quote the path in case it
// has spaces — the existing shellSplit inside parseMcpSpec understands
// double quotes.
const fsSpec = `filesystem=npx -y @modelcontextprotocol/server-filesystem ${quoteIfNeeded(rootDir)}`;
// Native filesystem tools. No subprocess, ~50-200 ms faster per call
// than the MCP server was, and `edit_file` takes a flat SEARCH/REPLACE
// shape instead of the `string="false"` JSON-in-string array that
// triggered R1's DSML hallucinations all through 0.4.x.
const tools = new ToolRegistry();
registerFilesystemTools(tools, { rootDir });
registerShellTools(tools, {
rootDir,
// Per-project "always allow" list persisted from prior ShellConfirm
// choices; merged on top of the built-in allowlist in shell.ts.
// GETTER form — re-read every dispatch so a prefix the user adds
// via ShellConfirm mid-session takes effect on the next shell call
// instead of waiting for `/new` or a relaunch.
extraAllowed: () => loadProjectShellAllowed(rootDir),
});
// `submit_plan` is always in the spec list so the prefix cache stays
// stable across plan-mode toggles (Pillar 1). The tool itself is a
// no-op outside plan mode and throws `PlanProposedError` when the
// user has `/plan`-enabled the session.
registerPlanTool(tools);
// `remember` / `forget` / `recall_memory` — cross-session user memory.
// Project scope hashes off rootDir so switching projects gets a fresh
// per-project memory store; the global scope is shared across runs.
registerMemoryTools(tools, { projectRoot: rootDir });
// `run_skill` — loads user-authored prompt packs on demand. The
// index itself (names + descriptions) is already pinned into the
// system prompt by `applyMemoryStack`; this tool serves the bodies.
// Passing projectRoot surfaces `<rootDir>/.reasonix/skills/` alongside
// the global scope.
registerSkillTools(tools, { projectRoot: rootDir });
process.stderr.write(
`▸ reasonix code: rooted at ${rootDir}, session "${session ?? "(ephemeral)"}"\n`,
`▸ reasonix code: rooted at ${rootDir}, session "${session ?? "(ephemeral)"}" · ${tools.size} native tool(s)\n`,
);
await chatCommand({
@@ -56,11 +93,9 @@ export async function codeCommand(opts: CodeOptions = {}): Promise<void> {
system: codeSystemPrompt(rootDir),
transcript: opts.transcript,
session,
mcp: [fsSpec],
seedTools: tools,
codeMode: { rootDir },
forceResume: opts.forceResume,
forceNew: opts.forceNew,
});
}
function quoteIfNeeded(s: string): string {
return /\s|"/.test(s) ? `"${s.replace(/"/g, '\\"')}"` : s;
}
+1
View File
@@ -51,6 +51,7 @@ export async function diffCommand(opts: DiffOptions): Promise<void> {
if (wantTui) {
const { waitUntilExit } = render(React.createElement(DiffApp, { report }), {
exitOnCtrlC: true,
patchConsole: false,
});
await waitUntilExit();
return;
+107
View File
@@ -0,0 +1,107 @@
/**
* `reasonix mcp inspect <spec>` — connect to one MCP server, list
* everything it exposes (tools, resources, prompts), print a
* human-readable summary. Useful as:
* - a diagnostic tool for "does my MCP server even work?"
* - a discovery tool for "what can this server do?"
* - the only CLI surface for the resources+prompts methods added
* in 0.4.5 (chat mode consumes tools but hasn't wired up the
* other two families yet).
*/
import { McpClient } from "../../mcp/client.js";
import { inspectMcpServer } from "../../mcp/inspect.js";
import type { InspectionReport } from "../../mcp/inspect.js";
import { parseMcpSpec } from "../../mcp/spec.js";
import { SseTransport } from "../../mcp/sse.js";
import { type McpTransport, StdioTransport } from "../../mcp/stdio.js";
export interface McpInspectOptions {
/** The raw --mcp spec string (e.g. `fs=npx -y @modelcontextprotocol/server-filesystem .`). */
spec: string;
/** Emit JSON on stdout instead of the human-readable table. */
json?: boolean;
}
export async function mcpInspectCommand(opts: McpInspectOptions): Promise<void> {
const spec = parseMcpSpec(opts.spec);
const transport: McpTransport =
spec.transport === "sse"
? new SseTransport({ url: spec.url })
: new StdioTransport({ command: spec.command, args: spec.args });
const client = new McpClient({ transport });
try {
await client.initialize();
const report = await inspectMcpServer(client);
if (opts.json) {
console.log(JSON.stringify(report, null, 2));
} else {
console.log(formatReport(spec.name ?? "(anon)", report));
}
} finally {
await client.close();
}
}
function formatReport(nsName: string, r: InspectionReport): string {
const lines: string[] = [];
lines.push(`MCP server [${nsName}]`);
lines.push(
` server ${r.serverInfo.name || "(unknown)"}${r.serverInfo.version ? ` v${r.serverInfo.version}` : ""}`,
);
lines.push(` protocol ${r.protocolVersion}`);
const capKeys = Object.keys(r.capabilities);
lines.push(` caps ${capKeys.length > 0 ? capKeys.join(", ") : "(none advertised)"}`);
if (r.instructions) {
lines.push(` notes ${r.instructions.trim().slice(0, 200)}`);
}
lines.push("");
lines.push(formatSection("Tools", r.tools, toolLine));
lines.push(formatSection("Resources", r.resources, resourceLine));
lines.push(formatSection("Prompts", r.prompts, promptLine));
return lines.join("\n");
}
function formatSection<T>(
title: string,
section: { supported: true; items: T[] } | { supported: false; reason: string },
render: (item: T) => string,
): string {
if (!section.supported) {
return `${title}: (not supported — ${section.reason})`;
}
if (section.items.length === 0) {
return `${title}: (none)`;
}
const lines = [`${title} (${section.items.length}):`];
for (const item of section.items) lines.push(` ${render(item)}`);
return lines.join("\n");
}
function toolLine(t: { name: string; description?: string }): string {
const desc = t.description ? ` — ${oneLine(t.description, 80)}` : "";
return `· ${t.name}${desc}`;
}
function resourceLine(r: { uri: string; name: string; mimeType?: string }): string {
const mime = r.mimeType ? ` [${r.mimeType}]` : "";
return `· ${r.name}${mime} ${r.uri}`;
}
function promptLine(p: {
name: string;
description?: string;
arguments?: Array<{ name: string; required?: boolean }>;
}): string {
const argPart =
p.arguments && p.arguments.length > 0
? ` (${p.arguments.map((a) => (a.required ? a.name : `${a.name}?`)).join(", ")})`
: "";
const desc = p.description ? ` — ${oneLine(p.description, 80)}` : "";
return `· ${p.name}${argPart}${desc}`;
}
function oneLine(s: string, max: number): string {
const flat = s.replace(/\s+/g, " ").trim();
return flat.length <= max ? flat : `${flat.slice(0, max - 1)}…`;
}
+1
View File
@@ -31,6 +31,7 @@ export async function replayCommand(opts: ReplayOptions): Promise<void> {
const pages = groupRecordsByTurn(parsed.records);
const { waitUntilExit } = render(React.createElement(ReplayApp, { meta: parsed.meta, pages }), {
exitOnCtrlC: true,
patchConsole: false,
});
await waitUntilExit();
}
+7
View File
@@ -11,6 +11,7 @@ import { SseTransport } from "../../mcp/sse.js";
import { type McpTransport, StdioTransport } from "../../mcp/stdio.js";
import { ToolRegistry } from "../../tools.js";
import { openTranscriptFile, recordFromLoopEvent, writeRecord } from "../../transcript.js";
import { appendUsage } from "../../usage.js";
export interface RunOptions {
task: string;
@@ -148,6 +149,12 @@ export async function runCommand(opts: RunOptions): Promise<void> {
if (ev.role === "tool") process.stdout.write(`\n[tool ${ev.toolName}] ${ev.content}\n`);
if (ev.role === "error") process.stderr.write(`\n[error] ${ev.error}\n`);
if (ev.role === "done") process.stdout.write("\n");
if (ev.role === "assistant_final" && ev.stats?.usage) {
// `reasonix run` is often used in CI / scripting — we want
// those turns to show up in `reasonix stats` too so the
// dashboard reflects all DeepSeek spend, not just TUI sessions.
appendUsage({ session: null, model: ev.stats.model, usage: ev.stats.usage });
}
// Persist every non-streaming event — deltas would flood the file and
// aren't useful for replay (replay renders final content, not keystrokes).
if (transcriptStream && ev.role !== "assistant_delta") {
+1 -1
View File
@@ -39,7 +39,7 @@ export async function setupCommand(_opts: SetupOptions = {}): Promise<void> {
unmount();
}}
/>,
{ exitOnCtrlC: true },
{ exitOnCtrlC: true, patchConsole: false },
);
await waitUntilExit();
}
+139 -5
View File
@@ -1,15 +1,60 @@
/**
* `reasonix stats` — two modes, decided by whether the user passed
* a transcript path.
*
* - `reasonix stats` → cross-session usage dashboard
* (reads `~/.reasonix/usage.jsonl`)
* - `reasonix stats <path>` → summary of a single JSONL transcript
* (original v0.1 behavior, kept so
* existing scripts don't break)
*
* The dashboard is the new story: for every turn `reasonix chat|code|run`
* has ever executed on this machine, we aggregate tokens + cost + the
* equivalent Claude spend, and print rolling-window totals (today /
* week / month / all-time). The savings column is the Pillar 1 pitch
* made concrete — "you paid $X; Claude would have charged $Y, a N%
* reduction."
*/
import { existsSync, readFileSync } from "node:fs";
import {
type UsageAggregate,
type UsageBucket,
aggregateUsage,
bucketCacheHitRatio,
bucketSavingsFraction,
defaultUsageLogPath,
formatLogSize,
readUsageLog,
} from "../../usage.js";
export interface StatsOptions {
transcript: string;
/** Optional transcript path. Absent → dashboard mode. */
transcript?: string;
/** Override usage log location (tests). */
logPath?: string;
/** Inject a fixed timestamp (tests) so rolling windows are deterministic. */
now?: number;
}
export function statsCommand(opts: StatsOptions): void {
if (!existsSync(opts.transcript)) {
console.error(`no such transcript: ${opts.transcript}`);
if (opts.transcript) {
transcriptSummary(opts.transcript);
return;
}
dashboard(opts);
}
// ---------------------------------------------------------------------
// Transcript summary — legacy v0.1 behavior, preserved verbatim.
// ---------------------------------------------------------------------
function transcriptSummary(path: string): void {
if (!existsSync(path)) {
console.error(`no such transcript: ${path}`);
process.exit(1);
}
const lines = readFileSync(opts.transcript, "utf8").split(/\r?\n/).filter(Boolean);
const lines = readFileSync(path, "utf8").split(/\r?\n/).filter(Boolean);
let assistantTurns = 0;
let toolCalls = 0;
let lastTurn = 0;
@@ -23,8 +68,97 @@ export function statsCommand(opts: StatsOptions): void {
/* skip */
}
}
console.log(`transcript: ${opts.transcript}`);
console.log(`transcript: ${path}`);
console.log(`assistant turns: ${assistantTurns}`);
console.log(`tool invocations: ${toolCalls}`);
console.log(`last turn index: ${lastTurn}`);
}
// ---------------------------------------------------------------------
// Dashboard — aggregates ~/.reasonix/usage.jsonl.
// ---------------------------------------------------------------------
function dashboard(opts: StatsOptions): void {
const path = opts.logPath ?? defaultUsageLogPath();
const records = readUsageLog(path);
if (records.length === 0) {
console.log("no usage data yet.");
console.log("");
console.log(` ${path}`);
console.log("");
console.log("run `reasonix chat`, `reasonix code`, or `reasonix run <task>` — every turn");
console.log("appends one line to the log and `reasonix stats` will roll it up.");
return;
}
const agg = aggregateUsage(records, { now: opts.now });
console.log(renderDashboard(agg, path));
}
/** Pure renderer — pulled out so tests can assert on the string directly. */
export function renderDashboard(agg: UsageAggregate, logPath: string): string {
const lines: string[] = [];
const size = formatLogSize(logPath);
lines.push(`Reasonix usage — ${logPath}${size ? ` (${size})` : ""}`);
lines.push("");
lines.push(header());
lines.push(divider());
for (const b of agg.buckets) {
lines.push(bucketRow(b));
}
lines.push("");
// Model + session breakdown — both trim to top 3 so a user with 20
// sessions doesn't drown the table.
if (agg.byModel.length > 0) {
const totalTurns = agg.buckets[agg.buckets.length - 1]?.turns ?? 0;
const top = agg.byModel[0];
if (top && totalTurns > 0) {
const pct = ((top.turns / totalTurns) * 100).toFixed(0);
lines.push(`most used model: ${top.model} (${pct}% of turns)`);
}
}
if (agg.bySession.length > 0) {
const top = agg.bySession[0];
if (top) lines.push(`top session: ${top.session} (${top.turns} turns)`);
}
if (agg.firstSeen) {
lines.push(`tracked since: ${new Date(agg.firstSeen).toISOString().slice(0, 10)}`);
}
return lines.join("\n");
}
function header(): string {
// Fixed column widths so alignment works in any TTY.
return [
pad("", 10),
pad("turns", 8, "right"),
pad("cache hit", 10, "right"),
pad("cost (USD)", 14, "right"),
pad("vs Claude", 14, "right"),
pad("saved", 10, "right"),
].join(" ");
}
function divider(): string {
return "-".repeat(70);
}
function bucketRow(b: UsageBucket): string {
const hit = bucketCacheHitRatio(b);
const savings = bucketSavingsFraction(b);
return [
pad(b.label, 10),
pad(b.turns.toString(), 8, "right"),
pad(b.turns > 0 ? `${(hit * 100).toFixed(1)}%` : "—", 10, "right"),
pad(b.turns > 0 ? `$${b.costUsd.toFixed(6)}` : "—", 14, "right"),
pad(b.turns > 0 ? `$${b.claudeEquivUsd.toFixed(4)}` : "—", 14, "right"),
pad(b.turns > 0 && savings > 0 ? `${(savings * 100).toFixed(1)}%` : "—", 10, "right"),
].join(" ");
}
function pad(s: string, width: number, align: "left" | "right" = "left"): string {
if (s.length >= width) return s;
const fill = " ".repeat(width - s.length);
return align === "right" ? `${fill}${s}` : `${s}${fill}`;
}
+143
View File
@@ -0,0 +1,143 @@
/**
* `reasonix update` — self-upgrade command.
*
* Talks to the npm registry, compares against the running version,
* and either runs `npm install -g reasonix@latest` (global install)
* or advises how to refresh the npx cache (ephemeral install).
*
* The decision logic is factored into `planUpdate()` so it can be
* unit-tested without spawning child processes or hitting the
* network. `updateCommand()` is the thin CLI wrapper that calls
* `getLatestVersion`, passes the result into `planUpdate`, and
* executes any suggested command.
*/
import { spawn } from "node:child_process";
import { VERSION, compareVersions, getLatestVersion, isNpxInstall } from "../../version.js";
export type UpdateAction = "up-to-date" | "newer-local" | "npx-hint" | "run-npm-install";
export interface UpdatePlan {
action: UpdateAction;
/** Human-readable summary; the CLI prints this verbatim. */
message: string;
/**
* Argv for the install command when `action === "run-npm-install"`.
* Absent otherwise. Kept as array so the CLI can pass it straight
* to `spawn` without re-parsing shell syntax.
*/
command?: string[];
}
export interface PlanUpdateInput {
current: string;
latest: string;
/** Overrides `isNpxInstall()` (tests). */
npx?: boolean;
}
/**
* Pure decision function: given current + latest + install kind,
* decide what the CLI should do. No I/O.
*
* newer-local — current > latest (dev build, local publish)
* up-to-date — current === latest
* npx-hint — current < latest AND running under npx
* run-npm-install — current < latest AND running as a real install
*/
export function planUpdate(input: PlanUpdateInput): UpdatePlan {
const diff = compareVersions(input.current, input.latest);
if (diff > 0) {
return {
action: "newer-local",
message: `current (${input.current}) is newer than the published ${input.latest} — nothing to do.`,
};
}
if (diff === 0) {
return { action: "up-to-date", message: `reasonix ${input.current} is up to date.` };
}
if (input.npx) {
return {
action: "npx-hint",
message: [
`reasonix ${input.latest} is available.`,
"you're running via npx — the next `npx reasonix ...` launch will auto-fetch",
"the latest (npx caches packages for a short window). to force a refresh",
"sooner, clear the cache: `npm cache clean --force`.",
].join("\n"),
};
}
return {
action: "run-npm-install",
message: `upgrading reasonix ${input.current} → ${input.latest}`,
command: ["npm", "install", "-g", "reasonix@latest"],
};
}
export interface UpdateCommandOptions {
/** Skip spawning npm; print the decision only. */
dryRun?: boolean;
/** Test seam: override the registry lookup. Returns null = offline. */
fetchLatest?: () => Promise<string | null>;
/** Test seam: override the npx detector. */
isNpx?: () => boolean;
/** Test seam: override the spawner. Must return exit code. */
spawnInstall?: (argv: string[]) => Promise<number>;
/** Test seam: stdout writer. */
write?: (msg: string) => void;
/** Test seam: process exit — tests don't want to tear down vitest. */
exit?: (code: number) => void;
}
function defaultSpawn(argv: string[]): Promise<number> {
return new Promise((resolve, reject) => {
// `shell: true` on Windows is what lets `npm` resolve to `npm.cmd`
// without routing through our `prepareSpawn` helper. The args here
// are literal strings under our control — no user input flows in,
// so injection is not a concern. Avoiding `prepareSpawn` keeps
// this command free of a dep on the shell tools module.
const child = spawn(argv[0]!, argv.slice(1), {
stdio: "inherit",
shell: process.platform === "win32",
});
child.once("error", reject);
child.once("exit", (code) => resolve(code ?? 1));
});
}
/**
* Run the update command. Prints a banner, resolves the latest
* version, prints the plan, and (unless `--dry-run`) executes the
* install when applicable.
*/
export async function updateCommand(opts: UpdateCommandOptions = {}): Promise<void> {
const write = opts.write ?? ((m: string) => process.stdout.write(m));
const exit = opts.exit ?? ((c: number) => process.exit(c));
const fetchLatest = opts.fetchLatest ?? (() => getLatestVersion({ force: true }));
const isNpx = opts.isNpx ?? isNpxInstall;
const doSpawn = opts.spawnInstall ?? defaultSpawn;
write(`current: reasonix ${VERSION}\n`);
const latest = await fetchLatest();
if (!latest) {
write("could not reach registry.npmjs.org — check your network.\n");
exit(1);
return;
}
write(`latest: reasonix ${latest}\n`);
const plan = planUpdate({ current: VERSION, latest, npx: isNpx() });
write(`\n${plan.message}\n`);
if (plan.action !== "run-npm-install" || !plan.command) return;
if (opts.dryRun) {
write(`(dry run) would run: ${plan.command.join(" ")}\n`);
return;
}
write(`\nrunning: ${plan.command.join(" ")}\n`);
const code = await doSpawn(plan.command);
if (code !== 0) {
write(`\nnpm exited with code ${code}. upgrade did not complete.\n`);
exit(code);
}
}
+45 -6
View File
@@ -1,15 +1,18 @@
import { Command } from "commander";
import { readConfig } from "../config.js";
import { VERSION } from "../index.js";
import { applyMemoryStack } from "../user-memory.js";
import { chatCommand } from "./commands/chat.js";
import { codeCommand } from "./commands/code.js";
import { diffCommand } from "./commands/diff.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 { resolveDefaults } from "./resolve.js";
@@ -36,7 +39,7 @@ program.action(async () => {
const defaults = resolveDefaults({});
await chatCommand({
model: defaults.model,
system: DEFAULT_SYSTEM,
system: applyMemoryStack(DEFAULT_SYSTEM, process.cwd()),
harvest: defaults.harvest,
branch: defaults.branch,
session: defaults.session,
@@ -58,6 +61,8 @@ program
)
.option("-m, --model <id>", "Override default reasoner model")
.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")
.action(async (dir: string | undefined, opts) => {
await codeCommand({
@@ -65,6 +70,8 @@ program
model: opts.model,
noSession: opts.session === false,
transcript: opts.transcript,
forceResume: !!opts.resume,
forceNew: !!opts.new,
});
});
@@ -89,6 +96,8 @@ program
)
.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("-n, --new", "Skip the session picker — always wipe prior messages and start fresh")
.option(
"--mcp <spec>",
'MCP server spec; repeatable. "name=cmd args...", "cmd args...", or a URL (http/https → SSE transport). Overrides config.mcp when provided.',
@@ -112,13 +121,15 @@ program
});
await chatCommand({
model: defaults.model,
system: opts.system,
system: applyMemoryStack(opts.system, process.cwd()),
transcript: opts.transcript,
harvest: defaults.harvest,
branch: defaults.branch,
session: defaults.session,
mcp: defaults.mcp,
mcpPrefix: opts.mcpPrefix,
forceResume: !!opts.resume,
forceNew: !!opts.new,
});
});
@@ -158,7 +169,7 @@ program
await runCommand({
task,
model: defaults.model,
system: opts.system,
system: applyMemoryStack(opts.system, process.cwd()),
harvest: defaults.harvest,
branch: defaults.branch,
transcript: opts.transcript,
@@ -168,9 +179,12 @@ program
});
program
.command("stats <transcript>")
.description("Summarize a JSONL transcript produced by `reasonix chat --transcript`.")
.action((transcript: string) => {
.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) => {
statsCommand({ transcript });
});
@@ -233,8 +247,33 @@ mcp
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) => {
try {
await mcpInspectCommand({ spec, json: !!opts.json });
} catch (err) {
process.stderr.write(`mcp inspect failed: ${(err as Error).message}\n`);
process.exit(1);
}
});
program.command("version").description("Print Reasonix version.").action(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")
.action(async (opts: { dryRun?: boolean }) => {
await updateCommand({ dryRun: !!opts.dryRun });
});
program.parseAsync(process.argv).catch((err) => {
console.error(err);
process.exit(1);
+919 -70
View File
File diff suppressed because it is too large. Load diff
+136 -32
View File
@@ -1,10 +1,11 @@
import { Box, Text } from "ink";
import React, { useEffect, useState } from "react";
import React from "react";
import { type TypedPlanState, isPlanStateEmpty } from "../../harvest.js";
import type { BranchProgress, BranchSummary } from "../../loop.js";
import type { TurnStats } from "../../telemetry.js";
import { PlanStateBlock } from "./PlanStateBlock.js";
import { Markdown } from "./markdown.js";
import { useElapsedSeconds, useTick } from "./ticker.js";
export type DisplayRole = "user" | "assistant" | "tool" | "system" | "error" | "info" | "warning";
@@ -20,6 +21,7 @@ export interface DisplayEvent {
stats?: TurnStats;
repair?: string;
streaming?: boolean;
toolCallBuild?: { name: string; chars: number };
}
export const EventRow = React.memo(function EventRow({ event }: { event: DisplayEvent }) {
@@ -54,10 +56,32 @@ export const EventRow = React.memo(function EventRow({ event }: { event: Display
);
}
if (event.role === "tool") {
// `flattenMcpResult` prefixes server-side errors with "ERROR: ".
// Render those in red with a ✗ marker so they don't blend into
// successful tool output (yellow) — the failure mode is what the
// model most likely needs to act on next, and the user needs to
// see at a glance.
const isError = event.text.startsWith("ERROR:");
const color = isError ? "red" : "yellow";
const marker = isError ? "✗" : "→";
// `edit_file` results get a dedicated diff renderer — colored
// line-by-line so `-` removals show red, `+` additions show
// green, unchanged context lines dim. Always full, never
// truncated: users need to see the whole change to trust
// /apply. Other tools keep the 400-char clip + /tool N escape.
const isEditFile =
(event.toolName === "edit_file" || event.toolName?.endsWith("_edit_file")) && !isError;
return (
<Box flexDirection="column" marginTop={1}>
<Text color="yellow">{`tool<${event.toolName ?? "?"}> →`}</Text>
<Text dimColor> {truncate(event.text, 400)}</Text>
<Text color={color}>{`tool<${event.toolName ?? "?"}> ${marker}`}</Text>
{isEditFile ? (
<EditFileDiff text={event.text} />
) : (
<Text color={isError ? "red" : undefined} dimColor={!isError}>
{" "}
{truncate(event.text, 400)}
</Text>
)}
</Box>
);
}
@@ -93,6 +117,61 @@ export const EventRow = React.memo(function EventRow({ event }: { event: Display
);
});
/**
* Render the payload of an `edit_file` tool result with proper
* diff coloring: first line is the header ("edited X (A→B chars)"),
* subsequent lines are prefixed with `-` (removed), `+` (added), or
* space (unchanged context). Unchanged lines render dim so the
* changed ones pop visually. No truncation — the whole diff is
* shown so the user can audit what landed before `/apply` or
* `git diff` review.
*/
function EditFileDiff({ text }: { text: string }) {
const lines = text.split(/\r?\n/);
// Line 0 is the status header ("edited X (A→B chars)"), Line 1 is
// the unified-diff hunk header ("@@ -N,M +N,M @@"), the rest is
// the colored diff body. We style the two headers distinctly so
// the hunk marker stands out the way git-diff's cyan `@@` does in
// most terminals.
const [statusHeader, hunkHeader, ...body] = lines;
return (
<Box flexDirection="column">
<Text dimColor>{` ${statusHeader ?? ""}`}</Text>
{hunkHeader !== undefined ? (
<Text color="cyan" bold>
{hunkHeader}
</Text>
) : null}
{body.map((line, i) => {
// Key includes the line content slice so React isn't forced
// to treat purely-positional identity; lines in the same
// diff don't reorder but could repeat (e.g. blank lines).
const key = `${i}-${line.slice(0, 32)}`;
if (line.startsWith("- ")) {
return (
<Text key={key} color="red">
{line}
</Text>
);
}
if (line.startsWith("+ ")) {
return (
<Text key={key} color="green">
{line}
</Text>
);
}
// Context line (starts with " ") or unknown — dim.
return (
<Text key={key} dimColor>
{line}
</Text>
);
})}
</Box>
);
}
function BranchBlock({ branch }: { branch: BranchSummary }) {
const per = branch.uncertainties
.map((u, i) => {
@@ -139,12 +218,7 @@ function ReasoningBlock({ reasoning }: { reasoning: string }) {
* the terminal viewport and leaves artifacts in scrollback.
*/
function Elapsed() {
const [s, setS] = useState(0);
useEffect(() => {
const start = Date.now();
const id = setInterval(() => setS(Math.floor((Date.now() - start) / 1000)), 1000);
return () => clearInterval(id);
}, []);
const s = useElapsedSeconds();
const mm = String(Math.floor(s / 60)).padStart(2, "0");
const ss = String(s % 60).padStart(2, "0");
return <Text dimColor>{`${mm}:${ss}`}</Text>;
@@ -197,12 +271,41 @@ function StreamingAssistant({ event }: { event: DisplayEvent }) {
const tail = lastLine(event.text, 140);
const reasoningTail = event.reasoning ? lastLine(event.reasoning, 120) : "";
// R1 ("deepseek-reasoner") generates reasoning_content first, then
// content. While reasoning is streaming but content is still empty,
// we were showing "(waiting for first token…)" — which looked like a
// hang. The data is flowing, it's just landing in the thinking
// channel. Reflect that honestly.
const reasoningOnly = !event.text && !!event.reasoning;
const toolCallBuild = event.toolCallBuild;
// Four distinct phases a turn can be in — label them plainly so
// the user doesn't have to decode "streaming · 391 + think 4506
// chars" to figure out what's happening:
// pre-first-byte: request in flight, no bytes back yet
// reasoning-only: R1 thinking, no visible content yet
// tool-call-only: tool_call arguments streaming, no content/reasoning bytes
// writing: content streaming (R1 has already produced its thought)
// both: rare — content present AND reasoning still growing
// We can't cheaply distinguish "reasoning still growing" from
// "reasoning finished but we already saw it", so when content is
// present we just say "writing response" and surface both counts.
const preFirstByte = !event.text && !event.reasoning && !toolCallBuild;
const reasoningOnly = !event.text && !!event.reasoning && !toolCallBuild;
const toolCallOnly = !event.text && !event.reasoning && !!toolCallBuild;
let label: string;
let labelColor: "yellow" | "cyan" | "green" | "magenta" | undefined;
if (preFirstByte) {
label = "request sent · waiting for server";
labelColor = "yellow";
} else if (reasoningOnly) {
label = `R1 reasoning · ${event.reasoning?.length ?? 0} chars of thought`;
labelColor = "cyan";
} else if (toolCallOnly) {
label = `assembling tool call <${toolCallBuild.name}> · ${toolCallBuild.chars} chars of arguments`;
labelColor = "magenta";
} else {
const parts: string[] = [`writing response · ${event.text.length} chars`];
if (event.reasoning) parts.push(`after ${event.reasoning.length} chars of reasoning`);
if (toolCallBuild) {
parts.push(`building tool call <${toolCallBuild.name}> · ${toolCallBuild.chars} chars`);
}
label = parts.join(" · ");
labelColor = "green";
}
return (
<Box flexDirection="column" marginTop={1}>
<Box>
@@ -210,11 +313,7 @@ function StreamingAssistant({ event }: { event: DisplayEvent }) {
assistant{" "}
</Text>
<Pulse />
<Text dimColor>
{" "}
({reasoningOnly ? "reasoning" : "streaming"} · {event.text.length}
{event.reasoning ? ` + think ${event.reasoning.length}` : ""} chars){" "}
</Text>
<Text color={labelColor}>{` ${label} `}</Text>
<Elapsed />
</Box>
{reasoningTail ? (
@@ -224,34 +323,39 @@ function StreamingAssistant({ event }: { event: DisplayEvent }) {
) : null}
{tail ? (
<Text dimColor>▸ {tail}</Text>
) : preFirstByte ? (
<Text dimColor italic>
{" connection open, first byte typically in 5-60s depending on model + load"}
</Text>
) : reasoningOnly ? (
<Text color="yellow" dimColor>
{
" R1 is thinking before it speaks — body text starts when reasoning completes (typically 20-90s)."
}
</Text>
) : (
<Text dimColor italic>
{" (waiting for first byte — connection is open)"}
) : toolCallOnly ? (
<Text color="magenta" dimColor>
{" tool-call arguments streaming — the model is about to dispatch a tool"}
</Text>
)}
) : event.reasoning ? (
<Text color="yellow" dimColor>
{" R1 still reasoning — body text or tool call arrives when thinking completes"}
</Text>
) : null}
</Box>
);
}
/**
* Blinking indicator so the user can tell the stream is alive even
* when the reasoner hasn't produced body text yet. Ticks every 500 ms
* regardless of content flow — it's a heartbeat, not a progress bar.
* when the reasoner hasn't produced body text yet. Uses the shared
* tick (TICK_MS ≈ 120ms) scaled down 4× so the visible blink rate
* lands around 500ms — feels like a heartbeat, not a progress bar.
*/
function Pulse() {
const [tick, setTick] = useState(0);
useEffect(() => {
const id = setInterval(() => setTick((t) => t + 1), 500);
return () => clearInterval(id);
}, []);
const tick = useTick();
const frames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
return <Text color="cyan">{frames[tick % frames.length]}</Text>;
return <Text color="cyan">{frames[Math.floor(tick / 4) % frames.length]}</Text>;
}
function lastLine(s: string, maxChars: number): string {
+97
View File
@@ -0,0 +1,97 @@
/**
* Modal-style approval for a `submit_plan` proposal.
*
* Three choices:
* 1. Approve + implement — exits plan mode, pushes a synthetic user
* message telling the model to implement the plan now.
* 2. Refine — stays in plan mode; tells the model to explore more
* and submit an improved plan.
* 3. Cancel — exits plan mode, drops the plan, tells the model the
* user didn't want any of it.
*
* Mirrors ShellConfirm in structure (border, SingleSelect, three
* options, no y/n hotkey — mid-typing triggers would be painful).
* The plan body is rendered verbatim above the picker so the user can
* actually read what they're approving.
*/
import { Box, Text } from "ink";
import React from "react";
import { SingleSelect } from "./Select.js";
import { Markdown } from "./markdown.js";
export type PlanConfirmChoice = "approve" | "refine" | "cancel";
export interface PlanConfirmProps {
plan: string;
onChoose: (choice: PlanConfirmChoice) => void;
/**
* Cap on rendered plan length. A pathological 20-KB plan would push
* the picker off the bottom of the terminal; we show the head +
* "(…N chars truncated — /tool for full output)" instead. The picker
* itself gets the full plan (it's already been committed to the
* transcript via the tool result).
*/
maxRenderedChars?: number;
}
const DEFAULT_MAX_RENDERED = 2400;
export function PlanConfirm({ plan, onChoose, maxRenderedChars }: PlanConfirmProps) {
const cap = maxRenderedChars ?? DEFAULT_MAX_RENDERED;
const tooLong = plan.length > cap;
const visible = tooLong
? `${plan.slice(0, cap)}\n\n… (${plan.length - cap} chars truncated — use /tool to view the full proposal)`
: plan;
// Crude signal for "the model left questions or risks for me" — the
// typical section headings. Triggers an extra hint toward the Refine
// option so users know where to answer them.
const hasOpenQuestions =
/^#{1,6}\s*(open[-\s]?questions?|risks?|unknowns?|assumptions?|unclear)/im.test(plan) ||
/^#{1,6}\s*(待确认|开放问题|风险|未知|假设|不确定)/im.test(plan);
return (
<Box flexDirection="column" borderStyle="round" borderColor="cyan" paddingX={1} marginY={1}>
<Box>
<Text bold color="cyan">
▸ plan submitted — awaiting your review
</Text>
</Box>
<Box marginTop={1} flexDirection="column">
<Markdown text={visible} />
</Box>
{hasOpenQuestions ? (
<Box marginTop={1}>
<Text color="yellow">
▲ the plan has open questions or flagged risks — pick{" "}
<Text bold>Refine / answer questions</Text> to write concrete answers before the model
moves on.
</Text>
</Box>
) : null}
<Box marginTop={1}>
<SingleSelect
initialValue={hasOpenQuestions ? "refine" : "approve"}
items={[
{
value: "approve",
label: "Approve and implement",
hint: "Exit plan mode. The model starts executing. You'll get a text input to add any last instructions (or just press Enter to skip).",
},
{
value: "refine",
label: "Refine / answer questions",
hint: "Stay in plan mode. Write answers, modifications, or critiques; the model revises and re-submits.",
},
{
value: "cancel",
label: "Cancel",
hint: "Exit plan mode. Drop the plan; the model won't implement it.",
},
]}
onSubmit={(v) => onChoose(v as PlanConfirmChoice)}
/>
</Box>
</Box>
);
}
+91
View File
@@ -0,0 +1,91 @@
/**
* Inline text input shown after the user picks Approve or Refine in
* PlanConfirm. Collects free-form feedback before the loop resumes.
*
* Why both paths: the plan may contain open questions or risks the
* model asked the user to weigh in on. If the user just picks Approve
* with no chance to answer, the model implements against its own
* guesses. This input lets the user answer questions, pass last-minute
* constraints, or (on Refine) request concrete changes. Empty input is
* fine for Approve (skip straight to implement) and triggers a
* "ask the user clarifying questions" path for Refine.
*
* Kept minimal: single-line prompt, Enter to submit, Esc to return to
* the picker without resuming.
*/
import { Box, Text, useInput } from "ink";
import React, { useState } from "react";
export interface PlanRefineInputProps {
/**
* Which path the user is on. Approve = "implement with these last
* instructions"; refine = "revise the plan with this feedback".
* Drives the header + hint text so users know what kind of message
* they're writing.
*/
mode: "approve" | "refine";
/** Called with trimmed feedback. Empty string is allowed. */
onSubmit: (feedback: string) => void;
/** Called when the user presses Esc to return to the picker. */
onCancel: () => void;
}
export function PlanRefineInput({ mode, onSubmit, onCancel }: PlanRefineInputProps) {
const [value, setValue] = useState("");
useInput((input, key) => {
if (key.escape) {
onCancel();
return;
}
if (key.return) {
onSubmit(value.trim());
return;
}
if (key.backspace || key.delete) {
setValue((v) => v.slice(0, -1));
return;
}
// Filter out non-printable chars; accept ordinary text + CJK.
if (input && !key.ctrl && !key.meta) {
setValue((v) => v + input);
}
});
const title =
mode === "approve"
? "▸ approving — any last instructions or answers to open questions?"
: "▸ refining — what should the model change?";
const hint =
mode === "approve"
? "Answer questions the plan raised, add constraints, or just press Enter to approve as-is."
: "Describe what's wrong or missing, or answer questions the plan raised.";
const blankHint =
mode === "approve"
? " (Enter with blank = approve without extra instructions.)"
: " (Enter with blank = ask the model to list concrete questions.)";
return (
<Box flexDirection="column" borderStyle="round" borderColor="yellow" paddingX={1} marginY={1}>
<Box>
<Text bold color="yellow">
{title}
</Text>
</Box>
<Box marginTop={1}>
<Text dimColor>
{hint} Enter to send · Esc to return to the picker.
{value === "" ? blankHint : ""}
</Text>
</Box>
<Box marginTop={1}>
<Text>
<Text color="yellow">› </Text>
<Text>{value || " "}</Text>
<Text color="yellow">▍</Text>
</Text>
</Box>
</Box>
);
}
+140 -19
View File
@@ -1,6 +1,7 @@
import { Box, Text } from "ink";
import TextInput from "ink-text-input";
import React from "react";
import { Box, Text, useInput } from "ink";
import React, { useRef, useState } from "react";
import { type MultilineKey, lineAndColumn, processMultilineKey } from "./multiline-keys.js";
import { useTick } from "./ticker.js";
export interface PromptInputProps {
value: string;
@@ -11,10 +12,16 @@ export interface PromptInputProps {
}
/**
* Keep `<TextInput>` mounted at all times and use its `focus` prop to gate
* input. Conditionally rendering it (mount / unmount between turns) loses
* the stdin raw-mode claim on some terminals, which silently drops
* keystrokes after the first turn finishes.
* Input box with real cursor support. ←/→ move one column, ↑/↓ move
* across lines in multi-line buffers, Ctrl+A / Ctrl+E jump to
* start/end of the current line. Backspace deletes before cursor,
* Delete deletes under cursor. Multi-line composition via Ctrl+J,
* Shift+Enter, or bash-style `\<Enter>`.
*
* Cursor state lives locally. When the parent replaces `value` out
* of band (history recall, slash completion, setup wizard) the
* cursor jumps to end; the `lastLocalValueRef` guards distinguishes
* that case from our own edits.
*/
export function PromptInput({
value,
@@ -23,21 +30,135 @@ export function PromptInput({
disabled,
placeholder,
}: PromptInputProps) {
const [cursor, setCursor] = useState(value.length);
// Tracks the last `value` we ourselves produced via onChange. If the
// incoming `value` prop diverges from this, the parent (or some other
// source) replaced the buffer — we reset the cursor to end.
const lastLocalValueRef = useRef(value);
if (value !== lastLocalValueRef.current) {
lastLocalValueRef.current = value;
if (cursor !== value.length) {
// Conditional setState during render is the "derived state" pattern;
// React schedules the re-render and the else branch of the `if`
// prevents infinite loops.
setCursor(value.length);
}
}
// Shared ticker drives the cursor blink. Dividing the tick by 4 lands
// the visible on/off cycle around 480ms — standard cursor cadence.
const tick = useTick();
const showCursor = disabled ? false : Math.floor(tick / 4) % 2 === 0;
useInput(
(input, key) => {
const ke: MultilineKey = {
input,
return: key.return,
shift: key.shift,
ctrl: key.ctrl,
meta: key.meta,
backspace: key.backspace,
delete: key.delete,
tab: key.tab,
upArrow: key.upArrow,
downArrow: key.downArrow,
leftArrow: key.leftArrow,
rightArrow: key.rightArrow,
escape: key.escape,
pageUp: key.pageUp,
pageDown: key.pageDown,
};
const action = processMultilineKey(value, cursor, ke);
if (action.next !== null) {
lastLocalValueRef.current = action.next;
onChange(action.next);
}
if (action.cursor !== null) {
setCursor(action.cursor);
}
if (action.submit) onSubmit(action.submitValue ?? value);
},
{ isActive: !disabled },
);
const effectivePlaceholder = disabled
? (placeholder ?? "…waiting for response…")
: (placeholder ?? "type a message, or /command");
: (placeholder ?? "type a message, or /command · Ctrl+J for newline");
const lines = value.length > 0 ? value.split("\n") : [""];
const borderColor = disabled ? "gray" : "cyan";
const { line: cursorLine, col: cursorCol } = lineAndColumn(value, cursor);
return (
<Box borderStyle="round" borderColor={disabled ? "gray" : "cyan"} paddingX={1}>
<Text bold color={disabled ? "gray" : "cyan"}>
you ›{" "}
</Text>
<TextInput
value={value}
onChange={onChange}
onSubmit={onSubmit}
focus={!disabled}
placeholder={effectivePlaceholder}
/>
<Box borderStyle="round" borderColor={borderColor} paddingX={1} flexDirection="column">
{lines.map((line, i) => {
const isFirst = i === 0;
const showPlaceholder = isFirst && value.length === 0;
const isCursorLine = i === cursorLine;
return (
// biome-ignore lint/suspicious/noArrayIndexKey: stable by construction — lines are derived from `value.split("\n")` and never reordered
<Box key={i}>
{isFirst ? (
<Text bold color={borderColor}>
you ›{" "}
</Text>
) : (
<Text dimColor>{" "}</Text>
)}
{showPlaceholder ? (
<>
{isCursorLine && !disabled ? (
<Text color={borderColor}>{showCursor ? "▌" : " "}</Text>
) : null}
<Text dimColor>{effectivePlaceholder}</Text>
</>
) : isCursorLine && !disabled ? (
<LineWithCursor
line={line}
col={cursorCol}
showCursor={showCursor}
borderColor={borderColor}
/>
) : (
<Text>{line}</Text>
)}
</Box>
);
})}
</Box>
);
}
function LineWithCursor({
line,
col,
showCursor,
borderColor,
}: {
line: string;
col: number;
showCursor: boolean;
borderColor: "cyan" | "gray";
}) {
const before = line.slice(0, col);
const atCursor = line.slice(col, col + 1);
const after = line.slice(col + 1);
if (atCursor.length === 0) {
// Cursor sits past the last char of this line (end-of-line). Render
// a trailing block so the user sees where they're typing next.
return (
<>
<Text>{before}</Text>
<Text color={borderColor}>{showCursor ? "▌" : " "}</Text>
</>
);
}
return (
<>
<Text>{before}</Text>
<Text inverse={showCursor}>{atCursor}</Text>
<Text>{after}</Text>
</>
);
}
+2
View File
@@ -52,6 +52,8 @@ export function ReplayApp({ meta, pages }: ReplayAppProps) {
const summary = {
turns: cumStats.turns,
totalCostUsd: cumStats.totalCostUsd,
totalInputCostUsd: cumStats.totalInputCostUsd,
totalOutputCostUsd: cumStats.totalOutputCostUsd,
claudeEquivalentUsd: cumStats.claudeEquivalentUsd,
savingsVsClaudePct: cumStats.savingsVsClaudePct,
cacheHitRatio: cumStats.cacheHitRatio,
+72
View File
@@ -0,0 +1,72 @@
import { Box, Text } from "ink";
import React from "react";
import { SingleSelect } from "./Select.js";
export type SessionChoice = "resume" | "new" | "delete";
export interface SessionPickerProps {
sessionName: string;
messageCount: number;
/** mtime of the session file; used to render "last active Nh ago". */
lastActive: Date;
onChoose: (choice: SessionChoice) => void;
}
export function SessionPicker({
sessionName,
messageCount,
lastActive,
onChoose,
}: SessionPickerProps) {
return (
<Box flexDirection="column" marginY={1}>
<Box marginBottom={1}>
<Text bold color="cyan">
{`Session "${sessionName}" has ${messageCount} prior message${messageCount === 1 ? "" : "s"}`}
</Text>
<Text dimColor>{` · last active ${relativeTime(lastActive)}`}</Text>
</Box>
<SingleSelect
initialValue="new"
items={[
{
value: "new",
label: "Start new conversation",
hint: "Previous messages kept on disk; your turn starts fresh.",
},
{
value: "resume",
label: "Resume",
hint: `Continue where you left off (${messageCount} messages in context).`,
},
{
value: "delete",
label: "Delete and start new",
hint: "Wipes the session file irreversibly. Other sessions untouched.",
},
]}
onSubmit={(v) => onChoose(v as SessionChoice)}
/>
<Box marginTop={1}>
<Text dimColor>↑↓ to move · Enter to pick</Text>
</Box>
</Box>
);
}
/**
* "Nh ago" / "Nm ago" / "yesterday" style relative time. Deliberately
* coarse — the picker just needs a sense of "how stale is this session".
*/
function relativeTime(date: Date): string {
const ms = Date.now() - date.getTime();
const mins = Math.floor(ms / 60_000);
if (mins < 1) return "just now";
if (mins < 60) return `${mins}m ago`;
const hours = Math.floor(mins / 60);
if (hours < 24) return `${hours}h ago`;
const days = Math.floor(hours / 24);
if (days === 1) return "yesterday";
if (days < 7) return `${days}d ago`;
return date.toISOString().slice(0, 10);
}
+105
View File
@@ -0,0 +1,105 @@
import { Box, Text } from "ink";
import React from "react";
import { SingleSelect } from "./Select.js";
export type ShellConfirmChoice = "run_once" | "always_allow" | "deny";
export interface ShellConfirmProps {
command: string;
/**
* The prefix that would be persisted if the user picks
* "always allow". Typically the first 1-2 tokens of `command`.
*/
allowPrefix: string;
onChoose: (choice: ShellConfirmChoice) => void;
}
/**
* Modal-style approval for a shell command the model wants to run.
* Three choices:
* 1. Run once — execute this invocation, prefix NOT remembered.
* 2. Always allow — persist the prefix to `~/.reasonix/config.json`
* under this project so every future invocation with that prefix
* auto-runs.
* 3. Deny — tell the model the user refused.
* Arrow keys + Enter. No y/n hotkey — too easy to trigger by accident
* when the user was mid-typing a response.
*/
export function ShellConfirm({ command, allowPrefix, onChoose }: ShellConfirmProps) {
return (
<Box flexDirection="column" borderStyle="round" borderColor="yellow" paddingX={1} marginY={1}>
<Box>
<Text bold color="yellow">
▸ model wants to run a shell command
</Text>
</Box>
<Box marginTop={1}>
<Text>
<Text dimColor>{"$ "}</Text>
<Text color="cyan">{command}</Text>
</Text>
</Box>
<Box marginTop={1}>
<SingleSelect
initialValue="run_once"
items={[
{
value: "run_once",
label: "Run once",
hint: "Execute this command, don't remember it.",
},
{
value: "always_allow",
label: `Always allow "${allowPrefix}" in this project`,
hint: "Save the prefix to ~/.reasonix/config.json; future matches auto-run.",
},
{
value: "deny",
label: "Deny",
hint: "Tell the model the user refused; it will continue without this command.",
},
]}
onSubmit={(v) => onChoose(v as ShellConfirmChoice)}
/>
</Box>
</Box>
);
}
/**
* Pick the "always allow" prefix from a full command. Heuristic:
* - one-token commands ("ls", "pytest") → the token itself
* - multi-token → first two tokens for well-known wrappers
* (`npm install`, `git commit`, `cargo add`, `docker run` …)
* otherwise just the first token (covers `node <script>` where the
* second token is usually a file path specific to this invocation).
* Exported so tests can pin the heuristic.
*/
export function derivePrefix(command: string): string {
const tokens = command.trim().split(/\s+/).filter(Boolean);
if (tokens.length === 0) return "";
if (tokens.length === 1) return tokens[0]!;
const first = tokens[0]!;
const TWO_TOKEN_WRAPPERS = new Set([
"npm",
"npx",
"pnpm",
"yarn",
"bun",
"git",
"cargo",
"go",
"docker",
"kubectl",
"python",
"python3",
"deno",
"pip",
"pip3",
"make",
"rake",
"bundle",
"gem",
]);
return TWO_TOKEN_WRAPPERS.has(first) ? `${first} ${tokens[1]}` : first;
}
+85
View File
@@ -0,0 +1,85 @@
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";
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;
}
/**
* Floating slash-command panel. Rendered below the input box when
* the user is typing a `/…` prefix. Navigation state lives in the
* parent (App.tsx owns `slashSelected`) so ↑/↓/Tab/Enter stay
* consistent with the useInput handler. This component is pure
* display: `matches` and `selectedIndex` come in, rows go out.
*/
export function SlashSuggestions({
matches,
selectedIndex,
}: SlashSuggestionsProps): React.ReactElement | null {
if (matches === null) return null;
if (matches.length === 0) {
return (
<Box paddingX={1}>
<Text color="yellow">no slash command matches that prefix</Text>
<Text dimColor> — Backspace to edit, or /help for the full list</Text>
</Box>
);
}
// 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 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;
return (
<Box flexDirection="column" paddingX={1}>
{hiddenAbove > 0 ? <Text dimColor> ↑ {hiddenAbove} more above</Text> : null}
{shown.map((spec, i) => (
<SuggestionRow key={spec.cmd} spec={spec} isSelected={windowStart + i === selectedIndex} />
))}
{hiddenBelow > 0 ? <Text dimColor> ↓ {hiddenBelow} more below</Text> : null}
<Text dimColor> ↑/↓ navigate · Tab or Enter to pick</Text>
</Box>
);
}
function SuggestionRow({ spec, isSelected }: { spec: SlashCommandSpec; isSelected: boolean }) {
const marker = isSelected ? "▸" : " ";
const name = `/${spec.cmd}`;
const argsSuffix = spec.argsHint ? ` ${spec.argsHint}` : "";
// Selected row gets full cyan coloring so it pops out against the
// dimmed others — mirrors the style GitHub Issues / Discord use
// for focused dropdown rows.
if (isSelected) {
return (
<Box>
<Text bold color="cyan">
{marker} {name.padEnd(12)}
{argsSuffix.padEnd(16)}
</Text>
<Text color="cyan"> {spec.summary}</Text>
</Box>
);
}
return (
<Box>
<Text dimColor>
{marker} {name.padEnd(12)}
{argsSuffix.padEnd(16)} {spec.summary}
</Text>
</Box>
);
}
+56 -10
View File
@@ -2,6 +2,7 @@ import { Box, Text } from "ink";
import React from "react";
import { DEEPSEEK_CONTEXT_TOKENS, DEFAULT_CONTEXT_TOKENS } from "../../telemetry.js";
import type { SessionSummary } from "../../telemetry.js";
import { VERSION } from "../../version.js";
export interface StatsPanelProps {
summary: SessionSummary;
@@ -9,6 +10,29 @@ export interface StatsPanelProps {
prefixHash: string;
harvestOn?: boolean;
branchBudget?: number;
/**
* True when `reasonix code` is currently running in read-only Plan
* Mode. Surfaced as a red "PLAN" tag in the panel header so the user
* can tell at a glance that edits are gated behind submit_plan +
* approval.
*/
planMode?: boolean;
/**
* Account balance fetched once at launch (and optionally refreshed
* per-turn by the TUI). `null` or absent hides the balance cell
* entirely — /user/balance failed or the user ran with `--no-config`.
* The top-up warning fires below 1.0 unit of whatever currency
* the endpoint reports so a Chinese user with CNY and a U.S. user
* with USD both see "getting low."
*/
balance?: { currency: string; total: number } | null;
/**
* Published npm version newer than VERSION. Rendered as a yellow
* "· update: X" nudge in the panel header. `null` / `undefined`
* hides the nudge (offline launch, already up to date, or check
* still in flight).
*/
updateAvailable?: string | null;
}
export function StatsPanel({
@@ -17,6 +41,9 @@ export function StatsPanel({
prefixHash,
harvestOn,
branchBudget,
planMode,
balance,
updateAvailable,
}: StatsPanelProps) {
const hitPct = (summary.cacheHitRatio * 100).toFixed(1);
const hitColor =
@@ -34,14 +61,26 @@ export function StatsPanel({
<Text color="cyan" bold>
Reasonix
</Text>
<Text dimColor>{` v${VERSION}`}</Text>
<Text dimColor> · model </Text>
<Text color="yellow">{model}</Text>
<Text dimColor> · prefix </Text>
<Text dimColor>{prefixHash}</Text>
{harvestOn ? <Text color="magenta"> · harvest</Text> : null}
{branchOn ? <Text color="blue"> · branch{branchBudget}</Text> : null}
{planMode ? (
<Text color="red" bold>
{" "}
· PLAN
</Text>
) : null}
</Text>
<Text>
{updateAvailable ? (
<Text color="yellow" bold>{`update: ${updateAvailable} · `}</Text>
) : null}
<Text dimColor>turns {summary.turns} · type /help</Text>
</Text>
<Text dimColor>turns {summary.turns} · type /help</Text>
</Box>
<Box marginTop={1} gap={3}>
<Text>
@@ -52,16 +91,13 @@ export function StatsPanel({
</Text>
<Text>
<Text dimColor>cost </Text>
<Text color="green">${summary.totalCostUsd.toFixed(6)}</Text>
</Text>
<Text>
<Text dimColor>vs Claude </Text>
<Text>${summary.claudeEquivalentUsd.toFixed(6)}</Text>
</Text>
<Text>
<Text dimColor>saving </Text>
<Text color="green" bold>
{summary.savingsVsClaudePct.toFixed(1)}%
${summary.totalCostUsd.toFixed(6)}
</Text>
<Text dimColor>
{" (in "}${summary.totalInputCostUsd.toFixed(6)}
{" · out "}${summary.totalOutputCostUsd.toFixed(6)}
{")"}
</Text>
</Text>
{summary.lastPromptTokens > 0 ? (
@@ -79,6 +115,16 @@ export function StatsPanel({
) : null}
</Text>
) : null}
{balance ? (
<Text>
<Text dimColor>balance </Text>
<Text color={balance.total < 1 ? "red" : balance.total < 5 ? "yellow" : "green"} bold>
{balance.currency === "USD" ? "$" : ""}
{balance.total.toFixed(2)}
{balance.currency !== "USD" ? ` ${balance.currency}` : ""}
</Text>
</Text>
) : null}
</Box>
</Box>
);
+219 -17
View File
@@ -144,8 +144,21 @@ export function stripMath(s: string): string {
);
}
/** Split a single line into styled segments for bold / italic / inline code. */
const INLINE_RE = /(\*\*([^*\n]+?)\*\*|`([^`\n]+?)`|(?<![*\w])\*([^*\n]+?)\*(?!\w))/g;
/**
* Split a single line into styled segments for bold / italic / inline
* code.
*
* Triple-backtick (```…```) runs are matched BEFORE the single-backtick
* case so a one-line code span like `​``bash echo hi``​` is captured
* whole instead of the single-backtick regex greedily eating the
* middle and leaving two stray backticks on each side (what 0.4.15
* users saw when the model emitted `​``bash …``​` on the same line as
* prose). Content may contain single backticks but not newlines —
* multi-line fenced code is a block-level concern handled in
* `parseBlocks`.
*/
const INLINE_RE =
/(\*\*([^*\n]+?)\*\*|```([^\n]+?)```|`([^`\n]+?)`|(?<![*\w])\*([^*\n]+?)\*(?!\w))/g;
function InlineMd({ text }: { text: string }) {
const parts: React.ReactNode[] = [];
@@ -156,6 +169,11 @@ function InlineMd({ text }: { text: string }) {
if (start > last) {
parts.push(<Text key={`t${idx++}`}>{text.slice(last, start)}</Text>);
}
// Groups, in the order they appear in INLINE_RE:
// m[2] = bold content (inside ** **)
// m[3] = triple-backtick content (strip leading lang tag)
// m[4] = single-backtick inline code
// m[5] = italic content (inside * *)
if (m[2] !== undefined) {
parts.push(
<Text key={`b${idx++}`} bold>
@@ -163,17 +181,26 @@ function InlineMd({ text }: { text: string }) {
</Text>,
);
} else if (m[3] !== undefined) {
// One-line fenced span: ```bash echo hi``` → drop the "bash "
// language tag so the user doesn't see it rendered in code color.
const stripped = m[3].replace(/^(\w+)\s+/, "");
parts.push(
<Text key={`c${idx++}`} color="yellow">
{m[3]}
{stripped}
</Text>,
);
} else if (m[4] !== undefined) {
parts.push(
<Text key={`i${idx++}`} italic>
<Text key={`c${idx++}`} color="yellow">
{m[4]}
</Text>,
);
} else if (m[5] !== undefined) {
parts.push(
<Text key={`i${idx++}`} italic>
{m[5]}
</Text>,
);
}
last = start + m[0].length;
}
@@ -219,7 +246,27 @@ interface EditBlockView {
replace: string;
}
type Block = ParagraphBlock | HeadingBlock | BulletBlock | CodeBlock | HrBlock | EditBlockView;
/**
* GitHub-Flavored-Markdown-ish tables. We don't do alignment flags
* (:--- / ---:) — column-wise left-alignment is fine for a terminal
* and the LLM rarely specifies alignment anyway. Columns grow to
* fit the widest cell, with a hard cap so a pathological 200-char
* cell doesn't blow past the terminal width.
*/
interface TableBlock {
kind: "table";
header: string[];
rows: string[][];
}
type Block =
| ParagraphBlock
| HeadingBlock
| BulletBlock
| CodeBlock
| HrBlock
| EditBlockView
| TableBlock;
export function parseBlocks(raw: string): Block[] {
const lines = raw.split(/\r?\n/);
@@ -230,6 +277,11 @@ export function parseBlocks(raw: string): Block[] {
let codeBuf: string[] = [];
let listBuf: BulletBlock | null = null;
// Fence length of the currently-open code block so a block opened
// with ````` closes only on `````, matching GFM. Empty when we're
// not in code mode.
let codeFence = "";
const flushPara = () => {
if (para.length) {
out.push({ kind: "paragraph", text: para.join(" ") });
@@ -287,22 +339,51 @@ export function parseBlocks(raw: string): Block[] {
}
}
const fence = line.match(/^```(\w*)/);
if (fence) {
if (inCode) {
out.push({ kind: "code", lang: codeLang, text: codeBuf.join("\n") });
codeBuf = [];
codeLang = "";
inCode = false;
} else {
// Fenced code block (GFM). The fence is 3+ backticks, may have up
// to 3 leading spaces, and carries an optional language tag. A
// closing fence must be the SAME backtick run length or longer.
//
// Two paths:
// a) Fence on its own line → multi-line block, accumulate until
// a matching close fence.
// b) Fence opens AND closes on the same line (e.g.
// `​``bash echo hi``​`) → emit as a one-line code block so
// the inline parser doesn't half-eat the backticks.
if (!inCode) {
const open = line.match(/^ {0,3}(`{3,})(\w*)\s*(.*)$/);
if (open) {
const fence = open[1]!;
const lang = open[2] ?? "";
const rest = open[3] ?? "";
const closeOnSame = rest.match(new RegExp(`^(.*?)${fence}\\s*$`));
if (closeOnSame) {
flushPara();
flushList();
out.push({ kind: "code", lang, text: (closeOnSame[1] ?? "").trim() });
continue;
}
flushPara();
flushList();
inCode = true;
codeLang = fence[1] ?? "";
codeLang = lang;
codeFence = fence;
// Anything after the opening fence on the SAME line is
// still body content (rare but legal).
if (rest.length > 0) codeBuf.push(rest);
continue;
}
} else {
// In code mode — check for closing fence. Same indent rules as
// opening, and the backtick run must be at least as long.
const close = line.match(/^ {0,3}(`{3,})\s*$/);
if (close && close[1]!.length >= codeFence.length) {
out.push({ kind: "code", lang: codeLang, text: codeBuf.join("\n") });
codeBuf = [];
codeLang = "";
codeFence = "";
inCode = false;
continue;
}
continue;
}
if (inCode) {
codeBuf.push(rawLine);
continue;
}
@@ -328,6 +409,31 @@ export function parseBlocks(raw: string): Block[] {
continue;
}
// Table detection: a line with at least one `|` where the NEXT
// line looks like a GFM separator (`| --- | --- |` or any mix of
// pipes + dashes + colons + spaces). Both the header row and the
// separator need to be present — a bare pipe in prose shouldn't
// trigger the table path.
if (line.includes("|")) {
const next = (lines[i + 1] ?? "").trim();
if (/^\|?\s*:?-{2,}:?\s*(\|\s*:?-{2,}:?\s*)+\|?\s*$/.test(next)) {
flushPara();
flushList();
const header = splitTableRow(line);
const rows: string[][] = [];
let j = i + 2; // skip header + separator
while (j < lines.length) {
const r = lines[j]!.replace(/\s+$/g, "");
if (r.trim() === "" || !r.includes("|")) break;
rows.push(splitTableRow(r));
j++;
}
out.push({ kind: "table", header, rows });
i = j - 1;
continue;
}
}
const bm = line.match(/^\s*[-*+]\s+(.+)$/);
if (bm) {
flushPara();
@@ -391,11 +497,107 @@ function BlockView({ block }: { block: Block }) {
);
case "edit-block":
return <EditBlockRow block={block} />;
case "table":
return <TableBlockRow block={block} />;
case "hr":
return <Text dimColor>{"────────────────────────"}</Text>;
}
}
/**
* Split one table row into trimmed cells. Leading/trailing pipes are
* optional (both `| a | b |` and `a | b` are accepted). Pipes escaped
* as `\|` stay in the cell content.
*/
function splitTableRow(line: string): string[] {
// Temporarily replace escaped pipes so split() doesn't fire on them.
const SENTINEL = "\u0000";
const masked = line.replace(/\\\|/g, SENTINEL);
const trimmed = masked.trim().replace(/^\||\|$/g, "");
return trimmed.split("|").map((c) => c.trim().replace(new RegExp(SENTINEL, "g"), "|"));
}
/**
* Render a GFM table as an aligned grid. Column widths are the max
* display length in that column, capped at 40 chars so one huge cell
* doesn't wreck the layout. Header row is bold + cyan; body rows use
* the default text color. Separator is a dim row of dashes.
*/
function TableBlockRow({ block }: { block: TableBlock }) {
const colCount = Math.max(block.header.length, ...block.rows.map((r) => r.length));
const widths: number[] = [];
for (let c = 0; c < colCount; c++) {
const cellLengths = [displayWidth(block.header[c] ?? "")];
for (const r of block.rows) cellLengths.push(displayWidth(r[c] ?? ""));
widths.push(Math.min(40, Math.max(3, ...cellLengths)));
}
const pad = (s: string, w: number) => {
const dw = displayWidth(s);
if (dw >= w) return s;
return s + " ".repeat(w - dw);
};
const separator = widths.map((w) => "─".repeat(w)).join("─┼─");
return (
<Box flexDirection="column">
<Box>
{block.header.map((cell, ci) => (
// biome-ignore lint/suspicious/noArrayIndexKey: table columns never reorder — derived from a static header array
<Text key={`h-${ci}`} bold color="cyan">
{pad(cell, widths[ci] ?? 3)}
{ci < colCount - 1 ? " │ " : ""}
</Text>
))}
</Box>
<Text dimColor>{separator}</Text>
{block.rows.map((row, ri) => (
// biome-ignore lint/suspicious/noArrayIndexKey: table rows render in source order and don't reorder
<Box key={`r-${ri}`}>
{Array.from({ length: colCount }).map((_, ci) => (
// biome-ignore lint/suspicious/noArrayIndexKey: same — column axis is fixed by the table shape
<Text key={`c-${ri}-${ci}`}>
{pad(row[ci] ?? "", widths[ci] ?? 3)}
{ci < colCount - 1 ? " │ " : ""}
</Text>
))}
</Box>
))}
</Box>
);
}
/**
* Terminal display width of a string, approximately. CJK characters
* and full-width punctuation take 2 columns; everything else is 1.
* Good enough for aligning table cells in a Chinese-or-English mix;
* real wcwidth is bigger than we need to drag in for this use case.
*/
function displayWidth(s: string): number {
let w = 0;
for (const ch of s) {
const code = ch.codePointAt(0) ?? 0;
// CJK unified ideographs, full-width forms, hiragana/katakana,
// Hangul syllables — rough bucket, close enough for the terminal.
if (
(code >= 0x1100 && code <= 0x115f) ||
(code >= 0x2e80 && code <= 0x303e) ||
(code >= 0x3041 && code <= 0x33ff) ||
(code >= 0x3400 && code <= 0x4dbf) ||
(code >= 0x4e00 && code <= 0x9fff) ||
(code >= 0xa000 && code <= 0xa4cf) ||
(code >= 0xac00 && code <= 0xd7a3) ||
(code >= 0xf900 && code <= 0xfaff) ||
(code >= 0xfe30 && code <= 0xfe4f) ||
(code >= 0xff00 && code <= 0xff60) ||
(code >= 0xffe0 && code <= 0xffe6)
) {
w += 2;
} else {
w += 1;
}
}
return w;
}
/**
* SEARCH/REPLACE rendered as a minimal diff: filename on top, red
* `-` lines, a gutter, green `+` lines. No inner markdown / inline
+199
View File
@@ -0,0 +1,199 @@
/**
* Pure keystroke → action reducer for PromptInput.
*
* Kept separate from the React component so the keyboard semantics
* are easy to unit-test. The component threads `useInput` through
* this function and applies the returned action.
*
* Edit model:
* - Full cursor support. ←/→ move one column. ↑/↓ move across
* lines in a multi-line buffer (column preserved when possible).
* Ctrl+A / Ctrl+E jump to start / end of the current line.
* - Backspace deletes the char before the cursor; Delete deletes
* the char under the cursor.
* - Printable chars (including multi-char paste bursts) insert
* at the cursor.
* - Enter submits unless Shift is held (newline), the line ends
* with '\' and cursor is at end (bash-style continuation), or
* the input is Ctrl+J (LF, terminal-universal newline).
* - Parent owns Tab, Esc, PageUp/Down (slash-complete, abort,
* unused). Arrow keys are split: empty buffer → parent (history
* recall); non-empty → child (cursor movement).
*/
export interface MultilineKey {
input: string;
return?: boolean;
shift?: boolean;
ctrl?: boolean;
meta?: boolean;
backspace?: boolean;
delete?: boolean;
tab?: boolean;
upArrow?: boolean;
downArrow?: boolean;
leftArrow?: boolean;
rightArrow?: boolean;
escape?: boolean;
pageUp?: boolean;
pageDown?: boolean;
}
export interface MultilineAction {
/** New buffer value. `null` = unchanged. */
next: string | null;
/** New cursor position (0..value.length). `null` = unchanged. */
cursor: number | null;
/** When `true`, fire `onSubmit(submitValue ?? value)`. */
submit: boolean;
submitValue?: string;
}
const BACKSLASH_SUFFIX = /\\$/;
const NOOP: MultilineAction = { next: null, cursor: null, submit: false };
export function processMultilineKey(
value: string,
cursor: number,
key: MultilineKey,
): MultilineAction {
// Parent-owned keys: Tab (slash-complete), Esc (abort), PageUp/Down.
if (key.tab || key.escape || key.pageUp || key.pageDown) {
return NOOP;
}
// Empty buffer + ↑/↓ → parent handles history recall.
if (value.length === 0 && (key.upArrow || key.downArrow)) {
return NOOP;
}
// Cursor motion.
if (key.leftArrow) {
return { next: null, cursor: Math.max(0, cursor - 1), submit: false };
}
if (key.rightArrow) {
return { next: null, cursor: Math.min(value.length, cursor + 1), submit: false };
}
if (key.upArrow) {
const moved = moveCursorUp(value, cursor);
return moved === cursor ? NOOP : { next: null, cursor: moved, submit: false };
}
if (key.downArrow) {
const moved = moveCursorDown(value, cursor);
return moved === cursor ? NOOP : { next: null, cursor: moved, submit: false };
}
// Emacs-style line jumps (universal across terminals; Home/End aren't
// reliably reported by Ink so we don't depend on them).
if (key.ctrl && key.input === "a") {
return { next: null, cursor: startOfLine(value, cursor), submit: false };
}
if (key.ctrl && key.input === "e") {
return { next: null, cursor: endOfLine(value, cursor), submit: false };
}
// Newline: Ctrl+J (LF literal) or ctrl+'j' normalized form.
if (key.input === "\n" || (key.ctrl && key.input === "j")) {
return insertAt(value, cursor, "\n");
}
if (key.return) {
if (key.shift) return insertAt(value, cursor, "\n");
// Bash-style line continuation: trailing '\' + Enter (only when the
// cursor sits at end-of-buffer, so a stray '\' mid-line doesn't
// trigger it).
if (cursor === value.length && BACKSLASH_SUFFIX.test(value)) {
const replaced = `${value.slice(0, -1)}\n`;
return { next: replaced, cursor: replaced.length, submit: false };
}
return { next: null, cursor: null, submit: true, submitValue: value };
}
// Backspace = delete the char BEFORE the cursor. We also accept
// `key.delete` and the raw DEL (0x7f) / BS (0x08) bytes as backspace
// for the same purpose — some Windows terminals (cmd.exe, certain
// winpty configs) report plain Backspace without setting
// `key.backspace`, which used to leave the user typing into a prompt
// where the Backspace key did nothing. Reasonix doesn't offer a
// separate forward-delete operation, so collapsing them is safe.
if (key.backspace || key.delete || key.input === "\x7f" || key.input === "\b") {
if (cursor === 0) return NOOP;
return {
next: value.slice(0, cursor - 1) + value.slice(cursor),
cursor: cursor - 1,
submit: false,
};
}
// Bare modifier events (Ctrl/Meta with no printable) and unhandled
// Ctrl-<letter> chords are dropped so a stray Ctrl+L doesn't insert "l".
if ((key.ctrl || key.meta) && key.input.length === 0) return NOOP;
if (key.ctrl || key.meta) return NOOP;
// Printable input (may be a multi-char paste; pasted newlines land
// inside the buffer rather than triggering submit on the first line).
if (key.input.length > 0) {
return insertAt(value, cursor, key.input);
}
return NOOP;
}
function insertAt(value: string, cursor: number, insert: string): MultilineAction {
return {
next: value.slice(0, cursor) + insert + value.slice(cursor),
cursor: cursor + insert.length,
submit: false,
};
}
/**
* Line + column of a cursor inside a buffer. Exported because the
* renderer needs the same mapping for drawing the cursor block on the
* right line.
*/
export function lineAndColumn(value: string, cursor: number): { line: number; col: number } {
let line = 0;
let col = 0;
const n = Math.min(cursor, value.length);
for (let i = 0; i < n; i++) {
if (value[i] === "\n") {
line++;
col = 0;
} else {
col++;
}
}
return { line, col };
}
function startOfLine(value: string, cursor: number): number {
return value.lastIndexOf("\n", cursor - 1) + 1;
}
function endOfLine(value: string, cursor: number): number {
const nl = value.indexOf("\n", cursor);
return nl === -1 ? value.length : nl;
}
function moveCursorUp(value: string, cursor: number): number {
const curStart = startOfLine(value, cursor);
if (curStart === 0) return cursor; // already on the first line
const col = cursor - curStart;
const prevEnd = curStart - 1; // the '\n' between the two lines
const prevStart = value.lastIndexOf("\n", prevEnd - 1) + 1;
const prevLen = prevEnd - prevStart;
return prevStart + Math.min(col, prevLen);
}
function moveCursorDown(value: string, cursor: number): number {
const nextNl = value.indexOf("\n", cursor);
if (nextNl === -1) return cursor; // already on the last line
const curStart = startOfLine(value, cursor);
const col = cursor - curStart;
const nextStart = nextNl + 1;
const followingNl = value.indexOf("\n", nextStart);
const nextLen = (followingNl === -1 ? value.length : followingNl) - nextStart;
return nextStart + Math.min(col, nextLen);
}
+873 -10
View File
@@ -1,6 +1,21 @@
import { spawnSync } from "node:child_process";
import {
HOOK_EVENTS,
type HookEvent,
type ResolvedHook,
globalSettingsPath,
projectSettingsPath,
} from "../../hooks.js";
import type { CacheFirstLoop } from "../../loop.js";
import type { InspectionReport } from "../../mcp/inspect.js";
import { PROJECT_MEMORY_FILE, memoryEnabled, readProjectMemory } from "../../project-memory.js";
import { deleteSession, listSessions } from "../../session.js";
import { SkillStore } from "../../skills.js";
import { DEEPSEEK_CONTEXT_TOKENS, DEFAULT_CONTEXT_TOKENS } from "../../telemetry.js";
import { aggregateUsage, defaultUsageLogPath, readUsageLog } from "../../usage.js";
import { type MemoryScope, MemoryStore } from "../../user-memory.js";
import { VERSION, compareVersions, isNpxInstall } from "../../version.js";
import { renderDashboard } from "../commands/stats.js";
export interface SlashResult {
/** Text to display back to the user as a system/info line. */
@@ -11,6 +26,13 @@ export interface SlashResult {
clear?: boolean;
/** Unknown command — display usage hint. */
unknown?: boolean;
/**
* Re-submit this text as a user message after displaying `info`.
* Used by `/retry` — the slash command truncates the log, then
* asks the TUI to push the original text back through the normal
* submit flow so a fresh turn runs.
*/
resubmit?: string;
}
/**
@@ -49,6 +71,188 @@ export interface SlashContext {
* replies "only available in code mode".
*/
codeRoot?: string;
/**
* How many edit blocks are currently pending `/apply` or `/discard`.
* Surfaced by `/status`. TUI populates it live from its pending ref;
* omitted → treat as 0 (chat-only session).
*/
pendingEditCount?: number;
/**
* Callback returning every tool result seen this session in
* chronological order (oldest first). Powers `/tool [N]` for
* inspecting the full untruncated output that `EventLog` clips at
* 400 chars for display. Absent → `/tool` replies "not available".
*/
toolHistory?: () => Array<{ toolName: string; text: string }>;
/**
* Pre-captured inspection reports for each connected MCP server.
* Populated once at chat startup (chat.tsx) so `/mcp` can render
* tools + resources + prompts synchronously without needing async
* handler support.
*/
mcpServers?: McpServerSummary[];
/**
* Directory `/memory` should resolve `REASONIX.md` from. In code
* mode this is the rootDir the filesystem tools are pinned to; in
* plain chat this is `process.cwd()` at launch time. Absent → the
* TUI is running in some non-cwd context (tests) and `/memory`
* replies "root unknown" instead of silently reading a different dir.
*/
memoryRoot?: string;
/**
* Current plan-mode state, surfaced in `/status` and toggled by
* `/plan`. Present iff the session is a `reasonix code` run — chat
* mode doesn't have plan mode.
*/
planMode?: boolean;
/**
* Callback the `/plan` slash uses to flip plan mode on/off. Also
* mirrors the state to the underlying ToolRegistry so dispatch
* enforcement follows. Absent → `/plan` replies "only available in
* code mode".
*/
setPlanMode?: (on: boolean) => void;
/**
* Callback that clears a pending-plan picker state. Called by
* `/apply-plan` so that when the user force-approves, the picker
* dismisses without also firing its own approval synthetic (the
* slash returns its own `resubmit` instead). Safe to call with no
* pending plan.
*/
clearPendingPlan?: () => void;
/**
* Re-load `~/.reasonix/settings.json` + `<project>/.reasonix/settings.json`
* and update both the App's hook state and the loop's mutable hook
* list. Returns the new hook count so the slash can echo a sane
* confirmation. Absent → `/hooks reload` replies "not available".
*/
reloadHooks?: () => number;
/**
* Latest published version if App's background registry check
* has completed, `null` otherwise (still in flight OR offline).
* Drives `/update` — the slash shows whatever the async check
* already resolved, so the command is fully synchronous.
*/
latestVersion?: string | null;
/**
* Fire-and-forget: kick off a fresh registry fetch. `/update`
* calls this whenever it encounters `latestVersion === null`
* so the user can rerun the slash a few seconds later and see
* a concrete answer. Absent → the slash just reports "pending"
* with no retry path.
*/
refreshLatestVersion?: () => void;
}
export interface McpServerSummary {
/** Short label shown in the `/mcp` output (server namespace or "anon"). */
label: string;
/** Original --mcp spec string. */
spec: string;
/** Count of tools bridged into the Reasonix registry from this server. */
toolCount: number;
/** Full inspection snapshot — used for the resources + prompts sections. */
report: InspectionReport;
}
/**
* Slash command registry. Drives `/help`, the on-type suggestion
* popup (`SlashSuggestions`), and auto-complete. Kept as data rather
* than derived from the `handleSlash` switch so summaries can be
* user-facing rather than code comments.
*
* `contextual` gates commands that only make sense in certain modes:
* - `"code"` — only show when the TUI is running `reasonix code`
* - absent → always shown
*/
export interface SlashCommandSpec {
cmd: string;
summary: string;
contextual?: "code";
/** If the command takes args, hint text shown after the name. */
argsHint?: string;
}
export const SLASH_COMMANDS: readonly SlashCommandSpec[] = [
{ cmd: "help", summary: "show the full command reference" },
{ cmd: "status", summary: "current model, flags, context, session" },
{
cmd: "preset",
argsHint: "<fast|smart|max>",
summary: "one-tap model + harvest + branch bundle",
},
{ cmd: "model", argsHint: "<id>", summary: "switch DeepSeek model id" },
{ cmd: "harvest", argsHint: "[on|off]", summary: "toggle Pillar-2 plan-state extraction" },
{ cmd: "branch", argsHint: "<N|off>", summary: "run N parallel samples per turn (N>=2)" },
{ cmd: "mcp", summary: "list MCP servers + tools attached to this session" },
{ cmd: "tool", argsHint: "[N]", summary: "dump full output of the Nth tool call (1=latest)" },
{
cmd: "memory",
argsHint: "[list|show <name>|forget <name>|clear <scope> confirm]",
summary: "show / manage pinned memory (REASONIX.md + ~/.reasonix/memory)",
},
{
cmd: "skill",
argsHint: "[list|show <name>|<name> [args]]",
summary: "list / run user skills (<project>/.reasonix/skills + ~/.reasonix/skills)",
},
{
cmd: "hooks",
argsHint: "[reload]",
summary: "list active hooks (settings.json under .reasonix/) · reload re-reads from disk",
},
{
cmd: "update",
summary: "show current vs latest version + the shell command to upgrade",
},
{
cmd: "stats",
summary:
"cross-session cost dashboard (today / week / month / all-time · cache hit · vs Claude)",
},
{ cmd: "think", summary: "dump the last turn's full R1 reasoning (reasoner only)" },
{ cmd: "retry", summary: "truncate & resend your last message (fresh sample)" },
{ cmd: "compact", argsHint: "[cap]", summary: "shrink oversized tool results in the log" },
{ cmd: "sessions", summary: "list saved sessions (current marked with ▸)" },
{ cmd: "forget", summary: "delete the current session from disk" },
{ cmd: "setup", summary: "reminds you to exit and run `reasonix setup`" },
{ cmd: "clear", summary: "clear visible scrollback only (log/context kept)" },
{ cmd: "new", summary: "start a fresh conversation (clear context + scrollback)" },
{ cmd: "exit", summary: "quit the TUI" },
// Code-mode only
{ cmd: "apply", summary: "commit pending edit blocks to disk", contextual: "code" },
{ cmd: "discard", summary: "drop pending edit blocks without writing", contextual: "code" },
{ cmd: "undo", summary: "roll back the last applied edit batch", contextual: "code" },
{
cmd: "commit",
argsHint: '"msg"',
summary: "git add -A && git commit -m ...",
contextual: "code",
},
{
cmd: "plan",
argsHint: "[on|off]",
summary: "toggle read-only plan mode (writes bounced until submit_plan + approval)",
contextual: "code",
},
{
cmd: "apply-plan",
summary: "force-approve a pending / in-text plan (fallback if picker was missed)",
contextual: "code",
},
];
/**
* Filter the registry by a prefix string (without the leading `/`).
* Empty prefix returns the full non-contextual list (plus code-mode
* entries when `codeMode` is true). Case-insensitive.
*/
export function suggestSlashCommands(prefix: string, codeMode = false): SlashCommandSpec[] {
const p = prefix.toLowerCase();
return SLASH_COMMANDS.filter((c) => {
if (c.contextual === "code" && !codeMode) return false;
return c.cmd.startsWith(p);
});
}
export function parseSlash(text: string): { cmd: string; args: string[] } | null {
@@ -71,7 +275,22 @@ export function handleSlash(
return { exit: true };
case "clear":
return { clear: true };
return {
clear: true,
info: "▸ cleared visible scrollback only. Context (message log) is intact — next turn still sees everything. Use /new to start fresh, or /forget to delete the session entirely.",
};
case "new":
case "reset": {
// Actually drop the in-memory log + rewrite the session file
// so the NEXT call has no prior context. Keeps session name,
// model, and other config — just the conversation is reset.
const { dropped } = loop.clearLog();
return {
clear: true,
info: `▸ new conversation — dropped ${dropped} message(s) from context. Same session, fresh slate.`,
};
}
case "help":
case "?":
@@ -88,13 +307,22 @@ export function handleSlash(
" /setup (exit + reconfigure) → run `reasonix setup`",
" /compact [cap] shrink large tool results in history (default 4k/result)",
" /think dump the most recent turn's full R1 reasoning (reasoner only)",
" /tool [N] list tool calls (or dump full output of #N, 1=most recent)",
" /memory [sub] show pinned memory (REASONIX.md + ~/.reasonix/memory).",
" subs: list | show <name> | forget <name> | clear <scope> confirm",
" /skill [sub] list / run user skills (project/.reasonix/skills + ~/.reasonix/skills).",
" subs: list | show <name> | <name> [args] (injects skill body as user turn)",
" /retry truncate & resend your last message (fresh sample from the model)",
" /apply (code mode) commit the pending edit blocks to disk",
" /discard (code mode) drop pending edits without writing",
" /undo (code mode) roll back the last applied edit batch",
' /commit "msg" (code mode) git add -A && git commit -m "msg"',
" /plan [on|off] (code mode) toggle read-only plan mode; writes gated behind submit_plan + your approval",
" /apply-plan (code mode) force-approve pending/in-text plan (fallback)",
" /sessions list saved sessions (current is marked with ▸)",
" /forget delete the current session from disk",
" /clear clear displayed history (log + session kept)",
" /new start fresh: drop all context + clear scrollback",
" /clear clear displayed scrollback only (context kept — model still sees it)",
" /exit quit",
"",
"Presets:",
@@ -109,15 +337,39 @@ export function handleSlash(
};
case "mcp": {
const servers = ctx.mcpServers ?? [];
const specs = ctx.mcpSpecs ?? [];
const toolSpecs = loop.prefix.toolSpecs ?? [];
if (specs.length === 0 && toolSpecs.length === 0) {
if (servers.length === 0 && specs.length === 0 && toolSpecs.length === 0) {
return {
info:
"no MCP servers attached. Run `reasonix setup` to pick some, " +
'or launch with --mcp "<spec>". `reasonix mcp list` shows the catalog.',
};
}
// Rich path — we have full inspection reports, so show each
// server with its tools / resources / prompts grouped together.
if (servers.length > 0) {
const lines: string[] = [];
for (const s of servers) {
const { report } = s;
const serverName = report.serverInfo.name || "(unknown)";
const serverVer = report.serverInfo.version ? ` v${report.serverInfo.version}` : "";
lines.push(`[${s.label}] ${serverName}${serverVer} — ${s.spec}`);
lines.push(` tools ${s.toolCount}`);
appendSection(lines, "resources", report.resources);
appendSection(lines, "prompts ", report.prompts);
lines.push("");
}
lines.push(
"Chat mode consumes tools today; resources+prompts are surfaced here for awareness.",
);
lines.push(
"Full catalog: `reasonix mcp list` · deeper diagnosis: `reasonix mcp inspect <spec>`.",
);
return { info: lines.join("\n") };
}
// Fallback — older path when the TUI hasn't populated `mcpServers`.
const lines: string[] = [];
if (specs.length > 0) {
lines.push(`MCP servers (${specs.length}):`);
@@ -140,6 +392,42 @@ export function handleSlash(
"`reasonix setup`. Changes take effect on next launch.",
};
case "retry": {
const prev = loop.retryLastUser();
if (!prev) {
return {
info: "nothing to retry — no prior user message in this session's log.",
};
}
const preview = prev.length > 80 ? `${prev.slice(0, 80)}…` : prev;
return {
info: `▸ retrying: "${preview}"`,
resubmit: prev,
};
}
case "memory": {
return handleMemorySlash(args, ctx);
}
case "skill":
case "skills": {
return handleSkillSlash(args, ctx);
}
case "hook":
case "hooks": {
return handleHooksSlash(args, loop, ctx);
}
case "update": {
return handleUpdateSlash(ctx);
}
case "stats": {
return handleStatsSlash();
}
case "think":
case "reasoning": {
const raw = loop.scratch.reasoning;
@@ -153,6 +441,43 @@ export function handleSlash(
return { info: `↳ full thinking (${raw.length} chars):\n\n${raw.trim()}` };
}
case "tool": {
// EventLog truncates tool results at 400 chars for display. When
// the user wants to check what the model actually read (e.g. to
// verify it isn't hallucinating a file's contents), they need
// the full text. `/tool` is the escape hatch.
const history = ctx.toolHistory?.() ?? [];
if (history.length === 0) {
return {
info:
"no tool calls yet in this session. `/tool` lists them once the model has actually " +
"used a tool; `/tool N` dumps the full (untruncated) output of the Nth-most-recent.",
};
}
const raw = (args[0] ?? "").toLowerCase();
if (raw === "" || raw === "list" || raw === "ls") {
return { info: formatToolList(history) };
}
const n = Number.parseInt(raw, 10);
if (!Number.isFinite(n) || n < 1) {
return {
info: "usage: /tool [N] (no arg → list; N=1 → most recent result in full, N=2 → previous, …)",
};
}
if (n > history.length) {
return {
info: `only ${history.length} tool call(s) in history — asked for #${n}. Try /tool with no arg to see the list.`,
};
}
const entry = history[history.length - n];
if (!entry) {
return { info: `could not read tool call #${n}` };
}
return {
info: `↳ tool<${entry.toolName}> #${n} (${entry.text.length} chars):\n\n${entry.text}`,
};
}
case "undo": {
if (!ctx.codeUndo) {
return {
@@ -180,6 +505,45 @@ export function handleSlash(
return { info: ctx.codeDiscard() };
}
case "plan": {
if (!ctx.setPlanMode) {
return {
info: "/plan is only available inside `reasonix code` — chat mode doesn't gate tool writes.",
};
}
const currentOn = Boolean(ctx.planMode);
const raw = (args[0] ?? "").toLowerCase();
let target: boolean;
if (raw === "on" || raw === "true" || raw === "1") target = true;
else if (raw === "off" || raw === "false" || raw === "0") target = false;
else target = !currentOn;
ctx.setPlanMode(target);
if (target) {
return {
info: "▸ plan mode ON — write tools are gated; the model MUST call `submit_plan` before anything executes. (The model can also call submit_plan on its own for big tasks even when plan mode is off — this toggle is the stronger, explicit constraint.) Type /plan off to leave.",
};
}
return {
info: "▸ plan mode OFF — write tools are live again. Model can still propose plans autonomously for large tasks.",
};
}
case "apply-plan":
case "applyplan": {
if (!ctx.setPlanMode) {
return {
info: "/apply-plan is only available inside `reasonix code`.",
};
}
ctx.setPlanMode(false);
ctx.clearPendingPlan?.();
return {
info: "▸ plan approved — implementing",
resubmit:
"The plan above has been approved. Implement it now. You are out of plan mode — use edit_file / write_file / run_command as needed. Stick to the plan unless you discover a concrete reason to deviate; if you do, tell me and wait for a response before making that deviation.",
};
}
case "commit": {
if (!ctx.codeRoot) {
return {
@@ -255,13 +619,33 @@ export function handleSlash(
case "status": {
const branchBudget = loop.branchOptions.budget ?? 1;
return {
info:
`model=${loop.model} ` +
`harvest=${loop.harvestEnabled ? "on" : "off"} ` +
`branch=${branchBudget > 1 ? branchBudget : "off"} ` +
`stream=${loop.stream ? "on" : "off"}`,
};
const ctxMax = DEEPSEEK_CONTEXT_TOKENS[loop.model] ?? DEFAULT_CONTEXT_TOKENS;
const lastPromptTokens = loop.stats.summary().lastPromptTokens;
const ctxPct = ctxMax > 0 ? Math.round((lastPromptTokens / ctxMax) * 100) : 0;
const ctxLine =
lastPromptTokens > 0
? ` ctx ${compactNum(lastPromptTokens)}/${compactNum(ctxMax)} (${ctxPct}%)`
: " ctx no turns yet";
const pending = ctx.pendingEditCount ?? 0;
const sessionLine = loop.sessionName
? ` session "${loop.sessionName}" · ${loop.log.length} messages in log (resumed ${loop.resumedMessageCount})`
: " session (ephemeral — no persistence)";
const mcpCount = ctx.mcpSpecs?.length ?? 0;
const toolCount = loop.prefix.toolSpecs.length;
const mcpLine = ` mcp ${mcpCount} server(s), ${toolCount} tool(s) in registry`;
const pendingLine =
pending > 0 ? ` edits ${pending} pending (/apply to commit, /discard to drop)` : "";
const planLine = ctx.planMode ? " plan ON — writes gated (submit_plan + approval)" : "";
const lines = [
` model ${loop.model}`,
` flags harvest=${loop.harvestEnabled ? "on" : "off"} · branch=${branchBudget > 1 ? branchBudget : "off"} · stream=${loop.stream ? "on" : "off"}`,
ctxLine,
mcpLine,
sessionLine,
];
if (pendingLine) lines.push(pendingLine);
if (planLine) lines.push(planLine);
return { info: lines.join("\n") };
}
case "model": {
@@ -319,6 +703,485 @@ export function handleSlash(
}
}
/**
* `/skill` family. Bare `/skill` (or `/skill list`) prints the
* discovered skills from `<projectRoot>/.reasonix/skills` (code mode
* only) + `~/.reasonix/skills`. `/skill show <name>` dumps one body
* inline for reading. `/skill <name> [args...]` injects the skill body
* as a user turn via `resubmit` — the same mechanism `/apply-plan`
* uses — so the next model turn runs with the skill's instructions
* fresh in the log.
*
* Project scope is only populated when the session has a `codeRoot`
* (set by `reasonix code`). In plain chat mode the store reads the
* global scope only, matching how user-memory behaves.
*/
/**
* `/update` — inside the TUI we deliberately do NOT spawn `npm install`.
* stdio:inherit into a running Ink renderer corrupts the display, and
* the process being upgraded is the same process that's still reading
* its own binaries (messy on Windows). Instead we surface what we
* already know from the App's background registry check and print the
* exact shell command the user should run after exiting.
*
* The `latestVersion` ctx field is populated by App.tsx's mount-time
* `getLatestVersion()` effect. When it's `null` we report the check
* as pending/offline — still a useful output (current version + how
* to force a fresh check from another terminal).
*/
/**
* `/stats` — dashboard view of `~/.reasonix/usage.jsonl`, the same
* roll-up `reasonix stats` (no arg) prints at the shell. Synchronous
* disk read; cheap enough that we don't bother caching between slash
* invocations.
*
* No transcript-path variant in-TUI: the per-file summary is scripty
* and rarely wanted mid-session. If someone needs it they have the
* CLI form (`reasonix stats <path>`).
*/
function handleStatsSlash(): SlashResult {
const path = defaultUsageLogPath();
const records = readUsageLog(path);
if (records.length === 0) {
return {
info: [
"no usage data yet.",
"",
` ${path}`,
"",
"every turn you run here appends one record — this session's turns",
"will show up in the dashboard once you send a message.",
].join("\n"),
};
}
const agg = aggregateUsage(records);
return { info: renderDashboard(agg, path) };
}
function handleUpdateSlash(ctx: SlashContext): SlashResult {
const latest = ctx.latestVersion ?? null;
const lines: string[] = [`current: reasonix ${VERSION}`];
if (latest === null) {
// Kick off a fresh fetch so a follow-up /update a few seconds
// later has a real answer instead of the same pending message.
ctx.refreshLatestVersion?.();
lines.push(
"latest: (not yet resolved — background check in flight or offline)",
"",
"triggered a fresh registry fetch — retry `/update` in a few seconds,",
"or run `reasonix update` in another terminal to force it synchronously.",
);
return { info: lines.join("\n") };
}
lines.push(`latest: reasonix ${latest}`);
const diff = compareVersions(VERSION, latest);
if (diff >= 0) {
lines.push("", "you're on the latest. nothing to do.");
return { info: lines.join("\n") };
}
if (isNpxInstall()) {
lines.push(
"",
"you're running via npx — the next `npx reasonix ...` launch will auto-fetch.",
"to force a refresh sooner: `npm cache clean --force`.",
);
} else {
lines.push(
"",
"to upgrade, exit this session and run:",
" reasonix update (interactive, dry-run supported via --dry-run)",
" npm install -g reasonix@latest (direct)",
"",
"in-session install is deliberately disabled — the npm spawn would",
"corrupt this TUI's rendering and Windows can lock the running binary.",
);
}
return { info: lines.join("\n") };
}
function handleHooksSlash(args: string[], loop: CacheFirstLoop, ctx: SlashContext): SlashResult {
const sub = (args[0] ?? "").toLowerCase();
if (sub === "reload") {
if (!ctx.reloadHooks) {
return {
info: "/hooks reload is not available in this context (no reload callback wired).",
};
}
const count = ctx.reloadHooks();
return { info: `▸ reloaded hooks · ${count} active` };
}
if (sub !== "" && sub !== "list" && sub !== "ls") {
return {
info: "usage: /hooks list active hooks\n /hooks reload re-read settings.json files",
};
}
const hooks = loop.hooks;
const projPath = ctx.codeRoot ? projectSettingsPath(ctx.codeRoot) : undefined;
const globPath = globalSettingsPath();
if (hooks.length === 0) {
const lines = [
"no hooks configured.",
"",
"drop a settings.json with a `hooks` key into either of:",
ctx.codeRoot
? ` · ${projPath} (project)`
: " · <project>/.reasonix/settings.json (project)",
` · ${globPath} (global)`,
"",
"events: PreToolUse, PostToolUse, UserPromptSubmit, Stop",
"exit 0 = pass · exit 2 = block (Pre*) · other = warn",
];
return { info: lines.join("\n") };
}
const grouped = new Map<HookEvent, ResolvedHook[]>();
for (const event of HOOK_EVENTS) grouped.set(event, []);
for (const h of hooks) grouped.get(h.event)?.push(h);
const lines: string[] = [`▸ ${hooks.length} hook(s) loaded`];
for (const event of HOOK_EVENTS) {
const list = grouped.get(event) ?? [];
if (list.length === 0) continue;
lines.push("", `${event}:`);
for (const h of list) {
const match = h.match && h.match !== "*" ? ` match=${h.match}` : "";
const desc = h.description ? ` — ${h.description}` : "";
lines.push(` [${h.scope}]${match} ${h.command}${desc}`);
}
}
lines.push("", `sources: project=${projPath ?? "(none — chat mode)"} · global=${globPath}`);
return { info: lines.join("\n") };
}
function handleSkillSlash(args: string[], ctx: SlashContext): SlashResult {
const store = new SkillStore({ projectRoot: ctx.codeRoot });
const sub = (args[0] ?? "").toLowerCase();
if (sub === "" || sub === "list" || sub === "ls") {
const skills = store.list();
if (skills.length === 0) {
const lines = ["no skills found. Reasonix reads skills from:"];
if (store.hasProjectScope()) {
lines.push(
" · <project>/.reasonix/skills/<name>/SKILL.md (or <name>.md) — project scope",
);
}
lines.push(" · ~/.reasonix/skills/<name>/SKILL.md (or <name>.md) — global scope");
if (!store.hasProjectScope()) {
lines.push(" (project scope is only active in `reasonix code`)");
}
lines.push(
"",
"Each file's frontmatter needs at least `name` and `description`.",
"Invoke a skill with `/skill <name> [args]` or by asking the model to call `run_skill`.",
);
return { info: lines.join("\n") };
}
const lines = [`User skills (${skills.length}):`];
for (const s of skills) {
const scope = `(${s.scope})`.padEnd(11);
const name = s.name.padEnd(24);
const desc = s.description.length > 70 ? `${s.description.slice(0, 69)}…` : s.description;
lines.push(` ${scope} ${name} ${desc}`);
}
lines.push("");
lines.push("View body: /skill show <name> Run: /skill <name> [args]");
return { info: lines.join("\n") };
}
if (sub === "show" || sub === "cat") {
const target = args[1];
if (!target) return { info: "usage: /skill show <name>" };
const skill = store.read(target);
if (!skill) return { info: `no skill found: ${target}` };
return {
info: [
`▸ ${skill.name} (${skill.scope})`,
skill.description ? ` ${skill.description}` : "",
` ${skill.path}`,
"",
skill.body,
]
.filter((l) => l !== "")
.join("\n"),
};
}
// Bare `/skill <name> [args...]` — inject the body as a user turn.
// The first arg is the skill name; remaining args are forwarded
// verbatim as the skill's "Arguments:" line.
const name = args[0] ?? "";
const skill = store.read(name);
if (!skill) {
return {
info: `no skill found: ${name} (try /skill list)`,
};
}
const extra = args.slice(1).join(" ").trim();
const header = `# Skill: ${skill.name}${skill.description ? `\n> ${skill.description}` : ""}`;
const argsLine = extra ? `\n\nArguments: ${extra}` : "";
const payload = `${header}\n\n${skill.body}${argsLine}`;
return {
info: `▸ running skill: ${skill.name}${extra ? ` — ${extra}` : ""}`,
resubmit: payload,
};
}
/**
* `/memory` family. Bare `/memory` shows what's pinned (REASONIX.md +
* both MEMORY.md blocks). Subcommands manage the user-memory store:
* list — every memory file, both scopes
* show <name> — dump one file's body
* show <scope>/<name> — disambiguate when name exists in both scopes
* forget <name> — delete (same scope resolution as show)
* clear <scope> confirm — wipe a scope (typed literal "confirm" required)
*/
function handleMemorySlash(args: string[], ctx: SlashContext): SlashResult {
if (!memoryEnabled()) {
return {
info: "memory is disabled (REASONIX_MEMORY=off in env). Unset the var to re-enable — no REASONIX.md or ~/.reasonix/memory content will be pinned in the meantime.",
};
}
if (!ctx.memoryRoot) {
return {
info: "no working directory on this session — `/memory` needs a root to resolve REASONIX.md from. (Running in a test harness?)",
};
}
// `codeRoot` is set only when running `reasonix code`. Chat mode has
// `memoryRoot` = cwd (for REASONIX.md), but we don't treat cwd as a
// sandbox — project-scope user memory requires a real code-mode root.
const store = new MemoryStore({ projectRoot: ctx.codeRoot });
const sub = (args[0] ?? "").toLowerCase();
if (sub === "list" || sub === "ls") {
const entries = store.list();
if (entries.length === 0) {
return {
info: "no user memories yet. The model can call `remember` to save one, or you can create files by hand in ~/.reasonix/memory/global/ or the per-project subdir.",
};
}
const lines = [`User memories (${entries.length}):`];
for (const e of entries) {
const tag = `${e.scope}/${e.type}`.padEnd(18);
const name = e.name.padEnd(28);
const desc = e.description.length > 70 ? `${e.description.slice(0, 69)}…` : e.description;
lines.push(` ${tag} ${name} ${desc}`);
}
lines.push("");
lines.push("View body: /memory show <name> Delete: /memory forget <name>");
return { info: lines.join("\n") };
}
if (sub === "show" || sub === "cat") {
const target = args[1];
if (!target) return { info: "usage: /memory show <name> or /memory show <scope>/<name>" };
const resolved = resolveMemoryTarget(store, target);
if (!resolved) return { info: `no memory found: ${target}` };
try {
const entry = store.read(resolved.scope, resolved.name);
return {
info: [
`▸ ${entry.scope}/${entry.name} (${entry.type}, created ${entry.createdAt || "?"})`,
entry.description ? ` ${entry.description}` : "",
"",
entry.body,
]
.filter((l) => l !== "")
.concat("")
.join("\n"),
};
} catch (err) {
return { info: `show failed: ${(err as Error).message}` };
}
}
if (sub === "forget" || sub === "rm" || sub === "delete") {
const target = args[1];
if (!target) return { info: "usage: /memory forget <name> or /memory forget <scope>/<name>" };
const resolved = resolveMemoryTarget(store, target);
if (!resolved) return { info: `no memory found: ${target}` };
try {
const ok = store.delete(resolved.scope, resolved.name);
return {
info: ok
? `▸ forgot ${resolved.scope}/${resolved.name}. Next /new or launch won't see it.`
: `could not forget ${resolved.scope}/${resolved.name} (already gone?)`,
};
} catch (err) {
return { info: `forget failed: ${(err as Error).message}` };
}
}
if (sub === "clear") {
const rawScope = (args[1] ?? "").toLowerCase();
if (rawScope !== "global" && rawScope !== "project") {
return { info: "usage: /memory clear <global|project> confirm" };
}
if ((args[2] ?? "").toLowerCase() !== "confirm") {
return {
info: `about to delete every memory in scope=${rawScope}. Re-run with the word 'confirm' to proceed: /memory clear ${rawScope} confirm`,
};
}
const scope = rawScope as MemoryScope;
const entries = store.list().filter((e) => e.scope === scope);
let deleted = 0;
for (const e of entries) {
try {
if (store.delete(scope, e.name)) deleted++;
} catch {
/* skip */
}
}
return { info: `▸ cleared scope=${scope} — deleted ${deleted} memory file(s).` };
}
// Bare `/memory` — show REASONIX.md + both MEMORY.md blocks.
const parts: string[] = [];
const projMem = readProjectMemory(ctx.memoryRoot);
if (projMem) {
const hdr = projMem.truncated
? `▸ ${PROJECT_MEMORY_FILE}: ${projMem.path} (${projMem.originalChars.toLocaleString()} chars, truncated)`
: `▸ ${PROJECT_MEMORY_FILE}: ${projMem.path} (${projMem.originalChars.toLocaleString()} chars)`;
parts.push(hdr, "", projMem.content);
}
const globalIdx = store.loadIndex("global");
if (globalIdx) {
parts.push(
"",
`▸ global memory (${globalIdx.originalChars.toLocaleString()} chars${globalIdx.truncated ? ", truncated" : ""})`,
"",
globalIdx.content,
);
}
const projectIdx = store.loadIndex("project");
if (projectIdx) {
parts.push(
"",
`▸ project memory (${projectIdx.originalChars.toLocaleString()} chars${projectIdx.truncated ? ", truncated" : ""})`,
"",
projectIdx.content,
);
}
if (parts.length === 0) {
return {
info: [
`no memory pinned in ${ctx.memoryRoot}.`,
"",
"Three layers are available:",
` 1. ${PROJECT_MEMORY_FILE} — committable team memory (in the repo).`,
" 2. ~/.reasonix/memory/global/ — your cross-project private memory.",
` 3. ~/.reasonix/memory/<project-hash>/ — this project's private memory.`,
"",
"Ask the model to `remember` something, or hand-edit files directly.",
"Changes take effect on next /new or launch — the system prompt is hashed once per session to keep the prefix cache warm.",
"",
"Subcommands: /memory list | /memory show <name> | /memory forget <name> | /memory clear <scope> confirm",
].join("\n"),
};
}
parts.push(
"",
"Changes take effect on next /new or launch. Subcommands: /memory list | show | forget | clear",
);
return { info: parts.join("\n") };
}
/**
* Parse a `/memory show|forget` argument. Accepts bare `<name>` or
* `<scope>/<name>`. For bare names, tries project scope first (more
* specific, usually what the user means) then falls back to global.
*/
function resolveMemoryTarget(
store: MemoryStore,
raw: string,
): { scope: MemoryScope; name: string } | null {
const slash = raw.indexOf("/");
if (slash > 0) {
const scopeRaw = raw.slice(0, slash).toLowerCase();
const name = raw.slice(slash + 1);
if (scopeRaw !== "global" && scopeRaw !== "project") return null;
const scope = scopeRaw as MemoryScope;
if (scope === "project" && !store.hasProjectScope()) return null;
return { scope, name };
}
for (const scope of ["project", "global"] as MemoryScope[]) {
if (scope === "project" && !store.hasProjectScope()) continue;
try {
store.read(scope, raw);
return { scope, name: raw };
} catch {
/* next scope */
}
}
return null;
}
/**
* Render a section (resources / prompts) of an MCP inspection into a
* compact "name count items" form, collapsing when unsupported.
* Names-only — descriptions and full metadata live in
* `reasonix mcp inspect`, which is purpose-built for the deep view.
*/
function appendSection(
lines: string[],
label: string,
section:
| { supported: true; items: Array<{ name: string }> }
| { supported: false; reason: string }
| undefined,
): void {
if (!section || !section.supported) {
lines.push(
` ${label.trim()} ${section?.supported === false ? "(not supported)" : "(none)"}`,
);
return;
}
const names = section.items.map((i) => i.name);
if (names.length === 0) {
lines.push(` ${label.trim()} (none)`);
return;
}
const head = names.slice(0, 5).join(", ");
const more = names.length > 5 ? ` +${names.length - 5} more` : "";
lines.push(` ${label.trim()} ${names.length} [${head}${more}]`);
}
function formatToolList(history: Array<{ toolName: string; text: string }>): string {
const total = history.length;
const header = `Tool calls in this session (${total}, most recent first):`;
// Show the 10 most recent. Older ones are rarely what the user
// wants — and the help footer tells them how to reach any entry
// by index if they do.
const shown = Math.min(total, 10);
const lines: string[] = [header];
for (let i = 0; i < shown; i++) {
const entry = history[total - 1 - i];
if (!entry) continue;
const idx = i + 1; // 1-based from most recent
const flat = entry.text.replace(/\s+/g, " ").trim();
const preview = flat.length > 80 ? `${flat.slice(0, 80)}…` : flat;
const name = entry.toolName.length > 24 ? `${entry.toolName.slice(0, 23)}…` : entry.toolName;
lines.push(
` #${String(idx).padStart(2)} ${name.padEnd(24)} ${String(entry.text.length).padStart(6)} chars ${preview}`,
);
}
if (total > shown) {
lines.push(` … (${total - shown} earlier, reach with /tool N)`);
}
lines.push("");
lines.push("View full output: /tool N (N=1 → most recent)");
return lines.join("\n");
}
function compactNum(n: number): string {
if (n < 1000) return String(n);
const k = n / 1000;
return k >= 100 ? `${Math.round(k)}k` : `${k.toFixed(1)}k`;
}
function stripOuterQuotes(s: string): string {
if (s.length >= 2 && s.startsWith('"') && s.endsWith('"')) {
return s.slice(1, -1);
+55
View File
@@ -0,0 +1,55 @@
import React, { type ReactNode, createContext, useContext, useEffect, useState } from "react";
/**
* Global heartbeat for every animated component (braille spinners,
* elapsed-seconds counters, cursor blink). A single setInterval feeds
* all of them instead of each component owning one. Consolidating the
* 5-6 independent timers that used to exist in App.tsx + EventLog.tsx +
* PromptInput.tsx into one source dramatically cuts the number of
* React re-renders per second on heavy turns and stops Ink from
* patching the terminal 30+ times/sec — the main amplifier of redraw
* artifacts on winpty/MINTTY-class Windows terminals.
*
* Resolution: `TICK_MS` (default 120). Components that want 500ms or
* 1s cadence just modulo the tick counter.
*/
export const TICK_MS = 120;
const TickContext = createContext(0);
export interface TickerProviderProps {
children: ReactNode;
/**
* When true, the provider skips the setInterval entirely — tick stays at
* 0, all consumers render once and never re-render from the timer. Used
* by PLAIN_UI mode so the cursor and any surviving spinners don't drive
* repaints on fragile Windows terminals.
*/
disabled?: boolean;
}
export function TickerProvider({ children, disabled }: TickerProviderProps) {
const [tick, setTick] = useState(0);
useEffect(() => {
if (disabled) return;
const id = setInterval(() => setTick((t) => t + 1), TICK_MS);
return () => clearInterval(id);
}, [disabled]);
return <TickContext.Provider value={tick}>{children}</TickContext.Provider>;
}
/** Current global tick. Re-renders the calling component every `TICK_MS`. */
export function useTick(): number {
return useContext(TickContext);
}
/**
* Seconds elapsed since the calling component mounted. Derived from
* the shared tick + a fresh Date.now() read, so no dedicated timer
* is needed.
*/
export function useElapsedSeconds(): number {
const [start] = useState(() => Date.now());
useTick(); // subscribe to the tick so we re-render
return Math.floor((Date.now() - start) / 1000);
}
+41
View File
@@ -45,6 +45,25 @@ export interface StreamChunk {
raw: any;
}
/**
* Response shape for DeepSeek's `/user/balance` endpoint. One entry
* per currency the account is funded in (typically CNY, sometimes
* USD). `total_balance` is the spendable figure; `granted_balance`
* counts promotional credits that expire, `topped_up_balance` is
* what the user paid for and keeps.
*/
export interface BalanceInfo {
currency: string;
total_balance: string;
granted_balance?: string;
topped_up_balance?: string;
}
export interface UserBalance {
is_available: boolean;
balance_infos: BalanceInfo[];
}
export interface DeepSeekClientOptions {
apiKey?: string;
baseUrl?: string;
@@ -92,6 +111,28 @@ export class DeepSeekClient {
return payload;
}
/**
* Fetch the current DeepSeek account balance. Separate endpoint
* from chat completions, no billing impact. Returns null on any
* network/auth failure so callers can gate the balance display
* without a hard error — the rest of the session works regardless.
*/
async getBalance(opts: { signal?: AbortSignal } = {}): Promise<UserBalance | null> {
try {
const resp = await this._fetch(`${this.baseUrl}/user/balance`, {
method: "GET",
headers: { Authorization: `Bearer ${this.apiKey}` },
signal: opts.signal,
});
if (!resp.ok) return null;
const data = (await resp.json()) as UserBalance;
if (!data || !Array.isArray(data.balance_infos)) return null;
return data;
} catch {
return null;
}
}
async chat(opts: ChatRequestOptions): Promise<ChatResponse> {
const ctrl = new AbortController();
const timer = setTimeout(() => ctrl.abort(), this.timeoutMs);
+33 -5
View File
@@ -15,9 +15,31 @@
import { existsSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { applyMemoryStack } from "../user-memory.js";
export const CODE_SYSTEM_PROMPT = `You are Reasonix Code, a coding assistant. You have filesystem tools (read_file, write_file, list_directory, search_files, etc.) rooted at the user's working directory.
# When to propose a plan (submit_plan)
You have a \`submit_plan\` tool that shows the user a markdown plan and lets them Approve / Refine / Cancel before you execute. Use it proactively when the task is large enough to deserve a review gate:
- Multi-file refactors or renames.
- Architecture changes (moving modules, splitting / merging files, new abstractions).
- Anything where "undo" after the fact would be expensive — migrations, destructive cleanups, API shape changes.
- When the user's request is ambiguous and multiple reasonable interpretations exist — propose your reading as a plan and let them confirm.
Skip submit_plan for small, obvious changes: one-line typo, clear bug with a clear fix, adding a missing import, renaming a local variable. Just do those.
Plan body: one-sentence summary, then a file-by-file breakdown of what you'll change and why, and any risks or open questions. If some decisions are genuinely up to the user (naming, tradeoffs, out-of-scope possibilities), list them in an "Open questions" section — the user sees the plan in a picker and has a text input to answer your questions before approving. Don't pretend certainty you don't have; flagged questions are how the user tells you what they care about. After calling submit_plan, STOP — don't call any more tools, wait for the user's verdict.
# Plan mode (/plan)
The user can ALSO enter "plan mode" via /plan, which is a stronger, explicit constraint:
- Write tools (edit_file, write_file, create_directory, move_file) and non-allowlisted run_command calls are BOUNCED at dispatch — you'll get a tool result like "unavailable in plan mode". Don't retry them.
- Read tools (read_file, list_directory, search_files, directory_tree, get_file_info) and allowlisted read-only / test shell commands still work — use them to investigate.
- You MUST call submit_plan before anything will execute. Approve exits plan mode; Refine stays in; Cancel exits without implementing.
# When to edit vs. when to explore
Only propose edits when the user explicitly asks you to change, fix, add, remove, refactor, or write something. Do NOT propose edits when the user asks you to:
@@ -52,9 +74,13 @@ Rules:
- Do NOT use write_file to change existing files — the user reviews your edits as SEARCH/REPLACE. write_file is only for files you explicitly want to overwrite wholesale (rare).
- Paths are relative to the working directory. Don't use absolute paths.
# Trust what you already know
Before exploring the filesystem to answer a factual question, check whether the answer is already in context: the user's current message, earlier turns in this conversation (including prior tool results from \`remember\`), and the pinned memory blocks at the top of this prompt. When the user has stated a fact or you have remembered one, it outranks what the files say — don't re-derive from code what the user already told you. Explore when you genuinely don't know.
# Exploration
- Avoid listing or reading inside these common dependency / build directories unless the user explicitly asks about them: node_modules, dist, build, out, .next, .nuxt, .svelte-kit, .git, .venv, venv, __pycache__, target, coverage, .turbo, .cache. They're expensive and usually irrelevant.
- Skip dependency, build, and VCS directories unless the user explicitly asks. The pinned .gitignore block (if any, below) is your authoritative denylist.
- Prefer search_files / grep over list_directory when you know roughly what you're looking for — it saves context and avoids enumerating huge trees.
# Style
@@ -70,23 +96,25 @@ Rules:
* the file — we hand it to the model as-is. Truncate long ones so we
* don't eat context budget on huge generated ignore lists.
*
* Missing or unreadable .gitignore → returns the base prompt unchanged.
* Stacking order (stable for cache prefix):
* base prompt → REASONIX.md → global MEMORY.md → project MEMORY.md → .gitignore
*/
export function codeSystemPrompt(rootDir: string): string {
const withMemory = applyMemoryStack(CODE_SYSTEM_PROMPT, rootDir);
const gitignorePath = join(rootDir, ".gitignore");
if (!existsSync(gitignorePath)) return CODE_SYSTEM_PROMPT;
if (!existsSync(gitignorePath)) return withMemory;
let content: string;
try {
content = readFileSync(gitignorePath, "utf8");
} catch {
return CODE_SYSTEM_PROMPT;
return withMemory;
}
const MAX = 2000;
const truncated =
content.length > MAX
? `${content.slice(0, MAX)}\n… (truncated ${content.length - MAX} chars)`
: content;
return `${CODE_SYSTEM_PROMPT}
return `${withMemory}
# Project .gitignore
+62
View File
@@ -44,6 +44,23 @@ export interface ReasonixConfig {
session?: string | null;
/** Marks that `reasonix setup` has completed at least once. */
setupCompleted?: boolean;
/**
* Whether `web_search` + `web_fetch` tools are registered. Default:
* enabled (no key required — backed by DuckDuckGo's public HTML
* endpoint). Set to `false` to keep the session offline.
*/
search?: boolean;
/**
* Per-project state keyed by absolute directory path. Written by the
* "always allow" choice on a shell confirmation prompt; merged into
* `registerShellTools({ extraAllowed })` when `reasonix code` runs
* against that directory again.
*/
projects?: {
[absoluteRootDir: string]: {
shellAllowed?: string[];
};
};
}
export function defaultConfigPath(): string {
@@ -78,12 +95,57 @@ export function loadApiKey(path: string = defaultConfigPath()): string | undefin
return readConfig(path).apiKey;
}
/**
* Resolve whether web-search tools should be registered. Default: on.
* Env `REASONIX_SEARCH=off` or config `search: false` turns it off.
* Any other value falls through to enabled.
*/
export function searchEnabled(path: string = defaultConfigPath()): boolean {
const env = process.env.REASONIX_SEARCH;
if (env === "off" || env === "false" || env === "0") return false;
const cfg = readConfig(path).search;
if (cfg === false) return false;
return true;
}
export function saveApiKey(key: string, path: string = defaultConfigPath()): void {
const cfg = readConfig(path);
cfg.apiKey = key.trim();
writeConfig(cfg, path);
}
/**
* Read the persisted "always allow" shell-command prefixes for a
* given project root. Returns an empty array when nothing's stored.
*/
export function loadProjectShellAllowed(
rootDir: string,
path: string = defaultConfigPath(),
): string[] {
const cfg = readConfig(path);
return cfg.projects?.[rootDir]?.shellAllowed ?? [];
}
/**
* Append a prefix to the project's shell-allowed list, dedup and
* persist. No-op if the prefix is empty/whitespace or already stored.
*/
export function addProjectShellAllowed(
rootDir: string,
prefix: string,
path: string = defaultConfigPath(),
): void {
const trimmed = prefix.trim();
if (!trimmed) return;
const cfg = readConfig(path);
if (!cfg.projects) cfg.projects = {};
if (!cfg.projects[rootDir]) cfg.projects[rootDir] = {};
const existing = cfg.projects[rootDir].shellAllowed ?? [];
if (existing.includes(trimmed)) return;
cfg.projects[rootDir].shellAllowed = [...existing, trimmed];
writeConfig(cfg, path);
}
export function isPlausibleKey(key: string): boolean {
const trimmed = key.trim();
return /^sk-[A-Za-z0-9_-]{16,}$/.test(trimmed);
+5
View File
@@ -68,8 +68,12 @@ export async function harvest(
reasoningContent: string | null | undefined,
client?: DeepSeekClient,
options: HarvestOptions = {},
signal?: AbortSignal,
): Promise<TypedPlanState> {
if (!client || !reasoningContent) return emptyPlanState();
// Fast-path the already-aborted case so we don't burn a network
// round-trip for a result the caller no longer wants.
if (signal?.aborted) return emptyPlanState();
const minLen = options.minReasoningLen ?? 40;
const trimmed = reasoningContent.trim();
if (trimmed.length < minLen) return emptyPlanState();
@@ -92,6 +96,7 @@ export async function harvest(
responseFormat: { type: "json_object" },
temperature: 0,
maxTokens: 600,
signal,
});
return parsePlanState(resp.content, maxItems, maxItemLen);
} catch {
+404
View File
@@ -0,0 +1,404 @@
/**
* Hooks — user-defined automation that fires at well-known points in
* the agent loop. Mirrors the two-scope layout we use for memory and
* skills:
*
* - `<project>/.reasonix/settings.json` — committable per-project
* - `~/.reasonix/settings.json` — every session
*
* A hook is a shell command. We invoke it with stdin = a JSON
* payload describing the event, and interpret the exit code:
*
* - `0` — pass; loop continues normally
* - `2` — block; for `PreToolUse` / `UserPromptSubmit` the
* loop refuses to continue with that step and surfaces the
* hook's stderr as the reason. For `PostToolUse` / `Stop` block
* is meaningless (the action already happened) — treat as warn.
* - anything else — warn; loop continues but stderr is rendered
* to the user as an inline notice.
*
* stdin JSON shape (one envelope per event):
*
* {
* "event": "PreToolUse" | "PostToolUse" | "UserPromptSubmit" | "Stop",
* "cwd": "<absolute project root or process.cwd()>",
* "toolName": "<string>", // tool events only
* "toolArgs": <unknown>, // tool events only — already JSON-decoded
* "toolResult": "<string>", // PostToolUse only — same body the model sees
* "prompt": "<string>", // UserPromptSubmit only
* "lastAssistantText": "<string>", // Stop only
* "turn": <number>, // Stop only
* }
*
* Hooks are executed in order: project scope first, then global.
* `Pre*` events stop dispatching at the first block; non-block
* outcomes accumulate into a single report so the UI can render
* each warning inline.
*/
import { spawn } from "node:child_process";
import { existsSync, readFileSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
export type HookEvent = "PreToolUse" | "PostToolUse" | "UserPromptSubmit" | "Stop";
/** All four events as a const array — drives slash listing + validation. */
export const HOOK_EVENTS: readonly HookEvent[] = [
"PreToolUse",
"PostToolUse",
"UserPromptSubmit",
"Stop",
] as const;
/** Only the gating events can block the loop. */
const BLOCKING_EVENTS: ReadonlySet<HookEvent> = new Set(["PreToolUse", "UserPromptSubmit"]);
/** Per-event default timeout. Tool/prompt hooks gate progress, so they're tight. */
const DEFAULT_TIMEOUTS_MS: Record<HookEvent, number> = {
PreToolUse: 5_000,
UserPromptSubmit: 5_000,
PostToolUse: 30_000,
Stop: 30_000,
};
export type HookScope = "project" | "global";
export interface HookConfig {
/**
* Tool-name pattern (PreToolUse / PostToolUse only). Anchored regex.
* Omitted or `"*"` matches every tool. Ignored for prompt / Stop
* events (they have no tool name to match against).
*/
match?: string;
/** Shell command to run. Spawned through the platform shell. */
command: string;
/** Optional human description — surfaced in `/hooks`. */
description?: string;
/** Per-hook timeout override in ms. */
timeout?: number;
/**
* Working directory for the spawned process. Defaults to:
* - project scope → the project root
* - global scope → process.cwd()
*/
cwd?: string;
}
/** Shape of `<scope>/.reasonix/settings.json` — only `hooks` for now. */
export interface HookSettings {
hooks?: Partial<Record<HookEvent, HookConfig[]>>;
}
/** A loaded hook with its origin scope baked in (used for ordering and `/hooks`). */
export interface ResolvedHook extends HookConfig {
event: HookEvent;
scope: HookScope;
/** Absolute path to the settings.json the hook came from. */
source: string;
}
/** Outcome of a single hook invocation. */
export interface HookOutcome {
/** Which hook fired. */
hook: ResolvedHook;
/**
* Decision:
* - `pass` — exit 0
* - `block` — exit 2 on a blocking event (otherwise downgraded to `warn`)
* - `warn` — non-zero exit that is not a successful block
* - `timeout` — the spawn was killed past `timeout`
* - `error` — could not spawn at all (missing command, etc.)
*/
decision: "pass" | "block" | "warn" | "timeout" | "error";
exitCode: number | null;
/** Captured stdout (trimmed). May be empty. */
stdout: string;
/** Captured stderr (trimmed). The block / warn message comes from here. */
stderr: string;
durationMs: number;
}
/** Aggregate report for `runHooks`. */
export interface HookReport {
event: HookEvent;
outcomes: HookOutcome[];
/** True iff at least one outcome was a `block` — only meaningful for blocking events. */
blocked: boolean;
}
export const HOOK_SETTINGS_FILENAME = "settings.json";
export const HOOK_SETTINGS_DIRNAME = ".reasonix";
/** Where the global settings.json lives. Equivalent to `~/.reasonix/settings.json`. */
export function globalSettingsPath(homeDirOverride?: string): string {
return join(homeDirOverride ?? homedir(), HOOK_SETTINGS_DIRNAME, HOOK_SETTINGS_FILENAME);
}
/** Where the project settings.json lives for a given root. */
export function projectSettingsPath(projectRoot: string): string {
return join(projectRoot, HOOK_SETTINGS_DIRNAME, HOOK_SETTINGS_FILENAME);
}
function readSettingsFile(path: string): HookSettings | null {
if (!existsSync(path)) return null;
try {
const raw = readFileSync(path, "utf8");
const parsed = JSON.parse(raw);
if (parsed && typeof parsed === "object") return parsed as HookSettings;
} catch {
/* malformed JSON → treat as no hooks; do NOT throw, the user
* shouldn't lose the whole CLI to a typo in their settings */
}
return null;
}
/**
* Pull every configured hook out of the project + global settings
* files, in the order they should fire (project first, global second,
* within each scope: array order from the file).
*
* Returns a flat list — the dispatcher filters by event + match
* pattern at run time. Loading is cheap (one or two JSON files), so
* we don't memoize across processes; re-load is allowed via
* `/hooks reload` and on every fresh App mount.
*/
export interface LoadHookSettingsOptions {
/** Absolute project root, if any. Without it, only global hooks load. */
projectRoot?: string;
/** Override `~` for tests. */
homeDir?: string;
}
export function loadHooks(opts: LoadHookSettingsOptions = {}): ResolvedHook[] {
const out: ResolvedHook[] = [];
if (opts.projectRoot) {
const projPath = projectSettingsPath(opts.projectRoot);
const settings = readSettingsFile(projPath);
if (settings) appendResolved(out, settings, "project", projPath);
}
const globalPath = globalSettingsPath(opts.homeDir);
const settings = readSettingsFile(globalPath);
if (settings) appendResolved(out, settings, "global", globalPath);
return out;
}
function appendResolved(
out: ResolvedHook[],
settings: HookSettings,
scope: HookScope,
source: string,
): void {
if (!settings.hooks) return;
for (const event of HOOK_EVENTS) {
const list = settings.hooks[event];
if (!Array.isArray(list)) continue;
for (const cfg of list) {
if (!cfg || typeof cfg.command !== "string" || cfg.command.trim() === "") continue;
out.push({ ...cfg, event, scope, source });
}
}
}
/**
* True if `toolName` matches the hook's `match` field. `"*"` and
* undefined match everything. Otherwise we anchor the field as a
* regex — partial-name matches don't fire, so `"file"` would not
* trigger on `read_file` (use `".*file"` for that).
*/
export function matchesTool(hook: ResolvedHook, toolName: string): boolean {
if (hook.event !== "PreToolUse" && hook.event !== "PostToolUse") return true;
const m = hook.match;
if (!m || m === "*") return true;
try {
const re = new RegExp(`^(?:${m})$`);
return re.test(toolName);
} catch {
/* malformed regex → don't fire (safer than firing on every tool) */
return false;
}
}
/** Payload envelope passed to hook stdin. */
export interface HookPayload {
event: HookEvent;
cwd: string;
toolName?: string;
toolArgs?: unknown;
toolResult?: string;
prompt?: string;
lastAssistantText?: string;
turn?: number;
}
/** Test seam — same shape as Node's spawn but returns a Promise of the raw outcome bits. */
export interface HookSpawnInput {
command: string;
cwd: string;
stdin: string;
timeoutMs: number;
}
export interface HookSpawnResult {
exitCode: number | null;
stdout: string;
stderr: string;
timedOut: boolean;
/** True iff spawn() itself failed (ENOENT, EACCES, …). */
spawnError?: Error;
}
export type HookSpawner = (input: HookSpawnInput) => Promise<HookSpawnResult>;
/**
* Default spawner — runs `command` through the platform shell so
* `&&`, pipes, env-var expansion all work without a tokenizer.
* Stdin is the JSON payload, stdout / stderr are buffered.
*
* Why `shell: true`? A hook is intentionally a shell command — that's
* the contract. Treating it like an argv array would surprise users
* who write `bun run check && eslint .` and expect it to behave the
* way it does in their terminal.
*/
function defaultSpawner(input: HookSpawnInput): Promise<HookSpawnResult> {
return new Promise<HookSpawnResult>((resolve) => {
const child = spawn(input.command, {
cwd: input.cwd,
shell: true,
stdio: ["pipe", "pipe", "pipe"],
});
let stdout = "";
let stderr = "";
let timedOut = false;
const timer = setTimeout(() => {
timedOut = true;
child.kill("SIGTERM");
// SIGTERM may not land on Windows for shell children — followed
// by a hard kill a moment later if the process is still around.
setTimeout(() => {
try {
child.kill("SIGKILL");
} catch {
/* already gone */
}
}, 500);
}, input.timeoutMs);
child.stdout.on("data", (chunk: Buffer) => {
stdout += chunk.toString("utf8");
});
child.stderr.on("data", (chunk: Buffer) => {
stderr += chunk.toString("utf8");
});
child.once("error", (err) => {
clearTimeout(timer);
resolve({
exitCode: null,
stdout,
stderr,
timedOut: false,
spawnError: err,
});
});
child.once("close", (code) => {
clearTimeout(timer);
resolve({
exitCode: code,
stdout: stdout.trim(),
stderr: stderr.trim(),
timedOut,
});
});
try {
child.stdin.write(input.stdin);
child.stdin.end();
} catch {
/* stdin write can race with spawn errors; the close handler
* still fires with exit 0/null */
}
});
}
/**
* Format a hook outcome as a single-line UI string. Used by both the
* loop (for `warning` events) and the App (for UserPromptSubmit /
* Stop outcomes). Centralizing keeps the language consistent across
* scopes.
*/
export function formatHookOutcomeMessage(outcome: HookOutcome): string {
if (outcome.decision === "pass") return "";
const detail = (outcome.stderr || outcome.stdout || "").trim();
const tag = `${outcome.hook.scope}/${outcome.hook.event}`;
const cmd =
outcome.hook.command.length > 60
? `${outcome.hook.command.slice(0, 60)}…`
: outcome.hook.command;
const head = `hook ${tag} \`${cmd}\` ${outcome.decision}`;
return detail ? `${head}: ${detail}` : head;
}
/**
* Decide the hook's outcome decision from raw spawn results.
* Pulled out as a pure function so tests can pin the matrix.
*/
export function decideOutcome(
event: HookEvent,
raw: HookSpawnResult,
): "pass" | "block" | "warn" | "timeout" | "error" {
if (raw.spawnError) return "error";
if (raw.timedOut) return BLOCKING_EVENTS.has(event) ? "block" : "warn";
if (raw.exitCode === 0) return "pass";
if (raw.exitCode === 2 && BLOCKING_EVENTS.has(event)) return "block";
return "warn";
}
export interface RunHooksOptions {
payload: HookPayload;
hooks: ResolvedHook[];
/** Test seam — defaults to a real `spawn`. */
spawner?: HookSpawner;
}
/**
* Filter hooks down to the ones that match `payload.event` (and
* `payload.toolName`, for tool events), then run them in order.
* Stops at the first `block` outcome on a blocking event so a
* gating hook can prevent later hooks from incorrectly seeing a
* success that wasn't going to happen.
*/
export async function runHooks(opts: RunHooksOptions): Promise<HookReport> {
const spawner = opts.spawner ?? defaultSpawner;
const event = opts.payload.event;
const toolName = opts.payload.toolName ?? "";
const matching = opts.hooks.filter((h) => h.event === event && matchesTool(h, toolName));
const outcomes: HookOutcome[] = [];
let blocked = false;
const stdin = `${JSON.stringify(opts.payload)}\n`;
for (const hook of matching) {
const start = Date.now();
const timeoutMs = hook.timeout ?? DEFAULT_TIMEOUTS_MS[event];
const cwd = hook.cwd ?? opts.payload.cwd;
const raw = await spawner({ command: hook.command, cwd, stdin, timeoutMs });
const decision = decideOutcome(event, raw);
outcomes.push({
hook,
decision,
exitCode: raw.exitCode,
stdout: raw.stdout,
stderr:
raw.stderr ||
(raw.spawnError ? raw.spawnError.message : "") ||
(raw.timedOut ? `hook timed out after ${timeoutMs}ms` : ""),
durationMs: Date.now() - start,
});
if (decision === "block") {
blocked = true;
break;
}
}
return { event, outcomes, blocked };
}
+145 -5
View File
@@ -3,7 +3,12 @@
export { DeepSeekClient, Usage } from "./client.js";
export type { ChatResponse, StreamChunk, DeepSeekClientOptions } from "./client.js";
export { CacheFirstLoop, formatLoopError, healLoadedMessages } from "./loop.js";
export {
CacheFirstLoop,
formatLoopError,
healLoadedMessages,
stripHallucinatedToolMarkup,
} from "./loop.js";
export type {
CacheFirstLoopOptions,
LoopEvent,
@@ -24,10 +29,76 @@ export type {
export { ImmutablePrefix, AppendOnlyLog, VolatileScratch } from "./memory.js";
export type { ImmutablePrefixOptions } from "./memory.js";
export { ToolRegistry } from "./tools.js";
export type { ToolDefinition } from "./tools.js";
export {
PROJECT_MEMORY_FILE,
PROJECT_MEMORY_MAX_CHARS,
applyProjectMemory,
memoryEnabled,
readProjectMemory,
} from "./project-memory.js";
export type { ProjectMemory } from "./project-memory.js";
export { SessionStats, costUsd, claudeEquivalentCost } from "./telemetry.js";
export {
MEMORY_INDEX_FILE,
MEMORY_INDEX_MAX_CHARS,
MemoryStore,
USER_MEMORY_DIR,
applyMemoryStack,
applyUserMemory,
projectHash,
sanitizeMemoryName,
} from "./user-memory.js";
export type {
MemoryEntry,
MemoryScope,
MemoryStoreOptions,
MemoryType,
WriteInput as MemoryWriteInput,
} from "./user-memory.js";
export { ToolRegistry } from "./tools.js";
export type { ToolDefinition, ToolCallContext } from "./tools.js";
export { registerFilesystemTools } from "./tools/filesystem.js";
export type { FilesystemToolsOptions } from "./tools/filesystem.js";
export { registerMemoryTools } from "./tools/memory.js";
export type { MemoryToolsOptions } from "./tools/memory.js";
export { PlanProposedError, registerPlanTool } from "./tools/plan.js";
export type { PlanToolOptions } from "./tools/plan.js";
export {
NeedsConfirmationError,
formatCommandResult,
isAllowed,
prepareSpawn,
quoteForCmdExe,
registerShellTools,
resolveExecutable,
runCommand,
tokenizeCommand,
} from "./tools/shell.js";
export type { RunCommandResult, ShellToolsOptions } from "./tools/shell.js";
export {
formatSearchResults,
htmlToText,
parseMojeekResults,
registerWebTools,
webFetch,
webSearch,
} from "./tools/web.js";
export type {
PageContent,
SearchResult,
WebFetchOptions,
WebSearchOptions,
WebToolsOptions,
} from "./tools/web.js";
export {
SessionStats,
costUsd,
inputCostUsd,
outputCostUsd,
claudeEquivalentCost,
} from "./telemetry.js";
export type { TurnStats, SessionSummary } from "./telemetry.js";
export {
@@ -101,6 +172,8 @@ export {
export type { BridgeOptions, BridgeResult, FlattenOptions } from "./mcp/registry.js";
export { parseMcpSpec } from "./mcp/spec.js";
export type { McpSpec, StdioMcpSpec, SseMcpSpec } from "./mcp/spec.js";
export { inspectMcpServer } from "./mcp/inspect.js";
export type { InspectionReport, SectionResult } from "./mcp/inspect.js";
// ---------- code mode (v0.3 — `reasonix code`) ----------
export {
@@ -131,6 +204,21 @@ export type {
JsonRpcRequest,
JsonRpcResponse,
JsonRpcMessage,
McpResource,
McpResourceContents,
McpResourceContentsText,
McpResourceContentsBlob,
ListResourcesResult,
ReadResourceResult,
McpPrompt,
McpPromptArgument,
McpPromptMessage,
McpPromptResourceBlock,
ListPromptsResult,
GetPromptResult,
McpProgressHandler,
McpProgressInfo,
ProgressNotificationParams,
} from "./mcp/types.js";
export { fetchWithRetry } from "./retry.js";
@@ -156,4 +244,56 @@ export type {
JSONSchema,
} from "./types.js";
export const VERSION = "0.4.2";
export {
LATEST_CACHE_TTL_MS,
LATEST_FETCH_TIMEOUT_MS,
VERSION,
compareVersions,
getLatestVersion,
isNpxInstall,
} from "./version.js";
export type { GetLatestVersionOptions } from "./version.js";
export {
HOOK_EVENTS,
HOOK_SETTINGS_DIRNAME,
HOOK_SETTINGS_FILENAME,
decideOutcome,
formatHookOutcomeMessage,
globalSettingsPath,
loadHooks,
matchesTool,
projectSettingsPath,
runHooks,
} from "./hooks.js";
export {
aggregateUsage,
appendUsage,
bucketCacheHitRatio,
bucketSavingsFraction,
defaultUsageLogPath,
formatLogSize,
readUsageLog,
} from "./usage.js";
export type {
AggregateOptions,
AppendUsageInput,
UsageAggregate,
UsageBucket,
UsageRecord,
} from "./usage.js";
export type {
HookConfig,
HookEvent,
HookOutcome,
HookPayload,
HookReport,
HookScope,
HookSettings,
HookSpawner,
HookSpawnInput,
HookSpawnResult,
LoadHookSettingsOptions,
ResolvedHook,
RunHooksOptions,
} from "./hooks.js";
+517 -34
View File
@@ -6,6 +6,13 @@ import {
runBranches,
} from "./consistency.js";
import { type HarvestOptions, type TypedPlanState, emptyPlanState, harvest } from "./harvest.js";
import {
type HookOutcome,
type HookPayload,
type ResolvedHook,
formatHookOutcomeMessage,
runHooks,
} from "./hooks.js";
import { DEFAULT_MAX_RESULT_CHARS, truncateForModel } from "./mcp/registry.js";
import { AppendOnlyLog, type ImmutablePrefix, VolatileScratch } from "./memory.js";
import { type RepairReport, ToolCallRepair } from "./repair/index.js";
@@ -22,6 +29,13 @@ import type { ChatMessage, ToolCall } from "./types.js";
export type EventRole =
| "assistant_delta"
| "assistant_final"
/**
* Emitted as `tool_calls[].function.arguments` streams in. A tool
* call with a large arguments payload produces no `content` or
* `reasoning_content` bytes — this is the only signal the UI has
* that the stream is alive during that window.
*/
| "tool_call_delta"
/**
* Yielded immediately before a tool is dispatched. Lets the TUI put
* up a "▸ tool<X> running…" spinner while the tool's Promise is
@@ -34,6 +48,15 @@ export type EventRole =
| "done"
| "error"
| "warning"
/**
* Transient "what's happening right now" indicator. Emitted during
* silent phases — between a tool result and the next iteration's
* first streaming byte, and right before harvest — so the TUI can
* show a spinner with explanatory text instead of looking frozen.
* The UI clears it on the next primary event (assistant_delta,
* tool_start, tool, assistant_final, error).
*/
| "status"
| "branch_start"
| "branch_progress"
| "branch_done";
@@ -65,6 +88,8 @@ export interface LoopEvent {
* what it returned. Needed by `reasonix diff` to explain divergences.
*/
toolArgs?: string;
/** Cumulative arguments-string length for `role === "tool_call_delta"`. */
toolCallArgsChars?: number;
stats?: TurnStats;
planState?: TypedPlanState;
repair?: RepairReport;
@@ -109,6 +134,21 @@ export interface CacheFirstLoopOptions {
* `~/.reasonix/sessions/<name>.jsonl` so the next run can resume.
*/
session?: string;
/**
* Resolved hook list — loaded from `<project>/.reasonix/settings.json`
* + `~/.reasonix/settings.json` by the CLI before constructing the loop.
* The loop dispatches `PreToolUse` and `PostToolUse` events itself; the
* CLI handles `UserPromptSubmit` and `Stop` since they live at the App
* boundary. Empty / unset → no hooks fire (the runtime cost of an empty
* filter is one ms). See `src/hooks.ts` for the full contract.
*/
hooks?: ResolvedHook[];
/**
* `cwd` reported to hooks via the stdin payload. Defaults to `process.cwd()`.
* `reasonix code` overrides this to the sandbox root so a hook that does
* `cd $REASONIX_CWD` lands in the project, not in the user's shell home.
*/
hookCwd?: string;
}
/**
@@ -147,17 +187,28 @@ export class CacheFirstLoop {
branchOptions: BranchOptions;
sessionName: string | null;
/**
* Hook list, mutable so `/hooks reload` can swap it without
* reconstructing the loop. Default empty — the filter cost on a
* tool call is one array length check.
*/
hooks: ResolvedHook[];
/** `cwd` reported to hook stdin. Resolved once at construction. */
readonly hookCwd: string;
/** Number of messages that were pre-loaded from the session file. */
readonly resumedMessageCount: number;
private _turn = 0;
private _streamPreference: boolean;
/**
* Set by {@link abort} to short-circuit the tool-call loop after the
* current iteration. Reset at the start of each `step()` so an Esc
* during one turn doesn't poison the next.
* AbortController per active turn. Threaded through the DeepSeek
* HTTP calls AND every tool dispatch so Esc actually cancels the
* in-flight network/subprocess work — not "we'll get to it after
* the current call finishes." Re-created at the start of each
* `step()` (the prior turn's signal has already fired).
*/
private _aborted = false;
private _turnAbort: AbortController = new AbortController();
constructor(opts: CacheFirstLoopOptions) {
this.client = opts.client;
@@ -174,6 +225,8 @@ export class CacheFirstLoop {
// the decision, keep the iter cap as a last-resort backstop for
// the case where something spins without growing the prompt.
this.maxToolIters = opts.maxToolIters ?? 64;
this.hooks = opts.hooks ?? [];
this.hookCwd = opts.hookCwd ?? process.cwd();
// Resolve branch config first (since it forces harvest on).
if (typeof opts.branch === "number") {
@@ -221,8 +274,18 @@ export class CacheFirstLoop {
for (const msg of messages) this.log.append(msg);
this.resumedMessageCount = messages.length;
if (healedCount > 0) {
// Persist the healed log back to disk so the damage doesn't
// re-surface on the next session load — otherwise `heal →
// append → resume → heal → …` would keep noticing the same
// broken tail every restart. Non-fatal on I/O error: the
// in-memory log is already healed so this session still works.
try {
rewriteSession(this.sessionName, messages);
} catch {
/* disk full / perms — skip, in-memory heal still applies */
}
process.stderr.write(
`▸ session "${this.sessionName}": healed ${healedCount} oversized tool result(s) (was ${healedFrom.toLocaleString()} chars total). Old payloads were truncated to fit DeepSeek's context window; the conversation is preserved.\n`,
`▸ session "${this.sessionName}": healed ${healedCount} entr${healedCount === 1 ? "y" : "ies"}${healedFrom > 0 ? ` (was ${healedFrom.toLocaleString()} chars oversized)` : " (dropped dangling tool_calls tail)"}. Rewrote session file.\n`,
);
}
} else {
@@ -243,7 +306,13 @@ export class CacheFirstLoop {
*/
compact(tightCapChars = 4000): { healedCount: number; charsSaved: number } {
const before = this.log.toMessages();
const { messages, healedCount, healedFrom } = healLoadedMessages(before, tightCapChars);
// Use `shrinkOversizedToolResults` (not `healLoadedMessages`) — the
// full heal would also strip a dangling `assistant.tool_calls` tail,
// which during an active turn is legitimate state we still need
// (tools haven't been dispatched yet). Structural healing is only
// appropriate at session LOAD; mid-session `/compact` is strictly
// about shrinking oversized tool payloads.
const { messages, healedCount, healedFrom } = shrinkOversizedToolResults(before, tightCapChars);
const afterBytes = messages
.filter((m) => m.role === "tool")
.reduce((s, m) => s + (typeof m.content === "string" ? m.content.length : 0), 0);
@@ -272,6 +341,31 @@ export class CacheFirstLoop {
}
}
/**
* Start a fresh conversation WITHOUT exiting. Drops every message
* in the in-memory log AND rewrites the session file to empty so
* a resume won't re-hydrate the old turns. Unlike `/forget`, which
* deletes the session entirely, this keeps the session name and
* config intact — it's the "new chat" button.
*
* The immutable prefix (system prompt + tool specs) is preserved
* — that's the cache-first invariant, not part of the conversation.
* Returns the number of messages dropped so the UI can show it.
*/
clearLog(): { dropped: number } {
const dropped = this.log.length;
this.log.compactInPlace([]);
if (this.sessionName) {
try {
rewriteSession(this.sessionName, []);
} catch {
/* disk issue shouldn't block the in-memory clear */
}
}
this.scratch.reset();
return { dropped };
}
/**
* Reconfigure model/harvest/branch/stream mid-session. The loop's log,
* scratch, and stats are preserved — only the per-turn behavior changes.
@@ -310,26 +404,83 @@ export class CacheFirstLoop {
}
private buildMessages(pendingUser: string | null): ChatMessage[] {
const msgs: ChatMessage[] = [...this.prefix.toMessages(), ...this.log.toMessages()];
// Full tool_calls ↔ tool pairing validation. DeepSeek 400s on
// both sides of this contract — unpaired assistant.tool_calls
// ("insufficient tool messages following") OR stray tool entries
// ("tool must be a response to a preceding tool_calls"). A corrupted
// session from an earlier build can have either. Rather than
// applying a bunch of narrow tail-trim heuristics, rebuild the
// message stream through the same validator used at load time so
// the payload we hand to the API is well-formed by construction.
const healed = healLoadedMessages(this.log.toMessages(), DEFAULT_MAX_RESULT_CHARS);
const msgs: ChatMessage[] = [...this.prefix.toMessages(), ...healed.messages];
if (pendingUser !== null) msgs.push({ role: "user", content: pendingUser });
return msgs;
}
/**
* Signal the currently-running {@link step} that the user wants to
* stop exploring. Takes effect at the next iteration boundary — if a
* tool call is mid-flight it will be allowed to finish, then the
* loop diverts to the forced-summary path so the user gets an
* answer instead of a cliff. Called by the TUI on Esc.
* Signal the currently-running {@link step} to stop **now**. Cancels
* the in-flight network request (DeepSeek HTTP/SSE) AND any tool call
* currently dispatching (MCP `notifications/cancelled` + promise
* reject). The loop itself also sees `signal.aborted` at each
* iteration boundary and exits quickly instead of looping again.
* Called by the TUI on Esc.
*/
abort(): void {
this._aborted = true;
this._turnAbort.abort();
}
/**
* Drop everything in the log after (and including) the most recent
* user message. Used by `/retry` so the caller can re-send that
* message with a fresh turn instead of layering another response on
* top of the prior exchange. Returns the content of the dropped user
* message, or `null` if there isn't one yet.
*
* Persists by rewriting the session file — otherwise the next
* launch would rehydrate the old exchange and `/retry` would seem
* to have done nothing.
*/
retryLastUser(): string | null {
const entries = this.log.entries;
let lastUserIdx = -1;
for (let i = entries.length - 1; i >= 0; i--) {
if (entries[i]!.role === "user") {
lastUserIdx = i;
break;
}
}
if (lastUserIdx < 0) return null;
const raw = entries[lastUserIdx]!.content;
const userText = typeof raw === "string" ? raw : "";
// Keep everything strictly before the user message. The caller
// will submit the text again through the normal path, which
// re-appends the user turn on first successful API response.
const preserved = entries.slice(0, lastUserIdx).map((m) => ({ ...m }));
this.log.compactInPlace(preserved);
if (this.sessionName) {
try {
rewriteSession(this.sessionName, preserved);
} catch {
/* disk-full / perms — in-memory compaction still applies */
}
}
return userText;
}
async *step(userInput: string): AsyncGenerator<LoopEvent> {
this._turn++;
this.scratch.reset();
this._aborted = false;
// A fresh user turn is a new intent — don't let StormBreaker's
// old sliding window of (name, args) signatures keep blocking
// calls that are now legitimately on-task. The window repopulates
// naturally as this turn's tool calls flow through.
this.repair.resetStorm();
// Fresh controller for this turn: the prior step's signal has
// already fired (or stayed clean); either way we don't want its
// state to bleed into the new turn.
this._turnAbort = new AbortController();
const signal = this._turnAbort.signal;
let pendingUser: string | null = userInput;
const toolSpecs = this.prefix.tools();
// 70% of the iter budget is the "you're getting close" threshold. We
@@ -339,15 +490,56 @@ export class CacheFirstLoop {
let warnedForIterBudget = false;
for (let iter = 0; iter < this.maxToolIters; iter++) {
if (this._aborted) {
if (signal.aborted) {
// Esc means "stop now" — not "stop and force another 30-90s
// reasoner call to produce a summary I didn't ask for". The
// user's mental model of cancel is immediate. We emit a
// synthetic assistant_final (tagged forcedSummary so the
// code-mode applier ignores it) with a short stopped
// message, then done. The prior tool outputs are still in
// the log if the user wants to continue — asking again
// will hit a warm cache and be cheap.
//
// Budget / context-guard still call forceSummaryAfterIterLimit
// because there the USER didn't choose to stop — we did —
// and leaving them staring at nothing is worse than one extra
// call.
yield {
turn: this._turn,
role: "warning",
content: `aborted at iter ${iter}/${this.maxToolIters} — forcing summary from what was gathered`,
content: `aborted at iter ${iter}/${this.maxToolIters} — stopped without producing a summary (press ↑ + Enter or /retry to resume)`,
};
yield* this.forceSummaryAfterIterLimit({ reason: "aborted" });
const stoppedMsg =
"[aborted by user (Esc) — no summary produced. Ask again or /retry when ready; prior tool output is still in the log.]";
this.appendAndPersist({ role: "assistant", content: stoppedMsg });
yield {
turn: this._turn,
role: "assistant_final",
content: stoppedMsg,
forcedSummary: true,
};
yield { turn: this._turn, role: "done", content: stoppedMsg };
return;
}
// Bridge the silence between the PREVIOUS iter's tool result and
// THIS iter's first streaming byte. R1 can spend 20-90s reasoning
// about tool output before the first delta lands, and prior to
// this hint the UI had nothing to render. Only emit on iter > 0
// because iter 0's "thinking" phase is already covered by the
// streaming row / StreamingAssistant's placeholder.
//
// Wording is explicit about the two things happening: the tool
// result IS being uploaded (it's now part of the next prompt) and
// the model IS thinking. Users were reading "thinking about the
// tool result" as the model-only phase, but the wait also covers
// the upload round-trip.
if (iter > 0) {
yield {
turn: this._turn,
role: "status",
content: "tool result uploaded · model thinking before next response…",
};
}
if (!warnedForIterBudget && iter >= warnAt) {
warnedForIterBudget = true;
yield {
@@ -403,6 +595,7 @@ export class CacheFirstLoop {
model: this.model,
messages,
tools: toolSpecs.length ? toolSpecs : undefined,
signal,
},
{
...this.branchOptions,
@@ -461,6 +654,7 @@ export class CacheFirstLoop {
model: this.model,
messages,
tools: toolSpecs.length ? toolSpecs : undefined,
signal,
})) {
if (chunk.contentDelta) {
assistantContent += chunk.contentDelta;
@@ -491,6 +685,16 @@ export class CacheFirstLoop {
if (d.argumentsDelta)
cur.function.arguments = (cur.function.arguments ?? "") + d.argumentsDelta;
callBuf.set(d.index, cur);
// Skip the id-only opener: name is empty until the next chunk.
if (cur.function.name) {
yield {
turn: this._turn,
role: "tool_call_delta",
content: "",
toolName: cur.function.name,
toolCallArgsChars: (cur.function.arguments ?? "").length,
};
}
}
if (chunk.usage) usage = chunk.usage;
}
@@ -500,6 +704,7 @@ export class CacheFirstLoop {
model: this.model,
messages,
tools: toolSpecs.length ? toolSpecs : undefined,
signal,
});
assistantContent = resp.content;
reasoningContent = resp.reasoningContent ?? "";
@@ -525,15 +730,31 @@ export class CacheFirstLoop {
}
this.scratch.reasoning = reasoningContent || null;
// Harvest is a second API round-trip (cheap model, but still
// 1-10s) that was previously silent. Bridge the gap with a
// status indicator so the TUI shows *something* instead of
// "reasoning finished, now staring at the wall."
if (
!preHarvestedPlanState &&
this.harvestEnabled &&
(reasoningContent?.trim().length ?? 0) >= 40
) {
yield {
turn: this._turn,
role: "status",
content: "extracting plan state from reasoning…",
};
}
const planState = preHarvestedPlanState
? preHarvestedPlanState
: this.harvestEnabled
? await harvest(reasoningContent || null, this.client, this.harvestOptions)
? await harvest(reasoningContent || null, this.client, this.harvestOptions, signal)
: emptyPlanState();
const { calls: repairedCalls, report } = this.repair.process(
toolCalls,
reasoningContent || null,
assistantContent || null,
);
this.appendAndPersist(this.assistantMessage(assistantContent, repairedCalls));
@@ -548,6 +769,25 @@ export class CacheFirstLoop {
branch: branchSummary,
};
// Loud signal when the storm breaker caught a repeat pattern.
// The `repair` field on assistant_final already carries the
// count as a subtext on the assistant row, but a dedicated
// warning row is far more noticeable — and critical when ALL
// calls were suppressed, because the turn then ends with no
// visible explanation of why nothing happened.
if (report.stormsBroken > 0) {
const noteTail = report.notes.length ? ` — ${report.notes[report.notes.length - 1]}` : "";
const allSuppressed = repairedCalls.length === 0 && toolCalls.length > 0;
const phrase = allSuppressed
? `stopped the model from calling the same tool with identical args repeatedly (all ${toolCalls.length} call(s) this turn were already in the recent-repeat window). Likely a stuck retry — reword your instruction, rule out the underlying blocker, or try /retry after fixing it`
: `suppressed ${report.stormsBroken} repeat tool call(s) that had fired 3+ times with identical args in a sliding window`;
yield {
turn: this._turn,
role: "warning",
content: `${phrase}${noteTail}`,
};
}
if (repairedCalls.length === 0) {
yield { turn: this._turn, role: "done", content: assistantContent };
return;
@@ -558,20 +798,70 @@ export class CacheFirstLoop {
// already is to DeepSeek's 131k context. If we're over 80%, the
// NEXT call (with the just-executed tools' results stuffed into
// history) will be worse, and fairly soon it'll 400 with
// "maximum context length". Divert to summary instead — same
// path as iter-cap and Esc-abort, just triggered by a different
// signal so the user sees *why* it happened.
// "maximum context length".
//
// Strategy, in order:
// 1. Try auto-compacting the log (shrink oversized tool
// results). If that gets us back under 80% we keep going —
// the user doesn't lose their turn to a premature summary.
// 2. If still over after compact, divert to the forced-summary
// path. BUT first drop the trailing assistant-with-tool_calls
// that we just appended — we haven't executed the tools yet,
// so sending this to the summary call with no matching tool
// responses would 400 ("insufficient tool messages following
// tool_calls"). The summary is about what was LEARNED so far,
// not what we intended to do next.
const ctxMax = DEEPSEEK_CONTEXT_TOKENS[this.model] ?? DEFAULT_CONTEXT_TOKENS;
if (usage && usage.promptTokens / ctxMax > 0.8) {
yield {
turn: this._turn,
role: "warning",
content: `context ${usage.promptTokens}/${ctxMax} (${Math.round(
(usage.promptTokens / ctxMax) * 100,
)}%) — more tools would overflow. Forcing summary from what was gathered.`,
};
yield* this.forceSummaryAfterIterLimit({ reason: "context-guard" });
return;
const before = usage.promptTokens;
const compactResult = this.compact(4000);
if (compactResult.healedCount > 0) {
// Rough estimate: 4 chars per token. Good enough to decide
// whether compaction pushed us back under the threshold; the
// exact number comes back from the NEXT API response's usage.
const approxSaved = Math.round(compactResult.charsSaved / 4);
const after = before - approxSaved;
yield {
turn: this._turn,
role: "warning",
content: `context ${before.toLocaleString()}/${ctxMax.toLocaleString()} — auto-compacted ${compactResult.healedCount} oversized tool result(s), saved ~${approxSaved.toLocaleString()} tokens (now ~${after.toLocaleString()}). Continuing.`,
};
// Intentionally don't re-check the threshold here: even if
// compaction didn't fully clear us under 80%, one more tool
// call's overhead isn't going to overflow, and the NEXT
// iter's fresh `usage` from the API will catch real danger.
} else {
yield {
turn: this._turn,
role: "warning",
content: `context ${before.toLocaleString()}/${ctxMax.toLocaleString()} (${Math.round(
(before / ctxMax) * 100,
)}%) — nothing to auto-compact. Forcing summary from what was gathered.`,
};
// Drop the trailing assistant-with-tool_calls we just
// appended. The forced-summary call would otherwise trip
// DeepSeek's "insufficient tool messages following tool_calls"
// validator, since we bail BEFORE dispatching the tools.
const tail = this.log.entries[this.log.entries.length - 1];
if (
tail &&
tail.role === "assistant" &&
Array.isArray(tail.tool_calls) &&
tail.tool_calls.length > 0
) {
const kept = this.log.entries.slice(0, -1);
this.log.compactInPlace([...kept]);
if (this.sessionName) {
try {
rewriteSession(this.sessionName, kept);
} catch {
/* disk issue shouldn't block the summary path */
}
}
}
yield* this.forceSummaryAfterIterLimit({ reason: "context-guard" });
return;
}
}
for (const call of repairedCalls) {
@@ -589,7 +879,52 @@ export class CacheFirstLoop {
toolName: name,
toolArgs: args,
};
const result = await this.tools.dispatch(name, args);
// PreToolUse hooks. A `block` decision (exit 2) skips dispatch
// and surfaces the hook's stderr as the tool result so the model
// sees a structured refusal instead of a silent omission. Non-
// block non-zero outcomes are warnings: the loop continues, the
// UI gets a yellow row.
const parsedArgs = safeParseToolArgs(args);
const preReport = await runHooks({
hooks: this.hooks,
payload: {
event: "PreToolUse",
cwd: this.hookCwd,
toolName: name,
toolArgs: parsedArgs,
},
});
for (const w of hookWarnings(preReport.outcomes, this._turn)) yield w;
let result: string;
if (preReport.blocked) {
const blocking = preReport.outcomes[preReport.outcomes.length - 1];
const reason = (
blocking?.stderr ||
blocking?.stdout ||
"blocked by PreToolUse hook"
).trim();
result = `[hook block] ${blocking?.hook.command ?? "<unknown>"}\n${reason}`;
} else {
result = await this.tools.dispatch(name, args, { signal });
// PostToolUse hooks — block is meaningless after the fact, so
// every non-pass outcome is a warning. Hooks here are the
// natural place for "after every edit, run the formatter."
const postReport = await runHooks({
hooks: this.hooks,
payload: {
event: "PostToolUse",
cwd: this.hookCwd,
toolName: name,
toolArgs: parsedArgs,
toolResult: result,
},
});
for (const w of hookWarnings(postReport.outcomes, this._turn)) yield w;
}
this.appendAndPersist({
role: "tool",
tool_call_id: call.id ?? "",
@@ -618,15 +953,37 @@ export class CacheFirstLoop {
opts: { reason: "budget" | "aborted" | "context-guard" } = { reason: "budget" },
): AsyncGenerator<LoopEvent> {
try {
// The summary call is non-streaming (reasoner, 30-60s typical).
// Without this status the user sees nothing happening after the
// yellow "budget reached" warning until the summary arrives.
yield {
turn: this._turn,
role: "status",
content: "summarizing what was gathered…",
};
const messages = this.buildMessages(null);
// Passing `tools: undefined` was supposed to force a text
// response, but R1 can still hallucinate tool-call markup
// (e.g. DSML `<|DSML|function_calls>…</|DSML|function_calls>`)
// in prose when it's been primed by prior tool use. An explicit
// user-role instruction plus post-hoc stripping of known
// hallucination shapes keeps the user from seeing raw markup.
messages.push({
role: "user",
content:
"I'm out of tool-call budget for this turn. Summarize in plain prose what you learned from the tool results above. Do NOT emit any tool calls, function-call markup, DSML invocations, or SEARCH/REPLACE edit blocks — they will be silently discarded. Just plain text.",
});
const resp = await this.client.chat({
model: this.model,
messages,
// no tools → model is forced to answer in text
signal: this._turnAbort.signal,
});
const rawContent = resp.content?.trim() ?? "";
const cleaned = stripHallucinatedToolMarkup(rawContent);
const summary =
resp.content?.trim() ||
"(model returned no text; try a narrower question or raise --max-tool-iters)";
cleaned ||
"(model emitted fake tool-call markup instead of a prose summary — try /retry with a narrower question, or /think to inspect R1's reasoning)";
const reasonPrefix = reasonPrefixFor(opts.reason, this.maxToolIters);
const annotated = `${reasonPrefix}\n\n${summary}`;
const summaryStats = this.stats.record(this._turn, this.model, resp.usage ?? new Usage());
@@ -668,6 +1025,53 @@ export class CacheFirstLoop {
}
}
/**
* R1 occasionally hallucinates tool-call markup as plain text when the
* real tool channel has been closed — typically our forced-summary
* path, where `tools: undefined` is supposed to force prose but isn't
* always respected. The markup isn't parsed by our tool-call path
* (the API response's structured `tool_calls` field is empty), so
* it's just noise in the user's view. Strip known envelope shapes.
*
* Exported so tests can exercise it against concrete R1 outputs.
*/
export function stripHallucinatedToolMarkup(s: string): string {
let out = s;
// DeepSeek's DSML envelope (both the full-width "|" character and
// the ASCII-only fallback we've seen — the full-width form is the
// one R1 emits in practice)
out = out.replace(/<|DSML|function_calls>[\s\S]*?<\/?|DSML|function_calls>/g, "");
out = out.replace(/<\|DSML\|function_calls>[\s\S]*?<\/?\|DSML\|function_calls>/g, "");
// Anthropic / generic XML-ish envelope
out = out.replace(/<function_calls>[\s\S]*?<\/function_calls>/g, "");
// Lone unpaired DSML opener left over after the closer was on a
// different line (seen when R1 truncates mid-call).
out = out.replace(/<|DSML|[\s\S]*$/g, "");
return out.trim();
}
/**
* Try to JSON-decode the model's tool-call arguments so PreToolUse /
* PostToolUse hooks get a structured object instead of a string.
* Falls back to the raw string when the model emits malformed JSON
* (the loop's own dispatch already tolerates that — keep parity).
*/
function safeParseToolArgs(raw: string): unknown {
try {
return JSON.parse(raw);
} catch {
return raw;
}
}
/** Format non-pass hook outcomes as `LoopEvent`s of role `warning`. */
function* hookWarnings(outcomes: HookOutcome[], turn: number): Generator<LoopEvent> {
for (const o of outcomes) {
if (o.decision === "pass") continue;
yield { turn, role: "warning", content: formatHookOutcomeMessage(o) };
}
}
function reasonPrefixFor(reason: "budget" | "aborted" | "context-guard", iterCap: number): string {
if (reason === "aborted") return "[aborted by user (Esc) — summarizing what I found so far]";
if (reason === "context-guard") {
@@ -697,7 +1101,13 @@ function summarizeBranch(chosen: BranchSample, samples: BranchSample[]): BranchS
* always small, (b) truncating user prompts would corrupt conversational
* intent in a way the user didn't author. Exported for tests.
*/
export function healLoadedMessages(
/**
* Shrink oversized tool results only — the original compact concern.
* Separated from `healLoadedMessages` so `/compact` (live, mid-session)
* doesn't accidentally strip structural tail that belongs in the
* current turn's state.
*/
export function shrinkOversizedToolResults(
messages: ChatMessage[],
maxChars: number,
): { messages: ChatMessage[]; healedCount: number; healedFrom: number } {
@@ -714,6 +1124,79 @@ export function healLoadedMessages(
return { messages: out, healedCount, healedFrom };
}
export function healLoadedMessages(
messages: ChatMessage[],
maxChars: number,
): { messages: ChatMessage[]; healedCount: number; healedFrom: number } {
// Pass 1: shrink oversized tool results (original heal purpose).
const shrunk = shrinkOversizedToolResults(messages, maxChars);
let healedCount = shrunk.healedCount;
// Pass 2: enforce tool_calls ↔ tool pairing across the full log.
//
// DeepSeek rejects two shapes at the API boundary:
// (a) assistant with tool_calls not followed by matching tool
// responses ("insufficient tool messages following tool_calls")
// (b) tool message without a preceding assistant.tool_calls with
// the matching tool_call_id ("must be a response to a preceding
// message with 'tool_calls'")
//
// Corrupted session files from earlier builds have hit both. Rebuild
// the message stream so only well-formed (assistant.tool_calls + all
// matching responses) groups survive. Plain user/assistant messages
// (no tool_calls) always pass through.
const out: ChatMessage[] = [];
const openCallIds = new Set<string>();
let droppedAssistantCalls = 0;
let droppedStrayTools = 0;
for (let i = 0; i < shrunk.messages.length; i++) {
const msg = shrunk.messages[i]!;
if (msg.role === "assistant" && Array.isArray(msg.tool_calls) && msg.tool_calls.length > 0) {
// Look ahead for tool responses matching every id in this
// assistant's tool_calls. If all present (in any order, but
// contiguous after this message), include the whole group.
const needed = new Set<string>();
for (const call of msg.tool_calls) {
if (call?.id) needed.add(call.id);
}
const candidates: ChatMessage[] = [];
let j = i + 1;
while (j < shrunk.messages.length && needed.size > 0) {
const nxt = shrunk.messages[j]!;
if (nxt.role !== "tool") break;
const id = nxt.tool_call_id ?? "";
if (!needed.has(id)) break;
needed.delete(id);
candidates.push(nxt);
j++;
}
if (needed.size === 0) {
// Every call has a response — emit the whole group.
out.push(msg);
for (const r of candidates) out.push(r);
i = j - 1; // for-loop ++ will advance past the last response
} else {
// Drop the assistant entry and anything that was speculatively
// its responses — they'd become stray tool messages.
droppedAssistantCalls += 1;
droppedStrayTools += candidates.length;
i = j - 1;
}
continue;
}
if (msg.role === "tool") {
// Any tool message that reaches here did NOT get consumed by
// the assistant-with-tool_calls branch above, so it's stray.
// Drop it — surfacing it would 400 the next API call.
droppedStrayTools += 1;
continue;
}
// Plain user/assistant/system message — pass through.
out.push(msg);
}
healedCount += droppedAssistantCalls + droppedStrayTools;
return { messages: out, healedCount, healedFrom: shrunk.healedFrom };
}
/**
* Annotate the `DeepSeek 400: … maximum context length …` error the API
* returns when a session's history has grown past 131,072 tokens. The
+178 -12
View File
@@ -8,15 +8,25 @@ import type { McpTransport } from "./stdio.js";
import {
type CallToolParams,
type CallToolResult,
type GetPromptParams,
type GetPromptResult,
type InitializeParams,
type InitializeResult,
type JsonRpcId,
type JsonRpcMessage,
type JsonRpcRequest,
type JsonRpcResponse,
type ListPromptsParams,
type ListPromptsResult,
type ListResourcesParams,
type ListResourcesResult,
type ListToolsResult,
MCP_PROTOCOL_VERSION,
type McpClientInfo,
type McpProgressHandler,
type ProgressNotificationParams,
type ReadResourceParams,
type ReadResourceResult,
isJsonRpcError,
} from "./types.js";
@@ -42,6 +52,16 @@ export class McpClient {
private readerStarted = false;
private initialized = false;
private _serverCapabilities: InitializeResult["capabilities"] = {};
private _serverInfo: InitializeResult["serverInfo"] = { name: "", version: "" };
private _protocolVersion = "";
private _instructions: string | undefined;
// Progress-token → handler for notifications/progress routing. Tokens
// are minted per call when the caller supplies an onProgress
// callback; cleared when the final response lands (or the pending
// request rejects). No leaks — the `try/finally` in callTool
// guarantees cleanup even on timeout.
private readonly progressHandlers = new Map<string | number, McpProgressHandler>();
private nextProgressToken = 1;
constructor(opts: McpClientOptions) {
this.transport = opts.transport;
@@ -54,6 +74,21 @@ export class McpClient {
return this._serverCapabilities;
}
/** Server's self-reported name + version, available after initialize(). */
get serverInfo(): InitializeResult["serverInfo"] {
return this._serverInfo;
}
/** Protocol version the server agreed to during the handshake. */
get protocolVersion(): string {
return this._protocolVersion;
}
/** Optional free-form instructions the server provides at handshake. */
get serverInstructions(): string | undefined {
return this._instructions;
}
/**
* Complete the initialize → initialized handshake. Must be called
* before any other method (otherwise compliant servers reject).
@@ -63,10 +98,18 @@ export class McpClient {
this.startReaderIfNeeded();
const result = await this.request<InitializeResult>("initialize", {
protocolVersion: MCP_PROTOCOL_VERSION,
capabilities: { tools: {} },
// Advertise every method the client can consume so servers know
// they can send listChanged notifications etc. Sub-feature flags
// (e.g. `resources.subscribe`) are omitted — we don't implement
// those yet and the empty object means "method-level support, no
// sub-features."
capabilities: { tools: {}, resources: {}, prompts: {} },
clientInfo: this.clientInfo,
} satisfies InitializeParams);
this._serverCapabilities = result.capabilities ?? {};
this._serverInfo = result.serverInfo ?? { name: "", version: "" };
this._protocolVersion = result.protocolVersion ?? "";
this._instructions = result.instructions;
// Per spec: client sends notifications/initialized after receiving the
// initialize response. Only then is the connection live for other
// methods.
@@ -84,13 +127,83 @@ export class McpClient {
return this.request<ListToolsResult>("tools/list", {});
}
/** Invoke a tool by name. Returns the raw MCP result (caller unwraps content). */
async callTool(name: string, args?: Record<string, unknown>): Promise<CallToolResult> {
/**
* Invoke a tool by name. When `onProgress` is supplied, attaches a
* fresh progress token so the server can send incremental updates
* via `notifications/progress`; they're routed to the callback until
* the final response arrives (or the request times out, in which
* case the handler is simply dropped — no extra notification).
*
* When `signal` is supplied, aborting it:
* 1) fires `notifications/cancelled` to the server (MCP 2024-11-05
* way of saying "forget this request, I no longer care"), and
* 2) rejects the pending promise immediately with an AbortError,
* so the caller doesn't have to wait for the subprocess to
* finish its in-flight file write or network request.
* The server MAY still emit a late response; we drop it in dispatch
* since the request id is gone from `pending`.
*/
async callTool(
name: string,
args?: Record<string, unknown>,
opts: { onProgress?: McpProgressHandler; signal?: AbortSignal } = {},
): Promise<CallToolResult> {
this.assertInitialized();
return this.request<CallToolResult>("tools/call", {
const params: CallToolParams = { name, arguments: args ?? {} };
let token: number | undefined;
if (opts.onProgress) {
token = this.nextProgressToken++;
this.progressHandlers.set(token, opts.onProgress);
params._meta = { progressToken: token };
}
try {
return await this.request<CallToolResult>("tools/call", params, opts.signal);
} finally {
if (token !== undefined) this.progressHandlers.delete(token);
}
}
/**
* List resources the server exposes. Supports a pagination cursor;
* callers interested in the full set should loop on `nextCursor`.
* Servers that don't support resources respond with method-not-found
* (−32601) — we surface that as a thrown Error so callers can gate
* on the `serverCapabilities.resources` field first.
*/
async listResources(cursor?: string): Promise<ListResourcesResult> {
this.assertInitialized();
return this.request<ListResourcesResult>("resources/list", {
...(cursor ? { cursor } : {}),
} satisfies ListResourcesParams);
}
/** Read the contents of a resource by URI. */
async readResource(uri: string): Promise<ReadResourceResult> {
this.assertInitialized();
return this.request<ReadResourceResult>("resources/read", {
uri,
} satisfies ReadResourceParams);
}
/** List prompt templates the server exposes. */
async listPrompts(cursor?: string): Promise<ListPromptsResult> {
this.assertInitialized();
return this.request<ListPromptsResult>("prompts/list", {
...(cursor ? { cursor } : {}),
} satisfies ListPromptsParams);
}
/**
* Fetch a rendered prompt by name. `args` supplies values for any
* required template arguments; the server validates. Returns messages
* ready to prepend to the model's input.
*/
async getPrompt(name: string, args?: Record<string, string>): Promise<GetPromptResult> {
this.assertInitialized();
return this.request<GetPromptResult>("prompts/get", {
name,
arguments: args ?? {},
} satisfies CallToolParams);
...(args ? { arguments: args } : {}),
} satisfies GetPromptParams);
}
/** Close the transport and reject any outstanding requests. */
@@ -109,12 +222,14 @@ export class McpClient {
if (!this.initialized) throw new Error("MCP client not initialized — call initialize() first");
}
private async request<R>(method: string, params: unknown): Promise<R> {
private async request<R>(method: string, params: unknown, signal?: AbortSignal): Promise<R> {
const id = this.nextId++;
const frame: JsonRpcRequest = { jsonrpc: "2.0", id, method, params };
let abortHandler: (() => void) | null = null;
const promise = new Promise<R>((resolve, reject) => {
const timeout = setTimeout(() => {
this.pending.delete(id);
if (abortHandler && signal) signal.removeEventListener("abort", abortHandler);
reject(
new Error(`MCP request ${method} (id=${id}) timed out after ${this.requestTimeoutMs}ms`),
);
@@ -124,9 +239,49 @@ export class McpClient {
reject,
timeout,
});
// Wire up cancellation: when signal fires, send an MCP cancellation
// notification to the server (so it can stop whatever it was doing)
// and reject the caller immediately — no need to wait for the
// subprocess to finish its in-flight work. Late responses from the
// server are dropped by `dispatch` because the id is gone from
// `pending`.
if (signal) {
if (signal.aborted) {
this.pending.delete(id);
clearTimeout(timeout);
reject(new Error(`MCP request ${method} (id=${id}) aborted before send`));
return;
}
abortHandler = () => {
this.pending.delete(id);
clearTimeout(timeout);
void this.transport
.send({
jsonrpc: "2.0",
method: "notifications/cancelled",
params: { requestId: id, reason: "aborted by user" },
})
.catch(() => {
// Transport may already be closing — swallow; we still
// reject the caller below so they unblock.
});
reject(new Error(`MCP request ${method} (id=${id}) aborted by user`));
};
signal.addEventListener("abort", abortHandler, { once: true });
}
});
await this.transport.send(frame);
return promise;
try {
await this.transport.send(frame);
} catch (err) {
this.pending.delete(id);
if (abortHandler && signal) signal.removeEventListener("abort", abortHandler);
throw err;
}
try {
return await promise;
} finally {
if (abortHandler && signal) signal.removeEventListener("abort", abortHandler);
}
}
private startReaderIfNeeded(): void {
@@ -152,9 +307,20 @@ export class McpClient {
}
private dispatch(msg: JsonRpcMessage): void {
// We only care about responses (have an `id`) for now. Server-initiated
// notifications are dropped until we support resources/prompts.
if (!("id" in msg) || msg.id === null || msg.id === undefined) return;
// Notifications (no `id`): route by method. Progress notifications
// go to the per-call handler if one was registered; everything
// else is dropped silently (we don't yet handle tools/list_changed
// or resources/list_changed).
if (!("id" in msg) || msg.id === null || msg.id === undefined) {
if ("method" in msg && msg.method === "notifications/progress") {
const p = msg.params as ProgressNotificationParams | undefined;
if (!p || p.progressToken === undefined) return;
const handler = this.progressHandlers.get(p.progressToken);
if (!handler) return; // late notification after the call resolved
handler({ progress: p.progress, total: p.total, message: p.message });
}
return;
}
if (!("result" in msg) && !("error" in msg)) return; // it's a request from server
const pending = this.pending.get(msg.id);
if (!pending) return; // late response after timeout; drop
+71
View File
@@ -0,0 +1,71 @@
/**
* Gather a full inspection report from an initialized MCP client:
* server info, capabilities, tools, resources, prompts. Methods the
* server doesn't support come back as `{ supported: false }` instead
* of throwing, so a CLI or UI can render a consistent "what this
* server exposes" summary even against minimal implementations.
*
* Pure with respect to I/O beyond the passed-in client — the CLI
* layer owns argument parsing, connection setup, and printing.
*/
import type { McpClient } from "./client.js";
import type { McpPrompt, McpResource, McpTool } from "./types.js";
export interface InspectionReport {
protocolVersion: string;
serverInfo: { name: string; version: string };
capabilities: Record<string, unknown>;
instructions?: string;
tools: SectionResult<McpTool>;
resources: SectionResult<McpResource>;
prompts: SectionResult<McpPrompt>;
}
export type SectionResult<T> =
| { supported: true; items: T[] }
| { supported: false; reason: string };
/**
* Run an inspection against a **already-initialized** client. Caller
* is responsible for `initialize()` before this and `close()` after.
* We keep this pure so unit tests can feed in a FakeMcpTransport and
* verify the aggregate shape without spinning up a real process.
*/
export async function inspectMcpServer(client: McpClient): Promise<InspectionReport> {
// We always *try* the three listings so the client learns whether a
// server without explicit capability flags still serves them —
// some servers omit capabilities but still respond to the methods.
const tools = await trySection<McpTool>(() => client.listTools().then((r) => r.tools));
const resources = await trySection<McpResource>(() =>
client.listResources().then((r) => r.resources),
);
const prompts = await trySection<McpPrompt>(() => client.listPrompts().then((r) => r.prompts));
return {
protocolVersion: client.protocolVersion || "(unknown)",
serverInfo: client.serverInfo,
capabilities: client.serverCapabilities ?? {},
instructions: client.serverInstructions,
tools,
resources,
prompts,
};
}
async function trySection<T>(load: () => Promise<T[]>): Promise<SectionResult<T>> {
try {
const items = await load();
return { supported: true, items };
} catch (err) {
const msg = (err as Error).message ?? String(err);
// -32601 is JSON-RPC "method not found" — the canonical response
// from a server that doesn't implement this family. Treat it as
// "not supported" rather than a hard error, so the CLI can render
// a clean summary instead of aborting on the first missing method.
if (/-32601/.test(msg) || /method not found/i.test(msg)) {
return { supported: false, reason: "method not found (-32601)" };
}
return { supported: false, reason: msg };
}
}
+29 -2
View File
@@ -36,6 +36,19 @@ export interface BridgeOptions {
* legitimately want bigger payloads can raise it explicitly.
*/
maxResultChars?: number;
/**
* Callback fired for every `notifications/progress` frame the server
* emits during any bridged tool call. Includes the registered
* (prefix-applied) tool name so a multi-server UI can attribute
* progress correctly. Absent → no `_meta.progressToken` is sent and
* the server won't emit progress for these calls.
*/
onProgress?: (info: {
toolName: string;
progress: number;
total?: number;
message?: string;
}) => void;
}
/**
@@ -80,8 +93,22 @@ export async function bridgeMcpTools(
name: registeredName,
description: mcpTool.description ?? "",
parameters: mcpTool.inputSchema as JSONSchema,
fn: async (args: Record<string, unknown>) => {
const toolResult = await client.callTool(mcpTool.name, args);
fn: async (args: Record<string, unknown>, ctx) => {
const toolResult = await client.callTool(mcpTool.name, args, {
// Forward server-side progress frames to the bridge caller,
// tagged with the registered name so multi-server UIs can
// disambiguate. No-op when `onProgress` isn't configured —
// the client then also omits the _meta.progressToken and
// the server won't emit progress.
onProgress: opts.onProgress
? (info) => opts.onProgress!({ toolName: registeredName, ...info })
: undefined,
// Thread the tool-dispatch AbortSignal all the way down to
// the MCP request so Esc truly cancels in flight — the
// client will emit notifications/cancelled AND reject the
// pending promise immediately, no "wait for subprocess".
signal: ctx?.signal,
});
return flattenMcpResult(toolResult, { maxChars: maxResultChars });
},
});
+144 -3
View File
@@ -10,8 +10,9 @@
* insulated as long as we keep up with the spec itself.
*
* Spec reference: https://spec.modelcontextprotocol.io/ (2024-11-05 draft
* at time of writing). Only the subset Reasonix consumes is modeled here —
* tools list/call + init handshake. Resources and prompts are deferred.
* at time of writing). Reasonix models the subset it consumes: tools
* list/call, resources list/read, prompts list/get, plus the init
* handshake. Sampling and progress notifications remain deferred.
*
* Transport note: the wire format for stdio MCP is **newline-delimited
* JSON** (NDJSON), not the LSP-style Content-Length header framing that
@@ -66,7 +67,11 @@ export interface McpClientInfo {
export interface McpClientCapabilities {
/** Empty object advertises support without any optional sub-features. */
tools?: Record<string, never>;
// resources / prompts / sampling would go here — deferred.
/** Advertised when the client can consume `resources/list` + `resources/read`. */
resources?: Record<string, never>;
/** Advertised when the client can consume `prompts/list` + `prompts/get`. */
prompts?: Record<string, never>;
// sampling would go here — deferred.
}
export interface InitializeParams {
@@ -111,8 +116,38 @@ export interface ListToolsResult {
export interface CallToolParams {
name: string;
arguments?: Record<string, unknown>;
/**
* MCP's `_meta` envelope carries out-of-band protocol metadata.
* Setting `progressToken` here tells the server "send me progress
* notifications back using this token"; the server must then emit
* `notifications/progress` frames until the response arrives.
*/
_meta?: { progressToken?: string | number };
}
/**
* Server → client notification emitted during a long-running request
* that the client subscribed to via `_meta.progressToken`. `progress`
* and `total` are typically matched units (files scanned, bytes
* processed, etc.); `total` may be missing when the server can't
* estimate the upper bound up front.
*/
export interface ProgressNotificationParams {
progressToken: string | number;
progress: number;
total?: number;
message?: string;
}
/** Values a `ProgressHandler` receives — `progressToken` is already matched away. */
export interface McpProgressInfo {
progress: number;
total?: number;
message?: string;
}
export type McpProgressHandler = (info: McpProgressInfo) => void;
export interface McpContentBlockText {
type: "text";
text: string;
@@ -133,6 +168,112 @@ export interface CallToolResult {
isError?: boolean;
}
// ---------- MCP resources ----------
/**
* A resource the server can expose — think "file the model can read."
* The URI is opaque to the client: servers may use `file://`, custom
* schemes, or bare strings. Reasonix doesn't interpret them.
*/
export interface McpResource {
uri: string;
name: string;
description?: string;
/** Hint for the content type (e.g. "text/markdown"). Purely informational. */
mimeType?: string;
}
export interface ListResourcesParams {
/** Pagination cursor from a previous listResources response. */
cursor?: string;
}
export interface ListResourcesResult {
resources: McpResource[];
nextCursor?: string;
}
export interface ReadResourceParams {
uri: string;
}
/**
* One resource can return multiple content blobs (e.g. the file + a
* side-car). `text` is the common case for UTF-8 content; `blob` is
* base64-encoded bytes for binary content. Servers populate exactly
* one of the two for each entry.
*/
export interface McpResourceContentsText {
uri: string;
mimeType?: string;
text: string;
}
export interface McpResourceContentsBlob {
uri: string;
mimeType?: string;
blob: string;
}
export type McpResourceContents = McpResourceContentsText | McpResourceContentsBlob;
export interface ReadResourceResult {
contents: McpResourceContents[];
}
// ---------- MCP prompts ----------
/**
* A parameterizable prompt template the server exposes. Clients fetch
* it with `prompts/get` and pass the result to the model as-is.
*/
export interface McpPromptArgument {
name: string;
description?: string;
required?: boolean;
}
export interface McpPrompt {
name: string;
description?: string;
arguments?: McpPromptArgument[];
}
export interface ListPromptsParams {
cursor?: string;
}
export interface ListPromptsResult {
prompts: McpPrompt[];
nextCursor?: string;
}
export interface GetPromptParams {
name: string;
arguments?: Record<string, string>;
}
/**
* MCP prompt messages are modeled after chat completions: role + content.
* Content can be a text block OR (per the spec) a resource/image block;
* Reasonix cares about text in v1, but surfaces the raw array so callers
* can render other kinds if they need to.
*/
export interface McpPromptMessage {
role: "user" | "assistant";
content: McpContentBlock | McpPromptResourceBlock;
}
export interface McpPromptResourceBlock {
type: "resource";
resource: McpResourceContents;
}
export interface GetPromptResult {
description?: string;
messages: McpPromptMessage[];
}
// ---------- convenience ----------
/** Current MCP protocol version Reasonix is coded against. */
+99
View File
@@ -0,0 +1,99 @@
/**
* Project memory — a user-authored `REASONIX.md` in the project root
* that gets pinned into the immutable-prefix system prompt.
*
* Design notes:
*
* - The file lands in `ImmutablePrefix.system`, so the whole memory
* block is hashed into the cache prefix fingerprint. Editing the
* file invalidates the prefix; unchanged memory across sessions
* keeps the DeepSeek prefix cache warm. That matches Pillar 1 —
* memory is a deliberate, stable prefix, not per-turn drift.
* - Only one source: the working-root `REASONIX.md`. No parent walk,
* no `~/.reasonix/REASONIX.md`, no CLAUDE.md fallback. User-global
* memory can come later; for v1 one file == one mental model.
* - Truncated at 8 000 chars (≈ 2k tokens). `.gitignore` gets 2 000
* because it's a constraint dump; memory gets more headroom because
* it's deliberate instructions.
* - Opt-out via `REASONIX_MEMORY=off|false|0`. No CLI flag — memory
* is a file, `rm REASONIX.md` is the other opt-out.
*/
import { existsSync, readFileSync } from "node:fs";
import { join } from "node:path";
export const PROJECT_MEMORY_FILE = "REASONIX.md";
export const PROJECT_MEMORY_MAX_CHARS = 8000;
export interface ProjectMemory {
/** Absolute path the memory was read from. */
path: string;
/** Post-truncation content (may include a "… (truncated N chars)" marker). */
content: string;
/** Original byte length before truncation. */
originalChars: number;
/** True iff `originalChars > PROJECT_MEMORY_MAX_CHARS`. */
truncated: boolean;
}
/**
* Read `REASONIX.md` from `rootDir`. Returns `null` when the file is
* missing, unreadable, or empty (whitespace-only counts as empty — an
* empty memory file shouldn't perturb the cache prefix).
*/
export function readProjectMemory(rootDir: string): ProjectMemory | null {
const path = join(rootDir, PROJECT_MEMORY_FILE);
if (!existsSync(path)) return null;
let raw: string;
try {
raw = readFileSync(path, "utf8");
} catch {
return null;
}
const trimmed = raw.trim();
if (!trimmed) return null;
const originalChars = trimmed.length;
const truncated = originalChars > PROJECT_MEMORY_MAX_CHARS;
const content = truncated
? `${trimmed.slice(0, PROJECT_MEMORY_MAX_CHARS)}\n… (truncated ${
originalChars - PROJECT_MEMORY_MAX_CHARS
} chars)`
: trimmed;
return { path, content, originalChars, truncated };
}
/**
* Resolve whether project memory should be read. Default: on.
* `REASONIX_MEMORY=off|false|0` turns it off (CI, reproducing issues,
* intentional offline runs).
*/
export function memoryEnabled(): boolean {
const env = process.env.REASONIX_MEMORY;
if (env === "off" || env === "false" || env === "0") return false;
return true;
}
/**
* Return `basePrompt` with the project's `REASONIX.md` appended as a
* "Project memory" section. No-op when the file is absent, empty, or
* memory is disabled via env.
*
* The appended block is deterministic — identical input ⇒ identical
* output — so every session that opens against the same memory file
* gets the same prefix hash.
*/
export function applyProjectMemory(basePrompt: string, rootDir: string): string {
if (!memoryEnabled()) return basePrompt;
const mem = readProjectMemory(rootDir);
if (!mem) return basePrompt;
return `${basePrompt}
# Project memory (REASONIX.md)
The user pinned these notes about this project — treat them as authoritative context for every turn:
\`\`\`
${mem.content}
\`\`\`
`;
}
+19 -1
View File
@@ -46,9 +46,21 @@ export class ToolCallRepair {
this.storm = new StormBreaker(opts.stormWindow ?? 6, opts.stormThreshold ?? 3);
}
/**
* Drop the StormBreaker's sliding window of recent (name, args)
* signatures. Called at the start of every user turn — a fresh user
* message is a new intent, so carrying old repetition state into it
* would turn a valid "try again with different input" flow into a
* false-positive block.
*/
resetStorm(): void {
this.storm.reset();
}
process(
declaredCalls: ToolCall[],
reasoningContent: string | null,
content: string | null = null,
): { calls: ToolCall[]; report: RepairReport } {
const report: RepairReport = {
scavenged: 0,
@@ -58,7 +70,13 @@ export class ToolCallRepair {
};
// 1. Scavenge — only add calls whose (name,args) signature is novel.
const scavenged = scavengeToolCalls(reasoningContent, {
// Scan both channels: reasoning (where R1 leaks JSON calls into
// <think>) AND content (where it emits DSML markup in regular
// turns). Joined with a newline so the scanners see the blobs as
// independent bodies. Dedup below keeps us from inflating if the
// same call shows up in both — first seen wins.
const combined = [reasoningContent ?? "", content ?? ""].filter(Boolean).join("\n");
const scavenged = scavengeToolCalls(combined || null, {
allowedNames: this.opts.allowedToolNames,
maxCalls: this.opts.maxScavenge ?? 4,
});
+101 -1
View File
@@ -30,7 +30,28 @@ export function scavengeToolCalls(
const notes: string[] = [];
const out: ToolCall[] = [];
for (const candidate of iterateJsonObjects(reasoningContent)) {
// Pattern A: DSML invoke blocks. R1 sometimes emits tool calls as
// its chat-template markup in the content channel instead of the
// proper `tool_calls` field. 0.4.3 stripped these from display;
// here we actually turn them back into proper ToolCalls so the
// model's intent isn't lost.
for (const invoke of iterateDsmlInvokes(reasoningContent)) {
if (out.length >= max) break;
if (!opts.allowedNames.has(invoke.name)) continue;
out.push({
function: {
name: invoke.name,
arguments: JSON.stringify(invoke.args),
},
});
notes.push(`scavenged DSML call: ${invoke.name}`);
}
// Pattern B: raw JSON objects (the original three shapes). Strip
// any DSML blocks we already processed so parameter JSON buried
// inside them doesn't get re-scavenged as a standalone call.
const nonDsml = stripDsmlBlocks(reasoningContent);
for (const candidate of iterateJsonObjects(nonDsml)) {
if (out.length >= max) break;
const call = coerceToToolCall(candidate, opts.allowedNames);
if (call) {
@@ -41,6 +62,85 @@ export function scavengeToolCalls(
return { calls: out, notes };
}
interface DsmlInvoke {
name: string;
args: Record<string, unknown>;
}
/**
* Yield DeepSeek DSML invoke blocks scavenged from text. R1's chat
* template uses these when the server-side tool-call serializer
* misfires — we see them verbatim in the content channel:
*
* <|DSML|function_calls>
* <|DSML|invoke name="filesystem_edit_file">
* <|DSML|parameter name="path" string="true">F:/x.html</|DSML|parameter>
* <|DSML|parameter name="edits" string="false">[…]</|DSML|parameter>
* </|DSML|invoke>
* </|DSML|function_calls>
*
* The wrapper class (| U+FF5C vs ASCII |) varies by model build, so
* we accept both. `string="true"` means the parameter value is a
* literal string; `string="false"` means it's JSON.
*/
/**
* Remove DSML invoke/function_calls blocks from text so the raw-JSON
* scanner below doesn't see parameter payloads as standalone calls.
* Mirrors the strip pass in `stripHallucinatedToolMarkup` but scoped
* to scavenge (we also want the `function_calls` wrapper gone —
* nothing useful to scavenge there).
*/
function stripDsmlBlocks(text: string): string {
let out = text;
out = out.replace(/<[||]DSML[||]function_calls>[\s\S]*?<\/?[||]DSML[||]function_calls>/g, "");
out = out.replace(/<[||]DSML[||]invoke\s+[^>]*>[\s\S]*?<\/[||]DSML[||]invoke>/g, "");
return out;
}
function* iterateDsmlInvokes(text: string): Generator<DsmlInvoke> {
// `|` (U+FF5C) in practice; `|` (ASCII) as a fallback seen in a
// minority of builds. `[||]` inside the regex covers both.
const INVOKE_RE = /<[||]DSML[||]invoke\s+name="([^"]+)">([\s\S]*?)<\/[||]DSML[||]invoke>/g;
for (const match of text.matchAll(INVOKE_RE)) {
const name = match[1];
const body = match[2];
if (!name || body === undefined) continue;
yield { name, args: parseDsmlParameters(body) };
}
}
/**
* Parse the parameter children of a DSML invoke body into a plain
* object. We tolerate:
* - `string="true"` → literal text; whitespace trimmed at the edges.
* - `string="false"` → JSON-parsed; falls back to literal text if the
* payload turns out to be malformed (better to hand a string
* through than lose the parameter entirely).
* - no `string="…"` attribute → treat as literal text (older/shorter
* DSML shapes we haven't formally seen but want to handle).
*/
function parseDsmlParameters(body: string): Record<string, unknown> {
const PARAM_RE =
/<[||]DSML[||]parameter\s+name="([^"]+)"(?:\s+string="(true|false)")?\s*>([\s\S]*?)<\/[||]DSML[||]parameter>/g;
const args: Record<string, unknown> = {};
for (const m of body.matchAll(PARAM_RE)) {
const key = m[1];
const stringFlag = m[2];
const raw = (m[3] ?? "").trim();
if (!key) continue;
if (stringFlag === "false") {
try {
args[key] = JSON.parse(raw);
continue;
} catch {
// Fall through — keep as literal so the information isn't lost.
}
}
args[key] = raw;
}
return args;
}
/** Yield every top-level JSON object substring in `text`. */
function* iterateJsonObjects(text: string): Generator<string> {
for (let i = 0; i < text.length; i++) {
+12 -1
View File
@@ -10,7 +10,14 @@
*/
import { Usage } from "./client.js";
import { type SessionSummary, type TurnStats, claudeEquivalentCost, costUsd } from "./telemetry.js";
import {
type SessionSummary,
type TurnStats,
claudeEquivalentCost,
costUsd,
inputCostUsd,
outputCostUsd,
} from "./telemetry.js";
import { type ReadTranscriptResult, type TranscriptRecord, readTranscript } from "./transcript.js";
/**
@@ -142,6 +149,8 @@ export function computeReplayStats(records: TranscriptRecord[]): ReplayStats {
function summarizeTurns(turns: TurnStats[]): SessionSummary {
const totalCost = turns.reduce((s, t) => s + t.cost, 0);
const totalInput = turns.reduce((s, t) => s + inputCostUsd(t.model, t.usage), 0);
const totalOutput = turns.reduce((s, t) => s + outputCostUsd(t.model, t.usage), 0);
const totalClaude = turns.reduce((s, t) => s + claudeEquivalentCost(t.usage), 0);
let hit = 0;
let miss = 0;
@@ -155,6 +164,8 @@ function summarizeTurns(turns: TurnStats[]): SessionSummary {
return {
turns: turns.length,
totalCostUsd: round(totalCost, 6),
totalInputCostUsd: round(totalInput, 6),
totalOutputCostUsd: round(totalOutput, 6),
claudeEquivalentUsd: round(totalClaude, 6),
savingsVsClaudePct: round(savingsVsClaude * 100, 2),
cacheHitRatio: round(cacheHitRatio, 4),
+254
View File
@@ -0,0 +1,254 @@
/**
* Skills — user-defined prompt packs pinned (by name) into the
* immutable prefix and loaded (by body) on demand.
*
* Two scopes mirror the user-memory layout:
* - `project` → `<projectRoot>/.reasonix/skills/` (this repo only)
* - `global` → `~/.reasonix/skills/` (every session)
*
* Project scope wins on a name collision. Deliberately NOT tied to
* any specific client's directory convention (`.claude/`, `.glm/`,
* etc.) — Reasonix is model-agnostic at the conversation layer, so
* coupling the skill filesystem to one vendor would break any user
* running a different backend.
*
* Accepted file layouts (both emit the same `Skill`):
* - `{dir}/<name>/SKILL.md` (preferred — lets a skill bundle
* additional assets alongside)
* - `{dir}/<name>.md` (flat, one-file shorthand)
*
* Frontmatter keys we read:
* - `name` — optional, defaults to the file / dir name
* - `description` — one-line index description (REQUIRED for listing)
* - `allowed-tools` — parsed but UNUSED in v1 (see tools/skills.ts)
*
* Cache-First contract (Pillar 1):
* - The PREFIX sees only names + descriptions (one line each).
* - Bodies enter the APPEND-ONLY LOG lazily, via `run_skill` or
* `/skill <name>` — never the prefix. That keeps the prefix hash
* stable across skill additions to the body store.
*/
import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
import { homedir } from "node:os";
import { join, resolve } from "node:path";
export const SKILLS_DIRNAME = "skills";
export const SKILL_FILE = "SKILL.md";
/** Cap on the pinned skills-index block, mirrors memory-index cap. */
export const SKILLS_INDEX_MAX_CHARS = 4000;
/** Skill identifier shape — alnum + `_` + `-` + interior `.`, 1-64 chars. */
const VALID_SKILL_NAME = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/;
export type SkillScope = "project" | "global";
export interface Skill {
/** Canonical name — sanitized, matches the directory / filename stem. */
name: string;
/** One-line description shown in the pinned index. */
description: string;
/** Full markdown body (post-frontmatter). Loaded on demand. */
body: string;
/** Which scope this skill was loaded from. */
scope: SkillScope;
/** Absolute path to the SKILL.md (or {name}.md) file. */
path: string;
/** Raw `allowed-tools` field from frontmatter, if any. Unused in v1. */
allowedTools?: string;
}
export interface SkillStoreOptions {
/** Override `$HOME` — tests point this at a tmpdir. */
homeDir?: string;
/**
* Absolute project root. Required to surface project-scope skills;
* omit (e.g. in `reasonix chat` without `code`) and the store only
* reads the global scope.
*/
projectRoot?: string;
}
/**
* Parse a `---` frontmatter block. Same minimal shape as user-memory:
* `key: value` lines, no quoting, no nesting. Returns `{}` data and the
* full input as body when no frontmatter fence is present — so hand-
* written files without frontmatter still surface (with empty desc).
*/
function parseFrontmatter(raw: string): { data: Record<string, string>; body: string } {
const lines = raw.split(/\r?\n/);
if (lines[0] !== "---") return { data: {}, body: raw };
const end = lines.indexOf("---", 1);
if (end < 0) return { data: {}, body: raw };
const data: Record<string, string> = {};
for (let i = 1; i < end; i++) {
const line = lines[i];
if (!line) continue;
const m = line.match(/^([a-zA-Z_][a-zA-Z0-9_-]*):\s*(.*)$/);
if (m?.[1]) data[m[1]] = (m[2] ?? "").trim();
}
return {
data,
body: lines
.slice(end + 1)
.join("\n")
.replace(/^\n+/, ""),
};
}
function isValidSkillName(name: string): boolean {
return VALID_SKILL_NAME.test(name);
}
export class SkillStore {
private readonly homeDir: string;
private readonly projectRoot: string | undefined;
constructor(opts: SkillStoreOptions = {}) {
this.homeDir = opts.homeDir ?? homedir();
this.projectRoot = opts.projectRoot ? resolve(opts.projectRoot) : undefined;
}
/** True iff this store was configured with a project root. */
hasProjectScope(): boolean {
return this.projectRoot !== undefined;
}
/**
* Root directories scanned, in priority order. Project scope first
* so a per-repo skill overrides a global one with the same name —
* users expect the local copy to win when both exist.
*/
roots(): Array<{ dir: string; scope: SkillScope }> {
const out: Array<{ dir: string; scope: SkillScope }> = [];
if (this.projectRoot) {
out.push({
dir: join(this.projectRoot, ".reasonix", SKILLS_DIRNAME),
scope: "project",
});
}
out.push({ dir: join(this.homeDir, ".reasonix", SKILLS_DIRNAME), scope: "global" });
return out;
}
/**
* List every skill visible to this store. On name collisions the
* higher-priority root (project over global) wins. Sorted by name
* for stable prefix hashing.
*/
list(): Skill[] {
const byName = new Map<string, Skill>();
for (const { dir, scope } of this.roots()) {
if (!existsSync(dir)) continue;
let entries: import("node:fs").Dirent[];
try {
entries = readdirSync(dir, { withFileTypes: true });
} catch {
continue;
}
for (const entry of entries) {
const skill = this.readEntry(dir, scope, entry);
if (!skill) continue;
if (!byName.has(skill.name)) byName.set(skill.name, skill);
}
}
return [...byName.values()].sort((a, b) => a.name.localeCompare(b.name));
}
/** Resolve one skill by name. Returns `null` if not found or malformed. */
read(name: string): Skill | null {
if (!isValidSkillName(name)) return null;
for (const { dir, scope } of this.roots()) {
if (!existsSync(dir)) continue;
const dirCandidate = join(dir, name, SKILL_FILE);
if (existsSync(dirCandidate) && statSync(dirCandidate).isFile()) {
return this.parse(dirCandidate, name, scope);
}
const flatCandidate = join(dir, `${name}.md`);
if (existsSync(flatCandidate) && statSync(flatCandidate).isFile()) {
return this.parse(flatCandidate, name, scope);
}
}
return null;
}
private readEntry(dir: string, scope: SkillScope, entry: import("node:fs").Dirent): Skill | null {
if (entry.isDirectory()) {
if (!isValidSkillName(entry.name)) return null;
const file = join(dir, entry.name, SKILL_FILE);
if (!existsSync(file)) return null;
return this.parse(file, entry.name, scope);
}
if (entry.isFile() && entry.name.endsWith(".md")) {
const stem = entry.name.slice(0, -3);
if (!isValidSkillName(stem)) return null;
return this.parse(join(dir, entry.name), stem, scope);
}
return null;
}
private parse(path: string, stem: string, scope: SkillScope): Skill | null {
let raw: string;
try {
raw = readFileSync(path, "utf8");
} catch {
return null;
}
const { data, body } = parseFrontmatter(raw);
const name = data.name && isValidSkillName(data.name) ? data.name : stem;
return {
name,
description: (data.description ?? "").trim(),
body: body.trim(),
scope,
path,
allowedTools: data["allowed-tools"],
};
}
}
/**
* Build a single index line for one skill. Shape mirrors memory's
* `indexLine` — a bullet suitable for a markdown fenced block in the
* system prompt. Description is truncated to keep the full line under
* ~150 chars.
*/
function skillIndexLine(s: Pick<Skill, "name" | "description">): string {
const safeDesc = s.description.replace(/\n/g, " ").trim();
const max = 130 - s.name.length;
const clipped = safeDesc.length > max ? `${safeDesc.slice(0, Math.max(1, max - 1))}…` : safeDesc;
return clipped ? `- ${s.name} — ${clipped}` : `- ${s.name}`;
}
/**
* Append a `# Skills` block to `basePrompt` listing every discovered
* skill (name + description only). Bodies are NOT inlined — that's the
* whole point: the prefix stays short and cacheable; full content loads
* on demand via `run_skill` or `/skill <name>`.
*
* Emits nothing when no skills are discovered — keeps the prefix hash
* stable for users who don't use skills at all.
*/
export function applySkillsIndex(basePrompt: string, opts: SkillStoreOptions = {}): string {
const store = new SkillStore(opts);
const skills = store.list().filter((s) => s.description);
if (skills.length === 0) return basePrompt;
const lines = skills.map(skillIndexLine);
const joined = lines.join("\n");
const truncated =
joined.length > SKILLS_INDEX_MAX_CHARS
? `${joined.slice(0, SKILLS_INDEX_MAX_CHARS)}\n… (truncated ${
joined.length - SKILLS_INDEX_MAX_CHARS
} chars)`
: joined;
return [
basePrompt,
"",
"# Skills — user-defined prompt packs",
"",
'One-liner index. Each skill is a self-contained instruction block (plus optional tool hints) the user or an earlier session saved. To load the full body, call `run_skill({ name: "<skill-name>" })` — the body is NOT in this prompt, only the name and description are. The user can also invoke a skill directly as `/skill <name>`.',
"",
"```",
truncated,
"```",
].join("\n");
}
+38
View File
@@ -37,6 +37,24 @@ export function costUsd(model: string, usage: Usage): number {
);
}
/** Input-side cost only (prompt, cache hit + miss). Used for the panel breakdown. */
export function inputCostUsd(model: string, usage: Usage): number {
const p = DEEPSEEK_PRICING[model];
if (!p) return 0;
return (
(usage.promptCacheHitTokens * p.inputCacheHit +
usage.promptCacheMissTokens * p.inputCacheMiss) /
1_000_000
);
}
/** Output-side cost only (completion tokens). Used for the panel breakdown. */
export function outputCostUsd(model: string, usage: Usage): number {
const p = DEEPSEEK_PRICING[model];
if (!p) return 0;
return (usage.completionTokens * p.output) / 1_000_000;
}
export function claudeEquivalentCost(usage: Usage): number {
return (
(usage.promptTokens * CLAUDE_SONNET_PRICING.input +
@@ -56,7 +74,17 @@ export interface TurnStats {
export interface SessionSummary {
turns: number;
totalCostUsd: number;
/**
* Input-side (prompt) cost aggregated across the session. Split
* from totalCostUsd so the panel can render "cost $X (in $Y · out
* $Z)" — users asked for visibility into where the spend lands.
*/
totalInputCostUsd: number;
/** Output-side (completion) cost aggregated across the session. */
totalOutputCostUsd: number;
/** @deprecated Claude reference; kept for benchmarks + replay compat, no longer surfaced in the TUI. */
claudeEquivalentUsd: number;
/** @deprecated. Same as claudeEquivalentUsd — synthetic ratio, not a real measurement. */
savingsVsClaudePct: number;
cacheHitRatio: number;
/**
@@ -97,6 +125,14 @@ export class SessionStats {
return c > 0 ? 1 - this.totalCost / c : 0;
}
get totalInputCost(): number {
return this.turns.reduce((sum, t) => sum + inputCostUsd(t.model, t.usage), 0);
}
get totalOutputCost(): number {
return this.turns.reduce((sum, t) => sum + outputCostUsd(t.model, t.usage), 0);
}
get aggregateCacheHitRatio(): number {
let hit = 0;
let miss = 0;
@@ -113,6 +149,8 @@ export class SessionStats {
return {
turns: this.turns.length,
totalCostUsd: round(this.totalCost, 6),
totalInputCostUsd: round(this.totalInputCost, 6),
totalOutputCostUsd: round(this.totalOutputCost, 6),
claudeEquivalentUsd: round(this.totalClaudeEquivalent, 6),
savingsVsClaudePct: round(this.savingsVsClaude * 100, 2),
cacheHitRatio: round(this.aggregateCacheHitRatio, 4),
+90 -4
View File
@@ -1,11 +1,42 @@
import { analyzeSchema, flattenSchema, nestArguments } from "./repair/flatten.js";
import type { JSONSchema, ToolSpec } from "./types.js";
/**
* Per-call context a tool `fn` can optionally consume. Today the only
* field is `signal`, plumbed through so long-running tools (MCP calls,
* HTTP requests) can abort when the user presses Esc. Omitted fields
* stay optional — tools written against the pre-0.4.9 signature keep
* working; they just ignore cancellation, which is fine for fast
* local work where "await finishes" happens before the next tick anyway.
*/
export interface ToolCallContext {
signal?: AbortSignal;
}
export interface ToolDefinition<A = any, R = any> {
name: string;
description?: string;
parameters?: JSONSchema;
fn: (args: A) => R | Promise<R>;
/**
* Marks a tool as read-only: safe to invoke during plan mode. `true`
* for tools that only observe (read_file, list_directory, search, web
* fetch/search). Leave undefined / `false` for anything that can write,
* execute, or mutate state.
*
* The registry enforces this at dispatch: non-readonly tools called
* while `planMode` is on return a refusal string the model can
* learn from, instead of actually running.
*/
readOnly?: boolean;
/**
* Dynamic read-only check for tools whose safety depends on arguments
* — `run_command` with an allowlisted argv is safe, `run_command
* rm -rf` isn't. Called with the parsed arguments; `true` means "treat
* as read-only for plan mode". Takes precedence over `readOnly` when
* both are set.
*/
readOnlyCheck?: (args: A) => boolean;
fn: (args: A, ctx?: ToolCallContext) => R | Promise<R>;
}
interface InternalTool extends ToolDefinition {
@@ -30,11 +61,29 @@ export interface ToolRegistryOptions {
export class ToolRegistry {
private readonly _tools = new Map<string, InternalTool>();
private readonly _autoFlatten: boolean;
/**
* When true, `dispatch` refuses any tool whose `readOnly` flag isn't
* set (and whose `readOnlyCheck` doesn't pass on the specific args).
* Drives `reasonix code`'s Plan Mode — the model can still explore
* via read tools but its writes and non-allowlisted shell calls are
* bounced until the user approves a submitted plan.
*/
private _planMode = false;
constructor(opts: ToolRegistryOptions = {}) {
this._autoFlatten = opts.autoFlatten !== false;
}
/** Enable / disable plan-mode enforcement at dispatch. */
setPlanMode(on: boolean): void {
this._planMode = Boolean(on);
}
/** True when the registry is currently refusing non-readonly calls. */
get planMode(): boolean {
return this._planMode;
}
register<A, R>(def: ToolDefinition<A, R>): this {
if (!def.name) throw new Error("tool requires a name");
const internal: InternalTool = { ...(def as ToolDefinition) };
@@ -76,7 +125,11 @@ export class ToolRegistry {
}));
}
async dispatch(name: string, argumentsRaw: string | Record<string, unknown>): Promise<string> {
async dispatch(
name: string,
argumentsRaw: string | Record<string, unknown>,
opts: { signal?: AbortSignal } = {},
): Promise<string> {
const tool = this._tools.get(name);
if (!tool) {
return JSON.stringify({ error: `unknown tool: ${name}` });
@@ -104,17 +157,50 @@ export class ToolRegistry {
args = nestArguments(args);
}
// Plan-mode enforcement — runs AFTER arg parsing so a tool with a
// runtime `readOnlyCheck` can inspect the actual args (e.g.
// `run_command` is read-only iff the command matches its allowlist).
if (this._planMode && !isReadOnlyCall(tool, args)) {
return JSON.stringify({
error: `${name}: unavailable in plan mode — this is a read-only exploration phase. Use read_file / list_directory / search_files / directory_tree / web_search / allowlisted shell commands to investigate. Call submit_plan with your proposed plan when you're ready for the user's review.`,
});
}
try {
const result = await tool.fn(args);
const result = await tool.fn(args, { signal: opts.signal });
return typeof result === "string" ? result : JSON.stringify(result);
} catch (err) {
const e = err as Error & { toToolResult?: () => unknown };
// Errors may opt into a richer tool-result shape by implementing
// `toToolResult()`. Used by `PlanProposedError` to smuggle the
// submitted plan text out to the UI without stuffing it into the
// error message (which the dispatcher truncates at no fixed limit,
// but keeping payloads structured is cleaner for UI parsing).
if (typeof e.toToolResult === "function") {
try {
return JSON.stringify(e.toToolResult());
} catch {
/* fall through to the default shape */
}
}
return JSON.stringify({
error: `${(err as Error).name}: ${(err as Error).message}`,
error: `${e.name}: ${e.message}`,
});
}
}
}
function isReadOnlyCall(tool: InternalTool, args: Record<string, unknown>): boolean {
if (tool.readOnlyCheck) {
try {
return Boolean(tool.readOnlyCheck(args as never));
} catch {
return false;
}
}
return tool.readOnly === true;
}
function hasDotKey(obj: Record<string, unknown>): boolean {
for (const k of Object.keys(obj)) {
if (k.includes(".")) return true;
+450
View File
@@ -0,0 +1,450 @@
/**
* Built-in filesystem tools for `reasonix code`.
*
* Why native instead of the official `@modelcontextprotocol/server-filesystem`:
* - No subprocess overhead — every call is 50-200 ms cheaper.
* - Schema shapes tuned for R1: `edit_file` takes a single
* SEARCH/REPLACE string instead of `string="false"`-encoded
* JSON arrays, which was the biggest single source of DSML
* hallucinations in 0.4.x.
* - Sandbox enforcement lives here so Reasonix can reason about
* it (tests cover path-traversal, symlink-escape, and the
* cwd-outside-root case) rather than trusting an external server.
* - No `npx install` / network dependency in `reasonix code`.
*
* Tool names + argument shapes intentionally mirror the official
* filesystem server so R1's muscle memory carries over. The only
* intentional divergence is `edit_file`, noted above.
*/
import { promises as fs } from "node:fs";
import * as pathMod from "node:path";
import type { ToolRegistry } from "../tools.js";
export interface FilesystemToolsOptions {
/** Absolute directory the tools may read/write. Paths outside this are refused. */
rootDir: string;
/**
* When `false`, register only read-side tools (read_file, list_directory,
* search_files, get_file_info, directory_tree). Useful for read-only
* workflows where the model should never mutate the tree. Default: true.
*/
allowWriting?: boolean;
/**
* Cap for a single file read, in bytes. Prevents a stray `read_file`
* on a multi-GB blob from OOM'ing Node. 2 MB is enough for any realistic
* source file (the biggest single-file TypeScript project checked in to
* GitHub is ~500 KB); pass higher when working with data files.
*/
maxReadBytes?: number;
/**
* Cap for total bytes returned from search_files / directory_tree /
* grep, so the model can't accidentally pull down the whole tree as
* one giant string. 256 KB by default.
*/
maxListBytes?: number;
}
const DEFAULT_MAX_READ_BYTES = 2 * 1024 * 1024;
const DEFAULT_MAX_LIST_BYTES = 256 * 1024;
export function registerFilesystemTools(
registry: ToolRegistry,
opts: FilesystemToolsOptions,
): ToolRegistry {
const rootDir = pathMod.resolve(opts.rootDir);
const allowWriting = opts.allowWriting !== false;
const maxReadBytes = opts.maxReadBytes ?? DEFAULT_MAX_READ_BYTES;
const maxListBytes = opts.maxListBytes ?? DEFAULT_MAX_LIST_BYTES;
/** Resolve path, enforce it's under rootDir, return absolute. */
const safePath = (raw: unknown): string => {
if (typeof raw !== "string" || raw.length === 0) {
throw new Error("path must be a non-empty string");
}
// Interpret relative paths against rootDir (the session's scope).
const resolved = pathMod.resolve(rootDir, raw);
const normRoot = pathMod.resolve(rootDir);
// Use relative() to catch any `..` segments that escape.
const rel = pathMod.relative(normRoot, resolved);
if (rel.startsWith("..") || pathMod.isAbsolute(rel)) {
throw new Error(`path escapes sandbox root (${normRoot}): ${raw}`);
}
return resolved;
};
registry.register({
name: "read_file",
description:
"Read a file under the sandbox root. Returns the full contents (truncated with a notice if larger than the per-call cap). Paths may be relative to the root or absolute-under-root.",
readOnly: true,
parameters: {
type: "object",
properties: {
path: { type: "string", description: "Path to read (relative to rootDir or absolute)." },
head: { type: "integer", description: "If set, return only the first N lines." },
tail: { type: "integer", description: "If set, return only the last N lines." },
},
required: ["path"],
},
fn: async (args: { path: string; head?: number; tail?: number }) => {
const abs = safePath(args.path);
const stat = await fs.stat(abs);
if (stat.isDirectory()) {
throw new Error(`not a file: ${args.path} (it's a directory)`);
}
const raw = await fs.readFile(abs);
if (raw.length > maxReadBytes) {
const head = raw.slice(0, maxReadBytes).toString("utf8");
return `${head}\n\n[…truncated ${raw.length - maxReadBytes} bytes — file is ${raw.length} B, cap ${maxReadBytes} B. Retry with head/tail for targeted view.]`;
}
const text = raw.toString("utf8");
if (typeof args.head === "number" && args.head > 0) {
return text.split(/\r?\n/).slice(0, args.head).join("\n");
}
if (typeof args.tail === "number" && args.tail > 0) {
let lines = text.split(/\r?\n/);
// Most files end with a final '\n', which splits into an empty
// trailing string. Drop it before slicing so tail=2 returns the
// last two *real* lines, not "last line + empty".
if (lines.length > 0 && lines[lines.length - 1] === "") lines = lines.slice(0, -1);
return lines.slice(Math.max(0, lines.length - args.tail)).join("\n");
}
return text;
},
});
registry.register({
name: "list_directory",
description:
"List entries in a directory under the sandbox root. Returns one line per entry, marking directories with a trailing slash. Not recursive — use directory_tree for that.",
readOnly: true,
parameters: {
type: "object",
properties: {
path: { type: "string", description: "Directory to list (default: root)." },
},
},
fn: async (args: { path?: string }) => {
const abs = safePath(args.path ?? ".");
const entries = await fs.readdir(abs, { withFileTypes: true });
const lines: string[] = [];
for (const e of entries.sort((a, b) => a.name.localeCompare(b.name))) {
lines.push(e.isDirectory() ? `${e.name}/` : e.name);
}
return lines.join("\n") || "(empty directory)";
},
});
registry.register({
name: "directory_tree",
description:
"Recursively list entries in a directory. Shows indented tree structure with directories marked '/'. Caps output so a huge tree doesn't drown the context.",
readOnly: true,
parameters: {
type: "object",
properties: {
path: { type: "string", description: "Root of the tree (default: sandbox root)." },
maxDepth: { type: "integer", description: "Max recursion depth (default 4)." },
},
},
fn: async (args: { path?: string; maxDepth?: number }) => {
const startAbs = safePath(args.path ?? ".");
const maxDepth = typeof args.maxDepth === "number" ? args.maxDepth : 4;
const lines: string[] = [];
let totalBytes = 0;
let truncated = false;
const walk = async (dir: string, depth: number): Promise<void> => {
if (truncated) return;
if (depth > maxDepth) return;
let entries: import("node:fs").Dirent[];
try {
entries = await fs.readdir(dir, { withFileTypes: true });
} catch {
return;
}
entries.sort((a, b) => a.name.localeCompare(b.name));
for (const e of entries) {
if (truncated) return;
const indent = " ".repeat(depth);
const line = e.isDirectory() ? `${indent}${e.name}/` : `${indent}${e.name}`;
totalBytes += line.length + 1;
if (totalBytes > maxListBytes) {
lines.push(` [… tree truncated at ${maxListBytes} bytes …]`);
truncated = true;
return;
}
lines.push(line);
if (e.isDirectory()) {
await walk(pathMod.join(dir, e.name), depth + 1);
}
}
};
await walk(startAbs, 0);
return lines.join("\n") || "(empty tree)";
},
});
registry.register({
name: "search_files",
description:
"Find files whose NAME matches a substring or regex. Case-insensitive. Walks the directory recursively under the sandbox root. Returns one path per line.",
readOnly: true,
parameters: {
type: "object",
properties: {
path: { type: "string", description: "Directory to start the search at (default: root)." },
pattern: {
type: "string",
description: "Substring (or regex) to match against filenames.",
},
},
required: ["pattern"],
},
fn: async (args: { path?: string; pattern: string }) => {
const startAbs = safePath(args.path ?? ".");
const needle = args.pattern.toLowerCase();
// Try as regex first (permits users who want patterns); fall
// back to plain substring when it's not a valid regex. Flag `i`
// so matching is case-insensitive regardless of path.
let re: RegExp | null = null;
try {
re = new RegExp(args.pattern, "i");
} catch {
re = null;
}
const matches: string[] = [];
let totalBytes = 0;
const walk = async (dir: string): Promise<void> => {
let entries: import("node:fs").Dirent[];
try {
entries = await fs.readdir(dir, { withFileTypes: true });
} catch {
return;
}
for (const e of entries) {
const full = pathMod.join(dir, e.name);
const lower = e.name.toLowerCase();
const hit = re ? re.test(e.name) : lower.includes(needle);
if (hit) {
const rel = pathMod.relative(rootDir, full);
if (totalBytes + rel.length + 1 > maxListBytes) {
matches.push("[… search truncated — refine pattern …]");
return;
}
matches.push(rel);
totalBytes += rel.length + 1;
}
if (e.isDirectory()) await walk(full);
}
};
await walk(startAbs);
return matches.length === 0 ? "(no matches)" : matches.join("\n");
},
});
registry.register({
name: "get_file_info",
description:
"Stat a path under the sandbox root. Returns type (file|directory|symlink), size in bytes, mtime in ISO-8601.",
readOnly: true,
parameters: {
type: "object",
properties: {
path: { type: "string" },
},
required: ["path"],
},
fn: async (args: { path: string }) => {
const abs = safePath(args.path);
const st = await fs.lstat(abs);
const type = st.isDirectory() ? "directory" : st.isSymbolicLink() ? "symlink" : "file";
return JSON.stringify({
type,
size: st.size,
mtime: st.mtime.toISOString(),
});
},
});
if (!allowWriting) return registry;
registry.register({
name: "write_file",
description:
"Create or overwrite a file under the sandbox root with the given content. Parent directories are created as needed.",
parameters: {
type: "object",
properties: {
path: { type: "string" },
content: { type: "string" },
},
required: ["path", "content"],
},
fn: async (args: { path: string; content: string }) => {
const abs = safePath(args.path);
await fs.mkdir(pathMod.dirname(abs), { recursive: true });
await fs.writeFile(abs, args.content, "utf8");
return `wrote ${args.content.length} chars to ${pathMod.relative(rootDir, abs)}`;
},
});
registry.register({
name: "edit_file",
description:
"Apply a SEARCH/REPLACE edit to an existing file. `search` must match exactly (whitespace sensitive) — no regex. The match must be unique in the file; otherwise the edit is refused to avoid surprise rewrites.",
parameters: {
type: "object",
properties: {
path: { type: "string" },
search: { type: "string", description: "Exact text to find (must be unique)." },
replace: { type: "string", description: "Text to substitute in place of `search`." },
},
required: ["path", "search", "replace"],
},
fn: async (args: { path: string; search: string; replace: string }) => {
const abs = safePath(args.path);
const before = await fs.readFile(abs, "utf8");
if (args.search.length === 0) {
throw new Error("edit_file: search cannot be empty");
}
const firstIdx = before.indexOf(args.search);
if (firstIdx < 0) {
throw new Error(`edit_file: search text not found in ${pathMod.relative(rootDir, abs)}`);
}
const nextIdx = before.indexOf(args.search, firstIdx + 1);
if (nextIdx >= 0) {
throw new Error(
`edit_file: search text appears multiple times in ${pathMod.relative(rootDir, abs)} — include more context to disambiguate`,
);
}
const after =
before.slice(0, firstIdx) + args.replace + before.slice(firstIdx + args.search.length);
await fs.writeFile(abs, after, "utf8");
const rel = pathMod.relative(rootDir, abs);
const header = `edited ${rel} (${args.search.length}→${args.replace.length} chars)`;
// Starting line number of the search block in the original
// file. `split/length` on the prefix gives a 1-based line
// count where the match begins, matching git-diff's @@ -N,M
// +N,M @@ header convention.
const startLine = before.slice(0, firstIdx).split(/\r?\n/).length;
const diff = renderEditDiff(args.search, args.replace, startLine);
return `${header}\n${diff}`;
},
});
registry.register({
name: "create_directory",
description: "Create a directory (and any missing parents) under the sandbox root.",
parameters: {
type: "object",
properties: { path: { type: "string" } },
required: ["path"],
},
fn: async (args: { path: string }) => {
const abs = safePath(args.path);
await fs.mkdir(abs, { recursive: true });
return `created ${pathMod.relative(rootDir, abs)}/`;
},
});
registry.register({
name: "move_file",
description: "Rename/move a file or directory under the sandbox root.",
parameters: {
type: "object",
properties: {
source: { type: "string" },
destination: { type: "string" },
},
required: ["source", "destination"],
},
fn: async (args: { source: string; destination: string }) => {
const src = safePath(args.source);
const dst = safePath(args.destination);
await fs.mkdir(pathMod.dirname(dst), { recursive: true });
await fs.rename(src, dst);
return `moved ${pathMod.relative(rootDir, src)} → ${pathMod.relative(rootDir, dst)}`;
},
});
return registry;
}
/**
* Format an edit_file change as a proper line-level diff, styled
* like `git diff`. Starts with a unified-diff hunk header —
* `@@ -startLine,oldCount +startLine,newCount @@` — so the user
* can tell where in the file the change lands. Body uses LCS
* (longest common subsequence) to mark lines as removed (`-`),
* added (`+`), or unchanged context (` `). Users were getting
* hundreds of `-` followed by hundreds of `+` for tiny changes
* because the naive "dump both sides" format can't tell what
* actually moved vs. stayed — this fixes that and adds line-
* number context on top.
*/
function renderEditDiff(search: string, replace: string, startLine: number): string {
const a = search.split(/\r?\n/);
const b = replace.split(/\r?\n/);
const diff = lineDiff(a, b);
const hunk = `@@ -${startLine},${a.length} +${startLine},${b.length} @@`;
const body = diff.map((d) => `${d.op === " " ? " " : d.op} ${d.line}`).join("\n");
return `${hunk}\n${body}`;
}
/**
* Compute a line-level diff via classic LCS dynamic programming.
* Good enough for SEARCH/REPLACE blocks where both sides are
* typically under a few hundred lines — O(n*m) space + time. For
* huge blocks we'd want Myers' algorithm, but the caller already
* caps the inline-display size and `/tool N` shows the full result,
* so quadratic is fine in practice.
*
* Exported so tests can exercise the diff logic without spinning
* up the full tool dispatch path.
*/
export function lineDiff(
a: readonly string[],
b: readonly string[],
): Array<{ op: "-" | "+" | " "; line: string }> {
const n = a.length;
const m = b.length;
// dp[i][j] = LCS length of a[0..i) and b[0..j).
const dp: number[][] = Array.from({ length: n + 1 }, () => new Array(m + 1).fill(0));
for (let i = 1; i <= n; i++) {
for (let j = 1; j <= m; j++) {
if (a[i - 1] === b[j - 1]) dp[i]![j] = dp[i - 1]![j - 1]! + 1;
else dp[i]![j] = Math.max(dp[i - 1]![j]!, dp[i]![j - 1]!);
}
}
// Backtrack to recover the op sequence.
const out: Array<{ op: "-" | "+" | " "; line: string }> = [];
let i = n;
let j = m;
while (i > 0 && j > 0) {
if (a[i - 1] === b[j - 1]) {
out.unshift({ op: " ", line: a[i - 1]! });
i--;
j--;
} else if ((dp[i - 1]![j] ?? 0) > (dp[i]![j - 1] ?? 0)) {
out.unshift({ op: "-", line: a[i - 1]! });
i--;
} else {
// Tie-break goes here (strictly less or equal): take the
// insertion first during backtrack so the final forward order
// renders removals BEFORE additions for a substitution —
// matches git-diff convention of `- old / + new`.
out.unshift({ op: "+", line: b[j - 1]! });
j--;
}
}
while (i > 0) {
out.unshift({ op: "-", line: a[i - 1]! });
i--;
}
while (j > 0) {
out.unshift({ op: "+", line: b[j - 1]! });
j--;
}
return out;
}
+180
View File
@@ -0,0 +1,180 @@
/**
* `remember` / `forget` / `recall_memory` — tools that let the model
* read and write the user-memory store across sessions.
*
* Scope rules:
* - `global` — always available (no sandbox needed).
* - `project` — requires a `projectRoot` on MemoryStore. In chat mode
* (no sandbox), the tools still register but a `scope=project` call
* returns a structured refusal so the model can try `global` instead.
*
* Memory changes are written eagerly but NOT re-loaded into the prefix
* mid-session (cache invariant). The user notices at `/new` or the next
* launch — or they can read fresh content via `recall_memory` which
* always hits disk.
*/
import type { ToolRegistry } from "../tools.js";
import {
type MemoryScope,
MemoryStore,
type MemoryType,
sanitizeMemoryName,
} from "../user-memory.js";
export interface MemoryToolsOptions {
/** Sandbox root for the `project` scope. Omit for chat mode. */
projectRoot?: string;
/** Override `~/.reasonix` (tests). */
homeDir?: string;
}
export function registerMemoryTools(
registry: ToolRegistry,
opts: MemoryToolsOptions = {},
): ToolRegistry {
const store = new MemoryStore({ homeDir: opts.homeDir, projectRoot: opts.projectRoot });
const hasProject = store.hasProjectScope();
registry.register({
name: "remember",
description:
"Save a memory for future sessions. Use when the user states a preference, corrects your approach, shares a non-obvious fact about this project, or explicitly asks you to remember something. Don't remember transient task state — only things worth recalling next session. The memory is written now but won't re-load into the system prompt until the next `/new` or launch.",
parameters: {
type: "object",
properties: {
type: {
type: "string",
enum: ["user", "feedback", "project", "reference"],
description:
"'user' = role/skills/prefs; 'feedback' = corrections or confirmed approaches; 'project' = facts/decisions about the current work; 'reference' = pointers to external systems the user uses.",
},
scope: {
type: "string",
enum: ["global", "project"],
description:
"'global' = applies across every project (preferences, tooling); 'project' = scoped to the current sandbox (decisions, local facts). Only available in `reasonix code`.",
},
name: {
type: "string",
description:
"filename-safe identifier, 3-40 chars, alnum + _ - . (no path separators, no leading dot).",
},
description: {
type: "string",
description: "One-line summary shown in MEMORY.md (under ~150 chars).",
},
content: {
type: "string",
description:
"Full memory body in markdown. For feedback/project types, structure as: rule/fact, then **Why:** line, then **How to apply:** line.",
},
},
required: ["type", "scope", "name", "description", "content"],
},
fn: async (args: {
type: MemoryType;
scope: MemoryScope;
name: string;
description: string;
content: string;
}) => {
if (args.scope === "project" && !hasProject) {
return JSON.stringify({
error:
"scope='project' is unavailable in this session (no sandbox root). Retry with scope='global', or ask the user to switch to `reasonix code` for project-scoped memory.",
});
}
try {
const path = store.write({
name: args.name,
type: args.type,
scope: args.scope,
description: args.description,
body: args.content,
});
const key = sanitizeMemoryName(args.name);
// The return text is load-bearing: it's the ONLY thing keeping
// the fact visible within the current session, because the
// prefix isn't re-hashed mid-session (Pillar 1). R1 reads this
// on its next turn — the wording is deliberately imperative so
// it doesn't get ignored in favor of explore-first behavior.
return [
`✓ REMEMBERED (${args.scope}/${key}): ${args.description}`,
"",
"TREAT THIS AS ESTABLISHED FACT for the rest of this session.",
"The user just told you — don't re-explore the filesystem to re-derive it.",
`(Saved to ${path}; pins into the system prompt on next /new or launch.)`,
].join("\n");
} catch (err) {
return JSON.stringify({ error: `remember failed: ${(err as Error).message}` });
}
},
});
registry.register({
name: "forget",
description:
"Delete a memory file and remove it from MEMORY.md. Use when the user explicitly asks to forget something, or when a previously-remembered fact has become wrong. Irreversible — no tombstone.",
parameters: {
type: "object",
properties: {
name: { type: "string", description: "Memory name (the identifier used in `remember`)." },
scope: { type: "string", enum: ["global", "project"] },
},
required: ["name", "scope"],
},
fn: async (args: { name: string; scope: MemoryScope }) => {
if (args.scope === "project" && !hasProject) {
return JSON.stringify({
error: "scope='project' is unavailable in this session (no sandbox root).",
});
}
try {
const existed = store.delete(args.scope, args.name);
return existed
? `forgot (${args.scope}/${sanitizeMemoryName(args.name)}). Re-load on next /new or launch.`
: `no such memory: ${args.scope}/${args.name} (nothing to forget).`;
} catch (err) {
return JSON.stringify({ error: `forget failed: ${(err as Error).message}` });
}
},
});
registry.register({
name: "recall_memory",
description:
"Read the full body of a memory file when its MEMORY.md one-liner (already in the system prompt) isn't enough detail. Most of the time the index suffices — only call this when the user's question genuinely requires the full context.",
readOnly: true,
parameters: {
type: "object",
properties: {
name: { type: "string" },
scope: { type: "string", enum: ["global", "project"] },
},
required: ["name", "scope"],
},
fn: async (args: { name: string; scope: MemoryScope }) => {
if (args.scope === "project" && !hasProject) {
return JSON.stringify({
error: "scope='project' is unavailable in this session (no sandbox root).",
});
}
try {
const entry = store.read(args.scope, args.name);
return [
`# ${entry.name} (${entry.scope}/${entry.type}, created ${entry.createdAt || "?"})`,
entry.description ? `> ${entry.description}` : "",
"",
entry.body,
]
.filter(Boolean)
.join("\n");
} catch (err) {
return JSON.stringify({ error: `recall failed: ${(err as Error).message}` });
}
},
});
return registry;
}
+101
View File
@@ -0,0 +1,101 @@
/**
* Plan Mode — read-only exploration phase for `reasonix code`.
*
* Shape (mirrors claude-code's plan/act split, adapted for Reasonix):
*
* 1. User types `/plan` → registry switches to plan-mode enforcement
* (write tools refused at dispatch; reads + allowlisted shell
* still work).
* 2. Model explores, then calls `submit_plan` with a markdown plan.
* 3. `submit_plan` throws `PlanProposedError`, which the TUI renders
* as a picker: Approve / Refine / Cancel.
* 4. Approve → registry leaves plan mode, a synthetic user message
* "The plan has been approved. Implement it now." is pushed into
* the loop so the next turn executes.
*
* The read-only enforcement lives in `ToolRegistry.dispatch` via
* `readOnly` / `readOnlyCheck`; this file only ships the `submit_plan`
* escape hatch and the error type that carries the plan out of the
* registry without stuffing it into the message.
*
* We do not change `ImmutablePrefix.toolSpecs` when plan mode toggles —
* that would break Pillar 1's prefix cache. Instead the same full spec
* list stays pinned, and the registry enforces mode at dispatch time.
* The refusal string teaches the model the rule; cache hits stay
* intact.
*/
import type { ToolRegistry } from "../tools.js";
/**
* Thrown by `submit_plan` when plan mode is active, carrying the plan
* text the TUI will render for the user's approval.
*
* Implements the `toToolResult` protocol so `ToolRegistry.dispatch`
* serializes the full plan into the tool-result JSON (not just the
* error message). The TUI parses `{ error, plan }` from the tool event
* and mounts the `PlanConfirm` picker.
*/
export class PlanProposedError extends Error {
readonly plan: string;
constructor(plan: string) {
super(
"PlanProposedError: plan submitted. STOP calling tools now — the TUI has shown the plan to the user. Wait for their next message; it will either approve (you'll then implement the plan), request a refinement (you should explore more and submit an updated plan), or cancel (drop the plan and ask what they want instead). Don't call any tools in the meantime.",
);
this.name = "PlanProposedError";
this.plan = plan;
}
/**
* Structured tool-result shape. Consumed by the TUI to extract the
* plan without regex-scraping the error message.
*/
toToolResult(): { error: string; plan: string } {
return { error: `${this.name}: ${this.message}`, plan: this.plan };
}
}
export interface PlanToolOptions {
/**
* Optional side-channel callback fired when the model submits a plan.
* The TUI uses this to preview the plan in real time (the tool-result
* event is also emitted; this is just earlier and friendlier to
* test harnesses that don't want to parse JSON).
*/
onPlanSubmitted?: (plan: string) => void;
}
export function registerPlanTool(registry: ToolRegistry, opts: PlanToolOptions = {}): ToolRegistry {
registry.register({
name: "submit_plan",
description:
"Submit a concrete plan to the user for review before executing. Use this for tasks that warrant a review gate — multi-file refactors, architecture changes, anything that would be expensive or confusing to undo. Skip it for small fixes (one-line typo, obvious bug with a clear fix) — just make the change. The user will either approve (you then implement it), ask for refinement, or cancel. If the user has already enabled /plan mode, writes are blocked at dispatch and you MUST use this. Write the plan as markdown with a one-line summary, a bulleted list of files to touch and what will change, and any risks or open questions.",
readOnly: true,
parameters: {
type: "object",
properties: {
plan: {
type: "string",
description:
"Markdown-formatted plan. Lead with a one-sentence summary. Then a file-by-file breakdown of what you'll change and why. Flag any risks or open questions at the end so the user can weigh in before you start.",
},
},
required: ["plan"],
},
fn: async (args: { plan: string }) => {
const plan = (args?.plan ?? "").trim();
if (!plan) {
throw new Error("submit_plan: empty plan — write a markdown plan and try again.");
}
// Always fire the picker, not just inside plan mode. Plan mode's
// role is the *stronger* constraint — it forces you into read-only
// until you submit. Outside plan mode, submit_plan is your own
// call: use it when the task is large enough to deserve a review
// gate (multi-file refactors, architecture changes, anything
// that would be expensive to undo), skip it for small fixes.
opts.onPlanSubmitted?.(plan);
throw new PlanProposedError(plan);
},
});
return registry;
}
+509
View File
@@ -0,0 +1,509 @@
/**
* Native shell tool — lets the model run commands inside the sandbox
* root so it can actually verify its own work (run tests, check git
* status, inspect a lockfile, etc.). Without this the coding-mode
* loop is "write code, hope it works, ask the user to run it" —
* defeats the purpose.
*
* Safety model:
* - Commands run with `cwd` pinned to the registered root. No
* path traversal via the command itself is enforced (users can
* `cat ../outside.txt`); the trust boundary is the directory
* you opened Reasonix from.
* - Commands are matched against a read-only / testing allowlist.
* Allowlisted commands execute immediately and return stdout +
* stderr merged. Everything else throws with a clear message —
* the UI translates that into an `/apply`-style confirm gate so
* the user sees the exact command before it runs.
* - Default timeout: 60s. Output cap: matches tool-result budget.
* - Every command that DOES run is spawned with `shell: false` and
* a tokenized argv — no string-to-shell interpolation, so the
* model can't accidentally construct a chained `rm` via quoting.
*
* This is intentionally narrower than what Claude Code / Aider ship:
* we gate more commands behind confirmation by default. Users who
* trust the model can widen the allowlist by instantiating their
* own tool registry.
*/
import { type SpawnOptions, spawn } from "node:child_process";
import { existsSync, statSync } from "node:fs";
import * as pathMod from "node:path";
import type { ToolRegistry } from "../tools.js";
export interface ShellToolsOptions {
/** Directory to run commands in. Must be an absolute path. */
rootDir: string;
/** Seconds before an individual command is killed. Default: 60. */
timeoutSec?: number;
/**
* Per-command stdout+stderr cap in characters. Default: 32_000 to
* match the tool-result budget.
*/
maxOutputChars?: number;
/**
* Extra command-name prefixes the user explicitly trusts. Added on
* top of the built-in allowlist. Examples: `["my-ci-script", "lint"]`.
*
* Accepts either a fixed array (captured once at registration) or a
* getter called on every dispatch. The getter form is load-bearing:
* when the TUI's `ShellConfirm` writes a new prefix to config mid-
* session, the running `run_command` must pick it up immediately —
* otherwise the same command gets re-prompted until the next launch.
*/
extraAllowed?: readonly string[] | (() => readonly string[]);
/**
* When true, skip the allowlist entirely and auto-run every command.
* Off by default — this is an escape hatch for non-interactive use
* (CI, benchmarks) where a human can't be in the loop to confirm.
*/
allowAll?: boolean;
}
const DEFAULT_TIMEOUT_SEC = 60;
const DEFAULT_MAX_OUTPUT_CHARS = 32_000;
/**
* Command prefixes we consider safe to run without asking the user.
* Rule of thumb: read-only reports, or test runners whose failure mode
* is "exit 1 with output." Nothing that can rewrite state, escalate,
* or touch the network.
*/
const BUILTIN_ALLOWLIST: ReadonlyArray<string> = [
// Repo inspection
"git status",
"git diff",
"git log",
"git show",
"git blame",
"git branch",
"git remote",
"git rev-parse",
"git config --get",
// Filesystem inspection
"ls",
"pwd",
"cat",
"head",
"tail",
"wc",
"file",
"tree",
"find",
"grep",
"rg",
// Language version probes
"node --version",
"node -v",
"npm --version",
"npx --version",
"python --version",
"python3 --version",
"cargo --version",
"go version",
"rustc --version",
"deno --version",
"bun --version",
// Test runners (non-destructive by convention)
"npm test",
"npm run test",
"npx vitest run",
"npx vitest",
"npx jest",
"pytest",
"python -m pytest",
"cargo test",
"cargo check",
"cargo clippy",
"go test",
"go vet",
"deno test",
"bun test",
// Linters / typecheckers (read-only by convention)
"npm run lint",
"npm run typecheck",
"npx tsc --noEmit",
"npx biome check",
"npx eslint",
"npx prettier --check",
"ruff",
"mypy",
];
/**
* Tokenize a shell-ish command string into argv. Handles single/double
* quoting; rejects unclosed quotes. Does NOT expand env vars, globs,
* backticks, or `$(…)` — the goal is to prevent the model from
* accidentally (or not) sneaking arbitrary shells past the allowlist
* via concatenation. Exported for testing.
*/
export function tokenizeCommand(cmd: string): string[] {
const out: string[] = [];
let cur = "";
let quote: '"' | "'" | null = null;
for (let i = 0; i < cmd.length; i++) {
const ch = cmd[i]!;
if (quote) {
if (ch === quote) {
quote = null;
} else if (ch === "\\" && quote === '"' && i + 1 < cmd.length) {
cur += cmd[++i];
} else {
cur += ch;
}
continue;
}
if (ch === '"' || ch === "'") {
quote = ch;
continue;
}
if (ch === " " || ch === "\t") {
if (cur.length > 0) {
out.push(cur);
cur = "";
}
continue;
}
cur += ch;
}
if (quote) throw new Error(`unclosed ${quote} in command`);
if (cur.length > 0) out.push(cur);
return out;
}
/**
* Return true when `cmd` matches an allowlisted prefix. Exported for
* testing. Match is on the space-normalized leading tokens so
* `git status -s ` and `git status` both match `git status`.
*/
export function isAllowed(cmd: string, extra: readonly string[] = []): boolean {
const normalized = cmd.trim().replace(/\s+/g, " ");
const allowlist = [...BUILTIN_ALLOWLIST, ...extra];
for (const prefix of allowlist) {
if (normalized === prefix) return true;
if (normalized.startsWith(`${prefix} `)) return true;
}
return false;
}
export interface RunCommandResult {
exitCode: number | null;
/** Combined stdout+stderr, truncated to `maxOutputChars` with a marker. */
output: string;
/** True when the process was killed for exceeding `timeoutSec`. */
timedOut: boolean;
}
export async function runCommand(
cmd: string,
opts: {
cwd: string;
timeoutSec?: number;
maxOutputChars?: number;
signal?: AbortSignal;
},
): Promise<RunCommandResult> {
const argv = tokenizeCommand(cmd);
if (argv.length === 0) throw new Error("run_command: empty command");
const timeoutMs = (opts.timeoutSec ?? DEFAULT_TIMEOUT_SEC) * 1000;
const maxChars = opts.maxOutputChars ?? DEFAULT_MAX_OUTPUT_CHARS;
const spawnOpts: SpawnOptions = {
cwd: opts.cwd,
shell: false, // no shell-expansion — see header comment
windowsHide: true,
env: process.env,
};
// Windows: two layered fixes on top of shell:false —
// 1. Resolve bare command names via PATH × PATHEXT (CreateProcess
// ignores PATHEXT, so `npm` alone misses `npm.cmd`).
// 2. Node 21.7.3+ (CVE-2024-27980) refuses to spawn `.cmd`/`.bat`
// directly even with shell:false and safe args — throws
// EINVAL at invocation time. Wrap those via `cmd.exe /d /s /c`
// with verbatim args + manual quoting, so shell metacharacters
// in arguments stay literal.
// Unix path is unchanged.
const { bin, args, spawnOverrides } = prepareSpawn(argv);
const effectiveSpawnOpts = { ...spawnOpts, ...spawnOverrides };
return await new Promise<RunCommandResult>((resolve, reject) => {
let child: import("node:child_process").ChildProcess;
try {
child = spawn(bin, args, effectiveSpawnOpts);
} catch (err) {
reject(err);
return;
}
let buf = "";
let timedOut = false;
const killTimer = setTimeout(() => {
timedOut = true;
child.kill("SIGKILL");
}, timeoutMs);
const onAbort = () => child.kill("SIGKILL");
opts.signal?.addEventListener("abort", onAbort, { once: true });
const onData = (chunk: Buffer | string) => {
buf += chunk.toString();
// Soft cap: we let the process keep running (killing early could
// hide a real failure), but we stop growing the buffer past 2×
// the cap so a chatty test can't OOM us.
if (buf.length > maxChars * 2) buf = `${buf.slice(0, maxChars * 2)}`;
};
child.stdout?.on("data", onData);
child.stderr?.on("data", onData);
child.on("error", (err) => {
clearTimeout(killTimer);
opts.signal?.removeEventListener("abort", onAbort);
reject(err);
});
child.on("close", (code) => {
clearTimeout(killTimer);
opts.signal?.removeEventListener("abort", onAbort);
const output =
buf.length > maxChars
? `${buf.slice(0, maxChars)}\n\n[… truncated ${buf.length - maxChars} chars …]`
: buf;
resolve({ exitCode: code, output, timedOut });
});
});
}
/**
* Test/override hooks for {@link resolveExecutable}. Omitting any field
* falls through to the real process globals — the runtime call path
* uses defaults; tests inject `platform` + `env` + `isFile` to exercise
* Windows-specific lookup from a Linux CI runner without touching
* actual fs.
*/
export interface ResolveExecutableOptions {
platform?: NodeJS.Platform;
env?: { PATH?: string; PATHEXT?: string };
/** Predicate swapped in by tests to avoid creating real files. */
isFile?: (path: string) => boolean;
/** Path.join used for the lookup. Defaults to Windows semantics on Windows. */
pathDelimiter?: string;
}
/**
* Resolve a bare command name (e.g. `npm`) to its on-disk path via
* PATH × PATHEXT on Windows. Returns the input unchanged on non-Windows
* platforms, when the input is already a path (contains `/`, `\`, or is
* absolute), or when no match is found in PATH × PATHEXT (caller gets a
* natural ENOENT from spawn, which surfaces cleanly).
*
* Why this exists: `child_process.spawn` with `shell: false` invokes
* Windows `CreateProcess`, which does not honor `PATHEXT` and does not
* search for `.cmd` / `.bat` wrappers. Node-ecosystem tools ship as
* `npm.cmd`, `npx.cmd`, `yarn.cmd`, etc., so a bare `npm` fails with
* ENOENT under `shell: false`. Flipping to `shell: true` would work
* but reintroduces shell-expansion (pipes, redirects, chained cmds)
* that the tool was explicitly designed to forbid. This resolver
* threads the needle.
*/
export function resolveExecutable(cmd: string, opts: ResolveExecutableOptions = {}): string {
const platform = opts.platform ?? process.platform;
if (platform !== "win32") return cmd;
if (!cmd) return cmd;
// Already a path fragment — spawn handles these natively.
if (cmd.includes("/") || cmd.includes("\\") || pathMod.isAbsolute(cmd)) return cmd;
// If the model wrote `npm.cmd` explicitly, respect that verbatim.
if (pathMod.extname(cmd)) return cmd;
const env = opts.env ?? process.env;
const pathExt = (env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD")
.split(";")
.map((e) => e.trim())
.filter(Boolean);
const delimiter = opts.pathDelimiter ?? (platform === "win32" ? ";" : pathMod.delimiter);
const pathDirs = (env.PATH ?? "").split(delimiter).filter(Boolean);
const isFile = opts.isFile ?? defaultIsFile;
for (const dir of pathDirs) {
for (const ext of pathExt) {
// Force win32 join so CI tests that pass `platform: "win32"`
// from a Linux runner get backslash-joined paths; the real-
// Windows runtime path lands here too and gets the correct
// separator regardless of where pathMod defaults.
const full = pathMod.win32.join(dir, cmd + ext);
if (isFile(full)) return full;
}
}
return cmd;
}
function defaultIsFile(full: string): boolean {
try {
return existsSync(full) && statSync(full).isFile();
} catch {
return false;
}
}
/**
* Prepare `(bin, args, spawnOpts)` for the runCommand spawn call,
* applying Windows-specific workarounds for (a) PATHEXT lookup and
* (b) the CVE-2024-27980 prohibition on direct `.cmd`/`.bat` spawns.
*
* Exported so tests can assert the transformation without booting an
* actual child process.
*/
export function prepareSpawn(
argv: readonly string[],
opts: ResolveExecutableOptions = {},
): { bin: string; args: string[]; spawnOverrides: SpawnOptions } {
const head = argv[0] ?? "";
const tail = argv.slice(1);
const platform = opts.platform ?? process.platform;
const resolved = resolveExecutable(head, opts);
if (platform !== "win32") {
return { bin: resolved, args: [...tail], spawnOverrides: {} };
}
// `.cmd` / `.bat` wrappers require cmd.exe on post-CVE Node.
if (/\.(cmd|bat)$/i.test(resolved)) {
const cmdline = [resolved, ...tail].map(quoteForCmdExe).join(" ");
return {
bin: "cmd.exe",
args: ["/d", "/s", "/c", cmdline],
// windowsVerbatimArguments prevents Node from re-quoting the /c
// payload — we've already composed an exact cmd.exe command
// line. Without this Node wraps our already-quoted string in
// another round of quotes and cmd.exe can't parse it.
spawnOverrides: { windowsVerbatimArguments: true },
};
}
// Bare command names that PATH × PATHEXT couldn't resolve to an
// on-disk file — these are almost always cmd.exe built-ins (`dir`,
// `echo`, `type`, `ver`, `vol`, `where`, `help`, …) which don't
// exist as standalone executables. Direct spawn crashes with ENOENT;
// routing through cmd.exe lets the built-in resolve, and if it's
// genuinely unknown the user gets the standard "'foo' is not
// recognized" message instead of a raw spawn failure.
if (isBareWindowsName(resolved) && resolved === head) {
const cmdline = [head, ...tail].map(quoteForCmdExe).join(" ");
return {
bin: "cmd.exe",
args: ["/d", "/s", "/c", cmdline],
spawnOverrides: { windowsVerbatimArguments: true },
};
}
return { bin: resolved, args: [...tail], spawnOverrides: {} };
}
/**
* True when `s` looks like a bare executable name — no path separator,
* no drive letter, no extension. Such names on Windows, when absent
* from PATH × PATHEXT, are almost always cmd.exe built-ins.
*/
function isBareWindowsName(s: string): boolean {
if (!s) return false;
if (s.includes("/") || s.includes("\\")) return false;
if (pathMod.isAbsolute(s)) return false;
if (pathMod.extname(s)) return false;
return true;
}
/**
* Quote an argument so cmd.exe parses it back as a single token. We
* always wrap in double quotes when the arg contains whitespace or
* any cmd.exe metacharacter, doubling embedded quotes per cmd.exe's
* `""` escape rule. Bare alphanumeric args pass through unquoted for
* readability in logs.
*
* Exported for test coverage of the quoting semantics.
*/
export function quoteForCmdExe(arg: string): string {
if (arg === "") return '""';
if (!/[\s"&|<>^%(),;!]/.test(arg)) return arg;
return `"${arg.replace(/"/g, '""')}"`;
}
/** Error thrown by `run_command` when the command isn't allowlisted. */
export class NeedsConfirmationError extends Error {
readonly command: string;
constructor(command: string) {
super(
`run_command: "${command}" needs the user's approval before it runs. STOP calling tools now — the TUI has already prompted the user to press y (run) or n (deny). Wait for their next message; it will either be the command's output (if they approved) or an instruction to continue without it (if they denied). Don't retry the command or call other shell commands in the meantime.`,
);
this.name = "NeedsConfirmationError";
this.command = command;
}
}
export function registerShellTools(registry: ToolRegistry, opts: ShellToolsOptions): ToolRegistry {
const rootDir = pathMod.resolve(opts.rootDir);
const timeoutSec = opts.timeoutSec ?? DEFAULT_TIMEOUT_SEC;
const maxOutputChars = opts.maxOutputChars ?? DEFAULT_MAX_OUTPUT_CHARS;
// Resolved on every dispatch so newly-persisted "always allow"
// prefixes take effect inside the session that added them, not just
// on the next launch. Static arrays are wrapped into a constant
// getter so the call site below is uniform.
const getExtraAllowed: () => readonly string[] =
typeof opts.extraAllowed === "function"
? opts.extraAllowed
: (() => {
const snapshot = opts.extraAllowed ?? [];
return () => snapshot;
})();
const allowAll = opts.allowAll ?? false;
registry.register({
name: "run_command",
description:
"Run a shell command in the project root and return its combined stdout+stderr. Common read-only inspection and test/lint/typecheck commands run immediately; anything that could mutate state, install dependencies, or touch the network is refused until the user confirms it in the TUI. Prefer this over asking the user to run a command manually — after edits, run the project's tests to verify.",
// Plan-mode gate: allow allowlisted commands through (git status,
// cargo check, ls, grep …) so the model can actually investigate
// during planning. Anything that would otherwise trigger a
// confirmation prompt is treated as "not read-only" and bounced.
readOnlyCheck: (args: { command?: unknown }) => {
if (allowAll) return true;
const cmd = typeof args?.command === "string" ? args.command.trim() : "";
if (!cmd) return false;
return isAllowed(cmd, getExtraAllowed());
},
parameters: {
type: "object",
properties: {
command: {
type: "string",
description:
"Full command line. Tokenized with POSIX-ish quoting; no shell expansion, no pipes, no redirects.",
},
timeoutSec: {
type: "integer",
description: `Override the default ${timeoutSec}s timeout for a single command.`,
},
},
required: ["command"],
},
fn: async (args: { command: string; timeoutSec?: number }, ctx) => {
const cmd = args.command.trim();
if (!cmd) throw new Error("run_command: empty command");
if (!allowAll && !isAllowed(cmd, getExtraAllowed())) {
throw new NeedsConfirmationError(cmd);
}
const effectiveTimeout = Math.max(1, Math.min(600, args.timeoutSec ?? timeoutSec));
const result = await runCommand(cmd, {
cwd: rootDir,
timeoutSec: effectiveTimeout,
maxOutputChars,
signal: ctx?.signal,
});
return formatCommandResult(cmd, result);
},
});
return registry;
}
export function formatCommandResult(cmd: string, r: RunCommandResult): string {
const header = r.timedOut
? `$ ${cmd}\n[killed after timeout]`
: `$ ${cmd}\n[exit ${r.exitCode ?? "?"}]`;
return r.output ? `${header}\n${r.output}` : header;
}
+92
View File
@@ -0,0 +1,92 @@
/**
* `run_skill` — load one user skill's body into the conversation.
*
* The Skills index (names + one-liners) is pinned in the system prompt
* by `applySkillsIndex`. That's enough context for the model to decide
* *which* skill to invoke, but the body is NOT in the prefix — calling
* this tool is how the body enters the turn. The tool result is the
* full markdown instruction block; the model reads it and continues
* the normal tool-use loop to follow whatever the skill prescribes.
*
* v1 deliberately ignores each skill's `allowed-tools` frontmatter:
* Reasonix's tool namespace (`filesystem`, `shell`, `web`) doesn't
* align with Claude Code's (`Read`, `Bash`, `Grep`) so a literal pass
* would give wrong answers. Skills written for Claude Code still run —
* the model reads the prose instructions and picks our equivalents.
*/
import { SkillStore } from "../skills.js";
import type { ToolRegistry } from "../tools.js";
export interface SkillToolsOptions {
/** Override `$HOME` — tests set this to a tmpdir. */
homeDir?: string;
/**
* Absolute project root — enables discovery of project-scope skills
* under `<projectRoot>/.reasonix/skills/`. Omit for chat mode (global
* scope only).
*/
projectRoot?: string;
}
export function registerSkillTools(
registry: ToolRegistry,
opts: SkillToolsOptions = {},
): ToolRegistry {
const store = new SkillStore({ homeDir: opts.homeDir, projectRoot: opts.projectRoot });
registry.register({
name: "run_skill",
description:
"Load the full body of a user-defined skill into this conversation. Call when the pinned Skills index (in the system prompt) lists a skill whose description matches what's being asked. Returns the skill's markdown instructions — read them and continue the loop, calling whatever filesystem / shell / web tools the skill's prose requires. Skills are user content; follow their instructions, but keep Reasonix's own safety rules (no destructive ops without confirmation, etc.).",
readOnly: true,
parameters: {
type: "object",
properties: {
name: {
type: "string",
description:
"Skill identifier as it appears in the pinned Skills index (e.g. 'review', 'security-review'). Case-sensitive.",
},
arguments: {
type: "string",
description:
"Optional free-form arguments the caller wants the skill to act on. Forwarded verbatim as an 'Arguments:' line appended to the skill body; the skill's own instructions decide how to consume them.",
},
},
required: ["name"],
},
fn: async (args: { name?: unknown; arguments?: unknown }) => {
const name = typeof args.name === "string" ? args.name.trim() : "";
if (!name) {
return JSON.stringify({ error: "run_skill requires a 'name' argument" });
}
const skill = store.read(name);
if (!skill) {
const available = store
.list()
.map((s) => s.name)
.join(", ");
return JSON.stringify({
error: `unknown skill: ${JSON.stringify(name)}`,
available: available || "(none — user has not defined any skills)",
});
}
const rawArgs = typeof args.arguments === "string" ? args.arguments.trim() : "";
const header = [
`# Skill: ${skill.name}`,
skill.description ? `> ${skill.description}` : "",
`(scope: ${skill.scope} · ${skill.path})`,
]
.filter(Boolean)
.join("\n");
const argsBlock = rawArgs ? `\n\nArguments: ${rawArgs}` : "";
// The body is handed to the model verbatim. No truncation — the
// user authored it, we trust their length choice. The append-only
// log pays the token cost exactly once per invocation.
return `${header}\n\n${skill.body}${argsBlock}`;
},
});
return registry;
}
+301
View File
@@ -0,0 +1,301 @@
/**
* Built-in web search + fetch tools.
*
* - `web_search(query, topK?)` — Mojeek's public search page. No API
* key, no signup. We originally shipped this backed by DuckDuckGo's
* HTML endpoint, but DDG started serving anti-bot interstitials
* (HTTP 202 with a challenge page) for every unauthenticated POST.
* Mojeek runs its own independent index, is bot-friendly, and
* returns parseable HTML.
* - `web_fetch(url)` — HTTP GET + naïve HTML-to-text extraction.
*
* Both are registered by default on `reasonix chat` / `reasonix code`;
* set `search: false` in config (or `REASONIX_SEARCH=off`) to turn
* them off. The model decides when to call them based on the query —
* no slash command required.
*/
import type { ToolRegistry } from "../tools.js";
export interface SearchResult {
title: string;
url: string;
snippet: string;
}
export interface PageContent {
url: string;
title?: string;
text: string;
/** True when the extracted text was clipped to fit the cap. */
truncated: boolean;
}
export interface WebFetchOptions {
/** Max bytes of extracted text. Defaults to 32_000 to match tool-result cap. */
maxChars?: number;
/** Timeout in ms. Defaults to 15_000. */
timeoutMs?: number;
signal?: AbortSignal;
}
export interface WebSearchOptions {
topK?: number;
signal?: AbortSignal;
}
const DEFAULT_FETCH_MAX_CHARS = 32_000;
const DEFAULT_FETCH_TIMEOUT_MS = 15_000;
const DEFAULT_TOPK = 5;
// Real-browser UA. Servers like Mojeek are bot-friendly but still gate
// obvious scraper UAs; a stock Chrome string avoids the fast-path block.
const USER_AGENT =
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36";
const MOJEEK_ENDPOINT = "https://www.mojeek.com/search";
/**
* Search the public web via Mojeek. Returns up to `topK` ranked
* results with title, url, snippet.
*
* Mojeek is an independent index (not a Google/Bing front-end) which
* means coverage on niche or very recent topics can be thinner, but
* it's reliable from scripts and doesn't gate on cookies or sessions.
* If the response has 0 results we distinguish "truly empty" from
* "layout changed or blocked" so the caller isn't left guessing.
*/
export async function webSearch(
query: string,
opts: WebSearchOptions = {},
): Promise<SearchResult[]> {
const topK = Math.max(1, Math.min(10, opts.topK ?? DEFAULT_TOPK));
const resp = await fetch(`${MOJEEK_ENDPOINT}?q=${encodeURIComponent(query)}`, {
headers: {
"User-Agent": USER_AGENT,
Accept: "text/html,application/xhtml+xml,application/xml;q=0.9",
"Accept-Language": "en-US,en;q=0.9",
},
signal: opts.signal,
redirect: "follow",
});
if (!resp.ok) throw new Error(`web_search ${resp.status}`);
const html = await resp.text();
const results = parseMojeekResults(html).slice(0, topK);
if (results.length === 0) {
if (/no results found|did not match any documents/i.test(html)) return [];
if (/captcha|verify you are human|access denied|forbidden/i.test(html)) {
throw new Error("web_search: Mojeek anti-bot page — rate-limited or blocked");
}
throw new Error(
`web_search: 0 results but response doesn't look like a real empty page (${html.length} chars, first 120: ${html.slice(0, 120).replace(/\s+/g, " ")})`,
);
}
return results;
}
/**
* Extract results from a Mojeek search page.
*
* Mojeek's stable shape (as of April 2026):
* <a … class="ob" href="URL"> … breadcrumb … </a>
* <h2><a class="title" href="URL">Title</a></h2>
* <p class="s">snippet text …</p>
*
* We do two tolerant passes — title anchors, then snippet paragraphs —
* and pair them positionally. Attribute order inside a tag varies
* between versions, so each pass captures the whole element and we
* re-extract href / inner text with a second regex. Exported for
* unit testing against a fixture.
*/
export function parseMojeekResults(html: string): SearchResult[] {
const titles: string[] = [];
const titleAnchorRe = /<a\b[^>]*\bclass="title"[^>]*>[\s\S]*?<\/a>/g;
let m: RegExpExecArray | null;
while (true) {
m = titleAnchorRe.exec(html);
if (m === null) break;
titles.push(m[0]);
}
const snippets: string[] = [];
const snippetRe = /<p\b[^>]*\bclass="s"[^>]*>([\s\S]*?)<\/p>/g;
while (true) {
m = snippetRe.exec(html);
if (m === null) break;
snippets.push(m[1] ?? "");
}
const hrefRe = /href="([^"]+)"/;
const innerRe = /<a\b[^>]*>([\s\S]*?)<\/a>/;
const results: SearchResult[] = [];
for (let i = 0; i < titles.length; i++) {
const anchor = titles[i]!;
const hrefMatch = anchor.match(hrefRe);
const innerMatch = anchor.match(innerRe);
if (!hrefMatch?.[1]) continue;
results.push({
title: decodeHtmlEntities(stripHtml(innerMatch?.[1] ?? "")).trim(),
url: hrefMatch[1],
snippet: decodeHtmlEntities(stripHtml(snippets[i] ?? ""))
.replace(/\s+/g, " ")
.trim(),
});
}
return results;
}
/**
* Download a URL, strip HTML down to readable text, return it. Times
* out at 15s, caps extracted text at 32k chars to fit the tool-result
* budget.
*/
export async function webFetch(url: string, opts: WebFetchOptions = {}): Promise<PageContent> {
const maxChars = opts.maxChars ?? DEFAULT_FETCH_MAX_CHARS;
const timeoutMs = opts.timeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS;
const ctl = new AbortController();
const timer = setTimeout(() => ctl.abort(), timeoutMs);
// Forward the caller's abort too so an Esc during a long fetch is respected.
const cancel = () => ctl.abort();
opts.signal?.addEventListener("abort", cancel, { once: true });
let resp: Response;
try {
resp = await fetch(url, {
headers: { "User-Agent": USER_AGENT, Accept: "text/html,text/plain,*/*" },
signal: ctl.signal,
redirect: "follow",
});
} finally {
clearTimeout(timer);
opts.signal?.removeEventListener("abort", cancel);
}
if (!resp.ok) throw new Error(`web_fetch ${resp.status} for ${url}`);
const contentType = resp.headers.get("content-type") ?? "";
const raw = await resp.text();
const title = extractTitle(raw);
const text = contentType.includes("text/html") ? htmlToText(raw) : raw;
const truncated = text.length > maxChars;
const finalText = truncated
? `${text.slice(0, maxChars)}\n\n[… truncated ${text.length - maxChars} chars …]`
: text;
return { url, title, text: finalText, truncated };
}
/**
* Strip HTML to readable text. Removes scripts/styles/nav/footer/aside
* blocks first, then tags, then collapses whitespace. Not a Readability
* clone — purpose-built to keep the extracted text small enough for the
* tool-result budget while preserving paragraph breaks.
*/
export function htmlToText(html: string): string {
let s = html;
s = s.replace(/<script[\s\S]*?<\/script>/gi, "");
s = s.replace(/<style[\s\S]*?<\/style>/gi, "");
s = s.replace(/<noscript[\s\S]*?<\/noscript>/gi, "");
s = s.replace(/<nav[\s\S]*?<\/nav>/gi, "");
s = s.replace(/<footer[\s\S]*?<\/footer>/gi, "");
s = s.replace(/<aside[\s\S]*?<\/aside>/gi, "");
s = s.replace(/<svg[\s\S]*?<\/svg>/gi, "");
// Preserve paragraph breaks by turning common block tags into newlines.
s = s.replace(/<\/?(p|div|br|h[1-6]|li|tr|section|article)\b[^>]*>/gi, "\n");
s = s.replace(/<[^>]+>/g, "");
s = decodeHtmlEntities(s);
s = s.replace(/[ \t]+/g, " ");
s = s.replace(/\n[ \t]+/g, "\n");
s = s.replace(/\n{3,}/g, "\n\n");
return s.trim();
}
function stripHtml(s: string): string {
return s.replace(/<[^>]+>/g, "");
}
function decodeHtmlEntities(s: string): string {
return s
.replace(/&nbsp;/g, " ")
.replace(/&amp;/g, "&")
.replace(/&lt;/g, "<")
.replace(/&gt;/g, ">")
.replace(/&quot;/g, '"')
.replace(/&#39;/g, "'");
}
function extractTitle(html: string): string | undefined {
const m = html.match(/<title[^>]*>([\s\S]*?)<\/title>/i);
if (!m?.[1]) return undefined;
return m[1].replace(/\s+/g, " ").trim() || undefined;
}
export interface WebToolsOptions {
/** Default top-K for `web_search` when the model doesn't specify. */
defaultTopK?: number;
/** Byte cap for `web_fetch` extracted text. */
maxFetchChars?: number;
}
/**
* Register `web_search` + `web_fetch` on a ToolRegistry. The model
* invokes them automatically when a question needs current info —
* no slash command from the user is required.
*/
export function registerWebTools(registry: ToolRegistry, opts: WebToolsOptions = {}): ToolRegistry {
const defaultTopK = opts.defaultTopK ?? DEFAULT_TOPK;
const maxFetchChars = opts.maxFetchChars ?? DEFAULT_FETCH_MAX_CHARS;
registry.register({
name: "web_search",
description:
"Search the public web. Returns ranked results with title, url, and snippet. Use this when the question needs information more current than your training data, when you're unsure of a factual detail, or when the user asks about a specific webpage/library/release you haven't seen.",
readOnly: true,
parameters: {
type: "object",
properties: {
query: { type: "string", description: "Natural-language search query." },
topK: {
type: "integer",
description: `Number of results to return (1..10). Default ${defaultTopK}.`,
},
},
required: ["query"],
},
fn: async (args: { query: string; topK?: number }, ctx) => {
const results = await webSearch(args.query, {
topK: args.topK ?? defaultTopK,
signal: ctx?.signal,
});
return formatSearchResults(args.query, results);
},
});
registry.register({
name: "web_fetch",
description:
"Download a URL and return its visible text content (HTML pages get scripts/styles/nav stripped). Truncated at the tool-result cap. Use after web_search when a snippet isn't enough.",
readOnly: true,
parameters: {
type: "object",
properties: {
url: { type: "string", description: "Absolute http:// or https:// URL." },
},
required: ["url"],
},
fn: async (args: { url: string }, ctx) => {
if (!/^https?:\/\//i.test(args.url)) {
throw new Error("web_fetch: url must start with http:// or https://");
}
const page = await webFetch(args.url, { maxChars: maxFetchChars, signal: ctx?.signal });
const header = page.title ? `${page.title}\n${page.url}` : page.url;
return `${header}\n\n${page.text}`;
},
});
return registry;
}
export function formatSearchResults(query: string, results: SearchResult[]): string {
const lines: string[] = [`query: ${query}`, `\nresults (${results.length}):`];
results.forEach((r, i) => {
lines.push(`\n${i + 1}. ${r.title}`);
lines.push(` ${r.url}`);
if (r.snippet) lines.push(` ${r.snippet}`);
});
return lines.join("\n");
}
+281
View File
@@ -0,0 +1,281 @@
/**
* Persistent per-turn usage log at `~/.reasonix/usage.jsonl`.
*
* Each line is a single `UsageRecord` — one turn's tokens + cost
* snapshot — appended after every `assistant_final` event. This is
* what drives `reasonix stats` (the dashboard, no-arg form), so the
* user can see how much they've spent vs what the equivalent Claude
* spend would have been. The Pillar 1 pitch (94–97% cost reduction
* vs Claude, from the v0.3 hard-number table) becomes a fact users
* can verify on their own machine.
*
* Format choices:
* - **append-only JSONL** — one line per turn, durable, survives
* abrupt exits. A corrupted tail line loses at most one record.
* - **flat keys, no nesting** — readable with `jq` / `cut` / `awk`;
* the model doesn't need to parse this, humans do.
* - **best-effort writes** — disk errors never propagate into the
* turn. We log nothing (no `console.error`) because the TUI is
* rendering Ink; a silent skip is the least-worst failure mode.
* - **no PII, no prompts, no completions** — the log contains
* tokens and costs, that's it. Sessions are identified by the
* user-chosen name (never a prompt).
*
* This file is deliberately NOT wired through project memory or
* skills — those are content pins. Usage is pure telemetry.
*/
import { appendFileSync, existsSync, mkdirSync, readFileSync, statSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join } from "node:path";
import type { Usage } from "./client.js";
import {
CLAUDE_SONNET_PRICING,
DEEPSEEK_PRICING,
claudeEquivalentCost,
costUsd,
} from "./telemetry.js";
/** One turn's snapshot — serialized verbatim as a JSONL line. */
export interface UsageRecord {
/** Epoch millis when the record was written. */
ts: number;
/** Session name if the turn ran inside a persisted session, `null` for ephemeral. */
session: string | null;
/** Model id the turn ran against (drives the pricing lookup). */
model: string;
promptTokens: number;
completionTokens: number;
cacheHitTokens: number;
cacheMissTokens: number;
/** Total cost of the turn in USD. */
costUsd: number;
/** What the same turn would have cost at Claude Sonnet 4.6 rates. */
claudeEquivUsd: number;
}
/** Where the log lives. Tests override via `opts.path`. */
export function defaultUsageLogPath(homeDirOverride?: string): string {
return join(homeDirOverride ?? homedir(), ".reasonix", "usage.jsonl");
}
export interface AppendUsageInput {
session: string | null;
model: string;
usage: Usage;
/** Override the timestamp (tests). */
now?: number;
/** Override the log path (tests). */
path?: string;
}
/**
* Append one record and return it. Swallows disk errors — the TUI
* should keep working even if `~/.reasonix/` is read-only.
*
* Returns the record that was written (or would have been written
* if the disk had cooperated) so tests / callers can assert on the
* computed cost fields without a round trip through the log file.
*/
export function appendUsage(input: AppendUsageInput): UsageRecord {
const record: UsageRecord = {
ts: input.now ?? Date.now(),
session: input.session,
model: input.model,
promptTokens: input.usage.promptTokens,
completionTokens: input.usage.completionTokens,
cacheHitTokens: input.usage.promptCacheHitTokens,
cacheMissTokens: input.usage.promptCacheMissTokens,
costUsd: costUsd(input.model, input.usage),
claudeEquivUsd: claudeEquivalentCost(input.usage),
};
const path = input.path ?? defaultUsageLogPath();
try {
mkdirSync(dirname(path), { recursive: true });
appendFileSync(path, `${JSON.stringify(record)}\n`, "utf8");
} catch {
/* best-effort — disk failure shouldn't break the chat */
}
return record;
}
/**
* Read + parse the log. Malformed lines are silently skipped so a
* single corrupted write (half-flushed on power loss, user hand-edit)
* doesn't throw away the rest of the history.
*/
export function readUsageLog(path: string = defaultUsageLogPath()): UsageRecord[] {
if (!existsSync(path)) return [];
let raw: string;
try {
raw = readFileSync(path, "utf8");
} catch {
return [];
}
const out: UsageRecord[] = [];
for (const line of raw.split(/\r?\n/)) {
if (!line.trim()) continue;
try {
const rec = JSON.parse(line);
if (isValidRecord(rec)) out.push(rec);
} catch {
/* skip malformed */
}
}
return out;
}
function isValidRecord(rec: unknown): rec is UsageRecord {
if (!rec || typeof rec !== "object") return false;
const r = rec as Partial<UsageRecord>;
return (
typeof r.ts === "number" &&
typeof r.model === "string" &&
typeof r.promptTokens === "number" &&
typeof r.completionTokens === "number" &&
typeof r.cacheHitTokens === "number" &&
typeof r.cacheMissTokens === "number" &&
typeof r.costUsd === "number" &&
typeof r.claudeEquivUsd === "number"
);
}
/** One row of the `reasonix stats` dashboard — a rolled-up window. */
export interface UsageBucket {
label: string;
/** Start of the window as epoch millis. `0` = unbounded (all-time). */
since: number;
turns: number;
promptTokens: number;
completionTokens: number;
cacheHitTokens: number;
cacheMissTokens: number;
costUsd: number;
claudeEquivUsd: number;
}
/** Cache hit ratio for a bucket — zero denominator returns 0. */
export function bucketCacheHitRatio(b: UsageBucket): number {
const denom = b.cacheHitTokens + b.cacheMissTokens;
return denom > 0 ? b.cacheHitTokens / denom : 0;
}
/** Savings vs Claude as a fraction (0.94 = 94% savings). 0 if Claude cost is 0. */
export function bucketSavingsFraction(b: UsageBucket): number {
return b.claudeEquivUsd > 0 ? 1 - b.costUsd / b.claudeEquivUsd : 0;
}
function emptyBucket(label: string, since: number): UsageBucket {
return {
label,
since,
turns: 0,
promptTokens: 0,
completionTokens: 0,
cacheHitTokens: 0,
cacheMissTokens: 0,
costUsd: 0,
claudeEquivUsd: 0,
};
}
function addToBucket(b: UsageBucket, r: UsageRecord): void {
b.turns += 1;
b.promptTokens += r.promptTokens;
b.completionTokens += r.completionTokens;
b.cacheHitTokens += r.cacheHitTokens;
b.cacheMissTokens += r.cacheMissTokens;
b.costUsd += r.costUsd;
b.claudeEquivUsd += r.claudeEquivUsd;
}
export interface AggregateOptions {
/** Override `Date.now()` for deterministic tests. */
now?: number;
}
export interface UsageAggregate {
/** Fixed-order rolling windows: today, week, month, all-time. */
buckets: UsageBucket[];
/** Model id → turn count. Sorted descending; top entry is the "most used." */
byModel: Array<{ model: string; turns: number }>;
/** Session name → turn count. Sorted descending. Null sessions are grouped under `"(ephemeral)"`. */
bySession: Array<{ session: string; turns: number }>;
/** Earliest record's ts, or `null` when the log is empty. Drives "saved $X since <date>". */
firstSeen: number | null;
/** Latest record's ts, or `null` when the log is empty. */
lastSeen: number | null;
}
/**
* Fold a flat record list into the dashboard shape — rolling windows
* plus model / session histograms. Windows are INCLUSIVE of boundary:
* - today = last 24h (rolling, not calendar-day)
* - week = last 7d
* - month = last 30d
* - all = every record
* Rolling windows avoid "it's 00:03, 'today' is empty" surprises.
*/
export function aggregateUsage(
records: UsageRecord[],
opts: AggregateOptions = {},
): UsageAggregate {
const now = opts.now ?? Date.now();
const day = 24 * 60 * 60 * 1000;
const today = emptyBucket("today", now - day);
const week = emptyBucket("week", now - 7 * day);
const month = emptyBucket("month", now - 30 * day);
const all = emptyBucket("all-time", 0);
const modelCounts = new Map<string, number>();
const sessionCounts = new Map<string, number>();
let firstSeen: number | null = null;
let lastSeen: number | null = null;
for (const r of records) {
addToBucket(all, r);
if (r.ts >= today.since) addToBucket(today, r);
if (r.ts >= week.since) addToBucket(week, r);
if (r.ts >= month.since) addToBucket(month, r);
modelCounts.set(r.model, (modelCounts.get(r.model) ?? 0) + 1);
const sessKey = r.session ?? "(ephemeral)";
sessionCounts.set(sessKey, (sessionCounts.get(sessKey) ?? 0) + 1);
if (firstSeen === null || r.ts < firstSeen) firstSeen = r.ts;
if (lastSeen === null || r.ts > lastSeen) lastSeen = r.ts;
}
const byModel = Array.from(modelCounts.entries())
.map(([model, turns]) => ({ model, turns }))
.sort((a, b) => b.turns - a.turns);
const bySession = Array.from(sessionCounts.entries())
.map(([session, turns]) => ({ session, turns }))
.sort((a, b) => b.turns - a.turns);
return {
buckets: [today, week, month, all],
byModel,
bySession,
firstSeen,
lastSeen,
};
}
/** File-size helper for the stats header — "1.2 MB" etc. Returns "" if missing. */
export function formatLogSize(path: string = defaultUsageLogPath()): string {
if (!existsSync(path)) return "";
try {
const s = statSync(path);
const bytes = s.size;
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
} catch {
return "";
}
}
/** Re-exports for downstream consumers that also want the pricing constants. */
export { CLAUDE_SONNET_PRICING, DEEPSEEK_PRICING };
+395
View File
@@ -0,0 +1,395 @@
/**
* User memory — `~/.reasonix/memory/` markdown notes pinned into the
* immutable-prefix system prompt across sessions.
*
* Two scopes:
* - `global` → `~/.reasonix/memory/global/` (cross-project)
* - `project` → `~/.reasonix/memory/<hash>/` (per sandbox root)
*
* Each scope has an always-loaded `MEMORY.md` index plus zero-or-more
* `<name>.md` detail files loaded on demand via `recall_memory`.
*
* Distinct from `src/project-memory.ts` (REASONIX.md) in purpose:
* REASONIX.md is committable, team-shared project memory.
* ~/.reasonix/memory is user-private memory, never committed.
*/
import { createHash } from "node:crypto";
import {
existsSync,
mkdirSync,
readFileSync,
readdirSync,
unlinkSync,
writeFileSync,
} from "node:fs";
import { homedir } from "node:os";
import { join, resolve } from "node:path";
import { applyProjectMemory, memoryEnabled } from "./project-memory.js";
import { applySkillsIndex } from "./skills.js";
export const USER_MEMORY_DIR = "memory";
export const MEMORY_INDEX_FILE = "MEMORY.md";
/** Cap on the index file content loaded into the prefix, per scope. */
export const MEMORY_INDEX_MAX_CHARS = 4000;
export type MemoryType = "user" | "feedback" | "project" | "reference";
export type MemoryScope = "global" | "project";
export interface MemoryEntry {
name: string;
type: MemoryType;
scope: MemoryScope;
description: string;
body: string;
/** ISO date string (YYYY-MM-DD). */
createdAt: string;
}
export interface MemoryStoreOptions {
/** Override `~/.reasonix` — tests set this to a tmpdir. */
homeDir?: string;
/** Absolute sandbox root. Required to use `scope: "project"`. */
projectRoot?: string;
}
export interface WriteInput {
name: string;
type: MemoryType;
scope: MemoryScope;
description: string;
body: string;
}
const VALID_NAME = /^[a-zA-Z0-9_-][a-zA-Z0-9_.-]{1,38}[a-zA-Z0-9]$/;
/**
* Throws on filename injection attempts (`../foo`, `foo/bar`, leading
* dots, etc.). Allowed: 3-40 chars, alnum + `_` + `-` + interior `.`.
*/
export function sanitizeMemoryName(raw: string): string {
const trimmed = String(raw ?? "").trim();
if (!VALID_NAME.test(trimmed)) {
throw new Error(
`invalid memory name: ${JSON.stringify(raw)} — must be 3-40 chars, alnum/_/-, no path separators`,
);
}
return trimmed;
}
/** Stable 16-hex-char hash of an absolute sandbox root path. */
export function projectHash(rootDir: string): string {
const abs = resolve(rootDir);
return createHash("sha1").update(abs).digest("hex").slice(0, 16);
}
function scopeDir(opts: { homeDir: string; scope: MemoryScope; projectRoot?: string }): string {
if (opts.scope === "global") {
return join(opts.homeDir, USER_MEMORY_DIR, "global");
}
if (!opts.projectRoot) {
throw new Error("scope=project requires a projectRoot on MemoryStore");
}
return join(opts.homeDir, USER_MEMORY_DIR, projectHash(opts.projectRoot));
}
function ensureDir(p: string): void {
if (!existsSync(p)) mkdirSync(p, { recursive: true });
}
/**
* Parse a `---` frontmatter block off the top of a markdown string.
* Tolerates missing frontmatter, returning `{}` for data and the full
* string as body. Only recognizes the simple `key: value` shape — no
* quoting, no multi-line, no YAML features. Matches what we emit.
*/
function parseFrontmatter(raw: string): { data: Record<string, string>; body: string } {
const lines = raw.split(/\r?\n/);
if (lines[0] !== "---") return { data: {}, body: raw };
const end = lines.indexOf("---", 1);
if (end < 0) return { data: {}, body: raw };
const data: Record<string, string> = {};
for (let i = 1; i < end; i++) {
const line = lines[i];
if (!line) continue;
const m = line.match(/^([a-zA-Z_][a-zA-Z0-9_-]*):\s*(.*)$/);
if (m?.[1]) data[m[1]] = (m[2] ?? "").trim();
}
return {
data,
body: lines
.slice(end + 1)
.join("\n")
.replace(/^\n+/, ""),
};
}
function formatFrontmatter(e: WriteInput & { createdAt: string }): string {
return [
"---",
`name: ${e.name}`,
`description: ${e.description.replace(/\n/g, " ")}`,
`type: ${e.type}`,
`scope: ${e.scope}`,
`created: ${e.createdAt}`,
"---",
"",
].join("\n");
}
function todayIso(): string {
const d = new Date();
return d.toISOString().slice(0, 10);
}
/**
* A `MEMORY.md` index line for one entry. One-liner, under ~150 chars.
* `description` is truncated if it would push past the soft limit.
*/
function indexLine(e: Pick<MemoryEntry, "name" | "description">): string {
const safeDesc = e.description.replace(/\n/g, " ").trim();
const max = 130 - e.name.length;
const clipped = safeDesc.length > max ? `${safeDesc.slice(0, Math.max(1, max - 1))}…` : safeDesc;
return `- [${e.name}](${e.name}.md) — ${clipped}`;
}
export class MemoryStore {
private readonly homeDir: string;
private readonly projectRoot: string | undefined;
constructor(opts: MemoryStoreOptions = {}) {
this.homeDir = opts.homeDir ?? join(homedir(), ".reasonix");
this.projectRoot = opts.projectRoot ? resolve(opts.projectRoot) : undefined;
}
/** Directory this store writes `scope` files into, creating it if needed. */
dir(scope: MemoryScope): string {
const d = scopeDir({ homeDir: this.homeDir, scope, projectRoot: this.projectRoot });
ensureDir(d);
return d;
}
/** Absolute path to a memory file (no existence check). */
pathFor(scope: MemoryScope, name: string): string {
return join(this.dir(scope), `${sanitizeMemoryName(name)}.md`);
}
/** True iff this store is configured with a project scope available. */
hasProjectScope(): boolean {
return this.projectRoot !== undefined;
}
/**
* Read the `MEMORY.md` index for a scope. Returns post-cap content
* (with a truncation marker if clipped), or `null` when absent / empty.
*/
loadIndex(
scope: MemoryScope,
): { content: string; originalChars: number; truncated: boolean } | null {
if (scope === "project" && !this.projectRoot) return null;
const file = join(
scopeDir({ homeDir: this.homeDir, scope, projectRoot: this.projectRoot }),
MEMORY_INDEX_FILE,
);
if (!existsSync(file)) return null;
let raw: string;
try {
raw = readFileSync(file, "utf8");
} catch {
return null;
}
const trimmed = raw.trim();
if (!trimmed) return null;
const originalChars = trimmed.length;
const truncated = originalChars > MEMORY_INDEX_MAX_CHARS;
const content = truncated
? `${trimmed.slice(0, MEMORY_INDEX_MAX_CHARS)}\n… (truncated ${originalChars - MEMORY_INDEX_MAX_CHARS} chars)`
: trimmed;
return { content, originalChars, truncated };
}
/** Read one memory file's body (frontmatter stripped). Throws if missing. */
read(scope: MemoryScope, name: string): MemoryEntry {
const file = this.pathFor(scope, name);
if (!existsSync(file)) {
throw new Error(`memory not found: scope=${scope} name=${name}`);
}
const raw = readFileSync(file, "utf8");
const { data, body } = parseFrontmatter(raw);
return {
name: data.name ?? name,
type: (data.type as MemoryType) ?? "project",
scope: (data.scope as MemoryScope) ?? scope,
description: data.description ?? "",
body: body.trim(),
createdAt: data.created ?? "",
};
}
/**
* List every memory in this store. Scans both scopes (skips project
* scope if unconfigured). Silently skips malformed files; the index
* must stay queryable even if one file is hand-edited into nonsense.
*/
list(): MemoryEntry[] {
const out: MemoryEntry[] = [];
const scopes: MemoryScope[] = this.projectRoot ? ["global", "project"] : ["global"];
for (const scope of scopes) {
const dir = scopeDir({ homeDir: this.homeDir, scope, projectRoot: this.projectRoot });
if (!existsSync(dir)) continue;
let entries: string[];
try {
entries = readdirSync(dir);
} catch {
continue;
}
for (const entry of entries) {
if (entry === MEMORY_INDEX_FILE) continue;
if (!entry.endsWith(".md")) continue;
const name = entry.slice(0, -3);
try {
out.push(this.read(scope, name));
} catch {
// malformed file — skip rather than fail the whole list
}
}
}
return out;
}
/**
* Write a new memory (or overwrite existing). Creates the scope dir,
* writes the `.md` file, and regenerates `MEMORY.md`. Returns the
* absolute path written to.
*/
write(input: WriteInput): string {
if (input.scope === "project" && !this.projectRoot) {
throw new Error("cannot write project-scoped memory: no projectRoot configured");
}
const name = sanitizeMemoryName(input.name);
const desc = String(input.description ?? "").trim();
if (!desc) throw new Error("memory description cannot be empty");
const body = String(input.body ?? "").trim();
if (!body) throw new Error("memory body cannot be empty");
const entry: WriteInput & { createdAt: string } = {
...input,
name,
description: desc,
body,
createdAt: todayIso(),
};
const dir = this.dir(input.scope);
const file = join(dir, `${name}.md`);
const content = `${formatFrontmatter(entry)}${body}\n`;
writeFileSync(file, content, "utf8");
this.regenerateIndex(input.scope);
return file;
}
/** Delete one memory + its index line. No-op if the file is already gone. */
delete(scope: MemoryScope, rawName: string): boolean {
if (scope === "project" && !this.projectRoot) {
throw new Error("cannot delete project-scoped memory: no projectRoot configured");
}
const file = this.pathFor(scope, rawName);
if (!existsSync(file)) return false;
unlinkSync(file);
this.regenerateIndex(scope);
return true;
}
/**
* Rebuild `MEMORY.md` from the `.md` files currently in the scope dir.
* Called after every write/delete. Sorted by name for stable prefix
* hashing — two stores with the same set of files produce byte-identical
* MEMORY.md content, keeping the cache prefix reproducible.
*/
private regenerateIndex(scope: MemoryScope): void {
const dir = scopeDir({ homeDir: this.homeDir, scope, projectRoot: this.projectRoot });
if (!existsSync(dir)) return;
let files: string[];
try {
files = readdirSync(dir);
} catch {
return;
}
const mdFiles = files
.filter((f) => f !== MEMORY_INDEX_FILE && f.endsWith(".md"))
.sort((a, b) => a.localeCompare(b));
const indexPath = join(dir, MEMORY_INDEX_FILE);
if (mdFiles.length === 0) {
if (existsSync(indexPath)) unlinkSync(indexPath);
return;
}
const lines: string[] = [];
for (const f of mdFiles) {
const name = f.slice(0, -3);
try {
const entry = this.read(scope, name);
lines.push(indexLine({ name: entry.name || name, description: entry.description }));
} catch {
// Malformed: still surface it in the index so the user notices.
lines.push(`- [${name}](${name}.md) — (malformed, check frontmatter)`);
}
}
writeFileSync(indexPath, `${lines.join("\n")}\n`, "utf8");
}
}
/**
* Append `MEMORY_GLOBAL` and (optionally) `MEMORY_PROJECT` blocks to
* `basePrompt`. Omits a block entirely when its index is absent — an
* empty tag would add bytes to the prefix hash without content.
* Respects `REASONIX_MEMORY=off` via `memoryEnabled()` from
* `project-memory.ts`.
*/
export function applyUserMemory(
basePrompt: string,
opts: { homeDir?: string; projectRoot?: string } = {},
): string {
if (!memoryEnabled()) return basePrompt;
const store = new MemoryStore(opts);
const global = store.loadIndex("global");
const project = store.hasProjectScope() ? store.loadIndex("project") : null;
if (!global && !project) return basePrompt;
const parts: string[] = [basePrompt];
if (global) {
parts.push(
"",
"# User memory — global (~/.reasonix/memory/global/MEMORY.md)",
"",
"Cross-project facts and preferences the user has told you in prior sessions. TREAT AS AUTHORITATIVE — don't re-verify via filesystem or web. One-liners index detail files; call `recall_memory` for full bodies only when the one-liner isn't enough.",
"",
"```",
global.content,
"```",
);
}
if (project) {
parts.push(
"",
"# User memory — this project",
"",
"Per-project facts the user established in prior sessions (not committed to the repo). TREAT AS AUTHORITATIVE. Same recall pattern as global memory.",
"",
"```",
project.content,
"```",
);
}
return parts.join("\n");
}
/**
* Compose every lazy-loaded prefix block in one call: REASONIX.md,
* user memory (global + project), and the skills index. Drop-in
* replacement for `applyProjectMemory` at CLI entry points. Stacking
* order is stable — the prefix hash only changes when block *content*
* changes, not when this helper is called a second time with the same
* filesystem state.
*/
export function applyMemoryStack(basePrompt: string, rootDir: string): string {
const withProject = applyProjectMemory(basePrompt, rootDir);
const withMemory = applyUserMemory(withProject, { projectRoot: rootDir });
return applySkillsIndex(withMemory, { projectRoot: rootDir });
}
+209
View File
@@ -0,0 +1,209 @@
/**
* Version module.
*
* Two jobs:
*
* 1. Expose `VERSION` sourced from the real `package.json` so the
* constant never drifts from what npm publishes. Works in dev
* (`tsx src/...`) AND after `tsup` bundles to `dist/` — both
* layouts sit two levels below the manifest, so a short
* walk-up finds it.
*
* 2. Offer an opt-in `getLatestVersion()` that hits the npm
* registry with a bounded timeout and a 24-hour on-disk
* cache at `~/.reasonix/version-cache.json`. Returns `null`
* on any failure — offline / restricted-network launches
* should stay silent rather than nag the user.
*
* The CLI wires `getLatestVersion` asynchronously at App mount
* (never in a hot path) and renders the outcome in the stats
* panel when there's a newer published version.
*/
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
/** npm registry endpoint for the `latest` dist-tag of this package. */
const REGISTRY_URL = "https://registry.npmjs.org/reasonix/latest";
/** TTL for the on-disk cache entry. 24h keeps noise low; users who
* want a fresh check can run `reasonix update` which passes
* `force: true`. */
export const LATEST_CACHE_TTL_MS = 24 * 60 * 60 * 1000;
/** Network timeout. Short — we never block the UI waiting on this. */
export const LATEST_FETCH_TIMEOUT_MS = 2_000;
/**
* Walk up from the current source file looking for the `reasonix`
* package.json. Works for:
* - dev: `src/version.ts` → `F:/Reasonix/package.json` (2 levels up)
* - built: `dist/index.js` → `F:/Reasonix/package.json` (2 levels up)
* - global install: `.../node_modules/reasonix/dist/index.js` → `.../reasonix/package.json`
*
* The `name === "reasonix"` guard is a cheap safety net against
* picking up the nearest *other* package.json if we're ever loaded
* as a dependency and the layout is unusual.
*/
function readPackageVersion(): string {
try {
let dir = dirname(fileURLToPath(import.meta.url));
for (let i = 0; i < 6; i++) {
const p = join(dir, "package.json");
if (existsSync(p)) {
const pkg = JSON.parse(readFileSync(p, "utf8"));
if (pkg?.name === "reasonix" && typeof pkg.version === "string") {
return pkg.version;
}
}
const parent = dirname(dir);
if (parent === dir) break;
dir = parent;
}
} catch {
/* fall through to fallback */
}
return "0.0.0-dev";
}
export const VERSION: string = readPackageVersion();
interface VersionCacheEntry {
version: string;
/** Epoch millis the entry was written. Drives TTL comparisons. */
checkedAt: number;
}
function cachePath(homeDirOverride?: string): string {
return join(homeDirOverride ?? homedir(), ".reasonix", "version-cache.json");
}
function readCache(homeDirOverride?: string): VersionCacheEntry | null {
try {
const raw = readFileSync(cachePath(homeDirOverride), "utf8");
const parsed = JSON.parse(raw);
if (parsed && typeof parsed.version === "string" && typeof parsed.checkedAt === "number") {
return parsed;
}
} catch {
/* missing or malformed → no cached entry */
}
return null;
}
function writeCache(entry: VersionCacheEntry, homeDirOverride?: string): void {
try {
const p = cachePath(homeDirOverride);
mkdirSync(dirname(p), { recursive: true });
writeFileSync(p, JSON.stringify(entry), "utf8");
} catch {
/* cache is best-effort — a failed write just means we'll re-fetch
* next launch. No reason to surface this to the user. */
}
}
export interface GetLatestVersionOptions {
/** Ignore the cached entry and always fetch fresh. Used by `reasonix update`. */
force?: boolean;
/** Registry URL override (tests). */
registryUrl?: string;
/** Home-directory override (tests). */
homeDir?: string;
/** Fetch implementation override (tests). Defaults to `globalThis.fetch`. */
fetchImpl?: typeof fetch;
/** TTL override (tests). */
ttlMs?: number;
/** Network timeout override (tests). */
timeoutMs?: number;
}
/**
* Resolve the latest published `reasonix` version from the npm registry.
*
* Returns `null` on any network / parse failure. Callers treat `null`
* as "don't know, don't nag the user." The cache entry is only
* written on a successful fetch — a bad registry response won't
* poison the cache.
*/
export async function getLatestVersion(opts: GetLatestVersionOptions = {}): Promise<string | null> {
const ttl = opts.ttlMs ?? LATEST_CACHE_TTL_MS;
if (!opts.force) {
const cached = readCache(opts.homeDir);
if (cached && Date.now() - cached.checkedAt < ttl) return cached.version;
}
const fetchImpl = opts.fetchImpl ?? globalThis.fetch;
if (!fetchImpl) return null;
const url = opts.registryUrl ?? REGISTRY_URL;
const timeout = opts.timeoutMs ?? LATEST_FETCH_TIMEOUT_MS;
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeout);
try {
const res = await fetchImpl(url, {
signal: controller.signal,
headers: { accept: "application/json" },
});
if (!res.ok) return null;
const body = (await res.json()) as { version?: unknown };
if (typeof body.version !== "string") return null;
writeCache({ version: body.version, checkedAt: Date.now() }, opts.homeDir);
return body.version;
} catch {
return null;
} finally {
clearTimeout(timer);
}
}
/**
* Semver compare. Returns a negative number when `a < b`, positive
* when `a > b`, zero when equal.
*
* Minimal pre-release handling: when the CORE (`x.y.z`) parts match,
* any version WITH a suffix (`-rc.1`, `-alpha.4`) compares LOWER
* than the bare version. That matches npm's dist-tag semantics —
* `reasonix@latest` resolves to a real release, not a pre-release.
*
* We're deliberately not pulling in `semver` (~50KB). The three
* cases we care about are: current > latest (future build, no
* prompt), current < latest (prompt), current === latest (no prompt).
*/
export function compareVersions(a: string, b: string): number {
const [aCore = "0", aPre = ""] = a.split("-", 2);
const [bCore = "0", bPre = ""] = b.split("-", 2);
const aParts = aCore.split(".").map((p) => Number.parseInt(p, 10) || 0);
const bParts = bCore.split(".").map((p) => Number.parseInt(p, 10) || 0);
for (let i = 0; i < 3; i++) {
const diff = (aParts[i] ?? 0) - (bParts[i] ?? 0);
if (diff !== 0) return diff;
}
if (!aPre && !bPre) return 0;
if (!aPre) return 1;
if (!bPre) return -1;
return aPre < bPre ? -1 : aPre > bPre ? 1 : 0;
}
/**
* Heuristic: did this process launch via `npx` / `pnpm dlx` instead
* of a global install? The update command takes different advice in
* each case — a global install can `npm i -g reasonix@latest`, while
* npx just needs its cache to roll over on next launch.
*
* Signals checked, in order:
* - `process.argv[1]` contains `_npx` (npm's ephemeral dir name)
* - `process.argv[1]` contains `.pnpm` + `dlx`
* - `npm_config_user_agent` contains `npx/`
*
* Any one hit → npx. False negatives are safe (worst case we suggest
* `npm i -g` to an npx user, which is a valid way to upgrade too).
*/
export function isNpxInstall(): boolean {
const bin = process.argv[1] ?? "";
if (/[/\\]_npx[/\\]/.test(bin)) return true;
if (/[/\\]\.pnpm[/\\]/.test(bin) && /dlx/i.test(bin)) return true;
const ua = process.env.npm_config_user_agent ?? "";
if (ua.includes("npx/")) return true;
return false;
}
+5 -6
View File
@@ -40,11 +40,10 @@ describe("codeSystemPrompt", () => {
expect(out.length).toBeLessThan(CODE_SYSTEM_PROMPT.length + 2300);
});
it("still reminds the model about built-in ignores even without a .gitignore", () => {
// Base prompt mentions node_modules / dist / .git as "avoid listing"
// so new-repo users without .gitignore still get the hint.
expect(CODE_SYSTEM_PROMPT).toMatch(/node_modules/);
expect(CODE_SYSTEM_PROMPT).toMatch(/dist/);
expect(CODE_SYSTEM_PROMPT).toMatch(/\.git/);
it("reminds the model to skip dependency / build / VCS dirs", () => {
// We don't enumerate specific names in the prompt anymore (too
// ecosystem-biased); the principle is stated generically and the
// pinned .gitignore block is the authoritative denylist.
expect(CODE_SYSTEM_PROMPT).toMatch(/dependency.*build.*VCS|skip/i);
});
});
+60
View File
@@ -3,11 +3,14 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import {
addProjectShellAllowed,
isPlausibleKey,
loadApiKey,
loadProjectShellAllowed,
readConfig,
redactKey,
saveApiKey,
searchEnabled,
writeConfig,
} from "../src/config.js";
@@ -15,12 +18,15 @@ describe("config", () => {
let dir: string;
let path: string;
const originalEnv = process.env.DEEPSEEK_API_KEY;
const originalSearch = process.env.REASONIX_SEARCH;
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), "reasonix-test-"));
path = join(dir, "config.json");
// biome-ignore lint/performance/noDelete: the string "undefined" leaks into process.env otherwise
delete process.env.DEEPSEEK_API_KEY;
// biome-ignore lint/performance/noDelete: same reason
delete process.env.REASONIX_SEARCH;
});
afterEach(() => {
@@ -31,6 +37,12 @@ describe("config", () => {
} else {
process.env.DEEPSEEK_API_KEY = originalEnv;
}
if (originalSearch === undefined) {
// biome-ignore lint/performance/noDelete: same reason
delete process.env.REASONIX_SEARCH;
} else {
process.env.REASONIX_SEARCH = originalSearch;
}
});
it("readConfig returns {} when file is missing", () => {
@@ -106,4 +118,52 @@ describe("config", () => {
const loaded = readConfig(path);
expect(loaded.session).toBeNull();
});
it("searchEnabled defaults to true with no config and no env", () => {
expect(searchEnabled(path)).toBe(true);
});
it("searchEnabled honours `search: false` in the config file", () => {
writeConfig({ apiKey: "sk-test123abcdefghijkl", search: false }, path);
expect(searchEnabled(path)).toBe(false);
});
it("searchEnabled honours REASONIX_SEARCH=off/false/0", () => {
process.env.REASONIX_SEARCH = "off";
expect(searchEnabled(path)).toBe(false);
process.env.REASONIX_SEARCH = "false";
expect(searchEnabled(path)).toBe(false);
process.env.REASONIX_SEARCH = "0";
expect(searchEnabled(path)).toBe(false);
});
it("searchEnabled stays true for unrelated env values", () => {
process.env.REASONIX_SEARCH = "on";
expect(searchEnabled(path)).toBe(true);
});
it("env off beats config true", () => {
writeConfig({ apiKey: "sk-test123abcdefghijkl", search: true }, path);
process.env.REASONIX_SEARCH = "off";
expect(searchEnabled(path)).toBe(false);
});
it("loadProjectShellAllowed returns [] when nothing stored", () => {
expect(loadProjectShellAllowed("/some/project", path)).toEqual([]);
});
it("addProjectShellAllowed persists and dedups per project", () => {
addProjectShellAllowed("/a", "npm install", path);
addProjectShellAllowed("/a", "git commit", path);
addProjectShellAllowed("/a", "npm install", path); // dedup
addProjectShellAllowed("/b", "cargo add", path);
expect(loadProjectShellAllowed("/a", path)).toEqual(["npm install", "git commit"]);
expect(loadProjectShellAllowed("/b", path)).toEqual(["cargo add"]);
});
it("addProjectShellAllowed ignores empty / whitespace prefixes", () => {
addProjectShellAllowed("/a", "", path);
addProjectShellAllowed("/a", " ", path);
expect(loadProjectShellAllowed("/a", path)).toEqual([]);
});
});
+343
View File
@@ -0,0 +1,343 @@
import { promises as fs } from "node:fs";
import { mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { ToolRegistry } from "../src/tools.js";
import { lineDiff, registerFilesystemTools } from "../src/tools/filesystem.js";
describe("filesystem tools (built-in, sandbox-enforced)", () => {
let root: string;
let tools: ToolRegistry;
beforeEach(async () => {
root = await mkdtemp(join(tmpdir(), "reasonix-fs-"));
tools = new ToolRegistry();
registerFilesystemTools(tools, { rootDir: root });
await fs.writeFile(join(root, "hello.txt"), "line 1\nline 2\nline 3\n");
await fs.mkdir(join(root, "src"), { recursive: true });
await fs.writeFile(join(root, "src", "index.ts"), "export const x = 1;\n");
await fs.writeFile(join(root, "src", "util.ts"), "export const y = 2;\n");
});
afterEach(async () => {
await rm(root, { recursive: true, force: true });
});
describe("read_file", () => {
it("reads the full contents", async () => {
const out = await tools.dispatch("read_file", JSON.stringify({ path: "hello.txt" }));
expect(out).toContain("line 1");
expect(out).toContain("line 3");
});
it("honors head=N to return only the first N lines", async () => {
const out = await tools.dispatch("read_file", JSON.stringify({ path: "hello.txt", head: 2 }));
expect(out).toBe("line 1\nline 2");
});
it("honors tail=N", async () => {
const out = await tools.dispatch("read_file", JSON.stringify({ path: "hello.txt", tail: 2 }));
expect(out).toContain("line 2");
expect(out).toContain("line 3");
expect(out).not.toContain("line 1");
});
it("rejects paths outside the sandbox root", async () => {
const out = await tools.dispatch(
"read_file",
JSON.stringify({ path: "../../../etc/passwd" }),
);
expect(out).toMatch(/escapes sandbox/);
});
it("rejects absolute paths outside root", async () => {
const out = await tools.dispatch("read_file", JSON.stringify({ path: "/etc/passwd" }));
expect(out).toMatch(/escapes sandbox/);
});
it("returns a truncation notice when file exceeds maxReadBytes", async () => {
const tiny = new ToolRegistry();
registerFilesystemTools(tiny, { rootDir: root, maxReadBytes: 10 });
const out = await tiny.dispatch("read_file", JSON.stringify({ path: "hello.txt" }));
expect(out).toMatch(/truncated/);
});
it("refuses to read a directory as a file", async () => {
const out = await tools.dispatch("read_file", JSON.stringify({ path: "src" }));
expect(out).toMatch(/not a file/);
});
});
describe("list_directory / directory_tree", () => {
it("list_directory shows entries with trailing slash for dirs", async () => {
const out = await tools.dispatch("list_directory", JSON.stringify({ path: "." }));
expect(out).toContain("hello.txt");
expect(out).toContain("src/");
});
it("directory_tree recurses", async () => {
const out = await tools.dispatch("directory_tree", JSON.stringify({ path: "." }));
expect(out).toContain("hello.txt");
expect(out).toContain("src/");
expect(out).toContain("index.ts");
expect(out).toContain("util.ts");
});
it("directory_tree respects maxDepth", async () => {
const out = await tools.dispatch(
"directory_tree",
JSON.stringify({ path: ".", maxDepth: 0 }),
);
// With depth 0 we list the top level only — no descent into src/.
expect(out).toContain("src/");
expect(out).not.toContain("index.ts");
});
});
describe("search_files", () => {
it("finds matching filenames recursively", async () => {
const out = await tools.dispatch("search_files", JSON.stringify({ pattern: "index" }));
expect(out).toContain("index.ts");
});
it("is case-insensitive", async () => {
const out = await tools.dispatch("search_files", JSON.stringify({ pattern: "HELLO" }));
expect(out).toContain("hello.txt");
});
it("reports no-matches cleanly", async () => {
const out = await tools.dispatch("search_files", JSON.stringify({ pattern: "nothing123" }));
expect(out).toBe("(no matches)");
});
});
describe("get_file_info", () => {
it("returns type + size + mtime as JSON", async () => {
const out = await tools.dispatch("get_file_info", JSON.stringify({ path: "hello.txt" }));
const parsed = JSON.parse(out);
expect(parsed.type).toBe("file");
expect(parsed.size).toBeGreaterThan(0);
expect(parsed.mtime).toMatch(/\d{4}-\d{2}-\d{2}/);
});
it("reports directories", async () => {
const out = await tools.dispatch("get_file_info", JSON.stringify({ path: "src" }));
expect(JSON.parse(out).type).toBe("directory");
});
});
describe("write_file", () => {
it("creates a new file with contents", async () => {
const out = await tools.dispatch(
"write_file",
JSON.stringify({ path: "new.md", content: "hi" }),
);
expect(out).toMatch(/wrote 2 chars/);
const disk = await fs.readFile(join(root, "new.md"), "utf8");
expect(disk).toBe("hi");
});
it("creates parent directories as needed", async () => {
await tools.dispatch("write_file", JSON.stringify({ path: "a/b/c/deep.txt", content: "x" }));
const disk = await fs.readFile(join(root, "a", "b", "c", "deep.txt"), "utf8");
expect(disk).toBe("x");
});
it("rejects writes outside the sandbox", async () => {
const out = await tools.dispatch(
"write_file",
JSON.stringify({ path: "../escape.txt", content: "bad" }),
);
expect(out).toMatch(/escapes sandbox/);
});
});
describe("edit_file (flat SEARCH/REPLACE — the anti-DSML shape)", () => {
it("replaces a unique search string", async () => {
await fs.writeFile(join(root, "a.txt"), "foo bar baz");
const out = await tools.dispatch(
"edit_file",
JSON.stringify({ path: "a.txt", search: "bar", replace: "QUX" }),
);
expect(out).toMatch(/edited/);
const disk = await fs.readFile(join(root, "a.txt"), "utf8");
expect(disk).toBe("foo QUX baz");
});
it("includes a git-style @@ -N,M +N,M @@ hunk header with the real starting line", async () => {
// File has 4 pre-existing lines; SEARCH starts at line 3.
// Expected hunk header: @@ -3,1 +3,2 @@ (1 old line → 2 new).
await fs.writeFile(join(root, "a.txt"), "alpha\nbeta\nTARGET\ntail\n");
const out = await tools.dispatch(
"edit_file",
JSON.stringify({ path: "a.txt", search: "TARGET", replace: "TARGET\nextra" }),
);
expect(out).toMatch(/@@ -3,1 \+3,2 @@/);
});
it("returns a proper LCS diff with context lines, not just - old / + new", async () => {
// The user-reported case: SEARCH is a single line, REPLACE keeps
// that line and adds three more below it. A naive dump-both-sides
// would show "- line\n+ line\n+ new1\n+ new2\n+ new3" (redundant
// `-` for the unchanged line). Proper LCS shows the first line
// as context (` `) and only the additions as `+`.
await fs.writeFile(
join(root, "a.txt"),
"const a = doc.getElementById('a');\nconst b = doc.getElementById('b');",
);
const search = "const a = doc.getElementById('a');";
const replace = [
"const a = doc.getElementById('a');",
"const b2 = doc.getElementById('b2');",
"const c = doc.getElementById('c');",
].join("\n");
const out = await tools.dispatch(
"edit_file",
JSON.stringify({ path: "a.txt", search, replace }),
);
// The unchanged first line appears as context (space-prefixed),
// NOT as a `-` / `+` pair.
expect(out).toContain(" const a = doc.getElementById('a');");
// The new lines are `+` prefixed.
expect(out).toContain("+ const b2 = doc.getElementById('b2');");
expect(out).toContain("+ const c = doc.getElementById('c');");
// No line should appear as both `-` and `+` for the preserved
// one — that was the old broken behavior.
const minuses = out.split("\n").filter((l) => l.startsWith("- "));
expect(minuses.some((l) => l.includes("getElementById('a')"))).toBe(false);
});
it("refuses when the search text is not found", async () => {
await fs.writeFile(join(root, "a.txt"), "foo bar");
const out = await tools.dispatch(
"edit_file",
JSON.stringify({ path: "a.txt", search: "baz", replace: "x" }),
);
expect(out).toMatch(/not found/);
});
it("refuses when the search text appears multiple times", async () => {
await fs.writeFile(join(root, "a.txt"), "cat cat cat");
const out = await tools.dispatch(
"edit_file",
JSON.stringify({ path: "a.txt", search: "cat", replace: "dog" }),
);
expect(out).toMatch(/multiple times/);
// File unchanged.
const disk = await fs.readFile(join(root, "a.txt"), "utf8");
expect(disk).toBe("cat cat cat");
});
it("refuses an empty search", async () => {
await fs.writeFile(join(root, "a.txt"), "x");
const out = await tools.dispatch(
"edit_file",
JSON.stringify({ path: "a.txt", search: "", replace: "y" }),
);
expect(out).toMatch(/search cannot be empty/);
});
});
describe("create_directory + move_file", () => {
it("create_directory is idempotent (mkdir -p)", async () => {
const a = await tools.dispatch("create_directory", JSON.stringify({ path: "d/e/f" }));
expect(a).toMatch(/created/);
const b = await tools.dispatch("create_directory", JSON.stringify({ path: "d/e/f" }));
expect(b).toMatch(/created/);
const st = await fs.stat(join(root, "d", "e", "f"));
expect(st.isDirectory()).toBe(true);
});
it("move_file renames", async () => {
const out = await tools.dispatch(
"move_file",
JSON.stringify({ source: "hello.txt", destination: "bye.txt" }),
);
expect(out).toMatch(/moved/);
const disk = await fs.readFile(join(root, "bye.txt"), "utf8");
expect(disk).toContain("line 1");
await expect(fs.stat(join(root, "hello.txt"))).rejects.toThrow();
});
it("move_file into a new subdir creates the parent", async () => {
await tools.dispatch(
"move_file",
JSON.stringify({ source: "hello.txt", destination: "archive/old.txt" }),
);
const disk = await fs.readFile(join(root, "archive", "old.txt"), "utf8");
expect(disk).toContain("line 1");
});
});
describe("allowWriting=false (read-only mode)", () => {
it("skips registering write_file / edit_file / create_directory / move_file", async () => {
const ro = new ToolRegistry();
registerFilesystemTools(ro, { rootDir: root, allowWriting: false });
expect(ro.has("read_file")).toBe(true);
expect(ro.has("list_directory")).toBe(true);
expect(ro.has("write_file")).toBe(false);
expect(ro.has("edit_file")).toBe(false);
expect(ro.has("create_directory")).toBe(false);
expect(ro.has("move_file")).toBe(false);
});
});
});
describe("lineDiff — LCS line-level diff used by edit_file", () => {
it("pure insertion: common prefix as context, new lines as +", () => {
const d = lineDiff(["a"], ["a", "b", "c"]);
expect(d).toEqual([
{ op: " ", line: "a" },
{ op: "+", line: "b" },
{ op: "+", line: "c" },
]);
});
it("pure deletion: kept lines as context, dropped as -", () => {
const d = lineDiff(["a", "b", "c"], ["a"]);
expect(d).toEqual([
{ op: " ", line: "a" },
{ op: "-", line: "b" },
{ op: "-", line: "c" },
]);
});
it("substitution: line-in-line-out without touching neighbors", () => {
const d = lineDiff(["a", "old", "c"], ["a", "new", "c"]);
// "a" and "c" stay as context; "old" → "new" is a -/+ pair.
expect(d.map((o) => o.op).join("")).toBe(" -+ ");
expect(d.map((o) => o.line)).toEqual(["a", "old", "new", "c"]);
});
it("identical arrays produce pure context (no +/- ops)", () => {
const lines = ["a", "b", "c"];
const d = lineDiff(lines, lines);
expect(d.every((o) => o.op === " ")).toBe(true);
});
it("empty search → all replace lines are added", () => {
const d = lineDiff([], ["x", "y"]);
expect(d).toEqual([
{ op: "+", line: "x" },
{ op: "+", line: "y" },
]);
});
it("handles the user's real case: one-line search → multi-line replace with the line preserved", () => {
const search = [
"const prestigePointsGainElement = doc.getElementById('prestige-points-gain');",
];
const replace = [
"const prestigePointsGainElement = doc.getElementById('prestige-points-gain');",
"const bonusClickElement = doc.getElementById('bonus-click');",
"const bonusCpsElement = doc.getElementById('bonus-cps');",
];
const d = lineDiff(search, replace);
// First line is context — not a -/+ redundant pair.
expect(d[0]!.op).toBe(" ");
expect(d[0]!.line).toContain("prestigePointsGainElement");
// The rest are pure additions.
expect(d.slice(1).every((o) => o.op === "+")).toBe(true);
});
});
+354
View File
@@ -0,0 +1,354 @@
/**
* Tests for the hooks module — settings loading, match patterns,
* outcome decisions, and the runHooks dispatcher with a stubbed
* spawner. No real subprocesses, no real filesystem outside tmp dirs.
*/
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import {
type HookSpawnInput,
type HookSpawnResult,
type ResolvedHook,
decideOutcome,
formatHookOutcomeMessage,
globalSettingsPath,
loadHooks,
matchesTool,
projectSettingsPath,
runHooks,
} from "../src/hooks.js";
function writeSettings(dir: string, json: unknown): string {
const path = join(dir, ".reasonix", "settings.json");
mkdirSync(join(dir, ".reasonix"), { recursive: true });
writeFileSync(path, JSON.stringify(json), "utf8");
return path;
}
function makeSpawner(
responses: HookSpawnResult[],
log?: HookSpawnInput[],
): (input: HookSpawnInput) => Promise<HookSpawnResult> {
let i = 0;
return async (input) => {
log?.push(input);
const r = responses[i++];
if (!r) throw new Error("spawner exhausted — test set up too few responses");
return r;
};
}
const ok = (overrides: Partial<HookSpawnResult> = {}): HookSpawnResult => ({
exitCode: 0,
stdout: "",
stderr: "",
timedOut: false,
...overrides,
});
describe("loadHooks", () => {
let home: string;
let project: string;
beforeEach(() => {
home = mkdtempSync(join(tmpdir(), "reasonix-hooks-home-"));
project = mkdtempSync(join(tmpdir(), "reasonix-hooks-proj-"));
});
afterEach(() => {
rmSync(home, { recursive: true, force: true });
rmSync(project, { recursive: true, force: true });
});
it("returns [] when no settings file exists in either scope", () => {
expect(loadHooks({ homeDir: home, projectRoot: project })).toEqual([]);
});
it("loads project then global, in array order, with scope tags", () => {
writeSettings(home, {
hooks: { Stop: [{ command: "echo global1" }, { command: "echo global2" }] },
});
writeSettings(project, {
hooks: { Stop: [{ command: "echo proj" }] },
});
const hooks = loadHooks({ homeDir: home, projectRoot: project });
expect(hooks.map((h) => `${h.scope}:${h.command}`)).toEqual([
"project:echo proj",
"global:echo global1",
"global:echo global2",
]);
});
it("ignores entries without a string command", () => {
writeSettings(home, {
hooks: {
Stop: [
{ command: "echo good" },
{ command: "" },
{ description: "no command" },
{ command: 42 } as unknown as { command: string },
],
},
});
const hooks = loadHooks({ homeDir: home });
expect(hooks).toHaveLength(1);
expect(hooks[0]?.command).toBe("echo good");
});
it("tolerates malformed JSON without throwing", () => {
mkdirSync(join(home, ".reasonix"), { recursive: true });
writeFileSync(join(home, ".reasonix", "settings.json"), "{ not valid json", "utf8");
expect(() => loadHooks({ homeDir: home })).not.toThrow();
expect(loadHooks({ homeDir: home })).toEqual([]);
});
it("project scope is skipped when projectRoot omitted", () => {
writeSettings(project, { hooks: { Stop: [{ command: "echo proj" }] } });
const hooks = loadHooks({ homeDir: home }); // no projectRoot
expect(hooks).toEqual([]);
});
it("paths reported by *SettingsPath helpers are absolute", () => {
expect(globalSettingsPath(home)).toBe(join(home, ".reasonix", "settings.json"));
expect(projectSettingsPath(project)).toBe(join(project, ".reasonix", "settings.json"));
});
});
describe("matchesTool", () => {
const baseHook: ResolvedHook = {
event: "PreToolUse",
scope: "global",
source: "/tmp/x",
command: "true",
};
it("returns true when match is undefined or '*'", () => {
expect(matchesTool(baseHook, "edit_file")).toBe(true);
expect(matchesTool({ ...baseHook, match: "*" }, "edit_file")).toBe(true);
});
it("anchored regex matches only the full tool name", () => {
const hook: ResolvedHook = { ...baseHook, match: "edit_file|write_file" };
expect(matchesTool(hook, "edit_file")).toBe(true);
expect(matchesTool(hook, "write_file")).toBe(true);
expect(matchesTool(hook, "read_file")).toBe(false);
// Substring should NOT match (anchored)
expect(matchesTool({ ...baseHook, match: "file" }, "edit_file")).toBe(false);
});
it("malformed regex falls back to no-match (safer than fire-on-everything)", () => {
const hook: ResolvedHook = { ...baseHook, match: "[unclosed" };
expect(matchesTool(hook, "edit_file")).toBe(false);
});
it("non-tool events ignore the match field", () => {
const hook: ResolvedHook = {
...baseHook,
event: "UserPromptSubmit",
match: "never",
};
expect(matchesTool(hook, "anything")).toBe(true);
});
});
describe("decideOutcome", () => {
it("exit 0 → pass", () => {
expect(decideOutcome("PreToolUse", ok())).toBe("pass");
});
it("exit 2 on PreToolUse → block", () => {
expect(decideOutcome("PreToolUse", ok({ exitCode: 2 }))).toBe("block");
});
it("exit 2 on PostToolUse → warn (block is meaningless after the fact)", () => {
expect(decideOutcome("PostToolUse", ok({ exitCode: 2 }))).toBe("warn");
});
it("any other non-zero → warn", () => {
expect(decideOutcome("PreToolUse", ok({ exitCode: 1 }))).toBe("warn");
expect(decideOutcome("Stop", ok({ exitCode: 127 }))).toBe("warn");
});
it("timeout on a blocking event → block, on a logging event → warn", () => {
expect(decideOutcome("PreToolUse", ok({ timedOut: true, exitCode: null }))).toBe("block");
expect(decideOutcome("Stop", ok({ timedOut: true, exitCode: null }))).toBe("warn");
});
it("spawn error → error, regardless of event", () => {
const err = ok({ exitCode: null, spawnError: new Error("ENOENT") });
expect(decideOutcome("PreToolUse", err)).toBe("error");
expect(decideOutcome("Stop", err)).toBe("error");
});
});
describe("runHooks", () => {
const hook = (overrides: Partial<ResolvedHook> = {}): ResolvedHook => ({
event: "PreToolUse",
scope: "project",
source: "/tmp/x",
command: "true",
...overrides,
});
it("filters by event AND tool match before running", async () => {
const log: HookSpawnInput[] = [];
const spawner = makeSpawner([ok()], log);
const hooks: ResolvedHook[] = [
hook({ event: "Stop", command: "wrong-event" }),
hook({ event: "PreToolUse", match: "write_file", command: "wrong-tool" }),
hook({ event: "PreToolUse", match: "edit_file", command: "right" }),
];
const report = await runHooks({
hooks,
spawner,
payload: { event: "PreToolUse", cwd: "/tmp", toolName: "edit_file" },
});
expect(log).toHaveLength(1);
expect(log[0]?.command).toBe("right");
expect(report.outcomes[0]?.decision).toBe("pass");
expect(report.blocked).toBe(false);
});
it("stops at the first block on a blocking event", async () => {
const log: HookSpawnInput[] = [];
const spawner = makeSpawner([ok(), ok({ exitCode: 2, stderr: "denied" }), ok()], log);
const hooks: ResolvedHook[] = [
hook({ command: "first" }),
hook({ command: "blocker" }),
hook({ command: "third — should not run" }),
];
const report = await runHooks({
hooks,
spawner,
payload: { event: "PreToolUse", cwd: "/tmp", toolName: "x" },
});
expect(log.map((l) => l.command)).toEqual(["first", "blocker"]);
expect(report.blocked).toBe(true);
expect(report.outcomes[1]?.decision).toBe("block");
});
it("does not stop on warn — collects every outcome", async () => {
const spawner = makeSpawner([ok({ exitCode: 1, stderr: "noisy" }), ok()]);
const hooks: ResolvedHook[] = [hook({ command: "warner" }), hook({ command: "ok" })];
const report = await runHooks({
hooks,
spawner,
payload: { event: "PreToolUse", cwd: "/tmp", toolName: "x" },
});
expect(report.outcomes.map((o) => o.decision)).toEqual(["warn", "pass"]);
expect(report.blocked).toBe(false);
});
it("stdin contains a single-line JSON envelope of the payload", async () => {
const log: HookSpawnInput[] = [];
const spawner = makeSpawner([ok()], log);
await runHooks({
hooks: [hook({ command: "echo" })],
spawner,
payload: {
event: "PreToolUse",
cwd: "/tmp",
toolName: "edit_file",
toolArgs: { path: "a.ts" },
},
});
const stdin = log[0]?.stdin ?? "";
const decoded = JSON.parse(stdin);
expect(decoded.event).toBe("PreToolUse");
expect(decoded.toolName).toBe("edit_file");
expect(decoded.toolArgs).toEqual({ path: "a.ts" });
expect(stdin.endsWith("\n")).toBe(true);
});
it("uses payload.cwd by default and per-hook cwd override when set", async () => {
const log: HookSpawnInput[] = [];
const spawner = makeSpawner([ok(), ok()], log);
await runHooks({
hooks: [hook({ command: "a" }), hook({ command: "b", cwd: "/special" })],
spawner,
payload: { event: "PreToolUse", cwd: "/payload-cwd", toolName: "x" },
});
expect(log[0]?.cwd).toBe("/payload-cwd");
expect(log[1]?.cwd).toBe("/special");
});
it("default timeout is 5s for blocking events and 30s for logging events", async () => {
const log: HookSpawnInput[] = [];
const spawner = makeSpawner([ok(), ok()], log);
const h: ResolvedHook[] = [
hook({ event: "PreToolUse", command: "pre" }),
hook({ event: "Stop", command: "stop" }),
];
await runHooks({
hooks: h,
spawner,
payload: { event: "PreToolUse", cwd: "/tmp", toolName: "x" },
});
await runHooks({
hooks: h,
spawner,
payload: { event: "Stop", cwd: "/tmp" },
});
expect(log[0]?.timeoutMs).toBe(5_000);
expect(log[1]?.timeoutMs).toBe(30_000);
});
it("per-hook timeout overrides the default", async () => {
const log: HookSpawnInput[] = [];
const spawner = makeSpawner([ok()], log);
await runHooks({
hooks: [hook({ command: "x", timeout: 999 })],
spawner,
payload: { event: "PreToolUse", cwd: "/tmp", toolName: "x" },
});
expect(log[0]?.timeoutMs).toBe(999);
});
});
describe("formatHookOutcomeMessage", () => {
const baseHook: ResolvedHook = {
event: "PostToolUse",
scope: "global",
source: "/tmp/x",
command: "echo hi",
};
it("returns empty string for pass", () => {
expect(
formatHookOutcomeMessage({
hook: baseHook,
decision: "pass",
exitCode: 0,
stdout: "",
stderr: "",
durationMs: 1,
}),
).toBe("");
});
it("includes scope/event tag, command, decision, and stderr detail", () => {
const msg = formatHookOutcomeMessage({
hook: baseHook,
decision: "warn",
exitCode: 1,
stdout: "",
stderr: "something went sideways",
durationMs: 5,
});
expect(msg).toContain("global/PostToolUse");
expect(msg).toContain("echo hi");
expect(msg).toContain("warn");
expect(msg).toContain("something went sideways");
});
it("truncates very long commands at 60 chars + ellipsis", () => {
const long = "x".repeat(200);
const msg = formatHookOutcomeMessage({
hook: { ...baseHook, command: long },
decision: "warn",
exitCode: 1,
stdout: "",
stderr: "",
durationMs: 5,
});
expect(msg).toContain(`${"x".repeat(60)}…`);
expect(msg).not.toContain("x".repeat(61));
});
});
+160 -6
View File
@@ -5,7 +5,7 @@
*/
import { describe, expect, it } from "vitest";
import { formatLoopError, healLoadedMessages } from "../src/loop.js";
import { formatLoopError, healLoadedMessages, stripHallucinatedToolMarkup } from "../src/loop.js";
import type { ChatMessage } from "../src/types.js";
describe("formatLoopError", () => {
@@ -37,9 +37,15 @@ describe("formatLoopError", () => {
describe("healLoadedMessages", () => {
it("truncates a giant tool result, leaves user/assistant messages alone", () => {
const big = "X".repeat(80_000);
// Needs a proper assistant.tool_calls + matching tool response so
// the 0.4.12+ validator doesn't prune the tool as stray.
const messages: ChatMessage[] = [
{ role: "user", content: "read the big file" },
{ role: "assistant", content: "", tool_calls: [] },
{
role: "assistant",
content: "",
tool_calls: [{ id: "t1", type: "function", function: { name: "read", arguments: "{}" } }],
},
{ role: "tool", tool_call_id: "t1", content: big },
{ role: "assistant", content: "here's what I found" },
];
@@ -54,18 +60,30 @@ describe("healLoadedMessages", () => {
expect(healed[3]).toEqual(messages[3]); // trailing assistant untouched
});
it("is a no-op when every message fits", () => {
it("is a no-op when every message fits AND pairing is valid", () => {
const messages: ChatMessage[] = [
{ role: "user", content: "hi" },
{ role: "tool", tool_call_id: "t1", content: "small result" },
{ role: "assistant", content: "hi back" },
];
const { messages: healed, healedCount } = healLoadedMessages(messages, 32_000);
expect(healedCount).toBe(0);
expect(healed).toEqual(messages); // structural equality, same strings
expect(healed).toEqual(messages);
});
it("heals multiple oversized tool messages in one pass", () => {
it("heals multiple oversized tool messages in one pass (all properly paired)", () => {
// Each oversized tool MUST be the response to a preceding
// assistant.tool_calls, otherwise the 0.4.12 validator prunes it.
const messages: ChatMessage[] = [
{ role: "user", content: "do three things" },
{
role: "assistant",
content: "",
tool_calls: [
{ id: "t1", type: "function", function: { name: "x", arguments: "{}" } },
{ id: "t2", type: "function", function: { name: "x", arguments: "{}" } },
{ id: "t3", type: "function", function: { name: "x", arguments: "{}" } },
],
},
{ role: "tool", tool_call_id: "t1", content: "A".repeat(40_000) },
{ role: "tool", tool_call_id: "t2", content: "B".repeat(50_000) },
{ role: "tool", tool_call_id: "t3", content: "small" },
@@ -74,4 +92,140 @@ describe("healLoadedMessages", () => {
expect(healedCount).toBe(2);
expect(healedFrom).toBe(90_000);
});
it("drops stray tool messages that have no preceding assistant.tool_calls", () => {
// This is the shape that triggered the "tool must be a response
// to a preceding tool_calls" 400 — a tool entry with no opener.
const messages: ChatMessage[] = [
{ role: "user", content: "hi" },
{ role: "tool", tool_call_id: "stray", content: "orphan result" },
{ role: "assistant", content: "sure" },
];
const { messages: healed, healedCount } = healLoadedMessages(messages, 32_000);
expect(healedCount).toBe(1);
expect(healed.map((m) => m.role)).toEqual(["user", "assistant"]);
});
it("drops an assistant.tool_calls whose response set is incomplete", () => {
// tool_calls declares [a, b], but only tool[a] follows. The
// validator can't deliver this to DeepSeek — drops the pair.
const messages: ChatMessage[] = [
{ role: "user", content: "hi" },
{
role: "assistant",
content: "",
tool_calls: [
{ id: "a", type: "function", function: { name: "x", arguments: "{}" } },
{ id: "b", type: "function", function: { name: "x", arguments: "{}" } },
],
},
{ role: "tool", tool_call_id: "a", content: "partial" },
{ role: "assistant", content: "trailing note" },
];
const { messages: healed, healedCount } = healLoadedMessages(messages, 32_000);
expect(healedCount).toBeGreaterThan(0);
// Assistant.tool_calls and its partial tool response both dropped;
// the trailing plain assistant note survives.
expect(healed.map((m) => m.role)).toEqual(["user", "assistant"]);
expect(healed[1]!.content).toBe("trailing note");
});
it("strips a dangling assistant-with-tool_calls tail (pre-0.4.12 session files)", () => {
const messages: ChatMessage[] = [
{ role: "user", content: "analyze" },
{ role: "assistant", content: "sure" },
{
role: "assistant",
content: "",
tool_calls: [{ id: "t1", type: "function", function: { name: "probe", arguments: "{}" } }],
},
// NO tool response follows — this is the corrupted shape that
// DeepSeek 400s on the next user message. Heal must drop it.
];
const { messages: healed, healedCount } = healLoadedMessages(messages, 32_000);
expect(healedCount).toBe(1);
expect(healed).toHaveLength(2);
expect(healed[healed.length - 1]!.role).toBe("assistant");
expect(healed[healed.length - 1]!.content).toBe("sure");
});
it("strips MULTIPLE trailing assistant-with-tool_calls entries (stacked corruption)", () => {
const messages: ChatMessage[] = [
{ role: "user", content: "go" },
{
role: "assistant",
content: "",
tool_calls: [{ id: "a", type: "function", function: { name: "x", arguments: "{}" } }],
},
{
role: "assistant",
content: "",
tool_calls: [{ id: "b", type: "function", function: { name: "x", arguments: "{}" } }],
},
];
const { messages: healed, healedCount } = healLoadedMessages(messages, 32_000);
// Both dangling assistant entries trimmed; user message survives.
expect(healedCount).toBe(2);
expect(healed).toHaveLength(1);
expect(healed[0]!.role).toBe("user");
});
it("keeps a PAIRED assistant.tool_calls + tool response intact", () => {
const messages: ChatMessage[] = [
{ role: "user", content: "go" },
{
role: "assistant",
content: "",
tool_calls: [{ id: "t1", type: "function", function: { name: "x", arguments: "{}" } }],
},
{ role: "tool", tool_call_id: "t1", content: "ok" },
];
const { messages: healed, healedCount } = healLoadedMessages(messages, 32_000);
expect(healedCount).toBe(0);
expect(healed).toEqual(messages);
});
});
describe("stripHallucinatedToolMarkup", () => {
it("removes a full DSML function_calls block (the R1 hallucination we saw live)", () => {
const input = [
"Let me look at the file structure.",
"",
'<|DSML|function_calls> <|DSML|invoke name="filesystem_edit_file">',
' <|DSML|parameter name="path" string="true">F:.html</|DSML|parameter>',
' <|DSML|parameter name="edits" string="false">[...]</|DSML|parameter>',
"</|DSML|invoke> </|DSML|function_calls>",
"",
"Saved.",
].join("\n");
const out = stripHallucinatedToolMarkup(input);
expect(out).toContain("Let me look at the file structure.");
expect(out).toContain("Saved.");
expect(out).not.toContain("DSML");
expect(out).not.toContain("filesystem_edit_file");
});
it("removes an Anthropic-style <function_calls> block", () => {
const input = "Here is the plan.\n<function_calls>\n<tool>...</tool>\n</function_calls>\nDone.";
const out = stripHallucinatedToolMarkup(input);
expect(out).toContain("Here is the plan.");
expect(out).toContain("Done.");
expect(out).not.toContain("function_calls");
});
it("strips a truncated DSML opener that never gets closed", () => {
const input = 'Before the junk.\n<|DSML|function_calls> <|DSML|invoke name="x"> ...';
const out = stripHallucinatedToolMarkup(input);
expect(out).toBe("Before the junk.");
});
it("leaves plain prose completely alone", () => {
const input = "Just a normal summary with no markup anywhere.";
expect(stripHallucinatedToolMarkup(input)).toBe(input);
});
it("returns empty string when ALL content was hallucinated markup", () => {
const input = "<|DSML|function_calls>garbage</|DSML|function_calls>";
expect(stripHallucinatedToolMarkup(input)).toBe("");
});
});
+124
View File
@@ -0,0 +1,124 @@
/**
* Smoke tests for hook wiring inside CacheFirstLoop. The full
* pass / block / warn matrix is covered in tests/hooks.test.ts with
* a stubbed spawner — here we just confirm the loop honors the
* `hooks` option and exposes a mutable list that `/hooks reload`
* can swap into without reconstructing the loop.
*/
import { describe, expect, it, vi } from "vitest";
import { DeepSeekClient } from "../src/client.js";
import type { ResolvedHook } from "../src/hooks.js";
import { CacheFirstLoop, type LoopEvent } from "../src/loop.js";
import { ImmutablePrefix } from "../src/memory.js";
import { ToolRegistry } from "../src/tools.js";
import type { ChatMessage } from "../src/types.js";
interface FakeResponseShape {
content?: string;
tool_calls?: unknown[];
}
function fakeFetch(responses: FakeResponseShape[]): typeof fetch {
let i = 0;
return vi.fn(async (_url: unknown, init: { body?: string } | undefined) => {
const body = init?.body ? JSON.parse(init.body) : {};
const resp = responses[i++] ?? responses[responses.length - 1]!;
return new Response(
JSON.stringify({
_echo_messages: body.messages as ChatMessage[],
choices: [
{
index: 0,
message: {
role: "assistant",
content: resp.content ?? "",
tool_calls: resp.tool_calls ?? undefined,
},
finish_reason: resp.tool_calls ? "tool_calls" : "stop",
},
],
usage: {
prompt_tokens: 100,
completion_tokens: 20,
total_tokens: 120,
prompt_cache_hit_tokens: 0,
prompt_cache_miss_tokens: 100,
},
}),
{ status: 200, headers: { "Content-Type": "application/json" } },
);
}) as unknown as typeof fetch;
}
function makeClient(responses: FakeResponseShape[]) {
return new DeepSeekClient({ apiKey: "sk-test", fetch: fakeFetch(responses) });
}
describe("CacheFirstLoop hook wiring", () => {
it("default hooks list is empty (zero overhead when no settings.json)", () => {
const loop = new CacheFirstLoop({
client: makeClient([{ content: "x" }]),
prefix: new ImmutablePrefix({ system: "s" }),
});
expect(loop.hooks).toEqual([]);
});
it("accepts a hooks list via options", () => {
const hooks: ResolvedHook[] = [
{ event: "Stop", scope: "global", source: "/x", command: "echo done" },
];
const loop = new CacheFirstLoop({
client: makeClient([{ content: "x" }]),
prefix: new ImmutablePrefix({ system: "s" }),
hooks,
});
expect(loop.hooks).toEqual(hooks);
});
it("hooks field is mutable so /hooks reload can swap without rebuild", () => {
const loop = new CacheFirstLoop({
client: makeClient([{ content: "x" }]),
prefix: new ImmutablePrefix({ system: "s" }),
});
const fresh: ResolvedHook[] = [
{ event: "PreToolUse", scope: "project", source: "/x", command: "true" },
];
loop.hooks = fresh;
expect(loop.hooks).toEqual(fresh);
});
it("hookCwd defaults to process.cwd() when not provided", () => {
const loop = new CacheFirstLoop({
client: makeClient([{ content: "x" }]),
prefix: new ImmutablePrefix({ system: "s" }),
});
expect(loop.hookCwd).toBe(process.cwd());
});
it("hookCwd takes the explicit override when set", () => {
const loop = new CacheFirstLoop({
client: makeClient([{ content: "x" }]),
prefix: new ImmutablePrefix({ system: "s" }),
hookCwd: "/some/sandbox/root",
});
expect(loop.hookCwd).toBe("/some/sandbox/root");
});
it("a no-tool-call turn never dispatches hooks (PreToolUse only fires around tools)", async () => {
// Sanity check: a plain text response means no PreToolUse hook
// would be invoked even if one were configured. We assert only
// through observable events here — no hook = no warning rows.
const client = makeClient([{ content: "just chatting" }]);
const loop = new CacheFirstLoop({
client,
prefix: new ImmutablePrefix({ system: "s" }),
stream: false,
hooks: [{ event: "PreToolUse", scope: "global", source: "/x", command: "noop" }],
});
const events: LoopEvent[] = [];
for await (const ev of loop.step("hi")) events.push(ev);
expect(events.find((e) => e.role === "warning")).toBeUndefined();
expect(events.find((e) => e.role === "assistant_final")?.content).toBe("just chatting");
});
});
+184 -19
View File
@@ -255,14 +255,16 @@ describe("CacheFirstLoop (non-streaming)", () => {
for await (const ev of loop.step("go")) {
if (ev.role === "warning") warnings.push(ev.content);
}
// Exactly one warning should fire (guard against the once-per-turn flag
// regressing). Content must mention the X/N count and "Esc".
expect(warnings).toHaveLength(1);
expect(warnings[0]).toMatch(/\d+\/4 tool calls used/);
expect(warnings[0]).toMatch(/Esc/);
// Identical fixture calls also trip the storm breaker in 0.4.19+,
// which emits its own warning. Filter for the iter-budget warning
// specifically — that's what this test guards (once-per-turn flag).
const iterBudgetWarnings = warnings.filter((w) => /tool calls used/.test(w));
expect(iterBudgetWarnings).toHaveLength(1);
expect(iterBudgetWarnings[0]).toMatch(/\d+\/4 tool calls used/);
expect(iterBudgetWarnings[0]).toMatch(/Esc/);
});
it("abort() mid-step diverts to the summary path with an 'aborted' prefix", async () => {
it("abort() mid-step stops immediately without a follow-up API call", async () => {
const reg = new ToolRegistry();
reg.register({
name: "probe",
@@ -274,11 +276,15 @@ describe("CacheFirstLoop (non-streaming)", () => {
content: "",
tool_calls: [{ id: "c", type: "function", function: { name: "probe", arguments: "{}" } }],
};
// Only one chaining response — after the abort fires on its tool
// event, the loop's next API call IS the forced-summary request, so
// the summary response needs to be index 1.
const responses: FakeResponseShape[] = [chainingToolCall, { content: "partial findings." }];
const client = makeClient(responses);
// Only one chaining response needed — abort should stop the loop
// before any follow-up model call. A second response in the array
// would indicate the loop made an unwanted extra API call.
const fetchSpy = vi.fn() as unknown as typeof fetch;
const responses: FakeResponseShape[] = [chainingToolCall];
const client = new DeepSeekClient({
apiKey: "sk-test",
fetch: fakeFetch(responses) as unknown as typeof fetch,
});
const loop = new CacheFirstLoop({
client,
prefix: new ImmutablePrefix({ system: "s", toolSpecs: reg.specs() }),
@@ -289,22 +295,33 @@ describe("CacheFirstLoop (non-streaming)", () => {
// Call abort AFTER the first tool event fires — simulates the user
// hitting Esc while the loop is exploring.
const events: { role: string; content?: string }[] = [];
const events: { role: string; content?: string; forcedSummary?: boolean }[] = [];
let aborted = false;
for await (const ev of loop.step("go")) {
events.push({ role: ev.role, content: ev.content });
events.push({ role: ev.role, content: ev.content, forcedSummary: ev.forcedSummary });
if (!aborted && ev.role === "tool") {
aborted = true;
loop.abort();
}
}
// Warning fires with the abort notice.
const warnings = events.filter((e) => e.role === "warning");
expect(warnings.some((w) => /aborted/.test(w.content ?? ""))).toBe(true);
expect(warnings.some((w) => /aborted at iter/.test(w.content ?? ""))).toBe(true);
// Synthetic assistant_final is tagged forcedSummary and carries
// the stopped-message text. It should NOT contain any model
// output because no second API call was made.
const finals = events.filter((e) => e.role === "assistant_final");
const summary = finals[finals.length - 1];
expect(summary!.content).toMatch(/aborted by user/);
expect(summary!.content).toContain("partial findings.");
const stopped = finals[finals.length - 1]!;
expect(stopped.forcedSummary).toBe(true);
expect(stopped.content).toMatch(/aborted by user \(Esc\)/);
expect(stopped.content).toMatch(/no summary produced/);
// Suite ends with `done`.
expect(events[events.length - 1]!.role).toBe("done");
// Silence unused-var warning.
void fetchSpy;
});
it("forces a summary when maxToolIters is exhausted, instead of stopping silently", async () => {
@@ -400,10 +417,13 @@ describe("CacheFirstLoop (non-streaming)", () => {
events.push({ role: ev.role, forcedSummary: ev.forcedSummary, content: ev.content });
}
// A warning must fire about the context guard.
// A warning must fire about the context guard. Accept both the
// auto-compact-saved-us variant and the nothing-to-compact variant
// — the message format shifted in 0.4.11 when we added the
// auto-compact attempt before forcing summary.
const warn = events.find((e) => e.role === "warning");
expect(warn).toBeDefined();
expect(warn!.content).toMatch(/context \d+\/\d+/);
expect(warn!.content).toMatch(/context [\d,]+\/[\d,]+/);
// The final assistant_final must be tagged forcedSummary and carry the context-guard prefix.
const finals = events.filter((e) => e.role === "assistant_final");
@@ -412,6 +432,97 @@ describe("CacheFirstLoop (non-streaming)", () => {
expect(summary!.content).toMatch(/context budget running low/);
});
it("context-guard auto-compacts oversized tool results and continues instead of jumping to summary", async () => {
// Pre-seed the log with an oversized tool result so compact has
// something to shrink. Then the model requests another tool call;
// the returned prompt_tokens trips the 80% guard. We expect compact
// to run, the warning to mention shrinking, and the loop to
// continue with the tool dispatch — no forced summary.
const reg = new ToolRegistry();
reg.register({
name: "probe",
description: "no-op",
parameters: { type: "object", properties: {} },
fn: async () => "ok",
});
const responses: FakeResponseShape[] = [
// Iter 0: chains a tool call, usage trips the guard.
{
content: "",
tool_calls: [{ id: "c1", type: "function", function: { name: "probe", arguments: "{}" } }],
usage: {
prompt_tokens: 120_000,
completion_tokens: 10,
total_tokens: 120_010,
prompt_cache_hit_tokens: 100_000,
prompt_cache_miss_tokens: 20_000,
},
},
// Iter 1: model wraps up normally after the tool result.
{ content: "done analyzing." },
];
const client = makeClient(responses);
const loop = new CacheFirstLoop({
client,
prefix: new ImmutablePrefix({ system: "s", toolSpecs: reg.specs() }),
tools: reg,
stream: false,
maxToolIters: 64,
});
// Put a big tool message into the log so compact has work to do.
loop.log.append({ role: "user", content: "do stuff" });
loop.log.append({
role: "tool",
tool_call_id: "prior",
content: "Z".repeat(60_000),
});
const events: { role: string; forcedSummary?: boolean; content?: string }[] = [];
for await (const ev of loop.step("continue")) {
events.push({ role: ev.role, forcedSummary: ev.forcedSummary, content: ev.content });
}
const warn = events.find((e) => e.role === "warning");
expect(warn).toBeDefined();
expect(warn!.content).toMatch(/auto-compacted \d+ oversized tool result/);
// Tool was actually dispatched (we didn't force-summary).
expect(events.find((e) => e.role === "tool")).toBeDefined();
// Final assistant_final should NOT be tagged forcedSummary — we
// took the happy path through the tool and a normal wrap-up.
const finals = events.filter((e) => e.role === "assistant_final");
const last = finals[finals.length - 1];
expect(last!.forcedSummary).toBeFalsy();
});
it("buildMessages strips a dangling assistant-with-tool_calls tail — defensive against 'insufficient tool messages' 400", async () => {
// Craft a log where the last entry is an assistant message with
// tool_calls but no matching tool responses. This is the shape
// that used to crash the forced-summary call with DeepSeek's
// 'insufficient tool messages following tool_calls' error.
const client = makeClient([{ content: "summary text" }]);
const loop = new CacheFirstLoop({
client,
prefix: new ImmutablePrefix({ system: "s" }),
stream: false,
});
loop.log.append({ role: "user", content: "hi" });
loop.log.append({
role: "assistant",
content: "",
tool_calls: [{ id: "x", type: "function", function: { name: "noop", arguments: "{}" } }],
});
// A chat turn from here should succeed, not 400, because
// buildMessages strips the unpaired tail.
const events: { role: string; content?: string }[] = [];
for await (const ev of loop.step("continue")) {
events.push({ role: ev.role, content: ev.content });
}
expect(events.find((e) => e.role === "error")).toBeUndefined();
// The fake fetch echoes the messages it received — no unpaired
// assistant+tool_calls should be in there.
expect(events.find((e) => e.role === "assistant_final")?.content).toContain("summary text");
});
it("surfaces an error event when the HTTP call fails with a non-retryable status", async () => {
// 401 is non-retryable (bad key). Using this avoids multi-retry waits.
const errFetch = vi.fn(async () => new Response("boom", { status: 401 }));
@@ -433,3 +544,57 @@ describe("CacheFirstLoop (non-streaming)", () => {
expect(roles).toContain("error");
});
});
describe("CacheFirstLoop (streaming) — tool_call_delta emission", () => {
it("yields tool_call_delta events carrying growing arg-char count", async () => {
const client = new DeepSeekClient({
apiKey: "sk-test",
// Fake fetch that streams an SSE body with a multi-chunk tool call.
fetch: (async (_url: any, _init: any) => {
const frames = [
`data: ${JSON.stringify({ choices: [{ delta: { tool_calls: [{ index: 0, id: "c1", function: {} }] } }] })}\n\n`,
`data: ${JSON.stringify({ choices: [{ delta: { tool_calls: [{ index: 0, function: { name: "edit_file", arguments: '{"path":"a.txt","search":"' } }] } }] })}\n\n`,
`data: ${JSON.stringify({ choices: [{ delta: { tool_calls: [{ index: 0, function: { arguments: 'old","replace":"new"}' } }] } }] })}\n\n`,
`data: ${JSON.stringify({ choices: [{ finish_reason: "tool_calls", delta: {} }], usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2, prompt_cache_hit_tokens: 0, prompt_cache_miss_tokens: 1 } })}\n\n`,
"data: [DONE]\n\n",
];
const body = new ReadableStream({
start(ctrl) {
for (const f of frames) ctrl.enqueue(new TextEncoder().encode(f));
ctrl.close();
},
});
return new Response(body, {
status: 200,
headers: { "Content-Type": "text/event-stream" },
});
}) as unknown as typeof fetch,
});
const tools = new ToolRegistry();
tools.register({
name: "edit_file",
parameters: { type: "object", properties: {}, required: [] },
fn: () => "ok",
});
const loop = new CacheFirstLoop({
client,
prefix: new ImmutablePrefix({ system: "s", toolSpecs: tools.specs() }),
tools,
stream: true,
maxToolIters: 1,
});
const deltas: Array<{ name?: string; chars?: number }> = [];
for await (const ev of loop.step("do it")) {
if (ev.role === "tool_call_delta") {
deltas.push({ name: ev.toolName, chars: ev.toolCallArgsChars });
}
if (ev.role === "tool_start") break;
}
expect(deltas.length).toBeGreaterThanOrEqual(2);
expect(deltas[0]!.name).toBe("edit_file");
expect(deltas[deltas.length - 1]!.chars).toBeGreaterThan(deltas[0]!.chars!);
});
});
+107
View File
@@ -159,3 +159,110 @@ describe("parseBlocks — SEARCH/REPLACE detection", () => {
);
});
});
describe("parseBlocks — GFM tables", () => {
it("recognizes a simple table with header + separator + rows", () => {
const md = [
"Intro paragraph.",
"",
"| 声望点 | 加成效果 |",
"|--------|----------|",
"| 每2点 | +1 点击力 |",
"| 每3点 | +10% CPS 乘数 |",
"",
"Trailing text.",
].join("\n");
const blocks = parseBlocks(md);
const table = blocks.find((b) => b.kind === "table");
expect(table).toBeDefined();
if (table && table.kind === "table") {
expect(table.header).toEqual(["声望点", "加成效果"]);
expect(table.rows).toHaveLength(2);
expect(table.rows[0]).toEqual(["每2点", "+1 点击力"]);
expect(table.rows[1]).toEqual(["每3点", "+10% CPS 乘数"]);
}
// Surrounding paragraphs still parsed as separate blocks.
expect(
blocks.find((b) => b.kind === "paragraph" && b.text === "Intro paragraph."),
).toBeDefined();
expect(blocks.find((b) => b.kind === "paragraph" && b.text === "Trailing text.")).toBeDefined();
});
it("accepts alignment colons in the separator without breaking", () => {
const md = ["| col1 | col2 |", "|:-----|-----:|", "| a | b |"].join("\n");
const [t] = parseBlocks(md).filter((b) => b.kind === "table");
expect(t).toBeDefined();
if (t && t.kind === "table") {
expect(t.header).toEqual(["col1", "col2"]);
expect(t.rows[0]).toEqual(["a", "b"]);
}
});
it("accepts tables without leading/trailing pipes", () => {
const md = ["col1 | col2", "-----|-----", "a | b"].join("\n");
const [t] = parseBlocks(md).filter((b) => b.kind === "table");
expect(t).toBeDefined();
if (t && t.kind === "table") {
expect(t.header).toEqual(["col1", "col2"]);
expect(t.rows[0]).toEqual(["a", "b"]);
}
});
it("does NOT trigger on a bare '|' in prose when next line is not a separator", () => {
const md = ["Use the pipe | operator to chain.", "Second paragraph."].join("\n");
const blocks = parseBlocks(md);
expect(blocks.find((b) => b.kind === "table")).toBeUndefined();
});
it("preserves escaped pipes inside cell content", () => {
const md = ["| a | b |", "|---|---|", "| x \\| y | z |"].join("\n");
const [t] = parseBlocks(md).filter((b) => b.kind === "table");
expect(t).toBeDefined();
if (t && t.kind === "table") {
expect(t.rows[0]).toEqual(["x | y", "z"]);
}
});
});
describe("parseBlocks — fenced code blocks", () => {
it("recognizes a plain multi-line fence", () => {
const blocks = parseBlocks("```bash\necho hi\necho bye\n```");
expect(blocks).toHaveLength(1);
expect(blocks[0]).toEqual({ kind: "code", lang: "bash", text: "echo hi\necho bye" });
});
it("allows up to 3 leading spaces on the fence line (GFM)", () => {
const blocks = parseBlocks(" ```bash\n echo indented\n ```");
const code = blocks.find((b) => b.kind === "code");
expect(code).toBeDefined();
expect(code && code.kind === "code" && code.lang).toBe("bash");
});
it("handles a one-line fenced code block (model puts everything on one line)", () => {
const blocks = parseBlocks("```bash svn commit -m hi```");
expect(blocks).toHaveLength(1);
expect(blocks[0]).toEqual({ kind: "code", lang: "bash", text: "svn commit -m hi" });
});
it("handles a one-line fenced block surrounded by prose paragraphs", () => {
const blocks = parseBlocks("Run this:\n\n```bash svn status```\n\nOr:\n\n```bash svn log```");
expect(blocks).toHaveLength(4);
expect(blocks[0]).toMatchObject({ kind: "paragraph" });
expect(blocks[1]).toMatchObject({ kind: "code", text: "svn status" });
expect(blocks[2]).toMatchObject({ kind: "paragraph" });
expect(blocks[3]).toMatchObject({ kind: "code", text: "svn log" });
});
it("closing fence must be at least as long as the opening fence", () => {
// Opened with 4 backticks so body can contain 3 without closing.
const blocks = parseBlocks("````\nsome ``` code\n````");
expect(blocks).toHaveLength(1);
expect(blocks[0]).toEqual({ kind: "code", lang: "", text: "some ``` code" });
});
it("an unclosed fence still emits a code block at EOF", () => {
const blocks = parseBlocks("```python\nprint('hi')");
const code = blocks.find((b) => b.kind === "code");
expect(code && code.kind === "code" && code.text).toBe("print('hi')");
});
});
+229
View File
@@ -0,0 +1,229 @@
/**
* Tests for inspectMcpServer (pure, runs against the fake transport).
* We don't unit-test the CLI wrapper — that's just argv parsing and
* stdout printing, covered by the integration story of "types compile".
*/
import { describe, expect, it } from "vitest";
import { McpClient } from "../src/mcp/client.js";
import { inspectMcpServer } from "../src/mcp/inspect.js";
import type { McpTransport } from "../src/mcp/stdio.js";
import {
type JsonRpcMessage,
type JsonRpcRequest,
MCP_PROTOCOL_VERSION,
} from "../src/mcp/types.js";
// A minimal in-process transport that answers methods from a handler
// map. Simpler than the FakeMcpTransport in mcp.test.ts — we only
// care about shape-of-response here, not call ordering.
class HandlerTransport implements McpTransport {
private readonly queue: JsonRpcMessage[] = [];
private readonly waiters: Array<(m: JsonRpcMessage | null) => void> = [];
private closed = false;
constructor(private readonly handlers: Record<string, (req: JsonRpcRequest) => JsonRpcMessage>) {}
async send(msg: JsonRpcMessage): Promise<void> {
if (this.closed) throw new Error("closed");
if (!("id" in msg) || !("method" in msg)) return; // notification from client
const req = msg as JsonRpcRequest;
const handler = this.handlers[req.method];
const response = handler
? handler(req)
: {
jsonrpc: "2.0",
id: req.id,
error: { code: -32601, message: `method not found: ${req.method}` },
};
const w = this.waiters.shift();
if (w) w(response as JsonRpcMessage);
else this.queue.push(response as JsonRpcMessage);
}
async *messages(): AsyncIterableIterator<JsonRpcMessage> {
while (true) {
if (this.queue.length > 0) {
yield this.queue.shift()!;
continue;
}
if (this.closed) return;
const next = await new Promise<JsonRpcMessage | null>((resolve) => {
this.waiters.push(resolve);
});
if (next === null) return;
yield next;
}
}
async close(): Promise<void> {
this.closed = true;
while (this.waiters.length > 0) this.waiters.shift()!(null);
}
}
function initOk(req: JsonRpcRequest): JsonRpcMessage {
return {
jsonrpc: "2.0",
id: req.id,
result: {
protocolVersion: MCP_PROTOCOL_VERSION,
serverInfo: { name: "test-server", version: "1.2.3" },
capabilities: { tools: {}, resources: {}, prompts: {} },
instructions: "Use tool X before Y.",
},
};
}
describe("inspectMcpServer", () => {
it("reports server info, capabilities, tools, resources, prompts — full-support server", async () => {
const transport = new HandlerTransport({
initialize: initOk,
"tools/list": (req) => ({
jsonrpc: "2.0",
id: req.id,
result: {
tools: [
{ name: "echo", description: "echoes", inputSchema: { type: "object" } },
{ name: "add", description: "a+b", inputSchema: { type: "object" } },
],
},
}),
"resources/list": (req) => ({
jsonrpc: "2.0",
id: req.id,
result: {
resources: [
{ uri: "file:///a.md", name: "a", mimeType: "text/markdown" },
{ uri: "custom://b", name: "b" },
],
},
}),
"prompts/list": (req) => ({
jsonrpc: "2.0",
id: req.id,
result: {
prompts: [
{
name: "summarize",
description: "summarize a doc",
arguments: [{ name: "lang", required: true }],
},
],
},
}),
});
const client = new McpClient({ transport });
await client.initialize();
const report = await inspectMcpServer(client);
expect(report.protocolVersion).toBe(MCP_PROTOCOL_VERSION);
expect(report.serverInfo).toEqual({ name: "test-server", version: "1.2.3" });
expect(report.instructions).toBe("Use tool X before Y.");
expect(report.tools).toEqual({
supported: true,
items: expect.arrayContaining([expect.objectContaining({ name: "echo" })]),
});
expect(report.resources.supported).toBe(true);
if (report.resources.supported) {
expect(report.resources.items.map((r) => r.name)).toEqual(["a", "b"]);
}
expect(report.prompts.supported).toBe(true);
if (report.prompts.supported) {
expect(report.prompts.items[0]!.arguments?.[0]?.name).toBe("lang");
}
await client.close();
});
it("marks resources+prompts as not supported when server returns -32601", async () => {
// Tools-only server: init returns, tools/list works, resources/list
// + prompts/list fall through to the default -32601 in HandlerTransport.
const transport = new HandlerTransport({
initialize: initOk,
"tools/list": (req) => ({
jsonrpc: "2.0",
id: req.id,
result: { tools: [] },
}),
});
const client = new McpClient({ transport });
await client.initialize();
const report = await inspectMcpServer(client);
expect(report.tools.supported).toBe(true);
expect(report.resources.supported).toBe(false);
expect(report.prompts.supported).toBe(false);
if (!report.resources.supported) {
expect(report.resources.reason).toMatch(/-32601/);
}
if (!report.prompts.supported) {
expect(report.prompts.reason).toMatch(/-32601/);
}
await client.close();
});
it("forwards non-32601 errors as the section reason so user sees real diagnostics", async () => {
const transport = new HandlerTransport({
initialize: initOk,
"tools/list": (req) => ({
jsonrpc: "2.0",
id: req.id,
error: { code: -32000, message: "server is overloaded" },
}),
"resources/list": (req) => ({
jsonrpc: "2.0",
id: req.id,
result: { resources: [] },
}),
"prompts/list": (req) => ({
jsonrpc: "2.0",
id: req.id,
result: { prompts: [] },
}),
});
const client = new McpClient({ transport });
await client.initialize();
const report = await inspectMcpServer(client);
expect(report.tools.supported).toBe(false);
if (!report.tools.supported) {
expect(report.tools.reason).toMatch(/overloaded/);
}
// Resources and prompts are supported and empty — should not be affected.
expect(report.resources.supported).toBe(true);
expect(report.prompts.supported).toBe(true);
await client.close();
});
});
describe("McpClient: initialize records serverInfo + protocolVersion + instructions", () => {
it("exposes server info, protocol version, instructions from the handshake", async () => {
const transport = new HandlerTransport({ initialize: initOk });
const client = new McpClient({ transport });
await client.initialize();
expect(client.serverInfo).toEqual({ name: "test-server", version: "1.2.3" });
expect(client.protocolVersion).toBe(MCP_PROTOCOL_VERSION);
expect(client.serverInstructions).toBe("Use tool X before Y.");
await client.close();
});
it("leaves serverInstructions undefined when absent from the init result", async () => {
const transport = new HandlerTransport({
initialize: (req) => ({
jsonrpc: "2.0",
id: req.id,
result: {
protocolVersion: MCP_PROTOCOL_VERSION,
serverInfo: { name: "minimal", version: "0" },
capabilities: { tools: {} },
},
}),
});
const client = new McpClient({ transport });
await client.initialize();
expect(client.serverInstructions).toBeUndefined();
await client.close();
});
});
+10 -5
View File
@@ -49,7 +49,7 @@ describe("MCP integration — real subprocess against bundled demo server", () =
const { tools } = await client.listTools();
const names = tools.map((t) => t.name).sort();
expect(names).toEqual(["add", "echo", "get_time"]);
expect(names).toEqual(["add", "echo", "get_time", "slow_count"]);
const echoResult = await client.callTool("echo", { msg: "hello" });
const echoText = echoResult.content.map((c) => ("text" in c ? c.text : "")).join("");
@@ -70,7 +70,12 @@ describe("MCP integration — real subprocess against bundled demo server", () =
await client.initialize();
const { registry, registeredNames } = await bridgeMcpTools(client, { namePrefix: "demo_" });
expect(registeredNames.sort()).toEqual(["demo_add", "demo_echo", "demo_get_time"]);
expect(registeredNames.sort()).toEqual([
"demo_add",
"demo_echo",
"demo_get_time",
"demo_slow_count",
]);
// Dispatch through the registry — should round-trip through MCP
const out = await registry.dispatch("demo_add", JSON.stringify({ a: 100, b: 1 }));
@@ -91,9 +96,9 @@ describe("MCP integration — real subprocess against bundled demo server", () =
const shared = new ToolRegistry();
const resA = await bridgeMcpTools(a, { registry: shared, namePrefix: "a_" });
const resB = await bridgeMcpTools(b, { registry: shared, namePrefix: "b_" });
expect(resA.registeredNames).toHaveLength(3);
expect(resB.registeredNames).toHaveLength(3);
expect(shared.size).toBe(6);
expect(resA.registeredNames).toHaveLength(4);
expect(resB.registeredNames).toHaveLength(4);
expect(shared.size).toBe(8);
const outA = await shared.dispatch("a_add", JSON.stringify({ a: 10, b: 20 }));
expect(outA).toContain("30");
+577 -1
View File
@@ -13,10 +13,14 @@ import { bridgeMcpTools, flattenMcpResult } from "../src/mcp/registry.js";
import type { McpTransport } from "../src/mcp/stdio.js";
import {
type CallToolResult,
type GetPromptResult,
type JsonRpcMessage,
type JsonRpcRequest,
type ListPromptsResult,
type ListResourcesResult,
MCP_PROTOCOL_VERSION,
type McpTool,
type ReadResourceResult,
} from "../src/mcp/types.js";
// ---------- fake transport ----------
@@ -29,6 +33,16 @@ interface FakeServerOptions {
errorFor?: Set<string>;
/** Track every call the server received. */
received?: JsonRpcRequest[];
/** resources/list response. Optional — omit to return empty. */
listResources?: () => ListResourcesResult;
/** resources/read response keyed by URI. Throw-returns method-not-found for unknowns. */
readResource?: (uri: string) => ReadResourceResult;
/** prompts/list response. */
listPrompts?: () => ListPromptsResult;
/** prompts/get response keyed by name. */
getPrompt?: (name: string, args?: Record<string, string>) => GetPromptResult;
/** Initialize capabilities override — defaults advertise tools only. */
capabilities?: Record<string, unknown>;
}
/**
@@ -87,7 +101,7 @@ class FakeMcpTransport implements McpTransport {
result: {
protocolVersion: MCP_PROTOCOL_VERSION,
serverInfo: { name: "fake-mcp", version: "0.0.0" },
capabilities: { tools: { listChanged: false } },
capabilities: this.opts.capabilities ?? { tools: { listChanged: false } },
},
};
case "tools/list":
@@ -110,6 +124,49 @@ class FakeMcpTransport implements McpTransport {
: { content: [{ type: "text" as const, text: `called ${params.name}` }] };
return { jsonrpc: "2.0", id: req.id, result };
}
case "resources/list":
if (!this.opts.listResources) {
return {
jsonrpc: "2.0",
id: req.id,
error: { code: -32601, message: "method not found: resources/list" },
};
}
return { jsonrpc: "2.0", id: req.id, result: this.opts.listResources() };
case "resources/read": {
if (!this.opts.readResource) {
return {
jsonrpc: "2.0",
id: req.id,
error: { code: -32601, message: "method not found: resources/read" },
};
}
const { uri } = req.params as { uri: string };
return { jsonrpc: "2.0", id: req.id, result: this.opts.readResource(uri) };
}
case "prompts/list":
if (!this.opts.listPrompts) {
return {
jsonrpc: "2.0",
id: req.id,
error: { code: -32601, message: "method not found: prompts/list" },
};
}
return { jsonrpc: "2.0", id: req.id, result: this.opts.listPrompts() };
case "prompts/get": {
if (!this.opts.getPrompt) {
return {
jsonrpc: "2.0",
id: req.id,
error: { code: -32601, message: "method not found: prompts/get" },
};
}
const { name, arguments: a } = req.params as {
name: string;
arguments?: Record<string, string>;
};
return { jsonrpc: "2.0", id: req.id, result: this.opts.getPrompt(name, a) };
}
default:
return {
jsonrpc: "2.0",
@@ -352,3 +409,522 @@ describe("bridgeMcpTools: result-size cap", () => {
void transport;
});
});
describe("McpClient: abort via AbortSignal", () => {
/**
* Transport that answers initialize and then stalls on tools/call —
* never sends a response. Used to exercise client-side abort:
* with no response coming, the promise must still reject promptly
* when the signal fires.
*/
function makeStallingTransport(): { transport: McpTransport; received: JsonRpcRequest[] } {
const received: JsonRpcRequest[] = [];
const queue: JsonRpcMessage[] = [];
const waiters: Array<(m: JsonRpcMessage | null) => void> = [];
let closed = false;
const push = (m: JsonRpcMessage) => {
const w = waiters.shift();
if (w) w(m);
else queue.push(m);
};
const transport: McpTransport = {
async send(msg) {
if (closed) throw new Error("closed");
if (!("id" in msg) || !("method" in msg)) {
received.push(msg as JsonRpcRequest);
return;
}
const req = msg as JsonRpcRequest;
received.push(req);
if (req.method === "initialize") {
push({
jsonrpc: "2.0",
id: req.id,
result: {
protocolVersion: MCP_PROTOCOL_VERSION,
serverInfo: { name: "stall", version: "0" },
capabilities: {},
},
});
}
// tools/call: no response, ever.
},
async *messages() {
while (true) {
if (queue.length > 0) {
yield queue.shift()!;
continue;
}
if (closed) return;
const next = await new Promise<JsonRpcMessage | null>((resolve) => {
waiters.push(resolve);
});
if (next === null) return;
yield next;
}
},
async close() {
closed = true;
while (waiters.length > 0) waiters.shift()!(null);
},
};
return { transport, received };
}
it("rejects the pending callTool promise when the signal aborts", async () => {
const { transport } = makeStallingTransport();
const client = new McpClient({ transport, requestTimeoutMs: 60_000 });
await client.initialize();
const ctrl = new AbortController();
const p = client.callTool("slow", {}, { signal: ctrl.signal });
// Fire the abort on the next microtask so the request actually
// reaches the transport before we cancel.
setTimeout(() => ctrl.abort(), 5);
await expect(p).rejects.toThrow(/aborted/);
await client.close();
});
it("emits notifications/cancelled with the request id on abort", async () => {
const { transport, received } = makeStallingTransport();
const client = new McpClient({ transport, requestTimeoutMs: 60_000 });
await client.initialize();
const ctrl = new AbortController();
const p = client.callTool("slow", {}, { signal: ctrl.signal });
setTimeout(() => ctrl.abort(), 5);
await p.catch(() => {});
const callReq = received.find((r) => r.method === "tools/call");
const cancelNotif = received.find((r) => r.method === "notifications/cancelled");
expect(callReq).toBeDefined();
expect(cancelNotif).toBeDefined();
expect((cancelNotif!.params as { requestId: number }).requestId).toBe(callReq!.id);
await client.close();
});
it("rejects immediately when called with an already-aborted signal", async () => {
const { transport } = makeStallingTransport();
const client = new McpClient({ transport, requestTimeoutMs: 60_000 });
await client.initialize();
const ctrl = new AbortController();
ctrl.abort();
await expect(client.callTool("slow", {}, { signal: ctrl.signal })).rejects.toThrow(/aborted/);
await client.close();
});
});
describe("McpClient: progress notifications", () => {
/**
* Build a transport where tools/call takes multiple "ticks" before
* responding — each tick emits a notifications/progress frame tied
* to the token the client sent in `_meta.progressToken`.
*/
function makeProgressTransport(
progressFrames: Array<{ progress: number; total?: number; message?: string }>,
): { transport: McpTransport; received: JsonRpcRequest[] } {
const received: JsonRpcRequest[] = [];
const queue: JsonRpcMessage[] = [];
const waiters: Array<(m: JsonRpcMessage | null) => void> = [];
let closed = false;
const push = (m: JsonRpcMessage) => {
const w = waiters.shift();
if (w) w(m);
else queue.push(m);
};
const transport: McpTransport = {
async send(msg) {
if (closed) throw new Error("closed");
if (!("id" in msg) || !("method" in msg)) return;
const req = msg as JsonRpcRequest;
received.push(req);
if (req.method === "initialize") {
push({
jsonrpc: "2.0",
id: req.id,
result: {
protocolVersion: MCP_PROTOCOL_VERSION,
serverInfo: { name: "fake", version: "0" },
capabilities: { tools: {} },
},
});
return;
}
if (req.method === "tools/call") {
const token = (req.params as { _meta?: { progressToken?: string | number } })._meta
?.progressToken;
// Emit progress frames first (all with the same token), then
// the final response.
for (const frame of progressFrames) {
push({
jsonrpc: "2.0",
method: "notifications/progress",
params: { progressToken: token, ...frame },
});
}
push({
jsonrpc: "2.0",
id: req.id,
result: { content: [{ type: "text" as const, text: "done" }] },
});
return;
}
push({
jsonrpc: "2.0",
id: req.id,
error: { code: -32601, message: "method not found" },
});
},
async *messages() {
while (true) {
if (queue.length > 0) {
yield queue.shift()!;
continue;
}
if (closed) return;
const next = await new Promise<JsonRpcMessage | null>((resolve) => {
waiters.push(resolve);
});
if (next === null) return;
yield next;
}
},
async close() {
closed = true;
while (waiters.length > 0) waiters.shift()!(null);
},
};
return { transport, received };
}
it("routes progress notifications to the per-call onProgress callback", async () => {
const { transport } = makeProgressTransport([
{ progress: 1, total: 3, message: "reading..." },
{ progress: 2, total: 3 },
{ progress: 3, total: 3, message: "done" },
]);
const client = new McpClient({ transport });
await client.initialize();
const received: Array<{ progress: number; total?: number; message?: string }> = [];
const result = await client.callTool("scan", {}, { onProgress: (info) => received.push(info) });
expect(result.content[0]).toEqual({ type: "text", text: "done" });
expect(received).toEqual([
{ progress: 1, total: 3, message: "reading..." },
{ progress: 2, total: 3, message: undefined },
{ progress: 3, total: 3, message: "done" },
]);
await client.close();
});
it("omits _meta.progressToken when no onProgress callback is provided", async () => {
const { transport, received } = makeProgressTransport([]);
const client = new McpClient({ transport });
await client.initialize();
await client.callTool("x", { k: 1 });
const callReq = received.find((r) => r.method === "tools/call")!;
expect((callReq.params as { _meta?: unknown })._meta).toBeUndefined();
await client.close();
});
it("sets a distinct _meta.progressToken when onProgress IS provided", async () => {
const { transport, received } = makeProgressTransport([]);
const client = new McpClient({ transport });
await client.initialize();
await client.callTool("x", {}, { onProgress: () => {} });
const callReq = received.find((r) => r.method === "tools/call")!;
const token = (callReq.params as { _meta?: { progressToken?: number } })._meta?.progressToken;
expect(token).toBeTypeOf("number");
});
it("late progress frames after the call resolved are dropped silently", async () => {
// Use the handler-transport shape from progress-transport: we
// send the final result, THEN push a trailing progress frame.
// The client must not throw when the handler map is already empty.
const received: JsonRpcRequest[] = [];
const queue: JsonRpcMessage[] = [];
const waiters: Array<(m: JsonRpcMessage | null) => void> = [];
let closed = false;
const push = (m: JsonRpcMessage) => {
const w = waiters.shift();
if (w) w(m);
else queue.push(m);
};
let lastToken: string | number | undefined;
const transport: McpTransport = {
async send(msg) {
if (!("id" in msg) || !("method" in msg)) return;
const req = msg as JsonRpcRequest;
received.push(req);
if (req.method === "initialize") {
push({
jsonrpc: "2.0",
id: req.id,
result: {
protocolVersion: MCP_PROTOCOL_VERSION,
serverInfo: { name: "fake", version: "0" },
capabilities: {},
},
});
} else if (req.method === "tools/call") {
lastToken = (req.params as { _meta?: { progressToken?: string | number } })._meta
?.progressToken;
// Final response first, then a trailing progress — mimics
// a race where the server finished but a progress frame
// was already in flight.
push({
jsonrpc: "2.0",
id: req.id,
result: { content: [] },
});
push({
jsonrpc: "2.0",
method: "notifications/progress",
params: { progressToken: lastToken, progress: 42 },
});
}
},
async *messages() {
while (true) {
if (queue.length > 0) {
yield queue.shift()!;
continue;
}
if (closed) return;
const next = await new Promise<JsonRpcMessage | null>((resolve) => {
waiters.push(resolve);
});
if (next === null) return;
yield next;
}
},
async close() {
closed = true;
while (waiters.length > 0) waiters.shift()!(null);
},
};
const client = new McpClient({ transport });
await client.initialize();
const seen: number[] = [];
await client.callTool("x", {}, { onProgress: (i) => seen.push(i.progress) });
// Give the reader loop a tick to process the trailing
// notification — should be swallowed, not thrown.
await new Promise((r) => setTimeout(r, 10));
expect(seen).toEqual([]); // the trailing frame was dropped
await client.close();
});
});
describe("bridgeMcpTools: progress pass-through", () => {
it("threads per-tool progress callbacks with the registered (prefixed) name", async () => {
const { transport } = (function makeProgressTransport(
frames: Array<{ progress: number; total?: number }>,
) {
const queue: JsonRpcMessage[] = [];
const waiters: Array<(m: JsonRpcMessage | null) => void> = [];
let closed = false;
const push = (m: JsonRpcMessage) => {
const w = waiters.shift();
if (w) w(m);
else queue.push(m);
};
const t: McpTransport = {
async send(msg) {
if (!("id" in msg) || !("method" in msg)) return;
const req = msg as JsonRpcRequest;
if (req.method === "initialize") {
push({
jsonrpc: "2.0",
id: req.id,
result: {
protocolVersion: MCP_PROTOCOL_VERSION,
serverInfo: { name: "fs", version: "0" },
capabilities: { tools: {} },
},
});
} else if (req.method === "tools/list") {
push({
jsonrpc: "2.0",
id: req.id,
result: {
tools: [{ name: "scan", description: "", inputSchema: { type: "object" } }],
},
});
} else if (req.method === "tools/call") {
const token = (req.params as { _meta?: { progressToken?: string | number } })._meta
?.progressToken;
for (const f of frames) {
push({
jsonrpc: "2.0",
method: "notifications/progress",
params: { progressToken: token, ...f },
});
}
push({
jsonrpc: "2.0",
id: req.id,
result: { content: [{ type: "text" as const, text: "ok" }] },
});
}
},
async *messages() {
while (true) {
if (queue.length > 0) {
yield queue.shift()!;
continue;
}
if (closed) return;
const next = await new Promise<JsonRpcMessage | null>((resolve) => {
waiters.push(resolve);
});
if (next === null) return;
yield next;
}
},
async close() {
closed = true;
while (waiters.length > 0) waiters.shift()!(null);
},
};
return { transport: t };
})([{ progress: 5, total: 10 }]);
const client = new McpClient({ transport });
await client.initialize();
const observed: Array<{ toolName: string; progress: number; total?: number }> = [];
const { registry } = await bridgeMcpTools(client, {
namePrefix: "fs_",
onProgress: ({ toolName, progress, total }) => observed.push({ toolName, progress, total }),
});
await registry.dispatch("fs_scan", "{}");
expect(observed).toEqual([{ toolName: "fs_scan", progress: 5, total: 10 }]);
await client.close();
});
});
describe("McpClient: resources", () => {
it("lists resources and reads one by URI", async () => {
const transport = new FakeMcpTransport({
tools: [],
capabilities: { tools: {}, resources: { listChanged: false } },
listResources: () => ({
resources: [
{ uri: "file:///a.md", name: "a", mimeType: "text/markdown" },
{ uri: "custom://b", name: "b" },
],
}),
readResource: (uri) => ({
contents: [{ uri, mimeType: "text/plain", text: `body of ${uri}` }],
}),
});
const client = new McpClient({ transport });
await client.initialize();
const list = await client.listResources();
expect(list.resources).toHaveLength(2);
expect(list.resources[0]!.uri).toBe("file:///a.md");
const read = await client.readResource("file:///a.md");
expect(read.contents).toHaveLength(1);
const block = read.contents[0]!;
expect("text" in block ? block.text : "").toBe("body of file:///a.md");
expect(block.mimeType).toBe("text/plain");
await client.close();
});
it("surfaces method-not-found as an error when the server lacks resources support", async () => {
// Default FakeMcpTransport (no listResources handler) → −32601.
const transport = new FakeMcpTransport({ tools: [] });
const client = new McpClient({ transport });
await client.initialize();
await expect(client.listResources()).rejects.toThrow(/-32601/);
await client.close();
});
it("advertises resources + prompts in the initialize capabilities payload", async () => {
const received: JsonRpcRequest[] = [];
const transport = new FakeMcpTransport({ tools: [], received });
const client = new McpClient({ transport });
await client.initialize();
const init = received.find((r) => r.method === "initialize")!;
const params = init.params as { capabilities: Record<string, unknown> };
// The client now claims to support all three method families.
expect(params.capabilities).toHaveProperty("tools");
expect(params.capabilities).toHaveProperty("resources");
expect(params.capabilities).toHaveProperty("prompts");
await client.close();
});
it("propagates the pagination cursor to resources/list", async () => {
const received: JsonRpcRequest[] = [];
const transport = new FakeMcpTransport({
tools: [],
received,
listResources: () => ({ resources: [], nextCursor: undefined }),
});
const client = new McpClient({ transport });
await client.initialize();
await client.listResources("page2");
const listReq = received.find((r) => r.method === "resources/list")!;
expect((listReq.params as { cursor?: string }).cursor).toBe("page2");
await client.close();
});
});
describe("McpClient: prompts", () => {
it("lists prompts and fetches a rendered one with arguments", async () => {
const transport = new FakeMcpTransport({
tools: [],
capabilities: { tools: {}, prompts: { listChanged: false } },
listPrompts: () => ({
prompts: [
{
name: "summarize",
description: "summarize a document",
arguments: [{ name: "lang", required: true }],
},
],
}),
getPrompt: (name, args) => ({
description: `rendered ${name}`,
messages: [
{
role: "user",
content: { type: "text", text: `please summarize in ${args?.lang ?? "?"}` },
},
],
}),
});
const client = new McpClient({ transport });
await client.initialize();
const list = await client.listPrompts();
expect(list.prompts).toHaveLength(1);
expect(list.prompts[0]!.name).toBe("summarize");
expect(list.prompts[0]!.arguments?.[0]?.required).toBe(true);
const got = await client.getPrompt("summarize", { lang: "zh" });
expect(got.messages).toHaveLength(1);
const msg = got.messages[0]!;
expect(msg.role).toBe("user");
expect(msg.content.type).toBe("text");
if (msg.content.type === "text") {
expect(msg.content.text).toContain("zh");
}
await client.close();
});
it("omits the arguments field when caller passes no args", async () => {
const received: JsonRpcRequest[] = [];
const transport = new FakeMcpTransport({
tools: [],
received,
getPrompt: () => ({ messages: [] }),
});
const client = new McpClient({ transport });
await client.initialize();
await client.getPrompt("hello");
const getReq = received.find((r) => r.method === "prompts/get")!;
expect(getReq.params).toEqual({ name: "hello" });
await client.close();
});
});
+245
View File
@@ -0,0 +1,245 @@
import { describe, expect, it } from "vitest";
import {
type MultilineKey,
lineAndColumn,
processMultilineKey,
} from "../src/cli/ui/multiline-keys.js";
function key(overrides: Partial<MultilineKey> = {}): MultilineKey {
return { input: "", ...overrides };
}
describe("processMultilineKey — inserts at cursor", () => {
it("inserts a printable char at the cursor (mid-string)", () => {
// "heo", cursor after "he" → insert "ll" in the middle
const r = processMultilineKey("heo", 2, key({ input: "ll" }));
expect(r.next).toBe("hello");
expect(r.cursor).toBe(4);
});
it("appends when cursor is at end", () => {
const r = processMultilineKey("hel", 3, key({ input: "l" }));
expect(r.next).toBe("hell");
expect(r.cursor).toBe(4);
});
it("inserts at position 0", () => {
const r = processMultilineKey("bc", 0, key({ input: "a" }));
expect(r.next).toBe("abc");
expect(r.cursor).toBe(1);
});
it("multi-char paste burst inserts as a block", () => {
const r = processMultilineKey("ab", 1, key({ input: "XYZ" }));
expect(r.next).toBe("aXYZb");
expect(r.cursor).toBe(4);
});
it("pasted newline lands inline (not a submit)", () => {
const r = processMultilineKey("a", 1, key({ input: "\nmore" }));
expect(r.next).toBe("a\nmore");
expect(r.submit).toBe(false);
});
});
describe("processMultilineKey — submit + newline", () => {
it("Enter submits by default", () => {
const r = processMultilineKey("hi", 2, key({ return: true }));
expect(r.submit).toBe(true);
expect(r.submitValue).toBe("hi");
});
it("Shift+Enter inserts a newline at the cursor", () => {
const r = processMultilineKey("abc", 1, key({ return: true, shift: true }));
expect(r.next).toBe("a\nbc");
expect(r.cursor).toBe(2);
expect(r.submit).toBe(false);
});
it("Ctrl+J inserts a newline at the cursor (ASCII LF form)", () => {
const r = processMultilineKey("abc", 2, key({ input: "\n" }));
expect(r.next).toBe("ab\nc");
expect(r.cursor).toBe(3);
});
it("Ctrl+J normalized as ctrl+'j' also inserts a newline", () => {
const r = processMultilineKey("abc", 2, key({ input: "j", ctrl: true }));
expect(r.next).toBe("ab\nc");
});
it("Enter with trailing \\\\ at end-of-buffer → bash continuation", () => {
const v = "line1\\";
const r = processMultilineKey(v, v.length, key({ return: true }));
expect(r.submit).toBe(false);
expect(r.next).toBe("line1\n");
expect(r.cursor).toBe(6);
});
it("Enter with \\\\ mid-buffer (cursor not at end) does NOT trigger continuation", () => {
// User has "foo\\bar" and hits Enter with cursor after "foo\\" — that's
// a real edit, not a continuation marker. Submit instead.
const r = processMultilineKey("foo\\bar", 4, key({ return: true }));
expect(r.submit).toBe(true);
expect(r.next).toBeNull();
});
it("plain Enter on an empty buffer still submits", () => {
const r = processMultilineKey("", 0, key({ return: true }));
expect(r.submit).toBe(true);
expect(r.submitValue).toBe("");
});
});
describe("processMultilineKey — deletion", () => {
it("Backspace deletes the char BEFORE the cursor, cursor moves back", () => {
const r = processMultilineKey("abcd", 2, key({ backspace: true }));
expect(r.next).toBe("acd");
expect(r.cursor).toBe(1);
});
it("Backspace at cursor 0 is a no-op", () => {
const r = processMultilineKey("abc", 0, key({ backspace: true }));
expect(r.next).toBeNull();
expect(r.cursor).toBeNull();
});
it("Delete behaves like Backspace (unified — some Windows terminals report Backspace as delete)", () => {
const r = processMultilineKey("abcd", 2, key({ delete: true }));
expect(r.next).toBe("acd");
expect(r.cursor).toBe(1);
});
it("Delete at cursor 0 is a no-op (nothing before the cursor)", () => {
const r = processMultilineKey("abc", 0, key({ delete: true }));
expect(r.next).toBeNull();
});
it("raw DEL byte (0x7f) in key.input is treated as backspace", () => {
const r = processMultilineKey("abcd", 2, key({ input: "\x7f" }));
expect(r.next).toBe("acd");
expect(r.cursor).toBe(1);
});
it("raw BS byte (0x08) in key.input is treated as backspace", () => {
const r = processMultilineKey("abcd", 2, key({ input: "\b" }));
expect(r.next).toBe("acd");
expect(r.cursor).toBe(1);
});
it("Backspace across a newline removes the newline", () => {
const r = processMultilineKey("a\nb", 2, key({ backspace: true }));
expect(r.next).toBe("ab");
expect(r.cursor).toBe(1);
});
});
describe("processMultilineKey — cursor motion", () => {
it("←/→ clamp to the buffer", () => {
expect(processMultilineKey("abc", 2, key({ leftArrow: true })).cursor).toBe(1);
expect(processMultilineKey("abc", 0, key({ leftArrow: true })).cursor).toBe(0);
expect(processMultilineKey("abc", 2, key({ rightArrow: true })).cursor).toBe(3);
expect(processMultilineKey("abc", 3, key({ rightArrow: true })).cursor).toBe(3);
});
it("↑/↓ on a single-line non-empty buffer is a no-op (doesn't eat for history)", () => {
// Single-line buffer: moveCursorUp has nowhere to go. Returns NOOP so
// the parent can decide what to do — but parent only does history on
// empty buffer, so the net effect is "nothing happens."
const up = processMultilineKey("hello", 3, key({ upArrow: true }));
expect(up).toEqual({ next: null, cursor: null, submit: false });
const down = processMultilineKey("hello", 3, key({ downArrow: true }));
expect(down).toEqual({ next: null, cursor: null, submit: false });
});
it("↑/↓ on an empty buffer defers to the parent (history recall)", () => {
expect(processMultilineKey("", 0, key({ upArrow: true }))).toEqual({
next: null,
cursor: null,
submit: false,
});
expect(processMultilineKey("", 0, key({ downArrow: true }))).toEqual({
next: null,
cursor: null,
submit: false,
});
});
it("↑ moves cursor to the previous line, preserving column when possible", () => {
// line 0: "hello" (cols 0-5)
// line 1: "world" (cols 0-5)
// cursor at col 3 on line 1 = index 5 (for "\n") + 3 + 1 = 9
const v = "hello\nworld";
const up = processMultilineKey(v, 9, key({ upArrow: true }));
// target: line 0 col 3 → index 3
expect(up.cursor).toBe(3);
});
it("↑ clamps column when the previous line is shorter", () => {
const v = "hi\nworld";
// cursor at line 1 col 4 = index 3 + 4 = 7
const up = processMultilineKey(v, 7, key({ upArrow: true }));
// target: line 0 col min(4, 2) = 2 → index 2
expect(up.cursor).toBe(2);
});
it("↓ moves cursor to the next line, preserving column", () => {
const v = "hello\nworld";
// cursor at line 0 col 2 = index 2
const down = processMultilineKey(v, 2, key({ downArrow: true }));
// target: line 1 col 2 → index 6 + 2 = 8
expect(down.cursor).toBe(8);
});
it("↓ clamps column when the next line is shorter", () => {
const v = "world\nhi";
// cursor at line 0 col 4 = index 4
const down = processMultilineKey(v, 4, key({ downArrow: true }));
// target: line 1 col min(4, 2) = 2 → index 6 + 2 = 8
expect(down.cursor).toBe(8);
});
it("Ctrl+A jumps to start of current line, Ctrl+E to end", () => {
const v = "one\ntwo\nthree";
// cursor mid-"two" at index 5 (o in two)
expect(processMultilineKey(v, 5, key({ input: "a", ctrl: true })).cursor).toBe(4);
expect(processMultilineKey(v, 5, key({ input: "e", ctrl: true })).cursor).toBe(7);
});
});
describe("processMultilineKey — parent-owned keys are ignored", () => {
it("Tab / Escape / PageUp / PageDown are dropped", () => {
expect(processMultilineKey("x", 1, key({ tab: true }))).toEqual({
next: null,
cursor: null,
submit: false,
});
expect(processMultilineKey("x", 1, key({ escape: true })).next).toBeNull();
expect(processMultilineKey("x", 1, key({ pageUp: true })).next).toBeNull();
expect(processMultilineKey("x", 1, key({ pageDown: true })).next).toBeNull();
});
it("unhandled Ctrl-<letter> chords are dropped (no accidental insert)", () => {
const r = processMultilineKey("x", 1, key({ input: "c", ctrl: true }));
expect(r.next).toBeNull();
expect(r.cursor).toBeNull();
});
it("Meta (Alt) key events are dropped", () => {
const r = processMultilineKey("x", 1, key({ input: "a", meta: true }));
expect(r.next).toBeNull();
});
});
describe("lineAndColumn", () => {
it("maps a cursor offset to {line, col}", () => {
expect(lineAndColumn("abc", 2)).toEqual({ line: 0, col: 2 });
expect(lineAndColumn("abc\ndef", 4)).toEqual({ line: 1, col: 0 });
expect(lineAndColumn("abc\ndef", 6)).toEqual({ line: 1, col: 2 });
expect(lineAndColumn("a\n\nb", 2)).toEqual({ line: 1, col: 0 });
expect(lineAndColumn("a\n\nb", 3)).toEqual({ line: 2, col: 0 });
});
it("clamps cursor values past value.length", () => {
expect(lineAndColumn("abc", 99)).toEqual({ line: 0, col: 3 });
});
});
+195
View File
@@ -0,0 +1,195 @@
/**
* Plan Mode — the dispatch-level enforcement (ToolRegistry read-only
* gate) and the submit_plan tool (PlanProposedError + toToolResult
* protocol).
*/
import { describe, expect, it } from "vitest";
import { ToolRegistry } from "../src/tools.js";
import { PlanProposedError, registerPlanTool } from "../src/tools/plan.js";
describe("ToolRegistry plan mode", () => {
it("starts with plan mode off by default", () => {
const reg = new ToolRegistry();
expect(reg.planMode).toBe(false);
});
it("setPlanMode toggles the flag", () => {
const reg = new ToolRegistry();
reg.setPlanMode(true);
expect(reg.planMode).toBe(true);
reg.setPlanMode(false);
expect(reg.planMode).toBe(false);
});
it("blocks non-readOnly tools when plan mode is on", async () => {
const reg = new ToolRegistry();
let ran = false;
reg.register({
name: "mutate",
// readOnly: undefined → treated as write
fn: () => {
ran = true;
return "ok";
},
});
reg.setPlanMode(true);
const out = await reg.dispatch("mutate", "{}");
expect(ran).toBe(false);
const payload = JSON.parse(out);
expect(payload.error).toMatch(/unavailable in plan mode/);
expect(payload.error).toMatch(/submit_plan/);
});
it("allows readOnly tools when plan mode is on", async () => {
const reg = new ToolRegistry();
reg.register({
name: "read_thing",
readOnly: true,
fn: () => "the-thing",
});
reg.setPlanMode(true);
const out = await reg.dispatch("read_thing", "{}");
expect(out).toBe("the-thing");
});
it("honors readOnlyCheck taking the actual arguments into account", async () => {
const reg = new ToolRegistry();
reg.register({
name: "maybe_read",
readOnlyCheck: (args: { kind?: string }) => args.kind === "read",
fn: (args: { kind?: string }) => `did-${args.kind}`,
});
reg.setPlanMode(true);
// Read call: allowed.
const readOut = await reg.dispatch("maybe_read", '{"kind":"read"}');
expect(readOut).toBe("did-read");
// Write call: refused.
const writeOut = await reg.dispatch("maybe_read", '{"kind":"write"}');
expect(JSON.parse(writeOut).error).toMatch(/unavailable in plan mode/);
});
it("readOnlyCheck takes precedence over readOnly when both are set", async () => {
const reg = new ToolRegistry();
reg.register({
name: "mixed",
readOnly: false,
readOnlyCheck: () => true,
fn: () => "ran",
});
reg.setPlanMode(true);
const out = await reg.dispatch("mixed", "{}");
expect(out).toBe("ran");
});
it("with plan mode off, readOnly flags don't interfere", async () => {
const reg = new ToolRegistry();
reg.register({
name: "normal",
fn: () => "ran",
});
expect(reg.planMode).toBe(false);
const out = await reg.dispatch("normal", "{}");
expect(out).toBe("ran");
});
it("serializes errors via toToolResult when the thrown error implements it", async () => {
const reg = new ToolRegistry();
reg.register({
name: "structured_err",
fn: () => {
const err = new Error("oops") as Error & { toToolResult?: () => unknown };
err.name = "StructuredError";
err.toToolResult = () => ({ error: "StructuredError: oops", extra: "pinned-out-of-band" });
throw err;
},
});
const out = await reg.dispatch("structured_err", "{}");
const parsed = JSON.parse(out);
expect(parsed.error).toBe("StructuredError: oops");
expect(parsed.extra).toBe("pinned-out-of-band");
});
it("falls back to the default error shape when toToolResult throws", async () => {
const reg = new ToolRegistry();
reg.register({
name: "broken_serializer",
fn: () => {
const err = new Error("base-message") as Error & { toToolResult?: () => unknown };
err.name = "Broken";
err.toToolResult = () => {
throw new Error("serialization failed");
};
throw err;
},
});
const out = await reg.dispatch("broken_serializer", "{}");
expect(JSON.parse(out).error).toBe("Broken: base-message");
});
});
describe("PlanProposedError", () => {
it("carries the plan on the instance and in toToolResult()", () => {
const err = new PlanProposedError("# Plan\n- step 1\n- step 2");
expect(err.name).toBe("PlanProposedError");
expect(err.plan).toBe("# Plan\n- step 1\n- step 2");
const payload = err.toToolResult();
expect(payload.plan).toBe("# Plan\n- step 1\n- step 2");
expect(payload.error).toMatch(/^PlanProposedError:/);
// Message tells the model to STOP so it doesn't keep calling tools.
expect(payload.error).toMatch(/STOP/);
});
});
describe("registerPlanTool + submit_plan", () => {
it("registers submit_plan as readOnly so it passes the plan-mode gate", () => {
const reg = new ToolRegistry();
registerPlanTool(reg);
expect(reg.has("submit_plan")).toBe(true);
expect(reg.get("submit_plan")?.readOnly).toBe(true);
});
it("throws PlanProposedError when called with a plan (plan mode ON)", async () => {
const reg = new ToolRegistry();
const submitted: string[] = [];
registerPlanTool(reg, { onPlanSubmitted: (p) => submitted.push(p) });
reg.setPlanMode(true);
const out = await reg.dispatch("submit_plan", JSON.stringify({ plan: "# Plan\n- A" }));
const parsed = JSON.parse(out);
expect(parsed.plan).toBe("# Plan\n- A");
expect(parsed.error).toMatch(/PlanProposedError/);
expect(submitted).toEqual(["# Plan\n- A"]);
});
it("also fires the picker when plan mode is OFF — autonomous proposals", async () => {
const reg = new ToolRegistry();
const submitted: string[] = [];
registerPlanTool(reg, { onPlanSubmitted: (p) => submitted.push(p) });
// Plan mode intentionally NOT enabled.
const out = await reg.dispatch("submit_plan", JSON.stringify({ plan: "big refactor plan" }));
const parsed = JSON.parse(out);
expect(parsed.plan).toBe("big refactor plan");
expect(parsed.error).toMatch(/PlanProposedError/);
expect(submitted).toEqual(["big refactor plan"]);
});
it("rejects an empty plan with a helpful message", async () => {
const reg = new ToolRegistry();
registerPlanTool(reg);
reg.setPlanMode(true);
const out = await reg.dispatch("submit_plan", JSON.stringify({ plan: " \n\n " }));
const parsed = JSON.parse(out);
expect(parsed.error).toMatch(/empty plan/);
// Empty-plan is a regular Error, not PlanProposedError — so there's
// no `plan` field.
expect(parsed.plan).toBeUndefined();
});
it("trims surrounding whitespace from the plan", async () => {
const reg = new ToolRegistry();
registerPlanTool(reg);
reg.setPlanMode(true);
const out = await reg.dispatch("submit_plan", JSON.stringify({ plan: "\n\n trimmed \n" }));
expect(JSON.parse(out).plan).toBe("trimmed");
});
});
+149
View File
@@ -0,0 +1,149 @@
/**
* Tests for the `REASONIX.md` project-memory loader. Pure I/O at the
* edge, so filesystem-backed tests using a temp dir.
*/
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { CODE_SYSTEM_PROMPT, codeSystemPrompt } from "../src/code/prompt.js";
import {
PROJECT_MEMORY_FILE,
PROJECT_MEMORY_MAX_CHARS,
applyProjectMemory,
memoryEnabled,
readProjectMemory,
} from "../src/project-memory.js";
const BASE = "You are a test assistant.";
describe("project-memory", () => {
let root: string;
const originalEnv = process.env.REASONIX_MEMORY;
beforeEach(() => {
root = mkdtempSync(join(tmpdir(), "reasonix-mem-"));
// biome-ignore lint/performance/noDelete: avoid leaking "undefined" into env
delete process.env.REASONIX_MEMORY;
});
afterEach(() => {
rmSync(root, { recursive: true, force: true });
if (originalEnv === undefined) {
// biome-ignore lint/performance/noDelete: same reason
delete process.env.REASONIX_MEMORY;
} else {
process.env.REASONIX_MEMORY = originalEnv;
}
});
describe("readProjectMemory", () => {
it("returns null when REASONIX.md is absent", () => {
expect(readProjectMemory(root)).toBeNull();
});
it("returns null when REASONIX.md is empty / whitespace-only", () => {
writeFileSync(join(root, PROJECT_MEMORY_FILE), " \n\n\t \n", "utf8");
expect(readProjectMemory(root)).toBeNull();
});
it("returns trimmed content + correct metadata for a normal file", () => {
const body = "# Notes\nAlways prefer tabs over spaces in this repo.\n";
writeFileSync(join(root, PROJECT_MEMORY_FILE), `\n\n${body}\n\n`, "utf8");
const mem = readProjectMemory(root);
expect(mem).not.toBeNull();
expect(mem?.content).toBe(body.trim());
expect(mem?.truncated).toBe(false);
expect(mem?.originalChars).toBe(body.trim().length);
expect(mem?.path.endsWith(PROJECT_MEMORY_FILE)).toBe(true);
});
it("truncates with a visible marker when over PROJECT_MEMORY_MAX_CHARS", () => {
const huge = "x".repeat(PROJECT_MEMORY_MAX_CHARS + 1500);
writeFileSync(join(root, PROJECT_MEMORY_FILE), huge, "utf8");
const mem = readProjectMemory(root);
expect(mem?.truncated).toBe(true);
expect(mem?.originalChars).toBe(PROJECT_MEMORY_MAX_CHARS + 1500);
expect(mem?.content).toMatch(/truncated 1500 chars/);
// Content is bounded: first MAX chars + the marker line.
expect(mem?.content.length).toBeLessThan(PROJECT_MEMORY_MAX_CHARS + 64);
});
});
describe("memoryEnabled", () => {
it("defaults to true when env is unset", () => {
expect(memoryEnabled()).toBe(true);
});
it.each(["off", "false", "0"])("returns false for REASONIX_MEMORY=%s", (val) => {
process.env.REASONIX_MEMORY = val;
expect(memoryEnabled()).toBe(false);
});
it("returns true for unrelated env values (on, 1, truthy, etc.)", () => {
for (const val of ["on", "1", "true", "yes"]) {
process.env.REASONIX_MEMORY = val;
expect(memoryEnabled()).toBe(true);
}
});
});
describe("applyProjectMemory", () => {
it("returns the base prompt unchanged when no memory file exists", () => {
expect(applyProjectMemory(BASE, root)).toBe(BASE);
});
it("appends a '# Project memory' fenced block when the file exists", () => {
writeFileSync(
join(root, PROJECT_MEMORY_FILE),
"# Notes\nTreat snake_case as the house style.\n",
"utf8",
);
const out = applyProjectMemory(BASE, root);
expect(out.length).toBeGreaterThan(BASE.length);
expect(out).toMatch(/# Project memory \(REASONIX\.md\)/);
expect(out).toContain("snake_case");
// Fenced block present.
expect(out).toMatch(/```\n[\s\S]*```/);
});
it("no-ops when REASONIX_MEMORY=off, even with a file present", () => {
writeFileSync(join(root, PROJECT_MEMORY_FILE), "content\n", "utf8");
process.env.REASONIX_MEMORY = "off";
expect(applyProjectMemory(BASE, root)).toBe(BASE);
});
it("is deterministic for identical inputs (cache-prefix-safe)", () => {
writeFileSync(join(root, PROJECT_MEMORY_FILE), "stable content\n", "utf8");
const a = applyProjectMemory(BASE, root);
const b = applyProjectMemory(BASE, root);
expect(a).toBe(b);
});
});
describe("codeSystemPrompt integration", () => {
it("stacks base → memory → .gitignore when both files exist", () => {
writeFileSync(
join(root, PROJECT_MEMORY_FILE),
"## House rules\nAlways write tests alongside new tools.\n",
"utf8",
);
writeFileSync(join(root, ".gitignore"), "node_modules/\ndist/\n", "utf8");
const out = codeSystemPrompt(root);
const memIdx = out.indexOf("# Project memory");
const gitIdx = out.indexOf("# Project .gitignore");
expect(memIdx).toBeGreaterThan(CODE_SYSTEM_PROMPT.length - 1);
expect(gitIdx).toBeGreaterThan(memIdx);
expect(out).toContain("Always write tests");
expect(out).toContain("node_modules/");
});
it("memory alone (no .gitignore) still appends only the memory block", () => {
writeFileSync(join(root, PROJECT_MEMORY_FILE), "memory-only content\n", "utf8");
const out = codeSystemPrompt(root);
expect(out).toContain("memory-only content");
expect(out).not.toMatch(/# Project \.gitignore/);
});
});
});
+47
View File
@@ -47,4 +47,51 @@ describe("ToolCallRepair pipeline", () => {
expect(calls.length).toBe(1);
expect(report.scavenged).toBe(0);
});
it("scavenges DSML tool calls from the content channel (regular turn, not just reasoning)", () => {
// R1 sometimes emits the DSML envelope in the content stream
// instead of the proper tool_calls field. Before this wire-up,
// the model's intent was silently dropped.
const repair = new ToolCallRepair({
allowedToolNames: new Set(["filesystem_read_file"]),
});
const content = [
"I'll read the file next.",
'<|DSML|invoke name="filesystem_read_file">',
' <|DSML|parameter name="path" string="true">README.md</|DSML|parameter>',
"</|DSML|invoke>",
].join("\n");
const { calls, report } = repair.process([], null, content);
expect(calls.length).toBe(1);
expect(calls[0]!.function.name).toBe("filesystem_read_file");
expect(JSON.parse(calls[0]!.function.arguments)).toEqual({ path: "README.md" });
expect(report.scavenged).toBe(1);
});
it("does not double-count when DSML appears in both reasoning and content", () => {
const repair = new ToolCallRepair({ allowedToolNames: new Set(["search"]) });
const dsml =
'<|DSML|invoke name="search"><|DSML|parameter name="q" string="true">ts</|DSML|parameter></|DSML|invoke>';
const { calls, report } = repair.process([], dsml, dsml);
expect(calls.length).toBe(1);
expect(report.scavenged).toBe(1);
});
it("resetStorm clears the repeat-window so post-reset calls aren't suppressed", () => {
const repair = new ToolCallRepair({
allowedToolNames: new Set(["x"]),
stormWindow: 6,
stormThreshold: 3,
});
// Build up to the storm threshold — third identical call would be suppressed.
for (let i = 0; i < 2; i++) {
repair.process([call(`c${i}`, "x", "{}")], null);
}
// Mid-turn reset (what step() does on each new user message).
repair.resetStorm();
// With a fresh window the next call passes through — no suppression.
const { calls, report } = repair.process([call("c-after", "x", "{}")], null);
expect(calls.length).toBe(1);
expect(report.stormsBroken).toBe(0);
});
});
+56
View File
@@ -44,4 +44,60 @@ describe("scavengeToolCalls", () => {
const r = scavengeToolCalls(reasoning, { allowedNames: allowed, maxCalls: 2 });
expect(r.calls.length).toBe(2);
});
it("extracts a DSML invoke block with string + JSON parameters", () => {
const dsmlAllowed = new Set(["filesystem_edit_file"]);
const input = [
"Let me make the edit.",
"",
'<|DSML|function_calls> <|DSML|invoke name="filesystem_edit_file">',
' <|DSML|parameter name="path" string="true">F:/x.html</|DSML|parameter>',
' <|DSML|parameter name="edits" string="false">[{"oldText":"a","newText":"b"}]</|DSML|parameter>',
"</|DSML|invoke> </|DSML|function_calls>",
].join("\n");
const r = scavengeToolCalls(input, { allowedNames: dsmlAllowed });
expect(r.calls.length).toBe(1);
const call = r.calls[0]!;
expect(call.function.name).toBe("filesystem_edit_file");
const args = JSON.parse(call.function.arguments);
expect(args.path).toBe("F:/x.html");
expect(args.edits).toEqual([{ oldText: "a", newText: "b" }]);
expect(r.notes[0]).toMatch(/DSML/);
});
it("accepts ASCII pipe DSML variant too", () => {
const dsmlAllowed = new Set(["search"]);
const input =
'<|DSML|invoke name="search"><|DSML|parameter name="q" string="true">ts</|DSML|parameter></|DSML|invoke>';
const r = scavengeToolCalls(input, { allowedNames: dsmlAllowed });
expect(r.calls.length).toBe(1);
expect(JSON.parse(r.calls[0]!.function.arguments)).toEqual({ q: "ts" });
});
it("DSML call with unknown tool name is skipped (allow-list guards us)", () => {
const input =
'<|DSML|invoke name="rm_rf_slash"><|DSML|parameter name="x" string="true">y</|DSML|parameter></|DSML|invoke>';
const r = scavengeToolCalls(input, { allowedNames: allowed });
expect(r.calls).toEqual([]);
});
it("DSML 'string=false' with malformed JSON falls back to literal text (loses no data)", () => {
const dsmlAllowed = new Set(["search"]);
const input =
'<|DSML|invoke name="search"><|DSML|parameter name="q" string="false">not valid json</|DSML|parameter></|DSML|invoke>';
const r = scavengeToolCalls(input, { allowedNames: dsmlAllowed });
expect(r.calls.length).toBe(1);
expect(JSON.parse(r.calls[0]!.function.arguments)).toEqual({ q: "not valid json" });
});
it("does not double-count: JSON args inside a DSML block don't become separate calls", () => {
const dsmlAllowed = new Set(["filesystem_edit_file"]);
// The inner JSON is a param value, not a standalone scavenge target.
const input =
'<|DSML|invoke name="filesystem_edit_file"><|DSML|parameter name="edits" string="false">{"name": "filesystem_edit_file", "arguments": {}}</|DSML|parameter></|DSML|invoke>';
const r = scavengeToolCalls(input, { allowedNames: dsmlAllowed });
// Expect exactly one call — the DSML wrapper. If Pattern B also
// fired on the inner JSON we'd see two.
expect(r.calls.length).toBe(1);
});
});
+30
View File
@@ -0,0 +1,30 @@
import { describe, expect, it } from "vitest";
import { derivePrefix } from "../src/cli/ui/ShellConfirm.js";
describe("derivePrefix", () => {
it("returns the sole token for single-word commands", () => {
expect(derivePrefix("ls")).toBe("ls");
expect(derivePrefix("pytest")).toBe("pytest");
});
it("uses the first two tokens for well-known wrappers", () => {
expect(derivePrefix("npm install lodash")).toBe("npm install");
expect(derivePrefix("git commit -m hi")).toBe("git commit");
expect(derivePrefix("cargo add serde")).toBe("cargo add");
expect(derivePrefix("docker run --rm foo")).toBe("docker run");
expect(derivePrefix("python3 -m pytest tests/")).toBe("python3 -m");
});
it("falls back to the first token for non-wrapper commands", () => {
// `node script.js` — the script name is specific to this invocation,
// so "node" alone is the useful prefix to persist.
expect(derivePrefix("node script.js")).toBe("node");
expect(derivePrefix("curl https://api.example.com")).toBe("curl");
});
it("normalizes whitespace and returns empty on empty input", () => {
expect(derivePrefix(" npm install ")).toBe("npm install");
expect(derivePrefix("")).toBe("");
expect(derivePrefix(" ")).toBe("");
});
});
+514
View File
@@ -0,0 +1,514 @@
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { ToolRegistry } from "../src/tools.js";
import {
NeedsConfirmationError,
formatCommandResult,
isAllowed,
prepareSpawn,
quoteForCmdExe,
registerShellTools,
resolveExecutable,
runCommand,
tokenizeCommand,
} from "../src/tools/shell.js";
describe("tokenizeCommand", () => {
it("splits on whitespace", () => {
expect(tokenizeCommand("git status -s")).toEqual(["git", "status", "-s"]);
});
it("keeps double-quoted spans as single tokens", () => {
expect(tokenizeCommand('grep "hello world" src')).toEqual(["grep", "hello world", "src"]);
});
it("keeps single-quoted spans as single tokens (literal, no backslash escapes)", () => {
expect(tokenizeCommand("echo 'a \\\\ b'")).toEqual(["echo", "a \\\\ b"]);
});
it("supports \\ escapes inside double quotes", () => {
expect(tokenizeCommand('echo "a \\"b\\" c"')).toEqual(["echo", 'a "b" c']);
});
it("rejects unclosed quotes", () => {
expect(() => tokenizeCommand('grep "unclosed')).toThrow(/unclosed/);
expect(() => tokenizeCommand("grep 'unclosed")).toThrow(/unclosed/);
});
it("collapses runs of whitespace", () => {
expect(tokenizeCommand(" git status ")).toEqual(["git", "status"]);
});
it("returns an empty array for an empty command", () => {
expect(tokenizeCommand("")).toEqual([]);
expect(tokenizeCommand(" ")).toEqual([]);
});
});
describe("isAllowed", () => {
it("matches exact prefix and prefix+args", () => {
expect(isAllowed("git status")).toBe(true);
expect(isAllowed("git status -s")).toBe(true);
expect(isAllowed("git statuses")).toBe(false); // no trailing space → not a prefix match
});
it("normalizes internal whitespace", () => {
expect(isAllowed("git status -s")).toBe(true);
});
it("rejects mutating operations not on the list", () => {
expect(isAllowed("git commit -m hi")).toBe(false);
expect(isAllowed("npm install lodash")).toBe(false);
expect(isAllowed("rm -rf dist")).toBe(false);
expect(isAllowed("curl http://example.com")).toBe(false);
});
it("accepts test-runner commands", () => {
expect(isAllowed("pytest tests/")).toBe(true);
expect(isAllowed("cargo test --release")).toBe(true);
expect(isAllowed("npm test")).toBe(true);
});
it("respects extra allowed prefixes", () => {
expect(isAllowed("my-lint src/")).toBe(false);
expect(isAllowed("my-lint src/", ["my-lint"])).toBe(true);
});
});
describe("runCommand", () => {
let tmp: string;
beforeEach(() => {
tmp = mkdtempSync(join(tmpdir(), "reasonix-shell-"));
});
afterEach(() => {
rmSync(tmp, { recursive: true, force: true });
});
it("captures stdout and reports exit 0 on success", async () => {
// `node -e '...'` is cross-platform; avoids cmd/bash differences.
const r = await runCommand("node -e \"process.stdout.write('hello')\"", { cwd: tmp });
expect(r.exitCode).toBe(0);
expect(r.output).toContain("hello");
expect(r.timedOut).toBe(false);
});
it("captures stderr and reports non-zero exit on failure", async () => {
const r = await runCommand("node -e \"process.stderr.write('oops'); process.exit(2)\"", {
cwd: tmp,
});
expect(r.exitCode).toBe(2);
expect(r.output).toContain("oops");
});
it("runs inside the given cwd, not the test's cwd", async () => {
writeFileSync(join(tmp, "marker.txt"), "present");
const r = await runCommand(
"node -e \"const fs=require('fs');process.stdout.write(fs.readFileSync('marker.txt','utf8'))\"",
{ cwd: tmp },
);
expect(r.output).toContain("present");
});
it("kills a command that exceeds the timeout", async () => {
// Sleep longer than timeout; 500ms sleep, 100ms timeout.
const r = await runCommand('node -e "setTimeout(()=>{},5000)"', {
cwd: tmp,
timeoutSec: 0.1 as unknown as number, // cast: the function accepts seconds; 0.1s = 100ms
});
expect(r.timedOut).toBe(true);
});
it("truncates long output with a marker", async () => {
const r = await runCommand("node -e \"process.stdout.write('x'.repeat(50000))\"", {
cwd: tmp,
maxOutputChars: 1000,
});
expect(r.output).toMatch(/\[… truncated \d+ chars …\]$/);
});
it("rejects empty commands", async () => {
await expect(runCommand("", { cwd: tmp })).rejects.toThrow(/empty command/);
});
it("rejects commands with unclosed quotes", async () => {
await expect(runCommand('echo "unclosed', { cwd: tmp })).rejects.toThrow(/unclosed/);
});
});
describe("registerShellTools — dispatch integration", () => {
let tmp: string;
beforeEach(() => {
tmp = mkdtempSync(join(tmpdir(), "reasonix-shell-"));
});
afterEach(() => {
rmSync(tmp, { recursive: true, force: true });
});
it("registers run_command", () => {
const registry = new ToolRegistry();
registerShellTools(registry, { rootDir: tmp });
expect(registry.size).toBe(1);
});
it("auto-runs allowlisted commands and returns formatted output", async () => {
const registry = new ToolRegistry();
registerShellTools(registry, { rootDir: tmp, extraAllowed: ["node"] });
const out = await registry.dispatch(
"run_command",
JSON.stringify({ command: "node --version" }),
);
expect(out).toMatch(/\$ node --version/);
expect(out).toMatch(/\[exit 0\]/);
});
it("refuses non-allowlisted commands with NeedsConfirmationError", async () => {
const registry = new ToolRegistry();
registerShellTools(registry, { rootDir: tmp });
const out = await registry.dispatch(
"run_command",
JSON.stringify({ command: "rm -rf node_modules" }),
);
expect(out).toMatch(/NeedsConfirmationError/);
expect(out).toMatch(/rm -rf node_modules/);
});
it("allowAll:true bypasses the allowlist entirely", async () => {
const registry = new ToolRegistry();
registerShellTools(registry, { rootDir: tmp, allowAll: true, extraAllowed: [] });
const out = await registry.dispatch(
"run_command",
JSON.stringify({ command: "node -e \"process.stdout.write('ok')\"" }),
);
expect(out).toMatch(/\[exit 0\]/);
expect(out).toContain("ok");
});
it("extraAllowed as a getter is re-read on every dispatch", async () => {
// Regression: picking "always allow" in ShellConfirm wrote to disk
// but the running run_command captured a stale snapshot, so the
// same command got re-prompted until the next launch. Getter form
// fixes this by re-resolving the allowlist on each call.
//
// `node -e` is deliberately NOT in BUILTIN_ALLOWLIST — only
// `node --version` / `node -v` are — so the "before" call must go
// through the extraAllowed path to succeed.
const cmd = "node -e \"process.stdout.write('ok')\"";
const registry = new ToolRegistry();
const list: string[] = [];
registerShellTools(registry, { rootDir: tmp, extraAllowed: () => list });
const before = await registry.dispatch("run_command", JSON.stringify({ command: cmd }));
expect(before).toMatch(/NeedsConfirmationError/);
// Simulate the TUI's "always allow" click — mutate the source the
// getter reads. No re-registration; the live tool instance picks
// it up.
list.push("node -e");
const after = await registry.dispatch("run_command", JSON.stringify({ command: cmd }));
expect(after).not.toMatch(/NeedsConfirmationError/);
expect(after).toMatch(/\[exit 0\]/);
expect(after).toContain("ok");
});
});
describe("formatCommandResult", () => {
it("marks the exit code on success", () => {
expect(formatCommandResult("ls", { exitCode: 0, output: "a\nb", timedOut: false })).toBe(
"$ ls\n[exit 0]\na\nb",
);
});
it("marks a killed-on-timeout run", () => {
expect(formatCommandResult("sleep 10", { exitCode: null, output: "", timedOut: true })).toBe(
"$ sleep 10\n[killed after timeout]",
);
});
it("elides the body when output is empty", () => {
expect(formatCommandResult("true", { exitCode: 0, output: "", timedOut: false })).toBe(
"$ true\n[exit 0]",
);
});
});
describe("resolveExecutable", () => {
it("returns the input unchanged on non-Windows platforms", () => {
expect(resolveExecutable("npm", { platform: "linux" })).toBe("npm");
expect(resolveExecutable("pytest", { platform: "darwin" })).toBe("pytest");
});
it("returns empty input unchanged", () => {
expect(resolveExecutable("", { platform: "win32" })).toBe("");
});
it("walks PATH × PATHEXT on Windows and returns the first hit", () => {
// PATHEXT case is preserved into the joined path, so the mock
// "filesystem" keys must match that case verbatim.
const hits = new Set(["C:\\tools\\npm.CMD"]);
const out = resolveExecutable("npm", {
platform: "win32",
env: { PATH: "C:\\nope;C:\\tools", PATHEXT: ".COM;.EXE;.BAT;.CMD" },
pathDelimiter: ";",
isFile: (p) => hits.has(p),
});
expect(out).toBe("C:\\tools\\npm.CMD");
});
it("honors PATHEXT ordering (.EXE beats .CMD when both exist)", () => {
const hits = new Set(["C:\\bin\\foo.EXE", "C:\\bin\\foo.CMD"]);
const out = resolveExecutable("foo", {
platform: "win32",
env: { PATH: "C:\\bin", PATHEXT: ".EXE;.CMD" },
pathDelimiter: ";",
isFile: (p) => hits.has(p),
});
expect(out).toBe("C:\\bin\\foo.EXE");
});
it("falls back to the raw cmd when PATH × PATHEXT yields nothing", () => {
const out = resolveExecutable("doesnotexist", {
platform: "win32",
env: { PATH: "C:\\bin", PATHEXT: ".EXE" },
pathDelimiter: ";",
isFile: () => false,
});
expect(out).toBe("doesnotexist");
});
it("skips lookup for absolute paths (\\ or /)", () => {
const called: string[] = [];
const out1 = resolveExecutable("C:\\tools\\npm.cmd", {
platform: "win32",
env: { PATH: "C:\\bin", PATHEXT: ".CMD" },
isFile: (p) => {
called.push(p);
return true;
},
});
expect(out1).toBe("C:\\tools\\npm.cmd");
const out2 = resolveExecutable("src/tool.js", {
platform: "win32",
env: { PATH: "C:\\bin", PATHEXT: ".CMD" },
isFile: () => true,
});
expect(out2).toBe("src/tool.js");
expect(called).toEqual([]);
});
it("skips lookup when the cmd already has an extension", () => {
const called: string[] = [];
const out = resolveExecutable("npm.cmd", {
platform: "win32",
env: { PATH: "C:\\bin", PATHEXT: ".CMD" },
isFile: (p) => {
called.push(p);
return true;
},
});
expect(out).toBe("npm.cmd");
expect(called).toEqual([]);
});
it("tolerates missing PATH / PATHEXT — returns cmd unchanged", () => {
const out = resolveExecutable("npm", {
platform: "win32",
env: {},
pathDelimiter: ";",
isFile: () => false,
});
expect(out).toBe("npm");
});
it("handles whitespace inside PATHEXT entries (' .CMD ' → '.CMD')", () => {
const hits = new Set(["C:\\bin\\npm.CMD"]);
const out = resolveExecutable("npm", {
platform: "win32",
env: { PATH: "C:\\bin", PATHEXT: " .CMD ; .EXE " },
pathDelimiter: ";",
isFile: (p) => hits.has(p),
});
expect(out).toBe("C:\\bin\\npm.CMD");
});
});
describe("quoteForCmdExe", () => {
it("leaves simple identifiers alone", () => {
expect(quoteForCmdExe("install")).toBe("install");
expect(quoteForCmdExe("foo-bar_123")).toBe("foo-bar_123");
});
it("double-quotes whitespace and cmd metacharacters", () => {
expect(quoteForCmdExe("hello world")).toBe('"hello world"');
expect(quoteForCmdExe("a&b")).toBe('"a&b"');
expect(quoteForCmdExe("a|b")).toBe('"a|b"');
expect(quoteForCmdExe("a>b")).toBe('"a>b"');
expect(quoteForCmdExe("a<b")).toBe('"a<b"');
expect(quoteForCmdExe("a^b")).toBe('"a^b"');
expect(quoteForCmdExe("a;b")).toBe('"a;b"');
});
it("doubles embedded quotes (cmd.exe escape rule)", () => {
expect(quoteForCmdExe('say "hi"')).toBe('"say ""hi"""');
});
it("empty string becomes an explicit empty-pair", () => {
expect(quoteForCmdExe("")).toBe('""');
});
it("round-trips `npm install foo` safely", () => {
const argv = ["C:\\Program Files\\nodejs\\npm.cmd", "install", "foo"];
const cmdline = argv.map(quoteForCmdExe).join(" ");
expect(cmdline).toBe('"C:\\Program Files\\nodejs\\npm.cmd" install foo');
});
});
describe("prepareSpawn", () => {
it("passes through unchanged on non-Windows", () => {
const out = prepareSpawn(["npm", "install"], { platform: "linux" });
expect(out.bin).toBe("npm");
expect(out.args).toEqual(["install"]);
expect(out.spawnOverrides).toEqual({});
});
it("wraps .cmd files through cmd.exe on Windows (post-CVE-2024-27980)", () => {
// Real-world install path with a space → quoting required.
const hits = new Set(["C:\\Program Files\\nodejs\\npm.CMD"]);
const out = prepareSpawn(["npm", "install", "foo"], {
platform: "win32",
env: { PATH: "C:\\Program Files\\nodejs", PATHEXT: ".EXE;.CMD" },
pathDelimiter: ";",
isFile: (p) => hits.has(p),
});
expect(out.bin).toBe("cmd.exe");
expect(out.args).toEqual([
"/d",
"/s",
"/c",
'"C:\\Program Files\\nodejs\\npm.CMD" install foo',
]);
expect(out.spawnOverrides.windowsVerbatimArguments).toBe(true);
});
it("wraps .cmd files without quoting when the resolved path has no metacharacters", () => {
const hits = new Set(["C:\\tools\\npm.CMD"]);
const out = prepareSpawn(["npm", "install"], {
platform: "win32",
env: { PATH: "C:\\tools", PATHEXT: ".EXE;.CMD" },
pathDelimiter: ";",
isFile: (p) => hits.has(p),
});
// No spaces in the path ⇒ no surrounding quotes; cmd.exe parses
// backslashes literally.
expect(out.args[3]).toBe("C:\\tools\\npm.CMD install");
});
it("wraps .bat files too", () => {
const hits = new Set(["C:\\bin\\gradle.BAT"]);
const out = prepareSpawn(["gradle", "build"], {
platform: "win32",
env: { PATH: "C:\\bin", PATHEXT: ".BAT" },
pathDelimiter: ";",
isFile: (p) => hits.has(p),
});
expect(out.bin).toBe("cmd.exe");
expect(out.args[3]).toMatch(/gradle\.BAT/);
});
it("spawns .exe directly (no cmd.exe wrapping)", () => {
const hits = new Set(["C:\\Program Files\\nodejs\\node.EXE"]);
const out = prepareSpawn(["node", "--version"], {
platform: "win32",
env: { PATH: "C:\\Program Files\\nodejs", PATHEXT: ".EXE;.CMD" },
pathDelimiter: ";",
isFile: (p) => hits.has(p),
});
expect(out.bin).toBe("C:\\Program Files\\nodejs\\node.EXE");
expect(out.args).toEqual(["--version"]);
expect(out.spawnOverrides).toEqual({});
});
it("cmd.exe-wrapping quotes args containing metacharacters", () => {
const hits = new Set(["C:\\tools\\tool.CMD"]);
const out = prepareSpawn(["tool", "a&b", "c|d"], {
platform: "win32",
env: { PATH: "C:\\tools", PATHEXT: ".CMD" },
pathDelimiter: ";",
isFile: (p) => hits.has(p),
});
expect(out.args[3]).toBe('C:\\tools\\tool.CMD "a&b" "c|d"');
});
it("routes bare unresolved Windows commands through cmd.exe (builtins)", () => {
// `dir`, `echo`, `type`, `ver`, … are cmd.exe built-ins — they
// don't exist as standalone exes, so PATHEXT lookup misses and a
// direct spawn ENOENTs. Wrapping in cmd.exe lets them resolve,
// and gives unknown commands a proper "'x' is not recognized"
// exit code instead of a raw spawn failure.
const out = prepareSpawn(["dir", ".reasonix"], {
platform: "win32",
env: { PATH: "C:\\nope", PATHEXT: ".EXE" },
pathDelimiter: ";",
isFile: () => false,
});
expect(out.bin).toBe("cmd.exe");
expect(out.args).toEqual(["/d", "/s", "/c", "dir .reasonix"]);
expect(out.spawnOverrides.windowsVerbatimArguments).toBe(true);
});
it("cmd.exe builtin wrapping quotes metacharacter args", () => {
const out = prepareSpawn(["echo", "a & b"], {
platform: "win32",
env: { PATH: "C:\\nope", PATHEXT: ".EXE" },
pathDelimiter: ";",
isFile: () => false,
});
expect(out.bin).toBe("cmd.exe");
expect(out.args[3]).toBe('echo "a & b"');
});
it("does not wrap paths-with-separators through cmd.exe", () => {
// Absolute or slash-containing inputs are NOT bare names; they're
// explicit disk paths — if the user points at a nonexistent one
// we want the spawn to ENOENT plainly, not through cmd.exe.
const out = prepareSpawn(["C:\\missing\\tool.exe", "arg"], {
platform: "win32",
env: { PATH: "", PATHEXT: ".EXE" },
pathDelimiter: ";",
isFile: () => false,
});
expect(out.bin).toBe("C:\\missing\\tool.exe");
expect(out.args).toEqual(["arg"]);
});
it("does not wrap already-extensioned commands", () => {
// `node.exe` with no PATH hit → user passed an explicit name;
// pass it straight to spawn (will ENOENT if truly absent).
const out = prepareSpawn(["node.exe", "-v"], {
platform: "win32",
env: { PATH: "", PATHEXT: ".EXE" },
pathDelimiter: ";",
isFile: () => false,
});
expect(out.bin).toBe("node.exe");
expect(out.args).toEqual(["-v"]);
});
});
describe("NeedsConfirmationError", () => {
it("carries the rejected command on the instance", () => {
const e = new NeedsConfirmationError("rm -rf /");
expect(e.command).toBe("rm -rf /");
expect(e.name).toBe("NeedsConfirmationError");
expect(e.message).toMatch(/rm -rf \//);
});
it("tells the model to stop and wait, not to retry", () => {
const e = new NeedsConfirmationError("npm install");
expect(e.message).toMatch(/STOP calling tools/i);
expect(e.message).toMatch(/y.*run.*n.*deny/i);
expect(e.message).not.toMatch(/apply-shell/);
});
});
+221
View File
@@ -0,0 +1,221 @@
/**
* Tests for the Skills store + prefix-index composer. Every test runs
* against a temp `homeDir` (global scope) and a temp `projectRoot`
* (project scope) so we never touch the developer's real skill dirs.
*/
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { SkillStore, applySkillsIndex } from "../src/skills.js";
const BASE = "You are a test assistant.";
type SkillRoot = "project" | "global";
function writeSkillDir(
root: string,
which: SkillRoot,
name: string,
frontmatter: Record<string, string>,
body: string,
homeOrProject: string,
): string {
const parent =
which === "global"
? join(homeOrProject, ".reasonix", "skills")
: join(root, ".reasonix", "skills");
const dir = join(parent, name);
mkdirSync(dir, { recursive: true });
const fmLines = ["---"];
for (const [k, v] of Object.entries(frontmatter)) fmLines.push(`${k}: ${v}`);
fmLines.push("---", "");
const path = join(dir, "SKILL.md");
writeFileSync(path, `${fmLines.join("\n")}${body}\n`, "utf8");
return path;
}
function writeFlatSkill(
dir: string,
name: string,
frontmatter: Record<string, string>,
body: string,
): string {
const skills = join(dir, ".reasonix", "skills");
mkdirSync(skills, { recursive: true });
const fmLines = ["---"];
for (const [k, v] of Object.entries(frontmatter)) fmLines.push(`${k}: ${v}`);
fmLines.push("---", "");
const path = join(skills, `${name}.md`);
writeFileSync(path, `${fmLines.join("\n")}${body}\n`, "utf8");
return path;
}
describe("SkillStore", () => {
let home: string;
let projectRoot: string;
beforeEach(() => {
home = mkdtempSync(join(tmpdir(), "reasonix-skills-home-"));
projectRoot = mkdtempSync(join(tmpdir(), "reasonix-skills-proj-"));
});
afterEach(() => {
rmSync(home, { recursive: true, force: true });
rmSync(projectRoot, { recursive: true, force: true });
});
it("returns an empty list when no skill dirs exist", () => {
const store = new SkillStore({ homeDir: home, projectRoot });
expect(store.list()).toEqual([]);
});
it("hasProjectScope reflects constructor argument", () => {
expect(new SkillStore({ homeDir: home }).hasProjectScope()).toBe(false);
expect(new SkillStore({ homeDir: home, projectRoot }).hasProjectScope()).toBe(true);
});
it("parses a SKILL.md dir-layout entry from the global scope", () => {
writeSkillDir(
projectRoot,
"global",
"review",
{ name: "review", description: "Review a pull request" },
"Run `git diff` and summarize risks.",
home,
);
const skills = new SkillStore({ homeDir: home, projectRoot }).list();
expect(skills).toHaveLength(1);
expect(skills[0]?.name).toBe("review");
expect(skills[0]?.scope).toBe("global");
expect(skills[0]?.body).toContain("git diff");
});
it("reads flat <name>.md files as well", () => {
writeFlatSkill(home, "ship-it", { description: "Commit and push changes" }, "body");
const skills = new SkillStore({ homeDir: home, projectRoot }).list();
expect(skills.map((s) => s.name)).toEqual(["ship-it"]);
expect(skills[0]?.description).toBe("Commit and push changes");
});
it("surfaces project-scope skills from <projectRoot>/.reasonix/skills", () => {
writeSkillDir(
projectRoot,
"project",
"deploy",
{ description: "Deploy to staging" },
"Run the staging pipeline.",
home,
);
const list = new SkillStore({ homeDir: home, projectRoot }).list();
expect(list).toHaveLength(1);
expect(list[0]?.scope).toBe("project");
expect(list[0]?.path).toContain(projectRoot);
});
it("project scope wins on a name collision with global", () => {
writeSkillDir(projectRoot, "global", "review", { description: "global one" }, "G", home);
writeSkillDir(projectRoot, "project", "review", { description: "project one" }, "P", home);
const store = new SkillStore({ homeDir: home, projectRoot });
const list = store.list();
expect(list).toHaveLength(1);
expect(list[0]?.scope).toBe("project");
expect(list[0]?.description).toBe("project one");
expect(store.read("review")?.body).toBe("P");
});
it("without projectRoot the store only reads the global scope", () => {
// Put a skill in the project dir and a skill in the global dir.
writeSkillDir(projectRoot, "project", "deploy", { description: "proj" }, "P", home);
writeSkillDir(projectRoot, "global", "review", { description: "glob" }, "G", home);
const store = new SkillStore({ homeDir: home }); // no projectRoot
const names = store.list().map((s) => s.name);
expect(names).toEqual(["review"]);
expect(store.hasProjectScope()).toBe(false);
});
it("rejects invalid skill names on read()", () => {
const store = new SkillStore({ homeDir: home, projectRoot });
expect(store.read("../etc/passwd")).toBeNull();
expect(store.read("foo/bar")).toBeNull();
expect(store.read("")).toBeNull();
});
it("skips dotfiles that would masquerade as skills", () => {
writeSkillDir(projectRoot, "global", "ok", { description: "fine" }, "body", home);
const dotDir = join(home, ".reasonix", "skills");
writeFileSync(join(dotDir, ".hidden.md"), "---\ndescription: x\n---\nbody\n", "utf8");
const list = new SkillStore({ homeDir: home, projectRoot }).list();
expect(list.map((s) => s.name)).toEqual(["ok"]);
});
});
describe("applySkillsIndex", () => {
let home: string;
let projectRoot: string;
beforeEach(() => {
home = mkdtempSync(join(tmpdir(), "reasonix-skills-idx-"));
projectRoot = mkdtempSync(join(tmpdir(), "reasonix-skills-idx-proj-"));
});
afterEach(() => {
rmSync(home, { recursive: true, force: true });
rmSync(projectRoot, { recursive: true, force: true });
});
it("returns the prompt unchanged when no skills exist", () => {
const out = applySkillsIndex(BASE, { homeDir: home, projectRoot });
expect(out).toBe(BASE);
});
it("emits a Skills section with one-liners but not bodies", () => {
writeSkillDir(
projectRoot,
"global",
"review",
{ description: "Review a pull request" },
"BODY-THAT-MUST-NOT-APPEAR",
home,
);
writeSkillDir(
projectRoot,
"global",
"init",
{ description: "Initialize a CLAUDE.md" },
"ALSO-SECRET",
home,
);
const out = applySkillsIndex(BASE, { homeDir: home, projectRoot });
expect(out).toContain("# Skills");
expect(out).toContain("- init — Initialize a CLAUDE.md");
expect(out).toContain("- review — Review a pull request");
expect(out).not.toContain("BODY-THAT-MUST-NOT-APPEAR");
expect(out).not.toContain("ALSO-SECRET");
});
it("merges project + global skills into a single index", () => {
writeSkillDir(projectRoot, "global", "hello", { description: "global hello" }, "x", home);
writeSkillDir(projectRoot, "project", "deploy", { description: "project deploy" }, "y", home);
const out = applySkillsIndex(BASE, { homeDir: home, projectRoot });
expect(out).toContain("- deploy — project deploy");
expect(out).toContain("- hello — global hello");
});
it("omits skills with blank descriptions from the pinned index", () => {
writeSkillDir(projectRoot, "global", "has-desc", { description: "I have one" }, "body", home);
writeSkillDir(projectRoot, "global", "no-desc", {}, "body", home);
const out = applySkillsIndex(BASE, { homeDir: home, projectRoot });
expect(out).toContain("- has-desc —");
expect(out).not.toContain("- no-desc");
});
it("is byte-stable across two calls with the same filesystem state", () => {
writeSkillDir(projectRoot, "global", "a", { description: "one" }, "x", home);
writeSkillDir(projectRoot, "global", "b", { description: "two" }, "y", home);
const first = applySkillsIndex(BASE, { homeDir: home, projectRoot });
const second = applySkillsIndex(BASE, { homeDir: home, projectRoot });
expect(first).toBe(second);
});
});
+449 -6
View File
@@ -1,8 +1,17 @@
import { describe, expect, it, vi } from "vitest";
import { handleSlash, parseSlash } from "../src/cli/ui/slash.js";
import { DeepSeekClient } from "../src/client.js";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
SLASH_COMMANDS,
handleSlash,
parseSlash,
suggestSlashCommands,
} from "../src/cli/ui/slash.js";
import { DeepSeekClient, Usage } from "../src/client.js";
import { CacheFirstLoop } from "../src/loop.js";
import { ImmutablePrefix } from "../src/memory.js";
import { VERSION } from "../src/version.js";
function makeLoop() {
const client = new DeepSeekClient({
@@ -35,8 +44,40 @@ describe("handleSlash", () => {
expect(handleSlash("quit", [], loop).exit).toBe(true);
});
it("/clear requests history clear", () => {
expect(handleSlash("clear", [], makeLoop()).clear).toBe(true);
it("/clear requests history clear + surfaces an info line about what it does", () => {
const r = handleSlash("clear", [], makeLoop());
expect(r.clear).toBe(true);
// Clear should also explain that context is NOT dropped — users
// keep confusing this with /new.
expect(r.info).toMatch(/visible scrollback only/);
expect(r.info).toMatch(/\/new/);
});
it("/new drops in-memory context AND clears scrollback", () => {
const loop = makeLoop();
loop.log.append({ role: "user", content: "message 1" });
loop.log.append({ role: "assistant", content: "reply 1" });
loop.log.append({ role: "user", content: "message 2" });
expect(loop.log.length).toBe(3);
const r = handleSlash("new", [], loop);
expect(r.clear).toBe(true);
expect(r.info).toMatch(/dropped 3/);
expect(loop.log.length).toBe(0);
});
it("/reset is an alias for /new (muscle memory)", () => {
const loop = makeLoop();
loop.log.append({ role: "user", content: "hi" });
const r = handleSlash("reset", [], loop);
expect(r.clear).toBe(true);
expect(loop.log.length).toBe(0);
});
it("/help distinguishes /clear (visual-only) from /new (drops context)", () => {
const r = handleSlash("help", [], makeLoop());
expect(r.info).toMatch(/\/new/);
// Wording explicitly notes context is kept on /clear.
expect(r.info).toMatch(/clear displayed scrollback only/);
});
it("/help returns a multi-line message", () => {
@@ -49,7 +90,9 @@ describe("handleSlash", () => {
it("/status reflects current loop config", () => {
const loop = makeLoop();
const r = handleSlash("status", [], loop);
expect(r.info).toMatch(/model=/);
// New format: indented table with labeled rows ("model", "flags",
// "ctx", "mcp", "session"). Harvest/branch live on the flags row.
expect(r.info).toMatch(/model\s+deepseek-/);
expect(r.info).toMatch(/harvest=off/);
expect(r.info).toMatch(/branch=off/);
});
@@ -304,6 +347,262 @@ describe("handleSlash", () => {
expect(r.info).toMatch(/\/think/);
});
it("/retry returns info + resubmit when there's a prior user message", () => {
const loop = makeLoop();
loop.log.append({ role: "user", content: "hello" });
loop.log.append({ role: "assistant", content: "hi back" });
const r = handleSlash("retry", [], loop);
expect(r.resubmit).toBe("hello");
expect(r.info).toMatch(/retrying/);
// After retry, the log should be empty (last user message and
// everything after were dropped; user will be re-pushed on next
// successful turn).
expect(loop.log.length).toBe(0);
});
it("/retry says nothing to retry when log has no user messages", () => {
const r = handleSlash("retry", [], makeLoop());
expect(r.info).toMatch(/nothing to retry/);
expect(r.resubmit).toBeUndefined();
});
it("/help mentions /retry", () => {
const r = handleSlash("help", [], makeLoop());
expect(r.info).toMatch(/\/retry/);
});
it("/tool with no history says none yet", () => {
const r = handleSlash("tool", [], makeLoop());
expect(r.info).toMatch(/no tool calls yet/);
});
it("/tool with history lists entries, most recent first", () => {
const r = handleSlash("tool", [], makeLoop(), {
toolHistory: () => [
{ toolName: "fs_read_file", text: "old content" },
{ toolName: "fs_list_directory", text: "newer content" },
],
});
expect(r.info).toMatch(/Tool calls in this session \(2/);
// Most recent is #1 — the list must order so fs_list_directory
// (newer) appears before fs_read_file (older).
const idxNewer = r.info!.indexOf("fs_list_directory");
const idxOlder = r.info!.indexOf("fs_read_file");
expect(idxNewer).toBeGreaterThan(-1);
expect(idxOlder).toBeGreaterThan(idxNewer);
});
it("/tool N dumps the Nth-most-recent tool output in full", () => {
const big = "X".repeat(2000);
const r = handleSlash("tool", ["1"], makeLoop(), {
toolHistory: () => [
{ toolName: "fs_read_file", text: "older" },
{ toolName: "fs_list_directory", text: big },
],
});
expect(r.info).toMatch(/tool<fs_list_directory>/);
expect(r.info).toMatch(/2000 chars/);
// Full 2000 X's included — not truncated.
expect(r.info).toContain(big);
});
it("/tool 2 reaches one call back from the most recent", () => {
const r = handleSlash("tool", ["2"], makeLoop(), {
toolHistory: () => [
{ toolName: "fs_read_file", text: "target" },
{ toolName: "fs_list_directory", text: "most recent" },
],
});
expect(r.info).toMatch(/tool<fs_read_file>/);
expect(r.info).toContain("target");
});
it("/tool N past history length reports bounds", () => {
const r = handleSlash("tool", ["5"], makeLoop(), {
toolHistory: () => [{ toolName: "fs_read_file", text: "one" }],
});
expect(r.info).toMatch(/only 1 tool call/);
});
it("/tool with non-numeric arg returns usage", () => {
const r = handleSlash("tool", ["huh"], makeLoop(), {
toolHistory: () => [{ toolName: "fs_read_file", text: "one" }],
});
expect(r.info).toMatch(/usage: \/tool/);
});
it("/tool list trims the display to 10 most recent but hints at older", () => {
const many = Array.from({ length: 15 }, (_, i) => ({
toolName: `t${i}`,
text: `call-${i}`,
}));
const r = handleSlash("tool", [], makeLoop(), { toolHistory: () => many });
// Most recent (#1 = t14) and 10th back (#10 = t5) should be shown.
expect(r.info).toContain("t14");
expect(r.info).toContain("t5");
// t4 would be #11 — beyond the first-page cutoff.
expect(r.info).toMatch(/5 earlier.*reach with \/tool N/);
});
it("/help mentions /tool", () => {
const r = handleSlash("help", [], makeLoop());
expect(r.info).toMatch(/\/tool/);
});
it("SLASH_COMMANDS registry contains every handler switch case", () => {
// Spot-check a handful so the registry doesn't silently drift
// from `handleSlash`. If a new case lands in handleSlash, it
// should also show up in suggestions — bump this list when
// adding.
const names = SLASH_COMMANDS.map((s) => s.cmd);
for (const required of [
"help",
"status",
"preset",
"model",
"branch",
"mcp",
"tool",
"memory",
"think",
"retry",
"compact",
"sessions",
"clear",
"exit",
"apply",
"discard",
"undo",
"commit",
"plan",
"apply-plan",
]) {
expect(names, `registry missing /${required}`).toContain(required);
}
});
it("suggestSlashCommands filters by prefix", () => {
expect(suggestSlashCommands("h").map((s) => s.cmd)).toEqual(["help", "harvest", "hooks"]);
// Case-insensitive.
expect(suggestSlashCommands("HE").map((s) => s.cmd)).toEqual(["help"]);
// Empty prefix returns everything (non-contextual).
expect(suggestSlashCommands("").length).toBeGreaterThan(5);
});
describe("/update", () => {
it("reports pending check when latestVersion is null (offline / in flight)", () => {
const r = handleSlash("update", [], makeLoop(), { latestVersion: null });
expect(r.info).toMatch(/current: reasonix/);
expect(r.info).toMatch(/not yet resolved/);
expect(r.info).toMatch(/reasonix update/);
});
it("reports up-to-date when current matches latest", () => {
const r = handleSlash("update", [], makeLoop(), { latestVersion: VERSION });
expect(r.info).toMatch(/on the latest/);
expect(r.info).not.toMatch(/npm install/);
});
it("prints shell command when latest is newer than current", () => {
const r = handleSlash("update", [], makeLoop(), { latestVersion: "99.99.99" });
expect(r.info).toMatch(/99\.99\.99/);
expect(r.info).toMatch(/reasonix update/);
expect(r.info).toMatch(/npm install -g reasonix@latest/);
});
it("is surfaced by suggestSlashCommands", () => {
const names = suggestSlashCommands("up").map((s) => s.cmd);
expect(names).toContain("update");
});
});
describe("/stats", () => {
it("prints a how-to when the usage log is empty / missing", () => {
// Use the real ~ here — if a real log exists (developer machine),
// this test would see real data. We assert only on a substring
// that's present either way: the path is always mentioned.
const r = handleSlash("stats", [], makeLoop());
expect(r.info).toMatch(/usage\.jsonl|turns/);
});
it("is surfaced by suggestSlashCommands", () => {
const names = suggestSlashCommands("sta").map((s) => s.cmd);
expect(names).toContain("stats");
});
});
it("suggestSlashCommands hides code-mode-only entries when codeMode=false", () => {
const names = suggestSlashCommands("", false).map((s) => s.cmd);
expect(names).not.toContain("apply");
expect(names).not.toContain("undo");
});
it("suggestSlashCommands shows code-mode-only entries when codeMode=true", () => {
const names = suggestSlashCommands("", true).map((s) => s.cmd);
expect(names).toContain("apply");
expect(names).toContain("undo");
});
it("/mcp with mcpServers renders per-server tools+resources+prompts", () => {
const r = handleSlash("mcp", [], makeLoop(), {
mcpServers: [
{
label: "fs",
spec: "fs=npx -y @scope/fs /tmp",
toolCount: 4,
report: {
protocolVersion: "2024-11-05",
serverInfo: { name: "fs-server", version: "1.0.0" },
capabilities: { tools: {}, resources: {} },
tools: { supported: true, items: [] },
resources: {
supported: true,
items: [
{ uri: "file:///a", name: "docs" },
{ uri: "file:///b", name: "readme" },
],
},
prompts: { supported: false, reason: "method not found (-32601)" },
},
},
],
});
expect(r.info).toMatch(/\[fs\].*fs-server v1\.0\.0/);
expect(r.info).toMatch(/tools\s+4/);
expect(r.info).toMatch(/resources\s+2\s+\[docs, readme\]/);
expect(r.info).toMatch(/prompts\s+\(not supported\)/);
});
it("/mcp falls back to the spec-only list when mcpServers is absent", () => {
const r = handleSlash("mcp", [], makeLoop(), {
mcpSpecs: ["filesystem=npx -y @scope/fs /tmp"],
});
expect(r.info).toMatch(/MCP servers \(1\)/);
expect(r.info).toMatch(/server-filesystem|fs/);
});
it("/status shows ctx / session / mcp / pending lines with rich detail", () => {
const loop = makeLoop();
// Make it look like one turn ran so lastPromptTokens > 0.
loop.stats.record(1, loop.model, new Usage(42_000, 50, 42_050, 40_000, 2_000));
loop.log.append({ role: "user", content: "hi" });
loop.log.append({ role: "assistant", content: "there" });
const r = handleSlash("status", [], loop, {
mcpSpecs: ["filesystem=npx -y @scope/fs /tmp", "mem=npx -y @scope/mem"],
pendingEditCount: 3,
});
expect(r.info).toMatch(/model\s+deepseek-/);
expect(r.info).toMatch(/ctx\s+\d+\.?\d*k?\/\d+k/);
expect(r.info).toMatch(/mcp\s+2 server\(s\)/);
expect(r.info).toMatch(/session.*\(ephemeral|session\s+"/);
expect(r.info).toMatch(/edits\s+3 pending/);
});
it("/status with pendingEditCount=0 hides the edits line", () => {
const r = handleSlash("status", [], makeLoop(), { pendingEditCount: 0 });
expect(r.info).not.toMatch(/pending/);
});
it("/commit strips surrounding double quotes from the message", () => {
// We can't exercise git without a real repo; instead, rely on the
// fact that /commit fails (no git repo at /nonexistent) but the
@@ -328,4 +627,148 @@ describe("handleSlash", () => {
const r = handleSlash("forget", [], loop);
expect(r.info).toMatch(/nothing to forget/);
});
describe("/memory", () => {
let root: string;
const originalEnv = process.env.REASONIX_MEMORY;
beforeEach(() => {
root = mkdtempSync(join(tmpdir(), "reasonix-mem-slash-"));
// biome-ignore lint/performance/noDelete: avoid "undefined" in env
delete process.env.REASONIX_MEMORY;
});
afterEach(() => {
rmSync(root, { recursive: true, force: true });
if (originalEnv === undefined) {
// biome-ignore lint/performance/noDelete: same reason
delete process.env.REASONIX_MEMORY;
} else {
process.env.REASONIX_MEMORY = originalEnv;
}
});
it("prints a how-to when no memory (REASONIX.md or ~/.reasonix/memory) exists", () => {
const r = handleSlash("memory", [], makeLoop(), { memoryRoot: root });
expect(r.info).toMatch(/no memory pinned/);
expect(r.info).toMatch(/REASONIX\.md/);
});
it("prints the REASONIX.md contents + path when present", () => {
writeFileSync(
join(root, "REASONIX.md"),
"# House rules\nSnake case only in this repo.\n",
"utf8",
);
const r = handleSlash("memory", [], makeLoop(), { memoryRoot: root });
expect(r.info).toMatch(/▸ REASONIX\.md:/);
expect(r.info).toContain("Snake case only");
expect(r.info).toMatch(/chars/);
});
it("says memory is disabled when REASONIX_MEMORY=off, even with a file present", () => {
writeFileSync(join(root, "REASONIX.md"), "content", "utf8");
process.env.REASONIX_MEMORY = "off";
const r = handleSlash("memory", [], makeLoop(), { memoryRoot: root });
expect(r.info).toMatch(/memory is disabled/);
});
it("refuses to guess a root when memoryRoot is absent", () => {
const r = handleSlash("memory", [], makeLoop());
expect(r.info).toMatch(/no working directory/);
});
});
describe("/plan + /apply-plan", () => {
it("/plan replies 'only in code mode' when setPlanMode callback is missing", () => {
const r = handleSlash("plan", [], makeLoop());
expect(r.info).toMatch(/only available inside `reasonix code`/);
});
it("/plan toggles when called with no args", () => {
const calls: boolean[] = [];
const r1 = handleSlash("plan", [], makeLoop(), {
planMode: false,
setPlanMode: (on) => calls.push(on),
});
expect(calls).toEqual([true]);
expect(r1.info).toMatch(/plan mode ON/);
const r2 = handleSlash("plan", [], makeLoop(), {
planMode: true,
setPlanMode: (on) => calls.push(on),
});
expect(calls).toEqual([true, false]);
expect(r2.info).toMatch(/plan mode OFF/);
});
it("/plan on / off / true / false / 0 / 1 parse correctly", () => {
const check = (arg: string, expected: boolean) => {
const calls: boolean[] = [];
handleSlash("plan", [arg], makeLoop(), {
planMode: !expected, // start from the opposite
setPlanMode: (on) => calls.push(on),
});
expect(calls, `arg=${arg}`).toEqual([expected]);
};
check("on", true);
check("true", true);
check("1", true);
check("off", false);
check("false", false);
check("0", false);
});
it("/plan explains the stronger-constraint relationship with autonomous submit_plan", () => {
const r = handleSlash("plan", ["on"], makeLoop(), {
setPlanMode: () => {},
planMode: false,
});
// The info text should be explicit that submit_plan can also fire
// outside plan mode (autonomous) — plan mode is the *stronger*
// constraint, not the only path.
expect(r.info).toMatch(/stronger/);
expect(r.info).toMatch(/submit_plan/);
});
it("/apply-plan replies 'only in code mode' when setPlanMode is missing", () => {
const r = handleSlash("apply-plan", [], makeLoop());
expect(r.info).toMatch(/only available inside `reasonix code`/);
});
it("/apply-plan flips plan mode off, clears pending, and resubmits the implement-now synthetic", () => {
const setCalls: boolean[] = [];
const clearCalls: number[] = [];
const r = handleSlash("apply-plan", [], makeLoop(), {
setPlanMode: (on) => setCalls.push(on),
clearPendingPlan: () => {
clearCalls.push(1);
},
});
expect(setCalls).toEqual([false]);
expect(clearCalls).toEqual([1]);
expect(r.info).toMatch(/plan approved/);
expect(r.resubmit).toMatch(/Implement it now/);
expect(r.resubmit).toMatch(/out of plan mode/);
});
it("/apply-plan works without a clearPendingPlan callback (only setPlanMode required)", () => {
const setCalls: boolean[] = [];
const r = handleSlash("apply-plan", [], makeLoop(), {
setPlanMode: (on) => setCalls.push(on),
// clearPendingPlan omitted — /apply-plan must still work
});
expect(setCalls).toEqual([false]);
expect(r.resubmit).toMatch(/Implement it now/);
});
it("/status surfaces plan mode when it's on", () => {
const r = handleSlash("status", [], makeLoop(), { planMode: true });
expect(r.info).toMatch(/plan\s+ON/);
});
it("/status hides the plan line when plan mode is off", () => {
const r = handleSlash("status", [], makeLoop(), { planMode: false });
expect(r.info).not.toMatch(/plan\s+ON/);
});
});
});
+33 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import { Usage } from "../src/client.js";
import { SessionStats, costUsd } from "../src/telemetry.js";
import { SessionStats, costUsd, inputCostUsd, outputCostUsd } from "../src/telemetry.js";
describe("Usage.cacheHitRatio", () => {
it("computes hit ratio", () => {
@@ -51,4 +51,36 @@ describe("SessionStats", () => {
stats.record(2, "deepseek-chat", new Usage(42_000, 200, 42_200, 40_000, 2_000));
expect(stats.summary().lastPromptTokens).toBe(42_000);
});
it("summary splits input + output costs — the new panel breakdown", () => {
const stats = new SessionStats();
stats.record(1, "deepseek-chat", new Usage(1000, 100, 1100, 800, 200));
const s = stats.summary();
// input: (800 * 0.07 + 200 * 0.27) / 1e6 = 0.000056 + 0.000054 = 0.00011
// output: 100 * 1.10 / 1e6 = 0.00011
expect(s.totalInputCostUsd).toBeCloseTo((800 * 0.07 + 200 * 0.27) / 1_000_000, 10);
expect(s.totalOutputCostUsd).toBeCloseTo((100 * 1.1) / 1_000_000, 10);
// Sum of input+output equals total (within rounding).
expect(s.totalInputCostUsd + s.totalOutputCostUsd).toBeCloseTo(s.totalCostUsd, 9);
});
});
describe("inputCostUsd / outputCostUsd", () => {
it("input cost covers cache-hit + cache-miss but NOT completion", () => {
const u = new Usage(1000, 100, 1100, 800, 200);
const i = inputCostUsd("deepseek-chat", u);
expect(i).toBeCloseTo((800 * 0.07 + 200 * 0.27) / 1_000_000, 10);
});
it("output cost covers completion only", () => {
const u = new Usage(1000, 100, 1100, 800, 200);
const o = outputCostUsd("deepseek-chat", u);
expect(o).toBeCloseTo((100 * 1.1) / 1_000_000, 10);
});
it("both return 0 for an unknown model", () => {
const u = new Usage(1000, 100, 1100, 800, 200);
expect(inputCostUsd("unknown", u)).toBe(0);
expect(outputCostUsd("unknown", u)).toBe(0);
});
});
+181
View File
@@ -0,0 +1,181 @@
/**
* Tests for the `remember` / `forget` / `recall_memory` tool surface.
* Dispatches through ToolRegistry like R1 would, so refusals surface
* as JSON-encoded `{ error: ... }` strings (matching dispatch semantics).
*/
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { ToolRegistry } from "../src/tools.js";
import { registerMemoryTools } from "../src/tools/memory.js";
import { MemoryStore } from "../src/user-memory.js";
describe("memory tools", () => {
let home: string;
let projectRoot: string;
beforeEach(() => {
home = mkdtempSync(join(tmpdir(), "reasonix-memtools-home-"));
projectRoot = mkdtempSync(join(tmpdir(), "reasonix-memtools-proj-"));
});
afterEach(() => {
rmSync(home, { recursive: true, force: true });
rmSync(projectRoot, { recursive: true, force: true });
});
describe("remember", () => {
it("writes a global memory and returns a human-readable confirmation", async () => {
const reg = new ToolRegistry();
registerMemoryTools(reg, { homeDir: home });
const out = await reg.dispatch("remember", {
type: "feedback",
scope: "global",
name: "pref_one",
description: "User prefers tabs",
content: "Always use tabs for indentation.",
});
expect(out).toMatch(/REMEMBERED \(global\/pref_one\)/);
expect(out).toMatch(/User prefers tabs/);
// Verify the store actually has it.
const store = new MemoryStore({ homeDir: home });
const listed = store.list();
expect(listed.map((e) => e.name)).toContain("pref_one");
});
it("refuses scope='project' when no projectRoot is configured", async () => {
const reg = new ToolRegistry();
registerMemoryTools(reg, { homeDir: home });
const out = await reg.dispatch("remember", {
type: "project",
scope: "project",
name: "xyz_abc",
description: "d",
content: "c",
});
const parsed = JSON.parse(out);
expect(parsed.error).toMatch(/scope='project'/);
});
it("allows scope='project' when projectRoot is configured", async () => {
const reg = new ToolRegistry();
registerMemoryTools(reg, { homeDir: home, projectRoot });
const out = await reg.dispatch("remember", {
type: "project",
scope: "project",
name: "bun_build",
description: "Build is bun run build",
content: "On this machine, no npm — only bun.",
});
expect(out).toMatch(/REMEMBERED \(project\/bun_build\)/);
});
it("returns an error (not a throw) for invalid names", async () => {
const reg = new ToolRegistry();
registerMemoryTools(reg, { homeDir: home });
const out = await reg.dispatch("remember", {
type: "user",
scope: "global",
name: "../bad",
description: "d",
content: "c",
});
const parsed = JSON.parse(out);
expect(parsed.error).toMatch(/invalid memory name/);
});
it("returns an error when description is empty", async () => {
const reg = new ToolRegistry();
registerMemoryTools(reg, { homeDir: home });
const out = await reg.dispatch("remember", {
type: "user",
scope: "global",
name: "nonempty_name",
description: "",
content: "body",
});
const parsed = JSON.parse(out);
expect(parsed.error).toMatch(/description/);
});
});
describe("forget", () => {
it("removes an existing memory and reports so", async () => {
const reg = new ToolRegistry();
registerMemoryTools(reg, { homeDir: home });
await reg.dispatch("remember", {
type: "user",
scope: "global",
name: "delete_me",
description: "d",
content: "c",
});
const out = await reg.dispatch("forget", { scope: "global", name: "delete_me" });
expect(out).toMatch(/forgot \(global\/delete_me\)/);
const store = new MemoryStore({ homeDir: home });
expect(store.list().map((e) => e.name)).not.toContain("delete_me");
});
it("is idempotent on a missing memory (reports 'no such memory')", async () => {
const reg = new ToolRegistry();
registerMemoryTools(reg, { homeDir: home });
const out = await reg.dispatch("forget", { scope: "global", name: "ghost_one" });
expect(out).toMatch(/no such memory/);
});
});
describe("recall_memory", () => {
it("returns the body of an existing memory (with header)", async () => {
const reg = new ToolRegistry();
registerMemoryTools(reg, { homeDir: home });
await reg.dispatch("remember", {
type: "feedback",
scope: "global",
name: "deep_detail",
description: "short one-liner",
content: "Full body with **markdown** and multiple paragraphs.\n\nSecond paragraph.",
});
const out = await reg.dispatch("recall_memory", {
scope: "global",
name: "deep_detail",
});
expect(out).toContain("deep_detail");
expect(out).toContain("Full body with **markdown**");
expect(out).toContain("Second paragraph.");
});
it("returns an error (not a throw) on missing name", async () => {
const reg = new ToolRegistry();
registerMemoryTools(reg, { homeDir: home });
const out = await reg.dispatch("recall_memory", { scope: "global", name: "ghost_one" });
const parsed = JSON.parse(out);
expect(parsed.error).toMatch(/recall failed/);
});
it("is marked readOnly (available in plan mode)", () => {
const reg = new ToolRegistry();
registerMemoryTools(reg, { homeDir: home });
const tool = reg.get("recall_memory");
expect(tool?.readOnly).toBe(true);
});
});
describe("registration", () => {
it("registers all three tools", () => {
const reg = new ToolRegistry();
registerMemoryTools(reg, { homeDir: home });
expect(reg.has("remember")).toBe(true);
expect(reg.has("forget")).toBe(true);
expect(reg.has("recall_memory")).toBe(true);
});
it("remember / forget are NOT marked readOnly (gated in plan mode)", () => {
const reg = new ToolRegistry();
registerMemoryTools(reg, { homeDir: home });
expect(reg.get("remember")?.readOnly).not.toBe(true);
expect(reg.get("forget")?.readOnly).not.toBe(true);
});
});
});
+97
View File
@@ -0,0 +1,97 @@
/**
* Tests for the `run_skill` tool. Uses a temp `homeDir` and optional
* `projectRoot` so the tool never reads real skill dirs.
*/
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { ToolRegistry } from "../src/tools.js";
import { registerSkillTools } from "../src/tools/skills.js";
/**
* Write a skill under `<baseDir>/.reasonix/skills/<name>/SKILL.md`.
* Callers pass their home tmpdir for global-scope skills, or their
* projectRoot tmpdir for project-scope skills — the on-disk layout is
* the same either way, only the base directory differs.
*/
function writeSkill(baseDir: string, name: string, description: string, body: string): void {
const dir = join(baseDir, ".reasonix", "skills", name);
mkdirSync(dir, { recursive: true });
writeFileSync(
join(dir, "SKILL.md"),
`---\nname: ${name}\ndescription: ${description}\n---\n\n${body}\n`,
"utf8",
);
}
describe("run_skill tool", () => {
let home: string;
let projectRoot: string;
beforeEach(() => {
home = mkdtempSync(join(tmpdir(), "reasonix-skilltool-"));
projectRoot = mkdtempSync(join(tmpdir(), "reasonix-skilltool-proj-"));
});
afterEach(() => {
rmSync(home, { recursive: true, force: true });
rmSync(projectRoot, { recursive: true, force: true });
});
it("registers run_skill as a read-only tool", () => {
const reg = new ToolRegistry();
registerSkillTools(reg, { homeDir: home });
const tool = reg.get("run_skill");
expect(tool).toBeDefined();
expect(tool?.readOnly).toBe(true);
});
it("returns the skill body when the name resolves (global scope)", async () => {
writeSkill(home, "review", "Review a PR", "Step 1: diff. Step 2: comment.");
const reg = new ToolRegistry();
registerSkillTools(reg, { homeDir: home });
const out = await reg.dispatch("run_skill", { name: "review" });
expect(out).toContain("# Skill: review");
expect(out).toContain("Review a PR");
expect(out).toContain("scope: global");
expect(out).toContain("Step 1: diff");
});
it("resolves project-scope skills when projectRoot is passed", async () => {
writeSkill(projectRoot, "deploy", "Deploy to staging", "Run pipeline.");
const reg = new ToolRegistry();
registerSkillTools(reg, { homeDir: home, projectRoot });
const out = await reg.dispatch("run_skill", { name: "deploy" });
expect(out).toContain("scope: project");
expect(out).toContain("Run pipeline");
});
it("appends a forwarded 'Arguments:' line when provided", async () => {
writeSkill(home, "greet", "Greet someone", "Say hello to the name in args.");
const reg = new ToolRegistry();
registerSkillTools(reg, { homeDir: home });
const out = await reg.dispatch("run_skill", { name: "greet", arguments: "Alice" });
expect(out).toContain("Arguments: Alice");
});
it("returns a structured error with available names on unknown skill", async () => {
writeSkill(home, "review", "Review a PR", "...");
writeSkill(home, "ship-it", "Push commit", "...");
const reg = new ToolRegistry();
registerSkillTools(reg, { homeDir: home });
const out = await reg.dispatch("run_skill", { name: "nope" });
const parsed = JSON.parse(out);
expect(parsed.error).toMatch(/unknown skill/);
expect(parsed.available).toContain("review");
expect(parsed.available).toContain("ship-it");
});
it("rejects an empty name", async () => {
const reg = new ToolRegistry();
registerSkillTools(reg, { homeDir: home });
const out = await reg.dispatch("run_skill", { name: "" });
expect(JSON.parse(out).error).toMatch(/requires a 'name'/);
});
});
+143
View File
@@ -0,0 +1,143 @@
/**
* Tests for the `reasonix update` command — pure decision function
* + the CLI orchestrator with every side effect mocked via its
* test seams. No network, no spawn, no process.exit.
*/
import { describe, expect, it } from "vitest";
import { planUpdate, updateCommand } from "../src/cli/commands/update.js";
import { VERSION } from "../src/version.js";
describe("planUpdate", () => {
it("up-to-date when current === latest", () => {
const plan = planUpdate({ current: "0.4.22", latest: "0.4.22" });
expect(plan.action).toBe("up-to-date");
expect(plan.command).toBeUndefined();
});
it("newer-local when current > latest (dev build)", () => {
const plan = planUpdate({ current: "0.5.0", latest: "0.4.22" });
expect(plan.action).toBe("newer-local");
expect(plan.command).toBeUndefined();
});
it("npx-hint when current < latest and running via npx", () => {
const plan = planUpdate({ current: "0.4.21", latest: "0.4.22", npx: true });
expect(plan.action).toBe("npx-hint");
expect(plan.command).toBeUndefined();
expect(plan.message).toContain("npx");
});
it("run-npm-install when current < latest and not npx", () => {
const plan = planUpdate({ current: "0.4.21", latest: "0.4.22", npx: false });
expect(plan.action).toBe("run-npm-install");
expect(plan.command).toEqual(["npm", "install", "-g", "reasonix@latest"]);
});
});
describe("updateCommand", () => {
function harness() {
const output: string[] = [];
let exitCode: number | undefined;
const spawnCalls: string[][] = [];
return {
output,
get exitCode() {
return exitCode;
},
spawnCalls,
write: (m: string) => {
output.push(m);
},
exit: (c: number) => {
exitCode = c;
},
spawnInstall: async (argv: string[]) => {
spawnCalls.push(argv);
return 0;
},
};
}
it("prints up-to-date and does NOT spawn when current === latest", async () => {
const h = harness();
await updateCommand({
fetchLatest: async () => VERSION,
isNpx: () => false,
write: h.write,
exit: h.exit,
spawnInstall: h.spawnInstall,
});
expect(h.output.join("")).toContain("up to date");
expect(h.spawnCalls).toHaveLength(0);
expect(h.exitCode).toBeUndefined();
});
it("prints npx hint and does NOT spawn when running under npx", async () => {
const h = harness();
await updateCommand({
fetchLatest: async () => "99.99.99",
isNpx: () => true,
write: h.write,
exit: h.exit,
spawnInstall: h.spawnInstall,
});
const joined = h.output.join("");
expect(joined).toContain("99.99.99");
expect(joined).toContain("npx");
expect(h.spawnCalls).toHaveLength(0);
});
it("spawns npm install -g when global install is behind latest", async () => {
const h = harness();
await updateCommand({
fetchLatest: async () => "99.99.99",
isNpx: () => false,
write: h.write,
exit: h.exit,
spawnInstall: h.spawnInstall,
});
expect(h.spawnCalls).toEqual([["npm", "install", "-g", "reasonix@latest"]]);
expect(h.exitCode).toBeUndefined();
});
it("--dry-run prints the command but does not spawn", async () => {
const h = harness();
await updateCommand({
fetchLatest: async () => "99.99.99",
isNpx: () => false,
dryRun: true,
write: h.write,
exit: h.exit,
spawnInstall: h.spawnInstall,
});
expect(h.spawnCalls).toHaveLength(0);
expect(h.output.join("")).toContain("(dry run)");
});
it("exits non-zero when the registry is unreachable", async () => {
const h = harness();
await updateCommand({
fetchLatest: async () => null,
isNpx: () => false,
write: h.write,
exit: h.exit,
spawnInstall: h.spawnInstall,
});
expect(h.output.join("")).toContain("could not reach");
expect(h.exitCode).toBe(1);
});
it("surfaces non-zero npm exit via the exit seam", async () => {
const h = harness();
await updateCommand({
fetchLatest: async () => "99.99.99",
isNpx: () => false,
write: h.write,
exit: h.exit,
spawnInstall: async () => 127,
});
expect(h.exitCode).toBe(127);
expect(h.output.join("")).toContain("did not complete");
});
});
+289
View File
@@ -0,0 +1,289 @@
/**
* Tests for the usage log + aggregator.
*
* Covered:
* - appendUsage round-trips (record → file → readUsageLog)
* - readUsageLog tolerates malformed tail lines + missing file
* - aggregateUsage rolls records into today / week / month / all
* using rolling windows against an injected `now`
* - bucketCacheHitRatio / bucketSavingsFraction handle zero-denominator
* - stats dashboard render contains the expected rows
*/
import { appendFileSync, mkdirSync, mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { renderDashboard } from "../src/cli/commands/stats.js";
import { Usage } from "../src/client.js";
import {
type UsageRecord,
aggregateUsage,
appendUsage,
bucketCacheHitRatio,
bucketSavingsFraction,
readUsageLog,
} from "../src/usage.js";
function usage(overrides: Partial<Usage> = {}): Usage {
return new Usage(
overrides.promptTokens ?? 100,
overrides.completionTokens ?? 20,
overrides.totalTokens ?? 120,
overrides.promptCacheHitTokens ?? 80,
overrides.promptCacheMissTokens ?? 20,
);
}
describe("appendUsage + readUsageLog", () => {
let dir: string;
let path: string;
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), "reasonix-usage-"));
path = join(dir, "usage.jsonl");
});
afterEach(() => {
rmSync(dir, { recursive: true, force: true });
});
it("round-trips a single record", () => {
const record = appendUsage({
session: "default",
model: "deepseek-reasoner",
usage: usage(),
now: 1_700_000_000_000,
path,
});
expect(record.session).toBe("default");
expect(record.costUsd).toBeGreaterThan(0);
expect(record.claudeEquivUsd).toBeGreaterThan(record.costUsd);
const loaded = readUsageLog(path);
expect(loaded).toHaveLength(1);
expect(loaded[0]?.ts).toBe(1_700_000_000_000);
expect(loaded[0]?.session).toBe("default");
});
it("returns [] when the log does not exist", () => {
expect(readUsageLog(path)).toEqual([]);
});
it("tolerates a malformed trailing line (skips it)", () => {
appendUsage({ session: null, model: "deepseek-chat", usage: usage(), path });
mkdirSync(dirname(path), { recursive: true });
appendFileSync(path, "{ not valid json\n", "utf8");
const loaded = readUsageLog(path);
expect(loaded).toHaveLength(1);
});
it("creates the parent directory if missing", () => {
const deep = join(dir, "a", "b", "usage.jsonl");
appendUsage({ session: null, model: "deepseek-chat", usage: usage(), path: deep });
expect(readUsageLog(deep)).toHaveLength(1);
});
it("swallows write failure silently (best-effort contract)", () => {
// Point at a path under a FILE, not a directory — mkdirSync will
// blow up and appendUsage should absorb it without throwing.
const blocker = join(dir, "blocker");
appendFileSync(blocker, "not a dir");
expect(() =>
appendUsage({
session: null,
model: "deepseek-chat",
usage: usage(),
path: join(blocker, "usage.jsonl"),
}),
).not.toThrow();
});
});
describe("aggregateUsage", () => {
const NOW = 1_700_000_000_000; // fixed epoch for all windows below
const DAY = 24 * 60 * 60 * 1000;
function rec(partial: Partial<UsageRecord> & { ts: number }): UsageRecord {
return {
session: null,
model: "deepseek-reasoner",
promptTokens: 100,
completionTokens: 20,
cacheHitTokens: 80,
cacheMissTokens: 20,
costUsd: 0.001,
claudeEquivUsd: 0.01,
...partial,
};
}
it("empty input → empty buckets, null firstSeen/lastSeen", () => {
const agg = aggregateUsage([], { now: NOW });
expect(agg.buckets.map((b) => b.turns)).toEqual([0, 0, 0, 0]);
expect(agg.firstSeen).toBeNull();
expect(agg.lastSeen).toBeNull();
});
it("rolls records into today / week / month / all by age", () => {
const records = [
rec({ ts: NOW - 60_000 }), // 1 min ago → today
rec({ ts: NOW - 2 * DAY }), // 2 days ago → week + month + all
rec({ ts: NOW - 10 * DAY }), // 10 days → month + all
rec({ ts: NOW - 90 * DAY }), // 90 days → only all-time
];
const agg = aggregateUsage(records, { now: NOW });
const [today, week, month, all] = agg.buckets;
expect(today?.turns).toBe(1);
expect(week?.turns).toBe(2);
expect(month?.turns).toBe(3);
expect(all?.turns).toBe(4);
});
it("sums token + cost fields across records in each window", () => {
const records = [
rec({
ts: NOW - 60_000,
costUsd: 0.5,
claudeEquivUsd: 5,
cacheHitTokens: 1,
cacheMissTokens: 0,
}),
rec({
ts: NOW - 60_001,
costUsd: 0.25,
claudeEquivUsd: 2,
cacheHitTokens: 1,
cacheMissTokens: 1,
}),
];
const agg = aggregateUsage(records, { now: NOW });
const today = agg.buckets[0];
expect(today?.costUsd).toBeCloseTo(0.75);
expect(today?.claudeEquivUsd).toBeCloseTo(7);
expect(today?.cacheHitTokens).toBe(2);
expect(today?.cacheMissTokens).toBe(1);
});
it("byModel + bySession sort descending and group nulls under (ephemeral)", () => {
const records = [
rec({ ts: NOW - 60_000, model: "deepseek-chat", session: "a" }),
rec({ ts: NOW - 60_000, model: "deepseek-reasoner", session: "a" }),
rec({ ts: NOW - 60_000, model: "deepseek-reasoner", session: "b" }),
rec({ ts: NOW - 60_000, model: "deepseek-reasoner", session: null }),
];
const agg = aggregateUsage(records, { now: NOW });
expect(agg.byModel[0]?.model).toBe("deepseek-reasoner");
expect(agg.byModel[0]?.turns).toBe(3);
expect(agg.bySession[0]?.session).toBe("a");
expect(agg.bySession.find((s) => s.session === "(ephemeral)")?.turns).toBe(1);
});
});
describe("bucket helpers", () => {
it("cache hit ratio — zero denominator → 0", () => {
const b = aggregateUsage([], { now: 1 }).buckets[0]!;
expect(bucketCacheHitRatio(b)).toBe(0);
});
it("cache hit ratio — 80 hit / 20 miss → 0.8", () => {
const agg = aggregateUsage(
[
{
ts: 1_700_000_000_000,
session: null,
model: "deepseek-chat",
promptTokens: 100,
completionTokens: 0,
cacheHitTokens: 80,
cacheMissTokens: 20,
costUsd: 0,
claudeEquivUsd: 0,
},
],
{ now: 1_700_000_000_000 },
);
const today = agg.buckets[0]!;
expect(bucketCacheHitRatio(today)).toBeCloseTo(0.8);
});
it("savings fraction — zero Claude cost → 0 (no division)", () => {
const b = aggregateUsage([], { now: 1 }).buckets[0]!;
expect(bucketSavingsFraction(b)).toBe(0);
});
it("savings fraction — cost $1 vs Claude $10 → 0.9", () => {
const agg = aggregateUsage(
[
{
ts: 1_700_000_000_000,
session: null,
model: "deepseek-chat",
promptTokens: 0,
completionTokens: 0,
cacheHitTokens: 0,
cacheMissTokens: 0,
costUsd: 1,
claudeEquivUsd: 10,
},
],
{ now: 1_700_000_000_000 },
);
expect(bucketSavingsFraction(agg.buckets[0]!)).toBeCloseTo(0.9);
});
});
describe("renderDashboard", () => {
it("includes the four window labels + header", () => {
const agg = aggregateUsage(
[
{
ts: 1_700_000_000_000,
session: "s",
model: "deepseek-reasoner",
promptTokens: 1,
completionTokens: 1,
cacheHitTokens: 1,
cacheMissTokens: 0,
costUsd: 0.001,
claudeEquivUsd: 0.1,
},
],
{ now: 1_700_000_000_000 },
);
const out = renderDashboard(agg, "/tmp/fake.jsonl");
expect(out).toContain("today");
expect(out).toContain("week");
expect(out).toContain("month");
expect(out).toContain("all-time");
expect(out).toContain("cache hit");
expect(out).toContain("vs Claude");
expect(out).toContain("most used model:");
expect(out).toContain("top session:");
expect(out).toContain("tracked since:");
});
it("renders em-dashes for empty buckets rather than $0.000000", () => {
const agg = aggregateUsage(
[
{
ts: 1_700_000_000_000 - 365 * 24 * 60 * 60 * 1000,
session: null,
model: "deepseek-chat",
promptTokens: 1,
completionTokens: 1,
cacheHitTokens: 1,
cacheMissTokens: 0,
costUsd: 0.001,
claudeEquivUsd: 0.01,
},
],
{ now: 1_700_000_000_000 },
);
const out = renderDashboard(agg, "/tmp/fake.jsonl");
// today / week / month should all be empty because the only record
// is a year old. The all-time row still has a cost.
// Each em-dash represents an empty cell.
const emDashCount = (out.match(/—/g) ?? []).length;
expect(emDashCount).toBeGreaterThan(0);
});
});
+394
View File
@@ -0,0 +1,394 @@
/**
* Tests for the `~/.reasonix/memory/` store and its prefix-loading
* composer. All I/O goes through a temp `homeDir` so the suite never
* touches the developer's actual memory files.
*/
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { applyProjectMemory } from "../src/project-memory.js";
import {
MEMORY_INDEX_FILE,
MEMORY_INDEX_MAX_CHARS,
MemoryStore,
applyMemoryStack,
applyUserMemory,
projectHash,
sanitizeMemoryName,
} from "../src/user-memory.js";
const BASE = "You are a test assistant.";
describe("user-memory", () => {
let home: string;
let projectRoot: string;
const originalEnv = process.env.REASONIX_MEMORY;
beforeEach(() => {
home = mkdtempSync(join(tmpdir(), "reasonix-umem-home-"));
projectRoot = mkdtempSync(join(tmpdir(), "reasonix-umem-proj-"));
// biome-ignore lint/performance/noDelete: avoid leaking "undefined" into env
delete process.env.REASONIX_MEMORY;
});
afterEach(() => {
rmSync(home, { recursive: true, force: true });
rmSync(projectRoot, { recursive: true, force: true });
if (originalEnv === undefined) {
// biome-ignore lint/performance/noDelete: same
delete process.env.REASONIX_MEMORY;
} else {
process.env.REASONIX_MEMORY = originalEnv;
}
});
describe("sanitizeMemoryName", () => {
it("accepts simple identifiers", () => {
expect(sanitizeMemoryName("foo_bar")).toBe("foo_bar");
expect(sanitizeMemoryName("abc-def.9")).toBe("abc-def.9");
expect(sanitizeMemoryName(" padded ")).toBe("padded");
});
it("rejects path-separator injection", () => {
expect(() => sanitizeMemoryName("../etc/passwd")).toThrow(/invalid memory name/);
expect(() => sanitizeMemoryName("foo/bar")).toThrow();
expect(() => sanitizeMemoryName("foo\\bar")).toThrow();
});
it("rejects leading dot / too-short / too-long names", () => {
expect(() => sanitizeMemoryName(".hidden")).toThrow();
expect(() => sanitizeMemoryName("ab")).toThrow();
expect(() => sanitizeMemoryName("a".repeat(41))).toThrow();
});
});
describe("projectHash", () => {
it("returns a stable 16-hex-char digest for the same path", () => {
const a = projectHash("/tmp/whatever");
const b = projectHash("/tmp/whatever");
expect(a).toBe(b);
expect(a).toMatch(/^[0-9a-f]{16}$/);
});
it("differs across paths", () => {
expect(projectHash("/tmp/a")).not.toBe(projectHash("/tmp/b"));
});
});
describe("MemoryStore basic I/O", () => {
it("writes a global memory and regenerates MEMORY.md", () => {
const store = new MemoryStore({ homeDir: home });
store.write({
name: "snake_case",
type: "feedback",
scope: "global",
description: "User prefers snake_case for new Python modules",
body: "Rule.\n\n**Why:** PEP 8.\n\n**How to apply:** new .py files default to snake_case.",
});
const file = join(home, "memory", "global", "snake_case.md");
expect(existsSync(file)).toBe(true);
const raw = readFileSync(file, "utf8");
expect(raw).toMatch(/^---\nname: snake_case\n/);
expect(raw).toContain("Rule.");
const indexPath = join(home, "memory", "global", MEMORY_INDEX_FILE);
expect(existsSync(indexPath)).toBe(true);
const index = readFileSync(indexPath, "utf8");
expect(index).toContain("[snake_case](snake_case.md)");
expect(index).toContain("User prefers snake_case");
});
it("round-trips write → read → list → delete for global scope", () => {
const store = new MemoryStore({ homeDir: home });
store.write({
name: "one",
type: "user",
scope: "global",
description: "First memory",
body: "content one",
});
store.write({
name: "two",
type: "reference",
scope: "global",
description: "Second memory",
body: "content two",
});
const listed = store.list();
expect(listed.map((e) => e.name).sort()).toEqual(["one", "two"]);
const one = store.read("global", "one");
expect(one.body).toBe("content one");
expect(one.type).toBe("user");
expect(one.description).toBe("First memory");
expect(one.createdAt).toMatch(/^\d{4}-\d{2}-\d{2}$/);
const removed = store.delete("global", "one");
expect(removed).toBe(true);
expect(store.list().map((e) => e.name)).toEqual(["two"]);
// MEMORY.md should no longer reference "one".
const index = readFileSync(join(home, "memory", "global", MEMORY_INDEX_FILE), "utf8");
expect(index).not.toContain("one.md");
expect(index).toContain("two.md");
});
it("returns false when deleting a nonexistent memory", () => {
const store = new MemoryStore({ homeDir: home });
expect(store.delete("global", "ghost")).toBe(false);
});
it("removes MEMORY.md entirely when the last memory is deleted", () => {
const store = new MemoryStore({ homeDir: home });
store.write({
name: "only",
type: "project",
scope: "global",
description: "d",
body: "b",
});
store.delete("global", "only");
const indexPath = join(home, "memory", "global", MEMORY_INDEX_FILE);
expect(existsSync(indexPath)).toBe(false);
});
it("refuses project scope without a projectRoot", () => {
const store = new MemoryStore({ homeDir: home });
expect(store.hasProjectScope()).toBe(false);
expect(() =>
store.write({
name: "nope",
type: "project",
scope: "project",
description: "d",
body: "b",
}),
).toThrow(/projectRoot/);
});
it("routes project scope into the hashed subdir", () => {
const store = new MemoryStore({ homeDir: home, projectRoot });
expect(store.hasProjectScope()).toBe(true);
store.write({
name: "bun_build",
type: "project",
scope: "project",
description: "Build command is `bun run build` on this machine",
body: "Body here.",
});
const hashDir = join(home, "memory", projectHash(projectRoot));
const file = join(hashDir, "bun_build.md");
expect(existsSync(file)).toBe(true);
// Global scope dir should NOT contain the project file.
expect(existsSync(join(home, "memory", "global", "bun_build.md"))).toBe(false);
});
it("validates description / body non-empty", () => {
const store = new MemoryStore({ homeDir: home });
expect(() =>
store.write({ name: "x_y_z", type: "user", scope: "global", description: "", body: "b" }),
).toThrow(/description/);
expect(() =>
store.write({
name: "x_y_z",
type: "user",
scope: "global",
description: "d",
body: " \n",
}),
).toThrow(/body/);
});
it("loadIndex returns null for absent scope, content + flag for present", () => {
const store = new MemoryStore({ homeDir: home });
expect(store.loadIndex("global")).toBeNull();
store.write({
name: "x_y_z",
type: "user",
scope: "global",
description: "hi",
body: "b",
});
const idx = store.loadIndex("global");
expect(idx).not.toBeNull();
expect(idx?.truncated).toBe(false);
expect(idx?.content).toContain("x_y_z");
});
it("loadIndex truncates with a visible marker past the cap", () => {
const store = new MemoryStore({ homeDir: home });
// Write many entries so MEMORY.md crosses the cap.
for (let i = 0; i < 80; i++) {
store.write({
name: `entry_${String(i).padStart(3, "0")}`,
type: "user",
scope: "global",
description: "x".repeat(120),
body: "b",
});
}
const idx = store.loadIndex("global");
expect(idx?.truncated).toBe(true);
expect(idx?.content).toMatch(/truncated \d+ chars/);
expect(idx?.content.length).toBeLessThan(MEMORY_INDEX_MAX_CHARS + 64);
});
it("list() skips malformed frontmatter gracefully", () => {
const store = new MemoryStore({ homeDir: home });
const dir = store.dir("global");
writeFileSync(join(dir, "broken.md"), "no frontmatter here, just text\n", "utf8");
store.write({
name: "sane",
type: "user",
scope: "global",
description: "ok",
body: "b",
});
const entries = store.list();
expect(entries.map((e) => e.name).sort()).toContain("sane");
});
it("regenerated MEMORY.md is byte-stable for identical file sets (cache-prefix safety)", () => {
const storeA = new MemoryStore({ homeDir: home });
storeA.write({ name: "a_one", type: "user", scope: "global", description: "d1", body: "b1" });
storeA.write({ name: "b_two", type: "user", scope: "global", description: "d2", body: "b2" });
const first = readFileSync(join(home, "memory", "global", MEMORY_INDEX_FILE), "utf8");
// Delete + re-write in reverse order — sorted index should match.
storeA.delete("global", "a_one");
storeA.delete("global", "b_two");
storeA.write({ name: "b_two", type: "user", scope: "global", description: "d2", body: "b2" });
storeA.write({ name: "a_one", type: "user", scope: "global", description: "d1", body: "b1" });
const second = readFileSync(join(home, "memory", "global", MEMORY_INDEX_FILE), "utf8");
expect(second).toBe(first);
});
});
describe("applyUserMemory", () => {
it("is a no-op when both scopes are empty", () => {
expect(applyUserMemory(BASE, { homeDir: home, projectRoot })).toBe(BASE);
});
it("appends only the global block when no project memory exists", () => {
const store = new MemoryStore({ homeDir: home, projectRoot });
store.write({
name: "pref_one",
type: "user",
scope: "global",
description: "prefers tabs",
body: "b",
});
const out = applyUserMemory(BASE, { homeDir: home, projectRoot });
expect(out).toContain("# User memory — global");
expect(out).not.toContain("# User memory — this project");
expect(out).toContain("pref_one");
});
it("appends both blocks when both scopes populated", () => {
const store = new MemoryStore({ homeDir: home, projectRoot });
store.write({
name: "global_one",
type: "user",
scope: "global",
description: "g",
body: "b",
});
store.write({
name: "project_one",
type: "project",
scope: "project",
description: "p",
body: "b",
});
const out = applyUserMemory(BASE, { homeDir: home, projectRoot });
expect(out).toContain("# User memory — global");
expect(out).toContain("# User memory — this project");
expect(out).toContain("global_one");
expect(out).toContain("project_one");
// Global precedes project — stable ordering for cache hash.
expect(out.indexOf("global_one")).toBeLessThan(out.indexOf("project_one"));
});
it("is deterministic — identical state ⇒ identical output (cache-safe)", () => {
const store = new MemoryStore({ homeDir: home, projectRoot });
store.write({
name: "stable",
type: "user",
scope: "global",
description: "d",
body: "b",
});
const a = applyUserMemory(BASE, { homeDir: home, projectRoot });
const b = applyUserMemory(BASE, { homeDir: home, projectRoot });
expect(a).toBe(b);
});
it("respects REASONIX_MEMORY=off", () => {
const store = new MemoryStore({ homeDir: home, projectRoot });
store.write({
name: "pref_one",
type: "user",
scope: "global",
description: "d",
body: "b",
});
process.env.REASONIX_MEMORY = "off";
expect(applyUserMemory(BASE, { homeDir: home, projectRoot })).toBe(BASE);
});
it("skips the project block when no projectRoot is configured", () => {
const store = new MemoryStore({ homeDir: home });
store.write({
name: "global_only",
type: "user",
scope: "global",
description: "d",
body: "b",
});
const out = applyUserMemory(BASE, { homeDir: home });
expect(out).toContain("# User memory — global");
expect(out).not.toContain("# User memory — this project");
});
});
describe("applyMemoryStack", () => {
it("composes REASONIX.md → global memory → project memory", () => {
writeFileSync(join(projectRoot, "REASONIX.md"), "Pinned by REASONIX.md\n", "utf8");
// applyMemoryStack uses ~/.reasonix by default — redirect via HOME
// isn't portable across Windows; use the public applyUserMemory
// directly for the global/project part and compose manually to
// check ordering is what the helper produces.
const withProj = applyProjectMemory(BASE, projectRoot);
const store = new MemoryStore({ homeDir: home, projectRoot });
store.write({
name: "g_pref",
type: "user",
scope: "global",
description: "global pref",
body: "b",
});
store.write({
name: "p_fact",
type: "project",
scope: "project",
description: "project fact",
body: "b",
});
const out = applyUserMemory(withProj, { homeDir: home, projectRoot });
// Order: REASONIX.md content → global → project. Each unique
// string should appear, and in that order.
const iReasonix = out.indexOf("Pinned by REASONIX.md");
const iGlobal = out.indexOf("g_pref");
const iProject = out.indexOf("p_fact");
expect(iReasonix).toBeGreaterThan(BASE.length - 1);
expect(iGlobal).toBeGreaterThan(iReasonix);
expect(iProject).toBeGreaterThan(iGlobal);
});
it("applyMemoryStack with no memory at all returns BASE unchanged", () => {
// No REASONIX.md, no HOME memory → stack is a no-op.
// Points applyMemoryStack at a tmp home by temporarily monkey-patching
// via the env — but we don't have a hook for that, so just assert the
// common case: fresh projectRoot with no REASONIX.md produces the
// REASONIX.md-removed output when user memory is empty too.
expect(applyMemoryStack(BASE, projectRoot)).toBe(BASE);
});
});
});
+193
View File
@@ -0,0 +1,193 @@
/**
* Tests for the version module — semver compare, npx detection, and
* the cached latest-version fetcher. Network is fully mocked: every
* `fetch` call goes through an injected stub so tests work offline
* and across CI providers without flake risk.
*/
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import {
LATEST_CACHE_TTL_MS,
VERSION,
compareVersions,
getLatestVersion,
isNpxInstall,
} from "../src/version.js";
describe("VERSION", () => {
it("matches the published package.json version", () => {
const pkgPath = join(process.cwd(), "package.json");
const pkg = JSON.parse(readFileSync(pkgPath, "utf8"));
expect(VERSION).toBe(pkg.version);
});
});
describe("compareVersions", () => {
it("compares major/minor/patch numerically", () => {
expect(compareVersions("0.4.22", "0.4.22")).toBe(0);
expect(compareVersions("0.4.21", "0.4.22")).toBeLessThan(0);
expect(compareVersions("0.4.22", "0.4.21")).toBeGreaterThan(0);
expect(compareVersions("0.5.0", "0.4.99")).toBeGreaterThan(0);
expect(compareVersions("1.0.0", "0.99.99")).toBeGreaterThan(0);
});
it("treats pre-release suffix as lower than bare version", () => {
expect(compareVersions("0.4.22-rc.1", "0.4.22")).toBeLessThan(0);
expect(compareVersions("0.4.22", "0.4.22-rc.1")).toBeGreaterThan(0);
expect(compareVersions("0.4.22-alpha.1", "0.4.22-alpha.1")).toBe(0);
expect(compareVersions("0.4.22-alpha.1", "0.4.22-alpha.2")).toBeLessThan(0);
});
it("tolerates mismatched part counts", () => {
expect(compareVersions("1", "1.0.0")).toBe(0);
expect(compareVersions("1.2", "1.2.0")).toBe(0);
expect(compareVersions("1.2.0", "1.2.1")).toBeLessThan(0);
});
});
describe("isNpxInstall", () => {
const originalArgv1 = process.argv[1];
const originalUa = process.env.npm_config_user_agent;
afterEach(() => {
process.argv[1] = originalArgv1;
if (originalUa === undefined) {
// biome-ignore lint/performance/noDelete: restore missing env var exactly
delete process.env.npm_config_user_agent;
} else {
process.env.npm_config_user_agent = originalUa;
}
});
it("detects _npx path fragment", () => {
process.argv[1] = "/Users/x/.npm/_npx/abc123/node_modules/.bin/reasonix";
// biome-ignore lint/performance/noDelete: cover the no-env case
delete process.env.npm_config_user_agent;
expect(isNpxInstall()).toBe(true);
});
it("detects npx via user-agent string", () => {
process.argv[1] = "/usr/local/bin/reasonix";
process.env.npm_config_user_agent = "npx/10.2.4 npm/10.2.4 node/v20.10.0";
expect(isNpxInstall()).toBe(true);
});
it("returns false for plain global install", () => {
process.argv[1] = "/usr/local/lib/node_modules/reasonix/dist/cli/index.js";
// biome-ignore lint/performance/noDelete: cover the no-env case
delete process.env.npm_config_user_agent;
expect(isNpxInstall()).toBe(false);
});
});
describe("getLatestVersion", () => {
let home: string;
beforeEach(() => {
home = mkdtempSync(join(tmpdir(), "reasonix-version-"));
});
afterEach(() => {
rmSync(home, { recursive: true, force: true });
});
function makeFetch(
body: unknown,
{ ok = true, status = 200 }: { ok?: boolean; status?: number } = {},
): typeof fetch {
return (async () =>
({
ok,
status,
json: async () => body,
}) as unknown as Response) as typeof fetch;
}
it("fetches from the registry and caches the result", async () => {
let calls = 0;
const fetchImpl = (async () => {
calls++;
return { ok: true, json: async () => ({ version: "0.9.9" }) } as unknown as Response;
}) as typeof fetch;
const v1 = await getLatestVersion({ homeDir: home, fetchImpl });
expect(v1).toBe("0.9.9");
expect(calls).toBe(1);
// Within TTL, no second network call.
const v2 = await getLatestVersion({ homeDir: home, fetchImpl });
expect(v2).toBe("0.9.9");
expect(calls).toBe(1);
// Cache file exists and parses.
const cacheFile = join(home, ".reasonix", "version-cache.json");
expect(existsSync(cacheFile)).toBe(true);
const parsed = JSON.parse(readFileSync(cacheFile, "utf8"));
expect(parsed.version).toBe("0.9.9");
expect(typeof parsed.checkedAt).toBe("number");
});
it("force:true bypasses the cache", async () => {
writeFileSync(join(home, ".reasonix-cache-preseed.json"), ""); // just ensures the tmp dir is real
// Preseed the cache directly.
const { mkdirSync } = await import("node:fs");
mkdirSync(join(home, ".reasonix"), { recursive: true });
writeFileSync(
join(home, ".reasonix", "version-cache.json"),
JSON.stringify({ version: "0.1.0", checkedAt: Date.now() }),
);
const fetchImpl = makeFetch({ version: "0.9.9" });
const v = await getLatestVersion({ homeDir: home, fetchImpl, force: true });
expect(v).toBe("0.9.9");
});
it("honors an expired cache entry as stale and refetches", async () => {
const { mkdirSync } = await import("node:fs");
mkdirSync(join(home, ".reasonix"), { recursive: true });
writeFileSync(
join(home, ".reasonix", "version-cache.json"),
JSON.stringify({
version: "0.1.0",
checkedAt: Date.now() - LATEST_CACHE_TTL_MS - 1000,
}),
);
const fetchImpl = makeFetch({ version: "0.9.9" });
const v = await getLatestVersion({ homeDir: home, fetchImpl });
expect(v).toBe("0.9.9");
});
it("returns null when fetch throws (offline)", async () => {
const fetchImpl = (async () => {
throw new Error("ENOTFOUND");
}) as unknown as typeof fetch;
const v = await getLatestVersion({ homeDir: home, fetchImpl });
expect(v).toBeNull();
});
it("returns null when the registry returns non-OK", async () => {
const fetchImpl = makeFetch({}, { ok: false, status: 500 });
const v = await getLatestVersion({ homeDir: home, fetchImpl });
expect(v).toBeNull();
});
it("returns null when the body has no version string", async () => {
const fetchImpl = makeFetch({ notVersion: true });
const v = await getLatestVersion({ homeDir: home, fetchImpl });
expect(v).toBeNull();
});
it("swallows cache write failures silently", async () => {
// Point homeDir at a file (not a directory) — mkdirSync will
// fail and writeCache should ignore the error. Returned version
// is still the freshly fetched one.
const fetchImpl = makeFetch({ version: "0.9.9" });
const busted = join(home, "not-a-dir");
writeFileSync(busted, "blocker");
const v = await getLatestVersion({ homeDir: busted, fetchImpl });
expect(v).toBe("0.9.9");
});
});
+292
View File
@@ -0,0 +1,292 @@
import { describe, expect, it, vi } from "vitest";
import { ToolRegistry } from "../src/tools.js";
import {
formatSearchResults,
htmlToText,
parseMojeekResults,
registerWebTools,
webFetch,
webSearch,
} from "../src/tools/web.js";
describe("htmlToText", () => {
it("strips script/style/nav/footer and preserves paragraph breaks", () => {
const html = `
<html><head><title>x</title><style>body{color:red}</style></head>
<body>
<nav><a>skip</a></nav>
<p>Hello <strong>world</strong>.</p>
<p>Second paragraph.</p>
<script>evil()</script>
<footer>fine print</footer>
</body></html>
`;
const out = htmlToText(html);
expect(out).toContain("Hello world.");
expect(out).toContain("Second paragraph.");
expect(out).not.toContain("evil");
expect(out).not.toContain("skip");
expect(out).not.toContain("fine print");
expect(out).not.toContain("color:red");
expect(out).toMatch(/Hello world\.\n\nSecond paragraph\./);
});
it("decodes the common entities", () => {
expect(htmlToText("<p>a &amp; b &lt;c&gt; &quot;d&quot;</p>")).toContain('a & b <c> "d"');
});
it("collapses whitespace runs but keeps paragraph breaks", () => {
const out = htmlToText("<p>one two</p><p>three</p>");
expect(out).toBe("one two\n\nthree");
});
});
describe("parseMojeekResults", () => {
// Fixture mirrors the shape Mojeek actually returns as of April 2026.
const sampleHtml = `
<ul class="results">
<li>
<a title="https://example.com/a" href="https://example.com/a" class="ob">
<p class="i"><span class="url">https://example.com</span></p>
</a>
<h2>
<a class="title" title="https://example.com/a" href="https://example.com/a">
Flutter 3.19 release notes
</a>
</h2>
<p class="s">
Flutter 3.19 introduces <strong>new Navigator</strong>&nbsp;APIs &amp; more.
</p>
</li>
<li>
<a href="https://medium.com/flutter/x" class="ob">
<p class="i"><span class="url">medium.com</span></p>
</a>
<h2>
<a class="title" href="https://medium.com/flutter/x">What's new in 3.19</a>
</h2>
<p class="s">An overview post.</p>
</li>
</ul>
`;
it("extracts title/url/snippet from the expected markup", () => {
const items = parseMojeekResults(sampleHtml);
expect(items).toHaveLength(2);
expect(items[0]).toEqual({
title: "Flutter 3.19 release notes",
url: "https://example.com/a",
snippet: "Flutter 3.19 introduces new Navigator APIs & more.",
});
expect(items[1]).toEqual({
title: "What's new in 3.19",
url: "https://medium.com/flutter/x",
snippet: "An overview post.",
});
});
it("returns empty on markup that doesn't match the expected shape", () => {
expect(parseMojeekResults("<html><body>nothing here</body></html>")).toEqual([]);
});
it("tolerates attribute-order swaps (href before class)", () => {
const html = `
<a href="https://example.com/z" class="title">Title Z</a>
<p class="s">Snippet Z.</p>
`;
const items = parseMojeekResults(html);
expect(items).toHaveLength(1);
expect(items[0]).toEqual({
title: "Title Z",
url: "https://example.com/z",
snippet: "Snippet Z.",
});
});
it("handles a title with no snippet sibling (empty snippet)", () => {
const html = `<a class="title" href="https://example.com/s">Solo</a>`;
const items = parseMojeekResults(html);
expect(items).toHaveLength(1);
expect(items[0]?.snippet).toBe("");
});
});
describe("webSearch", () => {
const twoResultsHtml = `
<a class="title" href="https://example.com/a">A</a>
<p class="s">snippet A</p>
<a class="title" href="https://example.com/b">B</a>
<p class="s">snippet B</p>`;
it("GETs Mojeek with a browser UA and query string", async () => {
const captured: { url: string; method: string; ua: string } = { url: "", method: "", ua: "" };
const originalFetch = globalThis.fetch;
globalThis.fetch = vi.fn(async (url: string | URL, init?: RequestInit) => {
captured.url = String(url);
captured.method = init?.method ?? "GET";
const headers = (init?.headers ?? {}) as Record<string, string>;
captured.ua = headers["User-Agent"] ?? "";
return new Response(twoResultsHtml, {
status: 200,
headers: { "Content-Type": "text/html" },
});
}) as unknown as typeof fetch;
try {
const out = await webSearch("flutter 3.19", { topK: 2 });
expect(captured.url).toContain("mojeek.com/search");
expect(captured.url).toContain("q=flutter%203.19");
expect(captured.method).toBe("GET");
expect(captured.ua).toMatch(/Mozilla\/5.0/);
expect(out).toHaveLength(2);
expect(out[0]?.title).toBe("A");
} finally {
globalThis.fetch = originalFetch;
}
});
it("clamps topK to [1, 10]", async () => {
const originalFetch = globalThis.fetch;
globalThis.fetch = vi.fn(
async () => new Response(twoResultsHtml, { status: 200 }),
) as unknown as typeof fetch;
try {
const outMax = await webSearch("x", { topK: 99 });
expect(outMax.length).toBeLessThanOrEqual(10);
const outMin = await webSearch("x", { topK: 0 });
expect(outMin.length).toBe(1);
} finally {
globalThis.fetch = originalFetch;
}
});
it("throws on non-2xx", async () => {
const originalFetch = globalThis.fetch;
globalThis.fetch = vi.fn(
async () => new Response("blocked", { status: 429 }),
) as unknown as typeof fetch;
try {
await expect(webSearch("q")).rejects.toThrow(/web_search 429/);
} finally {
globalThis.fetch = originalFetch;
}
});
it("returns [] on a legitimately empty 'No results' page", async () => {
const originalFetch = globalThis.fetch;
globalThis.fetch = vi.fn(
async () =>
new Response("<html><body>Your search did not match any documents.</body></html>", {
status: 200,
}),
) as unknown as typeof fetch;
try {
const out = await webSearch("zzyzx nothing here");
expect(out).toEqual([]);
} finally {
globalThis.fetch = originalFetch;
}
});
it("surfaces a clear error on an anti-bot interstitial", async () => {
const originalFetch = globalThis.fetch;
globalThis.fetch = vi.fn(
async () =>
new Response("<html>Please solve the captcha to continue.</html>", { status: 200 }),
) as unknown as typeof fetch;
try {
await expect(webSearch("q")).rejects.toThrow(/anti-bot|rate-limited|blocked/);
} finally {
globalThis.fetch = originalFetch;
}
});
it("surfaces a diagnostic error when the response looks like neither empty-nor-results", async () => {
const originalFetch = globalThis.fetch;
globalThis.fetch = vi.fn(
async () =>
new Response("<html><body>totally unexpected shape</body></html>", { status: 200 }),
) as unknown as typeof fetch;
try {
await expect(webSearch("q")).rejects.toThrow(/doesn't look like a real empty page/);
} finally {
globalThis.fetch = originalFetch;
}
});
});
describe("formatSearchResults", () => {
it("renders a query header + numbered list", () => {
const out = formatSearchResults("hello", [
{ title: "One", url: "https://one", snippet: "first" },
{ title: "Two", url: "https://two", snippet: "second" },
]);
expect(out).toMatch(/query: hello/);
expect(out).toMatch(/results \(2\)/);
expect(out).toMatch(/1\. One\n\s+https:\/\/one\n\s+first/);
expect(out).toMatch(/2\. Two/);
});
});
describe("registerWebTools", () => {
it("registers web_search and web_fetch", () => {
const registry = new ToolRegistry();
registerWebTools(registry);
expect(registry.size).toBe(2);
});
it("web_fetch refuses non-http(s) urls", async () => {
const registry = new ToolRegistry();
registerWebTools(registry);
const out = await registry.dispatch("web_fetch", JSON.stringify({ url: "file:///etc/passwd" }));
expect(out).toMatch(/must start with http/);
});
});
describe("webFetch", () => {
it("extracts title + body text from an html response", async () => {
const originalFetch = globalThis.fetch;
globalThis.fetch = vi.fn(
async () =>
new Response(
"<html><head><title>Demo</title></head><body><p>Hello world.</p></body></html>",
{ status: 200, headers: { "Content-Type": "text/html; charset=utf-8" } },
),
) as unknown as typeof fetch;
try {
const page = await webFetch("https://example.com/demo");
expect(page.title).toBe("Demo");
expect(page.text).toContain("Hello world.");
expect(page.text).not.toContain("<title>");
expect(page.truncated).toBe(false);
} finally {
globalThis.fetch = originalFetch;
}
});
it("truncates long pages and flags the result", async () => {
const originalFetch = globalThis.fetch;
const big = `<html><body><p>${"a".repeat(50_000)}</p></body></html>`;
globalThis.fetch = vi.fn(
async () => new Response(big, { status: 200, headers: { "Content-Type": "text/html" } }),
) as unknown as typeof fetch;
try {
const page = await webFetch("https://example.com/big", { maxChars: 1000 });
expect(page.truncated).toBe(true);
expect(page.text).toMatch(/\[… truncated \d+ chars …\]$/);
} finally {
globalThis.fetch = originalFetch;
}
});
it("surfaces non-2xx as a thrown error", async () => {
const originalFetch = globalThis.fetch;
globalThis.fetch = vi.fn(
async () => new Response("nope", { status: 404 }),
) as unknown as typeof fetch;
try {
await expect(webFetch("https://example.com/missing")).rejects.toThrow(/web_fetch 404/);
} finally {
globalThis.fetch = originalFetch;
}
});
});