mirror of
https://github.com/esengine/DeepSeek-Reasonix.git
synced 2026-11-07 10:45:59 -10:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 | ||
|
|
1e906bb577 | ||
|
|
a8c367ad0c |
No files matched your search
@@ -24,3 +24,9 @@ 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
|
||||
+607
@@ -3,6 +3,613 @@
|
||||
All notable changes to Reasonix. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/);
|
||||
this project uses [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [0.12.0] — 2026-04-28
|
||||
|
||||
**Headline:** Web dashboard. A top-tier local control plane that lives
|
||||
alongside the TUI — chat, files, MCP, skills, hooks, settings, all on
|
||||
one URL. Plus auto/flash/pro preset rework so model commitment is
|
||||
something you actually understand.
|
||||
|
||||
### Web dashboard (`/dashboard` slash)
|
||||
|
||||
A full-screen browser app, embedded HTTP server, 12 panels, modal
|
||||
mirroring back to the live TUI. 127.0.0.1 only, ephemeral token in
|
||||
the URL, CSRF on every mutation.
|
||||
|
||||
**Foundation (v0.12 base)**
|
||||
- HTTP server in `src/server/` — Node native `http`, zero new deps
|
||||
- Token + CSRF auth, audit log per mutation
|
||||
- Preact 10 + HTM SPA (no build step), CSS lifted from `src/cli/ui/theme.ts`
|
||||
- 12 panels, all functional: Chat / Overview / Usage / Sessions /
|
||||
Plans / Tools / Permissions / System / MCP / Skills / Memory /
|
||||
Hooks / Settings
|
||||
|
||||
**Chat parity (v0.13a)**
|
||||
- POST `/submit` routes through `handleSubmit` so slash commands,
|
||||
`!cmd`, `@path` work identically; SSE `/events` streams loop
|
||||
events live; `/abort` mirrors Esc; `/messages` snapshots the
|
||||
log; `/modal/resolve` lets web pick a ShellConfirm /
|
||||
ChoiceConfirm / PlanConfirm / EditConfirm — either surface
|
||||
resolves, the other's modal disappears
|
||||
- Web: marked.js + highlight.js 38-language pack, GFM tables,
|
||||
custom diff renderer for SEARCH/REPLACE blocks (red `-` / green
|
||||
`+`) and unified diffs, kind-specific tool cards (edit_file,
|
||||
read_file, write_file, run_command), markdown-styled assistant
|
||||
messages with reasoning blockquote, blinking cursor while
|
||||
streaming, scroll lock when user reads above bottom, custom
|
||||
scrollbars in brand palette
|
||||
|
||||
**Observability (v0.13b)**
|
||||
- Sessions browser — list / read any saved session
|
||||
- Plans archive — replay archived plans with risk pills
|
||||
- Usage time-series chart (uPlot) — daily cost / cache-saved / turns
|
||||
- System health — disk usage, version check, jobs
|
||||
|
||||
**Mutation surface (v0.14)**
|
||||
- MCP — list bridged servers + add/remove specs to config
|
||||
- Skills — list, edit body, create new, delete
|
||||
- Memory — REASONIX.md + global / project private memory editor
|
||||
- Hooks — settings.json hook block editor + reload
|
||||
- Settings — API key (write-only), base URL, preset, effort, search
|
||||
|
||||
**Polish (v0.15)**
|
||||
- Mobile responsive: sidebar collapses to drawer with hamburger,
|
||||
metric grid drops to 2 columns, header stacks vertically
|
||||
- Animations: fade-in for messages, slide-in for modals + toasts,
|
||||
`prefers-reduced-motion` respected
|
||||
- Toast system (top-right, auto-dismiss)
|
||||
- Global error overlay — `window.error` + `unhandledrejection` +
|
||||
Preact ErrorBoundary all funnel into a full-screen card with
|
||||
copy-details + "Report on GitHub" prefilled-issue button
|
||||
|
||||
**Editor drawer (post-v0.15)**
|
||||
- Click any path in chat tool cards → CodeMirror 6 drawer slides
|
||||
in from the right (50% width, full-screen on mobile)
|
||||
- Multi-tab, dirty flag, Cmd/Ctrl+S save, syntax highlighting in
|
||||
14 languages, gitignore-aware file picker
|
||||
- Drawer state persists across sidebar tab switches
|
||||
|
||||
**Live status bar (in Chat)**
|
||||
- model · ctx token gauge · cache hit % · turn cost · session
|
||||
cost · DeepSeek balance — 2.5s poll, mirrors TUI StatsPanel
|
||||
|
||||
**Live mode pickers (in Chat)**
|
||||
- Edit mode (review/auto/yolo) — instant
|
||||
- Effort (high/max) — applies next turn, also flippable from `/effort`
|
||||
- Preset (auto/flash/pro) — applies next turn via `applyPresetLive`
|
||||
- New / Clear conversation buttons (route through `/new` and `/clear`)
|
||||
|
||||
### Preset rework — auto / flash / pro
|
||||
|
||||
**Headline:** old `fast / smart / max` collapsed into model-commitment
|
||||
vocabulary that actually says what it does.
|
||||
|
||||
- **`auto`** — flash baseline, auto-escalates to pro on
|
||||
`<<<NEEDS_PRO>>>` markers or after 3+ tool failure signals.
|
||||
The default — covers ~96% of turns at flash cost.
|
||||
- **`flash`** — flash always. No auto-escalation. `/pro` still
|
||||
works for one-shot manual escalation.
|
||||
- **`pro`** — pro always. No downgrade. ~3× flash at the 5/31
|
||||
discount window, ~12× outside it.
|
||||
|
||||
`autoEscalate: boolean` added to the loop (constructor + reconfigure)
|
||||
gates both auto-escalation paths (NEEDS_PRO marker scavenge +
|
||||
failure-count threshold). `flash` and `pro` presets pass `false`,
|
||||
locking the running session to one model.
|
||||
|
||||
Legacy `fast / smart / max` names: still parse from existing
|
||||
config files but collapse to `auto` — simpler than mapping the old
|
||||
semantics onto the new vocabulary, user re-picks if they want flash
|
||||
or pro explicitly.
|
||||
|
||||
`applyPresetLive` callback in `DashboardContext` flips the live
|
||||
loop's model + autoEscalate + reasoningEffort the moment the user
|
||||
clicks a preset in the web Chat picker — no session restart.
|
||||
|
||||
### Other
|
||||
|
||||
- `cacheSavingsUsd(model, hitTokens)` in `src/telemetry.ts` — USD
|
||||
the prompt cache shaved off the bill (miss-price minus hit-price
|
||||
for cached tokens). Surfaced in `reasonix stats` dashboard +
|
||||
`/api/usage` rolled buckets + the Usage chart.
|
||||
- Built-in shell allowlist (`BUILTIN_ALLOWLIST`) re-exported for
|
||||
the dashboard's Permissions panel listing.
|
||||
- `removeProjectShellAllowed` + `clearProjectShellAllowed` in
|
||||
`src/config.ts`.
|
||||
- StreamableHttpTransport (MCP 2025-03-26) — already shipped in
|
||||
0.11.3 but documented here for completeness; this release adds
|
||||
the Mcp panel UI on top.
|
||||
- `DashboardEvent` + `ActiveModal` types exported from
|
||||
`src/server/context.ts` for downstream tooling.
|
||||
|
||||
### Tests
|
||||
|
||||
1568 vitest tests pass. New test files: `tests/server-dashboard.test.ts`
|
||||
(40 tests covering auth/CSRF, every endpoint shape, SSE round-trip,
|
||||
mid-modal mutations).
|
||||
|
||||
## [0.11.3] — 2026-04-27
|
||||
|
||||
**Headline:** Two long-deferred items land — `/permissions` makes the
|
||||
shell allowlist auditable and editable from inside the TUI, and
|
||||
Streamable HTTP MCP transport (2025-03-26 spec) clears the last debt
|
||||
from the v0.3 deferred queue.
|
||||
|
||||
### Added
|
||||
|
||||
- **`/permissions`** — list / add / remove / clear the shell
|
||||
allowlist without leaving the session. Bare `/permissions` shows
|
||||
the current edit mode (review / auto / yolo with a yolo-bypasses-
|
||||
allowlist banner), the per-project entries with 1-based indices,
|
||||
and the read-only builtin list grouped by leading verb. Subcommands:
|
||||
`/permissions add <prefix>` (multi-token OK), `/permissions remove
|
||||
<prefix-or-N>` (literal match or list index), `/permissions clear
|
||||
confirm`. Refuses to add a prefix that's already in the builtin
|
||||
list (no redundant project entry) and refuses to remove a builtin
|
||||
(read-only). Mutating subcommands require code mode. `perms`
|
||||
registered as alias.
|
||||
- **`removeProjectShellAllowed` + `clearProjectShellAllowed`**
|
||||
exported from `src/config.ts`. The remove helper does literal-
|
||||
prefix match (not prefix-of-prefix), so dropping `git` doesn't
|
||||
accidentally remove `git push origin main` if both were stored.
|
||||
- **MCP Streamable HTTP transport (2025-03-26 spec)** —
|
||||
`src/mcp/streamable-http.ts` implements the new single-endpoint
|
||||
protocol. POSTs JSON-RPC frames, handles all three response shapes
|
||||
(202 Accepted for notifications, `application/json` for single
|
||||
responses, `text/event-stream` for multi-frame streams covering
|
||||
progress + response). Captures `Mcp-Session-Id` from the first
|
||||
response that hands one out and echoes it on every subsequent
|
||||
request; surfaces 404-with-session as a "session expired" error
|
||||
so callers know to reinitialize. Long-lived GET stream for
|
||||
unsolicited server-initiated frames is deliberately deferred —
|
||||
POST-only handles full request/response/notification traffic
|
||||
for every server we'd realistically point at today.
|
||||
- **Spec parser** — `streamable+http(s)://` prefix routes to the
|
||||
new transport (`{ transport: "streamable-http", url, name }`).
|
||||
Plain `http(s)://` still routes to SSE (2024-11-05) so existing
|
||||
`--mcp` config entries keep working without surprise upgrades.
|
||||
Wired through `chat.tsx`, `run.ts`, and `reasonix mcp inspect`.
|
||||
Public API gains `StreamableHttpTransport` + the
|
||||
`StreamableHttpMcpSpec` type re-export.
|
||||
|
||||
### Tests
|
||||
|
||||
- `tests/permissions-slash.test.ts` — 16 tests covering listing,
|
||||
add, remove (by prefix and by 1-based index), clear, mode banner,
|
||||
builtin-collision rejection, codeRoot guard, alias.
|
||||
- `tests/config.test.ts` — 6 new tests for `removeProjectShellAllowed`
|
||||
/ `clearProjectShellAllowed` (literal-only matching, scoping per
|
||||
project, idempotent counts).
|
||||
- `tests/mcp-streamable-http.test.ts` — 8 tests against an in-process
|
||||
`http.Server` fake that speaks the 2025-03-26 wire shape: JSON
|
||||
response delivery, 202 ack as no-op, session-id capture+echo,
|
||||
multi-frame SSE ordering (progress → response), full McpClient
|
||||
initialize → tools/list round-trip, 404+session = "expired",
|
||||
500-as-error from `send()`, `close()` unblocks idle iterators.
|
||||
- `tests/mcp-spec.test.ts` — 4 tests for the new prefix parsing.
|
||||
|
||||
1521 tests pass (+24). Lint / typecheck / build clean.
|
||||
|
||||
## [0.11.2] — 2026-04-27
|
||||
|
||||
**Headline:** `/init` synthesizes a baseline REASONIX.md so a new
|
||||
project starts with context instead of cold. Closes the gap with
|
||||
Claude Code's `/init`, scoped to the structure REASONIX expects.
|
||||
|
||||
### Added
|
||||
|
||||
- **`/init`** — model-driven REASONIX.md generator. The slash
|
||||
emits a structured user-turn prompt (via the `resubmit` channel)
|
||||
that hard-constrains the model to a fact-only document with
|
||||
Stack / Layout / Commands / Conventions / Watch out for sections,
|
||||
capped at 80 lines / 3KB so REASONIX.md doesn't bloat the system
|
||||
prompt every launch. Reuses the existing filesystem tools (no new
|
||||
pipeline) and the result lands as a pending edit in the normal
|
||||
review queue, so the user audits before it hits disk. Refuses to
|
||||
overwrite an existing REASONIX.md without `/init force`. Removes
|
||||
the friction of having to hand-author a project memory file.
|
||||
|
||||
## [0.11.1] — 2026-04-27
|
||||
|
||||
**Headline:** Workspace-switching, end to end. Four real-use bugs
|
||||
that all hit the same scenario — `Esc` poisoned the next turn,
|
||||
Chinese-Windows shell errors came back as mojibake, the markdown
|
||||
renderer ate `\TEST` out of `F:\TEST1`, and the model had no idea
|
||||
how to change directories. Plus two new ways to do it: `/cwd <path>`
|
||||
the user types, and `change_workspace` the model calls (always
|
||||
gated on an explicit confirmation modal — no auto-switching).
|
||||
|
||||
### Fixed
|
||||
|
||||
- **`Esc` poisoned the next turn.** The loop's user-Esc abort branch
|
||||
processed the cancel correctly but left `_turnAbort` in an aborted
|
||||
state on its way out. The carry-abort logic at `step()` entry then
|
||||
re-aborted at iter 0 on every subsequent turn, so the user typed
|
||||
a fresh prompt and saw "stopped without producing a summary"
|
||||
before any model call ran. The session was effectively dead until
|
||||
restart. Fix: reset `_turnAbort` to a fresh controller before
|
||||
returning from the abort branch — the across-turn race that the
|
||||
carry logic guards against still works because a new `abort()`
|
||||
fired between turns aborts the new controller. Regression test
|
||||
added (`tests/loop.test.ts`).
|
||||
- **Mojibake on Chinese / Japanese / Korean Windows shell errors.**
|
||||
`runCommand` decoded child output as UTF-8 incrementally per
|
||||
chunk. Two failure modes:
|
||||
1. `cmd.exe`'s OWN error messages (e.g. "'sed' is not recognized
|
||||
as an internal or external command") come from a localized
|
||||
resource DLL and ignore `chcp 65001`, so on Chinese Windows
|
||||
the bytes are CP936/GBK and decoded as UTF-8 produced
|
||||
unreadable garbage.
|
||||
2. Multi-byte sequences could split across chunk boundaries and
|
||||
corrupt before the second half arrived.
|
||||
Fix: collect raw `Buffer[]` chunks and decode once at close via
|
||||
a new `smartDecodeOutput` — strict UTF-8 first; on Windows fall
|
||||
back to GB18030 (GBK superset) when UTF-8 rejects the bytes;
|
||||
last resort lossy UTF-8 keeps the structural exit-code marker
|
||||
intact. PowerShell's existing `injectPowerShellUtf8` prelude
|
||||
still covers the PS path; this fixes the path where the model
|
||||
invokes a native EXE directly (`run_command sed …`).
|
||||
- **Markdown renderer ate `\TEST` out of `F:\TEST1`.** `stripMath`'s
|
||||
catch-all LaTeX command stripper (`\\[a-zA-Z]+` → `""`) deleted any
|
||||
backslash-followed-by-letters sequence — fine for an invented
|
||||
`\textbf{…}` the model emitted, catastrophic for Windows paths in
|
||||
prose. `F:\TEST1` rendered as `F:1`. Fix: gate the entire
|
||||
`stripMath` pipeline on a math-marker pre-check (`$`, `\(`, `\[`,
|
||||
known LaTeX commands, `^{…}`/`_{…}`, Pandoc super/subscripts). When
|
||||
none are present we return the string untouched. Mixed inputs (a
|
||||
path AND real math in the same message) still run the pipeline —
|
||||
math correctness wins over path preservation in that rare collision.
|
||||
- **Model didn't know `/cwd` existed.** When asked to switch to a
|
||||
project on another drive, the model fumbled with `pwd`,
|
||||
`cd /d F:\TEST1`, and `2>&1` shell tricks (none of which work —
|
||||
`cd` doesn't carry across `run_command` calls and `2>&1` is rejected
|
||||
as a shell operator by design). The code-mode system prompt now has
|
||||
a "When the user wants to switch project / working directory"
|
||||
section telling the model to surface `/cwd <path>` once and stop,
|
||||
instead of trying to do it itself.
|
||||
|
||||
### Added
|
||||
|
||||
- **`change_workspace` tool** — model-callable workspace switching,
|
||||
gated on a confirmation modal. The tool fn validates the target,
|
||||
resolves it (absolute / `~`-expanded / relative-to-launch-cwd), then
|
||||
always throws a `WorkspaceConfirmationError` with the absolute
|
||||
path. App.tsx detects the marker and mounts a Switch / Deny modal;
|
||||
on approval it calls the same `applyCwdChange` path that drives
|
||||
`/cwd` (re-registers filesystem / shell / memory tools, reloads
|
||||
hooks, syncs the loop's hookCwd). On denial the model gets a
|
||||
synthetic "user refused, continue without it" message. No
|
||||
"always allow" option — workspace switches are per-target by
|
||||
nature. The code-mode system prompt now tells the model to call
|
||||
this tool (rather than fumble with `cd /d`) when the user asks
|
||||
to change projects, and to STOP after the call instead of chaining
|
||||
more tools before the user has confirmed.
|
||||
- **`/cwd <path>`** — switch the session's working directory mid-
|
||||
session. Validates the target (must exist, must be a directory),
|
||||
expands `~`, then atomically: updates the hook cwd, memory root,
|
||||
project shell allowlist, `@file` mention root, and re-registers
|
||||
filesystem / shell / memory / `run_skill` tools against the new
|
||||
path so file reads, edits, and shell commands all land in the
|
||||
new sandbox. MCP servers stay anchored to the original cwd
|
||||
(their stdio child was spawned with the launch root and there's
|
||||
no standard reconnect handshake) — the slash output flags this
|
||||
explicitly when MCP servers are present. The system prompt's
|
||||
gitignore-aware project tour is also frozen at launch so the
|
||||
prefix cache stays valid; the slash output notes it for users
|
||||
switching to a structurally different project.
|
||||
|
||||
## [0.11.0] — 2026-04-27
|
||||
|
||||
**Headline:** Local semantic search lands as an opt-in pillar — Ollama-
|
||||
backed embedding index, `reasonix index` CLI with progress spinner, a
|
||||
`/semantic` slash for status, and bilingual (zh/en) prompts. Plus a
|
||||
trio of subagent abort races that made `Esc` silently fail to stop a
|
||||
running subagent.
|
||||
|
||||
### Added — Pillar 5: local semantic search
|
||||
|
||||
- **`reasonix index`** — new CLI command that walks the project, line-
|
||||
windows source files, embeds via Ollama (`nomic-embed-text` by
|
||||
default, ~274 MB once), and persists a JSONL index at
|
||||
`.reasonix/semantic/`. Incremental by default (mtime-based), with
|
||||
`--rebuild` for a full wipe. Per-chunk failures are logged + skipped
|
||||
so one bad file doesn't kill a 30-minute build.
|
||||
- **Preflight prompts** — detects missing Ollama binary / daemon /
|
||||
model and offers to start `ollama serve` or `ollama pull <model>`
|
||||
with `[Y/n]` confirms. `--yes` for scripts. Non-TTY exits cleanly
|
||||
with a remediation hint.
|
||||
- **TTY progress spinner** — Braille `⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏` ticks every
|
||||
120ms via `setInterval`, INDEPENDENT of progress events. Builds
|
||||
that take 30+ seconds never look hung. Non-TTY mode keeps phase
|
||||
lines + heartbeats for parseable CI logs.
|
||||
- **Chunker safety** — `maxChunkChars` cap (default 4000 ≈ 1000
|
||||
tokens) with line-boundary splitting for oversized windows and
|
||||
hard-truncation for single overlong lines. Fixes Ollama 500 "the
|
||||
input length exceeds the context length" on minified / dense files.
|
||||
- **`semantic_search` tool** — registered in `reasonix code` only when
|
||||
an index exists. Tool description is now directive ("FIRST CHOICE
|
||||
for descriptive queries"); the code-mode system prompt grows a
|
||||
`# Search routing` fragment when the tool is registered, telling
|
||||
the model to prefer semantic_search for intent-style questions
|
||||
and fall back to grep for exact tokens.
|
||||
- **`/semantic` slash** — shows status (built? Ollama installed?
|
||||
daemon up?) plus how-to-enable hints. Fire-and-forget pattern, same
|
||||
as `/kill` — sync placeholder, async post via `ctx.postInfo`.
|
||||
- **Bilingual UI** — `src/index/semantic/i18n.ts` with EN/ZH dicts
|
||||
for every preflight + `/semantic` + progress label. Locale
|
||||
detection: `REASONIX_LANG` override → `LANG`/`LC_ALL`/`LC_MESSAGES`
|
||||
(Unix) → `Intl.DateTimeFormat` (Windows fallback) → `en`. Tool
|
||||
descriptions and CLI `--help` stay English on purpose (model-facing
|
||||
text aligns with training distribution; commander's --help is
|
||||
registered once at boot).
|
||||
- **Startup is silent** — no auto-prompt on `reasonix code` launch.
|
||||
If an index exists, the tool registers; otherwise the bootstrap
|
||||
is a no-op. Discovery happens via `/semantic` when the user is
|
||||
curious, or via the explicit `reasonix index` command.
|
||||
|
||||
### Fixed — subagent `Esc` abort races
|
||||
|
||||
- **`addEventListener("abort", …)` doesn't replay aborts** — DOM
|
||||
semantics: an already-aborted signal won't fire the abort event
|
||||
again, so a parent that aborted before `spawnSubagent` attached
|
||||
its listener silently lost the cancel. Sync-check `.aborted` at
|
||||
attach and forward immediately to `childLoop.abort()`.
|
||||
- **`step()` was overwriting aborted state** — at the top of
|
||||
`step()` we reassign `_turnAbort = new AbortController()`. If
|
||||
`loop.abort()` had been called BEFORE `step()` ran, the prior
|
||||
aborted controller was discarded and the fresh one started clean.
|
||||
Carry the aborted bit forward so the iter-0 check still bails.
|
||||
- **`forcedSummary` was treated as success** — when the loop aborted
|
||||
it yielded a synthetic `assistant_final` with `forcedSummary: true`
|
||||
and content `"[aborted by user (Esc) — no summary produced.]"`.
|
||||
The subagent stuffed that into `final` and returned `success: true`,
|
||||
so `/skill` cheerfully reported "subagent finished" with the abort
|
||||
message as the answer. Now `forcedSummary` routes to `errorMessage`
|
||||
→ `success: false` → caller renders the error.
|
||||
|
||||
### Added — docs / website
|
||||
|
||||
- **GitHub Pages site under `docs/`** — bilingual landing page (auto-
|
||||
detect via `navigator.language`, manual EN/中文 toggle, persisted
|
||||
per-browser), brand-gradient dark theme, hero terminal animation
|
||||
that mirrors the real TUI rendering primitives (◇/◆ role glyphs,
|
||||
yellow tool pills, rounded cyan EditBlockRow with `- old` red /
|
||||
`+ new` green diff lines, info-row pending/applied status).
|
||||
- **`README.zh-CN.md`** — full Chinese mirror of `README.md`. Both
|
||||
READMEs now carry a language switcher header at the top.
|
||||
|
||||
### Tests (+27, 1441 → 1468)
|
||||
|
||||
- `tests/semantic-chunker.test.ts` — line-window splitting, overlap,
|
||||
forward-slash path normalization, NUL-byte sniff; the new
|
||||
`chunkText` cap behavior (multi-line split + hard-truncate-overlong-
|
||||
line + idempotent passthrough).
|
||||
- `tests/semantic-store.test.ts` — JSONL roundtrip, cosine ranking,
|
||||
minScore threshold, dim-mismatch refusal, model-mismatch refusal,
|
||||
remove + wipe, fileMtimes.
|
||||
- `tests/semantic-embed-tolerant.test.ts` — `embedAll` returns
|
||||
`Array<Float32Array | null>` on per-chunk error (mocked Ollama 500),
|
||||
abort still throws globally, all-fail surface, progress fires once
|
||||
per chunk regardless of outcome.
|
||||
- `tests/semantic-i18n.test.ts` — locale detection precedence,
|
||||
override env var, placeholder substitution, ZH dict.
|
||||
- `tests/semantic-bootstrap.test.ts` — registers when index exists,
|
||||
silent skip otherwise (no startup prompt).
|
||||
- `tests/semantic-slash.test.ts` — `/semantic` status renderer,
|
||||
enabled / not-built / Chinese-locale paths.
|
||||
- `tests/semantic-launcher.test.ts` — `findOllamaBinary` contract.
|
||||
- `tests/code-prompt.test.ts` — search-routing fragment is absent by
|
||||
default and present + ordered before .gitignore when the flag is on.
|
||||
- `tests/subagent.test.ts` — regression: parent signal already aborted
|
||||
at dispatch time (race we previously dropped on the floor).
|
||||
|
||||
### Refactored
|
||||
|
||||
- **`src/code/prompt.ts`** — `codeSystemPrompt(rootDir, opts?)` grew
|
||||
a `hasSemanticSearch` flag; the routing fragment is appended only
|
||||
when the tool is actually registered. Cache prefix stays stable per
|
||||
session because the flag is captured at launch.
|
||||
|
||||
## [0.6.0] — 2026-04-24
|
||||
|
||||
**Headline:** Cost control becomes a first-class pillar. Default flips
|
||||
flash-first, `v4-pro` is opt-in, tool results auto-compact between
|
||||
turns, and the TUI grows per-turn cost visibility + a `/pro`
|
||||
one-shot upgrade. Month-over-month cost on an active coding project
|
||||
drops ~6–10× in practice.
|
||||
|
||||
### ⚠ Breaking (behavior, not API)
|
||||
|
||||
- **Default model is now `deepseek-v4-flash`**, not `deepseek-v4-pro`.
|
||||
`reasonix code`, `reasonix chat`, and subagents all land on flash
|
||||
by default. Users who need the frontier tier:
|
||||
`/preset max`, `/pro`, or `--model deepseek-v4-pro` on CLI.
|
||||
- **Preset defaults changed**. None of the three presets auto-enable
|
||||
`branch` or `harvest` anymore — both were hidden multipliers. The
|
||||
new matrix:
|
||||
| preset | model | effort | harvest | branch |
|
||||
|---|---|---|---|---|
|
||||
| fast | v4-flash | high | off | 1 |
|
||||
| smart (default) | v4-flash | max | off | 1 |
|
||||
| max | v4-pro | max | off | 1 |
|
||||
Users who want branching still get it via `/branch N`; users who
|
||||
want harvest still get it via `/harvest on`. Neither is implicit.
|
||||
- **Default preset is now `smart` (was `fast`).** Flash + full
|
||||
thinking budget is the best price/quality point for coding.
|
||||
- **`deepseek-chat` / `deepseek-reasoner` aliases scheduled for
|
||||
removal.** Still accepted (they map to flash non-thinking /
|
||||
thinking), but every user-facing surface (`/models`, setup wizard,
|
||||
`--help`) now advertises `v4-flash` / `v4-pro` only.
|
||||
|
||||
### Added — Cost control (Pillar 4)
|
||||
|
||||
- **`/pro` single-turn arming** — queue v4-pro for just the next
|
||||
turn; auto-disarms after. Separate from `/preset max` (persistent)
|
||||
so "this one task is hard" doesn't require a preset round-trip.
|
||||
Status bar shows `⇧ pro armed` in yellow while queued, `⇧ pro
|
||||
escalated` in red while the turn is actually running on pro.
|
||||
- **Failure-triggered auto-escalation** — the loop tracks
|
||||
`edit_file` SEARCH-not-found errors + ToolCallRepair fires per
|
||||
turn. 3+ signals flip the rest of the turn to `v4-pro` with a
|
||||
visible warning row. Counter resets at every turn start. No
|
||||
silent cost surprises.
|
||||
- **Model self-report escalation (`<<<NEEDS_PRO>>>`)** — system
|
||||
prompt teaches the model that when a task CLEARLY exceeds flash's
|
||||
capability (complex architecture, subtle correctness, genuine
|
||||
design trade-offs), emit the marker as the first line of its
|
||||
response. The loop aborts that call, retries this turn on pro,
|
||||
one shot. Guarded against infinite retry (pro never self-
|
||||
escalates) and streaming output is buffered so the marker never
|
||||
flickers on-screen before the retry fires.
|
||||
- **Turn-end auto-compaction** — every tool result over 3000 tokens
|
||||
gets shrunk to a cap at turn end. Biggest win for long sessions:
|
||||
a 12KB `read_file` output stops re-paying its cost on every
|
||||
future prompt. The proactive in-turn threshold also dropped from
|
||||
60% → 40% so the reactive 80% path rarely fires.
|
||||
- **Forced-summary + truncation-repair auxiliary calls hard-route to
|
||||
flash+effort=high** regardless of the main-turn tier. No reason to
|
||||
pay pro rates for "paraphrase these tool results into prose" or
|
||||
"close this truncated JSON."
|
||||
- **Subagent default flipped to `v4-flash` + `effort=high`**. Skill
|
||||
frontmatter `model:` / `effort:` remain the per-skill override.
|
||||
- **StatsPanel cost badges** — per-turn cost alongside session total.
|
||||
Colored thresholds: turn green under $0.05, yellow $0.05–0.20,
|
||||
red ≥$0.20; session same scale ×10.
|
||||
|
||||
### Added — UX
|
||||
|
||||
- **Plan body now flows into scrollback**, not inside the modal.
|
||||
`submit_plan` pushes a dedicated `role: "plan"` row into the
|
||||
Static log (rendered via the full markdown pipeline, never
|
||||
truncated); the PlanConfirm modal below shrinks to a tight
|
||||
approve/refine/cancel picker. Long plans are fully readable via
|
||||
terminal scrollback.
|
||||
- **Shared prompt fragments** — `TUI_FORMATTING_RULES` and
|
||||
`NEGATIVE_CLAIM_RULE` live once in `src/prompt-fragments.ts`,
|
||||
embedded into every system prompt (main code, default chat,
|
||||
subagent, built-in skills). Three near-identical copies
|
||||
collapsed; subagents gain the "don't assert absence without
|
||||
checking" guardrail they previously lacked.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **`run_skill` accepts decorated names.** The Skills index wrote
|
||||
entries like `- 🧬 explore`, and models copied the whole thing
|
||||
verbatim into `run_skill({name:"🧬 explore"})`. The index now
|
||||
uses a trailing `[🧬 subagent]` tag after the name, and
|
||||
`run_skill` normalizes inputs by stripping bracketed tags +
|
||||
leading emoji before lookup. Handles `"🧬 explore"`,
|
||||
`"[🧬 subagent] explore"`, `"explore [🧬 subagent]"`, etc.
|
||||
- **`edit_file` result no longer shown twice.** The interceptor's
|
||||
`applyNow` was pushing an info row, and the loop's tool event
|
||||
re-displayed the same text as a proper tool row. Dropped the info
|
||||
row push; the tool row alone carries the content.
|
||||
- **`run_command` / `run_background` descriptions teach their shell
|
||||
constraints upfront.** Explicit list of rejected operators
|
||||
(`&&`, `||`, `|`, `;`, `>`, `<`, `2>&1`), the `cd` doesn't-persist
|
||||
rule, a warning against unbounded-output commands (`netstat -ano`,
|
||||
`find /`), and concrete alternatives (`npm --prefix`, `cargo -C`,
|
||||
`git -C`). Models stop burning turns rediscovering these via
|
||||
error replies.
|
||||
|
||||
### Refactored (no behavior change)
|
||||
|
||||
- **App.tsx split** from 2931 → ~1980 lines by extracting
|
||||
`LiveRows.tsx`, `edit-history.ts`, `useEditHistory.ts`,
|
||||
`useCompletionPickers.ts`, `useSessionInfo.ts`, and
|
||||
`useSubagent.ts`. Every hook under 310 lines.
|
||||
- **slash.ts split** from 1786 → 20-line barrel. Types,
|
||||
SLASH_COMMANDS data + parse helpers, shared utility helpers, a
|
||||
handler registry (`dispatch.ts`), and 10 per-topic handler files
|
||||
all under `src/cli/ui/slash/`. Adding a command now means editing
|
||||
one handler file + one registry line.
|
||||
|
||||
### Docs
|
||||
|
||||
- **`docs/ARCHITECTURE.md` rewritten** for v0.6. The four pillars,
|
||||
current module layout (slash + handlers + hooks all reflected),
|
||||
design-evolution timeline replacing the stale roadmap,
|
||||
non-goals updated to call out "automatic cost escalation without
|
||||
user-visible announcement" as explicitly rejected.
|
||||
|
||||
## [0.5.24] — 2026-04-24
|
||||
|
||||
**Headline:** `reasonix code` gets a proper review gate, background
|
||||
process support, and aggressive context hygiene so long coding
|
||||
sessions stop bleeding money.
|
||||
|
||||
### Added
|
||||
|
||||
- **Edit-gate modes (review / auto)** — `edit_file` and `write_file`
|
||||
tool calls now route through a user gate. `review` (default) pops
|
||||
an `EditConfirm` modal with a scrollable diff + `y/n/a/A/Esc`
|
||||
keys; `auto` applies immediately and arms a 5-second undo banner.
|
||||
`Shift+Tab` cycles, `/mode` sets explicitly. Persisted to
|
||||
`~/.reasonix/config.json`.
|
||||
- **Session edit history** — every applied batch lands in an
|
||||
in-memory ring. `/history` lists them, `/show [id] [path]` dumps
|
||||
a stored diff (per-file when path given), `/undo [id] [path]`
|
||||
rolls back at any granularity (latest batch, specific batch,
|
||||
single file inside a batch). `u` keybind reaches back past the
|
||||
5-second banner as long as history has a non-undone entry.
|
||||
- **Background processes** — new `run_background` / `job_output` /
|
||||
`stop_job` / `list_jobs` tools for dev servers and watchers. Spawn
|
||||
returns after a ready-signal match (`listening on`, `Local:`,
|
||||
`compiled successfully`, …) or `waitSec` seconds. `/jobs` /
|
||||
`/kill <id>` / `/logs <id>` surface them to the user. Cleanup on
|
||||
SIGINT / SIGTERM / exit kills every child.
|
||||
- **Per-edit review modal (`src/cli/ui/EditConfirm.tsx`)** — diff
|
||||
viewport sized to terminal rows; `↑↓/j/k/Space/PgUp/PgDn/g/G`
|
||||
scroll a big diff in place. `a` applies rest of turn, `A` flips
|
||||
to AUTO for the session.
|
||||
- **Bottom mode status bar** — always-visible line above the prompt
|
||||
shows mode / pending count / Shift+Tab hint / running-jobs tag;
|
||||
flashes on mode change.
|
||||
- **Onboarding tip** — first `reasonix code` launch after upgrade
|
||||
posts the edit-gate keybindings once; suppressed after via the
|
||||
`editModeHintShown` flag.
|
||||
|
||||
### Changed
|
||||
|
||||
- **`read_file`** — adds `range:"A-B"` param (1-indexed, inclusive).
|
||||
Files longer than 200 lines with no scope return an auto-preview
|
||||
(head 80 + tail 40 + "N lines omitted" marker) instead of dumping
|
||||
everything. One `read_file` used to burn 6.5K tokens on a fat
|
||||
file; scoped reads cut that 3-5×.
|
||||
- **`directory_tree`** — default `maxDepth` 4 → 2; skips
|
||||
`node_modules`, `.git`, `dist`, `build`, `out`, `.next`, `.nuxt`,
|
||||
`target`, `.venv`, `venv`, `__pycache__`, `.pytest_cache`,
|
||||
`.mypy_cache`, `.cache`, `coverage` unless `include_deps:true`;
|
||||
collapses any directory past 50 children with a nudge toward
|
||||
`list_directory`.
|
||||
- **Auto-compact tool-call args** — after every `tool` response, the
|
||||
loop shrinks that call's `arguments` JSON if it exceeds 800
|
||||
tokens. Paths and short fields stay verbatim; long SEARCH /
|
||||
REPLACE / content strings get replaced with a `[…shrunk: N chars,
|
||||
M lines — tool already responded, see result]` marker. Cuts
|
||||
stale-args drag across every subsequent turn.
|
||||
- **`/compact`** — now covers both tool results (existing) and
|
||||
tool-call args (new) in one pass.
|
||||
- **`reasoningEffort` persistence** — `/effort high` now writes the
|
||||
choice to `~/.reasonix/config.json` and the loop picks it up at
|
||||
launch. Earlier versions silently reverted to `max` every relaunch.
|
||||
- **Prompt scope discipline** — code-mode prompt tells the model to
|
||||
stop after "run / start / launch" tasks instead of proactively
|
||||
refactoring, running tsc, or chasing unused imports.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **`run_background` confirmation path** — TUI now pops the shell
|
||||
confirm modal for `run_background` (not just `run_command`). A
|
||||
`kind` field on `pendingShell` routes approval to
|
||||
`JobRegistry.start()` so approving doesn't synchronously block on
|
||||
a dev server that never exits.
|
||||
- **`/kill` actually kills the tree** — Windows `taskkill /T /F`,
|
||||
POSIX `process.kill(-pid, …)` on a detached child. Earlier
|
||||
`SIGTERM` only killed the `npm.cmd` wrapper; `node → vite →
|
||||
esbuild` survived. `/kill` also posts a late "job N exit M" row
|
||||
when the stop resolves, so the user doesn't have to poll `/jobs`.
|
||||
|
||||
## [0.4.24] — 2026-04-22
|
||||
|
||||
**Headline:** `reasonix stats` is now a cross-session cost dashboard.
|
||||
|
||||
@@ -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,137 @@ command list.
|
||||
|
||||
---
|
||||
|
||||
## 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 +269,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,12 +309,14 @@ 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
|
||||
- `/effort high` — step down from the default `max` agent-class
|
||||
reasoning_effort for cheaper/faster turns on simple tasks.
|
||||
- `npx reasonix code --preset max` — v4-pro + 3-way self-consistency
|
||||
branching for gnarly refactors.
|
||||
- `npx reasonix code src/` — narrower sandbox (only `src/` is
|
||||
writable).
|
||||
@@ -182,7 +348,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 v0.5.21 · deepseek-v4-pro · harvest · max …`, the trailing
|
||||
`max` is the reasoning-effort badge — `/effort high` to step down).
|
||||
A quiet 24-hour background check against
|
||||
the npm registry surfaces a yellow `update: X.Y.Z` on the right side
|
||||
of the same row when a newer version has been published. No blocking,
|
||||
no nagging — the check runs once per day max and is silent on failure
|
||||
@@ -403,18 +571,25 @@ 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`) |
|
||||
| `/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 +643,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.
|
||||
|
||||
@@ -728,7 +903,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
|
||||
```
|
||||
|
||||
+836
@@ -0,0 +1,836 @@
|
||||
<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` 查看完整命令列表。
|
||||
|
||||
---
|
||||
|
||||
## 为什么选 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 max` —— v4-pro + 三路 self-consistency 分支,
|
||||
适合疑难重构。
|
||||
- `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 v0.5.21 · deepseek-v4-pro · harvest · 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 smart # 这次跑用 reasoner + R1 harvest
|
||||
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 <fast\|smart\|max>` | 一键预设(model + harvest + branch) |
|
||||
| `/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 <fast|smart|max> # 预设组合(model + harvest + branch)
|
||||
--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
|
||||
+1837
File diff suppressed because it is too large.
Load diff
+3636
File diff suppressed because it is too large.
Load diff
@@ -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>
|
||||
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 |
+406
@@ -0,0 +1,406 @@
|
||||
// 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": "v0.6 · 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": "v0.6 · 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 = [];
|
||||
|
||||
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 = 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);
|
||||
};
|
||||
|
||||
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() {
|
||||
applyLang(detectLang());
|
||||
wireLangButtons();
|
||||
wireCopyButtons();
|
||||
}
|
||||
|
||||
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,404 @@
|
||||
// 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.6.0 v4-flash REVIEW max … turn 1 · /help`
|
||||
// ──────────────────────────────────────────────────────────────────
|
||||
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">v0.6.0</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));
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
})();
|
||||
+5
-2
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "reasonix",
|
||||
"version": "0.5.16",
|
||||
"description": "DeepSeek-native agent framework: cache-first loop, R1 thought harvesting, tool-call repair.",
|
||||
"version": "0.12.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,6 +18,9 @@
|
||||
"files": [
|
||||
"dist",
|
||||
"data/deepseek-tokenizer.json.gz",
|
||||
"dashboard/index.html",
|
||||
"dashboard/app.js",
|
||||
"dashboard/app.css",
|
||||
"README.md",
|
||||
"LICENSE"
|
||||
],
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
// Minimal Ctrl+C probe. Usage: node scripts/ctrlc-probe.mjs
|
||||
// Reproduces the exact stdin setup Reasonix uses, then logs every byte
|
||||
// it sees and exits on \x03. Tells us whether the OS even delivers
|
||||
// Ctrl+C to a Node child on this terminal.
|
||||
|
||||
process.stdin.setRawMode(true);
|
||||
process.stdin.setEncoding("utf8");
|
||||
process.stdin.resume();
|
||||
|
||||
console.log("ctrl+c probe armed. press keys; ctrl+c should exit.");
|
||||
console.log("if ctrl+c does NOT exit, the byte never reaches Node on this terminal.\n");
|
||||
|
||||
process.stdin.on("data", (chunk) => {
|
||||
const s = String(chunk);
|
||||
for (const ch of s) {
|
||||
const code = ch.charCodeAt(0);
|
||||
process.stdout.write(`got byte: 0x${code.toString(16).padStart(2, "0")} (${JSON.stringify(ch)})\r\n`);
|
||||
if (ch === "\x03") {
|
||||
process.stdout.write("→ \\x03 detected, exiting.\r\n");
|
||||
process.exit(0);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
process.on("SIGINT", () => {
|
||||
process.stdout.write("→ SIGINT received, exiting.\r\n");
|
||||
process.exit(0);
|
||||
});
|
||||
@@ -0,0 +1,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);
|
||||
}
|
||||
});
|
||||
@@ -395,3 +395,204 @@ 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.
|
||||
|
||||
/**
|
||||
* Matches `@http://...` or `@https://...` at a word boundary. Captures the
|
||||
* URL minus the leading `@`. Trailing sentence punctuation is stripped
|
||||
* separately because URLs can legitimately contain `,` `.` `)` etc., and a
|
||||
* blanket trim would butcher real query strings.
|
||||
*/
|
||||
export const AT_URL_PATTERN = /(?<=^|\s)@(https?:\/\/\S+)/g;
|
||||
|
||||
/** Default cap on inlined URL body (chars). Matches DEFAULT_AT_MENTION_MAX_BYTES order-of-magnitude. */
|
||||
export const DEFAULT_AT_URL_MAX_CHARS = 32_000;
|
||||
|
||||
export interface AtUrlExpansion {
|
||||
/** The raw `@url` token as it appeared in the text. */
|
||||
token: string;
|
||||
/** Absolute URL (after trailing-punctuation strip). */
|
||||
url: string;
|
||||
/** True if content was inlined. False = skipped (reason in `skip`). */
|
||||
ok: boolean;
|
||||
/** Page title when extractable from `<title>`. */
|
||||
title?: string;
|
||||
/** Char count of the (post-truncation) inlined body. */
|
||||
chars?: number;
|
||||
/** True iff the original page exceeded `maxChars` and was clipped. */
|
||||
truncated?: boolean;
|
||||
/** Why the mention was skipped — set when ok=false. */
|
||||
skip?: "fetch-error" | "non-text" | "timeout" | "blocked";
|
||||
/** Free-form error message attached to skip outcomes. */
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export interface AtUrlOptions {
|
||||
/** Max chars of inlined body per URL. Default DEFAULT_AT_URL_MAX_CHARS. */
|
||||
maxChars?: number;
|
||||
/** Per-URL fetch timeout in ms. */
|
||||
timeoutMs?: number;
|
||||
/**
|
||||
* Override the fetcher — production wires `webFetch` from src/tools/web.ts.
|
||||
* Tests inject a stub so the suite stays offline.
|
||||
*/
|
||||
fetcher?: (
|
||||
url: string,
|
||||
opts: { maxChars?: number; timeoutMs?: number; signal?: AbortSignal },
|
||||
) => Promise<{ url: string; title?: string; text: string; truncated: boolean }>;
|
||||
/**
|
||||
* Optional cache the caller persists across calls (e.g. one map per
|
||||
* session). Hit-on-URL skips the fetch entirely. Omit for one-shot
|
||||
* tests that don't care about reuse.
|
||||
*/
|
||||
cache?: Map<string, AtUrlExpansion & { body?: string }>;
|
||||
/** Forward Esc/abort to the fetcher. */
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
/**
|
||||
* Expand `@http(s)://…` mentions in `text`. Returns the (possibly augmented)
|
||||
* text plus a per-URL report so the caller can surface fetched URLs in the
|
||||
* UI. Async because each URL hits the network; the file-mention sibling
|
||||
* (`expandAtMentions`) stays sync.
|
||||
*
|
||||
* Caching: when `opts.cache` is provided, a hit skips the network and
|
||||
* reuses the prior expansion (including its body). One Map per session is
|
||||
* the intended use — a long conversation that references the same URL
|
||||
* twice doesn't pay twice.
|
||||
*
|
||||
* Trailing-punctuation handling: a sentence like "see @https://x.com." has
|
||||
* the period stripped so the actual fetched URL is `https://x.com`. We
|
||||
* conservatively strip only `.,;:!?` and `)]}>` from the tail; anything
|
||||
* else is preserved so query strings survive intact.
|
||||
*/
|
||||
export async function expandAtUrls(
|
||||
text: string,
|
||||
opts: AtUrlOptions = {},
|
||||
): Promise<{ text: string; expansions: AtUrlExpansion[] }> {
|
||||
const maxChars = opts.maxChars ?? DEFAULT_AT_URL_MAX_CHARS;
|
||||
const fetcher = opts.fetcher;
|
||||
if (!fetcher) {
|
||||
throw new Error("expandAtUrls: fetcher option is required (wire src/tools/web.ts:webFetch)");
|
||||
}
|
||||
|
||||
// De-dupe by URL so the same `@https://x.com` referenced twice fetches once.
|
||||
const seen = new Map<string, AtUrlExpansion>();
|
||||
const bodies = new Map<string, string>();
|
||||
const order: string[] = [];
|
||||
|
||||
for (const match of text.matchAll(AT_URL_PATTERN)) {
|
||||
const rawUrl = match[1] ?? "";
|
||||
const url = stripUrlTail(rawUrl);
|
||||
if (!url) continue;
|
||||
if (seen.has(url)) continue;
|
||||
|
||||
const cached = opts.cache?.get(url);
|
||||
if (cached) {
|
||||
seen.set(url, cached);
|
||||
if (cached.body) bodies.set(url, cached.body);
|
||||
order.push(url);
|
||||
continue;
|
||||
}
|
||||
|
||||
let expansion: AtUrlExpansion;
|
||||
let body = "";
|
||||
try {
|
||||
const page = await fetcher(url, {
|
||||
maxChars,
|
||||
timeoutMs: opts.timeoutMs,
|
||||
signal: opts.signal,
|
||||
});
|
||||
body = page.text;
|
||||
expansion = {
|
||||
token: `@${url}`,
|
||||
url,
|
||||
ok: true,
|
||||
title: page.title,
|
||||
chars: body.length,
|
||||
truncated: page.truncated,
|
||||
};
|
||||
} catch (err) {
|
||||
const message = (err as Error).message ?? String(err);
|
||||
// Tag a few common shapes so the UI can hint at causes.
|
||||
let skip: AtUrlExpansion["skip"] = "fetch-error";
|
||||
if (/aborted|timeout/i.test(message)) skip = "timeout";
|
||||
else if (/40\d|forbidden|access denied|captcha/i.test(message)) skip = "blocked";
|
||||
expansion = {
|
||||
token: `@${url}`,
|
||||
url,
|
||||
ok: false,
|
||||
skip,
|
||||
error: message,
|
||||
};
|
||||
}
|
||||
seen.set(url, expansion);
|
||||
if (body) bodies.set(url, body);
|
||||
if (opts.cache) opts.cache.set(url, { ...expansion, body });
|
||||
order.push(url);
|
||||
}
|
||||
|
||||
if (seen.size === 0) return { text, expansions: [] };
|
||||
|
||||
const expansions = order.map((u) => seen.get(u)!).filter(Boolean);
|
||||
const blocks: string[] = [];
|
||||
for (const ex of expansions) {
|
||||
if (ex.ok) {
|
||||
const titleAttr = ex.title ? ` title="${escapeAttr(ex.title)}"` : "";
|
||||
const truncTag = ex.truncated ? ' truncated="true"' : "";
|
||||
const body = bodies.get(ex.url) ?? "";
|
||||
blocks.push(`<url href="${ex.url}"${titleAttr}${truncTag}>\n${body}\n</url>`);
|
||||
} else {
|
||||
const reasonAttr = ex.skip ?? "fetch-error";
|
||||
blocks.push(`<url href="${ex.url}" skipped="${reasonAttr}" />`);
|
||||
}
|
||||
}
|
||||
const augmented = `${text}\n\n[Referenced URLs]\n${blocks.join("\n\n")}`;
|
||||
return { text: augmented, expansions };
|
||||
}
|
||||
|
||||
/**
|
||||
* Strip trailing sentence punctuation from a URL captured at a word
|
||||
* boundary. `https://x.com.` → `https://x.com`; `https://x.com/?q=a)` →
|
||||
* `https://x.com/?q=a`. Conservative: only strips `.,;:!?` and unmatched
|
||||
* close-brackets `)]}>` from the very end. Internal punctuation in path /
|
||||
* query is preserved.
|
||||
*
|
||||
* Returns empty string if everything stripped — caller treats as "no URL."
|
||||
*/
|
||||
export function stripUrlTail(raw: string): string {
|
||||
let s = raw;
|
||||
while (s.length > 0) {
|
||||
const last = s[s.length - 1]!;
|
||||
if (".,;:!?".includes(last)) {
|
||||
s = s.slice(0, -1);
|
||||
continue;
|
||||
}
|
||||
if (")]}>".includes(last)) {
|
||||
// Only strip if the matching open bracket isn't elsewhere in the
|
||||
// URL — avoids butchering legitimate `(thing)` query fragments.
|
||||
const open = ({ ")": "(", "]": "[", "}": "{", ">": "<" } as const)[
|
||||
last as ")" | "]" | "}" | ">"
|
||||
];
|
||||
if (!s.includes(open)) {
|
||||
s = s.slice(0, -1);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
function escapeAttr(s: string): string {
|
||||
return s
|
||||
.replace(/"/g, """)
|
||||
.replace(/[\r\n]+/g, " ")
|
||||
.trim();
|
||||
}
|
||||
+72
-30
@@ -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";
|
||||
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 {
|
||||
@@ -51,7 +54,17 @@ 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). */
|
||||
@@ -101,39 +114,49 @@ function Root({
|
||||
}
|
||||
process.env.DEEPSEEK_API_KEY = key;
|
||||
|
||||
// KeystrokeProvider must wrap App from OUTSIDE — App.tsx itself
|
||||
// calls `useKeystroke` in its function body for global hotkeys
|
||||
// (Ctrl+C, Esc abort, Shift+Tab edit-mode cycle, @-mention picker,
|
||||
// slash-suggestion navigation). If the provider lives inside App's
|
||||
// render, `useContext(KeystrokeContext)` returns `null` at hook
|
||||
// call time and those handlers silently never subscribe.
|
||||
if (pending && appProps.session) {
|
||||
return (
|
||||
<SessionPicker
|
||||
sessionName={appProps.session}
|
||||
messageCount={pending.messageCount}
|
||||
lastActive={pending.lastActive}
|
||||
onChoose={(choice) => {
|
||||
if (choice === "new" || choice === "delete") {
|
||||
// Wipe the session file. "new" and "delete" do the same thing
|
||||
// at this step — the distinction is only in the picker's
|
||||
// wording. A future enhancement could archive on "new".
|
||||
rewriteSession(appProps.session!, []);
|
||||
}
|
||||
setPending(undefined);
|
||||
}}
|
||||
/>
|
||||
<KeystrokeProvider>
|
||||
<SessionPicker
|
||||
sessionName={appProps.session}
|
||||
messageCount={pending.messageCount}
|
||||
lastActive={pending.lastActive}
|
||||
onChoose={(choice) => {
|
||||
if (choice === "new" || choice === "delete") {
|
||||
// Wipe the session file. "new" and "delete" do the same thing
|
||||
// at this step — the distinction is only in the picker's
|
||||
// wording. A future enhancement could archive on "new".
|
||||
rewriteSession(appProps.session!, []);
|
||||
}
|
||||
setPending(undefined);
|
||||
}}
|
||||
/>
|
||||
</KeystrokeProvider>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<App
|
||||
model={appProps.model}
|
||||
system={appProps.system}
|
||||
transcript={appProps.transcript}
|
||||
harvest={appProps.harvest}
|
||||
branch={appProps.branch}
|
||||
session={appProps.session}
|
||||
tools={tools}
|
||||
mcpSpecs={mcpSpecs}
|
||||
mcpServers={mcpServers}
|
||||
progressSink={progressSink}
|
||||
codeMode={appProps.codeMode}
|
||||
/>
|
||||
<KeystrokeProvider>
|
||||
<App
|
||||
model={appProps.model}
|
||||
system={appProps.system}
|
||||
transcript={appProps.transcript}
|
||||
harvest={appProps.harvest}
|
||||
branch={appProps.branch}
|
||||
session={appProps.session}
|
||||
tools={tools}
|
||||
mcpSpecs={mcpSpecs}
|
||||
mcpServers={mcpServers}
|
||||
progressSink={progressSink}
|
||||
codeMode={appProps.codeMode}
|
||||
/>
|
||||
</KeystrokeProvider>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -170,7 +193,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 +225,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 +282,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 +305,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}
|
||||
|
||||
+68
-19
@@ -19,10 +19,13 @@
|
||||
*/
|
||||
|
||||
import { basename, resolve } from "node:path";
|
||||
import { loadProjectShellAllowed } from "../../config.js";
|
||||
import { loadEditMode, loadProjectShellAllowed } from "../../config.js";
|
||||
import { bootstrapSemanticSearchInCodeMode } from "../../index/semantic/tool.js";
|
||||
import { sanitizeName } from "../../session.js";
|
||||
import { ToolRegistry } from "../../tools.js";
|
||||
import { registerChoiceTool } from "../../tools/choice.js";
|
||||
import { registerFilesystemTools } from "../../tools/filesystem.js";
|
||||
import { JobRegistry } from "../../tools/jobs.js";
|
||||
import { registerMemoryTools } from "../../tools/memory.js";
|
||||
import { registerPlanTool } from "../../tools/plan.js";
|
||||
import { registerShellTools } from "../../tools/shell.js";
|
||||
@@ -65,43 +68,89 @@ 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),
|
||||
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,
|
||||
});
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
/**
|
||||
* `reasonix index` — build (or incrementally refresh) the project's
|
||||
* semantic search index.
|
||||
*
|
||||
* Usage:
|
||||
* reasonix index # incremental: only re-embeds changed files
|
||||
* reasonix index --rebuild # wipe + rebuild from scratch
|
||||
* reasonix index --model MODEL # override embedding model
|
||||
* reasonix index --dir PATH # index a different directory
|
||||
*
|
||||
* Output is rendered to stderr so piping the index to a script
|
||||
* (which we don't actually do today, but might) keeps stdout clean.
|
||||
*
|
||||
* On a TTY the progress writer paints `<spinner> <status> <elapsed>s`
|
||||
* on a single line, ticking every 120ms via setInterval — so the
|
||||
* line keeps animating even between onProgress events. That's the
|
||||
* load-bearing UX guarantee: builds that take 30+ seconds never
|
||||
* leave the user wondering whether the process is hung.
|
||||
*
|
||||
* On non-TTY (CI, piped logs) we emit one line per phase + a
|
||||
* periodic heartbeat. No \r tricks because they make logs unreadable.
|
||||
*/
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Braille spinner — same alphabet most CLI spinners use. Ten frames,
|
||||
* cycled at ~120ms each. Visually clear that the process is alive
|
||||
* even when no progress events fire (e.g. during phase transitions
|
||||
* or while waiting on Ollama's first model-load latency).
|
||||
*/
|
||||
const SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
|
||||
const SPINNER_INTERVAL_MS = 120;
|
||||
|
||||
function makeProgressWriter(tty: boolean): ProgressWriter {
|
||||
if (!tty) return makeNonTtyWriter();
|
||||
return makeTtyWriter();
|
||||
}
|
||||
|
||||
/**
|
||||
* Non-TTY writer — one line per phase transition + a heartbeat every
|
||||
* 50 embedded chunks. Keeps logs short and parseable while still
|
||||
* proving forward motion.
|
||||
*/
|
||||
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 */
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* TTY writer — paints `<spinner> <status> <elapsed>s` on a single
|
||||
* line via \r. The spinner ticks on a setInterval, INDEPENDENT of
|
||||
* onProgress events: even if the embedder hangs for 5 seconds on
|
||||
* the first model-load, the spinner keeps spinning so the user sees
|
||||
* the process is alive.
|
||||
*/
|
||||
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;
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -15,6 +15,7 @@ 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 +29,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();
|
||||
|
||||
@@ -9,6 +9,7 @@ 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 { ToolRegistry } from "../../tools.js";
|
||||
import { openTranscriptFile, recordFromLoopEvent, writeRecord } from "../../transcript.js";
|
||||
import { appendUsage } from "../../usage.js";
|
||||
@@ -86,12 +87,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`,
|
||||
);
|
||||
|
||||
@@ -154,18 +154,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 +179,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(" ");
|
||||
|
||||
+76
-13
@@ -1,10 +1,13 @@
|
||||
import { Command } from "commander";
|
||||
import { readConfig } from "../config.js";
|
||||
import { VERSION } from "../index.js";
|
||||
import { ESCALATION_CONTRACT } from "../prompt-fragments.js";
|
||||
import { listSessions } from "../session.js";
|
||||
import { applyMemoryStack } from "../user-memory.js";
|
||||
import { chatCommand } from "./commands/chat.js";
|
||||
import { codeCommand } from "./commands/code.js";
|
||||
import { diffCommand } from "./commands/diff.js";
|
||||
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 +17,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 +31,52 @@ 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}`;
|
||||
|
||||
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 +90,16 @@ 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. Model proposes SEARCH/REPLACE blocks; Reasonix applies them to disk. Use /preset max or /pro to escalate to v4-pro on hard tasks.",
|
||||
)
|
||||
.option("-m, --model <id>", "Override default reasoner model")
|
||||
.option("-m, --model <id>", "Override default model (v4-flash)")
|
||||
.option("--no-session", "Disable session persistence for this run")
|
||||
.option("-r, --resume", "Skip the session picker — always continue prior messages")
|
||||
.option("-n, --new", "Skip the session picker — always wipe prior messages and start fresh")
|
||||
.option("--transcript <path>", "Write a JSONL transcript to this path")
|
||||
.option(
|
||||
"--harvest",
|
||||
"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).",
|
||||
)
|
||||
.action(async (dir: string | undefined, opts) => {
|
||||
await codeCommand({
|
||||
@@ -99,20 +121,24 @@ program
|
||||
.option("--transcript <path>", "Write a JSONL transcript to this path")
|
||||
.option(
|
||||
"--preset <name>",
|
||||
"Bundle of model + harvest + branch. One of: fast, smart, max. Overrides config.preset.",
|
||||
"Model + effort bundle. One of: fast (flash·high), smart (flash·max, default), max (pro·max). Overrides config.preset.",
|
||||
)
|
||||
.option(
|
||||
"--harvest",
|
||||
"Extract typed plan state from R1 reasoning (Pillar 2). Overrides preset's harvest setting.",
|
||||
"Opt-in Pillar-2 plan-state extraction. Off by default — no preset enables it.",
|
||||
)
|
||||
.option(
|
||||
"--branch <n>",
|
||||
"Self-consistency: run N parallel samples per turn and pick the most confident (disables streaming; enables harvest)",
|
||||
"Self-consistency: run N parallel samples per turn (N× cost). Manual only — never auto-enabled.",
|
||||
(v) => Number.parseInt(v, 10),
|
||||
)
|
||||
.option("--session <name>", "Use a named session (default: from config, usually 'default').")
|
||||
.option("--no-session", "Disable session persistence for this run (ephemeral chat)")
|
||||
.option("-r, --resume", "Skip the session picker — always continue prior messages")
|
||||
.option(
|
||||
"-c, --continue",
|
||||
"Resume the most-recently-used session (any name) without showing the picker.",
|
||||
)
|
||||
.option("-n, --new", "Skip the session picker — always wipe prior messages and start fresh")
|
||||
.option(
|
||||
"--mcp <spec>",
|
||||
@@ -135,16 +161,28 @@ program
|
||||
preset: opts.preset,
|
||||
noConfig: opts.config === false,
|
||||
});
|
||||
// `-c` is "newest-touched session" + auto-resume; `-r` is "this
|
||||
// session's prior messages, even if you also passed --session".
|
||||
// When both are set we prefer the explicit `--session` + `-r`
|
||||
// (more specific input wins). `-c` only kicks in if `-r` wasn't.
|
||||
const continueOpts = opts.resume
|
||||
? { session: defaults.session, forceResume: true }
|
||||
: resolveContinueFlag(
|
||||
opts.continue,
|
||||
defaults.session,
|
||||
() => listSessions()[0],
|
||||
(msg) => process.stderr.write(`${msg}\n`),
|
||||
);
|
||||
await chatCommand({
|
||||
model: defaults.model,
|
||||
system: applyMemoryStack(opts.system, process.cwd()),
|
||||
transcript: opts.transcript,
|
||||
harvest: defaults.harvest,
|
||||
branch: defaults.branch,
|
||||
session: defaults.session,
|
||||
session: continueOpts.session,
|
||||
mcp: defaults.mcp,
|
||||
mcpPrefix: opts.mcpPrefix,
|
||||
forceResume: !!opts.resume,
|
||||
forceResume: continueOpts.forceResume,
|
||||
forceNew: !!opts.new,
|
||||
});
|
||||
});
|
||||
@@ -290,6 +328,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);
|
||||
|
||||
+42
-6
@@ -6,7 +6,7 @@
|
||||
* 1. Explicit per-setting CLI flag (`--model`, `--harvest`, `--branch`, `--mcp`)
|
||||
* 2. Explicit `--preset <name>` CLI flag
|
||||
* 3. `config.preset` from `~/.reasonix/config.json` (set by `reasonix setup`)
|
||||
* 4. Hardcoded "fast" preset defaults
|
||||
* 4. Hardcoded "smart" preset defaults (flash + effort=max)
|
||||
*
|
||||
* Keeping this logic in one place — rather than duplicating across
|
||||
* `chat` and `run` — means the precedence rule only lives in one unit
|
||||
@@ -14,10 +14,11 @@
|
||||
*/
|
||||
|
||||
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 +42,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 +57,7 @@ export function resolveDefaults(flags: RawCliFlags): ResolvedDefaults {
|
||||
|
||||
const session = resolveSession(flags.session, cfg.session);
|
||||
|
||||
return { model, harvest, branch, mcp, session };
|
||||
return { model, reasoningEffort, harvest, branch, mcp, session };
|
||||
}
|
||||
|
||||
function pickPreset(
|
||||
@@ -64,11 +66,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 +98,28 @@ function resolveSession(
|
||||
if (typeof configSession === "string" && configSession.length > 0) return configSession;
|
||||
return "default";
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the `-c/--continue` flag into a concrete `(session, forceResume)`
|
||||
* pair. When the flag is set we ask `getLatestSession` for the most-recently-
|
||||
* touched saved session and skip the picker; if nothing is on disk we
|
||||
* fall back silently to `fallbackSession` after emitting a single warning
|
||||
* line via `warn`.
|
||||
*
|
||||
* Pure & testable: callers inject the fs lookup. `cli/index.ts` plugs in
|
||||
* `() => listSessions()[0]`; tests pass a deterministic stub.
|
||||
*/
|
||||
export function resolveContinueFlag(
|
||||
flag: boolean | undefined,
|
||||
fallbackSession: string | undefined,
|
||||
getLatestSession: () => { name: string } | undefined,
|
||||
warn: (msg: string) => void = () => {},
|
||||
): { session: string | undefined; forceResume: boolean } {
|
||||
if (!flag) return { session: fallbackSession, forceResume: false };
|
||||
const latest = getLatestSession();
|
||||
if (!latest) {
|
||||
warn("▸ -c/--continue: no saved sessions yet — starting a fresh one.");
|
||||
return { session: fallbackSession, forceResume: false };
|
||||
}
|
||||
return { session: latest.name, forceResume: true };
|
||||
}
|
||||
+2746
-825
File diff suppressed because it is too large.
Load diff
@@ -30,7 +30,7 @@ export function AtMentionSuggestions({
|
||||
if (matches === null) return null;
|
||||
if (matches.length === 0) {
|
||||
return (
|
||||
<Box paddingX={1}>
|
||||
<Box paddingX={1} marginTop={1}>
|
||||
<Text color="yellow">no files match "@{query}"</Text>
|
||||
<Text dimColor>
|
||||
{" "}
|
||||
@@ -47,7 +47,7 @@ export function AtMentionSuggestions({
|
||||
const hiddenAbove = windowStart;
|
||||
const hiddenBelow = total - windowStart - shown.length;
|
||||
return (
|
||||
<Box flexDirection="column" paddingX={1}>
|
||||
<Box flexDirection="column" paddingX={1} marginTop={1}>
|
||||
{hiddenAbove > 0 ? <Text dimColor> ↑ {hiddenAbove} more above</Text> : null}
|
||||
{shown.map((path, i) => (
|
||||
<FileRow key={path} path={path} isSelected={windowStart + i === selectedIndex} />
|
||||
@@ -59,7 +59,6 @@ export function AtMentionSuggestions({
|
||||
}
|
||||
|
||||
function FileRow({ path, isSelected }: { path: string; isSelected: boolean }) {
|
||||
const marker = isSelected ? "▸" : " ";
|
||||
// Split the path so the basename visually pops — same dropdown
|
||||
// affordance as VS Code's Quick Open.
|
||||
const slash = path.lastIndexOf("/");
|
||||
@@ -68,19 +67,16 @@ function FileRow({ path, isSelected }: { path: string; isSelected: boolean }) {
|
||||
if (isSelected) {
|
||||
return (
|
||||
<Box>
|
||||
<Text bold color="cyan">
|
||||
{marker} {base}
|
||||
<Text backgroundColor="#67e8f9" color="black" bold>
|
||||
{` ▸ ${base}${dir ? ` ${dir}` : ""} `}
|
||||
</Text>
|
||||
<Text color="cyan">{dir ? ` ${dir}` : ""}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Box>
|
||||
<Text dimColor>
|
||||
{marker} {base}
|
||||
{dir ? ` ${dir}` : ""}
|
||||
</Text>
|
||||
<Text color="#94a3b8">{` ${base}`}</Text>
|
||||
{dir ? <Text dimColor>{` ${dir}`}</Text> : null}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
/**
|
||||
* Modal picker shown when the model calls `ask_choice`. Renders the
|
||||
* question + 2–4 option rows (title + dimmed summary) + an optional
|
||||
* "Let me type my own answer" escape hatch when `allowCustom` is true.
|
||||
*
|
||||
* The escape hatch matters because DeepSeek flash sometimes misframes
|
||||
* the alternatives — none actually fit the user's intent. Without a
|
||||
* bailout the user would have to cancel, type feedback, and wait for
|
||||
* another round-trip. With it they just type and ship.
|
||||
*
|
||||
* Border color: magenta — deliberately distinct from cyan (plan),
|
||||
* green (checkpoint), red (shell) so the user's eye learns the modes
|
||||
* without reading headers.
|
||||
*/
|
||||
|
||||
import { Box } from "ink";
|
||||
import React from "react";
|
||||
import type { ChoiceOption } from "../../tools/choice.js";
|
||||
import { ModalCard } from "./ModalCard.js";
|
||||
import { SingleSelect } from "./Select.js";
|
||||
|
||||
export type ChoiceConfirmChoice =
|
||||
| { kind: "pick"; optionId: string }
|
||||
| { kind: "custom" }
|
||||
| { kind: "cancel" };
|
||||
|
||||
export interface ChoiceConfirmProps {
|
||||
question: string;
|
||||
options: ChoiceOption[];
|
||||
allowCustom: boolean;
|
||||
onChoose: (choice: ChoiceConfirmChoice) => void;
|
||||
}
|
||||
|
||||
const CUSTOM_VALUE = "__custom__";
|
||||
const CANCEL_VALUE = "__cancel__";
|
||||
|
||||
function ChoiceConfirmInner({ question, options, allowCustom, onChoose }: ChoiceConfirmProps) {
|
||||
const items: Array<{ value: string; label: string; hint?: string }> = options.map((opt) => ({
|
||||
value: opt.id,
|
||||
label: `${opt.id} · ${opt.title}`,
|
||||
hint: opt.summary,
|
||||
}));
|
||||
if (allowCustom) {
|
||||
items.push({
|
||||
value: CUSTOM_VALUE,
|
||||
label: "Let me type my own answer",
|
||||
hint: "None of the above fits — type a free-form reply. The model reads it verbatim.",
|
||||
});
|
||||
}
|
||||
items.push({
|
||||
value: CANCEL_VALUE,
|
||||
label: "Cancel — drop the question",
|
||||
hint: "Model stops and asks what you want instead.",
|
||||
});
|
||||
|
||||
return (
|
||||
<ModalCard accent="#f0abfc" icon="🔀" title="model wants you to pick" subtitle={question}>
|
||||
<Box>
|
||||
<SingleSelect
|
||||
initialValue={options[0]?.id}
|
||||
items={items}
|
||||
onSubmit={(v) => {
|
||||
if (v === CUSTOM_VALUE) onChoose({ kind: "custom" });
|
||||
else if (v === CANCEL_VALUE) onChoose({ kind: "cancel" });
|
||||
else onChoose({ kind: "pick", optionId: v });
|
||||
}}
|
||||
onCancel={() => onChoose({ kind: "cancel" })}
|
||||
footer="[↑↓] navigate · [Enter] select · [Esc] cancel"
|
||||
/>
|
||||
</Box>
|
||||
</ModalCard>
|
||||
);
|
||||
}
|
||||
|
||||
export const ChoiceConfirm = React.memo(ChoiceConfirmInner);
|
||||
@@ -0,0 +1,214 @@
|
||||
import { Box, Text, useStdout } from "ink";
|
||||
import React, { useMemo, useState } from "react";
|
||||
import { formatEditBlockDiff } from "../../code/diff-preview.js";
|
||||
import type { EditBlock } from "../../code/edit-blocks.js";
|
||||
import { ModalCard } from "./ModalCard.js";
|
||||
import { useKeystroke } from "./keystroke-context.js";
|
||||
|
||||
/**
|
||||
* Choice surfaced to the interceptor when the user resolves the modal:
|
||||
* - `apply` → apply this edit, keep prompting on next.
|
||||
* - `reject` → tell the model the user refused; do NOT
|
||||
* retry the same edit.
|
||||
* - `apply-rest-of-turn` → apply this edit AND every remaining edit
|
||||
* this turn without further prompts. Resets
|
||||
* at the next user turn.
|
||||
* - `flip-to-auto` → apply this edit + persistently switch the
|
||||
* session to AUTO mode (survives restart).
|
||||
*/
|
||||
export type EditReviewChoice = "apply" | "reject" | "apply-rest-of-turn" | "flip-to-auto";
|
||||
|
||||
export interface EditConfirmProps {
|
||||
block: EditBlock;
|
||||
onChoose: (choice: EditReviewChoice) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Overhead reserved for non-diff UI inside the modal: border (2),
|
||||
* title (1), separator (1), file-header (1), scroll-indicator rows
|
||||
* (up to 2), footer + margin (3), plus breathing room for the host
|
||||
* TUI's chrome above (stats panel ≈ 4, historical live rows, prompt
|
||||
* input ≈ 2). 18 rows absorbed before the diff gets any budget.
|
||||
*/
|
||||
const MODAL_OVERHEAD_ROWS = 18;
|
||||
|
||||
/**
|
||||
* Absolute floor on the diff viewport. If the terminal is absurdly
|
||||
* short (< 26 rows total) we still show at least 8 diff lines so the
|
||||
* modal is usable; the user scrolls more aggressively but can't end up
|
||||
* with a zero-height viewport.
|
||||
*/
|
||||
const MIN_DIFF_ROWS = 8;
|
||||
|
||||
/**
|
||||
* Modal-style approval for a single model-proposed file edit.
|
||||
*
|
||||
* Why per-edit instead of end-of-turn batch: users reported they can't
|
||||
* tell if the model is about to make one small change or seven sprawling
|
||||
* ones until the turn is over. Per-edit prompts let the user intervene
|
||||
* early — reject a bad direction before the model builds on it, or
|
||||
* approve the first few and hit `a` to let the rest land.
|
||||
*
|
||||
* Diff viewport: we compute the UNCAPPED diff once, then slice to a
|
||||
* height budget derived from terminal rows. Large diffs (100+ lines)
|
||||
* are scrollable via j/k/↑/↓/Space/PgUp/PgDn/g/G — the user can page
|
||||
* through the whole change before deciding, and the action footer
|
||||
* never scrolls off the bottom. Before the scroll support a 97-line
|
||||
* scene.ts diff truncated at "… 67 more …" which was unreviewable.
|
||||
*/
|
||||
export function EditConfirm({ block, onChoose }: EditConfirmProps) {
|
||||
const { stdout } = useStdout();
|
||||
const rows = stdout?.rows ?? 40;
|
||||
const budget = Math.max(MIN_DIFF_ROWS, rows - MODAL_OVERHEAD_ROWS);
|
||||
|
||||
// Full diff — maxLines pushed high enough that the diff-preview
|
||||
// renderer never inserts its own truncation marker. Context trimming
|
||||
// (contextLines) still applies for tight scan.
|
||||
const allLines = useMemo(
|
||||
() => formatEditBlockDiff(block, { contextLines: 2, maxLines: 100_000, indent: " " }),
|
||||
[block],
|
||||
);
|
||||
|
||||
const [scroll, setScroll] = useState(0);
|
||||
const maxScroll = Math.max(0, allLines.length - budget);
|
||||
// Clamp scroll if budget shrinks (terminal resized) after a previous
|
||||
// keypress drove the offset past the new ceiling.
|
||||
const effectiveScroll = Math.min(scroll, maxScroll);
|
||||
|
||||
useKeystroke((ev) => {
|
||||
if (ev.paste) return;
|
||||
const input = ev.input;
|
||||
const key = ev;
|
||||
// Action keys first — decision wins over scroll so a user who
|
||||
// hammered PgDn can still hit `y` at the end without a stray
|
||||
// extra scroll.
|
||||
if (key.return || input === "y") {
|
||||
onChoose("apply");
|
||||
return;
|
||||
}
|
||||
if (input === "n") {
|
||||
onChoose("reject");
|
||||
return;
|
||||
}
|
||||
if (input === "a") {
|
||||
onChoose("apply-rest-of-turn");
|
||||
return;
|
||||
}
|
||||
if (input === "A") {
|
||||
onChoose("flip-to-auto");
|
||||
return;
|
||||
}
|
||||
// Scroll navigation — vim-ish (j/k) and emacs-ish (arrows) both
|
||||
// work. Space for "next page" is the pager convention.
|
||||
if (key.downArrow || input === "j") {
|
||||
setScroll((s) => Math.min(maxScroll, s + 1));
|
||||
return;
|
||||
}
|
||||
if (key.upArrow || input === "k") {
|
||||
setScroll((s) => Math.max(0, s - 1));
|
||||
return;
|
||||
}
|
||||
if (key.pageDown || input === " " || input === "f") {
|
||||
setScroll((s) => Math.min(maxScroll, s + Math.max(1, budget - 2)));
|
||||
return;
|
||||
}
|
||||
if (key.pageUp || input === "b") {
|
||||
setScroll((s) => Math.max(0, s - Math.max(1, budget - 2)));
|
||||
return;
|
||||
}
|
||||
if (input === "g") {
|
||||
setScroll(0);
|
||||
return;
|
||||
}
|
||||
if (input === "G") {
|
||||
setScroll(maxScroll);
|
||||
return;
|
||||
}
|
||||
// Esc falls through to the parent abort handler.
|
||||
});
|
||||
|
||||
const isNew = block.search === "";
|
||||
const removed = isNew ? 0 : (block.search.match(/\n/g)?.length ?? 0) + 1;
|
||||
const added = block.replace === "" ? 0 : (block.replace.match(/\n/g)?.length ?? 0) + 1;
|
||||
const tag = isNew ? "NEW" : "EDIT";
|
||||
|
||||
const visibleLines = allLines.slice(effectiveScroll, effectiveScroll + budget);
|
||||
const hiddenAbove = effectiveScroll;
|
||||
const hiddenBelow = Math.max(0, allLines.length - effectiveScroll - budget);
|
||||
const totalLines = allLines.length;
|
||||
const showScrollHud = hiddenAbove + hiddenBelow > 0;
|
||||
|
||||
const subtitleParts = [`-${removed} +${added} lines`];
|
||||
if (showScrollHud) {
|
||||
subtitleParts.push(
|
||||
`viewing ${effectiveScroll + 1}-${effectiveScroll + visibleLines.length}/${totalLines}`,
|
||||
);
|
||||
}
|
||||
return (
|
||||
<ModalCard
|
||||
accent={isNew ? "#86efac" : "#fcd34d"}
|
||||
icon={isNew ? "✚" : "✎"}
|
||||
title={`${tag} ${block.path}`}
|
||||
subtitle={subtitleParts.join(" · ")}
|
||||
>
|
||||
{hiddenAbove > 0 ? (
|
||||
<Text
|
||||
dimColor
|
||||
>{` ↑ ${hiddenAbove} line${hiddenAbove === 1 ? "" : "s"} above (↑/k or PgUp)`}</Text>
|
||||
) : null}
|
||||
<Box flexDirection="column">
|
||||
{visibleLines.map((line, i) => {
|
||||
const trimmed = line.trimStart();
|
||||
const color = trimmed.startsWith("+")
|
||||
? "#4ade80"
|
||||
: trimmed.startsWith("-")
|
||||
? "#f87171"
|
||||
: undefined;
|
||||
const dim = !color;
|
||||
return (
|
||||
<Text
|
||||
// Stable-enough: slice only shifts by scroll; React keys only
|
||||
// need to be unique within the current render.
|
||||
// biome-ignore lint/suspicious/noArrayIndexKey: list is static per render
|
||||
key={`diff-${effectiveScroll}-${i}`}
|
||||
color={color}
|
||||
dimColor={dim}
|
||||
>
|
||||
{line}
|
||||
</Text>
|
||||
);
|
||||
})}
|
||||
</Box>
|
||||
{hiddenBelow > 0 ? (
|
||||
<Text
|
||||
dimColor
|
||||
>{` ↓ ${hiddenBelow} line${hiddenBelow === 1 ? "" : "s"} below (↓/j or Space/PgDn)`}</Text>
|
||||
) : null}
|
||||
<Box marginTop={1}>
|
||||
<Text dimColor>
|
||||
{"["}
|
||||
<Text color="#67e8f9" bold>
|
||||
y
|
||||
</Text>
|
||||
{"/Enter] apply · ["}
|
||||
<Text color="#67e8f9" bold>
|
||||
n
|
||||
</Text>
|
||||
{"] reject · ["}
|
||||
<Text color="#67e8f9" bold>
|
||||
a
|
||||
</Text>
|
||||
{"] apply rest · ["}
|
||||
<Text color="#67e8f9" bold>
|
||||
A
|
||||
</Text>
|
||||
{"] flip AUTO · ["}
|
||||
<Text color="#67e8f9" bold>
|
||||
↑↓/Space
|
||||
</Text>
|
||||
{"] scroll · [Esc] abort"}
|
||||
</Text>
|
||||
</Box>
|
||||
</ModalCard>
|
||||
);
|
||||
}
|
||||
+555
-170
@@ -3,11 +3,50 @@ import React from "react";
|
||||
import { type TypedPlanState, isPlanStateEmpty } from "../../harvest.js";
|
||||
import type { BranchProgress, BranchSummary } from "../../loop.js";
|
||||
import type { TurnStats } from "../../telemetry.js";
|
||||
import type { PlanStep } from "../../tools/plan.js";
|
||||
import { PlanStateBlock } from "./PlanStateBlock.js";
|
||||
import { PlanStepList } from "./PlanStepList.js";
|
||||
import { Markdown } from "./markdown.js";
|
||||
import { COLOR, gradientCells } from "./theme.js";
|
||||
import { useElapsedSeconds, useTick } from "./ticker.js";
|
||||
import { formatDuration, summarizeToolResult } from "./tool-summary.js";
|
||||
|
||||
export type DisplayRole = "user" | "assistant" | "tool" | "system" | "error" | "info" | "warning";
|
||||
export type DisplayRole =
|
||||
| "user"
|
||||
| "assistant"
|
||||
| "tool"
|
||||
| "system"
|
||||
| "error"
|
||||
| "info"
|
||||
| "warning"
|
||||
/**
|
||||
* A plan body pushed to scrollback when the model calls `submit_plan`.
|
||||
* Rendered through the full markdown pipeline (not truncated), so the
|
||||
* user reads the whole thing in the permanent Static log and the
|
||||
* PlanConfirm modal below it stays a tight picker.
|
||||
*/
|
||||
| "plan"
|
||||
/**
|
||||
* One step of an approved plan ticked off via `mark_step_complete`.
|
||||
* Rendered as a compact `✓ step-id · title — result (N/M)` row so
|
||||
* the user can glance at the scrollback and see how far along the
|
||||
* execution is without scrolling through every tool call.
|
||||
*/
|
||||
| "step-progress"
|
||||
/**
|
||||
* Pushed once at session startup when an existing plan was loaded
|
||||
* from disk. Renders as a bordered box with the step list and
|
||||
* progress so the user sees exactly where they left off — much
|
||||
* more useful than the bare "2/5 done" info line it replaced.
|
||||
*/
|
||||
| "plan-resumed"
|
||||
/**
|
||||
* Read-only snapshot of an archived (completed) plan, pushed by
|
||||
* the `/replay` slash. Visually distinct from `plan-resumed` —
|
||||
* dim border + ⏪ icon — so the user immediately sees this is
|
||||
* historical, not the active plan.
|
||||
*/
|
||||
| "plan-replay";
|
||||
|
||||
export interface DisplayEvent {
|
||||
id: string;
|
||||
@@ -18,10 +57,66 @@ export interface DisplayEvent {
|
||||
branch?: BranchSummary;
|
||||
branchProgress?: BranchProgress;
|
||||
toolName?: string;
|
||||
/**
|
||||
* Raw JSON args the model passed to the tool. Carried through so the
|
||||
* web dashboard's snapshot endpoint can reconstruct the same
|
||||
* tool-specific rendering (edit_file diff, write_file content, etc)
|
||||
* the live SSE channel already provides. Not used by the Ink TUI
|
||||
* directly — it shows the args via OngoingToolRow / tool-summary.
|
||||
*/
|
||||
toolArgs?: string;
|
||||
/**
|
||||
* 1-based position in the session's tool-call history. Rendered as a
|
||||
* dim `/tool N` suffix on compact rows so the user can quickly jump
|
||||
* to the full output via the existing `/tool` slash command.
|
||||
*/
|
||||
toolIndex?: number;
|
||||
/** Wall-clock duration in ms between tool_start and result. */
|
||||
durationMs?: number;
|
||||
stats?: TurnStats;
|
||||
repair?: string;
|
||||
streaming?: boolean;
|
||||
toolCallBuild?: { name: string; chars: number };
|
||||
toolCallBuild?: { name: string; chars: number; index?: number; readyCount?: number };
|
||||
/**
|
||||
* Populated on `step-progress` rows: the step id, optional title,
|
||||
* completion counter, and optional notes. Rendered into the compact
|
||||
* single-row layout — no other role reads these fields.
|
||||
*/
|
||||
stepProgress?: {
|
||||
stepId: string;
|
||||
title?: string;
|
||||
completed: number;
|
||||
total: number;
|
||||
notes?: string;
|
||||
};
|
||||
/**
|
||||
* Populated on `plan-resumed` rows: the structured plan loaded from
|
||||
* disk + the set of step ids the user had already completed +
|
||||
* a relative-time hint for the header. Rendered as a bordered
|
||||
* snapshot so the user picks back up immediately.
|
||||
*/
|
||||
resumedPlan?: {
|
||||
steps: PlanStep[];
|
||||
completedStepIds: string[];
|
||||
relativeTime: string;
|
||||
/** Optional human-friendly title; rendered in the banner header when set. */
|
||||
summary?: string;
|
||||
};
|
||||
/**
|
||||
* Populated on `plan-replay` rows: the archived plan plus enough
|
||||
* navigation context (index / total) for the user to know where
|
||||
* they are in the archive history.
|
||||
*/
|
||||
replayPlan?: {
|
||||
summary?: string;
|
||||
body?: string;
|
||||
steps: PlanStep[];
|
||||
completedStepIds: string[];
|
||||
relativeTime: string;
|
||||
archiveBasename: string;
|
||||
index: number;
|
||||
total: number;
|
||||
};
|
||||
/**
|
||||
* Render a thin horizontal rule above this event. Used to mark
|
||||
* "start of a new user turn" so long scrollbacks get visual
|
||||
@@ -63,6 +158,34 @@ function RoleGlyph({
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Solid-background pill for tool names. Mirrors the StatsPanel's mode
|
||||
* pills so the visual language stays consistent across the screen:
|
||||
* status (auto/review/plan), tool name, model. Status drives the
|
||||
* background color — yellow for ok/in-flight, red for errors — so a
|
||||
* scrollback full of tool dispatches reads at a glance.
|
||||
*/
|
||||
function ToolPill({ label, status }: { label: string; status: "ok" | "err" }) {
|
||||
const bg = status === "err" ? "red" : "yellow";
|
||||
const symbol = status === "err" ? "✗" : "✓";
|
||||
return (
|
||||
<Text backgroundColor={bg} color="black" bold>
|
||||
{` ${symbol} ${label} `}
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Pad continuation lines so wrapped multi-line text aligns under the
|
||||
* glyph indent instead of jumping back to column 0. Header is `glyph
|
||||
* (1 col) + " " (2 cols)`, so subsequent lines need 3 leading spaces
|
||||
* to land under the body's first character.
|
||||
*/
|
||||
function indentContinuationLines(text: string): string {
|
||||
if (!text.includes("\n")) return text;
|
||||
return text.split("\n").join("\n ");
|
||||
}
|
||||
|
||||
export const EventRow = React.memo(function EventRow({
|
||||
event,
|
||||
projectRoot,
|
||||
@@ -72,12 +195,23 @@ export const EventRow = React.memo(function EventRow({
|
||||
}) {
|
||||
if (event.role === "user") {
|
||||
return (
|
||||
<Box marginTop={event.leadSeparator ? 1 : 0}>
|
||||
<RoleGlyph glyph={ROLE_GLYPH.user} color="cyan" />
|
||||
<Text>
|
||||
{" "}
|
||||
{event.text}
|
||||
</Text>
|
||||
<Box flexDirection="column">
|
||||
{event.leadSeparator ? <TurnSeparator /> : null}
|
||||
<Box>
|
||||
<RoleGlyph glyph={ROLE_GLYPH.user} color="cyan" />
|
||||
<Text>{" "}</Text>
|
||||
<Box
|
||||
flexDirection="column"
|
||||
borderStyle="single"
|
||||
borderTop={false}
|
||||
borderRight={false}
|
||||
borderBottom={false}
|
||||
borderColor={COLOR.user}
|
||||
paddingLeft={1}
|
||||
>
|
||||
<Text>{indentContinuationLines(event.text)}</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -87,9 +221,25 @@ export const EventRow = React.memo(function EventRow({
|
||||
<Box flexDirection="column" marginTop={1}>
|
||||
<Box>
|
||||
<RoleGlyph glyph={ROLE_GLYPH.assistant} color="green" />
|
||||
{event.stats ? <Text dimColor>{` ${event.stats.model}`}</Text> : null}
|
||||
{event.stats ? (
|
||||
<>
|
||||
<Text>{" "}</Text>
|
||||
<Text backgroundColor={COLOR.assistant} color="black" bold>
|
||||
{` ${event.stats.model.replace(/^deepseek-/, "")} `}
|
||||
</Text>
|
||||
</>
|
||||
) : null}
|
||||
</Box>
|
||||
<Box flexDirection="column" paddingLeft={2} marginTop={1}>
|
||||
<Box
|
||||
flexDirection="column"
|
||||
marginTop={1}
|
||||
borderStyle="single"
|
||||
borderTop={false}
|
||||
borderRight={false}
|
||||
borderBottom={false}
|
||||
borderColor={COLOR.assistant}
|
||||
paddingLeft={1}
|
||||
>
|
||||
{event.branch ? <BranchBlock branch={event.branch} /> : null}
|
||||
{event.reasoning ? <ReasoningBlock reasoning={event.reasoning} /> : null}
|
||||
{!isPlanStateEmpty(event.planState) ? (
|
||||
@@ -101,72 +251,243 @@ export const EventRow = React.memo(function EventRow({
|
||||
<Text dimColor>(no content)</Text>
|
||||
)}
|
||||
{event.stats ? <StatsLine stats={event.stats} /> : null}
|
||||
{event.repair ? <Text color="magenta">{event.repair}</Text> : null}
|
||||
{event.repair ? <Text color={COLOR.accent}>{event.repair}</Text> : null}
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
if (event.role === "tool") {
|
||||
// `flattenMcpResult` prefixes server-side errors with "ERROR: ".
|
||||
// Render the tool glyph in red with a ✗ direction marker so the
|
||||
// failure mode is unmissable — it's the signal the model needs
|
||||
// most for its next decision.
|
||||
const isError = event.text.startsWith("ERROR:");
|
||||
const color = isError ? "red" : "yellow";
|
||||
const glyph = isError ? ROLE_GLYPH.toolErr : ROLE_GLYPH.toolOk;
|
||||
const marker = isError ? "✗" : "→";
|
||||
// `edit_file` results get a dedicated diff renderer — colored
|
||||
// line-by-line so `-` removals show red, `+` additions show
|
||||
// green, unchanged context lines dim. Always full, never
|
||||
// truncated: users need to see the whole change to trust
|
||||
// /apply. Other tools keep the 400-char clip + /tool N escape.
|
||||
// `edit_file` results get a dedicated multi-line diff renderer —
|
||||
// colored line-by-line so `-` removals show red, `+` additions
|
||||
// show green, unchanged context lines dim. Always full, never
|
||||
// truncated: users need to see the whole change to trust /apply.
|
||||
const isExplicitError = event.text.startsWith("ERROR:");
|
||||
const isEditFile =
|
||||
(event.toolName === "edit_file" || event.toolName?.endsWith("_edit_file")) && !isError;
|
||||
return (
|
||||
<Box flexDirection="column" marginTop={1}>
|
||||
<Box>
|
||||
<RoleGlyph glyph={glyph} color={color} />
|
||||
<Text color={color} bold>{` ${event.toolName ?? "?"}`}</Text>
|
||||
<Text color={color} dimColor>{` ${marker}`}</Text>
|
||||
</Box>
|
||||
<Box flexDirection="column" paddingLeft={2} marginTop={1}>
|
||||
{isEditFile ? (
|
||||
(event.toolName === "edit_file" || event.toolName?.endsWith("_edit_file")) &&
|
||||
!isExplicitError;
|
||||
if (isEditFile) {
|
||||
return (
|
||||
<Box flexDirection="column" marginTop={1}>
|
||||
<Box>
|
||||
<ToolPill label={event.toolName ?? "?"} status="ok" />
|
||||
<Text dimColor>{" diff:"}</Text>
|
||||
</Box>
|
||||
<Box
|
||||
flexDirection="column"
|
||||
marginTop={1}
|
||||
borderStyle="single"
|
||||
borderTop={false}
|
||||
borderRight={false}
|
||||
borderBottom={false}
|
||||
borderColor={COLOR.tool}
|
||||
paddingLeft={1}
|
||||
>
|
||||
<EditFileDiff text={event.text} />
|
||||
) : (
|
||||
<Text color={isError ? "red" : undefined} dimColor={!isError}>
|
||||
{truncate(event.text, 400)}
|
||||
</Text>
|
||||
)}
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
// Compact one-line render for everything else. The summarizer
|
||||
// produces a tool-aware one-liner (exit code for shell, line
|
||||
// count for read_file, error tag for failures, ...). Full content
|
||||
// remains accessible via `/tool N`, hinted as a dim suffix.
|
||||
const summary = summarizeToolResult(event.toolName ?? "?", event.text);
|
||||
const status: "ok" | "err" = summary.isError ? "err" : "ok";
|
||||
const durationLabel =
|
||||
event.durationMs !== undefined && event.durationMs >= 100
|
||||
? formatDuration(event.durationMs)
|
||||
: "";
|
||||
const indexHint = event.toolIndex !== undefined ? ` /tool ${event.toolIndex}` : "";
|
||||
return (
|
||||
<Box>
|
||||
<ToolPill label={event.toolName ?? "?"} status={status} />
|
||||
{durationLabel ? <Text dimColor>{` ${durationLabel}`}</Text> : null}
|
||||
<Text dimColor>{" "}</Text>
|
||||
<Text color={status === "err" ? "red" : undefined} dimColor={status === "ok"}>
|
||||
{summary.summary}
|
||||
</Text>
|
||||
{indexHint ? <Text dimColor>{indexHint}</Text> : null}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
if (event.role === "error") {
|
||||
return (
|
||||
<Box marginTop={1}>
|
||||
<RoleGlyph glyph={ROLE_GLYPH.error} color="red" />
|
||||
<Text color="red">
|
||||
{" "}
|
||||
{event.text}
|
||||
<Text backgroundColor="#f87171" color="black" bold>
|
||||
{" ✦ ERROR "}
|
||||
</Text>
|
||||
<Text>{" "}</Text>
|
||||
<Text color="#f87171">{indentContinuationLines(event.text)}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
if (event.role === "info") {
|
||||
// Detect tone from the text so the info row carries semantic
|
||||
// weight: ▲/⚠ → warn, ✓ → ok, ✗/✖ → error, ↻ → reload, otherwise
|
||||
// a neutral ▸. The leading glyph (if any) is consumed and the
|
||||
// body renders dim.
|
||||
const m = event.text.match(/^([▸▶▲⚠✓✗✖↻ⓘ])\s*(.*)$/s);
|
||||
const lead = m?.[1] ?? "▸";
|
||||
const body = m?.[2] ?? event.text;
|
||||
let leadColor: string = COLOR.info;
|
||||
if (lead === "▲" || lead === "⚠") leadColor = COLOR.warn;
|
||||
else if (lead === "✓") leadColor = COLOR.ok;
|
||||
else if (lead === "✗" || lead === "✖") leadColor = COLOR.err;
|
||||
else if (lead === "↻") leadColor = COLOR.primary;
|
||||
return (
|
||||
<Box>
|
||||
<Text dimColor>{event.text}</Text>
|
||||
<Text color={leadColor} bold>
|
||||
{lead}
|
||||
</Text>
|
||||
<Text> </Text>
|
||||
<Text dimColor>{body}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
if (event.role === "plan") {
|
||||
return (
|
||||
<Box flexDirection="column" paddingX={1} marginY={1}>
|
||||
<Box>
|
||||
<Text bold color="cyan">
|
||||
{"📋 plan proposed — pick a choice below"}
|
||||
</Text>
|
||||
</Box>
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
<Markdown text={event.text} projectRoot={projectRoot} />
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
if (event.role === "step-progress") {
|
||||
const sp = event.stepProgress;
|
||||
const counter = sp && sp.total > 0 ? `${sp.completed}/${sp.total}` : "";
|
||||
const label = sp?.title ? `${sp.stepId} · ${sp.title}` : (sp?.stepId ?? "");
|
||||
return (
|
||||
<Box flexDirection="column" marginTop={1}>
|
||||
<Box>
|
||||
<Text backgroundColor="#4ade80" color="black" bold>
|
||||
{" ✓ STEP "}
|
||||
</Text>
|
||||
{counter ? (
|
||||
<>
|
||||
<Text>{" "}</Text>
|
||||
<Text color="#4ade80" bold>
|
||||
{counter}
|
||||
</Text>
|
||||
</>
|
||||
) : null}
|
||||
<Text>{" "}</Text>
|
||||
<Text color="#86efac">{label}</Text>
|
||||
</Box>
|
||||
{event.text ? (
|
||||
<Box paddingLeft={2}>
|
||||
<Text dimColor>{event.text}</Text>
|
||||
</Box>
|
||||
) : null}
|
||||
{sp?.notes ? (
|
||||
<Box paddingLeft={2}>
|
||||
<Text color="#fbbf24" dimColor>
|
||||
{`note: ${sp.notes}`}
|
||||
</Text>
|
||||
</Box>
|
||||
) : null}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
if (event.role === "plan-resumed") {
|
||||
const rp = event.resumedPlan;
|
||||
if (!rp || rp.steps.length === 0) return null;
|
||||
const total = rp.steps.length;
|
||||
const done = rp.completedStepIds.length;
|
||||
const completedSet = new Set(rp.completedStepIds);
|
||||
const statuses = new Map(
|
||||
rp.steps.map((s) => [
|
||||
s.id,
|
||||
completedSet.has(s.id) ? ("done" as const) : ("pending" as const),
|
||||
]),
|
||||
);
|
||||
// Focus the first pending step so the user immediately sees where
|
||||
// execution will resume from. If the plan is fully done, no focus.
|
||||
const nextStep = rp.steps.find((s) => !completedSet.has(s.id));
|
||||
return (
|
||||
<Box flexDirection="column" paddingX={1} marginY={1}>
|
||||
<Box>
|
||||
<Text backgroundColor="#67e8f9" color="black" bold>
|
||||
{" ↻ RESUMED PLAN "}
|
||||
</Text>
|
||||
<Text>{" "}</Text>
|
||||
<Text color="#67e8f9" bold>
|
||||
{`${done}/${total}`}
|
||||
</Text>
|
||||
<Text dimColor>{` done · last touched ${rp.relativeTime}`}</Text>
|
||||
</Box>
|
||||
{rp.summary ? (
|
||||
<Box marginTop={1}>
|
||||
<Text color="#67e8f9">{rp.summary}</Text>
|
||||
</Box>
|
||||
) : null}
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
<PlanStepList steps={rp.steps} statuses={statuses} focusStepId={nextStep?.id} />
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
if (event.role === "plan-replay") {
|
||||
const r = event.replayPlan;
|
||||
if (!r || r.steps.length === 0) return null;
|
||||
const total = r.steps.length;
|
||||
const completedSet = new Set(r.completedStepIds);
|
||||
const done = completedSet.size;
|
||||
const statuses = new Map(
|
||||
r.steps.map((s) => [s.id, completedSet.has(s.id) ? ("done" as const) : ("pending" as const)]),
|
||||
);
|
||||
const navHint = r.total > 1 ? ` · ${r.index}/${r.total}` : "";
|
||||
return (
|
||||
<Box flexDirection="column" paddingX={1} marginY={1}>
|
||||
<Box>
|
||||
<Text backgroundColor="#94a3b8" color="black" bold>
|
||||
{" ⏪ REPLAY "}
|
||||
</Text>
|
||||
<Text>{" "}</Text>
|
||||
<Text color="#94a3b8" bold>
|
||||
{`${done}/${total}`}
|
||||
</Text>
|
||||
<Text dimColor>{` done · ${r.relativeTime}${navHint}`}</Text>
|
||||
</Box>
|
||||
{r.summary ? (
|
||||
<Box marginTop={1}>
|
||||
<Text color="#94a3b8">{r.summary}</Text>
|
||||
</Box>
|
||||
) : null}
|
||||
<Box>
|
||||
<Text dimColor>{r.archiveBasename}</Text>
|
||||
</Box>
|
||||
{r.body ? (
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
<Markdown text={r.body} projectRoot={projectRoot} />
|
||||
</Box>
|
||||
) : null}
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
<PlanStepList steps={r.steps} statuses={statuses} />
|
||||
</Box>
|
||||
<Box marginTop={1}>
|
||||
<Text dimColor>
|
||||
{r.total > 1
|
||||
? `(read-only · /replay ${r.index === 1 ? 2 : 1} for the ${r.index === 1 ? "next" : "newest"} archive)`
|
||||
: "(read-only · this is an archived plan)"}
|
||||
</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
if (event.role === "warning") {
|
||||
return (
|
||||
<Box>
|
||||
<RoleGlyph glyph={ROLE_GLYPH.warning} color="yellow" />
|
||||
<Text color="yellow">
|
||||
{" "}
|
||||
{event.text}
|
||||
<Text backgroundColor="#fbbf24" color="black" bold>
|
||||
{" ▲ WARN "}
|
||||
</Text>
|
||||
<Text>{" "}</Text>
|
||||
<Text color="#fbbf24">{indentContinuationLines(event.text)}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -178,27 +499,38 @@ export const EventRow = React.memo(function EventRow({
|
||||
});
|
||||
|
||||
/**
|
||||
* Thin horizontal rule between turns with a cyan ◆ centered as the
|
||||
* Reasonix mark. Past-turn separators live inside `<Static>` (Ink's
|
||||
* render-once optimization), so animation here would freeze at
|
||||
* tick=0 on every past turn — we keep it static by design. The
|
||||
* animated heartbeat lives in PulsingAssistantGlyph (current turn)
|
||||
* and the Wordmark (StatsPanel) where rerender is free.
|
||||
* Decorative gradient rule between turns. Uses the brand gradient
|
||||
* (teal → fuchsia) so the boundary between "old turn" and "new
|
||||
* turn" reads as a designed accent rather than a dim minus-sign
|
||||
* row. Static — past separators live inside Ink's `<Static>`, so
|
||||
* animation would freeze at tick=0 anyway.
|
||||
*/
|
||||
function TurnSeparator() {
|
||||
const { stdout } = useStdout();
|
||||
const cols = stdout?.columns ?? 80;
|
||||
const width = Math.max(16, cols - 2);
|
||||
const half = Math.floor((width - 3) / 2);
|
||||
const left = "─".repeat(half);
|
||||
const right = "─".repeat(width - half - 3);
|
||||
// Reserve 5 cells for ` ◆ ` in the middle. Split the remainder
|
||||
// into two gradient halves so the brand mark sits on the seam.
|
||||
const sideWidth = Math.max(2, Math.floor((width - 5) / 2));
|
||||
const leftCells = gradientCells(sideWidth, "─");
|
||||
const rightCells = gradientCells(sideWidth, "─");
|
||||
return (
|
||||
<Box marginTop={1} marginBottom={1}>
|
||||
<Text dimColor>{left}</Text>
|
||||
<Text color="cyan" bold>
|
||||
{" ◆ "}
|
||||
{leftCells.map((c, i) => (
|
||||
// biome-ignore lint/suspicious/noArrayIndexKey: fixed-width gradient row
|
||||
<Text key={`tsep-l-${i}`} color={c.color}>
|
||||
{c.ch}
|
||||
</Text>
|
||||
))}
|
||||
<Text color={COLOR.brand} bold>
|
||||
{" ◆ "}
|
||||
</Text>
|
||||
<Text dimColor>{right}</Text>
|
||||
{rightCells.map((c, i) => (
|
||||
// biome-ignore lint/suspicious/noArrayIndexKey: fixed-width gradient row
|
||||
<Text key={`tsep-r-${i}`} color={c.color}>
|
||||
{c.ch}
|
||||
</Text>
|
||||
))}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -216,42 +548,57 @@ function EditFileDiff({ text }: { text: string }) {
|
||||
const lines = text.split(/\r?\n/);
|
||||
// Line 0 is the status header ("edited X (A→B chars)"), Line 1 is
|
||||
// the unified-diff hunk header ("@@ -N,M +N,M @@"), the rest is
|
||||
// the colored diff body. We style the two headers distinctly so
|
||||
// the hunk marker stands out the way git-diff's cyan `@@` does in
|
||||
// most terminals.
|
||||
// the colored diff body. The hunk header gets a magenta-bg pill —
|
||||
// same idiom as the rest of the TUI — so it visually anchors each
|
||||
// hunk. Body lines render with a colored gutter glyph + tinted bg
|
||||
// for + and -, so the diff scans like a syntax-highlighted patch
|
||||
// file rather than a wall of monochrome text.
|
||||
const [statusHeader, hunkHeader, ...body] = lines;
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
<Text dimColor>{` ${statusHeader ?? ""}`}</Text>
|
||||
{hunkHeader !== undefined ? (
|
||||
<Text color="cyan" bold>
|
||||
{hunkHeader}
|
||||
</Text>
|
||||
<Box marginTop={1}>
|
||||
<Text backgroundColor="#c4b5fd" color="black" bold>
|
||||
{` ${hunkHeader.trim()} `}
|
||||
</Text>
|
||||
</Box>
|
||||
) : null}
|
||||
{body.map((line, i) => {
|
||||
// Key includes the line content slice so React isn't forced
|
||||
// to treat purely-positional identity; lines in the same
|
||||
// diff don't reorder but could repeat (e.g. blank lines).
|
||||
const key = `${i}-${line.slice(0, 32)}`;
|
||||
if (line.startsWith("- ")) {
|
||||
// Strip the leading " " indent diff-preview adds to every
|
||||
// body line so the gutter glyph is column 0 regardless of
|
||||
// formatter changes upstream.
|
||||
const stripped = line.replace(/^ {2}/, "");
|
||||
if (stripped.startsWith("- ")) {
|
||||
return (
|
||||
<Text key={key} color="red">
|
||||
{line}
|
||||
</Text>
|
||||
<Box key={key}>
|
||||
<Text color="#f87171" bold>
|
||||
{"− "}
|
||||
</Text>
|
||||
<Text color="#fca5a5">{stripped.slice(2)}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
if (line.startsWith("+ ")) {
|
||||
if (stripped.startsWith("+ ")) {
|
||||
return (
|
||||
<Text key={key} color="green">
|
||||
{line}
|
||||
</Text>
|
||||
<Box key={key}>
|
||||
<Text color="#4ade80" bold>
|
||||
{"+ "}
|
||||
</Text>
|
||||
<Text color="#86efac">{stripped.slice(2)}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
// Context line (starts with " ") or unknown — dim.
|
||||
// Context line (starts with " ") or unknown — dim.
|
||||
return (
|
||||
<Text key={key} dimColor>
|
||||
{line}
|
||||
</Text>
|
||||
<Box key={key}>
|
||||
<Text dimColor>{" "}</Text>
|
||||
<Text dimColor>{stripped}</Text>
|
||||
</Box>
|
||||
);
|
||||
})}
|
||||
</Box>
|
||||
@@ -259,21 +606,36 @@ function EditFileDiff({ text }: { text: string }) {
|
||||
}
|
||||
|
||||
function BranchBlock({ branch }: { branch: BranchSummary }) {
|
||||
const per = branch.uncertainties
|
||||
.map((u, i) => {
|
||||
const marker = i === branch.chosenIndex ? "▸" : " ";
|
||||
const t = (branch.temperatures[i] ?? 0).toFixed(1);
|
||||
return `${marker} #${i} T=${t} u=${u}`;
|
||||
})
|
||||
.join(" ");
|
||||
return (
|
||||
<Box>
|
||||
<Text color="blue">
|
||||
{"⎇ branched "}
|
||||
<Text bold>{branch.budget}</Text>
|
||||
{` samples → picked #${branch.chosenIndex} `}
|
||||
<Text dimColor>{per}</Text>
|
||||
</Text>
|
||||
<Box flexDirection="column" marginBottom={1}>
|
||||
<Box>
|
||||
<Text backgroundColor="#93c5fd" color="black" bold>
|
||||
{` ⎇ BRANCH ×${branch.budget} `}
|
||||
</Text>
|
||||
<Text>{" "}</Text>
|
||||
<Text color="#93c5fd">picked </Text>
|
||||
<Text color="#93c5fd" bold>
|
||||
#{branch.chosenIndex}
|
||||
</Text>
|
||||
</Box>
|
||||
<Box paddingLeft={2} marginTop={1}>
|
||||
{branch.uncertainties.map((u, i) => {
|
||||
const chosen = i === branch.chosenIndex;
|
||||
const t = (branch.temperatures[i] ?? 0).toFixed(1);
|
||||
return (
|
||||
// biome-ignore lint/suspicious/noArrayIndexKey: branch index is positional and stable
|
||||
<Text key={`b-${i}`}>
|
||||
<Text color={chosen ? "#93c5fd" : "#475569"} bold={chosen}>
|
||||
{chosen ? "▸ " : " "}
|
||||
</Text>
|
||||
<Text color={chosen ? "#93c5fd" : "#94a3b8"} bold={chosen}>
|
||||
{`#${i}`}
|
||||
</Text>
|
||||
<Text dimColor>{` T=${t} u=${u} `}</Text>
|
||||
</Text>
|
||||
);
|
||||
})}
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -288,15 +650,14 @@ function ReasoningBlock({ reasoning }: { reasoning: string }) {
|
||||
// Users can dump the full reasoning with `/think` if needed.
|
||||
const preview =
|
||||
flat.length <= max ? flat : `… (+${flat.length - max} earlier chars) ${flat.slice(-max)}`;
|
||||
// ▏ (LEFT ONE EIGHTH BLOCK) renders as a thin vertical rule at the
|
||||
// cell edge — subtler than the role-level ▎ above, giving a
|
||||
// visual hierarchy: thick bar = role, thin bar = nested detail
|
||||
// under that role (thinking, stats, citations, etc).
|
||||
return (
|
||||
<Box marginBottom={1}>
|
||||
<Text dimColor>▏ </Text>
|
||||
<Text dimColor italic>
|
||||
thinking {preview}
|
||||
<Text backgroundColor={COLOR.accent} color="black" bold>
|
||||
{" ⋯ thinking "}
|
||||
</Text>
|
||||
<Text> </Text>
|
||||
<Text color={COLOR.accent} italic dimColor>
|
||||
{preview}
|
||||
</Text>
|
||||
</Box>
|
||||
);
|
||||
@@ -396,25 +757,34 @@ function StreamingAssistant({ event }: { event: DisplayEvent }) {
|
||||
const preFirstByte = !event.text && !event.reasoning && !toolCallBuild;
|
||||
const reasoningOnly = !event.text && !!event.reasoning && !toolCallBuild;
|
||||
const toolCallOnly = !event.text && !event.reasoning && !!toolCallBuild;
|
||||
// Phase pill — solid bg color per phase so the user reads
|
||||
// "what's happening" at a glance from across the screen.
|
||||
let pillBg: string;
|
||||
let pillText: string;
|
||||
let label: string;
|
||||
let labelColor: "yellow" | "cyan" | "green" | "magenta" | undefined;
|
||||
if (preFirstByte) {
|
||||
pillBg = "#fbbf24"; // amber
|
||||
pillText = "WAITING";
|
||||
label = "request sent · waiting for server";
|
||||
labelColor = "yellow";
|
||||
} else if (reasoningOnly) {
|
||||
label = `R1 reasoning · ${event.reasoning?.length ?? 0} chars of thought`;
|
||||
labelColor = "cyan";
|
||||
pillBg = "#c4b5fd"; // violet
|
||||
pillText = "THINKING";
|
||||
label = `${event.reasoning?.length ?? 0} chars of thought`;
|
||||
} else if (toolCallOnly) {
|
||||
label = `assembling tool call <${toolCallBuild.name}> · ${toolCallBuild.chars} chars of arguments`;
|
||||
labelColor = "magenta";
|
||||
pillBg = "#f0abfc"; // fuchsia
|
||||
pillText = "DISPATCH";
|
||||
label = `assembling${formatToolCallIndex(toolCallBuild)} <${toolCallBuild.name}> · ${toolCallBuild.chars} chars${formatReadyTail(toolCallBuild)}`;
|
||||
} else {
|
||||
const parts: string[] = [`writing response · ${event.text.length} chars`];
|
||||
if (event.reasoning) parts.push(`after ${event.reasoning.length} chars of reasoning`);
|
||||
pillBg = "#86efac"; // green
|
||||
pillText = "WRITING";
|
||||
const parts: string[] = [`${event.text.length} chars`];
|
||||
if (event.reasoning) parts.push(`after ${event.reasoning.length} reasoning`);
|
||||
if (toolCallBuild) {
|
||||
parts.push(`building tool call <${toolCallBuild.name}> · ${toolCallBuild.chars} chars`);
|
||||
parts.push(
|
||||
`tool${formatToolCallIndex(toolCallBuild)} <${toolCallBuild.name}> ${toolCallBuild.chars}c${formatReadyTail(toolCallBuild)}`,
|
||||
);
|
||||
}
|
||||
label = parts.join(" · ");
|
||||
labelColor = "green";
|
||||
}
|
||||
return (
|
||||
<Box flexDirection="column" marginTop={1}>
|
||||
@@ -422,36 +792,50 @@ function StreamingAssistant({ event }: { event: DisplayEvent }) {
|
||||
<PulsingAssistantGlyph />
|
||||
<Text>{" "}</Text>
|
||||
<Pulse />
|
||||
<Text color={labelColor}>{` ${label} `}</Text>
|
||||
<Text> </Text>
|
||||
<Text backgroundColor={pillBg} color="black" bold>
|
||||
{` ${pillText} `}
|
||||
</Text>
|
||||
<Text dimColor>{` ${label} `}</Text>
|
||||
<Elapsed />
|
||||
</Box>
|
||||
{reasoningTail ? (
|
||||
<Text dimColor italic>
|
||||
↳ thinking: {reasoningTail}
|
||||
</Text>
|
||||
<Box paddingLeft={3}>
|
||||
<Text color="#c4b5fd" italic dimColor>
|
||||
↳ {reasoningTail}
|
||||
</Text>
|
||||
</Box>
|
||||
) : null}
|
||||
{tail ? (
|
||||
<Text dimColor>▸ {tail}</Text>
|
||||
<Box paddingLeft={3}>
|
||||
<Text dimColor>▸ {tail}</Text>
|
||||
</Box>
|
||||
) : preFirstByte ? (
|
||||
// Non-dim yellow: first-time users misread the dim version as
|
||||
// Non-dim amber: first-time users misread the dim version as
|
||||
// "app frozen". The reassurance has to be VISIBLE to do its job.
|
||||
<Text color="yellow" italic>
|
||||
{" waiting for first byte — this is normal, typically 5-60s depending on model + load"}
|
||||
</Text>
|
||||
<Box paddingLeft={3}>
|
||||
<Text color="#fbbf24" italic>
|
||||
{"waiting for first byte — typical 5–60s depending on model + load"}
|
||||
</Text>
|
||||
</Box>
|
||||
) : reasoningOnly ? (
|
||||
<Text color="yellow" italic>
|
||||
{
|
||||
" R1 is thinking before it speaks — body text arrives when reasoning finishes (typically 20-90s, this is normal)"
|
||||
}
|
||||
</Text>
|
||||
<Box paddingLeft={3}>
|
||||
<Text color="#c4b5fd" italic>
|
||||
{"R1 thinks before it speaks — body text arrives when reasoning finishes (20–90s)"}
|
||||
</Text>
|
||||
</Box>
|
||||
) : toolCallOnly ? (
|
||||
<Text color="magenta" italic>
|
||||
{" tool-call arguments streaming — the model is about to dispatch a tool"}
|
||||
</Text>
|
||||
<Box paddingLeft={3}>
|
||||
<Text color="#f0abfc" italic>
|
||||
{"tool-call arguments streaming — about to dispatch"}
|
||||
</Text>
|
||||
</Box>
|
||||
) : event.reasoning ? (
|
||||
<Text color="yellow" italic>
|
||||
{" R1 still reasoning — body text or tool call arrives when thinking finishes"}
|
||||
</Text>
|
||||
<Box paddingLeft={3}>
|
||||
<Text color="#fbbf24" italic>
|
||||
{"R1 still reasoning — body text or tool call arrives when thinking finishes"}
|
||||
</Text>
|
||||
</Box>
|
||||
) : null}
|
||||
</Box>
|
||||
);
|
||||
@@ -469,6 +853,29 @@ function Pulse() {
|
||||
return <Text color="cyan">{frames[Math.floor(tick / 4) % frames.length]}</Text>;
|
||||
}
|
||||
|
||||
/**
|
||||
* "(call 3)" suffix for the tool-call label when we have the index.
|
||||
* Hides when the turn only has one call so the common case stays tidy.
|
||||
*/
|
||||
function formatToolCallIndex(tb: { index?: number; readyCount?: number } | undefined): string {
|
||||
if (!tb || tb.index === undefined) return "";
|
||||
// Only show the index when this isn't obviously the first + only call.
|
||||
if (tb.index === 0 && (tb.readyCount ?? 0) === 0) return "";
|
||||
return ` (call ${tb.index + 1})`;
|
||||
}
|
||||
|
||||
/**
|
||||
* "· 2 ready" tail that answers "how many tool calls have finished
|
||||
* streaming so far this turn?" — user feedback for multi-file turns
|
||||
* where the response takes 10–30s to stream. Hidden until readyCount
|
||||
* > 0 so single-call turns aren't cluttered.
|
||||
*/
|
||||
function formatReadyTail(tb: { readyCount?: number } | undefined): string {
|
||||
const n = tb?.readyCount ?? 0;
|
||||
if (n <= 0) return "";
|
||||
return ` · ${n} ready`;
|
||||
}
|
||||
|
||||
function lastLine(s: string, maxChars: number): string {
|
||||
const flat = s.replace(/\s+/g, " ").trim();
|
||||
if (!flat) return "";
|
||||
@@ -477,48 +884,26 @@ function lastLine(s: string, maxChars: number): string {
|
||||
|
||||
function StatsLine({ stats }: { stats: TurnStats }) {
|
||||
const hit = (stats.cacheHitRatio * 100).toFixed(1);
|
||||
const hitColor =
|
||||
stats.cacheHitRatio >= 0.7 ? "#4ade80" : stats.cacheHitRatio >= 0.4 ? "#fcd34d" : "#f87171";
|
||||
return (
|
||||
<Box>
|
||||
<Text dimColor>▏ </Text>
|
||||
<Text dimColor>
|
||||
{"cache "}
|
||||
{hit}
|
||||
{"% · tokens "}
|
||||
{stats.usage.promptTokens}
|
||||
{" → "}
|
||||
{stats.usage.completionTokens}
|
||||
{" · $"}
|
||||
{stats.cost.toFixed(6)}
|
||||
<Box marginTop={1}>
|
||||
<Text color={hitColor} bold>
|
||||
{`⌬ ${hit}%`}
|
||||
</Text>
|
||||
<Text dimColor>{" · "}</Text>
|
||||
<Text color="#94a3b8">
|
||||
{"in "}
|
||||
<Text color="#67e8f9" bold>
|
||||
{stats.usage.promptTokens}
|
||||
</Text>
|
||||
{" → out "}
|
||||
<Text color="#c4b5fd" bold>
|
||||
{stats.usage.completionTokens}
|
||||
</Text>
|
||||
</Text>
|
||||
<Text dimColor>{" · "}</Text>
|
||||
<Text color="#86efac" bold>{`$${stats.cost.toFixed(6)}`}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Show the *tail* of a long tool result by default — the useful signal
|
||||
* (return value, summary, error line) usually lives at the end, not the
|
||||
* top-of-file boilerplate. For `ERROR:`-prefixed results, keep the
|
||||
* first line intact (that's the actual error message) AND include the
|
||||
* tail, so stack-trace endings stay visible too.
|
||||
*
|
||||
* Rendered like: `(+N earlier chars) …<tail>` so users can tell at a
|
||||
* glance that something was elided. `/tool N` still dumps the full
|
||||
* content for cases where the middle matters.
|
||||
*/
|
||||
function truncate(s: string, max: number): string {
|
||||
if (s.length <= max) return s;
|
||||
if (s.startsWith("ERROR:")) {
|
||||
const firstNl = s.indexOf("\n");
|
||||
const firstLine = firstNl === -1 ? s : s.slice(0, firstNl);
|
||||
// If the first line alone is bigger than max, just show it truncated.
|
||||
if (firstLine.length >= max) {
|
||||
return `${firstLine.slice(0, max)}… (+${s.length - max} chars — /tool N for full)`;
|
||||
}
|
||||
const budget = max - firstLine.length - 10; // reserve space for separator + ellipsis
|
||||
const tail = s.slice(-budget);
|
||||
const skipped = s.length - firstLine.length - tail.length;
|
||||
return `${firstLine}\n… (+${skipped} chars) …\n${tail}`;
|
||||
}
|
||||
const skipped = s.length - max;
|
||||
return `… (+${skipped} earlier chars — /tool N for full) …\n${s.slice(-max)}`;
|
||||
}
|
||||
@@ -0,0 +1,335 @@
|
||||
import { Box, Text, useStdout } from "ink";
|
||||
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React as a runtime value (classic transform)
|
||||
import React from "react";
|
||||
import type { ApplyResult } from "../../code/edit-blocks.js";
|
||||
import type { EditMode } from "../../config.js";
|
||||
import type { JobRegistry } from "../../tools/jobs.js";
|
||||
import { useElapsedSeconds, useTick } from "./ticker.js";
|
||||
|
||||
export const SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
|
||||
|
||||
/**
|
||||
* Transient "what's happening now" row shown during silent phases
|
||||
* between the primary events — harvest round-trip, R1 thinking
|
||||
* about a tool result before the next streaming delta, forced
|
||||
* summary. Matches OngoingToolRow's visual language (braille
|
||||
* spinner + elapsed seconds) so the user's eyes track the same
|
||||
* spot regardless of which kind of wait it is.
|
||||
*/
|
||||
export function StatusRow({ text }: { text: string }) {
|
||||
const tick = useTick();
|
||||
const elapsed = useElapsedSeconds();
|
||||
return (
|
||||
<Box marginY={1} paddingX={1}>
|
||||
<Text color="#c4b5fd" bold>
|
||||
{SPINNER_FRAMES[tick % SPINNER_FRAMES.length]}
|
||||
</Text>
|
||||
<Text>{" "}</Text>
|
||||
<Text color="#c4b5fd">{text}</Text>
|
||||
<Text dimColor>{` · ${elapsed}s`}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* One-line bottom status bar showing the current edit mode, pending
|
||||
* queue size (review only), an undo hint (auto only / after /apply),
|
||||
* and the Shift+Tab nudge. Rendered immediately above PromptInput so
|
||||
* the mode is always in peripheral vision when the user's eyes are at
|
||||
* the prompt. Flashes briefly on mode change so Shift+Tab gives a
|
||||
* visible acknowledgment without the user having to scan the header.
|
||||
*
|
||||
* The plan-mode pill takes precedence — when plan mode is on, writes
|
||||
* are bounced regardless of edit mode, so surfacing it is more useful
|
||||
* than the review/auto toggle.
|
||||
*/
|
||||
export function ModeStatusBar({
|
||||
editMode,
|
||||
pendingCount,
|
||||
flash,
|
||||
planMode,
|
||||
undoArmed,
|
||||
jobs,
|
||||
}: {
|
||||
editMode: EditMode;
|
||||
pendingCount: number;
|
||||
flash: boolean;
|
||||
planMode: boolean;
|
||||
undoArmed: boolean;
|
||||
jobs?: JobRegistry;
|
||||
}) {
|
||||
// Subscribe to tick so the jobs count stays live — the registry is
|
||||
// mutated outside React, so we need a periodic repaint to catch it.
|
||||
// No-op when there's no registry (chat mode / tests).
|
||||
useTick();
|
||||
const running = jobs?.runningCount() ?? 0;
|
||||
const jobsTag =
|
||||
running > 0 ? (
|
||||
<Text color="yellow" bold>{` · ⏵ ${running} job${running === 1 ? "" : "s"}`}</Text>
|
||||
) : null;
|
||||
// The same mode pill is already in the StatsPanel header — here we
|
||||
// skip the pill and keep just a tight inline hint right above the
|
||||
// input so the user has the actionable bit (what y/n/u/Shift+Tab
|
||||
// do) without the whole tutorial.
|
||||
if (planMode) {
|
||||
return (
|
||||
<ModeBarFrame>
|
||||
<ModePill label="PLAN MODE" bg="red" flash={flash} />
|
||||
<Text dimColor>{" writes gated · /plan off to leave"}</Text>
|
||||
{jobsTag}
|
||||
</ModeBarFrame>
|
||||
);
|
||||
}
|
||||
const label = editMode === "yolo" ? "YOLO" : editMode === "auto" ? "AUTO" : "REVIEW";
|
||||
const bg = editMode === "yolo" ? "red" : editMode === "auto" ? "magenta" : "cyan";
|
||||
const mid =
|
||||
editMode === "yolo"
|
||||
? "edits + shell auto · /undo to roll back"
|
||||
: editMode === "auto"
|
||||
? "edits land now · u to undo"
|
||||
: pendingCount > 0
|
||||
? `${pendingCount} queued · y apply · n discard`
|
||||
: "edits queued · y apply · n discard";
|
||||
return (
|
||||
<ModeBarFrame>
|
||||
<ModePill label={label} bg={bg} flash={flash} />
|
||||
<Text dimColor>{` ${mid} · Shift+Tab to flip`}</Text>
|
||||
{jobsTag}
|
||||
</ModeBarFrame>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps the bottom mode/jobs row in a dim top rule + side padding
|
||||
* so the modeline reads as its own zone, separate from the prompt
|
||||
* input above. Keeps the live region border-free (the rule is a
|
||||
* single Text row, not a bordered Box) so Ink's eraseLines miscount
|
||||
* stays out of it.
|
||||
*/
|
||||
function ModeBarFrame({ children }: { children: React.ReactNode }) {
|
||||
const { stdout } = useStdout();
|
||||
const cols = stdout?.columns ?? 80;
|
||||
const ruleWidth = Math.max(20, cols - 2);
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
<Box paddingX={1}>
|
||||
<Text color="#475569" dimColor>
|
||||
{"╌".repeat(ruleWidth)}
|
||||
</Text>
|
||||
</Box>
|
||||
<Box paddingX={1}>{children}</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Solid-background mode badge so the bottom status bar reads at a
|
||||
* glance like a real editor's modeline (vim/helix style) instead of a
|
||||
* dim text label that blends into the prompt above. `flash` inverts
|
||||
* briefly after a mode flip — the existing modeFlash signal — for a
|
||||
* "yes, it changed" acknowledgement.
|
||||
*/
|
||||
function ModePill({
|
||||
label,
|
||||
bg,
|
||||
flash,
|
||||
}: {
|
||||
label: string;
|
||||
bg: "magenta" | "cyan" | "red";
|
||||
flash: boolean;
|
||||
}) {
|
||||
return (
|
||||
<Text backgroundColor={bg} color="white" bold inverse={flash}>
|
||||
{` ${label} `}
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* "Just auto-applied N edits — press u to undo" banner. Rendered below
|
||||
* the live rows after an auto-mode edit batch lands, visible for 5s.
|
||||
* `useTick` drives a crude live countdown so the user sees the window
|
||||
* shrinking. State cleanup (the banner disappearing) happens in the
|
||||
* parent's setTimeout — the component is purely display.
|
||||
*/
|
||||
export function UndoBanner({
|
||||
banner,
|
||||
}: {
|
||||
banner: { results: ApplyResult[]; expiresAt: number };
|
||||
}) {
|
||||
useTick();
|
||||
const remainingMs = Math.max(0, banner.expiresAt - Date.now());
|
||||
const remainingSec = Math.ceil(remainingMs / 1000);
|
||||
const ok = banner.results.filter((r) => r.status === "applied" || r.status === "created").length;
|
||||
const total = banner.results.length;
|
||||
const urgent = remainingSec <= 1;
|
||||
return (
|
||||
<Box marginY={1} paddingX={1}>
|
||||
<Text backgroundColor="#c4b5fd" color="black" bold>
|
||||
{` ✓ AUTO-APPLIED ${ok}/${total} `}
|
||||
</Text>
|
||||
<Text dimColor>{" press "}</Text>
|
||||
<Text backgroundColor="#67e8f9" color="black" bold>
|
||||
{" u "}
|
||||
</Text>
|
||||
<Text dimColor>{" to undo "}</Text>
|
||||
<Text color={urgent ? "#f87171" : "#c4b5fd"} bold={urgent}>
|
||||
{`${remainingSec}s`}
|
||||
</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Live one-line indicator for a running subagent. Sits below the
|
||||
* OngoingToolRow (the parent's tool dispatch row for `spawn_subagent`)
|
||||
* so the user sees both layers at once: outer "spawn_subagent
|
||||
* running…" + inner "⌬ subagent: <task> · iter N · 12.3s". Cleared
|
||||
* when the subagent ends; a one-line summary lands in historical.
|
||||
*/
|
||||
export function SubagentRow({
|
||||
activity,
|
||||
}: {
|
||||
activity: { task: string; iter: number; elapsedMs: number };
|
||||
}) {
|
||||
const tick = useTick();
|
||||
const seconds = (activity.elapsedMs / 1000).toFixed(1);
|
||||
return (
|
||||
<Box paddingLeft={3}>
|
||||
<Text color="#c4b5fd" bold>
|
||||
{SPINNER_FRAMES[tick % SPINNER_FRAMES.length]}
|
||||
</Text>
|
||||
<Text>{" "}</Text>
|
||||
<Text backgroundColor="#c4b5fd" color="black" bold>
|
||||
{" ⌬ subagent "}
|
||||
</Text>
|
||||
<Text color="#c4b5fd">{` ${activity.task}`}</Text>
|
||||
<Text dimColor>{` iter ${activity.iter} · ${seconds}s`}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Live spinner row while a tool call is in flight. Without this the
|
||||
* window between the model's `tool_calls` decision and the tool's
|
||||
* result (often seconds for a multi-KB `filesystem_edit_file`) looks
|
||||
* like the app has frozen — the streaming assistant display is
|
||||
* already cleared and the input is disabled, so there's nothing to
|
||||
* look at.
|
||||
*
|
||||
* Shows three signals: a braille spinner (liveness), an elapsed
|
||||
* timer in seconds (so "long" has a number attached), and a
|
||||
* per-tool summary of the most informative argument fields (path,
|
||||
* edits count, pattern, etc.). As of 0.4.8, MCP progress frames
|
||||
* (`notifications/progress`) land here too — bar + "n/N" when the
|
||||
* server reports a total, free-form message when not.
|
||||
*/
|
||||
export function OngoingToolRow({
|
||||
tool,
|
||||
progress,
|
||||
}: {
|
||||
tool: { name: string; args?: string };
|
||||
progress: { progress: number; total?: number; message?: string } | null;
|
||||
}) {
|
||||
const tick = useTick();
|
||||
const elapsed = useElapsedSeconds();
|
||||
const summary = summarizeToolArgs(tool.name, tool.args);
|
||||
return (
|
||||
<Box marginY={1} flexDirection="column" paddingX={1}>
|
||||
<Box>
|
||||
<Text color="#fcd34d" bold>
|
||||
{SPINNER_FRAMES[tick % SPINNER_FRAMES.length]}
|
||||
</Text>
|
||||
<Text>{" "}</Text>
|
||||
<Text backgroundColor="#fcd34d" color="black" bold>
|
||||
{` ⏵ ${tool.name} `}
|
||||
</Text>
|
||||
<Text color="#fcd34d">{" running"}</Text>
|
||||
<Text dimColor>{` · ${elapsed}s`}</Text>
|
||||
</Box>
|
||||
{progress ? (
|
||||
<Box paddingLeft={3}>
|
||||
<Text color="#67e8f9">{renderProgressLine(progress)}</Text>
|
||||
</Box>
|
||||
) : null}
|
||||
{summary ? (
|
||||
<Box paddingLeft={3}>
|
||||
<Text dimColor>{summary}</Text>
|
||||
</Box>
|
||||
) : null}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Render an MCP progress frame as a single line. When the server
|
||||
* reports `total`, show an ASCII progress bar + "n/total pct%";
|
||||
* otherwise just "progress" + optional message. Width is modest
|
||||
* so the line fits even in a narrow terminal.
|
||||
*/
|
||||
function renderProgressLine(p: { progress: number; total?: number; message?: string }): string {
|
||||
const msg = p.message ? ` ${p.message}` : "";
|
||||
if (p.total && p.total > 0) {
|
||||
const ratio = Math.max(0, Math.min(1, p.progress / p.total));
|
||||
const width = 20;
|
||||
const filled = Math.round(ratio * width);
|
||||
const bar = "█".repeat(filled) + "░".repeat(width - filled);
|
||||
const pct = (ratio * 100).toFixed(0);
|
||||
return `[${bar}] ${p.progress}/${p.total} ${pct}%${msg}`;
|
||||
}
|
||||
return `progress: ${p.progress}${msg}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Turn raw JSON tool arguments into a one-line human summary. For
|
||||
* common filesystem MCP tools we pull the actually-useful fields; for
|
||||
* anything else we fall back to a truncated raw string so the user
|
||||
* still sees *something* beyond the tool name.
|
||||
*
|
||||
* Match on suffix (e.g. `_read_file`) rather than exact name because
|
||||
* `bridgeMcpTools({ namePrefix: "filesystem_" })` prepends the server
|
||||
* namespace — tools arrive as `filesystem_read_file` in practice but
|
||||
* callers might wire up anonymous too.
|
||||
*/
|
||||
function summarizeToolArgs(name: string, args?: string): string {
|
||||
if (!args || args === "{}") return "";
|
||||
let parsed: Record<string, unknown>;
|
||||
try {
|
||||
parsed = JSON.parse(args) as Record<string, unknown>;
|
||||
} catch {
|
||||
// Unparseable JSON — show a head slice so user at least sees
|
||||
// what the model tried.
|
||||
return args.length > 80 ? `${args.slice(0, 80)}…` : args;
|
||||
}
|
||||
const hasSuffix = (s: string) => name === s || name.endsWith(`_${s}`);
|
||||
const path = typeof parsed.path === "string" ? parsed.path : undefined;
|
||||
if (hasSuffix("read_file")) {
|
||||
const head = typeof parsed.head === "number" ? `, head=${parsed.head}` : "";
|
||||
const tail = typeof parsed.tail === "number" ? `, tail=${parsed.tail}` : "";
|
||||
return `path: ${path ?? "?"}${head}${tail}`;
|
||||
}
|
||||
if (hasSuffix("write_file")) {
|
||||
const content = typeof parsed.content === "string" ? parsed.content : "";
|
||||
return `path: ${path ?? "?"} (${content.length} chars)`;
|
||||
}
|
||||
if (hasSuffix("edit_file")) {
|
||||
const edits = Array.isArray(parsed.edits) ? parsed.edits.length : 0;
|
||||
return `path: ${path ?? "?"} (${edits} edit${edits === 1 ? "" : "s"})`;
|
||||
}
|
||||
if (hasSuffix("list_directory") || hasSuffix("directory_tree")) {
|
||||
return `path: ${path ?? "?"}`;
|
||||
}
|
||||
if (hasSuffix("search_files")) {
|
||||
const pattern = typeof parsed.pattern === "string" ? parsed.pattern : "?";
|
||||
return `path: ${path ?? "?"} · pattern: ${pattern}`;
|
||||
}
|
||||
if (hasSuffix("move_file")) {
|
||||
const src = typeof parsed.source === "string" ? parsed.source : "?";
|
||||
const dst = typeof parsed.destination === "string" ? parsed.destination : "?";
|
||||
return `${src} → ${dst}`;
|
||||
}
|
||||
if (hasSuffix("get_file_info")) {
|
||||
return `path: ${path ?? "?"}`;
|
||||
}
|
||||
return args.length > 80 ? `${args.slice(0, 80)}…` : args;
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
/**
|
||||
* Shared visual frame for confirmation modals (ChoiceConfirm,
|
||||
* PlanConfirm, ShellConfirm, EditConfirm, PlanCheckpointConfirm,
|
||||
* PlanReviseConfirm). Each modal opens inside the live region — so
|
||||
* we keep the frame to plain Text rules and bg-pill headers, no
|
||||
* Ink `borderStyle` (that's the eraseLines miscount class of bug).
|
||||
*
|
||||
* Layout:
|
||||
*
|
||||
* ▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
|
||||
* [ ICON TITLE ] optional subtitle
|
||||
*
|
||||
* <children — body of the modal>
|
||||
*
|
||||
* ▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁
|
||||
*
|
||||
* Color drives the accent (top + bottom rules + title pill bg)
|
||||
* so the user learns to recognize "magenta = choice", "cyan =
|
||||
* plan", "red = shell", "yellow = edit review" by sight.
|
||||
*/
|
||||
|
||||
import { Box, Text, useStdout } from "ink";
|
||||
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React in value scope
|
||||
import React from "react";
|
||||
|
||||
export interface ModalCardProps {
|
||||
/** Accent color — title pill bg + top/bottom rule color. */
|
||||
accent: string;
|
||||
/** Section title shown in the bg-pill header. */
|
||||
title: string;
|
||||
/** Optional dim subtitle next to the title. */
|
||||
subtitle?: string;
|
||||
/** Optional leading glyph inside the title pill (icon). */
|
||||
icon?: string;
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
export function ModalCard({
|
||||
accent,
|
||||
title,
|
||||
subtitle,
|
||||
icon,
|
||||
children,
|
||||
}: ModalCardProps): React.ReactElement {
|
||||
const { stdout } = useStdout();
|
||||
const cols = stdout?.columns ?? 80;
|
||||
const ruleWidth = Math.min(80, Math.max(28, cols - 4));
|
||||
const titleText = icon ? ` ${icon} ${title} ` : ` ${title} `;
|
||||
return (
|
||||
<Box flexDirection="column" paddingX={1} marginY={1}>
|
||||
<Box>
|
||||
<Text color={accent}>{"▔".repeat(ruleWidth)}</Text>
|
||||
</Box>
|
||||
<Box marginTop={1}>
|
||||
<Text backgroundColor={accent} color="black" bold>
|
||||
{titleText}
|
||||
</Text>
|
||||
{subtitle ? <Text dimColor>{` ${subtitle}`}</Text> : null}
|
||||
</Box>
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
{children}
|
||||
</Box>
|
||||
<Box marginTop={1}>
|
||||
<Text color={accent} dimColor>
|
||||
{"▁".repeat(ruleWidth)}
|
||||
</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
/**
|
||||
* Modal-style picker shown when `mark_step_complete` pauses the loop
|
||||
* via `PlanCheckpointError`. Three choices:
|
||||
*
|
||||
* 1. Continue — push "Step X done, proceed." so the model starts
|
||||
* the next step on the next turn.
|
||||
* 2. Revise — open a feedback input; whatever the user types
|
||||
* becomes a synthetic "user feedback for remaining steps" message.
|
||||
* The model can then adjust its approach without starting the
|
||||
* whole plan over.
|
||||
* 3. Stop — push "User stopped the plan. Summarize what was
|
||||
* done." so the run ends cleanly rather than being abandoned.
|
||||
*
|
||||
* The ✓ step-progress scrollback row is pushed separately (by App.tsx
|
||||
* at checkpoint detection time), so this modal stays a tight picker —
|
||||
* no need to re-render the step body here.
|
||||
*/
|
||||
|
||||
import { Box } from "ink";
|
||||
import React from "react";
|
||||
import type { PlanStep } from "../../tools/plan.js";
|
||||
import { ModalCard } from "./ModalCard.js";
|
||||
import { PlanStepList, type StepStatus } from "./PlanStepList.js";
|
||||
import { SingleSelect } from "./Select.js";
|
||||
|
||||
export type CheckpointChoice = "continue" | "revise" | "stop";
|
||||
|
||||
export interface PlanCheckpointConfirmProps {
|
||||
stepId: string;
|
||||
title?: string;
|
||||
completed: number;
|
||||
total: number;
|
||||
/** Full step list from the approved plan, when available. */
|
||||
steps?: PlanStep[];
|
||||
/** Set of stepIds the model has marked complete so far. */
|
||||
completedStepIds?: Set<string>;
|
||||
onChoose: (choice: CheckpointChoice) => void;
|
||||
}
|
||||
|
||||
function PlanCheckpointConfirmInner({
|
||||
stepId,
|
||||
title,
|
||||
completed,
|
||||
total,
|
||||
steps,
|
||||
completedStepIds,
|
||||
onChoose,
|
||||
}: PlanCheckpointConfirmProps) {
|
||||
const label = title ? `${stepId} · ${title}` : stepId;
|
||||
const counter = total > 0 ? `${completed}/${total}` : "";
|
||||
const isLast = total > 0 && completed >= total;
|
||||
const statuses = buildStatusMap(steps, completedStepIds, stepId, isLast);
|
||||
const subtitle = counter ? `${counter} · ${label}` : label;
|
||||
return (
|
||||
<ModalCard accent="#86efac" icon="✓" title="checkpoint — step done" subtitle={subtitle}>
|
||||
{steps && steps.length > 0 ? (
|
||||
<Box marginBottom={1} flexDirection="column">
|
||||
<PlanStepList steps={steps} statuses={statuses} focusStepId={stepId} />
|
||||
</Box>
|
||||
) : null}
|
||||
<SingleSelect
|
||||
initialValue={isLast ? "stop" : "continue"}
|
||||
items={[
|
||||
{
|
||||
value: "continue",
|
||||
label: "Continue — run the next step",
|
||||
hint: "Model resumes with the next step. Use this when the result looks right and you don't need to tweak the remaining plan.",
|
||||
},
|
||||
{
|
||||
value: "revise",
|
||||
label: "Revise — give feedback before the next step",
|
||||
hint: "Stay paused, type guidance (scope changes, skip steps, alternative approach). The model adjusts the remaining plan based on your message.",
|
||||
},
|
||||
{
|
||||
value: "stop",
|
||||
label: "Stop — end the plan here",
|
||||
hint: "Model summarizes what was done and ends. Remaining steps are skipped.",
|
||||
},
|
||||
]}
|
||||
onSubmit={(v) => onChoose(v as CheckpointChoice)}
|
||||
onCancel={() => onChoose("stop")}
|
||||
footer="[↑↓] navigate · [Enter] select · [Esc] stop"
|
||||
/>
|
||||
</ModalCard>
|
||||
);
|
||||
}
|
||||
|
||||
export const PlanCheckpointConfirm = React.memo(PlanCheckpointConfirmInner);
|
||||
|
||||
/**
|
||||
* Derive a status map from the plan + completion set + current step.
|
||||
* The currently-just-finished step always renders as "done" even if
|
||||
* completedStepIds hasn't been flushed yet (it gets added in the
|
||||
* same render cycle, order not guaranteed). Steps ahead of the
|
||||
* cursor are "pending"; the next step after the current one isn't
|
||||
* marked "running" because nothing is actually running while the
|
||||
* picker is up — that belongs to the post-continue state.
|
||||
*/
|
||||
function buildStatusMap(
|
||||
steps: PlanStep[] | undefined,
|
||||
completedStepIds: Set<string> | undefined,
|
||||
currentStepId: string,
|
||||
isLast: boolean,
|
||||
): Map<string, StepStatus> {
|
||||
const map = new Map<string, StepStatus>();
|
||||
if (!steps) return map;
|
||||
for (const step of steps) {
|
||||
if (completedStepIds?.has(step.id) || step.id === currentStepId) {
|
||||
map.set(step.id, "done");
|
||||
} else {
|
||||
map.set(step.id, "pending");
|
||||
}
|
||||
}
|
||||
if (isLast) {
|
||||
// Every step is done; leave as "done" — no "running" overlay.
|
||||
}
|
||||
return map;
|
||||
}
|
||||
+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,23 @@
|
||||
* 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 { 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 +40,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: "#67e8f9",
|
||||
}
|
||||
: mode === "checkpoint-revise"
|
||||
? {
|
||||
title: "revising — what should change before the next step?",
|
||||
icon: "✏",
|
||||
accent: "#fbbf24",
|
||||
}
|
||||
: mode === "choice-custom"
|
||||
? {
|
||||
title: "custom answer — type whatever fits",
|
||||
icon: "🔀",
|
||||
accent: "#f0abfc",
|
||||
}
|
||||
: {
|
||||
title: "refining — what should the model change?",
|
||||
icon: "✏",
|
||||
accent: "#fbbf24",
|
||||
};
|
||||
const hint =
|
||||
mode === "approve"
|
||||
? "Answer questions the plan raised, add constraints, or just press Enter to approve as-is."
|
||||
: "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);
|
||||
@@ -18,30 +18,29 @@ import { Box, Text } from "ink";
|
||||
import React from "react";
|
||||
import type { TypedPlanState } from "../../harvest.js";
|
||||
|
||||
type FieldColor = "cyan" | "green" | "yellow" | "red";
|
||||
type FieldColor = string;
|
||||
|
||||
export function PlanStateBlock({ planState }: { planState: TypedPlanState }) {
|
||||
const fields: Array<[string, string[], FieldColor, boolean]> = [];
|
||||
if (planState.subgoals.length) fields.push(["subgoals", planState.subgoals, "cyan", false]);
|
||||
if (planState.subgoals.length) fields.push(["subgoals", planState.subgoals, "#67e8f9", false]);
|
||||
if (planState.hypotheses.length)
|
||||
fields.push(["hypotheses", planState.hypotheses, "green", false]);
|
||||
fields.push(["hypotheses", planState.hypotheses, "#86efac", false]);
|
||||
if (planState.uncertainties.length)
|
||||
fields.push(["uncertainties", planState.uncertainties, "yellow", false]);
|
||||
fields.push(["uncertainties", planState.uncertainties, "#fcd34d", false]);
|
||||
if (planState.rejectedPaths.length)
|
||||
fields.push(["rejected", planState.rejectedPaths, "red", true]);
|
||||
fields.push(["rejected", planState.rejectedPaths, "#94a3b8", true]);
|
||||
if (fields.length === 0) return null;
|
||||
|
||||
return (
|
||||
<Box flexDirection="column" marginBottom={1}>
|
||||
{fields.map(([label, items, color, dim]) => (
|
||||
<Text key={label}>
|
||||
<Text color={color} bold dimColor={dim}>
|
||||
{"‹ "}
|
||||
{label}
|
||||
<Box key={label}>
|
||||
<Text backgroundColor={color} color="black" bold dimColor={dim}>
|
||||
{` ${label} ${items.length} `}
|
||||
</Text>
|
||||
<Text dimColor>{` (${items.length})`}</Text>
|
||||
<Text>{`: ${items.join(" · ")}`}</Text>
|
||||
</Text>
|
||||
<Text>{" "}</Text>
|
||||
<Text dimColor={dim}>{items.join(" · ")}</Text>
|
||||
</Box>
|
||||
))}
|
||||
</Box>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
/**
|
||||
* Shared compact renderer for a plan's structured step list. Used by
|
||||
* PlanConfirm (on approval) and PlanCheckpointConfirm (mid-execution)
|
||||
* so the user always sees the same visual representation of the plan.
|
||||
*
|
||||
* Layout per step:
|
||||
*
|
||||
* ● ✓ step-1 · Extract tokens into a module
|
||||
* ●●▶ step-2 · Migrate session cookies
|
||||
* ●●● step-3 · Update tests
|
||||
*
|
||||
* The risk gutter (1–3 dots, green/yellow/red) is the signal the user
|
||||
* learns to scan: high-risk steps are what deserves review before
|
||||
* approve; low-risk is noise.
|
||||
*/
|
||||
|
||||
import { Box, Text } from "ink";
|
||||
import React from "react";
|
||||
import type { PlanStep, PlanStepRisk } from "../../tools/plan.js";
|
||||
|
||||
export type StepStatus = "pending" | "running" | "done" | "skipped";
|
||||
|
||||
export interface PlanStepListProps {
|
||||
steps: PlanStep[];
|
||||
/**
|
||||
* Map of stepId → status. Missing ids default to "pending" so a
|
||||
* plan just submitted (no completions yet) renders cleanly.
|
||||
*/
|
||||
statuses?: Map<string, StepStatus> | Record<string, StepStatus>;
|
||||
/**
|
||||
* Optional current step — rendered with a `›` gutter mark so the
|
||||
* user sees which one just completed / is about to run.
|
||||
*/
|
||||
focusStepId?: string;
|
||||
}
|
||||
|
||||
function riskDots(risk: PlanStep["risk"]): {
|
||||
dots: string;
|
||||
color: "green" | "yellow" | "red" | "gray";
|
||||
} {
|
||||
switch (risk) {
|
||||
case "high":
|
||||
return { dots: "●●●", color: "red" };
|
||||
case "med":
|
||||
return { dots: "●● ", color: "yellow" };
|
||||
case "low":
|
||||
return { dots: "● ", color: "green" };
|
||||
default:
|
||||
return { dots: " ", color: "gray" };
|
||||
}
|
||||
}
|
||||
|
||||
function getStatus(stepId: string, statuses: PlanStepListProps["statuses"]): StepStatus {
|
||||
if (!statuses) return "pending";
|
||||
if (statuses instanceof Map) {
|
||||
return statuses.get(stepId) ?? "pending";
|
||||
}
|
||||
return statuses[stepId] ?? "pending";
|
||||
}
|
||||
|
||||
function PlanStepListInner({ steps, statuses, focusStepId }: PlanStepListProps) {
|
||||
if (steps.length === 0) return null;
|
||||
const hasAnyRisk = steps.some((s) => s.risk !== undefined);
|
||||
const doneCount = Array.from({ length: steps.length }, (_, i) =>
|
||||
getStatus(steps[i]!.id, statuses),
|
||||
).filter((s) => s === "done").length;
|
||||
const pct = Math.round((doneCount / steps.length) * 100);
|
||||
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
<Box>
|
||||
<Text dimColor>
|
||||
{`${steps.length} step${steps.length === 1 ? "" : "s"}`}
|
||||
{doneCount > 0 ? ` · ${doneCount}/${steps.length} done (${pct}%)` : ""}
|
||||
{hasAnyRisk ? " · risk: " : ""}
|
||||
</Text>
|
||||
{hasAnyRisk ? <RiskLegend /> : null}
|
||||
</Box>
|
||||
<Box flexDirection="column" marginTop={1}>
|
||||
{steps.map((step) => {
|
||||
const status = getStatus(step.id, statuses);
|
||||
const focus = focusStepId === step.id;
|
||||
const risk = riskDots(step.risk);
|
||||
const titleDim = status === "done" || status === "skipped";
|
||||
return (
|
||||
<Box key={step.id}>
|
||||
<Text color={focus ? "#67e8f9" : "gray"} bold={focus}>
|
||||
{focus ? "▸ " : " "}
|
||||
</Text>
|
||||
<Text color={risk.color} bold>
|
||||
{risk.dots}
|
||||
</Text>
|
||||
<Text> </Text>
|
||||
<StatusBadge status={status} />
|
||||
<Text> </Text>
|
||||
<Text dimColor={titleDim} bold={focus}>
|
||||
{`${step.id} · ${step.title}`}
|
||||
</Text>
|
||||
</Box>
|
||||
);
|
||||
})}
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Status pill — solid-bg badge per step state. Reads at a glance
|
||||
* better than a glyph + color text: ` DONE `, ` RUN `, ` SKIP `,
|
||||
* ` PEND `. The label widths are normalized so the column under
|
||||
* the badge stays aligned even when statuses mix.
|
||||
*/
|
||||
function StatusBadge({ status }: { status: StepStatus }) {
|
||||
switch (status) {
|
||||
case "done":
|
||||
return (
|
||||
<Text backgroundColor="#4ade80" color="black" bold>
|
||||
{" ✓ DONE "}
|
||||
</Text>
|
||||
);
|
||||
case "running":
|
||||
return (
|
||||
<Text backgroundColor="#67e8f9" color="black" bold>
|
||||
{" ▶ RUN "}
|
||||
</Text>
|
||||
);
|
||||
case "skipped":
|
||||
return (
|
||||
<Text backgroundColor="#94a3b8" color="black" bold>
|
||||
{" — SKIP "}
|
||||
</Text>
|
||||
);
|
||||
default:
|
||||
return (
|
||||
<Text color="#94a3b8" dimColor>
|
||||
{" ☐ PEND "}
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function RiskLegend() {
|
||||
return (
|
||||
<Box>
|
||||
<Text color="green">●</Text>
|
||||
<Text dimColor> low </Text>
|
||||
<Text color="yellow">●●</Text>
|
||||
<Text dimColor> med </Text>
|
||||
<Text color="red">●●●</Text>
|
||||
<Text dimColor> high</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
export const PlanStepList = React.memo(PlanStepListInner);
|
||||
|
||||
export function riskOf(step: PlanStep): PlanStepRisk | undefined {
|
||||
return step.risk;
|
||||
}
|
||||
+513
-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,507 @@ export interface PromptInputProps {
|
||||
onSubmit: (v: string) => void;
|
||||
disabled?: boolean;
|
||||
placeholder?: string;
|
||||
/**
|
||||
* History recall. Fired when ↑/↓ hits a buffer boundary (empty
|
||||
* buffer, or cursor already at the first/last line of a multi-line
|
||||
* buffer). Parent walks its prompt history and swaps the value via
|
||||
* `onChange`. Absent → keys are consumed silently.
|
||||
*/
|
||||
onHistoryPrev?: () => void;
|
||||
onHistoryNext?: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Input box with real cursor support. ←/→ move one column, ↑/↓ move
|
||||
* across lines in multi-line buffers, Ctrl+A / Ctrl+E jump to
|
||||
* start/end of the current line. Backspace deletes before cursor,
|
||||
* Delete deletes under cursor. Multi-line composition via Ctrl+J,
|
||||
* Shift+Enter, or bash-style `\<Enter>`.
|
||||
*
|
||||
* Cursor state lives locally. When the parent replaces `value` out
|
||||
* of band (history recall, slash completion, setup wizard) the
|
||||
* cursor jumps to end; the `lastLocalValueRef` guards distinguishes
|
||||
* that case from our own edits.
|
||||
*/
|
||||
export function PromptInput({
|
||||
value,
|
||||
onChange,
|
||||
onSubmit,
|
||||
disabled,
|
||||
placeholder,
|
||||
onHistoryPrev,
|
||||
onHistoryNext,
|
||||
}: PromptInputProps) {
|
||||
const [cursor, setCursor] = useState(value.length);
|
||||
// Tracks the last `value` we ourselves produced via onChange. If the
|
||||
// incoming `value` prop diverges from this, the parent (or some other
|
||||
// source) replaced the buffer — we reset the cursor to end.
|
||||
|
||||
// Paste registry — keyed by sentinel id, holds original content.
|
||||
const pastesRef = useRef<Map<number, PasteEntry>>(new Map());
|
||||
const nextPasteIdRef = useRef<number>(0);
|
||||
|
||||
// Track external value replacement (history recall, slash completion).
|
||||
// When the parent swaps `value` we snap cursor to end.
|
||||
const lastLocalValueRef = useRef(value);
|
||||
if (value !== lastLocalValueRef.current) {
|
||||
lastLocalValueRef.current = value;
|
||||
if (cursor !== value.length) {
|
||||
// Conditional setState during render is the "derived state" pattern;
|
||||
// React schedules the re-render and the else branch of the `if`
|
||||
// prevents infinite loops.
|
||||
setCursor(value.length);
|
||||
}
|
||||
if (cursor !== value.length) setCursor(value.length);
|
||||
}
|
||||
|
||||
// Shared ticker drives the cursor blink. Dividing the tick by 4 lands
|
||||
// the visible on/off cycle around 480ms — standard cursor cadence.
|
||||
const tick = useTick();
|
||||
const showCursor = disabled ? false : Math.floor(tick / 4) % 2 === 0;
|
||||
/**
|
||||
* Register one paste blob and insert its sentinel at the current
|
||||
* cursor. Used both by `paste` events from the stdin reader (the
|
||||
* normal path on terminals that support DECSET 2004) and by the
|
||||
* fallback path inside `processMultilineKey` for chunks that
|
||||
* arrived without bracketed-paste markers.
|
||||
*/
|
||||
const registerPaste = (content: string) => {
|
||||
const v = lastLocalValueRef.current;
|
||||
const c = cursor;
|
||||
const id = nextPasteIdRef.current % PASTE_SENTINEL_RANGE;
|
||||
nextPasteIdRef.current = id + 1;
|
||||
pastesRef.current.set(id, makePasteEntry(id, content));
|
||||
const sentinel = encodePasteSentinel(id);
|
||||
const next = v.slice(0, c) + sentinel + v.slice(c);
|
||||
lastLocalValueRef.current = next;
|
||||
onChange(next);
|
||||
setCursor(c + 1);
|
||||
};
|
||||
|
||||
useInput(
|
||||
(input, key) => {
|
||||
const ke: MultilineKey = {
|
||||
input,
|
||||
return: key.return,
|
||||
shift: key.shift,
|
||||
ctrl: key.ctrl,
|
||||
meta: key.meta,
|
||||
backspace: key.backspace,
|
||||
delete: key.delete,
|
||||
tab: key.tab,
|
||||
upArrow: key.upArrow,
|
||||
downArrow: key.downArrow,
|
||||
leftArrow: key.leftArrow,
|
||||
rightArrow: key.rightArrow,
|
||||
escape: key.escape,
|
||||
pageUp: key.pageUp,
|
||||
pageDown: key.pageDown,
|
||||
};
|
||||
const action = processMultilineKey(value, cursor, ke);
|
||||
if (action.next !== null) {
|
||||
lastLocalValueRef.current = action.next;
|
||||
onChange(action.next);
|
||||
useKeystroke((ev) => {
|
||||
if (disabled) return;
|
||||
if (ev.paste) {
|
||||
// Bracketed-paste content delivered by the stdin reader.
|
||||
// Insert as one sentinel regardless of length.
|
||||
if (ev.input.length > 0) registerPaste(ev.input);
|
||||
return;
|
||||
}
|
||||
const key: MultilineKey = {
|
||||
input: ev.input,
|
||||
return: ev.return,
|
||||
shift: ev.shift,
|
||||
ctrl: ev.ctrl,
|
||||
meta: ev.meta,
|
||||
backspace: ev.backspace,
|
||||
delete: ev.delete,
|
||||
tab: ev.tab,
|
||||
upArrow: ev.upArrow,
|
||||
downArrow: ev.downArrow,
|
||||
leftArrow: ev.leftArrow,
|
||||
rightArrow: ev.rightArrow,
|
||||
escape: ev.escape,
|
||||
pageUp: ev.pageUp,
|
||||
pageDown: ev.pageDown,
|
||||
};
|
||||
const action = processMultilineKey(value, cursor, key);
|
||||
if (action.pasteRequest) {
|
||||
registerPaste(action.pasteRequest.content);
|
||||
return;
|
||||
}
|
||||
if (action.next !== null) {
|
||||
lastLocalValueRef.current = action.next;
|
||||
onChange(action.next);
|
||||
}
|
||||
if (action.cursor !== null) {
|
||||
setCursor(action.cursor);
|
||||
}
|
||||
if (action.submit) {
|
||||
const raw = action.submitValue ?? value;
|
||||
const expanded = expandPasteSentinels(raw, pastesRef.current);
|
||||
// GC unreachable paste entries — anything backspace'd out of
|
||||
// the buffer before submit. Keeps the registry from growing
|
||||
// unbounded across many turns.
|
||||
const reachable = new Set(listPasteIdsInBuffer(raw));
|
||||
for (const id of pastesRef.current.keys()) {
|
||||
if (!reachable.has(id)) pastesRef.current.delete(id);
|
||||
}
|
||||
if (action.cursor !== null) {
|
||||
setCursor(action.cursor);
|
||||
}
|
||||
if (action.submit) onSubmit(action.submitValue ?? value);
|
||||
},
|
||||
{ isActive: !disabled },
|
||||
);
|
||||
onSubmit(expanded);
|
||||
}
|
||||
if (action.historyHandoff === "prev") onHistoryPrev?.();
|
||||
if (action.historyHandoff === "next") onHistoryNext?.();
|
||||
}, !disabled);
|
||||
|
||||
// ── Render ──────────────────────────────────────────────────────
|
||||
|
||||
const { stdout } = useStdout();
|
||||
const cols = stdout?.columns ?? 80;
|
||||
const narrow = cols <= 90;
|
||||
const promptBody = narrow ? "› " : "you › ";
|
||||
const promptPrefix = BAR + promptBody;
|
||||
const continuationIndent = BAR + " ".repeat(promptBody.length);
|
||||
const prefixCells = promptPrefix.length;
|
||||
// Reserve 2 cells for the surrounding `paddingX={1}` plus 1 cell
|
||||
// for the cursor block when at end-of-line. Net visible budget per
|
||||
// line.
|
||||
const visibleCells = Math.max(8, cols - prefixCells - 3);
|
||||
|
||||
const placeholderActive = narrow
|
||||
? "type a message, or /command"
|
||||
: "type a message, or /command · [Ctrl+J] newline · [Ctrl+P/N] history";
|
||||
const effectivePlaceholder = disabled
|
||||
? (placeholder ?? "…waiting for response… · [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 ? (
|
||||
<Box>
|
||||
<Text color={barColorAt(0)}>{BAR}</Text>
|
||||
<Text dimColor>{continuationIndent.slice(BAR.length)}</Text>
|
||||
<Text dimColor>[Esc] to stop</Text>
|
||||
</Box>
|
||||
) : null}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
function LineWithCursor({
|
||||
line,
|
||||
col,
|
||||
showCursor,
|
||||
borderColor,
|
||||
}: {
|
||||
// ── PromptLine ────────────────────────────────────────────────────
|
||||
|
||||
interface PromptLineProps {
|
||||
line: string;
|
||||
col: number;
|
||||
showCursor: boolean;
|
||||
borderColor: "cyan" | "gray";
|
||||
}) {
|
||||
const before = line.slice(0, col);
|
||||
const atCursor = line.slice(col, col + 1);
|
||||
const after = line.slice(col + 1);
|
||||
if (atCursor.length === 0) {
|
||||
// Cursor sits past the last char of this line (end-of-line). Render
|
||||
// a trailing block so the user sees where they're typing next.
|
||||
isFirst: boolean;
|
||||
isCursorLine: boolean;
|
||||
cursorCol: number | null;
|
||||
/** True when the cursor block / inverse char should be drawn this tick. */
|
||||
cursorVisible: boolean;
|
||||
showPlaceholder: boolean;
|
||||
placeholderText: string;
|
||||
promptPrefix: string;
|
||||
continuationIndent: string;
|
||||
visibleCells: number;
|
||||
accentColor: "cyan" | "gray";
|
||||
/** Animated gradient color for the leading ▎ bar. Differs per row + tick. */
|
||||
barColor: string;
|
||||
pastes: ReadonlyMap<number, PasteEntry>;
|
||||
disabled: boolean;
|
||||
}
|
||||
|
||||
function PromptLine({
|
||||
line,
|
||||
isFirst,
|
||||
isCursorLine,
|
||||
cursorCol,
|
||||
cursorVisible,
|
||||
showPlaceholder,
|
||||
placeholderText,
|
||||
promptPrefix,
|
||||
continuationIndent,
|
||||
visibleCells,
|
||||
accentColor,
|
||||
barColor,
|
||||
pastes,
|
||||
disabled,
|
||||
}: PromptLineProps) {
|
||||
// The leading BAR cells of every prefix/continuation are the left
|
||||
// anchor bar — render them as a separate span colored by the
|
||||
// animated gradient so the bar appears to flow vertically.
|
||||
const barText = promptPrefix.slice(0, BAR.length);
|
||||
const bodyPrefix = promptPrefix.slice(BAR.length);
|
||||
const bodyContinuation = continuationIndent.slice(BAR.length);
|
||||
if (showPlaceholder) {
|
||||
return (
|
||||
<>
|
||||
<Text>{before}</Text>
|
||||
<Text color={borderColor}>{showCursor ? "▌" : " "}</Text>
|
||||
</>
|
||||
<Box>
|
||||
<Text color={barColor}>{barText}</Text>
|
||||
<Text bold color={accentColor}>
|
||||
{bodyPrefix}
|
||||
</Text>
|
||||
{!disabled ? <Text color={accentColor}>{cursorVisible ? "▌" : " "}</Text> : null}
|
||||
<Text dimColor>{placeholderText}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
const viewport = buildViewport(line, isCursorLine ? cursorCol : null, visibleCells, pastes);
|
||||
|
||||
// Render: prefix + (left marker?) + segments-with-cursor + (right marker?)
|
||||
return (
|
||||
<>
|
||||
<Text>{before}</Text>
|
||||
<Text inverse={showCursor}>{atCursor}</Text>
|
||||
<Text>{after}</Text>
|
||||
</>
|
||||
<Box>
|
||||
<Text color={barColor}>{barText}</Text>
|
||||
{isFirst ? (
|
||||
<Text bold color={accentColor}>
|
||||
{bodyPrefix}
|
||||
</Text>
|
||||
) : (
|
||||
<Text dimColor>{bodyContinuation}</Text>
|
||||
)}
|
||||
{viewport.hiddenLeft ? (
|
||||
<Text color="gray" dimColor>
|
||||
‹
|
||||
</Text>
|
||||
) : null}
|
||||
<ViewportContent
|
||||
segments={viewport.segments}
|
||||
cursorCell={isCursorLine ? viewport.cursorCell : null}
|
||||
accentColor={accentColor}
|
||||
cursorVisible={cursorVisible}
|
||||
/>
|
||||
{viewport.hiddenRight ? (
|
||||
<Text color="gray" dimColor>
|
||||
›
|
||||
</Text>
|
||||
) : null}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
// ── ViewportContent ────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Render a viewport's segments with a cursor block at `cursorCell`.
|
||||
* Walks segments in order; the cursor splits at most one segment
|
||||
* (the one containing the cursor cell), producing an inverted char
|
||||
* at that position.
|
||||
*
|
||||
* End-of-line cursor (cursorCell points past the last cell of the
|
||||
* last segment): emit a trailing block.
|
||||
*/
|
||||
function ViewportContent({
|
||||
segments,
|
||||
cursorCell,
|
||||
accentColor,
|
||||
cursorVisible,
|
||||
}: {
|
||||
segments: Segment[];
|
||||
cursorCell: number | null;
|
||||
accentColor: "cyan" | "gray";
|
||||
cursorVisible: boolean;
|
||||
}) {
|
||||
// No cursor on this line — straight render.
|
||||
if (cursorCell === null) {
|
||||
return <>{segments.map((seg, i) => renderSegment(seg, i, false))}</>;
|
||||
}
|
||||
|
||||
// Walk segments tallying cells; once we reach `cursorCell`, split
|
||||
// the segment to insert the cursor block.
|
||||
const out: React.ReactNode[] = [];
|
||||
let cells = 0;
|
||||
let placed = false;
|
||||
for (let i = 0; i < segments.length; i++) {
|
||||
const seg = segments[i]!;
|
||||
const segCells = segmentCells(seg);
|
||||
if (placed) {
|
||||
out.push(renderSegment(seg, i, false));
|
||||
continue;
|
||||
}
|
||||
if (cursorCell >= cells + segCells) {
|
||||
// Cursor isn't in this segment.
|
||||
out.push(renderSegment(seg, i, false));
|
||||
cells += segCells;
|
||||
continue;
|
||||
}
|
||||
// Cursor lands inside this segment.
|
||||
if (seg.kind === "paste") {
|
||||
// The cursor is "on" the paste sentinel — render the paste
|
||||
// block inversed so the user sees they're at it. Inverse
|
||||
// toggles with the blink so the paste sentinel stays
|
||||
// legible during the cursor's "off" half-cycle.
|
||||
out.push(
|
||||
<Text key={`p-${i}-cursor`} color="magenta" bold inverse={cursorVisible}>
|
||||
{seg.label}
|
||||
</Text>,
|
||||
);
|
||||
placed = true;
|
||||
cells += segCells;
|
||||
continue;
|
||||
}
|
||||
// text segment — split before/at-cursor/after by cell offset.
|
||||
const offsetIntoSeg = cursorCell - cells;
|
||||
const split = splitTextByCells(seg.text, offsetIntoSeg);
|
||||
if (split.before.length > 0) {
|
||||
out.push(<Text key={`t-${i}-b`}>{split.before}</Text>);
|
||||
}
|
||||
if (split.atCursor.length > 0) {
|
||||
out.push(
|
||||
<Text key={`t-${i}-c`} inverse={cursorVisible} color={accentColor}>
|
||||
{split.atCursor}
|
||||
</Text>,
|
||||
);
|
||||
} else {
|
||||
// Cursor sits past the segment's last char (end-of-text in this
|
||||
// segment). Render block here, blinking with the tick.
|
||||
out.push(
|
||||
<Text key={`t-${i}-c-eol`} color={accentColor}>
|
||||
{cursorVisible ? "▌" : " "}
|
||||
</Text>,
|
||||
);
|
||||
}
|
||||
if (split.after.length > 0) {
|
||||
out.push(<Text key={`t-${i}-a`}>{split.after}</Text>);
|
||||
}
|
||||
placed = true;
|
||||
cells += segCells;
|
||||
}
|
||||
|
||||
// Cursor sits past every segment (end of line).
|
||||
if (!placed) {
|
||||
out.push(
|
||||
<Text key="cursor-eol" color={accentColor}>
|
||||
{cursorVisible ? "▌" : " "}
|
||||
</Text>,
|
||||
);
|
||||
}
|
||||
|
||||
return <>{out}</>;
|
||||
}
|
||||
|
||||
function segmentCells(seg: Segment): number {
|
||||
if (seg.kind === "paste") return seg.label.length;
|
||||
return stringCells(seg.text);
|
||||
}
|
||||
|
||||
/**
|
||||
* Split a text string at a cell offset, returning the chars before
|
||||
* the offset, the char AT the offset (the cursor block highlights
|
||||
* it), and the chars after. A wide char that straddles the offset
|
||||
* is treated as the cursor's char.
|
||||
*/
|
||||
function splitTextByCells(
|
||||
text: string,
|
||||
cellOffset: number,
|
||||
): { before: string; atCursor: string; after: string } {
|
||||
let cells = 0;
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
const ch = text[i]!;
|
||||
const cw = charCellsForText(ch);
|
||||
if (cells === cellOffset) {
|
||||
return { before: text.slice(0, i), atCursor: ch, after: text.slice(i + 1) };
|
||||
}
|
||||
if (cells + cw > cellOffset) {
|
||||
// The wide char straddles the offset — show it as the cursor char.
|
||||
return { before: text.slice(0, i), atCursor: ch, after: text.slice(i + 1) };
|
||||
}
|
||||
cells += cw;
|
||||
}
|
||||
// Cursor at end of text.
|
||||
return { before: text, atCursor: "", after: "" };
|
||||
}
|
||||
|
||||
/**
|
||||
* Local cell-counting helper — duplicates `charCells` from
|
||||
* prompt-viewport but inlined to avoid a back-and-forth import (this
|
||||
* function is hot per-keystroke). Keep in sync.
|
||||
*/
|
||||
function charCellsForText(ch: string): number {
|
||||
const code = ch.charCodeAt(0);
|
||||
if (code < 0x20 || code === 0x7f) return 0;
|
||||
if (code < 0x1100) return 1;
|
||||
if (code >= 0x1100 && code <= 0x115f) return 2;
|
||||
if (code >= 0x2e80 && code <= 0x303e) return 2;
|
||||
if (code >= 0x3041 && code <= 0x33ff) return 2;
|
||||
if (code >= 0x3400 && code <= 0x4dbf) return 2;
|
||||
if (code >= 0x4e00 && code <= 0x9fff) return 2;
|
||||
if (code >= 0xa000 && code <= 0xa4cf) return 2;
|
||||
if (code >= 0xac00 && code <= 0xd7a3) return 2;
|
||||
if (code >= 0xf900 && code <= 0xfaff) return 2;
|
||||
if (code >= 0xfe30 && code <= 0xfe4f) return 2;
|
||||
if (code >= 0xff00 && code <= 0xff60) return 2;
|
||||
if (code >= 0xffe0 && code <= 0xffe6) return 2;
|
||||
return 1;
|
||||
}
|
||||
|
||||
function renderSegment(seg: Segment, key: number, _inverse: boolean): React.ReactNode {
|
||||
if (seg.kind === "text") {
|
||||
return <Text key={`s-${key}`}>{seg.text}</Text>;
|
||||
}
|
||||
// Paste sentinels render as a fuchsia bg-pill so they're visually
|
||||
// distinct from typed text — the user can see "this is the
|
||||
// collapsed paste, not 47 lines of code I typed". Matches the
|
||||
// bg-pill idiom used elsewhere (mode bars, tool names).
|
||||
return (
|
||||
<Text key={`s-${key}`} backgroundColor="#f0abfc" color="black" bold>
|
||||
{seg.label}
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
|
||||
// ── collapse helper (preserved from v1) ────────────────────────────
|
||||
|
||||
type RenderItem =
|
||||
| { kind: "line"; line: string; originalIndex: number }
|
||||
| { kind: "skip"; linesHidden: number };
|
||||
|
||||
const COLLAPSE_THRESHOLD = 20;
|
||||
const COLLAPSE_HEAD_LINES = 3;
|
||||
const COLLAPSE_TAIL_LINES = 2;
|
||||
|
||||
export function collapseLinesForDisplay(lines: string[], cursorLine: number): RenderItem[] {
|
||||
if (lines.length <= COLLAPSE_THRESHOLD) {
|
||||
return lines.map((line, i) => ({ kind: "line" as const, line, originalIndex: i }));
|
||||
}
|
||||
const keep = new Set<number>();
|
||||
for (let i = 0; i < COLLAPSE_HEAD_LINES && i < lines.length; i++) keep.add(i);
|
||||
for (let i = Math.max(0, lines.length - COLLAPSE_TAIL_LINES); i < lines.length; i++) keep.add(i);
|
||||
if (cursorLine >= 0 && cursorLine < lines.length) keep.add(cursorLine);
|
||||
const sorted = [...keep].sort((a, b) => a - b);
|
||||
const out: RenderItem[] = [];
|
||||
let prev = -1;
|
||||
for (const idx of sorted) {
|
||||
if (idx - prev > 1) {
|
||||
out.push({ kind: "skip", linesHidden: idx - prev - 1 });
|
||||
}
|
||||
out.push({ kind: "line", line: lines[idx] ?? "", originalIndex: idx });
|
||||
prev = idx;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -28,12 +28,18 @@ export function RecordView({ rec, compact = false }: RecordViewProps) {
|
||||
const toolContentMax = compact ? 200 : 400;
|
||||
|
||||
if (rec.role === "user") {
|
||||
// Continuation indent of 6 spaces matches the `you › ` prefix width
|
||||
// so wrapped multi-line user messages align under the body text
|
||||
// instead of jumping to column 0.
|
||||
const content = rec.content.includes("\n")
|
||||
? rec.content.split("\n").join("\n ")
|
||||
: rec.content;
|
||||
return (
|
||||
<Box marginTop={1}>
|
||||
<Text bold color="cyan">
|
||||
you ›{" "}
|
||||
</Text>
|
||||
<Text>{rec.content}</Text>
|
||||
<Text>{content}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -59,6 +59,7 @@ export function ReplayApp({ meta, pages }: ReplayAppProps) {
|
||||
cacheHitRatio: cumStats.cacheHitRatio,
|
||||
// Replay is read-only — no live last-turn prompt tokens to show.
|
||||
lastPromptTokens: 0,
|
||||
lastTurnCostUsd: 0,
|
||||
};
|
||||
|
||||
const prefixHash =
|
||||
|
||||
+17
-14
@@ -9,8 +9,9 @@
|
||||
* rendering quirk bundled (`ink-text-input`); adding more is low value.
|
||||
*/
|
||||
|
||||
import { Box, Text, useInput } from "ink";
|
||||
import { Box, Text } from "ink";
|
||||
import React, { useState } from "react";
|
||||
import { useKeystroke } from "./keystroke-context.js";
|
||||
|
||||
export interface SelectItem<V extends string = string> {
|
||||
/** Stable identifier — returned to caller on submit. */
|
||||
@@ -30,7 +31,7 @@ export interface SingleSelectProps<V extends string> {
|
||||
onCancel?: () => void;
|
||||
/**
|
||||
* Optional footer rendered dim beneath the list, e.g.
|
||||
* `"↑/↓ navigate · Enter select · Esc cancel"`. Makes keyboard
|
||||
* `"[↑↓] navigate · [Enter] select · [Esc] cancel"`. Makes keyboard
|
||||
* affordances discoverable — otherwise new users hit `y`/`n` and
|
||||
* wonder why nothing happens.
|
||||
*/
|
||||
@@ -50,15 +51,16 @@ export function SingleSelect<V extends string>({
|
||||
);
|
||||
const [index, setIndex] = useState(initialIndex === -1 ? 0 : initialIndex);
|
||||
|
||||
useInput((_input, key) => {
|
||||
if (key.upArrow) {
|
||||
useKeystroke((ev) => {
|
||||
if (ev.paste) return;
|
||||
if (ev.upArrow) {
|
||||
setIndex((i) => findNextEnabled(items, i, -1));
|
||||
} else if (key.downArrow) {
|
||||
} else if (ev.downArrow) {
|
||||
setIndex((i) => findNextEnabled(items, i, +1));
|
||||
} else if (key.return) {
|
||||
} else if (ev.return) {
|
||||
const chosen = items[index];
|
||||
if (chosen && !chosen.disabled) onSubmit(chosen.value);
|
||||
} else if (key.escape && onCancel) {
|
||||
} else if (ev.escape && onCancel) {
|
||||
onCancel();
|
||||
}
|
||||
});
|
||||
@@ -87,7 +89,7 @@ export interface MultiSelectProps<V extends string> {
|
||||
initialSelected?: V[];
|
||||
onSubmit: (values: V[]) => void;
|
||||
onCancel?: () => void;
|
||||
/** Footer hint under the list — e.g. "space toggle · enter confirm". */
|
||||
/** Footer hint under the list — e.g. "[Space] toggle · [Enter] confirm". */
|
||||
footer?: string;
|
||||
}
|
||||
|
||||
@@ -104,12 +106,13 @@ export function MultiSelect<V extends string>({
|
||||
});
|
||||
const [selected, setSelected] = useState<Set<V>>(new Set(initialSelected));
|
||||
|
||||
useInput((input, key) => {
|
||||
if (key.upArrow) {
|
||||
useKeystroke((ev) => {
|
||||
if (ev.paste) return;
|
||||
if (ev.upArrow) {
|
||||
setIndex((i) => findNextEnabled(items, i, -1));
|
||||
} else if (key.downArrow) {
|
||||
} else if (ev.downArrow) {
|
||||
setIndex((i) => findNextEnabled(items, i, +1));
|
||||
} else if (input === " ") {
|
||||
} else if (ev.input === " ") {
|
||||
const item = items[index];
|
||||
if (!item || item.disabled) return;
|
||||
setSelected((prev) => {
|
||||
@@ -118,13 +121,13 @@ export function MultiSelect<V extends string>({
|
||||
else next.add(item.value);
|
||||
return next;
|
||||
});
|
||||
} else if (key.return) {
|
||||
} else if (ev.return) {
|
||||
// Preserve catalog order rather than insertion order, so reruns
|
||||
// produce the same spec list for the same checkbox set — makes the
|
||||
// `config.json` diff trivially stable.
|
||||
const ordered = items.filter((i) => selected.has(i.value)).map((i) => i.value);
|
||||
onSubmit(ordered);
|
||||
} else if (key.escape && onCancel) {
|
||||
} else if (ev.escape && onCancel) {
|
||||
onCancel();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -48,7 +48,7 @@ export function SessionPicker({
|
||||
onSubmit={(v) => onChoose(v as SessionChoice)}
|
||||
/>
|
||||
<Box marginTop={1}>
|
||||
<Text dimColor>↑↓ to move · Enter to pick</Text>
|
||||
<Text dimColor>[↑↓] navigate · [Enter] select</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
|
||||
+47
-42
@@ -1,5 +1,6 @@
|
||||
import { Box, Text } from "ink";
|
||||
import React from "react";
|
||||
import { ModalCard } from "./ModalCard.js";
|
||||
import { SingleSelect } from "./Select.js";
|
||||
|
||||
export type ShellConfirmChoice = "run_once" | "always_allow" | "deny";
|
||||
@@ -11,6 +12,13 @@ export interface ShellConfirmProps {
|
||||
* "always allow". Typically the first 1-2 tokens of `command`.
|
||||
*/
|
||||
allowPrefix: string;
|
||||
/**
|
||||
* Which tool is asking. `run_background` spawns via JobRegistry and
|
||||
* returns early; `run_command` (default) blocks until the process
|
||||
* exits. Shown as a hint in the modal so the user knows whether
|
||||
* approving will block the TUI or not.
|
||||
*/
|
||||
kind?: "run_command" | "run_background";
|
||||
onChoose: (choice: ShellConfirmChoice) => void;
|
||||
}
|
||||
|
||||
@@ -25,51 +33,48 @@ export interface ShellConfirmProps {
|
||||
* Arrow keys + Enter. No y/n hotkey — too easy to trigger by accident
|
||||
* when the user was mid-typing a response.
|
||||
*/
|
||||
export function ShellConfirm({ command, allowPrefix, onChoose }: ShellConfirmProps) {
|
||||
export function ShellConfirm({ command, allowPrefix, kind, onChoose }: ShellConfirmProps) {
|
||||
const isBackground = kind === "run_background";
|
||||
const subtitle = isBackground
|
||||
? "long-running process — keeps running after approval, /kill to stop"
|
||||
: "model wants to run a shell command";
|
||||
return (
|
||||
<Box flexDirection="column" borderStyle="round" borderColor="yellow" paddingX={1} marginY={1}>
|
||||
<Box>
|
||||
<Text bold color="yellow">
|
||||
▸ model wants to run a shell command
|
||||
<ModalCard
|
||||
accent="#f87171"
|
||||
icon={isBackground ? "⏱" : "⚡"}
|
||||
title={isBackground ? "background process" : "shell command"}
|
||||
subtitle={subtitle}
|
||||
>
|
||||
<Box marginBottom={1}>
|
||||
<Text dimColor>{"$ "}</Text>
|
||||
<Text color="#67e8f9" bold>
|
||||
{command}
|
||||
</Text>
|
||||
</Box>
|
||||
<Box>
|
||||
<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.",
|
||||
},
|
||||
{
|
||||
value: "deny",
|
||||
label: "Deny",
|
||||
hint: "Tell the model the user refused; it will continue without this command.",
|
||||
},
|
||||
]}
|
||||
onSubmit={(v) => onChoose(v as ShellConfirmChoice)}
|
||||
onCancel={() => onChoose("deny")}
|
||||
footer="[↑↓] navigate · [Enter] select · [Esc] deny"
|
||||
/>
|
||||
</ModalCard>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -39,7 +39,7 @@ export function SlashArgPicker({
|
||||
// Hint mode: a single dim row explaining the argsHint + summary.
|
||||
if (kind === "hint") {
|
||||
return (
|
||||
<Box paddingX={1}>
|
||||
<Box paddingX={1} marginTop={1}>
|
||||
<Text dimColor>
|
||||
{" "}
|
||||
<Text bold>/{spec.cmd}</Text>
|
||||
@@ -52,7 +52,7 @@ export function SlashArgPicker({
|
||||
if (matches === null) return null;
|
||||
if (matches.length === 0) {
|
||||
return (
|
||||
<Box flexDirection="column" paddingX={1}>
|
||||
<Box flexDirection="column" paddingX={1} marginTop={1}>
|
||||
<Text dimColor>
|
||||
{" "}
|
||||
<Text bold>/{spec.cmd}</Text>
|
||||
@@ -71,7 +71,7 @@ export function SlashArgPicker({
|
||||
const hiddenAbove = windowStart;
|
||||
const hiddenBelow = total - windowStart - shown.length;
|
||||
return (
|
||||
<Box flexDirection="column" paddingX={1}>
|
||||
<Box flexDirection="column" paddingX={1} marginTop={1}>
|
||||
<Text dimColor>
|
||||
{" "}
|
||||
<Text bold>/{spec.cmd}</Text>
|
||||
|
||||
@@ -28,7 +28,7 @@ export function SlashSuggestions({
|
||||
if (matches === null) return null;
|
||||
if (matches.length === 0) {
|
||||
return (
|
||||
<Box paddingX={1}>
|
||||
<Box paddingX={1} marginTop={1}>
|
||||
<Text color="yellow">no slash command matches that prefix</Text>
|
||||
<Text dimColor> — Backspace to edit, or /help for the full list</Text>
|
||||
</Box>
|
||||
@@ -45,7 +45,7 @@ export function SlashSuggestions({
|
||||
const hiddenAbove = windowStart;
|
||||
const hiddenBelow = total - windowStart - shown.length;
|
||||
return (
|
||||
<Box flexDirection="column" paddingX={1}>
|
||||
<Box flexDirection="column" paddingX={1} marginTop={1}>
|
||||
{hiddenAbove > 0 ? <Text dimColor> ↑ {hiddenAbove} more above</Text> : null}
|
||||
{shown.map((spec, i) => (
|
||||
<SuggestionRow key={spec.cmd} spec={spec} isSelected={windowStart + i === selectedIndex} />
|
||||
@@ -57,29 +57,23 @@ export function SlashSuggestions({
|
||||
}
|
||||
|
||||
function SuggestionRow({ spec, isSelected }: { spec: SlashCommandSpec; isSelected: boolean }) {
|
||||
const marker = isSelected ? "▸" : " ";
|
||||
const name = `/${spec.cmd}`;
|
||||
const argsSuffix = spec.argsHint ? ` ${spec.argsHint}` : "";
|
||||
// Selected row gets full cyan coloring so it pops out against the
|
||||
// dimmed others — mirrors the style GitHub Issues / Discord use
|
||||
// for focused dropdown rows.
|
||||
// Selected row gets a solid-bg highlight (cyan) so it pops like
|
||||
// an editor's focused autocomplete entry. Non-selected rows stay
|
||||
// dim with a leading bullet for vertical rhythm.
|
||||
if (isSelected) {
|
||||
return (
|
||||
<Box>
|
||||
<Text bold color="cyan">
|
||||
{marker} {name.padEnd(12)}
|
||||
{argsSuffix.padEnd(16)}
|
||||
<Text backgroundColor="#67e8f9" color="black" bold>
|
||||
{` ▸ ${name.padEnd(12)}${argsSuffix.padEnd(16)} ${spec.summary} `}
|
||||
</Text>
|
||||
<Text color="cyan"> {spec.summary}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Box>
|
||||
<Text dimColor>
|
||||
{marker} {name.padEnd(12)}
|
||||
{argsSuffix.padEnd(16)} {spec.summary}
|
||||
</Text>
|
||||
<Text color="#94a3b8">{` ${name.padEnd(12)}${argsSuffix.padEnd(16)} ${spec.summary}`}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
+232
-82
@@ -1,49 +1,49 @@
|
||||
import { Box, Text, useStdout } from "ink";
|
||||
import React from "react";
|
||||
import type { EditMode } from "../../config.js";
|
||||
import { DEEPSEEK_CONTEXT_TOKENS, DEFAULT_CONTEXT_TOKENS } from "../../telemetry.js";
|
||||
import type { SessionSummary } from "../../telemetry.js";
|
||||
import { VERSION } from "../../version.js";
|
||||
import { useTick } from "./ticker.js";
|
||||
import { COLOR, GRADIENT } from "./theme.js";
|
||||
|
||||
const WORDMARK_LETTERS: ReadonlyArray<string> = ["R", "E", "A", "S", "O", "N", "I", "X"];
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* Gradient-flowing wordmark. Every tick the gradient shifts one
|
||||
* position so the colors visibly travel across the letters — like
|
||||
* a neon sign. Brand mark `◈` rides the same flow but also pulses
|
||||
* bold on/off (slow when idle, fast when busy) so a glance at the
|
||||
* top of the screen tells you whether the app is thinking.
|
||||
*
|
||||
* Tick is ~120 ms. `rotateEvery=4` ticks → one shift every ~480 ms
|
||||
* idle, ~240 ms when busy. Slow enough to be ambient, fast enough
|
||||
* to feel alive. Truecolor terminals get the smooth flow; 8-color
|
||||
* fallbacks just see all-cyan, which is still legible.
|
||||
*/
|
||||
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;
|
||||
function Wordmark({
|
||||
busy: _busy,
|
||||
animate: _animate,
|
||||
}: {
|
||||
busy: boolean;
|
||||
animate: boolean;
|
||||
}) {
|
||||
// Static gradient. The brand sweep teal → fuchsia is precomputed
|
||||
// once per render — no useTick subscription, no per-tick
|
||||
// re-render. Earlier versions flowed the colors over time, but
|
||||
// the per-tick re-render interleaved badly with terminal resize
|
||||
// (Ink's eraseLines misjudges row count when bars / wide text
|
||||
// wrap, ghost frames stack). Keeping this static eliminates the
|
||||
// multiplier; resize artifacts at most leave a single stale
|
||||
// frame instead of N.
|
||||
return (
|
||||
<Text>
|
||||
{WORDMARK_STYLES.map((c) => (
|
||||
<Text key={`${c.ch}-${c.color}`} color={c.color} bold={c.isLogo ? bright : true}>
|
||||
{c.ch}
|
||||
<Text color={GRADIENT[0]} bold>
|
||||
◈
|
||||
</Text>
|
||||
<Text> </Text>
|
||||
{WORDMARK_LETTERS.map((letter, i) => (
|
||||
<Text key={letter} color={GRADIENT[i % GRADIENT.length]} bold>
|
||||
{letter}
|
||||
</Text>
|
||||
))}
|
||||
</Text>
|
||||
@@ -56,6 +56,13 @@ export interface StatsPanelProps {
|
||||
prefixHash: string;
|
||||
harvestOn?: boolean;
|
||||
branchBudget?: number;
|
||||
/**
|
||||
* Current `reasoning_effort` cap. Shown as a green "· max" / yellow
|
||||
* "· high" tag in the header so the user always sees which tier the
|
||||
* next turn will use. Absent/undefined hides the tag (e.g. before
|
||||
* the loop is constructed).
|
||||
*/
|
||||
reasoningEffort?: "high" | "max";
|
||||
/**
|
||||
* True when `reasonix code` is currently running in read-only Plan
|
||||
* Mode. Surfaced as a red "PLAN" tag in the panel header so the user
|
||||
@@ -63,6 +70,12 @@ export interface StatsPanelProps {
|
||||
* approval.
|
||||
*/
|
||||
planMode?: boolean;
|
||||
/**
|
||||
* Edit-gate mode. Surfaced as a small pill in the header so the user
|
||||
* can see at a glance whether edits will be queued for review or
|
||||
* applied immediately. Omitted in chat (non-code) mode.
|
||||
*/
|
||||
editMode?: EditMode;
|
||||
/**
|
||||
* Account balance fetched once at launch (and optionally refreshed
|
||||
* per-turn by the TUI). `null` or absent hides the balance cell
|
||||
@@ -85,6 +98,19 @@ export interface StatsPanelProps {
|
||||
* visible at a glance from anywhere on screen.
|
||||
*/
|
||||
busy?: boolean;
|
||||
/**
|
||||
* /pro is queued — the next turn will run on v4-pro regardless of
|
||||
* `model`. Rendered as a yellow `⇧ pro armed` pill in the header so
|
||||
* the user has a clear "this turn will be expensive" signal before
|
||||
* submitting their message.
|
||||
*/
|
||||
proArmed?: boolean;
|
||||
/**
|
||||
* The CURRENT turn is running on v4-pro because the failure-
|
||||
* escalation threshold fired mid-turn. Rendered as a red `⇧ pro
|
||||
* escalated` pill. Clears at turn end.
|
||||
*/
|
||||
escalated?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -110,10 +136,14 @@ export function StatsPanel({
|
||||
prefixHash,
|
||||
harvestOn,
|
||||
branchBudget,
|
||||
reasoningEffort,
|
||||
planMode,
|
||||
editMode,
|
||||
balance,
|
||||
updateAvailable,
|
||||
busy,
|
||||
proArmed,
|
||||
escalated,
|
||||
}: StatsPanelProps) {
|
||||
const branchOn = (branchBudget ?? 1) > 1;
|
||||
const ctxMax = DEEPSEEK_CONTEXT_TOKENS[model] ?? DEFAULT_CONTEXT_TOKENS;
|
||||
@@ -127,19 +157,32 @@ export function StatsPanel({
|
||||
// actually had a chance to build, we flip to the live gradient.
|
||||
const coldStart = summary.turns <= COLD_START_TURNS;
|
||||
|
||||
// No gradient bars, no animation. Earlier versions had truecolor
|
||||
// gradient rules top+bottom and a tick-driven wordmark/bar flow,
|
||||
// but those are exactly the elements Ink's eraseLines miscounts
|
||||
// on resize: ~100-char gradient strings wrap 2-3 visual rows at
|
||||
// narrow widths, the per-tick re-render writes new frames before
|
||||
// the stale rows are erased, and ghost panels stack vertically
|
||||
// (the user-reported "刷屏" / multi-frame artifact). Fixed-row
|
||||
// panel + no per-tick churn keeps Ink's row math honest.
|
||||
return (
|
||||
<Box borderStyle="round" borderColor="cyan" flexDirection="column" paddingX={1}>
|
||||
<Box flexDirection="column" paddingX={1} marginBottom={1}>
|
||||
<Header
|
||||
model={model}
|
||||
prefixHash={prefixHash}
|
||||
harvestOn={harvestOn}
|
||||
branchOn={branchOn}
|
||||
branchBudget={branchBudget ?? 1}
|
||||
reasoningEffort={reasoningEffort}
|
||||
planMode={planMode}
|
||||
editMode={editMode}
|
||||
turns={summary.turns}
|
||||
updateAvailable={updateAvailable}
|
||||
narrow={narrow}
|
||||
busy={busy ?? false}
|
||||
proArmed={proArmed ?? false}
|
||||
escalated={escalated ?? false}
|
||||
animate={false}
|
||||
/>
|
||||
{narrow ? (
|
||||
<StackedMetrics
|
||||
@@ -168,54 +211,121 @@ function Header({
|
||||
harvestOn,
|
||||
branchOn,
|
||||
branchBudget,
|
||||
reasoningEffort,
|
||||
planMode,
|
||||
editMode,
|
||||
turns,
|
||||
updateAvailable,
|
||||
narrow,
|
||||
busy,
|
||||
proArmed,
|
||||
escalated,
|
||||
animate,
|
||||
}: {
|
||||
model: string;
|
||||
prefixHash: string;
|
||||
harvestOn?: boolean;
|
||||
branchOn: boolean;
|
||||
branchBudget: number;
|
||||
reasoningEffort?: "high" | "max";
|
||||
planMode?: boolean;
|
||||
editMode?: EditMode;
|
||||
turns: number;
|
||||
updateAvailable?: string | null;
|
||||
narrow: boolean;
|
||||
busy: boolean;
|
||||
proArmed: boolean;
|
||||
escalated: boolean;
|
||||
/** When false, suppress optional pills + animation to avoid wraps. */
|
||||
animate: boolean;
|
||||
}) {
|
||||
// Mode pill — pick the most informative one to surface in the
|
||||
// header. PLAN beats AUTO/review beats nothing. Pro armed/escalated
|
||||
// gets its own pill alongside.
|
||||
const modePill = planMode
|
||||
? { label: "PLAN", bg: "red" as const }
|
||||
: editMode === "auto"
|
||||
? { label: "AUTO", bg: "magenta" as const }
|
||||
: editMode === "review"
|
||||
? { label: "REVIEW", bg: "cyan" as const }
|
||||
: null;
|
||||
const proPill = escalated
|
||||
? { label: "⇧ PRO", bg: "red" as const }
|
||||
: proArmed
|
||||
? { label: "⇧ PRO", bg: "yellow" as const }
|
||||
: null;
|
||||
// Narrow / non-animate mode hides the secondary pills (harvest,
|
||||
// branch, reasoning effort) so the header always fits on one
|
||||
// visual row. Wrapping the header is the main amplifier of the
|
||||
// eraseLines miscount that produces the "screen flashing" effect.
|
||||
const showSecondary = animate && !narrow;
|
||||
return (
|
||||
<Box justifyContent="space-between">
|
||||
<Box>
|
||||
<Wordmark busy={busy} />
|
||||
<Text dimColor>{` v${VERSION}`}</Text>
|
||||
<Text dimColor> · </Text>
|
||||
<Text color="yellow">{model}</Text>
|
||||
{narrow ? null : (
|
||||
<Wordmark busy={busy} animate={animate} />
|
||||
<Text dimColor>{` ${VERSION}`}</Text>
|
||||
<Text dimColor>{" "}</Text>
|
||||
<Text color="yellow" bold>
|
||||
{model.replace(/^deepseek-/, "")}
|
||||
</Text>
|
||||
{modePill ? (
|
||||
<>
|
||||
<Text dimColor> · </Text>
|
||||
<Text dimColor>{prefixHash}</Text>
|
||||
<Text>{" "}</Text>
|
||||
<Pill label={modePill.label} bg={modePill.bg} />
|
||||
</>
|
||||
)}
|
||||
{harvestOn ? <Text color="magenta"> · harvest</Text> : null}
|
||||
{branchOn ? <Text color="blue"> · branch{branchBudget}</Text> : null}
|
||||
{planMode ? (
|
||||
<Text color="red" bold>
|
||||
{" · PLAN"}
|
||||
) : null}
|
||||
{proPill ? (
|
||||
<>
|
||||
<Text>{" "}</Text>
|
||||
<Pill label={proPill.label} bg={proPill.bg} />
|
||||
</>
|
||||
) : null}
|
||||
{showSecondary && harvestOn ? (
|
||||
<Text dimColor>
|
||||
<Text>{" "}</Text>
|
||||
<Text color="magenta">harvest</Text>
|
||||
</Text>
|
||||
) : null}
|
||||
{showSecondary && branchOn ? (
|
||||
<Text dimColor>
|
||||
<Text>{" "}</Text>
|
||||
<Text color="blue">{`branch×${branchBudget}`}</Text>
|
||||
</Text>
|
||||
) : null}
|
||||
{showSecondary && reasoningEffort === "max" ? (
|
||||
<>
|
||||
<Text>{" "}</Text>
|
||||
<Text color="green" dimColor>
|
||||
max
|
||||
</Text>
|
||||
</>
|
||||
) : null}
|
||||
{showSecondary && reasoningEffort === "high" ? (
|
||||
<>
|
||||
<Text>{" "}</Text>
|
||||
<Text color="yellow" dimColor>
|
||||
high
|
||||
</Text>
|
||||
</>
|
||||
) : null}
|
||||
</Box>
|
||||
<Text>
|
||||
{updateAvailable ? (
|
||||
<Text color="yellow" bold>{`update: ${updateAvailable} · `}</Text>
|
||||
) : null}
|
||||
<Text dimColor>{narrow ? `turn ${turns}` : `turn ${turns} · /help`}</Text>
|
||||
{updateAvailable ? <Text color="yellow" bold>{`↑ ${updateAvailable} `}</Text> : null}
|
||||
<Text dimColor>{narrow ? `t${turns}` : `turn ${turns} · /help`}</Text>
|
||||
</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
/** Solid-background tag, used for primary mode + pro indicators. */
|
||||
function Pill({ label, bg }: { label: string; bg: "red" | "magenta" | "cyan" | "yellow" }) {
|
||||
return (
|
||||
<Text backgroundColor={bg} color="white" bold>
|
||||
{` ${label} `}
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Wide-terminal layout (≥120 cols): single metrics row. Matches the
|
||||
* original panel, just with calmer spacing and the cold-start
|
||||
@@ -292,24 +402,26 @@ function ContextCell({
|
||||
if (promptTokens === 0) {
|
||||
return (
|
||||
<Text>
|
||||
<Text dimColor>ctx </Text>
|
||||
<Text color={COLOR.info} dimColor>
|
||||
{"▣ ctx "}
|
||||
</Text>
|
||||
<Text dimColor>— (no turns yet)</Text>
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
const color = ratio >= 0.8 ? "red" : ratio >= 0.6 ? "yellow" : "green";
|
||||
const color = ratio >= 0.8 ? COLOR.err : ratio >= 0.6 ? COLOR.warn : COLOR.ok;
|
||||
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.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="red" bold>
|
||||
<Text color={COLOR.err} bold>
|
||||
{" · /compact"}
|
||||
</Text>
|
||||
) : null}
|
||||
@@ -330,7 +442,9 @@ function CacheCell({
|
||||
if (turns === 0) {
|
||||
return (
|
||||
<Text>
|
||||
<Text dimColor>cache </Text>
|
||||
<Text color={COLOR.info} dimColor>
|
||||
{"⌬ cache "}
|
||||
</Text>
|
||||
<Text dimColor>—</Text>
|
||||
</Text>
|
||||
);
|
||||
@@ -338,7 +452,9 @@ function CacheCell({
|
||||
if (coldStart) {
|
||||
return (
|
||||
<Text>
|
||||
<Text dimColor>cache </Text>
|
||||
<Text color={COLOR.info} dimColor>
|
||||
{"⌬ cache "}
|
||||
</Text>
|
||||
<Text dimColor>{pct}% </Text>
|
||||
<Text dimColor italic>
|
||||
(cold start)
|
||||
@@ -346,10 +462,10 @@ function CacheCell({
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
const color = hitRatio >= 0.7 ? "green" : hitRatio >= 0.4 ? "yellow" : "red";
|
||||
const color = hitRatio >= 0.7 ? COLOR.ok : hitRatio >= 0.4 ? COLOR.warn : COLOR.err;
|
||||
return (
|
||||
<Text>
|
||||
<Text dimColor>cache </Text>
|
||||
<Text color={COLOR.info}>{"⌬ cache "}</Text>
|
||||
<Text color={color} bold>
|
||||
{pct}%
|
||||
</Text>
|
||||
@@ -357,6 +473,24 @@ function CacheCell({
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Color thresholds. Per-turn and session cumulative scale roughly 10×
|
||||
* apart — a $0.20 single turn should feel just as warn-worthy as a $2
|
||||
* session total. Values are rough "notice this" points, not hard caps.
|
||||
*/
|
||||
function turnCostColor(cost: number): string | undefined {
|
||||
if (cost <= 0) return undefined;
|
||||
if (cost >= 0.2) return COLOR.err;
|
||||
if (cost >= 0.05) return COLOR.warn;
|
||||
return COLOR.ok;
|
||||
}
|
||||
function sessionCostColor(cost: number): string | undefined {
|
||||
if (cost <= 0) return undefined;
|
||||
if (cost >= 5) return COLOR.err;
|
||||
if (cost >= 0.5) return COLOR.warn;
|
||||
return COLOR.ok;
|
||||
}
|
||||
|
||||
function CostCell({
|
||||
summary,
|
||||
coldStart,
|
||||
@@ -367,7 +501,9 @@ function CostCell({
|
||||
if (summary.turns === 0) {
|
||||
return (
|
||||
<Text>
|
||||
<Text dimColor>cost </Text>
|
||||
<Text color={COLOR.info} dimColor>
|
||||
{"◴ cost "}
|
||||
</Text>
|
||||
<Text dimColor>—</Text>
|
||||
</Text>
|
||||
);
|
||||
@@ -376,27 +512,27 @@ function CostCell({
|
||||
// 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 turnColor = coldStart ? undefined : turnCostColor(summary.lastTurnCostUsd);
|
||||
const sessionColor = coldStart ? undefined : sessionCostColor(summary.totalCostUsd);
|
||||
return (
|
||||
<Text>
|
||||
<Text dimColor>cost </Text>
|
||||
<Text color={primaryColor} bold={!coldStart} dimColor={coldStart}>
|
||||
${summary.totalCostUsd.toFixed(6)}
|
||||
<Text color={COLOR.info}>{"◴ turn "}</Text>
|
||||
<Text color={turnColor} bold={!coldStart} dimColor={coldStart}>
|
||||
${summary.lastTurnCostUsd.toFixed(4)}
|
||||
</Text>
|
||||
<Text dimColor>
|
||||
{" (in "}${summary.totalInputCostUsd.toFixed(6)}
|
||||
{" · out "}${summary.totalOutputCostUsd.toFixed(6)}
|
||||
{")"}
|
||||
<Text dimColor>{" · session "}</Text>
|
||||
<Text color={sessionColor} bold={!coldStart} dimColor={coldStart}>
|
||||
${summary.totalCostUsd.toFixed(4)}
|
||||
</Text>
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
|
||||
function BalanceCell({ balance }: { balance: { currency: string; total: number } }) {
|
||||
const color = balance.total < 1 ? "red" : balance.total < 5 ? "yellow" : "green";
|
||||
const color = balance.total < 1 ? COLOR.err : balance.total < 5 ? COLOR.warn : COLOR.ok;
|
||||
return (
|
||||
<Text>
|
||||
<Text dimColor>balance </Text>
|
||||
<Text color={COLOR.info}>{"◐ balance "}</Text>
|
||||
<Text color={color} bold>
|
||||
{balance.currency === "USD" ? "$" : ""}
|
||||
{balance.total.toFixed(2)}
|
||||
@@ -407,15 +543,29 @@ function BalanceCell({ balance }: { balance: { currency: string; total: number }
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* Truecolor progress bar. Filled cells use the threshold color (green
|
||||
* → amber → rose) so the bar communicates pressure at a glance;
|
||||
* empty cells use a dim shade so the empty portion is visible
|
||||
* without dominating. ▰/▱ have distinct shapes (filled vs hollow)
|
||||
* so the boundary is clear even when colors snap to 8-color slots
|
||||
* on legacy terminals.
|
||||
*/
|
||||
function Bar({ ratio, color }: { ratio: number; color: "green" | "yellow" | "red" }) {
|
||||
const cells = 10;
|
||||
function Bar({
|
||||
ratio,
|
||||
color,
|
||||
cells = 14,
|
||||
}: {
|
||||
ratio: number;
|
||||
color: string;
|
||||
cells?: number;
|
||||
}) {
|
||||
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>;
|
||||
return (
|
||||
<Text>
|
||||
<Text color={color}>{"▰".repeat(filled)}</Text>
|
||||
<Text dimColor>{"▱".repeat(cells - filled)}</Text>
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
/**
|
||||
* Welcome card on the empty session. The first thing a user sees
|
||||
* after launching `reasonix code` — needs to communicate, in the
|
||||
* ~5 seconds before they type, three things: brand, what to type,
|
||||
* how to escape. Card framing uses a gradient top rule + left-side
|
||||
* accent bar + sectioned hints so it reads as a designed surface
|
||||
* rather than a bare list. No bordered Boxes — those amplified
|
||||
* Ink's Windows eraseLines miscount.
|
||||
*/
|
||||
|
||||
import { Box, Text, useStdout } from "ink";
|
||||
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React in value scope
|
||||
import React from "react";
|
||||
import { COLOR, gradientCells } from "./theme.js";
|
||||
|
||||
export interface WelcomeBannerProps {
|
||||
/** True when running `reasonix code`. Surfaces code-mode hints. */
|
||||
inCodeMode?: boolean;
|
||||
}
|
||||
|
||||
export function WelcomeBanner({ inCodeMode }: WelcomeBannerProps): React.ReactElement {
|
||||
const { stdout } = useStdout();
|
||||
const cols = stdout?.columns ?? 80;
|
||||
const ruleWidth = Math.min(60, Math.max(28, cols - 4));
|
||||
return (
|
||||
<Box flexDirection="column" paddingX={1} marginY={1}>
|
||||
<GradientRule width={ruleWidth} />
|
||||
<BarRow>
|
||||
<Text bold color={COLOR.brand}>
|
||||
◈ welcome
|
||||
</Text>
|
||||
<Text dimColor>{" · type a message to start"}</Text>
|
||||
</BarRow>
|
||||
<BarRow />
|
||||
<BarRow>
|
||||
<Text bold color={COLOR.primary}>
|
||||
quick start
|
||||
</Text>
|
||||
</BarRow>
|
||||
<Hint cmd="/help" desc="every command + keyboard shortcut" />
|
||||
<Hint cmd="/skill" desc="invoke a stored playbook" />
|
||||
{inCodeMode ? (
|
||||
<>
|
||||
<Hint cmd="@path" desc="inline a file in your message" />
|
||||
<Hint cmd="!cmd" desc="run a shell command, output goes to context" />
|
||||
</>
|
||||
) : null}
|
||||
<Hint cmd="/exit" desc="quit (Ctrl+C also works)" />
|
||||
<BarRow />
|
||||
<BarRow>
|
||||
<Text dimColor italic>
|
||||
tip:
|
||||
</Text>
|
||||
<Text dimColor>{" Ctrl+J inserts a newline · trailing \\ also continues"}</Text>
|
||||
</BarRow>
|
||||
<Box marginTop={1}>
|
||||
<GradientRule width={ruleWidth} thin />
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* One-line gradient rule. `thin` swaps the half-block top/bottom so
|
||||
* the top of the card reads as a "header band" (▄ — bottom-half
|
||||
* filled) and the bottom as "section close" (▁ — minimal pixel
|
||||
* row). Same primitive the StatsPanel uses, kept consistent.
|
||||
*/
|
||||
function GradientRule({ width, thin }: { width: number; thin?: boolean }) {
|
||||
const cells = gradientCells(width, thin ? "▁" : "▄");
|
||||
return (
|
||||
<Box>
|
||||
{cells.map((c, i) => (
|
||||
// biome-ignore lint/suspicious/noArrayIndexKey: fixed-width gradient row, never reordered
|
||||
<Text key={`wrule-${i}`} color={c.color}>
|
||||
{c.ch}
|
||||
</Text>
|
||||
))}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Card row — left-side accent bar followed by content. Children
|
||||
* optional so we can use this for blank spacer rows (bar only).
|
||||
*/
|
||||
function BarRow({ children }: { children?: React.ReactNode }) {
|
||||
return (
|
||||
<Box>
|
||||
<Text color={COLOR.brand} bold>
|
||||
▎
|
||||
</Text>
|
||||
<Text> </Text>
|
||||
{children}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Single hint row — bold accent cmd token + dim description.
|
||||
* Padded so all cmd tokens line up regardless of length, like a
|
||||
* man-page synopsis.
|
||||
*/
|
||||
function Hint({ cmd, desc }: { cmd: string; desc: string }) {
|
||||
return (
|
||||
<BarRow>
|
||||
<Text bold color={COLOR.accent}>
|
||||
{cmd.padEnd(8)}
|
||||
</Text>
|
||||
<Text dimColor>{` ${desc}`}</Text>
|
||||
</BarRow>
|
||||
);
|
||||
}
|
||||
@@ -97,7 +97,7 @@ export function Wizard({ onComplete, onCancel, existingApiKey, initial }: Wizard
|
||||
}}
|
||||
/>
|
||||
<Box marginTop={1}>
|
||||
<Text dimColor>↑/↓ move · enter confirm · esc cancel</Text>
|
||||
<Text dimColor>[↑↓] navigate · [Enter] confirm · [Esc] cancel</Text>
|
||||
</Box>
|
||||
</StepFrame>
|
||||
);
|
||||
@@ -115,7 +115,7 @@ export function Wizard({ onComplete, onCancel, existingApiKey, initial }: Wizard
|
||||
const needsArgs = selected.some((name) => CATALOG_BY_NAME.get(name)?.userArgs);
|
||||
setStep(needsArgs ? "mcpArgs" : "review");
|
||||
}}
|
||||
footer="↑/↓ move · space toggle · enter confirm · esc cancel · leave empty to skip"
|
||||
footer="[↑↓] navigate · [Space] toggle · [Enter] confirm · [Esc] cancel · empty = skip"
|
||||
/>
|
||||
</StepFrame>
|
||||
);
|
||||
@@ -174,7 +174,7 @@ export function Wizard({ onComplete, onCancel, existingApiKey, initial }: Wizard
|
||||
</Box>
|
||||
) : null}
|
||||
<Box marginTop={1}>
|
||||
<Text dimColor>enter save · esc cancel</Text>
|
||||
<Text dimColor>[Enter] save · [Esc] cancel</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
<ReviewConfirm
|
||||
@@ -213,7 +213,7 @@ export function Wizard({ onComplete, onCancel, existingApiKey, initial }: Wizard
|
||||
<Text>Run `reasonix` any time to start chatting — your settings are remembered.</Text>
|
||||
</Box>
|
||||
<Box marginTop={1}>
|
||||
<Text dimColor>Press enter to exit.</Text>
|
||||
<Text dimColor>[Enter] to exit</Text>
|
||||
</Box>
|
||||
<ExitOnEnter onExit={exit} />
|
||||
</Box>
|
||||
@@ -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,69 @@
|
||||
import { Box, Text } from "ink";
|
||||
import React from "react";
|
||||
import { ModalCard } from "./ModalCard.js";
|
||||
import { SingleSelect } from "./Select.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) => 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.
|
||||
*/
|
||||
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="#f59e0b" icon="⇄" title="switch workspace" subtitle={subtitle}>
|
||||
<Box flexDirection="column" marginBottom={1}>
|
||||
<Box>
|
||||
<Text dimColor>{"from "}</Text>
|
||||
<Text color="#a3a3a3">{currentRoot}</Text>
|
||||
</Box>
|
||||
<Box>
|
||||
<Text dimColor>{"to "}</Text>
|
||||
<Text color="#67e8f9" 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 the user refused; it will continue without changing directories.",
|
||||
},
|
||||
]}
|
||||
onSubmit={(v) => onChoose(v as WorkspaceConfirmChoice)}
|
||||
onCancel={() => onChoose("deny")}
|
||||
footer="[↑↓] navigate · [Enter] select · [Esc] deny"
|
||||
/>
|
||||
</ModalCard>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
import { formatAllBlockDiffs } from "../../code/diff-preview.js";
|
||||
import type { ApplyResult, EditBlock, EditSnapshot } from "../../code/edit-blocks.js";
|
||||
|
||||
/**
|
||||
* One batch of edits that actually landed on disk — durable enough for
|
||||
* `/undo`, `/history`, and `/show` within a session. Not persisted
|
||||
* across restarts: restoring pre-apply content from a process that
|
||||
* crashed last week is git's job, not ours.
|
||||
*/
|
||||
export interface EditHistoryEntry {
|
||||
/** Sequence number within the session, stable for `/show <id>`. */
|
||||
id: number;
|
||||
/** Epoch ms when the entry was opened (first edit landed). */
|
||||
at: number;
|
||||
/**
|
||||
* Short tag for what produced the batch — "auto" (auto-mode tool
|
||||
* call), "auto-text" (auto-mode text SEARCH/REPLACE at turn end),
|
||||
* "review-apply" (user-approved modal edit or /apply flush).
|
||||
*/
|
||||
source: string;
|
||||
/** Edit blocks included in this batch, in arrival order. */
|
||||
blocks: EditBlock[];
|
||||
/** Per-block outcome — some may be "not-found" if SEARCH drifted. */
|
||||
results: ApplyResult[];
|
||||
/**
|
||||
* First-snapshot-per-path wins: this is what `/undo` restores to.
|
||||
* Deduped so multi-edit turns still roll back to pre-turn state.
|
||||
*/
|
||||
snapshots: EditSnapshot[];
|
||||
/**
|
||||
* Paths within this entry that have already been reverted (via
|
||||
* `/undo <id>`, `/undo <id> <path>`, or the newest-non-undone /undo
|
||||
* shortcut). Per-path instead of entry-level so a batch can be
|
||||
* partially undone — user reverts src/foo.ts out of a 3-file batch
|
||||
* without rolling back the other two.
|
||||
*/
|
||||
undoneFiles: Set<string>;
|
||||
}
|
||||
|
||||
/** True when every path in the entry has been undone. */
|
||||
export function isEntryFullyUndone(e: EditHistoryEntry): boolean {
|
||||
return e.snapshots.length > 0 && e.snapshots.every((s) => e.undoneFiles.has(s.path));
|
||||
}
|
||||
|
||||
/** Per-entry three-state status label for display. */
|
||||
export function entryStatus(e: EditHistoryEntry): "applied" | "UNDONE" | "PARTIAL" {
|
||||
if (e.undoneFiles.size === 0) return "applied";
|
||||
if (isEntryFullyUndone(e)) return "UNDONE";
|
||||
return "PARTIAL";
|
||||
}
|
||||
|
||||
/**
|
||||
* Render a batch of SEARCH/REPLACE application results as one
|
||||
* human-scannable info line per edit. Prefixes denote status so the
|
||||
* line reads well even without color (e.g. when piped to a log file
|
||||
* or stripped for screenshots):
|
||||
* ✓ applied src/foo.ts
|
||||
* ✓ created src/new.ts
|
||||
* ✗ not-found src/bar.ts (SEARCH text does not match…)
|
||||
*/
|
||||
export function formatEditResults(results: ApplyResult[]): string {
|
||||
const lines = results.map((r) => {
|
||||
const mark = r.status === "applied" || r.status === "created" ? "✓" : "✗";
|
||||
const detail = r.message ? ` (${r.message})` : "";
|
||||
return ` ${mark} ${r.status.padEnd(11)} ${r.path}${detail}`;
|
||||
});
|
||||
const ok = results.filter((r) => r.status === "applied" || r.status === "created").length;
|
||||
const total = results.length;
|
||||
const header = `▸ edit blocks: ${ok}/${total} applied — /undo to roll back, or \`git diff\` to review`;
|
||||
return [header, ...lines].join("\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* Pending-edits preview shown after each assistant turn that proposed
|
||||
* changes. Per-block path header + ±line-count, then a unified-diff-
|
||||
* style preview (context trimmed to 2 lines each side, total capped
|
||||
* at 20 lines per block). Users can eyeball what's about to land
|
||||
* BEFORE pressing `y` — the old summary-only view was a common
|
||||
* mistake surface.
|
||||
*
|
||||
* Each block gets a `[N]` label so users can target a subset via
|
||||
* `/apply 1` / `/apply 1,3-4` / `/discard 2` instead of being forced
|
||||
* into all-or-nothing.
|
||||
*/
|
||||
export function formatPendingPreview(blocks: EditBlock[]): string {
|
||||
const partial = blocks.length > 1 ? " · /apply N or 1,3-4 for partial" : "";
|
||||
const header = `▸ ${blocks.length} pending edit block(s) — /apply (or y) to commit · /discard (or n) to drop${partial}`;
|
||||
const diffLines = formatAllBlockDiffs(blocks, { numbered: blocks.length > 1 });
|
||||
return [header, ...diffLines].join("\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a `/apply <N>` / `/discard <N>` argument into a deduplicated,
|
||||
* sorted list of 1-based indices. Accepts:
|
||||
* - single value: `"3"` → [3]
|
||||
* - comma list: `"1,3,5"` → [1, 3, 5]
|
||||
* - range: `"2-4"` → [2, 3, 4]
|
||||
* - mixed: `"1,3-5,7"` → [1, 3, 4, 5, 7]
|
||||
* - whitespace + trailing commas tolerated.
|
||||
*
|
||||
* Bounds-checked against `max` (the count of pending blocks); any
|
||||
* out-of-range or malformed token returns `{ error }` so the caller
|
||||
* can surface a usage hint instead of silently applying the wrong
|
||||
* subset. Empty input returns `{ ok: [] }` so callers can detect
|
||||
* "user passed no indices" and treat that as the all-blocks default.
|
||||
*/
|
||||
export function parseEditIndices(raw: string, max: number): { ok: number[] } | { error: string } {
|
||||
const trimmed = raw.trim();
|
||||
if (!trimmed) return { ok: [] };
|
||||
if (max <= 0) return { error: "no pending edits to address" };
|
||||
const seen = new Set<number>();
|
||||
const tokens = trimmed
|
||||
.split(",")
|
||||
.map((t) => t.trim())
|
||||
.filter((t) => t.length > 0);
|
||||
if (tokens.length === 0) return { ok: [] };
|
||||
for (const tok of tokens) {
|
||||
const range = tok.match(/^(\d+)-(\d+)$/);
|
||||
if (range) {
|
||||
const a = Number.parseInt(range[1] ?? "", 10);
|
||||
const b = Number.parseInt(range[2] ?? "", 10);
|
||||
if (!Number.isFinite(a) || !Number.isFinite(b) || a < 1 || b < 1) {
|
||||
return { error: `invalid range: "${tok}"` };
|
||||
}
|
||||
const lo = Math.min(a, b);
|
||||
const hi = Math.max(a, b);
|
||||
if (hi > max) return { error: `index ${hi} out of range (max ${max})` };
|
||||
for (let i = lo; i <= hi; i++) seen.add(i);
|
||||
continue;
|
||||
}
|
||||
if (!/^\d+$/.test(tok)) return { error: `invalid index: "${tok}"` };
|
||||
const n = Number.parseInt(tok, 10);
|
||||
if (!Number.isFinite(n) || n < 1) return { error: `invalid index: "${tok}"` };
|
||||
if (n > max) return { error: `index ${n} out of range (max ${max})` };
|
||||
seen.add(n);
|
||||
}
|
||||
return { ok: [...seen].sort((a, b) => a - b) };
|
||||
}
|
||||
|
||||
/**
|
||||
* Partition `edits` into the subset addressed by `indices1Based` and
|
||||
* everything else (preserves original order). Pure helper so the
|
||||
* pending-edits queue can be sliced from the slash handler in App.tsx
|
||||
* without any React-state plumbing in the test path.
|
||||
*/
|
||||
export function partitionEdits<T>(
|
||||
edits: readonly T[],
|
||||
indices1Based: readonly number[],
|
||||
): { selected: T[]; remaining: T[] } {
|
||||
const picked = new Set(indices1Based);
|
||||
const selected: T[] = [];
|
||||
const remaining: T[] = [];
|
||||
for (let i = 0; i < edits.length; i++) {
|
||||
if (picked.has(i + 1)) selected.push(edits[i] as T);
|
||||
else remaining.push(edits[i] as T);
|
||||
}
|
||||
return { selected, remaining };
|
||||
}
|
||||
|
||||
/**
|
||||
* Per-file rows for the multi-level `/undo` output, without the
|
||||
* single-batch header (the caller prepends its own).
|
||||
*/
|
||||
export function formatUndoRows(results: ApplyResult[]): string[] {
|
||||
return results.map((r) => {
|
||||
const mark = r.status === "applied" ? "✓" : "✗";
|
||||
const detail = r.message ? ` (${r.message})` : "";
|
||||
return ` ${mark} ${r.path}${detail}`;
|
||||
});
|
||||
}
|
||||
|
||||
export function describeRepair(repair: {
|
||||
scavenged: number;
|
||||
truncationsFixed: number;
|
||||
stormsBroken: number;
|
||||
}): string {
|
||||
const parts: string[] = [];
|
||||
if (repair.scavenged) parts.push(`scavenged ${repair.scavenged}`);
|
||||
if (repair.truncationsFixed) parts.push(`repaired ${repair.truncationsFixed} truncation`);
|
||||
if (repair.stormsBroken) parts.push(`broke ${repair.stormsBroken} storm`);
|
||||
return parts.length ? `[repair] ${parts.join(", ")}` : "";
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
/**
|
||||
* Hash-mode (`#note` / `#g note`) prefix parsing — instant memory write.
|
||||
*
|
||||
* A `#` at the start of the user's input writes a one-liner to memory
|
||||
* pinned in the prefix from now on. Two scopes:
|
||||
*
|
||||
* - `#<note>` → project memory `<rootDir>/REASONIX.md`
|
||||
* (committable, team-shared)
|
||||
* - `#g <note>` → global memory `~/.reasonix/REASONIX.md`
|
||||
* (private, cross-project — never committed)
|
||||
*
|
||||
* Same idea as Claude Code's `#` prefix — faster than going through
|
||||
* a `/memory remember ...` slash for a one-liner like "always use pnpm".
|
||||
*
|
||||
* Trigger shape:
|
||||
* - `#` followed by zero-or-more spaces, then a non-empty body
|
||||
* - NOT `##` / `###` / etc. — those stay markdown headings to the model
|
||||
* - `\#foo` escape → not a memory write, leading backslash stripped before
|
||||
* submission so the model sees `#foo` literally
|
||||
*
|
||||
* Each call appends one bullet at the bottom; we don't try to parse
|
||||
* section structure. The user can reorganize manually whenever they
|
||||
* want.
|
||||
*/
|
||||
|
||||
import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
import { PROJECT_MEMORY_FILE } from "../../project-memory.js";
|
||||
|
||||
const PROJECT_HEADER = `# Reasonix project memory
|
||||
|
||||
Notes the user pinned via the \`#\` prompt prefix. The whole file is
|
||||
loaded into the immutable system prefix every session — keep it terse.
|
||||
|
||||
`;
|
||||
|
||||
const GLOBAL_HEADER = `# Reasonix global memory
|
||||
|
||||
Cross-project notes the user pinned via the \`#g\` prompt prefix. Loaded
|
||||
into every Reasonix session's prefix regardless of working directory.
|
||||
Private to this machine — not committed anywhere.
|
||||
|
||||
`;
|
||||
|
||||
/**
|
||||
* Result of `detectHashMemory`.
|
||||
*
|
||||
* - `kind: "memory"` — input is `#<note>`; write to project REASONIX.md.
|
||||
* - `kind: "memory-global"` — input is `#g <note>`; write to global file.
|
||||
* - `kind: "escape"` — input started with `\#`; submit `#foo` literally.
|
||||
* - returning `null` — input is unrelated to hash mode.
|
||||
*/
|
||||
export type HashMemoryParse =
|
||||
| { kind: "memory"; note: string }
|
||||
| { kind: "memory-global"; note: string }
|
||||
| { kind: "escape"; text: string };
|
||||
|
||||
/**
|
||||
* Classify a hash-prefixed input. Pure — no filesystem touch — so it's
|
||||
* trivially testable and can run before any I/O decision in handleSubmit.
|
||||
*
|
||||
* Order of checks matters:
|
||||
* 1. `\#…` escape (so `\#g foo` ALSO escapes — user can send `#g foo`
|
||||
* to the model verbatim).
|
||||
* 2. `##…` markdown heading (level-2+ passes through unchanged).
|
||||
* 3. `#g <body>` — global memory. Requires whitespace after the `g` so
|
||||
* a note that happens to start with `g` (e.g. `#good idea`) doesn't
|
||||
* route to global by accident.
|
||||
* 4. `#<body>` — project memory.
|
||||
*/
|
||||
export function detectHashMemory(text: string): HashMemoryParse | null {
|
||||
if (text.startsWith("\\#")) {
|
||||
return { kind: "escape", text: text.slice(1) };
|
||||
}
|
||||
if (!text.startsWith("#")) return null;
|
||||
// Markdown headings of level 2+ pass through to the model unchanged.
|
||||
// Only a single leading `#` (level-1 heading shape) is ambiguous; we
|
||||
// resolve that ambiguity in favor of memory write and document the
|
||||
// `\#` escape for users who want a literal H1 in the prompt.
|
||||
if (text.startsWith("##")) return null;
|
||||
// `#g <note>` — global memory. The space after `g` is mandatory so
|
||||
// notes like `#golang preference` route to project memory, not global.
|
||||
// `#g` alone (or `#g` + only whitespace) is treated as null — the
|
||||
// user clearly wanted the global form but typed no body, so we don't
|
||||
// silently fall back to project memory with body=`g`.
|
||||
if (/^#g\s*$/.test(text)) return null;
|
||||
const globalMatch = /^#g\s+(.+)$/s.exec(text);
|
||||
if (globalMatch) {
|
||||
const body = globalMatch[1]!.trim();
|
||||
if (!body) return null;
|
||||
return { kind: "memory-global", note: body };
|
||||
}
|
||||
const body = text.slice(1).trim();
|
||||
if (!body) return null;
|
||||
return { kind: "memory", note: body };
|
||||
}
|
||||
|
||||
export interface AppendMemoryResult {
|
||||
/** Absolute path written to. */
|
||||
path: string;
|
||||
/** True iff the file did not exist before this call. */
|
||||
created: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Append `note` as a single bullet to `<rootDir>/REASONIX.md`. Creates
|
||||
* the file with a short header when absent. Inserts a leading newline
|
||||
* if the existing file doesn't end with one, so bullets don't collide
|
||||
* with the previous section's last line.
|
||||
*/
|
||||
export function appendProjectMemory(rootDir: string, note: string): AppendMemoryResult {
|
||||
return appendBulletToFile(join(rootDir, PROJECT_MEMORY_FILE), note, PROJECT_HEADER);
|
||||
}
|
||||
|
||||
export const GLOBAL_MEMORY_DIR = ".reasonix";
|
||||
export const GLOBAL_MEMORY_FILE = "REASONIX.md";
|
||||
|
||||
/**
|
||||
* Resolve the path to the global memory file. Defaults to
|
||||
* `~/.reasonix/REASONIX.md`; callers (mainly tests) can override the
|
||||
* home dir to point at a tmpdir.
|
||||
*/
|
||||
export function globalMemoryPath(homeDir: string = homedir()): string {
|
||||
return join(homeDir, GLOBAL_MEMORY_DIR, GLOBAL_MEMORY_FILE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Append `note` to `~/.reasonix/REASONIX.md`. Creates the parent
|
||||
* directory + file if either is missing.
|
||||
*/
|
||||
export function appendGlobalMemory(note: string, homeDir?: string): AppendMemoryResult {
|
||||
return appendBulletToFile(globalMemoryPath(homeDir), note, GLOBAL_HEADER);
|
||||
}
|
||||
|
||||
function appendBulletToFile(path: string, note: string, newFileHeader: string): AppendMemoryResult {
|
||||
const trimmed = note.trim();
|
||||
if (!trimmed) throw new Error("note body cannot be empty");
|
||||
const bullet = `- ${trimmed}\n`;
|
||||
if (!existsSync(path)) {
|
||||
mkdirSync(dirname(path), { recursive: true });
|
||||
writeFileSync(path, `${newFileHeader}${bullet}`, "utf8");
|
||||
return { path, created: true };
|
||||
}
|
||||
let prefix = "";
|
||||
try {
|
||||
const existing = readFileSync(path, "utf8");
|
||||
if (existing.length > 0 && !existing.endsWith("\n")) prefix = "\n";
|
||||
} catch {
|
||||
// Unreadable but exists — let appendFileSync surface the real error.
|
||||
}
|
||||
appendFileSync(path, `${prefix}${bullet}`, "utf8");
|
||||
return { path, created: false };
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
/**
|
||||
* CSI sequence recovery for Ink's `useInput`.
|
||||
*
|
||||
* Why this exists. Ink delivers keyboard events through `parse-keypress`,
|
||||
* which reads stdin and recognises ANSI control-sequence-introducer
|
||||
* (CSI) sequences with a state machine plus a short timeout. On most
|
||||
* terminals this works: the byte stream `\x1b [ A` arrives in one
|
||||
* read, parse-keypress emits `{key.upArrow:true, input:""}`, life is
|
||||
* good.
|
||||
*
|
||||
* On Windows PowerShell + ConPTY (and a handful of embedded shells)
|
||||
* the bytes don't always arrive together. parse-keypress's timeout
|
||||
* expires between chunks, so it dispatches the lone `\x1b` as
|
||||
* `key.escape:true` and then dispatches the trailing `[A` as a
|
||||
* regular character event — `input:"[A", key.upArrow:undefined`. The
|
||||
* useInput consumer sees `[A` as plain text, inserts it into the
|
||||
* buffer, and the cursor never moves. Same shape on `[C` (right
|
||||
* arrow), `[Z` (Shift+Tab), `[5~` (PgUp), `[201~` (bracketed-paste
|
||||
* end), etc.
|
||||
*
|
||||
* Every Reasonix UI component that calls `useInput` is exposed to
|
||||
* this. Patching each one to re-recognise the bare CSI tail was
|
||||
* fragile — every release a new symptom appeared (cursor stuck,
|
||||
* paste markers leaking, Shift+Tab not toggling). So this module is
|
||||
* the single source of truth for CSI recovery: every input handler
|
||||
* runs the raw event through `recoverCsiTail` before reading
|
||||
* structured key flags.
|
||||
*
|
||||
* Recovery is conservative. We only rewrite when:
|
||||
* 1. None of the structured key flags Ink already populated for
|
||||
* this event is set (so a real upArrow press isn't second-
|
||||
* guessed).
|
||||
* 2. `input` exactly matches a recognised tail in either form —
|
||||
* the full `\x1b[X` sequence (in case the timeout merged it)
|
||||
* or the bare `[X` ConPTY-stripped variant.
|
||||
*
|
||||
* Anything else passes through unchanged.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Subset of Ink's `Key` interface that contains the structured flags
|
||||
* we know how to recover. Optional everywhere because callers from
|
||||
* different Ink versions may not populate every field.
|
||||
*/
|
||||
export interface CsiKeyFlags {
|
||||
upArrow?: boolean;
|
||||
downArrow?: boolean;
|
||||
leftArrow?: boolean;
|
||||
rightArrow?: boolean;
|
||||
pageUp?: boolean;
|
||||
pageDown?: boolean;
|
||||
delete?: boolean;
|
||||
shift?: boolean;
|
||||
tab?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* CSI tails we recognise. Each maps the printable bytes of a CSI
|
||||
* tail (the part after the `\x1b`) to the structured key flags they
|
||||
* should set. Bracketed-paste markers `[200~` / `[201~` are
|
||||
* intentionally absent — they're handled by PromptInput's paste
|
||||
* accumulator, which has different semantics (collect content
|
||||
* between markers rather than emit one keystroke).
|
||||
*/
|
||||
const CSI_TAIL_TO_FLAGS: ReadonlyArray<{ tail: string; flags: CsiKeyFlags }> = [
|
||||
// Arrow keys — the most common ConPTY victim.
|
||||
{ tail: "[A", flags: { upArrow: true } },
|
||||
{ tail: "[B", flags: { downArrow: true } },
|
||||
{ tail: "[C", flags: { rightArrow: true } },
|
||||
{ tail: "[D", flags: { leftArrow: true } },
|
||||
// Page navigation.
|
||||
{ tail: "[5~", flags: { pageUp: true } },
|
||||
{ tail: "[6~", flags: { pageDown: true } },
|
||||
// Forward-delete (the key labelled Delete on most keyboards).
|
||||
{ tail: "[3~", flags: { delete: true } },
|
||||
// Shift+Tab — terminal sends `\x1b[Z` rather than tab-with-shift.
|
||||
{ tail: "[Z", flags: { shift: true, tab: true } },
|
||||
];
|
||||
|
||||
/**
|
||||
* Did Ink already give us a structured key for this event? When
|
||||
* `true`, recovery is unnecessary and would risk overriding a real
|
||||
* keypress that happens to share `input` with a CSI tail.
|
||||
*/
|
||||
function alreadyStructured(flags: CsiKeyFlags): boolean {
|
||||
return Boolean(
|
||||
flags.upArrow ||
|
||||
flags.downArrow ||
|
||||
flags.leftArrow ||
|
||||
flags.rightArrow ||
|
||||
flags.pageUp ||
|
||||
flags.pageDown ||
|
||||
flags.delete ||
|
||||
(flags.tab && flags.shift),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* If `input` is a recognisable CSI tail (with or without the leading
|
||||
* `\x1b`), return the structured flags it should produce. Otherwise
|
||||
* `null`. Bracketed-paste markers always return `null` here — those
|
||||
* are handled by their own accumulator.
|
||||
*
|
||||
* Pure function. Pass already-structured events through (they
|
||||
* short-circuit) so a real arrow press doesn't get rewritten.
|
||||
*/
|
||||
export function recoverCsiTail(input: string, existing: CsiKeyFlags = {}): CsiKeyFlags | null {
|
||||
if (alreadyStructured(existing)) return null;
|
||||
for (const entry of CSI_TAIL_TO_FLAGS) {
|
||||
if (input === entry.tail || input === `\x1b${entry.tail}`) {
|
||||
return entry.flags;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tail forms (with and without the leading `\x1b`) that should never
|
||||
* end up as literal text in a user's prompt buffer. Used as a final
|
||||
* defensive pass before treating input as printable — if a CSI
|
||||
* fragment slipped past structured-key recovery (e.g. arrived
|
||||
* embedded inside a paste burst), at least drop the raw bytes
|
||||
* rather than insert them as garbage text.
|
||||
*
|
||||
* Includes the bracketed-paste markers `[200~` / `[201~` because a
|
||||
* paste whose start/end markers got chunked across reads can leave
|
||||
* those bytes in the printable input.
|
||||
*/
|
||||
export const STRIPPABLE_CSI_FRAGMENTS: readonly string[] = [
|
||||
"\u001b[200~",
|
||||
"\u001b[201~",
|
||||
"[200~",
|
||||
"[201~",
|
||||
...CSI_TAIL_TO_FLAGS.flatMap((e) => [`\u001b${e.tail}`, e.tail]),
|
||||
];
|
||||
|
||||
/** Remove every recognised CSI fragment from a string. */
|
||||
export function stripCsiFragments(input: string): string {
|
||||
let out = input;
|
||||
for (const frag of STRIPPABLE_CSI_FRAGMENTS) {
|
||||
if (out.includes(frag)) out = out.replaceAll(frag, "");
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
/**
|
||||
* KeystrokeContext — React surface in front of the raw stdin reader.
|
||||
*
|
||||
* Replaces Ink's `useInput` chain. Reasonix's components no longer
|
||||
* import `useInput` from "ink"; they call `useKeystroke(handler,
|
||||
* isActive)` from this module. The provider mounted once at App
|
||||
* level owns a `StdinReader`, subscribes a single fan-out function
|
||||
* to it, and dispatches each parsed `KeyEvent` to every active
|
||||
* consumer.
|
||||
*
|
||||
* Why a Context instead of a singleton import: the provider can be
|
||||
* disabled in tests / replay mode without touching the components,
|
||||
* and the lifecycle (start/stop on mount/unmount) is tied to the
|
||||
* React tree rather than a global side effect.
|
||||
*
|
||||
* Why not just keep Ink's useInput: Ink's parse-keypress uses a
|
||||
* 100 ms intra-CSI timeout that's too short for Windows ConPTY,
|
||||
* leaking arrow-key bytes / paste markers into the buffer. Our
|
||||
* reader uses 250 ms and recognises the ESC-stripped variants too
|
||||
* — see `stdin-reader.ts`.
|
||||
*/
|
||||
|
||||
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React as a runtime value
|
||||
import React, { createContext, useContext, useEffect, useRef } from "react";
|
||||
import { type KeyEvent, type StdinReader, getStdinReader } from "./stdin-reader.js";
|
||||
|
||||
interface KeystrokeBus {
|
||||
/** Subscribe — returns an unsubscribe function. */
|
||||
subscribe(handler: KeystrokeHandler): () => void;
|
||||
}
|
||||
|
||||
export type KeystrokeHandler = (ev: KeyEvent) => void;
|
||||
|
||||
const KeystrokeContext = createContext<KeystrokeBus | null>(null);
|
||||
|
||||
export interface KeystrokeProviderProps {
|
||||
children: React.ReactNode;
|
||||
/**
|
||||
* Optional reader override. Tests inject a synthetic reader so
|
||||
* they can `feed()` chunks instead of touching real stdin. Production
|
||||
* callers leave this unset and get the singleton.
|
||||
*/
|
||||
reader?: StdinReader;
|
||||
}
|
||||
|
||||
export function KeystrokeProvider({
|
||||
children,
|
||||
reader: providedReader,
|
||||
}: KeystrokeProviderProps): React.ReactElement {
|
||||
const handlersRef = useRef<Set<KeystrokeHandler>>(new Set());
|
||||
// Ref so the bus value's identity is stable across re-renders —
|
||||
// consumers don't accidentally re-subscribe every render.
|
||||
const busRef = useRef<KeystrokeBus | null>(null);
|
||||
if (busRef.current === null) {
|
||||
busRef.current = {
|
||||
subscribe(handler) {
|
||||
handlersRef.current.add(handler);
|
||||
return () => {
|
||||
handlersRef.current.delete(handler);
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
const reader = providedReader ?? getStdinReader();
|
||||
reader.start();
|
||||
const unsubscribe = reader.subscribe((ev) => {
|
||||
// Snapshot the handler set so handlers added/removed during
|
||||
// dispatch don't perturb iteration. Cheap — typical N=1-3.
|
||||
for (const fn of [...handlersRef.current]) fn(ev);
|
||||
});
|
||||
return () => {
|
||||
unsubscribe();
|
||||
// Don't `stop()` the singleton on every unmount — multiple
|
||||
// mounts (test reruns, hot-reload) must not tear down stdin.
|
||||
// The singleton's own start() is idempotent; stop() is the
|
||||
// process-exit handler's job.
|
||||
};
|
||||
}, [providedReader]);
|
||||
|
||||
return <KeystrokeContext.Provider value={busRef.current}>{children}</KeystrokeContext.Provider>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Subscribe to keystroke events. Mirrors Ink's `useInput` shape —
|
||||
* `handler(ev)` runs on every event while `isActive` is truthy
|
||||
* (default true). Set `isActive=false` to suspend the handler
|
||||
* (e.g. while a modal is up and shouldn't respond to global keys).
|
||||
*
|
||||
* Handler identity changes are tolerated — we re-subscribe via
|
||||
* useEffect on every render. Wrap your handler in `useCallback` if
|
||||
* you want to avoid that.
|
||||
*/
|
||||
export function useKeystroke(handler: KeystrokeHandler, isActive = true): void {
|
||||
const bus = useContext(KeystrokeContext);
|
||||
// Latest-handler ref so we can subscribe ONCE per active toggle
|
||||
// and still call the freshest closure on each event.
|
||||
const handlerRef = useRef(handler);
|
||||
handlerRef.current = handler;
|
||||
|
||||
useEffect(() => {
|
||||
if (!bus || !isActive) return undefined;
|
||||
return bus.subscribe((ev) => handlerRef.current(ev));
|
||||
}, [bus, isActive]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Lower-level hook for components that need a stable subscription
|
||||
* across the lifetime of the consumer (typically StdinReader-aware
|
||||
* unit tests).
|
||||
*/
|
||||
export function useKeystrokeBus(): KeystrokeBus | null {
|
||||
return useContext(KeystrokeContext);
|
||||
}
|
||||
|
||||
/** Test helper — assemble a KeyEvent with sensible defaults. */
|
||||
export function makeKeyEvent(overrides: Partial<KeyEvent> = {}): KeyEvent {
|
||||
return { input: "", ...overrides };
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
/**
|
||||
* `/loop <interval> <prompt>` parsing + status formatting.
|
||||
*
|
||||
* Claude-Code-style recurring prompt: at every `<interval>` tick, the
|
||||
* App auto-submits `<prompt>` as if the user typed it. Useful for "keep
|
||||
* checking the deploy" / "rerun tests" / "watch the build status until
|
||||
* green" — anything the user wants probed periodically without holding
|
||||
* the keyboard.
|
||||
*
|
||||
* Cancellation contract (enforced in App.tsx, not here — this file is
|
||||
* pure):
|
||||
* - `/loop stop` → explicit stop slash
|
||||
* - user types anything else → loop dies, user takes over
|
||||
* - Esc / /new / /clear / exit → loop dies
|
||||
* - one loop per session → re-issuing /loop replaces the prior
|
||||
*
|
||||
* Interval bounds:
|
||||
* - Minimum: 5 seconds (anything tighter and the model couldn't even
|
||||
* finish a turn before the next firing — we'd queue submits and
|
||||
* drift forever).
|
||||
* - Maximum: 6 hours (the upper end of "let it run while I sleep";
|
||||
* beyond that you should be writing a cron, not a TUI loop).
|
||||
*/
|
||||
|
||||
/** Lower bound on loop interval (ms). Faster than this would queue submits faster than turns finish. */
|
||||
export const MIN_LOOP_INTERVAL_MS = 5_000;
|
||||
/** Upper bound on loop interval (ms). Beyond a few hours, use cron. */
|
||||
export const MAX_LOOP_INTERVAL_MS = 6 * 60 * 60_000;
|
||||
|
||||
/**
|
||||
* Parse a duration string into milliseconds.
|
||||
*
|
||||
* Accepted forms (case-insensitive on the unit):
|
||||
* - `45` → 45_000 (bare number = seconds)
|
||||
* - `30s` → 30_000
|
||||
* - `5m` → 300_000
|
||||
* - `2h` → 7_200_000
|
||||
* - `1.5m` → 90_000 (fractional supported)
|
||||
*
|
||||
* Returns `null` on:
|
||||
* - empty input
|
||||
* - non-numeric / unknown unit
|
||||
* - negative or zero values
|
||||
* - values outside [MIN_LOOP_INTERVAL_MS, MAX_LOOP_INTERVAL_MS]
|
||||
*
|
||||
* Caller surfaces `null` as a usage hint to the user. Pure.
|
||||
*/
|
||||
export function parseLoopInterval(raw: string): { ms: number } | null {
|
||||
const s = raw.trim().toLowerCase();
|
||||
if (!s) return null;
|
||||
const m = /^([0-9]+(?:\.[0-9]+)?)(s|sec|secs|m|min|mins|h|hr|hrs)?$/.exec(s);
|
||||
if (!m) return null;
|
||||
const n = Number.parseFloat(m[1] ?? "");
|
||||
if (!Number.isFinite(n) || n <= 0) return null;
|
||||
const unit = m[2] ?? "s";
|
||||
let ms: number;
|
||||
if (unit === "s" || unit === "sec" || unit === "secs") ms = Math.round(n * 1000);
|
||||
else if (unit === "m" || unit === "min" || unit === "mins") ms = Math.round(n * 60_000);
|
||||
else if (unit === "h" || unit === "hr" || unit === "hrs") ms = Math.round(n * 60 * 60_000);
|
||||
else return null;
|
||||
if (ms < MIN_LOOP_INTERVAL_MS) return null;
|
||||
if (ms > MAX_LOOP_INTERVAL_MS) return null;
|
||||
return { ms };
|
||||
}
|
||||
|
||||
export interface ParsedLoopArgs {
|
||||
intervalMs: number;
|
||||
prompt: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse the full `/loop <interval> <prompt>` invocation. Args is the
|
||||
* commander-style tail (already split on whitespace, slash command
|
||||
* stripped). Returns `null` when the shape is wrong; caller emits a
|
||||
* usage hint.
|
||||
*
|
||||
* Special tokens:
|
||||
* - `stop` (case-insensitive) as the only arg → caller should stop
|
||||
* the active loop. Returns a sentinel: `{ stop: true }`.
|
||||
* - empty args → returns `{ status: true }` so the caller can print
|
||||
* the active-loop status (or "no loop active").
|
||||
*
|
||||
* Otherwise the first token is the interval, the rest is the prompt.
|
||||
* The prompt may itself be a slash command (`/loop 30s /status` is a
|
||||
* valid way to keep refreshing the status panel).
|
||||
*/
|
||||
export type LoopCommand =
|
||||
| { kind: "start"; intervalMs: number; prompt: string }
|
||||
| { kind: "stop" }
|
||||
| { kind: "status" }
|
||||
| { kind: "error"; message: string };
|
||||
|
||||
export function parseLoopCommand(args: readonly string[]): LoopCommand {
|
||||
if (args.length === 0) return { kind: "status" };
|
||||
const first = (args[0] ?? "").toLowerCase();
|
||||
if (args.length === 1 && (first === "stop" || first === "off" || first === "cancel")) {
|
||||
return { kind: "stop" };
|
||||
}
|
||||
const interval = parseLoopInterval(args[0] ?? "");
|
||||
if (!interval) {
|
||||
return {
|
||||
kind: "error",
|
||||
message:
|
||||
"usage: /loop <interval> <prompt> (interval = 5s..6h, e.g. 30s, 5m, 1h)\n" +
|
||||
" /loop stop (cancel an active loop)\n" +
|
||||
" /loop (show active-loop status)",
|
||||
};
|
||||
}
|
||||
const prompt = args.slice(1).join(" ").trim();
|
||||
if (!prompt) {
|
||||
return {
|
||||
kind: "error",
|
||||
message: `usage: /loop ${args[0]} <prompt> — interval is fine but the prompt is missing.`,
|
||||
};
|
||||
}
|
||||
return { kind: "start", intervalMs: interval.ms, prompt };
|
||||
}
|
||||
|
||||
/**
|
||||
* Format the active loop into a single-line status pill for the
|
||||
* modeline. `nextFireMs` is wall-clock ms until next firing; the
|
||||
* caller computes it from the stored `nextFireAt - Date.now()`.
|
||||
*
|
||||
* Examples:
|
||||
* "loop: `npm test` · next in 28s · iter 3"
|
||||
* "loop: `check deploy status` · firing now · iter 1"
|
||||
*/
|
||||
export function formatLoopStatus(prompt: string, nextFireMs: number, iter: number): string {
|
||||
const preview = prompt.length > 36 ? `${prompt.slice(0, 33)}…` : prompt;
|
||||
const when = nextFireMs <= 0 ? "firing now" : `next in ${formatDuration(nextFireMs)}`;
|
||||
return `loop: \`${preview}\` · ${when} · iter ${iter}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Human-friendly duration. Used by the loop status pill so a 4-minute
|
||||
* 23-second wait reads as "4m23s" instead of "263000".
|
||||
*/
|
||||
export function formatDuration(ms: number): string {
|
||||
if (ms < 1000) return `${ms}ms`;
|
||||
const totalSec = Math.round(ms / 1000);
|
||||
if (totalSec < 60) return `${totalSec}s`;
|
||||
const m = Math.floor(totalSec / 60);
|
||||
const s = totalSec % 60;
|
||||
if (m < 60) return s === 0 ? `${m}m` : `${m}m${s}s`;
|
||||
const h = Math.floor(m / 60);
|
||||
const mm = m % 60;
|
||||
return mm === 0 ? `${h}h` : `${h}h${mm}m`;
|
||||
}
|
||||
+718
-65
@@ -4,10 +4,13 @@
|
||||
* Handles the subset that actually shows up in LLM answers:
|
||||
* - ATX headers (# ##)
|
||||
* - Unordered / ordered lists
|
||||
* - Fenced code blocks (```lang)
|
||||
* - Inline **bold**, *italic*, `code`
|
||||
* - Task lists (- [ ] / - [x])
|
||||
* - Blockquotes (> …) — rendered with a left bar; nested / list-in-quote OK
|
||||
* - Fenced code blocks (```lang) — diagram langs get a distinct frame
|
||||
* - Inline **bold**, *italic*, `code`, ~~strikethrough~~
|
||||
* - GFM emoji shortcodes (:smile: :heart: :+1: …) — curated set
|
||||
* - Paragraphs separated by blank lines
|
||||
* - LaTeX delimiters are stripped (\( \), \[ \], \boxed{X})
|
||||
* - LaTeX delimiters stripped (\( \), \[ \], \boxed{X}); $…$ / $$…$$ too
|
||||
*
|
||||
* The goal is not TeX-perfect math — it's "stop showing raw backslashes to
|
||||
* the user." When the model insists on LaTeX, we strip the scaffolding and
|
||||
@@ -60,10 +63,57 @@ function toSubscript(s: string): string {
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Math indicator regex — gates the LaTeX-stripping pipeline so plain
|
||||
* prose with literal backslashes (Windows paths, escape sequences in
|
||||
* code prose) doesn't get mauled by the catch-all `\[a-zA-Z]+ → ""`
|
||||
* fallback at the bottom of stripMath.
|
||||
*
|
||||
* Without this guard, "F:\TEST1" got rendered as "F:1" because the
|
||||
* catch-all interpreted `\TEST` as an unknown LaTeX command and
|
||||
* deleted it. We only run the pipeline when the text actually
|
||||
* contains math markers we recognize: $-delimited spans, `\(`/`\[`
|
||||
* paren-delimiters, or one of the explicit LaTeX command names the
|
||||
* pipeline knows how to translate. Anything else passes through
|
||||
* untouched.
|
||||
*/
|
||||
const HAS_MATH_RE = new RegExp(
|
||||
[
|
||||
"\\$", // dollar-delimited (block or inline)
|
||||
"\\\\[([]", // \( or \[
|
||||
"\\\\[a-zA-Z]+\\s*\\{", // \anyCommand{...} — covers catch-all braced transforms
|
||||
// Bare (no-brace) LaTeX commands the pipeline knows how to handle.
|
||||
// Listed explicitly because a generic `\\[a-zA-Z]+` would also match
|
||||
// Windows paths (`F:\TEST1`) and re-introduce the bug we're fixing.
|
||||
"\\\\(?:cdot|times|div|pm|mp|leq|geq|neq|approx|in|notin|infty|sum|prod|int|alpha|beta|gamma|delta|theta|lambda|mu|pi|sigma|phi|omega|implies|iff|to|rightarrow|leftarrow|Rightarrow|Leftarrow|ldots|cdots|quad|qquad)(?![a-zA-Z])",
|
||||
"[\\^_]\\{", // LaTeX braced super/subscript: ^{2}, _{ij}
|
||||
"\\^[0-9+\\-n](?![A-Za-z])", // LaTeX single-char super: ^2, ^-, ^n
|
||||
"_[0-9+\\-](?![A-Za-z])", // LaTeX single-char sub: _1, _+, _-
|
||||
"\\^[A-Za-z0-9+\\-]+\\^", // Pandoc super: ^2^, ^abc^
|
||||
"(?<!~)~[A-Za-z0-9+\\-]+~(?!~)", // Pandoc sub: ~2~ (lookarounds avoid ~~strike~~)
|
||||
].join("|"),
|
||||
);
|
||||
|
||||
export function stripMath(s: string): string {
|
||||
if (!HAS_MATH_RE.test(s)) return s;
|
||||
return (
|
||||
s
|
||||
// Delimiters
|
||||
// Dollar-delimited math (KaTeX / MathJax convention). Block
|
||||
// `$$…$$` is unambiguous — strip the delimiters, wrap content
|
||||
// in double newlines so parseBlocks surfaces it as its own
|
||||
// paragraph instead of folding it into adjacent prose. Must
|
||||
// run BEFORE inline `$…$` so the block regex gets first crack.
|
||||
.replace(/\$\$([\s\S]+?)\$\$/g, (_m, c: string) => `\n\n${c.trim()}\n\n`)
|
||||
// Inline `$…$` is only stripped when a non-space char sits
|
||||
// immediately inside EACH dollar. That rules out:
|
||||
// - prices: `$5 per unit` (no closing $)
|
||||
// - `$5 and $10` (content ends/starts with space)
|
||||
// - `echo $HOME` (no closing $)
|
||||
// - `$ prompt` (space after open $)
|
||||
// The lookbehind/lookahead on `$` also keeps us from eating
|
||||
// half of a `$$…$$` pair that the block regex somehow missed.
|
||||
.replace(/(?<!\$)\$(?!\s)([^$\n]+?)(?<!\s)\$(?!\$)/g, "$1")
|
||||
// LaTeX delimiters
|
||||
.replace(/\\\(\s*/g, "")
|
||||
.replace(/\s*\\\)/g, "")
|
||||
.replace(/\\\[\s*/g, "\n")
|
||||
@@ -95,12 +145,19 @@ export function stripMath(s: string): string {
|
||||
.replace(/\\geq/g, "≥")
|
||||
.replace(/\\neq/g, "≠")
|
||||
.replace(/\\approx/g, "≈")
|
||||
.replace(/\\in\b/g, "∈")
|
||||
.replace(/\\notin\b/g, "∉")
|
||||
// Use `(?![a-zA-Z])` instead of `\b` because LaTeX commands
|
||||
// often abut subscript/superscript markers: `\sum_{i=1}^n`,
|
||||
// `\int_0^1`, etc. `\b` only fires between a word char and a
|
||||
// non-word char, but `_` IS a word char, so `\b` silently
|
||||
// refuses to match. The catch-all `\\[a-zA-Z]+` at the bottom
|
||||
// would then eat `\sum` to empty — losing the Σ entirely.
|
||||
// Lookahead-for-non-letter is the right fence: end of command.
|
||||
.replace(/\\in(?![a-zA-Z])/g, "∈")
|
||||
.replace(/\\notin(?![a-zA-Z])/g, "∉")
|
||||
.replace(/\\infty/g, "∞")
|
||||
.replace(/\\sum\b/g, "Σ")
|
||||
.replace(/\\prod\b/g, "Π")
|
||||
.replace(/\\int\b/g, "∫")
|
||||
.replace(/\\sum(?![a-zA-Z])/g, "Σ")
|
||||
.replace(/\\prod(?![a-zA-Z])/g, "Π")
|
||||
.replace(/\\int(?![a-zA-Z])/g, "∫")
|
||||
// Greek letters
|
||||
.replace(/\\alpha/g, "α")
|
||||
.replace(/\\beta/g, "β")
|
||||
@@ -114,9 +171,9 @@ export function stripMath(s: string): string {
|
||||
.replace(/\\phi/g, "φ")
|
||||
.replace(/\\omega/g, "ω")
|
||||
// Arrows / logic
|
||||
.replace(/\\implies\b/g, "⇒")
|
||||
.replace(/\\iff\b/g, "⇔")
|
||||
.replace(/\\to\b/g, "→")
|
||||
.replace(/\\implies(?![a-zA-Z])/g, "⇒")
|
||||
.replace(/\\iff(?![a-zA-Z])/g, "⇔")
|
||||
.replace(/\\to(?![a-zA-Z])/g, "→")
|
||||
.replace(/\\rightarrow/g, "→")
|
||||
.replace(/\\Rightarrow/g, "⇒")
|
||||
.replace(/\\leftarrow/g, "←")
|
||||
@@ -130,7 +187,27 @@ export function stripMath(s: string): string {
|
||||
.replace(/\\;/g, " ")
|
||||
.replace(/\\!/g, "")
|
||||
.replace(/\\\\/g, "\n")
|
||||
// Superscripts / subscripts — single token or {braced group of [\w+-]}
|
||||
// Pandoc-style inline super/subscripts — `x^2^` for superscript,
|
||||
// `H~2~O` for subscript. Handled HERE (not in INLINE_RE) because
|
||||
// the only useful rendering for a terminal is Unicode
|
||||
// super/subscript characters, which live in the same transform
|
||||
// pipeline as the LaTeX ^/_ rules below.
|
||||
//
|
||||
// Policy: only convert when EVERY character inside the markers
|
||||
// maps to a Unicode super/subscript glyph. `^2^` → `²` (good),
|
||||
// but `^foo^` can't be truly superscripted, so we leave the
|
||||
// whole thing literal rather than dropping the markers and
|
||||
// losing the model's intent. Guards on `~` use lookaround so
|
||||
// the subscript rule never fires inside a `~~strikethrough~~`.
|
||||
.replace(/\^([A-Za-z0-9+\-]+)\^/g, (m, g: string) => {
|
||||
for (const c of g) if (SUPERSCRIPT[c] === undefined) return m;
|
||||
return toSuperscript(g);
|
||||
})
|
||||
.replace(/(?<!~)~(?!~)([A-Za-z0-9+\-]+)~(?!~)/g, (m, g: string) => {
|
||||
for (const c of g) if (SUBSCRIPT[c] === undefined) return m;
|
||||
return toSubscript(g);
|
||||
})
|
||||
// LaTeX super/subscripts — single token or {braced group of [\w+-]}
|
||||
.replace(/\^\{([\w+-]+)\}/g, (_m, g: string) => toSuperscript(g))
|
||||
.replace(/\^([0-9+\-n])/g, (_m, g: string) => toSuperscript(g))
|
||||
.replace(/_\{([\w+-]+)\}/g, (_m, g: string) => toSubscript(g))
|
||||
@@ -146,6 +223,154 @@ export function stripMath(s: string): string {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* GFM emoji shortcode table. Curated ~70 entries covering what LLMs
|
||||
* actually emit in chat — faces, hearts, gestures, common signals
|
||||
* (✅ ❌ ⚠️), tech / productivity glyphs, a handful of weather and
|
||||
* objects. We deliberately skip flags (region codes, rarely used)
|
||||
* and the long tail.
|
||||
*
|
||||
* Unknown shortcodes pass through as literal `:name:` — safer than
|
||||
* guessing, and prevents false positives like `file.ts:10:` or a
|
||||
* `:classname:` in code from turning into garbage.
|
||||
*/
|
||||
const EMOJI_MAP: Record<string, string> = {
|
||||
// faces
|
||||
smile: "😄",
|
||||
smiley: "😃",
|
||||
grin: "😁",
|
||||
grinning: "😀",
|
||||
joy: "😂",
|
||||
laughing: "😆",
|
||||
heart_eyes: "😍",
|
||||
blush: "😊",
|
||||
sunglasses: "😎",
|
||||
thinking: "🤔",
|
||||
neutral_face: "😐",
|
||||
confused: "😕",
|
||||
cry: "😢",
|
||||
sob: "😭",
|
||||
rage: "😡",
|
||||
angry: "😠",
|
||||
scream: "😱",
|
||||
wink: "😉",
|
||||
kissing_heart: "😘",
|
||||
// hearts
|
||||
heart: "❤️",
|
||||
orange_heart: "🧡",
|
||||
yellow_heart: "💛",
|
||||
green_heart: "💚",
|
||||
blue_heart: "💙",
|
||||
purple_heart: "💜",
|
||||
black_heart: "🖤",
|
||||
white_heart: "🤍",
|
||||
broken_heart: "💔",
|
||||
sparkling_heart: "💖",
|
||||
two_hearts: "💕",
|
||||
// gestures
|
||||
"+1": "👍",
|
||||
"-1": "👎",
|
||||
thumbsup: "👍",
|
||||
thumbsdown: "👎",
|
||||
wave: "👋",
|
||||
clap: "👏",
|
||||
muscle: "💪",
|
||||
ok_hand: "👌",
|
||||
pray: "🙏",
|
||||
fist: "✊",
|
||||
point_up: "☝️",
|
||||
raised_hands: "🙌",
|
||||
handshake: "🤝",
|
||||
// symbols / signals
|
||||
rocket: "🚀",
|
||||
fire: "🔥",
|
||||
star: "⭐",
|
||||
star2: "🌟",
|
||||
sparkles: "✨",
|
||||
boom: "💥",
|
||||
zap: "⚡",
|
||||
tada: "🎉",
|
||||
bulb: "💡",
|
||||
warning: "⚠️",
|
||||
x: "❌",
|
||||
white_check_mark: "✅",
|
||||
heavy_check_mark: "✔️",
|
||||
ballot_box_with_check: "☑️",
|
||||
no_entry: "⛔",
|
||||
question: "❓",
|
||||
exclamation: "❗",
|
||||
bangbang: "‼️",
|
||||
bell: "🔔",
|
||||
mute: "🔕",
|
||||
hundred: "💯",
|
||||
"100": "💯",
|
||||
eyes: "👀",
|
||||
// tech / productivity
|
||||
computer: "💻",
|
||||
iphone: "📱",
|
||||
hammer: "🔨",
|
||||
wrench: "🔧",
|
||||
gear: "⚙️",
|
||||
package: "📦",
|
||||
floppy_disk: "💾",
|
||||
key: "🔑",
|
||||
lock: "🔒",
|
||||
unlock: "🔓",
|
||||
mag: "🔍",
|
||||
memo: "📝",
|
||||
pencil: "✏️",
|
||||
bookmark: "🔖",
|
||||
// charts / time
|
||||
chart_with_upwards_trend: "📈",
|
||||
chart_with_downwards_trend: "📉",
|
||||
bar_chart: "📊",
|
||||
hourglass: "⏳",
|
||||
calendar: "📅",
|
||||
// misc
|
||||
robot: "🤖",
|
||||
ghost: "👻",
|
||||
bug: "🐛",
|
||||
coffee: "☕",
|
||||
beer: "🍺",
|
||||
sun: "☀️",
|
||||
cloud: "☁️",
|
||||
rainbow: "🌈",
|
||||
speech_balloon: "💬",
|
||||
thought_balloon: "💭",
|
||||
construction: "🚧",
|
||||
};
|
||||
|
||||
/**
|
||||
* GFM autolinks — bare `<url>` / `<email>` shorthand. Rewrite to the
|
||||
* full `[url](url)` form so the existing link-rendering path applies
|
||||
* (blue + underline for external, URL validated for local). Only
|
||||
* unambiguous URL schemes are expanded: http(s) / ftp / mailto.
|
||||
* Anything else stays as literal `<foo>` text — some prose has
|
||||
* angle-bracketed phrases that aren't URLs.
|
||||
*/
|
||||
export function expandAutolinks(s: string): string {
|
||||
return s.replace(/<((?:https?|ftp|mailto):[^\s<>]+)>/g, "[$1]($1)");
|
||||
}
|
||||
|
||||
/**
|
||||
* Expand `:name:` GFM emoji shortcodes via {@link EMOJI_MAP}. The
|
||||
* regex matches broadly (letters / digits / `+` / `_` / `-`) so
|
||||
* `:+1:` works, but the ultimate gate is the map lookup — unknown
|
||||
* names stay literal. That's what keeps `file.ts:10:` and
|
||||
* `:classname:` from being mangled.
|
||||
*/
|
||||
export function expandEmoji(s: string): string {
|
||||
// Character class covers the whole GFM shortcode alphabet
|
||||
// (letters, digits, `_`, `+`, `-`). The leading `-` slot is
|
||||
// needed so `:-1:` resolves; putting it at the end of the class
|
||||
// keeps it literal. The map lookup is the true gate — unknown
|
||||
// names pass through untouched, so false-positive regex matches
|
||||
// in prose / code don't corrupt the text.
|
||||
return s.replace(/:([a-z0-9_+-]+):/gi, (m, name: string) => {
|
||||
return EMOJI_MAP[name.toLowerCase()] ?? m;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Citation links: `[text](url)` where url either points outside the repo
|
||||
* (rendered as a plain external link) or resolves to a file/line in the
|
||||
@@ -192,16 +417,63 @@ export function parseCitationUrl(url: string): CitationParts | null {
|
||||
return { path: trimmed };
|
||||
}
|
||||
|
||||
/**
|
||||
* Common typo-equivalents per file extension. When the model cites
|
||||
* `foo.ts` but the real file is `foo.tsx`, the validator still
|
||||
* resolves it via this map. Symmetric pairs (`.ts` ↔ `.tsx`,
|
||||
* `.js` ↔ `.jsx`, etc.) keep both directions working.
|
||||
*/
|
||||
const SIBLING_EXTENSIONS = new Map<string, ReadonlyArray<string>>([
|
||||
[".ts", [".tsx", ".mts", ".cts"]],
|
||||
[".tsx", [".ts"]],
|
||||
[".js", [".jsx", ".mjs", ".cjs"]],
|
||||
[".jsx", [".js"]],
|
||||
[".mjs", [".js", ".cjs"]],
|
||||
[".cjs", [".js", ".mjs"]],
|
||||
[".mts", [".ts"]],
|
||||
[".cts", [".ts"]],
|
||||
]);
|
||||
|
||||
function extOf(p: string): string {
|
||||
const m = /\.[^./\\]+$/.exec(p);
|
||||
return m ? m[0] : "";
|
||||
}
|
||||
|
||||
export function validateCitation(url: string, projectRoot: string): CitationStatus {
|
||||
const parts = parseCitationUrl(url);
|
||||
if (!parts || !parts.path) return { ok: false, reason: "empty path" };
|
||||
const fullPath = isAbsolute(parts.path) ? parts.path : join(projectRoot, parts.path);
|
||||
let stat: ReturnType<typeof statSync>;
|
||||
try {
|
||||
stat = statSync(fullPath);
|
||||
} catch {
|
||||
return { ok: false, reason: "file not found" };
|
||||
// Strip a leading `/` or `\\`. Models habitually write `/foo.ts`
|
||||
// meaning "project-root relative" — Aider / Claude-Code convention —
|
||||
// rather than POSIX root-absolute. A literal absolute path is still
|
||||
// reachable as `C:\foo` on Windows or once the strip drops the slash
|
||||
// and Node's `isAbsolute` correctly rejects what's left. Real unix
|
||||
// absolute references like `/etc/hosts` in a code citation are vanishingly
|
||||
// rare — if anyone needs one we can revisit.
|
||||
const normalized = parts.path.replace(/^[/\\]+/, "");
|
||||
const baseFullPath = isAbsolute(normalized) ? normalized : join(projectRoot, normalized);
|
||||
// Sibling-extension fallback: models routinely cite `foo.ts` when
|
||||
// the actual file is `foo.tsx` (or `.js`/`.jsx`/`.mjs`/`.cjs`).
|
||||
// The citation is the model's intent — it's right about WHICH
|
||||
// file, just typed the wrong extension. Probing siblings keeps a
|
||||
// genuinely missing path flagged while letting `.ts`↔`.tsx` slip
|
||||
// through silently.
|
||||
const siblings = SIBLING_EXTENSIONS.get(extOf(baseFullPath)) ?? [];
|
||||
const candidates = [
|
||||
baseFullPath,
|
||||
...siblings.map((ext) => baseFullPath.replace(/\.[^./\\]+$/, ext)),
|
||||
];
|
||||
let fullPath = baseFullPath;
|
||||
let stat: ReturnType<typeof statSync> | null = null;
|
||||
for (const candidate of candidates) {
|
||||
try {
|
||||
stat = statSync(candidate);
|
||||
fullPath = candidate;
|
||||
break;
|
||||
} catch {
|
||||
// try next candidate
|
||||
}
|
||||
}
|
||||
if (!stat) return { ok: false, reason: "file not found" };
|
||||
if (!stat.isFile()) return { ok: false, reason: "not a file" };
|
||||
if (parts.startLine === undefined) return { ok: true };
|
||||
let lineCount: number;
|
||||
@@ -221,11 +493,36 @@ export function validateCitation(url: string, projectRoot: string): CitationStat
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
/**
|
||||
* Heuristic: should this link URL be treated as a repo-file citation
|
||||
* (and thus validated / marked red-strikethrough if missing)? The
|
||||
* point is to STOP flagging things that obviously aren't paths —
|
||||
* otherwise users see a red "broken citations" box for content the
|
||||
* model wrote legitimately:
|
||||
* - `#anchor` — in-page anchor jump (not a file ref)
|
||||
* - `url` / `path` — placeholder words in demo text
|
||||
* - `/` — bare root
|
||||
* Rule: must contain a path separator, a dot, OR a `#` with a non-
|
||||
* bare-anchor prefix. Those are the shapes real file references use.
|
||||
*/
|
||||
export function shouldValidateAsCitation(url: string): boolean {
|
||||
// Anchor-only: `#foo` / `#` — page-local, not a file
|
||||
if (url.startsWith("#")) return false;
|
||||
// Bare root placeholders
|
||||
if (url === "/" || url === "\\" || url === "") return false;
|
||||
// Must look like a path: contains `/`, `\`, or `.` somewhere
|
||||
if (!/[/\\.]/.test(url)) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pre-scan rendered text for every `[text](url)` link, validate the
|
||||
* citation-shaped ones, and cache the result. Done once per Markdown
|
||||
* mount so InlineMd doesn't re-stat the filesystem on every keystroke
|
||||
* during streaming. External links short-circuit (no fs work).
|
||||
* during streaming. External links short-circuit (no fs work);
|
||||
* non-citation-shaped URLs are skipped entirely (left as default
|
||||
* cyan-underline link rendering) so placeholders in demo prose don't
|
||||
* clutter the broken-citation summary with false positives.
|
||||
*/
|
||||
export function collectCitations(text: string, projectRoot: string): CitationMap {
|
||||
const map: CitationMap = new Map();
|
||||
@@ -233,6 +530,7 @@ export function collectCitations(text: string, projectRoot: string): CitationMap
|
||||
for (const m of text.matchAll(re)) {
|
||||
const url = m[2] ?? "";
|
||||
if (!url || isExternalUrl(url)) continue;
|
||||
if (!shouldValidateAsCitation(url)) continue;
|
||||
if (map.has(url)) continue;
|
||||
map.set(url, validateCitation(url, projectRoot));
|
||||
}
|
||||
@@ -256,7 +554,7 @@ export function collectCitations(text: string, projectRoot: string): CitationMap
|
||||
* `parseBlocks`.
|
||||
*/
|
||||
const INLINE_RE =
|
||||
/(\[([^\]\n]+)\]\(([^)\n]+)\)|\*\*([^*\n]+?)\*\*|```([^\n]+?)```|`([^`\n]+?)`|(?<![*\w])\*([^*\n]+?)\*(?!\w))/g;
|
||||
/(\[([^\]\n]+)\]\(([^)\n]+)\)|\*\*\*([^*\n]+?)\*\*\*|\*\*([^*\n]+?)\*\*|```([^\n]+?)```|`([^`\n]+?)`|~~([^~\n]+?)~~|(?<![*\w])\*([^*\n]+?)\*(?!\w)|\\([*_~`[\](){}#+\-.!\\]))/g;
|
||||
|
||||
function InlineMd({
|
||||
text,
|
||||
@@ -277,10 +575,13 @@ function InlineMd({
|
||||
}
|
||||
// Groups, in the order they appear in INLINE_RE:
|
||||
// m[2] = link text m[3] = link url
|
||||
// m[4] = bold content (inside ** **)
|
||||
// m[5] = triple-backtick content (strip leading lang tag)
|
||||
// m[6] = single-backtick inline code
|
||||
// m[7] = italic content (inside * *)
|
||||
// m[4] = bold-italic content (inside *** ***)
|
||||
// m[5] = bold content (inside ** **)
|
||||
// m[6] = triple-backtick content (strip leading lang tag)
|
||||
// m[7] = single-backtick inline code
|
||||
// m[8] = strikethrough content (inside ~~ ~~)
|
||||
// m[9] = italic content (inside * *)
|
||||
// m[10] = backslash-escaped char (emit as literal)
|
||||
if (m[2] !== undefined && m[3] !== undefined) {
|
||||
const linkText = m[2];
|
||||
const url = m[3];
|
||||
@@ -308,31 +609,49 @@ function InlineMd({
|
||||
}
|
||||
} else if (m[4] !== undefined) {
|
||||
parts.push(
|
||||
<Text key={`b${idx++}`} bold>
|
||||
<Text key={`bi${idx++}`} bold italic>
|
||||
{m[4]}
|
||||
</Text>,
|
||||
);
|
||||
} else if (m[5] !== undefined) {
|
||||
parts.push(
|
||||
<Text key={`b${idx++}`} bold>
|
||||
{m[5]}
|
||||
</Text>,
|
||||
);
|
||||
} else if (m[6] !== undefined) {
|
||||
// One-line fenced span: ```bash echo hi``` → drop the "bash "
|
||||
// language tag so the user doesn't see it rendered in code color.
|
||||
const stripped = m[5].replace(/^(\w+)\s+/, "");
|
||||
const stripped = m[6].replace(/^(\w+)\s+/, "");
|
||||
parts.push(
|
||||
<Text key={`c${idx++}`} color="yellow">
|
||||
{stripped}
|
||||
</Text>,
|
||||
);
|
||||
} else if (m[6] !== undefined) {
|
||||
parts.push(
|
||||
<Text key={`c${idx++}`} color="yellow">
|
||||
{m[6]}
|
||||
</Text>,
|
||||
);
|
||||
} else if (m[7] !== undefined) {
|
||||
parts.push(
|
||||
<Text key={`i${idx++}`} italic>
|
||||
<Text key={`c${idx++}`} color="yellow">
|
||||
{m[7]}
|
||||
</Text>,
|
||||
);
|
||||
} else if (m[8] !== undefined) {
|
||||
parts.push(
|
||||
<Text key={`s${idx++}`} strikethrough dimColor>
|
||||
{m[8]}
|
||||
</Text>,
|
||||
);
|
||||
} else if (m[9] !== undefined) {
|
||||
parts.push(
|
||||
<Text key={`i${idx++}`} italic>
|
||||
{m[9]}
|
||||
</Text>,
|
||||
);
|
||||
} else if (m[10] !== undefined) {
|
||||
// Backslash escape — emit the escaped char as a plain Text node
|
||||
// so the subsequent pass of the regex engine doesn't re-interpret
|
||||
// the `*` / `` ` `` / `~` as markup. The `\` is dropped; only the
|
||||
// escaped char survives.
|
||||
parts.push(<Text key={`esc${idx++}`}>{m[10]}</Text>);
|
||||
}
|
||||
last = start + m[0].length;
|
||||
}
|
||||
@@ -359,12 +678,37 @@ function InlineMd({
|
||||
* length includes invisible markup chars.
|
||||
*/
|
||||
export function stripInlineMarkup(s: string): string {
|
||||
return s
|
||||
.replace(/\[([^\]\n]+)\]\(([^)\n]+)\)/g, "$1")
|
||||
.replace(/\*\*([^*\n]+?)\*\*/g, "$1")
|
||||
.replace(/```([^\n]+?)```/g, (_m, c: string) => c.replace(/^(\w+)\s+/, ""))
|
||||
.replace(/`([^`\n]+?)`/g, "$1")
|
||||
.replace(/(?<![*\w])\*([^*\n]+?)\*(?!\w)/g, "$1");
|
||||
// Single-pass strip using INLINE_RE so alternation precedence exactly
|
||||
// matches the runtime renderer. The prior implementation chained
|
||||
// sequential .replace() calls, which broke backslash escapes — the
|
||||
// inline-code regex would eat `\`code\`` as a `code\`` span before
|
||||
// the escape pass got a chance to neutralize each `\``.
|
||||
return s.replace(
|
||||
INLINE_RE,
|
||||
(
|
||||
match: string,
|
||||
_alt: string,
|
||||
linkText: string | undefined,
|
||||
_url: string | undefined,
|
||||
boldItalic: string | undefined,
|
||||
bold: string | undefined,
|
||||
code3: string | undefined,
|
||||
code1: string | undefined,
|
||||
strike: string | undefined,
|
||||
italic: string | undefined,
|
||||
escapeChar: string | undefined,
|
||||
) => {
|
||||
if (linkText !== undefined) return linkText;
|
||||
if (boldItalic !== undefined) return boldItalic;
|
||||
if (bold !== undefined) return bold;
|
||||
if (code3 !== undefined) return code3.replace(/^(\w+)\s+/, "");
|
||||
if (code1 !== undefined) return code1;
|
||||
if (strike !== undefined) return strike;
|
||||
if (italic !== undefined) return italic;
|
||||
if (escapeChar !== undefined) return escapeChar;
|
||||
return match;
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -384,12 +728,35 @@ interface HeadingBlock {
|
||||
level: number;
|
||||
text: string;
|
||||
}
|
||||
/**
|
||||
* One bullet-list item. `task` marks GFM task-list entries:
|
||||
* - `- [ ] do the thing` → `{ text: "do the thing", task: "todo" }`
|
||||
* - `- [x] shipped` → `{ text: "shipped", task: "done" }`
|
||||
* Regular bullets leave `task` undefined.
|
||||
*/
|
||||
export interface BulletItem {
|
||||
text: string;
|
||||
task?: "done" | "todo";
|
||||
}
|
||||
interface BulletBlock {
|
||||
kind: "bullet";
|
||||
items: string[];
|
||||
items: BulletItem[];
|
||||
ordered: boolean;
|
||||
start: number;
|
||||
}
|
||||
interface BlockquoteBlock {
|
||||
kind: "quote";
|
||||
/**
|
||||
* Parsed child blocks. After stripping one `>` prefix from each
|
||||
* gathered line, the remainder is re-fed through `parseBlocks` so
|
||||
* block-level constructs inside the quote (nested `>>` quotes,
|
||||
* lists, code fences, tables, …) render with their normal
|
||||
* formatting instead of as flattened text. Nesting depth is
|
||||
* whatever the markdown source expresses — the recursion closes
|
||||
* naturally when no line starts with `>` at its current level.
|
||||
*/
|
||||
children: Block[];
|
||||
}
|
||||
interface CodeBlock {
|
||||
kind: "code";
|
||||
lang: string;
|
||||
@@ -428,6 +795,7 @@ type Block =
|
||||
| ParagraphBlock
|
||||
| HeadingBlock
|
||||
| BulletBlock
|
||||
| BlockquoteBlock
|
||||
| CodeBlock
|
||||
| HrBlock
|
||||
| EditBlockView
|
||||
@@ -436,7 +804,12 @@ type Block =
|
||||
export function parseBlocks(raw: string): Block[] {
|
||||
const lines = raw.split(/\r?\n/);
|
||||
const out: Block[] = [];
|
||||
let para: string[] = [];
|
||||
// Each entry is one source line inside the current paragraph plus
|
||||
// the hard-break flag that applies AFTER it. Hard break = trailing
|
||||
// ` ` (two+ spaces before newline) per GFM. The flag decides
|
||||
// whether this line's content joins to the next with `\n` (hard,
|
||||
// preserves visual newline) or ` ` (soft, default paragraph reflow).
|
||||
let para: Array<{ text: string; hardBreak: boolean }> = [];
|
||||
let inCode = false;
|
||||
let codeLang = "";
|
||||
let codeBuf: string[] = [];
|
||||
@@ -448,10 +821,16 @@ export function parseBlocks(raw: string): Block[] {
|
||||
let codeFence = "";
|
||||
|
||||
const flushPara = () => {
|
||||
if (para.length) {
|
||||
out.push({ kind: "paragraph", text: para.join(" ") });
|
||||
para = [];
|
||||
if (para.length === 0) return;
|
||||
let joined = "";
|
||||
for (let k = 0; k < para.length; k++) {
|
||||
joined += para[k]!.text;
|
||||
if (k < para.length - 1) {
|
||||
joined += para[k]!.hardBreak ? "\n" : " ";
|
||||
}
|
||||
}
|
||||
out.push({ kind: "paragraph", text: joined });
|
||||
para = [];
|
||||
};
|
||||
const flushList = () => {
|
||||
if (listBuf) {
|
||||
@@ -472,7 +851,7 @@ export function parseBlocks(raw: string): Block[] {
|
||||
if (!inCode && /^<{7} SEARCH\s*$/.test(line)) {
|
||||
// Filename is the previous non-blank line we just pushed to para.
|
||||
// Pull it back out; if there isn't one, treat as literal text.
|
||||
const filename = para.pop()?.trim();
|
||||
const filename = para.pop()?.text.trim();
|
||||
if (filename) {
|
||||
flushPara();
|
||||
flushList();
|
||||
@@ -500,7 +879,7 @@ export function parseBlocks(raw: string): Block[] {
|
||||
}
|
||||
// Malformed — no separator or no close. Fall through: put
|
||||
// the filename back in the paragraph so we don't lose it.
|
||||
para.push(filename);
|
||||
para.push({ text: filename, hardBreak: false });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -656,6 +1035,38 @@ export function parseBlocks(raw: string): Block[] {
|
||||
}
|
||||
}
|
||||
|
||||
// Blockquote: consecutive `>` lines gather into one quote block.
|
||||
// We strip exactly one level of `>` prefix, then recursively run
|
||||
// the inner text through `parseBlocks`. That gets us:
|
||||
// - Nested `>>` rendering as a quote-in-a-quote (inner `>` is
|
||||
// still present after the outer strip, so the recursion fires).
|
||||
// - Lists, code fences, tables inside a quote — all keep their
|
||||
// normal formatting because parseBlocks handles them again.
|
||||
// - Blank-`>` lines become paragraph breaks inside the quote.
|
||||
//
|
||||
// We don't implement GFM "lazy continuation" (a line without `>`
|
||||
// after a non-empty quote line is still part of the quote) — LLMs
|
||||
// reliably re-emit `>` on each line, and enforcing the explicit
|
||||
// prefix avoids accidentally swallowing the paragraph that
|
||||
// follows a quote.
|
||||
const quoteMatch = line.match(/^\s*>\s?(.*)$/);
|
||||
if (quoteMatch) {
|
||||
flushPara();
|
||||
flushList();
|
||||
const innerLines: string[] = [quoteMatch[1] ?? ""];
|
||||
let j = i + 1;
|
||||
while (j < lines.length) {
|
||||
const nxt = lines[j]!.replace(/\s+$/g, "");
|
||||
const m = nxt.match(/^\s*>\s?(.*)$/);
|
||||
if (!m) break;
|
||||
innerLines.push(m[1] ?? "");
|
||||
j++;
|
||||
}
|
||||
out.push({ kind: "quote", children: parseBlocks(innerLines.join("\n")) });
|
||||
i = j - 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
const bm = line.match(/^\s*[-*+]\s+(.+)$/);
|
||||
if (bm) {
|
||||
flushPara();
|
||||
@@ -663,7 +1074,7 @@ export function parseBlocks(raw: string): Block[] {
|
||||
flushList();
|
||||
listBuf = { kind: "bullet", items: [], ordered: false, start: 1 };
|
||||
}
|
||||
listBuf.items.push(bm[1]!);
|
||||
listBuf.items.push(parseBulletItem(bm[1]!));
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -674,12 +1085,18 @@ export function parseBlocks(raw: string): Block[] {
|
||||
flushList();
|
||||
listBuf = { kind: "bullet", items: [], ordered: true, start: Number(om[1]) };
|
||||
}
|
||||
listBuf.items.push(om[2]!);
|
||||
listBuf.items.push(parseBulletItem(om[2]!));
|
||||
continue;
|
||||
}
|
||||
|
||||
flushList();
|
||||
para.push(line);
|
||||
// Hard line break: trailing ` ` (two or more spaces) on the raw
|
||||
// line before whitespace was stripped. Per GFM, this forces a
|
||||
// visible newline inside a paragraph (where soft-wrapped lines
|
||||
// normally join with a space). We stash the flag on THIS line
|
||||
// so flushPara knows whether to emit `\n` or ` ` AFTER it.
|
||||
const hardBreak = / {2,}\r?$/.test(rawLine);
|
||||
para.push({ text: line, hardBreak });
|
||||
}
|
||||
|
||||
if (inCode && codeBuf.length) {
|
||||
@@ -690,33 +1107,52 @@ export function parseBlocks(raw: string): Block[] {
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* GFM task-list prefix sniff: `[ ] …` / `[x] …` / `[X] …` at the start
|
||||
* of a bullet item's text becomes a task entry; anything else stays a
|
||||
* plain item. The bracket form without a trailing space (e.g. `[x]end`)
|
||||
* isn't standard and rarely appears — we require the space to avoid
|
||||
* false positives on array-index-style prose like `[1] see ref`.
|
||||
*/
|
||||
function parseBulletItem(raw: string): BulletItem {
|
||||
const m = raw.match(/^\[([ xX])\]\s+(.*)$/);
|
||||
if (!m) return { text: raw };
|
||||
const done = m[1]!.toLowerCase() === "x";
|
||||
return { text: m[2] ?? "", task: done ? "done" : "todo" };
|
||||
}
|
||||
|
||||
function BlockView({ block, citations }: { block: Block; citations?: CitationMap }) {
|
||||
switch (block.kind) {
|
||||
case "heading":
|
||||
return (
|
||||
<Text bold color="cyan">
|
||||
<InlineMd text={block.text} citations={citations} />
|
||||
</Text>
|
||||
);
|
||||
return <HeadingView level={block.level} text={block.text} citations={citations} />;
|
||||
case "paragraph":
|
||||
return <InlineMd text={block.text} citations={citations} />;
|
||||
return <ParagraphView text={block.text} citations={citations} />;
|
||||
case "bullet":
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
{block.items.map((item, i) => (
|
||||
<Box key={`${i}-${item.slice(0, 24)}`}>
|
||||
<Text color="cyan">{block.ordered ? ` ${block.start + i}. ` : " • "}</Text>
|
||||
<InlineMd text={item} citations={citations} />
|
||||
<Box key={`${i}-${item.text.slice(0, 24)}`}>
|
||||
<Text color={item.task === "done" ? "green" : "cyan"}>
|
||||
{bulletPrefix(block, i, item)}
|
||||
</Text>
|
||||
{item.task === "done" ? (
|
||||
<Text strikethrough dimColor>
|
||||
<InlineMd text={item.text} citations={citations} />
|
||||
</Text>
|
||||
) : (
|
||||
<InlineMd text={item.text} citations={citations} />
|
||||
)}
|
||||
</Box>
|
||||
))}
|
||||
</Box>
|
||||
);
|
||||
case "quote":
|
||||
return <BlockquoteView block={block} citations={citations} />;
|
||||
case "code":
|
||||
return (
|
||||
<Box borderStyle="single" borderColor="gray" paddingX={1}>
|
||||
<Text color="yellow">{block.text}</Text>
|
||||
</Box>
|
||||
);
|
||||
if (DIAGRAM_LANGS.has(block.lang.toLowerCase())) {
|
||||
return <DiagramCodeBlock lang={block.lang} text={block.text} />;
|
||||
}
|
||||
return <CodeBlockView lang={block.lang} text={block.text} />;
|
||||
case "edit-block":
|
||||
return <EditBlockRow block={block} />;
|
||||
case "table":
|
||||
@@ -726,6 +1162,82 @@ function BlockView({ block, citations }: { block: Block; citations?: CitationMap
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Paragraph renderer. Plain text goes straight to InlineMd. If the
|
||||
* paragraph carries embedded `\n` (inserted by parseBlocks when it
|
||||
* sees a GFM hard break — trailing ` ` on a source line), split
|
||||
* and render each segment as its own row so the newline is visible
|
||||
* in the terminal. Single-line paragraphs still render as one row
|
||||
* for tight layout.
|
||||
*/
|
||||
function ParagraphView({ text, citations }: { text: string; citations?: CitationMap }) {
|
||||
if (!text.includes("\n")) {
|
||||
return <InlineMd text={text} citations={citations} />;
|
||||
}
|
||||
const rows = text.split("\n");
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
{rows.map((row, i) => (
|
||||
// biome-ignore lint/suspicious/noArrayIndexKey: hard-break rows are source-ordered and never reorder
|
||||
<InlineMd key={`ln-${i}`} text={row} citations={citations} />
|
||||
))}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Pick the gutter glyph for a bullet-list item:
|
||||
* - ordered → ` N. `
|
||||
* - task done → ` ☒ ` (green + struck-through in the caller)
|
||||
* - task todo → ` ☐ `
|
||||
* - plain → ` • `
|
||||
* Width is stable within a list so text after the prefix stays aligned.
|
||||
*/
|
||||
function bulletPrefix(block: BulletBlock, i: number, item: BulletItem): string {
|
||||
if (block.ordered) return ` ${block.start + i}. `;
|
||||
if (item.task === "done") return " ☒ ";
|
||||
if (item.task === "todo") return " ☐ ";
|
||||
return " • ";
|
||||
}
|
||||
|
||||
/**
|
||||
* Blockquote renderer: left-bar frame (`borderLeft` only, dim) that
|
||||
* wraps any child block content. The bar grows with the rendered
|
||||
* height automatically — no manual per-line prefix — so a quote
|
||||
* containing a list, a code block, or another quote still looks
|
||||
* right regardless of how many rows each child consumes.
|
||||
*
|
||||
* Nested `>>` quotes surface as a BlockquoteView inside another
|
||||
* BlockquoteView, producing two adjacent bars (visually nested).
|
||||
* Inner blocks keep their normal colors (code yellow, bullet cyan,
|
||||
* etc.) — we dim only the bar, not the content, so a code snippet
|
||||
* inside a quote still reads as code.
|
||||
*/
|
||||
function BlockquoteView({
|
||||
block,
|
||||
citations,
|
||||
}: {
|
||||
block: BlockquoteBlock;
|
||||
citations?: CitationMap;
|
||||
}) {
|
||||
return (
|
||||
<Box
|
||||
borderStyle="single"
|
||||
borderColor="#c4b5fd"
|
||||
borderTop={false}
|
||||
borderRight={false}
|
||||
borderBottom={false}
|
||||
paddingLeft={1}
|
||||
flexDirection="column"
|
||||
gap={1}
|
||||
>
|
||||
{block.children.map((child, i) => (
|
||||
<BlockView key={`q-${i}-${child.kind}`} block={child} citations={citations} />
|
||||
))}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Split one table row into trimmed cells. Leading/trailing column
|
||||
* markers are optional (both `| a | b |` and `a | b` are accepted).
|
||||
@@ -867,8 +1379,149 @@ function EditBlockRow({ block }: { block: EditBlockView }) {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Code-block languages that render as graphs/diagrams in real
|
||||
* browsers but can't be drawn in a terminal. For these we show the
|
||||
* SOURCE with a distinct frame + a header and a "paste into viewer"
|
||||
* hint, so the user knows they're looking at a diagram-source block
|
||||
* rather than executable code.
|
||||
*/
|
||||
const DIAGRAM_LANGS = new Set([
|
||||
"mermaid",
|
||||
"dot",
|
||||
"graphviz",
|
||||
"plantuml",
|
||||
"puml",
|
||||
"flowchart",
|
||||
"sequencediagram",
|
||||
"gantt",
|
||||
"erdiagram",
|
||||
]);
|
||||
|
||||
/**
|
||||
* Viewer URL hint keyed by language — shown dim at the bottom of a
|
||||
* diagram-source block so users know where to paste it to see the
|
||||
* actual graph. Fallback is a generic "use the matching viewer" for
|
||||
* less common langs.
|
||||
*/
|
||||
const DIAGRAM_VIEWER_HINT: Record<string, string> = {
|
||||
mermaid: "→ paste at https://mermaid.live to view",
|
||||
plantuml: "→ paste at https://www.plantuml.com/plantuml to view",
|
||||
puml: "→ paste at https://www.plantuml.com/plantuml to view",
|
||||
dot: "→ paste at https://dreampuf.github.io/GraphvizOnline to view",
|
||||
graphviz: "→ paste at https://dreampuf.github.io/GraphvizOnline to view",
|
||||
};
|
||||
|
||||
/**
|
||||
* Render a diagram-source code block with a magenta double-line
|
||||
* frame + a `◇ lang diagram (source)` header + a viewer hint
|
||||
* underneath. Distinct from the plain code-block rendering so the
|
||||
* user can tell at a glance that the terminal couldn't draw the
|
||||
* actual graph — they're looking at source to copy out.
|
||||
*/
|
||||
/**
|
||||
* Heading renderer. Three tiers of solid-bg pill (cyan / violet /
|
||||
* fuchsia, walking down the brand gradient) so the heading tree is
|
||||
* scannable at a glance. H4+ collapses to bold accent text with a
|
||||
* leading ▸ marker — four pills stacked would visually overwhelm
|
||||
* the body, and headings rarely go that deep in answers anyway.
|
||||
*
|
||||
* Markdown sigils (#, ##, ###) are NEVER rendered literally inside
|
||||
* the pill: showing `### 标题` defeats the whole "this is a heading"
|
||||
* semantic. The sigil count goes into the pill's BG color choice;
|
||||
* the title text stands on its own.
|
||||
*/
|
||||
function HeadingView({
|
||||
level,
|
||||
text,
|
||||
citations,
|
||||
}: {
|
||||
level: number;
|
||||
text: string;
|
||||
citations?: CitationMap;
|
||||
}) {
|
||||
if (level === 1) {
|
||||
return (
|
||||
<Box marginY={1}>
|
||||
<Text backgroundColor="#67e8f9" color="black" bold>
|
||||
{` ${text} `}
|
||||
</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
if (level === 2) {
|
||||
return (
|
||||
<Box marginTop={1}>
|
||||
<Text backgroundColor="#c4b5fd" color="black" bold>
|
||||
{` ${text} `}
|
||||
</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
if (level === 3) {
|
||||
return (
|
||||
<Box marginTop={1}>
|
||||
<Text backgroundColor="#f0abfc" color="black" bold>
|
||||
{` ${text} `}
|
||||
</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Box marginTop={1}>
|
||||
<Text bold color="#f0abfc">
|
||||
▸{" "}
|
||||
</Text>
|
||||
<Text bold>
|
||||
<InlineMd text={text} citations={citations} />
|
||||
</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fenced code block. Round-cornered frame, language pill in the
|
||||
* top-left, body in syntax-flavored colors. Lives inside event rows
|
||||
* which Ink renders into `<Static>` (scrollback) — the eraseLines
|
||||
* miscount that bans bordered Boxes from the *live* region doesn't
|
||||
* apply here, since Static items render once and never repaint.
|
||||
*/
|
||||
function CodeBlockView({ lang, text }: { lang: string; text: string }) {
|
||||
const langLabel = lang.trim();
|
||||
return (
|
||||
<Box flexDirection="column" borderStyle="round" borderColor="#7dd3fc" paddingX={1}>
|
||||
{langLabel ? (
|
||||
<Box>
|
||||
<Text backgroundColor="#7dd3fc" color="black" bold>
|
||||
{` ${langLabel} `}
|
||||
</Text>
|
||||
</Box>
|
||||
) : null}
|
||||
<Text color="#fde68a">{text}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
function DiagramCodeBlock({ lang, text }: { lang: string; text: string }) {
|
||||
const hint =
|
||||
DIAGRAM_VIEWER_HINT[lang.toLowerCase()] ?? "→ render with the matching viewer to view";
|
||||
return (
|
||||
<Box flexDirection="column" borderStyle="double" borderColor="magenta" paddingX={1}>
|
||||
<Text bold color="magenta">
|
||||
{`◇ ${lang} diagram (source — terminal can't draw the graph)`}
|
||||
</Text>
|
||||
<Box marginTop={1}>
|
||||
<Text color="yellow">{text}</Text>
|
||||
</Box>
|
||||
<Box marginTop={1}>
|
||||
<Text dimColor>{hint}</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
export function Markdown({ text, projectRoot }: { text: string; projectRoot?: string }) {
|
||||
const cleaned = stripMath(text);
|
||||
const cleaned = expandAutolinks(expandEmoji(stripMath(text)));
|
||||
const root = projectRoot ?? process.cwd();
|
||||
const citations = React.useMemo(() => collectCitations(cleaned, root), [cleaned, root]);
|
||||
const blocks = React.useMemo(() => parseBlocks(cleaned), [cleaned]);
|
||||
|
||||
@@ -19,6 +19,12 @@
|
||||
* - Parent owns Tab, Esc, PageUp/Down (slash-complete, abort,
|
||||
* unused). Arrow keys are split: empty buffer → parent (history
|
||||
* recall); non-empty → child (cursor movement).
|
||||
*
|
||||
* CSI recovery is delegated to `key-normalize.ts` — see there for
|
||||
* the rationale. Every event flows through `recoverCsiTail` first,
|
||||
* which is the single source of truth for the Windows ConPTY case
|
||||
* (parse-keypress eats the leading `\x1b` and routes the bare
|
||||
* `[A`/`[C`/`[201~`/etc. through useInput as plain text).
|
||||
*/
|
||||
|
||||
export interface MultilineKey {
|
||||
@@ -47,8 +53,28 @@ export interface MultilineAction {
|
||||
/** When `true`, fire `onSubmit(submitValue ?? value)`. */
|
||||
submit: boolean;
|
||||
submitValue?: string;
|
||||
/**
|
||||
* When set, the key was ↑/↓ at a buffer boundary (empty buffer, or
|
||||
* cursor already at first/last line) and the component should hand
|
||||
* off to the parent's history-recall handler. The child's cursor
|
||||
* didn't move; the parent decides whether to swap in a prior
|
||||
* prompt. Lets users escape out of a multi-line buffer into
|
||||
* history without first emptying it — previously NOOP felt stuck.
|
||||
*/
|
||||
historyHandoff?: "prev" | "next";
|
||||
/**
|
||||
* Multi-char paste detected. The reducer is pure so it can't
|
||||
* allocate a sentinel id or write to the registry — it hands the
|
||||
* raw normalized payload up to PromptInput, which registers the
|
||||
* paste, picks a sentinel codepoint, and inserts THAT (one char)
|
||||
* into the buffer. Result: the user sees a `[paste #N · M lines]`
|
||||
* placeholder instead of the full content drowning the typed text.
|
||||
*/
|
||||
pasteRequest?: { content: string };
|
||||
}
|
||||
|
||||
import { recoverCsiTail, stripCsiFragments } from "./key-normalize.js";
|
||||
|
||||
const BACKSLASH_SUFFIX = /\\$/;
|
||||
|
||||
const NOOP: MultilineAction = { next: null, cursor: null, submit: false };
|
||||
@@ -56,19 +82,46 @@ const NOOP: MultilineAction = { next: null, cursor: null, submit: false };
|
||||
export function processMultilineKey(
|
||||
value: string,
|
||||
cursor: number,
|
||||
key: MultilineKey,
|
||||
keyIn: MultilineKey,
|
||||
): MultilineAction {
|
||||
// Parent-owned keys: Tab (slash-complete), Esc (abort), PageUp/Down.
|
||||
if (key.tab || key.escape || key.pageUp || key.pageDown) {
|
||||
// CSI recovery — bare `[A` / `[C` / `[Z` / `[5~` / etc. that
|
||||
// Windows ConPTY leaves in `input` after parse-keypress eats the
|
||||
// leading `\x1b`. See key-normalize.ts for the long version.
|
||||
const recovered = recoverCsiTail(keyIn.input, keyIn);
|
||||
const key: MultilineKey = recovered ? { ...keyIn, ...recovered, input: "" } : keyIn;
|
||||
|
||||
// Parent-owned keys: Tab (slash-complete), Esc (abort).
|
||||
if (key.tab || key.escape) {
|
||||
return NOOP;
|
||||
}
|
||||
|
||||
// Empty buffer + ↑/↓ → parent handles history recall.
|
||||
if (value.length === 0 && (key.upArrow || key.downArrow)) {
|
||||
return NOOP;
|
||||
// Buffer-wide navigation. Per-line motion (↑/↓ / Ctrl+A / Ctrl+E)
|
||||
// is already covered; PageUp/PageDown are the missing "jump to
|
||||
// top / bottom of the WHOLE buffer" pair, useful after pasting a
|
||||
// 500-line blob where ↑×500 is absurd. Repurposed from the
|
||||
// previous NOOP behavior (PageUp/Down had no binding).
|
||||
if (key.pageUp) {
|
||||
return cursor === 0 ? NOOP : { next: null, cursor: 0, submit: false };
|
||||
}
|
||||
if (key.pageDown) {
|
||||
return cursor === value.length ? NOOP : { next: null, cursor: value.length, submit: false };
|
||||
}
|
||||
|
||||
// Cursor motion.
|
||||
// History recall is bound to Ctrl+P / Ctrl+N (bash readline
|
||||
// convention) rather than ↑/↓. Reason: Windows Terminal + ConPTY
|
||||
// translates mouse wheel events to ↑/↓ keystrokes for raw-mode
|
||||
// child processes — indistinguishable at the byte level. If ↑/↓
|
||||
// recalled history, every wheel-scroll would corrupt the prompt
|
||||
// with a prior message. Ctrl+P/N is wheel-immune.
|
||||
if (key.ctrl && key.input === "p") {
|
||||
return { ...NOOP, historyHandoff: "prev" };
|
||||
}
|
||||
if (key.ctrl && key.input === "n") {
|
||||
return { ...NOOP, historyHandoff: "next" };
|
||||
}
|
||||
|
||||
// Cursor motion. Empty single-line buffer + ↑/↓ is now a no-op
|
||||
// (used to recall history; see Ctrl+P/N comment above).
|
||||
if (key.leftArrow) {
|
||||
return { next: null, cursor: Math.max(0, cursor - 1), submit: false };
|
||||
}
|
||||
@@ -92,8 +145,58 @@ export function processMultilineKey(
|
||||
if (key.ctrl && key.input === "e") {
|
||||
return { next: null, cursor: endOfLine(value, cursor), submit: false };
|
||||
}
|
||||
// Bash / readline conventions:
|
||||
// Ctrl+U — clear the whole buffer (readline treats this as
|
||||
// "clear from cursor to start"; for our text-area we treat it
|
||||
// as "clear all" because there's no ergonomic way to clear a
|
||||
// huge paste otherwise).
|
||||
// Ctrl+W — delete the word before the cursor.
|
||||
if (key.ctrl && key.input === "u") {
|
||||
return value.length === 0 ? NOOP : { next: "", cursor: 0, submit: false };
|
||||
}
|
||||
if (key.ctrl && key.input === "w") {
|
||||
if (cursor === 0) return NOOP;
|
||||
const wordStart = previousWordStart(value, cursor);
|
||||
return {
|
||||
next: value.slice(0, wordStart) + value.slice(cursor),
|
||||
cursor: wordStart,
|
||||
submit: false,
|
||||
};
|
||||
}
|
||||
|
||||
// Newline: Ctrl+J (LF literal) or ctrl+'j' normalized form.
|
||||
// Paste-burst detection. If `input` contains a newline (or
|
||||
// bracketed-paste markers from a terminal that supports them),
|
||||
// this is a paste — surface it as a `pasteRequest` so the parent
|
||||
// can register the blob and insert ONE sentinel codepoint instead
|
||||
// of the full content. The buffer stays small + readable; the
|
||||
// user sees `[paste #N · M lines]` where the paste lives.
|
||||
//
|
||||
// Always overrides `key.return` for pastes: Ink occasionally sets
|
||||
// key.return when a paste's trailing \n looks like Enter, which
|
||||
// would submit the partial buffer mid-paste and silently truncate
|
||||
// the content. Pastes always insert; Enter only submits typed
|
||||
// content. We normalize \r\n and bare \r to \n so mixed-line-
|
||||
// ending pastes (Windows clipboard, web copy) land cleanly.
|
||||
// Strip every recognised CSI fragment (paste markers, arrow tails,
|
||||
// etc.) defensively — if any leaked past structured-key recovery
|
||||
// they shouldn't get inserted into the buffer as text.
|
||||
const stripped = stripCsiFragments(key.input);
|
||||
// Paste = newline-containing input with MORE than just the newline
|
||||
// itself. A bare "\n" is Ctrl+J / one-keystroke newline (handled
|
||||
// below); only multi-char input wrapped around a newline is a real
|
||||
// paste burst that warrants a sentinel.
|
||||
const looksLikePaste =
|
||||
stripped.length > 1 && (stripped.includes("\n") || stripped.includes("\r"));
|
||||
if (looksLikePaste) {
|
||||
const normalized = stripped.replace(/\r\n?/g, "\n");
|
||||
return {
|
||||
next: null,
|
||||
cursor: null,
|
||||
submit: false,
|
||||
pasteRequest: { content: normalized },
|
||||
};
|
||||
}
|
||||
// Single-char Ctrl+J / LF: insert one newline.
|
||||
if (key.input === "\n" || (key.ctrl && key.input === "j")) {
|
||||
return insertAt(value, cursor, "\n");
|
||||
}
|
||||
@@ -172,6 +275,22 @@ function startOfLine(value: string, cursor: number): number {
|
||||
return value.lastIndexOf("\n", cursor - 1) + 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the start of the word immediately to the left of the cursor.
|
||||
* Skips trailing whitespace first (so Ctrl+W after typing space
|
||||
* still removes the previous word, not just the space), then walks
|
||||
* back over the word characters until a whitespace boundary or
|
||||
* start-of-buffer. Newlines count as whitespace, so Ctrl+W at the
|
||||
* start of a line deletes the preceding line's last word — same
|
||||
* behavior as bash/readline.
|
||||
*/
|
||||
function previousWordStart(value: string, cursor: number): number {
|
||||
let i = cursor;
|
||||
while (i > 0 && /\s/.test(value[i - 1] ?? "")) i--;
|
||||
while (i > 0 && !/\s/.test(value[i - 1] ?? "")) i--;
|
||||
return i;
|
||||
}
|
||||
|
||||
function endOfLine(value: string, cursor: number): number {
|
||||
const nl = value.indexOf("\n", cursor);
|
||||
return nl === -1 ? value.length : nl;
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
/**
|
||||
* Paste sentinels — represent a pasted blob as a single codepoint in
|
||||
* the input buffer instead of inlining its full contents.
|
||||
*
|
||||
* Why: a 3000-line paste shoved verbatim into the buffer drowns the
|
||||
* surrounding typed text, costs a lot to render per keystroke, and
|
||||
* makes navigation/clear awkward. Replace it with one PUA char (a
|
||||
* "sentinel") and store the real content in a side registry. The
|
||||
* buffer string stays small, the user types around the sentinel as
|
||||
* if it were a single character, and a Backspace at the sentinel
|
||||
* deletes the whole paste in one stroke. On submit we expand the
|
||||
* sentinels back to real content.
|
||||
*
|
||||
* Encoding:
|
||||
* - One codepoint per paste, in PUA range U+E100..U+E1FF (256 slots).
|
||||
* - The codepoint's offset within that range is the paste id.
|
||||
* - That gives us 256 distinct paste blobs per session before ids
|
||||
* wrap. In practice users paste a handful per session — wrap is
|
||||
* a non-issue, but if it happens, the new paste overwrites the
|
||||
* oldest registry entry; any stale sentinels still in the buffer
|
||||
* will render with a "(missing)" badge so the user can clean up.
|
||||
*
|
||||
* Range chosen from the Supplementary PUA-A region's neighbor (BMP
|
||||
* PUA) so a single `String.fromCharCode` works — no surrogate pairs,
|
||||
* no `length === 2` weirdness for cursor arithmetic.
|
||||
*/
|
||||
|
||||
export const PASTE_SENTINEL_BASE = 0xe100;
|
||||
export const PASTE_SENTINEL_RANGE = 256;
|
||||
export const PASTE_SENTINEL_END = PASTE_SENTINEL_BASE + PASTE_SENTINEL_RANGE;
|
||||
|
||||
export interface PasteEntry {
|
||||
id: number;
|
||||
content: string;
|
||||
lineCount: number;
|
||||
charCount: number;
|
||||
}
|
||||
|
||||
export function encodePasteSentinel(id: number): string {
|
||||
if (id < 0 || id >= PASTE_SENTINEL_RANGE) {
|
||||
throw new Error(`paste sentinel id ${id} out of range [0, ${PASTE_SENTINEL_RANGE})`);
|
||||
}
|
||||
return String.fromCharCode(PASTE_SENTINEL_BASE + id);
|
||||
}
|
||||
|
||||
/** Returns the paste id, or `null` if `ch` is not a sentinel codepoint. */
|
||||
export function decodePasteSentinel(ch: string): number | null {
|
||||
if (ch.length === 0) return null;
|
||||
const cp = ch.charCodeAt(0);
|
||||
if (cp < PASTE_SENTINEL_BASE || cp >= PASTE_SENTINEL_END) return null;
|
||||
return cp - PASTE_SENTINEL_BASE;
|
||||
}
|
||||
|
||||
export function isPasteSentinel(ch: string): boolean {
|
||||
return decodePasteSentinel(ch) !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a PasteEntry from raw paste content. Computes line + char
|
||||
* counts once at registration time so the renderer doesn't re-count
|
||||
* on every keystroke.
|
||||
*/
|
||||
export function makePasteEntry(id: number, content: string): PasteEntry {
|
||||
return {
|
||||
id,
|
||||
content,
|
||||
lineCount: content.split("\n").length,
|
||||
charCount: content.length,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Expand every sentinel in `text` back to its registered paste
|
||||
* content. Unknown sentinels (entry missing — registry was wiped, or
|
||||
* id wrap collision) drop to empty string so the resulting prompt
|
||||
* doesn't carry a literal PUA codepoint to the model.
|
||||
*
|
||||
* Used at submit time to recover the full prompt the user composed.
|
||||
*/
|
||||
export function expandPasteSentinels(
|
||||
text: string,
|
||||
pastes: ReadonlyMap<number, PasteEntry>,
|
||||
): string {
|
||||
let out = "";
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
const ch = text[i]!;
|
||||
const id = decodePasteSentinel(ch);
|
||||
if (id === null) {
|
||||
out += ch;
|
||||
continue;
|
||||
}
|
||||
const entry = pastes.get(id);
|
||||
out += entry?.content ?? "";
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Quick check: does the buffer contain ANY sentinel? Used to gate
|
||||
* UI hints (the "paste #N" listing in the prompt-box footer) without
|
||||
* walking the whole buffer twice.
|
||||
*/
|
||||
export function bufferHasPaste(text: string): boolean {
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
if (decodePasteSentinel(text[i]!) !== null) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Walk the buffer and return the ids of every sentinel still
|
||||
* present, in source order. Used by the registry's GC pass at
|
||||
* submit time so unreachable paste entries don't accumulate.
|
||||
* (No-op when the buffer is sentinel-free.)
|
||||
*/
|
||||
export function listPasteIdsInBuffer(text: string): number[] {
|
||||
const ids: number[] = [];
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
const id = decodePasteSentinel(text[i]!);
|
||||
if (id !== null) ids.push(id);
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format `1234` chars as `1.2KB` etc. Tiny helper used in placeholder
|
||||
* labels — kept here so paste-related display logic is co-located.
|
||||
*/
|
||||
export function formatBytesShort(n: number): string {
|
||||
if (n < 1024) return `${n}B`;
|
||||
if (n < 1024 * 1024) return `${(n / 1024).toFixed(n < 1024 * 10 ? 1 : 0)}KB`;
|
||||
return `${(n / (1024 * 1024)).toFixed(1)}MB`;
|
||||
}
|
||||
+96
-20
@@ -3,40 +3,116 @@
|
||||
* (in-chat `/preset`) and the wizard (first-run setup) read from here.
|
||||
*
|
||||
* Presets are the single vocabulary we teach new users: they don't need
|
||||
* to know model IDs, Pillar 2, branch budgets, or cost tradeoffs
|
||||
* independently — they pick "fast / smart / max" and we translate.
|
||||
* to know model IDs, reasoning effort, or thinking mode independently
|
||||
* — they pick "fast / smart / max" and we translate.
|
||||
*
|
||||
* Design rules (v0.6+):
|
||||
* - Branching (`branch >= 2`) is NEVER in a preset. Self-consistency
|
||||
* sampling is `N×` cost; auto-enabling it would ambush users into
|
||||
* multi-dollar turns without asking. Opt-in only via `/branch N`.
|
||||
* - Harvest (Pillar-2 plan-state extraction) is NEVER in a preset.
|
||||
* In practice it's display sugar — the typed plan state hasn't
|
||||
* fed back into orchestration decisions (branch trigger) often
|
||||
* enough to pay for the extra round-trip. Opt-in only via
|
||||
* `/harvest on`.
|
||||
* - The three tiers differ on only TWO knobs: model (flash/pro) and
|
||||
* reasoning effort (high/max). Same on-the-wire billing axis,
|
||||
* easy to reason about, easy to budget.
|
||||
*/
|
||||
|
||||
import type { PresetName } from "../../config.js";
|
||||
|
||||
export interface PresetSettings {
|
||||
model: string;
|
||||
/**
|
||||
* Reasoning-effort cap. `high` = shorter chain of thought; `max` =
|
||||
* agent-class default (deeper, more output). Effort is now decoupled
|
||||
* from preset — a separate `/effort` knob lets users tune it
|
||||
* orthogonally. The PRESETS table just picks the safest default.
|
||||
*/
|
||||
reasoningEffort: "high" | "max";
|
||||
/**
|
||||
* Auto-escalation switch. `auto` keeps the legacy NEEDS_PRO + failure
|
||||
* threshold behavior; `flash` and `pro` lock to the chosen model.
|
||||
*/
|
||||
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",
|
||||
/**
|
||||
* The three real presets. Old names (`fast / smart / max`) stay alive
|
||||
* as aliases mapped through `resolvePreset` so a config.json that
|
||||
* predates this rename still works without a migration script.
|
||||
*/
|
||||
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",
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* Resolve a preset name (canonical or unknown) to its settings.
|
||||
* Anything that isn't `auto | flash | pro` — including the dropped
|
||||
* legacy `fast / smart / max` aliases — collapses to `auto`. Simpler
|
||||
* than mapping legacy values (each legacy name had its own semantics
|
||||
* that don't 1:1 onto the new model-commitment vocabulary); auto is
|
||||
* the safe default and the user can re-pick explicitly.
|
||||
*/
|
||||
export function resolvePreset(name: PresetName | undefined): PresetSettings {
|
||||
return PRESETS[name ?? "fast"];
|
||||
if (name === "auto" || name === "flash" || name === "pro") return PRESETS[name];
|
||||
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,318 @@
|
||||
/**
|
||||
* Pure helpers for rendering one logical line of the prompt input as
|
||||
* exactly one visual row, regardless of how wide the line's content
|
||||
* is. Splitting this out from PromptInput so the math is testable
|
||||
* without React/Ink.
|
||||
*
|
||||
* Why we can't trust Ink/Yoga's text wrap: Ink uses `string-width` to
|
||||
* measure cells, but on CJK Windows terminals some glyphs render at
|
||||
* a different cell count than `string-width` reports. The terminal
|
||||
* wraps to a 2nd visual row, Ink's eraseLines miscounts, and the
|
||||
* scrollback fills with ghost rows from the previous frame's leak.
|
||||
*
|
||||
* Our fix is to never let the line wrap. We slice the text down to
|
||||
* the visible-cell budget ourselves and feed Ink a single Text whose
|
||||
* width is known to fit.
|
||||
*
|
||||
* Cursor visibility: when the user types past the visible width the
|
||||
* window slides so the cursor stays in view. `‹` and `›` markers
|
||||
* appear at the trimmed edges so the user can see content is hidden
|
||||
* to one side.
|
||||
*/
|
||||
|
||||
import { type PasteEntry, decodePasteSentinel, formatBytesShort } from "./paste-sentinels.js";
|
||||
|
||||
/**
|
||||
* One renderable atom of a viewport. The line's content is broken
|
||||
* into a sequence of these so a paste sentinel becomes a magenta
|
||||
* `[paste #N · Ml · KKB]` block while the surrounding text stays
|
||||
* normal.
|
||||
*/
|
||||
export type Segment = { kind: "text"; text: string } | { kind: "paste"; id: number; label: string };
|
||||
|
||||
export interface Viewport {
|
||||
/** Segments to render left-to-right. Sum of cells <= visibleCells. */
|
||||
segments: Segment[];
|
||||
/**
|
||||
* Visual cell column at which to draw the cursor block, measured
|
||||
* from the start of the viewport (0 = leftmost cell after the
|
||||
* prompt prefix). `null` means cursor is not on this line — the
|
||||
* caller renders a static line.
|
||||
*/
|
||||
cursorCell: number | null;
|
||||
/** True when content was clipped on the left side. */
|
||||
hiddenLeft: boolean;
|
||||
/** True when content was clipped on the right side. */
|
||||
hiddenRight: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cell width of a single character in a typical terminal grid.
|
||||
*
|
||||
* Approximation of Unicode East Asian Width=Wide / W treatment.
|
||||
* Range table is intentionally compact — covers the codepoints we
|
||||
* see in practice (CJK ideographs, fullwidth forms, Hangul syllables,
|
||||
* Hiragana / Katakana). Anything outside the wide ranges counts as
|
||||
* one cell. Control characters count as zero so we don't over-budget
|
||||
* for them.
|
||||
*
|
||||
* Not a full `string-width` clone. We deliberately don't honour the
|
||||
* "Ambiguous=2 in CJK locale" rule because it produces inconsistent
|
||||
* results across terminals and is the very source of Ink's wrap
|
||||
* miscount. Treating ambiguous chars as 1 cell here matches what
|
||||
* Ink/Yoga also does, so our slice math agrees with what Ink would
|
||||
* have rendered (had it not wrapped).
|
||||
*/
|
||||
export function charCells(ch: string): number {
|
||||
if (ch.length === 0) return 0;
|
||||
const code = ch.charCodeAt(0);
|
||||
if (code < 0x20 || code === 0x7f) return 0;
|
||||
if (code < 0x1100) return 1;
|
||||
// Hangul Jamo
|
||||
if (code >= 0x1100 && code <= 0x115f) return 2;
|
||||
// CJK Radicals, Kangxi Radicals, Ideographic Description, CJK Symbols
|
||||
if (code >= 0x2e80 && code <= 0x303e) return 2;
|
||||
// Hiragana, Katakana, Bopomofo, Hangul Compat Jamo, Kanbun
|
||||
if (code >= 0x3041 && code <= 0x33ff) return 2;
|
||||
// CJK Unified Ext A
|
||||
if (code >= 0x3400 && code <= 0x4dbf) return 2;
|
||||
// CJK Unified Ideographs
|
||||
if (code >= 0x4e00 && code <= 0x9fff) return 2;
|
||||
// Yi Syllables
|
||||
if (code >= 0xa000 && code <= 0xa4cf) return 2;
|
||||
// Hangul Syllables
|
||||
if (code >= 0xac00 && code <= 0xd7a3) return 2;
|
||||
// CJK Compatibility Ideographs
|
||||
if (code >= 0xf900 && code <= 0xfaff) return 2;
|
||||
// CJK Compatibility Forms
|
||||
if (code >= 0xfe30 && code <= 0xfe4f) return 2;
|
||||
// Halfwidth and Fullwidth Forms (fullwidth half is wide)
|
||||
if (code >= 0xff00 && code <= 0xff60) return 2;
|
||||
// Fullwidth signs
|
||||
if (code >= 0xffe0 && code <= 0xffe6) return 2;
|
||||
return 1;
|
||||
}
|
||||
|
||||
/** Total cells of a string, with paste sentinels expanded to placeholder width. */
|
||||
export function stringCells(s: string, pastes?: ReadonlyMap<number, PasteEntry>): number {
|
||||
let n = 0;
|
||||
for (let i = 0; i < s.length; i++) {
|
||||
const ch = s[i]!;
|
||||
const id = decodePasteSentinel(ch);
|
||||
if (id !== null) {
|
||||
n += pasteSentinelCells(id, pastes);
|
||||
} else {
|
||||
n += charCells(ch);
|
||||
}
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
/** Paste sentinel placeholder width — what we'd render for that sentinel. */
|
||||
export function pasteSentinelLabel(id: number, entry: PasteEntry | undefined): string {
|
||||
if (!entry) return `[paste #${id + 1} · (missing)]`;
|
||||
return `[paste #${id + 1} · ${entry.lineCount}l · ${formatBytesShort(entry.charCount)}]`;
|
||||
}
|
||||
|
||||
function pasteSentinelCells(id: number, pastes?: ReadonlyMap<number, PasteEntry>): number {
|
||||
const entry = pastes?.get(id);
|
||||
return pasteSentinelLabel(id, entry).length;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute the viewport for a line, keeping the cursor visible. When
|
||||
* the line's total cells fit in `visibleCells`, return the whole
|
||||
* line. Otherwise slice a window centred on the cursor with `‹` /
|
||||
* `›` markers indicating clipped sides.
|
||||
*
|
||||
* `cursorCol` is the cursor's char index within `line` (0 = before
|
||||
* first char; `line.length` = past last char). Pass `null` for
|
||||
* lines that don't host the cursor — the function returns a left-
|
||||
* aligned static viewport with truncation on the right.
|
||||
*/
|
||||
export function buildViewport(
|
||||
line: string,
|
||||
cursorCol: number | null,
|
||||
visibleCells: number,
|
||||
pastes?: ReadonlyMap<number, PasteEntry>,
|
||||
): Viewport {
|
||||
if (visibleCells <= 0) {
|
||||
return {
|
||||
segments: [],
|
||||
cursorCell: cursorCol === null ? null : 0,
|
||||
hiddenLeft: false,
|
||||
hiddenRight: line.length > 0,
|
||||
};
|
||||
}
|
||||
const totalCells = stringCells(line, pastes);
|
||||
|
||||
// Fast path: whole line fits.
|
||||
if (totalCells <= visibleCells) {
|
||||
const segments = textToSegments(line, pastes);
|
||||
let cursorCell: number | null = null;
|
||||
if (cursorCol !== null) {
|
||||
cursorCell = stringCells(line.slice(0, cursorCol), pastes);
|
||||
}
|
||||
return { segments, cursorCell, hiddenLeft: false, hiddenRight: false };
|
||||
}
|
||||
|
||||
// Static viewport (cursor not on this line) — clip from the right.
|
||||
if (cursorCol === null) {
|
||||
return clipFromLeft(line, visibleCells, pastes);
|
||||
}
|
||||
|
||||
// Cursor-bearing line: slide a window so cursor stays visible.
|
||||
// Reserve 1 cell on each potentially-clipped side for the marker.
|
||||
return clipAroundCursor(line, cursorCol, visibleCells, pastes);
|
||||
}
|
||||
|
||||
function clipFromLeft(
|
||||
line: string,
|
||||
visibleCells: number,
|
||||
pastes?: ReadonlyMap<number, PasteEntry>,
|
||||
): Viewport {
|
||||
// Show as much of the head as fits; mark the right edge as hidden.
|
||||
// Reserve 1 cell for the `›` marker.
|
||||
const budget = Math.max(1, visibleCells - 1);
|
||||
let used = 0;
|
||||
let end = 0;
|
||||
while (end < line.length) {
|
||||
const ch = line[end]!;
|
||||
const cw = charCellsAt(line, end, pastes);
|
||||
if (used + cw > budget) break;
|
||||
used += cw;
|
||||
end++;
|
||||
}
|
||||
const segments = textToSegments(line.slice(0, end), pastes);
|
||||
return { segments, cursorCell: null, hiddenLeft: false, hiddenRight: end < line.length };
|
||||
}
|
||||
|
||||
/**
|
||||
* Sliding window around the cursor. Algorithm:
|
||||
*
|
||||
* 1. Start with `start` and `end` both at the cursor index.
|
||||
* 2. Expand `end` rightward while there's budget, until cursor cell
|
||||
* visible or we hit end-of-line.
|
||||
* 3. Expand `start` leftward to fill remaining budget.
|
||||
* 4. Reserve 1 cell on each clipped side for the `‹`/`›` marker.
|
||||
*
|
||||
* The cursor cell is computed AFTER the slice is fixed, by counting
|
||||
* cells from `start` up to `cursorCol`.
|
||||
*/
|
||||
function clipAroundCursor(
|
||||
line: string,
|
||||
cursorCol: number,
|
||||
visibleCells: number,
|
||||
pastes?: ReadonlyMap<number, PasteEntry>,
|
||||
): Viewport {
|
||||
// `cursorCol` is between 0 and line.length (inclusive). The cursor
|
||||
// visually sits BEFORE the char at line[cursorCol] (or after the
|
||||
// last char when cursorCol === line.length).
|
||||
// We want both the char at the cursor (if any) AND a cell of cursor
|
||||
// padding visible.
|
||||
|
||||
// Budget — leave 1 cell for each marker we may need.
|
||||
let budget = visibleCells;
|
||||
// Right marker: needed if we don't reach end of line.
|
||||
// Left marker: needed if start > 0.
|
||||
// We don't know in advance, so allocate conservatively: -2 cells.
|
||||
const reservedForMarkers = 2;
|
||||
budget = Math.max(1, budget - reservedForMarkers);
|
||||
|
||||
// Try to keep cursor roughly centred. Start by aiming `start` ~
|
||||
// halfway behind cursorCol.
|
||||
const halfBudget = Math.floor(budget / 2);
|
||||
|
||||
// Walk left from cursor, accumulating cells, until we've spent
|
||||
// halfBudget OR hit the start of the line.
|
||||
let start = cursorCol;
|
||||
let leftCells = 0;
|
||||
while (start > 0 && leftCells < halfBudget) {
|
||||
const cw = charCellsAt(line, start - 1, pastes);
|
||||
if (leftCells + cw > halfBudget) break;
|
||||
start--;
|
||||
leftCells += cw;
|
||||
}
|
||||
|
||||
// Walk right from cursor, filling the remaining budget. We always
|
||||
// include a cell for the cursor itself if line[cursorCol] exists
|
||||
// (since the cursor block covers that char). At end-of-line we
|
||||
// include a phantom cell of cursor space.
|
||||
const rightBudget = budget - leftCells;
|
||||
let end = cursorCol;
|
||||
let rightCells = 0;
|
||||
// Include the char at the cursor (1 or 2 cells depending on width)
|
||||
// if there is one.
|
||||
const cursorChar = cursorCol < line.length ? charCellsAt(line, cursorCol, pastes) : 1;
|
||||
if (rightBudget >= cursorChar) {
|
||||
if (cursorCol < line.length) end = cursorCol + 1;
|
||||
rightCells = cursorChar;
|
||||
while (end < line.length && rightCells < rightBudget) {
|
||||
const cw = charCellsAt(line, end, pastes);
|
||||
if (rightCells + cw > rightBudget) break;
|
||||
rightCells += cw;
|
||||
end++;
|
||||
}
|
||||
}
|
||||
|
||||
// If we have leftover right-budget and there's still room on the
|
||||
// left, expand leftwards more (cursor stays towards the right
|
||||
// edge but more left context is shown — common when typing at
|
||||
// end of a long line).
|
||||
let extraLeftBudget = rightBudget - rightCells;
|
||||
while (start > 0 && extraLeftBudget > 0) {
|
||||
const cw = charCellsAt(line, start - 1, pastes);
|
||||
if (cw > extraLeftBudget) break;
|
||||
start--;
|
||||
leftCells += cw;
|
||||
extraLeftBudget -= cw;
|
||||
}
|
||||
|
||||
const hiddenLeft = start > 0;
|
||||
const hiddenRight = end < line.length;
|
||||
const segments = textToSegments(line.slice(start, end), pastes);
|
||||
// Cursor cell relative to the start of the slice. Markers are
|
||||
// rendered separately by the caller — they don't shift the
|
||||
// segment-relative offset so we don't add them here.
|
||||
const cursorCell = stringCells(line.slice(start, cursorCol), pastes);
|
||||
return { segments, cursorCell, hiddenLeft, hiddenRight };
|
||||
}
|
||||
|
||||
function charCellsAt(line: string, idx: number, pastes?: ReadonlyMap<number, PasteEntry>): number {
|
||||
const ch = line[idx]!;
|
||||
const id = decodePasteSentinel(ch);
|
||||
if (id !== null) {
|
||||
const entry = pastes?.get(id);
|
||||
return pasteSentinelLabel(id, entry).length;
|
||||
}
|
||||
return charCells(ch);
|
||||
}
|
||||
|
||||
/**
|
||||
* Walk the string and split it into text/paste segments. Pure —
|
||||
* doesn't allocate per-character objects (text runs accumulate in a
|
||||
* single segment). Used by both the fast and clipped paths.
|
||||
*/
|
||||
export function textToSegments(line: string, pastes?: ReadonlyMap<number, PasteEntry>): Segment[] {
|
||||
const out: Segment[] = [];
|
||||
let buf = "";
|
||||
const flushBuf = () => {
|
||||
if (buf.length > 0) {
|
||||
out.push({ kind: "text", text: buf });
|
||||
buf = "";
|
||||
}
|
||||
};
|
||||
for (let i = 0; i < line.length; i++) {
|
||||
const ch = line[i]!;
|
||||
const id = decodePasteSentinel(ch);
|
||||
if (id !== null) {
|
||||
flushBuf();
|
||||
const label = pasteSentinelLabel(id, pastes?.get(id));
|
||||
out.push({ kind: "paste", id, label });
|
||||
} else {
|
||||
buf += ch;
|
||||
}
|
||||
}
|
||||
flushBuf();
|
||||
return out;
|
||||
}
|
||||
+20
-1553
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,273 @@
|
||||
import type { SlashArgContext, SlashCommandSpec } from "./types.js";
|
||||
|
||||
export const SLASH_COMMANDS: readonly SlashCommandSpec[] = [
|
||||
{ cmd: "help", summary: "show the full command reference" },
|
||||
{ cmd: "status", summary: "current model, flags, context, session" },
|
||||
{
|
||||
cmd: "preset",
|
||||
argsHint: "<fast|smart|max>",
|
||||
summary: "one-tap model + harvest + branch bundle",
|
||||
argCompleter: ["fast", "smart", "max"],
|
||||
},
|
||||
{
|
||||
cmd: "model",
|
||||
argsHint: "<id>",
|
||||
summary: "switch DeepSeek model id",
|
||||
argCompleter: "models",
|
||||
},
|
||||
{ cmd: "models", summary: "list available models fetched from DeepSeek /models" },
|
||||
{
|
||||
cmd: "harvest",
|
||||
argsHint: "[on|off]",
|
||||
summary: "toggle Pillar-2 plan-state extraction",
|
||||
argCompleter: ["on", "off"],
|
||||
},
|
||||
{
|
||||
cmd: "branch",
|
||||
argsHint: "<N|off>",
|
||||
summary: "run N parallel samples per turn (N>=2)",
|
||||
argCompleter: ["off", "2", "3", "4", "5"],
|
||||
},
|
||||
{
|
||||
cmd: "effort",
|
||||
argsHint: "<high|max>",
|
||||
summary: "reasoning_effort cap — max is default (agent-class), high is cheaper/faster",
|
||||
argCompleter: ["max", "high"],
|
||||
},
|
||||
{
|
||||
cmd: "pro",
|
||||
argsHint: "[off]",
|
||||
summary: "arm v4-pro for the NEXT turn only (one-shot · auto-disarms after turn)",
|
||||
argCompleter: ["off"],
|
||||
},
|
||||
{ cmd: "mcp", summary: "list MCP servers + tools attached to this session" },
|
||||
{
|
||||
cmd: "resource",
|
||||
argsHint: "[uri]",
|
||||
summary: "browse + read MCP resources (no arg → list URIs; <uri> → fetch contents)",
|
||||
argCompleter: "mcp-resources",
|
||||
},
|
||||
{
|
||||
cmd: "prompt",
|
||||
argsHint: "[name]",
|
||||
summary: "browse + fetch MCP prompts (no arg → list names; <name> → render prompt)",
|
||||
argCompleter: "mcp-prompts",
|
||||
},
|
||||
{ cmd: "tool", argsHint: "[N]", summary: "dump full output of the Nth tool call (1=latest)" },
|
||||
{
|
||||
cmd: "memory",
|
||||
argsHint: "[list|show <name>|forget <name>|clear <scope> confirm]",
|
||||
summary: "show / manage pinned memory (REASONIX.md + ~/.reasonix/memory)",
|
||||
},
|
||||
{
|
||||
cmd: "skill",
|
||||
argsHint: "[list|show <name>|<name> [args]]",
|
||||
summary: "list / run user skills (<project>/.reasonix/skills + ~/.reasonix/skills)",
|
||||
},
|
||||
{
|
||||
cmd: "hooks",
|
||||
argsHint: "[reload]",
|
||||
summary: "list active hooks (settings.json under .reasonix/) · reload re-reads from disk",
|
||||
},
|
||||
{
|
||||
cmd: "permissions",
|
||||
argsHint: "[list|add <prefix>|remove <prefix|N>|clear confirm]",
|
||||
summary:
|
||||
"show / edit shell allowlist (builtin read-only · per-project: ~/.reasonix/config.json)",
|
||||
argCompleter: ["list", "add", "remove", "clear"],
|
||||
},
|
||||
{
|
||||
cmd: "dashboard",
|
||||
argsHint: "[stop]",
|
||||
summary: "launch the embedded web dashboard (127.0.0.1, token-gated)",
|
||||
argCompleter: ["stop"],
|
||||
},
|
||||
{
|
||||
cmd: "cwd",
|
||||
argsHint: "<path>",
|
||||
summary:
|
||||
"switch session working directory (re-registers code tools, reloads hooks; MCP servers stay)",
|
||||
},
|
||||
{
|
||||
cmd: "update",
|
||||
summary: "show current vs latest version + the shell command to upgrade",
|
||||
},
|
||||
{
|
||||
cmd: "stats",
|
||||
summary:
|
||||
"cross-session cost dashboard (today / week / month / all-time · cache hit · vs Claude)",
|
||||
},
|
||||
{ cmd: "think", summary: "dump the last turn's full R1 reasoning (reasoner only)" },
|
||||
{
|
||||
cmd: "context",
|
||||
summary: "break down where context tokens are going: system / tools / per-turn log",
|
||||
},
|
||||
{ cmd: "retry", summary: "truncate & resend your last message (fresh sample)" },
|
||||
{
|
||||
cmd: "compact",
|
||||
argsHint: "[tokens]",
|
||||
summary:
|
||||
"shrink oversized tool results AND tool-call args (edit_file search/replace) in the log; cap in tokens, default 4000",
|
||||
},
|
||||
{ cmd: "keys", summary: "show all keyboard shortcuts and prompt prefixes" },
|
||||
{ cmd: "plans", summary: "list this session's active + archived plans, newest first" },
|
||||
{
|
||||
cmd: "replay",
|
||||
summary: "load an archived plan as a read-only Time Travel snapshot (default: newest)",
|
||||
argsHint: "[N]",
|
||||
},
|
||||
{ cmd: "sessions", summary: "list saved sessions (current marked with ▸)" },
|
||||
{ cmd: "forget", summary: "delete the current session from disk" },
|
||||
{ cmd: "setup", summary: "reminds you to exit and run `reasonix setup`" },
|
||||
{
|
||||
cmd: "semantic",
|
||||
summary: "show semantic_search status — built? Ollama installed? how to enable",
|
||||
},
|
||||
{ cmd: "clear", summary: "clear visible scrollback only (log/context kept)" },
|
||||
{ cmd: "new", summary: "start a fresh conversation (clear context + scrollback)" },
|
||||
{
|
||||
cmd: "loop",
|
||||
argsHint: "<5s..6h> <prompt> · stop · (no args = status)",
|
||||
summary: "auto-resubmit <prompt> every <interval> until you type something / Esc / /loop stop",
|
||||
},
|
||||
{ cmd: "exit", summary: "quit the TUI" },
|
||||
// Code-mode only
|
||||
{
|
||||
cmd: "init",
|
||||
argsHint: "[force]",
|
||||
summary:
|
||||
"scan the project and synthesize a baseline REASONIX.md (model writes; review with /apply). `force` overwrites an existing file.",
|
||||
contextual: "code",
|
||||
argCompleter: ["force"],
|
||||
},
|
||||
{
|
||||
cmd: "apply",
|
||||
argsHint: "[N|N,M|N-M]",
|
||||
summary:
|
||||
"commit pending edit blocks to disk (no arg → all; `1`, `1,3`, or `1-4` → that subset, rest stay pending)",
|
||||
contextual: "code",
|
||||
},
|
||||
{
|
||||
cmd: "discard",
|
||||
argsHint: "[N|N,M|N-M]",
|
||||
summary: "drop pending edit blocks without writing (no arg → all; indices → that subset)",
|
||||
contextual: "code",
|
||||
},
|
||||
{
|
||||
cmd: "walk",
|
||||
summary:
|
||||
"step through pending edits one block at a time (git-add-p style: y/n per block, a apply rest, A flip AUTO)",
|
||||
contextual: "code",
|
||||
},
|
||||
{ cmd: "undo", summary: "roll back the last applied edit batch", contextual: "code" },
|
||||
{
|
||||
cmd: "history",
|
||||
summary: "list every edit batch this session (ids for /show, undone markers)",
|
||||
contextual: "code",
|
||||
},
|
||||
{
|
||||
cmd: "show",
|
||||
argsHint: "[id]",
|
||||
summary: "dump a stored edit diff (omit id for newest non-undone)",
|
||||
contextual: "code",
|
||||
},
|
||||
{
|
||||
cmd: "commit",
|
||||
argsHint: '"msg"',
|
||||
summary: "git add -A && git commit -m ...",
|
||||
contextual: "code",
|
||||
},
|
||||
{
|
||||
cmd: "plan",
|
||||
argsHint: "[on|off]",
|
||||
summary: "toggle read-only plan mode (writes bounced until submit_plan + approval)",
|
||||
contextual: "code",
|
||||
argCompleter: ["on", "off"],
|
||||
},
|
||||
{
|
||||
cmd: "apply-plan",
|
||||
summary: "force-approve a pending / in-text plan (fallback if picker was missed)",
|
||||
contextual: "code",
|
||||
},
|
||||
{
|
||||
cmd: "mode",
|
||||
argsHint: "[review|auto|yolo]",
|
||||
summary:
|
||||
"edit-gate: review (queue) · auto (apply+undo) · yolo (apply+auto-shell). Shift+Tab cycles.",
|
||||
contextual: "code",
|
||||
argCompleter: ["review", "auto", "yolo"],
|
||||
},
|
||||
{ cmd: "jobs", summary: "list background jobs started by run_background", contextual: "code" },
|
||||
{
|
||||
cmd: "kill",
|
||||
argsHint: "<id>",
|
||||
summary: "stop a background job by id (SIGTERM → SIGKILL after grace)",
|
||||
contextual: "code",
|
||||
},
|
||||
{
|
||||
cmd: "logs",
|
||||
argsHint: "<id> [lines]",
|
||||
summary: "tail a background job's output (default last 80 lines)",
|
||||
contextual: "code",
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
* Filter the registry by a prefix string (without the leading `/`).
|
||||
* Empty prefix returns the full non-contextual list (plus code-mode
|
||||
* entries when `codeMode` is true). Case-insensitive.
|
||||
*/
|
||||
export function suggestSlashCommands(prefix: string, codeMode = false): SlashCommandSpec[] {
|
||||
const p = prefix.toLowerCase();
|
||||
return SLASH_COMMANDS.filter((c) => {
|
||||
if (c.contextual === "code" && !codeMode) return false;
|
||||
return c.cmd.startsWith(p);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Classify the prompt buffer for argument completion. Returns `null`
|
||||
* when the buffer isn't in a slash-with-args state.
|
||||
*
|
||||
* Firing shape: input must start with `/<cmd> ` (space after a known
|
||||
* command). The character right after the space through end-of-buffer
|
||||
* is the "arg tail"; if the tail has NO internal whitespace the
|
||||
* picker is live (tail is the partial). If the tail has whitespace,
|
||||
* the user has moved past the first argument position and we surface
|
||||
* the usage hint only.
|
||||
*/
|
||||
export function detectSlashArgContext(input: string, codeMode = false): SlashArgContext | null {
|
||||
// `/cmd <rest>` — one space, rest captured up to end-of-buffer.
|
||||
const m = /^\/(\S+) ([\s\S]*)$/.exec(input);
|
||||
if (!m) return null;
|
||||
const cmdName = m[1]!.toLowerCase();
|
||||
const tail = m[2] ?? "";
|
||||
const spec = SLASH_COMMANDS.find(
|
||||
(s) => s.cmd === cmdName && (s.contextual !== "code" || codeMode),
|
||||
);
|
||||
if (!spec) return null;
|
||||
const hasInternalSpace = /\s/.test(tail);
|
||||
const partialOffset = input.length - tail.length;
|
||||
if (hasInternalSpace) {
|
||||
// Past the first arg position (typing the second arg for e.g.
|
||||
// `/edit <file> <instruction>`, or mid-sentence for free-form).
|
||||
return { spec, partial: tail, partialOffset, kind: "hint" };
|
||||
}
|
||||
// No internal whitespace — we're still typing the first arg. Picker
|
||||
// is live if the spec declares a completer; otherwise show a hint
|
||||
// ("what goes here?") since the user's guessing.
|
||||
return {
|
||||
spec,
|
||||
partial: tail,
|
||||
partialOffset,
|
||||
kind: spec.argCompleter ? "picker" : "hint",
|
||||
};
|
||||
}
|
||||
|
||||
export function parseSlash(text: string): { cmd: string; args: string[] } | null {
|
||||
if (!text.startsWith("/")) return null;
|
||||
const parts = text.slice(1).trim().split(/\s+/);
|
||||
const cmd = parts[0]?.toLowerCase() ?? "";
|
||||
if (!cmd) return null;
|
||||
return { cmd, args: parts.slice(1) };
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import type { CacheFirstLoop } from "../../../loop.js";
|
||||
import { handlers as adminHandlers } from "./handlers/admin.js";
|
||||
import { handlers as basicHandlers } from "./handlers/basic.js";
|
||||
import { handlers as dashboardHandlers } from "./handlers/dashboard.js";
|
||||
import { handlers as editsHandlers } from "./handlers/edits.js";
|
||||
import { handlers as initHandlers } from "./handlers/init.js";
|
||||
import { handlers as jobsHandlers } from "./handlers/jobs.js";
|
||||
import { handlers as mcpHandlers } from "./handlers/mcp.js";
|
||||
import { handlers as memoryHandlers } from "./handlers/memory.js";
|
||||
import { handlers as modelHandlers } from "./handlers/model.js";
|
||||
import { handlers as observabilityHandlers } from "./handlers/observability.js";
|
||||
import { handlers as permissionsHandlers } from "./handlers/permissions.js";
|
||||
import { handlers as plansHandlers } from "./handlers/plans.js";
|
||||
import { handlers as semanticHandlers } from "./handlers/semantic.js";
|
||||
import { handlers as sessionsHandlers } from "./handlers/sessions.js";
|
||||
import { handlers as skillHandlers } from "./handlers/skill.js";
|
||||
import type { SlashContext, SlashResult } from "./types.js";
|
||||
|
||||
/**
|
||||
* A slash handler receives the command's args + the loop + shared
|
||||
* runtime context, and returns a synchronous SlashResult. Async work
|
||||
* (balance fetches, stop_job) fires-and-forgets via `ctx.postInfo`
|
||||
* instead — keeps the TUI input non-blocking.
|
||||
*/
|
||||
export type SlashHandler = (args: string[], loop: CacheFirstLoop, ctx: SlashContext) => SlashResult;
|
||||
|
||||
/**
|
||||
* Flat map of cmd → handler. Composed from per-topic modules so each
|
||||
* feature's logic stays local; aliases (e.g. `exit` / `quit`) are just
|
||||
* extra keys in the per-module handlers bag pointing at the same fn.
|
||||
*
|
||||
* Ordering of the spread matters only for duplicate keys; there are
|
||||
* none. Keep alphabetical for diff sanity when adding modules.
|
||||
*/
|
||||
const HANDLERS: Record<string, SlashHandler> = {
|
||||
...adminHandlers,
|
||||
...basicHandlers,
|
||||
...dashboardHandlers,
|
||||
...editsHandlers,
|
||||
...initHandlers,
|
||||
...jobsHandlers,
|
||||
...mcpHandlers,
|
||||
...memoryHandlers,
|
||||
...modelHandlers,
|
||||
...observabilityHandlers,
|
||||
...permissionsHandlers,
|
||||
...plansHandlers,
|
||||
...semanticHandlers,
|
||||
...sessionsHandlers,
|
||||
...skillHandlers,
|
||||
};
|
||||
|
||||
export function handleSlash(
|
||||
cmd: string,
|
||||
args: string[],
|
||||
loop: CacheFirstLoop,
|
||||
ctx: SlashContext = {},
|
||||
): SlashResult {
|
||||
const h = HANDLERS[cmd];
|
||||
if (h) return h(args, loop, ctx);
|
||||
return { unknown: true, info: `unknown command: /${cmd} (try /help)` };
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
import { existsSync, statSync } from "node:fs";
|
||||
import * as pathMod from "node:path";
|
||||
import {
|
||||
HOOK_EVENTS,
|
||||
type HookEvent,
|
||||
type ResolvedHook,
|
||||
globalSettingsPath,
|
||||
projectSettingsPath,
|
||||
} from "../../../../hooks.js";
|
||||
import { aggregateUsage, defaultUsageLogPath, readUsageLog } from "../../../../usage.js";
|
||||
import { VERSION, compareVersions, isNpxInstall } from "../../../../version.js";
|
||||
import { renderDashboard } from "../../../commands/stats.js";
|
||||
import type { SlashHandler } from "../dispatch.js";
|
||||
|
||||
const hooks: SlashHandler = (args, loop, ctx) => {
|
||||
const sub = (args[0] ?? "").toLowerCase();
|
||||
|
||||
if (sub === "reload") {
|
||||
if (!ctx.reloadHooks) {
|
||||
return {
|
||||
info: "/hooks reload is not available in this context (no reload callback wired).",
|
||||
};
|
||||
}
|
||||
const count = ctx.reloadHooks();
|
||||
return { info: `▸ reloaded hooks · ${count} active` };
|
||||
}
|
||||
|
||||
if (sub !== "" && sub !== "list" && sub !== "ls") {
|
||||
return {
|
||||
info: "usage: /hooks list active hooks\n /hooks reload re-read settings.json files",
|
||||
};
|
||||
}
|
||||
|
||||
const all = loop.hooks;
|
||||
const projPath = ctx.codeRoot ? projectSettingsPath(ctx.codeRoot) : undefined;
|
||||
const globPath = globalSettingsPath();
|
||||
if (all.length === 0) {
|
||||
const lines = [
|
||||
"no hooks configured.",
|
||||
"",
|
||||
"drop a settings.json with a `hooks` key into either of:",
|
||||
ctx.codeRoot
|
||||
? ` · ${projPath} (project)`
|
||||
: " · <project>/.reasonix/settings.json (project)",
|
||||
` · ${globPath} (global)`,
|
||||
"",
|
||||
"events: PreToolUse, PostToolUse, UserPromptSubmit, Stop",
|
||||
"exit 0 = pass · exit 2 = block (Pre*) · other = warn",
|
||||
];
|
||||
return { info: lines.join("\n") };
|
||||
}
|
||||
|
||||
const grouped = new Map<HookEvent, ResolvedHook[]>();
|
||||
for (const event of HOOK_EVENTS) grouped.set(event, []);
|
||||
for (const h of all) grouped.get(h.event)?.push(h);
|
||||
|
||||
const lines: string[] = [`▸ ${all.length} hook(s) loaded`];
|
||||
for (const event of HOOK_EVENTS) {
|
||||
const list = grouped.get(event) ?? [];
|
||||
if (list.length === 0) continue;
|
||||
lines.push("", `${event}:`);
|
||||
for (const h of list) {
|
||||
const match = h.match && h.match !== "*" ? ` match=${h.match}` : "";
|
||||
const desc = h.description ? ` — ${h.description}` : "";
|
||||
lines.push(` [${h.scope}]${match} ${h.command}${desc}`);
|
||||
}
|
||||
}
|
||||
lines.push("", `sources: project=${projPath ?? "(none — chat mode)"} · global=${globPath}`);
|
||||
return { info: lines.join("\n") };
|
||||
};
|
||||
|
||||
/**
|
||||
* `/update` — inside the TUI we deliberately do NOT spawn `npm install`.
|
||||
* stdio:inherit into a running Ink renderer corrupts the display, and
|
||||
* the process being upgraded is the same process that's still reading
|
||||
* its own binaries (messy on Windows). Instead we surface what we
|
||||
* already know from the App's background registry check and print the
|
||||
* exact shell command the user should run after exiting.
|
||||
*
|
||||
* The `latestVersion` ctx field is populated by App.tsx's mount-time
|
||||
* `getLatestVersion()` effect. When it's `null` we report the check
|
||||
* as pending/offline — still a useful output (current version + how
|
||||
* to force a fresh check from another terminal).
|
||||
*/
|
||||
const update: SlashHandler = (_args, _loop, ctx) => {
|
||||
const latest = ctx.latestVersion ?? null;
|
||||
const lines: string[] = [`current: reasonix ${VERSION}`];
|
||||
if (latest === null) {
|
||||
// Kick off a fresh fetch so a follow-up /update a few seconds
|
||||
// later has a real answer instead of the same pending message.
|
||||
ctx.refreshLatestVersion?.();
|
||||
lines.push(
|
||||
"latest: (not yet resolved — background check in flight or offline)",
|
||||
"",
|
||||
"triggered a fresh registry fetch — retry `/update` in a few seconds,",
|
||||
"or run `reasonix update` in another terminal to force it synchronously.",
|
||||
);
|
||||
return { info: lines.join("\n") };
|
||||
}
|
||||
lines.push(`latest: reasonix ${latest}`);
|
||||
const diff = compareVersions(VERSION, latest);
|
||||
if (diff >= 0) {
|
||||
lines.push("", "you're on the latest. nothing to do.");
|
||||
return { info: lines.join("\n") };
|
||||
}
|
||||
if (isNpxInstall()) {
|
||||
lines.push(
|
||||
"",
|
||||
"you're running via npx — the next `npx reasonix ...` launch will auto-fetch.",
|
||||
"to force a refresh sooner: `npm cache clean --force`.",
|
||||
);
|
||||
} else {
|
||||
lines.push(
|
||||
"",
|
||||
"to upgrade, exit this session and run:",
|
||||
" reasonix update (interactive, dry-run supported via --dry-run)",
|
||||
" npm install -g reasonix@latest (direct)",
|
||||
"",
|
||||
"in-session install is deliberately disabled — the npm spawn would",
|
||||
"corrupt this TUI's rendering and Windows can lock the running binary.",
|
||||
);
|
||||
}
|
||||
return { info: lines.join("\n") };
|
||||
};
|
||||
|
||||
/**
|
||||
* `/stats` — dashboard view of `~/.reasonix/usage.jsonl`, the same
|
||||
* roll-up `reasonix stats` (no arg) prints at the shell. Synchronous
|
||||
* disk read; cheap enough that we don't bother caching between slash
|
||||
* invocations.
|
||||
*
|
||||
* No transcript-path variant in-TUI: the per-file summary is scripty
|
||||
* and rarely wanted mid-session. If someone needs it they have the
|
||||
* CLI form (`reasonix stats <path>`).
|
||||
*/
|
||||
const stats: SlashHandler = () => {
|
||||
const path = defaultUsageLogPath();
|
||||
const records = readUsageLog(path);
|
||||
if (records.length === 0) {
|
||||
return {
|
||||
info: [
|
||||
"no usage data yet.",
|
||||
"",
|
||||
` ${path}`,
|
||||
"",
|
||||
"every turn you run here appends one record — this session's turns",
|
||||
"will show up in the dashboard once you send a message.",
|
||||
].join("\n"),
|
||||
};
|
||||
}
|
||||
const agg = aggregateUsage(records);
|
||||
return { info: renderDashboard(agg, path) };
|
||||
};
|
||||
|
||||
/**
|
||||
* `/cwd <path>` — switch the session working directory mid-session.
|
||||
* Validates the target (must exist, must be a directory), normalizes
|
||||
* to an absolute path with `~` expansion, then defers the actual swap
|
||||
* to the App-supplied `setCwd` callback. The callback updates hook
|
||||
* cwd, memory root, project shell allowlist root, `@file` mention
|
||||
* root, and (in code mode) re-registers filesystem / shell / memory /
|
||||
* skill tools — see App.tsx for the wiring.
|
||||
*
|
||||
* MCP servers do NOT follow the cwd switch — their stdio child was
|
||||
* spawned with the original cwd at session start, and there's no
|
||||
* standard "reconnect with new cwd" handshake. The handler surfaces
|
||||
* a one-line warning when MCP servers are present so users aren't
|
||||
* surprised by tools still resolving paths against the old root.
|
||||
*/
|
||||
const cwd: SlashHandler = (args, _loop, ctx) => {
|
||||
if (!ctx.setCwd) {
|
||||
return {
|
||||
info: "/cwd is not available in this context (no setCwd callback wired).",
|
||||
};
|
||||
}
|
||||
const raw = (args[0] ?? "").trim();
|
||||
if (!raw) {
|
||||
return {
|
||||
info: "usage: /cwd <path> (absolute or relative, ~ expands to home)",
|
||||
};
|
||||
}
|
||||
const home = process.env.HOME ?? process.env.USERPROFILE ?? "";
|
||||
const expanded = raw.startsWith("~") && home ? pathMod.join(home, raw.slice(1)) : raw;
|
||||
const abs = pathMod.resolve(expanded);
|
||||
if (!existsSync(abs)) {
|
||||
return { info: `▸ /cwd: path does not exist — ${abs}` };
|
||||
}
|
||||
let isDir = false;
|
||||
try {
|
||||
isDir = statSync(abs).isDirectory();
|
||||
} catch {
|
||||
// Permission denied or transient FS error — treat as not-a-dir
|
||||
// and let the user see the exact path so they can investigate.
|
||||
}
|
||||
if (!isDir) {
|
||||
return { info: `▸ /cwd: not a directory — ${abs}` };
|
||||
}
|
||||
let info: string;
|
||||
try {
|
||||
info = ctx.setCwd(abs);
|
||||
} catch (err) {
|
||||
return { info: `▸ /cwd failed: ${(err as Error).message}` };
|
||||
}
|
||||
const lines = [info];
|
||||
if (ctx.mcpServers && ctx.mcpServers.length > 0) {
|
||||
lines.push(
|
||||
` note: ${ctx.mcpServers.length} MCP server(s) still anchored to the original cwd —`,
|
||||
" their tools won't follow this switch. Restart the session for full reset.",
|
||||
);
|
||||
}
|
||||
return { info: lines.join("\n") };
|
||||
};
|
||||
|
||||
export const handlers: Record<string, SlashHandler> = {
|
||||
hook: hooks,
|
||||
hooks,
|
||||
cwd,
|
||||
update,
|
||||
stats,
|
||||
};
|
||||
@@ -0,0 +1,218 @@
|
||||
import { formatDuration, formatLoopStatus, parseLoopCommand } from "../../loop.js";
|
||||
import type { SlashHandler } from "../dispatch.js";
|
||||
|
||||
const exit: SlashHandler = () => ({ exit: true });
|
||||
|
||||
const clear: SlashHandler = () => ({
|
||||
clear: true,
|
||||
info: "▸ terminal cleared (viewport + scrollback). Context (message log) is intact — next turn still sees everything. Use /new to start fresh, or /forget to delete the session entirely.",
|
||||
});
|
||||
|
||||
const resetLog: SlashHandler = (_args, loop) => {
|
||||
// Actually drop the in-memory log + rewrite the session file so the
|
||||
// NEXT call has no prior context. Keeps session name, model, and
|
||||
// other config — just the conversation is reset.
|
||||
const { dropped } = loop.clearLog();
|
||||
return {
|
||||
clear: true,
|
||||
info: `▸ new conversation — dropped ${dropped} message(s) from context. Same session, fresh slate.`,
|
||||
};
|
||||
};
|
||||
|
||||
const keys: SlashHandler = () => ({
|
||||
info: [
|
||||
"Keyboard & prompt shortcuts:",
|
||||
"",
|
||||
" Enter submit the current prompt",
|
||||
" Shift+Enter / Ctrl+J insert a newline (multi-line prompt)",
|
||||
" \\<Enter> bash-style line continuation",
|
||||
" ← → ↑ ↓ move cursor / recall history at buffer boundary",
|
||||
" PageUp / PageDown jump to top / bottom of the WHOLE buffer (handy after a big paste)",
|
||||
" Ctrl+A / Ctrl+E jump to start / end of the CURRENT line",
|
||||
" Ctrl+U clear the entire input buffer",
|
||||
" Ctrl+W delete the word before the cursor",
|
||||
" Backspace delete left; Delete delete under cursor",
|
||||
" Esc abort the in-flight turn",
|
||||
" y / n accept / reject pending edits (code mode)",
|
||||
" Shift+Tab cycle edit gate: review ↔ AUTO (code mode, persists to config)",
|
||||
" u undo the latest non-undone edit batch (session-wide, not just banner)",
|
||||
"",
|
||||
"Prompt prefixes:",
|
||||
" /<name> slash command; Tab/Enter picks from the suggestion list",
|
||||
" @<path> inline a file under [Referenced files] (code mode).",
|
||||
" Trailing `@…` opens a file picker; ↑/↓ navigate, Tab/Enter pick.",
|
||||
" @https://... fetch the URL, strip HTML, inline under [Referenced URLs].",
|
||||
" Cached per session — same URL twice fetches once.",
|
||||
" !<cmd> run <cmd> as shell in the sandbox root; output goes into context",
|
||||
" so the model sees it next turn. No allowlist gate.",
|
||||
" #<note> append <note> to <project>/REASONIX.md (committable, team-shared).",
|
||||
" #g <note> append <note> to ~/.reasonix/REASONIX.md (global, never committed).",
|
||||
" Both pin into the immutable prefix every future session.",
|
||||
" Use `\\#literal` if you actually want a `#` heading sent to the model.",
|
||||
"",
|
||||
"Pickers (slash + @-mention):",
|
||||
" ↑ / ↓ navigate the suggestion list",
|
||||
" Tab insert the highlighted item without submitting",
|
||||
" Enter insert and (slash) run it, (@) keep editing",
|
||||
"",
|
||||
"MCP exploration:",
|
||||
" /mcp servers + tool/resource/prompt counts",
|
||||
" /resource [uri] browse & read resources exposed by your MCP servers",
|
||||
" /prompt [name] browse & fetch prompts exposed by your MCP servers",
|
||||
"",
|
||||
"Useful slashes: /help · /context · /stats · /compact · /new · /exit",
|
||||
].join("\n"),
|
||||
});
|
||||
|
||||
const help: SlashHandler = () => ({
|
||||
info: [
|
||||
"Commands:",
|
||||
" /help this message",
|
||||
" /keys keyboard shortcuts + prompt prefixes (!, @, /)",
|
||||
" /status show current settings",
|
||||
" /preset <fast|smart|max> one-tap presets — see below",
|
||||
" /model <id> deepseek-v4-flash or deepseek-v4-pro",
|
||||
" /pro [off] arm v4-pro for NEXT turn only (one-shot, auto-disarms)",
|
||||
" /harvest [on|off] Pillar 2: structured plan-state extraction (OPT-IN — costs extra)",
|
||||
" /branch <N|off> run N parallel samples (N>=2) — MANUAL ONLY, N× cost",
|
||||
" /effort <high|max> reasoning_effort cap (max=full thinking, high=cheaper/faster)",
|
||||
" /mcp list MCP servers + tools attached to this session",
|
||||
" /resource [uri] browse + read MCP resources (no arg → list URIs; <uri> → fetch)",
|
||||
" /prompt [name] browse + fetch MCP prompts (no arg → list names; <name> → render)",
|
||||
" /setup (exit + reconfigure) → run `reasonix setup`",
|
||||
" /compact [tokens] shrink large tool results in history (default 4000 tokens/result)",
|
||||
" /think dump the most recent turn's full R1 reasoning (reasoner only)",
|
||||
" /tool [N] list tool calls (or dump full output of #N, 1=most recent)",
|
||||
" /memory [sub] show pinned memory (REASONIX.md + ~/.reasonix/memory).",
|
||||
" subs: list | show <name> | forget <name> | clear <scope> confirm",
|
||||
" /skill [sub] list / run user skills (project/.reasonix/skills + ~/.reasonix/skills).",
|
||||
" subs: list | show <name> | <name> [args] (injects skill body as user turn)",
|
||||
" /retry truncate & resend your last message (fresh sample from the model)",
|
||||
" /apply [N|1,3|1-4] (code mode) commit pending edit blocks (no arg → all; index → subset)",
|
||||
" /discard [N|1,3|1-4] (code mode) drop pending edits (no arg → all; index → subset)",
|
||||
" /walk (code mode) step through pending edits one block at a time (y/n per block, a apply rest, A flip AUTO)",
|
||||
" /undo (code mode) roll back the latest non-undone edit batch",
|
||||
" /history (code mode) list every edit batch this session",
|
||||
" /show [id] (code mode) dump a stored edit diff (newest when id omitted)",
|
||||
' /commit "msg" (code mode) git add -A && git commit -m "msg"',
|
||||
" /plan [on|off] (code mode) toggle read-only plan mode; writes gated behind submit_plan + your approval",
|
||||
" /apply-plan (code mode) force-approve pending/in-text plan (fallback)",
|
||||
" /mode [review|auto|yolo] (code mode) review = queue · auto = apply+undo banner · yolo = apply+auto-shell. Shift+Tab cycles all three.",
|
||||
" /jobs (code mode) list background processes (run_background) — running and exited",
|
||||
" /kill <id> (code mode) stop a background job by id (SIGTERM → SIGKILL)",
|
||||
" /logs <id> [lines] (code mode) tail a background job's output (default 80 lines)",
|
||||
" /sessions list saved sessions (current is marked with ▸)",
|
||||
" /forget delete the current session from disk",
|
||||
" /new start fresh: drop all context + clear scrollback",
|
||||
" /clear clear displayed scrollback only (context kept — model still sees it)",
|
||||
" /loop <interval> <prompt> auto-resubmit <prompt> every <interval> (5s..6h). /loop stop · type anything to cancel.",
|
||||
" /exit quit",
|
||||
"",
|
||||
"Shell shortcut:",
|
||||
" !<cmd> run <cmd> in the sandbox root; output goes into",
|
||||
" the conversation so the model sees it next turn.",
|
||||
" No allowlist gate — user-typed = explicit consent.",
|
||||
" Example: !git status !ls src/ !npm test",
|
||||
"",
|
||||
"Quick memory:",
|
||||
" #<note> append <note> to <project>/REASONIX.md (committable).",
|
||||
" Example: #findByEmail must be case-insensitive",
|
||||
" #g <note> append <note> to ~/.reasonix/REASONIX.md (global, never committed).",
|
||||
" Example: #g always run pnpm not npm",
|
||||
" Both pin into every future session's prefix. Faster than /memory.",
|
||||
" Use `\\#text` to send a literal `#text` to the model.",
|
||||
"",
|
||||
"File references (code mode):",
|
||||
" @path/to/file inline file content under [Referenced files] on send.",
|
||||
" Type `@` to open the picker (↑↓ navigate, Tab/Enter pick).",
|
||||
"",
|
||||
"URL references:",
|
||||
" @https://example.com fetch the URL, strip HTML, inline under [Referenced URLs].",
|
||||
" Same URL twice in one session fetches once (in-mem cache).",
|
||||
" Trailing sentence punctuation (./,/)) is stripped automatically.",
|
||||
"",
|
||||
"Presets (branch + harvest are NEVER auto-enabled — opt-in only):",
|
||||
" fast v4-flash · effort=high cheapest · quick Q&A, one-line edits",
|
||||
" smart v4-flash · effort=max ← default · day-to-day coding",
|
||||
" max v4-pro · effort=max ~12× fast · hard single-shots",
|
||||
"",
|
||||
"Sessions (auto-enabled by default, named 'default'):",
|
||||
" reasonix chat --session <name> use a different named session",
|
||||
" reasonix chat --no-session disable persistence for this run",
|
||||
"",
|
||||
"Known limitation:",
|
||||
" Resizing the terminal mid-session may stack ghost header frames in",
|
||||
" scrollback (Ink library's live-region clear doesn't account for line",
|
||||
" re-wrapping at the new width). Scroll-up history is unaffected; the",
|
||||
" artifact is purely visual and clears the next time you /clear.",
|
||||
].join("\n"),
|
||||
});
|
||||
|
||||
const setup: SlashHandler = () => ({
|
||||
info:
|
||||
"To reconfigure (preset, MCP servers, API key), exit this chat and run " +
|
||||
"`reasonix setup`. Changes take effect on next launch.",
|
||||
});
|
||||
|
||||
const retry: SlashHandler = (_args, loop) => {
|
||||
const prev = loop.retryLastUser();
|
||||
if (!prev) {
|
||||
return {
|
||||
info: "nothing to retry — no prior user message in this session's log.",
|
||||
};
|
||||
}
|
||||
const preview = prev.length > 80 ? `${prev.slice(0, 80)}…` : prev;
|
||||
return {
|
||||
info: `▸ retrying: "${preview}"`,
|
||||
resubmit: prev,
|
||||
};
|
||||
};
|
||||
|
||||
const loop: SlashHandler = (args, _loop, ctx) => {
|
||||
if (!ctx.startLoop || !ctx.stopLoop || !ctx.getLoopStatus) {
|
||||
return {
|
||||
info: "/loop is only available in the interactive TUI (not in run/replay).",
|
||||
};
|
||||
}
|
||||
const cmd = parseLoopCommand(args);
|
||||
if (cmd.kind === "error") return { info: cmd.message };
|
||||
if (cmd.kind === "stop") {
|
||||
const wasActive = ctx.getLoopStatus() !== null;
|
||||
ctx.stopLoop();
|
||||
return {
|
||||
info: wasActive ? "▸ loop stopped." : "no active loop to stop.",
|
||||
};
|
||||
}
|
||||
if (cmd.kind === "status") {
|
||||
const status = ctx.getLoopStatus();
|
||||
if (!status) {
|
||||
return {
|
||||
info:
|
||||
"no active loop. Start one with `/loop <interval> <prompt>` (e.g. /loop 30s npm test).\n" +
|
||||
"Cancels on: /loop stop · Esc · /clear · /new · any user-typed prompt.",
|
||||
};
|
||||
}
|
||||
return { info: `▸ ${formatLoopStatus(status.prompt, status.nextFireMs, status.iter)}` };
|
||||
}
|
||||
// kind === "start"
|
||||
ctx.startLoop(cmd.intervalMs, cmd.prompt);
|
||||
return {
|
||||
info: `▸ loop started — re-submitting "${cmd.prompt}" every ${formatDuration(
|
||||
cmd.intervalMs,
|
||||
)}. Type anything (or /loop stop) to cancel.`,
|
||||
};
|
||||
};
|
||||
|
||||
export const handlers: Record<string, SlashHandler> = {
|
||||
exit,
|
||||
quit: exit,
|
||||
clear,
|
||||
new: resetLog,
|
||||
reset: resetLog,
|
||||
keys,
|
||||
help,
|
||||
"?": help,
|
||||
setup,
|
||||
retry,
|
||||
loop,
|
||||
};
|
||||
@@ -0,0 +1,69 @@
|
||||
import type { SlashHandler } from "../dispatch.js";
|
||||
|
||||
/**
|
||||
* `/dashboard [stop]` — boot the embedded web dashboard attached to
|
||||
* the current session. The actual server start / state capture lives
|
||||
* in App.tsx (`startDashboard` callback), which has direct refs to
|
||||
* the live loop, tool registry, MCP servers, and edit-mode state.
|
||||
* The slash handler is just the user-facing input + output bridge.
|
||||
*
|
||||
* Sub-commands:
|
||||
* /dashboard → boot if not running, print URL; if running, print existing URL
|
||||
* /dashboard stop → tear down the server
|
||||
*/
|
||||
const dashboard: SlashHandler = (args, _loop, ctx) => {
|
||||
if (!ctx.startDashboard || !ctx.getDashboardUrl) {
|
||||
return {
|
||||
info: "/dashboard is not available in this context (no startDashboard callback wired).",
|
||||
};
|
||||
}
|
||||
|
||||
const sub = (args[0] ?? "").toLowerCase();
|
||||
|
||||
if (sub === "stop" || sub === "off") {
|
||||
if (!ctx.stopDashboard) {
|
||||
return { info: "/dashboard stop: no stop callback wired." };
|
||||
}
|
||||
const url = ctx.getDashboardUrl();
|
||||
if (!url) return { info: "▸ dashboard is not running." };
|
||||
// Fire-and-forget the async stop. Caller (App.tsx) handles errors
|
||||
// by posting to historical.
|
||||
ctx.stopDashboard();
|
||||
return { info: "▸ dashboard stopping…" };
|
||||
}
|
||||
|
||||
const existing = ctx.getDashboardUrl();
|
||||
if (existing) {
|
||||
return {
|
||||
info: [
|
||||
"▸ dashboard is already running:",
|
||||
` ${existing}`,
|
||||
"",
|
||||
"Open it in any browser. Type `/dashboard stop` to tear it down.",
|
||||
].join("\n"),
|
||||
};
|
||||
}
|
||||
|
||||
// Boot. Slash handlers are sync; we kick the start asynchronously
|
||||
// and let App.tsx's `postInfo` deliver the URL when the server is
|
||||
// listening.
|
||||
ctx
|
||||
.startDashboard()
|
||||
.then((url) => {
|
||||
ctx.postInfo?.(
|
||||
[
|
||||
"▸ dashboard ready:",
|
||||
` ${url}`,
|
||||
"",
|
||||
"127.0.0.1 only · token-gated. Type `/dashboard stop` to shut down.",
|
||||
].join("\n"),
|
||||
);
|
||||
})
|
||||
.catch((err: Error) => {
|
||||
ctx.postInfo?.(`▸ dashboard failed to start: ${err.message}`);
|
||||
});
|
||||
|
||||
return { info: "▸ starting dashboard server…" };
|
||||
};
|
||||
|
||||
export const handlers: Record<string, SlashHandler> = { dashboard };
|
||||
@@ -0,0 +1,182 @@
|
||||
import type { EditMode } from "../../../../config.js";
|
||||
import { parseEditIndices } from "../../edit-history.js";
|
||||
import type { SlashHandler } from "../dispatch.js";
|
||||
import { runGitCommit, stripOuterQuotes } from "../helpers.js";
|
||||
|
||||
const undo: SlashHandler = (args, _loop, ctx) => {
|
||||
if (!ctx.codeUndo) {
|
||||
return {
|
||||
info: "/undo is only available inside `reasonix code` — chat mode doesn't apply edits.",
|
||||
};
|
||||
}
|
||||
return { info: ctx.codeUndo(args) };
|
||||
};
|
||||
|
||||
const history: SlashHandler = (_args, _loop, ctx) => {
|
||||
if (!ctx.codeHistory) {
|
||||
return { info: "/history is only available inside `reasonix code`." };
|
||||
}
|
||||
return { info: ctx.codeHistory() };
|
||||
};
|
||||
|
||||
const show: SlashHandler = (args, _loop, ctx) => {
|
||||
if (!ctx.codeShowEdit) {
|
||||
return { info: "/show is only available inside `reasonix code`." };
|
||||
}
|
||||
return { info: ctx.codeShowEdit(args) };
|
||||
};
|
||||
|
||||
const apply: SlashHandler = (args, _loop, ctx) => {
|
||||
if (!ctx.codeApply) {
|
||||
return {
|
||||
info: "/apply is only available inside `reasonix code` (nothing to apply here).",
|
||||
};
|
||||
}
|
||||
const parsed = parseIndicesArg(args, ctx.pendingEditCount ?? 0);
|
||||
if ("error" in parsed) return { info: `/apply: ${parsed.error}` };
|
||||
return { info: ctx.codeApply(parsed.indices) };
|
||||
};
|
||||
|
||||
const discard: SlashHandler = (args, _loop, ctx) => {
|
||||
if (!ctx.codeDiscard) {
|
||||
return {
|
||||
info: "/discard is only available inside `reasonix code`.",
|
||||
};
|
||||
}
|
||||
const parsed = parseIndicesArg(args, ctx.pendingEditCount ?? 0);
|
||||
if ("error" in parsed) return { info: `/discard: ${parsed.error}` };
|
||||
return { info: ctx.codeDiscard(parsed.indices) };
|
||||
};
|
||||
|
||||
/**
|
||||
* Bridge between the `args: string[]` shape commander gives us and the
|
||||
* comma-separated index syntax users actually type ("/apply 1,3-4").
|
||||
* The TUI's slash parser splits on whitespace, so `1,3-4` arrives as
|
||||
* `["1,3-4"]` and `1, 3, 4` arrives as `["1,", "3,", "4"]`. Re-joining
|
||||
* with commas + delegating to `parseEditIndices` handles both shapes.
|
||||
*
|
||||
* Empty `args` → `{ indices: [] }` (caller treats as "all").
|
||||
*/
|
||||
function parseIndicesArg(
|
||||
args: readonly string[],
|
||||
max: number,
|
||||
): { indices: readonly number[] } | { error: string } {
|
||||
const raw = args.join(",").replace(/,+/g, ",").replace(/^,|,$/g, "");
|
||||
if (!raw) return { indices: [] };
|
||||
const parsed = parseEditIndices(raw, max);
|
||||
if ("error" in parsed) return { error: parsed.error };
|
||||
return { indices: parsed.ok };
|
||||
}
|
||||
|
||||
const plan: SlashHandler = (args, _loop, ctx) => {
|
||||
if (!ctx.setPlanMode) {
|
||||
return {
|
||||
info: "/plan is only available inside `reasonix code` — chat mode doesn't gate tool writes.",
|
||||
};
|
||||
}
|
||||
const currentOn = Boolean(ctx.planMode);
|
||||
const raw = (args[0] ?? "").toLowerCase();
|
||||
let target: boolean;
|
||||
if (raw === "on" || raw === "true" || raw === "1") target = true;
|
||||
else if (raw === "off" || raw === "false" || raw === "0") target = false;
|
||||
else target = !currentOn;
|
||||
ctx.setPlanMode(target);
|
||||
if (target) {
|
||||
return {
|
||||
info: "▸ plan mode ON — write tools are gated; the model MUST call `submit_plan` before anything executes. (The model can also call submit_plan on its own for big tasks even when plan mode is off — this toggle is the stronger, explicit constraint.) Type /plan off to leave.",
|
||||
};
|
||||
}
|
||||
return {
|
||||
info: "▸ plan mode OFF — write tools are live again. Model can still propose plans autonomously for large tasks.",
|
||||
};
|
||||
};
|
||||
|
||||
const applyPlan: SlashHandler = (_args, _loop, ctx) => {
|
||||
if (!ctx.setPlanMode) {
|
||||
return {
|
||||
info: "/apply-plan is only available inside `reasonix code`.",
|
||||
};
|
||||
}
|
||||
ctx.setPlanMode(false);
|
||||
ctx.clearPendingPlan?.();
|
||||
return {
|
||||
info: "▸ plan approved — implementing",
|
||||
resubmit:
|
||||
"The plan above has been approved. Implement it now. You are out of plan mode — use edit_file / write_file / run_command as needed. Stick to the plan unless you discover a concrete reason to deviate; if you do, tell me and wait for a response before making that deviation.",
|
||||
};
|
||||
};
|
||||
|
||||
const mode: SlashHandler = (args, _loop, ctx) => {
|
||||
if (!ctx.setEditMode) {
|
||||
return {
|
||||
info: "/mode is only available inside `reasonix code`.",
|
||||
};
|
||||
}
|
||||
const raw = (args[0] ?? "").toLowerCase();
|
||||
const current = ctx.editMode ?? "review";
|
||||
let target: EditMode;
|
||||
if (raw === "review") target = "review";
|
||||
else if (raw === "auto") target = "auto";
|
||||
else if (raw === "yolo") target = "yolo";
|
||||
else if (raw === "") {
|
||||
// Bare /mode cycles review → auto → yolo → review, mirroring
|
||||
// Shift+Tab. Users who just want to see current mode without
|
||||
// flipping can read /status.
|
||||
target = current === "review" ? "auto" : current === "auto" ? "yolo" : "review";
|
||||
} else {
|
||||
return {
|
||||
info: "usage: /mode <review|auto|yolo> (Shift+Tab also cycles)",
|
||||
};
|
||||
}
|
||||
ctx.setEditMode(target);
|
||||
const banner =
|
||||
target === "yolo"
|
||||
? "▸ edit mode: YOLO — edits AND shell commands auto-run with no prompt. /undo still rolls back edits. Use carefully."
|
||||
: target === "auto"
|
||||
? "▸ edit mode: AUTO — edits apply immediately; press u within 5s to undo, or /undo later. Shell commands still ask."
|
||||
: "▸ edit mode: review — edits queue for /apply (or y) / /discard (or n)";
|
||||
return { info: banner };
|
||||
};
|
||||
|
||||
const commit: SlashHandler = (args, _loop, ctx) => {
|
||||
if (!ctx.codeRoot) {
|
||||
return {
|
||||
info: "/commit is only available inside `reasonix code` (needs a rooted git repo).",
|
||||
};
|
||||
}
|
||||
// Reassemble the original argv. The parser lowercases cmd but leaves
|
||||
// args alone, and the TUI splits on whitespace which mangles quoted
|
||||
// messages — rejoin with spaces and strip a surrounding pair of
|
||||
// double quotes if the user wrote them.
|
||||
const raw = args.join(" ").trim();
|
||||
const message = stripOuterQuotes(raw);
|
||||
if (!message) {
|
||||
return {
|
||||
info: `usage: /commit "your commit message" — runs \`git add -A && git commit -m "…"\` in ${ctx.codeRoot}`,
|
||||
};
|
||||
}
|
||||
return runGitCommit(ctx.codeRoot, message);
|
||||
};
|
||||
|
||||
const walk: SlashHandler = (_args, _loop, ctx) => {
|
||||
if (!ctx.startWalkthrough) {
|
||||
return {
|
||||
info: "/walk is only available inside `reasonix code`.",
|
||||
};
|
||||
}
|
||||
return { info: ctx.startWalkthrough() };
|
||||
};
|
||||
|
||||
export const handlers: Record<string, SlashHandler> = {
|
||||
undo,
|
||||
history,
|
||||
show,
|
||||
apply,
|
||||
discard,
|
||||
plan,
|
||||
"apply-plan": applyPlan,
|
||||
applyplan: applyPlan,
|
||||
mode,
|
||||
commit,
|
||||
walk,
|
||||
};
|
||||
@@ -0,0 +1,126 @@
|
||||
/**
|
||||
* `/init` — auto-generate a baseline REASONIX.md by asking the model
|
||||
* to scan the project and synthesize a concise summary.
|
||||
*
|
||||
* Mechanism: the slash handler injects a structured user-turn prompt
|
||||
* (via `resubmit`) that hard-constrains the model to write a short,
|
||||
* fact-only document and stop. It uses the same filesystem tools the
|
||||
* model already has — no new tool, no new pipeline. The model's output
|
||||
* lands as an `edit_file` (empty SEARCH = create new) or `write_file`
|
||||
* SEARCH/REPLACE block, which goes through the normal /apply review
|
||||
* gate so the user can audit before the file hits disk.
|
||||
*
|
||||
* Why this shape rather than a CLI command: REASONIX.md goes into
|
||||
* the system prompt every session, so its content has to fit. A
|
||||
* model-driven generator that runs inside the same loop the user
|
||||
* will use later gives the most consistent output, and reusing the
|
||||
* existing edit-review flow means we don't have to invent a
|
||||
* separate "review the generated doc" UI.
|
||||
*/
|
||||
|
||||
import { existsSync } from "node:fs";
|
||||
import * as pathMod from "node:path";
|
||||
import type { SlashHandler } from "../dispatch.js";
|
||||
|
||||
/**
|
||||
* The init brief. Sent verbatim as a user turn (via resubmit). Hard
|
||||
* constraints up top because flash will skim and the structure of
|
||||
* the document matters for system-prompt budget. The "STOP after
|
||||
* writing" line is load-bearing — without it the model will follow
|
||||
* up with "want me to also …" and burn turns on noise.
|
||||
*/
|
||||
const INIT_PROMPT = [
|
||||
"# Task: Initialize REASONIX.md",
|
||||
"",
|
||||
"I want you to generate a REASONIX.md at the project root that captures",
|
||||
"the working knowledge a future Reasonix session needs to be productive",
|
||||
"here. This file is auto-pinned into your system prompt every launch,",
|
||||
"so its size and accuracy matter.",
|
||||
"",
|
||||
"## Hard constraints (do NOT relax these)",
|
||||
"",
|
||||
"- **Length cap: ≤ 80 lines / 3KB total.** Be concise. If you can't fit a",
|
||||
" section, drop it.",
|
||||
"- **Only document things you can verify by reading files.** Do NOT",
|
||||
" speculate about architectural intent, future roadmap, or design",
|
||||
" rationale. If it isn't obvious from the code, leave it out.",
|
||||
"- **No placeholder text.** No 'TODO: describe X', no 'Add more here'.",
|
||||
" Either state a fact or omit the section.",
|
||||
"",
|
||||
"## Procedure",
|
||||
"",
|
||||
"1. Read the top of any existing README* file.",
|
||||
"2. Read the manifest (package.json / Cargo.toml / pyproject.toml /",
|
||||
" go.mod / etc.) — pick whichever exists.",
|
||||
"3. `directory_tree` 1-2 levels deep on the project root, skipping",
|
||||
" common build/dependency dirs (node_modules, dist, target, .git,",
|
||||
" venv, __pycache__).",
|
||||
"4. Identify: primary language + framework, top-level layout, test",
|
||||
" runner, lint/format setup, build/run/test scripts, any non-obvious",
|
||||
" convention with visible evidence (commit message format, import",
|
||||
" order, naming pattern).",
|
||||
"5. Write REASONIX.md with the sections below, skipping any you can't",
|
||||
" fill from evidence.",
|
||||
"",
|
||||
"## Sections to use (skip ones with no evidence)",
|
||||
"",
|
||||
"- **Stack** — language + framework + 3-5 key deps. One line each.",
|
||||
"- **Layout** — top-level dirs and what lives in each. One line each.",
|
||||
"- **Commands** — verbatim from `scripts` block (or equivalent):",
|
||||
" build / test / lint / typecheck / dev / format. Whatever exists.",
|
||||
"- **Conventions** — only things visible in the code. Examples:",
|
||||
" '*.test.ts colocated with source', 'named exports only',",
|
||||
" 'commits use Conventional Commits prefix'. If you can't find any",
|
||||
" CONVENTION evidence, omit the whole section.",
|
||||
"- **Watch out for** — gotchas a new contributor would benefit from",
|
||||
" knowing BEFORE editing. Examples: 'edit_file SEARCH must match",
|
||||
" byte-for-byte', 'this dir is generated, don't edit by hand'.",
|
||||
" Omit if you find nothing concrete.",
|
||||
"",
|
||||
"## Output",
|
||||
"",
|
||||
"Write the result to `REASONIX.md` in the project root using the",
|
||||
"filesystem tools (edit_file with empty SEARCH if creating new,",
|
||||
"write_file if overwriting). After writing, STOP — do not summarize",
|
||||
"what you did, do not propose follow-up tasks. The user will review",
|
||||
"the pending edit via /apply.",
|
||||
"",
|
||||
"Start now.",
|
||||
].join("\n");
|
||||
|
||||
const init: SlashHandler = (args, _loop, ctx) => {
|
||||
if (!ctx.codeRoot) {
|
||||
return {
|
||||
info: [
|
||||
"/init only works in code mode (it needs filesystem tools).",
|
||||
"Run `reasonix code [path]` to start a session rooted at the",
|
||||
"project you want to initialize, then run /init.",
|
||||
].join("\n"),
|
||||
};
|
||||
}
|
||||
const force = (args[0] ?? "").toLowerCase() === "force";
|
||||
const target = pathMod.join(ctx.codeRoot, "REASONIX.md");
|
||||
if (existsSync(target) && !force) {
|
||||
return {
|
||||
info: [
|
||||
`▸ REASONIX.md already exists at ${target}`,
|
||||
"",
|
||||
" /init force regenerate from scratch (overwrites)",
|
||||
"",
|
||||
" Or edit it by hand — it's just markdown. The current file is",
|
||||
" pinned into the system prompt every launch as-is.",
|
||||
].join("\n"),
|
||||
};
|
||||
}
|
||||
return {
|
||||
info: [
|
||||
"▸ /init — model will scan the project and synthesize REASONIX.md.",
|
||||
" The result lands as a pending edit; review with /apply or /walk.",
|
||||
].join("\n"),
|
||||
resubmit: INIT_PROMPT,
|
||||
};
|
||||
};
|
||||
|
||||
export const handlers: Record<string, SlashHandler> = {
|
||||
init,
|
||||
};
|
||||
@@ -0,0 +1,84 @@
|
||||
import type { SlashHandler } from "../dispatch.js";
|
||||
|
||||
const jobs: SlashHandler = (_args, _loop, ctx) => {
|
||||
if (!ctx.jobs) {
|
||||
return { info: "/jobs is only available inside `reasonix code`." };
|
||||
}
|
||||
const rows = ctx.jobs.list();
|
||||
if (rows.length === 0) {
|
||||
return { info: "no background jobs yet — use run_background to start one" };
|
||||
}
|
||||
const lines = ["Background jobs:"];
|
||||
for (const r of rows) {
|
||||
const age = ((Date.now() - r.startedAt) / 1000).toFixed(1);
|
||||
const state = r.running
|
||||
? `running · pid ${r.pid ?? "?"}`
|
||||
: r.exitCode !== null
|
||||
? `exit ${r.exitCode}`
|
||||
: r.spawnError
|
||||
? "failed"
|
||||
: "stopped";
|
||||
lines.push(
|
||||
` ${String(r.id).padStart(3)} ${state.padEnd(20)} ${age.padStart(6)}s ago $ ${r.command}`,
|
||||
);
|
||||
}
|
||||
lines.push("");
|
||||
lines.push("/kill <id> to stop one · /logs <id> [lines] to tail output");
|
||||
return { info: lines.join("\n") };
|
||||
};
|
||||
|
||||
const kill: SlashHandler = (args, _loop, ctx) => {
|
||||
if (!ctx.jobs) return { info: "/kill is only available inside `reasonix code`." };
|
||||
const id = Number.parseInt(args[0] ?? "", 10);
|
||||
if (!Number.isFinite(id)) return { info: "usage: /kill <id> (see /jobs for ids)" };
|
||||
const rec = ctx.jobs.list().find((r) => r.id === id);
|
||||
if (!rec) return { info: `job ${id}: not found` };
|
||||
if (!rec.running) return { info: `job ${id} already exited (${rec.exitCode ?? "?"})` };
|
||||
// Fire-and-forget: the registry waits for grace + SIGKILL internally;
|
||||
// returning immediately keeps the slash synchronous so the user's
|
||||
// prompt doesn't lock up for 2s on every /kill. The postInfo
|
||||
// callback lands a follow-up row in historical when the kill
|
||||
// actually completes, so the user sees "job N stopped" without
|
||||
// polling /jobs.
|
||||
const jobsRef = ctx.jobs;
|
||||
void (async () => {
|
||||
const final = await jobsRef.stop(id);
|
||||
if (!final) return;
|
||||
const status = final.running
|
||||
? "still alive after SIGKILL (!) — report this as a bug"
|
||||
: final.exitCode !== null
|
||||
? `exit ${final.exitCode}`
|
||||
: "stopped";
|
||||
ctx.postInfo?.(`▸ job ${id} ${status}`);
|
||||
})();
|
||||
return {
|
||||
info: `▸ stopping job ${id} (tree kill: SIGTERM → SIGKILL after 2s grace; Windows: taskkill /T /F)`,
|
||||
};
|
||||
};
|
||||
|
||||
const logs: SlashHandler = (args, _loop, ctx) => {
|
||||
if (!ctx.jobs) return { info: "/logs is only available inside `reasonix code`." };
|
||||
const id = Number.parseInt(args[0] ?? "", 10);
|
||||
if (!Number.isFinite(id)) {
|
||||
return { info: "usage: /logs <id> [lines] (default last 80 lines)" };
|
||||
}
|
||||
const requested = Number.parseInt(args[1] ?? "", 10);
|
||||
const tail = Number.isFinite(requested) && requested > 0 ? requested : 80;
|
||||
const out = ctx.jobs.read(id, { tailLines: tail });
|
||||
if (!out) return { info: `job ${id}: not found` };
|
||||
const status = out.running
|
||||
? `running · pid ${out.pid ?? "?"}`
|
||||
: out.exitCode !== null
|
||||
? `exited ${out.exitCode}`
|
||||
: out.spawnError
|
||||
? `failed (${out.spawnError})`
|
||||
: "stopped";
|
||||
const header = `[job ${id} · ${status}]\n$ ${out.command}`;
|
||||
return { info: out.output ? `${header}\n${out.output}` : header };
|
||||
};
|
||||
|
||||
export const handlers: Record<string, SlashHandler> = {
|
||||
jobs,
|
||||
kill,
|
||||
logs,
|
||||
};
|
||||
@@ -0,0 +1,64 @@
|
||||
import type { SlashHandler } from "../dispatch.js";
|
||||
import { appendSection } from "../helpers.js";
|
||||
|
||||
const mcp: SlashHandler = (_args, loop, ctx) => {
|
||||
const servers = ctx.mcpServers ?? [];
|
||||
const specs = ctx.mcpSpecs ?? [];
|
||||
const toolSpecs = loop.prefix.toolSpecs ?? [];
|
||||
if (servers.length === 0 && specs.length === 0 && toolSpecs.length === 0) {
|
||||
return {
|
||||
info:
|
||||
"no MCP servers attached. Run `reasonix setup` to pick some, " +
|
||||
'or launch with --mcp "<spec>". `reasonix mcp list` shows the catalog.',
|
||||
};
|
||||
}
|
||||
// Rich path — we have full inspection reports, so show each server
|
||||
// with its tools / resources / prompts grouped together.
|
||||
if (servers.length > 0) {
|
||||
const lines: string[] = [];
|
||||
let anyResources = false;
|
||||
let anyPrompts = false;
|
||||
for (const s of servers) {
|
||||
const { report } = s;
|
||||
const serverName = report.serverInfo.name || "(unknown)";
|
||||
const serverVer = report.serverInfo.version ? ` v${report.serverInfo.version}` : "";
|
||||
lines.push(`[${s.label}] ${serverName}${serverVer} — ${s.spec}`);
|
||||
lines.push(` tools ${s.toolCount}`);
|
||||
appendSection(lines, "resources", report.resources);
|
||||
appendSection(lines, "prompts ", report.prompts);
|
||||
if (report.resources.supported && report.resources.items.length > 0) anyResources = true;
|
||||
if (report.prompts.supported && report.prompts.items.length > 0) anyPrompts = true;
|
||||
lines.push("");
|
||||
}
|
||||
if (anyResources || anyPrompts) {
|
||||
const hints: string[] = [];
|
||||
if (anyResources) hints.push("`/resource` to browse+read");
|
||||
if (anyPrompts) hints.push("`/prompt` to browse+fetch");
|
||||
lines.push(hints.join(" · "));
|
||||
} else {
|
||||
lines.push(
|
||||
"Chat mode consumes tools today; resources+prompts are surfaced here for awareness.",
|
||||
);
|
||||
}
|
||||
lines.push(
|
||||
"Full catalog: `reasonix mcp list` · deeper diagnosis: `reasonix mcp inspect <spec>`.",
|
||||
);
|
||||
return { info: lines.join("\n") };
|
||||
}
|
||||
// Fallback — older path when the TUI hasn't populated `mcpServers`.
|
||||
const lines: string[] = [];
|
||||
if (specs.length > 0) {
|
||||
lines.push(`MCP servers (${specs.length}):`);
|
||||
for (const spec of specs) lines.push(` · ${spec}`);
|
||||
lines.push("");
|
||||
}
|
||||
if (toolSpecs.length > 0) {
|
||||
lines.push(`Tools in registry (${toolSpecs.length}):`);
|
||||
for (const t of toolSpecs) lines.push(` · ${t.function.name}`);
|
||||
}
|
||||
lines.push("");
|
||||
lines.push("To change this set, exit and run `reasonix setup`.");
|
||||
return { info: lines.join("\n") };
|
||||
};
|
||||
|
||||
export const handlers: Record<string, SlashHandler> = { mcp };
|
||||
@@ -0,0 +1,169 @@
|
||||
import {
|
||||
PROJECT_MEMORY_FILE,
|
||||
memoryEnabled,
|
||||
readProjectMemory,
|
||||
} from "../../../../project-memory.js";
|
||||
import { type MemoryScope, MemoryStore } from "../../../../user-memory.js";
|
||||
import type { SlashHandler } from "../dispatch.js";
|
||||
import { resolveMemoryTarget } from "../helpers.js";
|
||||
|
||||
/**
|
||||
* `/memory` family. Bare `/memory` shows what's pinned (REASONIX.md +
|
||||
* both MEMORY.md blocks). Subcommands manage the user-memory store:
|
||||
* list — every memory file, both scopes
|
||||
* show <name> — dump one file's body
|
||||
* show <scope>/<name> — disambiguate when name exists in both scopes
|
||||
* forget <name> — delete (same scope resolution as show)
|
||||
* clear <scope> confirm — wipe a scope (typed literal "confirm" required)
|
||||
*/
|
||||
const memory: SlashHandler = (args, _loop, ctx) => {
|
||||
if (!memoryEnabled()) {
|
||||
return {
|
||||
info: "memory is disabled (REASONIX_MEMORY=off in env). Unset the var to re-enable — no REASONIX.md or ~/.reasonix/memory content will be pinned in the meantime.",
|
||||
};
|
||||
}
|
||||
if (!ctx.memoryRoot) {
|
||||
return {
|
||||
info: "no working directory on this session — `/memory` needs a root to resolve REASONIX.md from. (Running in a test harness?)",
|
||||
};
|
||||
}
|
||||
// `codeRoot` is set only when running `reasonix code`. Chat mode has
|
||||
// `memoryRoot` = cwd (for REASONIX.md), but we don't treat cwd as a
|
||||
// sandbox — project-scope user memory requires a real code-mode root.
|
||||
const store = new MemoryStore({ projectRoot: ctx.codeRoot });
|
||||
const sub = (args[0] ?? "").toLowerCase();
|
||||
|
||||
if (sub === "list" || sub === "ls") {
|
||||
const entries = store.list();
|
||||
if (entries.length === 0) {
|
||||
return {
|
||||
info: "no user memories yet. The model can call `remember` to save one, or you can create files by hand in ~/.reasonix/memory/global/ or the per-project subdir.",
|
||||
};
|
||||
}
|
||||
const lines = [`User memories (${entries.length}):`];
|
||||
for (const e of entries) {
|
||||
const tag = `${e.scope}/${e.type}`.padEnd(18);
|
||||
const name = e.name.padEnd(28);
|
||||
const desc = e.description.length > 70 ? `${e.description.slice(0, 69)}…` : e.description;
|
||||
lines.push(` ${tag} ${name} ${desc}`);
|
||||
}
|
||||
lines.push("");
|
||||
lines.push("View body: /memory show <name> Delete: /memory forget <name>");
|
||||
return { info: lines.join("\n") };
|
||||
}
|
||||
|
||||
if (sub === "show" || sub === "cat") {
|
||||
const target = args[1];
|
||||
if (!target) return { info: "usage: /memory show <name> or /memory show <scope>/<name>" };
|
||||
const resolved = resolveMemoryTarget(store, target);
|
||||
if (!resolved) return { info: `no memory found: ${target}` };
|
||||
try {
|
||||
const entry = store.read(resolved.scope, resolved.name);
|
||||
return {
|
||||
info: [
|
||||
`▸ ${entry.scope}/${entry.name} (${entry.type}, created ${entry.createdAt || "?"})`,
|
||||
entry.description ? ` ${entry.description}` : "",
|
||||
"",
|
||||
entry.body,
|
||||
]
|
||||
.filter((l) => l !== "")
|
||||
.concat("")
|
||||
.join("\n"),
|
||||
};
|
||||
} catch (err) {
|
||||
return { info: `show failed: ${(err as Error).message}` };
|
||||
}
|
||||
}
|
||||
|
||||
if (sub === "forget" || sub === "rm" || sub === "delete") {
|
||||
const target = args[1];
|
||||
if (!target) return { info: "usage: /memory forget <name> or /memory forget <scope>/<name>" };
|
||||
const resolved = resolveMemoryTarget(store, target);
|
||||
if (!resolved) return { info: `no memory found: ${target}` };
|
||||
try {
|
||||
const ok = store.delete(resolved.scope, resolved.name);
|
||||
return {
|
||||
info: ok
|
||||
? `▸ forgot ${resolved.scope}/${resolved.name}. Next /new or launch won't see it.`
|
||||
: `could not forget ${resolved.scope}/${resolved.name} (already gone?)`,
|
||||
};
|
||||
} catch (err) {
|
||||
return { info: `forget failed: ${(err as Error).message}` };
|
||||
}
|
||||
}
|
||||
|
||||
if (sub === "clear") {
|
||||
const rawScope = (args[1] ?? "").toLowerCase();
|
||||
if (rawScope !== "global" && rawScope !== "project") {
|
||||
return { info: "usage: /memory clear <global|project> confirm" };
|
||||
}
|
||||
if ((args[2] ?? "").toLowerCase() !== "confirm") {
|
||||
return {
|
||||
info: `about to delete every memory in scope=${rawScope}. Re-run with the word 'confirm' to proceed: /memory clear ${rawScope} confirm`,
|
||||
};
|
||||
}
|
||||
const scope = rawScope as MemoryScope;
|
||||
const entries = store.list().filter((e) => e.scope === scope);
|
||||
let deleted = 0;
|
||||
for (const e of entries) {
|
||||
try {
|
||||
if (store.delete(scope, e.name)) deleted++;
|
||||
} catch {
|
||||
/* skip */
|
||||
}
|
||||
}
|
||||
return { info: `▸ cleared scope=${scope} — deleted ${deleted} memory file(s).` };
|
||||
}
|
||||
|
||||
// Bare `/memory` — show REASONIX.md + both MEMORY.md blocks.
|
||||
const parts: string[] = [];
|
||||
const projMem = readProjectMemory(ctx.memoryRoot);
|
||||
if (projMem) {
|
||||
const hdr = projMem.truncated
|
||||
? `▸ ${PROJECT_MEMORY_FILE}: ${projMem.path} (${projMem.originalChars.toLocaleString()} chars, truncated)`
|
||||
: `▸ ${PROJECT_MEMORY_FILE}: ${projMem.path} (${projMem.originalChars.toLocaleString()} chars)`;
|
||||
parts.push(hdr, "", projMem.content);
|
||||
}
|
||||
const globalIdx = store.loadIndex("global");
|
||||
if (globalIdx) {
|
||||
parts.push(
|
||||
"",
|
||||
`▸ global memory (${globalIdx.originalChars.toLocaleString()} chars${globalIdx.truncated ? ", truncated" : ""})`,
|
||||
"",
|
||||
globalIdx.content,
|
||||
);
|
||||
}
|
||||
const projectIdx = store.loadIndex("project");
|
||||
if (projectIdx) {
|
||||
parts.push(
|
||||
"",
|
||||
`▸ project memory (${projectIdx.originalChars.toLocaleString()} chars${projectIdx.truncated ? ", truncated" : ""})`,
|
||||
"",
|
||||
projectIdx.content,
|
||||
);
|
||||
}
|
||||
if (parts.length === 0) {
|
||||
return {
|
||||
info: [
|
||||
`no memory pinned in ${ctx.memoryRoot}.`,
|
||||
"",
|
||||
"Three layers are available:",
|
||||
` 1. ${PROJECT_MEMORY_FILE} — committable team memory (in the repo).`,
|
||||
" 2. ~/.reasonix/memory/global/ — your cross-project private memory.",
|
||||
` 3. ~/.reasonix/memory/<project-hash>/ — this project's private memory.`,
|
||||
"",
|
||||
"Ask the model to `remember` something, or hand-edit files directly.",
|
||||
"Changes take effect on next /new or launch — the system prompt is hashed once per session to keep the prefix cache warm.",
|
||||
"",
|
||||
"Subcommands: /memory list | /memory show <name> | /memory forget <name> | /memory clear <scope> confirm",
|
||||
].join("\n"),
|
||||
};
|
||||
}
|
||||
parts.push(
|
||||
"",
|
||||
"Changes take effect on next /new or launch. Subcommands: /memory list | show | forget | clear",
|
||||
);
|
||||
return { info: parts.join("\n") };
|
||||
};
|
||||
|
||||
export const handlers: Record<string, SlashHandler> = { memory };
|
||||
@@ -0,0 +1,187 @@
|
||||
import { saveReasoningEffort } from "../../../../config.js";
|
||||
import type { SlashHandler } from "../dispatch.js";
|
||||
|
||||
const model: SlashHandler = (args, loop, ctx) => {
|
||||
const id = args[0];
|
||||
const known = ctx.models ?? null;
|
||||
if (!id) {
|
||||
const hint =
|
||||
known && known.length > 0
|
||||
? known.join(" | ")
|
||||
: "try deepseek-v4-flash or deepseek-v4-pro — run /models to fetch the live list";
|
||||
return { info: `usage: /model <id> (${hint})` };
|
||||
}
|
||||
loop.configure({ model: id });
|
||||
// Soft validation: if we have the live list and the id isn't in
|
||||
// it, flag a warning but still switch — DeepSeek may have just
|
||||
// released something we haven't indexed yet, and refusing would
|
||||
// be worse than a bad API error on the next call.
|
||||
if (known && known.length > 0 && !known.includes(id)) {
|
||||
return {
|
||||
info: `model → ${id} (⚠ not in the fetched catalog: ${known.join(", ")}. If this is wrong the next call will 400 — run /models to refresh.)`,
|
||||
};
|
||||
}
|
||||
return { info: `model → ${id}` };
|
||||
};
|
||||
|
||||
const models: SlashHandler = (_args, loop, ctx) => {
|
||||
const list = ctx.models ?? null;
|
||||
if (list === null) {
|
||||
ctx.refreshModels?.();
|
||||
return {
|
||||
info: "fetching /models from DeepSeek… run /models again in a moment. If it stays empty, your API key may lack permission or the network is blocked.",
|
||||
};
|
||||
}
|
||||
if (list.length === 0) {
|
||||
return {
|
||||
info: "DeepSeek /models returned an empty list. Try /models again, or check your account status at api-docs.deepseek.com.",
|
||||
};
|
||||
}
|
||||
const current = loop.model;
|
||||
const lines = list.map((id) => (id === current ? `▸ ${id} (current)` : ` ${id}`));
|
||||
return {
|
||||
info: [
|
||||
`Available models (DeepSeek /models · ${list.length} total):`,
|
||||
"",
|
||||
...lines,
|
||||
"",
|
||||
"Switch with: /model <id>",
|
||||
].join("\n"),
|
||||
};
|
||||
};
|
||||
|
||||
const harvest: SlashHandler = (args, loop) => {
|
||||
const arg = (args[0] ?? "").toLowerCase();
|
||||
const on = arg === "" ? !loop.harvestEnabled : arg === "on" || arg === "true" || arg === "1";
|
||||
loop.configure({ harvest: on });
|
||||
if (loop.harvestEnabled) {
|
||||
return {
|
||||
info: "harvest → on (Pillar-2 plan-state extraction · +1 cheap flash call per turn · opt-in only; no preset turns it on)",
|
||||
};
|
||||
}
|
||||
return { info: "harvest → off" };
|
||||
};
|
||||
|
||||
const preset: SlashHandler = (args, loop) => {
|
||||
const name = (args[0] ?? "").toLowerCase();
|
||||
// Persist the effort along with the preset change so a relaunch
|
||||
// doesn't revert to the previously-saved /effort value.
|
||||
const applyAndPersist = (effort: "high" | "max") => {
|
||||
try {
|
||||
saveReasoningEffort(effort);
|
||||
} catch {
|
||||
/* disk full / perms — runtime change still took effect */
|
||||
}
|
||||
};
|
||||
if (name === "fast" || name === "default") {
|
||||
loop.configure({
|
||||
model: "deepseek-v4-flash",
|
||||
reasoningEffort: "high",
|
||||
harvest: false,
|
||||
branch: 1,
|
||||
});
|
||||
applyAndPersist("high");
|
||||
return { info: "preset → fast (v4-flash · effort=high · cheapest)" };
|
||||
}
|
||||
if (name === "smart") {
|
||||
loop.configure({
|
||||
model: "deepseek-v4-flash",
|
||||
reasoningEffort: "max",
|
||||
harvest: false,
|
||||
branch: 1,
|
||||
});
|
||||
applyAndPersist("max");
|
||||
return { info: "preset → smart (v4-flash · effort=max · default · ~1.5× fast)" };
|
||||
}
|
||||
if (name === "max" || name === "best") {
|
||||
loop.configure({
|
||||
model: "deepseek-v4-pro",
|
||||
reasoningEffort: "max",
|
||||
harvest: false,
|
||||
branch: 1,
|
||||
});
|
||||
applyAndPersist("max");
|
||||
return {
|
||||
info: "preset → max (v4-pro · effort=max · ~12× fast · save for hard tasks, or use /pro for a single-turn bump)",
|
||||
};
|
||||
}
|
||||
return { info: "usage: /preset <fast|smart|max>" };
|
||||
};
|
||||
|
||||
const branch: SlashHandler = (args, loop) => {
|
||||
const raw = (args[0] ?? "").toLowerCase();
|
||||
if (raw === "" || raw === "off" || raw === "0" || raw === "1") {
|
||||
loop.configure({ branch: 1 });
|
||||
return { info: "branch → off" };
|
||||
}
|
||||
const n = Number.parseInt(raw, 10);
|
||||
if (!Number.isFinite(n) || n < 2) {
|
||||
return { info: "usage: /branch <N> (N>=2, or 'off')" };
|
||||
}
|
||||
if (n > 8) {
|
||||
return { info: "branch budget capped at 8 to prevent runaway cost" };
|
||||
}
|
||||
loop.configure({ branch: n });
|
||||
return {
|
||||
info: `branch → ${n} (runs ${n} parallel samples per turn · ${n}× per-turn cost · streaming disabled · manual only, no preset enables branching)`,
|
||||
};
|
||||
};
|
||||
|
||||
const effort: SlashHandler = (args, loop) => {
|
||||
const raw = (args[0] ?? "").toLowerCase();
|
||||
if (raw === "") {
|
||||
return {
|
||||
info: `reasoning_effort → ${loop.reasoningEffort} (use /effort high for cheaper/faster, /effort max for the agent-class default · persisted across relaunches)`,
|
||||
};
|
||||
}
|
||||
if (raw !== "high" && raw !== "max") {
|
||||
return { info: "usage: /effort <high|max>" };
|
||||
}
|
||||
loop.configure({ reasoningEffort: raw });
|
||||
// Persist so the next launch starts with this value instead of
|
||||
// reverting to the constructor default.
|
||||
try {
|
||||
saveReasoningEffort(raw);
|
||||
} catch {
|
||||
/* disk full / perms — runtime change still took effect */
|
||||
}
|
||||
return { info: `reasoning_effort → ${raw} (persisted)` };
|
||||
};
|
||||
|
||||
const pro: SlashHandler = (args, loop, ctx) => {
|
||||
const arg = (args[0] ?? "").toLowerCase();
|
||||
if (arg === "off" || arg === "cancel" || arg === "disarm") {
|
||||
if (!loop.proArmed) {
|
||||
return { info: "nothing armed — /pro with no args will arm pro for your next turn" };
|
||||
}
|
||||
if (ctx.disarmPro) ctx.disarmPro();
|
||||
else loop.disarmPro();
|
||||
return { info: "▸ /pro disarmed — next turn falls back to the current preset" };
|
||||
}
|
||||
if (arg && arg !== "on" && arg !== "arm") {
|
||||
return {
|
||||
info: "usage: /pro arm pro for the next turn (one-shot, auto-disarms after)\n /pro off cancel armed state before the next turn",
|
||||
};
|
||||
}
|
||||
if (ctx.armPro) ctx.armPro();
|
||||
else loop.armProForNextTurn();
|
||||
return {
|
||||
info: `▸ /pro armed — your NEXT message runs on ${ESCALATION_MODEL_ID} regardless of preset. Auto-disarms after one turn. Use /preset max for a persistent switch.`,
|
||||
};
|
||||
};
|
||||
|
||||
// Kept in sync with loop.ts ESCALATION_MODEL — hard-coding rather than
|
||||
// importing it because loop.ts already exports enough surface, and this
|
||||
// string is user-facing (description strings stay verbatim even if the
|
||||
// internal constant renames).
|
||||
const ESCALATION_MODEL_ID = "deepseek-v4-pro";
|
||||
|
||||
export const handlers: Record<string, SlashHandler> = {
|
||||
model,
|
||||
models,
|
||||
harvest,
|
||||
preset,
|
||||
branch,
|
||||
effort,
|
||||
pro,
|
||||
};
|
||||
@@ -0,0 +1,194 @@
|
||||
import { DEEPSEEK_CONTEXT_TOKENS, DEFAULT_CONTEXT_TOKENS } from "../../../../telemetry.js";
|
||||
import { countTokens } from "../../../../tokenizer.js";
|
||||
import type { SlashHandler } from "../dispatch.js";
|
||||
import { compactNum, formatToolList } from "../helpers.js";
|
||||
|
||||
const think: SlashHandler = (_args, loop) => {
|
||||
const raw = loop.scratch.reasoning;
|
||||
if (!raw || !raw.trim()) {
|
||||
return {
|
||||
info:
|
||||
"no reasoning cached. `/think` shows the full thinking-mode thought for the most recent " +
|
||||
"turn — only thinking-mode models (deepseek-v4-flash / -v4-pro / -reasoner) produce it, " +
|
||||
"and only once the turn completes.",
|
||||
};
|
||||
}
|
||||
return { info: `↳ full thinking (${raw.length} chars):\n\n${raw.trim()}` };
|
||||
};
|
||||
|
||||
const tool: SlashHandler = (args, _loop, ctx) => {
|
||||
// EventLog renders tool results as a one-line summary for display.
|
||||
// When the user wants to check what the model actually read (e.g.
|
||||
// to verify it isn't hallucinating a file's contents), they need
|
||||
// the full text. `/tool` is the escape hatch.
|
||||
const history = ctx.toolHistory?.() ?? [];
|
||||
if (history.length === 0) {
|
||||
return {
|
||||
info:
|
||||
"no tool calls yet in this session. `/tool` lists them once the model has actually " +
|
||||
"used a tool; `/tool N` dumps the full (untruncated) output of the Nth-most-recent.",
|
||||
};
|
||||
}
|
||||
const raw = (args[0] ?? "").toLowerCase();
|
||||
if (raw === "" || raw === "list" || raw === "ls") {
|
||||
return { info: formatToolList(history) };
|
||||
}
|
||||
const n = Number.parseInt(raw, 10);
|
||||
if (!Number.isFinite(n) || n < 1) {
|
||||
return {
|
||||
info: "usage: /tool [N] (no arg → list; N=1 → most recent result in full, N=2 → previous, …)",
|
||||
};
|
||||
}
|
||||
if (n > history.length) {
|
||||
return {
|
||||
info: `only ${history.length} tool call(s) in history — asked for #${n}. Try /tool with no arg to see the list.`,
|
||||
};
|
||||
}
|
||||
const entry = history[history.length - n];
|
||||
if (!entry) {
|
||||
return { info: `could not read tool call #${n}` };
|
||||
}
|
||||
return {
|
||||
info: `↳ tool<${entry.toolName}> #${n} (${entry.text.length} chars):\n\n${entry.text}`,
|
||||
};
|
||||
};
|
||||
|
||||
const context: SlashHandler = (_args, loop) => {
|
||||
// Measure each slice of the next request locally so the user can see
|
||||
// *where* context is being spent — a much more useful number than
|
||||
// the "last turn's total" the gauge shows. Tokenization is lazy so
|
||||
// the first /context call carries the data-file load cost (~100ms);
|
||||
// subsequent calls are pure compute.
|
||||
const systemTokens = countTokens(loop.prefix.system);
|
||||
const toolsTokens = countTokens(JSON.stringify(loop.prefix.toolSpecs));
|
||||
const entries = loop.log.toMessages();
|
||||
let userTokens = 0;
|
||||
let assistantTokens = 0;
|
||||
let toolResultTokens = 0;
|
||||
let toolCallTokens = 0;
|
||||
const toolBreakdown: Array<{ name: string; tokens: number; turn: number }> = [];
|
||||
let logTurn = 0;
|
||||
for (const e of entries) {
|
||||
const content = typeof e.content === "string" ? e.content : "";
|
||||
if (e.role === "user") {
|
||||
userTokens += countTokens(content);
|
||||
logTurn += 1;
|
||||
} else if (e.role === "assistant") {
|
||||
assistantTokens += countTokens(content);
|
||||
if (Array.isArray(e.tool_calls) && e.tool_calls.length > 0) {
|
||||
toolCallTokens += countTokens(JSON.stringify(e.tool_calls));
|
||||
}
|
||||
} else if (e.role === "tool") {
|
||||
const n = countTokens(content);
|
||||
toolResultTokens += n;
|
||||
toolBreakdown.push({ name: e.name ?? "?", tokens: n, turn: logTurn });
|
||||
}
|
||||
}
|
||||
const logTokens = userTokens + assistantTokens + toolResultTokens + toolCallTokens;
|
||||
const total = systemTokens + toolsTokens + logTokens;
|
||||
const ctxMax = DEEPSEEK_CONTEXT_TOKENS[loop.model] ?? DEFAULT_CONTEXT_TOKENS;
|
||||
const pct = (n: number) => (total > 0 ? `${Math.round((n / total) * 100)}%`.padStart(4) : " 0%");
|
||||
const row = (label: string, n: number, note = "") =>
|
||||
` ${label.padEnd(20)}${compactNum(n).padStart(8)} tokens ${pct(n)}${note ? ` ${note}` : ""}`;
|
||||
|
||||
const lines = [
|
||||
`Next-request estimate: ~${compactNum(total)} tokens of ${compactNum(ctxMax)} (${Math.round(
|
||||
(total / ctxMax) * 100,
|
||||
)}% of window)`,
|
||||
"",
|
||||
row("system prompt", systemTokens),
|
||||
row("tool specs", toolsTokens, `(${loop.prefix.toolSpecs.length} tools)`),
|
||||
row("log (all turns)", logTokens, `(${entries.length} messages)`),
|
||||
` user ${compactNum(userTokens).padStart(8)} tokens`,
|
||||
` assistant ${compactNum(assistantTokens).padStart(8)} tokens`,
|
||||
` tool-call args ${compactNum(toolCallTokens).padStart(8)} tokens`,
|
||||
` tool results ${compactNum(toolResultTokens).padStart(8)} tokens`,
|
||||
];
|
||||
|
||||
// Top 5 heaviest tool results — usually where unexpected bloat
|
||||
// lives (a big read_file, an unfiltered search_content).
|
||||
if (toolBreakdown.length > 0) {
|
||||
const top = [...toolBreakdown].sort((a, b) => b.tokens - a.tokens).slice(0, 5);
|
||||
lines.push("");
|
||||
lines.push(`Top tool results by cost (of ${toolBreakdown.length} total):`);
|
||||
for (const t of top) {
|
||||
lines.push(
|
||||
` turn ${String(t.turn).padStart(3)} ${t.name.padEnd(22)} ${compactNum(t.tokens).padStart(8)} tokens`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
lines.push("");
|
||||
lines.push(
|
||||
"Count is a local estimate (DeepSeek V3 tokenizer, pure-TS port); server prompt_tokens may add ~3-6% for chat-template role markers.",
|
||||
);
|
||||
return { info: lines.join("\n") };
|
||||
};
|
||||
|
||||
const status: SlashHandler = (_args, loop, ctx) => {
|
||||
const branchBudget = loop.branchOptions.budget ?? 1;
|
||||
const ctxMax = DEEPSEEK_CONTEXT_TOKENS[loop.model] ?? DEFAULT_CONTEXT_TOKENS;
|
||||
const lastPromptTokens = loop.stats.summary().lastPromptTokens;
|
||||
const ctxPct = ctxMax > 0 ? Math.round((lastPromptTokens / ctxMax) * 100) : 0;
|
||||
const ctxLine =
|
||||
lastPromptTokens > 0
|
||||
? ` ctx ${compactNum(lastPromptTokens)}/${compactNum(ctxMax)} (${ctxPct}%)`
|
||||
: " ctx no turns yet";
|
||||
const pending = ctx.pendingEditCount ?? 0;
|
||||
const sessionLine = loop.sessionName
|
||||
? ` session "${loop.sessionName}" · ${loop.log.length} messages in log (resumed ${loop.resumedMessageCount})`
|
||||
: " session (ephemeral — no persistence)";
|
||||
const mcpCount = ctx.mcpSpecs?.length ?? 0;
|
||||
const toolCount = loop.prefix.toolSpecs.length;
|
||||
const mcpLine = ` mcp ${mcpCount} server(s), ${toolCount} tool(s) in registry`;
|
||||
const pendingLine =
|
||||
pending > 0 ? ` edits ${pending} pending (/apply to commit, /discard to drop)` : "";
|
||||
const planLine = ctx.planMode ? " plan ON — writes gated (submit_plan + approval)" : "";
|
||||
const modeLine =
|
||||
ctx.editMode === "yolo"
|
||||
? " mode YOLO — edits + shell auto-run with no prompt (/undo still rolls back · Shift+Tab to flip)"
|
||||
: ctx.editMode === "auto"
|
||||
? " mode AUTO — edits apply immediately (u to undo within 5s · Shift+Tab to flip)"
|
||||
: ctx.editMode === "review"
|
||||
? " mode review — edits queue for /apply or y (Shift+Tab to flip)"
|
||||
: "";
|
||||
const lines = [
|
||||
` model ${loop.model}`,
|
||||
` flags harvest=${loop.harvestEnabled ? "on" : "off"} · branch=${branchBudget > 1 ? branchBudget : "off"} · stream=${loop.stream ? "on" : "off"} · effort=${loop.reasoningEffort}`,
|
||||
ctxLine,
|
||||
mcpLine,
|
||||
sessionLine,
|
||||
];
|
||||
if (pendingLine) lines.push(pendingLine);
|
||||
if (planLine) lines.push(planLine);
|
||||
if (modeLine) lines.push(modeLine);
|
||||
return { info: lines.join("\n") };
|
||||
};
|
||||
|
||||
const compact: SlashHandler = (args, loop) => {
|
||||
// Manual companion to the automatic 60%/80% auto-compact. Re-applies
|
||||
// token-aware truncation with a tighter cap (default 4000 tokens per
|
||||
// tool result) and rewrites the session file so the shrink persists.
|
||||
// Useful when the ctx gauge in StatsPanel goes yellow/red mid-session
|
||||
// and the user wants to keep chatting without /forget'ing everything.
|
||||
const tight = Number.parseInt(args[0] ?? "", 10);
|
||||
const cap = Number.isFinite(tight) && tight >= 100 ? tight : 4000;
|
||||
const { healedCount, tokensSaved, charsSaved } = loop.compact(cap);
|
||||
if (healedCount === 0) {
|
||||
return {
|
||||
info: `▸ nothing to compact — no tool result or tool-call args in history exceed ${cap.toLocaleString()} tokens.`,
|
||||
};
|
||||
}
|
||||
return {
|
||||
info: `▸ compacted ${healedCount} payload(s) to ${cap.toLocaleString()} tokens each (tool results + tool-call args), saved ${tokensSaved.toLocaleString()} tokens (${charsSaved.toLocaleString()} chars). Session file rewritten.`,
|
||||
};
|
||||
};
|
||||
|
||||
export const handlers: Record<string, SlashHandler> = {
|
||||
think,
|
||||
reasoning: think,
|
||||
tool,
|
||||
context,
|
||||
status,
|
||||
compact,
|
||||
};
|
||||
@@ -0,0 +1,196 @@
|
||||
import {
|
||||
addProjectShellAllowed,
|
||||
clearProjectShellAllowed,
|
||||
loadProjectShellAllowed,
|
||||
removeProjectShellAllowed,
|
||||
} from "../../../../config.js";
|
||||
import { BUILTIN_ALLOWLIST } from "../../../../tools/shell.js";
|
||||
import type { SlashHandler } from "../dispatch.js";
|
||||
|
||||
/**
|
||||
* `/permissions` family. Mirrors /memory's shape — bare lists state,
|
||||
* subcommands manage it. Two layers exist:
|
||||
*
|
||||
* 1. Builtin allowlist — baked into shell.ts (`BUILTIN_ALLOWLIST`),
|
||||
* always on. Read-only here.
|
||||
* 2. Per-project allowlist — `~/.reasonix/config.json`, populated by
|
||||
* "always allow" picks on ShellConfirm. Add / remove / clear here.
|
||||
*
|
||||
* Edit-mode (review / auto / yolo) is also surfaced at the top so users
|
||||
* see "yolo skips all of this" without having to re-derive it from /mode.
|
||||
*
|
||||
* Subcommands:
|
||||
* add <prefix...> — append a prefix (multi-token OK: "git push origin")
|
||||
* remove <prefix|N> — drop by exact prefix or 1-based project index
|
||||
* clear confirm — wipe every project entry (typed literal "confirm")
|
||||
*/
|
||||
const permissions: SlashHandler = (args, _loop, ctx) => {
|
||||
const sub = (args[0] ?? "").toLowerCase();
|
||||
const root = ctx.codeRoot;
|
||||
const mode = ctx.editMode ?? null;
|
||||
|
||||
// Bare → status + listing.
|
||||
if (sub === "" || sub === "list" || sub === "ls") {
|
||||
return { info: renderListing(root, mode) };
|
||||
}
|
||||
|
||||
// Mutating subcommands need a code-mode root.
|
||||
if (!root) {
|
||||
return {
|
||||
info: "/permissions add / remove / clear are only available inside `reasonix code` — they edit the project-scoped allowlist (`~/.reasonix/config.json` projects[<root>].shellAllowed).",
|
||||
};
|
||||
}
|
||||
|
||||
if (sub === "add") {
|
||||
const prefix = args.slice(1).join(" ").trim();
|
||||
if (!prefix) {
|
||||
return {
|
||||
info: 'usage: /permissions add <prefix> (multi-token OK: /permissions add "git push origin")',
|
||||
};
|
||||
}
|
||||
const before = loadProjectShellAllowed(root);
|
||||
if (before.includes(prefix)) {
|
||||
return { info: `▸ already allowed: ${prefix}` };
|
||||
}
|
||||
if (BUILTIN_ALLOWLIST.includes(prefix)) {
|
||||
return {
|
||||
info: `▸ \`${prefix}\` is already in the builtin allowlist — no per-project entry needed. (Builtin entries are always on.)`,
|
||||
};
|
||||
}
|
||||
addProjectShellAllowed(root, prefix);
|
||||
return {
|
||||
info: `▸ added: ${prefix}\n → next \`${prefix}\` invocation runs without prompting in this project.`,
|
||||
};
|
||||
}
|
||||
|
||||
if (sub === "remove" || sub === "rm" || sub === "delete") {
|
||||
const target = args.slice(1).join(" ").trim();
|
||||
if (!target) {
|
||||
return {
|
||||
info: "usage: /permissions remove <prefix-or-index> (e.g. /permissions remove 3, or /permissions remove npm)",
|
||||
};
|
||||
}
|
||||
const existing = loadProjectShellAllowed(root);
|
||||
let prefix: string | null = null;
|
||||
// Index form: "/permissions remove 3" → 1-based project index.
|
||||
if (/^\d+$/.test(target)) {
|
||||
const idx = Number.parseInt(target, 10);
|
||||
if (idx < 1 || idx > existing.length) {
|
||||
return {
|
||||
info:
|
||||
existing.length === 0
|
||||
? "▸ no project allowlist entries to remove."
|
||||
: `▸ index out of range: ${idx} (project list has ${existing.length} entries)`,
|
||||
};
|
||||
}
|
||||
prefix = existing[idx - 1] ?? null;
|
||||
} else {
|
||||
prefix = target;
|
||||
}
|
||||
if (prefix === null) return { info: "▸ nothing to remove." };
|
||||
// Builtin entries can't be touched — surface that explicitly.
|
||||
if (BUILTIN_ALLOWLIST.includes(prefix) && !existing.includes(prefix)) {
|
||||
return {
|
||||
info: `▸ \`${prefix}\` is in the builtin allowlist (read-only). Builtin entries can't be removed at runtime — they're baked into the binary.`,
|
||||
};
|
||||
}
|
||||
const ok = removeProjectShellAllowed(root, prefix);
|
||||
return {
|
||||
info: ok
|
||||
? `▸ removed: ${prefix}`
|
||||
: `▸ no such project entry: ${prefix} (try /permissions list to see what's stored)`,
|
||||
};
|
||||
}
|
||||
|
||||
if (sub === "clear") {
|
||||
if ((args[1] ?? "").toLowerCase() !== "confirm") {
|
||||
const count = loadProjectShellAllowed(root).length;
|
||||
return {
|
||||
info:
|
||||
count === 0
|
||||
? "▸ project allowlist is already empty."
|
||||
: `about to drop ${count} project allowlist entr${count === 1 ? "y" : "ies"} for ${root}. Re-run with the word 'confirm' to proceed: /permissions clear confirm`,
|
||||
};
|
||||
}
|
||||
const dropped = clearProjectShellAllowed(root);
|
||||
return {
|
||||
info:
|
||||
dropped === 0
|
||||
? "▸ project allowlist was already empty — nothing changed."
|
||||
: `▸ cleared ${dropped} project allowlist entr${dropped === 1 ? "y" : "ies"}.`,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
info: [
|
||||
"usage: /permissions [list] show current state",
|
||||
' /permissions add <prefix> persist (e.g. "npm run build")',
|
||||
" /permissions remove <prefix-or-N> drop one entry",
|
||||
" /permissions clear confirm wipe every project entry",
|
||||
].join("\n"),
|
||||
};
|
||||
};
|
||||
|
||||
function renderListing(root: string | undefined, mode: string | null): string {
|
||||
const lines: string[] = [];
|
||||
// Mode banner — edit-gate is the dial that decides whether the
|
||||
// allowlist matters for the next call.
|
||||
if (mode === "yolo") {
|
||||
lines.push(
|
||||
"▸ edit mode: YOLO — every shell command auto-runs, allowlist is bypassed. /mode review to re-enable prompts.",
|
||||
);
|
||||
} else if (mode === "auto") {
|
||||
lines.push(
|
||||
"▸ edit mode: auto — edits auto-apply, shell still gated by allowlist (or ShellConfirm prompt for non-allowlisted).",
|
||||
);
|
||||
} else if (mode === "review") {
|
||||
lines.push(
|
||||
"▸ edit mode: review — both edits and non-allowlisted shell commands ask before running.",
|
||||
);
|
||||
}
|
||||
lines.push("");
|
||||
|
||||
// Project list.
|
||||
if (root) {
|
||||
const project = loadProjectShellAllowed(root);
|
||||
lines.push(`Project allowlist (${project.length}) — ${root}`);
|
||||
if (project.length === 0) {
|
||||
lines.push(' (none — pick "always allow" on a ShellConfirm prompt to add one,');
|
||||
lines.push(" or `/permissions add <prefix>` directly.)");
|
||||
} else {
|
||||
project.forEach((p, i) => {
|
||||
lines.push(` ${String(i + 1).padStart(2)}. ${p}`);
|
||||
});
|
||||
}
|
||||
} else {
|
||||
lines.push("Project allowlist — (no project root; chat mode shows builtin entries only)");
|
||||
}
|
||||
lines.push("");
|
||||
|
||||
// Builtin list — grouped by leading verb so 40 lines stay scannable.
|
||||
lines.push(`Builtin allowlist (${BUILTIN_ALLOWLIST.length}) — read-only, baked in`);
|
||||
const grouped = new Map<string, string[]>();
|
||||
for (const entry of BUILTIN_ALLOWLIST) {
|
||||
const head = entry.split(" ")[0] ?? entry;
|
||||
if (!grouped.has(head)) grouped.set(head, []);
|
||||
grouped.get(head)!.push(entry);
|
||||
}
|
||||
for (const [head, items] of grouped) {
|
||||
if (items.length === 1 && items[0] === head) {
|
||||
lines.push(` · ${head}`);
|
||||
} else {
|
||||
const tail = items.map((i) => i.slice(head.length).trim() || "(bare)").join(", ");
|
||||
lines.push(` · ${head}: ${tail}`);
|
||||
}
|
||||
}
|
||||
lines.push("");
|
||||
lines.push(
|
||||
"Subcommands: /permissions add <prefix> · /permissions remove <prefix-or-N> · /permissions clear confirm",
|
||||
);
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
export const handlers: Record<string, SlashHandler> = {
|
||||
permissions,
|
||||
perms: permissions,
|
||||
};
|
||||
@@ -0,0 +1,111 @@
|
||||
/**
|
||||
* `/plans` — show this session's plan history. Both the live in-flight
|
||||
* plan (if any) and the archive of completed `.done.json` files. Local
|
||||
* to the current session by design — a plan lives with its project,
|
||||
* and resuming one just means cd'ing back to that project directory.
|
||||
*/
|
||||
|
||||
import { basename } from "node:path";
|
||||
import { listPlanArchives, loadPlanState, relativeTime } from "../../../../code/plan-store.js";
|
||||
import type { SlashHandler } from "../dispatch.js";
|
||||
|
||||
const plans: SlashHandler = (_args, loop) => {
|
||||
const sessionName = loop.sessionName;
|
||||
if (!sessionName) {
|
||||
return {
|
||||
info: "no session attached — `/plans` is per-session. Run `reasonix code` in a project to get a session.",
|
||||
};
|
||||
}
|
||||
const lines: string[] = [];
|
||||
// Active (in-flight) plan summary first — it's the one the user is
|
||||
// most likely asking about.
|
||||
const active = loadPlanState(sessionName);
|
||||
if (active && active.steps.length > 0) {
|
||||
const total = active.steps.length;
|
||||
const done = active.completedStepIds.length;
|
||||
const when = relativeTime(active.updatedAt);
|
||||
const label = active.summary ? `: ${active.summary}` : "";
|
||||
lines.push(
|
||||
`▸ active plan${label} — ${done}/${total} step${total === 1 ? "" : "s"} done · last touched ${when}`,
|
||||
);
|
||||
} else {
|
||||
lines.push("▸ active plan: (none)");
|
||||
}
|
||||
|
||||
// Archives (completed plans) — newest first.
|
||||
const archives = listPlanArchives(sessionName);
|
||||
if (archives.length === 0) {
|
||||
lines.push("");
|
||||
lines.push(
|
||||
"no archived plans yet for this session — they auto-archive when every step is done",
|
||||
);
|
||||
return { info: lines.join("\n") };
|
||||
}
|
||||
lines.push("");
|
||||
lines.push(`Archived (${archives.length}):`);
|
||||
for (const a of archives) {
|
||||
const when = relativeTime(a.completedAt);
|
||||
const total = a.steps.length;
|
||||
const done = a.completedStepIds.length;
|
||||
const completion = done >= total ? "complete" : `${done}/${total}`;
|
||||
// Prefer the model-supplied summary as the label; fall back to
|
||||
// the bare filename so legacy archives without a summary still
|
||||
// show something identifying.
|
||||
const label = a.summary ?? a.path.split(/[\\/]/).pop() ?? a.path;
|
||||
lines.push(
|
||||
` ✓ ${when.padEnd(10)} ${total} step${total === 1 ? "" : "s"} · ${completion} ${label}`,
|
||||
);
|
||||
}
|
||||
return { info: lines.join("\n") };
|
||||
};
|
||||
|
||||
/**
|
||||
* `/replay [N]` — Time Travel. Loads archive #N (1-based, newest
|
||||
* first; defaults to 1) and asks the TUI to render it as a read-only
|
||||
* snapshot. Pure display — no execution, no plan state changes.
|
||||
*
|
||||
* The structured payload (steps + completedStepIds + body + summary)
|
||||
* goes back through SlashResult.replayPlan so EventLog can apply the
|
||||
* same step-list rendering used elsewhere, complete with risk gutter
|
||||
* and ✓ status.
|
||||
*/
|
||||
const replay: SlashHandler = (args, loop) => {
|
||||
const sessionName = loop.sessionName;
|
||||
if (!sessionName) {
|
||||
return {
|
||||
info: "no session attached — `/replay` is per-session. Run `reasonix code` in a project to get a session.",
|
||||
};
|
||||
}
|
||||
const archives = listPlanArchives(sessionName);
|
||||
if (archives.length === 0) {
|
||||
return {
|
||||
info: "no archived plans yet for this session — `/replay` lights up once a plan completes (auto-archives when every step is done).",
|
||||
};
|
||||
}
|
||||
const arg = args[0]?.trim() ?? "";
|
||||
const index = arg ? Number.parseInt(arg, 10) : 1;
|
||||
if (!Number.isFinite(index) || index < 1 || index > archives.length) {
|
||||
return {
|
||||
info: `invalid index — \`/replay\` takes 1..${archives.length} (newest = 1). Use \`/plans\` to see the list.`,
|
||||
};
|
||||
}
|
||||
const a = archives[index - 1]!;
|
||||
return {
|
||||
replayPlan: {
|
||||
summary: a.summary,
|
||||
body: a.body,
|
||||
steps: a.steps,
|
||||
completedStepIds: a.completedStepIds,
|
||||
completedAt: a.completedAt,
|
||||
relativeTime: relativeTime(a.completedAt),
|
||||
archiveBasename: basename(a.path),
|
||||
index,
|
||||
total: archives.length,
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
export const handlers: Record<string, SlashHandler> = {
|
||||
plans,
|
||||
replay,
|
||||
};
|
||||
@@ -0,0 +1,133 @@
|
||||
/**
|
||||
* `/semantic` slash — show whether semantic_search is set up for
|
||||
* this project, and what to run if not.
|
||||
*
|
||||
* Behavior is purely informational. The actual setup happens via
|
||||
* `reasonix index` in the user's shell — same pattern `/setup` and
|
||||
* `/update` use. Doing the install / build inline would mean
|
||||
* suspending Ink and bringing it back, which is fragile (especially
|
||||
* the ANSI-cursor-up paths Windows shells already mishandle).
|
||||
*
|
||||
* All user-facing strings come from the i18n table so Chinese-locale
|
||||
* users see Chinese; everyone else gets English.
|
||||
*/
|
||||
|
||||
import { promises as fs } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { probeOllama } from "../../../../index/semantic/embedding.js";
|
||||
import { t } from "../../../../index/semantic/i18n.js";
|
||||
import { findOllamaBinary } from "../../../../index/semantic/ollama-launcher.js";
|
||||
import type { SlashHandler } from "../dispatch.js";
|
||||
|
||||
const semantic: SlashHandler = (_args, _loop, ctx) => {
|
||||
const root = ctx.codeRoot;
|
||||
if (!root) {
|
||||
return {
|
||||
info: "/semantic is only available inside `reasonix code` (needs a project root).",
|
||||
};
|
||||
}
|
||||
// Fire-and-forget: probes (file stat, optional Ollama HTTP) take
|
||||
// ~50–200ms which is too long to block the prompt. Same pattern
|
||||
// /kill uses — return a placeholder, post the rich result through
|
||||
// ctx.postInfo when ready. ctx.postInfo is wired by the TUI when
|
||||
// it owns historical rendering.
|
||||
void (async () => {
|
||||
const status = await renderSemanticStatus(root);
|
||||
ctx.postInfo?.(status);
|
||||
})();
|
||||
return { info: "▸ checking semantic_search status…" };
|
||||
};
|
||||
|
||||
/**
|
||||
* Async status renderer. The slash returns a synchronous
|
||||
* "fetching…" placeholder, then this function — invoked via
|
||||
* ctx.postInfo from the slash dispatcher wrapper — posts the real
|
||||
* status when probes finish. Keeps the slash handler signature sync
|
||||
* (the established pattern across the codebase).
|
||||
*
|
||||
* Exposed separately so tests can call it without faking the slash
|
||||
* machinery.
|
||||
*/
|
||||
export async function renderSemanticStatus(rootDir: string): Promise<string> {
|
||||
const lines: string[] = [t("slashHeader"), ""];
|
||||
const indexExists = await indexFileExists(rootDir);
|
||||
if (indexExists) {
|
||||
const meta = await readIndexMeta(rootDir);
|
||||
lines.push(t("slashEnabled"));
|
||||
if (meta) {
|
||||
lines.push(
|
||||
t("slashEnabledDetail", {
|
||||
chunks: meta.chunks,
|
||||
files: meta.files,
|
||||
}),
|
||||
);
|
||||
}
|
||||
lines.push(t("slashEnabledHowto"));
|
||||
return lines.join("\n");
|
||||
}
|
||||
// Not built yet. Walk the prerequisites in priority order.
|
||||
lines.push(t("slashIndexMissing"));
|
||||
lines.push(t("slashIndexInfo"));
|
||||
lines.push("");
|
||||
if (findOllamaBinary() === null) {
|
||||
lines.push(t("slashOllamaMissing"));
|
||||
} else {
|
||||
const probe = await probeOllama();
|
||||
if (!probe.ok) lines.push(t("slashDaemonDown"));
|
||||
}
|
||||
lines.push(t("slashHowToBuild"));
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
async function indexFileExists(rootDir: string): Promise<boolean> {
|
||||
try {
|
||||
await fs.access(path.join(rootDir, ".reasonix", "semantic", "index.meta.json"));
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
interface IndexSummary {
|
||||
chunks: number;
|
||||
files: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cheap summary of the index for the `/semantic` status panel.
|
||||
* Counts JSONL lines (each = one chunk) and unique paths via a Set.
|
||||
* For typical projects (<10k chunks) this is well under 50ms; for
|
||||
* very large repos we cap reads at 10MB to keep `/semantic` snappy.
|
||||
*/
|
||||
async function readIndexMeta(rootDir: string): Promise<IndexSummary | null> {
|
||||
const dataPath = path.join(rootDir, ".reasonix", "semantic", "index.jsonl");
|
||||
try {
|
||||
const stat = await fs.stat(dataPath);
|
||||
if (stat.size > 10 * 1024 * 1024) {
|
||||
// For huge indexes, give an order-of-magnitude estimate from
|
||||
// file size (avg ~500 bytes/chunk in practice). Files won't
|
||||
// be available, so we report just the chunk approximation.
|
||||
return { chunks: Math.round(stat.size / 500), files: 0 };
|
||||
}
|
||||
const raw = await fs.readFile(dataPath, "utf8");
|
||||
const seenPaths = new Set<string>();
|
||||
let chunks = 0;
|
||||
for (const line of raw.split("\n")) {
|
||||
if (line.length === 0) continue;
|
||||
chunks++;
|
||||
try {
|
||||
const parsed = JSON.parse(line) as { p?: string };
|
||||
if (parsed.p) seenPaths.add(parsed.p);
|
||||
} catch {
|
||||
/* tolerated — store rebuilds drop bad lines */
|
||||
}
|
||||
}
|
||||
return { chunks, files: seenPaths.size };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export const handlers: Record<string, SlashHandler> = {
|
||||
semantic,
|
||||
};
|
||||
@@ -0,0 +1,41 @@
|
||||
import { deleteSession, listSessions } from "../../../../session.js";
|
||||
import type { SlashHandler } from "../dispatch.js";
|
||||
|
||||
const sessions: SlashHandler = (_args, loop) => {
|
||||
const items = listSessions();
|
||||
if (items.length === 0) {
|
||||
return {
|
||||
info: "no saved sessions yet — chat normally and your messages will be saved automatically",
|
||||
};
|
||||
}
|
||||
const lines = ["Saved sessions:"];
|
||||
for (const s of items) {
|
||||
const sizeKb = (s.size / 1024).toFixed(1);
|
||||
const when = s.mtime.toISOString().replace("T", " ").slice(0, 16);
|
||||
const marker = s.name === loop.sessionName ? "▸" : " ";
|
||||
lines.push(
|
||||
` ${marker} ${s.name.padEnd(22)} ${String(s.messageCount).padStart(5)} msgs ${sizeKb.padStart(7)} KB ${when}`,
|
||||
);
|
||||
}
|
||||
lines.push("");
|
||||
lines.push("Resume with: reasonix chat --session <name>");
|
||||
return { info: lines.join("\n") };
|
||||
};
|
||||
|
||||
const forget: SlashHandler = (_args, loop) => {
|
||||
if (!loop.sessionName) {
|
||||
return { info: "not in a session — nothing to forget" };
|
||||
}
|
||||
const name = loop.sessionName;
|
||||
const ok = deleteSession(name);
|
||||
return {
|
||||
info: ok
|
||||
? `▸ deleted session "${name}" — current screen still shows the conversation, but next launch starts fresh`
|
||||
: `could not delete session "${name}" (already gone?)`,
|
||||
};
|
||||
};
|
||||
|
||||
export const handlers: Record<string, SlashHandler> = {
|
||||
sessions,
|
||||
forget,
|
||||
};
|
||||
@@ -0,0 +1,94 @@
|
||||
import { SkillStore } from "../../../../skills.js";
|
||||
import type { SlashHandler } from "../dispatch.js";
|
||||
|
||||
/**
|
||||
* `/skill` family. Bare `/skill` (or `/skill list`) prints the
|
||||
* discovered skills from `<projectRoot>/.reasonix/skills` (code mode
|
||||
* only) + `~/.reasonix/skills`. `/skill show <name>` dumps one body
|
||||
* inline for reading. `/skill <name> [args...]` injects the skill body
|
||||
* as a user turn via `resubmit` — the same mechanism `/apply-plan`
|
||||
* uses — so the next model turn runs with the skill's instructions
|
||||
* fresh in the log.
|
||||
*
|
||||
* Project scope is only populated when the session has a `codeRoot`
|
||||
* (set by `reasonix code`). In plain chat mode the store reads the
|
||||
* global scope only, matching how user-memory behaves.
|
||||
*/
|
||||
const skill: SlashHandler = (args, _loop, ctx) => {
|
||||
const store = new SkillStore({ projectRoot: ctx.codeRoot });
|
||||
const sub = (args[0] ?? "").toLowerCase();
|
||||
|
||||
if (sub === "" || sub === "list" || sub === "ls") {
|
||||
const skills = store.list();
|
||||
if (skills.length === 0) {
|
||||
const lines = ["no skills found. Reasonix reads skills from:"];
|
||||
if (store.hasProjectScope()) {
|
||||
lines.push(
|
||||
" · <project>/.reasonix/skills/<name>/SKILL.md (or <name>.md) — project scope",
|
||||
);
|
||||
}
|
||||
lines.push(" · ~/.reasonix/skills/<name>/SKILL.md (or <name>.md) — global scope");
|
||||
if (!store.hasProjectScope()) {
|
||||
lines.push(" (project scope is only active in `reasonix code`)");
|
||||
}
|
||||
lines.push(
|
||||
"",
|
||||
"Each file's frontmatter needs at least `name` and `description`.",
|
||||
"Invoke a skill with `/skill <name> [args]` or by asking the model to call `run_skill`.",
|
||||
);
|
||||
return { info: lines.join("\n") };
|
||||
}
|
||||
const lines = [`User skills (${skills.length}):`];
|
||||
for (const s of skills) {
|
||||
const scope = `(${s.scope})`.padEnd(11);
|
||||
const name = s.name.padEnd(24);
|
||||
const desc = s.description.length > 70 ? `${s.description.slice(0, 69)}…` : s.description;
|
||||
lines.push(` ${scope} ${name} ${desc}`);
|
||||
}
|
||||
lines.push("");
|
||||
lines.push("View body: /skill show <name> Run: /skill <name> [args]");
|
||||
return { info: lines.join("\n") };
|
||||
}
|
||||
|
||||
if (sub === "show" || sub === "cat") {
|
||||
const target = args[1];
|
||||
if (!target) return { info: "usage: /skill show <name>" };
|
||||
const found = store.read(target);
|
||||
if (!found) return { info: `no skill found: ${target}` };
|
||||
return {
|
||||
info: [
|
||||
`▸ ${found.name} (${found.scope})`,
|
||||
found.description ? ` ${found.description}` : "",
|
||||
` ${found.path}`,
|
||||
"",
|
||||
found.body,
|
||||
]
|
||||
.filter((l) => l !== "")
|
||||
.join("\n"),
|
||||
};
|
||||
}
|
||||
|
||||
// Bare `/skill <name> [args...]` — inject the body as a user turn.
|
||||
// The first arg is the skill name; remaining args are forwarded
|
||||
// verbatim as the skill's "Arguments:" line.
|
||||
const name = args[0] ?? "";
|
||||
const found = store.read(name);
|
||||
if (!found) {
|
||||
return {
|
||||
info: `no skill found: ${name} (try /skill list)`,
|
||||
};
|
||||
}
|
||||
const extra = args.slice(1).join(" ").trim();
|
||||
const header = `# Skill: ${found.name}${found.description ? `\n> ${found.description}` : ""}`;
|
||||
const argsLine = extra ? `\n\nArguments: ${extra}` : "";
|
||||
const payload = `${header}\n\n${found.body}${argsLine}`;
|
||||
return {
|
||||
info: `▸ running skill: ${found.name}${extra ? ` — ${extra}` : ""}`,
|
||||
resubmit: payload,
|
||||
};
|
||||
};
|
||||
|
||||
export const handlers: Record<string, SlashHandler> = {
|
||||
skill,
|
||||
skills: skill,
|
||||
};
|
||||
@@ -0,0 +1,145 @@
|
||||
import { spawnSync } from "node:child_process";
|
||||
import type { MemoryScope, MemoryStore } from "../../../user-memory.js";
|
||||
import type { SlashResult } from "./types.js";
|
||||
|
||||
/**
|
||||
* Parse a `/memory show|forget` argument. Accepts bare `<name>` or
|
||||
* `<scope>/<name>`. For bare names, tries project scope first (more
|
||||
* specific, usually what the user means) then falls back to global.
|
||||
*/
|
||||
export function resolveMemoryTarget(
|
||||
store: MemoryStore,
|
||||
raw: string,
|
||||
): { scope: MemoryScope; name: string } | null {
|
||||
const slash = raw.indexOf("/");
|
||||
if (slash > 0) {
|
||||
const scopeRaw = raw.slice(0, slash).toLowerCase();
|
||||
const name = raw.slice(slash + 1);
|
||||
if (scopeRaw !== "global" && scopeRaw !== "project") return null;
|
||||
const scope = scopeRaw as MemoryScope;
|
||||
if (scope === "project" && !store.hasProjectScope()) return null;
|
||||
return { scope, name };
|
||||
}
|
||||
for (const scope of ["project", "global"] as MemoryScope[]) {
|
||||
if (scope === "project" && !store.hasProjectScope()) continue;
|
||||
try {
|
||||
store.read(scope, raw);
|
||||
return { scope, name: raw };
|
||||
} catch {
|
||||
/* next scope */
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Render a section (resources / prompts) of an MCP inspection into a
|
||||
* compact "name count items" form, collapsing when unsupported.
|
||||
* Names-only — descriptions and full metadata live in
|
||||
* `reasonix mcp inspect`, which is purpose-built for the deep view.
|
||||
*/
|
||||
export function appendSection(
|
||||
lines: string[],
|
||||
label: string,
|
||||
section:
|
||||
| { supported: true; items: Array<{ name: string }> }
|
||||
| { supported: false; reason: string }
|
||||
| undefined,
|
||||
): void {
|
||||
if (!section || !section.supported) {
|
||||
lines.push(
|
||||
` ${label.trim()} ${section?.supported === false ? "(not supported)" : "(none)"}`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
const names = section.items.map((i) => i.name);
|
||||
if (names.length === 0) {
|
||||
lines.push(` ${label.trim()} (none)`);
|
||||
return;
|
||||
}
|
||||
const head = names.slice(0, 5).join(", ");
|
||||
const more = names.length > 5 ? ` +${names.length - 5} more` : "";
|
||||
lines.push(` ${label.trim()} ${names.length} [${head}${more}]`);
|
||||
}
|
||||
|
||||
export function formatToolList(history: Array<{ toolName: string; text: string }>): string {
|
||||
const total = history.length;
|
||||
const header = `Tool calls in this session (${total}, most recent first):`;
|
||||
// Show the 10 most recent. Older ones are rarely what the user
|
||||
// wants — and the help footer tells them how to reach any entry
|
||||
// by index if they do.
|
||||
const shown = Math.min(total, 10);
|
||||
const lines: string[] = [header];
|
||||
for (let i = 0; i < shown; i++) {
|
||||
const entry = history[total - 1 - i];
|
||||
if (!entry) continue;
|
||||
const idx = i + 1; // 1-based from most recent
|
||||
const flat = entry.text.replace(/\s+/g, " ").trim();
|
||||
const preview = flat.length > 80 ? `${flat.slice(0, 80)}…` : flat;
|
||||
const name = entry.toolName.length > 24 ? `${entry.toolName.slice(0, 23)}…` : entry.toolName;
|
||||
lines.push(
|
||||
` #${String(idx).padStart(2)} ${name.padEnd(24)} ${String(entry.text.length).padStart(6)} chars ${preview}`,
|
||||
);
|
||||
}
|
||||
if (total > shown) {
|
||||
lines.push(` … (${total - shown} earlier, reach with /tool N)`);
|
||||
}
|
||||
lines.push("");
|
||||
lines.push("View full output: /tool N (N=1 → most recent)");
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* Binary-K token formatter: 1234 → "1.2K", 131072 → "128K". Matches
|
||||
* DeepSeek's doc ("128K context"). Every call site here is rendering
|
||||
* token counts — if a future caller wants decimal-K for dollars or
|
||||
* similar, add a separate formatter rather than reusing this one.
|
||||
*/
|
||||
export function compactNum(n: number): string {
|
||||
if (n < 1024) return String(n);
|
||||
const k = n / 1024;
|
||||
return k >= 100 ? `${Math.round(k)}K` : `${k.toFixed(1)}K`;
|
||||
}
|
||||
|
||||
export function stripOuterQuotes(s: string): string {
|
||||
if (s.length >= 2 && s.startsWith('"') && s.endsWith('"')) {
|
||||
return s.slice(1, -1);
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
/**
|
||||
* Run `git add -A` then `git commit -m <message>` in `rootDir`. Returns
|
||||
* a SlashResult with a human-scannable info line. We surface stderr on
|
||||
* failure so the user sees exactly what git complained about (bad
|
||||
* config, pre-commit hook rejection, nothing staged, etc.).
|
||||
*/
|
||||
export function runGitCommit(rootDir: string, message: string): SlashResult {
|
||||
const add = spawnSync("git", ["add", "-A"], { cwd: rootDir, encoding: "utf8" });
|
||||
if (add.error || add.status !== 0) {
|
||||
return { info: `git add failed (${add.status ?? "?"}):\n${gitTail(add)}` };
|
||||
}
|
||||
const commit = spawnSync("git", ["commit", "-m", message], {
|
||||
cwd: rootDir,
|
||||
encoding: "utf8",
|
||||
});
|
||||
if (commit.error || commit.status !== 0) {
|
||||
return { info: `git commit failed (${commit.status ?? "?"}):\n${gitTail(commit)}` };
|
||||
}
|
||||
const firstLine = (commit.stdout || "").split(/\r?\n/)[0] ?? "";
|
||||
return { info: `▸ committed: ${message}${firstLine ? `\n ${firstLine}` : ""}` };
|
||||
}
|
||||
|
||||
/**
|
||||
* Safely extract whatever diagnostic text is available from a spawnSync
|
||||
* result — on Windows or when cwd doesn't exist, `stderr`/`stdout` can
|
||||
* be `undefined` and the caller has only `error.message` to go on.
|
||||
*/
|
||||
export function gitTail(res: ReturnType<typeof spawnSync>): string {
|
||||
const stderr = (res.stderr as string | undefined) ?? "";
|
||||
const stdout = (res.stdout as string | undefined) ?? "";
|
||||
const body = stderr.trim() || stdout.trim();
|
||||
if (body) return body;
|
||||
if (res.error) return (res.error as Error).message;
|
||||
return "(no output from git)";
|
||||
}
|
||||
@@ -0,0 +1,344 @@
|
||||
import type { EditMode } from "../../../config.js";
|
||||
import type { McpClient } from "../../../mcp/client.js";
|
||||
import type { InspectionReport } from "../../../mcp/inspect.js";
|
||||
import type { JobRegistry } from "../../../tools/jobs.js";
|
||||
import type { PlanStep } from "../../../tools/plan.js";
|
||||
|
||||
export interface SlashResult {
|
||||
/** Text to display back to the user as a system/info line. */
|
||||
info?: string;
|
||||
/** Exit the app. */
|
||||
exit?: boolean;
|
||||
/** Clear the visible history. */
|
||||
clear?: boolean;
|
||||
/** Unknown command — display usage hint. */
|
||||
unknown?: boolean;
|
||||
/**
|
||||
* Re-submit this text as a user message after displaying `info`.
|
||||
* Used by `/retry` — the slash command truncates the log, then
|
||||
* asks the TUI to push the original text back through the normal
|
||||
* submit flow so a fresh turn runs.
|
||||
*/
|
||||
resubmit?: string;
|
||||
/**
|
||||
* Render an archived plan as a read-only "Time Travel" block in
|
||||
* scrollback. Populated by `/replay [N]`. The TUI mounts it as a
|
||||
* `plan-replay` DisplayEvent so the same step-list / risk gutter
|
||||
* styling gets reused. Strictly a display payload — no execution.
|
||||
*/
|
||||
replayPlan?: {
|
||||
summary?: string;
|
||||
body?: string;
|
||||
steps: PlanStep[];
|
||||
completedStepIds: string[];
|
||||
completedAt: string;
|
||||
relativeTime: string;
|
||||
archiveBasename: string;
|
||||
/** 1-based index in `/plans` listing — surfaced in the header. */
|
||||
index: number;
|
||||
/** Total archives at the time of the lookup; helps the user navigate. */
|
||||
total: number;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Extra runtime context a slash handler may care about but that isn't
|
||||
* already on the loop. Kept as an optional object so tests that only
|
||||
* need loop-scoped commands can skip it, and callers only populate the
|
||||
* slots that apply to their session.
|
||||
*/
|
||||
export interface SlashContext {
|
||||
/**
|
||||
* The exact `--mcp` / config-derived spec strings that were bridged
|
||||
* into this session (one entry per server). Used by `/mcp`. Empty or
|
||||
* omitted → no MCP servers attached.
|
||||
*/
|
||||
mcpSpecs?: string[];
|
||||
/**
|
||||
* Callback for `/undo` — provided by the TUI when it's running in
|
||||
* code mode. Returns a human-readable report of what was restored.
|
||||
* Absent outside code mode → `/undo` replies "not available here".
|
||||
* Accepts slash args: `[id]`, `[id, path]`.
|
||||
*/
|
||||
codeUndo?: (args: readonly string[]) => string;
|
||||
/**
|
||||
* Callback for `/apply [N|N,M|N-M]` — commits pending edit blocks to
|
||||
* disk. Returns a report of what landed. With no `indices` (or `[]`),
|
||||
* applies every pending block; with explicit 1-based indices, applies
|
||||
* just those and leaves the rest pending. Absent → `/apply` replies
|
||||
* "nothing pending" or "not available outside code mode".
|
||||
*/
|
||||
codeApply?: (indices?: readonly number[]) => string;
|
||||
/**
|
||||
* Callback for `/discard [N|N,M|N-M]` — drops the pending edit blocks
|
||||
* without touching disk. Same indices semantics as `codeApply`: empty
|
||||
* means "drop all pending"; explicit indices drop just those.
|
||||
*/
|
||||
codeDiscard?: (indices?: readonly number[]) => string;
|
||||
/**
|
||||
* Callback for `/history` — returns a human-readable list of every
|
||||
* edit batch this session, newest last. Includes entry ids (for
|
||||
* `/show`) and undone status.
|
||||
*/
|
||||
codeHistory?: () => string;
|
||||
/**
|
||||
* Callback for `/show [id] [path]` — with no args, shows a per-file
|
||||
* summary of the newest non-undone entry. With id only, the entry's
|
||||
* per-file summary. With id + path, the full diff of that single
|
||||
* file in that entry.
|
||||
*/
|
||||
codeShowEdit?: (args: readonly string[]) => string;
|
||||
/**
|
||||
* Root directory passed by `reasonix code`. Enables `/commit`, which
|
||||
* runs `git add -A && git commit` in this directory. Missing → `/commit`
|
||||
* replies "only available in code mode".
|
||||
*/
|
||||
codeRoot?: string;
|
||||
/**
|
||||
* How many edit blocks are currently pending `/apply` or `/discard`.
|
||||
* Surfaced by `/status`. TUI populates it live from its pending ref;
|
||||
* omitted → treat as 0 (chat-only session).
|
||||
*/
|
||||
pendingEditCount?: number;
|
||||
/**
|
||||
* Callback returning every tool result seen this session in
|
||||
* chronological order (oldest first). Powers `/tool [N]` for
|
||||
* inspecting the full untruncated output that `EventLog` clips at
|
||||
* 400 chars for display. Absent → `/tool` replies "not available".
|
||||
*/
|
||||
toolHistory?: () => Array<{ toolName: string; text: string }>;
|
||||
/**
|
||||
* Pre-captured inspection reports for each connected MCP server.
|
||||
* Populated once at chat startup (chat.tsx) so `/mcp` can render
|
||||
* tools + resources + prompts synchronously without needing async
|
||||
* handler support.
|
||||
*/
|
||||
mcpServers?: McpServerSummary[];
|
||||
/**
|
||||
* Directory `/memory` should resolve `REASONIX.md` from. In code
|
||||
* mode this is the rootDir the filesystem tools are pinned to; in
|
||||
* plain chat this is `process.cwd()` at launch time. Absent → the
|
||||
* TUI is running in some non-cwd context (tests) and `/memory`
|
||||
* replies "root unknown" instead of silently reading a different dir.
|
||||
*/
|
||||
memoryRoot?: string;
|
||||
/**
|
||||
* Current plan-mode state, surfaced in `/status` and toggled by
|
||||
* `/plan`. Present iff the session is a `reasonix code` run — chat
|
||||
* mode doesn't have plan mode.
|
||||
*/
|
||||
planMode?: boolean;
|
||||
/**
|
||||
* Current edit-gate mode (`review` or `auto`). Surfaced in `/status`,
|
||||
* toggled by `/mode`, also flipped by the Shift+Tab keybind in the
|
||||
* TUI. Absent → not in `reasonix code`.
|
||||
*/
|
||||
editMode?: EditMode;
|
||||
/**
|
||||
* Set the edit-gate mode. Callback rather than raw state so App can
|
||||
* also persist the choice to config and echo the change in historical.
|
||||
*/
|
||||
setEditMode?: (mode: EditMode) => void;
|
||||
/**
|
||||
* Background-process registry backing /jobs / /kill / /logs. Present
|
||||
* iff the session is a `reasonix code` run. Slash handlers expect
|
||||
* synchronous info strings, but stop_job is async — we return a
|
||||
* "stopping, watch /jobs" info and let the registry do its thing.
|
||||
*/
|
||||
jobs?: JobRegistry;
|
||||
/**
|
||||
* Async-late append to the historical log. /kill uses this to
|
||||
* surface "job N stopped" the moment stop() actually resolves,
|
||||
* rather than leaving the user to poll /jobs themselves.
|
||||
*/
|
||||
postInfo?: (text: string) => void;
|
||||
/**
|
||||
* Callback the `/plan` slash uses to flip plan mode on/off. Also
|
||||
* mirrors the state to the underlying ToolRegistry so dispatch
|
||||
* enforcement follows. Absent → `/plan` replies "only available in
|
||||
* code mode".
|
||||
*/
|
||||
setPlanMode?: (on: boolean) => void;
|
||||
/**
|
||||
* Callback that clears a pending-plan picker state. Called by
|
||||
* `/apply-plan` so that when the user force-approves, the picker
|
||||
* dismisses without also firing its own approval synthetic (the
|
||||
* slash returns its own `resubmit` instead). Safe to call with no
|
||||
* pending plan.
|
||||
*/
|
||||
clearPendingPlan?: () => void;
|
||||
/**
|
||||
* Re-load `~/.reasonix/settings.json` + `<project>/.reasonix/settings.json`
|
||||
* and update both the App's hook state and the loop's mutable hook
|
||||
* list. Returns the new hook count so the slash can echo a sane
|
||||
* confirmation. Absent → `/hooks reload` replies "not available".
|
||||
*/
|
||||
reloadHooks?: () => number;
|
||||
/**
|
||||
* Switch the session working directory. Called by `/cwd <path>`.
|
||||
* Updates the hook cwd, memory root, project shell allowlist root,
|
||||
* `@file` mention root, and (in code mode) re-registers filesystem /
|
||||
* shell / memory / skill tools against the new path. Returns a
|
||||
* human-readable info line describing what changed; throws on
|
||||
* validation errors so the handler can surface the message.
|
||||
* Absent → `/cwd` replies "not available in this context".
|
||||
*/
|
||||
setCwd?: (path: string) => string;
|
||||
/**
|
||||
* Latest published version if App's background registry check
|
||||
* has completed, `null` otherwise (still in flight OR offline).
|
||||
* Drives `/update` — the slash shows whatever the async check
|
||||
* already resolved, so the command is fully synchronous.
|
||||
*/
|
||||
latestVersion?: string | null;
|
||||
/**
|
||||
* Fire-and-forget: kick off a fresh registry fetch. `/update`
|
||||
* calls this whenever it encounters `latestVersion === null`
|
||||
* so the user can rerun the slash a few seconds later and see
|
||||
* a concrete answer. Absent → the slash just reports "pending"
|
||||
* with no retry path.
|
||||
*/
|
||||
refreshLatestVersion?: () => void;
|
||||
/**
|
||||
* Model catalog fetched from DeepSeek's `/models` endpoint at App
|
||||
* mount. `null` → still in flight or the call failed (auth / offline);
|
||||
* `[]` → the API answered with zero entries. `/models` uses this to
|
||||
* render the list, and `/model <id>` uses it for soft validation
|
||||
* (warn-only — we still switch even on unknown ids since the list
|
||||
* can lag a newly-released model).
|
||||
*/
|
||||
models?: string[] | null;
|
||||
/**
|
||||
* Fire-and-forget refresh for the models list. Lets `/models` retry
|
||||
* after a flaky first fetch without needing async slash support.
|
||||
*/
|
||||
refreshModels?: () => void;
|
||||
/**
|
||||
* Arm pro for the next turn. Called by `/pro`. The TUI wires this
|
||||
* to both `loop.armProForNextTurn()` and its React mirror state so
|
||||
* the StatsPanel badge flips immediately. Absent → the handler
|
||||
* calls `loop.armProForNextTurn()` directly and the badge updates
|
||||
* on the next render tick (slightly laggy but still correct).
|
||||
*/
|
||||
armPro?: () => void;
|
||||
/** Cancel a pending /pro arming. Mirrors `armPro` semantics. */
|
||||
disarmPro?: () => void;
|
||||
/**
|
||||
* Start a recurring auto-submit. Called by `/loop <interval> <prompt>`.
|
||||
* Replaces any active loop. Caller (App.tsx) owns the timer + visible
|
||||
* countdown; the slash handler just kicks it off.
|
||||
*/
|
||||
startLoop?: (intervalMs: number, prompt: string) => void;
|
||||
/** Stop the active loop. No-op if none. */
|
||||
stopLoop?: () => void;
|
||||
/**
|
||||
* Snapshot of the active loop, for the `/loop` (no-args) status
|
||||
* branch. Returns null when no loop is active.
|
||||
*/
|
||||
getLoopStatus?: () => {
|
||||
prompt: string;
|
||||
intervalMs: number;
|
||||
iter: number;
|
||||
nextFireMs: number;
|
||||
} | null;
|
||||
/**
|
||||
* Mount the `/walk` per-block walkthrough modal over the current
|
||||
* pendingEdits queue. Returns the info text to surface (explanation
|
||||
* when nothing's pending, or the started-walk banner).
|
||||
*/
|
||||
startWalkthrough?: () => string;
|
||||
/**
|
||||
* Boot the embedded web dashboard server attached to this session
|
||||
* and return the human-readable info line to print (URL + token +
|
||||
* "open in browser" hint). The handler implementation lives in
|
||||
* App.tsx so it can capture the live loop / tools / MCP servers as
|
||||
* the dashboard's data context. Returns the URL string on success
|
||||
* for the slash to surface, or an Error to relay.
|
||||
*/
|
||||
startDashboard?: () => Promise<string>;
|
||||
/** Tear the dashboard server down. Mirrors stopLoop's shape; no-op when not running. */
|
||||
stopDashboard?: () => Promise<void>;
|
||||
/** Snapshot the dashboard's URL when running, null otherwise. */
|
||||
getDashboardUrl?: () => string | null;
|
||||
}
|
||||
|
||||
export interface McpServerSummary {
|
||||
/** Short label shown in the `/mcp` output (server namespace or "anon"). */
|
||||
label: string;
|
||||
/** Original --mcp spec string. */
|
||||
spec: string;
|
||||
/** Count of tools bridged into the Reasonix registry from this server. */
|
||||
toolCount: number;
|
||||
/** Full inspection snapshot — used for the resources + prompts sections. */
|
||||
report: InspectionReport;
|
||||
/**
|
||||
* Live MCP client, kept so `/resource` and `/prompt` can call
|
||||
* `readResource` / `getPrompt` against this server. Omitted by
|
||||
* callers that only build the summary for display; those slashes
|
||||
* fall back to "not available" when the client is missing.
|
||||
*/
|
||||
client?: McpClient;
|
||||
}
|
||||
|
||||
/**
|
||||
* Slash command registry. Drives `/help`, the on-type suggestion
|
||||
* popup (`SlashSuggestions`), and auto-complete. Kept as data rather
|
||||
* than derived from the `handleSlash` switch so summaries can be
|
||||
* user-facing rather than code comments.
|
||||
*
|
||||
* `contextual` gates commands that only make sense in certain modes:
|
||||
* - `"code"` — only show when the TUI is running `reasonix code`
|
||||
* - absent → always shown
|
||||
*/
|
||||
export interface SlashCommandSpec {
|
||||
cmd: string;
|
||||
summary: string;
|
||||
contextual?: "code";
|
||||
/** If the command takes args, hint text shown after the name. */
|
||||
argsHint?: string;
|
||||
/**
|
||||
* How the first argument position should autocomplete. Shapes the
|
||||
* picker that appears below the prompt once the user types `/<cmd>`
|
||||
* + space:
|
||||
* - `"models"` → DeepSeek model-id list fetched at startup.
|
||||
* - `"mcp-resources"` → live URIs aggregated across connected MCP servers.
|
||||
* - `"mcp-prompts"` → live prompt names aggregated across MCP servers.
|
||||
* - `string[]` → small enum of literal values (e.g. `["on", "off"]`).
|
||||
* - omitted → no picker; a persistent usage hint shows the
|
||||
* argsHint + summary so the user knows what to type.
|
||||
*
|
||||
* File-path completion is deliberately NOT offered here. Users who
|
||||
* want to reference a file in a prompt use `@path/to/file` (0.5.5);
|
||||
* the `@` picker already surfaces files with mtime + recently-used
|
||||
* ranking. Adding a second file-picker surface for slash commands
|
||||
* would split the UX without adding leverage.
|
||||
*/
|
||||
argCompleter?: "models" | "mcp-resources" | "mcp-prompts" | readonly string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Shape describing what the prompt buffer is asking for AFTER the
|
||||
* user has committed to a slash command (`/<cmd>`) and started
|
||||
* typing its first argument. Consumed by the TUI to drive an
|
||||
* argument-level picker.
|
||||
*/
|
||||
export interface SlashArgContext {
|
||||
/** The command spec (looked up by name from SLASH_COMMANDS). */
|
||||
spec: SlashCommandSpec;
|
||||
/** The partial first-argument text, possibly empty. */
|
||||
partial: string;
|
||||
/**
|
||||
* Buffer offset where `partial` begins. Used by the TUI to splice
|
||||
* a picked completion back in at the right position.
|
||||
*/
|
||||
partialOffset: number;
|
||||
/**
|
||||
* Classification of what the caller should show:
|
||||
* - `"picker"` → an interactive picker (file / enum / models). The
|
||||
* caller uses `spec.argCompleter` to pick the data source and
|
||||
* filters against `partial`.
|
||||
* - `"hint"` → past the completable position (additional args or
|
||||
* no completer declared). Caller shows a dim usage hint only.
|
||||
*/
|
||||
kind: "picker" | "hint";
|
||||
}
|
||||
@@ -0,0 +1,462 @@
|
||||
/**
|
||||
* Raw stdin reader with our own CSI parser.
|
||||
*
|
||||
* Replaces Ink's `useInput` chain (which uses `parse-keypress` with a
|
||||
* 100 ms intra-sequence timeout that's too short for Windows ConPTY).
|
||||
* That timeout was the root cause of every keyboard regression we
|
||||
* shipped a patch for in 0.7.x — paste markers leaking into the
|
||||
* buffer, arrow keys not crossing newlines, Shift+Tab silently failing.
|
||||
*
|
||||
* Design:
|
||||
* - One reader owns `process.stdin`. We call `setRawMode(true)`,
|
||||
* register a single `data` listener, and emit parsed `KeyEvent`s
|
||||
* to subscribers. As long as no `useInput` is called inside the
|
||||
* Ink tree, Ink itself never attaches its own listener — we're
|
||||
* the sole consumer of stdin.
|
||||
*
|
||||
* - The state machine is tiny: idle → esc → csi/ss3 → idle, plus a
|
||||
* `paste` accumulator that swallows everything between `\x1b[200~`
|
||||
* and `\x1b[201~`. ESC ambiguity (standalone Esc vs. start of a
|
||||
* CSI) is resolved by a 250 ms timer — much longer than parse-
|
||||
* keypress's 100 ms, so ConPTY-split sequences land in the
|
||||
* correct branch.
|
||||
*
|
||||
* - We also recognise the ESC-stripped variants (`[A`, `[200~`) at
|
||||
* idle-state lookahead, in case ConPTY consumed the leading ESC
|
||||
* before we even saw it. That used to be a recovery layer in
|
||||
* `key-normalize.ts`; with this reader as the sole input source
|
||||
* it folds into the parser proper.
|
||||
*
|
||||
* - `paste` events carry the full content so the consumer can route
|
||||
* it through paste-sentinel registration without re-parsing.
|
||||
*/
|
||||
|
||||
import { stdin } from "node:process";
|
||||
|
||||
/**
|
||||
* Single keystroke event. Shape mirrors Ink's `(input, key)` callback
|
||||
* pair for migration ergonomics — consumers reading `key.upArrow`
|
||||
* etc. can keep doing so. `paste` is the one new field; consumers
|
||||
* that care about pastes (PromptInput) check it explicitly.
|
||||
*/
|
||||
export interface KeyEvent {
|
||||
/**
|
||||
* Printable character(s). Non-empty for normal typing, Ctrl+letter
|
||||
* (the letter goes here with `ctrl:true`), Alt+letter (with
|
||||
* `meta:true`), and bracketed paste content (with `paste:true`).
|
||||
* Always empty for control keystrokes like arrows / Enter / Esc.
|
||||
*/
|
||||
input: string;
|
||||
upArrow?: boolean;
|
||||
downArrow?: boolean;
|
||||
leftArrow?: boolean;
|
||||
rightArrow?: boolean;
|
||||
pageUp?: boolean;
|
||||
pageDown?: boolean;
|
||||
home?: boolean;
|
||||
end?: boolean;
|
||||
delete?: boolean;
|
||||
backspace?: boolean;
|
||||
tab?: boolean;
|
||||
return?: boolean;
|
||||
escape?: boolean;
|
||||
shift?: boolean;
|
||||
ctrl?: boolean;
|
||||
meta?: boolean;
|
||||
/**
|
||||
* True iff this event delivers bracketed-paste content. `input`
|
||||
* holds the entire paste; consumers MUST NOT re-interpret it as
|
||||
* keystrokes (e.g. a `\n` in a paste shouldn't fire submit).
|
||||
*/
|
||||
paste?: boolean;
|
||||
}
|
||||
|
||||
type Subscriber = (ev: KeyEvent) => void;
|
||||
|
||||
/** ESC ambiguity timeout. Long enough for ConPTY-split sequences. */
|
||||
const ESC_TIMEOUT_MS = 250;
|
||||
|
||||
/** Bracketed-paste markers (DECSET 2004). */
|
||||
const PASTE_START = "\x1b[200~";
|
||||
const PASTE_END = "\x1b[201~";
|
||||
/** ESC-stripped variants — ConPTY occasionally eats the leading ESC. */
|
||||
const PASTE_START_BARE = "[200~";
|
||||
const PASTE_END_BARE = "[201~";
|
||||
|
||||
/**
|
||||
* CSI tails (the bytes that follow `\x1b[`) we recognise and the
|
||||
* structured event each produces. Order doesn't matter — lookups
|
||||
* are exact-match.
|
||||
*/
|
||||
const CSI_TAIL_MAP: ReadonlyArray<{ tail: string; ev: KeyEvent }> = [
|
||||
{ tail: "A", ev: { input: "", upArrow: true } },
|
||||
{ tail: "B", ev: { input: "", downArrow: true } },
|
||||
{ tail: "C", ev: { input: "", rightArrow: true } },
|
||||
{ tail: "D", ev: { input: "", leftArrow: true } },
|
||||
{ tail: "H", ev: { input: "", home: true } },
|
||||
{ tail: "F", ev: { input: "", end: true } },
|
||||
{ tail: "1~", ev: { input: "", home: true } },
|
||||
{ tail: "4~", ev: { input: "", end: true } },
|
||||
{ tail: "5~", ev: { input: "", pageUp: true } },
|
||||
{ tail: "6~", ev: { input: "", pageDown: true } },
|
||||
{ tail: "3~", ev: { input: "", delete: true } },
|
||||
{ tail: "Z", ev: { input: "", shift: true, tab: true } },
|
||||
// modifyOtherKeys (xterm CSI > 4 ; 2 m) sequences for Enter with
|
||||
// modifiers. Only fired when App.tsx has enabled the mode at
|
||||
// startup; otherwise Shift+Enter stays indistinguishable from Enter.
|
||||
// Modifier encoding: 2=shift, 3=alt, 4=alt+shift, 5=ctrl,
|
||||
// 6=ctrl+shift, 7=ctrl+alt, 8=ctrl+alt+shift. Keycode 13 = Enter.
|
||||
{ tail: "27;2;13~", ev: { input: "", return: true, shift: true } },
|
||||
{ tail: "27;5;13~", ev: { input: "", return: true, ctrl: true } },
|
||||
{ tail: "27;6;13~", ev: { input: "", return: true, ctrl: true, shift: true } },
|
||||
// Kitty keyboard protocol — same idea, different envelope:
|
||||
// `\x1b[<keycode>;<mod>u`. Some terminals (kitty, recent Windows
|
||||
// Terminal previews) prefer this shape. Harmless to map here too.
|
||||
{ tail: "13;2u", ev: { input: "", return: true, shift: true } },
|
||||
{ tail: "13;5u", ev: { input: "", return: true, ctrl: true } },
|
||||
{ tail: "13;6u", ev: { input: "", return: true, ctrl: true, shift: true } },
|
||||
];
|
||||
|
||||
/** SS3 sequences (`\x1bO<letter>`) — some terminals send these for arrows. */
|
||||
const SS3_MAP: Record<string, KeyEvent> = {
|
||||
A: { input: "", upArrow: true },
|
||||
B: { input: "", downArrow: true },
|
||||
C: { input: "", rightArrow: true },
|
||||
D: { input: "", leftArrow: true },
|
||||
H: { input: "", home: true },
|
||||
F: { input: "", end: true },
|
||||
};
|
||||
|
||||
/**
|
||||
* Lookahead matcher for ESC-stripped sequences. When `chunk[i]` is
|
||||
* `[`, we check the bytes immediately after to see if they form a
|
||||
* recognised CSI tail. If so we emit the structured event and tell
|
||||
* the caller how many bytes to consume. Returns `null` when no
|
||||
* recognised tail starts here.
|
||||
*/
|
||||
function tryEscapelessCsi(chunk: string, i: number): { advance: number; ev: KeyEvent } | null {
|
||||
if (chunk[i] !== "[") return null;
|
||||
// Paste start as a special case (handled by caller).
|
||||
// Try each known tail.
|
||||
for (const entry of CSI_TAIL_MAP) {
|
||||
const candidate = `[${entry.tail}`;
|
||||
if (chunk.slice(i, i + candidate.length) === candidate) {
|
||||
return { advance: candidate.length, ev: entry.ev };
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Final byte of a CSI sequence is in the range `0x40` (`@`) –
|
||||
* `0x7E` (`~`). Anything else is a parameter / intermediate byte.
|
||||
*/
|
||||
function isCsiFinal(ch: string): boolean {
|
||||
const code = ch.charCodeAt(0);
|
||||
return code >= 0x40 && code <= 0x7e;
|
||||
}
|
||||
|
||||
/**
|
||||
* Look up the CSI event for a fully-assembled sequence (without the
|
||||
* leading `\x1b[`). Returns `null` if we don't recognise it — which
|
||||
* is fine, we just drop the bytes silently rather than insert them
|
||||
* into the buffer as garbage text.
|
||||
*/
|
||||
function lookupCsi(tail: string): KeyEvent | null {
|
||||
for (const entry of CSI_TAIL_MAP) {
|
||||
if (entry.tail === tail) return entry.ev;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export class StdinReader {
|
||||
private subscribers = new Set<Subscriber>();
|
||||
private state: "idle" | "esc" | "csi" | "ss3" | "paste" = "idle";
|
||||
/** Buffer for partial sequences across chunks. */
|
||||
private csiBuf = "";
|
||||
/** Buffer for paste content. */
|
||||
private pasteBuf = "";
|
||||
private escTimer: NodeJS.Timeout | null = null;
|
||||
private started = false;
|
||||
/** The actual `data` listener — kept as a field so `stop()` can detach it. */
|
||||
private listener: ((chunk: Buffer | string) => void) | null = null;
|
||||
|
||||
start(): void {
|
||||
if (this.started) return;
|
||||
if (!stdin.isTTY) {
|
||||
// Non-TTY (piped input). We can't run interactively — don't try.
|
||||
return;
|
||||
}
|
||||
stdin.setRawMode(true);
|
||||
stdin.setEncoding("utf8");
|
||||
stdin.resume();
|
||||
this.listener = (chunk) =>
|
||||
this.handleChunk(typeof chunk === "string" ? chunk : chunk.toString("utf8"));
|
||||
stdin.on("data", this.listener);
|
||||
this.started = true;
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
if (!this.started) return;
|
||||
if (this.listener) {
|
||||
stdin.off("data", this.listener);
|
||||
this.listener = null;
|
||||
}
|
||||
if (stdin.isTTY) {
|
||||
try {
|
||||
stdin.setRawMode(false);
|
||||
} catch {
|
||||
// setRawMode may throw if stdin is already closed; ignore.
|
||||
}
|
||||
}
|
||||
stdin.pause();
|
||||
this.cancelEscTimer();
|
||||
this.state = "idle";
|
||||
this.csiBuf = "";
|
||||
this.pasteBuf = "";
|
||||
this.started = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Subscribe to parsed key events. Returns an unsubscribe function.
|
||||
* Multiple subscribers are supported — every event fans out to all
|
||||
* of them; the React Context layer above uses one subscriber and
|
||||
* dispatches further to its own consumer list.
|
||||
*/
|
||||
subscribe(fn: Subscriber): () => void {
|
||||
this.subscribers.add(fn);
|
||||
return () => {
|
||||
this.subscribers.delete(fn);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Inject a chunk of bytes as if it came from stdin. Used by tests
|
||||
* to drive the parser without a real TTY.
|
||||
*/
|
||||
feed(chunk: string): void {
|
||||
this.handleChunk(chunk);
|
||||
}
|
||||
|
||||
private dispatch(ev: KeyEvent): void {
|
||||
for (const sub of this.subscribers) sub(ev);
|
||||
}
|
||||
|
||||
private cancelEscTimer(): void {
|
||||
if (this.escTimer) {
|
||||
clearTimeout(this.escTimer);
|
||||
this.escTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
private scheduleEscTimer(): void {
|
||||
this.cancelEscTimer();
|
||||
this.escTimer = setTimeout(() => {
|
||||
// Standalone Esc — no follow-up byte arrived in time.
|
||||
if (this.state === "esc") {
|
||||
this.state = "idle";
|
||||
this.dispatch({ input: "", escape: true });
|
||||
}
|
||||
}, ESC_TIMEOUT_MS);
|
||||
}
|
||||
|
||||
private handleChunk(chunk: string): void {
|
||||
this.cancelEscTimer();
|
||||
let i = 0;
|
||||
while (i < chunk.length) {
|
||||
// ── paste accumulator ──
|
||||
if (this.state === "paste") {
|
||||
// Look for end marker (with or without ESC).
|
||||
const endA = chunk.indexOf(PASTE_END, i);
|
||||
const endB = chunk.indexOf(PASTE_END_BARE, i);
|
||||
let endIdx = -1;
|
||||
let endLen = 0;
|
||||
if (endA !== -1 && (endB === -1 || endA <= endB)) {
|
||||
endIdx = endA;
|
||||
endLen = PASTE_END.length;
|
||||
} else if (endB !== -1) {
|
||||
endIdx = endB;
|
||||
endLen = PASTE_END_BARE.length;
|
||||
}
|
||||
if (endIdx === -1) {
|
||||
this.pasteBuf += chunk.slice(i);
|
||||
i = chunk.length;
|
||||
break;
|
||||
}
|
||||
this.pasteBuf += chunk.slice(i, endIdx);
|
||||
this.dispatch({ input: this.pasteBuf, paste: true });
|
||||
this.pasteBuf = "";
|
||||
this.state = "idle";
|
||||
i = endIdx + endLen;
|
||||
continue;
|
||||
}
|
||||
|
||||
// ── CSI accumulator ──
|
||||
if (this.state === "csi") {
|
||||
const ch = chunk[i]!;
|
||||
this.csiBuf += ch;
|
||||
if (isCsiFinal(ch)) {
|
||||
this.dispatchCsi(this.csiBuf);
|
||||
this.csiBuf = "";
|
||||
// Only reset state if `dispatchCsi` didn't already mutate it
|
||||
// (it transitions to `paste` for the `200~` start marker —
|
||||
// resetting here would clobber that and the paste content
|
||||
// would be parsed as keystrokes).
|
||||
if (this.state === "csi") this.state = "idle";
|
||||
}
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
|
||||
// ── SS3 single-byte tail ──
|
||||
if (this.state === "ss3") {
|
||||
const ev = SS3_MAP[chunk[i]!];
|
||||
if (ev) this.dispatch(ev);
|
||||
this.state = "idle";
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
|
||||
// ── ESC pending ──
|
||||
if (this.state === "esc") {
|
||||
const ch = chunk[i]!;
|
||||
if (ch === "[") {
|
||||
this.state = "csi";
|
||||
this.csiBuf = "";
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
if (ch === "O") {
|
||||
this.state = "ss3";
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
// ESC + any other char = Alt+key (rare; we still dispatch).
|
||||
this.dispatch({ input: ch, meta: true });
|
||||
this.state = "idle";
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
|
||||
// ── idle ──
|
||||
const ch = chunk[i]!;
|
||||
|
||||
if (ch === "\x1b") {
|
||||
this.state = "esc";
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
|
||||
// ESC-stripped paste-start (ConPTY): bare `[200~` at idle.
|
||||
if (chunk.slice(i, i + PASTE_START_BARE.length) === PASTE_START_BARE) {
|
||||
this.state = "paste";
|
||||
this.pasteBuf = "";
|
||||
i += PASTE_START_BARE.length;
|
||||
continue;
|
||||
}
|
||||
// ESC-stripped CSI tails — recover before treating `[` as text.
|
||||
const escapeless = tryEscapelessCsi(chunk, i);
|
||||
if (escapeless) {
|
||||
this.dispatch(escapeless.ev);
|
||||
i += escapeless.advance;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Single-byte control keys.
|
||||
// \r (CR, 0x0D) is Enter on every terminal in raw mode.
|
||||
// \n (LF, 0x0A) is what Ctrl+J emits — keep it distinct so the
|
||||
// multiline reducer can map it to "insert newline" instead of
|
||||
// "submit". Pastes containing \n still arrive via either the
|
||||
// bracketed-paste accumulator or a multi-byte printable chunk
|
||||
// that includes the newline; neither hits this single-byte
|
||||
// branch, so this split is safe.
|
||||
if (ch === "\r") {
|
||||
this.dispatch({ input: "", return: true });
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
if (ch === "\n") {
|
||||
this.dispatch({ input: "j", ctrl: true });
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
if (ch === "\t") {
|
||||
this.dispatch({ input: "", tab: true });
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
if (ch === "\x7f" || ch === "\b") {
|
||||
this.dispatch({ input: "", backspace: true });
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
if (ch === "\x03") {
|
||||
// Ctrl+C — terminate the process. Raw mode disables the
|
||||
// default SIGINT, so we have to handle it ourselves.
|
||||
this.dispatch({ input: "c", ctrl: true });
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
|
||||
const code = ch.charCodeAt(0);
|
||||
// Other Ctrl+letter (0x01-0x1A → A-Z, except already-handled).
|
||||
if (code >= 1 && code <= 26) {
|
||||
const letter = String.fromCharCode(0x60 + code); // a..z
|
||||
this.dispatch({ input: letter, ctrl: true });
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Regular printable input. Coalesce a run of printable chars
|
||||
// into one event so a multi-byte UTF-8 paste-burst arrives as
|
||||
// one `input` rather than N adjacent events.
|
||||
let end = i + 1;
|
||||
while (end < chunk.length) {
|
||||
const c = chunk[end]!;
|
||||
if (c === "\x1b" || c === "\r" || c === "\n" || c === "\t") break;
|
||||
if (c === "\x7f" || c === "\b" || c === "\x03") break;
|
||||
const cc = c.charCodeAt(0);
|
||||
if (cc >= 1 && cc <= 26) break;
|
||||
// Don't swallow into a printable run if a CSI / paste prefix
|
||||
// starts at this position.
|
||||
if (c === "[" && tryEscapelessCsi(chunk, end)) break;
|
||||
if (chunk.slice(end, end + PASTE_START_BARE.length) === PASTE_START_BARE) break;
|
||||
end++;
|
||||
}
|
||||
this.dispatch({ input: chunk.slice(i, end) });
|
||||
i = end;
|
||||
}
|
||||
|
||||
// After processing, if we're still in `esc` state, schedule the
|
||||
// ambiguity timer. The next chunk may carry the rest of the CSI;
|
||||
// if not, the timer fires and dispatches a standalone Esc.
|
||||
if (this.state === "esc") {
|
||||
this.scheduleEscTimer();
|
||||
}
|
||||
}
|
||||
|
||||
private dispatchCsi(seq: string): void {
|
||||
// seq is the bytes after `\x1b[`, e.g. "A", "5~", "200~", "Z".
|
||||
if (seq === "200~") {
|
||||
this.state = "paste";
|
||||
this.pasteBuf = "";
|
||||
return;
|
||||
}
|
||||
if (seq === "201~") {
|
||||
// Stray paste-end — we shouldn't reach here outside paste mode,
|
||||
// but if we do, drop it silently.
|
||||
return;
|
||||
}
|
||||
const ev = lookupCsi(seq);
|
||||
if (ev) this.dispatch(ev);
|
||||
// Unknown CSI → drop. Do NOT insert raw bytes as text.
|
||||
}
|
||||
}
|
||||
|
||||
/** Singleton — one reader per process. */
|
||||
let singleton: StdinReader | null = null;
|
||||
|
||||
export function getStdinReader(): StdinReader {
|
||||
if (!singleton) singleton = new StdinReader();
|
||||
return singleton;
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
/**
|
||||
* Reasonix visual theme.
|
||||
*
|
||||
* One source of truth for colors, glyphs, and decorative blocks so
|
||||
* the TUI reads as one designed surface instead of fifteen
|
||||
* components inventing their own palette. All colors are truecolor
|
||||
* hex; Ink degrades to the nearest 256-color / 8-color slot on
|
||||
* older terminals, so the worst case is still legible.
|
||||
*
|
||||
* Why a module rather than a context: tests import these strings,
|
||||
* Ink components consume them as `color={...}` props, and there's
|
||||
* no theming switch (light/dark) — one project, one palette.
|
||||
*/
|
||||
|
||||
/** Brand gradient — the same teal → cyan → blue → purple → fuchsia
|
||||
* sweep used by the REASONIX wordmark. Reused for accent bars,
|
||||
* progress fills, and decorative dividers. */
|
||||
export const GRADIENT: ReadonlyArray<string> = [
|
||||
"#5eead4", // teal
|
||||
"#67e8f9", // cyan
|
||||
"#7dd3fc", // sky
|
||||
"#93c5fd", // blue
|
||||
"#a5b4fc", // indigo
|
||||
"#c4b5fd", // violet
|
||||
"#d8b4fe", // purple
|
||||
"#f0abfc", // fuchsia
|
||||
];
|
||||
|
||||
/** Solid palette — semantic colors used for status, role, and
|
||||
* accent surfaces. Sourced from the Tailwind 400/500 row so the
|
||||
* tone is consistent with the gradient. */
|
||||
export const COLOR = {
|
||||
primary: "#67e8f9", // cyan-300
|
||||
accent: "#c4b5fd", // violet-300
|
||||
brand: "#5eead4", // teal-300
|
||||
|
||||
user: "#67e8f9", // user message glyph + bar
|
||||
assistant: "#86efac", // green-300, assistant glyph + bar
|
||||
tool: "#fcd34d", // amber-300, tool ok pill bg
|
||||
toolErr: "#fda4af", // rose-300, tool err pill bg
|
||||
info: "#94a3b8", // slate-400, info / dim
|
||||
warn: "#fbbf24", // amber-400
|
||||
err: "#f87171", // red-400
|
||||
ok: "#4ade80", // green-400
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* Glyphs — one consistent alphabet for the whole TUI. Geometric
|
||||
* shapes (◇ ◆ ▣ ▥) make the role of a row readable at a glance
|
||||
* after one or two turns; arrows (› ▸ ▶) consistently mean
|
||||
* "selection / focus / next." Brand mark is reserved for the app
|
||||
* header.
|
||||
*/
|
||||
export const GLYPH = {
|
||||
brand: "◈",
|
||||
user: "◇",
|
||||
assistant: "◆",
|
||||
toolOk: "▣",
|
||||
toolErr: "▥",
|
||||
warn: "▲",
|
||||
err: "✦",
|
||||
arrow: "›",
|
||||
bullet: "·",
|
||||
bar: "▎",
|
||||
thinBar: "▏",
|
||||
block: "█",
|
||||
shade1: "░",
|
||||
shade2: "▒",
|
||||
shade3: "▓",
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* Render a horizontal gradient rule of the given width. Each cell
|
||||
* picks a color from the brand gradient interpolated across the
|
||||
* width, so at cols=80 the rule spans the full sweep. Used for
|
||||
* StatsPanel header/footer decoration and other "this section is
|
||||
* important" anchors.
|
||||
*/
|
||||
export function gradientCells(
|
||||
width: number,
|
||||
glyph: string = GLYPH.block,
|
||||
): Array<{ ch: string; color: string }> {
|
||||
const cells: Array<{ ch: string; color: string }> = [];
|
||||
if (width <= 0) return cells;
|
||||
const last = GRADIENT.length - 1;
|
||||
for (let i = 0; i < width; i++) {
|
||||
const t = width === 1 ? 0 : (i * last) / (width - 1);
|
||||
const lo = Math.floor(t);
|
||||
const hi = Math.min(last, lo + 1);
|
||||
// Pick the closer of the two anchor colors for this cell. Linear
|
||||
// hex blending could be fancier but the discrete steps already
|
||||
// read as a smooth fade at any reasonable width.
|
||||
const color = t - lo < 0.5 ? GRADIENT[lo]! : GRADIENT[hi]!;
|
||||
cells.push({ ch: glyph, color });
|
||||
}
|
||||
return cells;
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
/**
|
||||
* One-line tool-result summarizer for the compact scrollback row.
|
||||
*
|
||||
* Old rendering: glyph + arrow + blank line + 400-char body block.
|
||||
* Cost ~6–8 vertical lines per tool call. Long sessions drown in
|
||||
* noise; the actually-interesting tool result (an edit diff, a
|
||||
* checkpoint signal) gets buried.
|
||||
*
|
||||
* New rendering: glyph + tool name + arrow + a SINGLE-LINE summary
|
||||
* tailored to the tool family. Full content stays in the tool history
|
||||
* and can be expanded via `/tool N`. edit_file keeps its multi-line
|
||||
* diff renderer (the diff IS the value).
|
||||
*
|
||||
* Pure function — lives outside EventLog.tsx so it's testable without
|
||||
* Ink and can be reused if other surfaces (replay, transcript export)
|
||||
* want the same one-liner.
|
||||
*/
|
||||
|
||||
const MAX_SUMMARY_CHARS = 80;
|
||||
const TRAILING_ELLIPSIS = "…";
|
||||
|
||||
export interface ToolSummary {
|
||||
/** Single-line summary text. Empty string if the result was empty. */
|
||||
summary: string;
|
||||
/** True when the tool result represents a failure the renderer should color red. */
|
||||
isError: boolean;
|
||||
}
|
||||
|
||||
function clip(s: string, max: number): string {
|
||||
if (s.length <= max) return s;
|
||||
return s.slice(0, Math.max(1, max - TRAILING_ELLIPSIS.length)) + TRAILING_ELLIPSIS;
|
||||
}
|
||||
|
||||
function firstNonEmptyLine(text: string): string {
|
||||
for (const line of text.split(/\r?\n/)) {
|
||||
const trimmed = line.trim();
|
||||
if (trimmed) return trimmed;
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
/**
|
||||
* Render a duration in milliseconds as a tight human label for the
|
||||
* compact tool row. Picks a representation that fits in ~5 chars so
|
||||
* the surrounding row stays readable on narrow terminals.
|
||||
*
|
||||
* < 100ms → "47ms"
|
||||
* < 1000ms → "0.4s"
|
||||
* < 60s → "12s" (or "1.2s" for sub-10-second times)
|
||||
* >= 60s → "1m30s"
|
||||
*/
|
||||
export function formatDuration(ms: number): string {
|
||||
if (!Number.isFinite(ms) || ms < 0) return "";
|
||||
if (ms < 100) return `${Math.round(ms)}ms`;
|
||||
if (ms < 1000) return `${(ms / 1000).toFixed(1)}s`;
|
||||
if (ms < 10_000) return `${(ms / 1000).toFixed(1)}s`;
|
||||
if (ms < 60_000) return `${Math.round(ms / 1000)}s`;
|
||||
const totalSec = Math.round(ms / 1000);
|
||||
const m = Math.floor(totalSec / 60);
|
||||
const s = totalSec % 60;
|
||||
return s === 0 ? `${m}m` : `${m}m${s}s`;
|
||||
}
|
||||
|
||||
function formatBytes(n: number): string {
|
||||
if (n < 1000) return `${n}B`;
|
||||
if (n < 1_000_000) return `${(n / 1000).toFixed(1)}KB`;
|
||||
return `${(n / 1_000_000).toFixed(1)}MB`;
|
||||
}
|
||||
|
||||
function formatLineCount(text: string): string {
|
||||
// Cheap line count — the +1 covers files without a trailing newline.
|
||||
const lines = text.split(/\r?\n/).length;
|
||||
return `${lines} line${lines === 1 ? "" : "s"}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Try to recognize a structured error envelope. Reasonix tools emit
|
||||
* `{ "error": "..." }` JSON for failures and structured payloads
|
||||
* (PlanProposedError carries `{error, plan, ...}`) for special
|
||||
* signals. We surface the error name as the summary so the user
|
||||
* sees what kind of failure happened at a glance.
|
||||
*/
|
||||
function summarizeStructured(content: string): ToolSummary | null {
|
||||
const trimmed = content.trim();
|
||||
if (!trimmed.startsWith("{")) return null;
|
||||
try {
|
||||
const parsed = JSON.parse(trimmed);
|
||||
if (!parsed || typeof parsed !== "object") return null;
|
||||
const obj = parsed as Record<string, unknown>;
|
||||
// Plan / choice signals come through as errors carrying structured
|
||||
// payloads — the App-level handlers extract the structured part.
|
||||
// For the tool row here we just want the tag.
|
||||
if (typeof obj.error === "string") {
|
||||
const tag = obj.error.split(":", 1)[0]?.trim() ?? "error";
|
||||
const detail = obj.error.slice(tag.length + 1).trim();
|
||||
// The tag-only case (no colon body) — show the bare tag.
|
||||
const summary = detail ? `${tag} — ${detail}` : tag;
|
||||
// Plan / Choice errors are control-flow signals, not real errors.
|
||||
const isControlSignal =
|
||||
tag === "PlanProposedError" ||
|
||||
tag === "PlanCheckpointError" ||
|
||||
tag === "PlanRevisionProposedError" ||
|
||||
tag === "ChoiceRequestedError" ||
|
||||
tag === "NeedsConfirmationError";
|
||||
return { summary: clip(summary, MAX_SUMMARY_CHARS), isError: !isControlSignal };
|
||||
}
|
||||
// step_completed payload (when used outside the error path, kept
|
||||
// for forward-compat with non-throwing variants).
|
||||
if (obj.kind === "step_completed" && typeof obj.stepId === "string") {
|
||||
const result = typeof obj.result === "string" ? obj.result : "";
|
||||
return {
|
||||
summary: clip(`✓ ${obj.stepId}: ${result}`, MAX_SUMMARY_CHARS),
|
||||
isError: false,
|
||||
};
|
||||
}
|
||||
return null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Per-tool-name overrides for cases where a smarter summary is cheap
|
||||
* to compute. Returning null means "fall through to the generic
|
||||
* summary path."
|
||||
*
|
||||
* Suffix-match is on purpose: MCP-bridged tools come in prefixed
|
||||
* (`filesystem_read_file`, `git_search_files`) and we want them to
|
||||
* pick up the same specialized summary as the bare local name.
|
||||
*/
|
||||
function summarizeKnownTool(toolName: string, content: string): ToolSummary | null {
|
||||
const hasSuffix = (s: string) => toolName === s || toolName.endsWith(`_${s}`);
|
||||
if (hasSuffix("read_file")) {
|
||||
const lines = formatLineCount(content);
|
||||
const bytes = formatBytes(content.length);
|
||||
const head = clip(
|
||||
firstNonEmptyLine(content),
|
||||
MAX_SUMMARY_CHARS - lines.length - bytes.length - 8,
|
||||
);
|
||||
return {
|
||||
summary: head ? `${head} · ${lines} · ${bytes}` : `${lines} · ${bytes}`,
|
||||
isError: false,
|
||||
};
|
||||
}
|
||||
if (hasSuffix("list_directory") || hasSuffix("directory_tree")) {
|
||||
const entries = content.split(/\r?\n/).filter((l) => l.trim()).length;
|
||||
return { summary: `${entries} entr${entries === 1 ? "y" : "ies"}`, isError: false };
|
||||
}
|
||||
if (hasSuffix("search_files") || hasSuffix("search_content")) {
|
||||
const matches = content.split(/\r?\n/).filter((l) => l.trim()).length;
|
||||
if (matches === 0) return { summary: "no matches", isError: false };
|
||||
const first = firstNonEmptyLine(content);
|
||||
return {
|
||||
summary: clip(`${matches} match${matches === 1 ? "" : "es"} · ${first}`, MAX_SUMMARY_CHARS),
|
||||
isError: false,
|
||||
};
|
||||
}
|
||||
if (hasSuffix("write_file")) {
|
||||
const lines = formatLineCount(content);
|
||||
const bytes = formatBytes(content.length);
|
||||
return { summary: `wrote ${lines} · ${bytes}`, isError: false };
|
||||
}
|
||||
if (hasSuffix("run_command") || hasSuffix("run_background")) {
|
||||
// Native shell tools prepend "exit 0:" / "exit N:" or the result
|
||||
// already mentions exit code. Try to surface it.
|
||||
const exitMatch = content.match(/exit (?:code )?(-?\d+)/i);
|
||||
const first = firstNonEmptyLine(content);
|
||||
if (exitMatch) {
|
||||
const code = exitMatch[1];
|
||||
const isError = code !== "0";
|
||||
return {
|
||||
summary: clip(`exit ${code} · ${first}`, MAX_SUMMARY_CHARS),
|
||||
isError,
|
||||
};
|
||||
}
|
||||
return { summary: clip(first || "(no output)", MAX_SUMMARY_CHARS), isError: false };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function summarizeToolResult(toolName: string, content: string): ToolSummary {
|
||||
const isExplicitError = content.startsWith("ERROR:");
|
||||
if (isExplicitError) {
|
||||
const stripped = content.slice("ERROR:".length).trim();
|
||||
return { summary: clip(stripped || "(unknown error)", MAX_SUMMARY_CHARS), isError: true };
|
||||
}
|
||||
const structured = summarizeStructured(content);
|
||||
if (structured) return structured;
|
||||
const known = summarizeKnownTool(toolName, content);
|
||||
if (known) return known;
|
||||
// Generic: first line + size hint.
|
||||
const first = firstNonEmptyLine(content);
|
||||
if (!content.trim()) return { summary: "(empty)", isError: false };
|
||||
if (content.length <= MAX_SUMMARY_CHARS) {
|
||||
return { summary: clip(first, MAX_SUMMARY_CHARS), isError: false };
|
||||
}
|
||||
const sizeHint = formatBytes(content.length);
|
||||
const head = clip(first, MAX_SUMMARY_CHARS - sizeHint.length - 3);
|
||||
return { summary: `${head} · ${sizeHint}`, isError: false };
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import {
|
||||
type FileWithStats,
|
||||
detectAtPicker,
|
||||
listFilesWithStatsSync,
|
||||
rankPickerCandidates,
|
||||
} from "../../at-mentions.js";
|
||||
import {
|
||||
type McpServerSummary,
|
||||
type SlashArgContext,
|
||||
type SlashCommandSpec,
|
||||
detectSlashArgContext,
|
||||
suggestSlashCommands,
|
||||
} from "./slash.js";
|
||||
|
||||
export interface UseCompletionPickersParams {
|
||||
input: string;
|
||||
setInput: (v: string) => void;
|
||||
codeMode: { rootDir: string } | undefined;
|
||||
/**
|
||||
* Live working directory for the @-mention file picker. May differ
|
||||
* from `codeMode.rootDir` after a `/cwd` switch — `codeMode` keeps
|
||||
* the launch root for "is this a code-mode session?" checks while
|
||||
* this drives the actual file listing.
|
||||
*/
|
||||
rootDir: string;
|
||||
models: string[] | null;
|
||||
mcpServers: McpServerSummary[] | undefined;
|
||||
}
|
||||
|
||||
export interface UseCompletionPickersResult {
|
||||
// ── slash-name picker ──
|
||||
slashMatches: SlashCommandSpec[] | null;
|
||||
slashSelected: number;
|
||||
setSlashSelected: React.Dispatch<React.SetStateAction<number>>;
|
||||
|
||||
// ── @-mention picker ──
|
||||
atPicker: ReturnType<typeof detectAtPicker>;
|
||||
atMatches: readonly string[] | null;
|
||||
atSelected: number;
|
||||
setAtSelected: React.Dispatch<React.SetStateAction<number>>;
|
||||
pickAtMention: (chosenPath: string) => void;
|
||||
recordRecentFile: (path: string) => void;
|
||||
|
||||
// ── slash-arg picker ──
|
||||
slashArgContext: SlashArgContext | null;
|
||||
slashArgMatches: readonly string[] | null;
|
||||
slashArgSelected: number;
|
||||
setSlashArgSelected: React.Dispatch<React.SetStateAction<number>>;
|
||||
pickSlashArg: (chosen: string) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* The three mutually-exclusive input-prefix pickers share enough
|
||||
* structure (matches list + highlighted index + reset-on-shrink effect
|
||||
* + commit-back-into-buffer callback) that they live together here.
|
||||
* Priority in the parent useInput handler:
|
||||
* atMatches > slashArgMatches > slashMatches > prompt history
|
||||
* detection already disambiguates by construction — the slash-name
|
||||
* picker fires only when the buffer has no space; the slash-arg picker
|
||||
* only after a space; the @-picker only outside slash mode.
|
||||
*/
|
||||
export function useCompletionPickers({
|
||||
input,
|
||||
setInput,
|
||||
codeMode,
|
||||
rootDir,
|
||||
models,
|
||||
mcpServers,
|
||||
}: UseCompletionPickersParams): UseCompletionPickersResult {
|
||||
// ── slash-name picker ──
|
||||
const [slashSelected, setSlashSelected] = useState(0);
|
||||
const slashMatches = useMemo(() => {
|
||||
if (!input.startsWith("/") || input.includes(" ")) return null;
|
||||
return suggestSlashCommands(input.slice(1), !!codeMode);
|
||||
}, [input, codeMode]);
|
||||
useEffect(() => {
|
||||
setSlashSelected((prev) => {
|
||||
if (!slashMatches || slashMatches.length === 0) return 0;
|
||||
if (prev >= slashMatches.length) return slashMatches.length - 1;
|
||||
return prev;
|
||||
});
|
||||
}, [slashMatches]);
|
||||
|
||||
// ── @-mention picker ──
|
||||
const [atSelected, setAtSelected] = useState(0);
|
||||
// Walk the code root ONCE on mount, collecting mtime alongside path
|
||||
// so the picker can surface recently-edited files first. Files
|
||||
// created mid-session via tool edits won't appear until restart —
|
||||
// rare, and the user can always type the full path.
|
||||
const atFiles = useMemo<readonly FileWithStats[]>(() => {
|
||||
if (!codeMode) return [];
|
||||
try {
|
||||
return listFilesWithStatsSync(rootDir, { maxResults: 500 });
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}, [codeMode, rootDir]);
|
||||
// LRU of files touched by recent tool calls. Seeds the picker with
|
||||
// "stuff I just looked at" at the top, so a user typing `@` in the
|
||||
// same file they were just discussing gets it instantly.
|
||||
const recentFilesRef = useRef<string[]>([]);
|
||||
const recordRecentFile = useCallback((p: string) => {
|
||||
const list = recentFilesRef.current;
|
||||
const i = list.indexOf(p);
|
||||
if (i >= 0) list.splice(i, 1);
|
||||
list.unshift(p);
|
||||
if (list.length > 20) list.length = 20;
|
||||
}, []);
|
||||
const atPicker = useMemo(() => {
|
||||
if (!codeMode) return null;
|
||||
// Slash prefix wins — avoids the picker confusingly surfacing on
|
||||
// `/@wat`-style edge inputs.
|
||||
if (slashMatches !== null) return null;
|
||||
return detectAtPicker(input);
|
||||
}, [codeMode, input, slashMatches]);
|
||||
const atMatches = useMemo<readonly string[] | null>(() => {
|
||||
if (!atPicker) return null;
|
||||
return rankPickerCandidates(atFiles, atPicker.query, {
|
||||
limit: 40,
|
||||
recentlyUsed: recentFilesRef.current,
|
||||
});
|
||||
}, [atPicker, atFiles]);
|
||||
useEffect(() => {
|
||||
setAtSelected((prev) => {
|
||||
if (!atMatches || atMatches.length === 0) return 0;
|
||||
if (prev >= atMatches.length) return atMatches.length - 1;
|
||||
return prev;
|
||||
});
|
||||
}, [atMatches]);
|
||||
const pickAtMention = useCallback(
|
||||
(chosenPath: string) => {
|
||||
if (!atPicker) return;
|
||||
const before = input.slice(0, atPicker.atOffset);
|
||||
setInput(`${before}@${chosenPath} `);
|
||||
},
|
||||
[atPicker, input, setInput],
|
||||
);
|
||||
|
||||
// ── slash-arg picker ──
|
||||
const [slashArgSelected, setSlashArgSelected] = useState(0);
|
||||
const slashArgContext = useMemo<SlashArgContext | null>(() => {
|
||||
if (!input.startsWith("/")) return null;
|
||||
if (slashMatches !== null) return null;
|
||||
return detectSlashArgContext(input, !!codeMode);
|
||||
}, [input, slashMatches, codeMode]);
|
||||
const slashArgMatches = useMemo<readonly string[] | null>(() => {
|
||||
if (!slashArgContext || slashArgContext.kind !== "picker") return null;
|
||||
const completer = slashArgContext.spec.argCompleter;
|
||||
const partial = slashArgContext.partial;
|
||||
const needle = partial.toLowerCase();
|
||||
// Once the partial is an EXACT match for a valid completion, hide
|
||||
// the picker so Enter submits the command instead of re-picking
|
||||
// the same value in an infinite loop. Case-insensitive — users
|
||||
// may type `/preset FAST` and still mean the same thing.
|
||||
if (Array.isArray(completer)) {
|
||||
if (partial && completer.some((v) => v.toLowerCase() === needle)) return null;
|
||||
if (!partial) return completer.slice();
|
||||
return completer.filter((v) => v.toLowerCase().startsWith(needle));
|
||||
}
|
||||
if (completer === "models") {
|
||||
const all = models ?? [];
|
||||
if (partial && all.some((m) => m.toLowerCase() === needle)) return null;
|
||||
if (!partial) return all.slice(0, 40);
|
||||
return all.filter((m) => m.toLowerCase().includes(needle)).slice(0, 40);
|
||||
}
|
||||
if (completer === "mcp-resources") {
|
||||
// Aggregate URIs across every server's cached inspection.
|
||||
const uris: string[] = [];
|
||||
const servers = mcpServers ?? [];
|
||||
for (const s of servers) {
|
||||
if (!s.report.resources.supported) continue;
|
||||
for (const r of s.report.resources.items) uris.push(r.uri);
|
||||
}
|
||||
if (partial && uris.some((u) => u.toLowerCase() === needle)) return null;
|
||||
if (!partial) return uris.slice(0, 40);
|
||||
return uris.filter((u) => u.toLowerCase().includes(needle)).slice(0, 40);
|
||||
}
|
||||
if (completer === "mcp-prompts") {
|
||||
const names: string[] = [];
|
||||
const servers = mcpServers ?? [];
|
||||
for (const s of servers) {
|
||||
if (!s.report.prompts.supported) continue;
|
||||
for (const p of s.report.prompts.items) names.push(p.name);
|
||||
}
|
||||
if (partial && names.some((n) => n.toLowerCase() === needle)) return null;
|
||||
if (!partial) return names.slice(0, 40);
|
||||
return names.filter((n) => n.toLowerCase().includes(needle)).slice(0, 40);
|
||||
}
|
||||
return null;
|
||||
}, [slashArgContext, models, mcpServers]);
|
||||
useEffect(() => {
|
||||
setSlashArgSelected((prev) => {
|
||||
if (!slashArgMatches || slashArgMatches.length === 0) return 0;
|
||||
if (prev >= slashArgMatches.length) return slashArgMatches.length - 1;
|
||||
return prev;
|
||||
});
|
||||
}, [slashArgMatches]);
|
||||
const pickSlashArg = useCallback(
|
||||
(chosen: string) => {
|
||||
if (!slashArgContext) return;
|
||||
const before = input.slice(0, slashArgContext.partialOffset);
|
||||
// No trailing space — enum picks take no further args, so the
|
||||
// user presses Enter once more to run the command.
|
||||
setInput(`${before}${chosen}`);
|
||||
},
|
||||
[slashArgContext, input, setInput],
|
||||
);
|
||||
|
||||
return {
|
||||
slashMatches,
|
||||
slashSelected,
|
||||
setSlashSelected,
|
||||
atPicker,
|
||||
atMatches,
|
||||
atSelected,
|
||||
setAtSelected,
|
||||
pickAtMention,
|
||||
recordRecentFile,
|
||||
slashArgContext,
|
||||
slashArgMatches,
|
||||
slashArgSelected,
|
||||
setSlashArgSelected,
|
||||
pickSlashArg,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,309 @@
|
||||
import { useCallback, useRef, useState } from "react";
|
||||
import { formatAllBlockDiffs } from "../../code/diff-preview.js";
|
||||
import {
|
||||
type ApplyResult,
|
||||
type EditBlock,
|
||||
type EditSnapshot,
|
||||
restoreSnapshots,
|
||||
} from "../../code/edit-blocks.js";
|
||||
import {
|
||||
type EditHistoryEntry,
|
||||
entryStatus,
|
||||
formatUndoRows,
|
||||
isEntryFullyUndone,
|
||||
} from "./edit-history.js";
|
||||
|
||||
export interface UndoBannerState {
|
||||
results: ApplyResult[];
|
||||
expiresAt: number;
|
||||
}
|
||||
|
||||
export interface UseEditHistoryResult {
|
||||
/** Post-auto-apply banner state — rendered at the bottom for 5s. */
|
||||
undoBanner: UndoBannerState | null;
|
||||
/**
|
||||
* Append a batch of successfully-applied edits into the session's
|
||||
* edit history. If the current turn already has an open entry,
|
||||
* append into it (first-wins-per-path so `/undo` restores the
|
||||
* pre-turn state, not an intermediate half-edit). Otherwise open a
|
||||
* new entry.
|
||||
*/
|
||||
recordEdit: (
|
||||
source: string,
|
||||
blocks: readonly EditBlock[],
|
||||
results: readonly ApplyResult[],
|
||||
snaps: readonly EditSnapshot[],
|
||||
) => void;
|
||||
/**
|
||||
* Show the post-auto-apply undo banner for 5 seconds. Overwrites any
|
||||
* prior banner and replaces the auto-dismiss timer so multiple
|
||||
* edits inside a single turn don't prematurely expire the window.
|
||||
*/
|
||||
armUndoBanner: (results: ApplyResult[]) => void;
|
||||
/**
|
||||
* `/undo` — revert applied edits.
|
||||
* `/undo` → newest non-fully-undone entry, all its
|
||||
* remaining (non-undone) files.
|
||||
* `/undo <id>` → that specific entry's remaining files.
|
||||
* `/undo <id> <path>` → just that one file in that entry.
|
||||
* Works as long as the session is alive; no 5-second banner limit.
|
||||
*/
|
||||
codeUndo: (args?: readonly string[]) => string;
|
||||
/**
|
||||
* `/history` — list every edit batch this session. Each entry's id
|
||||
* is the token for `/show <id>` and the target of per-batch undo.
|
||||
*/
|
||||
codeHistory: () => string;
|
||||
/**
|
||||
* `/show` — inspect a stored edit batch.
|
||||
* `/show` → newest non-fully-undone entry, per-file summary.
|
||||
* `/show <id>` → that entry's per-file summary.
|
||||
* `/show <id> <path>` → full diff of one file in that entry.
|
||||
*/
|
||||
codeShowEdit: (args?: readonly string[]) => string;
|
||||
/**
|
||||
* Seal the in-progress entry so the next edit opens a fresh one.
|
||||
* Called at handleSubmit start — prior turns stay intact for
|
||||
* `/history` and `/undo` to walk through independently.
|
||||
*/
|
||||
sealCurrentEntry: () => void;
|
||||
/**
|
||||
* True when there's at least one history entry that isn't fully
|
||||
* undone yet. Used by the `u` keybind and the bottom ModeStatusBar.
|
||||
* Reads the ref fresh — callers must re-read each time.
|
||||
*/
|
||||
hasUndoable: () => boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Session-scoped edit history and undo machinery for `reasonix code`.
|
||||
* Keeps the history ref + snapshot bookkeeping out of App.tsx so the
|
||||
* parent only sees a small API: append, banner, three slash handlers,
|
||||
* a turn sealer, and an undoable probe.
|
||||
*
|
||||
* `codeMode` is optional because the hook is always mounted but its
|
||||
* handlers turn into no-ops when code mode isn't active.
|
||||
*/
|
||||
export function useEditHistory(codeMode: { rootDir: string } | undefined): UseEditHistoryResult {
|
||||
const editHistory = useRef<EditHistoryEntry[]>([]);
|
||||
const nextHistoryId = useRef(1);
|
||||
const currentTurnEntry = useRef<EditHistoryEntry | null>(null);
|
||||
const [undoBanner, setUndoBanner] = useState<UndoBannerState | null>(null);
|
||||
const undoTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
const recordEdit = useCallback<UseEditHistoryResult["recordEdit"]>(
|
||||
(source, blocks, results, snaps) => {
|
||||
if (snaps.length === 0) return;
|
||||
let entry = currentTurnEntry.current;
|
||||
if (!entry) {
|
||||
entry = {
|
||||
id: nextHistoryId.current++,
|
||||
at: Date.now(),
|
||||
source,
|
||||
blocks: [],
|
||||
results: [],
|
||||
snapshots: [],
|
||||
undoneFiles: new Set<string>(),
|
||||
};
|
||||
currentTurnEntry.current = entry;
|
||||
editHistory.current.push(entry);
|
||||
}
|
||||
entry.blocks.push(...blocks);
|
||||
entry.results.push(...results);
|
||||
const seen = new Set(entry.snapshots.map((s) => s.path));
|
||||
for (const s of snaps) {
|
||||
if (!seen.has(s.path)) entry.snapshots.push(s);
|
||||
}
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const armUndoBanner = useCallback<UseEditHistoryResult["armUndoBanner"]>((results) => {
|
||||
setUndoBanner({ results, expiresAt: Date.now() + 5000 });
|
||||
if (undoTimeoutRef.current) clearTimeout(undoTimeoutRef.current);
|
||||
undoTimeoutRef.current = setTimeout(() => {
|
||||
setUndoBanner(null);
|
||||
undoTimeoutRef.current = null;
|
||||
}, 5000);
|
||||
}, []);
|
||||
|
||||
const codeUndo = useCallback<UseEditHistoryResult["codeUndo"]>(
|
||||
(args = []) => {
|
||||
if (!codeMode) return "not in code mode";
|
||||
const root = codeMode.rootDir;
|
||||
|
||||
const revert = (entry: EditHistoryEntry, paths: readonly string[]): string => {
|
||||
const subset = entry.snapshots.filter((s) => paths.includes(s.path));
|
||||
if (subset.length === 0) {
|
||||
return `batch #${entry.id}: nothing to undo (already restored or path not in batch)`;
|
||||
}
|
||||
const results = restoreSnapshots(subset, root);
|
||||
for (const s of subset) entry.undoneFiles.add(s.path);
|
||||
if (currentTurnEntry.current === entry && isEntryFullyUndone(entry)) {
|
||||
currentTurnEntry.current = null;
|
||||
}
|
||||
if (undoTimeoutRef.current) {
|
||||
clearTimeout(undoTimeoutRef.current);
|
||||
undoTimeoutRef.current = null;
|
||||
}
|
||||
setUndoBanner(null);
|
||||
const when = new Date(entry.at).toISOString().replace("T", " ").slice(11, 19);
|
||||
const scope = subset.length === 1 ? subset[0]!.path : `${subset.length} file(s)`;
|
||||
const header = `▸ undo: reverted ${scope} from batch #${entry.id} (${when})`;
|
||||
return [header, ...formatUndoRows(results)].join("\n");
|
||||
};
|
||||
|
||||
const idArg = args[0];
|
||||
const pathArg = args[1];
|
||||
|
||||
if (!idArg) {
|
||||
for (let i = editHistory.current.length - 1; i >= 0; i--) {
|
||||
const e = editHistory.current[i]!;
|
||||
if (isEntryFullyUndone(e)) continue;
|
||||
const remaining = e.snapshots.map((s) => s.path).filter((p) => !e.undoneFiles.has(p));
|
||||
return revert(e, remaining);
|
||||
}
|
||||
return "nothing to undo — every batch in the session history is already undone";
|
||||
}
|
||||
|
||||
const id = Number.parseInt(idArg, 10);
|
||||
if (!Number.isFinite(id)) {
|
||||
return "usage: /undo [id] [path] (omit id for newest; id from /history; path from /show <id>)";
|
||||
}
|
||||
const entry = editHistory.current.find((e) => e.id === id);
|
||||
if (!entry) return `no edit #${id} — run /history to see valid ids`;
|
||||
|
||||
if (!pathArg) {
|
||||
const remaining = entry.snapshots
|
||||
.map((s) => s.path)
|
||||
.filter((p) => !entry.undoneFiles.has(p));
|
||||
if (remaining.length === 0) return `batch #${id} is already fully undone`;
|
||||
return revert(entry, remaining);
|
||||
}
|
||||
|
||||
const snap = entry.snapshots.find((s) => s.path === pathArg);
|
||||
if (!snap) {
|
||||
const files = [...new Set(entry.blocks.map((b) => b.path))];
|
||||
return `batch #${id} doesn't include "${pathArg}" — files in this batch: ${files.join(", ")}`;
|
||||
}
|
||||
if (entry.undoneFiles.has(pathArg)) {
|
||||
return `${pathArg} in batch #${id} is already undone`;
|
||||
}
|
||||
return revert(entry, [pathArg]);
|
||||
},
|
||||
[codeMode],
|
||||
);
|
||||
|
||||
const codeHistory = useCallback<UseEditHistoryResult["codeHistory"]>(() => {
|
||||
if (!codeMode) return "not in code mode";
|
||||
const entries = editHistory.current;
|
||||
if (entries.length === 0) return "no edits recorded this session yet";
|
||||
const lines = ["Edit history (oldest first):"];
|
||||
for (const e of entries) {
|
||||
const when = new Date(e.at).toISOString().replace("T", " ").slice(11, 19);
|
||||
const files = new Set(e.blocks.map((b) => b.path));
|
||||
const fileList = [...files].join(", ");
|
||||
const fileSummary = fileList.length > 60 ? `${fileList.slice(0, 60)}…` : fileList;
|
||||
const status = entryStatus(e);
|
||||
const statusText =
|
||||
status === "applied" ? "applied" : status === "PARTIAL" ? "PARTIAL" : "UNDONE ";
|
||||
lines.push(
|
||||
` #${String(e.id).padStart(3)} ${when} ${statusText} ${e.source.padEnd(12)} ${files.size} file · ${e.blocks.length} block ${fileSummary}`,
|
||||
);
|
||||
}
|
||||
lines.push("");
|
||||
lines.push(
|
||||
"/show <id> → per-file summary · /show <id> <path> → full diff of one file",
|
||||
);
|
||||
lines.push(
|
||||
"/undo → newest non-undone · /undo <id> [path] → target a specific batch or file",
|
||||
);
|
||||
return lines.join("\n");
|
||||
}, [codeMode]);
|
||||
|
||||
const codeShowEdit = useCallback<UseEditHistoryResult["codeShowEdit"]>(
|
||||
(args = []) => {
|
||||
if (!codeMode) return "not in code mode";
|
||||
const entries = editHistory.current;
|
||||
if (entries.length === 0) return "no edits recorded this session — /history is empty";
|
||||
|
||||
const idArg = args[0];
|
||||
const pathArg = args[1];
|
||||
|
||||
let entry: EditHistoryEntry | undefined;
|
||||
if (!idArg) {
|
||||
entry =
|
||||
[...entries].reverse().find((e) => !isEntryFullyUndone(e)) ?? entries[entries.length - 1];
|
||||
} else {
|
||||
const id = Number.parseInt(idArg, 10);
|
||||
if (!Number.isFinite(id)) {
|
||||
return "usage: /show [id] [path] (omit id for newest; path from the per-file summary)";
|
||||
}
|
||||
entry = entries.find((e) => e.id === id);
|
||||
if (!entry) return `no edit #${id} — run /history to see valid ids`;
|
||||
}
|
||||
if (!entry) return "unexpected: history lookup failed";
|
||||
|
||||
if (pathArg) {
|
||||
const fileBlocks = entry.blocks.filter((b) => b.path === pathArg);
|
||||
if (fileBlocks.length === 0) {
|
||||
const files = [...new Set(entry.blocks.map((b) => b.path))];
|
||||
return `batch #${entry.id} doesn't include "${pathArg}" — files in this batch: ${files.join(", ")}`;
|
||||
}
|
||||
const when = new Date(entry.at).toISOString().replace("T", " ").slice(11, 19);
|
||||
const state = entry.undoneFiles.has(pathArg) ? "UNDONE" : "applied";
|
||||
const header = `▸ edit #${entry.id} · ${when} · ${pathArg} · ${state} · ${fileBlocks.length} block(s)`;
|
||||
const diff = formatAllBlockDiffs(fileBlocks, { maxLines: 60, contextLines: 2 });
|
||||
const footer = entry.undoneFiles.has(pathArg)
|
||||
? "(already reverted — /history shows the batch-level status)"
|
||||
: `/undo ${entry.id} ${pathArg} → revert just this file`;
|
||||
return [header, ...diff, "", footer].join("\n");
|
||||
}
|
||||
|
||||
const when = new Date(entry.at).toISOString().replace("T", " ").slice(11, 19);
|
||||
const files = [...new Set(entry.blocks.map((b) => b.path))];
|
||||
const status = entryStatus(entry);
|
||||
const header = `▸ edit #${entry.id} · ${when} · ${entry.source} · ${status} · ${files.length} file(s)`;
|
||||
const countLines = (s: string) => (s.length === 0 ? 0 : (s.match(/\n/g)?.length ?? 0) + 1);
|
||||
const fileLines = files.map((path) => {
|
||||
const fileBlocks = entry!.blocks.filter((b) => b.path === path);
|
||||
let removed = 0;
|
||||
let added = 0;
|
||||
for (const b of fileBlocks) {
|
||||
removed += countLines(b.search);
|
||||
added += countLines(b.replace);
|
||||
}
|
||||
const state = entry!.undoneFiles.has(path) ? "UNDONE" : "applied";
|
||||
return ` ${state.padEnd(7)} -${String(removed).padStart(3)}/+${String(added).padStart(3)} ${path} (${fileBlocks.length} block${fileBlocks.length === 1 ? "" : "s"})`;
|
||||
});
|
||||
return [
|
||||
header,
|
||||
...fileLines,
|
||||
"",
|
||||
`/show ${entry.id} <path> → full diff of one file`,
|
||||
`/undo ${entry.id} <path> → revert just that file · /undo ${entry.id} → revert whole batch`,
|
||||
].join("\n");
|
||||
},
|
||||
[codeMode],
|
||||
);
|
||||
|
||||
const sealCurrentEntry = useCallback(() => {
|
||||
currentTurnEntry.current = null;
|
||||
}, []);
|
||||
|
||||
const hasUndoable = useCallback(
|
||||
() => editHistory.current.some((e) => !isEntryFullyUndone(e)),
|
||||
[],
|
||||
);
|
||||
|
||||
return {
|
||||
undoBanner,
|
||||
recordEdit,
|
||||
armUndoBanner,
|
||||
codeUndo,
|
||||
codeHistory,
|
||||
codeShowEdit,
|
||||
sealCurrentEntry,
|
||||
hasUndoable,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import type { CacheFirstLoop } from "../../loop.js";
|
||||
import { VERSION, compareVersions, getLatestVersion } from "../../version.js";
|
||||
|
||||
export interface Balance {
|
||||
currency: string;
|
||||
total: number;
|
||||
}
|
||||
|
||||
export interface UseSessionInfoResult {
|
||||
balance: Balance | null;
|
||||
models: string[] | null;
|
||||
latestVersion: string | null;
|
||||
/** Strictly-newer version string (for the header badge) — else `null`. */
|
||||
updateAvailable: string | null;
|
||||
refreshBalance: () => void;
|
||||
refreshModels: () => void;
|
||||
refreshLatestVersion: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ambient session-level data fetched from DeepSeek + the npm registry
|
||||
* at mount, refreshed either implicitly (balance after each turn) or
|
||||
* on demand (`/update`, `/models`).
|
||||
*
|
||||
* All three are best-effort — a `null` value means "not loaded yet or
|
||||
* the endpoint failed." The StatsPanel hides the cell in that case.
|
||||
*/
|
||||
export function useSessionInfo(loop: CacheFirstLoop): UseSessionInfoResult {
|
||||
const [balance, setBalance] = useState<Balance | null>(null);
|
||||
const [models, setModels] = useState<string[] | null>(null);
|
||||
const [latestVersion, setLatestVersion] = useState<string | null>(null);
|
||||
|
||||
// Fetch balance on mount. Non-blocking — the session works without
|
||||
// it; `null` hides the cell. handleSubmit calls refreshBalance in
|
||||
// its finally so the number tracks actual spend rather than
|
||||
// freezing at mount-time.
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
void (async () => {
|
||||
const bal = await loop.client.getBalance().catch(() => null);
|
||||
if (cancelled || !bal || !bal.balance_infos.length) return;
|
||||
const primary = bal.balance_infos[0]!;
|
||||
setBalance({ currency: primary.currency, total: Number(primary.total_balance) });
|
||||
})();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [loop]);
|
||||
|
||||
// Fetch the model catalog from DeepSeek once. Silent degrade on
|
||||
// failure (stays null), so `/models` can tell "still loading /
|
||||
// offline" apart from "loaded, here's the list."
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
void (async () => {
|
||||
const list = await loop.client.listModels().catch(() => null);
|
||||
if (cancelled || !list) return;
|
||||
setModels(list.data.map((m) => m.id));
|
||||
})();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [loop]);
|
||||
|
||||
// Background registry check — 24h disk cache absorbs repeated
|
||||
// launches, timeout bounded so a flaky network doesn't delay the
|
||||
// notification. `null` on failure (silent). We store the raw version
|
||||
// regardless of whether it's newer; the header badge's newer-only
|
||||
// check happens at the `updateAvailable` derivation below.
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
void (async () => {
|
||||
const latest = await getLatestVersion();
|
||||
if (cancelled || !latest) return;
|
||||
setLatestVersion(latest);
|
||||
})();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, []);
|
||||
|
||||
const updateAvailable =
|
||||
latestVersion && compareVersions(VERSION, latestVersion) < 0 ? latestVersion : null;
|
||||
|
||||
const refreshBalance = useCallback(() => {
|
||||
void (async () => {
|
||||
const bal = await loop.client.getBalance().catch(() => null);
|
||||
if (bal?.balance_infos.length) {
|
||||
const p = bal.balance_infos[0]!;
|
||||
setBalance({ currency: p.currency, total: Number(p.total_balance) });
|
||||
}
|
||||
})();
|
||||
}, [loop]);
|
||||
|
||||
const refreshModels = useCallback(() => {
|
||||
void (async () => {
|
||||
const list = await loop.client.listModels().catch(() => null);
|
||||
if (list) setModels(list.data.map((m) => m.id));
|
||||
})();
|
||||
}, [loop]);
|
||||
|
||||
const refreshLatestVersion = useCallback(() => {
|
||||
void (async () => {
|
||||
const fresh = await getLatestVersion({ force: true });
|
||||
if (fresh) setLatestVersion(fresh);
|
||||
})();
|
||||
}, []);
|
||||
|
||||
return {
|
||||
balance,
|
||||
models,
|
||||
latestVersion,
|
||||
updateAvailable,
|
||||
refreshBalance,
|
||||
refreshModels,
|
||||
refreshLatestVersion,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import type { SubagentEvent, SubagentSink } from "../../tools/subagent.js";
|
||||
import { appendUsage } from "../../usage.js";
|
||||
import type { DisplayEvent } from "./EventLog.js";
|
||||
|
||||
export interface SubagentActivity {
|
||||
task: string;
|
||||
iter: number;
|
||||
elapsedMs: number;
|
||||
}
|
||||
|
||||
export interface UseSubagentParams {
|
||||
session: string | undefined;
|
||||
setHistorical: React.Dispatch<React.SetStateAction<DisplayEvent[]>>;
|
||||
}
|
||||
|
||||
export interface UseSubagentResult {
|
||||
/** Live state for an in-flight subagent, null when none is running. */
|
||||
activity: SubagentActivity | null;
|
||||
/**
|
||||
* Ref captured by the loop's `subagentRunner` closure so even
|
||||
* late-spawned subagents find the current handler. Consumers pass
|
||||
* this to `spawnSubagent({ sink })`.
|
||||
*/
|
||||
sinkRef: React.MutableRefObject<SubagentSink>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Subagent UI wiring. `start` opens the activity row; each `progress`
|
||||
* updates iter + elapsed in place; `end` clears the row and posts a
|
||||
* one-line summary (with inline cost) into Historical. Only one
|
||||
* subagent is active at a time in the MVP — overlapping events just
|
||||
* replace the prior activity.
|
||||
*/
|
||||
export function useSubagent({ session, setHistorical }: UseSubagentParams): UseSubagentResult {
|
||||
const [activity, setActivity] = useState<SubagentActivity | null>(null);
|
||||
const sinkRef = useRef<SubagentSink>({ current: null });
|
||||
|
||||
useEffect(() => {
|
||||
sinkRef.current.current = (ev: SubagentEvent) => {
|
||||
if (ev.kind === "start") {
|
||||
setActivity({
|
||||
task: ev.task,
|
||||
iter: ev.iter ?? 0,
|
||||
elapsedMs: ev.elapsedMs ?? 0,
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (ev.kind === "progress") {
|
||||
setActivity({
|
||||
task: ev.task,
|
||||
iter: ev.iter ?? 0,
|
||||
elapsedMs: ev.elapsedMs ?? 0,
|
||||
});
|
||||
return;
|
||||
}
|
||||
// end
|
||||
setActivity(null);
|
||||
const seconds = ((ev.elapsedMs ?? 0) / 1000).toFixed(1);
|
||||
// Inline cost: the one number most users look at. Shown in the
|
||||
// Historical row so they don't have to run `/stats` to see it.
|
||||
const costTail =
|
||||
ev.costUsd !== undefined && ev.costUsd > 0 ? ` · $${ev.costUsd.toFixed(4)}` : "";
|
||||
const summary = ev.error
|
||||
? `⌬ subagent "${ev.task}" failed after ${seconds}s · ${ev.iter ?? 0} tool call(s) — ${ev.error}`
|
||||
: `⌬ subagent "${ev.task}" done in ${seconds}s · ${ev.iter ?? 0} tool call(s) · ${ev.turns ?? 0} turn(s)${costTail}`;
|
||||
setHistorical((prev) => [
|
||||
...prev,
|
||||
{
|
||||
id: `subagent-end-${Date.now()}`,
|
||||
role: "info",
|
||||
text: summary,
|
||||
},
|
||||
]);
|
||||
// Persist a subagent summary row to ~/.reasonix/usage.jsonl so
|
||||
// `/stats` and `reasonix stats` surface it. Skipped on error —
|
||||
// we only record what actually cost money and did work.
|
||||
if (!ev.error && ev.usage && ev.model) {
|
||||
appendUsage({
|
||||
session: session ?? null,
|
||||
model: ev.model,
|
||||
usage: ev.usage,
|
||||
kind: "subagent",
|
||||
subagent: {
|
||||
skillName: ev.skillName,
|
||||
taskPreview: ev.task.slice(0, 60),
|
||||
toolIters: ev.iter ?? 0,
|
||||
durationMs: ev.elapsedMs ?? 0,
|
||||
},
|
||||
});
|
||||
}
|
||||
};
|
||||
return () => {
|
||||
sinkRef.current.current = null;
|
||||
};
|
||||
}, [session, setHistorical]);
|
||||
|
||||
return { activity, sinkRef };
|
||||
}
|
||||
+23
-1
@@ -110,7 +110,17 @@ export class DeepSeekClient {
|
||||
process.env.DEEPSEEK_BASE_URL ??
|
||||
"https://api.deepseek.com"
|
||||
).replace(/\/+$/, "");
|
||||
this.timeoutMs = opts.timeoutMs ?? 120_000;
|
||||
// 11 min. DeepSeek's load-balancer may keep a connection open for
|
||||
// up to 10 minutes while the request waits in queue (non-streaming
|
||||
// sends empty lines, streaming sends `:` SSE keep-alive comments —
|
||||
// both are invisible to our parsers, so neither surfaces until the
|
||||
// real response starts). Timing out at the legacy 2-min default
|
||||
// killed queued requests prematurely, burned the queue slot on
|
||||
// retry, and could loop through the whole queue repeatedly.
|
||||
// Setting 11 min lets the server's own 10-min cap close the
|
||||
// connection first (clean EOF → natural retry), and our timer
|
||||
// is a safety net for genuinely hung sockets.
|
||||
this.timeoutMs = opts.timeoutMs ?? 660_000;
|
||||
this._fetch = opts.fetch ?? globalThis.fetch.bind(globalThis);
|
||||
this.retry = opts.retry ?? {};
|
||||
}
|
||||
@@ -125,6 +135,18 @@ export class DeepSeekClient {
|
||||
if (opts.temperature !== undefined) payload.temperature = opts.temperature;
|
||||
if (opts.maxTokens !== undefined) payload.max_tokens = opts.maxTokens;
|
||||
if (opts.responseFormat) payload.response_format = opts.responseFormat;
|
||||
// V4 thinking-mode toggle: lives under `extra_body.thinking.type` per
|
||||
// DeepSeek's docs. Docs also note that in thinking mode `temperature`,
|
||||
// `top_p`, `presence_penalty`, `frequency_penalty` are silently
|
||||
// ignored — we don't strip them here because the server's explicit
|
||||
// "setting won't report an error" contract means leaving them in is
|
||||
// safe and keeps the request payload diffable against OpenAI tooling.
|
||||
if (opts.thinking) {
|
||||
payload.extra_body = { thinking: { type: opts.thinking } };
|
||||
}
|
||||
if (opts.reasoningEffort) {
|
||||
payload.reasoning_effort = opts.reasoningEffort;
|
||||
}
|
||||
return payload;
|
||||
}
|
||||
|
||||
|
||||
@@ -23,6 +23,16 @@ export interface DiffPreviewOptions {
|
||||
indent?: string;
|
||||
}
|
||||
|
||||
export interface AllBlockDiffOptions extends DiffPreviewOptions {
|
||||
/**
|
||||
* Prefix each block's path-header with a 1-based `[N]` label. Used by
|
||||
* the pending-edits preview so the user can address individual blocks
|
||||
* via `/apply <N>` / `/discard <N>`. Off by default — single-block
|
||||
* surfaces (modal confirm, /show) don't need numbering.
|
||||
*/
|
||||
numbered?: boolean;
|
||||
}
|
||||
|
||||
/** Render one edit block's diff. Returns an array of formatted lines. */
|
||||
export function formatEditBlockDiff(block: EditBlock, opts: DiffPreviewOptions = {}): string[] {
|
||||
const contextLines = Math.max(0, opts.contextLines ?? 2);
|
||||
@@ -90,7 +100,7 @@ export function formatEditBlockDiff(block: EditBlock, opts: DiffPreviewOptions =
|
||||
*/
|
||||
export function formatAllBlockDiffs(
|
||||
blocks: readonly EditBlock[],
|
||||
opts: DiffPreviewOptions = {},
|
||||
opts: AllBlockDiffOptions = {},
|
||||
): string[] {
|
||||
const out: string[] = [];
|
||||
for (let i = 0; i < blocks.length; i++) {
|
||||
@@ -99,7 +109,8 @@ export function formatAllBlockDiffs(
|
||||
const added = countLines(b.replace);
|
||||
const tag = b.search === "" ? "NEW " : " ";
|
||||
if (i > 0) out.push("");
|
||||
out.push(` ${tag}${b.path} (-${removed} +${added} lines)`);
|
||||
const label = opts.numbered ? `[${i + 1}] ` : "";
|
||||
out.push(` ${label}${tag}${b.path} (-${removed} +${added} lines)`);
|
||||
out.push(...formatEditBlockDiff(b, opts));
|
||||
}
|
||||
return out;
|
||||
|
||||
@@ -153,6 +153,27 @@ export function applyEditBlocks(blocks: EditBlock[], rootDir: string): ApplyResu
|
||||
return blocks.map((b) => applyEditBlock(b, rootDir));
|
||||
}
|
||||
|
||||
/**
|
||||
* Build an EditBlock that represents a whole-file overwrite. If the
|
||||
* target exists, SEARCH = current content so applyEditBlock replaces
|
||||
* the whole thing when committed; if it doesn't, SEARCH is empty (the
|
||||
* create-new sentinel). Used by the edit-mode gate when routing a
|
||||
* `write_file` tool call through the review queue without executing
|
||||
* the write inline.
|
||||
*/
|
||||
export function toWholeFileEditBlock(path: string, content: string, rootDir: string): EditBlock {
|
||||
const abs = resolve(rootDir, path);
|
||||
let search = "";
|
||||
if (existsSync(abs)) {
|
||||
try {
|
||||
search = readFileSync(abs, "utf8");
|
||||
} catch {
|
||||
search = "";
|
||||
}
|
||||
}
|
||||
return { path, search, replace: content, offset: 0 };
|
||||
}
|
||||
|
||||
// ---------- snapshot / restore (for /undo) ----------
|
||||
|
||||
export interface EditSnapshot {
|
||||
|
||||
@@ -0,0 +1,292 @@
|
||||
/**
|
||||
* Per-session plan persistence.
|
||||
*
|
||||
* The structured plan that the model submits via `submit_plan` (and
|
||||
* subsequently mutates via `mark_step_complete` / `revise_plan`) is a
|
||||
* meaningful artifact of the user's work. Without persistence it
|
||||
* evaporates the moment the terminal closes — which means the user
|
||||
* loses context every time they take a coffee break, and the rich
|
||||
* checkpoint / revise / progress UX has nothing to attach to in
|
||||
* resumed sessions.
|
||||
*
|
||||
* This module ships the smallest useful piece: read/write a plan
|
||||
* state JSON next to the session's JSONL log. App.tsx loads on
|
||||
* mount and saves after every state change. Storage path mirrors
|
||||
* the JSONL convention: `~/.reasonix/sessions/<sanitized>.plan.json`.
|
||||
*
|
||||
* What's persisted: the structured `steps[]` (with risk levels), the
|
||||
* set of completedStepIds, and an updatedAt timestamp. The plan's
|
||||
* markdown body is NOT persisted here — it lives in the JSONL log
|
||||
* (it was a tool result), so resuming the session replays it
|
||||
* naturally if the user wants to re-read it. We only carry forward
|
||||
* the live state needed to keep mark_step_complete and revise_plan
|
||||
* meaningful.
|
||||
*/
|
||||
|
||||
import {
|
||||
existsSync,
|
||||
mkdirSync,
|
||||
readFileSync,
|
||||
readdirSync,
|
||||
renameSync,
|
||||
statSync,
|
||||
unlinkSync,
|
||||
writeFileSync,
|
||||
} from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
import { sanitizeName, sessionsDir } from "../session.js";
|
||||
import type { PlanStep } from "../tools/plan.js";
|
||||
|
||||
export interface PlanStateOnDisk {
|
||||
/** File format version — bump when shape changes. */
|
||||
version: 1;
|
||||
steps: PlanStep[];
|
||||
completedStepIds: string[];
|
||||
/** ISO8601 timestamp of the last write. */
|
||||
updatedAt: string;
|
||||
/**
|
||||
* Markdown body the model submitted via submit_plan. Persisted so
|
||||
* Time Travel replay can show the full proposal without going back
|
||||
* to the JSONL log. Optional — older / minimal plans may lack it.
|
||||
*/
|
||||
body?: string;
|
||||
/**
|
||||
* Optional one-sentence human-friendly title. Surfaces in the
|
||||
* PlanConfirm header, the resume banner, and /plans listings so
|
||||
* the user identifies plans by intent rather than file path.
|
||||
*/
|
||||
summary?: string;
|
||||
}
|
||||
|
||||
export function planStatePath(sessionName: string): string {
|
||||
return join(sessionsDir(), `${sanitizeName(sessionName)}.plan.json`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the persisted plan for this session, if any. Returns `null`
|
||||
* for missing / unreadable / malformed files — callers should treat
|
||||
* the absence of a stored plan as "no plan yet", not a hard error.
|
||||
*/
|
||||
export function loadPlanState(sessionName: string): PlanStateOnDisk | null {
|
||||
const path = planStatePath(sessionName);
|
||||
if (!existsSync(path)) return null;
|
||||
try {
|
||||
const raw = readFileSync(path, "utf8");
|
||||
const parsed = JSON.parse(raw) as Partial<PlanStateOnDisk>;
|
||||
if (!parsed || typeof parsed !== "object") return null;
|
||||
if (parsed.version !== 1) return null;
|
||||
if (!Array.isArray(parsed.steps)) return null;
|
||||
if (!Array.isArray(parsed.completedStepIds)) return null;
|
||||
if (typeof parsed.updatedAt !== "string") return null;
|
||||
// Defensive: filter out any malformed step entries so a partially
|
||||
// corrupted file still yields a usable subset.
|
||||
const steps: PlanStep[] = [];
|
||||
for (const s of parsed.steps) {
|
||||
if (!s || typeof s !== "object") continue;
|
||||
const e = s as unknown as Record<string, unknown>;
|
||||
if (typeof e.id !== "string" || !e.id) continue;
|
||||
if (typeof e.title !== "string" || !e.title) continue;
|
||||
if (typeof e.action !== "string" || !e.action) continue;
|
||||
const step: PlanStep = { id: e.id, title: e.title, action: e.action };
|
||||
if (e.risk === "low" || e.risk === "med" || e.risk === "high") step.risk = e.risk;
|
||||
steps.push(step);
|
||||
}
|
||||
if (steps.length === 0) return null;
|
||||
const completedStepIds = parsed.completedStepIds.filter(
|
||||
(id): id is string => typeof id === "string" && id.length > 0,
|
||||
);
|
||||
const out: PlanStateOnDisk = {
|
||||
version: 1,
|
||||
steps,
|
||||
completedStepIds,
|
||||
updatedAt: parsed.updatedAt,
|
||||
};
|
||||
if (typeof parsed.body === "string" && parsed.body) out.body = parsed.body;
|
||||
if (typeof parsed.summary === "string" && parsed.summary) out.summary = parsed.summary;
|
||||
return out;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Persist the current plan state. Called whenever the in-memory plan
|
||||
* meaningfully changes (submit, complete, revise). Best-effort: a
|
||||
* write failure logs to stderr but doesn't propagate — losing the
|
||||
* persisted copy is annoying but shouldn't crash the TUI.
|
||||
*/
|
||||
export function savePlanState(
|
||||
sessionName: string,
|
||||
steps: PlanStep[],
|
||||
completedStepIds: Iterable<string>,
|
||||
extras?: { body?: string; summary?: string },
|
||||
): void {
|
||||
const path = planStatePath(sessionName);
|
||||
try {
|
||||
mkdirSync(dirname(path), { recursive: true });
|
||||
const state: PlanStateOnDisk = {
|
||||
version: 1,
|
||||
steps,
|
||||
completedStepIds: [...completedStepIds],
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
if (extras?.body) state.body = extras.body;
|
||||
if (extras?.summary) state.summary = extras.summary;
|
||||
writeFileSync(path, `${JSON.stringify(state, null, 2)}\n`, "utf8");
|
||||
} catch (err) {
|
||||
process.stderr.write(
|
||||
`▸ plan-store: failed to save plan for "${sessionName}": ${(err as Error).message}\n`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** Remove the persisted plan, if any. Used on cancel / clean reset. */
|
||||
export function clearPlanState(sessionName: string): void {
|
||||
const path = planStatePath(sessionName);
|
||||
try {
|
||||
if (existsSync(path)) unlinkSync(path);
|
||||
} catch {
|
||||
/* nothing to do — leftover file is harmless, will be overwritten next save */
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Move the active plan to a timestamped .done.json archive when the
|
||||
* model has marked every step complete. Future Time-Travel replay
|
||||
* will load these archives; for now the archive just exists as a
|
||||
* historical artifact and frees the active plan.json so the next
|
||||
* session starts fresh.
|
||||
*
|
||||
* Returns the archive path on success, or null if there was nothing
|
||||
* to archive (no active plan) / the rename failed (logged to stderr,
|
||||
* not propagated — losing the archive is annoying but shouldn't
|
||||
* crash the TUI).
|
||||
*
|
||||
* The timestamp uses ISO 8601 with a millisecond suffix and `:` and
|
||||
* `.` swapped for `-` so the filename is filesystem-safe on Windows.
|
||||
* Two archives created within the same millisecond would collide;
|
||||
* we append a short random suffix to dodge that.
|
||||
*/
|
||||
export function archivePlanState(sessionName: string): string | null {
|
||||
const active = planStatePath(sessionName);
|
||||
if (!existsSync(active)) return null;
|
||||
const stamp = new Date().toISOString().replace(/[:.]/g, "-");
|
||||
const suffix = Math.random().toString(36).slice(2, 6);
|
||||
const archive = join(
|
||||
sessionsDir(),
|
||||
`${sanitizeName(sessionName)}.plan.${stamp}-${suffix}.done.json`,
|
||||
);
|
||||
try {
|
||||
renameSync(active, archive);
|
||||
return archive;
|
||||
} catch (err) {
|
||||
process.stderr.write(
|
||||
`▸ plan-store: failed to archive plan for "${sessionName}": ${(err as Error).message}\n`,
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Summary of one archived (completed) plan, as returned by
|
||||
* `listPlanArchives`. The `completedAt` ISO string comes from the
|
||||
* archive file's stored `updatedAt` (or its mtime as fallback) so it
|
||||
* survives across machines / clock skew. `path` is absolute and ready
|
||||
* for a future `/replay` to read directly.
|
||||
*/
|
||||
export interface PlanArchiveSummary {
|
||||
path: string;
|
||||
completedAt: string;
|
||||
steps: PlanStep[];
|
||||
completedStepIds: string[];
|
||||
/** Markdown body, when the archive carried it. */
|
||||
body?: string;
|
||||
/** One-line human-friendly title, when supplied. */
|
||||
summary?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* List all archived `.done.json` files for this session, newest
|
||||
* first. Used by `/plans` to give the user a project-local history.
|
||||
* Cross-project listing is intentionally NOT supported here — a plan
|
||||
* lives next to its session, and resuming it just means switching
|
||||
* back to that project's directory.
|
||||
*
|
||||
* Robust to missing dir / unreadable entries: a corrupt archive is
|
||||
* skipped, not propagated. Worst case the user sees a shorter list
|
||||
* than reality.
|
||||
*/
|
||||
export function listPlanArchives(sessionName: string): PlanArchiveSummary[] {
|
||||
const dir = sessionsDir();
|
||||
if (!existsSync(dir)) return [];
|
||||
const prefix = `${sanitizeName(sessionName)}.plan.`;
|
||||
const suffix = ".done.json";
|
||||
let entries: string[];
|
||||
try {
|
||||
entries = readdirSync(dir);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
const summaries: PlanArchiveSummary[] = [];
|
||||
for (const name of entries) {
|
||||
if (!name.startsWith(prefix) || !name.endsWith(suffix)) continue;
|
||||
const full = join(dir, name);
|
||||
try {
|
||||
const raw = readFileSync(full, "utf8");
|
||||
const parsed = JSON.parse(raw) as Partial<PlanStateOnDisk>;
|
||||
if (parsed.version !== 1) continue;
|
||||
if (!Array.isArray(parsed.steps) || parsed.steps.length === 0) continue;
|
||||
const steps = parsed.steps.filter(
|
||||
(s): s is PlanStep =>
|
||||
!!s &&
|
||||
typeof s === "object" &&
|
||||
typeof (s as PlanStep).id === "string" &&
|
||||
typeof (s as PlanStep).title === "string" &&
|
||||
typeof (s as PlanStep).action === "string",
|
||||
);
|
||||
if (steps.length === 0) continue;
|
||||
const completedStepIds = Array.isArray(parsed.completedStepIds)
|
||||
? parsed.completedStepIds.filter((id): id is string => typeof id === "string" && !!id)
|
||||
: [];
|
||||
// Prefer the file's own updatedAt; fall back to mtime if missing
|
||||
// or unparseable so a hand-edited archive still sorts sensibly.
|
||||
let completedAt = typeof parsed.updatedAt === "string" ? parsed.updatedAt : "";
|
||||
if (!completedAt || Number.isNaN(Date.parse(completedAt))) {
|
||||
try {
|
||||
completedAt = statSync(full).mtime.toISOString();
|
||||
} catch {
|
||||
completedAt = new Date(0).toISOString();
|
||||
}
|
||||
}
|
||||
const entry: PlanArchiveSummary = { path: full, completedAt, steps, completedStepIds };
|
||||
if (typeof parsed.body === "string" && parsed.body) entry.body = parsed.body;
|
||||
if (typeof parsed.summary === "string" && parsed.summary) entry.summary = parsed.summary;
|
||||
summaries.push(entry);
|
||||
} catch {
|
||||
// Skip the corrupt archive entirely.
|
||||
}
|
||||
}
|
||||
summaries.sort((a, b) => b.completedAt.localeCompare(a.completedAt));
|
||||
return summaries;
|
||||
}
|
||||
|
||||
/**
|
||||
* Render `updatedAt` as a short relative-time string for the resume
|
||||
* notice ("2h ago", "3 days ago"). Falls back to the raw ISO string
|
||||
* for anything beyond a week so users don't see misleading
|
||||
* "47 days ago" approximations.
|
||||
*/
|
||||
export function relativeTime(updatedAt: string, now: number = Date.now()): string {
|
||||
const t = Date.parse(updatedAt);
|
||||
if (Number.isNaN(t)) return updatedAt;
|
||||
const diffMs = Math.max(0, now - t);
|
||||
const sec = Math.floor(diffMs / 1000);
|
||||
if (sec < 60) return `${sec}s ago`;
|
||||
const min = Math.floor(sec / 60);
|
||||
if (min < 60) return `${min}m ago`;
|
||||
const hr = Math.floor(min / 60);
|
||||
if (hr < 24) return `${hr}h ago`;
|
||||
const day = Math.floor(hr / 24);
|
||||
if (day < 7) return `${day}d ago`;
|
||||
return updatedAt.slice(0, 10);
|
||||
}
|
||||
+115
-8
@@ -15,9 +15,10 @@
|
||||
|
||||
import { existsSync, readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { ESCALATION_CONTRACT, TUI_FORMATTING_RULES } from "../prompt-fragments.js";
|
||||
import { applyMemoryStack } from "../user-memory.js";
|
||||
|
||||
export const CODE_SYSTEM_PROMPT = `You are Reasonix Code, a coding assistant. You have filesystem tools (read_file, write_file, list_directory, search_files, etc.) rooted at the user's working directory.
|
||||
export const CODE_SYSTEM_PROMPT = `You are Reasonix Code, a coding assistant. You have filesystem tools (read_file, write_file, edit_file, list_directory, directory_tree, search_files, search_content, get_file_info) rooted at the user's working directory, plus run_command / run_background for shell.
|
||||
|
||||
# Cite or shut up — non-negotiable
|
||||
|
||||
@@ -50,6 +51,21 @@ Skip submit_plan for small, obvious changes: one-line typo, clear bug with a cle
|
||||
|
||||
Plan body: one-sentence summary, then a file-by-file breakdown of what you'll change and why, and any risks or open questions. If some decisions are genuinely up to the user (naming, tradeoffs, out-of-scope possibilities), list them in an "Open questions" section — the user sees the plan in a picker and has a text input to answer your questions before approving. Don't pretend certainty you don't have; flagged questions are how the user tells you what they care about. After calling submit_plan, STOP — don't call any more tools, wait for the user's verdict.
|
||||
|
||||
**Do NOT use submit_plan to present A/B/C route menus.** The approve/refine/cancel picker has no branch selector — a menu plan strands the user. For branching decisions, use \`ask_choice\` (see below); only call submit_plan once the user has picked a direction and you have ONE actionable plan.
|
||||
|
||||
# When to ask the user to pick (ask_choice)
|
||||
|
||||
You have an \`ask_choice\` tool. **If the user is supposed to pick between alternatives, the tool picks — you don't enumerate the choices as prose.** Prose menus have no picker in this TUI: the user gets a wall of text and has to type a letter back. The tool fires an arrow-key picker that's strictly better.
|
||||
|
||||
Call it when:
|
||||
- The user has asked for options / doesn't want a recommendation / wants to decide.
|
||||
- You've analyzed multiple approaches and the final call is theirs.
|
||||
- It's a preference fork you can't resolve without them (deployment target, team convention, taste).
|
||||
|
||||
Skip it when one option is clearly correct (just do it, or submit_plan) or a free-form text answer fits (ask in prose).
|
||||
|
||||
Each option: short stable id (A/B/C), one-line title, optional summary. \`allowCustom: true\` when their real answer might not fit. Max 6. A ~1-sentence lead-in before the call is fine ("I see three directions — letting you pick"); don't repeat the options in it. After the call, STOP.
|
||||
|
||||
# Plan mode (/plan)
|
||||
|
||||
The user can ALSO enter "plan mode" via /plan, which is a stronger, explicit constraint:
|
||||
@@ -58,15 +74,17 @@ The user can ALSO enter "plan mode" via /plan, which is a stronger, explicit con
|
||||
- You MUST call submit_plan before anything will execute. Approve exits plan mode; Refine stays in; Cancel exits without implementing.
|
||||
|
||||
|
||||
# Delegating to subagents via Skills (🧬)
|
||||
# Delegating to subagents via Skills
|
||||
|
||||
The pinned Skills index below lists playbooks you can invoke with \`run_skill\`. Skills marked with **🧬** spawn an **isolated subagent** — a fresh child loop that runs the playbook in its own context and returns only the final answer. The subagent's tool calls and reasoning never enter your context, so 🧬 skills are how you keep the main session lean.
|
||||
The pinned Skills index below lists playbooks you can invoke with \`run_skill\`. Entries tagged \`[🧬 subagent]\` spawn an **isolated subagent** — a fresh child loop that runs the playbook in its own context and returns only the final answer. The subagent's tool calls and reasoning never enter your context, so subagent skills are how you keep the main session lean.
|
||||
|
||||
**When you call \`run_skill\`, the \`name\` is ONLY the identifier before the tag** — e.g. \`run_skill({ name: "explore", arguments: "..." })\`, NOT \`"[🧬 subagent] explore"\` and NOT \`"explore [🧬 subagent]"\`. The tag is display sugar; the name argument is just the bare identifier.
|
||||
|
||||
Two built-ins ship by default:
|
||||
- **🧬 explore** — read-only investigation across the codebase. Use when the user says things like "find all places that...", "how does X work across the project", "survey the code for Y". Pass \`arguments\` describing the concrete question.
|
||||
- **🧬 research** — combines web search + code reading. Use for "is X supported by lib Y", "what's the canonical way to Z", "compare our impl to the spec".
|
||||
- **explore** \`[🧬 subagent]\` — read-only investigation across the codebase. Use when the user says things like "find all places that...", "how does X work across the project", "survey the code for Y". Pass \`arguments\` describing the concrete question.
|
||||
- **research** \`[🧬 subagent]\` — combines web search + code reading. Use for "is X supported by lib Y", "what's the canonical way to Z", "compare our impl to the spec".
|
||||
|
||||
When to delegate (call \`run_skill\` with a 🧬 skill):
|
||||
When to delegate (call \`run_skill\` with a subagent skill):
|
||||
- The task would otherwise need >5 file reads or searches.
|
||||
- You only need the conclusion, not the exploration trail.
|
||||
- The work is self-contained (you can describe it in one paragraph).
|
||||
@@ -89,6 +107,15 @@ In those cases, use tools to gather what you need, then reply in prose. No SEARC
|
||||
|
||||
When you do propose edits, the user will review them and decide whether to \`/apply\` or \`/discard\`. Don't assume they'll accept — write as if each edit will be audited, because it will.
|
||||
|
||||
Reasonix runs an **edit gate**. The user's current mode (\`review\` or \`auto\`) decides what happens to your writes; you DO NOT see which mode is active, and you SHOULD NOT ask. Write the same way in both cases.
|
||||
|
||||
- In \`auto\` mode \`edit_file\` / \`write_file\` calls land on disk immediately with an undo window — you'll get the normal "edit blocks: 1/1 applied" style response.
|
||||
- In \`review\` mode EACH \`edit_file\` / \`write_file\` call pauses tool dispatch while the user decides. You'll get one of these responses:
|
||||
- \`"edit blocks: 1/1 applied"\` — user approved it. Continue as normal.
|
||||
- \`"User rejected this edit to <path>. Don't retry the same SEARCH/REPLACE…"\` — user said no to THIS specific edit. Do NOT re-emit the same block, do NOT switch tools to sneak it past the gate (write_file → edit_file, or text-form SEARCH/REPLACE). Either take a clearly different approach or stop and ask the user what they want instead.
|
||||
- Text-form SEARCH/REPLACE blocks in your assistant reply queue for end-of-turn /apply — same "don't retry on rejection" rule.
|
||||
- If the user presses Esc mid-prompt the whole turn is aborted; you won't get another tool response. Don't keep spamming tool calls after an abort.
|
||||
|
||||
# Editing files
|
||||
|
||||
When you've been asked to change a file, output one or more SEARCH/REPLACE blocks in this exact format:
|
||||
@@ -129,11 +156,59 @@ Two different rules depending on which tool:
|
||||
- **Filesystem tools** (\`read_file\`, \`list_directory\`, \`search_files\`, \`edit_file\`, etc.): paths are sandbox-relative. \`/\` means the project root, \`/src/foo.ts\` means \`<project>/src/foo.ts\`. Both relative (\`src/foo.ts\`) and POSIX-absolute (\`/src/foo.ts\`) forms work.
|
||||
- **\`run_command\`**: the command runs in a real OS shell with cwd pinned to the project root. Paths inside the shell command are interpreted by THAT shell, not by us. **Never use leading \`/\` in run_command arguments** — Windows treats \`/tests\` as drive-root \`F:\\tests\` (non-existent), POSIX shells treat it as filesystem root. Use plain relative paths (\`tests\`, \`./tests\`, \`src/loop.ts\`) instead.
|
||||
|
||||
# When the user wants to switch project / working directory
|
||||
|
||||
If the user asks to switch / change / open a different directory or project ("切换到...", "switch to ...", "let's work in ...", "open the X project"), call **\`change_workspace\`** with the absolute target path. The tool always requires the user's explicit approval via a TUI modal — your call surfaces a "switch / deny" prompt, and STOPS your turn until they pick. After approval the filesystem / shell / memory tools re-register against the new root and your subsequent calls land there.
|
||||
|
||||
Hard rules:
|
||||
- Do NOT try to switch via \`run_command\` (\`cd\`, \`pushd\`, etc.) — your tool sandbox is pinned and \`cd\` inside one shell call doesn't carry to the next.
|
||||
- Do NOT chain other tool calls in the same turn as \`change_workspace\` — wait for the user's confirmation. Their next message will tell you whether the switch happened.
|
||||
- Do NOT call \`change_workspace\` to "preview" a sibling directory; only when the user explicitly asked to change projects.
|
||||
- The user can also type \`/cwd <path>\` themselves — fine, you'll see the new root take effect on the next turn either way.
|
||||
|
||||
# Foreground vs. background commands
|
||||
|
||||
You have TWO tools for running shell commands, and picking the right one is non-negotiable:
|
||||
|
||||
- \`run_command\` — blocks until the process exits. Use for: **tests, builds, lints, typechecks, git operations, one-shot scripts**. Anything that naturally returns in under a minute.
|
||||
- \`run_background\` — spawns and detaches after a brief startup window. Use for: **dev servers, watchers, any command with "dev" / "serve" / "watch" / "start" in the name**. Examples: \`npm run dev\`, \`pnpm dev\`, \`yarn start\`, \`vite\`, \`next dev\`, \`uvicorn app:app --reload\`, \`flask run\`, \`python -m http.server\`, \`cargo watch\`, \`tsc --watch\`, \`webpack serve\`.
|
||||
|
||||
**Never use run_command for a dev server.** It will block for 60s, time out, and the user will see a frozen tool call while the server was actually running fine. Always \`run_background\`, then \`job_output\` to peek at the logs when you need to verify something.
|
||||
|
||||
After \`run_background\`, tools available to you:
|
||||
- \`job_output(jobId, tailLines?)\` — read recent logs to verify startup / debug errors.
|
||||
- \`list_jobs\` — see every job this session (running + exited).
|
||||
- \`stop_job(jobId)\` — SIGTERM → SIGKILL after grace. Stop before switching port / config.
|
||||
|
||||
Don't re-start an already-running dev server — call \`list_jobs\` first when in doubt.
|
||||
|
||||
# Scope discipline on "run it" / "start it" requests
|
||||
|
||||
When the user's request is to **run / start / launch / serve / boot up** something, your job is ONLY:
|
||||
|
||||
1. Start it (\`run_background\` for dev servers, \`run_command\` for one-shots).
|
||||
2. Verify it came up (read a ready signal via \`job_output\`, or fetch the URL with \`web_fetch\` if they want you to confirm).
|
||||
3. Report what's running, where (URL / port / pid), and STOP.
|
||||
|
||||
Do NOT, in the same turn:
|
||||
- Run \`tsc\` / type-checkers / linters unless the user asked for it.
|
||||
- Scan for bugs to "proactively" fix. The page rendering is success.
|
||||
- Clean up unused imports, dead code, or refactor "while you're here."
|
||||
- Edit files to improve anything the user didn't mention.
|
||||
|
||||
If you notice an obvious issue, MENTION it in one sentence and wait for the user to say "fix it." The cost of over-eagerness is real: you burn tokens, make surprise edits the user didn't want, and chain into cascading "fix the new error I just introduced" loops. The storm-breaker will cut you off, but the user still sees the mess.
|
||||
|
||||
"It works" is the end state. Resist the urge to polish.
|
||||
|
||||
# Style
|
||||
|
||||
- Show edits; don't narrate them in prose. "Here's the fix:" is enough.
|
||||
- One short paragraph explaining *why*, then the blocks.
|
||||
- If you need to explore first (list / read / search), do it with tool calls before writing any prose — silence while exploring is fine.
|
||||
|
||||
${ESCALATION_CONTRACT}
|
||||
|
||||
${TUI_FORMATTING_RULES}
|
||||
`;
|
||||
|
||||
/**
|
||||
@@ -145,8 +220,40 @@ Two different rules depending on which tool:
|
||||
* Stacking order (stable for cache prefix):
|
||||
* base prompt → REASONIX.md → global MEMORY.md → project MEMORY.md → .gitignore
|
||||
*/
|
||||
export function codeSystemPrompt(rootDir: string): string {
|
||||
const withMemory = applyMemoryStack(CODE_SYSTEM_PROMPT, rootDir);
|
||||
/**
|
||||
* Routing fragment appended to the code-mode system prompt when the
|
||||
* project has a semantic index built. Without this nudge the model
|
||||
* defaults to grep (`search_content`) for every query — semantic
|
||||
* search loses the "first attempt" battle on token-rich phrasings
|
||||
* even when the question is descriptive.
|
||||
*
|
||||
* Kept short and explicit: rules over rationale. The model that needs
|
||||
* this hint isn't reading three paragraphs of "why semantic search
|
||||
* is good"; it needs a clear if/else.
|
||||
*/
|
||||
const SEMANTIC_SEARCH_ROUTING = `
|
||||
|
||||
# Search routing
|
||||
|
||||
You have BOTH \`semantic_search\` (vector index) and \`search_content\` (literal grep).
|
||||
|
||||
- **Descriptive queries** ("where do we handle X", "which file owns Y", "how does Z work", "find the logic that does …", "the code responsible for …") → call \`semantic_search\` FIRST. It indexes the project by meaning, so it finds the right file even when your phrasing shares no tokens with the code.
|
||||
- **Exact-token queries** (a specific identifier, regex, or "find every call to foo") → call \`search_content\`.
|
||||
|
||||
If \`semantic_search\` returns nothing useful (low scores, off-topic), THEN fall back to \`search_content\`. Don't go the other way — grepping a paraphrased question wastes turns.`;
|
||||
|
||||
export interface CodeSystemPromptOptions {
|
||||
/** True when semantic_search is registered for this run. Adds an
|
||||
* explicit routing fragment so the model picks it for intent-style
|
||||
* queries instead of defaulting to grep. */
|
||||
hasSemanticSearch?: boolean;
|
||||
}
|
||||
|
||||
export function codeSystemPrompt(rootDir: string, opts: CodeSystemPromptOptions = {}): string {
|
||||
const base = opts.hasSemanticSearch
|
||||
? `${CODE_SYSTEM_PROMPT}${SEMANTIC_SEARCH_ROUTING}`
|
||||
: CODE_SYSTEM_PROMPT;
|
||||
const withMemory = applyMemoryStack(base, rootDir);
|
||||
const gitignorePath = join(rootDir, ".gitignore");
|
||||
if (!existsSync(gitignorePath)) return withMemory;
|
||||
let content: string;
|
||||
|
||||
+157
-2
@@ -18,8 +18,52 @@ import { chmodSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
|
||||
/** One of the preset bundles (model + harvest + branch combo). */
|
||||
export type PresetName = "fast" | "smart" | "max";
|
||||
/**
|
||||
* Preset names — three model-commitment levels.
|
||||
* - `auto` — flash baseline + auto-escalate to pro on hard turns
|
||||
* (NEEDS_PRO marker / failure-count threshold both fire).
|
||||
* Default. Closest match to the legacy `smart` preset.
|
||||
* - `flash` — flash always. No auto-escalation. `/pro` still works
|
||||
* for one-shot manual escalation. Cheapest predictable.
|
||||
* - `pro` — pro always. No downgrade. ~3× cost vs flash at the
|
||||
* 2026-04 discount rate; more outside the window.
|
||||
*
|
||||
* Legacy `fast | smart | max` names stay in the union for back-compat
|
||||
* with existing `~/.reasonix/config.json` files; resolvePreset() maps
|
||||
* them to the new semantics.
|
||||
*/
|
||||
export type PresetName = "auto" | "flash" | "pro" | "fast" | "smart" | "max";
|
||||
|
||||
/**
|
||||
* How `reasonix code` handles model-issued tool calls. Two axes folded
|
||||
* into one enum because users think about "how trusting am I right now?"
|
||||
* as a single dial, not as "writes vs shell" pairs.
|
||||
*
|
||||
* - "review" — queue edits into pendingEdits (user /apply or `y` to
|
||||
* commit); shell commands NOT on the read-only allowlist
|
||||
* hit ShellConfirm. Default.
|
||||
* - "auto" — apply edits immediately, snapshot for /undo, show a
|
||||
* short undo banner. Shell still goes through ShellConfirm
|
||||
* for non-allowlisted commands.
|
||||
* - "yolo" — apply edits immediately AND auto-approve every shell
|
||||
* command. No prompts at all. Use when you trust the
|
||||
* current direction and just want to iterate fast; /undo
|
||||
* still rolls back individual edit batches.
|
||||
*
|
||||
* Persisted so `/mode <x>` survives a relaunch. Missing → "review".
|
||||
*
|
||||
* Codex-equivalence note: review ≈ untrusted, auto ≈ on-request,
|
||||
* yolo ≈ never.
|
||||
*/
|
||||
export type EditMode = "review" | "auto" | "yolo";
|
||||
|
||||
/**
|
||||
* reasoning_effort cap for the model. "max" is the agent-class default;
|
||||
* "high" is cheaper / faster. Persisted so `/effort high` survives a
|
||||
* relaunch — earlier versions silently reverted to "max" on every new
|
||||
* session, which burned budget unexpectedly.
|
||||
*/
|
||||
export type ReasoningEffort = "high" | "max";
|
||||
|
||||
export interface ReasonixConfig {
|
||||
apiKey?: string;
|
||||
@@ -29,6 +73,22 @@ export interface ReasonixConfig {
|
||||
* Maps to model + harvest + branch combos (see presets.ts). Missing → "fast".
|
||||
*/
|
||||
preset?: PresetName;
|
||||
/**
|
||||
* Edit-gate mode for `reasonix code`. See EditMode doc. Absent → "review".
|
||||
*/
|
||||
editMode?: EditMode;
|
||||
/**
|
||||
* Set to `true` the first time we've shown the "Shift+Tab cycles
|
||||
* review/AUTO" onboarding tip in `reasonix code`. Once seen, we stop
|
||||
* posting the tip — the bottom status bar carries the knowledge
|
||||
* forward without further nagging.
|
||||
*/
|
||||
editModeHintShown?: boolean;
|
||||
/**
|
||||
* Last reasoning_effort chosen via `/effort`. Loaded on launch so
|
||||
* "high" stays "high" — default is "max" when unset.
|
||||
*/
|
||||
reasoningEffort?: ReasoningEffort;
|
||||
/**
|
||||
* Default MCP server specs to bridge on every `reasonix chat`, in the
|
||||
* same `"name=cmd args..."` format that `--mcp` takes. Stored as strings
|
||||
@@ -146,6 +206,101 @@ export function addProjectShellAllowed(
|
||||
writeConfig(cfg, path);
|
||||
}
|
||||
|
||||
/**
|
||||
* Drop one prefix from the project's shell-allowed list. Returns true
|
||||
* when the prefix was present (and removed), false when it wasn't —
|
||||
* lets `/permissions remove` distinguish "removed" from "no such entry"
|
||||
* without a separate read. Match is exact after trim; we deliberately
|
||||
* do NOT prefix-match here (e.g. removing `git` shouldn't also drop
|
||||
* `git push origin main` if the user added both).
|
||||
*/
|
||||
export function removeProjectShellAllowed(
|
||||
rootDir: string,
|
||||
prefix: string,
|
||||
path: string = defaultConfigPath(),
|
||||
): boolean {
|
||||
const trimmed = prefix.trim();
|
||||
if (!trimmed) return false;
|
||||
const cfg = readConfig(path);
|
||||
const existing = cfg.projects?.[rootDir]?.shellAllowed ?? [];
|
||||
if (!existing.includes(trimmed)) return false;
|
||||
const next = existing.filter((p) => p !== trimmed);
|
||||
if (!cfg.projects) cfg.projects = {};
|
||||
if (!cfg.projects[rootDir]) cfg.projects[rootDir] = {};
|
||||
cfg.projects[rootDir].shellAllowed = next;
|
||||
writeConfig(cfg, path);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wipe every persisted shell-allow entry for a project. Returns the
|
||||
* number of prefixes that were dropped — zero if nothing was stored.
|
||||
*/
|
||||
export function clearProjectShellAllowed(
|
||||
rootDir: string,
|
||||
path: string = defaultConfigPath(),
|
||||
): number {
|
||||
const cfg = readConfig(path);
|
||||
const existing = cfg.projects?.[rootDir]?.shellAllowed ?? [];
|
||||
if (existing.length === 0) return 0;
|
||||
if (!cfg.projects) cfg.projects = {};
|
||||
if (!cfg.projects[rootDir]) cfg.projects[rootDir] = {};
|
||||
cfg.projects[rootDir].shellAllowed = [];
|
||||
writeConfig(cfg, path);
|
||||
return existing.length;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the persisted edit-mode. Unknown values fall back to "review" so
|
||||
* a user who hand-edits the file into an invalid state still gets the
|
||||
* safe default. `reasonix code` calls this at launch and the App lets
|
||||
* `/mode` / Shift+Tab flip it.
|
||||
*/
|
||||
export function loadEditMode(path: string = defaultConfigPath()): EditMode {
|
||||
const v = readConfig(path).editMode;
|
||||
return v === "auto" ? "auto" : "review";
|
||||
}
|
||||
|
||||
/** Persist the edit mode so `/mode auto` survives a relaunch. */
|
||||
export function saveEditMode(mode: EditMode, path: string = defaultConfigPath()): void {
|
||||
const cfg = readConfig(path);
|
||||
cfg.editMode = mode;
|
||||
writeConfig(cfg, path);
|
||||
}
|
||||
|
||||
/** True when the onboarding tip for the review/AUTO gate has been shown. */
|
||||
export function editModeHintShown(path: string = defaultConfigPath()): boolean {
|
||||
return readConfig(path).editModeHintShown === true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the persisted reasoning_effort. Unknown / missing values fall
|
||||
* back to "max" so the agent-class default is never silently overridden
|
||||
* by a hand-edited bad value in config.json.
|
||||
*/
|
||||
export function loadReasoningEffort(path: string = defaultConfigPath()): ReasoningEffort {
|
||||
const v = readConfig(path).reasoningEffort;
|
||||
return v === "high" ? "high" : "max";
|
||||
}
|
||||
|
||||
/** Persist the reasoning_effort cap so `/effort high` survives a relaunch. */
|
||||
export function saveReasoningEffort(
|
||||
effort: ReasoningEffort,
|
||||
path: string = defaultConfigPath(),
|
||||
): void {
|
||||
const cfg = readConfig(path);
|
||||
cfg.reasoningEffort = effort;
|
||||
writeConfig(cfg, path);
|
||||
}
|
||||
|
||||
/** Mark the onboarding tip as shown so subsequent launches skip it. */
|
||||
export function markEditModeHintShown(path: string = defaultConfigPath()): void {
|
||||
const cfg = readConfig(path);
|
||||
if (cfg.editModeHintShown === true) return;
|
||||
cfg.editModeHintShown = true;
|
||||
writeConfig(cfg, path);
|
||||
}
|
||||
|
||||
export function isPlausibleKey(key: string): boolean {
|
||||
const trimmed = key.trim();
|
||||
return /^sk-[A-Za-z0-9_-]{16,}$/.test(trimmed);
|
||||
|
||||
+15
-1
@@ -78,7 +78,14 @@ export async function harvest(
|
||||
const trimmed = reasoningContent.trim();
|
||||
if (trimmed.length < minLen) return emptyPlanState();
|
||||
|
||||
const model = options.model ?? "deepseek-chat";
|
||||
// Harvest is schema-constrained JSON extraction, not agent reasoning.
|
||||
// Default to v4-flash with `thinking: "disabled"` below — a few
|
||||
// hundred output tokens fit easily in the non-thinking budget, the
|
||||
// reply comes back ~10× faster than thinking mode, and the per-turn
|
||||
// cost stays an asterisk next to the main loop's spend rather than a
|
||||
// visible slice of it. (`deepseek-chat` was the compat alias for this
|
||||
// same route; we now name the real model.)
|
||||
const model = options.model ?? "deepseek-v4-flash";
|
||||
const maxItems = options.maxItems ?? 5;
|
||||
const maxItemLen = options.maxItemLen ?? 80;
|
||||
const system = SYSTEM_PROMPT.replace("{maxItems}", String(maxItems)).replace(
|
||||
@@ -96,6 +103,13 @@ export async function harvest(
|
||||
responseFormat: { type: "json_object" },
|
||||
temperature: 0,
|
||||
maxTokens: 600,
|
||||
// Pin mode + effort so a future default-model swap (e.g. someone
|
||||
// sets `options.model = "deepseek-v4-pro"`) can't accidentally
|
||||
// turn this micro-extraction into a multi-thousand-reasoning-
|
||||
// token call. DeepSeek ignores these on non-thinking models, so
|
||||
// the request stays valid regardless of the chosen model.
|
||||
thinking: "disabled",
|
||||
reasoningEffort: "high",
|
||||
signal,
|
||||
});
|
||||
return parsePlanState(resp.content, maxItems, maxItemLen);
|
||||
|
||||
+17
-3
@@ -83,8 +83,15 @@ export { registerFilesystemTools } from "./tools/filesystem.js";
|
||||
export type { FilesystemToolsOptions } from "./tools/filesystem.js";
|
||||
export { registerMemoryTools } from "./tools/memory.js";
|
||||
export type { MemoryToolsOptions } from "./tools/memory.js";
|
||||
export { PlanProposedError, registerPlanTool } from "./tools/plan.js";
|
||||
export type { PlanToolOptions } from "./tools/plan.js";
|
||||
export { ChoiceRequestedError, registerChoiceTool } from "./tools/choice.js";
|
||||
export type { ChoiceOption, ChoiceToolOptions } from "./tools/choice.js";
|
||||
export {
|
||||
PlanCheckpointError,
|
||||
PlanProposedError,
|
||||
PlanRevisionProposedError,
|
||||
registerPlanTool,
|
||||
} from "./tools/plan.js";
|
||||
export type { PlanStep, PlanStepRisk, PlanToolOptions, StepCompletion } from "./tools/plan.js";
|
||||
export { forkRegistryExcluding, registerSubagentTool } from "./tools/subagent.js";
|
||||
export type {
|
||||
SubagentEvent,
|
||||
@@ -193,6 +200,8 @@ export { StdioTransport } from "./mcp/stdio.js";
|
||||
export type { McpTransport, StdioTransportOptions } from "./mcp/stdio.js";
|
||||
export { SseTransport } from "./mcp/sse.js";
|
||||
export type { SseTransportOptions } from "./mcp/sse.js";
|
||||
export { StreamableHttpTransport } from "./mcp/streamable-http.js";
|
||||
export type { StreamableHttpTransportOptions } from "./mcp/streamable-http.js";
|
||||
export {
|
||||
DEFAULT_MAX_RESULT_CHARS,
|
||||
DEFAULT_MAX_RESULT_TOKENS,
|
||||
@@ -203,7 +212,12 @@ export {
|
||||
} from "./mcp/registry.js";
|
||||
export type { BridgeOptions, BridgeResult, FlattenOptions } from "./mcp/registry.js";
|
||||
export { parseMcpSpec } from "./mcp/spec.js";
|
||||
export type { McpSpec, StdioMcpSpec, SseMcpSpec } from "./mcp/spec.js";
|
||||
export type {
|
||||
McpSpec,
|
||||
SseMcpSpec,
|
||||
StdioMcpSpec,
|
||||
StreamableHttpMcpSpec,
|
||||
} from "./mcp/spec.js";
|
||||
export { inspectMcpServer } from "./mcp/inspect.js";
|
||||
export type { InspectionReport, SectionResult } from "./mcp/inspect.js";
|
||||
|
||||
|
||||
@@ -0,0 +1,246 @@
|
||||
/**
|
||||
* Build + query orchestrator for the semantic index.
|
||||
*
|
||||
* `buildIndex(root, opts)` walks the project, embeds new/changed
|
||||
* files, and persists. It is incremental by default — files whose
|
||||
* mtime hasn't moved since the last build are skipped, which is the
|
||||
* main reason the index can be kept fresh as a `Stop` hook or a
|
||||
* pre-`reasonix code` warm-up.
|
||||
*
|
||||
* `querySemantic(root, query, opts)` opens the on-disk index, embeds
|
||||
* the query, and returns top-K hits formatted for tool output. No
|
||||
* mutation; safe to call from any tool fn.
|
||||
*/
|
||||
|
||||
import { promises as fs } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { walkChunks } from "./chunker.js";
|
||||
import type { CodeChunk } from "./chunker.js";
|
||||
import { embed, embedAll, probeOllama } from "./embedding.js";
|
||||
import type { EmbedOptions } from "./embedding.js";
|
||||
import { normalize, openStore } from "./store.js";
|
||||
import type { IndexEntry, SearchHit } from "./store.js";
|
||||
|
||||
/** Default index dir relative to the project root. */
|
||||
export const INDEX_DIR_NAME = path.join(".reasonix", "semantic");
|
||||
|
||||
export interface BuildOptions extends EmbedOptions {
|
||||
/** Skip files larger than this many bytes. Default 256 KB. */
|
||||
maxFileBytes?: number;
|
||||
/** Lines per window. Default 60. */
|
||||
windowLines?: number;
|
||||
/** Window overlap. Default 12. */
|
||||
overlap?: number;
|
||||
/** Force a full rebuild (drop the existing index first). */
|
||||
rebuild?: boolean;
|
||||
/** Progress callback for the CLI to render counters. */
|
||||
onProgress?: (info: BuildProgress) => void;
|
||||
}
|
||||
|
||||
export interface BuildProgress {
|
||||
phase: "scan" | "embed" | "write" | "done";
|
||||
filesScanned?: number;
|
||||
chunksTotal?: number;
|
||||
chunksDone?: number;
|
||||
filesSkipped?: number;
|
||||
filesChanged?: number;
|
||||
}
|
||||
|
||||
export interface BuildResult {
|
||||
filesScanned: number;
|
||||
filesChanged: number;
|
||||
chunksAdded: number;
|
||||
chunksRemoved: number;
|
||||
/** Chunks that failed to embed (Ollama 500, transient errors) and
|
||||
* were skipped. Reported in the success line so users notice. */
|
||||
chunksSkipped: number;
|
||||
durationMs: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build (or incrementally update) the semantic index for `root`.
|
||||
* Probes Ollama first so a missing daemon fails before any chunking.
|
||||
*/
|
||||
export async function buildIndex(root: string, opts: BuildOptions = {}): Promise<BuildResult> {
|
||||
const t0 = Date.now();
|
||||
const indexDir = path.join(root, INDEX_DIR_NAME);
|
||||
|
||||
const probe = await probeOllama({ baseUrl: opts.baseUrl, signal: opts.signal });
|
||||
if (!probe.ok) {
|
||||
throw new Error(
|
||||
`Ollama is not reachable: ${probe.error}. Install from https://ollama.com, then \`ollama serve\` and \`ollama pull ${opts.model ?? "nomic-embed-text"}\`.`,
|
||||
);
|
||||
}
|
||||
|
||||
const model = opts.model ?? process.env.REASONIX_EMBED_MODEL ?? "nomic-embed-text";
|
||||
const store = await openStore(indexDir, model);
|
||||
if (opts.rebuild) await store.wipe();
|
||||
|
||||
// Snapshot the index's per-file mtimes so we can detect (a) changed
|
||||
// files (mtime moved) and (b) deleted files (path no longer exists
|
||||
// on disk after the walk).
|
||||
const lastMtimes = store.fileMtimes();
|
||||
const seenPaths = new Set<string>();
|
||||
|
||||
// Phase 1 — scan + chunk + collect mtime per file. Buffer chunks
|
||||
// by file because we need to drop+re-add per file when its mtime
|
||||
// changes (a partial update would leave stale chunks).
|
||||
const fileChunks = new Map<string, { chunks: CodeChunk[]; mtimeMs: number }>();
|
||||
let filesScanned = 0;
|
||||
let filesSkipped = 0;
|
||||
for await (const chunk of walkChunks(root, {
|
||||
windowLines: opts.windowLines,
|
||||
overlap: opts.overlap,
|
||||
maxFileBytes: opts.maxFileBytes,
|
||||
})) {
|
||||
seenPaths.add(chunk.path);
|
||||
let bucket = fileChunks.get(chunk.path);
|
||||
if (!bucket) {
|
||||
filesScanned++;
|
||||
const abs = path.join(root, chunk.path);
|
||||
let mtimeMs = 0;
|
||||
try {
|
||||
const stat = await fs.stat(abs);
|
||||
mtimeMs = stat.mtimeMs;
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
const last = lastMtimes.get(chunk.path);
|
||||
if (last !== undefined && last === mtimeMs && !opts.rebuild) {
|
||||
filesSkipped++;
|
||||
continue; // Unchanged — skip embedding.
|
||||
}
|
||||
bucket = { chunks: [], mtimeMs };
|
||||
fileChunks.set(chunk.path, bucket);
|
||||
}
|
||||
bucket.chunks.push(chunk);
|
||||
opts.onProgress?.({ phase: "scan", filesScanned });
|
||||
}
|
||||
|
||||
// Phase 2 — drop entries for files that disappeared (rename/delete).
|
||||
const deletedPaths: string[] = [];
|
||||
for (const oldPath of lastMtimes.keys()) {
|
||||
if (!seenPaths.has(oldPath)) deletedPaths.push(oldPath);
|
||||
}
|
||||
// Files whose chunks we re-built also need their old entries
|
||||
// evicted before the new ones are inserted, otherwise the index
|
||||
// grows duplicate snippets for the same range.
|
||||
const replacePaths = [...fileChunks.keys()].filter((p) => lastMtimes.has(p));
|
||||
const removed = await store.remove([...deletedPaths, ...replacePaths]);
|
||||
|
||||
// Phase 3 — embed buffered chunks file by file. Sequential per
|
||||
// file so the progress counter advances visibly; embedAll is
|
||||
// sequential internally (Ollama serializes anyway). Per-chunk
|
||||
// failures (Ollama 500, transient errors) are logged + skipped
|
||||
// via embedAll's null-slot convention so a single bad chunk
|
||||
// doesn't kill a long-running build.
|
||||
let chunksAdded = 0;
|
||||
let chunksSkipped = 0;
|
||||
const filesChanged = fileChunks.size;
|
||||
let chunksTotal = 0;
|
||||
for (const { chunks } of fileChunks.values()) chunksTotal += chunks.length;
|
||||
let chunksDone = 0;
|
||||
for (const [, bucket] of fileChunks) {
|
||||
if (bucket.chunks.length === 0) continue;
|
||||
const texts = bucket.chunks.map((c) => c.text);
|
||||
const vectors = await embedAll(texts, {
|
||||
...opts,
|
||||
onProgress: (done, total) => {
|
||||
opts.onProgress?.({
|
||||
phase: "embed",
|
||||
filesScanned,
|
||||
filesChanged,
|
||||
chunksTotal,
|
||||
chunksDone: chunksDone + done,
|
||||
});
|
||||
if (done === total) chunksDone += total;
|
||||
},
|
||||
onError: (idx, err) => {
|
||||
chunksSkipped++;
|
||||
const c = bucket.chunks[idx];
|
||||
const where = c ? `${c.path}:${c.startLine}-${c.endLine}` : `chunk #${idx}`;
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
// stderr only — non-fatal warnings shouldn't pollute stdout
|
||||
// (which the rest of the CLI keeps clean for piping).
|
||||
process.stderr.write(`\n ! skipped ${where}: ${msg}\n`);
|
||||
},
|
||||
});
|
||||
const entries: IndexEntry[] = [];
|
||||
for (let i = 0; i < bucket.chunks.length; i++) {
|
||||
const vec = vectors[i];
|
||||
if (!vec) continue; // skipped due to per-chunk error
|
||||
const c = bucket.chunks[i];
|
||||
if (!c) continue;
|
||||
normalize(vec);
|
||||
entries.push({
|
||||
path: c.path,
|
||||
startLine: c.startLine,
|
||||
endLine: c.endLine,
|
||||
text: c.text,
|
||||
embedding: vec,
|
||||
mtimeMs: bucket.mtimeMs,
|
||||
});
|
||||
}
|
||||
if (entries.length > 0) await store.add(entries);
|
||||
chunksAdded += entries.length;
|
||||
}
|
||||
|
||||
opts.onProgress?.({
|
||||
phase: "done",
|
||||
filesScanned,
|
||||
filesSkipped,
|
||||
filesChanged,
|
||||
chunksTotal,
|
||||
chunksDone,
|
||||
});
|
||||
|
||||
return {
|
||||
filesScanned,
|
||||
filesChanged,
|
||||
chunksAdded,
|
||||
chunksRemoved: removed,
|
||||
chunksSkipped,
|
||||
durationMs: Date.now() - t0,
|
||||
};
|
||||
}
|
||||
|
||||
export interface QueryOptions extends EmbedOptions {
|
||||
topK?: number;
|
||||
/** Drop hits below this cosine score. Default 0.3 — anything weaker is noise. */
|
||||
minScore?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Embed `query` and return ranked hits from the index. Returns
|
||||
* `null` when no index exists for `root` so the caller can decide
|
||||
* whether to fall back to grep + a "run reasonix index" hint.
|
||||
*/
|
||||
export async function querySemantic(
|
||||
root: string,
|
||||
query: string,
|
||||
opts: QueryOptions = {},
|
||||
): Promise<SearchHit[] | null> {
|
||||
const indexDir = path.join(root, INDEX_DIR_NAME);
|
||||
const model = opts.model ?? process.env.REASONIX_EMBED_MODEL ?? "nomic-embed-text";
|
||||
const store = await openStore(indexDir, model);
|
||||
if (store.empty) return null;
|
||||
const qvec = await embed(query, opts);
|
||||
normalize(qvec);
|
||||
return store.search(qvec, opts.topK ?? 8, opts.minScore ?? 0.3);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cheap synchronous-ish probe — returns true if the index dir
|
||||
* contains an index.meta.json. Used to gate `semantic_search` tool
|
||||
* registration: no index → no tool (model can't call something it
|
||||
* can't use).
|
||||
*/
|
||||
export async function indexExists(root: string): Promise<boolean> {
|
||||
const meta = path.join(root, INDEX_DIR_NAME, "index.meta.json");
|
||||
try {
|
||||
await fs.access(meta);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,319 @@
|
||||
/**
|
||||
* Code chunker — walks a directory and splits source files into
|
||||
* embedding-sized windows with `{path, startLine, endLine, text}`
|
||||
* metadata so semantic-search results carry a precise file:line
|
||||
* citation back into the conversation.
|
||||
*
|
||||
* Why line-window (not AST) for MVP:
|
||||
* - Language-agnostic: works on TS, Py, Rust, Go, Markdown,
|
||||
* config files — no per-language parser to ship and maintain.
|
||||
* - Predictable cost: a 500-line file produces ~10 chunks at
|
||||
* `windowLines=60, overlap=12`. Embedding cost scales linearly
|
||||
* with file size, no surprises.
|
||||
* - Cite-friendly: every chunk has exact line range. Click-through
|
||||
* in the UI is `path:startLine`.
|
||||
*
|
||||
* AST-aware chunking (split per function/class) is a real upgrade
|
||||
* for retrieval quality and is on the post-MVP list.
|
||||
*/
|
||||
|
||||
import { promises as fs } from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
export interface CodeChunk {
|
||||
/** Path relative to the index root, forward slashes. Stable across OS. */
|
||||
path: string;
|
||||
/** 1-based, inclusive. */
|
||||
startLine: number;
|
||||
endLine: number;
|
||||
text: string;
|
||||
}
|
||||
|
||||
export interface ChunkOptions {
|
||||
/** Lines per window. Default 60. */
|
||||
windowLines?: number;
|
||||
/** Lines of overlap between consecutive windows. Default 12. */
|
||||
overlap?: number;
|
||||
/** Skip files larger than this (bytes). Default 256 KB. */
|
||||
maxFileBytes?: number;
|
||||
/**
|
||||
* Hard ceiling on chunk text length, in characters. A 60-line slice
|
||||
* through a JSON blob or minified bundle can blow past nomic-embed-
|
||||
* text's context window (8K tokens, ~32K chars worst-case but as
|
||||
* little as 8K chars for non-English / dense token streams).
|
||||
* Default 4000 — comfortably under 1024 tokens for most code, with
|
||||
* room to spare for tokenizers that fragment unicode aggressively.
|
||||
*/
|
||||
maxChunkChars?: number;
|
||||
}
|
||||
|
||||
/** Default character cap per chunk — sized for nomic-embed-text. */
|
||||
export const DEFAULT_MAX_CHUNK_CHARS = 4000;
|
||||
|
||||
/**
|
||||
* Default skip-list. Mirrors what `directory_tree` already prunes
|
||||
* plus binary extensions that have zero retrieval value (and waste
|
||||
* embedding tokens). Keep this in sync with src/tools/filesystem.ts
|
||||
* if either drifts.
|
||||
*/
|
||||
const SKIP_DIRS: ReadonlySet<string> = new Set([
|
||||
"node_modules",
|
||||
".git",
|
||||
"dist",
|
||||
"build",
|
||||
"out",
|
||||
".next",
|
||||
".nuxt",
|
||||
"target",
|
||||
".venv",
|
||||
"venv",
|
||||
"__pycache__",
|
||||
".pytest_cache",
|
||||
".mypy_cache",
|
||||
".cache",
|
||||
"coverage",
|
||||
".turbo",
|
||||
".vercel",
|
||||
".reasonix",
|
||||
]);
|
||||
|
||||
const SKIP_FILES: ReadonlySet<string> = new Set([
|
||||
"package-lock.json",
|
||||
"yarn.lock",
|
||||
"pnpm-lock.yaml",
|
||||
"Cargo.lock",
|
||||
"poetry.lock",
|
||||
"Pipfile.lock",
|
||||
"go.sum",
|
||||
".DS_Store",
|
||||
]);
|
||||
|
||||
const BINARY_EXTS: ReadonlySet<string> = new Set([
|
||||
// Images
|
||||
".png",
|
||||
".jpg",
|
||||
".jpeg",
|
||||
".gif",
|
||||
".webp",
|
||||
".bmp",
|
||||
".ico",
|
||||
".tiff",
|
||||
// Fonts
|
||||
".woff",
|
||||
".woff2",
|
||||
".ttf",
|
||||
".otf",
|
||||
".eot",
|
||||
// Archives / binaries
|
||||
".zip",
|
||||
".tar",
|
||||
".gz",
|
||||
".rar",
|
||||
".7z",
|
||||
".exe",
|
||||
".dll",
|
||||
".so",
|
||||
".dylib",
|
||||
".class",
|
||||
".jar",
|
||||
".wasm",
|
||||
".o",
|
||||
".a",
|
||||
// Media
|
||||
".mp3",
|
||||
".mp4",
|
||||
".wav",
|
||||
".ogg",
|
||||
".webm",
|
||||
".mov",
|
||||
// Other
|
||||
".pdf",
|
||||
".sqlite",
|
||||
".db",
|
||||
]);
|
||||
|
||||
/**
|
||||
* Split file content into overlapping line windows. `overlap`
|
||||
* preserves context across chunk boundaries — a function whose
|
||||
* signature is on the boundary still appears in two adjacent chunks
|
||||
* so a query about it ranks both.
|
||||
*
|
||||
* Any window whose text exceeds `maxChunkChars` is post-split into
|
||||
* multiple sub-chunks at line boundaries (or hard-truncated for a
|
||||
* single overlong line) so every yielded chunk is safe to embed.
|
||||
*/
|
||||
export function chunkText(
|
||||
text: string,
|
||||
filePath: string,
|
||||
windowLines: number,
|
||||
overlap: number,
|
||||
maxChunkChars: number = DEFAULT_MAX_CHUNK_CHARS,
|
||||
): CodeChunk[] {
|
||||
const lines = text.split(/\r?\n/);
|
||||
if (lines.length === 0 || (lines.length === 1 && lines[0] === "")) return [];
|
||||
const stride = Math.max(1, windowLines - overlap);
|
||||
const chunks: CodeChunk[] = [];
|
||||
for (let start = 0; start < lines.length; start += stride) {
|
||||
const end = Math.min(lines.length, start + windowLines);
|
||||
const slice = lines.slice(start, end).join("\n").trim();
|
||||
if (slice.length === 0) {
|
||||
if (end >= lines.length) break;
|
||||
continue;
|
||||
}
|
||||
const window: CodeChunk = {
|
||||
path: filePath,
|
||||
startLine: start + 1,
|
||||
endLine: end,
|
||||
text: slice,
|
||||
};
|
||||
for (const sub of safeSplit(window, maxChunkChars)) chunks.push(sub);
|
||||
if (end >= lines.length) break;
|
||||
}
|
||||
return chunks;
|
||||
}
|
||||
|
||||
/**
|
||||
* Post-process a window so no chunk exceeds `maxChars`. We try to
|
||||
* preserve full-line granularity for retrieval quality:
|
||||
*
|
||||
* - Walk the window line by line, accumulating into a buffer until
|
||||
* adding the next line would exceed `maxChars`. Flush the buffer
|
||||
* as a sub-chunk, restart at that line.
|
||||
* - A single line longer than `maxChars` (long minified statement
|
||||
* / base64 blob / unicode-heavy line) gets emitted as its own
|
||||
* chunk, hard-truncated to `maxChars`. Coverage loss is acceptable
|
||||
* — minified content has near-zero retrieval value.
|
||||
*
|
||||
* Idempotent: chunks already under `maxChars` pass through unchanged
|
||||
* (well — the buffer logic still emits them as a single sub-chunk,
|
||||
* but the result is byte-equivalent).
|
||||
*/
|
||||
function safeSplit(chunk: CodeChunk, maxChars: number): CodeChunk[] {
|
||||
if (chunk.text.length <= maxChars) return [chunk];
|
||||
const lines = chunk.text.split("\n");
|
||||
const out: CodeChunk[] = [];
|
||||
let bufLines: string[] = [];
|
||||
let bufStart = chunk.startLine;
|
||||
let bufLen = 0;
|
||||
const flush = (untilLineNo: number): void => {
|
||||
if (bufLines.length === 0) return;
|
||||
out.push({
|
||||
path: chunk.path,
|
||||
startLine: bufStart,
|
||||
endLine: untilLineNo,
|
||||
text: bufLines.join("\n"),
|
||||
});
|
||||
bufLines = [];
|
||||
bufLen = 0;
|
||||
};
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const line = lines[i] ?? "";
|
||||
const lineLen = line.length + 1; // +newline
|
||||
if (lineLen > maxChars) {
|
||||
// Single line dwarfs the cap. Flush current buffer, then emit
|
||||
// a hard-truncated single-line chunk for this line.
|
||||
flush(chunk.startLine + i - 1);
|
||||
out.push({
|
||||
path: chunk.path,
|
||||
startLine: chunk.startLine + i,
|
||||
endLine: chunk.startLine + i,
|
||||
text: line.slice(0, maxChars),
|
||||
});
|
||||
bufStart = chunk.startLine + i + 1;
|
||||
continue;
|
||||
}
|
||||
if (bufLen + lineLen > maxChars && bufLines.length > 0) {
|
||||
flush(chunk.startLine + i - 1);
|
||||
bufStart = chunk.startLine + i;
|
||||
}
|
||||
bufLines.push(line);
|
||||
bufLen += lineLen;
|
||||
}
|
||||
flush(chunk.endLine);
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Walk `root` recursively and yield code chunks for every indexable
|
||||
* file. Pure async generator so callers can pipe through embedding +
|
||||
* progress reporting without buffering the whole repo in memory.
|
||||
*
|
||||
* The generator silently skips files larger than `maxFileBytes` —
|
||||
* generated bundles, vendored data, etc. — to avoid one huge file
|
||||
* dominating the budget. The threshold is intentionally low; the
|
||||
* real signal in oversized files is rare and the embedding cost
|
||||
* scales with chunk count.
|
||||
*/
|
||||
export async function* walkChunks(
|
||||
root: string,
|
||||
opts: ChunkOptions = {},
|
||||
): AsyncGenerator<CodeChunk> {
|
||||
const windowLines = opts.windowLines ?? 60;
|
||||
const overlap = Math.min(opts.overlap ?? 12, Math.max(0, windowLines - 1));
|
||||
const maxFileBytes = opts.maxFileBytes ?? 256 * 1024;
|
||||
const maxChunkChars = opts.maxChunkChars ?? DEFAULT_MAX_CHUNK_CHARS;
|
||||
|
||||
const stack: string[] = [root];
|
||||
while (stack.length > 0) {
|
||||
const dir = stack.pop();
|
||||
if (!dir) break;
|
||||
let entries: import("node:fs").Dirent[];
|
||||
try {
|
||||
entries = await fs.readdir(dir, { withFileTypes: true });
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
for (const entry of entries) {
|
||||
const name = entry.name;
|
||||
if (entry.isDirectory()) {
|
||||
if (SKIP_DIRS.has(name) || name.startsWith(".")) {
|
||||
// .git/.next/.cache etc. plus any hidden dir — same default
|
||||
// as `directory_tree`. Users opt in to dotfiles via a future
|
||||
// flag; MVP keeps the index lean.
|
||||
if (SKIP_DIRS.has(name) || name === ".git") continue;
|
||||
// Allow other dotdirs that aren't in SKIP_DIRS (rare).
|
||||
}
|
||||
stack.push(path.join(dir, name));
|
||||
continue;
|
||||
}
|
||||
if (!entry.isFile()) continue;
|
||||
if (SKIP_FILES.has(name)) continue;
|
||||
const ext = path.extname(name).toLowerCase();
|
||||
if (BINARY_EXTS.has(ext)) continue;
|
||||
const abs = path.join(dir, name);
|
||||
let stat: import("node:fs").Stats;
|
||||
try {
|
||||
stat = await fs.stat(abs);
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
if (stat.size > maxFileBytes) continue;
|
||||
// Read as utf-8. If decoding ever fails (random binary that
|
||||
// sneaks past the ext check), skip rather than crashing the
|
||||
// whole index build.
|
||||
let text: string;
|
||||
try {
|
||||
text = await fs.readFile(abs, "utf8");
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
// Quick null-byte sniff — catches binary files with weird /
|
||||
// missing extensions that BINARY_EXTS missed.
|
||||
if (text.indexOf("\0") !== -1) continue;
|
||||
const rel = path.relative(root, abs).split(path.sep).join("/");
|
||||
for (const chunk of chunkText(text, rel, windowLines, overlap, maxChunkChars)) {
|
||||
yield chunk;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Convenience: collect all chunks from a directory into an array.
|
||||
* For very large repos prefer streaming via `walkChunks`.
|
||||
*/
|
||||
export async function chunkDirectory(root: string, opts: ChunkOptions = {}): Promise<CodeChunk[]> {
|
||||
const out: CodeChunk[] = [];
|
||||
for await (const c of walkChunks(root, opts)) out.push(c);
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
/**
|
||||
* Embedding adapter — wraps Ollama's `/api/embeddings` endpoint.
|
||||
*
|
||||
* Ollama is the MVP backend choice for three reasons that match
|
||||
* Reasonix's pillars:
|
||||
* 1. **Local + zero telemetry** — runs on the user's machine, no
|
||||
* data ever leaves it. Same property as the rest of Reasonix.
|
||||
* 2. **Zero native deps for us** — we talk plain HTTP+JSON; no
|
||||
* ONNX runtime / WASM blob / platform-specific binary to ship.
|
||||
* `npm install reasonix` stays trivial.
|
||||
* 3. **Reuse across projects** — if the user already has Ollama
|
||||
* installed (likely for other LLM work), we cost them nothing
|
||||
* to add. If they don't, one `ollama pull <model>` is the
|
||||
* whole onboarding.
|
||||
*
|
||||
* Default model is `nomic-embed-text` — small (137M params), 768-dim
|
||||
* output, free, fast. Configurable via `embedModel` option for users
|
||||
* who want bigger / multilingual / domain-specific embedders.
|
||||
*/
|
||||
|
||||
const DEFAULT_OLLAMA_URL = "http://localhost:11434";
|
||||
const DEFAULT_EMBED_MODEL = "nomic-embed-text";
|
||||
const DEFAULT_TIMEOUT_MS = 30_000;
|
||||
|
||||
export interface EmbedOptions {
|
||||
/** Ollama base URL. Default `http://localhost:11434`. Override via env or config for remote daemons. */
|
||||
baseUrl?: string;
|
||||
/** Embedding model name. Default `nomic-embed-text`. */
|
||||
model?: string;
|
||||
/** Per-request timeout in ms. Default 30s. */
|
||||
timeoutMs?: number;
|
||||
/** Caller-controlled abort. */
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
export class EmbeddingError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
public override readonly cause?: unknown,
|
||||
) {
|
||||
super(message);
|
||||
this.name = "EmbeddingError";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Embed a single text. Returns a Float32Array (compact, fits the
|
||||
* cosine-scan inner loop), not a number[]. Throws `EmbeddingError`
|
||||
* with an actionable message when Ollama is unreachable so the
|
||||
* caller can surface install instructions instead of a generic
|
||||
* `fetch failed`.
|
||||
*/
|
||||
export async function embed(text: string, opts: EmbedOptions = {}): Promise<Float32Array> {
|
||||
const baseUrl = opts.baseUrl ?? process.env.OLLAMA_URL ?? DEFAULT_OLLAMA_URL;
|
||||
const model = opts.model ?? process.env.REASONIX_EMBED_MODEL ?? DEFAULT_EMBED_MODEL;
|
||||
const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
||||
|
||||
// Compose abort: caller's signal + our timeout. Either firing
|
||||
// tears down the request.
|
||||
const controller = new AbortController();
|
||||
const onCallerAbort = () => controller.abort(opts.signal?.reason);
|
||||
if (opts.signal) {
|
||||
if (opts.signal.aborted) controller.abort(opts.signal.reason);
|
||||
else opts.signal.addEventListener("abort", onCallerAbort, { once: true });
|
||||
}
|
||||
const timer = setTimeout(() => controller.abort(new Error("embedding timeout")), timeoutMs);
|
||||
|
||||
let res: Response;
|
||||
try {
|
||||
res = await fetch(`${baseUrl}/api/embeddings`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ model, prompt: text }),
|
||||
signal: controller.signal,
|
||||
});
|
||||
} catch (err) {
|
||||
clearTimeout(timer);
|
||||
if (opts.signal) opts.signal.removeEventListener("abort", onCallerAbort);
|
||||
// Connection refused (ECONNREFUSED) is the load-bearing case:
|
||||
// Ollama daemon isn't running. Surface the install hint clearly
|
||||
// so users don't have to grep a generic node:fetch error.
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
if (/ECONNREFUSED|connect ECONNREFUSED|fetch failed/i.test(msg)) {
|
||||
throw new EmbeddingError(
|
||||
`Cannot reach Ollama at ${baseUrl}. Install from https://ollama.com, then run \`ollama pull ${model}\` and \`ollama serve\`. Override the URL via OLLAMA_URL.`,
|
||||
err,
|
||||
);
|
||||
}
|
||||
throw new EmbeddingError(`embedding request failed: ${msg}`, err);
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
if (opts.signal) opts.signal.removeEventListener("abort", onCallerAbort);
|
||||
}
|
||||
|
||||
if (!res.ok) {
|
||||
const body = await res.text().catch(() => "");
|
||||
// 404 from Ollama with `model not found` body means user needs
|
||||
// to pull the model. Same logic as the install hint above.
|
||||
if (res.status === 404 && /model.*not found/i.test(body)) {
|
||||
throw new EmbeddingError(
|
||||
`Embedding model "${model}" not pulled. Run \`ollama pull ${model}\` once, then retry.`,
|
||||
);
|
||||
}
|
||||
throw new EmbeddingError(`Ollama returned ${res.status}: ${body.slice(0, 200)}`);
|
||||
}
|
||||
|
||||
const json = (await res.json()) as { embedding?: unknown };
|
||||
if (!json.embedding || !Array.isArray(json.embedding)) {
|
||||
throw new EmbeddingError(`Ollama response missing 'embedding' array`);
|
||||
}
|
||||
// Convert once to Float32Array so the cosine inner loop avoids
|
||||
// boxing/unboxing per dot product. 4× memory win over number[] too.
|
||||
const out = new Float32Array(json.embedding.length);
|
||||
for (let i = 0; i < json.embedding.length; i++) {
|
||||
const v = json.embedding[i];
|
||||
if (typeof v !== "number" || !Number.isFinite(v)) {
|
||||
throw new EmbeddingError(`embedding[${i}] is not a finite number`);
|
||||
}
|
||||
out[i] = v;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Embed many texts sequentially (Ollama's HTTP server is single-
|
||||
* threaded per model anyway — parallel requests just queue inside
|
||||
* the daemon). Surfaces progress via `onProgress` and per-text
|
||||
* failures via `onError`.
|
||||
*
|
||||
* Returns one slot per input text. A null slot means that text
|
||||
* failed to embed (Ollama 500, transient model error, …). Callers
|
||||
* MUST handle nulls — typically by filtering them out alongside the
|
||||
* parallel chunk-metadata array. This is the load-bearing fault-
|
||||
* tolerance that lets one bad chunk (e.g. a malformed file that
|
||||
* sneaks past size checks, or a transient daemon hiccup) skip the
|
||||
* chunk instead of aborting a 30-minute index build.
|
||||
*
|
||||
* Aborts (signal-driven) still throw — those are global, not
|
||||
* per-chunk.
|
||||
*/
|
||||
export async function embedAll(
|
||||
texts: readonly string[],
|
||||
opts: EmbedOptions & {
|
||||
onProgress?: (done: number, total: number) => void;
|
||||
/** Fired once per failed chunk with the index + error. Default:
|
||||
* none — callers can wire it to log a warning. */
|
||||
onError?: (index: number, err: unknown) => void;
|
||||
} = {},
|
||||
): Promise<Array<Float32Array | null>> {
|
||||
const out: Array<Float32Array | null> = new Array(texts.length).fill(null);
|
||||
for (let i = 0; i < texts.length; i++) {
|
||||
if (opts.signal?.aborted) {
|
||||
throw new EmbeddingError("embedding aborted");
|
||||
}
|
||||
const text = texts[i];
|
||||
if (text === undefined) continue;
|
||||
try {
|
||||
out[i] = await embed(text, opts);
|
||||
} catch (err) {
|
||||
// Don't throw — surface the error, leave a null slot, and
|
||||
// continue. If the abort signal fired *during* the request the
|
||||
// caller will pick that up on the next loop iteration.
|
||||
opts.onError?.(i, err);
|
||||
}
|
||||
opts.onProgress?.(i + 1, texts.length);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Probe the Ollama daemon. Returns `{ ok: true, models: string[] }`
|
||||
* if reachable, `{ ok: false, error }` otherwise. Used by
|
||||
* `reasonix index` to fail fast with a friendly message before doing
|
||||
* any chunking work.
|
||||
*/
|
||||
export async function probeOllama(
|
||||
opts: { baseUrl?: string; signal?: AbortSignal } = {},
|
||||
): Promise<{ ok: true; models: string[] } | { ok: false; error: string }> {
|
||||
const baseUrl = opts.baseUrl ?? process.env.OLLAMA_URL ?? DEFAULT_OLLAMA_URL;
|
||||
try {
|
||||
const res = await fetch(`${baseUrl}/api/tags`, { signal: opts.signal });
|
||||
if (!res.ok) return { ok: false, error: `Ollama returned ${res.status}` };
|
||||
const json = (await res.json()) as { models?: Array<{ name?: string }> };
|
||||
const models = (json.models ?? [])
|
||||
.map((m) => m.name)
|
||||
.filter((n): n is string => typeof n === "string");
|
||||
return { ok: true, models };
|
||||
} catch (err) {
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
return { ok: false, error: msg };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
/**
|
||||
* Semantic-search user-facing string table, EN + ZH.
|
||||
*
|
||||
* Why locale-aware here when the rest of Reasonix is English-only:
|
||||
* - These strings show up at high-friction moments (preflight prompts,
|
||||
* `/semantic` status). Misunderstanding them costs the user real
|
||||
* setup time. Other Reasonix surfaces (CLI --help, tool descriptions
|
||||
* the model sees) stay English on purpose — translating tool
|
||||
* descriptions would weaken the model's prompt-cache stability and
|
||||
* break alignment with training-data-typical wording.
|
||||
*
|
||||
* Locale detection precedence: REASONIX_LANG env override → LANG /
|
||||
* LC_ALL / LC_MESSAGES (Unix) → Intl.DateTimeFormat (Windows fallback)
|
||||
* → "en". The override exists so users on systems with mis-configured
|
||||
* LANG can force the language they actually read.
|
||||
*/
|
||||
|
||||
export type Locale = "en" | "zh";
|
||||
|
||||
let cachedLocale: Locale | null = null;
|
||||
|
||||
export function detectLocale(): Locale {
|
||||
if (cachedLocale) return cachedLocale;
|
||||
const override = (process.env.REASONIX_LANG ?? "").toLowerCase();
|
||||
if (override === "zh" || override === "en") {
|
||||
cachedLocale = override;
|
||||
return cachedLocale;
|
||||
}
|
||||
const env = process.env.LANG ?? process.env.LC_ALL ?? process.env.LC_MESSAGES ?? "";
|
||||
if (/^zh[-_]/i.test(env)) {
|
||||
cachedLocale = "zh";
|
||||
return "zh";
|
||||
}
|
||||
try {
|
||||
const sys = new Intl.DateTimeFormat().resolvedOptions().locale ?? "";
|
||||
if (/^zh[-_]/i.test(sys)) {
|
||||
cachedLocale = "zh";
|
||||
return "zh";
|
||||
}
|
||||
} catch {
|
||||
/* ignore — fall through to default */
|
||||
}
|
||||
cachedLocale = "en";
|
||||
return "en";
|
||||
}
|
||||
|
||||
/** Reset the cached locale. Tests use this; production never needs it. */
|
||||
export function resetLocaleCache(): void {
|
||||
cachedLocale = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lookup a string by key; substitutes `{name}` placeholders from `vars`.
|
||||
* Falls back to the English string when a translation is missing so a
|
||||
* partial dictionary update never produces a literal "[missing]" in
|
||||
* front of the user.
|
||||
*/
|
||||
export function t(key: keyof typeof EN, vars: Record<string, string | number> = {}): string {
|
||||
const loc = detectLocale();
|
||||
const dict = loc === "zh" ? ZH : EN;
|
||||
const tpl = dict[key] ?? EN[key];
|
||||
return tpl.replace(/\{(\w+)\}/g, (_m, name) => {
|
||||
const v = vars[name];
|
||||
return v === undefined ? `{${name}}` : String(v);
|
||||
});
|
||||
}
|
||||
|
||||
const EN = {
|
||||
// ── preflight ─────────────────────────────────────────────────────
|
||||
ollamaNotFound:
|
||||
"✗ `ollama` not found on PATH.\n Install from https://ollama.com (one-time, ~150 MB), then retry.\n",
|
||||
daemonNotReachableHint:
|
||||
"✗ Ollama daemon not reachable. Run `ollama serve` and retry, or pass --yes to start it automatically.\n",
|
||||
daemonStartConfirm: "Ollama daemon isn't running. Start `ollama serve` now?",
|
||||
daemonAbortStart: "✗ aborted — start `ollama serve` yourself and retry.\n",
|
||||
daemonStarting: "▸ starting `ollama serve`…\n",
|
||||
daemonStartTimeout:
|
||||
"✗ daemon didn't come up within 15s. Try `ollama serve` in a separate terminal and retry.\n",
|
||||
daemonReady: "✓ daemon up{pid}\n",
|
||||
modelNotPulledHint:
|
||||
'✗ embedding model "{model}" not pulled. Run `ollama pull {model}` and retry, or pass --yes to pull it automatically.\n',
|
||||
modelPullConfirm:
|
||||
'Embedding model "{model}" isn\'t pulled yet. Pull it now? (~274 MB for nomic-embed-text)',
|
||||
modelAbortPull: "✗ aborted — pull the model yourself and retry.\n",
|
||||
modelPulling: "▸ pulling {model}…\n",
|
||||
modelPullFailed: "✗ `ollama pull {model}` failed (exit {code}).\n",
|
||||
modelPulled: "✓ {model} pulled\n",
|
||||
|
||||
// ── progress ─────────────────────────────────────────────────────
|
||||
// The TTY-mode progress writer paints `<spinner> <status> <elapsed>s`
|
||||
// every 120ms. The status itself comes from one of these keys based
|
||||
// on the current phase. {files}, {done}, {total}, {pct} are
|
||||
// substituted by the writer.
|
||||
progressStarting: "starting…",
|
||||
progressScan: "scanning project · {files} files",
|
||||
progressEmbed: "embedding {done}/{total} chunks · {pct}%",
|
||||
progressEmbedHeartbeat: " {done}/{total}\n",
|
||||
progressScanLine: "scanning files…\n",
|
||||
progressEmbedLine: "embedding {total} chunks across {files} files…\n",
|
||||
// Final result line after a successful build.
|
||||
indexSuccess:
|
||||
"✓ indexed {scanned} files ({changed} changed, {added} new chunks, {removed} stale removed) in {seconds}s\n",
|
||||
indexSuccessWithSkips:
|
||||
"✓ indexed {scanned} files ({changed} changed, {added} new chunks, {removed} stale removed, {skipped} skipped due to embed errors) in {seconds}s\n",
|
||||
indexNothingToDo: " (nothing to do — re-run with --rebuild to force a full rebuild)\n",
|
||||
indexFailed: "✗ index failed: {msg}\n",
|
||||
|
||||
// ── /semantic slash ──────────────────────────────────────────────
|
||||
slashHeader: "semantic_search status",
|
||||
slashEnabled: "✓ enabled — index built, tool registered.",
|
||||
slashEnabledDetail: " index size: {chunks} chunks across {files} files",
|
||||
slashEnabledHowto: " the model will call semantic_search automatically when it fits.",
|
||||
slashIndexMissing: "✗ no index built yet for this project.",
|
||||
slashHowToBuild: " to enable, exit Reasonix and run in your shell:\n reasonix index",
|
||||
slashOllamaMissing: " prerequisite: install Ollama from https://ollama.com",
|
||||
slashDaemonDown:
|
||||
" Ollama is installed but the daemon isn't running. start it with: ollama serve",
|
||||
slashIndexInfo:
|
||||
" what semantic_search does: cross-language code understanding via local embeddings.\n better than grep when you describe WHAT something does, not WHICH token to find.",
|
||||
} as const;
|
||||
|
||||
const ZH: Partial<Record<keyof typeof EN, string>> = {
|
||||
ollamaNotFound:
|
||||
"✗ 未找到 `ollama`。\n 请访问 https://ollama.com 安装(一次性,约 150 MB),然后重试。\n",
|
||||
daemonNotReachableHint:
|
||||
"✗ Ollama 守护进程未启动。请运行 `ollama serve` 后重试,或加 --yes 让我自动启动。\n",
|
||||
daemonStartConfirm: "Ollama 守护进程未运行。现在启动 `ollama serve` 吗?",
|
||||
daemonAbortStart: "✗ 已取消——请自行运行 `ollama serve` 后重试。\n",
|
||||
daemonStarting: "▸ 正在启动 `ollama serve`…\n",
|
||||
daemonStartTimeout: "✗ 15 秒内守护进程未就绪。请在另一个终端运行 `ollama serve` 后重试。\n",
|
||||
daemonReady: "✓ 守护进程已启动{pid}\n",
|
||||
modelNotPulledHint:
|
||||
'✗ 嵌入模型 "{model}" 未下载。请运行 `ollama pull {model}` 后重试,或加 --yes 让我自动下载。\n',
|
||||
modelPullConfirm: '嵌入模型 "{model}" 还未下载。现在下载吗?(nomic-embed-text 约 274 MB)',
|
||||
modelAbortPull: "✗ 已取消——请自行下载模型后重试。\n",
|
||||
modelPulling: "▸ 正在下载 {model}…\n",
|
||||
modelPullFailed: "✗ `ollama pull {model}` 失败(退出码 {code})。\n",
|
||||
modelPulled: "✓ {model} 下载完成\n",
|
||||
|
||||
progressStarting: "正在启动…",
|
||||
progressScan: "扫描项目 · 已扫描 {files} 个文件",
|
||||
progressEmbed: "正在向量化 {done}/{total} 个片段 · {pct}%",
|
||||
progressEmbedHeartbeat: " {done}/{total}\n",
|
||||
progressScanLine: "正在扫描文件…\n",
|
||||
progressEmbedLine: "正在向量化 {total} 个片段(涉及 {files} 个文件)…\n",
|
||||
indexSuccess:
|
||||
"✓ 已建立索引:扫描 {scanned} 个文件({changed} 个有变化,新增 {added} 个片段,移除 {removed} 个过期);耗时 {seconds}s\n",
|
||||
indexSuccessWithSkips:
|
||||
"✓ 已建立索引:扫描 {scanned} 个文件({changed} 个有变化,新增 {added} 个片段,移除 {removed} 个过期,跳过 {skipped} 个嵌入失败的片段);耗时 {seconds}s\n",
|
||||
indexNothingToDo: " (没有变化——加 --rebuild 强制重建)\n",
|
||||
indexFailed: "✗ 建立索引失败:{msg}\n",
|
||||
|
||||
slashHeader: "semantic_search 状态",
|
||||
slashEnabled: "✓ 已启用——索引已建好,工具已注册。",
|
||||
slashEnabledDetail: " 索引规模:{chunks} 个片段,{files} 个文件",
|
||||
slashEnabledHowto: " 模型在合适的时候会自动调用 semantic_search。",
|
||||
slashIndexMissing: "✗ 当前项目还没有索引。",
|
||||
slashHowToBuild: " 启用方式:退出 Reasonix,在终端运行:\n reasonix index",
|
||||
slashOllamaMissing: " 前置依赖:从 https://ollama.com 安装 Ollama",
|
||||
slashDaemonDown: " 已装 Ollama 但守护进程未启动,请运行:ollama serve",
|
||||
slashIndexInfo:
|
||||
' semantic_search 用本地 embedding 做跨语言代码理解。\n 当你描述"做什么"而不是具体 token 时,比 grep 更好。',
|
||||
};
|
||||
Loaded 100 of 198 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user