Compare commits

...
14 Commits
Author SHA1 Message Date
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
58 changed files with 9209 additions and 600 deletions

No files matched your search

+707
View File
@@ -3,6 +3,713 @@
All notable changes to Reasonix. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/);
this project uses [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [0.4.22] — 2026-04-22
**Headline:** Version display in the TUI header + `reasonix update`
self-upgrade command.
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 quietly surfaces a yellow
`update: X.Y.Z` nudge on the right side of the same row when a
newer version has been published. The nudge never blocks startup —
the fetch is bounded at 2s with a 24h on-disk cache, and any
failure (offline, firewall, registry hiccup) is silent by design.
`reasonix update` is the command form: detects whether you're
running a global install vs an ephemeral `npx` spawn, and either
spawns `npm install -g reasonix@latest` for the former or prints a
cache-refresh hint for the latter. `--dry-run` prints the plan
without executing.
The `VERSION` constant now sources from `package.json` at runtime
(walking up from `import.meta.url`) instead of a hand-maintained
literal, so it can never drift again — it was stale at `0.4.20`
before this release. Tests assert they stay in sync.
### Added
- **`src/version.ts`** — exports `VERSION`, `compareVersions`,
`getLatestVersion`, `isNpxInstall`, and the
`LATEST_CACHE_TTL_MS` / `LATEST_FETCH_TIMEOUT_MS` constants.
`getLatestVersion` caches to `~/.reasonix/version-cache.json`
(24h TTL) and returns `null` on any failure.
- **`reasonix update`** subcommand (`src/cli/commands/update.ts`).
`planUpdate()` is the pure decision function, `updateCommand()`
is the CLI orchestrator with test seams (`fetchLatest`, `isNpx`,
`spawnInstall`, `write`, `exit`).
- **StatsPanel header shows `v${VERSION}`** inline, plus an
`update: X` badge (yellow, bold) on the right when
`updateAvailable` is passed. App.tsx fires the registry check
in a background `useEffect` on mount; only a version strictly
newer than the running one flips the state.
### Fixed
- **Drifted `VERSION` constant.** `src/index.ts` hard-coded
`"0.4.20"` while `package.json` was on `0.4.21`. Replaced with a
re-export from `src/version.ts`, which reads the manifest on
first access. A regression test pins them together.
### Tests (+19, suite 588 → 607)
- `tests/version.test.ts` — `VERSION === package.json.version`,
`compareVersions` covers numeric + pre-release ordering,
`isNpxInstall` covers the three detection paths,
`getLatestVersion` covers cache hit / force-refresh / expired
entry / network failure / bad body / cache-write failure.
- `tests/update-command.test.ts` — `planUpdate` returns the
correct action for all four decision quadrants; `updateCommand`
respects every seam: no-spawn on up-to-date, no-spawn on npx,
spawns on global-behind-latest, honors `--dry-run`, exits
non-zero on registry failure, surfaces npm's non-zero exit.
---
## [0.4.21] — 2026-04-22
**Headline:** Skills — user-authored prompt packs, two-scope layout
matching user-memory.
Reasonix discovers skills under `<project>/.reasonix/skills/` (project
scope) and `~/.reasonix/skills/` (global scope). Project wins on name
collisions — per-repo overrides of a global skill work the way users
expect. Deliberately NOT tied to any other tool's directory
convention (`.claude/`, `.glm/`, etc.): Reasonix is model-agnostic at
the conversation layer, so coupling the skill filesystem to one
vendor would break anyone running a different backend.
The pinned index (names + one-line descriptions) lives in the
immutable system prefix; bodies stay lazy and enter the append-only
log only when invoked — either by the model calling the new
`run_skill` tool or by the user typing `/skill <name> [args]`. No
DAG engine, no workflow DSL — the model reads the skill's prose and
continues the normal tool-use loop from there. Pillar 1's cache
invariants are preserved: adding skills grows the pinned index
(under a 4k char cap, with a truncation marker) but never alters
the rest of the prefix.
### Added
- **`src/skills.ts`** — `SkillStore` with `SkillScope` of `"project"`
or `"global"`, both layouts recognized (`{name}/SKILL.md` and flat
`{name}.md`). `applySkillsIndex` composer is pinned into
`applyMemoryStack` alongside REASONIX.md + user memory, receiving
the same `rootDir` so the project scope picks up
`<rootDir>/.reasonix/skills/`.
- **`run_skill` tool** (`src/tools/skills.ts`) — read-only, returns
the full markdown body plus an optional forwarded `Arguments:` line.
Registered in `reasonix chat` (global only) and `reasonix code`
(project + global).
- **`/skill` slash command** — `list` / `show <name>` / bare
`<name> [args]` form. The bare form injects the skill body as a
user turn via the same `resubmit` hook `/apply-plan` uses. Reads
project scope from `ctx.codeRoot`, mirroring how `/memory` behaves.
### Notes
- Each skill's `allowed-tools` frontmatter is parsed but **ignored**
in v1. Reasonix's tool namespace (`filesystem`, `shell`, `web`)
doesn't one-to-one map onto other clients' names; the model reads
the prose instructions and picks our equivalents. Will revisit
once the tradeoffs are clearer.
- What we explicitly did **not** add: workflow DSL, DAG scheduler,
parallel branches, sub-agents. Skills are prose; the model does the
sequencing. This keeps single-loop + append-only + cache-first
intact — the architectural non-goal "no multi-agent orchestration"
stands.
### Fixed
- **`ShellConfirm` "always allow" did not take effect until relaunch.**
The `run_command` tool captured `extraAllowed` as a snapshot at
registration time, so a prefix the user approved mid-session was
written to `~/.reasonix/config.json` but the in-memory tool still
refused it — the next invocation re-triggered the confirmation
modal. `ShellToolsOptions.extraAllowed` now accepts a getter in
addition to a static array; `reasonix code` passes
`() => loadProjectShellAllowed(rootDir)` so the allowlist is
re-read from disk on every dispatch. Static-array callers keep
working unchanged.
- **Windows cmd.exe built-ins (`dir`, `echo`, `type`, `ver`, …)
crashed with ENOENT.** These aren't standalone executables, so
`PATH × PATHEXT` lookup misses and `spawn dir` fails. `prepareSpawn`
now routes bare unresolved Windows commands through
`cmd.exe /d /s /c "<cmd> <args…>"` with verbatim-args + manual
metacharacter quoting — same wrapping strategy we already use for
`.cmd`/`.bat` files. Built-ins resolve correctly; genuinely unknown
commands get the standard "'foo' is not recognized as an internal
or external command" message instead of a raw spawn error.
Already-extensioned names (`node.exe`) and paths-with-separators
(`C:\tool.exe`) still pass through unwrapped so an explicit "I
know where this is" invocation fails loudly when it's missing.
## [0.4.19] — 2026-04-22
**Headline:** Windows shell hotfix + StormBreaker visibility.
`reasonix code` now runs `npm`, `npx`, `tsc`, `yarn`, `pnpm`, `bun`,
`pytest`, and every other `.cmd` / `.bat` wrapper on Windows — both
under Node 18/20 (broken by missing PATHEXT resolution) and Node
21.7.3+/24 (broken by CVE-2024-27980's prohibition on direct
`.cmd`/`.bat` spawns with `shell: false`). Unix behavior unchanged.
Plus: the StormBreaker anti-loop-detector no longer silently halts
a turn — when it fires it emits a visible warning row explaining
what was suppressed and what the user should do next, and its
sliding window resets on each new user message so a new intent
doesn't inherit the previous turn's repeat patterns.
### Fixed
- **`spawn npm ENOENT` on Windows** — `child_process.spawn` with
`shell: false` uses `CreateProcess`, which ignores PATHEXT. Bare
`npm` failed because no `npm.exe` exists — only `npm.cmd`. New
`resolveExecutable(cmd)` walks `PATH × PATHEXT` manually and
returns the full resolved path (`C:\Program Files\nodejs\npm.CMD`)
before handing to spawn. Keeps `shell: false` (no shell expansion
of piped / chained commands — the whole reason we avoided
`shell: true` to begin with).
- **`spawn npm EINVAL` on Node ≥ 21.7.3 / 24** — even with the
resolved `.cmd` path, Node's post-CVE-2024-27980 patch refuses to
execute `.cmd` / `.bat` files via direct spawn. Second layer:
`prepareSpawn()` detects a `.cmd` / `.bat` target on Windows and
rewrites the invocation to `cmd.exe /d /s /c "<bin> <args…>"`
with `windowsVerbatimArguments: true`. Each arg is routed through
`quoteForCmdExe()`, which wraps in double quotes when the arg
contains whitespace or cmd.exe metacharacters
(`" & | < > ^ % ( ) , ; !`) and doubles embedded quotes per
cmd.exe's `""` escape rule. Arguments like `a&b` stay literal;
they don't become shell operators.
### Added
- **`resolveExecutable(cmd, opts?)`** — exported from `src/tools/shell.ts`.
Windows PATH × PATHEXT resolver. Opts lets tests inject `platform`,
`env`, and `isFile` so the Windows-specific path can be exercised
from a Linux CI runner without touching real fs.
- **`prepareSpawn(argv, opts?)`** — exported. Returns the
`(bin, args, spawnOverrides)` tuple that runCommand should pass to
`child_process.spawn`. On non-Windows it's a passthrough; on
Windows it applies the PATHEXT lookup and the `cmd.exe` wrapping
when needed. Unit-tested without spawning real processes.
- **`quoteForCmdExe(arg)`** — exported. The per-arg quoting
function. Round-trip tested against realistic argvs
(`npm install`, paths with spaces, args containing
`& | < > ^`, empty strings, embedded double quotes).
- **Silent storm-break**. When `StormBreaker` caught a repeated
`(tool, args)` pattern it dropped the offending call but emitted
nothing user-visible beyond a small `[repair] broke 1 storm` note
on the assistant row. If the suppressed call was the only tool
call of the turn, the turn just ended — no explanation of why
nothing happened. Now the loop yields a dedicated `warning` event
(same channel as Esc-abort and budget warnings) with an
actionable message, distinguishing "all calls suppressed (stuck
retry)" from "some calls suppressed" cases.
- **StormBreaker state bleeds across user turns**. The sliding
window of recent signatures persisted for the lifetime of the
loop, so a stuck pattern from an earlier intent could false-
positive against the user's legitimate new "try again with
different input" request. `CacheFirstLoop.step()` now calls
`repair.resetStorm()` on every new user turn — the window
repopulates naturally as the new turn's tool calls fire, and
genuine repeats still trip after the usual 3-in-a-row pattern.
### Added
- **`ToolCallRepair.resetStorm()`** — exposes StormBreaker.reset
through the repair facade. Called by the loop at each user turn;
library consumers that drive `repair.process` manually can use it
too if they wrap their own turn semantics.
### Tests (+22, suite 566 → 588)
- `tests/shell-tools.test.ts` (+21) — `resolveExecutable` on
non-Windows (passthrough), PATHEXT walk (first-hit ordering,
whitespace-tolerant PATHEXT entries), absolute-path / slash /
already-extensioned passthrough, empty input, missing PATH /
PATHEXT. `quoteForCmdExe` (simple identifiers unquoted, whitespace
+ metachars quoted, embedded quotes doubled, empty string
→ `""`). `prepareSpawn` (unix passthrough, `.cmd` wraps via
cmd.exe, `.bat` wraps too, `.exe` direct, metachar args quoted,
PATHEXT miss falls through).
- `tests/repair/pipeline.test.ts` (+1) — `resetStorm` clears the
repeat-window so post-reset calls aren't suppressed.
- `tests/loop.test.ts` — the iter-budget warning test refined to
filter by the iter-specific pattern, since identical fixture
calls now also trip the (correct) storm warning.
### Internals
- `runCommand` in `src/tools/shell.ts` now calls `prepareSpawn`
instead of spawning `argv[0]` directly. Every codepath that was
going through `spawn` still does; the `bin` / `args` /
`spawnOverrides` it receives are platform-normalized.
- Existing allowlist + `readOnlyCheck` plan-mode gate + timeout /
output-cap / AbortSignal wiring is untouched.
- `CacheFirstLoop.step()` now resets the StormBreaker at the top of
each turn AND emits a `warning` event after `repair.process()`
when `report.stormsBroken > 0`. The existing `repair` field on
`assistant_final` still carries the count for historical records
/ transcripts.
---
## [0.4.18] — 2026-04-22
**Headline:** Plan Mode — the model can propose a markdown plan
autonomously for large tasks (multi-file refactors, architecture
changes, ambiguous requests), and you can also force a read-only
exploration phase via `/plan`. Picker shows Approve / Refine / Cancel.
Approve pushes a synthetic "implement now" message; Refine keeps the
model exploring; Cancel drops the plan. Designed around Pillar 1 —
tool specs stay pinned, so the cache prefix doesn't break when plan
mode toggles.
### Added
- **`submit_plan` tool** (`src/tools/plan.ts`) — registered by default
in `reasonix code`. Throws `PlanProposedError` carrying the plan
text via the new `toToolResult()` protocol on ToolRegistry. Fires
the picker whether or not plan mode is active — the model is
expected to propose plans on its own for large tasks; `/plan` is
the *stronger* constraint that forces the model into read-only.
- **`/plan` slash** (code mode only) — toggles read-only plan mode.
`/plan on`, `/plan off`, or `/plan` to flip. While on, the registry
refuses non-read-only dispatch; while off, the model can still
propose plans autonomously via submit_plan. `/status` surfaces the
state; `StatsPanel` shows a red `PLAN` tag.
- **`/apply-plan` slash** (code mode only) — force-approve fallback.
Clears plan mode, clears the pending-plan picker state, and
resubmits the implement-now synthetic via the existing `resubmit`
mechanism. Useful when the model wrote the plan in assistant text
instead of calling submit_plan, or when you want to keyboard-only
the approval without the picker.
- **`ToolDefinition.readOnly` + `readOnlyCheck`** — declarative gate
used by `ToolRegistry.dispatch` when plan mode is on. Read tools
(`read_file`, `list_directory`, `search_files`, `directory_tree`,
`get_file_info`, `web_search`, `web_fetch`) run normally. Write
tools bounce with a refusal the model reads and learns from.
`run_command` uses a dynamic `readOnlyCheck` so allowlisted
invocations (`git status`, `cargo check`, `npm test`, `grep`, …)
still work during planning — exploration isn't gated. Non-allowlisted
commands refuse just like other writes.
- **`ToolRegistry.setPlanMode(on)` / `.planMode`** — the enforcement
switch + accessor. Mirrored onto the UI's `planMode` React state so
the StatsPanel badge stays in sync.
- **`toToolResult()` extension protocol** on Error subclasses —
`ToolRegistry.dispatch` calls it if present when an error is thrown,
serializing custom fields alongside `error`. Used by
`PlanProposedError` to ferry the plan text to the UI without
regex-scraping the error message. Falls back safely on serialization
failure.
- **`PlanConfirm.tsx`** — 3-option Ink picker (Approve / Refine /
Cancel) with the plan rendered as **live Markdown** (via the
existing `Markdown` component — headings, lists, code, bold all
formatted, not raw text) in a cyan-bordered panel above. 2 400-char
rendered cap; longer plans get a "use /tool for full" truncation
marker. Live rows hidden while the picker is up, matching
`ShellConfirm`'s behavior. When the plan contains headings like
"Open questions", "Risks", "Assumptions", "待确认", "开放问题", "风险",
"未知", "假设", "不确定", the picker auto-selects the Refine option
by default and shows a yellow "▲ the plan has open questions —
pick Refine to answer them" hint above the options.
- **`PlanRefineInput.tsx`** — inline text input that appears after
the user picks either **Approve** or **Refine**. Picking Approve
lets the user type last-minute instructions or answers to the
model's open questions (blank Enter = approve as-is). Picking
Refine requires specifics — the input collects them and includes
them verbatim in the synthetic sent to the model, so "refine"
actually means "revise with this feedback" instead of the generic
"try again" message the first cut sent. Esc returns to the picker
without resuming the loop.
- **System-prompt guidance** (`CODE_SYSTEM_PROMPT`) — teaches the
model when to call submit_plan autonomously (big / risky / ambiguous
tasks) vs. just making the change (typos, obvious one-line fixes),
and how `/plan` mode adds the stronger dispatch gate on top.
### Tests (+24, suite 542→566)
- `tests/plan.test.ts` (+17) — ToolRegistry plan-mode gate
(default-off, toggle, block non-read-only, allow read-only, honor
`readOnlyCheck` per-args, precedence over `readOnly`, off-mode
noop); `toToolResult` protocol (serializes custom fields, falls
back on serializer failure); `PlanProposedError` carries plan +
STOP directive; `registerPlanTool` registers submit_plan as
read-only, fires picker both in and out of plan mode, rejects
empty plans, trims whitespace.
- `tests/slash.test.ts` (+7) — `/plan` registry entries + required
commands check; `/plan` toggle / on / off / true / false / 0 / 1;
`/plan` info text explicit about the stronger-constraint
relationship; `/apply-plan` code-mode gating; `/apply-plan` flips
mode + clears pending + resubmits; works without optional
`clearPendingPlan` callback; `/status` plan-mode line appears
iff on.
### Internals
- `src/tools/filesystem.ts` — read_file / list_directory /
directory_tree / search_files / get_file_info tagged readOnly.
- `src/tools/shell.ts` — run_command gets `readOnlyCheck` tied to
the existing `isAllowed` check + `allowAll` escape hatch.
- `src/tools/web.ts` — web_search / web_fetch tagged readOnly.
- `src/cli/commands/code.tsx` — `registerPlanTool(tools)` added after
the filesystem and shell registrations so the tool is always in
the pinned spec list (prefix cache stays stable across
plan-mode toggles).
- `src/index.ts` — re-exports `PlanProposedError`, `registerPlanTool`,
`PlanToolOptions` for library consumers.
---
## [0.4.17] — 2026-04-22
**Headline:** Project memory — drop a `REASONIX.md` in your project
root and its contents are pinned into the immutable-prefix system
prompt for every session in that directory. Persistent project
context (house conventions, domain glossary, gotchas the model keeps
forgetting) without eating per-turn context budget, and the prefix
cache stays warm as long as the file is stable.
### Added
- **`src/project-memory.ts`** — `readProjectMemory(rootDir)`,
`applyProjectMemory(basePrompt, rootDir)`, `memoryEnabled()`. One
source, one mental model: `REASONIX.md` at the project root, read
once at session start, appended as a fenced "# Project memory"
block after the base system prompt. Truncates at 8 000 chars
(≈ 2k tokens) with a visible marker; `.gitignore` gets 2 000
because it's a constraint dump, memory gets more headroom because
it's deliberate instructions. Re-exported from `src/index.ts` for
library consumers.
- **Auto-applied at every CLI entry** — top-level `reasonix`,
`reasonix chat`, `reasonix run`, and `reasonix code` all honor
the file. `code` resolves it against the rooted directory; the
others against `process.cwd()` at launch.
- **`/memory` slash command** — prints the resolved file path +
full contents (or a how-to stub when absent), so you can verify
what the model is actually seeing without reading the system
prompt blob. Reminds you changes take effect on the next launch
or `/new`; the system prompt is hashed once per session to keep
the prefix cache warm.
- **`REASONIX_MEMORY=off|false|0` env opt-out** — for CI or
intentional offline reproducibility. `rm REASONIX.md` is the
other opt-out.
### Tests (+25, suite 517→542)
- `tests/project-memory.test.ts` (+15) — absent / empty /
whitespace-only / normal / oversized file paths;
`memoryEnabled` env-value matrix; `applyProjectMemory` no-ops on
missing/disabled; determinism (identical input ⇒ identical
output, cache-prefix-safe); `codeSystemPrompt` stacks base →
memory → .gitignore in the right order when all three exist.
- `tests/slash.test.ts` (+4) — `/memory` prints the how-to when no
file, contents when present, "disabled" when env-off, "no root"
when `memoryRoot` is absent from the SlashContext. Registry
check updated to require `/memory`.
---
## [0.4.16] — 2026-04-22
**Headline:** Native `run_command` shell tool so the model can run
its own tests and verify its work (Claude Code / Aider parity).
3-choice picker for every unknown command — "run once", "always
allow in this project" (persists to `~/.reasonix/config.json`), or
"deny". Plus a session picker on startup so `reasonix code` stops
silently resuming the last conversation, and a Windows backspace fix.
### Added
- **`src/tools/shell.ts`** — `run_command(command, timeoutSec?)`
registered by default in `reasonix code`. Read-only / testing
commands (`git status`, `ls`, `cat`, `grep`, `rg`, `npm test`,
`pytest`, `cargo test`, `cargo check`, `cargo clippy`, `go test`,
`deno test`, `bun test`, `ruff`, `mypy`, `npx tsc --noEmit`,
`npx biome check`, language `--version` probes) auto-run. Anything
else goes through the ShellConfirm picker. 60s default timeout,
32k-char output cap. `shell: false` in the child_process spawn
so the model can't pipe / redirect / chain its way past the
allowlist.
- **`src/cli/ui/ShellConfirm.tsx`** — 3-option SingleSelect modal
that renders when the model asks to run a non-allowlisted
command. Borders + color so it's impossible to miss. Arrow-key
navigation; Enter confirms. No `y/n` hotkey — too easy to trigger
by accident mid-typing.
- **`src/cli/ui/SessionPicker.tsx`** — on `reasonix chat` /
`reasonix code` startup, if the session has prior messages, show
a 3-option picker: **New** (default, safer), **Resume** (continue
where you left off), **Delete and start new**. Flags `--resume`
/ `--new` bypass the picker for CI / muscle-memory.
- **Per-project persistent allowlist** — `config.projects[<abs>].shellAllowed`
stores prefixes the user approved via "always allow". On next
`reasonix code` in that dir they auto-run. Helpers
`loadProjectShellAllowed` / `addProjectShellAllowed` exported.
### Fixed
- **Backspace dead on some Windows terminals.** Certain Git Bash /
winpty combos report plain Backspace with `key.delete=true` and
`key.backspace=false`; the 0.4.15 cursor reducer split the two
and treated `delete` as forward-delete, which is a no-op when the
cursor is at the end of the buffer — so pressing Backspace did
nothing and Ctrl+Backspace (reported differently) was the only
way to delete. Now both flags collapse to backward-delete, plus
raw DEL (0x7f) and BS (0x08) bytes in `key.input` are honored as
backspace too.
### Tests (+43, suite 474→517)
- `tests/shell-tools.test.ts` (+27) — tokenizer (quoting, escapes,
unclosed-quote rejection); allowlist matching (exact / prefix /
whitespace normalization / extras); `runCommand` against real
child processes (stdout, stderr, cwd, timeout kill, output cap,
empty-command rejection); registry dispatch (auto-run, refusal
via `NeedsConfirmationError`, `allowAll: true` bypass);
`formatCommandResult`; `NeedsConfirmationError` name/message
invariants (no stale `/apply-shell` reference).
- `tests/shell-confirm.test.ts` (+4) — `derivePrefix` picks one or
two tokens based on known wrappers and normalizes whitespace.
- `tests/config.test.ts` (+3) — `loadProjectShellAllowed` defaults
to `[]`; `addProjectShellAllowed` persists and dedups per-project;
ignores empty prefixes.
- `tests/multiline-keys.test.ts` (+2) — raw DEL/BS bytes are
treated as backspace; `key.delete` unified with `key.backspace`.
---
## [0.4.15] — 2026-04-22
**Headline:** Web search + fetch tools (on by default, zero
configuration) plus real cursor editing in the prompt box (←/→,
Backspace/Delete mid-string, multi-line ↑/↓ navigation).
### Fixed
- **PromptInput was append-only** — cursor was always pinned to
the end of the buffer, so the only way to fix a typo was
backspacing back through everything after it. Now:
- `←` / `→` move the cursor one column (clamped to buffer).
- `↑` / `↓` move across lines in a multi-line buffer, preserving
column when possible, clamping when the target line is shorter.
- `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 input inserts at the cursor (including multi-char
paste bursts).
- `Shift+Enter` / `Ctrl+J` insert a newline at the cursor.
- **History recall no longer steals arrow keys from mid-edit.**
`↑` / `↓` only trigger prior-prompt recall when the buffer is
empty. A non-empty buffer keeps the arrows for cursor motion so
typed text isn't clobbered.
### Added
Web search + fetch tools are registered by default on `reasonix
chat` and `reasonix code`. The model calls `web_search` /
`web_fetch` on its own whenever a question needs fresher info than
its training data. Backed by **Mojeek**'s public search page — no
API key, no signup. Same Cache-First + repair + context-safety
plumbing as every other tool.
Implementation note: the first cut of this feature used DuckDuckGo,
but a live probe from the dev machine confirmed DDG now serves
HTTP 202 anti-bot pages for every unauthenticated POST regardless
of UA. Mojeek is an independent-index engine that's been stable
against the same probe (3/3 success on three queries spaced 3s
apart). Real-browser `User-Agent` string avoids Mojeek's
fast-path scraper filter.
- **`src/tools/web.ts`** — two functions + one registration helper:
- `webSearch(query, opts?)` — fetches DDG's HTML endpoint, parses
ranked results (title + url + snippet). `topK` is clamped to
[1, 10]. Parser decodes DDG's `uddg=<url>` redirect wrapper and
common HTML entities.
- `webFetch(url, opts?)` — HTTP GET + HTML-to-text extraction
(scripts/styles/nav/footer/aside/svg stripped, paragraph breaks
preserved, entities decoded). 15s timeout, 32k-char cap (matches
tool-result budget), forwards caller's AbortSignal so Esc during
a long fetch is honored.
- `registerWebTools(registry, opts?)` — registers both as
ToolRegistry entries the model can invoke. Tool descriptions
guide the model to call search whenever training data might be
stale.
- **`ReasonixConfig.search`** + **`searchEnabled()`** — a simple
boolean. Default on. Turn off with `search: false` in config or
`REASONIX_SEARCH=off|false|0` in env. No API keys, no provider
picker — one switch.
- **Auto-registered in chat/code.** `reasonix chat` and
`reasonix code` register `web_search` + `web_fetch` by default.
Zero setup: after the normal wizard, the model can already reach
the web.
### Tests (+18, suite 444→462)
- `tests/web-tools.test.ts` (+13) — htmlToText strips
scripts/styles/nav/footer + decodes entities + collapses
whitespace; `parseDuckDuckGoResults` decodes redirect URLs + entities
+ returns empty on unexpected markup; `webSearch` hits the DDG
endpoint with a browsery UA, respects topK, clamps to [1, 10],
throws on non-2xx; `formatSearchResults` renders the expected
layout; `registerWebTools` registers both verbs; `web_fetch` refuses
non-http(s) URLs; `webFetch` extracts title + body, truncates at
the cap with a visible marker, surfaces 404s.
- `tests/config.test.ts` (+5) — `searchEnabled` defaults to true;
honors `search: false` in file; honors `REASONIX_SEARCH=off|false|0`;
stays true for unrelated env values; env off beats config true.
---
## [0.4.14] — 2026-04-22
**Headline:** Render-load reductions for Windows terminals where
Ink's cursor-up repaint leaves ghost artifacts (winpty / MINTTY /
Git Bash). No single bug fix — a set of pressure reductions plus an
explicit opt-out for the terminals where nothing else helps.
### Fixed
- **`patchConsole: false`** on every `render()` call (chat, setup,
replay, diff). We never log to console during the TUI, so the
patch was pure overhead and a known redraw-glitch source on
wrapped-ANSI terminals.
- **Consolidated every animated component onto a single 120ms tick.**
Previously `Pulse` (500ms), `Elapsed` × 2 (1000ms each), `StatusRow`
(120ms + 1000ms), `OngoingToolRow` (120ms + 1000ms), and
`PromptInput` cursor blink (500ms) each owned a private
`setInterval`. On a streaming turn that's 6-10 uncoordinated
re-render sources firing into Ink's patch loop. New
`TickerProvider` / `useTick` / `useElapsedSeconds` in
`src/cli/ui/ticker.tsx` collapses all of them to one shared
counter — same visible behavior, ~5× fewer React re-renders per
second.
- **Flush interval 60ms → 100ms.** 10 Hz still feels live while
giving slow terminals more headroom per repaint. The prior 60ms
rate queued patches faster than some Windows terminals could
process them, manifesting as visible duplicates in scrollback.
- **`reasonix --version` no longer reports 0.4.3 forever.** The
hardcoded `VERSION` in `src/index.ts` had been stale since April
21; now matches `package.json`.
### Added
- **`REASONIX_UI=plain` env opt-out.** Suppresses every transient
row in the render tree (streaming preview, ongoing-tool spinner,
status line, processing fallback) AND disables the ticker
entirely. Only `<Static>` committed events + the input prompt are
drawn. Trades liveness for stability; use when the default TUI
produces ghost rendering on your terminal.
---
## [0.4.13] — 2026-04-22
**Headline:** Two streaming-row bugs that made `reasonix code` feel
broken: the spinner froze for the entire duration of a large
`edit_file` call, and multi-iteration turns displayed the previous
iteration's body text concatenated into the next one.
### Fixed
- **Streaming row no longer freezes during a large tool-call.** When
the model streams `tool_calls[].function.arguments` (kilobytes of
SEARCH/REPLACE for a big `edit_file`) there are zero `content` or
`reasoning_content` bytes, so the label sat on "writing response ·
N chars" untouched — indistinguishable from a hung network. The
loop now yields a new `tool_call_delta` event carrying the growing
cumulative argument-char count, and the TUI surfaces it either as
a dedicated "assembling tool call <name> · N chars of arguments"
phase (magenta) when content/reasoning are empty, or as an extra
segment on the "writing response" line when content is also
streaming.
- **Multi-iteration turns no longer concat prior iterations' text
into the next row.** A single `handleSubmit` can span N iterations
(each tool_call loops us around the model), and the streaming
buffer wasn't reset between them. If an iteration returned empty
content (pure tool_calls), the historical entry fell back to the
streaming-buffer's accumulated text — yielding an assistant block
that read like a concatenation of every prior iteration's reply.
Fix: clear `streamRef.text` / `.reasoning` / `.toolCallBuild` and
the per-flush buffers on every `assistant_final`.
- **Unique `<Static>` key per iteration.** A single turn's multiple
assistant_final events used to share one React key, which Ink
dedupes; the iteration counter fixes it.
### Added
- `LoopEvent` role `tool_call_delta` with field `toolCallArgsChars`
(cumulative arguments-string length for the call being assembled).
Useful for any UI consumer, not just the TUI.
### Tests (+1, suite 443→444)
- `tests/loop.test.ts` — new streaming test: fake SSE body streams a
tool_call across multiple chunks; asserts `tool_call_delta` events
carry a strictly-growing `toolCallArgsChars` and that the id-only
opener (name still empty) does not emit an event.
---
## [0.4.12] — 2026-04-22
**Headline:** Bulletproof tool_calls ↔ tool pairing so corrupted
session files can't keep 400ing forever. Auto-compact attempt
before forcing summary on context-guard so a single oversized
turn doesn't eat your entire session.
### Fixed
- **DeepSeek 400 "insufficient tool messages following tool_calls"**
after a forced-summary on context-guard. Root cause: the loop
appended `assistant.tool_calls` and then bailed to summary BEFORE
dispatching the tools, leaving the log in a shape DeepSeek's API
validator rejects. Fix: strip the dangling tail before calling
summary, and defensively validate at every `buildMessages` call.
- **DeepSeek 400 "tool must be a response to a preceding tool_calls"**
when typing anything after the above error. Root cause: partial
fixes left stray tool messages or half-matched tool_calls in the
log. Fix: `healLoadedMessages` now runs a full pairing validator
— any `assistant.tool_calls` whose response set is incomplete is
dropped along with its partial responses; any stray tool message
is dropped. Runs on session load (with disk rewrite to persist the
heal) AND on every outgoing API call (defensive).
- **Auto-compact before forcing summary** on context-guard trip.
Previously the loop immediately forced a summary at 80% context —
users lost a full turn of work. Now it first tries shrinking
oversized tool results; if that drops enough tokens, the turn
continues normally and the user can keep asking. Falls back to
forced summary only when compaction has nothing to shrink.
- **`CacheFirstLoop.compact()` no longer strips structural tail** —
split the "shrink oversized tool payloads" concern out from the
full load-time heal. `/compact` during a live session only
shrinks, never touches tool_calls/tool pairing (those edges are
legitimate mid-turn state).
### Internals
- New exported `shrinkOversizedToolResults(messages, cap)` for the
shrink-only concern. `healLoadedMessages` now composes
`shrinkOversizedToolResults` + the full pairing validator.
- Session load heal now rewrites the session file on disk when
anything was healed, so the damage doesn't re-surface every
restart.
### Tests (+5, 4 reshaped, suite 436→443)
- `tests/loop-error.test.ts` (+5) — `healLoadedMessages` drops a
stray tool without preceding tool_calls; drops an
assistant.tool_calls whose response set is incomplete; 4 existing
tests reshaped to use valid tool_call pairings (stray tools now
correctly get pruned by the validator).
- `tests/loop.test.ts` (+2) — context-guard auto-compacts oversized
tool results and continues instead of forcing summary; dangling
assistant-with-tool_calls tail stripped defensively at
buildMessages time.
---
## [0.4.11] — 2026-04-22
**Headline:** Real git-diff-style output for `edit_file`, `/new`
+554 -219
View File
@@ -6,230 +6,514 @@
[![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.
### 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).
---
## `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 +545,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 +554,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 +641,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
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "reasonix",
"version": "0.4.11",
"version": "0.4.22",
"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);
});
+92 -3
View File
@@ -1,6 +1,7 @@
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";
@@ -8,8 +9,17 @@ 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";
@@ -43,6 +53,10 @@ export interface ChatOptions {
* 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 {
@@ -58,10 +72,24 @@ interface RootProps extends ChatOptions {
* 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, mcpServers, progressSink, ...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
@@ -73,6 +101,26 @@ function Root({ initialKey, tools, mcpSpecs, mcpServers, progressSink, ...appPro
);
}
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}
@@ -189,6 +237,44 @@ export async function chatCommand(opts: ChatOptions): Promise<void> {
}
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}
@@ -196,9 +282,12 @@ export async function chatCommand(opts: ChatOptions): Promise<void> {
mcpSpecs={mcpSpecs}
mcpServers={mcpServers}
progressSink={progressSink}
sessionPreview={sessionPreview}
{...opts}
/>,
{ exitOnCtrlC: true },
// 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();
+36 -1
View File
@@ -19,9 +19,14 @@
*/
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 {
@@ -33,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> {
@@ -49,9 +58,33 @@ export async function codeCommand(opts: CodeOptions = {}): Promise<void> {
// 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)"}" · ${tools.size} native fs tool(s)\n`,
`▸ reasonix code: rooted at ${rootDir}, session "${session ?? "(ephemeral)"}" · ${tools.size} native tool(s)\n`,
);
await chatCommand({
@@ -62,5 +95,7 @@ export async function codeCommand(opts: CodeOptions = {}): Promise<void> {
session,
seedTools: tools,
codeMode: { rootDir },
forceResume: opts.forceResume,
forceNew: opts.forceNew,
});
}
+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;
+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();
}
+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();
}
+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);
}
}
+23 -3
View File
@@ -1,6 +1,7 @@
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";
@@ -11,6 +12,7 @@ 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";
@@ -37,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,
@@ -59,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({
@@ -66,6 +70,8 @@ program
model: opts.model,
noSession: opts.session === false,
transcript: opts.transcript,
forceResume: !!opts.resume,
forceNew: !!opts.new,
});
});
@@ -90,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.',
@@ -113,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,
});
});
@@ -159,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,
@@ -251,6 +261,16 @@ mcp
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);
+487 -77
View File
@@ -10,16 +10,23 @@ import {
restoreSnapshots,
snapshotBeforeEdits,
} from "../../code/edit-blocks.js";
import { addProjectShellAllowed } from "../../config.js";
import { CacheFirstLoop, DeepSeekClient, ImmutablePrefix } from "../../index.js";
import type { LoopEvent } from "../../loop.js";
import type { SessionSummary } from "../../telemetry.js";
import type { ToolRegistry } from "../../tools.js";
import { formatCommandResult, runCommand } from "../../tools/shell.js";
import { openTranscriptFile, recordFromLoopEvent, writeRecord } from "../../transcript.js";
import { VERSION, compareVersions, getLatestVersion } from "../../version.js";
import { type DisplayEvent, EventRow } from "./EventLog.js";
import { PlanConfirm, type PlanConfirmChoice } from "./PlanConfirm.js";
import { PlanRefineInput } from "./PlanRefineInput.js";
import { PromptInput } from "./PromptInput.js";
import { ShellConfirm, type ShellConfirmChoice, derivePrefix } from "./ShellConfirm.js";
import { SlashSuggestions } from "./SlashSuggestions.js";
import { StatsPanel } from "./StatsPanel.js";
import { type McpServerSummary, handleSlash, parseSlash, suggestSlashCommands } from "./slash.js";
import { TickerProvider, useElapsedSeconds, useTick } from "./ticker.js";
export interface AppProps {
model: string;
@@ -63,14 +70,25 @@ export interface AppProps {
/**
* Throttle interval in ms. We flush streaming deltas at most this often to
* avoid re-rendering the whole UI on every single token from DeepSeek.
* 60ms ≈ 16Hz, fast enough to feel live, slow enough to not thrash Ink.
* 100ms ≈ 10Hz, still feels live, gives fragile terminals (winpty/MINTTY)
* enough room to finish a repaint before the next one arrives.
*/
const FLUSH_INTERVAL_MS = 60;
const FLUSH_INTERVAL_MS = 100;
/**
* True when the user has opted out of live spinner/streaming rows.
* `REASONIX_UI=plain` suppresses every transient row in the render
* tree so only the `<Static>` committed history + the input prompt
* are drawn. Trades liveness for stability on terminals where Ink's
* cursor-up repaint leaves ghost artifacts.
*/
const PLAIN_UI = process.env.REASONIX_UI === "plain";
interface StreamingState {
id: string;
text: string;
reasoning: string;
toolCallBuild?: { name: string; chars: number };
}
export function App({
@@ -119,6 +137,11 @@ export function App({
// tracks reality. `null` means either the endpoint failed or we
// haven't fetched yet; the panel hides the cell in that case.
const [balance, setBalance] = useState<{ currency: string; total: number } | null>(null);
// Latest published version, populated in the background from the
// npm registry. `null` during the in-flight window and when the
// install is already current (or offline); rendered only when
// there's something newer to nudge the user toward.
const [updateAvailable, setUpdateAvailable] = useState<string | null>(null);
// Snapshots of every file the *last* edit batch touched, keyed by
// nothing more than "most recent". `/undo` restores from this ref
// and nulls it out — one level of undo, Aider-style. Multi-step
@@ -129,6 +152,41 @@ export function App({
// auto-apply — v0.4.1 showed that "model proposed, so apply" turns
// analysis into unintended edits. The user explicitly confirms now.
const pendingEdits = useRef<EditBlock[]>([]);
// Shell command the model asked to run that wasn't on the auto-run
// allowlist. Non-null renders the ShellConfirm modal and disables
// the prompt input; the user picks Run once / Always allow in this
// project / Deny and we feed the result back as a synthetic user
// message so the model sees what happened.
const [pendingShell, setPendingShell] = useState<string | null>(null);
// Plan text the model submitted via `submit_plan` while plan mode
// was active. Non-null renders PlanConfirm; user picks Approve /
// Refine / Cancel and we drive the loop from there. Separate from
// `planMode` because a pending plan is a one-shot decision even if
// plan mode stays on (Refine keeps mode on; Approve/Cancel flip off).
const [pendingPlan, setPendingPlan] = useState<string | null>(null);
// Stashed plan + intent while the user types free-form feedback
// (refinement or last instructions on approve). When the picker
// returns "refine" or "approve", we defer the loop-resume and show
// PlanRefineInput. User types + Enter → we ship it; Esc → restore
// pendingPlan and re-show the picker. Letting Approve also take
// input closes the "model left open questions, user had no place
// to answer them" hole.
const [stagedInput, setStagedInput] = useState<{
plan: string;
mode: "refine" | "approve";
} | null>(null);
// Plan-mode indicator — displayed in the StatsPanel, mirrored onto
// the ToolRegistry so dispatch enforces read-only. Toggled via the
// `/plan` slash and PlanConfirm picker. Ephemeral — not persisted
// across launches (you explicitly opt in per session).
const [planMode, setPlanMode] = useState<boolean>(false);
// Text waiting to be submitted AFTER the current turn finishes.
// Set by ShellConfirm's onChoose when the user approves faster than
// the model's "awaiting confirmation" response. We can't call
// handleSubmit directly because it early-returns on `busy === true`,
// so we abort the in-flight turn and let the effect below fire the
// submit once busy clears.
const [queuedSubmit, setQueuedSubmit] = useState<string | null>(null);
// Shell-style history of user prompts. ↑/↓ while idle walks it;
// submit pushes to the end. Cursor -1 = "live input", 0+ = "N turns
// back from newest". We don't persist history to disk — sessions
@@ -136,6 +194,8 @@ export function App({
// would need per-project scoping we haven't designed.
const promptHistory = useRef<string[]>([]);
const historyCursor = useRef<number>(-1);
// Disambiguates <Static> keys when a single turn yields multiple assistant_final events.
const assistantIterCounter = useRef<number>(0);
// Full untruncated tool results, in arrival order. The EventLog
// renderer clips tool output at 400 chars for display; `/tool N`
// reads from this ref to show the real thing. Not persisted — a
@@ -222,6 +282,22 @@ export function App({
};
}, [loop]);
// Background registry check — 24h disk cache absorbs repeated
// launches, timeout bounded so a flaky network doesn't delay the
// notification. Set to `null` on failure (silent: no network, no
// problem) and on "already latest" so the header stays quiet.
useEffect(() => {
let cancelled = false;
void (async () => {
const latest = await getLatestVersion();
if (cancelled || !latest) return;
if (compareVersions(VERSION, latest) < 0) setUpdateAvailable(latest);
})();
return () => {
cancelled = true;
};
}, []);
// Wire the shared progressSink so the bridge's onProgress → us.
// Only updates progress when the frame belongs to the currently-
// running tool: late frames from a previous call shouldn't overwrite
@@ -292,6 +368,11 @@ export function App({
return;
}
if (busy) return;
// ShellConfirm owns the full keyboard while it's showing. If we
// kept handling ↑/↓ / Tab here they'd race with its SingleSelect
// — the picker would move AND history recall would fire into the
// (hidden) prompt buffer. Bail early.
if (pendingShell) return;
// Slash-suggestion mode takes priority over history recall.
// When the user is typing a `/…` prefix and there are matches,
@@ -314,21 +395,27 @@ export function App({
}
}
// Outside slash mode: ↑/↓ recall prior prompts.
const hist = promptHistory.current;
if (key.upArrow) {
if (hist.length === 0) return;
const nextCursor = Math.min(historyCursor.current + 1, hist.length - 1);
historyCursor.current = nextCursor;
setInput(hist[hist.length - 1 - nextCursor] ?? "");
return;
}
if (key.downArrow) {
if (historyCursor.current < 0) return;
const nextCursor = historyCursor.current - 1;
historyCursor.current = nextCursor;
setInput(nextCursor < 0 ? "" : (hist[hist.length - 1 - nextCursor] ?? ""));
return;
// Outside slash mode: ↑/↓ recall prior prompts — but ONLY when the
// buffer is empty. A non-empty buffer hands those keys to
// PromptInput for cursor movement (multi-line navigation, or a
// no-op on single-line) so the user doesn't accidentally clobber
// typed text with a recalled prompt.
if (input.length === 0) {
const hist = promptHistory.current;
if (key.upArrow) {
if (hist.length === 0) return;
const nextCursor = Math.min(historyCursor.current + 1, hist.length - 1);
historyCursor.current = nextCursor;
setInput(hist[hist.length - 1 - nextCursor] ?? "");
return;
}
if (key.downArrow) {
if (historyCursor.current < 0) return;
const nextCursor = historyCursor.current - 1;
historyCursor.current = nextCursor;
setInput(nextCursor < 0 ? "" : (hist[hist.length - 1 - nextCursor] ?? ""));
return;
}
}
});
@@ -390,6 +477,25 @@ export function App({
[model, prefixHash],
);
/**
* Toggle plan mode on the local state AND on the ToolRegistry. The
* registry's copy is what actually gates dispatch; the local state
* drives the StatsPanel indicator and slash ergonomics. Kept in sync
* by funneling every toggle through this setter.
*/
const togglePlanMode = useCallback(
(on: boolean) => {
setPlanMode(on);
tools?.setPlanMode(on);
},
[tools],
);
/** Clear the pending-plan picker state; safe to call unconditionally. */
const clearPendingPlan = useCallback(() => {
setPendingPlan(null);
}, []);
const handleSubmit = useCallback(
async (raw: string) => {
let text = raw.trim();
@@ -437,6 +543,10 @@ export function App({
codeRoot: codeMode?.rootDir,
pendingEditCount: codeMode ? pendingEdits.current.length : undefined,
toolHistory: () => toolHistoryRef.current,
memoryRoot: codeMode?.rootDir ?? process.cwd(),
planMode,
setPlanMode: codeMode ? togglePlanMode : undefined,
clearPendingPlan: codeMode ? clearPendingPlan : undefined,
});
if (result.exit) {
transcriptRef.current?.end();
@@ -492,26 +602,37 @@ export function App({
const streamRef: StreamingState = { id: assistantId, text: "", reasoning: "" };
const contentBuf = { current: "" };
const reasoningBuf = { current: "" };
// Coalesces tool_call_delta events into one re-render per flush tick.
const toolCallBuildBuf: { current: { name: string; chars: number } | null } = {
current: null,
};
setStreaming({ id: assistantId, role: "assistant", text: "", streaming: true });
setBusy(true);
abortedThisTurn.current = false;
const flush = () => {
if (!contentBuf.current && !reasoningBuf.current) return;
if (!contentBuf.current && !reasoningBuf.current && !toolCallBuildBuf.current) return;
streamRef.text += contentBuf.current;
streamRef.reasoning += reasoningBuf.current;
if (toolCallBuildBuf.current) {
streamRef.toolCallBuild = toolCallBuildBuf.current;
}
contentBuf.current = "";
reasoningBuf.current = "";
toolCallBuildBuf.current = null;
setStreaming({
id: assistantId,
role: "assistant",
text: streamRef.text,
reasoning: streamRef.reasoning || undefined,
toolCallBuild: streamRef.toolCallBuild,
streaming: true,
});
};
const timer = setInterval(flush, FLUSH_INTERVAL_MS);
// In PLAIN mode the streaming row is suppressed, so flushing into
// streamRef does no visible work — skip the interval entirely.
const timer = PLAIN_UI ? null : setInterval(flush, FLUSH_INTERVAL_MS);
try {
for await (const ev of loop.step(text)) {
@@ -529,6 +650,13 @@ export function App({
} else if (ev.role === "assistant_delta") {
if (ev.content) contentBuf.current += ev.content;
if (ev.reasoningDelta) reasoningBuf.current += ev.reasoningDelta;
} else if (ev.role === "tool_call_delta") {
if (ev.toolName) {
toolCallBuildBuf.current = {
name: ev.toolName,
chars: ev.toolCallArgsChars ?? 0,
};
}
} else if (ev.role === "branch_start") {
setStreaming({
id: assistantId,
@@ -560,13 +688,15 @@ export function App({
// confusing in multi-iter tool-call chains.
setSummary(loop.stats.summary());
const finalText = ev.content || streamRef.text;
const iterReasoning = streamRef.reasoning || undefined;
const iterId = `${assistantId}-i${assistantIterCounter.current++}`;
setHistorical((prev) => [
...prev,
{
id: assistantId,
id: iterId,
role: "assistant",
text: finalText,
reasoning: streamRef.reasoning || undefined,
reasoning: iterReasoning,
planState: ev.planState,
branch: ev.branch,
stats: ev.stats,
@@ -574,6 +704,14 @@ export function App({
streaming: false,
},
]);
// streamRef is scoped to the whole handleSubmit call but each
// iteration's deltas must not bleed into the next.
streamRef.text = "";
streamRef.reasoning = "";
streamRef.toolCallBuild = undefined;
contentBuf.current = "";
reasoningBuf.current = "";
toolCallBuildBuf.current = null;
if (codeMode && finalText && !ev.forcedSummary) {
// Parse SEARCH/REPLACE blocks but DO NOT write them to
// disk. Store as pending — the user has to say /apply
@@ -621,6 +759,43 @@ export function App({
toolName: ev.toolName,
},
]);
// run_command rejected because the command isn't on the
// auto-allow list. Stash it so the y/n fast-path can run
// it after user confirmation. Only the latest such request
// is tracked — a second rejection overwrites the first.
if (
codeMode &&
ev.toolName === "run_command" &&
ev.content.includes('"NeedsConfirmationError:') &&
ev.toolArgs
) {
try {
const parsed = JSON.parse(ev.toolArgs) as { command?: unknown };
if (typeof parsed.command === "string" && parsed.command.trim()) {
setPendingShell(parsed.command.trim());
}
} catch {
/* malformed args — skip the prompt */
}
}
// submit_plan fired while plan mode was on — the registry
// serialized `{ error, plan }` via PlanProposedError's
// toToolResult(). Extract the plan and mount PlanConfirm.
// Only the latest submission is tracked; a second overrides.
if (
codeMode &&
ev.toolName === "submit_plan" &&
ev.content.includes('"PlanProposedError:')
) {
try {
const parsed = JSON.parse(ev.content) as { plan?: unknown };
if (typeof parsed.plan === "string" && parsed.plan.trim()) {
setPendingPlan(parsed.plan.trim());
}
} catch {
/* malformed payload — skip the picker */
}
}
} else if (ev.role === "error") {
setHistorical((prev) => [
...prev,
@@ -635,7 +810,7 @@ export function App({
}
flush();
} finally {
clearInterval(timer);
if (timer) clearInterval(timer);
setStreaming(null);
setOngoingTool(null);
setToolProgress(null);
@@ -654,6 +829,7 @@ export function App({
},
[
busy,
clearPendingPlan,
codeApply,
codeDiscard,
codeMode,
@@ -662,41 +838,293 @@ export function App({
loop,
mcpSpecs,
mcpServers,
planMode,
slashSelected,
togglePlanMode,
writeTranscript,
],
);
/**
* ShellConfirm callback. Three outcomes, all of them ending with a
* synthetic user message fed back into the loop so the model sees
* what happened next turn:
* - deny → "I denied running X." and we move on.
* - run_once / always_allow → run the command inside the sandbox
* root, attach the formatted output as the user turn. In the
* always_allow case we also persist the derived prefix to
* config so next invocation auto-runs.
*/
const handleShellConfirm = useCallback(
async (choice: ShellConfirmChoice) => {
const cmd = pendingShell;
if (!cmd || !codeMode) return;
setPendingShell(null);
let synthetic: string;
if (choice === "deny") {
setHistorical((prev) => [
...prev,
{ id: `sh-deny-${Date.now()}`, role: "info", text: `▸ denied: ${cmd}` },
]);
synthetic = `I denied running \`${cmd}\`. Please continue without running it.`;
} else {
if (choice === "always_allow") {
const prefix = derivePrefix(cmd);
addProjectShellAllowed(codeMode.rootDir, prefix);
setHistorical((prev) => [
...prev,
{
id: `sh-allow-${Date.now()}`,
role: "info",
text: `▸ always allowed "${prefix}" for ${codeMode.rootDir}`,
},
]);
}
setHistorical((prev) => [
...prev,
{ id: `sh-run-${Date.now()}`, role: "info", text: `▸ running: ${cmd}` },
]);
let body: string;
try {
const res = await runCommand(cmd, { cwd: codeMode.rootDir });
body = formatCommandResult(cmd, res);
} catch (err) {
body = `$ ${cmd}\n[failed to spawn] ${(err as Error).message}`;
}
setHistorical((prev) => [
...prev,
{ id: `sh-out-${Date.now()}`, role: "info", text: body },
]);
synthetic = `I ran the command you requested. Output:\n\n${body}`;
}
// If the prior turn is still streaming ("please confirm" chatter),
// handleSubmit would early-return on busy=true. Abort the in-flight
// turn and queue the synthetic for the effect below, which fires
// once busy clears. Otherwise submit directly.
if (busy) {
loop.abort();
setQueuedSubmit(synthetic);
} else {
await handleSubmit(synthetic);
}
},
[pendingShell, codeMode, handleSubmit, busy, loop],
);
// Drain the shell-confirm queue after the in-flight turn tears down.
// React closure staleness means handleShellConfirm can't just await
// the abort itself — this effect is the reliable edge detector.
useEffect(() => {
if (!busy && queuedSubmit !== null) {
const text = queuedSubmit;
setQueuedSubmit(null);
void handleSubmit(text);
}
}, [busy, queuedSubmit, handleSubmit]);
/**
* PlanConfirm callback. Three outcomes, all ending with a synthetic
* user message so the model sees the verdict on its next turn:
* - approve → exit plan mode, tell the model to implement now.
* - refine → stay in plan mode, tell the model to revise.
* - cancel → exit plan mode, tell the model to drop the plan.
* Mirrors handleShellConfirm's busy-queue dance — if the turn is
* still streaming "plan submitted, waiting" chatter when the user
* picks, we abort it and queue the synthetic for the effect above.
*
* `approve` is also callable with no pending plan (via the
* `/apply-plan` slash fallback, used when the model wrote a plan in
* assistant text instead of calling submit_plan). In that case we
* just flip plan mode off and push the implement-now message.
*/
const handlePlanConfirm = useCallback(
async (choice: PlanConfirmChoice) => {
const hadPendingPlan = pendingPlan !== null;
if (!hadPendingPlan && choice !== "approve") {
// Refine / Cancel without a pending plan is a no-op; only the
// /apply-plan fallback makes sense without one.
return;
}
if (choice === "refine" || choice === "approve") {
// Two-step: stash the plan + the intent, show the input, wait
// for user feedback before pushing anything. Approve collects
// "last instructions / answers to open questions" (blank is
// fine, user can just hit Enter). Refine collects required
// feedback so the model has concrete guidance to revise.
if (pendingPlan) {
setStagedInput({ plan: pendingPlan, mode: choice });
setPendingPlan(null);
} else if (choice === "approve") {
// /apply-plan fallback path — no pending plan, just approve.
setStagedInput({ plan: "", mode: "approve" });
}
return;
}
// Cancel — no input needed, fire immediately.
setPendingPlan(null);
togglePlanMode(false);
const marker = "▸ plan cancelled";
const synthetic =
"The plan was cancelled. Drop it entirely. Ask me what I actually want before proposing another plan or making any changes.";
setHistorical((prev) => [
...prev,
{ id: `plan-${choice}-${Date.now()}`, role: "info", text: marker },
]);
if (busy) {
loop.abort();
setQueuedSubmit(synthetic);
} else {
await handleSubmit(synthetic);
}
},
[pendingPlan, togglePlanMode, busy, loop, handleSubmit],
);
/**
* Fired when the user submits feedback from the inline input. The
* staged `mode` decides whether this is a refine or approve: refine
* stays in plan mode and asks the model to revise; approve exits
* plan mode and pushes the implement synthetic, with any user
* guidance (answers to open questions, last-minute preferences)
* included verbatim.
*/
const handleStagedInputSubmit = useCallback(
async (feedback: string) => {
const staged = stagedInput;
setStagedInput(null);
if (!staged) return;
const trimmed = feedback.trim();
let synthetic: string;
let marker: string;
if (staged.mode === "approve") {
togglePlanMode(false);
if (trimmed) {
synthetic = `The plan above has been approved. Implement it now. You are out of plan mode — use edit_file / write_file / run_command as needed.\n\nUser's additional instructions / answers to your open questions:\n\n${trimmed}\n\nFactor these in before the first edit. Stick to the plan unless you discover a concrete reason to deviate; if you do, tell me and wait for a response.`;
marker = `▸ plan approved + instructions — ${trimmed.length > 50 ? `${trimmed.slice(0, 50)}…` : trimmed}`;
} else {
synthetic =
"The plan above has been approved. Implement it now. You are out of plan mode — use edit_file / write_file / run_command as needed. If the plan listed open questions and I didn't answer them, default to the safest interpretation and call them out in your first reply. Don't fabricate preferences — if a question is truly unanswerable without me, stop and ask.";
marker = "▸ plan approved — implementing";
}
} else {
// refine
if (trimmed) {
synthetic = `The plan needs refinement. User feedback / answers:\n\n${trimmed}\n\nStay in plan mode — address the feedback (explore more if needed), then submit an improved submit_plan call. Don't propose a near-identical plan unless you explain why the feedback doesn't apply.`;
marker = `▸ refining — ${trimmed.length > 50 ? `${trimmed.slice(0, 50)}…` : trimmed}`;
} else {
synthetic =
"The plan needs refinement, but the user didn't give specifics. Ask them one or two concrete questions — scope, approach, file boundaries, or the risks you flagged — then wait for their answer before submitting an updated plan.";
marker = "▸ refining — asking the model to clarify";
}
}
setHistorical((prev) => [
...prev,
{ id: `plan-${staged.mode}-${Date.now()}`, role: "info", text: marker },
]);
if (busy) {
loop.abort();
setQueuedSubmit(synthetic);
} else {
await handleSubmit(synthetic);
}
},
[stagedInput, togglePlanMode, busy, loop, handleSubmit],
);
/** Esc on the inline input — restore the picker without resuming. */
const handleStagedInputCancel = useCallback(() => {
if (stagedInput?.plan) setPendingPlan(stagedInput.plan);
setStagedInput(null);
}, [stagedInput]);
return (
<Box flexDirection="column">
<StatsPanel
summary={summary}
model={loop.model}
prefixHash={prefixHash}
harvestOn={loop.harvestEnabled}
branchBudget={loop.branchOptions.budget}
balance={balance}
/>
<Static items={historical}>{(item) => <EventRow key={item.id} event={item} />}</Static>
{streaming ? (
<Box marginY={1}>
<EventRow event={streaming} />
</Box>
) : null}
{ongoingTool ? <OngoingToolRow tool={ongoingTool} progress={toolProgress} /> : null}
{!ongoingTool && statusLine ? <StatusRow text={statusLine} /> : null}
{/*
Belt-and-suspenders fallback: if we're busy but NONE of the
specific indicators (streaming, ongoingTool, statusLine) is
visible, something is still happening — show a generic
"processing…" so the user never stares at a silent ticker
without a label. Catches micro-gaps between events that the
targeted status lines don't cover.
*/}
{busy && !streaming && !ongoingTool && !statusLine ? <StatusRow text="processing…" /> : null}
<PromptInput value={input} onChange={setInput} onSubmit={handleSubmit} disabled={busy} />
<SlashSuggestions matches={slashMatches} selectedIndex={slashSelected} />
</Box>
<TickerProvider disabled={PLAIN_UI}>
<Box flexDirection="column">
<StatsPanel
summary={summary}
model={loop.model}
prefixHash={prefixHash}
harvestOn={loop.harvestEnabled}
branchBudget={loop.branchOptions.budget}
planMode={planMode}
balance={balance}
updateAvailable={updateAvailable}
/>
<Static items={historical}>{(item) => <EventRow key={item.id} event={item} />}</Static>
{/*
Live rows are hidden while the ShellConfirm modal is up — the
model's concurrent "please confirm" stream is noise the user
doesn't need, and the picker shouldn't fight it for visual
attention. They come back naturally once the user chooses and
the next turn begins.
*/}
{!PLAIN_UI && !pendingShell && !pendingPlan && !stagedInput && streaming ? (
<Box marginY={1}>
<EventRow event={streaming} />
</Box>
) : null}
{!PLAIN_UI && !pendingShell && !pendingPlan && !stagedInput && ongoingTool ? (
<OngoingToolRow tool={ongoingTool} progress={toolProgress} />
) : null}
{!PLAIN_UI &&
!pendingShell &&
!pendingPlan &&
!stagedInput &&
!ongoingTool &&
statusLine ? (
<StatusRow text={statusLine} />
) : null}
{/*
Belt-and-suspenders fallback: if we're busy but NONE of the
specific indicators (streaming, ongoingTool, statusLine) is
visible, something is still happening — show a generic
"processing…" so the user never stares at a silent ticker
without a label. Catches micro-gaps between events that the
targeted status lines don't cover.
*/}
{!PLAIN_UI &&
!pendingShell &&
!pendingPlan &&
!stagedInput &&
busy &&
!streaming &&
!ongoingTool &&
!statusLine ? (
<StatusRow text="processing…" />
) : null}
{stagedInput ? (
<PlanRefineInput
mode={stagedInput.mode}
onSubmit={handleStagedInputSubmit}
onCancel={handleStagedInputCancel}
/>
) : pendingPlan ? (
<PlanConfirm plan={pendingPlan} onChoose={handlePlanConfirm} />
) : pendingShell ? (
<ShellConfirm
command={pendingShell}
allowPrefix={derivePrefix(pendingShell)}
onChoose={handleShellConfirm}
/>
) : (
<>
<PromptInput
value={input}
onChange={setInput}
onSubmit={handleSubmit}
disabled={busy}
/>
<SlashSuggestions matches={slashMatches} selectedIndex={slashSelected} />
</>
)}
</Box>
</TickerProvider>
);
}
@@ -723,22 +1151,14 @@ export function App({
* spinner + elapsed seconds) so the user's eyes track the same
* spot regardless of which kind of wait it is.
*/
const SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
function StatusRow({ text }: { text: string }) {
const [tick, setTick] = useState(0);
const [elapsed, setElapsed] = useState(0);
useEffect(() => {
const start = Date.now();
const frameId = setInterval(() => setTick((t) => t + 1), 120);
const secId = setInterval(() => setElapsed(Math.floor((Date.now() - start) / 1000)), 1000);
return () => {
clearInterval(frameId);
clearInterval(secId);
};
}, []);
const frames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
const tick = useTick();
const elapsed = useElapsedSeconds();
return (
<Box marginY={1}>
<Text color="magenta">{frames[tick % frames.length]}</Text>
<Text color="magenta">{SPINNER_FRAMES[tick % SPINNER_FRAMES.length]}</Text>
<Text color="magenta">{` ${text}`}</Text>
<Text dimColor>{` ${elapsed}s`}</Text>
</Box>
@@ -752,23 +1172,13 @@ function OngoingToolRow({
tool: { name: string; args?: string };
progress: { progress: number; total?: number; message?: string } | null;
}) {
const [tick, setTick] = useState(0);
const [elapsed, setElapsed] = useState(0);
useEffect(() => {
const start = Date.now();
const frameId = setInterval(() => setTick((t) => t + 1), 120);
const secId = setInterval(() => setElapsed(Math.floor((Date.now() - start) / 1000)), 1000);
return () => {
clearInterval(frameId);
clearInterval(secId);
};
}, []);
const frames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
const tick = useTick();
const elapsed = useElapsedSeconds();
const summary = summarizeToolArgs(tool.name, tool.args);
return (
<Box marginY={1} flexDirection="column">
<Box>
<Text color="cyan">{frames[tick % frames.length]}</Text>
<Text color="cyan">{SPINNER_FRAMES[tick % SPINNER_FRAMES.length]}</Text>
<Text color="yellow">{` tool<${tool.name}> running…`}</Text>
<Text dimColor>{` ${elapsed}s`}</Text>
</Box>
+36 -27
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 }) {
@@ -216,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>;
@@ -274,32 +271,39 @@ function StreamingAssistant({ event }: { event: DisplayEvent }) {
const tail = lastLine(event.text, 140);
const reasoningTail = event.reasoning ? lastLine(event.reasoning, 120) : "";
const toolCallBuild = event.toolCallBuild;
// Four distinct phases a turn can be in — label them plainly so
// the user doesn't have to decode "streaming · 391 + think 4506
// chars" to figure out what's happening:
// pre-first-byte: request in flight, no bytes back yet
// reasoning-only: R1 thinking, no visible content yet
// tool-call-only: tool_call arguments streaming, no content/reasoning bytes
// writing: content streaming (R1 has already produced its thought)
// both: rare — content present AND reasoning still growing
// We can't cheaply distinguish "reasoning still growing" from
// "reasoning finished but we already saw it", so when content is
// present we just say "writing response" and surface both counts.
const preFirstByte = !event.text && !event.reasoning;
const reasoningOnly = !event.text && !!event.reasoning;
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" | undefined;
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 {
// Content phase. If reasoning is non-empty we include its size
// so the user knows R1 did a thinking pass before speaking.
label = event.reasoning
? `writing response · ${event.text.length} chars · after ${event.reasoning.length} chars of reasoning`
: `writing response · ${event.text.length} chars`;
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 (
@@ -319,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>
{" connection open, first byte typically in 5-60s depending on model + load"}
) : 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>
);
}
+91 -47
View File
@@ -1,6 +1,7 @@
import { Box, Text, useInput } from "ink";
import React, { useEffect, useState } from "react";
import { type MultilineKey, processMultilineKey } from "./multiline-keys.js";
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,19 +12,16 @@ export interface PromptInputProps {
}
/**
* Input box with multi-line composition support. Behaves like the
* old single-line prompt by default, but:
* - Ctrl+J inserts a newline (universal across terminals).
* - Shift+Enter inserts a newline (only on terminals that report
* the modifier via CSI-u — many don't).
* - `\<Enter>` at end of line acts as bash-style continuation —
* always works, even on terminals without modifier reporting.
* - Pasted multi-line text lands as-is instead of submitting on
* the first '\r'.
* 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>`.
*
* No mid-string insertion cursor — edits happen at the end, like
* a readline prompt in raw mode. Simple, predictable, enough for
* 95% of prompts and any code paste.
* 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,
@@ -32,24 +30,29 @@ export function PromptInput({
disabled,
placeholder,
}: PromptInputProps) {
const [showCursor, setShowCursor] = useState(true);
// Blink the end-of-input cursor so it's visibly alive even when
// the user hasn't typed for a while. 500 ms matches a typical
// terminal cursor blink.
useEffect(() => {
if (disabled) {
setShowCursor(false);
return;
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);
}
setShowCursor(true);
const id = setInterval(() => setShowCursor((s) => !s), 500);
return () => clearInterval(id);
}, [disabled]);
}
// 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 keyEvent: MultilineKey = {
const ke: MultilineKey = {
input,
return: key.return,
shift: key.shift,
@@ -66,8 +69,14 @@ export function PromptInput({
pageUp: key.pageUp,
pageDown: key.pageDown,
};
const action = processMultilineKey(value, keyEvent);
if (action.next !== null) onChange(action.next);
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 },
@@ -79,17 +88,14 @@ export function PromptInput({
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={borderColor} paddingX={1} flexDirection="column">
{lines.map((line, i) => {
const isLast = i === lines.length - 1;
const isFirst = i === 0;
const showPlaceholder = isFirst && value.length === 0;
// Line content never survives a re-keying here: the value buffer
// fully re-renders on every keystroke, so the array index IS the
// stable identity. Biome's rule targets list reordering, which
// doesn't apply to an append-only splits-by-newline view.
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}>
@@ -100,21 +106,59 @@ export function PromptInput({
) : (
<Text dimColor>{" "}</Text>
)}
{/* When showing the placeholder, the cursor is at position 0 —
put it BEFORE the dimmed hint text so it visually matches
"you're about to type here," not "you typed the placeholder."
When showing real content, the cursor follows the last char
of the last line (append-only edit model). */}
{showPlaceholder && isLast && !disabled ? (
<Text color={borderColor}>{showCursor ? "▌" : " "}</Text>
) : null}
{showPlaceholder ? <Text dimColor>{effectivePlaceholder}</Text> : <Text>{line}</Text>}
{!showPlaceholder && isLast && !disabled ? (
<Text color={borderColor}>{showCursor ? "▌" : " "}</Text>
) : null}
{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>
</>
);
}
+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;
}
+30 -1
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,13 @@ 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
@@ -18,6 +26,13 @@ export interface StatsPanelProps {
* 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({
@@ -26,7 +41,9 @@ export function StatsPanel({
prefixHash,
harvestOn,
branchBudget,
planMode,
balance,
updateAvailable,
}: StatsPanelProps) {
const hitPct = (summary.cacheHitRatio * 100).toFixed(1);
const hitColor =
@@ -44,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>
+77 -16
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;
}
@@ -250,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(" ") });
@@ -307,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;
}
+152 -75
View File
@@ -1,30 +1,34 @@
/**
* Pure keystroke → action reducer for MultilineInput.
* Pure keystroke → action reducer for PromptInput.
*
* Kept separate from the React component so the keyboard
* semantics are easy to unit-test. MultilineInput is otherwise
* a thin Ink wrapper that threads its `useInput` callback
* through this function and applies the result.
* 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.
*
* Terminal reality check: on most terminals, pressing Shift+Enter
* sends the exact same byte as plain Enter — the modifier is lost.
* That's why the reliable newline insertion path is Ctrl+J (which
* really is LF, distinct from CR), with Shift+Enter only working
* on terminals that opt into CSI-u modifier encoding. The `\<Enter>`
* bash-style continuation is the portable fallback.
* 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 {
/** Printable character(s) delivered by the key event, may be empty. */
input: string;
/** Modifier + named-key flags as Ink reports them. */
return?: boolean;
shift?: boolean;
ctrl?: boolean;
meta?: boolean;
backspace?: boolean;
delete?: boolean;
/** Navigation/editing keys owned by the parent App (slash-nav, history). */
tab?: boolean;
upArrow?: boolean;
downArrow?: boolean;
@@ -36,87 +40,160 @@ export interface MultilineKey {
}
export interface MultilineAction {
/** New value to set on the text buffer. `null` = unchanged. */
/** New buffer value. `null` = unchanged. */
next: string | null;
/** When `true`, the caller should fire `onSubmit(next ?? value)`. */
/** New cursor position (0..value.length). `null` = unchanged. */
cursor: number | null;
/** When `true`, fire `onSubmit(submitValue ?? value)`. */
submit: boolean;
/** When submitting, which value to submit (after any final trims). */
submitValue?: string;
}
const BACKSLASH_SUFFIX = /\\$/;
/**
* Decide what to do with a single keystroke against the current buffer.
*
* Decisions:
* Ctrl+J → insert '\n' (terminal-universal newline)
* Shift+Return → insert '\n' (works where CSI-u is on)
* Enter with "\" end → replace trailing '\' with '\n' (bash continuation)
* Enter → submit the current buffer
* Backspace/Delete → drop one char from the end (cursor-at-end model)
* Printable char(s) → append at the end
*
* We don't model an insertion cursor inside the string: always-at-end
* keeps the reducer tiny and matches how readline-in-raw-mode feels. The
* user can still edit by backspacing — for deep edits, exit and compose
* in $EDITOR.
*/
export function processMultilineKey(value: string, key: MultilineKey): MultilineAction {
// Parent App owns these keys: Tab for slash auto-complete, arrows
// for slash-nav/history, Esc for abort. Bowing out here keeps the
// text buffer from eating a stray "\t" or arrow escape sequence
// when both the parent and child useInput fire on the same event.
if (
key.tab ||
key.upArrow ||
key.downArrow ||
key.leftArrow ||
key.rightArrow ||
key.escape ||
key.pageUp ||
key.pageDown
) {
return { next: null, submit: false };
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;
}
// Reliable newline: Ctrl+J arrives as literal '\n' in key.input on
// every terminal we've checked. We also accept key.ctrl && input=='j'
// as a belt-and-braces match against terminals that normalize the
// control-char into its ASCII letter form.
// 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 { next: `${value}\n`, submit: false };
return insertAt(value, cursor, "\n");
}
if (key.return) {
// Shift+Return → newline (when terminal reports the modifier).
if (key.shift) {
return { next: `${value}\n`, submit: false };
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 };
}
// Bash-style line continuation: trailing '\' + Enter.
if (BACKSLASH_SUFFIX.test(value)) {
return { next: `${value.slice(0, -1)}\n`, submit: false };
}
// Plain Enter → submit.
return { next: null, submit: true, submitValue: value };
return { next: null, cursor: null, submit: true, submitValue: value };
}
if (key.backspace || key.delete) {
if (value.length === 0) return { next: null, submit: false };
return { next: value.slice(0, -1), submit: false };
// 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,
};
}
// Ignore bare modifier keys (ctrl/meta without accompanying printable).
if ((key.ctrl || key.meta) && key.input.length === 0) {
return { next: null, 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);
}
// Printable input (may be a multi-char paste burst — accept as-is;
// pasted newlines become part of the buffer rather than triggering
// submit on the first line).
if (key.input.length > 0 && !key.ctrl && !key.meta) {
return { next: value + key.input, submit: false };
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);
}
return { next: null, submit: false };
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);
}
+385
View File
@@ -1,8 +1,11 @@
import { spawnSync } from "node:child_process";
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 { type MemoryScope, MemoryStore } from "../../user-memory.js";
export interface SlashResult {
/** Text to display back to the user as a system/info line. */
@@ -78,6 +81,35 @@ export interface SlashContext {
* 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;
}
export interface McpServerSummary {
@@ -122,6 +154,16 @@ export const SLASH_COMMANDS: readonly SlashCommandSpec[] = [
{ 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: "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" },
@@ -141,6 +183,17 @@ export const SLASH_COMMANDS: readonly SlashCommandSpec[] = [
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",
},
];
/**
@@ -209,11 +262,17 @@ export function handleSlash(
" /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",
" /new start fresh: drop all context + clear scrollback",
@@ -301,6 +360,15 @@ export function handleSlash(
};
}
case "memory": {
return handleMemorySlash(args, ctx);
}
case "skill":
case "skills": {
return handleSkillSlash(args, ctx);
}
case "think":
case "reasoning": {
const raw = loop.scratch.reasoning;
@@ -378,6 +446,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 {
@@ -469,6 +576,7 @@ export function handleSlash(
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"}`,
@@ -477,6 +585,7 @@ export function handleSlash(
sessionLine,
];
if (pendingLine) lines.push(pendingLine);
if (planLine) lines.push(planLine);
return { info: lines.join("\n") };
}
@@ -535,6 +644,282 @@ 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.
*/
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.
+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);
}
+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);
+67 -1
View File
@@ -29,10 +29,68 @@ export type {
export { ImmutablePrefix, AppendOnlyLog, VolatileScratch } from "./memory.js";
export type { ImmutablePrefixOptions } from "./memory.js";
export {
PROJECT_MEMORY_FILE,
PROJECT_MEMORY_MAX_CHARS,
applyProjectMemory,
memoryEnabled,
readProjectMemory,
} from "./project-memory.js";
export type { ProjectMemory } from "./project-memory.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,
@@ -186,4 +244,12 @@ export type {
JSONSchema,
} from "./types.js";
export const VERSION = "0.4.3";
export {
LATEST_CACHE_TTL_MS,
LATEST_FETCH_TIMEOUT_MS,
VERSION,
compareVersions,
getLatestVersion,
isNpxInstall,
} from "./version.js";
export type { GetLatestVersionOptions } from "./version.js";
+213 -16
View File
@@ -22,6 +22,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
@@ -74,6 +81,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;
@@ -232,8 +241,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 {
@@ -254,7 +273,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);
@@ -346,7 +371,16 @@ 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;
}
@@ -404,6 +438,11 @@ export class CacheFirstLoop {
async *step(userInput: string): AsyncGenerator<LoopEvent> {
this._turn++;
this.scratch.reset();
// 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.
@@ -613,6 +652,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;
}
@@ -687,6 +736,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;
@@ -697,20 +765,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) {
@@ -883,7 +1001,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 } {
@@ -900,6 +1024,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
+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}
\`\`\`
`;
}
+11
View File
@@ -46,6 +46,17 @@ 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,
+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");
}
+71 -1
View File
@@ -17,6 +17,25 @@ export interface ToolDefinition<A = any, R = any> {
name: string;
description?: string;
parameters?: JSONSchema;
/**
* 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>;
}
@@ -42,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) };
@@ -120,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, { 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;
+6 -1
View File
@@ -77,6 +77,7 @@ export function registerFilesystemTools(
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: {
@@ -117,6 +118,7 @@ export function registerFilesystemTools(
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: {
@@ -138,6 +140,7 @@ export function registerFilesystemTools(
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: {
@@ -186,6 +189,7 @@ export function registerFilesystemTools(
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: {
@@ -243,6 +247,7 @@ export function registerFilesystemTools(
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: {
@@ -287,7 +292,7 @@ export function registerFilesystemTools(
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. This flat-string shape replaces the `{oldText, newText}[]` JSON array form that previously triggered R1 DSML hallucinations.",
"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: {
+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");
}
+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([]);
});
});
+115 -5
View File
@@ -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,6 +92,98 @@ 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", () => {
+157 -7
View File
@@ -255,11 +255,13 @@ 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 stops immediately without a follow-up API call", async () => {
@@ -415,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");
@@ -427,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 }));
@@ -448,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!);
});
});
+43
View File
@@ -223,3 +223,46 @@ describe("parseBlocks — GFM tables", () => {
}
});
});
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')");
});
});
+219 -86
View File
@@ -1,112 +1,245 @@
import { describe, expect, it } from "vitest";
import { type MultilineKey, processMultilineKey } from "../src/cli/ui/multiline-keys.js";
import {
type MultilineKey,
lineAndColumn,
processMultilineKey,
} from "../src/cli/ui/multiline-keys.js";
function key(overrides: Partial<MultilineKey> = {}): MultilineKey {
return { input: "", ...overrides };
}
describe("processMultilineKey", () => {
it("appends printable input at the end", () => {
const r = processMultilineKey("hel", key({ input: "l" }));
expect(r).toEqual({ next: "hell", submit: false });
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 a multi-char paste burst as-is", () => {
const r = processMultilineKey("", key({ input: "line1\nline2" }));
expect(r.next).toBe("line1\nline2");
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);
});
});
it("Enter on a plain buffer submits", () => {
const r = processMultilineKey("hi", key({ return: true }));
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");
expect(r.next).toBeNull();
});
it("Enter with trailing backslash converts to newline (bash-style continuation)", () => {
const r = processMultilineKey("line1\\", key({ return: true }));
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("Shift+Enter inserts a newline without submitting", () => {
const r = processMultilineKey("abc", key({ return: true, shift: true }));
expect(r.submit).toBe(false);
expect(r.next).toBe("abc\n");
});
it("Ctrl+J (ASCII LF) inserts a newline", () => {
const r = processMultilineKey("abc", key({ input: "\n" }));
expect(r.next).toBe("abc\n");
expect(r.submit).toBe(false);
});
it("Ctrl+J reported as ctrl+'j' (normalized form) also inserts a newline", () => {
const r = processMultilineKey("abc", key({ input: "j", ctrl: true }));
expect(r.next).toBe("abc\n");
expect(r.submit).toBe(false);
});
it("Backspace drops one char from the end", () => {
const r = processMultilineKey("abcd", key({ backspace: true }));
expect(r.next).toBe("abc");
});
it("Backspace on empty buffer is a no-op", () => {
const r = processMultilineKey("", key({ backspace: true }));
expect(r.next).toBeNull();
expect(r.submit).toBe(false);
});
it("Backspace can delete across newlines", () => {
const r = processMultilineKey("a\nb", key({ backspace: true }));
expect(r.next).toBe("a\n");
const r2 = processMultilineKey(r.next!, key({ backspace: true }));
expect(r2.next).toBe("a");
});
it("Delete behaves like Backspace (cursor-at-end model)", () => {
const r = processMultilineKey("xyz", key({ delete: true }));
expect(r.next).toBe("xy");
});
it("Tab is ignored (parent handles slash auto-complete)", () => {
const r = processMultilineKey("/he", key({ tab: true, input: "" }));
expect(r.next).toBeNull();
expect(r.submit).toBe(false);
});
it("Tab with '\\t' in input is still ignored", () => {
const r = processMultilineKey("x", key({ tab: true, input: "\t" }));
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("Arrow keys are ignored (parent handles slash-nav + history)", () => {
expect(processMultilineKey("x", key({ upArrow: true })).next).toBeNull();
expect(processMultilineKey("x", key({ downArrow: true })).next).toBeNull();
expect(processMultilineKey("x", key({ leftArrow: true })).next).toBeNull();
expect(processMultilineKey("x", key({ rightArrow: true })).next).toBeNull();
});
it("Escape is ignored (parent handles abort)", () => {
const r = processMultilineKey("x", key({ escape: true }));
expect(r.next).toBeNull();
});
it("Ctrl+<letter> that isn't j is dropped (no accidental text insert)", () => {
const r = processMultilineKey("x", key({ input: "c", ctrl: true }));
expect(r.next).toBeNull();
});
it("Meta (Alt) key events are dropped", () => {
const r = processMultilineKey("x", key({ input: "a", meta: true }));
expect(r.next).toBeNull();
});
it("Plain return on an empty buffer still submits (empty message case handled upstream)", () => {
const r = processMultilineKey("", key({ return: true }));
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/);
});
});
});
+18
View File
@@ -76,4 +76,22 @@ describe("ToolCallRepair pipeline", () => {
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);
});
});
+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);
});
});
+151 -1
View File
@@ -1,4 +1,7 @@
import { describe, expect, it, vi } from "vitest";
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,
@@ -459,6 +462,7 @@ describe("handleSlash", () => {
"branch",
"mcp",
"tool",
"memory",
"think",
"retry",
"compact",
@@ -469,6 +473,8 @@ describe("handleSlash", () => {
"discard",
"undo",
"commit",
"plan",
"apply-plan",
]) {
expect(names, `registry missing /${required}`).toContain(required);
}
@@ -578,4 +584,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/);
});
});
});
+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");
});
});
+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;
}
});
});