mirror of
https://github.com/esengine/DeepSeek-Reasonix.git
synced 2026-11-07 10:45:59 -10:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
146ddb0658 | ||
|
|
0620c8ee4e | ||
|
|
13a15bb665 | ||
|
|
ef787f8eba | ||
|
|
3b0dd73d31 | ||
|
|
d84de144b7 | ||
|
|
a47f457ef2 | ||
|
|
9a5bbcc0e8 | ||
|
|
a1dd12008d | ||
|
|
622d5f89bb | ||
|
|
f29eb405e6 | ||
|
|
d3613ddb18 | ||
|
|
f36282d258 | ||
|
|
33a3a7fd49 | ||
|
|
535a8ebb3b | ||
|
|
8860cedc2a | ||
|
|
98d6021ba9 | ||
|
|
3e71089068 | ||
|
|
7a5ef3b163 | ||
|
|
28b3f40b9e | ||
|
|
efb0a77648 | ||
|
|
70dcad6401 | ||
|
|
3e6fdac9c0 | ||
|
|
5ec643033c | ||
|
|
7f20ccf6ac | ||
|
|
fd26900d48 | ||
|
|
baedbf7292 | ||
|
|
d82aa833c9 | ||
|
|
937b9797aa | ||
|
|
32cccfaeca | ||
|
|
c1288d3a66 | ||
|
|
e0cdb7e7bb | ||
|
|
bf1bb778aa | ||
|
|
0c1d80fec9 | ||
|
|
9ba7fbdf86 | ||
|
|
1e58cf3e4b | ||
|
|
2dbf8bf723 | ||
|
|
c225dad853 | ||
|
|
a52f8facb4 | ||
|
|
fed2a515be | ||
|
|
067fcc21a4 | ||
|
|
957fc34c9b | ||
|
|
e0e7bb91f2 | ||
|
|
efd6d64176 | ||
|
|
44f309509e | ||
|
|
546e587a1e | ||
|
|
d58861e0d6 | ||
|
|
c9369d7532 | ||
|
|
78e6df6a4d | ||
|
|
9f88f3b330 | ||
|
|
72326254b6 | ||
|
|
baece15b65 | ||
|
|
fe9ad209eb | ||
|
|
be7daa017c | ||
|
|
c594ad71f7 | ||
|
|
23c81e6f11 | ||
|
|
0d0cdfc54a | ||
|
|
60c598527d | ||
|
|
494c62ef60 | ||
|
|
c43ada74e2 | ||
|
|
18b8d0d8df | ||
|
|
855b91c7ed | ||
|
|
efcab7d141 | ||
|
|
ca1406d864 | ||
|
|
477e710ad6 | ||
|
|
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 |
No files matched your search
@@ -0,0 +1,11 @@
|
||||
# Force LF line endings on every checkout, regardless of platform.
|
||||
# Biome's formatter is strict about CRLF — without this, a Windows clone
|
||||
# with autocrlf=true will land with CRLF in the working tree even though
|
||||
# the repo stores LF, and `npm run lint` (and prepublishOnly with it)
|
||||
# fails. See docs/style.md if you ever add binary types here.
|
||||
* text=auto eol=lf
|
||||
|
||||
# Lockfiles + the codemirror bundle are generated; treat them as
|
||||
# auto-detected text but never coerce.
|
||||
package-lock.json text eol=lf
|
||||
dashboard/codemirror.js text eol=lf
|
||||
@@ -24,3 +24,12 @@ sessions/
|
||||
.turbo/
|
||||
# Local-only Claude Code settings — personal overrides, never committed.
|
||||
.claude/settings.local.json
|
||||
# Per-user Reasonix state under .reasonix/ — committable team-level
|
||||
# files (settings.json, skills/) stay tracked, but the user-private
|
||||
# bits (semantic index, sessions, opt-out markers) never should.
|
||||
.reasonix/semantic/
|
||||
.reasonix/sessions/
|
||||
.reasonix/semantic-skip
|
||||
# Scratch entry regenerated each time scripts/bundle-codemirror.mjs runs.
|
||||
scripts/.cm-entry.mjs
|
||||
|
||||
+1250
File diff suppressed because it is too large.
Load diff
@@ -3,7 +3,11 @@
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<em>Cache-first agent loop for DeepSeek V3 & R1 — Ink TUI, MCP first-class, no LangChain.</em>
|
||||
<em>Cache-first agent loop for DeepSeek V4 (flash + pro) — Ink TUI, MCP first-class, no LangChain.</em>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<strong>English</strong> · <a href="./README.zh-CN.md">简体中文</a> · <a href="https://esengine.github.io/reasonix/">Website</a>
|
||||
</p>
|
||||
|
||||
# Reasonix
|
||||
@@ -14,9 +18,10 @@
|
||||
[](https://www.npmjs.com/package/reasonix)
|
||||
[](./package.json)
|
||||
|
||||
**A DeepSeek-native AI coding agent in your terminal.** Edits files as
|
||||
reviewable SEARCH/REPLACE blocks. Ink TUI. MCP first-class. No
|
||||
LangChain.
|
||||
**A DeepSeek-native AI coding agent in your terminal.** ~30× cheaper
|
||||
per task than Claude Code, with a cache-first loop engineered for
|
||||
DeepSeek's pricing model. Edits as reviewable SEARCH/REPLACE blocks.
|
||||
MIT-licensed. No IDE lock-in. MCP first-class.
|
||||
|
||||
---
|
||||
|
||||
@@ -67,6 +72,159 @@ command list.
|
||||
|
||||
---
|
||||
|
||||
## Web dashboard *(new in 0.12)*
|
||||
|
||||
Type `/dashboard` inside any session and Reasonix prints a localhost
|
||||
URL with a one-time token. Open it for a 13-tab control surface that
|
||||
mirrors the running TUI — chat (with live streaming), the editor (file
|
||||
tree + CodeMirror, syntax highlighting + autocomplete + side-by-side
|
||||
diff for pending edits), Usage / Sessions / Plans / Tools /
|
||||
Permissions / System / MCP / Skills / Memory / Hooks / Settings.
|
||||
|
||||
```
|
||||
reasonix code › /dashboard
|
||||
▸ http://127.0.0.1:54219/?token=… (open in browser)
|
||||
```
|
||||
|
||||
127.0.0.1 only, ephemeral token expires when the session ends, every
|
||||
mutation is CSRF-checked. The TUI keeps working — modals (shell
|
||||
confirms, plan reviews, edit gates) mirror to whichever surface you
|
||||
look at first. No build step, no Electron, no separate process to
|
||||
keep alive.
|
||||
|
||||
---
|
||||
|
||||
## Why Reasonix? (vs Cursor / Claude Code / Cline / Aider)
|
||||
|
||||
Three things you'd come to Reasonix for, that nothing else combines:
|
||||
|
||||
- **The cost economics actually land in your bill.** DeepSeek V4 is
|
||||
~30× cheaper than Claude Sonnet per token. Cheaper tokens alone
|
||||
isn't the win — *cheap tokens with a 90%+ prefix-cache hit* is.
|
||||
Reasonix's loop is engineered around append-only prompt growth so
|
||||
the cache-stable prefix survives every tool call, which the
|
||||
benchmarks section below verifies end-to-end (94.4% live, vs 46.6%
|
||||
for a generic harness against the same workload). The `/stats`
|
||||
panel tracks "vs Claude Sonnet 4.6" savings every turn so you can
|
||||
watch your bill not happen.
|
||||
|
||||
- **It lives in your terminal.** Pure CLI — no Electron, no VS Code
|
||||
extension, no IDE plugin to wedge into your editor. Sits next to
|
||||
git, tmux, and your shell history. macOS / Linux / Windows
|
||||
(PowerShell, Git Bash, Windows Terminal all tested). The only
|
||||
network call is to the DeepSeek API itself; no vendor server in
|
||||
the middle.
|
||||
|
||||
- **Open source and hackable, end to end.** MIT-licensed TypeScript.
|
||||
The entire loop, tool registry, cache-stable prefix, TUI, MCP
|
||||
bridge — all in `src/` under 30k lines. Fork it, ship a private
|
||||
build, drop it into CI. No SaaS layer, no enterprise tier, no
|
||||
feature gates.
|
||||
|
||||
| | Reasonix | Claude Code | Cursor | Cline | Aider |
|
||||
|---|---|---|---|---|---|
|
||||
| Backend | DeepSeek V4 only | Anthropic only | OpenAI / Anthropic | any (OpenRouter) | any (OpenRouter) |
|
||||
| Cost / typical task | **~$0.001–$0.005** | ~$0.05–$0.50 | $20/mo + usage | varies | varies |
|
||||
| Where it runs | terminal | terminal + IDE | IDE (Electron) | VS Code only | terminal |
|
||||
| License | **MIT** | closed | closed | Apache 2 | Apache 2 |
|
||||
| Cache-first prefix loop | **engineered (94% hit)** | basic | n/a | n/a | basic |
|
||||
| MCP servers | **first-class** | first-class | — | beta | — |
|
||||
| Plan mode (read-only audit gate) | **yes** | yes | — | yes | — |
|
||||
| User-authored skills | **yes** | yes | — | — | — |
|
||||
| Edit review (no auto-write) | **yes** (`/apply`) | yes | partial | yes | yes |
|
||||
| Workspace switch (`/cwd`, `change_workspace`) | **yes** | — | n/a (per-window) | — | — |
|
||||
| Cross-session cost dashboard | **yes** (`/stats`) | — | — | — | — |
|
||||
| Sandbox boundary enforcement | **strict** (refuses `..` escape) | yes | partial | yes | partial |
|
||||
|
||||
### Pick something else when
|
||||
|
||||
- **You want multi-provider flexibility** (mix Claude / GPT / Gemini /
|
||||
local Llama in one tool). Try [Aider](https://aider.chat) or
|
||||
[Cline](https://cline.bot). Reasonix is DeepSeek-only on purpose —
|
||||
every layer (cache-first loop, R1 harvesting, JSON-mode tool repair,
|
||||
reasoning-effort cap) is tuned against DeepSeek-specific behavior
|
||||
and economics. Coupling to one backend is the feature, not a
|
||||
limitation we'll grow out of.
|
||||
- **You want IDE integration** (inline diff in your gutter,
|
||||
multi-cursor, ghost text, refactor previews). Try
|
||||
[Cursor](https://cursor.com) or Claude Code's IDE mode. Reasonix
|
||||
is terminal-first; the diff lives in `git diff`, the file tree
|
||||
lives in `ls`, the chat lives in your shell.
|
||||
- **You're chasing the hardest reasoning benchmarks.** Claude Opus
|
||||
4.6 still wins some leaderboards. DeepSeek V4-pro is competitive
|
||||
on most coding tasks but doesn't lead every benchmark. If your
|
||||
task is "solve this PhD-level proof" rather than "fix this auth
|
||||
bug," start with Claude.
|
||||
- **You need fully-local / fully-free**. DeepSeek's API has free
|
||||
credit on signup, but isn't free forever. For air-gapped or
|
||||
always-free, look at Aider + Ollama or [Continue](https://continue.dev).
|
||||
|
||||
### "But DeepSeek now has an Anthropic-compatible API — can't I just point Claude Code at it?"
|
||||
|
||||
You can. DeepSeek ships an official Anthropic-compatible endpoint at
|
||||
`https://api.deepseek.com/anthropic`, and Claude Code (or any Anthropic
|
||||
SDK client) talks to it without modification. The protocol works. The
|
||||
**caching economics** don't transfer, and that's the whole point.
|
||||
|
||||
Look at DeepSeek's [own compatibility table](https://api-docs.deepseek.com/guides/anthropic_api):
|
||||
|
||||
| Field | Status on DeepSeek's compat endpoint |
|
||||
|---|---|
|
||||
| `cache_control` markers | **Ignored** |
|
||||
| `mcp_servers` (API-level) | Ignored |
|
||||
| `thinking.budget_tokens` | Ignored |
|
||||
| Images / documents / citations | Not supported |
|
||||
|
||||
`cache_control: Ignored` is the load-bearing line. Two completely
|
||||
different cache mechanics are colliding here:
|
||||
|
||||
| | Anthropic native | DeepSeek auto-cache |
|
||||
|---|---|---|
|
||||
| Model | **Marker-based.** You put `cache_control` on a message; Anthropic caches "everything up to this marker" as a content-addressed unit. Multiple markers = multiple independent breakpoints. | **Byte-stable prefix.** The cache fingerprints the literal byte stream from byte 0. |
|
||||
| Claude Code's design | Built around this. Markers on system prompt + tool defs let the loop reorder, compact, or insert metadata after the markers without losing the cache. | n/a — Claude Code wasn't designed for byte-stable prefixes. |
|
||||
| What happens when Claude Code → DeepSeek compat | Markers stripped (ignored). Claude Code's main caching strategy disappears. | Falls back to auto-cache. But Claude Code's prefix isn't byte-stable (markers were the *substitute* for byte-stability), so auto-cache misses too. |
|
||||
|
||||
Net effect: **Claude Code's loop, redirected at DeepSeek, gets the
|
||||
cheap tokens and loses the cache hit it depended on.** A loop running
|
||||
at 80%+ cache hit on Anthropic's marker cache lands somewhere in the
|
||||
40-60% range on DeepSeek's auto-cache (matches the generic-harness
|
||||
baseline in our benchmarks). Same model, same API, same workload —
|
||||
the loop's invariants don't fit the cache mechanic it's now talking
|
||||
to.
|
||||
|
||||
Reasonix's loop was designed around byte-stable prefix from line one.
|
||||
No markers, no breakpoints — append-only is the invariant. That's why
|
||||
the same τ-bench workload lands at **94.4% cache hit** on Reasonix
|
||||
and **46.6%** on a cache-hostile baseline (committed transcripts;
|
||||
benchmarks section below). At DeepSeek's pricing — $0.07/Mtok
|
||||
uncached, ~$0.014/Mtok cached — the difference between 50% and 94%
|
||||
hit is **roughly 2.5× on input cost alone**.
|
||||
|
||||
### "What about Aider / Cline / Continue?"
|
||||
|
||||
They support DeepSeek natively (no compat layer needed) and you do
|
||||
get the cheap token price. What you don't get is the DeepSeek-
|
||||
specific loop work — those tools' loops support every backend
|
||||
generically (OpenAI / Anthropic / local Llama / ...) and use
|
||||
compaction + summarization patterns that destroy byte-stability. They
|
||||
land in the same 40-60% cache-hit range as the baseline. Plus a
|
||||
handful of DeepSeek-specific quirks generic loops don't handle:
|
||||
|
||||
| Generic loops assume | DeepSeek actually does | Reasonix's fix |
|
||||
|---|---|---|
|
||||
| Reasoning emitted as a structured `thinking` block | R1 sometimes leaks tool-call JSON inside `<think>` tags | a `scavenge` pass that pulls escaped tool calls back out, otherwise the model thinks it called and waits for output that never comes |
|
||||
| Tool schemas validated strictly | DeepSeek silently drops deeply-nested object/array params | auto-flatten — nested params get rewritten to single-level prefixed names so the model sees them at all |
|
||||
| Tool-call args are well-formed JSON | DeepSeek occasionally produces `string="false"` and other malformed fragments | dedicated `ToolCallRepair` heals the common shapes before they hit dispatch |
|
||||
| Reasoning depth tuned via system-level switches | V4 exposes a `reasoning_effort` knob (`max` / `high`) | `/effort` slash + `--effort` flag, so users can step down for cheap turns |
|
||||
| Old tool results kept in full forever | 1M context — don't compact pre-emptively, but most agents do | call-storm breaker + result token cap, but the prefix is *never* rewritten; compaction lands as new turns at the tail |
|
||||
|
||||
> Cache-stability isn't a feature you turn on; it's an invariant
|
||||
> the loop is designed around. Reasonix isn't yet-another agent
|
||||
> CLI — it's an agent CLI built around DeepSeek's specific cache
|
||||
> mechanic and pricing model.
|
||||
|
||||
---
|
||||
|
||||
## `reasonix code` — pair programmer in your terminal
|
||||
|
||||
Scoped to the directory you launch from. The model has native
|
||||
@@ -133,6 +291,34 @@ 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
|
||||
|
||||
```
|
||||
@@ -145,13 +331,16 @@ reasonix code › /commit "fix: findByEmail case-insensitive"
|
||||
|
||||
- `/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).
|
||||
- `/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.
|
||||
- `npx reasonix code --preset max` — R1 + 3-way self-consistency
|
||||
branching for gnarly refactors.
|
||||
- `/effort high` — step down from the default `max` agent-class
|
||||
reasoning_effort for cheaper/faster turns on simple tasks.
|
||||
- `npx reasonix code --preset pro` — v4-pro for the whole session,
|
||||
no auto-downgrade to flash. Pair with `--branch 3` if you want
|
||||
3-way self-consistency on gnarly refactors.
|
||||
- `npx reasonix code src/` — narrower sandbox (only `src/` is
|
||||
writable).
|
||||
- `npx reasonix code --no-session` — ephemeral; nothing saved.
|
||||
@@ -182,7 +371,9 @@ in the file. No prompts, no completions, no tool arguments.
|
||||
### Staying current
|
||||
|
||||
The panel header shows the running version next to `Reasonix` (e.g.
|
||||
`Reasonix v0.4.22 · model …`). A quiet 24-hour background check against
|
||||
`Reasonix 0.12.6 · v4-flash · AUTO · 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
|
||||
@@ -367,7 +558,7 @@ your own MCP servers. Sessions persist per name under
|
||||
|
||||
```bash
|
||||
npx reasonix # uses saved config + wizard-selected MCP
|
||||
npx reasonix --preset smart # reasoner + R1 harvest for this run
|
||||
npx reasonix --preset pro # pin v4-pro for the whole run (no auto-downgrade)
|
||||
npx reasonix --session design # named session — resume later with --session design
|
||||
```
|
||||
|
||||
@@ -402,19 +593,26 @@ rendering, retries.
|
||||
|
||||
| command | what it does |
|
||||
|---|---|
|
||||
| `/preset <fast\|smart\|max>` | one-tap bundle (model + harvest + branch) |
|
||||
| `/model <id>` | switch DeepSeek model (`deepseek-chat`, `deepseek-reasoner`) |
|
||||
| `/preset <auto\|flash\|pro>` | model commitment — `auto` = flash with escalation, `flash` = locked flash, `pro` = locked pro |
|
||||
| `/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) |
|
||||
| `/think` | dump the last turn's full R1 reasoning |
|
||||
| `/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 |
|
||||
| `/mcp` | list attached MCP servers and their tools / resources / prompts |
|
||||
| `/resource [uri]` | browse + read MCP resources (no arg → list URIs; `<uri>` → fetch) |
|
||||
| `/prompt [name]` | browse + fetch MCP prompts |
|
||||
| `/tool [N]` | dump the Nth tool call's full output (1 = latest) |
|
||||
| `/compact [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**
|
||||
|
||||
@@ -468,8 +666,8 @@ rendering, retries.
|
||||
- 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.
|
||||
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.
|
||||
|
||||
@@ -575,7 +773,7 @@ npx reasonix sessions # list saved sessions
|
||||
Common flags:
|
||||
|
||||
```bash
|
||||
--preset <fast|smart|max> # bundle (model + harvest + branch)
|
||||
--preset <auto|flash|pro> # model commitment (auto / locked-flash / locked-pro)
|
||||
--model <id> # explicit model id
|
||||
--harvest / --no-harvest # R1 plan-state extraction
|
||||
--branch <N> # self-consistency budget
|
||||
@@ -728,7 +926,7 @@ cd reasonix
|
||||
npm install
|
||||
npm run dev code # run CLI from source via tsx
|
||||
npm run build # tsup to dist/
|
||||
npm test # vitest (648 tests)
|
||||
npm test # vitest (1482 tests)
|
||||
npm run lint # biome
|
||||
npm run typecheck # tsc --noEmit
|
||||
```
|
||||
|
||||
+855
@@ -0,0 +1,855 @@
|
||||
<p align="center">
|
||||
<img src="docs/logo.svg" alt="Reasonix — DeepSeek 原生的 agent 框架" width="640"/>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<em>为 DeepSeek V4(flash + pro)打造的缓存优先 agent 循环 — Ink TUI、原生 MCP、不依赖 LangChain。</em>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="./README.md">English</a> · <strong>简体中文</strong> · <a href="https://esengine.github.io/reasonix/">官方网站</a>
|
||||
</p>
|
||||
|
||||
# Reasonix
|
||||
|
||||
[](https://www.npmjs.com/package/reasonix)
|
||||
[](https://github.com/esengine/reasonix/actions/workflows/ci.yml)
|
||||
[](./LICENSE)
|
||||
[](https://www.npmjs.com/package/reasonix)
|
||||
[](./package.json)
|
||||
|
||||
**DeepSeek 原生的终端 AI 编程代理。** 单次任务成本约为 Claude Code 的
|
||||
1/30,缓存优先的循环是为 DeepSeek 的定价模型量身打造的。编辑以可审查的
|
||||
SEARCH/REPLACE 块呈现,落盘前必须确认。MIT 许可、不绑 IDE、原生 MCP。
|
||||
|
||||
---
|
||||
|
||||
## 60 秒快速上手
|
||||
|
||||
**1. 获取 DeepSeek API Key。** 注册即送免费额度:
|
||||
<https://platform.deepseek.com/api_keys>
|
||||
|
||||
**2. 切到项目目录运行。** 无需安装。
|
||||
|
||||
```bash
|
||||
cd my-project
|
||||
npx reasonix code
|
||||
```
|
||||
|
||||
首次运行会走 30 秒向导(粘贴 API key → 选预设 → 多选 MCP 服务器)。
|
||||
之后每次直接进入。
|
||||
|
||||
**3. 让它改代码。** 模型会以 SEARCH/REPLACE 块的形式提出编辑——
|
||||
你不 `/apply`,磁盘不会被改。
|
||||
|
||||
```
|
||||
reasonix code › users.ts 里 findByEmail 对大小写敏感导致登录失败,帮我改
|
||||
|
||||
assistant
|
||||
▸ tool<search_files> → src/users.ts, src/users.test.ts
|
||||
▸ tool<read_file> → (src/users.ts, 412 chars)
|
||||
▸ 找到了。findByEmail 直接用 === 比对。改成小写规范化并补一条测试。
|
||||
|
||||
src/users.ts
|
||||
<<<<<<< SEARCH
|
||||
return users.find(u => u.email === email);
|
||||
=======
|
||||
const needle = email.toLowerCase();
|
||||
return users.find(u => u.email.toLowerCase() === needle);
|
||||
>>>>>>> REPLACE
|
||||
|
||||
▸ 1 处待应用编辑(1 个文件)— /apply 写入 · /discard 丢弃
|
||||
|
||||
reasonix code › /apply
|
||||
▸ ✓ applied src/users.ts
|
||||
```
|
||||
|
||||
要求 Node ≥ 20.10。支持 macOS、Linux、Windows(PowerShell · Git Bash ·
|
||||
Windows Terminal)。任何时候按 `Esc` 中断;`/help` 查看完整命令列表。
|
||||
|
||||
---
|
||||
|
||||
## Web 控制台 *(0.12 新功能)*
|
||||
|
||||
会话内输入 `/dashboard`,Reasonix 会打印一个带一次性 token 的本地 URL。
|
||||
浏览器打开后是一个 13 个面板的控制面 —— 与正在运行的 TUI 实时双向同步:
|
||||
聊天(流式输出)、编辑器(文件树 + CodeMirror,语法高亮 + 自动补全 + 待
|
||||
审编辑的左右对比 diff)、Usage / Sessions / Plans / Tools / Permissions /
|
||||
System / MCP / Skills / Memory / Hooks / Settings。
|
||||
|
||||
```
|
||||
reasonix code › /dashboard
|
||||
▸ http://127.0.0.1:54219/?token=… (open in browser)
|
||||
```
|
||||
|
||||
仅监听 127.0.0.1,会话结束 token 立即失效,所有改动都走 CSRF 校验。
|
||||
TUI 继续可用 —— 弹窗(shell 确认、plan 审阅、edit 闸门)会同步到先看到
|
||||
它的那一边,另一边自动消失。没有打包步骤,没有 Electron,没有额外进程。
|
||||
|
||||
---
|
||||
|
||||
## 为什么选 Reasonix?(vs Cursor / Claude Code / Cline / Aider)
|
||||
|
||||
三件事,别家不会同时都给你:
|
||||
|
||||
- **成本节省落到账单上。** DeepSeek V4 的 token 单价大约是 Claude Sonnet
|
||||
的 1/30。光便宜还不够 —— *便宜的 token 配上 90%+ 的前缀缓存命中*才是关键。
|
||||
Reasonix 的循环按 append-only 增长设计,缓存稳定的前缀在每次工具调用之间
|
||||
都活着,下面的 benchmark 章节端到端验证过:实测 94.4% 缓存命中,对照组通用
|
||||
框架只有 46.6%。`/stats` 面板每轮都跟踪 "vs Claude Sonnet 4.6" 的节省额,
|
||||
你可以亲眼看着账单不涨。
|
||||
|
||||
- **它住在终端里。** 纯 CLI —— 没有 Electron,没有 VS Code 插件,没有要
|
||||
塞进编辑器的 IDE 插件。和 git、tmux、shell 历史并排。macOS / Linux /
|
||||
Windows(PowerShell、Git Bash、Windows Terminal 都测过)。唯一的网络
|
||||
请求就是 DeepSeek API 本身,中间没有厂商服务器。
|
||||
|
||||
- **开源且彻底可改。** MIT 许可的 TypeScript。整个循环、工具注册表、
|
||||
缓存稳定前缀、TUI、MCP 桥接 —— 全部在 `src/` 下,不到 3 万行。Fork
|
||||
它、做私有构建、塞进 CI 都可以。没有 SaaS 层,没有企业版,没有功能闸门。
|
||||
|
||||
| | Reasonix | Claude Code | Cursor | Cline | Aider |
|
||||
|---|---|---|---|---|---|
|
||||
| 后端 | 仅 DeepSeek V4 | 仅 Anthropic | OpenAI / Anthropic | 任意(OpenRouter)| 任意(OpenRouter)|
|
||||
| 单次任务成本 | **~$0.001–$0.005** | ~$0.05–$0.50 | $20/月 + 用量 | 视情况 | 视情况 |
|
||||
| 运行环境 | 终端 | 终端 + IDE | IDE(Electron)| 仅 VS Code | 终端 |
|
||||
| 开源协议 | **MIT** | 闭源 | 闭源 | Apache 2 | Apache 2 |
|
||||
| 缓存优先前缀循环 | **工程化(94% 命中)** | 基础 | n/a | n/a | 基础 |
|
||||
| MCP 服务器 | **原生支持** | 原生支持 | — | 测试中 | — |
|
||||
| 计划模式(只读审计闸门)| **支持** | 支持 | — | 支持 | — |
|
||||
| 用户编写的 skills | **支持** | 支持 | — | — | — |
|
||||
| 编辑审阅(不自动落盘)| **支持**(`/apply`)| 支持 | 部分 | 支持 | 支持 |
|
||||
| 工作区切换(`/cwd`、`change_workspace`)| **支持** | — | n/a(每窗一项目)| — | — |
|
||||
| 跨会话成本面板 | **支持**(`/stats`)| — | — | — | — |
|
||||
| 沙箱边界强制 | **严格**(拒绝 `..` 逃逸)| 支持 | 部分 | 支持 | 部分 |
|
||||
|
||||
### 这些情况下应该选别的
|
||||
|
||||
- **你想要多模型混用**(在一个工具里同时切 Claude / GPT / Gemini / 本地 Llama)。
|
||||
试试 [Aider](https://aider.chat) 或 [Cline](https://cline.bot)。Reasonix
|
||||
故意只绑 DeepSeek —— 每一层(缓存优先循环、R1 harvest、JSON 模式的工具
|
||||
调用修复、reasoning_effort 上限)都是为 DeepSeek 的具体行为和经济模型
|
||||
调出来的。绑死后端是设计选择,不是早晚要解决的限制。
|
||||
- **你想要 IDE 集成**(编辑器侧边栏 inline diff、多光标、ghost text、重构
|
||||
预览)。试试 [Cursor](https://cursor.com) 或 Claude Code 的 IDE 模式。
|
||||
Reasonix 是终端优先的:diff 在 `git diff` 里、文件树在 `ls` 里、对话
|
||||
在 shell 里。
|
||||
- **你在追最难的推理 benchmark**。Claude Opus 4.6 还是赢一些榜单的。
|
||||
DeepSeek V4-pro 在大多数编程任务上都很有竞争力,但不是每个 benchmark
|
||||
都领先。如果你的任务是"证明这个 PhD 级别的数学命题"而不是"修这个
|
||||
auth bug",从 Claude 起步更合适。
|
||||
- **你需要完全本地 / 永远免费**。DeepSeek API 注册送额度,但不是永久
|
||||
免费。要真正离线/永久免费,看看 Aider + Ollama 或者
|
||||
[Continue](https://continue.dev)。
|
||||
|
||||
### "DeepSeek 现在有 Anthropic 兼容 API 了,我直接拿 Claude Code 接上不就行?"
|
||||
|
||||
可以接。DeepSeek 官方提供了 Anthropic 兼容端点
|
||||
`https://api.deepseek.com/anthropic`,Claude Code(或任何 Anthropic SDK
|
||||
客户端)不改一行代码就能连上去。**协议跑得通,缓存经济学跑不通** ——
|
||||
而后者才是关键。
|
||||
|
||||
看 [DeepSeek 自己的兼容性表](https://api-docs.deepseek.com/guides/anthropic_api):
|
||||
|
||||
| 字段 | 在 DeepSeek 兼容端点上的状态 |
|
||||
|---|---|
|
||||
| `cache_control` 标记 | **Ignored(被忽略)** |
|
||||
| `mcp_servers`(API 层)| Ignored |
|
||||
| `thinking.budget_tokens` | Ignored |
|
||||
| 图像 / 文档 / 引用 | 不支持 |
|
||||
|
||||
`cache_control: Ignored` 就是杀手级的那一行。这里有**两套完全不同的缓存
|
||||
机制在打架**:
|
||||
|
||||
| | Anthropic 原生 | DeepSeek 自动缓存 |
|
||||
|---|---|---|
|
||||
| 模型 | **Marker 驱动。** 你在某条消息上打 `cache_control`,Anthropic 把"到此 marker 为止"的内容做内容寻址缓存。多个 marker = 多个独立断点。 | **Byte-stable prefix。** 缓存对字面字节流从第 0 字节起做指纹。 |
|
||||
| Claude Code 的设计 | 围绕这个设计的。在 system prompt + tool 定义上插 marker,让 loop 在 marker 之后做重排、压缩、插元数据都不丢缓存。 | n/a —— Claude Code 不是为 byte-stable prefix 设计的。 |
|
||||
| Claude Code 接 DeepSeek 兼容端点之后 | Marker 被 strip(忽略)。Claude Code 的主缓存策略消失。 | Fallback 到 auto-cache。但 Claude Code 的 prefix 不是 byte-stable 的(marker 本来就是 byte-stability 的*替代*),auto-cache 也命中不了。 |
|
||||
|
||||
净效果:**Claude Code 的 loop 重定向到 DeepSeek 之后,便宜 token 拿到了,
|
||||
原本依赖的缓存命中没了**。一个在 Anthropic marker cache 上 80%+ 命中的
|
||||
loop,到 DeepSeek 的 auto-cache 上大概率掉到 40-60%(跟我们 benchmark 里
|
||||
通用 harness 的 baseline 同区间)。同一个模型、同一个 API、同一个负载 ——
|
||||
loop 的 invariant 跟它现在对话的缓存机制不匹配。
|
||||
|
||||
Reasonix 的 loop 从第一行起就是按 byte-stable prefix 的不变量设计的。没有
|
||||
marker、没有断点 —— append-only 就是 invariant。这就是为什么同一份 τ-bench
|
||||
负载在 Reasonix 上是 **94.4% 缓存命中**、在 cache-hostile baseline 上是
|
||||
**46.6%**(已 commit 的 transcript,见下面 benchmark 段)。按 DeepSeek 的
|
||||
单价 —— $0.07/Mtok 非缓存、约 $0.014/Mtok 缓存命中 —— 50% 和 94% 命中之间
|
||||
**仅 input 这一侧就大约是 2.5× 的差距**。
|
||||
|
||||
### "那 Aider / Cline / Continue 呢?"
|
||||
|
||||
它们原生支持 DeepSeek(不需要兼容层),便宜 token 单价你确实拿到了。
|
||||
但你拿不到 DeepSeek-specific 的循环工程 —— 这些工具的 loop 是为**通用支持**
|
||||
所有后端(OpenAI / Anthropic / 本地 Llama / ...)设计的,用的是那种会破坏
|
||||
byte-stability 的通用压缩 / 摘要模式。命中率落在和 baseline 同样的 40-60%
|
||||
区间。再加上一堆 DeepSeek 怪癖通用 loop 不处理:
|
||||
|
||||
| 通用 loop 假定 | DeepSeek 实际行为 | Reasonix 怎么处理 |
|
||||
|---|---|---|
|
||||
| 推理通过结构化 `thinking` 块产出 | R1 偶尔把 tool-call JSON 漏到 `<think>` 标签里 | `scavenge` 扫描把漏出的 tool call 拣回,否则模型以为自己已经调用,等不到结果 |
|
||||
| tool schema 严格校验 | DeepSeek 静默丢弃深嵌套 object/array 参数 | auto-flatten:嵌套参数被重写成单层 prefixed name,模型才看得见 |
|
||||
| tool-call args 是良构 JSON | DeepSeek 偶发 `string="false"` 之类的破碎片段 | 专用 `ToolCallRepair` 在 dispatch 之前修好常见形状 |
|
||||
| 推理深度靠系统级开关 | V4 直接暴露 `reasoning_effort` 旋钮(`max` / `high`) | `/effort` slash + `--effort` flag,简单任务可以降到 high 省钱 |
|
||||
| 老 tool result 永久保留 | 1M context 不需要主动 compact,但通用工具都会做 | call-storm breaker + 结果 token cap,但前缀**永不重写** —— 压缩作为新 turn 追加在尾部 |
|
||||
|
||||
> 缓存稳定性不是一个开关,是 loop 设计之初就要建立的不变量。Reasonix
|
||||
> 不是"又一个 agent CLI",是**围绕 DeepSeek 具体的缓存机制和定价模型
|
||||
> 设计的 agent CLI**。
|
||||
|
||||
---
|
||||
|
||||
## `reasonix code` — 终端里的结对编程
|
||||
|
||||
作用域为启动目录。模型自带 `read_file` / `write_file` / `edit_file` /
|
||||
`list_directory` / `search_files` / `directory_tree` / `get_file_info` /
|
||||
`create_directory` / `move_file`,全部在沙箱内 —— 任何解析后落到启动根目录之外
|
||||
的路径(包括 `..` 或符号链接逃逸)都会被拒绝。再加上带只读白名单的
|
||||
`run_command`;任何会修改状态的命令(`npm install`、`git commit` 等)都要走
|
||||
确认弹窗。
|
||||
|
||||
### 流程演示:先看再改
|
||||
|
||||
对于"这段代码做什么用?"这类问题,模型会用读取类工具,然后用散文回答 ——
|
||||
不会出 SEARCH/REPLACE 块、也不会写文件。只有你明确要求修改时它才动手:
|
||||
|
||||
```
|
||||
reasonix code › 这个项目的路由是怎么组织的?
|
||||
assistant
|
||||
▸ tool<directory_tree> → (src/ tree, 47 entries)
|
||||
▸ tool<read_file> → (src/router.ts, 1.2 KB)
|
||||
▸ 路由分三层:顶层 AppRouter 注册 tab,每个 tab 用 React Router 的
|
||||
nested routes 写子路径,最后 …
|
||||
```
|
||||
|
||||
`edit_file` 的 SEARCH 块如果没有按字节精确匹配文件内容,编辑会被显式拒绝
|
||||
而不是模糊匹配。模型能看到错误并自行重试 —— 比起"静默改错","显式拒绝"
|
||||
是更安全的失败方式。
|
||||
|
||||
### Plan 模式 —— 执行前先审阅
|
||||
|
||||
任何比"改个 typo"更大的改动,模型会被引导先提交一份 markdown 计划。
|
||||
你会看到 **批准 / 重做 / 取消** 三选一:
|
||||
|
||||
```
|
||||
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
|
||||
```
|
||||
|
||||
**强制启用** 用 `/plan` —— 进入显式只读阶段:模型必须先提交计划,否则任何
|
||||
编辑或非白名单 shell 调用都不会执行。适合那些你想先审一遍再让模型动手的
|
||||
高风险改动。`/plan off` 或在弹窗里选 Approve/Cancel 退出。
|
||||
|
||||
### 输入前缀 —— `!cmd` 与 `@path`
|
||||
|
||||
两个不需要斜杠的内联快捷方式:
|
||||
|
||||
**`!<cmd>` —— 在沙箱里跑 shell 命令并把结果喂给模型。** 像 bash 一样在
|
||||
prompt 里直接打。输出既会进入可见日志,也会进入会话 —— 模型下一轮会基于它
|
||||
推理:
|
||||
|
||||
```
|
||||
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
|
||||
▸ …
|
||||
```
|
||||
|
||||
无白名单门 —— 用户主动输入的 shell 命令就是显式同意。60 秒超时、32k 字符
|
||||
上限,0.5.14 起会话恢复后依然保留。
|
||||
|
||||
**`@path/to/file` —— 内联一个文件作为 "Referenced files"。** 输入 `@`
|
||||
弹出选择器(↑/↓ 切换、Tab/Enter 插入)。比让模型 `read_file` 后再问更省事:
|
||||
"@src/users.ts 这个文件做什么用?"。沙箱限定:仅相对路径、不允许 `..`、单
|
||||
文件 64KB 上限。最近用过的文件排在前面。
|
||||
|
||||
### `/commit` —— 一步暂存 + 提交
|
||||
|
||||
```
|
||||
reasonix code › /commit "fix: findByEmail case-insensitive"
|
||||
▸ git add -A && git commit -m "fix: findByEmail case-insensitive"
|
||||
[main a1b2c3d] fix: findByEmail case-insensitive
|
||||
```
|
||||
|
||||
### 一些值得试试的命令
|
||||
|
||||
- `/tool 1` —— 打印最后一次工具调用的完整输出(当 400 字内联剪辑不够看时)。
|
||||
- `/think` —— 看上一轮模型的完整推理(思考模式:v4-flash / v4-pro / reasoner 别名)。
|
||||
- `/undo` —— 回滚上一批已应用的编辑。
|
||||
- `/new` —— 在同一目录开新会话,但不丢失旧会话文件。
|
||||
- `/effort high` —— 从默认 `max` agent 推理强度降一档,简单任务更省更快。
|
||||
- `npx reasonix code --preset pro` —— 整轮锁定 v4-pro,不再自动降级到
|
||||
flash。如果想要 self-consistency 分支,加 `--branch 3` 跑三路投票。
|
||||
- `npx reasonix code src/` —— 更窄的沙箱(只有 `src/` 可写)。
|
||||
- `npx reasonix code --no-session` —— 临时会话,什么都不存。
|
||||
|
||||
### `reasonix stats` —— 你到底省了多少?
|
||||
|
||||
每次 `reasonix chat|code|run` 跑完都会往
|
||||
`~/.reasonix/usage.jsonl` 追加一条精简记录(token + 成本 + Claude Sonnet
|
||||
4.6 同负载下的等价价格)。`reasonix stats` 不带参数会把日志聚合成今日 /
|
||||
本周 / 本月 / 历史 四个窗口:
|
||||
|
||||
```
|
||||
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%
|
||||
```
|
||||
|
||||
隐私:日志里只有 token、成本和你自己取的 session 名。没有 prompt、没有
|
||||
completion、没有工具参数。`reasonix stats <transcript>` 仍兼容老用法
|
||||
(按文件出 assistant turn + tool call 摘要)。
|
||||
|
||||
### 保持最新
|
||||
|
||||
面板顶栏在 `Reasonix` 旁边显示当前版本(如
|
||||
`Reasonix 0.12.6 · v4-flash · AUTO · max …`,最后那个 `max` 是推理强度
|
||||
徽章 —— `/effort high` 可降一档)。后台每 24 小时静默查询一次 npm
|
||||
registry,发现新版会在同一行右侧显示黄色 `update: X.Y.Z`。不阻塞、不烦人,
|
||||
每天最多查一次,离线 / 防火墙下静默失败。
|
||||
|
||||
```bash
|
||||
reasonix update # 打印当前 vs 最新,并执行 `npm i -g reasonix@latest`
|
||||
reasonix update --dry-run # 只打印计划,不实际安装
|
||||
```
|
||||
|
||||
通过 `npx` 用?命令会识别这种情况并改为打印 cache 刷新提示 —— npx 在下次
|
||||
调用时会自动取最新版本。
|
||||
|
||||
### 项目约定 —— `REASONIX.md`
|
||||
|
||||
把 `REASONIX.md` 放到项目根目录,每次启动都会被钉进 system prompt。可提交
|
||||
的团队记忆 —— 房间约定、领域词表、模型老忘的事情:
|
||||
|
||||
```bash
|
||||
cat > REASONIX.md <<'EOF'
|
||||
# Notes for Reasonix
|
||||
- Use snake_case for new Python modules; legacy camelCase modules keep their style.
|
||||
- `cargo check` is in the auto-run allowlist; full `cargo test` needs confirmation.
|
||||
- The `api/` dir mirrors `backend/` — keep schemas in sync.
|
||||
EOF
|
||||
```
|
||||
|
||||
重启(或 `/new`)后生效;前缀每会话只哈希一次,让 DeepSeek 的缓存保持热。
|
||||
`/memory` 打印当前已钉的内容。`REASONIX_MEMORY=off` 在 CI / 离线复现时关闭
|
||||
所有记忆来源。
|
||||
|
||||
### 用户记忆 —— `~/.reasonix/memory/`
|
||||
|
||||
第二层 **私人按用户** 的记忆放在你的 home 目录。不像 `REASONIX.md` 会被
|
||||
提交,模型自己也能通过 `remember` 工具往里写。两个作用域:
|
||||
|
||||
- `~/.reasonix/memory/global/` —— 跨项目(你的偏好、工具链)。
|
||||
- `~/.reasonix/memory/<project-hash>/` —— 限定一个 `reasonix code` 沙箱
|
||||
根目录(决策、本地事实、按仓库的快捷方式)。
|
||||
|
||||
每个作用域都维护一个总是加载的 `MEMORY.md` 索引(一行一条)+ 零或多个
|
||||
`<name>.md` 详情文件(按需通过 `recall_memory` 加载)。写入立刻生效;钉进
|
||||
system prompt 在下一次 `/new` 或重启时生效,以保证当前会话的缓存前缀稳定。
|
||||
|
||||
```
|
||||
reasonix code › 我用 bun 而不是 npm,请以后都用 bun 跑构建
|
||||
|
||||
assistant
|
||||
▸ tool<remember> → project/bun_build saved
|
||||
"Build command on this machine is `bun run build`"
|
||||
```
|
||||
|
||||
**斜杠**:`/memory` · `/memory list` · `/memory show <name>` ·
|
||||
`/memory forget <name>` · `/memory clear <scope> confirm`。
|
||||
**模型工具**:`remember(type, scope, name, description, content)` ·
|
||||
`forget(scope, name)` · `recall_memory(scope, name)`。
|
||||
|
||||
项目作用域只在 `reasonix code` 里可用(需要真实的沙箱根来计算哈希);纯
|
||||
`reasonix` 只有全局作用域。
|
||||
|
||||
### Skills —— 用户自定义的 prompt 包
|
||||
|
||||
Skill 就是你写在磁盘上的散文指令块。Reasonix 把它们的名字 + 一行描述钉
|
||||
进 system prompt;模型可以在合适时机自动调 `run_skill({name: "..."})`,
|
||||
你也可以打 `/skill <name> [args]` 手动触发。
|
||||
|
||||
两个作用域,与用户记忆同样的布局:
|
||||
|
||||
- `<project>/.reasonix/skills/` —— 按项目(提交进 git 给团队,或加入
|
||||
`.gitignore` 做个人草稿)。
|
||||
- `~/.reasonix/skills/` —— 全局,到处可用。
|
||||
|
||||
两种文件结构都行:`<name>/SKILL.md`(推荐 —— 可同时打包附带资源)或扁平
|
||||
`<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.
|
||||
```
|
||||
|
||||
用法:
|
||||
|
||||
```
|
||||
reasonix code › /skill review
|
||||
▸ running skill: review
|
||||
assistant
|
||||
▸ tool<run_command> → git diff --cached
|
||||
▸ 3 改动,1 个需要回归测试 …
|
||||
```
|
||||
|
||||
或者让模型自己挑 —— 因为 skill 名字 + 描述都在前缀里,问 "帮我看下未提交
|
||||
的改动有没有风险" 就会触发 `run_skill({name: "review"})`,不用你打斜杠。
|
||||
|
||||
**斜杠**:`/skill`(列出) · `/skill show <name>` · `/skill <name>
|
||||
[args]`(把 body 作为用户轮注入)。
|
||||
|
||||
**故意不绑死** 任何其他客户端的目录约定(`.claude/skills` 等等)——
|
||||
Reasonix 在对话层是模型无关的。任何 SKILL.md 都能用;body 是散文,所以
|
||||
为别的工具写的 skill 多半能直接用(Reasonix 工具名不同 —— `filesystem`
|
||||
/ `shell` / `web` —— 但模型读到指令后会挑我们的等价工具)。
|
||||
|
||||
### Hooks —— 围绕工具调用与轮次自动化
|
||||
|
||||
在 `.reasonix/`(项目或 `~/`)放一个 `settings.json`,Reasonix 会在
|
||||
循环里四个常见的点触发 shell 命令:工具运行前、工具返回后、prompt 到达
|
||||
模型前、轮次结束后。
|
||||
|
||||
```json
|
||||
// <project>/.reasonix/settings.json ← 可提交
|
||||
// ~/.reasonix/settings.json ← 按用户
|
||||
{
|
||||
"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 }]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
每个 hook 都是 shell 命令。Reasonix 调用时通过 stdin 传一份 JSON 信封,
|
||||
描述事件:
|
||||
|
||||
```json
|
||||
{ "event": "PreToolUse", "cwd": "/path/to/project",
|
||||
"toolName": "edit_file", "toolArgs": { "path": "src/x.ts", "..." } }
|
||||
```
|
||||
|
||||
退出码决定走向:
|
||||
|
||||
- **0** —— 通过;循环正常继续
|
||||
- **2** —— 阻断(仅对 `PreToolUse` / `UserPromptSubmit` 生效);hook 的
|
||||
stderr 会作为合成工具结果让模型看到,或者整条 prompt 直接被丢弃
|
||||
- **其他** —— 警告;循环继续,stderr 渲染为黄色行内提示
|
||||
|
||||
`match` 是对工具名的锚定正则;`*` 或省略匹配所有工具。项目 hook 先于全局
|
||||
hook 触发。默认超时:阻断类事件 5 秒,日志类事件 30 秒;可在每条 hook 里
|
||||
用 `timeout` 覆盖。
|
||||
|
||||
**斜杠**:`/hooks`(列出当前生效的 hook)· `/hooks reload`(不丢会话从磁盘
|
||||
重读 `settings.json`)。
|
||||
|
||||
### 在 TUI 里保持最新
|
||||
|
||||
`/update` 在运行中的会话里会显示当前版本、最近一次后台 24h 检查取到的最新
|
||||
版本,以及实际安装命令。这条斜杠 **不会** 直接 spawn `npm install` ——
|
||||
stdio:inherit 进入正在跑的 Ink 渲染器会把显示搞乱。要真正升级请退出会话,
|
||||
在新 shell 里执行 `reasonix update`。
|
||||
|
||||
---
|
||||
|
||||
## `reasonix` —— 也能当通用聊天
|
||||
|
||||
同一套 TUI,没有文件系统工具(除非你通过 MCP 主动接入)。适合起草、问答、
|
||||
schema 设计、架构讨论,或者驱动你自己的 MCP 服务器。会话按名字保存在
|
||||
`~/.reasonix/sessions/`。
|
||||
|
||||
```bash
|
||||
npx reasonix # 用已保存配置 + 向导选过的 MCP
|
||||
npx reasonix --preset pro # 整轮锁定 v4-pro(不自动降级)
|
||||
npx reasonix --session design # 命名会话 — 之后 --session design 续聊
|
||||
```
|
||||
|
||||
临时挂 MCP 服务器:
|
||||
|
||||
```bash
|
||||
npx reasonix \
|
||||
--mcp "fs=npx -y @modelcontextprotocol/server-filesystem /tmp/safe" \
|
||||
--mcp "kb=https://mcp.example.com/sse"
|
||||
```
|
||||
|
||||
MCP 工具走和原生工具一样的 Cache-First + 修复 + 上下文安全管线 —— 32k
|
||||
结果上限、实时进度通知渲染、自动重试。
|
||||
|
||||
---
|
||||
|
||||
## 会话内命令
|
||||
|
||||
**核心**
|
||||
|
||||
| 命令 | 作用 |
|
||||
|---|---|
|
||||
| `/help` · `/?` | 完整命令参考(带提示) |
|
||||
| `/status` | 当前模型 · flag · 上下文 · 会话 |
|
||||
| `/new` · `/reset` | 同会话内开新对话 |
|
||||
| `/clear` | 仅清空可见 scrollback(日志保留) |
|
||||
| `/retry` | 截断并重发上一条消息(重新采样) |
|
||||
| `/exit` · `/quit` | 退出 |
|
||||
|
||||
**模型**
|
||||
|
||||
| 命令 | 作用 |
|
||||
|---|---|
|
||||
| `/preset <auto\|flash\|pro>` | 模型策略 —— `auto` = flash 自动升级、`flash` = 锁 flash、`pro` = 锁 pro |
|
||||
| `/model <id>` | 切换 DeepSeek 模型(`deepseek-v4-flash`、`deepseek-v4-pro`,加上 `deepseek-chat` / `deepseek-reasoner` 兼容别名) |
|
||||
| `/models` | 列出 DeepSeek `/models` 端点的可用模型 |
|
||||
| `/harvest [on\|off]` | 切换 R1 plan-state 提取 |
|
||||
| `/branch <N\|off>` | 每轮跑 N 路并行采样,挑最佳(N ≥ 2) |
|
||||
| `/effort <high\|max>` | reasoning_effort 上限 —— `max` 是 agent 默认,`high` 更便宜更快 |
|
||||
| `/think` | 打印上一轮的完整 thinking-mode 推理 |
|
||||
|
||||
**上下文与工具**
|
||||
|
||||
| 命令 | 作用 |
|
||||
|---|---|
|
||||
| `/mcp` | 列出已挂载的 MCP 服务器及其 tool / resource / prompt |
|
||||
| `/resource [uri]` | 浏览 + 读取 MCP resource(无参 → 列 URI;`<uri>` → 拉取) |
|
||||
| `/prompt [name]` | 浏览 + 拉取 MCP prompt |
|
||||
| `/tool [N]` | 打印第 N 次工具调用的完整输出(1 = 最近) |
|
||||
| `/compact [tokens]` | 压缩日志里超大的工具结果(默认每条结果 4000 tokens) |
|
||||
| `/context` | 看上下文 token 都花在哪(system / tools / log) |
|
||||
| `/stats` | 跨会话成本仪表盘(today / week / month / all-time) |
|
||||
| `/keys` | 键盘快捷键 + 输入前缀(`!` / `@` / `/`)速查 |
|
||||
|
||||
**记忆与 Skill**
|
||||
|
||||
| 命令 | 作用 |
|
||||
|---|---|
|
||||
| `/memory` | 显示已钉记忆(REASONIX.md + ~/.reasonix/memory) |
|
||||
| `/memory list` · `show <name>` · `forget <name>` · `clear <scope> confirm` | 管理记忆库 |
|
||||
| `/skill` · `/skill list` | 列出已发现的 skill(项目 + 全局) |
|
||||
| `/skill show <name>` | 打印某个 skill 的 body |
|
||||
| `/skill <name> [args]` | 运行 skill(把 body 作为用户轮注入) |
|
||||
|
||||
**会话**
|
||||
|
||||
| 命令 | 作用 |
|
||||
|---|---|
|
||||
| `/sessions` | 列出已保存的会话(当前用 `▸` 标记) |
|
||||
| `/forget` | 从磁盘删除当前会话 |
|
||||
| `/setup` | 重新配置(退出后跑 `reasonix setup`) |
|
||||
|
||||
**只在 code 模式下** (`reasonix code`)
|
||||
|
||||
| 命令 | 作用 |
|
||||
|---|---|
|
||||
| `/apply` | 把待应用的 SEARCH/REPLACE 块写入磁盘 |
|
||||
| `/discard` | 丢弃待应用的编辑块 |
|
||||
| `/undo` | 回滚最后一批已应用的编辑 |
|
||||
| `/commit "msg"` | `git add -A && git commit -m "msg"` |
|
||||
| `/plan [on\|off]` | 切换只读 plan 模式 |
|
||||
| `/apply-plan` | 强制批准当前待审计划 |
|
||||
|
||||
**键盘**
|
||||
|
||||
- `Enter` —— 提交
|
||||
- `Shift+Enter` / `Ctrl+J` —— 换行(多行粘贴也行;
|
||||
`\` + Enter 是跨平台兜底)
|
||||
- `↑` / `↓` —— 空闲时翻 prompt 历史;在斜杠自动补全里上下选
|
||||
- `/foo` 前缀下按 `Tab` / `Enter` —— 接受高亮的建议
|
||||
- `Esc` —— 中断当前轮(停 API 调用、取消进行中的工具、拒绝待响应的 MCP 请求)
|
||||
- 确认弹窗里的 `y` / `n` —— 快捷接受 / 拒绝
|
||||
|
||||
---
|
||||
|
||||
## 会话与安全网
|
||||
|
||||
- 会话以 JSONL 形式保存在 `~/.reasonix/sessions/<name>.jsonl`(`reasonix
|
||||
code` 按目录分)。每条消息都原子追加;`Ctrl+C` 不会丢上下文。
|
||||
- 工具结果每次调用最多 32k 字符。超大会话加载时自动自愈(缩小并重写文件)。
|
||||
- 每次出站 API 调用前会校验 `assistant.tool_calls` / `tool` 的配对,损坏的
|
||||
会话不会一直 400。
|
||||
- 上下文仪表 50% 变黄、80% 变红并提示 `/compact`。接近 1M token 上限
|
||||
(V4 flash + pro)会先尝试自动压缩,再退化为强制总结。
|
||||
- `reasonix code` 沙箱拒绝任何解析后落到启动目录之外的路径(含符号链接
|
||||
逃逸和 `..` 穿越)。
|
||||
|
||||
### 故障排查:重复行 / 鬼影渲染
|
||||
|
||||
有些 Windows 终端(Git Bash / MINTTY / winpty 包装的 shell)没完整实现
|
||||
Ink 用的 ANSI cursor-up 转义。表现:spinner、流式预览、工具结果行不在原地
|
||||
覆盖刷新,反而在 scrollback 里印出多份。
|
||||
|
||||
遇到了就用 plain 模式:
|
||||
|
||||
```bash
|
||||
REASONIX_UI=plain npx reasonix code
|
||||
```
|
||||
|
||||
Plain 模式抑制了实时 / 动画行,关掉了内部 tick 计时器。代价是失去流式预览
|
||||
和 spinner,但 scrollback 稳定。Windows Terminal、Windows Terminal 里的
|
||||
PowerShell 7、WezTerm 不需要这个开关。
|
||||
|
||||
---
|
||||
|
||||
## Web 搜索 —— 默认开
|
||||
|
||||
模型一启动就有两个 web 工具:`web_search` 和 `web_fetch`。无 flag、无 API
|
||||
key、无注册。当你问到模型训练时没见过的事(新发布、最近事件、冷门 API),
|
||||
它会自己决定调 `web_search`;snippet 不够就跟一个 `web_fetch`。
|
||||
|
||||
底层是 **Mojeek** 的公开搜索页 —— 独立 web 索引,bot 友好,无 cookie /
|
||||
session。冷门或非常新的查询覆盖率比 Google/Bing 薄一些,但脚本里很可靠。
|
||||
(DDG 是原始后端,但 2026 年开始上反机器人页。)
|
||||
|
||||
**关掉**(离线 / 隐私 / CI):
|
||||
|
||||
```json
|
||||
// ~/.reasonix/config.json
|
||||
{ "apiKey": "sk-…", "search": false }
|
||||
```
|
||||
|
||||
```bash
|
||||
REASONIX_SEARCH=off npx reasonix code
|
||||
```
|
||||
|
||||
**接自己的**(Kagi、SearXNG、内部缓存):实现 `WebSearchProvider` 接口
|
||||
然后自己调 `registerWebTools(registry, { provider })`,或通过 `--mcp`
|
||||
桥接已有的 MCP 搜索服务器。
|
||||
|
||||
---
|
||||
|
||||
## MCP —— 自带工具
|
||||
|
||||
任意 [MCP](https://spec.modelcontextprotocol.io/) 服务器都能用。向导内置
|
||||
目录可选,或用 flag 直接挂:
|
||||
|
||||
```bash
|
||||
# stdio(本地子进程)
|
||||
npx reasonix --mcp "fs=npx -y @modelcontextprotocol/server-filesystem /tmp/safe"
|
||||
|
||||
# 同时挂多个
|
||||
npx reasonix \
|
||||
--mcp "fs=npx -y @modelcontextprotocol/server-filesystem /tmp/safe" \
|
||||
--mcp "demo=npx tsx examples/mcp-server-demo.ts"
|
||||
|
||||
# HTTP+SSE(远程 / 托管)
|
||||
npx reasonix --mcp "kb=https://mcp.example.com/sse"
|
||||
```
|
||||
|
||||
`reasonix mcp list` 显示精选目录。`reasonix mcp inspect <spec>` 不开聊天,
|
||||
直接连一次并打印服务器的 tool / resource / prompt。长任务的进度通知
|
||||
(2025-03-26 spec)会以进度条形式实时渲染在 spinner 里。
|
||||
|
||||
支持的传输:**stdio**(本地命令)和 **HTTP+SSE**(远程,MCP 2024-11-05
|
||||
spec)。
|
||||
|
||||
---
|
||||
|
||||
## CLI 参考
|
||||
|
||||
```bash
|
||||
npx reasonix code [path] # 编程模式,作用域 path(默认 cwd)
|
||||
npx reasonix # 聊天(用已保存配置)
|
||||
npx reasonix setup # 重跑配置向导
|
||||
npx reasonix chat --session work # 命名会话
|
||||
npx reasonix chat --no-session # 临时会话
|
||||
npx reasonix run "ask anything" # 一次性运行,结果流到 stdout
|
||||
npx reasonix stats session.jsonl # 总结一份 transcript
|
||||
npx reasonix replay chat.jsonl # 从 transcript 重建成本/缓存视图
|
||||
npx reasonix diff a.jsonl b.jsonl --md # 对比两份 transcript
|
||||
npx reasonix mcp list # 精选 MCP 目录
|
||||
npx reasonix mcp inspect <spec> # 探测单个 MCP 服务器
|
||||
npx reasonix sessions # 列已保存会话
|
||||
```
|
||||
|
||||
常用 flag:
|
||||
|
||||
```bash
|
||||
--preset <auto|flash|pro> # 模型策略(auto / 锁 flash / 锁 pro)
|
||||
--model <id> # 显式指定模型 ID
|
||||
--harvest / --no-harvest # R1 plan-state 提取
|
||||
--branch <N> # self-consistency 预算
|
||||
--mcp "name=cmd args…" # 挂 MCP 服务器(可重复)
|
||||
--transcript path.jsonl # 同时旁路写一份 JSONL transcript
|
||||
--session <name> # 命名会话(code 模式默认按目录)
|
||||
--no-session # 临时会话
|
||||
--no-config # 忽略 ~/.reasonix/config.json(CI 友好)
|
||||
```
|
||||
|
||||
环境变量(覆盖 config):
|
||||
|
||||
```bash
|
||||
export DEEPSEEK_API_KEY=sk-...
|
||||
export DEEPSEEK_BASE_URL=https://... # 可选的备用端点
|
||||
export REASONIX_MEMORY=off # 关闭 REASONIX.md + 用户记忆
|
||||
export REASONIX_SEARCH=off # 关闭 web_search / web_fetch
|
||||
export REASONIX_UI=plain # 关闭实时行(鬼影绕开)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 库用法
|
||||
|
||||
```ts
|
||||
import {
|
||||
CacheFirstLoop,
|
||||
DeepSeekClient,
|
||||
ImmutablePrefix,
|
||||
ToolRegistry,
|
||||
} from "reasonix";
|
||||
|
||||
const client = new DeepSeekClient(); // 从环境变量读 DEEPSEEK_API_KEY
|
||||
const tools = new ToolRegistry();
|
||||
|
||||
tools.register({
|
||||
name: "add",
|
||||
description: "Add two integers",
|
||||
parameters: {
|
||||
type: "object",
|
||||
properties: { a: { type: "integer" }, b: { type: "integer" } },
|
||||
required: ["a", "b"],
|
||||
},
|
||||
fn: ({ a, b }: { a: number; b: number }) => a + b,
|
||||
});
|
||||
|
||||
const loop = new CacheFirstLoop({
|
||||
client,
|
||||
tools,
|
||||
prefix: new ImmutablePrefix({
|
||||
system: "You are a math helper.",
|
||||
toolSpecs: tools.specs(),
|
||||
}),
|
||||
harvest: true,
|
||||
branch: 3,
|
||||
});
|
||||
|
||||
for await (const ev of loop.step("What is 17 + 25?")) {
|
||||
if (ev.role === "assistant_final") console.log(ev.content);
|
||||
}
|
||||
console.log(loop.stats.summary());
|
||||
```
|
||||
|
||||
`ChatOptions.seedTools` 接受一个预置好的 `ToolRegistry`,如果你只想要
|
||||
`reasonix code` 的 loop 接线、不要 CLI 包装。详见
|
||||
[docs/ARCHITECTURE.md](docs/ARCHITECTURE.md)。
|
||||
|
||||
---
|
||||
|
||||
## 性能对比 —— 缓存命中率自己也能验证
|
||||
|
||||
这里每个抽象都对应 DeepSeek 的一个具体特性 —— 极低 token 价、R1 推理轨
|
||||
迹、自动前缀缓存、JSON 模式。通用框架把这些机会全留在桌上。
|
||||
|
||||
| | Reasonix 默认 | 通用框架 |
|
||||
|---|---|---|
|
||||
| 前缀稳定的循环(→ 85–95% 缓存命中) | 是 | 否(每轮重建 prompt) |
|
||||
| 自动展平深层 tool schema | 是 | 否(DeepSeek 会丢参数) |
|
||||
| 带 jitter 退避的 429/503 重试 | 是 | 否(要自己写回调) |
|
||||
| 抢救泄到 `<think>` 里的 tool call | 是 | 否 |
|
||||
| 同参数重复爆发熔断 | 是 | 否 |
|
||||
| 实时缓存命中 / 成本 / vs Claude 面板 | 是 | 否 |
|
||||
|
||||
同一 τ-bench-lite 负载(8 个多轮工具调用任务 × 3 次重复 = 每边 48 次运行),
|
||||
实测 DeepSeek `deepseek-chat`,唯一变量是前缀稳定性:
|
||||
|
||||
| 指标 | 基线(缓存敌对) | Reasonix | 差值 |
|
||||
|---|---:|---:|---:|
|
||||
| 缓存命中 | 46.6% | **94.4%** | +47.7 pp |
|
||||
| 单任务成本 | $0.002599 | $0.001579 | **−39%** |
|
||||
| 通过率 | 96% (23/24) | **100% (24/24)** | — |
|
||||
|
||||
**无需消耗 API 额度即可复现:**
|
||||
|
||||
```bash
|
||||
git clone https://github.com/esengine/reasonix.git && cd reasonix && npm install
|
||||
npx reasonix replay benchmarks/tau-bench/transcripts/t01_address_happy.reasonix.r1.jsonl
|
||||
npx reasonix diff \
|
||||
benchmarks/tau-bench/transcripts/t01_address_happy.baseline.r1.jsonl \
|
||||
benchmarks/tau-bench/transcripts/t01_address_happy.reasonix.r1.jsonl
|
||||
```
|
||||
|
||||
提交进仓库的 JSONL 文件每轮带 `usage`、`cost`、`prefixHash`。Reasonix
|
||||
的前缀哈希在每次模型调用时都字节稳定;基线则每轮都变。缓存差距是从日志稳
|
||||
定性 **机械可推导** 的,不依赖于 prompt 写得不一样。
|
||||
|
||||
完整 48 次运行报告:
|
||||
[`benchmarks/tau-bench/report.md`](./benchmarks/tau-bench/report.md)。
|
||||
用自己的 API key 复现:`npx tsx benchmarks/tau-bench/runner.ts --repeats 3`。
|
||||
|
||||
MCP 参考运行(即使两个 MCP 子进程并发,整 5 轮也只有一个前缀哈希):
|
||||
|
||||
| 服务器 | 轮次 | 缓存命中 | 成本 | vs Claude |
|
||||
|---|---:|---:|---:|---:|
|
||||
| 内置 demo(`add` / `echo` / `get_time`) | 2 | **96.6%**(第 2 轮) | $0.000254 | −94.0% |
|
||||
| 官方 `server-filesystem` | 5 | **96.7%** | $0.001235 | −97.0% |
|
||||
| **两者并发** | 5 | **81.1%** | $0.001852 | −95.9% |
|
||||
|
||||
---
|
||||
|
||||
## Non-goals(明确不做)
|
||||
|
||||
- **多 agent 编排 / 子 agent**(用 LangGraph)。
|
||||
- **工作流 DSL / DAG 调度 / 并行分支引擎** —— skill 是散文,模型靠正常的
|
||||
tool-use 循环串起来。这样保住了单循环 + append-only + cache-first 三大
|
||||
不变量。
|
||||
- **多供应商抽象**(用 LiteLLM)。Reasonix 故意只做 DeepSeek —— 每个支柱
|
||||
(cache-first 循环、R1 抢救、tool-call 修复)都针对 DeepSeek 的具体行为
|
||||
和经济性做了调优。绑死一家后端是特性。
|
||||
- **RAG / 向量库**(用 LlamaIndex)。
|
||||
- **Web UI / SaaS。**
|
||||
|
||||
Reasonix 只做 DeepSeek,做到底。
|
||||
|
||||
---
|
||||
|
||||
## 开发
|
||||
|
||||
```bash
|
||||
git clone https://github.com/esengine/reasonix.git
|
||||
cd reasonix
|
||||
npm install
|
||||
npm run dev code # 用 tsx 直接从源码跑 CLI
|
||||
npm run build # tsup 打包到 dist/
|
||||
npm test # vitest(1482 个测试)
|
||||
npm run lint # biome
|
||||
npm run typecheck # tsc --noEmit
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## License
|
||||
|
||||
MIT
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
# Reasonix — working knowledge
|
||||
|
||||
TypeScript project. DeepSeek-native coding agent, cache-first loop.
|
||||
MIT-licensed. Node ≥20.10 required.
|
||||
|
||||
## Stack
|
||||
|
||||
- **Language** — TS 5.6+, ES2022, ESM (`"type": "module"`)
|
||||
- **CLI** — Commander.js + Ink 5 (React 18) TUI
|
||||
- **Test** — Vitest 2.x
|
||||
- **Lint / Format** — Biome 1.9 (2-space, double quotes, semicolons always, 100 width)
|
||||
- **Build** — tsup (bundle), `tsx` (dev runner)
|
||||
- **MCP** — stdio + SSE transports, in-process fake in tests
|
||||
|
||||
## Layout
|
||||
|
||||
| Path | What |
|
||||
|---|---|
|
||||
| `src/` | All source — `mcp/`, `tools/`, `cli/`, `code/`, `repair/`, `index/` |
|
||||
| `src/cli/` | CLI entry + commands (`chat.tsx`, `code.tsx`, `diff.ts`, etc.) + Ink TUI in `ui/` |
|
||||
| `src/tools/` | Tool defs (filesystem, shell, MCP, plan, subagent, web, workspace) |
|
||||
| `src/mcp/` | MCP client, transports (stdio, SSE), registry, spec |
|
||||
| `src/repair/` | Tool-call repair pipeline (flatten, scavenge, storm, truncation) |
|
||||
| `src/index/` | Semantic vector index |
|
||||
| `tests/` | Vitest tests, flat `*.test.ts` |
|
||||
| `examples/` | `basic-chat.ts`, `mcp-server-demo.ts`, etc. |
|
||||
| `benchmarks/` | Harvest + tau-bench harnesses |
|
||||
| `data/` | Tokenizer data (`deepseek-tokenizer.json.gz`) |
|
||||
| `dist/` | Build output — **do not edit** |
|
||||
| `.github/` | CI + issue templates |
|
||||
|
||||
## Commands
|
||||
|
||||
```sh
|
||||
npm run build # tsup → dist/
|
||||
npm run dev # tsx src/cli/index.ts
|
||||
npm run chat # tsx src/cli/index.ts chat
|
||||
npm run test # vitest run
|
||||
npm run test:watch # vitest
|
||||
npm run lint # biome check src tests
|
||||
npm run lint:fix # biome check --write src tests
|
||||
npm run format # biome format --write src tests
|
||||
npm run typecheck # tsc --noEmit
|
||||
```
|
||||
|
||||
`prepublishOnly`: lint → typecheck → test → build.
|
||||
|
||||
## Conventions
|
||||
|
||||
- **Imports** — explicit `import type` for type-only imports (Biome `useImportType: warn`). Direct relative imports within project, no barrel re-exports.
|
||||
- **Exports** — named exports only; no `export default`. Entry: `src/index.ts`.
|
||||
- **Tests** — vitest `describe`/`it`/`expect`, no globals. Naming: `<module>.test.ts` flat in `tests/`.
|
||||
- **JSX** — `.tsx` for Ink components. `jsx: "react"` in tsconfig.
|
||||
- **TypeScript** — `strict`, `noUncheckedIndexedAccess`, `noImplicitOverride`. Tools accept `ToolCallContext` (abort signal).
|
||||
- **MCP** — All transports implement `McpTransport` interface. Tools registered via registry at startup.
|
||||
- **Changelog** — Keep a Changelog format. Semver.
|
||||
|
||||
## Watch out for
|
||||
|
||||
- **This IS Reasonix** — edits to `src/loop.ts`, `src/repair/`, `src/tools/`, `src/mcp/` affect every session. Test before publishing.
|
||||
- **SEARCH must match byte-for-byte** — the edit-gate in `src/code/edit-blocks.ts` enforces exact match. Trailing whitespace or wrong indent = mismatch.
|
||||
- **`dist/`** is generated by `tsup`. Never hand-edit.
|
||||
- **`.reasonix/semantic/`** is auto-generated vector index. Never hand-edit.
|
||||
- **`sessions/` and `.reasonix/sessions/`** are user-private, git-ignored (per `.gitignore`).
|
||||
@@ -21,7 +21,11 @@ import {
|
||||
claudeEquivalentCost,
|
||||
loadDotenv,
|
||||
} from "../../src/index.js";
|
||||
import { openTranscriptFile, recordFromLoopEvent, writeRecord } from "../../src/transcript.js";
|
||||
import {
|
||||
openTranscriptFile,
|
||||
recordFromLoopEvent,
|
||||
writeRecord,
|
||||
} from "../../src/transcript/log.js";
|
||||
import { TASKS } from "./tasks.js";
|
||||
import type {
|
||||
HarvestBenchMeta,
|
||||
|
||||
@@ -25,7 +25,11 @@ import {
|
||||
costUsd,
|
||||
loadDotenv,
|
||||
} from "../../src/index.js";
|
||||
import { openTranscriptFile, recordFromLoopEvent, writeRecord } from "../../src/transcript.js";
|
||||
import {
|
||||
openTranscriptFile,
|
||||
recordFromLoopEvent,
|
||||
writeRecord,
|
||||
} from "../../src/transcript/log.js";
|
||||
import { BaselineAgent } from "./baseline.js";
|
||||
import { cloneDb } from "./db.js";
|
||||
import { TASKS } from "./tasks.js";
|
||||
|
||||
+1
-1
@@ -24,6 +24,6 @@
|
||||
}
|
||||
},
|
||||
"files": {
|
||||
"ignore": ["dist", "node_modules", "coverage", "*.d.ts"]
|
||||
"ignore": ["dist", "node_modules", "coverage", "*.d.ts", "dashboard/codemirror.js"]
|
||||
}
|
||||
}
|
||||
+2540
File diff suppressed because it is too large.
Load diff
+4542
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,36 @@
|
||||
var A=class O{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,i){[e,t]=CO(this,e,t);let r=[];return this.decompose(0,e,r,2),i.length&&i.decompose(0,i.length,r,3),this.decompose(t,this.length,r,1),WO.from(r,this.length-(t-e)+i.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=CO(this,e,t);let i=[];return this.decompose(e,t,i,0),WO.from(i,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),i=this.length-this.scanIdentical(e,-1),r=new $O(this),n=new $O(e);for(let s=t,a=t;;){if(r.next(s),n.next(s),s=0,r.lineBreak!=n.lineBreak||r.done!=n.done||r.value!=n.value)return!1;if(a+=r.value.length,r.done||a>=i)return!0}}iter(e=1){return new $O(this,e)}iterRange(e,t=this.length){return new Zr(this,e,t)}iterLines(e,t){let i;if(e==null)i=this.iter();else{t==null&&(t=this.lines+1);let r=this.line(e).from;i=this.iterRange(r,Math.max(r,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new _r(i)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?O.empty:e.length<=32?new Ce(e):WO.from(Ce.split(e,[]))}},Ce=class O extends A{constructor(e,t=um(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,i,r){for(let n=0;;n++){let s=this.text[n],a=r+s.length;if((t?i:a)>=e)return new gs(r,a,i,s);r=a+1,i++}}decompose(e,t,i,r){let n=e<=0&&t>=this.length?this:new O(wc(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(r&1){let s=i.pop(),a=Yr(n.text,s.text.slice(),0,n.length);if(a.length<=32)i.push(new O(a,s.length+n.length));else{let o=a.length>>1;i.push(new O(a.slice(0,o)),new O(a.slice(o)))}}else i.push(n)}replace(e,t,i){if(!(i instanceof O))return super.replace(e,t,i);[e,t]=CO(this,e,t);let r=Yr(this.text,Yr(i.text,wc(this.text,0,e)),t),n=this.length+i.length-(t-e);return r.length<=32?new O(r,n):WO.from(O.split(r,[]),n)}sliceString(e,t=this.length,i=`
|
||||
`){[e,t]=CO(this,e,t);let r="";for(let n=0,s=0;n<=t&&s<this.text.length;s++){let a=this.text[s],o=n+a.length;n>e&&s&&(r+=i),e<o&&t>n&&(r+=a.slice(Math.max(0,e-n),t-n)),n=o+1}return r}flatten(e){for(let t of this.text)e.push(t)}scanIdentical(){return 0}static split(e,t){let i=[],r=-1;for(let n of e)i.push(n),r+=n.length+1,i.length==32&&(t.push(new O(i,r)),i=[],r=-1);return r>-1&&t.push(new O(i,r)),t}},WO=class O extends A{constructor(e,t){super(),this.children=e,this.length=t,this.lines=0;for(let i of e)this.lines+=i.lines}lineInner(e,t,i,r){for(let n=0;;n++){let s=this.children[n],a=r+s.length,o=i+s.lines-1;if((t?o:a)>=e)return s.lineInner(e,t,i,r);r=a+1,i=o+1}}decompose(e,t,i,r){for(let n=0,s=0;s<=t&&n<this.children.length;n++){let a=this.children[n],o=s+a.length;if(e<=o&&t>=s){let l=r&((s<=e?1:0)|(o>=t?2:0));s>=e&&o<=t&&!l?i.push(a):a.decompose(e-s,t-s,i,l)}s=o+1}}replace(e,t,i){if([e,t]=CO(this,e,t),i.lines<this.lines)for(let r=0,n=0;r<this.children.length;r++){let s=this.children[r],a=n+s.length;if(e>=n&&t<=a){let o=s.replace(e-n,t-n,i),l=this.lines-s.lines+o.lines;if(o.lines<l>>4&&o.lines>l>>6){let c=this.children.slice();return c[r]=o,new O(c,this.length-(t-e)+i.length)}return super.replace(n,a,o)}n=a+1}return super.replace(e,t,i)}sliceString(e,t=this.length,i=`
|
||||
`){[e,t]=CO(this,e,t);let r="";for(let n=0,s=0;n<this.children.length&&s<=t;n++){let a=this.children[n],o=s+a.length;s>e&&n&&(r+=i),e<o&&t>s&&(r+=a.sliceString(e-s,t-s,i)),s=o+1}return r}flatten(e){for(let t of this.children)t.flatten(e)}scanIdentical(e,t){if(!(e instanceof O))return 0;let i=0,[r,n,s,a]=t>0?[0,0,this.children.length,e.children.length]:[this.children.length-1,e.children.length-1,-1,-1];for(;;r+=t,n+=t){if(r==s||n==a)return i;let o=this.children[r],l=e.children[n];if(o!=l)return i+o.scanIdentical(l,t);i+=o.length+1}}static from(e,t=e.reduce((i,r)=>i+r.length+1,-1)){let i=0;for(let f of e)i+=f.lines;if(i<32){let f=[];for(let d of e)d.flatten(f);return new Ce(f,t)}let r=Math.max(32,i>>5),n=r<<1,s=r>>1,a=[],o=0,l=-1,c=[];function h(f){let d;if(f.lines>n&&f instanceof O)for(let u of f.children)h(u);else f.lines>s&&(o>s||!o)?($(),a.push(f)):f instanceof Ce&&o&&(d=c[c.length-1])instanceof Ce&&f.lines+d.lines<=32?(o+=f.lines,l+=f.length+1,c[c.length-1]=new Ce(d.text.concat(f.text),d.length+1+f.length)):(o+f.lines>r&&$(),o+=f.lines,l+=f.length+1,c.push(f))}function $(){o!=0&&(a.push(c.length==1?c[0]:O.from(c,l)),l=-1,o=c.length=0)}for(let f of e)h(f);return $(),a.length==1?a[0]:new O(a,t)}};A.empty=new Ce([""],0);function um(O){let e=-1;for(let t of O)e+=t.length+1;return e}function Yr(O,e,t=0,i=1e9){for(let r=0,n=0,s=!0;n<O.length&&r<=i;n++){let a=O[n],o=r+a.length;o>=t&&(o>i&&(a=a.slice(0,i-r)),r<t&&(a=a.slice(t-r)),s?(e[e.length-1]+=a,s=!1):e.push(a)),r=o+1}return e}function wc(O,e,t){return Yr(O,[""],e,t)}var $O=class{constructor(e,t=1){this.dir=t,this.done=!1,this.lineBreak=!1,this.value="",this.nodes=[e],this.offsets=[t>0?1:(e instanceof Ce?e.text.length:e.children.length)<<1]}nextInner(e,t){for(this.done=this.lineBreak=!1;;){let i=this.nodes.length-1,r=this.nodes[i],n=this.offsets[i],s=n>>1,a=r instanceof Ce?r.text.length:r.children.length;if(s==(t>0?a:0)){if(i==0)return this.done=!0,this.value="",this;t>0&&this.offsets[i-1]++,this.nodes.pop(),this.offsets.pop()}else if((n&1)==(t>0?0:1)){if(this.offsets[i]+=t,e==0)return this.lineBreak=!0,this.value=`
|
||||
`,this;e--}else if(r instanceof Ce){let o=r.text[s+(t<0?-1:0)];if(this.offsets[i]+=t,o.length>Math.max(0,e))return this.value=e==0?o:t>0?o.slice(e):o.slice(0,o.length-e),this;e-=o.length}else{let o=r.children[s+(t<0?-1:0)];e>o.length?(e-=o.length,this.offsets[i]+=t):(t<0&&this.offsets[i]--,this.nodes.push(o),this.offsets.push(t>0?1:(o instanceof Ce?o.text.length:o.children.length)<<1))}}}next(e=0){return e<0&&(this.nextInner(-e,-this.dir),e=this.value.length),this.nextInner(e,this.dir)}},Zr=class{constructor(e,t,i){this.value="",this.done=!1,this.cursor=new $O(e,t>i?-1:1),this.pos=t>i?e.length:0,this.from=Math.min(t,i),this.to=Math.max(t,i)}nextInner(e,t){if(t<0?this.pos<=this.from:this.pos>=this.to)return this.value="",this.done=!0,this;e+=Math.max(0,t<0?this.pos-this.to:this.from-this.pos);let i=t<0?this.pos-this.from:this.to-this.pos;e>i&&(e=i),i-=e;let{value:r}=this.cursor.next(e);return this.pos+=(r.length+e)*t,this.value=r.length<=i?r:t<0?r.slice(r.length-i):r.slice(0,i),this.done=!this.value,this}next(e=0){return e<0?e=Math.max(e,this.from-this.pos):e>0&&(e=Math.min(e,this.to-this.pos)),this.nextInner(e,this.cursor.dir)}get lineBreak(){return this.cursor.lineBreak&&this.value!=""}},_r=class{constructor(e){this.inner=e,this.afterBreak=!0,this.value="",this.done=!1}next(e=0){let{done:t,lineBreak:i,value:r}=this.inner.next(e);return t&&this.afterBreak?(this.value="",this.afterBreak=!1):t?(this.done=!0,this.value=""):i?this.afterBreak?this.value="":(this.afterBreak=!0,this.next()):(this.value=r,this.afterBreak=!1),this}get lineBreak(){return!1}};typeof Symbol<"u"&&(A.prototype[Symbol.iterator]=function(){return this.iter()},$O.prototype[Symbol.iterator]=Zr.prototype[Symbol.iterator]=_r.prototype[Symbol.iterator]=function(){return this});var gs=class{constructor(e,t,i,r){this.from=e,this.to=t,this.number=i,this.text=r}get length(){return this.to-this.from}};function CO(O,e,t){return e=Math.max(0,Math.min(O.length,e)),[e,Math.max(e,Math.min(O.length,t))]}var UO="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,3b,f,,w,1j,,,,4,8,4,,3,7,a,2,t,,1m,,,,2,4,8,,9,,a,2,q,,2,2,1l,,4,2,4,2,2,3,3,,u,2,3,,b,2,1l,,4,5,,2,4,,k,2,m,6,,,1m,,,2,,4,8,,7,3,a,2,u,,1n,,,,c,,9,,14,,3,,1l,3,5,3,,4,7,2,b,2,t,,1m,,2,,2,,3,,5,2,7,2,b,2,s,2,1l,2,,,2,4,8,,9,,a,2,t,,20,,4,,2,3,,,8,,29,,2,7,c,8,2q,,2,9,b,6,22,2,r,,,,,,1j,e,,5,,2,5,b,,10,9,,2u,4,,6,,2,2,2,p,2,4,3,g,4,d,,2,2,6,,f,,jj,3,qa,3,t,3,t,2,u,2,1s,2,,7,8,,2,b,9,,19,3,3b,2,y,,3a,3,4,2,9,,6,3,63,2,2,,1m,,,7,,,,,2,8,6,a,2,,1c,h,1r,4,1c,7,,,5,,14,9,c,2,w,4,2,2,,3,1k,,,2,3,,,3,1m,8,2,2,48,3,,d,,7,4,,6,,3,2,5i,1m,,5,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,p,2,5,,47,2,q,i,d,,12,8,p,b,1a,3,1c,,2,4,2,2,13,,1v,6,2,2,2,2,c,,8,,1b,,1f,,,3,2,2,5,2,,,16,2,8,,6m,,2,,4,,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,ar,2,49,b,4w,,1i,f,1k,3,1d,4,2,2,1x,3,10,5,,8,1q,,c,2,1g,9,a,4,2,,2n,3,2,,,2,6,,4g,,3,8,l,2,1l,2,,,,,m,,e,7,3,5,5f,8,2,3,,,n,,29,,2,6,,,2,,,2,,2,6j,,2,4,6,2,,2,r,2,2d,8,2,,,2,2y,,,,2,6,,,2t,3,2,4,,5,77,9,,2,6t,,a,2,,,4,,40,4,2,2,4,,w,a,14,6,2,4,8,,9,6,2,3,1a,d,,2,ba,7,,6,,,2a,m,2,7,,2,,2,3e,6,3,,,2,,7,,,20,2,3,,,,9n,2,f0b,5,1n,7,t4,,1r,4,29,,f5k,2,43q,,,3,4,5,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,79,7,c5,4,15s,7,31,7,240,5,gx7k,2o,3k,6o".split(",").map(O=>O?parseInt(O,36):1);for(let O=1;O<UO.length;O++)UO[O]+=UO[O-1];function pm(O){for(let e=1;e<UO.length;e+=2)if(UO[e]>O)return UO[e-1]<=O;return!1}function bc(O){return O>=127462&&O<=127487}var xc=8205;function Qe(O,e,t=!0,i=!0){return(t?Rc:mm)(O,e,i)}function Rc(O,e,t){if(e==O.length)return e;e&&zc(O.charCodeAt(e))&&Vc(O.charCodeAt(e-1))&&e--;let i=de(O,e);for(e+=be(i);e<O.length;){let r=de(O,e);if(i==xc||r==xc||t&&pm(r))e+=be(r),i=r;else if(bc(r)){let n=0,s=e-2;for(;s>=0&&bc(de(O,s));)n++,s-=2;if(n%2==0)break;e+=2}else break}return e}function mm(O,e,t){for(;e>0;){let i=Rc(O,e-2,t);if(i<e)return i;e--}return 0}function zc(O){return O>=56320&&O<57344}function Vc(O){return O>=55296&&O<56320}function de(O,e){let t=O.charCodeAt(e);if(!Vc(t)||e+1==O.length)return t;let i=O.charCodeAt(e+1);return zc(i)?(t-55296<<10)+(i-56320)+65536:t}function Pi(O){return O<=65535?String.fromCharCode(O):(O-=65536,String.fromCharCode((O>>10)+55296,(O&1023)+56320))}function be(O){return O<65536?1:2}var Ps=/\r\n?|\n/,ue=function(O){return O[O.Simple=0]="Simple",O[O.TrackDel=1]="TrackDel",O[O.TrackBefore=2]="TrackBefore",O[O.TrackAfter=3]="TrackAfter",O}(ue||(ue={})),kt=class O{constructor(e){this.sections=e}get length(){let e=0;for(let t=0;t<this.sections.length;t+=2)e+=this.sections[t];return e}get newLength(){let e=0;for(let t=0;t<this.sections.length;t+=2){let i=this.sections[t+1];e+=i<0?this.sections[t]:i}return e}get empty(){return this.sections.length==0||this.sections.length==2&&this.sections[1]<0}iterGaps(e){for(let t=0,i=0,r=0;t<this.sections.length;){let n=this.sections[t++],s=this.sections[t++];s<0?(e(i,r,n),r+=n):r+=s,i+=n}}iterChangedRanges(
Line truncated
|
||||
`}get readOnly(){return this.facet(Ac)}phrase(e,...t){for(let i of this.facet(O.phrases))if(Object.prototype.hasOwnProperty.call(i,e)){e=i[e];break}return t.length&&(e=e.replace(/\$(\$|\d*)/g,(i,r)=>{if(r=="$")return"$";let n=+(r||1);return!n||n>t.length?i:t[n-1]})),e}languageDataAt(e,t,i=-1){let r=[];for(let n of this.facet(Uc))for(let s of n(this,t,i))Object.prototype.hasOwnProperty.call(s,e)&&r.push(s[e]);return r}charCategorizer(e){return xm(this.languageDataAt("wordChars",e).join(""))}wordAt(e){let{text:t,from:i,length:r}=this.doc.lineAt(e),n=this.charCategorizer(e),s=e-i,a=e-i;for(;s>0;){let o=Qe(t,s,!1);if(n(t.slice(o,s))!=H.Word)break;s=o}for(;a<r;){let o=Qe(t,a);if(n(t.slice(a,o))!=H.Word)break;a=o}return s==a?null:P.range(s+i,a+i)}};K.allowMultipleSelections=ys;K.tabSize=v.define({combine:O=>O.length?O[0]:4});K.lineSeparator=jc;K.readOnly=Ac;K.phrases=v.define({compare(O,e){let t=Object.keys(O),i=Object.keys(e);return t.length==i.length&&t.every(r=>O[r]==e[r])}});K.languageData=Uc;K.changeFilter=Gc;K.transactionFilter=Cc;K.transactionExtender=Ec;ui.reconfigure=j.define();function Ee(O,e,t={}){let i={};for(let r of O)for(let n of Object.keys(r)){let s=r[n],a=i[n];if(a===void 0)i[n]=s;else if(!(a===s||s===void 0))if(Object.hasOwnProperty.call(t,n))i[n]=t[n](a,s);else throw new Error("Config merge conflict for field "+n)}for(let r in e)i[r]===void 0&&(i[r]=e[r]);return i}var nt=class{eq(e){return this==e}range(e,t=e){return mi.create(e,t,this)}};nt.prototype.startSide=nt.prototype.endSide=0;nt.prototype.point=!1;nt.prototype.mapMode=ue.TrackDel;var mi=class O{constructor(e,t,i){this.from=e,this.to=t,this.value=i}static create(e,t,i){return new O(e,t,i)}};function vs(O,e){return O.from-e.from||O.value.startSide-e.value.startSide}var Ys=class O{constructor(e,t,i,r){this.from=e,this.to=t,this.value=i,this.maxPoint=r}get length(){return this.to[this.to.length-1]}findIndex(e,t,i,r=0){let n=i?this.to:this.from;for(let s=r,a=n.length;;){if(s==a)return s;let o=s+a>>1,l=n[o]-e||(i?this.value[o].endSide:this.value[o].startSide)-t;if(o==s)return l>=0?s:a;l>=0?a=o:s=o+1}}between(e,t,i,r){for(let n=this.findIndex(t,-1e9,!0),s=this.findIndex(i,1e9,!1,n);n<s;n++)if(r(this.from[n]+e,this.to[n]+e,this.value[n])===!1)return!1}map(e,t){let i=[],r=[],n=[],s=-1,a=-1;for(let o=0;o<this.value.length;o++){let l=this.value[o],c=this.from[o]+e,h=this.to[o]+e,$,f;if(c==h){let d=t.mapPos(c,l.startSide,l.mapMode);if(d==null||($=f=d,l.startSide!=l.endSide&&(f=t.mapPos(c,l.endSide),f<$)))continue}else if($=t.mapPos(c,l.startSide),f=t.mapPos(h,l.endSide),$>f||$==f&&l.startSide>0&&l.endSide<=0)continue;(f-$||l.endSide-l.startSide)<0||(s<0&&(s=$),l.point&&(a=Math.max(a,f-$)),i.push(l),r.push($-s),n.push(f-s))}return{mapped:i.length?new O(r,n,i,a):null,pos:s}}},N=class O{constructor(e,t,i,r){this.chunkPos=e,this.chunk=t,this.nextLayer=i,this.maxPoint=r}static create(e,t,i,r){return new O(e,t,i,r)}get length(){let e=this.chunk.length-1;return e<0?0:Math.max(this.chunkEnd(e),this.nextLayer.length)}get size(){if(this.isEmpty)return 0;let e=this.nextLayer.size;for(let t of this.chunk)e+=t.value.length;return e}chunkEnd(e){return this.chunkPos[e]+this.chunk[e].length}update(e){let{add:t=[],sort:i=!1,filterFrom:r=0,filterTo:n=this.length}=e,s=e.filter;if(t.length==0&&!s)return this;if(i&&(t=t.slice().sort(vs)),this.isEmpty)return t.length?O.of(t):this;let a=new qr(this,null,-1).goto(0),o=0,l=[],c=new ft;for(;a.value||o<t.length;)if(o<t.length&&(a.from-t[o].from||a.startSide-t[o].value.startSide)>=0){let h=t[o++];c.addInner(h.from,h.to,h.value)||l.push(h)}else a.rangeIndex==1&&a.chunkIndex<this.chunk.length&&(o==t.length||this.chunkEnd(a.chunkIndex)<t[o].from)&&(!s||r>this.chunkEnd(a.chunkIndex)||n<this.chunkPos[a.chunkIndex])&&c.addChunk(this.chunkPos[a.chunkIndex],this.chunk[a.chunkIndex])?a.nextChunk():((!s||r>a.to||n<a.from||s(a.from,a.to,a.value))&&(c.addInner(a.from,a.to,a.value)||l.push(mi.create(a.from,a.to,a.value))),a.next());return c.finishInner(this.nextLayer.isEmpty&&!l.length?O.empty:this.nextLayer.update({add:l,filter:s,filterFrom:r,filterTo:n}))}map(e){if(e.empty||this.isEmpty)return this;let t=[],i=[],r=-1;for(let s=0;s<this.chunk.length;s++){let a=this.chunkPos[s],o=this.chunk[s],l=e.touchesRange(a,a+o.length);if(l===!1)r=Math.max(r,o.maxPoint),t.push(o),i.push(e.mapPos(a));else if(l===!0){let{mapped:c,pos:h}=o.map(a,e);c&&(r=Math.max(r,c.maxPoint),t.push(c),i.push(h))}}let n=this.nextLayer.map(e);return t.length==0?n:new O(i,t,n||O.empty,r)}between(e,t,i){if(!this.isEmpty){for(let r=0;r<this.chunk.length;r++){let n=this.chunkPos[r],s=this.chunk[r];if(t>=n&&e<=n+s.length&&s.between(n,e-n,t-n,i)===!1)return}this.nextLayer.between(e,t,i)}}iter(e=0){return gi.from([this]).goto(e)}get isEmpty(){return this.nextLayer==this}static iter(e,t=0){return gi.from(e).goto(t)}static compare(e,t,i,r,n=-1){let s=e.filter(h=>h.maxPoint>0||!h.isEmpty&&h.maxPoint>=n),a=t.filter(h=>h.maxPoint>0||!h.isEmpty&&h.maxPoint>=n),o=Yc(s,a,i),l=new QO
Line truncated
|
||||
`)}static newName(){let e=Bc[Ic]||1;return Bc[Ic]=e+1,zs+e.toString(36)}static mount(e,t,i){let r=e[Vs],n=i&&i.nonce;r?n&&r.setNonce(n):r=new qs(e,n),r.mount(Array.isArray(t)?t:[t],e)}},Nc=new Map,qs=class{constructor(e,t){let i=e.ownerDocument||e,r=i.defaultView;if(!e.head&&e.adoptedStyleSheets&&r.CSSStyleSheet){let n=Nc.get(i);if(n)return e[Vs]=n;this.sheet=new r.CSSStyleSheet,Nc.set(i,this)}else this.styleTag=i.createElement("style"),t&&this.styleTag.setAttribute("nonce",t);this.modules=[],e[Vs]=this}mount(e,t){let i=this.sheet,r=0,n=0;for(let s=0;s<e.length;s++){let a=e[s],o=this.modules.indexOf(a);if(o<n&&o>-1&&(this.modules.splice(o,1),n--,o=-1),o==-1){if(this.modules.splice(n++,0,a),i)for(let l=0;l<a.rules.length;l++)i.insertRule(a.rules[l],r++)}else{for(;n<o;)r+=this.modules[n++].rules.length;r+=a.rules.length,n++}}if(i)t.adoptedStyleSheets.indexOf(this.sheet)<0&&(t.adoptedStyleSheets=[this.sheet,...t.adoptedStyleSheets]);else{let s="";for(let o=0;o<this.modules.length;o++)s+=this.modules[o].getRules()+`
|
||||
`;this.styleTag.textContent=s;let a=t.head||t;this.styleTag.parentNode!=a&&a.insertBefore(this.styleTag,a.firstChild)}}setNonce(e){this.styleTag&&this.styleTag.getAttribute("nonce")!=e&&this.styleTag.setAttribute("nonce",e)}};var vt={8:"Backspace",9:"Tab",10:"Enter",12:"NumLock",13:"Enter",16:"Shift",17:"Control",18:"Alt",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",44:"PrintScreen",45:"Insert",46:"Delete",59:";",61:"=",91:"Meta",92:"Meta",106:"*",107:"+",108:",",109:"-",110:".",111:"/",144:"NumLock",145:"ScrollLock",160:"Shift",161:"Shift",162:"Control",163:"Control",164:"Alt",165:"Alt",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'"},EO={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},vm=typeof navigator<"u"&&/Mac/.test(navigator.platform),Ym=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);for(fe=0;fe<10;fe++)vt[48+fe]=vt[96+fe]=String(fe);var fe;for(fe=1;fe<=24;fe++)vt[fe+111]="F"+fe;var fe;for(fe=65;fe<=90;fe++)vt[fe]=String.fromCharCode(fe+32),EO[fe]=String.fromCharCode(fe);var fe;for(Wr in vt)EO.hasOwnProperty(Wr)||(EO[Wr]=vt[Wr]);var Wr;function Fc(O){var e=vm&&O.metaKey&&O.shiftKey&&!O.ctrlKey&&!O.altKey||Ym&&O.shiftKey&&O.key&&O.key.length==1||O.key=="Unidentified",t=!e&&O.key||(O.shiftKey?EO:vt)[O.keyCode]||O.key||"Unidentified";return t=="Esc"&&(t="Escape"),t=="Del"&&(t="Delete"),t=="Left"&&(t="ArrowLeft"),t=="Up"&&(t="ArrowUp"),t=="Right"&&(t="ArrowRight"),t=="Down"&&(t="ArrowDown"),t}function Hr(O){let e;return O.nodeType==11?e=O.getSelection?O:O.ownerDocument:e=O,e.getSelection()}function As(O,e){return e?O==e||O.contains(e.nodeType!=1?e.parentNode:e):!1}function Zm(O){let e=O.activeElement;for(;e&&e.shadowRoot;)e=e.shadowRoot.activeElement;return e}function Dr(O,e){if(!e.anchorNode)return!1;try{return As(O,e.anchorNode)}catch{return!1}}function Ri(O){return O.nodeType==3?dO(O,0,O.nodeValue.length).getClientRects():O.nodeType==1?O.getClientRects():[]}function bi(O,e,t,i){return t?Hc(O,e,t,i,-1)||Hc(O,e,t,i,1):!1}function zi(O){for(var e=0;;e++)if(O=O.previousSibling,!O)return e}function Hc(O,e,t,i,r){for(;;){if(O==t&&e==i)return!0;if(e==(r<0?0:Yt(O))){if(O.nodeName=="DIV")return!1;let n=O.parentNode;if(!n||n.nodeType!=1)return!1;e=zi(O)+(r<0?0:1),O=n}else if(O.nodeType==1){if(O=O.childNodes[e+(r<0?-1:0)],O.nodeType==1&&O.contentEditable=="false")return!1;e=r<0?Yt(O):0}else return!1}}function Yt(O){return O.nodeType==3?O.nodeValue.length:O.childNodes.length}function wa(O,e){let t=e?O.left:O.right;return{left:t,right:t,top:O.top,bottom:O.bottom}}function _m(O){let e=O.visualViewport;return e?{left:0,right:e.width,top:0,bottom:e.height}:{left:0,right:O.innerWidth,top:0,bottom:O.innerHeight}}function zh(O,e){let t=e.width/O.offsetWidth,i=e.height/O.offsetHeight;return(t>.995&&t<1.005||!isFinite(t)||Math.abs(e.width-O.offsetWidth)<1)&&(t=1),(i>.995&&i<1.005||!isFinite(i)||Math.abs(e.height-O.offsetHeight)<1)&&(i=1),{scaleX:t,scaleY:i}}function Rm(O,e,t,i,r,n,s,a){let o=O.ownerDocument,l=o.defaultView||window;for(let c=O,h=!1;c&&!h;)if(c.nodeType==1){let $,f=c==o.body,d=1,u=1;if(f)$=_m(l);else{if(/^(fixed|sticky)$/.test(getComputedStyle(c).position)&&(h=!0),c.scrollHeight<=c.clientHeight&&c.scrollWidth<=c.clientWidth){c=c.assignedSlot||c.parentNode;continue}let g=c.getBoundingClientRect();({scaleX:d,scaleY:u}=zh(c,g)),$={left:g.left,right:g.left+c.clientWidth*d,top:g.top,bottom:g.top+c.clientHeight*u}}let p=0,m=0;if(r=="nearest")e.top<$.top?(m=-($.top-e.top+s),t>0&&e.bottom>$.bottom+m&&(m=e.bottom-$.bottom+m+s)):e.bottom>$.bottom&&(m=e.bottom-$.bottom+s,t<0&&e.top-m<$.top&&(m=-($.top+m-e.top+s)));else{let g=e.bottom-e.top,X=$.bottom-$.top;m=(r=="center"&&g<=X?e.top+g/2-X/2:r=="start"||r=="center"&&t<0?e.top-s:e.bottom-X+s)-$.top}if(i=="nearest"?e.left<$.left?(p=-($.left-e.left+n),t>0&&e.right>$.right+p&&(p=e.right-$.right+p+n)):e.right>$.right&&(p=e.right-$.right+n,t<0&&e.left<$.left+p&&(p=-($.left+p-e.left+n))):p=(i=="center"?e.left+(e.right-e.left)/2-($.right-$.left)/2:i=="start"==a?e.left-n:e.right-($.right-$.left)+n)-$.left,p||m)if(f)l.scrollBy(p,m);else{let g=0,X=0;if(m){let T=c.scrollTop;c.scrollTop+=m/u,X=(c.scrollTop-T)*u}if(p){let T=c.scrollLeft;c.scrollLeft+=p/d,g=(c.scrollLeft-T)*d}e={left:e.left-g,top:e.top-X,right:e.right-g,bottom:e.bottom-X},g&&Math.abs(g-p)<1&&(i="nearest"),X&&Math.abs(X-m)<1&&(r="nearest")}if(f)break;c=c.assignedSlot||c.parentNode}else if(c.nodeType==11)c=c.host;else break}function zm(O){let e=O.ownerDocument;for(let t=O.parentNode;t&&t!=e.body;)if(t.nodeType==1){if(t.scrollHeight>t.clientHeight||t.scrollWidth>t.clientWidth)return t;t=t.assignedSlot||t.parentNode}else if(t.nodeType==11)t=t.host;else break;return null}var Ls=class{constructor(){this.aLine truncated
|
||||
`,r=O.state.doc.line(r.number+(t?1:-1)),n=O.bidiSpans(r),l=O.visualLineSide(r,!t)}if(o){if(!o(c))return a}else{if(!i)return l;o=i(c)}a=l}}function Qg(O,e,t){let i=O.state.charCategorizer(e),r=i(t);return n=>{let s=i(n);return r==H.Space&&(r=s),r==s}}function $g(O,e,t,i){let r=e.head,n=t?1:-1;if(r==(t?O.state.doc.length:0))return P.cursor(r,e.assoc);let s=e.goalColumn,a,o=O.contentDOM.getBoundingClientRect(),l=O.coordsAtPos(r,e.assoc||-1),c=O.documentTop;if(l)s==null&&(s=l.left-o.left),a=n<0?l.top:l.bottom;else{let f=O.viewState.lineBlockAt(r);s==null&&(s=Math.min(o.right-o.left,O.defaultCharacterWidth*(r-f.from))),a=(n<0?f.top:f.bottom)+c}let h=o.left+s,$=i??O.viewState.heightOracle.textHeight>>1;for(let f=0;;f+=10){let d=a+($+f)*n,u=$Q(O,{x:h,y:d},!1,n);if(d<o.top||d>o.bottom||(n<0?u<r:u>r)){let p=O.docView.coordsForChar(u),m=!p||d<p.top?-1:1;return P.cursor(u,m,void 0,s)}}}function Ir(O,e,t){for(;;){let i=0;for(let r of O)r.between(e-1,e+1,(n,s,a)=>{if(e>n&&e<s){let o=i||t||(e-n<s-e?-1:1);e=o<0?n:s,i=o}});if(!i)return e}}function js(O,e,t){let i=Ir(O.state.facet(Ya).map(r=>r(O)),t.from,e.head>t.from?-1:1);return i==t.from?t:P.cursor(i,i<t.from?1:-1)}var ia=class{setSelectionOrigin(e){this.lastSelectionOrigin=e,this.lastSelectionTime=Date.now()}constructor(e){this.view=e,this.lastKeyCode=0,this.lastKeyTime=0,this.lastTouchTime=0,this.lastFocusTime=0,this.lastScrollTop=0,this.lastScrollLeft=0,this.pendingIOSKey=void 0,this.lastSelectionOrigin=null,this.lastSelectionTime=0,this.lastEscPress=0,this.lastContextMenu=0,this.scrollHandlers=[],this.handlers=Object.create(null),this.composing=-1,this.compositionFirstChange=null,this.compositionEndedAt=0,this.compositionPendingKey=!1,this.compositionPendingChange=!1,this.mouseSelection=null,this.draggedContent=null,this.handleEvent=this.handleEvent.bind(this),this.notifiedFocused=e.hasFocus,Y.safari&&e.contentDOM.addEventListener("input",()=>null),Y.gecko&&kg(e.contentDOM.ownerDocument)}handleEvent(e){!Pg(this.view,e)||this.ignoreDuringComposition(e)||e.type=="keydown"&&this.keydown(e)||this.runHandlers(e.type,e)}runHandlers(e,t){let i=this.handlers[e];if(i){for(let r of i.observers)r(this.view,t);for(let r of i.handlers){if(t.defaultPrevented)break;if(r(this.view,t)){t.preventDefault();break}}}}ensureHandlers(e){let t=fg(e),i=this.handlers,r=this.view.contentDOM;for(let n in t)if(n!="scroll"){let s=!t[n].handlers.length,a=i[n];a&&s!=!a.handlers.length&&(r.removeEventListener(n,this.handleEvent),a=null),a||r.addEventListener(n,this.handleEvent,{passive:s})}for(let n in i)n!="scroll"&&!t[n]&&r.removeEventListener(n,this.handleEvent);this.handlers=t}keydown(e){if(this.lastKeyCode=e.keyCode,this.lastKeyTime=Date.now(),e.keyCode==9&&Date.now()<this.lastEscPress+2e3)return!0;if(e.keyCode!=27&&dQ.indexOf(e.keyCode)<0&&(this.view.inputState.lastEscPress=0),Y.android&&Y.chrome&&!e.synthetic&&(e.keyCode==13||e.keyCode==8))return this.view.observer.delayAndroidKey(e.key,e.keyCode),!0;let t;return Y.ios&&!e.synthetic&&!e.altKey&&!e.metaKey&&((t=fQ.find(i=>i.keyCode==e.keyCode))&&!e.ctrlKey||dg.indexOf(e.key)>-1&&e.ctrlKey&&!e.shiftKey)?(this.pendingIOSKey=t||e,setTimeout(()=>this.flushIOSKey(),250),!0):(e.keyCode!=229&&this.view.observer.forceFlush(),!1)}flushIOSKey(e){let t=this.pendingIOSKey;return!t||t.key=="Enter"&&e&&e.from<e.to&&/^\S+$/.test(e.insert.toString())?!1:(this.pendingIOSKey=void 0,IO(this.view.contentDOM,t.key,t.keyCode,t instanceof KeyboardEvent?t:void 0))}ignoreDuringComposition(e){return/^key/.test(e.type)?this.composing>0?!0:Y.safari&&!Y.ios&&this.compositionPendingKey&&Date.now()-this.compositionEndedAt<100?(this.compositionPendingKey=!1,!0):!1:!1}startMouseSelection(e){this.mouseSelection&&this.mouseSelection.destroy(),this.mouseSelection=e}update(e){this.mouseSelection&&this.mouseSelection.update(e),this.draggedContent&&e.docChanged&&(this.draggedContent=this.draggedContent.map(e.changes)),e.transactions.length&&(this.lastKeyCode=this.lastSelectionTime=0)}destroy(){this.mouseSelection&&this.mouseSelection.destroy()}};function ch(O,e){return(t,i)=>{try{return e.call(O,i,t)}catch(r){ve(t.state,r)}}}function fg(O){let e=Object.create(null);function t(i){return e[i]||(e[i]={observers:[],handlers:[]})}for(let i of O){let r=i.spec;if(r&&r.domEventHandlers)for(let n in r.domEventHandlers){let s=r.domEventHandlers[n];s&&t(n).handlers.push(ch(i.value,s))}if(r&&r.domEventObservers)for(let n in r.domEventObservers){let s=r.domEventObservers[n];s&&t(n).observers.push(ch(i.value,s))}}for(let i in st)t(i).handlers.push(st[i]);for(let i in at)t(i).observers.push(at[i]);return e}var fQ=[{key:"Backspace",keyCode:8,inputType:"deleteContentBackward"},{key:"Enter",keyCode:13,inputType:"insertParagraph"},{key:"Enter",keyCode:13,inputType:"insertLineBreak"},{key:"Delete",keyCode:46,inputType:"deleteContentForward"}],dg="dthko",dQ=[16,17,18,20,91,92,224,225],Gr=6;function Cr(O){return Math.max(0,O)*.7+8}function ug(O,e){return Math.max(Math.abs(O.clientX-e.clientX),Math.abs(
Line truncated
|
||||
`&&O.lineWrapping&&(i&&(i=P.single(i.main.anchor-1,i.main.head-1)),t={from:r.from,to:r.to,insert:A.of([" "])}),t){if(Y.ios&&O.inputState.flushIOSKey(t)||Y.android&&(t.to==r.to&&(t.from==r.from||t.from==r.from-1&&O.state.sliceDoc(t.from,r.from)==" ")&&t.insert.length==1&&t.insert.lines==2&&IO(O.contentDOM,"Enter",13)||(t.from==r.from-1&&t.to==r.to&&t.insert.length==0||n==8&&t.insert.length<t.to-t.from&&t.to>r.head)&&IO(O.contentDOM,"Backspace",8)||t.from==r.from&&t.to==r.to+1&&t.insert.length==0&&IO(O.contentDOM,"Delete",46)))return!0;let s=t.insert.toString();O.inputState.composing>=0&&O.inputState.composing++;let a,o=()=>a||(a=Wg(O,t,i));return O.state.facet(tQ).some(l=>l(O,t.from,t.to,s,o))||O.dispatch(o()),!0}else if(i&&!i.main.eq(r)){let s=!1,a="select";return O.inputState.lastSelectionTime>Date.now()-50&&(O.inputState.lastSelectionOrigin=="select"&&(s=!0),a=O.inputState.lastSelectionOrigin),O.dispatch({selection:i,scrollIntoView:s,userEvent:a}),!0}else return!1}function Wg(O,e,t){let i,r=O.state,n=r.selection.main;if(e.from>=n.from&&e.to<=n.to&&e.to-e.from>=(n.to-n.from)/3&&(!t||t.main.empty&&t.main.from==e.from+e.insert.length)&&O.inputState.composing<0){let a=n.from<e.from?r.sliceDoc(n.from,e.from):"",o=n.to>e.to?r.sliceDoc(e.to,n.to):"";i=r.replaceSelection(O.state.toText(a+e.insert.sliceString(0,void 0,O.state.lineBreak)+o))}else{let a=r.changes(e),o=t&&t.main.to<=a.newLength?t.main:void 0;if(r.selection.ranges.length>1&&O.inputState.composing>=0&&e.to<=n.to&&e.to>=n.to-10){let l=O.state.sliceDoc(e.from,e.to),c,h=t&&hQ(O,t.main.head);if(h){let d=e.insert.length-(e.to-e.from);c={from:h.from,to:h.to-d}}else c=O.state.doc.lineAt(n.head);let $=n.to-e.to,f=n.to-n.from;i=r.changeByRange(d=>{if(d.from==n.from&&d.to==n.to)return{changes:a,range:o||d.map(a)};let u=d.to-$,p=u-l.length;if(d.to-d.from!=f||O.state.sliceDoc(p,u)!=l||d.to>=c.from&&d.from<=c.to)return{range:d};let m=r.changes({from:p,to:u,insert:e.insert}),g=d.to-n.to;return{changes:m,range:o?P.range(Math.max(0,o.anchor+g),Math.max(0,o.head+g)):d.map(m)}})}else i={changes:a,selection:o&&r.selection.replaceRange(o)}}let s="input.type";return(O.composing||O.inputState.compositionPendingChange&&O.inputState.compositionEndedAt>Date.now()-50)&&(O.inputState.compositionPendingChange=!1,s+=".compose",O.inputState.compositionFirstChange&&(s+=".start",O.inputState.compositionFirstChange=!1)),r.update(i,{userEvent:s,scrollIntoView:!0})}function Ug(O,e,t,i){let r=Math.min(O.length,e.length),n=0;for(;n<r&&O.charCodeAt(n)==e.charCodeAt(n);)n++;if(n==r&&O.length==e.length)return null;let s=O.length,a=e.length;for(;s>0&&a>0&&O.charCodeAt(s-1)==e.charCodeAt(a-1);)s--,a--;if(i=="end"){let o=Math.max(0,n-Math.min(s,a));t-=s+o-n}if(s<n&&O.length<e.length){let o=t<=n&&t>=s?n-t:0;n-=o,a=n+(a-s),s=n}else if(a<n){let o=t<=n&&t>=a?n-t:0;n-=o,s=n+(s-a),a=n}return{from:n,toA:s,toB:a}}function jg(O){let e=[];if(O.root.activeElement!=O.contentDOM)return e;let{anchorNode:t,anchorOffset:i,focusNode:r,focusOffset:n}=O.observer.selectionRange;return t&&(e.push(new sn(t,i)),(r!=t||n!=i)&&e.push(new sn(r,n))),e}function Gg(O,e){if(O.length==0)return null;let t=O[0].pos,i=O.length==2?O[1].pos:t;return t>-1&&i>-1?P.single(t+e,i+e):null}var Cg={childList:!0,characterData:!0,subtree:!0,attributes:!0,characterDataOldValue:!0},Gs=Y.ie&&Y.ie_version<=11,ma=class{constructor(e){this.view=e,this.active=!1,this.selectionRange=new Ls,this.selectionChanged=!1,this.delayedFlush=-1,this.resizeTimeout=-1,this.queue=[],this.delayedAndroidKey=null,this.flushingAndroidKey=-1,this.lastChange=0,this.scrollTargets=[],this.intersection=null,this.resizeScroll=null,this.intersecting=!1,this.gapIntersection=null,this.gaps=[],this.printQuery=null,this.parentCheck=-1,this.dom=e.contentDOM,this.observer=new MutationObserver(t=>{for(let i of t)this.queue.push(i);(Y.ie&&Y.ie_version<=11||Y.ios&&e.composing)&&t.some(i=>i.type=="childList"&&i.removedNodes.length||i.type=="characterData"&&i.oldValue.length>i.target.nodeValue.length)?this.flushSoon():this.flush()}),Gs&&(this.onCharData=t=>{this.queue.push({target:t.target,type:"characterData",oldValue:t.prevValue}),this.flushSoon()}),this.onSelectionChange=this.onSelectionChange.bind(this),this.onResize=this.onResize.bind(this),this.onPrint=this.onPrint.bind(this),this.onScroll=this.onScroll.bind(this),window.matchMedia&&(this.printQuery=window.matchMedia("print")),typeof ResizeObserver=="function"&&(this.resizeScroll=new ResizeObserver(()=>{var t;((t=this.view.docView)===null||t===void 0?void 0:t.lastUpdate)<Date.now()-75&&this.onResize()}),this.resizeScroll.observe(e.scrollDOM)),this.addWindowListeners(this.win=e.win),this.start(),typeof IntersectionObserver=="function"&&(this.intersection=new IntersectionObserver(t=>{this.parentCheck<0&&(this.parentCheck=setTimeout(this.listenForScroll.bind(this),1e3)),t.length>0&&t[t.length-1].intersectionRatio>0!=this.intersecting&&(this.intersecting=!this.intersecting,this.intersecting!=this.view.inView&&this.onScrollChang
Line truncated
|
||||
`:i=="r"?"\r":i=="t"?" ":"\\")}eq(e){return this.search==e.search&&this.replace==e.replace&&this.caseSensitive==e.caseSensitive&&this.regexp==e.regexp&&this.wholeWord==e.wholeWord}create(){return this.regexp?new qo(this):new Vo(this)}getCursor(e,t=0,i){let r=e.doc?e:K.create({doc:e});return i==null&&(i=r.doc.length),this.regexp?ii(this,r,t,i):Oi(this,r,t,i)}},Mn=class{constructor(e){this.spec=e}};function Oi(O,e,t,i){return new sO(e.doc,O.unquoted,t,i,O.caseSensitive?void 0:r=>r.toLowerCase(),O.wholeWord?w1(e.doc,e.charCategorizer(e.selection.main.head)):void 0)}function w1(O,e){return(t,i,r,n)=>((n>t||n+r.length<i)&&(n=Math.max(0,t-2),r=O.sliceString(n,Math.min(O.length,i+2))),(e(Dn(r,t-n))!=H.Word||e(In(r,t-n))!=H.Word)&&(e(In(r,i-n))!=H.Word||e(Dn(r,i-n))!=H.Word))}var Vo=class extends Mn{constructor(e){super(e)}nextMatch(e,t,i){let r=Oi(this.spec,e,i,e.doc.length).nextOverlapping();return r.done&&(r=Oi(this.spec,e,0,t).nextOverlapping()),r.done?null:r.value}prevMatchInRange(e,t,i){for(let r=i;;){let n=Math.max(t,r-1e4-this.spec.unquoted.length),s=Oi(this.spec,e,n,r),a=null;for(;!s.nextOverlapping().done;)a=s.value;if(a)return a;if(n==t)return null;r-=1e4}}prevMatch(e,t,i){return this.prevMatchInRange(e,0,t)||this.prevMatchInRange(e,i,e.doc.length)}getReplacement(e){return this.spec.unquote(this.spec.replace)}matchAll(e,t){let i=Oi(this.spec,e,0,e.doc.length),r=[];for(;!i.next().done;){if(r.length>=t)return null;r.push(i.value)}return r}highlight(e,t,i,r){let n=Oi(this.spec,e,Math.max(0,t-this.spec.unquoted.length),Math.min(i+this.spec.unquoted.length,e.doc.length));for(;!n.next().done;)r(n.value.from,n.value.to)}};function ii(O,e,t,i){return new jn(e.doc,O.search,{ignoreCase:!O.caseSensitive,test:O.wholeWord?b1(e.charCategorizer(e.selection.main.head)):void 0},t,i)}function Dn(O,e){return O.slice(Qe(O,e,!1),e)}function In(O,e){return O.slice(e,Qe(O,e))}function b1(O){return(e,t,i)=>!i[0].length||(O(Dn(i.input,i.index))!=H.Word||O(In(i.input,i.index))!=H.Word)&&(O(In(i.input,i.index+i[0].length))!=H.Word||O(Dn(i.input,i.index+i[0].length))!=H.Word)}var qo=class extends Mn{nextMatch(e,t,i){let r=ii(this.spec,e,i,e.doc.length).next();return r.done&&(r=ii(this.spec,e,0,t).next()),r.done?null:r.value}prevMatchInRange(e,t,i){for(let r=1;;r++){let n=Math.max(t,i-r*1e4),s=ii(this.spec,e,n,i),a=null;for(;!s.next().done;)a=s.value;if(a&&(n==t||a.from>n+10))return a;if(n==t)return null}}prevMatch(e,t,i){return this.prevMatchInRange(e,0,t)||this.prevMatchInRange(e,i,e.doc.length)}getReplacement(e){return this.spec.unquote(this.spec.replace).replace(/\$([$&\d+])/g,(t,i)=>i=="$"?"$":i=="&"?e.match[0]:i!="0"&&+i<e.match.length?e.match[i]:t)}matchAll(e,t){let i=ii(this.spec,e,0,e.doc.length),r=[];for(;!i.next().done;){if(r.length>=t)return null;r.push(i.value)}return r}highlight(e,t,i,r){let n=ii(this.spec,e,Math.max(0,t-250),Math.min(i+250,e.doc.length));for(;!n.next().done;)r(n.value.from,n.value.to)}},ar=j.define(),Go=j.define(),nO=$e.define({create(O){return new sr(Wo(O).create(),null)},update(O,e){for(let t of e.effects)t.is(ar)?O=new sr(t.value.create(),O.panel):t.is(Go)&&(O=new sr(O.query,t.value?Co:null));return O},provide:O=>Ci.from(O,e=>e.panel)});var sr=class{constructor(e,t){this.query=e,this.panel=t}},x1=R.mark({class:"cm-searchMatch"}),k1=R.mark({class:"cm-searchMatch cm-searchMatch-selected"}),v1=pe.fromClass(class{constructor(O){this.view=O,this.decorations=this.highlight(O.state.field(nO))}update(O){let e=O.state.field(nO);(e!=O.startState.field(nO)||O.docChanged||O.selectionSet||O.viewportChanged)&&(this.decorations=this.highlight(e))}highlight({query:O,panel:e}){if(!e||!O.spec.valid)return R.none;let{view:t}=this,i=new ft;for(let r=0,n=t.visibleRanges,s=n.length;r<s;r++){let{from:a,to:o}=n[r];for(;r<s-1&&o>n[r+1].from-2*250;)o=n[++r].to;O.highlight(t.state,a,o,(l,c)=>{let h=t.state.selection.ranges.some($=>$.from==l&&$.to==c);i.add(l,c,h?k1:x1)})}return i.finish()}},{decorations:O=>O.decorations});function or(O){return e=>{let t=e.state.field(nO,!1);return t&&t.query.spec.valid?O(e,t):vf(e)}}var Bn=or((O,{query:e})=>{let{to:t}=O.state.selection.main,i=e.nextMatch(O.state,t,t);if(!i)return!1;let r=P.single(i.from,i.to),n=O.state.facet(ri);return O.dispatch({selection:r,effects:[Eo(O,i),n.scrollToMatch(r.main,O)],userEvent:"select.search"}),kf(O),!0}),Nn=or((O,{query:e})=>{let{state:t}=O,{from:i}=t.selection.main,r=e.prevMatch(t,i,i);if(!r)return!1;let n=P.single(r.from,r.to),s=O.state.facet(ri);return O.dispatch({selection:n,effects:[Eo(O,r),s.scrollToMatch(n.main,O)],userEvent:"select.search"}),kf(O),!0}),Y1=or((O,{query:e})=>{let t=e.matchAll(O.state,1e3);return!t||!t.length?!1:(O.dispatch({selection:P.create(t.map(i=>P.range(i.from,i.to))),userEvent:"select.search.matches"}),!0)}),Z1=({state:O,dispatch:e})=>{let t=O.selection;if(t.ranges.length>1||t.main.empty)return!1;let{from:i,to:r}=t.main,n=[],s=0;for(let a=new sO(O.doc,O.sliceDoc(i,r));!a.next().done;){if(n.length>1e3)return!1;a.value.from==i
Line truncated
|
||||
\${}
|
||||
} catch (\${error}) {
|
||||
\${}
|
||||
}`,{label:"try",detail:"/ catch block",type:"keyword"}),W("if (${}) {\n ${}\n}",{label:"if",detail:"block",type:"keyword"}),W(`if (\${}) {
|
||||
\${}
|
||||
} else {
|
||||
\${}
|
||||
}`,{label:"if",detail:"/ else block",type:"keyword"}),W(`class \${name} {
|
||||
constructor(\${params}) {
|
||||
\${}
|
||||
}
|
||||
}`,{label:"class",detail:"definition",type:"keyword"}),W('import {${names}} from "${module}"\n${}',{label:"import",detail:"named",type:"keyword"}),W('import ${name} from "${module}"\n${}',{label:"import",detail:"default",type:"keyword"})],bT=Bf.concat([W("interface ${name} {\n ${}\n}",{label:"interface",detail:"definition",type:"keyword"}),W("type ${name} = ${type}",{label:"type",detail:"definition",type:"keyword"}),W("enum ${name} {\n ${}\n}",{label:"enum",detail:"definition",type:"keyword"})]),Mf=new Pt,Nf=new Set(["Script","Block","FunctionExpression","FunctionDeclaration","ArrowFunction","MethodDeclaration","ForStatement"]);function cr(O){return(e,t)=>{let i=e.node.getChild("VariableDefinition");return i&&t(i,O),!0}}var xT=["FunctionDeclaration"],kT={FunctionDeclaration:cr("function"),ClassDeclaration:cr("class"),ClassExpression:()=>!0,EnumDeclaration:cr("constant"),TypeAliasDeclaration:cr("type"),NamespaceDeclaration:cr("namespace"),VariableDefinition(O,e){O.matchContext(xT)||e(O,"variable")},TypeDefinition(O,e){e(O,"type")},__proto__:null};function Ff(O,e){let t=Mf.get(e);if(t)return t;let i=[],r=!0;function n(s,a){let o=O.sliceString(s.from,s.to);i.push({label:o,type:a})}return e.cursor(C.IncludeAnonymous).iterate(s=>{if(r)r=!1;else if(s.name){let a=kT[s.name];if(a&&a(s,n)||Nf.has(s.name))return!1}else if(s.to-s.from>8192){for(let a of Ff(O,s.node))i.push(a);return!1}}),Mf.set(e,i),i}var Df=/^[\w$\xa1-\uffff][\w$\d\xa1-\uffff]*$/,Hf=["TemplateString","String","RegExp","LineComment","BlockComment","VariableDefinition","TypeDefinition","Label","PropertyDefinition","PropertyName","PrivatePropertyDefinition","PrivatePropertyName",".","?."];function vT(O){let e=q(O.state).resolveInner(O.pos,-1);if(Hf.indexOf(e.name)>-1)return null;let t=e.name=="VariableName"||e.to-e.from<20&&Df.test(O.state.sliceDoc(e.from,e.to));if(!t&&!O.explicit)return null;let i=[];for(let r=e;r;r=r.parent)Nf.has(r.name)&&(i=i.concat(Ff(O.state.doc,r)));return{options:i,from:t?e.from:O.pos,validFor:Df}}var ht=re.define({name:"javascript",parser:Lf.configure({props:[ne.add({IfStatement:oe({except:/^\s*({|else\b)/}),TryStatement:oe({except:/^\s*({|catch\b|finally\b)/}),LabeledStatement:KO,SwitchBody:O=>{let e=O.textAfter,t=/^\s*\}/.test(e),i=/^\s*(case|default)\b/.test(e);return O.baseIndent+(t?0:i?1:2)*O.unit},Block:_e({closing:"}"}),ArrowFunction:O=>O.baseIndent+O.unit,"TemplateString BlockComment":()=>null,"Statement Property":oe({except:/^{/}),JSXElement(O){let e=/^\s*<\//.test(O.textAfter);return O.lineIndent(O.node.from)+(e?0:O.unit)},JSXEscape(O){let e=/\s*\}/.test(O.textAfter);return O.lineIndent(O.node.from)+(e?0:O.unit)},"JSXOpenTag JSXSelfClosingTag"(O){return O.column(O.node.from)+O.unit}}),J.add({"Block ClassBody SwitchBody EnumBody ObjectExpression ArrayExpression ObjectType":me,BlockComment(O){return{from:O.from+2,to:O.to-2}}})]}),languageData:{closeBrackets:{brackets:["(","[","{","'",'"',"`"]},commentTokens:{line:"//",block:{open:"/*",close:"*/"}},indentOnInput:/^\s*(?:case |default:|\{|\}|<\/)$/,wordChars:"$"}}),Kf={test:O=>/^JSX/.test(O.name),facet:Fi({commentTokens:{block:{open:"{/*",close:"*/}"}}})},rl=ht.configure({dialect:"ts"},"typescript"),nl=ht.configure({dialect:"jsx",props:[Tn.add(O=>O.isTop?[Kf]:void 0)]}),sl=ht.configure({dialect:"jsx ts",props:[Tn.add(O=>O.isTop?[Kf]:void 0)]},"typescript"),Jf=O=>({label:O,type:"keyword"}),ed="break case const continue default delete export extends false finally in instanceof let new return static super switch this throw true typeof var yield".split(" ").map(Jf),YT=ed.concat(["declare","implements","private","protected","public"].map(Jf));function hr(O={}){let e=O.jsx?O.typescript?sl:nl:O.typescript?rl:ht,t=O.typescript?bT.concat(YT):Bf.concat(ed);return new F(e,[ht.data.of({autocomplete:rO(Hf,Rt(t))}),ht.data.of({autocomplete:vT}),O.jsx?RT:[]])}function ZT(O){for(;;){if(O.name=="JSXOpenTag"||O.name=="JSXSelfClosingTag"||O.name=="JSXFragmentTag")return O;if(O.name=="JSXEscape"||!O.parent)return null;O=O.parent}}function If(O,e,t=O.length){for(let i=e?.firstChild;i;i=i.nextSibling)if(i.name=="JSXIdentifier"||i.name=="JSXBuiltin"||i.name=="JSXNamespacedName"||i.name=="JSXMemberExpression")return O.sliceString(i.from,Math.min(i.to,t));return""}var _T=typeof navigator=="object"&&/Android\b/.test(navigator.userAgent),RT=x.inputHandler.of((O,e,t,i,r)=>{if((_T?O.composing:O.compositionStarted)||O.state.readOnly||e!=t||i!=">"&&i!="/"||!ht.isActiveAt(O.state,e,-1))return!1;let n=r(),{state:s}=n,a=s.changeByRange(o=>{var l;let{head:c}=o,h=q(s).resolveInner(c-1,-1),$;if(h.name=="JSXStartTag"&&(h=h.parent),!(s.doc.sliceString(c-1,c)!=i||h.name=="JSXAttributeValue"&&h.to>c)){if(i==">"&&h.name=="JSXFragmentTag")return{range:o,changes:{from:c,insert:"</>"}};if(i=="/"&&h.name=="JSXStartCloseTag"){let f=h.parent,d=f.parent;if(d&&f.from==c-2&&(($=If(s.doc,d.firstChild,c))||((l=d.firstChild)===null||l===void 0?void 0:l.name)=="JSXFragmentTag")){let u=`${$}>`;return{range:P.cursor(c+u.length
Line truncated
|
||||
|
||||
`,{label:"if",detail:"block",type:"keyword"}),W("if ${}:\n ${}\nelse:\n ${}",{label:"if",detail:"/ else block",type:"keyword"}),W("class ${name}:\n def __init__(self, ${params}):\n ${}",{label:"class",detail:"definition",type:"keyword"}),W("import ${module}",{label:"import",detail:"statement",type:"keyword"}),W("from ${module} import ${names}",{label:"from",detail:"import",type:"keyword"})],Iy=rO(Pd,Rt(My.concat(Dy)));function ud(O){let{node:e,pos:t}=O,i=O.lineIndent(t,-1),r=null;for(;;){let n=e.childBefore(t);if(n)if(n.name=="Comment")t=n.from;else if(n.name=="Body")O.baseIndentFor(n)+O.unit<=i&&(r=n),e=n;else if(n.type.is("Statement"))e=n;else break;else break}return r}function pd(O,e){let t=O.baseIndentFor(e),i=O.lineAt(O.pos,-1),r=i.from+i.text.length;return/^\s*($|#)/.test(i.text)&&O.node.to<r+100&&!/\S/.test(O.state.sliceDoc(r,O.node.to))&&O.lineIndent(O.pos,-1)<=t||/^\s*(else:|elif |except |finally:)/.test(O.textAfter)&&O.lineIndent(O.pos,-1)>t?null:t+O.unit}var Ql=re.define({name:"python",parser:$d.configure({props:[ne.add({Body:O=>{var e;let t=ud(O);return(e=pd(O,t||O.node))!==null&&e!==void 0?e:O.continue()},IfStatement:O=>/^\s*(else:|elif )/.test(O.textAfter)?O.baseIndent:O.continue(),"ForStatement WhileStatement":O=>/^\s*else:/.test(O.textAfter)?O.baseIndent:O.continue(),TryStatement:O=>/^\s*(except |finally:|else:)/.test(O.textAfter)?O.baseIndent:O.continue(),"TupleExpression ComprehensionExpression ParamList ArgList ParenthesizedExpression":_e({closing:")"}),"DictionaryExpression DictionaryComprehensionExpression SetExpression SetComprehensionExpression":_e({closing:"}"}),"ArrayExpression ArrayComprehensionExpression":_e({closing:"]"}),"String FormatString":()=>null,Script:O=>{var e;let t=ud(O);return(e=t&&pd(O,t))!==null&&e!==void 0?e:O.continue()}}),J.add({"ArrayExpression DictionaryExpression SetExpression TupleExpression":me,Body:(O,e)=>({from:O.from+1,to:O.to-(O.to==e.doc.length?0:1)})})]}),languageData:{closeBrackets:{brackets:["(","[","{","'",'"',"'''",'"""'],stringPrefixes:["f","fr","rf","r","u","b","br","rb","F","FR","RF","R","U","B","BR","RB"]},commentTokens:{line:"#"},indentOnInput:/^\s*([\}\]\)]|else:|elif |except |finally:)$/}});function Sd(){return new F(Ql,[Ql.data.of({autocomplete:Ly}),Ql.data.of({autocomplete:Iy})])}var rs=class O{static create(e,t,i,r,n){let s=r+(r<<8)+e+(t<<4)|0;return new O(e,t,i,s,n,[],[])}constructor(e,t,i,r,n,s,a){this.type=e,this.value=t,this.from=i,this.hash=r,this.end=n,this.children=s,this.positions=a,this.hashProp=[[_.contextHash,r]]}addChild(e,t){e.prop(_.contextHash)!=this.hash&&(e=new M(e.type,e.children,e.positions,e.length,this.hashProp)),this.children.push(e),this.positions.push(t)}toTree(e,t=this.end){let i=this.children.length-1;return i>=0&&(t=Math.max(t,this.positions[i]+this.children[i].length+this.from)),new M(e.types[this.type],this.children,this.positions,t-this.from).balance({makeTree:(r,n,s)=>new M(ce.none,r,n,s,this.hashProp)})}},y;(function(O){O[O.Document=1]="Document",O[O.CodeBlock=2]="CodeBlock",O[O.FencedCode=3]="FencedCode",O[O.Blockquote=4]="Blockquote",O[O.HorizontalRule=5]="HorizontalRule",O[O.BulletList=6]="BulletList",O[O.OrderedList=7]="OrderedList",O[O.ListItem=8]="ListItem",O[O.ATXHeading1=9]="ATXHeading1",O[O.ATXHeading2=10]="ATXHeading2",O[O.ATXHeading3=11]="ATXHeading3",O[O.ATXHeading4=12]="ATXHeading4",O[O.ATXHeading5=13]="ATXHeading5",O[O.ATXHeading6=14]="ATXHeading6",O[O.SetextHeading1=15]="SetextHeading1",O[O.SetextHeading2=16]="SetextHeading2",O[O.HTMLBlock=17]="HTMLBlock",O[O.LinkReference=18]="LinkReference",O[O.Paragraph=19]="Paragraph",O[O.CommentBlock=20]="CommentBlock",O[O.ProcessingInstructionBlock=21]="ProcessingInstructionBlock",O[O.Escape=22]="Escape",O[O.Entity=23]="Entity",O[O.HardBreak=24]="HardBreak",O[O.Emphasis=25]="Emphasis",O[O.StrongEmphasis=26]="StrongEmphasis",O[O.Link=27]="Link",O[O.Image=28]="Image",O[O.InlineCode=29]="InlineCode",O[O.HTMLTag=30]="HTMLTag",O[O.Comment=31]="Comment",O[O.ProcessingInstruction=32]="ProcessingInstruction",O[O.Autolink=33]="Autolink",O[O.HeaderMark=34]="HeaderMark",O[O.QuoteMark=35]="QuoteMark",O[O.ListMark=36]="ListMark",O[O.LinkMark=37]="LinkMark",O[O.EmphasisMark=38]="EmphasisMark",O[O.CodeMark=39]="CodeMark",O[O.CodeText=40]="CodeText",O[O.CodeInfo=41]="CodeInfo",O[O.LinkTitle=42]="LinkTitle",O[O.LinkLabel=43]="LinkLabel",O[O.URL=44]="URL"})(y||(y={}));var dl=class{constructor(e,t){this.start=e,this.content=t,this.marks=[],this.parsers=[]}},ul=class{constructor(){this.text="",this.baseIndent=0,this.basePos=0,this.depth=0,this.markers=[],this.pos=0,this.indent=0,this.next=-1}forward(){this.basePos>this.pos&&this.forwardInner()}forwardInner(){let e=this.skipSpace(this.basePos);this.indent=this.countIndent(e,this.pos,this.indent),this.pos=e,this.next=e==this.text.length?-1:this.text.charCodeAt(e)}skipSpace(e){return fr(this.text,e)}reset(e){for(this.text=e,this.baseIndent=this.basePos=this.pos=this.indent=0,this.forwardInner(),this.depth=1;this.markers.len
Line truncated
|
||||
`+t.scrub(),n=this.advance(r);return n>-1&&n<r.length?this.complete(e,i,n):!1}finish(e,t){return(this.stage==2||this.stage==3)&&fr(t.content,this.pos)==t.content.length?this.complete(e,t,t.content.length):!1}complete(e,t,i){return e.addLeafElement(t,L(y.LinkReference,this.start,this.start+i,this.elts)),!0}nextStage(e){return e?(this.pos=e.to-this.start,this.elts.push(e),this.stage++,!0):(e===!1&&(this.stage=-1),!1)}advance(e){for(;;){if(this.stage==-1)return-1;if(this.stage==0){if(!this.nextStage(Nd(e,this.pos,this.start,!0)))return-1;if(e.charCodeAt(this.pos)!=58)return this.stage=-1;this.elts.push(L(y.LinkMark,this.pos+this.start,this.pos+this.start+1)),this.pos++}else if(this.stage==1){if(!this.nextStage(Id(e,fr(e,this.pos),this.start)))return-1}else if(this.stage==2){let t=fr(e,this.pos),i=0;if(t>this.pos){let r=Bd(e,t,this.start);if(r){let n=$l(e,r.to-this.start);n>0&&(this.nextStage(r),i=n)}}return i||(i=$l(e,this.pos)),i>0&&i<e.length?i:-1}else return $l(e,this.pos)}}};function $l(O,e){for(;e<O.length;e++){let t=O.charCodeAt(e);if(t==10)break;if(!rt(t))return-1}return e}var Pl=class{nextLine(e,t,i){let r=t.depth<e.stack.length?-1:Ud(t),n=t.next;if(r<0)return!1;let s=L(y.HeaderMark,e.lineStart+t.pos,e.lineStart+r);return e.nextLine(),e.addLeafElement(i,L(n==61?y.SetextHeading1:y.SetextHeading2,i.start,e.prevLineEnd(),[...e.parser.parseInline(i.content,i.start),s])),!0}finish(){return!1}},Ed={LinkReference(O,e){return e.content.charCodeAt(0)==91?new gl(e):null},SetextHeading(){return new Pl}},By=[(O,e)=>Wd(e)>=0,(O,e)=>zd(e)>=0,(O,e)=>Vd(e)>=0,(O,e)=>xl(e,O,!0)>=0,(O,e)=>kl(e,O,!0)>=0,(O,e)=>bl(e,O,!0)>=0,(O,e)=>Cd(e,O,!0)>=0],Ny={text:"",end:0},Sl=class{constructor(e,t,i,r){this.parser=e,this.input=t,this.ranges=r,this.line=new ul,this.atEnd=!1,this.reusePlaceholders=new Map,this.stoppedAt=null,this.rangeI=0,this.to=r[r.length-1].to,this.lineStart=this.absoluteLineStart=this.absoluteLineEnd=r[0].from,this.block=rs.create(y.Document,0,this.lineStart,0,0),this.stack=[this.block],this.fragments=i.length?new yl(i,t):null,this.readLine()}get parsedPos(){return this.absoluteLineStart}advance(){if(this.stoppedAt!=null&&this.absoluteLineStart>this.stoppedAt)return this.finish();let{line:e}=this;for(;;){for(let i=0;;){let r=e.depth<this.stack.length?this.stack[this.stack.length-1]:null;for(;i<e.markers.length&&(!r||e.markers[i].from<r.end);){let n=e.markers[i++];this.addNode(n.type,n.from,n.to)}if(!r)break;this.finishContext()}if(e.pos<e.text.length)break;if(!this.nextLine())return this.finish()}if(this.fragments&&this.reuseFragment(e.basePos))return null;e:for(;;){for(let i of this.parser.blockParsers)if(i){let r=i(this,e);if(r!=!1){if(r==!0)return null;e.forward();continue e}}break}let t=new dl(this.lineStart+e.pos,e.text.slice(e.pos));for(let i of this.parser.leafBlockParsers)if(i){let r=i(this,t);r&&t.parsers.push(r)}e:for(;this.nextLine()&&e.pos!=e.text.length;){if(e.indent<e.baseIndent+4){for(let i of this.parser.endLeafBlock)if(i(this,e,t))break e}for(let i of t.parsers)if(i.nextLine(this,e,t))return null;t.content+=`
|
||||
`+e.scrub();for(let i of e.markers)t.marks.push(i)}return this.finishLeaf(t),null}stopAt(e){if(this.stoppedAt!=null&&this.stoppedAt<e)throw new RangeError("Can't move stoppedAt forward");this.stoppedAt=e}reuseFragment(e){if(!this.fragments.moveTo(this.absoluteLineStart+e,this.absoluteLineStart)||!this.fragments.matches(this.block.hash))return!1;let t=this.fragments.takeNodes(this);return t?(this.absoluteLineStart+=t,this.lineStart=Fd(this.absoluteLineStart,this.ranges),this.moveRangeI(),this.absoluteLineStart<this.to?(this.lineStart++,this.absoluteLineStart++,this.readLine()):(this.atEnd=!0,this.readLine()),!0):!1}get depth(){return this.stack.length}parentType(e=this.depth-1){return this.parser.nodeSet.types[this.stack[e].type]}nextLine(){return this.lineStart+=this.line.text.length,this.absoluteLineEnd>=this.to?(this.absoluteLineStart=this.absoluteLineEnd,this.atEnd=!0,this.readLine(),!1):(this.lineStart++,this.absoluteLineStart=this.absoluteLineEnd+1,this.moveRangeI(),this.readLine(),!0)}peekLine(){return this.scanLine(this.absoluteLineEnd+1).text}moveRangeI(){for(;this.rangeI<this.ranges.length-1&&this.absoluteLineStart>=this.ranges[this.rangeI].to;)this.rangeI++,this.absoluteLineStart=Math.max(this.absoluteLineStart,this.ranges[this.rangeI].from)}scanLine(e){let t=Ny;if(t.end=e,e>=this.to)t.text="";else if(t.text=this.lineChunkAt(e),t.end+=t.text.length,this.ranges.length>1){let i=this.absoluteLineStart,r=this.rangeI;for(;this.ranges[r].to<t.end;){r++;let n=this.ranges[r].from,s=this.lineChunkAt(n);t.end=n+s.length,t.text=t.text.slice(0,this.ranges[r-1].to-i)+s,i=t.end-t.text.length}}return t}readLine(){let{line:e}=this,{text:t,end:i}=this.scanLine(this.absoluteLineStart);for(this.absoluteLineEnd=i,e.reset(t);e.depth<this.stack.length;e.depth++){let r=this.stack[e.depth],n=this.parser.skipContextMarkup[r.type];if(!n)throw new Error("Unhandled block context "+y[r.type]);let s=this.line.markers.length;if(!n(r,this,e)){this.line.markers.length>s&&(r.end=this.line.markers[this.line.markers.length-1].to),e.forward();break}e.forward()}}lineChunkAt(e){let t=this.input.chunk(e),i;if(this.input.lineChunks)i=t==`
|
||||
`?"":t;else{let r=t.indexOf(`
|
||||
`);i=r<0?t:t.slice(0,r)}return e+i.length>this.to?i.slice(0,this.to-e):i}prevLineEnd(){return this.atEnd?this.lineStart:this.lineStart-1}startContext(e,t,i=0){this.block=rs.create(e,i,this.lineStart+t,this.block.hash,this.lineStart+this.line.text.length),this.stack.push(this.block)}startComposite(e,t,i=0){this.startContext(this.parser.getNodeType(e),t,i)}addNode(e,t,i){typeof e=="number"&&(e=new M(this.parser.nodeSet.types[e],si,si,(i??this.prevLineEnd())-t)),this.block.addChild(e,t-this.block.from)}addElement(e){this.block.addChild(e.toTree(this.parser.nodeSet),e.from-this.block.from)}addLeafElement(e,t){this.addNode(this.buffer.writeElements(Tl(t.children,e.marks),-t.from).finish(t.type,t.to-t.from),t.from)}finishContext(){let e=this.stack.pop(),t=this.stack[this.stack.length-1];t.addChild(e.toTree(this.parser.nodeSet),e.from-t.from),this.block=t}finish(){for(;this.stack.length>1;)this.finishContext();return this.addGaps(this.block.toTree(this.parser.nodeSet,this.lineStart))}addGaps(e){return this.ranges.length>1?Ad(this.ranges,0,e.topNode,this.ranges[0].from,this.reusePlaceholders):e}finishLeaf(e){for(let i of e.parsers)if(i.finish(this,e))return;let t=Tl(this.parser.parseInline(e.content,e.start),e.marks);this.addNode(this.buffer.writeElements(t,-e.start).finish(y.Paragraph,e.content.length),e.start)}elt(e,t,i,r){return typeof e=="string"?L(this.parser.getNodeType(e),t,i,r):new ss(e,t)}get buffer(){return new ns(this.parser.nodeSet)}};function Ad(O,e,t,i,r){let n=O[e].to,s=[],a=[],o=t.from+i;function l(c,h){for(;h?c>=n:c>n;){let $=O[e+1].from-n;i+=$,c+=$,e++,n=O[e].to}}for(let c=t.firstChild;c;c=c.nextSibling){l(c.from+i,!0);let h=c.from+i,$,f=r.get(c.tree);f?$=f:c.to+i>n?($=Ad(O,e,c,i,r),l(c.to+i,!1)):$=c.toTree(),s.push($),a.push(h-o)}return l(t.to+i,!1),new M(t.type,s,a,t.to+i-o,t.tree?t.tree.propValues:void 0)}var ur=class O extends Ft{constructor(e,t,i,r,n,s,a,o,l){super(),this.nodeSet=e,this.blockParsers=t,this.leafBlockParsers=i,this.blockNames=r,this.endLeafBlock=n,this.skipContextMarkup=s,this.inlineParsers=a,this.inlineNames=o,this.wrappers=l,this.nodeTypes=Object.create(null);for(let c of e.types)this.nodeTypes[c.name]=c.id}createParse(e,t,i){let r=new Sl(this,e,t,i);for(let n of this.wrappers)r=n(r,e,t,i);return r}configure(e){let t=Xl(e);if(!t)return this;let{nodeSet:i,skipContextMarkup:r}=this,n=this.blockParsers.slice(),s=this.leafBlockParsers.slice(),a=this.blockNames.slice(),o=this.inlineParsers.slice(),l=this.inlineNames.slice(),c=this.endLeafBlock.slice(),h=this.wrappers;if($r(t.defineNodes)){r=Object.assign({},r);let $=i.types.slice(),f;for(let d of t.defineNodes){let{name:u,block:p,composite:m,style:g}=typeof d=="string"?{name:d}:d;if($.some(S=>S.name==u))continue;m&&(r[$.length]=(S,k,b)=>m(k,b,S.value));let X=$.length,T=m?["Block","BlockContext"]:p?X>=y.ATXHeading1&&X<=y.SetextHeading2?["Block","LeafBlock","Heading"]:["Block","LeafBlock"]:void 0;$.push(ce.define({id:X,name:u,props:T&&[[_.group,T]]})),g&&(f||(f={}),Array.isArray(g)||g instanceof De?f[u]=g:Object.assign(f,g))}i=new Bt($),f&&(i=i.extend(I(f)))}if($r(t.props)&&(i=i.extend(...t.props)),$r(t.remove))for(let $ of t.remove){let f=this.blockNames.indexOf($),d=this.inlineNames.indexOf($);f>-1&&(n[f]=s[f]=void 0),d>-1&&(o[d]=void 0)}if($r(t.parseBlock))for(let $ of t.parseBlock){let f=a.indexOf($.name);if(f>-1)n[f]=$.parse,s[f]=$.leaf;else{let d=$.before?is(a,$.before):$.after?is(a,$.after)+1:a.length-1;n.splice(d,0,$.parse),s.splice(d,0,$.leaf),a.splice(d,0,$.name)}$.endLeaf&&c.push($.endLeaf)}if($r(t.parseInline))for(let $ of t.parseInline){let f=l.indexOf($.name);if(f>-1)o[f]=$.parse;else{let d=$.before?is(l,$.before):$.after?is(l,$.after)+1:l.length-1;o.splice(d,0,$.parse),l.splice(d,0,$.name)}}return t.wrap&&(h=h.concat(t.wrap)),new O(i,n,s,a,c,r,o,l,h)}getNodeType(e){let t=this.nodeTypes[e];if(t==null)throw new RangeError(`Unknown node type '${e}'`);return t}parseInline(e,t){let i=new mr(this,e,t);e:for(let r=t;r<i.end;){let n=i.char(r);for(let s of this.inlineParsers)if(s){let a=s(i,n,r);if(a>=0){r=a;continue e}}r++}return i.resolveMarkers(0)}};function $r(O){return O!=null&&O.length>0}function Xl(O){if(!Array.isArray(O))return O;if(O.length==0)return null;let e=Xl(O[0]);if(O.length==1)return e;let t=Xl(O.slice(1));if(!t||!e)return e||t;let i=(s,a)=>(s||si).concat(a||si),r=e.wrap,n=t.wrap;return{props:i(e.props,t.props),defineNodes:i(e.defineNodes,t.defineNodes),parseBlock:i(e.parseBlock,t.parseBlock),parseInline:i(e.parseInline,t.parseInline),remove:i(e.remove,t.remove),wrap:r?n?(s,a,o,l)=>r(n(s,a,o,l),a,o,l):r:n}}function is(O,e){let t=O.indexOf(e);if(t<0)throw new RangeError(`Position specified relative to unknown parser ${e}`);return t}var Ld=[ce.none];for(let O=1,e;e=y[O];O++)Ld[O]=ce.define({id:O,name:e,props:O>=y.Escape?[]:[[_.group,O in Rd?["Block","BlockContext"]:["Block","LeafBlock"]]],top:e=="Document"});var si=[],ns=class{constructor(e){this.nodeSet=e,this.content=[],this.nodes=[]}write(e,t,i,r=0){return t
Line truncated
|
||||
`;)n--;this.fragmentEnd=n?n-1:0}let i=this.cursor;i||(i=this.cursor=this.fragment.tree.cursor(),i.firstChild());let r=e+this.fragment.offset;for(;i.to<=r;)if(!i.parent())return!1;for(;;){if(i.from>=r)return this.fragment.from<=t;if(!i.childAfter(r))return!1}}matches(e){let t=this.cursor.tree;return t&&t.prop(_.contextHash)==e}takeNodes(e){let t=this.cursor,i=this.fragment.offset,r=this.fragmentEnd-(this.fragment.openEnd?1:0),n=e.absoluteLineStart,s=n,a=e.block.children.length,o=s,l=a;for(;;){if(t.to-i>r){if(t.type.isAnonymous&&t.firstChild())continue;break}let c=Fd(t.from-i,e.ranges);if(t.to-i<=e.ranges[e.rangeI].to)e.addNode(t.tree,c);else{let h=new M(e.parser.nodeSet.types[y.Paragraph],[],[],0,e.block.hashProp);e.reusePlaceholders.set(h,t.tree),e.addNode(h,c)}if(t.type.is("Block")&&(Hy.indexOf(t.type.id)<0?(s=t.to-i,a=e.block.children.length):(s=o,a=l),o=t.to-i,l=e.block.children.length),!t.nextSibling())break}for(;e.block.children.length>a;)e.block.children.pop(),e.block.positions.pop();return s-n}};function Fd(O,e){let t=O;for(let i=1;i<e.length;i++){let r=e[i-1].to,n=e[i].from;r<O&&(t-=n-r)}return t}var Ky=I({"Blockquote/...":Q.quote,HorizontalRule:Q.contentSeparator,"ATXHeading1/... SetextHeading1/...":Q.heading1,"ATXHeading2/... SetextHeading2/...":Q.heading2,"ATXHeading3/...":Q.heading3,"ATXHeading4/...":Q.heading4,"ATXHeading5/...":Q.heading5,"ATXHeading6/...":Q.heading6,"Comment CommentBlock":Q.comment,Escape:Q.escape,Entity:Q.character,"Emphasis/...":Q.emphasis,"StrongEmphasis/...":Q.strong,"Link/... Image/...":Q.link,"OrderedList/... BulletList/...":Q.list,"BlockQuote/...":Q.quote,"InlineCode CodeText":Q.monospace,"URL Autolink":Q.url,"HeaderMark HardBreak QuoteMark ListMark LinkMark EmphasisMark CodeMark":Q.processingInstruction,"CodeInfo LinkLabel":Q.labelName,LinkTitle:Q.string,Paragraph:Q.content}),Hd=new ur(new Bt(Ld).extend(Ky),Object.keys(Os).map(O=>Os[O]),Object.keys(Os).map(O=>Ed[O]),Object.keys(Os),By,Rd,Object.keys(fl).map(O=>fl[O]),Object.keys(fl),[]);function Jy(O,e,t){let i=[];for(let r=O.firstChild,n=e;;r=r.nextSibling){let s=r?r.from:t;if(s>n&&i.push({from:n,to:s}),!r)break;n=r.to}return i}function Kd(O){let{codeParser:e,htmlParser:t}=O;return{wrap:gO((r,n)=>{let s=r.type.id;if(e&&(s==y.CodeBlock||s==y.FencedCode)){let a="";if(s==y.FencedCode){let l=r.node.getChild(y.CodeInfo);l&&(a=n.read(l.from,l.to))}let o=e(a);if(o)return{parser:o,overlay:l=>l.type.id==y.CodeText,bracketed:s==y.FencedCode}}else if(t&&(s==y.HTMLBlock||s==y.HTMLTag||s==y.CommentBlock))return{parser:t,overlay:Jy(r.node,r.from,r.to)};return null})}}var ew={resolve:"Strikethrough",mark:"StrikethroughMark"},tw={defineNodes:[{name:"Strikethrough",style:{"Strikethrough/...":Q.strikethrough}},{name:"StrikethroughMark",style:Q.processingInstruction}],parseInline:[{name:"Strikethrough",parse(O,e,t){if(e!=126||O.char(t+1)!=126||O.char(t+2)==126)return-1;let i=O.slice(t-1,t),r=O.slice(t+2,t+3),n=/\s|^$/.test(i),s=/\s|^$/.test(r),a=pr.test(i),o=pr.test(r);return O.addDelimiter(ew,t,t+2,!s&&(!o||n||a),!n&&(!a||s||o))},after:"Emphasis"}]};function dr(O,e,t=0,i,r=0){let n=0,s=!0,a=-1,o=-1,l=!1,c=()=>{i.push(O.elt("TableCell",r+a,r+o,O.parser.parseInline(e.slice(a,o),r+a)))};for(let h=t;h<e.length;h++){let $=e.charCodeAt(h);$==124&&!l?((!s||a>-1)&&n++,s=!1,i&&(a>-1&&c(),i.push(O.elt("TableDelimiter",h+r,h+r+1))),a=o=-1):(l||$!=32&&$!=9)&&(a<0&&(a=h),o=h+1),l=!l&&$==92}return a>-1&&(n++,i&&c()),n}function bd(O,e){for(let t=e;t<O.length;t++){let i=O.charCodeAt(t);if(i==124)return!0;i==92&&t++}return!1}var Jd=/^\|?(\s*:?-+:?\s*\|)+(\s*:?-+:?\s*)?$/,os=class{constructor(){this.rows=null}nextLine(e,t,i){if(this.rows==null){this.rows=!1;let r;if((t.next==45||t.next==58||t.next==124)&&Jd.test(r=t.text.slice(t.pos))){let n=[];dr(e,i.content,0,n,i.start)==dr(e,r,t.pos)&&(this.rows=[e.elt("TableHeader",i.start,i.start+i.content.length,n),e.elt("TableDelimiter",e.lineStart+t.pos,e.lineStart+t.text.length)])}}else if(this.rows){let r=[];dr(e,t.text,t.pos,r,e.lineStart),this.rows.push(e.elt("TableRow",e.lineStart+t.pos,e.lineStart+t.text.length,r))}return!1}finish(e,t){return this.rows?(e.addLeafElement(t,e.elt("Table",t.start,t.start+t.content.length,this.rows)),!0):!1}},Ow={defineNodes:[{name:"Table",block:!0},{name:"TableHeader",style:{"TableHeader/...":Q.heading}},"TableRow",{name:"TableCell",style:Q.content},{name:"TableDelimiter",style:Q.processingInstruction}],parseBlock:[{name:"Table",leaf(O,e){return bd(e.content,0)?new os:null},endLeaf(O,e,t){if(t.parsers.some(r=>r instanceof os)||!bd(e.text,e.basePos))return!1;let i=O.peekLine();return Jd.test(i)&&dr(O,e.text,e.basePos)==dr(O,i,e.basePos)},before:"SetextHeading"}]},wl=class{nextLine(){return!1}finish(e,t){return e.addLeafElement(t,e.elt("Task",t.start,t.start+t.content.length,[e.elt("TaskMarker",t.start,t.start+3),...e.parser.parseInline(t.content.slice(3),t.start+3)])),!0}},iw={defineNodes:[{name:"Task",block:!0,style:Q.list},{name:"TaskMarker",style:Q.atom}],parseBlock:[{name
Line truncated
|
||||
\${}
|
||||
}`,{label:"select",detail:"statement",type:"keyword"}),W("case ${}:\n${}",{label:"case",type:"keyword"}),W("switch ${} {\n ${}\n}",{label:"switch",detail:"statement",type:"keyword"}),W("switch ${}.(${type}) {\n ${}\n}",{label:"switch",detail:"type statement",type:"keyword"}),W("if ${} {\n ${}\n}",{label:"if",detail:"block",type:"keyword"}),W(`if \${} {
|
||||
\${}
|
||||
} else {
|
||||
\${}
|
||||
}`,{label:"if",detail:"/ else block",type:"keyword"}),W('import ${name} "${module}"\n${}',{label:"import",detail:"declaration",type:"keyword"})],Qp=new Pt,fp=new Set(["SourceFile","Block","FunctionDecl","MethodDecl","FunctionLiteral","ForStatement","SwitchStatement","TypeSwitchStatement","IfStatement"]);function hi(O,e){return(t,i)=>{e:for(let r=t.node.firstChild,n=0,s=null;;){for(;!r;){if(!n)break e;n--,r=s.nextSibling,s=s.parent}e&&r.name==e||r.name=="SpecList"?(n++,s=r,r=r.firstChild):(r.name=="DefName"&&i(r,O),r=r.nextSibling)}return!0}}var q0={FunctionDecl:hi("function"),VarDecl:hi("var","VarSpec"),ConstDecl:hi("constant","ConstSpec"),TypeDecl:hi("type","TypeSpec"),ImportDecl:hi("constant","ImportSpec"),Parameter:hi("var"),__proto__:null};function dp(O,e){let t=Qp.get(e);if(t)return t;let i=[],r=!0;function n(s,a){let o=O.sliceString(s.from,s.to);i.push({label:o,type:a})}return e.cursor(C.IncludeAnonymous).iterate(s=>{if(r)r=!1;else if(s.name){let a=q0[s.name];if(a&&a(s,n)||fp.has(s.name))return!1}else if(s.to-s.from>8192){for(let a of dp(O,s.node))i.push(a);return!1}}),Qp.set(e,i),i}var $p=/^[\w$\xa1-\uffff][\w$\d\xa1-\uffff]*$/,up=["String","LineComment","BlockComment","DefName","LabelName","FieldName",".","?."],W0=O=>{let e=q(O.state).resolveInner(O.pos,-1);if(up.indexOf(e.name)>-1)return null;let t=e.name=="VariableName"||e.to-e.from<20&&$p.test(O.state.sliceDoc(e.from,e.to));if(!t&&!O.explicit)return null;let i=[];for(let r=e;r;r=r.parent)fp.has(r.name)&&(i=i.concat(dp(O.state.doc,r)));return{options:i,from:t?e.from:O.pos,validFor:$p}},Hl=re.define({name:"go",parser:hp.configure({props:[ne.add({IfStatement:oe({except:/^\s*({|else\b)/}),LabeledStatement:KO,"SwitchBlock SelectBlock":O=>{let e=O.textAfter,t=/^\s*\}/.test(e),i=/^\s*(case|default)\b/.test(e);return O.baseIndent+(t||i?0:O.unit)},Block:_e({closing:"}"}),BlockComment:()=>null,Statement:oe({except:/^{/})}),J.add({"Block SwitchBlock SelectBlock LiteralValue InterfaceType StructType SpecList":me,BlockComment(O){return{from:O.from+2,to:O.to-2}}})]}),languageData:{closeBrackets:{brackets:["(","[","{","'",'"',"`"]},commentTokens:{line:"//",block:{open:"/*",close:"*/"}},indentOnInput:/^\s*(?:case\b|default\b|\})$/}}),U0=O=>({label:O,type:"keyword"}),j0="interface struct chan map package go return break continue goto fallthrough else defer range true false nil".split(" ").map(U0);function pp(){let O=V0.concat(j0);return new F(Hl,[Hl.data.of({autocomplete:rO(up,Rt(O))}),Hl.data.of({autocomplete:W0})])}var mp=1,G0=2,C0=3,E0=82,A0=76,L0=117,M0=85,D0=97,I0=122,B0=65,N0=90,F0=95,Kl=48,gp=34,H0=40,Pp=41,K0=32,Sp=62,J0=new V(O=>{if(O.next==A0||O.next==M0?O.advance():O.next==L0&&(O.advance(),O.next==Kl+8&&O.advance()),O.next!=E0||(O.advance(),O.next!=gp))return;O.advance();let e="";for(;O.next!=H0;){if(O.next==K0||O.next<=13||O.next==Pp)return;e+=String.fromCharCode(O.next),O.advance()}for(O.advance();;){if(O.next<0)return O.acceptToken(mp);if(O.next==Pp){let t=!0;for(let i=0;t&&i<e.length;i++)O.peek(i+1)!=e.charCodeAt(i)&&(t=!1);if(t&&O.peek(e.length+1)==gp)return O.acceptToken(mp,2+e.length)}O.advance()}}),ex=new V(O=>{if(O.next==Sp)O.peek(1)==Sp&&O.acceptToken(G0,1);else{let e=!1,t=0;for(;;t++){if(O.next>=B0&&O.next<=N0)e=!0;else{if(O.next>=D0&&O.next<=I0)return;if(O.next!=F0&&!(O.next>=Kl&&O.next<=Kl+9))break}O.advance()}e&&t>1&&O.acceptToken(C0)}},{extend:!0}),tx=I({"typedef struct union enum class typename decltype auto template operator friend noexcept namespace using requires concept import export module __attribute__ __declspec __based":Q.definitionKeyword,"extern MsCallModifier MsPointerModifier extern static register thread_local inline const volatile restrict _Atomic mutable constexpr constinit consteval virtual explicit VirtualSpecifier Access":Q.modifier,"if else switch for while do case default return break continue goto throw try catch":Q.controlKeyword,"co_return co_yield co_await":Q.controlKeyword,"new sizeof delete static_assert":Q.operatorKeyword,"NULL nullptr":Q.null,this:Q.self,"True False":Q.bool,"TypeSize PrimitiveType":Q.standard(Q.typeName),TypeIdentifier:Q.typeName,FieldIdentifier:Q.propertyName,"CallExpression/FieldExpression/FieldIdentifier":Q.function(Q.propertyName),"ModuleName/Identifier":Q.namespace,PartitionName:Q.labelName,StatementIdentifier:Q.labelName,"Identifier DestructorName":Q.variableName,"CallExpression/Identifier":Q.function(Q.variableName),"CallExpression/ScopedIdentifier/Identifier":Q.function(Q.variableName),"FunctionDeclarator/Identifier FunctionDeclarator/DestructorName":Q.function(Q.definition(Q.variableName)),NamespaceIdentifier:Q.namespace,OperatorName:Q.operator,ArithOp:Q.arithmeticOperator,LogicOp:Q.logicOperator,BitOp:Q.bitwiseOperator,CompareOp:Q.compareOperator,AssignOp:Q.definitionOperator,UpdateOp:Q.updateOperator,LineComment:Q.lineComment,BlockComment:Q.blockComment,Number:Q.number,String:Q.string,"RawString SystemLibString":Q.special(Q.string),CharLiteral:Q.character,EscapeSequence:Q.escape,"
Line truncated
|
||||
`;function Ip(O,e,t){let i=Object.create(null);i.true=i.false=Ux,i.null=i.unknown=jx;for(let r of O.split(" "))r&&(i[r]=Mp);for(let r of e.split(" "))r&&(i[r]=Dp);for(let r of(t||"").split(" "))r&&(i[r]=Jx);return i}var RO="array binary bit boolean char character clob date decimal double float int integer interval large national nchar nclob numeric object precision real smallint time timestamp varchar varying ",zO="absolute action add after all allocate alter and any are as asc assertion at authorization before begin between both breadth by call cascade cascaded case cast catalog check close collate collation column commit condition connect connection constraint constraints constructor continue corresponding count create cross cube current current_date current_default_transform_group current_transform_group_for_type current_path current_role current_time current_timestamp current_user cursor cycle data day deallocate declare default deferrable deferred delete depth deref desc describe descriptor deterministic diagnostics disconnect distinct do domain drop dynamic each else elseif end end-exec equals escape except exception exec execute exists exit external fetch first for foreign found from free full function general get global go goto grant group grouping handle having hold hour identity if immediate in indicator initially inner inout input insert intersect into is isolation join key language last lateral leading leave left level like limit local localtime localtimestamp locator loop map match method minute modifies module month names natural nesting new next no none not of old on only open option or order ordinality out outer output overlaps pad parameter partial path prepare preserve primary prior privileges procedure public read reads recursive redo ref references referencing relative release repeat resignal restrict result return returns revoke right role rollback rollup routine row rows savepoint schema scroll search second section select session session_user set sets signal similar size some space specific specifictype sql sqlexception sqlstate sqlwarning start state static system_user table temporary then timezone_hour timezone_minute to trailing transaction translation treat trigger under undo union unique unnest until update usage user using value values view when whenever where while with without work write year zone ",cc={backslashEscapes:!1,hashComments:!1,spaceAfterDashes:!1,slashComments:!1,doubleQuotedStrings:!1,doubleDollarQuotedStrings:!1,unquotedBitLiterals:!1,treatBitsAsBytes:!1,charSetCasts:!1,plsqlQuotingMechanism:!1,operatorChars:"*+-%<>!=&|~^/",specialVar:"?",identifierQuotes:'"',words:Ip(zO,RO)};function rk(O,e,t,i){let r={};for(let n in cc)r[n]=(O.hasOwnProperty(n)?O:cc)[n];return e&&(r.words=Ip(e,t||"",i)),r}function Bp(O){return new V(e=>{var t;let{next:i}=e;if(e.advance(),ZO(i,ac)){for(;ZO(e.next,ac);)e.advance();e.acceptToken(qx)}else if(i==36&&O.doubleDollarQuotedStrings){let r=lc(e,"");e.next==36&&(e.advance(),tk(e,r),e.acceptToken(yr))}else if(i==39||i==34&&O.doubleQuotedStrings)_O(e,i,O.backslashEscapes),e.acceptToken(yr);else if(i==35&&O.hashComments||i==47&&e.next==47&&O.slashComments)Cp(e),e.acceptToken(qp);else if(i==45&&e.next==45&&(!O.spaceAfterDashes||e.peek(1)==32))Cp(e),e.acceptToken(qp);else if(i==47&&e.next==42){e.advance();for(let r=1;;){let n=e.next;if(e.next<0)break;if(e.advance(),n==42&&e.next==47){if(r--,e.advance(),!r)break}else n==47&&e.next==42&&(r++,e.advance())}e.acceptToken(Wx)}else if((i==101||i==69)&&e.next==39)e.advance(),_O(e,39,!0);else if((i==110||i==78)&&e.next==39&&O.charSetCasts)e.advance(),_O(e,39,O.backslashEscapes),e.acceptToken(yr);else if(i==95&&O.charSetCasts)for(let r=0;;r++){if(e.next==39&&r>1){e.advance(),_O(e,39,O.backslashEscapes),e.acceptToken(yr);break}if(!oc(e.next))break;e.advance()}else if(O.plsqlQuotingMechanism&&(i==113||i==81)&&e.next==39&&e.peek(1)>0&&!ZO(e.peek(1),ac)){let r=e.peek(1);e.advance(2),Ok(e,r),e.acceptToken(yr)}else if(i==40)e.acceptToken(Gx);else if(i==41)e.acceptToken(Cx);else if(i==123)e.acceptToken(Ex);else if(i==125)e.acceptToken(Ax);else if(i==91)e.acceptToken(Lx);else if(i==93)e.acceptToken(Mx);else if(i==59)e.acceptToken(Dx);else if(O.unquotedBitLiterals&&i==48&&e.next==98)e.advance(),jp(e),e.acceptToken(Up);else if((i==98||i==66)&&(e.next==39||e.next==34)){let r=e.next;e.advance(),O.treatBitsAsBytes?(_O(e,r,O.backslashEscapes),e.acceptToken(Kx)):(jp(e,r),e.acceptToken(Up))}else if(i==48&&(e.next==120||e.next==88)||(i==120||i==88)&&e.next==39){let r=e.next==39;for(e.advance();ek(e.next);)e.advance();r&&e.next==39&&e.advance(),e.acceptToken(sc)}else if(i==46&&e.next>=48&&e.next<=57)Gp(e,!0),e.acceptToken(sc);else if(i==46)e.acceptToken(Ix);else if(i>=48&&i<=57)Gp(e,!1),e.acceptToken(sc);else if(ZO(i,O.operatorChars)){for(;ZO(e.next,O.operatorChars);)e.advance();e.acceptToken(Bx)}else if(ZO(i,O.specialVar))e.next==i&&e.advance(),ik(e),e.acceptToken(Fx);else if(ZO(i,O.identifierQuotes))_O(e,i,!1),e.accept
Line truncated
|
||||
@@ -0,0 +1,19 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>Reasonix</title>
|
||||
<meta name="reasonix-token" content="__REASONIX_TOKEN__" />
|
||||
<meta name="reasonix-mode" content="__REASONIX_MODE__" />
|
||||
<link rel="stylesheet" href="/assets/app.css?token=__REASONIX_TOKEN__" />
|
||||
<link rel="stylesheet" href="https://esm.sh/[email protected]/dist/uPlot.min.css" />
|
||||
<link rel="stylesheet" href="https://esm.sh/[email protected]/styles/github-dark.min.css" />
|
||||
</head>
|
||||
<body>
|
||||
<div id="root">
|
||||
<div class="boot">loading…</div>
|
||||
</div>
|
||||
<script type="module" src="/assets/app.js?token=__REASONIX_TOKEN__"></script>
|
||||
</body>
|
||||
</html>
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
Whitespace-only changes.
+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,12 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
|
||||
<defs>
|
||||
<linearGradient id="g" x1="0%" y1="0%" x2="100%" y2="100%">
|
||||
<stop offset="0%" stop-color="#5eead4"/>
|
||||
<stop offset="50%" stop-color="#93c5fd"/>
|
||||
<stop offset="100%" stop-color="#c4b5fd"/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<rect width="64" height="64" rx="12" fill="#0a0d14"/>
|
||||
<path d="M 32,10 L 54,32 L 32,54 L 10,32 Z" fill="none" stroke="url(#g)" stroke-width="3" stroke-linejoin="round"/>
|
||||
<path d="M 32,21 L 43,32 L 32,43 L 21,32 Z" fill="url(#g)" opacity="0.9"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 568 B |
+462
@@ -0,0 +1,462 @@
|
||||
// Reasonix landing — i18n auto-switch (en / zh).
|
||||
// Detection precedence: ?lang=xx → localStorage → navigator.language → "en".
|
||||
// Falls back gracefully when localStorage is unavailable (private mode, etc).
|
||||
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
const STORAGE_KEY = "reasonix.lang";
|
||||
const DEFAULT_LANG = "en";
|
||||
const SUPPORTED = ["en", "zh"];
|
||||
|
||||
const translations = {
|
||||
en: {
|
||||
"nav.features": "Features",
|
||||
"nav.quickstart": "Quick start",
|
||||
"nav.benchmarks": "Benchmarks",
|
||||
"nav.github": "GitHub",
|
||||
|
||||
"hero.badge": "v{version} · DeepSeek V4 · cache-first",
|
||||
"hero.title.line1": "DeepSeek-native",
|
||||
"hero.title.line2": "AI coding agent in your terminal",
|
||||
"hero.sub":
|
||||
"Cache-first agent loop for DeepSeek V4 (flash + pro). Edits files as reviewable SEARCH/REPLACE blocks. Ink TUI. MCP first-class. No LangChain.",
|
||||
"hero.copy": "Copy",
|
||||
"hero.copy.done": "Copied",
|
||||
"hero.cta.start": "Get started →",
|
||||
"hero.cta.star": "Star on GitHub",
|
||||
"hero.stat.cache": "prefix cache hit rate",
|
||||
"hero.stat.cost": "cheaper vs Claude Sonnet 4.6",
|
||||
"hero.stat.pass": "τ-bench-lite pass rate",
|
||||
|
||||
"term.user":
|
||||
"users.ts findByEmail is case-sensitive — login fails for users with uppercase emails",
|
||||
"term.found":
|
||||
"▸ Found it. findByEmail uses === directly. Switch to lowercase normalization.",
|
||||
"term.pending": "▸ 1 pending edit · /apply to write · /discard to drop",
|
||||
|
||||
"why.title": "Why Reasonix",
|
||||
"why.sub":
|
||||
"Every abstraction earns its weight against a DeepSeek-specific property — dirt-cheap tokens, R1 traces, automatic prefix caching, JSON mode. Generic wrappers leave these on the table.",
|
||||
"why.cache.title": "Cache-first loop",
|
||||
"why.cache.body":
|
||||
"Append-only conversation log keeps the prompt prefix byte-stable across turns, so DeepSeek's automatic cache hits 85–95% — not 40%.",
|
||||
"why.cost.title": "Cost is a pillar",
|
||||
"why.cost.body":
|
||||
"Flash-first defaults, turn-end auto-compaction, model self-escalation when (and only when) needed. Per-turn cost badge in the TUI.",
|
||||
"why.tui.title": "Ink TUI, no web",
|
||||
"why.tui.body":
|
||||
"Lives in your terminal. Streaming preview, slash commands, plan picker, edit-confirm modal. Plain mode for stubborn Windows shells.",
|
||||
"why.mcp.title": "MCP first-class",
|
||||
"why.mcp.body":
|
||||
"Stdio + HTTP+SSE transports. Live progress notifications. Same cache-safety + repair plumbing as native tools.",
|
||||
"why.safe.title": "Reviewable edits",
|
||||
"why.safe.body":
|
||||
"Edits arrive as SEARCH/REPLACE blocks; nothing hits disk until /apply. Per-file diff confirm modal, undo history, sandboxed paths.",
|
||||
"why.ctx.title": "1M-token aware",
|
||||
"why.ctx.body":
|
||||
"Context gauge with proactive compaction, oversized tool-result repair, forced-summary fallback near the window edge.",
|
||||
|
||||
"qs.title": "Quick start (60 seconds)",
|
||||
"qs.step1.title": "Get a DeepSeek API key",
|
||||
"qs.step1.body":
|
||||
'Free credit on signup at <a href="https://platform.deepseek.com/api_keys" target="_blank" rel="noopener">platform.deepseek.com</a>.',
|
||||
"qs.step2.title": "Point it at a project",
|
||||
"qs.step2.body": "No install needed.",
|
||||
"qs.step2.note":
|
||||
"First run walks you through a 30-second wizard (paste API key → pick preset → pick MCP servers).",
|
||||
"qs.step3.title": "Ask it to edit",
|
||||
"qs.step3.body":
|
||||
"The model proposes edits as SEARCH/REPLACE blocks — nothing hits disk until you <code>/apply</code>.",
|
||||
"qs.req":
|
||||
"Requires Node ≥ 20.10. macOS, Linux, Windows (PowerShell · Git Bash · Windows Terminal). Press <kbd>Esc</kbd> anytime to abort; <code>/help</code> for the full command list.",
|
||||
|
||||
"feat.title": "In the box",
|
||||
"feat.code.title": "Pair programmer mode",
|
||||
"feat.code.body":
|
||||
"<code>read_file</code> · <code>write_file</code> · <code>edit_file</code> · <code>search_files</code> · <code>directory_tree</code> · <code>run_command</code> with read-only allowlist. Sandboxed to the launch root — no path escapes. Plan mode and per-edit review modal.",
|
||||
"feat.memory.title": "Two-layer memory",
|
||||
"feat.memory.body":
|
||||
"Committable <code>REASONIX.md</code> for team conventions plus a private per-user <code>~/.reasonix/memory/</code> with global and per-project scopes. The model can write to it via the <code>remember</code> tool.",
|
||||
"feat.skills.title": "User-authored prompt packs",
|
||||
"feat.skills.body":
|
||||
"Drop <code>SKILL.md</code> files anywhere. Names + descriptions are pinned in the prefix; the model picks them autonomously, or you trigger with <code>/skill name</code>.",
|
||||
"feat.hooks.title": "Lifecycle hooks",
|
||||
"feat.hooks.body":
|
||||
"Shell commands fire at <code>PreToolUse</code> · <code>PostToolUse</code> · <code>UserPromptSubmit</code> · <code>Stop</code>. Exit code drives pass / block / warn.",
|
||||
"feat.mcp.title": "Bring your own tools",
|
||||
"feat.mcp.body":
|
||||
'Wizard catalog, or <code>--mcp "name=cmd"</code> to attach stdio / HTTP+SSE servers on the fly. Live progress bars on long calls.',
|
||||
"feat.web.title": "Web search built-in",
|
||||
"feat.web.body":
|
||||
"<code>web_search</code> + <code>web_fetch</code> via Mojeek — no key, no signup, off-by-flag for offline / CI. Bring-your-own provider via the <code>WebSearchProvider</code> interface.",
|
||||
|
||||
"bench.title": "Verify the cache claim yourself",
|
||||
"bench.sub":
|
||||
"On the same τ-bench-lite workload (8 multi-turn tool-use tasks × 3 repeats = 48 runs per side), live DeepSeek <code>deepseek-chat</code>, sole variable prefix stability:",
|
||||
"bench.col.metric": "metric",
|
||||
"bench.col.baseline": "baseline (cache-hostile)",
|
||||
"bench.col.reasonix": "Reasonix",
|
||||
"bench.col.delta": "delta",
|
||||
"bench.row.cache": "cache hit",
|
||||
"bench.row.cost": "cost / task",
|
||||
"bench.row.pass": "pass rate",
|
||||
"bench.repro.intro": "Reproduce without spending an API credit:",
|
||||
"bench.repro.note":
|
||||
"The committed JSONL transcripts carry per-turn <code>usage</code>, <code>cost</code>, and <code>prefixHash</code>. Reasonix's prefix hash stays byte-stable across every model call.",
|
||||
|
||||
"cli.title": "CLI at a glance",
|
||||
"cli.code": "coding mode scoped to path",
|
||||
"cli.chat": "chat (uses saved config)",
|
||||
"cli.setup": "reconfigure the wizard",
|
||||
"cli.run": "one-shot, streams to stdout",
|
||||
"cli.stats": "cross-session cost dashboard",
|
||||
"cli.mcp": "probe a single MCP server",
|
||||
"cli.flags.intro": "Common flags:",
|
||||
"cli.f.preset": "model + harvest + branch bundle",
|
||||
"cli.f.model": "explicit DeepSeek model id",
|
||||
"cli.f.mcp": "attach an MCP server (repeatable)",
|
||||
"cli.f.session": "named session",
|
||||
"cli.f.noconf": "ignore ~/.reasonix/config.json (CI)",
|
||||
|
||||
"ctab.title": "Ready to try?",
|
||||
"ctab.sub": "One <code>npx</code> away. Sandboxed. Reviewable. 96% cheaper.",
|
||||
"ctab.gh": "GitHub repository →",
|
||||
"ctab.npm": "npm package",
|
||||
|
||||
"foot.tag": "DeepSeek does deep, deeply.",
|
||||
"foot.col.project": "Project",
|
||||
"foot.col.docs": "Docs",
|
||||
"foot.col.community": "Community",
|
||||
"foot.changelog": "Changelog",
|
||||
"foot.readme": "README",
|
||||
"foot.readme.zh": "中文 README",
|
||||
"foot.arch": "Architecture",
|
||||
"foot.issues": "Issues",
|
||||
"foot.discuss": "Discussions",
|
||||
"foot.copyright": "© 2026 Reasonix · MIT License",
|
||||
},
|
||||
|
||||
zh: {
|
||||
"nav.features": "特性",
|
||||
"nav.quickstart": "快速上手",
|
||||
"nav.benchmarks": "性能对比",
|
||||
"nav.github": "GitHub",
|
||||
|
||||
"hero.badge": "v{version} · DeepSeek V4 · 缓存优先",
|
||||
"hero.title.line1": "DeepSeek 原生",
|
||||
"hero.title.line2": "终端里的 AI 编程代理",
|
||||
"hero.sub":
|
||||
"为 DeepSeek V4(flash + pro)打造的缓存优先 agent 循环。编辑以可审查的 SEARCH/REPLACE 块呈现,落盘前必须确认。Ink TUI、原生支持 MCP,不依赖 LangChain。",
|
||||
"hero.copy": "复制",
|
||||
"hero.copy.done": "已复制",
|
||||
"hero.cta.start": "开始使用 →",
|
||||
"hero.cta.star": "在 GitHub 加星",
|
||||
"hero.stat.cache": "前缀缓存命中率",
|
||||
"hero.stat.cost": "相比 Claude Sonnet 4.6 节省",
|
||||
"hero.stat.pass": "τ-bench-lite 通过率",
|
||||
|
||||
"term.user":
|
||||
"users.ts 里 findByEmail 对大小写敏感导致登录失败,帮我改",
|
||||
"term.found":
|
||||
"▸ 找到了。findByEmail 直接用 === 比对。改成小写规范化并补一条测试。",
|
||||
"term.pending": "▸ 1 处待应用编辑 · /apply 写入 · /discard 丢弃",
|
||||
|
||||
"why.title": "为什么选 Reasonix",
|
||||
"why.sub":
|
||||
"每个抽象都对应 DeepSeek 的一个具体特性——极低 token 价、R1 推理轨迹、自动前缀缓存、JSON 模式。通用框架把这些机会全留在桌上。",
|
||||
"why.cache.title": "缓存优先的循环",
|
||||
"why.cache.body":
|
||||
"对话日志只追加不重写,前缀字节级稳定,DeepSeek 的自动前缀缓存命中能稳定打到 85–95%,而不是 40%。",
|
||||
"why.cost.title": "成本是头等公民",
|
||||
"why.cost.body":
|
||||
"默认 flash 优先、turn 末尾自动压缩、必要时模型自我升级到 pro。TUI 有实时单轮成本徽章。",
|
||||
"why.tui.title": "Ink TUI,不靠浏览器",
|
||||
"why.tui.body":
|
||||
"完全在终端里。流式预览、斜杠命令、计划审阅、编辑确认弹窗。Windows 顽固终端可启用 plain 模式。",
|
||||
"why.mcp.title": "原生 MCP",
|
||||
"why.mcp.body":
|
||||
"stdio + HTTP+SSE 双传输。长任务有实时进度条。和原生工具一样走缓存安全 + 自动修复管线。",
|
||||
"why.safe.title": "编辑可审阅",
|
||||
"why.safe.body":
|
||||
"编辑以 SEARCH/REPLACE 块呈现,/apply 之前不动磁盘。逐文件 diff 确认、撤销历史、路径沙箱。",
|
||||
"why.ctx.title": "百万 token 感知",
|
||||
"why.ctx.body":
|
||||
"上下文仪表 + 主动压缩、超大工具结果自动修复、贴近上限自动总结兜底。",
|
||||
|
||||
"qs.title": "60 秒快速上手",
|
||||
"qs.step1.title": "获取 DeepSeek API Key",
|
||||
"qs.step1.body":
|
||||
'在 <a href="https://platform.deepseek.com/api_keys" target="_blank" rel="noopener">platform.deepseek.com</a> 注册即送免费额度。',
|
||||
"qs.step2.title": "切到项目目录运行",
|
||||
"qs.step2.body": "无需安装。",
|
||||
"qs.step2.note":
|
||||
"首次运行会走 30 秒向导:粘贴 API key → 选预设 → 勾选 MCP 服务器。",
|
||||
"qs.step3.title": "让它改代码",
|
||||
"qs.step3.body":
|
||||
"模型会以 SEARCH/REPLACE 块的形式提出编辑——你不 <code>/apply</code>,磁盘不会被改。",
|
||||
"qs.req":
|
||||
"需要 Node ≥ 20.10。支持 macOS、Linux、Windows(PowerShell · Git Bash · Windows Terminal)。任何时候按 <kbd>Esc</kbd> 中断;<code>/help</code> 查看完整命令。",
|
||||
|
||||
"feat.title": "开箱即用",
|
||||
"feat.code.title": "结对编程模式",
|
||||
"feat.code.body":
|
||||
"<code>read_file</code> · <code>write_file</code> · <code>edit_file</code> · <code>search_files</code> · <code>directory_tree</code> · 带只读白名单的 <code>run_command</code>。沙箱限定在启动目录——路径逃逸一律拒绝。支持 plan 模式与逐次编辑确认弹窗。",
|
||||
"feat.memory.title": "两层记忆系统",
|
||||
"feat.memory.body":
|
||||
"可提交的 <code>REASONIX.md</code> 承载团队约定,私人 <code>~/.reasonix/memory/</code> 分全局与按项目两个作用域。模型可通过 <code>remember</code> 工具自行写入。",
|
||||
"feat.skills.title": "用户定义的 prompt 包",
|
||||
"feat.skills.body":
|
||||
"把 <code>SKILL.md</code> 丢进任意位置。名字 + 描述会被钉在前缀里,模型可自动调用,或你用 <code>/skill name</code> 手动触发。",
|
||||
"feat.hooks.title": "生命周期钩子",
|
||||
"feat.hooks.body":
|
||||
"在 <code>PreToolUse</code> · <code>PostToolUse</code> · <code>UserPromptSubmit</code> · <code>Stop</code> 四个点触发 shell 命令,退出码决定放行 / 阻断 / 警告。",
|
||||
"feat.mcp.title": "自带工具进来",
|
||||
"feat.mcp.body":
|
||||
'向导内置目录,或用 <code>--mcp "name=cmd"</code> 直接挂 stdio / HTTP+SSE 服务器。长任务渲染实时进度条。',
|
||||
"feat.web.title": "内置联网搜索",
|
||||
"feat.web.body":
|
||||
"<code>web_search</code> + <code>web_fetch</code>,背靠 Mojeek——无需 key、无需注册,离线 / CI 可关闭。可通过 <code>WebSearchProvider</code> 接口接入自家搜索。",
|
||||
|
||||
"bench.title": "缓存命中率自己也能验证",
|
||||
"bench.sub":
|
||||
"同一 τ-bench-lite 负载(8 个多轮工具调用任务 × 3 次重复 = 每边 48 次运行),实测 DeepSeek <code>deepseek-chat</code>,唯一变量是前缀稳定性:",
|
||||
"bench.col.metric": "指标",
|
||||
"bench.col.baseline": "基线(缓存敌对)",
|
||||
"bench.col.reasonix": "Reasonix",
|
||||
"bench.col.delta": "差值",
|
||||
"bench.row.cache": "缓存命中",
|
||||
"bench.row.cost": "单任务成本",
|
||||
"bench.row.pass": "通过率",
|
||||
"bench.repro.intro": "无需消耗 API 额度即可复现:",
|
||||
"bench.repro.note":
|
||||
"提交进仓库的 JSONL 文件每轮带 <code>usage</code>、<code>cost</code>、<code>prefixHash</code>。Reasonix 的前缀哈希在每次模型调用时都字节稳定。",
|
||||
|
||||
"cli.title": "CLI 速览",
|
||||
"cli.code": "针对指定路径的编程模式",
|
||||
"cli.chat": "聊天模式(读取已保存配置)",
|
||||
"cli.setup": "重新跑配置向导",
|
||||
"cli.run": "一次性运行,结果流到 stdout",
|
||||
"cli.stats": "跨会话的成本仪表盘",
|
||||
"cli.mcp": "探测单个 MCP 服务器",
|
||||
"cli.flags.intro": "常用 flag:",
|
||||
"cli.f.preset": "模型 + harvest + 分支并行 一键组合",
|
||||
"cli.f.model": "显式指定 DeepSeek 模型 ID",
|
||||
"cli.f.mcp": "挂载 MCP 服务器(可重复)",
|
||||
"cli.f.session": "命名会话",
|
||||
"cli.f.noconf": "忽略 ~/.reasonix/config.json(CI 友好)",
|
||||
|
||||
"ctab.title": "准备好了吗?",
|
||||
"ctab.sub": "一条 <code>npx</code> 即可开始。沙箱、可审阅、便宜 96%。",
|
||||
"ctab.gh": "GitHub 仓库 →",
|
||||
"ctab.npm": "npm 包",
|
||||
|
||||
"foot.tag": "Reasonix 只做 DeepSeek,做到底。",
|
||||
"foot.col.project": "项目",
|
||||
"foot.col.docs": "文档",
|
||||
"foot.col.community": "社区",
|
||||
"foot.changelog": "更新日志",
|
||||
"foot.readme": "英文 README",
|
||||
"foot.readme.zh": "中文 README",
|
||||
"foot.arch": "架构文档",
|
||||
"foot.issues": "问题反馈",
|
||||
"foot.discuss": "讨论区",
|
||||
"foot.copyright": "© 2026 Reasonix · MIT 协议",
|
||||
},
|
||||
};
|
||||
|
||||
function safeStorageGet(key) {
|
||||
try {
|
||||
return window.localStorage.getItem(key);
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function safeStorageSet(key, value) {
|
||||
try {
|
||||
window.localStorage.setItem(key, value);
|
||||
} catch (_) {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
function detectLang() {
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
const queryLang = params.get("lang");
|
||||
if (queryLang && SUPPORTED.includes(queryLang)) return queryLang;
|
||||
|
||||
const stored = safeStorageGet(STORAGE_KEY);
|
||||
if (stored && SUPPORTED.includes(stored)) return stored;
|
||||
|
||||
const navLang = (navigator.language || navigator.userLanguage || "").toLowerCase();
|
||||
if (navLang.startsWith("zh")) return "zh";
|
||||
|
||||
if (Array.isArray(navigator.languages)) {
|
||||
for (const l of navigator.languages) {
|
||||
if (l && l.toLowerCase().startsWith("zh")) return "zh";
|
||||
}
|
||||
}
|
||||
|
||||
return DEFAULT_LANG;
|
||||
}
|
||||
|
||||
let currentLang = DEFAULT_LANG;
|
||||
const langListeners = [];
|
||||
|
||||
// Version is rendered into translation strings via a `{version}` token
|
||||
// (see hero.badge). Source of truth is npm — `loadVersion()` fetches
|
||||
// it on page load and re-applies translations. Until that resolves
|
||||
// we fall back to the most recently cached value, then to a baked-in
|
||||
// default. Only places this constant matters: the user is offline AND
|
||||
// visits the site for the first time. Bumping it occasionally on
|
||||
// major version cuts is fine; the npm fetch handles everything else.
|
||||
const VERSION_STORAGE_KEY = "reasonix.version";
|
||||
const VERSION_FALLBACK = "0.12";
|
||||
const versionListeners = [];
|
||||
let currentVersion = VERSION_FALLBACK;
|
||||
|
||||
function applyVersion(v) {
|
||||
if (typeof v !== "string" || !v || v === currentVersion) return;
|
||||
currentVersion = v;
|
||||
safeStorageSet(VERSION_STORAGE_KEY, v);
|
||||
applyLang(currentLang); // re-render any `{version}` tokens
|
||||
for (const fn of versionListeners) {
|
||||
try {
|
||||
fn(v);
|
||||
} catch (_) {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function loadVersion() {
|
||||
try {
|
||||
const r = await fetch("https://registry.npmjs.org/reasonix/latest", {
|
||||
cache: "no-cache",
|
||||
});
|
||||
if (!r.ok) return;
|
||||
const data = await r.json();
|
||||
if (data && typeof data.version === "string") applyVersion(data.version);
|
||||
} catch (_) {
|
||||
/* offline / firewall — keep cached or fallback */
|
||||
}
|
||||
}
|
||||
|
||||
function fillVersion(s) {
|
||||
return typeof s === "string" ? s.replace(/\{version\}/g, currentVersion) : s;
|
||||
}
|
||||
|
||||
function applyLang(lang) {
|
||||
if (!SUPPORTED.includes(lang)) lang = DEFAULT_LANG;
|
||||
const changed = lang !== currentLang;
|
||||
currentLang = lang;
|
||||
const dict = translations[lang];
|
||||
|
||||
document.documentElement.lang = lang === "zh" ? "zh-CN" : "en";
|
||||
document.documentElement.setAttribute("data-lang", lang);
|
||||
|
||||
document.querySelectorAll("[data-i18n]").forEach((el) => {
|
||||
const key = el.getAttribute("data-i18n");
|
||||
if (dict[key] !== undefined) {
|
||||
el.innerHTML = fillVersion(dict[key]);
|
||||
}
|
||||
});
|
||||
|
||||
document.querySelectorAll("[data-lang-btn]").forEach((btn) => {
|
||||
const isActive = btn.getAttribute("data-lang-btn") === lang;
|
||||
btn.setAttribute("aria-pressed", isActive ? "true" : "false");
|
||||
});
|
||||
|
||||
safeStorageSet(STORAGE_KEY, lang);
|
||||
|
||||
if (changed) {
|
||||
for (const fn of langListeners) {
|
||||
try {
|
||||
fn(lang);
|
||||
} catch (_) {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Public API for sibling scripts (term-anim.js).
|
||||
window.Reasonix = window.Reasonix || {};
|
||||
window.Reasonix.t = function (key) {
|
||||
const dict = translations[currentLang] || translations[DEFAULT_LANG];
|
||||
return dict[key];
|
||||
};
|
||||
window.Reasonix.lang = function () {
|
||||
return currentLang;
|
||||
};
|
||||
window.Reasonix.onLangChange = function (fn) {
|
||||
if (typeof fn === "function") langListeners.push(fn);
|
||||
};
|
||||
window.Reasonix.version = function () {
|
||||
return currentVersion;
|
||||
};
|
||||
window.Reasonix.onVersionChange = function (fn) {
|
||||
if (typeof fn === "function") versionListeners.push(fn);
|
||||
};
|
||||
|
||||
function wireLangButtons() {
|
||||
document.querySelectorAll("[data-lang-btn]").forEach((btn) => {
|
||||
btn.addEventListener("click", () => {
|
||||
applyLang(btn.getAttribute("data-lang-btn"));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function wireCopyButtons() {
|
||||
document.querySelectorAll("[data-copy]").forEach((btn) => {
|
||||
btn.addEventListener("click", async () => {
|
||||
const text = btn.getAttribute("data-copy");
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
} catch (_) {
|
||||
const ta = document.createElement("textarea");
|
||||
ta.value = text;
|
||||
ta.style.position = "fixed";
|
||||
ta.style.opacity = "0";
|
||||
document.body.appendChild(ta);
|
||||
ta.select();
|
||||
try {
|
||||
document.execCommand("copy");
|
||||
} catch (_) {
|
||||
/* ignore */
|
||||
}
|
||||
document.body.removeChild(ta);
|
||||
}
|
||||
const lang = document.documentElement.getAttribute("data-lang") || DEFAULT_LANG;
|
||||
const original = translations[lang]["hero.copy"] || "Copy";
|
||||
const done = translations[lang]["hero.copy.done"] || "Copied";
|
||||
btn.textContent = done;
|
||||
btn.classList.add("copied");
|
||||
setTimeout(() => {
|
||||
btn.textContent = original;
|
||||
btn.classList.remove("copied");
|
||||
}, 1600);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function init() {
|
||||
// Use the cached npm version (if any) so the badge isn't visibly
|
||||
// wrong on first paint; fall back to the baked-in default. Then
|
||||
// fire off the live fetch — when it resolves, applyVersion()
|
||||
// re-applies translations and notifies subscribers (term-anim).
|
||||
const cached = safeStorageGet(VERSION_STORAGE_KEY);
|
||||
if (typeof cached === "string" && /^\d+\.\d+/.test(cached)) currentVersion = cached;
|
||||
applyLang(detectLang());
|
||||
wireLangButtons();
|
||||
wireCopyButtons();
|
||||
loadVersion();
|
||||
}
|
||||
|
||||
if (document.readyState === "loading") {
|
||||
document.addEventListener("DOMContentLoaded", init);
|
||||
} else {
|
||||
init();
|
||||
}
|
||||
})();
|
||||
+493
@@ -0,0 +1,493 @@
|
||||
<!doctype html>
|
||||
<html lang="en" data-lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>Reasonix — DeepSeek-native AI coding agent</title>
|
||||
<meta
|
||||
name="description"
|
||||
content="Cache-first agent loop for DeepSeek V4. Ink TUI. MCP first-class. 94%+ prefix cache hit, ~96% cheaper than Claude on the same workload. No LangChain."
|
||||
/>
|
||||
<meta name="theme-color" content="#0b0f17" />
|
||||
|
||||
<meta property="og:title" content="Reasonix — DeepSeek-native AI coding agent" />
|
||||
<meta
|
||||
property="og:description"
|
||||
content="Cache-first agent loop for DeepSeek V4 (flash + pro). Ink TUI. MCP first-class. No LangChain."
|
||||
/>
|
||||
<meta property="og:type" content="website" />
|
||||
<meta property="og:url" content="https://esengine.github.io/reasonix/" />
|
||||
<meta property="og:image" content="https://raw.githubusercontent.com/esengine/reasonix/main/docs/logo.svg" />
|
||||
<meta name="twitter:card" content="summary_large_image" />
|
||||
|
||||
<link rel="icon" type="image/svg+xml" href="favicon.svg" />
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||
<link
|
||||
href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&family=JetBrains+Mono:wght@400;500;600;700&family=Noto+Sans+SC:wght@400;500;600;700;800&display=swap"
|
||||
rel="stylesheet"
|
||||
/>
|
||||
<link rel="stylesheet" href="styles.css" />
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div class="bg-grid" aria-hidden="true"></div>
|
||||
<div class="bg-glow" aria-hidden="true"></div>
|
||||
|
||||
<header class="nav">
|
||||
<a class="nav-brand" href="#top" aria-label="Reasonix">
|
||||
<span class="brand-mark" aria-hidden="true">
|
||||
<span class="diamond"></span>
|
||||
<span class="diamond inner"></span>
|
||||
</span>
|
||||
<span class="brand-name">Reasonix</span>
|
||||
</a>
|
||||
|
||||
<nav class="nav-links">
|
||||
<a href="#features" data-i18n="nav.features">Features</a>
|
||||
<a href="#quickstart" data-i18n="nav.quickstart">Quick start</a>
|
||||
<a href="#benchmarks" data-i18n="nav.benchmarks">Benchmarks</a>
|
||||
<a
|
||||
href="https://github.com/esengine/reasonix"
|
||||
target="_blank"
|
||||
rel="noopener"
|
||||
data-i18n="nav.github"
|
||||
>GitHub</a
|
||||
>
|
||||
</nav>
|
||||
|
||||
<div class="nav-actions">
|
||||
<div class="lang-switch" role="group" aria-label="Language">
|
||||
<button data-lang-btn="en" type="button" aria-pressed="true">EN</button>
|
||||
<button data-lang-btn="zh" type="button" aria-pressed="false">中文</button>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main id="top">
|
||||
<section class="hero">
|
||||
<div class="hero-inner">
|
||||
<div class="badge" data-i18n="hero.badge">v0.6 · DeepSeek V4 · cache-first</div>
|
||||
<h1 class="hero-title">
|
||||
<span class="grad-text" data-i18n="hero.title.line1">DeepSeek-native</span>
|
||||
<br />
|
||||
<span data-i18n="hero.title.line2">AI coding agent in your terminal</span>
|
||||
</h1>
|
||||
<p class="hero-sub" data-i18n="hero.sub">
|
||||
Cache-first agent loop for DeepSeek V4 (flash + pro). Edits files as
|
||||
reviewable SEARCH/REPLACE blocks. Ink TUI. MCP first-class. No LangChain.
|
||||
</p>
|
||||
|
||||
<div class="hero-install">
|
||||
<code class="install-cmd"
|
||||
><span class="prompt">$</span> <span class="cmd">npx reasonix code</span></code
|
||||
>
|
||||
<button class="copy-btn" data-copy="npx reasonix code" data-i18n="hero.copy">
|
||||
Copy
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="hero-ctas">
|
||||
<a class="cta primary" href="#quickstart" data-i18n="hero.cta.start">
|
||||
Get started →
|
||||
</a>
|
||||
<a
|
||||
class="cta ghost"
|
||||
href="https://github.com/esengine/reasonix"
|
||||
target="_blank"
|
||||
rel="noopener"
|
||||
data-i18n="hero.cta.star"
|
||||
>Star on GitHub</a
|
||||
>
|
||||
</div>
|
||||
|
||||
<div class="hero-stats">
|
||||
<div class="stat">
|
||||
<div class="stat-num grad-text">94.4%</div>
|
||||
<div class="stat-label" data-i18n="hero.stat.cache">prefix cache hit rate</div>
|
||||
</div>
|
||||
<div class="stat">
|
||||
<div class="stat-num grad-text">~96%</div>
|
||||
<div class="stat-label" data-i18n="hero.stat.cost">cheaper vs Claude Sonnet 4.6</div>
|
||||
</div>
|
||||
<div class="stat">
|
||||
<div class="stat-num grad-text">100%</div>
|
||||
<div class="stat-label" data-i18n="hero.stat.pass">τ-bench-lite pass rate</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="hero-terminal" aria-hidden="true">
|
||||
<div class="term-bar">
|
||||
<span class="dot r"></span><span class="dot y"></span><span class="dot g"></span>
|
||||
<span class="term-title">reasonix code</span>
|
||||
<button class="term-replay" type="button" data-replay aria-label="replay">↻</button>
|
||||
</div>
|
||||
<div class="term-body" id="term-body" data-anim-root></div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="why">
|
||||
<div class="container">
|
||||
<h2 class="section-title" data-i18n="why.title">Why Reasonix</h2>
|
||||
<p class="section-sub" data-i18n="why.sub">
|
||||
Every abstraction earns its weight against a DeepSeek-specific property —
|
||||
dirt-cheap tokens, R1 traces, automatic prefix caching, JSON mode. Generic
|
||||
wrappers leave these on the table.
|
||||
</p>
|
||||
|
||||
<div class="why-grid">
|
||||
<article class="why-card">
|
||||
<div class="why-icon">◈</div>
|
||||
<h3 data-i18n="why.cache.title">Cache-first loop</h3>
|
||||
<p data-i18n="why.cache.body">
|
||||
Append-only conversation log keeps the prompt prefix byte-stable across
|
||||
turns, so DeepSeek's automatic cache hits 85–95% — not 40%.
|
||||
</p>
|
||||
</article>
|
||||
<article class="why-card">
|
||||
<div class="why-icon">¥</div>
|
||||
<h3 data-i18n="why.cost.title">Cost is a pillar</h3>
|
||||
<p data-i18n="why.cost.body">
|
||||
Flash-first defaults, turn-end auto-compaction, model self-escalation
|
||||
when (and only when) needed. Per-turn cost badge in the TUI.
|
||||
</p>
|
||||
</article>
|
||||
<article class="why-card">
|
||||
<div class="why-icon">⌨</div>
|
||||
<h3 data-i18n="why.tui.title">Ink TUI, no web</h3>
|
||||
<p data-i18n="why.tui.body">
|
||||
Lives in your terminal. Streaming preview, slash commands, plan picker,
|
||||
edit-confirm modal. Plain mode for stubborn Windows shells.
|
||||
</p>
|
||||
</article>
|
||||
<article class="why-card">
|
||||
<div class="why-icon">⊕</div>
|
||||
<h3 data-i18n="why.mcp.title">MCP first-class</h3>
|
||||
<p data-i18n="why.mcp.body">
|
||||
Stdio + HTTP+SSE transports. Live progress notifications. Same
|
||||
cache-safety + repair plumbing as native tools.
|
||||
</p>
|
||||
</article>
|
||||
<article class="why-card">
|
||||
<div class="why-icon">↶</div>
|
||||
<h3 data-i18n="why.safe.title">Reviewable edits</h3>
|
||||
<p data-i18n="why.safe.body">
|
||||
Edits arrive as SEARCH/REPLACE blocks; nothing hits disk until /apply.
|
||||
Per-file diff confirm modal, undo history, sandboxed paths.
|
||||
</p>
|
||||
</article>
|
||||
<article class="why-card">
|
||||
<div class="why-icon">∞</div>
|
||||
<h3 data-i18n="why.ctx.title">1M-token aware</h3>
|
||||
<p data-i18n="why.ctx.body">
|
||||
Context gauge with proactive compaction, oversized tool-result repair,
|
||||
forced-summary fallback near the window edge.
|
||||
</p>
|
||||
</article>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section id="quickstart" class="quickstart">
|
||||
<div class="container">
|
||||
<h2 class="section-title" data-i18n="qs.title">Quick start (60 seconds)</h2>
|
||||
<ol class="qs-steps">
|
||||
<li>
|
||||
<h3 data-i18n="qs.step1.title">Get a DeepSeek API key</h3>
|
||||
<p data-i18n="qs.step1.body">
|
||||
Free credit on signup at
|
||||
<a href="https://platform.deepseek.com/api_keys" target="_blank" rel="noopener"
|
||||
>platform.deepseek.com</a
|
||||
>.
|
||||
</p>
|
||||
</li>
|
||||
<li>
|
||||
<h3 data-i18n="qs.step2.title">Point it at a project</h3>
|
||||
<p data-i18n="qs.step2.body">No install needed.</p>
|
||||
<pre class="code"><code>cd my-project
|
||||
npx reasonix code</code></pre>
|
||||
<p data-i18n="qs.step2.note">
|
||||
First run walks you through a 30-second wizard (paste API key → pick
|
||||
preset → pick MCP servers).
|
||||
</p>
|
||||
</li>
|
||||
<li>
|
||||
<h3 data-i18n="qs.step3.title">Ask it to edit</h3>
|
||||
<p data-i18n="qs.step3.body">
|
||||
The model proposes edits as SEARCH/REPLACE blocks — nothing hits disk
|
||||
until you <code>/apply</code>.
|
||||
</p>
|
||||
</li>
|
||||
</ol>
|
||||
|
||||
<p class="req" data-i18n="qs.req">
|
||||
Requires Node ≥ 20.10. macOS, Linux, Windows (PowerShell · Git Bash · Windows
|
||||
Terminal). Press <kbd>Esc</kbd> anytime to abort; <code>/help</code> for the
|
||||
full command list.
|
||||
</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section id="features" class="features">
|
||||
<div class="container">
|
||||
<h2 class="section-title" data-i18n="feat.title">In the box</h2>
|
||||
|
||||
<div class="feat-grid">
|
||||
<article class="feat">
|
||||
<h3>
|
||||
<span class="feat-tag">code</span>
|
||||
<span data-i18n="feat.code.title">Pair programmer mode</span>
|
||||
</h3>
|
||||
<p data-i18n="feat.code.body">
|
||||
<code>read_file</code> · <code>write_file</code> · <code>edit_file</code> ·
|
||||
<code>search_files</code> · <code>directory_tree</code> ·
|
||||
<code>run_command</code> with read-only allowlist. Sandboxed to the
|
||||
launch root — no path escapes. Plan mode and per-edit review modal.
|
||||
</p>
|
||||
</article>
|
||||
<article class="feat">
|
||||
<h3>
|
||||
<span class="feat-tag">memory</span>
|
||||
<span data-i18n="feat.memory.title">Two-layer memory</span>
|
||||
</h3>
|
||||
<p data-i18n="feat.memory.body">
|
||||
Committable <code>REASONIX.md</code> for team conventions plus a private
|
||||
per-user <code>~/.reasonix/memory/</code> with global and per-project
|
||||
scopes. The model can write to it via the <code>remember</code> tool.
|
||||
</p>
|
||||
</article>
|
||||
<article class="feat">
|
||||
<h3>
|
||||
<span class="feat-tag">skills</span>
|
||||
<span data-i18n="feat.skills.title">User-authored prompt packs</span>
|
||||
</h3>
|
||||
<p data-i18n="feat.skills.body">
|
||||
Drop <code>SKILL.md</code> files anywhere. Names + descriptions are
|
||||
pinned in the prefix; the model picks them autonomously, or you trigger
|
||||
with <code>/skill name</code>.
|
||||
</p>
|
||||
</article>
|
||||
<article class="feat">
|
||||
<h3>
|
||||
<span class="feat-tag">hooks</span>
|
||||
<span data-i18n="feat.hooks.title">Lifecycle hooks</span>
|
||||
</h3>
|
||||
<p data-i18n="feat.hooks.body">
|
||||
Shell commands fire at <code>PreToolUse</code> · <code>PostToolUse</code>
|
||||
· <code>UserPromptSubmit</code> · <code>Stop</code>. Exit code drives
|
||||
pass / block / warn.
|
||||
</p>
|
||||
</article>
|
||||
<article class="feat">
|
||||
<h3>
|
||||
<span class="feat-tag">mcp</span>
|
||||
<span data-i18n="feat.mcp.title">Bring your own tools</span>
|
||||
</h3>
|
||||
<p data-i18n="feat.mcp.body">
|
||||
Wizard catalog, or <code>--mcp "name=cmd"</code> to attach stdio /
|
||||
HTTP+SSE servers on the fly. Live progress bars on long calls.
|
||||
</p>
|
||||
</article>
|
||||
<article class="feat">
|
||||
<h3>
|
||||
<span class="feat-tag">web</span>
|
||||
<span data-i18n="feat.web.title">Web search built-in</span>
|
||||
</h3>
|
||||
<p data-i18n="feat.web.body">
|
||||
<code>web_search</code> + <code>web_fetch</code> via Mojeek — no key, no
|
||||
signup, off-by-flag for offline / CI. Bring-your-own provider via the
|
||||
<code>WebSearchProvider</code> interface.
|
||||
</p>
|
||||
</article>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section id="benchmarks" class="bench">
|
||||
<div class="container">
|
||||
<h2 class="section-title" data-i18n="bench.title">Verify the cache claim yourself</h2>
|
||||
<p class="section-sub" data-i18n="bench.sub">
|
||||
On the same τ-bench-lite workload (8 multi-turn tool-use tasks × 3 repeats =
|
||||
48 runs per side), live DeepSeek <code>deepseek-chat</code>, sole variable
|
||||
prefix stability:
|
||||
</p>
|
||||
|
||||
<div class="bench-table-wrap">
|
||||
<table class="bench-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th data-i18n="bench.col.metric">metric</th>
|
||||
<th data-i18n="bench.col.baseline">baseline (cache-hostile)</th>
|
||||
<th data-i18n="bench.col.reasonix">Reasonix</th>
|
||||
<th data-i18n="bench.col.delta">delta</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td data-i18n="bench.row.cache">cache hit</td>
|
||||
<td>46.6%</td>
|
||||
<td class="hi">94.4%</td>
|
||||
<td>+47.7 pp</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td data-i18n="bench.row.cost">cost / task</td>
|
||||
<td>$0.002599</td>
|
||||
<td class="hi">$0.001579</td>
|
||||
<td><strong>−39%</strong></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td data-i18n="bench.row.pass">pass rate</td>
|
||||
<td>96% (23/24)</td>
|
||||
<td class="hi">100% (24/24)</td>
|
||||
<td>—</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<p data-i18n="bench.repro.intro">Reproduce without spending an API credit:</p>
|
||||
<pre class="code"><code>git clone https://github.com/esengine/reasonix.git && cd reasonix && npm install
|
||||
npx reasonix replay benchmarks/tau-bench/transcripts/t01_address_happy.reasonix.r1.jsonl
|
||||
npx reasonix diff \
|
||||
benchmarks/tau-bench/transcripts/t01_address_happy.baseline.r1.jsonl \
|
||||
benchmarks/tau-bench/transcripts/t01_address_happy.reasonix.r1.jsonl</code></pre>
|
||||
|
||||
<p data-i18n="bench.repro.note">
|
||||
The committed JSONL transcripts carry per-turn <code>usage</code>,
|
||||
<code>cost</code>, and <code>prefixHash</code>. Reasonix's prefix hash stays
|
||||
byte-stable across every model call.
|
||||
</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="cli">
|
||||
<div class="container">
|
||||
<h2 class="section-title" data-i18n="cli.title">CLI at a glance</h2>
|
||||
<pre class="code"><code>npx reasonix code [path] <span class="hash"># <span data-i18n="cli.code">coding mode scoped to path</span></span>
|
||||
npx reasonix <span class="hash"># <span data-i18n="cli.chat">chat (uses saved config)</span></span>
|
||||
npx reasonix setup <span class="hash"># <span data-i18n="cli.setup">reconfigure the wizard</span></span>
|
||||
npx reasonix run "ask anything" <span class="hash"># <span data-i18n="cli.run">one-shot, streams to stdout</span></span>
|
||||
npx reasonix stats <span class="hash"># <span data-i18n="cli.stats">cross-session cost dashboard</span></span>
|
||||
npx reasonix mcp inspect <spec> <span class="hash"># <span data-i18n="cli.mcp">probe a single MCP server</span></span></code></pre>
|
||||
|
||||
<p class="cli-flags" data-i18n="cli.flags.intro">Common flags:</p>
|
||||
<pre class="code"><code>--preset <fast|smart|max> <span class="hash"># <span data-i18n="cli.f.preset">model + harvest + branch bundle</span></span>
|
||||
--model <id> <span class="hash"># <span data-i18n="cli.f.model">explicit DeepSeek model id</span></span>
|
||||
--mcp "name=cmd args…" <span class="hash"># <span data-i18n="cli.f.mcp">attach an MCP server (repeatable)</span></span>
|
||||
--session <name> <span class="hash"># <span data-i18n="cli.f.session">named session</span></span>
|
||||
--no-config <span class="hash"># <span data-i18n="cli.f.noconf">ignore ~/.reasonix/config.json (CI)</span></span></code></pre>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="cta-band">
|
||||
<div class="container">
|
||||
<h2 data-i18n="ctab.title">Ready to try?</h2>
|
||||
<p data-i18n="ctab.sub">
|
||||
One <code>npx</code> away. Sandboxed. Reviewable. 96% cheaper.
|
||||
</p>
|
||||
<div class="hero-ctas center">
|
||||
<a
|
||||
class="cta primary"
|
||||
href="https://github.com/esengine/reasonix"
|
||||
target="_blank"
|
||||
rel="noopener"
|
||||
data-i18n="ctab.gh"
|
||||
>GitHub repository →</a
|
||||
>
|
||||
<a
|
||||
class="cta ghost"
|
||||
href="https://www.npmjs.com/package/reasonix"
|
||||
target="_blank"
|
||||
rel="noopener"
|
||||
data-i18n="ctab.npm"
|
||||
>npm package</a
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
<footer class="foot">
|
||||
<div class="container foot-inner">
|
||||
<div>
|
||||
<a href="#top" class="nav-brand">
|
||||
<span class="brand-mark small" aria-hidden="true">
|
||||
<span class="diamond"></span>
|
||||
<span class="diamond inner"></span>
|
||||
</span>
|
||||
<span class="brand-name">Reasonix</span>
|
||||
</a>
|
||||
<p class="foot-tag" data-i18n="foot.tag">DeepSeek does deep, deeply.</p>
|
||||
</div>
|
||||
<div class="foot-cols">
|
||||
<div>
|
||||
<h4 data-i18n="foot.col.project">Project</h4>
|
||||
<a href="https://github.com/esengine/reasonix" target="_blank" rel="noopener">GitHub</a>
|
||||
<a href="https://www.npmjs.com/package/reasonix" target="_blank" rel="noopener">npm</a>
|
||||
<a
|
||||
href="https://github.com/esengine/reasonix/blob/main/CHANGELOG.md"
|
||||
target="_blank"
|
||||
rel="noopener"
|
||||
data-i18n="foot.changelog"
|
||||
>Changelog</a
|
||||
>
|
||||
<a
|
||||
href="https://github.com/esengine/reasonix/blob/main/LICENSE"
|
||||
target="_blank"
|
||||
rel="noopener"
|
||||
>MIT</a
|
||||
>
|
||||
</div>
|
||||
<div>
|
||||
<h4 data-i18n="foot.col.docs">Docs</h4>
|
||||
<a
|
||||
href="https://github.com/esengine/reasonix#readme"
|
||||
target="_blank"
|
||||
rel="noopener"
|
||||
data-i18n="foot.readme"
|
||||
>README</a
|
||||
>
|
||||
<a
|
||||
href="https://github.com/esengine/reasonix/blob/main/README.zh-CN.md"
|
||||
target="_blank"
|
||||
rel="noopener"
|
||||
data-i18n="foot.readme.zh"
|
||||
>中文 README</a
|
||||
>
|
||||
<a
|
||||
href="https://github.com/esengine/reasonix/blob/main/docs/ARCHITECTURE.md"
|
||||
target="_blank"
|
||||
rel="noopener"
|
||||
data-i18n="foot.arch"
|
||||
>Architecture</a
|
||||
>
|
||||
</div>
|
||||
<div>
|
||||
<h4 data-i18n="foot.col.community">Community</h4>
|
||||
<a
|
||||
href="https://github.com/esengine/reasonix/issues"
|
||||
target="_blank"
|
||||
rel="noopener"
|
||||
data-i18n="foot.issues"
|
||||
>Issues</a
|
||||
>
|
||||
<a
|
||||
href="https://github.com/esengine/reasonix/discussions"
|
||||
target="_blank"
|
||||
rel="noopener"
|
||||
data-i18n="foot.discuss"
|
||||
>Discussions</a
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="foot-bottom">
|
||||
<span data-i18n="foot.copyright">© 2026 Reasonix · MIT License</span>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
<script src="i18n.js"></script>
|
||||
<script src="term-anim.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
+1189
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,420 @@
|
||||
// Hero terminal animation — simulates a `reasonix code` session using
|
||||
// the real TUI rendering primitives:
|
||||
// ◇ / ◆ role glyphs + colored vertical accent bars
|
||||
// ` ✓ tool_name ` pills (yellow bg, black text)
|
||||
// EditBlockRow: rounded cyan border, filename, `- old` red / `+ new` green
|
||||
// info rows: dim glyph + dim body (slate)
|
||||
//
|
||||
// Reads i18n strings via Reasonix.t(); restarts on language toggle.
|
||||
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
const ROOT_SEL = "[data-anim-root]";
|
||||
const REPLAY_SEL = "[data-replay]";
|
||||
|
||||
const tr = (key, fallback) => {
|
||||
if (window.Reasonix && typeof window.Reasonix.t === "function") {
|
||||
const v = window.Reasonix.t(key);
|
||||
if (v !== undefined && v !== null && v !== "") return v;
|
||||
}
|
||||
return fallback != null ? fallback : key;
|
||||
};
|
||||
|
||||
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||
|
||||
function el(tag, cls, text) {
|
||||
const n = document.createElement(tag);
|
||||
if (cls) n.className = cls;
|
||||
if (text != null) n.textContent = text;
|
||||
return n;
|
||||
}
|
||||
|
||||
// Brand gradient — same stops as src/cli/ui/theme.ts GRADIENT.
|
||||
const GRADIENT = [
|
||||
"#5eead4",
|
||||
"#67e8f9",
|
||||
"#7dd3fc",
|
||||
"#93c5fd",
|
||||
"#a5b4fc",
|
||||
"#c4b5fd",
|
||||
"#d8b4fe",
|
||||
"#f0abfc",
|
||||
];
|
||||
|
||||
// ──────────────────────────────────────────────────────────────────
|
||||
// Header bar — `◈ REASONIX v0.12.x v4-flash REVIEW max … turn 1 · /help`
|
||||
// Version comes from the i18n script (which fetched it from npm).
|
||||
// Falls back to a baked-in default before the fetch lands.
|
||||
// ──────────────────────────────────────────────────────────────────
|
||||
function currentVersion() {
|
||||
const r = window.Reasonix;
|
||||
return (r && typeof r.version === "function" ? r.version() : null) || "0.12";
|
||||
}
|
||||
|
||||
function buildHeader(turn) {
|
||||
const h = el("div", "thead");
|
||||
h.innerHTML =
|
||||
'<span class="tw-mark">◈</span>' +
|
||||
'<span class="tw-name">REASONIX</span>' +
|
||||
`<span class="tw-ver">v${currentVersion()}</span>` +
|
||||
'<span class="tw-model">v4-flash</span>' +
|
||||
'<span class="tw-pill review">REVIEW</span>' +
|
||||
'<span class="tw-effort">max</span>' +
|
||||
'<span class="tw-spacer"></span>' +
|
||||
'<span class="tw-turn">turn ' +
|
||||
turn +
|
||||
" · /help</span>";
|
||||
return h;
|
||||
}
|
||||
|
||||
// ──────────────────────────────────────────────────────────────────
|
||||
// User row — ◇ glyph (cyan) + cyan vertical accent bar + text.
|
||||
// Mirrors EventLog.tsx role="user" render.
|
||||
// ──────────────────────────────────────────────────────────────────
|
||||
function buildUserRow(text) {
|
||||
const row = el("div", "trow trow-user");
|
||||
row.innerHTML =
|
||||
'<span class="trole role-user">◇</span>' +
|
||||
'<span class="tbar-cyan">▎</span>' +
|
||||
'<span class="trow-body"></span>';
|
||||
row.querySelector(".trow-body").textContent = text;
|
||||
return row;
|
||||
}
|
||||
|
||||
// Same shape as a user row but the body content is built progressively
|
||||
// by the animation. Returns the row + an `input` ref + a `caret` span.
|
||||
function buildLiveUserRow() {
|
||||
const row = el("div", "trow trow-user trow-live");
|
||||
row.innerHTML =
|
||||
'<span class="trole role-user">◇</span>' +
|
||||
'<span class="tbar-cyan">▎</span>' +
|
||||
'<span class="trow-body"><span class="tinput"></span><span class="tcaret">▍</span></span>';
|
||||
row._input = row.querySelector(".tinput");
|
||||
row._caret = row.querySelector(".tcaret");
|
||||
return row;
|
||||
}
|
||||
|
||||
// ──────────────────────────────────────────────────────────────────
|
||||
// Tool pill row — ` ✓ tool_name ` duration dim summary /tool N
|
||||
// Yellow bg pill (red bg for errors). Mirrors ToolPill in EventLog.tsx.
|
||||
// ──────────────────────────────────────────────────────────────────
|
||||
function buildToolRow(name, summary, durationLabel, indexHint) {
|
||||
const row = el("div", "trow trow-tool");
|
||||
const pill = el("span", "tpill tpill-ok");
|
||||
pill.textContent = " ✓ " + name + " ";
|
||||
row.appendChild(pill);
|
||||
if (durationLabel) {
|
||||
row.appendChild(el("span", "tdim", " " + durationLabel));
|
||||
}
|
||||
row.appendChild(el("span", "tdim", " " + summary));
|
||||
if (indexHint) {
|
||||
row.appendChild(el("span", "tdim tindex", " /tool " + indexHint));
|
||||
}
|
||||
return row;
|
||||
}
|
||||
|
||||
// ──────────────────────────────────────────────────────────────────
|
||||
// Assistant row — ◆ glyph + ` v4-flash ` pill, then a green-bordered
|
||||
// body the caller fills with text + (optionally) an EditBlockRow.
|
||||
// Returns { row, body } so the caller can append into body.
|
||||
// ──────────────────────────────────────────────────────────────────
|
||||
function buildAssistantRow() {
|
||||
const row = el("div", "trow trow-asst");
|
||||
row.innerHTML =
|
||||
'<div class="trow-asst-head">' +
|
||||
'<span class="trole role-asst">◆</span>' +
|
||||
'<span class="tpill tpill-model"> v4-flash </span>' +
|
||||
"</div>" +
|
||||
'<div class="trow-asst-body">' +
|
||||
'<span class="tbar-green">▎</span>' +
|
||||
'<div class="trow-asst-content"></div>' +
|
||||
"</div>";
|
||||
return { row, body: row.querySelector(".trow-asst-content") };
|
||||
}
|
||||
|
||||
// ──────────────────────────────────────────────────────────────────
|
||||
// EditBlockRow — rounded cyan border, filename in cyan bold, then
|
||||
// `- old` red and `+ new` green lines. NO literal SEARCH/REPLACE
|
||||
// markers (the model's text format is parsed; only the diff is
|
||||
// shown). Mirrors EditBlockRow in markdown.tsx.
|
||||
// ──────────────────────────────────────────────────────────────────
|
||||
function buildEditBlock(filename, oldLines, newLines) {
|
||||
const box = el("div", "tedit");
|
||||
const head = el("div", "tedit-head");
|
||||
head.appendChild(el("span", "tedit-filename", filename));
|
||||
box.appendChild(head);
|
||||
const diff = el("div", "tedit-diff");
|
||||
box.appendChild(diff);
|
||||
return { box, diff, oldLines, newLines };
|
||||
}
|
||||
|
||||
// ──────────────────────────────────────────────────────────────────
|
||||
// Info row — colored glyph + dim body. Used for pending + applied
|
||||
// status lines, mirrors EventLog.tsx role="info".
|
||||
// ──────────────────────────────────────────────────────────────────
|
||||
function buildInfoRow(glyph, glyphColor, body) {
|
||||
const row = el("div", "trow trow-info");
|
||||
const g = el("span", "tinfo-glyph", glyph);
|
||||
g.style.color = glyphColor;
|
||||
row.appendChild(g);
|
||||
row.appendChild(el("span", "tdim", " " + body));
|
||||
return row;
|
||||
}
|
||||
|
||||
// ──────────────────────────────────────────────────────────────────
|
||||
// Animate text into a target node, character by character.
|
||||
// ──────────────────────────────────────────────────────────────────
|
||||
async function typeInto(target, text, perChar, cancelled) {
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
target.appendChild(document.createTextNode(text[i]));
|
||||
const j = perChar * (0.85 + Math.random() * 0.3);
|
||||
const ch = text[i];
|
||||
const pause = /[,。、;:,.;:]/.test(ch) ? perChar * 4 : 0;
|
||||
// eslint-disable-next-line no-await-in-loop
|
||||
await sleep(j + pause);
|
||||
if (cancelled && cancelled()) return;
|
||||
}
|
||||
}
|
||||
|
||||
// Cancellation token — interrupts in-flight cycles when the user
|
||||
// toggles language or clicks replay so we don't double-render.
|
||||
let token = 0;
|
||||
|
||||
async function runCycle(root) {
|
||||
const myToken = ++token;
|
||||
const cancelled = () => myToken !== token;
|
||||
|
||||
root.classList.remove("trun-fade");
|
||||
root.innerHTML = "";
|
||||
|
||||
root.appendChild(buildHeader(1));
|
||||
|
||||
await sleep(400);
|
||||
if (cancelled()) return;
|
||||
|
||||
// 1. Live user prompt — types the question, then converts to a
|
||||
// permanent user row on submit.
|
||||
const userMsg = tr(
|
||||
"term.user",
|
||||
"users.ts findByEmail is case-sensitive — login fails"
|
||||
);
|
||||
const live = buildLiveUserRow();
|
||||
root.appendChild(live);
|
||||
await sleep(400);
|
||||
if (cancelled()) return;
|
||||
await typeInto(live._input, userMsg, 32, cancelled);
|
||||
if (cancelled()) return;
|
||||
await sleep(550);
|
||||
live._caret.remove();
|
||||
live.classList.add("trow-sent");
|
||||
|
||||
// 2. Tool pills appear one by one. Real summaries come from
|
||||
// summarizeToolResult() in summarize.ts — we hard-code the
|
||||
// representative output for this scene.
|
||||
await sleep(380);
|
||||
if (cancelled()) return;
|
||||
root.appendChild(
|
||||
buildToolRow(
|
||||
"search_files",
|
||||
"matched 2 files: src/users.ts, src/users.test.ts",
|
||||
"0.4s",
|
||||
"1"
|
||||
)
|
||||
);
|
||||
await sleep(560);
|
||||
if (cancelled()) return;
|
||||
root.appendChild(
|
||||
buildToolRow("read_file", "read src/users.ts (412 chars)", "0.2s", "2")
|
||||
);
|
||||
await sleep(640);
|
||||
if (cancelled()) return;
|
||||
|
||||
// 3. Assistant row — ◆ + model pill, then green-bordered body
|
||||
// containing the streamed text and the EditBlockRow.
|
||||
const a = buildAssistantRow();
|
||||
root.appendChild(a.row);
|
||||
await sleep(280);
|
||||
if (cancelled()) return;
|
||||
|
||||
const replyP = el("p", "tmd-p");
|
||||
a.body.appendChild(replyP);
|
||||
const replyMsg = tr(
|
||||
"term.found",
|
||||
"Found it. findByEmail uses === directly. Switching to lowercase normalization."
|
||||
);
|
||||
await typeInto(replyP, replyMsg, 18, cancelled);
|
||||
if (cancelled()) return;
|
||||
await sleep(360);
|
||||
|
||||
// 4. EditBlockRow — rounded cyan border with filename + colored
|
||||
// diff lines. No SEARCH/REPLACE markers.
|
||||
const eb = buildEditBlock(
|
||||
"src/users.ts",
|
||||
[" return users.find(u => u.email === email);"],
|
||||
[
|
||||
" const needle = email.toLowerCase();",
|
||||
" return users.find(u => u.email.toLowerCase() === needle);",
|
||||
]
|
||||
);
|
||||
a.body.appendChild(eb.box);
|
||||
await sleep(220);
|
||||
if (cancelled()) return;
|
||||
|
||||
for (const line of eb.oldLines) {
|
||||
const r = el("div", "tdiff tdiff-old", "- " + line);
|
||||
eb.diff.appendChild(r);
|
||||
// eslint-disable-next-line no-await-in-loop
|
||||
await sleep(180);
|
||||
if (cancelled()) return;
|
||||
}
|
||||
for (const line of eb.newLines) {
|
||||
const r = el("div", "tdiff tdiff-new", "+ " + line);
|
||||
eb.diff.appendChild(r);
|
||||
// eslint-disable-next-line no-await-in-loop
|
||||
await sleep(180);
|
||||
if (cancelled()) return;
|
||||
}
|
||||
await sleep(420);
|
||||
if (cancelled()) return;
|
||||
|
||||
// 5. Pending info row — slate `▸` + dim body. Real text from
|
||||
// formatPendingPreview() in edit-history.ts.
|
||||
root.appendChild(
|
||||
buildInfoRow(
|
||||
"▸",
|
||||
"#94a3b8",
|
||||
tr(
|
||||
"term.pending",
|
||||
"1 pending edit block(s) — /apply (or y) to commit · /discard (or n) to drop"
|
||||
)
|
||||
)
|
||||
);
|
||||
await sleep(1700);
|
||||
if (cancelled()) return;
|
||||
|
||||
// 6. /apply — second user turn. Live row, types `/apply`, then
|
||||
// transforms to a sent row. No tool pills (slash is local).
|
||||
const apply = buildLiveUserRow();
|
||||
root.appendChild(apply);
|
||||
await sleep(420);
|
||||
if (cancelled()) return;
|
||||
await typeInto(apply._input, "/apply", 75, cancelled);
|
||||
if (cancelled()) return;
|
||||
await sleep(380);
|
||||
apply._caret.remove();
|
||||
apply.classList.add("trow-sent");
|
||||
|
||||
// 7. Applied info rows — first the header, then the per-file line.
|
||||
// Mirrors formatEditResults() in edit-history.ts.
|
||||
await sleep(420);
|
||||
root.appendChild(
|
||||
buildInfoRow(
|
||||
"▸",
|
||||
"#94a3b8",
|
||||
"edit blocks: 1/1 applied — /undo to roll back, or `git diff` to review"
|
||||
)
|
||||
);
|
||||
const ok = el("div", "trow trow-info trow-info-detail");
|
||||
const gl = el("span", "tinfo-glyph", "✓");
|
||||
gl.style.color = "#4ade80";
|
||||
ok.appendChild(el("span", "tdim", " "));
|
||||
ok.appendChild(gl);
|
||||
ok.appendChild(el("span", "tdim", " applied src/users.ts"));
|
||||
root.appendChild(ok);
|
||||
|
||||
await sleep(2800);
|
||||
if (cancelled()) return;
|
||||
|
||||
// 8. Fade and loop.
|
||||
root.classList.add("trun-fade");
|
||||
await sleep(900);
|
||||
if (cancelled()) return;
|
||||
runCycle(root);
|
||||
}
|
||||
|
||||
// Reduced-motion fallback — paint the final scene without typing.
|
||||
function runStatic(root) {
|
||||
root.innerHTML = "";
|
||||
root.appendChild(buildHeader(1));
|
||||
root.appendChild(buildUserRow(tr("term.user", "")));
|
||||
root.appendChild(
|
||||
buildToolRow(
|
||||
"search_files",
|
||||
"matched 2 files: src/users.ts, src/users.test.ts",
|
||||
"0.4s",
|
||||
"1"
|
||||
)
|
||||
);
|
||||
root.appendChild(
|
||||
buildToolRow("read_file", "read src/users.ts (412 chars)", "0.2s", "2")
|
||||
);
|
||||
const a = buildAssistantRow();
|
||||
root.appendChild(a.row);
|
||||
const p = el("p", "tmd-p");
|
||||
p.textContent = tr("term.found", "");
|
||||
a.body.appendChild(p);
|
||||
const eb = buildEditBlock(
|
||||
"src/users.ts",
|
||||
[" return users.find(u => u.email === email);"],
|
||||
[
|
||||
" const needle = email.toLowerCase();",
|
||||
" return users.find(u => u.email.toLowerCase() === needle);",
|
||||
]
|
||||
);
|
||||
a.body.appendChild(eb.box);
|
||||
eb.oldLines.forEach((l) =>
|
||||
eb.diff.appendChild(el("div", "tdiff tdiff-old", "- " + l))
|
||||
);
|
||||
eb.newLines.forEach((l) =>
|
||||
eb.diff.appendChild(el("div", "tdiff tdiff-new", "+ " + l))
|
||||
);
|
||||
root.appendChild(buildInfoRow("▸", "#94a3b8", tr("term.pending", "")));
|
||||
}
|
||||
|
||||
function init() {
|
||||
const root = document.querySelector(ROOT_SEL);
|
||||
if (!root) return;
|
||||
|
||||
if (window.Reasonix && typeof window.Reasonix.onLangChange === "function") {
|
||||
window.Reasonix.onLangChange(() => runCycle(root));
|
||||
}
|
||||
// npm version arrives async after first paint — patch the header's
|
||||
// version pill in place so we don't have to re-run the whole
|
||||
// animation just to update one number.
|
||||
if (window.Reasonix && typeof window.Reasonix.onVersionChange === "function") {
|
||||
window.Reasonix.onVersionChange((v) => {
|
||||
const pill = root.querySelector(".tw-ver");
|
||||
if (pill) pill.textContent = "v" + v;
|
||||
});
|
||||
}
|
||||
|
||||
document.querySelectorAll(REPLAY_SEL).forEach((btn) => {
|
||||
btn.addEventListener("click", () => runCycle(root));
|
||||
});
|
||||
|
||||
const prm = window.matchMedia
|
||||
? window.matchMedia("(prefers-reduced-motion: reduce)")
|
||||
: null;
|
||||
if (prm && prm.matches) {
|
||||
runStatic(root);
|
||||
return;
|
||||
}
|
||||
|
||||
runCycle(root);
|
||||
}
|
||||
|
||||
window.Reasonix = window.Reasonix || {};
|
||||
window.Reasonix.term = {
|
||||
replay() {
|
||||
const root = document.querySelector(ROOT_SEL);
|
||||
if (root) runCycle(root);
|
||||
},
|
||||
};
|
||||
|
||||
if (document.readyState === "loading") {
|
||||
document.addEventListener("DOMContentLoaded", init);
|
||||
} else {
|
||||
init();
|
||||
}
|
||||
})();
|
||||
Generated
+1530
-555
File diff suppressed because it is too large.
Load diff
+37
-3
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "reasonix",
|
||||
"version": "0.5.18",
|
||||
"description": "DeepSeek-native agent framework: cache-first loop, R1 thought harvesting, tool-call repair.",
|
||||
"version": "0.16.0",
|
||||
"description": "DeepSeek-native coding agent: cache-first loop, flash-first cost control, tool-call repair.",
|
||||
"type": "module",
|
||||
"bin": {
|
||||
"reasonix": "dist/cli/index.js"
|
||||
@@ -18,11 +18,16 @@
|
||||
"files": [
|
||||
"dist",
|
||||
"data/deepseek-tokenizer.json.gz",
|
||||
"dashboard/index.html",
|
||||
"dashboard/app.js",
|
||||
"dashboard/app.css",
|
||||
"dashboard/codemirror.js",
|
||||
"README.md",
|
||||
"LICENSE"
|
||||
],
|
||||
"scripts": {
|
||||
"build": "tsup",
|
||||
"build:cm": "node scripts/bundle-codemirror.mjs",
|
||||
"dev": "tsx src/cli/index.ts",
|
||||
"chat": "tsx src/cli/index.ts chat",
|
||||
"test": "vitest run",
|
||||
@@ -31,8 +36,14 @@
|
||||
"lint:fix": "biome check --write src tests",
|
||||
"format": "biome format --write src tests",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"verify": "npm run lint && npm run typecheck && npm run test --silent",
|
||||
"prepare": "simple-git-hooks || true",
|
||||
"prepublishOnly": "npm run lint && npm run typecheck && npm run test && npm run build"
|
||||
},
|
||||
"simple-git-hooks": {
|
||||
"pre-commit": "npm run lint",
|
||||
"pre-push": "npm run verify"
|
||||
},
|
||||
"keywords": [
|
||||
"agent",
|
||||
"llm",
|
||||
@@ -62,12 +73,35 @@
|
||||
"ink": "^5.1.0",
|
||||
"ink-spinner": "^5.0.0",
|
||||
"ink-text-input": "^6.0.0",
|
||||
"react": "^18.3.1"
|
||||
"react": "^18.3.1",
|
||||
"string-width": "^7.2.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@biomejs/biome": "^1.9.4",
|
||||
"@codemirror/autocomplete": "^6.16.0",
|
||||
"@codemirror/commands": "^6.5.0",
|
||||
"@codemirror/lang-cpp": "^6.0.2",
|
||||
"@codemirror/lang-css": "^6.2.1",
|
||||
"@codemirror/lang-go": "^6.0.1",
|
||||
"@codemirror/lang-html": "^6.4.9",
|
||||
"@codemirror/lang-javascript": "^6.2.2",
|
||||
"@codemirror/lang-json": "^6.0.1",
|
||||
"@codemirror/lang-markdown": "^6.2.5",
|
||||
"@codemirror/lang-php": "^6.0.1",
|
||||
"@codemirror/lang-python": "^6.1.6",
|
||||
"@codemirror/lang-rust": "^6.0.1",
|
||||
"@codemirror/lang-sql": "^6.6.4",
|
||||
"@codemirror/lang-xml": "^6.1.0",
|
||||
"@codemirror/lang-yaml": "^6.1.1",
|
||||
"@codemirror/language": "^6.10.1",
|
||||
"@codemirror/search": "^6.5.6",
|
||||
"@codemirror/state": "^6.4.1",
|
||||
"@codemirror/theme-one-dark": "^6.1.2",
|
||||
"@codemirror/view": "^6.26.0",
|
||||
"@types/node": "^22.9.0",
|
||||
"@types/react": "^18.3.12",
|
||||
"esbuild": "^0.21.5",
|
||||
"simple-git-hooks": "^2.13.1",
|
||||
"tsup": "^8.3.5",
|
||||
"tsx": "^4.19.2",
|
||||
"typescript": "^5.6.3",
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Bundle every CodeMirror package the dashboard editor needs into one
|
||||
* local ESM file at dashboard/codemirror.js. Replaces the runtime
|
||||
* esm.sh imports — CDN multi-instance issues (different copies of
|
||||
* @lezer/highlight breaking tag identity, etc.) just go away once
|
||||
* everything ships in a single bundle.
|
||||
*
|
||||
* Run after bumping any @codemirror/* package version:
|
||||
* node scripts/bundle-codemirror.mjs
|
||||
*
|
||||
* The output is committed to the repo and shipped in the npm tarball.
|
||||
*/
|
||||
import { build } from "esbuild";
|
||||
import { mkdirSync, writeFileSync } from "node:fs";
|
||||
import { dirname, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url));
|
||||
const repoRoot = resolve(here, "..");
|
||||
const entryPath = resolve(repoRoot, "scripts/.cm-entry.mjs");
|
||||
const outPath = resolve(repoRoot, "dashboard/codemirror.js");
|
||||
|
||||
// Re-export every symbol the editor needs as a single flat record.
|
||||
// Same shape app.js's old loadCodeMirror() returned, so swapping the
|
||||
// runtime fetch for `import * as cm from "./codemirror.js"` is a
|
||||
// one-line change on the consumer side.
|
||||
const entry = `
|
||||
import { EditorState, Compartment } from "@codemirror/state";
|
||||
import {
|
||||
EditorView, keymap, lineNumbers, highlightActiveLine,
|
||||
highlightActiveLineGutter, drawSelection,
|
||||
} from "@codemirror/view";
|
||||
import {
|
||||
defaultKeymap, history, historyKeymap, indentWithTab,
|
||||
} from "@codemirror/commands";
|
||||
import {
|
||||
syntaxHighlighting, defaultHighlightStyle, bracketMatching,
|
||||
indentOnInput, foldGutter, foldKeymap,
|
||||
} from "@codemirror/language";
|
||||
import {
|
||||
closeBrackets, closeBracketsKeymap, autocompletion, completionKeymap,
|
||||
} from "@codemirror/autocomplete";
|
||||
import { searchKeymap, highlightSelectionMatches } from "@codemirror/search";
|
||||
import { oneDark } from "@codemirror/theme-one-dark";
|
||||
|
||||
import { javascript } from "@codemirror/lang-javascript";
|
||||
import { python } from "@codemirror/lang-python";
|
||||
import { markdown } from "@codemirror/lang-markdown";
|
||||
import { json } from "@codemirror/lang-json";
|
||||
import { html as htmlLang } from "@codemirror/lang-html";
|
||||
import { css } from "@codemirror/lang-css";
|
||||
import { rust } from "@codemirror/lang-rust";
|
||||
import { go } from "@codemirror/lang-go";
|
||||
import { cpp } from "@codemirror/lang-cpp";
|
||||
import { yaml } from "@codemirror/lang-yaml";
|
||||
import { sql } from "@codemirror/lang-sql";
|
||||
import { xml } from "@codemirror/lang-xml";
|
||||
import { php } from "@codemirror/lang-php";
|
||||
|
||||
export {
|
||||
EditorState, Compartment,
|
||||
EditorView, keymap, lineNumbers, highlightActiveLine,
|
||||
highlightActiveLineGutter, drawSelection,
|
||||
defaultKeymap, history, historyKeymap, indentWithTab,
|
||||
syntaxHighlighting, defaultHighlightStyle, bracketMatching,
|
||||
indentOnInput, foldGutter, foldKeymap,
|
||||
closeBrackets, closeBracketsKeymap, autocompletion, completionKeymap,
|
||||
searchKeymap, highlightSelectionMatches,
|
||||
oneDark,
|
||||
};
|
||||
|
||||
export const langs = {
|
||||
javascript,
|
||||
typescript: () => javascript({ typescript: true }),
|
||||
python,
|
||||
markdown,
|
||||
json,
|
||||
html: htmlLang,
|
||||
css,
|
||||
rust,
|
||||
go,
|
||||
cpp,
|
||||
yaml,
|
||||
sql,
|
||||
xml,
|
||||
php,
|
||||
};
|
||||
`;
|
||||
|
||||
mkdirSync(dirname(entryPath), { recursive: true });
|
||||
writeFileSync(entryPath, entry);
|
||||
|
||||
await build({
|
||||
entryPoints: [entryPath],
|
||||
outfile: outPath,
|
||||
bundle: true,
|
||||
format: "esm",
|
||||
target: "es2022",
|
||||
minify: true,
|
||||
legalComments: "none",
|
||||
logLevel: "info",
|
||||
});
|
||||
|
||||
console.log(`bundled → ${outPath}`);
|
||||
@@ -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,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,46 @@
|
||||
import { type WriteStream, chmodSync, createWriteStream, mkdirSync } from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
import type { Event } from "../core/events.js";
|
||||
import { sanitizeName, sessionsDir } from "../memory/session.js";
|
||||
import type { EventSink } from "../ports/event-sink.js";
|
||||
|
||||
export function eventLogPath(sessionName: string): string {
|
||||
return join(sessionsDir(), `${sanitizeName(sessionName)}.events.jsonl`);
|
||||
}
|
||||
|
||||
export class JsonlEventSink implements EventSink {
|
||||
private buffered = 0;
|
||||
|
||||
constructor(private readonly stream: WriteStream) {}
|
||||
|
||||
append(ev: Event): void {
|
||||
this.stream.write(`${JSON.stringify(ev)}\n`);
|
||||
this.buffered++;
|
||||
}
|
||||
|
||||
flush(): Promise<void> {
|
||||
return new Promise((resolve) => {
|
||||
if (this.buffered === 0) return resolve();
|
||||
this.stream.uncork();
|
||||
this.buffered = 0;
|
||||
resolve();
|
||||
});
|
||||
}
|
||||
|
||||
close(): Promise<void> {
|
||||
return new Promise((resolve) => {
|
||||
this.stream.end(() => resolve());
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export function openEventSink(path: string): JsonlEventSink {
|
||||
mkdirSync(dirname(path), { recursive: true });
|
||||
const stream = createWriteStream(path, { flags: "a" });
|
||||
try {
|
||||
chmodSync(path, 0o600);
|
||||
} catch {
|
||||
/* chmod no-op on Windows */
|
||||
}
|
||||
return new JsonlEventSink(stream);
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { existsSync, readFileSync } from "node:fs";
|
||||
import type { Event } from "../core/events.js";
|
||||
import type { EventSource } from "../ports/event-sink.js";
|
||||
import { eventLogPath } from "./event-sink-jsonl.js";
|
||||
|
||||
export function readEventLogFile(path: string): Event[] {
|
||||
if (!existsSync(path)) return [];
|
||||
const raw = readFileSync(path, "utf8");
|
||||
const out: Event[] = [];
|
||||
for (const line of raw.split(/\r?\n/)) {
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed) continue;
|
||||
try {
|
||||
const ev = JSON.parse(trimmed) as Event;
|
||||
if (ev && typeof ev === "object" && typeof (ev as { type?: unknown }).type === "string") {
|
||||
out.push(ev);
|
||||
}
|
||||
} catch {
|
||||
/* malformed mid-line write — best-effort skip */
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export class JsonlEventSource implements EventSource {
|
||||
async *read(sessionName: string): AsyncIterable<Event> {
|
||||
const events = readEventLogFile(eventLogPath(sessionName));
|
||||
for (const ev of events) yield ev;
|
||||
}
|
||||
}
|
||||
+243
-109
@@ -1,35 +1,12 @@
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
/** Expand `@path` mentions inline. Paths must resolve inside rootDir; escapes / oversize get a skip note, not content. */
|
||||
|
||||
import { type Dirent, existsSync, readFileSync, readdirSync, statSync } from "node:fs";
|
||||
import { readdir, stat } from "node:fs/promises";
|
||||
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",
|
||||
@@ -54,23 +31,7 @@ export interface ListFilesOptions {
|
||||
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).
|
||||
*/
|
||||
/** Sync on purpose — fits the TUI's single-turn-per-tick model. Skips dot-DIRS but keeps dotfiles. */
|
||||
export function listFilesSync(root: string, opts: ListFilesOptions = {}): string[] {
|
||||
return listFilesWithStatsSync(root, opts).map((e) => e.path);
|
||||
}
|
||||
@@ -82,15 +43,7 @@ export interface FileWithStats {
|
||||
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).
|
||||
*/
|
||||
/** Stat failures kept as `mtimeMs: 0` — entry still appears, sinks to bottom of 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);
|
||||
@@ -128,24 +81,84 @@ export function listFilesWithStatsSync(root: string, opts: ListFilesOptions = {}
|
||||
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.
|
||||
*/
|
||||
/** Parallel stat per directory — Windows stat syscalls are 3-5× slower than Linux. */
|
||||
export async function listFilesWithStatsAsync(
|
||||
root: string,
|
||||
opts: ListFilesOptions = {},
|
||||
): Promise<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 = async (dirAbs: string, dirRel: string): Promise<void> => {
|
||||
if (out.length >= maxResults) return;
|
||||
let entries: Dirent[];
|
||||
try {
|
||||
entries = await readdir(dirAbs, { withFileTypes: true });
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
entries.sort((a, b) => a.name.localeCompare(b.name));
|
||||
// Pull file stats for THIS directory in parallel before
|
||||
// recursing — readdir gave us all the names at once, may as
|
||||
// well issue all the stats at once too. Recursion stays
|
||||
// sequential so the alphabetical ordering of the merged list
|
||||
// matches the sync walk's contract.
|
||||
const fileEnts: Dirent[] = [];
|
||||
for (const ent of entries) {
|
||||
if (out.length >= maxResults) break;
|
||||
if (ent.isDirectory()) {
|
||||
if (ent.name.startsWith(".") || ignore.has(ent.name)) continue;
|
||||
// Drain pending file stats from THIS directory before
|
||||
// descending so the output order stays DFS-alphabetical.
|
||||
if (fileEnts.length > 0) {
|
||||
await statBatch(fileEnts, dirAbs, dirRel, out, maxResults);
|
||||
fileEnts.length = 0;
|
||||
if (out.length >= maxResults) return;
|
||||
}
|
||||
await walk(join(dirAbs, ent.name), dirRel ? `${dirRel}/${ent.name}` : ent.name);
|
||||
} else if (ent.isFile()) {
|
||||
fileEnts.push(ent);
|
||||
}
|
||||
}
|
||||
if (fileEnts.length > 0 && out.length < maxResults) {
|
||||
await statBatch(fileEnts, dirAbs, dirRel, out, maxResults);
|
||||
}
|
||||
};
|
||||
|
||||
await walk(rootAbs, "");
|
||||
return out;
|
||||
}
|
||||
|
||||
async function statBatch(
|
||||
ents: readonly Dirent[],
|
||||
dirAbs: string,
|
||||
dirRel: string,
|
||||
out: FileWithStats[],
|
||||
maxResults: number,
|
||||
): Promise<void> {
|
||||
const remaining = Math.max(0, maxResults - out.length);
|
||||
const batch = ents.slice(0, remaining);
|
||||
const stats = await Promise.all(
|
||||
batch.map((e) =>
|
||||
stat(join(dirAbs, e.name))
|
||||
.then((s) => s.mtimeMs)
|
||||
.catch(() => 0),
|
||||
),
|
||||
);
|
||||
for (let i = 0; i < batch.length; i++) {
|
||||
const ent = batch[i]!;
|
||||
out.push({
|
||||
path: dirRel ? `${dirRel}/${ent.name}` : ent.name,
|
||||
mtimeMs: stats[i] ?? 0,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/** Trailing-token only, anchored at end-of-input — distinct from `AT_MENTION_PATTERN` which scans all. */
|
||||
export const AT_PICKER_PREFIX = /(?:^|\s)@([a-zA-Z0-9_./\\-]*)$/;
|
||||
|
||||
/**
|
||||
* 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;
|
||||
@@ -163,31 +176,9 @@ 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,
|
||||
@@ -249,17 +240,7 @@ export function rankPickerCandidates(
|
||||
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.
|
||||
*/
|
||||
/** Word-boundary anchor rejects `@` embedded in emails / social handles; trailing `.` stripped before lookup. */
|
||||
export const AT_MENTION_PATTERN = /(?<=^|\s)@([a-zA-Z0-9_./\\-]+)/g;
|
||||
|
||||
export interface AtMentionExpansion {
|
||||
@@ -278,10 +259,6 @@ export interface AtMentionExpansion {
|
||||
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;
|
||||
@@ -290,11 +267,6 @@ export interface AtMentionOptions {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 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,
|
||||
@@ -395,3 +367,165 @@ const defaultFs: NonNullable<AtMentionOptions["fs"]> = {
|
||||
},
|
||||
read: (p) => readFileSync(p, "utf8"),
|
||||
};
|
||||
|
||||
// @url mentions — async sibling of @path. Matches `@http(s)://...` after a
|
||||
// word boundary, fetches each URL once per session (in-memory cache), and
|
||||
// appends a "Referenced URLs" block under the prompt the model sees. Uses
|
||||
// the same web-fetch + HTML-strip pipeline as the model's `web_fetch` tool
|
||||
// so a `@url` reference and a model-issued fetch produce identical content.
|
||||
|
||||
/** Trailing punctuation stripped separately — URLs legitimately contain `,` `.` `)` in query strings. */
|
||||
export const AT_URL_PATTERN = /(?<=^|\s)@(https?:\/\/\S+)/g;
|
||||
|
||||
/** Default cap on inlined URL body (chars). Matches DEFAULT_AT_MENTION_MAX_BYTES order-of-magnitude. */
|
||||
export const DEFAULT_AT_URL_MAX_CHARS = 32_000;
|
||||
|
||||
export interface AtUrlExpansion {
|
||||
/** The raw `@url` token as it appeared in the text. */
|
||||
token: string;
|
||||
/** Absolute URL (after trailing-punctuation strip). */
|
||||
url: string;
|
||||
/** True if content was inlined. False = skipped (reason in `skip`). */
|
||||
ok: boolean;
|
||||
/** Page title when extractable from `<title>`. */
|
||||
title?: string;
|
||||
/** Char count of the (post-truncation) inlined body. */
|
||||
chars?: number;
|
||||
/** True iff the original page exceeded `maxChars` and was clipped. */
|
||||
truncated?: boolean;
|
||||
/** Why the mention was skipped — set when ok=false. */
|
||||
skip?: "fetch-error" | "non-text" | "timeout" | "blocked";
|
||||
/** Free-form error message attached to skip outcomes. */
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export interface AtUrlOptions {
|
||||
/** Max chars of inlined body per URL. Default DEFAULT_AT_URL_MAX_CHARS. */
|
||||
maxChars?: number;
|
||||
/** Per-URL fetch timeout in ms. */
|
||||
timeoutMs?: number;
|
||||
fetcher?: (
|
||||
url: string,
|
||||
opts: { maxChars?: number; timeoutMs?: number; signal?: AbortSignal },
|
||||
) => Promise<{ url: string; title?: string; text: string; truncated: boolean }>;
|
||||
cache?: Map<string, AtUrlExpansion & { body?: string }>;
|
||||
/** Forward Esc/abort to the fetcher. */
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
export async function expandAtUrls(
|
||||
text: string,
|
||||
opts: AtUrlOptions = {},
|
||||
): Promise<{ text: string; expansions: AtUrlExpansion[] }> {
|
||||
const maxChars = opts.maxChars ?? DEFAULT_AT_URL_MAX_CHARS;
|
||||
const fetcher = opts.fetcher;
|
||||
if (!fetcher) {
|
||||
throw new Error("expandAtUrls: fetcher option is required (wire src/tools/web.ts:webFetch)");
|
||||
}
|
||||
|
||||
// De-dupe by URL so the same `@https://x.com` referenced twice fetches once.
|
||||
const seen = new Map<string, AtUrlExpansion>();
|
||||
const bodies = new Map<string, string>();
|
||||
const order: string[] = [];
|
||||
|
||||
for (const match of text.matchAll(AT_URL_PATTERN)) {
|
||||
const rawUrl = match[1] ?? "";
|
||||
const url = stripUrlTail(rawUrl);
|
||||
if (!url) continue;
|
||||
if (seen.has(url)) continue;
|
||||
|
||||
const cached = opts.cache?.get(url);
|
||||
if (cached) {
|
||||
seen.set(url, cached);
|
||||
if (cached.body) bodies.set(url, cached.body);
|
||||
order.push(url);
|
||||
continue;
|
||||
}
|
||||
|
||||
let expansion: AtUrlExpansion;
|
||||
let body = "";
|
||||
try {
|
||||
const page = await fetcher(url, {
|
||||
maxChars,
|
||||
timeoutMs: opts.timeoutMs,
|
||||
signal: opts.signal,
|
||||
});
|
||||
body = page.text;
|
||||
expansion = {
|
||||
token: `@${url}`,
|
||||
url,
|
||||
ok: true,
|
||||
title: page.title,
|
||||
chars: body.length,
|
||||
truncated: page.truncated,
|
||||
};
|
||||
} catch (err) {
|
||||
const message = (err as Error).message ?? String(err);
|
||||
// Tag a few common shapes so the UI can hint at causes.
|
||||
let skip: AtUrlExpansion["skip"] = "fetch-error";
|
||||
if (/aborted|timeout/i.test(message)) skip = "timeout";
|
||||
else if (/40\d|forbidden|access denied|captcha/i.test(message)) skip = "blocked";
|
||||
expansion = {
|
||||
token: `@${url}`,
|
||||
url,
|
||||
ok: false,
|
||||
skip,
|
||||
error: message,
|
||||
};
|
||||
}
|
||||
seen.set(url, expansion);
|
||||
if (body) bodies.set(url, body);
|
||||
if (opts.cache) opts.cache.set(url, { ...expansion, body });
|
||||
order.push(url);
|
||||
}
|
||||
|
||||
if (seen.size === 0) return { text, expansions: [] };
|
||||
|
||||
const expansions = order.map((u) => seen.get(u)!).filter(Boolean);
|
||||
const blocks: string[] = [];
|
||||
for (const ex of expansions) {
|
||||
if (ex.ok) {
|
||||
const titleAttr = ex.title ? ` title="${escapeAttr(ex.title)}"` : "";
|
||||
const truncTag = ex.truncated ? ' truncated="true"' : "";
|
||||
const body = bodies.get(ex.url) ?? "";
|
||||
blocks.push(`<url href="${ex.url}"${titleAttr}${truncTag}>\n${body}\n</url>`);
|
||||
} else {
|
||||
const reasonAttr = ex.skip ?? "fetch-error";
|
||||
blocks.push(`<url href="${ex.url}" skipped="${reasonAttr}" />`);
|
||||
}
|
||||
}
|
||||
const augmented = `${text}\n\n[Referenced URLs]\n${blocks.join("\n\n")}`;
|
||||
return { text: augmented, expansions };
|
||||
}
|
||||
|
||||
/** Only strips `.,;:!?` and unmatched close-brackets — internal path / query punctuation preserved. */
|
||||
export function stripUrlTail(raw: string): string {
|
||||
let s = raw;
|
||||
while (s.length > 0) {
|
||||
const last = s[s.length - 1]!;
|
||||
if (".,;:!?".includes(last)) {
|
||||
s = s.slice(0, -1);
|
||||
continue;
|
||||
}
|
||||
if (")]}>".includes(last)) {
|
||||
// Only strip if the matching open bracket isn't elsewhere in the
|
||||
// URL — avoids butchering legitimate `(thing)` query fragments.
|
||||
const open = ({ ")": "(", "]": "[", "}": "{", ">": "<" } as const)[
|
||||
last as ")" | "]" | "}" | ">"
|
||||
];
|
||||
if (!s.includes(open)) {
|
||||
s = s.slice(0, -1);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
function escapeAttr(s: string): string {
|
||||
return s
|
||||
.replace(/"/g, """)
|
||||
.replace(/[\r\n]+/g, " ")
|
||||
.trim();
|
||||
}
|
||||
+88
-31
@@ -9,17 +9,20 @@ import { bridgeMcpTools } from "../../mcp/registry.js";
|
||||
import { parseMcpSpec } from "../../mcp/spec.js";
|
||||
import { SseTransport } from "../../mcp/sse.js";
|
||||
import { type McpTransport, StdioTransport } from "../../mcp/stdio.js";
|
||||
import { StreamableHttpTransport } from "../../mcp/streamable-http.js";
|
||||
import {
|
||||
loadSessionMessages,
|
||||
rewriteSession,
|
||||
sessionPath as sessionPathOf,
|
||||
} from "../../session.js";
|
||||
} from "../../memory/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 {
|
||||
@@ -35,6 +38,13 @@ export interface ChatOptions {
|
||||
transcript?: string;
|
||||
harvest?: boolean;
|
||||
branch?: number;
|
||||
/**
|
||||
* Soft USD cap on session spend. Undefined → no cap (default).
|
||||
* The loop warns once at 80% and refuses to start a new turn at
|
||||
* 100%. Users can bump or clear via `/budget <usd>` / `/budget off`
|
||||
* mid-session.
|
||||
*/
|
||||
budgetUsd?: number;
|
||||
session?: string;
|
||||
/** Zero or more MCP server specs. Each: `"name=cmd args..."` or `"cmd args..."`. */
|
||||
mcp?: string[];
|
||||
@@ -51,11 +61,27 @@ 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;
|
||||
/**
|
||||
* `/cwd <path>` callback — re-registers every rootDir-dependent
|
||||
* native tool against the new path. Optional so embedders that
|
||||
* don't want live cwd switching can omit it (the slash command
|
||||
* then falls back to non-tool updates only).
|
||||
*/
|
||||
reregisterTools?: (rootDir: string) => void;
|
||||
};
|
||||
/** Skip the session picker — assume "Resume" (backwards-compatible auto-continue). */
|
||||
forceResume?: boolean;
|
||||
/** Skip the session picker — assume "New" (wipe the session file and start fresh). */
|
||||
forceNew?: boolean;
|
||||
/**
|
||||
* When true, suppress auto-launch of the embedded web dashboard.
|
||||
* Default behavior (false/undefined) is to boot it on mount so the
|
||||
* URL is visible in the status bar.
|
||||
*/
|
||||
noDashboard?: boolean;
|
||||
}
|
||||
|
||||
interface RootProps extends ChatOptions {
|
||||
@@ -101,39 +127,51 @@ 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}
|
||||
budgetUsd={appProps.budgetUsd}
|
||||
session={appProps.session}
|
||||
tools={tools}
|
||||
mcpSpecs={mcpSpecs}
|
||||
mcpServers={mcpServers}
|
||||
progressSink={progressSink}
|
||||
codeMode={appProps.codeMode}
|
||||
noDashboard={appProps.noDashboard}
|
||||
/>
|
||||
</KeystrokeProvider>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -170,7 +208,9 @@ export async function chatCommand(opts: ChatOptions): Promise<void> {
|
||||
const transport: McpTransport =
|
||||
spec.transport === "sse"
|
||||
? new SseTransport({ url: spec.url })
|
||||
: new StdioTransport({ command: spec.command, args: spec.args });
|
||||
: spec.transport === "streamable-http"
|
||||
? new StreamableHttpTransport({ url: spec.url })
|
||||
: new StdioTransport({ command: spec.command, args: spec.args });
|
||||
const mcp = new McpClient({ transport });
|
||||
await mcp.initialize();
|
||||
const bridge = await bridgeMcpTools(mcp, {
|
||||
@@ -200,7 +240,9 @@ export async function chatCommand(opts: ChatOptions): Promise<void> {
|
||||
}
|
||||
const label = spec.name ?? "anon";
|
||||
const source =
|
||||
spec.transport === "sse" ? spec.url : `${spec.command} ${spec.args.join(" ")}`;
|
||||
spec.transport === "sse" || spec.transport === "streamable-http"
|
||||
? spec.url
|
||||
: `${spec.command} ${spec.args.join(" ")}`;
|
||||
process.stderr.write(
|
||||
`▸ MCP[${label}]: ${bridge.registeredNames.length} tool(s) from ${source}\n`,
|
||||
);
|
||||
@@ -255,6 +297,10 @@ export async function chatCommand(opts: ChatOptions): Promise<void> {
|
||||
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
|
||||
@@ -274,6 +320,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}
|
||||
|
||||
+79
-20
@@ -19,10 +19,13 @@
|
||||
*/
|
||||
|
||||
import { basename, resolve } from "node:path";
|
||||
import { loadProjectShellAllowed } from "../../config.js";
|
||||
import { sanitizeName } from "../../session.js";
|
||||
import { loadEditMode, loadProjectShellAllowed } from "../../config.js";
|
||||
import { bootstrapSemanticSearchInCodeMode } from "../../index/semantic/tool.js";
|
||||
import { sanitizeName } from "../../memory/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";
|
||||
@@ -50,6 +53,14 @@ export interface CodeOptions {
|
||||
* reasoning surfaced explicitly can pass `--harvest`.
|
||||
*/
|
||||
harvest?: boolean;
|
||||
/**
|
||||
* Soft USD spend cap. Off by default. Same semantics as `chat`:
|
||||
* warns at 80%, refuses next turn at 100%. Mid-session adjustable
|
||||
* via `/budget <usd>` slash command.
|
||||
*/
|
||||
budgetUsd?: number;
|
||||
/** Suppress the auto-launched embedded web dashboard. */
|
||||
noDashboard?: boolean;
|
||||
}
|
||||
|
||||
export async function codeCommand(opts: CodeOptions = {}): Promise<void> {
|
||||
@@ -65,44 +76,92 @@ export async function codeCommand(opts: CodeOptions = {}): Promise<void> {
|
||||
// shape instead of the `string="false"` JSON-in-string array that
|
||||
// triggered R1's DSML hallucinations all through 0.4.x.
|
||||
const tools = new ToolRegistry();
|
||||
registerFilesystemTools(tools, { rootDir });
|
||||
registerShellTools(tools, {
|
||||
rootDir,
|
||||
// Per-project "always allow" list persisted from prior ShellConfirm
|
||||
// choices; merged on top of the built-in allowlist in shell.ts.
|
||||
// GETTER form — re-read every dispatch so a prefix the user adds
|
||||
// via ShellConfirm mid-session takes effect on the next shell call
|
||||
// instead of waiting for `/new` or a relaunch.
|
||||
extraAllowed: () => loadProjectShellAllowed(rootDir),
|
||||
});
|
||||
// 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();
|
||||
// Bundled re-registration so `/cwd <path>` can swap every rootDir-
|
||||
// dependent tool atomically. ToolRegistry.register is keyed by name
|
||||
// and overwrites in-place, so re-calling these against the existing
|
||||
// registry replaces the closures cleanly without disturbing tool
|
||||
// specs (names/descriptions/params don't reference rootDir, so the
|
||||
// prefix cache survives).
|
||||
const registerRootedTools = (root: string): void => {
|
||||
registerFilesystemTools(tools, { rootDir: root });
|
||||
registerShellTools(tools, {
|
||||
rootDir: root,
|
||||
// Per-project "always allow" list persisted from prior ShellConfirm
|
||||
// choices; merged on top of the built-in allowlist in shell.ts.
|
||||
// GETTER form — re-read every dispatch so a prefix the user adds
|
||||
// via ShellConfirm mid-session takes effect on the next shell call
|
||||
// instead of waiting for `/new` or a relaunch.
|
||||
extraAllowed: () => loadProjectShellAllowed(root),
|
||||
// `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,
|
||||
});
|
||||
// `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: root });
|
||||
};
|
||||
registerRootedTools(rootDir);
|
||||
// `submit_plan` is always in the spec list so the prefix cache stays
|
||||
// stable across plan-mode toggles (Pillar 1). The tool itself is a
|
||||
// no-op outside plan mode and throws `PlanProposedError` when the
|
||||
// user has `/plan`-enabled the session.
|
||||
registerPlanTool(tools);
|
||||
// `remember` / `forget` / `recall_memory` — cross-session user memory.
|
||||
// Project scope hashes off rootDir so switching projects gets a fresh
|
||||
// per-project memory store; the global scope is shared across runs.
|
||||
registerMemoryTools(tools, { projectRoot: rootDir });
|
||||
// `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);
|
||||
// `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.
|
||||
|
||||
// Bootstrap semantic_search. Silent: registers the tool when an
|
||||
// on-disk index already exists, skips entirely otherwise. Setup
|
||||
// happens via the explicit `reasonix index` command — never
|
||||
// by surprise on launch.
|
||||
const semantic = await bootstrapSemanticSearchInCodeMode(tools, rootDir);
|
||||
|
||||
process.stderr.write(
|
||||
`▸ reasonix code: rooted at ${rootDir}, session "${session ?? "(ephemeral)"}" · ${tools.size} native tool(s)\n`,
|
||||
`▸ reasonix code: rooted at ${rootDir}, session "${session ?? "(ephemeral)"}" · ${tools.size} native tool(s)${
|
||||
semantic.enabled ? " · semantic_search on" : ""
|
||||
}\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",
|
||||
model: opts.model ?? "deepseek-v4-flash",
|
||||
harvest: opts.harvest ?? false,
|
||||
system: codeSystemPrompt(rootDir),
|
||||
budgetUsd: opts.budgetUsd,
|
||||
system: codeSystemPrompt(rootDir, { hasSemanticSearch: semantic.enabled }),
|
||||
transcript: opts.transcript,
|
||||
session,
|
||||
seedTools: tools,
|
||||
codeMode: { rootDir },
|
||||
codeMode: { rootDir, jobs, reregisterTools: registerRootedTools },
|
||||
forceResume: opts.forceResume,
|
||||
forceNew: opts.forceNew,
|
||||
noDashboard: opts.noDashboard,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,333 @@
|
||||
/** Drafts via diff + recent log (style mimicry); commit uses `-F -` so multi-line bodies survive shell quoting. */
|
||||
|
||||
import { spawn, spawnSync } from "node:child_process";
|
||||
import { mkdtempSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { stdin, stdout } from "node:process";
|
||||
import { createInterface } from "node:readline/promises";
|
||||
import { DeepSeekClient } from "../../client.js";
|
||||
import { loadApiKey } from "../../config.js";
|
||||
import { loadDotenv } from "../../env.js";
|
||||
|
||||
export interface CommitOptions {
|
||||
/** Override the default model (deepseek-v4-flash). */
|
||||
model?: string;
|
||||
/** Skip the confirmation step — useful in scripts where the diff has been pre-reviewed. */
|
||||
yes?: boolean;
|
||||
}
|
||||
|
||||
const DEFAULT_MODEL = "deepseek-v4-flash";
|
||||
const DIFF_BYTE_CAP = 80 * 1024;
|
||||
const LOG_COUNT = 10;
|
||||
|
||||
const SYSTEM_PROMPT = `You draft git commit messages.
|
||||
|
||||
Output ONLY the commit message — no preamble, no \`\`\` fences, no "Here's a commit message:" lead-in. The first line of your output IS the commit subject.
|
||||
|
||||
Match the project's existing style:
|
||||
- Look at the recent commits provided. Mirror their voice, conventional-commit prefix usage (or absence), tense, length, body structure.
|
||||
- If recent commits use a "type(scope): summary" prefix, use it. If they don't, don't invent one.
|
||||
- Subject line: one line, ≤72 chars, imperative mood, no trailing period.
|
||||
- Body (optional): explain WHY when the diff isn't self-evident. Wrap at ~72 chars. Skip the body for trivial changes — repeating the subject in the body is noise.
|
||||
|
||||
The diff is the source of truth for what changed; describe THAT, not your guesses about the broader project. If the diff includes a deletion you can't explain from the surrounding context, name it but don't speculate about why.
|
||||
|
||||
No emojis unless the recent commits use them.
|
||||
No co-author trailers, no "Generated with X" footers.`;
|
||||
|
||||
function runGit(
|
||||
args: string[],
|
||||
opts: { input?: string } = {},
|
||||
): { stdout: string; stderr: string; status: number | null } {
|
||||
const result = spawnSync("git", args, {
|
||||
encoding: "utf8",
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
input: opts.input,
|
||||
maxBuffer: 32 * 1024 * 1024,
|
||||
});
|
||||
return {
|
||||
stdout: result.stdout ?? "",
|
||||
stderr: result.stderr ?? "",
|
||||
status: result.status,
|
||||
};
|
||||
}
|
||||
|
||||
function dieIfNotGitRepo(): void {
|
||||
const r = runGit(["rev-parse", "--is-inside-work-tree"]);
|
||||
if (r.status !== 0) {
|
||||
process.stderr.write("reasonix commit: not inside a git repository.\n");
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
interface DiffResult {
|
||||
diff: string;
|
||||
source: "staged" | "working-tree";
|
||||
truncated: boolean;
|
||||
}
|
||||
|
||||
function readDiff(): DiffResult | null {
|
||||
const staged = runGit(["diff", "--staged", "--no-color"]);
|
||||
if (staged.status !== 0) {
|
||||
process.stderr.write(`reasonix commit: git diff --staged failed: ${staged.stderr.trim()}\n`);
|
||||
process.exit(1);
|
||||
}
|
||||
if (staged.stdout.trim().length > 0) {
|
||||
return capDiff(staged.stdout, "staged");
|
||||
}
|
||||
const wt = runGit(["diff", "--no-color"]);
|
||||
if (wt.stdout.trim().length === 0) {
|
||||
return null;
|
||||
}
|
||||
return capDiff(wt.stdout, "working-tree");
|
||||
}
|
||||
|
||||
function capDiff(raw: string, source: "staged" | "working-tree"): DiffResult {
|
||||
if (raw.length <= DIFF_BYTE_CAP) {
|
||||
return { diff: raw, source, truncated: false };
|
||||
}
|
||||
const head = raw.slice(0, Math.floor(DIFF_BYTE_CAP * 0.7));
|
||||
const tail = raw.slice(-Math.floor(DIFF_BYTE_CAP * 0.3));
|
||||
return {
|
||||
diff: `${head}\n\n[… ${raw.length - DIFF_BYTE_CAP} bytes of diff truncated …]\n\n${tail}`,
|
||||
source,
|
||||
truncated: true,
|
||||
};
|
||||
}
|
||||
|
||||
function readRecentCommits(): string {
|
||||
const r = runGit(["log", `-${LOG_COUNT}`, "--no-merges", "--format=%s%n%b%n---END---"]);
|
||||
if (r.status !== 0) {
|
||||
// Repo may not have any commits yet (initial commit case). Don't
|
||||
// fail — let the model work from the diff alone.
|
||||
return "";
|
||||
}
|
||||
return r.stdout.trim();
|
||||
}
|
||||
|
||||
async function draftMessage(
|
||||
client: DeepSeekClient,
|
||||
model: string,
|
||||
diff: DiffResult,
|
||||
recentCommits: string,
|
||||
): Promise<string> {
|
||||
const userParts: string[] = [];
|
||||
if (recentCommits) {
|
||||
userParts.push(`Recent commits (style reference):\n\n${recentCommits}`);
|
||||
}
|
||||
if (diff.source === "working-tree") {
|
||||
userParts.push(
|
||||
"(NOTE: diff is from the working tree, not the staging area — nothing is staged yet. The user will stage selectively after seeing the draft.)",
|
||||
);
|
||||
}
|
||||
userParts.push(`Diff to summarize:\n\n${diff.diff}`);
|
||||
|
||||
const resp = await client.chat({
|
||||
model,
|
||||
messages: [
|
||||
{ role: "system", content: SYSTEM_PROMPT },
|
||||
{ role: "user", content: userParts.join("\n\n") },
|
||||
],
|
||||
temperature: 0.2,
|
||||
});
|
||||
return stripCodeFences(resp.content.trim());
|
||||
}
|
||||
|
||||
function stripCodeFences(s: string): string {
|
||||
// Some models still wrap output in ``` despite the system prompt
|
||||
// telling them not to. Strip a single leading + trailing fence pair
|
||||
// if present. Only operates on a wrapping pair — internal fences
|
||||
// (a code block inside the body) stay.
|
||||
const trimmed = s.trim();
|
||||
const fenceOpen = /^```[a-zA-Z]*\n/;
|
||||
const fenceClose = /\n?```$/;
|
||||
if (fenceOpen.test(trimmed) && fenceClose.test(trimmed)) {
|
||||
return trimmed.replace(fenceOpen, "").replace(fenceClose, "").trim();
|
||||
}
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
function printDraft(message: string): void {
|
||||
const sep = "─".repeat(60);
|
||||
process.stdout.write(`\n${sep}\n${message}\n${sep}\n\n`);
|
||||
}
|
||||
|
||||
async function promptChoice(): Promise<"accept" | "regen" | "edit" | "cancel"> {
|
||||
const rl = createInterface({ input: stdin, output: stdout });
|
||||
try {
|
||||
const answer = await rl.question("[a]ccept / [r]egenerate / [e]dit / [c]ancel: ");
|
||||
const k = answer.trim().toLowerCase();
|
||||
if (k === "" || k === "a" || k === "y" || k === "yes") return "accept";
|
||||
if (k === "r" || k === "regen" || k === "regenerate") return "regen";
|
||||
if (k === "e" || k === "edit") return "edit";
|
||||
return "cancel";
|
||||
} finally {
|
||||
rl.close();
|
||||
}
|
||||
}
|
||||
|
||||
function editInExternal(initial: string): string | null {
|
||||
const editor = process.env.GIT_EDITOR ?? process.env.VISUAL ?? process.env.EDITOR;
|
||||
if (!editor) {
|
||||
process.stderr.write(
|
||||
"reasonix commit: no $EDITOR / $VISUAL / $GIT_EDITOR set — can't open editor. Pick [a]ccept and `git commit --amend` afterwards.\n",
|
||||
);
|
||||
return null;
|
||||
}
|
||||
const dir = mkdtempSync(join(tmpdir(), "reasonix-commit-"));
|
||||
const path = join(dir, "COMMIT_EDITMSG");
|
||||
writeFileSync(path, initial, "utf8");
|
||||
// spawnSync with shell:true is required so $EDITOR strings like
|
||||
// `code --wait` work — they're shell command lines, not argv tuples.
|
||||
// The trust boundary is the user's own env var; matches how git
|
||||
// itself launches editors.
|
||||
const result = spawnSync(`${editor} "${path}"`, {
|
||||
stdio: "inherit",
|
||||
shell: true,
|
||||
});
|
||||
if (result.status !== 0) {
|
||||
try {
|
||||
unlinkSync(path);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
process.stderr.write(
|
||||
`reasonix commit: editor exited ${result.status} — keeping prior draft.\n`,
|
||||
);
|
||||
return null;
|
||||
}
|
||||
let edited: string;
|
||||
try {
|
||||
edited = readFileSync(path, "utf8");
|
||||
} catch {
|
||||
return null;
|
||||
} finally {
|
||||
try {
|
||||
unlinkSync(path);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
// Strip git's standard `# …` comment lines, even though we didn't
|
||||
// emit any — a user habituated to `git commit` may add `#`-prefixed
|
||||
// notes by reflex.
|
||||
const cleaned = edited
|
||||
.split(/\r?\n/)
|
||||
.filter((line) => !/^\s*#/.test(line))
|
||||
.join("\n")
|
||||
.trim();
|
||||
return cleaned || null;
|
||||
}
|
||||
|
||||
function commitWithMessage(message: string): void {
|
||||
// -F - reads the message from stdin, sidestepping shell quoting and
|
||||
// letting multi-line bodies through cleanly. Inherit stdio so the
|
||||
// user sees git's own confirmation / pre-commit hook output.
|
||||
const child = spawn("git", ["commit", "-F", "-"], {
|
||||
stdio: ["pipe", "inherit", "inherit"],
|
||||
});
|
||||
child.stdin.write(message);
|
||||
child.stdin.end();
|
||||
child.on("close", (code) => {
|
||||
if (code !== 0) {
|
||||
process.stderr.write(`reasonix commit: git commit exited ${code}.\n`);
|
||||
process.exit(code ?? 1);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export async function commitCommand(opts: CommitOptions = {}): Promise<void> {
|
||||
loadDotenv();
|
||||
dieIfNotGitRepo();
|
||||
|
||||
const apiKey = loadApiKey() ?? process.env.DEEPSEEK_API_KEY;
|
||||
if (!apiKey) {
|
||||
process.stderr.write(
|
||||
"reasonix commit: DEEPSEEK_API_KEY not set. Run `reasonix setup` to save one, or export it.\n",
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const diff = readDiff();
|
||||
if (!diff) {
|
||||
process.stderr.write(
|
||||
"reasonix commit: no staged changes and working tree is clean — nothing to commit.\n",
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
if (diff.source === "working-tree") {
|
||||
process.stderr.write(
|
||||
"reasonix commit: nothing staged — drafting from working-tree diff. Stage your changes and re-run, or use the draft as a starting point.\n",
|
||||
);
|
||||
}
|
||||
if (diff.truncated) {
|
||||
process.stderr.write(
|
||||
"reasonix commit: diff exceeded 80KB; head + tail sent to the model. Large diffs often produce vague drafts — consider committing in smaller chunks.\n",
|
||||
);
|
||||
}
|
||||
|
||||
const client = new DeepSeekClient({ apiKey });
|
||||
const model = opts.model ?? DEFAULT_MODEL;
|
||||
const recentCommits = readRecentCommits();
|
||||
|
||||
let message = "";
|
||||
let firstPass = true;
|
||||
while (true) {
|
||||
if (firstPass) {
|
||||
process.stdout.write("Drafting commit message…\n");
|
||||
} else {
|
||||
process.stdout.write("Regenerating…\n");
|
||||
}
|
||||
firstPass = false;
|
||||
try {
|
||||
message = await draftMessage(client, model, diff, recentCommits);
|
||||
} catch (err) {
|
||||
process.stderr.write(`reasonix commit: model call failed — ${(err as Error).message}\n`);
|
||||
process.exit(1);
|
||||
}
|
||||
if (!message) {
|
||||
process.stderr.write("reasonix commit: model returned an empty draft. Try again.\n");
|
||||
process.exit(1);
|
||||
}
|
||||
printDraft(message);
|
||||
|
||||
if (opts.yes) break;
|
||||
if (diff.source === "working-tree") {
|
||||
// Refuse to commit a working-tree-derived draft — the staging
|
||||
// area is empty so `git commit` would fail anyway. Print the
|
||||
// draft so the user can copy it; exit 0 because we did our job.
|
||||
process.stdout.write(
|
||||
"(no staged changes — draft printed above for you to copy. Stage with `git add` and re-run to commit.)\n",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const choice = await promptChoice();
|
||||
if (choice === "accept") break;
|
||||
if (choice === "cancel") {
|
||||
process.stderr.write("commit cancelled.\n");
|
||||
return;
|
||||
}
|
||||
if (choice === "edit") {
|
||||
const edited = editInExternal(message);
|
||||
if (edited) {
|
||||
message = edited;
|
||||
printDraft(message);
|
||||
// Re-prompt: the user may want to edit again, accept, etc.
|
||||
const next = await promptChoice();
|
||||
if (next === "accept") break;
|
||||
if (next === "cancel") {
|
||||
process.stderr.write("commit cancelled.\n");
|
||||
return;
|
||||
}
|
||||
// next is "regen" or another "edit" — fall through to the
|
||||
// loop top to re-draft (regen) or land back at this branch.
|
||||
}
|
||||
// editor returned no edit — loop top will regen by default.
|
||||
}
|
||||
// Anything else (regen, or unsuccessful edit) → loop top redraws.
|
||||
}
|
||||
|
||||
commitWithMessage(message);
|
||||
}
|
||||
@@ -2,8 +2,8 @@ import { writeFileSync } from "node:fs";
|
||||
import { basename } from "node:path";
|
||||
import { render } from "ink";
|
||||
import React from "react";
|
||||
import { diffTranscripts, renderMarkdown, renderSummaryTable } from "../../diff.js";
|
||||
import { readTranscript } from "../../transcript.js";
|
||||
import { diffTranscripts, renderMarkdown, renderSummaryTable } from "../../transcript/diff.js";
|
||||
import { readTranscript } from "../../transcript/log.js";
|
||||
import { DiffApp } from "../ui/DiffApp.js";
|
||||
|
||||
export interface DiffOptions {
|
||||
@@ -18,13 +18,6 @@ export interface DiffOptions {
|
||||
tui?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compare two transcripts. Three output paths, picked in order:
|
||||
* - If --md is passed: write the markdown report. Also prints the stdout
|
||||
* summary so the user sees what was exported.
|
||||
* - If --print, no TTY, or --md (see above): stdout summary table.
|
||||
* - Otherwise: interactive Ink TUI with split-pane + n/N divergence jump.
|
||||
*/
|
||||
export async function diffCommand(opts: DiffOptions): Promise<void> {
|
||||
const aParsed = readTranscript(opts.a);
|
||||
const bParsed = readTranscript(opts.b);
|
||||
|
||||
@@ -0,0 +1,358 @@
|
||||
/** Plain-text (not Ink) — must work when everything else is broken. fail → exit 1; warn → exit 0. */
|
||||
|
||||
import { existsSync, statSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
import { DeepSeekClient } from "../../client.js";
|
||||
import { defaultConfigPath, readConfig } from "../../config.js";
|
||||
import { loadDotenv } from "../../env.js";
|
||||
import { loadHooks } from "../../hooks.js";
|
||||
import { indexExists } from "../../index/semantic/builder.js";
|
||||
import { checkOllamaStatus } from "../../index/semantic/ollama-launcher.js";
|
||||
import { listSessions } from "../../memory/session.js";
|
||||
import { VERSION } from "../../version.js";
|
||||
|
||||
type Level = "ok" | "warn" | "fail";
|
||||
|
||||
interface Check {
|
||||
label: string;
|
||||
level: Level;
|
||||
detail: string;
|
||||
}
|
||||
|
||||
const TTY = process.stdout.isTTY && process.env.TERM !== "dumb";
|
||||
|
||||
function color(text: string, code: string): string {
|
||||
if (!TTY) return text;
|
||||
return `\x1b[${code}m${text}\x1b[0m`;
|
||||
}
|
||||
|
||||
function badge(level: Level): string {
|
||||
if (level === "ok") return color("✓", "32");
|
||||
if (level === "warn") return color("⚠", "33");
|
||||
return color("✗", "31");
|
||||
}
|
||||
|
||||
function tail4(s: string): string {
|
||||
return s.length <= 4 ? s : `…${s.slice(-4)}`;
|
||||
}
|
||||
|
||||
function fmtBytes(n: number): string {
|
||||
if (n < 1024) return `${n} B`;
|
||||
if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
|
||||
return `${(n / 1024 / 1024).toFixed(1)} MB`;
|
||||
}
|
||||
|
||||
async function checkApiKey(): Promise<Check> {
|
||||
const fromEnv = process.env.DEEPSEEK_API_KEY;
|
||||
if (fromEnv) {
|
||||
return {
|
||||
label: "api key ",
|
||||
level: "ok",
|
||||
detail: `set via env DEEPSEEK_API_KEY (${tail4(fromEnv)})`,
|
||||
};
|
||||
}
|
||||
try {
|
||||
const cfg = readConfig();
|
||||
if (cfg.apiKey) {
|
||||
return {
|
||||
label: "api key ",
|
||||
level: "ok",
|
||||
detail: `from ${defaultConfigPath()} (${tail4(cfg.apiKey)})`,
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
/* fall through */
|
||||
}
|
||||
return {
|
||||
label: "api key ",
|
||||
level: "fail",
|
||||
detail:
|
||||
"not set — `reasonix setup` to save one, or export DEEPSEEK_API_KEY. Get a key at https://platform.deepseek.com/api_keys",
|
||||
};
|
||||
}
|
||||
|
||||
async function checkConfig(): Promise<Check> {
|
||||
const path = defaultConfigPath();
|
||||
if (!existsSync(path)) {
|
||||
return {
|
||||
label: "config ",
|
||||
level: "warn",
|
||||
detail: "missing — running with library defaults. `reasonix setup` writes one.",
|
||||
};
|
||||
}
|
||||
try {
|
||||
const cfg = readConfig(path);
|
||||
const parts: string[] = [];
|
||||
if (cfg.preset) parts.push(`preset=${cfg.preset}`);
|
||||
if (cfg.editMode) parts.push(`editMode=${cfg.editMode}`);
|
||||
if (cfg.mcp && cfg.mcp.length > 0) parts.push(`mcp=${cfg.mcp.length}`);
|
||||
return {
|
||||
label: "config ",
|
||||
level: "ok",
|
||||
detail: `${path}${parts.length ? ` (${parts.join(", ")})` : ""}`,
|
||||
};
|
||||
} catch (err) {
|
||||
return {
|
||||
label: "config ",
|
||||
level: "fail",
|
||||
detail: `${path} unreadable — ${(err as Error).message}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async function checkApiReach(): Promise<Check> {
|
||||
const key = process.env.DEEPSEEK_API_KEY ?? readConfig().apiKey;
|
||||
if (!key) {
|
||||
return {
|
||||
label: "api reach ",
|
||||
level: "warn",
|
||||
detail: "skipped — no api key to test with",
|
||||
};
|
||||
}
|
||||
try {
|
||||
const client = new DeepSeekClient({ apiKey: key });
|
||||
const ctl = new AbortController();
|
||||
const timer = setTimeout(() => ctl.abort(), 8_000);
|
||||
let balance: Awaited<ReturnType<DeepSeekClient["getBalance"]>>;
|
||||
try {
|
||||
balance = await client.getBalance({ signal: ctl.signal });
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
if (!balance) {
|
||||
return {
|
||||
label: "api reach ",
|
||||
level: "fail",
|
||||
detail: "/user/balance returned null — auth failed or network blocked",
|
||||
};
|
||||
}
|
||||
if (!balance.is_available) {
|
||||
const info = balance.balance_infos[0];
|
||||
return {
|
||||
label: "api reach ",
|
||||
level: "warn",
|
||||
detail: `account flagged not-available${info ? ` (${info.total_balance} ${info.currency})` : ""} — top up or check your dashboard`,
|
||||
};
|
||||
}
|
||||
const info = balance.balance_infos[0];
|
||||
return {
|
||||
label: "api reach ",
|
||||
level: "ok",
|
||||
detail: info
|
||||
? `/user/balance ok — ${info.total_balance} ${info.currency}`
|
||||
: "/user/balance ok",
|
||||
};
|
||||
} catch (err) {
|
||||
return {
|
||||
label: "api reach ",
|
||||
level: "fail",
|
||||
detail: `${(err as Error).message}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async function checkTokenizer(): Promise<Check> {
|
||||
// The tokenizer file is the gzipped vocab shipped under data/. We
|
||||
// resolve relative to the package's dist/ rather than process.cwd()
|
||||
// — the same logic the runtime uses when loading on first count.
|
||||
const candidates = [
|
||||
join(
|
||||
dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, "$1")),
|
||||
"..",
|
||||
"..",
|
||||
"..",
|
||||
"data",
|
||||
"deepseek-tokenizer.json.gz",
|
||||
),
|
||||
join(process.cwd(), "data", "deepseek-tokenizer.json.gz"),
|
||||
];
|
||||
for (const p of candidates) {
|
||||
if (existsSync(p)) {
|
||||
try {
|
||||
const stat = statSync(p);
|
||||
return {
|
||||
label: "tokenizer ",
|
||||
level: "ok",
|
||||
detail: `${p} (${fmtBytes(stat.size)})`,
|
||||
};
|
||||
} catch {
|
||||
/* try next */
|
||||
}
|
||||
}
|
||||
}
|
||||
return {
|
||||
label: "tokenizer ",
|
||||
level: "warn",
|
||||
detail:
|
||||
"data/deepseek-tokenizer.json.gz not found — token counts will fall back to char heuristics",
|
||||
};
|
||||
}
|
||||
|
||||
async function checkSessions(): Promise<Check> {
|
||||
try {
|
||||
const list = listSessions();
|
||||
if (list.length === 0) {
|
||||
return {
|
||||
label: "sessions ",
|
||||
level: "ok",
|
||||
detail: "0 saved",
|
||||
};
|
||||
}
|
||||
const totalBytes = list.reduce((s, e) => s + e.size, 0);
|
||||
const oldest = list[list.length - 1]!;
|
||||
const ageDays = Math.floor((Date.now() - oldest.mtime.getTime()) / (24 * 60 * 60 * 1000));
|
||||
const stale = list.filter(
|
||||
(e) => Date.now() - e.mtime.getTime() >= 90 * 24 * 60 * 60 * 1000,
|
||||
).length;
|
||||
const detail = `${list.length} saved · ${fmtBytes(totalBytes)} · oldest ${ageDays}d`;
|
||||
if (stale > 0) {
|
||||
return {
|
||||
label: "sessions ",
|
||||
level: "warn",
|
||||
detail: `${detail} · ${stale} idle ≥90d (run /prune-sessions)`,
|
||||
};
|
||||
}
|
||||
return { label: "sessions ", level: "ok", detail };
|
||||
} catch (err) {
|
||||
return {
|
||||
label: "sessions ",
|
||||
level: "warn",
|
||||
detail: `cannot list — ${(err as Error).message}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async function checkHooks(projectRoot: string): Promise<Check> {
|
||||
try {
|
||||
const all = loadHooks({ projectRoot });
|
||||
const global = all.filter((h) => h.scope === "global").length;
|
||||
const project = all.filter((h) => h.scope === "project").length;
|
||||
return {
|
||||
label: "hooks ",
|
||||
level: "ok",
|
||||
detail: `${global} global, ${project} project`,
|
||||
};
|
||||
} catch (err) {
|
||||
return {
|
||||
label: "hooks ",
|
||||
level: "warn",
|
||||
detail: `couldn't parse settings.json — ${(err as Error).message}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async function checkOllama(projectRoot: string): Promise<Check> {
|
||||
// Ollama is only meaningful when an index has been built — otherwise
|
||||
// the daemon being down is just noise. Skip the check entirely on
|
||||
// projects that don't use semantic search.
|
||||
let exists = false;
|
||||
try {
|
||||
exists = await indexExists(projectRoot);
|
||||
} catch {
|
||||
/* treat as no index */
|
||||
}
|
||||
if (!exists) {
|
||||
return {
|
||||
label: "ollama ",
|
||||
level: "ok",
|
||||
detail: "not in use (no semantic index built; `reasonix index` to enable)",
|
||||
};
|
||||
}
|
||||
try {
|
||||
const status = await checkOllamaStatus(process.env.REASONIX_EMBED_MODEL ?? "nomic-embed-text");
|
||||
if (!status.binaryFound) {
|
||||
return {
|
||||
label: "ollama ",
|
||||
level: "warn",
|
||||
detail: "binary not on PATH — semantic_search will fail; install from https://ollama.com",
|
||||
};
|
||||
}
|
||||
if (!status.daemonRunning) {
|
||||
return {
|
||||
label: "ollama ",
|
||||
level: "warn",
|
||||
detail: "daemon not running — `ollama serve` (or just call /semantic in TUI to auto-start)",
|
||||
};
|
||||
}
|
||||
if (!status.modelPulled) {
|
||||
return {
|
||||
label: "ollama ",
|
||||
level: "warn",
|
||||
detail: `model ${status.modelName} not pulled — \`ollama pull ${status.modelName}\``,
|
||||
};
|
||||
}
|
||||
return {
|
||||
label: "ollama ",
|
||||
level: "ok",
|
||||
detail: `daemon up · model ${status.modelName} ready`,
|
||||
};
|
||||
} catch (err) {
|
||||
return {
|
||||
label: "ollama ",
|
||||
level: "warn",
|
||||
detail: `probe failed — ${(err as Error).message}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async function checkProject(projectRoot: string): Promise<Check> {
|
||||
// Heuristic: a "real" project has either .git, REASONIX.md, or
|
||||
// package.json. Lacking all three, `reasonix code` still works but
|
||||
// @-mentions and the project-memory pin won't surface much.
|
||||
const markers = [".git", "REASONIX.md", "package.json", "pyproject.toml", "Cargo.toml", "go.mod"];
|
||||
const found = markers.filter((m) => existsSync(join(projectRoot, m)));
|
||||
if (found.length === 0) {
|
||||
return {
|
||||
label: "project ",
|
||||
level: "warn",
|
||||
detail: `${projectRoot} has none of: ${markers.slice(0, 3).join(", ")} … — \`reasonix code\` will still run, but @-mentions and project memory have nothing to anchor`,
|
||||
};
|
||||
}
|
||||
return {
|
||||
label: "project ",
|
||||
level: "ok",
|
||||
detail: `${projectRoot} (${found.join(", ")})`,
|
||||
};
|
||||
}
|
||||
|
||||
export async function doctorCommand(): Promise<void> {
|
||||
loadDotenv();
|
||||
|
||||
const projectRoot = resolve(process.cwd());
|
||||
console.log(`${color(`reasonix ${VERSION} · doctor`, "1")} (cwd: ${projectRoot})`);
|
||||
console.log(` home: ${homedir()}`);
|
||||
console.log("");
|
||||
|
||||
// Run independent checks in parallel — saves ~5s when api-reach has
|
||||
// to time out. Each handler swallows its own throws into a `fail`
|
||||
// result so a thrown promise can't kill the whole report.
|
||||
const checks = await Promise.all([
|
||||
checkApiKey(),
|
||||
checkConfig(),
|
||||
checkApiReach(),
|
||||
checkTokenizer(),
|
||||
checkSessions(),
|
||||
checkHooks(projectRoot),
|
||||
checkOllama(projectRoot),
|
||||
checkProject(projectRoot),
|
||||
]);
|
||||
|
||||
for (const c of checks) {
|
||||
console.log(` ${badge(c.level)} ${c.label} ${c.detail}`);
|
||||
}
|
||||
|
||||
const ok = checks.filter((c) => c.level === "ok").length;
|
||||
const warn = checks.filter((c) => c.level === "warn").length;
|
||||
const fail = checks.filter((c) => c.level === "fail").length;
|
||||
console.log("");
|
||||
const summary = `${ok} ok · ${warn} warn · ${fail} fail`;
|
||||
if (fail > 0) {
|
||||
console.log(color(summary, "31"));
|
||||
process.exit(1);
|
||||
} else if (warn > 0) {
|
||||
console.log(color(summary, "33"));
|
||||
} else {
|
||||
console.log(color(summary, "32"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
import { eventLogPath } from "../../adapters/event-sink-jsonl.js";
|
||||
import { readEventLogFile } from "../../adapters/event-source-jsonl.js";
|
||||
import type { Event } from "../../core/events.js";
|
||||
import { replay as replayReducers } from "../../core/reducers.js";
|
||||
|
||||
export interface EventsOptions {
|
||||
name: string;
|
||||
type?: string;
|
||||
since?: number;
|
||||
tail?: number;
|
||||
json?: boolean;
|
||||
projection?: boolean;
|
||||
}
|
||||
|
||||
export function eventsCommand(opts: EventsOptions): void {
|
||||
const path = eventLogPath(opts.name);
|
||||
let events = readEventLogFile(path);
|
||||
|
||||
if (events.length === 0) {
|
||||
console.error(`no events for session "${opts.name}"`);
|
||||
console.error(`looked at: ${path}`);
|
||||
console.error("(sessions auto-create the sidecar on first turn — has this session run yet?)");
|
||||
process.exit(1);
|
||||
return;
|
||||
}
|
||||
|
||||
if (opts.type) events = events.filter((e) => e.type === opts.type);
|
||||
if (opts.since !== undefined && Number.isFinite(opts.since)) {
|
||||
events = events.filter((e) => e.id >= opts.since!);
|
||||
}
|
||||
if (opts.tail !== undefined && Number.isFinite(opts.tail) && opts.tail > 0) {
|
||||
events = events.slice(-opts.tail);
|
||||
}
|
||||
|
||||
if (opts.projection) {
|
||||
const p = replayReducers(events);
|
||||
console.log(JSON.stringify(p, mapReplacer, 2));
|
||||
return;
|
||||
}
|
||||
|
||||
if (opts.json) {
|
||||
for (const e of events) console.log(JSON.stringify(e));
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`[events] ${opts.name} ${events.length} event(s) ${path}`);
|
||||
console.log("");
|
||||
for (const e of events) console.log(formatEvent(e));
|
||||
}
|
||||
|
||||
function formatEvent(e: Event): string {
|
||||
const id = String(e.id).padStart(4);
|
||||
const turn = `t${e.turn}`.padEnd(4);
|
||||
const ts = e.ts.replace("T", " ").replace(/\.\d+Z$/, "");
|
||||
const type = e.type.padEnd(22);
|
||||
return `[${id}] ${turn} ${ts} ${type} ${detailsFor(e)}`;
|
||||
}
|
||||
|
||||
function detailsFor(e: Event): string {
|
||||
switch (e.type) {
|
||||
case "user.message":
|
||||
return quote(e.text, 80);
|
||||
case "slash.invoked":
|
||||
return `/${e.name} ${e.args}`.trim();
|
||||
case "model.turn.started":
|
||||
return `model=${e.model} effort=${e.reasoningEffort} prefix=${e.prefixHash.slice(0, 8)}`;
|
||||
case "model.delta":
|
||||
return `${e.channel} ${quote(e.text, 60)}`;
|
||||
case "model.final": {
|
||||
const u = e.usage;
|
||||
const tokens = `in=${u.prompt_tokens ?? 0} out=${u.completion_tokens ?? 0}`;
|
||||
const tail = e.forcedSummary ? " [forcedSummary]" : "";
|
||||
return `cost=$${e.costUsd.toFixed(4)} ${tokens}${tail}`;
|
||||
}
|
||||
case "tool.intent":
|
||||
return `${e.callId} ${e.name} args=${truncate(e.args, 60)}`;
|
||||
case "tool.dispatched":
|
||||
return e.callId;
|
||||
case "tool.denied":
|
||||
return `${e.callId} reason=${e.reason}`;
|
||||
case "tool.result":
|
||||
return `${e.callId} ${e.ok ? "ok" : "err"} ${e.output.length}B${e.truncated ? " [trunc]" : ""}`;
|
||||
case "effect.file.touched":
|
||||
return `${e.mode} ${e.path} (${e.bytes}B)`;
|
||||
case "effect.memory.written":
|
||||
return `${e.scope}:${e.key}`;
|
||||
case "plan.submitted":
|
||||
return `${e.steps.length} step(s)`;
|
||||
case "plan.step.completed":
|
||||
return `${e.stepId}${e.title ? ` — ${e.title}` : ""}`;
|
||||
case "checkpoint.created":
|
||||
return `${e.checkpointId} "${e.name}" ${e.fileCount} file(s) ${e.bytes}B`;
|
||||
case "checkpoint.restored":
|
||||
return `${e.checkpointId} restored=${e.restored} removed=${e.removed} skipped=${e.skipped}`;
|
||||
case "hook.fired":
|
||||
return `${e.phase} ${e.hookName} → ${e.outcome}`;
|
||||
case "policy.budget.warning":
|
||||
return `$${e.spentUsd.toFixed(4)} / $${e.capUsd.toFixed(2)}`;
|
||||
case "policy.budget.blocked":
|
||||
return `$${e.spentUsd.toFixed(4)} / $${e.capUsd.toFixed(2)} BLOCKED`;
|
||||
case "policy.escalated":
|
||||
return `${e.fromModel} → ${e.toModel} (${e.reason})${e.rationale ? ` "${e.rationale}"` : ""}`;
|
||||
case "session.opened":
|
||||
return `${e.name} resumed-from-turn=${e.resumedFromTurn}`;
|
||||
case "session.compacted":
|
||||
return `${e.beforeMessages} → ${e.afterMessages} msgs (${e.reason})`;
|
||||
case "capability.registered":
|
||||
return `${e.name} ${e.permission}`;
|
||||
case "capability.removed":
|
||||
return e.name;
|
||||
case "status":
|
||||
return quote(e.text, 80);
|
||||
case "error":
|
||||
return `${e.recoverable ? "[recoverable] " : ""}${quote(e.message, 80)}`;
|
||||
default:
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
function quote(s: string, max: number): string {
|
||||
const flat = s.replace(/\s+/g, " ").trim();
|
||||
return flat.length <= max ? `"${flat}"` : `"${flat.slice(0, max - 1)}…"`;
|
||||
}
|
||||
|
||||
function truncate(s: string, max: number): string {
|
||||
return s.length <= max ? s : `${s.slice(0, max - 1)}…`;
|
||||
}
|
||||
|
||||
/** WorkspaceView holds files in a Map; default JSON.stringify drops it. */
|
||||
function mapReplacer(_key: string, value: unknown): unknown {
|
||||
if (value instanceof Map) return Object.fromEntries(value);
|
||||
if (value instanceof Set) return [...value];
|
||||
return value;
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
/** `reasonix index` — progress writes go to stderr so stdout stays pipeable. */
|
||||
|
||||
import { resolve } from "node:path";
|
||||
import { buildIndex } from "../../index/semantic/builder.js";
|
||||
import type { BuildProgress, BuildResult } from "../../index/semantic/builder.js";
|
||||
import { t } from "../../index/semantic/i18n.js";
|
||||
import { ollamaPreflight } from "../../index/semantic/preflight.js";
|
||||
|
||||
export interface IndexCommandOptions {
|
||||
rebuild?: boolean;
|
||||
model?: string;
|
||||
dir?: string;
|
||||
/** Ollama base URL override. */
|
||||
ollamaUrl?: string;
|
||||
/** Skip preflight prompts (yes to all). For scripts that already
|
||||
* know Ollama is set up. Default false. */
|
||||
yes?: boolean;
|
||||
}
|
||||
|
||||
export async function indexCommand(opts: IndexCommandOptions = {}): Promise<void> {
|
||||
const root = resolve(opts.dir ?? process.cwd());
|
||||
const tty = process.stderr.isTTY === true && process.stdin.isTTY === true;
|
||||
const model = opts.model ?? process.env.REASONIX_EMBED_MODEL ?? "nomic-embed-text";
|
||||
|
||||
// Preflight: detect Ollama state and offer to fix what's missing.
|
||||
// Runs before chunking so the user doesn't watch a scan finish only
|
||||
// to hit "daemon not reachable" on the first embed call.
|
||||
const preflightOk = await ollamaPreflight({
|
||||
model,
|
||||
baseUrl: opts.ollamaUrl,
|
||||
interactive: tty && !opts.yes,
|
||||
yesToAll: opts.yes ?? false,
|
||||
});
|
||||
if (!preflightOk) process.exit(1);
|
||||
|
||||
const writer = makeProgressWriter(tty);
|
||||
|
||||
const t0 = Date.now();
|
||||
let result: BuildResult;
|
||||
try {
|
||||
result = await buildIndex(root, {
|
||||
rebuild: opts.rebuild,
|
||||
model,
|
||||
baseUrl: opts.ollamaUrl,
|
||||
onProgress: (p) => writer.update(p),
|
||||
});
|
||||
} catch (err) {
|
||||
writer.clear();
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
process.stderr.write(t("indexFailed", { msg }));
|
||||
process.exit(1);
|
||||
}
|
||||
writer.clear();
|
||||
|
||||
const seconds = ((Date.now() - t0) / 1000).toFixed(1);
|
||||
const successKey = result.chunksSkipped > 0 ? "indexSuccessWithSkips" : "indexSuccess";
|
||||
process.stderr.write(
|
||||
t(successKey, {
|
||||
scanned: result.filesScanned,
|
||||
changed: result.filesChanged,
|
||||
added: result.chunksAdded,
|
||||
removed: result.chunksRemoved,
|
||||
skipped: result.chunksSkipped,
|
||||
seconds,
|
||||
}),
|
||||
);
|
||||
if (result.filesChanged === 0 && !opts.rebuild) {
|
||||
process.stderr.write(t("indexNothingToDo"));
|
||||
}
|
||||
}
|
||||
|
||||
interface ProgressWriter {
|
||||
update(p: BuildProgress): void;
|
||||
clear(): void;
|
||||
}
|
||||
|
||||
const SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
|
||||
const SPINNER_INTERVAL_MS = 120;
|
||||
|
||||
function makeProgressWriter(tty: boolean): ProgressWriter {
|
||||
if (!tty) return makeNonTtyWriter();
|
||||
return makeTtyWriter();
|
||||
}
|
||||
|
||||
function makeNonTtyWriter(): ProgressWriter {
|
||||
let lastPhase: BuildProgress["phase"] | null = null;
|
||||
let lastChunks = 0;
|
||||
return {
|
||||
update(p) {
|
||||
if (p.phase !== lastPhase) {
|
||||
lastPhase = p.phase;
|
||||
if (p.phase === "scan") {
|
||||
process.stderr.write(t("progressScanLine"));
|
||||
} else if (p.phase === "embed") {
|
||||
process.stderr.write(
|
||||
t("progressEmbedLine", {
|
||||
total: p.chunksTotal ?? 0,
|
||||
files: p.filesChanged ?? 0,
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
if (p.phase === "embed" && p.chunksDone !== undefined && p.chunksDone - lastChunks >= 50) {
|
||||
lastChunks = p.chunksDone;
|
||||
process.stderr.write(
|
||||
t("progressEmbedHeartbeat", {
|
||||
done: p.chunksDone,
|
||||
total: p.chunksTotal ?? "?",
|
||||
}),
|
||||
);
|
||||
}
|
||||
},
|
||||
clear() {
|
||||
/* non-TTY keeps its accumulated lines */
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Spinner ticks on its own setInterval so a hung embedder still shows liveness. */
|
||||
function makeTtyWriter(): ProgressWriter {
|
||||
let status = t("progressStarting");
|
||||
let lastLineLen = 0;
|
||||
let frameIdx = 0;
|
||||
const startTs = Date.now();
|
||||
|
||||
const repaint = () => {
|
||||
const frame = SPINNER_FRAMES[frameIdx % SPINNER_FRAMES.length];
|
||||
frameIdx++;
|
||||
const elapsed = ((Date.now() - startTs) / 1000).toFixed(1);
|
||||
const line = `${frame} ${status} ${elapsed}s`;
|
||||
const padded = line + " ".repeat(Math.max(0, lastLineLen - line.length));
|
||||
process.stderr.write(`\r${padded}`);
|
||||
lastLineLen = line.length;
|
||||
};
|
||||
|
||||
// Paint the initial frame immediately so the user sees text on
|
||||
// line one — don't wait for the first interval tick.
|
||||
repaint();
|
||||
const interval = setInterval(repaint, SPINNER_INTERVAL_MS);
|
||||
|
||||
return {
|
||||
update(p) {
|
||||
if (p.phase === "scan") {
|
||||
status = t("progressScan", { files: p.filesScanned ?? 0 });
|
||||
} else if (p.phase === "embed") {
|
||||
const done = p.chunksDone ?? 0;
|
||||
const total = p.chunksTotal ?? 0;
|
||||
const pct = total > 0 ? ((done / total) * 100).toFixed(0) : "0";
|
||||
status = t("progressEmbed", { done, total, pct });
|
||||
}
|
||||
// Repaint immediately on event arrival so the new counter
|
||||
// shows up before the next interval tick (avoids a 120ms lag
|
||||
// on each progress update).
|
||||
repaint();
|
||||
},
|
||||
clear() {
|
||||
clearInterval(interval);
|
||||
if (lastLineLen > 0) {
|
||||
process.stderr.write(`\r${" ".repeat(lastLineLen)}\r`);
|
||||
lastLineLen = 0;
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,20 +1,10 @@
|
||||
/**
|
||||
* `reasonix mcp inspect <spec>` — connect to one MCP server, list
|
||||
* everything it exposes (tools, resources, prompts), print a
|
||||
* human-readable summary. Useful as:
|
||||
* - a diagnostic tool for "does my MCP server even work?"
|
||||
* - a discovery tool for "what can this server do?"
|
||||
* - the only CLI surface for the resources+prompts methods added
|
||||
* in 0.4.5 (chat mode consumes tools but hasn't wired up the
|
||||
* other two families yet).
|
||||
*/
|
||||
|
||||
import { McpClient } from "../../mcp/client.js";
|
||||
import { inspectMcpServer } from "../../mcp/inspect.js";
|
||||
import type { InspectionReport } from "../../mcp/inspect.js";
|
||||
import { parseMcpSpec } from "../../mcp/spec.js";
|
||||
import { SseTransport } from "../../mcp/sse.js";
|
||||
import { type McpTransport, StdioTransport } from "../../mcp/stdio.js";
|
||||
import { StreamableHttpTransport } from "../../mcp/streamable-http.js";
|
||||
|
||||
export interface McpInspectOptions {
|
||||
/** The raw --mcp spec string (e.g. `fs=npx -y @modelcontextprotocol/server-filesystem .`). */
|
||||
@@ -28,7 +18,9 @@ export async function mcpInspectCommand(opts: McpInspectOptions): Promise<void>
|
||||
const transport: McpTransport =
|
||||
spec.transport === "sse"
|
||||
? new SseTransport({ url: spec.url })
|
||||
: new StdioTransport({ command: spec.command, args: spec.args });
|
||||
: spec.transport === "streamable-http"
|
||||
? new StreamableHttpTransport({ url: spec.url })
|
||||
: new StdioTransport({ command: spec.command, args: spec.args });
|
||||
const client = new McpClient({ transport });
|
||||
try {
|
||||
await client.initialize();
|
||||
|
||||
@@ -1,11 +1,3 @@
|
||||
/**
|
||||
* `reasonix mcp <subcmd>` — the MCP discovery / helper surface.
|
||||
*
|
||||
* Currently one subcommand: `list`. Prints a curated catalog of popular
|
||||
* MCP servers with their `--mcp` commands ready to copy-paste. More
|
||||
* subcommands (`init`, `try`, etc.) may land in later alphas.
|
||||
*/
|
||||
|
||||
import { MCP_CATALOG, mcpCommandFor } from "../../mcp/catalog.js";
|
||||
|
||||
export interface McpListOptions {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { render } from "ink";
|
||||
import React from "react";
|
||||
import { groupRecordsByTurn, replayFromFile } from "../../replay.js";
|
||||
import type { TranscriptRecord } from "../../transcript.js";
|
||||
import type { TranscriptRecord } from "../../transcript/log.js";
|
||||
import { groupRecordsByTurn, replayFromFile } from "../../transcript/replay.js";
|
||||
import { ReplayApp } from "../ui/ReplayApp.js";
|
||||
|
||||
export interface ReplayOptions {
|
||||
@@ -12,13 +12,6 @@ export interface ReplayOptions {
|
||||
print?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Replay a transcript. Two modes:
|
||||
* - Interactive TUI (default when stdout is a TTY): Ink-based j/k navigation.
|
||||
* - Stdout pretty-print (--print, or when stdout is piped): one-shot text
|
||||
* dump + summary. Kept working so shell pipes, CI logs, and `less`
|
||||
* workflows still behave sensibly.
|
||||
*/
|
||||
export async function replayCommand(opts: ReplayOptions): Promise<void> {
|
||||
const wantPrint =
|
||||
opts.print || !process.stdout.isTTY || opts.head !== undefined || opts.tail !== undefined;
|
||||
@@ -36,7 +29,6 @@ export async function replayCommand(opts: ReplayOptions): Promise<void> {
|
||||
await waitUntilExit();
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
// stdout pretty-print path (original behavior, preserved for piping / CI)
|
||||
|
||||
function printReplay(opts: ReplayOptions): void {
|
||||
|
||||
+11
-4
@@ -9,9 +9,10 @@ import { bridgeMcpTools } from "../../mcp/registry.js";
|
||||
import { parseMcpSpec } from "../../mcp/spec.js";
|
||||
import { SseTransport } from "../../mcp/sse.js";
|
||||
import { type McpTransport, StdioTransport } from "../../mcp/stdio.js";
|
||||
import { StreamableHttpTransport } from "../../mcp/streamable-http.js";
|
||||
import { appendUsage } from "../../telemetry/usage.js";
|
||||
import { ToolRegistry } from "../../tools.js";
|
||||
import { openTranscriptFile, recordFromLoopEvent, writeRecord } from "../../transcript.js";
|
||||
import { appendUsage } from "../../usage.js";
|
||||
import { openTranscriptFile, recordFromLoopEvent, writeRecord } from "../../transcript/log.js";
|
||||
|
||||
export interface RunOptions {
|
||||
task: string;
|
||||
@@ -21,6 +22,7 @@ export interface RunOptions {
|
||||
harvest?: boolean;
|
||||
/** Self-consistency budget. > 1 runs N parallel samples and picks the best. */
|
||||
branch?: number;
|
||||
budgetUsd?: number;
|
||||
/** JSONL transcript path — lets `reasonix replay` / `diff` audit this run. */
|
||||
transcript?: string;
|
||||
/** Zero or more MCP server specs. Each: `"name=cmd args..."` or `"cmd args..."`. */
|
||||
@@ -86,12 +88,16 @@ export async function runCommand(opts: RunOptions): Promise<void> {
|
||||
const transport: McpTransport =
|
||||
spec.transport === "sse"
|
||||
? new SseTransport({ url: spec.url })
|
||||
: new StdioTransport({ command: spec.command, args: spec.args });
|
||||
: spec.transport === "streamable-http"
|
||||
? new StreamableHttpTransport({ url: spec.url })
|
||||
: new StdioTransport({ command: spec.command, args: spec.args });
|
||||
const mcp = new McpClient({ transport });
|
||||
await mcp.initialize();
|
||||
const bridge = await bridgeMcpTools(mcp, { registry: tools, namePrefix: prefix });
|
||||
const source =
|
||||
spec.transport === "sse" ? spec.url : `${spec.command} ${spec.args.join(" ")}`;
|
||||
spec.transport === "sse" || spec.transport === "streamable-http"
|
||||
? spec.url
|
||||
: `${spec.command} ${spec.args.join(" ")}`;
|
||||
process.stderr.write(
|
||||
`▸ MCP[${spec.name ?? "anon"}]: ${bridge.registeredNames.length} tool(s) from ${source}\n`,
|
||||
);
|
||||
@@ -122,6 +128,7 @@ export async function runCommand(opts: RunOptions): Promise<void> {
|
||||
model: opts.model,
|
||||
harvest: opts.harvest,
|
||||
branch: opts.branch,
|
||||
budgetUsd: opts.budgetUsd,
|
||||
});
|
||||
const prefixHash = prefix.fingerprint;
|
||||
|
||||
|
||||
@@ -1,14 +1,3 @@
|
||||
/**
|
||||
* `reasonix sessions` — CLI equivalent of the `/sessions` slash command.
|
||||
*
|
||||
* Two modes:
|
||||
* - `reasonix sessions` list every session under ~/.reasonix/sessions/
|
||||
* - `reasonix sessions <name>` dump one session's messages in readable form
|
||||
*
|
||||
* Neither needs an API key — pure filesystem reads of JSONL files written
|
||||
* by previous chat runs.
|
||||
*/
|
||||
|
||||
import { listSessions, loadSessionMessages, sessionPath } from "../../index.js";
|
||||
import type { ChatMessage } from "../../index.js";
|
||||
|
||||
|
||||
+11
-27
@@ -1,20 +1,4 @@
|
||||
/**
|
||||
* `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."
|
||||
*/
|
||||
/** `reasonix stats [path]` — path arg switches to per-transcript mode; default is the cross-session dashboard. */
|
||||
|
||||
import { existsSync, readFileSync } from "node:fs";
|
||||
import {
|
||||
@@ -26,7 +10,7 @@ import {
|
||||
defaultUsageLogPath,
|
||||
formatLogSize,
|
||||
readUsageLog,
|
||||
} from "../../usage.js";
|
||||
} from "../../telemetry/usage.js";
|
||||
|
||||
export interface StatsOptions {
|
||||
/** Optional transcript path. Absent → dashboard mode. */
|
||||
@@ -45,10 +29,6 @@ export function statsCommand(opts: StatsOptions): void {
|
||||
dashboard(opts);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// Transcript summary — legacy v0.1 behavior, preserved verbatim.
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
function transcriptSummary(path: string): void {
|
||||
if (!existsSync(path)) {
|
||||
console.error(`no such transcript: ${path}`);
|
||||
@@ -74,10 +54,6 @@ function transcriptSummary(path: string): void {
|
||||
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);
|
||||
@@ -154,18 +130,21 @@ function renderSubagentSection(sub: NonNullable<UsageAggregate["subagents"]>): s
|
||||
|
||||
function header(): string {
|
||||
// Fixed column widths so alignment works in any TTY.
|
||||
// `cache saved` reports DeepSeek's hit-vs-miss USD diff; the existing
|
||||
// `saved` column is the % saved vs Claude-Sonnet equivalent.
|
||||
return [
|
||||
pad("", 10),
|
||||
pad("turns", 8, "right"),
|
||||
pad("cache hit", 10, "right"),
|
||||
pad("cost (USD)", 14, "right"),
|
||||
pad("cache saved", 14, "right"),
|
||||
pad("vs Claude", 14, "right"),
|
||||
pad("saved", 10, "right"),
|
||||
].join(" ");
|
||||
}
|
||||
|
||||
function divider(): string {
|
||||
return "-".repeat(70);
|
||||
return "-".repeat(86);
|
||||
}
|
||||
|
||||
function bucketRow(b: UsageBucket): string {
|
||||
@@ -176,6 +155,11 @@ function bucketRow(b: UsageBucket): string {
|
||||
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.cacheSavingsUsd > 0 ? `$${b.cacheSavingsUsd.toFixed(4)}` : "—",
|
||||
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(" ");
|
||||
|
||||
@@ -1,17 +1,3 @@
|
||||
/**
|
||||
* `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";
|
||||
|
||||
@@ -21,11 +7,6 @@ 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[];
|
||||
}
|
||||
|
||||
@@ -36,15 +17,7 @@ export interface PlanUpdateInput {
|
||||
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
|
||||
*/
|
||||
/** Pure decision — split out so tests don't need to spawn child processes or hit the network. */
|
||||
export function planUpdate(input: PlanUpdateInput): UpdatePlan {
|
||||
const diff = compareVersions(input.current, input.latest);
|
||||
if (diff > 0) {
|
||||
@@ -105,11 +78,6 @@ function defaultSpawn(argv: string[]): Promise<number> {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 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));
|
||||
|
||||
+168
-15
@@ -1,10 +1,16 @@
|
||||
import { Command } from "commander";
|
||||
import { readConfig } from "../config.js";
|
||||
import { VERSION } from "../index.js";
|
||||
import { applyMemoryStack } from "../user-memory.js";
|
||||
import { listSessions } from "../memory/session.js";
|
||||
import { applyMemoryStack } from "../memory/user.js";
|
||||
import { ESCALATION_CONTRACT } from "../prompt-fragments.js";
|
||||
import { chatCommand } from "./commands/chat.js";
|
||||
import { codeCommand } from "./commands/code.js";
|
||||
import { commitCommand } from "./commands/commit.js";
|
||||
import { diffCommand } from "./commands/diff.js";
|
||||
import { doctorCommand } from "./commands/doctor.js";
|
||||
import { eventsCommand } from "./commands/events.js";
|
||||
import { indexCommand } from "./commands/index.js";
|
||||
import { mcpInspectCommand } from "./commands/mcp-inspect.js";
|
||||
import { mcpListCommand } from "./commands/mcp.js";
|
||||
import { replayCommand } from "./commands/replay.js";
|
||||
@@ -14,7 +20,7 @@ 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.
|
||||
|
||||
@@ -28,33 +34,64 @@ Every factual claim about a codebase must be backed by evidence. Reasonix VALIDA
|
||||
|
||||
**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.`;
|
||||
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}`;
|
||||
|
||||
/** Lenient: malformed → undefined (no cap) so a bad flag doesn't abort launch. */
|
||||
function parseBudgetFlag(raw: number | undefined): number | undefined {
|
||||
if (raw === undefined) return undefined;
|
||||
if (!Number.isFinite(raw) || raw <= 0) {
|
||||
process.stderr.write(
|
||||
`▲ ignoring --budget=${raw} (must be a positive number) — running with no cap\n`,
|
||||
);
|
||||
return undefined;
|
||||
}
|
||||
return raw;
|
||||
}
|
||||
|
||||
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: applyMemoryStack(DEFAULT_SYSTEM, process.cwd()),
|
||||
harvest: defaults.harvest,
|
||||
branch: defaults.branch,
|
||||
session: defaults.session,
|
||||
session: continueOpts.session,
|
||||
mcp: defaults.mcp,
|
||||
forceResume: continueOpts.forceResume,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -68,16 +105,25 @@ program
|
||||
program
|
||||
.command("code [dir]")
|
||||
.description(
|
||||
"Code-editing chat — filesystem tools rooted at <dir> (default: cwd), coding system prompt, deepseek-reasoner. 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 baseline. Model proposes SEARCH/REPLACE blocks; Reasonix applies them to disk. Use /preset pro or /pro to lock v4-pro on hard tasks.",
|
||||
)
|
||||
.option("-m, --model <id>", "Override default 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",
|
||||
"Extract typed plan state from R1 reasoning (Pillar 2). Adds ~10-15% cost per turn. Off by default in code mode.",
|
||||
"Opt-in Pillar-2 plan-state extraction. Adds one flash call per turn; off by default (no preset enables it).",
|
||||
)
|
||||
.option(
|
||||
"--budget <usd>",
|
||||
"Soft USD cap on session spend. Off by default. Warns at 80%, refuses next turn at 100%. Mid-session: /budget <usd> or /budget off.",
|
||||
(v) => Number.parseFloat(v),
|
||||
)
|
||||
.option(
|
||||
"--no-dashboard",
|
||||
"Suppress the auto-launched embedded web dashboard. Default behavior boots it on TUI mount and shows the URL in the status bar (clickable in OSC-8-aware terminals).",
|
||||
)
|
||||
.action(async (dir: string | undefined, opts) => {
|
||||
await codeCommand({
|
||||
@@ -88,6 +134,8 @@ program
|
||||
forceResume: !!opts.resume,
|
||||
forceNew: !!opts.new,
|
||||
harvest: !!opts.harvest,
|
||||
budgetUsd: parseBudgetFlag(opts.budget),
|
||||
noDashboard: opts.dashboard === false,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -99,20 +147,29 @@ 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 bundle. One of: auto (flash → pro on hard turns, default), flash (always flash), pro (always pro). 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(
|
||||
"--budget <usd>",
|
||||
"Soft USD cap on session spend. Off by default. Warns at 80%, refuses next turn at 100%. Mid-session: /budget <usd> or /budget off.",
|
||||
(v) => Number.parseFloat(v),
|
||||
)
|
||||
.option("--session <name>", "Use a named session (default: from config, usually 'default').")
|
||||
.option("--no-session", "Disable session persistence for this run (ephemeral chat)")
|
||||
.option("-r, --resume", "Skip the session picker — always continue prior messages")
|
||||
.option(
|
||||
"-c, --continue",
|
||||
"Resume the most-recently-used session (any name) without showing the picker.",
|
||||
)
|
||||
.option("-n, --new", "Skip the session picker — always wipe prior messages and start fresh")
|
||||
.option(
|
||||
"--mcp <spec>",
|
||||
@@ -125,6 +182,10 @@ program
|
||||
"Global prefix applied to every MCP tool (only honored when no per-spec name is set; avoids collisions with a single anonymous server)",
|
||||
)
|
||||
.option("--no-config", "Ignore `~/.reasonix/config.json` — useful for CI or reproducing issues")
|
||||
.option(
|
||||
"--no-dashboard",
|
||||
"Suppress the auto-launched embedded web dashboard. Default behavior boots it on TUI mount and shows the URL in the status bar (clickable in OSC-8-aware terminals).",
|
||||
)
|
||||
.action(async (opts) => {
|
||||
const defaults = resolveDefaults({
|
||||
model: opts.model,
|
||||
@@ -135,17 +196,31 @@ 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: applyMemoryStack(opts.system, process.cwd()),
|
||||
transcript: opts.transcript,
|
||||
harvest: defaults.harvest,
|
||||
branch: defaults.branch,
|
||||
session: defaults.session,
|
||||
budgetUsd: parseBudgetFlag(opts.budget),
|
||||
session: continueOpts.session,
|
||||
mcp: defaults.mcp,
|
||||
mcpPrefix: opts.mcpPrefix,
|
||||
forceResume: !!opts.resume,
|
||||
forceResume: continueOpts.forceResume,
|
||||
forceNew: !!opts.new,
|
||||
noDashboard: opts.dashboard === false,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -154,13 +229,18 @@ program
|
||||
.description("Run a single task non-interactively, streaming output.")
|
||||
.option("-m, --model <id>", "DeepSeek model id (overrides preset)")
|
||||
.option("-s, --system <prompt>", "System prompt", DEFAULT_SYSTEM)
|
||||
.option("--preset <name>", "Bundle of model + harvest + branch: fast | smart | max")
|
||||
.option("--preset <name>", "Model bundle: auto | flash | pro (default: auto)")
|
||||
.option("--harvest", "Extract typed plan state from R1 reasoning (Pillar 2)")
|
||||
.option(
|
||||
"--branch <n>",
|
||||
"Self-consistency: run N parallel samples per turn and pick the most confident",
|
||||
(v) => Number.parseInt(v, 10),
|
||||
)
|
||||
.option(
|
||||
"--budget <usd>",
|
||||
"Soft USD cap on session spend. Off by default. Refuses to start a new turn once cumulative cost ≥ cap.",
|
||||
(v) => Number.parseFloat(v),
|
||||
)
|
||||
.option("--transcript <path>", "Write a JSONL transcript to this path for replay/diff")
|
||||
.option(
|
||||
"--mcp <spec>",
|
||||
@@ -188,6 +268,7 @@ program
|
||||
system: applyMemoryStack(opts.system, process.cwd()),
|
||||
harvest: defaults.harvest,
|
||||
branch: defaults.branch,
|
||||
budgetUsd: parseBudgetFlag(opts.budget),
|
||||
transcript: opts.transcript,
|
||||
mcp: defaults.mcp,
|
||||
mcpPrefix: opts.mcpPrefix,
|
||||
@@ -204,6 +285,29 @@ program
|
||||
statsCommand({ transcript });
|
||||
});
|
||||
|
||||
program
|
||||
.command("doctor")
|
||||
.description(
|
||||
"One-command health check — API key, config, /user/balance reachability, tokenizer, sessions, hooks, Ollama (if used), project markers. Exit 1 on any fail; 0 on warn / clean.",
|
||||
)
|
||||
.action(async () => {
|
||||
await doctorCommand();
|
||||
});
|
||||
|
||||
program
|
||||
.command("commit")
|
||||
.description(
|
||||
"Draft a commit message from the staged diff (or working tree, if nothing staged), matching your repo's recent commit style. Review interactively before it lands.",
|
||||
)
|
||||
.option("-m, --model <id>", "Override the default model (deepseek-v4-flash)")
|
||||
.option(
|
||||
"-y, --yes",
|
||||
"Skip the [a]ccept / [r]egenerate prompt and commit the first draft. Useful in scripts.",
|
||||
)
|
||||
.action(async (opts) => {
|
||||
await commitCommand({ model: opts.model, yes: !!opts.yes });
|
||||
});
|
||||
|
||||
program
|
||||
.command("sessions [name]")
|
||||
.description("List saved chat sessions, or inspect one by name.")
|
||||
@@ -212,6 +316,30 @@ program
|
||||
sessionsCommand({ name, verbose: !!opts.verbose });
|
||||
});
|
||||
|
||||
program
|
||||
.command("events <name>")
|
||||
.description(
|
||||
"Pretty-print the kernel event-log sidecar (~/.reasonix/sessions/<name>.events.jsonl) — every typed Event the session produced.",
|
||||
)
|
||||
.option("--type <type>", "Show only events of this type (e.g., tool.intent)")
|
||||
.option("--since <id>", "Show only events with id >= N", (v) => Number.parseInt(v, 10))
|
||||
.option("--tail <n>", "Show only the last N events", (v) => Number.parseInt(v, 10))
|
||||
.option("--json", "Emit raw JSONL passthrough instead of formatted lines (for jq pipelines)")
|
||||
.option(
|
||||
"--projection",
|
||||
"Replace the listing with the final reduced ProjectionSet (conversation, budget, plan, …)",
|
||||
)
|
||||
.action((name: string, opts) => {
|
||||
eventsCommand({
|
||||
name,
|
||||
type: opts.type,
|
||||
since: Number.isFinite(opts.since) ? opts.since : undefined,
|
||||
tail: Number.isFinite(opts.tail) ? opts.tail : undefined,
|
||||
json: !!opts.json,
|
||||
projection: !!opts.projection,
|
||||
});
|
||||
});
|
||||
|
||||
program
|
||||
.command("replay <transcript>")
|
||||
.description(
|
||||
@@ -290,6 +418,31 @@ program
|
||||
await updateCommand({ dryRun: !!opts.dryRun });
|
||||
});
|
||||
|
||||
program
|
||||
.command("index")
|
||||
.description(
|
||||
"Build (or incrementally refresh) a local semantic search index for the project so `reasonix code` can answer 'where do we…' questions by meaning, not just by token. Uses Ollama as the embedding backend; missing daemon / model is offered to the user with a confirm prompt.",
|
||||
)
|
||||
.option("--rebuild", "Wipe and rebuild from scratch")
|
||||
.option("--model <name>", "Embedding model (default: nomic-embed-text)")
|
||||
.option("--dir <path>", "Project root to index (default: cwd)")
|
||||
.option("--ollama-url <url>", "Override Ollama base URL (default: http://localhost:11434)")
|
||||
.option(
|
||||
"-y, --yes",
|
||||
"Skip preflight prompts — auto-start the daemon and pull the model if missing (use in scripts)",
|
||||
)
|
||||
.action(
|
||||
async (opts: {
|
||||
rebuild?: boolean;
|
||||
model?: string;
|
||||
dir?: string;
|
||||
ollamaUrl?: string;
|
||||
yes?: boolean;
|
||||
}) => {
|
||||
await indexCommand(opts);
|
||||
},
|
||||
);
|
||||
|
||||
program.parseAsync(process.argv).catch((err) => {
|
||||
console.error(err);
|
||||
process.exit(1);
|
||||
|
||||
+32
-19
@@ -1,23 +1,11 @@
|
||||
/**
|
||||
* Merge config defaults with CLI flags into the concrete options that
|
||||
* `chatCommand` / `runCommand` need.
|
||||
*
|
||||
* Precedence (highest wins):
|
||||
* 1. Explicit per-setting CLI flag (`--model`, `--harvest`, `--branch`, `--mcp`)
|
||||
* 2. Explicit `--preset <name>` CLI flag
|
||||
* 3. `config.preset` from `~/.reasonix/config.json` (set by `reasonix setup`)
|
||||
* 4. Hardcoded "fast" preset defaults
|
||||
*
|
||||
* Keeping this logic in one place — rather than duplicating across
|
||||
* `chat` and `run` — means the precedence rule only lives in one unit
|
||||
* test and the shape of the merge is identical for both commands.
|
||||
*/
|
||||
/** Precedence: per-setting flag > --preset > config.preset > "auto" defaults. */
|
||||
|
||||
import { type PresetName, type ReasonixConfig, readConfig } from "../config.js";
|
||||
import { PRESETS } from "./ui/presets.js";
|
||||
import { resolvePreset } from "./ui/presets.js";
|
||||
|
||||
export interface ResolvedDefaults {
|
||||
model: string;
|
||||
reasoningEffort: "high" | "max";
|
||||
harvest: boolean;
|
||||
branch: number | undefined;
|
||||
mcp: string[];
|
||||
@@ -41,9 +29,10 @@ export interface RawCliFlags {
|
||||
export function resolveDefaults(flags: RawCliFlags): ResolvedDefaults {
|
||||
const cfg: ReasonixConfig = flags.noConfig ? {} : readConfig();
|
||||
const preset = pickPreset(flags.preset, cfg.preset);
|
||||
const presetSettings = PRESETS[preset];
|
||||
const presetSettings = resolvePreset(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 +44,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,11 +53,20 @@ function pickPreset(
|
||||
): PresetName {
|
||||
if (flagPreset && isPresetName(flagPreset)) return flagPreset;
|
||||
if (configPreset) return configPreset;
|
||||
return "fast";
|
||||
return "auto";
|
||||
}
|
||||
|
||||
function isPresetName(s: string): s is PresetName {
|
||||
return s === "fast" || s === "smart" || s === "max";
|
||||
return (
|
||||
s === "auto" ||
|
||||
s === "flash" ||
|
||||
s === "pro" ||
|
||||
// Legacy names — kept callable so old `--preset smart` invocations
|
||||
// and stale config.json entries don't error out.
|
||||
s === "fast" ||
|
||||
s === "smart" ||
|
||||
s === "max"
|
||||
);
|
||||
}
|
||||
|
||||
function normalizeBranch(raw: number | undefined): number | undefined {
|
||||
@@ -87,3 +85,18 @@ function resolveSession(
|
||||
if (typeof configSession === "string" && configSession.length > 0) return configSession;
|
||||
return "default";
|
||||
}
|
||||
|
||||
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 };
|
||||
}
|
||||
+3509
-842
File diff suppressed because it is too large.
Load diff
@@ -1,6 +1,7 @@
|
||||
import { Box, Text } from "ink";
|
||||
// biome-ignore lint/style/useImportType: tsconfig.jsx = "react" needs React in value scope for JSX compilation
|
||||
import React from "react";
|
||||
import { COLOR, GLYPH } from "./theme.js";
|
||||
|
||||
export interface AtMentionSuggestionsProps {
|
||||
/**
|
||||
@@ -16,11 +17,21 @@ export interface AtMentionSuggestionsProps {
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* `@`-mention picker. Rendered below the input box while the user is
|
||||
* typing an `@…` prefix in code mode. Visual grammar matches the
|
||||
* design's file picker:
|
||||
*
|
||||
* @ files matching "auth" esc
|
||||
* ▸ login.ts src/auth/
|
||||
* refresh.ts src/auth/
|
||||
* validators.ts src/auth/
|
||||
* auth.test.ts tests/
|
||||
* [↑↓] navigate · Tab / ⏎ insert as @path · file content inlined
|
||||
*
|
||||
* Basename in primary cyan (the user's eye lands here first), dir
|
||||
* suffix in dim info color. No solid-bg pill on the selected row —
|
||||
* leading ▸ + bold + brighter color does the same job without the
|
||||
* loud bg block. Mirrors {@link SlashSuggestions}.
|
||||
*/
|
||||
export function AtMentionSuggestions({
|
||||
matches,
|
||||
@@ -30,12 +41,13 @@ export function AtMentionSuggestions({
|
||||
if (matches === null) return null;
|
||||
if (matches.length === 0) {
|
||||
return (
|
||||
<Box paddingX={1}>
|
||||
<Text color="yellow">no files match "@{query}"</Text>
|
||||
<Text dimColor>
|
||||
{" "}
|
||||
— keep typing, or Backspace to edit. Paths resolve from the code root.
|
||||
<Box paddingX={1} marginTop={1}>
|
||||
<Text color={COLOR.warn} bold>
|
||||
{GLYPH.warn}
|
||||
</Text>
|
||||
<Text> </Text>
|
||||
<Text color={COLOR.warn}>{`no files match "@${query}"`}</Text>
|
||||
<Text dimColor>{" — keep typing or Backspace; paths resolve from the code root"}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -47,40 +59,46 @@ export function AtMentionSuggestions({
|
||||
const hiddenAbove = windowStart;
|
||||
const hiddenBelow = total - windowStart - shown.length;
|
||||
return (
|
||||
<Box flexDirection="column" paddingX={1}>
|
||||
{hiddenAbove > 0 ? <Text dimColor> ↑ {hiddenAbove} more above</Text> : null}
|
||||
<Box flexDirection="column" paddingX={1} marginTop={1}>
|
||||
<Box>
|
||||
<Text color={COLOR.primary} bold>
|
||||
{"@ "}
|
||||
</Text>
|
||||
<Text dimColor>
|
||||
{query
|
||||
? `${total} match${total === 1 ? "" : "es"} for "${query}"`
|
||||
: `${total} file${total === 1 ? "" : "s"}`}
|
||||
</Text>
|
||||
{hiddenAbove > 0 ? <Text dimColor>{` ↑ ${hiddenAbove} above`}</Text> : null}
|
||||
</Box>
|
||||
{shown.map((path, i) => (
|
||||
<FileRow key={path} path={path} isSelected={windowStart + i === selectedIndex} />
|
||||
))}
|
||||
{hiddenBelow > 0 ? <Text dimColor> ↓ {hiddenBelow} more below</Text> : null}
|
||||
<Text dimColor> [↑↓] navigate · [Tab]/[Enter] pick · file content inlined on send</Text>
|
||||
{hiddenBelow > 0 ? <Text dimColor>{` ↓ ${hiddenBelow} below`}</Text> : null}
|
||||
<Box marginTop={0}>
|
||||
<Text dimColor>{" ↑↓ navigate · Tab / ⏎ insert as @path · esc cancel"}</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
function FileRow({ path, isSelected }: { path: string; isSelected: boolean }) {
|
||||
const marker = isSelected ? "▸" : " ";
|
||||
// Split the path so the basename visually pops — same dropdown
|
||||
// affordance as VS Code's Quick Open.
|
||||
// affordance as VS Code's Quick Open. Basename in primary cyan
|
||||
// (selected: bold), dir suffix in dim info color so the eye lands
|
||||
// on the filename first and uses the path only as a disambiguator.
|
||||
const slash = path.lastIndexOf("/");
|
||||
const dir = slash >= 0 ? `${path.slice(0, slash)}/` : "";
|
||||
const base = slash >= 0 ? path.slice(slash + 1) : path;
|
||||
if (isSelected) {
|
||||
return (
|
||||
<Box>
|
||||
<Text bold color="cyan">
|
||||
{marker} {base}
|
||||
</Text>
|
||||
<Text color="cyan">{dir ? ` ${dir}` : ""}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Box>
|
||||
<Text dimColor>
|
||||
{marker} {base}
|
||||
{dir ? ` ${dir}` : ""}
|
||||
<Text color={isSelected ? COLOR.primary : COLOR.info} bold={isSelected}>
|
||||
{isSelected ? `${GLYPH.cur} ` : " "}
|
||||
</Text>
|
||||
<Text color={COLOR.primary} bold={isSelected}>
|
||||
{base.padEnd(20)}
|
||||
</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,259 @@
|
||||
import { Box, Text, useStdout } from "ink";
|
||||
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React in value scope for JSX compilation
|
||||
import React from "react";
|
||||
import stringWidth from "string-width";
|
||||
import type { SessionSummary } from "../../telemetry/stats.js";
|
||||
import { ChromeRule } from "./primitives.js";
|
||||
import { COLOR, GRADIENT } from "./theme.js";
|
||||
|
||||
const COLD_START_TURNS = 3;
|
||||
const CACHE_BAR_CELLS = 10;
|
||||
|
||||
export type Preset = "auto" | "flash" | "pro";
|
||||
|
||||
export interface ChromeBarProps {
|
||||
summary: SessionSummary;
|
||||
rootDir?: string;
|
||||
sessionName?: string | null;
|
||||
preset?: Preset;
|
||||
planMode?: boolean;
|
||||
proArmed?: boolean;
|
||||
escalated?: boolean;
|
||||
updateAvailable?: string | null;
|
||||
balance?: { currency: string; total: number } | null;
|
||||
budgetUsd?: number | null;
|
||||
/** Scroll progress: 0 = at latest, 1 = at oldest. Hides the pill at 0. */
|
||||
scrollRatio?: number;
|
||||
}
|
||||
|
||||
export function ChromeBar(props: ChromeBarProps): React.ReactElement {
|
||||
const { stdout } = useStdout();
|
||||
const cols = (stdout?.columns ?? 80) - 2; // subtract paddingX={1} on both sides
|
||||
const cold = props.summary.turns <= COLD_START_TURNS;
|
||||
const projectName = props.rootDir ? basename(props.rootDir) : null;
|
||||
const mode = pickModePill(props.planMode, props.preset);
|
||||
const proPill = props.escalated
|
||||
? { label: "⇧ pro", color: COLOR.err }
|
||||
: props.proArmed
|
||||
? { label: "⇧ pro", color: COLOR.warn }
|
||||
: null;
|
||||
|
||||
// Greedy width-aware fit. Layout (each gap is exactly ONE space — single
|
||||
// suffix on update/mode/pro/scroll, single prefix on balance/cache):
|
||||
// [brand][·project][›session]<spacer>[scroll][update][mode][pro]$cost w bal cache █▓▓▓
|
||||
// Always-shown carve out the budget first; optional pieces are dropped
|
||||
// by priority — balance > cache > session > update — until the row fits.
|
||||
// (`flexGrow` spacer can shrink to 0, so no minimum reserve.) Cache is
|
||||
// shown unconditionally now: pre-turn-4 it renders dim with a "—" so
|
||||
// it's "default on" instead of materializing only after a few turns.
|
||||
const SEP = 3; // " · " / " › "
|
||||
const GAP = 1;
|
||||
const scrollLabel =
|
||||
props.scrollRatio !== undefined && props.scrollRatio > 0
|
||||
? `[↑ ${Math.round(props.scrollRatio * 100)}%]`
|
||||
: "";
|
||||
const updateLabel = props.updateAvailable ? `↑ ${props.updateAvailable}` : "";
|
||||
const balanceLabel = props.balance ? formatBalanceLabel(props.balance) : "";
|
||||
const cachePct = Math.round(props.summary.cacheHitRatio * 100);
|
||||
// Use the worst-case rendered cache string (3-digit pct, full bar) so the
|
||||
// shed decision doesn't oscillate as the percentage changes turn-to-turn.
|
||||
const cacheLabel = `cache ${"█".repeat(CACHE_BAR_CELLS)} 100%`;
|
||||
const costLabel = `$${props.summary.totalCostUsd.toFixed(4)}${
|
||||
props.budgetUsd && props.budgetUsd > 0 ? ` / $${props.budgetUsd.toFixed(2)}` : ""
|
||||
}`;
|
||||
|
||||
const brandW = stringWidth("◈ reasonix");
|
||||
const projectW = projectName ? SEP + stringWidth(projectName) : 0;
|
||||
const fixedLeft = brandW + projectW;
|
||||
const scrollW = scrollLabel ? stringWidth(scrollLabel) + GAP : 0;
|
||||
const modeW = mode ? stringWidth(`[${mode.label}]`) + GAP : 0;
|
||||
const proW = proPill ? stringWidth(`[${proPill.label}]`) + GAP : 0;
|
||||
const costW = stringWidth(costLabel);
|
||||
const fixedRight = scrollW + modeW + proW + costW;
|
||||
let budget = cols - fixedLeft - fixedRight;
|
||||
|
||||
const balanceOptW = balanceLabel ? GAP + stringWidth(balanceLabel) : 0;
|
||||
const cacheOptW = GAP + stringWidth(cacheLabel);
|
||||
const sessionOptW = props.sessionName ? SEP + stringWidth(props.sessionName) : 0;
|
||||
const updateOptW = updateLabel ? stringWidth(updateLabel) + GAP : 0;
|
||||
|
||||
const showBalance = balanceOptW > 0 && budget >= balanceOptW;
|
||||
if (showBalance) budget -= balanceOptW;
|
||||
const showCache = budget >= cacheOptW;
|
||||
if (showCache) budget -= cacheOptW;
|
||||
const showSession = sessionOptW > 0 && budget >= sessionOptW;
|
||||
if (showSession) budget -= sessionOptW;
|
||||
const showUpdate = updateOptW > 0 && budget >= updateOptW;
|
||||
if (showUpdate) budget -= updateOptW;
|
||||
|
||||
return (
|
||||
<Box flexDirection="column" paddingX={1}>
|
||||
<Box>
|
||||
<Text bold color={GRADIENT[0]}>
|
||||
{"◈ "}
|
||||
</Text>
|
||||
<Text color={COLOR.brand} bold>
|
||||
reasonix
|
||||
</Text>
|
||||
{projectName ? (
|
||||
<>
|
||||
<Text color={COLOR.info} dimColor>
|
||||
{" · "}
|
||||
</Text>
|
||||
<Text>{projectName}</Text>
|
||||
{showSession && props.sessionName ? (
|
||||
<>
|
||||
<Text color={COLOR.info} dimColor>
|
||||
{" › "}
|
||||
</Text>
|
||||
<Text color={COLOR.info}>{props.sessionName}</Text>
|
||||
</>
|
||||
) : null}
|
||||
</>
|
||||
) : null}
|
||||
|
||||
<Box flexGrow={1} />
|
||||
|
||||
{scrollLabel ? (
|
||||
<>
|
||||
<Text color={COLOR.accent} bold>
|
||||
{scrollLabel}
|
||||
</Text>
|
||||
<Text> </Text>
|
||||
</>
|
||||
) : null}
|
||||
{showUpdate ? (
|
||||
<>
|
||||
<Text color={COLOR.warn} bold>
|
||||
{updateLabel}
|
||||
</Text>
|
||||
<Text> </Text>
|
||||
</>
|
||||
) : null}
|
||||
{mode ? (
|
||||
<>
|
||||
<Text color={mode.color} bold>
|
||||
{`[${mode.label}]`}
|
||||
</Text>
|
||||
<Text> </Text>
|
||||
</>
|
||||
) : null}
|
||||
{proPill ? (
|
||||
<>
|
||||
<Text color={proPill.color} bold>
|
||||
{`[${proPill.label}]`}
|
||||
</Text>
|
||||
<Text> </Text>
|
||||
</>
|
||||
) : null}
|
||||
<CostPill summary={props.summary} cold={cold} budgetUsd={props.budgetUsd} />
|
||||
{showBalance && props.balance ? (
|
||||
<>
|
||||
<Text> </Text>
|
||||
<BalancePill balance={props.balance} />
|
||||
</>
|
||||
) : null}
|
||||
{showCache ? (
|
||||
<>
|
||||
<Text> </Text>
|
||||
<CachePill ratio={props.summary.cacheHitRatio} cold={cold} pct={cachePct} />
|
||||
</>
|
||||
) : null}
|
||||
</Box>
|
||||
<ChromeRule />
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
function formatBalanceLabel(balance: { currency: string; total: number }): string {
|
||||
const sym = balance.currency === "USD" ? "$" : balance.currency === "CNY" ? "¥" : "";
|
||||
const suf = sym ? "" : ` ${balance.currency}`;
|
||||
return `w ${sym}${balance.total.toFixed(2)}${suf}`;
|
||||
}
|
||||
|
||||
function CostPill({
|
||||
summary,
|
||||
cold,
|
||||
budgetUsd,
|
||||
}: {
|
||||
summary: SessionSummary;
|
||||
cold: boolean;
|
||||
budgetUsd?: number | null;
|
||||
}): React.ReactElement {
|
||||
const cost = summary.totalCostUsd;
|
||||
const color = cold ? COLOR.info : sessionCostColor(cost);
|
||||
return (
|
||||
<>
|
||||
<Text color={color} bold={!cold} dimColor={cold}>
|
||||
{`$${cost.toFixed(4)}`}
|
||||
</Text>
|
||||
{budgetUsd && budgetUsd > 0 ? (
|
||||
<Text color={COLOR.info} dimColor>
|
||||
{` / $${budgetUsd.toFixed(2)}`}
|
||||
</Text>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function BalancePill({
|
||||
balance,
|
||||
}: {
|
||||
balance: { currency: string; total: number };
|
||||
}): React.ReactElement {
|
||||
const { total } = balance;
|
||||
const color = total < 1 ? COLOR.err : total < 5 ? COLOR.warn : COLOR.ok;
|
||||
return <Text color={color}>{formatBalanceLabel(balance)}</Text>;
|
||||
}
|
||||
|
||||
function CachePill({
|
||||
ratio,
|
||||
cold,
|
||||
pct,
|
||||
}: {
|
||||
ratio: number;
|
||||
cold: boolean;
|
||||
pct: number;
|
||||
}): React.ReactElement {
|
||||
const color = ratio >= 0.7 ? COLOR.ok : ratio >= 0.4 ? COLOR.warn : COLOR.err;
|
||||
const filled = Math.max(0, Math.min(CACHE_BAR_CELLS, Math.round(ratio * CACHE_BAR_CELLS)));
|
||||
const empty = CACHE_BAR_CELLS - filled;
|
||||
return (
|
||||
<>
|
||||
<Text color={COLOR.info} dimColor>
|
||||
{"cache "}
|
||||
</Text>
|
||||
<Text color={cold ? COLOR.info : color} dimColor={cold}>
|
||||
{"█".repeat(filled)}
|
||||
</Text>
|
||||
<Text dimColor>{"░".repeat(empty)}</Text>
|
||||
<Text color={cold ? undefined : color} bold={!cold} dimColor={cold}>
|
||||
{cold && pct === 0 ? " —" : ` ${pct}%`}
|
||||
</Text>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function pickModePill(
|
||||
planMode: boolean | undefined,
|
||||
preset: Preset | undefined,
|
||||
): { label: string; color: string } | null {
|
||||
if (planMode) return { label: "PLAN", color: COLOR.err };
|
||||
if (!preset) return null;
|
||||
if (preset === "pro") return { label: "pro", color: COLOR.accent };
|
||||
if (preset === "flash") return { label: "flash", color: COLOR.info };
|
||||
return { label: "auto", color: COLOR.primary };
|
||||
}
|
||||
|
||||
function sessionCostColor(cost: number): string | undefined {
|
||||
if (cost <= 0) return undefined;
|
||||
if (cost >= 5) return COLOR.err;
|
||||
if (cost >= 0.5) return COLOR.warn;
|
||||
return COLOR.ok;
|
||||
}
|
||||
|
||||
function basename(path: string): string {
|
||||
const norm = path.replace(/\\/g, "/");
|
||||
const i = norm.lastIndexOf("/");
|
||||
return i === -1 ? norm : norm.slice(i + 1);
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import { Box, Text, useStdout } from "ink";
|
||||
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React in value scope for JSX compilation
|
||||
import React, { useMemo } from "react";
|
||||
import stringWidth from "string-width";
|
||||
import type { CacheFirstLoop } from "../../loop.js";
|
||||
import type { SessionSummary } from "../../telemetry/stats.js";
|
||||
import { computeCtxBreakdown } from "./ctx-breakdown.js";
|
||||
import { Bar, ChromeRule, formatTokens } from "./primitives.js";
|
||||
import { COLOR } from "./theme.js";
|
||||
|
||||
interface CtxFooterProps {
|
||||
loop: CacheFirstLoop;
|
||||
summary: SessionSummary;
|
||||
}
|
||||
|
||||
const BAR_CELLS = 14;
|
||||
|
||||
export function CtxFooter({ loop, summary }: CtxFooterProps): React.ReactElement {
|
||||
// Memoize on turn boundary. `summary.turns` is a freshness key — its
|
||||
// change forces recomputation when the loop's log appends a new turn.
|
||||
// biome-ignore lint/correctness/useExhaustiveDependencies: summary.turns is a freshness key, not a value used in the body
|
||||
const data = useMemo(() => computeCtxBreakdown(loop), [loop, summary.turns]);
|
||||
const { stdout } = useStdout();
|
||||
const cols = (stdout?.columns ?? 80) - 2;
|
||||
|
||||
const total = data.systemTokens + data.toolsTokens + data.logTokens + data.inputTokens;
|
||||
const ratio = data.ctxMax > 0 ? Math.min(1, total / data.ctxMax) : 0;
|
||||
const pct = Math.round(ratio * 100);
|
||||
const severity = pct >= 80 ? COLOR.err : pct >= 60 ? COLOR.warn : COLOR.ok;
|
||||
|
||||
// Always-shown core: label + bar + total + pct + (compact warn when severe)
|
||||
const labelStr = " ctx ";
|
||||
const totalStr = `${formatTokens(total)}/${formatTokens(data.ctxMax)}`;
|
||||
const pctStr = ` · ${pct}%`;
|
||||
const warnStr = pct >= 80 ? " · /compact" : "";
|
||||
const fixedW =
|
||||
stringWidth(labelStr) +
|
||||
BAR_CELLS +
|
||||
1 + // space after bar
|
||||
stringWidth(totalStr) +
|
||||
stringWidth(pctStr) +
|
||||
stringWidth(warnStr);
|
||||
|
||||
// Optional breakdown segments. Greedy fit by priority (drop first → drop last):
|
||||
// input → log → tools → sys. Sys comes off the line LAST because it's
|
||||
// the most stable number; users learn its size and read other segments
|
||||
// relative to it.
|
||||
let budget = cols - fixedW;
|
||||
const sysSeg = ` · sys ${formatTokens(data.systemTokens)}`;
|
||||
const toolsSeg = ` · tools ${formatTokens(data.toolsTokens)}`;
|
||||
const logSeg = ` · log ${formatTokens(data.logTokens)}`;
|
||||
const inputSeg = data.inputTokens > 0 ? ` · input ${formatTokens(data.inputTokens)}` : "";
|
||||
|
||||
const showSys = budget >= stringWidth(sysSeg);
|
||||
if (showSys) budget -= stringWidth(sysSeg);
|
||||
const showTools = budget >= stringWidth(toolsSeg);
|
||||
if (showTools) budget -= stringWidth(toolsSeg);
|
||||
const showLog = budget >= stringWidth(logSeg);
|
||||
if (showLog) budget -= stringWidth(logSeg);
|
||||
const showInput = inputSeg !== "" && budget >= stringWidth(inputSeg);
|
||||
if (showInput) budget -= stringWidth(inputSeg);
|
||||
|
||||
return (
|
||||
<Box flexDirection="column" paddingX={1}>
|
||||
<ChromeRule />
|
||||
<Text>
|
||||
<Text color={COLOR.info} dimColor>
|
||||
{labelStr}
|
||||
</Text>
|
||||
<Bar ratio={ratio} color={severity} cells={BAR_CELLS} />
|
||||
<Text> </Text>
|
||||
<Text color={severity} bold>
|
||||
{totalStr}
|
||||
</Text>
|
||||
<Text dimColor>{pctStr}</Text>
|
||||
{showSys ? <Text dimColor>{sysSeg}</Text> : null}
|
||||
{showTools ? <Text dimColor>{toolsSeg}</Text> : null}
|
||||
{showLog ? <Text dimColor>{logSeg}</Text> : null}
|
||||
{showInput ? <Text dimColor>{inputSeg}</Text> : null}
|
||||
{warnStr ? (
|
||||
<Text color={COLOR.err} bold>
|
||||
{warnStr}
|
||||
</Text>
|
||||
) : null}
|
||||
</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
/** Single-line text input for deny-with-reason — uses our KeystrokeContext, not ink-text-input. */
|
||||
|
||||
import { Box, Text } from "ink";
|
||||
import React, { useState } from "react";
|
||||
import { useKeystroke } from "./keystroke-context.js";
|
||||
|
||||
export interface DenyContextInputProps {
|
||||
label?: string;
|
||||
onSubmit: (context: string) => void;
|
||||
onCancel: () => void;
|
||||
}
|
||||
|
||||
export function DenyContextInput({
|
||||
label = "Reason for denying:",
|
||||
onSubmit,
|
||||
onCancel,
|
||||
}: DenyContextInputProps) {
|
||||
const [value, setValue] = useState("");
|
||||
|
||||
useKeystroke((ev) => {
|
||||
if (ev.paste) {
|
||||
setValue((v) => v + ev.input);
|
||||
return;
|
||||
}
|
||||
if (ev.escape) {
|
||||
onCancel();
|
||||
return;
|
||||
}
|
||||
if (ev.return) {
|
||||
onSubmit(value);
|
||||
return;
|
||||
}
|
||||
if (ev.backspace) {
|
||||
setValue((v) => v.slice(0, -1));
|
||||
return;
|
||||
}
|
||||
if (ev.input && !ev.tab && !ev.upArrow && !ev.downArrow && !ev.leftArrow && !ev.rightArrow) {
|
||||
setValue((v) => v + ev.input);
|
||||
}
|
||||
});
|
||||
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
<Box>
|
||||
<Text dimColor>{label} </Text>
|
||||
<Text>{value}</Text>
|
||||
<Text backgroundColor="#67e8f9" color="black">
|
||||
{" "}
|
||||
</Text>
|
||||
</Box>
|
||||
<Box marginTop={1}>
|
||||
<Text dimColor>
|
||||
{"["}
|
||||
<Text color="#67e8f9" bold>
|
||||
Enter
|
||||
</Text>
|
||||
{"] confirm · ["}
|
||||
<Text color="#67e8f9" bold>
|
||||
Esc
|
||||
</Text>
|
||||
{"] cancel"}
|
||||
</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -16,7 +16,7 @@ import {
|
||||
type TurnPair,
|
||||
findNextDivergence,
|
||||
findPrevDivergence,
|
||||
} from "../../diff.js";
|
||||
} from "../../transcript/diff.js";
|
||||
import { RecordView } from "./RecordView.js";
|
||||
|
||||
export interface DiffAppProps {
|
||||
|
||||
@@ -0,0 +1,228 @@
|
||||
import { Box, Text, useStdout } from "ink";
|
||||
import React, { useMemo, useState } from "react";
|
||||
import { formatEditBlockSplit } from "../../code/diff-preview.js";
|
||||
import type { EditBlock } from "../../code/edit-blocks.js";
|
||||
import { DenyContextInput } from "./DenyContextInput.js";
|
||||
import { ModalCard } from "./ModalCard.js";
|
||||
import { SplitDiff } from "./SplitDiff.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, denyContext?: string) => 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);
|
||||
|
||||
// Side-by-side rows — maxLines pushed high so the split renderer
|
||||
// never inserts its own truncation marker; we slice + scroll here.
|
||||
// contextLines: 2 keeps the trim tight on each end.
|
||||
const allRows = useMemo(
|
||||
() => formatEditBlockSplit(block, { contextLines: 2, maxLines: 100_000 }),
|
||||
[block],
|
||||
);
|
||||
|
||||
const [scroll, setScroll] = useState(0);
|
||||
const maxScroll = Math.max(0, allRows.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);
|
||||
|
||||
const [phase, setPhase] = useState<"review" | "context">("review");
|
||||
|
||||
useKeystroke((ev) => {
|
||||
if (ev.paste) return;
|
||||
if (phase === "context") 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") {
|
||||
setPhase("context");
|
||||
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 visibleRows = allRows.slice(effectiveScroll, effectiveScroll + budget);
|
||||
const hiddenAbove = effectiveScroll;
|
||||
const hiddenBelow = Math.max(0, allRows.length - effectiveScroll - budget);
|
||||
const totalLines = allRows.length;
|
||||
const showScrollHud = hiddenAbove + hiddenBelow > 0;
|
||||
|
||||
const subtitleParts = [`-${removed} +${added} lines`];
|
||||
if (showScrollHud) {
|
||||
subtitleParts.push(
|
||||
`viewing ${effectiveScroll + 1}-${effectiveScroll + visibleRows.length}/${totalLines}`,
|
||||
);
|
||||
}
|
||||
|
||||
if (phase === "context") {
|
||||
return (
|
||||
<ModalCard
|
||||
accent={isNew ? "#86efac" : "#fcd34d"}
|
||||
icon={isNew ? "✚" : "✎"}
|
||||
title={`${tag} ${block.path}`}
|
||||
subtitle="rejecting — add context (optional)"
|
||||
>
|
||||
<DenyContextInput
|
||||
label="Reason for rejecting (or Enter to reject without context): "
|
||||
onSubmit={(context) => onChoose("reject", context)}
|
||||
onCancel={() => setPhase("review")}
|
||||
/>
|
||||
</ModalCard>
|
||||
);
|
||||
}
|
||||
|
||||
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}
|
||||
<SplitDiff rows={visibleRows} />
|
||||
<Box>
|
||||
<Text color="#fbc8c8" backgroundColor="#2a1212">
|
||||
{" - old "}
|
||||
</Text>
|
||||
<Text>{" "}</Text>
|
||||
<Text color="#bef0c8" backgroundColor="#0c2718">
|
||||
{" + new "}
|
||||
</Text>
|
||||
<Text dimColor>
|
||||
{" side-by-side · removed lines on the left, added on the right · paired by offset"}
|
||||
</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 with reason · ["}
|
||||
<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>
|
||||
);
|
||||
}
|
||||
+666
-229
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,360 @@
|
||||
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 { CharBar } from "./char-bar.js";
|
||||
import { useElapsedSeconds, useSlowTick, 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 the slow tick so the jobs count stays live — the
|
||||
// registry is mutated outside React, so we need a periodic repaint
|
||||
// to catch it. 1Hz is enough for a count badge: a 1s lag for a job
|
||||
// appearing/disappearing is imperceptible vs how long jobs run.
|
||||
// No-op when there's no registry (chat mode / tests).
|
||||
useSlowTick();
|
||||
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 — bracket-text style matching the StatsPanel chrome at top
|
||||
* (one canonical pill style across the whole TUI). `flash` inverts
|
||||
* briefly after a mode flip so the user sees "yes, it changed"; once
|
||||
* the flash fades it returns to its quiet bracket form.
|
||||
*
|
||||
* Why bracket and not solid bg: the mode is already shown in the top
|
||||
* chrome's pill. Repeating the same info as a loud, padded block
|
||||
* directly above the prompt was visual repetition, not reinforcement.
|
||||
* Bracket here keeps the actionable hint readable while the flash
|
||||
* still does its acknowledgement job.
|
||||
*/
|
||||
function ModePill({
|
||||
label,
|
||||
bg,
|
||||
flash,
|
||||
}: {
|
||||
label: string;
|
||||
bg: "magenta" | "cyan" | "red";
|
||||
flash: boolean;
|
||||
}) {
|
||||
return (
|
||||
<Text color={bg} 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.
|
||||
* The countdown ticks once per second — slow tick is the right
|
||||
* cadence here (faster re-renders just redraw the same digit).
|
||||
* 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 };
|
||||
}) {
|
||||
// Fast tick so the char bar shrinks one cell at a time rather than
|
||||
// jumping in 1s gulps. With FAST_TICK_MS=120 we get ~42 frames over
|
||||
// a 5s window — smooth enough that the bar reads as a continuous
|
||||
// countdown without looking like a stutter.
|
||||
useTick();
|
||||
const totalMs = 5000; // mirrors armUndoBanner's hard-coded window
|
||||
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;
|
||||
// 20-cell bar, 4 cells per second. Filled = remaining time.
|
||||
const pct = (remainingMs / totalMs) * 100;
|
||||
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>
|
||||
<CharBar pct={pct} width={20} color={urgent ? "#f87171" : "#c4b5fd"} showLabel={false} />
|
||||
<Text dimColor>{" "}</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);
|
||||
// Bracket-text style — same vocabulary as the static ToolPill so a
|
||||
// turn that contains both finished tools and a live subagent reads
|
||||
// as a consistent column. The braille spinner + colored ⌬ + colored
|
||||
// name carry enough weight without a solid-bg block.
|
||||
return (
|
||||
<Box paddingLeft={3}>
|
||||
<Text color="#c4b5fd" bold>
|
||||
{SPINNER_FRAMES[tick % SPINNER_FRAMES.length]}
|
||||
</Text>
|
||||
<Text>{" "}</Text>
|
||||
<Text color="#c4b5fd" 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);
|
||||
// Bracket-text style — matches the static ToolPill that lands once
|
||||
// the call resolves, so a row of in-flight + finished tools reads
|
||||
// as one continuous column instead of two visual languages.
|
||||
return (
|
||||
<Box marginY={1} flexDirection="column" paddingX={1}>
|
||||
<Box>
|
||||
<Text color="#fcd34d" bold>
|
||||
{SPINNER_FRAMES[tick % SPINNER_FRAMES.length]}
|
||||
</Text>
|
||||
<Text>{" "}</Text>
|
||||
<Text color="#fcd34d" bold>
|
||||
{`▣ ${tool.name}`}
|
||||
</Text>
|
||||
<Text dimColor>{` running · ${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,115 @@
|
||||
/**
|
||||
* Shared visual frame for confirmation modals (ChoiceConfirm,
|
||||
* PlanConfirm, ShellConfirm, EditConfirm, PlanCheckpointConfirm,
|
||||
* PlanReviseConfirm). Renders as a true bordered card matching the
|
||||
* design doc — full accent-colored Unicode box around header + body,
|
||||
* with a horizontal rule separating the title row from the content
|
||||
* area so the modal reads as a discrete interrupt, not just a few
|
||||
* spaced lines in the live region.
|
||||
*
|
||||
* Layout:
|
||||
*
|
||||
* ╭───────────────────────────────────────────────╮
|
||||
* │ ICON TITLE subtitle │
|
||||
* ├───────────────────────────────────────────────┤
|
||||
* │ │
|
||||
* │ <children — body of the modal> │
|
||||
* │ │
|
||||
* ╰───────────────────────────────────────────────╯
|
||||
*
|
||||
* Color drives the accent (border + icon + title) so the user learns
|
||||
* to recognize the modal type by glance: violet = choice, cyan = plan,
|
||||
* amber = shell, green = edit review, red = budget exhausted.
|
||||
*
|
||||
* Why Ink `borderStyle="round"` is fine here despite the historical
|
||||
* comment about eraseLines miscounts: the modals only render in
|
||||
* single-instance positions (they replace the prompt area, never the
|
||||
* scrollback), so the frame doesn't get re-painted every tick. The
|
||||
* earlier bug class was about animated wide rows wrapping mid-render.
|
||||
*/
|
||||
|
||||
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 — border + icon + title text. */
|
||||
accent: string;
|
||||
/** Section title — rendered bold in the accent color. */
|
||||
title: string;
|
||||
/** Optional dim subtitle next to the title. */
|
||||
subtitle?: string;
|
||||
/** Optional leading glyph (icon). Rendered in the accent color. */
|
||||
icon?: string;
|
||||
/**
|
||||
* Optional footer slot — renders below a horizontal rule, after the
|
||||
* body. Used for action-button rows like `[apply] [discard]` so they
|
||||
* sit visually pinned to the bottom of the modal regardless of body
|
||||
* scroll height. When absent, the modal ends right after the body.
|
||||
*/
|
||||
footer?: React.ReactNode;
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
export function ModalCard({
|
||||
accent,
|
||||
title,
|
||||
subtitle,
|
||||
icon,
|
||||
footer,
|
||||
children,
|
||||
}: ModalCardProps): React.ReactElement {
|
||||
const { stdout } = useStdout();
|
||||
const cols = stdout?.columns ?? 80;
|
||||
// Subtract 4: 2 cells for the left+right border + 2 cells of paddingX.
|
||||
// Min 28 keeps the rule visible even on absurdly narrow terminals.
|
||||
const innerWidth = Math.min(76, Math.max(28, cols - 6));
|
||||
|
||||
return (
|
||||
<Box flexDirection="column" borderStyle="round" borderColor={accent} paddingX={1} marginY={1}>
|
||||
{/* Header row — icon + bold title in accent color, dim subtitle
|
||||
right-aligned. The horizontal rule below it doubles as a
|
||||
separator and a visual weight that says "this is the thing
|
||||
to read". */}
|
||||
<Box>
|
||||
{icon ? (
|
||||
<>
|
||||
<Text color={accent} bold>
|
||||
{icon}
|
||||
</Text>
|
||||
<Text>{" "}</Text>
|
||||
</>
|
||||
) : null}
|
||||
<Text color={accent} bold>
|
||||
{title}
|
||||
</Text>
|
||||
{subtitle ? (
|
||||
<>
|
||||
<Box flexGrow={1} />
|
||||
<Text dimColor>{subtitle}</Text>
|
||||
</>
|
||||
) : null}
|
||||
</Box>
|
||||
<Box>
|
||||
<Text color={accent} dimColor>
|
||||
{"─".repeat(innerWidth)}
|
||||
</Text>
|
||||
</Box>
|
||||
{/* Body — children render with no extra padding so the modal
|
||||
body looks like one continuous content area inside the border. */}
|
||||
<Box flexDirection="column">{children}</Box>
|
||||
{/* Optional footer — divider rule + slot. Lets modals separate
|
||||
actions from body without each one re-implementing the rule. */}
|
||||
{footer ? (
|
||||
<>
|
||||
<Box>
|
||||
<Text color={accent} dimColor>
|
||||
{"─".repeat(innerWidth)}
|
||||
</Text>
|
||||
</Box>
|
||||
<Box flexDirection="column">{footer}</Box>
|
||||
</>
|
||||
) : null}
|
||||
</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;
|
||||
}
|
||||
+52
-122
@@ -9,99 +9,34 @@
|
||||
* 3. Cancel — exits plan mode, drops the plan, tells the model the
|
||||
* user didn't want any of it.
|
||||
*
|
||||
* Mirrors ShellConfirm in structure (border, SingleSelect, three
|
||||
* options, no y/n hotkey — mid-typing triggers would be painful).
|
||||
* The plan body is rendered verbatim above the picker so the user can
|
||||
* actually read what they're approving.
|
||||
* 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";
|
||||
import { Markdown } from "./markdown.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;
|
||||
/**
|
||||
* Cap on rendered plan length. A pathological 20-KB plan would push
|
||||
* the picker off the bottom of the terminal; we show the head +
|
||||
* "(…N chars truncated — /tool for full output)" instead. The picker
|
||||
* itself gets the full plan (it's already been committed to the
|
||||
* transcript via the tool result).
|
||||
*/
|
||||
maxRenderedChars?: number;
|
||||
projectRoot?: string;
|
||||
/**
|
||||
* Override the terminal-row count used for vertical clamping. Tests
|
||||
* pass this to avoid depending on `process.stdout.rows`; runtime
|
||||
* callers leave it unset and we read the real TTY size.
|
||||
*/
|
||||
terminalRows?: number;
|
||||
}
|
||||
|
||||
const DEFAULT_MAX_RENDERED = 2400;
|
||||
/**
|
||||
* Reserved terminal rows for the picker chrome (border + header +
|
||||
* divider + open-questions hint + SingleSelect with three options +
|
||||
* footer + the assistant-turn block Ink already printed above).
|
||||
* Empirically ~16; we round up to 18 for safety.
|
||||
*/
|
||||
const PICKER_CHROME_ROWS = 18;
|
||||
/**
|
||||
* Rough markdown expansion factor. One source line commonly renders
|
||||
* as 1–3 terminal rows: wrap on narrow terminals doubles long lines,
|
||||
* code fences add top/bottom rules, list items get bullet indent,
|
||||
* headings sometimes pick up blank rows. A factor of 2 is the
|
||||
* conservative bet that lets us keep `bodyRowBudget` > 0 on a 24-row
|
||||
* terminal while still guaranteeing the picker stays on-screen. If
|
||||
* this is wrong in practice it's wrong in the "trim too aggressively"
|
||||
* direction, which shows a truncation marker rather than flickering.
|
||||
*/
|
||||
const MARKDOWN_EXPANSION = 2;
|
||||
const MIN_BODY_ROWS = 4;
|
||||
|
||||
/**
|
||||
* Trim `text` to the first `maxLines` source lines, appending a
|
||||
* truncation marker when it was cut. Source lines, NOT rendered rows
|
||||
* — callers must divide their row budget by the expected markdown
|
||||
* expansion factor before passing it here.
|
||||
*/
|
||||
export function clampBodyByLines(text: string, maxLines: number): string {
|
||||
const lines = text.split("\n");
|
||||
if (lines.length <= maxLines) return text;
|
||||
const kept = lines.slice(0, maxLines).join("\n");
|
||||
const dropped = lines.length - maxLines;
|
||||
return `${kept}\n\n… (${dropped} more lines truncated — resize the terminal to see more, or /tool for the full proposal)`;
|
||||
}
|
||||
|
||||
function PlanConfirmInner({
|
||||
plan,
|
||||
onChoose,
|
||||
maxRenderedChars,
|
||||
projectRoot,
|
||||
terminalRows,
|
||||
}: PlanConfirmProps) {
|
||||
const cap = maxRenderedChars ?? DEFAULT_MAX_RENDERED;
|
||||
const charTrunc = plan.length > cap;
|
||||
const charCapped = charTrunc
|
||||
? `${plan.slice(0, cap)}\n\n… (${plan.length - cap} chars truncated — use /tool to view the full proposal)`
|
||||
: plan;
|
||||
// Vertical clamp. Flicker root-cause: when rendered content exceeds
|
||||
// the TTY row count Ink falls back to "clear + full redraw" each
|
||||
// frame, and every parent re-render redraws the big Markdown subtree.
|
||||
// Capping the body to (rows - picker chrome) keeps the whole modal
|
||||
// inside the terminal so Ink uses incremental diffs and the picker
|
||||
// stops thrashing. See Bug A in 0.5.14.
|
||||
const rows = terminalRows ?? process.stdout?.rows ?? 24;
|
||||
const renderedBudget = Math.max(MIN_BODY_ROWS * MARKDOWN_EXPANSION, rows - PICKER_CHROME_ROWS);
|
||||
// Divide by the expansion factor so source-line clamp produces a
|
||||
// rendered height that actually fits the terminal. Without this the
|
||||
// rendered body overflows → Ink clears + redraws each frame → flicker.
|
||||
const sourceLineBudget = Math.max(MIN_BODY_ROWS, Math.floor(renderedBudget / MARKDOWN_EXPANSION));
|
||||
const visible = clampBodyByLines(charCapped, sourceLineBudget);
|
||||
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.
|
||||
@@ -110,55 +45,50 @@ function PlanConfirmInner({
|
||||
/^#{1,6}\s*(待确认|开放问题|风险|未知|假设|不确定)/im.test(plan);
|
||||
|
||||
return (
|
||||
<Box flexDirection="column" borderStyle="round" borderColor="cyan" paddingX={1} marginY={1}>
|
||||
<Box>
|
||||
<Text bold color="cyan">
|
||||
▸ plan submitted — awaiting your review
|
||||
</Text>
|
||||
</Box>
|
||||
<Box>
|
||||
<Text color="cyan" dimColor>
|
||||
{"──────────────────────────────────────────"}
|
||||
</Text>
|
||||
</Box>
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
<Markdown text={visible} projectRoot={projectRoot} />
|
||||
</Box>
|
||||
<ModalCard
|
||||
accent="#67e8f9"
|
||||
icon="📋"
|
||||
title="plan proposed"
|
||||
subtitle={summary ?? "approve / refine / cancel"}
|
||||
>
|
||||
{hasOpenQuestions ? (
|
||||
<Box marginTop={1}>
|
||||
<Text color="yellow">
|
||||
▲ the plan has open questions or flagged risks — pick{" "}
|
||||
<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}
|
||||
<Box marginTop={1}>
|
||||
<SingleSelect
|
||||
initialValue={hasOpenQuestions ? "refine" : "approve"}
|
||||
items={[
|
||||
{
|
||||
value: "approve",
|
||||
label: "Approve and implement",
|
||||
hint: "Exit plan mode. The model starts executing. You'll get a text input to add any last instructions (or just press Enter to skip).",
|
||||
},
|
||||
{
|
||||
value: "refine",
|
||||
label: "Refine / answer questions",
|
||||
hint: "Stay in plan mode. Write answers, modifications, or critiques; the model revises and re-submits.",
|
||||
},
|
||||
{
|
||||
value: "cancel",
|
||||
label: "Cancel",
|
||||
hint: "Exit plan mode. Drop the plan; the model won't implement it.",
|
||||
},
|
||||
]}
|
||||
onSubmit={(v) => onChoose(v as PlanConfirmChoice)}
|
||||
onCancel={() => onChoose("cancel")}
|
||||
footer="[↑↓] navigate · [Enter] select · [Esc] cancel"
|
||||
/>
|
||||
</Box>
|
||||
</Box>
|
||||
{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>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -14,17 +14,24 @@
|
||||
* the picker without resuming.
|
||||
*/
|
||||
|
||||
import { Box, Text, useInput } from "ink";
|
||||
import { Box, Text } from "ink";
|
||||
import React, { useState } from "react";
|
||||
import { ModalCard } from "./ModalCard.js";
|
||||
import { useKeystroke } from "./keystroke-context.js";
|
||||
import { COLOR } from "./theme.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".
|
||||
* Drives the header + hint text so users know what kind of message
|
||||
* they're writing.
|
||||
* 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";
|
||||
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. */
|
||||
@@ -34,58 +41,94 @@ export interface PlanRefineInputProps {
|
||||
export function PlanRefineInput({ mode, onSubmit, onCancel }: PlanRefineInputProps) {
|
||||
const [value, setValue] = useState("");
|
||||
|
||||
useInput((input, key) => {
|
||||
if (key.escape) {
|
||||
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 (key.return) {
|
||||
if (ev.return) {
|
||||
onSubmit(value.trim());
|
||||
return;
|
||||
}
|
||||
if (key.backspace || key.delete) {
|
||||
if (ev.backspace || ev.delete) {
|
||||
setValue((v) => v.slice(0, -1));
|
||||
return;
|
||||
}
|
||||
// Filter out non-printable chars; accept ordinary text + CJK.
|
||||
if (input && !key.ctrl && !key.meta) {
|
||||
setValue((v) => v + input);
|
||||
if (ev.input && !ev.ctrl && !ev.meta) {
|
||||
setValue((v) => v + ev.input);
|
||||
}
|
||||
});
|
||||
|
||||
const title =
|
||||
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"
|
||||
? "▸ approving — any last instructions or answers to open questions?"
|
||||
: "▸ refining — what should the model change?";
|
||||
? {
|
||||
title: "approving — any last instructions?",
|
||||
icon: "◇",
|
||||
accent: COLOR.primary,
|
||||
}
|
||||
: mode === "checkpoint-revise"
|
||||
? {
|
||||
title: "revising — what should change before the next step?",
|
||||
icon: "✎",
|
||||
accent: COLOR.warn,
|
||||
}
|
||||
: mode === "choice-custom"
|
||||
? {
|
||||
title: "custom answer — type whatever fits",
|
||||
icon: "⌥",
|
||||
accent: COLOR.accent,
|
||||
}
|
||||
: {
|
||||
title: "refining — what should the model change?",
|
||||
icon: "✎",
|
||||
accent: COLOR.warn,
|
||||
};
|
||||
const hint =
|
||||
mode === "approve"
|
||||
? "Answer questions the plan raised, add constraints, or just press Enter to approve as-is."
|
||||
: "Describe what's wrong or missing, or answer questions the plan raised.";
|
||||
: 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.)"
|
||||
: " (Enter with blank = ask the model to list concrete questions.)";
|
||||
: mode === "checkpoint-revise"
|
||||
? " (Enter with blank = continue with the current plan.)"
|
||||
: mode === "choice-custom"
|
||||
? " (Enter with blank = ask the model what you actually want.)"
|
||||
: " (Enter with blank = ask the model to list concrete questions.)";
|
||||
|
||||
return (
|
||||
<Box flexDirection="column" borderStyle="round" borderColor="yellow" paddingX={1} marginY={1}>
|
||||
<Box>
|
||||
<Text bold color="yellow">
|
||||
{title}
|
||||
</Text>
|
||||
</Box>
|
||||
<Box marginTop={1}>
|
||||
<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 marginTop={1}>
|
||||
<Text>
|
||||
<Text color="yellow">› </Text>
|
||||
<Text>{value || " "}</Text>
|
||||
<Text color="yellow">▍</Text>
|
||||
<Box>
|
||||
<Text color={meta.accent} bold>
|
||||
{"› "}
|
||||
</Text>
|
||||
<Text>{value}</Text>
|
||||
<Text color={meta.accent} bold>
|
||||
{cursorOn ? "▍" : " "}
|
||||
</Text>
|
||||
</Box>
|
||||
</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);
|
||||
@@ -9,39 +9,44 @@
|
||||
* - uncertainties: yellow — attention required (like tool)
|
||||
* - rejected paths: red dim — ruled out (muted, like error-but-resolved)
|
||||
*
|
||||
* Only the label is colored + bold. The items themselves render in the
|
||||
* terminal's default foreground, so they stay readable on any background —
|
||||
* which is why the old single-magenta block was hard to see on dark themes.
|
||||
* Visual: colored bold label + count, then dim items. No solid-bg pill
|
||||
* — every assistant turn surfaces this block, so the bracket-text style
|
||||
* keeps it from shouting four colored bg blocks at the user every turn.
|
||||
* Color alone (the bold label) is enough to identify the field type.
|
||||
*/
|
||||
|
||||
import { Box, Text } from "ink";
|
||||
import React from "react";
|
||||
import type { TypedPlanState } from "../../harvest.js";
|
||||
import { COLOR } from "./theme.js";
|
||||
|
||||
type FieldColor = "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, COLOR.primary, false]);
|
||||
if (planState.hypotheses.length)
|
||||
fields.push(["hypotheses", planState.hypotheses, "green", false]);
|
||||
fields.push(["hypotheses", planState.hypotheses, COLOR.assistant, false]);
|
||||
if (planState.uncertainties.length)
|
||||
fields.push(["uncertainties", planState.uncertainties, "yellow", false]);
|
||||
fields.push(["uncertainties", planState.uncertainties, COLOR.warn, false]);
|
||||
if (planState.rejectedPaths.length)
|
||||
fields.push(["rejected", planState.rejectedPaths, "red", true]);
|
||||
fields.push(["rejected", planState.rejectedPaths, COLOR.info, true]);
|
||||
if (fields.length === 0) return null;
|
||||
|
||||
return (
|
||||
<Box flexDirection="column" marginBottom={1}>
|
||||
{fields.map(([label, items, color, dim]) => (
|
||||
<Text key={label}>
|
||||
<Box key={label}>
|
||||
<Text color={color} bold dimColor={dim}>
|
||||
{"‹ "}
|
||||
{label}
|
||||
</Text>
|
||||
<Text dimColor>{` (${items.length})`}</Text>
|
||||
<Text>{`: ${items.join(" · ")}`}</Text>
|
||||
</Text>
|
||||
<Text dimColor>{" · "}</Text>
|
||||
<Text dimColor={dim} color={dim ? undefined : COLOR.info}>
|
||||
{items.join(" · ")}
|
||||
</Text>
|
||||
</Box>
|
||||
))}
|
||||
</Box>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
/**
|
||||
* Compact tree-style 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.
|
||||
*
|
||||
* Layout per step:
|
||||
*
|
||||
* 2/5 done (40%) · est. 5 steps
|
||||
* ┣ ✓ step-1 · Extract tokens into a module
|
||||
* ┣ ✓ step-2 · Migrate session cookies ⚠ med
|
||||
* ┣ ▸ step-3 · Update tests ⚠ high
|
||||
* ┣ ○ step-4 · Run regression suite
|
||||
* ┗ ○ step-5 · Audit every callsite
|
||||
* ████████░░░░░░░░░░░░ 40%
|
||||
*
|
||||
* Why this shape:
|
||||
* - Status icons (✓ ▸ ○ ✗) read at a glance — color + glyph are
|
||||
* redundant signals, useful for color-blind users and for
|
||||
* terminals where a single bg-color cell is the only contrast.
|
||||
* - Tree branch lines (┣ ┗) visually bind the steps as one group
|
||||
* and mark "last step" with a corner — the eye finds the bottom
|
||||
* without counting.
|
||||
* - Risk only shown ≥medium. low risk on every line is noise (most
|
||||
* steps are low-risk — that's the default). med + high are the
|
||||
* ones that deserve attention before approve.
|
||||
* - Bottom progress bar (24 cells of █ / ░) makes "how far in are
|
||||
* we" answerable from the cursor's eye position alone.
|
||||
*/
|
||||
|
||||
import { Box, Text } from "ink";
|
||||
import React from "react";
|
||||
import type { PlanStep, PlanStepRisk } from "../../tools/plan.js";
|
||||
import { CharBar } from "./char-bar.js";
|
||||
import { COLOR, GLYPH } from "./theme.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 the `cur` (▸) glyph in cyan
|
||||
* even when its status is still "pending", so the user sees which
|
||||
* one's about to run. If the step's status is "running" we always
|
||||
* use the cur glyph regardless of focusStepId.
|
||||
*/
|
||||
focusStepId?: string;
|
||||
}
|
||||
|
||||
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";
|
||||
}
|
||||
|
||||
interface StatusGlyph {
|
||||
glyph: string;
|
||||
color: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Map (status, focus) → (glyph, color). Centralized so a future tweak
|
||||
* (e.g. add a "queued for retry" state) lands in one switch instead of
|
||||
* five render branches.
|
||||
*/
|
||||
function statusGlyph(status: StepStatus, isCur: boolean): StatusGlyph {
|
||||
if (status === "done") return { glyph: GLYPH.done, color: COLOR.ok };
|
||||
if (status === "running") return { glyph: GLYPH.cur, color: COLOR.primary };
|
||||
if (status === "skipped") return { glyph: GLYPH.fail, color: COLOR.info };
|
||||
// pending: focus override gets the cur glyph (▸) in primary color so
|
||||
// the active row pops without us needing a separate column.
|
||||
if (isCur) return { glyph: GLYPH.cur, color: COLOR.primary };
|
||||
return { glyph: GLYPH.pending, color: COLOR.info };
|
||||
}
|
||||
|
||||
function riskLabel(risk: PlanStepRisk | undefined): { text: string; color: string } | null {
|
||||
if (risk === "med") return { text: `${GLYPH.warn} med`, color: COLOR.warn };
|
||||
if (risk === "high") return { text: `${GLYPH.warn} high`, color: COLOR.err };
|
||||
// low + undefined: omitted entirely (the default reading should be
|
||||
// "low risk" — surfacing it on every line buries the med/high ones).
|
||||
return null;
|
||||
}
|
||||
|
||||
function PlanStepListInner({ steps, statuses, focusStepId }: PlanStepListProps) {
|
||||
if (steps.length === 0) return null;
|
||||
const statusList = steps.map((s) => getStatus(s.id, statuses));
|
||||
const total = steps.length;
|
||||
const doneCount = statusList.filter((s) => s === "done").length;
|
||||
const pct = Math.round((doneCount / total) * 100);
|
||||
// Show progress only when the plan has any motion. A freshly-submitted
|
||||
// plan with 0/N done renders without the bar to avoid an empty
|
||||
// "░░░░░░░░░░ 0%" rule that signals nothing.
|
||||
const showProgress = doneCount > 0;
|
||||
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
<Box>
|
||||
<Text dimColor>
|
||||
{showProgress
|
||||
? `${doneCount}/${total} done (${pct}%) · ${total} step${total === 1 ? "" : "s"}`
|
||||
: `${total} step${total === 1 ? "" : "s"}`}
|
||||
</Text>
|
||||
</Box>
|
||||
<Box flexDirection="column">
|
||||
{steps.map((step, i) => {
|
||||
const status = statusList[i]!;
|
||||
const isLast = i === total - 1;
|
||||
const isCur = focusStepId === step.id;
|
||||
const sg = statusGlyph(status, isCur);
|
||||
const risk = riskLabel(step.risk);
|
||||
const titleDim = status === "done" || status === "skipped";
|
||||
return (
|
||||
<Box key={step.id}>
|
||||
<Text color={COLOR.info} dimColor>
|
||||
{isLast ? GLYPH.branchEnd : GLYPH.branch}
|
||||
</Text>
|
||||
<Text>{" "}</Text>
|
||||
<Text color={sg.color} bold={status === "running" || isCur}>
|
||||
{sg.glyph}
|
||||
</Text>
|
||||
<Text>{" "}</Text>
|
||||
<Text
|
||||
dimColor={titleDim}
|
||||
bold={isCur || status === "running"}
|
||||
strikethrough={status === "done" || status === "skipped"}
|
||||
>
|
||||
{`${step.id} · ${step.title}`}
|
||||
</Text>
|
||||
{risk ? (
|
||||
<>
|
||||
<Text>{" "}</Text>
|
||||
<Text color={risk.color}>{risk.text}</Text>
|
||||
</>
|
||||
) : null}
|
||||
</Box>
|
||||
);
|
||||
})}
|
||||
</Box>
|
||||
{showProgress ? (
|
||||
<Box>
|
||||
<Text>{" "}</Text>
|
||||
<CharBar pct={pct} width={24} />
|
||||
</Box>
|
||||
) : null}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
export const PlanStepList = React.memo(PlanStepListInner);
|
||||
|
||||
export function riskOf(step: PlanStep): PlanStepRisk | undefined {
|
||||
return step.risk;
|
||||
}
|
||||
+522
-117
@@ -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,516 @@ 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… · [Esc] to stop")
|
||||
: (placeholder ?? "type a message, or /command · [Shift+Enter] / [Ctrl+J] newline");
|
||||
? (placeholder ?? "…waiting for response…")
|
||||
: (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 && !narrow && value.length === 0 ? (
|
||||
<Box>
|
||||
<Text color={barColorAt(0)}>{BAR}</Text>
|
||||
<Text dimColor>{continuationIndent.slice(BAR.length)}</Text>
|
||||
<Text dimColor>
|
||||
[PgUp/PgDn] scroll log · [End] jump to latest · drag to select · auto-scrolls at edge
|
||||
</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;
|
||||
}
|
||||
@@ -10,7 +10,7 @@
|
||||
|
||||
import { Box, Text } from "ink";
|
||||
import React from "react";
|
||||
import type { TranscriptRecord } from "../../transcript.js";
|
||||
import type { TranscriptRecord } from "../../transcript/log.js";
|
||||
import { PlanStateBlock } from "./PlanStateBlock.js";
|
||||
|
||||
export interface RecordViewProps {
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -10,8 +10,8 @@
|
||||
|
||||
import { Box, Static, Text, useApp, useInput } from "ink";
|
||||
import React, { useMemo, useState } from "react";
|
||||
import { type TurnPage, computeCumulativeStats } from "../../replay.js";
|
||||
import type { TranscriptMeta } from "../../transcript.js";
|
||||
import type { TranscriptMeta } from "../../transcript/log.js";
|
||||
import { type TurnPage, computeCumulativeStats } from "../../transcript/replay.js";
|
||||
import { RecordView } from "./RecordView.js";
|
||||
import { StatsPanel } from "./StatsPanel.js";
|
||||
|
||||
@@ -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 =
|
||||
@@ -74,11 +75,7 @@ export function ReplayApp({ meta, pages }: ReplayAppProps) {
|
||||
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
<StatsPanel
|
||||
summary={summary}
|
||||
model={cumStats.models[0] ?? meta?.model ?? "?"}
|
||||
prefixHash={prefixHash}
|
||||
/>
|
||||
<StatsPanel summary={summary} />
|
||||
|
||||
<Box flexDirection="column" marginTop={1} paddingX={1}>
|
||||
<Box justifyContent="space-between">
|
||||
|
||||
+92
-32
@@ -9,8 +9,10 @@
|
||||
* 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";
|
||||
import { COLOR } from "./theme.js";
|
||||
|
||||
export interface SelectItem<V extends string = string> {
|
||||
/** Stable identifier — returned to caller on submit. */
|
||||
@@ -21,19 +23,16 @@ export interface SelectItem<V extends string = string> {
|
||||
hint?: string;
|
||||
/** If true, item is not selectable (rendered dimmed, skipped on nav). */
|
||||
disabled?: boolean;
|
||||
/** Tab on this item starts inline-edit; typed text is forwarded as `onSubmit`'s 2nd arg. */
|
||||
denyWithContext?: boolean;
|
||||
}
|
||||
|
||||
export interface SingleSelectProps<V extends string> {
|
||||
items: SelectItem<V>[];
|
||||
initialValue?: V;
|
||||
onSubmit: (value: V) => void;
|
||||
onSubmit: (value: V, context?: string) => 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.
|
||||
*/
|
||||
/** Optional dim footer beneath the list — e.g. "[↑↓] navigate · [Enter] select · [Esc] cancel". */
|
||||
footer?: string;
|
||||
}
|
||||
|
||||
@@ -49,33 +48,83 @@ export function SingleSelect<V extends string>({
|
||||
items.findIndex((i) => i.value === initialValue && !i.disabled),
|
||||
);
|
||||
const [index, setIndex] = useState(initialIndex === -1 ? 0 : initialIndex);
|
||||
const [editingContext, setEditingContext] = useState<string | null>(null);
|
||||
const activeItem = items[index];
|
||||
const isEditing = editingContext !== null;
|
||||
|
||||
useInput((_input, key) => {
|
||||
if (key.upArrow) {
|
||||
useKeystroke((ev) => {
|
||||
if (isEditing) {
|
||||
if (ev.paste) {
|
||||
setEditingContext((v) => (v ?? "") + ev.input);
|
||||
return;
|
||||
}
|
||||
if (ev.escape) {
|
||||
setEditingContext(null);
|
||||
} else if (ev.upArrow || ev.downArrow) {
|
||||
setEditingContext(null);
|
||||
setIndex((i) => findNextEnabled(items, i, ev.upArrow ? -1 : +1));
|
||||
} else if (ev.return) {
|
||||
const chosen = items[index];
|
||||
if (chosen && !chosen.disabled) {
|
||||
const ctx = editingContext || undefined;
|
||||
setEditingContext(null);
|
||||
onSubmit(chosen.value, ctx);
|
||||
}
|
||||
} else if (ev.backspace) {
|
||||
setEditingContext((v) => (v ?? "").slice(0, -1));
|
||||
} else if (ev.tab) {
|
||||
setEditingContext((v) => `${v ?? ""}, `);
|
||||
} else if (ev.input) {
|
||||
setEditingContext((v) => (v ?? "") + ev.input);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
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.tab && activeItem?.denyWithContext) {
|
||||
setEditingContext("");
|
||||
} 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();
|
||||
}
|
||||
});
|
||||
|
||||
const canDenyWithContext = activeItem?.denyWithContext;
|
||||
const resolvedFooter = (() => {
|
||||
if (isEditing) return "[Enter] confirm · [Esc] cancel · [↑↓] change option";
|
||||
return (
|
||||
footer ??
|
||||
(canDenyWithContext
|
||||
? "[↑↓] navigate · [Enter] select · [Tab] add context · [Esc] cancel"
|
||||
: undefined)
|
||||
);
|
||||
})();
|
||||
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
{items.map((item, i) => (
|
||||
<SelectRow
|
||||
key={item.value}
|
||||
item={item}
|
||||
active={i === index}
|
||||
marker={i === index ? "▸" : " "}
|
||||
/>
|
||||
))}
|
||||
{footer ? (
|
||||
{items.map((item, i) => {
|
||||
const showEditing = i === index && isEditing;
|
||||
const displayLabel = showEditing ? `${item.label}, ${editingContext}` : item.label;
|
||||
return (
|
||||
<SelectRow
|
||||
key={item.value}
|
||||
item={{ ...item, label: displayLabel }}
|
||||
active={i === index}
|
||||
marker={i === index ? "▸" : " "}
|
||||
showInlineCursor={showEditing}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
{resolvedFooter ? (
|
||||
<Box marginTop={1}>
|
||||
<Text dimColor>{footer}</Text>
|
||||
<Text dimColor>{resolvedFooter}</Text>
|
||||
</Box>
|
||||
) : null}
|
||||
</Box>
|
||||
@@ -87,7 +136,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;
|
||||
}
|
||||
|
||||
@@ -104,12 +153,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) => {
|
||||
@@ -118,13 +168,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();
|
||||
}
|
||||
});
|
||||
@@ -158,18 +208,28 @@ function SelectRow<V extends string>({
|
||||
item,
|
||||
active,
|
||||
marker,
|
||||
showInlineCursor = false,
|
||||
}: {
|
||||
item: SelectItem<V>;
|
||||
active: boolean;
|
||||
marker: string;
|
||||
showInlineCursor?: boolean;
|
||||
}) {
|
||||
const color = item.disabled ? "gray" : active ? "cyan" : undefined;
|
||||
// Color: dim for disabled, primary cyan + bold for active, plain
|
||||
// default for inactive. Keeps the active-row affordance consistent
|
||||
// with the slash + at-mention pickers (▸ + colored text).
|
||||
const color = item.disabled ? COLOR.info : active ? COLOR.primary : undefined;
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
<Box>
|
||||
<Text color={color}>
|
||||
<Text color={color} bold={active} dimColor={item.disabled}>
|
||||
{marker} {item.label}
|
||||
</Text>
|
||||
{showInlineCursor ? (
|
||||
<Text backgroundColor="#67e8f9" color="black">
|
||||
{" "}
|
||||
</Text>
|
||||
) : null}
|
||||
</Box>
|
||||
{item.hint ? (
|
||||
<Box paddingLeft={marker.length + 1}>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Box, Text } from "ink";
|
||||
import React from "react";
|
||||
import { SingleSelect } from "./Select.js";
|
||||
import { COLOR, GLYPH } from "./theme.js";
|
||||
|
||||
export type SessionChoice = "resume" | "new" | "delete";
|
||||
|
||||
@@ -12,6 +13,15 @@ export interface SessionPickerProps {
|
||||
onChoose: (choice: SessionChoice) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resume / new / delete picker shown at launch when a prior session
|
||||
* file exists. Three lines of header (brand mark · session summary)
|
||||
* then the selector, then a footer with key bindings.
|
||||
*
|
||||
* Visual grammar matches the design's session-resume modal: brand
|
||||
* glyph in primary color, session name highlighted, the rest dim.
|
||||
* No solid-bg pills — bracket-text style continues.
|
||||
*/
|
||||
export function SessionPicker({
|
||||
sessionName,
|
||||
messageCount,
|
||||
@@ -21,9 +31,14 @@ export function SessionPicker({
|
||||
return (
|
||||
<Box flexDirection="column" marginY={1}>
|
||||
<Box marginBottom={1}>
|
||||
<Text bold color="cyan">
|
||||
{`Session "${sessionName}" has ${messageCount} prior message${messageCount === 1 ? "" : "s"}`}
|
||||
<Text color={COLOR.brand} bold>
|
||||
{GLYPH.brand}
|
||||
</Text>
|
||||
<Text>{" "}</Text>
|
||||
<Text color={COLOR.primary} bold>
|
||||
{`"${sessionName}"`}
|
||||
</Text>
|
||||
<Text dimColor>{` has ${messageCount} prior message${messageCount === 1 ? "" : "s"}`}</Text>
|
||||
<Text dimColor>{` · last active ${relativeTime(lastActive)}`}</Text>
|
||||
</Box>
|
||||
<SingleSelect
|
||||
@@ -48,7 +63,7 @@ export function SessionPicker({
|
||||
onSubmit={(v) => onChoose(v as SessionChoice)}
|
||||
/>
|
||||
<Box marginTop={1}>
|
||||
<Text dimColor>↑↓ to move · Enter to pick</Text>
|
||||
<Text dimColor>{" ↑↓ navigate · ⏎ select"}</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
|
||||
+33
-13
@@ -2,6 +2,7 @@ import { Box, Text, useApp } from "ink";
|
||||
import TextInput from "ink-text-input";
|
||||
import React, { useState } from "react";
|
||||
import { defaultConfigPath, isPlausibleKey, redactKey, saveApiKey } from "../../config.js";
|
||||
import { COLOR, GLYPH, GRADIENT } from "./theme.js";
|
||||
|
||||
export interface SetupProps {
|
||||
onReady: (apiKey: string) => void;
|
||||
@@ -33,18 +34,34 @@ export function Setup({ onReady }: SetupProps) {
|
||||
};
|
||||
|
||||
return (
|
||||
<Box flexDirection="column" borderStyle="round" borderColor="cyan" paddingX={1}>
|
||||
<Text bold color="cyan">
|
||||
Welcome to Reasonix.
|
||||
</Text>
|
||||
<Box marginTop={1}>
|
||||
<Text>Paste your DeepSeek API key to get started.</Text>
|
||||
<Box flexDirection="column" paddingX={1} marginY={1}>
|
||||
<Box>
|
||||
<Text bold color={GRADIENT[0]}>
|
||||
{GLYPH.brand}
|
||||
</Text>
|
||||
<Text>{" "}</Text>
|
||||
<Text bold>Welcome to </Text>
|
||||
<Text bold color={GRADIENT[2]}>
|
||||
REASONIX
|
||||
</Text>
|
||||
</Box>
|
||||
<Text dimColor>Get one (free credit on signup): https://platform.deepseek.com/api_keys</Text>
|
||||
<Text dimColor>Saved locally to {defaultConfigPath()}</Text>
|
||||
<Box marginTop={1}>
|
||||
<Text bold color="cyan">
|
||||
{"key › "}
|
||||
<Text color={COLOR.info}>Paste your DeepSeek API key to get started.</Text>
|
||||
</Box>
|
||||
<Box>
|
||||
<Text dimColor>{" free credit on signup · "}</Text>
|
||||
<Text color={COLOR.primary}>https://platform.deepseek.com/api_keys</Text>
|
||||
</Box>
|
||||
<Box>
|
||||
<Text dimColor>{" saved to "}</Text>
|
||||
<Text dimColor>{defaultConfigPath()}</Text>
|
||||
</Box>
|
||||
<Box marginTop={1}>
|
||||
<Text bold color={COLOR.brand}>
|
||||
{GLYPH.bar}
|
||||
</Text>
|
||||
<Text bold color={COLOR.primary}>
|
||||
{" › "}
|
||||
</Text>
|
||||
<TextInput
|
||||
value={value}
|
||||
@@ -56,15 +73,18 @@ export function Setup({ onReady }: SetupProps) {
|
||||
</Box>
|
||||
{error ? (
|
||||
<Box marginTop={1}>
|
||||
<Text color="red">{error}</Text>
|
||||
<Text color={COLOR.err} bold>
|
||||
{GLYPH.err}
|
||||
</Text>
|
||||
<Text color={COLOR.err}>{` ${error}`}</Text>
|
||||
</Box>
|
||||
) : value ? (
|
||||
<Box marginTop={1}>
|
||||
<Text dimColor>preview: {redactKey(value)}</Text>
|
||||
<Text dimColor>{` preview · ${redactKey(value)}`}</Text>
|
||||
</Box>
|
||||
) : null}
|
||||
<Box marginTop={1}>
|
||||
<Text dimColor>(Type /exit to abort.)</Text>
|
||||
<Text dimColor>{" /exit to abort"}</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
|
||||
+58
-44
@@ -1,6 +1,8 @@
|
||||
import { Box, Text } from "ink";
|
||||
import React from "react";
|
||||
import { ModalCard } from "./ModalCard.js";
|
||||
import { SingleSelect } from "./Select.js";
|
||||
import { COLOR } from "./theme.js";
|
||||
|
||||
export type ShellConfirmChoice = "run_once" | "always_allow" | "deny";
|
||||
|
||||
@@ -11,7 +13,14 @@ export interface ShellConfirmProps {
|
||||
* "always allow". Typically the first 1-2 tokens of `command`.
|
||||
*/
|
||||
allowPrefix: string;
|
||||
onChoose: (choice: ShellConfirmChoice) => void;
|
||||
/**
|
||||
* 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, denyContext?: string) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -23,53 +32,58 @@ export interface ShellConfirmProps {
|
||||
* auto-runs.
|
||||
* 3. Deny — tell the model the user refused.
|
||||
* Arrow keys + Enter. No y/n hotkey — too easy to trigger by accident
|
||||
* when the user was mid-typing a response.
|
||||
* when the user was mid-typing a response. Tab on Deny opens inline
|
||||
* context entry, returned as `onChoose`'s 2nd arg.
|
||||
*/
|
||||
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";
|
||||
|
||||
const denyItem = {
|
||||
value: "deny" as const,
|
||||
label: "Deny",
|
||||
hint: "Not what you wanted? Press Tab to append `,` and tell the model what to do instead.",
|
||||
denyWithContext: true as const,
|
||||
};
|
||||
|
||||
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={COLOR.err}
|
||||
icon={isBackground ? "⏱" : "⚡"}
|
||||
title={isBackground ? "background process" : "shell command"}
|
||||
subtitle={subtitle}
|
||||
>
|
||||
<Box marginBottom={1}>
|
||||
<Text color={COLOR.primary} bold>
|
||||
{"$ "}
|
||||
</Text>
|
||||
<Text bold>{command}</Text>
|
||||
</Box>
|
||||
<Box>
|
||||
<Text color="yellow" dimColor>
|
||||
{"──────────────────────────────────────────"}
|
||||
</Text>
|
||||
</Box>
|
||||
<Box marginTop={1}>
|
||||
<Text>
|
||||
<Text dimColor>{"$ "}</Text>
|
||||
<Text color="cyan">{command}</Text>
|
||||
</Text>
|
||||
</Box>
|
||||
<Box marginTop={1}>
|
||||
<SingleSelect
|
||||
initialValue="run_once"
|
||||
items={[
|
||||
{
|
||||
value: "run_once",
|
||||
label: "Run once",
|
||||
hint: "Execute this command, don't remember it.",
|
||||
},
|
||||
{
|
||||
value: "always_allow",
|
||||
label: `Always allow "${allowPrefix}" in this project`,
|
||||
hint: "Save the prefix to ~/.reasonix/config.json; future matches auto-run.",
|
||||
},
|
||||
{
|
||||
value: "deny",
|
||||
label: "Deny",
|
||||
hint: "Tell the model the user refused; it will continue without this command.",
|
||||
},
|
||||
]}
|
||||
onSubmit={(v) => onChoose(v as ShellConfirmChoice)}
|
||||
onCancel={() => onChoose("deny")}
|
||||
footer="[↑↓] navigate · [Enter] select · [Esc] deny"
|
||||
/>
|
||||
</Box>
|
||||
</Box>
|
||||
<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.",
|
||||
},
|
||||
denyItem,
|
||||
]}
|
||||
onSubmit={(v, ctx) => {
|
||||
if (v === "deny") onChoose("deny", ctx);
|
||||
else onChoose(v as ShellConfirmChoice);
|
||||
}}
|
||||
onCancel={() => onChoose("deny")}
|
||||
footer="[↑↓] navigate · [Enter] select · [Tab] add context · [Esc] deny"
|
||||
/>
|
||||
</ModalCard>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ import { Box, Text } from "ink";
|
||||
// biome-ignore lint/style/useImportType: tsconfig.jsx = "react" needs React in value scope for JSX compilation
|
||||
import React from "react";
|
||||
import type { SlashCommandSpec } from "./slash.js";
|
||||
import { COLOR, GLYPH } from "./theme.js";
|
||||
|
||||
export interface SlashArgPickerProps {
|
||||
/**
|
||||
@@ -36,15 +37,28 @@ export function SlashArgPicker({
|
||||
kind,
|
||||
partial,
|
||||
}: SlashArgPickerProps): React.ReactElement | null {
|
||||
// Hint mode: a single dim row explaining the argsHint + summary.
|
||||
// Header row shared by both hint and picker modes — same shape so
|
||||
// the UI looks like the same affordance, just with or without rows
|
||||
// beneath. cmd in accent violet (matches SlashSuggestions), argsHint
|
||||
// in dim, summary in info.
|
||||
const headerRow = (
|
||||
<Box>
|
||||
<Text color={COLOR.accent} bold>
|
||||
{"/ "}
|
||||
</Text>
|
||||
<Text color={COLOR.accent} bold>
|
||||
{`/${spec.cmd}`}
|
||||
</Text>
|
||||
{spec.argsHint ? <Text dimColor>{` ${spec.argsHint}`}</Text> : null}
|
||||
<Text dimColor>{` ${spec.summary}`}</Text>
|
||||
</Box>
|
||||
);
|
||||
|
||||
// Hint mode: header only.
|
||||
if (kind === "hint") {
|
||||
return (
|
||||
<Box paddingX={1}>
|
||||
<Text dimColor>
|
||||
{" "}
|
||||
<Text bold>/{spec.cmd}</Text>
|
||||
{spec.argsHint ? ` ${spec.argsHint}` : ""} — {spec.summary}
|
||||
</Text>
|
||||
<Box paddingX={1} marginTop={1}>
|
||||
{headerRow}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -52,13 +66,15 @@ export function SlashArgPicker({
|
||||
if (matches === null) return null;
|
||||
if (matches.length === 0) {
|
||||
return (
|
||||
<Box flexDirection="column" paddingX={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 flexDirection="column" paddingX={1} marginTop={1}>
|
||||
{headerRow}
|
||||
<Box>
|
||||
<Text color={COLOR.warn} bold>
|
||||
{GLYPH.warn}
|
||||
</Text>
|
||||
<Text color={COLOR.warn}>{` no match for "${partial}"`}</Text>
|
||||
<Text dimColor>{" — keep typing, or Backspace to edit"}</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -71,37 +87,28 @@ export function SlashArgPicker({
|
||||
const hiddenAbove = windowStart;
|
||||
const hiddenBelow = total - windowStart - shown.length;
|
||||
return (
|
||||
<Box flexDirection="column" paddingX={1}>
|
||||
<Text dimColor>
|
||||
{" "}
|
||||
<Text bold>/{spec.cmd}</Text>
|
||||
{spec.argsHint ? ` ${spec.argsHint}` : ""} — {spec.summary}
|
||||
</Text>
|
||||
{hiddenAbove > 0 ? <Text dimColor> ↑ {hiddenAbove} more above</Text> : null}
|
||||
<Box flexDirection="column" paddingX={1} marginTop={1}>
|
||||
{headerRow}
|
||||
{hiddenAbove > 0 ? <Text dimColor>{` ↑ ${hiddenAbove} 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>
|
||||
{hiddenBelow > 0 ? <Text dimColor>{` ↓ ${hiddenBelow} below`}</Text> : null}
|
||||
<Box marginTop={0}>
|
||||
<Text dimColor>{" ↑↓ navigate · Tab / ⏎ pick · esc cancel"}</Text>
|
||||
</Box>
|
||||
</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 color={isSelected ? COLOR.primary : COLOR.info} bold={isSelected}>
|
||||
{isSelected ? `${GLYPH.cur} ` : " "}
|
||||
</Text>
|
||||
<Text color={isSelected ? COLOR.user : COLOR.info} bold={isSelected} dimColor={!isSelected}>
|
||||
{value}
|
||||
</Text>
|
||||
</Box>
|
||||
);
|
||||
|
||||
@@ -2,6 +2,7 @@ import { Box, Text } from "ink";
|
||||
// biome-ignore lint/style/useImportType: tsconfig.jsx = "react" needs React in value scope for JSX compilation
|
||||
import React from "react";
|
||||
import type { SlashCommandSpec } from "./slash.js";
|
||||
import { COLOR, GLYPH } from "./theme.js";
|
||||
|
||||
export interface SlashSuggestionsProps {
|
||||
/**
|
||||
@@ -15,11 +16,21 @@ export interface SlashSuggestionsProps {
|
||||
}
|
||||
|
||||
/**
|
||||
* Floating slash-command panel. Rendered below the input box when
|
||||
* the user is typing a `/…` prefix. Navigation state lives in the
|
||||
* parent (App.tsx owns `slashSelected`) so ↑/↓/Tab/Enter stay
|
||||
* consistent with the useInput handler. This component is pure
|
||||
* display: `matches` and `selectedIndex` come in, rows go out.
|
||||
* Slash-command palette. Rendered below the input box while the user
|
||||
* is typing a `/…` prefix. Visual grammar matches the design doc's
|
||||
* picker style:
|
||||
*
|
||||
* / suggestions esc cancel
|
||||
* ▸ /checkpoint [name] snapshot the workspace
|
||||
* /restore <name> roll back files to a checkpoint
|
||||
* /diff cumulative diff vs session start
|
||||
* [↑↓] navigate · [Tab/⏎] pick
|
||||
*
|
||||
* Cmd tokens render in accent violet (one consistent color for "this
|
||||
* is a command"), descriptions in dim info color. The selected row
|
||||
* gets a leading ▸ + bold cmd; non-selected rows get a 2-space pad in
|
||||
* the same column so the cmd column stays aligned. No solid-bg pill —
|
||||
* the bracket-text pattern from the chrome carries through here.
|
||||
*/
|
||||
export function SlashSuggestions({
|
||||
matches,
|
||||
@@ -28,9 +39,13 @@ export function SlashSuggestions({
|
||||
if (matches === null) return null;
|
||||
if (matches.length === 0) {
|
||||
return (
|
||||
<Box paddingX={1}>
|
||||
<Text color="yellow">no slash command matches that prefix</Text>
|
||||
<Text dimColor> — Backspace to edit, or /help for the full list</Text>
|
||||
<Box paddingX={1} marginTop={1}>
|
||||
<Text color={COLOR.warn} bold>
|
||||
{GLYPH.warn}
|
||||
</Text>
|
||||
<Text> </Text>
|
||||
<Text color={COLOR.warn}>no slash command matches that prefix</Text>
|
||||
<Text dimColor>{" — Backspace to edit, or /help for the full list"}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -45,40 +60,40 @@ export function SlashSuggestions({
|
||||
const hiddenAbove = windowStart;
|
||||
const hiddenBelow = total - windowStart - shown.length;
|
||||
return (
|
||||
<Box flexDirection="column" paddingX={1}>
|
||||
{hiddenAbove > 0 ? <Text dimColor> ↑ {hiddenAbove} more above</Text> : null}
|
||||
<Box flexDirection="column" paddingX={1} marginTop={1}>
|
||||
<Box>
|
||||
<Text color={COLOR.accent} bold>
|
||||
{"/ "}
|
||||
</Text>
|
||||
<Text dimColor>{`${total} command${total === 1 ? "" : "s"}`}</Text>
|
||||
{hiddenAbove > 0 ? <Text dimColor>{` ↑ ${hiddenAbove} above`}</Text> : null}
|
||||
</Box>
|
||||
{shown.map((spec, i) => (
|
||||
<SuggestionRow key={spec.cmd} spec={spec} isSelected={windowStart + i === selectedIndex} />
|
||||
))}
|
||||
{hiddenBelow > 0 ? <Text dimColor> ↓ {hiddenBelow} more below</Text> : null}
|
||||
<Text dimColor> [↑↓] navigate · [Tab]/[Enter] pick</Text>
|
||||
{hiddenBelow > 0 ? <Text dimColor>{` ↓ ${hiddenBelow} below`}</Text> : null}
|
||||
<Box marginTop={0}>
|
||||
<Text dimColor>{" ↑↓ navigate · Tab / ⏎ pick · esc cancel"}</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
function SuggestionRow({ spec, isSelected }: { spec: SlashCommandSpec; isSelected: boolean }) {
|
||||
const marker = isSelected ? "▸" : " ";
|
||||
const name = `/${spec.cmd}`;
|
||||
const argsSuffix = spec.argsHint ? ` ${spec.argsHint}` : "";
|
||||
// Selected row gets full cyan coloring so it pops out against the
|
||||
// dimmed others — mirrors the style GitHub Issues / Discord use
|
||||
// for focused dropdown rows.
|
||||
if (isSelected) {
|
||||
return (
|
||||
<Box>
|
||||
<Text bold color="cyan">
|
||||
{marker} {name.padEnd(12)}
|
||||
{argsSuffix.padEnd(16)}
|
||||
</Text>
|
||||
<Text color="cyan"> {spec.summary}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
const argsSuffix = spec.argsHint ? spec.argsHint : "";
|
||||
return (
|
||||
<Box>
|
||||
<Text dimColor>
|
||||
{marker} {name.padEnd(12)}
|
||||
{argsSuffix.padEnd(16)} {spec.summary}
|
||||
<Text color={isSelected ? COLOR.primary : COLOR.info} bold={isSelected}>
|
||||
{isSelected ? `${GLYPH.cur} ` : " "}
|
||||
</Text>
|
||||
<Text color={COLOR.accent} bold={isSelected}>
|
||||
{name.padEnd(14)}
|
||||
</Text>
|
||||
<Text dimColor>{argsSuffix.padEnd(14)}</Text>
|
||||
<Text>{" "}</Text>
|
||||
<Text color={isSelected ? COLOR.user : COLOR.info} dimColor={!isSelected}>
|
||||
{spec.summary}
|
||||
</Text>
|
||||
</Box>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
/**
|
||||
* Side-by-side diff renderer — git-difftool / delta-style "old | new"
|
||||
* layout. Each row shows the same logical position on both sides;
|
||||
* removed lines have content on the left only with a red wash, added
|
||||
* lines on the right with a green wash, common context appears on
|
||||
* both sides dim.
|
||||
*
|
||||
* Layout:
|
||||
*
|
||||
* 40 function loginUser(...) │ 40 function loginUser(...)
|
||||
* 41 - if (!email) throw new Error… │ 41 + if (!email || typeof email…
|
||||
* │ 42 + throw new TypeError(…)
|
||||
* │ 43 + }
|
||||
* 42 return verify(email, …) │ 44 return verify(email, …)
|
||||
*
|
||||
* Width is derived from the terminal — half each side minus a 3-cell
|
||||
* separator (` │ `). Long lines truncate with `…` rather than wrap,
|
||||
* so the row count stays predictable for the parent's height budget.
|
||||
*/
|
||||
|
||||
import { Box, Text, useStdout } from "ink";
|
||||
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React in value scope for React.Fragment
|
||||
import React from "react";
|
||||
import type { SplitDiffRow } from "../../code/diff-preview.js";
|
||||
import { COLOR } from "./theme.js";
|
||||
|
||||
export interface SplitDiffProps {
|
||||
rows: readonly SplitDiffRow[];
|
||||
/**
|
||||
* Total columns budget. Defaults to terminal width. Modal callers
|
||||
* pass a smaller number so the diff fits inside the modal frame.
|
||||
*/
|
||||
totalCols?: number;
|
||||
}
|
||||
|
||||
export function SplitDiff({ rows, totalCols }: SplitDiffProps): React.ReactElement {
|
||||
const { stdout } = useStdout();
|
||||
const cols = totalCols ?? stdout?.columns ?? 80;
|
||||
// Reserve ~6 cells for outer border + padding on the modal/log side,
|
||||
// 3 cells for the ` │ ` separator. Half the rest per column.
|
||||
const innerCols = Math.max(40, cols - 6);
|
||||
const halfCols = Math.floor((innerCols - 3) / 2);
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
{rows.map((row, i) => (
|
||||
<Box key={`r-${i}-${row.left.num ?? "p"}-${row.right.num ?? "p"}`}>
|
||||
<Cell side={row.left} width={halfCols} which="left" />
|
||||
<Text color={COLOR.info} dimColor>
|
||||
{" │ "}
|
||||
</Text>
|
||||
<Cell side={row.right} width={halfCols} which="right" />
|
||||
</Box>
|
||||
))}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
function Cell({
|
||||
side,
|
||||
width,
|
||||
which,
|
||||
}: {
|
||||
side: SplitDiffRow["left"] | SplitDiffRow["right"];
|
||||
width: number;
|
||||
which: "left" | "right";
|
||||
}) {
|
||||
const numPad = 4; // up to 9999 lines
|
||||
const sgnPad = 1; // single-char sign
|
||||
const inner = Math.max(8, width - numPad - sgnPad - 2 /* spaces */);
|
||||
|
||||
const numStr = side.num !== null ? String(side.num).padStart(numPad) : " ".repeat(numPad);
|
||||
const sign =
|
||||
side.kind === "del" ? "-" : side.kind === "add" ? "+" : side.kind === "pad" ? " " : " ";
|
||||
const raw = side.text;
|
||||
const truncated = raw.length > inner ? `${raw.slice(0, inner - 1)}…` : raw;
|
||||
// Pad to fixed width so the bg color stretches across the whole
|
||||
// column even when the text is short — without this the red/green
|
||||
// wash would only cover the actual chars and the rest of the row
|
||||
// would be terminal default, which looks broken.
|
||||
const padded = truncated.padEnd(inner);
|
||||
|
||||
if (side.kind === "del") {
|
||||
return (
|
||||
<Text color="#fbc8c8" backgroundColor="#2a1212">
|
||||
{`${numStr} ${sign} ${padded}`}
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
if (side.kind === "add") {
|
||||
return (
|
||||
<Text color="#bef0c8" backgroundColor="#0c2718">
|
||||
{`${numStr} ${sign} ${padded}`}
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
if (side.kind === "pad") {
|
||||
// Empty side — mute everything, no bg, no glyph. The "… more
|
||||
// lines" capRows marker also rides this kind on the left side
|
||||
// when present, so we render its text dim italic.
|
||||
return (
|
||||
<Text color={COLOR.info} dimColor italic={!!raw}>
|
||||
{`${numStr} ${sign} ${padded}`}
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
// ctx: same content both sides, dim
|
||||
return <Text dimColor>{`${numStr} ${sign} ${padded}`}</Text>;
|
||||
}
|
||||
+210
-388
@@ -1,432 +1,254 @@
|
||||
import { basename } from "node:path";
|
||||
import { Box, Text, useStdout } from "ink";
|
||||
import React from "react";
|
||||
import { DEEPSEEK_CONTEXT_TOKENS, DEFAULT_CONTEXT_TOKENS } from "../../telemetry.js";
|
||||
import type { SessionSummary } from "../../telemetry.js";
|
||||
import { VERSION } from "../../version.js";
|
||||
import { useTick } from "./ticker.js";
|
||||
import stringWidth from "string-width";
|
||||
import type { EditMode } from "../../config.js";
|
||||
import type { SessionSummary } from "../../telemetry/stats.js";
|
||||
import { Bar, ChromeRule } from "./primitives.js";
|
||||
import { COLOR, GRADIENT } from "./theme.js";
|
||||
|
||||
/**
|
||||
* Cyan → blue → purple truecolor gradient for the REASONIX wordmark.
|
||||
* Each char gets its own hex color — terminals that support 24-bit
|
||||
* color (nearly all since 2016) render this as a smooth fade. Older
|
||||
* 256-color terminals snap to nearest; 8-color fall all the way back
|
||||
* to plain cyan via Ink's color pipeline, so the worst case is still
|
||||
* legible.
|
||||
*/
|
||||
const WORDMARK_STYLES: ReadonlyArray<{ ch: string; color: string; isLogo: boolean }> = [
|
||||
{ ch: "◈", color: "#5eead4", isLogo: true }, // teal — brand mark
|
||||
{ ch: " ", color: "#5eead4", isLogo: false },
|
||||
{ ch: "R", color: "#67e8f9", isLogo: false }, // cyan
|
||||
{ ch: "E", color: "#7dd3fc", isLogo: false }, // sky
|
||||
{ ch: "A", color: "#93c5fd", isLogo: false }, // blue
|
||||
{ ch: "S", color: "#a5b4fc", isLogo: false }, // indigo
|
||||
{ ch: "O", color: "#c4b5fd", isLogo: false }, // violet
|
||||
{ ch: "N", color: "#d8b4fe", isLogo: false }, // purple
|
||||
{ ch: "I", color: "#f0abfc", isLogo: false }, // fuchsia
|
||||
{ ch: "X", color: "#f0abfc", isLogo: false }, // fuchsia
|
||||
];
|
||||
|
||||
/**
|
||||
* Gradient-filled, animated app wordmark. The `◈` brand mark breathes
|
||||
* (bold on/off) once every ~1.6s when idle, ~600ms when the model is
|
||||
* working, so a glance at the top of the screen tells you immediately
|
||||
* whether the app is doing something. Letters' keys use the char+color
|
||||
* pair (not an index) so React state attaches to the glyph itself;
|
||||
* fine because WORDMARK_STYLES never reorders.
|
||||
*/
|
||||
function Wordmark({ busy }: { busy: boolean }) {
|
||||
const tick = useTick();
|
||||
// Slow pulse = 12 ticks (~1.4s). Busy pulse = 5 ticks (~600ms).
|
||||
const period = busy ? 5 : 12;
|
||||
const bright = Math.floor(tick / period) % 2 === 0;
|
||||
return (
|
||||
<Text>
|
||||
{WORDMARK_STYLES.map((c) => (
|
||||
<Text key={`${c.ch}-${c.color}`} color={c.color} bold={c.isLogo ? bright : true}>
|
||||
{c.ch}
|
||||
</Text>
|
||||
))}
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
const COLD_START_TURNS = 3;
|
||||
|
||||
export interface StatsPanelProps {
|
||||
summary: SessionSummary;
|
||||
model: string;
|
||||
prefixHash: string;
|
||||
harvestOn?: boolean;
|
||||
branchBudget?: number;
|
||||
/**
|
||||
* True when `reasonix code` is currently running in read-only Plan
|
||||
* Mode. Surfaced as a red "PLAN" tag in the panel header so the user
|
||||
* can tell at a glance that edits are gated behind submit_plan +
|
||||
* approval.
|
||||
*/
|
||||
planMode?: boolean;
|
||||
/**
|
||||
* Account balance fetched once at launch (and optionally refreshed
|
||||
* per-turn by the TUI). `null` or absent hides the balance cell
|
||||
* entirely — /user/balance failed or the user ran with `--no-config`.
|
||||
* The top-up warning fires below 1.0 unit of whatever currency
|
||||
* the endpoint reports so a Chinese user with CNY and a U.S. user
|
||||
* with USD both see "getting low."
|
||||
*/
|
||||
editMode?: EditMode;
|
||||
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;
|
||||
proArmed?: boolean;
|
||||
escalated?: boolean;
|
||||
budgetUsd?: number | null;
|
||||
rootDir?: string;
|
||||
sessionName?: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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,
|
||||
planMode,
|
||||
editMode,
|
||||
balance,
|
||||
updateAvailable,
|
||||
busy,
|
||||
proArmed,
|
||||
escalated,
|
||||
budgetUsd,
|
||||
rootDir,
|
||||
sessionName,
|
||||
}: StatsPanelProps) {
|
||||
const branchOn = (branchBudget ?? 1) > 1;
|
||||
const ctxMax = DEEPSEEK_CONTEXT_TOKENS[model] ?? DEFAULT_CONTEXT_TOKENS;
|
||||
const ctxRatio = summary.lastPromptTokens / ctxMax;
|
||||
const { stdout } = useStdout();
|
||||
const columns = stdout?.columns ?? 80;
|
||||
const narrow = columns < NARROW_BREAKPOINT;
|
||||
|
||||
// Cold-start: first few turns render cache+cost muted so a 0.0% hit
|
||||
// rate on turn 1 doesn't look like an error. Once the cache has
|
||||
// actually had a chance to build, we flip to the live gradient.
|
||||
const coldStart = summary.turns <= COLD_START_TURNS;
|
||||
|
||||
return (
|
||||
<Box borderStyle="round" borderColor="cyan" flexDirection="column" paddingX={1}>
|
||||
<Header
|
||||
model={model}
|
||||
prefixHash={prefixHash}
|
||||
harvestOn={harvestOn}
|
||||
branchOn={branchOn}
|
||||
branchBudget={branchBudget ?? 1}
|
||||
<Box flexDirection="column" paddingX={1}>
|
||||
<ChromeRow
|
||||
editMode={editMode}
|
||||
planMode={planMode}
|
||||
turns={summary.turns}
|
||||
proArmed={proArmed ?? false}
|
||||
escalated={escalated ?? false}
|
||||
summary={summary}
|
||||
coldStart={coldStart}
|
||||
rootDir={rootDir}
|
||||
sessionName={sessionName ?? null}
|
||||
updateAvailable={updateAvailable}
|
||||
narrow={narrow}
|
||||
busy={busy ?? false}
|
||||
balance={balance ?? null}
|
||||
/>
|
||||
{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,
|
||||
planMode,
|
||||
turns,
|
||||
updateAvailable,
|
||||
narrow,
|
||||
busy,
|
||||
}: {
|
||||
model: string;
|
||||
prefixHash: string;
|
||||
harvestOn?: boolean;
|
||||
branchOn: boolean;
|
||||
branchBudget: number;
|
||||
planMode?: boolean;
|
||||
turns: number;
|
||||
updateAvailable?: string | null;
|
||||
narrow: boolean;
|
||||
busy: boolean;
|
||||
}) {
|
||||
return (
|
||||
<Box justifyContent="space-between">
|
||||
<Box>
|
||||
<Wordmark busy={busy} />
|
||||
<Text dimColor>{` v${VERSION}`}</Text>
|
||||
<Text dimColor> · </Text>
|
||||
<Text color="yellow">{model}</Text>
|
||||
{narrow ? null : (
|
||||
<>
|
||||
<Text dimColor> · </Text>
|
||||
<Text dimColor>{prefixHash}</Text>
|
||||
</>
|
||||
)}
|
||||
{harvestOn ? <Text color="magenta"> · harvest</Text> : null}
|
||||
{branchOn ? <Text color="blue"> · branch{branchBudget}</Text> : null}
|
||||
{planMode ? (
|
||||
<Text color="red" bold>
|
||||
{" · PLAN"}
|
||||
</Text>
|
||||
) : null}
|
||||
</Box>
|
||||
<Text>
|
||||
{updateAvailable ? (
|
||||
<Text color="yellow" bold>{`update: ${updateAvailable} · `}</Text>
|
||||
) : null}
|
||||
<Text dimColor>{narrow ? `turn ${turns}` : `turn ${turns} · /help`}</Text>
|
||||
</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Wide-terminal layout (≥120 cols): single metrics row. Matches the
|
||||
* original panel, just with calmer spacing and the cold-start
|
||||
* treatment folded in.
|
||||
*/
|
||||
function InlineMetrics({
|
||||
summary,
|
||||
ctxRatio,
|
||||
ctxMax,
|
||||
balance,
|
||||
coldStart,
|
||||
}: {
|
||||
summary: SessionSummary;
|
||||
ctxRatio: number;
|
||||
ctxMax: number;
|
||||
balance?: { currency: string; total: number } | null;
|
||||
coldStart: boolean;
|
||||
}) {
|
||||
return (
|
||||
<Box marginTop={1} gap={3}>
|
||||
<ContextCell ratio={ctxRatio} promptTokens={summary.lastPromptTokens} ctxMax={ctxMax} />
|
||||
<CacheCell hitRatio={summary.cacheHitRatio} coldStart={coldStart} turns={summary.turns} />
|
||||
<CostCell summary={summary} coldStart={coldStart} />
|
||||
{balance ? <BalanceCell balance={balance} /> : null}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Narrow-terminal layout (<120 cols): one metric per line, in priority
|
||||
* order (ctx → balance → cache → cost). Order matters because users
|
||||
* scanning a cramped terminal want "am I about to hit a wall?" answered
|
||||
* first; dollars spent comes later.
|
||||
*/
|
||||
function StackedMetrics({
|
||||
summary,
|
||||
ctxRatio,
|
||||
ctxMax,
|
||||
balance,
|
||||
coldStart,
|
||||
}: {
|
||||
summary: SessionSummary;
|
||||
ctxRatio: number;
|
||||
ctxMax: number;
|
||||
balance?: { currency: string; total: number } | null;
|
||||
coldStart: boolean;
|
||||
}) {
|
||||
return (
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
<ContextCell
|
||||
ratio={ctxRatio}
|
||||
promptTokens={summary.lastPromptTokens}
|
||||
ctxMax={ctxMax}
|
||||
showBar
|
||||
/>
|
||||
{balance ? <BalanceCell balance={balance} /> : null}
|
||||
<CacheCell hitRatio={summary.cacheHitRatio} coldStart={coldStart} turns={summary.turns} />
|
||||
<CostCell summary={summary} coldStart={coldStart} />
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
function ContextCell({
|
||||
ratio,
|
||||
promptTokens,
|
||||
ctxMax,
|
||||
showBar,
|
||||
}: {
|
||||
ratio: number;
|
||||
promptTokens: number;
|
||||
ctxMax: number;
|
||||
showBar?: boolean;
|
||||
}) {
|
||||
if (promptTokens === 0) {
|
||||
return (
|
||||
<Text>
|
||||
<Text dimColor>ctx </Text>
|
||||
<Text dimColor>— (no turns yet)</Text>
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
const color = ratio >= 0.8 ? "red" : ratio >= 0.6 ? "yellow" : "green";
|
||||
const pct = Math.round(ratio * 100);
|
||||
return (
|
||||
<Text>
|
||||
<Text dimColor>ctx </Text>
|
||||
{showBar ? <Bar ratio={ratio} color={color} /> : null}
|
||||
{showBar ? <Text> </Text> : null}
|
||||
<Text color={color} bold>
|
||||
{formatTokens(promptTokens)}/{formatTokens(ctxMax)}
|
||||
</Text>
|
||||
<Text dimColor> ({pct}%)</Text>
|
||||
{ratio >= 0.8 ? (
|
||||
<Text color="red" bold>
|
||||
{" · /compact"}
|
||||
</Text>
|
||||
<ChromeRule />
|
||||
{budgetUsd !== null && budgetUsd !== undefined ? (
|
||||
<BudgetRow spent={summary.totalCostUsd} cap={budgetUsd} />
|
||||
) : null}
|
||||
</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
function CacheCell({
|
||||
hitRatio,
|
||||
coldStart,
|
||||
turns,
|
||||
}: {
|
||||
hitRatio: number;
|
||||
coldStart: boolean;
|
||||
turns: number;
|
||||
}) {
|
||||
const pct = (hitRatio * 100).toFixed(1);
|
||||
if (turns === 0) {
|
||||
return (
|
||||
<Text>
|
||||
<Text dimColor>cache </Text>
|
||||
<Text dimColor>—</Text>
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
if (coldStart) {
|
||||
return (
|
||||
<Text>
|
||||
<Text dimColor>cache </Text>
|
||||
<Text dimColor>{pct}% </Text>
|
||||
<Text dimColor italic>
|
||||
(cold start)
|
||||
</Text>
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
const color = hitRatio >= 0.7 ? "green" : hitRatio >= 0.4 ? "yellow" : "red";
|
||||
return (
|
||||
<Text>
|
||||
<Text dimColor>cache </Text>
|
||||
<Text color={color} bold>
|
||||
{pct}%
|
||||
</Text>
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
|
||||
function CostCell({
|
||||
function ChromeRow({
|
||||
editMode,
|
||||
planMode,
|
||||
proArmed,
|
||||
escalated,
|
||||
summary,
|
||||
coldStart,
|
||||
rootDir,
|
||||
sessionName,
|
||||
updateAvailable,
|
||||
balance,
|
||||
}: {
|
||||
editMode?: EditMode;
|
||||
planMode?: boolean;
|
||||
proArmed: boolean;
|
||||
escalated: boolean;
|
||||
summary: SessionSummary;
|
||||
coldStart: boolean;
|
||||
rootDir?: string;
|
||||
sessionName?: string | null;
|
||||
updateAvailable?: string | null;
|
||||
balance?: { currency: string; total: number } | null;
|
||||
}) {
|
||||
if (summary.turns === 0) {
|
||||
return (
|
||||
<Text>
|
||||
<Text dimColor>cost </Text>
|
||||
<Text dimColor>—</Text>
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
// The first turn is unavoidably a cache-miss (nothing to hit),
|
||||
// so the dollar figure is front-loaded. Muting it during the
|
||||
// cold-start window keeps the "expensive first turn" from
|
||||
// reading as "something is wrong."
|
||||
const primaryColor = coldStart ? undefined : "green";
|
||||
const modePill = pickModePill(planMode, editMode);
|
||||
const proPill = escalated
|
||||
? { label: "⇧ pro", color: COLOR.err }
|
||||
: proArmed
|
||||
? { label: "⇧ pro", color: COLOR.warn }
|
||||
: null;
|
||||
const projectName = rootDir ? basename(rootDir) : null;
|
||||
const cachePct = Math.round(summary.cacheHitRatio * 100);
|
||||
const cacheColor =
|
||||
summary.cacheHitRatio >= 0.7 ? COLOR.ok : summary.cacheHitRatio >= 0.4 ? COLOR.warn : COLOR.err;
|
||||
const balanceLabel = balance
|
||||
? `[w ${balance.currency === "USD" ? "$" : ""}${balance.total.toFixed(2)}${balance.currency !== "USD" ? ` ${balance.currency}` : ""}]`
|
||||
: "";
|
||||
const costLabel = `[$${summary.totalCostUsd.toFixed(4)}]`;
|
||||
const cacheLabel = "[c ▰▰▰▰▰▰ 100%]";
|
||||
const updateLabel = updateAvailable ? `↑ ${updateAvailable}` : "";
|
||||
|
||||
// Greedy width-aware fit. Layout (every gap = 2 cells, applied as suffix
|
||||
// to update/mode/pro and as prefix to balance/cache):
|
||||
// [brand][·project][›session]<spacer>[update][mode][pro][cost][balance][cache]
|
||||
// Always shown: brand, project (if rootDir), mode (if set), pro (if armed),
|
||||
// cost. These carve fixedLeft / fixedRight first.
|
||||
// Optional, dropped greedy by priority: balance > cache > session > update.
|
||||
// The flexbox spacer can shrink to 0, so no minimum reserve.
|
||||
const { stdout } = useStdout();
|
||||
const cols = (stdout?.columns ?? 80) - 2; // subtract paddingX={1} on both sides
|
||||
const SEP_DOT = stringWidth(" · ");
|
||||
const SEP_ARROW = stringWidth(" › ");
|
||||
const GAP = 2;
|
||||
|
||||
const fixedLeft =
|
||||
stringWidth("◈ reasonix") + (projectName ? SEP_DOT + stringWidth(projectName) : 0);
|
||||
const modeW = modePill ? GAP + stringWidth(`[${modePill.label}]`) : 0;
|
||||
const proW = proPill ? GAP + stringWidth(`[${proPill.label}]`) : 0;
|
||||
const fixedRight = modeW + proW + stringWidth(costLabel);
|
||||
let budget = cols - fixedLeft - fixedRight;
|
||||
|
||||
const balW = balance ? GAP + stringWidth(balanceLabel) : 0;
|
||||
const cacheW = GAP + stringWidth(cacheLabel);
|
||||
const sessionW = sessionName ? SEP_ARROW + stringWidth(sessionName) : 0;
|
||||
const updateW = updateLabel ? GAP + stringWidth(updateLabel) : 0;
|
||||
|
||||
const showBalance = balW > 0 && budget >= balW;
|
||||
if (showBalance) budget -= balW;
|
||||
const showCache = budget >= cacheW;
|
||||
if (showCache) budget -= cacheW;
|
||||
const showSession = sessionW > 0 && budget >= sessionW;
|
||||
if (showSession) budget -= sessionW;
|
||||
const showUpdate = updateW > 0 && budget >= updateW;
|
||||
if (showUpdate) budget -= updateW;
|
||||
|
||||
return (
|
||||
<Text>
|
||||
<Text dimColor>cost </Text>
|
||||
<Text color={primaryColor} bold={!coldStart} dimColor={coldStart}>
|
||||
${summary.totalCostUsd.toFixed(6)}
|
||||
<Box>
|
||||
<Text bold color={GRADIENT[0]}>
|
||||
{"◈ "}
|
||||
</Text>
|
||||
<Text dimColor>
|
||||
{" (in "}${summary.totalInputCostUsd.toFixed(6)}
|
||||
{" · out "}${summary.totalOutputCostUsd.toFixed(6)}
|
||||
{")"}
|
||||
<Text color={COLOR.brand} bold>
|
||||
reasonix
|
||||
</Text>
|
||||
</Text>
|
||||
{projectName ? (
|
||||
<>
|
||||
<Text color={COLOR.info} dimColor>
|
||||
{" · "}
|
||||
</Text>
|
||||
<Text>{projectName}</Text>
|
||||
{showSession && sessionName ? (
|
||||
<>
|
||||
<Text color={COLOR.info} dimColor>
|
||||
{" › "}
|
||||
</Text>
|
||||
<Text color={COLOR.info}>{sessionName}</Text>
|
||||
</>
|
||||
) : null}
|
||||
</>
|
||||
) : null}
|
||||
|
||||
<Box flexGrow={1} />
|
||||
|
||||
{showUpdate ? (
|
||||
<>
|
||||
<Text color={COLOR.warn} bold>
|
||||
{updateLabel}
|
||||
</Text>
|
||||
<Text>{" "}</Text>
|
||||
</>
|
||||
) : null}
|
||||
{modePill ? (
|
||||
<>
|
||||
<Text color={modePill.color} bold>
|
||||
{`[${modePill.label}]`}
|
||||
</Text>
|
||||
<Text>{" "}</Text>
|
||||
</>
|
||||
) : null}
|
||||
{proPill ? (
|
||||
<>
|
||||
<Text color={proPill.color} bold>
|
||||
{`[${proPill.label}]`}
|
||||
</Text>
|
||||
<Text>{" "}</Text>
|
||||
</>
|
||||
) : null}
|
||||
<Text
|
||||
color={
|
||||
summary.turns === 0 || coldStart ? COLOR.info : sessionCostColor(summary.totalCostUsd)
|
||||
}
|
||||
bold={summary.turns > 0 && !coldStart}
|
||||
dimColor={summary.turns === 0 || coldStart}
|
||||
>
|
||||
{costLabel}
|
||||
</Text>
|
||||
{showBalance && balance ? (
|
||||
<>
|
||||
<Text>{" "}</Text>
|
||||
<Text color={balance.total < 1 ? COLOR.err : balance.total < 5 ? COLOR.warn : COLOR.ok}>
|
||||
{balanceLabel}
|
||||
</Text>
|
||||
</>
|
||||
) : null}
|
||||
{showCache ? (
|
||||
<>
|
||||
<Text>{" "}</Text>
|
||||
<Text dimColor>{"["}</Text>
|
||||
<Text dimColor>{"c "}</Text>
|
||||
<Bar
|
||||
ratio={summary.cacheHitRatio}
|
||||
color={coldStart ? COLOR.info : cacheColor}
|
||||
cells={6}
|
||||
dim={coldStart}
|
||||
/>
|
||||
<Text> </Text>
|
||||
<Text color={coldStart ? undefined : cacheColor} dimColor={coldStart}>
|
||||
{coldStart && summary.turns === 0 ? "—" : `${cachePct}%`}
|
||||
</Text>
|
||||
<Text dimColor>{"]"}</Text>
|
||||
</>
|
||||
) : null}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
function BalanceCell({ balance }: { balance: { currency: string; total: number } }) {
|
||||
const color = balance.total < 1 ? "red" : balance.total < 5 ? "yellow" : "green";
|
||||
function pickModePill(
|
||||
planMode: boolean | undefined,
|
||||
editMode: EditMode | undefined,
|
||||
): { label: string; color: string } | null {
|
||||
if (planMode) return { label: "PLAN", color: COLOR.err };
|
||||
if (editMode === "yolo") return { label: "yolo", color: COLOR.err };
|
||||
if (editMode === "auto") return { label: "auto", color: COLOR.primary };
|
||||
if (editMode === "review") return { label: "review", color: COLOR.info };
|
||||
return null;
|
||||
}
|
||||
|
||||
function BudgetRow({ spent, cap }: { spent: number; cap: number }) {
|
||||
const pct = Math.max(0, (spent / cap) * 100);
|
||||
const color = pct >= 100 ? "#f87171" : pct >= 80 ? "#fbbf24" : "#94a3b8";
|
||||
return (
|
||||
<Text>
|
||||
<Text dimColor>balance </Text>
|
||||
<Text color={color} bold>
|
||||
{balance.currency === "USD" ? "$" : ""}
|
||||
{balance.total.toFixed(2)}
|
||||
{balance.currency !== "USD" ? ` ${balance.currency}` : ""}
|
||||
<Box>
|
||||
<Text dimColor>{" budget "}</Text>
|
||||
<Text color={color}>
|
||||
{`$${spent.toFixed(4)} / $${cap.toFixed(2)}`}
|
||||
<Text dimColor>{` (${pct.toFixed(0)}%)`}</Text>
|
||||
</Text>
|
||||
</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Unicode progress bar for the narrow layout's context cell. 10 cells
|
||||
* wide — narrow terminals are already cramped, and the bar is just a
|
||||
* visual cue for the percentage next to it, not the primary readout.
|
||||
*/
|
||||
function Bar({ ratio, color }: { ratio: number; color: "green" | "yellow" | "red" }) {
|
||||
const cells = 10;
|
||||
const filled = Math.max(0, Math.min(cells, Math.round(ratio * cells)));
|
||||
const bar = "█".repeat(filled) + "░".repeat(cells - filled);
|
||||
return <Text color={color}>{bar}</Text>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compact token formatter using binary K (÷1024): 1234 → "1.2K",
|
||||
* 131072 → "128K". Matches DeepSeek's marketing label of "128K context
|
||||
* length" — showing "131k" confused users (the actual limit is
|
||||
* 128×1024 = 131,072 tokens, but the doc consistently says "128K").
|
||||
* Uppercase K signals binary-K to anyone who notices.
|
||||
*/
|
||||
function formatTokens(n: number): string {
|
||||
if (n < 1024) return String(n);
|
||||
const k = n / 1024;
|
||||
return k >= 100 ? `${k.toFixed(0)}K` : `${k.toFixed(1)}K`;
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
/**
|
||||
* Welcome card on the empty session. The FIRST thing every user sees
|
||||
* after launching `reasonix code` — must communicate brand identity,
|
||||
* what to type next, and how to escape, all in the ~5 seconds before
|
||||
* the user starts typing.
|
||||
*
|
||||
* Layout (matches design/tui-redesign-ink.html welcome state):
|
||||
*
|
||||
* ◈ R E A S O N I X
|
||||
*
|
||||
* DeepSeek-native coding agent · cache-first · flash-first
|
||||
*
|
||||
* /skill invoke a stored playbook by name
|
||||
* @file inline a file's contents in your message
|
||||
* /checkpoint snapshot the workspace before a risky turn
|
||||
* /help every slash command + keyboard shortcut
|
||||
*
|
||||
* tip · ctrl+j newline · trailing \ continues
|
||||
*
|
||||
* Why the redesign: the previous version was a left-aligned hint list
|
||||
* with a tiny `◈ welcome` row — functional but invisible as brand. The
|
||||
* gradient wordmark is the one chance per launch to plant identity, so
|
||||
* we make it large + centered + colored across all 8 brand-gradient
|
||||
* stops. The tagline below answers "what is this?" in one line. Cards
|
||||
* answer "what do I type?" — the only three things a new user actually
|
||||
* needs to know in the first 5 seconds.
|
||||
*
|
||||
* Why no animation: an animated gradient pan was tried, but Ink's
|
||||
* eraseLines miscounts on resize when wide rows reflow, leaving
|
||||
* stale frames stacked. Static gradient renders identically and
|
||||
* costs zero ticker subscriptions.
|
||||
*/
|
||||
|
||||
import { Box, Text, useStdout } from "ink";
|
||||
import React from "react";
|
||||
import { COLOR, GRADIENT } from "./theme.js";
|
||||
|
||||
export interface WelcomeBannerProps {
|
||||
/** True when running `reasonix code`. Surfaces code-mode hints. */
|
||||
inCodeMode?: boolean;
|
||||
/**
|
||||
* Live URL of the embedded dashboard, or null when it isn't running.
|
||||
* Surfacing this in the welcome card is how users discover the web UI
|
||||
* — the chrome pill version was unreliable across terminals, so the
|
||||
* card became the canonical pointer.
|
||||
*/
|
||||
dashboardUrl?: string | null;
|
||||
}
|
||||
|
||||
const WORDMARK = "REASONIX";
|
||||
const TAGLINE_CHAT = "DeepSeek-native agent · cache-first · flash-first";
|
||||
const TAGLINE_CODE = "DeepSeek-native coding agent · cache-first · flash-first";
|
||||
|
||||
interface QuickCard {
|
||||
cmd: string;
|
||||
desc: string;
|
||||
}
|
||||
|
||||
const CARDS_CHAT: QuickCard[] = [
|
||||
{ cmd: "/help", desc: "every slash command + keyboard shortcut" },
|
||||
{ cmd: "/skill", desc: "invoke a stored playbook by name" },
|
||||
{ cmd: "/dashboard", desc: "open the embedded web UI (chat · stats · settings)" },
|
||||
{ cmd: "/preset pro", desc: "switch to v4-pro for hard reasoning tasks" },
|
||||
{ cmd: "/exit", desc: "quit the TUI (Ctrl+C twice also works)" },
|
||||
];
|
||||
|
||||
const CARDS_CODE: QuickCard[] = [
|
||||
{ cmd: "@file", desc: "inline a file's contents in your message" },
|
||||
{ cmd: "!cmd", desc: "run shell — output is captured for context" },
|
||||
{ cmd: "/checkpoint", desc: "snapshot the workspace before a risky turn" },
|
||||
{ cmd: "/dashboard", desc: "open the embedded web UI (chat · files · stats · settings)" },
|
||||
{ cmd: "/help", desc: "every slash command + keyboard shortcut" },
|
||||
];
|
||||
|
||||
export function WelcomeBanner({
|
||||
inCodeMode,
|
||||
dashboardUrl,
|
||||
}: WelcomeBannerProps): React.ReactElement {
|
||||
const { stdout } = useStdout();
|
||||
const cols = stdout?.columns ?? 80;
|
||||
// Wordmark width: each letter + space between letters. With letter-
|
||||
// spacing of 1 cell, "R E A S O N I X" is 8*2-1 = 15 cells, plus the
|
||||
// brand mark "◈ " = 2 cells, total 17 cells. We center on the term
|
||||
// width, capped to a sane minimum so very narrow terminals don't
|
||||
// produce negative pad.
|
||||
const wordmarkText = `◈ ${WORDMARK.split("").join(" ")}`;
|
||||
const wordmarkWidth = wordmarkText.length;
|
||||
const tagline = inCodeMode ? TAGLINE_CODE : TAGLINE_CHAT;
|
||||
const cards = inCodeMode ? CARDS_CODE : CARDS_CHAT;
|
||||
|
||||
// Center column 1: pad-left to put wordmark at terminal center
|
||||
const wordmarkPad = Math.max(0, Math.floor((cols - wordmarkWidth) / 2));
|
||||
const taglinePad = Math.max(0, Math.floor((cols - tagline.length) / 2));
|
||||
// Cards left-margin: align to a comfortable indent rather than
|
||||
// center each row (keeps the cmd column aligned).
|
||||
const cardsIndent = Math.max(2, Math.floor((cols - 60) / 2));
|
||||
const tipText = "tip · ctrl+j newline · trailing \\ also continues";
|
||||
const tipPad = Math.max(0, Math.floor((cols - tipText.length) / 2));
|
||||
|
||||
return (
|
||||
<Box flexDirection="column" marginY={1}>
|
||||
{/* Wordmark — gradient across the 8 letters of REASONIX. The
|
||||
brand mark `◈` sits in the brand teal as the first stop, then
|
||||
each letter steps through the gradient. Bold throughout for
|
||||
weight; spacing keeps it from reading as a single dense word. */}
|
||||
<Box>
|
||||
<Text>{" ".repeat(wordmarkPad)}</Text>
|
||||
<Text bold color={GRADIENT[0]}>
|
||||
{"◈ "}
|
||||
</Text>
|
||||
{WORDMARK.split("").map((letter, i) => (
|
||||
// Wordmark is fixed-string ("REASONIX") — letters are unique
|
||||
// and the array never reorders, so per-letter key is stable.
|
||||
<React.Fragment key={letter}>
|
||||
<Text bold color={GRADIENT[i % GRADIENT.length]}>
|
||||
{letter}
|
||||
</Text>
|
||||
{i < WORDMARK.length - 1 ? <Text> </Text> : null}
|
||||
</React.Fragment>
|
||||
))}
|
||||
</Box>
|
||||
|
||||
<Box marginTop={1}>
|
||||
<Text>{" ".repeat(taglinePad)}</Text>
|
||||
<Text color={COLOR.info}>{tagline}</Text>
|
||||
</Box>
|
||||
|
||||
{/* Quick-start cards — cmd token in accent violet, desc dim.
|
||||
Aligned in two columns so the eye can scan command names
|
||||
without having to read each desc. */}
|
||||
<Box flexDirection="column" marginTop={2}>
|
||||
{cards.map((card) => (
|
||||
<Box key={card.cmd}>
|
||||
<Text>{" ".repeat(cardsIndent)}</Text>
|
||||
<Text bold color={COLOR.accent}>
|
||||
{card.cmd.padEnd(14)}
|
||||
</Text>
|
||||
<Text color={COLOR.info}>{card.desc}</Text>
|
||||
</Box>
|
||||
))}
|
||||
</Box>
|
||||
|
||||
{/* Live dashboard URL — printed once, centered, when the embedded
|
||||
server is up. This is the canonical pointer to the web UI; the
|
||||
chrome pill version was unreliable across terminals so we
|
||||
surface the URL here (one-shot at launch) and let the user
|
||||
re-fetch via `/dashboard` whenever the welcome card has
|
||||
scrolled away. */}
|
||||
{dashboardUrl ? (
|
||||
<Box marginTop={2}>
|
||||
<Text>{" ".repeat(Math.max(0, Math.floor((cols - (dashboardUrl.length + 9)) / 2)))}</Text>
|
||||
<Text color={COLOR.brand} bold>
|
||||
{"▸ web · "}
|
||||
</Text>
|
||||
<Text color={COLOR.accent}>{dashboardUrl}</Text>
|
||||
</Box>
|
||||
) : null}
|
||||
|
||||
<Box marginTop={dashboardUrl ? 1 : 2}>
|
||||
<Text>{" ".repeat(tipPad)}</Text>
|
||||
<Text dimColor>{tipText}</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -59,7 +59,7 @@ export function Wizard({ onComplete, onCancel, existingApiKey, initial }: Wizard
|
||||
const [step, setStep] = useState<Step>(existingApiKey ? "preset" : "apiKey");
|
||||
const [data, setData] = useState<WizardData>({
|
||||
apiKey: existingApiKey ?? "",
|
||||
preset: initial?.preset ?? "fast",
|
||||
preset: initial?.preset ?? "auto",
|
||||
selectedCatalog: deriveInitialCatalog(initial?.mcp ?? []),
|
||||
catalogArgs: {},
|
||||
});
|
||||
@@ -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>
|
||||
@@ -386,8 +386,8 @@ function SummaryLine({ label, value }: { label: string; value: string }) {
|
||||
// ---------- data helpers ----------
|
||||
|
||||
function presetItems(): SelectItem<PresetName>[] {
|
||||
return (["fast", "smart", "max"] as PresetName[]).map((name) => ({
|
||||
value: name,
|
||||
return (["auto", "flash", "pro"] as const).map((name) => ({
|
||||
value: name as PresetName,
|
||||
label: `${name} — ${PRESET_DESCRIPTIONS[name].headline}`,
|
||||
hint: PRESET_DESCRIPTIONS[name].cost,
|
||||
}));
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import { Box, Text } from "ink";
|
||||
import React from "react";
|
||||
import { ModalCard } from "./ModalCard.js";
|
||||
import { SingleSelect } from "./Select.js";
|
||||
import { COLOR } from "./theme.js";
|
||||
|
||||
export type WorkspaceConfirmChoice = "switch" | "deny";
|
||||
|
||||
export interface WorkspaceConfirmProps {
|
||||
/** Resolved absolute path the model wants to switch to. */
|
||||
path: string;
|
||||
/** Current session root, shown above the target so the user sees the diff. */
|
||||
currentRoot: string;
|
||||
/** Number of MCP servers still attached — surfaced so the user knows
|
||||
* those won't follow the switch (their child processes were spawned
|
||||
* with the original cwd). 0 means no warning. */
|
||||
mcpServerCount: number;
|
||||
onChoose: (choice: WorkspaceConfirmChoice, denyContext?: string) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Modal-style approval for a `change_workspace` tool call. Two
|
||||
* choices, Enter / Esc bindings. No "always allow" — workspace
|
||||
* switches are per-target by nature. Tab on Deny opens inline
|
||||
* context entry, returned as `onChoose`'s 2nd arg.
|
||||
*/
|
||||
export function WorkspaceConfirm({
|
||||
path,
|
||||
currentRoot,
|
||||
mcpServerCount,
|
||||
onChoose,
|
||||
}: WorkspaceConfirmProps) {
|
||||
const subtitle =
|
||||
mcpServerCount > 0
|
||||
? `MCP servers (${mcpServerCount}) stay anchored to the original launch root.`
|
||||
: "Re-registers filesystem / shell / memory tools at the new path.";
|
||||
|
||||
return (
|
||||
<ModalCard accent={COLOR.warn} icon="⇄" title="switch workspace" subtitle={subtitle}>
|
||||
<Box flexDirection="column" marginBottom={1}>
|
||||
<Box>
|
||||
<Text dimColor>{"from "}</Text>
|
||||
<Text color={COLOR.info}>{currentRoot}</Text>
|
||||
</Box>
|
||||
<Box>
|
||||
<Text dimColor>{"to "}</Text>
|
||||
<Text color={COLOR.primary} bold>
|
||||
{path}
|
||||
</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
<SingleSelect
|
||||
initialValue="switch"
|
||||
items={[
|
||||
{
|
||||
value: "switch",
|
||||
label: "Switch",
|
||||
hint: "Re-register filesystem / shell / memory tools against the new root.",
|
||||
},
|
||||
{
|
||||
value: "deny",
|
||||
label: "Deny",
|
||||
hint: "Tell the model why you're refusing; it will continue without changing directories.",
|
||||
denyWithContext: true,
|
||||
},
|
||||
]}
|
||||
onSubmit={(v, ctx) => onChoose(v as WorkspaceConfirmChoice, ctx)}
|
||||
onCancel={() => onChoose("deny")}
|
||||
footer="[↑↓] navigate · [Enter] select · [Tab] add context · [Esc] deny"
|
||||
/>
|
||||
</ModalCard>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/** Alt-screen lifecycle — restore must be idempotent and run on SIGINT/SIGTERM/exit so the user's main buffer always comes back. */
|
||||
|
||||
import { useEffect } from "react";
|
||||
|
||||
function isInteractiveTty(): boolean {
|
||||
return Boolean(process.stdout?.isTTY);
|
||||
}
|
||||
|
||||
export function useAltScreen(): void {
|
||||
useEffect(() => {
|
||||
if (!isInteractiveTty()) return;
|
||||
// 1002 = button-event tracking (press + drag + release); 1006 = SGR coords.
|
||||
// Shift+drag bypasses tracking for native terminal selection.
|
||||
process.stdout.write("\x1b[?1049h\x1b[2J\x1b[H\x1b[?1002h\x1b[?1006h");
|
||||
|
||||
let restored = false;
|
||||
const restore = () => {
|
||||
if (restored) return;
|
||||
restored = true;
|
||||
try {
|
||||
process.stdout.write("\x1b[?1006l\x1b[?1002l\x1b[?1000l\x1b[?1049l");
|
||||
} catch {
|
||||
/* terminal closed */
|
||||
}
|
||||
};
|
||||
|
||||
process.once("exit", restore);
|
||||
process.once("SIGINT", () => {
|
||||
restore();
|
||||
process.exit(130);
|
||||
});
|
||||
process.once("SIGTERM", () => {
|
||||
restore();
|
||||
process.exit(143);
|
||||
});
|
||||
|
||||
return restore;
|
||||
}, []);
|
||||
}
|
||||
+1
-28
@@ -1,25 +1,5 @@
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
/** User-typed `!cmd` skips the allowlist — that gate is for the MODEL, not the user. */
|
||||
|
||||
/**
|
||||
* 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();
|
||||
@@ -27,13 +7,6 @@ export function detectBangCommand(text: string): string | 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,118 @@
|
||||
/**
|
||||
* Character-cell progress bar — the visual primitive shared across:
|
||||
* · cache hit ratio in the status bar
|
||||
* · undo banner countdown
|
||||
* · /context token-usage breakdown (stacked variant)
|
||||
* · plan step progress
|
||||
* · MCP progress notifications
|
||||
* · walk-through "block N of M" position
|
||||
*
|
||||
* Why one helper: in a TUI you can only convey "fraction" by character
|
||||
* fill, not by gradient bg. Doing it ad-hoc per call site led to five
|
||||
* subtly different bar styles (some used `█/░`, some `■/-`, some
|
||||
* inverted bg). Centralizing here means the visual cue is one
|
||||
* consistent thing the user reads at-a-glance everywhere.
|
||||
*
|
||||
* All variants render in 1 row, 1 cell tall. Width defaults to 24
|
||||
* which is wide enough for "10% increments are visible to the eye"
|
||||
* but narrow enough to fit beside other status info.
|
||||
*/
|
||||
|
||||
import { Box, Text } from "ink";
|
||||
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React in value scope for JSX compilation
|
||||
import React from "react";
|
||||
import { COLOR, GLYPH } from "./theme.js";
|
||||
|
||||
export interface CharBarProps {
|
||||
/** 0–100 (clamped). Negative or NaN → 0; >100 → 100. */
|
||||
pct: number;
|
||||
/** Cell count. Default 24. Min 4 enforced so the bar is at least readable. */
|
||||
width?: number;
|
||||
/** Filled-cell color. Defaults to brand cyan. */
|
||||
color?: string;
|
||||
/** Empty-cell color. Defaults to dim slate. */
|
||||
emptyColor?: string;
|
||||
/**
|
||||
* Whether to render the percentage label after the bar. Off when the
|
||||
* caller wants to put its own meta after (e.g. "12 of 30 done").
|
||||
*/
|
||||
showLabel?: boolean;
|
||||
/** Optional label override (default: "{pct}%"). */
|
||||
label?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Single-color progress bar. Render shape:
|
||||
* `████████████░░░░░░░░░░░░ 50%`
|
||||
*
|
||||
* Filled section is `█` in `color`, empty section is `░` in
|
||||
* `emptyColor`. Label sits in the same row, dim by default.
|
||||
*/
|
||||
export function CharBar({
|
||||
pct,
|
||||
width = 24,
|
||||
color = COLOR.primary,
|
||||
emptyColor,
|
||||
showLabel = true,
|
||||
label,
|
||||
}: CharBarProps): React.ReactElement {
|
||||
const total = Math.max(4, width);
|
||||
const clamped = Math.max(0, Math.min(100, Number.isFinite(pct) ? pct : 0));
|
||||
const filled = Math.round((total * clamped) / 100);
|
||||
return (
|
||||
<Box>
|
||||
<Text color={color}>{GLYPH.block.repeat(filled)}</Text>
|
||||
<Text color={emptyColor ?? COLOR.info} dimColor>
|
||||
{GLYPH.shade1.repeat(total - filled)}
|
||||
</Text>
|
||||
{showLabel ? <Text dimColor>{` ${label ?? `${Math.round(clamped)}%`}`}</Text> : null}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
export interface StackedSegment {
|
||||
/** Percent of the total width this segment occupies. 0–100. */
|
||||
pct: number;
|
||||
color: string;
|
||||
/** Optional label (used by legend renderer; not rendered in the bar). */
|
||||
label?: string;
|
||||
}
|
||||
|
||||
export interface StackedCharBarProps {
|
||||
segments: readonly StackedSegment[];
|
||||
width?: number;
|
||||
/** Color of the trailing "free / unused" cells. */
|
||||
emptyColor?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stacked progress bar. Multiple colored segments + a trailing empty
|
||||
* region. Rendered left-to-right in segment order; if the segments'
|
||||
* pcts sum >100 the trailing empty just becomes 0.
|
||||
*
|
||||
* Used by `/context` to break down system / tools / log / input
|
||||
* occupancy across the prompt budget.
|
||||
*/
|
||||
export function StackedCharBar({
|
||||
segments,
|
||||
width = 32,
|
||||
emptyColor,
|
||||
}: StackedCharBarProps): React.ReactElement {
|
||||
const total = Math.max(4, width);
|
||||
const cells = segments.map((s) => Math.max(0, Math.round((total * s.pct) / 100)));
|
||||
const used = cells.reduce((acc, n) => acc + n, 0);
|
||||
const empty = Math.max(0, total - used);
|
||||
return (
|
||||
<Box>
|
||||
{segments.map((seg, i) => (
|
||||
// biome-ignore lint/suspicious/noArrayIndexKey: ordered, fixed-shape
|
||||
<Text key={`seg-${i}`} color={seg.color}>
|
||||
{GLYPH.block.repeat(cells[i] ?? 0)}
|
||||
</Text>
|
||||
))}
|
||||
<Text color={emptyColor ?? COLOR.info} dimColor>
|
||||
{GLYPH.shade1.repeat(empty)}
|
||||
</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
/** OSC 52 clipboard write + temp-file fallback. */
|
||||
|
||||
import { writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
const OSC_52_LIMIT = 75_000;
|
||||
|
||||
export interface ClipboardWrite {
|
||||
osc52: boolean;
|
||||
filePath: string | null;
|
||||
size: number;
|
||||
}
|
||||
|
||||
export function writeClipboard(text: string): ClipboardWrite {
|
||||
const filePath = join(tmpdir(), `reasonix-clip-${Date.now()}.txt`);
|
||||
let osc52 = false;
|
||||
if (text.length <= OSC_52_LIMIT) {
|
||||
const b64 = Buffer.from(text, "utf8").toString("base64");
|
||||
process.stdout.write(`\x1b]52;c;${b64}\x1b\\`);
|
||||
osc52 = true;
|
||||
}
|
||||
let writtenPath: string | null = null;
|
||||
try {
|
||||
writeFileSync(filePath, text, "utf8");
|
||||
writtenPath = filePath;
|
||||
} catch {
|
||||
/* read-only fs */
|
||||
}
|
||||
return { osc52, filePath: writtenPath, size: text.length };
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
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 { CacheFirstLoop } from "../../loop.js";
|
||||
import { DEEPSEEK_CONTEXT_TOKENS, DEFAULT_CONTEXT_TOKENS } from "../../telemetry/stats.js";
|
||||
import { countTokens } from "../../tokenizer.js";
|
||||
import { formatTokens } from "./primitives.js";
|
||||
import { COLOR } from "./theme.js";
|
||||
|
||||
export interface CtxBreakdownData {
|
||||
systemTokens: number;
|
||||
toolsTokens: number;
|
||||
logTokens: number;
|
||||
inputTokens: number;
|
||||
ctxMax: number;
|
||||
toolsCount: number;
|
||||
logMessages: number;
|
||||
topTools: Array<{ name: string; tokens: number; turn: number }>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Walk the loop's prefix + log and tally tokens per category. Cheap
|
||||
* after the tokenizer warm-up (~100 ms first call, sub-ms after).
|
||||
* Memoize at the call site if used inside a render path.
|
||||
*/
|
||||
export function computeCtxBreakdown(loop: CacheFirstLoop): CtxBreakdownData {
|
||||
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 ctxMax = DEEPSEEK_CONTEXT_TOKENS[loop.model] ?? DEFAULT_CONTEXT_TOKENS;
|
||||
const topTools = [...toolBreakdown].sort((a, b) => b.tokens - a.tokens).slice(0, 5);
|
||||
return {
|
||||
systemTokens,
|
||||
toolsTokens,
|
||||
logTokens,
|
||||
inputTokens: 0,
|
||||
ctxMax,
|
||||
toolsCount: loop.prefix.toolSpecs.length,
|
||||
logMessages: entries.length,
|
||||
topTools,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 4-segment stacked bar with legend + top-tools list. Pushed to
|
||||
* scrollback by the `/context` slash; the always-on bottom footer
|
||||
* uses its own slim 1-row layout in `CtxFooter`.
|
||||
*/
|
||||
export function CtxBreakdownBlock({ data }: { data: CtxBreakdownData }): React.ReactElement {
|
||||
const total = data.systemTokens + data.toolsTokens + data.logTokens + data.inputTokens;
|
||||
const winPct = data.ctxMax > 0 ? Math.round((total / data.ctxMax) * 100) : 0;
|
||||
const barWidth = 48;
|
||||
const cellOf = (n: number) => (data.ctxMax > 0 ? Math.round((n / data.ctxMax) * barWidth) : 0);
|
||||
const sysCells = cellOf(data.systemTokens);
|
||||
const toolsCells = cellOf(data.toolsTokens);
|
||||
const logCells = cellOf(data.logTokens);
|
||||
const inputCells = cellOf(data.inputTokens);
|
||||
const used = sysCells + toolsCells + logCells + inputCells;
|
||||
const freeCells = Math.max(0, barWidth - used);
|
||||
const sevColor = winPct >= 80 ? COLOR.err : winPct >= 60 ? COLOR.warn : COLOR.ok;
|
||||
|
||||
return (
|
||||
<Box
|
||||
flexDirection="column"
|
||||
marginY={1}
|
||||
borderStyle="single"
|
||||
borderTop={false}
|
||||
borderRight={false}
|
||||
borderBottom={false}
|
||||
borderColor={COLOR.brand}
|
||||
paddingLeft={1}
|
||||
>
|
||||
<Box>
|
||||
<Text color={COLOR.brand} bold>
|
||||
▣ context
|
||||
</Text>
|
||||
<Text dimColor>{` ${formatTokens(total)} of ${formatTokens(data.ctxMax)}`}</Text>
|
||||
<Text dimColor>{" · "}</Text>
|
||||
<Text color={sevColor} bold>
|
||||
{`${winPct}%`}
|
||||
</Text>
|
||||
{winPct >= 80 ? (
|
||||
<Text color={COLOR.err} bold>
|
||||
{" · /compact"}
|
||||
</Text>
|
||||
) : null}
|
||||
</Box>
|
||||
<Box>
|
||||
<Text color={COLOR.brand}>{"█".repeat(sysCells)}</Text>
|
||||
<Text color={COLOR.accent}>{"█".repeat(toolsCells)}</Text>
|
||||
<Text color={COLOR.primary}>{"█".repeat(logCells)}</Text>
|
||||
<Text color={COLOR.tool}>{"█".repeat(inputCells)}</Text>
|
||||
<Text color={COLOR.info} dimColor>
|
||||
{"░".repeat(freeCells)}
|
||||
</Text>
|
||||
</Box>
|
||||
<Box>
|
||||
<Text color={COLOR.brand}>■</Text>
|
||||
<Text dimColor>{` system ${formatTokens(data.systemTokens)}`}</Text>
|
||||
<Text>{" "}</Text>
|
||||
<Text color={COLOR.accent}>■</Text>
|
||||
<Text dimColor>{` tools ${formatTokens(data.toolsTokens)}`}</Text>
|
||||
<Text dimColor>{` (${data.toolsCount})`}</Text>
|
||||
<Text>{" "}</Text>
|
||||
<Text color={COLOR.primary}>■</Text>
|
||||
<Text dimColor>{` log ${formatTokens(data.logTokens)}`}</Text>
|
||||
<Text dimColor>{` (${data.logMessages} msg)`}</Text>
|
||||
<Text>{" "}</Text>
|
||||
<Text color={COLOR.tool}>■</Text>
|
||||
<Text dimColor>{` input ${formatTokens(data.inputTokens)}`}</Text>
|
||||
</Box>
|
||||
{data.topTools.length > 0 ? (
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
<Text dimColor>{` top tool results by cost (${data.topTools.length}):`}</Text>
|
||||
{data.topTools.map((t) => (
|
||||
<Box key={`${t.turn}-${t.name}`}>
|
||||
<Text dimColor>{` turn ${String(t.turn).padStart(3)} `}</Text>
|
||||
<Text color={COLOR.info}>{t.name.padEnd(22)}</Text>
|
||||
<Text dimColor>{` ${formatTokens(t.tokens).padStart(8)}`}</Text>
|
||||
</Box>
|
||||
))}
|
||||
</Box>
|
||||
) : null}
|
||||
<Box marginTop={1}>
|
||||
<Text dimColor>{" /compact shrinks oversized tool results · /new wipes log"}</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
import { formatAllBlockDiffs } from "../../code/diff-preview.js";
|
||||
import type { ApplyResult, EditBlock, EditSnapshot } from "../../code/edit-blocks.js";
|
||||
|
||||
/** Session-only — restoring pre-apply content across restarts 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;
|
||||
/** Tag for what produced the batch — "auto" / "auto-text" / "review-apply". */
|
||||
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 — multi-edit turns roll back to pre-turn state. */
|
||||
snapshots: EditSnapshot[];
|
||||
/** Per-path so a multi-file batch can be partially undone. */
|
||||
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";
|
||||
}
|
||||
|
||||
/** Status prefix is `✓`/`✗` so the line reads without color (piped, screenshots). */
|
||||
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");
|
||||
}
|
||||
|
||||
/** `[N]` labels so users can `/apply 1,3-4` instead of 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");
|
||||
}
|
||||
|
||||
/** Empty input → `{ ok: [] }` so callers detect "no indices" → default to all-blocks. */
|
||||
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) };
|
||||
}
|
||||
|
||||
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 };
|
||||
}
|
||||
|
||||
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,18 @@
|
||||
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 Frame, frameToAnsi } from "../../frame/index.js";
|
||||
|
||||
/** Frame → JSX. One Box per row. */
|
||||
export function renderFrame(f: Frame, keyPrefix: string): React.ReactElement {
|
||||
return (
|
||||
<>
|
||||
{f.rows.map((row, i) => (
|
||||
// biome-ignore lint/suspicious/noArrayIndexKey: row index is the row's identity
|
||||
<Box key={`${keyPrefix}/${i}`} height={1} flexShrink={0}>
|
||||
<Text>{frameToAnsi({ width: f.width, rows: [row] })}</Text>
|
||||
</Box>
|
||||
))}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
/** `#` writes project memory, `#g` global; `##+` stays a markdown heading; `\#` escapes and submits the literal `#`. */
|
||||
|
||||
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 "../../memory/project.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.
|
||||
|
||||
`;
|
||||
|
||||
export type HashMemoryParse =
|
||||
| { kind: "memory"; note: string }
|
||||
| { kind: "memory-global"; note: string }
|
||||
| { kind: "escape"; text: string };
|
||||
|
||||
/** Order: escape > `##` heading > `#g <body>` (mandatory space) > `#<body>` project. */
|
||||
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;
|
||||
}
|
||||
|
||||
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";
|
||||
|
||||
export function globalMemoryPath(homeDir: string = homedir()): string {
|
||||
return join(homeDir, GLOBAL_MEMORY_DIR, GLOBAL_MEMORY_FILE);
|
||||
}
|
||||
|
||||
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,73 @@
|
||||
/** CSI tail recovery for Ink useInput — Windows ConPTY splits `\x1b[A` across reads; we re-merge. */
|
||||
/** Only rewrites when no structured key flag is set AND input matches a known tail exactly. */
|
||||
|
||||
/** Structured-flag subset of Ink's Key — optional across Ink versions. */
|
||||
export interface CsiKeyFlags {
|
||||
upArrow?: boolean;
|
||||
downArrow?: boolean;
|
||||
leftArrow?: boolean;
|
||||
rightArrow?: boolean;
|
||||
pageUp?: boolean;
|
||||
pageDown?: boolean;
|
||||
delete?: boolean;
|
||||
shift?: boolean;
|
||||
tab?: boolean;
|
||||
}
|
||||
|
||||
/** Bracketed-paste `[200~`/`[201~` excluded — handled by PromptInput's paste accumulator. */
|
||||
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 } },
|
||||
];
|
||||
|
||||
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),
|
||||
);
|
||||
}
|
||||
|
||||
/** Already-structured events short-circuit so a real arrow press isn't 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;
|
||||
}
|
||||
|
||||
/** Includes paste `[200~`/`[201~` for the case where their markers chunked across reads. */
|
||||
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,134 @@
|
||||
/**
|
||||
* 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`.
|
||||
*/
|
||||
|
||||
import { useInput } from "ink";
|
||||
// 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; falls back to Ink's useInput when no KeystrokeProvider is mounted. */
|
||||
export function useKeystroke(handler: KeystrokeHandler, isActive = true): void {
|
||||
const bus = useContext(KeystrokeContext);
|
||||
const handlerRef = useRef(handler);
|
||||
handlerRef.current = handler;
|
||||
|
||||
useEffect(() => {
|
||||
if (!bus || !isActive) return undefined;
|
||||
return bus.subscribe((ev) => handlerRef.current(ev));
|
||||
}, [bus, isActive]);
|
||||
|
||||
useInput(
|
||||
(input, key) => {
|
||||
if (bus) return;
|
||||
handlerRef.current({
|
||||
input,
|
||||
upArrow: key.upArrow,
|
||||
downArrow: key.downArrow,
|
||||
leftArrow: key.leftArrow,
|
||||
rightArrow: key.rightArrow,
|
||||
return: key.return,
|
||||
escape: key.escape,
|
||||
backspace: key.backspace,
|
||||
delete: key.delete,
|
||||
tab: key.tab,
|
||||
shift: key.shift,
|
||||
ctrl: key.ctrl,
|
||||
meta: key.meta,
|
||||
pageUp: key.pageUp,
|
||||
pageDown: key.pageDown,
|
||||
});
|
||||
},
|
||||
{ isActive: !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 };
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,613 @@
|
||||
/**
|
||||
* Row-granular log rendering pipeline. Each `DisplayEvent` is
|
||||
* decomposed into one or more {@link LogItem}s — either a 1-row
|
||||
* inline `LogRow` (most chat noise: info / warn / error /
|
||||
* step-progress) or a multi-row atomic `LogBlock` (complex
|
||||
* components like plan / ctx-breakdown that we haven't broken
|
||||
* down yet).
|
||||
*
|
||||
* Why this exists: Ink's `overflow="hidden"` does NOT reliably clip
|
||||
* children with negative `marginTop` — content bleeds upward into
|
||||
* sibling regions (the chrome pills disappeared at scroll=0 in 0.13.0
|
||||
* because of exactly this). Clipping IS reliable for positive
|
||||
* overflow at the BOTTOM of a fixed-height parent. So instead of
|
||||
* fighting layout, we pre-flatten events into terminal-row units,
|
||||
* slice the row list, and render the slice as a stack of `<Box
|
||||
* height={1}>` items. Each item maps 1:1 to a terminal line, the
|
||||
* parent's overflow=hidden naturally clips overflow at the bottom,
|
||||
* and `justifyContent="flex-end"` (when at scroll=0) clips overflow
|
||||
* at the top by the same mechanism.
|
||||
*
|
||||
* Migration plan:
|
||||
* · 0.13.x : info / warn / error / step-progress → rows.
|
||||
* Everything else falls back to a single `LogBlock`
|
||||
* wrapping the existing `<EventRow>` component, so
|
||||
* the pipeline works end-to-end while complex roles
|
||||
* keep their old rendering.
|
||||
* · later : user / assistant text bodies → rows (split on \n,
|
||||
* one row per visual line).
|
||||
* · later : tool / edit_file diff → rows.
|
||||
* · later : plan / plan-replay / ctx-breakdown → rows.
|
||||
*
|
||||
* The slicer (`sliceLogItems`) treats `LogBlock`s as snap-points:
|
||||
* a partially-visible block at the viewport's top edge gets either
|
||||
* fully included or fully excluded, the user briefly "sticks" on
|
||||
* boundaries when wheel-scrolling through one. Once everything is
|
||||
* migrated to rows, scrolling is uniformly smooth.
|
||||
*/
|
||||
|
||||
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 DisplayEvent, EventRow } from "./EventLog.js";
|
||||
import { COLOR } from "./theme.js";
|
||||
|
||||
/**
|
||||
* Greedy character-count wrap. Accurate for ASCII / Latin; CJK
|
||||
* (where one char ≈ 2 cells) under-counts, but the parent's
|
||||
* overflow="hidden" still clips the bleed — at worst a visually-
|
||||
* tight row, not a layout break. Word-aware wrap is a future polish;
|
||||
* for now we just need the row count to be close enough that the
|
||||
* slicer's row arithmetic and the scrollbar thumb position aren't
|
||||
* obviously off.
|
||||
*/
|
||||
function wrapToWidth(text: string, width: number): string[] {
|
||||
if (width <= 0) return [text];
|
||||
const out: string[] = [];
|
||||
for (const line of text.split("\n")) {
|
||||
if (line.length === 0) {
|
||||
out.push("");
|
||||
continue;
|
||||
}
|
||||
if (line.length <= width) {
|
||||
out.push(line);
|
||||
continue;
|
||||
}
|
||||
let i = 0;
|
||||
while (i < line.length) {
|
||||
out.push(line.slice(i, i + width));
|
||||
i += width;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* One terminal line. Always renders inside an outer `<Box height={1}
|
||||
* flexShrink={0}>` so the slicer's row arithmetic stays exact —
|
||||
* overlong content soft-wraps in Ink unless we constrain row height,
|
||||
* which we don't here, but the parent's `overflow="hidden"` clips
|
||||
* any wrap-induced overflow.
|
||||
*/
|
||||
export interface LogRow {
|
||||
kind: "row";
|
||||
/** Stable React key. Must be unique within the rendered slice. */
|
||||
id: string;
|
||||
content: React.ReactElement;
|
||||
}
|
||||
|
||||
/**
|
||||
* A multi-row atomic component. Used as the fall-back when an event
|
||||
* role hasn't been broken down into individual rows yet. The slicer
|
||||
* snaps to block boundaries — partially-visible blocks at the viewport
|
||||
* top either render in full or get excluded.
|
||||
*/
|
||||
export interface LogBlock {
|
||||
kind: "block";
|
||||
id: string;
|
||||
/** Estimated terminal row count. Used by the slicer for cumulative
|
||||
* row arithmetic. Over-estimates are safer (reserve more rows
|
||||
* than needed) than under-estimates (block crowds the viewport
|
||||
* and content past the bottom clips silently). */
|
||||
rows: number;
|
||||
content: React.ReactElement;
|
||||
}
|
||||
|
||||
export type LogItem = LogRow | LogBlock;
|
||||
|
||||
/**
|
||||
* Row count for an item, used by the slicer.
|
||||
* `LogRow` is always 1; `LogBlock` carries its own estimate.
|
||||
*/
|
||||
export function itemRows(item: LogItem): number {
|
||||
return item.kind === "row" ? 1 : item.rows;
|
||||
}
|
||||
|
||||
/**
|
||||
* Detect the leading glyph in an info-row text and pick a color tone.
|
||||
* Mirrors the existing dispatch in `EventLog.tsx` so migrated rows
|
||||
* look identical to the legacy renderer for the same event payload.
|
||||
*/
|
||||
function detectInfoTone(text: string): { lead: string; color: string; body: string } {
|
||||
const m = text.match(/^([▸▶▲⚠✓✗✖↻ⓘ])\s*(.*)$/s);
|
||||
const lead = m?.[1] ?? "▸";
|
||||
const body = m?.[2] ?? text;
|
||||
let color: string = COLOR.info;
|
||||
if (lead === "▲" || lead === "⚠") color = COLOR.warn;
|
||||
else if (lead === "✓") color = COLOR.ok;
|
||||
else if (lead === "✗" || lead === "✖") color = COLOR.err;
|
||||
else if (lead === "↻") color = COLOR.primary;
|
||||
return { lead, color, body };
|
||||
}
|
||||
|
||||
/**
|
||||
* Render a single accent-bar row. The bar is the left vertical
|
||||
* border of the wrapper Box; subsequent rows of the same event share
|
||||
* the bar's color so vertically-adjacent rows visually merge into one
|
||||
* continuous bar (which is what users read as "this is one log entry").
|
||||
*
|
||||
* `prefix` is rendered inline before the line's body; pass `null` for
|
||||
* continuation lines that should align under the body, not the glyph.
|
||||
*/
|
||||
function AccentRow({
|
||||
color,
|
||||
prefix,
|
||||
body,
|
||||
bodyColor,
|
||||
bodyDim,
|
||||
}: {
|
||||
color: string;
|
||||
prefix: React.ReactNode | null;
|
||||
body: string;
|
||||
bodyColor?: string;
|
||||
bodyDim?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<Box
|
||||
borderStyle="single"
|
||||
borderTop={false}
|
||||
borderRight={false}
|
||||
borderBottom={false}
|
||||
borderColor={color}
|
||||
paddingLeft={1}
|
||||
>
|
||||
{prefix}
|
||||
<Text color={bodyColor} dimColor={bodyDim}>
|
||||
{body}
|
||||
</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Decompose a plain "accent-bar + glyph + multiline text" event into
|
||||
* one row per visual line, word-wrapping at `width`. The first line
|
||||
* carries the glyph; continuation lines align under the body so they
|
||||
* read as one entry.
|
||||
*/
|
||||
function accentRows(
|
||||
baseId: string,
|
||||
glyph: string,
|
||||
glyphColor: string,
|
||||
text: string,
|
||||
bodyColor: string | undefined,
|
||||
bodyDim: boolean,
|
||||
width: number,
|
||||
): LogRow[] {
|
||||
// Reserve cells for the border (1) + paddingLeft (1) + glyph + 2-space
|
||||
// gap so the wrap width matches the visual content column.
|
||||
const indentCells = 1 + 1 + glyph.length + 2;
|
||||
const inner = Math.max(8, width - indentCells);
|
||||
const lines = wrapToWidth(text, inner);
|
||||
return lines.map((line, i) => ({
|
||||
kind: "row" as const,
|
||||
id: `${baseId}/${i}`,
|
||||
content:
|
||||
i === 0 ? (
|
||||
<AccentRow
|
||||
color={glyphColor}
|
||||
prefix={
|
||||
<>
|
||||
<Text color={glyphColor} bold>
|
||||
{glyph}
|
||||
</Text>
|
||||
<Text>{" "}</Text>
|
||||
</>
|
||||
}
|
||||
body={line}
|
||||
bodyColor={bodyColor}
|
||||
bodyDim={bodyDim}
|
||||
/>
|
||||
) : (
|
||||
<AccentRow
|
||||
color={glyphColor}
|
||||
prefix={<Text>{" ".repeat(glyph.length + 2)}</Text>}
|
||||
body={line}
|
||||
bodyColor={bodyColor}
|
||||
bodyDim={bodyDim}
|
||||
/>
|
||||
),
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Decompose a finished `assistant` event into rows so a long summary
|
||||
* scrolls one terminal line at a time. Header (glyph + model badge)
|
||||
* is its own row; body becomes one row per wrapped line under the
|
||||
* assistant accent bar; stats / repair occupy dedicated trailing rows.
|
||||
*
|
||||
* **Fall-through:** events that carry branch / reasoning / non-empty
|
||||
* planState fall back to the legacy `LogBlock` because those
|
||||
* sub-components have their own internal layout we haven't row-split
|
||||
* yet. This keeps every advanced-feature event readable; the dominant
|
||||
* case (a plain summary turn) gets row-level scrolling.
|
||||
*
|
||||
* **Trade-off:** the row body bypasses the markdown renderer, so
|
||||
* inline formatting (bold / italic / code spans) is rendered as plain
|
||||
* text. Most assistant prose reads fine without it, and the original
|
||||
* formatted text is still in `~/.reasonix/sessions/<name>.jsonl`. If
|
||||
* code-block fidelity matters, users can /transcript or pipe the file
|
||||
* to `bat`. Worth it for the scrolling win.
|
||||
*/
|
||||
function assistantToRows(event: DisplayEvent, projectRoot?: string, width = 80): LogItem[] {
|
||||
// Skip row migration for events with branch / reasoning / planState —
|
||||
// those sub-blocks have nested layout we'd lose by flattening, and
|
||||
// they're uncommon enough that LogBlock fall-back is fine for v1.
|
||||
const hasComplexSub =
|
||||
event.branch || event.reasoning || (event.planState && Object.keys(event.planState).length > 0);
|
||||
if (hasComplexSub) {
|
||||
return [
|
||||
{
|
||||
kind: "block",
|
||||
id: event.id,
|
||||
rows: estimatedHeight(event),
|
||||
content: <EventRow event={event} projectRoot={projectRoot} />,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
const items: LogItem[] = [];
|
||||
// Top spacer matches the legacy renderer's `marginTop={1}`.
|
||||
items.push({
|
||||
kind: "row",
|
||||
id: `${event.id}/spacer-top`,
|
||||
content: <Text> </Text>,
|
||||
});
|
||||
// Header: assistant glyph + (optional) model badge.
|
||||
items.push({
|
||||
kind: "row",
|
||||
id: `${event.id}/head`,
|
||||
content: (
|
||||
<Box>
|
||||
<Text color={COLOR.assistant} bold>
|
||||
{"◆"}
|
||||
</Text>
|
||||
{event.stats ? (
|
||||
<>
|
||||
<Text>{" "}</Text>
|
||||
<Text backgroundColor={COLOR.assistant} color="black" bold>
|
||||
{` ${event.stats.model.replace(/^deepseek-/, "")} `}
|
||||
</Text>
|
||||
</>
|
||||
) : null}
|
||||
</Box>
|
||||
),
|
||||
});
|
||||
// Body rows — one per wrapped line, all sharing the assistant
|
||||
// accent bar on the left so they read as one entry visually even
|
||||
// though they're independent rows for scroll arithmetic.
|
||||
const body = event.text || "(empty body — likely tool-call only)";
|
||||
const dim = !event.text;
|
||||
items.push(...accentRows(event.id, "", COLOR.assistant, body, COLOR.assistant, dim, width));
|
||||
// Repair note: single line, accent violet, indented under the body.
|
||||
if (event.repair) {
|
||||
items.push({
|
||||
kind: "row",
|
||||
id: `${event.id}/repair`,
|
||||
content: (
|
||||
<Box paddingLeft={2}>
|
||||
<Text color={COLOR.accent}>{event.repair}</Text>
|
||||
</Box>
|
||||
),
|
||||
});
|
||||
}
|
||||
// Stats line — inlined here (kept as a 1-row LogRow rather than a
|
||||
// LogBlock) so the user can scroll past it cleanly.
|
||||
if (event.stats) {
|
||||
const hit = (event.stats.cacheHitRatio * 100).toFixed(1);
|
||||
const hitColor =
|
||||
event.stats.cacheHitRatio >= 0.7
|
||||
? "#4ade80"
|
||||
: event.stats.cacheHitRatio >= 0.4
|
||||
? "#fcd34d"
|
||||
: "#f87171";
|
||||
items.push({
|
||||
kind: "row",
|
||||
id: `${event.id}/stats`,
|
||||
content: (
|
||||
<Box paddingLeft={2}>
|
||||
<Text color={hitColor} bold>
|
||||
{`⌬ ${hit}%`}
|
||||
</Text>
|
||||
<Text dimColor>{" · "}</Text>
|
||||
<Text color="#94a3b8">{"in "}</Text>
|
||||
<Text color="#67e8f9" bold>
|
||||
{event.stats.usage.promptTokens}
|
||||
</Text>
|
||||
<Text color="#94a3b8">{" → out "}</Text>
|
||||
<Text color="#c4b5fd" bold>
|
||||
{event.stats.usage.completionTokens}
|
||||
</Text>
|
||||
<Text dimColor>{" · "}</Text>
|
||||
<Text color="#86efac" bold>{`$${event.stats.cost.toFixed(6)}`}</Text>
|
||||
</Box>
|
||||
),
|
||||
});
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a single `DisplayEvent` to its row-pipeline representation.
|
||||
* Migrated roles return `LogRow[]` (one item per visual terminal line,
|
||||
* word-wrapped to `width`); everything else falls back to a single
|
||||
* `LogBlock` wrapping the legacy `<EventRow>` component.
|
||||
*
|
||||
* `projectRoot` is forwarded to the legacy renderer for fall-back
|
||||
* blocks (used by the markdown renderer to resolve relative paths).
|
||||
*
|
||||
* `width` is the terminal column count. Used to word-wrap accent rows
|
||||
* so a single long line decomposes into the right number of rows —
|
||||
* this matters for the slicer's row arithmetic and for the scrollbar
|
||||
* thumb position, both of which assume row count == visual lines.
|
||||
*/
|
||||
export function eventToItems(event: DisplayEvent, projectRoot?: string, width = 80): LogItem[] {
|
||||
if (event.role === "info") {
|
||||
const { lead, color, body } = detectInfoTone(event.text);
|
||||
return accentRows(event.id, lead, color, body, undefined, true, width);
|
||||
}
|
||||
if (event.role === "warning") {
|
||||
return accentRows(event.id, "▲ warn", COLOR.warn, event.text, COLOR.warn, false, width);
|
||||
}
|
||||
if (event.role === "error") {
|
||||
return accentRows(event.id, "✦ error", COLOR.err, event.text, COLOR.err, false, width);
|
||||
}
|
||||
if (event.role === "assistant" && !event.streaming) {
|
||||
return assistantToRows(event, projectRoot, width);
|
||||
}
|
||||
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 ?? "");
|
||||
const rows: LogRow[] = [];
|
||||
// marginTop={1} in the legacy renderer — emit one blank spacer row.
|
||||
rows.push({
|
||||
kind: "row",
|
||||
id: `${event.id}/spacer`,
|
||||
content: <Text> </Text>,
|
||||
});
|
||||
// Header row: green-on-black STEP pill + counter + label.
|
||||
rows.push({
|
||||
kind: "row",
|
||||
id: `${event.id}/head`,
|
||||
content: (
|
||||
<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>
|
||||
),
|
||||
});
|
||||
// Optional body lines (one per \n-split line).
|
||||
if (event.text) {
|
||||
for (const [i, line] of event.text.split("\n").entries()) {
|
||||
rows.push({
|
||||
kind: "row",
|
||||
id: `${event.id}/body/${i}`,
|
||||
content: (
|
||||
<Box paddingLeft={2}>
|
||||
<Text dimColor>{line}</Text>
|
||||
</Box>
|
||||
),
|
||||
});
|
||||
}
|
||||
}
|
||||
if (sp?.notes) {
|
||||
rows.push({
|
||||
kind: "row",
|
||||
id: `${event.id}/notes`,
|
||||
content: (
|
||||
<Box paddingLeft={2}>
|
||||
<Text color="#fbbf24" dimColor>
|
||||
{`note: ${sp.notes}`}
|
||||
</Text>
|
||||
</Box>
|
||||
),
|
||||
});
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
// Fallback: render the whole event as one atomic block via the
|
||||
// legacy `EventRow`. Estimates row count via a copy of the slicer's
|
||||
// heightOf logic. Once a role is migrated above, this branch stops
|
||||
// running for that role.
|
||||
return [
|
||||
{
|
||||
kind: "block",
|
||||
id: event.id,
|
||||
rows: estimatedHeight(event),
|
||||
content: <EventRow event={event} projectRoot={projectRoot} />,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Mirror of the slicer's `heightOfEvent` from App.tsx — kept in sync
|
||||
* by hand. Used only for fall-back `LogBlock`s; migrated roles
|
||||
* compute their row count exactly via the row count itself.
|
||||
*/
|
||||
function estimatedHeight(e: DisplayEvent): number {
|
||||
const text = e.text ?? "";
|
||||
const wrapLines = Math.max(0, Math.floor(text.length / 80));
|
||||
if (e.role === "user") return 3 + wrapLines;
|
||||
if (e.role === "assistant") {
|
||||
let h = 4 + wrapLines;
|
||||
if (e.reasoning) h += 3;
|
||||
if (e.branch) h += 4;
|
||||
return h;
|
||||
}
|
||||
if (e.role === "tool") {
|
||||
const isEditFile = e.toolName === "edit_file" || e.toolName?.endsWith("_edit_file");
|
||||
if (isEditFile) {
|
||||
const diffLines = (text.match(/\n/g)?.length ?? 0) + 1;
|
||||
return 6 + Math.min(20, diffLines);
|
||||
}
|
||||
return 2;
|
||||
}
|
||||
if (e.role === "plan" || e.role === "plan-replay" || e.role === "plan-resumed") return 10;
|
||||
if (e.role === "ctx-breakdown") return 7;
|
||||
return 2;
|
||||
}
|
||||
|
||||
export interface RowSlice {
|
||||
items: LogItem[];
|
||||
/** Highest valid scroll offset (rows). Caller clamps with this. */
|
||||
maxScrollRows: number;
|
||||
/** Total rows across all events (informational, e.g. for "↑ N rows above" hints). */
|
||||
totalRows: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Slice the flat `LogItem` list to fit `available` viewport rows,
|
||||
* scrolled up by `scrollOffsetRows` from the bottom.
|
||||
*
|
||||
* Snap behavior: if the viewport top edge would fall *inside* a
|
||||
* `LogBlock`, the block is included in full (so it might extend
|
||||
* partially above the viewport — clipped by the parent's flex-end
|
||||
* + overflow=hidden). The same trick that makes the BOTTOM of a tall
|
||||
* latest event readable is what makes block snap-rendering safe.
|
||||
*/
|
||||
export function sliceLogItems(
|
||||
items: readonly LogItem[],
|
||||
available: number,
|
||||
scrollOffsetRows: number,
|
||||
): RowSlice {
|
||||
if (items.length === 0) {
|
||||
return { items: [], maxScrollRows: 0, totalRows: 0 };
|
||||
}
|
||||
const heights = items.map(itemRows);
|
||||
const totalRows = heights.reduce((a, b) => a + b, 0);
|
||||
// Cap the scroll so the OLDEST viewport-full of rows (oldest line at
|
||||
// the top of the viewport) is reachable but the user never scrolls
|
||||
// past it into empty space. With `totalRows - 1` the user could
|
||||
// scroll until only one row remained visible — scrollbar at the top
|
||||
// and viewport mostly empty, which feels broken. Leaving a viewport-
|
||||
// worth of rows below the absolute top means Home / max-scroll lands
|
||||
// on a fully-populated viewport showing the start of the log.
|
||||
const maxScrollRows = Math.max(0, totalRows - available);
|
||||
const offset = Math.max(0, Math.min(scrollOffsetRows, maxScrollRows));
|
||||
|
||||
const viewportBottom = totalRows - offset;
|
||||
const viewportTop = Math.max(0, viewportBottom - available);
|
||||
|
||||
// Walk forward, picking items whose row range overlaps the viewport.
|
||||
// Items entirely above viewport are dropped; entirely below ends the
|
||||
// walk early.
|
||||
let cursor = 0;
|
||||
let firstIdx = -1;
|
||||
let lastIdx = -1;
|
||||
for (let i = 0; i < items.length; i++) {
|
||||
const eStart = cursor;
|
||||
const eEnd = cursor + heights[i]!;
|
||||
cursor = eEnd;
|
||||
if (eEnd <= viewportTop) continue;
|
||||
if (eStart >= viewportBottom) break;
|
||||
if (firstIdx === -1) firstIdx = i;
|
||||
lastIdx = i;
|
||||
}
|
||||
if (firstIdx === -1) {
|
||||
// Should not happen with clamped offset + non-empty items, but
|
||||
// fall back to "render the last item" so the user never sees a
|
||||
// blank middle.
|
||||
return { items: [items[items.length - 1]!], maxScrollRows, totalRows };
|
||||
}
|
||||
return {
|
||||
items: items.slice(firstIdx, lastIdx + 1),
|
||||
maxScrollRows,
|
||||
totalRows,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrap a `LogItem` in the height-1 (or natural-height for blocks) Box
|
||||
* that keeps the slicer's row arithmetic exact. `flexShrink={0}`
|
||||
* prevents Ink from squashing rows when the parent's content overflows.
|
||||
*/
|
||||
export function renderLogItem(item: LogItem): React.ReactElement {
|
||||
if (item.kind === "row") {
|
||||
return (
|
||||
<Box key={item.id} height={1} flexShrink={0}>
|
||||
{item.content}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Box key={item.id} flexShrink={0}>
|
||||
{item.content}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* One-row hint pinned at the bottom of the log viewport when the user
|
||||
* has scrolled up. Tells them how many rows of newer content sit
|
||||
* below the visible window and how to jump back. Hidden when the user
|
||||
* is at the bottom (offset === 0) since there's nothing to point to.
|
||||
*
|
||||
* `rowsBelow` is the same as the active `logScrollOffset` (rows from
|
||||
* the bottom that aren't currently visible).
|
||||
*/
|
||||
export function BottomHint({
|
||||
rowsBelow,
|
||||
totalRows,
|
||||
viewportRows,
|
||||
}: {
|
||||
rowsBelow: number;
|
||||
totalRows: number;
|
||||
viewportRows: number;
|
||||
}) {
|
||||
if (rowsBelow <= 0) return null;
|
||||
const maxScroll = Math.max(1, totalRows - viewportRows);
|
||||
const ratioFromTop = Math.max(0, Math.min(1, (totalRows - rowsBelow - viewportRows) / maxScroll));
|
||||
const pct = Math.round((1 - ratioFromTop) * 100);
|
||||
const rowsAbove = Math.max(0, totalRows - viewportRows - rowsBelow);
|
||||
const barCells = 16;
|
||||
const markerAt = Math.max(0, Math.min(barCells - 1, Math.round(ratioFromTop * (barCells - 1))));
|
||||
const left = "─".repeat(markerAt);
|
||||
const right = "─".repeat(barCells - 1 - markerAt);
|
||||
return (
|
||||
<Box height={1} flexShrink={0}>
|
||||
<Text color={COLOR.primary} bold>
|
||||
{`↑ ${rowsAbove}`}
|
||||
</Text>
|
||||
<Text>{" "}</Text>
|
||||
<Text dimColor>▕</Text>
|
||||
<Text color={COLOR.info} dimColor>
|
||||
{left}
|
||||
</Text>
|
||||
<Text color={COLOR.brand} bold>
|
||||
●
|
||||
</Text>
|
||||
<Text color={COLOR.info} dimColor>
|
||||
{right}
|
||||
</Text>
|
||||
<Text dimColor>▏</Text>
|
||||
<Text>{" "}</Text>
|
||||
<Text color={COLOR.primary} bold>{`${pct}%`}</Text>
|
||||
<Text>{" "}</Text>
|
||||
<Text color={COLOR.primary}>{`↓ ${rowsBelow}`}</Text>
|
||||
<Text dimColor>{" · End to jump · wheel to scroll"}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
/** Pure parsing for `/loop <interval> <prompt>`; cancellation contract is enforced in App.tsx. */
|
||||
|
||||
/** 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;
|
||||
|
||||
/** Returns null on bad shape OR out-of-range; caller surfaces as usage hint. */
|
||||
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;
|
||||
}
|
||||
|
||||
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 };
|
||||
}
|
||||
|
||||
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}`;
|
||||
}
|
||||
|
||||
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`;
|
||||
}
|
||||
@@ -0,0 +1,310 @@
|
||||
/** Markdown→Frame compiler reusing `parseBlocks` from markdown.tsx; tables / edit blocks / citations fall back to plain text. */
|
||||
|
||||
import {
|
||||
type Cell,
|
||||
type Frame,
|
||||
type TextOpts,
|
||||
borderLeft,
|
||||
empty,
|
||||
pad,
|
||||
text,
|
||||
vstack,
|
||||
} from "../../frame/index.js";
|
||||
import { type Block, parseBlocks } from "./markdown.js";
|
||||
import { COLOR } from "./theme.js";
|
||||
|
||||
/** Mirrors `markdown.tsx` INLINE_RE — link/bold/italic/code/strike/escape. */
|
||||
const INLINE_RE =
|
||||
/(\[([^\]\n]+)\]\(([^)\n]+)\)|\*\*\*([^*\n]+?)\*\*\*|\*\*([^*\n]+?)\*\*|```([^\n]+?)```|`([^`\n]+?)`|~~([^~\n]+?)~~|(?<![*\w])\*([^*\n]+?)\*(?!\w)|\\([*_~`[\](){}#+\-.!\\]))/g;
|
||||
|
||||
interface InlineSegment {
|
||||
text: string;
|
||||
opts: Omit<TextOpts, "width">;
|
||||
}
|
||||
|
||||
function parseInline(input: string, baseOpts: Omit<TextOpts, "width">): InlineSegment[] {
|
||||
const out: InlineSegment[] = [];
|
||||
let lastEnd = 0;
|
||||
// The regex is /g so we must reset lastIndex when reusing it.
|
||||
INLINE_RE.lastIndex = 0;
|
||||
for (let m = INLINE_RE.exec(input); m !== null; m = INLINE_RE.exec(input)) {
|
||||
if (m.index > lastEnd) {
|
||||
out.push({ text: input.slice(lastEnd, m.index), opts: baseOpts });
|
||||
}
|
||||
const linkText = m[2];
|
||||
const linkUrl = m[3];
|
||||
const boldItalic = m[4];
|
||||
const bold = m[5];
|
||||
const code3 = m[6];
|
||||
const code1 = m[7];
|
||||
const strike = m[8];
|
||||
const italic = m[9];
|
||||
const escapeChar = m[10];
|
||||
if (linkText !== undefined) {
|
||||
out.push({
|
||||
text: linkText,
|
||||
opts: { ...baseOpts, fg: COLOR.accent, underline: true, href: linkUrl },
|
||||
});
|
||||
} else if (boldItalic !== undefined) {
|
||||
out.push({ text: boldItalic, opts: { ...baseOpts, bold: true, italic: true } });
|
||||
} else if (bold !== undefined) {
|
||||
out.push({ text: bold, opts: { ...baseOpts, bold: true } });
|
||||
} else if (code3 !== undefined) {
|
||||
// Strip leading "lang " prefix (consistent with the legacy renderer)
|
||||
const stripped = code3.replace(/^(\w+)\s+/, "");
|
||||
out.push({ text: stripped, opts: { ...baseOpts, fg: "#67e8f9", bg: "#0f172a" } });
|
||||
} else if (code1 !== undefined) {
|
||||
out.push({ text: code1, opts: { ...baseOpts, fg: "#67e8f9", bg: "#0f172a" } });
|
||||
} else if (strike !== undefined) {
|
||||
out.push({ text: strike, opts: { ...baseOpts, dim: true } });
|
||||
} else if (italic !== undefined) {
|
||||
out.push({ text: italic, opts: { ...baseOpts, italic: true } });
|
||||
} else if (escapeChar !== undefined) {
|
||||
out.push({ text: escapeChar, opts: baseOpts });
|
||||
}
|
||||
lastEnd = m.index + m[0]!.length;
|
||||
}
|
||||
if (lastEnd < input.length) {
|
||||
out.push({ text: input.slice(lastEnd), opts: baseOpts });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Single wrap loop over flattened (cell, style) atoms — keeps wrap logic in one place across styles. */
|
||||
function segmentsToFrame(segs: readonly InlineSegment[], width: number): Frame {
|
||||
if (width <= 0) return empty(0);
|
||||
// Build a flat list of "atoms" — each atom is one grapheme + its
|
||||
// style. We reuse Frame's text() to handle grapheme width / 2-wide
|
||||
// chars correctly: rendering each segment to a 1-row Frame at a
|
||||
// very wide budget gives back its cell array, which we splice
|
||||
// together for the wrap.
|
||||
const atoms: Cell[] = [];
|
||||
for (const seg of segs) {
|
||||
if (!seg.text) continue;
|
||||
// Use a generous width so the segment doesn't pre-wrap inside text()
|
||||
const f = text(seg.text, { ...seg.opts, width: Math.max(width, seg.text.length * 2 + 4) });
|
||||
if (f.rows.length > 0) {
|
||||
// Strip trailing space-padding the text() helper adds; the
|
||||
// segment's actual cells are the leading non-space prefix.
|
||||
let stop = f.rows[0]!.length;
|
||||
while (
|
||||
stop > 0 &&
|
||||
f.rows[0]![stop - 1]!.char === " " &&
|
||||
f.rows[0]![stop - 1]!.fg === undefined &&
|
||||
f.rows[0]![stop - 1]!.bg === undefined
|
||||
) {
|
||||
stop--;
|
||||
}
|
||||
for (let i = 0; i < stop; i++) atoms.push(f.rows[0]![i]!);
|
||||
}
|
||||
// Multi-line segments (rare with inline markup, but possible if
|
||||
// text contained \n) — append blank cells then continue.
|
||||
for (let li = 1; li < f.rows.length; li++) {
|
||||
// Insert a newline marker via a sentinel cell? Simpler: emit
|
||||
// a hard-break row right now and continue with the next line.
|
||||
// To keep `atoms` 1-D, we encode \n as a special cell char and
|
||||
// handle in the wrap loop. Use a SOH sentinel char that won't
|
||||
// appear in real text.
|
||||
atoms.push({ char: "\n", width: 1 });
|
||||
let stop = f.rows[li]!.length;
|
||||
while (
|
||||
stop > 0 &&
|
||||
f.rows[li]![stop - 1]!.char === " " &&
|
||||
f.rows[li]![stop - 1]!.fg === undefined
|
||||
) {
|
||||
stop--;
|
||||
}
|
||||
for (let i = 0; i < stop; i++) atoms.push(f.rows[li]![i]!);
|
||||
}
|
||||
}
|
||||
// Greedy wrap: walk atoms, accumulate cells until current row width
|
||||
// would exceed `width` (skipping tail cells from the count); on a
|
||||
// newline atom, force a row break.
|
||||
const SPACE: Cell = { char: " ", width: 1 };
|
||||
const rows: Cell[][] = [];
|
||||
let cur: Cell[] = [];
|
||||
let curW = 0;
|
||||
let lastSpaceIdx = -1;
|
||||
const flushRow = (forceNewline = false): void => {
|
||||
while (curW < width) {
|
||||
cur.push(SPACE);
|
||||
curW += 1;
|
||||
}
|
||||
rows.push(cur);
|
||||
cur = [];
|
||||
curW = 0;
|
||||
lastSpaceIdx = -1;
|
||||
if (forceNewline) return;
|
||||
};
|
||||
for (const a of atoms) {
|
||||
if (a.char === "\n") {
|
||||
flushRow(true);
|
||||
continue;
|
||||
}
|
||||
const w = a.tail ? 0 : a.width;
|
||||
if (curW + w > width) {
|
||||
// Try to break at the last whitespace we saw — soft wrap.
|
||||
if (lastSpaceIdx >= 0 && lastSpaceIdx > 0) {
|
||||
// Cut the row at lastSpaceIdx; carry overflow atoms into the
|
||||
// next row.
|
||||
const overflow = cur.slice(lastSpaceIdx + 1);
|
||||
cur = cur.slice(0, lastSpaceIdx);
|
||||
let newW = 0;
|
||||
for (const c of cur) newW += c.tail ? 0 : c.width;
|
||||
// Pad current row to width
|
||||
while (newW < width) {
|
||||
cur.push(SPACE);
|
||||
newW += 1;
|
||||
}
|
||||
rows.push(cur);
|
||||
cur = overflow;
|
||||
curW = 0;
|
||||
for (const c of cur) curW += c.tail ? 0 : c.width;
|
||||
lastSpaceIdx = -1;
|
||||
} else {
|
||||
// No whitespace to break at — hard wrap.
|
||||
flushRow();
|
||||
}
|
||||
}
|
||||
if (a.char === " ") lastSpaceIdx = cur.length;
|
||||
cur.push(a);
|
||||
curW += w;
|
||||
}
|
||||
if (cur.length > 0 || rows.length === 0) {
|
||||
flushRow();
|
||||
}
|
||||
return { width, rows };
|
||||
}
|
||||
|
||||
function paragraphFrame(p: { text: string }, width: number): Frame {
|
||||
const segs = parseInline(p.text, {});
|
||||
return segmentsToFrame(segs, width);
|
||||
}
|
||||
|
||||
function headingFrame(h: { level: number; text: string }, width: number): Frame {
|
||||
const isMajor = h.level <= 3;
|
||||
const fg = isMajor ? COLOR.brand : COLOR.accent;
|
||||
const segs = parseInline(h.text, { bold: true, fg, dim: !isMajor });
|
||||
return vstack(segmentsToFrame(segs, width), text("", { width }));
|
||||
}
|
||||
|
||||
/** Continuation lines align under the body, not under the bullet. */
|
||||
function bulletListFrame(
|
||||
b: { items: { text: string; task?: "done" | "todo" }[]; ordered?: boolean },
|
||||
width: number,
|
||||
): Frame {
|
||||
const rows: Frame[] = [];
|
||||
for (let i = 0; i < b.items.length; i++) {
|
||||
const item = b.items[i]!;
|
||||
let prefix: string;
|
||||
let prefixOpts: Omit<TextOpts, "width">;
|
||||
if (item.task === "done") {
|
||||
prefix = "[x] ";
|
||||
prefixOpts = { fg: COLOR.ok, bold: true };
|
||||
} else if (item.task === "todo") {
|
||||
prefix = "[ ] ";
|
||||
prefixOpts = { fg: COLOR.warn, bold: true };
|
||||
} else if (b.ordered) {
|
||||
prefix = `${i + 1}. `;
|
||||
prefixOpts = { fg: COLOR.info, bold: true };
|
||||
} else {
|
||||
prefix = "• ";
|
||||
prefixOpts = { fg: COLOR.info, bold: true };
|
||||
}
|
||||
const prefixWidth = prefix.length;
|
||||
const indentRow = " ".repeat(prefixWidth);
|
||||
const innerSegs = parseInline(item.text, {});
|
||||
const innerFrame = segmentsToFrame(innerSegs, Math.max(8, width - prefixWidth));
|
||||
// Decorate first line with prefix, subsequent lines with spaces.
|
||||
const decoratedRows: Frame[] = innerFrame.rows.map((r, li) => {
|
||||
const indent =
|
||||
li === 0
|
||||
? text(prefix, { width: prefixWidth, ...prefixOpts })
|
||||
: text(indentRow, { width: prefixWidth });
|
||||
return {
|
||||
width: prefixWidth + innerFrame.width,
|
||||
rows: [[...indent.rows[0]!, ...r]],
|
||||
};
|
||||
});
|
||||
rows.push(...decoratedRows);
|
||||
}
|
||||
return vstack(...rows);
|
||||
}
|
||||
|
||||
function codeBlockFrame(c: { lang: string; text: string }, width: number): Frame {
|
||||
const lines = c.text.split("\n");
|
||||
const rows: Frame[] = [];
|
||||
if (c.lang) {
|
||||
rows.push(text(c.lang, { width, fg: COLOR.info, dim: true, italic: true }));
|
||||
}
|
||||
for (const line of lines) {
|
||||
rows.push(text(line || " ", { width, fg: "#67e8f9", bg: "#0f172a" }));
|
||||
}
|
||||
return vstack(...rows);
|
||||
}
|
||||
|
||||
function blockquoteFrame(bq: { children: Block[] }, width: number): Frame {
|
||||
const inner = bq.children.map((child) => blockToFrame(child, Math.max(8, width - 2)));
|
||||
const stacked = inner.length === 0 ? empty(Math.max(8, width - 2)) : vstack(...inner);
|
||||
return borderLeft(pad(stacked, 0, 0, 0, 1), COLOR.info);
|
||||
}
|
||||
|
||||
function hrFrame(width: number): Frame {
|
||||
return text("─".repeat(width), { width, fg: COLOR.info, dim: true });
|
||||
}
|
||||
|
||||
function blockToFrame(b: Block, width: number): Frame {
|
||||
switch (b.kind) {
|
||||
case "paragraph":
|
||||
return paragraphFrame(b, width);
|
||||
case "heading":
|
||||
return headingFrame(b, width);
|
||||
case "bullet":
|
||||
return bulletListFrame(b, width);
|
||||
case "code":
|
||||
return codeBlockFrame(b, width);
|
||||
case "quote":
|
||||
return blockquoteFrame(b, width);
|
||||
case "hr":
|
||||
return hrFrame(width);
|
||||
case "table":
|
||||
// Tables: render as plain-text rows for now; full table layout
|
||||
// is a future migration. Header gets bold, body rows dim.
|
||||
return vstack(
|
||||
text(b.header.join(" | "), { width, bold: true }),
|
||||
text(b.header.map(() => "─").join("─┼─"), { width, dim: true }),
|
||||
text(b.rows.map((r) => r.join(" | ")).join("\n"), { width, dim: true }),
|
||||
);
|
||||
case "edit-block":
|
||||
// Aider edit blocks: render filename + SEARCH/REPLACE summaries
|
||||
// as plain text. The full diff renderer lives in EditBlockRow
|
||||
// which we keep on the legacy Ink path until migration.
|
||||
return text(`${b.filename}\n<<< SEARCH\n${b.search}\n=======\n${b.replace}\n>>> REPLACE`, {
|
||||
width,
|
||||
dim: true,
|
||||
});
|
||||
default:
|
||||
// Unknown block kind — should never happen given the parser's
|
||||
// exhaustive Block union, but stay defensive.
|
||||
return empty(width);
|
||||
}
|
||||
}
|
||||
|
||||
export function markdownToFrame(markdown: string, width: number): Frame {
|
||||
if (!markdown) return empty(width);
|
||||
const blocks = parseBlocks(markdown);
|
||||
if (blocks.length === 0) return empty(width);
|
||||
const frames: Frame[] = [];
|
||||
for (let i = 0; i < blocks.length; i++) {
|
||||
const b = blocks[i]!;
|
||||
frames.push(blockToFrame(b, width));
|
||||
// Inter-block separator. Skip after blocks that already include
|
||||
// their own trailing spacer (headings) so we don't double-space.
|
||||
const isLast = i === blocks.length - 1;
|
||||
const carriesOwnSpacer = b.kind === "heading";
|
||||
if (!isLast && !carriesOwnSpacer) {
|
||||
frames.push(text("", { width }));
|
||||
}
|
||||
}
|
||||
return vstack(...frames);
|
||||
}
|
||||
+765
-71
File diff suppressed because it is too large.
Load diff
@@ -1,24 +1,4 @@
|
||||
/**
|
||||
* `/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.
|
||||
*/
|
||||
/** `/resource` + `/prompt` handlers — async (round-trip to MCP server), so App.tsx calls directly instead of `handleSlash`. */
|
||||
|
||||
import type { McpClient } from "../../mcp/client.js";
|
||||
import type {
|
||||
@@ -30,11 +10,6 @@ import type {
|
||||
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 {
|
||||
@@ -167,12 +142,6 @@ function formatOnePromptMessage(m: McpPromptMessage): string {
|
||||
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,
|
||||
|
||||
+100
-35
@@ -1,25 +1,4 @@
|
||||
/**
|
||||
* Pure keystroke → action reducer for PromptInput.
|
||||
*
|
||||
* Kept separate from the React component so the keyboard semantics
|
||||
* are easy to unit-test. The component threads `useInput` through
|
||||
* this function and applies the returned action.
|
||||
*
|
||||
* Edit model:
|
||||
* - Full cursor support. ←/→ move one column. ↑/↓ move across
|
||||
* lines in a multi-line buffer (column preserved when possible).
|
||||
* Ctrl+A / Ctrl+E jump to start / end of the current line.
|
||||
* - Backspace deletes the char before the cursor; Delete deletes
|
||||
* the char under the cursor.
|
||||
* - Printable chars (including multi-char paste bursts) insert
|
||||
* at the cursor.
|
||||
* - Enter submits unless Shift is held (newline), the line ends
|
||||
* with '\' and cursor is at end (bash-style continuation), or
|
||||
* the input is Ctrl+J (LF, terminal-universal newline).
|
||||
* - Parent owns Tab, Esc, PageUp/Down (slash-complete, abort,
|
||||
* unused). Arrow keys are split: empty buffer → parent (history
|
||||
* recall); non-empty → child (cursor movement).
|
||||
*/
|
||||
/** Pure keystroke→action reducer; arrow keys at buffer boundary defer to the parent for history recall. */
|
||||
|
||||
export interface MultilineKey {
|
||||
input: string;
|
||||
@@ -47,8 +26,14 @@ export interface MultilineAction {
|
||||
/** When `true`, fire `onSubmit(submitValue ?? value)`. */
|
||||
submit: boolean;
|
||||
submitValue?: string;
|
||||
/** Set when ↑/↓ hits a buffer boundary — parent handles history recall. */
|
||||
historyHandoff?: "prev" | "next";
|
||||
/** Reducer is pure — hands raw paste to PromptInput which allocates a sentinel and inserts that. */
|
||||
pasteRequest?: { content: string };
|
||||
}
|
||||
|
||||
import { recoverCsiTail, stripCsiFragments } from "./key-normalize.js";
|
||||
|
||||
const BACKSLASH_SUFFIX = /\\$/;
|
||||
|
||||
const NOOP: MultilineAction = { next: null, cursor: null, submit: false };
|
||||
@@ -56,19 +41,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 +104,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");
|
||||
}
|
||||
@@ -148,11 +210,6 @@ function insertAt(value: string, cursor: number, insert: string): MultilineActio
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Line + column of a cursor inside a buffer. Exported because the
|
||||
* renderer needs the same mapping for drawing the cursor block on the
|
||||
* right line.
|
||||
*/
|
||||
export function lineAndColumn(value: string, cursor: number): { line: number; col: number } {
|
||||
let line = 0;
|
||||
let col = 0;
|
||||
@@ -172,6 +229,14 @@ function startOfLine(value: string, cursor: number): number {
|
||||
return value.lastIndexOf("\n", cursor - 1) + 1;
|
||||
}
|
||||
|
||||
/** Skips trailing whitespace first so Ctrl+W after a space still removes the previous word. */
|
||||
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;
|
||||
|
||||
@@ -1,18 +1,5 @@
|
||||
/**
|
||||
* 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).
|
||||
*/
|
||||
/** Display-only — the MODEL always receives full paste text. */
|
||||
|
||||
/** 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. */
|
||||
@@ -35,19 +22,6 @@ export interface PasteCollapseResult {
|
||||
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 = {},
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
/** PUA range U+E100..U+E1FF (BMP, no surrogate pairs) so each sentinel is one codepoint and cursor arithmetic stays trivial. */
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
export function makePasteEntry(id: number, content: string): PasteEntry {
|
||||
return {
|
||||
id,
|
||||
content,
|
||||
lineCount: content.split("\n").length,
|
||||
charCount: content.length,
|
||||
};
|
||||
}
|
||||
|
||||
/** Unknown sentinels drop to empty — never leak a PUA codepoint into the prompt. */
|
||||
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;
|
||||
}
|
||||
|
||||
export function bufferHasPaste(text: string): boolean {
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
if (decodePasteSentinel(text[i]!) !== null) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
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`;
|
||||
}
|
||||
+64
-26
@@ -1,42 +1,80 @@
|
||||
/**
|
||||
* One place that defines what each preset means. Both `slash.ts`
|
||||
* (in-chat `/preset`) and the wizard (first-run setup) read from here.
|
||||
*
|
||||
* Presets are the single vocabulary we teach new users: they don't need
|
||||
* to know model IDs, Pillar 2, branch budgets, or cost tradeoffs
|
||||
* independently — they pick "fast / smart / max" and we translate.
|
||||
*/
|
||||
/** Preset table — branch and harvest stay off here so users never get ambushed into N× cost without opting in. */
|
||||
|
||||
import type { PresetName } from "../../config.js";
|
||||
|
||||
export interface PresetSettings {
|
||||
model: string;
|
||||
reasoningEffort: "high" | "max";
|
||||
autoEscalate: boolean;
|
||||
/** Pillar-2 harvest. Always false in presets — opt-in via /harvest. */
|
||||
harvest: boolean;
|
||||
/** Branch budget. `1` means branching off. */
|
||||
/** Branch budget. Always 1 in presets — opt-in via /branch. */
|
||||
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 },
|
||||
};
|
||||
|
||||
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",
|
||||
/** Old names `fast`/`smart`/`max` aliased via `resolvePreset` so legacy configs still load. */
|
||||
export const PRESETS: Record<"auto" | "flash" | "pro", PresetSettings> = {
|
||||
// auto — flash baseline + auto-escalate to pro when the model emits
|
||||
// <<<NEEDS_PRO>>> OR after 3+ tool failure signals in one turn.
|
||||
// The default: cheap when easy, smart when hard.
|
||||
auto: {
|
||||
model: "deepseek-v4-flash",
|
||||
reasoningEffort: "max",
|
||||
autoEscalate: true,
|
||||
harvest: false,
|
||||
branch: 1,
|
||||
},
|
||||
smart: {
|
||||
headline: "deepseek-reasoner + Pillar 2 harvest",
|
||||
cost: "~10× cost vs fast · slower · better on multi-step tasks",
|
||||
// flash — always flash, never escalate. `/pro` still arms a single
|
||||
// manual turn; auto-promotion is the thing this disables. Use when
|
||||
// you want predictable cost per turn.
|
||||
flash: {
|
||||
model: "deepseek-v4-flash",
|
||||
reasoningEffort: "max",
|
||||
autoEscalate: false,
|
||||
harvest: false,
|
||||
branch: 1,
|
||||
},
|
||||
max: {
|
||||
headline: "reasoner + harvest + self-consistency (3 branches)",
|
||||
cost: "~30× cost vs fast · slowest · for hard single-shots",
|
||||
// pro — always pro. Hard pin; the model never downgrades. Use for
|
||||
// multi-turn architecture work where flash is just going to keep
|
||||
// escalating anyway and the back-and-forth wastes turns.
|
||||
pro: {
|
||||
model: "deepseek-v4-pro",
|
||||
reasoningEffort: "max",
|
||||
autoEscalate: false,
|
||||
harvest: false,
|
||||
branch: 1,
|
||||
},
|
||||
};
|
||||
|
||||
export const PRESET_DESCRIPTIONS: Record<
|
||||
"auto" | "flash" | "pro",
|
||||
{ headline: string; cost: string }
|
||||
> = {
|
||||
auto: {
|
||||
headline: "flash → pro on hard turns",
|
||||
cost: "default · ~96% turns stay on flash · pro kicks in only when needed",
|
||||
},
|
||||
flash: {
|
||||
headline: "v4-flash always",
|
||||
cost: "cheapest · predictable · /pro still works for a one-turn bump",
|
||||
},
|
||||
pro: {
|
||||
headline: "v4-pro always",
|
||||
cost: "~3× flash (5/31 discount) / ~12× full price · for hard multi-turn work",
|
||||
},
|
||||
};
|
||||
|
||||
/** Legacy aliases: fast→flash+high, smart→auto, max→pro. Unknown names fall through to auto. */
|
||||
export function resolvePreset(name: PresetName | undefined): PresetSettings {
|
||||
return PRESETS[name ?? "fast"];
|
||||
if (name === "auto" || name === "flash" || name === "pro") return PRESETS[name];
|
||||
if (name === "fast") return { ...PRESETS.flash, reasoningEffort: "high" };
|
||||
if (name === "smart") return PRESETS.auto;
|
||||
if (name === "max") return PRESETS.pro;
|
||||
return PRESETS.auto;
|
||||
}
|
||||
|
||||
/** Canonical name for storage / display — unknown values become auto. */
|
||||
export function canonicalPresetName(name: PresetName | undefined): "auto" | "flash" | "pro" {
|
||||
if (name === "auto" || name === "flash" || name === "pro") return name;
|
||||
return "auto";
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
import { Text, useStdout } from "ink";
|
||||
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React in value scope for JSX compilation
|
||||
import React from "react";
|
||||
import { COLOR } from "./theme.js";
|
||||
|
||||
/**
|
||||
* Faint full-width horizontal rule. Width tracks the terminal columns
|
||||
* minus 2 cells so it lines up exactly under content rendered inside
|
||||
* a `paddingX={1}` parent — the standard chrome layout. Used by the
|
||||
* top chrome bar, the replay StatsPanel, and the bottom ctx footer.
|
||||
*/
|
||||
export function ChromeRule(): React.ReactElement {
|
||||
const { stdout } = useStdout();
|
||||
const cols = stdout?.columns ?? 80;
|
||||
const w = Math.max(20, cols - 2);
|
||||
return <Text dimColor>{"─".repeat(w)}</Text>;
|
||||
}
|
||||
|
||||
/** Compact binary-K formatter — `1234 → "1.2K"`, `131072 → "128K"`. */
|
||||
export function formatTokens(n: number): string {
|
||||
if (n < 1024) return String(n);
|
||||
const k = n / 1024;
|
||||
return k >= 100 ? `${k.toFixed(0)}K` : `${k.toFixed(1)}K`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Filled / empty progress bar. `▰▱` glyphs have distinct shapes so the
|
||||
* boundary stays visible even when the terminal collapses to 8-color slots.
|
||||
*/
|
||||
export function Bar({
|
||||
ratio,
|
||||
color,
|
||||
cells = 14,
|
||||
dim,
|
||||
}: {
|
||||
ratio: number;
|
||||
color: string;
|
||||
cells?: number;
|
||||
dim?: boolean;
|
||||
}): React.ReactElement {
|
||||
const filled = Math.max(0, Math.min(cells, Math.round(ratio * cells)));
|
||||
return (
|
||||
<Text>
|
||||
<Text color={color} dimColor={dim}>
|
||||
{"▰".repeat(filled)}
|
||||
</Text>
|
||||
<Text dimColor>{"▱".repeat(cells - filled)}</Text>
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* `▣ ctx ▰▰▱▱… 14K/128K (11%)` — the canonical context-pressure cell.
|
||||
* Used by the persistent footer (chat) and StatsPanel (replay). Color
|
||||
* thresholds match the `/compact` warning policy in the loop:
|
||||
* green <60% · amber 60-80% · red ≥80% (with `· /compact` hint).
|
||||
*/
|
||||
export function ContextCell({
|
||||
ratio,
|
||||
promptTokens,
|
||||
ctxMax,
|
||||
showBar,
|
||||
}: {
|
||||
ratio: number;
|
||||
promptTokens: number;
|
||||
ctxMax: number;
|
||||
showBar?: boolean;
|
||||
}): React.ReactElement {
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
/** Slice each prompt line to a single visual row — Ink/Yoga wrap miscounts on CJK Windows terminals and leaks ghost rows. */
|
||||
|
||||
import { type PasteEntry, decodePasteSentinel, formatBytesShort } from "./paste-sentinels.js";
|
||||
|
||||
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[];
|
||||
/** `null` when cursor is not on this 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;
|
||||
}
|
||||
|
||||
/** Treats Ambiguous=1 to match Ink/Yoga's own miscount — agreement matters more than correctness here. */
|
||||
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;
|
||||
}
|
||||
|
||||
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 };
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
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
-1553
File diff suppressed because it is too large.
Load diff
Loaded 100 of 303 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user