mirror of
https://github.com/esengine/DeepSeek-Reasonix.git
synced 2026-11-07 10:45:59 -10:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
50c757d203 | ||
|
|
50670ee41b | ||
|
|
70e0ad1aba | ||
|
|
1de2349350 | ||
|
|
98f19d1d47 | ||
|
|
d6bb4054dc | ||
|
|
9e3c62ed1e | ||
|
|
ee274035c6 | ||
|
|
500868b490 | ||
|
|
7aa71324c4 | ||
|
|
e530cab7a7 | ||
|
|
bf45687414 | ||
|
|
f28d27290c | ||
|
|
5453fc6dc3 | ||
|
|
94a3c9d56e | ||
|
|
4cb445b280 | ||
|
|
918ed2ca50 | ||
|
|
ebc967be35 | ||
|
|
2e64d63c8b | ||
|
|
6d8a2c596c | ||
|
|
f6931481ba | ||
|
|
15b0cfc894 | ||
|
|
331e01fda1 | ||
|
|
877a9ee03b | ||
|
|
a4ff99236b | ||
|
|
c3d327e27f | ||
|
|
acb3a3ffee | ||
|
|
7e1695f945 | ||
|
|
248dd134ba | ||
|
|
e5a75119cb | ||
|
|
11155add8a | ||
|
|
f82f93559b | ||
|
|
5a7d16c24f | ||
|
|
292e51f0c2 | ||
|
|
c5b0906576 | ||
|
|
30ca814809 | ||
|
|
000e7c3ac0 | ||
|
|
a22355a2ab | ||
|
|
39a4e137dc | ||
|
|
0383255de2 | ||
|
|
b2a50d50f5 | ||
|
|
e486a8e23a | ||
|
|
a4c1e9b478 | ||
|
|
9fdbdf738b | ||
|
|
f3f844b3dc | ||
|
|
d65ca4f67f | ||
|
|
ee577995d0 | ||
|
|
e3d6fe3a86 | ||
|
|
bfc4cd38ee | ||
|
|
0ccc419d0d | ||
|
|
7542aca687 | ||
|
|
1e906bb577 | ||
|
|
a8c367ad0c | ||
|
|
2d35cab39e | ||
|
|
874d7df2f7 | ||
|
|
4d39744d99 | ||
|
|
74da4f2a92 | ||
|
|
36f6d245f9 | ||
|
|
a44c23c0a8 | ||
|
|
337ded3839 | ||
|
|
8ec6c630bd | ||
|
|
a787272ceb | ||
|
|
0ca16d6e2d | ||
|
|
ecf2ea372b | ||
|
|
335de43db5 | ||
|
|
af077ddb24 | ||
|
|
84ea648c84 | ||
|
|
2d95c5787d | ||
|
|
19a2b8d2be | ||
|
|
ca27ca50bf | ||
|
|
d4615d6e76 | ||
|
|
9eff2e2cfc | ||
|
|
c2f8e9b734 | ||
|
|
d52599ec44 | ||
|
|
3c8669577d | ||
|
|
3fee4e6883 | ||
|
|
41d21f7cea | ||
|
|
715d8b5950 | ||
|
|
911f043db8 | ||
|
|
ce85319c9b | ||
|
|
2a9a9b386b | ||
|
|
e3cfbb58dd | ||
|
|
becaf487e8 | ||
|
|
6111d8f621 | ||
|
|
d8ba9f9669 | ||
|
|
e409e9d8d9 | ||
|
|
4d21ca4c4c | ||
|
|
1ccc1d7e67 | ||
|
|
fd344986e8 | ||
|
|
6ceb73d367 | ||
|
|
dee96f66a2 | ||
|
|
6b4d8652e4 | ||
|
|
5f7d8f238a | ||
|
|
dc38c765e8 | ||
|
|
59bd38b1aa | ||
|
|
3484c04133 | ||
|
|
7075608ddc | ||
|
|
27a32b7b94 | ||
|
|
1391534f6c | ||
|
|
169d66d46a | ||
|
|
2836b5d406 | ||
|
|
d0bd6852c1 | ||
|
|
cb2f2a550b | ||
|
|
e472f4cb79 | ||
|
|
14887264bb | ||
|
|
63ced2fa5b | ||
|
|
461e736cbc | ||
|
|
d932c50ab3 | ||
|
|
b4c461c6ad | ||
|
|
2f4e28b7cb | ||
|
|
5f715d05ee | ||
|
|
b662c63894 | ||
|
|
e793c7d59d | ||
|
|
7cd862194a | ||
|
|
407793c99e | ||
|
|
5e124cec36 | ||
|
|
7fce6e650c | ||
|
|
5941043489 | ||
|
|
f142f8874d | ||
|
|
fb5977743c | ||
|
|
26b50e9242 | ||
|
|
7233eddced | ||
|
|
3a92ba2787 | ||
|
|
6307b92af2 | ||
|
|
2e42ae53aa | ||
|
|
5ff0ef4535 | ||
|
|
ce963be2e2 | ||
|
|
e5357f0df5 | ||
|
|
c148b342fc | ||
|
|
74e796b1c6 | ||
|
|
c1965b1d1e |
No files matched your search
@@ -37,3 +37,13 @@ jobs:
|
||||
|
||||
- name: Build (tsup)
|
||||
run: npm run build
|
||||
|
||||
# Smoke-test the bench harnesses themselves. --dry skips all LLM
|
||||
# calls, so this catches wiring regressions (task factories, CLI
|
||||
# parsing, file IO, checker determinism) without needing a
|
||||
# DEEPSEEK_API_KEY in CI.
|
||||
- name: τ-bench harness dry-run
|
||||
run: npx tsx benchmarks/tau-bench/runner.ts --dry --out /tmp/tau-dry.json
|
||||
|
||||
- name: Harvest-bench harness dry-run
|
||||
run: npx tsx benchmarks/harvest/runner.ts --dry --out /tmp/harvest-dry.json
|
||||
@@ -22,3 +22,5 @@ sessions/
|
||||
!benchmarks/tau-bench/transcripts/
|
||||
!benchmarks/tau-bench/transcripts/*.jsonl
|
||||
.turbo/
|
||||
# Local-only Claude Code settings — personal overrides, never committed.
|
||||
.claude/settings.local.json
|
||||
+2448
File diff suppressed because it is too large.
Load diff
@@ -1,3 +1,11 @@
|
||||
<p align="center">
|
||||
<img src="docs/logo.svg" alt="Reasonix — DeepSeek-native agent framework" width="640"/>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<em>Cache-first agent loop for DeepSeek V4 (flash + pro) — Ink TUI, MCP first-class, no LangChain.</em>
|
||||
</p>
|
||||
|
||||
# Reasonix
|
||||
|
||||
[](https://www.npmjs.com/package/reasonix)
|
||||
@@ -6,147 +14,630 @@
|
||||
[](https://www.npmjs.com/package/reasonix)
|
||||
[](./package.json)
|
||||
|
||||
**The DeepSeek-native agent framework.** TypeScript. Ink TUI. No LangChain.
|
||||
|
||||
Reasonix is not another generic agent wrapper. Every abstraction is justified
|
||||
by a DeepSeek-specific property — dirt-cheap tokens, R1 reasoning traces,
|
||||
automatic prefix caching, JSON mode. Generic frameworks treat DeepSeek as
|
||||
"OpenAI with a different base URL" and leave these advantages on the table.
|
||||
Reasonix leans into them.
|
||||
|
||||
```bash
|
||||
npx reasonix chat # first run prompts for your DeepSeek key
|
||||
# inside the TUI, type /help for everything else
|
||||
```
|
||||
|
||||
No flag soup. All feature toggles live behind slash commands in the TUI.
|
||||
**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 |
|
||||
|---|---|---|
|
||||
| **Cache-First Loop** | Immutable prefix + append-only log = prefix byte-stable across turns → DeepSeek's automatic prefix cache hits at 70–95% | always on |
|
||||
| **R1 Thought Harvesting** | Parses `reasoning_content` into typed `{ subgoals, hypotheses, uncertainties, rejectedPaths }` via a cheap V3 call | `--harvest` |
|
||||
| **Self-Consistency Branching** | Runs N parallel samples at spread temperatures; picks the one with the fewest flagged uncertainties | `--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 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>
|
||||
|
||||
**2. Point it at a project.** No install needed.
|
||||
|
||||
```bash
|
||||
cd my-project
|
||||
npx reasonix code
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
**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.
|
||||
|
||||
---
|
||||
|
||||
## Why not just use LangChain?
|
||||
## `reasonix code` — pair programmer in your terminal
|
||||
|
||||
Even on the default `fast` preset (no harvest, no branching), Reasonix bakes
|
||||
in five DeepSeek-specific defences that generic agent frameworks leave to you:
|
||||
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.
|
||||
|
||||
| | 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 | ✅ | ❌ |
|
||||
### Walkthrough: explore before editing
|
||||
|
||||
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.
|
||||
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:
|
||||
|
||||
## Validated numbers
|
||||
|
||||
**τ-bench-lite** — 8 multi-turn tool-use tasks, same tools / same prompt
|
||||
on both sides, sole variable is prefix stability. Measured on live
|
||||
DeepSeek `deepseek-chat`:
|
||||
|
||||
| metric | baseline (cache-hostile) | Reasonix | delta |
|
||||
|---|---:|---:|---:|
|
||||
| runs | 8 | 8 | — |
|
||||
| **cache hit** | 43.9% | **94.3%** | **+50.3pp** |
|
||||
| cost / task | $0.002783 | $0.001621 | **−42% (×0.58)** |
|
||||
| vs Claude Sonnet 4.6 (token-count estimate) | — | — | **~96% cheaper** |
|
||||
| pass rate | 100% (8/8) | 88% (7/8) | 1 refusal-task predicate too strict (see [report.md][r]) |
|
||||
|
||||
**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
|
||||
```
|
||||
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 写子路径,最后 …
|
||||
```
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
Full 16-run report: [`benchmarks/tau-bench/report.md`][r]. Reproduce
|
||||
with your own API key: `npx tsx benchmarks/tau-bench/runner.ts`.
|
||||
### Plan mode — review before executing
|
||||
|
||||
[r]: ./benchmarks/tau-bench/report.md
|
||||
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.
|
||||
|
||||
### Prompt prefixes — `!cmd` and `@path`
|
||||
|
||||
Two inline shortcuts that don't need a slash:
|
||||
|
||||
**`!<cmd>` — run a shell command in the sandbox and feed it to the
|
||||
model.** Typed at the prompt, like bash. Output lands in the visible
|
||||
log AND in the session so the model's next turn reasons about it:
|
||||
|
||||
```
|
||||
reasonix code › !git status --short
|
||||
▸ M src/users.ts
|
||||
▸ M src/users.test.ts
|
||||
|
||||
reasonix code › 把这两个文件的改动说明一下
|
||||
assistant
|
||||
▸ tool<read_file> → src/users.ts, src/users.test.ts
|
||||
▸ …
|
||||
```
|
||||
|
||||
No allowlist gate — user-typed shell = explicit consent. 60s timeout,
|
||||
32k char cap, survives session resume since 0.5.14.
|
||||
|
||||
**`@path/to/file` — inline a file under "Referenced files."** Start
|
||||
typing `@` and a picker appears (↑/↓ navigate, Tab/Enter to insert).
|
||||
Good for "what does @src/users.ts do?" without making the model
|
||||
`read_file` it first. Sandboxed: relative paths only, no `..` escape,
|
||||
64KB per-file cap. Recent files rank higher.
|
||||
|
||||
### `/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 reasoning for the last turn
|
||||
(thinking-mode models: v4-flash / v4-pro / reasoner alias).
|
||||
- `/undo` — roll back the last applied edit batch.
|
||||
- `/new` — start fresh in the same directory without losing the
|
||||
session file.
|
||||
- `/effort high` — step down from the default `max` agent-class
|
||||
reasoning_effort for cheaper/faster turns on simple tasks.
|
||||
- `npx reasonix code --preset max` — v4-pro + 3-way self-consistency
|
||||
branching for gnarly refactors.
|
||||
- `npx reasonix code src/` — narrower sandbox (only `src/` is
|
||||
writable).
|
||||
- `npx reasonix code --no-session` — ephemeral; nothing saved.
|
||||
|
||||
### `reasonix stats` — how much did you actually save?
|
||||
|
||||
Every turn `reasonix chat|code|run` runs appends a compact record
|
||||
(tokens + cost + what Claude Sonnet 4.6 would have charged) to
|
||||
`~/.reasonix/usage.jsonl`. `reasonix stats` with no args rolls that
|
||||
log into today / week / month / all-time windows:
|
||||
|
||||
```
|
||||
Reasonix usage — /Users/you/.reasonix/usage.jsonl
|
||||
|
||||
turns cache hit cost (USD) vs Claude saved
|
||||
----------------------------------------------------------------------
|
||||
today 8 95.1% $0.004821 $0.1348 96.4%
|
||||
week 34 93.8% $0.023104 $0.6081 96.2%
|
||||
month 127 94.2% $0.081530 $2.1452 96.2%
|
||||
all-time 342 94.0% $0.210881 $5.8934 96.4%
|
||||
```
|
||||
|
||||
Privacy: only tokens, costs, and the session name you chose land
|
||||
in the file. No prompts, no completions, no tool arguments.
|
||||
`reasonix stats <transcript>` keeps the old per-file summary
|
||||
(assistant turns + tool calls) for scripts that already use it.
|
||||
|
||||
### Staying current
|
||||
|
||||
The panel header shows the running version next to `Reasonix` (e.g.
|
||||
`Reasonix v0.5.21 · deepseek-v4-pro · harvest · max …`, the trailing
|
||||
`max` is the reasoning-effort badge — `/effort high` to step down).
|
||||
A quiet 24-hour background check against
|
||||
the npm registry surfaces a yellow `update: X.Y.Z` on the right side
|
||||
of the same row when a newer version has been published. No blocking,
|
||||
no nagging — the check runs once per day max and is silent on failure
|
||||
(offline, firewall, etc.).
|
||||
|
||||
```bash
|
||||
reasonix update # print current vs latest, run `npm i -g reasonix@latest`
|
||||
reasonix update --dry-run # print the plan without running anything
|
||||
```
|
||||
|
||||
Running via `npx`? The command detects that and prints a
|
||||
cache-refresh hint instead — npx picks up the newest version on
|
||||
its next invocation automatically.
|
||||
|
||||
### Project conventions — `REASONIX.md`
|
||||
|
||||
Drop a `REASONIX.md` in the project root and its contents are pinned
|
||||
into the system prompt every launch. Committable team memory — house
|
||||
conventions, domain glossary, things the model keeps forgetting:
|
||||
|
||||
```bash
|
||||
cat > REASONIX.md <<'EOF'
|
||||
# Notes for Reasonix
|
||||
- Use snake_case for new Python modules; legacy camelCase modules keep their style.
|
||||
- `cargo check` is in the auto-run allowlist; full `cargo test` needs confirmation.
|
||||
- The `api/` dir mirrors `backend/` — keep schemas in sync.
|
||||
EOF
|
||||
```
|
||||
|
||||
Re-launch (or `/new`) to pick it up; the prefix is hashed once per
|
||||
session to keep the DeepSeek cache warm. `/memory` prints what's
|
||||
currently pinned. `REASONIX_MEMORY=off` disables every memory source
|
||||
for CI / offline repro.
|
||||
|
||||
### User memory — `~/.reasonix/memory/`
|
||||
|
||||
A second, **private per-user** memory layer lives under your home
|
||||
directory. Unlike `REASONIX.md` it's never committed, and the model
|
||||
can write to it itself via the `remember` tool. Two scopes:
|
||||
|
||||
- `~/.reasonix/memory/global/` — cross-project (your preferences,
|
||||
tooling).
|
||||
- `~/.reasonix/memory/<project-hash>/` — scoped to one sandbox root
|
||||
in `reasonix code` (decisions, local facts, per-repo shortcuts).
|
||||
|
||||
Each scope keeps an always-loaded `MEMORY.md` index of one-liners
|
||||
plus zero or more `<name>.md` detail files (loaded on demand via
|
||||
`recall_memory`). Writes land immediately; pinning into the system
|
||||
prompt takes effect on next `/new` or launch so the cache prefix
|
||||
stays stable for the current session.
|
||||
|
||||
```
|
||||
reasonix code › 我用 bun 而不是 npm,请以后都用 bun 跑构建
|
||||
|
||||
assistant
|
||||
▸ tool<remember> → project/bun_build saved
|
||||
"Build command on this machine is `bun run build`"
|
||||
```
|
||||
|
||||
**Slash**: `/memory` · `/memory list` · `/memory show <name>` ·
|
||||
`/memory forget <name>` · `/memory clear <scope> confirm`.
|
||||
**Model tools**: `remember(type, scope, name, description, content)` ·
|
||||
`forget(scope, name)` · `recall_memory(scope, name)`.
|
||||
|
||||
Project scope is only available inside `reasonix code` (needs a real
|
||||
sandbox root to hash); plain `reasonix` gets the global scope only.
|
||||
|
||||
### Skills — user-authored prompt packs
|
||||
|
||||
Skills are prose instruction blocks you drop on disk. Reasonix pins
|
||||
their names + one-line descriptions into the system prompt; the
|
||||
model can call `run_skill({name: "..."})` on its own when a match
|
||||
fits, or you can type `/skill <name> [args]` to run one manually.
|
||||
|
||||
Two scopes, same layout as user memory:
|
||||
|
||||
- `<project>/.reasonix/skills/` — per-project skills (commit them to
|
||||
share with your team, or add to `.gitignore` for personal drafts).
|
||||
- `~/.reasonix/skills/` — global skills available everywhere.
|
||||
|
||||
Either layout works: `<name>/SKILL.md` (preferred — can bundle
|
||||
additional assets alongside) or flat `<name>.md`.
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: review
|
||||
description: Review uncommitted changes and flag risks
|
||||
---
|
||||
|
||||
Run `git diff` on staged and unstaged changes. Summarize what each
|
||||
hunk does, call out potential regressions, and list files that might
|
||||
need additional tests. Don't propose edits unless I ask.
|
||||
```
|
||||
|
||||
Use it:
|
||||
|
||||
```
|
||||
reasonix code › /skill review
|
||||
▸ running skill: review
|
||||
assistant
|
||||
▸ tool<run_command> → git diff --cached
|
||||
▸ 3 改动,1 个需要回归测试 …
|
||||
```
|
||||
|
||||
Or let the model pick autonomously — because the skill's name +
|
||||
description are pinned in the prefix, asking "帮我看下未提交的改动有没
|
||||
有风险" triggers `run_skill({name: "review"})` without you typing the
|
||||
slash command.
|
||||
|
||||
**Slash**: `/skill` (list) · `/skill show <name>` · `/skill <name>
|
||||
[args]` (inject body as user turn).
|
||||
|
||||
**Deliberately not tied** to any other client's directory convention
|
||||
(`.claude/skills`, etc.) — Reasonix is model-agnostic at the
|
||||
conversation layer. Any SKILL.md you author works; the body is
|
||||
prose, so skills authored for other tools usually port over unchanged
|
||||
(Reasonix's tool names differ — `filesystem` / `shell` / `web` — but
|
||||
the model reads the instructions and picks our equivalents).
|
||||
|
||||
### Hooks — automate around tool calls and turns
|
||||
|
||||
Drop a `settings.json` under `.reasonix/` (project or `~/`) and
|
||||
Reasonix will fire shell commands at four well-known points in
|
||||
the loop: before a tool runs, after a tool returns, before your
|
||||
prompt reaches the model, and after the turn ends.
|
||||
|
||||
```json
|
||||
// <project>/.reasonix/settings.json ← committable
|
||||
// ~/.reasonix/settings.json ← per-user
|
||||
{
|
||||
"hooks": {
|
||||
"PreToolUse": [{ "match": "edit_file|write_file", "command": "bun scripts/guard.ts" }],
|
||||
"PostToolUse": [{ "match": "edit_file", "command": "biome format --write" }],
|
||||
"UserPromptSubmit": [{ "command": "echo $(date +%s) >> ~/.reasonix/prompts.log" }],
|
||||
"Stop": [{ "command": "bun test --run", "timeout": 60000 }]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Each hook is a shell command. Reasonix invokes it with stdin = a
|
||||
JSON envelope describing the event:
|
||||
|
||||
```json
|
||||
{ "event": "PreToolUse", "cwd": "/path/to/project",
|
||||
"toolName": "edit_file", "toolArgs": { "path": "src/x.ts", "..." } }
|
||||
```
|
||||
|
||||
Exit code drives the decision:
|
||||
|
||||
- **0** — pass; loop continues normally
|
||||
- **2** — block (only on `PreToolUse` / `UserPromptSubmit`); the
|
||||
hook's stderr becomes the synthetic tool result the model sees,
|
||||
or the prompt is dropped entirely
|
||||
- **anything else** — warn; loop continues, stderr renders as a
|
||||
yellow row inline
|
||||
|
||||
`match` is anchored regex on the tool name; `*` or omitted matches
|
||||
every tool. Project hooks fire before global hooks. Default
|
||||
timeouts: 5s for blocking events, 30s for logging events; per-hook
|
||||
`timeout` overrides.
|
||||
|
||||
**Slash**: `/hooks` (list active hooks) · `/hooks reload` (re-read
|
||||
`settings.json` from disk without losing your session).
|
||||
|
||||
### Staying current from inside the TUI
|
||||
|
||||
`/update` inside a running session shows your current version, the
|
||||
last-resolved latest version (from the quiet 24h background check),
|
||||
and the shell command to run. The slash does *not* spawn
|
||||
`npm install` — stdio:inherit into a running Ink renderer corrupts
|
||||
the display. Exit the session and run `reasonix update` in a
|
||||
fresh shell when you actually want to install.
|
||||
|
||||
---
|
||||
|
||||
## Usage
|
||||
## `reasonix` — also works as general chat
|
||||
|
||||
### CLI
|
||||
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 chat # auto-saves to session 'default'; resumes next time
|
||||
npx reasonix chat --session work # use a different named session
|
||||
npx reasonix chat --no-session # ephemeral — nothing persisted
|
||||
npx reasonix run "ask anything" # one-shot, streams to stdout
|
||||
npx reasonix stats session.jsonl # quick summary of a transcript
|
||||
npx reasonix replay chat.jsonl # pretty-print a transcript + rebuild cost/cache offline
|
||||
npx reasonix diff a.jsonl b.jsonl --md diff.md # compare two transcripts: cache/cost delta + first divergence
|
||||
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
|
||||
```
|
||||
|
||||
Sessions live as JSONL under `~/.reasonix/sessions/<name>.jsonl` — every
|
||||
turn's message log is appended atomically, so killing the CLI never loses
|
||||
context. Inside the TUI: `/sessions` to list, `/forget` to delete the
|
||||
current one.
|
||||
|
||||
### Inside the chat — slash commands
|
||||
|
||||
A command strip runs under the input box so you don't have to memorize
|
||||
anything. Type `/help` for the full list. The biggest shortcut:
|
||||
|
||||
```
|
||||
/preset fast deepseek-chat, no harvest, no branch (default)
|
||||
/preset smart reasoner + harvest (~10x cost)
|
||||
/preset max reasoner + harvest + branch 3 (~30x cost, slowest)
|
||||
```
|
||||
|
||||
One-tap switch between fast daily driver, careful thinker, and max-quality
|
||||
self-consistency. Individual knobs are available too:
|
||||
|
||||
```
|
||||
/status show current model / harvest / branch / stream
|
||||
/model <id> deepseek-chat or deepseek-reasoner
|
||||
/harvest [on|off] Pillar 2 — parse R1 reasoning into typed plan state
|
||||
/branch <N|off> run N parallel samples per turn, pick most confident
|
||||
/clear clear displayed history (log is kept)
|
||||
/exit quit
|
||||
```
|
||||
|
||||
The top panel shows active flags live: `· harvest · branch3` appear next to
|
||||
the model once enabled.
|
||||
|
||||
### Flags (for automation / CI)
|
||||
|
||||
The same knobs are also available as CLI flags if you're scripting:
|
||||
Bridge your own MCP servers on the fly:
|
||||
|
||||
```bash
|
||||
npx reasonix chat -m deepseek-reasoner --harvest --branch 3 --transcript session.jsonl
|
||||
npx reasonix \
|
||||
--mcp "fs=npx -y @modelcontextprotocol/server-filesystem /tmp/safe" \
|
||||
--mcp "kb=https://mcp.example.com/sse"
|
||||
```
|
||||
|
||||
### Library
|
||||
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-v4-flash`, `deepseek-v4-pro`, plus `deepseek-chat` / `deepseek-reasoner` compat aliases) |
|
||||
| `/models` | list live models from DeepSeek `/models` endpoint |
|
||||
| `/harvest [on\|off]` | toggle R1 plan-state extraction |
|
||||
| `/branch <N\|off>` | run N parallel samples per turn, pick best (N ≥ 2) |
|
||||
| `/effort <high\|max>` | reasoning_effort cap — `max` is the agent default, `high` is cheaper/faster |
|
||||
| `/think` | dump the last turn's full thinking-mode reasoning |
|
||||
|
||||
**Context & tools**
|
||||
|
||||
| command | what it does |
|
||||
|---|---|
|
||||
| `/mcp` | list attached MCP servers and their tools / resources / prompts |
|
||||
| `/resource [uri]` | browse + read MCP resources (no arg → list URIs; `<uri>` → fetch) |
|
||||
| `/prompt [name]` | browse + fetch MCP prompts |
|
||||
| `/tool [N]` | dump the Nth tool call's full output (1 = latest) |
|
||||
| `/compact [tokens]` | shrink oversized tool results in the log (default 4000 tokens/result) |
|
||||
| `/context` | break down where context tokens are going (system / tools / log) |
|
||||
| `/stats` | cross-session cost dashboard (today / week / month / all-time) |
|
||||
| `/keys` | keyboard shortcuts + prompt prefixes (`!` / `@` / `/`) cheatsheet |
|
||||
|
||||
**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 1M-token window (V4 flash + pro) 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 # rebuild cost/cache from a transcript
|
||||
npx reasonix diff a.jsonl b.jsonl --md # compare two transcripts
|
||||
npx reasonix mcp list # curated MCP catalog
|
||||
npx reasonix mcp inspect <spec> # probe a single MCP server
|
||||
npx reasonix sessions # list saved sessions
|
||||
```
|
||||
|
||||
Common flags:
|
||||
|
||||
```bash
|
||||
--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)
|
||||
```
|
||||
|
||||
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 {
|
||||
@@ -178,7 +669,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?")) {
|
||||
@@ -187,26 +678,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.
|
||||
|
||||
On first run the CLI prompts for your DeepSeek API key and saves it to
|
||||
`~/.reasonix/config.json`. Alternatives:
|
||||
---
|
||||
|
||||
## 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-... # env var (wins over config file)
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
@@ -218,15 +765,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 (89 tests)
|
||||
npm test # vitest (1007 tests)
|
||||
npm run lint # biome
|
||||
npm run typecheck # tsc --noEmit
|
||||
```
|
||||
|
||||
See [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) for internals.
|
||||
|
||||
---
|
||||
|
||||
## License
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
# Harvest eval harness (Pillar 2)
|
||||
|
||||
Measures Pillar 2 (R1 Thought Harvesting) the same way `tau-bench/`
|
||||
measures Pillar 1 (Cache-First Loop): isolate one variable, produce
|
||||
numbers anyone can reproduce.
|
||||
|
||||
## What's different from τ-bench-lite?
|
||||
|
||||
Deliberately different task shape:
|
||||
|
||||
| | τ-bench-lite | harvest-bench |
|
||||
|---|---|---|
|
||||
| task style | multi-turn tool-use | single-turn reasoning |
|
||||
| user simulator | yes (LLM) | no |
|
||||
| DB state | yes | no |
|
||||
| checker | DB-predicate | regex + set/value compare |
|
||||
| target | Pillar 1 | Pillar 2 |
|
||||
| model | deepseek-chat (default) | deepseek-reasoner (only R1 has `reasoning_content` for harvest to work on) |
|
||||
|
||||
The two harnesses answer different questions:
|
||||
|
||||
- **τ-bench-lite**: *"Does Cache-First actually cut cost on real tool-use
|
||||
workflows?"* (yes — 47.7pp cache, −39% cost on 48-run data.)
|
||||
- **harvest-bench**: *"Does the extra V3 harvest call add measurable
|
||||
value above plain R1?"* (TBD — run it to find out.)
|
||||
|
||||
## Modes
|
||||
|
||||
Three modes isolate one variable each:
|
||||
|
||||
| mode | model | harvest | what it measures |
|
||||
|---|---|---|---|
|
||||
| `baseline` | deepseek-chat | off | floor reference — V3 at its best |
|
||||
| `reasoner` | deepseek-reasoner | off | raw R1 gain over V3 on reasoning |
|
||||
| `reasoner-harvest` | deepseek-reasoner | on | R1 + the extra V3 harvest call |
|
||||
|
||||
Deltas:
|
||||
|
||||
- `baseline → reasoner` answers "is R1 worth the price on these
|
||||
problems?"
|
||||
- `reasoner → reasoner-harvest` answers "is the harvest call worth
|
||||
its incremental cost?"
|
||||
|
||||
## Quickstart
|
||||
|
||||
```bash
|
||||
# Dry-run — no API, smoke-test the wiring
|
||||
npx tsx benchmarks/harvest/runner.ts --dry
|
||||
|
||||
# Full run (live DeepSeek, costs ~$0.20-0.60 for 6 tasks × 3 modes × 1 repeat)
|
||||
export DEEPSEEK_API_KEY=sk-...
|
||||
npx tsx benchmarks/harvest/runner.ts
|
||||
|
||||
# Tighter run with 3 repeats (~$0.60-2.00)
|
||||
npx tsx benchmarks/harvest/runner.ts --repeats 3
|
||||
|
||||
# Only the hard tasks (skip the easy floor)
|
||||
npx tsx benchmarks/harvest/runner.ts --task pseudoprime_base2
|
||||
npx tsx benchmarks/harvest/runner.ts --task derangements_d7
|
||||
npx tsx benchmarks/harvest/runner.ts --task euler_quadratic_break
|
||||
|
||||
# Bump per-call timeout (reasoner + harvest occasionally blow past the 120s default)
|
||||
npx tsx benchmarks/harvest/runner.ts --timeout 600
|
||||
|
||||
# Per-run transcripts so you can reasonix replay / diff them
|
||||
npx tsx benchmarks/harvest/runner.ts --repeats 3 --transcripts-dir transcripts/
|
||||
|
||||
# Render report
|
||||
npx tsx benchmarks/harvest/report.ts benchmarks/harvest/results-*.json
|
||||
```
|
||||
|
||||
## Tasks (v0.3 seed)
|
||||
|
||||
Split into two bands:
|
||||
|
||||
**Easy band** — V3 chat solves these, so baseline has a real pass rate and the bench has a reference floor.
|
||||
|
||||
| id | shape | why |
|
||||
|---|---|---|
|
||||
| `mod7_list` | number theory, 29-element list | R1 often tries enumeration first, then reaches for modular arithmetic — clean rejectedPaths signal |
|
||||
| `flips_until_3heads` | probability, single integer | classic recurrence; R1 either derives or recalls, harvest should see hypotheses diverge |
|
||||
| `three_hats` | logic puzzle, one-word answer | pure deduction chain, tests harvest's ability to extract the nested reasoning |
|
||||
|
||||
**Hard band** — picked specifically for known V3 failure modes. If R1 systematically beats V3 on these, and harvest further beats R1-only, we have our Pillar 2 story.
|
||||
|
||||
| id | shape | why V3 tends to fail |
|
||||
|---|---|---|
|
||||
| `pseudoprime_base2` | smallest Fermat pseudoprime to base 2 = **341** | V3 often answers 561 (Carmichael) or some other composite it remembers — R1 actually checks 2^n mod n |
|
||||
| `derangements_d7` | D_7 = **1854** | V3 approximates via n!/e and rounds wrong, or recalls D_6/D_8; R1 uses the recurrence D_n=(n−1)(D_{n−1}+D_{n−2}) |
|
||||
| `euler_quadratic_break` | smallest n where n²+n+41 is composite = **40** | V3 frequently confuses with n²−n+41 (first fails at 41); R1 checks small n systematically |
|
||||
|
||||
Adding a new task: see `tasks.ts`. Any checker that's deterministic is
|
||||
fair game — extract numeric/list/text with regex, compare with set
|
||||
equality or string matching.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- **No LLM-as-judge.** Brittle and expensive; defeats the point of a
|
||||
reproducible bench. If a checker is too hard to write deterministically,
|
||||
the task doesn't belong here.
|
||||
- **No tool-use tasks.** Those live in `tau-bench/`. Different story.
|
||||
- **No multi-turn.** v0.3 harness is single-turn Q/A. Multi-turn reasoning
|
||||
eval is separate scope.
|
||||
- **No benchmark-data cherry-picking.** When results come in, we publish
|
||||
them whether they validate Pillar 2 or not. "harvest didn't help on
|
||||
these 3 tasks" is still useful information.
|
||||
@@ -0,0 +1,82 @@
|
||||
# Reasonix harvest eval (Pillar 2)
|
||||
|
||||
**Date:** 2026-04-21T16:44:21.011Z
|
||||
**Tasks:** 6 · repeats × 1 · modes: baseline, reasoner, reasoner-harvest
|
||||
**Reasonix version:** 0.2.2
|
||||
|
||||
## Summary by mode
|
||||
|
||||
| mode | runs | pass rate | cache hit | cost / run | harvest turns | subgoals | uncertainties |
|
||||
|---|---:|---:|---:|---:|---:|---:|---:|
|
||||
| baseline | 6 | 100% | 39.5% | $0.001371 | 0.0 | 0.0 | 0.0 |
|
||||
| reasoner | 6 | 100% | 74.2% | $0.004170 | 0.0 | 0.0 | 0.0 |
|
||||
| reasoner-harvest | 6 | 83% | 61.6% | $0.003304 | 0.8 | 2.8 | 1.3 |
|
||||
|
||||
## Deltas
|
||||
|
||||
- **baseline → reasoner**
|
||||
- pass rate: 0pp
|
||||
- cost: ×3.04 (each run costs more)
|
||||
- harvest signal / run: 0.0 subgoals, 0.0 uncertainties
|
||||
|
||||
- **baseline → reasoner-harvest**
|
||||
- pass rate: -17pp
|
||||
- cost: ×2.41 (each run costs more)
|
||||
- harvest signal / run: 2.8 subgoals, 1.3 uncertainties
|
||||
|
||||
## Per-task breakdown
|
||||
|
||||
| task | mode | rep | verdict | cache | cost | sg | un | note |
|
||||
|---|---|---:|:---:|---:|---:|---:|---:|---|
|
||||
| mod7_list | baseline | 1 | ✅ | 86.5% | $0.001361 | 0 | 0 | |
|
||||
| mod7_list | reasoner | 1 | ✅ | 86.5% | $0.004797 | 0 | 0 | |
|
||||
| mod7_list | reasoner-harvest | 1 | ✅ | 86.5% | $0.003045 | 4 | 2 | |
|
||||
| flips_until_3heads | baseline | 1 | ✅ | 92.8% | $0.001198 | 0 | 0 | |
|
||||
| flips_until_3heads | reasoner | 1 | ✅ | 92.8% | $0.002830 | 0 | 0 | |
|
||||
| flips_until_3heads | reasoner-harvest | 1 | ✅ | 92.8% | $0.001691 | 4 | 0 | |
|
||||
| three_hats | baseline | 1 | ✅ | 57.7% | $0.001514 | 0 | 0 | |
|
||||
| three_hats | reasoner | 1 | ✅ | 57.7% | $0.009340 | 0 | 0 | |
|
||||
| three_hats | reasoner-harvest | 1 | ✅ | 57.7% | $0.009651 | 3 | 2 | |
|
||||
| pseudoprime_base2 | baseline | 1 | ✅ | 0.0% | $0.001894 | 0 | 0 | |
|
||||
| pseudoprime_base2 | reasoner | 1 | ✅ | 75.3% | $0.003128 | 0 | 0 | |
|
||||
| pseudoprime_base2 | reasoner-harvest | 1 | ❌ | 0.0% | $0.000000 | 0 | 0 | This operation was aborted |
|
||||
| derangements_d7 | baseline | 1 | ✅ | 0.0% | $0.001273 | 0 | 0 | |
|
||||
| derangements_d7 | reasoner | 1 | ✅ | 71.9% | $0.003492 | 0 | 0 | |
|
||||
| derangements_d7 | reasoner-harvest | 1 | ✅ | 71.9% | $0.002843 | 3 | 2 | |
|
||||
| euler_quadratic_break | baseline | 1 | ✅ | 0.0% | $0.000985 | 0 | 0 | |
|
||||
| euler_quadratic_break | reasoner | 1 | ✅ | 61.0% | $0.001431 | 0 | 0 | |
|
||||
| euler_quadratic_break | reasoner-harvest | 1 | ✅ | 61.0% | $0.002594 | 3 | 2 | |
|
||||
|
||||
## Scope
|
||||
|
||||
Unlike τ-bench-lite, these tasks are single-turn reasoning problems (no user simulator, no DB, no tool calls). Checkers are deterministic — regex + set / value compare, never an LLM judge. The point is to isolate whether the Pillar 2 harvest step adds measurable value above plain reasoner usage.
|
||||
|
||||
Interpretation: `baseline` (chat / V3) is a floor. `reasoner` shows the raw R1 gain. `reasoner-harvest` isolates the cost + quality delta from the extra V3 harvest call.
|
||||
## Findings (v0.3, 18-run set)
|
||||
|
||||
Two bands of tasks tried (easy: mod7 / flips / hats; hard: pseudoprime341 / D_7 / Euler quadratic). The hard band was chosen for *known V3 failure modes*. Result:
|
||||
|
||||
1. **V3 chat passed all six tasks, including the three "hard" ones.** DeepSeek V3 knew 341 is the smallest base-2 pseudoprime, computed D_7=1854, and identified n=40 as the first Euler-polynomial failure. The tasks are well-known enough to be in training; the trap-answer variants (561, 265, 41) that the checkers specifically reject didn't fire.
|
||||
2. **Reasoner cost 3.04× baseline for identical pass rates (6/6 both sides).** On this task set, R1 adds cost and latency without measurable quality. The cache-hit story *does* extend to reasoner (74.2% mean), so Pillar 1 generalizes to R1 — but that's not a Pillar 2 story.
|
||||
3. **Harvest produced real signal** (mean 2.8 subgoals, 1.3 uncertainties per run where it fired) but didn't improve outcomes. One run hit the 300s timeout (bumped from 120s), suggesting reasoner-harvest latency is still unpredictable on some problems.
|
||||
|
||||
### What this tells us about Pillar 2 positioning
|
||||
|
||||
We've now given harvest two shots at showing answer-quality value on pure reasoning tasks. Both times V3 ate its lunch. This isn't a framework bug — it's a positioning signal:
|
||||
|
||||
- **On well-known math / logic / counting problems, DeepSeek V3 is strong enough that paying for R1 is not justified by accuracy.** Pillar 2's "smart preset" cost multiplier (10×) quoted in the README is real but for most single-question Q/A it buys nothing.
|
||||
- **Harvest's plausible value surfaces are not "better math answers".** More likely: (a) transparency / auditability for developers, (b) planning support when tools are in the mix, (c) driving branch-sampling on cases where uncertainty correlates with wrongness. None of those are tested here.
|
||||
|
||||
### Recommendation
|
||||
|
||||
Don't ship v0.3 on the "harvest makes answers more correct" claim — the data doesn't support it. Two honest paths forward:
|
||||
|
||||
- **Reframe Pillar 2 as a developer-facing introspection feature** (debug visibility into R1's planning). Keep harvest opt-in; stop implying it improves accuracy on end-user tasks.
|
||||
- **Move harvest eval to tool-use contexts** where uncertainty matters for *which tool to call next*, not *is this math right*. That's a new task shape — different harness, not a bigger task set here.
|
||||
|
||||
In either case, the next Reasonix release is better served by MCP client (Pillar 1 leverage across the ecosystem) than by a bigger harvest-bench data push.
|
||||
|
||||
### Notes
|
||||
|
||||
- Cache hit on baseline runs surprised me (39.5% mean). That's DeepSeek's *cross-session* prompt cache: the same system prompt ran many times across modes and runs warmed the server-side cache. Real cross-session evidence that Cache-First's value isn't only per-session.
|
||||
- 5-subgoals cap still hit uniformly. `HarvestOptions.maxItems` default is 5; harvest is truncating. Moot unless we find a setting where that matters.
|
||||
@@ -0,0 +1,232 @@
|
||||
/**
|
||||
* Render a harvest-bench results.json into a markdown report.
|
||||
*
|
||||
* npx tsx benchmarks/harvest/report.ts benchmarks/harvest/results-<date>.json
|
||||
* npx tsx benchmarks/harvest/report.ts <input.json> --out report.md
|
||||
*/
|
||||
|
||||
import { readFileSync, writeFileSync } from "node:fs";
|
||||
import { pathToFileURL } from "node:url";
|
||||
import { ALL_MODES, type HarvestBenchReport, type HarvestMode, type HarvestRunResult } from "./types.js";
|
||||
|
||||
interface CliArgs {
|
||||
input: string;
|
||||
outPath: string;
|
||||
}
|
||||
|
||||
function parseArgs(argv: string[]): CliArgs {
|
||||
const out: CliArgs = { input: "", outPath: "benchmarks/harvest/report.md" };
|
||||
const positional: string[] = [];
|
||||
for (let i = 0; i < argv.length; i++) {
|
||||
const a = argv[i];
|
||||
if (a === "--out") out.outPath = argv[++i] ?? out.outPath;
|
||||
else if (a && !a.startsWith("--")) positional.push(a);
|
||||
}
|
||||
out.input = positional[0] ?? "";
|
||||
if (!out.input) {
|
||||
throw new Error("usage: npx tsx benchmarks/harvest/report.ts <results.json> [--out report.md]");
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
interface Agg {
|
||||
runs: number;
|
||||
passes: number;
|
||||
avgCache: number;
|
||||
avgCost: number;
|
||||
avgClaudeCost: number;
|
||||
avgHarvestedTurns: number;
|
||||
avgSubgoals: number;
|
||||
avgUncertainties: number;
|
||||
}
|
||||
|
||||
function aggregate(results: HarvestRunResult[]): Agg {
|
||||
if (results.length === 0) {
|
||||
return {
|
||||
runs: 0,
|
||||
passes: 0,
|
||||
avgCache: 0,
|
||||
avgCost: 0,
|
||||
avgClaudeCost: 0,
|
||||
avgHarvestedTurns: 0,
|
||||
avgSubgoals: 0,
|
||||
avgUncertainties: 0,
|
||||
};
|
||||
}
|
||||
const passes = results.filter((r) => r.verdict === "pass").length;
|
||||
const mean = (fn: (r: HarvestRunResult) => number) =>
|
||||
results.reduce((s, r) => s + fn(r), 0) / results.length;
|
||||
return {
|
||||
runs: results.length,
|
||||
passes,
|
||||
avgCache: mean((r) => r.cacheHitRatio),
|
||||
avgCost: mean((r) => r.costUsd),
|
||||
avgClaudeCost: mean((r) => r.claudeEquivalentUsd),
|
||||
avgHarvestedTurns: mean((r) => r.harvestedTurns),
|
||||
avgSubgoals: mean((r) => r.totalSubgoals),
|
||||
avgUncertainties: mean((r) => r.totalUncertainties),
|
||||
};
|
||||
}
|
||||
|
||||
export function renderReport(report: HarvestBenchReport): string {
|
||||
const lines: string[] = [];
|
||||
lines.push("# Reasonix harvest eval (Pillar 2)");
|
||||
lines.push("");
|
||||
lines.push(`**Date:** ${report.meta.date}`);
|
||||
lines.push(
|
||||
`**Tasks:** ${report.meta.taskCount} · repeats × ${report.meta.repeatsPerTask} · modes: ${report.meta.modesRun.join(", ")}`,
|
||||
);
|
||||
lines.push(`**Reasonix version:** ${report.meta.reasonixVersion}`);
|
||||
lines.push("");
|
||||
|
||||
// Per-mode summary
|
||||
lines.push("## Summary by mode");
|
||||
lines.push("");
|
||||
lines.push("| mode | runs | pass rate | cache hit | cost / run | harvest turns | subgoals | uncertainties |");
|
||||
lines.push("|---|---:|---:|---:|---:|---:|---:|---:|");
|
||||
for (const mode of ALL_MODES) {
|
||||
const rs = report.results.filter((r) => r.mode === mode);
|
||||
const a = aggregate(rs);
|
||||
if (a.runs === 0) continue;
|
||||
lines.push(
|
||||
`| ${mode} | ${a.runs} | ${pct(a.passes, a.runs)} | ${pct1(a.avgCache)} | $${a.avgCost.toFixed(6)} | ${a.avgHarvestedTurns.toFixed(1)} | ${a.avgSubgoals.toFixed(1)} | ${a.avgUncertainties.toFixed(1)} |`,
|
||||
);
|
||||
}
|
||||
lines.push("");
|
||||
|
||||
// Pairwise deltas that actually answer the question
|
||||
lines.push("## Deltas");
|
||||
lines.push("");
|
||||
const modes = ALL_MODES.filter((m) =>
|
||||
report.results.some((r) => r.mode === m),
|
||||
);
|
||||
if (modes.length >= 2) {
|
||||
const baseline = aggregate(report.results.filter((r) => r.mode === modes[0]));
|
||||
for (let i = 1; i < modes.length; i++) {
|
||||
const mode = modes[i]!;
|
||||
const agg = aggregate(report.results.filter((r) => r.mode === mode));
|
||||
const passDelta = (agg.passes / Math.max(agg.runs, 1)) - (baseline.passes / Math.max(baseline.runs, 1));
|
||||
const costRatio = baseline.avgCost > 0 ? agg.avgCost / baseline.avgCost : 0;
|
||||
lines.push(`- **${modes[0]} → ${mode}**`);
|
||||
lines.push(` - pass rate: ${(passDelta * 100).toFixed(0)}pp`);
|
||||
lines.push(` - cost: ×${costRatio.toFixed(2)} (each run costs ${costRatio > 1 ? "more" : "less"})`);
|
||||
lines.push(` - harvest signal / run: ${agg.avgSubgoals.toFixed(1)} subgoals, ${agg.avgUncertainties.toFixed(1)} uncertainties`);
|
||||
lines.push("");
|
||||
}
|
||||
}
|
||||
|
||||
// Per-task breakdown
|
||||
lines.push("## Per-task breakdown");
|
||||
lines.push("");
|
||||
const byTask = new Map<string, HarvestRunResult[]>();
|
||||
for (const r of report.results) {
|
||||
const list = byTask.get(r.taskId) ?? [];
|
||||
list.push(r);
|
||||
byTask.set(r.taskId, list);
|
||||
}
|
||||
lines.push("| task | mode | rep | verdict | cache | cost | sg | un | note |");
|
||||
lines.push("|---|---|---:|:---:|---:|---:|---:|---:|---|");
|
||||
for (const [taskId, runs] of byTask) {
|
||||
for (const r of runs) {
|
||||
const mark = r.verdict === "pass" ? "✅" : r.verdict === "fail" ? "❌" : "•";
|
||||
lines.push(
|
||||
`| ${taskId} | ${r.mode} | ${r.repeat} | ${mark} | ${pct1(r.cacheHitRatio)} | $${r.costUsd.toFixed(6)} | ${r.totalSubgoals} | ${r.totalUncertainties} | ${truncate(r.checkNote ?? "", 40)} |`,
|
||||
);
|
||||
}
|
||||
}
|
||||
lines.push("");
|
||||
|
||||
lines.push("## Scope");
|
||||
lines.push("");
|
||||
lines.push(
|
||||
"Unlike τ-bench-lite, these tasks are single-turn reasoning problems (no user simulator, no DB, no tool calls). Checkers are deterministic — regex + set / value compare, never an LLM judge. The point is to isolate whether the Pillar 2 harvest step adds measurable value above plain reasoner usage.",
|
||||
);
|
||||
lines.push("");
|
||||
lines.push(
|
||||
"Interpretation: `baseline` (chat / V3) is a floor. `reasoner` shows the raw R1 gain. `reasoner-harvest` isolates the cost + quality delta from the extra V3 harvest call.",
|
||||
);
|
||||
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* Findings section is hand-written into report.md after rendering — the
|
||||
* numbers don't interpret themselves, and boilerplate sections full of
|
||||
* "TBD — analyse the data" are worse than nothing. Append with append().
|
||||
*
|
||||
* This section has been updated twice: after the first 9-run set (which
|
||||
* bottomed out at V3 on easy tasks) and after this 18-run set (which
|
||||
* bottomed out at V3 on *hard* tasks too).
|
||||
*/
|
||||
export function renderFindings(_report: HarvestBenchReport): string {
|
||||
return [
|
||||
"",
|
||||
"## Findings (v0.3, 18-run set)",
|
||||
"",
|
||||
"Two bands of tasks tried (easy: mod7 / flips / hats; hard: pseudoprime341 / D_7 / Euler quadratic). The hard band was chosen for *known V3 failure modes*. Result:",
|
||||
"",
|
||||
"1. **V3 chat passed all six tasks, including the three \"hard\" ones.** DeepSeek V3 knew 341 is the smallest base-2 pseudoprime, computed D_7=1854, and identified n=40 as the first Euler-polynomial failure. The tasks are well-known enough to be in training; the trap-answer variants (561, 265, 41) that the checkers specifically reject didn't fire.",
|
||||
"2. **Reasoner cost 3.04× baseline for identical pass rates (6/6 both sides).** On this task set, R1 adds cost and latency without measurable quality. The cache-hit story *does* extend to reasoner (74.2% mean), so Pillar 1 generalizes to R1 — but that's not a Pillar 2 story.",
|
||||
"3. **Harvest produced real signal** (mean 2.8 subgoals, 1.3 uncertainties per run where it fired) but didn't improve outcomes. One run hit the 300s timeout (bumped from 120s), suggesting reasoner-harvest latency is still unpredictable on some problems.",
|
||||
"",
|
||||
"### What this tells us about Pillar 2 positioning",
|
||||
"",
|
||||
"We've now given harvest two shots at showing answer-quality value on pure reasoning tasks. Both times V3 ate its lunch. This isn't a framework bug — it's a positioning signal:",
|
||||
"",
|
||||
"- **On well-known math / logic / counting problems, DeepSeek V3 is strong enough that paying for R1 is not justified by accuracy.** Pillar 2's \"smart preset\" cost multiplier (10×) quoted in the README is real but for most single-question Q/A it buys nothing.",
|
||||
"- **Harvest's plausible value surfaces are not \"better math answers\".** More likely: (a) transparency / auditability for developers, (b) planning support when tools are in the mix, (c) driving branch-sampling on cases where uncertainty correlates with wrongness. None of those are tested here.",
|
||||
"",
|
||||
"### Recommendation",
|
||||
"",
|
||||
"Don't ship v0.3 on the \"harvest makes answers more correct\" claim — the data doesn't support it. Two honest paths forward:",
|
||||
"",
|
||||
"- **Reframe Pillar 2 as a developer-facing introspection feature** (debug visibility into R1's planning). Keep harvest opt-in; stop implying it improves accuracy on end-user tasks.",
|
||||
"- **Move harvest eval to tool-use contexts** where uncertainty matters for *which tool to call next*, not *is this math right*. That's a new task shape — different harness, not a bigger task set here.",
|
||||
"",
|
||||
"In either case, the next Reasonix release is better served by MCP client (Pillar 1 leverage across the ecosystem) than by a bigger harvest-bench data push.",
|
||||
"",
|
||||
"### Notes",
|
||||
"",
|
||||
"- Cache hit on baseline runs surprised me (39.5% mean). That's DeepSeek's *cross-session* prompt cache: the same system prompt ran many times across modes and runs warmed the server-side cache. Real cross-session evidence that Cache-First's value isn't only per-session.",
|
||||
"- 5-subgoals cap still hit uniformly. `HarvestOptions.maxItems` default is 5; harvest is truncating. Moot unless we find a setting where that matters.",
|
||||
"",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
function pct(num: number, denom: number): string {
|
||||
if (denom === 0) return "—";
|
||||
return `${((num / denom) * 100).toFixed(0)}%`;
|
||||
}
|
||||
|
||||
function pct1(x: number): string {
|
||||
return `${(x * 100).toFixed(1)}%`;
|
||||
}
|
||||
|
||||
function truncate(s: string, n: number): string {
|
||||
return s.length > n ? `${s.slice(0, n)}…` : s;
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const args = parseArgs(process.argv.slice(2));
|
||||
const raw = readFileSync(args.input, "utf8");
|
||||
const report = JSON.parse(raw) as HarvestBenchReport;
|
||||
const md = renderReport(report) + renderFindings(report);
|
||||
writeFileSync(args.outPath, md, "utf8");
|
||||
console.log(`wrote ${args.outPath} (${report.results.length} runs)`);
|
||||
}
|
||||
|
||||
function isMain(): boolean {
|
||||
const entry = process.argv[1];
|
||||
if (!entry) return false;
|
||||
return import.meta.url === pathToFileURL(entry).href;
|
||||
}
|
||||
|
||||
if (isMain()) {
|
||||
main().catch((err) => {
|
||||
console.error(err);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
|
||||
// Suppress unused import warning — kept in scope so ALL_MODES order matches renderer iteration.
|
||||
export type { HarvestMode };
|
||||
@@ -0,0 +1,305 @@
|
||||
{
|
||||
"meta": {
|
||||
"date": "2026-04-21T16:44:21.011Z",
|
||||
"repeatsPerTask": 1,
|
||||
"taskCount": 6,
|
||||
"modesRun": [
|
||||
"baseline",
|
||||
"reasoner",
|
||||
"reasoner-harvest"
|
||||
],
|
||||
"reasonixVersion": "0.2.2"
|
||||
},
|
||||
"results": [
|
||||
{
|
||||
"taskId": "mod7_list",
|
||||
"mode": "baseline",
|
||||
"repeat": 1,
|
||||
"verdict": "pass",
|
||||
"finalAgentMessage": "Alright, let's go step-by-step.\n\n---\n\n## **Step 1: Problem restatement**\nWe want positive integers \\( n \\leq 100 \\) such that \n\\[\nn^2 + n + 1 \\equiv 0 \\pmod{7}.\n\\]\n\n---\n\n## **Step 2: Try residues modulo 7**\nLet \\( n \\equiv r \\pmod{7} \\), where \\( r \\in \\{0, 1, 2, 3, 4, 5, 6\\} \\).\n\nWe compute \\( r^2 + r + 1 \\mod 7 \\):\n\n- \\( r = 0 \\): \\( 0 + 0 + 1 = 1 \\) → not divisible by 7.\n- \\( r = 1 \\): \\( 1 + 1 + 1 = 3 \\) → no.\n- \\( r = 2 \\): \\( 4 + 2 + 1 = 7 \\equiv 0 \\) → yes.\n- \\( r = 3 \\): \\( 9 + 3 + 1 = 13 \\equiv 6 \\) → no.\n- \\( r = 4 \\): \\( 16 + 4 + 1 = 21 \\equiv 0 \\) → yes.\n- \\( r = 5 \\): \\( 25 + 5 + 1 = 31 \\equiv 3 \\) → no.\n- \\( r = 6 \\): \\( 36 + 6 + 1 = 43 \\equiv 1 \\) → no.\n\nSo \\( n \\equiv 2 \\pmod{7} \\) or \\( n \\equiv 4 \\pmod{7} \\).\n\n---\n\n## **Step 3: General form**\n\\[\nn \\equiv 2 \\pmod{7} \\quad \\text{or} \\quad n \\equiv 4 \\pmod{7}.\n\\]\n\nThat means \\( n = 7k + 2 \\) or \\( n = 7k + 4 \\) for some integer \\( k \\ge 0 \\).\n\n---\n\n## **Step 4: Positive integers \\( n \\leq 100 \\)**\n**Case 1:** \\( n = 7k + 2 \\), \\( n \\leq 100 \\), \\( k \\ge 0 \\).\n\n\\( 7k + 2 \\leq 100 \\) → \\( 7k \\leq 98 \\) → \\( k \\leq 14 \\).\n\nSo \\( k = 0, 1, 2, \\dots, 14 \\) gives \\( n = 2, 9, 16, \\dots, 100 \\).\n\nCheck \\( n=100 \\): \\( 7 \\times 14 + 2 = 98 + 2 = 100 \\) okay.\n\n---\n\n**Case 2:** \\( n = 7k + 4 \\), \\( n \\leq 100 \\), \\( k \\ge 0 \\).\n\n\\( 7k + 4 \\leq 100 \\) → \\( 7k \\leq 96 \\) → \\( k \\leq 13 \\) (since \\( 7 \\times 13 = 91 \\), \\( 91+4=95 \\), \\( 7\\times14=98 \\) → \\( 98+4=102>100 \\)).\n\nSo \\( k = 0, 1, 2, \\dots, 13 \\) gives \\( n = 4, 11, 18, \\dots, 95 \\).\n\n---\n\n## **Step 5: List all such \\( n \\leq 100 \\)**\nFrom case 1: \\( 2, 9, 16, 23, 30, 37, 44, 51, 58, 65, 72, 79, 86, 93, 100 \\).\n\nFrom case 2: \\( 4, 11, 18, 25, 32, 39, 46, 53, 60, 67, 74, 81, 88, 95 \\).\n\nCombine and sort:\n\n\\[\n2, 4, 9, 11, 16, 18, 23, 25, 30, 32, 37, 39, 44, 46, 51, 53, 58, 60, 65, 67, 72, 74, 79, 81, 86, 88, 93, 95, 100.\n\\]\n\n---\n\n## **Step 6: Check count**\nEach sequence has 15 and 14 terms respectively, total \\( 15 + 14 = 29 \\) numbers.\n\nCheck: \\( n=2 \\) works? \\( 4+2+1=7 \\) yes. \\( n=4 \\) works? \\( 16+4+1=21 \\) yes. \\( n=100 \\) works? \\( 10000+100+1=10101 \\), divide by 7: \\( 10101/7 = 1443 \\) yes.\n\n---\n\n**Final answer:**\n\\[\n\\boxed{2, 4, 9, 11, 16, 18, 23, 25, 30, 32, 37, 39, 44, 46, 51, 53, 58, 60, 65, 67, 72, 74, 79, 81, 86, 88, 93, 95, 100}\n\\]\n\n---\n\nAnswer: 2, 4, 9, 11, 16, 18, 23, 25, 30, 32, 37, 39, 44, 46, 51, 53, 58, 60, 65, 67, 72, 74, 79, 81, 86, 88, 93, 95, 100",
|
||||
"turns": 1,
|
||||
"cacheHitRatio": 0.8648648648648649,
|
||||
"costUsd": 0.0013612800000000003,
|
||||
"claudeEquivalentUsd": 0.018687,
|
||||
"harvestedTurns": 0,
|
||||
"totalSubgoals": 0,
|
||||
"totalUncertainties": 0,
|
||||
"totalHypotheses": 0,
|
||||
"totalRejectedPaths": 0
|
||||
},
|
||||
{
|
||||
"taskId": "mod7_list",
|
||||
"mode": "reasoner",
|
||||
"repeat": 1,
|
||||
"verdict": "pass",
|
||||
"finalAgentMessage": "The condition \\(n^2 + n + 1\\) divisible by 7 is equivalent to \\(n^2 + n + 1 \\equiv 0 \\pmod{7}\\). Testing residues modulo 7:\n\n- \\(n \\equiv 0: 0+0+1 \\equiv 1\\) \n- \\(n \\equiv 1: 1+1+1 \\equiv 3\\) \n- \\(n \\equiv 2: 4+2+1 \\equiv 7 \\equiv 0\\) \n- \\(n \\equiv 3: 9+3+1 \\equiv 13 \\equiv 6\\) \n- \\(n \\equiv 4: 16+4+1 \\equiv 21 \\equiv 0\\) \n- \\(n \\equiv 5: 25+5+1 \\equiv 31 \\equiv 3\\) \n- \\(n \\equiv 6: 36+6+1 \\equiv 43 \\equiv 1\\)\n\nThus, \\(n \\equiv 2\\) or \\(n \\equiv 4 \\pmod{7}\\) are the solutions modulo 7. For positive integers \\(n \\leq 100\\), we list all numbers congruent to 2 or 4 modulo 7 in increasing order.\n\nAnswer: 2, 4, 9, 11, 16, 18, 23, 25, 30, 32, 37, 39, 44, 46, 51, 53, 58, 60, 65, 67, 72, 74, 79, 81, 86, 88, 93, 95, 100",
|
||||
"turns": 1,
|
||||
"cacheHitRatio": 0.8648648648648649,
|
||||
"costUsd": 0.00479742,
|
||||
"claudeEquivalentUsd": 0.032982,
|
||||
"harvestedTurns": 0,
|
||||
"totalSubgoals": 0,
|
||||
"totalUncertainties": 0,
|
||||
"totalHypotheses": 0,
|
||||
"totalRejectedPaths": 0
|
||||
},
|
||||
{
|
||||
"taskId": "mod7_list",
|
||||
"mode": "reasoner-harvest",
|
||||
"repeat": 1,
|
||||
"verdict": "pass",
|
||||
"finalAgentMessage": "The congruence \\(n^2 + n + 1 \\equiv 0 \\pmod{7}\\) is solved by testing residues modulo 7. The solutions are \\(n \\equiv 2\\) and \\(n \\equiv 4 \\pmod{7}\\). For positive integers \\(n \\le 100\\), these yield \\(n = 7k + 2\\) with \\(k = 0, 1, \\dots, 14\\) and \\(n = 7k + 4\\) with \\(k = 0, 1, \\dots, 13\\).\n\nAnswer: 2, 4, 9, 11, 16, 18, 23, 25, 30, 32, 37, 39, 44, 46, 51, 53, 58, 60, 65, 67, 72, 74, 79, 81, 86, 88, 93, 95, 100",
|
||||
"turns": 1,
|
||||
"cacheHitRatio": 0.8648648648648649,
|
||||
"costUsd": 0.00304542,
|
||||
"claudeEquivalentUsd": 0.020982,
|
||||
"harvestedTurns": 1,
|
||||
"totalSubgoals": 4,
|
||||
"totalUncertainties": 2,
|
||||
"totalHypotheses": 2,
|
||||
"totalRejectedPaths": 2
|
||||
},
|
||||
{
|
||||
"taskId": "flips_until_3heads",
|
||||
"mode": "baseline",
|
||||
"repeat": 1,
|
||||
"verdict": "pass",
|
||||
"finalAgentMessage": "Alright, let's reason through this step-by-step.\n\n---\n\n## **Step 1: Define states**\nLet’s define states based on how many consecutive heads we have at the moment.\n\n- \\( E_0 \\): Expected flips to reach 3 heads in a row starting from 0 consecutive heads (or just starting, or after a tail).\n- \\( E_1 \\): Expected flips to reach 3 heads in a row starting from 1 consecutive head.\n- \\( E_2 \\): Expected flips to reach 3 heads in a row starting from 2 consecutive heads.\n\nWe want \\( E_0 \\).\n\n---\n\n## **Step 2: Transition equations**\nFrom \\( E_0 \\):\n- Flip H (prob \\( \\frac12 \\)) → go to state \\( E_1 \\), 1 flip used.\n- Flip T (prob \\( \\frac12 \\)) → stay in \\( E_0 \\), 1 flip used.\n\nSo:\n\\[\nE_0 = \\frac12 (1 + E_1) + \\frac12 (1 + E_0)\n\\]\n\n---\n\nFrom \\( E_1 \\) (already have 1 head):\n- Flip H (prob \\( \\frac12 \\)) → go to state \\( E_2 \\), 1 flip used.\n- Flip T (prob \\( \\frac12 \\)) → go to state \\( E_0 \\), 1 flip used.\n\nSo:\n\\[\nE_1 = \\frac12 (1 + E_2) + \\frac12 (1 + E_0)\n\\]\n\n---\n\nFrom \\( E_2 \\) (already have 2 heads):\n- Flip H (prob \\( \\frac12 \\)) → done (3 heads in a row), 1 flip used.\n- Flip T (prob \\( \\frac12 \\)) → go to state \\( E_0 \\), 1 flip used.\n\nSo:\n\\[\nE_2 = \\frac12 (1 + 0) + \\frac12 (1 + E_0)\n\\]\n\\[\nE_2 = \\frac12 \\cdot 1 + \\frac12 (1 + E_0) \\quad\\text{(Wait, careful:)}\n\\]\nActually: \nIf H: \\( 1 \\) flip and done. \nIf T: \\( 1 \\) flip and then \\( E_0 \\) more.\n\nSo:\n\\[\nE_2 = \\frac12 \\cdot 1 + \\frac12 (1 + E_0)\n\\]\nCheck: \nH: 1 flip → total 1, done. Contribution: \\( \\frac12 \\times 1 \\). \nT: 1 flip + \\( E_0 \\) more → total \\( 1 + E_0 \\). Contribution: \\( \\frac12 \\times (1 + E_0) \\).\n\nYes:\n\\[\nE_2 = \\frac12 \\cdot 1 + \\frac12 (1 + E_0) = \\frac12 + \\frac12 + \\frac12 E_0 = 1 + \\frac{E_0}{2}.\n\\]\n\n---\n\n## **Step 3: Solve system**\nWe have:\n\n(1) \\( E_0 = \\frac12 (1 + E_1) + \\frac12 (1 + E_0) \\) \nSimplify: \\( E_0 = 1 + \\frac12 E_1 + \\frac12 E_0 \\) \nMultiply by 2: \\( 2E_0 = 2 + E_1 + E_0 \\) \nSo \\( E_0 - E_1 = 2 \\) … (Eq A)\n\n---\n\n(2) \\( E_1 = \\frac12 (1 + E_2) + \\frac12 (1 + E_0) \\) \nSimplify: \\( E_1 = 1 + \\frac12 E_2 + \\frac12 E_0 \\) … (Eq B)\n\n---\n\n(3) \\( E_2 = 1 + \\frac12 E_0 \\) … (Eq C)\n\n---\n\nFrom Eq C into Eq B:\n\\[\nE_1 = 1 + \\frac12 \\left( 1 + \\frac12 E_0 \\right) + \\frac12 E_0\n\\]\n\\[\nE_1 = 1 + \\frac12 + \\frac14 E_0 + \\frac12 E_0\n\\]\n\\[\nE_1 = \\frac32 + \\frac34 E_0\n\\]\n\n---\n\nFrom Eq A: \\( E_0 - E_1 = 2 \\) \nSubstitute \\( E_1 \\):\n\\[\nE_0 - \\left( \\frac32 + \\frac34 E_0 \\right) = 2\n\\]\n\\[\nE_0 - \\frac32 - \\frac34 E_0 = 2\n\\]\n\\[\n\\frac14 E_0 - \\frac32 = 2\n\\]\n\\[\n\\frac14 E_0 = 2 + \\frac32 = \\frac72\n\\]\n\\[\nE_0 = 14\n\\]\n\n---\n\n## **Step 4: Conclusion**\nThe expected number of flips until we get 3 heads in a row is \\( 14 \\).\n\n---\n\n**Answer:** 14",
|
||||
"turns": 1,
|
||||
"cacheHitRatio": 0.927536231884058,
|
||||
"costUsd": 0.00119823,
|
||||
"claudeEquivalentUsd": 0.016467,
|
||||
"harvestedTurns": 0,
|
||||
"totalSubgoals": 0,
|
||||
"totalUncertainties": 0,
|
||||
"totalHypotheses": 0,
|
||||
"totalRejectedPaths": 0
|
||||
},
|
||||
{
|
||||
"taskId": "flips_until_3heads",
|
||||
"mode": "reasoner",
|
||||
"repeat": 1,
|
||||
"verdict": "pass",
|
||||
"finalAgentMessage": "The expected number of flips required to get three consecutive heads is 14, derived from solving the system of linear equations for the Markov chain states representing the current streak of heads.\n\nAnswer: 14",
|
||||
"turns": 1,
|
||||
"cacheHitRatio": 0.927536231884058,
|
||||
"costUsd": 0.00283024,
|
||||
"claudeEquivalentUsd": 0.019512,
|
||||
"harvestedTurns": 0,
|
||||
"totalSubgoals": 0,
|
||||
"totalUncertainties": 0,
|
||||
"totalHypotheses": 0,
|
||||
"totalRejectedPaths": 0
|
||||
},
|
||||
{
|
||||
"taskId": "flips_until_3heads",
|
||||
"mode": "reasoner-harvest",
|
||||
"repeat": 1,
|
||||
"verdict": "pass",
|
||||
"finalAgentMessage": "The expected number of flips until three consecutive heads appear is 14.\n\nAnswer: 14",
|
||||
"turns": 1,
|
||||
"cacheHitRatio": 0.927536231884058,
|
||||
"costUsd": 0.00169144,
|
||||
"claudeEquivalentUsd": 0.011712,
|
||||
"harvestedTurns": 1,
|
||||
"totalSubgoals": 4,
|
||||
"totalUncertainties": 0,
|
||||
"totalHypotheses": 2,
|
||||
"totalRejectedPaths": 0
|
||||
},
|
||||
{
|
||||
"taskId": "three_hats",
|
||||
"mode": "baseline",
|
||||
"repeat": 1,
|
||||
"verdict": "pass",
|
||||
"finalAgentMessage": "Let's break this down step by step.\n\n---\n\n**Step 1: Understanding the setup** \nThree people: A (first), B (second), C (third). \nEach hat is red (R) or blue (B). \nThey know: at least one hat is red. \nEach sees the other two hats, not their own. \nThey are asked in order: \"Do you know your hat color?\" \nA answers no, B answers no, C answers yes. \nWe want C’s hat color.\n\n---\n\n**Step 2: From A’s perspective when asked** \nA sees B and C. \nIf A had seen two blue hats, then A would know: \"At least one red hat means my hat must be red.\" \nSo A says \"no\" → A did **not** see two blue hats. \nThus A sees at least one red hat on {B, C}.\n\nPossible cases for what A sees (B, C): \n(R, R), (R, B), (B, R) — all have at least one red.\n\n---\n\n**Step 3: B’s reasoning when asked** \nB hears A say \"no\". \nB sees A and C. \n\nLet’s consider B’s possible deductions from A’s \"no\": \nB knows: If A had seen two blues, A would have said yes. Since A said no, A saw at least one red among B and C. \nBut B sees A and C. \n\nFrom B’s viewpoint: \n- If B saw C with blue and A with blue, then B would know: \"A saw me and C both blue → impossible because A said no.\" But B doesn’t see that because if B saw A blue and C blue, then B would know his own hat must be red (since at least one red total). But then B would answer yes. \nSo B’s \"no\" means B did **not** see A and C both blue. \n\nAlso, B considers: Could my hat be blue? Let’s check: \nSuppose B sees A red, C blue. Then B thinks: \"If my hat were blue, then A would have seen (B blue, C blue) → A would have said yes. But A said no, so my hat cannot be blue.\" \nSo if B saw (A red, C blue), B would deduce: \"My hat must be red.\" Then B would answer yes. \nBut B said no → so B did **not** see (A red, C blue).\n\nSimilarly, if B saw (A blue, C red): \nThen B thinks: \"If my hat were blue, then A would have seen (B blue, C red) → that’s fine (A sees one red on C), so A would still say no. If my hat were red, then A would see (B red, C red) → A would still say no. So I don’t know.\" That’s consistent with B saying no. \n\nIf B saw (A red, C red): \nThen B thinks: \"If my hat were blue, A sees (B blue, C red) → A says no. If my hat were red, A sees (B red, C red) → A says no. So I don’t know.\" That’s also consistent with B saying no.\n\nSo B says no in cases: \nB sees (A blue, C red) or (A red, C red). \nB would say yes if B saw (A red, C blue) — but that didn’t happen. \n\n---\n\n**Step 4: C’s reasoning** \nC hears A says no, B says no. \nC sees A and B. \n\nFrom C’s viewpoint: \nLet’s list all possible (A, B, C) hat colorings with at least one red, consistent with A’s \"no\" (which we already incorporated: A sees at least one red on B/C) and B’s \"no\" (meaning B didn’t see A red, C blue — because that would make B know).\n\nPossible cases for (A, B) that C could see: \n\n1. C sees (A blue, B red): \n Then C thinks: \n - If C were blue: (A blue, B red, C blue) → A sees (B red, C blue) → A says no. B sees (A blue, C blue) → B sees two blues? Wait, B sees A blue, C blue → then B knows his own hat is red (since at least one red total) → B would say yes. But B said no → contradiction. So C cannot be blue. \n So C must be red. \n\n2. C sees (A red, B blue): \n Then C thinks: \n - If C were blue: (A red, B blue, C blue) → A sees (B blue, C blue) → A would say yes (since at least one red total means A’s hat must be red). But A said no → contradiction. So C cannot be blue. \n So C must be red. \n\n3. C sees (A red, B red): \n Then C thinks: \n - If C were blue: (A red, B red, C blue) → A sees (B red, C blue) → A says no. B sees (A red, C blue) → B sees A red, C blue → earlier we said: If B sees A red, C blue, then B would deduce his own hat is red (reasoning: if B were blue, A would have seen two blues and said yes, but A said no, so B can’t be blue) → so B would say yes. But B actually said no → contradiction. So C cannot be blue. \n - If C were red: (A red, B red, C red) → A sees (B red, C red) → A says no. B sees (A red, C red) → B says no. Works fine. \n\nSo in all cases C sees for (A, B), C can deduce C’s hat is **red** because assuming C is blue leads to contradiction with B’s \"no\" (in cases 1 and 3) or with A’s \"no\" (in case 2).\n\n---\n\n**Step 5: Conclusion** \nC answers yes, and C’s hat must be red.\n\n---\n\nAnswer: red",
|
||||
"turns": 1,
|
||||
"cacheHitRatio": 0.5765765765765766,
|
||||
"costUsd": 0.0015142700000000003,
|
||||
"claudeEquivalentUsd": 0.020748,
|
||||
"harvestedTurns": 0,
|
||||
"totalSubgoals": 0,
|
||||
"totalUncertainties": 0,
|
||||
"totalHypotheses": 0,
|
||||
"totalRejectedPaths": 0
|
||||
},
|
||||
{
|
||||
"taskId": "three_hats",
|
||||
"mode": "reasoner",
|
||||
"repeat": 1,
|
||||
"verdict": "pass",
|
||||
"finalAgentMessage": "Answer: red",
|
||||
"turns": 1,
|
||||
"cacheHitRatio": 0.5765765765765766,
|
||||
"costUsd": 0.009340119999999999,
|
||||
"claudeEquivalentUsd": 0.064068,
|
||||
"harvestedTurns": 0,
|
||||
"totalSubgoals": 0,
|
||||
"totalUncertainties": 0,
|
||||
"totalHypotheses": 0,
|
||||
"totalRejectedPaths": 0
|
||||
},
|
||||
{
|
||||
"taskId": "three_hats",
|
||||
"mode": "reasoner-harvest",
|
||||
"repeat": 1,
|
||||
"verdict": "pass",
|
||||
"finalAgentMessage": "The third person deduces their hat color based on the previous responses. Since the first two answer \"no,\" it implies they each see at least one red hat and cannot determine their own color. Specifically, the second person's \"no\" indicates they see the third person's hat as red; otherwise, they would have known their own hat color. Therefore, the third person's hat must be red.\n\nAnswer: red",
|
||||
"turns": 1,
|
||||
"cacheHitRatio": 0.5765765765765766,
|
||||
"costUsd": 0.0096511,
|
||||
"claudeEquivalentUsd": 0.066198,
|
||||
"harvestedTurns": 1,
|
||||
"totalSubgoals": 3,
|
||||
"totalUncertainties": 2,
|
||||
"totalHypotheses": 3,
|
||||
"totalRejectedPaths": 3
|
||||
},
|
||||
{
|
||||
"taskId": "pseudoprime_base2",
|
||||
"mode": "baseline",
|
||||
"repeat": 1,
|
||||
"verdict": "pass",
|
||||
"finalAgentMessage": "Alright, let's go step-by-step.\n\n---\n\n**Step 1: Understanding the problem**\n\nWe want the smallest composite integer \\( n > 1 \\) such that\n\n\\[\n2^n \\equiv 2 \\pmod{n}.\n\\]\n\nEquivalently, \\( 2^{n-1} \\equiv 1 \\pmod{n} \\) for composite \\( n \\).\n\nThis means \\( n \\) is a **Fermat pseudoprime to base 2**.\n\nWe check composite numbers starting from the smallest.\n\n---\n\n**Step 2: Check small composites**\n\n- \\( n = 4 \\): composite. \n\\( 2^4 = 16 \\), \\( 16 \\mod 4 = 0 \\), not \\( 2 \\). So \\( 2^4 \\equiv 0 \\not\\equiv 2 \\pmod{4} \\). Fails.\n\n- \\( n = 6 \\): composite. \n\\( 2^6 = 64 \\), \\( 64 \\mod 6 = 4 \\), not \\( 2 \\). Fails.\n\n- \\( n = 8 \\): composite. \n\\( 2^8 = 256 \\), \\( 256 \\mod 8 = 0 \\), not \\( 2 \\). Fails.\n\n- \\( n = 9 \\): composite. \n\\( 2^9 = 512 \\), \\( 512 \\mod 9 \\): \n\\( 512 \\div 9 \\), \\( 9 \\times 56 = 504 \\), remainder \\( 8 \\), not \\( 2 \\). Fails.\n\n- \\( n = 10 \\): composite. \n\\( 2^{10} = 1024 \\), \\( 1024 \\mod 10 = 4 \\), not \\( 2 \\). Fails.\n\n---\n\n**Step 3: Try n = 15**\n\n\\( n = 15 \\): composite. \n\\( 2^{15} = 32768 \\). \nCheck mod 15: \nWe can use mod arithmetic: \n\\( 2^4 = 16 \\equiv 1 \\pmod{15} \\)?? Wait, check: \\( 16 \\mod 15 = 1 \\), yes. \nSo \\( 2^{15} = (2^4)^3 \\times 2^3 = 1^3 \\times 8 = 8 \\pmod{15} \\). \nSo \\( 2^{15} \\equiv 8 \\not\\equiv 2 \\pmod{15} \\). Fails.\n\n---\n\n**Step 4: Try n = 21**\n\n\\( n = 21 \\): composite. \nMod 21: \n\\( 2^6 = 64 \\equiv 1 \\pmod{21} \\)? Check: \\( 64 \\div 21 = 3 \\times 21 = 63 \\), remainder 1, yes. \nSo \\( 2^{21} = (2^6)^3 \\times 2^3 \\equiv 1^3 \\times 8 = 8 \\pmod{21} \\). Not 2. Fails.\n\n---\n\n**Step 5: Try n = 22**\n\n\\( n = 22 \\): composite. \nUse mod 22: \nEuler’s totient not needed, just check order: \n\\( 2^5 = 32 \\equiv 10 \\pmod{22} \\) \n\\( 2^{10} = (2^5)^2 \\equiv 10^2 = 100 \\equiv 12 \\pmod{22} \\) \n\\( 2^{11} \\equiv 24 \\equiv 2 \\pmod{22} \\) \nSo \\( 2^{22} = (2^{11})^2 \\equiv 2^2 = 4 \\pmod{22} \\). Not 2. Fails.\n\n---\n\n**Step 6: Try n = 25**\n\n\\( n = 25 \\): composite. \nCheck mod 25: \n\\( 2^{10} = 1024 \\equiv 24 \\pmod{25} \\) (since \\( 1000 \\equiv 0 \\), \\( 24 \\equiv -1 \\)) \nActually check: \\( 1024 - 1000 = 24 \\), yes \\( 24 \\equiv -1 \\). \nSo \\( 2^{20} \\equiv 1 \\pmod{25} \\). \nThus \\( 2^{25} = 2^{20} \\times 2^5 \\equiv 1 \\times 32 = 7 \\pmod{25} \\). Not 2. Fails.\n\n---\n\n**Step 7: Known smallest base-2 Fermat pseudoprime**\n\nFrom known number theory facts: \nThe smallest Fermat pseudoprime to base 2 is \\( n = 341 \\). \nBut let's check smaller ones just in case I’m skipping one.\n\n---\n\n**Step 8: Try n = 91**\n\n91 = 7 × 13. \nCheck mod 7: \\( 2^{91} \\equiv (2^6)^{15} \\times 2^1 \\equiv 1^{15} \\times 2 = 2 \\pmod{7} \\). \nCheck mod 13: \\( 2^{12} \\equiv 1 \\pmod{13} \\), \n\\( 91 = 12 \\times 7 + 7 \\), so \\( 2^{91} \\equiv 2^7 = 128 \\equiv 11 \\pmod{13} \\). \nFor \\( 2^{91} \\equiv 2 \\pmod{91} \\), we need \\( 2^{91} \\equiv 2 \\) mod 7 and mod 13. \nMod 13 we got 11, not 2. So fails.\n\n---\n\n**Step 9: Try n = 341**\n\n341 = 11 × 31. \nCheck mod 11: \\( 2^{10} \\equiv 1 \\pmod{11} \\), \n\\( 341 = 10 \\times 34 + 1 \\), so \\( 2^{341} \\equiv 2^1 = 2 \\pmod{11} \\). Good. \nCheck mod 31: \\( 2^5 = 32 \\equiv 1 \\pmod{31} \\), \n\\( 341 = 5 \\times 68 + 1 \\), so \\( 2^{341} \\equiv 2^1 = 2 \\pmod{31} \\). \nSo \\( 2^{341} \\equiv 2 \\) mod 11 and mod 31, hence mod 341. \nThus \\( 341 \\) works.\n\n---\n\n**Step 10: Check smaller than 341**\n\nKnown list: 341 is smallest. Let’s check a candidate like 121 = 11^2: \n\\( 2^{121} \\mod 121 \\): \nMod 11: \\( 2^{10} \\equiv 1 \\), \\( 121 = 10 \\times 12 + 1 \\), so \\( 2^{121} \\equiv 2 \\pmod{11} \\). \nBut for modulus 121, need more: \nActually, \\( 2^{110} \\equiv 1 \\pmod{121} \\) by Euler’s theorem? Not exactly, but known: 121 is not a pseudoprime base 2. Quick check: \n\\( 2^{121} - 2 \\) divisible by 121? Probably not. Let’s skip detailed check; known fact is 341 is smallest.\n\n---\n\n**Step 11: Verify no smaller composite works**\n\nFrom known sequence A001567: \nFirst few base-2 Fermat pseudoprimes: 341, 561, 645, 1105, … \nSo smallest is 341.\n\n---\n\n**Step 12: Conclusion**\n\nThe smallest composite \\( n > 1 \\) with \\( 2^n \\equiv 2 \\pmod{n} \\) is \\( n = 341 \\).\n\n---\n\n**Answer:** 341",
|
||||
"turns": 1,
|
||||
"cacheHitRatio": 0,
|
||||
"costUsd": 0.0018940500000000002,
|
||||
"claudeEquivalentUsd": 0.02577,
|
||||
"harvestedTurns": 0,
|
||||
"totalSubgoals": 0,
|
||||
"totalUncertainties": 0,
|
||||
"totalHypotheses": 0,
|
||||
"totalRejectedPaths": 0
|
||||
},
|
||||
{
|
||||
"taskId": "pseudoprime_base2",
|
||||
"mode": "reasoner",
|
||||
"repeat": 1,
|
||||
"verdict": "pass",
|
||||
"finalAgentMessage": "The smallest composite integer \\(n > 1\\) satisfying \\(2^n \\equiv 2 \\pmod{n}\\) is \\(n = 341\\). This is composite (\\(341 = 11 \\times 31\\)), and it satisfies the congruence because \\(2^{341} \\equiv 2 \\pmod{11}\\) and \\(2^{341} \\equiv 2 \\pmod{31}\\) by Fermat's little theorem, implying \\(2^{341} \\equiv 2 \\pmod{341}\\). All smaller composite integers (e.g., 4, 6, 8, 9, 10, 15, 21) fail to satisfy the condition.\n\nAnswer: 341",
|
||||
"turns": 1,
|
||||
"cacheHitRatio": 0.7529411764705882,
|
||||
"costUsd": 0.0031281200000000003,
|
||||
"claudeEquivalentUsd": 0.02154,
|
||||
"harvestedTurns": 0,
|
||||
"totalSubgoals": 0,
|
||||
"totalUncertainties": 0,
|
||||
"totalHypotheses": 0,
|
||||
"totalRejectedPaths": 0
|
||||
},
|
||||
{
|
||||
"taskId": "pseudoprime_base2",
|
||||
"mode": "reasoner-harvest",
|
||||
"repeat": 1,
|
||||
"verdict": "fail",
|
||||
"checkNote": "This operation was aborted",
|
||||
"finalAgentMessage": "",
|
||||
"turns": 0,
|
||||
"cacheHitRatio": 0,
|
||||
"costUsd": 0,
|
||||
"claudeEquivalentUsd": 0,
|
||||
"harvestedTurns": 0,
|
||||
"totalSubgoals": 0,
|
||||
"totalUncertainties": 0,
|
||||
"totalHypotheses": 0,
|
||||
"totalRejectedPaths": 0,
|
||||
"errorMessage": "This operation was aborted"
|
||||
},
|
||||
{
|
||||
"taskId": "derangements_d7",
|
||||
"mode": "baseline",
|
||||
"repeat": 1,
|
||||
"verdict": "pass",
|
||||
"finalAgentMessage": "Alright, let's go step-by-step.\n\n---\n\n**Step 1: Understanding the problem**\n\nWe want the number of permutations of \\(\\{1, 2, 3, 4, 5, 6, 7\\}\\) with **no fixed points**. \nA fixed point means \\(\\pi(i) = i\\) for some \\(i\\). \nA permutation with no fixed points is called a **derangement**. \nThe number of derangements of \\(n\\) elements is denoted \\(D_n\\) or \\(!n\\).\n\n---\n\n**Step 2: Formula for derangements**\n\nThe formula for \\(D_n\\) is:\n\n\\[\nD_n = n! \\sum_{k=0}^{n} \\frac{(-1)^k}{k!}\n\\]\n\nFor \\(n=7\\):\n\n\\[\nD_7 = 7! \\left( \\frac{1}{0!} - \\frac{1}{1!} + \\frac{1}{2!} - \\frac{1}{3!} + \\frac{1}{4!} - \\frac{1}{5!} + \\frac{1}{6!} - \\frac{1}{7!} \\right)\n\\]\n\n---\n\n**Step 3: Compute step-by-step**\n\nFirst, \\(7! = 5040\\).\n\nNow compute the sum:\n\n\\[\n\\sum_{k=0}^{7} \\frac{(-1)^k}{k!} \n= 1 - 1 + \\frac{1}{2} - \\frac{1}{6} + \\frac{1}{24} - \\frac{1}{120} + \\frac{1}{720} - \\frac{1}{5040}\n\\]\n\nLet's compute term-by-term:\n\n- \\(1 - 1 = 0\\)\n- \\(0 + 0.5 = 0.5\\)\n- \\(0.5 - \\frac{1}{6} \\approx 0.5 - 0.1666667 = 0.3333333\\)\n- \\(0.3333333 + \\frac{1}{24} \\approx 0.3333333 + 0.0416667 = 0.375\\)\n- \\(0.375 - \\frac{1}{120} \\approx 0.375 - 0.0083333 = 0.3666667\\)\n- \\(0.3666667 + \\frac{1}{720} \\approx 0.3666667 + 0.0013889 = 0.3680556\\)\n- \\(0.3680556 - \\frac{1}{5040} \\approx 0.3680556 - 0.0001984 = 0.3678572\\)\n\nSo the sum is approximately \\(0.367857142857...\\)\n\n---\n\n**Step 4: Multiply by \\(7!\\)**\n\n\\[\nD_7 = 5040 \\times 0.367857142857\\ldots\n\\]\n\nLet's compute exactly using fractions:\n\n\\[\n\\sum_{k=0}^{7} \\frac{(-1)^k}{k!} \n= \\frac{1}{2!} - \\frac{1}{3!} + \\frac{1}{4!} - \\frac{1}{5!} + \\frac{1}{6!} - \\frac{1}{7!}\n\\]\n\nWrite with common denominator \\(7! = 5040\\):\n\n- \\(\\frac{1}{2!} = \\frac{2520}{5040}\\)\n- \\(\\frac{1}{3!} = \\frac{840}{5040}\\)\n- \\(\\frac{1}{4!} = \\frac{210}{5040}\\)\n- \\(\\frac{1}{5!} = \\frac{42}{5040}\\)\n- \\(\\frac{1}{6!} = \\frac{7}{5040}\\)\n- \\(\\frac{1}{7!} = \\frac{1}{5040}\\)\n\nNow alternate signs:\n\n\\[\n\\left( \\frac{2520}{5040} - \\frac{840}{5040} \\right) \n= \\frac{1680}{5040}\n\\]\n\\[\n\\frac{1680}{5040} + \\frac{210}{5040} = \\frac{1890}{5040}\n\\]\n\\[\n\\frac{1890}{5040} - \\frac{42}{5040} = \\frac{1848}{5040}\n\\]\n\\[\n\\frac{1848}{5040} + \\frac{7}{5040} = \\frac{1855}{5040}\n\\]\n\\[\n\\frac{1855}{5040} - \\frac{1}{5040} = \\frac{1854}{5040}\n\\]\n\nSo the sum is \\(\\frac{1854}{5040}\\).\n\n---\n\n**Step 5: Multiply by \\(7!\\)**\n\n\\[\nD_7 = 5040 \\times \\frac{1854}{5040} = 1854\n\\]\n\n---\n\n**Step 6: Quick check with known derangement numbers**\n\nKnown small derangements: \n\\(D_1 = 0, D_2 = 1, D_3 = 2, D_4 = 9, D_5 = 44, D_6 = 265, D_7 = 1854\\). \nYes, matches known sequence.\n\n---\n\n**Final answer:**\n\nAnswer: 1854",
|
||||
"turns": 1,
|
||||
"cacheHitRatio": 0,
|
||||
"costUsd": 0.00127253,
|
||||
"claudeEquivalentUsd": 0.017292,
|
||||
"harvestedTurns": 0,
|
||||
"totalSubgoals": 0,
|
||||
"totalUncertainties": 0,
|
||||
"totalHypotheses": 0,
|
||||
"totalRejectedPaths": 0
|
||||
},
|
||||
{
|
||||
"taskId": "derangements_d7",
|
||||
"mode": "reasoner",
|
||||
"repeat": 1,
|
||||
"verdict": "pass",
|
||||
"finalAgentMessage": "The number of derangements of \\(n\\) distinct objects, denoted \\(D_n\\), counts permutations with no fixed points. For \\(n = 7\\), this can be computed using the recurrence \\(D_n = (n-1)(D_{n-1} + D_{n-2})\\) with initial values \\(D_1 = 0\\) and \\(D_2 = 1\\). \nThus: \n\\(D_3 = 2(1+0) = 2\\), \n\\(D_4 = 3(2+1) = 9\\), \n\\(D_5 = 4(9+2) = 44\\), \n\\(D_6 = 5(44+9) = 265\\), \n\\(D_7 = 6(265+44) = 1854\\).\n\nAnswer: 1854",
|
||||
"turns": 1,
|
||||
"cacheHitRatio": 0.7191011235955056,
|
||||
"costUsd": 0.00349167,
|
||||
"claudeEquivalentUsd": 0.024027,
|
||||
"harvestedTurns": 0,
|
||||
"totalSubgoals": 0,
|
||||
"totalUncertainties": 0,
|
||||
"totalHypotheses": 0,
|
||||
"totalRejectedPaths": 0
|
||||
},
|
||||
{
|
||||
"taskId": "derangements_d7",
|
||||
"mode": "reasoner-harvest",
|
||||
"repeat": 1,
|
||||
"verdict": "pass",
|
||||
"finalAgentMessage": "The number of derangements of \\(n\\) elements, denoted \\(D_n\\), counts permutations with no fixed points. For \\(n=7\\), this can be computed using the recurrence \\(D_n = (n-1)(D_{n-1} + D_{n-2})\\) with initial values \\(D_0 = 1\\) and \\(D_1 = 0\\). Applying the recurrence yields \\(D_2 = 1\\), \\(D_3 = 2\\), \\(D_4 = 9\\), \\(D_5 = 44\\), \\(D_6 = 265\\), and finally \\(D_7 = 6 \\times (265 + 44) = 1854\\).\n\nAnswer: 1854",
|
||||
"turns": 1,
|
||||
"cacheHitRatio": 0.7191011235955056,
|
||||
"costUsd": 0.0028434299999999997,
|
||||
"claudeEquivalentUsd": 0.019587,
|
||||
"harvestedTurns": 1,
|
||||
"totalSubgoals": 3,
|
||||
"totalUncertainties": 2,
|
||||
"totalHypotheses": 2,
|
||||
"totalRejectedPaths": 2
|
||||
},
|
||||
{
|
||||
"taskId": "euler_quadratic_break",
|
||||
"mode": "baseline",
|
||||
"repeat": 1,
|
||||
"verdict": "pass",
|
||||
"finalAgentMessage": "Let’s check \\( f(n) = n^2 + n + 41 \\) for small \\( n \\):\n\n- \\( n = 0 \\): \\( f(0) = 41 \\) (prime) \n- \\( n = 1 \\): \\( f(1) = 1 + 1 + 41 = 43 \\) (prime) \n- \\( n = 2 \\): \\( f(2) = 4 + 2 + 41 = 47 \\) (prime) \n- \\( n = 3 \\): \\( f(3) = 9 + 3 + 41 = 53 \\) (prime) \n- \\( n = 4 \\): \\( f(4) = 16 + 4 + 41 = 61 \\) (prime) \n- \\( n = 5 \\): \\( f(5) = 25 + 5 + 41 = 71 \\) (prime) \n- \\( n = 6 \\): \\( f(6) = 36 + 6 + 41 = 83 \\) (prime) \n- \\( n = 7 \\): \\( f(7) = 49 + 7 + 41 = 97 \\) (prime) \n- \\( n = 8 \\): \\( f(8) = 64 + 8 + 41 = 113 \\) (prime) \n- \\( n = 9 \\): \\( f(9) = 81 + 9 + 41 = 131 \\) (prime) \n- \\( n = 10 \\): \\( f(10) = 100 + 10 + 41 = 151 \\) (prime) \n\nWe can keep going, but the first known counterexample for this famous Euler polynomial is \\( n = 40 \\), because \n\\[\nf(40) = 40^2 + 40 + 41 = 1600 + 40 + 41 = 1681.\n\\] \nCheck if \\( 1681 \\) is prime: \n\\( 1681 = 41^2 \\) (since \\( 41 \\times 41 = 1681 \\)), so it’s composite.\n\nBut wait — let’s check if there’s a smaller \\( n \\) where \\( f(n) \\) is composite. \nWe can test \\( n = 41 \\): \n\\( f(41) = 41^2 + 41 + 41 = 1681 + 82 = 1763 \\), which is \\( 41 \\times 43 \\) (since \\( 1763/41 = 43 \\)), so composite. But \\( n = 41 \\) is larger than \\( n = 40 \\).\n\nCheck \\( n = 39 \\): \\( f(39) = 1521 + 39 + 41 = 1601 \\). Test divisibility: not divisible by primes up to \\( \\sqrt{1601} \\approx 40 \\), seems prime. \n\nCheck \\( n = 40 \\) is indeed the first composite? Let’s check \\( n = 1 \\) to \\( 39 \\) quickly for a smaller counterexample: \nWe can note \\( f(n) = n(n+1) + 41 \\). If \\( 41 \\mid f(n) \\), then \\( 41 \\mid n(n+1) \\). \nThat happens when \\( n \\equiv 0 \\pmod{41} \\) or \\( n \\equiv 40 \\pmod{41} \\). \nThe smallest positive such \\( n \\) is \\( n = 40 \\) (since \\( n=41 \\) is larger). \nSo for \\( n = 40 \\), \\( f(40) = 40 \\times 41 + 41 = 41 \\times 41 \\) is composite. \n\nCheck \\( n = 0 \\) to \\( 39 \\): no multiple of 41 except \\( n=0 \\) (which gives 41, prime). So \\( n=40 \\) is indeed the first nonnegative integer where \\( f(n) \\) is composite.\n\nThus smallest \\( n \\) is \\( 40 \\), \\( f(40) = 1681 = 41^2 \\).\n\n**Answer:** 40",
|
||||
"turns": 1,
|
||||
"cacheHitRatio": 0,
|
||||
"costUsd": 0.00098535,
|
||||
"claudeEquivalentUsd": 0.013365,
|
||||
"harvestedTurns": 0,
|
||||
"totalSubgoals": 0,
|
||||
"totalUncertainties": 0,
|
||||
"totalHypotheses": 0,
|
||||
"totalRejectedPaths": 0
|
||||
},
|
||||
{
|
||||
"taskId": "euler_quadratic_break",
|
||||
"mode": "reasoner",
|
||||
"repeat": 1,
|
||||
"verdict": "pass",
|
||||
"finalAgentMessage": "The smallest nonnegative integer \\(n\\) for which \\(f(n) = n^2 + n + 41\\) is composite is \\(n = 40\\). At this value, \\(f(40) = 40^2 + 40 + 41 = 1681 = 41^2\\), which is not prime.\n\nAnswer: 40",
|
||||
"turns": 1,
|
||||
"cacheHitRatio": 0.6095238095238096,
|
||||
"costUsd": 0.0014309199999999998,
|
||||
"claudeEquivalentUsd": 0.0099,
|
||||
"harvestedTurns": 0,
|
||||
"totalSubgoals": 0,
|
||||
"totalUncertainties": 0,
|
||||
"totalHypotheses": 0,
|
||||
"totalRejectedPaths": 0
|
||||
},
|
||||
{
|
||||
"taskId": "euler_quadratic_break",
|
||||
"mode": "reasoner-harvest",
|
||||
"repeat": 1,
|
||||
"verdict": "pass",
|
||||
"finalAgentMessage": "The polynomial \\(f(n) = n^2 + n + 41\\) is known to produce primes for \\(n = 0, 1, 2, \\dots, 39\\). At \\(n = 40\\), we have \\(f(40) = 40^2 + 40 + 41 = 1681\\), and \\(1681 = 41^2\\), which is composite. Therefore, \\(n = 40\\) is the smallest nonnegative integer where \\(f(n)\\) fails to be prime.\n\nAnswer: 40",
|
||||
"turns": 1,
|
||||
"cacheHitRatio": 0.6095238095238096,
|
||||
"costUsd": 0.0025938099999999998,
|
||||
"claudeEquivalentUsd": 0.017865,
|
||||
"harvestedTurns": 1,
|
||||
"totalSubgoals": 3,
|
||||
"totalUncertainties": 2,
|
||||
"totalHypotheses": 3,
|
||||
"totalRejectedPaths": 2
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,312 @@
|
||||
/**
|
||||
* Harvest-bench runner.
|
||||
*
|
||||
* Usage:
|
||||
* npx tsx benchmarks/harvest/runner.ts # all tasks, all modes, 1 repeat
|
||||
* npx tsx benchmarks/harvest/runner.ts --task mod7_list
|
||||
* npx tsx benchmarks/harvest/runner.ts --mode reasoner-harvest --repeats 3
|
||||
* npx tsx benchmarks/harvest/runner.ts --transcripts-dir transcripts/
|
||||
* npx tsx benchmarks/harvest/runner.ts --dry # smoke test wiring, no API
|
||||
*
|
||||
* Writes results.json. Render report.md with `report.ts`.
|
||||
*/
|
||||
|
||||
import { type WriteStream, mkdirSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { pathToFileURL } from "node:url";
|
||||
import {
|
||||
CacheFirstLoop,
|
||||
DeepSeekClient,
|
||||
ImmutablePrefix,
|
||||
claudeEquivalentCost,
|
||||
loadDotenv,
|
||||
} from "../../src/index.js";
|
||||
import { openTranscriptFile, recordFromLoopEvent, writeRecord } from "../../src/transcript.js";
|
||||
import { TASKS } from "./tasks.js";
|
||||
import type {
|
||||
HarvestBenchMeta,
|
||||
HarvestBenchReport,
|
||||
HarvestMode,
|
||||
HarvestRunResult,
|
||||
HarvestTask,
|
||||
} from "./types.js";
|
||||
import { ALL_MODES } from "./types.js";
|
||||
|
||||
loadDotenv();
|
||||
|
||||
interface CliArgs {
|
||||
taskFilter: string | null;
|
||||
modes: HarvestMode[];
|
||||
repeats: number;
|
||||
outPath: string | null;
|
||||
transcriptsDir: string | null;
|
||||
/** Per-HTTP-call timeout in ms. Default 300_000 (5 min) — reasoner + harvest runs legitimately need this. */
|
||||
timeoutMs: number;
|
||||
dry: boolean;
|
||||
verbose: boolean;
|
||||
}
|
||||
|
||||
function parseArgs(argv: string[]): CliArgs {
|
||||
const out: CliArgs = {
|
||||
taskFilter: null,
|
||||
modes: [...ALL_MODES],
|
||||
repeats: 1,
|
||||
outPath: null,
|
||||
transcriptsDir: null,
|
||||
timeoutMs: 300_000,
|
||||
dry: false,
|
||||
verbose: false,
|
||||
};
|
||||
for (let i = 0; i < argv.length; i++) {
|
||||
const a = argv[i];
|
||||
if (a === "--task") out.taskFilter = argv[++i] ?? null;
|
||||
else if (a === "--mode") {
|
||||
const v = (argv[++i] ?? "").toLowerCase() as HarvestMode;
|
||||
if ((ALL_MODES as string[]).includes(v)) out.modes = [v];
|
||||
} else if (a === "--repeats") out.repeats = Number.parseInt(argv[++i] ?? "1", 10);
|
||||
else if (a === "--out") out.outPath = argv[++i] ?? null;
|
||||
else if (a === "--transcripts-dir") out.transcriptsDir = argv[++i] ?? null;
|
||||
else if (a === "--timeout") {
|
||||
// Accept seconds for humans, convert to ms internally.
|
||||
const secs = Number.parseInt(argv[++i] ?? "300", 10);
|
||||
if (Number.isFinite(secs) && secs > 0) out.timeoutMs = secs * 1000;
|
||||
} else if (a === "--dry") out.dry = true;
|
||||
else if (a === "--verbose" || a === "-v") out.verbose = true;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// ---------- model resolution ----------
|
||||
|
||||
function modelForMode(mode: HarvestMode): string {
|
||||
if (mode === "baseline") return "deepseek-chat";
|
||||
return "deepseek-reasoner";
|
||||
}
|
||||
|
||||
function harvestForMode(mode: HarvestMode): boolean {
|
||||
return mode === "reasoner-harvest";
|
||||
}
|
||||
|
||||
// ---------- run one task in one mode ----------
|
||||
|
||||
async function runOnce(
|
||||
task: HarvestTask,
|
||||
mode: HarvestMode,
|
||||
rep: number,
|
||||
client: DeepSeekClient,
|
||||
transcriptStream: WriteStream | null,
|
||||
): Promise<HarvestRunResult> {
|
||||
const model = modelForMode(mode);
|
||||
const harvest = harvestForMode(mode);
|
||||
|
||||
const prefix = new ImmutablePrefix({ system: task.systemPrompt });
|
||||
const loop = new CacheFirstLoop({
|
||||
client,
|
||||
prefix,
|
||||
model,
|
||||
harvest,
|
||||
stream: false,
|
||||
});
|
||||
const prefixHash = prefix.fingerprint;
|
||||
|
||||
let harvestedTurns = 0;
|
||||
let totalSubgoals = 0;
|
||||
let totalUncertainties = 0;
|
||||
let totalHypotheses = 0;
|
||||
let totalRejectedPaths = 0;
|
||||
let finalText = "";
|
||||
let errorMessage: string | undefined;
|
||||
|
||||
if (transcriptStream) {
|
||||
writeRecord(transcriptStream, {
|
||||
ts: new Date().toISOString(),
|
||||
turn: 1,
|
||||
role: "user",
|
||||
content: task.prompt,
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
for await (const ev of loop.step(task.prompt)) {
|
||||
if (transcriptStream && ev.role !== "assistant_delta") {
|
||||
writeRecord(transcriptStream, recordFromLoopEvent(ev, { model, prefixHash }));
|
||||
}
|
||||
if (ev.role === "assistant_final") {
|
||||
finalText = ev.content;
|
||||
if (ev.planState) {
|
||||
if (
|
||||
ev.planState.subgoals.length +
|
||||
ev.planState.hypotheses.length +
|
||||
ev.planState.uncertainties.length +
|
||||
ev.planState.rejectedPaths.length >
|
||||
0
|
||||
) {
|
||||
harvestedTurns++;
|
||||
totalSubgoals += ev.planState.subgoals.length;
|
||||
totalHypotheses += ev.planState.hypotheses.length;
|
||||
totalUncertainties += ev.planState.uncertainties.length;
|
||||
totalRejectedPaths += ev.planState.rejectedPaths.length;
|
||||
}
|
||||
}
|
||||
} else if (ev.role === "done") {
|
||||
finalText = ev.content || finalText;
|
||||
break;
|
||||
} else if (ev.role === "error") {
|
||||
throw new Error(ev.error ?? "loop error");
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
errorMessage = (err as Error).message;
|
||||
}
|
||||
|
||||
const verdict = errorMessage ? { verdict: "fail" as const, note: errorMessage } : task.check(finalText);
|
||||
|
||||
return {
|
||||
taskId: task.id,
|
||||
mode,
|
||||
repeat: rep + 1,
|
||||
verdict: verdict.verdict,
|
||||
checkNote: verdict.note,
|
||||
finalAgentMessage: finalText,
|
||||
turns: loop.stats.turns.length,
|
||||
cacheHitRatio: loop.stats.aggregateCacheHitRatio,
|
||||
costUsd: loop.stats.totalCost,
|
||||
claudeEquivalentUsd: loop.stats.turns.reduce((s, t) => s + claudeEquivalentCost(t.usage), 0),
|
||||
harvestedTurns,
|
||||
totalSubgoals,
|
||||
totalUncertainties,
|
||||
totalHypotheses,
|
||||
totalRejectedPaths,
|
||||
errorMessage,
|
||||
};
|
||||
}
|
||||
|
||||
// ---------- dry mode ----------
|
||||
|
||||
function runDry(args: CliArgs): HarvestBenchReport {
|
||||
const tasks = filterTasks(args.taskFilter);
|
||||
const results: HarvestRunResult[] = [];
|
||||
for (const task of tasks) {
|
||||
// Exercise each checker with a deliberately wrong reply so we know
|
||||
// the wiring is live — not a pass on empty.
|
||||
const sanity = task.check("Answer: this is not the right answer at all");
|
||||
console.log(`[${task.id}] checker exercises ok (sanity verdict=${sanity.verdict})`);
|
||||
for (const mode of args.modes) {
|
||||
results.push({
|
||||
taskId: task.id,
|
||||
mode,
|
||||
repeat: 1,
|
||||
verdict: "inconclusive",
|
||||
checkNote: "dry-run (no model call)",
|
||||
finalAgentMessage: "[dry-run]",
|
||||
turns: 0,
|
||||
cacheHitRatio: 0,
|
||||
costUsd: 0,
|
||||
claudeEquivalentUsd: 0,
|
||||
harvestedTurns: 0,
|
||||
totalSubgoals: 0,
|
||||
totalUncertainties: 0,
|
||||
totalHypotheses: 0,
|
||||
totalRejectedPaths: 0,
|
||||
});
|
||||
}
|
||||
}
|
||||
return { meta: buildMeta(args, tasks.length), results };
|
||||
}
|
||||
|
||||
// ---------- main ----------
|
||||
|
||||
function filterTasks(filter: string | null): HarvestTask[] {
|
||||
if (!filter) return TASKS;
|
||||
const t = TASKS.find((x) => x.id === filter);
|
||||
if (!t) throw new Error(`unknown task: ${filter}`);
|
||||
return [t];
|
||||
}
|
||||
|
||||
function buildMeta(args: CliArgs, taskCount: number): HarvestBenchMeta {
|
||||
return {
|
||||
date: new Date().toISOString(),
|
||||
repeatsPerTask: args.repeats,
|
||||
taskCount,
|
||||
modesRun: args.modes,
|
||||
reasonixVersion: "0.2.2",
|
||||
};
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const args = parseArgs(process.argv.slice(2));
|
||||
|
||||
if (args.dry) {
|
||||
const report = runDry(args);
|
||||
writeReport(report, args.outPath);
|
||||
return;
|
||||
}
|
||||
|
||||
const client = new DeepSeekClient({ timeoutMs: args.timeoutMs });
|
||||
const tasks = filterTasks(args.taskFilter);
|
||||
|
||||
if (args.transcriptsDir) mkdirSync(args.transcriptsDir, { recursive: true });
|
||||
|
||||
const results: HarvestRunResult[] = [];
|
||||
for (const task of tasks) {
|
||||
for (let rep = 0; rep < args.repeats; rep++) {
|
||||
for (const mode of args.modes) {
|
||||
let stream: WriteStream | null = null;
|
||||
if (args.transcriptsDir) {
|
||||
const fname = `${task.id}.${mode}.r${rep + 1}.jsonl`;
|
||||
stream = openTranscriptFile(join(args.transcriptsDir, fname), {
|
||||
version: 1,
|
||||
source: `harvest-bench/${mode}`,
|
||||
model: modelForMode(mode),
|
||||
task: task.id,
|
||||
mode,
|
||||
repeat: rep + 1,
|
||||
startedAt: new Date().toISOString(),
|
||||
});
|
||||
}
|
||||
const started = Date.now();
|
||||
let result: HarvestRunResult;
|
||||
try {
|
||||
result = await runOnce(task, mode, rep, client, stream);
|
||||
} finally {
|
||||
stream?.end();
|
||||
}
|
||||
const elapsed = ((Date.now() - started) / 1000).toFixed(1);
|
||||
console.log(
|
||||
`[${task.id}/${mode}/r${rep + 1}] verdict=${result.verdict}` +
|
||||
` cache=${(result.cacheHitRatio * 100).toFixed(1)}%` +
|
||||
` cost=$${result.costUsd.toFixed(6)}` +
|
||||
` harvest=${result.harvestedTurns}:${result.totalSubgoals}s/${result.totalUncertainties}u` +
|
||||
` (${elapsed}s)` +
|
||||
(result.checkNote ? ` ${result.checkNote}` : ""),
|
||||
);
|
||||
results.push(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const report: HarvestBenchReport = { meta: buildMeta(args, tasks.length), results };
|
||||
writeReport(report, args.outPath);
|
||||
}
|
||||
|
||||
function writeReport(report: HarvestBenchReport, outPath: string | null): void {
|
||||
const path =
|
||||
outPath ?? `benchmarks/harvest/results-${new Date().toISOString().replace(/[:.]/g, "-")}.json`;
|
||||
writeFileSync(path, `${JSON.stringify(report, null, 2)}\n`, "utf8");
|
||||
console.log(`wrote ${path}`);
|
||||
}
|
||||
|
||||
function isMain(): boolean {
|
||||
const entry = process.argv[1];
|
||||
if (!entry) return false;
|
||||
return import.meta.url === pathToFileURL(entry).href;
|
||||
}
|
||||
|
||||
if (isMain()) {
|
||||
main().catch((err) => {
|
||||
console.error(err);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
|
||||
export { main as runHarvestBench };
|
||||
@@ -0,0 +1,171 @@
|
||||
/**
|
||||
* Seed reasoning tasks for the harvest eval harness.
|
||||
*
|
||||
* Each task has:
|
||||
* - a minimal system prompt (so the comparison is about the model, not
|
||||
* the prompt)
|
||||
* - a single user question
|
||||
* - a deterministic checker (regex + set/value compare)
|
||||
*
|
||||
* When adding a new task, prefer problems where:
|
||||
* - the answer has a clean shape (a number, a small set, a yes/no +
|
||||
* explanation) — easier to check
|
||||
* - reasoning actually matters (so harvest has signal to extract);
|
||||
* trivia questions are out of scope
|
||||
* - there's a known-good answer; judgment calls are out of scope
|
||||
*/
|
||||
|
||||
import type { HarvestTask } from "./types.js";
|
||||
|
||||
const CONCISE_SYSTEM = `You are a precise reasoner. Think carefully, then state your final answer on a clearly-labeled line starting with "Answer:".`;
|
||||
|
||||
/**
|
||||
* Parse all non-negative integers out of a string. Handles commas,
|
||||
* ranges written as "2-4" (expands to 2,3,4), and ignores numbers that
|
||||
* look like formula references (e.g. "n^2", "mod 7") by only accepting
|
||||
* integers after we strip common LaTeX decorations.
|
||||
*/
|
||||
function extractIntegers(text: string): number[] {
|
||||
// Strip LaTeX delimiters so n_1 / n^2 / \{ ... \} don't confuse us.
|
||||
const cleaned = text
|
||||
.replace(/\\[a-zA-Z]+/g, " ") // \frac, \mod etc.
|
||||
.replace(/[{}\\]/g, " ")
|
||||
.replace(/[_^]\d+/g, " "); // subscript/superscript numbers
|
||||
// Expand ranges: "2-4" → "2,3,4" (only for small gaps)
|
||||
const rangeExpanded = cleaned.replace(/(\d+)\s*[-–]\s*(\d+)/g, (_, a, b) => {
|
||||
const lo = Number.parseInt(a, 10);
|
||||
const hi = Number.parseInt(b, 10);
|
||||
if (!Number.isFinite(lo) || !Number.isFinite(hi) || hi - lo > 50) return `${a} ${b}`;
|
||||
const out: number[] = [];
|
||||
for (let i = Math.min(lo, hi); i <= Math.max(lo, hi); i++) out.push(i);
|
||||
return out.join(" ");
|
||||
});
|
||||
const matches = rangeExpanded.match(/-?\d+/g) ?? [];
|
||||
return matches.map((m) => Number.parseInt(m, 10)).filter((n) => Number.isFinite(n));
|
||||
}
|
||||
|
||||
/** Extract content after the last "Answer:" label (case-insensitive). */
|
||||
function extractAnswerLine(text: string): string {
|
||||
const matches = [...text.matchAll(/answer\s*[::]\s*([^\n]+)/gi)];
|
||||
if (matches.length === 0) return text;
|
||||
return matches[matches.length - 1]![1]!.trim();
|
||||
}
|
||||
|
||||
// ---------- expected answers ----------
|
||||
|
||||
/** Positive n ≤ 100 such that n^2 + n + 1 ≡ 0 (mod 7). */
|
||||
const MOD7_EXPECTED: number[] = (() => {
|
||||
const out: number[] = [];
|
||||
for (let n = 1; n <= 100; n++) {
|
||||
if ((n * n + n + 1) % 7 === 0) out.push(n);
|
||||
}
|
||||
return out;
|
||||
})();
|
||||
|
||||
/**
|
||||
* Single-integer checker. Pulls the first plausible integer from the last
|
||||
* "Answer:" line; compares for exact equality.
|
||||
*/
|
||||
function checkSingleInt(expected: number) {
|
||||
return (reply: string) => {
|
||||
const answerLine = extractAnswerLine(reply);
|
||||
const nums = extractIntegers(answerLine);
|
||||
if (nums.length === 0) return { verdict: "fail" as const, note: "no number in Answer line" };
|
||||
const n = nums[0]!;
|
||||
if (n === expected) return { verdict: "pass" as const };
|
||||
return { verdict: "fail" as const, note: `got ${n}, expected ${expected}` };
|
||||
};
|
||||
}
|
||||
|
||||
// ---------- tasks ----------
|
||||
|
||||
export const TASKS: HarvestTask[] = [
|
||||
{
|
||||
id: "mod7_list",
|
||||
description:
|
||||
"Number theory — find all positive n ≤ 100 with n^2+n+1 ≡ 0 (mod 7). 29-element set. Classic R1 scratch-work territory.",
|
||||
systemPrompt: CONCISE_SYSTEM,
|
||||
prompt:
|
||||
"Find all positive integers n with n ≤ 100 such that n^2 + n + 1 is divisible by 7. Briefly justify, then end with the full list on a line starting with \"Answer:\".",
|
||||
check: (reply) => {
|
||||
const answerLine = extractAnswerLine(reply);
|
||||
const found = new Set(extractIntegers(answerLine).filter((n) => n >= 1 && n <= 100));
|
||||
const expected = new Set(MOD7_EXPECTED);
|
||||
if (found.size === 0) {
|
||||
return { verdict: "fail", note: "no integers extracted from Answer line" };
|
||||
}
|
||||
// Exact set equality — both containment directions.
|
||||
for (const n of expected) if (!found.has(n)) return { verdict: "fail", note: `missing n=${n}` };
|
||||
for (const n of found) if (!expected.has(n)) return { verdict: "fail", note: `extra n=${n}` };
|
||||
return { verdict: "pass" };
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
id: "flips_until_3heads",
|
||||
description:
|
||||
"Probability — expected coin flips until 3 consecutive heads. Answer: 14. Tests whether R1 derives via recurrence or via memorized result.",
|
||||
systemPrompt: CONCISE_SYSTEM,
|
||||
prompt:
|
||||
"A fair coin is flipped repeatedly until you see 3 heads in a row. What is the expected number of total flips? Give a single integer on a line starting with \"Answer:\".",
|
||||
check: (reply) => {
|
||||
const answerLine = extractAnswerLine(reply);
|
||||
const nums = extractIntegers(answerLine);
|
||||
if (nums.length === 0) return { verdict: "fail", note: "no number in Answer line" };
|
||||
// Accept the first sensible number — sometimes agents write "Answer: 14 flips".
|
||||
const n = nums[0]!;
|
||||
if (n === 14) return { verdict: "pass" };
|
||||
return { verdict: "fail", note: `got ${n}, expected 14` };
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
id: "three_hats",
|
||||
description:
|
||||
"Logic — three people wear red/blue hats, at least one red, they're asked in order. First two say no, third says yes. What color? Answer: red (deducible because if third were blue, the first two could see one red + one unknown and wouldn't have said no on their full first round, for most configurations the third can only be certain if red).",
|
||||
systemPrompt: CONCISE_SYSTEM,
|
||||
prompt:
|
||||
'Three people wear hats that are each red or blue. They are told at least one hat is red. Each can see the other two hats but not their own. They are asked in order: "Do you know your hat color?" The first two answer no. The third answers yes. What color is the third person\'s hat? Give a one-word answer on a line starting with "Answer:".',
|
||||
check: (reply) => {
|
||||
const answerLine = extractAnswerLine(reply).toLowerCase();
|
||||
// Accept "red" as a standalone word (not "redirected" etc).
|
||||
if (/\bred\b/.test(answerLine) && !/\bblue\b/.test(answerLine)) {
|
||||
return { verdict: "pass" };
|
||||
}
|
||||
if (/\bblue\b/.test(answerLine)) return { verdict: "fail", note: "answered blue" };
|
||||
return { verdict: "fail", note: "no clear color in Answer line" };
|
||||
},
|
||||
},
|
||||
|
||||
// ---------- hard tasks (picked for known V3 failure modes) ----------
|
||||
|
||||
{
|
||||
id: "pseudoprime_base2",
|
||||
description:
|
||||
"Number theory — smallest composite n > 1 such that 2^n ≡ 2 (mod n). This is the smallest Fermat pseudoprime to base 2. Answer: 341 (= 11·31). V3 frequently answers 561 (Carmichael / wrong base-2 property) or 9 (not actually a pseudoprime to base 2, verifying the model isn't computing). R1 usually gets this right.",
|
||||
systemPrompt: CONCISE_SYSTEM,
|
||||
prompt:
|
||||
'Find the smallest composite integer n > 1 such that 2^n is congruent to 2 modulo n (i.e., n is a Fermat pseudoprime to base 2). Briefly justify, then give a single integer on a line starting with "Answer:".',
|
||||
check: checkSingleInt(341),
|
||||
},
|
||||
|
||||
{
|
||||
id: "derangements_d7",
|
||||
description:
|
||||
"Combinatorics — number of derangements of 7 elements. Answer: 1854 (D_7 = 7! · (1 − 1/1! + 1/2! − 1/3! + … ± 1/7!) = 5040 · 0.367857… = 1854). V3 sometimes approximates via n!/e and rounds wrong, or confuses with D_6=265 or D_8=14833. R1's explicit recurrence D_n = (n-1)(D_{n-1}+D_{n-2}) avoids the mistake.",
|
||||
systemPrompt: CONCISE_SYSTEM,
|
||||
prompt:
|
||||
'How many permutations of {1, 2, 3, 4, 5, 6, 7} have no fixed points? (This is D_7, the derangement number.) Briefly justify, then give a single integer on a line starting with "Answer:".',
|
||||
check: checkSingleInt(1854),
|
||||
},
|
||||
|
||||
{
|
||||
id: "euler_quadratic_break",
|
||||
description:
|
||||
"Number theory — smallest nonneg integer n where n^2 + n + 41 is NOT prime. Euler's prime-generating polynomial famously produces primes for n = 0..39 and first fails at n = 40 (40²+40+41 = 1681 = 41²). V3 often confuses this with the related n²-n+41 (first fails at 41) or cites the wrong threshold. R1 checks small n systematically.",
|
||||
systemPrompt: CONCISE_SYSTEM,
|
||||
prompt:
|
||||
'Consider the polynomial f(n) = n^2 + n + 41 for n = 0, 1, 2, …. What is the smallest nonneg integer n at which f(n) fails to be prime? Briefly justify (including the value of f(n) at that point), then give just the integer n on a line starting with "Answer:".',
|
||||
check: checkSingleInt(40),
|
||||
},
|
||||
];
|
||||
@@ -0,0 +1,82 @@
|
||||
/**
|
||||
* Types for the harvest eval harness.
|
||||
*
|
||||
* Scope: this is deliberately NOT τ-bench-lite. These tasks:
|
||||
* - are single-turn Q/A (no user simulator, no DB)
|
||||
* - target reasoning-heavy problems (math, logic, planning)
|
||||
* - use deterministic checkers (regex extraction + set/value compare),
|
||||
* never an LLM judge
|
||||
*
|
||||
* The point is to measure Pillar 2 (harvest) the same way τ-bench-lite
|
||||
* measures Pillar 1 (cache-first): isolate one variable, produce numbers
|
||||
* anyone can reproduce.
|
||||
*/
|
||||
|
||||
export type HarvestMode =
|
||||
/** deepseek-chat, no Reasonix tricks. Floor reference for answer quality on reasoning tasks (V3 at its best). */
|
||||
| "baseline"
|
||||
/** deepseek-reasoner, no harvest. Isolates "does reasoner help over chat on these problems?" */
|
||||
| "reasoner"
|
||||
/** deepseek-reasoner + harvest. Isolates "does the extra V3 harvest call add quality / change behavior?" */
|
||||
| "reasoner-harvest";
|
||||
|
||||
export const ALL_MODES: HarvestMode[] = ["baseline", "reasoner", "reasoner-harvest"];
|
||||
|
||||
/**
|
||||
* Checker verdict. We don't use boolean directly because "maybe" is real
|
||||
* — e.g. "answer in the right shape but can't verify without running the
|
||||
* program". For v0.3 we only use {pass, fail}, but the shape leaves room.
|
||||
*/
|
||||
export type CheckVerdict = "pass" | "fail" | "inconclusive";
|
||||
|
||||
export interface HarvestTask {
|
||||
id: string;
|
||||
/** One-line human description, not shown to the model. */
|
||||
description: string;
|
||||
/** System prompt. Kept minimal so harvest signal can be attributed to the model, not to prompt engineering. */
|
||||
systemPrompt: string;
|
||||
/** The single question. */
|
||||
prompt: string;
|
||||
/**
|
||||
* Check the agent's final reply. Returns pass/fail/inconclusive plus an
|
||||
* optional one-line explanation the report can surface.
|
||||
*
|
||||
* IMPORTANT: must be pure and deterministic. No LLM calls, no file I/O.
|
||||
*/
|
||||
check: (agentReply: string) => { verdict: CheckVerdict; note?: string };
|
||||
}
|
||||
|
||||
export interface HarvestRunResult {
|
||||
taskId: string;
|
||||
mode: HarvestMode;
|
||||
repeat: number;
|
||||
verdict: CheckVerdict;
|
||||
checkNote?: string;
|
||||
finalAgentMessage: string;
|
||||
/** Turns the loop completed (usually 1 for a single-shot Q/A, > 1 if tool-calls happen). */
|
||||
turns: number;
|
||||
cacheHitRatio: number;
|
||||
costUsd: number;
|
||||
claudeEquivalentUsd: number;
|
||||
/** Harvest-specific — only non-zero on reasoner-harvest mode. */
|
||||
harvestedTurns: number;
|
||||
totalSubgoals: number;
|
||||
totalUncertainties: number;
|
||||
totalHypotheses: number;
|
||||
totalRejectedPaths: number;
|
||||
/** Optional error message if the run crashed (model down, timeout, etc). */
|
||||
errorMessage?: string;
|
||||
}
|
||||
|
||||
export interface HarvestBenchMeta {
|
||||
date: string;
|
||||
repeatsPerTask: number;
|
||||
taskCount: number;
|
||||
modesRun: HarvestMode[];
|
||||
reasonixVersion: string;
|
||||
}
|
||||
|
||||
export interface HarvestBenchReport {
|
||||
meta: HarvestBenchMeta;
|
||||
results: HarvestRunResult[];
|
||||
}
|
||||
@@ -1,46 +1,78 @@
|
||||
# Reasonix tool-use eval (τ-bench-lite)
|
||||
|
||||
**Date:** 2026-04-21T12:31:25.027Z
|
||||
**Date:** 2026-04-21T14:57:44.906Z
|
||||
**Agent model:** `deepseek-chat`
|
||||
**User-simulator model:** `deepseek-chat`
|
||||
**Tasks:** 8, repeats × 1
|
||||
**Reasonix version:** 0.0.6
|
||||
**Tasks:** 8, repeats × 3
|
||||
**Reasonix version:** 0.2.1
|
||||
|
||||
## Summary
|
||||
|
||||
| metric | baseline | reasonix | delta |
|
||||
|---|---:|---:|---:|
|
||||
| runs | 8 | 8 | — |
|
||||
| pass rate | 100% | 88% | -13pp |
|
||||
| cache hit | 43.9% | 94.3% | **+50.3pp** |
|
||||
| mean cost / task | $0.002783 | $0.001621 | ×0.58 |
|
||||
| mean turns | 4.6 | 4.6 | — |
|
||||
| mean tool calls | 2.8 | 3.1 | — |
|
||||
| runs | 24 | 24 | — |
|
||||
| pass rate | 96% | 100% | +4pp |
|
||||
| cache hit | 46.6% | 94.4% | **+47.7pp** |
|
||||
| mean cost / task | $0.002599 | $0.001579 | ×0.61 |
|
||||
| mean turns | 4.4 | 4.6 | — |
|
||||
| mean tool calls | 3.0 | 2.7 | — |
|
||||
|
||||
**Reasonix vs Claude Sonnet 4.6 (estimated, same token counts):**
|
||||
Claude would cost ~$0.039776 / task, so Reasonix saves ~96.1%.
|
||||
Claude would cost ~$0.038203 / task, so Reasonix saves ~96.0%.
|
||||
(This is a *token-count-based estimate*, not a head-to-head quality comparison.)
|
||||
|
||||
## Per-task breakdown
|
||||
|
||||
| task | mode | pass | turns | tools | cache | cost |
|
||||
|---|---|:---:|---:|---:|---:|---:|
|
||||
| t01_address_happy | baseline | ✅ | 3 | 2 | 44.4% | $0.001202 |
|
||||
| t01_address_happy | reasonix | ✅ | 3 | 3 | 94.8% | $0.000875 |
|
||||
| t02_address_not_allowed | baseline | ✅ | 8 | 5 | 43.7% | $0.006048 |
|
||||
| t02_address_not_allowed | reasonix | ✅ | 8 | 3 | 95.9% | $0.002833 |
|
||||
| t03_cancel_processing | baseline | ✅ | 2 | 2 | 54.1% | $0.000843 |
|
||||
| t03_cancel_processing | reasonix | ✅ | 3 | 3 | 93.6% | $0.000832 |
|
||||
| t04_refund_delivered | baseline | ✅ | 2 | 3 | 64.4% | $0.001114 |
|
||||
| t04_refund_delivered | reasonix | ✅ | 3 | 3 | 94.2% | $0.000926 |
|
||||
| t05_refund_not_delivered | baseline | ✅ | 8 | 2 | 22.2% | $0.004724 |
|
||||
| t05_refund_not_delivered | reasonix | ❌ | 8 | 4 | 95.2% | $0.003329 |
|
||||
| t06_multi_order_lookup | baseline | ✅ | 3 | 3 | 52.9% | $0.001692 |
|
||||
| t06_multi_order_lookup | reasonix | ✅ | 4 | 3 | 92.4% | $0.001448 |
|
||||
| t07_wrong_identity | baseline | ✅ | 8 | 2 | 14.9% | $0.005182 |
|
||||
| t07_wrong_identity | reasonix | ✅ | 6 | 3 | 94.9% | $0.002008 |
|
||||
| t08_address_then_cancel | baseline | ✅ | 3 | 3 | 54.9% | $0.001455 |
|
||||
| t08_address_then_cancel | reasonix | ✅ | 2 | 3 | 93.3% | $0.000713 |
|
||||
| t01_address_happy | baseline | ✅ | 3 | 3 | 53.1% | $0.001383 |
|
||||
| t01_address_happy | reasonix | ✅ | 3 | 3 | 94.4% | $0.000896 |
|
||||
| t01_address_happy | baseline | ✅ | 3 | 3 | 53.3% | $0.001405 |
|
||||
| t01_address_happy | reasonix | ✅ | 3 | 2 | 95.0% | $0.000756 |
|
||||
| t01_address_happy | baseline | ✅ | 3 | 2 | 44.0% | $0.001193 |
|
||||
| t01_address_happy | reasonix | ✅ | 3 | 2 | 92.6% | $0.000848 |
|
||||
| t02_address_not_allowed | baseline | ✅ | 8 | 2 | 23.6% | $0.004647 |
|
||||
| t02_address_not_allowed | reasonix | ✅ | 8 | 4 | 95.6% | $0.003067 |
|
||||
| t02_address_not_allowed | baseline | ✅ | 8 | 3 | 29.9% | $0.005585 |
|
||||
| t02_address_not_allowed | reasonix | ✅ | 8 | 2 | 96.2% | $0.002822 |
|
||||
| t02_address_not_allowed | baseline | ✅ | 8 | 7 | 50.7% | $0.007021 |
|
||||
| t02_address_not_allowed | reasonix | ✅ | 8 | 3 | 95.8% | $0.003140 |
|
||||
| t03_cancel_processing | baseline | ✅ | 3 | 3 | 53.3% | $0.001349 |
|
||||
| t03_cancel_processing | reasonix | ✅ | 3 | 3 | 94.9% | $0.000803 |
|
||||
| t03_cancel_processing | baseline | ✅ | 2 | 3 | 64.6% | $0.001041 |
|
||||
| t03_cancel_processing | reasonix | ✅ | 2 | 2 | 93.8% | $0.000563 |
|
||||
| t03_cancel_processing | baseline | ✅ | 3 | 3 | 53.4% | $0.001332 |
|
||||
| t03_cancel_processing | reasonix | ✅ | 2 | 2 | 93.8% | $0.000566 |
|
||||
| t04_refund_delivered | baseline | ✅ | 2 | 2 | 55.9% | $0.001007 |
|
||||
| t04_refund_delivered | reasonix | ✅ | 2 | 3 | 91.0% | $0.000911 |
|
||||
| t04_refund_delivered | baseline | ✅ | 3 | 2 | 44.8% | $0.001268 |
|
||||
| t04_refund_delivered | reasonix | ✅ | 3 | 3 | 93.2% | $0.000941 |
|
||||
| t04_refund_delivered | baseline | ✅ | 3 | 3 | 53.5% | $0.001469 |
|
||||
| t04_refund_delivered | reasonix | ✅ | 3 | 3 | 94.4% | $0.000952 |
|
||||
| t05_refund_not_delivered | baseline | ✅ | 8 | 4 | 41.7% | $0.005369 |
|
||||
| t05_refund_not_delivered | reasonix | ✅ | 7 | 2 | 96.3% | $0.002212 |
|
||||
| t05_refund_not_delivered | baseline | ✅ | 8 | 3 | 30.6% | $0.004762 |
|
||||
| t05_refund_not_delivered | reasonix | ✅ | 8 | 4 | 95.1% | $0.003159 |
|
||||
| t05_refund_not_delivered | baseline | ✅ | 6 | 2 | 24.8% | $0.003128 |
|
||||
| t05_refund_not_delivered | reasonix | ✅ | 6 | 2 | 94.7% | $0.001927 |
|
||||
| t06_multi_order_lookup | baseline | ✅ | 2 | 2 | 52.4% | $0.000913 |
|
||||
| t06_multi_order_lookup | reasonix | ✅ | 3 | 2 | 92.7% | $0.000988 |
|
||||
| t06_multi_order_lookup | baseline | ✅ | 3 | 2 | 41.2% | $0.001530 |
|
||||
| t06_multi_order_lookup | reasonix | ✅ | 3 | 2 | 93.4% | $0.000996 |
|
||||
| t06_multi_order_lookup | baseline | ✅ | 3 | 4 | 60.9% | $0.001920 |
|
||||
| t06_multi_order_lookup | reasonix | ✅ | 3 | 2 | 92.2% | $0.000947 |
|
||||
| t07_wrong_identity | baseline | ❌ | 2 | 2 | 54.9% | $0.000815 |
|
||||
| t07_wrong_identity | reasonix | ✅ | 8 | 2 | 95.5% | $0.002777 |
|
||||
| t07_wrong_identity | baseline | ✅ | 8 | 3 | 26.6% | $0.004953 |
|
||||
| t07_wrong_identity | reasonix | ✅ | 7 | 2 | 95.6% | $0.002356 |
|
||||
| t07_wrong_identity | baseline | ✅ | 8 | 3 | 24.0% | $0.005210 |
|
||||
| t07_wrong_identity | reasonix | ✅ | 8 | 2 | 96.3% | $0.002587 |
|
||||
| t08_address_then_cancel | baseline | ✅ | 3 | 3 | 53.4% | $0.001465 |
|
||||
| t08_address_then_cancel | reasonix | ✅ | 3 | 4 | 94.6% | $0.001174 |
|
||||
| t08_address_then_cancel | baseline | ✅ | 3 | 4 | 62.1% | $0.001677 |
|
||||
| t08_address_then_cancel | reasonix | ✅ | 3 | 5 | 94.1% | $0.001371 |
|
||||
| t08_address_then_cancel | baseline | ✅ | 3 | 5 | 66.5% | $0.001933 |
|
||||
| t08_address_then_cancel | reasonix | ✅ | 3 | 4 | 93.5% | $0.001142 |
|
||||
|
||||
## Scope & caveats
|
||||
|
||||
|
||||
+605
-157
@@ -1,11 +1,11 @@
|
||||
{
|
||||
"meta": {
|
||||
"date": "2026-04-21T12:31:25.027Z",
|
||||
"date": "2026-04-21T14:57:44.906Z",
|
||||
"model": "deepseek-chat",
|
||||
"userSimModel": "deepseek-chat",
|
||||
"taskCount": 8,
|
||||
"repeatsPerTask": 1,
|
||||
"reasonixVersion": "0.0.6"
|
||||
"repeatsPerTask": 3,
|
||||
"reasonixVersion": "0.2.1"
|
||||
},
|
||||
"results": [
|
||||
{
|
||||
@@ -13,14 +13,14 @@
|
||||
"mode": "baseline",
|
||||
"pass": true,
|
||||
"turns": 3,
|
||||
"toolCalls": 2,
|
||||
"cacheHitRatio": 0.4438664932813177,
|
||||
"costUsd": 0.00120248,
|
||||
"claudeEquivalentUsd": 0.018837,
|
||||
"promptTokens": 4614,
|
||||
"completionTokens": 333,
|
||||
"toolCalls": 3,
|
||||
"cacheHitRatio": 0.531435349940688,
|
||||
"costUsd": 0.0013829700000000003,
|
||||
"claudeEquivalentUsd": 0.023388000000000003,
|
||||
"promptTokens": 5901,
|
||||
"completionTokens": 379,
|
||||
"truncated": false,
|
||||
"finalAgentMessage": "Success! I've updated the shipping address for your order o_1002. The new shipping address is now \"5 Birch Rd, NYC, NY 10001\". Your order is still in processing status and will be shipped to this new address."
|
||||
"finalAgentMessage": "Success! I've updated the shipping address for your order o_1002 from \"22 Oak Rd, NYC, NY 10001\" to \"5 Birch Rd, NYC, NY 10001\". \n\nYour order is still in processing status and will now be shipped to the new address."
|
||||
},
|
||||
{
|
||||
"taskId": "t01_address_happy",
|
||||
@@ -28,181 +28,573 @@
|
||||
"pass": true,
|
||||
"turns": 3,
|
||||
"toolCalls": 3,
|
||||
"cacheHitRatio": 0.9479003310681303,
|
||||
"costUsd": 0.0008751300000000002,
|
||||
"claudeEquivalentUsd": 0.022857000000000002,
|
||||
"promptTokens": 5739,
|
||||
"completionTokens": 376,
|
||||
"cacheHitRatio": 0.9444063143445436,
|
||||
"costUsd": 0.0008962600000000001,
|
||||
"claudeEquivalentUsd": 0.023259000000000002,
|
||||
"promptTokens": 5828,
|
||||
"completionTokens": 385,
|
||||
"truncated": false,
|
||||
"finalAgentMessage": "Perfect! I've successfully updated the shipping address for your order o_1002. The new address is now:\n\n**5 Birch Rd, NYC, NY 10001**\n\nYour order of running shoes size 10 will now be shipped to this new address. Is there anything else I can help you with today?"
|
||||
"finalAgentMessage": "Success! I've updated the shipping address for your order o_1002 to **5 Birch Rd, NYC, NY 10001**. \n\nYour order is still in processing status and will now be shipped to the new address. Is there anything else you need help with today?"
|
||||
},
|
||||
{
|
||||
"taskId": "t01_address_happy",
|
||||
"mode": "baseline",
|
||||
"pass": true,
|
||||
"turns": 3,
|
||||
"toolCalls": 3,
|
||||
"cacheHitRatio": 0.533242645808536,
|
||||
"costUsd": 0.00140507,
|
||||
"claudeEquivalentUsd": 0.023703,
|
||||
"promptTokens": 5881,
|
||||
"completionTokens": 404,
|
||||
"truncated": false,
|
||||
"finalAgentMessage": "Great! I've successfully updated the shipping address for your order o_1002. The new address is now: **5 Birch Rd, NYC, NY 10001**.\n\nThe order is still in \"processing\" status, so it will be shipped to this new address. Is there anything else I can help you with?"
|
||||
},
|
||||
{
|
||||
"taskId": "t01_address_happy",
|
||||
"mode": "reasonix",
|
||||
"pass": true,
|
||||
"turns": 3,
|
||||
"toolCalls": 2,
|
||||
"cacheHitRatio": 0.9502183406113537,
|
||||
"costUsd": 0.0007556,
|
||||
"claudeEquivalentUsd": 0.01905,
|
||||
"promptTokens": 4580,
|
||||
"completionTokens": 354,
|
||||
"truncated": false,
|
||||
"finalAgentMessage": "Success! I've updated the shipping address for your order o_1002 to \"5 Birch Rd, NYC, NY 10001\". Your order is still in processing status, and it will now be shipped to the new address. Is there anything else I can help you with today?"
|
||||
},
|
||||
{
|
||||
"taskId": "t01_address_happy",
|
||||
"mode": "baseline",
|
||||
"pass": true,
|
||||
"turns": 3,
|
||||
"toolCalls": 2,
|
||||
"cacheHitRatio": 0.44005156854318866,
|
||||
"costUsd": 0.00119348,
|
||||
"claudeEquivalentUsd": 0.018687000000000002,
|
||||
"promptTokens": 4654,
|
||||
"completionTokens": 315,
|
||||
"truncated": false,
|
||||
"finalAgentMessage": "Perfect! I've successfully updated the shipping address for your order o_1002. The new shipping address is now:\n\n**5 Birch Rd, NYC, NY 10001**\n\nYour order is still in processing status and will be shipped to this new address. Is there anything else I can help you with?"
|
||||
},
|
||||
{
|
||||
"taskId": "t01_address_happy",
|
||||
"mode": "reasonix",
|
||||
"pass": true,
|
||||
"turns": 3,
|
||||
"toolCalls": 2,
|
||||
"cacheHitRatio": 0.9257604764943629,
|
||||
"costUsd": 0.00084767,
|
||||
"claudeEquivalentUsd": 0.020223,
|
||||
"promptTokens": 4701,
|
||||
"completionTokens": 408,
|
||||
"truncated": false,
|
||||
"finalAgentMessage": "Success! I've updated the shipping address for your order o_1002. The new shipping address is now: **5 Birch Rd, NYC, NY 10001**.\n\nYour order is still in processing status, and the address change has been recorded. Is there anything else I can help you with today?"
|
||||
},
|
||||
{
|
||||
"taskId": "t02_address_not_allowed",
|
||||
"mode": "baseline",
|
||||
"pass": true,
|
||||
"turns": 8,
|
||||
"toolCalls": 5,
|
||||
"cacheHitRatio": 0.4369385555156306,
|
||||
"costUsd": 0.006047880000000001,
|
||||
"claudeEquivalentUsd": 0.09382199999999999,
|
||||
"promptTokens": 22264,
|
||||
"completionTokens": 1802,
|
||||
"toolCalls": 2,
|
||||
"cacheHitRatio": 0.2358892823588928,
|
||||
"costUsd": 0.0046473899999999995,
|
||||
"claudeEquivalentUsd": 0.06284100000000001,
|
||||
"promptTokens": 13837,
|
||||
"completionTokens": 1422,
|
||||
"truncated": true,
|
||||
"finalAgentMessage": "As you can see, the system returns the same error. I cannot override this.\n\nI've provided all the information I have:\n- Your order o_1001 is shipped\n- My tools only allow address updates on \"processing\" orders\n- I have no escalation capabilities\n- Your email is [email protected]\n- You have another order (o_1005) that's delivered\n\nIf you need to speak with a human, you must use other contact methods like phone, email, or visiting a store. I don't have those capabilities built into my system.\n\nI'm sorry I can't provide the escalation you're requesting, but I'm being honest about my limitations. Is there anything else within my actual capabilities that I can help you with?"
|
||||
"finalAgentMessage": "I understand you're determined to get this resolved, but I need to be completely transparent about what I can and cannot do:\n\n1. **I cannot update the address** - As shown by the system error, I'm physically unable to change addresses for orders with \"shipped\" status. The tool returns an error and won't allow the change.\n\n2. **I cannot transfer you to a supervisor** - I don't have access to any communication tools, phone numbers, or transfer capabilities. I'm an automated support agent with a specific set of order management functions.\n\n3. **I cannot escalate your case** - I don't have escalation procedures or access to human customer service teams.\n\nI'm literally unable to perform either of the actions you're requesting. Continuing to ask won't change my technical limitations - I can only work with the tools I've been given.\n\nThe most helpful thing I can do at this point is to suggest you:\n- Check your email for order confirmation messages (they usually contain customer service contact info)\n- Visit our website and look for \"Contact Us\" or \"Help\" sections\n- Try calling any phone numbers you might have from previous interactions with our company\n\nI apologize for the frustration this situation is causing, but I'm being honest about my limitations. Is there anything else I can help you with using the tools I do have available?"
|
||||
},
|
||||
{
|
||||
"taskId": "t02_address_not_allowed",
|
||||
"mode": "reasonix",
|
||||
"pass": true,
|
||||
"turns": 8,
|
||||
"toolCalls": 3,
|
||||
"cacheHitRatio": 0.959254361105863,
|
||||
"costUsd": 0.00283263,
|
||||
"claudeEquivalentUsd": 0.069342,
|
||||
"promptTokens": 15879,
|
||||
"completionTokens": 1447,
|
||||
"truncated": true,
|
||||
"finalAgentMessage": "I understand you want this noted, but I need to be honest with you - I don't have a tool to add notes to accounts or orders. The tools I have access to are limited to the specific functions you've seen:\n\n1. Look up orders\n2. Look up users \n3. Update addresses (only for processing orders)\n4. Cancel orders (only for processing orders)\n5. Refund orders (for delivered orders)\n6. List user orders\n\nThere's no tool available to me for adding notes, comments, or annotations to accounts or orders. I can only perform the specific actions listed above.\n\nThe best I can do is confirm that you've requested the address change to \"99 New St, SF, CA\" for order o_1001, but this conversation won't be recorded in the system. You would need to contact customer service through official channels to have this noted in your account.\n\nIs there anything else I can help you with using my available tools?"
|
||||
},
|
||||
{
|
||||
"taskId": "t03_cancel_processing",
|
||||
"mode": "baseline",
|
||||
"pass": true,
|
||||
"turns": 2,
|
||||
"toolCalls": 2,
|
||||
"cacheHitRatio": 0.5411499436302142,
|
||||
"costUsd": 0.0008434600000000001,
|
||||
"claudeEquivalentUsd": 0.014319000000000002,
|
||||
"promptTokens": 3548,
|
||||
"completionTokens": 245,
|
||||
"truncated": false,
|
||||
"finalAgentMessage": "Perfect! I've successfully cancelled your order o_1004. The order has been updated to \"cancelled\" status. You should receive a confirmation email shortly. Is there anything else I can help you with today?"
|
||||
},
|
||||
{
|
||||
"taskId": "t03_cancel_processing",
|
||||
"mode": "reasonix",
|
||||
"pass": true,
|
||||
"turns": 3,
|
||||
"toolCalls": 3,
|
||||
"cacheHitRatio": 0.9357702349869451,
|
||||
"costUsd": 0.0008323500000000001,
|
||||
"claudeEquivalentUsd": 0.022095,
|
||||
"promptTokens": 5745,
|
||||
"completionTokens": 324,
|
||||
"truncated": false,
|
||||
"finalAgentMessage": "You're very welcome, Dev! No trouble at all - that's what we're here for. Your order has been cancelled successfully. Have a great day!"
|
||||
},
|
||||
{
|
||||
"taskId": "t04_refund_delivered",
|
||||
"mode": "baseline",
|
||||
"pass": true,
|
||||
"turns": 2,
|
||||
"toolCalls": 3,
|
||||
"cacheHitRatio": 0.6440251572327044,
|
||||
"costUsd": 0.0011135000000000001,
|
||||
"claudeEquivalentUsd": 0.02031,
|
||||
"promptTokens": 4770,
|
||||
"completionTokens": 400,
|
||||
"truncated": false,
|
||||
"finalAgentMessage": "Great news! I've successfully processed your refund for order o_1003. A refund of $55 has been issued for the broken desk lamp with the reason \"lamp arrived completely broken.\" The refund has been recorded in our system and should be processed back to your original payment method within the standard timeframe for your payment provider.\n\nIs there anything else I can help you with today?"
|
||||
},
|
||||
{
|
||||
"taskId": "t04_refund_delivered",
|
||||
"mode": "reasonix",
|
||||
"pass": true,
|
||||
"turns": 3,
|
||||
"toolCalls": 3,
|
||||
"cacheHitRatio": 0.9416652241647914,
|
||||
"costUsd": 0.0009260900000000001,
|
||||
"claudeEquivalentUsd": 0.023526000000000002,
|
||||
"promptTokens": 5777,
|
||||
"completionTokens": 413,
|
||||
"truncated": false,
|
||||
"finalAgentMessage": "Great news! I've successfully processed a refund of $55 for your order o_1003 (desk lamp). The refund has been recorded with the reason \"arrived broken.\"\n\nYou should see the refund reflected in your original payment method within 3-5 business days, depending on your bank or payment provider's processing time.\n\nIs there anything else I can help you with today?"
|
||||
},
|
||||
{
|
||||
"taskId": "t05_refund_not_delivered",
|
||||
"mode": "baseline",
|
||||
"pass": true,
|
||||
"turns": 8,
|
||||
"toolCalls": 2,
|
||||
"cacheHitRatio": 0.2223009853264337,
|
||||
"costUsd": 0.0047238900000000006,
|
||||
"claudeEquivalentUsd": 0.063351,
|
||||
"promptTokens": 14107,
|
||||
"completionTokens": 1402,
|
||||
"truncated": true,
|
||||
"finalAgentMessage": "I understand you're upset, but I need to be completely transparent: **I cannot process a refund for order o_1002 because it's in \"processing\" status, and the system will not allow it.** This isn't a matter of me refusing to do my job - it's a technical limitation that I cannot bypass.\n\nI've already demonstrated this by attempting the refund and receiving the error: `\"cannot refund: status=processing\"`\n\nSince you've made it clear that:\n1. You won't wait for delivery\n2. You won't cancel the order \n3. I cannot escalate to a supervisor\n4. The system blocks refunds for processing orders\n\nThere is literally nothing more I can do for you within the constraints of this automated system.\n\nYour only path forward to get an immediate resolution is to contact customer service through other channels (phone, email, live chat) where human agents have different system access and authority.\n\nI apologize that I cannot provide the solution you want, but I'm being honest about my limitations."
|
||||
},
|
||||
{
|
||||
"taskId": "t05_refund_not_delivered",
|
||||
"mode": "reasonix",
|
||||
"pass": false,
|
||||
"turns": 8,
|
||||
"toolCalls": 4,
|
||||
"cacheHitRatio": 0.9518716577540107,
|
||||
"costUsd": 0.003329140000000001,
|
||||
"claudeEquivalentUsd": 0.079761,
|
||||
"promptTokens": 17952,
|
||||
"completionTokens": 1727,
|
||||
"cacheHitRatio": 0.9560694920880823,
|
||||
"costUsd": 0.0030673800000000006,
|
||||
"claudeEquivalentUsd": 0.07663199999999999,
|
||||
"promptTokens": 18074,
|
||||
"completionTokens": 1494,
|
||||
"truncated": true,
|
||||
"finalAgentMessage": "I understand you want to escalate to a human supervisor, but I need to be honest about my limitations as an AI support agent.\n\n**What I can do:**\n- Provide you with escalation contact information\n- Confirm your order cancellation details\n- Document your request in this conversation\n\n**What I cannot do:**\n- Transfer you to a human supervisor (no transfer capability)\n- Generate formal documentation\n- Access supervisor contact systems\n\n**Escalation options available to you:**\n\n1. **Phone escalation:** Call 1-800-COMPANY, press 0 for operator, request supervisor\n2. **Email escalation:** Email [email protected] with subject \"ESCALATION: Order o_1002\"\n3. **Online form:** Visit company.com/contact, select \"Supervisor Request\"\n\n**For your escalation, include:**\n- Order ID: o_1002\n- Customer: Bo Wang (u_bo)\n- Issue: Need formal cancellation/refund documentation\n- Reference: This chat conversation\n\nI've provided all the information and tools available to me. For human supervisor assistance, you'll need to use one of the escalation methods above."
|
||||
"finalAgentMessage": "I understand you want this address change request noted, but I need to be honest - I don't have any tools to add notes to accounts or orders. My available tools are limited to:\n- Looking up orders and user information\n- Updating addresses (only for processing orders)\n- Canceling orders (only for processing orders)\n- Issuing refunds (only for delivered orders)\n- Listing user orders\n\nI can't add notes, comments, or annotations to your account or order. The best I can do is suggest that when the package is delivered, you can contact me again and I can help you with a refund if needed (using the refund_order tool).\n\nFor now, I would strongly recommend:\n1. Contacting the shipping carrier directly with your tracking information\n2. Reaching out to our customer service team via email or phone\n3. Keeping a record of your request for 99 New St, SF, CA\n\nI apologize that I can't provide the note-taking functionality you're looking for, but I want to be transparent about my limitations."
|
||||
},
|
||||
{
|
||||
"taskId": "t06_multi_order_lookup",
|
||||
"taskId": "t02_address_not_allowed",
|
||||
"mode": "baseline",
|
||||
"pass": true,
|
||||
"turns": 8,
|
||||
"toolCalls": 3,
|
||||
"cacheHitRatio": 0.29918476711704006,
|
||||
"costUsd": 0.00558507,
|
||||
"claudeEquivalentUsd": 0.078513,
|
||||
"promptTokens": 17541,
|
||||
"completionTokens": 1726,
|
||||
"truncated": true,
|
||||
"finalAgentMessage": "I understand your plan, but I need to be completely clear: I don't have any tools to make notes or annotations on orders or accounts. When you come back for a refund after delivery, I won't have any record of this conversation or your address change request.\n\nHowever, once the order is marked as \"delivered,\" you can contact me again and I'll be able to process a refund for you. At that time, you'll need to provide:\n1. Your name and order ID again\n2. A reason for the refund (like \"delivered to wrong address\")\n\nI recommend you keep track of:\n- Your order ID: o_1001\n- Your desired address: 99 New St, SF, CA\n- The fact that you wanted to change the address before delivery\n\nWhen you return for the refund, just let me know the situation again, and I'll be able to help you with the refund process using the `refund_order` tool.\n\nIs there anything else I can help you with right now?"
|
||||
},
|
||||
{
|
||||
"taskId": "t02_address_not_allowed",
|
||||
"mode": "reasonix",
|
||||
"pass": true,
|
||||
"turns": 8,
|
||||
"toolCalls": 2,
|
||||
"cacheHitRatio": 0.9616535218928475,
|
||||
"costUsd": 0.0028220600000000004,
|
||||
"claudeEquivalentUsd": 0.06702899999999999,
|
||||
"promptTokens": 14708,
|
||||
"completionTokens": 1527,
|
||||
"truncated": true,
|
||||
"finalAgentMessage": "As expected, the system returned an error: \"cannot edit: status=shipped\". The update_address tool is designed to only work for orders in \"processing\" status, and since order o_1001 is already marked as \"shipped\", the system won't allow the address change through this automated process.\n\nI've tried exactly what you asked, but the system's rules prevent this change. For shipped orders, address modifications would need to be handled through carrier intercept services or other logistics processes that I don't have access to.\n\nIs there anything else I can help you with using my available tools?"
|
||||
},
|
||||
{
|
||||
"taskId": "t02_address_not_allowed",
|
||||
"mode": "baseline",
|
||||
"pass": true,
|
||||
"turns": 8,
|
||||
"toolCalls": 7,
|
||||
"cacheHitRatio": 0.5073297860788359,
|
||||
"costUsd": 0.0070210900000000015,
|
||||
"claudeEquivalentUsd": 0.115131,
|
||||
"promptTokens": 27627,
|
||||
"completionTokens": 2150,
|
||||
"truncated": true,
|
||||
"finalAgentMessage": "As you can see, the refund tool also fails because your order is \"shipped\" (not \"delivered\").\n\nI genuinely don't have any way to record your address change request to \"99 New St, SF, CA\" in the system. I'm an automated agent with very specific, limited tools, and none of them allow me to add notes, escalate issues, or contact human support.\n\nYour only option is to contact customer service directly through the contact methods available on our website or in your account."
|
||||
},
|
||||
{
|
||||
"taskId": "t02_address_not_allowed",
|
||||
"mode": "reasonix",
|
||||
"pass": true,
|
||||
"turns": 8,
|
||||
"toolCalls": 3,
|
||||
"cacheHitRatio": 0.958138999251454,
|
||||
"costUsd": 0.0031397900000000004,
|
||||
"claudeEquivalentUsd": 0.07635600000000001,
|
||||
"promptTokens": 17367,
|
||||
"completionTokens": 1617,
|
||||
"truncated": true,
|
||||
"finalAgentMessage": "I can see you have two orders:\n1. o_1001 - wool sweater M - shipped (the one you're asking about)\n2. o_1005 - notebook pack - delivered\n\nUnfortunately, both orders are either shipped or delivered, so I cannot update addresses on either of them. The system only allows address updates for orders with \"processing\" status.\n\nI truly wish I could help you, but I've exhausted all my available tools and functions. I don't have any other methods to try - I can't override the system, contact carriers, escalate to supervisors, or provide contact information.\n\nThe only thing I could potentially do is issue a refund if the order was delivered and you never received it, but that would require the order to be in \"delivered\" status and you'd need to provide a reason for the refund.\n\nI'm sorry I can't be more helpful with your address change request."
|
||||
},
|
||||
{
|
||||
"taskId": "t03_cancel_processing",
|
||||
"mode": "baseline",
|
||||
"pass": true,
|
||||
"turns": 3,
|
||||
"toolCalls": 3,
|
||||
"cacheHitRatio": 0.5285135556248053,
|
||||
"costUsd": 0.00169246,
|
||||
"claudeEquivalentUsd": 0.027954,
|
||||
"promptTokens": 6418,
|
||||
"completionTokens": 580,
|
||||
"cacheHitRatio": 0.5333333333333333,
|
||||
"costUsd": 0.0013487000000000002,
|
||||
"claudeEquivalentUsd": 0.022935000000000004,
|
||||
"promptTokens": 5880,
|
||||
"completionTokens": 353,
|
||||
"truncated": false,
|
||||
"finalAgentMessage": "I've double-checked, and the system shows exactly 2 orders for user ID u_ari (Ari Chen):\n\n1. **Order o_1001**: Wool sweater M - Status: **shipped** - Price: $89\n - Shipping to: 1 Elm St, SF, CA 94110\n\n2. **Order o_1005**: Notebook pack - Status: **delivered** - Price: $22 \n - Delivered to: 1 Elm St, SF, CA 94110\n\nThese are all the orders on file for your account. If you were expecting more orders, it's possible they might be under a different user ID or there could be a discrepancy. Do you have any other order IDs you'd like me to check individually?"
|
||||
"finalAgentMessage": "Perfect! I've successfully cancelled your order o_1004. The order has been updated to \"cancelled\" status. \n\nYou're all set - no further action is needed on your part. Is there anything else I can help you with?"
|
||||
},
|
||||
{
|
||||
"taskId": "t06_multi_order_lookup",
|
||||
"taskId": "t03_cancel_processing",
|
||||
"mode": "reasonix",
|
||||
"pass": true,
|
||||
"turns": 4,
|
||||
"turns": 3,
|
||||
"toolCalls": 3,
|
||||
"cacheHitRatio": 0.9235443037974683,
|
||||
"costUsd": 0.0014482,
|
||||
"claudeEquivalentUsd": 0.03426,
|
||||
"promptTokens": 7900,
|
||||
"completionTokens": 704,
|
||||
"cacheHitRatio": 0.9489849955869374,
|
||||
"costUsd": 0.00080305,
|
||||
"claudeEquivalentUsd": 0.02175,
|
||||
"promptTokens": 5665,
|
||||
"completionTokens": 317,
|
||||
"truncated": false,
|
||||
"finalAgentMessage": "I've confirmed the list again. Here are **all** the orders under your account (u_ari):\n\n1. **Order ID: o_1001**\n - Item: Wool sweater M\n - Status: **shipped**\n - Price: $89\n - Address: 1 Elm St, SF, CA 94110\n\n2. **Order ID: o_1005**\n - Item: Notebook pack\n - Status: **delivered**\n - Price: $22\n - Address: 1 Elm St, SF, CA 94110\n\nThat's the complete list - there are no other orders in your account, and none are in \"processing\" status. Both orders have already progressed beyond the processing stage."
|
||||
"finalAgentMessage": "Your order #o_1004 has been successfully cancelled! No trouble at all - we're happy to help. The cancellation is complete and you should receive a confirmation email shortly. Is there anything else I can assist you with?"
|
||||
},
|
||||
{
|
||||
"taskId": "t07_wrong_identity",
|
||||
"taskId": "t03_cancel_processing",
|
||||
"mode": "baseline",
|
||||
"pass": true,
|
||||
"turns": 2,
|
||||
"toolCalls": 3,
|
||||
"cacheHitRatio": 0.6460567823343849,
|
||||
"costUsd": 0.00104125,
|
||||
"claudeEquivalentUsd": 0.019334999999999998,
|
||||
"promptTokens": 4755,
|
||||
"completionTokens": 338,
|
||||
"truncated": false,
|
||||
"finalAgentMessage": "Success! I've cancelled your order o_1004. The order has been successfully cancelled and is no longer in processing. You should receive a confirmation email shortly. Is there anything else I can help you with today?"
|
||||
},
|
||||
{
|
||||
"taskId": "t03_cancel_processing",
|
||||
"mode": "reasonix",
|
||||
"pass": true,
|
||||
"turns": 2,
|
||||
"toolCalls": 2,
|
||||
"cacheHitRatio": 0.9379310344827586,
|
||||
"costUsd": 0.0005629000000000001,
|
||||
"claudeEquivalentUsd": 0.014204999999999999,
|
||||
"promptTokens": 3480,
|
||||
"completionTokens": 251,
|
||||
"truncated": false,
|
||||
"finalAgentMessage": "Perfect! I've successfully cancelled your order o_1004. The order has been updated to \"cancelled\" status. You should receive a confirmation email shortly. Is there anything else I can help you with?"
|
||||
},
|
||||
{
|
||||
"taskId": "t03_cancel_processing",
|
||||
"mode": "baseline",
|
||||
"pass": true,
|
||||
"turns": 3,
|
||||
"toolCalls": 3,
|
||||
"cacheHitRatio": 0.5341509112587294,
|
||||
"costUsd": 0.0013319700000000002,
|
||||
"claudeEquivalentUsd": 0.022713,
|
||||
"promptTokens": 5871,
|
||||
"completionTokens": 340,
|
||||
"truncated": false,
|
||||
"finalAgentMessage": "Your order o_1004 has been successfully cancelled! The status is now showing as \"cancelled\". You should receive a confirmation email shortly.\n\nIs there anything else I can help you with today?"
|
||||
},
|
||||
{
|
||||
"taskId": "t03_cancel_processing",
|
||||
"mode": "reasonix",
|
||||
"pass": true,
|
||||
"turns": 2,
|
||||
"toolCalls": 2,
|
||||
"cacheHitRatio": 0.9376615914966964,
|
||||
"costUsd": 0.00056647,
|
||||
"claudeEquivalentUsd": 0.014253000000000002,
|
||||
"promptTokens": 3481,
|
||||
"completionTokens": 254,
|
||||
"truncated": false,
|
||||
"finalAgentMessage": "Perfect! I've successfully cancelled your order (o_1004). The order has been updated to \"cancelled\" status. You should receive a confirmation email shortly. Is there anything else I can help you with today?"
|
||||
},
|
||||
{
|
||||
"taskId": "t04_refund_delivered",
|
||||
"mode": "baseline",
|
||||
"pass": true,
|
||||
"turns": 2,
|
||||
"toolCalls": 2,
|
||||
"cacheHitRatio": 0.5592572364827962,
|
||||
"costUsd": 0.00100704,
|
||||
"claudeEquivalentUsd": 0.016821000000000003,
|
||||
"promptTokens": 3662,
|
||||
"completionTokens": 389,
|
||||
"truncated": false,
|
||||
"finalAgentMessage": "Perfect! I've successfully processed your refund request for order o_1003. A refund of $55 has been issued for your desk lamp that arrived broken. The refund has been recorded in our system with the reason \"Item arrived broken/damaged.\"\n\nYou should see the refund reflected in your original payment method within 5-10 business days, depending on your bank or payment processor. Is there anything else I can help you with today?"
|
||||
},
|
||||
{
|
||||
"taskId": "t04_refund_delivered",
|
||||
"mode": "reasonix",
|
||||
"pass": true,
|
||||
"turns": 2,
|
||||
"toolCalls": 3,
|
||||
"cacheHitRatio": 0.9100794646591385,
|
||||
"costUsd": 0.0009113400000000001,
|
||||
"claudeEquivalentUsd": 0.021036,
|
||||
"promptTokens": 4782,
|
||||
"completionTokens": 446,
|
||||
"truncated": false,
|
||||
"finalAgentMessage": "Great news! I've successfully processed your refund for order o_1003. A refund of $55 has been issued for your desk lamp that arrived broken. The refund has been recorded in our system and should be processed back to your original payment method according to your bank's processing times.\n\nIs there anything else I can help you with today?"
|
||||
},
|
||||
{
|
||||
"taskId": "t04_refund_delivered",
|
||||
"mode": "baseline",
|
||||
"pass": true,
|
||||
"turns": 3,
|
||||
"toolCalls": 2,
|
||||
"cacheHitRatio": 0.4484076433121019,
|
||||
"costUsd": 0.0012684000000000003,
|
||||
"claudeEquivalentUsd": 0.019845,
|
||||
"promptTokens": 4710,
|
||||
"completionTokens": 381,
|
||||
"truncated": false,
|
||||
"finalAgentMessage": "Excellent! Your refund has been successfully processed for order o_1003. A refund of $55 has been issued for your desk lamp that arrived broken. The refund has been recorded in our system. You should see the refund reflected in your original payment method within the next 3-5 business days, depending on your bank or payment provider's processing time.\n\nIs there anything else I can help you with today?"
|
||||
},
|
||||
{
|
||||
"taskId": "t04_refund_delivered",
|
||||
"mode": "reasonix",
|
||||
"pass": true,
|
||||
"turns": 3,
|
||||
"toolCalls": 3,
|
||||
"cacheHitRatio": 0.9323050556983719,
|
||||
"costUsd": 0.0009406500000000001,
|
||||
"claudeEquivalentUsd": 0.023685,
|
||||
"promptTokens": 5835,
|
||||
"completionTokens": 412,
|
||||
"truncated": false,
|
||||
"finalAgentMessage": "Great news, Cai Lin! I've successfully processed your refund for order o_1003. A refund of $55 has been issued for your desk lamp that arrived broken. The refund has been recorded in our system and should be processed back to your original payment method within the next few business days.\n\nIs there anything else I can help you with today?"
|
||||
},
|
||||
{
|
||||
"taskId": "t04_refund_delivered",
|
||||
"mode": "baseline",
|
||||
"pass": true,
|
||||
"turns": 3,
|
||||
"toolCalls": 3,
|
||||
"cacheHitRatio": 0.5346700083542189,
|
||||
"costUsd": 0.0014687500000000002,
|
||||
"claudeEquivalentUsd": 0.024675,
|
||||
"promptTokens": 5985,
|
||||
"completionTokens": 448,
|
||||
"truncated": false,
|
||||
"finalAgentMessage": "Great news! I've successfully processed a refund for your order o_1003. A refund of $55 has been issued for the desk lamp that arrived broken. The refund has been recorded with the reason \"Item arrived broken.\"\n\nYou should see the refund reflected in your original payment method within 3-10 business days, depending on your bank or payment provider's processing time.\n\nIs there anything else I can help you with today?"
|
||||
},
|
||||
{
|
||||
"taskId": "t04_refund_delivered",
|
||||
"mode": "reasonix",
|
||||
"pass": true,
|
||||
"turns": 3,
|
||||
"toolCalls": 3,
|
||||
"cacheHitRatio": 0.944082332761578,
|
||||
"costUsd": 0.0009518000000000002,
|
||||
"claudeEquivalentUsd": 0.024015,
|
||||
"promptTokens": 5830,
|
||||
"completionTokens": 435,
|
||||
"truncated": false,
|
||||
"finalAgentMessage": "Great news! Your refund has been successfully processed for order o_1003. A refund of $55 has been issued for your desk lamp that arrived broken. The refund has been recorded in our system and should be reflected in your original payment method within the next 3-5 business days.\n\nIs there anything else I can help you with today?"
|
||||
},
|
||||
{
|
||||
"taskId": "t05_refund_not_delivered",
|
||||
"mode": "baseline",
|
||||
"pass": true,
|
||||
"turns": 8,
|
||||
"toolCalls": 2,
|
||||
"cacheHitRatio": 0.14927362388377982,
|
||||
"costUsd": 0.00518212,
|
||||
"claudeEquivalentUsd": 0.06654299999999999,
|
||||
"promptTokens": 15006,
|
||||
"completionTokens": 1435,
|
||||
"toolCalls": 4,
|
||||
"cacheHitRatio": 0.41699244201198854,
|
||||
"costUsd": 0.0053685500000000014,
|
||||
"claudeEquivalentUsd": 0.08194500000000002,
|
||||
"promptTokens": 19185,
|
||||
"completionTokens": 1626,
|
||||
"truncated": true,
|
||||
"finalAgentMessage": "I cannot cancel order o_1004. The system shows this order belongs to Dev Patel, not Bo Wang. I cannot process any order modifications without proper verification of ownership.\n\nThis conversation regarding the cancellation of order o_1004 is now closed. You will need to contact customer service through official support channels if you wish to pursue this further.\n\nIs there anything else I can help you with today?"
|
||||
"finalAgentMessage": "I can see you only have one order (o_1002), and it's in \"processing\" status. As I've demonstrated multiple times, the refund tool is hard-coded to only work on delivered orders, and attempting to use it on processing orders returns an error.\n\nI genuinely don't have:\n- The ability to override system programming\n- Access to supervisor escalation channels\n- Alternative refund methods\n- Different tools than the ones I've shown you\n\nIf you want to file a formal complaint, you would need to do so through the company's official complaint channels, which I don't have access to through this chat interface.\n\nI've exhausted every option available to me. I can only:\n1. Cancel order o_1002 (which you've refused)\n2. Update the shipping address on order o_1002\n3. Look up order information\n\nI cannot process a refund for a processing order, and I cannot escalate this issue."
|
||||
},
|
||||
{
|
||||
"taskId": "t07_wrong_identity",
|
||||
"taskId": "t05_refund_not_delivered",
|
||||
"mode": "reasonix",
|
||||
"pass": true,
|
||||
"turns": 7,
|
||||
"toolCalls": 2,
|
||||
"cacheHitRatio": 0.9630875453660264,
|
||||
"costUsd": 0.0022117900000000004,
|
||||
"claudeEquivalentUsd": 0.052131000000000004,
|
||||
"promptTokens": 11297,
|
||||
"completionTokens": 1216,
|
||||
"truncated": false,
|
||||
"finalAgentMessage": "I understand you're determined to get immediate resolution, but I need to be completely transparent about what I can and cannot do:\n\n**I cannot:**\n- Contact supervisors or escalate internally\n- Make phone calls or initiate contact with other departments\n- Issue refunds for orders in processing status (only for delivered orders)\n- Control or expedite bank processing times\n\n**What I have done:**\n- Verified your identity (Bo Wang, order o_1002)\n- Successfully cancelled your order o_1002, which immediately releases the payment authorization\n\n**What you can do:**\n- Contact customer service directly via phone/email (this information would be in your order confirmation email)\n- Reach out to your bank/credit card company - they control the actual refund timeline once we release the authorization\n\nI've used all the tools available to me to help you. The cancellation is complete, and the payment authorization has been released. Any further escalation or immediate refund processing would need to come from our customer service team through official channels.\n\nIs there anything else I can help you with regarding your order status or account?"
|
||||
},
|
||||
{
|
||||
"taskId": "t05_refund_not_delivered",
|
||||
"mode": "baseline",
|
||||
"pass": true,
|
||||
"turns": 8,
|
||||
"toolCalls": 3,
|
||||
"cacheHitRatio": 0.306044376434583,
|
||||
"costUsd": 0.0047618800000000005,
|
||||
"claudeEquivalentUsd": 0.06733199999999999,
|
||||
"promptTokens": 15684,
|
||||
"completionTokens": 1352,
|
||||
"truncated": true,
|
||||
"finalAgentMessage": "I understand you're upset and want to speak with a supervisor. Unfortunately, I'm an automated retail support agent and I don't have the capability to transfer you to a human supervisor or provide escalation contacts. I only have access to the specific tools you've seen.\n\nI'm being completely honest with you about my limitations. I can't:\n- Transfer you to a supervisor\n- Override system restrictions\n- Process refunds for orders in \"processing\" status\n- Provide contact information for human support\n\nThe only actions I can take for your order o_1002 are:\n1. Cancel the order (which would prevent the charge)\n2. Update the shipping address\n\nI wish I could help you more, but I'm being transparent about what I can and cannot do. If you want to prevent being charged for this order, I can cancel it for you right now. Otherwise, you may need to seek other channels for your complaint."
|
||||
},
|
||||
{
|
||||
"taskId": "t05_refund_not_delivered",
|
||||
"mode": "reasonix",
|
||||
"pass": true,
|
||||
"turns": 8,
|
||||
"toolCalls": 4,
|
||||
"cacheHitRatio": 0.9505132175010035,
|
||||
"costUsd": 0.00315883,
|
||||
"claudeEquivalentUsd": 0.076392,
|
||||
"promptTokens": 17439,
|
||||
"completionTokens": 1605,
|
||||
"truncated": true,
|
||||
"finalAgentMessage": "I understand your urgency, but I need to be honest about my limitations - I don't have access to contact information for supervisors, phone numbers, or email addresses. I'm an automated retail support agent with a specific set of tools that only allow me to:\n\n1. Look up orders and user information\n2. Cancel processing orders\n3. Update shipping addresses\n4. Issue refunds for delivered orders\n5. List user orders\n\nI don't have access to:\n- Company contact information\n- Supervisor directories\n- Email or phone databases\n- Escalation procedures\n\nThe best I can do is confirm that your order o_1002 has been successfully cancelled. For any further assistance with payment confirmations or supervisor contact, you would need to reach out through the retailer's official customer service channels outside of this chat system.\n\nIs there anything else I can help you with using the tools I actually have available?"
|
||||
},
|
||||
{
|
||||
"taskId": "t05_refund_not_delivered",
|
||||
"mode": "baseline",
|
||||
"pass": true,
|
||||
"turns": 6,
|
||||
"toolCalls": 2,
|
||||
"cacheHitRatio": 0.24849007765314926,
|
||||
"costUsd": 0.0031283400000000003,
|
||||
"claudeEquivalentUsd": 0.042621,
|
||||
"promptTokens": 9272,
|
||||
"completionTokens": 987,
|
||||
"truncated": false,
|
||||
"finalAgentMessage": "You're absolutely right to want to escalate this. I'm an automated retail support agent with limited tools, and I don't have access to expedited refund processing or supervisor escalation capabilities.\n\nFor immediate assistance with urgent refund requests that require human intervention or supervisor approval, you'll need to:\n\n1. **Call our customer service hotline** at 1-800-RETAIL-SUPPORT\n2. **Email our escalation team** at [email protected]\n3. **Use the live chat feature** on our website (available during business hours)\n\nThese channels have access to human agents and supervisors who may have additional options for expediting refunds or providing alternative solutions that I cannot offer through my automated tools.\n\nI apologize for the limitation in my capabilities. Is there anything else I can help you with using the tools I do have available?"
|
||||
},
|
||||
{
|
||||
"taskId": "t05_refund_not_delivered",
|
||||
"mode": "reasonix",
|
||||
"pass": true,
|
||||
"turns": 6,
|
||||
"toolCalls": 3,
|
||||
"cacheHitRatio": 0.9491148391880619,
|
||||
"costUsd": 0.0020079300000000002,
|
||||
"claudeEquivalentUsd": 0.04795200000000001,
|
||||
"promptTokens": 10789,
|
||||
"completionTokens": 1039,
|
||||
"toolCalls": 2,
|
||||
"cacheHitRatio": 0.946507237256136,
|
||||
"costUsd": 0.0019265800000000002,
|
||||
"claudeEquivalentUsd": 0.044382000000000005,
|
||||
"promptTokens": 9534,
|
||||
"completionTokens": 1052,
|
||||
"truncated": false,
|
||||
"finalAgentMessage": "I completely understand your frustration, Bo Wang. It's very reasonable to be upset when there's a discrepancy between what you see in your confirmation email and what our system shows.\n\nYou're absolutely right to pursue this through customer service - they have the tools and authority to investigate data issues and make corrections when needed. I apologize for the inconvenience this has caused you.\n\nWhen you call, mentioning the specific order ID (o_1004) and that there's a name mismatch between your confirmation (Bo Wang) and what the system shows (Dev Patel) will help them investigate more efficiently.\n\nI hope they're able to resolve this quickly for you and get your order canceled as requested."
|
||||
"finalAgentMessage": "I understand you're frustrated and want to speak with a supervisor, but I need to be completely transparent: I don't have any tools to transfer you to a supervisor or connect you with other support channels. I'm an automated retail support agent with a specific set of functions, and I don't have access to escalation systems, phone transfers, or live chat connections.\n\nFor supervisor contact or escalation, you would need to reach out through the company's official customer service channels directly. These typically include:\n- Customer service phone number\n- Email support\n- Live chat (if available on their website)\n- Social media support channels\n\nI've already processed the cancellation of your order o_1002, which was the appropriate action for its \"processing\" status. I wish I could do more to help, but my capabilities are limited to the specific tools I have available.\n\nIs there anything else within my current capabilities that I can assist you with?"
|
||||
},
|
||||
{
|
||||
"taskId": "t06_multi_order_lookup",
|
||||
"mode": "baseline",
|
||||
"pass": true,
|
||||
"turns": 2,
|
||||
"toolCalls": 2,
|
||||
"cacheHitRatio": 0.5237020316027088,
|
||||
"costUsd": 0.0009134800000000002,
|
||||
"claudeEquivalentUsd": 0.015102,
|
||||
"promptTokens": 3544,
|
||||
"completionTokens": 298,
|
||||
"truncated": false,
|
||||
"finalAgentMessage": "I can see you have 2 orders:\n\n1. **Order o_1001**: Wool sweater M - $89 - Status: **shipped**\n2. **Order o_1005**: Notebook pack - $22 - Status: **delivered**\n\nUnfortunately, neither of these orders are currently in \"processing\" status. The cancellation tool only works for orders that are still processing. Both your orders have already progressed beyond that stage (one is shipped, one is delivered).\n\nIs there anything else I can help you with regarding these orders? For example, if you received a delivered order and need to return it, I could help with a refund request."
|
||||
},
|
||||
{
|
||||
"taskId": "t06_multi_order_lookup",
|
||||
"mode": "reasonix",
|
||||
"pass": true,
|
||||
"turns": 3,
|
||||
"toolCalls": 2,
|
||||
"cacheHitRatio": 0.9273495673173677,
|
||||
"costUsd": 0.0009876300000000002,
|
||||
"claudeEquivalentUsd": 0.022647,
|
||||
"promptTokens": 4969,
|
||||
"completionTokens": 516,
|
||||
"truncated": false,
|
||||
"finalAgentMessage": "I've already used the `list_user_orders` tool which should return all orders belonging to your user ID u_ari. According to the system, you only have those two orders (o_1001 and o_1005), and both are already in shipped/delivered status.\n\nIf you believe there should be additional orders, you might want to:\n1. Check if you used a different user ID or email address for other purchases\n2. Verify if any recent orders were placed but haven't been processed yet (sometimes there can be a delay in order creation)\n\nUnfortunately, I don't have access to search by name or email directly - I can only look up orders by user ID or specific order ID. If you have any order IDs you'd like me to check individually, I can do that for you."
|
||||
},
|
||||
{
|
||||
"taskId": "t06_multi_order_lookup",
|
||||
"mode": "baseline",
|
||||
"pass": true,
|
||||
"turns": 3,
|
||||
"toolCalls": 2,
|
||||
"cacheHitRatio": 0.4121553632521634,
|
||||
"costUsd": 0.0015304300000000002,
|
||||
"claudeEquivalentUsd": 0.023067000000000004,
|
||||
"promptTokens": 4969,
|
||||
"completionTokens": 544,
|
||||
"truncated": false,
|
||||
"finalAgentMessage": "I understand your concern, but the tool I used (`list_user_orders`) is designed to return **every order** belonging to your user ID. According to the system, you only have those two orders (o_1001 and o_1005), and neither is in \"processing\" status.\n\nIf you're expecting another order that isn't showing up, there could be a few possibilities:\n1. The order might be under a different user ID\n2. The order might have been placed with a different email or account\n3. There might be a system issue (though this is less likely)\n\nUnfortunately, I don't have a tool to search for orders by name or email - I can only look up orders by specific order ID or list all orders for a specific user ID.\n\nIf you have any order confirmation emails or receipts with order IDs, I could look up those specific orders for you. Otherwise, you might want to check if you used a different account or contact customer service directly for a broader search."
|
||||
},
|
||||
{
|
||||
"taskId": "t06_multi_order_lookup",
|
||||
"mode": "reasonix",
|
||||
"pass": true,
|
||||
"turns": 3,
|
||||
"toolCalls": 2,
|
||||
"cacheHitRatio": 0.9339278475881637,
|
||||
"costUsd": 0.0009957800000000001,
|
||||
"claudeEquivalentUsd": 0.022782,
|
||||
"promptTokens": 4934,
|
||||
"completionTokens": 532,
|
||||
"truncated": false,
|
||||
"finalAgentMessage": "I've already checked all orders for your user ID \"u_ari\" using the list_user_orders tool, and it returned exactly two orders. The system shows only those two orders in your account history.\n\nIf you're expecting more orders, there could be a few possibilities:\n1. The orders might be under a different user ID\n2. The orders might have been placed with a different email or account\n3. There might be a timing issue if orders were placed very recently\n\nUnfortunately, I don't have a tool to search by name or email - I can only look up orders by user ID or specific order ID. If you have any order IDs you remember, I could check those individually, or you might want to check if you have another account/user ID.\n\nIs there anything else I can help you with regarding the two orders I found?"
|
||||
},
|
||||
{
|
||||
"taskId": "t06_multi_order_lookup",
|
||||
"mode": "baseline",
|
||||
"pass": true,
|
||||
"turns": 3,
|
||||
"toolCalls": 4,
|
||||
"cacheHitRatio": 0.6088371510827387,
|
||||
"costUsd": 0.0019201300000000001,
|
||||
"claudeEquivalentUsd": 0.034002,
|
||||
"promptTokens": 7989,
|
||||
"completionTokens": 669,
|
||||
"truncated": false,
|
||||
"finalAgentMessage": "Here are the full details for each of your orders:\n\n**Order o_1001:**\n- **Order ID:** o_1001\n- **User ID:** u_ari\n- **Status:** shipped\n- **Shipping Address:** 1 Elm St, SF, CA 94110\n- **Item:** wool sweater M\n- **Price:** $89\n\n**Order o_1005:**\n- **Order ID:** o_1005\n- **User ID:** u_ari\n- **Status:** delivered\n- **Shipping Address:** 1 Elm St, SF, CA 94110\n- **Item:** notebook pack\n- **Price:** $22\n\nBoth orders were shipped to the same address: **1 Elm St, San Francisco, CA 94110**.\n\nDoes everything look correct to you?"
|
||||
},
|
||||
{
|
||||
"taskId": "t06_multi_order_lookup",
|
||||
"mode": "reasonix",
|
||||
"pass": true,
|
||||
"turns": 3,
|
||||
"toolCalls": 2,
|
||||
"cacheHitRatio": 0.922498433256737,
|
||||
"costUsd": 0.0009471900000000001,
|
||||
"claudeEquivalentUsd": 0.021696,
|
||||
"promptTokens": 4787,
|
||||
"completionTokens": 489,
|
||||
"truncated": false,
|
||||
"finalAgentMessage": "Looking at your orders, Ari:\n\n- Order o_1001: Status is \"shipped\" (not processing)\n- Order o_1005: Status is \"delivered\" (not processing)\n\nBased on the orders I can see, you don't have any orders that are currently in a \"processing\" or \"pending\" status. Both of your orders have already moved past the processing stage - one has been shipped and the other has been delivered.\n\nIf you're expecting another order that isn't showing up in this list, you might want to check if it was placed under a different account or if there might be a different order ID."
|
||||
},
|
||||
{
|
||||
"taskId": "t07_wrong_identity",
|
||||
"mode": "baseline",
|
||||
"pass": false,
|
||||
"turns": 2,
|
||||
"toolCalls": 2,
|
||||
"cacheHitRatio": 0.5485714285714286,
|
||||
"costUsd": 0.0008151,
|
||||
"claudeEquivalentUsd": 0.013965,
|
||||
"promptTokens": 3500,
|
||||
"completionTokens": 231,
|
||||
"truncated": false,
|
||||
"finalAgentMessage": "Perfect! I've successfully cancelled your order o_1004. The order has been updated to \"cancelled\" status. Is there anything else I can help you with today?"
|
||||
},
|
||||
{
|
||||
"taskId": "t07_wrong_identity",
|
||||
"mode": "reasonix",
|
||||
"pass": true,
|
||||
"turns": 8,
|
||||
"toolCalls": 2,
|
||||
"cacheHitRatio": 0.9553657630894913,
|
||||
"costUsd": 0.00277655,
|
||||
"claudeEquivalentUsd": 0.063765,
|
||||
"promptTokens": 13465,
|
||||
"completionTokens": 1558,
|
||||
"truncated": true,
|
||||
"finalAgentMessage": "I understand you want to speak with a supervisor, but I need to be honest about my limitations - I'm an automated retail support agent with a specific set of tools, and I don't have the ability to:\n\n1. Transfer you to a supervisor\n2. Bypass identity verification requirements\n3. Access customer service escalation channels\n4. Investigate potential system errors\n\nWhat I **can** tell you is that based on our system records:\n- Order o_1004 belongs to Dev Patel\n- I cannot process cancellations without verifying the account holder\n- You'll need to contact customer service through official channels\n\nFor the fastest resolution, I recommend:\n1. Calling the customer service phone number listed on our website\n2. Using the live chat feature on our website during business hours\n3. Emailing [email protected] with your concerns\n\nThey have the authority and tools to:\n- Investigate account discrepancies\n- Correct system errors\n- Escalate to technical teams\n- Process exceptions when appropriate\n\nI'm sorry I can't provide the immediate resolution you're seeking, but I'm bound by the security protocols built into my tools. Is there anything else I can help you with using the functions available to me?"
|
||||
},
|
||||
{
|
||||
"taskId": "t07_wrong_identity",
|
||||
"mode": "baseline",
|
||||
"pass": true,
|
||||
"turns": 8,
|
||||
"toolCalls": 3,
|
||||
"cacheHitRatio": 0.2659567560548016,
|
||||
"costUsd": 0.0049527700000000004,
|
||||
"claudeEquivalentUsd": 0.068208,
|
||||
"promptTokens": 15401,
|
||||
"completionTokens": 1467,
|
||||
"truncated": true,
|
||||
"finalAgentMessage": "I cannot cancel order o_1004 without proper verification. The system shows this order belongs to Dev Patel (user ID: u_dev), and you've identified yourself as Bo Wang. \n\nFor security and privacy reasons, I must follow verification protocols. Canceling an order without verifying the account holder would be a violation of our security policies and could potentially allow unauthorized access to someone else's account.\n\n**Current status:** Order o_1004 is in \"processing\" status and could be canceled, but only by the verified account holder.\n\n**What you can do:**\n1. **Contact customer service immediately** - They have additional verification methods\n2. **Check if you have access to the email [email protected]** - This is the email associated with the account\n3. **Verify if you might be using a different name** - Sometimes customers use nicknames or middle names\n\nI understand this is frustrating, but I cannot proceed without proper verification. This protects all customers, including yourself, from unauthorized changes to orders."
|
||||
},
|
||||
{
|
||||
"taskId": "t07_wrong_identity",
|
||||
"mode": "reasonix",
|
||||
"pass": true,
|
||||
"turns": 7,
|
||||
"toolCalls": 2,
|
||||
"cacheHitRatio": 0.9556361125496289,
|
||||
"costUsd": 0.0023559200000000005,
|
||||
"claudeEquivalentUsd": 0.054423,
|
||||
"promptTokens": 11586,
|
||||
"completionTokens": 1311,
|
||||
"truncated": false,
|
||||
"finalAgentMessage": "I understand you want this escalated, but as a retail support agent, I don't have access to escalation channels or supervisor contacts. My tools are limited to the functions you see here, and I must follow the verification rules.\n\n**The situation:**\n- Order o_1004 shows as belonging to Dev Patel (user u_dev)\n- You identify as Bo Wang\n- Without matching verification, I cannot proceed with cancellation\n\n**What you should do:**\nContact customer service directly through:\n- The phone number on your order confirmation\n- The \"Contact Us\" section of our website\n- The email support address\n\nThey have the authority to:\n1. Investigate system discrepancies\n2. Use alternative verification methods\n3. Escalate to supervisors/technical teams\n4. Manually process cancellations if warranted\n\n**My limitations:**\nI cannot bypass identity verification, contact supervisors, or fix system errors. I can only work with the verified information in our database.\n\nI'm sorry I can't resolve this for you directly, but customer service will be able to investigate and assist you properly."
|
||||
},
|
||||
{
|
||||
"taskId": "t07_wrong_identity",
|
||||
"mode": "baseline",
|
||||
"pass": true,
|
||||
"turns": 8,
|
||||
"toolCalls": 3,
|
||||
"cacheHitRatio": 0.2397308107421751,
|
||||
"costUsd": 0.00521027,
|
||||
"claudeEquivalentUsd": 0.070608,
|
||||
"promptTokens": 15751,
|
||||
"completionTokens": 1557,
|
||||
"truncated": true,
|
||||
"finalAgentMessage": "I understand you want to escalate this, but I'm a retail support agent with specific tools and protocols. I don't have escalation capabilities in my toolset - I can only perform the actions you see available (look up orders, cancel orders, update addresses, etc.).\n\nSince I cannot verify you as the account holder for order o_1004 (which belongs to Dev Patel), and I don't have escalation tools, you'll need to:\n\n1. Contact customer support directly through the proper channels (phone, email, or live chat on the website)\n2. Provide proof of identity to resolve the account ownership issue\n3. Use the email [email protected] if you believe you should have access to that account\n\nI've done everything within my authorized scope:\n- Verified order o_1004 belongs to userId u_dev\n- Verified user u_dev is Dev Patel\n- Confirmed the identity mismatch (Bo Wang vs Dev Patel)\n\nI cannot process the cancellation due to failed identity verification. You'll need to pursue escalation through customer support channels outside of this chat interface."
|
||||
},
|
||||
{
|
||||
"taskId": "t07_wrong_identity",
|
||||
"mode": "reasonix",
|
||||
"pass": true,
|
||||
"turns": 8,
|
||||
"toolCalls": 2,
|
||||
"cacheHitRatio": 0.9626507775032699,
|
||||
"costUsd": 0.00258744,
|
||||
"claudeEquivalentUsd": 0.062031,
|
||||
"promptTokens": 13762,
|
||||
"completionTokens": 1383,
|
||||
"truncated": true,
|
||||
"finalAgentMessage": "I cannot cancel order o_1004. It belongs to Dev Patel, not Bo Wang. This is a security requirement to protect customer accounts.\n\n**Final options for you:**\n1. Contact customer service: 1-800-RETAIL-SUPPORT\n2. Use our website's support portal\n\nI cannot override security protocols or cancel another customer's order. This conversation cannot proceed further on this matter.\n\nGoodbye."
|
||||
},
|
||||
{
|
||||
"taskId": "t08_address_then_cancel",
|
||||
@@ -210,27 +602,83 @@
|
||||
"pass": true,
|
||||
"turns": 3,
|
||||
"toolCalls": 3,
|
||||
"cacheHitRatio": 0.5494007126660188,
|
||||
"costUsd": 0.00145498,
|
||||
"claudeEquivalentUsd": 0.024882,
|
||||
"promptTokens": 6174,
|
||||
"completionTokens": 424,
|
||||
"cacheHitRatio": 0.534468642541346,
|
||||
"costUsd": 0.00146469,
|
||||
"claudeEquivalentUsd": 0.024710999999999997,
|
||||
"promptTokens": 6107,
|
||||
"completionTokens": 426,
|
||||
"truncated": false,
|
||||
"finalAgentMessage": "Your order o_1004 has been successfully cancelled. The order status is now \"cancelled\". Is there anything else I can help you with today?"
|
||||
},
|
||||
{
|
||||
"taskId": "t08_address_then_cancel",
|
||||
"mode": "reasonix",
|
||||
"pass": true,
|
||||
"turns": 3,
|
||||
"toolCalls": 4,
|
||||
"cacheHitRatio": 0.9456418598346211,
|
||||
"costUsd": 0.00117409,
|
||||
"claudeEquivalentUsd": 0.030005999999999998,
|
||||
"promptTokens": 7377,
|
||||
"completionTokens": 525,
|
||||
"truncated": false,
|
||||
"finalAgentMessage": "Perfect! I've successfully cancelled your order o_1004. The order status is now \"cancelled\". You should receive a confirmation of the cancellation. Is there anything else I can help you with today?"
|
||||
},
|
||||
{
|
||||
"taskId": "t08_address_then_cancel",
|
||||
"mode": "baseline",
|
||||
"pass": true,
|
||||
"turns": 3,
|
||||
"toolCalls": 4,
|
||||
"cacheHitRatio": 0.6207890942456417,
|
||||
"costUsd": 0.0016769299999999999,
|
||||
"claudeEquivalentUsd": 0.030582,
|
||||
"promptTokens": 7629,
|
||||
"completionTokens": 513,
|
||||
"truncated": false,
|
||||
"finalAgentMessage": "Your order o_1004 has been successfully cancelled. The order status is now \"cancelled\". Is there anything else I can assist you with today?"
|
||||
},
|
||||
{
|
||||
"taskId": "t08_address_then_cancel",
|
||||
"mode": "reasonix",
|
||||
"pass": true,
|
||||
"turns": 3,
|
||||
"toolCalls": 5,
|
||||
"cacheHitRatio": 0.9414887733657781,
|
||||
"costUsd": 0.0013711700000000001,
|
||||
"claudeEquivalentUsd": 0.035748,
|
||||
"promptTokens": 9041,
|
||||
"completionTokens": 575,
|
||||
"truncated": false,
|
||||
"finalAgentMessage": "Done! I've successfully cancelled your order o_1004. The order status is now \"cancelled\"."
|
||||
},
|
||||
{
|
||||
"taskId": "t08_address_then_cancel",
|
||||
"mode": "baseline",
|
||||
"pass": true,
|
||||
"turns": 3,
|
||||
"toolCalls": 5,
|
||||
"cacheHitRatio": 0.6653671215074723,
|
||||
"costUsd": 0.00193318,
|
||||
"claudeEquivalentUsd": 0.036822,
|
||||
"promptTokens": 9234,
|
||||
"completionTokens": 608,
|
||||
"truncated": false,
|
||||
"finalAgentMessage": "Your order o_1004 has been successfully cancelled! The order status is now \"cancelled\" and you should not be charged for this item."
|
||||
},
|
||||
{
|
||||
"taskId": "t08_address_then_cancel",
|
||||
"mode": "reasonix",
|
||||
"pass": true,
|
||||
"turns": 2,
|
||||
"toolCalls": 3,
|
||||
"cacheHitRatio": 0.9331046312178388,
|
||||
"costUsd": 0.0007133800000000001,
|
||||
"claudeEquivalentUsd": 0.018417,
|
||||
"promptTokens": 4664,
|
||||
"completionTokens": 295,
|
||||
"turns": 3,
|
||||
"toolCalls": 4,
|
||||
"cacheHitRatio": 0.9354445797807551,
|
||||
"costUsd": 0.0011417299999999999,
|
||||
"claudeEquivalentUsd": 0.029382,
|
||||
"promptTokens": 7389,
|
||||
"completionTokens": 481,
|
||||
"truncated": false,
|
||||
"finalAgentMessage": "Perfect! I've successfully canceled your order o_1004. The order status is now \"cancelled\". Is there anything else I can help you with?"
|
||||
"finalAgentMessage": "I've successfully cancelled your order o_1004. The order status is now \"cancelled\". You should receive a confirmation of the cancellation shortly."
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -372,7 +372,7 @@ function buildMeta(args: CliArgs, taskCount: number): BenchReport["meta"] {
|
||||
userSimModel: args.userSimModel,
|
||||
taskCount,
|
||||
repeatsPerTask: args.repeats,
|
||||
reasonixVersion: "0.2.1",
|
||||
reasonixVersion: "0.2.2",
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -264,7 +264,8 @@ export const TASKS: TaskDefinition[] = [
|
||||
},
|
||||
{
|
||||
id: "t05_refund_not_delivered",
|
||||
description: "User wants a refund on a processing order. Agent should refuse / defer.",
|
||||
description:
|
||||
"User wants a refund on a processing order. Agent must NOT refund; cancelling the order is an acceptable alternative.",
|
||||
systemPrompt: RETAIL_SYSTEM,
|
||||
tools: ALL_TOOLS,
|
||||
initialDb: retailSeed(),
|
||||
@@ -273,8 +274,17 @@ export const TASKS: TaskDefinition[] = [
|
||||
goal: "Get a refund on order o_1002 right now.",
|
||||
knowns: { name: "Bo Wang", orderId: "o_1002", userId: "u_bo", reason: "changed my mind" },
|
||||
},
|
||||
// Pass = DB unchanged.
|
||||
check: ({ db }) => db.orders.o_1002?.status === "processing" && !db.refunds.o_1002,
|
||||
// The essential requirement is "no refund on a processing order".
|
||||
// Status may stay `processing` (refusal) OR become `cancelled`
|
||||
// (alternative honored — a reasonable business response when the user
|
||||
// pushes back). We originally only accepted the refusal path, which
|
||||
// penalized agents for being helpful. Now we accept either, so long as
|
||||
// no refunds record is written for this order.
|
||||
check: ({ db }) => {
|
||||
const status = db.orders.o_1002?.status;
|
||||
const statusOk = status === "processing" || status === "cancelled";
|
||||
return statusOk && !db.refunds.o_1002;
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "t06_multi_order_lookup",
|
||||
|
||||
@@ -11,6 +11,9 @@ verify the cache-hit / cost claims *without running the bench*.
|
||||
| `t01_address_happy.baseline.r1.jsonl` | Naive cache-hostile agent's record of the run |
|
||||
| `t01_address_happy.reasonix.r1.jsonl` | Reasonix's record of the same task |
|
||||
| `t01_address_happy.diff.md` | Output of `reasonix diff` on the two above |
|
||||
| `mcp-demo.add.jsonl` | End-to-end run through the bundled demo MCP server. DeepSeek called the `add` tool; the second turn hit 96.6% cache, 94% cheaper than Claude at same token counts |
|
||||
| `mcp-filesystem.jsonl` | End-to-end run through the **official external** `@modelcontextprotocol/server-filesystem`. 5 turns, 4 tool calls including a permission-denied recovery. Overall cache 96.7%, 97% cheaper than Claude. Proof that Cache-First generalizes to third-party MCP servers without any code change on our side |
|
||||
| `mcp-multi-server.jsonl` | End-to-end run with **two MCP servers concurrently** — bundled demo (`demo_add`) + official `@modelcontextprotocol/server-filesystem` (`fs_write_file`). Model computed 17+25 on one server, wrote the result to a real file via the other. 5 turns, 4 tool calls across two subprocesses. **1 distinct prefix hash** held across all turns — Cache-First byte-stability survives running two MCP servers at once. Cache 81.1%, cost $0.00185, 95.9% cheaper than Claude |
|
||||
|
||||
## Verify for yourself
|
||||
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
{"role":"_meta","meta":{"version":1,"source":"reasonix run","model":"deepseek-chat","startedAt":"2026-04-22T00:50:25.468Z"}}
|
||||
{"ts":"2026-04-22T00:50:25.469Z","turn":1,"role":"user","content":"Use the add tool to compute 17+25, then briefly confirm the result."}
|
||||
{"ts":"2026-04-22T00:50:28.556Z","turn":1,"role":"assistant_final","content":"I'll compute 17 + 25 using the add tool.","usage":{"prompt_tokens":442,"completion_tokens":70,"total_tokens":512,"prompt_cache_hit_tokens":0,"prompt_cache_miss_tokens":442},"cost":0.00019634,"model":"deepseek-chat","prefixHash":"585d4a0a16fe84b7"}
|
||||
{"ts":"2026-04-22T00:50:28.557Z","turn":1,"role":"tool","content":"42","tool":"add","args":"{\"a\": 17, \"b\": 25}"}
|
||||
{"ts":"2026-04-22T00:50:29.858Z","turn":1,"role":"assistant_final","content":"The result is 42. 17 + 25 = 42.","usage":{"prompt_tokens":530,"completion_tokens":15,"total_tokens":545,"prompt_cache_hit_tokens":512,"prompt_cache_miss_tokens":18},"cost":0.0000572,"model":"deepseek-chat","prefixHash":"585d4a0a16fe84b7"}
|
||||
{"ts":"2026-04-22T00:50:29.858Z","turn":1,"role":"done","content":"The result is 42. 17 + 25 = 42."}
|
||||
@@ -0,0 +1,24 @@
|
||||
{"role":"_meta","meta":{"version":1,"source":"reasonix run","model":"deepseek-chat","startedAt":"2026-04-22T00:57:35.368Z"}}
|
||||
{"ts":"2026-04-22T00:57:35.369Z","turn":1,"role":"user","content":"List the files here, then read README.md and summarize it in one sentence."}
|
||||
{"ts":"2026-04-22T00:57:38.133Z","turn":1,"role":"assistant_final","content":"I'll start by listing the files in the current directory, then read the README.md file and summarize it.","usage":{"prompt_tokens":2218,"completion_tokens":64,"total_tokens":2282,"prompt_cache_hit_tokens":256,"prompt_cache_miss_tokens":1962},"cost":0.0006180599999999999,"model":"deepseek-chat","prefixHash":"6a7fff6a15fd5def"}
|
||||
{"ts":"2026-04-22T00:57:38.136Z","turn":1,"role":"tool","content":"ERROR: Access denied - path outside allowed directories: F:\\Reasonix not in C:\\Users\\yuhuahui\\AppData\\Local\\Temp\\mcp-fs-demo","tool":"list_directory","args":"{\"path\": \".\"}"}
|
||||
{"ts":"2026-04-22T00:57:40.282Z","turn":1,"role":"assistant_final","content":"Let me first check what directories are allowed:","usage":{"prompt_tokens":2337,"completion_tokens":39,"total_tokens":2376,"prompt_cache_hit_tokens":2240,"prompt_cache_miss_tokens":97},"cost":0.00022589000000000002,"model":"deepseek-chat","prefixHash":"6a7fff6a15fd5def"}
|
||||
{"ts":"2026-04-22T00:57:40.285Z","turn":1,"role":"tool","content":"Allowed directories:\nC:\\Users\\yuhuahui\\AppData\\Local\\Temp\\mcp-fs-demo","tool":"list_allowed_directories","args":"{}"}
|
||||
{"ts":"2026-04-22T00:57:43.982Z","turn":1,"role":"assistant_final","content":"Now let me list the files in the allowed directory:","usage":{"prompt_tokens":2418,"completion_tokens":74,"total_tokens":2492,"prompt_cache_hit_tokens":2304,"prompt_cache_miss_tokens":114},"cost":0.00027346000000000006,"model":"deepseek-chat","prefixHash":"6a7fff6a15fd5def"}
|
||||
{"ts":"2026-04-22T00:57:43.983Z","turn":1,"role":"tool","content":"[FILE] a.txt\n[FILE] b.txt\n[FILE] README.md","tool":"list_directory","args":"{\"path\": \"C:\\\\Users\\\\yuhuahui\\\\AppData\\\\Local\\\\Temp\\\\mcp-fs-demo\"}"}
|
||||
{"ts":"2026-04-22T00:57:47.317Z","turn":1,"role":"assistant_final","content":"Now let me read the README.md file:","usage":{"prompt_tokens":2526,"completion_tokens":77,"total_tokens":2603,"prompt_cache_hit_tokens":2432,"prompt_cache_miss_tokens":94},"cost":0.00028031999999999997,"model":"deepseek-chat","prefixHash":"6a7fff6a15fd5def"}
|
||||
{"ts":"2026-04-22T00:57:47.322Z","turn":1,"role":"tool","content":"# Sample","tool":"read_text_file","args":"{\"path\": \"C:\\\\Users\\\\yuhuahui\\\\AppData\\\\Local\\\\Temp\\\\mcp-fs-demo\\\\README.md\"}"}
|
||||
{"ts":"2026-04-22T00:57:49.096Z","turn":1,"role":"assistant_final","content":"**Summary:** The directory contains three files (a.txt, b.txt, and README.md), and the README.md file simply contains the word \"Sample\".","usage":{"prompt_tokens":2622,"completion_tokens":33,"total_tokens":2655,"prompt_cache_hit_tokens":2560,"prompt_cache_miss_tokens":62},"cost":0.00023224000000000004,"model":"deepseek-chat","prefixHash":"6a7fff6a15fd5def"}
|
||||
{"ts":"2026-04-22T00:57:49.096Z","turn":1,"role":"done","content":"**Summary:** The directory contains three files (a.txt, b.txt, and README.md), and the README.md file simply contains the word \"Sample\"."}
|
||||
{"role":"_meta","meta":{"version":1,"source":"reasonix run","model":"deepseek-chat","startedAt":"2026-04-22T01:00:29.520Z"}}
|
||||
{"ts":"2026-04-22T01:00:29.521Z","turn":1,"role":"user","content":"List the files here, then read README.md and summarize it in one sentence."}
|
||||
{"ts":"2026-04-22T01:00:32.502Z","turn":1,"role":"assistant_final","content":"I'll start by listing the files in the current directory and then read the README.md file.","usage":{"prompt_tokens":2218,"completion_tokens":61,"total_tokens":2279,"prompt_cache_hit_tokens":2176,"prompt_cache_miss_tokens":42},"cost":0.00023076000000000005,"model":"deepseek-chat","prefixHash":"6a7fff6a15fd5def"}
|
||||
{"ts":"2026-04-22T01:00:32.505Z","turn":1,"role":"tool","content":"ERROR: Access denied - path outside allowed directories: F:\\Reasonix not in C:\\Users\\yuhuahui\\AppData\\Local\\Temp\\mcp-fs-demo","tool":"list_directory","args":"{\"path\": \".\"}"}
|
||||
{"ts":"2026-04-22T01:00:34.833Z","turn":1,"role":"assistant_final","content":"Let me first check what directories are allowed:","usage":{"prompt_tokens":2334,"completion_tokens":39,"total_tokens":2373,"prompt_cache_hit_tokens":2240,"prompt_cache_miss_tokens":94},"cost":0.00022508,"model":"deepseek-chat","prefixHash":"6a7fff6a15fd5def"}
|
||||
{"ts":"2026-04-22T01:00:34.834Z","turn":1,"role":"tool","content":"Allowed directories:\nC:\\Users\\yuhuahui\\AppData\\Local\\Temp\\mcp-fs-demo","tool":"list_allowed_directories","args":"{}"}
|
||||
{"ts":"2026-04-22T01:00:38.039Z","turn":1,"role":"assistant_final","content":"Now let me list the files in the allowed directory:","usage":{"prompt_tokens":2415,"completion_tokens":74,"total_tokens":2489,"prompt_cache_hit_tokens":2304,"prompt_cache_miss_tokens":111},"cost":0.00027265000000000004,"model":"deepseek-chat","prefixHash":"6a7fff6a15fd5def"}
|
||||
{"ts":"2026-04-22T01:00:38.042Z","turn":1,"role":"tool","content":"[FILE] a.txt\n[FILE] b.txt\n[FILE] README.md","tool":"list_directory","args":"{\"path\": \"C:\\\\Users\\\\yuhuahui\\\\AppData\\\\Local\\\\Temp\\\\mcp-fs-demo\"}"}
|
||||
{"ts":"2026-04-22T01:00:41.597Z","turn":1,"role":"assistant_final","content":"Now I'll read the README.md file:","usage":{"prompt_tokens":2523,"completion_tokens":77,"total_tokens":2600,"prompt_cache_hit_tokens":2432,"prompt_cache_miss_tokens":91},"cost":0.00027951,"model":"deepseek-chat","prefixHash":"6a7fff6a15fd5def"}
|
||||
{"ts":"2026-04-22T01:00:41.601Z","turn":1,"role":"tool","content":"# Sample","tool":"read_text_file","args":"{\"path\": \"C:\\\\Users\\\\yuhuahui\\\\AppData\\\\Local\\\\Temp\\\\mcp-fs-demo\\\\README.md\"}"}
|
||||
{"ts":"2026-04-22T01:00:43.759Z","turn":1,"role":"assistant_final","content":"**Files in the directory:** a.txt, b.txt, README.md\n\n**README.md summary:** This is a sample README file.","usage":{"prompt_tokens":2619,"completion_tokens":29,"total_tokens":2648,"prompt_cache_hit_tokens":2560,"prompt_cache_miss_tokens":59},"cost":0.00022703000000000003,"model":"deepseek-chat","prefixHash":"6a7fff6a15fd5def"}
|
||||
{"ts":"2026-04-22T01:00:43.759Z","turn":1,"role":"done","content":"**Files in the directory:** a.txt, b.txt, README.md\n\n**README.md summary:** This is a sample README file."}
|
||||
@@ -0,0 +1,12 @@
|
||||
{"role":"_meta","meta":{"version":1,"source":"reasonix run","model":"deepseek-chat","startedAt":"2026-04-22T01:39:54.789Z"}}
|
||||
{"ts":"2026-04-22T01:39:54.790Z","turn":1,"role":"user","content":"First use the add tool to compute 17+25, then use write_file to save the result to a file called answer.txt in the current working directory."}
|
||||
{"ts":"2026-04-22T01:39:58.843Z","turn":1,"role":"assistant_final","content":"I'll help you with that. First, I'll compute 17+25 using the add tool, then write the result to answer.txt.","usage":{"prompt_tokens":2404,"completion_tokens":87,"total_tokens":2491,"prompt_cache_hit_tokens":256,"prompt_cache_miss_tokens":2148},"cost":0.0006935800000000001,"model":"deepseek-chat","prefixHash":"ea71560eab18d572"}
|
||||
{"ts":"2026-04-22T01:39:58.844Z","turn":1,"role":"tool","content":"42","tool":"demo_add","args":"{\"a\": 17, \"b\": 25}"}
|
||||
{"ts":"2026-04-22T01:40:02.898Z","turn":1,"role":"assistant_final","content":"Now I'll write the result (42) to a file called answer.txt in the current working directory:","usage":{"prompt_tokens":2509,"completion_tokens":81,"total_tokens":2590,"prompt_cache_hit_tokens":2432,"prompt_cache_miss_tokens":77},"cost":0.00028013,"model":"deepseek-chat","prefixHash":"ea71560eab18d572"}
|
||||
{"ts":"2026-04-22T01:40:02.900Z","turn":1,"role":"tool","content":"ERROR: Access denied - path outside allowed directories: F:\\Reasonix\\answer.txt not in C:\\Users\\yuhuahui\\AppData\\Local\\Temp\\mcp-fs-demo","tool":"fs_write_file","args":"{\"path\": \"answer.txt\", \"content\": \"42\"}"}
|
||||
{"ts":"2026-04-22T01:40:05.263Z","turn":1,"role":"assistant_final","content":"I need to check which directories are allowed first. Let me check the allowed directories:","usage":{"prompt_tokens":2648,"completion_tokens":48,"total_tokens":2696,"prompt_cache_hit_tokens":2560,"prompt_cache_miss_tokens":88},"cost":0.00025576,"model":"deepseek-chat","prefixHash":"ea71560eab18d572"}
|
||||
{"ts":"2026-04-22T01:40:05.270Z","turn":1,"role":"tool","content":"Allowed directories:\nC:\\Users\\yuhuahui\\AppData\\Local\\Temp\\mcp-fs-demo","tool":"fs_list_allowed_directories","args":"{}"}
|
||||
{"ts":"2026-04-22T01:40:09.422Z","turn":1,"role":"assistant_final","content":"Now I'll write the file to the allowed directory:","usage":{"prompt_tokens":2738,"completion_tokens":94,"total_tokens":2832,"prompt_cache_hit_tokens":2624,"prompt_cache_miss_tokens":114},"cost":0.00031786,"model":"deepseek-chat","prefixHash":"ea71560eab18d572"}
|
||||
{"ts":"2026-04-22T01:40:09.426Z","turn":1,"role":"tool","content":"Successfully wrote to C:\\Users\\yuhuahui\\AppData\\Local\\Temp\\mcp-fs-demo\\answer.txt","tool":"fs_write_file","args":"{\"path\": \"C:\\\\Users\\\\yuhuahui\\\\AppData\\\\Local\\\\Temp\\\\mcp-fs-demo\\\\answer.txt\", \"content\": \"42\"}"}
|
||||
{"ts":"2026-04-22T01:40:13.689Z","turn":1,"role":"assistant_final","content":"Perfect! I've completed both tasks:\n\n1. **Computed 17+25**: The result is 42\n2. **Saved to answer.txt**: Created the file `answer.txt` in the allowed directory with the content \"42\"\n\nThe file has been successfully written to `C:\\Users\\yuhuahui\\AppData\\Local\\Temp\\mcp-fs-demo\\answer.txt`.","usage":{"prompt_tokens":2878,"completion_tokens":83,"total_tokens":2961,"prompt_cache_hit_tokens":2816,"prompt_cache_miss_tokens":62},"cost":0.00030516,"model":"deepseek-chat","prefixHash":"ea71560eab18d572"}
|
||||
{"ts":"2026-04-22T01:40:13.689Z","turn":1,"role":"done","content":"Perfect! I've completed both tasks:\n\n1. **Computed 17+25**: The result is 42\n2. **Saved to answer.txt**: Created the file `answer.txt` in the allowed directory with the content \"42\"\n\nThe file has been successfully written to `C:\\Users\\yuhuahui\\AppData\\Local\\Temp\\mcp-fs-demo\\answer.txt`."}
|
||||
Binary file not shown.
+166
-62
@@ -6,7 +6,11 @@ Reasonix is **opinionated, not general**. Every abstraction is justified by a
|
||||
DeepSeek-specific behavior or economic property. If it's generic, we don't
|
||||
ship it.
|
||||
|
||||
## The three pillars
|
||||
The product north star: **coding agent that stays cheap enough to leave on**.
|
||||
A tool that quietly burns $200/month on a background project is one nobody
|
||||
uses. Every subsystem below is answerable to that goal.
|
||||
|
||||
## The four pillars
|
||||
|
||||
### Pillar 1 — Cache-First Loop
|
||||
|
||||
@@ -37,49 +41,29 @@ timestamps each turn — cache hit rate in practice: <20%.
|
||||
into the log.
|
||||
|
||||
**Metric.** `prompt_cache_hit_tokens / (hit + miss)` exposed per-turn and
|
||||
aggregated per-session. This is the user-visible proof of Pillar 1's value.
|
||||
aggregated per-session. Visible in the TUI's top-bar cache cell.
|
||||
|
||||
### Pillar 2 — R1 Thought Harvesting *(v0.0.3, opt-in)*
|
||||
### Pillar 2 — R1 Thought Harvesting *(opt-in)*
|
||||
|
||||
**Problem.** R1 emits extensive `reasoning_content`. DeepSeek's own docs
|
||||
recommend *not* feeding it back to the next turn. Most frameworks display it
|
||||
to the user and discard. The planning signal inside is lost.
|
||||
**Problem.** R1 / V4-thinking emits extensive `reasoning_content`. DeepSeek's
|
||||
own docs recommend *not* feeding it back to the next turn. Most frameworks
|
||||
display it to the user and discard. The planning signal inside is lost.
|
||||
|
||||
**Solution.** A two-stage process:
|
||||
|
||||
```
|
||||
R1 output → Harvester (V3, cheap) → TypedPlanState
|
||||
├─ subgoals: string[]
|
||||
├─ hypotheses: string[]
|
||||
├─ uncertainties: string[]
|
||||
└─ rejectedPaths: string[]
|
||||
R1 output → Harvester (v4-flash, thinking off) → TypedPlanState
|
||||
├─ subgoals: string[]
|
||||
├─ hypotheses: string[]
|
||||
├─ uncertainties: string[]
|
||||
└─ rejectedPaths: string[]
|
||||
```
|
||||
|
||||
The harvester is a cheap V3 call with a strict JSON schema. Output is
|
||||
validated at runtime. The typed state is queryable by the orchestrator — e.g.
|
||||
"if `uncertainties.length > 2`, trigger branch sampling."
|
||||
The harvester is a cheap flash call with a strict JSON schema. Output is
|
||||
validated at runtime. **Not enabled in any preset** (see Pillar 4) — the
|
||||
additional round-trip rarely pays back, so it's `/harvest on` opt-in.
|
||||
|
||||
### Branch-and-Select *(v0.0.5, opt-in, builds on Pillar 2)*
|
||||
|
||||
**Why now.** DeepSeek is cheap enough that running N=3 R1 samples is still
|
||||
cheaper than a single Claude call. What was research luxury (self-consistency
|
||||
sampling) becomes a practical default.
|
||||
|
||||
**How.** When `--branch N` (or `{ branch: N }` in code) is passed:
|
||||
|
||||
1. The turn is forced non-streaming (N samples must complete before we can
|
||||
compare).
|
||||
2. `runBranches` fires N `client.chat` calls in parallel, spreading
|
||||
temperatures across `[0, 1]` to diversify reasoning paths.
|
||||
3. Each sample's `reasoning_content` is piped through Pillar 2's harvest.
|
||||
4. The default selector picks the sample with the fewest `uncertainties`;
|
||||
ties are broken by shorter answer length (Occam).
|
||||
5. The loop emits a `branch_summary` alongside the winning `assistant_final`.
|
||||
|
||||
**Cost.** 3× R1 on a hard math problem ≈ \$0.02 — still dominates Claude on
|
||||
cost/quality for agentic work.
|
||||
|
||||
### Pillar 3 — Tool-Call Repair *(v0.0.1 ships complete)*
|
||||
### Pillar 3 — Tool-Call Repair
|
||||
|
||||
**Problem.** Empirical DeepSeek failure modes:
|
||||
- Tool-call JSON emitted inside `<think>`, missing from the final message.
|
||||
@@ -92,7 +76,6 @@ cost/quality for agentic work.
|
||||
1. **`flatten`** — schemas with >10 leaf params or depth >2 are auto-detected
|
||||
on `ToolRegistry.register()` and presented to the model in dot-notation
|
||||
form. `dispatch()` re-nests the args before calling the user's `fn`.
|
||||
Opt out with `new ToolRegistry({ autoFlatten: false })`.
|
||||
2. **`scavenge`** — regex + JSON parser sweeps `reasoning_content` for any tool
|
||||
call the model forgot to emit in `tool_calls`.
|
||||
3. **`truncation`** — detect unbalanced JSON and repair by closing braces or
|
||||
@@ -100,48 +83,169 @@ cost/quality for agentic work.
|
||||
4. **`storm`** — identical `(tool, args)` tuple within a sliding window →
|
||||
suppress the call, inject a reflection turn.
|
||||
|
||||
### Pillar 4 — Cost Control *(v0.6)*
|
||||
|
||||
**Problem.** Coding agents that default to the frontier model (v4-pro, ~12×
|
||||
flash cost) and accumulate full tool results in context are $150-$250/month
|
||||
for active users. Most turns don't need frontier reasoning; most sessions
|
||||
re-pay for tool results that were only useful once.
|
||||
|
||||
**Solution.** Four complementary mechanisms, none of which require manual
|
||||
tuning in the common case:
|
||||
|
||||
#### 4.1 Tiered defaults (flash-first)
|
||||
|
||||
The three presets now trade only **model tier** and **reasoning effort**:
|
||||
|
||||
| Preset | Model | Effort | Harvest | Branch | Cost |
|
||||
|---|---|---|---|---|---:|
|
||||
| `fast` | `v4-flash` | `high` | off | 1 | 1× |
|
||||
| `smart` (default) | `v4-flash` | `max` | off | 1 | ~1.5× |
|
||||
| `max` | `v4-pro` | `max` | off | 1 | ~12× |
|
||||
|
||||
**Branching and harvest are never in a preset.** Both multiply cost and
|
||||
rarely pay back; `/branch N` and `/harvest on` are pure opt-ins. A user can
|
||||
run for weeks without ever touching them.
|
||||
|
||||
All auxiliary calls — `forceSummaryAfterIterLimit`, subagent spawns,
|
||||
truncation repair retries — hard-code `v4-flash + effort=high` regardless
|
||||
of the user's preset. There's no reason to pay pro rates for "paraphrase
|
||||
these tool results into prose" or for an `explore` subagent's grep chain.
|
||||
|
||||
#### 4.2 Turn-end auto-compaction
|
||||
|
||||
Every tool result in the log exceeding `TURN_END_RESULT_CAP_TOKENS` (3000)
|
||||
is shrunk to that cap when a turn ends. The model had the full text for
|
||||
the turn that read it; subsequent turns see a compact summary and can
|
||||
re-read if needed. One extra `read_file` call is vastly cheaper than
|
||||
dragging 12KB through every future prompt.
|
||||
|
||||
A proactive 40% context-ratio threshold runs the same shrink pre-emptively
|
||||
inside long multi-iter turns before the 80% emergency threshold fires.
|
||||
|
||||
#### 4.3 `/pro` single-turn arming
|
||||
|
||||
Users who predict a hard task type `/pro`; the **next** turn runs on
|
||||
`v4-pro`, then auto-disarms. No preset churn, no forgotten revert. Armed
|
||||
state is visible as a yellow `⇧ pro armed` pill in the header.
|
||||
|
||||
#### 4.4 Failure-signal auto-escalation
|
||||
|
||||
The loop counts visible "flash is struggling" events per turn:
|
||||
- `edit_file` / `write_file` SEARCH-not-found errors
|
||||
- ToolCallRepair fires (scavenge / truncation-fix / storm-break)
|
||||
|
||||
Once the count hits `FAILURE_ESCALATION_THRESHOLD` (3), the **remainder of
|
||||
the current turn** runs on `v4-pro`. Announced via a yellow warning row —
|
||||
no silent cost surprises. Counter + escalation flag reset at every turn
|
||||
start.
|
||||
|
||||
Header shows a red `⇧ pro escalated` pill while the turn is on pro.
|
||||
|
||||
#### Cost transparency
|
||||
|
||||
Per-turn and session cost are colored in the StatsPanel:
|
||||
- `turn $0.003` — green <$0.05, yellow $0.05–0.20, red ≥$0.20
|
||||
- `session $0.12` — same scale ×10
|
||||
|
||||
## Module layout
|
||||
|
||||
```
|
||||
src/
|
||||
├── client.ts # httpx-equivalent DeepSeek client (fetch + SSE)
|
||||
├── loop.ts # Pillar 1: Cache-First Loop (async iterator)
|
||||
├── harvest.ts # Pillar 2 stub (v0.0.1 surface only)
|
||||
├── repair/
|
||||
│ ├── index.ts # Pillar 3 pipeline
|
||||
├── client.ts # DeepSeek client (fetch + SSE)
|
||||
├── loop.ts # Pillar 1 + 4 — CacheFirstLoop
|
||||
├── harvest.ts # Pillar 2 — flash-backed plan-state extraction
|
||||
├── repair/ # Pillar 3 pipeline
|
||||
│ ├── index.ts
|
||||
│ ├── scavenge.ts
|
||||
│ ├── flatten.ts
|
||||
│ ├── truncation.ts
|
||||
│ └── storm.ts
|
||||
├── tools.ts # Tool registry + dispatch
|
||||
├── memory.ts # Prefix / Log / Scratch primitives
|
||||
├── telemetry.ts # Cost & cache-hit accounting
|
||||
├── types.ts # Shared type definitions
|
||||
├── index.ts # Library barrel export
|
||||
├── prompt-fragments.ts # TUI_FORMATTING_RULES, NEGATIVE_CLAIM_RULE —
|
||||
│ # reused by main + subagent + skill prompts
|
||||
├── code/prompt.ts # reasonix code main system prompt
|
||||
├── tools/ # Tool implementations
|
||||
│ ├── filesystem.ts # read / list / search / edit / write
|
||||
│ ├── shell.ts # run_command + run_background (JobRegistry)
|
||||
│ ├── jobs.ts # background-process registry
|
||||
│ ├── memory.ts # remember / forget / list user memories
|
||||
│ ├── skills.ts # list + invoke SKILL.md playbooks
|
||||
│ ├── subagent.ts # spawn_subagent — flash+high by default
|
||||
│ ├── plan.ts # submit_plan (review gate)
|
||||
│ └── web.ts # web_search, web_fetch
|
||||
├── mcp/ # MCP client + bridge (stdio + SSE)
|
||||
├── memory.ts # ImmutablePrefix / AppendOnlyLog / VolatileScratch
|
||||
├── project-memory.ts # REASONIX.md loader
|
||||
├── user-memory.ts # ~/.reasonix/memory/ store (project + global)
|
||||
├── skills.ts # built-in explore + research skills
|
||||
├── session.ts # JSONL session persistence
|
||||
├── telemetry.ts # cost + cache-hit accounting + SessionSummary
|
||||
├── tokenizer.ts # DeepSeek V3 tokenizer (ported)
|
||||
├── usage.ts # ~/.reasonix/usage.jsonl roll-up
|
||||
├── types.ts # ChatMessage, ToolCall, ToolSpec
|
||||
├── index.ts # library barrel
|
||||
└── cli/
|
||||
├── index.ts # commander entry
|
||||
├── commands/ # chat, run, stats, version
|
||||
└── ui/ # Ink React components (App, StatsPanel, EventLog, PromptInput)
|
||||
├── index.ts # commander entry
|
||||
├── resolve.ts # config + CLI flag precedence
|
||||
├── commands/ # chat, code, run, stats, sessions, ...
|
||||
└── ui/
|
||||
├── App.tsx # root Ink component (~1984 LOC, was 2931)
|
||||
├── LiveRows.tsx # spinner rows (OngoingTool / Status / ...)
|
||||
├── EventLog.tsx # Historical row rendering
|
||||
├── StatsPanel.tsx # top bar + cost badges
|
||||
├── PromptInput.tsx # cursor-aware multi-line input
|
||||
├── PlanConfirm.tsx # submit_plan review modal
|
||||
├── ShellConfirm.tsx # run_command approval modal
|
||||
├── EditConfirm.tsx # per-edit review modal
|
||||
├── markdown.tsx # Ink-native markdown renderer
|
||||
├── edit-history.ts # EditHistoryEntry + formatters
|
||||
├── useEditHistory.ts # /undo, /history, /show state machine
|
||||
├── useCompletionPickers.ts # slash, @, slash-arg pickers
|
||||
├── useSessionInfo.ts # balance + models + updates fetch
|
||||
├── useSubagent.ts # subagent sink wiring
|
||||
└── slash/ # /-command implementation
|
||||
├── types.ts # SlashContext, SlashResult, ...
|
||||
├── commands.ts # SLASH_COMMANDS data + parse + suggest
|
||||
├── helpers.ts # git, memory, token formatters
|
||||
├── dispatch.ts # registry + handleSlash lookup
|
||||
└── handlers/ # per-topic: basic, mcp, memory,
|
||||
# skill, admin, observability, edits,
|
||||
# jobs, sessions, model (/pro lives here)
|
||||
```
|
||||
|
||||
## Roadmap
|
||||
Files kept small by design: the largest module under `cli/ui/` is 2K
|
||||
lines (App.tsx), every handler under `slash/handlers/` is ≤200 lines,
|
||||
every hook under `cli/ui/` is ≤310 lines. Adding a new slash command
|
||||
means editing one handler file and one registry line.
|
||||
|
||||
- **v0.0.1** — Pillar 1 end-to-end, Pillar 3 complete, Ink TUI, τ-bench scaffold.
|
||||
- **v0.0.2** — First-run key prompt, saved to `~/.reasonix/config.json`.
|
||||
- **v0.0.3** — Pillar 2 MVP (opt-in harvest), retry layer, TextInput fix.
|
||||
- **v0.0.4** — Schema flatten auto-applied in ToolRegistry (closes Pillar 3).
|
||||
- **v0.0.5** — Self-consistency branching (`--branch N`) driven by Pillar 2
|
||||
plan-state uncertainty count.
|
||||
- **v0.0.6** — Named session persistence (`--session <name>`), JSONL log
|
||||
stored under `~/.reasonix/sessions/`, restored into the append-only log
|
||||
on resume.
|
||||
## Design evolution
|
||||
|
||||
- **v0.0.x** — Pillar 1 end-to-end, Pillar 3 complete, Ink TUI scaffold.
|
||||
- **v0.1** — τ-bench numbers published, streaming polish, transcript replay.
|
||||
- **v0.2** — Self-consistency / branch-budget sampling driven by plan state.
|
||||
- **v0.3** — MCP client, session persistence.
|
||||
- **v0.3** — MCP client (stdio + SSE), session persistence.
|
||||
- **v0.4.x** — `reasonix code` with SEARCH/REPLACE edits, review/auto
|
||||
gate, background jobs, hooks.
|
||||
- **v0.5.x** — V4 model support, skills, memory, subagents, actionable
|
||||
error messages.
|
||||
- **v0.6** *(current)* —
|
||||
- **Pillar 4 cost control** (flash-first defaults, auto-compaction,
|
||||
`/pro` one-shot, failure-triggered escalation, cost badges).
|
||||
- `deepseek-chat` / `deepseek-reasoner` scheduled for deprecation —
|
||||
all user-facing surfaces updated to `v4-flash` / `v4-pro`.
|
||||
- `branch` + `harvest` removed from every preset; manual opt-in only.
|
||||
- Shared prompt fragments (`TUI_FORMATTING_RULES`, `NEGATIVE_CLAIM_RULE`).
|
||||
- UI refactor: App.tsx split into 6 hooks/components, slash.ts split
|
||||
into 13 per-topic modules.
|
||||
|
||||
## Explicit non-goals
|
||||
|
||||
- Multi-agent orchestration.
|
||||
- Multi-agent orchestration as a first-class concept (subagents are a
|
||||
cost-reduction mechanism, not a coordination primitive).
|
||||
- RAG / vector retrieval.
|
||||
- Support for non-DeepSeek backends.
|
||||
- Support for non-DeepSeek backends (an OpenAI-compatible shim would
|
||||
work today via `--model` override, but is not tested).
|
||||
- Web UI / SaaS.
|
||||
- Automatic cost escalation without user-visible announcement. Every
|
||||
pro-tier model call is surfaced; silent escalation was considered
|
||||
and rejected.
|
||||
@@ -0,0 +1,95 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="760" height="170" viewBox="0 0 760 170" role="img" aria-label="Reasonix — DeepSeek-native agent framework">
|
||||
<title>Reasonix</title>
|
||||
<defs>
|
||||
<!-- Signature cyan → violet → fuchsia gradient used across the TUI wordmark
|
||||
and the brand mark. Renders well on both GitHub dark and light bg. -->
|
||||
<linearGradient id="rx-grad" x1="0%" y1="0%" x2="100%" y2="0%">
|
||||
<stop offset="0%" stop-color="#5eead4"/>
|
||||
<stop offset="15%" stop-color="#67e8f9"/>
|
||||
<stop offset="30%" stop-color="#7dd3fc"/>
|
||||
<stop offset="45%" stop-color="#93c5fd"/>
|
||||
<stop offset="60%" stop-color="#a5b4fc"/>
|
||||
<stop offset="75%" stop-color="#c4b5fd"/>
|
||||
<stop offset="90%" stop-color="#d8b4fe"/>
|
||||
<stop offset="100%" stop-color="#f0abfc"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="rx-grad-mark" x1="0%" y1="0%" x2="100%" y2="100%">
|
||||
<stop offset="0%" stop-color="#5eead4"/>
|
||||
<stop offset="50%" stop-color="#93c5fd"/>
|
||||
<stop offset="100%" stop-color="#c4b5fd"/>
|
||||
</linearGradient>
|
||||
<filter id="glow" x="-50%" y="-50%" width="200%" height="200%">
|
||||
<feGaussianBlur stdDeviation="3" result="blur"/>
|
||||
<feMerge>
|
||||
<feMergeNode in="blur"/>
|
||||
<feMergeNode in="SourceGraphic"/>
|
||||
</feMerge>
|
||||
</filter>
|
||||
</defs>
|
||||
|
||||
<!-- ◈ brand mark: concentric diamonds. Outer stroke pulses,
|
||||
inner fill breathes, whole group rotates slowly. The rotation
|
||||
is subtle (12s / full turn) so it feels like a heartbeat, not a
|
||||
spinner. -->
|
||||
<g transform="translate(90, 85)" filter="url(#glow)">
|
||||
<g>
|
||||
<animateTransform attributeName="transform" type="rotate"
|
||||
from="0" to="360" dur="18s" repeatCount="indefinite"/>
|
||||
<!-- Outer hollow diamond -->
|
||||
<path d="M 0,-46 L 46,0 L 0,46 L -46,0 Z"
|
||||
fill="none"
|
||||
stroke="url(#rx-grad-mark)"
|
||||
stroke-width="3.5"
|
||||
stroke-linejoin="round">
|
||||
<animate attributeName="stroke-width"
|
||||
values="3.5;5.5;3.5"
|
||||
dur="2.4s"
|
||||
repeatCount="indefinite"/>
|
||||
</path>
|
||||
<!-- Middle hollow diamond -->
|
||||
<path d="M 0,-26 L 26,0 L 0,26 L -26,0 Z"
|
||||
fill="none"
|
||||
stroke="url(#rx-grad-mark)"
|
||||
stroke-width="2"
|
||||
stroke-linejoin="round"
|
||||
opacity="0.7">
|
||||
<animate attributeName="opacity"
|
||||
values="0.4;0.9;0.4"
|
||||
dur="2.4s"
|
||||
begin="0.8s"
|
||||
repeatCount="indefinite"/>
|
||||
</path>
|
||||
<!-- Inner solid diamond -->
|
||||
<path d="M 0,-11 L 11,0 L 0,11 L -11,0 Z"
|
||||
fill="url(#rx-grad-mark)">
|
||||
<animate attributeName="opacity"
|
||||
values="0.75;1;0.75"
|
||||
dur="2.4s"
|
||||
repeatCount="indefinite"/>
|
||||
</path>
|
||||
</g>
|
||||
</g>
|
||||
|
||||
<!-- REASONIX wordmark with shifting gradient. The x1 offset animates
|
||||
so the gradient crawls left-to-right across the letters — a
|
||||
slow rainbow sweep that gives the logo life without being noisy. -->
|
||||
<text x="170" y="102"
|
||||
font-family="ui-monospace, SFMono-Regular, 'Cascadia Code', Menlo, Consolas, 'DejaVu Sans Mono', monospace"
|
||||
font-size="68"
|
||||
font-weight="800"
|
||||
fill="url(#rx-grad)"
|
||||
letter-spacing="6">REASONIX
|
||||
<animate attributeName="opacity"
|
||||
values="0.9;1;0.9"
|
||||
dur="3.2s"
|
||||
repeatCount="indefinite"/>
|
||||
</text>
|
||||
|
||||
<!-- Tagline sits just below the wordmark. Slate-500 reads well on
|
||||
both GitHub dark and light themes (~4.5:1 contrast either way). -->
|
||||
<text x="172" y="136"
|
||||
font-family="ui-monospace, SFMono-Regular, 'Cascadia Code', Menlo, Consolas, 'DejaVu Sans Mono', monospace"
|
||||
font-size="15"
|
||||
fill="#64748b"
|
||||
letter-spacing="0.5">DeepSeek-native agent framework · cache-first loop · Ink TUI</text>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 3.8 KiB |
@@ -0,0 +1,238 @@
|
||||
/**
|
||||
* Bundled demo MCP server.
|
||||
*
|
||||
* A minimal stdio MCP server that exposes three tools: echo, add, get_time.
|
||||
* Useful for:
|
||||
* - running the MCP integration end-to-end without installing
|
||||
* an external server
|
||||
* - giving the integration tests a real subprocess to spawn
|
||||
* - showing the minimal shape of a server for folks writing their own
|
||||
*
|
||||
* Usage:
|
||||
* npx tsx examples/mcp-server-demo.ts # speaks MCP on stdin/stdout
|
||||
* reasonix chat --mcp "npx tsx examples/mcp-server-demo.ts"
|
||||
*
|
||||
* Spec reference: https://spec.modelcontextprotocol.io/ (2024-11-05)
|
||||
* Only the subset this demo needs is implemented — initialize, tools/list,
|
||||
* tools/call, notifications/initialized (no-op).
|
||||
*/
|
||||
|
||||
import { createInterface } from "node:readline";
|
||||
|
||||
const PROTOCOL_VERSION = "2024-11-05";
|
||||
|
||||
interface JsonRpcRequest {
|
||||
jsonrpc: "2.0";
|
||||
id?: string | number;
|
||||
method: string;
|
||||
params?: unknown;
|
||||
}
|
||||
|
||||
interface JsonRpcSuccess {
|
||||
jsonrpc: "2.0";
|
||||
id: string | number;
|
||||
result: unknown;
|
||||
}
|
||||
|
||||
interface JsonRpcError {
|
||||
jsonrpc: "2.0";
|
||||
id: string | number | null;
|
||||
error: { code: number; message: string; data?: unknown };
|
||||
}
|
||||
|
||||
const TOOLS = [
|
||||
{
|
||||
name: "echo",
|
||||
description: "Echoes the provided message back.",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: { msg: { type: "string", description: "What to echo" } },
|
||||
required: ["msg"],
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "add",
|
||||
description: "Adds two integers and returns the sum.",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
a: { type: "integer" },
|
||||
b: { type: "integer" },
|
||||
},
|
||||
required: ["a", "b"],
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "get_time",
|
||||
description: "Returns the server's current ISO-8601 timestamp.",
|
||||
inputSchema: { type: "object", properties: {} },
|
||||
},
|
||||
{
|
||||
name: "slow_count",
|
||||
description:
|
||||
"Counts from 1 to n with a ~300 ms pause between steps, emitting notifications/progress frames along the way. Useful for demonstrating Reasonix's progress-bar UI.",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
n: { type: "integer", description: "Final number to count to (default 5, max 20)" },
|
||||
},
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
interface JsonRpcNotification {
|
||||
jsonrpc: "2.0";
|
||||
method: string;
|
||||
params?: unknown;
|
||||
}
|
||||
|
||||
function send(msg: JsonRpcSuccess | JsonRpcError | JsonRpcNotification): void {
|
||||
// Stdio MCP framing: one JSON per line.
|
||||
process.stdout.write(`${JSON.stringify(msg)}\n`);
|
||||
}
|
||||
|
||||
async function handleRequest(
|
||||
req: JsonRpcRequest,
|
||||
): Promise<JsonRpcSuccess | JsonRpcError | null> {
|
||||
const id = req.id ?? null;
|
||||
|
||||
switch (req.method) {
|
||||
case "initialize": {
|
||||
return {
|
||||
jsonrpc: "2.0",
|
||||
id: id ?? 0,
|
||||
result: {
|
||||
protocolVersion: PROTOCOL_VERSION,
|
||||
serverInfo: { name: "reasonix-demo-mcp", version: "0.0.1" },
|
||||
capabilities: { tools: { listChanged: false } },
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
case "notifications/initialized":
|
||||
// No response for notifications.
|
||||
return null;
|
||||
|
||||
case "tools/list": {
|
||||
return { jsonrpc: "2.0", id: id ?? 0, result: { tools: TOOLS } };
|
||||
}
|
||||
|
||||
case "tools/call": {
|
||||
const params = (req.params ?? {}) as {
|
||||
name?: string;
|
||||
arguments?: Record<string, unknown>;
|
||||
_meta?: { progressToken?: string | number };
|
||||
};
|
||||
const name = params.name ?? "";
|
||||
const args = params.arguments ?? {};
|
||||
const progressToken = params._meta?.progressToken;
|
||||
const out = await callTool(name, args, progressToken);
|
||||
if (out.error) {
|
||||
return {
|
||||
jsonrpc: "2.0",
|
||||
id: id ?? 0,
|
||||
result: {
|
||||
content: [{ type: "text", text: out.error }],
|
||||
isError: true,
|
||||
},
|
||||
};
|
||||
}
|
||||
return {
|
||||
jsonrpc: "2.0",
|
||||
id: id ?? 0,
|
||||
result: { content: [{ type: "text", text: out.text }] },
|
||||
};
|
||||
}
|
||||
|
||||
default:
|
||||
return {
|
||||
jsonrpc: "2.0",
|
||||
id,
|
||||
error: { code: -32601, message: `method not found: ${req.method}` },
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async function callTool(
|
||||
name: string,
|
||||
args: Record<string, unknown>,
|
||||
progressToken: string | number | undefined,
|
||||
): Promise<{ text: string; error?: string }> {
|
||||
if (name === "echo") {
|
||||
const msg = typeof args.msg === "string" ? args.msg : "";
|
||||
return { text: `echo: ${msg}` };
|
||||
}
|
||||
if (name === "add") {
|
||||
const a = typeof args.a === "number" ? args.a : Number(args.a);
|
||||
const b = typeof args.b === "number" ? args.b : Number(args.b);
|
||||
if (!Number.isFinite(a) || !Number.isFinite(b)) {
|
||||
return { text: "", error: "add: both a and b must be numbers" };
|
||||
}
|
||||
return { text: String(a + b) };
|
||||
}
|
||||
if (name === "get_time") {
|
||||
return { text: new Date().toISOString() };
|
||||
}
|
||||
if (name === "slow_count") {
|
||||
// Cap at 20 so an over-eager model can't make the demo run for
|
||||
// minutes. Default 5 gives ~1.5s which is plenty to see the bar.
|
||||
const raw = typeof args.n === "number" ? args.n : Number(args.n);
|
||||
const n = Number.isFinite(raw) && raw >= 1 ? Math.min(Math.floor(raw), 20) : 5;
|
||||
for (let i = 1; i <= n; i++) {
|
||||
await new Promise((r) => setTimeout(r, 300));
|
||||
if (progressToken !== undefined) {
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
method: "notifications/progress",
|
||||
params: {
|
||||
progressToken,
|
||||
progress: i,
|
||||
total: n,
|
||||
message: `counting ${i} of ${n}`,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
return { text: `counted to ${n}` };
|
||||
}
|
||||
return { text: "", error: `unknown tool: ${name}` };
|
||||
}
|
||||
|
||||
function main(): void {
|
||||
const rl = createInterface({ input: process.stdin, crlfDelay: Number.POSITIVE_INFINITY });
|
||||
rl.on("line", (line) => {
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed) return;
|
||||
let req: JsonRpcRequest;
|
||||
try {
|
||||
req = JSON.parse(trimmed) as JsonRpcRequest;
|
||||
} catch {
|
||||
// malformed input — respond with parse error
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
id: null,
|
||||
error: { code: -32700, message: "parse error" },
|
||||
});
|
||||
return;
|
||||
}
|
||||
// Fire-and-forget: handleRequest is async so slow tools (slow_count
|
||||
// and any future streamed-progress tools) can emit notifications
|
||||
// between in-flight requests without blocking the reader loop. Any
|
||||
// unexpected throw lands as an internal-error response so malformed
|
||||
// tool logic doesn't silently hang the client.
|
||||
handleRequest(req)
|
||||
.then((resp) => {
|
||||
if (resp) send(resp);
|
||||
})
|
||||
.catch((err) => {
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
id: req.id ?? null,
|
||||
error: { code: -32603, message: `internal: ${(err as Error).message}` },
|
||||
});
|
||||
});
|
||||
});
|
||||
rl.on("close", () => process.exit(0));
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -0,0 +1,70 @@
|
||||
/**
|
||||
* Library example: programmatic replay + diff.
|
||||
*
|
||||
* This example runs with no API key and no DeepSeek calls — it reads the
|
||||
* reference transcripts committed at benchmarks/tau-bench/transcripts/ and
|
||||
* reconstructs the v0.1 cache-hit / cost numbers offline.
|
||||
*
|
||||
* Run from the repo root:
|
||||
* npx tsx examples/replay-and-diff.ts
|
||||
*
|
||||
* Anything you can do with `reasonix replay` / `reasonix diff` is available
|
||||
* here as a function you can drive from your own scripts (CI gates, eval
|
||||
* dashboards, blog post generation, etc.).
|
||||
*/
|
||||
|
||||
import {
|
||||
computeReplayStats,
|
||||
diffTranscripts,
|
||||
readTranscript,
|
||||
renderDiffSummary,
|
||||
} from "../src/index.js";
|
||||
|
||||
const BASELINE = "benchmarks/tau-bench/transcripts/t01_address_happy.baseline.r1.jsonl";
|
||||
const REASONIX = "benchmarks/tau-bench/transcripts/t01_address_happy.reasonix.r1.jsonl";
|
||||
|
||||
// ---------- 1. Replay a single transcript as pure data ----------
|
||||
|
||||
const parsed = readTranscript(REASONIX);
|
||||
const stats = computeReplayStats(parsed.records);
|
||||
|
||||
console.log("=== Reasonix side, computed from transcript alone ===");
|
||||
console.log(` model calls: ${stats.turns}`);
|
||||
console.log(` cache hit: ${(stats.cacheHitRatio * 100).toFixed(1)}%`);
|
||||
console.log(` total cost: $${stats.totalCostUsd.toFixed(6)}`);
|
||||
console.log(` vs claude estimate: $${stats.claudeEquivalentUsd.toFixed(6)}`);
|
||||
console.log(` savings: ${stats.savingsVsClaudePct.toFixed(1)}%`);
|
||||
console.log(` prefix hashes: ${stats.prefixHashes.length} distinct`);
|
||||
if (stats.prefixHashes.length === 1) {
|
||||
console.log(` → byte-stable: ${stats.prefixHashes[0]?.slice(0, 16)}…`);
|
||||
}
|
||||
console.log();
|
||||
|
||||
// ---------- 2. Diff two transcripts ----------
|
||||
|
||||
const aParsed = readTranscript(BASELINE);
|
||||
const bParsed = readTranscript(REASONIX);
|
||||
|
||||
const report = diffTranscripts(
|
||||
{ label: "baseline", parsed: aParsed },
|
||||
{ label: "reasonix", parsed: bParsed },
|
||||
);
|
||||
|
||||
// renderDiffSummary returns a monochrome stdout-ready string. Equivalent to
|
||||
// what `reasonix diff --print` outputs.
|
||||
console.log(renderDiffSummary(report));
|
||||
|
||||
// ---------- 3. Direct programmatic access to pairs ----------
|
||||
//
|
||||
// You can also inspect report.pairs directly — useful for writing custom
|
||||
// filters like "show me only the turns where tool calls differed".
|
||||
|
||||
console.log("\n=== Turns where A and B took different paths ===");
|
||||
const divergent = report.pairs.filter((p) => p.kind !== "match");
|
||||
if (divergent.length === 0) {
|
||||
console.log(" (none — both agents followed the same path on every turn)");
|
||||
} else {
|
||||
for (const p of divergent) {
|
||||
console.log(` turn ${p.turn}: ${p.kind}${p.divergenceNote ? ` — ${p.divergenceNote}` : ""}`);
|
||||
}
|
||||
}
|
||||
+3
-2
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "reasonix",
|
||||
"version": "0.2.1",
|
||||
"description": "DeepSeek-native agent framework: cache-first loop, R1 thought harvesting, tool-call repair.",
|
||||
"version": "0.7.3",
|
||||
"description": "DeepSeek-native coding agent: cache-first loop, flash-first cost control, tool-call repair.",
|
||||
"type": "module",
|
||||
"bin": {
|
||||
"reasonix": "dist/cli/index.js"
|
||||
@@ -17,6 +17,7 @@
|
||||
},
|
||||
"files": [
|
||||
"dist",
|
||||
"data/deepseek-tokenizer.json.gz",
|
||||
"README.md",
|
||||
"LICENSE"
|
||||
],
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Regenerate `data/deepseek-tokenizer.json.gz` from an upstream
|
||||
* `tokenizer.json` (as shipped in DeepSeek's deepseek_v3_tokenizer.zip).
|
||||
*
|
||||
* Why slim+gz: the full tokenizer.json is 7.5MB; we only need four
|
||||
* fields (vocab, merges, pre_tokenizer, added_tokens). Strip + gzip
|
||||
* drops the committed artifact to ~1.7MB with no loss of fidelity
|
||||
* for encode-side token counting.
|
||||
*
|
||||
* Usage: `node --experimental-strip-types scripts/prepare-tokenizer.ts <path/to/tokenizer.json>`
|
||||
* (or via `tsx` / `ts-node`.)
|
||||
*/
|
||||
|
||||
import { readFileSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { gzipSync } from "node:zlib";
|
||||
|
||||
const src = process.argv[2];
|
||||
if (!src) {
|
||||
process.stderr.write("usage: prepare-tokenizer.ts <tokenizer.json>\n");
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
const raw = JSON.parse(readFileSync(src, "utf8"));
|
||||
const slim = {
|
||||
added_tokens: raw.added_tokens,
|
||||
pre_tokenizer: raw.pre_tokenizer,
|
||||
model: { type: raw.model.type, vocab: raw.model.vocab, merges: raw.model.merges },
|
||||
};
|
||||
const gz = gzipSync(Buffer.from(JSON.stringify(slim)), { level: 9 });
|
||||
const outPath = join(process.cwd(), "data", "deepseek-tokenizer.json.gz");
|
||||
writeFileSync(outPath, gz);
|
||||
process.stdout.write(`wrote ${outPath} (${(gz.length / 1024).toFixed(1)} KB)\n`);
|
||||
@@ -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);
|
||||
});
|
||||
@@ -0,0 +1,397 @@
|
||||
/**
|
||||
* Expand `@path/to/file` mentions in a user prompt to inline file
|
||||
* content.
|
||||
*
|
||||
* Why: most interactive coding sessions start with "look at X, then
|
||||
* change Y". Typing `@src/loop.ts` reads faster and cheaper than
|
||||
* "look at src/loop.ts (and the model fires read_file, and we pay for
|
||||
* the round trip)" — the model sees the file content from turn 1
|
||||
* instead of round-tripping a tool call for it.
|
||||
*
|
||||
* Shape: the user's text is kept verbatim. Expanded file contents are
|
||||
* appended in a "Referenced files" block at the end, each wrapped in
|
||||
* `<file path="...">...</file>` so the model can cite them back
|
||||
* unambiguously.
|
||||
*
|
||||
* Safety: paths must resolve inside `rootDir` (no `..` escape, no
|
||||
* absolute paths), must exist as a regular file, and must be under
|
||||
* `maxBytes`. Missing / too-large / escaping paths get a short note
|
||||
* appended instead of content so the user sees why it was skipped.
|
||||
*/
|
||||
|
||||
import { type Dirent, existsSync, readFileSync, readdirSync, statSync } from "node:fs";
|
||||
import { isAbsolute, join, relative, resolve } from "node:path";
|
||||
|
||||
/** Caps match tool-result dispatch truncation (0.5.2). */
|
||||
export const DEFAULT_AT_MENTION_MAX_BYTES = 64 * 1024;
|
||||
|
||||
/**
|
||||
* Default directory names skipped when listing files for the picker.
|
||||
* Matches what most repos gitignore AND keeps the picker off the
|
||||
* hottest bloat — `node_modules` alone can be 100k+ entries.
|
||||
*/
|
||||
export const DEFAULT_PICKER_IGNORE_DIRS: readonly string[] = [
|
||||
"node_modules",
|
||||
".git",
|
||||
"dist",
|
||||
"build",
|
||||
".next",
|
||||
"out",
|
||||
"coverage",
|
||||
".cache",
|
||||
".vscode",
|
||||
".idea",
|
||||
"target",
|
||||
".venv",
|
||||
"venv",
|
||||
"__pycache__",
|
||||
];
|
||||
|
||||
export interface ListFilesOptions {
|
||||
/** Cap the walk once we've collected this many entries. Default 500. */
|
||||
maxResults?: number;
|
||||
/** Directory names to skip entirely. Defaults to {@link DEFAULT_PICKER_IGNORE_DIRS}. */
|
||||
ignoreDirs?: readonly string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Walk `root` recursively and return relative file paths (forward-slash
|
||||
* separator, regardless of platform) for the `@` picker.
|
||||
*
|
||||
* Synchronous on purpose: this runs once at App mount (and on each turn
|
||||
* so newly-created files show up) and blocks the render thread for a
|
||||
* predictable ~10-50ms on a moderate repo. An async variant would need
|
||||
* to coordinate with the Ink render loop; sync fits the rest of the
|
||||
* TUI's single-turn-per-tick model cleanly.
|
||||
*
|
||||
* Skips:
|
||||
* - directories in `ignoreDirs` (default: DEFAULT_PICKER_IGNORE_DIRS)
|
||||
* - any directory whose name starts with `.` (covers `.git`,
|
||||
* `.vscode`, dotfile vendors). Dotfile REGULAR FILES (`.env`,
|
||||
* `.gitignore`, `.prettierrc`) are kept — users reference them.
|
||||
* - entries the walker can't read (permission errors, broken links).
|
||||
*/
|
||||
export function listFilesSync(root: string, opts: ListFilesOptions = {}): string[] {
|
||||
return listFilesWithStatsSync(root, opts).map((e) => e.path);
|
||||
}
|
||||
|
||||
export interface FileWithStats {
|
||||
/** Relative path with forward-slash separator. */
|
||||
path: string;
|
||||
/** Modification time (Date.getTime() / ms since epoch). 0 when stat failed. */
|
||||
mtimeMs: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Same walk as {@link listFilesSync} but also statS each file for
|
||||
* modification time. Used by the `@` picker to surface recently-
|
||||
* edited files first — matches VS Code Quick Open / similar UX.
|
||||
*
|
||||
* Stat failures don't throw: the entry is kept with `mtimeMs: 0` so
|
||||
* it still appears in the picker (just sinks to the bottom of the
|
||||
* recency sort).
|
||||
*/
|
||||
export function listFilesWithStatsSync(root: string, opts: ListFilesOptions = {}): FileWithStats[] {
|
||||
const maxResults = Math.max(1, opts.maxResults ?? 500);
|
||||
const ignore = new Set(opts.ignoreDirs ?? DEFAULT_PICKER_IGNORE_DIRS);
|
||||
const rootAbs = resolve(root);
|
||||
const out: FileWithStats[] = [];
|
||||
|
||||
const walk = (dirAbs: string, dirRel: string) => {
|
||||
if (out.length >= maxResults) return;
|
||||
let entries: Dirent[];
|
||||
try {
|
||||
entries = readdirSync(dirAbs, { withFileTypes: true });
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
entries.sort((a, b) => a.name.localeCompare(b.name));
|
||||
for (const ent of entries) {
|
||||
if (out.length >= maxResults) return;
|
||||
const relPath = dirRel ? `${dirRel}/${ent.name}` : ent.name;
|
||||
if (ent.isDirectory()) {
|
||||
if (ent.name.startsWith(".") || ignore.has(ent.name)) continue;
|
||||
walk(join(dirAbs, ent.name), relPath);
|
||||
} else if (ent.isFile()) {
|
||||
let mtimeMs = 0;
|
||||
try {
|
||||
mtimeMs = statSync(join(dirAbs, ent.name)).mtimeMs;
|
||||
} catch {
|
||||
/* stat failed (permission / EAGAIN) — keep the entry with mtime=0 */
|
||||
}
|
||||
out.push({ path: relPath, mtimeMs });
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
walk(rootAbs, "");
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prefix pattern used by the `@` picker to detect an IN-PROGRESS
|
||||
* mention at the END of the input buffer. Captures the partial path
|
||||
* (which may be empty — just `@`) so the picker can use it as a
|
||||
* substring filter.
|
||||
*
|
||||
* Distinct from {@link AT_MENTION_PATTERN} (which finds completed
|
||||
* mentions anywhere in the text for expansion-at-submit). This one
|
||||
* fires on the trailing token only, anchored at end-of-input.
|
||||
*/
|
||||
export const AT_PICKER_PREFIX = /(?:^|\s)@([a-zA-Z0-9_./\\-]*)$/;
|
||||
|
||||
/**
|
||||
* Return the picker state for a given input buffer: the partial query
|
||||
* (may be empty string — just `@`) and the buffer offset of the `@`
|
||||
* character. `null` when the buffer doesn't end in a mention-in-
|
||||
* progress.
|
||||
*/
|
||||
export function detectAtPicker(input: string): { query: string; atOffset: number } | null {
|
||||
const m = AT_PICKER_PREFIX.exec(input);
|
||||
if (!m) return null;
|
||||
const query = m[1] ?? "";
|
||||
// `m.index` is the offset of the capture group's SURROUNDING match —
|
||||
// which starts at either ^ or the preceding whitespace. The `@`
|
||||
// itself is at `end-of-input - query.length - 1`.
|
||||
const atOffset = input.length - query.length - 1;
|
||||
return { query, atOffset };
|
||||
}
|
||||
|
||||
/** A candidate accepted by the picker ranker — either a bare path or a path with mtime. */
|
||||
export type PickerCandidate = string | FileWithStats;
|
||||
|
||||
export interface RankPickerOptions {
|
||||
/** Upper bound on returned entries. Default 40. */
|
||||
limit?: number;
|
||||
/**
|
||||
* Paths the user or model has touched recently (via tool calls like
|
||||
* `read_file` / `edit_file`). Matching paths get a recency boost so
|
||||
* the picker surfaces "stuff I just looked at" near the top.
|
||||
*/
|
||||
recentlyUsed?: readonly string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter and rank candidate files against the picker's partial query.
|
||||
*
|
||||
* Empty query:
|
||||
* - Sort by "recently used" bucket first (if provided), then mtime
|
||||
* descending (newer first), then path alpha.
|
||||
* - Pure-string input (no mtime data) falls back to alpha since
|
||||
* recency info isn't available.
|
||||
*
|
||||
* Non-empty query:
|
||||
* - Case-insensitive substring match, with a basename-prefix boost
|
||||
* so `lo` floats `loop.ts`-shaped paths to the top.
|
||||
* - Ties broken first by recently-used membership, then mtime.
|
||||
*
|
||||
* Back-compat: passes `string[]` through the same logic (mtime = 0,
|
||||
* recently-used still honored).
|
||||
*/
|
||||
export function rankPickerCandidates(
|
||||
files: readonly PickerCandidate[],
|
||||
query: string,
|
||||
limitOrOpts?: number | RankPickerOptions,
|
||||
): string[] {
|
||||
const opts: RankPickerOptions =
|
||||
typeof limitOrOpts === "number" ? { limit: limitOrOpts } : (limitOrOpts ?? {});
|
||||
const limit = opts.limit ?? 40;
|
||||
const recent = new Set(opts.recentlyUsed ?? []);
|
||||
|
||||
const entries: FileWithStats[] = files.map((f) =>
|
||||
typeof f === "string" ? { path: f, mtimeMs: 0 } : f,
|
||||
);
|
||||
|
||||
if (!query) {
|
||||
// Only re-sort when we actually have signal to sort by. If input
|
||||
// is bare strings (mtime = 0 everywhere) AND there's no recent-
|
||||
// used list, preserve input order so callers keep their existing
|
||||
// layout. Passing FileWithStats or a non-empty recentlyUsed opts
|
||||
// you into mtime+recency ranking.
|
||||
const anyMtime = entries.some((e) => e.mtimeMs > 0);
|
||||
if (!anyMtime && recent.size === 0) {
|
||||
return entries.slice(0, limit).map((e) => e.path);
|
||||
}
|
||||
const sorted = [...entries].sort((a, b) => {
|
||||
const aRecent = recent.has(a.path) ? 1 : 0;
|
||||
const bRecent = recent.has(b.path) ? 1 : 0;
|
||||
if (aRecent !== bRecent) return bRecent - aRecent;
|
||||
if (a.mtimeMs !== b.mtimeMs) return b.mtimeMs - a.mtimeMs;
|
||||
return a.path.localeCompare(b.path);
|
||||
});
|
||||
return sorted.slice(0, limit).map((e) => e.path);
|
||||
}
|
||||
|
||||
const needle = query.toLowerCase();
|
||||
const scored: Array<{ path: string; score: number; mtimeMs: number; recent: boolean }> = [];
|
||||
for (const e of entries) {
|
||||
const lower = e.path.toLowerCase();
|
||||
const hit = lower.indexOf(needle);
|
||||
if (hit < 0) continue;
|
||||
const slash = lower.lastIndexOf("/");
|
||||
const base = slash >= 0 ? lower.slice(slash + 1) : lower;
|
||||
let score = 2;
|
||||
if (base.startsWith(needle)) score = 0;
|
||||
else if (lower.startsWith(needle)) score = 1;
|
||||
scored.push({
|
||||
path: e.path,
|
||||
score: score * 10_000 + hit,
|
||||
mtimeMs: e.mtimeMs,
|
||||
recent: recent.has(e.path),
|
||||
});
|
||||
}
|
||||
scored.sort((a, b) => {
|
||||
if (a.score !== b.score) return a.score - b.score;
|
||||
// Tie-break: recently-used, then mtime (newer first).
|
||||
if (a.recent !== b.recent) return a.recent ? -1 : 1;
|
||||
return b.mtimeMs - a.mtimeMs;
|
||||
});
|
||||
return scored.slice(0, limit).map((s) => s.path);
|
||||
}
|
||||
|
||||
/**
|
||||
* Matches `@` at a word boundary (start-of-string or preceded by
|
||||
* whitespace) followed by a path-like token. Deliberately rejects `@`
|
||||
* embedded in longer words (email addresses, mentions on social sites)
|
||||
* by requiring the word boundary.
|
||||
*
|
||||
* Path charset keeps it to the characters that appear in real repo
|
||||
* paths — letters, digits, `_` `-` `.` `/` `\`. Trailing `.` (e.g.
|
||||
* `@foo.ts.`) is stripped before lookup so a sentence-terminating
|
||||
* period doesn't break the mention.
|
||||
*/
|
||||
export const AT_MENTION_PATTERN = /(?<=^|\s)@([a-zA-Z0-9_./\\-]+)/g;
|
||||
|
||||
export interface AtMentionExpansion {
|
||||
/** The raw `@path` token as it appeared in the text. */
|
||||
token: string;
|
||||
/** The relative path, as resolved against rootDir. */
|
||||
path: string;
|
||||
/** True if the content was inlined. False = skipped (reason in `skip`). */
|
||||
ok: boolean;
|
||||
/** Bytes read (only for ok=true). */
|
||||
bytes?: number;
|
||||
/** Why the mention was skipped. Set when ok=false. */
|
||||
skip?: "missing" | "not-file" | "too-large" | "escape" | "read-error";
|
||||
}
|
||||
|
||||
export interface AtMentionOptions {
|
||||
/** Max file size in bytes before a mention is skipped. */
|
||||
maxBytes?: number;
|
||||
/**
|
||||
* Optional file-system overrides for tests. Real callers omit these;
|
||||
* the helper falls through to `node:fs`.
|
||||
*/
|
||||
fs?: {
|
||||
exists: (path: string) => boolean;
|
||||
isFile: (path: string) => boolean;
|
||||
size: (path: string) => number;
|
||||
read: (path: string) => string;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Expand `@path` mentions in `text`. Returns the (possibly augmented)
|
||||
* text plus a per-mention report so the caller can surface expansions
|
||||
* in the UI.
|
||||
*/
|
||||
export function expandAtMentions(
|
||||
text: string,
|
||||
rootDir: string,
|
||||
opts: AtMentionOptions = {},
|
||||
): { text: string; expansions: AtMentionExpansion[] } {
|
||||
const maxBytes = opts.maxBytes ?? DEFAULT_AT_MENTION_MAX_BYTES;
|
||||
const fs = opts.fs ?? defaultFs;
|
||||
const root = resolve(rootDir);
|
||||
// De-dupe by token so `@file.ts` referenced twice inlines once.
|
||||
const seen = new Map<string, AtMentionExpansion>();
|
||||
const expansions: AtMentionExpansion[] = [];
|
||||
|
||||
for (const match of text.matchAll(AT_MENTION_PATTERN)) {
|
||||
const rawPath = match[1] ?? "";
|
||||
// Strip trailing dot (sentence terminator): `@foo.ts.` → `@foo.ts`.
|
||||
// Keep internal dots intact.
|
||||
const cleaned = rawPath.replace(/\.+$/, "");
|
||||
if (!cleaned) continue;
|
||||
const token = `@${cleaned}`;
|
||||
if (seen.has(token)) continue;
|
||||
|
||||
const expansion = resolveMention(cleaned, root, maxBytes, fs);
|
||||
seen.set(token, expansion);
|
||||
expansions.push(expansion);
|
||||
}
|
||||
|
||||
if (expansions.length === 0) return { text, expansions };
|
||||
|
||||
// Build the trailing "Referenced files" block. Keep successful
|
||||
// inlines and skipped ones (with their reason) so the model sees
|
||||
// both what's here and what's missing.
|
||||
const blocks: string[] = [];
|
||||
for (const ex of expansions) {
|
||||
if (ex.ok) {
|
||||
const content = readSafe(root, ex.path, fs);
|
||||
blocks.push(`<file path="${ex.path}">\n${content}\n</file>`);
|
||||
} else {
|
||||
blocks.push(`<file path="${ex.path}" skipped="${ex.skip}" />`);
|
||||
}
|
||||
}
|
||||
const augmented = `${text}\n\n[Referenced files]\n${blocks.join("\n\n")}`;
|
||||
return { text: augmented, expansions };
|
||||
}
|
||||
|
||||
function resolveMention(
|
||||
rawPath: string,
|
||||
root: string,
|
||||
maxBytes: number,
|
||||
fs: NonNullable<AtMentionOptions["fs"]>,
|
||||
): AtMentionExpansion {
|
||||
// Reject absolute paths — `@/etc/passwd` should not inline.
|
||||
if (isAbsolute(rawPath)) {
|
||||
return { token: `@${rawPath}`, path: rawPath, ok: false, skip: "escape" };
|
||||
}
|
||||
const resolved = resolve(root, rawPath);
|
||||
// Sandbox escape: after resolution the path must still be inside root.
|
||||
const rel = relative(root, resolved);
|
||||
if (rel.startsWith("..") || isAbsolute(rel)) {
|
||||
return { token: `@${rawPath}`, path: rawPath, ok: false, skip: "escape" };
|
||||
}
|
||||
if (!fs.exists(resolved)) {
|
||||
return { token: `@${rawPath}`, path: rawPath, ok: false, skip: "missing" };
|
||||
}
|
||||
if (!fs.isFile(resolved)) {
|
||||
return { token: `@${rawPath}`, path: rawPath, ok: false, skip: "not-file" };
|
||||
}
|
||||
const size = fs.size(resolved);
|
||||
if (size > maxBytes) {
|
||||
return { token: `@${rawPath}`, path: rawPath, ok: false, skip: "too-large", bytes: size };
|
||||
}
|
||||
return { token: `@${rawPath}`, path: rawPath, ok: true, bytes: size };
|
||||
}
|
||||
|
||||
function readSafe(root: string, rawPath: string, fs: NonNullable<AtMentionOptions["fs"]>): string {
|
||||
const resolved = resolve(root, rawPath);
|
||||
try {
|
||||
return fs.read(resolved);
|
||||
} catch {
|
||||
return "(read failed)";
|
||||
}
|
||||
}
|
||||
|
||||
const defaultFs: NonNullable<AtMentionOptions["fs"]> = {
|
||||
exists: (p) => existsSync(p),
|
||||
isFile: (p) => {
|
||||
try {
|
||||
return statSync(p).isFile();
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
size: (p) => {
|
||||
try {
|
||||
return statSync(p).size;
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
},
|
||||
read: (p) => readFileSync(p, "utf8"),
|
||||
};
|
||||
+254
-7
@@ -1,9 +1,34 @@
|
||||
import { existsSync, statSync } from "node:fs";
|
||||
import { render } from "ink";
|
||||
import React, { useState } from "react";
|
||||
import { loadApiKey } from "../../config.js";
|
||||
import { loadApiKey, searchEnabled } from "../../config.js";
|
||||
import { loadDotenv } from "../../env.js";
|
||||
import { McpClient } from "../../mcp/client.js";
|
||||
import { type InspectionReport, inspectMcpServer } from "../../mcp/inspect.js";
|
||||
import { bridgeMcpTools } from "../../mcp/registry.js";
|
||||
import { parseMcpSpec } from "../../mcp/spec.js";
|
||||
import { SseTransport } from "../../mcp/sse.js";
|
||||
import { type McpTransport, StdioTransport } from "../../mcp/stdio.js";
|
||||
import {
|
||||
loadSessionMessages,
|
||||
rewriteSession,
|
||||
sessionPath as sessionPathOf,
|
||||
} from "../../session.js";
|
||||
import { ToolRegistry } from "../../tools.js";
|
||||
import { registerChoiceTool } from "../../tools/choice.js";
|
||||
import { registerMemoryTools } from "../../tools/memory.js";
|
||||
import { registerWebTools } from "../../tools/web.js";
|
||||
import { App } from "../ui/App.js";
|
||||
import { SessionPicker } from "../ui/SessionPicker.js";
|
||||
import { Setup } from "../ui/Setup.js";
|
||||
import type { McpServerSummary } from "../ui/slash.js";
|
||||
|
||||
export interface ProgressInfo {
|
||||
toolName: string;
|
||||
progress: number;
|
||||
total?: number;
|
||||
message?: string;
|
||||
}
|
||||
|
||||
export interface ChatOptions {
|
||||
model: string;
|
||||
@@ -12,14 +37,59 @@ export interface ChatOptions {
|
||||
harvest?: boolean;
|
||||
branch?: number;
|
||||
session?: string;
|
||||
/** Zero or more MCP server specs. Each: `"name=cmd args..."` or `"cmd args..."`. */
|
||||
mcp?: string[];
|
||||
/** Global prefix — only used when a single anonymous server is given. */
|
||||
mcpPrefix?: string;
|
||||
/**
|
||||
* Pre-built ToolRegistry used as a seed. MCP bridges (if any) are
|
||||
* layered on top of whatever's already registered. Used by
|
||||
* `reasonix code` to register native filesystem tools in place of
|
||||
* the old `npx -y @modelcontextprotocol/server-filesystem` subprocess.
|
||||
*/
|
||||
seedTools?: ToolRegistry;
|
||||
/**
|
||||
* Enable SEARCH/REPLACE edit-block processing after each assistant turn.
|
||||
* Set by `reasonix code`; plain `reasonix chat` leaves this off.
|
||||
*/
|
||||
codeMode?: { rootDir: string; jobs?: import("../../tools/jobs.js").JobRegistry };
|
||||
/** Skip the session picker — assume "Resume" (backwards-compatible auto-continue). */
|
||||
forceResume?: boolean;
|
||||
/** Skip the session picker — assume "New" (wipe the session file and start fresh). */
|
||||
forceNew?: boolean;
|
||||
}
|
||||
|
||||
interface RootProps extends ChatOptions {
|
||||
initialKey: string | undefined;
|
||||
tools: ToolRegistry | undefined;
|
||||
mcpSpecs: string[];
|
||||
mcpServers: McpServerSummary[];
|
||||
/**
|
||||
* Shared ref the bridge's `onProgress` callback writes through.
|
||||
* App sets `.current` to its own handler on mount so every
|
||||
* progress frame from any bridged tool lands in the UI's
|
||||
* `OngoingToolRow`. Ref keeps the wire-up synchronous with
|
||||
* React reconciliation (no effect-timing surprises).
|
||||
*/
|
||||
progressSink: { current: ((info: ProgressInfo) => void) | null };
|
||||
/** Present when the session has prior messages; drives the picker. */
|
||||
sessionPreview?: { messageCount: number; lastActive: Date };
|
||||
}
|
||||
|
||||
function Root({ initialKey, ...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
|
||||
@@ -30,8 +100,27 @@ function Root({ initialKey, ...appProps }: RootProps) {
|
||||
/>
|
||||
);
|
||||
}
|
||||
// Ensure the loop's DeepSeekClient picks up the key when it lazy-instantiates.
|
||||
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}
|
||||
@@ -40,6 +129,11 @@ function Root({ initialKey, ...appProps }: RootProps) {
|
||||
harvest={appProps.harvest}
|
||||
branch={appProps.branch}
|
||||
session={appProps.session}
|
||||
tools={tools}
|
||||
mcpSpecs={mcpSpecs}
|
||||
mcpServers={mcpServers}
|
||||
progressSink={progressSink}
|
||||
codeMode={appProps.codeMode}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -47,8 +141,161 @@ function Root({ initialKey, ...appProps }: RootProps) {
|
||||
export async function chatCommand(opts: ChatOptions): Promise<void> {
|
||||
loadDotenv();
|
||||
const initialKey = loadApiKey();
|
||||
const { waitUntilExit } = render(<Root initialKey={initialKey} {...opts} />, {
|
||||
exitOnCtrlC: true,
|
||||
});
|
||||
await waitUntilExit();
|
||||
|
||||
const requestedSpecs = opts.mcp ?? [];
|
||||
const clients: McpClient[] = [];
|
||||
const successfulSpecs: string[] = [];
|
||||
const failedSpecs: Array<{ spec: string; reason: string }> = [];
|
||||
const mcpServers: McpServerSummary[] = [];
|
||||
// Shared progress sink: the bridge's onProgress callback writes
|
||||
// through `progressSink.current`, which App.tsx sets to its UI
|
||||
// updater on mount. Started null so early progress frames (before
|
||||
// the App has mounted) are dropped rather than buffered.
|
||||
const progressSink: { current: ((info: ProgressInfo) => void) | null } = { current: null };
|
||||
// Seed registry from the caller (e.g. reasonix code's native
|
||||
// filesystem tools) — MCP bridges layer on top rather than
|
||||
// replacing. When no seed AND no MCP, tools stays undefined and
|
||||
// the loop runs as a bare chat.
|
||||
let tools: ToolRegistry | undefined = opts.seedTools;
|
||||
|
||||
if (requestedSpecs.length > 0) {
|
||||
if (!tools) tools = new ToolRegistry();
|
||||
for (const raw of requestedSpecs) {
|
||||
try {
|
||||
const spec = parseMcpSpec(raw);
|
||||
const prefix = spec.name
|
||||
? `${spec.name}_`
|
||||
: requestedSpecs.length === 1 && opts.mcpPrefix
|
||||
? opts.mcpPrefix
|
||||
: "";
|
||||
const transport: McpTransport =
|
||||
spec.transport === "sse"
|
||||
? new SseTransport({ url: spec.url })
|
||||
: new StdioTransport({ command: spec.command, args: spec.args });
|
||||
const mcp = new McpClient({ transport });
|
||||
await mcp.initialize();
|
||||
const bridge = await bridgeMcpTools(mcp, {
|
||||
registry: tools,
|
||||
namePrefix: prefix,
|
||||
onProgress: (info) => progressSink.current?.(info),
|
||||
});
|
||||
// Collect resources + prompts once at startup so the /mcp
|
||||
// slash can render them synchronously. Servers that don't
|
||||
// support these fall through as `{supported: false}` instead
|
||||
// of throwing — see inspectMcpServer.
|
||||
let report: InspectionReport;
|
||||
try {
|
||||
report = await inspectMcpServer(mcp);
|
||||
} catch {
|
||||
// If the inspect call itself fails (rare — shouldn't happen
|
||||
// since inspectMcpServer swallows -32601), synthesize a
|
||||
// minimal report so `/mcp` still has something to render.
|
||||
report = {
|
||||
protocolVersion: mcp.protocolVersion,
|
||||
serverInfo: mcp.serverInfo,
|
||||
capabilities: mcp.serverCapabilities ?? {},
|
||||
tools: { supported: true, items: [] },
|
||||
resources: { supported: false, reason: "inspect failed" },
|
||||
prompts: { supported: false, reason: "inspect failed" },
|
||||
};
|
||||
}
|
||||
const label = spec.name ?? "anon";
|
||||
const source =
|
||||
spec.transport === "sse" ? spec.url : `${spec.command} ${spec.args.join(" ")}`;
|
||||
process.stderr.write(
|
||||
`▸ MCP[${label}]: ${bridge.registeredNames.length} tool(s) from ${source}\n`,
|
||||
);
|
||||
clients.push(mcp);
|
||||
successfulSpecs.push(raw);
|
||||
mcpServers.push({
|
||||
label,
|
||||
spec: raw,
|
||||
toolCount: bridge.registeredNames.length,
|
||||
report,
|
||||
client: mcp,
|
||||
});
|
||||
} catch (err) {
|
||||
// Per-server failure is non-fatal: one broken server shouldn't
|
||||
// kill a chat that has working servers configured. We record
|
||||
// the failure, show a visible warning, and keep going. User
|
||||
// can fix via `reasonix setup` (unchecks the broken entry)
|
||||
// without losing their other servers.
|
||||
const reason = (err as Error).message;
|
||||
failedSpecs.push({ spec: raw, reason });
|
||||
process.stderr.write(
|
||||
`▸ MCP setup SKIPPED for "${raw}": ${reason}\n → this server will not be available this session. Run \`reasonix setup\` to remove it, or fix the underlying issue (missing npm package, network, etc.).\n`,
|
||||
);
|
||||
}
|
||||
}
|
||||
// If every requested server failed AND no seed registry was
|
||||
// provided, drop the empty registry so the loop still runs as a
|
||||
// bare chat instead of advertising zero tools. If the caller
|
||||
// passed seedTools we keep the registry — the seed tools are
|
||||
// still there and usable.
|
||||
if (successfulSpecs.length === 0 && !opts.seedTools) {
|
||||
tools = undefined;
|
||||
}
|
||||
}
|
||||
const 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).
|
||||
// `run_skill` is registered later in App.tsx (where the client
|
||||
// exists) so it can wire the subagent runner for runAs:subagent
|
||||
// skills.
|
||||
if (!opts.seedTools) {
|
||||
if (!tools) tools = new ToolRegistry();
|
||||
registerMemoryTools(tools, {});
|
||||
// `ask_choice` — branching primitive, useful in chat too (stylistic
|
||||
// preferences, doc language, library picks). Independent of plan
|
||||
// mode, which chat doesn't have anyway.
|
||||
registerChoiceTool(tools);
|
||||
}
|
||||
|
||||
// Decide whether to show the session picker. It's gated on: session
|
||||
// persistence is on, the session file already has prior messages, and
|
||||
// the caller didn't pre-commit to one of the choices via --resume /
|
||||
// --new flags. `--new` wipes the file now (before the loop opens),
|
||||
// so the App mounts against a fresh log.
|
||||
let sessionPreview: { messageCount: number; lastActive: Date } | undefined;
|
||||
if (opts.session && !opts.forceResume && !opts.forceNew) {
|
||||
const prior = loadSessionMessages(opts.session);
|
||||
if (prior.length > 0) {
|
||||
const p = sessionPathOf(opts.session);
|
||||
const mtime = existsSync(p) ? statSync(p).mtime : new Date();
|
||||
sessionPreview = { messageCount: prior.length, lastActive: mtime };
|
||||
}
|
||||
} else if (opts.session && opts.forceNew) {
|
||||
rewriteSession(opts.session, []);
|
||||
}
|
||||
|
||||
const { waitUntilExit } = render(
|
||||
<Root
|
||||
initialKey={initialKey}
|
||||
tools={tools}
|
||||
mcpSpecs={mcpSpecs}
|
||||
mcpServers={mcpServers}
|
||||
progressSink={progressSink}
|
||||
sessionPreview={sessionPreview}
|
||||
{...opts}
|
||||
/>,
|
||||
// patchConsole:false — we never log to console during the TUI, and the
|
||||
// patch is a known redraw-glitch source on winpty/MINTTY terminals.
|
||||
{ exitOnCtrlC: true, patchConsole: false },
|
||||
);
|
||||
try {
|
||||
await waitUntilExit();
|
||||
} finally {
|
||||
for (const c of clients) await c.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
/**
|
||||
* `reasonix code [dir]` — opinionated wrapper around `reasonix chat` for
|
||||
* code-editing workflows.
|
||||
*
|
||||
* What it does differently from plain chat:
|
||||
* - Registers native filesystem tools rooted at the given directory
|
||||
* (CWD by default). No subprocess, no `npx install` step, R1-
|
||||
* friendly schemas. Replaced the old `@modelcontextprotocol/server-filesystem`
|
||||
* subprocess in 0.4.9 because its `edit_file` argv shape was the
|
||||
* biggest driver of R1 DSML hallucinations.
|
||||
* - Uses a coding-focused system prompt (src/code/prompt.ts) that
|
||||
* teaches the model to propose edits as SEARCH/REPLACE blocks.
|
||||
* - Defaults to the `smart` preset (reasoner + harvest) because
|
||||
* coding tasks pay back R1 thinking.
|
||||
* - Scopes its session to the directory so projects don't share
|
||||
* conversation history.
|
||||
* - Hooks `codeMode` into the TUI so assistant replies get parsed
|
||||
* for SEARCH/REPLACE blocks and applied on disk after each turn.
|
||||
*/
|
||||
|
||||
import { basename, resolve } from "node:path";
|
||||
import { loadProjectShellAllowed } from "../../config.js";
|
||||
import { sanitizeName } from "../../session.js";
|
||||
import { ToolRegistry } from "../../tools.js";
|
||||
import { registerChoiceTool } from "../../tools/choice.js";
|
||||
import { registerFilesystemTools } from "../../tools/filesystem.js";
|
||||
import { JobRegistry } from "../../tools/jobs.js";
|
||||
import { registerMemoryTools } from "../../tools/memory.js";
|
||||
import { registerPlanTool } from "../../tools/plan.js";
|
||||
import { registerShellTools } from "../../tools/shell.js";
|
||||
import { chatCommand } from "./chat.js";
|
||||
|
||||
export interface CodeOptions {
|
||||
/** Directory to root the filesystem tools at. Defaults to process.cwd(). */
|
||||
dir?: string;
|
||||
/** Override the default `smart` model. */
|
||||
model?: string;
|
||||
/** Disable session persistence. */
|
||||
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;
|
||||
/**
|
||||
* Opt into Pillar 2 harvesting (extracts a typed plan state from R1
|
||||
* reasoning via an extra V3 call). Default OFF in code mode — the
|
||||
* displayed subgoals/hypotheses/rejectedPaths have no programmatic
|
||||
* consumer, only `uncertainties.length` feeds branching, and the
|
||||
* extra V3 call adds ~10-15% per-turn cost. Users who want the
|
||||
* reasoning surfaced explicitly can pass `--harvest`.
|
||||
*/
|
||||
harvest?: boolean;
|
||||
}
|
||||
|
||||
export async function codeCommand(opts: CodeOptions = {}): Promise<void> {
|
||||
const { codeSystemPrompt } = await import("../../code/prompt.js");
|
||||
const rootDir = resolve(opts.dir ?? process.cwd());
|
||||
// Per-directory session so switching projects doesn't mix histories.
|
||||
// `code-<sanitized-basename>` fits the session name rules without
|
||||
// truncating most project names.
|
||||
const session = opts.noSession ? undefined : `code-${sanitizeName(basename(rootDir))}`;
|
||||
|
||||
// Native filesystem tools. No subprocess, ~50-200 ms faster per call
|
||||
// than the MCP server was, and `edit_file` takes a flat SEARCH/REPLACE
|
||||
// shape instead of the `string="false"` JSON-in-string array that
|
||||
// triggered R1's DSML hallucinations all through 0.4.x.
|
||||
const tools = new ToolRegistry();
|
||||
registerFilesystemTools(tools, { rootDir });
|
||||
// Background-process registry shared between the shell tools and the
|
||||
// TUI's /jobs + /kill slashes + exit cleanup. One per `reasonix code`
|
||||
// run — orphan prevention on SIGINT / process exit kills everything
|
||||
// it owns, so dev servers don't outlive the Reasonix process.
|
||||
const jobs = new JobRegistry();
|
||||
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),
|
||||
jobs,
|
||||
});
|
||||
// `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);
|
||||
// `ask_choice` — branching primitive. Independent of plan mode: the
|
||||
// model uses it to put a 2–4 way choice in front of the user
|
||||
// (strategy, style, library pick) without trying to squeeze the
|
||||
// menu into a submit_plan body. Keeping it always-registered
|
||||
// preserves the prefix cache across plan-mode toggles.
|
||||
registerChoiceTool(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` is intentionally NOT registered here — App.tsx wires it
|
||||
// up with the subagent runner attached, so `runAs: subagent` skills
|
||||
// can spawn isolated child loops. Doing it here would mean the App's
|
||||
// re-registration would shadow the no-runner version, which works
|
||||
// (last write wins) but obscures the wiring.
|
||||
|
||||
process.stderr.write(
|
||||
`▸ reasonix code: rooted at ${rootDir}, session "${session ?? "(ephemeral)"}" · ${tools.size} native tool(s)\n`,
|
||||
);
|
||||
|
||||
// Belt-and-suspenders cleanup: even though spawn(detached:false)
|
||||
// should tie child processes to the parent's lifetime, Windows cmd.exe
|
||||
// wrappers occasionally leak. Kill everything on both clean and
|
||||
// signal-driven exits. 'exit' fires too late for async I/O but is our
|
||||
// only guaranteed last word; the signal handlers do the heavy lifting.
|
||||
const sigShutdown = () => {
|
||||
void jobs.shutdown();
|
||||
};
|
||||
process.once("SIGINT", sigShutdown);
|
||||
process.once("SIGTERM", sigShutdown);
|
||||
process.once("exit", sigShutdown);
|
||||
|
||||
await chatCommand({
|
||||
model: opts.model ?? "deepseek-v4-flash",
|
||||
harvest: opts.harvest ?? false,
|
||||
system: codeSystemPrompt(rootDir),
|
||||
transcript: opts.transcript,
|
||||
session,
|
||||
seedTools: tools,
|
||||
codeMode: { rootDir, jobs },
|
||||
forceResume: opts.forceResume,
|
||||
forceNew: opts.forceNew,
|
||||
});
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
/**
|
||||
* `reasonix mcp inspect <spec>` — connect to one MCP server, list
|
||||
* everything it exposes (tools, resources, prompts), print a
|
||||
* human-readable summary. Useful as:
|
||||
* - a diagnostic tool for "does my MCP server even work?"
|
||||
* - a discovery tool for "what can this server do?"
|
||||
* - the only CLI surface for the resources+prompts methods added
|
||||
* in 0.4.5 (chat mode consumes tools but hasn't wired up the
|
||||
* other two families yet).
|
||||
*/
|
||||
|
||||
import { McpClient } from "../../mcp/client.js";
|
||||
import { inspectMcpServer } from "../../mcp/inspect.js";
|
||||
import type { InspectionReport } from "../../mcp/inspect.js";
|
||||
import { parseMcpSpec } from "../../mcp/spec.js";
|
||||
import { SseTransport } from "../../mcp/sse.js";
|
||||
import { type McpTransport, StdioTransport } from "../../mcp/stdio.js";
|
||||
|
||||
export interface McpInspectOptions {
|
||||
/** The raw --mcp spec string (e.g. `fs=npx -y @modelcontextprotocol/server-filesystem .`). */
|
||||
spec: string;
|
||||
/** Emit JSON on stdout instead of the human-readable table. */
|
||||
json?: boolean;
|
||||
}
|
||||
|
||||
export async function mcpInspectCommand(opts: McpInspectOptions): Promise<void> {
|
||||
const spec = parseMcpSpec(opts.spec);
|
||||
const transport: McpTransport =
|
||||
spec.transport === "sse"
|
||||
? new SseTransport({ url: spec.url })
|
||||
: new StdioTransport({ command: spec.command, args: spec.args });
|
||||
const client = new McpClient({ transport });
|
||||
try {
|
||||
await client.initialize();
|
||||
const report = await inspectMcpServer(client);
|
||||
if (opts.json) {
|
||||
console.log(JSON.stringify(report, null, 2));
|
||||
} else {
|
||||
console.log(formatReport(spec.name ?? "(anon)", report));
|
||||
}
|
||||
} finally {
|
||||
await client.close();
|
||||
}
|
||||
}
|
||||
|
||||
function formatReport(nsName: string, r: InspectionReport): string {
|
||||
const lines: string[] = [];
|
||||
lines.push(`MCP server [${nsName}]`);
|
||||
lines.push(
|
||||
` server ${r.serverInfo.name || "(unknown)"}${r.serverInfo.version ? ` v${r.serverInfo.version}` : ""}`,
|
||||
);
|
||||
lines.push(` protocol ${r.protocolVersion}`);
|
||||
const capKeys = Object.keys(r.capabilities);
|
||||
lines.push(` caps ${capKeys.length > 0 ? capKeys.join(", ") : "(none advertised)"}`);
|
||||
if (r.instructions) {
|
||||
lines.push(` notes ${r.instructions.trim().slice(0, 200)}`);
|
||||
}
|
||||
lines.push("");
|
||||
lines.push(formatSection("Tools", r.tools, toolLine));
|
||||
lines.push(formatSection("Resources", r.resources, resourceLine));
|
||||
lines.push(formatSection("Prompts", r.prompts, promptLine));
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
function formatSection<T>(
|
||||
title: string,
|
||||
section: { supported: true; items: T[] } | { supported: false; reason: string },
|
||||
render: (item: T) => string,
|
||||
): string {
|
||||
if (!section.supported) {
|
||||
return `${title}: (not supported — ${section.reason})`;
|
||||
}
|
||||
if (section.items.length === 0) {
|
||||
return `${title}: (none)`;
|
||||
}
|
||||
const lines = [`${title} (${section.items.length}):`];
|
||||
for (const item of section.items) lines.push(` ${render(item)}`);
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
function toolLine(t: { name: string; description?: string }): string {
|
||||
const desc = t.description ? ` — ${oneLine(t.description, 80)}` : "";
|
||||
return `· ${t.name}${desc}`;
|
||||
}
|
||||
|
||||
function resourceLine(r: { uri: string; name: string; mimeType?: string }): string {
|
||||
const mime = r.mimeType ? ` [${r.mimeType}]` : "";
|
||||
return `· ${r.name}${mime} ${r.uri}`;
|
||||
}
|
||||
|
||||
function promptLine(p: {
|
||||
name: string;
|
||||
description?: string;
|
||||
arguments?: Array<{ name: string; required?: boolean }>;
|
||||
}): string {
|
||||
const argPart =
|
||||
p.arguments && p.arguments.length > 0
|
||||
? ` (${p.arguments.map((a) => (a.required ? a.name : `${a.name}?`)).join(", ")})`
|
||||
: "";
|
||||
const desc = p.description ? ` — ${oneLine(p.description, 80)}` : "";
|
||||
return `· ${p.name}${argPart}${desc}`;
|
||||
}
|
||||
|
||||
function oneLine(s: string, max: number): string {
|
||||
const flat = s.replace(/\s+/g, " ").trim();
|
||||
return flat.length <= max ? flat : `${flat.slice(0, max - 1)}…`;
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
/**
|
||||
* `reasonix mcp <subcmd>` — the MCP discovery / helper surface.
|
||||
*
|
||||
* Currently one subcommand: `list`. Prints a curated catalog of popular
|
||||
* MCP servers with their `--mcp` commands ready to copy-paste. More
|
||||
* subcommands (`init`, `try`, etc.) may land in later alphas.
|
||||
*/
|
||||
|
||||
import { MCP_CATALOG, mcpCommandFor } from "../../mcp/catalog.js";
|
||||
|
||||
export interface McpListOptions {
|
||||
/** Emit JSON on stdout instead of the human-readable table. */
|
||||
json?: boolean;
|
||||
}
|
||||
|
||||
export function mcpListCommand(opts: McpListOptions): void {
|
||||
if (opts.json) {
|
||||
console.log(JSON.stringify(MCP_CATALOG, null, 2));
|
||||
return;
|
||||
}
|
||||
|
||||
console.log("Popular MCP servers you can bridge into Reasonix:");
|
||||
console.log("");
|
||||
for (const entry of MCP_CATALOG) {
|
||||
console.log(` ${pad(entry.name, 12)} ${entry.summary}`);
|
||||
console.log(` ${mcpCommandFor(entry)}`);
|
||||
if (entry.note) console.log(` · ${entry.note}`);
|
||||
console.log("");
|
||||
}
|
||||
console.log("Usage: reasonix chat <one-of-the---mcp-lines-above>");
|
||||
console.log(
|
||||
"Docs: https://github.com/modelcontextprotocol/servers — Anthropic's official server repo",
|
||||
);
|
||||
console.log(
|
||||
" https://mcp.so — community-maintained catalog",
|
||||
);
|
||||
}
|
||||
|
||||
function pad(s: string, width: number): string {
|
||||
return s.length >= width ? s : s + " ".repeat(width - s.length);
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
@@ -74,6 +75,11 @@ function printReplay(opts: ReplayOptions): void {
|
||||
} else if (stats.prefixHashes.length > 1) {
|
||||
console.log(" (prefix churned — cache-hostile session)");
|
||||
}
|
||||
if (stats.harvestedTurns > 0) {
|
||||
console.log(`harvest (Pillar 2): ${stats.harvestedTurns} turn(s) produced plan state`);
|
||||
console.log(` subgoals: ${stats.totalSubgoals}`);
|
||||
console.log(` uncertainties: ${stats.totalUncertainties}`);
|
||||
}
|
||||
}
|
||||
|
||||
function sliceRecords(records: TranscriptRecord[], opts: ReplayOptions): TranscriptRecord[] {
|
||||
@@ -100,6 +106,21 @@ function renderRecord(rec: TranscriptRecord): void {
|
||||
})()
|
||||
: "";
|
||||
console.log(`${turn} AGENT:${cost}${cache} ${oneLine(rec.content)}`);
|
||||
if (rec.planState) {
|
||||
const ps = rec.planState;
|
||||
if (ps.subgoals.length)
|
||||
console.log(` ‹ subgoals (${ps.subgoals.length}): ${ps.subgoals.join(" · ")}`);
|
||||
if (ps.hypotheses.length)
|
||||
console.log(` ‹ hypotheses (${ps.hypotheses.length}): ${ps.hypotheses.join(" · ")}`);
|
||||
if (ps.uncertainties.length)
|
||||
console.log(
|
||||
` ‹ uncertainties(${ps.uncertainties.length}): ${ps.uncertainties.join(" · ")}`,
|
||||
);
|
||||
if (ps.rejectedPaths.length)
|
||||
console.log(
|
||||
` ‹ rejected (${ps.rejectedPaths.length}): ${ps.rejectedPaths.join(" · ")}`,
|
||||
);
|
||||
}
|
||||
} else if (rec.role === "tool") {
|
||||
const args = rec.args ? ` args=${oneLine(rec.args, 80)}` : "";
|
||||
console.log(`${turn} TOOL ${rec.tool ?? "?"}:${args} → ${oneLine(rec.content, 120)}`);
|
||||
|
||||
+122
-9
@@ -1,13 +1,32 @@
|
||||
import type { WriteStream } from "node:fs";
|
||||
import { stdin, stdout } from "node:process";
|
||||
import { createInterface } from "node:readline/promises";
|
||||
import { defaultConfigPath, isPlausibleKey, loadApiKey, saveApiKey } from "../../config.js";
|
||||
import { loadDotenv } from "../../env.js";
|
||||
import { CacheFirstLoop, DeepSeekClient, ImmutablePrefix } from "../../index.js";
|
||||
import { McpClient } from "../../mcp/client.js";
|
||||
import { bridgeMcpTools } from "../../mcp/registry.js";
|
||||
import { parseMcpSpec } from "../../mcp/spec.js";
|
||||
import { SseTransport } from "../../mcp/sse.js";
|
||||
import { type McpTransport, StdioTransport } from "../../mcp/stdio.js";
|
||||
import { ToolRegistry } from "../../tools.js";
|
||||
import { openTranscriptFile, recordFromLoopEvent, writeRecord } from "../../transcript.js";
|
||||
import { appendUsage } from "../../usage.js";
|
||||
|
||||
export interface RunOptions {
|
||||
task: string;
|
||||
model: string;
|
||||
system: string;
|
||||
/** Opt into Pillar 2 plan-state harvesting. Adds a cheap V3 call per turn. */
|
||||
harvest?: boolean;
|
||||
/** Self-consistency budget. > 1 runs N parallel samples and picks the best. */
|
||||
branch?: number;
|
||||
/** JSONL transcript path — lets `reasonix replay` / `diff` audit this run. */
|
||||
transcript?: string;
|
||||
/** Zero or more MCP server specs. Each: `"name=cmd args..."` or `"cmd args..."`. */
|
||||
mcp?: string[];
|
||||
/** Global prefix — only honored when a single anonymous server is given. */
|
||||
mcpPrefix?: string;
|
||||
}
|
||||
|
||||
async function ensureApiKey(): Promise<string> {
|
||||
@@ -48,19 +67,113 @@ export async function runCommand(opts: RunOptions): Promise<void> {
|
||||
const apiKey = await ensureApiKey();
|
||||
process.env.DEEPSEEK_API_KEY = apiKey;
|
||||
|
||||
const client = new DeepSeekClient();
|
||||
const prefix = new ImmutablePrefix({ system: opts.system });
|
||||
const loop = new CacheFirstLoop({ client, prefix, model: opts.model });
|
||||
|
||||
for await (const ev of loop.step(opts.task)) {
|
||||
if (ev.role === "assistant_delta" && ev.content) process.stdout.write(ev.content);
|
||||
if (ev.role === "tool") process.stdout.write(`\n[tool ${ev.toolName}] ${ev.content}\n`);
|
||||
if (ev.role === "error") process.stderr.write(`\n[error] ${ev.error}\n`);
|
||||
if (ev.role === "done") process.stdout.write("\n");
|
||||
// Optional MCP setup — mirrors chat's flow. Must happen before loop
|
||||
// construction so the tools make it into the prefix.
|
||||
const requestedSpecs = opts.mcp ?? [];
|
||||
const clients: McpClient[] = [];
|
||||
let tools: ToolRegistry | undefined;
|
||||
let successCount = 0;
|
||||
if (requestedSpecs.length > 0) {
|
||||
tools = new ToolRegistry();
|
||||
for (const raw of requestedSpecs) {
|
||||
try {
|
||||
const spec = parseMcpSpec(raw);
|
||||
const prefix = spec.name
|
||||
? `${spec.name}_`
|
||||
: requestedSpecs.length === 1 && opts.mcpPrefix
|
||||
? opts.mcpPrefix
|
||||
: "";
|
||||
const transport: McpTransport =
|
||||
spec.transport === "sse"
|
||||
? new SseTransport({ url: spec.url })
|
||||
: new StdioTransport({ command: spec.command, args: spec.args });
|
||||
const mcp = new McpClient({ transport });
|
||||
await mcp.initialize();
|
||||
const bridge = await bridgeMcpTools(mcp, { registry: tools, namePrefix: prefix });
|
||||
const source =
|
||||
spec.transport === "sse" ? spec.url : `${spec.command} ${spec.args.join(" ")}`;
|
||||
process.stderr.write(
|
||||
`▸ MCP[${spec.name ?? "anon"}]: ${bridge.registeredNames.length} tool(s) from ${source}\n`,
|
||||
);
|
||||
clients.push(mcp);
|
||||
successCount++;
|
||||
} catch (err) {
|
||||
// Non-fatal — skip and continue, same as `reasonix chat`. A
|
||||
// one-shot `run` invocation with a broken MCP server otherwise
|
||||
// fails the whole run over a side-concern tool the task might
|
||||
// not even touch.
|
||||
process.stderr.write(
|
||||
`▸ MCP setup SKIPPED for "${raw}": ${(err as Error).message}\n → run \`reasonix setup\` to remove broken entries from your saved config.\n`,
|
||||
);
|
||||
}
|
||||
}
|
||||
if (successCount === 0) tools = undefined;
|
||||
}
|
||||
|
||||
const client = new DeepSeekClient();
|
||||
const prefix = new ImmutablePrefix({
|
||||
system: opts.system,
|
||||
toolSpecs: tools?.specs(),
|
||||
});
|
||||
const loop = new CacheFirstLoop({
|
||||
client,
|
||||
prefix,
|
||||
tools,
|
||||
model: opts.model,
|
||||
harvest: opts.harvest,
|
||||
branch: opts.branch,
|
||||
});
|
||||
const prefixHash = prefix.fingerprint;
|
||||
|
||||
let transcriptStream: WriteStream | null = null;
|
||||
if (opts.transcript) {
|
||||
transcriptStream = openTranscriptFile(opts.transcript, {
|
||||
version: 1,
|
||||
source: "reasonix run",
|
||||
model: opts.model,
|
||||
startedAt: new Date().toISOString(),
|
||||
});
|
||||
// Also persist the user turn itself (the loop's event stream starts with
|
||||
// assistant output, not the prompt we're about to send).
|
||||
writeRecord(transcriptStream, {
|
||||
ts: new Date().toISOString(),
|
||||
turn: 1,
|
||||
role: "user",
|
||||
content: opts.task,
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
for await (const ev of loop.step(opts.task)) {
|
||||
if (ev.role === "assistant_delta" && ev.content) process.stdout.write(ev.content);
|
||||
if (ev.role === "tool") process.stdout.write(`\n[tool ${ev.toolName}] ${ev.content}\n`);
|
||||
if (ev.role === "error") process.stderr.write(`\n[error] ${ev.error}\n`);
|
||||
if (ev.role === "done") process.stdout.write("\n");
|
||||
if (ev.role === "assistant_final" && ev.stats?.usage) {
|
||||
// `reasonix run` is often used in CI / scripting — we want
|
||||
// those turns to show up in `reasonix stats` too so the
|
||||
// dashboard reflects all DeepSeek spend, not just TUI sessions.
|
||||
appendUsage({ session: null, model: ev.stats.model, usage: ev.stats.usage });
|
||||
}
|
||||
// Persist every non-streaming event — deltas would flood the file and
|
||||
// aren't useful for replay (replay renders final content, not keystrokes).
|
||||
if (transcriptStream && ev.role !== "assistant_delta") {
|
||||
writeRecord(transcriptStream, recordFromLoopEvent(ev, { model: opts.model, prefixHash }));
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
transcriptStream?.end();
|
||||
}
|
||||
|
||||
const s = loop.stats.summary();
|
||||
process.stdout.write(
|
||||
`\n— turns:${s.turns} cache:${(s.cacheHitRatio * 100).toFixed(1)}% ` +
|
||||
`cost:$${s.totalCostUsd.toFixed(6)} save-vs-claude:${s.savingsVsClaudePct.toFixed(1)}%\n`,
|
||||
);
|
||||
if (opts.transcript) {
|
||||
process.stdout.write(`\ntranscript: ${opts.transcript}\n`);
|
||||
process.stdout.write(` → npx reasonix replay ${opts.transcript}\n`);
|
||||
}
|
||||
|
||||
for (const c of clients) await c.close();
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
/**
|
||||
* `reasonix sessions` — CLI equivalent of the `/sessions` slash command.
|
||||
*
|
||||
* Two modes:
|
||||
* - `reasonix sessions` list every session under ~/.reasonix/sessions/
|
||||
* - `reasonix sessions <name>` dump one session's messages in readable form
|
||||
*
|
||||
* Neither needs an API key — pure filesystem reads of JSONL files written
|
||||
* by previous chat runs.
|
||||
*/
|
||||
|
||||
import { listSessions, loadSessionMessages, sessionPath } from "../../index.js";
|
||||
import type { ChatMessage } from "../../index.js";
|
||||
|
||||
export interface SessionsOptions {
|
||||
/** When present, inspect that session instead of listing. */
|
||||
name?: string;
|
||||
/** Include assistant tool-call metadata in the inspect output. */
|
||||
verbose?: boolean;
|
||||
}
|
||||
|
||||
export function sessionsCommand(opts: SessionsOptions): void {
|
||||
if (opts.name) {
|
||||
inspectSession(opts.name, !!opts.verbose);
|
||||
} else {
|
||||
listAll();
|
||||
}
|
||||
}
|
||||
|
||||
function listAll(): void {
|
||||
const items = listSessions();
|
||||
if (items.length === 0) {
|
||||
console.log(
|
||||
"no saved sessions yet — run `reasonix chat` (sessions are auto-saved unless --no-session).",
|
||||
);
|
||||
return;
|
||||
}
|
||||
console.log("Saved sessions (~/.reasonix/sessions/):");
|
||||
console.log("");
|
||||
console.log(` ${"name".padEnd(22)} ${"msgs".padStart(6)} ${"size".padStart(8)} modified`);
|
||||
console.log(` ${"─".repeat(60)}`);
|
||||
for (const s of items) {
|
||||
const sizeKb = `${(s.size / 1024).toFixed(1)} KB`;
|
||||
const when = s.mtime.toISOString().replace("T", " ").slice(0, 16);
|
||||
console.log(
|
||||
` ${s.name.padEnd(22)} ${String(s.messageCount).padStart(6)} ${sizeKb.padStart(8)} ${when}`,
|
||||
);
|
||||
}
|
||||
console.log("");
|
||||
console.log("Inspect: reasonix sessions <name>");
|
||||
console.log("Resume: reasonix chat --session <name>");
|
||||
}
|
||||
|
||||
function inspectSession(name: string, verbose: boolean): void {
|
||||
const path = sessionPath(name);
|
||||
const messages = loadSessionMessages(name);
|
||||
if (messages.length === 0) {
|
||||
console.error(`no session named "${name}" (or it's empty).`);
|
||||
console.error(`looked at: ${path}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
console.log(`[session] ${name} ${messages.length} messages ${path}`);
|
||||
console.log("");
|
||||
|
||||
let turnIndex = 0;
|
||||
for (const msg of messages) {
|
||||
renderMessage(msg, turnIndex, verbose);
|
||||
// Roughly bump "turn" after each user message so the reader can follow
|
||||
// the conversation shape without the transcript's richer turn numbering.
|
||||
if (msg.role === "user") turnIndex++;
|
||||
}
|
||||
}
|
||||
|
||||
function renderMessage(msg: ChatMessage, turnIdx: number, verbose: boolean): void {
|
||||
const turn = turnIdx > 0 ? `[t${turnIdx}]` : "[start]";
|
||||
const content = typeof msg.content === "string" ? msg.content : "";
|
||||
const flat = oneLine(content);
|
||||
|
||||
if (msg.role === "user") {
|
||||
console.log(`${turn} USER: ${flat}`);
|
||||
} else if (msg.role === "assistant") {
|
||||
console.log(`${turn} AGENT: ${flat || "(tool call only)"}`);
|
||||
if (verbose && msg.tool_calls?.length) {
|
||||
for (const tc of msg.tool_calls) {
|
||||
console.log(
|
||||
` → call ${tc.function?.name} ${truncate(tc.function?.arguments ?? "", 80)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
} else if (msg.role === "tool") {
|
||||
console.log(`${turn} TOOL ${msg.name ?? "?"}: ${truncate(flat, 160)}`);
|
||||
} else if (msg.role === "system") {
|
||||
if (verbose) console.log(`${turn} SYSTEM: ${truncate(flat, 160)}`);
|
||||
// otherwise suppress — session's system prompt is usually session-wide
|
||||
// boilerplate.
|
||||
}
|
||||
}
|
||||
|
||||
function oneLine(s: string, max = 200): string {
|
||||
const collapsed = s.replace(/\s+/g, " ").trim();
|
||||
return collapsed.length > max ? `${collapsed.slice(0, max)}…` : collapsed;
|
||||
}
|
||||
|
||||
function truncate(s: string, max: number): string {
|
||||
return s.length <= max ? s : `${s.slice(0, max)}…`;
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
/**
|
||||
* `reasonix setup` — re-mount the first-run wizard on demand so users
|
||||
* can reconfigure (add/remove MCP servers, switch preset) without
|
||||
* editing JSON by hand.
|
||||
*
|
||||
* Invoked both explicitly (`reasonix setup`) and implicitly (the no-args
|
||||
* entry point when `setupCompleted` is false).
|
||||
*/
|
||||
|
||||
import { render } from "ink";
|
||||
import React from "react";
|
||||
import { loadApiKey, readConfig } from "../../config.js";
|
||||
import { loadDotenv } from "../../env.js";
|
||||
import { Wizard } from "../ui/Wizard.js";
|
||||
|
||||
export interface SetupOptions {
|
||||
/**
|
||||
* When true, bypass the API-key step even if no key is saved — useful
|
||||
* from test harnesses. Normal CLI use always pushes through the key
|
||||
* step when missing.
|
||||
*/
|
||||
skipKeyStep?: boolean;
|
||||
}
|
||||
|
||||
export async function setupCommand(_opts: SetupOptions = {}): Promise<void> {
|
||||
loadDotenv();
|
||||
const existingKey = loadApiKey();
|
||||
const existing = readConfig();
|
||||
|
||||
const { waitUntilExit, unmount } = render(
|
||||
<Wizard
|
||||
existingApiKey={existingKey}
|
||||
initial={{ preset: existing.preset, mcp: existing.mcp }}
|
||||
onComplete={() => {
|
||||
// Ink handles its own enter-to-exit inside the "saved" step; we
|
||||
// just wait for the app to exit naturally.
|
||||
}}
|
||||
onCancel={() => {
|
||||
unmount();
|
||||
}}
|
||||
/>,
|
||||
{ exitOnCtrlC: true, patchConsole: false },
|
||||
);
|
||||
await waitUntilExit();
|
||||
}
|
||||
+163
-5
@@ -1,15 +1,60 @@
|
||||
/**
|
||||
* `reasonix stats` — two modes, decided by whether the user passed
|
||||
* a transcript path.
|
||||
*
|
||||
* - `reasonix stats` → cross-session usage dashboard
|
||||
* (reads `~/.reasonix/usage.jsonl`)
|
||||
* - `reasonix stats <path>` → summary of a single JSONL transcript
|
||||
* (original v0.1 behavior, kept so
|
||||
* existing scripts don't break)
|
||||
*
|
||||
* The dashboard is the new story: for every turn `reasonix chat|code|run`
|
||||
* has ever executed on this machine, we aggregate tokens + cost + the
|
||||
* equivalent Claude spend, and print rolling-window totals (today /
|
||||
* week / month / all-time). The savings column is the Pillar 1 pitch
|
||||
* made concrete — "you paid $X; Claude would have charged $Y, a N%
|
||||
* reduction."
|
||||
*/
|
||||
|
||||
import { existsSync, readFileSync } from "node:fs";
|
||||
import {
|
||||
type UsageAggregate,
|
||||
type UsageBucket,
|
||||
aggregateUsage,
|
||||
bucketCacheHitRatio,
|
||||
bucketSavingsFraction,
|
||||
defaultUsageLogPath,
|
||||
formatLogSize,
|
||||
readUsageLog,
|
||||
} from "../../usage.js";
|
||||
|
||||
export interface StatsOptions {
|
||||
transcript: string;
|
||||
/** Optional transcript path. Absent → dashboard mode. */
|
||||
transcript?: string;
|
||||
/** Override usage log location (tests). */
|
||||
logPath?: string;
|
||||
/** Inject a fixed timestamp (tests) so rolling windows are deterministic. */
|
||||
now?: number;
|
||||
}
|
||||
|
||||
export function statsCommand(opts: StatsOptions): void {
|
||||
if (!existsSync(opts.transcript)) {
|
||||
console.error(`no such transcript: ${opts.transcript}`);
|
||||
if (opts.transcript) {
|
||||
transcriptSummary(opts.transcript);
|
||||
return;
|
||||
}
|
||||
dashboard(opts);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// Transcript summary — legacy v0.1 behavior, preserved verbatim.
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
function transcriptSummary(path: string): void {
|
||||
if (!existsSync(path)) {
|
||||
console.error(`no such transcript: ${path}`);
|
||||
process.exit(1);
|
||||
}
|
||||
const lines = readFileSync(opts.transcript, "utf8").split(/\r?\n/).filter(Boolean);
|
||||
const lines = readFileSync(path, "utf8").split(/\r?\n/).filter(Boolean);
|
||||
let assistantTurns = 0;
|
||||
let toolCalls = 0;
|
||||
let lastTurn = 0;
|
||||
@@ -23,8 +68,121 @@ export function statsCommand(opts: StatsOptions): void {
|
||||
/* skip */
|
||||
}
|
||||
}
|
||||
console.log(`transcript: ${opts.transcript}`);
|
||||
console.log(`transcript: ${path}`);
|
||||
console.log(`assistant turns: ${assistantTurns}`);
|
||||
console.log(`tool invocations: ${toolCalls}`);
|
||||
console.log(`last turn index: ${lastTurn}`);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// Dashboard — aggregates ~/.reasonix/usage.jsonl.
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
function dashboard(opts: StatsOptions): void {
|
||||
const path = opts.logPath ?? defaultUsageLogPath();
|
||||
const records = readUsageLog(path);
|
||||
if (records.length === 0) {
|
||||
console.log("no usage data yet.");
|
||||
console.log("");
|
||||
console.log(` ${path}`);
|
||||
console.log("");
|
||||
console.log("run `reasonix chat`, `reasonix code`, or `reasonix run <task>` — every turn");
|
||||
console.log("appends one line to the log and `reasonix stats` will roll it up.");
|
||||
return;
|
||||
}
|
||||
|
||||
const agg = aggregateUsage(records, { now: opts.now });
|
||||
console.log(renderDashboard(agg, path));
|
||||
}
|
||||
|
||||
/** Pure renderer — pulled out so tests can assert on the string directly. */
|
||||
export function renderDashboard(agg: UsageAggregate, logPath: string): string {
|
||||
const lines: string[] = [];
|
||||
const size = formatLogSize(logPath);
|
||||
lines.push(`Reasonix usage — ${logPath}${size ? ` (${size})` : ""}`);
|
||||
lines.push("");
|
||||
lines.push(header());
|
||||
lines.push(divider());
|
||||
for (const b of agg.buckets) {
|
||||
lines.push(bucketRow(b));
|
||||
}
|
||||
lines.push("");
|
||||
|
||||
// Model + session breakdown — both trim to top 3 so a user with 20
|
||||
// sessions doesn't drown the table.
|
||||
if (agg.byModel.length > 0) {
|
||||
const totalTurns = agg.buckets[agg.buckets.length - 1]?.turns ?? 0;
|
||||
const top = agg.byModel[0];
|
||||
if (top && totalTurns > 0) {
|
||||
const pct = ((top.turns / totalTurns) * 100).toFixed(0);
|
||||
lines.push(`most used model: ${top.model} (${pct}% of turns)`);
|
||||
}
|
||||
}
|
||||
if (agg.bySession.length > 0) {
|
||||
const top = agg.bySession[0];
|
||||
if (top) lines.push(`top session: ${top.session} (${top.turns} turns)`);
|
||||
}
|
||||
if (agg.firstSeen) {
|
||||
lines.push(`tracked since: ${new Date(agg.firstSeen).toISOString().slice(0, 10)}`);
|
||||
}
|
||||
if (agg.subagents) {
|
||||
lines.push("");
|
||||
lines.push(renderSubagentSection(agg.subagents));
|
||||
}
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
function renderSubagentSection(sub: NonNullable<UsageAggregate["subagents"]>): string {
|
||||
const lines: string[] = [];
|
||||
const seconds = (sub.totalDurationMs / 1000).toFixed(1);
|
||||
lines.push(
|
||||
`subagent activity: ${sub.total} run(s) · $${sub.costUsd.toFixed(6)} · ${seconds}s total`,
|
||||
);
|
||||
// Show at most 5 skills so the section never dwarfs the main table.
|
||||
const top = sub.bySkill.slice(0, 5);
|
||||
for (const s of top) {
|
||||
const sec = (s.durationMs / 1000).toFixed(1);
|
||||
lines.push(
|
||||
` ${pad(s.skillName, 18)} ${pad(`${s.count}`, 4, "right")} $${s.costUsd.toFixed(6)} ${sec}s`,
|
||||
);
|
||||
}
|
||||
if (sub.bySkill.length > top.length) {
|
||||
lines.push(` (+${sub.bySkill.length - top.length} more)`);
|
||||
}
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
function header(): string {
|
||||
// Fixed column widths so alignment works in any TTY.
|
||||
return [
|
||||
pad("", 10),
|
||||
pad("turns", 8, "right"),
|
||||
pad("cache hit", 10, "right"),
|
||||
pad("cost (USD)", 14, "right"),
|
||||
pad("vs Claude", 14, "right"),
|
||||
pad("saved", 10, "right"),
|
||||
].join(" ");
|
||||
}
|
||||
|
||||
function divider(): string {
|
||||
return "-".repeat(70);
|
||||
}
|
||||
|
||||
function bucketRow(b: UsageBucket): string {
|
||||
const hit = bucketCacheHitRatio(b);
|
||||
const savings = bucketSavingsFraction(b);
|
||||
return [
|
||||
pad(b.label, 10),
|
||||
pad(b.turns.toString(), 8, "right"),
|
||||
pad(b.turns > 0 ? `${(hit * 100).toFixed(1)}%` : "—", 10, "right"),
|
||||
pad(b.turns > 0 ? `$${b.costUsd.toFixed(6)}` : "—", 14, "right"),
|
||||
pad(b.turns > 0 ? `$${b.claudeEquivUsd.toFixed(4)}` : "—", 14, "right"),
|
||||
pad(b.turns > 0 && savings > 0 ? `${(savings * 100).toFixed(1)}%` : "—", 10, "right"),
|
||||
].join(" ");
|
||||
}
|
||||
|
||||
function pad(s: string, width: number, align: "left" | "right" = "left"): string {
|
||||
if (s.length >= width) return s;
|
||||
const fill = " ".repeat(width - s.length);
|
||||
return align === "right" ? `${fill}${s}` : `${s}${fill}`;
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
+217
-33
@@ -1,14 +1,43 @@
|
||||
import { Command } from "commander";
|
||||
import { readConfig } from "../config.js";
|
||||
import { VERSION } from "../index.js";
|
||||
import { ESCALATION_CONTRACT } from "../prompt-fragments.js";
|
||||
import { applyMemoryStack } from "../user-memory.js";
|
||||
import { chatCommand } from "./commands/chat.js";
|
||||
import { codeCommand } from "./commands/code.js";
|
||||
import { diffCommand } from "./commands/diff.js";
|
||||
import { mcpInspectCommand } from "./commands/mcp-inspect.js";
|
||||
import { mcpListCommand } from "./commands/mcp.js";
|
||||
import { replayCommand } from "./commands/replay.js";
|
||||
import { runCommand } from "./commands/run.js";
|
||||
import { sessionsCommand } from "./commands/sessions.js";
|
||||
import { setupCommand } from "./commands/setup.js";
|
||||
import { statsCommand } from "./commands/stats.js";
|
||||
import { updateCommand } from "./commands/update.js";
|
||||
import { versionCommand } from "./commands/version.js";
|
||||
import { resolveDefaults } from "./resolve.js";
|
||||
|
||||
const DEFAULT_SYSTEM =
|
||||
"You are Reasonix, a helpful DeepSeek-powered assistant. Be concise and accurate. Use tools when available.";
|
||||
const DEFAULT_SYSTEM = `You are Reasonix, a helpful DeepSeek-powered assistant. Be concise and accurate. Use tools when available.
|
||||
|
||||
# Cite or shut up — non-negotiable
|
||||
|
||||
Every factual claim about a codebase must be backed by evidence. Reasonix VALIDATES your citations — broken paths render in **red strikethrough with ❌** in front of the user.
|
||||
|
||||
**Positive claims** — append a markdown link:
|
||||
- ✅ \`The MCP client supports listResources [listResources](src/mcp/client.ts:142).\`
|
||||
- ❌ \`The MCP client supports listResources.\` ← unverifiable, do not write.
|
||||
|
||||
**Negative claims** ("X is missing", "Y isn't implemented", "lacks Z") are the #1 hallucination shape. STOP before writing them. If you have a search tool, call it first; if the search returns nothing, cite the search itself as evidence (\`No matches for "foo" in src/\`). If you have no tool, qualify hard: "I haven't verified — this is a guess."
|
||||
|
||||
Asserting absence without checking is how evaluative answers go wrong. Treat the urge to write "missing" as a red flag in your own reasoning.
|
||||
|
||||
# Don't invent what changes — search instead
|
||||
|
||||
Your training data has a cutoff. When an answer's correctness depends on something that changes over time (the user is asking what's happening, not what's true) and a search tool is available, search first. Inventing currently-correct values from training memory is the most common way these answers go wrong, and the user usually can't tell until much later.
|
||||
|
||||
The signal isn't a topic list — it's: "if I'm wrong about this, is it because reality moved on?". If yes, ground the answer in fresh evidence; if no (definitions, mechanisms, well-established APIs), answer from memory.
|
||||
|
||||
${ESCALATION_CONTRACT}`;
|
||||
|
||||
const program = new Command();
|
||||
program
|
||||
@@ -16,64 +45,182 @@ program
|
||||
.description("DeepSeek-native agent framework — built for cache hits and cheap tokens.")
|
||||
.version(VERSION);
|
||||
|
||||
// `reasonix` with no subcommand → launch the friendliest flow.
|
||||
// First run (no config yet) → interactive setup wizard.
|
||||
// Otherwise → chat with saved defaults. This is the "one command to
|
||||
// rule them all" entry for non-power-users: they don't need to learn
|
||||
// `chat` / `setup` / `--mcp` — just type `reasonix`.
|
||||
program.action(async () => {
|
||||
const cfg = readConfig();
|
||||
if (!cfg.setupCompleted) {
|
||||
await setupCommand({});
|
||||
return;
|
||||
}
|
||||
const defaults = resolveDefaults({});
|
||||
await chatCommand({
|
||||
model: defaults.model,
|
||||
system: applyMemoryStack(DEFAULT_SYSTEM, process.cwd()),
|
||||
harvest: defaults.harvest,
|
||||
branch: defaults.branch,
|
||||
session: defaults.session,
|
||||
mcp: defaults.mcp,
|
||||
});
|
||||
});
|
||||
|
||||
program
|
||||
.command("chat")
|
||||
.description("Interactive Ink TUI with live cache/cost panel.")
|
||||
.option("-m, --model <id>", "DeepSeek model id", "deepseek-chat")
|
||||
.option("-s, --system <prompt>", "System prompt (pinned in the immutable prefix)", DEFAULT_SYSTEM)
|
||||
.command("setup")
|
||||
.description("Interactive wizard — API key, preset, MCP servers. Re-run any time to reconfigure.")
|
||||
.action(async () => {
|
||||
await setupCommand({});
|
||||
});
|
||||
|
||||
program
|
||||
.command("code [dir]")
|
||||
.description(
|
||||
"Code-editing chat — filesystem tools rooted at <dir> (default: cwd), coding system prompt, v4-flash. Model proposes SEARCH/REPLACE blocks; Reasonix applies them to disk. Use /preset max or /pro to escalate to v4-pro on hard tasks.",
|
||||
)
|
||||
.option("-m, --model <id>", "Override default model (v4-flash)")
|
||||
.option("--no-session", "Disable session persistence for this run")
|
||||
.option("-r, --resume", "Skip the session picker — always continue prior messages")
|
||||
.option("-n, --new", "Skip the session picker — always wipe prior messages and start fresh")
|
||||
.option("--transcript <path>", "Write a JSONL transcript to this path")
|
||||
.option(
|
||||
"--harvest",
|
||||
"Extract typed plan state from R1 reasoning (Pillar 2, adds a cheap V3 call per turn)",
|
||||
"Opt-in Pillar-2 plan-state extraction. Adds one flash call per turn; off by default (no preset enables it).",
|
||||
)
|
||||
.action(async (dir: string | undefined, opts) => {
|
||||
await codeCommand({
|
||||
dir,
|
||||
model: opts.model,
|
||||
noSession: opts.session === false,
|
||||
transcript: opts.transcript,
|
||||
forceResume: !!opts.resume,
|
||||
forceNew: !!opts.new,
|
||||
harvest: !!opts.harvest,
|
||||
});
|
||||
});
|
||||
|
||||
program
|
||||
.command("chat")
|
||||
.description("Interactive Ink TUI with live cache/cost panel.")
|
||||
.option("-m, --model <id>", "DeepSeek model id (overrides preset)")
|
||||
.option("-s, --system <prompt>", "System prompt (pinned in the immutable prefix)", DEFAULT_SYSTEM)
|
||||
.option("--transcript <path>", "Write a JSONL transcript to this path")
|
||||
.option(
|
||||
"--preset <name>",
|
||||
"Model + effort bundle. One of: fast (flash·high), smart (flash·max, default), max (pro·max). Overrides config.preset.",
|
||||
)
|
||||
.option(
|
||||
"--harvest",
|
||||
"Opt-in Pillar-2 plan-state extraction. Off by default — no preset enables it.",
|
||||
)
|
||||
.option(
|
||||
"--branch <n>",
|
||||
"Self-consistency: run N parallel samples per turn and pick the most confident (disables streaming; enables harvest)",
|
||||
"Self-consistency: run N parallel samples per turn (N× cost). Manual only — never auto-enabled.",
|
||||
(v) => Number.parseInt(v, 10),
|
||||
)
|
||||
.option(
|
||||
"--session <name>",
|
||||
"Use a named session (default: 'default'). Resume the same session next time.",
|
||||
)
|
||||
.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.',
|
||||
(value: string, previous: string[] = []) => [...previous, value],
|
||||
[] as string[],
|
||||
)
|
||||
.option(
|
||||
"--mcp-prefix <str>",
|
||||
"Global prefix applied to every MCP tool (only honored when no per-spec name is set; avoids collisions with a single anonymous server)",
|
||||
)
|
||||
.option("--no-config", "Ignore `~/.reasonix/config.json` — useful for CI or reproducing issues")
|
||||
.action(async (opts) => {
|
||||
// Default behavior: every chat is auto-saved to a session named 'default'
|
||||
// and auto-resumed next launch. Pass --no-session to opt out, or
|
||||
// --session <name> to use a different session.
|
||||
let session: string | undefined;
|
||||
if (opts.session === false) {
|
||||
session = undefined; // --no-session
|
||||
} else if (typeof opts.session === "string" && opts.session.length > 0) {
|
||||
session = opts.session;
|
||||
} else {
|
||||
session = "default";
|
||||
}
|
||||
await chatCommand({
|
||||
const defaults = resolveDefaults({
|
||||
model: opts.model,
|
||||
system: opts.system,
|
||||
harvest: opts.harvest,
|
||||
branch: opts.branch,
|
||||
mcp: opts.mcp as string[],
|
||||
session: opts.session,
|
||||
preset: opts.preset,
|
||||
noConfig: opts.config === false,
|
||||
});
|
||||
await chatCommand({
|
||||
model: defaults.model,
|
||||
system: applyMemoryStack(opts.system, process.cwd()),
|
||||
transcript: opts.transcript,
|
||||
harvest: !!opts.harvest,
|
||||
branch: Number.isFinite(opts.branch) && opts.branch > 1 ? opts.branch : undefined,
|
||||
session,
|
||||
harvest: defaults.harvest,
|
||||
branch: defaults.branch,
|
||||
session: defaults.session,
|
||||
mcp: defaults.mcp,
|
||||
mcpPrefix: opts.mcpPrefix,
|
||||
forceResume: !!opts.resume,
|
||||
forceNew: !!opts.new,
|
||||
});
|
||||
});
|
||||
|
||||
program
|
||||
.command("run <task>")
|
||||
.description("Run a single task non-interactively, streaming output.")
|
||||
.option("-m, --model <id>", "DeepSeek model id", "deepseek-chat")
|
||||
.option("-m, --model <id>", "DeepSeek model id (overrides preset)")
|
||||
.option("-s, --system <prompt>", "System prompt", DEFAULT_SYSTEM)
|
||||
.option("--preset <name>", "Bundle of model + harvest + branch: fast | smart | max")
|
||||
.option("--harvest", "Extract typed plan state from R1 reasoning (Pillar 2)")
|
||||
.option(
|
||||
"--branch <n>",
|
||||
"Self-consistency: run N parallel samples per turn and pick the most confident",
|
||||
(v) => Number.parseInt(v, 10),
|
||||
)
|
||||
.option("--transcript <path>", "Write a JSONL transcript to this path for replay/diff")
|
||||
.option(
|
||||
"--mcp <spec>",
|
||||
'MCP server spec; repeatable. "name=cmd args...", "cmd args...", or a URL (http/https → SSE).',
|
||||
(value: string, previous: string[] = []) => [...previous, value],
|
||||
[] as string[],
|
||||
)
|
||||
.option(
|
||||
"--mcp-prefix <str>",
|
||||
"Global prefix (only honored when no per-spec name is set; for a single anonymous server)",
|
||||
)
|
||||
.option("--no-config", "Ignore `~/.reasonix/config.json` — useful for CI or reproducing issues")
|
||||
.action(async (task: string, opts) => {
|
||||
await runCommand({ task, model: opts.model, system: opts.system });
|
||||
const defaults = resolveDefaults({
|
||||
model: opts.model,
|
||||
harvest: opts.harvest,
|
||||
branch: opts.branch,
|
||||
mcp: opts.mcp as string[],
|
||||
preset: opts.preset,
|
||||
noConfig: opts.config === false,
|
||||
});
|
||||
await runCommand({
|
||||
task,
|
||||
model: defaults.model,
|
||||
system: applyMemoryStack(opts.system, process.cwd()),
|
||||
harvest: defaults.harvest,
|
||||
branch: defaults.branch,
|
||||
transcript: opts.transcript,
|
||||
mcp: defaults.mcp,
|
||||
mcpPrefix: opts.mcpPrefix,
|
||||
});
|
||||
});
|
||||
|
||||
program
|
||||
.command("stats <transcript>")
|
||||
.description("Summarize a JSONL transcript produced by `reasonix chat --transcript`.")
|
||||
.action((transcript: string) => {
|
||||
.command("stats [transcript]")
|
||||
.description(
|
||||
"Show usage dashboard (today / week / month / all-time · turns · cache hit · cost · savings vs Claude). " +
|
||||
"Pass a transcript path to fall back to the per-file summary (assistant turns + tool calls).",
|
||||
)
|
||||
.action((transcript: string | undefined) => {
|
||||
statsCommand({ transcript });
|
||||
});
|
||||
|
||||
program
|
||||
.command("sessions [name]")
|
||||
.description("List saved chat sessions, or inspect one by name.")
|
||||
.option("-v, --verbose", "Include system prompts + tool-call metadata when inspecting")
|
||||
.action((name: string | undefined, opts) => {
|
||||
sessionsCommand({ name, verbose: !!opts.verbose });
|
||||
});
|
||||
|
||||
program
|
||||
.command("replay <transcript>")
|
||||
.description(
|
||||
@@ -113,8 +260,45 @@ program
|
||||
});
|
||||
});
|
||||
|
||||
const mcp = program
|
||||
.command("mcp")
|
||||
.description("Model Context Protocol helpers — discover servers, test your setup.");
|
||||
|
||||
mcp
|
||||
.command("list")
|
||||
.description("Show a curated catalog of popular MCP servers with ready-to-use --mcp commands.")
|
||||
.option("--json", "Emit the catalog as JSON instead of the human-readable table")
|
||||
.action((opts) => {
|
||||
mcpListCommand({ json: !!opts.json });
|
||||
});
|
||||
|
||||
mcp
|
||||
.command("inspect <spec>")
|
||||
.description(
|
||||
'Connect to one MCP server and print its server info + tools/resources/prompts. <spec> takes the same forms as --mcp ("name=cmd args", "cmd args", or an SSE URL).',
|
||||
)
|
||||
.option("--json", "Emit the full inspection report as JSON instead of the human-readable summary")
|
||||
.action(async (spec: string, opts) => {
|
||||
try {
|
||||
await mcpInspectCommand({ spec, json: !!opts.json });
|
||||
} catch (err) {
|
||||
process.stderr.write(`mcp inspect failed: ${(err as Error).message}\n`);
|
||||
process.exit(1);
|
||||
}
|
||||
});
|
||||
|
||||
program.command("version").description("Print Reasonix version.").action(versionCommand);
|
||||
|
||||
program
|
||||
.command("update")
|
||||
.description(
|
||||
"Check the npm registry for a newer Reasonix and install it. Detects npx vs global install; for npx users, prints a cache-refresh hint instead of running `npm i -g`.",
|
||||
)
|
||||
.option("--dry-run", "Print the plan without executing the install")
|
||||
.action(async (opts: { dryRun?: boolean }) => {
|
||||
await updateCommand({ dryRun: !!opts.dryRun });
|
||||
});
|
||||
|
||||
program.parseAsync(process.argv).catch((err) => {
|
||||
console.error(err);
|
||||
process.exit(1);
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
/**
|
||||
* Merge config defaults with CLI flags into the concrete options that
|
||||
* `chatCommand` / `runCommand` need.
|
||||
*
|
||||
* Precedence (highest wins):
|
||||
* 1. Explicit per-setting CLI flag (`--model`, `--harvest`, `--branch`, `--mcp`)
|
||||
* 2. Explicit `--preset <name>` CLI flag
|
||||
* 3. `config.preset` from `~/.reasonix/config.json` (set by `reasonix setup`)
|
||||
* 4. Hardcoded "smart" preset defaults (flash + effort=max)
|
||||
*
|
||||
* Keeping this logic in one place — rather than duplicating across
|
||||
* `chat` and `run` — means the precedence rule only lives in one unit
|
||||
* test and the shape of the merge is identical for both commands.
|
||||
*/
|
||||
|
||||
import { type PresetName, type ReasonixConfig, readConfig } from "../config.js";
|
||||
import { PRESETS } from "./ui/presets.js";
|
||||
|
||||
export interface ResolvedDefaults {
|
||||
model: string;
|
||||
reasoningEffort: "high" | "max";
|
||||
harvest: boolean;
|
||||
branch: number | undefined;
|
||||
mcp: string[];
|
||||
session: string | undefined;
|
||||
}
|
||||
|
||||
export interface RawCliFlags {
|
||||
model?: string;
|
||||
harvest?: boolean;
|
||||
/** From `commander`; already parseInt'd. */
|
||||
branch?: number;
|
||||
mcp?: string[];
|
||||
/** Commander's `--no-session` surfaces as `false`; `--session X` as a string. */
|
||||
session?: string | false;
|
||||
/** `--preset <name>`. */
|
||||
preset?: string;
|
||||
/** When true, ignore config entirely (power-user escape hatch). */
|
||||
noConfig?: boolean;
|
||||
}
|
||||
|
||||
export function resolveDefaults(flags: RawCliFlags): ResolvedDefaults {
|
||||
const cfg: ReasonixConfig = flags.noConfig ? {} : readConfig();
|
||||
const preset = pickPreset(flags.preset, cfg.preset);
|
||||
const presetSettings = PRESETS[preset];
|
||||
|
||||
const model = flags.model ?? presetSettings.model;
|
||||
const reasoningEffort = presetSettings.reasoningEffort;
|
||||
const harvest = flags.harvest === true ? true : presetSettings.harvest;
|
||||
const branchFromFlag = normalizeBranch(flags.branch);
|
||||
const branch = branchFromFlag ?? (presetSettings.branch > 1 ? presetSettings.branch : undefined);
|
||||
|
||||
// `--mcp` accumulator is [] when absent. Treat empty from flags as
|
||||
// "user didn't pass" → fall through to config. Users who explicitly
|
||||
// want zero MCP servers can pass `--no-config` or edit the file.
|
||||
const mcp = flags.mcp && flags.mcp.length > 0 ? flags.mcp : (cfg.mcp ?? []);
|
||||
|
||||
const session = resolveSession(flags.session, cfg.session);
|
||||
|
||||
return { model, reasoningEffort, harvest, branch, mcp, session };
|
||||
}
|
||||
|
||||
function pickPreset(
|
||||
flagPreset: string | undefined,
|
||||
configPreset: PresetName | undefined,
|
||||
): PresetName {
|
||||
if (flagPreset && isPresetName(flagPreset)) return flagPreset;
|
||||
if (configPreset) return configPreset;
|
||||
return "smart";
|
||||
}
|
||||
|
||||
function isPresetName(s: string): s is PresetName {
|
||||
return s === "fast" || s === "smart" || s === "max";
|
||||
}
|
||||
|
||||
function normalizeBranch(raw: number | undefined): number | undefined {
|
||||
if (raw === undefined) return undefined;
|
||||
if (!Number.isFinite(raw) || raw <= 1) return undefined;
|
||||
return Math.min(raw, 8);
|
||||
}
|
||||
|
||||
function resolveSession(
|
||||
flag: string | false | undefined,
|
||||
configSession: string | null | undefined,
|
||||
): string | undefined {
|
||||
if (flag === false) return undefined; // --no-session
|
||||
if (typeof flag === "string" && flag.length > 0) return flag;
|
||||
if (configSession === null) return undefined; // config opted out
|
||||
if (typeof configSession === "string" && configSession.length > 0) return configSession;
|
||||
return "default";
|
||||
}
|
||||
+2508
-70
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,86 @@
|
||||
import { Box, Text } from "ink";
|
||||
// biome-ignore lint/style/useImportType: tsconfig.jsx = "react" needs React in value scope for JSX compilation
|
||||
import React from "react";
|
||||
|
||||
export interface AtMentionSuggestionsProps {
|
||||
/**
|
||||
* Current matching file paths, ranked by the picker. `null` means
|
||||
* "not in @-prefix mode" — render nothing. Empty array means "in @
|
||||
* mode but no files match that partial" — render a hint.
|
||||
*/
|
||||
matches: readonly string[] | null;
|
||||
/** Index (within `matches`) of the currently highlighted row. */
|
||||
selectedIndex: number;
|
||||
/** The partial query the user typed after `@`. Shown in the hint row. */
|
||||
query: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Floating `@`-mention picker. Rendered below the input box when the
|
||||
* user is typing an `@…` prefix in code mode. Navigation state lives
|
||||
* in the parent (App.tsx owns `atSelected`) — this component is pure
|
||||
* display. Mirrors {@link SlashSuggestions} shape so the keybindings
|
||||
* and layout feel identical across the two pickers.
|
||||
*/
|
||||
export function AtMentionSuggestions({
|
||||
matches,
|
||||
selectedIndex,
|
||||
query,
|
||||
}: AtMentionSuggestionsProps): React.ReactElement | null {
|
||||
if (matches === null) return null;
|
||||
if (matches.length === 0) {
|
||||
return (
|
||||
<Box paddingX={1} marginTop={1}>
|
||||
<Text color="yellow">no files match "@{query}"</Text>
|
||||
<Text dimColor>
|
||||
{" "}
|
||||
— keep typing, or Backspace to edit. Paths resolve from the code root.
|
||||
</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
const MAX = 8;
|
||||
const total = matches.length;
|
||||
const windowStart =
|
||||
total <= MAX ? 0 : Math.max(0, Math.min(selectedIndex - Math.floor(MAX / 2), total - MAX));
|
||||
const shown = matches.slice(windowStart, windowStart + MAX);
|
||||
const hiddenAbove = windowStart;
|
||||
const hiddenBelow = total - windowStart - shown.length;
|
||||
return (
|
||||
<Box flexDirection="column" paddingX={1} marginTop={1}>
|
||||
{hiddenAbove > 0 ? <Text dimColor> ↑ {hiddenAbove} more above</Text> : null}
|
||||
{shown.map((path, i) => (
|
||||
<FileRow key={path} path={path} isSelected={windowStart + i === selectedIndex} />
|
||||
))}
|
||||
{hiddenBelow > 0 ? <Text dimColor> ↓ {hiddenBelow} more below</Text> : null}
|
||||
<Text dimColor> [↑↓] navigate · [Tab]/[Enter] pick · file content inlined on send</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
function FileRow({ path, isSelected }: { path: string; isSelected: boolean }) {
|
||||
const marker = isSelected ? "▸" : " ";
|
||||
// Split the path so the basename visually pops — same dropdown
|
||||
// affordance as VS Code's Quick Open.
|
||||
const slash = path.lastIndexOf("/");
|
||||
const dir = slash >= 0 ? `${path.slice(0, slash)}/` : "";
|
||||
const base = slash >= 0 ? path.slice(slash + 1) : path;
|
||||
if (isSelected) {
|
||||
return (
|
||||
<Box>
|
||||
<Text bold color="cyan">
|
||||
{marker} {base}
|
||||
</Text>
|
||||
<Text color="cyan">{dir ? ` ${dir}` : ""}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Box>
|
||||
<Text dimColor>
|
||||
{marker} {base}
|
||||
{dir ? ` ${dir}` : ""}
|
||||
</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
/**
|
||||
* Modal picker shown when the model calls `ask_choice`. Renders the
|
||||
* question + 2–4 option rows (title + dimmed summary) + an optional
|
||||
* "Let me type my own answer" escape hatch when `allowCustom` is true.
|
||||
*
|
||||
* The escape hatch matters because DeepSeek flash sometimes misframes
|
||||
* the alternatives — none actually fit the user's intent. Without a
|
||||
* bailout the user would have to cancel, type feedback, and wait for
|
||||
* another round-trip. With it they just type and ship.
|
||||
*
|
||||
* Border color: magenta — deliberately distinct from cyan (plan),
|
||||
* green (checkpoint), red (shell) so the user's eye learns the modes
|
||||
* without reading headers.
|
||||
*/
|
||||
|
||||
import { Box, Text } from "ink";
|
||||
import React from "react";
|
||||
import type { ChoiceOption } from "../../tools/choice.js";
|
||||
import { SingleSelect } from "./Select.js";
|
||||
|
||||
export type ChoiceConfirmChoice =
|
||||
| { kind: "pick"; optionId: string }
|
||||
| { kind: "custom" }
|
||||
| { kind: "cancel" };
|
||||
|
||||
export interface ChoiceConfirmProps {
|
||||
question: string;
|
||||
options: ChoiceOption[];
|
||||
allowCustom: boolean;
|
||||
onChoose: (choice: ChoiceConfirmChoice) => void;
|
||||
}
|
||||
|
||||
const CUSTOM_VALUE = "__custom__";
|
||||
const CANCEL_VALUE = "__cancel__";
|
||||
|
||||
function ChoiceConfirmInner({ question, options, allowCustom, onChoose }: ChoiceConfirmProps) {
|
||||
const items: Array<{ value: string; label: string; hint?: string }> = options.map((opt) => ({
|
||||
value: opt.id,
|
||||
label: `${opt.id} · ${opt.title}`,
|
||||
hint: opt.summary,
|
||||
}));
|
||||
if (allowCustom) {
|
||||
items.push({
|
||||
value: CUSTOM_VALUE,
|
||||
label: "Let me type my own answer",
|
||||
hint: "None of the above fits — type a free-form reply. The model reads it verbatim.",
|
||||
});
|
||||
}
|
||||
items.push({
|
||||
value: CANCEL_VALUE,
|
||||
label: "Cancel — drop the question",
|
||||
hint: "Model stops and asks what you want instead.",
|
||||
});
|
||||
|
||||
return (
|
||||
<Box flexDirection="column" borderStyle="round" borderColor="magenta" paddingX={1} marginY={1}>
|
||||
<Box>
|
||||
<Text bold color="magenta">
|
||||
🔀 the model is asking you to pick
|
||||
</Text>
|
||||
</Box>
|
||||
<Box marginTop={1}>
|
||||
<Text>{question}</Text>
|
||||
</Box>
|
||||
<Box marginTop={1}>
|
||||
<SingleSelect
|
||||
initialValue={options[0]?.id}
|
||||
items={items}
|
||||
onSubmit={(v) => {
|
||||
if (v === CUSTOM_VALUE) onChoose({ kind: "custom" });
|
||||
else if (v === CANCEL_VALUE) onChoose({ kind: "cancel" });
|
||||
else onChoose({ kind: "pick", optionId: v });
|
||||
}}
|
||||
onCancel={() => onChoose({ kind: "cancel" })}
|
||||
footer="[↑↓] navigate · [Enter] select · [Esc] cancel"
|
||||
/>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
export const ChoiceConfirm = React.memo(ChoiceConfirmInner);
|
||||
@@ -0,0 +1,220 @@
|
||||
import { Box, Text, useInput, useStdout } from "ink";
|
||||
import React, { useMemo, useState } from "react";
|
||||
import { formatEditBlockDiff } from "../../code/diff-preview.js";
|
||||
import type { EditBlock } from "../../code/edit-blocks.js";
|
||||
|
||||
/**
|
||||
* Choice surfaced to the interceptor when the user resolves the modal:
|
||||
* - `apply` → apply this edit, keep prompting on next.
|
||||
* - `reject` → tell the model the user refused; do NOT
|
||||
* retry the same edit.
|
||||
* - `apply-rest-of-turn` → apply this edit AND every remaining edit
|
||||
* this turn without further prompts. Resets
|
||||
* at the next user turn.
|
||||
* - `flip-to-auto` → apply this edit + persistently switch the
|
||||
* session to AUTO mode (survives restart).
|
||||
*/
|
||||
export type EditReviewChoice = "apply" | "reject" | "apply-rest-of-turn" | "flip-to-auto";
|
||||
|
||||
export interface EditConfirmProps {
|
||||
block: EditBlock;
|
||||
onChoose: (choice: EditReviewChoice) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Overhead reserved for non-diff UI inside the modal: border (2),
|
||||
* title (1), separator (1), file-header (1), scroll-indicator rows
|
||||
* (up to 2), footer + margin (3), plus breathing room for the host
|
||||
* TUI's chrome above (stats panel ≈ 4, historical live rows, prompt
|
||||
* input ≈ 2). 18 rows absorbed before the diff gets any budget.
|
||||
*/
|
||||
const MODAL_OVERHEAD_ROWS = 18;
|
||||
|
||||
/**
|
||||
* Absolute floor on the diff viewport. If the terminal is absurdly
|
||||
* short (< 26 rows total) we still show at least 8 diff lines so the
|
||||
* modal is usable; the user scrolls more aggressively but can't end up
|
||||
* with a zero-height viewport.
|
||||
*/
|
||||
const MIN_DIFF_ROWS = 8;
|
||||
|
||||
/**
|
||||
* Modal-style approval for a single model-proposed file edit.
|
||||
*
|
||||
* Why per-edit instead of end-of-turn batch: users reported they can't
|
||||
* tell if the model is about to make one small change or seven sprawling
|
||||
* ones until the turn is over. Per-edit prompts let the user intervene
|
||||
* early — reject a bad direction before the model builds on it, or
|
||||
* approve the first few and hit `a` to let the rest land.
|
||||
*
|
||||
* Diff viewport: we compute the UNCAPPED diff once, then slice to a
|
||||
* height budget derived from terminal rows. Large diffs (100+ lines)
|
||||
* are scrollable via j/k/↑/↓/Space/PgUp/PgDn/g/G — the user can page
|
||||
* through the whole change before deciding, and the action footer
|
||||
* never scrolls off the bottom. Before the scroll support a 97-line
|
||||
* scene.ts diff truncated at "… 67 more …" which was unreviewable.
|
||||
*/
|
||||
export function EditConfirm({ block, onChoose }: EditConfirmProps) {
|
||||
const { stdout } = useStdout();
|
||||
const rows = stdout?.rows ?? 40;
|
||||
const budget = Math.max(MIN_DIFF_ROWS, rows - MODAL_OVERHEAD_ROWS);
|
||||
|
||||
// Full diff — maxLines pushed high enough that the diff-preview
|
||||
// renderer never inserts its own truncation marker. Context trimming
|
||||
// (contextLines) still applies for tight scan.
|
||||
const allLines = useMemo(
|
||||
() => formatEditBlockDiff(block, { contextLines: 2, maxLines: 100_000, indent: " " }),
|
||||
[block],
|
||||
);
|
||||
|
||||
const [scroll, setScroll] = useState(0);
|
||||
const maxScroll = Math.max(0, allLines.length - budget);
|
||||
// Clamp scroll if budget shrinks (terminal resized) after a previous
|
||||
// keypress drove the offset past the new ceiling.
|
||||
const effectiveScroll = Math.min(scroll, maxScroll);
|
||||
|
||||
useInput((input, key) => {
|
||||
// Action keys first — decision wins over scroll so a user who
|
||||
// hammered PgDn can still hit `y` at the end without a stray
|
||||
// extra scroll.
|
||||
if (key.return || input === "y") {
|
||||
onChoose("apply");
|
||||
return;
|
||||
}
|
||||
if (input === "n") {
|
||||
onChoose("reject");
|
||||
return;
|
||||
}
|
||||
if (input === "a") {
|
||||
onChoose("apply-rest-of-turn");
|
||||
return;
|
||||
}
|
||||
if (input === "A") {
|
||||
onChoose("flip-to-auto");
|
||||
return;
|
||||
}
|
||||
// Scroll navigation — vim-ish (j/k) and emacs-ish (arrows) both
|
||||
// work. Space for "next page" is the pager convention.
|
||||
if (key.downArrow || input === "j") {
|
||||
setScroll((s) => Math.min(maxScroll, s + 1));
|
||||
return;
|
||||
}
|
||||
if (key.upArrow || input === "k") {
|
||||
setScroll((s) => Math.max(0, s - 1));
|
||||
return;
|
||||
}
|
||||
if (key.pageDown || input === " " || input === "f") {
|
||||
setScroll((s) => Math.min(maxScroll, s + Math.max(1, budget - 2)));
|
||||
return;
|
||||
}
|
||||
if (key.pageUp || input === "b") {
|
||||
setScroll((s) => Math.max(0, s - Math.max(1, budget - 2)));
|
||||
return;
|
||||
}
|
||||
if (input === "g") {
|
||||
setScroll(0);
|
||||
return;
|
||||
}
|
||||
if (input === "G") {
|
||||
setScroll(maxScroll);
|
||||
return;
|
||||
}
|
||||
// Esc falls through to the parent abort handler.
|
||||
});
|
||||
|
||||
const isNew = block.search === "";
|
||||
const removed = isNew ? 0 : (block.search.match(/\n/g)?.length ?? 0) + 1;
|
||||
const added = block.replace === "" ? 0 : (block.replace.match(/\n/g)?.length ?? 0) + 1;
|
||||
const tag = isNew ? "NEW" : "EDIT";
|
||||
|
||||
const visibleLines = allLines.slice(effectiveScroll, effectiveScroll + budget);
|
||||
const hiddenAbove = effectiveScroll;
|
||||
const hiddenBelow = Math.max(0, allLines.length - effectiveScroll - budget);
|
||||
const totalLines = allLines.length;
|
||||
const showScrollHud = hiddenAbove + hiddenBelow > 0;
|
||||
|
||||
return (
|
||||
<Box flexDirection="column" borderStyle="round" borderColor="yellow" paddingX={1} marginY={1}>
|
||||
<Box>
|
||||
<Text bold color="yellow">
|
||||
{"▸ model wants to edit a file"}
|
||||
</Text>
|
||||
</Box>
|
||||
<Box>
|
||||
<Text color="yellow" dimColor>
|
||||
{"──────────────────────────────────────────"}
|
||||
</Text>
|
||||
</Box>
|
||||
<Box marginTop={1}>
|
||||
<Text>
|
||||
<Text color={isNew ? "green" : "yellow"} bold>{`[${tag}] `}</Text>
|
||||
<Text color="cyan">{block.path}</Text>
|
||||
<Text dimColor>{` (-${removed} +${added} lines)`}</Text>
|
||||
{showScrollHud ? (
|
||||
<Text dimColor>
|
||||
{` · viewing ${effectiveScroll + 1}-${effectiveScroll + visibleLines.length}/${totalLines}`}
|
||||
</Text>
|
||||
) : null}
|
||||
</Text>
|
||||
</Box>
|
||||
{hiddenAbove > 0 ? (
|
||||
<Text
|
||||
dimColor
|
||||
>{` ↑ ${hiddenAbove} line${hiddenAbove === 1 ? "" : "s"} above (↑/k or PgUp)`}</Text>
|
||||
) : null}
|
||||
<Box marginTop={hiddenAbove > 0 ? 0 : 1} flexDirection="column">
|
||||
{visibleLines.map((line, i) => {
|
||||
const trimmed = line.trimStart();
|
||||
const color = trimmed.startsWith("+")
|
||||
? "green"
|
||||
: trimmed.startsWith("-")
|
||||
? "red"
|
||||
: undefined;
|
||||
const dim = !color;
|
||||
return (
|
||||
<Text
|
||||
// Stable-enough: slice only shifts by scroll; React keys only
|
||||
// need to be unique within the current render.
|
||||
// biome-ignore lint/suspicious/noArrayIndexKey: list is static per render
|
||||
key={`diff-${effectiveScroll}-${i}`}
|
||||
color={color}
|
||||
dimColor={dim}
|
||||
>
|
||||
{line}
|
||||
</Text>
|
||||
);
|
||||
})}
|
||||
</Box>
|
||||
{hiddenBelow > 0 ? (
|
||||
<Text
|
||||
dimColor
|
||||
>{` ↓ ${hiddenBelow} line${hiddenBelow === 1 ? "" : "s"} below (↓/j or Space/PgDn)`}</Text>
|
||||
) : null}
|
||||
<Box marginTop={1}>
|
||||
<Text dimColor>
|
||||
{"["}
|
||||
<Text color="cyan" bold>
|
||||
y
|
||||
</Text>
|
||||
{"/Enter] apply · ["}
|
||||
<Text color="cyan" bold>
|
||||
n
|
||||
</Text>
|
||||
{"] reject · ["}
|
||||
<Text color="cyan" bold>
|
||||
a
|
||||
</Text>
|
||||
{"] apply rest · ["}
|
||||
<Text color="cyan" bold>
|
||||
A
|
||||
</Text>
|
||||
{"] flip AUTO · ["}
|
||||
<Text color="cyan" bold>
|
||||
↑↓/Space
|
||||
</Text>
|
||||
{"] scroll · [Esc] abort"}
|
||||
</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
+592
-89
@@ -1,11 +1,51 @@
|
||||
import { Box, Text } from "ink";
|
||||
import React, { useEffect, useState } from "react";
|
||||
import { Box, Text, useStdout } from "ink";
|
||||
import React from "react";
|
||||
import { type TypedPlanState, isPlanStateEmpty } from "../../harvest.js";
|
||||
import type { BranchProgress, BranchSummary } from "../../loop.js";
|
||||
import type { TurnStats } from "../../telemetry.js";
|
||||
import type { PlanStep } from "../../tools/plan.js";
|
||||
import { PlanStateBlock } from "./PlanStateBlock.js";
|
||||
import { PlanStepList } from "./PlanStepList.js";
|
||||
import { Markdown } from "./markdown.js";
|
||||
import { useElapsedSeconds, useTick } from "./ticker.js";
|
||||
import { formatDuration, summarizeToolResult } from "./tool-summary.js";
|
||||
|
||||
export type DisplayRole = "user" | "assistant" | "tool" | "system" | "error" | "info";
|
||||
export type DisplayRole =
|
||||
| "user"
|
||||
| "assistant"
|
||||
| "tool"
|
||||
| "system"
|
||||
| "error"
|
||||
| "info"
|
||||
| "warning"
|
||||
/**
|
||||
* A plan body pushed to scrollback when the model calls `submit_plan`.
|
||||
* Rendered through the full markdown pipeline (not truncated), so the
|
||||
* user reads the whole thing in the permanent Static log and the
|
||||
* PlanConfirm modal below it stays a tight picker.
|
||||
*/
|
||||
| "plan"
|
||||
/**
|
||||
* One step of an approved plan ticked off via `mark_step_complete`.
|
||||
* Rendered as a compact `✓ step-id · title — result (N/M)` row so
|
||||
* the user can glance at the scrollback and see how far along the
|
||||
* execution is without scrolling through every tool call.
|
||||
*/
|
||||
| "step-progress"
|
||||
/**
|
||||
* Pushed once at session startup when an existing plan was loaded
|
||||
* from disk. Renders as a bordered box with the step list and
|
||||
* progress so the user sees exactly where they left off — much
|
||||
* more useful than the bare "2/5 done" info line it replaced.
|
||||
*/
|
||||
| "plan-resumed"
|
||||
/**
|
||||
* Read-only snapshot of an archived (completed) plan, pushed by
|
||||
* the `/replay` slash. Visually distinct from `plan-resumed` —
|
||||
* dim border + ⏪ icon — so the user immediately sees this is
|
||||
* historical, not the active plan.
|
||||
*/
|
||||
| "plan-replay";
|
||||
|
||||
export interface DisplayEvent {
|
||||
id: string;
|
||||
@@ -16,19 +56,125 @@ export interface DisplayEvent {
|
||||
branch?: BranchSummary;
|
||||
branchProgress?: BranchProgress;
|
||||
toolName?: string;
|
||||
/**
|
||||
* 1-based position in the session's tool-call history. Rendered as a
|
||||
* dim `/tool N` suffix on compact rows so the user can quickly jump
|
||||
* to the full output via the existing `/tool` slash command.
|
||||
*/
|
||||
toolIndex?: number;
|
||||
/** Wall-clock duration in ms between tool_start and result. */
|
||||
durationMs?: number;
|
||||
stats?: TurnStats;
|
||||
repair?: string;
|
||||
streaming?: boolean;
|
||||
toolCallBuild?: { name: string; chars: number; index?: number; readyCount?: number };
|
||||
/**
|
||||
* Populated on `step-progress` rows: the step id, optional title,
|
||||
* completion counter, and optional notes. Rendered into the compact
|
||||
* single-row layout — no other role reads these fields.
|
||||
*/
|
||||
stepProgress?: {
|
||||
stepId: string;
|
||||
title?: string;
|
||||
completed: number;
|
||||
total: number;
|
||||
notes?: string;
|
||||
};
|
||||
/**
|
||||
* Populated on `plan-resumed` rows: the structured plan loaded from
|
||||
* disk + the set of step ids the user had already completed +
|
||||
* a relative-time hint for the header. Rendered as a bordered
|
||||
* snapshot so the user picks back up immediately.
|
||||
*/
|
||||
resumedPlan?: {
|
||||
steps: PlanStep[];
|
||||
completedStepIds: string[];
|
||||
relativeTime: string;
|
||||
/** Optional human-friendly title; rendered in the banner header when set. */
|
||||
summary?: string;
|
||||
};
|
||||
/**
|
||||
* Populated on `plan-replay` rows: the archived plan plus enough
|
||||
* navigation context (index / total) for the user to know where
|
||||
* they are in the archive history.
|
||||
*/
|
||||
replayPlan?: {
|
||||
summary?: string;
|
||||
body?: string;
|
||||
steps: PlanStep[];
|
||||
completedStepIds: string[];
|
||||
relativeTime: string;
|
||||
archiveBasename: string;
|
||||
index: number;
|
||||
total: number;
|
||||
};
|
||||
/**
|
||||
* Render a thin horizontal rule above this event. Used to mark
|
||||
* "start of a new user turn" so long scrollbacks get visual
|
||||
* pacing — without it, five-turn sessions read as one wall of
|
||||
* text. Only the *first* user message in a session should leave
|
||||
* this off; App.tsx sets it based on whether history is empty.
|
||||
*/
|
||||
leadSeparator?: boolean;
|
||||
}
|
||||
|
||||
export const EventRow = React.memo(function EventRow({ event }: { event: DisplayEvent }) {
|
||||
/**
|
||||
* Reasonix visual language: every event is anchored by a geometric
|
||||
* glyph in its role color. Together they form a consistent alphabet
|
||||
* (◇ ◆ ▣ ▥ ▲ ✦) the eye learns fast — no text labels needed after
|
||||
* the first couple of turns. `◈` is the brand mark, reserved for
|
||||
* the app header.
|
||||
*/
|
||||
const ROLE_GLYPH = {
|
||||
user: "◇",
|
||||
assistant: "◆",
|
||||
assistantPulse: "◇", // pulse alternate for streaming state
|
||||
toolOk: "▣",
|
||||
toolErr: "▥",
|
||||
warning: "▲",
|
||||
error: "✦",
|
||||
} as const;
|
||||
|
||||
function RoleGlyph({
|
||||
glyph,
|
||||
color,
|
||||
}: {
|
||||
glyph: string;
|
||||
color: "cyan" | "green" | "yellow" | "red" | "magenta" | "blue";
|
||||
}) {
|
||||
return (
|
||||
<Text color={color} bold>
|
||||
{glyph}
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Pad continuation lines so wrapped multi-line text aligns under the
|
||||
* glyph indent instead of jumping back to column 0. Header is `glyph
|
||||
* (1 col) + " " (2 cols)`, so subsequent lines need 3 leading spaces
|
||||
* to land under the body's first character.
|
||||
*/
|
||||
function indentContinuationLines(text: string): string {
|
||||
if (!text.includes("\n")) return text;
|
||||
return text.split("\n").join("\n ");
|
||||
}
|
||||
|
||||
export const EventRow = React.memo(function EventRow({
|
||||
event,
|
||||
projectRoot,
|
||||
}: {
|
||||
event: DisplayEvent;
|
||||
projectRoot?: string;
|
||||
}) {
|
||||
if (event.role === "user") {
|
||||
return (
|
||||
<Box>
|
||||
<Text bold color="cyan">
|
||||
you ›{" "}
|
||||
<Box marginTop={event.leadSeparator ? 1 : 0}>
|
||||
<RoleGlyph glyph={ROLE_GLYPH.user} color="cyan" />
|
||||
<Text>
|
||||
{" "}
|
||||
{indentContinuationLines(event.text)}
|
||||
</Text>
|
||||
<Text>{event.text}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -37,36 +183,85 @@ export const EventRow = React.memo(function EventRow({ event }: { event: Display
|
||||
return (
|
||||
<Box flexDirection="column" marginTop={1}>
|
||||
<Box>
|
||||
<Text bold color="green">
|
||||
assistant
|
||||
</Text>
|
||||
<RoleGlyph glyph={ROLE_GLYPH.assistant} color="green" />
|
||||
{event.stats ? <Text dimColor>{` ${event.stats.model}`}</Text> : null}
|
||||
</Box>
|
||||
<Box flexDirection="column" paddingLeft={2} marginTop={1}>
|
||||
{event.branch ? <BranchBlock branch={event.branch} /> : null}
|
||||
{event.reasoning ? <ReasoningBlock reasoning={event.reasoning} /> : null}
|
||||
{!isPlanStateEmpty(event.planState) ? (
|
||||
<PlanStateBlock planState={event.planState!} />
|
||||
) : null}
|
||||
{event.text ? (
|
||||
<Markdown text={event.text} projectRoot={projectRoot} />
|
||||
) : (
|
||||
<Text dimColor>(no content)</Text>
|
||||
)}
|
||||
{event.stats ? <StatsLine stats={event.stats} /> : null}
|
||||
{event.repair ? <Text color="magenta">{event.repair}</Text> : null}
|
||||
</Box>
|
||||
{event.branch ? <BranchBlock branch={event.branch} /> : null}
|
||||
{event.reasoning ? <ReasoningBlock reasoning={event.reasoning} /> : null}
|
||||
{!isPlanStateEmpty(event.planState) ? (
|
||||
<PlanStateBlock planState={event.planState!} />
|
||||
) : null}
|
||||
{event.text ? <Markdown text={event.text} /> : <Text dimColor>(no content)</Text>}
|
||||
{event.stats ? <StatsLine stats={event.stats} /> : null}
|
||||
{event.repair ? <Text color="magenta">{event.repair}</Text> : null}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
if (event.role === "tool") {
|
||||
// `edit_file` results get a dedicated multi-line diff renderer —
|
||||
// colored line-by-line so `-` removals show red, `+` additions
|
||||
// show green, unchanged context lines dim. Always full, never
|
||||
// truncated: users need to see the whole change to trust /apply.
|
||||
const isExplicitError = event.text.startsWith("ERROR:");
|
||||
const isEditFile =
|
||||
(event.toolName === "edit_file" || event.toolName?.endsWith("_edit_file")) &&
|
||||
!isExplicitError;
|
||||
if (isEditFile) {
|
||||
return (
|
||||
<Box flexDirection="column" marginTop={1}>
|
||||
<Box>
|
||||
<RoleGlyph glyph={ROLE_GLYPH.toolOk} color="yellow" />
|
||||
<Text color="yellow" bold>{` ${event.toolName ?? "?"}`}</Text>
|
||||
<Text color="yellow" dimColor>
|
||||
{" →"}
|
||||
</Text>
|
||||
</Box>
|
||||
<Box flexDirection="column" paddingLeft={2} marginTop={1}>
|
||||
<EditFileDiff text={event.text} />
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
// Compact one-line render for everything else. The summarizer
|
||||
// produces a tool-aware one-liner (exit code for shell, line
|
||||
// count for read_file, error tag for failures, ...). Full content
|
||||
// remains accessible via `/tool N`, hinted as a dim suffix.
|
||||
const summary = summarizeToolResult(event.toolName ?? "?", event.text);
|
||||
const color = summary.isError ? "red" : "yellow";
|
||||
const glyph = summary.isError ? ROLE_GLYPH.toolErr : ROLE_GLYPH.toolOk;
|
||||
const marker = summary.isError ? "✗" : "→";
|
||||
const durationLabel =
|
||||
event.durationMs !== undefined && event.durationMs >= 100
|
||||
? ` (${formatDuration(event.durationMs)})`
|
||||
: "";
|
||||
const indexHint = event.toolIndex !== undefined ? ` /tool ${event.toolIndex}` : "";
|
||||
return (
|
||||
<Box flexDirection="column" marginTop={1}>
|
||||
<Text color="yellow">{`tool<${event.toolName ?? "?"}> →`}</Text>
|
||||
<Text dimColor> {truncate(event.text, 400)}</Text>
|
||||
<Box>
|
||||
<RoleGlyph glyph={glyph} color={color} />
|
||||
<Text color={color} bold>{` ${event.toolName ?? "?"}`}</Text>
|
||||
{durationLabel ? <Text dimColor>{durationLabel}</Text> : null}
|
||||
<Text color={color} dimColor>{` ${marker} `}</Text>
|
||||
<Text color={summary.isError ? "red" : undefined} dimColor={!summary.isError}>
|
||||
{summary.summary}
|
||||
</Text>
|
||||
{indexHint ? <Text dimColor>{indexHint}</Text> : null}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
if (event.role === "error") {
|
||||
return (
|
||||
<Box marginTop={1}>
|
||||
<Text color="red" bold>
|
||||
error{" "}
|
||||
<RoleGlyph glyph={ROLE_GLYPH.error} color="red" />
|
||||
<Text color="red">
|
||||
{" "}
|
||||
{indentContinuationLines(event.text)}
|
||||
</Text>
|
||||
<Text color="red">{event.text}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -77,6 +272,144 @@ export const EventRow = React.memo(function EventRow({ event }: { event: Display
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
if (event.role === "plan") {
|
||||
return (
|
||||
<Box flexDirection="column" borderStyle="round" borderColor="cyan" paddingX={1} marginY={1}>
|
||||
<Box>
|
||||
<Text bold color="cyan">
|
||||
{"📋 plan proposed — pick a choice below"}
|
||||
</Text>
|
||||
</Box>
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
<Markdown text={event.text} projectRoot={projectRoot} />
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
if (event.role === "step-progress") {
|
||||
const sp = event.stepProgress;
|
||||
const counter = sp && sp.total > 0 ? ` (${sp.completed}/${sp.total})` : "";
|
||||
const label = sp?.title ? `${sp.stepId} · ${sp.title}` : (sp?.stepId ?? "");
|
||||
return (
|
||||
<Box flexDirection="column" marginTop={1}>
|
||||
<Box>
|
||||
<Text color="green" bold>
|
||||
✓
|
||||
</Text>
|
||||
<Text color="green">{` ${label}`}</Text>
|
||||
<Text dimColor>{counter}</Text>
|
||||
</Box>
|
||||
{event.text ? (
|
||||
<Box paddingLeft={2}>
|
||||
<Text dimColor>{event.text}</Text>
|
||||
</Box>
|
||||
) : null}
|
||||
{sp?.notes ? (
|
||||
<Box paddingLeft={2}>
|
||||
<Text color="yellow" dimColor>
|
||||
{`note: ${sp.notes}`}
|
||||
</Text>
|
||||
</Box>
|
||||
) : null}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
if (event.role === "plan-resumed") {
|
||||
const rp = event.resumedPlan;
|
||||
if (!rp || rp.steps.length === 0) return null;
|
||||
const total = rp.steps.length;
|
||||
const done = rp.completedStepIds.length;
|
||||
const completedSet = new Set(rp.completedStepIds);
|
||||
const statuses = new Map(
|
||||
rp.steps.map((s) => [
|
||||
s.id,
|
||||
completedSet.has(s.id) ? ("done" as const) : ("pending" as const),
|
||||
]),
|
||||
);
|
||||
// Focus the first pending step so the user immediately sees where
|
||||
// execution will resume from. If the plan is fully done, no focus
|
||||
// (the picker pattern uses › for "next up").
|
||||
const nextStep = rp.steps.find((s) => !completedSet.has(s.id));
|
||||
return (
|
||||
<Box flexDirection="column" borderStyle="round" borderColor="cyan" paddingX={1} marginY={1}>
|
||||
<Box flexDirection="column">
|
||||
<Box>
|
||||
<Text bold color="cyan">
|
||||
▸ resumed plan
|
||||
</Text>
|
||||
<Text dimColor>{` ${done}/${total} done · last touched ${rp.relativeTime}`}</Text>
|
||||
</Box>
|
||||
{rp.summary ? (
|
||||
<Box>
|
||||
<Text color="cyan">{` ${rp.summary}`}</Text>
|
||||
</Box>
|
||||
) : null}
|
||||
</Box>
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
<PlanStepList steps={rp.steps} statuses={statuses} focusStepId={nextStep?.id} />
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
if (event.role === "plan-replay") {
|
||||
const r = event.replayPlan;
|
||||
if (!r || r.steps.length === 0) return null;
|
||||
const total = r.steps.length;
|
||||
const completedSet = new Set(r.completedStepIds);
|
||||
const done = completedSet.size;
|
||||
const statuses = new Map(
|
||||
r.steps.map((s) => [s.id, completedSet.has(s.id) ? ("done" as const) : ("pending" as const)]),
|
||||
);
|
||||
const navHint = r.total > 1 ? ` · ${r.index}/${r.total}` : "";
|
||||
return (
|
||||
<Box flexDirection="column" borderStyle="round" borderColor="gray" paddingX={1} marginY={1}>
|
||||
<Box flexDirection="column">
|
||||
<Box>
|
||||
<Text bold dimColor>
|
||||
⏪ replay
|
||||
</Text>
|
||||
<Text
|
||||
dimColor
|
||||
>{` completed ${r.relativeTime} · ${done}/${total} done${navHint}`}</Text>
|
||||
</Box>
|
||||
{r.summary ? (
|
||||
<Box>
|
||||
<Text dimColor>{` ${r.summary}`}</Text>
|
||||
</Box>
|
||||
) : null}
|
||||
<Box>
|
||||
<Text dimColor>{` ${r.archiveBasename}`}</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
{r.body ? (
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
<Markdown text={r.body} projectRoot={projectRoot} />
|
||||
</Box>
|
||||
) : null}
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
<PlanStepList steps={r.steps} statuses={statuses} />
|
||||
</Box>
|
||||
<Box marginTop={1}>
|
||||
<Text dimColor>
|
||||
{r.total > 1
|
||||
? `(read-only · /replay ${r.index === 1 ? 2 : 1} for the ${r.index === 1 ? "next" : "newest"} archive)`
|
||||
: "(read-only · this is an archived plan)"}
|
||||
</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
if (event.role === "warning") {
|
||||
return (
|
||||
<Box>
|
||||
<RoleGlyph glyph={ROLE_GLYPH.warning} color="yellow" />
|
||||
<Text color="yellow">
|
||||
{" "}
|
||||
{indentContinuationLines(event.text)}
|
||||
</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Box>
|
||||
<Text>{event.text}</Text>
|
||||
@@ -84,6 +417,87 @@ export const EventRow = React.memo(function EventRow({ event }: { event: Display
|
||||
);
|
||||
});
|
||||
|
||||
/**
|
||||
* Thin horizontal rule between turns with a cyan ◆ centered as the
|
||||
* Reasonix mark. Past-turn separators live inside `<Static>` (Ink's
|
||||
* render-once optimization), so animation here would freeze at
|
||||
* tick=0 on every past turn — we keep it static by design. The
|
||||
* animated heartbeat lives in PulsingAssistantGlyph (current turn)
|
||||
* and the Wordmark (StatsPanel) where rerender is free.
|
||||
*/
|
||||
function TurnSeparator() {
|
||||
const { stdout } = useStdout();
|
||||
const cols = stdout?.columns ?? 80;
|
||||
const width = Math.max(16, cols - 2);
|
||||
const half = Math.floor((width - 3) / 2);
|
||||
const left = "─".repeat(half);
|
||||
const right = "─".repeat(width - half - 3);
|
||||
return (
|
||||
<Box marginTop={1} marginBottom={1}>
|
||||
<Text dimColor>{left}</Text>
|
||||
<Text color="cyan" bold>
|
||||
{" ◆ "}
|
||||
</Text>
|
||||
<Text dimColor>{right}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the payload of an `edit_file` tool result with proper
|
||||
* diff coloring: first line is the header ("edited X (A→B chars)"),
|
||||
* subsequent lines are prefixed with `-` (removed), `+` (added), or
|
||||
* space (unchanged context). Unchanged lines render dim so the
|
||||
* changed ones pop visually. No truncation — the whole diff is
|
||||
* shown so the user can audit what landed before `/apply` or
|
||||
* `git diff` review.
|
||||
*/
|
||||
function EditFileDiff({ text }: { text: string }) {
|
||||
const lines = text.split(/\r?\n/);
|
||||
// Line 0 is the status header ("edited X (A→B chars)"), Line 1 is
|
||||
// the unified-diff hunk header ("@@ -N,M +N,M @@"), the rest is
|
||||
// the colored diff body. We style the two headers distinctly so
|
||||
// the hunk marker stands out the way git-diff's cyan `@@` does in
|
||||
// most terminals.
|
||||
const [statusHeader, hunkHeader, ...body] = lines;
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
<Text dimColor>{` ${statusHeader ?? ""}`}</Text>
|
||||
{hunkHeader !== undefined ? (
|
||||
<Text color="cyan" bold>
|
||||
{hunkHeader}
|
||||
</Text>
|
||||
) : null}
|
||||
{body.map((line, i) => {
|
||||
// Key includes the line content slice so React isn't forced
|
||||
// to treat purely-positional identity; lines in the same
|
||||
// diff don't reorder but could repeat (e.g. blank lines).
|
||||
const key = `${i}-${line.slice(0, 32)}`;
|
||||
if (line.startsWith("- ")) {
|
||||
return (
|
||||
<Text key={key} color="red">
|
||||
{line}
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
if (line.startsWith("+ ")) {
|
||||
return (
|
||||
<Text key={key} color="green">
|
||||
{line}
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
// Context line (starts with " ") or unknown — dim.
|
||||
return (
|
||||
<Text key={key} dimColor>
|
||||
{line}
|
||||
</Text>
|
||||
);
|
||||
})}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
function BranchBlock({ branch }: { branch: BranchSummary }) {
|
||||
const per = branch.uncertainties
|
||||
.map((u, i) => {
|
||||
@@ -95,7 +509,7 @@ function BranchBlock({ branch }: { branch: BranchSummary }) {
|
||||
return (
|
||||
<Box>
|
||||
<Text color="blue">
|
||||
{"🔀 branched "}
|
||||
{"⎇ branched "}
|
||||
<Text bold>{branch.budget}</Text>
|
||||
{` samples → picked #${branch.chosenIndex} `}
|
||||
<Text dimColor>{per}</Text>
|
||||
@@ -104,35 +518,25 @@ function BranchBlock({ branch }: { branch: BranchSummary }) {
|
||||
);
|
||||
}
|
||||
|
||||
function PlanStateBlock({ planState }: { planState: TypedPlanState }) {
|
||||
const lines: Array<[string, string[]]> = [];
|
||||
if (planState.subgoals.length) lines.push(["subgoals", planState.subgoals]);
|
||||
if (planState.hypotheses.length) lines.push(["hypotheses", planState.hypotheses]);
|
||||
if (planState.uncertainties.length) lines.push(["uncertainties", planState.uncertainties]);
|
||||
if (planState.rejectedPaths.length) lines.push(["rejected", planState.rejectedPaths]);
|
||||
return (
|
||||
<Box flexDirection="column" marginBottom={1}>
|
||||
{lines.map(([label, items]) => (
|
||||
<Text key={label} color="magenta">
|
||||
{"‹ "}
|
||||
<Text bold>{label}</Text>
|
||||
{` (${items.length}): ${items.join(" · ")}`}
|
||||
</Text>
|
||||
))}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
function ReasoningBlock({ reasoning }: { reasoning: string }) {
|
||||
const max = 220;
|
||||
const max = 260;
|
||||
const flat = reasoning.replace(/\s+/g, " ").trim();
|
||||
// Show the TAIL of the reasoning rather than the head. R1 opens
|
||||
// with generic scaffolding ("let me look at the structure...") that
|
||||
// repeats across turns and hides the part users actually want to
|
||||
// see — the decision right before the model commits to an action.
|
||||
// Users can dump the full reasoning with `/think` if needed.
|
||||
const preview =
|
||||
flat.length <= max ? flat : `${flat.slice(0, max)}… (+${flat.length - max} chars)`;
|
||||
flat.length <= max ? flat : `… (+${flat.length - max} earlier chars) ${flat.slice(-max)}`;
|
||||
// ▏ (LEFT ONE EIGHTH BLOCK) renders as a thin vertical rule at the
|
||||
// cell edge — subtler than the role-level ▎ above, giving a
|
||||
// visual hierarchy: thick bar = role, thin bar = nested detail
|
||||
// under that role (thinking, stats, citations, etc).
|
||||
return (
|
||||
<Box marginBottom={1}>
|
||||
<Text dimColor>▏ </Text>
|
||||
<Text dimColor italic>
|
||||
{"↳ thinking: "}
|
||||
{preview}
|
||||
thinking {preview}
|
||||
</Text>
|
||||
</Box>
|
||||
);
|
||||
@@ -144,17 +548,28 @@ 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>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Animated role glyph for the actively-streaming assistant. Alternates
|
||||
* ◆ ↔ ◇ every ~480ms so the user can see the model is alive even
|
||||
* during R1's long pre-first-byte silence. Settles back to a static
|
||||
* ◆ once the turn ends (StreamingAssistant is unmounted).
|
||||
*/
|
||||
function PulsingAssistantGlyph() {
|
||||
const tick = useTick();
|
||||
const on = Math.floor(tick / 4) % 2 === 0;
|
||||
return (
|
||||
<Text color="green" bold>
|
||||
{on ? ROLE_GLYPH.assistant : ROLE_GLYPH.assistantPulse}
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
|
||||
function StreamingAssistant({ event }: { event: DisplayEvent }) {
|
||||
if (event.branchProgress) {
|
||||
const p = event.branchProgress;
|
||||
@@ -163,15 +578,17 @@ function StreamingAssistant({ event }: { event: DisplayEvent }) {
|
||||
return (
|
||||
<Box flexDirection="column" marginTop={1}>
|
||||
<Box>
|
||||
<Text bold color="green">
|
||||
assistant{" "}
|
||||
</Text>
|
||||
<PulsingAssistantGlyph />
|
||||
<Text color="blue">
|
||||
🔀 launching {p.total} parallel samples (R1 thinking in parallel)…{" "}
|
||||
{" ⎇ launching "}
|
||||
{p.total}
|
||||
{" parallel samples (R1 thinking in parallel)… "}
|
||||
</Text>
|
||||
<Elapsed />
|
||||
</Box>
|
||||
<Text dimColor>{" "}spread across T=0.0/0.5/1.0 · typical wait 30-90s for reasoner</Text>
|
||||
<Text color="yellow">
|
||||
{" "}spread across T=0.0/0.5/1.0 · reasoner typically takes 30-90s — this is normal
|
||||
</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -179,11 +596,13 @@ function StreamingAssistant({ event }: { event: DisplayEvent }) {
|
||||
return (
|
||||
<Box flexDirection="column" marginTop={1}>
|
||||
<Box>
|
||||
<Text bold color="green">
|
||||
assistant{" "}
|
||||
</Text>
|
||||
<PulsingAssistantGlyph />
|
||||
<Text color="blue">
|
||||
🔀 branching {p.completed}/{p.total} ({pct}%){" "}
|
||||
{" ⎇ branching "}
|
||||
{p.completed}/{p.total}
|
||||
{" ("}
|
||||
{pct}
|
||||
{"%) "}
|
||||
</Text>
|
||||
<Elapsed />
|
||||
</Box>
|
||||
@@ -202,16 +621,50 @@ function StreamingAssistant({ event }: { event: DisplayEvent }) {
|
||||
|
||||
const tail = lastLine(event.text, 140);
|
||||
const reasoningTail = event.reasoning ? lastLine(event.reasoning, 120) : "";
|
||||
const toolCallBuild = event.toolCallBuild;
|
||||
// Four distinct phases a turn can be in — label them plainly so
|
||||
// the user doesn't have to decode "streaming · 391 + think 4506
|
||||
// chars" to figure out what's happening:
|
||||
// pre-first-byte: request in flight, no bytes back yet
|
||||
// reasoning-only: R1 thinking, no visible content yet
|
||||
// tool-call-only: tool_call arguments streaming, no content/reasoning bytes
|
||||
// writing: content streaming (R1 has already produced its thought)
|
||||
// both: rare — content present AND reasoning still growing
|
||||
// We can't cheaply distinguish "reasoning still growing" from
|
||||
// "reasoning finished but we already saw it", so when content is
|
||||
// present we just say "writing response" and surface both counts.
|
||||
const preFirstByte = !event.text && !event.reasoning && !toolCallBuild;
|
||||
const reasoningOnly = !event.text && !!event.reasoning && !toolCallBuild;
|
||||
const toolCallOnly = !event.text && !event.reasoning && !!toolCallBuild;
|
||||
let label: string;
|
||||
let labelColor: "yellow" | "cyan" | "green" | "magenta" | undefined;
|
||||
if (preFirstByte) {
|
||||
label = "request sent · waiting for server";
|
||||
labelColor = "yellow";
|
||||
} else if (reasoningOnly) {
|
||||
label = `R1 reasoning · ${event.reasoning?.length ?? 0} chars of thought`;
|
||||
labelColor = "cyan";
|
||||
} else if (toolCallOnly) {
|
||||
label = `assembling tool call${formatToolCallIndex(toolCallBuild)} <${toolCallBuild.name}> · ${toolCallBuild.chars} chars of arguments${formatReadyTail(toolCallBuild)}`;
|
||||
labelColor = "magenta";
|
||||
} else {
|
||||
const parts: string[] = [`writing response · ${event.text.length} chars`];
|
||||
if (event.reasoning) parts.push(`after ${event.reasoning.length} chars of reasoning`);
|
||||
if (toolCallBuild) {
|
||||
parts.push(
|
||||
`building tool call${formatToolCallIndex(toolCallBuild)} <${toolCallBuild.name}> · ${toolCallBuild.chars} chars${formatReadyTail(toolCallBuild)}`,
|
||||
);
|
||||
}
|
||||
label = parts.join(" · ");
|
||||
labelColor = "green";
|
||||
}
|
||||
return (
|
||||
<Box flexDirection="column" marginTop={1}>
|
||||
<Box>
|
||||
<Text bold color="green">
|
||||
assistant{" "}
|
||||
</Text>
|
||||
<Text dimColor>
|
||||
(streaming · {event.text.length}
|
||||
{event.reasoning ? ` + think ${event.reasoning.length}` : ""} chars){" "}
|
||||
</Text>
|
||||
<PulsingAssistantGlyph />
|
||||
<Text>{" "}</Text>
|
||||
<Pulse />
|
||||
<Text color={labelColor}>{` ${label} `}</Text>
|
||||
<Elapsed />
|
||||
</Box>
|
||||
{reasoningTail ? (
|
||||
@@ -221,15 +674,66 @@ function StreamingAssistant({ event }: { event: DisplayEvent }) {
|
||||
) : null}
|
||||
{tail ? (
|
||||
<Text dimColor>▸ {tail}</Text>
|
||||
) : (
|
||||
<Text dimColor italic>
|
||||
{" (waiting for first token…)"}
|
||||
) : preFirstByte ? (
|
||||
// Non-dim yellow: first-time users misread the dim version as
|
||||
// "app frozen". The reassurance has to be VISIBLE to do its job.
|
||||
<Text color="yellow" italic>
|
||||
{" waiting for first byte — this is normal, typically 5-60s depending on model + load"}
|
||||
</Text>
|
||||
)}
|
||||
) : reasoningOnly ? (
|
||||
<Text color="yellow" italic>
|
||||
{
|
||||
" R1 is thinking before it speaks — body text arrives when reasoning finishes (typically 20-90s, this is normal)"
|
||||
}
|
||||
</Text>
|
||||
) : toolCallOnly ? (
|
||||
<Text color="magenta" italic>
|
||||
{" tool-call arguments streaming — the model is about to dispatch a tool"}
|
||||
</Text>
|
||||
) : event.reasoning ? (
|
||||
<Text color="yellow" italic>
|
||||
{" R1 still reasoning — body text or tool call arrives when thinking finishes"}
|
||||
</Text>
|
||||
) : null}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Blinking indicator so the user can tell the stream is alive even
|
||||
* when the reasoner hasn't produced body text yet. Uses the shared
|
||||
* tick (TICK_MS ≈ 120ms) scaled down 4× so the visible blink rate
|
||||
* lands around 500ms — feels like a heartbeat, not a progress bar.
|
||||
*/
|
||||
function Pulse() {
|
||||
const tick = useTick();
|
||||
const frames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
|
||||
return <Text color="cyan">{frames[Math.floor(tick / 4) % frames.length]}</Text>;
|
||||
}
|
||||
|
||||
/**
|
||||
* "(call 3)" suffix for the tool-call label when we have the index.
|
||||
* Hides when the turn only has one call so the common case stays tidy.
|
||||
*/
|
||||
function formatToolCallIndex(tb: { index?: number; readyCount?: number } | undefined): string {
|
||||
if (!tb || tb.index === undefined) return "";
|
||||
// Only show the index when this isn't obviously the first + only call.
|
||||
if (tb.index === 0 && (tb.readyCount ?? 0) === 0) return "";
|
||||
return ` (call ${tb.index + 1})`;
|
||||
}
|
||||
|
||||
/**
|
||||
* "· 2 ready" tail that answers "how many tool calls have finished
|
||||
* streaming so far this turn?" — user feedback for multi-file turns
|
||||
* where the response takes 10–30s to stream. Hidden until readyCount
|
||||
* > 0 so single-call turns aren't cluttered.
|
||||
*/
|
||||
function formatReadyTail(tb: { readyCount?: number } | undefined): string {
|
||||
const n = tb?.readyCount ?? 0;
|
||||
if (n <= 0) return "";
|
||||
return ` · ${n} ready`;
|
||||
}
|
||||
|
||||
function lastLine(s: string, maxChars: number): string {
|
||||
const flat = s.replace(/\s+/g, " ").trim();
|
||||
if (!flat) return "";
|
||||
@@ -239,19 +743,18 @@ function lastLine(s: string, maxChars: number): string {
|
||||
function StatsLine({ stats }: { stats: TurnStats }) {
|
||||
const hit = (stats.cacheHitRatio * 100).toFixed(1);
|
||||
return (
|
||||
<Text dimColor>
|
||||
{" ↳ cache "}
|
||||
{hit}
|
||||
{"% · tokens "}
|
||||
{stats.usage.promptTokens}
|
||||
{"→"}
|
||||
{stats.usage.completionTokens}
|
||||
{" · $"}
|
||||
{stats.cost.toFixed(6)}
|
||||
</Text>
|
||||
<Box>
|
||||
<Text dimColor>▏ </Text>
|
||||
<Text dimColor>
|
||||
{"cache "}
|
||||
{hit}
|
||||
{"% · tokens "}
|
||||
{stats.usage.promptTokens}
|
||||
{" → "}
|
||||
{stats.usage.completionTokens}
|
||||
{" · $"}
|
||||
{stats.cost.toFixed(6)}
|
||||
</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
function truncate(s: string, max: number): string {
|
||||
return s.length <= max ? s : `${s.slice(0, max)}… (+${s.length - max} chars)`;
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
import { Box, Text } from "ink";
|
||||
import React from "react";
|
||||
import type { ApplyResult } from "../../code/edit-blocks.js";
|
||||
import type { EditMode } from "../../config.js";
|
||||
import type { JobRegistry } from "../../tools/jobs.js";
|
||||
import { useElapsedSeconds, useTick } from "./ticker.js";
|
||||
|
||||
export const SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
|
||||
|
||||
/**
|
||||
* Transient "what's happening now" row shown during silent phases
|
||||
* between the primary events — harvest round-trip, R1 thinking
|
||||
* about a tool result before the next streaming delta, forced
|
||||
* summary. Matches OngoingToolRow's visual language (braille
|
||||
* spinner + elapsed seconds) so the user's eyes track the same
|
||||
* spot regardless of which kind of wait it is.
|
||||
*/
|
||||
export function StatusRow({ text }: { text: string }) {
|
||||
const tick = useTick();
|
||||
const elapsed = useElapsedSeconds();
|
||||
return (
|
||||
<Box marginY={1}>
|
||||
<Text color="magenta">{SPINNER_FRAMES[tick % SPINNER_FRAMES.length]}</Text>
|
||||
<Text color="magenta">{` ${text}`}</Text>
|
||||
<Text dimColor>{` ${elapsed}s`}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* One-line bottom status bar showing the current edit mode, pending
|
||||
* queue size (review only), an undo hint (auto only / after /apply),
|
||||
* and the Shift+Tab nudge. Rendered immediately above PromptInput so
|
||||
* the mode is always in peripheral vision when the user's eyes are at
|
||||
* the prompt. Flashes briefly on mode change so Shift+Tab gives a
|
||||
* visible acknowledgment without the user having to scan the header.
|
||||
*
|
||||
* The plan-mode pill takes precedence — when plan mode is on, writes
|
||||
* are bounced regardless of edit mode, so surfacing it is more useful
|
||||
* than the review/auto toggle.
|
||||
*/
|
||||
export function ModeStatusBar({
|
||||
editMode,
|
||||
pendingCount,
|
||||
flash,
|
||||
planMode,
|
||||
undoArmed,
|
||||
jobs,
|
||||
}: {
|
||||
editMode: EditMode;
|
||||
pendingCount: number;
|
||||
flash: boolean;
|
||||
planMode: boolean;
|
||||
undoArmed: boolean;
|
||||
jobs?: JobRegistry;
|
||||
}) {
|
||||
// Subscribe to tick so the jobs count stays live — the registry is
|
||||
// mutated outside React, so we need a periodic repaint to catch it.
|
||||
// No-op when there's no registry (chat mode / tests).
|
||||
useTick();
|
||||
const running = jobs?.runningCount() ?? 0;
|
||||
const jobsTag =
|
||||
running > 0 ? (
|
||||
<Text color="yellow" bold>{` · ⏵ ${running} job${running === 1 ? "" : "s"}`}</Text>
|
||||
) : null;
|
||||
if (planMode) {
|
||||
return (
|
||||
<Box paddingX={1}>
|
||||
<Text color="red" bold inverse={flash}>
|
||||
{"▸ PLAN"}
|
||||
</Text>
|
||||
<Text dimColor>
|
||||
{" writes gated — submit_plan + approval required · /plan off to leave"}
|
||||
</Text>
|
||||
{jobsTag}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
const label = editMode === "auto" ? "AUTO" : "review";
|
||||
const color = editMode === "auto" ? "magenta" : "cyan";
|
||||
const mid =
|
||||
editMode === "auto"
|
||||
? undoArmed
|
||||
? "edits apply immediately · u = undo last batch"
|
||||
: "edits apply immediately · 5s undo window after each batch"
|
||||
: pendingCount > 0
|
||||
? `${pendingCount} queued · y = /apply · n = /discard`
|
||||
: "edits queue for review · y = /apply · n = /discard";
|
||||
const flip = editMode === "auto" ? "Shift+Tab → review" : "Shift+Tab → AUTO";
|
||||
return (
|
||||
<Box paddingX={1}>
|
||||
<Text color={color} bold inverse={flash}>
|
||||
{`▸ ${label}`}
|
||||
</Text>
|
||||
<Text dimColor>{` ${mid} · ${flip}`}</Text>
|
||||
{jobsTag}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* "Just auto-applied N edits — press u to undo" banner. Rendered below
|
||||
* the live rows after an auto-mode edit batch lands, visible for 5s.
|
||||
* `useTick` drives a crude live countdown so the user sees the window
|
||||
* shrinking. State cleanup (the banner disappearing) happens in the
|
||||
* parent's setTimeout — the component is purely display.
|
||||
*/
|
||||
export function UndoBanner({
|
||||
banner,
|
||||
}: {
|
||||
banner: { results: ApplyResult[]; expiresAt: number };
|
||||
}) {
|
||||
useTick();
|
||||
const remainingMs = Math.max(0, banner.expiresAt - Date.now());
|
||||
const remainingSec = Math.ceil(remainingMs / 1000);
|
||||
const ok = banner.results.filter((r) => r.status === "applied" || r.status === "created").length;
|
||||
const total = banner.results.length;
|
||||
return (
|
||||
<Box marginY={1} borderStyle="round" borderColor="magenta" paddingX={1}>
|
||||
<Text color="magenta" bold>
|
||||
{"✓ auto-applied "}
|
||||
</Text>
|
||||
<Text color="magenta">{`${ok}/${total} edit${total === 1 ? "" : "s"}`}</Text>
|
||||
<Text dimColor>{" · press "}</Text>
|
||||
<Text color="magenta" bold>
|
||||
{"u"}
|
||||
</Text>
|
||||
<Text dimColor>{" to undo ("}</Text>
|
||||
<Text color={remainingSec <= 1 ? "red" : "magenta"}>{`${remainingSec}s`}</Text>
|
||||
<Text dimColor>{")"}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Live one-line indicator for a running subagent. Sits below the
|
||||
* OngoingToolRow (the parent's tool dispatch row for `spawn_subagent`)
|
||||
* so the user sees both layers at once: outer "spawn_subagent
|
||||
* running…" + inner "⌬ subagent: <task> · iter N · 12.3s". Cleared
|
||||
* when the subagent ends; a one-line summary lands in historical.
|
||||
*/
|
||||
export function SubagentRow({
|
||||
activity,
|
||||
}: {
|
||||
activity: { task: string; iter: number; elapsedMs: number };
|
||||
}) {
|
||||
const tick = useTick();
|
||||
const seconds = (activity.elapsedMs / 1000).toFixed(1);
|
||||
return (
|
||||
<Box paddingLeft={2}>
|
||||
<Text color="magenta">{SPINNER_FRAMES[tick % SPINNER_FRAMES.length]}</Text>
|
||||
<Text color="magenta">{` ⌬ subagent: ${activity.task}`}</Text>
|
||||
<Text dimColor>{` · iter ${activity.iter} · ${seconds}s`}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Live spinner row while a tool call is in flight. Without this the
|
||||
* window between the model's `tool_calls` decision and the tool's
|
||||
* result (often seconds for a multi-KB `filesystem_edit_file`) looks
|
||||
* like the app has frozen — the streaming assistant display is
|
||||
* already cleared and the input is disabled, so there's nothing to
|
||||
* look at.
|
||||
*
|
||||
* Shows three signals: a braille spinner (liveness), an elapsed
|
||||
* timer in seconds (so "long" has a number attached), and a
|
||||
* per-tool summary of the most informative argument fields (path,
|
||||
* edits count, pattern, etc.). As of 0.4.8, MCP progress frames
|
||||
* (`notifications/progress`) land here too — bar + "n/N" when the
|
||||
* server reports a total, free-form message when not.
|
||||
*/
|
||||
export function OngoingToolRow({
|
||||
tool,
|
||||
progress,
|
||||
}: {
|
||||
tool: { name: string; args?: string };
|
||||
progress: { progress: number; total?: number; message?: string } | null;
|
||||
}) {
|
||||
const tick = useTick();
|
||||
const elapsed = useElapsedSeconds();
|
||||
const summary = summarizeToolArgs(tool.name, tool.args);
|
||||
return (
|
||||
<Box marginY={1} flexDirection="column">
|
||||
<Box>
|
||||
<Text color="cyan">{SPINNER_FRAMES[tick % SPINNER_FRAMES.length]}</Text>
|
||||
<Text color="yellow">{` tool<${tool.name}> running…`}</Text>
|
||||
<Text dimColor>{` ${elapsed}s`}</Text>
|
||||
</Box>
|
||||
{progress ? (
|
||||
<Box paddingLeft={2}>
|
||||
<Text color="cyan">{renderProgressLine(progress)}</Text>
|
||||
</Box>
|
||||
) : null}
|
||||
{summary ? (
|
||||
<Box paddingLeft={2}>
|
||||
<Text dimColor>{summary}</Text>
|
||||
</Box>
|
||||
) : null}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Render an MCP progress frame as a single line. When the server
|
||||
* reports `total`, show an ASCII progress bar + "n/total pct%";
|
||||
* otherwise just "progress" + optional message. Width is modest
|
||||
* so the line fits even in a narrow terminal.
|
||||
*/
|
||||
function renderProgressLine(p: { progress: number; total?: number; message?: string }): string {
|
||||
const msg = p.message ? ` ${p.message}` : "";
|
||||
if (p.total && p.total > 0) {
|
||||
const ratio = Math.max(0, Math.min(1, p.progress / p.total));
|
||||
const width = 20;
|
||||
const filled = Math.round(ratio * width);
|
||||
const bar = "█".repeat(filled) + "░".repeat(width - filled);
|
||||
const pct = (ratio * 100).toFixed(0);
|
||||
return `[${bar}] ${p.progress}/${p.total} ${pct}%${msg}`;
|
||||
}
|
||||
return `progress: ${p.progress}${msg}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Turn raw JSON tool arguments into a one-line human summary. For
|
||||
* common filesystem MCP tools we pull the actually-useful fields; for
|
||||
* anything else we fall back to a truncated raw string so the user
|
||||
* still sees *something* beyond the tool name.
|
||||
*
|
||||
* Match on suffix (e.g. `_read_file`) rather than exact name because
|
||||
* `bridgeMcpTools({ namePrefix: "filesystem_" })` prepends the server
|
||||
* namespace — tools arrive as `filesystem_read_file` in practice but
|
||||
* callers might wire up anonymous too.
|
||||
*/
|
||||
function summarizeToolArgs(name: string, args?: string): string {
|
||||
if (!args || args === "{}") return "";
|
||||
let parsed: Record<string, unknown>;
|
||||
try {
|
||||
parsed = JSON.parse(args) as Record<string, unknown>;
|
||||
} catch {
|
||||
// Unparseable JSON — show a head slice so user at least sees
|
||||
// what the model tried.
|
||||
return args.length > 80 ? `${args.slice(0, 80)}…` : args;
|
||||
}
|
||||
const hasSuffix = (s: string) => name === s || name.endsWith(`_${s}`);
|
||||
const path = typeof parsed.path === "string" ? parsed.path : undefined;
|
||||
if (hasSuffix("read_file")) {
|
||||
const head = typeof parsed.head === "number" ? `, head=${parsed.head}` : "";
|
||||
const tail = typeof parsed.tail === "number" ? `, tail=${parsed.tail}` : "";
|
||||
return `path: ${path ?? "?"}${head}${tail}`;
|
||||
}
|
||||
if (hasSuffix("write_file")) {
|
||||
const content = typeof parsed.content === "string" ? parsed.content : "";
|
||||
return `path: ${path ?? "?"} (${content.length} chars)`;
|
||||
}
|
||||
if (hasSuffix("edit_file")) {
|
||||
const edits = Array.isArray(parsed.edits) ? parsed.edits.length : 0;
|
||||
return `path: ${path ?? "?"} (${edits} edit${edits === 1 ? "" : "s"})`;
|
||||
}
|
||||
if (hasSuffix("list_directory") || hasSuffix("directory_tree")) {
|
||||
return `path: ${path ?? "?"}`;
|
||||
}
|
||||
if (hasSuffix("search_files")) {
|
||||
const pattern = typeof parsed.pattern === "string" ? parsed.pattern : "?";
|
||||
return `path: ${path ?? "?"} · pattern: ${pattern}`;
|
||||
}
|
||||
if (hasSuffix("move_file")) {
|
||||
const src = typeof parsed.source === "string" ? parsed.source : "?";
|
||||
const dst = typeof parsed.destination === "string" ? parsed.destination : "?";
|
||||
return `${src} → ${dst}`;
|
||||
}
|
||||
if (hasSuffix("get_file_info")) {
|
||||
return `path: ${path ?? "?"}`;
|
||||
}
|
||||
return args.length > 80 ? `${args.slice(0, 80)}…` : args;
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
/**
|
||||
* Modal-style picker shown when `mark_step_complete` pauses the loop
|
||||
* via `PlanCheckpointError`. Three choices:
|
||||
*
|
||||
* 1. Continue — push "Step X done, proceed." so the model starts
|
||||
* the next step on the next turn.
|
||||
* 2. Revise — open a feedback input; whatever the user types
|
||||
* becomes a synthetic "user feedback for remaining steps" message.
|
||||
* The model can then adjust its approach without starting the
|
||||
* whole plan over.
|
||||
* 3. Stop — push "User stopped the plan. Summarize what was
|
||||
* done." so the run ends cleanly rather than being abandoned.
|
||||
*
|
||||
* The ✓ step-progress scrollback row is pushed separately (by App.tsx
|
||||
* at checkpoint detection time), so this modal stays a tight picker —
|
||||
* no need to re-render the step body here.
|
||||
*/
|
||||
|
||||
import { Box, Text } from "ink";
|
||||
import React from "react";
|
||||
import type { PlanStep } from "../../tools/plan.js";
|
||||
import { PlanStepList, type StepStatus } from "./PlanStepList.js";
|
||||
import { SingleSelect } from "./Select.js";
|
||||
|
||||
export type CheckpointChoice = "continue" | "revise" | "stop";
|
||||
|
||||
export interface PlanCheckpointConfirmProps {
|
||||
stepId: string;
|
||||
title?: string;
|
||||
completed: number;
|
||||
total: number;
|
||||
/** Full step list from the approved plan, when available. */
|
||||
steps?: PlanStep[];
|
||||
/** Set of stepIds the model has marked complete so far. */
|
||||
completedStepIds?: Set<string>;
|
||||
onChoose: (choice: CheckpointChoice) => void;
|
||||
}
|
||||
|
||||
function PlanCheckpointConfirmInner({
|
||||
stepId,
|
||||
title,
|
||||
completed,
|
||||
total,
|
||||
steps,
|
||||
completedStepIds,
|
||||
onChoose,
|
||||
}: PlanCheckpointConfirmProps) {
|
||||
const label = title ? `${stepId} · ${title}` : stepId;
|
||||
const counter = total > 0 ? ` (${completed}/${total})` : "";
|
||||
const isLast = total > 0 && completed >= total;
|
||||
const statuses = buildStatusMap(steps, completedStepIds, stepId, isLast);
|
||||
return (
|
||||
<Box flexDirection="column" borderStyle="round" borderColor="green" paddingX={1} marginY={1}>
|
||||
<Box>
|
||||
<Text bold color="green">
|
||||
▸ checkpoint — step done
|
||||
</Text>
|
||||
<Text dimColor>{` ${label}${counter}`}</Text>
|
||||
</Box>
|
||||
{steps && steps.length > 0 ? (
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
<PlanStepList steps={steps} statuses={statuses} focusStepId={stepId} />
|
||||
</Box>
|
||||
) : null}
|
||||
<Box marginTop={1}>
|
||||
<SingleSelect
|
||||
initialValue={isLast ? "stop" : "continue"}
|
||||
items={[
|
||||
{
|
||||
value: "continue",
|
||||
label: "Continue — run the next step",
|
||||
hint: "Model resumes with the next step. Use this when the result looks right and you don't need to tweak the remaining plan.",
|
||||
},
|
||||
{
|
||||
value: "revise",
|
||||
label: "Revise — give feedback before the next step",
|
||||
hint: "Stay paused, type guidance (scope changes, skip steps, alternative approach). The model adjusts the remaining plan based on your message.",
|
||||
},
|
||||
{
|
||||
value: "stop",
|
||||
label: "Stop — end the plan here",
|
||||
hint: "Model summarizes what was done and ends. Remaining steps are skipped.",
|
||||
},
|
||||
]}
|
||||
onSubmit={(v) => onChoose(v as CheckpointChoice)}
|
||||
onCancel={() => onChoose("stop")}
|
||||
footer="[↑↓] navigate · [Enter] select · [Esc] stop"
|
||||
/>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
export const PlanCheckpointConfirm = React.memo(PlanCheckpointConfirmInner);
|
||||
|
||||
/**
|
||||
* Derive a status map from the plan + completion set + current step.
|
||||
* The currently-just-finished step always renders as "done" even if
|
||||
* completedStepIds hasn't been flushed yet (it gets added in the
|
||||
* same render cycle, order not guaranteed). Steps ahead of the
|
||||
* cursor are "pending"; the next step after the current one isn't
|
||||
* marked "running" because nothing is actually running while the
|
||||
* picker is up — that belongs to the post-continue state.
|
||||
*/
|
||||
function buildStatusMap(
|
||||
steps: PlanStep[] | undefined,
|
||||
completedStepIds: Set<string> | undefined,
|
||||
currentStepId: string,
|
||||
isLast: boolean,
|
||||
): Map<string, StepStatus> {
|
||||
const map = new Map<string, StepStatus>();
|
||||
if (!steps) return map;
|
||||
for (const step of steps) {
|
||||
if (completedStepIds?.has(step.id) || step.id === currentStepId) {
|
||||
map.set(step.id, "done");
|
||||
} else {
|
||||
map.set(step.id, "pending");
|
||||
}
|
||||
}
|
||||
if (isLast) {
|
||||
// Every step is done; leave as "done" — no "running" overlay.
|
||||
}
|
||||
return map;
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
/**
|
||||
* 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.
|
||||
*
|
||||
* The plan BODY is NOT rendered inside this modal — App.tsx pushes it
|
||||
* into the Static scrollback as a `role: "plan"` display event the
|
||||
* moment submit_plan fires. That's a one-time markdown render into
|
||||
* permanent history, so the user reads the full proposal above and
|
||||
* the modal below stays a tight picker. The previous design (body
|
||||
* rendered inside the modal with an aggressive line clamp) left users
|
||||
* staring at "(25 more lines truncated)" and unable to approve safely.
|
||||
*/
|
||||
|
||||
import { Box, Text } from "ink";
|
||||
import React from "react";
|
||||
import type { PlanStep } from "../../tools/plan.js";
|
||||
import { PlanStepList } from "./PlanStepList.js";
|
||||
import { SingleSelect } from "./Select.js";
|
||||
|
||||
export type PlanConfirmChoice = "approve" | "refine" | "cancel";
|
||||
|
||||
export interface PlanConfirmProps {
|
||||
plan: string;
|
||||
steps?: PlanStep[];
|
||||
/** Optional human-friendly title from the model — surfaced in the header. */
|
||||
summary?: string;
|
||||
onChoose: (choice: PlanConfirmChoice) => void;
|
||||
projectRoot?: string;
|
||||
}
|
||||
|
||||
function PlanConfirmInner({ plan, steps, summary, onChoose }: PlanConfirmProps) {
|
||||
// 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 flexDirection="column">
|
||||
<Box>
|
||||
<Text bold color="cyan">
|
||||
▸ plan proposed (full text above) — approve / refine / cancel
|
||||
</Text>
|
||||
</Box>
|
||||
{summary ? (
|
||||
<Box>
|
||||
<Text color="cyan">{` ${summary}`}</Text>
|
||||
</Box>
|
||||
) : null}
|
||||
</Box>
|
||||
{hasOpenQuestions ? (
|
||||
<Box marginTop={1}>
|
||||
<Text color="yellow">
|
||||
▲ the plan flags open questions or risks — pick{" "}
|
||||
<Text bold>Refine / answer questions</Text> to write concrete answers before the model
|
||||
moves on.
|
||||
</Text>
|
||||
</Box>
|
||||
) : null}
|
||||
{steps && steps.length > 0 ? (
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
<PlanStepList steps={steps} />
|
||||
</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)}
|
||||
onCancel={() => onChoose("cancel")}
|
||||
footer="[↑↓] navigate · [Enter] select · [Esc] cancel"
|
||||
/>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
// React.memo: parent App re-renders every 120ms while the global ticker
|
||||
// is running (even with the live status rows hidden — context changes
|
||||
// propagate). Unless props change, skip re-rendering the heavy Markdown
|
||||
// subtree. Default shallow prop compare is fine — `plan` + `onChoose`
|
||||
// identity + `projectRoot` are the only fields that change.
|
||||
export const PlanConfirm = React.memo(PlanConfirmInner);
|
||||
@@ -0,0 +1,106 @@
|
||||
/**
|
||||
* 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";
|
||||
* checkpoint-revise = mid-execution pause, user is tweaking the
|
||||
* remaining plan after seeing a step's result; choice-custom = user
|
||||
* typed an off-list answer to an ask_choice branch. Drives the
|
||||
* header + hint text so users know what kind of message they're
|
||||
* writing.
|
||||
*/
|
||||
mode: "approve" | "refine" | "checkpoint-revise" | "choice-custom";
|
||||
/** 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?"
|
||||
: mode === "checkpoint-revise"
|
||||
? "▸ revising — what should change before the next step?"
|
||||
: mode === "choice-custom"
|
||||
? "▸ custom answer — type whatever fits"
|
||||
: "▸ 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."
|
||||
: mode === "checkpoint-revise"
|
||||
? "Scope change, skip steps, alternative approach — the model will adjust the remaining plan based on this."
|
||||
: mode === "choice-custom"
|
||||
? "Free-form reply. The model reads it verbatim and proceeds — no need to match the listed options."
|
||||
: "Describe what's wrong or missing, or answer questions the plan raised.";
|
||||
const blankHint =
|
||||
mode === "approve"
|
||||
? " (Enter with blank = approve without extra instructions.)"
|
||||
: mode === "checkpoint-revise"
|
||||
? " (Enter with blank = continue with the current plan.)"
|
||||
: mode === "choice-custom"
|
||||
? " (Enter with blank = ask the model what you actually want.)"
|
||||
: " (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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
/**
|
||||
* Modal shown when the model proposes a plan revision via
|
||||
* `revise_plan`. Renders a step-level diff between the old remaining
|
||||
* tail and the new proposed tail:
|
||||
*
|
||||
* ●● ✓ step-2 · Wire middleware (kept, dim)
|
||||
* − ●●● ✗ step-3 · Migrate session cookies (removed, red)
|
||||
* + ●● ▶ step-3 · Skip cookie migration (added, green)
|
||||
* + ●● ▶ step-4 · Update cookie tests (added, green)
|
||||
*
|
||||
* Two buttons: Accept / Reject. Accept replaces the in-memory plan's
|
||||
* remaining steps with the new ones; Reject leaves the original plan
|
||||
* intact and lets the model continue. The picker's border is amber
|
||||
* to distinguish from the green checkpoint picker — revisions are a
|
||||
* different decision point, deserve a different visual lane.
|
||||
*/
|
||||
|
||||
import { Box, Text } from "ink";
|
||||
import React from "react";
|
||||
import type { PlanStep } from "../../tools/plan.js";
|
||||
import { SingleSelect } from "./Select.js";
|
||||
|
||||
export type ReviseChoice = "accept" | "reject";
|
||||
|
||||
export interface PlanReviseConfirmProps {
|
||||
reason: string;
|
||||
/** Remaining steps from the current plan (before this revision). */
|
||||
oldRemaining: PlanStep[];
|
||||
/** Remaining steps the model is proposing as a replacement. */
|
||||
newRemaining: PlanStep[];
|
||||
/** Optional updated plan summary. */
|
||||
summary?: string;
|
||||
onChoose: (choice: ReviseChoice) => void;
|
||||
}
|
||||
|
||||
interface DiffRow {
|
||||
kind: "kept" | "removed" | "added";
|
||||
step: PlanStep;
|
||||
}
|
||||
|
||||
function computeDiff(oldSteps: PlanStep[], newSteps: PlanStep[]): DiffRow[] {
|
||||
const oldIds = new Set(oldSteps.map((s) => s.id));
|
||||
const newIds = new Set(newSteps.map((s) => s.id));
|
||||
const rows: DiffRow[] = [];
|
||||
// Show removed (in old, not in new) first — preserve original order.
|
||||
for (const s of oldSteps) {
|
||||
if (!newIds.has(s.id)) rows.push({ kind: "removed", step: s });
|
||||
}
|
||||
// Then walk new list. Steps in both lists render as kept; new-only as added.
|
||||
for (const s of newSteps) {
|
||||
rows.push({ kind: oldIds.has(s.id) ? "kept" : "added", step: s });
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
function riskDots(risk: PlanStep["risk"]): {
|
||||
dots: string;
|
||||
color: "green" | "yellow" | "red" | "gray";
|
||||
} {
|
||||
switch (risk) {
|
||||
case "high":
|
||||
return { dots: "●●●", color: "red" };
|
||||
case "med":
|
||||
return { dots: "●● ", color: "yellow" };
|
||||
case "low":
|
||||
return { dots: "● ", color: "green" };
|
||||
default:
|
||||
return { dots: " ", color: "gray" };
|
||||
}
|
||||
}
|
||||
|
||||
function PlanReviseConfirmInner({
|
||||
reason,
|
||||
oldRemaining,
|
||||
newRemaining,
|
||||
summary,
|
||||
onChoose,
|
||||
}: PlanReviseConfirmProps) {
|
||||
const rows = computeDiff(oldRemaining, newRemaining);
|
||||
const removedCount = rows.filter((r) => r.kind === "removed").length;
|
||||
const addedCount = rows.filter((r) => r.kind === "added").length;
|
||||
const keptCount = rows.filter((r) => r.kind === "kept").length;
|
||||
return (
|
||||
<Box flexDirection="column" borderStyle="round" borderColor="yellow" paddingX={1} marginY={1}>
|
||||
<Box>
|
||||
<Text bold color="yellow">
|
||||
✏ plan revision proposed
|
||||
</Text>
|
||||
<Text dimColor>{` −${removedCount} +${addedCount} (${keptCount} kept)`}</Text>
|
||||
</Box>
|
||||
<Box marginTop={1}>
|
||||
<Text>{reason}</Text>
|
||||
</Box>
|
||||
{summary ? (
|
||||
<Box marginTop={1}>
|
||||
<Text dimColor>{`updated summary: ${summary}`}</Text>
|
||||
</Box>
|
||||
) : null}
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
{rows.map((row) => {
|
||||
const risk = riskDots(row.step.risk);
|
||||
const prefix = row.kind === "removed" ? "−" : row.kind === "added" ? "+" : " ";
|
||||
const prefixColor =
|
||||
row.kind === "removed" ? "red" : row.kind === "added" ? "green" : "gray";
|
||||
const dim = row.kind === "kept";
|
||||
const strike = row.kind === "removed";
|
||||
return (
|
||||
<Box key={`${row.kind}-${row.step.id}`}>
|
||||
<Text color={prefixColor} bold>
|
||||
{`${prefix} `}
|
||||
</Text>
|
||||
<Text color={risk.color} bold dimColor={dim}>
|
||||
{risk.dots}
|
||||
</Text>
|
||||
<Text dimColor={dim} strikethrough={strike}>
|
||||
{` ${row.step.id} · ${row.step.title}`}
|
||||
</Text>
|
||||
</Box>
|
||||
);
|
||||
})}
|
||||
</Box>
|
||||
<Box marginTop={1}>
|
||||
<SingleSelect
|
||||
initialValue="accept"
|
||||
items={[
|
||||
{
|
||||
value: "accept",
|
||||
label: "Accept revision — apply the new step list",
|
||||
hint: "Replaces the remaining plan with the proposed steps. Done steps are untouched.",
|
||||
},
|
||||
{
|
||||
value: "reject",
|
||||
label: "Reject — keep the original plan",
|
||||
hint: "Drops the proposal. Model continues with the original remaining steps.",
|
||||
},
|
||||
]}
|
||||
onSubmit={(v) => onChoose(v as ReviseChoice)}
|
||||
onCancel={() => onChoose("reject")}
|
||||
footer="[↑↓] navigate · [Enter] select · [Esc] reject"
|
||||
/>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
export const PlanReviseConfirm = React.memo(PlanReviseConfirmInner);
|
||||
@@ -0,0 +1,48 @@
|
||||
/**
|
||||
* Shared Ink block that renders a TypedPlanState. Used by the live chat
|
||||
* EventLog AND by the RecordView in replay/diff TUIs, so harvest output
|
||||
* looks identical live and on replay.
|
||||
*
|
||||
* Colors are semantic (not decorative):
|
||||
* - subgoals: cyan — structure / plan
|
||||
* - hypotheses: green — current beliefs (like assistant)
|
||||
* - uncertainties: yellow — attention required (like tool)
|
||||
* - rejected paths: red dim — ruled out (muted, like error-but-resolved)
|
||||
*
|
||||
* Only the label is colored + bold. The items themselves render in the
|
||||
* terminal's default foreground, so they stay readable on any background —
|
||||
* which is why the old single-magenta block was hard to see on dark themes.
|
||||
*/
|
||||
|
||||
import { Box, Text } from "ink";
|
||||
import React from "react";
|
||||
import type { TypedPlanState } from "../../harvest.js";
|
||||
|
||||
type FieldColor = "cyan" | "green" | "yellow" | "red";
|
||||
|
||||
export function PlanStateBlock({ planState }: { planState: TypedPlanState }) {
|
||||
const fields: Array<[string, string[], FieldColor, boolean]> = [];
|
||||
if (planState.subgoals.length) fields.push(["subgoals", planState.subgoals, "cyan", false]);
|
||||
if (planState.hypotheses.length)
|
||||
fields.push(["hypotheses", planState.hypotheses, "green", false]);
|
||||
if (planState.uncertainties.length)
|
||||
fields.push(["uncertainties", planState.uncertainties, "yellow", false]);
|
||||
if (planState.rejectedPaths.length)
|
||||
fields.push(["rejected", planState.rejectedPaths, "red", true]);
|
||||
if (fields.length === 0) return null;
|
||||
|
||||
return (
|
||||
<Box flexDirection="column" marginBottom={1}>
|
||||
{fields.map(([label, items, color, dim]) => (
|
||||
<Text key={label}>
|
||||
<Text color={color} bold dimColor={dim}>
|
||||
{"‹ "}
|
||||
{label}
|
||||
</Text>
|
||||
<Text dimColor>{` (${items.length})`}</Text>
|
||||
<Text>{`: ${items.join(" · ")}`}</Text>
|
||||
</Text>
|
||||
))}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
/**
|
||||
* Shared compact renderer for a plan's structured step list. Used by
|
||||
* PlanConfirm (on approval) and PlanCheckpointConfirm (mid-execution)
|
||||
* so the user always sees the same visual representation of the plan.
|
||||
*
|
||||
* Layout per step:
|
||||
*
|
||||
* ● ✓ step-1 · Extract tokens into a module
|
||||
* ●●▶ step-2 · Migrate session cookies
|
||||
* ●●● step-3 · Update tests
|
||||
*
|
||||
* The risk gutter (1–3 dots, green/yellow/red) is the signal the user
|
||||
* learns to scan: high-risk steps are what deserves review before
|
||||
* approve; low-risk is noise.
|
||||
*/
|
||||
|
||||
import { Box, Text } from "ink";
|
||||
import React from "react";
|
||||
import type { PlanStep, PlanStepRisk } from "../../tools/plan.js";
|
||||
|
||||
export type StepStatus = "pending" | "running" | "done" | "skipped";
|
||||
|
||||
export interface PlanStepListProps {
|
||||
steps: PlanStep[];
|
||||
/**
|
||||
* Map of stepId → status. Missing ids default to "pending" so a
|
||||
* plan just submitted (no completions yet) renders cleanly.
|
||||
*/
|
||||
statuses?: Map<string, StepStatus> | Record<string, StepStatus>;
|
||||
/**
|
||||
* Optional current step — rendered with a `›` gutter mark so the
|
||||
* user sees which one just completed / is about to run.
|
||||
*/
|
||||
focusStepId?: string;
|
||||
}
|
||||
|
||||
function riskDots(risk: PlanStep["risk"]): {
|
||||
dots: string;
|
||||
color: "green" | "yellow" | "red" | "gray";
|
||||
} {
|
||||
switch (risk) {
|
||||
case "high":
|
||||
return { dots: "●●●", color: "red" };
|
||||
case "med":
|
||||
return { dots: "●● ", color: "yellow" };
|
||||
case "low":
|
||||
return { dots: "● ", color: "green" };
|
||||
default:
|
||||
return { dots: " ", color: "gray" };
|
||||
}
|
||||
}
|
||||
|
||||
function statusGlyph(status: StepStatus): {
|
||||
glyph: string;
|
||||
color: "green" | "cyan" | "gray" | "yellow";
|
||||
} {
|
||||
switch (status) {
|
||||
case "done":
|
||||
return { glyph: "✓", color: "green" };
|
||||
case "running":
|
||||
return { glyph: "▶", color: "cyan" };
|
||||
case "skipped":
|
||||
return { glyph: "—", color: "gray" };
|
||||
default:
|
||||
return { glyph: " ", color: "yellow" };
|
||||
}
|
||||
}
|
||||
|
||||
function getStatus(stepId: string, statuses: PlanStepListProps["statuses"]): StepStatus {
|
||||
if (!statuses) return "pending";
|
||||
if (statuses instanceof Map) {
|
||||
return statuses.get(stepId) ?? "pending";
|
||||
}
|
||||
return statuses[stepId] ?? "pending";
|
||||
}
|
||||
|
||||
function PlanStepListInner({ steps, statuses, focusStepId }: PlanStepListProps) {
|
||||
if (steps.length === 0) return null;
|
||||
const hasAnyRisk = steps.some((s) => s.risk !== undefined);
|
||||
const doneCount = Array.from({ length: steps.length }, (_, i) =>
|
||||
getStatus(steps[i]!.id, statuses),
|
||||
).filter((s) => s === "done").length;
|
||||
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
<Box>
|
||||
<Text dimColor>
|
||||
{`${steps.length} step${steps.length === 1 ? "" : "s"}`}
|
||||
{doneCount > 0 ? ` · ${doneCount} done` : ""}
|
||||
{hasAnyRisk ? " · risk: " : ""}
|
||||
</Text>
|
||||
{hasAnyRisk ? <RiskLegend /> : null}
|
||||
</Box>
|
||||
<Box flexDirection="column" marginTop={1}>
|
||||
{steps.map((step) => {
|
||||
const status = getStatus(step.id, statuses);
|
||||
const focus = focusStepId === step.id;
|
||||
const risk = riskDots(step.risk);
|
||||
const glyph = statusGlyph(status);
|
||||
const titleDim = status === "done" || status === "skipped";
|
||||
return (
|
||||
<Box key={step.id}>
|
||||
<Text color={focus ? "cyan" : "gray"} bold={focus}>
|
||||
{focus ? "› " : " "}
|
||||
</Text>
|
||||
<Text color={risk.color} bold>
|
||||
{risk.dots}
|
||||
</Text>
|
||||
<Text color={glyph.color} bold>
|
||||
{` ${glyph.glyph} `}
|
||||
</Text>
|
||||
<Text dimColor={titleDim}>{`${step.id} · ${step.title}`}</Text>
|
||||
</Box>
|
||||
);
|
||||
})}
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
function RiskLegend() {
|
||||
return (
|
||||
<Box>
|
||||
<Text color="green">●</Text>
|
||||
<Text dimColor> low </Text>
|
||||
<Text color="yellow">●●</Text>
|
||||
<Text dimColor> med </Text>
|
||||
<Text color="red">●●●</Text>
|
||||
<Text dimColor> high</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
export const PlanStepList = React.memo(PlanStepListInner);
|
||||
|
||||
export function riskOf(step: PlanStep): PlanStepRisk | undefined {
|
||||
return step.risk;
|
||||
}
|
||||
+515
-19
@@ -1,6 +1,38 @@
|
||||
import { Box, Text } from "ink";
|
||||
import TextInput from "ink-text-input";
|
||||
import React from "react";
|
||||
import { Box, Text, useInput, useStdout } from "ink";
|
||||
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React as a runtime value (classic transform compiles JSX to React.createElement)
|
||||
import React, { useRef, useState } from "react";
|
||||
import { type MultilineKey, lineAndColumn, processMultilineKey } from "./multiline-keys.js";
|
||||
import {
|
||||
PASTE_SENTINEL_RANGE,
|
||||
type PasteEntry,
|
||||
decodePasteSentinel,
|
||||
encodePasteSentinel,
|
||||
expandPasteSentinels,
|
||||
formatBytesShort,
|
||||
listPasteIdsInBuffer,
|
||||
makePasteEntry,
|
||||
} from "./paste-sentinels.js";
|
||||
import { useTick } from "./ticker.js";
|
||||
|
||||
/**
|
||||
* DECSET 2004 (bracketed paste) markers. The terminal sends these
|
||||
* around every paste action when bracketed-paste mode is enabled
|
||||
* (App.tsx writes the enable sequence at mount). Surface as exact
|
||||
* literal byte strings so we can locate them in `input` regardless
|
||||
* of how stdin chunks the surrounding bytes.
|
||||
*/
|
||||
const PASTE_START_MARKER = "\u001b[200~";
|
||||
const PASTE_END_MARKER = "\u001b[201~";
|
||||
/**
|
||||
* Merge-fallback window for terminals that strip bracketed-paste
|
||||
* markers (Windows PowerShell + ConPTY + Ink eats `\x1b[200~`).
|
||||
* One Ctrl+V arrives as N chunks 1-5ms apart; we collapse them by
|
||||
* checking arrival time + that the previous sentinel is still at
|
||||
* cursor-1 (no typing happened). 30ms is well below the ~100ms
|
||||
* minimum a human can release+repress Ctrl+V, so deliberate
|
||||
* back-to-back pastes never falsely merge.
|
||||
*/
|
||||
const PASTE_MERGE_WINDOW_MS = 30;
|
||||
|
||||
export interface PromptInputProps {
|
||||
value: string;
|
||||
@@ -8,13 +40,27 @@ export interface PromptInputProps {
|
||||
onSubmit: (v: string) => void;
|
||||
disabled?: boolean;
|
||||
placeholder?: string;
|
||||
/**
|
||||
* History recall. Fired when ↑/↓ hits a buffer boundary (empty
|
||||
* buffer, or cursor already at the first/last line of a multi-line
|
||||
* buffer). Parent walks its prompt history and swaps the value via
|
||||
* `onChange`. Absent → keys are consumed silently.
|
||||
*/
|
||||
onHistoryPrev?: () => void;
|
||||
onHistoryNext?: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep `<TextInput>` mounted at all times and use its `focus` prop to gate
|
||||
* input. Conditionally rendering it (mount / unmount between turns) loses
|
||||
* the stdin raw-mode claim on some terminals, which silently drops
|
||||
* keystrokes after the first turn finishes.
|
||||
* Input box with real cursor support. ←/→ move one column, ↑/↓ move
|
||||
* across lines in multi-line buffers, Ctrl+A / Ctrl+E jump to
|
||||
* start/end of the current line. Backspace deletes before cursor,
|
||||
* Delete deletes under cursor. Multi-line composition via Ctrl+J,
|
||||
* Shift+Enter, or bash-style `\<Enter>`.
|
||||
*
|
||||
* Cursor state lives locally. When the parent replaces `value` out
|
||||
* of band (history recall, slash completion, setup wizard) the
|
||||
* cursor jumps to end; the `lastLocalValueRef` guards distinguishes
|
||||
* that case from our own edits.
|
||||
*/
|
||||
export function PromptInput({
|
||||
value,
|
||||
@@ -22,22 +68,472 @@ export function PromptInput({
|
||||
onSubmit,
|
||||
disabled,
|
||||
placeholder,
|
||||
onHistoryPrev,
|
||||
onHistoryNext,
|
||||
}: PromptInputProps) {
|
||||
const [cursor, setCursor] = useState(value.length);
|
||||
// Paste registry. Maps sentinel id → original paste content. Each
|
||||
// entry is keyed by the codepoint stored in the buffer string.
|
||||
// Lives in a ref because rendering doesn't depend on identity —
|
||||
// mutating the map in-place is fine, the per-keystroke render
|
||||
// reads the current state directly. `nextPasteIdRef` wraps modulo
|
||||
// PASTE_SENTINEL_RANGE; collisions are rare in practice (256 slots,
|
||||
// typical session has <10 pastes).
|
||||
const pastesRef = useRef<Map<number, PasteEntry>>(new Map());
|
||||
const nextPasteIdRef = useRef<number>(0);
|
||||
// Bracketed-paste accumulator. When a paste begins, the terminal
|
||||
// sends `\x1b[200~`; when it ends, `\x1b[201~`. We accumulate
|
||||
// everything between markers into ONE entry. Works on terminals
|
||||
// that pass markers through to Ink intact (iTerm, kitty, alacritty,
|
||||
// most modern terminals on macOS/Linux). Doesn't work on Windows
|
||||
// PowerShell+ConPTY where Ink's parse-keypress eats the markers
|
||||
// before we see them — fallback below covers that case.
|
||||
// null = not currently inside a paste; string = accumulating.
|
||||
const pasteAccumRef = useRef<string | null>(null);
|
||||
// Tight time-window merge fallback. When bracketed-paste markers
|
||||
// don't reach us (Ink ate them, terminal didn't send them, etc.),
|
||||
// a single user paste arrives as N stdin chunks 1-5ms apart, and
|
||||
// each chunk on its own looks like a paste burst (multi-line
|
||||
// content). Without merging the user gets four `[paste #N]`
|
||||
// placeholders for one Ctrl+V. With a 30ms window + a guard that
|
||||
// the previous sentinel is still right at cursor-1 (no typing
|
||||
// happened in between), chunks of one paste collapse into one
|
||||
// entry. The window is below human reaction time for double-
|
||||
// pasting (Ctrl+V release → re-press takes 100ms+), so two
|
||||
// deliberate pastes never falsely merge.
|
||||
const lastPasteRef = useRef<{ id: number; at: number } | null>(null);
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
// Synchronous mirror of `cursor` for the same reason. When two
|
||||
// useInput firings happen in the same React tick (PowerShell+Ink
|
||||
// emits useInput twice per stdin chunk), the second fire's
|
||||
// closure still sees the stale `cursor` from before the first
|
||||
// fire's setCursor took effect. Reading from a ref we update
|
||||
// synchronously inside `registerPaste` lets the second fire's
|
||||
// merge guard see the just-inserted sentinel at cursor-1.
|
||||
const cursorRef = useRef(cursor);
|
||||
cursorRef.current = cursor;
|
||||
|
||||
// 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;
|
||||
|
||||
// Helper: register an accumulated paste blob and insert its
|
||||
// sentinel into the buffer at the current cursor. If the previous
|
||||
// paste's sentinel is still at cursor-1 AND we're inside the
|
||||
// sub-human-reaction merge window, append to that entry instead
|
||||
// of creating a new sentinel — this collapses chunks of one
|
||||
// user paste action that arrived as multiple stdin reads (the
|
||||
// PowerShell+ConPTY+Ink case where bracketed-paste markers got
|
||||
// eaten upstream).
|
||||
const registerPaste = (content: string) => {
|
||||
// Read from refs, NOT from closure variables. PowerShell+Ink
|
||||
// fires useInput twice per stdin chunk; both fires close over
|
||||
// the same stale `value` and `cursor` from React state. Refs
|
||||
// get updated synchronously below, so the second fire sees the
|
||||
// just-inserted sentinel at cursor-1 and the merge guard fires
|
||||
// correctly. This was the core reason a single Ctrl+V kept
|
||||
// producing four `[paste #N]` placeholders.
|
||||
const v = lastLocalValueRef.current;
|
||||
const c = cursorRef.current;
|
||||
const now = Date.now();
|
||||
const last = lastPasteRef.current;
|
||||
const prevChar = c > 0 ? v[c - 1] : null;
|
||||
const prevId = prevChar ? decodePasteSentinel(prevChar) : null;
|
||||
const canMerge =
|
||||
last !== null &&
|
||||
prevId === last.id &&
|
||||
now - last.at < PASTE_MERGE_WINDOW_MS &&
|
||||
pastesRef.current.has(last.id);
|
||||
if (canMerge && last) {
|
||||
const existing = pastesRef.current.get(last.id);
|
||||
if (existing) {
|
||||
const merged = existing.content + content;
|
||||
pastesRef.current.set(last.id, makePasteEntry(last.id, merged));
|
||||
lastPasteRef.current = { id: last.id, at: now };
|
||||
return;
|
||||
}
|
||||
}
|
||||
const id = nextPasteIdRef.current % PASTE_SENTINEL_RANGE;
|
||||
nextPasteIdRef.current = id + 1;
|
||||
pastesRef.current.set(id, makePasteEntry(id, content));
|
||||
const sentinel = encodePasteSentinel(id);
|
||||
const next = v.slice(0, c) + sentinel + v.slice(c);
|
||||
// Update refs synchronously so the SECOND useInput fire (same
|
||||
// React tick) sees the new buffer + cursor. Then schedule the
|
||||
// React state updates for re-render.
|
||||
lastLocalValueRef.current = next;
|
||||
cursorRef.current = c + 1;
|
||||
onChange(next);
|
||||
setCursor(c + 1);
|
||||
lastPasteRef.current = { id, at: now };
|
||||
};
|
||||
|
||||
useInput(
|
||||
(input, key) => {
|
||||
// Bracketed-paste accumulator. The terminal tells us EXACTLY
|
||||
// when a paste begins / ends via `\x1b[200~` / `\x1b[201~`.
|
||||
// Even when a 50KB paste arrives across many stdin reads,
|
||||
// the markers bracket the entire paste once. We accumulate
|
||||
// everything between them into a single sentinel — solving
|
||||
// the "one user paste shows up as N adjacent placeholders"
|
||||
// bug without resorting to time-based heuristics that would
|
||||
// wrongly merge two quick deliberate pastes. On terminals
|
||||
// that don't support DECSET 2004 (cmd.exe), markers never
|
||||
// appear and we fall back to the per-chunk pasteRequest
|
||||
// path below — chunks split visually but stay correct.
|
||||
if (pasteAccumRef.current !== null) {
|
||||
const endIdx = input.indexOf(PASTE_END_MARKER);
|
||||
if (endIdx === -1) {
|
||||
pasteAccumRef.current += input;
|
||||
return;
|
||||
}
|
||||
const content = pasteAccumRef.current + input.slice(0, endIdx);
|
||||
pasteAccumRef.current = null;
|
||||
registerPaste(content);
|
||||
return;
|
||||
}
|
||||
const startIdx = input.indexOf(PASTE_START_MARKER);
|
||||
if (startIdx !== -1) {
|
||||
const afterStart = input.slice(startIdx + PASTE_START_MARKER.length);
|
||||
const endIdx = afterStart.indexOf(PASTE_END_MARKER);
|
||||
if (endIdx !== -1) {
|
||||
// Whole paste in one read — register and we're done.
|
||||
registerPaste(afterStart.slice(0, endIdx));
|
||||
} else {
|
||||
// Open paste mode for subsequent useInput events.
|
||||
pasteAccumRef.current = afterStart;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const ke: MultilineKey = {
|
||||
input,
|
||||
return: key.return,
|
||||
shift: key.shift,
|
||||
ctrl: key.ctrl,
|
||||
meta: key.meta,
|
||||
backspace: key.backspace,
|
||||
delete: key.delete,
|
||||
tab: key.tab,
|
||||
upArrow: key.upArrow,
|
||||
downArrow: key.downArrow,
|
||||
leftArrow: key.leftArrow,
|
||||
rightArrow: key.rightArrow,
|
||||
escape: key.escape,
|
||||
pageUp: key.pageUp,
|
||||
pageDown: key.pageDown,
|
||||
};
|
||||
const action = processMultilineKey(value, cursor, ke);
|
||||
if (action.pasteRequest) {
|
||||
// No bracketed-paste markers were seen — terminal doesn't
|
||||
// support DECSET 2004, or Ink's key parser ate them. Fall
|
||||
// back to per-chunk paste registration. Two chunks of the
|
||||
// same big paste land as two placeholders; correctness
|
||||
// preserved, only visual cohesion lost.
|
||||
registerPaste(action.pasteRequest.content);
|
||||
return;
|
||||
}
|
||||
if (action.next !== null) {
|
||||
lastLocalValueRef.current = action.next;
|
||||
onChange(action.next);
|
||||
}
|
||||
if (action.cursor !== null) {
|
||||
setCursor(action.cursor);
|
||||
}
|
||||
if (action.submit) {
|
||||
// Expand sentinels back to real paste content before handing
|
||||
// the prompt up to the parent. The buffer carries placeholders
|
||||
// for display; the model needs the full text.
|
||||
const raw = action.submitValue ?? value;
|
||||
const expanded = expandPasteSentinels(raw, pastesRef.current);
|
||||
// GC unreachable paste entries — anything whose sentinel was
|
||||
// backspace'd out of the buffer before submit. Keeps the
|
||||
// registry from growing unbounded across many turns.
|
||||
const reachable = new Set(listPasteIdsInBuffer(raw));
|
||||
for (const id of pastesRef.current.keys()) {
|
||||
if (!reachable.has(id)) pastesRef.current.delete(id);
|
||||
}
|
||||
onSubmit(expanded);
|
||||
}
|
||||
if (action.historyHandoff === "prev") onHistoryPrev?.();
|
||||
if (action.historyHandoff === "next") onHistoryNext?.();
|
||||
},
|
||||
{ isActive: !disabled },
|
||||
);
|
||||
|
||||
// Narrow-terminal mode: drop the `you ›` (6 col) prefix to a `›` (2
|
||||
// col) marker so the writable area on 80-col terminals reclaims 4
|
||||
// cols. Threshold of 90 keeps the friendly `you ›` on anything that
|
||||
// resembles a normal terminal; modern laptops tend to default to
|
||||
// 100+ cols, narrow ones (split panes, embedded shells) tend to be
|
||||
// <=90. Continuation indent shrinks proportionally so wrapped lines
|
||||
// still align under the prompt arrow.
|
||||
const { stdout } = useStdout();
|
||||
const cols = stdout?.columns ?? 80;
|
||||
const narrow = cols <= 90;
|
||||
const promptPrefix = narrow ? "› " : "you › ";
|
||||
const continuationIndent = narrow ? " " : " ";
|
||||
const placeholderActive = narrow
|
||||
? "type a message, or /command"
|
||||
: "type a message, or /command · [Shift+Enter] / [Ctrl+J] newline";
|
||||
const effectivePlaceholder = disabled
|
||||
? (placeholder ?? "…waiting for response…")
|
||||
: (placeholder ?? "type a message, or /command");
|
||||
: (placeholder ?? placeholderActive);
|
||||
|
||||
const lines = value.length > 0 ? value.split("\n") : [""];
|
||||
const borderColor = disabled ? "gray" : "cyan";
|
||||
const { line: cursorLine, col: cursorCol } = lineAndColumn(value, cursor);
|
||||
// For large buffers (e.g. a big paste), rendering every line
|
||||
// re-runs Ink's layout + terminal write on every keystroke. Each
|
||||
// keystroke touching 500 rendered lines flickers visibly on most
|
||||
// terminals. Collapse to HEAD + cursor-line + TAIL with a dim
|
||||
// `[… N lines hidden …]` marker. Edit position is still anywhere;
|
||||
// the visible cursor line follows the cursor into/out of the
|
||||
// collapsed region so the user never loses sight of what they're
|
||||
// typing. Submitted value is the FULL buffer — collapse is purely
|
||||
// visual.
|
||||
const renderItems = collapseLinesForDisplay(lines, cursorLine);
|
||||
// When the buffer is large enough to be collapsed, surface a dim
|
||||
// hint about the buffer-wide shortcuts. The user just pasted 500
|
||||
// lines; without this they have no idea PageUp/Ctrl+U exist and
|
||||
// ↑×500 is the only path back to the top.
|
||||
const showHugeBufferHints = lines.length > 20;
|
||||
|
||||
return (
|
||||
<Box borderStyle="round" borderColor={disabled ? "gray" : "cyan"} paddingX={1}>
|
||||
<Text bold color={disabled ? "gray" : "cyan"}>
|
||||
you ›{" "}
|
||||
</Text>
|
||||
<TextInput
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
onSubmit={onSubmit}
|
||||
focus={!disabled}
|
||||
placeholder={effectivePlaceholder}
|
||||
/>
|
||||
// Explicit `width={cols}` pins the Box to the exact terminal width.
|
||||
// Without it, Ink auto-flexes children — long CJK input (Chinese
|
||||
// chars are 2 cells wide) can overflow the terminal column count
|
||||
// and trigger Ink's eraseLines miscount, which leaves ghost top
|
||||
// borders stacking in scrollback every ticker tick. Same fix
|
||||
// StatsPanel applies for the header frame.
|
||||
<Box
|
||||
borderStyle="round"
|
||||
borderColor={borderColor}
|
||||
paddingX={1}
|
||||
flexDirection="column"
|
||||
width={cols}
|
||||
>
|
||||
{renderItems.map((item, renderIdx) => {
|
||||
if (item.kind === "skip") {
|
||||
return (
|
||||
// biome-ignore lint/suspicious/noArrayIndexKey: stable — skip markers are derived from a fixed-size window over `lines`
|
||||
<Box key={`skip-${renderIdx}`}>
|
||||
<Text dimColor>{continuationIndent}</Text>
|
||||
<Text
|
||||
dimColor
|
||||
>{`[… ${item.linesHidden} line${item.linesHidden === 1 ? "" : "s"} hidden — full content kept, submitted on Enter …]`}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
const line = item.line;
|
||||
const i = item.originalIndex;
|
||||
const isFirst = i === 0;
|
||||
const showPlaceholder = isFirst && value.length === 0;
|
||||
const isCursorLine = i === cursorLine;
|
||||
return (
|
||||
<Box key={`ln-${i}`}>
|
||||
{isFirst ? (
|
||||
<Text bold color={borderColor}>
|
||||
{promptPrefix}
|
||||
</Text>
|
||||
) : (
|
||||
<Text dimColor>{continuationIndent}</Text>
|
||||
)}
|
||||
{showPlaceholder ? (
|
||||
<>
|
||||
{isCursorLine && !disabled ? (
|
||||
<Text color={borderColor}>{showCursor ? "▌" : " "}</Text>
|
||||
) : null}
|
||||
<Text dimColor>{effectivePlaceholder}</Text>
|
||||
</>
|
||||
) : isCursorLine && !disabled ? (
|
||||
<LineWithCursor
|
||||
line={line}
|
||||
col={cursorCol}
|
||||
showCursor={showCursor}
|
||||
borderColor={borderColor}
|
||||
pastes={pastesRef.current}
|
||||
/>
|
||||
) : (
|
||||
<RenderLine line={line} pastes={pastesRef.current} />
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
})}
|
||||
{showHugeBufferHints && !disabled ? (
|
||||
<Box>
|
||||
<Text dimColor>{continuationIndent}</Text>
|
||||
<Text dimColor>
|
||||
{`[${lines.length} lines · PageUp/PageDown jump to top/bottom · Ctrl+U clear · Ctrl+W del word]`}
|
||||
</Text>
|
||||
</Box>
|
||||
) : null}
|
||||
{/* Disabled-state Esc hint kept inside the bordered Box so the
|
||||
live region's structure is one Box, not a `<>`-wrapped pair.
|
||||
The fragment shape was a structural change with no layout
|
||||
benefit — moving back here matches the simpler shape from
|
||||
before 0.7.2, which the duplicating-borders Ink quirk amplified. */}
|
||||
{disabled ? (
|
||||
<Box>
|
||||
<Text dimColor>{continuationIndent}</Text>
|
||||
<Text dimColor>[Esc] to stop</Text>
|
||||
</Box>
|
||||
) : null}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* One visual slot in the rendered prompt box. Either a real buffer
|
||||
* line (with its original index so the cursor / first-line prefix
|
||||
* still line up) or a "skip" marker summarizing hidden rows.
|
||||
*/
|
||||
type RenderItem =
|
||||
| { kind: "line"; line: string; originalIndex: number }
|
||||
| { kind: "skip"; linesHidden: number };
|
||||
|
||||
/**
|
||||
* Above this line count we stop rendering every line on every
|
||||
* keystroke — a 500-line paste would otherwise make Ink redraw
|
||||
* hundreds of rows per character typed, which is visibly janky.
|
||||
* Chosen empirically: under 20 lines the user is still visually
|
||||
* scanning the buffer; above that they're almost always looking
|
||||
* at a pasted blob that should be summarized.
|
||||
*/
|
||||
const COLLAPSE_THRESHOLD = 20;
|
||||
const COLLAPSE_HEAD_LINES = 3;
|
||||
const COLLAPSE_TAIL_LINES = 2;
|
||||
|
||||
export function collapseLinesForDisplay(lines: string[], cursorLine: number): RenderItem[] {
|
||||
if (lines.length <= COLLAPSE_THRESHOLD) {
|
||||
return lines.map((line, i) => ({ kind: "line" as const, line, originalIndex: i }));
|
||||
}
|
||||
// Always show the first HEAD lines, the last TAIL lines, and
|
||||
// the cursor line if it falls in the collapsed middle. Union
|
||||
// the indices so head/cursor/tail overlap collapses cleanly.
|
||||
const keep = new Set<number>();
|
||||
for (let i = 0; i < COLLAPSE_HEAD_LINES && i < lines.length; i++) keep.add(i);
|
||||
for (let i = Math.max(0, lines.length - COLLAPSE_TAIL_LINES); i < lines.length; i++) keep.add(i);
|
||||
if (cursorLine >= 0 && cursorLine < lines.length) keep.add(cursorLine);
|
||||
const sorted = [...keep].sort((a, b) => a - b);
|
||||
const out: RenderItem[] = [];
|
||||
let prev = -1;
|
||||
for (const idx of sorted) {
|
||||
if (idx - prev > 1) {
|
||||
out.push({ kind: "skip", linesHidden: idx - prev - 1 });
|
||||
}
|
||||
out.push({ kind: "line", line: lines[idx] ?? "", originalIndex: idx });
|
||||
prev = idx;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Render a buffer line with paste sentinels expanded into magenta
|
||||
* `[paste #N · …]` placeholder blocks. Used for non-cursor lines and
|
||||
* for the prefix / suffix segments around the cursor on the cursor
|
||||
* line.
|
||||
*
|
||||
* Each codepoint is emitted as either:
|
||||
* - text: accumulated in `buf`, flushed when a sentinel or the end
|
||||
* of the line is reached.
|
||||
* - placeholder block: a styled `[paste #N · 3337l · 184KB]` Text.
|
||||
*
|
||||
* No layout magic — the emitted segments sit inline in the parent
|
||||
* Box's row, just like plain text.
|
||||
*/
|
||||
function RenderLine({
|
||||
line,
|
||||
pastes,
|
||||
inverse,
|
||||
}: {
|
||||
line: string;
|
||||
pastes: ReadonlyMap<number, PasteEntry>;
|
||||
inverse?: boolean;
|
||||
}) {
|
||||
const segments: React.ReactNode[] = [];
|
||||
let buf = "";
|
||||
let segIdx = 0;
|
||||
const flushBuf = () => {
|
||||
if (buf.length === 0) return;
|
||||
segments.push(
|
||||
<Text key={`t-${segIdx++}`} inverse={inverse}>
|
||||
{buf}
|
||||
</Text>,
|
||||
);
|
||||
buf = "";
|
||||
};
|
||||
for (let i = 0; i < line.length; i++) {
|
||||
const ch = line[i]!;
|
||||
const id = decodePasteSentinel(ch);
|
||||
if (id === null) {
|
||||
buf += ch;
|
||||
continue;
|
||||
}
|
||||
flushBuf();
|
||||
const entry = pastes.get(id);
|
||||
const label = entry
|
||||
? `[paste #${id + 1} · ${entry.lineCount}l · ${formatBytesShort(entry.charCount)}]`
|
||||
: `[paste #${id + 1} · (missing)]`;
|
||||
segments.push(
|
||||
<Text key={`p-${segIdx++}`} color="magenta" bold inverse={inverse}>
|
||||
{label}
|
||||
</Text>,
|
||||
);
|
||||
}
|
||||
flushBuf();
|
||||
if (segments.length === 0) {
|
||||
// Empty line — return a single empty Text so Ink still renders a
|
||||
// row. Otherwise this Box collapses to zero height.
|
||||
return <Text> </Text>;
|
||||
}
|
||||
return <>{segments}</>;
|
||||
}
|
||||
|
||||
function LineWithCursor({
|
||||
line,
|
||||
col,
|
||||
showCursor,
|
||||
borderColor,
|
||||
pastes,
|
||||
}: {
|
||||
line: string;
|
||||
col: number;
|
||||
showCursor: boolean;
|
||||
borderColor: "cyan" | "gray";
|
||||
pastes: ReadonlyMap<number, PasteEntry>;
|
||||
}) {
|
||||
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 (
|
||||
<>
|
||||
<RenderLine line={before} pastes={pastes} />
|
||||
<Text color={borderColor}>{showCursor ? "▌" : " "}</Text>
|
||||
</>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<>
|
||||
<RenderLine line={before} pastes={pastes} />
|
||||
<RenderLine line={atCursor} pastes={pastes} inverse={showCursor} />
|
||||
<RenderLine line={after} pastes={pastes} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -11,6 +11,7 @@
|
||||
import { Box, Text } from "ink";
|
||||
import React from "react";
|
||||
import type { TranscriptRecord } from "../../transcript.js";
|
||||
import { PlanStateBlock } from "./PlanStateBlock.js";
|
||||
|
||||
export interface RecordViewProps {
|
||||
rec: TranscriptRecord;
|
||||
@@ -27,12 +28,18 @@ export function RecordView({ rec, compact = false }: RecordViewProps) {
|
||||
const toolContentMax = compact ? 200 : 400;
|
||||
|
||||
if (rec.role === "user") {
|
||||
// Continuation indent of 6 spaces matches the `you › ` prefix width
|
||||
// so wrapped multi-line user messages align under the body text
|
||||
// instead of jumping to column 0.
|
||||
const content = rec.content.includes("\n")
|
||||
? rec.content.split("\n").join("\n ")
|
||||
: rec.content;
|
||||
return (
|
||||
<Box marginTop={1}>
|
||||
<Text bold color="cyan">
|
||||
you ›{" "}
|
||||
</Text>
|
||||
<Text>{rec.content}</Text>
|
||||
<Text>{content}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -51,6 +58,7 @@ export function RecordView({ rec, compact = false }: RecordViewProps) {
|
||||
) : null}
|
||||
{rec.usage ? <CacheBadge usage={rec.usage} /> : null}
|
||||
</Box>
|
||||
{rec.planState ? <PlanStateBlock planState={rec.planState} /> : null}
|
||||
{rec.content ? (
|
||||
<Text>{rec.content}</Text>
|
||||
) : (
|
||||
|
||||
@@ -52,9 +52,14 @@ export function ReplayApp({ meta, pages }: ReplayAppProps) {
|
||||
const summary = {
|
||||
turns: cumStats.turns,
|
||||
totalCostUsd: cumStats.totalCostUsd,
|
||||
totalInputCostUsd: cumStats.totalInputCostUsd,
|
||||
totalOutputCostUsd: cumStats.totalOutputCostUsd,
|
||||
claudeEquivalentUsd: cumStats.claudeEquivalentUsd,
|
||||
savingsVsClaudePct: cumStats.savingsVsClaudePct,
|
||||
cacheHitRatio: cumStats.cacheHitRatio,
|
||||
// Replay is read-only — no live last-turn prompt tokens to show.
|
||||
lastPromptTokens: 0,
|
||||
lastTurnCostUsd: 0,
|
||||
};
|
||||
|
||||
const prefixHash =
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
/**
|
||||
* Minimal arrow-key list components for Ink — single-select and
|
||||
* multi-select. No external deps beyond Ink's `useInput`.
|
||||
*
|
||||
* Why hand-roll: `ink-select-input` exists, but it defaults to
|
||||
* Enter-only interaction (no space-to-toggle for multi-select), doesn't
|
||||
* expose the "hint / footer" slot we want under each item, and would be
|
||||
* another dep for ~60 lines of UI code. Reasonix already has one React
|
||||
* rendering quirk bundled (`ink-text-input`); adding more is low value.
|
||||
*/
|
||||
|
||||
import { Box, Text, useInput } from "ink";
|
||||
import React, { useState } from "react";
|
||||
|
||||
export interface SelectItem<V extends string = string> {
|
||||
/** Stable identifier — returned to caller on submit. */
|
||||
value: V;
|
||||
/** First-row label. */
|
||||
label: string;
|
||||
/** Optional second row rendered dimmed. */
|
||||
hint?: string;
|
||||
/** If true, item is not selectable (rendered dimmed, skipped on nav). */
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
export interface SingleSelectProps<V extends string> {
|
||||
items: SelectItem<V>[];
|
||||
initialValue?: V;
|
||||
onSubmit: (value: V) => void;
|
||||
onCancel?: () => void;
|
||||
/**
|
||||
* Optional footer rendered dim beneath the list, e.g.
|
||||
* `"[↑↓] navigate · [Enter] select · [Esc] cancel"`. Makes keyboard
|
||||
* affordances discoverable — otherwise new users hit `y`/`n` and
|
||||
* wonder why nothing happens.
|
||||
*/
|
||||
footer?: string;
|
||||
}
|
||||
|
||||
export function SingleSelect<V extends string>({
|
||||
items,
|
||||
initialValue,
|
||||
onSubmit,
|
||||
onCancel,
|
||||
footer,
|
||||
}: SingleSelectProps<V>) {
|
||||
const initialIndex = Math.max(
|
||||
0,
|
||||
items.findIndex((i) => i.value === initialValue && !i.disabled),
|
||||
);
|
||||
const [index, setIndex] = useState(initialIndex === -1 ? 0 : initialIndex);
|
||||
|
||||
useInput((_input, key) => {
|
||||
if (key.upArrow) {
|
||||
setIndex((i) => findNextEnabled(items, i, -1));
|
||||
} else if (key.downArrow) {
|
||||
setIndex((i) => findNextEnabled(items, i, +1));
|
||||
} else if (key.return) {
|
||||
const chosen = items[index];
|
||||
if (chosen && !chosen.disabled) onSubmit(chosen.value);
|
||||
} else if (key.escape && onCancel) {
|
||||
onCancel();
|
||||
}
|
||||
});
|
||||
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
{items.map((item, i) => (
|
||||
<SelectRow
|
||||
key={item.value}
|
||||
item={item}
|
||||
active={i === index}
|
||||
marker={i === index ? "▸" : " "}
|
||||
/>
|
||||
))}
|
||||
{footer ? (
|
||||
<Box marginTop={1}>
|
||||
<Text dimColor>{footer}</Text>
|
||||
</Box>
|
||||
) : null}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
export interface MultiSelectProps<V extends string> {
|
||||
items: SelectItem<V>[];
|
||||
initialSelected?: V[];
|
||||
onSubmit: (values: V[]) => void;
|
||||
onCancel?: () => void;
|
||||
/** Footer hint under the list — e.g. "[Space] toggle · [Enter] confirm". */
|
||||
footer?: string;
|
||||
}
|
||||
|
||||
export function MultiSelect<V extends string>({
|
||||
items,
|
||||
initialSelected = [],
|
||||
onSubmit,
|
||||
onCancel,
|
||||
footer,
|
||||
}: MultiSelectProps<V>) {
|
||||
const [index, setIndex] = useState(() => {
|
||||
const first = items.findIndex((i) => !i.disabled);
|
||||
return first === -1 ? 0 : first;
|
||||
});
|
||||
const [selected, setSelected] = useState<Set<V>>(new Set(initialSelected));
|
||||
|
||||
useInput((input, key) => {
|
||||
if (key.upArrow) {
|
||||
setIndex((i) => findNextEnabled(items, i, -1));
|
||||
} else if (key.downArrow) {
|
||||
setIndex((i) => findNextEnabled(items, i, +1));
|
||||
} else if (input === " ") {
|
||||
const item = items[index];
|
||||
if (!item || item.disabled) return;
|
||||
setSelected((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (next.has(item.value)) next.delete(item.value);
|
||||
else next.add(item.value);
|
||||
return next;
|
||||
});
|
||||
} else if (key.return) {
|
||||
// Preserve catalog order rather than insertion order, so reruns
|
||||
// produce the same spec list for the same checkbox set — makes the
|
||||
// `config.json` diff trivially stable.
|
||||
const ordered = items.filter((i) => selected.has(i.value)).map((i) => i.value);
|
||||
onSubmit(ordered);
|
||||
} else if (key.escape && onCancel) {
|
||||
onCancel();
|
||||
}
|
||||
});
|
||||
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
{items.map((item, i) => {
|
||||
const checked = selected.has(item.value);
|
||||
const marker = checked ? "[x]" : "[ ]";
|
||||
return (
|
||||
<SelectRow
|
||||
key={item.value}
|
||||
item={item}
|
||||
active={i === index}
|
||||
marker={`${i === index ? "▸" : " "} ${marker}`}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
{footer ? (
|
||||
<Box marginTop={1}>
|
||||
<Text dimColor>{footer}</Text>
|
||||
</Box>
|
||||
) : null}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------- internals ----------
|
||||
|
||||
function SelectRow<V extends string>({
|
||||
item,
|
||||
active,
|
||||
marker,
|
||||
}: {
|
||||
item: SelectItem<V>;
|
||||
active: boolean;
|
||||
marker: string;
|
||||
}) {
|
||||
const color = item.disabled ? "gray" : active ? "cyan" : undefined;
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
<Box>
|
||||
<Text color={color}>
|
||||
{marker} {item.label}
|
||||
</Text>
|
||||
</Box>
|
||||
{item.hint ? (
|
||||
<Box paddingLeft={marker.length + 1}>
|
||||
<Text dimColor>{item.hint}</Text>
|
||||
</Box>
|
||||
) : null}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
function findNextEnabled<V extends string>(
|
||||
items: SelectItem<V>[],
|
||||
from: number,
|
||||
step: -1 | 1,
|
||||
): number {
|
||||
if (items.length === 0) return 0;
|
||||
let i = from;
|
||||
for (let tries = 0; tries < items.length; tries++) {
|
||||
i = (i + step + items.length) % items.length;
|
||||
if (!items[i]?.disabled) return i;
|
||||
}
|
||||
return from;
|
||||
}
|
||||
@@ -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>[↑↓] navigate · [Enter] select</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);
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
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;
|
||||
/**
|
||||
* Which tool is asking. `run_background` spawns via JobRegistry and
|
||||
* returns early; `run_command` (default) blocks until the process
|
||||
* exits. Shown as a hint in the modal so the user knows whether
|
||||
* approving will block the TUI or not.
|
||||
*/
|
||||
kind?: "run_command" | "run_background";
|
||||
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, kind, onChoose }: ShellConfirmProps) {
|
||||
const isBackground = kind === "run_background";
|
||||
return (
|
||||
<Box flexDirection="column" borderStyle="round" borderColor="red" paddingX={1} marginY={1}>
|
||||
<Box>
|
||||
<Text bold color="red">
|
||||
{isBackground
|
||||
? "▸ model wants to start a BACKGROUND process"
|
||||
: "▸ model wants to run a shell command"}
|
||||
</Text>
|
||||
</Box>
|
||||
{isBackground ? (
|
||||
<Box>
|
||||
<Text dimColor>
|
||||
{" (long-running: dev server / watcher; keeps running after approval, /kill to stop)"}
|
||||
</Text>
|
||||
</Box>
|
||||
) : null}
|
||||
<Box>
|
||||
<Text color="red" dimColor>
|
||||
{"──────────────────────────────────────────"}
|
||||
</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)}
|
||||
onCancel={() => onChoose("deny")}
|
||||
footer="[↑↓] navigate · [Enter] select · [Esc] deny"
|
||||
/>
|
||||
</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;
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
import { Box, Text } from "ink";
|
||||
// biome-ignore lint/style/useImportType: tsconfig.jsx = "react" needs React in value scope for JSX compilation
|
||||
import React from "react";
|
||||
import type { SlashCommandSpec } from "./slash.js";
|
||||
|
||||
export interface SlashArgPickerProps {
|
||||
/**
|
||||
* When set, render a picker with these matches (filter already
|
||||
* applied upstream). Null → not in picker mode; check `hintSpec`
|
||||
* for a usage hint instead.
|
||||
*/
|
||||
matches: readonly string[] | null;
|
||||
/** Highlighted row within `matches`. */
|
||||
selectedIndex: number;
|
||||
/**
|
||||
* Spec of the command the user is typing args for. Used to render
|
||||
* the header label ("/edit <file>") even when matches is empty or
|
||||
* the caller wants a hint instead of a picker.
|
||||
*/
|
||||
spec: SlashCommandSpec;
|
||||
/** What kind of arg guidance to render. */
|
||||
kind: "picker" | "hint";
|
||||
/** The user's partial input — shown in the "no matches" hint. */
|
||||
partial: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Argument-level picker for a slash command. Mirrors the visual
|
||||
* layout of SlashSuggestions / AtMentionSuggestions so the UI stays
|
||||
* consistent across all three picker surfaces.
|
||||
*/
|
||||
export function SlashArgPicker({
|
||||
matches,
|
||||
selectedIndex,
|
||||
spec,
|
||||
kind,
|
||||
partial,
|
||||
}: SlashArgPickerProps): React.ReactElement | null {
|
||||
// Hint mode: a single dim row explaining the argsHint + summary.
|
||||
if (kind === "hint") {
|
||||
return (
|
||||
<Box paddingX={1} marginTop={1}>
|
||||
<Text dimColor>
|
||||
{" "}
|
||||
<Text bold>/{spec.cmd}</Text>
|
||||
{spec.argsHint ? ` ${spec.argsHint}` : ""} — {spec.summary}
|
||||
</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
if (matches === null) return null;
|
||||
if (matches.length === 0) {
|
||||
return (
|
||||
<Box flexDirection="column" paddingX={1} marginTop={1}>
|
||||
<Text dimColor>
|
||||
{" "}
|
||||
<Text bold>/{spec.cmd}</Text>
|
||||
{spec.argsHint ? ` ${spec.argsHint}` : ""} — {spec.summary}
|
||||
</Text>
|
||||
<Text color="yellow"> no match for "{partial}" — keep typing, or Backspace to edit</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
const MAX = 8;
|
||||
const total = matches.length;
|
||||
const windowStart =
|
||||
total <= MAX ? 0 : Math.max(0, Math.min(selectedIndex - Math.floor(MAX / 2), total - MAX));
|
||||
const shown = matches.slice(windowStart, windowStart + MAX);
|
||||
const hiddenAbove = windowStart;
|
||||
const hiddenBelow = total - windowStart - shown.length;
|
||||
return (
|
||||
<Box flexDirection="column" paddingX={1} marginTop={1}>
|
||||
<Text dimColor>
|
||||
{" "}
|
||||
<Text bold>/{spec.cmd}</Text>
|
||||
{spec.argsHint ? ` ${spec.argsHint}` : ""} — {spec.summary}
|
||||
</Text>
|
||||
{hiddenAbove > 0 ? <Text dimColor> ↑ {hiddenAbove} more above</Text> : null}
|
||||
{shown.map((value, i) => (
|
||||
<ArgRow key={value} value={value} isSelected={windowStart + i === selectedIndex} />
|
||||
))}
|
||||
{hiddenBelow > 0 ? <Text dimColor> ↓ {hiddenBelow} more below</Text> : null}
|
||||
<Text dimColor> [↑↓] navigate · [Tab]/[Enter] pick</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
function ArgRow({ value, isSelected }: { value: string; isSelected: boolean }) {
|
||||
const marker = isSelected ? "▸" : " ";
|
||||
if (isSelected) {
|
||||
return (
|
||||
<Box>
|
||||
<Text bold color="cyan">
|
||||
{marker} {value}
|
||||
</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Box>
|
||||
<Text dimColor>
|
||||
{marker} {value}
|
||||
</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import { Box, Text } from "ink";
|
||||
// biome-ignore lint/style/useImportType: tsconfig.jsx = "react" needs React in value scope for JSX compilation
|
||||
import React from "react";
|
||||
import type { SlashCommandSpec } from "./slash.js";
|
||||
|
||||
export interface SlashSuggestionsProps {
|
||||
/**
|
||||
* Current matching suggestions, computed by the parent. `null` means
|
||||
* "not in slash-prefix mode" — render nothing. Empty array means "in
|
||||
* slash mode but no matches" — render the "no matches" hint.
|
||||
*/
|
||||
matches: SlashCommandSpec[] | null;
|
||||
/** Index (within `matches`) of the currently highlighted row. */
|
||||
selectedIndex: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Floating slash-command panel. Rendered below the input box when
|
||||
* the user is typing a `/…` prefix. Navigation state lives in the
|
||||
* parent (App.tsx owns `slashSelected`) so ↑/↓/Tab/Enter stay
|
||||
* consistent with the useInput handler. This component is pure
|
||||
* display: `matches` and `selectedIndex` come in, rows go out.
|
||||
*/
|
||||
export function SlashSuggestions({
|
||||
matches,
|
||||
selectedIndex,
|
||||
}: SlashSuggestionsProps): React.ReactElement | null {
|
||||
if (matches === null) return null;
|
||||
if (matches.length === 0) {
|
||||
return (
|
||||
<Box paddingX={1} marginTop={1}>
|
||||
<Text color="yellow">no slash command matches that prefix</Text>
|
||||
<Text dimColor> — Backspace to edit, or /help for the full list</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
// Limit rows so the suggestion list never dwarfs the rest of the
|
||||
// UI. Keep the currently-selected row in view by sliding the
|
||||
// window when the selection is near either edge.
|
||||
const MAX = 8;
|
||||
const total = matches.length;
|
||||
const windowStart =
|
||||
total <= MAX ? 0 : Math.max(0, Math.min(selectedIndex - Math.floor(MAX / 2), total - MAX));
|
||||
const shown = matches.slice(windowStart, windowStart + MAX);
|
||||
const hiddenAbove = windowStart;
|
||||
const hiddenBelow = total - windowStart - shown.length;
|
||||
return (
|
||||
<Box flexDirection="column" paddingX={1} marginTop={1}>
|
||||
{hiddenAbove > 0 ? <Text dimColor> ↑ {hiddenAbove} more above</Text> : null}
|
||||
{shown.map((spec, i) => (
|
||||
<SuggestionRow key={spec.cmd} spec={spec} isSelected={windowStart + i === selectedIndex} />
|
||||
))}
|
||||
{hiddenBelow > 0 ? <Text dimColor> ↓ {hiddenBelow} more below</Text> : null}
|
||||
<Text dimColor> [↑↓] navigate · [Tab]/[Enter] pick</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
function SuggestionRow({ spec, isSelected }: { spec: SlashCommandSpec; isSelected: boolean }) {
|
||||
const marker = isSelected ? "▸" : " ";
|
||||
const name = `/${spec.cmd}`;
|
||||
const argsSuffix = spec.argsHint ? ` ${spec.argsHint}` : "";
|
||||
// Selected row gets full cyan coloring so it pops out against the
|
||||
// dimmed others — mirrors the style GitHub Issues / Discord use
|
||||
// for focused dropdown rows.
|
||||
if (isSelected) {
|
||||
return (
|
||||
<Box>
|
||||
<Text bold color="cyan">
|
||||
{marker} {name.padEnd(12)}
|
||||
{argsSuffix.padEnd(16)}
|
||||
</Text>
|
||||
<Text color="cyan"> {spec.summary}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Box>
|
||||
<Text dimColor>
|
||||
{marker} {name.padEnd(12)}
|
||||
{argsSuffix.padEnd(16)} {spec.summary}
|
||||
</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
+495
-41
@@ -1,6 +1,55 @@
|
||||
import { Box, Text } from "ink";
|
||||
import { Box, Text, useStdout } from "ink";
|
||||
import React from "react";
|
||||
import type { EditMode } from "../../config.js";
|
||||
import { DEEPSEEK_CONTEXT_TOKENS, DEFAULT_CONTEXT_TOKENS } from "../../telemetry.js";
|
||||
import type { SessionSummary } from "../../telemetry.js";
|
||||
import { VERSION } from "../../version.js";
|
||||
import { useTick } from "./ticker.js";
|
||||
|
||||
/**
|
||||
* Cyan → blue → purple truecolor gradient for the REASONIX wordmark.
|
||||
* Each char gets its own hex color — terminals that support 24-bit
|
||||
* color (nearly all since 2016) render this as a smooth fade. Older
|
||||
* 256-color terminals snap to nearest; 8-color fall all the way back
|
||||
* to plain cyan via Ink's color pipeline, so the worst case is still
|
||||
* legible.
|
||||
*/
|
||||
const WORDMARK_STYLES: ReadonlyArray<{ ch: string; color: string; isLogo: boolean }> = [
|
||||
{ ch: "◈", color: "#5eead4", isLogo: true }, // teal — brand mark
|
||||
{ ch: " ", color: "#5eead4", isLogo: false },
|
||||
{ ch: "R", color: "#67e8f9", isLogo: false }, // cyan
|
||||
{ ch: "E", color: "#7dd3fc", isLogo: false }, // sky
|
||||
{ ch: "A", color: "#93c5fd", isLogo: false }, // blue
|
||||
{ ch: "S", color: "#a5b4fc", isLogo: false }, // indigo
|
||||
{ ch: "O", color: "#c4b5fd", isLogo: false }, // violet
|
||||
{ ch: "N", color: "#d8b4fe", isLogo: false }, // purple
|
||||
{ ch: "I", color: "#f0abfc", isLogo: false }, // fuchsia
|
||||
{ ch: "X", color: "#f0abfc", isLogo: false }, // fuchsia
|
||||
];
|
||||
|
||||
/**
|
||||
* Gradient-filled, animated app wordmark. The `◈` brand mark breathes
|
||||
* (bold on/off) once every ~1.6s when idle, ~600ms when the model is
|
||||
* working, so a glance at the top of the screen tells you immediately
|
||||
* whether the app is doing something. Letters' keys use the char+color
|
||||
* pair (not an index) so React state attaches to the glyph itself;
|
||||
* fine because WORDMARK_STYLES never reorders.
|
||||
*/
|
||||
function Wordmark({ busy }: { busy: boolean }) {
|
||||
const tick = useTick();
|
||||
// Slow pulse = 12 ticks (~1.4s). Busy pulse = 5 ticks (~600ms).
|
||||
const period = busy ? 5 : 12;
|
||||
const bright = Math.floor(tick / period) % 2 === 0;
|
||||
return (
|
||||
<Text>
|
||||
{WORDMARK_STYLES.map((c) => (
|
||||
<Text key={`${c.ch}-${c.color}`} color={c.color} bold={c.isLogo ? bright : true}>
|
||||
{c.ch}
|
||||
</Text>
|
||||
))}
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
|
||||
export interface StatsPanelProps {
|
||||
summary: SessionSummary;
|
||||
@@ -8,57 +57,462 @@ export interface StatsPanelProps {
|
||||
prefixHash: string;
|
||||
harvestOn?: boolean;
|
||||
branchBudget?: number;
|
||||
/**
|
||||
* Current `reasoning_effort` cap. Shown as a green "· max" / yellow
|
||||
* "· high" tag in the header so the user always sees which tier the
|
||||
* next turn will use. Absent/undefined hides the tag (e.g. before
|
||||
* the loop is constructed).
|
||||
*/
|
||||
reasoningEffort?: "high" | "max";
|
||||
/**
|
||||
* True when `reasonix code` is currently running in read-only Plan
|
||||
* Mode. Surfaced as a red "PLAN" tag in the panel header so the user
|
||||
* can tell at a glance that edits are gated behind submit_plan +
|
||||
* approval.
|
||||
*/
|
||||
planMode?: boolean;
|
||||
/**
|
||||
* Edit-gate mode. Surfaced as a small pill in the header so the user
|
||||
* can see at a glance whether edits will be queued for review or
|
||||
* applied immediately. Omitted in chat (non-code) mode.
|
||||
*/
|
||||
editMode?: EditMode;
|
||||
/**
|
||||
* Account balance fetched once at launch (and optionally refreshed
|
||||
* per-turn by the TUI). `null` or absent hides the balance cell
|
||||
* entirely — /user/balance failed or the user ran with `--no-config`.
|
||||
* The top-up warning fires below 1.0 unit of whatever currency
|
||||
* the endpoint reports so a Chinese user with CNY and a U.S. user
|
||||
* with USD both see "getting low."
|
||||
*/
|
||||
balance?: { currency: string; total: number } | null;
|
||||
/**
|
||||
* Published npm version newer than VERSION. Rendered as a yellow
|
||||
* "· update: X" nudge in the panel header. `null` / `undefined`
|
||||
* hides the nudge (offline launch, already up to date, or check
|
||||
* still in flight).
|
||||
*/
|
||||
updateAvailable?: string | null;
|
||||
/**
|
||||
* True when the loop is currently mid-turn — drives the wordmark's
|
||||
* "busy breathing" animation. Visual signal that the app is thinking,
|
||||
* visible at a glance from anywhere on screen.
|
||||
*/
|
||||
busy?: boolean;
|
||||
/**
|
||||
* /pro is queued — the next turn will run on v4-pro regardless of
|
||||
* `model`. Rendered as a yellow `⇧ pro armed` pill in the header so
|
||||
* the user has a clear "this turn will be expensive" signal before
|
||||
* submitting their message.
|
||||
*/
|
||||
proArmed?: boolean;
|
||||
/**
|
||||
* The CURRENT turn is running on v4-pro because the failure-
|
||||
* escalation threshold fired mid-turn. Rendered as a red `⇧ pro
|
||||
* escalated` pill. Clears at turn end.
|
||||
*/
|
||||
escalated?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Terminal width under which we switch from one-line metrics to a
|
||||
* stacked layout. Below 120 cols the wide version wraps mid-number
|
||||
* and the parens ("in $X · out $Y") get split across lines — which
|
||||
* looks broken. Stacking costs one row but stays readable on every
|
||||
* SSH / split-pane case we've hit.
|
||||
*/
|
||||
const NARROW_BREAKPOINT = 120;
|
||||
|
||||
/**
|
||||
* Cache-hit ratio is always zero on turn 1 (there's literally no cache
|
||||
* to hit yet). Showing that as red "0.0%" is a false alarm — new users
|
||||
* read it as "something is broken." We suppress the gradient until a
|
||||
* few turns have landed; by turn 4 the cache has had time to warm up.
|
||||
*/
|
||||
const COLD_START_TURNS = 3;
|
||||
|
||||
export function StatsPanel({
|
||||
summary,
|
||||
model,
|
||||
prefixHash,
|
||||
harvestOn,
|
||||
branchBudget,
|
||||
reasoningEffort,
|
||||
planMode,
|
||||
editMode,
|
||||
balance,
|
||||
updateAvailable,
|
||||
busy,
|
||||
proArmed,
|
||||
escalated,
|
||||
}: StatsPanelProps) {
|
||||
const hitPct = (summary.cacheHitRatio * 100).toFixed(1);
|
||||
const hitColor =
|
||||
summary.cacheHitRatio >= 0.7 ? "green" : summary.cacheHitRatio >= 0.4 ? "yellow" : "red";
|
||||
const branchOn = (branchBudget ?? 1) > 1;
|
||||
const ctxMax = DEEPSEEK_CONTEXT_TOKENS[model] ?? DEFAULT_CONTEXT_TOKENS;
|
||||
const ctxRatio = summary.lastPromptTokens / ctxMax;
|
||||
const { stdout } = useStdout();
|
||||
const columns = stdout?.columns ?? 80;
|
||||
const narrow = columns < NARROW_BREAKPOINT;
|
||||
|
||||
// Cold-start: first few turns render cache+cost muted so a 0.0% hit
|
||||
// rate on turn 1 doesn't look like an error. Once the cache has
|
||||
// actually had a chance to build, we flip to the live gradient.
|
||||
const coldStart = summary.turns <= COLD_START_TURNS;
|
||||
|
||||
return (
|
||||
<Box borderStyle="round" borderColor="cyan" flexDirection="column" paddingX={1}>
|
||||
<Box justifyContent="space-between">
|
||||
<Text>
|
||||
<Text color="cyan" bold>
|
||||
Reasonix
|
||||
</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}
|
||||
</Text>
|
||||
<Text dimColor>turns {summary.turns} · type /help</Text>
|
||||
</Box>
|
||||
<Box marginTop={1} gap={3}>
|
||||
<Text>
|
||||
<Text dimColor>cache hit </Text>
|
||||
<Text color={hitColor} bold>
|
||||
{hitPct}%
|
||||
</Text>
|
||||
</Text>
|
||||
<Text>
|
||||
<Text dimColor>cost </Text>
|
||||
<Text color="green">${summary.totalCostUsd.toFixed(6)}</Text>
|
||||
</Text>
|
||||
<Text>
|
||||
<Text dimColor>vs Claude </Text>
|
||||
<Text>${summary.claudeEquivalentUsd.toFixed(6)}</Text>
|
||||
</Text>
|
||||
<Text>
|
||||
<Text dimColor>saving </Text>
|
||||
<Text color="green" bold>
|
||||
{summary.savingsVsClaudePct.toFixed(1)}%
|
||||
</Text>
|
||||
</Text>
|
||||
</Box>
|
||||
// Explicit `width={columns}` pins the border frame to the exact
|
||||
// terminal width. Without this, Ink auto-flexes the Box to
|
||||
// container width, and on terminal resize the prior frame's
|
||||
// wrapped-overflow can leave tails in the scrollback (each
|
||||
// redraw stacks a slightly-wider-or-narrower frame). Fixing
|
||||
// width per-render doesn't eliminate the underlying Ink
|
||||
// limitation (eraseLines counts logical rows, not post-wrap
|
||||
// display rows) but makes each frame's dimensions exact so
|
||||
// there's no residual uncertainty in the erase.
|
||||
<Box borderStyle="round" borderColor="cyan" flexDirection="column" paddingX={1} width={columns}>
|
||||
<Header
|
||||
model={model}
|
||||
prefixHash={prefixHash}
|
||||
harvestOn={harvestOn}
|
||||
branchOn={branchOn}
|
||||
branchBudget={branchBudget ?? 1}
|
||||
reasoningEffort={reasoningEffort}
|
||||
planMode={planMode}
|
||||
editMode={editMode}
|
||||
turns={summary.turns}
|
||||
updateAvailable={updateAvailable}
|
||||
narrow={narrow}
|
||||
busy={busy ?? false}
|
||||
proArmed={proArmed ?? false}
|
||||
escalated={escalated ?? false}
|
||||
/>
|
||||
{narrow ? (
|
||||
<StackedMetrics
|
||||
summary={summary}
|
||||
ctxRatio={ctxRatio}
|
||||
ctxMax={ctxMax}
|
||||
balance={balance}
|
||||
coldStart={coldStart}
|
||||
/>
|
||||
) : (
|
||||
<InlineMetrics
|
||||
summary={summary}
|
||||
ctxRatio={ctxRatio}
|
||||
ctxMax={ctxMax}
|
||||
balance={balance}
|
||||
coldStart={coldStart}
|
||||
/>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
function Header({
|
||||
model,
|
||||
prefixHash,
|
||||
harvestOn,
|
||||
branchOn,
|
||||
branchBudget,
|
||||
reasoningEffort,
|
||||
planMode,
|
||||
editMode,
|
||||
turns,
|
||||
updateAvailable,
|
||||
narrow,
|
||||
busy,
|
||||
proArmed,
|
||||
escalated,
|
||||
}: {
|
||||
model: string;
|
||||
prefixHash: string;
|
||||
harvestOn?: boolean;
|
||||
branchOn: boolean;
|
||||
branchBudget: number;
|
||||
reasoningEffort?: "high" | "max";
|
||||
planMode?: boolean;
|
||||
editMode?: EditMode;
|
||||
turns: number;
|
||||
updateAvailable?: string | null;
|
||||
narrow: boolean;
|
||||
busy: boolean;
|
||||
proArmed: boolean;
|
||||
escalated: boolean;
|
||||
}) {
|
||||
return (
|
||||
<Box justifyContent="space-between">
|
||||
<Box>
|
||||
<Wordmark busy={busy} />
|
||||
<Text dimColor>{` v${VERSION}`}</Text>
|
||||
<Text dimColor> · </Text>
|
||||
<Text color="yellow">{model}</Text>
|
||||
{narrow ? null : (
|
||||
<>
|
||||
<Text dimColor> · </Text>
|
||||
<Text dimColor>{prefixHash}</Text>
|
||||
</>
|
||||
)}
|
||||
{harvestOn ? <Text color="magenta"> · harvest</Text> : null}
|
||||
{branchOn ? <Text color="blue"> · branch{branchBudget}</Text> : null}
|
||||
{reasoningEffort === "max" ? <Text color="green"> · max</Text> : null}
|
||||
{reasoningEffort === "high" ? <Text color="yellow"> · high</Text> : null}
|
||||
{planMode ? (
|
||||
<Text color="red" bold>
|
||||
{" · PLAN"}
|
||||
</Text>
|
||||
) : null}
|
||||
{editMode ? (
|
||||
<Text color={editMode === "auto" ? "magenta" : "cyan"} bold>
|
||||
{editMode === "auto" ? " · AUTO" : " · review"}
|
||||
</Text>
|
||||
) : null}
|
||||
{escalated ? (
|
||||
<Text color="red" bold>
|
||||
{" · ⇧ pro escalated"}
|
||||
</Text>
|
||||
) : proArmed ? (
|
||||
<Text color="yellow" bold>
|
||||
{" · ⇧ pro armed"}
|
||||
</Text>
|
||||
) : null}
|
||||
</Box>
|
||||
<Text>
|
||||
{updateAvailable ? (
|
||||
<Text color="yellow" bold>{`update: ${updateAvailable} · `}</Text>
|
||||
) : null}
|
||||
<Text dimColor>{narrow ? `turn ${turns}` : `turn ${turns} · /help`}</Text>
|
||||
</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Wide-terminal layout (≥120 cols): single metrics row. Matches the
|
||||
* original panel, just with calmer spacing and the cold-start
|
||||
* treatment folded in.
|
||||
*/
|
||||
function InlineMetrics({
|
||||
summary,
|
||||
ctxRatio,
|
||||
ctxMax,
|
||||
balance,
|
||||
coldStart,
|
||||
}: {
|
||||
summary: SessionSummary;
|
||||
ctxRatio: number;
|
||||
ctxMax: number;
|
||||
balance?: { currency: string; total: number } | null;
|
||||
coldStart: boolean;
|
||||
}) {
|
||||
return (
|
||||
<Box marginTop={1} gap={3}>
|
||||
<ContextCell ratio={ctxRatio} promptTokens={summary.lastPromptTokens} ctxMax={ctxMax} />
|
||||
<CacheCell hitRatio={summary.cacheHitRatio} coldStart={coldStart} turns={summary.turns} />
|
||||
<CostCell summary={summary} coldStart={coldStart} />
|
||||
{balance ? <BalanceCell balance={balance} /> : null}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Narrow-terminal layout (<120 cols): one metric per line, in priority
|
||||
* order (ctx → balance → cache → cost). Order matters because users
|
||||
* scanning a cramped terminal want "am I about to hit a wall?" answered
|
||||
* first; dollars spent comes later.
|
||||
*/
|
||||
function StackedMetrics({
|
||||
summary,
|
||||
ctxRatio,
|
||||
ctxMax,
|
||||
balance,
|
||||
coldStart,
|
||||
}: {
|
||||
summary: SessionSummary;
|
||||
ctxRatio: number;
|
||||
ctxMax: number;
|
||||
balance?: { currency: string; total: number } | null;
|
||||
coldStart: boolean;
|
||||
}) {
|
||||
return (
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
<ContextCell
|
||||
ratio={ctxRatio}
|
||||
promptTokens={summary.lastPromptTokens}
|
||||
ctxMax={ctxMax}
|
||||
showBar
|
||||
/>
|
||||
{balance ? <BalanceCell balance={balance} /> : null}
|
||||
<CacheCell hitRatio={summary.cacheHitRatio} coldStart={coldStart} turns={summary.turns} />
|
||||
<CostCell summary={summary} coldStart={coldStart} />
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
function ContextCell({
|
||||
ratio,
|
||||
promptTokens,
|
||||
ctxMax,
|
||||
showBar,
|
||||
}: {
|
||||
ratio: number;
|
||||
promptTokens: number;
|
||||
ctxMax: number;
|
||||
showBar?: boolean;
|
||||
}) {
|
||||
if (promptTokens === 0) {
|
||||
return (
|
||||
<Text>
|
||||
<Text dimColor>ctx </Text>
|
||||
<Text dimColor>— (no turns yet)</Text>
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
const color = ratio >= 0.8 ? "red" : ratio >= 0.6 ? "yellow" : "green";
|
||||
const pct = Math.round(ratio * 100);
|
||||
return (
|
||||
<Text>
|
||||
<Text dimColor>ctx </Text>
|
||||
{showBar ? <Bar ratio={ratio} color={color} /> : null}
|
||||
{showBar ? <Text> </Text> : null}
|
||||
<Text color={color} bold>
|
||||
{formatTokens(promptTokens)}/{formatTokens(ctxMax)}
|
||||
</Text>
|
||||
<Text dimColor> ({pct}%)</Text>
|
||||
{ratio >= 0.8 ? (
|
||||
<Text color="red" bold>
|
||||
{" · /compact"}
|
||||
</Text>
|
||||
) : null}
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
|
||||
function CacheCell({
|
||||
hitRatio,
|
||||
coldStart,
|
||||
turns,
|
||||
}: {
|
||||
hitRatio: number;
|
||||
coldStart: boolean;
|
||||
turns: number;
|
||||
}) {
|
||||
const pct = (hitRatio * 100).toFixed(1);
|
||||
if (turns === 0) {
|
||||
return (
|
||||
<Text>
|
||||
<Text dimColor>cache </Text>
|
||||
<Text dimColor>—</Text>
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
if (coldStart) {
|
||||
return (
|
||||
<Text>
|
||||
<Text dimColor>cache </Text>
|
||||
<Text dimColor>{pct}% </Text>
|
||||
<Text dimColor italic>
|
||||
(cold start)
|
||||
</Text>
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
const color = hitRatio >= 0.7 ? "green" : hitRatio >= 0.4 ? "yellow" : "red";
|
||||
return (
|
||||
<Text>
|
||||
<Text dimColor>cache </Text>
|
||||
<Text color={color} bold>
|
||||
{pct}%
|
||||
</Text>
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Color thresholds. Per-turn and session cumulative scale roughly 10×
|
||||
* apart — a $0.20 single turn should feel just as warn-worthy as a $2
|
||||
* session total. Values are rough "notice this" points, not hard caps.
|
||||
*/
|
||||
function turnCostColor(cost: number): "green" | "yellow" | "red" | undefined {
|
||||
if (cost <= 0) return undefined;
|
||||
if (cost >= 0.2) return "red";
|
||||
if (cost >= 0.05) return "yellow";
|
||||
return "green";
|
||||
}
|
||||
function sessionCostColor(cost: number): "green" | "yellow" | "red" | undefined {
|
||||
if (cost <= 0) return undefined;
|
||||
if (cost >= 5) return "red";
|
||||
if (cost >= 0.5) return "yellow";
|
||||
return "green";
|
||||
}
|
||||
|
||||
function CostCell({
|
||||
summary,
|
||||
coldStart,
|
||||
}: {
|
||||
summary: SessionSummary;
|
||||
coldStart: boolean;
|
||||
}) {
|
||||
if (summary.turns === 0) {
|
||||
return (
|
||||
<Text>
|
||||
<Text dimColor>cost </Text>
|
||||
<Text dimColor>—</Text>
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
// The first turn is unavoidably a cache-miss (nothing to hit),
|
||||
// so the dollar figure is front-loaded. Muting it during the
|
||||
// cold-start window keeps the "expensive first turn" from
|
||||
// reading as "something is wrong."
|
||||
const turnColor = coldStart ? undefined : turnCostColor(summary.lastTurnCostUsd);
|
||||
const sessionColor = coldStart ? undefined : sessionCostColor(summary.totalCostUsd);
|
||||
return (
|
||||
<Text>
|
||||
<Text dimColor>turn </Text>
|
||||
<Text color={turnColor} bold={!coldStart} dimColor={coldStart}>
|
||||
${summary.lastTurnCostUsd.toFixed(4)}
|
||||
</Text>
|
||||
<Text dimColor>{" · session "}</Text>
|
||||
<Text color={sessionColor} bold={!coldStart} dimColor={coldStart}>
|
||||
${summary.totalCostUsd.toFixed(4)}
|
||||
</Text>
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
|
||||
function BalanceCell({ balance }: { balance: { currency: string; total: number } }) {
|
||||
const color = balance.total < 1 ? "red" : balance.total < 5 ? "yellow" : "green";
|
||||
return (
|
||||
<Text>
|
||||
<Text dimColor>balance </Text>
|
||||
<Text color={color} bold>
|
||||
{balance.currency === "USD" ? "$" : ""}
|
||||
{balance.total.toFixed(2)}
|
||||
{balance.currency !== "USD" ? ` ${balance.currency}` : ""}
|
||||
</Text>
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Unicode progress bar for the narrow layout's context cell. 10 cells
|
||||
* wide — narrow terminals are already cramped, and the bar is just a
|
||||
* visual cue for the percentage next to it, not the primary readout.
|
||||
*/
|
||||
function Bar({ ratio, color }: { ratio: number; color: "green" | "yellow" | "red" }) {
|
||||
const cells = 10;
|
||||
const filled = Math.max(0, Math.min(cells, Math.round(ratio * cells)));
|
||||
const bar = "█".repeat(filled) + "░".repeat(cells - filled);
|
||||
return <Text color={color}>{bar}</Text>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compact token formatter using binary K (÷1024): 1234 → "1.2K",
|
||||
* 131072 → "128K". Matches DeepSeek's marketing label of "128K context
|
||||
* length" — showing "131k" confused users (the actual limit is
|
||||
* 128×1024 = 131,072 tokens, but the doc consistently says "128K").
|
||||
* Uppercase K signals binary-K to anyone who notices.
|
||||
*/
|
||||
function formatTokens(n: number): string {
|
||||
if (n < 1024) return String(n);
|
||||
const k = n / 1024;
|
||||
return k >= 100 ? `${k.toFixed(0)}K` : `${k.toFixed(1)}K`;
|
||||
}
|
||||
@@ -0,0 +1,447 @@
|
||||
/**
|
||||
* First-run / re-configure wizard.
|
||||
*
|
||||
* Walks a new user through: API key → preset pick → MCP server pick →
|
||||
* per-server args → save. Saved output lives in `~/.reasonix/config.json`
|
||||
* so the next `reasonix chat` starts with everything already wired.
|
||||
*
|
||||
* The wizard is the antidote to "too many CLI flags" — a new user should
|
||||
* never have to read `--help` to get MCP + a sensible model combo
|
||||
* working. Everything a user could set via `--mcp`, `--harvest`,
|
||||
* `--branch`, etc. can be picked here in a few arrow-key presses.
|
||||
*/
|
||||
|
||||
import { Box, Text, useApp, useInput } from "ink";
|
||||
import TextInput from "ink-text-input";
|
||||
// biome-ignore lint/style/useImportType: JSX (jsx: "react") needs React as a value at runtime
|
||||
import React, { useState } from "react";
|
||||
import {
|
||||
type PresetName,
|
||||
type ReasonixConfig,
|
||||
defaultConfigPath,
|
||||
isPlausibleKey,
|
||||
readConfig,
|
||||
redactKey,
|
||||
writeConfig,
|
||||
} from "../../config.js";
|
||||
import { type CatalogEntry, MCP_CATALOG } from "../../mcp/catalog.js";
|
||||
import { MultiSelect, type SelectItem, SingleSelect } from "./Select.js";
|
||||
import { PRESET_DESCRIPTIONS } from "./presets.js";
|
||||
|
||||
export interface WizardProps {
|
||||
/** Called once the config has been saved. */
|
||||
onComplete: (cfg: ReasonixConfig) => void;
|
||||
/** Called if the user presses Esc to abort. */
|
||||
onCancel?: () => void;
|
||||
/** Skip the API-key step if a key already exists (env or config). */
|
||||
existingApiKey?: string;
|
||||
/** Pre-fill selections when re-running (reconfigure flow). */
|
||||
initial?: {
|
||||
preset?: PresetName;
|
||||
mcp?: string[];
|
||||
};
|
||||
}
|
||||
|
||||
type Step = "apiKey" | "preset" | "mcp" | "mcpArgs" | "review" | "saved";
|
||||
|
||||
interface WizardData {
|
||||
apiKey: string;
|
||||
preset: PresetName;
|
||||
selectedCatalog: string[]; // entries from MCP_CATALOG by `name`
|
||||
/** Captured user inputs per catalog entry that has `userArgs` (e.g. fs dir). */
|
||||
catalogArgs: Record<string, string>;
|
||||
}
|
||||
|
||||
const CATALOG_BY_NAME = new Map(MCP_CATALOG.map((e) => [e.name, e]));
|
||||
|
||||
export function Wizard({ onComplete, onCancel, existingApiKey, initial }: WizardProps) {
|
||||
const { exit } = useApp();
|
||||
const [step, setStep] = useState<Step>(existingApiKey ? "preset" : "apiKey");
|
||||
const [data, setData] = useState<WizardData>({
|
||||
apiKey: existingApiKey ?? "",
|
||||
preset: initial?.preset ?? "fast",
|
||||
selectedCatalog: deriveInitialCatalog(initial?.mcp ?? []),
|
||||
catalogArgs: {},
|
||||
});
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// Global Esc → cancel. Disabled once we've started saving to avoid
|
||||
// ejecting out of a half-written state.
|
||||
useInput((_input, key) => {
|
||||
if (key.escape && step !== "saved" && onCancel) onCancel();
|
||||
});
|
||||
|
||||
if (step === "apiKey") {
|
||||
return (
|
||||
<ApiKeyStep
|
||||
onSubmit={(key) => {
|
||||
setData((d) => ({ ...d, apiKey: key }));
|
||||
setError(null);
|
||||
setStep("preset");
|
||||
}}
|
||||
error={error}
|
||||
onError={setError}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (step === "preset") {
|
||||
return (
|
||||
<StepFrame title="Pick a preset" step={1} total={3}>
|
||||
<SingleSelect<PresetName>
|
||||
items={presetItems()}
|
||||
initialValue={data.preset}
|
||||
onSubmit={(preset) => {
|
||||
setData((d) => ({ ...d, preset }));
|
||||
setStep("mcp");
|
||||
}}
|
||||
/>
|
||||
<Box marginTop={1}>
|
||||
<Text dimColor>[↑↓] navigate · [Enter] confirm · [Esc] cancel</Text>
|
||||
</Box>
|
||||
</StepFrame>
|
||||
);
|
||||
}
|
||||
|
||||
if (step === "mcp") {
|
||||
return (
|
||||
<StepFrame title="Which MCP servers should Reasonix wire up for you?" step={2} total={3}>
|
||||
<MultiSelect
|
||||
items={mcpItems()}
|
||||
initialSelected={data.selectedCatalog}
|
||||
onSubmit={(selected) => {
|
||||
setData((d) => ({ ...d, selectedCatalog: selected }));
|
||||
// Only advance to the args step if any selected entry needs args.
|
||||
const needsArgs = selected.some((name) => CATALOG_BY_NAME.get(name)?.userArgs);
|
||||
setStep(needsArgs ? "mcpArgs" : "review");
|
||||
}}
|
||||
footer="[↑↓] navigate · [Space] toggle · [Enter] confirm · [Esc] cancel · empty = skip"
|
||||
/>
|
||||
</StepFrame>
|
||||
);
|
||||
}
|
||||
|
||||
if (step === "mcpArgs") {
|
||||
const pending = data.selectedCatalog.filter((name) => {
|
||||
const entry = CATALOG_BY_NAME.get(name);
|
||||
return entry?.userArgs && !data.catalogArgs[name];
|
||||
});
|
||||
if (pending.length === 0) {
|
||||
setStep("review");
|
||||
return null;
|
||||
}
|
||||
const currentName = pending[0]!;
|
||||
const entry = CATALOG_BY_NAME.get(currentName)!;
|
||||
return (
|
||||
<McpArgsStep
|
||||
entry={entry}
|
||||
error={error}
|
||||
onSubmit={(value) => {
|
||||
setData((d) => ({
|
||||
...d,
|
||||
catalogArgs: { ...d.catalogArgs, [currentName]: value },
|
||||
}));
|
||||
setError(null);
|
||||
}}
|
||||
onError={setError}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (step === "review") {
|
||||
const specs = data.selectedCatalog.map((name) => buildSpec(name, data.catalogArgs));
|
||||
return (
|
||||
<StepFrame title="Ready to save" step={3} total={3}>
|
||||
<Box flexDirection="column">
|
||||
<SummaryLine label="API key" value={redactKey(data.apiKey)} />
|
||||
<SummaryLine label="Preset" value={data.preset} />
|
||||
<SummaryLine
|
||||
label="MCP"
|
||||
value={specs.length === 0 ? "(none)" : `${specs.length} server(s)`}
|
||||
/>
|
||||
{specs.map((spec, i) => (
|
||||
// biome-ignore lint/suspicious/noArrayIndexKey: review-only render, order fixed
|
||||
<Box key={i} paddingLeft={14}>
|
||||
<Text dimColor>· {spec}</Text>
|
||||
</Box>
|
||||
))}
|
||||
<Box marginTop={1}>
|
||||
<Text>Saves to {defaultConfigPath()}</Text>
|
||||
</Box>
|
||||
{error ? (
|
||||
<Box marginTop={1}>
|
||||
<Text color="red">{error}</Text>
|
||||
</Box>
|
||||
) : null}
|
||||
<Box marginTop={1}>
|
||||
<Text dimColor>[Enter] save · [Esc] cancel</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
<ReviewConfirm
|
||||
onConfirm={() => {
|
||||
try {
|
||||
const specsNow = data.selectedCatalog.map((name) =>
|
||||
buildSpec(name, data.catalogArgs),
|
||||
);
|
||||
const prev = readConfig();
|
||||
const next: ReasonixConfig = {
|
||||
...prev,
|
||||
apiKey: data.apiKey,
|
||||
preset: data.preset,
|
||||
mcp: specsNow,
|
||||
setupCompleted: true,
|
||||
};
|
||||
writeConfig(next);
|
||||
setStep("saved");
|
||||
onComplete(next);
|
||||
} catch (e) {
|
||||
setError(`Could not save config: ${(e as Error).message}`);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</StepFrame>
|
||||
);
|
||||
}
|
||||
|
||||
// saved
|
||||
return (
|
||||
<Box flexDirection="column" borderStyle="round" borderColor="green" paddingX={1}>
|
||||
<Text bold color="green">
|
||||
▸ Saved.
|
||||
</Text>
|
||||
<Box marginTop={1}>
|
||||
<Text>Run `reasonix` any time to start chatting — your settings are remembered.</Text>
|
||||
</Box>
|
||||
<Box marginTop={1}>
|
||||
<Text dimColor>[Enter] to exit</Text>
|
||||
</Box>
|
||||
<ExitOnEnter onExit={exit} />
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------- step components ----------
|
||||
|
||||
function ApiKeyStep({
|
||||
onSubmit,
|
||||
error,
|
||||
onError,
|
||||
}: {
|
||||
onSubmit: (key: string) => void;
|
||||
error: string | null;
|
||||
onError: (e: string | null) => void;
|
||||
}) {
|
||||
const [value, setValue] = useState("");
|
||||
return (
|
||||
<Box flexDirection="column" borderStyle="round" borderColor="cyan" paddingX={1}>
|
||||
<Text bold color="cyan">
|
||||
Welcome to Reasonix.
|
||||
</Text>
|
||||
<Box marginTop={1}>
|
||||
<Text>Paste your DeepSeek API key to get started.</Text>
|
||||
</Box>
|
||||
<Text dimColor>Get one (free credit on signup): https://platform.deepseek.com/api_keys</Text>
|
||||
<Text dimColor>Saved locally to {defaultConfigPath()}</Text>
|
||||
<Box marginTop={1}>
|
||||
<Text bold color="cyan">
|
||||
{"key › "}
|
||||
</Text>
|
||||
<TextInput
|
||||
value={value}
|
||||
onChange={setValue}
|
||||
onSubmit={(raw) => {
|
||||
const trimmed = raw.trim();
|
||||
if (!isPlausibleKey(trimmed)) {
|
||||
onError("Doesn't look like a DeepSeek key. They start with 'sk-' and are 30+ chars.");
|
||||
setValue("");
|
||||
return;
|
||||
}
|
||||
onSubmit(trimmed);
|
||||
}}
|
||||
mask="•"
|
||||
placeholder="sk-..."
|
||||
/>
|
||||
</Box>
|
||||
{error ? (
|
||||
<Box marginTop={1}>
|
||||
<Text color="red">{error}</Text>
|
||||
</Box>
|
||||
) : value ? (
|
||||
<Box marginTop={1}>
|
||||
<Text dimColor>preview: {redactKey(value)}</Text>
|
||||
</Box>
|
||||
) : null}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
function McpArgsStep({
|
||||
entry,
|
||||
error,
|
||||
onSubmit,
|
||||
onError,
|
||||
}: {
|
||||
entry: CatalogEntry;
|
||||
error: string | null;
|
||||
onSubmit: (value: string) => void;
|
||||
onError: (e: string | null) => void;
|
||||
}) {
|
||||
const [value, setValue] = useState("");
|
||||
return (
|
||||
<StepFrame title={`Configure ${entry.name}`} step={2} total={3}>
|
||||
<Box flexDirection="column">
|
||||
<Text>{entry.summary}</Text>
|
||||
{entry.note ? (
|
||||
<Box marginTop={1}>
|
||||
<Text dimColor>{entry.note}</Text>
|
||||
</Box>
|
||||
) : null}
|
||||
<Box marginTop={1}>
|
||||
<Text>Required parameter: </Text>
|
||||
<Text bold>{entry.userArgs}</Text>
|
||||
</Box>
|
||||
<Box marginTop={1}>
|
||||
<Text bold color="cyan">
|
||||
{entry.userArgs}
|
||||
{" › "}
|
||||
</Text>
|
||||
<TextInput
|
||||
value={value}
|
||||
onChange={setValue}
|
||||
onSubmit={(raw) => {
|
||||
const trimmed = raw.trim();
|
||||
if (!trimmed) {
|
||||
onError(`${entry.name} needs a value — got an empty string.`);
|
||||
return;
|
||||
}
|
||||
onSubmit(trimmed);
|
||||
setValue("");
|
||||
}}
|
||||
placeholder={placeholderFor(entry)}
|
||||
/>
|
||||
</Box>
|
||||
{error ? (
|
||||
<Box marginTop={1}>
|
||||
<Text color="red">{error}</Text>
|
||||
</Box>
|
||||
) : null}
|
||||
</Box>
|
||||
</StepFrame>
|
||||
);
|
||||
}
|
||||
|
||||
function ReviewConfirm({ onConfirm }: { onConfirm: () => void }) {
|
||||
useInput((_i, key) => {
|
||||
if (key.return) onConfirm();
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
function ExitOnEnter({ onExit }: { onExit: () => void }) {
|
||||
useInput((_i, key) => {
|
||||
if (key.return) onExit();
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
// ---------- small bits ----------
|
||||
|
||||
function StepFrame({
|
||||
title,
|
||||
step,
|
||||
total,
|
||||
children,
|
||||
}: {
|
||||
title: string;
|
||||
step: number;
|
||||
total: number;
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<Box flexDirection="column" borderStyle="round" borderColor="cyan" paddingX={1}>
|
||||
<Box>
|
||||
<Text dimColor>
|
||||
Step {step}/{total} ·{" "}
|
||||
</Text>
|
||||
<Text bold color="cyan">
|
||||
{title}
|
||||
</Text>
|
||||
</Box>
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
{children}
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
function SummaryLine({ label, value }: { label: string; value: string }) {
|
||||
return (
|
||||
<Box>
|
||||
<Text>{label.padEnd(12)}</Text>
|
||||
<Text bold>{value}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------- data helpers ----------
|
||||
|
||||
function presetItems(): SelectItem<PresetName>[] {
|
||||
return (["fast", "smart", "max"] as PresetName[]).map((name) => ({
|
||||
value: name,
|
||||
label: `${name} — ${PRESET_DESCRIPTIONS[name].headline}`,
|
||||
hint: PRESET_DESCRIPTIONS[name].cost,
|
||||
}));
|
||||
}
|
||||
|
||||
function mcpItems(): SelectItem<string>[] {
|
||||
return MCP_CATALOG.map((entry) => {
|
||||
const hintParts: string[] = [entry.summary];
|
||||
if (entry.userArgs) hintParts.push(`(you'll provide ${entry.userArgs})`);
|
||||
if (entry.note) hintParts.push(entry.note);
|
||||
return {
|
||||
value: entry.name,
|
||||
label: entry.name,
|
||||
hint: hintParts.join(" · "),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function placeholderFor(entry: CatalogEntry): string {
|
||||
if (entry.name === "filesystem") return "e.g. /tmp/reasonix-sandbox";
|
||||
if (entry.name === "sqlite") return "e.g. ./notes.sqlite";
|
||||
return entry.userArgs ?? "";
|
||||
}
|
||||
|
||||
function deriveInitialCatalog(existingSpecs: string[]): string[] {
|
||||
// Best-effort recovery: if the user previously picked catalog entries,
|
||||
// the spec strings look like `name=npx -y <pkg> ...`. Match by package
|
||||
// so reconfigure pre-checks the same boxes.
|
||||
const packageToName = new Map(MCP_CATALOG.map((e) => [e.package, e.name]));
|
||||
const out: string[] = [];
|
||||
for (const spec of existingSpecs) {
|
||||
for (const [pkg, name] of packageToName) {
|
||||
if (spec.includes(pkg)) {
|
||||
out.push(name);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the `--mcp` spec string for a catalog entry. Same format
|
||||
* `mcpCommandFor` produces for `reasonix mcp list`, minus the leading
|
||||
* `--mcp "..."` wrapper — we store the inner spec directly.
|
||||
*/
|
||||
export function buildSpec(name: string, argsByName: Record<string, string>): string {
|
||||
const entry = CATALOG_BY_NAME.get(name);
|
||||
if (!entry) return name; // shouldn't happen; fall back gracefully
|
||||
const userArg = entry.userArgs ? argsByName[name] : undefined;
|
||||
const tail = userArg ? ` ${quoteIfNeeded(userArg)}` : "";
|
||||
return `${entry.name}=npx -y ${entry.package}${tail}`;
|
||||
}
|
||||
|
||||
function quoteIfNeeded(s: string): string {
|
||||
return /\s|"/.test(s) ? `"${s.replace(/"/g, '\\"')}"` : s;
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/**
|
||||
* Bash-mode (`!cmd`) prefix parsing.
|
||||
*
|
||||
* A `!` at the start of the user's input means "run this as a shell
|
||||
* command in the sandbox root, and put both the command and its output
|
||||
* into the conversation so the model sees it next turn." Same idea as
|
||||
* Claude Code's `!` prefix — faster than round-tripping through the
|
||||
* model just to cat a file or check git status.
|
||||
*
|
||||
* Design choice: user-typed `!` commands skip the allowlist. The
|
||||
* allowlist exists to bound what the MODEL can do with run_command;
|
||||
* the user typing `!git push` by hand is explicit consent. If a user
|
||||
* wants stricter gating they can set `REASONIX_BANG_CONFIRM=1` in a
|
||||
* future iteration.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Return the command portion of a `!`-prefixed input, or `null` if
|
||||
* the text isn't a bang invocation. Trims leading/trailing whitespace
|
||||
* from the command body. `!` alone (or `!` followed by only whitespace)
|
||||
* returns `null` — no command to run.
|
||||
*/
|
||||
export function detectBangCommand(text: string): string | null {
|
||||
if (!text.startsWith("!")) return null;
|
||||
const body = text.slice(1).trim();
|
||||
if (!body) return null;
|
||||
return body;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format a bang command + its output into a single user-role message
|
||||
* body that the model will see on the next turn. The `[!cmd]` header
|
||||
* marks the run explicitly so the model can distinguish
|
||||
* user-typed shell output from its own `run_command` tool results
|
||||
* (which are `role: tool`, different message shape entirely).
|
||||
*/
|
||||
export function formatBangUserMessage(cmd: string, output: string): string {
|
||||
return `[!${cmd}]\n${output}`;
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
import { formatAllBlockDiffs } from "../../code/diff-preview.js";
|
||||
import type { ApplyResult, EditBlock, EditSnapshot } from "../../code/edit-blocks.js";
|
||||
|
||||
/**
|
||||
* One batch of edits that actually landed on disk — durable enough for
|
||||
* `/undo`, `/history`, and `/show` within a session. Not persisted
|
||||
* across restarts: restoring pre-apply content from a process that
|
||||
* crashed last week is git's job, not ours.
|
||||
*/
|
||||
export interface EditHistoryEntry {
|
||||
/** Sequence number within the session, stable for `/show <id>`. */
|
||||
id: number;
|
||||
/** Epoch ms when the entry was opened (first edit landed). */
|
||||
at: number;
|
||||
/**
|
||||
* Short tag for what produced the batch — "auto" (auto-mode tool
|
||||
* call), "auto-text" (auto-mode text SEARCH/REPLACE at turn end),
|
||||
* "review-apply" (user-approved modal edit or /apply flush).
|
||||
*/
|
||||
source: string;
|
||||
/** Edit blocks included in this batch, in arrival order. */
|
||||
blocks: EditBlock[];
|
||||
/** Per-block outcome — some may be "not-found" if SEARCH drifted. */
|
||||
results: ApplyResult[];
|
||||
/**
|
||||
* First-snapshot-per-path wins: this is what `/undo` restores to.
|
||||
* Deduped so multi-edit turns still roll back to pre-turn state.
|
||||
*/
|
||||
snapshots: EditSnapshot[];
|
||||
/**
|
||||
* Paths within this entry that have already been reverted (via
|
||||
* `/undo <id>`, `/undo <id> <path>`, or the newest-non-undone /undo
|
||||
* shortcut). Per-path instead of entry-level so a batch can be
|
||||
* partially undone — user reverts src/foo.ts out of a 3-file batch
|
||||
* without rolling back the other two.
|
||||
*/
|
||||
undoneFiles: Set<string>;
|
||||
}
|
||||
|
||||
/** True when every path in the entry has been undone. */
|
||||
export function isEntryFullyUndone(e: EditHistoryEntry): boolean {
|
||||
return e.snapshots.length > 0 && e.snapshots.every((s) => e.undoneFiles.has(s.path));
|
||||
}
|
||||
|
||||
/** Per-entry three-state status label for display. */
|
||||
export function entryStatus(e: EditHistoryEntry): "applied" | "UNDONE" | "PARTIAL" {
|
||||
if (e.undoneFiles.size === 0) return "applied";
|
||||
if (isEntryFullyUndone(e)) return "UNDONE";
|
||||
return "PARTIAL";
|
||||
}
|
||||
|
||||
/**
|
||||
* Render a batch of SEARCH/REPLACE application results as one
|
||||
* human-scannable info line per edit. Prefixes denote status so the
|
||||
* line reads well even without color (e.g. when piped to a log file
|
||||
* or stripped for screenshots):
|
||||
* ✓ applied src/foo.ts
|
||||
* ✓ created src/new.ts
|
||||
* ✗ not-found src/bar.ts (SEARCH text does not match…)
|
||||
*/
|
||||
export function formatEditResults(results: ApplyResult[]): string {
|
||||
const lines = results.map((r) => {
|
||||
const mark = r.status === "applied" || r.status === "created" ? "✓" : "✗";
|
||||
const detail = r.message ? ` (${r.message})` : "";
|
||||
return ` ${mark} ${r.status.padEnd(11)} ${r.path}${detail}`;
|
||||
});
|
||||
const ok = results.filter((r) => r.status === "applied" || r.status === "created").length;
|
||||
const total = results.length;
|
||||
const header = `▸ edit blocks: ${ok}/${total} applied — /undo to roll back, or \`git diff\` to review`;
|
||||
return [header, ...lines].join("\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* Pending-edits preview shown after each assistant turn that proposed
|
||||
* changes. Per-block path header + ±line-count, then a unified-diff-
|
||||
* style preview (context trimmed to 2 lines each side, total capped
|
||||
* at 20 lines per block). Users can eyeball what's about to land
|
||||
* BEFORE pressing `y` — the old summary-only view was a common
|
||||
* mistake surface.
|
||||
*/
|
||||
export function formatPendingPreview(blocks: EditBlock[]): string {
|
||||
const header = `▸ ${blocks.length} pending edit block(s) — /apply (or y) to commit · /discard (or n) to drop`;
|
||||
const diffLines = formatAllBlockDiffs(blocks);
|
||||
return [header, ...diffLines].join("\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* Per-file rows for the multi-level `/undo` output, without the
|
||||
* single-batch header (the caller prepends its own).
|
||||
*/
|
||||
export function formatUndoRows(results: ApplyResult[]): string[] {
|
||||
return results.map((r) => {
|
||||
const mark = r.status === "applied" ? "✓" : "✗";
|
||||
const detail = r.message ? ` (${r.message})` : "";
|
||||
return ` ${mark} ${r.path}${detail}`;
|
||||
});
|
||||
}
|
||||
|
||||
export function describeRepair(repair: {
|
||||
scavenged: number;
|
||||
truncationsFixed: number;
|
||||
stormsBroken: number;
|
||||
}): string {
|
||||
const parts: string[] = [];
|
||||
if (repair.scavenged) parts.push(`scavenged ${repair.scavenged}`);
|
||||
if (repair.truncationsFixed) parts.push(`repaired ${repair.truncationsFixed} truncation`);
|
||||
if (repair.stormsBroken) parts.push(`broke ${repair.stormsBroken} storm`);
|
||||
return parts.length ? `[repair] ${parts.join(", ")}` : "";
|
||||
}
|
||||
+1126
-62
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,242 @@
|
||||
/**
|
||||
* `/resource` and `/prompt` slash handlers for the chat/code TUI.
|
||||
*
|
||||
* The slash-command registry (slash.ts) advertises both commands so the
|
||||
* argument-level picker and /help surface them, but the actual read/fetch
|
||||
* work is async — McpClient.readResource and getPrompt both round-trip to
|
||||
* the server — so it doesn't fit the synchronous `handleSlash` shape used
|
||||
* by every other slash command. App.tsx intercepts the commands directly
|
||||
* and calls into the helpers below.
|
||||
*
|
||||
* Split by effect boundary:
|
||||
* - formatters (resource list, contents, prompt list, messages) are
|
||||
* pure over already-fetched data and unit-tested
|
||||
* - find-server helpers are pure lookups against inspection reports
|
||||
* - `handleMcpBrowseSlash` is the async orchestrator App.tsx calls
|
||||
*
|
||||
* v1 intentionally does NOT inject the fetched resource/prompt into the
|
||||
* next model turn. It's a display-only browser so users can see what
|
||||
* their MCP servers expose. A future version may add a Tab-to-inject
|
||||
* hotkey once the UX is settled.
|
||||
*/
|
||||
|
||||
import type { McpClient } from "../../mcp/client.js";
|
||||
import type {
|
||||
GetPromptResult,
|
||||
McpPromptMessage,
|
||||
McpResourceContents,
|
||||
ReadResourceResult,
|
||||
} from "../../mcp/types.js";
|
||||
import type { DisplayEvent } from "./EventLog.js";
|
||||
import type { McpServerSummary } from "./slash.js";
|
||||
|
||||
/**
|
||||
* React setState for Historical — typed loose because the App state
|
||||
* shape is App-internal. We only ever append, so `(prev) => prev.concat(row)`
|
||||
* works against any array-of-DisplayEvent state.
|
||||
*/
|
||||
export type HistoricalSetter = (updater: (prev: DisplayEvent[]) => DisplayEvent[]) => void;
|
||||
|
||||
export function formatResourceList(servers: readonly McpServerSummary[]): string {
|
||||
const lines: string[] = [];
|
||||
let total = 0;
|
||||
for (const s of servers) {
|
||||
if (!s.report.resources.supported) continue;
|
||||
const items = s.report.resources.items;
|
||||
if (items.length === 0) continue;
|
||||
lines.push(`[${s.label}] ${items.length} resource(s):`);
|
||||
for (const r of items.slice(0, 20)) {
|
||||
const name = r.name && r.name !== r.uri ? ` ${r.name}` : "";
|
||||
const mime = r.mimeType ? ` · ${r.mimeType}` : "";
|
||||
lines.push(` · ${r.uri}${name}${mime}`);
|
||||
total++;
|
||||
}
|
||||
if (items.length > 20) lines.push(` (+${items.length - 20} more)`);
|
||||
lines.push("");
|
||||
}
|
||||
if (total === 0) {
|
||||
return "No resources on any connected MCP server (or no servers connected). `/mcp` shows the current set.";
|
||||
}
|
||||
lines.push("Read one: `/resource <uri>` — or use Tab in the picker.");
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
export function formatPromptList(servers: readonly McpServerSummary[]): string {
|
||||
const lines: string[] = [];
|
||||
let total = 0;
|
||||
for (const s of servers) {
|
||||
if (!s.report.prompts.supported) continue;
|
||||
const items = s.report.prompts.items;
|
||||
if (items.length === 0) continue;
|
||||
lines.push(`[${s.label}] ${items.length} prompt(s):`);
|
||||
for (const p of items.slice(0, 20)) {
|
||||
const desc = p.description ? ` — ${p.description}` : "";
|
||||
const argHint =
|
||||
p.arguments && p.arguments.length > 0
|
||||
? ` (args: ${p.arguments.map((a) => a.name + (a.required ? "*" : "?")).join(", ")})`
|
||||
: "";
|
||||
lines.push(` · ${p.name}${argHint}${desc}`);
|
||||
total++;
|
||||
}
|
||||
if (items.length > 20) lines.push(` (+${items.length - 20} more)`);
|
||||
lines.push("");
|
||||
}
|
||||
if (total === 0) {
|
||||
return "No prompts on any connected MCP server (or no servers connected). `/mcp` shows the current set.";
|
||||
}
|
||||
lines.push(
|
||||
"Fetch one: `/prompt <name>` — args are not supported yet; prompts with required args will surface an error from the server.",
|
||||
);
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
export function findServerForResource(
|
||||
servers: readonly McpServerSummary[],
|
||||
uri: string,
|
||||
): McpServerSummary | null {
|
||||
for (const s of servers) {
|
||||
if (!s.report.resources.supported) continue;
|
||||
if (s.report.resources.items.some((r) => r.uri === uri)) return s;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function findServerForPrompt(
|
||||
servers: readonly McpServerSummary[],
|
||||
name: string,
|
||||
): McpServerSummary | null {
|
||||
for (const s of servers) {
|
||||
if (!s.report.prompts.supported) continue;
|
||||
if (s.report.prompts.items.some((p) => p.name === name)) return s;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function formatResourceContents(uri: string, result: ReadResourceResult): string {
|
||||
const lines: string[] = [`Resource ${uri} (${result.contents.length} content block(s)):`, ""];
|
||||
for (let i = 0; i < result.contents.length; i++) {
|
||||
const c = result.contents[i]!;
|
||||
const header = `— block ${i + 1}${c.mimeType ? ` · ${c.mimeType}` : ""}`;
|
||||
lines.push(header);
|
||||
lines.push(formatOneResourceContent(c));
|
||||
lines.push("");
|
||||
}
|
||||
return lines.join("\n").trimEnd();
|
||||
}
|
||||
|
||||
function formatOneResourceContent(c: McpResourceContents): string {
|
||||
if ("text" in c) {
|
||||
const MAX = 8_000;
|
||||
if (c.text.length > MAX) {
|
||||
return `${c.text.slice(0, MAX)}\n\n[…truncated ${c.text.length - MAX} chars; full contents available via McpClient.readResource in library mode.]`;
|
||||
}
|
||||
return c.text;
|
||||
}
|
||||
// blob — we can't render arbitrary binary in the TUI; give the size.
|
||||
const bytes = typeof c.blob === "string" ? approximateBase64ByteSize(c.blob) : 0;
|
||||
return `[binary · ~${bytes.toLocaleString()} bytes · base64]`;
|
||||
}
|
||||
|
||||
function approximateBase64ByteSize(b64: string): number {
|
||||
// 4 base64 chars encode 3 bytes; padding `=` trims the output.
|
||||
const padding = b64.endsWith("==") ? 2 : b64.endsWith("=") ? 1 : 0;
|
||||
return Math.floor((b64.length * 3) / 4) - padding;
|
||||
}
|
||||
|
||||
export function formatPromptMessages(name: string, result: GetPromptResult): string {
|
||||
const lines: string[] = [
|
||||
`Prompt ${name}${result.description ? ` — ${result.description}` : ""}`,
|
||||
`(${result.messages.length} message(s))`,
|
||||
"",
|
||||
];
|
||||
for (let i = 0; i < result.messages.length; i++) {
|
||||
const m = result.messages[i]!;
|
||||
lines.push(`— ${i + 1}. ${m.role}`);
|
||||
lines.push(formatOnePromptMessage(m));
|
||||
lines.push("");
|
||||
}
|
||||
return lines.join("\n").trimEnd();
|
||||
}
|
||||
|
||||
function formatOnePromptMessage(m: McpPromptMessage): string {
|
||||
const block = m.content as { type?: string; text?: string; resource?: McpResourceContents };
|
||||
if (block.type === "text" && typeof block.text === "string") return block.text;
|
||||
if (block.type === "resource" && block.resource) {
|
||||
return `[resource: ${block.resource.uri}]\n${formatOneResourceContent(block.resource)}`;
|
||||
}
|
||||
return `[non-text content: ${block.type ?? "unknown"}]`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Orchestrator. Looks up the right server, calls readResource/getPrompt
|
||||
* via its `client`, and pushes one info row into `Historical`. Errors
|
||||
* (server missing, -32601, network) surface as a warning row; the user
|
||||
* can always fall back to `reasonix mcp inspect <spec>` for diagnostics.
|
||||
*/
|
||||
export async function handleMcpBrowseSlash(
|
||||
kind: "resource" | "prompt",
|
||||
arg: string,
|
||||
servers: readonly McpServerSummary[],
|
||||
setHistorical: HistoricalSetter,
|
||||
): Promise<void> {
|
||||
const ts = Date.now();
|
||||
const push = (role: DisplayEvent["role"], text: string) => {
|
||||
setHistorical((prev) => [...prev, { id: `mcp-${role}-${ts}-${prev.length}`, role, text }]);
|
||||
};
|
||||
|
||||
// No arg → list mode.
|
||||
if (!arg) {
|
||||
push("info", kind === "resource" ? formatResourceList(servers) : formatPromptList(servers));
|
||||
return;
|
||||
}
|
||||
|
||||
if (kind === "resource") {
|
||||
const server = findServerForResource(servers, arg);
|
||||
if (!server) {
|
||||
push(
|
||||
"warning",
|
||||
`no server exposes resource "${arg}". \`/resource\` with no arg lists what's available.`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
const client: McpClient | undefined = server.client;
|
||||
if (!client) {
|
||||
push(
|
||||
"warning",
|
||||
`server [${server.label}] is not connected (display-only). Resource read requires a live MCP client.`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const result = await client.readResource(arg);
|
||||
push("info", formatResourceContents(arg, result));
|
||||
} catch (err) {
|
||||
push("warning", `readResource failed: ${(err as Error).message}`);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// prompt
|
||||
const server = findServerForPrompt(servers, arg);
|
||||
if (!server) {
|
||||
push(
|
||||
"warning",
|
||||
`no server exposes prompt "${arg}". \`/prompt\` with no arg lists what's available.`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
const client: McpClient | undefined = server.client;
|
||||
if (!client) {
|
||||
push(
|
||||
"warning",
|
||||
`server [${server.label}] is not connected (display-only). Prompt fetch requires a live MCP client.`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const result = await client.getPrompt(arg);
|
||||
push("info", formatPromptMessages(arg, result));
|
||||
} catch (err) {
|
||||
push("warning", `getPrompt failed: ${(err as Error).message}`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,314 @@
|
||||
/**
|
||||
* Pure keystroke → action reducer for PromptInput.
|
||||
*
|
||||
* Kept separate from the React component so the keyboard semantics
|
||||
* are easy to unit-test. The component threads `useInput` through
|
||||
* this function and applies the returned action.
|
||||
*
|
||||
* Edit model:
|
||||
* - Full cursor support. ←/→ move one column. ↑/↓ move across
|
||||
* lines in a multi-line buffer (column preserved when possible).
|
||||
* Ctrl+A / Ctrl+E jump to start / end of the current line.
|
||||
* - Backspace deletes the char before the cursor; Delete deletes
|
||||
* the char under the cursor.
|
||||
* - Printable chars (including multi-char paste bursts) insert
|
||||
* at the cursor.
|
||||
* - Enter submits unless Shift is held (newline), the line ends
|
||||
* with '\' and cursor is at end (bash-style continuation), or
|
||||
* the input is Ctrl+J (LF, terminal-universal newline).
|
||||
* - Parent owns Tab, Esc, PageUp/Down (slash-complete, abort,
|
||||
* unused). Arrow keys are split: empty buffer → parent (history
|
||||
* recall); non-empty → child (cursor movement).
|
||||
*/
|
||||
|
||||
export interface MultilineKey {
|
||||
input: string;
|
||||
return?: boolean;
|
||||
shift?: boolean;
|
||||
ctrl?: boolean;
|
||||
meta?: boolean;
|
||||
backspace?: boolean;
|
||||
delete?: boolean;
|
||||
tab?: boolean;
|
||||
upArrow?: boolean;
|
||||
downArrow?: boolean;
|
||||
leftArrow?: boolean;
|
||||
rightArrow?: boolean;
|
||||
escape?: boolean;
|
||||
pageUp?: boolean;
|
||||
pageDown?: boolean;
|
||||
}
|
||||
|
||||
export interface MultilineAction {
|
||||
/** New buffer value. `null` = unchanged. */
|
||||
next: string | null;
|
||||
/** New cursor position (0..value.length). `null` = unchanged. */
|
||||
cursor: number | null;
|
||||
/** When `true`, fire `onSubmit(submitValue ?? value)`. */
|
||||
submit: boolean;
|
||||
submitValue?: string;
|
||||
/**
|
||||
* When set, the key was ↑/↓ at a buffer boundary (empty buffer, or
|
||||
* cursor already at first/last line) and the component should hand
|
||||
* off to the parent's history-recall handler. The child's cursor
|
||||
* didn't move; the parent decides whether to swap in a prior
|
||||
* prompt. Lets users escape out of a multi-line buffer into
|
||||
* history without first emptying it — previously NOOP felt stuck.
|
||||
*/
|
||||
historyHandoff?: "prev" | "next";
|
||||
/**
|
||||
* Multi-char paste detected. The reducer is pure so it can't
|
||||
* allocate a sentinel id or write to the registry — it hands the
|
||||
* raw normalized payload up to PromptInput, which registers the
|
||||
* paste, picks a sentinel codepoint, and inserts THAT (one char)
|
||||
* into the buffer. Result: the user sees a `[paste #N · M lines]`
|
||||
* placeholder instead of the full content drowning the typed text.
|
||||
*/
|
||||
pasteRequest?: { content: string };
|
||||
}
|
||||
|
||||
const BACKSLASH_SUFFIX = /\\$/;
|
||||
|
||||
const NOOP: MultilineAction = { next: null, cursor: null, submit: false };
|
||||
|
||||
function rewriteRawArrowEscape(key: MultilineKey): MultilineKey {
|
||||
if (key.upArrow || key.downArrow || key.leftArrow || key.rightArrow) return key;
|
||||
if (key.input === "\x1b[A") return { ...key, upArrow: true, input: "" };
|
||||
if (key.input === "\x1b[B") return { ...key, downArrow: true, input: "" };
|
||||
if (key.input === "\x1b[C") return { ...key, rightArrow: true, input: "" };
|
||||
if (key.input === "\x1b[D") return { ...key, leftArrow: true, input: "" };
|
||||
return key;
|
||||
}
|
||||
|
||||
export function processMultilineKey(
|
||||
value: string,
|
||||
cursor: number,
|
||||
keyIn: MultilineKey,
|
||||
): MultilineAction {
|
||||
// Raw-escape fallback for terminals (some Windows configurations —
|
||||
// cmd.exe, older winpty) that don't set `key.upArrow` / etc. on
|
||||
// arrow-key press and instead leak the raw ANSI CSI sequence into
|
||||
// `input`. Without this, `\x1b[A` lands on the "printable" branch
|
||||
// below and the user sees literal escape bytes inserted into their
|
||||
// buffer. Rewrite the event into the structured key here.
|
||||
const key: MultilineKey = rewriteRawArrowEscape(keyIn);
|
||||
|
||||
// Parent-owned keys: Tab (slash-complete), Esc (abort).
|
||||
if (key.tab || key.escape) {
|
||||
return NOOP;
|
||||
}
|
||||
|
||||
// Buffer-wide navigation. Per-line motion (↑/↓ / Ctrl+A / Ctrl+E)
|
||||
// is already covered; PageUp/PageDown are the missing "jump to
|
||||
// top / bottom of the WHOLE buffer" pair, useful after pasting a
|
||||
// 500-line blob where ↑×500 is absurd. Repurposed from the
|
||||
// previous NOOP behavior (PageUp/Down had no binding).
|
||||
if (key.pageUp) {
|
||||
return cursor === 0 ? NOOP : { next: null, cursor: 0, submit: false };
|
||||
}
|
||||
if (key.pageDown) {
|
||||
return cursor === value.length ? NOOP : { next: null, cursor: value.length, submit: false };
|
||||
}
|
||||
|
||||
// Empty buffer + ↑/↓ → parent handles history recall.
|
||||
if (value.length === 0 && (key.upArrow || key.downArrow)) {
|
||||
return { ...NOOP, historyHandoff: key.upArrow ? "prev" : "next" };
|
||||
}
|
||||
|
||||
// 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);
|
||||
// Cursor already on the first line — hand off to history recall
|
||||
// instead of sitting stuck. Users can now escape into history
|
||||
// from the middle of a multi-line draft.
|
||||
if (moved === cursor) return { ...NOOP, historyHandoff: "prev" };
|
||||
return { next: null, cursor: moved, submit: false };
|
||||
}
|
||||
if (key.downArrow) {
|
||||
const moved = moveCursorDown(value, cursor);
|
||||
if (moved === cursor) return { ...NOOP, historyHandoff: "next" };
|
||||
return { 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 };
|
||||
}
|
||||
// Bash / readline conventions:
|
||||
// Ctrl+U — clear the whole buffer (readline treats this as
|
||||
// "clear from cursor to start"; for our text-area we treat it
|
||||
// as "clear all" because there's no ergonomic way to clear a
|
||||
// huge paste otherwise).
|
||||
// Ctrl+W — delete the word before the cursor.
|
||||
if (key.ctrl && key.input === "u") {
|
||||
return value.length === 0 ? NOOP : { next: "", cursor: 0, submit: false };
|
||||
}
|
||||
if (key.ctrl && key.input === "w") {
|
||||
if (cursor === 0) return NOOP;
|
||||
const wordStart = previousWordStart(value, cursor);
|
||||
return {
|
||||
next: value.slice(0, wordStart) + value.slice(cursor),
|
||||
cursor: wordStart,
|
||||
submit: false,
|
||||
};
|
||||
}
|
||||
|
||||
// Paste-burst detection. If `input` contains a newline (or
|
||||
// bracketed-paste markers from a terminal that supports them),
|
||||
// this is a paste — surface it as a `pasteRequest` so the parent
|
||||
// can register the blob and insert ONE sentinel codepoint instead
|
||||
// of the full content. The buffer stays small + readable; the
|
||||
// user sees `[paste #N · M lines]` where the paste lives.
|
||||
//
|
||||
// Always overrides `key.return` for pastes: Ink occasionally sets
|
||||
// key.return when a paste's trailing \n looks like Enter, which
|
||||
// would submit the partial buffer mid-paste and silently truncate
|
||||
// the content. Pastes always insert; Enter only submits typed
|
||||
// content. We normalize \r\n and bare \r to \n so mixed-line-
|
||||
// ending pastes (Windows clipboard, web copy) land cleanly.
|
||||
const stripped = key.input.replaceAll("\u001b[200~", "").replaceAll("\u001b[201~", "");
|
||||
// Paste = newline-containing input with MORE than just the newline
|
||||
// itself. A bare "\n" is Ctrl+J / one-keystroke newline (handled
|
||||
// below); only multi-char input wrapped around a newline is a real
|
||||
// paste burst that warrants a sentinel.
|
||||
const looksLikePaste =
|
||||
stripped.length > 1 && (stripped.includes("\n") || stripped.includes("\r"));
|
||||
if (looksLikePaste) {
|
||||
const normalized = stripped.replace(/\r\n?/g, "\n");
|
||||
return {
|
||||
next: null,
|
||||
cursor: null,
|
||||
submit: false,
|
||||
pasteRequest: { content: normalized },
|
||||
};
|
||||
}
|
||||
// Single-char Ctrl+J / LF: insert one newline.
|
||||
if (key.input === "\n" || (key.ctrl && key.input === "j")) {
|
||||
return insertAt(value, cursor, "\n");
|
||||
}
|
||||
|
||||
if (key.return) {
|
||||
if (key.shift) return insertAt(value, cursor, "\n");
|
||||
// Bash-style line continuation: trailing '\' + Enter (only when the
|
||||
// cursor sits at end-of-buffer, so a stray '\' mid-line doesn't
|
||||
// trigger it).
|
||||
if (cursor === value.length && BACKSLASH_SUFFIX.test(value)) {
|
||||
const replaced = `${value.slice(0, -1)}\n`;
|
||||
return { next: replaced, cursor: replaced.length, submit: false };
|
||||
}
|
||||
return { next: null, cursor: null, submit: true, submitValue: value };
|
||||
}
|
||||
|
||||
// Backspace = delete the char BEFORE the cursor. We also accept
|
||||
// `key.delete` and the raw DEL (0x7f) / BS (0x08) bytes as backspace
|
||||
// for the same purpose — some Windows terminals (cmd.exe, certain
|
||||
// winpty configs) report plain Backspace without setting
|
||||
// `key.backspace`, which used to leave the user typing into a prompt
|
||||
// where the Backspace key did nothing. Reasonix doesn't offer a
|
||||
// separate forward-delete operation, so collapsing them is safe.
|
||||
if (key.backspace || key.delete || key.input === "\x7f" || key.input === "\b") {
|
||||
if (cursor === 0) return NOOP;
|
||||
return {
|
||||
next: value.slice(0, cursor - 1) + value.slice(cursor),
|
||||
cursor: cursor - 1,
|
||||
submit: false,
|
||||
};
|
||||
}
|
||||
|
||||
// Bare modifier events (Ctrl/Meta with no printable) and unhandled
|
||||
// Ctrl-<letter> chords are dropped so a stray Ctrl+L doesn't insert "l".
|
||||
if ((key.ctrl || key.meta) && key.input.length === 0) return NOOP;
|
||||
if (key.ctrl || key.meta) return NOOP;
|
||||
|
||||
// Printable input (may be a multi-char paste; pasted newlines land
|
||||
// inside the buffer rather than triggering submit on the first line).
|
||||
if (key.input.length > 0) {
|
||||
return insertAt(value, cursor, key.input);
|
||||
}
|
||||
|
||||
return NOOP;
|
||||
}
|
||||
|
||||
function insertAt(value: string, cursor: number, insert: string): MultilineAction {
|
||||
return {
|
||||
next: value.slice(0, cursor) + insert + value.slice(cursor),
|
||||
cursor: cursor + insert.length,
|
||||
submit: false,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Line + column of a cursor inside a buffer. Exported because the
|
||||
* renderer needs the same mapping for drawing the cursor block on the
|
||||
* right line.
|
||||
*/
|
||||
export function lineAndColumn(value: string, cursor: number): { line: number; col: number } {
|
||||
let line = 0;
|
||||
let col = 0;
|
||||
const n = Math.min(cursor, value.length);
|
||||
for (let i = 0; i < n; i++) {
|
||||
if (value[i] === "\n") {
|
||||
line++;
|
||||
col = 0;
|
||||
} else {
|
||||
col++;
|
||||
}
|
||||
}
|
||||
return { line, col };
|
||||
}
|
||||
|
||||
function startOfLine(value: string, cursor: number): number {
|
||||
return value.lastIndexOf("\n", cursor - 1) + 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the start of the word immediately to the left of the cursor.
|
||||
* Skips trailing whitespace first (so Ctrl+W after typing space
|
||||
* still removes the previous word, not just the space), then walks
|
||||
* back over the word characters until a whitespace boundary or
|
||||
* start-of-buffer. Newlines count as whitespace, so Ctrl+W at the
|
||||
* start of a line deletes the preceding line's last word — same
|
||||
* behavior as bash/readline.
|
||||
*/
|
||||
function previousWordStart(value: string, cursor: number): number {
|
||||
let i = cursor;
|
||||
while (i > 0 && /\s/.test(value[i - 1] ?? "")) i--;
|
||||
while (i > 0 && !/\s/.test(value[i - 1] ?? "")) i--;
|
||||
return i;
|
||||
}
|
||||
|
||||
function endOfLine(value: string, cursor: number): number {
|
||||
const nl = value.indexOf("\n", cursor);
|
||||
return nl === -1 ? value.length : nl;
|
||||
}
|
||||
|
||||
function moveCursorUp(value: string, cursor: number): number {
|
||||
const curStart = startOfLine(value, cursor);
|
||||
if (curStart === 0) return cursor; // already on the first line
|
||||
const col = cursor - curStart;
|
||||
const prevEnd = curStart - 1; // the '\n' between the two lines
|
||||
const prevStart = value.lastIndexOf("\n", prevEnd - 1) + 1;
|
||||
const prevLen = prevEnd - prevStart;
|
||||
return prevStart + Math.min(col, prevLen);
|
||||
}
|
||||
|
||||
function moveCursorDown(value: string, cursor: number): number {
|
||||
const nextNl = value.indexOf("\n", cursor);
|
||||
if (nextNl === -1) return cursor; // already on the last line
|
||||
const curStart = startOfLine(value, cursor);
|
||||
const col = cursor - curStart;
|
||||
const nextStart = nextNl + 1;
|
||||
const followingNl = value.indexOf("\n", nextStart);
|
||||
const nextLen = (followingNl === -1 ? value.length : followingNl) - nextStart;
|
||||
return nextStart + Math.min(col, nextLen);
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
/**
|
||||
* Collapse long user-typed input for display purposes.
|
||||
*
|
||||
* Problem: pasting a stack trace, log dump, or sample file into the
|
||||
* prompt box floods the Historical scrollback with a huge block — the
|
||||
* user can't see their previous turns, the assistant's replies, or
|
||||
* where the cursor is. Terminal UIs have shipped this shape for
|
||||
* years (iTerm's "pasted text" notation, Claude Code's preview).
|
||||
*
|
||||
* Split of concerns: the MODEL still gets the full text. This helper
|
||||
* only rewrites what we render in the Historical row. `@` expansions
|
||||
* and `!` bang outputs have their own display paths (unaffected).
|
||||
*/
|
||||
|
||||
/** Defaults tuned to typical prose vs. typical code-paste shapes. */
|
||||
export const DEFAULT_PASTE_LINE_THRESHOLD = 40;
|
||||
export const DEFAULT_PASTE_CHAR_THRESHOLD = 2000;
|
||||
/** Lines kept visible at the head of a collapsed paste. */
|
||||
export const DEFAULT_PASTE_HEAD_LINES = 10;
|
||||
|
||||
export interface PasteCollapseOptions {
|
||||
lineThreshold?: number;
|
||||
charThreshold?: number;
|
||||
headLines?: number;
|
||||
}
|
||||
|
||||
export interface PasteCollapseResult {
|
||||
/** Text to render in the Historical row (possibly collapsed). */
|
||||
displayText: string;
|
||||
/** True when collapsing happened. False = input passed through verbatim. */
|
||||
collapsed: boolean;
|
||||
/** Original char length — exposed so callers can log/annotate. */
|
||||
originalChars: number;
|
||||
/** Original line count. */
|
||||
originalLines: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Collapse `input` when it exceeds either the line OR char threshold.
|
||||
* Display shape:
|
||||
*
|
||||
* ▸ pasted 2.3 KB (84 lines) — first 10 shown, full text sent to model
|
||||
* line 1
|
||||
* line 2
|
||||
* …
|
||||
* line 10
|
||||
* … (74 more lines)
|
||||
*
|
||||
* Short input passes through unchanged — collapsed = false.
|
||||
*/
|
||||
export function formatLongPaste(
|
||||
input: string,
|
||||
opts: PasteCollapseOptions = {},
|
||||
): PasteCollapseResult {
|
||||
const lineCap = opts.lineThreshold ?? DEFAULT_PASTE_LINE_THRESHOLD;
|
||||
const charCap = opts.charThreshold ?? DEFAULT_PASTE_CHAR_THRESHOLD;
|
||||
const headN = Math.max(1, opts.headLines ?? DEFAULT_PASTE_HEAD_LINES);
|
||||
|
||||
const originalChars = input.length;
|
||||
const lines = input.split("\n");
|
||||
const originalLines = lines.length;
|
||||
|
||||
if (originalChars <= charCap && originalLines <= lineCap) {
|
||||
return { displayText: input, collapsed: false, originalChars, originalLines };
|
||||
}
|
||||
|
||||
const header = `▸ pasted ${formatBytes(originalChars)} (${originalLines} lines) — first ${Math.min(headN, originalLines)} shown, full text sent to model`;
|
||||
const head = lines.slice(0, headN).join("\n");
|
||||
const remaining = originalLines - headN;
|
||||
const footer = remaining > 0 ? `… (${remaining} more line${remaining === 1 ? "" : "s"})` : "";
|
||||
const displayText = footer ? `${header}\n${head}\n${footer}` : `${header}\n${head}`;
|
||||
return { displayText, collapsed: true, originalChars, originalLines };
|
||||
}
|
||||
|
||||
function formatBytes(n: number): string {
|
||||
if (n < 1024) return `${n} B`;
|
||||
const kb = n / 1024;
|
||||
if (kb < 1024) return `${kb.toFixed(kb >= 10 ? 0 : 1)} KB`;
|
||||
const mb = kb / 1024;
|
||||
return `${mb.toFixed(mb >= 10 ? 0 : 1)} MB`;
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
/**
|
||||
* Paste sentinels — represent a pasted blob as a single codepoint in
|
||||
* the input buffer instead of inlining its full contents.
|
||||
*
|
||||
* Why: a 3000-line paste shoved verbatim into the buffer drowns the
|
||||
* surrounding typed text, costs a lot to render per keystroke, and
|
||||
* makes navigation/clear awkward. Replace it with one PUA char (a
|
||||
* "sentinel") and store the real content in a side registry. The
|
||||
* buffer string stays small, the user types around the sentinel as
|
||||
* if it were a single character, and a Backspace at the sentinel
|
||||
* deletes the whole paste in one stroke. On submit we expand the
|
||||
* sentinels back to real content.
|
||||
*
|
||||
* Encoding:
|
||||
* - One codepoint per paste, in PUA range U+E100..U+E1FF (256 slots).
|
||||
* - The codepoint's offset within that range is the paste id.
|
||||
* - That gives us 256 distinct paste blobs per session before ids
|
||||
* wrap. In practice users paste a handful per session — wrap is
|
||||
* a non-issue, but if it happens, the new paste overwrites the
|
||||
* oldest registry entry; any stale sentinels still in the buffer
|
||||
* will render with a "(missing)" badge so the user can clean up.
|
||||
*
|
||||
* Range chosen from the Supplementary PUA-A region's neighbor (BMP
|
||||
* PUA) so a single `String.fromCharCode` works — no surrogate pairs,
|
||||
* no `length === 2` weirdness for cursor arithmetic.
|
||||
*/
|
||||
|
||||
export const PASTE_SENTINEL_BASE = 0xe100;
|
||||
export const PASTE_SENTINEL_RANGE = 256;
|
||||
export const PASTE_SENTINEL_END = PASTE_SENTINEL_BASE + PASTE_SENTINEL_RANGE;
|
||||
|
||||
export interface PasteEntry {
|
||||
id: number;
|
||||
content: string;
|
||||
lineCount: number;
|
||||
charCount: number;
|
||||
}
|
||||
|
||||
export function encodePasteSentinel(id: number): string {
|
||||
if (id < 0 || id >= PASTE_SENTINEL_RANGE) {
|
||||
throw new Error(`paste sentinel id ${id} out of range [0, ${PASTE_SENTINEL_RANGE})`);
|
||||
}
|
||||
return String.fromCharCode(PASTE_SENTINEL_BASE + id);
|
||||
}
|
||||
|
||||
/** Returns the paste id, or `null` if `ch` is not a sentinel codepoint. */
|
||||
export function decodePasteSentinel(ch: string): number | null {
|
||||
if (ch.length === 0) return null;
|
||||
const cp = ch.charCodeAt(0);
|
||||
if (cp < PASTE_SENTINEL_BASE || cp >= PASTE_SENTINEL_END) return null;
|
||||
return cp - PASTE_SENTINEL_BASE;
|
||||
}
|
||||
|
||||
export function isPasteSentinel(ch: string): boolean {
|
||||
return decodePasteSentinel(ch) !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a PasteEntry from raw paste content. Computes line + char
|
||||
* counts once at registration time so the renderer doesn't re-count
|
||||
* on every keystroke.
|
||||
*/
|
||||
export function makePasteEntry(id: number, content: string): PasteEntry {
|
||||
return {
|
||||
id,
|
||||
content,
|
||||
lineCount: content.split("\n").length,
|
||||
charCount: content.length,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Expand every sentinel in `text` back to its registered paste
|
||||
* content. Unknown sentinels (entry missing — registry was wiped, or
|
||||
* id wrap collision) drop to empty string so the resulting prompt
|
||||
* doesn't carry a literal PUA codepoint to the model.
|
||||
*
|
||||
* Used at submit time to recover the full prompt the user composed.
|
||||
*/
|
||||
export function expandPasteSentinels(
|
||||
text: string,
|
||||
pastes: ReadonlyMap<number, PasteEntry>,
|
||||
): string {
|
||||
let out = "";
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
const ch = text[i]!;
|
||||
const id = decodePasteSentinel(ch);
|
||||
if (id === null) {
|
||||
out += ch;
|
||||
continue;
|
||||
}
|
||||
const entry = pastes.get(id);
|
||||
out += entry?.content ?? "";
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Quick check: does the buffer contain ANY sentinel? Used to gate
|
||||
* UI hints (the "paste #N" listing in the prompt-box footer) without
|
||||
* walking the whole buffer twice.
|
||||
*/
|
||||
export function bufferHasPaste(text: string): boolean {
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
if (decodePasteSentinel(text[i]!) !== null) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Walk the buffer and return the ids of every sentinel still
|
||||
* present, in source order. Used by the registry's GC pass at
|
||||
* submit time so unreachable paste entries don't accumulate.
|
||||
* (No-op when the buffer is sentinel-free.)
|
||||
*/
|
||||
export function listPasteIdsInBuffer(text: string): number[] {
|
||||
const ids: number[] = [];
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
const id = decodePasteSentinel(text[i]!);
|
||||
if (id !== null) ids.push(id);
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format `1234` chars as `1.2KB` etc. Tiny helper used in placeholder
|
||||
* labels — kept here so paste-related display logic is co-located.
|
||||
*/
|
||||
export function formatBytesShort(n: number): string {
|
||||
if (n < 1024) return `${n}B`;
|
||||
if (n < 1024 * 1024) return `${(n / 1024).toFixed(n < 1024 * 10 ? 1 : 0)}KB`;
|
||||
return `${(n / (1024 * 1024)).toFixed(1)}MB`;
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
/**
|
||||
* One place that defines what each preset means. Both `slash.ts`
|
||||
* (in-chat `/preset`) and the wizard (first-run setup) read from here.
|
||||
*
|
||||
* Presets are the single vocabulary we teach new users: they don't need
|
||||
* to know model IDs, reasoning effort, or thinking mode independently
|
||||
* — they pick "fast / smart / max" and we translate.
|
||||
*
|
||||
* Design rules (v0.6+):
|
||||
* - Branching (`branch >= 2`) is NEVER in a preset. Self-consistency
|
||||
* sampling is `N×` cost; auto-enabling it would ambush users into
|
||||
* multi-dollar turns without asking. Opt-in only via `/branch N`.
|
||||
* - Harvest (Pillar-2 plan-state extraction) is NEVER in a preset.
|
||||
* In practice it's display sugar — the typed plan state hasn't
|
||||
* fed back into orchestration decisions (branch trigger) often
|
||||
* enough to pay for the extra round-trip. Opt-in only via
|
||||
* `/harvest on`.
|
||||
* - The three tiers differ on only TWO knobs: model (flash/pro) and
|
||||
* reasoning effort (high/max). Same on-the-wire billing axis,
|
||||
* easy to reason about, easy to budget.
|
||||
*/
|
||||
|
||||
import type { PresetName } from "../../config.js";
|
||||
|
||||
export interface PresetSettings {
|
||||
model: string;
|
||||
/**
|
||||
* Reasoning-effort cap sent per turn. `high` = shorter chain of
|
||||
* thought (cheaper, faster); `max` = agent-class default (deeper,
|
||||
* more output tokens). DeepSeek ignores this field on non-thinking
|
||||
* calls, so it's safe to pin across models.
|
||||
*/
|
||||
reasoningEffort: "high" | "max";
|
||||
/**
|
||||
* Pillar-2 plan-state extraction. Every preset ships `false` (see
|
||||
* module header); kept in the shape so a user who later flips it on
|
||||
* at runtime still round-trips cleanly. `/harvest on` toggles it.
|
||||
*/
|
||||
harvest: boolean;
|
||||
/**
|
||||
* Branch budget. Every preset ships `1` (off). `/branch N` with
|
||||
* N>=2 is the only way to enable self-consistency sampling.
|
||||
*/
|
||||
branch: number;
|
||||
}
|
||||
|
||||
export const PRESETS: Record<PresetName, PresetSettings> = {
|
||||
// fast — flash + effort=high. Quick Q&A, one-line tweaks, anything
|
||||
// where shallow reasoning is enough. Cheapest turn possible.
|
||||
fast: { model: "deepseek-v4-flash", reasoningEffort: "high", harvest: false, branch: 1 },
|
||||
// smart — flash + effort=max. Full thinking budget on the cheap
|
||||
// model. The default: handles 90%+ of coding work at a fraction
|
||||
// of pro's cost.
|
||||
smart: { model: "deepseek-v4-flash", reasoningEffort: "max", harvest: false, branch: 1 },
|
||||
// max — pro + effort=max. Frontier model for hard tasks: cross-
|
||||
// file architecture, subtle bug hunts, anything where flash's
|
||||
// reasoning has measurably failed. ~12× per-token vs flash; save
|
||||
// for when you need it, or use `/pro` to escalate a single turn.
|
||||
max: { model: "deepseek-v4-pro", reasoningEffort: "max", harvest: false, branch: 1 },
|
||||
};
|
||||
|
||||
export const PRESET_DESCRIPTIONS: Record<PresetName, { headline: string; cost: string }> = {
|
||||
fast: {
|
||||
headline: "v4-flash · effort=high",
|
||||
cost: "cheapest · quick Q&A, one-line edits",
|
||||
},
|
||||
smart: {
|
||||
headline: "v4-flash · effort=max",
|
||||
cost: "~1.5× fast · default · day-to-day coding",
|
||||
},
|
||||
max: {
|
||||
headline: "v4-pro · effort=max",
|
||||
cost: "~12× fast · hard single-shots · use /pro for a single-turn bump",
|
||||
},
|
||||
};
|
||||
|
||||
export function resolvePreset(name: PresetName | undefined): PresetSettings {
|
||||
return PRESETS[name ?? "smart"];
|
||||
}
|
||||
+20
-157
@@ -1,157 +1,20 @@
|
||||
import type { CacheFirstLoop } from "../../loop.js";
|
||||
import { deleteSession, listSessions } from "../../session.js";
|
||||
|
||||
export interface SlashResult {
|
||||
/** Text to display back to the user as a system/info line. */
|
||||
info?: string;
|
||||
/** Exit the app. */
|
||||
exit?: boolean;
|
||||
/** Clear the visible history. */
|
||||
clear?: boolean;
|
||||
/** Unknown command — display usage hint. */
|
||||
unknown?: boolean;
|
||||
}
|
||||
|
||||
export function parseSlash(text: string): { cmd: string; args: string[] } | null {
|
||||
if (!text.startsWith("/")) return null;
|
||||
const parts = text.slice(1).trim().split(/\s+/);
|
||||
const cmd = parts[0]?.toLowerCase() ?? "";
|
||||
if (!cmd) return null;
|
||||
return { cmd, args: parts.slice(1) };
|
||||
}
|
||||
|
||||
export function handleSlash(cmd: string, args: string[], loop: CacheFirstLoop): SlashResult {
|
||||
switch (cmd) {
|
||||
case "exit":
|
||||
case "quit":
|
||||
return { exit: true };
|
||||
|
||||
case "clear":
|
||||
return { clear: true };
|
||||
|
||||
case "help":
|
||||
case "?":
|
||||
return {
|
||||
info: [
|
||||
"Commands:",
|
||||
" /help this message",
|
||||
" /status show current settings",
|
||||
" /preset <fast|smart|max> one-tap presets — see below",
|
||||
" /model <id> deepseek-chat or deepseek-reasoner",
|
||||
" /harvest [on|off] Pillar 2: structured plan-state extraction",
|
||||
" /branch <N|off> run N parallel samples (N>=2), pick most confident",
|
||||
" /sessions list saved sessions (current is marked with ▸)",
|
||||
" /forget delete the current session from disk",
|
||||
" /clear clear displayed history (log + session kept)",
|
||||
" /exit quit",
|
||||
"",
|
||||
"Presets:",
|
||||
" fast deepseek-chat no harvest no branch ~1¢/100turns ← default",
|
||||
" smart reasoner harvest ~10x cost, slower",
|
||||
" max reasoner harvest branch 3 ~30x cost, slowest",
|
||||
"",
|
||||
"Sessions (auto-enabled by default, named 'default'):",
|
||||
" reasonix chat --session <name> use a different named session",
|
||||
" reasonix chat --no-session disable persistence for this run",
|
||||
].join("\n"),
|
||||
};
|
||||
|
||||
case "sessions": {
|
||||
const items = listSessions();
|
||||
if (items.length === 0) {
|
||||
return {
|
||||
info: "no saved sessions yet — chat normally and your messages will be saved automatically",
|
||||
};
|
||||
}
|
||||
const lines = ["Saved sessions:"];
|
||||
for (const s of items) {
|
||||
const sizeKb = (s.size / 1024).toFixed(1);
|
||||
const when = s.mtime.toISOString().replace("T", " ").slice(0, 16);
|
||||
const marker = s.name === loop.sessionName ? "▸" : " ";
|
||||
lines.push(
|
||||
` ${marker} ${s.name.padEnd(22)} ${String(s.messageCount).padStart(5)} msgs ${sizeKb.padStart(7)} KB ${when}`,
|
||||
);
|
||||
}
|
||||
lines.push("");
|
||||
lines.push("Resume with: reasonix chat --session <name>");
|
||||
return { info: lines.join("\n") };
|
||||
}
|
||||
|
||||
case "forget": {
|
||||
if (!loop.sessionName) {
|
||||
return { info: "not in a session — nothing to forget" };
|
||||
}
|
||||
const name = loop.sessionName;
|
||||
const ok = deleteSession(name);
|
||||
return {
|
||||
info: ok
|
||||
? `▸ deleted session "${name}" — current screen still shows the conversation, but next launch starts fresh`
|
||||
: `could not delete session "${name}" (already gone?)`,
|
||||
};
|
||||
}
|
||||
|
||||
case "status": {
|
||||
const branchBudget = loop.branchOptions.budget ?? 1;
|
||||
return {
|
||||
info:
|
||||
`model=${loop.model} ` +
|
||||
`harvest=${loop.harvestEnabled ? "on" : "off"} ` +
|
||||
`branch=${branchBudget > 1 ? branchBudget : "off"} ` +
|
||||
`stream=${loop.stream ? "on" : "off"}`,
|
||||
};
|
||||
}
|
||||
|
||||
case "model": {
|
||||
const id = args[0];
|
||||
if (!id) return { info: "usage: /model <id> (try deepseek-chat or deepseek-reasoner)" };
|
||||
loop.configure({ model: id });
|
||||
return { info: `model → ${id}` };
|
||||
}
|
||||
|
||||
case "harvest": {
|
||||
const arg = (args[0] ?? "").toLowerCase();
|
||||
const on = arg === "" ? !loop.harvestEnabled : arg === "on" || arg === "true" || arg === "1";
|
||||
loop.configure({ harvest: on });
|
||||
return { info: `harvest → ${loop.harvestEnabled ? "on" : "off"}` };
|
||||
}
|
||||
|
||||
case "preset": {
|
||||
const name = (args[0] ?? "").toLowerCase();
|
||||
if (name === "fast" || name === "default") {
|
||||
loop.configure({ model: "deepseek-chat", harvest: false, branch: 1 });
|
||||
return { info: "preset → fast (deepseek-chat, no harvest, no branch)" };
|
||||
}
|
||||
if (name === "smart") {
|
||||
loop.configure({ model: "deepseek-reasoner", harvest: true, branch: 1 });
|
||||
return { info: "preset → smart (reasoner + harvest, ~10x cost vs fast)" };
|
||||
}
|
||||
if (name === "max" || name === "best") {
|
||||
loop.configure({ model: "deepseek-reasoner", harvest: true, branch: 3 });
|
||||
return {
|
||||
info: "preset → max (reasoner + harvest + branch3, ~30x cost vs fast, slowest)",
|
||||
};
|
||||
}
|
||||
return { info: "usage: /preset <fast|smart|max>" };
|
||||
}
|
||||
|
||||
case "branch": {
|
||||
const raw = (args[0] ?? "").toLowerCase();
|
||||
if (raw === "" || raw === "off" || raw === "0" || raw === "1") {
|
||||
loop.configure({ branch: 1 });
|
||||
return { info: "branch → off" };
|
||||
}
|
||||
const n = Number.parseInt(raw, 10);
|
||||
if (!Number.isFinite(n) || n < 2) {
|
||||
return { info: "usage: /branch <N> (N>=2, or 'off')" };
|
||||
}
|
||||
if (n > 8) {
|
||||
return { info: "branch budget capped at 8 to prevent runaway cost" };
|
||||
}
|
||||
loop.configure({ branch: n });
|
||||
return { info: `branch → ${n} (harvest auto-enabled; streaming disabled)` };
|
||||
}
|
||||
|
||||
default:
|
||||
return { unknown: true, info: `unknown command: /${cmd} (try /help)` };
|
||||
}
|
||||
}
|
||||
// Slash-command barrel. Public surface is stable across the slash/
|
||||
// split — App.tsx, tests, and sibling components continue to import
|
||||
// { handleSlash, parseSlash, suggestSlashCommands, SLASH_COMMANDS, ... }
|
||||
// from "./slash.js". Everything below is re-exported from the per-topic
|
||||
// modules under ./slash/.
|
||||
export {
|
||||
SLASH_COMMANDS,
|
||||
detectSlashArgContext,
|
||||
parseSlash,
|
||||
suggestSlashCommands,
|
||||
} from "./slash/commands.js";
|
||||
export { handleSlash } from "./slash/dispatch.js";
|
||||
export type { SlashHandler } from "./slash/dispatch.js";
|
||||
export type {
|
||||
McpServerSummary,
|
||||
SlashArgContext,
|
||||
SlashCommandSpec,
|
||||
SlashContext,
|
||||
SlashResult,
|
||||
} from "./slash/types.js";
|
||||
@@ -0,0 +1,219 @@
|
||||
import type { SlashArgContext, SlashCommandSpec } from "./types.js";
|
||||
|
||||
export const SLASH_COMMANDS: readonly SlashCommandSpec[] = [
|
||||
{ cmd: "help", summary: "show the full command reference" },
|
||||
{ cmd: "status", summary: "current model, flags, context, session" },
|
||||
{
|
||||
cmd: "preset",
|
||||
argsHint: "<fast|smart|max>",
|
||||
summary: "one-tap model + harvest + branch bundle",
|
||||
argCompleter: ["fast", "smart", "max"],
|
||||
},
|
||||
{
|
||||
cmd: "model",
|
||||
argsHint: "<id>",
|
||||
summary: "switch DeepSeek model id",
|
||||
argCompleter: "models",
|
||||
},
|
||||
{ cmd: "models", summary: "list available models fetched from DeepSeek /models" },
|
||||
{
|
||||
cmd: "harvest",
|
||||
argsHint: "[on|off]",
|
||||
summary: "toggle Pillar-2 plan-state extraction",
|
||||
argCompleter: ["on", "off"],
|
||||
},
|
||||
{
|
||||
cmd: "branch",
|
||||
argsHint: "<N|off>",
|
||||
summary: "run N parallel samples per turn (N>=2)",
|
||||
argCompleter: ["off", "2", "3", "4", "5"],
|
||||
},
|
||||
{
|
||||
cmd: "effort",
|
||||
argsHint: "<high|max>",
|
||||
summary: "reasoning_effort cap — max is default (agent-class), high is cheaper/faster",
|
||||
argCompleter: ["max", "high"],
|
||||
},
|
||||
{
|
||||
cmd: "pro",
|
||||
argsHint: "[off]",
|
||||
summary: "arm v4-pro for the NEXT turn only (one-shot · auto-disarms after turn)",
|
||||
argCompleter: ["off"],
|
||||
},
|
||||
{ cmd: "mcp", summary: "list MCP servers + tools attached to this session" },
|
||||
{
|
||||
cmd: "resource",
|
||||
argsHint: "[uri]",
|
||||
summary: "browse + read MCP resources (no arg → list URIs; <uri> → fetch contents)",
|
||||
argCompleter: "mcp-resources",
|
||||
},
|
||||
{
|
||||
cmd: "prompt",
|
||||
argsHint: "[name]",
|
||||
summary: "browse + fetch MCP prompts (no arg → list names; <name> → render prompt)",
|
||||
argCompleter: "mcp-prompts",
|
||||
},
|
||||
{ cmd: "tool", argsHint: "[N]", summary: "dump full output of the Nth tool call (1=latest)" },
|
||||
{
|
||||
cmd: "memory",
|
||||
argsHint: "[list|show <name>|forget <name>|clear <scope> confirm]",
|
||||
summary: "show / manage pinned memory (REASONIX.md + ~/.reasonix/memory)",
|
||||
},
|
||||
{
|
||||
cmd: "skill",
|
||||
argsHint: "[list|show <name>|<name> [args]]",
|
||||
summary: "list / run user skills (<project>/.reasonix/skills + ~/.reasonix/skills)",
|
||||
},
|
||||
{
|
||||
cmd: "hooks",
|
||||
argsHint: "[reload]",
|
||||
summary: "list active hooks (settings.json under .reasonix/) · reload re-reads from disk",
|
||||
},
|
||||
{
|
||||
cmd: "update",
|
||||
summary: "show current vs latest version + the shell command to upgrade",
|
||||
},
|
||||
{
|
||||
cmd: "stats",
|
||||
summary:
|
||||
"cross-session cost dashboard (today / week / month / all-time · cache hit · vs Claude)",
|
||||
},
|
||||
{ cmd: "think", summary: "dump the last turn's full R1 reasoning (reasoner only)" },
|
||||
{
|
||||
cmd: "context",
|
||||
summary: "break down where context tokens are going: system / tools / per-turn log",
|
||||
},
|
||||
{ cmd: "retry", summary: "truncate & resend your last message (fresh sample)" },
|
||||
{
|
||||
cmd: "compact",
|
||||
argsHint: "[tokens]",
|
||||
summary:
|
||||
"shrink oversized tool results AND tool-call args (edit_file search/replace) in the log; cap in tokens, default 4000",
|
||||
},
|
||||
{ cmd: "keys", summary: "show all keyboard shortcuts and prompt prefixes" },
|
||||
{ cmd: "plans", summary: "list this session's active + archived plans, newest first" },
|
||||
{
|
||||
cmd: "replay",
|
||||
summary: "load an archived plan as a read-only Time Travel snapshot (default: newest)",
|
||||
argsHint: "[N]",
|
||||
},
|
||||
{ cmd: "sessions", summary: "list saved sessions (current marked with ▸)" },
|
||||
{ cmd: "forget", summary: "delete the current session from disk" },
|
||||
{ cmd: "setup", summary: "reminds you to exit and run `reasonix setup`" },
|
||||
{ cmd: "clear", summary: "clear visible scrollback only (log/context kept)" },
|
||||
{ cmd: "new", summary: "start a fresh conversation (clear context + scrollback)" },
|
||||
{ cmd: "exit", summary: "quit the TUI" },
|
||||
// Code-mode only
|
||||
{ cmd: "apply", summary: "commit pending edit blocks to disk", contextual: "code" },
|
||||
{ cmd: "discard", summary: "drop pending edit blocks without writing", contextual: "code" },
|
||||
{ cmd: "undo", summary: "roll back the last applied edit batch", contextual: "code" },
|
||||
{
|
||||
cmd: "history",
|
||||
summary: "list every edit batch this session (ids for /show, undone markers)",
|
||||
contextual: "code",
|
||||
},
|
||||
{
|
||||
cmd: "show",
|
||||
argsHint: "[id]",
|
||||
summary: "dump a stored edit diff (omit id for newest non-undone)",
|
||||
contextual: "code",
|
||||
},
|
||||
{
|
||||
cmd: "commit",
|
||||
argsHint: '"msg"',
|
||||
summary: "git add -A && git commit -m ...",
|
||||
contextual: "code",
|
||||
},
|
||||
{
|
||||
cmd: "plan",
|
||||
argsHint: "[on|off]",
|
||||
summary: "toggle read-only plan mode (writes bounced until submit_plan + approval)",
|
||||
contextual: "code",
|
||||
argCompleter: ["on", "off"],
|
||||
},
|
||||
{
|
||||
cmd: "apply-plan",
|
||||
summary: "force-approve a pending / in-text plan (fallback if picker was missed)",
|
||||
contextual: "code",
|
||||
},
|
||||
{
|
||||
cmd: "mode",
|
||||
argsHint: "[review|auto]",
|
||||
summary: "edit-gate: review (queue for /apply) or auto (apply+undo banner). Shift+Tab cycles.",
|
||||
contextual: "code",
|
||||
argCompleter: ["review", "auto"],
|
||||
},
|
||||
{ cmd: "jobs", summary: "list background jobs started by run_background", contextual: "code" },
|
||||
{
|
||||
cmd: "kill",
|
||||
argsHint: "<id>",
|
||||
summary: "stop a background job by id (SIGTERM → SIGKILL after grace)",
|
||||
contextual: "code",
|
||||
},
|
||||
{
|
||||
cmd: "logs",
|
||||
argsHint: "<id> [lines]",
|
||||
summary: "tail a background job's output (default last 80 lines)",
|
||||
contextual: "code",
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
* Filter the registry by a prefix string (without the leading `/`).
|
||||
* Empty prefix returns the full non-contextual list (plus code-mode
|
||||
* entries when `codeMode` is true). Case-insensitive.
|
||||
*/
|
||||
export function suggestSlashCommands(prefix: string, codeMode = false): SlashCommandSpec[] {
|
||||
const p = prefix.toLowerCase();
|
||||
return SLASH_COMMANDS.filter((c) => {
|
||||
if (c.contextual === "code" && !codeMode) return false;
|
||||
return c.cmd.startsWith(p);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Classify the prompt buffer for argument completion. Returns `null`
|
||||
* when the buffer isn't in a slash-with-args state.
|
||||
*
|
||||
* Firing shape: input must start with `/<cmd> ` (space after a known
|
||||
* command). The character right after the space through end-of-buffer
|
||||
* is the "arg tail"; if the tail has NO internal whitespace the
|
||||
* picker is live (tail is the partial). If the tail has whitespace,
|
||||
* the user has moved past the first argument position and we surface
|
||||
* the usage hint only.
|
||||
*/
|
||||
export function detectSlashArgContext(input: string, codeMode = false): SlashArgContext | null {
|
||||
// `/cmd <rest>` — one space, rest captured up to end-of-buffer.
|
||||
const m = /^\/(\S+) ([\s\S]*)$/.exec(input);
|
||||
if (!m) return null;
|
||||
const cmdName = m[1]!.toLowerCase();
|
||||
const tail = m[2] ?? "";
|
||||
const spec = SLASH_COMMANDS.find(
|
||||
(s) => s.cmd === cmdName && (s.contextual !== "code" || codeMode),
|
||||
);
|
||||
if (!spec) return null;
|
||||
const hasInternalSpace = /\s/.test(tail);
|
||||
const partialOffset = input.length - tail.length;
|
||||
if (hasInternalSpace) {
|
||||
// Past the first arg position (typing the second arg for e.g.
|
||||
// `/edit <file> <instruction>`, or mid-sentence for free-form).
|
||||
return { spec, partial: tail, partialOffset, kind: "hint" };
|
||||
}
|
||||
// No internal whitespace — we're still typing the first arg. Picker
|
||||
// is live if the spec declares a completer; otherwise show a hint
|
||||
// ("what goes here?") since the user's guessing.
|
||||
return {
|
||||
spec,
|
||||
partial: tail,
|
||||
partialOffset,
|
||||
kind: spec.argCompleter ? "picker" : "hint",
|
||||
};
|
||||
}
|
||||
|
||||
export function parseSlash(text: string): { cmd: string; args: string[] } | null {
|
||||
if (!text.startsWith("/")) return null;
|
||||
const parts = text.slice(1).trim().split(/\s+/);
|
||||
const cmd = parts[0]?.toLowerCase() ?? "";
|
||||
if (!cmd) return null;
|
||||
return { cmd, args: parts.slice(1) };
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import type { CacheFirstLoop } from "../../../loop.js";
|
||||
import { handlers as adminHandlers } from "./handlers/admin.js";
|
||||
import { handlers as basicHandlers } from "./handlers/basic.js";
|
||||
import { handlers as editsHandlers } from "./handlers/edits.js";
|
||||
import { handlers as jobsHandlers } from "./handlers/jobs.js";
|
||||
import { handlers as mcpHandlers } from "./handlers/mcp.js";
|
||||
import { handlers as memoryHandlers } from "./handlers/memory.js";
|
||||
import { handlers as modelHandlers } from "./handlers/model.js";
|
||||
import { handlers as observabilityHandlers } from "./handlers/observability.js";
|
||||
import { handlers as plansHandlers } from "./handlers/plans.js";
|
||||
import { handlers as sessionsHandlers } from "./handlers/sessions.js";
|
||||
import { handlers as skillHandlers } from "./handlers/skill.js";
|
||||
import type { SlashContext, SlashResult } from "./types.js";
|
||||
|
||||
/**
|
||||
* A slash handler receives the command's args + the loop + shared
|
||||
* runtime context, and returns a synchronous SlashResult. Async work
|
||||
* (balance fetches, stop_job) fires-and-forgets via `ctx.postInfo`
|
||||
* instead — keeps the TUI input non-blocking.
|
||||
*/
|
||||
export type SlashHandler = (args: string[], loop: CacheFirstLoop, ctx: SlashContext) => SlashResult;
|
||||
|
||||
/**
|
||||
* Flat map of cmd → handler. Composed from per-topic modules so each
|
||||
* feature's logic stays local; aliases (e.g. `exit` / `quit`) are just
|
||||
* extra keys in the per-module handlers bag pointing at the same fn.
|
||||
*
|
||||
* Ordering of the spread matters only for duplicate keys; there are
|
||||
* none. Keep alphabetical for diff sanity when adding modules.
|
||||
*/
|
||||
const HANDLERS: Record<string, SlashHandler> = {
|
||||
...adminHandlers,
|
||||
...basicHandlers,
|
||||
...editsHandlers,
|
||||
...jobsHandlers,
|
||||
...mcpHandlers,
|
||||
...memoryHandlers,
|
||||
...modelHandlers,
|
||||
...observabilityHandlers,
|
||||
...plansHandlers,
|
||||
...sessionsHandlers,
|
||||
...skillHandlers,
|
||||
};
|
||||
|
||||
export function handleSlash(
|
||||
cmd: string,
|
||||
args: string[],
|
||||
loop: CacheFirstLoop,
|
||||
ctx: SlashContext = {},
|
||||
): SlashResult {
|
||||
const h = HANDLERS[cmd];
|
||||
if (h) return h(args, loop, ctx);
|
||||
return { unknown: true, info: `unknown command: /${cmd} (try /help)` };
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
import {
|
||||
HOOK_EVENTS,
|
||||
type HookEvent,
|
||||
type ResolvedHook,
|
||||
globalSettingsPath,
|
||||
projectSettingsPath,
|
||||
} from "../../../../hooks.js";
|
||||
import { aggregateUsage, defaultUsageLogPath, readUsageLog } from "../../../../usage.js";
|
||||
import { VERSION, compareVersions, isNpxInstall } from "../../../../version.js";
|
||||
import { renderDashboard } from "../../../commands/stats.js";
|
||||
import type { SlashHandler } from "../dispatch.js";
|
||||
|
||||
const hooks: SlashHandler = (args, loop, ctx) => {
|
||||
const sub = (args[0] ?? "").toLowerCase();
|
||||
|
||||
if (sub === "reload") {
|
||||
if (!ctx.reloadHooks) {
|
||||
return {
|
||||
info: "/hooks reload is not available in this context (no reload callback wired).",
|
||||
};
|
||||
}
|
||||
const count = ctx.reloadHooks();
|
||||
return { info: `▸ reloaded hooks · ${count} active` };
|
||||
}
|
||||
|
||||
if (sub !== "" && sub !== "list" && sub !== "ls") {
|
||||
return {
|
||||
info: "usage: /hooks list active hooks\n /hooks reload re-read settings.json files",
|
||||
};
|
||||
}
|
||||
|
||||
const all = loop.hooks;
|
||||
const projPath = ctx.codeRoot ? projectSettingsPath(ctx.codeRoot) : undefined;
|
||||
const globPath = globalSettingsPath();
|
||||
if (all.length === 0) {
|
||||
const lines = [
|
||||
"no hooks configured.",
|
||||
"",
|
||||
"drop a settings.json with a `hooks` key into either of:",
|
||||
ctx.codeRoot
|
||||
? ` · ${projPath} (project)`
|
||||
: " · <project>/.reasonix/settings.json (project)",
|
||||
` · ${globPath} (global)`,
|
||||
"",
|
||||
"events: PreToolUse, PostToolUse, UserPromptSubmit, Stop",
|
||||
"exit 0 = pass · exit 2 = block (Pre*) · other = warn",
|
||||
];
|
||||
return { info: lines.join("\n") };
|
||||
}
|
||||
|
||||
const grouped = new Map<HookEvent, ResolvedHook[]>();
|
||||
for (const event of HOOK_EVENTS) grouped.set(event, []);
|
||||
for (const h of all) grouped.get(h.event)?.push(h);
|
||||
|
||||
const lines: string[] = [`▸ ${all.length} hook(s) loaded`];
|
||||
for (const event of HOOK_EVENTS) {
|
||||
const list = grouped.get(event) ?? [];
|
||||
if (list.length === 0) continue;
|
||||
lines.push("", `${event}:`);
|
||||
for (const h of list) {
|
||||
const match = h.match && h.match !== "*" ? ` match=${h.match}` : "";
|
||||
const desc = h.description ? ` — ${h.description}` : "";
|
||||
lines.push(` [${h.scope}]${match} ${h.command}${desc}`);
|
||||
}
|
||||
}
|
||||
lines.push("", `sources: project=${projPath ?? "(none — chat mode)"} · global=${globPath}`);
|
||||
return { info: lines.join("\n") };
|
||||
};
|
||||
|
||||
/**
|
||||
* `/update` — inside the TUI we deliberately do NOT spawn `npm install`.
|
||||
* stdio:inherit into a running Ink renderer corrupts the display, and
|
||||
* the process being upgraded is the same process that's still reading
|
||||
* its own binaries (messy on Windows). Instead we surface what we
|
||||
* already know from the App's background registry check and print the
|
||||
* exact shell command the user should run after exiting.
|
||||
*
|
||||
* The `latestVersion` ctx field is populated by App.tsx's mount-time
|
||||
* `getLatestVersion()` effect. When it's `null` we report the check
|
||||
* as pending/offline — still a useful output (current version + how
|
||||
* to force a fresh check from another terminal).
|
||||
*/
|
||||
const update: SlashHandler = (_args, _loop, ctx) => {
|
||||
const latest = ctx.latestVersion ?? null;
|
||||
const lines: string[] = [`current: reasonix ${VERSION}`];
|
||||
if (latest === null) {
|
||||
// Kick off a fresh fetch so a follow-up /update a few seconds
|
||||
// later has a real answer instead of the same pending message.
|
||||
ctx.refreshLatestVersion?.();
|
||||
lines.push(
|
||||
"latest: (not yet resolved — background check in flight or offline)",
|
||||
"",
|
||||
"triggered a fresh registry fetch — retry `/update` in a few seconds,",
|
||||
"or run `reasonix update` in another terminal to force it synchronously.",
|
||||
);
|
||||
return { info: lines.join("\n") };
|
||||
}
|
||||
lines.push(`latest: reasonix ${latest}`);
|
||||
const diff = compareVersions(VERSION, latest);
|
||||
if (diff >= 0) {
|
||||
lines.push("", "you're on the latest. nothing to do.");
|
||||
return { info: lines.join("\n") };
|
||||
}
|
||||
if (isNpxInstall()) {
|
||||
lines.push(
|
||||
"",
|
||||
"you're running via npx — the next `npx reasonix ...` launch will auto-fetch.",
|
||||
"to force a refresh sooner: `npm cache clean --force`.",
|
||||
);
|
||||
} else {
|
||||
lines.push(
|
||||
"",
|
||||
"to upgrade, exit this session and run:",
|
||||
" reasonix update (interactive, dry-run supported via --dry-run)",
|
||||
" npm install -g reasonix@latest (direct)",
|
||||
"",
|
||||
"in-session install is deliberately disabled — the npm spawn would",
|
||||
"corrupt this TUI's rendering and Windows can lock the running binary.",
|
||||
);
|
||||
}
|
||||
return { info: lines.join("\n") };
|
||||
};
|
||||
|
||||
/**
|
||||
* `/stats` — dashboard view of `~/.reasonix/usage.jsonl`, the same
|
||||
* roll-up `reasonix stats` (no arg) prints at the shell. Synchronous
|
||||
* disk read; cheap enough that we don't bother caching between slash
|
||||
* invocations.
|
||||
*
|
||||
* No transcript-path variant in-TUI: the per-file summary is scripty
|
||||
* and rarely wanted mid-session. If someone needs it they have the
|
||||
* CLI form (`reasonix stats <path>`).
|
||||
*/
|
||||
const stats: SlashHandler = () => {
|
||||
const path = defaultUsageLogPath();
|
||||
const records = readUsageLog(path);
|
||||
if (records.length === 0) {
|
||||
return {
|
||||
info: [
|
||||
"no usage data yet.",
|
||||
"",
|
||||
` ${path}`,
|
||||
"",
|
||||
"every turn you run here appends one record — this session's turns",
|
||||
"will show up in the dashboard once you send a message.",
|
||||
].join("\n"),
|
||||
};
|
||||
}
|
||||
const agg = aggregateUsage(records);
|
||||
return { info: renderDashboard(agg, path) };
|
||||
};
|
||||
|
||||
export const handlers: Record<string, SlashHandler> = {
|
||||
hook: hooks,
|
||||
hooks,
|
||||
update,
|
||||
stats,
|
||||
};
|
||||
@@ -0,0 +1,160 @@
|
||||
import type { SlashHandler } from "../dispatch.js";
|
||||
|
||||
const exit: SlashHandler = () => ({ exit: true });
|
||||
|
||||
const clear: SlashHandler = () => ({
|
||||
clear: true,
|
||||
info: "▸ terminal cleared (viewport + scrollback). Context (message log) is intact — next turn still sees everything. Use /new to start fresh, or /forget to delete the session entirely.",
|
||||
});
|
||||
|
||||
const resetLog: SlashHandler = (_args, loop) => {
|
||||
// Actually drop the in-memory log + rewrite the session file so the
|
||||
// NEXT call has no prior context. Keeps session name, model, and
|
||||
// other config — just the conversation is reset.
|
||||
const { dropped } = loop.clearLog();
|
||||
return {
|
||||
clear: true,
|
||||
info: `▸ new conversation — dropped ${dropped} message(s) from context. Same session, fresh slate.`,
|
||||
};
|
||||
};
|
||||
|
||||
const keys: SlashHandler = () => ({
|
||||
info: [
|
||||
"Keyboard & prompt shortcuts:",
|
||||
"",
|
||||
" Enter submit the current prompt",
|
||||
" Shift+Enter / Ctrl+J insert a newline (multi-line prompt)",
|
||||
" \\<Enter> bash-style line continuation",
|
||||
" ← → ↑ ↓ move cursor / recall history at buffer boundary",
|
||||
" PageUp / PageDown jump to top / bottom of the WHOLE buffer (handy after a big paste)",
|
||||
" Ctrl+A / Ctrl+E jump to start / end of the CURRENT line",
|
||||
" Ctrl+U clear the entire input buffer",
|
||||
" Ctrl+W delete the word before the cursor",
|
||||
" Backspace delete left; Delete delete under cursor",
|
||||
" Esc abort the in-flight turn",
|
||||
" y / n accept / reject pending edits (code mode)",
|
||||
" Shift+Tab cycle edit gate: review ↔ AUTO (code mode, persists to config)",
|
||||
" u undo the latest non-undone edit batch (session-wide, not just banner)",
|
||||
"",
|
||||
"Prompt prefixes:",
|
||||
" /<name> slash command; Tab/Enter picks from the suggestion list",
|
||||
" @<path> inline a file under [Referenced files] (code mode).",
|
||||
" Trailing `@…` opens a file picker; ↑/↓ navigate, Tab/Enter pick.",
|
||||
" !<cmd> run <cmd> as shell in the sandbox root; output goes into context",
|
||||
" so the model sees it next turn. No allowlist gate.",
|
||||
"",
|
||||
"Pickers (slash + @-mention):",
|
||||
" ↑ / ↓ navigate the suggestion list",
|
||||
" Tab insert the highlighted item without submitting",
|
||||
" Enter insert and (slash) run it, (@) keep editing",
|
||||
"",
|
||||
"MCP exploration:",
|
||||
" /mcp servers + tool/resource/prompt counts",
|
||||
" /resource [uri] browse & read resources exposed by your MCP servers",
|
||||
" /prompt [name] browse & fetch prompts exposed by your MCP servers",
|
||||
"",
|
||||
"Useful slashes: /help · /context · /stats · /compact · /new · /exit",
|
||||
].join("\n"),
|
||||
});
|
||||
|
||||
const help: SlashHandler = () => ({
|
||||
info: [
|
||||
"Commands:",
|
||||
" /help this message",
|
||||
" /keys keyboard shortcuts + prompt prefixes (!, @, /)",
|
||||
" /status show current settings",
|
||||
" /preset <fast|smart|max> one-tap presets — see below",
|
||||
" /model <id> deepseek-v4-flash or deepseek-v4-pro",
|
||||
" /pro [off] arm v4-pro for NEXT turn only (one-shot, auto-disarms)",
|
||||
" /harvest [on|off] Pillar 2: structured plan-state extraction (OPT-IN — costs extra)",
|
||||
" /branch <N|off> run N parallel samples (N>=2) — MANUAL ONLY, N× cost",
|
||||
" /effort <high|max> reasoning_effort cap (max=full thinking, high=cheaper/faster)",
|
||||
" /mcp list MCP servers + tools attached to this session",
|
||||
" /resource [uri] browse + read MCP resources (no arg → list URIs; <uri> → fetch)",
|
||||
" /prompt [name] browse + fetch MCP prompts (no arg → list names; <name> → render)",
|
||||
" /setup (exit + reconfigure) → run `reasonix setup`",
|
||||
" /compact [tokens] shrink large tool results in history (default 4000 tokens/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 latest non-undone edit batch",
|
||||
" /history (code mode) list every edit batch this session",
|
||||
" /show [id] (code mode) dump a stored edit diff (newest when id omitted)",
|
||||
' /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)",
|
||||
" /mode [review|auto] (code mode) edit-gate: queue edits for /apply or apply instantly (Shift+Tab cycles, u undoes within 5s)",
|
||||
" /jobs (code mode) list background processes (run_background) — running and exited",
|
||||
" /kill <id> (code mode) stop a background job by id (SIGTERM → SIGKILL)",
|
||||
" /logs <id> [lines] (code mode) tail a background job's output (default 80 lines)",
|
||||
" /sessions list saved sessions (current is marked with ▸)",
|
||||
" /forget delete the current session from disk",
|
||||
" /new start fresh: drop all context + clear scrollback",
|
||||
" /clear clear displayed scrollback only (context kept — model still sees it)",
|
||||
" /exit quit",
|
||||
"",
|
||||
"Shell shortcut:",
|
||||
" !<cmd> run <cmd> in the sandbox root; output goes into",
|
||||
" the conversation so the model sees it next turn.",
|
||||
" No allowlist gate — user-typed = explicit consent.",
|
||||
" Example: !git status !ls src/ !npm test",
|
||||
"",
|
||||
"File references (code mode):",
|
||||
" @path/to/file inline file content under [Referenced files] on send.",
|
||||
" Type `@` to open the picker (↑↓ navigate, Tab/Enter pick).",
|
||||
"",
|
||||
"Presets (branch + harvest are NEVER auto-enabled — opt-in only):",
|
||||
" fast v4-flash · effort=high cheapest · quick Q&A, one-line edits",
|
||||
" smart v4-flash · effort=max ← default · day-to-day coding",
|
||||
" max v4-pro · effort=max ~12× fast · hard single-shots",
|
||||
"",
|
||||
"Sessions (auto-enabled by default, named 'default'):",
|
||||
" reasonix chat --session <name> use a different named session",
|
||||
" reasonix chat --no-session disable persistence for this run",
|
||||
"",
|
||||
"Known limitation:",
|
||||
" Resizing the terminal mid-session may stack ghost header frames in",
|
||||
" scrollback (Ink library's live-region clear doesn't account for line",
|
||||
" re-wrapping at the new width). Scroll-up history is unaffected; the",
|
||||
" artifact is purely visual and clears the next time you /clear.",
|
||||
].join("\n"),
|
||||
});
|
||||
|
||||
const setup: SlashHandler = () => ({
|
||||
info:
|
||||
"To reconfigure (preset, MCP servers, API key), exit this chat and run " +
|
||||
"`reasonix setup`. Changes take effect on next launch.",
|
||||
});
|
||||
|
||||
const retry: SlashHandler = (_args, loop) => {
|
||||
const prev = loop.retryLastUser();
|
||||
if (!prev) {
|
||||
return {
|
||||
info: "nothing to retry — no prior user message in this session's log.",
|
||||
};
|
||||
}
|
||||
const preview = prev.length > 80 ? `${prev.slice(0, 80)}…` : prev;
|
||||
return {
|
||||
info: `▸ retrying: "${preview}"`,
|
||||
resubmit: prev,
|
||||
};
|
||||
};
|
||||
|
||||
export const handlers: Record<string, SlashHandler> = {
|
||||
exit,
|
||||
quit: exit,
|
||||
clear,
|
||||
new: resetLog,
|
||||
reset: resetLog,
|
||||
keys,
|
||||
help,
|
||||
"?": help,
|
||||
setup,
|
||||
retry,
|
||||
};
|
||||
@@ -0,0 +1,142 @@
|
||||
import type { EditMode } from "../../../../config.js";
|
||||
import type { SlashHandler } from "../dispatch.js";
|
||||
import { runGitCommit, stripOuterQuotes } from "../helpers.js";
|
||||
|
||||
const undo: SlashHandler = (args, _loop, ctx) => {
|
||||
if (!ctx.codeUndo) {
|
||||
return {
|
||||
info: "/undo is only available inside `reasonix code` — chat mode doesn't apply edits.",
|
||||
};
|
||||
}
|
||||
return { info: ctx.codeUndo(args) };
|
||||
};
|
||||
|
||||
const history: SlashHandler = (_args, _loop, ctx) => {
|
||||
if (!ctx.codeHistory) {
|
||||
return { info: "/history is only available inside `reasonix code`." };
|
||||
}
|
||||
return { info: ctx.codeHistory() };
|
||||
};
|
||||
|
||||
const show: SlashHandler = (args, _loop, ctx) => {
|
||||
if (!ctx.codeShowEdit) {
|
||||
return { info: "/show is only available inside `reasonix code`." };
|
||||
}
|
||||
return { info: ctx.codeShowEdit(args) };
|
||||
};
|
||||
|
||||
const apply: SlashHandler = (_args, _loop, ctx) => {
|
||||
if (!ctx.codeApply) {
|
||||
return {
|
||||
info: "/apply is only available inside `reasonix code` (nothing to apply here).",
|
||||
};
|
||||
}
|
||||
return { info: ctx.codeApply() };
|
||||
};
|
||||
|
||||
const discard: SlashHandler = (_args, _loop, ctx) => {
|
||||
if (!ctx.codeDiscard) {
|
||||
return {
|
||||
info: "/discard is only available inside `reasonix code`.",
|
||||
};
|
||||
}
|
||||
return { info: ctx.codeDiscard() };
|
||||
};
|
||||
|
||||
const plan: SlashHandler = (args, _loop, ctx) => {
|
||||
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.",
|
||||
};
|
||||
};
|
||||
|
||||
const applyPlan: SlashHandler = (_args, _loop, ctx) => {
|
||||
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.",
|
||||
};
|
||||
};
|
||||
|
||||
const mode: SlashHandler = (args, _loop, ctx) => {
|
||||
if (!ctx.setEditMode) {
|
||||
return {
|
||||
info: "/mode is only available inside `reasonix code`.",
|
||||
};
|
||||
}
|
||||
const raw = (args[0] ?? "").toLowerCase();
|
||||
const current = ctx.editMode ?? "review";
|
||||
let target: EditMode;
|
||||
if (raw === "review") target = "review";
|
||||
else if (raw === "auto") target = "auto";
|
||||
else if (raw === "") {
|
||||
// Bare /mode toggles, mirroring Shift+Tab. Users who just want to
|
||||
// see current mode without flipping can read /status.
|
||||
target = current === "auto" ? "review" : "auto";
|
||||
} else {
|
||||
return { info: "usage: /mode <review|auto> (Shift+Tab also cycles)" };
|
||||
}
|
||||
ctx.setEditMode(target);
|
||||
return {
|
||||
info:
|
||||
target === "auto"
|
||||
? "▸ edit mode: AUTO — edits apply immediately; press u within 5s to undo, or /undo later"
|
||||
: "▸ edit mode: review — edits queue for /apply (or y) / /discard (or n)",
|
||||
};
|
||||
};
|
||||
|
||||
const commit: SlashHandler = (args, _loop, ctx) => {
|
||||
if (!ctx.codeRoot) {
|
||||
return {
|
||||
info: "/commit is only available inside `reasonix code` (needs a rooted git repo).",
|
||||
};
|
||||
}
|
||||
// Reassemble the original argv. The parser lowercases cmd but leaves
|
||||
// args alone, and the TUI splits on whitespace which mangles quoted
|
||||
// messages — rejoin with spaces and strip a surrounding pair of
|
||||
// double quotes if the user wrote them.
|
||||
const raw = args.join(" ").trim();
|
||||
const message = stripOuterQuotes(raw);
|
||||
if (!message) {
|
||||
return {
|
||||
info: `usage: /commit "your commit message" — runs \`git add -A && git commit -m "…"\` in ${ctx.codeRoot}`,
|
||||
};
|
||||
}
|
||||
return runGitCommit(ctx.codeRoot, message);
|
||||
};
|
||||
|
||||
export const handlers: Record<string, SlashHandler> = {
|
||||
undo,
|
||||
history,
|
||||
show,
|
||||
apply,
|
||||
discard,
|
||||
plan,
|
||||
"apply-plan": applyPlan,
|
||||
applyplan: applyPlan,
|
||||
mode,
|
||||
commit,
|
||||
};
|
||||
@@ -0,0 +1,84 @@
|
||||
import type { SlashHandler } from "../dispatch.js";
|
||||
|
||||
const jobs: SlashHandler = (_args, _loop, ctx) => {
|
||||
if (!ctx.jobs) {
|
||||
return { info: "/jobs is only available inside `reasonix code`." };
|
||||
}
|
||||
const rows = ctx.jobs.list();
|
||||
if (rows.length === 0) {
|
||||
return { info: "no background jobs yet — use run_background to start one" };
|
||||
}
|
||||
const lines = ["Background jobs:"];
|
||||
for (const r of rows) {
|
||||
const age = ((Date.now() - r.startedAt) / 1000).toFixed(1);
|
||||
const state = r.running
|
||||
? `running · pid ${r.pid ?? "?"}`
|
||||
: r.exitCode !== null
|
||||
? `exit ${r.exitCode}`
|
||||
: r.spawnError
|
||||
? "failed"
|
||||
: "stopped";
|
||||
lines.push(
|
||||
` ${String(r.id).padStart(3)} ${state.padEnd(20)} ${age.padStart(6)}s ago $ ${r.command}`,
|
||||
);
|
||||
}
|
||||
lines.push("");
|
||||
lines.push("/kill <id> to stop one · /logs <id> [lines] to tail output");
|
||||
return { info: lines.join("\n") };
|
||||
};
|
||||
|
||||
const kill: SlashHandler = (args, _loop, ctx) => {
|
||||
if (!ctx.jobs) return { info: "/kill is only available inside `reasonix code`." };
|
||||
const id = Number.parseInt(args[0] ?? "", 10);
|
||||
if (!Number.isFinite(id)) return { info: "usage: /kill <id> (see /jobs for ids)" };
|
||||
const rec = ctx.jobs.list().find((r) => r.id === id);
|
||||
if (!rec) return { info: `job ${id}: not found` };
|
||||
if (!rec.running) return { info: `job ${id} already exited (${rec.exitCode ?? "?"})` };
|
||||
// Fire-and-forget: the registry waits for grace + SIGKILL internally;
|
||||
// returning immediately keeps the slash synchronous so the user's
|
||||
// prompt doesn't lock up for 2s on every /kill. The postInfo
|
||||
// callback lands a follow-up row in historical when the kill
|
||||
// actually completes, so the user sees "job N stopped" without
|
||||
// polling /jobs.
|
||||
const jobsRef = ctx.jobs;
|
||||
void (async () => {
|
||||
const final = await jobsRef.stop(id);
|
||||
if (!final) return;
|
||||
const status = final.running
|
||||
? "still alive after SIGKILL (!) — report this as a bug"
|
||||
: final.exitCode !== null
|
||||
? `exit ${final.exitCode}`
|
||||
: "stopped";
|
||||
ctx.postInfo?.(`▸ job ${id} ${status}`);
|
||||
})();
|
||||
return {
|
||||
info: `▸ stopping job ${id} (tree kill: SIGTERM → SIGKILL after 2s grace; Windows: taskkill /T /F)`,
|
||||
};
|
||||
};
|
||||
|
||||
const logs: SlashHandler = (args, _loop, ctx) => {
|
||||
if (!ctx.jobs) return { info: "/logs is only available inside `reasonix code`." };
|
||||
const id = Number.parseInt(args[0] ?? "", 10);
|
||||
if (!Number.isFinite(id)) {
|
||||
return { info: "usage: /logs <id> [lines] (default last 80 lines)" };
|
||||
}
|
||||
const requested = Number.parseInt(args[1] ?? "", 10);
|
||||
const tail = Number.isFinite(requested) && requested > 0 ? requested : 80;
|
||||
const out = ctx.jobs.read(id, { tailLines: tail });
|
||||
if (!out) return { info: `job ${id}: not found` };
|
||||
const status = out.running
|
||||
? `running · pid ${out.pid ?? "?"}`
|
||||
: out.exitCode !== null
|
||||
? `exited ${out.exitCode}`
|
||||
: out.spawnError
|
||||
? `failed (${out.spawnError})`
|
||||
: "stopped";
|
||||
const header = `[job ${id} · ${status}]\n$ ${out.command}`;
|
||||
return { info: out.output ? `${header}\n${out.output}` : header };
|
||||
};
|
||||
|
||||
export const handlers: Record<string, SlashHandler> = {
|
||||
jobs,
|
||||
kill,
|
||||
logs,
|
||||
};
|
||||
@@ -0,0 +1,64 @@
|
||||
import type { SlashHandler } from "../dispatch.js";
|
||||
import { appendSection } from "../helpers.js";
|
||||
|
||||
const mcp: SlashHandler = (_args, loop, ctx) => {
|
||||
const servers = ctx.mcpServers ?? [];
|
||||
const specs = ctx.mcpSpecs ?? [];
|
||||
const toolSpecs = loop.prefix.toolSpecs ?? [];
|
||||
if (servers.length === 0 && specs.length === 0 && toolSpecs.length === 0) {
|
||||
return {
|
||||
info:
|
||||
"no MCP servers attached. Run `reasonix setup` to pick some, " +
|
||||
'or launch with --mcp "<spec>". `reasonix mcp list` shows the catalog.',
|
||||
};
|
||||
}
|
||||
// Rich path — we have full inspection reports, so show each server
|
||||
// with its tools / resources / prompts grouped together.
|
||||
if (servers.length > 0) {
|
||||
const lines: string[] = [];
|
||||
let anyResources = false;
|
||||
let anyPrompts = false;
|
||||
for (const s of servers) {
|
||||
const { report } = s;
|
||||
const serverName = report.serverInfo.name || "(unknown)";
|
||||
const serverVer = report.serverInfo.version ? ` v${report.serverInfo.version}` : "";
|
||||
lines.push(`[${s.label}] ${serverName}${serverVer} — ${s.spec}`);
|
||||
lines.push(` tools ${s.toolCount}`);
|
||||
appendSection(lines, "resources", report.resources);
|
||||
appendSection(lines, "prompts ", report.prompts);
|
||||
if (report.resources.supported && report.resources.items.length > 0) anyResources = true;
|
||||
if (report.prompts.supported && report.prompts.items.length > 0) anyPrompts = true;
|
||||
lines.push("");
|
||||
}
|
||||
if (anyResources || anyPrompts) {
|
||||
const hints: string[] = [];
|
||||
if (anyResources) hints.push("`/resource` to browse+read");
|
||||
if (anyPrompts) hints.push("`/prompt` to browse+fetch");
|
||||
lines.push(hints.join(" · "));
|
||||
} else {
|
||||
lines.push(
|
||||
"Chat mode consumes tools today; resources+prompts are surfaced here for awareness.",
|
||||
);
|
||||
}
|
||||
lines.push(
|
||||
"Full catalog: `reasonix mcp list` · deeper diagnosis: `reasonix mcp inspect <spec>`.",
|
||||
);
|
||||
return { info: lines.join("\n") };
|
||||
}
|
||||
// Fallback — older path when the TUI hasn't populated `mcpServers`.
|
||||
const lines: string[] = [];
|
||||
if (specs.length > 0) {
|
||||
lines.push(`MCP servers (${specs.length}):`);
|
||||
for (const spec of specs) lines.push(` · ${spec}`);
|
||||
lines.push("");
|
||||
}
|
||||
if (toolSpecs.length > 0) {
|
||||
lines.push(`Tools in registry (${toolSpecs.length}):`);
|
||||
for (const t of toolSpecs) lines.push(` · ${t.function.name}`);
|
||||
}
|
||||
lines.push("");
|
||||
lines.push("To change this set, exit and run `reasonix setup`.");
|
||||
return { info: lines.join("\n") };
|
||||
};
|
||||
|
||||
export const handlers: Record<string, SlashHandler> = { mcp };
|
||||
@@ -0,0 +1,169 @@
|
||||
import {
|
||||
PROJECT_MEMORY_FILE,
|
||||
memoryEnabled,
|
||||
readProjectMemory,
|
||||
} from "../../../../project-memory.js";
|
||||
import { type MemoryScope, MemoryStore } from "../../../../user-memory.js";
|
||||
import type { SlashHandler } from "../dispatch.js";
|
||||
import { resolveMemoryTarget } from "../helpers.js";
|
||||
|
||||
/**
|
||||
* `/memory` family. Bare `/memory` shows what's pinned (REASONIX.md +
|
||||
* both MEMORY.md blocks). Subcommands manage the user-memory store:
|
||||
* list — every memory file, both scopes
|
||||
* show <name> — dump one file's body
|
||||
* show <scope>/<name> — disambiguate when name exists in both scopes
|
||||
* forget <name> — delete (same scope resolution as show)
|
||||
* clear <scope> confirm — wipe a scope (typed literal "confirm" required)
|
||||
*/
|
||||
const memory: SlashHandler = (args, _loop, ctx) => {
|
||||
if (!memoryEnabled()) {
|
||||
return {
|
||||
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") };
|
||||
};
|
||||
|
||||
export const handlers: Record<string, SlashHandler> = { memory };
|
||||
@@ -0,0 +1,187 @@
|
||||
import { saveReasoningEffort } from "../../../../config.js";
|
||||
import type { SlashHandler } from "../dispatch.js";
|
||||
|
||||
const model: SlashHandler = (args, loop, ctx) => {
|
||||
const id = args[0];
|
||||
const known = ctx.models ?? null;
|
||||
if (!id) {
|
||||
const hint =
|
||||
known && known.length > 0
|
||||
? known.join(" | ")
|
||||
: "try deepseek-v4-flash or deepseek-v4-pro — run /models to fetch the live list";
|
||||
return { info: `usage: /model <id> (${hint})` };
|
||||
}
|
||||
loop.configure({ model: id });
|
||||
// Soft validation: if we have the live list and the id isn't in
|
||||
// it, flag a warning but still switch — DeepSeek may have just
|
||||
// released something we haven't indexed yet, and refusing would
|
||||
// be worse than a bad API error on the next call.
|
||||
if (known && known.length > 0 && !known.includes(id)) {
|
||||
return {
|
||||
info: `model → ${id} (⚠ not in the fetched catalog: ${known.join(", ")}. If this is wrong the next call will 400 — run /models to refresh.)`,
|
||||
};
|
||||
}
|
||||
return { info: `model → ${id}` };
|
||||
};
|
||||
|
||||
const models: SlashHandler = (_args, loop, ctx) => {
|
||||
const list = ctx.models ?? null;
|
||||
if (list === null) {
|
||||
ctx.refreshModels?.();
|
||||
return {
|
||||
info: "fetching /models from DeepSeek… run /models again in a moment. If it stays empty, your API key may lack permission or the network is blocked.",
|
||||
};
|
||||
}
|
||||
if (list.length === 0) {
|
||||
return {
|
||||
info: "DeepSeek /models returned an empty list. Try /models again, or check your account status at api-docs.deepseek.com.",
|
||||
};
|
||||
}
|
||||
const current = loop.model;
|
||||
const lines = list.map((id) => (id === current ? `▸ ${id} (current)` : ` ${id}`));
|
||||
return {
|
||||
info: [
|
||||
`Available models (DeepSeek /models · ${list.length} total):`,
|
||||
"",
|
||||
...lines,
|
||||
"",
|
||||
"Switch with: /model <id>",
|
||||
].join("\n"),
|
||||
};
|
||||
};
|
||||
|
||||
const harvest: SlashHandler = (args, loop) => {
|
||||
const arg = (args[0] ?? "").toLowerCase();
|
||||
const on = arg === "" ? !loop.harvestEnabled : arg === "on" || arg === "true" || arg === "1";
|
||||
loop.configure({ harvest: on });
|
||||
if (loop.harvestEnabled) {
|
||||
return {
|
||||
info: "harvest → on (Pillar-2 plan-state extraction · +1 cheap flash call per turn · opt-in only; no preset turns it on)",
|
||||
};
|
||||
}
|
||||
return { info: "harvest → off" };
|
||||
};
|
||||
|
||||
const preset: SlashHandler = (args, loop) => {
|
||||
const name = (args[0] ?? "").toLowerCase();
|
||||
// Persist the effort along with the preset change so a relaunch
|
||||
// doesn't revert to the previously-saved /effort value.
|
||||
const applyAndPersist = (effort: "high" | "max") => {
|
||||
try {
|
||||
saveReasoningEffort(effort);
|
||||
} catch {
|
||||
/* disk full / perms — runtime change still took effect */
|
||||
}
|
||||
};
|
||||
if (name === "fast" || name === "default") {
|
||||
loop.configure({
|
||||
model: "deepseek-v4-flash",
|
||||
reasoningEffort: "high",
|
||||
harvest: false,
|
||||
branch: 1,
|
||||
});
|
||||
applyAndPersist("high");
|
||||
return { info: "preset → fast (v4-flash · effort=high · cheapest)" };
|
||||
}
|
||||
if (name === "smart") {
|
||||
loop.configure({
|
||||
model: "deepseek-v4-flash",
|
||||
reasoningEffort: "max",
|
||||
harvest: false,
|
||||
branch: 1,
|
||||
});
|
||||
applyAndPersist("max");
|
||||
return { info: "preset → smart (v4-flash · effort=max · default · ~1.5× fast)" };
|
||||
}
|
||||
if (name === "max" || name === "best") {
|
||||
loop.configure({
|
||||
model: "deepseek-v4-pro",
|
||||
reasoningEffort: "max",
|
||||
harvest: false,
|
||||
branch: 1,
|
||||
});
|
||||
applyAndPersist("max");
|
||||
return {
|
||||
info: "preset → max (v4-pro · effort=max · ~12× fast · save for hard tasks, or use /pro for a single-turn bump)",
|
||||
};
|
||||
}
|
||||
return { info: "usage: /preset <fast|smart|max>" };
|
||||
};
|
||||
|
||||
const branch: SlashHandler = (args, loop) => {
|
||||
const raw = (args[0] ?? "").toLowerCase();
|
||||
if (raw === "" || raw === "off" || raw === "0" || raw === "1") {
|
||||
loop.configure({ branch: 1 });
|
||||
return { info: "branch → off" };
|
||||
}
|
||||
const n = Number.parseInt(raw, 10);
|
||||
if (!Number.isFinite(n) || n < 2) {
|
||||
return { info: "usage: /branch <N> (N>=2, or 'off')" };
|
||||
}
|
||||
if (n > 8) {
|
||||
return { info: "branch budget capped at 8 to prevent runaway cost" };
|
||||
}
|
||||
loop.configure({ branch: n });
|
||||
return {
|
||||
info: `branch → ${n} (runs ${n} parallel samples per turn · ${n}× per-turn cost · streaming disabled · manual only, no preset enables branching)`,
|
||||
};
|
||||
};
|
||||
|
||||
const effort: SlashHandler = (args, loop) => {
|
||||
const raw = (args[0] ?? "").toLowerCase();
|
||||
if (raw === "") {
|
||||
return {
|
||||
info: `reasoning_effort → ${loop.reasoningEffort} (use /effort high for cheaper/faster, /effort max for the agent-class default · persisted across relaunches)`,
|
||||
};
|
||||
}
|
||||
if (raw !== "high" && raw !== "max") {
|
||||
return { info: "usage: /effort <high|max>" };
|
||||
}
|
||||
loop.configure({ reasoningEffort: raw });
|
||||
// Persist so the next launch starts with this value instead of
|
||||
// reverting to the constructor default.
|
||||
try {
|
||||
saveReasoningEffort(raw);
|
||||
} catch {
|
||||
/* disk full / perms — runtime change still took effect */
|
||||
}
|
||||
return { info: `reasoning_effort → ${raw} (persisted)` };
|
||||
};
|
||||
|
||||
const pro: SlashHandler = (args, loop, ctx) => {
|
||||
const arg = (args[0] ?? "").toLowerCase();
|
||||
if (arg === "off" || arg === "cancel" || arg === "disarm") {
|
||||
if (!loop.proArmed) {
|
||||
return { info: "nothing armed — /pro with no args will arm pro for your next turn" };
|
||||
}
|
||||
if (ctx.disarmPro) ctx.disarmPro();
|
||||
else loop.disarmPro();
|
||||
return { info: "▸ /pro disarmed — next turn falls back to the current preset" };
|
||||
}
|
||||
if (arg && arg !== "on" && arg !== "arm") {
|
||||
return {
|
||||
info: "usage: /pro arm pro for the next turn (one-shot, auto-disarms after)\n /pro off cancel armed state before the next turn",
|
||||
};
|
||||
}
|
||||
if (ctx.armPro) ctx.armPro();
|
||||
else loop.armProForNextTurn();
|
||||
return {
|
||||
info: `▸ /pro armed — your NEXT message runs on ${ESCALATION_MODEL_ID} regardless of preset. Auto-disarms after one turn. Use /preset max for a persistent switch.`,
|
||||
};
|
||||
};
|
||||
|
||||
// Kept in sync with loop.ts ESCALATION_MODEL — hard-coding rather than
|
||||
// importing it because loop.ts already exports enough surface, and this
|
||||
// string is user-facing (description strings stay verbatim even if the
|
||||
// internal constant renames).
|
||||
const ESCALATION_MODEL_ID = "deepseek-v4-pro";
|
||||
|
||||
export const handlers: Record<string, SlashHandler> = {
|
||||
model,
|
||||
models,
|
||||
harvest,
|
||||
preset,
|
||||
branch,
|
||||
effort,
|
||||
pro,
|
||||
};
|
||||
@@ -0,0 +1,192 @@
|
||||
import { DEEPSEEK_CONTEXT_TOKENS, DEFAULT_CONTEXT_TOKENS } from "../../../../telemetry.js";
|
||||
import { countTokens } from "../../../../tokenizer.js";
|
||||
import type { SlashHandler } from "../dispatch.js";
|
||||
import { compactNum, formatToolList } from "../helpers.js";
|
||||
|
||||
const think: SlashHandler = (_args, loop) => {
|
||||
const raw = loop.scratch.reasoning;
|
||||
if (!raw || !raw.trim()) {
|
||||
return {
|
||||
info:
|
||||
"no reasoning cached. `/think` shows the full thinking-mode thought for the most recent " +
|
||||
"turn — only thinking-mode models (deepseek-v4-flash / -v4-pro / -reasoner) produce it, " +
|
||||
"and only once the turn completes.",
|
||||
};
|
||||
}
|
||||
return { info: `↳ full thinking (${raw.length} chars):\n\n${raw.trim()}` };
|
||||
};
|
||||
|
||||
const tool: SlashHandler = (args, _loop, ctx) => {
|
||||
// EventLog renders tool results as a one-line summary for display.
|
||||
// When the user wants to check what the model actually read (e.g.
|
||||
// to verify it isn't hallucinating a file's contents), they need
|
||||
// the full text. `/tool` is the escape hatch.
|
||||
const history = ctx.toolHistory?.() ?? [];
|
||||
if (history.length === 0) {
|
||||
return {
|
||||
info:
|
||||
"no tool calls yet in this session. `/tool` lists them once the model has actually " +
|
||||
"used a tool; `/tool N` dumps the full (untruncated) output of the Nth-most-recent.",
|
||||
};
|
||||
}
|
||||
const raw = (args[0] ?? "").toLowerCase();
|
||||
if (raw === "" || raw === "list" || raw === "ls") {
|
||||
return { info: formatToolList(history) };
|
||||
}
|
||||
const n = Number.parseInt(raw, 10);
|
||||
if (!Number.isFinite(n) || n < 1) {
|
||||
return {
|
||||
info: "usage: /tool [N] (no arg → list; N=1 → most recent result in full, N=2 → previous, …)",
|
||||
};
|
||||
}
|
||||
if (n > history.length) {
|
||||
return {
|
||||
info: `only ${history.length} tool call(s) in history — asked for #${n}. Try /tool with no arg to see the list.`,
|
||||
};
|
||||
}
|
||||
const entry = history[history.length - n];
|
||||
if (!entry) {
|
||||
return { info: `could not read tool call #${n}` };
|
||||
}
|
||||
return {
|
||||
info: `↳ tool<${entry.toolName}> #${n} (${entry.text.length} chars):\n\n${entry.text}`,
|
||||
};
|
||||
};
|
||||
|
||||
const context: SlashHandler = (_args, loop) => {
|
||||
// Measure each slice of the next request locally so the user can see
|
||||
// *where* context is being spent — a much more useful number than
|
||||
// the "last turn's total" the gauge shows. Tokenization is lazy so
|
||||
// the first /context call carries the data-file load cost (~100ms);
|
||||
// subsequent calls are pure compute.
|
||||
const systemTokens = countTokens(loop.prefix.system);
|
||||
const toolsTokens = countTokens(JSON.stringify(loop.prefix.toolSpecs));
|
||||
const entries = loop.log.toMessages();
|
||||
let userTokens = 0;
|
||||
let assistantTokens = 0;
|
||||
let toolResultTokens = 0;
|
||||
let toolCallTokens = 0;
|
||||
const toolBreakdown: Array<{ name: string; tokens: number; turn: number }> = [];
|
||||
let logTurn = 0;
|
||||
for (const e of entries) {
|
||||
const content = typeof e.content === "string" ? e.content : "";
|
||||
if (e.role === "user") {
|
||||
userTokens += countTokens(content);
|
||||
logTurn += 1;
|
||||
} else if (e.role === "assistant") {
|
||||
assistantTokens += countTokens(content);
|
||||
if (Array.isArray(e.tool_calls) && e.tool_calls.length > 0) {
|
||||
toolCallTokens += countTokens(JSON.stringify(e.tool_calls));
|
||||
}
|
||||
} else if (e.role === "tool") {
|
||||
const n = countTokens(content);
|
||||
toolResultTokens += n;
|
||||
toolBreakdown.push({ name: e.name ?? "?", tokens: n, turn: logTurn });
|
||||
}
|
||||
}
|
||||
const logTokens = userTokens + assistantTokens + toolResultTokens + toolCallTokens;
|
||||
const total = systemTokens + toolsTokens + logTokens;
|
||||
const ctxMax = DEEPSEEK_CONTEXT_TOKENS[loop.model] ?? DEFAULT_CONTEXT_TOKENS;
|
||||
const pct = (n: number) => (total > 0 ? `${Math.round((n / total) * 100)}%`.padStart(4) : " 0%");
|
||||
const row = (label: string, n: number, note = "") =>
|
||||
` ${label.padEnd(20)}${compactNum(n).padStart(8)} tokens ${pct(n)}${note ? ` ${note}` : ""}`;
|
||||
|
||||
const lines = [
|
||||
`Next-request estimate: ~${compactNum(total)} tokens of ${compactNum(ctxMax)} (${Math.round(
|
||||
(total / ctxMax) * 100,
|
||||
)}% of window)`,
|
||||
"",
|
||||
row("system prompt", systemTokens),
|
||||
row("tool specs", toolsTokens, `(${loop.prefix.toolSpecs.length} tools)`),
|
||||
row("log (all turns)", logTokens, `(${entries.length} messages)`),
|
||||
` user ${compactNum(userTokens).padStart(8)} tokens`,
|
||||
` assistant ${compactNum(assistantTokens).padStart(8)} tokens`,
|
||||
` tool-call args ${compactNum(toolCallTokens).padStart(8)} tokens`,
|
||||
` tool results ${compactNum(toolResultTokens).padStart(8)} tokens`,
|
||||
];
|
||||
|
||||
// Top 5 heaviest tool results — usually where unexpected bloat
|
||||
// lives (a big read_file, an unfiltered search_content).
|
||||
if (toolBreakdown.length > 0) {
|
||||
const top = [...toolBreakdown].sort((a, b) => b.tokens - a.tokens).slice(0, 5);
|
||||
lines.push("");
|
||||
lines.push(`Top tool results by cost (of ${toolBreakdown.length} total):`);
|
||||
for (const t of top) {
|
||||
lines.push(
|
||||
` turn ${String(t.turn).padStart(3)} ${t.name.padEnd(22)} ${compactNum(t.tokens).padStart(8)} tokens`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
lines.push("");
|
||||
lines.push(
|
||||
"Count is a local estimate (DeepSeek V3 tokenizer, pure-TS port); server prompt_tokens may add ~3-6% for chat-template role markers.",
|
||||
);
|
||||
return { info: lines.join("\n") };
|
||||
};
|
||||
|
||||
const status: SlashHandler = (_args, loop, ctx) => {
|
||||
const branchBudget = loop.branchOptions.budget ?? 1;
|
||||
const ctxMax = DEEPSEEK_CONTEXT_TOKENS[loop.model] ?? DEFAULT_CONTEXT_TOKENS;
|
||||
const lastPromptTokens = loop.stats.summary().lastPromptTokens;
|
||||
const ctxPct = ctxMax > 0 ? Math.round((lastPromptTokens / ctxMax) * 100) : 0;
|
||||
const ctxLine =
|
||||
lastPromptTokens > 0
|
||||
? ` ctx ${compactNum(lastPromptTokens)}/${compactNum(ctxMax)} (${ctxPct}%)`
|
||||
: " ctx no turns yet";
|
||||
const pending = ctx.pendingEditCount ?? 0;
|
||||
const sessionLine = loop.sessionName
|
||||
? ` session "${loop.sessionName}" · ${loop.log.length} messages in log (resumed ${loop.resumedMessageCount})`
|
||||
: " session (ephemeral — no persistence)";
|
||||
const mcpCount = ctx.mcpSpecs?.length ?? 0;
|
||||
const toolCount = loop.prefix.toolSpecs.length;
|
||||
const mcpLine = ` mcp ${mcpCount} server(s), ${toolCount} tool(s) in registry`;
|
||||
const pendingLine =
|
||||
pending > 0 ? ` edits ${pending} pending (/apply to commit, /discard to drop)` : "";
|
||||
const planLine = ctx.planMode ? " plan ON — writes gated (submit_plan + approval)" : "";
|
||||
const modeLine =
|
||||
ctx.editMode === "auto"
|
||||
? " mode AUTO — edits apply immediately (u to undo within 5s · Shift+Tab to flip)"
|
||||
: ctx.editMode === "review"
|
||||
? " mode review — edits queue for /apply or y (Shift+Tab to flip)"
|
||||
: "";
|
||||
const lines = [
|
||||
` model ${loop.model}`,
|
||||
` flags harvest=${loop.harvestEnabled ? "on" : "off"} · branch=${branchBudget > 1 ? branchBudget : "off"} · stream=${loop.stream ? "on" : "off"} · effort=${loop.reasoningEffort}`,
|
||||
ctxLine,
|
||||
mcpLine,
|
||||
sessionLine,
|
||||
];
|
||||
if (pendingLine) lines.push(pendingLine);
|
||||
if (planLine) lines.push(planLine);
|
||||
if (modeLine) lines.push(modeLine);
|
||||
return { info: lines.join("\n") };
|
||||
};
|
||||
|
||||
const compact: SlashHandler = (args, loop) => {
|
||||
// Manual companion to the automatic 60%/80% auto-compact. Re-applies
|
||||
// token-aware truncation with a tighter cap (default 4000 tokens per
|
||||
// tool result) and rewrites the session file so the shrink persists.
|
||||
// Useful when the ctx gauge in StatsPanel goes yellow/red mid-session
|
||||
// and the user wants to keep chatting without /forget'ing everything.
|
||||
const tight = Number.parseInt(args[0] ?? "", 10);
|
||||
const cap = Number.isFinite(tight) && tight >= 100 ? tight : 4000;
|
||||
const { healedCount, tokensSaved, charsSaved } = loop.compact(cap);
|
||||
if (healedCount === 0) {
|
||||
return {
|
||||
info: `▸ nothing to compact — no tool result or tool-call args in history exceed ${cap.toLocaleString()} tokens.`,
|
||||
};
|
||||
}
|
||||
return {
|
||||
info: `▸ compacted ${healedCount} payload(s) to ${cap.toLocaleString()} tokens each (tool results + tool-call args), saved ${tokensSaved.toLocaleString()} tokens (${charsSaved.toLocaleString()} chars). Session file rewritten.`,
|
||||
};
|
||||
};
|
||||
|
||||
export const handlers: Record<string, SlashHandler> = {
|
||||
think,
|
||||
reasoning: think,
|
||||
tool,
|
||||
context,
|
||||
status,
|
||||
compact,
|
||||
};
|
||||
@@ -0,0 +1,111 @@
|
||||
/**
|
||||
* `/plans` — show this session's plan history. Both the live in-flight
|
||||
* plan (if any) and the archive of completed `.done.json` files. Local
|
||||
* to the current session by design — a plan lives with its project,
|
||||
* and resuming one just means cd'ing back to that project directory.
|
||||
*/
|
||||
|
||||
import { basename } from "node:path";
|
||||
import { listPlanArchives, loadPlanState, relativeTime } from "../../../../code/plan-store.js";
|
||||
import type { SlashHandler } from "../dispatch.js";
|
||||
|
||||
const plans: SlashHandler = (_args, loop) => {
|
||||
const sessionName = loop.sessionName;
|
||||
if (!sessionName) {
|
||||
return {
|
||||
info: "no session attached — `/plans` is per-session. Run `reasonix code` in a project to get a session.",
|
||||
};
|
||||
}
|
||||
const lines: string[] = [];
|
||||
// Active (in-flight) plan summary first — it's the one the user is
|
||||
// most likely asking about.
|
||||
const active = loadPlanState(sessionName);
|
||||
if (active && active.steps.length > 0) {
|
||||
const total = active.steps.length;
|
||||
const done = active.completedStepIds.length;
|
||||
const when = relativeTime(active.updatedAt);
|
||||
const label = active.summary ? `: ${active.summary}` : "";
|
||||
lines.push(
|
||||
`▸ active plan${label} — ${done}/${total} step${total === 1 ? "" : "s"} done · last touched ${when}`,
|
||||
);
|
||||
} else {
|
||||
lines.push("▸ active plan: (none)");
|
||||
}
|
||||
|
||||
// Archives (completed plans) — newest first.
|
||||
const archives = listPlanArchives(sessionName);
|
||||
if (archives.length === 0) {
|
||||
lines.push("");
|
||||
lines.push(
|
||||
"no archived plans yet for this session — they auto-archive when every step is done",
|
||||
);
|
||||
return { info: lines.join("\n") };
|
||||
}
|
||||
lines.push("");
|
||||
lines.push(`Archived (${archives.length}):`);
|
||||
for (const a of archives) {
|
||||
const when = relativeTime(a.completedAt);
|
||||
const total = a.steps.length;
|
||||
const done = a.completedStepIds.length;
|
||||
const completion = done >= total ? "complete" : `${done}/${total}`;
|
||||
// Prefer the model-supplied summary as the label; fall back to
|
||||
// the bare filename so legacy archives without a summary still
|
||||
// show something identifying.
|
||||
const label = a.summary ?? a.path.split(/[\\/]/).pop() ?? a.path;
|
||||
lines.push(
|
||||
` ✓ ${when.padEnd(10)} ${total} step${total === 1 ? "" : "s"} · ${completion} ${label}`,
|
||||
);
|
||||
}
|
||||
return { info: lines.join("\n") };
|
||||
};
|
||||
|
||||
/**
|
||||
* `/replay [N]` — Time Travel. Loads archive #N (1-based, newest
|
||||
* first; defaults to 1) and asks the TUI to render it as a read-only
|
||||
* snapshot. Pure display — no execution, no plan state changes.
|
||||
*
|
||||
* The structured payload (steps + completedStepIds + body + summary)
|
||||
* goes back through SlashResult.replayPlan so EventLog can apply the
|
||||
* same step-list rendering used elsewhere, complete with risk gutter
|
||||
* and ✓ status.
|
||||
*/
|
||||
const replay: SlashHandler = (args, loop) => {
|
||||
const sessionName = loop.sessionName;
|
||||
if (!sessionName) {
|
||||
return {
|
||||
info: "no session attached — `/replay` is per-session. Run `reasonix code` in a project to get a session.",
|
||||
};
|
||||
}
|
||||
const archives = listPlanArchives(sessionName);
|
||||
if (archives.length === 0) {
|
||||
return {
|
||||
info: "no archived plans yet for this session — `/replay` lights up once a plan completes (auto-archives when every step is done).",
|
||||
};
|
||||
}
|
||||
const arg = args[0]?.trim() ?? "";
|
||||
const index = arg ? Number.parseInt(arg, 10) : 1;
|
||||
if (!Number.isFinite(index) || index < 1 || index > archives.length) {
|
||||
return {
|
||||
info: `invalid index — \`/replay\` takes 1..${archives.length} (newest = 1). Use \`/plans\` to see the list.`,
|
||||
};
|
||||
}
|
||||
const a = archives[index - 1]!;
|
||||
return {
|
||||
replayPlan: {
|
||||
summary: a.summary,
|
||||
body: a.body,
|
||||
steps: a.steps,
|
||||
completedStepIds: a.completedStepIds,
|
||||
completedAt: a.completedAt,
|
||||
relativeTime: relativeTime(a.completedAt),
|
||||
archiveBasename: basename(a.path),
|
||||
index,
|
||||
total: archives.length,
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
export const handlers: Record<string, SlashHandler> = {
|
||||
plans,
|
||||
replay,
|
||||
};
|
||||
@@ -0,0 +1,41 @@
|
||||
import { deleteSession, listSessions } from "../../../../session.js";
|
||||
import type { SlashHandler } from "../dispatch.js";
|
||||
|
||||
const sessions: SlashHandler = (_args, loop) => {
|
||||
const items = listSessions();
|
||||
if (items.length === 0) {
|
||||
return {
|
||||
info: "no saved sessions yet — chat normally and your messages will be saved automatically",
|
||||
};
|
||||
}
|
||||
const lines = ["Saved sessions:"];
|
||||
for (const s of items) {
|
||||
const sizeKb = (s.size / 1024).toFixed(1);
|
||||
const when = s.mtime.toISOString().replace("T", " ").slice(0, 16);
|
||||
const marker = s.name === loop.sessionName ? "▸" : " ";
|
||||
lines.push(
|
||||
` ${marker} ${s.name.padEnd(22)} ${String(s.messageCount).padStart(5)} msgs ${sizeKb.padStart(7)} KB ${when}`,
|
||||
);
|
||||
}
|
||||
lines.push("");
|
||||
lines.push("Resume with: reasonix chat --session <name>");
|
||||
return { info: lines.join("\n") };
|
||||
};
|
||||
|
||||
const forget: SlashHandler = (_args, loop) => {
|
||||
if (!loop.sessionName) {
|
||||
return { info: "not in a session — nothing to forget" };
|
||||
}
|
||||
const name = loop.sessionName;
|
||||
const ok = deleteSession(name);
|
||||
return {
|
||||
info: ok
|
||||
? `▸ deleted session "${name}" — current screen still shows the conversation, but next launch starts fresh`
|
||||
: `could not delete session "${name}" (already gone?)`,
|
||||
};
|
||||
};
|
||||
|
||||
export const handlers: Record<string, SlashHandler> = {
|
||||
sessions,
|
||||
forget,
|
||||
};
|
||||
@@ -0,0 +1,94 @@
|
||||
import { SkillStore } from "../../../../skills.js";
|
||||
import type { SlashHandler } from "../dispatch.js";
|
||||
|
||||
/**
|
||||
* `/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.
|
||||
*/
|
||||
const skill: SlashHandler = (args, _loop, ctx) => {
|
||||
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 found = store.read(target);
|
||||
if (!found) return { info: `no skill found: ${target}` };
|
||||
return {
|
||||
info: [
|
||||
`▸ ${found.name} (${found.scope})`,
|
||||
found.description ? ` ${found.description}` : "",
|
||||
` ${found.path}`,
|
||||
"",
|
||||
found.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 found = store.read(name);
|
||||
if (!found) {
|
||||
return {
|
||||
info: `no skill found: ${name} (try /skill list)`,
|
||||
};
|
||||
}
|
||||
const extra = args.slice(1).join(" ").trim();
|
||||
const header = `# Skill: ${found.name}${found.description ? `\n> ${found.description}` : ""}`;
|
||||
const argsLine = extra ? `\n\nArguments: ${extra}` : "";
|
||||
const payload = `${header}\n\n${found.body}${argsLine}`;
|
||||
return {
|
||||
info: `▸ running skill: ${found.name}${extra ? ` — ${extra}` : ""}`,
|
||||
resubmit: payload,
|
||||
};
|
||||
};
|
||||
|
||||
export const handlers: Record<string, SlashHandler> = {
|
||||
skill,
|
||||
skills: skill,
|
||||
};
|
||||
@@ -0,0 +1,145 @@
|
||||
import { spawnSync } from "node:child_process";
|
||||
import type { MemoryScope, MemoryStore } from "../../../user-memory.js";
|
||||
import type { SlashResult } from "./types.js";
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
export function resolveMemoryTarget(
|
||||
store: MemoryStore,
|
||||
raw: string,
|
||||
): { scope: MemoryScope; name: string } | null {
|
||||
const slash = raw.indexOf("/");
|
||||
if (slash > 0) {
|
||||
const scopeRaw = raw.slice(0, slash).toLowerCase();
|
||||
const name = raw.slice(slash + 1);
|
||||
if (scopeRaw !== "global" && scopeRaw !== "project") return null;
|
||||
const scope = scopeRaw as MemoryScope;
|
||||
if (scope === "project" && !store.hasProjectScope()) return null;
|
||||
return { scope, name };
|
||||
}
|
||||
for (const scope of ["project", "global"] as MemoryScope[]) {
|
||||
if (scope === "project" && !store.hasProjectScope()) continue;
|
||||
try {
|
||||
store.read(scope, raw);
|
||||
return { scope, name: raw };
|
||||
} catch {
|
||||
/* next scope */
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Render a section (resources / prompts) of an MCP inspection into a
|
||||
* compact "name count items" form, collapsing when unsupported.
|
||||
* Names-only — descriptions and full metadata live in
|
||||
* `reasonix mcp inspect`, which is purpose-built for the deep view.
|
||||
*/
|
||||
export function appendSection(
|
||||
lines: string[],
|
||||
label: string,
|
||||
section:
|
||||
| { supported: true; items: Array<{ name: string }> }
|
||||
| { supported: false; reason: string }
|
||||
| undefined,
|
||||
): void {
|
||||
if (!section || !section.supported) {
|
||||
lines.push(
|
||||
` ${label.trim()} ${section?.supported === false ? "(not supported)" : "(none)"}`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
const names = section.items.map((i) => i.name);
|
||||
if (names.length === 0) {
|
||||
lines.push(` ${label.trim()} (none)`);
|
||||
return;
|
||||
}
|
||||
const head = names.slice(0, 5).join(", ");
|
||||
const more = names.length > 5 ? ` +${names.length - 5} more` : "";
|
||||
lines.push(` ${label.trim()} ${names.length} [${head}${more}]`);
|
||||
}
|
||||
|
||||
export function formatToolList(history: Array<{ toolName: string; text: string }>): string {
|
||||
const total = history.length;
|
||||
const header = `Tool calls in this session (${total}, most recent first):`;
|
||||
// Show the 10 most recent. Older ones are rarely what the user
|
||||
// wants — and the help footer tells them how to reach any entry
|
||||
// by index if they do.
|
||||
const shown = Math.min(total, 10);
|
||||
const lines: string[] = [header];
|
||||
for (let i = 0; i < shown; i++) {
|
||||
const entry = history[total - 1 - i];
|
||||
if (!entry) continue;
|
||||
const idx = i + 1; // 1-based from most recent
|
||||
const flat = entry.text.replace(/\s+/g, " ").trim();
|
||||
const preview = flat.length > 80 ? `${flat.slice(0, 80)}…` : flat;
|
||||
const name = entry.toolName.length > 24 ? `${entry.toolName.slice(0, 23)}…` : entry.toolName;
|
||||
lines.push(
|
||||
` #${String(idx).padStart(2)} ${name.padEnd(24)} ${String(entry.text.length).padStart(6)} chars ${preview}`,
|
||||
);
|
||||
}
|
||||
if (total > shown) {
|
||||
lines.push(` … (${total - shown} earlier, reach with /tool N)`);
|
||||
}
|
||||
lines.push("");
|
||||
lines.push("View full output: /tool N (N=1 → most recent)");
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* Binary-K token formatter: 1234 → "1.2K", 131072 → "128K". Matches
|
||||
* DeepSeek's doc ("128K context"). Every call site here is rendering
|
||||
* token counts — if a future caller wants decimal-K for dollars or
|
||||
* similar, add a separate formatter rather than reusing this one.
|
||||
*/
|
||||
export function compactNum(n: number): string {
|
||||
if (n < 1024) return String(n);
|
||||
const k = n / 1024;
|
||||
return k >= 100 ? `${Math.round(k)}K` : `${k.toFixed(1)}K`;
|
||||
}
|
||||
|
||||
export function stripOuterQuotes(s: string): string {
|
||||
if (s.length >= 2 && s.startsWith('"') && s.endsWith('"')) {
|
||||
return s.slice(1, -1);
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
/**
|
||||
* Run `git add -A` then `git commit -m <message>` in `rootDir`. Returns
|
||||
* a SlashResult with a human-scannable info line. We surface stderr on
|
||||
* failure so the user sees exactly what git complained about (bad
|
||||
* config, pre-commit hook rejection, nothing staged, etc.).
|
||||
*/
|
||||
export function runGitCommit(rootDir: string, message: string): SlashResult {
|
||||
const add = spawnSync("git", ["add", "-A"], { cwd: rootDir, encoding: "utf8" });
|
||||
if (add.error || add.status !== 0) {
|
||||
return { info: `git add failed (${add.status ?? "?"}):\n${gitTail(add)}` };
|
||||
}
|
||||
const commit = spawnSync("git", ["commit", "-m", message], {
|
||||
cwd: rootDir,
|
||||
encoding: "utf8",
|
||||
});
|
||||
if (commit.error || commit.status !== 0) {
|
||||
return { info: `git commit failed (${commit.status ?? "?"}):\n${gitTail(commit)}` };
|
||||
}
|
||||
const firstLine = (commit.stdout || "").split(/\r?\n/)[0] ?? "";
|
||||
return { info: `▸ committed: ${message}${firstLine ? `\n ${firstLine}` : ""}` };
|
||||
}
|
||||
|
||||
/**
|
||||
* Safely extract whatever diagnostic text is available from a spawnSync
|
||||
* result — on Windows or when cwd doesn't exist, `stderr`/`stdout` can
|
||||
* be `undefined` and the caller has only `error.message` to go on.
|
||||
*/
|
||||
export function gitTail(res: ReturnType<typeof spawnSync>): string {
|
||||
const stderr = (res.stderr as string | undefined) ?? "";
|
||||
const stdout = (res.stdout as string | undefined) ?? "";
|
||||
const body = stderr.trim() || stdout.trim();
|
||||
if (body) return body;
|
||||
if (res.error) return (res.error as Error).message;
|
||||
return "(no output from git)";
|
||||
}
|
||||
@@ -0,0 +1,294 @@
|
||||
import type { EditMode } from "../../../config.js";
|
||||
import type { McpClient } from "../../../mcp/client.js";
|
||||
import type { InspectionReport } from "../../../mcp/inspect.js";
|
||||
import type { JobRegistry } from "../../../tools/jobs.js";
|
||||
import type { PlanStep } from "../../../tools/plan.js";
|
||||
|
||||
export interface SlashResult {
|
||||
/** Text to display back to the user as a system/info line. */
|
||||
info?: string;
|
||||
/** Exit the app. */
|
||||
exit?: boolean;
|
||||
/** Clear the visible history. */
|
||||
clear?: boolean;
|
||||
/** Unknown command — display usage hint. */
|
||||
unknown?: boolean;
|
||||
/**
|
||||
* Re-submit this text as a user message after displaying `info`.
|
||||
* Used by `/retry` — the slash command truncates the log, then
|
||||
* asks the TUI to push the original text back through the normal
|
||||
* submit flow so a fresh turn runs.
|
||||
*/
|
||||
resubmit?: string;
|
||||
/**
|
||||
* Render an archived plan as a read-only "Time Travel" block in
|
||||
* scrollback. Populated by `/replay [N]`. The TUI mounts it as a
|
||||
* `plan-replay` DisplayEvent so the same step-list / risk gutter
|
||||
* styling gets reused. Strictly a display payload — no execution.
|
||||
*/
|
||||
replayPlan?: {
|
||||
summary?: string;
|
||||
body?: string;
|
||||
steps: PlanStep[];
|
||||
completedStepIds: string[];
|
||||
completedAt: string;
|
||||
relativeTime: string;
|
||||
archiveBasename: string;
|
||||
/** 1-based index in `/plans` listing — surfaced in the header. */
|
||||
index: number;
|
||||
/** Total archives at the time of the lookup; helps the user navigate. */
|
||||
total: number;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Extra runtime context a slash handler may care about but that isn't
|
||||
* already on the loop. Kept as an optional object so tests that only
|
||||
* need loop-scoped commands can skip it, and callers only populate the
|
||||
* slots that apply to their session.
|
||||
*/
|
||||
export interface SlashContext {
|
||||
/**
|
||||
* The exact `--mcp` / config-derived spec strings that were bridged
|
||||
* into this session (one entry per server). Used by `/mcp`. Empty or
|
||||
* omitted → no MCP servers attached.
|
||||
*/
|
||||
mcpSpecs?: string[];
|
||||
/**
|
||||
* Callback for `/undo` — provided by the TUI when it's running in
|
||||
* code mode. Returns a human-readable report of what was restored.
|
||||
* Absent outside code mode → `/undo` replies "not available here".
|
||||
* Accepts slash args: `[id]`, `[id, path]`.
|
||||
*/
|
||||
codeUndo?: (args: readonly string[]) => string;
|
||||
/**
|
||||
* Callback for `/apply` — commits pending edit blocks to disk. Returns
|
||||
* a report of what landed. Absent → `/apply` replies "nothing pending"
|
||||
* or "not available outside code mode".
|
||||
*/
|
||||
codeApply?: () => string;
|
||||
/**
|
||||
* Callback for `/discard` — drops the pending edit blocks without
|
||||
* touching disk.
|
||||
*/
|
||||
codeDiscard?: () => string;
|
||||
/**
|
||||
* Callback for `/history` — returns a human-readable list of every
|
||||
* edit batch this session, newest last. Includes entry ids (for
|
||||
* `/show`) and undone status.
|
||||
*/
|
||||
codeHistory?: () => string;
|
||||
/**
|
||||
* Callback for `/show [id] [path]` — with no args, shows a per-file
|
||||
* summary of the newest non-undone entry. With id only, the entry's
|
||||
* per-file summary. With id + path, the full diff of that single
|
||||
* file in that entry.
|
||||
*/
|
||||
codeShowEdit?: (args: readonly string[]) => string;
|
||||
/**
|
||||
* Root directory passed by `reasonix code`. Enables `/commit`, which
|
||||
* runs `git add -A && git commit` in this directory. Missing → `/commit`
|
||||
* replies "only available in code mode".
|
||||
*/
|
||||
codeRoot?: string;
|
||||
/**
|
||||
* How many edit blocks are currently pending `/apply` or `/discard`.
|
||||
* Surfaced by `/status`. TUI populates it live from its pending ref;
|
||||
* omitted → treat as 0 (chat-only session).
|
||||
*/
|
||||
pendingEditCount?: number;
|
||||
/**
|
||||
* Callback returning every tool result seen this session in
|
||||
* chronological order (oldest first). Powers `/tool [N]` for
|
||||
* inspecting the full untruncated output that `EventLog` clips at
|
||||
* 400 chars for display. Absent → `/tool` replies "not available".
|
||||
*/
|
||||
toolHistory?: () => Array<{ toolName: string; text: string }>;
|
||||
/**
|
||||
* Pre-captured inspection reports for each connected MCP server.
|
||||
* Populated once at chat startup (chat.tsx) so `/mcp` can render
|
||||
* tools + resources + prompts synchronously without needing async
|
||||
* handler support.
|
||||
*/
|
||||
mcpServers?: McpServerSummary[];
|
||||
/**
|
||||
* Directory `/memory` should resolve `REASONIX.md` from. In code
|
||||
* mode this is the rootDir the filesystem tools are pinned to; in
|
||||
* plain chat this is `process.cwd()` at launch time. Absent → the
|
||||
* TUI is running in some non-cwd context (tests) and `/memory`
|
||||
* replies "root unknown" instead of silently reading a different dir.
|
||||
*/
|
||||
memoryRoot?: string;
|
||||
/**
|
||||
* Current plan-mode state, surfaced in `/status` and toggled by
|
||||
* `/plan`. Present iff the session is a `reasonix code` run — chat
|
||||
* mode doesn't have plan mode.
|
||||
*/
|
||||
planMode?: boolean;
|
||||
/**
|
||||
* Current edit-gate mode (`review` or `auto`). Surfaced in `/status`,
|
||||
* toggled by `/mode`, also flipped by the Shift+Tab keybind in the
|
||||
* TUI. Absent → not in `reasonix code`.
|
||||
*/
|
||||
editMode?: EditMode;
|
||||
/**
|
||||
* Set the edit-gate mode. Callback rather than raw state so App can
|
||||
* also persist the choice to config and echo the change in historical.
|
||||
*/
|
||||
setEditMode?: (mode: EditMode) => void;
|
||||
/**
|
||||
* Background-process registry backing /jobs / /kill / /logs. Present
|
||||
* iff the session is a `reasonix code` run. Slash handlers expect
|
||||
* synchronous info strings, but stop_job is async — we return a
|
||||
* "stopping, watch /jobs" info and let the registry do its thing.
|
||||
*/
|
||||
jobs?: JobRegistry;
|
||||
/**
|
||||
* Async-late append to the historical log. /kill uses this to
|
||||
* surface "job N stopped" the moment stop() actually resolves,
|
||||
* rather than leaving the user to poll /jobs themselves.
|
||||
*/
|
||||
postInfo?: (text: string) => void;
|
||||
/**
|
||||
* Callback the `/plan` slash uses to flip plan mode on/off. Also
|
||||
* mirrors the state to the underlying ToolRegistry so dispatch
|
||||
* enforcement follows. Absent → `/plan` replies "only available in
|
||||
* code mode".
|
||||
*/
|
||||
setPlanMode?: (on: boolean) => void;
|
||||
/**
|
||||
* Callback that clears a pending-plan picker state. Called by
|
||||
* `/apply-plan` so that when the user force-approves, the picker
|
||||
* dismisses without also firing its own approval synthetic (the
|
||||
* slash returns its own `resubmit` instead). Safe to call with no
|
||||
* pending plan.
|
||||
*/
|
||||
clearPendingPlan?: () => void;
|
||||
/**
|
||||
* Re-load `~/.reasonix/settings.json` + `<project>/.reasonix/settings.json`
|
||||
* and update both the App's hook state and the loop's mutable hook
|
||||
* list. Returns the new hook count so the slash can echo a sane
|
||||
* confirmation. Absent → `/hooks reload` replies "not available".
|
||||
*/
|
||||
reloadHooks?: () => number;
|
||||
/**
|
||||
* Latest published version if App's background registry check
|
||||
* has completed, `null` otherwise (still in flight OR offline).
|
||||
* Drives `/update` — the slash shows whatever the async check
|
||||
* already resolved, so the command is fully synchronous.
|
||||
*/
|
||||
latestVersion?: string | null;
|
||||
/**
|
||||
* Fire-and-forget: kick off a fresh registry fetch. `/update`
|
||||
* calls this whenever it encounters `latestVersion === null`
|
||||
* so the user can rerun the slash a few seconds later and see
|
||||
* a concrete answer. Absent → the slash just reports "pending"
|
||||
* with no retry path.
|
||||
*/
|
||||
refreshLatestVersion?: () => void;
|
||||
/**
|
||||
* Model catalog fetched from DeepSeek's `/models` endpoint at App
|
||||
* mount. `null` → still in flight or the call failed (auth / offline);
|
||||
* `[]` → the API answered with zero entries. `/models` uses this to
|
||||
* render the list, and `/model <id>` uses it for soft validation
|
||||
* (warn-only — we still switch even on unknown ids since the list
|
||||
* can lag a newly-released model).
|
||||
*/
|
||||
models?: string[] | null;
|
||||
/**
|
||||
* Fire-and-forget refresh for the models list. Lets `/models` retry
|
||||
* after a flaky first fetch without needing async slash support.
|
||||
*/
|
||||
refreshModels?: () => void;
|
||||
/**
|
||||
* Arm pro for the next turn. Called by `/pro`. The TUI wires this
|
||||
* to both `loop.armProForNextTurn()` and its React mirror state so
|
||||
* the StatsPanel badge flips immediately. Absent → the handler
|
||||
* calls `loop.armProForNextTurn()` directly and the badge updates
|
||||
* on the next render tick (slightly laggy but still correct).
|
||||
*/
|
||||
armPro?: () => void;
|
||||
/** Cancel a pending /pro arming. Mirrors `armPro` semantics. */
|
||||
disarmPro?: () => void;
|
||||
}
|
||||
|
||||
export interface McpServerSummary {
|
||||
/** Short label shown in the `/mcp` output (server namespace or "anon"). */
|
||||
label: string;
|
||||
/** Original --mcp spec string. */
|
||||
spec: string;
|
||||
/** Count of tools bridged into the Reasonix registry from this server. */
|
||||
toolCount: number;
|
||||
/** Full inspection snapshot — used for the resources + prompts sections. */
|
||||
report: InspectionReport;
|
||||
/**
|
||||
* Live MCP client, kept so `/resource` and `/prompt` can call
|
||||
* `readResource` / `getPrompt` against this server. Omitted by
|
||||
* callers that only build the summary for display; those slashes
|
||||
* fall back to "not available" when the client is missing.
|
||||
*/
|
||||
client?: McpClient;
|
||||
}
|
||||
|
||||
/**
|
||||
* Slash command registry. Drives `/help`, the on-type suggestion
|
||||
* popup (`SlashSuggestions`), and auto-complete. Kept as data rather
|
||||
* than derived from the `handleSlash` switch so summaries can be
|
||||
* user-facing rather than code comments.
|
||||
*
|
||||
* `contextual` gates commands that only make sense in certain modes:
|
||||
* - `"code"` — only show when the TUI is running `reasonix code`
|
||||
* - absent → always shown
|
||||
*/
|
||||
export interface SlashCommandSpec {
|
||||
cmd: string;
|
||||
summary: string;
|
||||
contextual?: "code";
|
||||
/** If the command takes args, hint text shown after the name. */
|
||||
argsHint?: string;
|
||||
/**
|
||||
* How the first argument position should autocomplete. Shapes the
|
||||
* picker that appears below the prompt once the user types `/<cmd>`
|
||||
* + space:
|
||||
* - `"models"` → DeepSeek model-id list fetched at startup.
|
||||
* - `"mcp-resources"` → live URIs aggregated across connected MCP servers.
|
||||
* - `"mcp-prompts"` → live prompt names aggregated across MCP servers.
|
||||
* - `string[]` → small enum of literal values (e.g. `["on", "off"]`).
|
||||
* - omitted → no picker; a persistent usage hint shows the
|
||||
* argsHint + summary so the user knows what to type.
|
||||
*
|
||||
* File-path completion is deliberately NOT offered here. Users who
|
||||
* want to reference a file in a prompt use `@path/to/file` (0.5.5);
|
||||
* the `@` picker already surfaces files with mtime + recently-used
|
||||
* ranking. Adding a second file-picker surface for slash commands
|
||||
* would split the UX without adding leverage.
|
||||
*/
|
||||
argCompleter?: "models" | "mcp-resources" | "mcp-prompts" | readonly string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Shape describing what the prompt buffer is asking for AFTER the
|
||||
* user has committed to a slash command (`/<cmd>`) and started
|
||||
* typing its first argument. Consumed by the TUI to drive an
|
||||
* argument-level picker.
|
||||
*/
|
||||
export interface SlashArgContext {
|
||||
/** The command spec (looked up by name from SLASH_COMMANDS). */
|
||||
spec: SlashCommandSpec;
|
||||
/** The partial first-argument text, possibly empty. */
|
||||
partial: string;
|
||||
/**
|
||||
* Buffer offset where `partial` begins. Used by the TUI to splice
|
||||
* a picked completion back in at the right position.
|
||||
*/
|
||||
partialOffset: number;
|
||||
/**
|
||||
* Classification of what the caller should show:
|
||||
* - `"picker"` → an interactive picker (file / enum / models). The
|
||||
* caller uses `spec.argCompleter` to pick the data source and
|
||||
* filters against `partial`.
|
||||
* - `"hint"` → past the completable position (additional args or
|
||||
* no completer declared). Caller shows a dim usage hint only.
|
||||
*/
|
||||
kind: "picker" | "hint";
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
/**
|
||||
* One-line tool-result summarizer for the compact scrollback row.
|
||||
*
|
||||
* Old rendering: glyph + arrow + blank line + 400-char body block.
|
||||
* Cost ~6–8 vertical lines per tool call. Long sessions drown in
|
||||
* noise; the actually-interesting tool result (an edit diff, a
|
||||
* checkpoint signal) gets buried.
|
||||
*
|
||||
* New rendering: glyph + tool name + arrow + a SINGLE-LINE summary
|
||||
* tailored to the tool family. Full content stays in the tool history
|
||||
* and can be expanded via `/tool N`. edit_file keeps its multi-line
|
||||
* diff renderer (the diff IS the value).
|
||||
*
|
||||
* Pure function — lives outside EventLog.tsx so it's testable without
|
||||
* Ink and can be reused if other surfaces (replay, transcript export)
|
||||
* want the same one-liner.
|
||||
*/
|
||||
|
||||
const MAX_SUMMARY_CHARS = 80;
|
||||
const TRAILING_ELLIPSIS = "…";
|
||||
|
||||
export interface ToolSummary {
|
||||
/** Single-line summary text. Empty string if the result was empty. */
|
||||
summary: string;
|
||||
/** True when the tool result represents a failure the renderer should color red. */
|
||||
isError: boolean;
|
||||
}
|
||||
|
||||
function clip(s: string, max: number): string {
|
||||
if (s.length <= max) return s;
|
||||
return s.slice(0, Math.max(1, max - TRAILING_ELLIPSIS.length)) + TRAILING_ELLIPSIS;
|
||||
}
|
||||
|
||||
function firstNonEmptyLine(text: string): string {
|
||||
for (const line of text.split(/\r?\n/)) {
|
||||
const trimmed = line.trim();
|
||||
if (trimmed) return trimmed;
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
/**
|
||||
* Render a duration in milliseconds as a tight human label for the
|
||||
* compact tool row. Picks a representation that fits in ~5 chars so
|
||||
* the surrounding row stays readable on narrow terminals.
|
||||
*
|
||||
* < 100ms → "47ms"
|
||||
* < 1000ms → "0.4s"
|
||||
* < 60s → "12s" (or "1.2s" for sub-10-second times)
|
||||
* >= 60s → "1m30s"
|
||||
*/
|
||||
export function formatDuration(ms: number): string {
|
||||
if (!Number.isFinite(ms) || ms < 0) return "";
|
||||
if (ms < 100) return `${Math.round(ms)}ms`;
|
||||
if (ms < 1000) return `${(ms / 1000).toFixed(1)}s`;
|
||||
if (ms < 10_000) return `${(ms / 1000).toFixed(1)}s`;
|
||||
if (ms < 60_000) return `${Math.round(ms / 1000)}s`;
|
||||
const totalSec = Math.round(ms / 1000);
|
||||
const m = Math.floor(totalSec / 60);
|
||||
const s = totalSec % 60;
|
||||
return s === 0 ? `${m}m` : `${m}m${s}s`;
|
||||
}
|
||||
|
||||
function formatBytes(n: number): string {
|
||||
if (n < 1000) return `${n}B`;
|
||||
if (n < 1_000_000) return `${(n / 1000).toFixed(1)}KB`;
|
||||
return `${(n / 1_000_000).toFixed(1)}MB`;
|
||||
}
|
||||
|
||||
function formatLineCount(text: string): string {
|
||||
// Cheap line count — the +1 covers files without a trailing newline.
|
||||
const lines = text.split(/\r?\n/).length;
|
||||
return `${lines} line${lines === 1 ? "" : "s"}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Try to recognize a structured error envelope. Reasonix tools emit
|
||||
* `{ "error": "..." }` JSON for failures and structured payloads
|
||||
* (PlanProposedError carries `{error, plan, ...}`) for special
|
||||
* signals. We surface the error name as the summary so the user
|
||||
* sees what kind of failure happened at a glance.
|
||||
*/
|
||||
function summarizeStructured(content: string): ToolSummary | null {
|
||||
const trimmed = content.trim();
|
||||
if (!trimmed.startsWith("{")) return null;
|
||||
try {
|
||||
const parsed = JSON.parse(trimmed);
|
||||
if (!parsed || typeof parsed !== "object") return null;
|
||||
const obj = parsed as Record<string, unknown>;
|
||||
// Plan / choice signals come through as errors carrying structured
|
||||
// payloads — the App-level handlers extract the structured part.
|
||||
// For the tool row here we just want the tag.
|
||||
if (typeof obj.error === "string") {
|
||||
const tag = obj.error.split(":", 1)[0]?.trim() ?? "error";
|
||||
const detail = obj.error.slice(tag.length + 1).trim();
|
||||
// The tag-only case (no colon body) — show the bare tag.
|
||||
const summary = detail ? `${tag} — ${detail}` : tag;
|
||||
// Plan / Choice errors are control-flow signals, not real errors.
|
||||
const isControlSignal =
|
||||
tag === "PlanProposedError" ||
|
||||
tag === "PlanCheckpointError" ||
|
||||
tag === "PlanRevisionProposedError" ||
|
||||
tag === "ChoiceRequestedError" ||
|
||||
tag === "NeedsConfirmationError";
|
||||
return { summary: clip(summary, MAX_SUMMARY_CHARS), isError: !isControlSignal };
|
||||
}
|
||||
// step_completed payload (when used outside the error path, kept
|
||||
// for forward-compat with non-throwing variants).
|
||||
if (obj.kind === "step_completed" && typeof obj.stepId === "string") {
|
||||
const result = typeof obj.result === "string" ? obj.result : "";
|
||||
return {
|
||||
summary: clip(`✓ ${obj.stepId}: ${result}`, MAX_SUMMARY_CHARS),
|
||||
isError: false,
|
||||
};
|
||||
}
|
||||
return null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Per-tool-name overrides for cases where a smarter summary is cheap
|
||||
* to compute. Returning null means "fall through to the generic
|
||||
* summary path."
|
||||
*
|
||||
* Suffix-match is on purpose: MCP-bridged tools come in prefixed
|
||||
* (`filesystem_read_file`, `git_search_files`) and we want them to
|
||||
* pick up the same specialized summary as the bare local name.
|
||||
*/
|
||||
function summarizeKnownTool(toolName: string, content: string): ToolSummary | null {
|
||||
const hasSuffix = (s: string) => toolName === s || toolName.endsWith(`_${s}`);
|
||||
if (hasSuffix("read_file")) {
|
||||
const lines = formatLineCount(content);
|
||||
const bytes = formatBytes(content.length);
|
||||
const head = clip(
|
||||
firstNonEmptyLine(content),
|
||||
MAX_SUMMARY_CHARS - lines.length - bytes.length - 8,
|
||||
);
|
||||
return {
|
||||
summary: head ? `${head} · ${lines} · ${bytes}` : `${lines} · ${bytes}`,
|
||||
isError: false,
|
||||
};
|
||||
}
|
||||
if (hasSuffix("list_directory") || hasSuffix("directory_tree")) {
|
||||
const entries = content.split(/\r?\n/).filter((l) => l.trim()).length;
|
||||
return { summary: `${entries} entr${entries === 1 ? "y" : "ies"}`, isError: false };
|
||||
}
|
||||
if (hasSuffix("search_files") || hasSuffix("search_content")) {
|
||||
const matches = content.split(/\r?\n/).filter((l) => l.trim()).length;
|
||||
if (matches === 0) return { summary: "no matches", isError: false };
|
||||
const first = firstNonEmptyLine(content);
|
||||
return {
|
||||
summary: clip(`${matches} match${matches === 1 ? "" : "es"} · ${first}`, MAX_SUMMARY_CHARS),
|
||||
isError: false,
|
||||
};
|
||||
}
|
||||
if (hasSuffix("write_file")) {
|
||||
const lines = formatLineCount(content);
|
||||
const bytes = formatBytes(content.length);
|
||||
return { summary: `wrote ${lines} · ${bytes}`, isError: false };
|
||||
}
|
||||
if (hasSuffix("run_command") || hasSuffix("run_background")) {
|
||||
// Native shell tools prepend "exit 0:" / "exit N:" or the result
|
||||
// already mentions exit code. Try to surface it.
|
||||
const exitMatch = content.match(/exit (?:code )?(-?\d+)/i);
|
||||
const first = firstNonEmptyLine(content);
|
||||
if (exitMatch) {
|
||||
const code = exitMatch[1];
|
||||
const isError = code !== "0";
|
||||
return {
|
||||
summary: clip(`exit ${code} · ${first}`, MAX_SUMMARY_CHARS),
|
||||
isError,
|
||||
};
|
||||
}
|
||||
return { summary: clip(first || "(no output)", MAX_SUMMARY_CHARS), isError: false };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function summarizeToolResult(toolName: string, content: string): ToolSummary {
|
||||
const isExplicitError = content.startsWith("ERROR:");
|
||||
if (isExplicitError) {
|
||||
const stripped = content.slice("ERROR:".length).trim();
|
||||
return { summary: clip(stripped || "(unknown error)", MAX_SUMMARY_CHARS), isError: true };
|
||||
}
|
||||
const structured = summarizeStructured(content);
|
||||
if (structured) return structured;
|
||||
const known = summarizeKnownTool(toolName, content);
|
||||
if (known) return known;
|
||||
// Generic: first line + size hint.
|
||||
const first = firstNonEmptyLine(content);
|
||||
if (!content.trim()) return { summary: "(empty)", isError: false };
|
||||
if (content.length <= MAX_SUMMARY_CHARS) {
|
||||
return { summary: clip(first, MAX_SUMMARY_CHARS), isError: false };
|
||||
}
|
||||
const sizeHint = formatBytes(content.length);
|
||||
const head = clip(first, MAX_SUMMARY_CHARS - sizeHint.length - 3);
|
||||
return { summary: `${head} · ${sizeHint}`, isError: false };
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import {
|
||||
type FileWithStats,
|
||||
detectAtPicker,
|
||||
listFilesWithStatsSync,
|
||||
rankPickerCandidates,
|
||||
} from "../../at-mentions.js";
|
||||
import {
|
||||
type McpServerSummary,
|
||||
type SlashArgContext,
|
||||
type SlashCommandSpec,
|
||||
detectSlashArgContext,
|
||||
suggestSlashCommands,
|
||||
} from "./slash.js";
|
||||
|
||||
export interface UseCompletionPickersParams {
|
||||
input: string;
|
||||
setInput: (v: string) => void;
|
||||
codeMode: { rootDir: string } | undefined;
|
||||
models: string[] | null;
|
||||
mcpServers: McpServerSummary[] | undefined;
|
||||
}
|
||||
|
||||
export interface UseCompletionPickersResult {
|
||||
// ── slash-name picker ──
|
||||
slashMatches: SlashCommandSpec[] | null;
|
||||
slashSelected: number;
|
||||
setSlashSelected: React.Dispatch<React.SetStateAction<number>>;
|
||||
|
||||
// ── @-mention picker ──
|
||||
atPicker: ReturnType<typeof detectAtPicker>;
|
||||
atMatches: readonly string[] | null;
|
||||
atSelected: number;
|
||||
setAtSelected: React.Dispatch<React.SetStateAction<number>>;
|
||||
pickAtMention: (chosenPath: string) => void;
|
||||
recordRecentFile: (path: string) => void;
|
||||
|
||||
// ── slash-arg picker ──
|
||||
slashArgContext: SlashArgContext | null;
|
||||
slashArgMatches: readonly string[] | null;
|
||||
slashArgSelected: number;
|
||||
setSlashArgSelected: React.Dispatch<React.SetStateAction<number>>;
|
||||
pickSlashArg: (chosen: string) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* The three mutually-exclusive input-prefix pickers share enough
|
||||
* structure (matches list + highlighted index + reset-on-shrink effect
|
||||
* + commit-back-into-buffer callback) that they live together here.
|
||||
* Priority in the parent useInput handler:
|
||||
* atMatches > slashArgMatches > slashMatches > prompt history
|
||||
* detection already disambiguates by construction — the slash-name
|
||||
* picker fires only when the buffer has no space; the slash-arg picker
|
||||
* only after a space; the @-picker only outside slash mode.
|
||||
*/
|
||||
export function useCompletionPickers({
|
||||
input,
|
||||
setInput,
|
||||
codeMode,
|
||||
models,
|
||||
mcpServers,
|
||||
}: UseCompletionPickersParams): UseCompletionPickersResult {
|
||||
// ── slash-name picker ──
|
||||
const [slashSelected, setSlashSelected] = useState(0);
|
||||
const slashMatches = useMemo(() => {
|
||||
if (!input.startsWith("/") || input.includes(" ")) return null;
|
||||
return suggestSlashCommands(input.slice(1), !!codeMode);
|
||||
}, [input, codeMode]);
|
||||
useEffect(() => {
|
||||
setSlashSelected((prev) => {
|
||||
if (!slashMatches || slashMatches.length === 0) return 0;
|
||||
if (prev >= slashMatches.length) return slashMatches.length - 1;
|
||||
return prev;
|
||||
});
|
||||
}, [slashMatches]);
|
||||
|
||||
// ── @-mention picker ──
|
||||
const [atSelected, setAtSelected] = useState(0);
|
||||
// Walk the code root ONCE on mount, collecting mtime alongside path
|
||||
// so the picker can surface recently-edited files first. Files
|
||||
// created mid-session via tool edits won't appear until restart —
|
||||
// rare, and the user can always type the full path.
|
||||
const atFiles = useMemo<readonly FileWithStats[]>(() => {
|
||||
if (!codeMode?.rootDir) return [];
|
||||
try {
|
||||
return listFilesWithStatsSync(codeMode.rootDir, { maxResults: 500 });
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}, [codeMode?.rootDir]);
|
||||
// LRU of files touched by recent tool calls. Seeds the picker with
|
||||
// "stuff I just looked at" at the top, so a user typing `@` in the
|
||||
// same file they were just discussing gets it instantly.
|
||||
const recentFilesRef = useRef<string[]>([]);
|
||||
const recordRecentFile = useCallback((p: string) => {
|
||||
const list = recentFilesRef.current;
|
||||
const i = list.indexOf(p);
|
||||
if (i >= 0) list.splice(i, 1);
|
||||
list.unshift(p);
|
||||
if (list.length > 20) list.length = 20;
|
||||
}, []);
|
||||
const atPicker = useMemo(() => {
|
||||
if (!codeMode?.rootDir) return null;
|
||||
// Slash prefix wins — avoids the picker confusingly surfacing on
|
||||
// `/@wat`-style edge inputs.
|
||||
if (slashMatches !== null) return null;
|
||||
return detectAtPicker(input);
|
||||
}, [codeMode?.rootDir, input, slashMatches]);
|
||||
const atMatches = useMemo<readonly string[] | null>(() => {
|
||||
if (!atPicker) return null;
|
||||
return rankPickerCandidates(atFiles, atPicker.query, {
|
||||
limit: 40,
|
||||
recentlyUsed: recentFilesRef.current,
|
||||
});
|
||||
}, [atPicker, atFiles]);
|
||||
useEffect(() => {
|
||||
setAtSelected((prev) => {
|
||||
if (!atMatches || atMatches.length === 0) return 0;
|
||||
if (prev >= atMatches.length) return atMatches.length - 1;
|
||||
return prev;
|
||||
});
|
||||
}, [atMatches]);
|
||||
const pickAtMention = useCallback(
|
||||
(chosenPath: string) => {
|
||||
if (!atPicker) return;
|
||||
const before = input.slice(0, atPicker.atOffset);
|
||||
setInput(`${before}@${chosenPath} `);
|
||||
},
|
||||
[atPicker, input, setInput],
|
||||
);
|
||||
|
||||
// ── slash-arg picker ──
|
||||
const [slashArgSelected, setSlashArgSelected] = useState(0);
|
||||
const slashArgContext = useMemo<SlashArgContext | null>(() => {
|
||||
if (!input.startsWith("/")) return null;
|
||||
if (slashMatches !== null) return null;
|
||||
return detectSlashArgContext(input, !!codeMode);
|
||||
}, [input, slashMatches, codeMode]);
|
||||
const slashArgMatches = useMemo<readonly string[] | null>(() => {
|
||||
if (!slashArgContext || slashArgContext.kind !== "picker") return null;
|
||||
const completer = slashArgContext.spec.argCompleter;
|
||||
const partial = slashArgContext.partial;
|
||||
const needle = partial.toLowerCase();
|
||||
// Once the partial is an EXACT match for a valid completion, hide
|
||||
// the picker so Enter submits the command instead of re-picking
|
||||
// the same value in an infinite loop. Case-insensitive — users
|
||||
// may type `/preset FAST` and still mean the same thing.
|
||||
if (Array.isArray(completer)) {
|
||||
if (partial && completer.some((v) => v.toLowerCase() === needle)) return null;
|
||||
if (!partial) return completer.slice();
|
||||
return completer.filter((v) => v.toLowerCase().startsWith(needle));
|
||||
}
|
||||
if (completer === "models") {
|
||||
const all = models ?? [];
|
||||
if (partial && all.some((m) => m.toLowerCase() === needle)) return null;
|
||||
if (!partial) return all.slice(0, 40);
|
||||
return all.filter((m) => m.toLowerCase().includes(needle)).slice(0, 40);
|
||||
}
|
||||
if (completer === "mcp-resources") {
|
||||
// Aggregate URIs across every server's cached inspection.
|
||||
const uris: string[] = [];
|
||||
const servers = mcpServers ?? [];
|
||||
for (const s of servers) {
|
||||
if (!s.report.resources.supported) continue;
|
||||
for (const r of s.report.resources.items) uris.push(r.uri);
|
||||
}
|
||||
if (partial && uris.some((u) => u.toLowerCase() === needle)) return null;
|
||||
if (!partial) return uris.slice(0, 40);
|
||||
return uris.filter((u) => u.toLowerCase().includes(needle)).slice(0, 40);
|
||||
}
|
||||
if (completer === "mcp-prompts") {
|
||||
const names: string[] = [];
|
||||
const servers = mcpServers ?? [];
|
||||
for (const s of servers) {
|
||||
if (!s.report.prompts.supported) continue;
|
||||
for (const p of s.report.prompts.items) names.push(p.name);
|
||||
}
|
||||
if (partial && names.some((n) => n.toLowerCase() === needle)) return null;
|
||||
if (!partial) return names.slice(0, 40);
|
||||
return names.filter((n) => n.toLowerCase().includes(needle)).slice(0, 40);
|
||||
}
|
||||
return null;
|
||||
}, [slashArgContext, models, mcpServers]);
|
||||
useEffect(() => {
|
||||
setSlashArgSelected((prev) => {
|
||||
if (!slashArgMatches || slashArgMatches.length === 0) return 0;
|
||||
if (prev >= slashArgMatches.length) return slashArgMatches.length - 1;
|
||||
return prev;
|
||||
});
|
||||
}, [slashArgMatches]);
|
||||
const pickSlashArg = useCallback(
|
||||
(chosen: string) => {
|
||||
if (!slashArgContext) return;
|
||||
const before = input.slice(0, slashArgContext.partialOffset);
|
||||
// No trailing space — enum picks take no further args, so the
|
||||
// user presses Enter once more to run the command.
|
||||
setInput(`${before}${chosen}`);
|
||||
},
|
||||
[slashArgContext, input, setInput],
|
||||
);
|
||||
|
||||
return {
|
||||
slashMatches,
|
||||
slashSelected,
|
||||
setSlashSelected,
|
||||
atPicker,
|
||||
atMatches,
|
||||
atSelected,
|
||||
setAtSelected,
|
||||
pickAtMention,
|
||||
recordRecentFile,
|
||||
slashArgContext,
|
||||
slashArgMatches,
|
||||
slashArgSelected,
|
||||
setSlashArgSelected,
|
||||
pickSlashArg,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,309 @@
|
||||
import { useCallback, useRef, useState } from "react";
|
||||
import { formatAllBlockDiffs } from "../../code/diff-preview.js";
|
||||
import {
|
||||
type ApplyResult,
|
||||
type EditBlock,
|
||||
type EditSnapshot,
|
||||
restoreSnapshots,
|
||||
} from "../../code/edit-blocks.js";
|
||||
import {
|
||||
type EditHistoryEntry,
|
||||
entryStatus,
|
||||
formatUndoRows,
|
||||
isEntryFullyUndone,
|
||||
} from "./edit-history.js";
|
||||
|
||||
export interface UndoBannerState {
|
||||
results: ApplyResult[];
|
||||
expiresAt: number;
|
||||
}
|
||||
|
||||
export interface UseEditHistoryResult {
|
||||
/** Post-auto-apply banner state — rendered at the bottom for 5s. */
|
||||
undoBanner: UndoBannerState | null;
|
||||
/**
|
||||
* Append a batch of successfully-applied edits into the session's
|
||||
* edit history. If the current turn already has an open entry,
|
||||
* append into it (first-wins-per-path so `/undo` restores the
|
||||
* pre-turn state, not an intermediate half-edit). Otherwise open a
|
||||
* new entry.
|
||||
*/
|
||||
recordEdit: (
|
||||
source: string,
|
||||
blocks: readonly EditBlock[],
|
||||
results: readonly ApplyResult[],
|
||||
snaps: readonly EditSnapshot[],
|
||||
) => void;
|
||||
/**
|
||||
* Show the post-auto-apply undo banner for 5 seconds. Overwrites any
|
||||
* prior banner and replaces the auto-dismiss timer so multiple
|
||||
* edits inside a single turn don't prematurely expire the window.
|
||||
*/
|
||||
armUndoBanner: (results: ApplyResult[]) => void;
|
||||
/**
|
||||
* `/undo` — revert applied edits.
|
||||
* `/undo` → newest non-fully-undone entry, all its
|
||||
* remaining (non-undone) files.
|
||||
* `/undo <id>` → that specific entry's remaining files.
|
||||
* `/undo <id> <path>` → just that one file in that entry.
|
||||
* Works as long as the session is alive; no 5-second banner limit.
|
||||
*/
|
||||
codeUndo: (args?: readonly string[]) => string;
|
||||
/**
|
||||
* `/history` — list every edit batch this session. Each entry's id
|
||||
* is the token for `/show <id>` and the target of per-batch undo.
|
||||
*/
|
||||
codeHistory: () => string;
|
||||
/**
|
||||
* `/show` — inspect a stored edit batch.
|
||||
* `/show` → newest non-fully-undone entry, per-file summary.
|
||||
* `/show <id>` → that entry's per-file summary.
|
||||
* `/show <id> <path>` → full diff of one file in that entry.
|
||||
*/
|
||||
codeShowEdit: (args?: readonly string[]) => string;
|
||||
/**
|
||||
* Seal the in-progress entry so the next edit opens a fresh one.
|
||||
* Called at handleSubmit start — prior turns stay intact for
|
||||
* `/history` and `/undo` to walk through independently.
|
||||
*/
|
||||
sealCurrentEntry: () => void;
|
||||
/**
|
||||
* True when there's at least one history entry that isn't fully
|
||||
* undone yet. Used by the `u` keybind and the bottom ModeStatusBar.
|
||||
* Reads the ref fresh — callers must re-read each time.
|
||||
*/
|
||||
hasUndoable: () => boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Session-scoped edit history and undo machinery for `reasonix code`.
|
||||
* Keeps the history ref + snapshot bookkeeping out of App.tsx so the
|
||||
* parent only sees a small API: append, banner, three slash handlers,
|
||||
* a turn sealer, and an undoable probe.
|
||||
*
|
||||
* `codeMode` is optional because the hook is always mounted but its
|
||||
* handlers turn into no-ops when code mode isn't active.
|
||||
*/
|
||||
export function useEditHistory(codeMode: { rootDir: string } | undefined): UseEditHistoryResult {
|
||||
const editHistory = useRef<EditHistoryEntry[]>([]);
|
||||
const nextHistoryId = useRef(1);
|
||||
const currentTurnEntry = useRef<EditHistoryEntry | null>(null);
|
||||
const [undoBanner, setUndoBanner] = useState<UndoBannerState | null>(null);
|
||||
const undoTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
const recordEdit = useCallback<UseEditHistoryResult["recordEdit"]>(
|
||||
(source, blocks, results, snaps) => {
|
||||
if (snaps.length === 0) return;
|
||||
let entry = currentTurnEntry.current;
|
||||
if (!entry) {
|
||||
entry = {
|
||||
id: nextHistoryId.current++,
|
||||
at: Date.now(),
|
||||
source,
|
||||
blocks: [],
|
||||
results: [],
|
||||
snapshots: [],
|
||||
undoneFiles: new Set<string>(),
|
||||
};
|
||||
currentTurnEntry.current = entry;
|
||||
editHistory.current.push(entry);
|
||||
}
|
||||
entry.blocks.push(...blocks);
|
||||
entry.results.push(...results);
|
||||
const seen = new Set(entry.snapshots.map((s) => s.path));
|
||||
for (const s of snaps) {
|
||||
if (!seen.has(s.path)) entry.snapshots.push(s);
|
||||
}
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const armUndoBanner = useCallback<UseEditHistoryResult["armUndoBanner"]>((results) => {
|
||||
setUndoBanner({ results, expiresAt: Date.now() + 5000 });
|
||||
if (undoTimeoutRef.current) clearTimeout(undoTimeoutRef.current);
|
||||
undoTimeoutRef.current = setTimeout(() => {
|
||||
setUndoBanner(null);
|
||||
undoTimeoutRef.current = null;
|
||||
}, 5000);
|
||||
}, []);
|
||||
|
||||
const codeUndo = useCallback<UseEditHistoryResult["codeUndo"]>(
|
||||
(args = []) => {
|
||||
if (!codeMode) return "not in code mode";
|
||||
const root = codeMode.rootDir;
|
||||
|
||||
const revert = (entry: EditHistoryEntry, paths: readonly string[]): string => {
|
||||
const subset = entry.snapshots.filter((s) => paths.includes(s.path));
|
||||
if (subset.length === 0) {
|
||||
return `batch #${entry.id}: nothing to undo (already restored or path not in batch)`;
|
||||
}
|
||||
const results = restoreSnapshots(subset, root);
|
||||
for (const s of subset) entry.undoneFiles.add(s.path);
|
||||
if (currentTurnEntry.current === entry && isEntryFullyUndone(entry)) {
|
||||
currentTurnEntry.current = null;
|
||||
}
|
||||
if (undoTimeoutRef.current) {
|
||||
clearTimeout(undoTimeoutRef.current);
|
||||
undoTimeoutRef.current = null;
|
||||
}
|
||||
setUndoBanner(null);
|
||||
const when = new Date(entry.at).toISOString().replace("T", " ").slice(11, 19);
|
||||
const scope = subset.length === 1 ? subset[0]!.path : `${subset.length} file(s)`;
|
||||
const header = `▸ undo: reverted ${scope} from batch #${entry.id} (${when})`;
|
||||
return [header, ...formatUndoRows(results)].join("\n");
|
||||
};
|
||||
|
||||
const idArg = args[0];
|
||||
const pathArg = args[1];
|
||||
|
||||
if (!idArg) {
|
||||
for (let i = editHistory.current.length - 1; i >= 0; i--) {
|
||||
const e = editHistory.current[i]!;
|
||||
if (isEntryFullyUndone(e)) continue;
|
||||
const remaining = e.snapshots.map((s) => s.path).filter((p) => !e.undoneFiles.has(p));
|
||||
return revert(e, remaining);
|
||||
}
|
||||
return "nothing to undo — every batch in the session history is already undone";
|
||||
}
|
||||
|
||||
const id = Number.parseInt(idArg, 10);
|
||||
if (!Number.isFinite(id)) {
|
||||
return "usage: /undo [id] [path] (omit id for newest; id from /history; path from /show <id>)";
|
||||
}
|
||||
const entry = editHistory.current.find((e) => e.id === id);
|
||||
if (!entry) return `no edit #${id} — run /history to see valid ids`;
|
||||
|
||||
if (!pathArg) {
|
||||
const remaining = entry.snapshots
|
||||
.map((s) => s.path)
|
||||
.filter((p) => !entry.undoneFiles.has(p));
|
||||
if (remaining.length === 0) return `batch #${id} is already fully undone`;
|
||||
return revert(entry, remaining);
|
||||
}
|
||||
|
||||
const snap = entry.snapshots.find((s) => s.path === pathArg);
|
||||
if (!snap) {
|
||||
const files = [...new Set(entry.blocks.map((b) => b.path))];
|
||||
return `batch #${id} doesn't include "${pathArg}" — files in this batch: ${files.join(", ")}`;
|
||||
}
|
||||
if (entry.undoneFiles.has(pathArg)) {
|
||||
return `${pathArg} in batch #${id} is already undone`;
|
||||
}
|
||||
return revert(entry, [pathArg]);
|
||||
},
|
||||
[codeMode],
|
||||
);
|
||||
|
||||
const codeHistory = useCallback<UseEditHistoryResult["codeHistory"]>(() => {
|
||||
if (!codeMode) return "not in code mode";
|
||||
const entries = editHistory.current;
|
||||
if (entries.length === 0) return "no edits recorded this session yet";
|
||||
const lines = ["Edit history (oldest first):"];
|
||||
for (const e of entries) {
|
||||
const when = new Date(e.at).toISOString().replace("T", " ").slice(11, 19);
|
||||
const files = new Set(e.blocks.map((b) => b.path));
|
||||
const fileList = [...files].join(", ");
|
||||
const fileSummary = fileList.length > 60 ? `${fileList.slice(0, 60)}…` : fileList;
|
||||
const status = entryStatus(e);
|
||||
const statusText =
|
||||
status === "applied" ? "applied" : status === "PARTIAL" ? "PARTIAL" : "UNDONE ";
|
||||
lines.push(
|
||||
` #${String(e.id).padStart(3)} ${when} ${statusText} ${e.source.padEnd(12)} ${files.size} file · ${e.blocks.length} block ${fileSummary}`,
|
||||
);
|
||||
}
|
||||
lines.push("");
|
||||
lines.push(
|
||||
"/show <id> → per-file summary · /show <id> <path> → full diff of one file",
|
||||
);
|
||||
lines.push(
|
||||
"/undo → newest non-undone · /undo <id> [path] → target a specific batch or file",
|
||||
);
|
||||
return lines.join("\n");
|
||||
}, [codeMode]);
|
||||
|
||||
const codeShowEdit = useCallback<UseEditHistoryResult["codeShowEdit"]>(
|
||||
(args = []) => {
|
||||
if (!codeMode) return "not in code mode";
|
||||
const entries = editHistory.current;
|
||||
if (entries.length === 0) return "no edits recorded this session — /history is empty";
|
||||
|
||||
const idArg = args[0];
|
||||
const pathArg = args[1];
|
||||
|
||||
let entry: EditHistoryEntry | undefined;
|
||||
if (!idArg) {
|
||||
entry =
|
||||
[...entries].reverse().find((e) => !isEntryFullyUndone(e)) ?? entries[entries.length - 1];
|
||||
} else {
|
||||
const id = Number.parseInt(idArg, 10);
|
||||
if (!Number.isFinite(id)) {
|
||||
return "usage: /show [id] [path] (omit id for newest; path from the per-file summary)";
|
||||
}
|
||||
entry = entries.find((e) => e.id === id);
|
||||
if (!entry) return `no edit #${id} — run /history to see valid ids`;
|
||||
}
|
||||
if (!entry) return "unexpected: history lookup failed";
|
||||
|
||||
if (pathArg) {
|
||||
const fileBlocks = entry.blocks.filter((b) => b.path === pathArg);
|
||||
if (fileBlocks.length === 0) {
|
||||
const files = [...new Set(entry.blocks.map((b) => b.path))];
|
||||
return `batch #${entry.id} doesn't include "${pathArg}" — files in this batch: ${files.join(", ")}`;
|
||||
}
|
||||
const when = new Date(entry.at).toISOString().replace("T", " ").slice(11, 19);
|
||||
const state = entry.undoneFiles.has(pathArg) ? "UNDONE" : "applied";
|
||||
const header = `▸ edit #${entry.id} · ${when} · ${pathArg} · ${state} · ${fileBlocks.length} block(s)`;
|
||||
const diff = formatAllBlockDiffs(fileBlocks, { maxLines: 60, contextLines: 2 });
|
||||
const footer = entry.undoneFiles.has(pathArg)
|
||||
? "(already reverted — /history shows the batch-level status)"
|
||||
: `/undo ${entry.id} ${pathArg} → revert just this file`;
|
||||
return [header, ...diff, "", footer].join("\n");
|
||||
}
|
||||
|
||||
const when = new Date(entry.at).toISOString().replace("T", " ").slice(11, 19);
|
||||
const files = [...new Set(entry.blocks.map((b) => b.path))];
|
||||
const status = entryStatus(entry);
|
||||
const header = `▸ edit #${entry.id} · ${when} · ${entry.source} · ${status} · ${files.length} file(s)`;
|
||||
const countLines = (s: string) => (s.length === 0 ? 0 : (s.match(/\n/g)?.length ?? 0) + 1);
|
||||
const fileLines = files.map((path) => {
|
||||
const fileBlocks = entry!.blocks.filter((b) => b.path === path);
|
||||
let removed = 0;
|
||||
let added = 0;
|
||||
for (const b of fileBlocks) {
|
||||
removed += countLines(b.search);
|
||||
added += countLines(b.replace);
|
||||
}
|
||||
const state = entry!.undoneFiles.has(path) ? "UNDONE" : "applied";
|
||||
return ` ${state.padEnd(7)} -${String(removed).padStart(3)}/+${String(added).padStart(3)} ${path} (${fileBlocks.length} block${fileBlocks.length === 1 ? "" : "s"})`;
|
||||
});
|
||||
return [
|
||||
header,
|
||||
...fileLines,
|
||||
"",
|
||||
`/show ${entry.id} <path> → full diff of one file`,
|
||||
`/undo ${entry.id} <path> → revert just that file · /undo ${entry.id} → revert whole batch`,
|
||||
].join("\n");
|
||||
},
|
||||
[codeMode],
|
||||
);
|
||||
|
||||
const sealCurrentEntry = useCallback(() => {
|
||||
currentTurnEntry.current = null;
|
||||
}, []);
|
||||
|
||||
const hasUndoable = useCallback(
|
||||
() => editHistory.current.some((e) => !isEntryFullyUndone(e)),
|
||||
[],
|
||||
);
|
||||
|
||||
return {
|
||||
undoBanner,
|
||||
recordEdit,
|
||||
armUndoBanner,
|
||||
codeUndo,
|
||||
codeHistory,
|
||||
codeShowEdit,
|
||||
sealCurrentEntry,
|
||||
hasUndoable,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import type { CacheFirstLoop } from "../../loop.js";
|
||||
import { VERSION, compareVersions, getLatestVersion } from "../../version.js";
|
||||
|
||||
export interface Balance {
|
||||
currency: string;
|
||||
total: number;
|
||||
}
|
||||
|
||||
export interface UseSessionInfoResult {
|
||||
balance: Balance | null;
|
||||
models: string[] | null;
|
||||
latestVersion: string | null;
|
||||
/** Strictly-newer version string (for the header badge) — else `null`. */
|
||||
updateAvailable: string | null;
|
||||
refreshBalance: () => void;
|
||||
refreshModels: () => void;
|
||||
refreshLatestVersion: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ambient session-level data fetched from DeepSeek + the npm registry
|
||||
* at mount, refreshed either implicitly (balance after each turn) or
|
||||
* on demand (`/update`, `/models`).
|
||||
*
|
||||
* All three are best-effort — a `null` value means "not loaded yet or
|
||||
* the endpoint failed." The StatsPanel hides the cell in that case.
|
||||
*/
|
||||
export function useSessionInfo(loop: CacheFirstLoop): UseSessionInfoResult {
|
||||
const [balance, setBalance] = useState<Balance | null>(null);
|
||||
const [models, setModels] = useState<string[] | null>(null);
|
||||
const [latestVersion, setLatestVersion] = useState<string | null>(null);
|
||||
|
||||
// Fetch balance on mount. Non-blocking — the session works without
|
||||
// it; `null` hides the cell. handleSubmit calls refreshBalance in
|
||||
// its finally so the number tracks actual spend rather than
|
||||
// freezing at mount-time.
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
void (async () => {
|
||||
const bal = await loop.client.getBalance().catch(() => null);
|
||||
if (cancelled || !bal || !bal.balance_infos.length) return;
|
||||
const primary = bal.balance_infos[0]!;
|
||||
setBalance({ currency: primary.currency, total: Number(primary.total_balance) });
|
||||
})();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [loop]);
|
||||
|
||||
// Fetch the model catalog from DeepSeek once. Silent degrade on
|
||||
// failure (stays null), so `/models` can tell "still loading /
|
||||
// offline" apart from "loaded, here's the list."
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
void (async () => {
|
||||
const list = await loop.client.listModels().catch(() => null);
|
||||
if (cancelled || !list) return;
|
||||
setModels(list.data.map((m) => m.id));
|
||||
})();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [loop]);
|
||||
|
||||
// Background registry check — 24h disk cache absorbs repeated
|
||||
// launches, timeout bounded so a flaky network doesn't delay the
|
||||
// notification. `null` on failure (silent). We store the raw version
|
||||
// regardless of whether it's newer; the header badge's newer-only
|
||||
// check happens at the `updateAvailable` derivation below.
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
void (async () => {
|
||||
const latest = await getLatestVersion();
|
||||
if (cancelled || !latest) return;
|
||||
setLatestVersion(latest);
|
||||
})();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, []);
|
||||
|
||||
const updateAvailable =
|
||||
latestVersion && compareVersions(VERSION, latestVersion) < 0 ? latestVersion : null;
|
||||
|
||||
const refreshBalance = useCallback(() => {
|
||||
void (async () => {
|
||||
const bal = await loop.client.getBalance().catch(() => null);
|
||||
if (bal?.balance_infos.length) {
|
||||
const p = bal.balance_infos[0]!;
|
||||
setBalance({ currency: p.currency, total: Number(p.total_balance) });
|
||||
}
|
||||
})();
|
||||
}, [loop]);
|
||||
|
||||
const refreshModels = useCallback(() => {
|
||||
void (async () => {
|
||||
const list = await loop.client.listModels().catch(() => null);
|
||||
if (list) setModels(list.data.map((m) => m.id));
|
||||
})();
|
||||
}, [loop]);
|
||||
|
||||
const refreshLatestVersion = useCallback(() => {
|
||||
void (async () => {
|
||||
const fresh = await getLatestVersion({ force: true });
|
||||
if (fresh) setLatestVersion(fresh);
|
||||
})();
|
||||
}, []);
|
||||
|
||||
return {
|
||||
balance,
|
||||
models,
|
||||
latestVersion,
|
||||
updateAvailable,
|
||||
refreshBalance,
|
||||
refreshModels,
|
||||
refreshLatestVersion,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import type { SubagentEvent, SubagentSink } from "../../tools/subagent.js";
|
||||
import { appendUsage } from "../../usage.js";
|
||||
import type { DisplayEvent } from "./EventLog.js";
|
||||
|
||||
export interface SubagentActivity {
|
||||
task: string;
|
||||
iter: number;
|
||||
elapsedMs: number;
|
||||
}
|
||||
|
||||
export interface UseSubagentParams {
|
||||
session: string | undefined;
|
||||
setHistorical: React.Dispatch<React.SetStateAction<DisplayEvent[]>>;
|
||||
}
|
||||
|
||||
export interface UseSubagentResult {
|
||||
/** Live state for an in-flight subagent, null when none is running. */
|
||||
activity: SubagentActivity | null;
|
||||
/**
|
||||
* Ref captured by the loop's `subagentRunner` closure so even
|
||||
* late-spawned subagents find the current handler. Consumers pass
|
||||
* this to `spawnSubagent({ sink })`.
|
||||
*/
|
||||
sinkRef: React.MutableRefObject<SubagentSink>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Subagent UI wiring. `start` opens the activity row; each `progress`
|
||||
* updates iter + elapsed in place; `end` clears the row and posts a
|
||||
* one-line summary (with inline cost) into Historical. Only one
|
||||
* subagent is active at a time in the MVP — overlapping events just
|
||||
* replace the prior activity.
|
||||
*/
|
||||
export function useSubagent({ session, setHistorical }: UseSubagentParams): UseSubagentResult {
|
||||
const [activity, setActivity] = useState<SubagentActivity | null>(null);
|
||||
const sinkRef = useRef<SubagentSink>({ current: null });
|
||||
|
||||
useEffect(() => {
|
||||
sinkRef.current.current = (ev: SubagentEvent) => {
|
||||
if (ev.kind === "start") {
|
||||
setActivity({
|
||||
task: ev.task,
|
||||
iter: ev.iter ?? 0,
|
||||
elapsedMs: ev.elapsedMs ?? 0,
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (ev.kind === "progress") {
|
||||
setActivity({
|
||||
task: ev.task,
|
||||
iter: ev.iter ?? 0,
|
||||
elapsedMs: ev.elapsedMs ?? 0,
|
||||
});
|
||||
return;
|
||||
}
|
||||
// end
|
||||
setActivity(null);
|
||||
const seconds = ((ev.elapsedMs ?? 0) / 1000).toFixed(1);
|
||||
// Inline cost: the one number most users look at. Shown in the
|
||||
// Historical row so they don't have to run `/stats` to see it.
|
||||
const costTail =
|
||||
ev.costUsd !== undefined && ev.costUsd > 0 ? ` · $${ev.costUsd.toFixed(4)}` : "";
|
||||
const summary = ev.error
|
||||
? `⌬ subagent "${ev.task}" failed after ${seconds}s · ${ev.iter ?? 0} tool call(s) — ${ev.error}`
|
||||
: `⌬ subagent "${ev.task}" done in ${seconds}s · ${ev.iter ?? 0} tool call(s) · ${ev.turns ?? 0} turn(s)${costTail}`;
|
||||
setHistorical((prev) => [
|
||||
...prev,
|
||||
{
|
||||
id: `subagent-end-${Date.now()}`,
|
||||
role: "info",
|
||||
text: summary,
|
||||
},
|
||||
]);
|
||||
// Persist a subagent summary row to ~/.reasonix/usage.jsonl so
|
||||
// `/stats` and `reasonix stats` surface it. Skipped on error —
|
||||
// we only record what actually cost money and did work.
|
||||
if (!ev.error && ev.usage && ev.model) {
|
||||
appendUsage({
|
||||
session: session ?? null,
|
||||
model: ev.model,
|
||||
usage: ev.usage,
|
||||
kind: "subagent",
|
||||
subagent: {
|
||||
skillName: ev.skillName,
|
||||
taskPreview: ev.task.slice(0, 60),
|
||||
toolIters: ev.iter ?? 0,
|
||||
durationMs: ev.elapsedMs ?? 0,
|
||||
},
|
||||
});
|
||||
}
|
||||
};
|
||||
return () => {
|
||||
sinkRef.current.current = null;
|
||||
};
|
||||
}, [session, setHistorical]);
|
||||
|
||||
return { activity, sinkRef };
|
||||
}
|
||||
+104
-1
@@ -45,6 +45,42 @@ export interface StreamChunk {
|
||||
raw: any;
|
||||
}
|
||||
|
||||
/**
|
||||
* Response shape for DeepSeek's `/user/balance` endpoint. One entry
|
||||
* per currency the account is funded in (typically CNY, sometimes
|
||||
* USD). `total_balance` is the spendable figure; `granted_balance`
|
||||
* counts promotional credits that expire, `topped_up_balance` is
|
||||
* what the user paid for and keeps.
|
||||
*/
|
||||
export interface BalanceInfo {
|
||||
currency: string;
|
||||
total_balance: string;
|
||||
granted_balance?: string;
|
||||
topped_up_balance?: string;
|
||||
}
|
||||
|
||||
export interface UserBalance {
|
||||
is_available: boolean;
|
||||
balance_infos: BalanceInfo[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Response shape for DeepSeek's `/models` endpoint. Mirrors the OpenAI
|
||||
* models list shape DeepSeek copied — `id` is the model name to pass to
|
||||
* `/chat/completions`, `owned_by` is the provider string (always
|
||||
* `"deepseek"` today).
|
||||
*/
|
||||
export interface ModelInfo {
|
||||
id: string;
|
||||
object: "model";
|
||||
owned_by: string;
|
||||
}
|
||||
|
||||
export interface ModelList {
|
||||
object: "list";
|
||||
data: ModelInfo[];
|
||||
}
|
||||
|
||||
export interface DeepSeekClientOptions {
|
||||
apiKey?: string;
|
||||
baseUrl?: string;
|
||||
@@ -74,7 +110,17 @@ export class DeepSeekClient {
|
||||
process.env.DEEPSEEK_BASE_URL ??
|
||||
"https://api.deepseek.com"
|
||||
).replace(/\/+$/, "");
|
||||
this.timeoutMs = opts.timeoutMs ?? 120_000;
|
||||
// 11 min. DeepSeek's load-balancer may keep a connection open for
|
||||
// up to 10 minutes while the request waits in queue (non-streaming
|
||||
// sends empty lines, streaming sends `:` SSE keep-alive comments —
|
||||
// both are invisible to our parsers, so neither surfaces until the
|
||||
// real response starts). Timing out at the legacy 2-min default
|
||||
// killed queued requests prematurely, burned the queue slot on
|
||||
// retry, and could loop through the whole queue repeatedly.
|
||||
// Setting 11 min lets the server's own 10-min cap close the
|
||||
// connection first (clean EOF → natural retry), and our timer
|
||||
// is a safety net for genuinely hung sockets.
|
||||
this.timeoutMs = opts.timeoutMs ?? 660_000;
|
||||
this._fetch = opts.fetch ?? globalThis.fetch.bind(globalThis);
|
||||
this.retry = opts.retry ?? {};
|
||||
}
|
||||
@@ -89,9 +135,66 @@ export class DeepSeekClient {
|
||||
if (opts.temperature !== undefined) payload.temperature = opts.temperature;
|
||||
if (opts.maxTokens !== undefined) payload.max_tokens = opts.maxTokens;
|
||||
if (opts.responseFormat) payload.response_format = opts.responseFormat;
|
||||
// V4 thinking-mode toggle: lives under `extra_body.thinking.type` per
|
||||
// DeepSeek's docs. Docs also note that in thinking mode `temperature`,
|
||||
// `top_p`, `presence_penalty`, `frequency_penalty` are silently
|
||||
// ignored — we don't strip them here because the server's explicit
|
||||
// "setting won't report an error" contract means leaving them in is
|
||||
// safe and keeps the request payload diffable against OpenAI tooling.
|
||||
if (opts.thinking) {
|
||||
payload.extra_body = { thinking: { type: opts.thinking } };
|
||||
}
|
||||
if (opts.reasoningEffort) {
|
||||
payload.reasoning_effort = opts.reasoningEffort;
|
||||
}
|
||||
return payload;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch the current DeepSeek account balance. Separate endpoint
|
||||
* from chat completions, no billing impact. Returns null on any
|
||||
* network/auth failure so callers can gate the balance display
|
||||
* without a hard error — the rest of the session works regardless.
|
||||
*/
|
||||
async getBalance(opts: { signal?: AbortSignal } = {}): Promise<UserBalance | null> {
|
||||
try {
|
||||
const resp = await this._fetch(`${this.baseUrl}/user/balance`, {
|
||||
method: "GET",
|
||||
headers: { Authorization: `Bearer ${this.apiKey}` },
|
||||
signal: opts.signal,
|
||||
});
|
||||
if (!resp.ok) return null;
|
||||
const data = (await resp.json()) as UserBalance;
|
||||
if (!data || !Array.isArray(data.balance_infos)) return null;
|
||||
return data;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch the model catalog DeepSeek currently exposes. Today this is
|
||||
* `deepseek-chat` (V3) and `deepseek-reasoner` (R1), but querying is
|
||||
* the only way to learn about new ones without a Reasonix release.
|
||||
* Returns null on any network/auth failure so callers can degrade
|
||||
* gracefully — e.g. `/models` falls back to the hardcoded hint.
|
||||
*/
|
||||
async listModels(opts: { signal?: AbortSignal } = {}): Promise<ModelList | null> {
|
||||
try {
|
||||
const resp = await this._fetch(`${this.baseUrl}/models`, {
|
||||
method: "GET",
|
||||
headers: { Authorization: `Bearer ${this.apiKey}` },
|
||||
signal: opts.signal,
|
||||
});
|
||||
if (!resp.ok) return null;
|
||||
const data = (await resp.json()) as ModelList;
|
||||
if (!data || !Array.isArray(data.data)) return null;
|
||||
return data;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async chat(opts: ChatRequestOptions): Promise<ChatResponse> {
|
||||
const ctrl = new AbortController();
|
||||
const timer = setTimeout(() => ctrl.abort(), this.timeoutMs);
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
/**
|
||||
* Render a SEARCH/REPLACE edit block as a compact unified-diff-style
|
||||
* preview for the code-mode confirm gate. Shows the user what's about
|
||||
* to land on disk BEFORE they press `y` — catches "wrong file" and
|
||||
* "wrong replacement" mistakes that the old path + line-count summary
|
||||
* couldn't.
|
||||
*
|
||||
* Not a full Myers diff: we trim shared leading/trailing lines as
|
||||
* context and render the middle divergence as `-old` / `+new`. That's
|
||||
* enough for the common SEARCH/REPLACE shape (small change inside a
|
||||
* function body, wrapped with a few lines of surrounding code for
|
||||
* uniqueness) and avoids pulling in a diff library.
|
||||
*/
|
||||
|
||||
import type { EditBlock } from "./edit-blocks.js";
|
||||
|
||||
export interface DiffPreviewOptions {
|
||||
/** How many lines of unchanged context to show at each end. Default 2. */
|
||||
contextLines?: number;
|
||||
/** Hard cap on total rendered lines. Default 20 — beyond this the preview collapses. */
|
||||
maxLines?: number;
|
||||
/** Indent applied to every output line. Default 8 spaces — matches the pending-preview nesting. */
|
||||
indent?: string;
|
||||
}
|
||||
|
||||
/** Render one edit block's diff. Returns an array of formatted lines. */
|
||||
export function formatEditBlockDiff(block: EditBlock, opts: DiffPreviewOptions = {}): string[] {
|
||||
const contextLines = Math.max(0, opts.contextLines ?? 2);
|
||||
const maxLines = Math.max(4, opts.maxLines ?? 20);
|
||||
const indent = opts.indent ?? " ";
|
||||
|
||||
const search = block.search === "" ? [] : block.search.split("\n");
|
||||
const replace = block.replace.split("\n");
|
||||
|
||||
// New-file case: no search to compare, show the full new content
|
||||
// (capped). Mark every line `+` so the user knows it's all additions.
|
||||
if (search.length === 0) {
|
||||
return renderAllPlus(replace, indent, maxLines);
|
||||
}
|
||||
|
||||
// Common leading / trailing lines — shared context we can collapse.
|
||||
let leading = 0;
|
||||
while (
|
||||
leading < search.length &&
|
||||
leading < replace.length &&
|
||||
search[leading] === replace[leading]
|
||||
) {
|
||||
leading++;
|
||||
}
|
||||
let trailing = 0;
|
||||
while (
|
||||
trailing < search.length - leading &&
|
||||
trailing < replace.length - leading &&
|
||||
search[search.length - 1 - trailing] === replace[replace.length - 1 - trailing]
|
||||
) {
|
||||
trailing++;
|
||||
}
|
||||
|
||||
const searchMiddle = search.slice(leading, search.length - trailing);
|
||||
const replaceMiddle = replace.slice(leading, replace.length - trailing);
|
||||
|
||||
// Trim context to `contextLines` on each side.
|
||||
const leadShown = search.slice(Math.max(0, leading - contextLines), leading);
|
||||
const leadHidden = leading - leadShown.length;
|
||||
const trailShown = search.slice(
|
||||
search.length - trailing,
|
||||
search.length - trailing + contextLines,
|
||||
);
|
||||
const trailHidden = trailing - trailShown.length;
|
||||
|
||||
const out: string[] = [];
|
||||
if (leadHidden > 0) {
|
||||
out.push(`${indent} … ${leadHidden} unchanged line${leadHidden === 1 ? "" : "s"} above`);
|
||||
}
|
||||
for (const l of leadShown) out.push(`${indent} ${l}`);
|
||||
for (const l of searchMiddle) out.push(`${indent}- ${l}`);
|
||||
for (const l of replaceMiddle) out.push(`${indent}+ ${l}`);
|
||||
for (const l of trailShown) out.push(`${indent} ${l}`);
|
||||
if (trailHidden > 0) {
|
||||
out.push(`${indent} … ${trailHidden} unchanged line${trailHidden === 1 ? "" : "s"} below`);
|
||||
}
|
||||
|
||||
return capLines(out, maxLines, indent);
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the full set of blocks back-to-back, each preceded by a
|
||||
* path-and-size header so the user can tell which file owns each
|
||||
* diff chunk. Blocks are separated by a blank line for breathing room.
|
||||
*/
|
||||
export function formatAllBlockDiffs(
|
||||
blocks: readonly EditBlock[],
|
||||
opts: DiffPreviewOptions = {},
|
||||
): string[] {
|
||||
const out: string[] = [];
|
||||
for (let i = 0; i < blocks.length; i++) {
|
||||
const b = blocks[i]!;
|
||||
const removed = b.search === "" ? 0 : countLines(b.search);
|
||||
const added = countLines(b.replace);
|
||||
const tag = b.search === "" ? "NEW " : " ";
|
||||
if (i > 0) out.push("");
|
||||
out.push(` ${tag}${b.path} (-${removed} +${added} lines)`);
|
||||
out.push(...formatEditBlockDiff(b, opts));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function countLines(s: string): number {
|
||||
if (s.length === 0) return 0;
|
||||
return (s.match(/\n/g)?.length ?? 0) + 1;
|
||||
}
|
||||
|
||||
function renderAllPlus(lines: string[], indent: string, maxLines: number): string[] {
|
||||
const out = lines.map((l) => `${indent}+ ${l}`);
|
||||
return capLines(out, maxLines, indent);
|
||||
}
|
||||
|
||||
function capLines(lines: string[], maxLines: number, indent: string): string[] {
|
||||
if (lines.length <= maxLines) return lines;
|
||||
const head = lines.slice(0, maxLines - 1);
|
||||
const hidden = lines.length - head.length;
|
||||
head.push(`${indent}… (${hidden} more diff lines — full content applies on /apply)`);
|
||||
return head;
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
/**
|
||||
* Aider-style SEARCH/REPLACE edit blocks.
|
||||
*
|
||||
* The model emits blocks in this exact shape, one or more per response:
|
||||
*
|
||||
* path/to/file.ts
|
||||
* <<<<<<< SEARCH
|
||||
* exact existing lines (whitespace-sensitive)
|
||||
* =======
|
||||
* replacement lines
|
||||
* >>>>>>> REPLACE
|
||||
*
|
||||
* We chose this over unified diffs because:
|
||||
* - Models produce it reliably — no line-number drift.
|
||||
* - It tolerates multi-edit responses without ambiguity over which
|
||||
* hunk belongs to which file.
|
||||
* - Aider has years of evidence that this format works even against
|
||||
* weaker models than DeepSeek R1, so it's a conservative pick.
|
||||
*
|
||||
* The SEARCH text must match the file byte-for-byte. Empty SEARCH is a
|
||||
* sentinel for "create new file" — the REPLACE becomes the whole file.
|
||||
* If SEARCH doesn't match we refuse the edit and surface the failure;
|
||||
* we do NOT guess or fuzzy-match. A wrong silent edit is worse than a
|
||||
* missing one — the user can re-ask with the exact current content.
|
||||
*/
|
||||
|
||||
import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
|
||||
import { dirname, resolve } from "node:path";
|
||||
|
||||
export interface EditBlock {
|
||||
/** Path as written by the model — relative to rootDir, or absolute. */
|
||||
path: string;
|
||||
/** Literal text to match in the target file. Empty → create new file. */
|
||||
search: string;
|
||||
/** Replacement text to write in place of `search`. */
|
||||
replace: string;
|
||||
/** Char offset in the source message where this block started. */
|
||||
offset: number;
|
||||
}
|
||||
|
||||
export type ApplyStatus =
|
||||
/** Edit landed on disk. */
|
||||
| "applied"
|
||||
/** New file created (SEARCH was empty and file didn't exist). */
|
||||
| "created"
|
||||
/** File exists but SEARCH block wasn't found in its content. */
|
||||
| "not-found"
|
||||
/** File doesn't exist and SEARCH was non-empty (can't create without content). */
|
||||
| "file-missing"
|
||||
/** Path escapes rootDir — refused on safety grounds. */
|
||||
| "path-escape"
|
||||
/** fs write / read threw. */
|
||||
| "error";
|
||||
|
||||
export interface ApplyResult {
|
||||
path: string;
|
||||
status: ApplyStatus;
|
||||
/** Extra detail (e.g. error message) for logs. */
|
||||
message?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* One edit block per match. The regex is anchored to the 7-char marker
|
||||
* lines because those are visually distinct and unlikely to appear in
|
||||
* normal code.
|
||||
*
|
||||
* Anchored with `^` + `m` flag so the filename has to live on its own
|
||||
* line. Keeps us from matching e.g. a JS-import string that happens to
|
||||
* contain `<<<<<<< SEARCH` in inner text.
|
||||
*/
|
||||
// `\n?` before the =======/REPLACE separators makes the body optional:
|
||||
// empty SEARCH (new-file sentinel) works without requiring a gratuitous
|
||||
// empty line, and the same holds for empty REPLACE (file-deletion
|
||||
// semantics, not yet supported but cheaply representable).
|
||||
const BLOCK_RE = /^(\S[^\n]*)\n<{7} SEARCH\n([\s\S]*?)\n?={7}\n([\s\S]*?)\n?>{7} REPLACE/gm;
|
||||
|
||||
export function parseEditBlocks(text: string): EditBlock[] {
|
||||
const out: EditBlock[] = [];
|
||||
BLOCK_RE.lastIndex = 0;
|
||||
let m: RegExpExecArray | null = BLOCK_RE.exec(text);
|
||||
while (m !== null) {
|
||||
out.push({
|
||||
path: m[1]!.trim(),
|
||||
search: m[2]!,
|
||||
replace: m[3]!,
|
||||
offset: m.index,
|
||||
});
|
||||
m = BLOCK_RE.exec(text);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function applyEditBlock(block: EditBlock, rootDir: string): ApplyResult {
|
||||
const absRoot = resolve(rootDir);
|
||||
const absTarget = resolve(absRoot, block.path);
|
||||
// Refuse paths that escape rootDir. `resolve` normalizes `..`, so
|
||||
// startsWith on the normalized pair is enough.
|
||||
if (absTarget !== absRoot && !absTarget.startsWith(`${absRoot}${sep()}`)) {
|
||||
return {
|
||||
path: block.path,
|
||||
status: "path-escape",
|
||||
message: `resolved path ${absTarget} is outside rootDir ${absRoot}`,
|
||||
};
|
||||
}
|
||||
|
||||
const searchEmpty = block.search.length === 0;
|
||||
const exists = existsSync(absTarget);
|
||||
|
||||
try {
|
||||
if (!exists) {
|
||||
if (!searchEmpty) {
|
||||
return {
|
||||
path: block.path,
|
||||
status: "file-missing",
|
||||
message: "file does not exist; to create it, use an empty SEARCH block",
|
||||
};
|
||||
}
|
||||
mkdirSync(dirname(absTarget), { recursive: true });
|
||||
writeFileSync(absTarget, block.replace, "utf8");
|
||||
return { path: block.path, status: "created" };
|
||||
}
|
||||
|
||||
const content = readFileSync(absTarget, "utf8");
|
||||
if (searchEmpty) {
|
||||
return {
|
||||
path: block.path,
|
||||
status: "not-found",
|
||||
message: "empty SEARCH only creates new files — this file already exists",
|
||||
};
|
||||
}
|
||||
const idx = content.indexOf(block.search);
|
||||
if (idx === -1) {
|
||||
return {
|
||||
path: block.path,
|
||||
status: "not-found",
|
||||
message: "SEARCH text does not match the current file content exactly",
|
||||
};
|
||||
}
|
||||
// Replace only the first occurrence — if the model needs multiple
|
||||
// identical edits it should emit multiple blocks (each anchored by
|
||||
// more surrounding context). Auto-expanding to replace-all is a
|
||||
// footgun when the same string legitimately appears in several
|
||||
// unrelated places.
|
||||
const replaced = `${content.slice(0, idx)}${block.replace}${content.slice(idx + block.search.length)}`;
|
||||
writeFileSync(absTarget, replaced, "utf8");
|
||||
return { path: block.path, status: "applied" };
|
||||
} catch (err) {
|
||||
return { path: block.path, status: "error", message: (err as Error).message };
|
||||
}
|
||||
}
|
||||
|
||||
export function applyEditBlocks(blocks: EditBlock[], rootDir: string): ApplyResult[] {
|
||||
return blocks.map((b) => applyEditBlock(b, rootDir));
|
||||
}
|
||||
|
||||
/**
|
||||
* Build an EditBlock that represents a whole-file overwrite. If the
|
||||
* target exists, SEARCH = current content so applyEditBlock replaces
|
||||
* the whole thing when committed; if it doesn't, SEARCH is empty (the
|
||||
* create-new sentinel). Used by the edit-mode gate when routing a
|
||||
* `write_file` tool call through the review queue without executing
|
||||
* the write inline.
|
||||
*/
|
||||
export function toWholeFileEditBlock(path: string, content: string, rootDir: string): EditBlock {
|
||||
const abs = resolve(rootDir, path);
|
||||
let search = "";
|
||||
if (existsSync(abs)) {
|
||||
try {
|
||||
search = readFileSync(abs, "utf8");
|
||||
} catch {
|
||||
search = "";
|
||||
}
|
||||
}
|
||||
return { path, search, replace: content, offset: 0 };
|
||||
}
|
||||
|
||||
// ---------- snapshot / restore (for /undo) ----------
|
||||
|
||||
export interface EditSnapshot {
|
||||
/** Path relative to rootDir, as the block named it. */
|
||||
path: string;
|
||||
/**
|
||||
* File content before the edit batch was applied. `null` means the
|
||||
* file didn't exist yet — restoring that means deleting whatever the
|
||||
* edit created.
|
||||
*/
|
||||
prevContent: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Capture the current state of every file an edit batch is about to
|
||||
* touch, so `/undo` can roll back if the user doesn't like the result.
|
||||
* De-duplicates by path because one batch can contain multiple blocks
|
||||
* for the same file, and we only want one "before" snapshot per file.
|
||||
*/
|
||||
export function snapshotBeforeEdits(blocks: EditBlock[], rootDir: string): EditSnapshot[] {
|
||||
const absRoot = resolve(rootDir);
|
||||
const seen = new Set<string>();
|
||||
const snapshots: EditSnapshot[] = [];
|
||||
for (const b of blocks) {
|
||||
if (seen.has(b.path)) continue;
|
||||
seen.add(b.path);
|
||||
const abs = resolve(absRoot, b.path);
|
||||
if (!existsSync(abs)) {
|
||||
snapshots.push({ path: b.path, prevContent: null });
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
snapshots.push({ path: b.path, prevContent: readFileSync(abs, "utf8") });
|
||||
} catch {
|
||||
// Unreadable (permission / binary) — record null so we at least
|
||||
// don't pretend the snapshot is authoritative. The restore path
|
||||
// will treat null as "delete on undo", which is wrong in that
|
||||
// case but the file wasn't ours to begin with.
|
||||
snapshots.push({ path: b.path, prevContent: null });
|
||||
}
|
||||
}
|
||||
return snapshots;
|
||||
}
|
||||
|
||||
/**
|
||||
* Restore files to their snapshotted state. Snapshots with
|
||||
* `prevContent === null` were created by the edit, so undo = delete.
|
||||
* Otherwise the prior content is written back, replacing whatever the
|
||||
* edit left behind.
|
||||
*/
|
||||
export function restoreSnapshots(snapshots: EditSnapshot[], rootDir: string): ApplyResult[] {
|
||||
const absRoot = resolve(rootDir);
|
||||
return snapshots.map((snap) => {
|
||||
const abs = resolve(absRoot, snap.path);
|
||||
if (abs !== absRoot && !abs.startsWith(`${absRoot}${sep()}`)) {
|
||||
return {
|
||||
path: snap.path,
|
||||
status: "path-escape",
|
||||
message: "snapshot path escapes rootDir — refusing to restore",
|
||||
};
|
||||
}
|
||||
try {
|
||||
if (snap.prevContent === null) {
|
||||
if (existsSync(abs)) unlinkSync(abs);
|
||||
return {
|
||||
path: snap.path,
|
||||
status: "applied",
|
||||
message: "removed (the edit had created it)",
|
||||
};
|
||||
}
|
||||
writeFileSync(abs, snap.prevContent, "utf8");
|
||||
return {
|
||||
path: snap.path,
|
||||
status: "applied",
|
||||
message: "restored to pre-edit content",
|
||||
};
|
||||
} catch (err) {
|
||||
return { path: snap.path, status: "error", message: (err as Error).message };
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** Platform separator — `\` on Windows, `/` elsewhere. */
|
||||
function sep(): string {
|
||||
return process.platform === "win32" ? "\\" : "/";
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
/**
|
||||
* Durable checkpoint for the pending-edits queue.
|
||||
*
|
||||
* Code mode holds parsed SEARCH/REPLACE blocks in an in-memory
|
||||
* `useRef<EditBlock[]>` until the user runs `/apply` or `/discard`.
|
||||
* Pre-0.5.14 that was ephemeral: a crash or accidental Ctrl+C after
|
||||
* the model proposed seven edits discarded all seven — the session
|
||||
* log had the assistant text, but the "please review this batch"
|
||||
* state was gone.
|
||||
*
|
||||
* This module checkpoints the queue to
|
||||
* `~/.reasonix/sessions/<name>.pending.json`
|
||||
* after every mutation (parse → set / apply → clear / discard →
|
||||
* clear). On session resume the App reads the file and re-populates
|
||||
* the queue. If the file doesn't exist the session resumes as before.
|
||||
*
|
||||
* Format choices:
|
||||
* - JSON (not JSONL) — the queue is a single array written at once,
|
||||
* not a stream of records.
|
||||
* - Overwrite-on-write — the queue is small (kilobytes) and atomicity
|
||||
* is "last write wins"; partial-write on crash is fine since we'd
|
||||
* rather lose the checkpoint than have a torn file block resume.
|
||||
* - Best-effort I/O — disk full or permission denied must not break
|
||||
* the session. Silent skip matches the rest of the durable logs
|
||||
* (session.ts, usage.ts).
|
||||
*
|
||||
* Ephemeral sessions (sessionName === null) skip persistence entirely:
|
||||
* there's no stable name to key the checkpoint to.
|
||||
*/
|
||||
|
||||
import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
import { sanitizeName, sessionsDir } from "../session.js";
|
||||
import type { EditBlock } from "./edit-blocks.js";
|
||||
|
||||
/** Absolute path for the checkpoint file that belongs to this session. */
|
||||
export function pendingEditsPath(sessionName: string): string {
|
||||
return join(sessionsDir(), `${sanitizeName(sessionName)}.pending.json`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Write the queue to disk, or delete the checkpoint file when `blocks`
|
||||
* is empty. Callers pass the full current queue every time; we don't
|
||||
* attempt append-style deltas because the queue is tiny.
|
||||
*
|
||||
* No-op when `sessionName` is null (ephemeral session has nowhere to
|
||||
* write), so call sites can pass the session name directly without a
|
||||
* null guard.
|
||||
*/
|
||||
export function savePendingEdits(sessionName: string | null, blocks: EditBlock[]): void {
|
||||
if (!sessionName) return;
|
||||
const path = pendingEditsPath(sessionName);
|
||||
try {
|
||||
if (blocks.length === 0) {
|
||||
if (existsSync(path)) unlinkSync(path);
|
||||
return;
|
||||
}
|
||||
mkdirSync(dirname(path), { recursive: true });
|
||||
writeFileSync(path, JSON.stringify(blocks, null, 2), "utf8");
|
||||
} catch {
|
||||
/* best-effort — disk full / perms should not break the session */
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Load the queue from disk, returns `null` when there's no checkpoint.
|
||||
* A malformed file (power-loss torn write, user hand-edit) also returns
|
||||
* null — silent recovery beats failing to open the session.
|
||||
*/
|
||||
export function loadPendingEdits(sessionName: string | null): EditBlock[] | null {
|
||||
if (!sessionName) return null;
|
||||
const path = pendingEditsPath(sessionName);
|
||||
if (!existsSync(path)) return null;
|
||||
let raw: string;
|
||||
try {
|
||||
raw = readFileSync(path, "utf8");
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
const parsed = JSON.parse(raw);
|
||||
if (!Array.isArray(parsed)) return null;
|
||||
const out: EditBlock[] = [];
|
||||
for (const item of parsed) {
|
||||
if (
|
||||
item &&
|
||||
typeof item === "object" &&
|
||||
typeof item.path === "string" &&
|
||||
typeof item.search === "string" &&
|
||||
typeof item.replace === "string" &&
|
||||
typeof item.offset === "number"
|
||||
) {
|
||||
out.push(item as EditBlock);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Delete the checkpoint file unconditionally — called by /apply and /discard. */
|
||||
export function clearPendingEdits(sessionName: string | null): void {
|
||||
if (!sessionName) return;
|
||||
const path = pendingEditsPath(sessionName);
|
||||
try {
|
||||
if (existsSync(path)) unlinkSync(path);
|
||||
} catch {
|
||||
/* best-effort */
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,292 @@
|
||||
/**
|
||||
* Per-session plan persistence.
|
||||
*
|
||||
* The structured plan that the model submits via `submit_plan` (and
|
||||
* subsequently mutates via `mark_step_complete` / `revise_plan`) is a
|
||||
* meaningful artifact of the user's work. Without persistence it
|
||||
* evaporates the moment the terminal closes — which means the user
|
||||
* loses context every time they take a coffee break, and the rich
|
||||
* checkpoint / revise / progress UX has nothing to attach to in
|
||||
* resumed sessions.
|
||||
*
|
||||
* This module ships the smallest useful piece: read/write a plan
|
||||
* state JSON next to the session's JSONL log. App.tsx loads on
|
||||
* mount and saves after every state change. Storage path mirrors
|
||||
* the JSONL convention: `~/.reasonix/sessions/<sanitized>.plan.json`.
|
||||
*
|
||||
* What's persisted: the structured `steps[]` (with risk levels), the
|
||||
* set of completedStepIds, and an updatedAt timestamp. The plan's
|
||||
* markdown body is NOT persisted here — it lives in the JSONL log
|
||||
* (it was a tool result), so resuming the session replays it
|
||||
* naturally if the user wants to re-read it. We only carry forward
|
||||
* the live state needed to keep mark_step_complete and revise_plan
|
||||
* meaningful.
|
||||
*/
|
||||
|
||||
import {
|
||||
existsSync,
|
||||
mkdirSync,
|
||||
readFileSync,
|
||||
readdirSync,
|
||||
renameSync,
|
||||
statSync,
|
||||
unlinkSync,
|
||||
writeFileSync,
|
||||
} from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
import { sanitizeName, sessionsDir } from "../session.js";
|
||||
import type { PlanStep } from "../tools/plan.js";
|
||||
|
||||
export interface PlanStateOnDisk {
|
||||
/** File format version — bump when shape changes. */
|
||||
version: 1;
|
||||
steps: PlanStep[];
|
||||
completedStepIds: string[];
|
||||
/** ISO8601 timestamp of the last write. */
|
||||
updatedAt: string;
|
||||
/**
|
||||
* Markdown body the model submitted via submit_plan. Persisted so
|
||||
* Time Travel replay can show the full proposal without going back
|
||||
* to the JSONL log. Optional — older / minimal plans may lack it.
|
||||
*/
|
||||
body?: string;
|
||||
/**
|
||||
* Optional one-sentence human-friendly title. Surfaces in the
|
||||
* PlanConfirm header, the resume banner, and /plans listings so
|
||||
* the user identifies plans by intent rather than file path.
|
||||
*/
|
||||
summary?: string;
|
||||
}
|
||||
|
||||
export function planStatePath(sessionName: string): string {
|
||||
return join(sessionsDir(), `${sanitizeName(sessionName)}.plan.json`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the persisted plan for this session, if any. Returns `null`
|
||||
* for missing / unreadable / malformed files — callers should treat
|
||||
* the absence of a stored plan as "no plan yet", not a hard error.
|
||||
*/
|
||||
export function loadPlanState(sessionName: string): PlanStateOnDisk | null {
|
||||
const path = planStatePath(sessionName);
|
||||
if (!existsSync(path)) return null;
|
||||
try {
|
||||
const raw = readFileSync(path, "utf8");
|
||||
const parsed = JSON.parse(raw) as Partial<PlanStateOnDisk>;
|
||||
if (!parsed || typeof parsed !== "object") return null;
|
||||
if (parsed.version !== 1) return null;
|
||||
if (!Array.isArray(parsed.steps)) return null;
|
||||
if (!Array.isArray(parsed.completedStepIds)) return null;
|
||||
if (typeof parsed.updatedAt !== "string") return null;
|
||||
// Defensive: filter out any malformed step entries so a partially
|
||||
// corrupted file still yields a usable subset.
|
||||
const steps: PlanStep[] = [];
|
||||
for (const s of parsed.steps) {
|
||||
if (!s || typeof s !== "object") continue;
|
||||
const e = s as unknown as Record<string, unknown>;
|
||||
if (typeof e.id !== "string" || !e.id) continue;
|
||||
if (typeof e.title !== "string" || !e.title) continue;
|
||||
if (typeof e.action !== "string" || !e.action) continue;
|
||||
const step: PlanStep = { id: e.id, title: e.title, action: e.action };
|
||||
if (e.risk === "low" || e.risk === "med" || e.risk === "high") step.risk = e.risk;
|
||||
steps.push(step);
|
||||
}
|
||||
if (steps.length === 0) return null;
|
||||
const completedStepIds = parsed.completedStepIds.filter(
|
||||
(id): id is string => typeof id === "string" && id.length > 0,
|
||||
);
|
||||
const out: PlanStateOnDisk = {
|
||||
version: 1,
|
||||
steps,
|
||||
completedStepIds,
|
||||
updatedAt: parsed.updatedAt,
|
||||
};
|
||||
if (typeof parsed.body === "string" && parsed.body) out.body = parsed.body;
|
||||
if (typeof parsed.summary === "string" && parsed.summary) out.summary = parsed.summary;
|
||||
return out;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Persist the current plan state. Called whenever the in-memory plan
|
||||
* meaningfully changes (submit, complete, revise). Best-effort: a
|
||||
* write failure logs to stderr but doesn't propagate — losing the
|
||||
* persisted copy is annoying but shouldn't crash the TUI.
|
||||
*/
|
||||
export function savePlanState(
|
||||
sessionName: string,
|
||||
steps: PlanStep[],
|
||||
completedStepIds: Iterable<string>,
|
||||
extras?: { body?: string; summary?: string },
|
||||
): void {
|
||||
const path = planStatePath(sessionName);
|
||||
try {
|
||||
mkdirSync(dirname(path), { recursive: true });
|
||||
const state: PlanStateOnDisk = {
|
||||
version: 1,
|
||||
steps,
|
||||
completedStepIds: [...completedStepIds],
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
if (extras?.body) state.body = extras.body;
|
||||
if (extras?.summary) state.summary = extras.summary;
|
||||
writeFileSync(path, `${JSON.stringify(state, null, 2)}\n`, "utf8");
|
||||
} catch (err) {
|
||||
process.stderr.write(
|
||||
`▸ plan-store: failed to save plan for "${sessionName}": ${(err as Error).message}\n`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** Remove the persisted plan, if any. Used on cancel / clean reset. */
|
||||
export function clearPlanState(sessionName: string): void {
|
||||
const path = planStatePath(sessionName);
|
||||
try {
|
||||
if (existsSync(path)) unlinkSync(path);
|
||||
} catch {
|
||||
/* nothing to do — leftover file is harmless, will be overwritten next save */
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Move the active plan to a timestamped .done.json archive when the
|
||||
* model has marked every step complete. Future Time-Travel replay
|
||||
* will load these archives; for now the archive just exists as a
|
||||
* historical artifact and frees the active plan.json so the next
|
||||
* session starts fresh.
|
||||
*
|
||||
* Returns the archive path on success, or null if there was nothing
|
||||
* to archive (no active plan) / the rename failed (logged to stderr,
|
||||
* not propagated — losing the archive is annoying but shouldn't
|
||||
* crash the TUI).
|
||||
*
|
||||
* The timestamp uses ISO 8601 with a millisecond suffix and `:` and
|
||||
* `.` swapped for `-` so the filename is filesystem-safe on Windows.
|
||||
* Two archives created within the same millisecond would collide;
|
||||
* we append a short random suffix to dodge that.
|
||||
*/
|
||||
export function archivePlanState(sessionName: string): string | null {
|
||||
const active = planStatePath(sessionName);
|
||||
if (!existsSync(active)) return null;
|
||||
const stamp = new Date().toISOString().replace(/[:.]/g, "-");
|
||||
const suffix = Math.random().toString(36).slice(2, 6);
|
||||
const archive = join(
|
||||
sessionsDir(),
|
||||
`${sanitizeName(sessionName)}.plan.${stamp}-${suffix}.done.json`,
|
||||
);
|
||||
try {
|
||||
renameSync(active, archive);
|
||||
return archive;
|
||||
} catch (err) {
|
||||
process.stderr.write(
|
||||
`▸ plan-store: failed to archive plan for "${sessionName}": ${(err as Error).message}\n`,
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Summary of one archived (completed) plan, as returned by
|
||||
* `listPlanArchives`. The `completedAt` ISO string comes from the
|
||||
* archive file's stored `updatedAt` (or its mtime as fallback) so it
|
||||
* survives across machines / clock skew. `path` is absolute and ready
|
||||
* for a future `/replay` to read directly.
|
||||
*/
|
||||
export interface PlanArchiveSummary {
|
||||
path: string;
|
||||
completedAt: string;
|
||||
steps: PlanStep[];
|
||||
completedStepIds: string[];
|
||||
/** Markdown body, when the archive carried it. */
|
||||
body?: string;
|
||||
/** One-line human-friendly title, when supplied. */
|
||||
summary?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* List all archived `.done.json` files for this session, newest
|
||||
* first. Used by `/plans` to give the user a project-local history.
|
||||
* Cross-project listing is intentionally NOT supported here — a plan
|
||||
* lives next to its session, and resuming it just means switching
|
||||
* back to that project's directory.
|
||||
*
|
||||
* Robust to missing dir / unreadable entries: a corrupt archive is
|
||||
* skipped, not propagated. Worst case the user sees a shorter list
|
||||
* than reality.
|
||||
*/
|
||||
export function listPlanArchives(sessionName: string): PlanArchiveSummary[] {
|
||||
const dir = sessionsDir();
|
||||
if (!existsSync(dir)) return [];
|
||||
const prefix = `${sanitizeName(sessionName)}.plan.`;
|
||||
const suffix = ".done.json";
|
||||
let entries: string[];
|
||||
try {
|
||||
entries = readdirSync(dir);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
const summaries: PlanArchiveSummary[] = [];
|
||||
for (const name of entries) {
|
||||
if (!name.startsWith(prefix) || !name.endsWith(suffix)) continue;
|
||||
const full = join(dir, name);
|
||||
try {
|
||||
const raw = readFileSync(full, "utf8");
|
||||
const parsed = JSON.parse(raw) as Partial<PlanStateOnDisk>;
|
||||
if (parsed.version !== 1) continue;
|
||||
if (!Array.isArray(parsed.steps) || parsed.steps.length === 0) continue;
|
||||
const steps = parsed.steps.filter(
|
||||
(s): s is PlanStep =>
|
||||
!!s &&
|
||||
typeof s === "object" &&
|
||||
typeof (s as PlanStep).id === "string" &&
|
||||
typeof (s as PlanStep).title === "string" &&
|
||||
typeof (s as PlanStep).action === "string",
|
||||
);
|
||||
if (steps.length === 0) continue;
|
||||
const completedStepIds = Array.isArray(parsed.completedStepIds)
|
||||
? parsed.completedStepIds.filter((id): id is string => typeof id === "string" && !!id)
|
||||
: [];
|
||||
// Prefer the file's own updatedAt; fall back to mtime if missing
|
||||
// or unparseable so a hand-edited archive still sorts sensibly.
|
||||
let completedAt = typeof parsed.updatedAt === "string" ? parsed.updatedAt : "";
|
||||
if (!completedAt || Number.isNaN(Date.parse(completedAt))) {
|
||||
try {
|
||||
completedAt = statSync(full).mtime.toISOString();
|
||||
} catch {
|
||||
completedAt = new Date(0).toISOString();
|
||||
}
|
||||
}
|
||||
const entry: PlanArchiveSummary = { path: full, completedAt, steps, completedStepIds };
|
||||
if (typeof parsed.body === "string" && parsed.body) entry.body = parsed.body;
|
||||
if (typeof parsed.summary === "string" && parsed.summary) entry.summary = parsed.summary;
|
||||
summaries.push(entry);
|
||||
} catch {
|
||||
// Skip the corrupt archive entirely.
|
||||
}
|
||||
}
|
||||
summaries.sort((a, b) => b.completedAt.localeCompare(a.completedAt));
|
||||
return summaries;
|
||||
}
|
||||
|
||||
/**
|
||||
* Render `updatedAt` as a short relative-time string for the resume
|
||||
* notice ("2h ago", "3 days ago"). Falls back to the raw ISO string
|
||||
* for anything beyond a week so users don't see misleading
|
||||
* "47 days ago" approximations.
|
||||
*/
|
||||
export function relativeTime(updatedAt: string, now: number = Date.now()): string {
|
||||
const t = Date.parse(updatedAt);
|
||||
if (Number.isNaN(t)) return updatedAt;
|
||||
const diffMs = Math.max(0, now - t);
|
||||
const sec = Math.floor(diffMs / 1000);
|
||||
if (sec < 60) return `${sec}s ago`;
|
||||
const min = Math.floor(sec / 60);
|
||||
if (min < 60) return `${min}m ago`;
|
||||
const hr = Math.floor(min / 60);
|
||||
if (hr < 24) return `${hr}h ago`;
|
||||
const day = Math.floor(hr / 24);
|
||||
if (day < 7) return `${day}d ago`;
|
||||
return updatedAt.slice(0, 10);
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
/**
|
||||
* System prompt used by `reasonix code`. Teaches the model:
|
||||
*
|
||||
* 1. It has a filesystem MCP bridge rooted at the user's CWD.
|
||||
* 2. To modify files it emits SEARCH/REPLACE blocks (not
|
||||
* `write_file` — that would whole-file rewrite and kill diff
|
||||
* reviewability).
|
||||
* 3. Read first, edit second — SEARCH must match byte-for-byte.
|
||||
* 4. Be concise. The user can read a diff faster than prose.
|
||||
*
|
||||
* Kept short on purpose. Long system prompts eat context budget that
|
||||
* the Cache-First Loop is trying to conserve. The SEARCH/REPLACE spec
|
||||
* is the one unavoidable bloat; we trim everything else.
|
||||
*/
|
||||
|
||||
import { existsSync, readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { ESCALATION_CONTRACT, TUI_FORMATTING_RULES } from "../prompt-fragments.js";
|
||||
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, edit_file, list_directory, directory_tree, search_files, search_content, get_file_info) rooted at the user's working directory, plus run_command / run_background for shell.
|
||||
|
||||
# Cite or shut up — non-negotiable
|
||||
|
||||
Every factual claim you make about THIS codebase must be backed by evidence. Reasonix VALIDATES the citations you write — broken paths or out-of-range lines render in **red strikethrough with ❌** in front of the user.
|
||||
|
||||
**Positive claims** (a file exists, a function does X, a feature IS implemented) — append a markdown link to the source:
|
||||
|
||||
- ✅ Correct: \`The MCP client supports listResources [listResources](src/mcp/client.ts:142).\`
|
||||
- ❌ Wrong: \`The MCP client supports listResources.\` ← no citation, looks authoritative but unverifiable.
|
||||
|
||||
**Negative claims** (X is missing, Y is not implemented, lacks Z, doesn't have W) are the **most common hallucination shape**. They feel safe to write because no citation seems possible — but that's exactly why you must NOT write them on instinct.
|
||||
|
||||
If you are about to write "X is missing" or "Y is not implemented" — **STOP**. Call \`search_content\` for the relevant symbol or term FIRST. Only then:
|
||||
|
||||
- If the search returns matches → you were wrong; correct yourself and cite the matches.
|
||||
- If the search returns nothing → state the absence with the search query as your evidence: \`No callers of \\\`foo()\\\` found (search_content "foo").\`
|
||||
|
||||
Asserting absence without a search is the #1 way evaluative answers go wrong. Treat the urge to write "missing" as a red flag in your own reasoning.
|
||||
|
||||
# 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.
|
||||
|
||||
**Do NOT use submit_plan to present A/B/C route menus.** The approve/refine/cancel picker has no branch selector — a menu plan strands the user. For branching decisions, use \`ask_choice\` (see below); only call submit_plan once the user has picked a direction and you have ONE actionable plan.
|
||||
|
||||
# When to ask the user to pick (ask_choice)
|
||||
|
||||
You have an \`ask_choice\` tool. **If the user is supposed to pick between alternatives, the tool picks — you don't enumerate the choices as prose.** Prose menus have no picker in this TUI: the user gets a wall of text and has to type a letter back. The tool fires an arrow-key picker that's strictly better.
|
||||
|
||||
Call it when:
|
||||
- The user has asked for options / doesn't want a recommendation / wants to decide.
|
||||
- You've analyzed multiple approaches and the final call is theirs.
|
||||
- It's a preference fork you can't resolve without them (deployment target, team convention, taste).
|
||||
|
||||
Skip it when one option is clearly correct (just do it, or submit_plan) or a free-form text answer fits (ask in prose).
|
||||
|
||||
Each option: short stable id (A/B/C), one-line title, optional summary. \`allowCustom: true\` when their real answer might not fit. Max 6. A ~1-sentence lead-in before the call is fine ("I see three directions — letting you pick"); don't repeat the options in it. After the call, STOP.
|
||||
|
||||
# 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.
|
||||
|
||||
|
||||
# Delegating to subagents via Skills
|
||||
|
||||
The pinned Skills index below lists playbooks you can invoke with \`run_skill\`. Entries tagged \`[🧬 subagent]\` spawn an **isolated subagent** — a fresh child loop that runs the playbook in its own context and returns only the final answer. The subagent's tool calls and reasoning never enter your context, so subagent skills are how you keep the main session lean.
|
||||
|
||||
**When you call \`run_skill\`, the \`name\` is ONLY the identifier before the tag** — e.g. \`run_skill({ name: "explore", arguments: "..." })\`, NOT \`"[🧬 subagent] explore"\` and NOT \`"explore [🧬 subagent]"\`. The tag is display sugar; the name argument is just the bare identifier.
|
||||
|
||||
Two built-ins ship by default:
|
||||
- **explore** \`[🧬 subagent]\` — read-only investigation across the codebase. Use when the user says things like "find all places that...", "how does X work across the project", "survey the code for Y". Pass \`arguments\` describing the concrete question.
|
||||
- **research** \`[🧬 subagent]\` — combines web search + code reading. Use for "is X supported by lib Y", "what's the canonical way to Z", "compare our impl to the spec".
|
||||
|
||||
When to delegate (call \`run_skill\` with a subagent skill):
|
||||
- The task would otherwise need >5 file reads or searches.
|
||||
- You only need the conclusion, not the exploration trail.
|
||||
- The work is self-contained (you can describe it in one paragraph).
|
||||
|
||||
When NOT to delegate:
|
||||
- Direct, narrow questions answerable in 1-2 tool calls — just do them.
|
||||
- Anything where you need to track intermediate results yourself (planning, multi-step edits).
|
||||
- Anything that requires user interaction (subagents can't submit plans or ask you for clarification).
|
||||
|
||||
Always pass a clear, self-contained \`arguments\` — that text is the **only** context the subagent gets.
|
||||
|
||||
# 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:
|
||||
- analyze, read, explore, describe, or summarize a project
|
||||
- explain how something works
|
||||
- answer a question about the code
|
||||
|
||||
In those cases, use tools to gather what you need, then reply in prose. No SEARCH/REPLACE blocks, no file changes. If you're unsure what the user wants, ask.
|
||||
|
||||
When you do propose edits, the user will review them and decide whether to \`/apply\` or \`/discard\`. Don't assume they'll accept — write as if each edit will be audited, because it will.
|
||||
|
||||
Reasonix runs an **edit gate**. The user's current mode (\`review\` or \`auto\`) decides what happens to your writes; you DO NOT see which mode is active, and you SHOULD NOT ask. Write the same way in both cases.
|
||||
|
||||
- In \`auto\` mode \`edit_file\` / \`write_file\` calls land on disk immediately with an undo window — you'll get the normal "edit blocks: 1/1 applied" style response.
|
||||
- In \`review\` mode EACH \`edit_file\` / \`write_file\` call pauses tool dispatch while the user decides. You'll get one of these responses:
|
||||
- \`"edit blocks: 1/1 applied"\` — user approved it. Continue as normal.
|
||||
- \`"User rejected this edit to <path>. Don't retry the same SEARCH/REPLACE…"\` — user said no to THIS specific edit. Do NOT re-emit the same block, do NOT switch tools to sneak it past the gate (write_file → edit_file, or text-form SEARCH/REPLACE). Either take a clearly different approach or stop and ask the user what they want instead.
|
||||
- Text-form SEARCH/REPLACE blocks in your assistant reply queue for end-of-turn /apply — same "don't retry on rejection" rule.
|
||||
- If the user presses Esc mid-prompt the whole turn is aborted; you won't get another tool response. Don't keep spamming tool calls after an abort.
|
||||
|
||||
# Editing files
|
||||
|
||||
When you've been asked to change a file, output one or more SEARCH/REPLACE blocks in this exact format:
|
||||
|
||||
path/to/file.ext
|
||||
<<<<<<< SEARCH
|
||||
exact existing lines from the file, including whitespace
|
||||
=======
|
||||
the new lines
|
||||
>>>>>>> REPLACE
|
||||
|
||||
Rules:
|
||||
- Always read_file first so your SEARCH matches byte-for-byte. If it doesn't match, the edit is rejected and you'll have to retry with the exact current content.
|
||||
- One edit per block. Multiple blocks in one response are fine.
|
||||
- To create a new file, leave SEARCH empty:
|
||||
path/to/new.ts
|
||||
<<<<<<< SEARCH
|
||||
=======
|
||||
(whole file content here)
|
||||
>>>>>>> REPLACE
|
||||
- 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
|
||||
|
||||
- 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\` over \`list_directory\` when you know roughly what you're looking for — it saves context and avoids enumerating huge trees. Note: \`search_files\` matches file NAMES; for searching file CONTENTS use \`search_content\`.
|
||||
- Available exploration tools: \`read_file\`, \`list_directory\`, \`directory_tree\`, \`search_files\` (filename match), \`search_content\` (content grep — use for "where is X called", "find all references to Y"), \`get_file_info\`. Don't call \`grep\` or other tools that aren't in this list — they don't exist as functions.
|
||||
|
||||
# Path conventions
|
||||
|
||||
Two different rules depending on which tool:
|
||||
|
||||
- **Filesystem tools** (\`read_file\`, \`list_directory\`, \`search_files\`, \`edit_file\`, etc.): paths are sandbox-relative. \`/\` means the project root, \`/src/foo.ts\` means \`<project>/src/foo.ts\`. Both relative (\`src/foo.ts\`) and POSIX-absolute (\`/src/foo.ts\`) forms work.
|
||||
- **\`run_command\`**: the command runs in a real OS shell with cwd pinned to the project root. Paths inside the shell command are interpreted by THAT shell, not by us. **Never use leading \`/\` in run_command arguments** — Windows treats \`/tests\` as drive-root \`F:\\tests\` (non-existent), POSIX shells treat it as filesystem root. Use plain relative paths (\`tests\`, \`./tests\`, \`src/loop.ts\`) instead.
|
||||
|
||||
# Foreground vs. background commands
|
||||
|
||||
You have TWO tools for running shell commands, and picking the right one is non-negotiable:
|
||||
|
||||
- \`run_command\` — blocks until the process exits. Use for: **tests, builds, lints, typechecks, git operations, one-shot scripts**. Anything that naturally returns in under a minute.
|
||||
- \`run_background\` — spawns and detaches after a brief startup window. Use for: **dev servers, watchers, any command with "dev" / "serve" / "watch" / "start" in the name**. Examples: \`npm run dev\`, \`pnpm dev\`, \`yarn start\`, \`vite\`, \`next dev\`, \`uvicorn app:app --reload\`, \`flask run\`, \`python -m http.server\`, \`cargo watch\`, \`tsc --watch\`, \`webpack serve\`.
|
||||
|
||||
**Never use run_command for a dev server.** It will block for 60s, time out, and the user will see a frozen tool call while the server was actually running fine. Always \`run_background\`, then \`job_output\` to peek at the logs when you need to verify something.
|
||||
|
||||
After \`run_background\`, tools available to you:
|
||||
- \`job_output(jobId, tailLines?)\` — read recent logs to verify startup / debug errors.
|
||||
- \`list_jobs\` — see every job this session (running + exited).
|
||||
- \`stop_job(jobId)\` — SIGTERM → SIGKILL after grace. Stop before switching port / config.
|
||||
|
||||
Don't re-start an already-running dev server — call \`list_jobs\` first when in doubt.
|
||||
|
||||
# Scope discipline on "run it" / "start it" requests
|
||||
|
||||
When the user's request is to **run / start / launch / serve / boot up** something, your job is ONLY:
|
||||
|
||||
1. Start it (\`run_background\` for dev servers, \`run_command\` for one-shots).
|
||||
2. Verify it came up (read a ready signal via \`job_output\`, or fetch the URL with \`web_fetch\` if they want you to confirm).
|
||||
3. Report what's running, where (URL / port / pid), and STOP.
|
||||
|
||||
Do NOT, in the same turn:
|
||||
- Run \`tsc\` / type-checkers / linters unless the user asked for it.
|
||||
- Scan for bugs to "proactively" fix. The page rendering is success.
|
||||
- Clean up unused imports, dead code, or refactor "while you're here."
|
||||
- Edit files to improve anything the user didn't mention.
|
||||
|
||||
If you notice an obvious issue, MENTION it in one sentence and wait for the user to say "fix it." The cost of over-eagerness is real: you burn tokens, make surprise edits the user didn't want, and chain into cascading "fix the new error I just introduced" loops. The storm-breaker will cut you off, but the user still sees the mess.
|
||||
|
||||
"It works" is the end state. Resist the urge to polish.
|
||||
|
||||
# Style
|
||||
|
||||
- Show edits; don't narrate them in prose. "Here's the fix:" is enough.
|
||||
- One short paragraph explaining *why*, then the blocks.
|
||||
- If you need to explore first (list / read / search), do it with tool calls before writing any prose — silence while exploring is fine.
|
||||
|
||||
${ESCALATION_CONTRACT}
|
||||
|
||||
${TUI_FORMATTING_RULES}
|
||||
`;
|
||||
|
||||
/**
|
||||
* Inject the project's `.gitignore` content into the system prompt as a
|
||||
* "respect this on top of the built-in denylist" hint. We don't parse
|
||||
* 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.
|
||||
*
|
||||
* 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 withMemory;
|
||||
let content: string;
|
||||
try {
|
||||
content = readFileSync(gitignorePath, "utf8");
|
||||
} catch {
|
||||
return withMemory;
|
||||
}
|
||||
const MAX = 2000;
|
||||
const truncated =
|
||||
content.length > MAX
|
||||
? `${content.slice(0, MAX)}\n… (truncated ${content.length - MAX} chars)`
|
||||
: content;
|
||||
return `${withMemory}
|
||||
|
||||
# Project .gitignore
|
||||
|
||||
The user's repo ships this .gitignore — treat every pattern as "don't traverse or edit inside these paths unless explicitly asked":
|
||||
|
||||
\`\`\`
|
||||
${truncated}
|
||||
\`\`\`
|
||||
`;
|
||||
}
|
||||
+173
@@ -8,15 +8,92 @@
|
||||
* The library itself never touches the config file — it only reads
|
||||
* `DEEPSEEK_API_KEY` from the environment. The CLI is responsible for
|
||||
* pulling from the config file and exposing it via env var to the loop.
|
||||
*
|
||||
* Beyond the API key, the config also remembers the user's *defaults*
|
||||
* from `reasonix setup`: preset, MCP servers, session. This is what
|
||||
* makes `reasonix chat` with no flags "just work" after first-run.
|
||||
*/
|
||||
|
||||
import { chmodSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
|
||||
/** One of the preset bundles (model + harvest + branch combo). */
|
||||
export type PresetName = "fast" | "smart" | "max";
|
||||
|
||||
/**
|
||||
* How `reasonix code` handles model-issued edits:
|
||||
* - "review" — queue the edit into pendingEdits; user /apply or `y` commits.
|
||||
* - "auto" — apply immediately, snapshot for /undo, show a short undo
|
||||
* banner so the user can roll back with one keystroke.
|
||||
* Persisted so `/mode auto` survives a relaunch. Missing → "review".
|
||||
*/
|
||||
export type EditMode = "review" | "auto";
|
||||
|
||||
/**
|
||||
* reasoning_effort cap for the model. "max" is the agent-class default;
|
||||
* "high" is cheaper / faster. Persisted so `/effort high` survives a
|
||||
* relaunch — earlier versions silently reverted to "max" on every new
|
||||
* session, which burned budget unexpectedly.
|
||||
*/
|
||||
export type ReasoningEffort = "high" | "max";
|
||||
|
||||
export interface ReasonixConfig {
|
||||
apiKey?: string;
|
||||
baseUrl?: string;
|
||||
/**
|
||||
* Default preset for `reasonix chat` / `reasonix run` when no flags override.
|
||||
* Maps to model + harvest + branch combos (see presets.ts). Missing → "fast".
|
||||
*/
|
||||
preset?: PresetName;
|
||||
/**
|
||||
* Edit-gate mode for `reasonix code`. See EditMode doc. Absent → "review".
|
||||
*/
|
||||
editMode?: EditMode;
|
||||
/**
|
||||
* Set to `true` the first time we've shown the "Shift+Tab cycles
|
||||
* review/AUTO" onboarding tip in `reasonix code`. Once seen, we stop
|
||||
* posting the tip — the bottom status bar carries the knowledge
|
||||
* forward without further nagging.
|
||||
*/
|
||||
editModeHintShown?: boolean;
|
||||
/**
|
||||
* Last reasoning_effort chosen via `/effort`. Loaded on launch so
|
||||
* "high" stays "high" — default is "max" when unset.
|
||||
*/
|
||||
reasoningEffort?: ReasoningEffort;
|
||||
/**
|
||||
* Default MCP server specs to bridge on every `reasonix chat`, in the
|
||||
* same `"name=cmd args..."` format that `--mcp` takes. Stored as strings
|
||||
* so `reasonix setup` stays symmetrical with the flag — one parser, one
|
||||
* format in the config file, grep-friendly.
|
||||
*/
|
||||
mcp?: string[];
|
||||
/**
|
||||
* Default session name (null/missing → "default", which is what the
|
||||
* CLI has been doing anyway). `reasonix setup` lets users pick a name
|
||||
* or opt into ephemeral.
|
||||
*/
|
||||
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 {
|
||||
@@ -51,12 +128,108 @@ 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);
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the persisted edit-mode. Unknown values fall back to "review" so
|
||||
* a user who hand-edits the file into an invalid state still gets the
|
||||
* safe default. `reasonix code` calls this at launch and the App lets
|
||||
* `/mode` / Shift+Tab flip it.
|
||||
*/
|
||||
export function loadEditMode(path: string = defaultConfigPath()): EditMode {
|
||||
const v = readConfig(path).editMode;
|
||||
return v === "auto" ? "auto" : "review";
|
||||
}
|
||||
|
||||
/** Persist the edit mode so `/mode auto` survives a relaunch. */
|
||||
export function saveEditMode(mode: EditMode, path: string = defaultConfigPath()): void {
|
||||
const cfg = readConfig(path);
|
||||
cfg.editMode = mode;
|
||||
writeConfig(cfg, path);
|
||||
}
|
||||
|
||||
/** True when the onboarding tip for the review/AUTO gate has been shown. */
|
||||
export function editModeHintShown(path: string = defaultConfigPath()): boolean {
|
||||
return readConfig(path).editModeHintShown === true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the persisted reasoning_effort. Unknown / missing values fall
|
||||
* back to "max" so the agent-class default is never silently overridden
|
||||
* by a hand-edited bad value in config.json.
|
||||
*/
|
||||
export function loadReasoningEffort(path: string = defaultConfigPath()): ReasoningEffort {
|
||||
const v = readConfig(path).reasoningEffort;
|
||||
return v === "high" ? "high" : "max";
|
||||
}
|
||||
|
||||
/** Persist the reasoning_effort cap so `/effort high` survives a relaunch. */
|
||||
export function saveReasoningEffort(
|
||||
effort: ReasoningEffort,
|
||||
path: string = defaultConfigPath(),
|
||||
): void {
|
||||
const cfg = readConfig(path);
|
||||
cfg.reasoningEffort = effort;
|
||||
writeConfig(cfg, path);
|
||||
}
|
||||
|
||||
/** Mark the onboarding tip as shown so subsequent launches skip it. */
|
||||
export function markEditModeHintShown(path: string = defaultConfigPath()): void {
|
||||
const cfg = readConfig(path);
|
||||
if (cfg.editModeHintShown === true) return;
|
||||
cfg.editModeHintShown = true;
|
||||
writeConfig(cfg, path);
|
||||
}
|
||||
|
||||
export function isPlausibleKey(key: string): boolean {
|
||||
const trimmed = key.trim();
|
||||
return /^sk-[A-Za-z0-9_-]{16,}$/.test(trimmed);
|
||||
|
||||
Loaded 100 of 204 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user