mirror of
https://github.com/esengine/DeepSeek-Reasonix.git
synced 2026-11-07 10:45:59 -10:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
30ee7cd818 | ||
|
|
72eb3a2a39 | ||
|
|
8780dae388 | ||
|
|
c9f3e733fa | ||
|
|
bf9bed64e8 | ||
|
|
02fcadf9e8 | ||
|
|
9254d3ae87 | ||
|
|
1d3b9e9c77 | ||
|
|
8694f7767e | ||
|
|
6fb3de2261 | ||
|
|
f5df1f9f5f | ||
|
|
73660729ab | ||
|
|
701dbcc32b | ||
|
|
1603479a3d | ||
|
|
d263068bb2 | ||
|
|
83768b92e4 | ||
|
|
9174c1ba59 | ||
|
|
95c978722a | ||
|
|
37e741afa1 | ||
|
|
526e3edc97 | ||
|
|
60024a5223 | ||
|
|
e463fe7518 | ||
|
|
53ab16bab4 | ||
|
|
4b2f2bf183 | ||
|
|
9d775acb94 | ||
|
|
70bffed518 | ||
|
|
77285a251c | ||
|
|
7f7b48021e | ||
|
|
732593e4ed | ||
|
|
d4662df023 | ||
|
|
06f4716e17 | ||
|
|
49d4648b07 | ||
|
|
634f8e6028 | ||
|
|
9d09a14f91 | ||
|
|
1c023126d9 | ||
|
|
87d87c8f47 | ||
|
|
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 |
No files matched your search
+718
@@ -3,6 +3,724 @@
|
||||
All notable changes to Reasonix. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/);
|
||||
this project uses [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [0.6.0] — 2026-04-24
|
||||
|
||||
**Headline:** Cost control becomes a first-class pillar. Default flips
|
||||
flash-first, `v4-pro` is opt-in, tool results auto-compact between
|
||||
turns, and the TUI grows per-turn cost visibility + a `/pro`
|
||||
one-shot upgrade. Month-over-month cost on an active coding project
|
||||
drops ~6–10× in practice.
|
||||
|
||||
### ⚠ Breaking (behavior, not API)
|
||||
|
||||
- **Default model is now `deepseek-v4-flash`**, not `deepseek-v4-pro`.
|
||||
`reasonix code`, `reasonix chat`, and subagents all land on flash
|
||||
by default. Users who need the frontier tier:
|
||||
`/preset max`, `/pro`, or `--model deepseek-v4-pro` on CLI.
|
||||
- **Preset defaults changed**. None of the three presets auto-enable
|
||||
`branch` or `harvest` anymore — both were hidden multipliers. The
|
||||
new matrix:
|
||||
| preset | model | effort | harvest | branch |
|
||||
|---|---|---|---|---|
|
||||
| fast | v4-flash | high | off | 1 |
|
||||
| smart (default) | v4-flash | max | off | 1 |
|
||||
| max | v4-pro | max | off | 1 |
|
||||
Users who want branching still get it via `/branch N`; users who
|
||||
want harvest still get it via `/harvest on`. Neither is implicit.
|
||||
- **Default preset is now `smart` (was `fast`).** Flash + full
|
||||
thinking budget is the best price/quality point for coding.
|
||||
- **`deepseek-chat` / `deepseek-reasoner` aliases scheduled for
|
||||
removal.** Still accepted (they map to flash non-thinking /
|
||||
thinking), but every user-facing surface (`/models`, setup wizard,
|
||||
`--help`) now advertises `v4-flash` / `v4-pro` only.
|
||||
|
||||
### Added — Cost control (Pillar 4)
|
||||
|
||||
- **`/pro` single-turn arming** — queue v4-pro for just the next
|
||||
turn; auto-disarms after. Separate from `/preset max` (persistent)
|
||||
so "this one task is hard" doesn't require a preset round-trip.
|
||||
Status bar shows `⇧ pro armed` in yellow while queued, `⇧ pro
|
||||
escalated` in red while the turn is actually running on pro.
|
||||
- **Failure-triggered auto-escalation** — the loop tracks
|
||||
`edit_file` SEARCH-not-found errors + ToolCallRepair fires per
|
||||
turn. 3+ signals flip the rest of the turn to `v4-pro` with a
|
||||
visible warning row. Counter resets at every turn start. No
|
||||
silent cost surprises.
|
||||
- **Model self-report escalation (`<<<NEEDS_PRO>>>`)** — system
|
||||
prompt teaches the model that when a task CLEARLY exceeds flash's
|
||||
capability (complex architecture, subtle correctness, genuine
|
||||
design trade-offs), emit the marker as the first line of its
|
||||
response. The loop aborts that call, retries this turn on pro,
|
||||
one shot. Guarded against infinite retry (pro never self-
|
||||
escalates) and streaming output is buffered so the marker never
|
||||
flickers on-screen before the retry fires.
|
||||
- **Turn-end auto-compaction** — every tool result over 3000 tokens
|
||||
gets shrunk to a cap at turn end. Biggest win for long sessions:
|
||||
a 12KB `read_file` output stops re-paying its cost on every
|
||||
future prompt. The proactive in-turn threshold also dropped from
|
||||
60% → 40% so the reactive 80% path rarely fires.
|
||||
- **Forced-summary + truncation-repair auxiliary calls hard-route to
|
||||
flash+effort=high** regardless of the main-turn tier. No reason to
|
||||
pay pro rates for "paraphrase these tool results into prose" or
|
||||
"close this truncated JSON."
|
||||
- **Subagent default flipped to `v4-flash` + `effort=high`**. Skill
|
||||
frontmatter `model:` / `effort:` remain the per-skill override.
|
||||
- **StatsPanel cost badges** — per-turn cost alongside session total.
|
||||
Colored thresholds: turn green under $0.05, yellow $0.05–0.20,
|
||||
red ≥$0.20; session same scale ×10.
|
||||
|
||||
### Added — UX
|
||||
|
||||
- **Plan body now flows into scrollback**, not inside the modal.
|
||||
`submit_plan` pushes a dedicated `role: "plan"` row into the
|
||||
Static log (rendered via the full markdown pipeline, never
|
||||
truncated); the PlanConfirm modal below shrinks to a tight
|
||||
approve/refine/cancel picker. Long plans are fully readable via
|
||||
terminal scrollback.
|
||||
- **Shared prompt fragments** — `TUI_FORMATTING_RULES` and
|
||||
`NEGATIVE_CLAIM_RULE` live once in `src/prompt-fragments.ts`,
|
||||
embedded into every system prompt (main code, default chat,
|
||||
subagent, built-in skills). Three near-identical copies
|
||||
collapsed; subagents gain the "don't assert absence without
|
||||
checking" guardrail they previously lacked.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **`run_skill` accepts decorated names.** The Skills index wrote
|
||||
entries like `- 🧬 explore`, and models copied the whole thing
|
||||
verbatim into `run_skill({name:"🧬 explore"})`. The index now
|
||||
uses a trailing `[🧬 subagent]` tag after the name, and
|
||||
`run_skill` normalizes inputs by stripping bracketed tags +
|
||||
leading emoji before lookup. Handles `"🧬 explore"`,
|
||||
`"[🧬 subagent] explore"`, `"explore [🧬 subagent]"`, etc.
|
||||
- **`edit_file` result no longer shown twice.** The interceptor's
|
||||
`applyNow` was pushing an info row, and the loop's tool event
|
||||
re-displayed the same text as a proper tool row. Dropped the info
|
||||
row push; the tool row alone carries the content.
|
||||
- **`run_command` / `run_background` descriptions teach their shell
|
||||
constraints upfront.** Explicit list of rejected operators
|
||||
(`&&`, `||`, `|`, `;`, `>`, `<`, `2>&1`), the `cd` doesn't-persist
|
||||
rule, a warning against unbounded-output commands (`netstat -ano`,
|
||||
`find /`), and concrete alternatives (`npm --prefix`, `cargo -C`,
|
||||
`git -C`). Models stop burning turns rediscovering these via
|
||||
error replies.
|
||||
|
||||
### Refactored (no behavior change)
|
||||
|
||||
- **App.tsx split** from 2931 → ~1980 lines by extracting
|
||||
`LiveRows.tsx`, `edit-history.ts`, `useEditHistory.ts`,
|
||||
`useCompletionPickers.ts`, `useSessionInfo.ts`, and
|
||||
`useSubagent.ts`. Every hook under 310 lines.
|
||||
- **slash.ts split** from 1786 → 20-line barrel. Types,
|
||||
SLASH_COMMANDS data + parse helpers, shared utility helpers, a
|
||||
handler registry (`dispatch.ts`), and 10 per-topic handler files
|
||||
all under `src/cli/ui/slash/`. Adding a command now means editing
|
||||
one handler file + one registry line.
|
||||
|
||||
### Docs
|
||||
|
||||
- **`docs/ARCHITECTURE.md` rewritten** for v0.6. The four pillars,
|
||||
current module layout (slash + handlers + hooks all reflected),
|
||||
design-evolution timeline replacing the stale roadmap,
|
||||
non-goals updated to call out "automatic cost escalation without
|
||||
user-visible announcement" as explicitly rejected.
|
||||
|
||||
## [0.5.24] — 2026-04-24
|
||||
|
||||
**Headline:** `reasonix code` gets a proper review gate, background
|
||||
process support, and aggressive context hygiene so long coding
|
||||
sessions stop bleeding money.
|
||||
|
||||
### Added
|
||||
|
||||
- **Edit-gate modes (review / auto)** — `edit_file` and `write_file`
|
||||
tool calls now route through a user gate. `review` (default) pops
|
||||
an `EditConfirm` modal with a scrollable diff + `y/n/a/A/Esc`
|
||||
keys; `auto` applies immediately and arms a 5-second undo banner.
|
||||
`Shift+Tab` cycles, `/mode` sets explicitly. Persisted to
|
||||
`~/.reasonix/config.json`.
|
||||
- **Session edit history** — every applied batch lands in an
|
||||
in-memory ring. `/history` lists them, `/show [id] [path]` dumps
|
||||
a stored diff (per-file when path given), `/undo [id] [path]`
|
||||
rolls back at any granularity (latest batch, specific batch,
|
||||
single file inside a batch). `u` keybind reaches back past the
|
||||
5-second banner as long as history has a non-undone entry.
|
||||
- **Background processes** — new `run_background` / `job_output` /
|
||||
`stop_job` / `list_jobs` tools for dev servers and watchers. Spawn
|
||||
returns after a ready-signal match (`listening on`, `Local:`,
|
||||
`compiled successfully`, …) or `waitSec` seconds. `/jobs` /
|
||||
`/kill <id>` / `/logs <id>` surface them to the user. Cleanup on
|
||||
SIGINT / SIGTERM / exit kills every child.
|
||||
- **Per-edit review modal (`src/cli/ui/EditConfirm.tsx`)** — diff
|
||||
viewport sized to terminal rows; `↑↓/j/k/Space/PgUp/PgDn/g/G`
|
||||
scroll a big diff in place. `a` applies rest of turn, `A` flips
|
||||
to AUTO for the session.
|
||||
- **Bottom mode status bar** — always-visible line above the prompt
|
||||
shows mode / pending count / Shift+Tab hint / running-jobs tag;
|
||||
flashes on mode change.
|
||||
- **Onboarding tip** — first `reasonix code` launch after upgrade
|
||||
posts the edit-gate keybindings once; suppressed after via the
|
||||
`editModeHintShown` flag.
|
||||
|
||||
### Changed
|
||||
|
||||
- **`read_file`** — adds `range:"A-B"` param (1-indexed, inclusive).
|
||||
Files longer than 200 lines with no scope return an auto-preview
|
||||
(head 80 + tail 40 + "N lines omitted" marker) instead of dumping
|
||||
everything. One `read_file` used to burn 6.5K tokens on a fat
|
||||
file; scoped reads cut that 3-5×.
|
||||
- **`directory_tree`** — default `maxDepth` 4 → 2; skips
|
||||
`node_modules`, `.git`, `dist`, `build`, `out`, `.next`, `.nuxt`,
|
||||
`target`, `.venv`, `venv`, `__pycache__`, `.pytest_cache`,
|
||||
`.mypy_cache`, `.cache`, `coverage` unless `include_deps:true`;
|
||||
collapses any directory past 50 children with a nudge toward
|
||||
`list_directory`.
|
||||
- **Auto-compact tool-call args** — after every `tool` response, the
|
||||
loop shrinks that call's `arguments` JSON if it exceeds 800
|
||||
tokens. Paths and short fields stay verbatim; long SEARCH /
|
||||
REPLACE / content strings get replaced with a `[…shrunk: N chars,
|
||||
M lines — tool already responded, see result]` marker. Cuts
|
||||
stale-args drag across every subsequent turn.
|
||||
- **`/compact`** — now covers both tool results (existing) and
|
||||
tool-call args (new) in one pass.
|
||||
- **`reasoningEffort` persistence** — `/effort high` now writes the
|
||||
choice to `~/.reasonix/config.json` and the loop picks it up at
|
||||
launch. Earlier versions silently reverted to `max` every relaunch.
|
||||
- **Prompt scope discipline** — code-mode prompt tells the model to
|
||||
stop after "run / start / launch" tasks instead of proactively
|
||||
refactoring, running tsc, or chasing unused imports.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **`run_background` confirmation path** — TUI now pops the shell
|
||||
confirm modal for `run_background` (not just `run_command`). A
|
||||
`kind` field on `pendingShell` routes approval to
|
||||
`JobRegistry.start()` so approving doesn't synchronously block on
|
||||
a dev server that never exits.
|
||||
- **`/kill` actually kills the tree** — Windows `taskkill /T /F`,
|
||||
POSIX `process.kill(-pid, …)` on a detached child. Earlier
|
||||
`SIGTERM` only killed the `npm.cmd` wrapper; `node → vite →
|
||||
esbuild` survived. `/kill` also posts a late "job N exit M" row
|
||||
when the stop resolves, so the user doesn't have to poll `/jobs`.
|
||||
|
||||
## [0.4.24] — 2026-04-22
|
||||
|
||||
**Headline:** `reasonix stats` is now a cross-session cost dashboard.
|
||||
|
||||
Every turn `reasonix chat|code|run` executes now appends one line to
|
||||
`~/.reasonix/usage.jsonl` carrying tokens + cost + the equivalent
|
||||
Claude Sonnet 4.6 cost. `reasonix stats` (no arg) rolls that log up
|
||||
into today / week / month / all-time windows:
|
||||
|
||||
```
|
||||
Reasonix usage — /Users/you/.reasonix/usage.jsonl (2.3 KB)
|
||||
|
||||
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%
|
||||
|
||||
most used model: deepseek-reasoner (84% of turns)
|
||||
top session: default (214 turns)
|
||||
tracked since: 2026-04-20
|
||||
```
|
||||
|
||||
Pillar 1's pitch (94–97% cost reduction vs Claude) turns from a
|
||||
blog number into a fact users can check on their own machine. The
|
||||
savings column is derived per turn (not synthesized) from the
|
||||
existing `claudeEquivalentCost()` helper in `src/telemetry.ts`.
|
||||
|
||||
Back-compat: `reasonix stats <transcript>` still works — passing a
|
||||
path falls back to the old per-file summary (assistant turns + tool
|
||||
calls). No arg → dashboard.
|
||||
|
||||
Privacy: the log contains tokens + costs + the user-chosen session
|
||||
name, nothing else. No prompts, no completions, no tool args.
|
||||
|
||||
### Added
|
||||
|
||||
- **`/stats` slash** — same dashboard, in-session. Reads
|
||||
`~/.reasonix/usage.jsonl` and renders via the shared
|
||||
`renderDashboard` pure function, so the shell command and the
|
||||
slash stay in sync by construction.
|
||||
- **`src/usage.ts`** — `appendUsage` (best-effort JSONL write,
|
||||
swallows disk failures so a read-only `~/` never breaks the
|
||||
turn), `readUsageLog` (malformed-line tolerant), `aggregateUsage`
|
||||
(rolling windows: 24h / 7d / 30d / all, plus model + session
|
||||
histograms), `bucketCacheHitRatio`, `bucketSavingsFraction`,
|
||||
`formatLogSize`.
|
||||
- **Wire-up** in `src/cli/ui/App.tsx` (assistant_final event) and
|
||||
`src/cli/commands/run.ts` (CI / scripting turns land in the same
|
||||
log as TUI turns).
|
||||
- **Upgraded `reasonix stats`**. No-arg → dashboard; transcript arg
|
||||
→ legacy per-file summary. `renderDashboard(agg, path)` is an
|
||||
exported pure function so tests can assert the string output.
|
||||
|
||||
### Tests (+15, suite 708 → 723)
|
||||
|
||||
- `tests/usage.test.ts` covers: appendUsage round-trip, empty
|
||||
log / malformed-line tolerance / parent-dir auto-creation / silent
|
||||
write-failure (points path at a regular file), aggregateUsage
|
||||
(empty, rolling-window bucketing, cross-record sums, byModel +
|
||||
bySession sort + (ephemeral) grouping), bucket helpers with zero
|
||||
denominators, renderDashboard (row labels + em-dash fallback).
|
||||
|
||||
---
|
||||
|
||||
## [0.4.23] — 2026-04-22
|
||||
|
||||
**Headline:** Hooks — user-defined automation that fires at four
|
||||
well-known points in the loop. Same two-scope layout (project +
|
||||
global) as memory and skills.
|
||||
|
||||
A hook is a shell command. Reasonix invokes it with stdin = a JSON
|
||||
envelope describing the event. The exit code drives the decision:
|
||||
`0` = pass, `2` = block (only on `PreToolUse` / `UserPromptSubmit`),
|
||||
anything else = warn (rendered inline as a yellow row, the loop
|
||||
keeps going). Block on a tool event swaps the dispatch for a
|
||||
synthetic tool result carrying the hook's stderr — the model sees
|
||||
a structured refusal instead of a silent omission, and can
|
||||
reason about what to do next.
|
||||
|
||||
Settings file:
|
||||
|
||||
```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 }]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Project hooks fire before global hooks. `match` is anchored regex
|
||||
on the tool name (`*` or omitted = match every tool); ignored for
|
||||
prompt / Stop events. Per-hook `timeout` overrides the defaults
|
||||
(5s for blocking events, 30s for logging events). The CLI loads
|
||||
both files at App mount; `/hooks` lists what's active and
|
||||
`/hooks reload` re-reads disk without tearing down the running
|
||||
loop (so the append-only log is preserved).
|
||||
|
||||
Deliberate non-goals for v1: workflow DSL, conditional chaining,
|
||||
hook templates. Hooks are shell commands — the user already has
|
||||
a programming language, we don't need to invent one.
|
||||
|
||||
### Added
|
||||
|
||||
- **`src/hooks.ts`** — `loadHooks` (project + global merge),
|
||||
`runHooks` (event filter + stdin JSON + spawn dispatch),
|
||||
`decideOutcome` (pure exit-code → decision matrix), `matchesTool`
|
||||
(anchored-regex name filter), `formatHookOutcomeMessage` (single
|
||||
source of truth for the warning row text). Spawner is injectable
|
||||
for tests; default uses `shell: true` so `&&`, pipes, env
|
||||
expansion all behave the way they do in the user's terminal.
|
||||
- **`CacheFirstLoopOptions.hooks` + `hookCwd`**. Loop dispatches
|
||||
`PreToolUse` (around line 866 in `src/loop.ts`) and `PostToolUse`
|
||||
(immediately after dispatch). `loop.hooks` is mutable so
|
||||
`/hooks reload` can swap the list without rebuilding the loop.
|
||||
- **App-level `UserPromptSubmit` + `Stop`**. `App.tsx` calls
|
||||
`runHooks` before pushing the user message (block = drop the
|
||||
prompt) and after `loop.step` resolves (warnings only, since the
|
||||
turn already ended).
|
||||
- **`/hooks` slash command**. `list` (default) groups loaded hooks
|
||||
by event with scope tags; `reload` re-reads settings.json from
|
||||
disk via the App-provided `reloadHooks` callback.
|
||||
- **`/update` slash command**. Shows current vs the last-resolved
|
||||
latest (piggybacks on App.tsx's mount-time background check) and
|
||||
prints the exact shell command to upgrade. Deliberately does NOT
|
||||
spawn `npm install` from inside the TUI — stdio:inherit into a
|
||||
running Ink renderer corrupts the display, and on Windows the
|
||||
currently-running binary can be locked. Users exit the session
|
||||
and run `reasonix update` in a fresh shell.
|
||||
|
||||
### Tests (+36, suite 672 → 708)
|
||||
|
||||
- `tests/hooks.test.ts` — `loadHooks` (empty / project+global / array
|
||||
order / ignore malformed entries / tolerate malformed JSON / no
|
||||
project root → global only / path helpers), `matchesTool` (`*` /
|
||||
anchored regex / substring rejected / malformed regex falls back
|
||||
to no-match / non-tool events ignore match), `decideOutcome`
|
||||
(exit 0 / exit 2 / non-zero / timeout / spawn error per event),
|
||||
`runHooks` (filters by event+match before running, stops at first
|
||||
block, doesn't stop on warn, stdin envelope shape, cwd routing,
|
||||
default timeouts, per-hook timeout override), `formatHookOutcomeMessage`
|
||||
(pass → empty / non-pass includes scope+command+detail / 60-char
|
||||
truncation).
|
||||
- `tests/loop-hooks.test.ts` — `CacheFirstLoop` accepts a hook list,
|
||||
default empty, `loop.hooks` is mutable, `hookCwd` defaults to
|
||||
`process.cwd()` and honors override, no-tool turn doesn't fire
|
||||
PreToolUse hooks.
|
||||
- `tests/slash.test.ts` — updated `suggestSlashCommands("h")` to
|
||||
include the new `hooks` command; added 4 tests for `/update`
|
||||
(pending / up-to-date / upgrade-available / suggest-surfaces-it).
|
||||
|
||||
---
|
||||
|
||||
## [0.4.22] — 2026-04-22
|
||||
|
||||
**Headline:** Version display in the TUI header + `reasonix update`
|
||||
self-upgrade command.
|
||||
|
||||
Two small quality-of-life additions. The stats panel now carries the
|
||||
running version (`Reasonix v0.4.22 · model …`) so users can tell at
|
||||
a glance whether they're on the latest build; a 24-hour background
|
||||
check against the npm registry quietly surfaces a yellow
|
||||
`update: X.Y.Z` nudge on the right side of the same row when a
|
||||
newer version has been published. The nudge never blocks startup —
|
||||
the fetch is bounded at 2s with a 24h on-disk cache, and any
|
||||
failure (offline, firewall, registry hiccup) is silent by design.
|
||||
|
||||
`reasonix update` is the command form: detects whether you're
|
||||
running a global install vs an ephemeral `npx` spawn, and either
|
||||
spawns `npm install -g reasonix@latest` for the former or prints a
|
||||
cache-refresh hint for the latter. `--dry-run` prints the plan
|
||||
without executing.
|
||||
|
||||
The `VERSION` constant now sources from `package.json` at runtime
|
||||
(walking up from `import.meta.url`) instead of a hand-maintained
|
||||
literal, so it can never drift again — it was stale at `0.4.20`
|
||||
before this release. Tests assert they stay in sync.
|
||||
|
||||
### Added
|
||||
|
||||
- **`src/version.ts`** — exports `VERSION`, `compareVersions`,
|
||||
`getLatestVersion`, `isNpxInstall`, and the
|
||||
`LATEST_CACHE_TTL_MS` / `LATEST_FETCH_TIMEOUT_MS` constants.
|
||||
`getLatestVersion` caches to `~/.reasonix/version-cache.json`
|
||||
(24h TTL) and returns `null` on any failure.
|
||||
- **`reasonix update`** subcommand (`src/cli/commands/update.ts`).
|
||||
`planUpdate()` is the pure decision function, `updateCommand()`
|
||||
is the CLI orchestrator with test seams (`fetchLatest`, `isNpx`,
|
||||
`spawnInstall`, `write`, `exit`).
|
||||
- **StatsPanel header shows `v${VERSION}`** inline, plus an
|
||||
`update: X` badge (yellow, bold) on the right when
|
||||
`updateAvailable` is passed. App.tsx fires the registry check
|
||||
in a background `useEffect` on mount; only a version strictly
|
||||
newer than the running one flips the state.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Drifted `VERSION` constant.** `src/index.ts` hard-coded
|
||||
`"0.4.20"` while `package.json` was on `0.4.21`. Replaced with a
|
||||
re-export from `src/version.ts`, which reads the manifest on
|
||||
first access. A regression test pins them together.
|
||||
|
||||
### Tests (+19, suite 588 → 607)
|
||||
|
||||
- `tests/version.test.ts` — `VERSION === package.json.version`,
|
||||
`compareVersions` covers numeric + pre-release ordering,
|
||||
`isNpxInstall` covers the three detection paths,
|
||||
`getLatestVersion` covers cache hit / force-refresh / expired
|
||||
entry / network failure / bad body / cache-write failure.
|
||||
- `tests/update-command.test.ts` — `planUpdate` returns the
|
||||
correct action for all four decision quadrants; `updateCommand`
|
||||
respects every seam: no-spawn on up-to-date, no-spawn on npx,
|
||||
spawns on global-behind-latest, honors `--dry-run`, exits
|
||||
non-zero on registry failure, surfaces npm's non-zero exit.
|
||||
|
||||
---
|
||||
|
||||
## [0.4.21] — 2026-04-22
|
||||
|
||||
**Headline:** Skills — user-authored prompt packs, two-scope layout
|
||||
matching user-memory.
|
||||
|
||||
Reasonix discovers skills under `<project>/.reasonix/skills/` (project
|
||||
scope) and `~/.reasonix/skills/` (global scope). Project wins on name
|
||||
collisions — per-repo overrides of a global skill work the way users
|
||||
expect. Deliberately NOT tied to any other tool's directory
|
||||
convention (`.claude/`, `.glm/`, etc.): Reasonix is model-agnostic at
|
||||
the conversation layer, so coupling the skill filesystem to one
|
||||
vendor would break anyone running a different backend.
|
||||
|
||||
The pinned index (names + one-line descriptions) lives in the
|
||||
immutable system prefix; bodies stay lazy and enter the append-only
|
||||
log only when invoked — either by the model calling the new
|
||||
`run_skill` tool or by the user typing `/skill <name> [args]`. No
|
||||
DAG engine, no workflow DSL — the model reads the skill's prose and
|
||||
continues the normal tool-use loop from there. Pillar 1's cache
|
||||
invariants are preserved: adding skills grows the pinned index
|
||||
(under a 4k char cap, with a truncation marker) but never alters
|
||||
the rest of the prefix.
|
||||
|
||||
### Added
|
||||
|
||||
- **`src/skills.ts`** — `SkillStore` with `SkillScope` of `"project"`
|
||||
or `"global"`, both layouts recognized (`{name}/SKILL.md` and flat
|
||||
`{name}.md`). `applySkillsIndex` composer is pinned into
|
||||
`applyMemoryStack` alongside REASONIX.md + user memory, receiving
|
||||
the same `rootDir` so the project scope picks up
|
||||
`<rootDir>/.reasonix/skills/`.
|
||||
- **`run_skill` tool** (`src/tools/skills.ts`) — read-only, returns
|
||||
the full markdown body plus an optional forwarded `Arguments:` line.
|
||||
Registered in `reasonix chat` (global only) and `reasonix code`
|
||||
(project + global).
|
||||
- **`/skill` slash command** — `list` / `show <name>` / bare
|
||||
`<name> [args]` form. The bare form injects the skill body as a
|
||||
user turn via the same `resubmit` hook `/apply-plan` uses. Reads
|
||||
project scope from `ctx.codeRoot`, mirroring how `/memory` behaves.
|
||||
|
||||
### Notes
|
||||
|
||||
- Each skill's `allowed-tools` frontmatter is parsed but **ignored**
|
||||
in v1. Reasonix's tool namespace (`filesystem`, `shell`, `web`)
|
||||
doesn't one-to-one map onto other clients' names; the model reads
|
||||
the prose instructions and picks our equivalents. Will revisit
|
||||
once the tradeoffs are clearer.
|
||||
- What we explicitly did **not** add: workflow DSL, DAG scheduler,
|
||||
parallel branches, sub-agents. Skills are prose; the model does the
|
||||
sequencing. This keeps single-loop + append-only + cache-first
|
||||
intact — the architectural non-goal "no multi-agent orchestration"
|
||||
stands.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **`ShellConfirm` "always allow" did not take effect until relaunch.**
|
||||
The `run_command` tool captured `extraAllowed` as a snapshot at
|
||||
registration time, so a prefix the user approved mid-session was
|
||||
written to `~/.reasonix/config.json` but the in-memory tool still
|
||||
refused it — the next invocation re-triggered the confirmation
|
||||
modal. `ShellToolsOptions.extraAllowed` now accepts a getter in
|
||||
addition to a static array; `reasonix code` passes
|
||||
`() => loadProjectShellAllowed(rootDir)` so the allowlist is
|
||||
re-read from disk on every dispatch. Static-array callers keep
|
||||
working unchanged.
|
||||
- **Windows cmd.exe built-ins (`dir`, `echo`, `type`, `ver`, …)
|
||||
crashed with ENOENT.** These aren't standalone executables, so
|
||||
`PATH × PATHEXT` lookup misses and `spawn dir` fails. `prepareSpawn`
|
||||
now routes bare unresolved Windows commands through
|
||||
`cmd.exe /d /s /c "<cmd> <args…>"` with verbatim-args + manual
|
||||
metacharacter quoting — same wrapping strategy we already use for
|
||||
`.cmd`/`.bat` files. Built-ins resolve correctly; genuinely unknown
|
||||
commands get the standard "'foo' is not recognized as an internal
|
||||
or external command" message instead of a raw spawn error.
|
||||
Already-extensioned names (`node.exe`) and paths-with-separators
|
||||
(`C:\tool.exe`) still pass through unwrapped so an explicit "I
|
||||
know where this is" invocation fails loudly when it's missing.
|
||||
|
||||
## [0.4.19] — 2026-04-22
|
||||
|
||||
**Headline:** Windows shell hotfix + StormBreaker visibility.
|
||||
`reasonix code` now runs `npm`, `npx`, `tsc`, `yarn`, `pnpm`, `bun`,
|
||||
`pytest`, and every other `.cmd` / `.bat` wrapper on Windows — both
|
||||
under Node 18/20 (broken by missing PATHEXT resolution) and Node
|
||||
21.7.3+/24 (broken by CVE-2024-27980's prohibition on direct
|
||||
`.cmd`/`.bat` spawns with `shell: false`). Unix behavior unchanged.
|
||||
Plus: the StormBreaker anti-loop-detector no longer silently halts
|
||||
a turn — when it fires it emits a visible warning row explaining
|
||||
what was suppressed and what the user should do next, and its
|
||||
sliding window resets on each new user message so a new intent
|
||||
doesn't inherit the previous turn's repeat patterns.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **`spawn npm ENOENT` on Windows** — `child_process.spawn` with
|
||||
`shell: false` uses `CreateProcess`, which ignores PATHEXT. Bare
|
||||
`npm` failed because no `npm.exe` exists — only `npm.cmd`. New
|
||||
`resolveExecutable(cmd)` walks `PATH × PATHEXT` manually and
|
||||
returns the full resolved path (`C:\Program Files\nodejs\npm.CMD`)
|
||||
before handing to spawn. Keeps `shell: false` (no shell expansion
|
||||
of piped / chained commands — the whole reason we avoided
|
||||
`shell: true` to begin with).
|
||||
- **`spawn npm EINVAL` on Node ≥ 21.7.3 / 24** — even with the
|
||||
resolved `.cmd` path, Node's post-CVE-2024-27980 patch refuses to
|
||||
execute `.cmd` / `.bat` files via direct spawn. Second layer:
|
||||
`prepareSpawn()` detects a `.cmd` / `.bat` target on Windows and
|
||||
rewrites the invocation to `cmd.exe /d /s /c "<bin> <args…>"`
|
||||
with `windowsVerbatimArguments: true`. Each arg is routed through
|
||||
`quoteForCmdExe()`, which wraps in double quotes when the arg
|
||||
contains whitespace or cmd.exe metacharacters
|
||||
(`" & | < > ^ % ( ) , ; !`) and doubles embedded quotes per
|
||||
cmd.exe's `""` escape rule. Arguments like `a&b` stay literal;
|
||||
they don't become shell operators.
|
||||
|
||||
### Added
|
||||
|
||||
- **`resolveExecutable(cmd, opts?)`** — exported from `src/tools/shell.ts`.
|
||||
Windows PATH × PATHEXT resolver. Opts lets tests inject `platform`,
|
||||
`env`, and `isFile` so the Windows-specific path can be exercised
|
||||
from a Linux CI runner without touching real fs.
|
||||
- **`prepareSpawn(argv, opts?)`** — exported. Returns the
|
||||
`(bin, args, spawnOverrides)` tuple that runCommand should pass to
|
||||
`child_process.spawn`. On non-Windows it's a passthrough; on
|
||||
Windows it applies the PATHEXT lookup and the `cmd.exe` wrapping
|
||||
when needed. Unit-tested without spawning real processes.
|
||||
- **`quoteForCmdExe(arg)`** — exported. The per-arg quoting
|
||||
function. Round-trip tested against realistic argvs
|
||||
(`npm install`, paths with spaces, args containing
|
||||
`& | < > ^`, empty strings, embedded double quotes).
|
||||
|
||||
- **Silent storm-break**. When `StormBreaker` caught a repeated
|
||||
`(tool, args)` pattern it dropped the offending call but emitted
|
||||
nothing user-visible beyond a small `[repair] broke 1 storm` note
|
||||
on the assistant row. If the suppressed call was the only tool
|
||||
call of the turn, the turn just ended — no explanation of why
|
||||
nothing happened. Now the loop yields a dedicated `warning` event
|
||||
(same channel as Esc-abort and budget warnings) with an
|
||||
actionable message, distinguishing "all calls suppressed (stuck
|
||||
retry)" from "some calls suppressed" cases.
|
||||
- **StormBreaker state bleeds across user turns**. The sliding
|
||||
window of recent signatures persisted for the lifetime of the
|
||||
loop, so a stuck pattern from an earlier intent could false-
|
||||
positive against the user's legitimate new "try again with
|
||||
different input" request. `CacheFirstLoop.step()` now calls
|
||||
`repair.resetStorm()` on every new user turn — the window
|
||||
repopulates naturally as the new turn's tool calls fire, and
|
||||
genuine repeats still trip after the usual 3-in-a-row pattern.
|
||||
|
||||
### Added
|
||||
|
||||
- **`ToolCallRepair.resetStorm()`** — exposes StormBreaker.reset
|
||||
through the repair facade. Called by the loop at each user turn;
|
||||
library consumers that drive `repair.process` manually can use it
|
||||
too if they wrap their own turn semantics.
|
||||
|
||||
### Tests (+22, suite 566 → 588)
|
||||
|
||||
- `tests/shell-tools.test.ts` (+21) — `resolveExecutable` on
|
||||
non-Windows (passthrough), PATHEXT walk (first-hit ordering,
|
||||
whitespace-tolerant PATHEXT entries), absolute-path / slash /
|
||||
already-extensioned passthrough, empty input, missing PATH /
|
||||
PATHEXT. `quoteForCmdExe` (simple identifiers unquoted, whitespace
|
||||
+ metachars quoted, embedded quotes doubled, empty string
|
||||
→ `""`). `prepareSpawn` (unix passthrough, `.cmd` wraps via
|
||||
cmd.exe, `.bat` wraps too, `.exe` direct, metachar args quoted,
|
||||
PATHEXT miss falls through).
|
||||
- `tests/repair/pipeline.test.ts` (+1) — `resetStorm` clears the
|
||||
repeat-window so post-reset calls aren't suppressed.
|
||||
- `tests/loop.test.ts` — the iter-budget warning test refined to
|
||||
filter by the iter-specific pattern, since identical fixture
|
||||
calls now also trip the (correct) storm warning.
|
||||
|
||||
### Internals
|
||||
|
||||
- `runCommand` in `src/tools/shell.ts` now calls `prepareSpawn`
|
||||
instead of spawning `argv[0]` directly. Every codepath that was
|
||||
going through `spawn` still does; the `bin` / `args` /
|
||||
`spawnOverrides` it receives are platform-normalized.
|
||||
- Existing allowlist + `readOnlyCheck` plan-mode gate + timeout /
|
||||
output-cap / AbortSignal wiring is untouched.
|
||||
- `CacheFirstLoop.step()` now resets the StormBreaker at the top of
|
||||
each turn AND emits a `warning` event after `repair.process()`
|
||||
when `report.stormsBroken > 0`. The existing `repair` field on
|
||||
`assistant_final` still carries the count for historical records
|
||||
/ transcripts.
|
||||
|
||||
---
|
||||
|
||||
## [0.4.18] — 2026-04-22
|
||||
|
||||
**Headline:** Plan Mode — the model can propose a markdown plan
|
||||
autonomously for large tasks (multi-file refactors, architecture
|
||||
changes, ambiguous requests), and you can also force a read-only
|
||||
exploration phase via `/plan`. Picker shows Approve / Refine / Cancel.
|
||||
Approve pushes a synthetic "implement now" message; Refine keeps the
|
||||
model exploring; Cancel drops the plan. Designed around Pillar 1 —
|
||||
tool specs stay pinned, so the cache prefix doesn't break when plan
|
||||
mode toggles.
|
||||
|
||||
### Added
|
||||
|
||||
- **`submit_plan` tool** (`src/tools/plan.ts`) — registered by default
|
||||
in `reasonix code`. Throws `PlanProposedError` carrying the plan
|
||||
text via the new `toToolResult()` protocol on ToolRegistry. Fires
|
||||
the picker whether or not plan mode is active — the model is
|
||||
expected to propose plans on its own for large tasks; `/plan` is
|
||||
the *stronger* constraint that forces the model into read-only.
|
||||
- **`/plan` slash** (code mode only) — toggles read-only plan mode.
|
||||
`/plan on`, `/plan off`, or `/plan` to flip. While on, the registry
|
||||
refuses non-read-only dispatch; while off, the model can still
|
||||
propose plans autonomously via submit_plan. `/status` surfaces the
|
||||
state; `StatsPanel` shows a red `PLAN` tag.
|
||||
- **`/apply-plan` slash** (code mode only) — force-approve fallback.
|
||||
Clears plan mode, clears the pending-plan picker state, and
|
||||
resubmits the implement-now synthetic via the existing `resubmit`
|
||||
mechanism. Useful when the model wrote the plan in assistant text
|
||||
instead of calling submit_plan, or when you want to keyboard-only
|
||||
the approval without the picker.
|
||||
- **`ToolDefinition.readOnly` + `readOnlyCheck`** — declarative gate
|
||||
used by `ToolRegistry.dispatch` when plan mode is on. Read tools
|
||||
(`read_file`, `list_directory`, `search_files`, `directory_tree`,
|
||||
`get_file_info`, `web_search`, `web_fetch`) run normally. Write
|
||||
tools bounce with a refusal the model reads and learns from.
|
||||
`run_command` uses a dynamic `readOnlyCheck` so allowlisted
|
||||
invocations (`git status`, `cargo check`, `npm test`, `grep`, …)
|
||||
still work during planning — exploration isn't gated. Non-allowlisted
|
||||
commands refuse just like other writes.
|
||||
- **`ToolRegistry.setPlanMode(on)` / `.planMode`** — the enforcement
|
||||
switch + accessor. Mirrored onto the UI's `planMode` React state so
|
||||
the StatsPanel badge stays in sync.
|
||||
- **`toToolResult()` extension protocol** on Error subclasses —
|
||||
`ToolRegistry.dispatch` calls it if present when an error is thrown,
|
||||
serializing custom fields alongside `error`. Used by
|
||||
`PlanProposedError` to ferry the plan text to the UI without
|
||||
regex-scraping the error message. Falls back safely on serialization
|
||||
failure.
|
||||
- **`PlanConfirm.tsx`** — 3-option Ink picker (Approve / Refine /
|
||||
Cancel) with the plan rendered as **live Markdown** (via the
|
||||
existing `Markdown` component — headings, lists, code, bold all
|
||||
formatted, not raw text) in a cyan-bordered panel above. 2 400-char
|
||||
rendered cap; longer plans get a "use /tool for full" truncation
|
||||
marker. Live rows hidden while the picker is up, matching
|
||||
`ShellConfirm`'s behavior. When the plan contains headings like
|
||||
"Open questions", "Risks", "Assumptions", "待确认", "开放问题", "风险",
|
||||
"未知", "假设", "不确定", the picker auto-selects the Refine option
|
||||
by default and shows a yellow "▲ the plan has open questions —
|
||||
pick Refine to answer them" hint above the options.
|
||||
- **`PlanRefineInput.tsx`** — inline text input that appears after
|
||||
the user picks either **Approve** or **Refine**. Picking Approve
|
||||
lets the user type last-minute instructions or answers to the
|
||||
model's open questions (blank Enter = approve as-is). Picking
|
||||
Refine requires specifics — the input collects them and includes
|
||||
them verbatim in the synthetic sent to the model, so "refine"
|
||||
actually means "revise with this feedback" instead of the generic
|
||||
"try again" message the first cut sent. Esc returns to the picker
|
||||
without resuming the loop.
|
||||
- **System-prompt guidance** (`CODE_SYSTEM_PROMPT`) — teaches the
|
||||
model when to call submit_plan autonomously (big / risky / ambiguous
|
||||
tasks) vs. just making the change (typos, obvious one-line fixes),
|
||||
and how `/plan` mode adds the stronger dispatch gate on top.
|
||||
|
||||
### Tests (+24, suite 542→566)
|
||||
|
||||
- `tests/plan.test.ts` (+17) — ToolRegistry plan-mode gate
|
||||
(default-off, toggle, block non-read-only, allow read-only, honor
|
||||
`readOnlyCheck` per-args, precedence over `readOnly`, off-mode
|
||||
noop); `toToolResult` protocol (serializes custom fields, falls
|
||||
back on serializer failure); `PlanProposedError` carries plan +
|
||||
STOP directive; `registerPlanTool` registers submit_plan as
|
||||
read-only, fires picker both in and out of plan mode, rejects
|
||||
empty plans, trims whitespace.
|
||||
- `tests/slash.test.ts` (+7) — `/plan` registry entries + required
|
||||
commands check; `/plan` toggle / on / off / true / false / 0 / 1;
|
||||
`/plan` info text explicit about the stronger-constraint
|
||||
relationship; `/apply-plan` code-mode gating; `/apply-plan` flips
|
||||
mode + clears pending + resubmits; works without optional
|
||||
`clearPendingPlan` callback; `/status` plan-mode line appears
|
||||
iff on.
|
||||
|
||||
### Internals
|
||||
|
||||
- `src/tools/filesystem.ts` — read_file / list_directory /
|
||||
directory_tree / search_files / get_file_info tagged readOnly.
|
||||
- `src/tools/shell.ts` — run_command gets `readOnlyCheck` tied to
|
||||
the existing `isAllowed` check + `allowAll` escape hatch.
|
||||
- `src/tools/web.ts` — web_search / web_fetch tagged readOnly.
|
||||
- `src/cli/commands/code.tsx` — `registerPlanTool(tools)` added after
|
||||
the filesystem and shell registrations so the tool is always in
|
||||
the pinned spec list (prefix cache stays stable across
|
||||
plan-mode toggles).
|
||||
- `src/index.ts` — re-exports `PlanProposedError`, `registerPlanTool`,
|
||||
`PlanToolOptions` for library consumers.
|
||||
|
||||
---
|
||||
|
||||
## [0.4.17] — 2026-04-22
|
||||
|
||||
**Headline:** Project memory — drop a `REASONIX.md` in your project
|
||||
|
||||
@@ -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,8 +14,9 @@
|
||||
[](https://www.npmjs.com/package/reasonix)
|
||||
[](./package.json)
|
||||
|
||||
**A DeepSeek-native AI coding assistant in your terminal.** Ink TUI. MCP
|
||||
first-class. No LangChain.
|
||||
**A DeepSeek-native AI coding agent in your terminal.** Edits files as
|
||||
reviewable SEARCH/REPLACE blocks. Ink TUI. MCP first-class. No
|
||||
LangChain.
|
||||
|
||||
---
|
||||
|
||||
@@ -16,60 +25,27 @@ first-class. No LangChain.
|
||||
**1. Get a DeepSeek API key.** Free credit on signup:
|
||||
<https://platform.deepseek.com/api_keys>
|
||||
|
||||
**2. Run it.** No install needed.
|
||||
|
||||
```bash
|
||||
npx reasonix
|
||||
```
|
||||
|
||||
First run walks you through a 30-second wizard:
|
||||
|
||||
- paste your API key (saved to `~/.reasonix/config.json`)
|
||||
- pick a preset — `fast` (cheap chat, default), `smart` (+R1 reasoning), `max` (+self-consistency branching)
|
||||
- multi-select MCP servers from a catalog (filesystem, memory, github, puppeteer, …)
|
||||
|
||||
Every run after that drops you straight into chat.
|
||||
|
||||
**3. Inside the chat.** Type anything and hit Enter. Type `/help` to see
|
||||
every command. The status bar at the top shows cache hit %, cost so far,
|
||||
balance, and context usage. Press `Esc` to cancel whatever is running.
|
||||
|
||||
```
|
||||
reasonix › explain what this project does
|
||||
assistant
|
||||
…streams R1 reasoning into a dim preview, then writes the answer…
|
||||
status bar: cache hit 92% · cost $0.001 · ctx 8k/131k (6%) · balance 12.34 CNY
|
||||
```
|
||||
|
||||
Requires Node ≥ 18. Works on macOS, Linux, Windows (Git Bash + PowerShell).
|
||||
|
||||
---
|
||||
|
||||
## Using `reasonix code` — your terminal pair programmer
|
||||
|
||||
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.
|
||||
**2. Point it at a project.** No install needed.
|
||||
|
||||
```bash
|
||||
cd my-project
|
||||
npx reasonix code
|
||||
```
|
||||
|
||||
### Walkthrough: fix a bug
|
||||
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 对大小写敏感导致登录失败,帮我改成大小写不敏感
|
||||
reasonix code › users.ts 里 findByEmail 对大小写敏感导致登录失败,帮我改
|
||||
|
||||
assistant
|
||||
▸ R1 reasoning · 1243 chars of thought
|
||||
▸ tool<search_files> → src/users.ts, src/users.test.ts
|
||||
▸ tool<read_file> → (src/users.ts, 412 chars)
|
||||
▸ tool<read_file> → (src/users.test.ts, 820 chars)
|
||||
▸ 找到了。findByEmail 直接用 === 比对。我把查询和存储都规范化为小写,并补上一条测试。
|
||||
▸ 找到了。findByEmail 直接用 === 比对。改成小写规范化并补一条测试。
|
||||
|
||||
src/users.ts
|
||||
<<<<<<< SEARCH
|
||||
@@ -79,49 +55,34 @@ src/users.ts
|
||||
return users.find(u => u.email.toLowerCase() === needle);
|
||||
>>>>>>> REPLACE
|
||||
|
||||
src/users.test.ts
|
||||
<<<<<<< SEARCH
|
||||
it("finds by email", () => {
|
||||
expect(findByEmail("[email protected]")).toBeDefined();
|
||||
});
|
||||
=======
|
||||
it("finds by email", () => {
|
||||
expect(findByEmail("[email protected]")).toBeDefined();
|
||||
});
|
||||
▸ 1 pending edit across 1 file — /apply to write · /discard to drop
|
||||
|
||||
it("is case-insensitive", () => {
|
||||
expect(findByEmail("[email protected]")).toBeDefined();
|
||||
});
|
||||
>>>>>>> REPLACE
|
||||
|
||||
▸ 2 pending edits across 2 files — /apply to write · /discard to drop
|
||||
reasonix code › /apply
|
||||
▸ ✓ applied src/users.ts
|
||||
```
|
||||
|
||||
**At this point nothing has been written to disk.** You have three
|
||||
options:
|
||||
Requires Node ≥ 20.10. macOS, Linux, Windows (PowerShell / Git Bash /
|
||||
Windows Terminal). Press `Esc` anytime to abort; `/help` for the full
|
||||
command list.
|
||||
|
||||
- `/apply` — commit the pending blocks. You'll see `✓ applied
|
||||
src/users.ts` and `✓ applied src/users.test.ts`. A snapshot of the
|
||||
pre-edit file is kept so `/undo` can roll back.
|
||||
- `/discard` — throw the blocks away without writing.
|
||||
- Keep chatting — ask for adjustments. Say "also cover the empty
|
||||
string case" and the model proposes another block set.
|
||||
---
|
||||
|
||||
After applying:
|
||||
## `reasonix code` — pair programmer in your terminal
|
||||
|
||||
```
|
||||
reasonix code › /commit "fix: findByEmail case-insensitive"
|
||||
▸ git add -A && git commit -m "fix: findByEmail case-insensitive"
|
||||
[main a1b2c3d] fix: findByEmail case-insensitive
|
||||
```
|
||||
|
||||
`/commit` runs `git add -A && git commit -m ...` from the sandbox root.
|
||||
Scoped to the directory you launch from. The model has native
|
||||
`read_file` / `write_file` / `edit_file` / `list_directory` /
|
||||
`search_files` / `directory_tree` / `get_file_info` /
|
||||
`create_directory` / `move_file` tools, all sandboxed — any path that
|
||||
resolves outside the launch root (including `..` and symlink escapes)
|
||||
is refused. Plus `run_command` with a read-only allowlist; anything
|
||||
state-mutating (`npm install`, `git commit`, …) is gated behind a
|
||||
confirmation picker.
|
||||
|
||||
### Walkthrough: explore before editing
|
||||
|
||||
For "what does this code do?" questions the model uses the read-side
|
||||
tools and replies in prose — no SEARCH/REPLACE blocks, no file writes.
|
||||
Ask to change something only when you mean it:
|
||||
tools and replies in prose — no SEARCH/REPLACE blocks, no file
|
||||
writes. Ask to change something only when you mean it:
|
||||
|
||||
```
|
||||
reasonix code › 这个项目的路由是怎么组织的?
|
||||
@@ -132,29 +93,147 @@ assistant
|
||||
nested routes 写子路径,最后 …
|
||||
```
|
||||
|
||||
If the SEARCH text doesn't match the file byte-for-byte, `edit_file`
|
||||
refuses the edit loudly rather than fuzzy-matching. The model sees the
|
||||
error and retries with the correct search text — silent wrong edits are
|
||||
worse than visible rejections.
|
||||
If an `edit_file` SEARCH block doesn't match the file byte-for-byte,
|
||||
the edit is refused loudly rather than fuzzy-matched. The model sees
|
||||
the error and retries — silent wrong edits are worse than visible
|
||||
rejections.
|
||||
|
||||
### Plan mode — review before executing
|
||||
|
||||
For anything bigger than a typo, the model is encouraged to propose a
|
||||
markdown plan first. You'll see a picker with **Approve / Refine /
|
||||
Cancel**:
|
||||
|
||||
```
|
||||
reasonix code › 把 auth 从 JWT 迁移到 session cookies
|
||||
|
||||
▸ plan submitted — awaiting your review
|
||||
────────────────────────────────────────
|
||||
## Summary
|
||||
Swap JWT middleware for session cookies, keep user table intact.
|
||||
|
||||
## Files
|
||||
- src/auth/middleware.ts — replace `verifyJwt` with `readSession`
|
||||
- src/auth/session.ts — new file, in-memory store + signed cookie
|
||||
- src/routes/login.ts — return Set-Cookie instead of a token
|
||||
- tests/auth/*.test.ts — update fixtures
|
||||
|
||||
## Risks
|
||||
- Existing logged-in users get logged out (no migration).
|
||||
- Session store is in-memory; restart clears sessions.
|
||||
────────────────────────────────────────
|
||||
▸ Approve and implement
|
||||
Refine — explore more
|
||||
Cancel
|
||||
```
|
||||
|
||||
**Force it** with `/plan` — enters an explicit read-only phase where
|
||||
the model *must* submit a plan before any edit or non-allowlisted
|
||||
shell call will execute. Use for high-stakes changes you want to
|
||||
audit before the model touches disk. `/plan off` or picker
|
||||
Approve/Cancel exits.
|
||||
|
||||
### 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 R1 reasoning for the last turn
|
||||
(reasoner preset only).
|
||||
- `/memory` — show the project's `REASONIX.md` (see below).
|
||||
- `/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.
|
||||
- Drop `--no-session` for an ephemeral session that doesn't persist.
|
||||
- `/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.
|
||||
|
||||
### Project memory — `REASONIX.md`
|
||||
### `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 immutable-prefix system prompt every time you launch
|
||||
`reasonix` in that directory. Good for house conventions, domain
|
||||
glossary, or things the model keeps forgetting:
|
||||
into the system prompt every launch. Committable team memory — house
|
||||
conventions, domain glossary, things the model keeps forgetting:
|
||||
|
||||
```bash
|
||||
cat > REASONIX.md <<'EOF'
|
||||
@@ -167,18 +246,151 @@ 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 the lookup for CI /
|
||||
offline repro.
|
||||
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.
|
||||
|
||||
```bash
|
||||
npx reasonix code src/ # narrower sandbox (only src/ is writable)
|
||||
npx reasonix code --no-session # ephemeral — nothing saved to disk
|
||||
npx reasonix code --preset max # R1 reasoning + 3-way self-consistency
|
||||
```
|
||||
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.
|
||||
|
||||
---
|
||||
|
||||
## Using `reasonix` — general chat
|
||||
## `reasonix` — also works as general chat
|
||||
|
||||
Same TUI, no filesystem tools unless you opt in via MCP. Good for
|
||||
drafting, Q&A, schema design, architecture discussions, or driving
|
||||
@@ -187,102 +399,81 @@ your own MCP servers. Sessions persist per name under
|
||||
|
||||
```bash
|
||||
npx reasonix # uses saved config + wizard-selected MCP
|
||||
npx reasonix --preset smart # one-shot override
|
||||
npx reasonix --session design # named session
|
||||
npx reasonix --session design # resume it later — history intact
|
||||
npx reasonix --preset smart # reasoner + R1 harvest for this run
|
||||
npx reasonix --session design # named session — resume later with --session design
|
||||
```
|
||||
|
||||
### Walkthrough: a multi-turn session with R1 reasoning
|
||||
|
||||
```
|
||||
reasonix › /preset smart
|
||||
▸ switched to smart · model deepseek-reasoner · harvest on · branch off
|
||||
|
||||
reasonix › 我要给一个 Flutter 应用设计限时折扣的弹窗展示规则。目标:
|
||||
每天首次打开时弹一次,连续弹 3 天后休眠 7 天。怎么实现?
|
||||
|
||||
assistant
|
||||
▸ R1 reasoning · 2410 chars of thought
|
||||
‹ subgoals (3): 持久化展示计数 · 判断是否过了 24h · 休眠窗口判断
|
||||
‹ hypotheses (2): SharedPreferences 存计数 · lastShownAt 时间戳
|
||||
‹ uncertainties (1): 用户换设备后重置的策略
|
||||
|
||||
建议数据模型:
|
||||
lastShownAt: DateTime
|
||||
consecutiveShows: int (0..3)
|
||||
sleepUntil: DateTime?
|
||||
…
|
||||
```
|
||||
|
||||
`/think` dumps the full R1 thought trace; `/status` shows the current
|
||||
model / flags / context use; `/retry` re-samples the same prompt with
|
||||
a fresh random seed (useful when the first answer missed something).
|
||||
|
||||
### Walkthrough: attach MCP tools on the fly
|
||||
Bridge your own MCP servers on the fly:
|
||||
|
||||
```bash
|
||||
# Attach the official filesystem server sandboxed to /tmp/scratch,
|
||||
# plus a remote knowledge-base over SSE.
|
||||
npx reasonix \
|
||||
--mcp "fs=npx -y @modelcontextprotocol/server-filesystem /tmp/scratch" \
|
||||
--mcp "fs=npx -y @modelcontextprotocol/server-filesystem /tmp/safe" \
|
||||
--mcp "kb=https://mcp.example.com/sse"
|
||||
```
|
||||
|
||||
Inside the chat:
|
||||
|
||||
```
|
||||
reasonix › /mcp
|
||||
▸ fs (stdio, 11 tools) fs_read_file · fs_list_directory · fs_write_file · …
|
||||
▸ kb (sse, 4 tools) kb_search · kb_get · kb_list_collections · kb_stat
|
||||
|
||||
reasonix › 在 /tmp/scratch 下把所有 .log 文件里含 "ERROR" 的行收集到 errors.txt
|
||||
assistant
|
||||
▸ tool<fs_search_files> → 4 matches
|
||||
▸ tool<fs_read_file> → …
|
||||
▸ tool<fs_write_file> → wrote 2.4 KB to errors.txt
|
||||
▸ 已写入 errors.txt — 共 38 行,分布在 4 个源文件中。
|
||||
```
|
||||
|
||||
MCP tools go through the same Cache-First + repair + context-safety
|
||||
plumbing as native tools, including the 32k result cap and live
|
||||
progress-notification rendering.
|
||||
|
||||
### When to use `reasonix` vs `reasonix code`
|
||||
|
||||
| situation | command |
|
||||
|---|---|
|
||||
| Editing files in the current project | `reasonix code` |
|
||||
| Exploring a project without writing files | `reasonix code` (it only writes on `/apply`) |
|
||||
| Design / architecture / research chat | `reasonix` |
|
||||
| Driving your own MCP servers | `reasonix --mcp "..."` |
|
||||
| One-shot question, no TUI | `reasonix run "..."` |
|
||||
| Reproducing a prior session / benchmark | `reasonix replay path.jsonl` |
|
||||
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 |
|
||||
| `/help` · `/?` | full command reference with hints |
|
||||
| `/status` | current model · flags · context · session |
|
||||
| `/new` · `/reset` | fresh conversation in the same session |
|
||||
| `/clear` | clear visible scrollback only (log kept) |
|
||||
| `/retry` | truncate and resend your last message (fresh sample) |
|
||||
| `/exit` · `/quit` | quit |
|
||||
|
||||
**Model**
|
||||
|
||||
| command | what it does |
|
||||
|---|---|
|
||||
| `/preset <fast\|smart\|max>` | one-tap bundle (model + harvest + branch) |
|
||||
| `/model <id>` | switch DeepSeek model (`deepseek-chat`, `deepseek-reasoner`) |
|
||||
| `/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) |
|
||||
| `/mcp` | list attached MCP servers and their tools |
|
||||
| `/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) |
|
||||
| `/think` | dump the last turn's full R1 reasoning |
|
||||
| `/retry` | truncate and resend your last message (fresh sample) |
|
||||
| `/compact [cap]` | shrink oversized tool results in the log |
|
||||
| `/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 |
|
||||
| `/new` (alias `/reset`) | start a fresh conversation in the same session |
|
||||
| `/clear` | clear visible scrollback only (log kept) |
|
||||
| `/setup` | reconfigure (exit and run `reasonix setup`) |
|
||||
| `/exit` | quit |
|
||||
|
||||
Additional commands in `reasonix code`:
|
||||
**Code mode only** (`reasonix code`)
|
||||
|
||||
| command | what it does |
|
||||
|---|---|
|
||||
@@ -290,32 +481,36 @@ Additional commands in `reasonix code`:
|
||||
| `/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:**
|
||||
**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 matches
|
||||
- `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)
|
||||
- `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.
|
||||
- Sessions live as JSONL under `~/.reasonix/sessions/<name>.jsonl`
|
||||
(per directory for `reasonix code`). Every message appended
|
||||
atomically; `Ctrl+C` never loses context.
|
||||
- Tool results are capped at 32k chars per call. Oversized sessions
|
||||
self-heal on load (shrinks + rewrites the file).
|
||||
- Malformed `assistant.tool_calls` / `tool` pairing is validated on
|
||||
every outgoing API call so a corrupted session can't keep 400ing.
|
||||
- Context gauge turns yellow at 50%, red at 80% with a `/compact` nudge.
|
||||
Approaching the 131k window triggers an automatic compaction attempt
|
||||
before falling back to a forced summary.
|
||||
- The model's sandbox in `reasonix code` refuses any path that resolves
|
||||
outside the launch directory, including symlink escape and `..` traversal.
|
||||
- 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
|
||||
|
||||
@@ -329,18 +524,12 @@ If you hit this, run with plain mode:
|
||||
|
||||
```bash
|
||||
REASONIX_UI=plain npx reasonix code
|
||||
# or
|
||||
REASONIX_UI=plain npx reasonix
|
||||
```
|
||||
|
||||
Plain mode suppresses every live/animated row and disables the
|
||||
internal tick timer. You lose the streaming preview and spinners
|
||||
but gain stable scrollback. Committed events (your prompts, tool
|
||||
results, the model's final responses) still render normally via
|
||||
Ink's `<Static>` append path.
|
||||
|
||||
Windows Terminal, PowerShell 7 in Windows Terminal, and WezTerm
|
||||
don't need this opt-out.
|
||||
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.
|
||||
|
||||
---
|
||||
|
||||
@@ -352,19 +541,11 @@ 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`.
|
||||
|
||||
```
|
||||
you › Flutter 3.19 新加了什么?
|
||||
assistant
|
||||
▸ tool<web_search> → query: "Flutter 3.19 new features"
|
||||
▸ tool<web_fetch> → https://docs.flutter.dev/release/3-19
|
||||
▸ 3.19 主要新增了 …
|
||||
```
|
||||
|
||||
Backed by **Mojeek**'s public search page — an independent web index,
|
||||
no API key, no signup, bot-friendly. Coverage on niche or very recent
|
||||
queries can be thinner than Google/Bing, but it's reliable from
|
||||
scripts and doesn't gate on cookies or sessions. (DDG was the original
|
||||
backend but it started serving anti-bot pages in 2026.)
|
||||
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):
|
||||
|
||||
@@ -374,37 +555,11 @@ backend but it started serving anti-bot pages in 2026.)
|
||||
```
|
||||
|
||||
```bash
|
||||
# Or one env var (wins over config):
|
||||
REASONIX_SEARCH=off npx reasonix
|
||||
REASONIX_SEARCH=off npx reasonix code
|
||||
```
|
||||
|
||||
**Bring your own provider** (Kagi, SearXNG, Serper, an internal
|
||||
cache) — implement the two tools however you want and register them
|
||||
manually:
|
||||
|
||||
```ts
|
||||
import { ToolRegistry } from "reasonix";
|
||||
// Register your own `web_search` / `web_fetch` on a ToolRegistry,
|
||||
// then pass it to CacheFirstLoop (or `reasonix chat --no-config`
|
||||
// with seedTools via library API).
|
||||
```
|
||||
|
||||
Inside the session:
|
||||
|
||||
```
|
||||
reasonix › Flutter 3.19 引入了什么新的 Navigator API?
|
||||
assistant
|
||||
▸ tool<web_search> → query: "Flutter 3.19 new Navigator API"
|
||||
answer: Flutter 3.19 introduces the NavigatorObserver changes …
|
||||
1. Flutter 3.19 Release Notes — https://docs.flutter.dev/…
|
||||
2. What's new in Flutter 3.19 — https://medium.com/…
|
||||
▸ tool<web_fetch> → https://docs.flutter.dev/release/release-notes/3-19-0
|
||||
(full page text, clipped at 32k)
|
||||
▸ 3.19 新增了 …
|
||||
```
|
||||
|
||||
For advanced / self-hosted search (Kagi, SearXNG, internal caches)
|
||||
implement the `WebSearchProvider` interface and call
|
||||
**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`.
|
||||
|
||||
@@ -412,14 +567,14 @@ existing MCP search server via `--mcp`.
|
||||
|
||||
## MCP — bring your own tools
|
||||
|
||||
Any [MCP](https://spec.modelcontextprotocol.io/) server works. Wizard
|
||||
lets you pick from a catalog, or drive it by flag:
|
||||
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 servers at once
|
||||
# multiple at once
|
||||
npx reasonix \
|
||||
--mcp "fs=npx -y @modelcontextprotocol/server-filesystem /tmp/safe" \
|
||||
--mcp "demo=npx tsx examples/mcp-server-demo.ts"
|
||||
@@ -428,21 +583,22 @@ npx reasonix \
|
||||
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.
|
||||
`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).
|
||||
Supported transports: **stdio** (local command) and **HTTP+SSE**
|
||||
(remote, MCP 2024-11-05 spec).
|
||||
|
||||
---
|
||||
|
||||
## CLI reference
|
||||
|
||||
```bash
|
||||
npx reasonix # chat (uses saved config)
|
||||
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
|
||||
@@ -474,6 +630,9 @@ 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)
|
||||
```
|
||||
|
||||
---
|
||||
@@ -519,13 +678,14 @@ for await (const ev of loop.step("What is 17 + 25?")) {
|
||||
console.log(loop.stats.summary());
|
||||
```
|
||||
|
||||
`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.
|
||||
`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.
|
||||
|
||||
---
|
||||
|
||||
## Why Reasonix (not LangChain)
|
||||
## 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
|
||||
@@ -539,11 +699,10 @@ caching, JSON mode. Generic wrappers leave these on the table.
|
||||
| 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 |
|
||||
| First-run config prompt + Markdown TUI | 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:
|
||||
repeats = 48 runs per side, live DeepSeek `deepseek-chat`, sole
|
||||
variable prefix stability:
|
||||
|
||||
| metric | baseline (cache-hostile) | Reasonix | delta |
|
||||
|---|---:|---:|---:|
|
||||
@@ -551,7 +710,7 @@ prefix stability:
|
||||
| cost / task | $0.002599 | $0.001579 | **−39%** |
|
||||
| pass rate | 96% (23/24) | **100% (24/24)** | — |
|
||||
|
||||
**Verify it yourself — no API key, zero cost:**
|
||||
**Reproduce without spending an API credit:**
|
||||
|
||||
```bash
|
||||
git clone https://github.com/esengine/reasonix.git && cd reasonix && npm install
|
||||
@@ -567,8 +726,10 @@ 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`.
|
||||
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):
|
||||
@@ -583,10 +744,16 @@ with two concurrent MCP subprocesses):
|
||||
|
||||
## Non-goals
|
||||
|
||||
- Multi-agent orchestration (use LangGraph).
|
||||
- RAG / vector stores (use LlamaIndex).
|
||||
- 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.
|
||||
|
||||
@@ -598,9 +765,9 @@ 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 (444 tests)
|
||||
npm test # vitest (1007 tests)
|
||||
npm run lint # biome
|
||||
npm run typecheck # tsc --noEmit
|
||||
```
|
||||
|
||||
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 |
+3
-2
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "reasonix",
|
||||
"version": "0.4.17",
|
||||
"description": "DeepSeek-native agent framework: cache-first loop, R1 thought harvesting, tool-call repair.",
|
||||
"version": "0.10.0",
|
||||
"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,28 @@
|
||||
// Minimal Ctrl+C probe. Usage: node scripts/ctrlc-probe.mjs
|
||||
// Reproduces the exact stdin setup Reasonix uses, then logs every byte
|
||||
// it sees and exits on \x03. Tells us whether the OS even delivers
|
||||
// Ctrl+C to a Node child on this terminal.
|
||||
|
||||
process.stdin.setRawMode(true);
|
||||
process.stdin.setEncoding("utf8");
|
||||
process.stdin.resume();
|
||||
|
||||
console.log("ctrl+c probe armed. press keys; ctrl+c should exit.");
|
||||
console.log("if ctrl+c does NOT exit, the byte never reaches Node on this terminal.\n");
|
||||
|
||||
process.stdin.on("data", (chunk) => {
|
||||
const s = String(chunk);
|
||||
for (const ch of s) {
|
||||
const code = ch.charCodeAt(0);
|
||||
process.stdout.write(`got byte: 0x${code.toString(16).padStart(2, "0")} (${JSON.stringify(ch)})\r\n`);
|
||||
if (ch === "\x03") {
|
||||
process.stdout.write("→ \\x03 detected, exiting.\r\n");
|
||||
process.exit(0);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
process.on("SIGINT", () => {
|
||||
process.stdout.write("→ SIGINT received, exiting.\r\n");
|
||||
process.exit(0);
|
||||
});
|
||||
@@ -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,30 @@
|
||||
// Shift+Enter probe. Usage: node scripts/shift-enter-probe.mjs
|
||||
// Enables modifyOtherKeys + kitty keyboard protocol, then prints the
|
||||
// raw bytes for every keypress. Press Shift+Enter and see what your
|
||||
// terminal actually emits — if it's just "0x0d", the host doesn't
|
||||
// support either protocol and there's nothing Reasonix can do at the
|
||||
// raw-stdin layer.
|
||||
|
||||
process.stdout.write("\u001b[>4;2m"); // modifyOtherKeys level 2 (xterm)
|
||||
process.stdout.write("\u001b[>1u"); // kitty keyboard protocol level 1
|
||||
|
||||
process.stdin.setRawMode(true);
|
||||
process.stdin.setEncoding("utf8");
|
||||
process.stdin.resume();
|
||||
|
||||
console.log("shift+enter probe armed. press keys; ctrl+c exits.");
|
||||
console.log("expected for shift+enter:");
|
||||
console.log(" modifyOtherKeys → 0x1b 0x5b 0x32 0x37 0x3b 0x32 0x3b 0x31 0x33 0x7e (\\x1b[27;2;13~)");
|
||||
console.log(" kitty → 0x1b 0x5b 0x31 0x33 0x3b 0x32 0x75 (\\x1b[13;2u)");
|
||||
console.log(" unsupported → 0x0d (just \\r — no way to distinguish)\n");
|
||||
|
||||
process.stdin.on("data", (chunk) => {
|
||||
const s = String(chunk);
|
||||
const bytes = [...s].map((c) => `0x${c.charCodeAt(0).toString(16).padStart(2, "0")}`).join(" ");
|
||||
process.stdout.write(`got: ${bytes} (${JSON.stringify(s)})\r\n`);
|
||||
if (s.includes("\x03")) {
|
||||
process.stdout.write("\u001b[>4m"); // disable modifyOtherKeys
|
||||
process.stdout.write("\u001b[<u"); // pop kitty level
|
||||
process.exit(0);
|
||||
}
|
||||
});
|
||||
@@ -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,598 @@
|
||||
/**
|
||||
* 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"),
|
||||
};
|
||||
|
||||
// =============================================================================
|
||||
// @url mentions — async sibling of @path. Matches `@http(s)://...` after a
|
||||
// word boundary, fetches each URL once per session (in-memory cache), and
|
||||
// appends a "Referenced URLs" block under the prompt the model sees. Uses
|
||||
// the same web-fetch + HTML-strip pipeline as the model's `web_fetch` tool
|
||||
// so a `@url` reference and a model-issued fetch produce identical content.
|
||||
|
||||
/**
|
||||
* Matches `@http://...` or `@https://...` at a word boundary. Captures the
|
||||
* URL minus the leading `@`. Trailing sentence punctuation is stripped
|
||||
* separately because URLs can legitimately contain `,` `.` `)` etc., and a
|
||||
* blanket trim would butcher real query strings.
|
||||
*/
|
||||
export const AT_URL_PATTERN = /(?<=^|\s)@(https?:\/\/\S+)/g;
|
||||
|
||||
/** Default cap on inlined URL body (chars). Matches DEFAULT_AT_MENTION_MAX_BYTES order-of-magnitude. */
|
||||
export const DEFAULT_AT_URL_MAX_CHARS = 32_000;
|
||||
|
||||
export interface AtUrlExpansion {
|
||||
/** The raw `@url` token as it appeared in the text. */
|
||||
token: string;
|
||||
/** Absolute URL (after trailing-punctuation strip). */
|
||||
url: string;
|
||||
/** True if content was inlined. False = skipped (reason in `skip`). */
|
||||
ok: boolean;
|
||||
/** Page title when extractable from `<title>`. */
|
||||
title?: string;
|
||||
/** Char count of the (post-truncation) inlined body. */
|
||||
chars?: number;
|
||||
/** True iff the original page exceeded `maxChars` and was clipped. */
|
||||
truncated?: boolean;
|
||||
/** Why the mention was skipped — set when ok=false. */
|
||||
skip?: "fetch-error" | "non-text" | "timeout" | "blocked";
|
||||
/** Free-form error message attached to skip outcomes. */
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export interface AtUrlOptions {
|
||||
/** Max chars of inlined body per URL. Default DEFAULT_AT_URL_MAX_CHARS. */
|
||||
maxChars?: number;
|
||||
/** Per-URL fetch timeout in ms. */
|
||||
timeoutMs?: number;
|
||||
/**
|
||||
* Override the fetcher — production wires `webFetch` from src/tools/web.ts.
|
||||
* Tests inject a stub so the suite stays offline.
|
||||
*/
|
||||
fetcher?: (
|
||||
url: string,
|
||||
opts: { maxChars?: number; timeoutMs?: number; signal?: AbortSignal },
|
||||
) => Promise<{ url: string; title?: string; text: string; truncated: boolean }>;
|
||||
/**
|
||||
* Optional cache the caller persists across calls (e.g. one map per
|
||||
* session). Hit-on-URL skips the fetch entirely. Omit for one-shot
|
||||
* tests that don't care about reuse.
|
||||
*/
|
||||
cache?: Map<string, AtUrlExpansion & { body?: string }>;
|
||||
/** Forward Esc/abort to the fetcher. */
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
/**
|
||||
* Expand `@http(s)://…` mentions in `text`. Returns the (possibly augmented)
|
||||
* text plus a per-URL report so the caller can surface fetched URLs in the
|
||||
* UI. Async because each URL hits the network; the file-mention sibling
|
||||
* (`expandAtMentions`) stays sync.
|
||||
*
|
||||
* Caching: when `opts.cache` is provided, a hit skips the network and
|
||||
* reuses the prior expansion (including its body). One Map per session is
|
||||
* the intended use — a long conversation that references the same URL
|
||||
* twice doesn't pay twice.
|
||||
*
|
||||
* Trailing-punctuation handling: a sentence like "see @https://x.com." has
|
||||
* the period stripped so the actual fetched URL is `https://x.com`. We
|
||||
* conservatively strip only `.,;:!?` and `)]}>` from the tail; anything
|
||||
* else is preserved so query strings survive intact.
|
||||
*/
|
||||
export async function expandAtUrls(
|
||||
text: string,
|
||||
opts: AtUrlOptions = {},
|
||||
): Promise<{ text: string; expansions: AtUrlExpansion[] }> {
|
||||
const maxChars = opts.maxChars ?? DEFAULT_AT_URL_MAX_CHARS;
|
||||
const fetcher = opts.fetcher;
|
||||
if (!fetcher) {
|
||||
throw new Error("expandAtUrls: fetcher option is required (wire src/tools/web.ts:webFetch)");
|
||||
}
|
||||
|
||||
// De-dupe by URL so the same `@https://x.com` referenced twice fetches once.
|
||||
const seen = new Map<string, AtUrlExpansion>();
|
||||
const bodies = new Map<string, string>();
|
||||
const order: string[] = [];
|
||||
|
||||
for (const match of text.matchAll(AT_URL_PATTERN)) {
|
||||
const rawUrl = match[1] ?? "";
|
||||
const url = stripUrlTail(rawUrl);
|
||||
if (!url) continue;
|
||||
if (seen.has(url)) continue;
|
||||
|
||||
const cached = opts.cache?.get(url);
|
||||
if (cached) {
|
||||
seen.set(url, cached);
|
||||
if (cached.body) bodies.set(url, cached.body);
|
||||
order.push(url);
|
||||
continue;
|
||||
}
|
||||
|
||||
let expansion: AtUrlExpansion;
|
||||
let body = "";
|
||||
try {
|
||||
const page = await fetcher(url, {
|
||||
maxChars,
|
||||
timeoutMs: opts.timeoutMs,
|
||||
signal: opts.signal,
|
||||
});
|
||||
body = page.text;
|
||||
expansion = {
|
||||
token: `@${url}`,
|
||||
url,
|
||||
ok: true,
|
||||
title: page.title,
|
||||
chars: body.length,
|
||||
truncated: page.truncated,
|
||||
};
|
||||
} catch (err) {
|
||||
const message = (err as Error).message ?? String(err);
|
||||
// Tag a few common shapes so the UI can hint at causes.
|
||||
let skip: AtUrlExpansion["skip"] = "fetch-error";
|
||||
if (/aborted|timeout/i.test(message)) skip = "timeout";
|
||||
else if (/40\d|forbidden|access denied|captcha/i.test(message)) skip = "blocked";
|
||||
expansion = {
|
||||
token: `@${url}`,
|
||||
url,
|
||||
ok: false,
|
||||
skip,
|
||||
error: message,
|
||||
};
|
||||
}
|
||||
seen.set(url, expansion);
|
||||
if (body) bodies.set(url, body);
|
||||
if (opts.cache) opts.cache.set(url, { ...expansion, body });
|
||||
order.push(url);
|
||||
}
|
||||
|
||||
if (seen.size === 0) return { text, expansions: [] };
|
||||
|
||||
const expansions = order.map((u) => seen.get(u)!).filter(Boolean);
|
||||
const blocks: string[] = [];
|
||||
for (const ex of expansions) {
|
||||
if (ex.ok) {
|
||||
const titleAttr = ex.title ? ` title="${escapeAttr(ex.title)}"` : "";
|
||||
const truncTag = ex.truncated ? ' truncated="true"' : "";
|
||||
const body = bodies.get(ex.url) ?? "";
|
||||
blocks.push(`<url href="${ex.url}"${titleAttr}${truncTag}>\n${body}\n</url>`);
|
||||
} else {
|
||||
const reasonAttr = ex.skip ?? "fetch-error";
|
||||
blocks.push(`<url href="${ex.url}" skipped="${reasonAttr}" />`);
|
||||
}
|
||||
}
|
||||
const augmented = `${text}\n\n[Referenced URLs]\n${blocks.join("\n\n")}`;
|
||||
return { text: augmented, expansions };
|
||||
}
|
||||
|
||||
/**
|
||||
* Strip trailing sentence punctuation from a URL captured at a word
|
||||
* boundary. `https://x.com.` → `https://x.com`; `https://x.com/?q=a)` →
|
||||
* `https://x.com/?q=a`. Conservative: only strips `.,;:!?` and unmatched
|
||||
* close-brackets `)]}>` from the very end. Internal punctuation in path /
|
||||
* query is preserved.
|
||||
*
|
||||
* Returns empty string if everything stripped — caller treats as "no URL."
|
||||
*/
|
||||
export function stripUrlTail(raw: string): string {
|
||||
let s = raw;
|
||||
while (s.length > 0) {
|
||||
const last = s[s.length - 1]!;
|
||||
if (".,;:!?".includes(last)) {
|
||||
s = s.slice(0, -1);
|
||||
continue;
|
||||
}
|
||||
if (")]}>".includes(last)) {
|
||||
// Only strip if the matching open bracket isn't elsewhere in the
|
||||
// URL — avoids butchering legitimate `(thing)` query fragments.
|
||||
const open = ({ ")": "(", "]": "[", "}": "{", ">": "<" } as const)[
|
||||
last as ")" | "]" | "}" | ">"
|
||||
];
|
||||
if (!s.includes(open)) {
|
||||
s = s.slice(0, -1);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
function escapeAttr(s: string): string {
|
||||
return s
|
||||
.replace(/"/g, """)
|
||||
.replace(/[\r\n]+/g, " ")
|
||||
.trim();
|
||||
}
|
||||
+69
-28
@@ -15,10 +15,13 @@ import {
|
||||
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 { KeystrokeProvider } from "../ui/keystroke-context.js";
|
||||
import type { McpServerSummary } from "../ui/slash.js";
|
||||
|
||||
export interface ProgressInfo {
|
||||
@@ -50,7 +53,7 @@ export interface ChatOptions {
|
||||
* Enable SEARCH/REPLACE edit-block processing after each assistant turn.
|
||||
* Set by `reasonix code`; plain `reasonix chat` leaves this off.
|
||||
*/
|
||||
codeMode?: { rootDir: string };
|
||||
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). */
|
||||
@@ -100,39 +103,49 @@ function Root({
|
||||
}
|
||||
process.env.DEEPSEEK_API_KEY = key;
|
||||
|
||||
// KeystrokeProvider must wrap App from OUTSIDE — App.tsx itself
|
||||
// calls `useKeystroke` in its function body for global hotkeys
|
||||
// (Ctrl+C, Esc abort, Shift+Tab edit-mode cycle, @-mention picker,
|
||||
// slash-suggestion navigation). If the provider lives inside App's
|
||||
// render, `useContext(KeystrokeContext)` returns `null` at hook
|
||||
// call time and those handlers silently never subscribe.
|
||||
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);
|
||||
}}
|
||||
/>
|
||||
<KeystrokeProvider>
|
||||
<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);
|
||||
}}
|
||||
/>
|
||||
</KeystrokeProvider>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<App
|
||||
model={appProps.model}
|
||||
system={appProps.system}
|
||||
transcript={appProps.transcript}
|
||||
harvest={appProps.harvest}
|
||||
branch={appProps.branch}
|
||||
session={appProps.session}
|
||||
tools={tools}
|
||||
mcpSpecs={mcpSpecs}
|
||||
mcpServers={mcpServers}
|
||||
progressSink={progressSink}
|
||||
codeMode={appProps.codeMode}
|
||||
/>
|
||||
<KeystrokeProvider>
|
||||
<App
|
||||
model={appProps.model}
|
||||
system={appProps.system}
|
||||
transcript={appProps.transcript}
|
||||
harvest={appProps.harvest}
|
||||
branch={appProps.branch}
|
||||
session={appProps.session}
|
||||
tools={tools}
|
||||
mcpSpecs={mcpSpecs}
|
||||
mcpServers={mcpServers}
|
||||
progressSink={progressSink}
|
||||
codeMode={appProps.codeMode}
|
||||
/>
|
||||
</KeystrokeProvider>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -210,6 +223,7 @@ export async function chatCommand(opts: ChatOptions): Promise<void> {
|
||||
spec: raw,
|
||||
toolCount: bridge.registeredNames.length,
|
||||
report,
|
||||
client: mcp,
|
||||
});
|
||||
} catch (err) {
|
||||
// Per-server failure is non-fatal: one broken server shouldn't
|
||||
@@ -243,6 +257,22 @@ export async function chatCommand(opts: ChatOptions): Promise<void> {
|
||||
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 /
|
||||
@@ -260,6 +290,17 @@ export async function chatCommand(opts: ChatOptions): Promise<void> {
|
||||
rewriteSession(opts.session, []);
|
||||
}
|
||||
|
||||
// No startup clear, no resize listener. Earlier attempts wrote
|
||||
// various combinations of \x1b[2J / \x1b[3J / cursor-home to
|
||||
// present a 'clean canvas' on launch and to neutralize Ink's
|
||||
// eraseLines miscount on resize, but on xterm.js-based terminals
|
||||
// (VSCode integrated terminal in particular) those sequences
|
||||
// interfere with scrollback in ways that make wheel-up scroll
|
||||
// dead. Letting Ink mount directly leaves the user's previous
|
||||
// shell prompt visible above (scrolling up just works) and
|
||||
// accepts the resize-ghost / launch-noise tradeoffs as known
|
||||
// limitations — `/clear` is the manual reset.
|
||||
|
||||
const { waitUntilExit } = render(
|
||||
<Root
|
||||
initialKey={initialKey}
|
||||
|
||||
@@ -19,10 +19,14 @@
|
||||
*/
|
||||
|
||||
import { basename, resolve } from "node:path";
|
||||
import { loadProjectShellAllowed } from "../../config.js";
|
||||
import { loadEditMode, 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";
|
||||
|
||||
@@ -39,6 +43,15 @@ export interface CodeOptions {
|
||||
forceResume?: boolean;
|
||||
/** Skip the session picker — always wipe prior messages and start fresh. */
|
||||
forceNew?: boolean;
|
||||
/**
|
||||
* Opt into Pillar 2 harvesting (extracts a typed plan state from R1
|
||||
* reasoning via an extra V3 call). Default OFF in code mode — the
|
||||
* displayed subgoals/hypotheses/rejectedPaths have no programmatic
|
||||
* consumer, only `uncertainties.length` feeds branching, and the
|
||||
* extra V3 call adds ~10-15% per-turn cost. Users who want the
|
||||
* reasoning surfaced explicitly can pass `--harvest`.
|
||||
*/
|
||||
harvest?: boolean;
|
||||
}
|
||||
|
||||
export async function codeCommand(opts: CodeOptions = {}): Promise<void> {
|
||||
@@ -55,25 +68,71 @@ export async function codeCommand(opts: CodeOptions = {}): Promise<void> {
|
||||
// triggered R1's DSML hallucinations all through 0.4.x.
|
||||
const tools = new ToolRegistry();
|
||||
registerFilesystemTools(tools, { rootDir });
|
||||
// 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.
|
||||
extraAllowed: loadProjectShellAllowed(rootDir),
|
||||
// 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),
|
||||
// `yolo` edit-mode disables shell confirmations entirely. Re-read
|
||||
// from config on each dispatch so /mode yolo (or Shift+Tab cycling
|
||||
// through to it) flips the gate live without forcing a relaunch.
|
||||
allowAll: () => loadEditMode() === "yolo",
|
||||
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. We DON'T install SIGINT/SIGTERM
|
||||
// handlers here — that overrode Node's default "exit on Ctrl+C" with
|
||||
// a silent no-op, which made Ctrl+C feel broken in the TUI. App.tsx
|
||||
// owns the SIGINT path now (it shows the quit-armed banner and calls
|
||||
// exit() on confirmation); this 'exit' hook just guarantees the job
|
||||
// registry is drained on the way out, regardless of which exit path
|
||||
// fired.
|
||||
process.once("exit", () => {
|
||||
void jobs.shutdown();
|
||||
});
|
||||
|
||||
await chatCommand({
|
||||
model: opts.model ?? "deepseek-reasoner",
|
||||
harvest: true, // smart preset's harvest setting, always on for code
|
||||
model: opts.model ?? "deepseek-v4-flash",
|
||||
harvest: opts.harvest ?? false,
|
||||
system: codeSystemPrompt(rootDir),
|
||||
transcript: opts.transcript,
|
||||
session,
|
||||
seedTools: tools,
|
||||
codeMode: { rootDir },
|
||||
codeMode: { rootDir, jobs },
|
||||
forceResume: opts.forceResume,
|
||||
forceNew: opts.forceNew,
|
||||
});
|
||||
|
||||
@@ -11,6 +11,7 @@ import { SseTransport } from "../../mcp/sse.js";
|
||||
import { type McpTransport, StdioTransport } from "../../mcp/stdio.js";
|
||||
import { ToolRegistry } from "../../tools.js";
|
||||
import { openTranscriptFile, recordFromLoopEvent, writeRecord } from "../../transcript.js";
|
||||
import { appendUsage } from "../../usage.js";
|
||||
|
||||
export interface RunOptions {
|
||||
task: string;
|
||||
@@ -148,6 +149,12 @@ export async function runCommand(opts: RunOptions): Promise<void> {
|
||||
if (ev.role === "tool") process.stdout.write(`\n[tool ${ev.toolName}] ${ev.content}\n`);
|
||||
if (ev.role === "error") process.stderr.write(`\n[error] ${ev.error}\n`);
|
||||
if (ev.role === "done") process.stdout.write("\n");
|
||||
if (ev.role === "assistant_final" && ev.stats?.usage) {
|
||||
// `reasonix run` is often used in CI / scripting — we want
|
||||
// those turns to show up in `reasonix stats` too so the
|
||||
// dashboard reflects all DeepSeek spend, not just TUI sessions.
|
||||
appendUsage({ session: null, model: ev.stats.model, usage: ev.stats.usage });
|
||||
}
|
||||
// Persist every non-streaming event — deltas would flood the file and
|
||||
// aren't useful for replay (replay renders final content, not keystrokes).
|
||||
if (transcriptStream && ev.role !== "assistant_delta") {
|
||||
|
||||
+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);
|
||||
}
|
||||
}
|
||||
+87
-20
@@ -1,7 +1,9 @@
|
||||
import { Command } from "commander";
|
||||
import { readConfig } from "../config.js";
|
||||
import { VERSION } from "../index.js";
|
||||
import { applyProjectMemory } from "../project-memory.js";
|
||||
import { ESCALATION_CONTRACT } from "../prompt-fragments.js";
|
||||
import { listSessions } from "../session.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";
|
||||
@@ -12,37 +14,68 @@ 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";
|
||||
import { resolveContinueFlag, 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
|
||||
.name("reasonix")
|
||||
.description("DeepSeek-native agent framework — built for cache hits and cheap tokens.")
|
||||
.version(VERSION);
|
||||
.version(VERSION)
|
||||
.option(
|
||||
"-c, --continue",
|
||||
"Resume the most recently used chat session without showing the picker.",
|
||||
);
|
||||
|
||||
// `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 () => {
|
||||
program.action(async (opts: { continue?: boolean }) => {
|
||||
const cfg = readConfig();
|
||||
if (!cfg.setupCompleted) {
|
||||
await setupCommand({});
|
||||
return;
|
||||
}
|
||||
const defaults = resolveDefaults({});
|
||||
const continueOpts = resolveContinueFlag(
|
||||
opts.continue,
|
||||
defaults.session,
|
||||
() => listSessions()[0],
|
||||
(msg) => process.stderr.write(`${msg}\n`),
|
||||
);
|
||||
await chatCommand({
|
||||
model: defaults.model,
|
||||
system: applyProjectMemory(DEFAULT_SYSTEM, process.cwd()),
|
||||
system: applyMemoryStack(DEFAULT_SYSTEM, process.cwd()),
|
||||
harvest: defaults.harvest,
|
||||
branch: defaults.branch,
|
||||
session: defaults.session,
|
||||
session: continueOpts.session,
|
||||
mcp: defaults.mcp,
|
||||
forceResume: continueOpts.forceResume,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -56,13 +89,17 @@ program
|
||||
program
|
||||
.command("code [dir]")
|
||||
.description(
|
||||
"Code-editing chat — filesystem MCP auto-bridged at <dir> (default: cwd), coding system prompt, smart preset. Model proposes SEARCH/REPLACE blocks; Reasonix applies them to disk.",
|
||||
"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 reasoner model")
|
||||
.option("-m, --model <id>", "Override default model (v4-flash)")
|
||||
.option("--no-session", "Disable session persistence for this run")
|
||||
.option("-r, --resume", "Skip the session picker — always continue prior messages")
|
||||
.option("-n, --new", "Skip the session picker — always wipe prior messages and start fresh")
|
||||
.option("--transcript <path>", "Write a JSONL transcript to this path")
|
||||
.option(
|
||||
"--harvest",
|
||||
"Opt-in Pillar-2 plan-state extraction. Adds one flash call per turn; off by default (no preset enables it).",
|
||||
)
|
||||
.action(async (dir: string | undefined, opts) => {
|
||||
await codeCommand({
|
||||
dir,
|
||||
@@ -71,6 +108,7 @@ program
|
||||
transcript: opts.transcript,
|
||||
forceResume: !!opts.resume,
|
||||
forceNew: !!opts.new,
|
||||
harvest: !!opts.harvest,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -82,20 +120,24 @@ program
|
||||
.option("--transcript <path>", "Write a JSONL transcript to this path")
|
||||
.option(
|
||||
"--preset <name>",
|
||||
"Bundle of model + harvest + branch. One of: fast, smart, max. Overrides config.preset.",
|
||||
"Model + effort bundle. One of: fast (flash·high), smart (flash·max, default), max (pro·max). Overrides config.preset.",
|
||||
)
|
||||
.option(
|
||||
"--harvest",
|
||||
"Extract typed plan state from R1 reasoning (Pillar 2). Overrides preset's harvest setting.",
|
||||
"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: from config, usually 'default').")
|
||||
.option("--no-session", "Disable session persistence for this run (ephemeral chat)")
|
||||
.option("-r, --resume", "Skip the session picker — always continue prior messages")
|
||||
.option(
|
||||
"-c, --continue",
|
||||
"Resume the most-recently-used session (any name) without showing the picker.",
|
||||
)
|
||||
.option("-n, --new", "Skip the session picker — always wipe prior messages and start fresh")
|
||||
.option(
|
||||
"--mcp <spec>",
|
||||
@@ -118,16 +160,28 @@ program
|
||||
preset: opts.preset,
|
||||
noConfig: opts.config === false,
|
||||
});
|
||||
// `-c` is "newest-touched session" + auto-resume; `-r` is "this
|
||||
// session's prior messages, even if you also passed --session".
|
||||
// When both are set we prefer the explicit `--session` + `-r`
|
||||
// (more specific input wins). `-c` only kicks in if `-r` wasn't.
|
||||
const continueOpts = opts.resume
|
||||
? { session: defaults.session, forceResume: true }
|
||||
: resolveContinueFlag(
|
||||
opts.continue,
|
||||
defaults.session,
|
||||
() => listSessions()[0],
|
||||
(msg) => process.stderr.write(`${msg}\n`),
|
||||
);
|
||||
await chatCommand({
|
||||
model: defaults.model,
|
||||
system: applyProjectMemory(opts.system, process.cwd()),
|
||||
system: applyMemoryStack(opts.system, process.cwd()),
|
||||
transcript: opts.transcript,
|
||||
harvest: defaults.harvest,
|
||||
branch: defaults.branch,
|
||||
session: defaults.session,
|
||||
session: continueOpts.session,
|
||||
mcp: defaults.mcp,
|
||||
mcpPrefix: opts.mcpPrefix,
|
||||
forceResume: !!opts.resume,
|
||||
forceResume: continueOpts.forceResume,
|
||||
forceNew: !!opts.new,
|
||||
});
|
||||
});
|
||||
@@ -168,7 +222,7 @@ program
|
||||
await runCommand({
|
||||
task,
|
||||
model: defaults.model,
|
||||
system: applyProjectMemory(opts.system, process.cwd()),
|
||||
system: applyMemoryStack(opts.system, process.cwd()),
|
||||
harvest: defaults.harvest,
|
||||
branch: defaults.branch,
|
||||
transcript: opts.transcript,
|
||||
@@ -178,9 +232,12 @@ program
|
||||
});
|
||||
|
||||
program
|
||||
.command("stats <transcript>")
|
||||
.description("Summarize a JSONL transcript produced by `reasonix chat --transcript`.")
|
||||
.action((transcript: string) => {
|
||||
.command("stats [transcript]")
|
||||
.description(
|
||||
"Show usage dashboard (today / week / month / all-time · turns · cache hit · cost · savings vs Claude). " +
|
||||
"Pass a transcript path to fall back to the per-file summary (assistant turns + tool calls).",
|
||||
)
|
||||
.action((transcript: string | undefined) => {
|
||||
statsCommand({ transcript });
|
||||
});
|
||||
|
||||
@@ -260,6 +317,16 @@ mcp
|
||||
|
||||
program.command("version").description("Print Reasonix version.").action(versionCommand);
|
||||
|
||||
program
|
||||
.command("update")
|
||||
.description(
|
||||
"Check the npm registry for a newer Reasonix and install it. Detects npx vs global install; for npx users, prints a cache-refresh hint instead of running `npm i -g`.",
|
||||
)
|
||||
.option("--dry-run", "Print the plan without executing the install")
|
||||
.action(async (opts: { dryRun?: boolean }) => {
|
||||
await updateCommand({ dryRun: !!opts.dryRun });
|
||||
});
|
||||
|
||||
program.parseAsync(process.argv).catch((err) => {
|
||||
console.error(err);
|
||||
process.exit(1);
|
||||
|
||||
+30
-3
@@ -6,7 +6,7 @@
|
||||
* 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 "fast" preset defaults
|
||||
* 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
|
||||
@@ -18,6 +18,7 @@ import { PRESETS } from "./ui/presets.js";
|
||||
|
||||
export interface ResolvedDefaults {
|
||||
model: string;
|
||||
reasoningEffort: "high" | "max";
|
||||
harvest: boolean;
|
||||
branch: number | undefined;
|
||||
mcp: string[];
|
||||
@@ -44,6 +45,7 @@ export function resolveDefaults(flags: RawCliFlags): ResolvedDefaults {
|
||||
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);
|
||||
@@ -55,7 +57,7 @@ export function resolveDefaults(flags: RawCliFlags): ResolvedDefaults {
|
||||
|
||||
const session = resolveSession(flags.session, cfg.session);
|
||||
|
||||
return { model, harvest, branch, mcp, session };
|
||||
return { model, reasoningEffort, harvest, branch, mcp, session };
|
||||
}
|
||||
|
||||
function pickPreset(
|
||||
@@ -64,7 +66,7 @@ function pickPreset(
|
||||
): PresetName {
|
||||
if (flagPreset && isPresetName(flagPreset)) return flagPreset;
|
||||
if (configPreset) return configPreset;
|
||||
return "fast";
|
||||
return "smart";
|
||||
}
|
||||
|
||||
function isPresetName(s: string): s is PresetName {
|
||||
@@ -87,3 +89,28 @@ function resolveSession(
|
||||
if (typeof configSession === "string" && configSession.length > 0) return configSession;
|
||||
return "default";
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the `-c/--continue` flag into a concrete `(session, forceResume)`
|
||||
* pair. When the flag is set we ask `getLatestSession` for the most-recently-
|
||||
* touched saved session and skip the picker; if nothing is on disk we
|
||||
* fall back silently to `fallbackSession` after emitting a single warning
|
||||
* line via `warn`.
|
||||
*
|
||||
* Pure & testable: callers inject the fs lookup. `cli/index.ts` plugs in
|
||||
* `() => listSessions()[0]`; tests pass a deterministic stub.
|
||||
*/
|
||||
export function resolveContinueFlag(
|
||||
flag: boolean | undefined,
|
||||
fallbackSession: string | undefined,
|
||||
getLatestSession: () => { name: string } | undefined,
|
||||
warn: (msg: string) => void = () => {},
|
||||
): { session: string | undefined; forceResume: boolean } {
|
||||
if (!flag) return { session: fallbackSession, forceResume: false };
|
||||
const latest = getLatestSession();
|
||||
if (!latest) {
|
||||
warn("▸ -c/--continue: no saved sessions yet — starting a fresh one.");
|
||||
return { session: fallbackSession, forceResume: false };
|
||||
}
|
||||
return { session: latest.name, forceResume: true };
|
||||
}
|
||||
+2615
-425
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,82 @@
|
||||
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 }) {
|
||||
// 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 backgroundColor="#67e8f9" color="black" bold>
|
||||
{` ▸ ${base}${dir ? ` ${dir}` : ""} `}
|
||||
</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Box>
|
||||
<Text color="#94a3b8">{` ${base}`}</Text>
|
||||
{dir ? <Text dimColor>{` ${dir}`}</Text> : null}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
/**
|
||||
* 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 } from "ink";
|
||||
import React from "react";
|
||||
import type { ChoiceOption } from "../../tools/choice.js";
|
||||
import { ModalCard } from "./ModalCard.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 (
|
||||
<ModalCard accent="#f0abfc" icon="🔀" title="model wants you to pick" subtitle={question}>
|
||||
<Box>
|
||||
<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>
|
||||
</ModalCard>
|
||||
);
|
||||
}
|
||||
|
||||
export const ChoiceConfirm = React.memo(ChoiceConfirmInner);
|
||||
@@ -0,0 +1,214 @@
|
||||
import { Box, Text, useStdout } from "ink";
|
||||
import React, { useMemo, useState } from "react";
|
||||
import { formatEditBlockDiff } from "../../code/diff-preview.js";
|
||||
import type { EditBlock } from "../../code/edit-blocks.js";
|
||||
import { ModalCard } from "./ModalCard.js";
|
||||
import { useKeystroke } from "./keystroke-context.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);
|
||||
|
||||
useKeystroke((ev) => {
|
||||
if (ev.paste) return;
|
||||
const input = ev.input;
|
||||
const key = ev;
|
||||
// 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;
|
||||
|
||||
const subtitleParts = [`-${removed} +${added} lines`];
|
||||
if (showScrollHud) {
|
||||
subtitleParts.push(
|
||||
`viewing ${effectiveScroll + 1}-${effectiveScroll + visibleLines.length}/${totalLines}`,
|
||||
);
|
||||
}
|
||||
return (
|
||||
<ModalCard
|
||||
accent={isNew ? "#86efac" : "#fcd34d"}
|
||||
icon={isNew ? "✚" : "✎"}
|
||||
title={`${tag} ${block.path}`}
|
||||
subtitle={subtitleParts.join(" · ")}
|
||||
>
|
||||
{hiddenAbove > 0 ? (
|
||||
<Text
|
||||
dimColor
|
||||
>{` ↑ ${hiddenAbove} line${hiddenAbove === 1 ? "" : "s"} above (↑/k or PgUp)`}</Text>
|
||||
) : null}
|
||||
<Box flexDirection="column">
|
||||
{visibleLines.map((line, i) => {
|
||||
const trimmed = line.trimStart();
|
||||
const color = trimmed.startsWith("+")
|
||||
? "#4ade80"
|
||||
: trimmed.startsWith("-")
|
||||
? "#f87171"
|
||||
: 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="#67e8f9" bold>
|
||||
y
|
||||
</Text>
|
||||
{"/Enter] apply · ["}
|
||||
<Text color="#67e8f9" bold>
|
||||
n
|
||||
</Text>
|
||||
{"] reject · ["}
|
||||
<Text color="#67e8f9" bold>
|
||||
a
|
||||
</Text>
|
||||
{"] apply rest · ["}
|
||||
<Text color="#67e8f9" bold>
|
||||
A
|
||||
</Text>
|
||||
{"] flip AUTO · ["}
|
||||
<Text color="#67e8f9" bold>
|
||||
↑↓/Space
|
||||
</Text>
|
||||
{"] scroll · [Esc] abort"}
|
||||
</Text>
|
||||
</Box>
|
||||
</ModalCard>
|
||||
);
|
||||
}
|
||||
+655
-139
@@ -1,13 +1,52 @@
|
||||
import { Box, Text } from "ink";
|
||||
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 { COLOR, gradientCells } from "./theme.js";
|
||||
import { useElapsedSeconds, useTick } from "./ticker.js";
|
||||
import { formatDuration, summarizeToolResult } from "./tool-summary.js";
|
||||
|
||||
export type DisplayRole = "user" | "assistant" | "tool" | "system" | "error" | "info" | "warning";
|
||||
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;
|
||||
@@ -18,20 +57,153 @@ 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 };
|
||||
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>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Solid-background pill for tool names. Mirrors the StatsPanel's mode
|
||||
* pills so the visual language stays consistent across the screen:
|
||||
* status (auto/review/plan), tool name, model. Status drives the
|
||||
* background color — yellow for ok/in-flight, red for errors — so a
|
||||
* scrollback full of tool dispatches reads at a glance.
|
||||
*/
|
||||
function ToolPill({ label, status }: { label: string; status: "ok" | "err" }) {
|
||||
const bg = status === "err" ? "red" : "yellow";
|
||||
const symbol = status === "err" ? "✗" : "✓";
|
||||
return (
|
||||
<Text backgroundColor={bg} color="black" bold>
|
||||
{` ${symbol} ${label} `}
|
||||
</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 ›{" "}
|
||||
</Text>
|
||||
<Text>{event.text}</Text>
|
||||
<Box flexDirection="column">
|
||||
{event.leadSeparator ? <TurnSeparator /> : null}
|
||||
<Box>
|
||||
<RoleGlyph glyph={ROLE_GLYPH.user} color="cyan" />
|
||||
<Text>{" "}</Text>
|
||||
<Box
|
||||
flexDirection="column"
|
||||
borderStyle="single"
|
||||
borderTop={false}
|
||||
borderRight={false}
|
||||
borderBottom={false}
|
||||
borderColor={COLOR.user}
|
||||
paddingLeft={1}
|
||||
>
|
||||
<Text>{indentContinuationLines(event.text)}</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -40,73 +212,274 @@ 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>{" "}</Text>
|
||||
<Text backgroundColor={COLOR.assistant} color="black" bold>
|
||||
{` ${event.stats.model.replace(/^deepseek-/, "")} `}
|
||||
</Text>
|
||||
</>
|
||||
) : null}
|
||||
</Box>
|
||||
<Box
|
||||
flexDirection="column"
|
||||
marginTop={1}
|
||||
borderStyle="single"
|
||||
borderTop={false}
|
||||
borderRight={false}
|
||||
borderBottom={false}
|
||||
borderColor={COLOR.assistant}
|
||||
paddingLeft={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={COLOR.accent}>{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") {
|
||||
// `flattenMcpResult` prefixes server-side errors with "ERROR: ".
|
||||
// Render those in red with a ✗ marker so they don't blend into
|
||||
// successful tool output (yellow) — the failure mode is what the
|
||||
// model most likely needs to act on next, and the user needs to
|
||||
// see at a glance.
|
||||
const isError = event.text.startsWith("ERROR:");
|
||||
const color = isError ? "red" : "yellow";
|
||||
const marker = isError ? "✗" : "→";
|
||||
// `edit_file` results get a dedicated diff renderer — colored
|
||||
// line-by-line so `-` removals show red, `+` additions show
|
||||
// green, unchanged context lines dim. Always full, never
|
||||
// truncated: users need to see the whole change to trust
|
||||
// /apply. Other tools keep the 400-char clip + /tool N escape.
|
||||
// `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")) && !isError;
|
||||
(event.toolName === "edit_file" || event.toolName?.endsWith("_edit_file")) &&
|
||||
!isExplicitError;
|
||||
if (isEditFile) {
|
||||
return (
|
||||
<Box flexDirection="column" marginTop={1}>
|
||||
<Box>
|
||||
<ToolPill label={event.toolName ?? "?"} status="ok" />
|
||||
<Text dimColor>{" diff:"}</Text>
|
||||
</Box>
|
||||
<Box
|
||||
flexDirection="column"
|
||||
marginTop={1}
|
||||
borderStyle="single"
|
||||
borderTop={false}
|
||||
borderRight={false}
|
||||
borderBottom={false}
|
||||
borderColor={COLOR.tool}
|
||||
paddingLeft={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 status: "ok" | "err" = summary.isError ? "err" : "ok";
|
||||
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={color}>{`tool<${event.toolName ?? "?"}> ${marker}`}</Text>
|
||||
{isEditFile ? (
|
||||
<EditFileDiff text={event.text} />
|
||||
) : (
|
||||
<Text color={isError ? "red" : undefined} dimColor={!isError}>
|
||||
{" "}
|
||||
{truncate(event.text, 400)}
|
||||
</Text>
|
||||
)}
|
||||
<Box>
|
||||
<ToolPill label={event.toolName ?? "?"} status={status} />
|
||||
{durationLabel ? <Text dimColor>{` ${durationLabel}`}</Text> : null}
|
||||
<Text dimColor>{" "}</Text>
|
||||
<Text color={status === "err" ? "red" : undefined} dimColor={status === "ok"}>
|
||||
{summary.summary}
|
||||
</Text>
|
||||
{indexHint ? <Text dimColor>{indexHint}</Text> : null}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
if (event.role === "error") {
|
||||
return (
|
||||
<Box marginTop={1}>
|
||||
<Text color="red" bold>
|
||||
error{" "}
|
||||
<Text backgroundColor="#f87171" color="black" bold>
|
||||
{" ✦ ERROR "}
|
||||
</Text>
|
||||
<Text color="red">{event.text}</Text>
|
||||
<Text>{" "}</Text>
|
||||
<Text color="#f87171">{indentContinuationLines(event.text)}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
if (event.role === "info") {
|
||||
// Detect tone from the text so the info row carries semantic
|
||||
// weight: ▲/⚠ → warn, ✓ → ok, ✗/✖ → error, ↻ → reload, otherwise
|
||||
// a neutral ▸. The leading glyph (if any) is consumed and the
|
||||
// body renders dim.
|
||||
const m = event.text.match(/^([▸▶▲⚠✓✗✖↻ⓘ])\s*(.*)$/s);
|
||||
const lead = m?.[1] ?? "▸";
|
||||
const body = m?.[2] ?? event.text;
|
||||
let leadColor: string = COLOR.info;
|
||||
if (lead === "▲" || lead === "⚠") leadColor = COLOR.warn;
|
||||
else if (lead === "✓") leadColor = COLOR.ok;
|
||||
else if (lead === "✗" || lead === "✖") leadColor = COLOR.err;
|
||||
else if (lead === "↻") leadColor = COLOR.primary;
|
||||
return (
|
||||
<Box>
|
||||
<Text dimColor>{event.text}</Text>
|
||||
<Text color={leadColor} bold>
|
||||
{lead}
|
||||
</Text>
|
||||
<Text> </Text>
|
||||
<Text dimColor>{body}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
if (event.role === "plan") {
|
||||
return (
|
||||
<Box flexDirection="column" 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 backgroundColor="#4ade80" color="black" bold>
|
||||
{" ✓ STEP "}
|
||||
</Text>
|
||||
{counter ? (
|
||||
<>
|
||||
<Text>{" "}</Text>
|
||||
<Text color="#4ade80" bold>
|
||||
{counter}
|
||||
</Text>
|
||||
</>
|
||||
) : null}
|
||||
<Text>{" "}</Text>
|
||||
<Text color="#86efac">{label}</Text>
|
||||
</Box>
|
||||
{event.text ? (
|
||||
<Box paddingLeft={2}>
|
||||
<Text dimColor>{event.text}</Text>
|
||||
</Box>
|
||||
) : null}
|
||||
{sp?.notes ? (
|
||||
<Box paddingLeft={2}>
|
||||
<Text color="#fbbf24" 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.
|
||||
const nextStep = rp.steps.find((s) => !completedSet.has(s.id));
|
||||
return (
|
||||
<Box flexDirection="column" paddingX={1} marginY={1}>
|
||||
<Box>
|
||||
<Text backgroundColor="#67e8f9" color="black" bold>
|
||||
{" ↻ RESUMED PLAN "}
|
||||
</Text>
|
||||
<Text>{" "}</Text>
|
||||
<Text color="#67e8f9" bold>
|
||||
{`${done}/${total}`}
|
||||
</Text>
|
||||
<Text dimColor>{` done · last touched ${rp.relativeTime}`}</Text>
|
||||
</Box>
|
||||
{rp.summary ? (
|
||||
<Box marginTop={1}>
|
||||
<Text color="#67e8f9">{rp.summary}</Text>
|
||||
</Box>
|
||||
) : null}
|
||||
<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" paddingX={1} marginY={1}>
|
||||
<Box>
|
||||
<Text backgroundColor="#94a3b8" color="black" bold>
|
||||
{" ⏪ REPLAY "}
|
||||
</Text>
|
||||
<Text>{" "}</Text>
|
||||
<Text color="#94a3b8" bold>
|
||||
{`${done}/${total}`}
|
||||
</Text>
|
||||
<Text dimColor>{` done · ${r.relativeTime}${navHint}`}</Text>
|
||||
</Box>
|
||||
{r.summary ? (
|
||||
<Box marginTop={1}>
|
||||
<Text color="#94a3b8">{r.summary}</Text>
|
||||
</Box>
|
||||
) : null}
|
||||
<Box>
|
||||
<Text dimColor>{r.archiveBasename}</Text>
|
||||
</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>
|
||||
<Text color="yellow">▸ </Text>
|
||||
<Text color="yellow">{event.text}</Text>
|
||||
<Text backgroundColor="#fbbf24" color="black" bold>
|
||||
{" ▲ WARN "}
|
||||
</Text>
|
||||
<Text>{" "}</Text>
|
||||
<Text color="#fbbf24">{indentContinuationLines(event.text)}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -117,6 +490,43 @@ export const EventRow = React.memo(function EventRow({ event }: { event: Display
|
||||
);
|
||||
});
|
||||
|
||||
/**
|
||||
* Decorative gradient rule between turns. Uses the brand gradient
|
||||
* (teal → fuchsia) so the boundary between "old turn" and "new
|
||||
* turn" reads as a designed accent rather than a dim minus-sign
|
||||
* row. Static — past separators live inside Ink's `<Static>`, so
|
||||
* animation would freeze at tick=0 anyway.
|
||||
*/
|
||||
function TurnSeparator() {
|
||||
const { stdout } = useStdout();
|
||||
const cols = stdout?.columns ?? 80;
|
||||
const width = Math.max(16, cols - 2);
|
||||
// Reserve 5 cells for ` ◆ ` in the middle. Split the remainder
|
||||
// into two gradient halves so the brand mark sits on the seam.
|
||||
const sideWidth = Math.max(2, Math.floor((width - 5) / 2));
|
||||
const leftCells = gradientCells(sideWidth, "─");
|
||||
const rightCells = gradientCells(sideWidth, "─");
|
||||
return (
|
||||
<Box marginTop={1} marginBottom={1}>
|
||||
{leftCells.map((c, i) => (
|
||||
// biome-ignore lint/suspicious/noArrayIndexKey: fixed-width gradient row
|
||||
<Text key={`tsep-l-${i}`} color={c.color}>
|
||||
{c.ch}
|
||||
</Text>
|
||||
))}
|
||||
<Text color={COLOR.brand} bold>
|
||||
{" ◆ "}
|
||||
</Text>
|
||||
{rightCells.map((c, i) => (
|
||||
// biome-ignore lint/suspicious/noArrayIndexKey: fixed-width gradient row
|
||||
<Text key={`tsep-r-${i}`} color={c.color}>
|
||||
{c.ch}
|
||||
</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)"),
|
||||
@@ -130,42 +540,57 @@ 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.
|
||||
// the colored diff body. The hunk header gets a magenta-bg pill —
|
||||
// same idiom as the rest of the TUI — so it visually anchors each
|
||||
// hunk. Body lines render with a colored gutter glyph + tinted bg
|
||||
// for + and -, so the diff scans like a syntax-highlighted patch
|
||||
// file rather than a wall of monochrome text.
|
||||
const [statusHeader, hunkHeader, ...body] = lines;
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
<Text dimColor>{` ${statusHeader ?? ""}`}</Text>
|
||||
{hunkHeader !== undefined ? (
|
||||
<Text color="cyan" bold>
|
||||
{hunkHeader}
|
||||
</Text>
|
||||
<Box marginTop={1}>
|
||||
<Text backgroundColor="#c4b5fd" color="black" bold>
|
||||
{` ${hunkHeader.trim()} `}
|
||||
</Text>
|
||||
</Box>
|
||||
) : 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("- ")) {
|
||||
// Strip the leading " " indent diff-preview adds to every
|
||||
// body line so the gutter glyph is column 0 regardless of
|
||||
// formatter changes upstream.
|
||||
const stripped = line.replace(/^ {2}/, "");
|
||||
if (stripped.startsWith("- ")) {
|
||||
return (
|
||||
<Text key={key} color="red">
|
||||
{line}
|
||||
</Text>
|
||||
<Box key={key}>
|
||||
<Text color="#f87171" bold>
|
||||
{"− "}
|
||||
</Text>
|
||||
<Text color="#fca5a5">{stripped.slice(2)}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
if (line.startsWith("+ ")) {
|
||||
if (stripped.startsWith("+ ")) {
|
||||
return (
|
||||
<Text key={key} color="green">
|
||||
{line}
|
||||
</Text>
|
||||
<Box key={key}>
|
||||
<Text color="#4ade80" bold>
|
||||
{"+ "}
|
||||
</Text>
|
||||
<Text color="#86efac">{stripped.slice(2)}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
// Context line (starts with " ") or unknown — dim.
|
||||
// Context line (starts with " ") or unknown — dim.
|
||||
return (
|
||||
<Text key={key} dimColor>
|
||||
{line}
|
||||
</Text>
|
||||
<Box key={key}>
|
||||
<Text dimColor>{" "}</Text>
|
||||
<Text dimColor>{stripped}</Text>
|
||||
</Box>
|
||||
);
|
||||
})}
|
||||
</Box>
|
||||
@@ -173,21 +598,36 @@ function EditFileDiff({ text }: { text: string }) {
|
||||
}
|
||||
|
||||
function BranchBlock({ branch }: { branch: BranchSummary }) {
|
||||
const per = branch.uncertainties
|
||||
.map((u, i) => {
|
||||
const marker = i === branch.chosenIndex ? "▸" : " ";
|
||||
const t = (branch.temperatures[i] ?? 0).toFixed(1);
|
||||
return `${marker} #${i} T=${t} u=${u}`;
|
||||
})
|
||||
.join(" ");
|
||||
return (
|
||||
<Box>
|
||||
<Text color="blue">
|
||||
{"🔀 branched "}
|
||||
<Text bold>{branch.budget}</Text>
|
||||
{` samples → picked #${branch.chosenIndex} `}
|
||||
<Text dimColor>{per}</Text>
|
||||
</Text>
|
||||
<Box flexDirection="column" marginBottom={1}>
|
||||
<Box>
|
||||
<Text backgroundColor="#93c5fd" color="black" bold>
|
||||
{` ⎇ BRANCH ×${branch.budget} `}
|
||||
</Text>
|
||||
<Text>{" "}</Text>
|
||||
<Text color="#93c5fd">picked </Text>
|
||||
<Text color="#93c5fd" bold>
|
||||
#{branch.chosenIndex}
|
||||
</Text>
|
||||
</Box>
|
||||
<Box paddingLeft={2} marginTop={1}>
|
||||
{branch.uncertainties.map((u, i) => {
|
||||
const chosen = i === branch.chosenIndex;
|
||||
const t = (branch.temperatures[i] ?? 0).toFixed(1);
|
||||
return (
|
||||
// biome-ignore lint/suspicious/noArrayIndexKey: branch index is positional and stable
|
||||
<Text key={`b-${i}`}>
|
||||
<Text color={chosen ? "#93c5fd" : "#475569"} bold={chosen}>
|
||||
{chosen ? "▸ " : " "}
|
||||
</Text>
|
||||
<Text color={chosen ? "#93c5fd" : "#94a3b8"} bold={chosen}>
|
||||
{`#${i}`}
|
||||
</Text>
|
||||
<Text dimColor>{` T=${t} u=${u} `}</Text>
|
||||
</Text>
|
||||
);
|
||||
})}
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -204,8 +644,11 @@ function ReasoningBlock({ reasoning }: { reasoning: string }) {
|
||||
flat.length <= max ? flat : `… (+${flat.length - max} earlier chars) ${flat.slice(-max)}`;
|
||||
return (
|
||||
<Box marginBottom={1}>
|
||||
<Text dimColor italic>
|
||||
{"↳ thinking: "}
|
||||
<Text backgroundColor={COLOR.accent} color="black" bold>
|
||||
{" ⋯ thinking "}
|
||||
</Text>
|
||||
<Text> </Text>
|
||||
<Text color={COLOR.accent} italic dimColor>
|
||||
{preview}
|
||||
</Text>
|
||||
</Box>
|
||||
@@ -224,6 +667,22 @@ function Elapsed() {
|
||||
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;
|
||||
@@ -232,15 +691,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>
|
||||
);
|
||||
}
|
||||
@@ -248,11 +709,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>
|
||||
@@ -286,61 +749,85 @@ function StreamingAssistant({ event }: { event: DisplayEvent }) {
|
||||
const preFirstByte = !event.text && !event.reasoning && !toolCallBuild;
|
||||
const reasoningOnly = !event.text && !!event.reasoning && !toolCallBuild;
|
||||
const toolCallOnly = !event.text && !event.reasoning && !!toolCallBuild;
|
||||
// Phase pill — solid bg color per phase so the user reads
|
||||
// "what's happening" at a glance from across the screen.
|
||||
let pillBg: string;
|
||||
let pillText: string;
|
||||
let label: string;
|
||||
let labelColor: "yellow" | "cyan" | "green" | "magenta" | undefined;
|
||||
if (preFirstByte) {
|
||||
pillBg = "#fbbf24"; // amber
|
||||
pillText = "WAITING";
|
||||
label = "request sent · waiting for server";
|
||||
labelColor = "yellow";
|
||||
} else if (reasoningOnly) {
|
||||
label = `R1 reasoning · ${event.reasoning?.length ?? 0} chars of thought`;
|
||||
labelColor = "cyan";
|
||||
pillBg = "#c4b5fd"; // violet
|
||||
pillText = "THINKING";
|
||||
label = `${event.reasoning?.length ?? 0} chars of thought`;
|
||||
} else if (toolCallOnly) {
|
||||
label = `assembling tool call <${toolCallBuild.name}> · ${toolCallBuild.chars} chars of arguments`;
|
||||
labelColor = "magenta";
|
||||
pillBg = "#f0abfc"; // fuchsia
|
||||
pillText = "DISPATCH";
|
||||
label = `assembling${formatToolCallIndex(toolCallBuild)} <${toolCallBuild.name}> · ${toolCallBuild.chars} chars${formatReadyTail(toolCallBuild)}`;
|
||||
} else {
|
||||
const parts: string[] = [`writing response · ${event.text.length} chars`];
|
||||
if (event.reasoning) parts.push(`after ${event.reasoning.length} chars of reasoning`);
|
||||
pillBg = "#86efac"; // green
|
||||
pillText = "WRITING";
|
||||
const parts: string[] = [`${event.text.length} chars`];
|
||||
if (event.reasoning) parts.push(`after ${event.reasoning.length} reasoning`);
|
||||
if (toolCallBuild) {
|
||||
parts.push(`building tool call <${toolCallBuild.name}> · ${toolCallBuild.chars} chars`);
|
||||
parts.push(
|
||||
`tool${formatToolCallIndex(toolCallBuild)} <${toolCallBuild.name}> ${toolCallBuild.chars}c${formatReadyTail(toolCallBuild)}`,
|
||||
);
|
||||
}
|
||||
label = parts.join(" · ");
|
||||
labelColor = "green";
|
||||
}
|
||||
return (
|
||||
<Box flexDirection="column" marginTop={1}>
|
||||
<Box>
|
||||
<Text bold color="green">
|
||||
assistant{" "}
|
||||
</Text>
|
||||
<PulsingAssistantGlyph />
|
||||
<Text>{" "}</Text>
|
||||
<Pulse />
|
||||
<Text color={labelColor}>{` ${label} `}</Text>
|
||||
<Text> </Text>
|
||||
<Text backgroundColor={pillBg} color="black" bold>
|
||||
{` ${pillText} `}
|
||||
</Text>
|
||||
<Text dimColor>{` ${label} `}</Text>
|
||||
<Elapsed />
|
||||
</Box>
|
||||
{reasoningTail ? (
|
||||
<Text dimColor italic>
|
||||
↳ thinking: {reasoningTail}
|
||||
</Text>
|
||||
<Box paddingLeft={3}>
|
||||
<Text color="#c4b5fd" italic dimColor>
|
||||
↳ {reasoningTail}
|
||||
</Text>
|
||||
</Box>
|
||||
) : null}
|
||||
{tail ? (
|
||||
<Text dimColor>▸ {tail}</Text>
|
||||
<Box paddingLeft={3}>
|
||||
<Text dimColor>▸ {tail}</Text>
|
||||
</Box>
|
||||
) : preFirstByte ? (
|
||||
<Text dimColor italic>
|
||||
{" connection open, first byte typically in 5-60s depending on model + load"}
|
||||
</Text>
|
||||
// Non-dim amber: first-time users misread the dim version as
|
||||
// "app frozen". The reassurance has to be VISIBLE to do its job.
|
||||
<Box paddingLeft={3}>
|
||||
<Text color="#fbbf24" italic>
|
||||
{"waiting for first byte — typical 5–60s depending on model + load"}
|
||||
</Text>
|
||||
</Box>
|
||||
) : reasoningOnly ? (
|
||||
<Text color="yellow" dimColor>
|
||||
{
|
||||
" R1 is thinking before it speaks — body text starts when reasoning completes (typically 20-90s)."
|
||||
}
|
||||
</Text>
|
||||
<Box paddingLeft={3}>
|
||||
<Text color="#c4b5fd" italic>
|
||||
{"R1 thinks before it speaks — body text arrives when reasoning finishes (20–90s)"}
|
||||
</Text>
|
||||
</Box>
|
||||
) : toolCallOnly ? (
|
||||
<Text color="magenta" dimColor>
|
||||
{" tool-call arguments streaming — the model is about to dispatch a tool"}
|
||||
</Text>
|
||||
<Box paddingLeft={3}>
|
||||
<Text color="#f0abfc" italic>
|
||||
{"tool-call arguments streaming — about to dispatch"}
|
||||
</Text>
|
||||
</Box>
|
||||
) : event.reasoning ? (
|
||||
<Text color="yellow" dimColor>
|
||||
{" R1 still reasoning — body text or tool call arrives when thinking completes"}
|
||||
</Text>
|
||||
<Box paddingLeft={3}>
|
||||
<Text color="#fbbf24" italic>
|
||||
{"R1 still reasoning — body text or tool call arrives when thinking finishes"}
|
||||
</Text>
|
||||
</Box>
|
||||
) : null}
|
||||
</Box>
|
||||
);
|
||||
@@ -358,6 +845,29 @@ function Pulse() {
|
||||
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 "";
|
||||
@@ -366,20 +876,26 @@ function lastLine(s: string, maxChars: number): string {
|
||||
|
||||
function StatsLine({ stats }: { stats: TurnStats }) {
|
||||
const hit = (stats.cacheHitRatio * 100).toFixed(1);
|
||||
const hitColor =
|
||||
stats.cacheHitRatio >= 0.7 ? "#4ade80" : stats.cacheHitRatio >= 0.4 ? "#fcd34d" : "#f87171";
|
||||
return (
|
||||
<Text dimColor>
|
||||
{" ↳ cache "}
|
||||
{hit}
|
||||
{"% · tokens "}
|
||||
{stats.usage.promptTokens}
|
||||
{"→"}
|
||||
{stats.usage.completionTokens}
|
||||
{" · $"}
|
||||
{stats.cost.toFixed(6)}
|
||||
</Text>
|
||||
<Box marginTop={1}>
|
||||
<Text color={hitColor} bold>
|
||||
{`⌬ ${hit}%`}
|
||||
</Text>
|
||||
<Text dimColor>{" · "}</Text>
|
||||
<Text color="#94a3b8">
|
||||
{"in "}
|
||||
<Text color="#67e8f9" bold>
|
||||
{stats.usage.promptTokens}
|
||||
</Text>
|
||||
{" → out "}
|
||||
<Text color="#c4b5fd" bold>
|
||||
{stats.usage.completionTokens}
|
||||
</Text>
|
||||
</Text>
|
||||
<Text dimColor>{" · "}</Text>
|
||||
<Text color="#86efac" bold>{`$${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,335 @@
|
||||
import { Box, Text, useStdout } from "ink";
|
||||
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React as a runtime value (classic transform)
|
||||
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} paddingX={1}>
|
||||
<Text color="#c4b5fd" bold>
|
||||
{SPINNER_FRAMES[tick % SPINNER_FRAMES.length]}
|
||||
</Text>
|
||||
<Text>{" "}</Text>
|
||||
<Text color="#c4b5fd">{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;
|
||||
// The same mode pill is already in the StatsPanel header — here we
|
||||
// skip the pill and keep just a tight inline hint right above the
|
||||
// input so the user has the actionable bit (what y/n/u/Shift+Tab
|
||||
// do) without the whole tutorial.
|
||||
if (planMode) {
|
||||
return (
|
||||
<ModeBarFrame>
|
||||
<ModePill label="PLAN MODE" bg="red" flash={flash} />
|
||||
<Text dimColor>{" writes gated · /plan off to leave"}</Text>
|
||||
{jobsTag}
|
||||
</ModeBarFrame>
|
||||
);
|
||||
}
|
||||
const label = editMode === "yolo" ? "YOLO" : editMode === "auto" ? "AUTO" : "REVIEW";
|
||||
const bg = editMode === "yolo" ? "red" : editMode === "auto" ? "magenta" : "cyan";
|
||||
const mid =
|
||||
editMode === "yolo"
|
||||
? "edits + shell auto · /undo to roll back"
|
||||
: editMode === "auto"
|
||||
? "edits land now · u to undo"
|
||||
: pendingCount > 0
|
||||
? `${pendingCount} queued · y apply · n discard`
|
||||
: "edits queued · y apply · n discard";
|
||||
return (
|
||||
<ModeBarFrame>
|
||||
<ModePill label={label} bg={bg} flash={flash} />
|
||||
<Text dimColor>{` ${mid} · Shift+Tab to flip`}</Text>
|
||||
{jobsTag}
|
||||
</ModeBarFrame>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps the bottom mode/jobs row in a dim top rule + side padding
|
||||
* so the modeline reads as its own zone, separate from the prompt
|
||||
* input above. Keeps the live region border-free (the rule is a
|
||||
* single Text row, not a bordered Box) so Ink's eraseLines miscount
|
||||
* stays out of it.
|
||||
*/
|
||||
function ModeBarFrame({ children }: { children: React.ReactNode }) {
|
||||
const { stdout } = useStdout();
|
||||
const cols = stdout?.columns ?? 80;
|
||||
const ruleWidth = Math.max(20, cols - 2);
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
<Box paddingX={1}>
|
||||
<Text color="#475569" dimColor>
|
||||
{"╌".repeat(ruleWidth)}
|
||||
</Text>
|
||||
</Box>
|
||||
<Box paddingX={1}>{children}</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Solid-background mode badge so the bottom status bar reads at a
|
||||
* glance like a real editor's modeline (vim/helix style) instead of a
|
||||
* dim text label that blends into the prompt above. `flash` inverts
|
||||
* briefly after a mode flip — the existing modeFlash signal — for a
|
||||
* "yes, it changed" acknowledgement.
|
||||
*/
|
||||
function ModePill({
|
||||
label,
|
||||
bg,
|
||||
flash,
|
||||
}: {
|
||||
label: string;
|
||||
bg: "magenta" | "cyan" | "red";
|
||||
flash: boolean;
|
||||
}) {
|
||||
return (
|
||||
<Text backgroundColor={bg} color="white" bold inverse={flash}>
|
||||
{` ${label} `}
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* "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;
|
||||
const urgent = remainingSec <= 1;
|
||||
return (
|
||||
<Box marginY={1} paddingX={1}>
|
||||
<Text backgroundColor="#c4b5fd" color="black" bold>
|
||||
{` ✓ AUTO-APPLIED ${ok}/${total} `}
|
||||
</Text>
|
||||
<Text dimColor>{" press "}</Text>
|
||||
<Text backgroundColor="#67e8f9" color="black" bold>
|
||||
{" u "}
|
||||
</Text>
|
||||
<Text dimColor>{" to undo "}</Text>
|
||||
<Text color={urgent ? "#f87171" : "#c4b5fd"} bold={urgent}>
|
||||
{`${remainingSec}s`}
|
||||
</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={3}>
|
||||
<Text color="#c4b5fd" bold>
|
||||
{SPINNER_FRAMES[tick % SPINNER_FRAMES.length]}
|
||||
</Text>
|
||||
<Text>{" "}</Text>
|
||||
<Text backgroundColor="#c4b5fd" color="black" bold>
|
||||
{" ⌬ subagent "}
|
||||
</Text>
|
||||
<Text color="#c4b5fd">{` ${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" paddingX={1}>
|
||||
<Box>
|
||||
<Text color="#fcd34d" bold>
|
||||
{SPINNER_FRAMES[tick % SPINNER_FRAMES.length]}
|
||||
</Text>
|
||||
<Text>{" "}</Text>
|
||||
<Text backgroundColor="#fcd34d" color="black" bold>
|
||||
{` ⏵ ${tool.name} `}
|
||||
</Text>
|
||||
<Text color="#fcd34d">{" running"}</Text>
|
||||
<Text dimColor>{` · ${elapsed}s`}</Text>
|
||||
</Box>
|
||||
{progress ? (
|
||||
<Box paddingLeft={3}>
|
||||
<Text color="#67e8f9">{renderProgressLine(progress)}</Text>
|
||||
</Box>
|
||||
) : null}
|
||||
{summary ? (
|
||||
<Box paddingLeft={3}>
|
||||
<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,70 @@
|
||||
/**
|
||||
* Shared visual frame for confirmation modals (ChoiceConfirm,
|
||||
* PlanConfirm, ShellConfirm, EditConfirm, PlanCheckpointConfirm,
|
||||
* PlanReviseConfirm). Each modal opens inside the live region — so
|
||||
* we keep the frame to plain Text rules and bg-pill headers, no
|
||||
* Ink `borderStyle` (that's the eraseLines miscount class of bug).
|
||||
*
|
||||
* Layout:
|
||||
*
|
||||
* ▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
|
||||
* [ ICON TITLE ] optional subtitle
|
||||
*
|
||||
* <children — body of the modal>
|
||||
*
|
||||
* ▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁
|
||||
*
|
||||
* Color drives the accent (top + bottom rules + title pill bg)
|
||||
* so the user learns to recognize "magenta = choice", "cyan =
|
||||
* plan", "red = shell", "yellow = edit review" by sight.
|
||||
*/
|
||||
|
||||
import { Box, Text, useStdout } from "ink";
|
||||
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React in value scope
|
||||
import React from "react";
|
||||
|
||||
export interface ModalCardProps {
|
||||
/** Accent color — title pill bg + top/bottom rule color. */
|
||||
accent: string;
|
||||
/** Section title shown in the bg-pill header. */
|
||||
title: string;
|
||||
/** Optional dim subtitle next to the title. */
|
||||
subtitle?: string;
|
||||
/** Optional leading glyph inside the title pill (icon). */
|
||||
icon?: string;
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
export function ModalCard({
|
||||
accent,
|
||||
title,
|
||||
subtitle,
|
||||
icon,
|
||||
children,
|
||||
}: ModalCardProps): React.ReactElement {
|
||||
const { stdout } = useStdout();
|
||||
const cols = stdout?.columns ?? 80;
|
||||
const ruleWidth = Math.min(80, Math.max(28, cols - 4));
|
||||
const titleText = icon ? ` ${icon} ${title} ` : ` ${title} `;
|
||||
return (
|
||||
<Box flexDirection="column" paddingX={1} marginY={1}>
|
||||
<Box>
|
||||
<Text color={accent}>{"▔".repeat(ruleWidth)}</Text>
|
||||
</Box>
|
||||
<Box marginTop={1}>
|
||||
<Text backgroundColor={accent} color="black" bold>
|
||||
{titleText}
|
||||
</Text>
|
||||
{subtitle ? <Text dimColor>{` ${subtitle}`}</Text> : null}
|
||||
</Box>
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
{children}
|
||||
</Box>
|
||||
<Box marginTop={1}>
|
||||
<Text color={accent} dimColor>
|
||||
{"▁".repeat(ruleWidth)}
|
||||
</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
/**
|
||||
* 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 } from "ink";
|
||||
import React from "react";
|
||||
import type { PlanStep } from "../../tools/plan.js";
|
||||
import { ModalCard } from "./ModalCard.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);
|
||||
const subtitle = counter ? `${counter} · ${label}` : label;
|
||||
return (
|
||||
<ModalCard accent="#86efac" icon="✓" title="checkpoint — step done" subtitle={subtitle}>
|
||||
{steps && steps.length > 0 ? (
|
||||
<Box marginBottom={1} flexDirection="column">
|
||||
<PlanStepList steps={steps} statuses={statuses} focusStepId={stepId} />
|
||||
</Box>
|
||||
) : null}
|
||||
<SingleSelect
|
||||
initialValue={isLast ? "stop" : "continue"}
|
||||
items={[
|
||||
{
|
||||
value: "continue",
|
||||
label: "Continue — run the next step",
|
||||
hint: "Model resumes with the next step. 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"
|
||||
/>
|
||||
</ModalCard>
|
||||
);
|
||||
}
|
||||
|
||||
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,100 @@
|
||||
/**
|
||||
* 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 { ModalCard } from "./ModalCard.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 (
|
||||
<ModalCard
|
||||
accent="#67e8f9"
|
||||
icon="📋"
|
||||
title="plan proposed"
|
||||
subtitle={summary ?? "approve / refine / cancel"}
|
||||
>
|
||||
{hasOpenQuestions ? (
|
||||
<Box marginBottom={1}>
|
||||
<Text color="#fbbf24">
|
||||
▲ 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 marginBottom={1} flexDirection="column">
|
||||
<PlanStepList steps={steps} />
|
||||
</Box>
|
||||
) : null}
|
||||
<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"
|
||||
/>
|
||||
</ModalCard>
|
||||
);
|
||||
}
|
||||
|
||||
// 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,133 @@
|
||||
/**
|
||||
* 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 } from "ink";
|
||||
import React, { useState } from "react";
|
||||
import { ModalCard } from "./ModalCard.js";
|
||||
import { useKeystroke } from "./keystroke-context.js";
|
||||
import { useTick } from "./ticker.js";
|
||||
|
||||
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("");
|
||||
|
||||
useKeystroke((ev) => {
|
||||
if (ev.paste) {
|
||||
// Insert paste content as-is. Multi-line pastes flatten via
|
||||
// newlines becoming spaces because this is a single-line input.
|
||||
setValue((v) => v + ev.input.replace(/\r?\n/g, " "));
|
||||
return;
|
||||
}
|
||||
if (ev.escape) {
|
||||
onCancel();
|
||||
return;
|
||||
}
|
||||
if (ev.return) {
|
||||
onSubmit(value.trim());
|
||||
return;
|
||||
}
|
||||
if (ev.backspace || ev.delete) {
|
||||
setValue((v) => v.slice(0, -1));
|
||||
return;
|
||||
}
|
||||
// Filter out non-printable chars; accept ordinary text + CJK.
|
||||
if (ev.input && !ev.ctrl && !ev.meta) {
|
||||
setValue((v) => v + ev.input);
|
||||
}
|
||||
});
|
||||
|
||||
const tick = useTick();
|
||||
// Slow blink for the cursor block (~480 ms on/off). Same cadence
|
||||
// as the wordmark's brand-mark pulse; reads as "input is alive".
|
||||
const cursorOn = Math.floor(tick / 4) % 2 === 0;
|
||||
|
||||
const meta =
|
||||
mode === "approve"
|
||||
? {
|
||||
title: "approving — any last instructions?",
|
||||
icon: "📋",
|
||||
accent: "#67e8f9",
|
||||
}
|
||||
: mode === "checkpoint-revise"
|
||||
? {
|
||||
title: "revising — what should change before the next step?",
|
||||
icon: "✏",
|
||||
accent: "#fbbf24",
|
||||
}
|
||||
: mode === "choice-custom"
|
||||
? {
|
||||
title: "custom answer — type whatever fits",
|
||||
icon: "🔀",
|
||||
accent: "#f0abfc",
|
||||
}
|
||||
: {
|
||||
title: "refining — what should the model change?",
|
||||
icon: "✏",
|
||||
accent: "#fbbf24",
|
||||
};
|
||||
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 adjusts the remaining plan."
|
||||
: 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 (
|
||||
<ModalCard accent={meta.accent} icon={meta.icon} title={meta.title}>
|
||||
<Box marginBottom={1}>
|
||||
<Text dimColor>
|
||||
{hint} Enter to send · Esc to return to the picker.
|
||||
{value === "" ? blankHint : ""}
|
||||
</Text>
|
||||
</Box>
|
||||
<Box>
|
||||
<Text color={meta.accent} bold>
|
||||
{"› "}
|
||||
</Text>
|
||||
<Text>{value}</Text>
|
||||
<Text color={meta.accent} bold>
|
||||
{cursorOn ? "▍" : " "}
|
||||
</Text>
|
||||
</Box>
|
||||
</ModalCard>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
/**
|
||||
* 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 { ModalCard } from "./ModalCard.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: string } {
|
||||
switch (risk) {
|
||||
case "high":
|
||||
return { dots: "●●●", color: "#f87171" };
|
||||
case "med":
|
||||
return { dots: "●● ", color: "#fbbf24" };
|
||||
case "low":
|
||||
return { dots: "● ", color: "#4ade80" };
|
||||
default:
|
||||
return { dots: " ", color: "#94a3b8" };
|
||||
}
|
||||
}
|
||||
|
||||
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 (
|
||||
<ModalCard
|
||||
accent="#fbbf24"
|
||||
icon="✏"
|
||||
title="plan revision proposed"
|
||||
subtitle={`−${removedCount} +${addedCount} · ${keptCount} kept`}
|
||||
>
|
||||
<Box marginBottom={1}>
|
||||
<Text>{reason}</Text>
|
||||
</Box>
|
||||
{summary ? (
|
||||
<Box marginBottom={1}>
|
||||
<Text dimColor>{`updated summary: ${summary}`}</Text>
|
||||
</Box>
|
||||
) : null}
|
||||
<Box marginBottom={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" ? "#f87171" : row.kind === "added" ? "#4ade80" : "#94a3b8";
|
||||
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>
|
||||
<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"
|
||||
/>
|
||||
</ModalCard>
|
||||
);
|
||||
}
|
||||
|
||||
export const PlanReviseConfirm = React.memo(PlanReviseConfirmInner);
|
||||
@@ -18,30 +18,29 @@ import { Box, Text } from "ink";
|
||||
import React from "react";
|
||||
import type { TypedPlanState } from "../../harvest.js";
|
||||
|
||||
type FieldColor = "cyan" | "green" | "yellow" | "red";
|
||||
type FieldColor = string;
|
||||
|
||||
export function PlanStateBlock({ planState }: { planState: TypedPlanState }) {
|
||||
const fields: Array<[string, string[], FieldColor, boolean]> = [];
|
||||
if (planState.subgoals.length) fields.push(["subgoals", planState.subgoals, "cyan", false]);
|
||||
if (planState.subgoals.length) fields.push(["subgoals", planState.subgoals, "#67e8f9", false]);
|
||||
if (planState.hypotheses.length)
|
||||
fields.push(["hypotheses", planState.hypotheses, "green", false]);
|
||||
fields.push(["hypotheses", planState.hypotheses, "#86efac", false]);
|
||||
if (planState.uncertainties.length)
|
||||
fields.push(["uncertainties", planState.uncertainties, "yellow", false]);
|
||||
fields.push(["uncertainties", planState.uncertainties, "#fcd34d", false]);
|
||||
if (planState.rejectedPaths.length)
|
||||
fields.push(["rejected", planState.rejectedPaths, "red", true]);
|
||||
fields.push(["rejected", planState.rejectedPaths, "#94a3b8", 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}
|
||||
<Box key={label}>
|
||||
<Text backgroundColor={color} color="black" bold dimColor={dim}>
|
||||
{` ${label} ${items.length} `}
|
||||
</Text>
|
||||
<Text dimColor>{` (${items.length})`}</Text>
|
||||
<Text>{`: ${items.join(" · ")}`}</Text>
|
||||
</Text>
|
||||
<Text>{" "}</Text>
|
||||
<Text dimColor={dim}>{items.join(" · ")}</Text>
|
||||
</Box>
|
||||
))}
|
||||
</Box>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
/**
|
||||
* 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 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;
|
||||
const pct = Math.round((doneCount / steps.length) * 100);
|
||||
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
<Box>
|
||||
<Text dimColor>
|
||||
{`${steps.length} step${steps.length === 1 ? "" : "s"}`}
|
||||
{doneCount > 0 ? ` · ${doneCount}/${steps.length} done (${pct}%)` : ""}
|
||||
{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 titleDim = status === "done" || status === "skipped";
|
||||
return (
|
||||
<Box key={step.id}>
|
||||
<Text color={focus ? "#67e8f9" : "gray"} bold={focus}>
|
||||
{focus ? "▸ " : " "}
|
||||
</Text>
|
||||
<Text color={risk.color} bold>
|
||||
{risk.dots}
|
||||
</Text>
|
||||
<Text> </Text>
|
||||
<StatusBadge status={status} />
|
||||
<Text> </Text>
|
||||
<Text dimColor={titleDim} bold={focus}>
|
||||
{`${step.id} · ${step.title}`}
|
||||
</Text>
|
||||
</Box>
|
||||
);
|
||||
})}
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Status pill — solid-bg badge per step state. Reads at a glance
|
||||
* better than a glyph + color text: ` DONE `, ` RUN `, ` SKIP `,
|
||||
* ` PEND `. The label widths are normalized so the column under
|
||||
* the badge stays aligned even when statuses mix.
|
||||
*/
|
||||
function StatusBadge({ status }: { status: StepStatus }) {
|
||||
switch (status) {
|
||||
case "done":
|
||||
return (
|
||||
<Text backgroundColor="#4ade80" color="black" bold>
|
||||
{" ✓ DONE "}
|
||||
</Text>
|
||||
);
|
||||
case "running":
|
||||
return (
|
||||
<Text backgroundColor="#67e8f9" color="black" bold>
|
||||
{" ▶ RUN "}
|
||||
</Text>
|
||||
);
|
||||
case "skipped":
|
||||
return (
|
||||
<Text backgroundColor="#94a3b8" color="black" bold>
|
||||
{" — SKIP "}
|
||||
</Text>
|
||||
);
|
||||
default:
|
||||
return (
|
||||
<Text color="#94a3b8" dimColor>
|
||||
{" ☐ PEND "}
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
+512
-116
@@ -1,7 +1,52 @@
|
||||
import { Box, Text, useInput } from "ink";
|
||||
import { Box, Text, useStdout } from "ink";
|
||||
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React as a runtime value (classic transform compiles JSX to React.createElement)
|
||||
import React, { useRef, useState } from "react";
|
||||
import { useKeystroke } from "./keystroke-context.js";
|
||||
import { type MultilineKey, lineAndColumn, processMultilineKey } from "./multiline-keys.js";
|
||||
import { useTick } from "./ticker.js";
|
||||
import {
|
||||
PASTE_SENTINEL_RANGE,
|
||||
type PasteEntry,
|
||||
encodePasteSentinel,
|
||||
expandPasteSentinels,
|
||||
listPasteIdsInBuffer,
|
||||
makePasteEntry,
|
||||
} from "./paste-sentinels.js";
|
||||
import { type Segment, buildViewport, stringCells } from "./prompt-viewport.js";
|
||||
import { GRADIENT } from "./theme.js";
|
||||
|
||||
/**
|
||||
* Visual anchor: a left vertical rule (▎ + space) running down every
|
||||
* line of the input. Colored with the accent color so disabled state
|
||||
* dims it; gives the input area a clear "you type here" boundary
|
||||
* without using bordered Boxes (those amplified Ink's eraseLines
|
||||
* miscount on Windows). Length is fixed at 2 so the prefix-cell math
|
||||
* stays trivial.
|
||||
*/
|
||||
const BAR = "▎ ";
|
||||
|
||||
/**
|
||||
* Prompt input v2 — no Ink useInput, no Yoga text wrapping, no
|
||||
* cursor blink. Replaces the bordered-Box / multi-Text approach
|
||||
* that was driving the Windows ghost-row regressions.
|
||||
*
|
||||
* Pipeline:
|
||||
* - Subscribes to the global keystroke bus (which is fed by our
|
||||
* own raw stdin parser, NOT Ink's parse-keypress).
|
||||
* - Pure events: `paste` events go to the paste registry; everything
|
||||
* else flows through `processMultilineKey` (the existing reducer
|
||||
* with all the cursor / submit / history-recall semantics).
|
||||
* - Render: one logical line per <Box> row. Each row renders as
|
||||
* EXACTLY one visual row — content longer than the visible cell
|
||||
* budget is clipped via `buildViewport`, with `‹` / `›` markers
|
||||
* where content is hidden. The cursor moves the viewport so it
|
||||
* stays visible.
|
||||
*
|
||||
* Cursor blinks at ~480 ms half-period. The ticker that drives the
|
||||
* blink also flows the left-bar gradient and the wordmark, so
|
||||
* we're already paying for re-render every tick — the cursor blink
|
||||
* is free on top of that. Disabled state freezes the cursor solid
|
||||
* so the disabled prompt doesn't compete with the active spinner.
|
||||
*/
|
||||
|
||||
export interface PromptInputProps {
|
||||
value: string;
|
||||
@@ -9,156 +54,507 @@ 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;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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,
|
||||
onChange,
|
||||
onSubmit,
|
||||
disabled,
|
||||
placeholder,
|
||||
onHistoryPrev,
|
||||
onHistoryNext,
|
||||
}: PromptInputProps) {
|
||||
const [cursor, setCursor] = useState(value.length);
|
||||
// Tracks the last `value` we ourselves produced via onChange. If the
|
||||
// incoming `value` prop diverges from this, the parent (or some other
|
||||
// source) replaced the buffer — we reset the cursor to end.
|
||||
|
||||
// Paste registry — keyed by sentinel id, holds original content.
|
||||
const pastesRef = useRef<Map<number, PasteEntry>>(new Map());
|
||||
const nextPasteIdRef = useRef<number>(0);
|
||||
|
||||
// Track external value replacement (history recall, slash completion).
|
||||
// When the parent swaps `value` we snap 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);
|
||||
}
|
||||
if (cursor !== value.length) setCursor(value.length);
|
||||
}
|
||||
|
||||
// Shared ticker drives the cursor blink. Dividing the tick by 4 lands
|
||||
// the visible on/off cycle around 480ms — standard cursor cadence.
|
||||
const tick = useTick();
|
||||
const showCursor = disabled ? false : Math.floor(tick / 4) % 2 === 0;
|
||||
/**
|
||||
* Register one paste blob and insert its sentinel at the current
|
||||
* cursor. Used both by `paste` events from the stdin reader (the
|
||||
* normal path on terminals that support DECSET 2004) and by the
|
||||
* fallback path inside `processMultilineKey` for chunks that
|
||||
* arrived without bracketed-paste markers.
|
||||
*/
|
||||
const registerPaste = (content: string) => {
|
||||
const v = lastLocalValueRef.current;
|
||||
const c = cursor;
|
||||
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);
|
||||
lastLocalValueRef.current = next;
|
||||
onChange(next);
|
||||
setCursor(c + 1);
|
||||
};
|
||||
|
||||
useInput(
|
||||
(input, key) => {
|
||||
const ke: MultilineKey = {
|
||||
input,
|
||||
return: key.return,
|
||||
shift: key.shift,
|
||||
ctrl: key.ctrl,
|
||||
meta: key.meta,
|
||||
backspace: key.backspace,
|
||||
delete: key.delete,
|
||||
tab: key.tab,
|
||||
upArrow: key.upArrow,
|
||||
downArrow: key.downArrow,
|
||||
leftArrow: key.leftArrow,
|
||||
rightArrow: key.rightArrow,
|
||||
escape: key.escape,
|
||||
pageUp: key.pageUp,
|
||||
pageDown: key.pageDown,
|
||||
};
|
||||
const action = processMultilineKey(value, cursor, ke);
|
||||
if (action.next !== null) {
|
||||
lastLocalValueRef.current = action.next;
|
||||
onChange(action.next);
|
||||
useKeystroke((ev) => {
|
||||
if (disabled) return;
|
||||
if (ev.paste) {
|
||||
// Bracketed-paste content delivered by the stdin reader.
|
||||
// Insert as one sentinel regardless of length.
|
||||
if (ev.input.length > 0) registerPaste(ev.input);
|
||||
return;
|
||||
}
|
||||
const key: MultilineKey = {
|
||||
input: ev.input,
|
||||
return: ev.return,
|
||||
shift: ev.shift,
|
||||
ctrl: ev.ctrl,
|
||||
meta: ev.meta,
|
||||
backspace: ev.backspace,
|
||||
delete: ev.delete,
|
||||
tab: ev.tab,
|
||||
upArrow: ev.upArrow,
|
||||
downArrow: ev.downArrow,
|
||||
leftArrow: ev.leftArrow,
|
||||
rightArrow: ev.rightArrow,
|
||||
escape: ev.escape,
|
||||
pageUp: ev.pageUp,
|
||||
pageDown: ev.pageDown,
|
||||
};
|
||||
const action = processMultilineKey(value, cursor, key);
|
||||
if (action.pasteRequest) {
|
||||
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) {
|
||||
const raw = action.submitValue ?? value;
|
||||
const expanded = expandPasteSentinels(raw, pastesRef.current);
|
||||
// GC unreachable paste entries — anything 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);
|
||||
}
|
||||
if (action.cursor !== null) {
|
||||
setCursor(action.cursor);
|
||||
}
|
||||
if (action.submit) onSubmit(action.submitValue ?? value);
|
||||
},
|
||||
{ isActive: !disabled },
|
||||
);
|
||||
onSubmit(expanded);
|
||||
}
|
||||
if (action.historyHandoff === "prev") onHistoryPrev?.();
|
||||
if (action.historyHandoff === "next") onHistoryNext?.();
|
||||
}, !disabled);
|
||||
|
||||
// ── Render ──────────────────────────────────────────────────────
|
||||
|
||||
const { stdout } = useStdout();
|
||||
const cols = stdout?.columns ?? 80;
|
||||
const narrow = cols <= 90;
|
||||
const promptBody = narrow ? "› " : "you › ";
|
||||
const promptPrefix = BAR + promptBody;
|
||||
const continuationIndent = BAR + " ".repeat(promptBody.length);
|
||||
const prefixCells = promptPrefix.length;
|
||||
// Reserve 2 cells for the surrounding `paddingX={1}` plus 1 cell
|
||||
// for the cursor block when at end-of-line. Net visible budget per
|
||||
// line.
|
||||
const visibleCells = Math.max(8, cols - prefixCells - 3);
|
||||
|
||||
const placeholderActive = narrow
|
||||
? "type a message, or /command"
|
||||
: "type a message, or /command · [Ctrl+J] newline · [Ctrl+P/N] history";
|
||||
const effectivePlaceholder = disabled
|
||||
? (placeholder ?? "…waiting for response…")
|
||||
: (placeholder ?? "type a message, or /command · Ctrl+J for newline");
|
||||
: (placeholder ?? placeholderActive);
|
||||
|
||||
const lines = value.length > 0 ? value.split("\n") : [""];
|
||||
const borderColor = disabled ? "gray" : "cyan";
|
||||
const accentColor = disabled ? "gray" : "cyan";
|
||||
// Static bar + static cursor. Earlier versions flowed the bar
|
||||
// gradient and blinked the cursor via the global ticker; both
|
||||
// drove per-tick re-renders that interleaved badly with terminal
|
||||
// resize (Ink's eraseLines miscounts logical vs visual rows on
|
||||
// wrap, ghost frames stack). The bar still gets a gradient — just
|
||||
// a fixed sweep based on row index, no time component.
|
||||
const barColorAt = (rowIdx: number): string =>
|
||||
disabled ? "gray" : GRADIENT[((rowIdx % GRADIENT.length) + GRADIENT.length) % GRADIENT.length]!;
|
||||
const cursorVisible = true;
|
||||
const { line: cursorLine, col: cursorCol } = lineAndColumn(value, cursor);
|
||||
|
||||
// Big-buffer mitigation: if the buffer has many logical lines,
|
||||
// collapse middle rows so Ink isn't redrawing 500+ rows per
|
||||
// keystroke.
|
||||
const renderItems = collapseLinesForDisplay(lines, cursorLine);
|
||||
const showHugeBufferHints = lines.length > 20;
|
||||
|
||||
return (
|
||||
<Box borderStyle="round" borderColor={borderColor} paddingX={1} flexDirection="column">
|
||||
{lines.map((line, i) => {
|
||||
const isFirst = i === 0;
|
||||
const showPlaceholder = isFirst && value.length === 0;
|
||||
const isCursorLine = i === cursorLine;
|
||||
return (
|
||||
// biome-ignore lint/suspicious/noArrayIndexKey: stable by construction — lines are derived from `value.split("\n")` and never reordered
|
||||
<Box key={i}>
|
||||
{isFirst ? (
|
||||
<Text bold color={borderColor}>
|
||||
you ›{" "}
|
||||
<Box flexDirection="column" paddingX={1}>
|
||||
{renderItems.map((item, renderIdx) => {
|
||||
if (item.kind === "skip") {
|
||||
return (
|
||||
// biome-ignore lint/suspicious/noArrayIndexKey: stable — collapse markers derive from a fixed sliding window
|
||||
<Box key={`skip-${renderIdx}`}>
|
||||
<Text color={barColorAt(renderIdx)}>{BAR}</Text>
|
||||
<Text dimColor>{continuationIndent.slice(BAR.length)}</Text>
|
||||
<Text dimColor>
|
||||
{`[… ${item.linesHidden} line${item.linesHidden === 1 ? "" : "s"} hidden — full content kept, submitted on Enter …]`}
|
||||
</Text>
|
||||
) : (
|
||||
<Text dimColor>{" "}</Text>
|
||||
)}
|
||||
{showPlaceholder ? (
|
||||
<>
|
||||
{isCursorLine && !disabled ? (
|
||||
<Text color={borderColor}>{showCursor ? "▌" : " "}</Text>
|
||||
) : null}
|
||||
<Text dimColor>{effectivePlaceholder}</Text>
|
||||
</>
|
||||
) : isCursorLine && !disabled ? (
|
||||
<LineWithCursor
|
||||
line={line}
|
||||
col={cursorCol}
|
||||
showCursor={showCursor}
|
||||
borderColor={borderColor}
|
||||
/>
|
||||
) : (
|
||||
<Text>{line}</Text>
|
||||
)}
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
const i = item.originalIndex;
|
||||
const line = item.line;
|
||||
const isFirst = i === 0;
|
||||
const isCursorLine = i === cursorLine;
|
||||
const showPlaceholder = isFirst && value.length === 0;
|
||||
return (
|
||||
<PromptLine
|
||||
key={`ln-${i}`}
|
||||
line={line}
|
||||
isFirst={isFirst}
|
||||
isCursorLine={isCursorLine && !disabled}
|
||||
cursorCol={isCursorLine ? cursorCol : null}
|
||||
cursorVisible={cursorVisible}
|
||||
showPlaceholder={showPlaceholder}
|
||||
placeholderText={effectivePlaceholder}
|
||||
promptPrefix={promptPrefix}
|
||||
continuationIndent={continuationIndent}
|
||||
visibleCells={visibleCells}
|
||||
accentColor={accentColor}
|
||||
barColor={barColorAt(i)}
|
||||
pastes={pastesRef.current}
|
||||
disabled={disabled === true}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
{showHugeBufferHints && !disabled ? (
|
||||
<Box>
|
||||
<Text color={barColorAt(0)}>{BAR}</Text>
|
||||
<Text dimColor>{continuationIndent.slice(BAR.length)}</Text>
|
||||
<Text dimColor>
|
||||
{`[${lines.length} lines · PageUp/PageDown jump to top/bottom · Ctrl+U clear · Ctrl+W del word]`}
|
||||
</Text>
|
||||
</Box>
|
||||
) : null}
|
||||
{!disabled && !narrow && value.length > 0 && !value.includes("\n") ? (
|
||||
<Box>
|
||||
<Text color={barColorAt(0)}>{BAR}</Text>
|
||||
<Text dimColor>{continuationIndent.slice(BAR.length)}</Text>
|
||||
<Text dimColor>
|
||||
[Ctrl+J] newline · [Enter] submit · ends with \ for line continuation
|
||||
</Text>
|
||||
</Box>
|
||||
) : null}
|
||||
{disabled ? (
|
||||
<Box>
|
||||
<Text color={barColorAt(0)}>{BAR}</Text>
|
||||
<Text dimColor>{continuationIndent.slice(BAR.length)}</Text>
|
||||
<Text dimColor>[Esc] to stop</Text>
|
||||
</Box>
|
||||
) : null}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
function LineWithCursor({
|
||||
line,
|
||||
col,
|
||||
showCursor,
|
||||
borderColor,
|
||||
}: {
|
||||
// ── PromptLine ────────────────────────────────────────────────────
|
||||
|
||||
interface PromptLineProps {
|
||||
line: string;
|
||||
col: number;
|
||||
showCursor: boolean;
|
||||
borderColor: "cyan" | "gray";
|
||||
}) {
|
||||
const before = line.slice(0, col);
|
||||
const atCursor = line.slice(col, col + 1);
|
||||
const after = line.slice(col + 1);
|
||||
if (atCursor.length === 0) {
|
||||
// Cursor sits past the last char of this line (end-of-line). Render
|
||||
// a trailing block so the user sees where they're typing next.
|
||||
isFirst: boolean;
|
||||
isCursorLine: boolean;
|
||||
cursorCol: number | null;
|
||||
/** True when the cursor block / inverse char should be drawn this tick. */
|
||||
cursorVisible: boolean;
|
||||
showPlaceholder: boolean;
|
||||
placeholderText: string;
|
||||
promptPrefix: string;
|
||||
continuationIndent: string;
|
||||
visibleCells: number;
|
||||
accentColor: "cyan" | "gray";
|
||||
/** Animated gradient color for the leading ▎ bar. Differs per row + tick. */
|
||||
barColor: string;
|
||||
pastes: ReadonlyMap<number, PasteEntry>;
|
||||
disabled: boolean;
|
||||
}
|
||||
|
||||
function PromptLine({
|
||||
line,
|
||||
isFirst,
|
||||
isCursorLine,
|
||||
cursorCol,
|
||||
cursorVisible,
|
||||
showPlaceholder,
|
||||
placeholderText,
|
||||
promptPrefix,
|
||||
continuationIndent,
|
||||
visibleCells,
|
||||
accentColor,
|
||||
barColor,
|
||||
pastes,
|
||||
disabled,
|
||||
}: PromptLineProps) {
|
||||
// The leading BAR cells of every prefix/continuation are the left
|
||||
// anchor bar — render them as a separate span colored by the
|
||||
// animated gradient so the bar appears to flow vertically.
|
||||
const barText = promptPrefix.slice(0, BAR.length);
|
||||
const bodyPrefix = promptPrefix.slice(BAR.length);
|
||||
const bodyContinuation = continuationIndent.slice(BAR.length);
|
||||
if (showPlaceholder) {
|
||||
return (
|
||||
<>
|
||||
<Text>{before}</Text>
|
||||
<Text color={borderColor}>{showCursor ? "▌" : " "}</Text>
|
||||
</>
|
||||
<Box>
|
||||
<Text color={barColor}>{barText}</Text>
|
||||
<Text bold color={accentColor}>
|
||||
{bodyPrefix}
|
||||
</Text>
|
||||
{!disabled ? <Text color={accentColor}>{cursorVisible ? "▌" : " "}</Text> : null}
|
||||
<Text dimColor>{placeholderText}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
const viewport = buildViewport(line, isCursorLine ? cursorCol : null, visibleCells, pastes);
|
||||
|
||||
// Render: prefix + (left marker?) + segments-with-cursor + (right marker?)
|
||||
return (
|
||||
<>
|
||||
<Text>{before}</Text>
|
||||
<Text inverse={showCursor}>{atCursor}</Text>
|
||||
<Text>{after}</Text>
|
||||
</>
|
||||
<Box>
|
||||
<Text color={barColor}>{barText}</Text>
|
||||
{isFirst ? (
|
||||
<Text bold color={accentColor}>
|
||||
{bodyPrefix}
|
||||
</Text>
|
||||
) : (
|
||||
<Text dimColor>{bodyContinuation}</Text>
|
||||
)}
|
||||
{viewport.hiddenLeft ? (
|
||||
<Text color="gray" dimColor>
|
||||
‹
|
||||
</Text>
|
||||
) : null}
|
||||
<ViewportContent
|
||||
segments={viewport.segments}
|
||||
cursorCell={isCursorLine ? viewport.cursorCell : null}
|
||||
accentColor={accentColor}
|
||||
cursorVisible={cursorVisible}
|
||||
/>
|
||||
{viewport.hiddenRight ? (
|
||||
<Text color="gray" dimColor>
|
||||
›
|
||||
</Text>
|
||||
) : null}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
// ── ViewportContent ────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Render a viewport's segments with a cursor block at `cursorCell`.
|
||||
* Walks segments in order; the cursor splits at most one segment
|
||||
* (the one containing the cursor cell), producing an inverted char
|
||||
* at that position.
|
||||
*
|
||||
* End-of-line cursor (cursorCell points past the last cell of the
|
||||
* last segment): emit a trailing block.
|
||||
*/
|
||||
function ViewportContent({
|
||||
segments,
|
||||
cursorCell,
|
||||
accentColor,
|
||||
cursorVisible,
|
||||
}: {
|
||||
segments: Segment[];
|
||||
cursorCell: number | null;
|
||||
accentColor: "cyan" | "gray";
|
||||
cursorVisible: boolean;
|
||||
}) {
|
||||
// No cursor on this line — straight render.
|
||||
if (cursorCell === null) {
|
||||
return <>{segments.map((seg, i) => renderSegment(seg, i, false))}</>;
|
||||
}
|
||||
|
||||
// Walk segments tallying cells; once we reach `cursorCell`, split
|
||||
// the segment to insert the cursor block.
|
||||
const out: React.ReactNode[] = [];
|
||||
let cells = 0;
|
||||
let placed = false;
|
||||
for (let i = 0; i < segments.length; i++) {
|
||||
const seg = segments[i]!;
|
||||
const segCells = segmentCells(seg);
|
||||
if (placed) {
|
||||
out.push(renderSegment(seg, i, false));
|
||||
continue;
|
||||
}
|
||||
if (cursorCell >= cells + segCells) {
|
||||
// Cursor isn't in this segment.
|
||||
out.push(renderSegment(seg, i, false));
|
||||
cells += segCells;
|
||||
continue;
|
||||
}
|
||||
// Cursor lands inside this segment.
|
||||
if (seg.kind === "paste") {
|
||||
// The cursor is "on" the paste sentinel — render the paste
|
||||
// block inversed so the user sees they're at it. Inverse
|
||||
// toggles with the blink so the paste sentinel stays
|
||||
// legible during the cursor's "off" half-cycle.
|
||||
out.push(
|
||||
<Text key={`p-${i}-cursor`} color="magenta" bold inverse={cursorVisible}>
|
||||
{seg.label}
|
||||
</Text>,
|
||||
);
|
||||
placed = true;
|
||||
cells += segCells;
|
||||
continue;
|
||||
}
|
||||
// text segment — split before/at-cursor/after by cell offset.
|
||||
const offsetIntoSeg = cursorCell - cells;
|
||||
const split = splitTextByCells(seg.text, offsetIntoSeg);
|
||||
if (split.before.length > 0) {
|
||||
out.push(<Text key={`t-${i}-b`}>{split.before}</Text>);
|
||||
}
|
||||
if (split.atCursor.length > 0) {
|
||||
out.push(
|
||||
<Text key={`t-${i}-c`} inverse={cursorVisible} color={accentColor}>
|
||||
{split.atCursor}
|
||||
</Text>,
|
||||
);
|
||||
} else {
|
||||
// Cursor sits past the segment's last char (end-of-text in this
|
||||
// segment). Render block here, blinking with the tick.
|
||||
out.push(
|
||||
<Text key={`t-${i}-c-eol`} color={accentColor}>
|
||||
{cursorVisible ? "▌" : " "}
|
||||
</Text>,
|
||||
);
|
||||
}
|
||||
if (split.after.length > 0) {
|
||||
out.push(<Text key={`t-${i}-a`}>{split.after}</Text>);
|
||||
}
|
||||
placed = true;
|
||||
cells += segCells;
|
||||
}
|
||||
|
||||
// Cursor sits past every segment (end of line).
|
||||
if (!placed) {
|
||||
out.push(
|
||||
<Text key="cursor-eol" color={accentColor}>
|
||||
{cursorVisible ? "▌" : " "}
|
||||
</Text>,
|
||||
);
|
||||
}
|
||||
|
||||
return <>{out}</>;
|
||||
}
|
||||
|
||||
function segmentCells(seg: Segment): number {
|
||||
if (seg.kind === "paste") return seg.label.length;
|
||||
return stringCells(seg.text);
|
||||
}
|
||||
|
||||
/**
|
||||
* Split a text string at a cell offset, returning the chars before
|
||||
* the offset, the char AT the offset (the cursor block highlights
|
||||
* it), and the chars after. A wide char that straddles the offset
|
||||
* is treated as the cursor's char.
|
||||
*/
|
||||
function splitTextByCells(
|
||||
text: string,
|
||||
cellOffset: number,
|
||||
): { before: string; atCursor: string; after: string } {
|
||||
let cells = 0;
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
const ch = text[i]!;
|
||||
const cw = charCellsForText(ch);
|
||||
if (cells === cellOffset) {
|
||||
return { before: text.slice(0, i), atCursor: ch, after: text.slice(i + 1) };
|
||||
}
|
||||
if (cells + cw > cellOffset) {
|
||||
// The wide char straddles the offset — show it as the cursor char.
|
||||
return { before: text.slice(0, i), atCursor: ch, after: text.slice(i + 1) };
|
||||
}
|
||||
cells += cw;
|
||||
}
|
||||
// Cursor at end of text.
|
||||
return { before: text, atCursor: "", after: "" };
|
||||
}
|
||||
|
||||
/**
|
||||
* Local cell-counting helper — duplicates `charCells` from
|
||||
* prompt-viewport but inlined to avoid a back-and-forth import (this
|
||||
* function is hot per-keystroke). Keep in sync.
|
||||
*/
|
||||
function charCellsForText(ch: string): number {
|
||||
const code = ch.charCodeAt(0);
|
||||
if (code < 0x20 || code === 0x7f) return 0;
|
||||
if (code < 0x1100) return 1;
|
||||
if (code >= 0x1100 && code <= 0x115f) return 2;
|
||||
if (code >= 0x2e80 && code <= 0x303e) return 2;
|
||||
if (code >= 0x3041 && code <= 0x33ff) return 2;
|
||||
if (code >= 0x3400 && code <= 0x4dbf) return 2;
|
||||
if (code >= 0x4e00 && code <= 0x9fff) return 2;
|
||||
if (code >= 0xa000 && code <= 0xa4cf) return 2;
|
||||
if (code >= 0xac00 && code <= 0xd7a3) return 2;
|
||||
if (code >= 0xf900 && code <= 0xfaff) return 2;
|
||||
if (code >= 0xfe30 && code <= 0xfe4f) return 2;
|
||||
if (code >= 0xff00 && code <= 0xff60) return 2;
|
||||
if (code >= 0xffe0 && code <= 0xffe6) return 2;
|
||||
return 1;
|
||||
}
|
||||
|
||||
function renderSegment(seg: Segment, key: number, _inverse: boolean): React.ReactNode {
|
||||
if (seg.kind === "text") {
|
||||
return <Text key={`s-${key}`}>{seg.text}</Text>;
|
||||
}
|
||||
// Paste sentinels render as a fuchsia bg-pill so they're visually
|
||||
// distinct from typed text — the user can see "this is the
|
||||
// collapsed paste, not 47 lines of code I typed". Matches the
|
||||
// bg-pill idiom used elsewhere (mode bars, tool names).
|
||||
return (
|
||||
<Text key={`s-${key}`} backgroundColor="#f0abfc" color="black" bold>
|
||||
{seg.label}
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
|
||||
// ── collapse helper (preserved from v1) ────────────────────────────
|
||||
|
||||
type RenderItem =
|
||||
| { kind: "line"; line: string; originalIndex: number }
|
||||
| { kind: "skip"; linesHidden: number };
|
||||
|
||||
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 }));
|
||||
}
|
||||
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;
|
||||
}
|
||||
@@ -28,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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -59,6 +59,7 @@ export function ReplayApp({ meta, pages }: ReplayAppProps) {
|
||||
cacheHitRatio: cumStats.cacheHitRatio,
|
||||
// Replay is read-only — no live last-turn prompt tokens to show.
|
||||
lastPromptTokens: 0,
|
||||
lastTurnCostUsd: 0,
|
||||
};
|
||||
|
||||
const prefixHash =
|
||||
|
||||
+29
-13
@@ -9,8 +9,9 @@
|
||||
* rendering quirk bundled (`ink-text-input`); adding more is low value.
|
||||
*/
|
||||
|
||||
import { Box, Text, useInput } from "ink";
|
||||
import { Box, Text } from "ink";
|
||||
import React, { useState } from "react";
|
||||
import { useKeystroke } from "./keystroke-context.js";
|
||||
|
||||
export interface SelectItem<V extends string = string> {
|
||||
/** Stable identifier — returned to caller on submit. */
|
||||
@@ -28,6 +29,13 @@ export interface SingleSelectProps<V extends string> {
|
||||
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>({
|
||||
@@ -35,6 +43,7 @@ export function SingleSelect<V extends string>({
|
||||
initialValue,
|
||||
onSubmit,
|
||||
onCancel,
|
||||
footer,
|
||||
}: SingleSelectProps<V>) {
|
||||
const initialIndex = Math.max(
|
||||
0,
|
||||
@@ -42,15 +51,16 @@ export function SingleSelect<V extends string>({
|
||||
);
|
||||
const [index, setIndex] = useState(initialIndex === -1 ? 0 : initialIndex);
|
||||
|
||||
useInput((_input, key) => {
|
||||
if (key.upArrow) {
|
||||
useKeystroke((ev) => {
|
||||
if (ev.paste) return;
|
||||
if (ev.upArrow) {
|
||||
setIndex((i) => findNextEnabled(items, i, -1));
|
||||
} else if (key.downArrow) {
|
||||
} else if (ev.downArrow) {
|
||||
setIndex((i) => findNextEnabled(items, i, +1));
|
||||
} else if (key.return) {
|
||||
} else if (ev.return) {
|
||||
const chosen = items[index];
|
||||
if (chosen && !chosen.disabled) onSubmit(chosen.value);
|
||||
} else if (key.escape && onCancel) {
|
||||
} else if (ev.escape && onCancel) {
|
||||
onCancel();
|
||||
}
|
||||
});
|
||||
@@ -65,6 +75,11 @@ export function SingleSelect<V extends string>({
|
||||
marker={i === index ? "▸" : " "}
|
||||
/>
|
||||
))}
|
||||
{footer ? (
|
||||
<Box marginTop={1}>
|
||||
<Text dimColor>{footer}</Text>
|
||||
</Box>
|
||||
) : null}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -74,7 +89,7 @@ export interface MultiSelectProps<V extends string> {
|
||||
initialSelected?: V[];
|
||||
onSubmit: (values: V[]) => void;
|
||||
onCancel?: () => void;
|
||||
/** Footer hint under the list — e.g. "space toggle · enter confirm". */
|
||||
/** Footer hint under the list — e.g. "[Space] toggle · [Enter] confirm". */
|
||||
footer?: string;
|
||||
}
|
||||
|
||||
@@ -91,12 +106,13 @@ export function MultiSelect<V extends string>({
|
||||
});
|
||||
const [selected, setSelected] = useState<Set<V>>(new Set(initialSelected));
|
||||
|
||||
useInput((input, key) => {
|
||||
if (key.upArrow) {
|
||||
useKeystroke((ev) => {
|
||||
if (ev.paste) return;
|
||||
if (ev.upArrow) {
|
||||
setIndex((i) => findNextEnabled(items, i, -1));
|
||||
} else if (key.downArrow) {
|
||||
} else if (ev.downArrow) {
|
||||
setIndex((i) => findNextEnabled(items, i, +1));
|
||||
} else if (input === " ") {
|
||||
} else if (ev.input === " ") {
|
||||
const item = items[index];
|
||||
if (!item || item.disabled) return;
|
||||
setSelected((prev) => {
|
||||
@@ -105,13 +121,13 @@ export function MultiSelect<V extends string>({
|
||||
else next.add(item.value);
|
||||
return next;
|
||||
});
|
||||
} else if (key.return) {
|
||||
} else if (ev.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) {
|
||||
} else if (ev.escape && onCancel) {
|
||||
onCancel();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -48,7 +48,7 @@ export function SessionPicker({
|
||||
onSubmit={(v) => onChoose(v as SessionChoice)}
|
||||
/>
|
||||
<Box marginTop={1}>
|
||||
<Text dimColor>↑↓ to move · Enter to pick</Text>
|
||||
<Text dimColor>[↑↓] navigate · [Enter] select</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
|
||||
+47
-35
@@ -1,5 +1,6 @@
|
||||
import { Box, Text } from "ink";
|
||||
import React from "react";
|
||||
import { ModalCard } from "./ModalCard.js";
|
||||
import { SingleSelect } from "./Select.js";
|
||||
|
||||
export type ShellConfirmChoice = "run_once" | "always_allow" | "deny";
|
||||
@@ -11,6 +12,13 @@ export interface ShellConfirmProps {
|
||||
* "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;
|
||||
}
|
||||
|
||||
@@ -25,44 +33,48 @@ export interface ShellConfirmProps {
|
||||
* Arrow keys + Enter. No y/n hotkey — too easy to trigger by accident
|
||||
* when the user was mid-typing a response.
|
||||
*/
|
||||
export function ShellConfirm({ command, allowPrefix, onChoose }: ShellConfirmProps) {
|
||||
export function ShellConfirm({ command, allowPrefix, kind, onChoose }: ShellConfirmProps) {
|
||||
const isBackground = kind === "run_background";
|
||||
const subtitle = isBackground
|
||||
? "long-running process — keeps running after approval, /kill to stop"
|
||||
: "model wants to run a shell command";
|
||||
return (
|
||||
<Box flexDirection="column" borderStyle="round" borderColor="yellow" paddingX={1} marginY={1}>
|
||||
<Box>
|
||||
<Text bold color="yellow">
|
||||
▸ model wants to run a shell command
|
||||
<ModalCard
|
||||
accent="#f87171"
|
||||
icon={isBackground ? "⏱" : "⚡"}
|
||||
title={isBackground ? "background process" : "shell command"}
|
||||
subtitle={subtitle}
|
||||
>
|
||||
<Box marginBottom={1}>
|
||||
<Text dimColor>{"$ "}</Text>
|
||||
<Text color="#67e8f9" bold>
|
||||
{command}
|
||||
</Text>
|
||||
</Box>
|
||||
<Box marginTop={1}>
|
||||
<Text>
|
||||
<Text dimColor>{"$ "}</Text>
|
||||
<Text color="cyan">{command}</Text>
|
||||
</Text>
|
||||
</Box>
|
||||
<Box marginTop={1}>
|
||||
<SingleSelect
|
||||
initialValue="run_once"
|
||||
items={[
|
||||
{
|
||||
value: "run_once",
|
||||
label: "Run once",
|
||||
hint: "Execute this command, don't remember it.",
|
||||
},
|
||||
{
|
||||
value: "always_allow",
|
||||
label: `Always allow "${allowPrefix}" in this project`,
|
||||
hint: "Save the prefix to ~/.reasonix/config.json; future matches auto-run.",
|
||||
},
|
||||
{
|
||||
value: "deny",
|
||||
label: "Deny",
|
||||
hint: "Tell the model the user refused; it will continue without this command.",
|
||||
},
|
||||
]}
|
||||
onSubmit={(v) => onChoose(v as ShellConfirmChoice)}
|
||||
/>
|
||||
</Box>
|
||||
</Box>
|
||||
<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"
|
||||
/>
|
||||
</ModalCard>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -28,7 +28,7 @@ export function SlashSuggestions({
|
||||
if (matches === null) return null;
|
||||
if (matches.length === 0) {
|
||||
return (
|
||||
<Box paddingX={1}>
|
||||
<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>
|
||||
@@ -45,41 +45,35 @@ export function SlashSuggestions({
|
||||
const hiddenAbove = windowStart;
|
||||
const hiddenBelow = total - windowStart - shown.length;
|
||||
return (
|
||||
<Box flexDirection="column" paddingX={1}>
|
||||
<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 or Enter to pick</Text>
|
||||
<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.
|
||||
// Selected row gets a solid-bg highlight (cyan) so it pops like
|
||||
// an editor's focused autocomplete entry. Non-selected rows stay
|
||||
// dim with a leading bullet for vertical rhythm.
|
||||
if (isSelected) {
|
||||
return (
|
||||
<Box>
|
||||
<Text bold color="cyan">
|
||||
{marker} {name.padEnd(12)}
|
||||
{argsSuffix.padEnd(16)}
|
||||
<Text backgroundColor="#67e8f9" color="black" bold>
|
||||
{` ▸ ${name.padEnd(12)}${argsSuffix.padEnd(16)} ${spec.summary} `}
|
||||
</Text>
|
||||
<Text color="cyan"> {spec.summary}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Box>
|
||||
<Text dimColor>
|
||||
{marker} {name.padEnd(12)}
|
||||
{argsSuffix.padEnd(16)} {spec.summary}
|
||||
</Text>
|
||||
<Text color="#94a3b8">{` ${name.padEnd(12)}${argsSuffix.padEnd(16)} ${spec.summary}`}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
+533
-64
@@ -1,7 +1,54 @@
|
||||
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 { COLOR, GRADIENT } from "./theme.js";
|
||||
|
||||
const WORDMARK_LETTERS: ReadonlyArray<string> = ["R", "E", "A", "S", "O", "N", "I", "X"];
|
||||
|
||||
/**
|
||||
* Gradient-flowing wordmark. Every tick the gradient shifts one
|
||||
* position so the colors visibly travel across the letters — like
|
||||
* a neon sign. Brand mark `◈` rides the same flow but also pulses
|
||||
* bold on/off (slow when idle, fast when busy) so a glance at the
|
||||
* top of the screen tells you whether the app is thinking.
|
||||
*
|
||||
* Tick is ~120 ms. `rotateEvery=4` ticks → one shift every ~480 ms
|
||||
* idle, ~240 ms when busy. Slow enough to be ambient, fast enough
|
||||
* to feel alive. Truecolor terminals get the smooth flow; 8-color
|
||||
* fallbacks just see all-cyan, which is still legible.
|
||||
*/
|
||||
function Wordmark({
|
||||
busy: _busy,
|
||||
animate: _animate,
|
||||
}: {
|
||||
busy: boolean;
|
||||
animate: boolean;
|
||||
}) {
|
||||
// Static gradient. The brand sweep teal → fuchsia is precomputed
|
||||
// once per render — no useTick subscription, no per-tick
|
||||
// re-render. Earlier versions flowed the colors over time, but
|
||||
// the per-tick re-render interleaved badly with terminal resize
|
||||
// (Ink's eraseLines misjudges row count when bars / wide text
|
||||
// wrap, ghost frames stack). Keeping this static eliminates the
|
||||
// multiplier; resize artifacts at most leave a single stale
|
||||
// frame instead of N.
|
||||
return (
|
||||
<Text>
|
||||
<Text color={GRADIENT[0]} bold>
|
||||
◈
|
||||
</Text>
|
||||
<Text> </Text>
|
||||
{WORDMARK_LETTERS.map((letter, i) => (
|
||||
<Text key={letter} color={GRADIENT[i % GRADIENT.length]} bold>
|
||||
{letter}
|
||||
</Text>
|
||||
))}
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
|
||||
export interface StatsPanelProps {
|
||||
summary: SessionSummary;
|
||||
@@ -9,6 +56,26 @@ 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
|
||||
@@ -18,96 +85,498 @@ export interface StatsPanelProps {
|
||||
* with USD both see "getting low."
|
||||
*/
|
||||
balance?: { currency: string; total: number } | null;
|
||||
/**
|
||||
* Published npm version newer than VERSION. Rendered as a yellow
|
||||
* "· update: X" nudge in the panel header. `null` / `undefined`
|
||||
* hides the nudge (offline launch, already up to date, or check
|
||||
* still in flight).
|
||||
*/
|
||||
updateAvailable?: string | null;
|
||||
/**
|
||||
* 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 ctxColor = ctxRatio >= 0.8 ? "red" : ctxRatio >= 0.5 ? "yellow" : undefined;
|
||||
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;
|
||||
|
||||
// No gradient bars, no animation. Earlier versions had truecolor
|
||||
// gradient rules top+bottom and a tick-driven wordmark/bar flow,
|
||||
// but those are exactly the elements Ink's eraseLines miscounts
|
||||
// on resize: ~100-char gradient strings wrap 2-3 visual rows at
|
||||
// narrow widths, the per-tick re-render writes new frames before
|
||||
// the stale rows are erased, and ghost panels stack vertically
|
||||
// (the user-reported "刷屏" / multi-frame artifact). Fixed-row
|
||||
// panel + no per-tick churn keeps Ink's row math honest.
|
||||
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}
|
||||
<Box flexDirection="column" paddingX={1} marginBottom={1}>
|
||||
<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}
|
||||
animate={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,
|
||||
animate,
|
||||
}: {
|
||||
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;
|
||||
/** When false, suppress optional pills + animation to avoid wraps. */
|
||||
animate: boolean;
|
||||
}) {
|
||||
// Mode pill — pick the most informative one to surface in the
|
||||
// header. PLAN beats AUTO/review beats nothing. Pro armed/escalated
|
||||
// gets its own pill alongside.
|
||||
const modePill = planMode
|
||||
? { label: "PLAN", bg: "red" as const }
|
||||
: editMode === "auto"
|
||||
? { label: "AUTO", bg: "magenta" as const }
|
||||
: editMode === "review"
|
||||
? { label: "REVIEW", bg: "cyan" as const }
|
||||
: null;
|
||||
const proPill = escalated
|
||||
? { label: "⇧ PRO", bg: "red" as const }
|
||||
: proArmed
|
||||
? { label: "⇧ PRO", bg: "yellow" as const }
|
||||
: null;
|
||||
// Narrow / non-animate mode hides the secondary pills (harvest,
|
||||
// branch, reasoning effort) so the header always fits on one
|
||||
// visual row. Wrapping the header is the main amplifier of the
|
||||
// eraseLines miscount that produces the "screen flashing" effect.
|
||||
const showSecondary = animate && !narrow;
|
||||
return (
|
||||
<Box justifyContent="space-between">
|
||||
<Box>
|
||||
<Wordmark busy={busy} animate={animate} />
|
||||
<Text dimColor>{` ${VERSION}`}</Text>
|
||||
<Text dimColor>{" "}</Text>
|
||||
<Text color="yellow" bold>
|
||||
{model.replace(/^deepseek-/, "")}
|
||||
</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" bold>
|
||||
${summary.totalCostUsd.toFixed(6)}
|
||||
</Text>
|
||||
{modePill ? (
|
||||
<>
|
||||
<Text>{" "}</Text>
|
||||
<Pill label={modePill.label} bg={modePill.bg} />
|
||||
</>
|
||||
) : null}
|
||||
{proPill ? (
|
||||
<>
|
||||
<Text>{" "}</Text>
|
||||
<Pill label={proPill.label} bg={proPill.bg} />
|
||||
</>
|
||||
) : null}
|
||||
{showSecondary && harvestOn ? (
|
||||
<Text dimColor>
|
||||
{" (in "}${summary.totalInputCostUsd.toFixed(6)}
|
||||
{" · out "}${summary.totalOutputCostUsd.toFixed(6)}
|
||||
{")"}
|
||||
</Text>
|
||||
</Text>
|
||||
{summary.lastPromptTokens > 0 ? (
|
||||
<Text>
|
||||
<Text dimColor>ctx </Text>
|
||||
<Text color={ctxColor} bold={ctxColor !== undefined}>
|
||||
{formatTokens(summary.lastPromptTokens)}/{formatTokens(ctxMax)}
|
||||
</Text>
|
||||
<Text dimColor> ({(ctxRatio * 100).toFixed(0)}%)</Text>
|
||||
{ctxRatio >= 0.8 ? (
|
||||
<Text color="red" bold>
|
||||
{" "}
|
||||
· /compact
|
||||
</Text>
|
||||
) : null}
|
||||
<Text>{" "}</Text>
|
||||
<Text color="magenta">harvest</Text>
|
||||
</Text>
|
||||
) : null}
|
||||
{balance ? (
|
||||
<Text>
|
||||
<Text dimColor>balance </Text>
|
||||
<Text color={balance.total < 1 ? "red" : balance.total < 5 ? "yellow" : "green"} bold>
|
||||
{balance.currency === "USD" ? "$" : ""}
|
||||
{balance.total.toFixed(2)}
|
||||
{balance.currency !== "USD" ? ` ${balance.currency}` : ""}
|
||||
</Text>
|
||||
{showSecondary && branchOn ? (
|
||||
<Text dimColor>
|
||||
<Text>{" "}</Text>
|
||||
<Text color="blue">{`branch×${branchBudget}`}</Text>
|
||||
</Text>
|
||||
) : null}
|
||||
{showSecondary && reasoningEffort === "max" ? (
|
||||
<>
|
||||
<Text>{" "}</Text>
|
||||
<Text color="green" dimColor>
|
||||
max
|
||||
</Text>
|
||||
</>
|
||||
) : null}
|
||||
{showSecondary && reasoningEffort === "high" ? (
|
||||
<>
|
||||
<Text>{" "}</Text>
|
||||
<Text color="yellow" dimColor>
|
||||
high
|
||||
</Text>
|
||||
</>
|
||||
) : null}
|
||||
</Box>
|
||||
<Text>
|
||||
{updateAvailable ? <Text color="yellow" bold>{`↑ ${updateAvailable} `}</Text> : null}
|
||||
<Text dimColor>{narrow ? `t${turns}` : `turn ${turns} · /help`}</Text>
|
||||
</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
/** Solid-background tag, used for primary mode + pro indicators. */
|
||||
function Pill({ label, bg }: { label: string; bg: "red" | "magenta" | "cyan" | "yellow" }) {
|
||||
return (
|
||||
<Text backgroundColor={bg} color="white" bold>
|
||||
{` ${label} `}
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Compact integer formatter: 1234 → "1.2k", 131072 → "131k". Keeps the
|
||||
* panel narrow enough to fit on 80-col terminals even when the context
|
||||
* is near full.
|
||||
* 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 color={COLOR.info} dimColor>
|
||||
{"▣ ctx "}
|
||||
</Text>
|
||||
<Text dimColor>— (no turns yet)</Text>
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
const color = ratio >= 0.8 ? COLOR.err : ratio >= 0.6 ? COLOR.warn : COLOR.ok;
|
||||
const pct = Math.round(ratio * 100);
|
||||
return (
|
||||
<Text>
|
||||
<Text color={COLOR.info}>{"▣ ctx "}</Text>
|
||||
<Bar ratio={ratio} color={color} cells={showBar ? 14 : 10} />
|
||||
<Text> </Text>
|
||||
<Text color={color} bold>
|
||||
{formatTokens(promptTokens)}/{formatTokens(ctxMax)}
|
||||
</Text>
|
||||
<Text dimColor> ({pct}%)</Text>
|
||||
{ratio >= 0.8 ? (
|
||||
<Text color={COLOR.err} 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 color={COLOR.info} dimColor>
|
||||
{"⌬ cache "}
|
||||
</Text>
|
||||
<Text dimColor>—</Text>
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
if (coldStart) {
|
||||
return (
|
||||
<Text>
|
||||
<Text color={COLOR.info} dimColor>
|
||||
{"⌬ cache "}
|
||||
</Text>
|
||||
<Text dimColor>{pct}% </Text>
|
||||
<Text dimColor italic>
|
||||
(cold start)
|
||||
</Text>
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
const color = hitRatio >= 0.7 ? COLOR.ok : hitRatio >= 0.4 ? COLOR.warn : COLOR.err;
|
||||
return (
|
||||
<Text>
|
||||
<Text color={COLOR.info}>{"⌬ 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): string | undefined {
|
||||
if (cost <= 0) return undefined;
|
||||
if (cost >= 0.2) return COLOR.err;
|
||||
if (cost >= 0.05) return COLOR.warn;
|
||||
return COLOR.ok;
|
||||
}
|
||||
function sessionCostColor(cost: number): string | undefined {
|
||||
if (cost <= 0) return undefined;
|
||||
if (cost >= 5) return COLOR.err;
|
||||
if (cost >= 0.5) return COLOR.warn;
|
||||
return COLOR.ok;
|
||||
}
|
||||
|
||||
function CostCell({
|
||||
summary,
|
||||
coldStart,
|
||||
}: {
|
||||
summary: SessionSummary;
|
||||
coldStart: boolean;
|
||||
}) {
|
||||
if (summary.turns === 0) {
|
||||
return (
|
||||
<Text>
|
||||
<Text color={COLOR.info} 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 color={COLOR.info}>{"◴ 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 ? COLOR.err : balance.total < 5 ? COLOR.warn : COLOR.ok;
|
||||
return (
|
||||
<Text>
|
||||
<Text color={COLOR.info}>{"◐ balance "}</Text>
|
||||
<Text color={color} bold>
|
||||
{balance.currency === "USD" ? "$" : ""}
|
||||
{balance.total.toFixed(2)}
|
||||
{balance.currency !== "USD" ? ` ${balance.currency}` : ""}
|
||||
</Text>
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Truecolor progress bar. Filled cells use the threshold color (green
|
||||
* → amber → rose) so the bar communicates pressure at a glance;
|
||||
* empty cells use a dim shade so the empty portion is visible
|
||||
* without dominating. ▰/▱ have distinct shapes (filled vs hollow)
|
||||
* so the boundary is clear even when colors snap to 8-color slots
|
||||
* on legacy terminals.
|
||||
*/
|
||||
function Bar({
|
||||
ratio,
|
||||
color,
|
||||
cells = 14,
|
||||
}: {
|
||||
ratio: number;
|
||||
color: string;
|
||||
cells?: number;
|
||||
}) {
|
||||
const filled = Math.max(0, Math.min(cells, Math.round(ratio * cells)));
|
||||
return (
|
||||
<Text>
|
||||
<Text color={color}>{"▰".repeat(filled)}</Text>
|
||||
<Text dimColor>{"▱".repeat(cells - filled)}</Text>
|
||||
</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 < 1000) return String(n);
|
||||
const k = n / 1000;
|
||||
return k >= 100 ? `${k.toFixed(0)}k` : `${k.toFixed(1)}k`;
|
||||
if (n < 1024) return String(n);
|
||||
const k = n / 1024;
|
||||
return k >= 100 ? `${k.toFixed(0)}K` : `${k.toFixed(1)}K`;
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
/**
|
||||
* Welcome card on the empty session. The first thing a user sees
|
||||
* after launching `reasonix code` — needs to communicate, in the
|
||||
* ~5 seconds before they type, three things: brand, what to type,
|
||||
* how to escape. Card framing uses a gradient top rule + left-side
|
||||
* accent bar + sectioned hints so it reads as a designed surface
|
||||
* rather than a bare list. No bordered Boxes — those amplified
|
||||
* Ink's Windows eraseLines miscount.
|
||||
*/
|
||||
|
||||
import { Box, Text, useStdout } from "ink";
|
||||
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React in value scope
|
||||
import React from "react";
|
||||
import { COLOR, gradientCells } from "./theme.js";
|
||||
|
||||
export interface WelcomeBannerProps {
|
||||
/** True when running `reasonix code`. Surfaces code-mode hints. */
|
||||
inCodeMode?: boolean;
|
||||
}
|
||||
|
||||
export function WelcomeBanner({ inCodeMode }: WelcomeBannerProps): React.ReactElement {
|
||||
const { stdout } = useStdout();
|
||||
const cols = stdout?.columns ?? 80;
|
||||
const ruleWidth = Math.min(60, Math.max(28, cols - 4));
|
||||
return (
|
||||
<Box flexDirection="column" paddingX={1} marginY={1}>
|
||||
<GradientRule width={ruleWidth} />
|
||||
<BarRow>
|
||||
<Text bold color={COLOR.brand}>
|
||||
◈ welcome
|
||||
</Text>
|
||||
<Text dimColor>{" · type a message to start"}</Text>
|
||||
</BarRow>
|
||||
<BarRow />
|
||||
<BarRow>
|
||||
<Text bold color={COLOR.primary}>
|
||||
quick start
|
||||
</Text>
|
||||
</BarRow>
|
||||
<Hint cmd="/help" desc="every command + keyboard shortcut" />
|
||||
<Hint cmd="/skill" desc="invoke a stored playbook" />
|
||||
{inCodeMode ? (
|
||||
<>
|
||||
<Hint cmd="@path" desc="inline a file in your message" />
|
||||
<Hint cmd="!cmd" desc="run a shell command, output goes to context" />
|
||||
</>
|
||||
) : null}
|
||||
<Hint cmd="/exit" desc="quit (Ctrl+C also works)" />
|
||||
<BarRow />
|
||||
<BarRow>
|
||||
<Text dimColor italic>
|
||||
tip:
|
||||
</Text>
|
||||
<Text dimColor>{" Ctrl+J inserts a newline · trailing \\ also continues"}</Text>
|
||||
</BarRow>
|
||||
<Box marginTop={1}>
|
||||
<GradientRule width={ruleWidth} thin />
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* One-line gradient rule. `thin` swaps the half-block top/bottom so
|
||||
* the top of the card reads as a "header band" (▄ — bottom-half
|
||||
* filled) and the bottom as "section close" (▁ — minimal pixel
|
||||
* row). Same primitive the StatsPanel uses, kept consistent.
|
||||
*/
|
||||
function GradientRule({ width, thin }: { width: number; thin?: boolean }) {
|
||||
const cells = gradientCells(width, thin ? "▁" : "▄");
|
||||
return (
|
||||
<Box>
|
||||
{cells.map((c, i) => (
|
||||
// biome-ignore lint/suspicious/noArrayIndexKey: fixed-width gradient row, never reordered
|
||||
<Text key={`wrule-${i}`} color={c.color}>
|
||||
{c.ch}
|
||||
</Text>
|
||||
))}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Card row — left-side accent bar followed by content. Children
|
||||
* optional so we can use this for blank spacer rows (bar only).
|
||||
*/
|
||||
function BarRow({ children }: { children?: React.ReactNode }) {
|
||||
return (
|
||||
<Box>
|
||||
<Text color={COLOR.brand} bold>
|
||||
▎
|
||||
</Text>
|
||||
<Text> </Text>
|
||||
{children}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Single hint row — bold accent cmd token + dim description.
|
||||
* Padded so all cmd tokens line up regardless of length, like a
|
||||
* man-page synopsis.
|
||||
*/
|
||||
function Hint({ cmd, desc }: { cmd: string; desc: string }) {
|
||||
return (
|
||||
<BarRow>
|
||||
<Text bold color={COLOR.accent}>
|
||||
{cmd.padEnd(8)}
|
||||
</Text>
|
||||
<Text dimColor>{` ${desc}`}</Text>
|
||||
</BarRow>
|
||||
);
|
||||
}
|
||||
@@ -97,7 +97,7 @@ export function Wizard({ onComplete, onCancel, existingApiKey, initial }: Wizard
|
||||
}}
|
||||
/>
|
||||
<Box marginTop={1}>
|
||||
<Text dimColor>↑/↓ move · enter confirm · esc cancel</Text>
|
||||
<Text dimColor>[↑↓] navigate · [Enter] confirm · [Esc] cancel</Text>
|
||||
</Box>
|
||||
</StepFrame>
|
||||
);
|
||||
@@ -115,7 +115,7 @@ export function Wizard({ onComplete, onCancel, existingApiKey, initial }: Wizard
|
||||
const needsArgs = selected.some((name) => CATALOG_BY_NAME.get(name)?.userArgs);
|
||||
setStep(needsArgs ? "mcpArgs" : "review");
|
||||
}}
|
||||
footer="↑/↓ move · space toggle · enter confirm · esc cancel · leave empty to skip"
|
||||
footer="[↑↓] navigate · [Space] toggle · [Enter] confirm · [Esc] cancel · empty = skip"
|
||||
/>
|
||||
</StepFrame>
|
||||
);
|
||||
@@ -174,7 +174,7 @@ export function Wizard({ onComplete, onCancel, existingApiKey, initial }: Wizard
|
||||
</Box>
|
||||
) : null}
|
||||
<Box marginTop={1}>
|
||||
<Text dimColor>enter save · esc cancel</Text>
|
||||
<Text dimColor>[Enter] save · [Esc] cancel</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
<ReviewConfirm
|
||||
@@ -213,7 +213,7 @@ export function Wizard({ onComplete, onCancel, existingApiKey, initial }: Wizard
|
||||
<Text>Run `reasonix` any time to start chatting — your settings are remembered.</Text>
|
||||
</Box>
|
||||
<Box marginTop={1}>
|
||||
<Text dimColor>Press enter to exit.</Text>
|
||||
<Text dimColor>[Enter] to exit</Text>
|
||||
</Box>
|
||||
<ExitOnEnter onExit={exit} />
|
||||
</Box>
|
||||
|
||||
@@ -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,182 @@
|
||||
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.
|
||||
*
|
||||
* Each block gets a `[N]` label so users can target a subset via
|
||||
* `/apply 1` / `/apply 1,3-4` / `/discard 2` instead of being forced
|
||||
* into all-or-nothing.
|
||||
*/
|
||||
export function formatPendingPreview(blocks: EditBlock[]): string {
|
||||
const partial = blocks.length > 1 ? " · /apply N or 1,3-4 for partial" : "";
|
||||
const header = `▸ ${blocks.length} pending edit block(s) — /apply (or y) to commit · /discard (or n) to drop${partial}`;
|
||||
const diffLines = formatAllBlockDiffs(blocks, { numbered: blocks.length > 1 });
|
||||
return [header, ...diffLines].join("\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a `/apply <N>` / `/discard <N>` argument into a deduplicated,
|
||||
* sorted list of 1-based indices. Accepts:
|
||||
* - single value: `"3"` → [3]
|
||||
* - comma list: `"1,3,5"` → [1, 3, 5]
|
||||
* - range: `"2-4"` → [2, 3, 4]
|
||||
* - mixed: `"1,3-5,7"` → [1, 3, 4, 5, 7]
|
||||
* - whitespace + trailing commas tolerated.
|
||||
*
|
||||
* Bounds-checked against `max` (the count of pending blocks); any
|
||||
* out-of-range or malformed token returns `{ error }` so the caller
|
||||
* can surface a usage hint instead of silently applying the wrong
|
||||
* subset. Empty input returns `{ ok: [] }` so callers can detect
|
||||
* "user passed no indices" and treat that as the all-blocks default.
|
||||
*/
|
||||
export function parseEditIndices(raw: string, max: number): { ok: number[] } | { error: string } {
|
||||
const trimmed = raw.trim();
|
||||
if (!trimmed) return { ok: [] };
|
||||
if (max <= 0) return { error: "no pending edits to address" };
|
||||
const seen = new Set<number>();
|
||||
const tokens = trimmed
|
||||
.split(",")
|
||||
.map((t) => t.trim())
|
||||
.filter((t) => t.length > 0);
|
||||
if (tokens.length === 0) return { ok: [] };
|
||||
for (const tok of tokens) {
|
||||
const range = tok.match(/^(\d+)-(\d+)$/);
|
||||
if (range) {
|
||||
const a = Number.parseInt(range[1] ?? "", 10);
|
||||
const b = Number.parseInt(range[2] ?? "", 10);
|
||||
if (!Number.isFinite(a) || !Number.isFinite(b) || a < 1 || b < 1) {
|
||||
return { error: `invalid range: "${tok}"` };
|
||||
}
|
||||
const lo = Math.min(a, b);
|
||||
const hi = Math.max(a, b);
|
||||
if (hi > max) return { error: `index ${hi} out of range (max ${max})` };
|
||||
for (let i = lo; i <= hi; i++) seen.add(i);
|
||||
continue;
|
||||
}
|
||||
if (!/^\d+$/.test(tok)) return { error: `invalid index: "${tok}"` };
|
||||
const n = Number.parseInt(tok, 10);
|
||||
if (!Number.isFinite(n) || n < 1) return { error: `invalid index: "${tok}"` };
|
||||
if (n > max) return { error: `index ${n} out of range (max ${max})` };
|
||||
seen.add(n);
|
||||
}
|
||||
return { ok: [...seen].sort((a, b) => a - b) };
|
||||
}
|
||||
|
||||
/**
|
||||
* Partition `edits` into the subset addressed by `indices1Based` and
|
||||
* everything else (preserves original order). Pure helper so the
|
||||
* pending-edits queue can be sliced from the slash handler in App.tsx
|
||||
* without any React-state plumbing in the test path.
|
||||
*/
|
||||
export function partitionEdits<T>(
|
||||
edits: readonly T[],
|
||||
indices1Based: readonly number[],
|
||||
): { selected: T[]; remaining: T[] } {
|
||||
const picked = new Set(indices1Based);
|
||||
const selected: T[] = [];
|
||||
const remaining: T[] = [];
|
||||
for (let i = 0; i < edits.length; i++) {
|
||||
if (picked.has(i + 1)) selected.push(edits[i] as T);
|
||||
else remaining.push(edits[i] as T);
|
||||
}
|
||||
return { selected, remaining };
|
||||
}
|
||||
|
||||
/**
|
||||
* 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(", ")}` : "";
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
/**
|
||||
* Hash-mode (`#note` / `#g note`) prefix parsing — instant memory write.
|
||||
*
|
||||
* A `#` at the start of the user's input writes a one-liner to memory
|
||||
* pinned in the prefix from now on. Two scopes:
|
||||
*
|
||||
* - `#<note>` → project memory `<rootDir>/REASONIX.md`
|
||||
* (committable, team-shared)
|
||||
* - `#g <note>` → global memory `~/.reasonix/REASONIX.md`
|
||||
* (private, cross-project — never committed)
|
||||
*
|
||||
* Same idea as Claude Code's `#` prefix — faster than going through
|
||||
* a `/memory remember ...` slash for a one-liner like "always use pnpm".
|
||||
*
|
||||
* Trigger shape:
|
||||
* - `#` followed by zero-or-more spaces, then a non-empty body
|
||||
* - NOT `##` / `###` / etc. — those stay markdown headings to the model
|
||||
* - `\#foo` escape → not a memory write, leading backslash stripped before
|
||||
* submission so the model sees `#foo` literally
|
||||
*
|
||||
* Each call appends one bullet at the bottom; we don't try to parse
|
||||
* section structure. The user can reorganize manually whenever they
|
||||
* want.
|
||||
*/
|
||||
|
||||
import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
import { PROJECT_MEMORY_FILE } from "../../project-memory.js";
|
||||
|
||||
const PROJECT_HEADER = `# Reasonix project memory
|
||||
|
||||
Notes the user pinned via the \`#\` prompt prefix. The whole file is
|
||||
loaded into the immutable system prefix every session — keep it terse.
|
||||
|
||||
`;
|
||||
|
||||
const GLOBAL_HEADER = `# Reasonix global memory
|
||||
|
||||
Cross-project notes the user pinned via the \`#g\` prompt prefix. Loaded
|
||||
into every Reasonix session's prefix regardless of working directory.
|
||||
Private to this machine — not committed anywhere.
|
||||
|
||||
`;
|
||||
|
||||
/**
|
||||
* Result of `detectHashMemory`.
|
||||
*
|
||||
* - `kind: "memory"` — input is `#<note>`; write to project REASONIX.md.
|
||||
* - `kind: "memory-global"` — input is `#g <note>`; write to global file.
|
||||
* - `kind: "escape"` — input started with `\#`; submit `#foo` literally.
|
||||
* - returning `null` — input is unrelated to hash mode.
|
||||
*/
|
||||
export type HashMemoryParse =
|
||||
| { kind: "memory"; note: string }
|
||||
| { kind: "memory-global"; note: string }
|
||||
| { kind: "escape"; text: string };
|
||||
|
||||
/**
|
||||
* Classify a hash-prefixed input. Pure — no filesystem touch — so it's
|
||||
* trivially testable and can run before any I/O decision in handleSubmit.
|
||||
*
|
||||
* Order of checks matters:
|
||||
* 1. `\#…` escape (so `\#g foo` ALSO escapes — user can send `#g foo`
|
||||
* to the model verbatim).
|
||||
* 2. `##…` markdown heading (level-2+ passes through unchanged).
|
||||
* 3. `#g <body>` — global memory. Requires whitespace after the `g` so
|
||||
* a note that happens to start with `g` (e.g. `#good idea`) doesn't
|
||||
* route to global by accident.
|
||||
* 4. `#<body>` — project memory.
|
||||
*/
|
||||
export function detectHashMemory(text: string): HashMemoryParse | null {
|
||||
if (text.startsWith("\\#")) {
|
||||
return { kind: "escape", text: text.slice(1) };
|
||||
}
|
||||
if (!text.startsWith("#")) return null;
|
||||
// Markdown headings of level 2+ pass through to the model unchanged.
|
||||
// Only a single leading `#` (level-1 heading shape) is ambiguous; we
|
||||
// resolve that ambiguity in favor of memory write and document the
|
||||
// `\#` escape for users who want a literal H1 in the prompt.
|
||||
if (text.startsWith("##")) return null;
|
||||
// `#g <note>` — global memory. The space after `g` is mandatory so
|
||||
// notes like `#golang preference` route to project memory, not global.
|
||||
// `#g` alone (or `#g` + only whitespace) is treated as null — the
|
||||
// user clearly wanted the global form but typed no body, so we don't
|
||||
// silently fall back to project memory with body=`g`.
|
||||
if (/^#g\s*$/.test(text)) return null;
|
||||
const globalMatch = /^#g\s+(.+)$/s.exec(text);
|
||||
if (globalMatch) {
|
||||
const body = globalMatch[1]!.trim();
|
||||
if (!body) return null;
|
||||
return { kind: "memory-global", note: body };
|
||||
}
|
||||
const body = text.slice(1).trim();
|
||||
if (!body) return null;
|
||||
return { kind: "memory", note: body };
|
||||
}
|
||||
|
||||
export interface AppendMemoryResult {
|
||||
/** Absolute path written to. */
|
||||
path: string;
|
||||
/** True iff the file did not exist before this call. */
|
||||
created: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Append `note` as a single bullet to `<rootDir>/REASONIX.md`. Creates
|
||||
* the file with a short header when absent. Inserts a leading newline
|
||||
* if the existing file doesn't end with one, so bullets don't collide
|
||||
* with the previous section's last line.
|
||||
*/
|
||||
export function appendProjectMemory(rootDir: string, note: string): AppendMemoryResult {
|
||||
return appendBulletToFile(join(rootDir, PROJECT_MEMORY_FILE), note, PROJECT_HEADER);
|
||||
}
|
||||
|
||||
export const GLOBAL_MEMORY_DIR = ".reasonix";
|
||||
export const GLOBAL_MEMORY_FILE = "REASONIX.md";
|
||||
|
||||
/**
|
||||
* Resolve the path to the global memory file. Defaults to
|
||||
* `~/.reasonix/REASONIX.md`; callers (mainly tests) can override the
|
||||
* home dir to point at a tmpdir.
|
||||
*/
|
||||
export function globalMemoryPath(homeDir: string = homedir()): string {
|
||||
return join(homeDir, GLOBAL_MEMORY_DIR, GLOBAL_MEMORY_FILE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Append `note` to `~/.reasonix/REASONIX.md`. Creates the parent
|
||||
* directory + file if either is missing.
|
||||
*/
|
||||
export function appendGlobalMemory(note: string, homeDir?: string): AppendMemoryResult {
|
||||
return appendBulletToFile(globalMemoryPath(homeDir), note, GLOBAL_HEADER);
|
||||
}
|
||||
|
||||
function appendBulletToFile(path: string, note: string, newFileHeader: string): AppendMemoryResult {
|
||||
const trimmed = note.trim();
|
||||
if (!trimmed) throw new Error("note body cannot be empty");
|
||||
const bullet = `- ${trimmed}\n`;
|
||||
if (!existsSync(path)) {
|
||||
mkdirSync(dirname(path), { recursive: true });
|
||||
writeFileSync(path, `${newFileHeader}${bullet}`, "utf8");
|
||||
return { path, created: true };
|
||||
}
|
||||
let prefix = "";
|
||||
try {
|
||||
const existing = readFileSync(path, "utf8");
|
||||
if (existing.length > 0 && !existing.endsWith("\n")) prefix = "\n";
|
||||
} catch {
|
||||
// Unreadable but exists — let appendFileSync surface the real error.
|
||||
}
|
||||
appendFileSync(path, `${prefix}${bullet}`, "utf8");
|
||||
return { path, created: false };
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
/**
|
||||
* CSI sequence recovery for Ink's `useInput`.
|
||||
*
|
||||
* Why this exists. Ink delivers keyboard events through `parse-keypress`,
|
||||
* which reads stdin and recognises ANSI control-sequence-introducer
|
||||
* (CSI) sequences with a state machine plus a short timeout. On most
|
||||
* terminals this works: the byte stream `\x1b [ A` arrives in one
|
||||
* read, parse-keypress emits `{key.upArrow:true, input:""}`, life is
|
||||
* good.
|
||||
*
|
||||
* On Windows PowerShell + ConPTY (and a handful of embedded shells)
|
||||
* the bytes don't always arrive together. parse-keypress's timeout
|
||||
* expires between chunks, so it dispatches the lone `\x1b` as
|
||||
* `key.escape:true` and then dispatches the trailing `[A` as a
|
||||
* regular character event — `input:"[A", key.upArrow:undefined`. The
|
||||
* useInput consumer sees `[A` as plain text, inserts it into the
|
||||
* buffer, and the cursor never moves. Same shape on `[C` (right
|
||||
* arrow), `[Z` (Shift+Tab), `[5~` (PgUp), `[201~` (bracketed-paste
|
||||
* end), etc.
|
||||
*
|
||||
* Every Reasonix UI component that calls `useInput` is exposed to
|
||||
* this. Patching each one to re-recognise the bare CSI tail was
|
||||
* fragile — every release a new symptom appeared (cursor stuck,
|
||||
* paste markers leaking, Shift+Tab not toggling). So this module is
|
||||
* the single source of truth for CSI recovery: every input handler
|
||||
* runs the raw event through `recoverCsiTail` before reading
|
||||
* structured key flags.
|
||||
*
|
||||
* Recovery is conservative. We only rewrite when:
|
||||
* 1. None of the structured key flags Ink already populated for
|
||||
* this event is set (so a real upArrow press isn't second-
|
||||
* guessed).
|
||||
* 2. `input` exactly matches a recognised tail in either form —
|
||||
* the full `\x1b[X` sequence (in case the timeout merged it)
|
||||
* or the bare `[X` ConPTY-stripped variant.
|
||||
*
|
||||
* Anything else passes through unchanged.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Subset of Ink's `Key` interface that contains the structured flags
|
||||
* we know how to recover. Optional everywhere because callers from
|
||||
* different Ink versions may not populate every field.
|
||||
*/
|
||||
export interface CsiKeyFlags {
|
||||
upArrow?: boolean;
|
||||
downArrow?: boolean;
|
||||
leftArrow?: boolean;
|
||||
rightArrow?: boolean;
|
||||
pageUp?: boolean;
|
||||
pageDown?: boolean;
|
||||
delete?: boolean;
|
||||
shift?: boolean;
|
||||
tab?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* CSI tails we recognise. Each maps the printable bytes of a CSI
|
||||
* tail (the part after the `\x1b`) to the structured key flags they
|
||||
* should set. Bracketed-paste markers `[200~` / `[201~` are
|
||||
* intentionally absent — they're handled by PromptInput's paste
|
||||
* accumulator, which has different semantics (collect content
|
||||
* between markers rather than emit one keystroke).
|
||||
*/
|
||||
const CSI_TAIL_TO_FLAGS: ReadonlyArray<{ tail: string; flags: CsiKeyFlags }> = [
|
||||
// Arrow keys — the most common ConPTY victim.
|
||||
{ tail: "[A", flags: { upArrow: true } },
|
||||
{ tail: "[B", flags: { downArrow: true } },
|
||||
{ tail: "[C", flags: { rightArrow: true } },
|
||||
{ tail: "[D", flags: { leftArrow: true } },
|
||||
// Page navigation.
|
||||
{ tail: "[5~", flags: { pageUp: true } },
|
||||
{ tail: "[6~", flags: { pageDown: true } },
|
||||
// Forward-delete (the key labelled Delete on most keyboards).
|
||||
{ tail: "[3~", flags: { delete: true } },
|
||||
// Shift+Tab — terminal sends `\x1b[Z` rather than tab-with-shift.
|
||||
{ tail: "[Z", flags: { shift: true, tab: true } },
|
||||
];
|
||||
|
||||
/**
|
||||
* Did Ink already give us a structured key for this event? When
|
||||
* `true`, recovery is unnecessary and would risk overriding a real
|
||||
* keypress that happens to share `input` with a CSI tail.
|
||||
*/
|
||||
function alreadyStructured(flags: CsiKeyFlags): boolean {
|
||||
return Boolean(
|
||||
flags.upArrow ||
|
||||
flags.downArrow ||
|
||||
flags.leftArrow ||
|
||||
flags.rightArrow ||
|
||||
flags.pageUp ||
|
||||
flags.pageDown ||
|
||||
flags.delete ||
|
||||
(flags.tab && flags.shift),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* If `input` is a recognisable CSI tail (with or without the leading
|
||||
* `\x1b`), return the structured flags it should produce. Otherwise
|
||||
* `null`. Bracketed-paste markers always return `null` here — those
|
||||
* are handled by their own accumulator.
|
||||
*
|
||||
* Pure function. Pass already-structured events through (they
|
||||
* short-circuit) so a real arrow press doesn't get rewritten.
|
||||
*/
|
||||
export function recoverCsiTail(input: string, existing: CsiKeyFlags = {}): CsiKeyFlags | null {
|
||||
if (alreadyStructured(existing)) return null;
|
||||
for (const entry of CSI_TAIL_TO_FLAGS) {
|
||||
if (input === entry.tail || input === `\x1b${entry.tail}`) {
|
||||
return entry.flags;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tail forms (with and without the leading `\x1b`) that should never
|
||||
* end up as literal text in a user's prompt buffer. Used as a final
|
||||
* defensive pass before treating input as printable — if a CSI
|
||||
* fragment slipped past structured-key recovery (e.g. arrived
|
||||
* embedded inside a paste burst), at least drop the raw bytes
|
||||
* rather than insert them as garbage text.
|
||||
*
|
||||
* Includes the bracketed-paste markers `[200~` / `[201~` because a
|
||||
* paste whose start/end markers got chunked across reads can leave
|
||||
* those bytes in the printable input.
|
||||
*/
|
||||
export const STRIPPABLE_CSI_FRAGMENTS: readonly string[] = [
|
||||
"\u001b[200~",
|
||||
"\u001b[201~",
|
||||
"[200~",
|
||||
"[201~",
|
||||
...CSI_TAIL_TO_FLAGS.flatMap((e) => [`\u001b${e.tail}`, e.tail]),
|
||||
];
|
||||
|
||||
/** Remove every recognised CSI fragment from a string. */
|
||||
export function stripCsiFragments(input: string): string {
|
||||
let out = input;
|
||||
for (const frag of STRIPPABLE_CSI_FRAGMENTS) {
|
||||
if (out.includes(frag)) out = out.replaceAll(frag, "");
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
/**
|
||||
* KeystrokeContext — React surface in front of the raw stdin reader.
|
||||
*
|
||||
* Replaces Ink's `useInput` chain. Reasonix's components no longer
|
||||
* import `useInput` from "ink"; they call `useKeystroke(handler,
|
||||
* isActive)` from this module. The provider mounted once at App
|
||||
* level owns a `StdinReader`, subscribes a single fan-out function
|
||||
* to it, and dispatches each parsed `KeyEvent` to every active
|
||||
* consumer.
|
||||
*
|
||||
* Why a Context instead of a singleton import: the provider can be
|
||||
* disabled in tests / replay mode without touching the components,
|
||||
* and the lifecycle (start/stop on mount/unmount) is tied to the
|
||||
* React tree rather than a global side effect.
|
||||
*
|
||||
* Why not just keep Ink's useInput: Ink's parse-keypress uses a
|
||||
* 100 ms intra-CSI timeout that's too short for Windows ConPTY,
|
||||
* leaking arrow-key bytes / paste markers into the buffer. Our
|
||||
* reader uses 250 ms and recognises the ESC-stripped variants too
|
||||
* — see `stdin-reader.ts`.
|
||||
*/
|
||||
|
||||
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React as a runtime value
|
||||
import React, { createContext, useContext, useEffect, useRef } from "react";
|
||||
import { type KeyEvent, type StdinReader, getStdinReader } from "./stdin-reader.js";
|
||||
|
||||
interface KeystrokeBus {
|
||||
/** Subscribe — returns an unsubscribe function. */
|
||||
subscribe(handler: KeystrokeHandler): () => void;
|
||||
}
|
||||
|
||||
export type KeystrokeHandler = (ev: KeyEvent) => void;
|
||||
|
||||
const KeystrokeContext = createContext<KeystrokeBus | null>(null);
|
||||
|
||||
export interface KeystrokeProviderProps {
|
||||
children: React.ReactNode;
|
||||
/**
|
||||
* Optional reader override. Tests inject a synthetic reader so
|
||||
* they can `feed()` chunks instead of touching real stdin. Production
|
||||
* callers leave this unset and get the singleton.
|
||||
*/
|
||||
reader?: StdinReader;
|
||||
}
|
||||
|
||||
export function KeystrokeProvider({
|
||||
children,
|
||||
reader: providedReader,
|
||||
}: KeystrokeProviderProps): React.ReactElement {
|
||||
const handlersRef = useRef<Set<KeystrokeHandler>>(new Set());
|
||||
// Ref so the bus value's identity is stable across re-renders —
|
||||
// consumers don't accidentally re-subscribe every render.
|
||||
const busRef = useRef<KeystrokeBus | null>(null);
|
||||
if (busRef.current === null) {
|
||||
busRef.current = {
|
||||
subscribe(handler) {
|
||||
handlersRef.current.add(handler);
|
||||
return () => {
|
||||
handlersRef.current.delete(handler);
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
const reader = providedReader ?? getStdinReader();
|
||||
reader.start();
|
||||
const unsubscribe = reader.subscribe((ev) => {
|
||||
// Snapshot the handler set so handlers added/removed during
|
||||
// dispatch don't perturb iteration. Cheap — typical N=1-3.
|
||||
for (const fn of [...handlersRef.current]) fn(ev);
|
||||
});
|
||||
return () => {
|
||||
unsubscribe();
|
||||
// Don't `stop()` the singleton on every unmount — multiple
|
||||
// mounts (test reruns, hot-reload) must not tear down stdin.
|
||||
// The singleton's own start() is idempotent; stop() is the
|
||||
// process-exit handler's job.
|
||||
};
|
||||
}, [providedReader]);
|
||||
|
||||
return <KeystrokeContext.Provider value={busRef.current}>{children}</KeystrokeContext.Provider>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Subscribe to keystroke events. Mirrors Ink's `useInput` shape —
|
||||
* `handler(ev)` runs on every event while `isActive` is truthy
|
||||
* (default true). Set `isActive=false` to suspend the handler
|
||||
* (e.g. while a modal is up and shouldn't respond to global keys).
|
||||
*
|
||||
* Handler identity changes are tolerated — we re-subscribe via
|
||||
* useEffect on every render. Wrap your handler in `useCallback` if
|
||||
* you want to avoid that.
|
||||
*/
|
||||
export function useKeystroke(handler: KeystrokeHandler, isActive = true): void {
|
||||
const bus = useContext(KeystrokeContext);
|
||||
// Latest-handler ref so we can subscribe ONCE per active toggle
|
||||
// and still call the freshest closure on each event.
|
||||
const handlerRef = useRef(handler);
|
||||
handlerRef.current = handler;
|
||||
|
||||
useEffect(() => {
|
||||
if (!bus || !isActive) return undefined;
|
||||
return bus.subscribe((ev) => handlerRef.current(ev));
|
||||
}, [bus, isActive]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Lower-level hook for components that need a stable subscription
|
||||
* across the lifetime of the consumer (typically StdinReader-aware
|
||||
* unit tests).
|
||||
*/
|
||||
export function useKeystrokeBus(): KeystrokeBus | null {
|
||||
return useContext(KeystrokeContext);
|
||||
}
|
||||
|
||||
/** Test helper — assemble a KeyEvent with sensible defaults. */
|
||||
export function makeKeyEvent(overrides: Partial<KeyEvent> = {}): KeyEvent {
|
||||
return { input: "", ...overrides };
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
/**
|
||||
* `/loop <interval> <prompt>` parsing + status formatting.
|
||||
*
|
||||
* Claude-Code-style recurring prompt: at every `<interval>` tick, the
|
||||
* App auto-submits `<prompt>` as if the user typed it. Useful for "keep
|
||||
* checking the deploy" / "rerun tests" / "watch the build status until
|
||||
* green" — anything the user wants probed periodically without holding
|
||||
* the keyboard.
|
||||
*
|
||||
* Cancellation contract (enforced in App.tsx, not here — this file is
|
||||
* pure):
|
||||
* - `/loop stop` → explicit stop slash
|
||||
* - user types anything else → loop dies, user takes over
|
||||
* - Esc / /new / /clear / exit → loop dies
|
||||
* - one loop per session → re-issuing /loop replaces the prior
|
||||
*
|
||||
* Interval bounds:
|
||||
* - Minimum: 5 seconds (anything tighter and the model couldn't even
|
||||
* finish a turn before the next firing — we'd queue submits and
|
||||
* drift forever).
|
||||
* - Maximum: 6 hours (the upper end of "let it run while I sleep";
|
||||
* beyond that you should be writing a cron, not a TUI loop).
|
||||
*/
|
||||
|
||||
/** Lower bound on loop interval (ms). Faster than this would queue submits faster than turns finish. */
|
||||
export const MIN_LOOP_INTERVAL_MS = 5_000;
|
||||
/** Upper bound on loop interval (ms). Beyond a few hours, use cron. */
|
||||
export const MAX_LOOP_INTERVAL_MS = 6 * 60 * 60_000;
|
||||
|
||||
/**
|
||||
* Parse a duration string into milliseconds.
|
||||
*
|
||||
* Accepted forms (case-insensitive on the unit):
|
||||
* - `45` → 45_000 (bare number = seconds)
|
||||
* - `30s` → 30_000
|
||||
* - `5m` → 300_000
|
||||
* - `2h` → 7_200_000
|
||||
* - `1.5m` → 90_000 (fractional supported)
|
||||
*
|
||||
* Returns `null` on:
|
||||
* - empty input
|
||||
* - non-numeric / unknown unit
|
||||
* - negative or zero values
|
||||
* - values outside [MIN_LOOP_INTERVAL_MS, MAX_LOOP_INTERVAL_MS]
|
||||
*
|
||||
* Caller surfaces `null` as a usage hint to the user. Pure.
|
||||
*/
|
||||
export function parseLoopInterval(raw: string): { ms: number } | null {
|
||||
const s = raw.trim().toLowerCase();
|
||||
if (!s) return null;
|
||||
const m = /^([0-9]+(?:\.[0-9]+)?)(s|sec|secs|m|min|mins|h|hr|hrs)?$/.exec(s);
|
||||
if (!m) return null;
|
||||
const n = Number.parseFloat(m[1] ?? "");
|
||||
if (!Number.isFinite(n) || n <= 0) return null;
|
||||
const unit = m[2] ?? "s";
|
||||
let ms: number;
|
||||
if (unit === "s" || unit === "sec" || unit === "secs") ms = Math.round(n * 1000);
|
||||
else if (unit === "m" || unit === "min" || unit === "mins") ms = Math.round(n * 60_000);
|
||||
else if (unit === "h" || unit === "hr" || unit === "hrs") ms = Math.round(n * 60 * 60_000);
|
||||
else return null;
|
||||
if (ms < MIN_LOOP_INTERVAL_MS) return null;
|
||||
if (ms > MAX_LOOP_INTERVAL_MS) return null;
|
||||
return { ms };
|
||||
}
|
||||
|
||||
export interface ParsedLoopArgs {
|
||||
intervalMs: number;
|
||||
prompt: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse the full `/loop <interval> <prompt>` invocation. Args is the
|
||||
* commander-style tail (already split on whitespace, slash command
|
||||
* stripped). Returns `null` when the shape is wrong; caller emits a
|
||||
* usage hint.
|
||||
*
|
||||
* Special tokens:
|
||||
* - `stop` (case-insensitive) as the only arg → caller should stop
|
||||
* the active loop. Returns a sentinel: `{ stop: true }`.
|
||||
* - empty args → returns `{ status: true }` so the caller can print
|
||||
* the active-loop status (or "no loop active").
|
||||
*
|
||||
* Otherwise the first token is the interval, the rest is the prompt.
|
||||
* The prompt may itself be a slash command (`/loop 30s /status` is a
|
||||
* valid way to keep refreshing the status panel).
|
||||
*/
|
||||
export type LoopCommand =
|
||||
| { kind: "start"; intervalMs: number; prompt: string }
|
||||
| { kind: "stop" }
|
||||
| { kind: "status" }
|
||||
| { kind: "error"; message: string };
|
||||
|
||||
export function parseLoopCommand(args: readonly string[]): LoopCommand {
|
||||
if (args.length === 0) return { kind: "status" };
|
||||
const first = (args[0] ?? "").toLowerCase();
|
||||
if (args.length === 1 && (first === "stop" || first === "off" || first === "cancel")) {
|
||||
return { kind: "stop" };
|
||||
}
|
||||
const interval = parseLoopInterval(args[0] ?? "");
|
||||
if (!interval) {
|
||||
return {
|
||||
kind: "error",
|
||||
message:
|
||||
"usage: /loop <interval> <prompt> (interval = 5s..6h, e.g. 30s, 5m, 1h)\n" +
|
||||
" /loop stop (cancel an active loop)\n" +
|
||||
" /loop (show active-loop status)",
|
||||
};
|
||||
}
|
||||
const prompt = args.slice(1).join(" ").trim();
|
||||
if (!prompt) {
|
||||
return {
|
||||
kind: "error",
|
||||
message: `usage: /loop ${args[0]} <prompt> — interval is fine but the prompt is missing.`,
|
||||
};
|
||||
}
|
||||
return { kind: "start", intervalMs: interval.ms, prompt };
|
||||
}
|
||||
|
||||
/**
|
||||
* Format the active loop into a single-line status pill for the
|
||||
* modeline. `nextFireMs` is wall-clock ms until next firing; the
|
||||
* caller computes it from the stored `nextFireAt - Date.now()`.
|
||||
*
|
||||
* Examples:
|
||||
* "loop: `npm test` · next in 28s · iter 3"
|
||||
* "loop: `check deploy status` · firing now · iter 1"
|
||||
*/
|
||||
export function formatLoopStatus(prompt: string, nextFireMs: number, iter: number): string {
|
||||
const preview = prompt.length > 36 ? `${prompt.slice(0, 33)}…` : prompt;
|
||||
const when = nextFireMs <= 0 ? "firing now" : `next in ${formatDuration(nextFireMs)}`;
|
||||
return `loop: \`${preview}\` · ${when} · iter ${iter}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Human-friendly duration. Used by the loop status pill so a 4-minute
|
||||
* 23-second wait reads as "4m23s" instead of "263000".
|
||||
*/
|
||||
export function formatDuration(ms: number): string {
|
||||
if (ms < 1000) return `${ms}ms`;
|
||||
const totalSec = Math.round(ms / 1000);
|
||||
if (totalSec < 60) return `${totalSec}s`;
|
||||
const m = Math.floor(totalSec / 60);
|
||||
const s = totalSec % 60;
|
||||
if (m < 60) return s === 0 ? `${m}m` : `${m}m${s}s`;
|
||||
const h = Math.floor(m / 60);
|
||||
const mm = m % 60;
|
||||
return mm === 0 ? `${h}h` : `${h}h${mm}m`;
|
||||
}
|
||||
+963
-88
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}`);
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,12 @@
|
||||
* - Parent owns Tab, Esc, PageUp/Down (slash-complete, abort,
|
||||
* unused). Arrow keys are split: empty buffer → parent (history
|
||||
* recall); non-empty → child (cursor movement).
|
||||
*
|
||||
* CSI recovery is delegated to `key-normalize.ts` — see there for
|
||||
* the rationale. Every event flows through `recoverCsiTail` first,
|
||||
* which is the single source of truth for the Windows ConPTY case
|
||||
* (parse-keypress eats the leading `\x1b` and routes the bare
|
||||
* `[A`/`[C`/`[201~`/etc. through useInput as plain text).
|
||||
*/
|
||||
|
||||
export interface MultilineKey {
|
||||
@@ -47,8 +53,28 @@ export interface MultilineAction {
|
||||
/** 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 };
|
||||
}
|
||||
|
||||
import { recoverCsiTail, stripCsiFragments } from "./key-normalize.js";
|
||||
|
||||
const BACKSLASH_SUFFIX = /\\$/;
|
||||
|
||||
const NOOP: MultilineAction = { next: null, cursor: null, submit: false };
|
||||
@@ -56,19 +82,46 @@ const NOOP: MultilineAction = { next: null, cursor: null, submit: false };
|
||||
export function processMultilineKey(
|
||||
value: string,
|
||||
cursor: number,
|
||||
key: MultilineKey,
|
||||
keyIn: MultilineKey,
|
||||
): MultilineAction {
|
||||
// Parent-owned keys: Tab (slash-complete), Esc (abort), PageUp/Down.
|
||||
if (key.tab || key.escape || key.pageUp || key.pageDown) {
|
||||
// CSI recovery — bare `[A` / `[C` / `[Z` / `[5~` / etc. that
|
||||
// Windows ConPTY leaves in `input` after parse-keypress eats the
|
||||
// leading `\x1b`. See key-normalize.ts for the long version.
|
||||
const recovered = recoverCsiTail(keyIn.input, keyIn);
|
||||
const key: MultilineKey = recovered ? { ...keyIn, ...recovered, input: "" } : keyIn;
|
||||
|
||||
// Parent-owned keys: Tab (slash-complete), Esc (abort).
|
||||
if (key.tab || key.escape) {
|
||||
return NOOP;
|
||||
}
|
||||
|
||||
// Empty buffer + ↑/↓ → parent handles history recall.
|
||||
if (value.length === 0 && (key.upArrow || key.downArrow)) {
|
||||
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 };
|
||||
}
|
||||
|
||||
// Cursor motion.
|
||||
// History recall is bound to Ctrl+P / Ctrl+N (bash readline
|
||||
// convention) rather than ↑/↓. Reason: Windows Terminal + ConPTY
|
||||
// translates mouse wheel events to ↑/↓ keystrokes for raw-mode
|
||||
// child processes — indistinguishable at the byte level. If ↑/↓
|
||||
// recalled history, every wheel-scroll would corrupt the prompt
|
||||
// with a prior message. Ctrl+P/N is wheel-immune.
|
||||
if (key.ctrl && key.input === "p") {
|
||||
return { ...NOOP, historyHandoff: "prev" };
|
||||
}
|
||||
if (key.ctrl && key.input === "n") {
|
||||
return { ...NOOP, historyHandoff: "next" };
|
||||
}
|
||||
|
||||
// Cursor motion. Empty single-line buffer + ↑/↓ is now a no-op
|
||||
// (used to recall history; see Ctrl+P/N comment above).
|
||||
if (key.leftArrow) {
|
||||
return { next: null, cursor: Math.max(0, cursor - 1), submit: false };
|
||||
}
|
||||
@@ -92,8 +145,58 @@ export function processMultilineKey(
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
// Newline: Ctrl+J (LF literal) or ctrl+'j' normalized form.
|
||||
// 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.
|
||||
// Strip every recognised CSI fragment (paste markers, arrow tails,
|
||||
// etc.) defensively — if any leaked past structured-key recovery
|
||||
// they shouldn't get inserted into the buffer as text.
|
||||
const stripped = stripCsiFragments(key.input);
|
||||
// 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");
|
||||
}
|
||||
@@ -172,6 +275,22 @@ 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;
|
||||
|
||||
@@ -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`;
|
||||
}
|
||||
+50
-13
@@ -3,40 +3,77 @@
|
||||
* (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, Pillar 2, branch budgets, or cost tradeoffs
|
||||
* independently — they pick "fast / smart / max" and we translate.
|
||||
* 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. `1` means branching off. */
|
||||
/**
|
||||
* 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: { model: "deepseek-chat", harvest: false, branch: 1 },
|
||||
smart: { model: "deepseek-reasoner", harvest: true, branch: 1 },
|
||||
max: { model: "deepseek-reasoner", harvest: true, branch: 3 },
|
||||
// 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: "deepseek-chat, no reasoning harvest, no branching",
|
||||
cost: "~1¢ per 100 turns · default",
|
||||
headline: "v4-flash · effort=high",
|
||||
cost: "cheapest · quick Q&A, one-line edits",
|
||||
},
|
||||
smart: {
|
||||
headline: "deepseek-reasoner + Pillar 2 harvest",
|
||||
cost: "~10× cost vs fast · slower · better on multi-step tasks",
|
||||
headline: "v4-flash · effort=max",
|
||||
cost: "~1.5× fast · default · day-to-day coding",
|
||||
},
|
||||
max: {
|
||||
headline: "reasoner + harvest + self-consistency (3 branches)",
|
||||
cost: "~30× cost vs fast · slowest · for hard single-shots",
|
||||
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 ?? "fast"];
|
||||
return PRESETS[name ?? "smart"];
|
||||
}
|
||||
@@ -0,0 +1,318 @@
|
||||
/**
|
||||
* Pure helpers for rendering one logical line of the prompt input as
|
||||
* exactly one visual row, regardless of how wide the line's content
|
||||
* is. Splitting this out from PromptInput so the math is testable
|
||||
* without React/Ink.
|
||||
*
|
||||
* Why we can't trust Ink/Yoga's text wrap: Ink uses `string-width` to
|
||||
* measure cells, but on CJK Windows terminals some glyphs render at
|
||||
* a different cell count than `string-width` reports. The terminal
|
||||
* wraps to a 2nd visual row, Ink's eraseLines miscounts, and the
|
||||
* scrollback fills with ghost rows from the previous frame's leak.
|
||||
*
|
||||
* Our fix is to never let the line wrap. We slice the text down to
|
||||
* the visible-cell budget ourselves and feed Ink a single Text whose
|
||||
* width is known to fit.
|
||||
*
|
||||
* Cursor visibility: when the user types past the visible width the
|
||||
* window slides so the cursor stays in view. `‹` and `›` markers
|
||||
* appear at the trimmed edges so the user can see content is hidden
|
||||
* to one side.
|
||||
*/
|
||||
|
||||
import { type PasteEntry, decodePasteSentinel, formatBytesShort } from "./paste-sentinels.js";
|
||||
|
||||
/**
|
||||
* One renderable atom of a viewport. The line's content is broken
|
||||
* into a sequence of these so a paste sentinel becomes a magenta
|
||||
* `[paste #N · Ml · KKB]` block while the surrounding text stays
|
||||
* normal.
|
||||
*/
|
||||
export type Segment = { kind: "text"; text: string } | { kind: "paste"; id: number; label: string };
|
||||
|
||||
export interface Viewport {
|
||||
/** Segments to render left-to-right. Sum of cells <= visibleCells. */
|
||||
segments: Segment[];
|
||||
/**
|
||||
* Visual cell column at which to draw the cursor block, measured
|
||||
* from the start of the viewport (0 = leftmost cell after the
|
||||
* prompt prefix). `null` means cursor is not on this line — the
|
||||
* caller renders a static line.
|
||||
*/
|
||||
cursorCell: number | null;
|
||||
/** True when content was clipped on the left side. */
|
||||
hiddenLeft: boolean;
|
||||
/** True when content was clipped on the right side. */
|
||||
hiddenRight: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cell width of a single character in a typical terminal grid.
|
||||
*
|
||||
* Approximation of Unicode East Asian Width=Wide / W treatment.
|
||||
* Range table is intentionally compact — covers the codepoints we
|
||||
* see in practice (CJK ideographs, fullwidth forms, Hangul syllables,
|
||||
* Hiragana / Katakana). Anything outside the wide ranges counts as
|
||||
* one cell. Control characters count as zero so we don't over-budget
|
||||
* for them.
|
||||
*
|
||||
* Not a full `string-width` clone. We deliberately don't honour the
|
||||
* "Ambiguous=2 in CJK locale" rule because it produces inconsistent
|
||||
* results across terminals and is the very source of Ink's wrap
|
||||
* miscount. Treating ambiguous chars as 1 cell here matches what
|
||||
* Ink/Yoga also does, so our slice math agrees with what Ink would
|
||||
* have rendered (had it not wrapped).
|
||||
*/
|
||||
export function charCells(ch: string): number {
|
||||
if (ch.length === 0) return 0;
|
||||
const code = ch.charCodeAt(0);
|
||||
if (code < 0x20 || code === 0x7f) return 0;
|
||||
if (code < 0x1100) return 1;
|
||||
// Hangul Jamo
|
||||
if (code >= 0x1100 && code <= 0x115f) return 2;
|
||||
// CJK Radicals, Kangxi Radicals, Ideographic Description, CJK Symbols
|
||||
if (code >= 0x2e80 && code <= 0x303e) return 2;
|
||||
// Hiragana, Katakana, Bopomofo, Hangul Compat Jamo, Kanbun
|
||||
if (code >= 0x3041 && code <= 0x33ff) return 2;
|
||||
// CJK Unified Ext A
|
||||
if (code >= 0x3400 && code <= 0x4dbf) return 2;
|
||||
// CJK Unified Ideographs
|
||||
if (code >= 0x4e00 && code <= 0x9fff) return 2;
|
||||
// Yi Syllables
|
||||
if (code >= 0xa000 && code <= 0xa4cf) return 2;
|
||||
// Hangul Syllables
|
||||
if (code >= 0xac00 && code <= 0xd7a3) return 2;
|
||||
// CJK Compatibility Ideographs
|
||||
if (code >= 0xf900 && code <= 0xfaff) return 2;
|
||||
// CJK Compatibility Forms
|
||||
if (code >= 0xfe30 && code <= 0xfe4f) return 2;
|
||||
// Halfwidth and Fullwidth Forms (fullwidth half is wide)
|
||||
if (code >= 0xff00 && code <= 0xff60) return 2;
|
||||
// Fullwidth signs
|
||||
if (code >= 0xffe0 && code <= 0xffe6) return 2;
|
||||
return 1;
|
||||
}
|
||||
|
||||
/** Total cells of a string, with paste sentinels expanded to placeholder width. */
|
||||
export function stringCells(s: string, pastes?: ReadonlyMap<number, PasteEntry>): number {
|
||||
let n = 0;
|
||||
for (let i = 0; i < s.length; i++) {
|
||||
const ch = s[i]!;
|
||||
const id = decodePasteSentinel(ch);
|
||||
if (id !== null) {
|
||||
n += pasteSentinelCells(id, pastes);
|
||||
} else {
|
||||
n += charCells(ch);
|
||||
}
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
/** Paste sentinel placeholder width — what we'd render for that sentinel. */
|
||||
export function pasteSentinelLabel(id: number, entry: PasteEntry | undefined): string {
|
||||
if (!entry) return `[paste #${id + 1} · (missing)]`;
|
||||
return `[paste #${id + 1} · ${entry.lineCount}l · ${formatBytesShort(entry.charCount)}]`;
|
||||
}
|
||||
|
||||
function pasteSentinelCells(id: number, pastes?: ReadonlyMap<number, PasteEntry>): number {
|
||||
const entry = pastes?.get(id);
|
||||
return pasteSentinelLabel(id, entry).length;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute the viewport for a line, keeping the cursor visible. When
|
||||
* the line's total cells fit in `visibleCells`, return the whole
|
||||
* line. Otherwise slice a window centred on the cursor with `‹` /
|
||||
* `›` markers indicating clipped sides.
|
||||
*
|
||||
* `cursorCol` is the cursor's char index within `line` (0 = before
|
||||
* first char; `line.length` = past last char). Pass `null` for
|
||||
* lines that don't host the cursor — the function returns a left-
|
||||
* aligned static viewport with truncation on the right.
|
||||
*/
|
||||
export function buildViewport(
|
||||
line: string,
|
||||
cursorCol: number | null,
|
||||
visibleCells: number,
|
||||
pastes?: ReadonlyMap<number, PasteEntry>,
|
||||
): Viewport {
|
||||
if (visibleCells <= 0) {
|
||||
return {
|
||||
segments: [],
|
||||
cursorCell: cursorCol === null ? null : 0,
|
||||
hiddenLeft: false,
|
||||
hiddenRight: line.length > 0,
|
||||
};
|
||||
}
|
||||
const totalCells = stringCells(line, pastes);
|
||||
|
||||
// Fast path: whole line fits.
|
||||
if (totalCells <= visibleCells) {
|
||||
const segments = textToSegments(line, pastes);
|
||||
let cursorCell: number | null = null;
|
||||
if (cursorCol !== null) {
|
||||
cursorCell = stringCells(line.slice(0, cursorCol), pastes);
|
||||
}
|
||||
return { segments, cursorCell, hiddenLeft: false, hiddenRight: false };
|
||||
}
|
||||
|
||||
// Static viewport (cursor not on this line) — clip from the right.
|
||||
if (cursorCol === null) {
|
||||
return clipFromLeft(line, visibleCells, pastes);
|
||||
}
|
||||
|
||||
// Cursor-bearing line: slide a window so cursor stays visible.
|
||||
// Reserve 1 cell on each potentially-clipped side for the marker.
|
||||
return clipAroundCursor(line, cursorCol, visibleCells, pastes);
|
||||
}
|
||||
|
||||
function clipFromLeft(
|
||||
line: string,
|
||||
visibleCells: number,
|
||||
pastes?: ReadonlyMap<number, PasteEntry>,
|
||||
): Viewport {
|
||||
// Show as much of the head as fits; mark the right edge as hidden.
|
||||
// Reserve 1 cell for the `›` marker.
|
||||
const budget = Math.max(1, visibleCells - 1);
|
||||
let used = 0;
|
||||
let end = 0;
|
||||
while (end < line.length) {
|
||||
const ch = line[end]!;
|
||||
const cw = charCellsAt(line, end, pastes);
|
||||
if (used + cw > budget) break;
|
||||
used += cw;
|
||||
end++;
|
||||
}
|
||||
const segments = textToSegments(line.slice(0, end), pastes);
|
||||
return { segments, cursorCell: null, hiddenLeft: false, hiddenRight: end < line.length };
|
||||
}
|
||||
|
||||
/**
|
||||
* Sliding window around the cursor. Algorithm:
|
||||
*
|
||||
* 1. Start with `start` and `end` both at the cursor index.
|
||||
* 2. Expand `end` rightward while there's budget, until cursor cell
|
||||
* visible or we hit end-of-line.
|
||||
* 3. Expand `start` leftward to fill remaining budget.
|
||||
* 4. Reserve 1 cell on each clipped side for the `‹`/`›` marker.
|
||||
*
|
||||
* The cursor cell is computed AFTER the slice is fixed, by counting
|
||||
* cells from `start` up to `cursorCol`.
|
||||
*/
|
||||
function clipAroundCursor(
|
||||
line: string,
|
||||
cursorCol: number,
|
||||
visibleCells: number,
|
||||
pastes?: ReadonlyMap<number, PasteEntry>,
|
||||
): Viewport {
|
||||
// `cursorCol` is between 0 and line.length (inclusive). The cursor
|
||||
// visually sits BEFORE the char at line[cursorCol] (or after the
|
||||
// last char when cursorCol === line.length).
|
||||
// We want both the char at the cursor (if any) AND a cell of cursor
|
||||
// padding visible.
|
||||
|
||||
// Budget — leave 1 cell for each marker we may need.
|
||||
let budget = visibleCells;
|
||||
// Right marker: needed if we don't reach end of line.
|
||||
// Left marker: needed if start > 0.
|
||||
// We don't know in advance, so allocate conservatively: -2 cells.
|
||||
const reservedForMarkers = 2;
|
||||
budget = Math.max(1, budget - reservedForMarkers);
|
||||
|
||||
// Try to keep cursor roughly centred. Start by aiming `start` ~
|
||||
// halfway behind cursorCol.
|
||||
const halfBudget = Math.floor(budget / 2);
|
||||
|
||||
// Walk left from cursor, accumulating cells, until we've spent
|
||||
// halfBudget OR hit the start of the line.
|
||||
let start = cursorCol;
|
||||
let leftCells = 0;
|
||||
while (start > 0 && leftCells < halfBudget) {
|
||||
const cw = charCellsAt(line, start - 1, pastes);
|
||||
if (leftCells + cw > halfBudget) break;
|
||||
start--;
|
||||
leftCells += cw;
|
||||
}
|
||||
|
||||
// Walk right from cursor, filling the remaining budget. We always
|
||||
// include a cell for the cursor itself if line[cursorCol] exists
|
||||
// (since the cursor block covers that char). At end-of-line we
|
||||
// include a phantom cell of cursor space.
|
||||
const rightBudget = budget - leftCells;
|
||||
let end = cursorCol;
|
||||
let rightCells = 0;
|
||||
// Include the char at the cursor (1 or 2 cells depending on width)
|
||||
// if there is one.
|
||||
const cursorChar = cursorCol < line.length ? charCellsAt(line, cursorCol, pastes) : 1;
|
||||
if (rightBudget >= cursorChar) {
|
||||
if (cursorCol < line.length) end = cursorCol + 1;
|
||||
rightCells = cursorChar;
|
||||
while (end < line.length && rightCells < rightBudget) {
|
||||
const cw = charCellsAt(line, end, pastes);
|
||||
if (rightCells + cw > rightBudget) break;
|
||||
rightCells += cw;
|
||||
end++;
|
||||
}
|
||||
}
|
||||
|
||||
// If we have leftover right-budget and there's still room on the
|
||||
// left, expand leftwards more (cursor stays towards the right
|
||||
// edge but more left context is shown — common when typing at
|
||||
// end of a long line).
|
||||
let extraLeftBudget = rightBudget - rightCells;
|
||||
while (start > 0 && extraLeftBudget > 0) {
|
||||
const cw = charCellsAt(line, start - 1, pastes);
|
||||
if (cw > extraLeftBudget) break;
|
||||
start--;
|
||||
leftCells += cw;
|
||||
extraLeftBudget -= cw;
|
||||
}
|
||||
|
||||
const hiddenLeft = start > 0;
|
||||
const hiddenRight = end < line.length;
|
||||
const segments = textToSegments(line.slice(start, end), pastes);
|
||||
// Cursor cell relative to the start of the slice. Markers are
|
||||
// rendered separately by the caller — they don't shift the
|
||||
// segment-relative offset so we don't add them here.
|
||||
const cursorCell = stringCells(line.slice(start, cursorCol), pastes);
|
||||
return { segments, cursorCell, hiddenLeft, hiddenRight };
|
||||
}
|
||||
|
||||
function charCellsAt(line: string, idx: number, pastes?: ReadonlyMap<number, PasteEntry>): number {
|
||||
const ch = line[idx]!;
|
||||
const id = decodePasteSentinel(ch);
|
||||
if (id !== null) {
|
||||
const entry = pastes?.get(id);
|
||||
return pasteSentinelLabel(id, entry).length;
|
||||
}
|
||||
return charCells(ch);
|
||||
}
|
||||
|
||||
/**
|
||||
* Walk the string and split it into text/paste segments. Pure —
|
||||
* doesn't allocate per-character objects (text runs accumulate in a
|
||||
* single segment). Used by both the fast and clipped paths.
|
||||
*/
|
||||
export function textToSegments(line: string, pastes?: ReadonlyMap<number, PasteEntry>): Segment[] {
|
||||
const out: Segment[] = [];
|
||||
let buf = "";
|
||||
const flushBuf = () => {
|
||||
if (buf.length > 0) {
|
||||
out.push({ kind: "text", text: buf });
|
||||
buf = "";
|
||||
}
|
||||
};
|
||||
for (let i = 0; i < line.length; i++) {
|
||||
const ch = line[i]!;
|
||||
const id = decodePasteSentinel(ch);
|
||||
if (id !== null) {
|
||||
flushBuf();
|
||||
const label = pasteSentinelLabel(id, pastes?.get(id));
|
||||
out.push({ kind: "paste", id, label });
|
||||
} else {
|
||||
buf += ch;
|
||||
}
|
||||
}
|
||||
flushBuf();
|
||||
return out;
|
||||
}
|
||||
+20
-695
@@ -1,695 +1,20 @@
|
||||
import { spawnSync } from "node:child_process";
|
||||
import type { CacheFirstLoop } from "../../loop.js";
|
||||
import type { InspectionReport } from "../../mcp/inspect.js";
|
||||
import { PROJECT_MEMORY_FILE, memoryEnabled, readProjectMemory } from "../../project-memory.js";
|
||||
import { deleteSession, listSessions } from "../../session.js";
|
||||
import { DEEPSEEK_CONTEXT_TOKENS, DEFAULT_CONTEXT_TOKENS } from "../../telemetry.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;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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".
|
||||
*/
|
||||
codeUndo?: () => 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;
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
|
||||
export interface McpServerSummary {
|
||||
/** Short label shown in the `/mcp` output (server namespace or "anon"). */
|
||||
label: string;
|
||||
/** Original --mcp spec string. */
|
||||
spec: string;
|
||||
/** Count of tools bridged into the Reasonix registry from this server. */
|
||||
toolCount: number;
|
||||
/** Full inspection snapshot — used for the resources + prompts sections. */
|
||||
report: InspectionReport;
|
||||
}
|
||||
|
||||
/**
|
||||
* Slash command registry. Drives `/help`, the on-type suggestion
|
||||
* popup (`SlashSuggestions`), and auto-complete. Kept as data rather
|
||||
* than derived from the `handleSlash` switch so summaries can be
|
||||
* user-facing rather than code comments.
|
||||
*
|
||||
* `contextual` gates commands that only make sense in certain modes:
|
||||
* - `"code"` — only show when the TUI is running `reasonix code`
|
||||
* - absent → always shown
|
||||
*/
|
||||
export interface SlashCommandSpec {
|
||||
cmd: string;
|
||||
summary: string;
|
||||
contextual?: "code";
|
||||
/** If the command takes args, hint text shown after the name. */
|
||||
argsHint?: string;
|
||||
}
|
||||
|
||||
export const SLASH_COMMANDS: readonly SlashCommandSpec[] = [
|
||||
{ cmd: "help", summary: "show the full command reference" },
|
||||
{ cmd: "status", summary: "current model, flags, context, session" },
|
||||
{
|
||||
cmd: "preset",
|
||||
argsHint: "<fast|smart|max>",
|
||||
summary: "one-tap model + harvest + branch bundle",
|
||||
},
|
||||
{ cmd: "model", argsHint: "<id>", summary: "switch DeepSeek model id" },
|
||||
{ cmd: "harvest", argsHint: "[on|off]", summary: "toggle Pillar-2 plan-state extraction" },
|
||||
{ cmd: "branch", argsHint: "<N|off>", summary: "run N parallel samples per turn (N>=2)" },
|
||||
{ cmd: "mcp", summary: "list MCP servers + tools attached to this session" },
|
||||
{ cmd: "tool", argsHint: "[N]", summary: "dump full output of the Nth tool call (1=latest)" },
|
||||
{ cmd: "memory", summary: "show the project's REASONIX.md (pinned into the system prompt)" },
|
||||
{ cmd: "think", summary: "dump the last turn's full R1 reasoning (reasoner only)" },
|
||||
{ cmd: "retry", summary: "truncate & resend your last message (fresh sample)" },
|
||||
{ cmd: "compact", argsHint: "[cap]", summary: "shrink oversized tool results in the log" },
|
||||
{ cmd: "sessions", summary: "list saved sessions (current marked with ▸)" },
|
||||
{ cmd: "forget", summary: "delete the current session from disk" },
|
||||
{ cmd: "setup", summary: "reminds you to exit and run `reasonix setup`" },
|
||||
{ cmd: "clear", summary: "clear visible scrollback only (log/context kept)" },
|
||||
{ cmd: "new", summary: "start a fresh conversation (clear context + scrollback)" },
|
||||
{ cmd: "exit", summary: "quit the TUI" },
|
||||
// Code-mode only
|
||||
{ cmd: "apply", summary: "commit pending edit blocks to disk", contextual: "code" },
|
||||
{ cmd: "discard", summary: "drop pending edit blocks without writing", contextual: "code" },
|
||||
{ cmd: "undo", summary: "roll back the last applied edit batch", contextual: "code" },
|
||||
{
|
||||
cmd: "commit",
|
||||
argsHint: '"msg"',
|
||||
summary: "git add -A && git commit -m ...",
|
||||
contextual: "code",
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
* Filter the registry by a prefix string (without the leading `/`).
|
||||
* Empty prefix returns the full non-contextual list (plus code-mode
|
||||
* entries when `codeMode` is true). Case-insensitive.
|
||||
*/
|
||||
export function suggestSlashCommands(prefix: string, codeMode = false): SlashCommandSpec[] {
|
||||
const p = prefix.toLowerCase();
|
||||
return SLASH_COMMANDS.filter((c) => {
|
||||
if (c.contextual === "code" && !codeMode) return false;
|
||||
return c.cmd.startsWith(p);
|
||||
});
|
||||
}
|
||||
|
||||
export function parseSlash(text: string): { cmd: string; args: string[] } | null {
|
||||
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,
|
||||
ctx: SlashContext = {},
|
||||
): SlashResult {
|
||||
switch (cmd) {
|
||||
case "exit":
|
||||
case "quit":
|
||||
return { exit: true };
|
||||
|
||||
case "clear":
|
||||
return {
|
||||
clear: true,
|
||||
info: "▸ cleared visible scrollback only. Context (message log) is intact — next turn still sees everything. Use /new to start fresh, or /forget to delete the session entirely.",
|
||||
};
|
||||
|
||||
case "new":
|
||||
case "reset": {
|
||||
// Actually drop the in-memory log + rewrite the session file
|
||||
// so the NEXT call has no prior context. Keeps session name,
|
||||
// model, and other config — just the conversation is reset.
|
||||
const { dropped } = loop.clearLog();
|
||||
return {
|
||||
clear: true,
|
||||
info: `▸ new conversation — dropped ${dropped} message(s) from context. Same session, fresh slate.`,
|
||||
};
|
||||
}
|
||||
|
||||
case "help":
|
||||
case "?":
|
||||
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",
|
||||
" /mcp list MCP servers + tools attached to this session",
|
||||
" /setup (exit + reconfigure) → run `reasonix setup`",
|
||||
" /compact [cap] shrink large tool results in history (default 4k/result)",
|
||||
" /think dump the most recent turn's full R1 reasoning (reasoner only)",
|
||||
" /tool [N] list tool calls (or dump full output of #N, 1=most recent)",
|
||||
" /memory show the project's REASONIX.md (pinned into the system prompt)",
|
||||
" /retry truncate & resend your last message (fresh sample from the model)",
|
||||
" /apply (code mode) commit the pending edit blocks to disk",
|
||||
" /discard (code mode) drop pending edits without writing",
|
||||
" /undo (code mode) roll back the last applied edit batch",
|
||||
' /commit "msg" (code mode) git add -A && git commit -m "msg"',
|
||||
" /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",
|
||||
"",
|
||||
"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 "mcp": {
|
||||
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[] = [];
|
||||
for (const s of servers) {
|
||||
const { report } = s;
|
||||
const serverName = report.serverInfo.name || "(unknown)";
|
||||
const serverVer = report.serverInfo.version ? ` v${report.serverInfo.version}` : "";
|
||||
lines.push(`[${s.label}] ${serverName}${serverVer} — ${s.spec}`);
|
||||
lines.push(` tools ${s.toolCount}`);
|
||||
appendSection(lines, "resources", report.resources);
|
||||
appendSection(lines, "prompts ", report.prompts);
|
||||
lines.push("");
|
||||
}
|
||||
lines.push(
|
||||
"Chat mode consumes tools today; resources+prompts are surfaced here for awareness.",
|
||||
);
|
||||
lines.push(
|
||||
"Full catalog: `reasonix mcp list` · deeper diagnosis: `reasonix mcp inspect <spec>`.",
|
||||
);
|
||||
return { info: lines.join("\n") };
|
||||
}
|
||||
// Fallback — older path when the TUI hasn't populated `mcpServers`.
|
||||
const lines: string[] = [];
|
||||
if (specs.length > 0) {
|
||||
lines.push(`MCP servers (${specs.length}):`);
|
||||
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") };
|
||||
}
|
||||
|
||||
case "setup":
|
||||
return {
|
||||
info:
|
||||
"To reconfigure (preset, MCP servers, API key), exit this chat and run " +
|
||||
"`reasonix setup`. Changes take effect on next launch.",
|
||||
};
|
||||
|
||||
case "retry": {
|
||||
const prev = loop.retryLastUser();
|
||||
if (!prev) {
|
||||
return {
|
||||
info: "nothing to retry — no prior user message in this session's log.",
|
||||
};
|
||||
}
|
||||
const preview = prev.length > 80 ? `${prev.slice(0, 80)}…` : prev;
|
||||
return {
|
||||
info: `▸ retrying: "${preview}"`,
|
||||
resubmit: prev,
|
||||
};
|
||||
}
|
||||
|
||||
case "memory": {
|
||||
if (!memoryEnabled()) {
|
||||
return {
|
||||
info: "project memory is disabled (REASONIX_MEMORY=off in env). Unset the var to re-enable; no REASONIX.md will be pinned in the meantime.",
|
||||
};
|
||||
}
|
||||
if (!ctx.memoryRoot) {
|
||||
return {
|
||||
info: "no project root on this session — `/memory` needs a working directory to resolve REASONIX.md from.",
|
||||
};
|
||||
}
|
||||
const mem = readProjectMemory(ctx.memoryRoot);
|
||||
if (!mem) {
|
||||
return {
|
||||
info: [
|
||||
`no ${PROJECT_MEMORY_FILE} in ${ctx.memoryRoot}.`,
|
||||
"",
|
||||
"Project memory is an optional file you pin notes into — project conventions,",
|
||||
"things the model keeps forgetting, domain glossary, setup gotchas. When present,",
|
||||
"its contents are appended to the system prompt (the immutable-prefix region)",
|
||||
"so every turn sees it without eating per-turn context, and the prefix cache stays",
|
||||
"warm as long as the file is stable.",
|
||||
"",
|
||||
`Create it with: echo "# Project notes for Reasonix" > ${PROJECT_MEMORY_FILE}`,
|
||||
"Re-launch (or `/new`) to pick up changes — the prefix is hashed at session start.",
|
||||
].join("\n"),
|
||||
};
|
||||
}
|
||||
const header = mem.truncated
|
||||
? `▸ project memory: ${mem.path} (${mem.originalChars.toLocaleString()} chars, truncated for the prefix)`
|
||||
: `▸ project memory: ${mem.path} (${mem.originalChars.toLocaleString()} chars)`;
|
||||
return {
|
||||
info: [
|
||||
header,
|
||||
"",
|
||||
mem.content,
|
||||
"",
|
||||
"Changes take effect on the next launch or `/new` — the system prompt is hashed once per session to keep the prefix cache warm.",
|
||||
].join("\n"),
|
||||
};
|
||||
}
|
||||
|
||||
case "think":
|
||||
case "reasoning": {
|
||||
const raw = loop.scratch.reasoning;
|
||||
if (!raw || !raw.trim()) {
|
||||
return {
|
||||
info:
|
||||
"no reasoning cached. `/think` shows the full R1 thought for the most recent turn — " +
|
||||
"only `deepseek-reasoner` produces it, and only once the turn completes.",
|
||||
};
|
||||
}
|
||||
return { info: `↳ full thinking (${raw.length} chars):\n\n${raw.trim()}` };
|
||||
}
|
||||
|
||||
case "tool": {
|
||||
// EventLog truncates tool results at 400 chars for display. When
|
||||
// the user wants to check what the model actually read (e.g. to
|
||||
// verify it isn't hallucinating a file's contents), they need
|
||||
// the full text. `/tool` is the escape hatch.
|
||||
const history = ctx.toolHistory?.() ?? [];
|
||||
if (history.length === 0) {
|
||||
return {
|
||||
info:
|
||||
"no tool calls yet in this session. `/tool` lists them once the model has actually " +
|
||||
"used a tool; `/tool N` dumps the full (untruncated) output of the Nth-most-recent.",
|
||||
};
|
||||
}
|
||||
const raw = (args[0] ?? "").toLowerCase();
|
||||
if (raw === "" || raw === "list" || raw === "ls") {
|
||||
return { info: formatToolList(history) };
|
||||
}
|
||||
const n = Number.parseInt(raw, 10);
|
||||
if (!Number.isFinite(n) || n < 1) {
|
||||
return {
|
||||
info: "usage: /tool [N] (no arg → list; N=1 → most recent result in full, N=2 → previous, …)",
|
||||
};
|
||||
}
|
||||
if (n > history.length) {
|
||||
return {
|
||||
info: `only ${history.length} tool call(s) in history — asked for #${n}. Try /tool with no arg to see the list.`,
|
||||
};
|
||||
}
|
||||
const entry = history[history.length - n];
|
||||
if (!entry) {
|
||||
return { info: `could not read tool call #${n}` };
|
||||
}
|
||||
return {
|
||||
info: `↳ tool<${entry.toolName}> #${n} (${entry.text.length} chars):\n\n${entry.text}`,
|
||||
};
|
||||
}
|
||||
|
||||
case "undo": {
|
||||
if (!ctx.codeUndo) {
|
||||
return {
|
||||
info: "/undo is only available inside `reasonix code` — chat mode doesn't apply edits.",
|
||||
};
|
||||
}
|
||||
return { info: ctx.codeUndo() };
|
||||
}
|
||||
|
||||
case "apply": {
|
||||
if (!ctx.codeApply) {
|
||||
return {
|
||||
info: "/apply is only available inside `reasonix code` (nothing to apply here).",
|
||||
};
|
||||
}
|
||||
return { info: ctx.codeApply() };
|
||||
}
|
||||
|
||||
case "discard": {
|
||||
if (!ctx.codeDiscard) {
|
||||
return {
|
||||
info: "/discard is only available inside `reasonix code`.",
|
||||
};
|
||||
}
|
||||
return { info: ctx.codeDiscard() };
|
||||
}
|
||||
|
||||
case "commit": {
|
||||
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);
|
||||
}
|
||||
|
||||
case "compact": {
|
||||
// Manual companion to the automatic heal-on-load. Re-applies
|
||||
// truncation with a tighter cap (4k chars 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 >= 500 ? tight : 4000;
|
||||
const { healedCount, charsSaved } = loop.compact(cap);
|
||||
if (healedCount === 0) {
|
||||
return {
|
||||
info: `▸ nothing to compact — no tool result in history exceeds ${cap.toLocaleString()} chars.`,
|
||||
};
|
||||
}
|
||||
return {
|
||||
info: `▸ compacted ${healedCount} tool result(s), saved ${charsSaved.toLocaleString()} chars (~${Math.round(charsSaved / 4).toLocaleString()} tokens). Session file rewritten.`,
|
||||
};
|
||||
}
|
||||
|
||||
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;
|
||||
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 lines = [
|
||||
` model ${loop.model}`,
|
||||
` flags harvest=${loop.harvestEnabled ? "on" : "off"} · branch=${branchBudget > 1 ? branchBudget : "off"} · stream=${loop.stream ? "on" : "off"}`,
|
||||
ctxLine,
|
||||
mcpLine,
|
||||
sessionLine,
|
||||
];
|
||||
if (pendingLine) lines.push(pendingLine);
|
||||
return { info: lines.join("\n") };
|
||||
}
|
||||
|
||||
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)` };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Render a section (resources / prompts) of an MCP inspection into a
|
||||
* compact "name count items" form, collapsing when unsupported.
|
||||
* Names-only — descriptions and full metadata live in
|
||||
* `reasonix mcp inspect`, which is purpose-built for the deep view.
|
||||
*/
|
||||
function appendSection(
|
||||
lines: string[],
|
||||
label: string,
|
||||
section:
|
||||
| { supported: true; items: Array<{ name: string }> }
|
||||
| { supported: false; reason: string }
|
||||
| undefined,
|
||||
): void {
|
||||
if (!section || !section.supported) {
|
||||
lines.push(
|
||||
` ${label.trim()} ${section?.supported === false ? "(not supported)" : "(none)"}`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
const names = section.items.map((i) => i.name);
|
||||
if (names.length === 0) {
|
||||
lines.push(` ${label.trim()} (none)`);
|
||||
return;
|
||||
}
|
||||
const head = names.slice(0, 5).join(", ");
|
||||
const more = names.length > 5 ? ` +${names.length - 5} more` : "";
|
||||
lines.push(` ${label.trim()} ${names.length} [${head}${more}]`);
|
||||
}
|
||||
|
||||
function formatToolList(history: Array<{ toolName: string; text: string }>): string {
|
||||
const total = history.length;
|
||||
const header = `Tool calls in this session (${total}, most recent first):`;
|
||||
// Show the 10 most recent. Older ones are rarely what the user
|
||||
// wants — and the help footer tells them how to reach any entry
|
||||
// by index if they do.
|
||||
const shown = Math.min(total, 10);
|
||||
const lines: string[] = [header];
|
||||
for (let i = 0; i < shown; i++) {
|
||||
const entry = history[total - 1 - i];
|
||||
if (!entry) continue;
|
||||
const idx = i + 1; // 1-based from most recent
|
||||
const flat = entry.text.replace(/\s+/g, " ").trim();
|
||||
const preview = flat.length > 80 ? `${flat.slice(0, 80)}…` : flat;
|
||||
const name = entry.toolName.length > 24 ? `${entry.toolName.slice(0, 23)}…` : entry.toolName;
|
||||
lines.push(
|
||||
` #${String(idx).padStart(2)} ${name.padEnd(24)} ${String(entry.text.length).padStart(6)} chars ${preview}`,
|
||||
);
|
||||
}
|
||||
if (total > shown) {
|
||||
lines.push(` … (${total - shown} earlier, reach with /tool N)`);
|
||||
}
|
||||
lines.push("");
|
||||
lines.push("View full output: /tool N (N=1 → most recent)");
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
function compactNum(n: number): string {
|
||||
if (n < 1000) return String(n);
|
||||
const k = n / 1000;
|
||||
return k >= 100 ? `${Math.round(k)}k` : `${k.toFixed(1)}k`;
|
||||
}
|
||||
|
||||
function stripOuterQuotes(s: string): string {
|
||||
if (s.length >= 2 && s.startsWith('"') && s.endsWith('"')) {
|
||||
return s.slice(1, -1);
|
||||
}
|
||||
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.).
|
||||
*/
|
||||
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.
|
||||
*/
|
||||
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)";
|
||||
}
|
||||
// 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,242 @@
|
||||
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: "loop",
|
||||
argsHint: "<5s..6h> <prompt> · stop · (no args = status)",
|
||||
summary: "auto-resubmit <prompt> every <interval> until you type something / Esc / /loop stop",
|
||||
},
|
||||
{ cmd: "exit", summary: "quit the TUI" },
|
||||
// Code-mode only
|
||||
{
|
||||
cmd: "apply",
|
||||
argsHint: "[N|N,M|N-M]",
|
||||
summary:
|
||||
"commit pending edit blocks to disk (no arg → all; `1`, `1,3`, or `1-4` → that subset, rest stay pending)",
|
||||
contextual: "code",
|
||||
},
|
||||
{
|
||||
cmd: "discard",
|
||||
argsHint: "[N|N,M|N-M]",
|
||||
summary: "drop pending edit blocks without writing (no arg → all; indices → that subset)",
|
||||
contextual: "code",
|
||||
},
|
||||
{
|
||||
cmd: "walk",
|
||||
summary:
|
||||
"step through pending edits one block at a time (git-add-p style: y/n per block, a apply rest, A flip AUTO)",
|
||||
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|yolo]",
|
||||
summary:
|
||||
"edit-gate: review (queue) · auto (apply+undo) · yolo (apply+auto-shell). Shift+Tab cycles.",
|
||||
contextual: "code",
|
||||
argCompleter: ["review", "auto", "yolo"],
|
||||
},
|
||||
{ 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,218 @@
|
||||
import { formatDuration, formatLoopStatus, parseLoopCommand } from "../../loop.js";
|
||||
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.",
|
||||
" @https://... fetch the URL, strip HTML, inline under [Referenced URLs].",
|
||||
" Cached per session — same URL twice fetches once.",
|
||||
" !<cmd> run <cmd> as shell in the sandbox root; output goes into context",
|
||||
" so the model sees it next turn. No allowlist gate.",
|
||||
" #<note> append <note> to <project>/REASONIX.md (committable, team-shared).",
|
||||
" #g <note> append <note> to ~/.reasonix/REASONIX.md (global, never committed).",
|
||||
" Both pin into the immutable prefix every future session.",
|
||||
" Use `\\#literal` if you actually want a `#` heading sent to the model.",
|
||||
"",
|
||||
"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 [N|1,3|1-4] (code mode) commit pending edit blocks (no arg → all; index → subset)",
|
||||
" /discard [N|1,3|1-4] (code mode) drop pending edits (no arg → all; index → subset)",
|
||||
" /walk (code mode) step through pending edits one block at a time (y/n per block, a apply rest, A flip AUTO)",
|
||||
" /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|yolo] (code mode) review = queue · auto = apply+undo banner · yolo = apply+auto-shell. Shift+Tab cycles all three.",
|
||||
" /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)",
|
||||
" /loop <interval> <prompt> auto-resubmit <prompt> every <interval> (5s..6h). /loop stop · type anything to cancel.",
|
||||
" /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",
|
||||
"",
|
||||
"Quick memory:",
|
||||
" #<note> append <note> to <project>/REASONIX.md (committable).",
|
||||
" Example: #findByEmail must be case-insensitive",
|
||||
" #g <note> append <note> to ~/.reasonix/REASONIX.md (global, never committed).",
|
||||
" Example: #g always run pnpm not npm",
|
||||
" Both pin into every future session's prefix. Faster than /memory.",
|
||||
" Use `\\#text` to send a literal `#text` to the model.",
|
||||
"",
|
||||
"File references (code mode):",
|
||||
" @path/to/file inline file content under [Referenced files] on send.",
|
||||
" Type `@` to open the picker (↑↓ navigate, Tab/Enter pick).",
|
||||
"",
|
||||
"URL references:",
|
||||
" @https://example.com fetch the URL, strip HTML, inline under [Referenced URLs].",
|
||||
" Same URL twice in one session fetches once (in-mem cache).",
|
||||
" Trailing sentence punctuation (./,/)) is stripped automatically.",
|
||||
"",
|
||||
"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,
|
||||
};
|
||||
};
|
||||
|
||||
const loop: SlashHandler = (args, _loop, ctx) => {
|
||||
if (!ctx.startLoop || !ctx.stopLoop || !ctx.getLoopStatus) {
|
||||
return {
|
||||
info: "/loop is only available in the interactive TUI (not in run/replay).",
|
||||
};
|
||||
}
|
||||
const cmd = parseLoopCommand(args);
|
||||
if (cmd.kind === "error") return { info: cmd.message };
|
||||
if (cmd.kind === "stop") {
|
||||
const wasActive = ctx.getLoopStatus() !== null;
|
||||
ctx.stopLoop();
|
||||
return {
|
||||
info: wasActive ? "▸ loop stopped." : "no active loop to stop.",
|
||||
};
|
||||
}
|
||||
if (cmd.kind === "status") {
|
||||
const status = ctx.getLoopStatus();
|
||||
if (!status) {
|
||||
return {
|
||||
info:
|
||||
"no active loop. Start one with `/loop <interval> <prompt>` (e.g. /loop 30s npm test).\n" +
|
||||
"Cancels on: /loop stop · Esc · /clear · /new · any user-typed prompt.",
|
||||
};
|
||||
}
|
||||
return { info: `▸ ${formatLoopStatus(status.prompt, status.nextFireMs, status.iter)}` };
|
||||
}
|
||||
// kind === "start"
|
||||
ctx.startLoop(cmd.intervalMs, cmd.prompt);
|
||||
return {
|
||||
info: `▸ loop started — re-submitting "${cmd.prompt}" every ${formatDuration(
|
||||
cmd.intervalMs,
|
||||
)}. Type anything (or /loop stop) to cancel.`,
|
||||
};
|
||||
};
|
||||
|
||||
export const handlers: Record<string, SlashHandler> = {
|
||||
exit,
|
||||
quit: exit,
|
||||
clear,
|
||||
new: resetLog,
|
||||
reset: resetLog,
|
||||
keys,
|
||||
help,
|
||||
"?": help,
|
||||
setup,
|
||||
retry,
|
||||
loop,
|
||||
};
|
||||
@@ -0,0 +1,182 @@
|
||||
import type { EditMode } from "../../../../config.js";
|
||||
import { parseEditIndices } from "../../edit-history.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).",
|
||||
};
|
||||
}
|
||||
const parsed = parseIndicesArg(args, ctx.pendingEditCount ?? 0);
|
||||
if ("error" in parsed) return { info: `/apply: ${parsed.error}` };
|
||||
return { info: ctx.codeApply(parsed.indices) };
|
||||
};
|
||||
|
||||
const discard: SlashHandler = (args, _loop, ctx) => {
|
||||
if (!ctx.codeDiscard) {
|
||||
return {
|
||||
info: "/discard is only available inside `reasonix code`.",
|
||||
};
|
||||
}
|
||||
const parsed = parseIndicesArg(args, ctx.pendingEditCount ?? 0);
|
||||
if ("error" in parsed) return { info: `/discard: ${parsed.error}` };
|
||||
return { info: ctx.codeDiscard(parsed.indices) };
|
||||
};
|
||||
|
||||
/**
|
||||
* Bridge between the `args: string[]` shape commander gives us and the
|
||||
* comma-separated index syntax users actually type ("/apply 1,3-4").
|
||||
* The TUI's slash parser splits on whitespace, so `1,3-4` arrives as
|
||||
* `["1,3-4"]` and `1, 3, 4` arrives as `["1,", "3,", "4"]`. Re-joining
|
||||
* with commas + delegating to `parseEditIndices` handles both shapes.
|
||||
*
|
||||
* Empty `args` → `{ indices: [] }` (caller treats as "all").
|
||||
*/
|
||||
function parseIndicesArg(
|
||||
args: readonly string[],
|
||||
max: number,
|
||||
): { indices: readonly number[] } | { error: string } {
|
||||
const raw = args.join(",").replace(/,+/g, ",").replace(/^,|,$/g, "");
|
||||
if (!raw) return { indices: [] };
|
||||
const parsed = parseEditIndices(raw, max);
|
||||
if ("error" in parsed) return { error: parsed.error };
|
||||
return { indices: parsed.ok };
|
||||
}
|
||||
|
||||
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 === "yolo") target = "yolo";
|
||||
else if (raw === "") {
|
||||
// Bare /mode cycles review → auto → yolo → review, mirroring
|
||||
// Shift+Tab. Users who just want to see current mode without
|
||||
// flipping can read /status.
|
||||
target = current === "review" ? "auto" : current === "auto" ? "yolo" : "review";
|
||||
} else {
|
||||
return {
|
||||
info: "usage: /mode <review|auto|yolo> (Shift+Tab also cycles)",
|
||||
};
|
||||
}
|
||||
ctx.setEditMode(target);
|
||||
const banner =
|
||||
target === "yolo"
|
||||
? "▸ edit mode: YOLO — edits AND shell commands auto-run with no prompt. /undo still rolls back edits. Use carefully."
|
||||
: target === "auto"
|
||||
? "▸ edit mode: AUTO — edits apply immediately; press u within 5s to undo, or /undo later. Shell commands still ask."
|
||||
: "▸ edit mode: review — edits queue for /apply (or y) / /discard (or n)";
|
||||
return { info: banner };
|
||||
};
|
||||
|
||||
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);
|
||||
};
|
||||
|
||||
const walk: SlashHandler = (_args, _loop, ctx) => {
|
||||
if (!ctx.startWalkthrough) {
|
||||
return {
|
||||
info: "/walk is only available inside `reasonix code`.",
|
||||
};
|
||||
}
|
||||
return { info: ctx.startWalkthrough() };
|
||||
};
|
||||
|
||||
export const handlers: Record<string, SlashHandler> = {
|
||||
undo,
|
||||
history,
|
||||
show,
|
||||
apply,
|
||||
discard,
|
||||
plan,
|
||||
"apply-plan": applyPlan,
|
||||
applyplan: applyPlan,
|
||||
mode,
|
||||
commit,
|
||||
walk,
|
||||
};
|
||||
@@ -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,194 @@
|
||||
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 === "yolo"
|
||||
? " mode YOLO — edits + shell auto-run with no prompt (/undo still rolls back · Shift+Tab to flip)"
|
||||
: 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,321 @@
|
||||
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 [N|N,M|N-M]` — commits pending edit blocks to
|
||||
* disk. Returns a report of what landed. With no `indices` (or `[]`),
|
||||
* applies every pending block; with explicit 1-based indices, applies
|
||||
* just those and leaves the rest pending. Absent → `/apply` replies
|
||||
* "nothing pending" or "not available outside code mode".
|
||||
*/
|
||||
codeApply?: (indices?: readonly number[]) => string;
|
||||
/**
|
||||
* Callback for `/discard [N|N,M|N-M]` — drops the pending edit blocks
|
||||
* without touching disk. Same indices semantics as `codeApply`: empty
|
||||
* means "drop all pending"; explicit indices drop just those.
|
||||
*/
|
||||
codeDiscard?: (indices?: readonly number[]) => 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;
|
||||
/**
|
||||
* Start a recurring auto-submit. Called by `/loop <interval> <prompt>`.
|
||||
* Replaces any active loop. Caller (App.tsx) owns the timer + visible
|
||||
* countdown; the slash handler just kicks it off.
|
||||
*/
|
||||
startLoop?: (intervalMs: number, prompt: string) => void;
|
||||
/** Stop the active loop. No-op if none. */
|
||||
stopLoop?: () => void;
|
||||
/**
|
||||
* Snapshot of the active loop, for the `/loop` (no-args) status
|
||||
* branch. Returns null when no loop is active.
|
||||
*/
|
||||
getLoopStatus?: () => {
|
||||
prompt: string;
|
||||
intervalMs: number;
|
||||
iter: number;
|
||||
nextFireMs: number;
|
||||
} | null;
|
||||
/**
|
||||
* Mount the `/walk` per-block walkthrough modal over the current
|
||||
* pendingEdits queue. Returns the info text to surface (explanation
|
||||
* when nothing's pending, or the started-walk banner).
|
||||
*/
|
||||
startWalkthrough?: () => string;
|
||||
}
|
||||
|
||||
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,462 @@
|
||||
/**
|
||||
* Raw stdin reader with our own CSI parser.
|
||||
*
|
||||
* Replaces Ink's `useInput` chain (which uses `parse-keypress` with a
|
||||
* 100 ms intra-sequence timeout that's too short for Windows ConPTY).
|
||||
* That timeout was the root cause of every keyboard regression we
|
||||
* shipped a patch for in 0.7.x — paste markers leaking into the
|
||||
* buffer, arrow keys not crossing newlines, Shift+Tab silently failing.
|
||||
*
|
||||
* Design:
|
||||
* - One reader owns `process.stdin`. We call `setRawMode(true)`,
|
||||
* register a single `data` listener, and emit parsed `KeyEvent`s
|
||||
* to subscribers. As long as no `useInput` is called inside the
|
||||
* Ink tree, Ink itself never attaches its own listener — we're
|
||||
* the sole consumer of stdin.
|
||||
*
|
||||
* - The state machine is tiny: idle → esc → csi/ss3 → idle, plus a
|
||||
* `paste` accumulator that swallows everything between `\x1b[200~`
|
||||
* and `\x1b[201~`. ESC ambiguity (standalone Esc vs. start of a
|
||||
* CSI) is resolved by a 250 ms timer — much longer than parse-
|
||||
* keypress's 100 ms, so ConPTY-split sequences land in the
|
||||
* correct branch.
|
||||
*
|
||||
* - We also recognise the ESC-stripped variants (`[A`, `[200~`) at
|
||||
* idle-state lookahead, in case ConPTY consumed the leading ESC
|
||||
* before we even saw it. That used to be a recovery layer in
|
||||
* `key-normalize.ts`; with this reader as the sole input source
|
||||
* it folds into the parser proper.
|
||||
*
|
||||
* - `paste` events carry the full content so the consumer can route
|
||||
* it through paste-sentinel registration without re-parsing.
|
||||
*/
|
||||
|
||||
import { stdin } from "node:process";
|
||||
|
||||
/**
|
||||
* Single keystroke event. Shape mirrors Ink's `(input, key)` callback
|
||||
* pair for migration ergonomics — consumers reading `key.upArrow`
|
||||
* etc. can keep doing so. `paste` is the one new field; consumers
|
||||
* that care about pastes (PromptInput) check it explicitly.
|
||||
*/
|
||||
export interface KeyEvent {
|
||||
/**
|
||||
* Printable character(s). Non-empty for normal typing, Ctrl+letter
|
||||
* (the letter goes here with `ctrl:true`), Alt+letter (with
|
||||
* `meta:true`), and bracketed paste content (with `paste:true`).
|
||||
* Always empty for control keystrokes like arrows / Enter / Esc.
|
||||
*/
|
||||
input: string;
|
||||
upArrow?: boolean;
|
||||
downArrow?: boolean;
|
||||
leftArrow?: boolean;
|
||||
rightArrow?: boolean;
|
||||
pageUp?: boolean;
|
||||
pageDown?: boolean;
|
||||
home?: boolean;
|
||||
end?: boolean;
|
||||
delete?: boolean;
|
||||
backspace?: boolean;
|
||||
tab?: boolean;
|
||||
return?: boolean;
|
||||
escape?: boolean;
|
||||
shift?: boolean;
|
||||
ctrl?: boolean;
|
||||
meta?: boolean;
|
||||
/**
|
||||
* True iff this event delivers bracketed-paste content. `input`
|
||||
* holds the entire paste; consumers MUST NOT re-interpret it as
|
||||
* keystrokes (e.g. a `\n` in a paste shouldn't fire submit).
|
||||
*/
|
||||
paste?: boolean;
|
||||
}
|
||||
|
||||
type Subscriber = (ev: KeyEvent) => void;
|
||||
|
||||
/** ESC ambiguity timeout. Long enough for ConPTY-split sequences. */
|
||||
const ESC_TIMEOUT_MS = 250;
|
||||
|
||||
/** Bracketed-paste markers (DECSET 2004). */
|
||||
const PASTE_START = "\x1b[200~";
|
||||
const PASTE_END = "\x1b[201~";
|
||||
/** ESC-stripped variants — ConPTY occasionally eats the leading ESC. */
|
||||
const PASTE_START_BARE = "[200~";
|
||||
const PASTE_END_BARE = "[201~";
|
||||
|
||||
/**
|
||||
* CSI tails (the bytes that follow `\x1b[`) we recognise and the
|
||||
* structured event each produces. Order doesn't matter — lookups
|
||||
* are exact-match.
|
||||
*/
|
||||
const CSI_TAIL_MAP: ReadonlyArray<{ tail: string; ev: KeyEvent }> = [
|
||||
{ tail: "A", ev: { input: "", upArrow: true } },
|
||||
{ tail: "B", ev: { input: "", downArrow: true } },
|
||||
{ tail: "C", ev: { input: "", rightArrow: true } },
|
||||
{ tail: "D", ev: { input: "", leftArrow: true } },
|
||||
{ tail: "H", ev: { input: "", home: true } },
|
||||
{ tail: "F", ev: { input: "", end: true } },
|
||||
{ tail: "1~", ev: { input: "", home: true } },
|
||||
{ tail: "4~", ev: { input: "", end: true } },
|
||||
{ tail: "5~", ev: { input: "", pageUp: true } },
|
||||
{ tail: "6~", ev: { input: "", pageDown: true } },
|
||||
{ tail: "3~", ev: { input: "", delete: true } },
|
||||
{ tail: "Z", ev: { input: "", shift: true, tab: true } },
|
||||
// modifyOtherKeys (xterm CSI > 4 ; 2 m) sequences for Enter with
|
||||
// modifiers. Only fired when App.tsx has enabled the mode at
|
||||
// startup; otherwise Shift+Enter stays indistinguishable from Enter.
|
||||
// Modifier encoding: 2=shift, 3=alt, 4=alt+shift, 5=ctrl,
|
||||
// 6=ctrl+shift, 7=ctrl+alt, 8=ctrl+alt+shift. Keycode 13 = Enter.
|
||||
{ tail: "27;2;13~", ev: { input: "", return: true, shift: true } },
|
||||
{ tail: "27;5;13~", ev: { input: "", return: true, ctrl: true } },
|
||||
{ tail: "27;6;13~", ev: { input: "", return: true, ctrl: true, shift: true } },
|
||||
// Kitty keyboard protocol — same idea, different envelope:
|
||||
// `\x1b[<keycode>;<mod>u`. Some terminals (kitty, recent Windows
|
||||
// Terminal previews) prefer this shape. Harmless to map here too.
|
||||
{ tail: "13;2u", ev: { input: "", return: true, shift: true } },
|
||||
{ tail: "13;5u", ev: { input: "", return: true, ctrl: true } },
|
||||
{ tail: "13;6u", ev: { input: "", return: true, ctrl: true, shift: true } },
|
||||
];
|
||||
|
||||
/** SS3 sequences (`\x1bO<letter>`) — some terminals send these for arrows. */
|
||||
const SS3_MAP: Record<string, KeyEvent> = {
|
||||
A: { input: "", upArrow: true },
|
||||
B: { input: "", downArrow: true },
|
||||
C: { input: "", rightArrow: true },
|
||||
D: { input: "", leftArrow: true },
|
||||
H: { input: "", home: true },
|
||||
F: { input: "", end: true },
|
||||
};
|
||||
|
||||
/**
|
||||
* Lookahead matcher for ESC-stripped sequences. When `chunk[i]` is
|
||||
* `[`, we check the bytes immediately after to see if they form a
|
||||
* recognised CSI tail. If so we emit the structured event and tell
|
||||
* the caller how many bytes to consume. Returns `null` when no
|
||||
* recognised tail starts here.
|
||||
*/
|
||||
function tryEscapelessCsi(chunk: string, i: number): { advance: number; ev: KeyEvent } | null {
|
||||
if (chunk[i] !== "[") return null;
|
||||
// Paste start as a special case (handled by caller).
|
||||
// Try each known tail.
|
||||
for (const entry of CSI_TAIL_MAP) {
|
||||
const candidate = `[${entry.tail}`;
|
||||
if (chunk.slice(i, i + candidate.length) === candidate) {
|
||||
return { advance: candidate.length, ev: entry.ev };
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Final byte of a CSI sequence is in the range `0x40` (`@`) –
|
||||
* `0x7E` (`~`). Anything else is a parameter / intermediate byte.
|
||||
*/
|
||||
function isCsiFinal(ch: string): boolean {
|
||||
const code = ch.charCodeAt(0);
|
||||
return code >= 0x40 && code <= 0x7e;
|
||||
}
|
||||
|
||||
/**
|
||||
* Look up the CSI event for a fully-assembled sequence (without the
|
||||
* leading `\x1b[`). Returns `null` if we don't recognise it — which
|
||||
* is fine, we just drop the bytes silently rather than insert them
|
||||
* into the buffer as garbage text.
|
||||
*/
|
||||
function lookupCsi(tail: string): KeyEvent | null {
|
||||
for (const entry of CSI_TAIL_MAP) {
|
||||
if (entry.tail === tail) return entry.ev;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export class StdinReader {
|
||||
private subscribers = new Set<Subscriber>();
|
||||
private state: "idle" | "esc" | "csi" | "ss3" | "paste" = "idle";
|
||||
/** Buffer for partial sequences across chunks. */
|
||||
private csiBuf = "";
|
||||
/** Buffer for paste content. */
|
||||
private pasteBuf = "";
|
||||
private escTimer: NodeJS.Timeout | null = null;
|
||||
private started = false;
|
||||
/** The actual `data` listener — kept as a field so `stop()` can detach it. */
|
||||
private listener: ((chunk: Buffer | string) => void) | null = null;
|
||||
|
||||
start(): void {
|
||||
if (this.started) return;
|
||||
if (!stdin.isTTY) {
|
||||
// Non-TTY (piped input). We can't run interactively — don't try.
|
||||
return;
|
||||
}
|
||||
stdin.setRawMode(true);
|
||||
stdin.setEncoding("utf8");
|
||||
stdin.resume();
|
||||
this.listener = (chunk) =>
|
||||
this.handleChunk(typeof chunk === "string" ? chunk : chunk.toString("utf8"));
|
||||
stdin.on("data", this.listener);
|
||||
this.started = true;
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
if (!this.started) return;
|
||||
if (this.listener) {
|
||||
stdin.off("data", this.listener);
|
||||
this.listener = null;
|
||||
}
|
||||
if (stdin.isTTY) {
|
||||
try {
|
||||
stdin.setRawMode(false);
|
||||
} catch {
|
||||
// setRawMode may throw if stdin is already closed; ignore.
|
||||
}
|
||||
}
|
||||
stdin.pause();
|
||||
this.cancelEscTimer();
|
||||
this.state = "idle";
|
||||
this.csiBuf = "";
|
||||
this.pasteBuf = "";
|
||||
this.started = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Subscribe to parsed key events. Returns an unsubscribe function.
|
||||
* Multiple subscribers are supported — every event fans out to all
|
||||
* of them; the React Context layer above uses one subscriber and
|
||||
* dispatches further to its own consumer list.
|
||||
*/
|
||||
subscribe(fn: Subscriber): () => void {
|
||||
this.subscribers.add(fn);
|
||||
return () => {
|
||||
this.subscribers.delete(fn);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Inject a chunk of bytes as if it came from stdin. Used by tests
|
||||
* to drive the parser without a real TTY.
|
||||
*/
|
||||
feed(chunk: string): void {
|
||||
this.handleChunk(chunk);
|
||||
}
|
||||
|
||||
private dispatch(ev: KeyEvent): void {
|
||||
for (const sub of this.subscribers) sub(ev);
|
||||
}
|
||||
|
||||
private cancelEscTimer(): void {
|
||||
if (this.escTimer) {
|
||||
clearTimeout(this.escTimer);
|
||||
this.escTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
private scheduleEscTimer(): void {
|
||||
this.cancelEscTimer();
|
||||
this.escTimer = setTimeout(() => {
|
||||
// Standalone Esc — no follow-up byte arrived in time.
|
||||
if (this.state === "esc") {
|
||||
this.state = "idle";
|
||||
this.dispatch({ input: "", escape: true });
|
||||
}
|
||||
}, ESC_TIMEOUT_MS);
|
||||
}
|
||||
|
||||
private handleChunk(chunk: string): void {
|
||||
this.cancelEscTimer();
|
||||
let i = 0;
|
||||
while (i < chunk.length) {
|
||||
// ── paste accumulator ──
|
||||
if (this.state === "paste") {
|
||||
// Look for end marker (with or without ESC).
|
||||
const endA = chunk.indexOf(PASTE_END, i);
|
||||
const endB = chunk.indexOf(PASTE_END_BARE, i);
|
||||
let endIdx = -1;
|
||||
let endLen = 0;
|
||||
if (endA !== -1 && (endB === -1 || endA <= endB)) {
|
||||
endIdx = endA;
|
||||
endLen = PASTE_END.length;
|
||||
} else if (endB !== -1) {
|
||||
endIdx = endB;
|
||||
endLen = PASTE_END_BARE.length;
|
||||
}
|
||||
if (endIdx === -1) {
|
||||
this.pasteBuf += chunk.slice(i);
|
||||
i = chunk.length;
|
||||
break;
|
||||
}
|
||||
this.pasteBuf += chunk.slice(i, endIdx);
|
||||
this.dispatch({ input: this.pasteBuf, paste: true });
|
||||
this.pasteBuf = "";
|
||||
this.state = "idle";
|
||||
i = endIdx + endLen;
|
||||
continue;
|
||||
}
|
||||
|
||||
// ── CSI accumulator ──
|
||||
if (this.state === "csi") {
|
||||
const ch = chunk[i]!;
|
||||
this.csiBuf += ch;
|
||||
if (isCsiFinal(ch)) {
|
||||
this.dispatchCsi(this.csiBuf);
|
||||
this.csiBuf = "";
|
||||
// Only reset state if `dispatchCsi` didn't already mutate it
|
||||
// (it transitions to `paste` for the `200~` start marker —
|
||||
// resetting here would clobber that and the paste content
|
||||
// would be parsed as keystrokes).
|
||||
if (this.state === "csi") this.state = "idle";
|
||||
}
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
|
||||
// ── SS3 single-byte tail ──
|
||||
if (this.state === "ss3") {
|
||||
const ev = SS3_MAP[chunk[i]!];
|
||||
if (ev) this.dispatch(ev);
|
||||
this.state = "idle";
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
|
||||
// ── ESC pending ──
|
||||
if (this.state === "esc") {
|
||||
const ch = chunk[i]!;
|
||||
if (ch === "[") {
|
||||
this.state = "csi";
|
||||
this.csiBuf = "";
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
if (ch === "O") {
|
||||
this.state = "ss3";
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
// ESC + any other char = Alt+key (rare; we still dispatch).
|
||||
this.dispatch({ input: ch, meta: true });
|
||||
this.state = "idle";
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
|
||||
// ── idle ──
|
||||
const ch = chunk[i]!;
|
||||
|
||||
if (ch === "\x1b") {
|
||||
this.state = "esc";
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
|
||||
// ESC-stripped paste-start (ConPTY): bare `[200~` at idle.
|
||||
if (chunk.slice(i, i + PASTE_START_BARE.length) === PASTE_START_BARE) {
|
||||
this.state = "paste";
|
||||
this.pasteBuf = "";
|
||||
i += PASTE_START_BARE.length;
|
||||
continue;
|
||||
}
|
||||
// ESC-stripped CSI tails — recover before treating `[` as text.
|
||||
const escapeless = tryEscapelessCsi(chunk, i);
|
||||
if (escapeless) {
|
||||
this.dispatch(escapeless.ev);
|
||||
i += escapeless.advance;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Single-byte control keys.
|
||||
// \r (CR, 0x0D) is Enter on every terminal in raw mode.
|
||||
// \n (LF, 0x0A) is what Ctrl+J emits — keep it distinct so the
|
||||
// multiline reducer can map it to "insert newline" instead of
|
||||
// "submit". Pastes containing \n still arrive via either the
|
||||
// bracketed-paste accumulator or a multi-byte printable chunk
|
||||
// that includes the newline; neither hits this single-byte
|
||||
// branch, so this split is safe.
|
||||
if (ch === "\r") {
|
||||
this.dispatch({ input: "", return: true });
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
if (ch === "\n") {
|
||||
this.dispatch({ input: "j", ctrl: true });
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
if (ch === "\t") {
|
||||
this.dispatch({ input: "", tab: true });
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
if (ch === "\x7f" || ch === "\b") {
|
||||
this.dispatch({ input: "", backspace: true });
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
if (ch === "\x03") {
|
||||
// Ctrl+C — terminate the process. Raw mode disables the
|
||||
// default SIGINT, so we have to handle it ourselves.
|
||||
this.dispatch({ input: "c", ctrl: true });
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
|
||||
const code = ch.charCodeAt(0);
|
||||
// Other Ctrl+letter (0x01-0x1A → A-Z, except already-handled).
|
||||
if (code >= 1 && code <= 26) {
|
||||
const letter = String.fromCharCode(0x60 + code); // a..z
|
||||
this.dispatch({ input: letter, ctrl: true });
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Regular printable input. Coalesce a run of printable chars
|
||||
// into one event so a multi-byte UTF-8 paste-burst arrives as
|
||||
// one `input` rather than N adjacent events.
|
||||
let end = i + 1;
|
||||
while (end < chunk.length) {
|
||||
const c = chunk[end]!;
|
||||
if (c === "\x1b" || c === "\r" || c === "\n" || c === "\t") break;
|
||||
if (c === "\x7f" || c === "\b" || c === "\x03") break;
|
||||
const cc = c.charCodeAt(0);
|
||||
if (cc >= 1 && cc <= 26) break;
|
||||
// Don't swallow into a printable run if a CSI / paste prefix
|
||||
// starts at this position.
|
||||
if (c === "[" && tryEscapelessCsi(chunk, end)) break;
|
||||
if (chunk.slice(end, end + PASTE_START_BARE.length) === PASTE_START_BARE) break;
|
||||
end++;
|
||||
}
|
||||
this.dispatch({ input: chunk.slice(i, end) });
|
||||
i = end;
|
||||
}
|
||||
|
||||
// After processing, if we're still in `esc` state, schedule the
|
||||
// ambiguity timer. The next chunk may carry the rest of the CSI;
|
||||
// if not, the timer fires and dispatches a standalone Esc.
|
||||
if (this.state === "esc") {
|
||||
this.scheduleEscTimer();
|
||||
}
|
||||
}
|
||||
|
||||
private dispatchCsi(seq: string): void {
|
||||
// seq is the bytes after `\x1b[`, e.g. "A", "5~", "200~", "Z".
|
||||
if (seq === "200~") {
|
||||
this.state = "paste";
|
||||
this.pasteBuf = "";
|
||||
return;
|
||||
}
|
||||
if (seq === "201~") {
|
||||
// Stray paste-end — we shouldn't reach here outside paste mode,
|
||||
// but if we do, drop it silently.
|
||||
return;
|
||||
}
|
||||
const ev = lookupCsi(seq);
|
||||
if (ev) this.dispatch(ev);
|
||||
// Unknown CSI → drop. Do NOT insert raw bytes as text.
|
||||
}
|
||||
}
|
||||
|
||||
/** Singleton — one reader per process. */
|
||||
let singleton: StdinReader | null = null;
|
||||
|
||||
export function getStdinReader(): StdinReader {
|
||||
if (!singleton) singleton = new StdinReader();
|
||||
return singleton;
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
/**
|
||||
* Reasonix visual theme.
|
||||
*
|
||||
* One source of truth for colors, glyphs, and decorative blocks so
|
||||
* the TUI reads as one designed surface instead of fifteen
|
||||
* components inventing their own palette. All colors are truecolor
|
||||
* hex; Ink degrades to the nearest 256-color / 8-color slot on
|
||||
* older terminals, so the worst case is still legible.
|
||||
*
|
||||
* Why a module rather than a context: tests import these strings,
|
||||
* Ink components consume them as `color={...}` props, and there's
|
||||
* no theming switch (light/dark) — one project, one palette.
|
||||
*/
|
||||
|
||||
/** Brand gradient — the same teal → cyan → blue → purple → fuchsia
|
||||
* sweep used by the REASONIX wordmark. Reused for accent bars,
|
||||
* progress fills, and decorative dividers. */
|
||||
export const GRADIENT: ReadonlyArray<string> = [
|
||||
"#5eead4", // teal
|
||||
"#67e8f9", // cyan
|
||||
"#7dd3fc", // sky
|
||||
"#93c5fd", // blue
|
||||
"#a5b4fc", // indigo
|
||||
"#c4b5fd", // violet
|
||||
"#d8b4fe", // purple
|
||||
"#f0abfc", // fuchsia
|
||||
];
|
||||
|
||||
/** Solid palette — semantic colors used for status, role, and
|
||||
* accent surfaces. Sourced from the Tailwind 400/500 row so the
|
||||
* tone is consistent with the gradient. */
|
||||
export const COLOR = {
|
||||
primary: "#67e8f9", // cyan-300
|
||||
accent: "#c4b5fd", // violet-300
|
||||
brand: "#5eead4", // teal-300
|
||||
|
||||
user: "#67e8f9", // user message glyph + bar
|
||||
assistant: "#86efac", // green-300, assistant glyph + bar
|
||||
tool: "#fcd34d", // amber-300, tool ok pill bg
|
||||
toolErr: "#fda4af", // rose-300, tool err pill bg
|
||||
info: "#94a3b8", // slate-400, info / dim
|
||||
warn: "#fbbf24", // amber-400
|
||||
err: "#f87171", // red-400
|
||||
ok: "#4ade80", // green-400
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* Glyphs — one consistent alphabet for the whole TUI. Geometric
|
||||
* shapes (◇ ◆ ▣ ▥) make the role of a row readable at a glance
|
||||
* after one or two turns; arrows (› ▸ ▶) consistently mean
|
||||
* "selection / focus / next." Brand mark is reserved for the app
|
||||
* header.
|
||||
*/
|
||||
export const GLYPH = {
|
||||
brand: "◈",
|
||||
user: "◇",
|
||||
assistant: "◆",
|
||||
toolOk: "▣",
|
||||
toolErr: "▥",
|
||||
warn: "▲",
|
||||
err: "✦",
|
||||
arrow: "›",
|
||||
bullet: "·",
|
||||
bar: "▎",
|
||||
thinBar: "▏",
|
||||
block: "█",
|
||||
shade1: "░",
|
||||
shade2: "▒",
|
||||
shade3: "▓",
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* Render a horizontal gradient rule of the given width. Each cell
|
||||
* picks a color from the brand gradient interpolated across the
|
||||
* width, so at cols=80 the rule spans the full sweep. Used for
|
||||
* StatsPanel header/footer decoration and other "this section is
|
||||
* important" anchors.
|
||||
*/
|
||||
export function gradientCells(
|
||||
width: number,
|
||||
glyph: string = GLYPH.block,
|
||||
): Array<{ ch: string; color: string }> {
|
||||
const cells: Array<{ ch: string; color: string }> = [];
|
||||
if (width <= 0) return cells;
|
||||
const last = GRADIENT.length - 1;
|
||||
for (let i = 0; i < width; i++) {
|
||||
const t = width === 1 ? 0 : (i * last) / (width - 1);
|
||||
const lo = Math.floor(t);
|
||||
const hi = Math.min(last, lo + 1);
|
||||
// Pick the closer of the two anchor colors for this cell. Linear
|
||||
// hex blending could be fancier but the discrete steps already
|
||||
// read as a smooth fade at any reasonable width.
|
||||
const color = t - lo < 0.5 ? GRADIENT[lo]! : GRADIENT[hi]!;
|
||||
cells.push({ ch: glyph, color });
|
||||
}
|
||||
return cells;
|
||||
}
|
||||
@@ -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 };
|
||||
}
|
||||
+63
-1
@@ -64,6 +64,23 @@ export interface UserBalance {
|
||||
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;
|
||||
@@ -93,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 ?? {};
|
||||
}
|
||||
@@ -108,6 +135,18 @@ 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;
|
||||
}
|
||||
|
||||
@@ -133,6 +172,29 @@ export class DeepSeekClient {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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,135 @@
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
|
||||
export interface AllBlockDiffOptions extends DiffPreviewOptions {
|
||||
/**
|
||||
* Prefix each block's path-header with a 1-based `[N]` label. Used by
|
||||
* the pending-edits preview so the user can address individual blocks
|
||||
* via `/apply <N>` / `/discard <N>`. Off by default — single-block
|
||||
* surfaces (modal confirm, /show) don't need numbering.
|
||||
*/
|
||||
numbered?: boolean;
|
||||
}
|
||||
|
||||
/** 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: AllBlockDiffOptions = {},
|
||||
): 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("");
|
||||
const label = opts.numbered ? `[${i + 1}] ` : "";
|
||||
out.push(` ${label}${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;
|
||||
}
|
||||
@@ -153,6 +153,27 @@ export function applyEditBlocks(blocks: EditBlock[], rootDir: string): ApplyResu
|
||||
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 {
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
+143
-7
@@ -15,9 +15,86 @@
|
||||
|
||||
import { existsSync, readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { applyProjectMemory } from "../project-memory.js";
|
||||
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, list_directory, search_files, etc.) rooted at the user's working directory.
|
||||
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
|
||||
|
||||
@@ -30,6 +107,15 @@ In those cases, use tools to gather what you need, then reply in prose. No SEARC
|
||||
|
||||
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:
|
||||
@@ -53,16 +139,66 @@ Rules:
|
||||
- Do NOT use write_file to change existing files — the user reviews your edits as SEARCH/REPLACE. write_file is only for files you explicitly want to overwrite wholesale (rare).
|
||||
- Paths are relative to the working directory. Don't use absolute paths.
|
||||
|
||||
# Trust what you already know
|
||||
|
||||
Before exploring the filesystem to answer a factual question, check whether the answer is already in context: the user's current message, earlier turns in this conversation (including prior tool results from \`remember\`), and the pinned memory blocks at the top of this prompt. When the user has stated a fact or you have remembered one, it outranks what the files say — don't re-derive from code what the user already told you. Explore when you genuinely don't know.
|
||||
|
||||
# Exploration
|
||||
|
||||
- Avoid listing or reading inside these common dependency / build directories unless the user explicitly asks about them: node_modules, dist, build, out, .next, .nuxt, .svelte-kit, .git, .venv, venv, __pycache__, target, coverage, .turbo, .cache. They're expensive and usually irrelevant.
|
||||
- Prefer search_files / grep over list_directory when you know roughly what you're looking for — it saves context and avoids enumerating huge trees.
|
||||
- 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 / grep / read), do it with tool calls before writing any prose — silence while exploring is fine.
|
||||
- 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}
|
||||
`;
|
||||
|
||||
/**
|
||||
@@ -72,10 +208,10 @@ Rules:
|
||||
* don't eat context budget on huge generated ignore lists.
|
||||
*
|
||||
* Stacking order (stable for cache prefix):
|
||||
* base prompt → project memory (REASONIX.md) → .gitignore block
|
||||
* base prompt → REASONIX.md → global MEMORY.md → project MEMORY.md → .gitignore
|
||||
*/
|
||||
export function codeSystemPrompt(rootDir: string): string {
|
||||
const withMemory = applyProjectMemory(CODE_SYSTEM_PROMPT, rootDir);
|
||||
const withMemory = applyMemoryStack(CODE_SYSTEM_PROMPT, rootDir);
|
||||
const gitignorePath = join(rootDir, ".gitignore");
|
||||
if (!existsSync(gitignorePath)) return withMemory;
|
||||
let content: string;
|
||||
|
||||
@@ -21,6 +21,37 @@ 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 tool calls. Two axes folded
|
||||
* into one enum because users think about "how trusting am I right now?"
|
||||
* as a single dial, not as "writes vs shell" pairs.
|
||||
*
|
||||
* - "review" — queue edits into pendingEdits (user /apply or `y` to
|
||||
* commit); shell commands NOT on the read-only allowlist
|
||||
* hit ShellConfirm. Default.
|
||||
* - "auto" — apply edits immediately, snapshot for /undo, show a
|
||||
* short undo banner. Shell still goes through ShellConfirm
|
||||
* for non-allowlisted commands.
|
||||
* - "yolo" — apply edits immediately AND auto-approve every shell
|
||||
* command. No prompts at all. Use when you trust the
|
||||
* current direction and just want to iterate fast; /undo
|
||||
* still rolls back individual edit batches.
|
||||
*
|
||||
* Persisted so `/mode <x>` survives a relaunch. Missing → "review".
|
||||
*
|
||||
* Codex-equivalence note: review ≈ untrusted, auto ≈ on-request,
|
||||
* yolo ≈ never.
|
||||
*/
|
||||
export type EditMode = "review" | "auto" | "yolo";
|
||||
|
||||
/**
|
||||
* 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;
|
||||
@@ -29,6 +60,22 @@ export interface ReasonixConfig {
|
||||
* 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
|
||||
@@ -146,6 +193,57 @@ export function addProjectShellAllowed(
|
||||
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);
|
||||
|
||||
+15
-1
@@ -78,7 +78,14 @@ export async function harvest(
|
||||
const trimmed = reasoningContent.trim();
|
||||
if (trimmed.length < minLen) return emptyPlanState();
|
||||
|
||||
const model = options.model ?? "deepseek-chat";
|
||||
// Harvest is schema-constrained JSON extraction, not agent reasoning.
|
||||
// Default to v4-flash with `thinking: "disabled"` below — a few
|
||||
// hundred output tokens fit easily in the non-thinking budget, the
|
||||
// reply comes back ~10× faster than thinking mode, and the per-turn
|
||||
// cost stays an asterisk next to the main loop's spend rather than a
|
||||
// visible slice of it. (`deepseek-chat` was the compat alias for this
|
||||
// same route; we now name the real model.)
|
||||
const model = options.model ?? "deepseek-v4-flash";
|
||||
const maxItems = options.maxItems ?? 5;
|
||||
const maxItemLen = options.maxItemLen ?? 80;
|
||||
const system = SYSTEM_PROMPT.replace("{maxItems}", String(maxItems)).replace(
|
||||
@@ -96,6 +103,13 @@ export async function harvest(
|
||||
responseFormat: { type: "json_object" },
|
||||
temperature: 0,
|
||||
maxTokens: 600,
|
||||
// Pin mode + effort so a future default-model swap (e.g. someone
|
||||
// sets `options.model = "deepseek-v4-pro"`) can't accidentally
|
||||
// turn this micro-extraction into a multi-thousand-reasoning-
|
||||
// token call. DeepSeek ignores these on non-thinking models, so
|
||||
// the request stays valid regardless of the chosen model.
|
||||
thinking: "disabled",
|
||||
reasoningEffort: "high",
|
||||
signal,
|
||||
});
|
||||
return parsePlanState(resp.content, maxItems, maxItemLen);
|
||||
|
||||
+404
@@ -0,0 +1,404 @@
|
||||
/**
|
||||
* Hooks — user-defined automation that fires at well-known points in
|
||||
* the agent loop. Mirrors the two-scope layout we use for memory and
|
||||
* skills:
|
||||
*
|
||||
* - `<project>/.reasonix/settings.json` — committable per-project
|
||||
* - `~/.reasonix/settings.json` — every session
|
||||
*
|
||||
* A hook is a shell command. We invoke it with stdin = a JSON
|
||||
* payload describing the event, and interpret the exit code:
|
||||
*
|
||||
* - `0` — pass; loop continues normally
|
||||
* - `2` — block; for `PreToolUse` / `UserPromptSubmit` the
|
||||
* loop refuses to continue with that step and surfaces the
|
||||
* hook's stderr as the reason. For `PostToolUse` / `Stop` block
|
||||
* is meaningless (the action already happened) — treat as warn.
|
||||
* - anything else — warn; loop continues but stderr is rendered
|
||||
* to the user as an inline notice.
|
||||
*
|
||||
* stdin JSON shape (one envelope per event):
|
||||
*
|
||||
* {
|
||||
* "event": "PreToolUse" | "PostToolUse" | "UserPromptSubmit" | "Stop",
|
||||
* "cwd": "<absolute project root or process.cwd()>",
|
||||
* "toolName": "<string>", // tool events only
|
||||
* "toolArgs": <unknown>, // tool events only — already JSON-decoded
|
||||
* "toolResult": "<string>", // PostToolUse only — same body the model sees
|
||||
* "prompt": "<string>", // UserPromptSubmit only
|
||||
* "lastAssistantText": "<string>", // Stop only
|
||||
* "turn": <number>, // Stop only
|
||||
* }
|
||||
*
|
||||
* Hooks are executed in order: project scope first, then global.
|
||||
* `Pre*` events stop dispatching at the first block; non-block
|
||||
* outcomes accumulate into a single report so the UI can render
|
||||
* each warning inline.
|
||||
*/
|
||||
|
||||
import { spawn } from "node:child_process";
|
||||
import { existsSync, readFileSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
export type HookEvent = "PreToolUse" | "PostToolUse" | "UserPromptSubmit" | "Stop";
|
||||
|
||||
/** All four events as a const array — drives slash listing + validation. */
|
||||
export const HOOK_EVENTS: readonly HookEvent[] = [
|
||||
"PreToolUse",
|
||||
"PostToolUse",
|
||||
"UserPromptSubmit",
|
||||
"Stop",
|
||||
] as const;
|
||||
|
||||
/** Only the gating events can block the loop. */
|
||||
const BLOCKING_EVENTS: ReadonlySet<HookEvent> = new Set(["PreToolUse", "UserPromptSubmit"]);
|
||||
|
||||
/** Per-event default timeout. Tool/prompt hooks gate progress, so they're tight. */
|
||||
const DEFAULT_TIMEOUTS_MS: Record<HookEvent, number> = {
|
||||
PreToolUse: 5_000,
|
||||
UserPromptSubmit: 5_000,
|
||||
PostToolUse: 30_000,
|
||||
Stop: 30_000,
|
||||
};
|
||||
|
||||
export type HookScope = "project" | "global";
|
||||
|
||||
export interface HookConfig {
|
||||
/**
|
||||
* Tool-name pattern (PreToolUse / PostToolUse only). Anchored regex.
|
||||
* Omitted or `"*"` matches every tool. Ignored for prompt / Stop
|
||||
* events (they have no tool name to match against).
|
||||
*/
|
||||
match?: string;
|
||||
/** Shell command to run. Spawned through the platform shell. */
|
||||
command: string;
|
||||
/** Optional human description — surfaced in `/hooks`. */
|
||||
description?: string;
|
||||
/** Per-hook timeout override in ms. */
|
||||
timeout?: number;
|
||||
/**
|
||||
* Working directory for the spawned process. Defaults to:
|
||||
* - project scope → the project root
|
||||
* - global scope → process.cwd()
|
||||
*/
|
||||
cwd?: string;
|
||||
}
|
||||
|
||||
/** Shape of `<scope>/.reasonix/settings.json` — only `hooks` for now. */
|
||||
export interface HookSettings {
|
||||
hooks?: Partial<Record<HookEvent, HookConfig[]>>;
|
||||
}
|
||||
|
||||
/** A loaded hook with its origin scope baked in (used for ordering and `/hooks`). */
|
||||
export interface ResolvedHook extends HookConfig {
|
||||
event: HookEvent;
|
||||
scope: HookScope;
|
||||
/** Absolute path to the settings.json the hook came from. */
|
||||
source: string;
|
||||
}
|
||||
|
||||
/** Outcome of a single hook invocation. */
|
||||
export interface HookOutcome {
|
||||
/** Which hook fired. */
|
||||
hook: ResolvedHook;
|
||||
/**
|
||||
* Decision:
|
||||
* - `pass` — exit 0
|
||||
* - `block` — exit 2 on a blocking event (otherwise downgraded to `warn`)
|
||||
* - `warn` — non-zero exit that is not a successful block
|
||||
* - `timeout` — the spawn was killed past `timeout`
|
||||
* - `error` — could not spawn at all (missing command, etc.)
|
||||
*/
|
||||
decision: "pass" | "block" | "warn" | "timeout" | "error";
|
||||
exitCode: number | null;
|
||||
/** Captured stdout (trimmed). May be empty. */
|
||||
stdout: string;
|
||||
/** Captured stderr (trimmed). The block / warn message comes from here. */
|
||||
stderr: string;
|
||||
durationMs: number;
|
||||
}
|
||||
|
||||
/** Aggregate report for `runHooks`. */
|
||||
export interface HookReport {
|
||||
event: HookEvent;
|
||||
outcomes: HookOutcome[];
|
||||
/** True iff at least one outcome was a `block` — only meaningful for blocking events. */
|
||||
blocked: boolean;
|
||||
}
|
||||
|
||||
export const HOOK_SETTINGS_FILENAME = "settings.json";
|
||||
export const HOOK_SETTINGS_DIRNAME = ".reasonix";
|
||||
|
||||
/** Where the global settings.json lives. Equivalent to `~/.reasonix/settings.json`. */
|
||||
export function globalSettingsPath(homeDirOverride?: string): string {
|
||||
return join(homeDirOverride ?? homedir(), HOOK_SETTINGS_DIRNAME, HOOK_SETTINGS_FILENAME);
|
||||
}
|
||||
|
||||
/** Where the project settings.json lives for a given root. */
|
||||
export function projectSettingsPath(projectRoot: string): string {
|
||||
return join(projectRoot, HOOK_SETTINGS_DIRNAME, HOOK_SETTINGS_FILENAME);
|
||||
}
|
||||
|
||||
function readSettingsFile(path: string): HookSettings | null {
|
||||
if (!existsSync(path)) return null;
|
||||
try {
|
||||
const raw = readFileSync(path, "utf8");
|
||||
const parsed = JSON.parse(raw);
|
||||
if (parsed && typeof parsed === "object") return parsed as HookSettings;
|
||||
} catch {
|
||||
/* malformed JSON → treat as no hooks; do NOT throw, the user
|
||||
* shouldn't lose the whole CLI to a typo in their settings */
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pull every configured hook out of the project + global settings
|
||||
* files, in the order they should fire (project first, global second,
|
||||
* within each scope: array order from the file).
|
||||
*
|
||||
* Returns a flat list — the dispatcher filters by event + match
|
||||
* pattern at run time. Loading is cheap (one or two JSON files), so
|
||||
* we don't memoize across processes; re-load is allowed via
|
||||
* `/hooks reload` and on every fresh App mount.
|
||||
*/
|
||||
export interface LoadHookSettingsOptions {
|
||||
/** Absolute project root, if any. Without it, only global hooks load. */
|
||||
projectRoot?: string;
|
||||
/** Override `~` for tests. */
|
||||
homeDir?: string;
|
||||
}
|
||||
|
||||
export function loadHooks(opts: LoadHookSettingsOptions = {}): ResolvedHook[] {
|
||||
const out: ResolvedHook[] = [];
|
||||
if (opts.projectRoot) {
|
||||
const projPath = projectSettingsPath(opts.projectRoot);
|
||||
const settings = readSettingsFile(projPath);
|
||||
if (settings) appendResolved(out, settings, "project", projPath);
|
||||
}
|
||||
const globalPath = globalSettingsPath(opts.homeDir);
|
||||
const settings = readSettingsFile(globalPath);
|
||||
if (settings) appendResolved(out, settings, "global", globalPath);
|
||||
return out;
|
||||
}
|
||||
|
||||
function appendResolved(
|
||||
out: ResolvedHook[],
|
||||
settings: HookSettings,
|
||||
scope: HookScope,
|
||||
source: string,
|
||||
): void {
|
||||
if (!settings.hooks) return;
|
||||
for (const event of HOOK_EVENTS) {
|
||||
const list = settings.hooks[event];
|
||||
if (!Array.isArray(list)) continue;
|
||||
for (const cfg of list) {
|
||||
if (!cfg || typeof cfg.command !== "string" || cfg.command.trim() === "") continue;
|
||||
out.push({ ...cfg, event, scope, source });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* True if `toolName` matches the hook's `match` field. `"*"` and
|
||||
* undefined match everything. Otherwise we anchor the field as a
|
||||
* regex — partial-name matches don't fire, so `"file"` would not
|
||||
* trigger on `read_file` (use `".*file"` for that).
|
||||
*/
|
||||
export function matchesTool(hook: ResolvedHook, toolName: string): boolean {
|
||||
if (hook.event !== "PreToolUse" && hook.event !== "PostToolUse") return true;
|
||||
const m = hook.match;
|
||||
if (!m || m === "*") return true;
|
||||
try {
|
||||
const re = new RegExp(`^(?:${m})$`);
|
||||
return re.test(toolName);
|
||||
} catch {
|
||||
/* malformed regex → don't fire (safer than firing on every tool) */
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Payload envelope passed to hook stdin. */
|
||||
export interface HookPayload {
|
||||
event: HookEvent;
|
||||
cwd: string;
|
||||
toolName?: string;
|
||||
toolArgs?: unknown;
|
||||
toolResult?: string;
|
||||
prompt?: string;
|
||||
lastAssistantText?: string;
|
||||
turn?: number;
|
||||
}
|
||||
|
||||
/** Test seam — same shape as Node's spawn but returns a Promise of the raw outcome bits. */
|
||||
export interface HookSpawnInput {
|
||||
command: string;
|
||||
cwd: string;
|
||||
stdin: string;
|
||||
timeoutMs: number;
|
||||
}
|
||||
|
||||
export interface HookSpawnResult {
|
||||
exitCode: number | null;
|
||||
stdout: string;
|
||||
stderr: string;
|
||||
timedOut: boolean;
|
||||
/** True iff spawn() itself failed (ENOENT, EACCES, …). */
|
||||
spawnError?: Error;
|
||||
}
|
||||
|
||||
export type HookSpawner = (input: HookSpawnInput) => Promise<HookSpawnResult>;
|
||||
|
||||
/**
|
||||
* Default spawner — runs `command` through the platform shell so
|
||||
* `&&`, pipes, env-var expansion all work without a tokenizer.
|
||||
* Stdin is the JSON payload, stdout / stderr are buffered.
|
||||
*
|
||||
* Why `shell: true`? A hook is intentionally a shell command — that's
|
||||
* the contract. Treating it like an argv array would surprise users
|
||||
* who write `bun run check && eslint .` and expect it to behave the
|
||||
* way it does in their terminal.
|
||||
*/
|
||||
function defaultSpawner(input: HookSpawnInput): Promise<HookSpawnResult> {
|
||||
return new Promise<HookSpawnResult>((resolve) => {
|
||||
const child = spawn(input.command, {
|
||||
cwd: input.cwd,
|
||||
shell: true,
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
});
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
let timedOut = false;
|
||||
const timer = setTimeout(() => {
|
||||
timedOut = true;
|
||||
child.kill("SIGTERM");
|
||||
// SIGTERM may not land on Windows for shell children — followed
|
||||
// by a hard kill a moment later if the process is still around.
|
||||
setTimeout(() => {
|
||||
try {
|
||||
child.kill("SIGKILL");
|
||||
} catch {
|
||||
/* already gone */
|
||||
}
|
||||
}, 500);
|
||||
}, input.timeoutMs);
|
||||
|
||||
child.stdout.on("data", (chunk: Buffer) => {
|
||||
stdout += chunk.toString("utf8");
|
||||
});
|
||||
child.stderr.on("data", (chunk: Buffer) => {
|
||||
stderr += chunk.toString("utf8");
|
||||
});
|
||||
child.once("error", (err) => {
|
||||
clearTimeout(timer);
|
||||
resolve({
|
||||
exitCode: null,
|
||||
stdout,
|
||||
stderr,
|
||||
timedOut: false,
|
||||
spawnError: err,
|
||||
});
|
||||
});
|
||||
child.once("close", (code) => {
|
||||
clearTimeout(timer);
|
||||
resolve({
|
||||
exitCode: code,
|
||||
stdout: stdout.trim(),
|
||||
stderr: stderr.trim(),
|
||||
timedOut,
|
||||
});
|
||||
});
|
||||
|
||||
try {
|
||||
child.stdin.write(input.stdin);
|
||||
child.stdin.end();
|
||||
} catch {
|
||||
/* stdin write can race with spawn errors; the close handler
|
||||
* still fires with exit 0/null */
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Format a hook outcome as a single-line UI string. Used by both the
|
||||
* loop (for `warning` events) and the App (for UserPromptSubmit /
|
||||
* Stop outcomes). Centralizing keeps the language consistent across
|
||||
* scopes.
|
||||
*/
|
||||
export function formatHookOutcomeMessage(outcome: HookOutcome): string {
|
||||
if (outcome.decision === "pass") return "";
|
||||
const detail = (outcome.stderr || outcome.stdout || "").trim();
|
||||
const tag = `${outcome.hook.scope}/${outcome.hook.event}`;
|
||||
const cmd =
|
||||
outcome.hook.command.length > 60
|
||||
? `${outcome.hook.command.slice(0, 60)}…`
|
||||
: outcome.hook.command;
|
||||
const head = `hook ${tag} \`${cmd}\` ${outcome.decision}`;
|
||||
return detail ? `${head}: ${detail}` : head;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decide the hook's outcome decision from raw spawn results.
|
||||
* Pulled out as a pure function so tests can pin the matrix.
|
||||
*/
|
||||
export function decideOutcome(
|
||||
event: HookEvent,
|
||||
raw: HookSpawnResult,
|
||||
): "pass" | "block" | "warn" | "timeout" | "error" {
|
||||
if (raw.spawnError) return "error";
|
||||
if (raw.timedOut) return BLOCKING_EVENTS.has(event) ? "block" : "warn";
|
||||
if (raw.exitCode === 0) return "pass";
|
||||
if (raw.exitCode === 2 && BLOCKING_EVENTS.has(event)) return "block";
|
||||
return "warn";
|
||||
}
|
||||
|
||||
export interface RunHooksOptions {
|
||||
payload: HookPayload;
|
||||
hooks: ResolvedHook[];
|
||||
/** Test seam — defaults to a real `spawn`. */
|
||||
spawner?: HookSpawner;
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter hooks down to the ones that match `payload.event` (and
|
||||
* `payload.toolName`, for tool events), then run them in order.
|
||||
* Stops at the first `block` outcome on a blocking event so a
|
||||
* gating hook can prevent later hooks from incorrectly seeing a
|
||||
* success that wasn't going to happen.
|
||||
*/
|
||||
export async function runHooks(opts: RunHooksOptions): Promise<HookReport> {
|
||||
const spawner = opts.spawner ?? defaultSpawner;
|
||||
const event = opts.payload.event;
|
||||
const toolName = opts.payload.toolName ?? "";
|
||||
const matching = opts.hooks.filter((h) => h.event === event && matchesTool(h, toolName));
|
||||
|
||||
const outcomes: HookOutcome[] = [];
|
||||
let blocked = false;
|
||||
const stdin = `${JSON.stringify(opts.payload)}\n`;
|
||||
|
||||
for (const hook of matching) {
|
||||
const start = Date.now();
|
||||
const timeoutMs = hook.timeout ?? DEFAULT_TIMEOUTS_MS[event];
|
||||
const cwd = hook.cwd ?? opts.payload.cwd;
|
||||
const raw = await spawner({ command: hook.command, cwd, stdin, timeoutMs });
|
||||
const decision = decideOutcome(event, raw);
|
||||
outcomes.push({
|
||||
hook,
|
||||
decision,
|
||||
exitCode: raw.exitCode,
|
||||
stdout: raw.stdout,
|
||||
stderr:
|
||||
raw.stderr ||
|
||||
(raw.spawnError ? raw.spawnError.message : "") ||
|
||||
(raw.timedOut ? `hook timed out after ${timeoutMs}ms` : ""),
|
||||
durationMs: Date.now() - start,
|
||||
});
|
||||
if (decision === "block") {
|
||||
blocked = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return { event, outcomes, blocked };
|
||||
}
|
||||
+117
-1
@@ -6,9 +6,30 @@ export type { ChatResponse, StreamChunk, DeepSeekClientOptions } from "./client.
|
||||
export {
|
||||
CacheFirstLoop,
|
||||
formatLoopError,
|
||||
fixToolCallPairing,
|
||||
healLoadedMessages,
|
||||
healLoadedMessagesByTokens,
|
||||
stripHallucinatedToolMarkup,
|
||||
} from "./loop.js";
|
||||
export {
|
||||
AT_MENTION_PATTERN,
|
||||
AT_PICKER_PREFIX,
|
||||
DEFAULT_AT_MENTION_MAX_BYTES,
|
||||
DEFAULT_PICKER_IGNORE_DIRS,
|
||||
detectAtPicker,
|
||||
expandAtMentions,
|
||||
listFilesSync,
|
||||
listFilesWithStatsSync,
|
||||
rankPickerCandidates,
|
||||
} from "./at-mentions.js";
|
||||
export type {
|
||||
AtMentionExpansion,
|
||||
AtMentionOptions,
|
||||
FileWithStats,
|
||||
ListFilesOptions,
|
||||
PickerCandidate,
|
||||
RankPickerOptions,
|
||||
} from "./at-mentions.js";
|
||||
export type {
|
||||
CacheFirstLoopOptions,
|
||||
LoopEvent,
|
||||
@@ -38,17 +59,58 @@ export {
|
||||
} from "./project-memory.js";
|
||||
export type { ProjectMemory } from "./project-memory.js";
|
||||
|
||||
export {
|
||||
MEMORY_INDEX_FILE,
|
||||
MEMORY_INDEX_MAX_CHARS,
|
||||
MemoryStore,
|
||||
USER_MEMORY_DIR,
|
||||
applyMemoryStack,
|
||||
applyUserMemory,
|
||||
projectHash,
|
||||
sanitizeMemoryName,
|
||||
} from "./user-memory.js";
|
||||
export type {
|
||||
MemoryEntry,
|
||||
MemoryScope,
|
||||
MemoryStoreOptions,
|
||||
MemoryType,
|
||||
WriteInput as MemoryWriteInput,
|
||||
} from "./user-memory.js";
|
||||
|
||||
export { ToolRegistry } from "./tools.js";
|
||||
export type { ToolDefinition, ToolCallContext } from "./tools.js";
|
||||
export { registerFilesystemTools } from "./tools/filesystem.js";
|
||||
export type { FilesystemToolsOptions } from "./tools/filesystem.js";
|
||||
export { registerMemoryTools } from "./tools/memory.js";
|
||||
export type { MemoryToolsOptions } from "./tools/memory.js";
|
||||
export { ChoiceRequestedError, registerChoiceTool } from "./tools/choice.js";
|
||||
export type { ChoiceOption, ChoiceToolOptions } from "./tools/choice.js";
|
||||
export {
|
||||
PlanCheckpointError,
|
||||
PlanProposedError,
|
||||
PlanRevisionProposedError,
|
||||
registerPlanTool,
|
||||
} from "./tools/plan.js";
|
||||
export type { PlanStep, PlanStepRisk, PlanToolOptions, StepCompletion } from "./tools/plan.js";
|
||||
export { forkRegistryExcluding, registerSubagentTool } from "./tools/subagent.js";
|
||||
export type {
|
||||
SubagentEvent,
|
||||
SubagentSink,
|
||||
SubagentToolOptions,
|
||||
} from "./tools/subagent.js";
|
||||
export {
|
||||
NeedsConfirmationError,
|
||||
detectShellOperator,
|
||||
formatCommandResult,
|
||||
injectPowerShellUtf8,
|
||||
isAllowed,
|
||||
prepareSpawn,
|
||||
quoteForCmdExe,
|
||||
registerShellTools,
|
||||
resolveExecutable,
|
||||
runCommand,
|
||||
tokenizeCommand,
|
||||
withUtf8Codepage,
|
||||
} from "./tools/shell.js";
|
||||
export type { RunCommandResult, ShellToolsOptions } from "./tools/shell.js";
|
||||
export {
|
||||
@@ -140,9 +202,11 @@ export { SseTransport } from "./mcp/sse.js";
|
||||
export type { SseTransportOptions } from "./mcp/sse.js";
|
||||
export {
|
||||
DEFAULT_MAX_RESULT_CHARS,
|
||||
DEFAULT_MAX_RESULT_TOKENS,
|
||||
bridgeMcpTools,
|
||||
flattenMcpResult,
|
||||
truncateForModel,
|
||||
truncateForModelByTokens,
|
||||
} from "./mcp/registry.js";
|
||||
export type { BridgeOptions, BridgeResult, FlattenOptions } from "./mcp/registry.js";
|
||||
export { parseMcpSpec } from "./mcp/spec.js";
|
||||
@@ -219,4 +283,56 @@ export type {
|
||||
JSONSchema,
|
||||
} from "./types.js";
|
||||
|
||||
export const VERSION = "0.4.17";
|
||||
export {
|
||||
LATEST_CACHE_TTL_MS,
|
||||
LATEST_FETCH_TIMEOUT_MS,
|
||||
VERSION,
|
||||
compareVersions,
|
||||
getLatestVersion,
|
||||
isNpxInstall,
|
||||
} from "./version.js";
|
||||
export type { GetLatestVersionOptions } from "./version.js";
|
||||
|
||||
export {
|
||||
HOOK_EVENTS,
|
||||
HOOK_SETTINGS_DIRNAME,
|
||||
HOOK_SETTINGS_FILENAME,
|
||||
decideOutcome,
|
||||
formatHookOutcomeMessage,
|
||||
globalSettingsPath,
|
||||
loadHooks,
|
||||
matchesTool,
|
||||
projectSettingsPath,
|
||||
runHooks,
|
||||
} from "./hooks.js";
|
||||
export {
|
||||
aggregateUsage,
|
||||
appendUsage,
|
||||
bucketCacheHitRatio,
|
||||
bucketSavingsFraction,
|
||||
defaultUsageLogPath,
|
||||
formatLogSize,
|
||||
readUsageLog,
|
||||
} from "./usage.js";
|
||||
export type {
|
||||
AggregateOptions,
|
||||
AppendUsageInput,
|
||||
UsageAggregate,
|
||||
UsageBucket,
|
||||
UsageRecord,
|
||||
} from "./usage.js";
|
||||
export type {
|
||||
HookConfig,
|
||||
HookEvent,
|
||||
HookOutcome,
|
||||
HookPayload,
|
||||
HookReport,
|
||||
HookScope,
|
||||
HookSettings,
|
||||
HookSpawner,
|
||||
HookSpawnInput,
|
||||
HookSpawnResult,
|
||||
LoadHookSettingsOptions,
|
||||
ResolvedHook,
|
||||
RunHooksOptions,
|
||||
} from "./hooks.js";
|
||||
+1243
-96
File diff suppressed because it is too large.
Load diff
@@ -7,6 +7,7 @@
|
||||
* MCP ecosystem tool, wrapped in Reasonix's Pillar 1 + Pillar 3 benefits.
|
||||
*/
|
||||
|
||||
import { countTokens } from "../tokenizer.js";
|
||||
import { ToolRegistry } from "../tools.js";
|
||||
import type { JSONSchema } from "../types.js";
|
||||
import type { McpClient } from "./client.js";
|
||||
@@ -58,6 +59,18 @@ export interface BridgeOptions {
|
||||
*/
|
||||
export const DEFAULT_MAX_RESULT_CHARS = 32_000;
|
||||
|
||||
/**
|
||||
* Token-aware cap for tool results, in DeepSeek V3 tokens.
|
||||
*
|
||||
* 8,000 tokens ≈ 6% of DeepSeek V3's 131K context. One oversized tool
|
||||
* result can't eat more than that no matter what character density the
|
||||
* content has. The char cap (32K chars) only bounds tokens for English
|
||||
* — CJK text at 1 char/token blows past 16K tokens under the same
|
||||
* ceiling. With the tokenizer shipped in 0.5.0 we can cap the thing
|
||||
* that actually matters.
|
||||
*/
|
||||
export const DEFAULT_MAX_RESULT_TOKENS = 8_000;
|
||||
|
||||
export interface BridgeResult {
|
||||
registry: ToolRegistry;
|
||||
/** Names actually registered (may differ from MCP names when a prefix is applied). */
|
||||
@@ -159,6 +172,94 @@ export function truncateForModel(s: string, maxChars: number): string {
|
||||
return `${head}\n\n[…truncated ${dropped} chars — raise BridgeOptions.maxResultChars, or call the tool with a narrower scope (filter, head, pagination)…]\n\n${tail}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Token-aware truncation. Same head+tail policy as `truncateForModel`,
|
||||
* but sizes the slices against a DeepSeek V3 token budget instead of a
|
||||
* raw character count — so CJK text (which previously survived at 2×
|
||||
* the token cost per char) gets capped at the same effective context
|
||||
* footprint as English.
|
||||
*
|
||||
* Strategy: fast path when `s.length <= maxTokens` (every token is ≥1
|
||||
* char, so this bounds tokens ≤ maxTokens — skip tokenize entirely).
|
||||
* Short-ish strings are confirmed against the real token count.
|
||||
* Long strings go straight to char-sliced head+tail with one or two
|
||||
* tokenize-verify-and-shrink rounds per slice — we deliberately never
|
||||
* tokenize the full input, because pathological repetitive text
|
||||
* (megabytes of `AAAA…`) can cost 30s+ on the pure-TS BPE port.
|
||||
*/
|
||||
export function truncateForModelByTokens(s: string, maxTokens: number): string {
|
||||
if (maxTokens <= 0) return "";
|
||||
// Every token is ≥1 char — if length ≤ budget, tokens ≤ budget.
|
||||
if (s.length <= maxTokens) return s;
|
||||
// Small enough to tokenize-check without pathological cost: confirm
|
||||
// whether we're actually over budget. (Threshold is the char-bound
|
||||
// worst case for English/code — ~4 chars/token.)
|
||||
if (s.length <= maxTokens * 4) {
|
||||
const tokens = countTokens(s);
|
||||
if (tokens <= maxTokens) return s;
|
||||
}
|
||||
|
||||
const markerOverhead = 48; // rough token cost of the truncation marker
|
||||
const contentBudget = Math.max(0, maxTokens - markerOverhead);
|
||||
const tailBudget = Math.min(256, Math.floor(contentBudget * 0.1));
|
||||
const headBudget = Math.max(0, contentBudget - tailBudget);
|
||||
|
||||
const head = sizePrefixToTokens(s, headBudget);
|
||||
const tail = sizeSuffixToTokens(s, tailBudget);
|
||||
const droppedChars = s.length - head.length - tail.length;
|
||||
// Estimate dropped tokens from the per-slice char/token ratio we
|
||||
// already measured, rather than paying another full-string tokenize.
|
||||
// The marker says "~N tokens" so the ≤10% slop is visible to readers.
|
||||
const headTokens = head ? countTokens(head) : 0;
|
||||
const tailTokens = tail ? countTokens(tail) : 0;
|
||||
const sampleChars = head.length + tail.length;
|
||||
const sampleTokens = headTokens + tailTokens;
|
||||
const ratio = sampleChars > 0 ? sampleTokens / sampleChars : 0.3;
|
||||
const estTotalTokens = Math.ceil(s.length * ratio);
|
||||
const droppedTokens = Math.max(0, estTotalTokens - sampleTokens);
|
||||
return `${head}\n\n[…truncated ~${droppedTokens} tokens (${droppedChars} chars) — raise BridgeOptions.maxResultTokens, or call the tool with a narrower scope (filter, head, pagination)…]\n\n${tail}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Slice `s` from the start to the largest prefix that fits `budget`
|
||||
* tokens. Never tokenizes the full input: starts with a char-bound
|
||||
* estimate, then verifies and shrinks. Converges in 1–2 iterations.
|
||||
*/
|
||||
function sizePrefixToTokens(s: string, budget: number): string {
|
||||
if (budget <= 0 || s.length === 0) return "";
|
||||
// Optimistic starting size: assume ~4 chars/token (English/code
|
||||
// average). If the content is denser (CJK ~1 char/token), the first
|
||||
// tokenize will show we're over and we shrink.
|
||||
let size = Math.min(s.length, budget * 4);
|
||||
for (let iter = 0; iter < 6; iter++) {
|
||||
if (size <= 0) return "";
|
||||
const slice = s.slice(0, size);
|
||||
const count = countTokens(slice);
|
||||
if (count <= budget) return slice;
|
||||
// Shrink by the overshoot fraction plus a small safety margin.
|
||||
const next = Math.floor(size * (budget / count) * 0.95);
|
||||
if (next >= size) return s.slice(0, Math.max(0, size - 1));
|
||||
size = next;
|
||||
}
|
||||
return s.slice(0, Math.max(0, size));
|
||||
}
|
||||
|
||||
/** Slice `s` from the end to the largest suffix that fits `budget` tokens. */
|
||||
function sizeSuffixToTokens(s: string, budget: number): string {
|
||||
if (budget <= 0 || s.length === 0) return "";
|
||||
let size = Math.min(s.length, budget * 4);
|
||||
for (let iter = 0; iter < 6; iter++) {
|
||||
if (size <= 0) return "";
|
||||
const slice = s.slice(-size);
|
||||
const count = countTokens(slice);
|
||||
if (count <= budget) return slice;
|
||||
const next = Math.floor(size * (budget / count) * 0.95);
|
||||
if (next >= size) return s.slice(-Math.max(0, size - 1));
|
||||
size = next;
|
||||
}
|
||||
return s.slice(-Math.max(0, size));
|
||||
}
|
||||
|
||||
function blockToString(block: McpContentBlock): string {
|
||||
if (block.type === "text") return block.text;
|
||||
if (block.type === "image") return `[image ${block.mimeType}, ${block.data.length} chars base64]`;
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
/**
|
||||
* Reusable prompt fragments. Every rule that applies across multiple
|
||||
* prompt surfaces (main agent + subagents + built-in skills) lives
|
||||
* here so one edit covers every place the model learns the house
|
||||
* style. The 4-copy formatting-rule drift that motivated this was a
|
||||
* real bug: Unicode box-drawing warnings diverged between subagent
|
||||
* prompts, and the main code prompt lacked them entirely even though
|
||||
* its reply goes through the same markdown renderer.
|
||||
*/
|
||||
|
||||
/**
|
||||
* How replies get rendered. Matches behaviors the TUI's markdown
|
||||
* pipeline (src/cli/ui/markdown.tsx) actually handles best.
|
||||
* Embedded literally into prompts — no string interpolation, so it
|
||||
* survives Reasonix's prefix-cache hashing unchanged across sessions.
|
||||
*/
|
||||
export const TUI_FORMATTING_RULES = `Formatting (rendered in a TUI with a real markdown renderer):
|
||||
- Tabular data → GitHub-Flavored Markdown tables with ASCII pipes (\`| col | col |\` header + \`| --- | --- |\` separator). Never use Unicode box-drawing characters (│ ─ ┼ ┌ ┐ └ ┘ ├ ┤) — they look intentional but break terminal word-wrap and render as garbled columns at narrow widths.
|
||||
- Keep table cells short (one phrase each). If a cell needs a paragraph, use bullets below the table instead.
|
||||
- Code, file paths with line ranges, and shell commands → fenced code blocks (\`\`\`).
|
||||
- Do NOT draw decorative frames around content with \`┌──┐ │ └──┘\` characters. The renderer adds its own borders; extra ASCII art adds noise and shatters at narrow widths.
|
||||
- For flow charts and diagrams: a plain bullet list with \`→\` or \`↓\` between steps. Don't try to draw boxes-and-arrows in ASCII; it never survives word-wrap.`;
|
||||
|
||||
/**
|
||||
* Self-report escalation contract — teaches the model (running on
|
||||
* flash by default) how to ask for a retry on v4-pro. When Reasonix
|
||||
* sees "<<<NEEDS_PRO>>>" as the first line of assistant output on
|
||||
* flash, it aborts the call, upgrades this turn to pro, and re-issues
|
||||
* the same messages. One retry per turn; pro never re-escalates.
|
||||
*
|
||||
* Why this exists: non-expert users can't reliably predict which
|
||||
* tasks need the frontier tier, and reactive-only escalation (wait
|
||||
* for flash to fail N times) wastes tokens + time. Letting the model
|
||||
* self-assess catches hard tasks upfront when flash recognizes the
|
||||
* difficulty — without silently auto-upgrading every prompt (which
|
||||
* would destroy cost savings).
|
||||
*
|
||||
* Use sparingly: most coding tasks stay on flash. The escape hatch
|
||||
* is for tasks where flash would otherwise emit a mediocre / guessed
|
||||
* answer.
|
||||
*/
|
||||
export const ESCALATION_CONTRACT = `Cost-aware escalation (when you're running on deepseek-v4-flash):
|
||||
|
||||
If a task CLEARLY exceeds what flash can do well — complex cross-file architecture refactors, subtle concurrency / security / correctness invariants you can't resolve with confidence, or a design trade-off you'd be guessing at — output the marker as the FIRST line of your response (nothing before it, not even whitespace on a separate line). This aborts the current call and retries this turn on deepseek-v4-pro, one shot.
|
||||
|
||||
Two accepted forms:
|
||||
- \`<<<NEEDS_PRO>>>\` — bare marker, no rationale.
|
||||
- \`<<<NEEDS_PRO: <one-sentence reason>>>>\` — preferred. The reason text appears in the user-visible warning ("⇧ flash requested escalation — <your reason>"), so they understand WHY a more expensive call is happening. Keep it under ~150 chars, no newlines, no nested \`>\` characters. Examples: \`<<<NEEDS_PRO: cross-file refactor across 6 modules with circular imports>>>\` or \`<<<NEEDS_PRO: subtle session-token race; flash would likely miss the locking invariant>>>\`.
|
||||
|
||||
Do NOT emit any other content in the same response when you request escalation. Use this sparingly: normal tasks — reading files, small edits, clear bug fixes, straightforward feature additions — stay on flash. Request escalation ONLY when you would otherwise produce a guess or a visibly-mediocre answer. If in doubt, attempt the task on flash first; the system also escalates automatically if you hit 3+ repair / SEARCH-mismatch errors in a single turn (the user sees a typed breakdown).`;
|
||||
|
||||
/**
|
||||
* "Don't assert absence without checking." Subagents that run without
|
||||
* this rule will confidently report "X is missing" based on their
|
||||
* partial exploration, and the parent agent swallows it as fact. The
|
||||
* main code prompt has its own, longer version of this — kept separate
|
||||
* because the code agent is in a richer conversational frame.
|
||||
*/
|
||||
export const NEGATIVE_CLAIM_RULE = `Negative claims ("X is missing", "Y isn't implemented", "there's no Z") are the #1 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 have a search tool (\`search_content\`, \`grep\`, web search), call it FIRST before asserting absence:
|
||||
- Returns matches → you were wrong; correct yourself and cite the matches.
|
||||
- Returns nothing → state the absence WITH the search query as evidence: \`No callers of \\\`foo()\\\` found (search_content "foo").\`
|
||||
|
||||
If you have no search tool, qualify hard: "I haven't verified — this is a guess." Never assert absence with fake authority.`;
|
||||
@@ -46,6 +46,17 @@ export class ToolCallRepair {
|
||||
this.storm = new StormBreaker(opts.stormWindow ?? 6, opts.stormThreshold ?? 3);
|
||||
}
|
||||
|
||||
/**
|
||||
* Drop the StormBreaker's sliding window of recent (name, args)
|
||||
* signatures. Called at the start of every user turn — a fresh user
|
||||
* message is a new intent, so carrying old repetition state into it
|
||||
* would turn a valid "try again with different input" flow into a
|
||||
* false-positive block.
|
||||
*/
|
||||
resetStorm(): void {
|
||||
this.storm.reset();
|
||||
}
|
||||
|
||||
process(
|
||||
declaredCalls: ToolCall[],
|
||||
reasoningContent: string | null,
|
||||
|
||||
@@ -170,6 +170,7 @@ function summarizeTurns(turns: TurnStats[]): SessionSummary {
|
||||
savingsVsClaudePct: round(savingsVsClaude * 100, 2),
|
||||
cacheHitRatio: round(cacheHitRatio, 4),
|
||||
lastPromptTokens: lastTurn?.usage.promptTokens ?? 0,
|
||||
lastTurnCostUsd: round(lastTurn?.cost ?? 0, 6),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -107,6 +107,15 @@ export function deleteSession(name: string): boolean {
|
||||
const path = sessionPath(name);
|
||||
try {
|
||||
unlinkSync(path);
|
||||
// Best-effort cleanup of side-car files that belong to this session
|
||||
// so `/forget` doesn't leave orphans in `sessionsDir()`. Currently
|
||||
// just the pending-edits checkpoint (src/code/pending-edits.ts).
|
||||
const sidecar = path.replace(/\.jsonl$/, ".pending.json");
|
||||
try {
|
||||
unlinkSync(sidecar);
|
||||
} catch {
|
||||
/* no sidecar present — expected for sessions without pending edits */
|
||||
}
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
|
||||
+534
@@ -0,0 +1,534 @@
|
||||
/**
|
||||
* Skills — user-defined prompt packs pinned (by name) into the
|
||||
* immutable prefix and loaded (by body) on demand.
|
||||
*
|
||||
* Two scopes mirror the user-memory layout:
|
||||
* - `project` → `<projectRoot>/.reasonix/skills/` (this repo only)
|
||||
* - `global` → `~/.reasonix/skills/` (every session)
|
||||
*
|
||||
* Project scope wins on a name collision. Deliberately NOT tied to
|
||||
* any specific client's directory convention (`.claude/`, `.glm/`,
|
||||
* etc.) — Reasonix is model-agnostic at the conversation layer, so
|
||||
* coupling the skill filesystem to one vendor would break any user
|
||||
* running a different backend.
|
||||
*
|
||||
* Accepted file layouts (both emit the same `Skill`):
|
||||
* - `{dir}/<name>/SKILL.md` (preferred — lets a skill bundle
|
||||
* additional assets alongside)
|
||||
* - `{dir}/<name>.md` (flat, one-file shorthand)
|
||||
*
|
||||
* Frontmatter keys we read:
|
||||
* - `name` — optional, defaults to the file / dir name
|
||||
* - `description` — one-line index description (REQUIRED for listing)
|
||||
* - `allowed-tools` — parsed but UNUSED in v1 (see tools/skills.ts)
|
||||
*
|
||||
* Cache-First contract (Pillar 1):
|
||||
* - The PREFIX sees only names + descriptions (one line each).
|
||||
* - Bodies enter the APPEND-ONLY LOG lazily, via `run_skill` or
|
||||
* `/skill <name>` — never the prefix. That keeps the prefix hash
|
||||
* stable across skill additions to the body store.
|
||||
*/
|
||||
|
||||
import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { join, resolve } from "node:path";
|
||||
import { NEGATIVE_CLAIM_RULE, TUI_FORMATTING_RULES } from "./prompt-fragments.js";
|
||||
|
||||
export const SKILLS_DIRNAME = "skills";
|
||||
export const SKILL_FILE = "SKILL.md";
|
||||
/** Cap on the pinned skills-index block, mirrors memory-index cap. */
|
||||
export const SKILLS_INDEX_MAX_CHARS = 4000;
|
||||
/** Skill identifier shape — alnum + `_` + `-` + interior `.`, 1-64 chars. */
|
||||
const VALID_SKILL_NAME = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/;
|
||||
|
||||
export type SkillScope = "project" | "global" | "builtin";
|
||||
|
||||
/**
|
||||
* Execution mode for a skill. `inline` (default) returns the body as a
|
||||
* tool result so the body enters the parent's append-only log — the
|
||||
* model continues the loop using the loaded instructions. `subagent`
|
||||
* spawns an isolated child loop with the body as the system prompt and
|
||||
* the user-supplied `arguments` as the task; only the child's final
|
||||
* answer comes back. Use `subagent` for big-context exploration / research
|
||||
* playbooks where the parent doesn't need to see the trail.
|
||||
*/
|
||||
export type SkillRunAs = "inline" | "subagent";
|
||||
|
||||
export interface Skill {
|
||||
/** Canonical name — sanitized, matches the directory / filename stem. */
|
||||
name: string;
|
||||
/** One-line description shown in the pinned index. */
|
||||
description: string;
|
||||
/** Full markdown body (post-frontmatter). Loaded on demand. */
|
||||
body: string;
|
||||
/** Which scope this skill was loaded from. */
|
||||
scope: SkillScope;
|
||||
/** Absolute path to the SKILL.md (or {name}.md) file, or "(builtin)" for shipped defaults. */
|
||||
path: string;
|
||||
/** Raw `allowed-tools` field from frontmatter, if any. Unused in v1. */
|
||||
allowedTools?: string;
|
||||
/**
|
||||
* Execution mode (frontmatter `runAs`). Defaults to `inline` for
|
||||
* backwards compatibility with skills written before this field
|
||||
* existed.
|
||||
*/
|
||||
runAs: SkillRunAs;
|
||||
/**
|
||||
* Frontmatter `model` — when set, overrides the default model the
|
||||
* subagent runs on. Only meaningful when `runAs === "subagent"`.
|
||||
* Accept any DeepSeek model id; the subagent layer falls back to its
|
||||
* own default if this is missing or invalid.
|
||||
*/
|
||||
model?: string;
|
||||
}
|
||||
|
||||
export interface SkillStoreOptions {
|
||||
/** Override `$HOME` — tests point this at a tmpdir. */
|
||||
homeDir?: string;
|
||||
/**
|
||||
* Absolute project root. Required to surface project-scope skills;
|
||||
* omit (e.g. in `reasonix chat` without `code`) and the store only
|
||||
* reads the global scope.
|
||||
*/
|
||||
projectRoot?: string;
|
||||
/**
|
||||
* Suppress the bundled built-in skills (`explore`, `research`).
|
||||
* Used by unit tests that want to assert exact list contents
|
||||
* without the +2 builtins distorting counts. Production callers
|
||||
* leave this off so users always get the bundled defaults.
|
||||
*/
|
||||
disableBuiltins?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a `---` frontmatter block. Same minimal shape as user-memory:
|
||||
* `key: value` lines, no quoting, no nesting. Returns `{}` data and the
|
||||
* full input as body when no frontmatter fence is present — so hand-
|
||||
* written files without frontmatter still surface (with empty desc).
|
||||
*/
|
||||
function parseFrontmatter(raw: string): { data: Record<string, string>; body: string } {
|
||||
const lines = raw.split(/\r?\n/);
|
||||
if (lines[0] !== "---") return { data: {}, body: raw };
|
||||
const end = lines.indexOf("---", 1);
|
||||
if (end < 0) return { data: {}, body: raw };
|
||||
const data: Record<string, string> = {};
|
||||
for (let i = 1; i < end; i++) {
|
||||
const line = lines[i];
|
||||
if (!line) continue;
|
||||
const m = line.match(/^([a-zA-Z_][a-zA-Z0-9_-]*):\s*(.*)$/);
|
||||
if (m?.[1]) data[m[1]] = (m[2] ?? "").trim();
|
||||
}
|
||||
return {
|
||||
data,
|
||||
body: lines
|
||||
.slice(end + 1)
|
||||
.join("\n")
|
||||
.replace(/^\n+/, ""),
|
||||
};
|
||||
}
|
||||
|
||||
function isValidSkillName(name: string): boolean {
|
||||
return VALID_SKILL_NAME.test(name);
|
||||
}
|
||||
|
||||
export class SkillStore {
|
||||
private readonly homeDir: string;
|
||||
private readonly projectRoot: string | undefined;
|
||||
private readonly disableBuiltins: boolean;
|
||||
|
||||
constructor(opts: SkillStoreOptions = {}) {
|
||||
this.homeDir = opts.homeDir ?? homedir();
|
||||
this.projectRoot = opts.projectRoot ? resolve(opts.projectRoot) : undefined;
|
||||
this.disableBuiltins = opts.disableBuiltins === true;
|
||||
}
|
||||
|
||||
/** True iff this store was configured with a project root. */
|
||||
hasProjectScope(): boolean {
|
||||
return this.projectRoot !== undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Root directories scanned, in priority order. Project scope first
|
||||
* so a per-repo skill overrides a global one with the same name —
|
||||
* users expect the local copy to win when both exist.
|
||||
*/
|
||||
roots(): Array<{ dir: string; scope: SkillScope }> {
|
||||
const out: Array<{ dir: string; scope: SkillScope }> = [];
|
||||
if (this.projectRoot) {
|
||||
out.push({
|
||||
dir: join(this.projectRoot, ".reasonix", SKILLS_DIRNAME),
|
||||
scope: "project",
|
||||
});
|
||||
}
|
||||
out.push({ dir: join(this.homeDir, ".reasonix", SKILLS_DIRNAME), scope: "global" });
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* List every skill visible to this store. On name collisions the
|
||||
* higher-priority root (project over global over builtin) wins.
|
||||
* Sorted by name for stable prefix hashing.
|
||||
*/
|
||||
list(): Skill[] {
|
||||
const byName = new Map<string, Skill>();
|
||||
for (const { dir, scope } of this.roots()) {
|
||||
if (!existsSync(dir)) continue;
|
||||
let entries: import("node:fs").Dirent[];
|
||||
try {
|
||||
entries = readdirSync(dir, { withFileTypes: true });
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
for (const entry of entries) {
|
||||
const skill = this.readEntry(dir, scope, entry);
|
||||
if (!skill) continue;
|
||||
if (!byName.has(skill.name)) byName.set(skill.name, skill);
|
||||
}
|
||||
}
|
||||
// Builtins are appended last so user/project files take precedence
|
||||
// when names collide. The same priority you'd expect: my-project's
|
||||
// "explore" overrides the shipped one without forcing a different
|
||||
// name.
|
||||
if (!this.disableBuiltins) {
|
||||
for (const skill of BUILTIN_SKILLS) {
|
||||
if (!byName.has(skill.name)) byName.set(skill.name, skill);
|
||||
}
|
||||
}
|
||||
return [...byName.values()].sort((a, b) => a.name.localeCompare(b.name));
|
||||
}
|
||||
|
||||
/** Resolve one skill by name. Returns `null` if not found or malformed. */
|
||||
read(name: string): Skill | null {
|
||||
if (!isValidSkillName(name)) return null;
|
||||
for (const { dir, scope } of this.roots()) {
|
||||
if (!existsSync(dir)) continue;
|
||||
const dirCandidate = join(dir, name, SKILL_FILE);
|
||||
if (existsSync(dirCandidate) && statSync(dirCandidate).isFile()) {
|
||||
return this.parse(dirCandidate, name, scope);
|
||||
}
|
||||
const flatCandidate = join(dir, `${name}.md`);
|
||||
if (existsSync(flatCandidate) && statSync(flatCandidate).isFile()) {
|
||||
return this.parse(flatCandidate, name, scope);
|
||||
}
|
||||
}
|
||||
// Fall back to builtins. Same precedence as `list()` — user-authored
|
||||
// wins, builtins are the floor.
|
||||
if (!this.disableBuiltins) {
|
||||
for (const skill of BUILTIN_SKILLS) {
|
||||
if (skill.name === name) return skill;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private readEntry(dir: string, scope: SkillScope, entry: import("node:fs").Dirent): Skill | null {
|
||||
if (entry.isDirectory()) {
|
||||
if (!isValidSkillName(entry.name)) return null;
|
||||
const file = join(dir, entry.name, SKILL_FILE);
|
||||
if (!existsSync(file)) return null;
|
||||
return this.parse(file, entry.name, scope);
|
||||
}
|
||||
if (entry.isFile() && entry.name.endsWith(".md")) {
|
||||
const stem = entry.name.slice(0, -3);
|
||||
if (!isValidSkillName(stem)) return null;
|
||||
return this.parse(join(dir, entry.name), stem, scope);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private parse(path: string, stem: string, scope: SkillScope): Skill | null {
|
||||
let raw: string;
|
||||
try {
|
||||
raw = readFileSync(path, "utf8");
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
const { data, body } = parseFrontmatter(raw);
|
||||
const name = data.name && isValidSkillName(data.name) ? data.name : stem;
|
||||
return {
|
||||
name,
|
||||
description: (data.description ?? "").trim(),
|
||||
body: body.trim(),
|
||||
scope,
|
||||
path,
|
||||
allowedTools: data["allowed-tools"],
|
||||
runAs: parseRunAs(data.runAs),
|
||||
model: data.model?.startsWith("deepseek-") ? data.model : undefined,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Coerce a frontmatter `runAs` string to the discriminated union. Any
|
||||
* value other than the literal "subagent" is treated as inline — typos
|
||||
* and unknown values default to the safe (non-spawning) mode rather
|
||||
* than failing the load.
|
||||
*/
|
||||
function parseRunAs(raw: string | undefined): SkillRunAs {
|
||||
return raw?.trim() === "subagent" ? "subagent" : "inline";
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a single index line for one skill. Shape mirrors memory's
|
||||
* `indexLine` — a bullet suitable for a markdown fenced block in the
|
||||
* system prompt. Description is truncated to keep the full line under
|
||||
* ~150 chars.
|
||||
*
|
||||
* Subagent-runAs skills carry a `[🧬 subagent]` tag AFTER the name
|
||||
* so the model can't confuse the marker for part of the skill name.
|
||||
* (Historical bug: when the marker led the name — `- 🧬 explore` —
|
||||
* models would call `run_skill({ name: "🧬 explore" })` verbatim
|
||||
* and fail lookup. Wrapping the marker in brackets AFTER the name
|
||||
* eliminates that confusion; `run_skill`'s name arg also strips any
|
||||
* leading non-word chars as a belt-and-suspenders measure.)
|
||||
*/
|
||||
function skillIndexLine(s: Pick<Skill, "name" | "description" | "runAs">): string {
|
||||
const safeDesc = s.description.replace(/\n/g, " ").trim();
|
||||
const tag = s.runAs === "subagent" ? " [🧬 subagent]" : "";
|
||||
const max = 130 - s.name.length - tag.length;
|
||||
const clipped = safeDesc.length > max ? `${safeDesc.slice(0, Math.max(1, max - 1))}…` : safeDesc;
|
||||
return clipped ? `- ${s.name}${tag} — ${clipped}` : `- ${s.name}${tag}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Append a `# Skills` block to `basePrompt` listing every discovered
|
||||
* skill (name + description only). Bodies are NOT inlined — that's the
|
||||
* whole point: the prefix stays short and cacheable; full content loads
|
||||
* on demand via `run_skill` or `/skill <name>`.
|
||||
*
|
||||
* Emits nothing when no skills are discovered — keeps the prefix hash
|
||||
* stable for users who don't use skills at all.
|
||||
*/
|
||||
export function applySkillsIndex(basePrompt: string, opts: SkillStoreOptions = {}): string {
|
||||
const store = new SkillStore(opts);
|
||||
const skills = store.list().filter((s) => s.description);
|
||||
if (skills.length === 0) return basePrompt;
|
||||
const lines = skills.map(skillIndexLine);
|
||||
const joined = lines.join("\n");
|
||||
const truncated =
|
||||
joined.length > SKILLS_INDEX_MAX_CHARS
|
||||
? `${joined.slice(0, SKILLS_INDEX_MAX_CHARS)}\n… (truncated ${
|
||||
joined.length - SKILLS_INDEX_MAX_CHARS
|
||||
} chars)`
|
||||
: joined;
|
||||
return [
|
||||
basePrompt,
|
||||
"",
|
||||
"# Skills — playbooks you can invoke",
|
||||
"",
|
||||
'One-liner index. Each entry is either a built-in or a user-authored playbook. Call `run_skill({ name: "<skill-name>", arguments: "<task>" })` — the `name` is JUST the skill identifier (e.g. `"explore"`), NOT the `[🧬 subagent]` tag that appears after it. Entries tagged `[🧬 subagent]` spawn an **isolated subagent** — its tool calls and reasoning never enter your context, only its final answer does. Use subagent skills for tasks that would otherwise flood your context (deep exploration, multi-step research, anything where you only need the conclusion). Plain skills are inlined: their body becomes a tool result you read and act on directly. The user can also invoke a skill via `/skill <name>`.',
|
||||
"",
|
||||
"```",
|
||||
truncated,
|
||||
"```",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* Built-in skills shipped with Reasonix. These are always available
|
||||
* (no install step) and live as constants rather than files because:
|
||||
* - Zero filesystem coupling — no copy-on-first-run dance, nothing
|
||||
* to migrate when we update them.
|
||||
* - They participate in the same `byName` priority as user/project
|
||||
* skills: write `~/.reasonix/skills/explore.md` to override.
|
||||
*
|
||||
* Keep this list small and high-leverage. The bar for adding one: it
|
||||
* demonstrates a pattern users would otherwise have to invent
|
||||
* themselves, and the body fits in a screen.
|
||||
*/
|
||||
const BUILTIN_EXPLORE_BODY = `You are running as an exploration subagent. Your job is to investigate the codebase the parent agent pointed you at, then return one focused, distilled answer.
|
||||
|
||||
How to operate:
|
||||
- Use read_file, search_files, search_content, directory_tree, list_directory, get_file_info as your primary tools. Stay read-only.
|
||||
- For "find all places that call / reference / use X" questions, use \`search_content\` (content grep) — NOT \`search_files\` (which only matches file names). This is the most common subagent mistake; using the wrong tool gives empty results and you waste your iter budget chasing a phantom.
|
||||
- Cast a wide net first (search_content for symbol references, directory_tree for structure) to map the territory; then read the 3-10 most relevant files in full.
|
||||
- Don't read every file — be selective. Aim for breadth on the first pass, depth only where the question demands it.
|
||||
- Stop exploring as soon as you can answer the question. The parent doesn't see your tool calls, so over-exploration is pure waste.
|
||||
|
||||
Your final answer:
|
||||
- One paragraph (or a few short bullets). Lead with the conclusion.
|
||||
- Cite specific file paths + line ranges when they support the answer.
|
||||
- If the question can't be answered from what you found, say so plainly and suggest where to look next.
|
||||
- No follow-up offers, no "let me know if you need more." The parent will ask again if they need more.
|
||||
|
||||
${NEGATIVE_CLAIM_RULE}
|
||||
|
||||
${TUI_FORMATTING_RULES}
|
||||
|
||||
The 'task' the parent gave you is the question you must answer. Treat any other reading of it as scope creep.`;
|
||||
|
||||
const BUILTIN_RESEARCH_BODY = `You are running as a research subagent. Your job is to gather information from code AND the web, synthesize it, and return one focused conclusion.
|
||||
|
||||
How to operate:
|
||||
- Combine code reading (read_file, search_files) with web tools (web_search, web_fetch) as appropriate to the question.
|
||||
- For "how does X work" / "is Y supported" questions: web first to find the canonical reference, then verify against the local code.
|
||||
- For "what's our policy on Z" / "where do we use Q": local code first, web only if you need to compare against external standards.
|
||||
- Cap yourself at ~10 tool calls. If you can't converge in 10, return what you have plus a note about what's missing.
|
||||
|
||||
Your final answer:
|
||||
- One paragraph (or short bullets). Lead with the conclusion.
|
||||
- Cite both code (file:line) AND web sources (URL) when they back the answer.
|
||||
- Distinguish "I verified this in code" from "I read this on a docs page" — the parent will trust the former more.
|
||||
- If the answer is uncertain, say so. Don't invent confidence.
|
||||
|
||||
${NEGATIVE_CLAIM_RULE}
|
||||
|
||||
${TUI_FORMATTING_RULES}
|
||||
|
||||
The 'task' the parent gave you is the research question. Stay on it.`;
|
||||
|
||||
const BUILTIN_REVIEW_BODY = `You are running as a code-review subagent. Your job is to inspect the changes the user is about to ship — usually the current git branch vs its upstream — and produce a focused review the parent can hand back to the user.
|
||||
|
||||
How to operate:
|
||||
- Default scope: the current branch's diff vs the default branch. If the user's task names a specific commit range or files, honor that instead.
|
||||
- Discover scope first: \`run_command git status\`, \`git diff --stat\`, \`git log --oneline\` to see what changed. Then \`git diff\` (or \`git diff <base>...HEAD\`) for the actual hunks.
|
||||
- Read the touched files (\`read_file\`) when the diff alone doesn't carry enough context — function signatures, surrounding invariants, callers.
|
||||
- For "any callers depending on this?" questions: \`search_content\` against the symbol BEFORE asserting impact.
|
||||
- Stay read-only. Never \`run_command git commit\`, never write files, never propose SEARCH/REPLACE blocks. The parent decides whether to act on your findings.
|
||||
- Cap yourself at ~12 tool calls. If the diff is too big to review in one pass, pick the riskiest 2-3 files and say so explicitly.
|
||||
|
||||
What to look for, in priority order:
|
||||
1. **Correctness bugs** — off-by-one, null/undefined handling, race conditions, wrong sign / wrong operator, edge cases the code doesn't handle.
|
||||
2. **Security** — injection (SQL, shell, path traversal), secrets in code, missing authz checks, unsafe deserialization.
|
||||
3. **Behavior changes the diff hides** — renames that miss callers, removed branches that were load-bearing, error-handling that now swallows what used to surface.
|
||||
4. **Tests** — does the change have tests for the new behavior? Are existing tests still meaningful, or did the change make them tautological?
|
||||
5. **Style + consistency** — only flag deviations that matter (unsafe \`any\`, missing types in TypeScript, inconsistent error shape). Don't pile on cosmetic nits if the substance is clean.
|
||||
|
||||
Your final answer:
|
||||
- Lead with a one-sentence verdict: "ship as-is" / "minor nits, OK to ship after" / "blocking issues, do not ship".
|
||||
- Then a short bulleted list of issues, each with: file:line citation + the problem in one sentence + what to change.
|
||||
- Group by severity if you have more than 4 items: **Blocking**, **Should-fix**, **Nits**.
|
||||
- If everything looks clean, say so plainly. Don't manufacture concerns.
|
||||
|
||||
${NEGATIVE_CLAIM_RULE}
|
||||
|
||||
${TUI_FORMATTING_RULES}
|
||||
|
||||
The 'task' the parent gave you describes WHAT to review (a branch, a file set, or "the pending changes"). Stay on it; don't redesign the feature.`;
|
||||
|
||||
const BUILTIN_SECURITY_REVIEW_BODY = `You are running as a security-review subagent. Your job is to inspect the changes the user is about to ship — usually the current git branch vs its upstream — through a security lens specifically, and report exploitable issues.
|
||||
|
||||
How to operate:
|
||||
- Default scope: the current branch's diff vs the default branch. If the user names a different range or a directory, honor that.
|
||||
- Discover scope first: \`git status\`, \`git diff --stat\`, \`git diff <base>...HEAD\`. Read touched files (\`read_file\`) when the diff alone doesn't carry security context — auth checks, input validation, the actual handler that calls into the changed function.
|
||||
- Use \`search_content\` to verify "is this user-controlled input ever sanitized later?" / "are there other call sites that depend on this validation?" before asserting impact.
|
||||
- Stay read-only. Never write, never run destructive commands, never propose SEARCH/REPLACE blocks. The parent decides what to act on.
|
||||
- Cap yourself at ~12 tool calls. If the diff is too big, focus on the riskiest 2-3 files and say so explicitly.
|
||||
|
||||
Threat model — flag with severity:
|
||||
|
||||
**CRITICAL** (do-not-ship):
|
||||
- SQL / NoSQL / shell / template injection — user input concatenated into a query, command, or template without parameterization.
|
||||
- Path traversal — user-controlled filenames touching the filesystem without canonicalization + sandbox check.
|
||||
- Authentication / authorization missing — endpoints / actions that should require a session check but don't.
|
||||
- Hardcoded secrets — API keys, passwords, signing tokens visible in the diff.
|
||||
- Deserialization of untrusted input — \`pickle.loads\`, \`yaml.load\` (non-safe), \`eval\`, \`Function()\`, \`unserialize()\`.
|
||||
- Cryptographic mistakes — homemade crypto, weak hashes (MD5/SHA-1) for passwords, missing IVs, ECB mode, predictable nonces.
|
||||
|
||||
**HIGH**:
|
||||
- XSS — user input rendered into HTML without escaping (or wrong escaping context).
|
||||
- SSRF — fetching URLs from user input without an allowlist.
|
||||
- Race conditions in security-relevant code — TOCTOU on auth/file checks.
|
||||
- Open redirects — user-controlled URL passed to a redirect helper.
|
||||
- Insufficient logging on security events (login failure, permission denial) — only flag if the codebase clearly DOES log elsewhere.
|
||||
|
||||
**MEDIUM**:
|
||||
- Verbose error messages leaking internal paths / stack traces / SQL.
|
||||
- Missing rate limiting on a credential / token endpoint.
|
||||
- Cross-origin / cookie-flag issues (missing \`Secure\` / \`HttpOnly\` / \`SameSite\`).
|
||||
|
||||
Things to NOT pile on (out of scope here — the regular /review covers them):
|
||||
- Style, formatting, naming.
|
||||
- Performance, refactor opportunities, test coverage gaps that aren't security-relevant.
|
||||
- "Should be a constant" / "extract this helper" — irrelevant to ship-blocking.
|
||||
|
||||
Your final answer:
|
||||
- Lead with a one-sentence verdict: "no security issues found", "minor concerns", or "blocking issues".
|
||||
- Then a list grouped by severity. Each item: file:line + 1-sentence threat + 1-sentence fix direction (no full SEARCH/REPLACE — the user / parent agent will write that).
|
||||
- If clean, say so plainly. Don't manufacture findings.
|
||||
|
||||
${NEGATIVE_CLAIM_RULE}
|
||||
|
||||
${TUI_FORMATTING_RULES}
|
||||
|
||||
The 'task' the parent gave you names what to review. Stay on it; don't redesign the feature.`;
|
||||
|
||||
const BUILTIN_TEST_BODY = `You are running as the parent agent — this skill is INLINED, not a subagent. The user invoked /test (or asked you to "run the tests and fix failures"). Your job: run the project's test suite, diagnose any failure, propose fixes as SEARCH/REPLACE edit blocks, then re-run. Repeat until green or you hit a wall you should escalate.
|
||||
|
||||
How to operate:
|
||||
|
||||
1. **Detect the test command**.
|
||||
- Look for \`package.json\` → \`scripts.test\` first (most common: \`npm test\`, \`pnpm test\`, \`yarn test\`).
|
||||
- If no package.json or no test script: try \`pytest\`, \`go test ./...\`, \`cargo test\` based on what files exist (pyproject.toml/requirements.txt → pytest; go.mod → go test; Cargo.toml → cargo test).
|
||||
- If you can't tell, ASK the user for the command — don't guess. One question, one tool call to confirm.
|
||||
|
||||
2. **Run it via run_command** (typical timeout 120s, bigger if the suite is large). Capture stdout + stderr.
|
||||
|
||||
3. **Read the failures**. Pull out: which test names failed, the actual error/traceback, the file + line that threw. Don't just paraphrase — locate the exact assertion or stack frame.
|
||||
|
||||
4. **Propose fixes**. For each distinct failure:
|
||||
- If the failure is in PRODUCTION code (test catches a real bug) → propose a SEARCH/REPLACE that fixes the production code.
|
||||
- If the failure is in TEST code (test is wrong, codebase is right) → propose a SEARCH/REPLACE that updates the test, AND say so explicitly: "This is a test bug, not a production bug — updating the assertion."
|
||||
- If the failure is environmental (missing dep, wrong node version, missing fixture file) → say so and stop. Don't try to install packages or change config without checking with the user.
|
||||
|
||||
5. **Apply + re-run**. After the user accepts the edit blocks, run the test command again. Iterate.
|
||||
|
||||
6. **Stop conditions**:
|
||||
- All tests pass → report green, summarize what changed.
|
||||
- Same test still failing after 2 fix attempts on the same line → STOP. Tell the user "I've tried twice, it's still failing — here's what I think is happening, want me to try a different angle?". Don't loop indefinitely.
|
||||
- 3+ unrelated failures → fix one at a time, smallest first, so each pass narrows the surface.
|
||||
|
||||
Don't:
|
||||
- Run \`npm install\` / \`pip install\` / \`cargo update\` without asking — those mutate lockfiles and have global effects.
|
||||
- Disable, skip, or delete failing tests to "make it green". If a test seems wrong, update its assertion with a one-sentence explanation, but never add \`.skip\` / \`it.skip\` / \`@pytest.mark.skip\`.
|
||||
- Modify the test runner config (vitest.config, jest.config, etc.) to silence failures.
|
||||
|
||||
Lead each turn with a one-line status: "▸ running \`npm test\` ..." → "▸ 2 failures in tests/foo.test.ts — first is …" → so the user always knows where you are without scrolling tool output.`;
|
||||
|
||||
const BUILTIN_SKILLS: readonly Skill[] = Object.freeze([
|
||||
Object.freeze<Skill>({
|
||||
name: "explore",
|
||||
description:
|
||||
"Explore the codebase in an isolated subagent — wide-net read-only investigation that returns one distilled answer. Best for: 'find all places that...', 'how does X work across the project', 'survey the code for Y'.",
|
||||
body: BUILTIN_EXPLORE_BODY,
|
||||
scope: "builtin",
|
||||
path: "(builtin)",
|
||||
runAs: "subagent",
|
||||
}),
|
||||
Object.freeze<Skill>({
|
||||
name: "research",
|
||||
description:
|
||||
"Research a question by combining web search + code reading in an isolated subagent. Best for: 'is X feature supported by lib Y', 'what's the canonical way to do Z', 'compare our impl against the spec'.",
|
||||
body: BUILTIN_RESEARCH_BODY,
|
||||
scope: "builtin",
|
||||
path: "(builtin)",
|
||||
runAs: "subagent",
|
||||
}),
|
||||
Object.freeze<Skill>({
|
||||
name: "review",
|
||||
description:
|
||||
"Review the pending changes (current branch diff by default) in an isolated subagent — flags correctness, security, missing tests, hidden behavior changes; reports verdict + per-issue file:line. Read-only; the parent decides what to act on.",
|
||||
body: BUILTIN_REVIEW_BODY,
|
||||
scope: "builtin",
|
||||
path: "(builtin)",
|
||||
runAs: "subagent",
|
||||
}),
|
||||
Object.freeze<Skill>({
|
||||
name: "security-review",
|
||||
description:
|
||||
"Security-focused review of the current branch diff in an isolated subagent — flags injection/authz/secrets/deserialization/path-traversal/crypto issues, severity-tagged. Read-only. Use when shipping changes that touch auth, input parsing, file IO, or external requests.",
|
||||
body: BUILTIN_SECURITY_REVIEW_BODY,
|
||||
scope: "builtin",
|
||||
path: "(builtin)",
|
||||
runAs: "subagent",
|
||||
}),
|
||||
Object.freeze<Skill>({
|
||||
name: "test",
|
||||
description:
|
||||
"Run the project's test suite, diagnose failures, propose SEARCH/REPLACE fixes, re-run until green (or stop after 2 fix attempts on the same failure). Inlined — runs in the parent loop so you see the edit blocks and can /apply them. Detects npm/pnpm/yarn/pytest/go/cargo.",
|
||||
body: BUILTIN_TEST_BODY,
|
||||
scope: "builtin",
|
||||
path: "(builtin)",
|
||||
runAs: "inline",
|
||||
}),
|
||||
]);
|
||||
+45
-8
@@ -1,12 +1,33 @@
|
||||
import type { Usage } from "./client.js";
|
||||
|
||||
/** USD per 1M tokens. Update as DeepSeek pricing changes. */
|
||||
/**
|
||||
* USD per 1M tokens. Source: DeepSeek's CNY price sheet
|
||||
* (https://api-docs.deepseek.com/zh-cn/quick_start/pricing) converted
|
||||
* at a fixed 7.2 CNY/USD rate so billing stays stable across daily FX
|
||||
* drift; revisit if the rate moves more than ±5%.
|
||||
*
|
||||
* 2026-04 V4 launch:
|
||||
* - deepseek-v4-flash ¥0.2 / ¥1 / ¥2 (hit / miss / out per 1M)
|
||||
* - deepseek-v4-pro ¥1 / ¥12 / ¥24
|
||||
*
|
||||
* deepseek-chat and deepseek-reasoner are now thin compat aliases for
|
||||
* v4-flash's non-thinking and thinking modes respectively — same
|
||||
* underlying model, same bill. We keep them in the table so existing
|
||||
* sessions (and configs that hard-code these names) keep pricing.
|
||||
*
|
||||
* Historical note: sessions logged before this file was updated remain
|
||||
* as-is in `~/.reasonix/usage.jsonl` — USD is frozen at record time,
|
||||
* we never retroactively rewrite billing history.
|
||||
*/
|
||||
export const DEEPSEEK_PRICING: Record<
|
||||
string,
|
||||
{ inputCacheHit: number; inputCacheMiss: number; output: number }
|
||||
> = {
|
||||
"deepseek-chat": { inputCacheHit: 0.07, inputCacheMiss: 0.27, output: 1.1 },
|
||||
"deepseek-reasoner": { inputCacheHit: 0.14, inputCacheMiss: 0.55, output: 2.19 },
|
||||
"deepseek-v4-flash": { inputCacheHit: 0.028, inputCacheMiss: 0.139, output: 0.278 },
|
||||
"deepseek-v4-pro": { inputCacheHit: 0.139, inputCacheMiss: 1.667, output: 3.333 },
|
||||
// Compat aliases — priced as v4-flash per the deprecation notice.
|
||||
"deepseek-chat": { inputCacheHit: 0.028, inputCacheMiss: 0.139, output: 0.278 },
|
||||
"deepseek-reasoner": { inputCacheHit: 0.028, inputCacheMiss: 0.139, output: 0.278 },
|
||||
};
|
||||
|
||||
/** Reference Claude Sonnet 4.6 pricing (USD per 1M tokens). */
|
||||
@@ -14,13 +35,21 @@ export const CLAUDE_SONNET_PRICING = { input: 3.0, output: 15.0 };
|
||||
|
||||
/**
|
||||
* Maximum prompt-side context window per DeepSeek model, in tokens.
|
||||
* Both V3 (`deepseek-chat`) and R1 (`deepseek-reasoner`) currently expose
|
||||
* a 131,072-token prompt limit per the OpenAPI spec; completion caps
|
||||
* differ but don't affect the prompt budget the StatsPanel shows.
|
||||
* V4 (flash + pro) jumps to 1,000,000 tokens. The compat aliases
|
||||
* (deepseek-chat / deepseek-reasoner) inherit that through the
|
||||
* v4-flash route — we bump them so the StatsPanel gauge reflects
|
||||
* what the API actually accepts.
|
||||
*
|
||||
* Completion caps (e.g. 384K for V4) are enforced by the server, not
|
||||
* tracked here — they don't affect the prompt-side budget the panel
|
||||
* shows. If a future feature surfaces output-cap warnings we'll add
|
||||
* a sibling table.
|
||||
*/
|
||||
export const DEEPSEEK_CONTEXT_TOKENS: Record<string, number> = {
|
||||
"deepseek-chat": 131_072,
|
||||
"deepseek-reasoner": 131_072,
|
||||
"deepseek-v4-flash": 1_000_000,
|
||||
"deepseek-v4-pro": 1_000_000,
|
||||
"deepseek-chat": 1_000_000,
|
||||
"deepseek-reasoner": 1_000_000,
|
||||
};
|
||||
|
||||
/** Fallback when the caller's model id isn't in the table — safe lower bound. */
|
||||
@@ -94,6 +123,13 @@ export interface SessionSummary {
|
||||
* prompt + user delta + any new tool outputs).
|
||||
*/
|
||||
lastPromptTokens: number;
|
||||
/**
|
||||
* Most recent turn's USD cost. Complements `totalCostUsd` so the TUI
|
||||
* can render "this turn: $X · session: $Y" — users asked for a
|
||||
* per-turn signal so a mid-session jump from flash to pro is
|
||||
* immediately visible, not hidden inside the session aggregate.
|
||||
*/
|
||||
lastTurnCostUsd: number;
|
||||
}
|
||||
|
||||
export class SessionStats {
|
||||
@@ -155,6 +191,7 @@ export class SessionStats {
|
||||
savingsVsClaudePct: round(this.savingsVsClaude * 100, 2),
|
||||
cacheHitRatio: round(this.aggregateCacheHitRatio, 4),
|
||||
lastPromptTokens: last?.usage.promptTokens ?? 0,
|
||||
lastTurnCostUsd: round(last?.cost ?? 0, 6),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,375 @@
|
||||
/**
|
||||
* Pure-TS port of DeepSeek's V3 tokenizer. Reads the slimmed+gzipped
|
||||
* HuggingFace-format tokenizer data shipped at
|
||||
* `data/deepseek-tokenizer.json.gz` and implements enough of the HF
|
||||
* pipeline (Split pre-tokenizers → ByteLevel → BPE) to count tokens
|
||||
* offline without pulling the `@lenml/tokenizers` or native Rust deps.
|
||||
*
|
||||
* Accuracy target: within ~3% of the API-returned `usage.prompt_tokens`
|
||||
* for mixed CJK+English+code input. Exact-to-API match would also
|
||||
* require replaying the Jinja chat template (role markers / tool call
|
||||
* framing); we intentionally skip that — for a gauge/UI estimate the
|
||||
* raw-text count is the useful number.
|
||||
*
|
||||
* Scope: ENCODE-SIDE ONLY. We don't need decode for counting; adding
|
||||
* it later is trivial via the inverse byte-level table.
|
||||
*/
|
||||
|
||||
import { existsSync, readFileSync } from "node:fs";
|
||||
import { createRequire } from "node:module";
|
||||
import { dirname, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { gunzipSync } from "node:zlib";
|
||||
|
||||
interface AddedToken {
|
||||
id: number;
|
||||
content: string;
|
||||
special: boolean;
|
||||
normalized: boolean;
|
||||
}
|
||||
|
||||
interface SplitPretokenizer {
|
||||
type: "Split";
|
||||
pattern: { Regex: string };
|
||||
behavior: "Isolated" | "Removed" | string;
|
||||
invert: boolean;
|
||||
}
|
||||
|
||||
interface ByteLevelPretokenizer {
|
||||
type: "ByteLevel";
|
||||
add_prefix_space: boolean;
|
||||
trim_offsets: boolean;
|
||||
use_regex: boolean;
|
||||
}
|
||||
|
||||
type Pretokenizer = SplitPretokenizer | ByteLevelPretokenizer;
|
||||
|
||||
interface TokenizerData {
|
||||
added_tokens: AddedToken[];
|
||||
pre_tokenizer: {
|
||||
type: "Sequence";
|
||||
pretokenizers: Pretokenizer[];
|
||||
};
|
||||
model: {
|
||||
type: "BPE";
|
||||
vocab: Record<string, number>;
|
||||
merges: string[];
|
||||
};
|
||||
}
|
||||
|
||||
interface LoadedTokenizer {
|
||||
vocab: Record<string, number>;
|
||||
mergeRank: Map<string, number>;
|
||||
splitRegexes: RegExp[];
|
||||
byteToChar: string[];
|
||||
/**
|
||||
* Non-special added tokens (e.g. `<think>`, `<|fim▁hole|>`) that the
|
||||
* HF tokenizer recognizes as atomic units when they appear inline in
|
||||
* the text. Special tokens like `<|begin▁of▁sentence|>` are NOT in
|
||||
* this list — the model ignores them when they appear in user text
|
||||
* (the default HF `split_special_tokens=False` behavior), so we do
|
||||
* the same: they get tokenized byte-by-byte, not as the special ID.
|
||||
*/
|
||||
addedPattern: RegExp | null;
|
||||
addedMap: Map<string, number>;
|
||||
}
|
||||
|
||||
/**
|
||||
* GPT-2 byte-to-unicode mapping. Covers every byte 0..255 with a
|
||||
* deterministic visible-printable unicode char — this is what lets the
|
||||
* byte-level BPE show up in JSON vocabs as readable strings (`Ġ` for
|
||||
* space, `Ċ` for `\n`, etc). Identical across every byte-level BPE
|
||||
* tokenizer DeepSeek ships.
|
||||
*/
|
||||
function buildByteToChar(): string[] {
|
||||
const result: string[] = new Array(256);
|
||||
const bs: number[] = [];
|
||||
for (let b = 33; b <= 126; b++) bs.push(b);
|
||||
for (let b = 161; b <= 172; b++) bs.push(b);
|
||||
for (let b = 174; b <= 255; b++) bs.push(b);
|
||||
const cs = bs.slice();
|
||||
let n = 0;
|
||||
for (let b = 0; b < 256; b++) {
|
||||
if (!bs.includes(b)) {
|
||||
bs.push(b);
|
||||
cs.push(256 + n);
|
||||
n++;
|
||||
}
|
||||
}
|
||||
for (let i = 0; i < bs.length; i++) {
|
||||
result[bs[i]!] = String.fromCodePoint(cs[i]!);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
let cached: LoadedTokenizer | null = null;
|
||||
|
||||
/**
|
||||
* Find the bundled tokenizer data file. Resolution order (first hit wins):
|
||||
* 1. `REASONIX_TOKENIZER_PATH` env var (tests / custom builds).
|
||||
* 2. `../data/deepseek-tokenizer.json.gz` relative to this module —
|
||||
* covers dev (src/tokenizer.ts → data/) AND production bundled at
|
||||
* dist/index.js → dist/../data = data/.
|
||||
* 3. `../../data/deepseek-tokenizer.json.gz` — covers the CLI bundle
|
||||
* at dist/cli/index.js → dist/cli/../../data = data/. Without this
|
||||
* step 2 resolves to dist/data/ which doesn't exist (the data file
|
||||
* is shipped at package root per package.json `files` entry), and
|
||||
* every step() preflight crashes the loop with ENOENT.
|
||||
* 4. `require.resolve("reasonix/package.json")` — last-resort package
|
||||
* root lookup for unusual bundlers.
|
||||
*/
|
||||
function resolveDataPath(): string {
|
||||
if (process.env.REASONIX_TOKENIZER_PATH) return process.env.REASONIX_TOKENIZER_PATH;
|
||||
const candidates: string[] = [];
|
||||
try {
|
||||
const here = dirname(fileURLToPath(import.meta.url));
|
||||
candidates.push(join(here, "..", "data", "deepseek-tokenizer.json.gz"));
|
||||
candidates.push(join(here, "..", "..", "data", "deepseek-tokenizer.json.gz"));
|
||||
} catch {
|
||||
/* import.meta.url unavailable — skip to the package resolution step. */
|
||||
}
|
||||
try {
|
||||
const req = createRequire(import.meta.url);
|
||||
candidates.push(
|
||||
join(dirname(req.resolve("reasonix/package.json")), "data", "deepseek-tokenizer.json.gz"),
|
||||
);
|
||||
} catch {
|
||||
/* Not installed as `reasonix/` — the earlier candidates still may hit. */
|
||||
}
|
||||
for (const p of candidates) {
|
||||
if (existsSync(p)) return p;
|
||||
}
|
||||
// Nothing exists — return the first candidate anyway so readFileSync
|
||||
// surfaces a concrete path in the ENOENT message (better than silent miss).
|
||||
return candidates[0] ?? join(process.cwd(), "data", "deepseek-tokenizer.json.gz");
|
||||
}
|
||||
|
||||
function loadTokenizer(): LoadedTokenizer {
|
||||
if (cached) return cached;
|
||||
const buf = readFileSync(resolveDataPath());
|
||||
const json = gunzipSync(buf).toString("utf8");
|
||||
const data = JSON.parse(json) as TokenizerData;
|
||||
|
||||
const mergeRank = new Map<string, number>();
|
||||
for (let i = 0; i < data.model.merges.length; i++) {
|
||||
mergeRank.set(data.model.merges[i]!, i);
|
||||
}
|
||||
|
||||
const splitRegexes: RegExp[] = [];
|
||||
for (const p of data.pre_tokenizer.pretokenizers) {
|
||||
if (p.type === "Split") {
|
||||
// All three Split rules use Isolated — matches become their own
|
||||
// pre-tokens and so do the in-between stretches. The ByteLevel
|
||||
// stage in the Sequence does no extra splitting here
|
||||
// (use_regex:false), so our 3 Split regexes are the whole story.
|
||||
splitRegexes.push(new RegExp(p.pattern.Regex, "gu"));
|
||||
}
|
||||
}
|
||||
|
||||
const addedMap = new Map<string, number>();
|
||||
const addedContents: string[] = [];
|
||||
for (const t of data.added_tokens) {
|
||||
if (!t.special) {
|
||||
addedMap.set(t.content, t.id);
|
||||
addedContents.push(t.content);
|
||||
}
|
||||
}
|
||||
// Longest-first ensures greedy matching doesn't lose a longer token
|
||||
// to a shorter prefix (e.g. `<think>` before `<`).
|
||||
addedContents.sort((a, b) => b.length - a.length);
|
||||
const addedPattern = addedContents.length
|
||||
? new RegExp(addedContents.map(escapeRegex).join("|"), "g")
|
||||
: null;
|
||||
|
||||
cached = {
|
||||
vocab: data.model.vocab,
|
||||
mergeRank,
|
||||
splitRegexes,
|
||||
byteToChar: buildByteToChar(),
|
||||
addedPattern,
|
||||
addedMap,
|
||||
};
|
||||
return cached;
|
||||
}
|
||||
|
||||
function escapeRegex(s: string): string {
|
||||
return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply one "Isolated" Split: the matches become their own pre-tokens,
|
||||
* stretches between matches pass through unchanged. Empty pre-tokens
|
||||
* are dropped so downstream stages don't see them.
|
||||
*/
|
||||
function applySplit(chunks: string[], re: RegExp): string[] {
|
||||
const out: string[] = [];
|
||||
for (const chunk of chunks) {
|
||||
if (!chunk) continue;
|
||||
// Reset lastIndex — reusing a /g regex across matchAll iterations
|
||||
// is safe (matchAll internally advances), but across different
|
||||
// input strings we want a clean start.
|
||||
re.lastIndex = 0;
|
||||
let last = 0;
|
||||
for (const m of chunk.matchAll(re)) {
|
||||
const idx = m.index ?? 0;
|
||||
if (idx > last) out.push(chunk.slice(last, idx));
|
||||
if (m[0].length > 0) out.push(m[0]);
|
||||
last = idx + m[0].length;
|
||||
}
|
||||
if (last < chunk.length) out.push(chunk.slice(last));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** UTF-8 bytes of `s`, each mapped to its byte-level visible char. */
|
||||
function byteLevelEncode(s: string, byteToChar: string[]): string {
|
||||
const bytes = new TextEncoder().encode(s);
|
||||
let out = "";
|
||||
for (let i = 0; i < bytes.length; i++) out += byteToChar[bytes[i]!];
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard BPE merge loop. Starts from single byte-level chars and
|
||||
* repeatedly applies the lowest-rank merge until none remain. O(n²)
|
||||
* in chunk length, which is fine because chunks are ≤ a few hundred
|
||||
* byte-level chars after pre-tokenization (and most are <50).
|
||||
*/
|
||||
function bpeEncode(piece: string, mergeRank: Map<string, number>): string[] {
|
||||
if (piece.length <= 1) return piece ? [piece] : [];
|
||||
let word: string[] = Array.from(piece);
|
||||
while (true) {
|
||||
let bestIdx = -1;
|
||||
let bestRank = Number.POSITIVE_INFINITY;
|
||||
for (let i = 0; i < word.length - 1; i++) {
|
||||
const pair = `${word[i]} ${word[i + 1]}`;
|
||||
const rank = mergeRank.get(pair);
|
||||
if (rank !== undefined && rank < bestRank) {
|
||||
bestRank = rank;
|
||||
bestIdx = i;
|
||||
if (rank === 0) break; // 0 is already the best possible
|
||||
}
|
||||
}
|
||||
if (bestIdx < 0) break;
|
||||
word = [
|
||||
...word.slice(0, bestIdx),
|
||||
word[bestIdx]! + word[bestIdx + 1]!,
|
||||
...word.slice(bestIdx + 2),
|
||||
];
|
||||
if (word.length === 1) break;
|
||||
}
|
||||
return word;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tokenize a UTF-8 string into DeepSeek token IDs. Mirrors the HF
|
||||
* pipeline: (1) isolate non-special added tokens so they stay atomic,
|
||||
* (2) for each in-between segment run the three Split regexes, (3)
|
||||
* byte-level encode, (4) BPE merge, (5) look up vocab IDs.
|
||||
*
|
||||
* Not reentrancy-hazardous: loads a module-level singleton on first
|
||||
* call and reuses it. Subsequent calls are pure compute.
|
||||
*/
|
||||
export function encode(text: string): number[] {
|
||||
if (!text) return [];
|
||||
const t = loadTokenizer();
|
||||
const ids: number[] = [];
|
||||
|
||||
const process = (segment: string) => {
|
||||
if (!segment) return;
|
||||
let chunks: string[] = [segment];
|
||||
for (const re of t.splitRegexes) chunks = applySplit(chunks, re);
|
||||
for (const chunk of chunks) {
|
||||
if (!chunk) continue;
|
||||
const byteLevel = byteLevelEncode(chunk, t.byteToChar);
|
||||
const pieces = bpeEncode(byteLevel, t.mergeRank);
|
||||
for (const p of pieces) {
|
||||
const id = t.vocab[p];
|
||||
// If not in vocab we silently skip: shouldn't happen for
|
||||
// byte-level BPE (every single byte has its own vocab entry),
|
||||
// but if a future tokenizer update breaks that invariant we'd
|
||||
// rather under-count than throw from a UI gauge.
|
||||
if (id !== undefined) ids.push(id);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if (t.addedPattern) {
|
||||
t.addedPattern.lastIndex = 0;
|
||||
let last = 0;
|
||||
for (const m of text.matchAll(t.addedPattern)) {
|
||||
const idx = m.index ?? 0;
|
||||
if (idx > last) process(text.slice(last, idx));
|
||||
const id = t.addedMap.get(m[0]);
|
||||
if (id !== undefined) ids.push(id);
|
||||
last = idx + m[0].length;
|
||||
}
|
||||
if (last < text.length) process(text.slice(last));
|
||||
} else {
|
||||
process(text);
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fast path for UI: we only need the count, not the IDs. Saves a
|
||||
* per-call array allocation and lets callers batch large logs
|
||||
* without holding the full ID stream.
|
||||
*/
|
||||
export function countTokens(text: string): number {
|
||||
return encode(text).length;
|
||||
}
|
||||
|
||||
/**
|
||||
* Estimate the tokens a full conversation would cost. Sums raw-text
|
||||
* counts for every message's content; we do NOT add overhead for the
|
||||
* chat template's role markers (`<|User|>`, `<|Assistant|>`) because
|
||||
* the exact framing varies between the chat/reasoner templates and
|
||||
* DeepSeek applies them server-side anyway. Empirically adds ~3-6%
|
||||
* to the real `prompt_tokens` — callers who care can post-multiply.
|
||||
*/
|
||||
export function estimateConversationTokens(
|
||||
messages: Array<{ content?: string | null; tool_calls?: unknown }>,
|
||||
): number {
|
||||
let total = 0;
|
||||
for (const m of messages) {
|
||||
if (typeof m.content === "string" && m.content) {
|
||||
total += countTokens(m.content);
|
||||
}
|
||||
// Tool-call arguments are serialized as JSON in the prompt by the
|
||||
// chat template; their bytes WILL count upstream, so we count
|
||||
// them too. Stringify-once is cheap relative to the tokenize.
|
||||
if (m.tool_calls && Array.isArray(m.tool_calls) && m.tool_calls.length > 0) {
|
||||
total += countTokens(JSON.stringify(m.tool_calls));
|
||||
}
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
/**
|
||||
* Estimate the tokens a full DeepSeek request would cost: the
|
||||
* conversation-side tokens (what `estimateConversationTokens` already
|
||||
* counts) PLUS the serialized tool-spec payload. Tool specs ride in
|
||||
* their own JSON blob in the request body, not folded into any
|
||||
* message's `content`, so they need a separate count to land an
|
||||
* accurate preflight estimate.
|
||||
*
|
||||
* Returned number matches what `/context` displays for "next request"
|
||||
* — reuse this helper anywhere (preflight guard, diagnostics, UI) to
|
||||
* keep the two values from drifting.
|
||||
*/
|
||||
export function estimateRequestTokens(
|
||||
messages: Array<{ content?: string | null; tool_calls?: unknown }>,
|
||||
toolSpecs?: ReadonlyArray<unknown> | null,
|
||||
): number {
|
||||
let total = estimateConversationTokens(messages);
|
||||
if (toolSpecs && toolSpecs.length > 0) {
|
||||
total += countTokens(JSON.stringify(toolSpecs));
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
/** Exposed for tests — resets the lazy-load singleton. */
|
||||
export function _resetForTests(): void {
|
||||
cached = null;
|
||||
}
|
||||
+138
-3
@@ -1,3 +1,4 @@
|
||||
import { truncateForModel, truncateForModelByTokens } from "./mcp/registry.js";
|
||||
import { analyzeSchema, flattenSchema, nestArguments } from "./repair/flatten.js";
|
||||
import type { JSONSchema, ToolSpec } from "./types.js";
|
||||
|
||||
@@ -17,6 +18,25 @@ export interface ToolDefinition<A = any, R = any> {
|
||||
name: string;
|
||||
description?: string;
|
||||
parameters?: JSONSchema;
|
||||
/**
|
||||
* Marks a tool as read-only: safe to invoke during plan mode. `true`
|
||||
* for tools that only observe (read_file, list_directory, search, web
|
||||
* fetch/search). Leave undefined / `false` for anything that can write,
|
||||
* execute, or mutate state.
|
||||
*
|
||||
* The registry enforces this at dispatch: non-readonly tools called
|
||||
* while `planMode` is on return a refusal string the model can
|
||||
* learn from, instead of actually running.
|
||||
*/
|
||||
readOnly?: boolean;
|
||||
/**
|
||||
* Dynamic read-only check for tools whose safety depends on arguments
|
||||
* — `run_command` with an allowlisted argv is safe, `run_command
|
||||
* rm -rf` isn't. Called with the parsed arguments; `true` means "treat
|
||||
* as read-only for plan mode". Takes precedence over `readOnly` when
|
||||
* both are set.
|
||||
*/
|
||||
readOnlyCheck?: (args: A) => boolean;
|
||||
fn: (args: A, ctx?: ToolCallContext) => R | Promise<R>;
|
||||
}
|
||||
|
||||
@@ -39,14 +59,63 @@ export interface ToolRegistryOptions {
|
||||
autoFlatten?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Callback form for `setToolInterceptor` — receives the tool name and
|
||||
* already-parsed arguments; returns a string to short-circuit dispatch
|
||||
* (the returned value becomes the tool result the model sees), or
|
||||
* `null` / `undefined` to fall through to the registered tool fn.
|
||||
*
|
||||
* Used by `reasonix code`'s edit-mode gate: `edit_file` / `write_file`
|
||||
* are intercepted in "review" mode (queued into pendingEdits, returning
|
||||
* "queued for /apply") or handled inline in "auto" mode (snapshot +
|
||||
* apply, then surface an undo banner). Other tools pass through.
|
||||
*/
|
||||
export type ToolInterceptor = (
|
||||
name: string,
|
||||
args: Record<string, unknown>,
|
||||
) => string | null | undefined | Promise<string | null | undefined>;
|
||||
|
||||
export class ToolRegistry {
|
||||
private readonly _tools = new Map<string, InternalTool>();
|
||||
private readonly _autoFlatten: boolean;
|
||||
/**
|
||||
* When true, `dispatch` refuses any tool whose `readOnly` flag isn't
|
||||
* set (and whose `readOnlyCheck` doesn't pass on the specific args).
|
||||
* Drives `reasonix code`'s Plan Mode — the model can still explore
|
||||
* via read tools but its writes and non-allowlisted shell calls are
|
||||
* bounced until the user approves a submitted plan.
|
||||
*/
|
||||
private _planMode = false;
|
||||
/**
|
||||
* Optional hook run after arg parsing but before tool.fn. Lets the TUI
|
||||
* reroute specific tool calls (e.g. edit_file in review mode) without
|
||||
* modifying the tool definitions themselves.
|
||||
*/
|
||||
private _interceptor: ToolInterceptor | null = null;
|
||||
|
||||
constructor(opts: ToolRegistryOptions = {}) {
|
||||
this._autoFlatten = opts.autoFlatten !== false;
|
||||
}
|
||||
|
||||
/** Enable / disable plan-mode enforcement at dispatch. */
|
||||
setPlanMode(on: boolean): void {
|
||||
this._planMode = Boolean(on);
|
||||
}
|
||||
|
||||
/** True when the registry is currently refusing non-readonly calls. */
|
||||
get planMode(): boolean {
|
||||
return this._planMode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Install or clear the dispatch interceptor. At most one interceptor
|
||||
* is active at a time — calling twice replaces the previous. Pass
|
||||
* `null` to remove.
|
||||
*/
|
||||
setToolInterceptor(fn: ToolInterceptor | null): void {
|
||||
this._interceptor = fn;
|
||||
}
|
||||
|
||||
register<A, R>(def: ToolDefinition<A, R>): this {
|
||||
if (!def.name) throw new Error("tool requires a name");
|
||||
const internal: InternalTool = { ...(def as ToolDefinition) };
|
||||
@@ -91,7 +160,7 @@ export class ToolRegistry {
|
||||
async dispatch(
|
||||
name: string,
|
||||
argumentsRaw: string | Record<string, unknown>,
|
||||
opts: { signal?: AbortSignal } = {},
|
||||
opts: { signal?: AbortSignal; maxResultChars?: number; maxResultTokens?: number } = {},
|
||||
): Promise<string> {
|
||||
const tool = this._tools.get(name);
|
||||
if (!tool) {
|
||||
@@ -120,17 +189,83 @@ export class ToolRegistry {
|
||||
args = nestArguments(args);
|
||||
}
|
||||
|
||||
// Plan-mode enforcement — runs AFTER arg parsing so a tool with a
|
||||
// runtime `readOnlyCheck` can inspect the actual args (e.g.
|
||||
// `run_command` is read-only iff the command matches its allowlist).
|
||||
if (this._planMode && !isReadOnlyCall(tool, args)) {
|
||||
return JSON.stringify({
|
||||
error: `${name}: unavailable in plan mode — this is a read-only exploration phase. Use read_file / list_directory / search_files / directory_tree / web_search / allowlisted shell commands to investigate. Call submit_plan with your proposed plan when you're ready for the user's review.`,
|
||||
});
|
||||
}
|
||||
|
||||
// Interceptor runs after plan-mode (so a plan-mode refusal still
|
||||
// wins) but before the real tool fn. A string return is treated as
|
||||
// the full tool result; null / undefined means "not my concern,
|
||||
// fall through." Uncaught throws from the interceptor are surfaced
|
||||
// through the same error path as a failed tool fn below.
|
||||
if (this._interceptor) {
|
||||
try {
|
||||
const short = await this._interceptor(name, args);
|
||||
if (typeof short === "string") return short;
|
||||
} catch (err) {
|
||||
return JSON.stringify({
|
||||
error: `${name}: interceptor failed — ${(err as Error).message}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await tool.fn(args, { signal: opts.signal });
|
||||
return typeof result === "string" ? result : JSON.stringify(result);
|
||||
const str = typeof result === "string" ? result : JSON.stringify(result);
|
||||
// Pre-clip at dispatch so a single fat result can't balloon the
|
||||
// log (and disk session file) on its way in. Healing at load time
|
||||
// still catches pre-existing oversize entries; this closes the
|
||||
// door on new ones.
|
||||
//
|
||||
// Two caps available: `maxResultTokens` (preferred — bounds the
|
||||
// real context footprint, so CJK doesn't slip past at 2× density)
|
||||
// and `maxResultChars` (legacy). If both are set, apply both and
|
||||
// the tighter one wins; char-only callers keep their old behavior.
|
||||
let clipped = str;
|
||||
if (opts.maxResultTokens !== undefined) {
|
||||
clipped = truncateForModelByTokens(clipped, opts.maxResultTokens);
|
||||
}
|
||||
if (opts.maxResultChars !== undefined) {
|
||||
clipped = truncateForModel(clipped, opts.maxResultChars);
|
||||
}
|
||||
return clipped;
|
||||
} catch (err) {
|
||||
const e = err as Error & { toToolResult?: () => unknown };
|
||||
// Errors may opt into a richer tool-result shape by implementing
|
||||
// `toToolResult()`. Used by `PlanProposedError` to smuggle the
|
||||
// submitted plan text out to the UI without stuffing it into the
|
||||
// error message (which the dispatcher truncates at no fixed limit,
|
||||
// but keeping payloads structured is cleaner for UI parsing).
|
||||
if (typeof e.toToolResult === "function") {
|
||||
try {
|
||||
return JSON.stringify(e.toToolResult());
|
||||
} catch {
|
||||
/* fall through to the default shape */
|
||||
}
|
||||
}
|
||||
return JSON.stringify({
|
||||
error: `${(err as Error).name}: ${(err as Error).message}`,
|
||||
error: `${e.name}: ${e.message}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function isReadOnlyCall(tool: InternalTool, args: Record<string, unknown>): boolean {
|
||||
if (tool.readOnlyCheck) {
|
||||
try {
|
||||
return Boolean(tool.readOnlyCheck(args as never));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return tool.readOnly === true;
|
||||
}
|
||||
|
||||
function hasDotKey(obj: Record<string, unknown>): boolean {
|
||||
for (const k of Object.keys(obj)) {
|
||||
if (k.includes(".")) return true;
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
/**
|
||||
* ask_choice — the primitive for "user needs to pick between alternatives".
|
||||
*
|
||||
* Why it exists: `submit_plan` is for ONE concrete plan the user approves.
|
||||
* Models routinely misused it to present A/B/C option menus, leaving the
|
||||
* user stuck with an approve/refine/cancel picker that had no way to
|
||||
* select a route. `ask_choice` gives branching its own tool so plan
|
||||
* mode stays about one actionable thing at a time.
|
||||
*
|
||||
* Shape mirrors `submit_plan`:
|
||||
* 1. Model calls `ask_choice` with a question and 2–4 options.
|
||||
* 2. The tool throws `ChoiceRequestedError`; the registry serializes
|
||||
* the payload via `toToolResult`.
|
||||
* 3. TUI parses the tagged error, mounts `ChoiceConfirm`, user picks
|
||||
* one option (or types a custom answer via the escape hatch, or
|
||||
* cancels).
|
||||
* 4. A synthetic user message feeds the choice back — "user picked
|
||||
* <id>" or "user answered: <text>" — and the loop resumes.
|
||||
*
|
||||
* Auto-flatten note: the `options` array of objects is exactly the
|
||||
* schema shape that DeepSeek V3/R1 is known to drop. `ToolRegistry`
|
||||
* auto-flattens and re-nests on dispatch (Pillar 3), so we don't need
|
||||
* to hand-flatten here. We still `sanitizeOptions` at runtime because
|
||||
* even with flatten-repair, models occasionally emit empty strings or
|
||||
* miss fields entirely.
|
||||
*/
|
||||
|
||||
import type { ToolRegistry } from "../tools.js";
|
||||
|
||||
/**
|
||||
* One option in a branching question. `id` is what gets fed back to
|
||||
* the model when the user picks; keep it short and stable (A, B, C,
|
||||
* or option-1 / option-2 / ...). `summary` is optional extra context
|
||||
* the UI shows as a dimmed sub-line under the title.
|
||||
*/
|
||||
export interface ChoiceOption {
|
||||
id: string;
|
||||
title: string;
|
||||
summary?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Thrown by `ask_choice`. Carries the branching question plus the
|
||||
* options list out to the TUI via the `toToolResult` protocol. The
|
||||
* error message tells the model to STOP so it doesn't race past the
|
||||
* picker with more tool calls — same pattern as `PlanProposedError`.
|
||||
*/
|
||||
export class ChoiceRequestedError extends Error {
|
||||
readonly question: string;
|
||||
readonly options: ChoiceOption[];
|
||||
readonly allowCustom: boolean;
|
||||
constructor(question: string, options: ChoiceOption[], allowCustom: boolean) {
|
||||
super(
|
||||
"ChoiceRequestedError: choice submitted. STOP calling tools now — the TUI has shown the options to the user. Wait for their next message; it will either be 'user picked <id>' (carry on with that branch), 'user answered: <text>' (custom free-form reply; read and proceed), or 'user cancelled the choice' (drop the question and ask what they want instead). Don't call any tools in the meantime.",
|
||||
);
|
||||
this.name = "ChoiceRequestedError";
|
||||
this.question = question;
|
||||
this.options = options;
|
||||
this.allowCustom = allowCustom;
|
||||
}
|
||||
|
||||
toToolResult(): {
|
||||
error: string;
|
||||
question: string;
|
||||
options: ChoiceOption[];
|
||||
allowCustom: boolean;
|
||||
} {
|
||||
return {
|
||||
error: `${this.name}: ${this.message}`,
|
||||
question: this.question,
|
||||
options: this.options,
|
||||
allowCustom: this.allowCustom,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export interface ChoiceToolOptions {
|
||||
/**
|
||||
* Side-channel preview fired when the model asks. The tool-result
|
||||
* event also carries the payload; this is the earlier hook for
|
||||
* test harnesses or alternative UIs that don't want to parse JSON.
|
||||
*/
|
||||
onChoiceRequested?: (question: string, options: ChoiceOption[]) => void;
|
||||
}
|
||||
|
||||
function sanitizeOptions(raw: unknown): ChoiceOption[] {
|
||||
if (!Array.isArray(raw)) return [];
|
||||
const out: ChoiceOption[] = [];
|
||||
const seen = new Set<string>();
|
||||
for (const entry of raw) {
|
||||
if (!entry || typeof entry !== "object") continue;
|
||||
const e = entry as Record<string, unknown>;
|
||||
const id = typeof e.id === "string" ? e.id.trim() : "";
|
||||
const title = typeof e.title === "string" ? e.title.trim() : "";
|
||||
if (!id || !title) continue;
|
||||
if (seen.has(id)) continue;
|
||||
seen.add(id);
|
||||
const summary = typeof e.summary === "string" ? e.summary.trim() || undefined : undefined;
|
||||
const opt: ChoiceOption = { id, title };
|
||||
if (summary) opt.summary = summary;
|
||||
out.push(opt);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function registerChoiceTool(
|
||||
registry: ToolRegistry,
|
||||
opts: ChoiceToolOptions = {},
|
||||
): ToolRegistry {
|
||||
registry.register({
|
||||
name: "ask_choice",
|
||||
description:
|
||||
"Present 2–6 alternatives to the user. The principle: if the user is supposed to pick, the tool picks — you don't enumerate the choices as prose. Prose menus have no picker in this TUI, so the user gets a wall of text to scroll through and a letter to type, strictly worse than the magenta picker this tool renders. Call it whenever (a) the user has asked for options, (b) you've analyzed multiple approaches and the final call is theirs, or (c) it's a preference fork you can't resolve without them. Skip it when one option is clearly best (just do it, or submit_plan) or a free-form text answer fits (ask in prose). Keep option ids short and stable (A/B/C). Each option: title + optional summary. allowCustom=true when their real answer might not fit. Max 6 options — narrow first if more. A one-sentence lead-in before the call is fine; don't repeat the options in it.",
|
||||
readOnly: true,
|
||||
parameters: {
|
||||
type: "object",
|
||||
properties: {
|
||||
question: {
|
||||
type: "string",
|
||||
description:
|
||||
"The question to put in front of the user. One sentence. Don't repeat the options in the question text — the picker renders them separately.",
|
||||
},
|
||||
options: {
|
||||
type: "array",
|
||||
description:
|
||||
"2–4 alternatives. Each needs a stable id and a short title; summary is optional.",
|
||||
items: {
|
||||
type: "object",
|
||||
properties: {
|
||||
id: { type: "string", description: "Short stable id (A, B, C, or option-1)." },
|
||||
title: { type: "string", description: "One-line title shown as the option label." },
|
||||
summary: {
|
||||
type: "string",
|
||||
description:
|
||||
"Optional. A second dimmed line with more detail. Keep under ~80 chars.",
|
||||
},
|
||||
},
|
||||
required: ["id", "title"],
|
||||
},
|
||||
},
|
||||
allowCustom: {
|
||||
type: "boolean",
|
||||
description:
|
||||
"If true, the picker shows a 'Let me type my own answer' escape hatch. Default false. Turn on when the user's real answer might not fit any of your pre-defined options.",
|
||||
},
|
||||
},
|
||||
required: ["question", "options"],
|
||||
},
|
||||
fn: async (args: { question: string; options: unknown; allowCustom?: boolean }) => {
|
||||
const question = (args?.question ?? "").trim();
|
||||
if (!question) {
|
||||
throw new Error(
|
||||
"ask_choice: question is required — write one sentence explaining the decision.",
|
||||
);
|
||||
}
|
||||
const options = sanitizeOptions(args?.options);
|
||||
if (options.length < 2) {
|
||||
throw new Error(
|
||||
"ask_choice: need at least 2 well-formed options (each with a non-empty id and title). If you just need a text answer, ask the user in plain assistant text instead.",
|
||||
);
|
||||
}
|
||||
if (options.length > 6) {
|
||||
throw new Error(
|
||||
"ask_choice: too many options (max 6). If you really have this many branches, split into two sequential ask_choice calls or narrow down first.",
|
||||
);
|
||||
}
|
||||
const allowCustom = args?.allowCustom === true;
|
||||
opts.onChoiceRequested?.(question, options);
|
||||
throw new ChoiceRequestedError(question, options, allowCustom);
|
||||
},
|
||||
});
|
||||
return registry;
|
||||
}
|
||||
+369
-23
@@ -48,6 +48,110 @@ export interface FilesystemToolsOptions {
|
||||
const DEFAULT_MAX_READ_BYTES = 2 * 1024 * 1024;
|
||||
const DEFAULT_MAX_LIST_BYTES = 256 * 1024;
|
||||
|
||||
/**
|
||||
* When `read_file` is called without `head` / `tail` / `range`, files
|
||||
* above this line count auto-trim to a head-plus-tail preview instead
|
||||
* of dumping everything into the turn's context. Observed: five
|
||||
* `read_file` calls in one session accounted for ~18K tokens (6.5K +
|
||||
* 3.9K + 3.2K + 2.4K + 1.6K), a sizable chunk of the 27K total in
|
||||
* tool results. Most of those reads wanted ~20 lines near one edit —
|
||||
* the other 480 lines were inventory the model never cites.
|
||||
*
|
||||
* 200 is a deliberate middle ground: typical CLI / config / test
|
||||
* files fit entirely; sprawling service files force the model to say
|
||||
* what it actually wants (`range:"120-180"` or `search_content`).
|
||||
*/
|
||||
const DEFAULT_AUTO_PREVIEW_LINES = 200;
|
||||
/**
|
||||
* When auto-preview triggers, show this many lines at the top
|
||||
* (structure / imports / public API) plus `AUTO_PREVIEW_TAIL_LINES`
|
||||
* at the bottom (often the recently-edited tail).
|
||||
*/
|
||||
const AUTO_PREVIEW_HEAD_LINES = 80;
|
||||
const AUTO_PREVIEW_TAIL_LINES = 40;
|
||||
|
||||
/**
|
||||
* Directory names skipped by `search_content` unless `include_deps:true`
|
||||
* is passed. The intent is "user is asking about THEIR code, not the
|
||||
* libraries they depend on" — vendored / generated trees would otherwise
|
||||
* dominate every match list. Pass include_deps when you genuinely need
|
||||
* to grep a dependency.
|
||||
*/
|
||||
const SKIP_DIR_NAMES: ReadonlySet<string> = new Set([
|
||||
"node_modules",
|
||||
".git",
|
||||
".hg",
|
||||
".svn",
|
||||
"dist",
|
||||
"build",
|
||||
"out",
|
||||
".next",
|
||||
".nuxt",
|
||||
"target", // Rust / Java
|
||||
".venv",
|
||||
"venv",
|
||||
"__pycache__",
|
||||
".pytest_cache",
|
||||
".mypy_cache",
|
||||
".cache",
|
||||
"coverage",
|
||||
]);
|
||||
|
||||
/**
|
||||
* Cheap binary-by-extension check for `search_content`. We err on the
|
||||
* side of skipping so a NUL-byte content sniff is the second line of
|
||||
* defense (handles e.g. a `.txt` that's actually a binary dump).
|
||||
*/
|
||||
const BINARY_EXTENSIONS: ReadonlySet<string> = new Set([
|
||||
".png",
|
||||
".jpg",
|
||||
".jpeg",
|
||||
".gif",
|
||||
".bmp",
|
||||
".ico",
|
||||
".webp",
|
||||
".tiff",
|
||||
".pdf",
|
||||
".zip",
|
||||
".tar",
|
||||
".gz",
|
||||
".bz2",
|
||||
".xz",
|
||||
".7z",
|
||||
".rar",
|
||||
".exe",
|
||||
".dll",
|
||||
".so",
|
||||
".dylib",
|
||||
".bin",
|
||||
".class",
|
||||
".jar",
|
||||
".war",
|
||||
".o",
|
||||
".obj",
|
||||
".lib",
|
||||
".a",
|
||||
".woff",
|
||||
".woff2",
|
||||
".ttf",
|
||||
".otf",
|
||||
".eot",
|
||||
".mp3",
|
||||
".mp4",
|
||||
".mov",
|
||||
".avi",
|
||||
".webm",
|
||||
".wasm",
|
||||
".pyc",
|
||||
".pyo",
|
||||
]);
|
||||
|
||||
function isLikelyBinaryByName(name: string): boolean {
|
||||
const dot = name.lastIndexOf(".");
|
||||
if (dot < 0) return false;
|
||||
return BINARY_EXTENSIONS.has(name.slice(dot).toLowerCase());
|
||||
}
|
||||
|
||||
export function registerFilesystemTools(
|
||||
registry: ToolRegistry,
|
||||
opts: FilesystemToolsOptions,
|
||||
@@ -62,8 +166,22 @@ export function registerFilesystemTools(
|
||||
if (typeof raw !== "string" || raw.length === 0) {
|
||||
throw new Error("path must be a non-empty string");
|
||||
}
|
||||
// Interpret relative paths against rootDir (the session's scope).
|
||||
const resolved = pathMod.resolve(rootDir, raw);
|
||||
// Sandbox-root semantics: a leading POSIX-style `/` (or `\` on
|
||||
// Windows) means "from the project root", not "from the filesystem
|
||||
// root". Models routinely write `path: "/"` or `path: "/src/foo.ts"`
|
||||
// intending the sandbox root — without this normalization,
|
||||
// path.resolve interprets `/` as the actual drive root (`F:\` on
|
||||
// Windows, `/` on POSIX) and the escape check rightly rejects it,
|
||||
// confusing the model. Strip leading separators so the rest of the
|
||||
// resolution treats the input as relative to rootDir. Drive-letter
|
||||
// absolutes (`C:\foo`) and Unix absolutes outside rootDir still
|
||||
// get caught by the relative-escape check below.
|
||||
let normalized = raw;
|
||||
while (normalized.startsWith("/") || normalized.startsWith("\\")) {
|
||||
normalized = normalized.slice(1);
|
||||
}
|
||||
if (normalized.length === 0) normalized = ".";
|
||||
const resolved = pathMod.resolve(rootDir, normalized);
|
||||
const normRoot = pathMod.resolve(rootDir);
|
||||
// Use relative() to catch any `..` segments that escape.
|
||||
const rel = pathMod.relative(normRoot, resolved);
|
||||
@@ -75,18 +193,27 @@ export function registerFilesystemTools(
|
||||
|
||||
registry.register({
|
||||
name: "read_file",
|
||||
description:
|
||||
"Read a file under the sandbox root. Returns the full contents (truncated with a notice if larger than the per-call cap). Paths may be relative to the root or absolute-under-root.",
|
||||
description: `Read a file under the sandbox root. To save context, PREFER to scope the read instead of pulling the whole file:
|
||||
- head: N → first N lines (imports, public API, small configs)
|
||||
- tail: N → last N lines (recently-added code, log tails)
|
||||
- range: "A-B" → inclusive line range A..B, 1-indexed (e.g. "120-180" around an edit site)
|
||||
When none of these is given AND the file is longer than ${DEFAULT_AUTO_PREVIEW_LINES} lines, the tool auto-returns a head+tail preview with an "N lines omitted" marker rather than dumping everything. If you need the middle, re-call with a range. Prefer search_content to locate a symbol first, then read_file with a range around the hit — one scoped read beats three full-file reads.`,
|
||||
readOnly: true,
|
||||
parameters: {
|
||||
type: "object",
|
||||
properties: {
|
||||
path: { type: "string", description: "Path to read (relative to rootDir or absolute)." },
|
||||
head: { type: "integer", description: "If set, return only the first N lines." },
|
||||
tail: { type: "integer", description: "If set, return only the last N lines." },
|
||||
range: {
|
||||
type: "string",
|
||||
description:
|
||||
'Inclusive line range like "50-100" or "50-50". 1-indexed. Takes precedence over head/tail when all three are set. Out-of-range requests clamp to file bounds.',
|
||||
},
|
||||
},
|
||||
required: ["path"],
|
||||
},
|
||||
fn: async (args: { path: string; head?: number; tail?: number }) => {
|
||||
fn: async (args: { path: string; head?: number; tail?: number; range?: string }) => {
|
||||
const abs = safePath(args.path);
|
||||
const stat = await fs.stat(abs);
|
||||
if (stat.isDirectory()) {
|
||||
@@ -94,22 +221,64 @@ export function registerFilesystemTools(
|
||||
}
|
||||
const raw = await fs.readFile(abs);
|
||||
if (raw.length > maxReadBytes) {
|
||||
const head = raw.slice(0, maxReadBytes).toString("utf8");
|
||||
return `${head}\n\n[…truncated ${raw.length - maxReadBytes} bytes — file is ${raw.length} B, cap ${maxReadBytes} B. Retry with head/tail for targeted view.]`;
|
||||
const headBytes = raw.slice(0, maxReadBytes).toString("utf8");
|
||||
return `${headBytes}\n\n[…truncated ${raw.length - maxReadBytes} bytes — file is ${raw.length} B, cap ${maxReadBytes} B. Retry with head/tail/range for targeted view.]`;
|
||||
}
|
||||
const text = raw.toString("utf8");
|
||||
let lines = text.split(/\r?\n/);
|
||||
// Most files end with '\n' which splits into an empty trailing
|
||||
// entry; drop it so head/tail/range counts match the user's
|
||||
// visible line numbers in an editor.
|
||||
if (lines.length > 0 && lines[lines.length - 1] === "") lines = lines.slice(0, -1);
|
||||
const totalLines = lines.length;
|
||||
|
||||
// range wins over head/tail when set — the most precise ask
|
||||
// should dominate. Parse "A-B" strictly; bad formats fall through
|
||||
// to head/tail / auto-preview instead of erroring.
|
||||
if (typeof args.range === "string" && /^\d+\s*-\s*\d+$/.test(args.range)) {
|
||||
const [rawStart, rawEnd] = args.range.split("-").map((s) => Number.parseInt(s, 10));
|
||||
const start = Math.max(1, rawStart ?? 1);
|
||||
const end = Math.min(totalLines, Math.max(start, rawEnd ?? totalLines));
|
||||
const slice = lines.slice(start - 1, end);
|
||||
const label = `[range ${start}-${end} of ${totalLines} lines]`;
|
||||
return `${label}\n${slice.join("\n")}`;
|
||||
}
|
||||
if (typeof args.head === "number" && args.head > 0) {
|
||||
return text.split(/\r?\n/).slice(0, args.head).join("\n");
|
||||
const count = Math.min(args.head, totalLines);
|
||||
const slice = lines.slice(0, count);
|
||||
const marker =
|
||||
count < totalLines
|
||||
? `\n\n[…head ${count} of ${totalLines} lines — call again with range / tail for more]`
|
||||
: "";
|
||||
return slice.join("\n") + marker;
|
||||
}
|
||||
if (typeof args.tail === "number" && args.tail > 0) {
|
||||
let lines = text.split(/\r?\n/);
|
||||
// Most files end with a final '\n', which splits into an empty
|
||||
// trailing string. Drop it before slicing so tail=2 returns the
|
||||
// last two *real* lines, not "last line + empty".
|
||||
if (lines.length > 0 && lines[lines.length - 1] === "") lines = lines.slice(0, -1);
|
||||
return lines.slice(Math.max(0, lines.length - args.tail)).join("\n");
|
||||
const count = Math.min(args.tail, totalLines);
|
||||
const slice = lines.slice(totalLines - count);
|
||||
const marker =
|
||||
count < totalLines
|
||||
? `[…tail ${count} of ${totalLines} lines — call again with range / head for more]\n\n`
|
||||
: "";
|
||||
return marker + slice.join("\n");
|
||||
}
|
||||
return text;
|
||||
|
||||
// No explicit scope + file is small → full content.
|
||||
if (totalLines <= DEFAULT_AUTO_PREVIEW_LINES) return lines.join("\n");
|
||||
|
||||
// No explicit scope + file is large → head + tail preview plus
|
||||
// a marker telling the model how much it missed and how to get
|
||||
// it. This is the single biggest lever on read_file token cost —
|
||||
// historically a 500-line file dumped ~4K tokens into the turn
|
||||
// even when the model only needed 20 of them.
|
||||
const head = lines.slice(0, AUTO_PREVIEW_HEAD_LINES).join("\n");
|
||||
const tail = lines.slice(totalLines - AUTO_PREVIEW_TAIL_LINES).join("\n");
|
||||
const omitted = totalLines - AUTO_PREVIEW_HEAD_LINES - AUTO_PREVIEW_TAIL_LINES;
|
||||
return [
|
||||
`[auto-preview: head ${AUTO_PREVIEW_HEAD_LINES} + tail ${AUTO_PREVIEW_TAIL_LINES} of ${totalLines} lines]`,
|
||||
head,
|
||||
`\n[… ${omitted} lines omitted — call read_file again with range:"A-B" (1-indexed) or head / tail to get the middle]\n`,
|
||||
tail,
|
||||
].join("\n");
|
||||
},
|
||||
});
|
||||
|
||||
@@ -117,6 +286,7 @@ export function registerFilesystemTools(
|
||||
name: "list_directory",
|
||||
description:
|
||||
"List entries in a directory under the sandbox root. Returns one line per entry, marking directories with a trailing slash. Not recursive — use directory_tree for that.",
|
||||
readOnly: true,
|
||||
parameters: {
|
||||
type: "object",
|
||||
properties: {
|
||||
@@ -136,21 +306,40 @@ export function registerFilesystemTools(
|
||||
|
||||
registry.register({
|
||||
name: "directory_tree",
|
||||
description:
|
||||
"Recursively list entries in a directory. Shows indented tree structure with directories marked '/'. Caps output so a huge tree doesn't drown the context.",
|
||||
description: `Recursively list entries in a directory. Shows indented tree structure with directories marked '/'. Budget-aware by default:
|
||||
- maxDepth defaults to 2 (root + one level). A depth-4 tree on a real repo blew ~5K tokens in one call. If you truly need deeper, pass maxDepth:N explicitly.
|
||||
- Skips ${[...SKIP_DIR_NAMES].sort().join(", ")} unless include_deps:true. Traversing into node_modules / .git / dist is almost always token-waste.
|
||||
- Large subtrees (>50 children) auto-collapse to "[N files, M dirs hidden — list_directory <path> to inspect]" so one huge folder can't dominate the output.
|
||||
Prefer \`list_directory\` for a single-level view, \`search_files\` to find specific paths, and \`search_content\` to find code.`,
|
||||
readOnly: true,
|
||||
parameters: {
|
||||
type: "object",
|
||||
properties: {
|
||||
path: { type: "string", description: "Root of the tree (default: sandbox root)." },
|
||||
maxDepth: { type: "integer", description: "Max recursion depth (default 4)." },
|
||||
maxDepth: {
|
||||
type: "integer",
|
||||
description:
|
||||
"Max recursion depth (default 2). Depth 0 shows only the top-level entries; depth 2 is usually enough to see module structure.",
|
||||
},
|
||||
include_deps: {
|
||||
type: "boolean",
|
||||
description:
|
||||
"When true, also traverse node_modules / .git / dist / build / etc. Off by default — most exploration questions are about the user's own code.",
|
||||
},
|
||||
},
|
||||
},
|
||||
fn: async (args: { path?: string; maxDepth?: number }) => {
|
||||
fn: async (args: { path?: string; maxDepth?: number; include_deps?: boolean }) => {
|
||||
const startAbs = safePath(args.path ?? ".");
|
||||
const maxDepth = typeof args.maxDepth === "number" ? args.maxDepth : 4;
|
||||
const maxDepth = typeof args.maxDepth === "number" ? args.maxDepth : 2;
|
||||
const includeDeps = args.include_deps === true;
|
||||
const lines: string[] = [];
|
||||
let totalBytes = 0;
|
||||
let truncated = false;
|
||||
// Per-directory child cap — long fixture / asset folders (200+
|
||||
// snapshots) would otherwise dominate; the collapse keeps the
|
||||
// overall shape visible. Modest: normal source dirs have <50
|
||||
// entries.
|
||||
const PER_DIR_CHILD_CAP = 50;
|
||||
const walk = async (dir: string, depth: number): Promise<void> => {
|
||||
if (truncated) return;
|
||||
if (depth > maxDepth) return;
|
||||
@@ -161,10 +350,31 @@ export function registerFilesystemTools(
|
||||
return;
|
||||
}
|
||||
entries.sort((a, b) => a.name.localeCompare(b.name));
|
||||
let emitted = 0;
|
||||
for (const e of entries) {
|
||||
if (truncated) return;
|
||||
// Dep-skip applies only to DIRECTORIES (a file named
|
||||
// "node_modules" is fine to list). Anything in the skip set
|
||||
// still shows up as a single node with a trailing " (skipped)"
|
||||
// hint so the model knows the dir exists but wasn't walked.
|
||||
const skip = e.isDirectory() && !includeDeps && SKIP_DIR_NAMES.has(e.name);
|
||||
if (emitted >= PER_DIR_CHILD_CAP) {
|
||||
const remaining = entries.length - emitted;
|
||||
let restFiles = 0;
|
||||
let restDirs = 0;
|
||||
for (const r of entries.slice(emitted)) {
|
||||
if (r.isDirectory()) restDirs++;
|
||||
else restFiles++;
|
||||
}
|
||||
const indent = " ".repeat(depth);
|
||||
lines.push(
|
||||
`${indent}[… ${remaining} entries hidden (${restDirs} dirs, ${restFiles} files) — list_directory on this path to see all]`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
const indent = " ".repeat(depth);
|
||||
const line = e.isDirectory() ? `${indent}${e.name}/` : `${indent}${e.name}`;
|
||||
const suffix = skip ? " (skipped — pass include_deps:true to traverse)" : "";
|
||||
const line = e.isDirectory() ? `${indent}${e.name}/${suffix}` : `${indent}${e.name}`;
|
||||
totalBytes += line.length + 1;
|
||||
if (totalBytes > maxListBytes) {
|
||||
lines.push(` [… tree truncated at ${maxListBytes} bytes …]`);
|
||||
@@ -172,7 +382,8 @@ export function registerFilesystemTools(
|
||||
return;
|
||||
}
|
||||
lines.push(line);
|
||||
if (e.isDirectory()) {
|
||||
emitted++;
|
||||
if (e.isDirectory() && !skip) {
|
||||
await walk(pathMod.join(dir, e.name), depth + 1);
|
||||
}
|
||||
}
|
||||
@@ -186,6 +397,7 @@ export function registerFilesystemTools(
|
||||
name: "search_files",
|
||||
description:
|
||||
"Find files whose NAME matches a substring or regex. Case-insensitive. Walks the directory recursively under the sandbox root. Returns one path per line.",
|
||||
readOnly: true,
|
||||
parameters: {
|
||||
type: "object",
|
||||
properties: {
|
||||
@@ -239,10 +451,144 @@ export function registerFilesystemTools(
|
||||
},
|
||||
});
|
||||
|
||||
registry.register({
|
||||
name: "search_content",
|
||||
description:
|
||||
"Recursively grep file CONTENTS for a substring or regex. This is the right tool for 'find all places that call X', 'where is Y referenced', 'what files contain Z'. Different from search_files (which matches FILE NAMES). Returns one match per line in 'path:line: text' format. Skips dependency / VCS / build directories (node_modules, .git, dist, build, .next, target, .venv) and binary files by default.",
|
||||
readOnly: true,
|
||||
parameters: {
|
||||
type: "object",
|
||||
properties: {
|
||||
pattern: {
|
||||
type: "string",
|
||||
description: "Substring (or regex) to search file contents for.",
|
||||
},
|
||||
path: {
|
||||
type: "string",
|
||||
description: "Directory to start the search at (default: sandbox root).",
|
||||
},
|
||||
glob: {
|
||||
type: "string",
|
||||
description:
|
||||
"Optional file-name suffix or substring filter. Examples: '.ts' (only TypeScript), 'test' (any file with 'test' in the name). Reduces noise when you know the file shape.",
|
||||
},
|
||||
case_sensitive: {
|
||||
type: "boolean",
|
||||
description: "When true, match case exactly. Default false (case-insensitive).",
|
||||
},
|
||||
include_deps: {
|
||||
type: "boolean",
|
||||
description:
|
||||
"When true, also search inside node_modules / .git / dist / build / etc. Off by default — most exploration questions are about the user's own code.",
|
||||
},
|
||||
},
|
||||
required: ["pattern"],
|
||||
},
|
||||
fn: async (args: {
|
||||
pattern: string;
|
||||
path?: string;
|
||||
glob?: string;
|
||||
case_sensitive?: boolean;
|
||||
include_deps?: boolean;
|
||||
}) => {
|
||||
const startAbs = safePath(args.path ?? ".");
|
||||
const caseSensitive = args.case_sensitive === true;
|
||||
const includeDeps = args.include_deps === true;
|
||||
const nameFilter = typeof args.glob === "string" ? args.glob.toLowerCase() : null;
|
||||
// Try the pattern as a regex first (lets the model say `\bdispatch\(`
|
||||
// for a word-bounded match); fall back to literal substring on
|
||||
// invalid regex. No `g` flag — we test once per line, so global
|
||||
// statefulness (lastIndex tracking) would just be noise.
|
||||
let re: RegExp | null = null;
|
||||
try {
|
||||
re = new RegExp(args.pattern, caseSensitive ? "" : "i");
|
||||
} catch {
|
||||
re = null;
|
||||
}
|
||||
const needle = caseSensitive ? args.pattern : args.pattern.toLowerCase();
|
||||
const matches: string[] = [];
|
||||
let totalBytes = 0;
|
||||
let scanned = 0;
|
||||
let truncated = false;
|
||||
|
||||
const walk = async (dir: string): Promise<void> => {
|
||||
if (truncated) return;
|
||||
let entries: import("node:fs").Dirent[];
|
||||
try {
|
||||
entries = await fs.readdir(dir, { withFileTypes: true });
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
for (const e of entries) {
|
||||
if (truncated) return;
|
||||
if (e.isDirectory()) {
|
||||
if (!includeDeps && SKIP_DIR_NAMES.has(e.name)) continue;
|
||||
await walk(pathMod.join(dir, e.name));
|
||||
continue;
|
||||
}
|
||||
if (!e.isFile()) continue;
|
||||
if (nameFilter && !e.name.toLowerCase().includes(nameFilter)) continue;
|
||||
if (isLikelyBinaryByName(e.name)) continue;
|
||||
const full = pathMod.join(dir, e.name);
|
||||
let stat: import("node:fs").Stats;
|
||||
try {
|
||||
stat = await fs.stat(full);
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
// Per-file size cap so a 50MB log doesn't dominate the search.
|
||||
// Anything legitimately interesting fits in 2 MB; bigger files
|
||||
// are usually data dumps or generated bundles.
|
||||
if (stat.size > 2 * 1024 * 1024) continue;
|
||||
let raw: Buffer;
|
||||
try {
|
||||
raw = await fs.readFile(full);
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
// Content-based binary sniff: a NUL byte in the first 8KB is
|
||||
// a strong indicator. Catches binaries with .json or .txt
|
||||
// extensions (yes, this happens).
|
||||
const firstNul = raw.indexOf(0);
|
||||
if (firstNul !== -1 && firstNul < 8 * 1024) continue;
|
||||
const text = raw.toString("utf8");
|
||||
const rel = pathMod.relative(rootDir, full);
|
||||
const lines = text.split(/\r?\n/);
|
||||
for (let li = 0; li < lines.length; li++) {
|
||||
const line = lines[li]!;
|
||||
const lineForCheck = caseSensitive ? line : line.toLowerCase();
|
||||
const hit = re ? re.test(line) : lineForCheck.includes(needle);
|
||||
if (!hit) continue;
|
||||
// Truncate very long lines so one giant minified file
|
||||
// doesn't blow the budget on a single match.
|
||||
const display = line.length > 200 ? `${line.slice(0, 200)}…` : line;
|
||||
const out = `${rel}:${li + 1}: ${display}`;
|
||||
if (totalBytes + out.length + 1 > maxListBytes) {
|
||||
matches.push(`[… truncated at ${maxListBytes} bytes — refine pattern or path …]`);
|
||||
truncated = true;
|
||||
return;
|
||||
}
|
||||
matches.push(out);
|
||||
totalBytes += out.length + 1;
|
||||
}
|
||||
scanned++;
|
||||
}
|
||||
};
|
||||
await walk(startAbs);
|
||||
if (matches.length === 0) {
|
||||
return scanned === 0
|
||||
? "(no files scanned — path empty or all files filtered out)"
|
||||
: `(no matches across ${scanned} file${scanned === 1 ? "" : "s"})`;
|
||||
}
|
||||
return matches.join("\n");
|
||||
},
|
||||
});
|
||||
|
||||
registry.register({
|
||||
name: "get_file_info",
|
||||
description:
|
||||
"Stat a path under the sandbox root. Returns type (file|directory|symlink), size in bytes, mtime in ISO-8601.",
|
||||
readOnly: true,
|
||||
parameters: {
|
||||
type: "object",
|
||||
properties: {
|
||||
@@ -287,7 +633,7 @@ export function registerFilesystemTools(
|
||||
registry.register({
|
||||
name: "edit_file",
|
||||
description:
|
||||
"Apply a SEARCH/REPLACE edit to an existing file. `search` must match exactly (whitespace sensitive) — no regex. The match must be unique in the file; otherwise the edit is refused to avoid surprise rewrites. This flat-string shape replaces the `{oldText, newText}[]` JSON array form that previously triggered R1 DSML hallucinations.",
|
||||
"Apply a SEARCH/REPLACE edit to an existing file. `search` must match exactly (whitespace sensitive) — no regex. The match must be unique in the file; otherwise the edit is refused to avoid surprise rewrites.",
|
||||
parameters: {
|
||||
type: "object",
|
||||
properties: {
|
||||
|
||||
Loaded 100 of 165 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user