mirror of
https://github.com/esengine/DeepSeek-Reasonix.git
synced 2026-11-07 10:45:59 -10:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
33a3a7fd49 | ||
|
|
535a8ebb3b | ||
|
|
8860cedc2a | ||
|
|
98d6021ba9 | ||
|
|
3e71089068 | ||
|
|
7a5ef3b163 | ||
|
|
28b3f40b9e | ||
|
|
efb0a77648 | ||
|
|
70dcad6401 | ||
|
|
3e6fdac9c0 | ||
|
|
5ec643033c | ||
|
|
7f20ccf6ac | ||
|
|
fd26900d48 | ||
|
|
baedbf7292 | ||
|
|
d82aa833c9 | ||
|
|
937b9797aa | ||
|
|
32cccfaeca | ||
|
|
c1288d3a66 | ||
|
|
e0cdb7e7bb | ||
|
|
bf1bb778aa | ||
|
|
0c1d80fec9 | ||
|
|
9ba7fbdf86 | ||
|
|
1e58cf3e4b | ||
|
|
2dbf8bf723 | ||
|
|
c225dad853 | ||
|
|
a52f8facb4 | ||
|
|
fed2a515be | ||
|
|
067fcc21a4 | ||
|
|
957fc34c9b | ||
|
|
e0e7bb91f2 | ||
|
|
efd6d64176 | ||
|
|
44f309509e | ||
|
|
546e587a1e | ||
|
|
d58861e0d6 | ||
|
|
c9369d7532 | ||
|
|
78e6df6a4d | ||
|
|
9f88f3b330 | ||
|
|
72326254b6 | ||
|
|
baece15b65 | ||
|
|
fe9ad209eb | ||
|
|
be7daa017c |
No files matched your search
@@ -0,0 +1,11 @@
|
||||
# Force LF line endings on every checkout, regardless of platform.
|
||||
# Biome's formatter is strict about CRLF — without this, a Windows clone
|
||||
# with autocrlf=true will land with CRLF in the working tree even though
|
||||
# the repo stores LF, and `npm run lint` (and prepublishOnly with it)
|
||||
# fails. See docs/style.md if you ever add binary types here.
|
||||
* text=auto eol=lf
|
||||
|
||||
# Lockfiles + the codemirror bundle are generated; treat them as
|
||||
# auto-detected text but never coerce.
|
||||
package-lock.json text eol=lf
|
||||
dashboard/codemirror.js text eol=lf
|
||||
@@ -30,3 +30,6 @@ sessions/
|
||||
.reasonix/semantic/
|
||||
.reasonix/sessions/
|
||||
.reasonix/semantic-skip
|
||||
# Scratch entry regenerated each time scripts/bundle-codemirror.mjs runs.
|
||||
scripts/.cm-entry.mjs
|
||||
|
||||
+681
@@ -3,6 +3,687 @@
|
||||
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.14.0] — 2026-04-29
|
||||
|
||||
**Headline:** Two real bug fixes (post-shell-confirm session lockup,
|
||||
post-workspace-switch ENOENT on edit_file), a new `/copy` mode for
|
||||
copying across multi-screen log content, an always-on context-pressure
|
||||
footer above the prompt, and width-aware chrome that stops dropping
|
||||
pills when there's clearly room. Plus a quiet refactor: shared UI
|
||||
primitives, dead-code purge in StatsPanel.
|
||||
|
||||
- fix(loop): streaming-abort path now resets `_turnAbort` before
|
||||
returning. Without this, a queued-submit triggered by App.tsx
|
||||
(ShellConfirm "run once" → `loop.abort()` + `setQueuedSubmit`)
|
||||
produced a spurious `aborted at iter 0/64 — stopped without
|
||||
producing a summary` the moment the synthetic message reached
|
||||
the loop, locking the session until the user `/retry`'d.
|
||||
- fix(tui): `edit_file` interceptor now reads the workspace root via
|
||||
`currentRootDirRef` instead of capturing `currentRootDir` in a
|
||||
stale closure. Workspace switch (`change_workspace` → modal approve)
|
||||
rebound `read_file` / `run_command` to the new root but left the
|
||||
interceptor pointing at the old one — `edit_file` wrote to the
|
||||
old path while `read_file` looked in the new one, surfacing as a
|
||||
mysterious ENOENT for a file the model had just successfully edited.
|
||||
- feat(tui): `/copy` exits the alt-screen, dumps the rendered log to
|
||||
the main screen, and listens for any keystroke to restore. Native
|
||||
terminal scrollback + drag-select work on the dump — solves the
|
||||
"can't copy text that scrolled past the viewport" problem alt-screen
|
||||
introduced. Re-entering alt-screen and bumping React state forces
|
||||
Ink to redraw the TUI cleanly. Multiple enter/exit cycles per
|
||||
session; React tree, event log, model session, prompt draft all
|
||||
preserved across the toggle.
|
||||
- feat(tui): always-on context-pressure footer above the prompt —
|
||||
`ctx ▰▰▰▱▱▱▱▱▱▱▱▱▱▱ 14K/977K · 1% · sys 5.8K · tools 6.1K · log 0`.
|
||||
Single-row layout matches the chrome bar's `▰▱` visual language.
|
||||
Width-aware shed for the breakdown segments (input → log → tools →
|
||||
sys). `/context` toggles visibility (default on); the rich
|
||||
4-color stacked breakdown is still pushed to scrollback for
|
||||
headless / replay surfaces that don't carry the toggle callback.
|
||||
- feat(tui): chrome bar pill rendering switches from preemptive
|
||||
`narrow = cols < 120` to width-aware greedy shed. Optional pills
|
||||
(balance > cache > session > update) drop in priority order only
|
||||
when `string-width` math says they won't fit — at 100 cols all
|
||||
five render where the old code dropped three. Cache pill is now
|
||||
default-on (cold-start dim treatment instead of hiding).
|
||||
- refactor(ui): `Bar`, `formatTokens`, `ChromeRule`, `ContextCell`
|
||||
promoted to `src/cli/ui/primitives.tsx` (were duplicated 2-3× across
|
||||
`StatsPanel` / `ChromeBar` / `EventLog` / `log-frame`). `CtxBreakdownBlock`
|
||||
+ `computeCtxBreakdown` extracted to `src/cli/ui/ctx-breakdown.tsx`
|
||||
so `/context` and the footer share the same compute path. `StatsPanel`
|
||||
shrunk from 769 → ~280 lines (dead helpers from the chrome
|
||||
redesign era removed).
|
||||
- feat(core): v0.14 architecture scaffold — `src/core/events.ts`
|
||||
(25-variant Event union + 7 view types), `src/core/reducers.ts`
|
||||
(pure projections + `apply` / `replay` combinators), `src/ports/*.ts`
|
||||
(6 ports: ModelClient, ToolHost, EventSink, MemoryStore, HookRunner,
|
||||
CheckpointStore). Types only; zero behavior change. 19 reducer tests
|
||||
pin the conversation / budget / plan / workspace / capabilities /
|
||||
status / session-meta projections and prove `replay()` determinism.
|
||||
|
||||
## [0.13.5] — 2026-04-29
|
||||
|
||||
**Headline:** TUI overhaul. Chrome reverts to native Ink Box +
|
||||
flexGrow (Phase 6a's Frame-compiler chrome was clipping pills on
|
||||
Windows Terminal / ConPTY). Vertical scrollbar replaced with a
|
||||
`[↑ N%]` chrome pill + horizontal mini-bar in the bottom hint —
|
||||
column-aligned scrollbars are unreliable while some log atoms
|
||||
still render through legacy ReactElements. Streaming gains the
|
||||
design's `responding ░▒▓█▓▒░░░░` marquee and a `▌` cursor blink
|
||||
at end-of-body.
|
||||
|
||||
- chrome: `ChromeBar` uses native flex; preset pill (`[auto]` /
|
||||
`[flash]` / `[pro]`) replaces edit-mode pill (edit mode still
|
||||
surfaces via `ModeStatusBar`); CNY balance renders as `w ¥8.50`;
|
||||
cost pill includes inline budget when set.
|
||||
- streaming: full body text streams in (was 140-char tail) with a
|
||||
blinking primary-color cursor; `responding` row shows a 12-cell
|
||||
marching wave (`░▒▓█▓▒`) at 120ms ticks. Matches
|
||||
`design/tui-redesign-ink.html`.
|
||||
- scroll: vertical `ScrollBar` removed; chrome shows `[↑ N%]` when
|
||||
scrolled, `BottomHint` shows `↑ N · ▕──●──▏ X% · ↓ M · End`.
|
||||
- frame: `src/frame/width.ts` delegates to the `string-width`
|
||||
package; hand-rolled width tables removed.
|
||||
- chore: project `CLAUDE.md` codifies code/comment conventions
|
||||
(terse comments, no Phase-N essays, libraries over hand-rolled
|
||||
unicode math).
|
||||
|
||||
## [0.12.15] — 2026-04-28
|
||||
|
||||
**Headline:** Every user-facing string that still said
|
||||
`fast / smart / max` is now `auto / flash / pro` — the canonical
|
||||
names presets have used since the autoEscalate split. CLI flags
|
||||
(`chat --preset`, `run --preset`), `/help`'s preset table,
|
||||
`/preset`'s argHint and completer, the slash handler's `usage:`
|
||||
line, and the `code` command description all updated.
|
||||
|
||||
Old `config.json` files keep working: `resolvePreset` still maps
|
||||
`fast → flash·effort=high`, `smart → auto`, `max → pro`. What
|
||||
changed is the interactive surface — `/preset fast` now prints
|
||||
usage instead of silently doing the right thing, so the in-chat
|
||||
vocabulary matches what's documented.
|
||||
|
||||
## [0.12.14] — 2026-04-28
|
||||
|
||||
**Headline:** Three TUI confirmations the dashboard couldn't see —
|
||||
`change_workspace`, plan checkpoints, plan revisions — now mirror to
|
||||
the web modal layer with the same Switch/Deny/Continue/Revise/Stop/
|
||||
Accept/Reject choices the terminal exposes. Plus: a deferred-dispatch
|
||||
fix for parallel tool calls that was silently writing files into the
|
||||
old workspace, and the in-flight row finally tells you _what tool_ is
|
||||
running, not just "waiting".
|
||||
|
||||
### Loop — workspace-switch parallel-batch fix
|
||||
|
||||
When DeepSeek emits `change_workspace + write_file` in one assistant
|
||||
message, every call dispatched in sequence — write_file fired against
|
||||
the OLD sandbox before the user had a chance to approve the modal,
|
||||
silently dropping the new file in the wrong project. Every subsequent
|
||||
call in the same batch now gets a synthetic "deferred — re-issue on
|
||||
your next turn" result; tool_call ↔ tool pairing stays valid for
|
||||
DeepSeek's next-turn validator. Test in `tests/loop.test.ts` locks it.
|
||||
|
||||
### Server / context
|
||||
|
||||
- `ActiveModal` gains three new shapes: `workspace`, `checkpoint`,
|
||||
`revision`. `getActiveModal` returns them so a freshly-connected
|
||||
client paints the right modal mid-prompt.
|
||||
- `DashboardContext` adds `resolveWorkspaceConfirm`,
|
||||
`resolveCheckpointConfirm` (with optional `text` for revise-with-
|
||||
feedback in one shot), and `resolveReviseConfirm`.
|
||||
- `/api/modal/resolve` accepts the three new `kind`s with their
|
||||
per-shape choice validation. 503 when a resolver isn't wired.
|
||||
|
||||
### App.tsx wiring
|
||||
|
||||
- `pendingWorkspace`, `pendingCheckpoint`, `pendingRevision` each
|
||||
broadcast `modal-up`/`modal-down` SSE events.
|
||||
- Web's "revise + feedback in one shot" path bypasses the TUI's
|
||||
staged-input two-step by accepting an explicit snap override on
|
||||
`handleCheckpointReviseSubmit` — no more setStagedX → re-render →
|
||||
ref-mirror microtask race.
|
||||
|
||||
### Dashboard SPA
|
||||
|
||||
- New `WorkspaceModal`, `CheckpointModal`, `RevisionModal` Preact
|
||||
components. Modal switch dispatches them by `modal.kind`.
|
||||
- In-flight row now shows the active tool + key args (path / command
|
||||
truncated to 80 chars / char count) once `tool_start` fires —
|
||||
`write_file → /path/to/foo (12,345 ch)` instead of "waiting…".
|
||||
- Tool-start no longer pushes a placeholder info row. The InFlightRow
|
||||
carries the live state; the result card replaces it on `tool`.
|
||||
- ErrorBoundary stops auto-recovering after 3 catches and renders a
|
||||
manual "Try again" button — no more silent flickering loop.
|
||||
- `.modal-cmd` gets `overflow-x: auto` + `max-height: 240px` so a
|
||||
pathological multi-kilobyte command can't push the rest of the
|
||||
panel offscreen.
|
||||
|
||||
## [0.12.13] — 2026-04-28
|
||||
|
||||
**Fix:** the chat feed kept yanking the user back to the bottom
|
||||
during streaming — wheel-up didn't stick. Two bugs stacked:
|
||||
|
||||
1. The scroll listener attached to `document.querySelector(".chat-feed")`
|
||||
on first mount, but the `.chat-feed` div was conditionally
|
||||
rendered (only when at least one message existed). On a fresh
|
||||
session the listener never attached, so the "is the user
|
||||
scrolled away?" flag was never flipped to `false`.
|
||||
2. Even after the listener attached, the auto-scroll effect's
|
||||
own `el.scrollTop = el.scrollHeight` write fires a `scroll`
|
||||
event that re-snaps the flag back to `true`. Manual wheel
|
||||
scrolls were racing the next streaming delta's auto-snap.
|
||||
|
||||
Both fixed:
|
||||
|
||||
- `.chat-feed` is now always rendered (the empty-state copy
|
||||
moved inside it). A `feedRef` ref attaches the scroll
|
||||
listener on first paint.
|
||||
- A new `autoScrollInFlight` ref gates the listener: events
|
||||
observed during a programmatic scroll write are ignored, so
|
||||
only genuine user wheel/drag flips the auto-scroll guard.
|
||||
|
||||
## [0.12.12] — 2026-04-28
|
||||
|
||||
**Headline:** Indexing from the dashboard now actually wires up
|
||||
`semantic_search` for the running session — no more "build the
|
||||
index, restart, build again" dance — and a dismissible Chat
|
||||
banner steers users to the Semantic panel when no index exists.
|
||||
|
||||
### Loop / prefix
|
||||
|
||||
- `ImmutablePrefix` gains an `addTool(spec)` method that pushes a
|
||||
new tool spec onto the live prefix. The class name is now a
|
||||
half-truth (toolSpecs is exposed via getter, backed by a mutable
|
||||
array) but the rationale is documented inline: a one-time cache
|
||||
miss is cheaper than asking users to restart the session.
|
||||
- New `DashboardContext.addToolToPrefix(spec)` callback. Wired
|
||||
from `App.tsx` to `loop.prefix.addTool`.
|
||||
|
||||
### Server
|
||||
|
||||
- `runIndex` (the dashboard's buildIndex wrapper) calls
|
||||
`registerSemanticSearchTool(ctx.tools, …)` after a successful
|
||||
build, then `ctx.addToolToPrefix(spec)` so the model sees
|
||||
`semantic_search` from the next turn. Failures are non-fatal —
|
||||
the index is still on disk, the next session bootstrap picks
|
||||
it up.
|
||||
- `/api/overview` returns `semanticIndexExists` (`true`/`false`/
|
||||
`null`) so the Chat panel can render the banner without an
|
||||
extra round-trip.
|
||||
|
||||
### Dashboard — Chat panel
|
||||
|
||||
- New top-of-Chat banner: `≈ Semantic search isn't enabled for
|
||||
this project — Build it →` with a dismiss `×`. Visible only
|
||||
when `semanticIndexExists === false` and not previously
|
||||
dismissed (state in `localStorage` as `rx.semanticBannerDismissed`).
|
||||
- Click "Build it →" fires `appBus.dispatchEvent("navigate-tab")`
|
||||
with `tabId: "semantic"` — the existing nav handler picks it up.
|
||||
|
||||
## [0.12.11] — 2026-04-28
|
||||
|
||||
**Headline:** Tell users what to do when Ollama isn't installed
|
||||
yet. The 0.12.9 Semantic panel just said "not reachable" with a
|
||||
generic copy-this-command blurb — the new flow distinguishes
|
||||
"binary missing" from "daemon down" from "model not pulled" and
|
||||
offers a one-click action for each level it can resolve.
|
||||
|
||||
### Server
|
||||
|
||||
- `GET /api/semantic` now returns the full `checkOllamaStatus`
|
||||
payload — `binaryFound`, `daemonRunning`, `modelPulled`,
|
||||
`modelName`, `installedModels` — instead of the raw probe.
|
||||
- New endpoints:
|
||||
- `POST /api/semantic/ollama/start` — runs `startOllamaDaemon`
|
||||
(15s timeout). Returns `{ ready, pid }`.
|
||||
- `POST /api/semantic/ollama/pull` — fire-and-forget
|
||||
`pullOllamaModel`. Per-model `PULLS` map tracks status +
|
||||
last log line; `/api/semantic` includes it as `pull`.
|
||||
|
||||
### Dashboard — Semantic panel
|
||||
|
||||
Tri-state Ollama section:
|
||||
- **No binary** → red "not installed" pill + Install Ollama
|
||||
card with macOS / Windows / Linux install instructions. We
|
||||
deliberately don't run package managers for the user.
|
||||
- **Binary, daemon down** → yellow "daemon down" pill + "Start
|
||||
daemon" button (calls `ollama/start`).
|
||||
- **Daemon up, model missing** → "not pulled" pill + "Pull
|
||||
<model>" button. Live status row during the pull (latest
|
||||
ollama output line, elapsed seconds, success/error pill).
|
||||
- **Everything ready** → green pill, Index buttons enable.
|
||||
|
||||
Polling speeds up to 1.2s while a pull or build job is running.
|
||||
|
||||
## [0.12.10] — 2026-04-28
|
||||
|
||||
**Headline:** Move the in-flight indicator out of the top-left
|
||||
corner and put the live counters next to it. Previously the
|
||||
spinner appeared above the message stream — far from where the
|
||||
user's eyes already were (input + status bar) — and the only
|
||||
moving signal during a turn was the streaming text itself.
|
||||
|
||||
### Chat panel
|
||||
|
||||
- New **InFlightRow** rendered just above the ChatStatusBar
|
||||
whenever a turn is in flight. Format:
|
||||
`⠋ thinking · 2.3s · reasoning 1,204 ch · out 0 ch · [Abort]`
|
||||
- Phase auto-flips between `thinking` (only reasoning growing),
|
||||
`streaming` (text growing), and `waiting` (neither — model is
|
||||
thinking with no token output yet, e.g. before the first
|
||||
delta arrives).
|
||||
- Elapsed seconds tick every 500ms via a per-turn interval so
|
||||
the user sees motion even when the model is in a long pause
|
||||
between deltas.
|
||||
- Character counts come from the existing `streaming` state — no
|
||||
new wire fields, just rendering data we already have.
|
||||
- Top "turn in flight" row is gone; only `statusLine` notices
|
||||
still render up there when not busy.
|
||||
|
||||
## [0.12.9] — 2026-04-28
|
||||
|
||||
**Headline:** Semantic indexing without leaving the session.
|
||||
Previously you had to exit the TUI, run `reasonix index`, wait,
|
||||
then re-enter — every change. Now there's a Semantic panel in
|
||||
the dashboard that drives `buildIndex` in the background and
|
||||
shows live progress.
|
||||
|
||||
### Server
|
||||
|
||||
- `src/server/api/semantic.ts` — new endpoint set:
|
||||
- `GET /api/semantic` → Ollama probe + index existence
|
||||
+ current job snapshot
|
||||
- `POST /api/semantic/start` → kick off `buildIndex({ rebuild })`
|
||||
fire-and-forget, returns 202
|
||||
- `POST /api/semantic/stop` → flag job as aborting (advisory;
|
||||
`buildIndex` doesn't honor a
|
||||
signal yet, lands when it does)
|
||||
- Per-root `JobRecord` map (module-scoped) tracks phase
|
||||
(scan/embed/write/done/error) + counters (filesScanned,
|
||||
chunksTotal, chunksDone, …) updated via `onProgress`.
|
||||
|
||||
### Dashboard
|
||||
|
||||
- New **Semantic** sidebar tab. Polls `/api/semantic` every 1.2s
|
||||
while a job is running, every 5s when idle.
|
||||
- Surfaces Ollama daemon reachability + listed models, current
|
||||
index existence, and the live job: phase pill, file/chunk
|
||||
counters, percentage progress bar, elapsed seconds, last
|
||||
result on completion, error text on failure.
|
||||
- Buttons: **Index (incremental)**, **Rebuild (wipe + full)**,
|
||||
**Stop**. Disabled appropriately when Ollama isn't reachable
|
||||
or another job is running. Inline guidance on missing daemon.
|
||||
- Standalone `reasonix dashboard` mode shows a polite "code-mode
|
||||
required" empty state — no project root, nothing to index.
|
||||
|
||||
## [0.12.8] — 2026-04-28
|
||||
|
||||
**Fix:** the dashboard row in 0.12.7 collapsed the URL and
|
||||
description onto one Box; on terminals that hide the OSC 8
|
||||
escape, Ink's text-width measurement counted the escape bytes
|
||||
as visible characters and the description wrapped through the
|
||||
middle of the URL. Split into two stacked rows:
|
||||
|
||||
```
|
||||
◇ web open the dashboard in a browser (chat · files · stats · settings)
|
||||
http://127.0.0.1:NNNN/?token=…
|
||||
```
|
||||
|
||||
URL still wrapped in the OSC 8 hyperlink — but it's the only
|
||||
content on its row, so a width miscount can't clobber anything.
|
||||
|
||||
## [0.12.7] — 2026-04-28
|
||||
|
||||
**Headline:** Dashboard discoverability. Most users had no idea
|
||||
`/dashboard` existed — the URL is now visible from the first turn,
|
||||
on its own row in the status panel, with a one-line description of
|
||||
what the dashboard actually offers. Clickable in OSC-8-aware
|
||||
terminals (iTerm2, WezTerm, Windows Terminal, VS Code, recent
|
||||
gnome-terminal); copy-pasteable everywhere else.
|
||||
|
||||
### TUI
|
||||
|
||||
- Auto-launch the embedded dashboard when `reasonix code` /
|
||||
`reasonix chat` mount. Failures are silent (a missing dashboard
|
||||
never blocks the TUI), tear-down still happens on unmount /
|
||||
`/dashboard stop`.
|
||||
- `--no-dashboard` opts out per-session (CI, hardened
|
||||
environments, anyone allergic to a localhost listener).
|
||||
- New status-panel row:
|
||||
`◇ web http://127.0.0.1:NNNN/?token=… open the dashboard
|
||||
in a browser (chat · files · stats · settings)`
|
||||
rendered between the header and the metrics so it never fights
|
||||
for space.
|
||||
- URL wrapped in an OSC 8 hyperlink — Cmd/Ctrl-click in any
|
||||
terminal that supports the escape; bare text otherwise.
|
||||
- `App` gains a `noDashboard` prop, `StatsPanel` a `dashboardUrl`
|
||||
prop. Both threaded through `chatCommand` / `codeCommand`.
|
||||
|
||||
## [0.12.6] — 2026-04-28
|
||||
|
||||
**Headline:** Bigger fixes for the things you actually look at:
|
||||
the edit-review modal is now a real side-by-side diff, the
|
||||
sidebar collapses to icons, and the call-storm breaker stops
|
||||
mistaking legitimate read → edit → verify cycles for storms.
|
||||
|
||||
### Edit review modal
|
||||
|
||||
- Two-column **side-by-side diff** ("before" left, "after" right)
|
||||
with hljs syntax highlighting per the file's language. Adjacent
|
||||
removed/added line runs pair into rows so the change reads
|
||||
cleanly across the gutter.
|
||||
- Red tint + `−` marker on the removed side; green tint + `+` on
|
||||
the added side; context lines render unchanged.
|
||||
- Modal payload (`{ kind: "edit-review" }`) gained `search` and
|
||||
`replace` fields holding the full block contents — the old
|
||||
truncated `preview` string stays alongside for older clients.
|
||||
`src/cli/ui/App.tsx` and `src/server/context.ts` updated.
|
||||
|
||||
### Sidebar — icon-only collapse
|
||||
|
||||
- New `◀ collapse` button at the bottom of the sidebar shrinks
|
||||
it from 220px → 52px and hides every label, leaving just the
|
||||
glyphs. `▶ expand` brings labels back. Choice persists in
|
||||
`localStorage` (`rx.sidebarCollapsed`).
|
||||
- Tabs in the collapsed state center the glyph and keep the
|
||||
primary-color active indicator.
|
||||
|
||||
### Call-storm breaker — false-positive fix
|
||||
|
||||
The `read → edit → verify → edit → verify` pattern was tripping
|
||||
the storm protection (3 identical `read_file` calls within the
|
||||
window). The fix sources its "did this call mutate state?"
|
||||
signal from the existing ToolRegistry — each tool already
|
||||
declares `readOnly` / `readOnlyCheck` for plan-mode gating, so
|
||||
no new flag was added. The breaker now:
|
||||
|
||||
- Tags every buffer entry as read-only or mutating based on the
|
||||
predicate the loop wires in (`def.readOnly === true`, with
|
||||
`readOnlyCheck` taking precedence on the actual args).
|
||||
- On a mutating call, drops prior read-only entries from the
|
||||
window — a re-read after `edit_file` is fresh, not a repeat.
|
||||
- Keeps mutator entries alongside, so a model looping on
|
||||
identical `edit_file` calls still trips on the threshold.
|
||||
|
||||
`StormBreaker(window, threshold, isMutating?)` is the public
|
||||
shape; `ToolCallRepair` accepts an `isMutating` predicate.
|
||||
Without one (older callers, isolated tests) every call counts —
|
||||
back-compat preserved. Three new storm tests cover the cases.
|
||||
|
||||
## [0.12.5] — 2026-04-28
|
||||
|
||||
**Headline:** Stop loading CodeMirror from a CDN, fix the legacy
|
||||
preset migration that broke 2 CI tests, and replace the markdown
|
||||
preview toggle with a proper Edit / Split / Preview tri-state.
|
||||
|
||||
### Editor — local CodeMirror bundle
|
||||
|
||||
- `scripts/bundle-codemirror.mjs` — esbuild-based bundler that
|
||||
pulls every `@codemirror/*` package from `node_modules` and
|
||||
produces `dashboard/codemirror.js` (~937 KB minified ESM).
|
||||
- `npm run build:cm` rebuilds it. Output is committed so a fresh
|
||||
`npm install` doesn't have to run esbuild.
|
||||
- `dashboard/app.js` now does `import("/assets/codemirror.js")`
|
||||
instead of 21 `import("https://esm.sh/...")` calls. One copy of
|
||||
every package = no Tag identity issues, no transitive-version
|
||||
drift between cold loads.
|
||||
- `serveAsset` learns to serve `codemirror.js`. `package.json`
|
||||
ships the bundle in `files`. Biome ignores the minified file.
|
||||
- `@codemirror/*` + `esbuild` added to devDependencies — they
|
||||
feed the bundler, they don't end up in the runtime install.
|
||||
|
||||
### Editor — markdown view modes
|
||||
|
||||
- Replaced the `Preview`/`Edit` boolean with a three-state
|
||||
segmented control: **Edit** (source only, default), **Split**
|
||||
(source on the left, rendered on the right, with a divider),
|
||||
**Preview** (rendered only). Buttons live in the editor bar
|
||||
and are markdown-only — non-md tabs hide the group entirely.
|
||||
- The CodeMirror remount effect now keys on `viewMode`, so
|
||||
flipping between Edit and Split doesn't leave a stale view.
|
||||
|
||||
### Preset rework — CI fix
|
||||
|
||||
`resolvePreset` was collapsing every legacy name (`fast`, `smart`,
|
||||
`max`) to `auto`, which made two `tests/resolve.test.ts` cases
|
||||
fail because they assert the legacy mapping that older config
|
||||
files depend on. Restored the original semantics:
|
||||
- `fast` → flash with `effort: high` (no auto-escalate)
|
||||
- `smart` → auto (flash + max + auto-escalate)
|
||||
- `max` → pro
|
||||
Anything else still collapses to auto. Suite back to 1568 / 1568.
|
||||
|
||||
## [0.12.4] — 2026-04-28
|
||||
|
||||
**Headline:** The two real editor problems that 0.12.2/3 didn't
|
||||
actually fix: highlighting was still missing for every language,
|
||||
and the new markdown preview produced a half-rendered page where
|
||||
the bottom got dumped into a `<pre>`.
|
||||
|
||||
### Editor
|
||||
|
||||
- **Pin `@lezer/highlight` + `@lezer/common` in the esm.sh
|
||||
`?deps=` list.** The silent-no-highlights failure was caused by
|
||||
duplicated `@lezer/highlight` instances across CodeMirror
|
||||
packages: `tags.keyword` etc. are JS objects compared by
|
||||
identity, so when the language pack and the theme each loaded
|
||||
their own copy, the parser produced tags the theme didn't
|
||||
recognize, and all coloring quietly went away. Pinning common
|
||||
+ highlight forces every package to share one set.
|
||||
- **Separate `Marked` instance for the markdown preview
|
||||
(`previewMarked`).** The chat renderer is loaded with custom
|
||||
`code` handling for SEARCH/REPLACE diffs and edit:foo/path
|
||||
fence syntax — that ran on every preview too, occasionally
|
||||
swallowing the rest of the document into one `<pre>` block on
|
||||
certain inputs. Preview now uses a vanilla marked + a slim
|
||||
hljs-only `code` override.
|
||||
|
||||
## [0.12.3] — 2026-04-28
|
||||
|
||||
**Headline:** Editor as a first-class sidebar tab. The drawer was
|
||||
the only way in, which meant you had to start a chat and click a
|
||||
file path before you could browse anything. Now there's a sidebar
|
||||
entry that opens the file tree directly.
|
||||
|
||||
### Editor
|
||||
|
||||
- New **Editor** tab in the sidebar (after Chat). Mounts the
|
||||
`EditorPanel` full-width inside `.main` — same file tree,
|
||||
tabs, CodeMirror — no drawer chrome.
|
||||
- `.main` gets a `main-editor` modifier when the editor tab is
|
||||
active, dropping the 28×36 panel padding and letting the
|
||||
editor fill the viewport.
|
||||
- The chat drawer entry point still works (clicking a path in a
|
||||
tool card slides the drawer in over the current tab). Drawer
|
||||
and sidebar Editor are separate instances; their tab state
|
||||
doesn't share yet — revisit if it becomes annoying.
|
||||
|
||||
## [0.12.2] — 2026-04-28
|
||||
|
||||
**Headline:** Editor polish pass. Tabs at the top span the full
|
||||
editor width like VS Code, syntax highlighting actually shows up,
|
||||
the gutter/line numbers match the dark theme, autocomplete pops
|
||||
on every keystroke instead of waiting for a manual trigger.
|
||||
|
||||
### Editor
|
||||
|
||||
- **Tabs on top, full width** — moved out of `.editor-main` and
|
||||
into a sibling `.editor-tabs` that sits above the side+main
|
||||
body row. Active tab gets a primary-color top border and the
|
||||
editor's own background, so it visually merges into the code
|
||||
surface (VS Code pattern). The file panel can collapse and the
|
||||
tab bar stays put.
|
||||
- **Highlighting works** — `oneDark` already ships its own
|
||||
HighlightStyle; the existing `defaultHighlightStyle` wrap was
|
||||
fine but ordered before `oneDark`, so it didn't cover languages
|
||||
oneDark misses. Reordered to fall back AFTER oneDark and added
|
||||
`highlightActiveLineGutter` so the active row stands out in the
|
||||
gutter too.
|
||||
- **Gutter restyled** — `.cm-gutters` gets a darker `#21252b`
|
||||
background, line numbers use the muted `#495162` for inactive
|
||||
rows and `#abb2bf` for the active row, with a 40px min-width
|
||||
and 16px right-padding. Fold gutter ships alongside (click the
|
||||
arrow next to a brace to fold).
|
||||
- **Autocomplete** — `autocompletion({ activateOnTyping: true,
|
||||
closeOnBlur: true, maxRenderedOptions: 30 })` so suggestions
|
||||
pop while you type. Added `completionKeymap` so Tab/Enter pick
|
||||
the highlighted entry. Popup styled to the dark palette.
|
||||
- **Tab close ergonomics** — close button has a fixed 18px box
|
||||
so the tab doesn't jump width when the dirty dot toggles.
|
||||
|
||||
All edits in `dashboard/app.js` `EditorPanel` + `dashboard/app.css`.
|
||||
|
||||
## [0.12.1] — 2026-04-28
|
||||
|
||||
**Headline:** Editor v2 — VS Code-style file tree, collapsible file
|
||||
panel, wider drawer. The 0.12.0 editor opened on the right at 50%
|
||||
with a flat alphabetical file list; on a normal-width window that
|
||||
felt cramped and the file list scrolled forever.
|
||||
|
||||
### Editor
|
||||
|
||||
- **File tree** — flat path list collapses into a recursive folder
|
||||
tree. Folders sort first, files alphabetically; click `▶` to
|
||||
expand, `▼` to collapse. The expanded set lives in panel state so
|
||||
it survives drawer close/reopen within a session.
|
||||
- **Collapsible side panel** — `◀` button at the top of the file
|
||||
panel hides everything except a thin `▶` button that brings it
|
||||
back. Editor area gets the full drawer width when files are out
|
||||
of the way.
|
||||
- **Wider drawer** — `.editor-drawer-host.open` bumped from 50% →
|
||||
65% (min-width 360 → 420) so the editor breathes.
|
||||
- **Filter still flat** — when the search box has text, the tree
|
||||
view collapses to the existing flat filtered list (paths are
|
||||
more useful than indented names when you're searching).
|
||||
|
||||
No backend changes. All edits in `dashboard/app.js` `EditorPanel`
|
||||
+ `dashboard/app.css`.
|
||||
|
||||
## [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
|
||||
|
||||
@@ -72,6 +72,28 @@ command list.
|
||||
|
||||
---
|
||||
|
||||
## Web dashboard *(new in 0.12)*
|
||||
|
||||
Type `/dashboard` inside any session and Reasonix prints a localhost
|
||||
URL with a one-time token. Open it for a 13-tab control surface that
|
||||
mirrors the running TUI — chat (with live streaming), the editor (file
|
||||
tree + CodeMirror, syntax highlighting + autocomplete + side-by-side
|
||||
diff for pending edits), Usage / Sessions / Plans / Tools /
|
||||
Permissions / System / MCP / Skills / Memory / Hooks / Settings.
|
||||
|
||||
```
|
||||
reasonix code › /dashboard
|
||||
▸ http://127.0.0.1:54219/?token=… (open in browser)
|
||||
```
|
||||
|
||||
127.0.0.1 only, ephemeral token expires when the session ends, every
|
||||
mutation is CSRF-checked. The TUI keeps working — modals (shell
|
||||
confirms, plan reviews, edit gates) mirror to whichever surface you
|
||||
look at first. No build step, no Electron, no separate process to
|
||||
keep alive.
|
||||
|
||||
---
|
||||
|
||||
## Why Reasonix? (vs Cursor / Claude Code / Cline / Aider)
|
||||
|
||||
Three things you'd come to Reasonix for, that nothing else combines:
|
||||
@@ -316,8 +338,9 @@ reasonix code › /commit "fix: findByEmail case-insensitive"
|
||||
session file.
|
||||
- `/effort high` — step down from the default `max` agent-class
|
||||
reasoning_effort for cheaper/faster turns on simple tasks.
|
||||
- `npx reasonix code --preset max` — v4-pro + 3-way self-consistency
|
||||
branching for gnarly refactors.
|
||||
- `npx reasonix code --preset pro` — v4-pro for the whole session,
|
||||
no auto-downgrade to flash. Pair with `--branch 3` if you want
|
||||
3-way self-consistency on gnarly refactors.
|
||||
- `npx reasonix code src/` — narrower sandbox (only `src/` is
|
||||
writable).
|
||||
- `npx reasonix code --no-session` — ephemeral; nothing saved.
|
||||
@@ -348,8 +371,8 @@ 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.5.21 · deepseek-v4-pro · harvest · max …`, the trailing
|
||||
`max` is the reasoning-effort badge — `/effort high` to step down).
|
||||
`Reasonix 0.12.6 · v4-flash · AUTO · max …`, the trailing `max` is
|
||||
the reasoning-effort badge — `/effort high` to step down).
|
||||
A quiet 24-hour background check against
|
||||
the npm registry surfaces a yellow `update: X.Y.Z` on the right side
|
||||
of the same row when a newer version has been published. No blocking,
|
||||
@@ -535,7 +558,7 @@ your own MCP servers. Sessions persist per name under
|
||||
|
||||
```bash
|
||||
npx reasonix # uses saved config + wizard-selected MCP
|
||||
npx reasonix --preset smart # reasoner + R1 harvest for this run
|
||||
npx reasonix --preset pro # pin v4-pro for the whole run (no auto-downgrade)
|
||||
npx reasonix --session design # named session — resume later with --session design
|
||||
```
|
||||
|
||||
@@ -570,7 +593,7 @@ rendering, retries.
|
||||
|
||||
| command | what it does |
|
||||
|---|---|
|
||||
| `/preset <fast\|smart\|max>` | one-tap bundle (model + harvest + branch) |
|
||||
| `/preset <auto\|flash\|pro>` | model commitment — `auto` = flash with escalation, `flash` = locked flash, `pro` = locked pro |
|
||||
| `/model <id>` | switch DeepSeek model (`deepseek-v4-flash`, `deepseek-v4-pro`, plus `deepseek-chat` / `deepseek-reasoner` compat aliases) |
|
||||
| `/models` | list live models from DeepSeek `/models` endpoint |
|
||||
| `/harvest [on\|off]` | toggle R1 plan-state extraction |
|
||||
@@ -750,7 +773,7 @@ npx reasonix sessions # list saved sessions
|
||||
Common flags:
|
||||
|
||||
```bash
|
||||
--preset <fast|smart|max> # bundle (model + harvest + branch)
|
||||
--preset <auto|flash|pro> # model commitment (auto / locked-flash / locked-pro)
|
||||
--model <id> # explicit model id
|
||||
--harvest / --no-harvest # R1 plan-state extraction
|
||||
--branch <N> # self-consistency budget
|
||||
|
||||
+26
-7
@@ -69,6 +69,25 @@ Windows Terminal)。任何时候按 `Esc` 中断;`/help` 查看完整命令
|
||||
|
||||
---
|
||||
|
||||
## Web 控制台 *(0.12 新功能)*
|
||||
|
||||
会话内输入 `/dashboard`,Reasonix 会打印一个带一次性 token 的本地 URL。
|
||||
浏览器打开后是一个 13 个面板的控制面 —— 与正在运行的 TUI 实时双向同步:
|
||||
聊天(流式输出)、编辑器(文件树 + CodeMirror,语法高亮 + 自动补全 + 待
|
||||
审编辑的左右对比 diff)、Usage / Sessions / Plans / Tools / Permissions /
|
||||
System / MCP / Skills / Memory / Hooks / Settings。
|
||||
|
||||
```
|
||||
reasonix code › /dashboard
|
||||
▸ http://127.0.0.1:54219/?token=… (open in browser)
|
||||
```
|
||||
|
||||
仅监听 127.0.0.1,会话结束 token 立即失效,所有改动都走 CSRF 校验。
|
||||
TUI 继续可用 —— 弹窗(shell 确认、plan 审阅、edit 闸门)会同步到先看到
|
||||
它的那一边,另一边自动消失。没有打包步骤,没有 Electron,没有额外进程。
|
||||
|
||||
---
|
||||
|
||||
## 为什么选 Reasonix?(vs Cursor / Claude Code / Cline / Aider)
|
||||
|
||||
三件事,别家不会同时都给你:
|
||||
@@ -284,8 +303,8 @@ reasonix code › /commit "fix: findByEmail case-insensitive"
|
||||
- `/undo` —— 回滚上一批已应用的编辑。
|
||||
- `/new` —— 在同一目录开新会话,但不丢失旧会话文件。
|
||||
- `/effort high` —— 从默认 `max` agent 推理强度降一档,简单任务更省更快。
|
||||
- `npx reasonix code --preset max` —— v4-pro + 三路 self-consistency 分支,
|
||||
适合疑难重构。
|
||||
- `npx reasonix code --preset pro` —— 整轮锁定 v4-pro,不再自动降级到
|
||||
flash。如果想要 self-consistency 分支,加 `--branch 3` 跑三路投票。
|
||||
- `npx reasonix code src/` —— 更窄的沙箱(只有 `src/` 可写)。
|
||||
- `npx reasonix code --no-session` —— 临时会话,什么都不存。
|
||||
|
||||
@@ -314,8 +333,8 @@ completion、没有工具参数。`reasonix stats <transcript>` 仍兼容老用
|
||||
### 保持最新
|
||||
|
||||
面板顶栏在 `Reasonix` 旁边显示当前版本(如
|
||||
`Reasonix v0.5.21 · deepseek-v4-pro · harvest · max …`,最后那个 `max` 是
|
||||
推理强度徽章 —— `/effort high` 可降一档)。后台每 24 小时静默查询一次 npm
|
||||
`Reasonix 0.12.6 · v4-flash · AUTO · max …`,最后那个 `max` 是推理强度
|
||||
徽章 —— `/effort high` 可降一档)。后台每 24 小时静默查询一次 npm
|
||||
registry,发现新版会在同一行右侧显示黄色 `update: X.Y.Z`。不阻塞、不烦人,
|
||||
每天最多查一次,离线 / 防火墙下静默失败。
|
||||
|
||||
@@ -479,7 +498,7 @@ schema 设计、架构讨论,或者驱动你自己的 MCP 服务器。会话
|
||||
|
||||
```bash
|
||||
npx reasonix # 用已保存配置 + 向导选过的 MCP
|
||||
npx reasonix --preset smart # 这次跑用 reasoner + R1 harvest
|
||||
npx reasonix --preset pro # 整轮锁定 v4-pro(不自动降级)
|
||||
npx reasonix --session design # 命名会话 — 之后 --session design 续聊
|
||||
```
|
||||
|
||||
@@ -513,7 +532,7 @@ MCP 工具走和原生工具一样的 Cache-First + 修复 + 上下文安全管
|
||||
|
||||
| 命令 | 作用 |
|
||||
|---|---|
|
||||
| `/preset <fast\|smart\|max>` | 一键预设(model + harvest + branch) |
|
||||
| `/preset <auto\|flash\|pro>` | 模型策略 —— `auto` = flash 自动升级、`flash` = 锁 flash、`pro` = 锁 pro |
|
||||
| `/model <id>` | 切换 DeepSeek 模型(`deepseek-v4-flash`、`deepseek-v4-pro`,加上 `deepseek-chat` / `deepseek-reasoner` 兼容别名) |
|
||||
| `/models` | 列出 DeepSeek `/models` 端点的可用模型 |
|
||||
| `/harvest [on\|off]` | 切换 R1 plan-state 提取 |
|
||||
@@ -679,7 +698,7 @@ npx reasonix sessions # 列已保存会话
|
||||
常用 flag:
|
||||
|
||||
```bash
|
||||
--preset <fast|smart|max> # 预设组合(model + harvest + branch)
|
||||
--preset <auto|flash|pro> # 模型策略(auto / 锁 flash / 锁 pro)
|
||||
--model <id> # 显式指定模型 ID
|
||||
--harvest / --no-harvest # R1 plan-state 提取
|
||||
--branch <N> # self-consistency 预算
|
||||
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
# Reasonix — working knowledge
|
||||
|
||||
TypeScript project. DeepSeek-native coding agent, cache-first loop.
|
||||
MIT-licensed. Node ≥20.10 required.
|
||||
|
||||
## Stack
|
||||
|
||||
- **Language** — TS 5.6+, ES2022, ESM (`"type": "module"`)
|
||||
- **CLI** — Commander.js + Ink 5 (React 18) TUI
|
||||
- **Test** — Vitest 2.x
|
||||
- **Lint / Format** — Biome 1.9 (2-space, double quotes, semicolons always, 100 width)
|
||||
- **Build** — tsup (bundle), `tsx` (dev runner)
|
||||
- **MCP** — stdio + SSE transports, in-process fake in tests
|
||||
|
||||
## Layout
|
||||
|
||||
| Path | What |
|
||||
|---|---|
|
||||
| `src/` | All source — `mcp/`, `tools/`, `cli/`, `code/`, `repair/`, `index/` |
|
||||
| `src/cli/` | CLI entry + commands (`chat.tsx`, `code.tsx`, `diff.ts`, etc.) + Ink TUI in `ui/` |
|
||||
| `src/tools/` | Tool defs (filesystem, shell, MCP, plan, subagent, web, workspace) |
|
||||
| `src/mcp/` | MCP client, transports (stdio, SSE), registry, spec |
|
||||
| `src/repair/` | Tool-call repair pipeline (flatten, scavenge, storm, truncation) |
|
||||
| `src/index/` | Semantic vector index |
|
||||
| `tests/` | Vitest tests, flat `*.test.ts` |
|
||||
| `examples/` | `basic-chat.ts`, `mcp-server-demo.ts`, etc. |
|
||||
| `benchmarks/` | Harvest + tau-bench harnesses |
|
||||
| `data/` | Tokenizer data (`deepseek-tokenizer.json.gz`) |
|
||||
| `dist/` | Build output — **do not edit** |
|
||||
| `.github/` | CI + issue templates |
|
||||
|
||||
## Commands
|
||||
|
||||
```sh
|
||||
npm run build # tsup → dist/
|
||||
npm run dev # tsx src/cli/index.ts
|
||||
npm run chat # tsx src/cli/index.ts chat
|
||||
npm run test # vitest run
|
||||
npm run test:watch # vitest
|
||||
npm run lint # biome check src tests
|
||||
npm run lint:fix # biome check --write src tests
|
||||
npm run format # biome format --write src tests
|
||||
npm run typecheck # tsc --noEmit
|
||||
```
|
||||
|
||||
`prepublishOnly`: lint → typecheck → test → build.
|
||||
|
||||
## Conventions
|
||||
|
||||
- **Imports** — explicit `import type` for type-only imports (Biome `useImportType: warn`). Direct relative imports within project, no barrel re-exports.
|
||||
- **Exports** — named exports only; no `export default`. Entry: `src/index.ts`.
|
||||
- **Tests** — vitest `describe`/`it`/`expect`, no globals. Naming: `<module>.test.ts` flat in `tests/`.
|
||||
- **JSX** — `.tsx` for Ink components. `jsx: "react"` in tsconfig.
|
||||
- **TypeScript** — `strict`, `noUncheckedIndexedAccess`, `noImplicitOverride`. Tools accept `ToolCallContext` (abort signal).
|
||||
- **MCP** — All transports implement `McpTransport` interface. Tools registered via registry at startup.
|
||||
- **Changelog** — Keep a Changelog format. Semver.
|
||||
|
||||
## Watch out for
|
||||
|
||||
- **This IS Reasonix** — edits to `src/loop.ts`, `src/repair/`, `src/tools/`, `src/mcp/` affect every session. Test before publishing.
|
||||
- **SEARCH must match byte-for-byte** — the edit-gate in `src/code/edit-blocks.ts` enforces exact match. Trailing whitespace or wrong indent = mismatch.
|
||||
- **`dist/`** is generated by `tsup`. Never hand-edit.
|
||||
- **`.reasonix/semantic/`** is auto-generated vector index. Never hand-edit.
|
||||
- **`sessions/` and `.reasonix/sessions/`** are user-private, git-ignored (per `.gitignore`).
|
||||
+1
-1
@@ -24,6 +24,6 @@
|
||||
}
|
||||
},
|
||||
"files": {
|
||||
"ignore": ["dist", "node_modules", "coverage", "*.d.ts"]
|
||||
"ignore": ["dist", "node_modules", "coverage", "*.d.ts", "dashboard/codemirror.js"]
|
||||
}
|
||||
}
|
||||
+2540
File diff suppressed because it is too large.
Load diff
+4542
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,36 @@
|
||||
var A=class O{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,i){[e,t]=CO(this,e,t);let r=[];return this.decompose(0,e,r,2),i.length&&i.decompose(0,i.length,r,3),this.decompose(t,this.length,r,1),WO.from(r,this.length-(t-e)+i.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=CO(this,e,t);let i=[];return this.decompose(e,t,i,0),WO.from(i,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),i=this.length-this.scanIdentical(e,-1),r=new $O(this),n=new $O(e);for(let s=t,a=t;;){if(r.next(s),n.next(s),s=0,r.lineBreak!=n.lineBreak||r.done!=n.done||r.value!=n.value)return!1;if(a+=r.value.length,r.done||a>=i)return!0}}iter(e=1){return new $O(this,e)}iterRange(e,t=this.length){return new Zr(this,e,t)}iterLines(e,t){let i;if(e==null)i=this.iter();else{t==null&&(t=this.lines+1);let r=this.line(e).from;i=this.iterRange(r,Math.max(r,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new _r(i)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?O.empty:e.length<=32?new Ce(e):WO.from(Ce.split(e,[]))}},Ce=class O extends A{constructor(e,t=um(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,i,r){for(let n=0;;n++){let s=this.text[n],a=r+s.length;if((t?i:a)>=e)return new gs(r,a,i,s);r=a+1,i++}}decompose(e,t,i,r){let n=e<=0&&t>=this.length?this:new O(wc(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(r&1){let s=i.pop(),a=Yr(n.text,s.text.slice(),0,n.length);if(a.length<=32)i.push(new O(a,s.length+n.length));else{let o=a.length>>1;i.push(new O(a.slice(0,o)),new O(a.slice(o)))}}else i.push(n)}replace(e,t,i){if(!(i instanceof O))return super.replace(e,t,i);[e,t]=CO(this,e,t);let r=Yr(this.text,Yr(i.text,wc(this.text,0,e)),t),n=this.length+i.length-(t-e);return r.length<=32?new O(r,n):WO.from(O.split(r,[]),n)}sliceString(e,t=this.length,i=`
|
||||
`){[e,t]=CO(this,e,t);let r="";for(let n=0,s=0;n<=t&&s<this.text.length;s++){let a=this.text[s],o=n+a.length;n>e&&s&&(r+=i),e<o&&t>n&&(r+=a.slice(Math.max(0,e-n),t-n)),n=o+1}return r}flatten(e){for(let t of this.text)e.push(t)}scanIdentical(){return 0}static split(e,t){let i=[],r=-1;for(let n of e)i.push(n),r+=n.length+1,i.length==32&&(t.push(new O(i,r)),i=[],r=-1);return r>-1&&t.push(new O(i,r)),t}},WO=class O extends A{constructor(e,t){super(),this.children=e,this.length=t,this.lines=0;for(let i of e)this.lines+=i.lines}lineInner(e,t,i,r){for(let n=0;;n++){let s=this.children[n],a=r+s.length,o=i+s.lines-1;if((t?o:a)>=e)return s.lineInner(e,t,i,r);r=a+1,i=o+1}}decompose(e,t,i,r){for(let n=0,s=0;s<=t&&n<this.children.length;n++){let a=this.children[n],o=s+a.length;if(e<=o&&t>=s){let l=r&((s<=e?1:0)|(o>=t?2:0));s>=e&&o<=t&&!l?i.push(a):a.decompose(e-s,t-s,i,l)}s=o+1}}replace(e,t,i){if([e,t]=CO(this,e,t),i.lines<this.lines)for(let r=0,n=0;r<this.children.length;r++){let s=this.children[r],a=n+s.length;if(e>=n&&t<=a){let o=s.replace(e-n,t-n,i),l=this.lines-s.lines+o.lines;if(o.lines<l>>4&&o.lines>l>>6){let c=this.children.slice();return c[r]=o,new O(c,this.length-(t-e)+i.length)}return super.replace(n,a,o)}n=a+1}return super.replace(e,t,i)}sliceString(e,t=this.length,i=`
|
||||
`){[e,t]=CO(this,e,t);let r="";for(let n=0,s=0;n<this.children.length&&s<=t;n++){let a=this.children[n],o=s+a.length;s>e&&n&&(r+=i),e<o&&t>s&&(r+=a.sliceString(e-s,t-s,i)),s=o+1}return r}flatten(e){for(let t of this.children)t.flatten(e)}scanIdentical(e,t){if(!(e instanceof O))return 0;let i=0,[r,n,s,a]=t>0?[0,0,this.children.length,e.children.length]:[this.children.length-1,e.children.length-1,-1,-1];for(;;r+=t,n+=t){if(r==s||n==a)return i;let o=this.children[r],l=e.children[n];if(o!=l)return i+o.scanIdentical(l,t);i+=o.length+1}}static from(e,t=e.reduce((i,r)=>i+r.length+1,-1)){let i=0;for(let f of e)i+=f.lines;if(i<32){let f=[];for(let d of e)d.flatten(f);return new Ce(f,t)}let r=Math.max(32,i>>5),n=r<<1,s=r>>1,a=[],o=0,l=-1,c=[];function h(f){let d;if(f.lines>n&&f instanceof O)for(let u of f.children)h(u);else f.lines>s&&(o>s||!o)?($(),a.push(f)):f instanceof Ce&&o&&(d=c[c.length-1])instanceof Ce&&f.lines+d.lines<=32?(o+=f.lines,l+=f.length+1,c[c.length-1]=new Ce(d.text.concat(f.text),d.length+1+f.length)):(o+f.lines>r&&$(),o+=f.lines,l+=f.length+1,c.push(f))}function $(){o!=0&&(a.push(c.length==1?c[0]:O.from(c,l)),l=-1,o=c.length=0)}for(let f of e)h(f);return $(),a.length==1?a[0]:new O(a,t)}};A.empty=new Ce([""],0);function um(O){let e=-1;for(let t of O)e+=t.length+1;return e}function Yr(O,e,t=0,i=1e9){for(let r=0,n=0,s=!0;n<O.length&&r<=i;n++){let a=O[n],o=r+a.length;o>=t&&(o>i&&(a=a.slice(0,i-r)),r<t&&(a=a.slice(t-r)),s?(e[e.length-1]+=a,s=!1):e.push(a)),r=o+1}return e}function wc(O,e,t){return Yr(O,[""],e,t)}var $O=class{constructor(e,t=1){this.dir=t,this.done=!1,this.lineBreak=!1,this.value="",this.nodes=[e],this.offsets=[t>0?1:(e instanceof Ce?e.text.length:e.children.length)<<1]}nextInner(e,t){for(this.done=this.lineBreak=!1;;){let i=this.nodes.length-1,r=this.nodes[i],n=this.offsets[i],s=n>>1,a=r instanceof Ce?r.text.length:r.children.length;if(s==(t>0?a:0)){if(i==0)return this.done=!0,this.value="",this;t>0&&this.offsets[i-1]++,this.nodes.pop(),this.offsets.pop()}else if((n&1)==(t>0?0:1)){if(this.offsets[i]+=t,e==0)return this.lineBreak=!0,this.value=`
|
||||
`,this;e--}else if(r instanceof Ce){let o=r.text[s+(t<0?-1:0)];if(this.offsets[i]+=t,o.length>Math.max(0,e))return this.value=e==0?o:t>0?o.slice(e):o.slice(0,o.length-e),this;e-=o.length}else{let o=r.children[s+(t<0?-1:0)];e>o.length?(e-=o.length,this.offsets[i]+=t):(t<0&&this.offsets[i]--,this.nodes.push(o),this.offsets.push(t>0?1:(o instanceof Ce?o.text.length:o.children.length)<<1))}}}next(e=0){return e<0&&(this.nextInner(-e,-this.dir),e=this.value.length),this.nextInner(e,this.dir)}},Zr=class{constructor(e,t,i){this.value="",this.done=!1,this.cursor=new $O(e,t>i?-1:1),this.pos=t>i?e.length:0,this.from=Math.min(t,i),this.to=Math.max(t,i)}nextInner(e,t){if(t<0?this.pos<=this.from:this.pos>=this.to)return this.value="",this.done=!0,this;e+=Math.max(0,t<0?this.pos-this.to:this.from-this.pos);let i=t<0?this.pos-this.from:this.to-this.pos;e>i&&(e=i),i-=e;let{value:r}=this.cursor.next(e);return this.pos+=(r.length+e)*t,this.value=r.length<=i?r:t<0?r.slice(r.length-i):r.slice(0,i),this.done=!this.value,this}next(e=0){return e<0?e=Math.max(e,this.from-this.pos):e>0&&(e=Math.min(e,this.to-this.pos)),this.nextInner(e,this.cursor.dir)}get lineBreak(){return this.cursor.lineBreak&&this.value!=""}},_r=class{constructor(e){this.inner=e,this.afterBreak=!0,this.value="",this.done=!1}next(e=0){let{done:t,lineBreak:i,value:r}=this.inner.next(e);return t&&this.afterBreak?(this.value="",this.afterBreak=!1):t?(this.done=!0,this.value=""):i?this.afterBreak?this.value="":(this.afterBreak=!0,this.next()):(this.value=r,this.afterBreak=!1),this}get lineBreak(){return!1}};typeof Symbol<"u"&&(A.prototype[Symbol.iterator]=function(){return this.iter()},$O.prototype[Symbol.iterator]=Zr.prototype[Symbol.iterator]=_r.prototype[Symbol.iterator]=function(){return this});var gs=class{constructor(e,t,i,r){this.from=e,this.to=t,this.number=i,this.text=r}get length(){return this.to-this.from}};function CO(O,e,t){return e=Math.max(0,Math.min(O.length,e)),[e,Math.max(e,Math.min(O.length,t))]}var UO="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,3b,f,,w,1j,,,,4,8,4,,3,7,a,2,t,,1m,,,,2,4,8,,9,,a,2,q,,2,2,1l,,4,2,4,2,2,3,3,,u,2,3,,b,2,1l,,4,5,,2,4,,k,2,m,6,,,1m,,,2,,4,8,,7,3,a,2,u,,1n,,,,c,,9,,14,,3,,1l,3,5,3,,4,7,2,b,2,t,,1m,,2,,2,,3,,5,2,7,2,b,2,s,2,1l,2,,,2,4,8,,9,,a,2,t,,20,,4,,2,3,,,8,,29,,2,7,c,8,2q,,2,9,b,6,22,2,r,,,,,,1j,e,,5,,2,5,b,,10,9,,2u,4,,6,,2,2,2,p,2,4,3,g,4,d,,2,2,6,,f,,jj,3,qa,3,t,3,t,2,u,2,1s,2,,7,8,,2,b,9,,19,3,3b,2,y,,3a,3,4,2,9,,6,3,63,2,2,,1m,,,7,,,,,2,8,6,a,2,,1c,h,1r,4,1c,7,,,5,,14,9,c,2,w,4,2,2,,3,1k,,,2,3,,,3,1m,8,2,2,48,3,,d,,7,4,,6,,3,2,5i,1m,,5,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,p,2,5,,47,2,q,i,d,,12,8,p,b,1a,3,1c,,2,4,2,2,13,,1v,6,2,2,2,2,c,,8,,1b,,1f,,,3,2,2,5,2,,,16,2,8,,6m,,2,,4,,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,ar,2,49,b,4w,,1i,f,1k,3,1d,4,2,2,1x,3,10,5,,8,1q,,c,2,1g,9,a,4,2,,2n,3,2,,,2,6,,4g,,3,8,l,2,1l,2,,,,,m,,e,7,3,5,5f,8,2,3,,,n,,29,,2,6,,,2,,,2,,2,6j,,2,4,6,2,,2,r,2,2d,8,2,,,2,2y,,,,2,6,,,2t,3,2,4,,5,77,9,,2,6t,,a,2,,,4,,40,4,2,2,4,,w,a,14,6,2,4,8,,9,6,2,3,1a,d,,2,ba,7,,6,,,2a,m,2,7,,2,,2,3e,6,3,,,2,,7,,,20,2,3,,,,9n,2,f0b,5,1n,7,t4,,1r,4,29,,f5k,2,43q,,,3,4,5,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,79,7,c5,4,15s,7,31,7,240,5,gx7k,2o,3k,6o".split(",").map(O=>O?parseInt(O,36):1);for(let O=1;O<UO.length;O++)UO[O]+=UO[O-1];function pm(O){for(let e=1;e<UO.length;e+=2)if(UO[e]>O)return UO[e-1]<=O;return!1}function bc(O){return O>=127462&&O<=127487}var xc=8205;function Qe(O,e,t=!0,i=!0){return(t?Rc:mm)(O,e,i)}function Rc(O,e,t){if(e==O.length)return e;e&&zc(O.charCodeAt(e))&&Vc(O.charCodeAt(e-1))&&e--;let i=de(O,e);for(e+=be(i);e<O.length;){let r=de(O,e);if(i==xc||r==xc||t&&pm(r))e+=be(r),i=r;else if(bc(r)){let n=0,s=e-2;for(;s>=0&&bc(de(O,s));)n++,s-=2;if(n%2==0)break;e+=2}else break}return e}function mm(O,e,t){for(;e>0;){let i=Rc(O,e-2,t);if(i<e)return i;e--}return 0}function zc(O){return O>=56320&&O<57344}function Vc(O){return O>=55296&&O<56320}function de(O,e){let t=O.charCodeAt(e);if(!Vc(t)||e+1==O.length)return t;let i=O.charCodeAt(e+1);return zc(i)?(t-55296<<10)+(i-56320)+65536:t}function Pi(O){return O<=65535?String.fromCharCode(O):(O-=65536,String.fromCharCode((O>>10)+55296,(O&1023)+56320))}function be(O){return O<65536?1:2}var Ps=/\r\n?|\n/,ue=function(O){return O[O.Simple=0]="Simple",O[O.TrackDel=1]="TrackDel",O[O.TrackBefore=2]="TrackBefore",O[O.TrackAfter=3]="TrackAfter",O}(ue||(ue={})),kt=class O{constructor(e){this.sections=e}get length(){let e=0;for(let t=0;t<this.sections.length;t+=2)e+=this.sections[t];return e}get newLength(){let e=0;for(let t=0;t<this.sections.length;t+=2){let i=this.sections[t+1];e+=i<0?this.sections[t]:i}return e}get empty(){return this.sections.length==0||this.sections.length==2&&this.sections[1]<0}iterGaps(e){for(let t=0,i=0,r=0;t<this.sections.length;){let n=this.sections[t++],s=this.sections[t++];s<0?(e(i,r,n),r+=n):r+=s,i+=n}}iterChangedRanges(
Line truncated
|
||||
`}get readOnly(){return this.facet(Ac)}phrase(e,...t){for(let i of this.facet(O.phrases))if(Object.prototype.hasOwnProperty.call(i,e)){e=i[e];break}return t.length&&(e=e.replace(/\$(\$|\d*)/g,(i,r)=>{if(r=="$")return"$";let n=+(r||1);return!n||n>t.length?i:t[n-1]})),e}languageDataAt(e,t,i=-1){let r=[];for(let n of this.facet(Uc))for(let s of n(this,t,i))Object.prototype.hasOwnProperty.call(s,e)&&r.push(s[e]);return r}charCategorizer(e){return xm(this.languageDataAt("wordChars",e).join(""))}wordAt(e){let{text:t,from:i,length:r}=this.doc.lineAt(e),n=this.charCategorizer(e),s=e-i,a=e-i;for(;s>0;){let o=Qe(t,s,!1);if(n(t.slice(o,s))!=H.Word)break;s=o}for(;a<r;){let o=Qe(t,a);if(n(t.slice(a,o))!=H.Word)break;a=o}return s==a?null:P.range(s+i,a+i)}};K.allowMultipleSelections=ys;K.tabSize=v.define({combine:O=>O.length?O[0]:4});K.lineSeparator=jc;K.readOnly=Ac;K.phrases=v.define({compare(O,e){let t=Object.keys(O),i=Object.keys(e);return t.length==i.length&&t.every(r=>O[r]==e[r])}});K.languageData=Uc;K.changeFilter=Gc;K.transactionFilter=Cc;K.transactionExtender=Ec;ui.reconfigure=j.define();function Ee(O,e,t={}){let i={};for(let r of O)for(let n of Object.keys(r)){let s=r[n],a=i[n];if(a===void 0)i[n]=s;else if(!(a===s||s===void 0))if(Object.hasOwnProperty.call(t,n))i[n]=t[n](a,s);else throw new Error("Config merge conflict for field "+n)}for(let r in e)i[r]===void 0&&(i[r]=e[r]);return i}var nt=class{eq(e){return this==e}range(e,t=e){return mi.create(e,t,this)}};nt.prototype.startSide=nt.prototype.endSide=0;nt.prototype.point=!1;nt.prototype.mapMode=ue.TrackDel;var mi=class O{constructor(e,t,i){this.from=e,this.to=t,this.value=i}static create(e,t,i){return new O(e,t,i)}};function vs(O,e){return O.from-e.from||O.value.startSide-e.value.startSide}var Ys=class O{constructor(e,t,i,r){this.from=e,this.to=t,this.value=i,this.maxPoint=r}get length(){return this.to[this.to.length-1]}findIndex(e,t,i,r=0){let n=i?this.to:this.from;for(let s=r,a=n.length;;){if(s==a)return s;let o=s+a>>1,l=n[o]-e||(i?this.value[o].endSide:this.value[o].startSide)-t;if(o==s)return l>=0?s:a;l>=0?a=o:s=o+1}}between(e,t,i,r){for(let n=this.findIndex(t,-1e9,!0),s=this.findIndex(i,1e9,!1,n);n<s;n++)if(r(this.from[n]+e,this.to[n]+e,this.value[n])===!1)return!1}map(e,t){let i=[],r=[],n=[],s=-1,a=-1;for(let o=0;o<this.value.length;o++){let l=this.value[o],c=this.from[o]+e,h=this.to[o]+e,$,f;if(c==h){let d=t.mapPos(c,l.startSide,l.mapMode);if(d==null||($=f=d,l.startSide!=l.endSide&&(f=t.mapPos(c,l.endSide),f<$)))continue}else if($=t.mapPos(c,l.startSide),f=t.mapPos(h,l.endSide),$>f||$==f&&l.startSide>0&&l.endSide<=0)continue;(f-$||l.endSide-l.startSide)<0||(s<0&&(s=$),l.point&&(a=Math.max(a,f-$)),i.push(l),r.push($-s),n.push(f-s))}return{mapped:i.length?new O(r,n,i,a):null,pos:s}}},N=class O{constructor(e,t,i,r){this.chunkPos=e,this.chunk=t,this.nextLayer=i,this.maxPoint=r}static create(e,t,i,r){return new O(e,t,i,r)}get length(){let e=this.chunk.length-1;return e<0?0:Math.max(this.chunkEnd(e),this.nextLayer.length)}get size(){if(this.isEmpty)return 0;let e=this.nextLayer.size;for(let t of this.chunk)e+=t.value.length;return e}chunkEnd(e){return this.chunkPos[e]+this.chunk[e].length}update(e){let{add:t=[],sort:i=!1,filterFrom:r=0,filterTo:n=this.length}=e,s=e.filter;if(t.length==0&&!s)return this;if(i&&(t=t.slice().sort(vs)),this.isEmpty)return t.length?O.of(t):this;let a=new qr(this,null,-1).goto(0),o=0,l=[],c=new ft;for(;a.value||o<t.length;)if(o<t.length&&(a.from-t[o].from||a.startSide-t[o].value.startSide)>=0){let h=t[o++];c.addInner(h.from,h.to,h.value)||l.push(h)}else a.rangeIndex==1&&a.chunkIndex<this.chunk.length&&(o==t.length||this.chunkEnd(a.chunkIndex)<t[o].from)&&(!s||r>this.chunkEnd(a.chunkIndex)||n<this.chunkPos[a.chunkIndex])&&c.addChunk(this.chunkPos[a.chunkIndex],this.chunk[a.chunkIndex])?a.nextChunk():((!s||r>a.to||n<a.from||s(a.from,a.to,a.value))&&(c.addInner(a.from,a.to,a.value)||l.push(mi.create(a.from,a.to,a.value))),a.next());return c.finishInner(this.nextLayer.isEmpty&&!l.length?O.empty:this.nextLayer.update({add:l,filter:s,filterFrom:r,filterTo:n}))}map(e){if(e.empty||this.isEmpty)return this;let t=[],i=[],r=-1;for(let s=0;s<this.chunk.length;s++){let a=this.chunkPos[s],o=this.chunk[s],l=e.touchesRange(a,a+o.length);if(l===!1)r=Math.max(r,o.maxPoint),t.push(o),i.push(e.mapPos(a));else if(l===!0){let{mapped:c,pos:h}=o.map(a,e);c&&(r=Math.max(r,c.maxPoint),t.push(c),i.push(h))}}let n=this.nextLayer.map(e);return t.length==0?n:new O(i,t,n||O.empty,r)}between(e,t,i){if(!this.isEmpty){for(let r=0;r<this.chunk.length;r++){let n=this.chunkPos[r],s=this.chunk[r];if(t>=n&&e<=n+s.length&&s.between(n,e-n,t-n,i)===!1)return}this.nextLayer.between(e,t,i)}}iter(e=0){return gi.from([this]).goto(e)}get isEmpty(){return this.nextLayer==this}static iter(e,t=0){return gi.from(e).goto(t)}static compare(e,t,i,r,n=-1){let s=e.filter(h=>h.maxPoint>0||!h.isEmpty&&h.maxPoint>=n),a=t.filter(h=>h.maxPoint>0||!h.isEmpty&&h.maxPoint>=n),o=Yc(s,a,i),l=new QO
Line truncated
|
||||
`)}static newName(){let e=Bc[Ic]||1;return Bc[Ic]=e+1,zs+e.toString(36)}static mount(e,t,i){let r=e[Vs],n=i&&i.nonce;r?n&&r.setNonce(n):r=new qs(e,n),r.mount(Array.isArray(t)?t:[t],e)}},Nc=new Map,qs=class{constructor(e,t){let i=e.ownerDocument||e,r=i.defaultView;if(!e.head&&e.adoptedStyleSheets&&r.CSSStyleSheet){let n=Nc.get(i);if(n)return e[Vs]=n;this.sheet=new r.CSSStyleSheet,Nc.set(i,this)}else this.styleTag=i.createElement("style"),t&&this.styleTag.setAttribute("nonce",t);this.modules=[],e[Vs]=this}mount(e,t){let i=this.sheet,r=0,n=0;for(let s=0;s<e.length;s++){let a=e[s],o=this.modules.indexOf(a);if(o<n&&o>-1&&(this.modules.splice(o,1),n--,o=-1),o==-1){if(this.modules.splice(n++,0,a),i)for(let l=0;l<a.rules.length;l++)i.insertRule(a.rules[l],r++)}else{for(;n<o;)r+=this.modules[n++].rules.length;r+=a.rules.length,n++}}if(i)t.adoptedStyleSheets.indexOf(this.sheet)<0&&(t.adoptedStyleSheets=[this.sheet,...t.adoptedStyleSheets]);else{let s="";for(let o=0;o<this.modules.length;o++)s+=this.modules[o].getRules()+`
|
||||
`;this.styleTag.textContent=s;let a=t.head||t;this.styleTag.parentNode!=a&&a.insertBefore(this.styleTag,a.firstChild)}}setNonce(e){this.styleTag&&this.styleTag.getAttribute("nonce")!=e&&this.styleTag.setAttribute("nonce",e)}};var vt={8:"Backspace",9:"Tab",10:"Enter",12:"NumLock",13:"Enter",16:"Shift",17:"Control",18:"Alt",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",44:"PrintScreen",45:"Insert",46:"Delete",59:";",61:"=",91:"Meta",92:"Meta",106:"*",107:"+",108:",",109:"-",110:".",111:"/",144:"NumLock",145:"ScrollLock",160:"Shift",161:"Shift",162:"Control",163:"Control",164:"Alt",165:"Alt",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'"},EO={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},vm=typeof navigator<"u"&&/Mac/.test(navigator.platform),Ym=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);for(fe=0;fe<10;fe++)vt[48+fe]=vt[96+fe]=String(fe);var fe;for(fe=1;fe<=24;fe++)vt[fe+111]="F"+fe;var fe;for(fe=65;fe<=90;fe++)vt[fe]=String.fromCharCode(fe+32),EO[fe]=String.fromCharCode(fe);var fe;for(Wr in vt)EO.hasOwnProperty(Wr)||(EO[Wr]=vt[Wr]);var Wr;function Fc(O){var e=vm&&O.metaKey&&O.shiftKey&&!O.ctrlKey&&!O.altKey||Ym&&O.shiftKey&&O.key&&O.key.length==1||O.key=="Unidentified",t=!e&&O.key||(O.shiftKey?EO:vt)[O.keyCode]||O.key||"Unidentified";return t=="Esc"&&(t="Escape"),t=="Del"&&(t="Delete"),t=="Left"&&(t="ArrowLeft"),t=="Up"&&(t="ArrowUp"),t=="Right"&&(t="ArrowRight"),t=="Down"&&(t="ArrowDown"),t}function Hr(O){let e;return O.nodeType==11?e=O.getSelection?O:O.ownerDocument:e=O,e.getSelection()}function As(O,e){return e?O==e||O.contains(e.nodeType!=1?e.parentNode:e):!1}function Zm(O){let e=O.activeElement;for(;e&&e.shadowRoot;)e=e.shadowRoot.activeElement;return e}function Dr(O,e){if(!e.anchorNode)return!1;try{return As(O,e.anchorNode)}catch{return!1}}function Ri(O){return O.nodeType==3?dO(O,0,O.nodeValue.length).getClientRects():O.nodeType==1?O.getClientRects():[]}function bi(O,e,t,i){return t?Hc(O,e,t,i,-1)||Hc(O,e,t,i,1):!1}function zi(O){for(var e=0;;e++)if(O=O.previousSibling,!O)return e}function Hc(O,e,t,i,r){for(;;){if(O==t&&e==i)return!0;if(e==(r<0?0:Yt(O))){if(O.nodeName=="DIV")return!1;let n=O.parentNode;if(!n||n.nodeType!=1)return!1;e=zi(O)+(r<0?0:1),O=n}else if(O.nodeType==1){if(O=O.childNodes[e+(r<0?-1:0)],O.nodeType==1&&O.contentEditable=="false")return!1;e=r<0?Yt(O):0}else return!1}}function Yt(O){return O.nodeType==3?O.nodeValue.length:O.childNodes.length}function wa(O,e){let t=e?O.left:O.right;return{left:t,right:t,top:O.top,bottom:O.bottom}}function _m(O){let e=O.visualViewport;return e?{left:0,right:e.width,top:0,bottom:e.height}:{left:0,right:O.innerWidth,top:0,bottom:O.innerHeight}}function zh(O,e){let t=e.width/O.offsetWidth,i=e.height/O.offsetHeight;return(t>.995&&t<1.005||!isFinite(t)||Math.abs(e.width-O.offsetWidth)<1)&&(t=1),(i>.995&&i<1.005||!isFinite(i)||Math.abs(e.height-O.offsetHeight)<1)&&(i=1),{scaleX:t,scaleY:i}}function Rm(O,e,t,i,r,n,s,a){let o=O.ownerDocument,l=o.defaultView||window;for(let c=O,h=!1;c&&!h;)if(c.nodeType==1){let $,f=c==o.body,d=1,u=1;if(f)$=_m(l);else{if(/^(fixed|sticky)$/.test(getComputedStyle(c).position)&&(h=!0),c.scrollHeight<=c.clientHeight&&c.scrollWidth<=c.clientWidth){c=c.assignedSlot||c.parentNode;continue}let g=c.getBoundingClientRect();({scaleX:d,scaleY:u}=zh(c,g)),$={left:g.left,right:g.left+c.clientWidth*d,top:g.top,bottom:g.top+c.clientHeight*u}}let p=0,m=0;if(r=="nearest")e.top<$.top?(m=-($.top-e.top+s),t>0&&e.bottom>$.bottom+m&&(m=e.bottom-$.bottom+m+s)):e.bottom>$.bottom&&(m=e.bottom-$.bottom+s,t<0&&e.top-m<$.top&&(m=-($.top+m-e.top+s)));else{let g=e.bottom-e.top,X=$.bottom-$.top;m=(r=="center"&&g<=X?e.top+g/2-X/2:r=="start"||r=="center"&&t<0?e.top-s:e.bottom-X+s)-$.top}if(i=="nearest"?e.left<$.left?(p=-($.left-e.left+n),t>0&&e.right>$.right+p&&(p=e.right-$.right+p+n)):e.right>$.right&&(p=e.right-$.right+n,t<0&&e.left<$.left+p&&(p=-($.left+p-e.left+n))):p=(i=="center"?e.left+(e.right-e.left)/2-($.right-$.left)/2:i=="start"==a?e.left-n:e.right-($.right-$.left)+n)-$.left,p||m)if(f)l.scrollBy(p,m);else{let g=0,X=0;if(m){let T=c.scrollTop;c.scrollTop+=m/u,X=(c.scrollTop-T)*u}if(p){let T=c.scrollLeft;c.scrollLeft+=p/d,g=(c.scrollLeft-T)*d}e={left:e.left-g,top:e.top-X,right:e.right-g,bottom:e.bottom-X},g&&Math.abs(g-p)<1&&(i="nearest"),X&&Math.abs(X-m)<1&&(r="nearest")}if(f)break;c=c.assignedSlot||c.parentNode}else if(c.nodeType==11)c=c.host;else break}function zm(O){let e=O.ownerDocument;for(let t=O.parentNode;t&&t!=e.body;)if(t.nodeType==1){if(t.scrollHeight>t.clientHeight||t.scrollWidth>t.clientWidth)return t;t=t.assignedSlot||t.parentNode}else if(t.nodeType==11)t=t.host;else break;return null}var Ls=class{constructor(){this.aLine truncated
|
||||
`,r=O.state.doc.line(r.number+(t?1:-1)),n=O.bidiSpans(r),l=O.visualLineSide(r,!t)}if(o){if(!o(c))return a}else{if(!i)return l;o=i(c)}a=l}}function Qg(O,e,t){let i=O.state.charCategorizer(e),r=i(t);return n=>{let s=i(n);return r==H.Space&&(r=s),r==s}}function $g(O,e,t,i){let r=e.head,n=t?1:-1;if(r==(t?O.state.doc.length:0))return P.cursor(r,e.assoc);let s=e.goalColumn,a,o=O.contentDOM.getBoundingClientRect(),l=O.coordsAtPos(r,e.assoc||-1),c=O.documentTop;if(l)s==null&&(s=l.left-o.left),a=n<0?l.top:l.bottom;else{let f=O.viewState.lineBlockAt(r);s==null&&(s=Math.min(o.right-o.left,O.defaultCharacterWidth*(r-f.from))),a=(n<0?f.top:f.bottom)+c}let h=o.left+s,$=i??O.viewState.heightOracle.textHeight>>1;for(let f=0;;f+=10){let d=a+($+f)*n,u=$Q(O,{x:h,y:d},!1,n);if(d<o.top||d>o.bottom||(n<0?u<r:u>r)){let p=O.docView.coordsForChar(u),m=!p||d<p.top?-1:1;return P.cursor(u,m,void 0,s)}}}function Ir(O,e,t){for(;;){let i=0;for(let r of O)r.between(e-1,e+1,(n,s,a)=>{if(e>n&&e<s){let o=i||t||(e-n<s-e?-1:1);e=o<0?n:s,i=o}});if(!i)return e}}function js(O,e,t){let i=Ir(O.state.facet(Ya).map(r=>r(O)),t.from,e.head>t.from?-1:1);return i==t.from?t:P.cursor(i,i<t.from?1:-1)}var ia=class{setSelectionOrigin(e){this.lastSelectionOrigin=e,this.lastSelectionTime=Date.now()}constructor(e){this.view=e,this.lastKeyCode=0,this.lastKeyTime=0,this.lastTouchTime=0,this.lastFocusTime=0,this.lastScrollTop=0,this.lastScrollLeft=0,this.pendingIOSKey=void 0,this.lastSelectionOrigin=null,this.lastSelectionTime=0,this.lastEscPress=0,this.lastContextMenu=0,this.scrollHandlers=[],this.handlers=Object.create(null),this.composing=-1,this.compositionFirstChange=null,this.compositionEndedAt=0,this.compositionPendingKey=!1,this.compositionPendingChange=!1,this.mouseSelection=null,this.draggedContent=null,this.handleEvent=this.handleEvent.bind(this),this.notifiedFocused=e.hasFocus,Y.safari&&e.contentDOM.addEventListener("input",()=>null),Y.gecko&&kg(e.contentDOM.ownerDocument)}handleEvent(e){!Pg(this.view,e)||this.ignoreDuringComposition(e)||e.type=="keydown"&&this.keydown(e)||this.runHandlers(e.type,e)}runHandlers(e,t){let i=this.handlers[e];if(i){for(let r of i.observers)r(this.view,t);for(let r of i.handlers){if(t.defaultPrevented)break;if(r(this.view,t)){t.preventDefault();break}}}}ensureHandlers(e){let t=fg(e),i=this.handlers,r=this.view.contentDOM;for(let n in t)if(n!="scroll"){let s=!t[n].handlers.length,a=i[n];a&&s!=!a.handlers.length&&(r.removeEventListener(n,this.handleEvent),a=null),a||r.addEventListener(n,this.handleEvent,{passive:s})}for(let n in i)n!="scroll"&&!t[n]&&r.removeEventListener(n,this.handleEvent);this.handlers=t}keydown(e){if(this.lastKeyCode=e.keyCode,this.lastKeyTime=Date.now(),e.keyCode==9&&Date.now()<this.lastEscPress+2e3)return!0;if(e.keyCode!=27&&dQ.indexOf(e.keyCode)<0&&(this.view.inputState.lastEscPress=0),Y.android&&Y.chrome&&!e.synthetic&&(e.keyCode==13||e.keyCode==8))return this.view.observer.delayAndroidKey(e.key,e.keyCode),!0;let t;return Y.ios&&!e.synthetic&&!e.altKey&&!e.metaKey&&((t=fQ.find(i=>i.keyCode==e.keyCode))&&!e.ctrlKey||dg.indexOf(e.key)>-1&&e.ctrlKey&&!e.shiftKey)?(this.pendingIOSKey=t||e,setTimeout(()=>this.flushIOSKey(),250),!0):(e.keyCode!=229&&this.view.observer.forceFlush(),!1)}flushIOSKey(e){let t=this.pendingIOSKey;return!t||t.key=="Enter"&&e&&e.from<e.to&&/^\S+$/.test(e.insert.toString())?!1:(this.pendingIOSKey=void 0,IO(this.view.contentDOM,t.key,t.keyCode,t instanceof KeyboardEvent?t:void 0))}ignoreDuringComposition(e){return/^key/.test(e.type)?this.composing>0?!0:Y.safari&&!Y.ios&&this.compositionPendingKey&&Date.now()-this.compositionEndedAt<100?(this.compositionPendingKey=!1,!0):!1:!1}startMouseSelection(e){this.mouseSelection&&this.mouseSelection.destroy(),this.mouseSelection=e}update(e){this.mouseSelection&&this.mouseSelection.update(e),this.draggedContent&&e.docChanged&&(this.draggedContent=this.draggedContent.map(e.changes)),e.transactions.length&&(this.lastKeyCode=this.lastSelectionTime=0)}destroy(){this.mouseSelection&&this.mouseSelection.destroy()}};function ch(O,e){return(t,i)=>{try{return e.call(O,i,t)}catch(r){ve(t.state,r)}}}function fg(O){let e=Object.create(null);function t(i){return e[i]||(e[i]={observers:[],handlers:[]})}for(let i of O){let r=i.spec;if(r&&r.domEventHandlers)for(let n in r.domEventHandlers){let s=r.domEventHandlers[n];s&&t(n).handlers.push(ch(i.value,s))}if(r&&r.domEventObservers)for(let n in r.domEventObservers){let s=r.domEventObservers[n];s&&t(n).observers.push(ch(i.value,s))}}for(let i in st)t(i).handlers.push(st[i]);for(let i in at)t(i).observers.push(at[i]);return e}var fQ=[{key:"Backspace",keyCode:8,inputType:"deleteContentBackward"},{key:"Enter",keyCode:13,inputType:"insertParagraph"},{key:"Enter",keyCode:13,inputType:"insertLineBreak"},{key:"Delete",keyCode:46,inputType:"deleteContentForward"}],dg="dthko",dQ=[16,17,18,20,91,92,224,225],Gr=6;function Cr(O){return Math.max(0,O)*.7+8}function ug(O,e){return Math.max(Math.abs(O.clientX-e.clientX),Math.abs(
Line truncated
|
||||
`&&O.lineWrapping&&(i&&(i=P.single(i.main.anchor-1,i.main.head-1)),t={from:r.from,to:r.to,insert:A.of([" "])}),t){if(Y.ios&&O.inputState.flushIOSKey(t)||Y.android&&(t.to==r.to&&(t.from==r.from||t.from==r.from-1&&O.state.sliceDoc(t.from,r.from)==" ")&&t.insert.length==1&&t.insert.lines==2&&IO(O.contentDOM,"Enter",13)||(t.from==r.from-1&&t.to==r.to&&t.insert.length==0||n==8&&t.insert.length<t.to-t.from&&t.to>r.head)&&IO(O.contentDOM,"Backspace",8)||t.from==r.from&&t.to==r.to+1&&t.insert.length==0&&IO(O.contentDOM,"Delete",46)))return!0;let s=t.insert.toString();O.inputState.composing>=0&&O.inputState.composing++;let a,o=()=>a||(a=Wg(O,t,i));return O.state.facet(tQ).some(l=>l(O,t.from,t.to,s,o))||O.dispatch(o()),!0}else if(i&&!i.main.eq(r)){let s=!1,a="select";return O.inputState.lastSelectionTime>Date.now()-50&&(O.inputState.lastSelectionOrigin=="select"&&(s=!0),a=O.inputState.lastSelectionOrigin),O.dispatch({selection:i,scrollIntoView:s,userEvent:a}),!0}else return!1}function Wg(O,e,t){let i,r=O.state,n=r.selection.main;if(e.from>=n.from&&e.to<=n.to&&e.to-e.from>=(n.to-n.from)/3&&(!t||t.main.empty&&t.main.from==e.from+e.insert.length)&&O.inputState.composing<0){let a=n.from<e.from?r.sliceDoc(n.from,e.from):"",o=n.to>e.to?r.sliceDoc(e.to,n.to):"";i=r.replaceSelection(O.state.toText(a+e.insert.sliceString(0,void 0,O.state.lineBreak)+o))}else{let a=r.changes(e),o=t&&t.main.to<=a.newLength?t.main:void 0;if(r.selection.ranges.length>1&&O.inputState.composing>=0&&e.to<=n.to&&e.to>=n.to-10){let l=O.state.sliceDoc(e.from,e.to),c,h=t&&hQ(O,t.main.head);if(h){let d=e.insert.length-(e.to-e.from);c={from:h.from,to:h.to-d}}else c=O.state.doc.lineAt(n.head);let $=n.to-e.to,f=n.to-n.from;i=r.changeByRange(d=>{if(d.from==n.from&&d.to==n.to)return{changes:a,range:o||d.map(a)};let u=d.to-$,p=u-l.length;if(d.to-d.from!=f||O.state.sliceDoc(p,u)!=l||d.to>=c.from&&d.from<=c.to)return{range:d};let m=r.changes({from:p,to:u,insert:e.insert}),g=d.to-n.to;return{changes:m,range:o?P.range(Math.max(0,o.anchor+g),Math.max(0,o.head+g)):d.map(m)}})}else i={changes:a,selection:o&&r.selection.replaceRange(o)}}let s="input.type";return(O.composing||O.inputState.compositionPendingChange&&O.inputState.compositionEndedAt>Date.now()-50)&&(O.inputState.compositionPendingChange=!1,s+=".compose",O.inputState.compositionFirstChange&&(s+=".start",O.inputState.compositionFirstChange=!1)),r.update(i,{userEvent:s,scrollIntoView:!0})}function Ug(O,e,t,i){let r=Math.min(O.length,e.length),n=0;for(;n<r&&O.charCodeAt(n)==e.charCodeAt(n);)n++;if(n==r&&O.length==e.length)return null;let s=O.length,a=e.length;for(;s>0&&a>0&&O.charCodeAt(s-1)==e.charCodeAt(a-1);)s--,a--;if(i=="end"){let o=Math.max(0,n-Math.min(s,a));t-=s+o-n}if(s<n&&O.length<e.length){let o=t<=n&&t>=s?n-t:0;n-=o,a=n+(a-s),s=n}else if(a<n){let o=t<=n&&t>=a?n-t:0;n-=o,s=n+(s-a),a=n}return{from:n,toA:s,toB:a}}function jg(O){let e=[];if(O.root.activeElement!=O.contentDOM)return e;let{anchorNode:t,anchorOffset:i,focusNode:r,focusOffset:n}=O.observer.selectionRange;return t&&(e.push(new sn(t,i)),(r!=t||n!=i)&&e.push(new sn(r,n))),e}function Gg(O,e){if(O.length==0)return null;let t=O[0].pos,i=O.length==2?O[1].pos:t;return t>-1&&i>-1?P.single(t+e,i+e):null}var Cg={childList:!0,characterData:!0,subtree:!0,attributes:!0,characterDataOldValue:!0},Gs=Y.ie&&Y.ie_version<=11,ma=class{constructor(e){this.view=e,this.active=!1,this.selectionRange=new Ls,this.selectionChanged=!1,this.delayedFlush=-1,this.resizeTimeout=-1,this.queue=[],this.delayedAndroidKey=null,this.flushingAndroidKey=-1,this.lastChange=0,this.scrollTargets=[],this.intersection=null,this.resizeScroll=null,this.intersecting=!1,this.gapIntersection=null,this.gaps=[],this.printQuery=null,this.parentCheck=-1,this.dom=e.contentDOM,this.observer=new MutationObserver(t=>{for(let i of t)this.queue.push(i);(Y.ie&&Y.ie_version<=11||Y.ios&&e.composing)&&t.some(i=>i.type=="childList"&&i.removedNodes.length||i.type=="characterData"&&i.oldValue.length>i.target.nodeValue.length)?this.flushSoon():this.flush()}),Gs&&(this.onCharData=t=>{this.queue.push({target:t.target,type:"characterData",oldValue:t.prevValue}),this.flushSoon()}),this.onSelectionChange=this.onSelectionChange.bind(this),this.onResize=this.onResize.bind(this),this.onPrint=this.onPrint.bind(this),this.onScroll=this.onScroll.bind(this),window.matchMedia&&(this.printQuery=window.matchMedia("print")),typeof ResizeObserver=="function"&&(this.resizeScroll=new ResizeObserver(()=>{var t;((t=this.view.docView)===null||t===void 0?void 0:t.lastUpdate)<Date.now()-75&&this.onResize()}),this.resizeScroll.observe(e.scrollDOM)),this.addWindowListeners(this.win=e.win),this.start(),typeof IntersectionObserver=="function"&&(this.intersection=new IntersectionObserver(t=>{this.parentCheck<0&&(this.parentCheck=setTimeout(this.listenForScroll.bind(this),1e3)),t.length>0&&t[t.length-1].intersectionRatio>0!=this.intersecting&&(this.intersecting=!this.intersecting,this.intersecting!=this.view.inView&&this.onScrollChang
Line truncated
|
||||
`:i=="r"?"\r":i=="t"?" ":"\\")}eq(e){return this.search==e.search&&this.replace==e.replace&&this.caseSensitive==e.caseSensitive&&this.regexp==e.regexp&&this.wholeWord==e.wholeWord}create(){return this.regexp?new qo(this):new Vo(this)}getCursor(e,t=0,i){let r=e.doc?e:K.create({doc:e});return i==null&&(i=r.doc.length),this.regexp?ii(this,r,t,i):Oi(this,r,t,i)}},Mn=class{constructor(e){this.spec=e}};function Oi(O,e,t,i){return new sO(e.doc,O.unquoted,t,i,O.caseSensitive?void 0:r=>r.toLowerCase(),O.wholeWord?w1(e.doc,e.charCategorizer(e.selection.main.head)):void 0)}function w1(O,e){return(t,i,r,n)=>((n>t||n+r.length<i)&&(n=Math.max(0,t-2),r=O.sliceString(n,Math.min(O.length,i+2))),(e(Dn(r,t-n))!=H.Word||e(In(r,t-n))!=H.Word)&&(e(In(r,i-n))!=H.Word||e(Dn(r,i-n))!=H.Word))}var Vo=class extends Mn{constructor(e){super(e)}nextMatch(e,t,i){let r=Oi(this.spec,e,i,e.doc.length).nextOverlapping();return r.done&&(r=Oi(this.spec,e,0,t).nextOverlapping()),r.done?null:r.value}prevMatchInRange(e,t,i){for(let r=i;;){let n=Math.max(t,r-1e4-this.spec.unquoted.length),s=Oi(this.spec,e,n,r),a=null;for(;!s.nextOverlapping().done;)a=s.value;if(a)return a;if(n==t)return null;r-=1e4}}prevMatch(e,t,i){return this.prevMatchInRange(e,0,t)||this.prevMatchInRange(e,i,e.doc.length)}getReplacement(e){return this.spec.unquote(this.spec.replace)}matchAll(e,t){let i=Oi(this.spec,e,0,e.doc.length),r=[];for(;!i.next().done;){if(r.length>=t)return null;r.push(i.value)}return r}highlight(e,t,i,r){let n=Oi(this.spec,e,Math.max(0,t-this.spec.unquoted.length),Math.min(i+this.spec.unquoted.length,e.doc.length));for(;!n.next().done;)r(n.value.from,n.value.to)}};function ii(O,e,t,i){return new jn(e.doc,O.search,{ignoreCase:!O.caseSensitive,test:O.wholeWord?b1(e.charCategorizer(e.selection.main.head)):void 0},t,i)}function Dn(O,e){return O.slice(Qe(O,e,!1),e)}function In(O,e){return O.slice(e,Qe(O,e))}function b1(O){return(e,t,i)=>!i[0].length||(O(Dn(i.input,i.index))!=H.Word||O(In(i.input,i.index))!=H.Word)&&(O(In(i.input,i.index+i[0].length))!=H.Word||O(Dn(i.input,i.index+i[0].length))!=H.Word)}var qo=class extends Mn{nextMatch(e,t,i){let r=ii(this.spec,e,i,e.doc.length).next();return r.done&&(r=ii(this.spec,e,0,t).next()),r.done?null:r.value}prevMatchInRange(e,t,i){for(let r=1;;r++){let n=Math.max(t,i-r*1e4),s=ii(this.spec,e,n,i),a=null;for(;!s.next().done;)a=s.value;if(a&&(n==t||a.from>n+10))return a;if(n==t)return null}}prevMatch(e,t,i){return this.prevMatchInRange(e,0,t)||this.prevMatchInRange(e,i,e.doc.length)}getReplacement(e){return this.spec.unquote(this.spec.replace).replace(/\$([$&\d+])/g,(t,i)=>i=="$"?"$":i=="&"?e.match[0]:i!="0"&&+i<e.match.length?e.match[i]:t)}matchAll(e,t){let i=ii(this.spec,e,0,e.doc.length),r=[];for(;!i.next().done;){if(r.length>=t)return null;r.push(i.value)}return r}highlight(e,t,i,r){let n=ii(this.spec,e,Math.max(0,t-250),Math.min(i+250,e.doc.length));for(;!n.next().done;)r(n.value.from,n.value.to)}},ar=j.define(),Go=j.define(),nO=$e.define({create(O){return new sr(Wo(O).create(),null)},update(O,e){for(let t of e.effects)t.is(ar)?O=new sr(t.value.create(),O.panel):t.is(Go)&&(O=new sr(O.query,t.value?Co:null));return O},provide:O=>Ci.from(O,e=>e.panel)});var sr=class{constructor(e,t){this.query=e,this.panel=t}},x1=R.mark({class:"cm-searchMatch"}),k1=R.mark({class:"cm-searchMatch cm-searchMatch-selected"}),v1=pe.fromClass(class{constructor(O){this.view=O,this.decorations=this.highlight(O.state.field(nO))}update(O){let e=O.state.field(nO);(e!=O.startState.field(nO)||O.docChanged||O.selectionSet||O.viewportChanged)&&(this.decorations=this.highlight(e))}highlight({query:O,panel:e}){if(!e||!O.spec.valid)return R.none;let{view:t}=this,i=new ft;for(let r=0,n=t.visibleRanges,s=n.length;r<s;r++){let{from:a,to:o}=n[r];for(;r<s-1&&o>n[r+1].from-2*250;)o=n[++r].to;O.highlight(t.state,a,o,(l,c)=>{let h=t.state.selection.ranges.some($=>$.from==l&&$.to==c);i.add(l,c,h?k1:x1)})}return i.finish()}},{decorations:O=>O.decorations});function or(O){return e=>{let t=e.state.field(nO,!1);return t&&t.query.spec.valid?O(e,t):vf(e)}}var Bn=or((O,{query:e})=>{let{to:t}=O.state.selection.main,i=e.nextMatch(O.state,t,t);if(!i)return!1;let r=P.single(i.from,i.to),n=O.state.facet(ri);return O.dispatch({selection:r,effects:[Eo(O,i),n.scrollToMatch(r.main,O)],userEvent:"select.search"}),kf(O),!0}),Nn=or((O,{query:e})=>{let{state:t}=O,{from:i}=t.selection.main,r=e.prevMatch(t,i,i);if(!r)return!1;let n=P.single(r.from,r.to),s=O.state.facet(ri);return O.dispatch({selection:n,effects:[Eo(O,r),s.scrollToMatch(n.main,O)],userEvent:"select.search"}),kf(O),!0}),Y1=or((O,{query:e})=>{let t=e.matchAll(O.state,1e3);return!t||!t.length?!1:(O.dispatch({selection:P.create(t.map(i=>P.range(i.from,i.to))),userEvent:"select.search.matches"}),!0)}),Z1=({state:O,dispatch:e})=>{let t=O.selection;if(t.ranges.length>1||t.main.empty)return!1;let{from:i,to:r}=t.main,n=[],s=0;for(let a=new sO(O.doc,O.sliceDoc(i,r));!a.next().done;){if(n.length>1e3)return!1;a.value.from==i
Line truncated
|
||||
\${}
|
||||
} catch (\${error}) {
|
||||
\${}
|
||||
}`,{label:"try",detail:"/ catch block",type:"keyword"}),W("if (${}) {\n ${}\n}",{label:"if",detail:"block",type:"keyword"}),W(`if (\${}) {
|
||||
\${}
|
||||
} else {
|
||||
\${}
|
||||
}`,{label:"if",detail:"/ else block",type:"keyword"}),W(`class \${name} {
|
||||
constructor(\${params}) {
|
||||
\${}
|
||||
}
|
||||
}`,{label:"class",detail:"definition",type:"keyword"}),W('import {${names}} from "${module}"\n${}',{label:"import",detail:"named",type:"keyword"}),W('import ${name} from "${module}"\n${}',{label:"import",detail:"default",type:"keyword"})],bT=Bf.concat([W("interface ${name} {\n ${}\n}",{label:"interface",detail:"definition",type:"keyword"}),W("type ${name} = ${type}",{label:"type",detail:"definition",type:"keyword"}),W("enum ${name} {\n ${}\n}",{label:"enum",detail:"definition",type:"keyword"})]),Mf=new Pt,Nf=new Set(["Script","Block","FunctionExpression","FunctionDeclaration","ArrowFunction","MethodDeclaration","ForStatement"]);function cr(O){return(e,t)=>{let i=e.node.getChild("VariableDefinition");return i&&t(i,O),!0}}var xT=["FunctionDeclaration"],kT={FunctionDeclaration:cr("function"),ClassDeclaration:cr("class"),ClassExpression:()=>!0,EnumDeclaration:cr("constant"),TypeAliasDeclaration:cr("type"),NamespaceDeclaration:cr("namespace"),VariableDefinition(O,e){O.matchContext(xT)||e(O,"variable")},TypeDefinition(O,e){e(O,"type")},__proto__:null};function Ff(O,e){let t=Mf.get(e);if(t)return t;let i=[],r=!0;function n(s,a){let o=O.sliceString(s.from,s.to);i.push({label:o,type:a})}return e.cursor(C.IncludeAnonymous).iterate(s=>{if(r)r=!1;else if(s.name){let a=kT[s.name];if(a&&a(s,n)||Nf.has(s.name))return!1}else if(s.to-s.from>8192){for(let a of Ff(O,s.node))i.push(a);return!1}}),Mf.set(e,i),i}var Df=/^[\w$\xa1-\uffff][\w$\d\xa1-\uffff]*$/,Hf=["TemplateString","String","RegExp","LineComment","BlockComment","VariableDefinition","TypeDefinition","Label","PropertyDefinition","PropertyName","PrivatePropertyDefinition","PrivatePropertyName",".","?."];function vT(O){let e=q(O.state).resolveInner(O.pos,-1);if(Hf.indexOf(e.name)>-1)return null;let t=e.name=="VariableName"||e.to-e.from<20&&Df.test(O.state.sliceDoc(e.from,e.to));if(!t&&!O.explicit)return null;let i=[];for(let r=e;r;r=r.parent)Nf.has(r.name)&&(i=i.concat(Ff(O.state.doc,r)));return{options:i,from:t?e.from:O.pos,validFor:Df}}var ht=re.define({name:"javascript",parser:Lf.configure({props:[ne.add({IfStatement:oe({except:/^\s*({|else\b)/}),TryStatement:oe({except:/^\s*({|catch\b|finally\b)/}),LabeledStatement:KO,SwitchBody:O=>{let e=O.textAfter,t=/^\s*\}/.test(e),i=/^\s*(case|default)\b/.test(e);return O.baseIndent+(t?0:i?1:2)*O.unit},Block:_e({closing:"}"}),ArrowFunction:O=>O.baseIndent+O.unit,"TemplateString BlockComment":()=>null,"Statement Property":oe({except:/^{/}),JSXElement(O){let e=/^\s*<\//.test(O.textAfter);return O.lineIndent(O.node.from)+(e?0:O.unit)},JSXEscape(O){let e=/\s*\}/.test(O.textAfter);return O.lineIndent(O.node.from)+(e?0:O.unit)},"JSXOpenTag JSXSelfClosingTag"(O){return O.column(O.node.from)+O.unit}}),J.add({"Block ClassBody SwitchBody EnumBody ObjectExpression ArrayExpression ObjectType":me,BlockComment(O){return{from:O.from+2,to:O.to-2}}})]}),languageData:{closeBrackets:{brackets:["(","[","{","'",'"',"`"]},commentTokens:{line:"//",block:{open:"/*",close:"*/"}},indentOnInput:/^\s*(?:case |default:|\{|\}|<\/)$/,wordChars:"$"}}),Kf={test:O=>/^JSX/.test(O.name),facet:Fi({commentTokens:{block:{open:"{/*",close:"*/}"}}})},rl=ht.configure({dialect:"ts"},"typescript"),nl=ht.configure({dialect:"jsx",props:[Tn.add(O=>O.isTop?[Kf]:void 0)]}),sl=ht.configure({dialect:"jsx ts",props:[Tn.add(O=>O.isTop?[Kf]:void 0)]},"typescript"),Jf=O=>({label:O,type:"keyword"}),ed="break case const continue default delete export extends false finally in instanceof let new return static super switch this throw true typeof var yield".split(" ").map(Jf),YT=ed.concat(["declare","implements","private","protected","public"].map(Jf));function hr(O={}){let e=O.jsx?O.typescript?sl:nl:O.typescript?rl:ht,t=O.typescript?bT.concat(YT):Bf.concat(ed);return new F(e,[ht.data.of({autocomplete:rO(Hf,Rt(t))}),ht.data.of({autocomplete:vT}),O.jsx?RT:[]])}function ZT(O){for(;;){if(O.name=="JSXOpenTag"||O.name=="JSXSelfClosingTag"||O.name=="JSXFragmentTag")return O;if(O.name=="JSXEscape"||!O.parent)return null;O=O.parent}}function If(O,e,t=O.length){for(let i=e?.firstChild;i;i=i.nextSibling)if(i.name=="JSXIdentifier"||i.name=="JSXBuiltin"||i.name=="JSXNamespacedName"||i.name=="JSXMemberExpression")return O.sliceString(i.from,Math.min(i.to,t));return""}var _T=typeof navigator=="object"&&/Android\b/.test(navigator.userAgent),RT=x.inputHandler.of((O,e,t,i,r)=>{if((_T?O.composing:O.compositionStarted)||O.state.readOnly||e!=t||i!=">"&&i!="/"||!ht.isActiveAt(O.state,e,-1))return!1;let n=r(),{state:s}=n,a=s.changeByRange(o=>{var l;let{head:c}=o,h=q(s).resolveInner(c-1,-1),$;if(h.name=="JSXStartTag"&&(h=h.parent),!(s.doc.sliceString(c-1,c)!=i||h.name=="JSXAttributeValue"&&h.to>c)){if(i==">"&&h.name=="JSXFragmentTag")return{range:o,changes:{from:c,insert:"</>"}};if(i=="/"&&h.name=="JSXStartCloseTag"){let f=h.parent,d=f.parent;if(d&&f.from==c-2&&(($=If(s.doc,d.firstChild,c))||((l=d.firstChild)===null||l===void 0?void 0:l.name)=="JSXFragmentTag")){let u=`${$}>`;return{range:P.cursor(c+u.length
Line truncated
|
||||
|
||||
`,{label:"if",detail:"block",type:"keyword"}),W("if ${}:\n ${}\nelse:\n ${}",{label:"if",detail:"/ else block",type:"keyword"}),W("class ${name}:\n def __init__(self, ${params}):\n ${}",{label:"class",detail:"definition",type:"keyword"}),W("import ${module}",{label:"import",detail:"statement",type:"keyword"}),W("from ${module} import ${names}",{label:"from",detail:"import",type:"keyword"})],Iy=rO(Pd,Rt(My.concat(Dy)));function ud(O){let{node:e,pos:t}=O,i=O.lineIndent(t,-1),r=null;for(;;){let n=e.childBefore(t);if(n)if(n.name=="Comment")t=n.from;else if(n.name=="Body")O.baseIndentFor(n)+O.unit<=i&&(r=n),e=n;else if(n.type.is("Statement"))e=n;else break;else break}return r}function pd(O,e){let t=O.baseIndentFor(e),i=O.lineAt(O.pos,-1),r=i.from+i.text.length;return/^\s*($|#)/.test(i.text)&&O.node.to<r+100&&!/\S/.test(O.state.sliceDoc(r,O.node.to))&&O.lineIndent(O.pos,-1)<=t||/^\s*(else:|elif |except |finally:)/.test(O.textAfter)&&O.lineIndent(O.pos,-1)>t?null:t+O.unit}var Ql=re.define({name:"python",parser:$d.configure({props:[ne.add({Body:O=>{var e;let t=ud(O);return(e=pd(O,t||O.node))!==null&&e!==void 0?e:O.continue()},IfStatement:O=>/^\s*(else:|elif )/.test(O.textAfter)?O.baseIndent:O.continue(),"ForStatement WhileStatement":O=>/^\s*else:/.test(O.textAfter)?O.baseIndent:O.continue(),TryStatement:O=>/^\s*(except |finally:|else:)/.test(O.textAfter)?O.baseIndent:O.continue(),"TupleExpression ComprehensionExpression ParamList ArgList ParenthesizedExpression":_e({closing:")"}),"DictionaryExpression DictionaryComprehensionExpression SetExpression SetComprehensionExpression":_e({closing:"}"}),"ArrayExpression ArrayComprehensionExpression":_e({closing:"]"}),"String FormatString":()=>null,Script:O=>{var e;let t=ud(O);return(e=t&&pd(O,t))!==null&&e!==void 0?e:O.continue()}}),J.add({"ArrayExpression DictionaryExpression SetExpression TupleExpression":me,Body:(O,e)=>({from:O.from+1,to:O.to-(O.to==e.doc.length?0:1)})})]}),languageData:{closeBrackets:{brackets:["(","[","{","'",'"',"'''",'"""'],stringPrefixes:["f","fr","rf","r","u","b","br","rb","F","FR","RF","R","U","B","BR","RB"]},commentTokens:{line:"#"},indentOnInput:/^\s*([\}\]\)]|else:|elif |except |finally:)$/}});function Sd(){return new F(Ql,[Ql.data.of({autocomplete:Ly}),Ql.data.of({autocomplete:Iy})])}var rs=class O{static create(e,t,i,r,n){let s=r+(r<<8)+e+(t<<4)|0;return new O(e,t,i,s,n,[],[])}constructor(e,t,i,r,n,s,a){this.type=e,this.value=t,this.from=i,this.hash=r,this.end=n,this.children=s,this.positions=a,this.hashProp=[[_.contextHash,r]]}addChild(e,t){e.prop(_.contextHash)!=this.hash&&(e=new M(e.type,e.children,e.positions,e.length,this.hashProp)),this.children.push(e),this.positions.push(t)}toTree(e,t=this.end){let i=this.children.length-1;return i>=0&&(t=Math.max(t,this.positions[i]+this.children[i].length+this.from)),new M(e.types[this.type],this.children,this.positions,t-this.from).balance({makeTree:(r,n,s)=>new M(ce.none,r,n,s,this.hashProp)})}},y;(function(O){O[O.Document=1]="Document",O[O.CodeBlock=2]="CodeBlock",O[O.FencedCode=3]="FencedCode",O[O.Blockquote=4]="Blockquote",O[O.HorizontalRule=5]="HorizontalRule",O[O.BulletList=6]="BulletList",O[O.OrderedList=7]="OrderedList",O[O.ListItem=8]="ListItem",O[O.ATXHeading1=9]="ATXHeading1",O[O.ATXHeading2=10]="ATXHeading2",O[O.ATXHeading3=11]="ATXHeading3",O[O.ATXHeading4=12]="ATXHeading4",O[O.ATXHeading5=13]="ATXHeading5",O[O.ATXHeading6=14]="ATXHeading6",O[O.SetextHeading1=15]="SetextHeading1",O[O.SetextHeading2=16]="SetextHeading2",O[O.HTMLBlock=17]="HTMLBlock",O[O.LinkReference=18]="LinkReference",O[O.Paragraph=19]="Paragraph",O[O.CommentBlock=20]="CommentBlock",O[O.ProcessingInstructionBlock=21]="ProcessingInstructionBlock",O[O.Escape=22]="Escape",O[O.Entity=23]="Entity",O[O.HardBreak=24]="HardBreak",O[O.Emphasis=25]="Emphasis",O[O.StrongEmphasis=26]="StrongEmphasis",O[O.Link=27]="Link",O[O.Image=28]="Image",O[O.InlineCode=29]="InlineCode",O[O.HTMLTag=30]="HTMLTag",O[O.Comment=31]="Comment",O[O.ProcessingInstruction=32]="ProcessingInstruction",O[O.Autolink=33]="Autolink",O[O.HeaderMark=34]="HeaderMark",O[O.QuoteMark=35]="QuoteMark",O[O.ListMark=36]="ListMark",O[O.LinkMark=37]="LinkMark",O[O.EmphasisMark=38]="EmphasisMark",O[O.CodeMark=39]="CodeMark",O[O.CodeText=40]="CodeText",O[O.CodeInfo=41]="CodeInfo",O[O.LinkTitle=42]="LinkTitle",O[O.LinkLabel=43]="LinkLabel",O[O.URL=44]="URL"})(y||(y={}));var dl=class{constructor(e,t){this.start=e,this.content=t,this.marks=[],this.parsers=[]}},ul=class{constructor(){this.text="",this.baseIndent=0,this.basePos=0,this.depth=0,this.markers=[],this.pos=0,this.indent=0,this.next=-1}forward(){this.basePos>this.pos&&this.forwardInner()}forwardInner(){let e=this.skipSpace(this.basePos);this.indent=this.countIndent(e,this.pos,this.indent),this.pos=e,this.next=e==this.text.length?-1:this.text.charCodeAt(e)}skipSpace(e){return fr(this.text,e)}reset(e){for(this.text=e,this.baseIndent=this.basePos=this.pos=this.indent=0,this.forwardInner(),this.depth=1;this.markers.len
Line truncated
|
||||
`+t.scrub(),n=this.advance(r);return n>-1&&n<r.length?this.complete(e,i,n):!1}finish(e,t){return(this.stage==2||this.stage==3)&&fr(t.content,this.pos)==t.content.length?this.complete(e,t,t.content.length):!1}complete(e,t,i){return e.addLeafElement(t,L(y.LinkReference,this.start,this.start+i,this.elts)),!0}nextStage(e){return e?(this.pos=e.to-this.start,this.elts.push(e),this.stage++,!0):(e===!1&&(this.stage=-1),!1)}advance(e){for(;;){if(this.stage==-1)return-1;if(this.stage==0){if(!this.nextStage(Nd(e,this.pos,this.start,!0)))return-1;if(e.charCodeAt(this.pos)!=58)return this.stage=-1;this.elts.push(L(y.LinkMark,this.pos+this.start,this.pos+this.start+1)),this.pos++}else if(this.stage==1){if(!this.nextStage(Id(e,fr(e,this.pos),this.start)))return-1}else if(this.stage==2){let t=fr(e,this.pos),i=0;if(t>this.pos){let r=Bd(e,t,this.start);if(r){let n=$l(e,r.to-this.start);n>0&&(this.nextStage(r),i=n)}}return i||(i=$l(e,this.pos)),i>0&&i<e.length?i:-1}else return $l(e,this.pos)}}};function $l(O,e){for(;e<O.length;e++){let t=O.charCodeAt(e);if(t==10)break;if(!rt(t))return-1}return e}var Pl=class{nextLine(e,t,i){let r=t.depth<e.stack.length?-1:Ud(t),n=t.next;if(r<0)return!1;let s=L(y.HeaderMark,e.lineStart+t.pos,e.lineStart+r);return e.nextLine(),e.addLeafElement(i,L(n==61?y.SetextHeading1:y.SetextHeading2,i.start,e.prevLineEnd(),[...e.parser.parseInline(i.content,i.start),s])),!0}finish(){return!1}},Ed={LinkReference(O,e){return e.content.charCodeAt(0)==91?new gl(e):null},SetextHeading(){return new Pl}},By=[(O,e)=>Wd(e)>=0,(O,e)=>zd(e)>=0,(O,e)=>Vd(e)>=0,(O,e)=>xl(e,O,!0)>=0,(O,e)=>kl(e,O,!0)>=0,(O,e)=>bl(e,O,!0)>=0,(O,e)=>Cd(e,O,!0)>=0],Ny={text:"",end:0},Sl=class{constructor(e,t,i,r){this.parser=e,this.input=t,this.ranges=r,this.line=new ul,this.atEnd=!1,this.reusePlaceholders=new Map,this.stoppedAt=null,this.rangeI=0,this.to=r[r.length-1].to,this.lineStart=this.absoluteLineStart=this.absoluteLineEnd=r[0].from,this.block=rs.create(y.Document,0,this.lineStart,0,0),this.stack=[this.block],this.fragments=i.length?new yl(i,t):null,this.readLine()}get parsedPos(){return this.absoluteLineStart}advance(){if(this.stoppedAt!=null&&this.absoluteLineStart>this.stoppedAt)return this.finish();let{line:e}=this;for(;;){for(let i=0;;){let r=e.depth<this.stack.length?this.stack[this.stack.length-1]:null;for(;i<e.markers.length&&(!r||e.markers[i].from<r.end);){let n=e.markers[i++];this.addNode(n.type,n.from,n.to)}if(!r)break;this.finishContext()}if(e.pos<e.text.length)break;if(!this.nextLine())return this.finish()}if(this.fragments&&this.reuseFragment(e.basePos))return null;e:for(;;){for(let i of this.parser.blockParsers)if(i){let r=i(this,e);if(r!=!1){if(r==!0)return null;e.forward();continue e}}break}let t=new dl(this.lineStart+e.pos,e.text.slice(e.pos));for(let i of this.parser.leafBlockParsers)if(i){let r=i(this,t);r&&t.parsers.push(r)}e:for(;this.nextLine()&&e.pos!=e.text.length;){if(e.indent<e.baseIndent+4){for(let i of this.parser.endLeafBlock)if(i(this,e,t))break e}for(let i of t.parsers)if(i.nextLine(this,e,t))return null;t.content+=`
|
||||
`+e.scrub();for(let i of e.markers)t.marks.push(i)}return this.finishLeaf(t),null}stopAt(e){if(this.stoppedAt!=null&&this.stoppedAt<e)throw new RangeError("Can't move stoppedAt forward");this.stoppedAt=e}reuseFragment(e){if(!this.fragments.moveTo(this.absoluteLineStart+e,this.absoluteLineStart)||!this.fragments.matches(this.block.hash))return!1;let t=this.fragments.takeNodes(this);return t?(this.absoluteLineStart+=t,this.lineStart=Fd(this.absoluteLineStart,this.ranges),this.moveRangeI(),this.absoluteLineStart<this.to?(this.lineStart++,this.absoluteLineStart++,this.readLine()):(this.atEnd=!0,this.readLine()),!0):!1}get depth(){return this.stack.length}parentType(e=this.depth-1){return this.parser.nodeSet.types[this.stack[e].type]}nextLine(){return this.lineStart+=this.line.text.length,this.absoluteLineEnd>=this.to?(this.absoluteLineStart=this.absoluteLineEnd,this.atEnd=!0,this.readLine(),!1):(this.lineStart++,this.absoluteLineStart=this.absoluteLineEnd+1,this.moveRangeI(),this.readLine(),!0)}peekLine(){return this.scanLine(this.absoluteLineEnd+1).text}moveRangeI(){for(;this.rangeI<this.ranges.length-1&&this.absoluteLineStart>=this.ranges[this.rangeI].to;)this.rangeI++,this.absoluteLineStart=Math.max(this.absoluteLineStart,this.ranges[this.rangeI].from)}scanLine(e){let t=Ny;if(t.end=e,e>=this.to)t.text="";else if(t.text=this.lineChunkAt(e),t.end+=t.text.length,this.ranges.length>1){let i=this.absoluteLineStart,r=this.rangeI;for(;this.ranges[r].to<t.end;){r++;let n=this.ranges[r].from,s=this.lineChunkAt(n);t.end=n+s.length,t.text=t.text.slice(0,this.ranges[r-1].to-i)+s,i=t.end-t.text.length}}return t}readLine(){let{line:e}=this,{text:t,end:i}=this.scanLine(this.absoluteLineStart);for(this.absoluteLineEnd=i,e.reset(t);e.depth<this.stack.length;e.depth++){let r=this.stack[e.depth],n=this.parser.skipContextMarkup[r.type];if(!n)throw new Error("Unhandled block context "+y[r.type]);let s=this.line.markers.length;if(!n(r,this,e)){this.line.markers.length>s&&(r.end=this.line.markers[this.line.markers.length-1].to),e.forward();break}e.forward()}}lineChunkAt(e){let t=this.input.chunk(e),i;if(this.input.lineChunks)i=t==`
|
||||
`?"":t;else{let r=t.indexOf(`
|
||||
`);i=r<0?t:t.slice(0,r)}return e+i.length>this.to?i.slice(0,this.to-e):i}prevLineEnd(){return this.atEnd?this.lineStart:this.lineStart-1}startContext(e,t,i=0){this.block=rs.create(e,i,this.lineStart+t,this.block.hash,this.lineStart+this.line.text.length),this.stack.push(this.block)}startComposite(e,t,i=0){this.startContext(this.parser.getNodeType(e),t,i)}addNode(e,t,i){typeof e=="number"&&(e=new M(this.parser.nodeSet.types[e],si,si,(i??this.prevLineEnd())-t)),this.block.addChild(e,t-this.block.from)}addElement(e){this.block.addChild(e.toTree(this.parser.nodeSet),e.from-this.block.from)}addLeafElement(e,t){this.addNode(this.buffer.writeElements(Tl(t.children,e.marks),-t.from).finish(t.type,t.to-t.from),t.from)}finishContext(){let e=this.stack.pop(),t=this.stack[this.stack.length-1];t.addChild(e.toTree(this.parser.nodeSet),e.from-t.from),this.block=t}finish(){for(;this.stack.length>1;)this.finishContext();return this.addGaps(this.block.toTree(this.parser.nodeSet,this.lineStart))}addGaps(e){return this.ranges.length>1?Ad(this.ranges,0,e.topNode,this.ranges[0].from,this.reusePlaceholders):e}finishLeaf(e){for(let i of e.parsers)if(i.finish(this,e))return;let t=Tl(this.parser.parseInline(e.content,e.start),e.marks);this.addNode(this.buffer.writeElements(t,-e.start).finish(y.Paragraph,e.content.length),e.start)}elt(e,t,i,r){return typeof e=="string"?L(this.parser.getNodeType(e),t,i,r):new ss(e,t)}get buffer(){return new ns(this.parser.nodeSet)}};function Ad(O,e,t,i,r){let n=O[e].to,s=[],a=[],o=t.from+i;function l(c,h){for(;h?c>=n:c>n;){let $=O[e+1].from-n;i+=$,c+=$,e++,n=O[e].to}}for(let c=t.firstChild;c;c=c.nextSibling){l(c.from+i,!0);let h=c.from+i,$,f=r.get(c.tree);f?$=f:c.to+i>n?($=Ad(O,e,c,i,r),l(c.to+i,!1)):$=c.toTree(),s.push($),a.push(h-o)}return l(t.to+i,!1),new M(t.type,s,a,t.to+i-o,t.tree?t.tree.propValues:void 0)}var ur=class O extends Ft{constructor(e,t,i,r,n,s,a,o,l){super(),this.nodeSet=e,this.blockParsers=t,this.leafBlockParsers=i,this.blockNames=r,this.endLeafBlock=n,this.skipContextMarkup=s,this.inlineParsers=a,this.inlineNames=o,this.wrappers=l,this.nodeTypes=Object.create(null);for(let c of e.types)this.nodeTypes[c.name]=c.id}createParse(e,t,i){let r=new Sl(this,e,t,i);for(let n of this.wrappers)r=n(r,e,t,i);return r}configure(e){let t=Xl(e);if(!t)return this;let{nodeSet:i,skipContextMarkup:r}=this,n=this.blockParsers.slice(),s=this.leafBlockParsers.slice(),a=this.blockNames.slice(),o=this.inlineParsers.slice(),l=this.inlineNames.slice(),c=this.endLeafBlock.slice(),h=this.wrappers;if($r(t.defineNodes)){r=Object.assign({},r);let $=i.types.slice(),f;for(let d of t.defineNodes){let{name:u,block:p,composite:m,style:g}=typeof d=="string"?{name:d}:d;if($.some(S=>S.name==u))continue;m&&(r[$.length]=(S,k,b)=>m(k,b,S.value));let X=$.length,T=m?["Block","BlockContext"]:p?X>=y.ATXHeading1&&X<=y.SetextHeading2?["Block","LeafBlock","Heading"]:["Block","LeafBlock"]:void 0;$.push(ce.define({id:X,name:u,props:T&&[[_.group,T]]})),g&&(f||(f={}),Array.isArray(g)||g instanceof De?f[u]=g:Object.assign(f,g))}i=new Bt($),f&&(i=i.extend(I(f)))}if($r(t.props)&&(i=i.extend(...t.props)),$r(t.remove))for(let $ of t.remove){let f=this.blockNames.indexOf($),d=this.inlineNames.indexOf($);f>-1&&(n[f]=s[f]=void 0),d>-1&&(o[d]=void 0)}if($r(t.parseBlock))for(let $ of t.parseBlock){let f=a.indexOf($.name);if(f>-1)n[f]=$.parse,s[f]=$.leaf;else{let d=$.before?is(a,$.before):$.after?is(a,$.after)+1:a.length-1;n.splice(d,0,$.parse),s.splice(d,0,$.leaf),a.splice(d,0,$.name)}$.endLeaf&&c.push($.endLeaf)}if($r(t.parseInline))for(let $ of t.parseInline){let f=l.indexOf($.name);if(f>-1)o[f]=$.parse;else{let d=$.before?is(l,$.before):$.after?is(l,$.after)+1:l.length-1;o.splice(d,0,$.parse),l.splice(d,0,$.name)}}return t.wrap&&(h=h.concat(t.wrap)),new O(i,n,s,a,c,r,o,l,h)}getNodeType(e){let t=this.nodeTypes[e];if(t==null)throw new RangeError(`Unknown node type '${e}'`);return t}parseInline(e,t){let i=new mr(this,e,t);e:for(let r=t;r<i.end;){let n=i.char(r);for(let s of this.inlineParsers)if(s){let a=s(i,n,r);if(a>=0){r=a;continue e}}r++}return i.resolveMarkers(0)}};function $r(O){return O!=null&&O.length>0}function Xl(O){if(!Array.isArray(O))return O;if(O.length==0)return null;let e=Xl(O[0]);if(O.length==1)return e;let t=Xl(O.slice(1));if(!t||!e)return e||t;let i=(s,a)=>(s||si).concat(a||si),r=e.wrap,n=t.wrap;return{props:i(e.props,t.props),defineNodes:i(e.defineNodes,t.defineNodes),parseBlock:i(e.parseBlock,t.parseBlock),parseInline:i(e.parseInline,t.parseInline),remove:i(e.remove,t.remove),wrap:r?n?(s,a,o,l)=>r(n(s,a,o,l),a,o,l):r:n}}function is(O,e){let t=O.indexOf(e);if(t<0)throw new RangeError(`Position specified relative to unknown parser ${e}`);return t}var Ld=[ce.none];for(let O=1,e;e=y[O];O++)Ld[O]=ce.define({id:O,name:e,props:O>=y.Escape?[]:[[_.group,O in Rd?["Block","BlockContext"]:["Block","LeafBlock"]]],top:e=="Document"});var si=[],ns=class{constructor(e){this.nodeSet=e,this.content=[],this.nodes=[]}write(e,t,i,r=0){return t
Line truncated
|
||||
`;)n--;this.fragmentEnd=n?n-1:0}let i=this.cursor;i||(i=this.cursor=this.fragment.tree.cursor(),i.firstChild());let r=e+this.fragment.offset;for(;i.to<=r;)if(!i.parent())return!1;for(;;){if(i.from>=r)return this.fragment.from<=t;if(!i.childAfter(r))return!1}}matches(e){let t=this.cursor.tree;return t&&t.prop(_.contextHash)==e}takeNodes(e){let t=this.cursor,i=this.fragment.offset,r=this.fragmentEnd-(this.fragment.openEnd?1:0),n=e.absoluteLineStart,s=n,a=e.block.children.length,o=s,l=a;for(;;){if(t.to-i>r){if(t.type.isAnonymous&&t.firstChild())continue;break}let c=Fd(t.from-i,e.ranges);if(t.to-i<=e.ranges[e.rangeI].to)e.addNode(t.tree,c);else{let h=new M(e.parser.nodeSet.types[y.Paragraph],[],[],0,e.block.hashProp);e.reusePlaceholders.set(h,t.tree),e.addNode(h,c)}if(t.type.is("Block")&&(Hy.indexOf(t.type.id)<0?(s=t.to-i,a=e.block.children.length):(s=o,a=l),o=t.to-i,l=e.block.children.length),!t.nextSibling())break}for(;e.block.children.length>a;)e.block.children.pop(),e.block.positions.pop();return s-n}};function Fd(O,e){let t=O;for(let i=1;i<e.length;i++){let r=e[i-1].to,n=e[i].from;r<O&&(t-=n-r)}return t}var Ky=I({"Blockquote/...":Q.quote,HorizontalRule:Q.contentSeparator,"ATXHeading1/... SetextHeading1/...":Q.heading1,"ATXHeading2/... SetextHeading2/...":Q.heading2,"ATXHeading3/...":Q.heading3,"ATXHeading4/...":Q.heading4,"ATXHeading5/...":Q.heading5,"ATXHeading6/...":Q.heading6,"Comment CommentBlock":Q.comment,Escape:Q.escape,Entity:Q.character,"Emphasis/...":Q.emphasis,"StrongEmphasis/...":Q.strong,"Link/... Image/...":Q.link,"OrderedList/... BulletList/...":Q.list,"BlockQuote/...":Q.quote,"InlineCode CodeText":Q.monospace,"URL Autolink":Q.url,"HeaderMark HardBreak QuoteMark ListMark LinkMark EmphasisMark CodeMark":Q.processingInstruction,"CodeInfo LinkLabel":Q.labelName,LinkTitle:Q.string,Paragraph:Q.content}),Hd=new ur(new Bt(Ld).extend(Ky),Object.keys(Os).map(O=>Os[O]),Object.keys(Os).map(O=>Ed[O]),Object.keys(Os),By,Rd,Object.keys(fl).map(O=>fl[O]),Object.keys(fl),[]);function Jy(O,e,t){let i=[];for(let r=O.firstChild,n=e;;r=r.nextSibling){let s=r?r.from:t;if(s>n&&i.push({from:n,to:s}),!r)break;n=r.to}return i}function Kd(O){let{codeParser:e,htmlParser:t}=O;return{wrap:gO((r,n)=>{let s=r.type.id;if(e&&(s==y.CodeBlock||s==y.FencedCode)){let a="";if(s==y.FencedCode){let l=r.node.getChild(y.CodeInfo);l&&(a=n.read(l.from,l.to))}let o=e(a);if(o)return{parser:o,overlay:l=>l.type.id==y.CodeText,bracketed:s==y.FencedCode}}else if(t&&(s==y.HTMLBlock||s==y.HTMLTag||s==y.CommentBlock))return{parser:t,overlay:Jy(r.node,r.from,r.to)};return null})}}var ew={resolve:"Strikethrough",mark:"StrikethroughMark"},tw={defineNodes:[{name:"Strikethrough",style:{"Strikethrough/...":Q.strikethrough}},{name:"StrikethroughMark",style:Q.processingInstruction}],parseInline:[{name:"Strikethrough",parse(O,e,t){if(e!=126||O.char(t+1)!=126||O.char(t+2)==126)return-1;let i=O.slice(t-1,t),r=O.slice(t+2,t+3),n=/\s|^$/.test(i),s=/\s|^$/.test(r),a=pr.test(i),o=pr.test(r);return O.addDelimiter(ew,t,t+2,!s&&(!o||n||a),!n&&(!a||s||o))},after:"Emphasis"}]};function dr(O,e,t=0,i,r=0){let n=0,s=!0,a=-1,o=-1,l=!1,c=()=>{i.push(O.elt("TableCell",r+a,r+o,O.parser.parseInline(e.slice(a,o),r+a)))};for(let h=t;h<e.length;h++){let $=e.charCodeAt(h);$==124&&!l?((!s||a>-1)&&n++,s=!1,i&&(a>-1&&c(),i.push(O.elt("TableDelimiter",h+r,h+r+1))),a=o=-1):(l||$!=32&&$!=9)&&(a<0&&(a=h),o=h+1),l=!l&&$==92}return a>-1&&(n++,i&&c()),n}function bd(O,e){for(let t=e;t<O.length;t++){let i=O.charCodeAt(t);if(i==124)return!0;i==92&&t++}return!1}var Jd=/^\|?(\s*:?-+:?\s*\|)+(\s*:?-+:?\s*)?$/,os=class{constructor(){this.rows=null}nextLine(e,t,i){if(this.rows==null){this.rows=!1;let r;if((t.next==45||t.next==58||t.next==124)&&Jd.test(r=t.text.slice(t.pos))){let n=[];dr(e,i.content,0,n,i.start)==dr(e,r,t.pos)&&(this.rows=[e.elt("TableHeader",i.start,i.start+i.content.length,n),e.elt("TableDelimiter",e.lineStart+t.pos,e.lineStart+t.text.length)])}}else if(this.rows){let r=[];dr(e,t.text,t.pos,r,e.lineStart),this.rows.push(e.elt("TableRow",e.lineStart+t.pos,e.lineStart+t.text.length,r))}return!1}finish(e,t){return this.rows?(e.addLeafElement(t,e.elt("Table",t.start,t.start+t.content.length,this.rows)),!0):!1}},Ow={defineNodes:[{name:"Table",block:!0},{name:"TableHeader",style:{"TableHeader/...":Q.heading}},"TableRow",{name:"TableCell",style:Q.content},{name:"TableDelimiter",style:Q.processingInstruction}],parseBlock:[{name:"Table",leaf(O,e){return bd(e.content,0)?new os:null},endLeaf(O,e,t){if(t.parsers.some(r=>r instanceof os)||!bd(e.text,e.basePos))return!1;let i=O.peekLine();return Jd.test(i)&&dr(O,e.text,e.basePos)==dr(O,i,e.basePos)},before:"SetextHeading"}]},wl=class{nextLine(){return!1}finish(e,t){return e.addLeafElement(t,e.elt("Task",t.start,t.start+t.content.length,[e.elt("TaskMarker",t.start,t.start+3),...e.parser.parseInline(t.content.slice(3),t.start+3)])),!0}},iw={defineNodes:[{name:"Task",block:!0,style:Q.list},{name:"TaskMarker",style:Q.atom}],parseBlock:[{name
Line truncated
|
||||
\${}
|
||||
}`,{label:"select",detail:"statement",type:"keyword"}),W("case ${}:\n${}",{label:"case",type:"keyword"}),W("switch ${} {\n ${}\n}",{label:"switch",detail:"statement",type:"keyword"}),W("switch ${}.(${type}) {\n ${}\n}",{label:"switch",detail:"type statement",type:"keyword"}),W("if ${} {\n ${}\n}",{label:"if",detail:"block",type:"keyword"}),W(`if \${} {
|
||||
\${}
|
||||
} else {
|
||||
\${}
|
||||
}`,{label:"if",detail:"/ else block",type:"keyword"}),W('import ${name} "${module}"\n${}',{label:"import",detail:"declaration",type:"keyword"})],Qp=new Pt,fp=new Set(["SourceFile","Block","FunctionDecl","MethodDecl","FunctionLiteral","ForStatement","SwitchStatement","TypeSwitchStatement","IfStatement"]);function hi(O,e){return(t,i)=>{e:for(let r=t.node.firstChild,n=0,s=null;;){for(;!r;){if(!n)break e;n--,r=s.nextSibling,s=s.parent}e&&r.name==e||r.name=="SpecList"?(n++,s=r,r=r.firstChild):(r.name=="DefName"&&i(r,O),r=r.nextSibling)}return!0}}var q0={FunctionDecl:hi("function"),VarDecl:hi("var","VarSpec"),ConstDecl:hi("constant","ConstSpec"),TypeDecl:hi("type","TypeSpec"),ImportDecl:hi("constant","ImportSpec"),Parameter:hi("var"),__proto__:null};function dp(O,e){let t=Qp.get(e);if(t)return t;let i=[],r=!0;function n(s,a){let o=O.sliceString(s.from,s.to);i.push({label:o,type:a})}return e.cursor(C.IncludeAnonymous).iterate(s=>{if(r)r=!1;else if(s.name){let a=q0[s.name];if(a&&a(s,n)||fp.has(s.name))return!1}else if(s.to-s.from>8192){for(let a of dp(O,s.node))i.push(a);return!1}}),Qp.set(e,i),i}var $p=/^[\w$\xa1-\uffff][\w$\d\xa1-\uffff]*$/,up=["String","LineComment","BlockComment","DefName","LabelName","FieldName",".","?."],W0=O=>{let e=q(O.state).resolveInner(O.pos,-1);if(up.indexOf(e.name)>-1)return null;let t=e.name=="VariableName"||e.to-e.from<20&&$p.test(O.state.sliceDoc(e.from,e.to));if(!t&&!O.explicit)return null;let i=[];for(let r=e;r;r=r.parent)fp.has(r.name)&&(i=i.concat(dp(O.state.doc,r)));return{options:i,from:t?e.from:O.pos,validFor:$p}},Hl=re.define({name:"go",parser:hp.configure({props:[ne.add({IfStatement:oe({except:/^\s*({|else\b)/}),LabeledStatement:KO,"SwitchBlock SelectBlock":O=>{let e=O.textAfter,t=/^\s*\}/.test(e),i=/^\s*(case|default)\b/.test(e);return O.baseIndent+(t||i?0:O.unit)},Block:_e({closing:"}"}),BlockComment:()=>null,Statement:oe({except:/^{/})}),J.add({"Block SwitchBlock SelectBlock LiteralValue InterfaceType StructType SpecList":me,BlockComment(O){return{from:O.from+2,to:O.to-2}}})]}),languageData:{closeBrackets:{brackets:["(","[","{","'",'"',"`"]},commentTokens:{line:"//",block:{open:"/*",close:"*/"}},indentOnInput:/^\s*(?:case\b|default\b|\})$/}}),U0=O=>({label:O,type:"keyword"}),j0="interface struct chan map package go return break continue goto fallthrough else defer range true false nil".split(" ").map(U0);function pp(){let O=V0.concat(j0);return new F(Hl,[Hl.data.of({autocomplete:rO(up,Rt(O))}),Hl.data.of({autocomplete:W0})])}var mp=1,G0=2,C0=3,E0=82,A0=76,L0=117,M0=85,D0=97,I0=122,B0=65,N0=90,F0=95,Kl=48,gp=34,H0=40,Pp=41,K0=32,Sp=62,J0=new V(O=>{if(O.next==A0||O.next==M0?O.advance():O.next==L0&&(O.advance(),O.next==Kl+8&&O.advance()),O.next!=E0||(O.advance(),O.next!=gp))return;O.advance();let e="";for(;O.next!=H0;){if(O.next==K0||O.next<=13||O.next==Pp)return;e+=String.fromCharCode(O.next),O.advance()}for(O.advance();;){if(O.next<0)return O.acceptToken(mp);if(O.next==Pp){let t=!0;for(let i=0;t&&i<e.length;i++)O.peek(i+1)!=e.charCodeAt(i)&&(t=!1);if(t&&O.peek(e.length+1)==gp)return O.acceptToken(mp,2+e.length)}O.advance()}}),ex=new V(O=>{if(O.next==Sp)O.peek(1)==Sp&&O.acceptToken(G0,1);else{let e=!1,t=0;for(;;t++){if(O.next>=B0&&O.next<=N0)e=!0;else{if(O.next>=D0&&O.next<=I0)return;if(O.next!=F0&&!(O.next>=Kl&&O.next<=Kl+9))break}O.advance()}e&&t>1&&O.acceptToken(C0)}},{extend:!0}),tx=I({"typedef struct union enum class typename decltype auto template operator friend noexcept namespace using requires concept import export module __attribute__ __declspec __based":Q.definitionKeyword,"extern MsCallModifier MsPointerModifier extern static register thread_local inline const volatile restrict _Atomic mutable constexpr constinit consteval virtual explicit VirtualSpecifier Access":Q.modifier,"if else switch for while do case default return break continue goto throw try catch":Q.controlKeyword,"co_return co_yield co_await":Q.controlKeyword,"new sizeof delete static_assert":Q.operatorKeyword,"NULL nullptr":Q.null,this:Q.self,"True False":Q.bool,"TypeSize PrimitiveType":Q.standard(Q.typeName),TypeIdentifier:Q.typeName,FieldIdentifier:Q.propertyName,"CallExpression/FieldExpression/FieldIdentifier":Q.function(Q.propertyName),"ModuleName/Identifier":Q.namespace,PartitionName:Q.labelName,StatementIdentifier:Q.labelName,"Identifier DestructorName":Q.variableName,"CallExpression/Identifier":Q.function(Q.variableName),"CallExpression/ScopedIdentifier/Identifier":Q.function(Q.variableName),"FunctionDeclarator/Identifier FunctionDeclarator/DestructorName":Q.function(Q.definition(Q.variableName)),NamespaceIdentifier:Q.namespace,OperatorName:Q.operator,ArithOp:Q.arithmeticOperator,LogicOp:Q.logicOperator,BitOp:Q.bitwiseOperator,CompareOp:Q.compareOperator,AssignOp:Q.definitionOperator,UpdateOp:Q.updateOperator,LineComment:Q.lineComment,BlockComment:Q.blockComment,Number:Q.number,String:Q.string,"RawString SystemLibString":Q.special(Q.string),CharLiteral:Q.character,EscapeSequence:Q.escape,"
Line truncated
|
||||
`;function Ip(O,e,t){let i=Object.create(null);i.true=i.false=Ux,i.null=i.unknown=jx;for(let r of O.split(" "))r&&(i[r]=Mp);for(let r of e.split(" "))r&&(i[r]=Dp);for(let r of(t||"").split(" "))r&&(i[r]=Jx);return i}var RO="array binary bit boolean char character clob date decimal double float int integer interval large national nchar nclob numeric object precision real smallint time timestamp varchar varying ",zO="absolute action add after all allocate alter and any are as asc assertion at authorization before begin between both breadth by call cascade cascaded case cast catalog check close collate collation column commit condition connect connection constraint constraints constructor continue corresponding count create cross cube current current_date current_default_transform_group current_transform_group_for_type current_path current_role current_time current_timestamp current_user cursor cycle data day deallocate declare default deferrable deferred delete depth deref desc describe descriptor deterministic diagnostics disconnect distinct do domain drop dynamic each else elseif end end-exec equals escape except exception exec execute exists exit external fetch first for foreign found from free full function general get global go goto grant group grouping handle having hold hour identity if immediate in indicator initially inner inout input insert intersect into is isolation join key language last lateral leading leave left level like limit local localtime localtimestamp locator loop map match method minute modifies module month names natural nesting new next no none not of old on only open option or order ordinality out outer output overlaps pad parameter partial path prepare preserve primary prior privileges procedure public read reads recursive redo ref references referencing relative release repeat resignal restrict result return returns revoke right role rollback rollup routine row rows savepoint schema scroll search second section select session session_user set sets signal similar size some space specific specifictype sql sqlexception sqlstate sqlwarning start state static system_user table temporary then timezone_hour timezone_minute to trailing transaction translation treat trigger under undo union unique unnest until update usage user using value values view when whenever where while with without work write year zone ",cc={backslashEscapes:!1,hashComments:!1,spaceAfterDashes:!1,slashComments:!1,doubleQuotedStrings:!1,doubleDollarQuotedStrings:!1,unquotedBitLiterals:!1,treatBitsAsBytes:!1,charSetCasts:!1,plsqlQuotingMechanism:!1,operatorChars:"*+-%<>!=&|~^/",specialVar:"?",identifierQuotes:'"',words:Ip(zO,RO)};function rk(O,e,t,i){let r={};for(let n in cc)r[n]=(O.hasOwnProperty(n)?O:cc)[n];return e&&(r.words=Ip(e,t||"",i)),r}function Bp(O){return new V(e=>{var t;let{next:i}=e;if(e.advance(),ZO(i,ac)){for(;ZO(e.next,ac);)e.advance();e.acceptToken(qx)}else if(i==36&&O.doubleDollarQuotedStrings){let r=lc(e,"");e.next==36&&(e.advance(),tk(e,r),e.acceptToken(yr))}else if(i==39||i==34&&O.doubleQuotedStrings)_O(e,i,O.backslashEscapes),e.acceptToken(yr);else if(i==35&&O.hashComments||i==47&&e.next==47&&O.slashComments)Cp(e),e.acceptToken(qp);else if(i==45&&e.next==45&&(!O.spaceAfterDashes||e.peek(1)==32))Cp(e),e.acceptToken(qp);else if(i==47&&e.next==42){e.advance();for(let r=1;;){let n=e.next;if(e.next<0)break;if(e.advance(),n==42&&e.next==47){if(r--,e.advance(),!r)break}else n==47&&e.next==42&&(r++,e.advance())}e.acceptToken(Wx)}else if((i==101||i==69)&&e.next==39)e.advance(),_O(e,39,!0);else if((i==110||i==78)&&e.next==39&&O.charSetCasts)e.advance(),_O(e,39,O.backslashEscapes),e.acceptToken(yr);else if(i==95&&O.charSetCasts)for(let r=0;;r++){if(e.next==39&&r>1){e.advance(),_O(e,39,O.backslashEscapes),e.acceptToken(yr);break}if(!oc(e.next))break;e.advance()}else if(O.plsqlQuotingMechanism&&(i==113||i==81)&&e.next==39&&e.peek(1)>0&&!ZO(e.peek(1),ac)){let r=e.peek(1);e.advance(2),Ok(e,r),e.acceptToken(yr)}else if(i==40)e.acceptToken(Gx);else if(i==41)e.acceptToken(Cx);else if(i==123)e.acceptToken(Ex);else if(i==125)e.acceptToken(Ax);else if(i==91)e.acceptToken(Lx);else if(i==93)e.acceptToken(Mx);else if(i==59)e.acceptToken(Dx);else if(O.unquotedBitLiterals&&i==48&&e.next==98)e.advance(),jp(e),e.acceptToken(Up);else if((i==98||i==66)&&(e.next==39||e.next==34)){let r=e.next;e.advance(),O.treatBitsAsBytes?(_O(e,r,O.backslashEscapes),e.acceptToken(Kx)):(jp(e,r),e.acceptToken(Up))}else if(i==48&&(e.next==120||e.next==88)||(i==120||i==88)&&e.next==39){let r=e.next==39;for(e.advance();ek(e.next);)e.advance();r&&e.next==39&&e.advance(),e.acceptToken(sc)}else if(i==46&&e.next>=48&&e.next<=57)Gp(e,!0),e.acceptToken(sc);else if(i==46)e.acceptToken(Ix);else if(i>=48&&i<=57)Gp(e,!1),e.acceptToken(sc);else if(ZO(i,O.operatorChars)){for(;ZO(e.next,O.operatorChars);)e.advance();e.acceptToken(Bx)}else if(ZO(i,O.specialVar))e.next==i&&e.advance(),ik(e),e.acceptToken(Fx);else if(ZO(i,O.identifierQuotes))_O(e,i,!1),e.accept
Line truncated
|
||||
@@ -0,0 +1,19 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>Reasonix</title>
|
||||
<meta name="reasonix-token" content="__REASONIX_TOKEN__" />
|
||||
<meta name="reasonix-mode" content="__REASONIX_MODE__" />
|
||||
<link rel="stylesheet" href="/assets/app.css?token=__REASONIX_TOKEN__" />
|
||||
<link rel="stylesheet" href="https://esm.sh/[email protected]/dist/uPlot.min.css" />
|
||||
<link rel="stylesheet" href="https://esm.sh/[email protected]/styles/github-dark.min.css" />
|
||||
</head>
|
||||
<body>
|
||||
<div id="root">
|
||||
<div class="boot">loading…</div>
|
||||
</div>
|
||||
<script type="module" src="/assets/app.js?token=__REASONIX_TOKEN__"></script>
|
||||
</body>
|
||||
</html>
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
+59
-3
@@ -16,7 +16,7 @@
|
||||
"nav.benchmarks": "Benchmarks",
|
||||
"nav.github": "GitHub",
|
||||
|
||||
"hero.badge": "v0.6 · DeepSeek V4 · cache-first",
|
||||
"hero.badge": "v{version} · DeepSeek V4 · cache-first",
|
||||
"hero.title.line1": "DeepSeek-native",
|
||||
"hero.title.line2": "AI coding agent in your terminal",
|
||||
"hero.sub":
|
||||
@@ -143,7 +143,7 @@
|
||||
"nav.benchmarks": "性能对比",
|
||||
"nav.github": "GitHub",
|
||||
|
||||
"hero.badge": "v0.6 · DeepSeek V4 · 缓存优先",
|
||||
"hero.badge": "v{version} · DeepSeek V4 · 缓存优先",
|
||||
"hero.title.line1": "DeepSeek 原生",
|
||||
"hero.title.line2": "终端里的 AI 编程代理",
|
||||
"hero.sub":
|
||||
@@ -304,6 +304,49 @@
|
||||
let currentLang = DEFAULT_LANG;
|
||||
const langListeners = [];
|
||||
|
||||
// Version is rendered into translation strings via a `{version}` token
|
||||
// (see hero.badge). Source of truth is npm — `loadVersion()` fetches
|
||||
// it on page load and re-applies translations. Until that resolves
|
||||
// we fall back to the most recently cached value, then to a baked-in
|
||||
// default. Only places this constant matters: the user is offline AND
|
||||
// visits the site for the first time. Bumping it occasionally on
|
||||
// major version cuts is fine; the npm fetch handles everything else.
|
||||
const VERSION_STORAGE_KEY = "reasonix.version";
|
||||
const VERSION_FALLBACK = "0.12";
|
||||
const versionListeners = [];
|
||||
let currentVersion = VERSION_FALLBACK;
|
||||
|
||||
function applyVersion(v) {
|
||||
if (typeof v !== "string" || !v || v === currentVersion) return;
|
||||
currentVersion = v;
|
||||
safeStorageSet(VERSION_STORAGE_KEY, v);
|
||||
applyLang(currentLang); // re-render any `{version}` tokens
|
||||
for (const fn of versionListeners) {
|
||||
try {
|
||||
fn(v);
|
||||
} catch (_) {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function loadVersion() {
|
||||
try {
|
||||
const r = await fetch("https://registry.npmjs.org/reasonix/latest", {
|
||||
cache: "no-cache",
|
||||
});
|
||||
if (!r.ok) return;
|
||||
const data = await r.json();
|
||||
if (data && typeof data.version === "string") applyVersion(data.version);
|
||||
} catch (_) {
|
||||
/* offline / firewall — keep cached or fallback */
|
||||
}
|
||||
}
|
||||
|
||||
function fillVersion(s) {
|
||||
return typeof s === "string" ? s.replace(/\{version\}/g, currentVersion) : s;
|
||||
}
|
||||
|
||||
function applyLang(lang) {
|
||||
if (!SUPPORTED.includes(lang)) lang = DEFAULT_LANG;
|
||||
const changed = lang !== currentLang;
|
||||
@@ -316,7 +359,7 @@
|
||||
document.querySelectorAll("[data-i18n]").forEach((el) => {
|
||||
const key = el.getAttribute("data-i18n");
|
||||
if (dict[key] !== undefined) {
|
||||
el.innerHTML = dict[key];
|
||||
el.innerHTML = fillVersion(dict[key]);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -350,6 +393,12 @@
|
||||
window.Reasonix.onLangChange = function (fn) {
|
||||
if (typeof fn === "function") langListeners.push(fn);
|
||||
};
|
||||
window.Reasonix.version = function () {
|
||||
return currentVersion;
|
||||
};
|
||||
window.Reasonix.onVersionChange = function (fn) {
|
||||
if (typeof fn === "function") versionListeners.push(fn);
|
||||
};
|
||||
|
||||
function wireLangButtons() {
|
||||
document.querySelectorAll("[data-lang-btn]").forEach((btn) => {
|
||||
@@ -393,9 +442,16 @@
|
||||
}
|
||||
|
||||
function init() {
|
||||
// Use the cached npm version (if any) so the badge isn't visibly
|
||||
// wrong on first paint; fall back to the baked-in default. Then
|
||||
// fire off the live fetch — when it resolves, applyVersion()
|
||||
// re-applies translations and notifies subscribers (term-anim).
|
||||
const cached = safeStorageGet(VERSION_STORAGE_KEY);
|
||||
if (typeof cached === "string" && /^\d+\.\d+/.test(cached)) currentVersion = cached;
|
||||
applyLang(detectLang());
|
||||
wireLangButtons();
|
||||
wireCopyButtons();
|
||||
loadVersion();
|
||||
}
|
||||
|
||||
if (document.readyState === "loading") {
|
||||
|
||||
+18
-2
@@ -43,14 +43,21 @@
|
||||
];
|
||||
|
||||
// ──────────────────────────────────────────────────────────────────
|
||||
// Header bar — `◈ REASONIX v0.6.0 v4-flash REVIEW max … turn 1 · /help`
|
||||
// Header bar — `◈ REASONIX v0.12.x v4-flash REVIEW max … turn 1 · /help`
|
||||
// Version comes from the i18n script (which fetched it from npm).
|
||||
// Falls back to a baked-in default before the fetch lands.
|
||||
// ──────────────────────────────────────────────────────────────────
|
||||
function currentVersion() {
|
||||
const r = window.Reasonix;
|
||||
return (r && typeof r.version === "function" ? r.version() : null) || "0.12";
|
||||
}
|
||||
|
||||
function buildHeader(turn) {
|
||||
const h = el("div", "thead");
|
||||
h.innerHTML =
|
||||
'<span class="tw-mark">◈</span>' +
|
||||
'<span class="tw-name">REASONIX</span>' +
|
||||
'<span class="tw-ver">v0.6.0</span>' +
|
||||
`<span class="tw-ver">v${currentVersion()}</span>` +
|
||||
'<span class="tw-model">v4-flash</span>' +
|
||||
'<span class="tw-pill review">REVIEW</span>' +
|
||||
'<span class="tw-effort">max</span>' +
|
||||
@@ -372,6 +379,15 @@
|
||||
if (window.Reasonix && typeof window.Reasonix.onLangChange === "function") {
|
||||
window.Reasonix.onLangChange(() => runCycle(root));
|
||||
}
|
||||
// npm version arrives async after first paint — patch the header's
|
||||
// version pill in place so we don't have to re-run the whole
|
||||
// animation just to update one number.
|
||||
if (window.Reasonix && typeof window.Reasonix.onVersionChange === "function") {
|
||||
window.Reasonix.onVersionChange((v) => {
|
||||
const pill = root.querySelector(".tw-ver");
|
||||
if (pill) pill.textContent = "v" + v;
|
||||
});
|
||||
}
|
||||
|
||||
document.querySelectorAll(REPLAY_SEL).forEach((btn) => {
|
||||
btn.addEventListener("click", () => runCycle(root));
|
||||
|
||||
Generated
+1530
-555
File diff suppressed because it is too large.
Load diff
+36
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "reasonix",
|
||||
"version": "0.11.3",
|
||||
"version": "0.14.0",
|
||||
"description": "DeepSeek-native coding agent: cache-first loop, flash-first cost control, tool-call repair.",
|
||||
"type": "module",
|
||||
"bin": {
|
||||
@@ -18,11 +18,16 @@
|
||||
"files": [
|
||||
"dist",
|
||||
"data/deepseek-tokenizer.json.gz",
|
||||
"dashboard/index.html",
|
||||
"dashboard/app.js",
|
||||
"dashboard/app.css",
|
||||
"dashboard/codemirror.js",
|
||||
"README.md",
|
||||
"LICENSE"
|
||||
],
|
||||
"scripts": {
|
||||
"build": "tsup",
|
||||
"build:cm": "node scripts/bundle-codemirror.mjs",
|
||||
"dev": "tsx src/cli/index.ts",
|
||||
"chat": "tsx src/cli/index.ts chat",
|
||||
"test": "vitest run",
|
||||
@@ -31,8 +36,14 @@
|
||||
"lint:fix": "biome check --write src tests",
|
||||
"format": "biome format --write src tests",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"verify": "npm run lint && npm run typecheck && npm run test --silent",
|
||||
"prepare": "simple-git-hooks || true",
|
||||
"prepublishOnly": "npm run lint && npm run typecheck && npm run test && npm run build"
|
||||
},
|
||||
"simple-git-hooks": {
|
||||
"pre-commit": "npm run lint",
|
||||
"pre-push": "npm run verify"
|
||||
},
|
||||
"keywords": [
|
||||
"agent",
|
||||
"llm",
|
||||
@@ -62,12 +73,35 @@
|
||||
"ink": "^5.1.0",
|
||||
"ink-spinner": "^5.0.0",
|
||||
"ink-text-input": "^6.0.0",
|
||||
"react": "^18.3.1"
|
||||
"react": "^18.3.1",
|
||||
"string-width": "^7.2.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@biomejs/biome": "^1.9.4",
|
||||
"@codemirror/autocomplete": "^6.16.0",
|
||||
"@codemirror/commands": "^6.5.0",
|
||||
"@codemirror/lang-cpp": "^6.0.2",
|
||||
"@codemirror/lang-css": "^6.2.1",
|
||||
"@codemirror/lang-go": "^6.0.1",
|
||||
"@codemirror/lang-html": "^6.4.9",
|
||||
"@codemirror/lang-javascript": "^6.2.2",
|
||||
"@codemirror/lang-json": "^6.0.1",
|
||||
"@codemirror/lang-markdown": "^6.2.5",
|
||||
"@codemirror/lang-php": "^6.0.1",
|
||||
"@codemirror/lang-python": "^6.1.6",
|
||||
"@codemirror/lang-rust": "^6.0.1",
|
||||
"@codemirror/lang-sql": "^6.6.4",
|
||||
"@codemirror/lang-xml": "^6.1.0",
|
||||
"@codemirror/lang-yaml": "^6.1.1",
|
||||
"@codemirror/language": "^6.10.1",
|
||||
"@codemirror/search": "^6.5.6",
|
||||
"@codemirror/state": "^6.4.1",
|
||||
"@codemirror/theme-one-dark": "^6.1.2",
|
||||
"@codemirror/view": "^6.26.0",
|
||||
"@types/node": "^22.9.0",
|
||||
"@types/react": "^18.3.12",
|
||||
"esbuild": "^0.21.5",
|
||||
"simple-git-hooks": "^2.13.1",
|
||||
"tsup": "^8.3.5",
|
||||
"tsx": "^4.19.2",
|
||||
"typescript": "^5.6.3",
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Bundle every CodeMirror package the dashboard editor needs into one
|
||||
* local ESM file at dashboard/codemirror.js. Replaces the runtime
|
||||
* esm.sh imports — CDN multi-instance issues (different copies of
|
||||
* @lezer/highlight breaking tag identity, etc.) just go away once
|
||||
* everything ships in a single bundle.
|
||||
*
|
||||
* Run after bumping any @codemirror/* package version:
|
||||
* node scripts/bundle-codemirror.mjs
|
||||
*
|
||||
* The output is committed to the repo and shipped in the npm tarball.
|
||||
*/
|
||||
import { build } from "esbuild";
|
||||
import { mkdirSync, writeFileSync } from "node:fs";
|
||||
import { dirname, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url));
|
||||
const repoRoot = resolve(here, "..");
|
||||
const entryPath = resolve(repoRoot, "scripts/.cm-entry.mjs");
|
||||
const outPath = resolve(repoRoot, "dashboard/codemirror.js");
|
||||
|
||||
// Re-export every symbol the editor needs as a single flat record.
|
||||
// Same shape app.js's old loadCodeMirror() returned, so swapping the
|
||||
// runtime fetch for `import * as cm from "./codemirror.js"` is a
|
||||
// one-line change on the consumer side.
|
||||
const entry = `
|
||||
import { EditorState, Compartment } from "@codemirror/state";
|
||||
import {
|
||||
EditorView, keymap, lineNumbers, highlightActiveLine,
|
||||
highlightActiveLineGutter, drawSelection,
|
||||
} from "@codemirror/view";
|
||||
import {
|
||||
defaultKeymap, history, historyKeymap, indentWithTab,
|
||||
} from "@codemirror/commands";
|
||||
import {
|
||||
syntaxHighlighting, defaultHighlightStyle, bracketMatching,
|
||||
indentOnInput, foldGutter, foldKeymap,
|
||||
} from "@codemirror/language";
|
||||
import {
|
||||
closeBrackets, closeBracketsKeymap, autocompletion, completionKeymap,
|
||||
} from "@codemirror/autocomplete";
|
||||
import { searchKeymap, highlightSelectionMatches } from "@codemirror/search";
|
||||
import { oneDark } from "@codemirror/theme-one-dark";
|
||||
|
||||
import { javascript } from "@codemirror/lang-javascript";
|
||||
import { python } from "@codemirror/lang-python";
|
||||
import { markdown } from "@codemirror/lang-markdown";
|
||||
import { json } from "@codemirror/lang-json";
|
||||
import { html as htmlLang } from "@codemirror/lang-html";
|
||||
import { css } from "@codemirror/lang-css";
|
||||
import { rust } from "@codemirror/lang-rust";
|
||||
import { go } from "@codemirror/lang-go";
|
||||
import { cpp } from "@codemirror/lang-cpp";
|
||||
import { yaml } from "@codemirror/lang-yaml";
|
||||
import { sql } from "@codemirror/lang-sql";
|
||||
import { xml } from "@codemirror/lang-xml";
|
||||
import { php } from "@codemirror/lang-php";
|
||||
|
||||
export {
|
||||
EditorState, Compartment,
|
||||
EditorView, keymap, lineNumbers, highlightActiveLine,
|
||||
highlightActiveLineGutter, drawSelection,
|
||||
defaultKeymap, history, historyKeymap, indentWithTab,
|
||||
syntaxHighlighting, defaultHighlightStyle, bracketMatching,
|
||||
indentOnInput, foldGutter, foldKeymap,
|
||||
closeBrackets, closeBracketsKeymap, autocompletion, completionKeymap,
|
||||
searchKeymap, highlightSelectionMatches,
|
||||
oneDark,
|
||||
};
|
||||
|
||||
export const langs = {
|
||||
javascript,
|
||||
typescript: () => javascript({ typescript: true }),
|
||||
python,
|
||||
markdown,
|
||||
json,
|
||||
html: htmlLang,
|
||||
css,
|
||||
rust,
|
||||
go,
|
||||
cpp,
|
||||
yaml,
|
||||
sql,
|
||||
xml,
|
||||
php,
|
||||
};
|
||||
`;
|
||||
|
||||
mkdirSync(dirname(entryPath), { recursive: true });
|
||||
writeFileSync(entryPath, entry);
|
||||
|
||||
await build({
|
||||
entryPoints: [entryPath],
|
||||
outfile: outPath,
|
||||
bundle: true,
|
||||
format: "esm",
|
||||
target: "es2022",
|
||||
minify: true,
|
||||
legalComments: "none",
|
||||
logLevel: "info",
|
||||
});
|
||||
|
||||
console.log(`bundled → ${outPath}`);
|
||||
@@ -20,6 +20,7 @@
|
||||
*/
|
||||
|
||||
import { type Dirent, existsSync, readFileSync, readdirSync, statSync } from "node:fs";
|
||||
import { readdir, stat } from "node:fs/promises";
|
||||
import { isAbsolute, join, relative, resolve } from "node:path";
|
||||
|
||||
/** Caps match tool-result dispatch truncation (0.5.2). */
|
||||
@@ -128,6 +129,92 @@ export function listFilesWithStatsSync(root: string, opts: ListFilesOptions = {}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Async variant of {@link listFilesWithStatsSync}. Same walk semantics
|
||||
* (DFS, alphabetical, respects ignore + maxResults), but each
|
||||
* directory's entries are stat'd in parallel via `Promise.all`,
|
||||
* which slashes wall-clock time on Windows where individual stat
|
||||
* syscalls are 3-5x slower than Linux.
|
||||
*
|
||||
* Use this from the TUI mount path so a 500-file repo doesn't add
|
||||
* 200-300ms of synchronous block to first paint. Sync variant is
|
||||
* kept for paths where the caller can't `await` (server APIs,
|
||||
* test scaffolding).
|
||||
*/
|
||||
export async function listFilesWithStatsAsync(
|
||||
root: string,
|
||||
opts: ListFilesOptions = {},
|
||||
): Promise<FileWithStats[]> {
|
||||
const maxResults = Math.max(1, opts.maxResults ?? 500);
|
||||
const ignore = new Set(opts.ignoreDirs ?? DEFAULT_PICKER_IGNORE_DIRS);
|
||||
const rootAbs = resolve(root);
|
||||
const out: FileWithStats[] = [];
|
||||
|
||||
const walk = async (dirAbs: string, dirRel: string): Promise<void> => {
|
||||
if (out.length >= maxResults) return;
|
||||
let entries: Dirent[];
|
||||
try {
|
||||
entries = await readdir(dirAbs, { withFileTypes: true });
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
entries.sort((a, b) => a.name.localeCompare(b.name));
|
||||
// Pull file stats for THIS directory in parallel before
|
||||
// recursing — readdir gave us all the names at once, may as
|
||||
// well issue all the stats at once too. Recursion stays
|
||||
// sequential so the alphabetical ordering of the merged list
|
||||
// matches the sync walk's contract.
|
||||
const fileEnts: Dirent[] = [];
|
||||
for (const ent of entries) {
|
||||
if (out.length >= maxResults) break;
|
||||
if (ent.isDirectory()) {
|
||||
if (ent.name.startsWith(".") || ignore.has(ent.name)) continue;
|
||||
// Drain pending file stats from THIS directory before
|
||||
// descending so the output order stays DFS-alphabetical.
|
||||
if (fileEnts.length > 0) {
|
||||
await statBatch(fileEnts, dirAbs, dirRel, out, maxResults);
|
||||
fileEnts.length = 0;
|
||||
if (out.length >= maxResults) return;
|
||||
}
|
||||
await walk(join(dirAbs, ent.name), dirRel ? `${dirRel}/${ent.name}` : ent.name);
|
||||
} else if (ent.isFile()) {
|
||||
fileEnts.push(ent);
|
||||
}
|
||||
}
|
||||
if (fileEnts.length > 0 && out.length < maxResults) {
|
||||
await statBatch(fileEnts, dirAbs, dirRel, out, maxResults);
|
||||
}
|
||||
};
|
||||
|
||||
await walk(rootAbs, "");
|
||||
return out;
|
||||
}
|
||||
|
||||
async function statBatch(
|
||||
ents: readonly Dirent[],
|
||||
dirAbs: string,
|
||||
dirRel: string,
|
||||
out: FileWithStats[],
|
||||
maxResults: number,
|
||||
): Promise<void> {
|
||||
const remaining = Math.max(0, maxResults - out.length);
|
||||
const batch = ents.slice(0, remaining);
|
||||
const stats = await Promise.all(
|
||||
batch.map((e) =>
|
||||
stat(join(dirAbs, e.name))
|
||||
.then((s) => s.mtimeMs)
|
||||
.catch(() => 0),
|
||||
),
|
||||
);
|
||||
for (let i = 0; i < batch.length; i++) {
|
||||
const ent = batch[i]!;
|
||||
out.push({
|
||||
path: dirRel ? `${dirRel}/${ent.name}` : ent.name,
|
||||
mtimeMs: stats[i] ?? 0,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prefix pattern used by the `@` picker to detect an IN-PROGRESS
|
||||
* mention at the END of the input buffer. Captures the partial path
|
||||
|
||||
@@ -38,6 +38,13 @@ export interface ChatOptions {
|
||||
transcript?: string;
|
||||
harvest?: boolean;
|
||||
branch?: number;
|
||||
/**
|
||||
* Soft USD cap on session spend. Undefined → no cap (default).
|
||||
* The loop warns once at 80% and refuses to start a new turn at
|
||||
* 100%. Users can bump or clear via `/budget <usd>` / `/budget off`
|
||||
* mid-session.
|
||||
*/
|
||||
budgetUsd?: number;
|
||||
session?: string;
|
||||
/** Zero or more MCP server specs. Each: `"name=cmd args..."` or `"cmd args..."`. */
|
||||
mcp?: string[];
|
||||
@@ -69,6 +76,12 @@ export interface ChatOptions {
|
||||
forceResume?: boolean;
|
||||
/** Skip the session picker — assume "New" (wipe the session file and start fresh). */
|
||||
forceNew?: boolean;
|
||||
/**
|
||||
* When true, suppress auto-launch of the embedded web dashboard.
|
||||
* Default behavior (false/undefined) is to boot it on mount so the
|
||||
* URL is visible in the status bar.
|
||||
*/
|
||||
noDashboard?: boolean;
|
||||
}
|
||||
|
||||
interface RootProps extends ChatOptions {
|
||||
@@ -149,12 +162,14 @@ function Root({
|
||||
transcript={appProps.transcript}
|
||||
harvest={appProps.harvest}
|
||||
branch={appProps.branch}
|
||||
budgetUsd={appProps.budgetUsd}
|
||||
session={appProps.session}
|
||||
tools={tools}
|
||||
mcpSpecs={mcpSpecs}
|
||||
mcpServers={mcpServers}
|
||||
progressSink={progressSink}
|
||||
codeMode={appProps.codeMode}
|
||||
noDashboard={appProps.noDashboard}
|
||||
/>
|
||||
</KeystrokeProvider>
|
||||
);
|
||||
|
||||
@@ -53,6 +53,14 @@ export interface CodeOptions {
|
||||
* reasoning surfaced explicitly can pass `--harvest`.
|
||||
*/
|
||||
harvest?: boolean;
|
||||
/**
|
||||
* Soft USD spend cap. Off by default. Same semantics as `chat`:
|
||||
* warns at 80%, refuses next turn at 100%. Mid-session adjustable
|
||||
* via `/budget <usd>` slash command.
|
||||
*/
|
||||
budgetUsd?: number;
|
||||
/** Suppress the auto-launched embedded web dashboard. */
|
||||
noDashboard?: boolean;
|
||||
}
|
||||
|
||||
export async function codeCommand(opts: CodeOptions = {}): Promise<void> {
|
||||
@@ -146,6 +154,7 @@ export async function codeCommand(opts: CodeOptions = {}): Promise<void> {
|
||||
await chatCommand({
|
||||
model: opts.model ?? "deepseek-v4-flash",
|
||||
harvest: opts.harvest ?? false,
|
||||
budgetUsd: opts.budgetUsd,
|
||||
system: codeSystemPrompt(rootDir, { hasSemanticSearch: semantic.enabled }),
|
||||
transcript: opts.transcript,
|
||||
session,
|
||||
@@ -153,5 +162,6 @@ export async function codeCommand(opts: CodeOptions = {}): Promise<void> {
|
||||
codeMode: { rootDir, jobs, reregisterTools: registerRootedTools },
|
||||
forceResume: opts.forceResume,
|
||||
forceNew: opts.forceNew,
|
||||
noDashboard: opts.noDashboard,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,359 @@
|
||||
/**
|
||||
* `reasonix commit` — draft a commit message from staged changes.
|
||||
*
|
||||
* Workflow:
|
||||
* 1. Read `git diff --staged`. Empty staging area falls back to the
|
||||
* working tree (with a warning), so a quick `reasonix commit`
|
||||
* after editing-without-add still produces a draft instead of
|
||||
* silently no-op'ing.
|
||||
* 2. Read `git log -10 --format=%s%n%b%n---END---` so the model can
|
||||
* match the project's actual commit style instead of generic
|
||||
* "feat: …" boilerplate. The diff IS the spec; the log is the
|
||||
* voice.
|
||||
* 3. One non-streaming flash call drafts the message. Default model
|
||||
* is v4-flash — drafting a commit message doesn't need pro.
|
||||
* 4. Print the draft. Read a key from stdin: a/A/Enter accept, r/R
|
||||
* regenerate, e/E open in $EDITOR, c/C cancel.
|
||||
* 5. Accept → `git commit -F -` with the message on stdin so multi-
|
||||
* line bodies survive intact (no shell quoting concerns).
|
||||
*
|
||||
* The whole flow is plain text — no Ink — because it's a one-shot
|
||||
* command. Keeping it dependency-free means it works even when the
|
||||
* TUI bundle has a runtime issue.
|
||||
*
|
||||
* Loaded `.env` via `loadDotenv()` first thing so users who keep
|
||||
* DEEPSEEK_API_KEY in `.env` (instead of shell env) don't see a
|
||||
* confusing "key not set" error here.
|
||||
*/
|
||||
|
||||
import { spawn, spawnSync } from "node:child_process";
|
||||
import { mkdtempSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { stdin, stdout } from "node:process";
|
||||
import { createInterface } from "node:readline/promises";
|
||||
import { DeepSeekClient } from "../../client.js";
|
||||
import { loadApiKey } from "../../config.js";
|
||||
import { loadDotenv } from "../../env.js";
|
||||
|
||||
export interface CommitOptions {
|
||||
/** Override the default model (deepseek-v4-flash). */
|
||||
model?: string;
|
||||
/** Skip the confirmation step — useful in scripts where the diff has been pre-reviewed. */
|
||||
yes?: boolean;
|
||||
}
|
||||
|
||||
const DEFAULT_MODEL = "deepseek-v4-flash";
|
||||
const DIFF_BYTE_CAP = 80 * 1024;
|
||||
const LOG_COUNT = 10;
|
||||
|
||||
const SYSTEM_PROMPT = `You draft git commit messages.
|
||||
|
||||
Output ONLY the commit message — no preamble, no \`\`\` fences, no "Here's a commit message:" lead-in. The first line of your output IS the commit subject.
|
||||
|
||||
Match the project's existing style:
|
||||
- Look at the recent commits provided. Mirror their voice, conventional-commit prefix usage (or absence), tense, length, body structure.
|
||||
- If recent commits use a "type(scope): summary" prefix, use it. If they don't, don't invent one.
|
||||
- Subject line: one line, ≤72 chars, imperative mood, no trailing period.
|
||||
- Body (optional): explain WHY when the diff isn't self-evident. Wrap at ~72 chars. Skip the body for trivial changes — repeating the subject in the body is noise.
|
||||
|
||||
The diff is the source of truth for what changed; describe THAT, not your guesses about the broader project. If the diff includes a deletion you can't explain from the surrounding context, name it but don't speculate about why.
|
||||
|
||||
No emojis unless the recent commits use them.
|
||||
No co-author trailers, no "Generated with X" footers.`;
|
||||
|
||||
function runGit(
|
||||
args: string[],
|
||||
opts: { input?: string } = {},
|
||||
): { stdout: string; stderr: string; status: number | null } {
|
||||
const result = spawnSync("git", args, {
|
||||
encoding: "utf8",
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
input: opts.input,
|
||||
maxBuffer: 32 * 1024 * 1024,
|
||||
});
|
||||
return {
|
||||
stdout: result.stdout ?? "",
|
||||
stderr: result.stderr ?? "",
|
||||
status: result.status,
|
||||
};
|
||||
}
|
||||
|
||||
function dieIfNotGitRepo(): void {
|
||||
const r = runGit(["rev-parse", "--is-inside-work-tree"]);
|
||||
if (r.status !== 0) {
|
||||
process.stderr.write("reasonix commit: not inside a git repository.\n");
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
interface DiffResult {
|
||||
diff: string;
|
||||
source: "staged" | "working-tree";
|
||||
truncated: boolean;
|
||||
}
|
||||
|
||||
function readDiff(): DiffResult | null {
|
||||
const staged = runGit(["diff", "--staged", "--no-color"]);
|
||||
if (staged.status !== 0) {
|
||||
process.stderr.write(`reasonix commit: git diff --staged failed: ${staged.stderr.trim()}\n`);
|
||||
process.exit(1);
|
||||
}
|
||||
if (staged.stdout.trim().length > 0) {
|
||||
return capDiff(staged.stdout, "staged");
|
||||
}
|
||||
const wt = runGit(["diff", "--no-color"]);
|
||||
if (wt.stdout.trim().length === 0) {
|
||||
return null;
|
||||
}
|
||||
return capDiff(wt.stdout, "working-tree");
|
||||
}
|
||||
|
||||
function capDiff(raw: string, source: "staged" | "working-tree"): DiffResult {
|
||||
if (raw.length <= DIFF_BYTE_CAP) {
|
||||
return { diff: raw, source, truncated: false };
|
||||
}
|
||||
const head = raw.slice(0, Math.floor(DIFF_BYTE_CAP * 0.7));
|
||||
const tail = raw.slice(-Math.floor(DIFF_BYTE_CAP * 0.3));
|
||||
return {
|
||||
diff: `${head}\n\n[… ${raw.length - DIFF_BYTE_CAP} bytes of diff truncated …]\n\n${tail}`,
|
||||
source,
|
||||
truncated: true,
|
||||
};
|
||||
}
|
||||
|
||||
function readRecentCommits(): string {
|
||||
const r = runGit(["log", `-${LOG_COUNT}`, "--no-merges", "--format=%s%n%b%n---END---"]);
|
||||
if (r.status !== 0) {
|
||||
// Repo may not have any commits yet (initial commit case). Don't
|
||||
// fail — let the model work from the diff alone.
|
||||
return "";
|
||||
}
|
||||
return r.stdout.trim();
|
||||
}
|
||||
|
||||
async function draftMessage(
|
||||
client: DeepSeekClient,
|
||||
model: string,
|
||||
diff: DiffResult,
|
||||
recentCommits: string,
|
||||
): Promise<string> {
|
||||
const userParts: string[] = [];
|
||||
if (recentCommits) {
|
||||
userParts.push(`Recent commits (style reference):\n\n${recentCommits}`);
|
||||
}
|
||||
if (diff.source === "working-tree") {
|
||||
userParts.push(
|
||||
"(NOTE: diff is from the working tree, not the staging area — nothing is staged yet. The user will stage selectively after seeing the draft.)",
|
||||
);
|
||||
}
|
||||
userParts.push(`Diff to summarize:\n\n${diff.diff}`);
|
||||
|
||||
const resp = await client.chat({
|
||||
model,
|
||||
messages: [
|
||||
{ role: "system", content: SYSTEM_PROMPT },
|
||||
{ role: "user", content: userParts.join("\n\n") },
|
||||
],
|
||||
temperature: 0.2,
|
||||
});
|
||||
return stripCodeFences(resp.content.trim());
|
||||
}
|
||||
|
||||
function stripCodeFences(s: string): string {
|
||||
// Some models still wrap output in ``` despite the system prompt
|
||||
// telling them not to. Strip a single leading + trailing fence pair
|
||||
// if present. Only operates on a wrapping pair — internal fences
|
||||
// (a code block inside the body) stay.
|
||||
const trimmed = s.trim();
|
||||
const fenceOpen = /^```[a-zA-Z]*\n/;
|
||||
const fenceClose = /\n?```$/;
|
||||
if (fenceOpen.test(trimmed) && fenceClose.test(trimmed)) {
|
||||
return trimmed.replace(fenceOpen, "").replace(fenceClose, "").trim();
|
||||
}
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
function printDraft(message: string): void {
|
||||
const sep = "─".repeat(60);
|
||||
process.stdout.write(`\n${sep}\n${message}\n${sep}\n\n`);
|
||||
}
|
||||
|
||||
async function promptChoice(): Promise<"accept" | "regen" | "edit" | "cancel"> {
|
||||
const rl = createInterface({ input: stdin, output: stdout });
|
||||
try {
|
||||
const answer = await rl.question("[a]ccept / [r]egenerate / [e]dit / [c]ancel: ");
|
||||
const k = answer.trim().toLowerCase();
|
||||
if (k === "" || k === "a" || k === "y" || k === "yes") return "accept";
|
||||
if (k === "r" || k === "regen" || k === "regenerate") return "regen";
|
||||
if (k === "e" || k === "edit") return "edit";
|
||||
return "cancel";
|
||||
} finally {
|
||||
rl.close();
|
||||
}
|
||||
}
|
||||
|
||||
function editInExternal(initial: string): string | null {
|
||||
const editor = process.env.GIT_EDITOR ?? process.env.VISUAL ?? process.env.EDITOR;
|
||||
if (!editor) {
|
||||
process.stderr.write(
|
||||
"reasonix commit: no $EDITOR / $VISUAL / $GIT_EDITOR set — can't open editor. Pick [a]ccept and `git commit --amend` afterwards.\n",
|
||||
);
|
||||
return null;
|
||||
}
|
||||
const dir = mkdtempSync(join(tmpdir(), "reasonix-commit-"));
|
||||
const path = join(dir, "COMMIT_EDITMSG");
|
||||
writeFileSync(path, initial, "utf8");
|
||||
// spawnSync with shell:true is required so $EDITOR strings like
|
||||
// `code --wait` work — they're shell command lines, not argv tuples.
|
||||
// The trust boundary is the user's own env var; matches how git
|
||||
// itself launches editors.
|
||||
const result = spawnSync(`${editor} "${path}"`, {
|
||||
stdio: "inherit",
|
||||
shell: true,
|
||||
});
|
||||
if (result.status !== 0) {
|
||||
try {
|
||||
unlinkSync(path);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
process.stderr.write(
|
||||
`reasonix commit: editor exited ${result.status} — keeping prior draft.\n`,
|
||||
);
|
||||
return null;
|
||||
}
|
||||
let edited: string;
|
||||
try {
|
||||
edited = readFileSync(path, "utf8");
|
||||
} catch {
|
||||
return null;
|
||||
} finally {
|
||||
try {
|
||||
unlinkSync(path);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
// Strip git's standard `# …` comment lines, even though we didn't
|
||||
// emit any — a user habituated to `git commit` may add `#`-prefixed
|
||||
// notes by reflex.
|
||||
const cleaned = edited
|
||||
.split(/\r?\n/)
|
||||
.filter((line) => !/^\s*#/.test(line))
|
||||
.join("\n")
|
||||
.trim();
|
||||
return cleaned || null;
|
||||
}
|
||||
|
||||
function commitWithMessage(message: string): void {
|
||||
// -F - reads the message from stdin, sidestepping shell quoting and
|
||||
// letting multi-line bodies through cleanly. Inherit stdio so the
|
||||
// user sees git's own confirmation / pre-commit hook output.
|
||||
const child = spawn("git", ["commit", "-F", "-"], {
|
||||
stdio: ["pipe", "inherit", "inherit"],
|
||||
});
|
||||
child.stdin.write(message);
|
||||
child.stdin.end();
|
||||
child.on("close", (code) => {
|
||||
if (code !== 0) {
|
||||
process.stderr.write(`reasonix commit: git commit exited ${code}.\n`);
|
||||
process.exit(code ?? 1);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export async function commitCommand(opts: CommitOptions = {}): Promise<void> {
|
||||
loadDotenv();
|
||||
dieIfNotGitRepo();
|
||||
|
||||
const apiKey = loadApiKey() ?? process.env.DEEPSEEK_API_KEY;
|
||||
if (!apiKey) {
|
||||
process.stderr.write(
|
||||
"reasonix commit: DEEPSEEK_API_KEY not set. Run `reasonix setup` to save one, or export it.\n",
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const diff = readDiff();
|
||||
if (!diff) {
|
||||
process.stderr.write(
|
||||
"reasonix commit: no staged changes and working tree is clean — nothing to commit.\n",
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
if (diff.source === "working-tree") {
|
||||
process.stderr.write(
|
||||
"reasonix commit: nothing staged — drafting from working-tree diff. Stage your changes and re-run, or use the draft as a starting point.\n",
|
||||
);
|
||||
}
|
||||
if (diff.truncated) {
|
||||
process.stderr.write(
|
||||
"reasonix commit: diff exceeded 80KB; head + tail sent to the model. Large diffs often produce vague drafts — consider committing in smaller chunks.\n",
|
||||
);
|
||||
}
|
||||
|
||||
const client = new DeepSeekClient({ apiKey });
|
||||
const model = opts.model ?? DEFAULT_MODEL;
|
||||
const recentCommits = readRecentCommits();
|
||||
|
||||
let message = "";
|
||||
let firstPass = true;
|
||||
while (true) {
|
||||
if (firstPass) {
|
||||
process.stdout.write("Drafting commit message…\n");
|
||||
} else {
|
||||
process.stdout.write("Regenerating…\n");
|
||||
}
|
||||
firstPass = false;
|
||||
try {
|
||||
message = await draftMessage(client, model, diff, recentCommits);
|
||||
} catch (err) {
|
||||
process.stderr.write(`reasonix commit: model call failed — ${(err as Error).message}\n`);
|
||||
process.exit(1);
|
||||
}
|
||||
if (!message) {
|
||||
process.stderr.write("reasonix commit: model returned an empty draft. Try again.\n");
|
||||
process.exit(1);
|
||||
}
|
||||
printDraft(message);
|
||||
|
||||
if (opts.yes) break;
|
||||
if (diff.source === "working-tree") {
|
||||
// Refuse to commit a working-tree-derived draft — the staging
|
||||
// area is empty so `git commit` would fail anyway. Print the
|
||||
// draft so the user can copy it; exit 0 because we did our job.
|
||||
process.stdout.write(
|
||||
"(no staged changes — draft printed above for you to copy. Stage with `git add` and re-run to commit.)\n",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const choice = await promptChoice();
|
||||
if (choice === "accept") break;
|
||||
if (choice === "cancel") {
|
||||
process.stderr.write("commit cancelled.\n");
|
||||
return;
|
||||
}
|
||||
if (choice === "edit") {
|
||||
const edited = editInExternal(message);
|
||||
if (edited) {
|
||||
message = edited;
|
||||
printDraft(message);
|
||||
// Re-prompt: the user may want to edit again, accept, etc.
|
||||
const next = await promptChoice();
|
||||
if (next === "accept") break;
|
||||
if (next === "cancel") {
|
||||
process.stderr.write("commit cancelled.\n");
|
||||
return;
|
||||
}
|
||||
// next is "regen" or another "edit" — fall through to the
|
||||
// loop top to re-draft (regen) or land back at this branch.
|
||||
}
|
||||
// editor returned no edit — loop top will regen by default.
|
||||
}
|
||||
// Anything else (regen, or unsuccessful edit) → loop top redraws.
|
||||
}
|
||||
|
||||
commitWithMessage(message);
|
||||
}
|
||||
@@ -0,0 +1,375 @@
|
||||
/**
|
||||
* `reasonix doctor` — one-command health check.
|
||||
*
|
||||
* Output is plain text, not Ink. The whole point of this command is
|
||||
* "everything else is broken, what's wrong?" — if Ink couldn't mount
|
||||
* the user has no diagnostic surface left. ANSI color codes only,
|
||||
* gracefully degrading to bare text on dumb terminals (TERM=dumb /
|
||||
* no-tty).
|
||||
*
|
||||
* Each check returns a `level` (ok / warn / fail) so the summary
|
||||
* line at the bottom counts them. `fail` is reserved for things
|
||||
* that block usage entirely (no API key, broken config); `warn`
|
||||
* is "this works but a feature is degraded" (Ollama down, no
|
||||
* project memory, large session backlog).
|
||||
*
|
||||
* No exit code on warn — exit 0. fail → exit 1, so CI / scripts can
|
||||
* fast-fail on misconfiguration.
|
||||
*/
|
||||
|
||||
import { existsSync, statSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
import { DeepSeekClient } from "../../client.js";
|
||||
import { defaultConfigPath, readConfig } from "../../config.js";
|
||||
import { loadDotenv } from "../../env.js";
|
||||
import { loadHooks } from "../../hooks.js";
|
||||
import { indexExists } from "../../index/semantic/builder.js";
|
||||
import { checkOllamaStatus } from "../../index/semantic/ollama-launcher.js";
|
||||
import { listSessions } from "../../session.js";
|
||||
import { VERSION } from "../../version.js";
|
||||
|
||||
type Level = "ok" | "warn" | "fail";
|
||||
|
||||
interface Check {
|
||||
label: string;
|
||||
level: Level;
|
||||
detail: string;
|
||||
}
|
||||
|
||||
const TTY = process.stdout.isTTY && process.env.TERM !== "dumb";
|
||||
|
||||
function color(text: string, code: string): string {
|
||||
if (!TTY) return text;
|
||||
return `\x1b[${code}m${text}\x1b[0m`;
|
||||
}
|
||||
|
||||
function badge(level: Level): string {
|
||||
if (level === "ok") return color("✓", "32");
|
||||
if (level === "warn") return color("⚠", "33");
|
||||
return color("✗", "31");
|
||||
}
|
||||
|
||||
function tail4(s: string): string {
|
||||
return s.length <= 4 ? s : `…${s.slice(-4)}`;
|
||||
}
|
||||
|
||||
function fmtBytes(n: number): string {
|
||||
if (n < 1024) return `${n} B`;
|
||||
if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
|
||||
return `${(n / 1024 / 1024).toFixed(1)} MB`;
|
||||
}
|
||||
|
||||
async function checkApiKey(): Promise<Check> {
|
||||
const fromEnv = process.env.DEEPSEEK_API_KEY;
|
||||
if (fromEnv) {
|
||||
return {
|
||||
label: "api key ",
|
||||
level: "ok",
|
||||
detail: `set via env DEEPSEEK_API_KEY (${tail4(fromEnv)})`,
|
||||
};
|
||||
}
|
||||
try {
|
||||
const cfg = readConfig();
|
||||
if (cfg.apiKey) {
|
||||
return {
|
||||
label: "api key ",
|
||||
level: "ok",
|
||||
detail: `from ${defaultConfigPath()} (${tail4(cfg.apiKey)})`,
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
/* fall through */
|
||||
}
|
||||
return {
|
||||
label: "api key ",
|
||||
level: "fail",
|
||||
detail:
|
||||
"not set — `reasonix setup` to save one, or export DEEPSEEK_API_KEY. Get a key at https://platform.deepseek.com/api_keys",
|
||||
};
|
||||
}
|
||||
|
||||
async function checkConfig(): Promise<Check> {
|
||||
const path = defaultConfigPath();
|
||||
if (!existsSync(path)) {
|
||||
return {
|
||||
label: "config ",
|
||||
level: "warn",
|
||||
detail: "missing — running with library defaults. `reasonix setup` writes one.",
|
||||
};
|
||||
}
|
||||
try {
|
||||
const cfg = readConfig(path);
|
||||
const parts: string[] = [];
|
||||
if (cfg.preset) parts.push(`preset=${cfg.preset}`);
|
||||
if (cfg.editMode) parts.push(`editMode=${cfg.editMode}`);
|
||||
if (cfg.mcp && cfg.mcp.length > 0) parts.push(`mcp=${cfg.mcp.length}`);
|
||||
return {
|
||||
label: "config ",
|
||||
level: "ok",
|
||||
detail: `${path}${parts.length ? ` (${parts.join(", ")})` : ""}`,
|
||||
};
|
||||
} catch (err) {
|
||||
return {
|
||||
label: "config ",
|
||||
level: "fail",
|
||||
detail: `${path} unreadable — ${(err as Error).message}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async function checkApiReach(): Promise<Check> {
|
||||
const key = process.env.DEEPSEEK_API_KEY ?? readConfig().apiKey;
|
||||
if (!key) {
|
||||
return {
|
||||
label: "api reach ",
|
||||
level: "warn",
|
||||
detail: "skipped — no api key to test with",
|
||||
};
|
||||
}
|
||||
try {
|
||||
const client = new DeepSeekClient({ apiKey: key });
|
||||
const ctl = new AbortController();
|
||||
const timer = setTimeout(() => ctl.abort(), 8_000);
|
||||
let balance: Awaited<ReturnType<DeepSeekClient["getBalance"]>>;
|
||||
try {
|
||||
balance = await client.getBalance({ signal: ctl.signal });
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
if (!balance) {
|
||||
return {
|
||||
label: "api reach ",
|
||||
level: "fail",
|
||||
detail: "/user/balance returned null — auth failed or network blocked",
|
||||
};
|
||||
}
|
||||
if (!balance.is_available) {
|
||||
const info = balance.balance_infos[0];
|
||||
return {
|
||||
label: "api reach ",
|
||||
level: "warn",
|
||||
detail: `account flagged not-available${info ? ` (${info.total_balance} ${info.currency})` : ""} — top up or check your dashboard`,
|
||||
};
|
||||
}
|
||||
const info = balance.balance_infos[0];
|
||||
return {
|
||||
label: "api reach ",
|
||||
level: "ok",
|
||||
detail: info
|
||||
? `/user/balance ok — ${info.total_balance} ${info.currency}`
|
||||
: "/user/balance ok",
|
||||
};
|
||||
} catch (err) {
|
||||
return {
|
||||
label: "api reach ",
|
||||
level: "fail",
|
||||
detail: `${(err as Error).message}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async function checkTokenizer(): Promise<Check> {
|
||||
// The tokenizer file is the gzipped vocab shipped under data/. We
|
||||
// resolve relative to the package's dist/ rather than process.cwd()
|
||||
// — the same logic the runtime uses when loading on first count.
|
||||
const candidates = [
|
||||
join(
|
||||
dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, "$1")),
|
||||
"..",
|
||||
"..",
|
||||
"..",
|
||||
"data",
|
||||
"deepseek-tokenizer.json.gz",
|
||||
),
|
||||
join(process.cwd(), "data", "deepseek-tokenizer.json.gz"),
|
||||
];
|
||||
for (const p of candidates) {
|
||||
if (existsSync(p)) {
|
||||
try {
|
||||
const stat = statSync(p);
|
||||
return {
|
||||
label: "tokenizer ",
|
||||
level: "ok",
|
||||
detail: `${p} (${fmtBytes(stat.size)})`,
|
||||
};
|
||||
} catch {
|
||||
/* try next */
|
||||
}
|
||||
}
|
||||
}
|
||||
return {
|
||||
label: "tokenizer ",
|
||||
level: "warn",
|
||||
detail:
|
||||
"data/deepseek-tokenizer.json.gz not found — token counts will fall back to char heuristics",
|
||||
};
|
||||
}
|
||||
|
||||
async function checkSessions(): Promise<Check> {
|
||||
try {
|
||||
const list = listSessions();
|
||||
if (list.length === 0) {
|
||||
return {
|
||||
label: "sessions ",
|
||||
level: "ok",
|
||||
detail: "0 saved",
|
||||
};
|
||||
}
|
||||
const totalBytes = list.reduce((s, e) => s + e.size, 0);
|
||||
const oldest = list[list.length - 1]!;
|
||||
const ageDays = Math.floor((Date.now() - oldest.mtime.getTime()) / (24 * 60 * 60 * 1000));
|
||||
const stale = list.filter(
|
||||
(e) => Date.now() - e.mtime.getTime() >= 90 * 24 * 60 * 60 * 1000,
|
||||
).length;
|
||||
const detail = `${list.length} saved · ${fmtBytes(totalBytes)} · oldest ${ageDays}d`;
|
||||
if (stale > 0) {
|
||||
return {
|
||||
label: "sessions ",
|
||||
level: "warn",
|
||||
detail: `${detail} · ${stale} idle ≥90d (run /prune-sessions)`,
|
||||
};
|
||||
}
|
||||
return { label: "sessions ", level: "ok", detail };
|
||||
} catch (err) {
|
||||
return {
|
||||
label: "sessions ",
|
||||
level: "warn",
|
||||
detail: `cannot list — ${(err as Error).message}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async function checkHooks(projectRoot: string): Promise<Check> {
|
||||
try {
|
||||
const all = loadHooks({ projectRoot });
|
||||
const global = all.filter((h) => h.scope === "global").length;
|
||||
const project = all.filter((h) => h.scope === "project").length;
|
||||
return {
|
||||
label: "hooks ",
|
||||
level: "ok",
|
||||
detail: `${global} global, ${project} project`,
|
||||
};
|
||||
} catch (err) {
|
||||
return {
|
||||
label: "hooks ",
|
||||
level: "warn",
|
||||
detail: `couldn't parse settings.json — ${(err as Error).message}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async function checkOllama(projectRoot: string): Promise<Check> {
|
||||
// Ollama is only meaningful when an index has been built — otherwise
|
||||
// the daemon being down is just noise. Skip the check entirely on
|
||||
// projects that don't use semantic search.
|
||||
let exists = false;
|
||||
try {
|
||||
exists = await indexExists(projectRoot);
|
||||
} catch {
|
||||
/* treat as no index */
|
||||
}
|
||||
if (!exists) {
|
||||
return {
|
||||
label: "ollama ",
|
||||
level: "ok",
|
||||
detail: "not in use (no semantic index built; `reasonix index` to enable)",
|
||||
};
|
||||
}
|
||||
try {
|
||||
const status = await checkOllamaStatus(process.env.REASONIX_EMBED_MODEL ?? "nomic-embed-text");
|
||||
if (!status.binaryFound) {
|
||||
return {
|
||||
label: "ollama ",
|
||||
level: "warn",
|
||||
detail: "binary not on PATH — semantic_search will fail; install from https://ollama.com",
|
||||
};
|
||||
}
|
||||
if (!status.daemonRunning) {
|
||||
return {
|
||||
label: "ollama ",
|
||||
level: "warn",
|
||||
detail: "daemon not running — `ollama serve` (or just call /semantic in TUI to auto-start)",
|
||||
};
|
||||
}
|
||||
if (!status.modelPulled) {
|
||||
return {
|
||||
label: "ollama ",
|
||||
level: "warn",
|
||||
detail: `model ${status.modelName} not pulled — \`ollama pull ${status.modelName}\``,
|
||||
};
|
||||
}
|
||||
return {
|
||||
label: "ollama ",
|
||||
level: "ok",
|
||||
detail: `daemon up · model ${status.modelName} ready`,
|
||||
};
|
||||
} catch (err) {
|
||||
return {
|
||||
label: "ollama ",
|
||||
level: "warn",
|
||||
detail: `probe failed — ${(err as Error).message}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async function checkProject(projectRoot: string): Promise<Check> {
|
||||
// Heuristic: a "real" project has either .git, REASONIX.md, or
|
||||
// package.json. Lacking all three, `reasonix code` still works but
|
||||
// @-mentions and the project-memory pin won't surface much.
|
||||
const markers = [".git", "REASONIX.md", "package.json", "pyproject.toml", "Cargo.toml", "go.mod"];
|
||||
const found = markers.filter((m) => existsSync(join(projectRoot, m)));
|
||||
if (found.length === 0) {
|
||||
return {
|
||||
label: "project ",
|
||||
level: "warn",
|
||||
detail: `${projectRoot} has none of: ${markers.slice(0, 3).join(", ")} … — \`reasonix code\` will still run, but @-mentions and project memory have nothing to anchor`,
|
||||
};
|
||||
}
|
||||
return {
|
||||
label: "project ",
|
||||
level: "ok",
|
||||
detail: `${projectRoot} (${found.join(", ")})`,
|
||||
};
|
||||
}
|
||||
|
||||
export async function doctorCommand(): Promise<void> {
|
||||
loadDotenv();
|
||||
|
||||
const projectRoot = resolve(process.cwd());
|
||||
console.log(`${color(`reasonix ${VERSION} · doctor`, "1")} (cwd: ${projectRoot})`);
|
||||
console.log(` home: ${homedir()}`);
|
||||
console.log("");
|
||||
|
||||
// Run independent checks in parallel — saves ~5s when api-reach has
|
||||
// to time out. Each handler swallows its own throws into a `fail`
|
||||
// result so a thrown promise can't kill the whole report.
|
||||
const checks = await Promise.all([
|
||||
checkApiKey(),
|
||||
checkConfig(),
|
||||
checkApiReach(),
|
||||
checkTokenizer(),
|
||||
checkSessions(),
|
||||
checkHooks(projectRoot),
|
||||
checkOllama(projectRoot),
|
||||
checkProject(projectRoot),
|
||||
]);
|
||||
|
||||
for (const c of checks) {
|
||||
console.log(` ${badge(c.level)} ${c.label} ${c.detail}`);
|
||||
}
|
||||
|
||||
const ok = checks.filter((c) => c.level === "ok").length;
|
||||
const warn = checks.filter((c) => c.level === "warn").length;
|
||||
const fail = checks.filter((c) => c.level === "fail").length;
|
||||
console.log("");
|
||||
const summary = `${ok} ok · ${warn} warn · ${fail} fail`;
|
||||
if (fail > 0) {
|
||||
console.log(color(summary, "31"));
|
||||
process.exit(1);
|
||||
} else if (warn > 0) {
|
||||
console.log(color(summary, "33"));
|
||||
} else {
|
||||
console.log(color(summary, "32"));
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,12 @@ export interface RunOptions {
|
||||
harvest?: boolean;
|
||||
/** Self-consistency budget. > 1 runs N parallel samples and picks the best. */
|
||||
branch?: number;
|
||||
/**
|
||||
* Soft USD spend cap. Off by default; the run aborts with a clear
|
||||
* error once cumulative cost ≥ cap so non-interactive callers
|
||||
* (CI, batched evals) have a circuit breaker.
|
||||
*/
|
||||
budgetUsd?: number;
|
||||
/** JSONL transcript path — lets `reasonix replay` / `diff` audit this run. */
|
||||
transcript?: string;
|
||||
/** Zero or more MCP server specs. Each: `"name=cmd args..."` or `"cmd args..."`. */
|
||||
@@ -127,6 +133,7 @@ export async function runCommand(opts: RunOptions): Promise<void> {
|
||||
model: opts.model,
|
||||
harvest: opts.harvest,
|
||||
branch: opts.branch,
|
||||
budgetUsd: opts.budgetUsd,
|
||||
});
|
||||
const prefixHash = prefix.fingerprint;
|
||||
|
||||
|
||||
@@ -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(" ");
|
||||
|
||||
+74
-3
@@ -6,7 +6,9 @@ import { listSessions } from "../session.js";
|
||||
import { applyMemoryStack } from "../user-memory.js";
|
||||
import { chatCommand } from "./commands/chat.js";
|
||||
import { codeCommand } from "./commands/code.js";
|
||||
import { commitCommand } from "./commands/commit.js";
|
||||
import { diffCommand } from "./commands/diff.js";
|
||||
import { doctorCommand } from "./commands/doctor.js";
|
||||
import { indexCommand } from "./commands/index.js";
|
||||
import { mcpInspectCommand } from "./commands/mcp-inspect.js";
|
||||
import { mcpListCommand } from "./commands/mcp.js";
|
||||
@@ -41,6 +43,24 @@ The signal isn't a topic list — it's: "if I'm wrong about this, is it because
|
||||
|
||||
${ESCALATION_CONTRACT}`;
|
||||
|
||||
/**
|
||||
* Validate a `--budget` flag value. Returns `undefined` (no cap) when
|
||||
* unset, NaN, or non-positive — the loop interprets `undefined` as
|
||||
* "no budget", so a malformed flag falls back to the default rather
|
||||
* than aborting the launch. The slash command uses the same lenient
|
||||
* parse so behavior matches at runtime.
|
||||
*/
|
||||
function parseBudgetFlag(raw: number | undefined): number | undefined {
|
||||
if (raw === undefined) return undefined;
|
||||
if (!Number.isFinite(raw) || raw <= 0) {
|
||||
process.stderr.write(
|
||||
`▲ ignoring --budget=${raw} (must be a positive number) — running with no cap\n`,
|
||||
);
|
||||
return undefined;
|
||||
}
|
||||
return raw;
|
||||
}
|
||||
|
||||
const program = new Command();
|
||||
program
|
||||
.name("reasonix")
|
||||
@@ -90,7 +110,7 @@ program
|
||||
program
|
||||
.command("code [dir]")
|
||||
.description(
|
||||
"Code-editing chat — filesystem tools rooted at <dir> (default: cwd), coding system prompt, v4-flash. Model proposes SEARCH/REPLACE blocks; Reasonix applies them to disk. Use /preset max or /pro to escalate to v4-pro on hard tasks.",
|
||||
"Code-editing chat — filesystem tools rooted at <dir> (default: cwd), coding system prompt, v4-flash baseline. Model proposes SEARCH/REPLACE blocks; Reasonix applies them to disk. Use /preset pro or /pro to lock v4-pro on hard tasks.",
|
||||
)
|
||||
.option("-m, --model <id>", "Override default model (v4-flash)")
|
||||
.option("--no-session", "Disable session persistence for this run")
|
||||
@@ -101,6 +121,15 @@ program
|
||||
"--harvest",
|
||||
"Opt-in Pillar-2 plan-state extraction. Adds one flash call per turn; off by default (no preset enables it).",
|
||||
)
|
||||
.option(
|
||||
"--budget <usd>",
|
||||
"Soft USD cap on session spend. Off by default. Warns at 80%, refuses next turn at 100%. Mid-session: /budget <usd> or /budget off.",
|
||||
(v) => Number.parseFloat(v),
|
||||
)
|
||||
.option(
|
||||
"--no-dashboard",
|
||||
"Suppress the auto-launched embedded web dashboard. Default behavior boots it on TUI mount and shows the URL in the status bar (clickable in OSC-8-aware terminals).",
|
||||
)
|
||||
.action(async (dir: string | undefined, opts) => {
|
||||
await codeCommand({
|
||||
dir,
|
||||
@@ -110,6 +139,8 @@ program
|
||||
forceResume: !!opts.resume,
|
||||
forceNew: !!opts.new,
|
||||
harvest: !!opts.harvest,
|
||||
budgetUsd: parseBudgetFlag(opts.budget),
|
||||
noDashboard: opts.dashboard === false,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -121,7 +152,7 @@ program
|
||||
.option("--transcript <path>", "Write a JSONL transcript to this path")
|
||||
.option(
|
||||
"--preset <name>",
|
||||
"Model + effort bundle. One of: fast (flash·high), smart (flash·max, default), max (pro·max). Overrides config.preset.",
|
||||
"Model bundle. One of: auto (flash → pro on hard turns, default), flash (always flash), pro (always pro). Overrides config.preset.",
|
||||
)
|
||||
.option(
|
||||
"--harvest",
|
||||
@@ -132,6 +163,11 @@ program
|
||||
"Self-consistency: run N parallel samples per turn (N× cost). Manual only — never auto-enabled.",
|
||||
(v) => Number.parseInt(v, 10),
|
||||
)
|
||||
.option(
|
||||
"--budget <usd>",
|
||||
"Soft USD cap on session spend. Off by default. Warns at 80%, refuses next turn at 100%. Mid-session: /budget <usd> or /budget off.",
|
||||
(v) => Number.parseFloat(v),
|
||||
)
|
||||
.option("--session <name>", "Use a named session (default: from config, usually 'default').")
|
||||
.option("--no-session", "Disable session persistence for this run (ephemeral chat)")
|
||||
.option("-r, --resume", "Skip the session picker — always continue prior messages")
|
||||
@@ -151,6 +187,10 @@ program
|
||||
"Global prefix applied to every MCP tool (only honored when no per-spec name is set; avoids collisions with a single anonymous server)",
|
||||
)
|
||||
.option("--no-config", "Ignore `~/.reasonix/config.json` — useful for CI or reproducing issues")
|
||||
.option(
|
||||
"--no-dashboard",
|
||||
"Suppress the auto-launched embedded web dashboard. Default behavior boots it on TUI mount and shows the URL in the status bar (clickable in OSC-8-aware terminals).",
|
||||
)
|
||||
.action(async (opts) => {
|
||||
const defaults = resolveDefaults({
|
||||
model: opts.model,
|
||||
@@ -179,11 +219,13 @@ program
|
||||
transcript: opts.transcript,
|
||||
harvest: defaults.harvest,
|
||||
branch: defaults.branch,
|
||||
budgetUsd: parseBudgetFlag(opts.budget),
|
||||
session: continueOpts.session,
|
||||
mcp: defaults.mcp,
|
||||
mcpPrefix: opts.mcpPrefix,
|
||||
forceResume: continueOpts.forceResume,
|
||||
forceNew: !!opts.new,
|
||||
noDashboard: opts.dashboard === false,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -192,13 +234,18 @@ program
|
||||
.description("Run a single task non-interactively, streaming output.")
|
||||
.option("-m, --model <id>", "DeepSeek model id (overrides preset)")
|
||||
.option("-s, --system <prompt>", "System prompt", DEFAULT_SYSTEM)
|
||||
.option("--preset <name>", "Bundle of model + harvest + branch: fast | smart | max")
|
||||
.option("--preset <name>", "Model bundle: auto | flash | pro (default: auto)")
|
||||
.option("--harvest", "Extract typed plan state from R1 reasoning (Pillar 2)")
|
||||
.option(
|
||||
"--branch <n>",
|
||||
"Self-consistency: run N parallel samples per turn and pick the most confident",
|
||||
(v) => Number.parseInt(v, 10),
|
||||
)
|
||||
.option(
|
||||
"--budget <usd>",
|
||||
"Soft USD cap on session spend. Off by default. Refuses to start a new turn once cumulative cost ≥ cap.",
|
||||
(v) => Number.parseFloat(v),
|
||||
)
|
||||
.option("--transcript <path>", "Write a JSONL transcript to this path for replay/diff")
|
||||
.option(
|
||||
"--mcp <spec>",
|
||||
@@ -226,6 +273,7 @@ program
|
||||
system: applyMemoryStack(opts.system, process.cwd()),
|
||||
harvest: defaults.harvest,
|
||||
branch: defaults.branch,
|
||||
budgetUsd: parseBudgetFlag(opts.budget),
|
||||
transcript: opts.transcript,
|
||||
mcp: defaults.mcp,
|
||||
mcpPrefix: opts.mcpPrefix,
|
||||
@@ -242,6 +290,29 @@ program
|
||||
statsCommand({ transcript });
|
||||
});
|
||||
|
||||
program
|
||||
.command("doctor")
|
||||
.description(
|
||||
"One-command health check — API key, config, /user/balance reachability, tokenizer, sessions, hooks, Ollama (if used), project markers. Exit 1 on any fail; 0 on warn / clean.",
|
||||
)
|
||||
.action(async () => {
|
||||
await doctorCommand();
|
||||
});
|
||||
|
||||
program
|
||||
.command("commit")
|
||||
.description(
|
||||
"Draft a commit message from the staged diff (or working tree, if nothing staged), matching your repo's recent commit style. Review interactively before it lands.",
|
||||
)
|
||||
.option("-m, --model <id>", "Override the default model (deepseek-v4-flash)")
|
||||
.option(
|
||||
"-y, --yes",
|
||||
"Skip the [a]ccept / [r]egenerate prompt and commit the first draft. Useful in scripts.",
|
||||
)
|
||||
.action(async (opts) => {
|
||||
await commitCommand({ model: opts.model, yes: !!opts.yes });
|
||||
});
|
||||
|
||||
program
|
||||
.command("sessions [name]")
|
||||
.description("List saved chat sessions, or inspect one by name.")
|
||||
|
||||
+14
-5
@@ -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 "smart" preset defaults (flash + effort=max)
|
||||
* 4. Hardcoded "auto" preset defaults (flash → pro on hard turns)
|
||||
*
|
||||
* Keeping this logic in one place — rather than duplicating across
|
||||
* `chat` and `run` — means the precedence rule only lives in one unit
|
||||
@@ -14,7 +14,7 @@
|
||||
*/
|
||||
|
||||
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;
|
||||
@@ -42,7 +42,7 @@ 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;
|
||||
@@ -66,11 +66,20 @@ function pickPreset(
|
||||
): PresetName {
|
||||
if (flagPreset && isPresetName(flagPreset)) return flagPreset;
|
||||
if (configPreset) return configPreset;
|
||||
return "smart";
|
||||
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 {
|
||||
|
||||
+1223
-125
File diff suppressed because it is too large.
Load diff
@@ -1,6 +1,7 @@
|
||||
import { Box, Text } from "ink";
|
||||
// biome-ignore lint/style/useImportType: tsconfig.jsx = "react" needs React in value scope for JSX compilation
|
||||
import React from "react";
|
||||
import { COLOR, GLYPH } from "./theme.js";
|
||||
|
||||
export interface AtMentionSuggestionsProps {
|
||||
/**
|
||||
@@ -16,11 +17,21 @@ export interface AtMentionSuggestionsProps {
|
||||
}
|
||||
|
||||
/**
|
||||
* Floating `@`-mention picker. Rendered below the input box when the
|
||||
* user is typing an `@…` prefix in code mode. Navigation state lives
|
||||
* in the parent (App.tsx owns `atSelected`) — this component is pure
|
||||
* display. Mirrors {@link SlashSuggestions} shape so the keybindings
|
||||
* and layout feel identical across the two pickers.
|
||||
* `@`-mention picker. Rendered below the input box while the user is
|
||||
* typing an `@…` prefix in code mode. Visual grammar matches the
|
||||
* design's file picker:
|
||||
*
|
||||
* @ files matching "auth" esc
|
||||
* ▸ login.ts src/auth/
|
||||
* refresh.ts src/auth/
|
||||
* validators.ts src/auth/
|
||||
* auth.test.ts tests/
|
||||
* [↑↓] navigate · Tab / ⏎ insert as @path · file content inlined
|
||||
*
|
||||
* Basename in primary cyan (the user's eye lands here first), dir
|
||||
* suffix in dim info color. No solid-bg pill on the selected row —
|
||||
* leading ▸ + bold + brighter color does the same job without the
|
||||
* loud bg block. Mirrors {@link SlashSuggestions}.
|
||||
*/
|
||||
export function AtMentionSuggestions({
|
||||
matches,
|
||||
@@ -31,11 +42,12 @@ export function AtMentionSuggestions({
|
||||
if (matches.length === 0) {
|
||||
return (
|
||||
<Box paddingX={1} marginTop={1}>
|
||||
<Text color="yellow">no files match "@{query}"</Text>
|
||||
<Text dimColor>
|
||||
{" "}
|
||||
— keep typing, or Backspace to edit. Paths resolve from the code root.
|
||||
<Text color={COLOR.warn} bold>
|
||||
{GLYPH.warn}
|
||||
</Text>
|
||||
<Text> </Text>
|
||||
<Text color={COLOR.warn}>{`no files match "@${query}"`}</Text>
|
||||
<Text dimColor>{" — keep typing or Backspace; paths resolve from the code root"}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -48,34 +60,44 @@ export function AtMentionSuggestions({
|
||||
const hiddenBelow = total - windowStart - shown.length;
|
||||
return (
|
||||
<Box flexDirection="column" paddingX={1} marginTop={1}>
|
||||
{hiddenAbove > 0 ? <Text dimColor> ↑ {hiddenAbove} more above</Text> : null}
|
||||
<Box>
|
||||
<Text color={COLOR.primary} bold>
|
||||
{"@ "}
|
||||
</Text>
|
||||
<Text dimColor>
|
||||
{query
|
||||
? `${total} match${total === 1 ? "" : "es"} for "${query}"`
|
||||
: `${total} file${total === 1 ? "" : "s"}`}
|
||||
</Text>
|
||||
{hiddenAbove > 0 ? <Text dimColor>{` ↑ ${hiddenAbove} above`}</Text> : null}
|
||||
</Box>
|
||||
{shown.map((path, i) => (
|
||||
<FileRow key={path} path={path} isSelected={windowStart + i === selectedIndex} />
|
||||
))}
|
||||
{hiddenBelow > 0 ? <Text dimColor> ↓ {hiddenBelow} more below</Text> : null}
|
||||
<Text dimColor> [↑↓] navigate · [Tab]/[Enter] pick · file content inlined on send</Text>
|
||||
{hiddenBelow > 0 ? <Text dimColor>{` ↓ ${hiddenBelow} below`}</Text> : null}
|
||||
<Box marginTop={0}>
|
||||
<Text dimColor>{" ↑↓ navigate · Tab / ⏎ insert as @path · esc cancel"}</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
function FileRow({ path, isSelected }: { path: string; isSelected: boolean }) {
|
||||
// Split the path so the basename visually pops — same dropdown
|
||||
// affordance as VS Code's Quick Open.
|
||||
// affordance as VS Code's Quick Open. Basename in primary cyan
|
||||
// (selected: bold), dir suffix in dim info color so the eye lands
|
||||
// on the filename first and uses the path only as a disambiguator.
|
||||
const slash = path.lastIndexOf("/");
|
||||
const dir = slash >= 0 ? `${path.slice(0, slash)}/` : "";
|
||||
const base = slash >= 0 ? path.slice(slash + 1) : path;
|
||||
if (isSelected) {
|
||||
return (
|
||||
<Box>
|
||||
<Text backgroundColor="#67e8f9" color="black" bold>
|
||||
{` ▸ ${base}${dir ? ` ${dir}` : ""} `}
|
||||
</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Box>
|
||||
<Text color="#94a3b8">{` ${base}`}</Text>
|
||||
<Text color={isSelected ? COLOR.primary : COLOR.info} bold={isSelected}>
|
||||
{isSelected ? `${GLYPH.cur} ` : " "}
|
||||
</Text>
|
||||
<Text color={COLOR.primary} bold={isSelected}>
|
||||
{base.padEnd(20)}
|
||||
</Text>
|
||||
{dir ? <Text dimColor>{` ${dir}`}</Text> : null}
|
||||
</Box>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,259 @@
|
||||
import { Box, Text, useStdout } from "ink";
|
||||
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React in value scope for JSX compilation
|
||||
import React from "react";
|
||||
import stringWidth from "string-width";
|
||||
import type { SessionSummary } from "../../telemetry.js";
|
||||
import { ChromeRule } from "./primitives.js";
|
||||
import { COLOR, GRADIENT } from "./theme.js";
|
||||
|
||||
const COLD_START_TURNS = 3;
|
||||
const CACHE_BAR_CELLS = 10;
|
||||
|
||||
export type Preset = "auto" | "flash" | "pro";
|
||||
|
||||
export interface ChromeBarProps {
|
||||
summary: SessionSummary;
|
||||
rootDir?: string;
|
||||
sessionName?: string | null;
|
||||
preset?: Preset;
|
||||
planMode?: boolean;
|
||||
proArmed?: boolean;
|
||||
escalated?: boolean;
|
||||
updateAvailable?: string | null;
|
||||
balance?: { currency: string; total: number } | null;
|
||||
budgetUsd?: number | null;
|
||||
/** Scroll progress: 0 = at latest, 1 = at oldest. Hides the pill at 0. */
|
||||
scrollRatio?: number;
|
||||
}
|
||||
|
||||
export function ChromeBar(props: ChromeBarProps): React.ReactElement {
|
||||
const { stdout } = useStdout();
|
||||
const cols = (stdout?.columns ?? 80) - 2; // subtract paddingX={1} on both sides
|
||||
const cold = props.summary.turns <= COLD_START_TURNS;
|
||||
const projectName = props.rootDir ? basename(props.rootDir) : null;
|
||||
const mode = pickModePill(props.planMode, props.preset);
|
||||
const proPill = props.escalated
|
||||
? { label: "⇧ pro", color: COLOR.err }
|
||||
: props.proArmed
|
||||
? { label: "⇧ pro", color: COLOR.warn }
|
||||
: null;
|
||||
|
||||
// Greedy width-aware fit. Layout (each gap is exactly ONE space — single
|
||||
// suffix on update/mode/pro/scroll, single prefix on balance/cache):
|
||||
// [brand][·project][›session]<spacer>[scroll][update][mode][pro]$cost w bal cache █▓▓▓
|
||||
// Always-shown carve out the budget first; optional pieces are dropped
|
||||
// by priority — balance > cache > session > update — until the row fits.
|
||||
// (`flexGrow` spacer can shrink to 0, so no minimum reserve.) Cache is
|
||||
// shown unconditionally now: pre-turn-4 it renders dim with a "—" so
|
||||
// it's "default on" instead of materializing only after a few turns.
|
||||
const SEP = 3; // " · " / " › "
|
||||
const GAP = 1;
|
||||
const scrollLabel =
|
||||
props.scrollRatio !== undefined && props.scrollRatio > 0
|
||||
? `[↑ ${Math.round(props.scrollRatio * 100)}%]`
|
||||
: "";
|
||||
const updateLabel = props.updateAvailable ? `↑ ${props.updateAvailable}` : "";
|
||||
const balanceLabel = props.balance ? formatBalanceLabel(props.balance) : "";
|
||||
const cachePct = Math.round(props.summary.cacheHitRatio * 100);
|
||||
// Use the worst-case rendered cache string (3-digit pct, full bar) so the
|
||||
// shed decision doesn't oscillate as the percentage changes turn-to-turn.
|
||||
const cacheLabel = `cache ${"█".repeat(CACHE_BAR_CELLS)} 100%`;
|
||||
const costLabel = `$${props.summary.totalCostUsd.toFixed(4)}${
|
||||
props.budgetUsd && props.budgetUsd > 0 ? ` / $${props.budgetUsd.toFixed(2)}` : ""
|
||||
}`;
|
||||
|
||||
const brandW = stringWidth("◈ reasonix");
|
||||
const projectW = projectName ? SEP + stringWidth(projectName) : 0;
|
||||
const fixedLeft = brandW + projectW;
|
||||
const scrollW = scrollLabel ? stringWidth(scrollLabel) + GAP : 0;
|
||||
const modeW = mode ? stringWidth(`[${mode.label}]`) + GAP : 0;
|
||||
const proW = proPill ? stringWidth(`[${proPill.label}]`) + GAP : 0;
|
||||
const costW = stringWidth(costLabel);
|
||||
const fixedRight = scrollW + modeW + proW + costW;
|
||||
let budget = cols - fixedLeft - fixedRight;
|
||||
|
||||
const balanceOptW = balanceLabel ? GAP + stringWidth(balanceLabel) : 0;
|
||||
const cacheOptW = GAP + stringWidth(cacheLabel);
|
||||
const sessionOptW = props.sessionName ? SEP + stringWidth(props.sessionName) : 0;
|
||||
const updateOptW = updateLabel ? stringWidth(updateLabel) + GAP : 0;
|
||||
|
||||
const showBalance = balanceOptW > 0 && budget >= balanceOptW;
|
||||
if (showBalance) budget -= balanceOptW;
|
||||
const showCache = budget >= cacheOptW;
|
||||
if (showCache) budget -= cacheOptW;
|
||||
const showSession = sessionOptW > 0 && budget >= sessionOptW;
|
||||
if (showSession) budget -= sessionOptW;
|
||||
const showUpdate = updateOptW > 0 && budget >= updateOptW;
|
||||
if (showUpdate) budget -= updateOptW;
|
||||
|
||||
return (
|
||||
<Box flexDirection="column" paddingX={1}>
|
||||
<Box>
|
||||
<Text bold color={GRADIENT[0]}>
|
||||
{"◈ "}
|
||||
</Text>
|
||||
<Text color={COLOR.brand} bold>
|
||||
reasonix
|
||||
</Text>
|
||||
{projectName ? (
|
||||
<>
|
||||
<Text color={COLOR.info} dimColor>
|
||||
{" · "}
|
||||
</Text>
|
||||
<Text>{projectName}</Text>
|
||||
{showSession && props.sessionName ? (
|
||||
<>
|
||||
<Text color={COLOR.info} dimColor>
|
||||
{" › "}
|
||||
</Text>
|
||||
<Text color={COLOR.info}>{props.sessionName}</Text>
|
||||
</>
|
||||
) : null}
|
||||
</>
|
||||
) : null}
|
||||
|
||||
<Box flexGrow={1} />
|
||||
|
||||
{scrollLabel ? (
|
||||
<>
|
||||
<Text color={COLOR.accent} bold>
|
||||
{scrollLabel}
|
||||
</Text>
|
||||
<Text> </Text>
|
||||
</>
|
||||
) : null}
|
||||
{showUpdate ? (
|
||||
<>
|
||||
<Text color={COLOR.warn} bold>
|
||||
{updateLabel}
|
||||
</Text>
|
||||
<Text> </Text>
|
||||
</>
|
||||
) : null}
|
||||
{mode ? (
|
||||
<>
|
||||
<Text color={mode.color} bold>
|
||||
{`[${mode.label}]`}
|
||||
</Text>
|
||||
<Text> </Text>
|
||||
</>
|
||||
) : null}
|
||||
{proPill ? (
|
||||
<>
|
||||
<Text color={proPill.color} bold>
|
||||
{`[${proPill.label}]`}
|
||||
</Text>
|
||||
<Text> </Text>
|
||||
</>
|
||||
) : null}
|
||||
<CostPill summary={props.summary} cold={cold} budgetUsd={props.budgetUsd} />
|
||||
{showBalance && props.balance ? (
|
||||
<>
|
||||
<Text> </Text>
|
||||
<BalancePill balance={props.balance} />
|
||||
</>
|
||||
) : null}
|
||||
{showCache ? (
|
||||
<>
|
||||
<Text> </Text>
|
||||
<CachePill ratio={props.summary.cacheHitRatio} cold={cold} pct={cachePct} />
|
||||
</>
|
||||
) : null}
|
||||
</Box>
|
||||
<ChromeRule />
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
function formatBalanceLabel(balance: { currency: string; total: number }): string {
|
||||
const sym = balance.currency === "USD" ? "$" : balance.currency === "CNY" ? "¥" : "";
|
||||
const suf = sym ? "" : ` ${balance.currency}`;
|
||||
return `w ${sym}${balance.total.toFixed(2)}${suf}`;
|
||||
}
|
||||
|
||||
function CostPill({
|
||||
summary,
|
||||
cold,
|
||||
budgetUsd,
|
||||
}: {
|
||||
summary: SessionSummary;
|
||||
cold: boolean;
|
||||
budgetUsd?: number | null;
|
||||
}): React.ReactElement {
|
||||
const cost = summary.totalCostUsd;
|
||||
const color = cold ? COLOR.info : sessionCostColor(cost);
|
||||
return (
|
||||
<>
|
||||
<Text color={color} bold={!cold} dimColor={cold}>
|
||||
{`$${cost.toFixed(4)}`}
|
||||
</Text>
|
||||
{budgetUsd && budgetUsd > 0 ? (
|
||||
<Text color={COLOR.info} dimColor>
|
||||
{` / $${budgetUsd.toFixed(2)}`}
|
||||
</Text>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function BalancePill({
|
||||
balance,
|
||||
}: {
|
||||
balance: { currency: string; total: number };
|
||||
}): React.ReactElement {
|
||||
const { total } = balance;
|
||||
const color = total < 1 ? COLOR.err : total < 5 ? COLOR.warn : COLOR.ok;
|
||||
return <Text color={color}>{formatBalanceLabel(balance)}</Text>;
|
||||
}
|
||||
|
||||
function CachePill({
|
||||
ratio,
|
||||
cold,
|
||||
pct,
|
||||
}: {
|
||||
ratio: number;
|
||||
cold: boolean;
|
||||
pct: number;
|
||||
}): React.ReactElement {
|
||||
const color = ratio >= 0.7 ? COLOR.ok : ratio >= 0.4 ? COLOR.warn : COLOR.err;
|
||||
const filled = Math.max(0, Math.min(CACHE_BAR_CELLS, Math.round(ratio * CACHE_BAR_CELLS)));
|
||||
const empty = CACHE_BAR_CELLS - filled;
|
||||
return (
|
||||
<>
|
||||
<Text color={COLOR.info} dimColor>
|
||||
{"cache "}
|
||||
</Text>
|
||||
<Text color={cold ? COLOR.info : color} dimColor={cold}>
|
||||
{"█".repeat(filled)}
|
||||
</Text>
|
||||
<Text dimColor>{"░".repeat(empty)}</Text>
|
||||
<Text color={cold ? undefined : color} bold={!cold} dimColor={cold}>
|
||||
{cold && pct === 0 ? " —" : ` ${pct}%`}
|
||||
</Text>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function pickModePill(
|
||||
planMode: boolean | undefined,
|
||||
preset: Preset | undefined,
|
||||
): { label: string; color: string } | null {
|
||||
if (planMode) return { label: "PLAN", color: COLOR.err };
|
||||
if (!preset) return null;
|
||||
if (preset === "pro") return { label: "pro", color: COLOR.accent };
|
||||
if (preset === "flash") return { label: "flash", color: COLOR.info };
|
||||
return { label: "auto", color: COLOR.primary };
|
||||
}
|
||||
|
||||
function sessionCostColor(cost: number): string | undefined {
|
||||
if (cost <= 0) return undefined;
|
||||
if (cost >= 5) return COLOR.err;
|
||||
if (cost >= 0.5) return COLOR.warn;
|
||||
return COLOR.ok;
|
||||
}
|
||||
|
||||
function basename(path: string): string {
|
||||
const norm = path.replace(/\\/g, "/");
|
||||
const i = norm.lastIndexOf("/");
|
||||
return i === -1 ? norm : norm.slice(i + 1);
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import { Box, Text, useStdout } from "ink";
|
||||
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React in value scope for JSX compilation
|
||||
import React, { useMemo } from "react";
|
||||
import stringWidth from "string-width";
|
||||
import type { CacheFirstLoop } from "../../loop.js";
|
||||
import type { SessionSummary } from "../../telemetry.js";
|
||||
import { computeCtxBreakdown } from "./ctx-breakdown.js";
|
||||
import { Bar, ChromeRule, formatTokens } from "./primitives.js";
|
||||
import { COLOR } from "./theme.js";
|
||||
|
||||
interface CtxFooterProps {
|
||||
loop: CacheFirstLoop;
|
||||
summary: SessionSummary;
|
||||
}
|
||||
|
||||
const BAR_CELLS = 14;
|
||||
|
||||
export function CtxFooter({ loop, summary }: CtxFooterProps): React.ReactElement {
|
||||
// Memoize on turn boundary. `summary.turns` is a freshness key — its
|
||||
// change forces recomputation when the loop's log appends a new turn.
|
||||
// biome-ignore lint/correctness/useExhaustiveDependencies: summary.turns is a freshness key, not a value used in the body
|
||||
const data = useMemo(() => computeCtxBreakdown(loop), [loop, summary.turns]);
|
||||
const { stdout } = useStdout();
|
||||
const cols = (stdout?.columns ?? 80) - 2;
|
||||
|
||||
const total = data.systemTokens + data.toolsTokens + data.logTokens + data.inputTokens;
|
||||
const ratio = data.ctxMax > 0 ? Math.min(1, total / data.ctxMax) : 0;
|
||||
const pct = Math.round(ratio * 100);
|
||||
const severity = pct >= 80 ? COLOR.err : pct >= 60 ? COLOR.warn : COLOR.ok;
|
||||
|
||||
// Always-shown core: label + bar + total + pct + (compact warn when severe)
|
||||
const labelStr = " ctx ";
|
||||
const totalStr = `${formatTokens(total)}/${formatTokens(data.ctxMax)}`;
|
||||
const pctStr = ` · ${pct}%`;
|
||||
const warnStr = pct >= 80 ? " · /compact" : "";
|
||||
const fixedW =
|
||||
stringWidth(labelStr) +
|
||||
BAR_CELLS +
|
||||
1 + // space after bar
|
||||
stringWidth(totalStr) +
|
||||
stringWidth(pctStr) +
|
||||
stringWidth(warnStr);
|
||||
|
||||
// Optional breakdown segments. Greedy fit by priority (drop first → drop last):
|
||||
// input → log → tools → sys. Sys comes off the line LAST because it's
|
||||
// the most stable number; users learn its size and read other segments
|
||||
// relative to it.
|
||||
let budget = cols - fixedW;
|
||||
const sysSeg = ` · sys ${formatTokens(data.systemTokens)}`;
|
||||
const toolsSeg = ` · tools ${formatTokens(data.toolsTokens)}`;
|
||||
const logSeg = ` · log ${formatTokens(data.logTokens)}`;
|
||||
const inputSeg = data.inputTokens > 0 ? ` · input ${formatTokens(data.inputTokens)}` : "";
|
||||
|
||||
const showSys = budget >= stringWidth(sysSeg);
|
||||
if (showSys) budget -= stringWidth(sysSeg);
|
||||
const showTools = budget >= stringWidth(toolsSeg);
|
||||
if (showTools) budget -= stringWidth(toolsSeg);
|
||||
const showLog = budget >= stringWidth(logSeg);
|
||||
if (showLog) budget -= stringWidth(logSeg);
|
||||
const showInput = inputSeg !== "" && budget >= stringWidth(inputSeg);
|
||||
if (showInput) budget -= stringWidth(inputSeg);
|
||||
|
||||
return (
|
||||
<Box flexDirection="column" paddingX={1}>
|
||||
<ChromeRule />
|
||||
<Text>
|
||||
<Text color={COLOR.info} dimColor>
|
||||
{labelStr}
|
||||
</Text>
|
||||
<Bar ratio={ratio} color={severity} cells={BAR_CELLS} />
|
||||
<Text> </Text>
|
||||
<Text color={severity} bold>
|
||||
{totalStr}
|
||||
</Text>
|
||||
<Text dimColor>{pctStr}</Text>
|
||||
{showSys ? <Text dimColor>{sysSeg}</Text> : null}
|
||||
{showTools ? <Text dimColor>{toolsSeg}</Text> : null}
|
||||
{showLog ? <Text dimColor>{logSeg}</Text> : null}
|
||||
{showInput ? <Text dimColor>{inputSeg}</Text> : null}
|
||||
{warnStr ? (
|
||||
<Text color={COLOR.err} bold>
|
||||
{warnStr}
|
||||
</Text>
|
||||
) : null}
|
||||
</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
+51
-58
@@ -1,8 +1,9 @@
|
||||
import { Box, Text, useStdout } from "ink";
|
||||
import React, { useMemo, useState } from "react";
|
||||
import { formatEditBlockDiff } from "../../code/diff-preview.js";
|
||||
import { formatEditBlockSplit } from "../../code/diff-preview.js";
|
||||
import type { EditBlock } from "../../code/edit-blocks.js";
|
||||
import { ModalCard } from "./ModalCard.js";
|
||||
import { SplitDiff } from "./SplitDiff.js";
|
||||
import { useKeystroke } from "./keystroke-context.js";
|
||||
|
||||
/**
|
||||
@@ -61,16 +62,16 @@ export function EditConfirm({ block, onChoose }: EditConfirmProps) {
|
||||
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: " " }),
|
||||
// Side-by-side rows — maxLines pushed high so the split renderer
|
||||
// never inserts its own truncation marker; we slice + scroll here.
|
||||
// contextLines: 2 keeps the trim tight on each end.
|
||||
const allRows = useMemo(
|
||||
() => formatEditBlockSplit(block, { contextLines: 2, maxLines: 100_000 }),
|
||||
[block],
|
||||
);
|
||||
|
||||
const [scroll, setScroll] = useState(0);
|
||||
const maxScroll = Math.max(0, allLines.length - budget);
|
||||
const maxScroll = Math.max(0, allRows.length - budget);
|
||||
// Clamp scroll if budget shrinks (terminal resized) after a previous
|
||||
// keypress drove the offset past the new ceiling.
|
||||
const effectiveScroll = Math.min(scroll, maxScroll);
|
||||
@@ -132,83 +133,75 @@ export function EditConfirm({ block, onChoose }: EditConfirmProps) {
|
||||
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 visibleRows = allRows.slice(effectiveScroll, effectiveScroll + budget);
|
||||
const hiddenAbove = effectiveScroll;
|
||||
const hiddenBelow = Math.max(0, allLines.length - effectiveScroll - budget);
|
||||
const totalLines = allLines.length;
|
||||
const hiddenBelow = Math.max(0, allRows.length - effectiveScroll - budget);
|
||||
const totalLines = allRows.length;
|
||||
const showScrollHud = hiddenAbove + hiddenBelow > 0;
|
||||
|
||||
const subtitleParts = [`-${removed} +${added} lines`];
|
||||
if (showScrollHud) {
|
||||
subtitleParts.push(
|
||||
`viewing ${effectiveScroll + 1}-${effectiveScroll + visibleLines.length}/${totalLines}`,
|
||||
`viewing ${effectiveScroll + 1}-${effectiveScroll + visibleRows.length}/${totalLines}`,
|
||||
);
|
||||
}
|
||||
const footer = (
|
||||
<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>
|
||||
);
|
||||
|
||||
return (
|
||||
<ModalCard
|
||||
accent={isNew ? "#86efac" : "#fcd34d"}
|
||||
icon={isNew ? "✚" : "✎"}
|
||||
title={`${tag} ${block.path}`}
|
||||
subtitle={subtitleParts.join(" · ")}
|
||||
footer={footer}
|
||||
>
|
||||
{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>
|
||||
);
|
||||
})}
|
||||
<SplitDiff rows={visibleRows} />
|
||||
<Box>
|
||||
<Text color="#fbc8c8" backgroundColor="#2a1212">
|
||||
{" - old "}
|
||||
</Text>
|
||||
<Text>{" "}</Text>
|
||||
<Text color="#bef0c8" backgroundColor="#0c2718">
|
||||
{" + new "}
|
||||
</Text>
|
||||
<Text dimColor>
|
||||
{" side-by-side · removed lines on the left, added on the right · paired by offset"}
|
||||
</Text>
|
||||
</Box>
|
||||
{hiddenBelow > 0 ? (
|
||||
<Text
|
||||
dimColor
|
||||
>{` ↓ ${hiddenBelow} line${hiddenBelow === 1 ? "" : "s"} below (↓/j or Space/PgDn)`}</Text>
|
||||
) : null}
|
||||
<Box marginTop={1}>
|
||||
<Text dimColor>
|
||||
{"["}
|
||||
<Text color="#67e8f9" bold>
|
||||
y
|
||||
</Text>
|
||||
{"/Enter] apply · ["}
|
||||
<Text color="#67e8f9" bold>
|
||||
n
|
||||
</Text>
|
||||
{"] reject · ["}
|
||||
<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>
|
||||
);
|
||||
}
|
||||
+198
-138
@@ -6,8 +6,10 @@ import type { TurnStats } from "../../telemetry.js";
|
||||
import type { PlanStep } from "../../tools/plan.js";
|
||||
import { PlanStateBlock } from "./PlanStateBlock.js";
|
||||
import { PlanStepList } from "./PlanStepList.js";
|
||||
import { CtxBreakdownBlock, type CtxBreakdownData } from "./ctx-breakdown.js";
|
||||
import { Markdown } from "./markdown.js";
|
||||
import { COLOR, gradientCells } from "./theme.js";
|
||||
import { formatTokens } from "./primitives.js";
|
||||
import { COLOR, GLYPH, gradientCells } from "./theme.js";
|
||||
import { useElapsedSeconds, useTick } from "./ticker.js";
|
||||
import { formatDuration, summarizeToolResult } from "./tool-summary.js";
|
||||
|
||||
@@ -46,7 +48,15 @@ export type DisplayRole =
|
||||
* dim border + ⏪ icon — so the user immediately sees this is
|
||||
* historical, not the active plan.
|
||||
*/
|
||||
| "plan-replay";
|
||||
| "plan-replay"
|
||||
/**
|
||||
* Token-usage breakdown rendered by the `/context` slash. Carries
|
||||
* a structured `ctxBreakdown` payload so EventLog can render the
|
||||
* stacked colored char-bar with proper Box+Text layout — slash
|
||||
* info text can't carry per-segment color, so /context pushes this
|
||||
* specialized event role instead of plain "info".
|
||||
*/
|
||||
| "ctx-breakdown";
|
||||
|
||||
export interface DisplayEvent {
|
||||
id: string;
|
||||
@@ -57,6 +67,14 @@ 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
|
||||
@@ -117,6 +135,11 @@ export interface DisplayEvent {
|
||||
* this off; App.tsx sets it based on whether history is empty.
|
||||
*/
|
||||
leadSeparator?: boolean;
|
||||
/**
|
||||
* Populated on `ctx-breakdown` rows. Token counts per category +
|
||||
* the context window cap; rendered via `<CtxBreakdownBlock>`.
|
||||
*/
|
||||
ctxBreakdown?: CtxBreakdownData;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -151,18 +174,24 @@ 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.
|
||||
* Tool name + status indicator. Bracket-text style (not solid-bg pill)
|
||||
* because tool calls cluster — a turn with 6 reads + 2 edits + a grep
|
||||
* would mean 9 high-contrast color blocks fighting for attention.
|
||||
* Bracket text + colored glyph + colored name gives the eye a clear
|
||||
* landmark per row without making every row shout.
|
||||
*
|
||||
* ▣ read_file → ok
|
||||
* ▥ run_command → err (rose)
|
||||
*
|
||||
* Visual grammar matches the design doc: status icon first, name in
|
||||
* the matching color, no padded-bg block.
|
||||
*/
|
||||
function ToolPill({ label, status }: { label: string; status: "ok" | "err" }) {
|
||||
const bg = status === "err" ? "red" : "yellow";
|
||||
const symbol = status === "err" ? "✗" : "✓";
|
||||
const color = status === "err" ? COLOR.toolErr : COLOR.tool;
|
||||
const symbol = status === "err" ? GLYPH.toolErr : GLYPH.toolOk;
|
||||
return (
|
||||
<Text backgroundColor={bg} color="black" bold>
|
||||
{` ${symbol} ${label} `}
|
||||
<Text color={color} bold>
|
||||
{`${symbol} ${label}`}
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
@@ -240,7 +269,7 @@ export const EventRow = React.memo(function EventRow({
|
||||
{event.text ? (
|
||||
<Markdown text={event.text} projectRoot={projectRoot} />
|
||||
) : (
|
||||
<Text dimColor>(no content)</Text>
|
||||
<Text dimColor>(empty body — likely tool-call only)</Text>
|
||||
)}
|
||||
{event.stats ? <StatsLine stats={event.stats} /> : null}
|
||||
{event.repair ? <Text color={COLOR.accent}>{event.repair}</Text> : null}
|
||||
@@ -279,10 +308,11 @@ export const EventRow = React.memo(function EventRow({
|
||||
</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.
|
||||
// Compact one-line render for everything else. Wrapped in a
|
||||
// yellow-left-bar Box so it shares the same "card column" visual
|
||||
// language as user/assistant turns — the eye reads the conversation
|
||||
// log as one continuous column with role-coded accents, not as a
|
||||
// mix of bordered turns and disconnected naked rows.
|
||||
const summary = summarizeToolResult(event.toolName ?? "?", event.text);
|
||||
const status: "ok" | "err" = summary.isError ? "err" : "ok";
|
||||
const durationLabel =
|
||||
@@ -291,7 +321,14 @@ export const EventRow = React.memo(function EventRow({
|
||||
: "";
|
||||
const indexHint = event.toolIndex !== undefined ? ` /tool ${event.toolIndex}` : "";
|
||||
return (
|
||||
<Box>
|
||||
<Box
|
||||
borderStyle="single"
|
||||
borderTop={false}
|
||||
borderRight={false}
|
||||
borderBottom={false}
|
||||
borderColor={status === "err" ? COLOR.toolErr : COLOR.tool}
|
||||
paddingLeft={1}
|
||||
>
|
||||
<ToolPill label={event.toolName ?? "?"} status={status} />
|
||||
{durationLabel ? <Text dimColor>{` ${durationLabel}`}</Text> : null}
|
||||
<Text dimColor>{" "}</Text>
|
||||
@@ -304,12 +341,20 @@ export const EventRow = React.memo(function EventRow({
|
||||
}
|
||||
if (event.role === "error") {
|
||||
return (
|
||||
<Box marginTop={1}>
|
||||
<Text backgroundColor="#f87171" color="black" bold>
|
||||
{" ✦ ERROR "}
|
||||
<Box
|
||||
marginTop={1}
|
||||
borderStyle="single"
|
||||
borderTop={false}
|
||||
borderRight={false}
|
||||
borderBottom={false}
|
||||
borderColor={COLOR.err}
|
||||
paddingLeft={1}
|
||||
>
|
||||
<Text color={COLOR.err} bold>
|
||||
✦ error
|
||||
</Text>
|
||||
<Text>{" "}</Text>
|
||||
<Text color="#f87171">{indentContinuationLines(event.text)}</Text>
|
||||
<Text color={COLOR.err}>{indentContinuationLines(event.text)}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -326,8 +371,18 @@ export const EventRow = React.memo(function EventRow({
|
||||
else if (lead === "✓") leadColor = COLOR.ok;
|
||||
else if (lead === "✗" || lead === "✖") leadColor = COLOR.err;
|
||||
else if (lead === "↻") leadColor = COLOR.primary;
|
||||
// Same conversation-column visual: left bar in the lead's color,
|
||||
// glyph + body indented under it. Without the bar, info rows looked
|
||||
// like floating debug text rather than a coherent log entry.
|
||||
return (
|
||||
<Box>
|
||||
<Box
|
||||
borderStyle="single"
|
||||
borderTop={false}
|
||||
borderRight={false}
|
||||
borderBottom={false}
|
||||
borderColor={leadColor}
|
||||
paddingLeft={1}
|
||||
>
|
||||
<Text color={leadColor} bold>
|
||||
{lead}
|
||||
</Text>
|
||||
@@ -474,15 +529,25 @@ export const EventRow = React.memo(function EventRow({
|
||||
}
|
||||
if (event.role === "warning") {
|
||||
return (
|
||||
<Box>
|
||||
<Text backgroundColor="#fbbf24" color="black" bold>
|
||||
{" ▲ WARN "}
|
||||
<Box
|
||||
borderStyle="single"
|
||||
borderTop={false}
|
||||
borderRight={false}
|
||||
borderBottom={false}
|
||||
borderColor={COLOR.warn}
|
||||
paddingLeft={1}
|
||||
>
|
||||
<Text color={COLOR.warn} bold>
|
||||
▲ warn
|
||||
</Text>
|
||||
<Text>{" "}</Text>
|
||||
<Text color="#fbbf24">{indentContinuationLines(event.text)}</Text>
|
||||
<Text color={COLOR.warn}>{indentContinuationLines(event.text)}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
if (event.role === "ctx-breakdown" && event.ctxBreakdown) {
|
||||
return <CtxBreakdownBlock data={event.ctxBreakdown} />;
|
||||
}
|
||||
return (
|
||||
<Box>
|
||||
<Text>{event.text}</Text>
|
||||
@@ -642,15 +707,39 @@ 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)}`;
|
||||
// Approximate tokens for the meta line — R1 reasoning_content runs
|
||||
// 4-6 chars/token in English, which is what /think also uses for
|
||||
// its summary header. Rough is fine; the user reads "ballpark size"
|
||||
// not "exact bill".
|
||||
const tokensApprox = Math.max(1, Math.round(flat.length / 4.5));
|
||||
const tokLabel =
|
||||
tokensApprox >= 1000 ? `${(tokensApprox / 1000).toFixed(1)}k` : `${tokensApprox}`;
|
||||
// Layout (matches design/tui-redesign-ink.html R1 reasoning state):
|
||||
// R1 ↯ reasoning · ~Nk tok
|
||||
// │ <preview text — dim violet italic, left-bordered>
|
||||
// The left border is a Box `borderStyle="single" borderLeft` colored
|
||||
// violet — same idiom user/assistant turns use, just dimmer to mark
|
||||
// this as supplementary thought rather than primary content.
|
||||
return (
|
||||
<Box marginBottom={1}>
|
||||
<Text backgroundColor={COLOR.accent} color="black" bold>
|
||||
{" ⋯ thinking "}
|
||||
</Text>
|
||||
<Text> </Text>
|
||||
<Text color={COLOR.accent} italic dimColor>
|
||||
{preview}
|
||||
</Text>
|
||||
<Box flexDirection="column" marginBottom={1}>
|
||||
<Box>
|
||||
<Text color={COLOR.accent} bold>
|
||||
R1 ↯
|
||||
</Text>
|
||||
<Text dimColor>{` reasoning · ~${tokLabel} tok · /think for full`}</Text>
|
||||
</Box>
|
||||
<Box
|
||||
borderStyle="single"
|
||||
borderTop={false}
|
||||
borderRight={false}
|
||||
borderBottom={false}
|
||||
borderColor={COLOR.accent}
|
||||
paddingLeft={1}
|
||||
>
|
||||
<Text color={COLOR.accent} italic dimColor>
|
||||
{preview}
|
||||
</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -668,17 +757,16 @@ function Elapsed() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Animated role glyph for the actively-streaming assistant. Alternates
|
||||
* ◆ ↔ ◇ every ~480ms so the user can see the model is alive even
|
||||
* during R1's long pre-first-byte silence. Settles back to a static
|
||||
* ◆ once the turn ends (StreamingAssistant is unmounted).
|
||||
* Role glyph for the actively-streaming assistant. The braille
|
||||
* spinner sitting next to it (`Pulse`) already conveys "alive" — a
|
||||
* second animated indicator on the same row was visually noisy AND
|
||||
* doubled the fast-tick subscriber count for the streaming row. The
|
||||
* glyph stays static; the spinner does the liveness signaling.
|
||||
*/
|
||||
function PulsingAssistantGlyph() {
|
||||
const tick = useTick();
|
||||
const on = Math.floor(tick / 4) % 2 === 0;
|
||||
return (
|
||||
<Text color="green" bold>
|
||||
{on ? ROLE_GLYPH.assistant : ROLE_GLYPH.assistantPulse}
|
||||
{ROLE_GLYPH.assistant}
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
@@ -732,117 +820,95 @@ function StreamingAssistant({ event }: { event: DisplayEvent }) {
|
||||
);
|
||||
}
|
||||
|
||||
const tail = lastLine(event.text, 140);
|
||||
const reasoningTail = event.reasoning ? lastLine(event.reasoning, 120) : "";
|
||||
const toolCallBuild = event.toolCallBuild;
|
||||
// Four distinct phases a turn can be in — label them plainly so
|
||||
// the user doesn't have to decode "streaming · 391 + think 4506
|
||||
// chars" to figure out what's happening:
|
||||
// pre-first-byte: request in flight, no bytes back yet
|
||||
// reasoning-only: R1 thinking, no visible content yet
|
||||
// tool-call-only: tool_call arguments streaming, no content/reasoning bytes
|
||||
// writing: content streaming (R1 has already produced its thought)
|
||||
// both: rare — content present AND reasoning still growing
|
||||
// We can't cheaply distinguish "reasoning still growing" from
|
||||
// "reasoning finished but we already saw it", so when content is
|
||||
// present we just say "writing response" and surface both counts.
|
||||
const preFirstByte = !event.text && !event.reasoning && !toolCallBuild;
|
||||
const reasoningOnly = !event.text && !!event.reasoning && !toolCallBuild;
|
||||
const toolCallOnly = !event.text && !event.reasoning && !!toolCallBuild;
|
||||
// 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;
|
||||
const text = event.text;
|
||||
const reasoning = event.reasoning;
|
||||
const preFirstByte = !text && !reasoning && !toolCallBuild;
|
||||
const reasoningOnly = !text && !!reasoning && !toolCallBuild;
|
||||
const toolCallOnly = !text && !reasoning && !!toolCallBuild;
|
||||
|
||||
let phaseVerb: string | null = null;
|
||||
let phaseColor: string = COLOR.assistant;
|
||||
if (preFirstByte) {
|
||||
pillBg = "#fbbf24"; // amber
|
||||
pillText = "WAITING";
|
||||
label = "request sent · waiting for server";
|
||||
phaseVerb = "waiting";
|
||||
phaseColor = COLOR.warn;
|
||||
} else if (reasoningOnly) {
|
||||
pillBg = "#c4b5fd"; // violet
|
||||
pillText = "THINKING";
|
||||
label = `${event.reasoning?.length ?? 0} chars of thought`;
|
||||
phaseVerb = "thinking";
|
||||
phaseColor = COLOR.accent;
|
||||
} else if (toolCallOnly) {
|
||||
pillBg = "#f0abfc"; // fuchsia
|
||||
pillText = "DISPATCH";
|
||||
label = `assembling${formatToolCallIndex(toolCallBuild)} <${toolCallBuild.name}> · ${toolCallBuild.chars} chars${formatReadyTail(toolCallBuild)}`;
|
||||
} else {
|
||||
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(
|
||||
`tool${formatToolCallIndex(toolCallBuild)} <${toolCallBuild.name}> ${toolCallBuild.chars}c${formatReadyTail(toolCallBuild)}`,
|
||||
);
|
||||
}
|
||||
label = parts.join(" · ");
|
||||
phaseVerb = `dispatching ${toolCallBuild.name}`;
|
||||
phaseColor = COLOR.accent;
|
||||
}
|
||||
|
||||
const verb = phaseVerb ?? "responding";
|
||||
const verbColor = phaseVerb ? phaseColor : COLOR.info;
|
||||
return (
|
||||
<Box flexDirection="column" marginTop={1}>
|
||||
<Box>
|
||||
<PulsingAssistantGlyph />
|
||||
<Text>{" "}</Text>
|
||||
<Pulse />
|
||||
<Text> </Text>
|
||||
<Text backgroundColor={pillBg} color="black" bold>
|
||||
{` ${pillText} `}
|
||||
<Text color={verbColor} dimColor={!phaseVerb}>
|
||||
{verb}
|
||||
</Text>
|
||||
<Text dimColor>{` ${label} `}</Text>
|
||||
<Text> </Text>
|
||||
<Marquee />
|
||||
<Text> </Text>
|
||||
<Elapsed />
|
||||
</Box>
|
||||
{reasoningTail ? (
|
||||
<Box paddingLeft={3}>
|
||||
<Text color="#c4b5fd" italic dimColor>
|
||||
↳ {reasoningTail}
|
||||
<Box
|
||||
marginTop={1}
|
||||
borderStyle="single"
|
||||
borderTop={false}
|
||||
borderRight={false}
|
||||
borderBottom={false}
|
||||
borderColor={COLOR.assistant}
|
||||
paddingLeft={1}
|
||||
flexDirection="column"
|
||||
>
|
||||
{reasoning ? <ReasoningBlock reasoning={reasoning} /> : null}
|
||||
{text ? (
|
||||
<Text>
|
||||
{text}
|
||||
<BlinkingCursor />
|
||||
</Text>
|
||||
</Box>
|
||||
) : null}
|
||||
{tail ? (
|
||||
<Box paddingLeft={3}>
|
||||
<Text dimColor>▸ {tail}</Text>
|
||||
</Box>
|
||||
) : preFirstByte ? (
|
||||
// Non-dim amber: first-time users misread the dim version as
|
||||
// "app frozen". The reassurance has to be VISIBLE to do its job.
|
||||
<Box paddingLeft={3}>
|
||||
<Text color="#fbbf24" italic>
|
||||
{"waiting for first byte — typical 5–60s depending on model + load"}
|
||||
) : (
|
||||
<Text dimColor>
|
||||
{preFirstByte
|
||||
? "waiting for first byte — 5-60s typical"
|
||||
: reasoningOnly
|
||||
? `R1 thinking · ~${Math.round((reasoning?.length ?? 0) / 4)} tok so far`
|
||||
: toolCallOnly
|
||||
? `assembling ${toolCallBuild.name}${formatToolCallIndex(toolCallBuild)} · ${toolCallBuild.chars} chars${formatReadyTail(toolCallBuild)}`
|
||||
: ""}
|
||||
<Text> </Text>
|
||||
<BlinkingCursor />
|
||||
</Text>
|
||||
</Box>
|
||||
) : reasoningOnly ? (
|
||||
<Box paddingLeft={3}>
|
||||
<Text color="#c4b5fd" italic>
|
||||
{"R1 thinks before it speaks — body text arrives when reasoning finishes (20–90s)"}
|
||||
</Text>
|
||||
</Box>
|
||||
) : toolCallOnly ? (
|
||||
<Box paddingLeft={3}>
|
||||
<Text color="#f0abfc" italic>
|
||||
{"tool-call arguments streaming — about to dispatch"}
|
||||
</Text>
|
||||
</Box>
|
||||
) : event.reasoning ? (
|
||||
<Box paddingLeft={3}>
|
||||
<Text color="#fbbf24" italic>
|
||||
{"R1 still reasoning — body text or tool call arrives when thinking finishes"}
|
||||
</Text>
|
||||
</Box>
|
||||
) : null}
|
||||
)}
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Blinking indicator so the user can tell the stream is alive even
|
||||
* when the reasoner hasn't produced body text yet. Uses the shared
|
||||
* tick (TICK_MS ≈ 120ms) scaled down 4× so the visible blink rate
|
||||
* lands around 500ms — feels like a heartbeat, not a progress bar.
|
||||
*/
|
||||
function Pulse() {
|
||||
/** Blinking ▌ at the end of the streaming body. ~960ms cycle (matches the
|
||||
* design's 900ms steps(2) blink; integer-tick approximation). */
|
||||
function BlinkingCursor() {
|
||||
const tick = useTick();
|
||||
const frames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
|
||||
return <Text color="cyan">{frames[Math.floor(tick / 4) % frames.length]}</Text>;
|
||||
const visible = Math.floor(tick / 4) % 2 === 0;
|
||||
return <Text color={COLOR.primary}>{visible ? "▌" : " "}</Text>;
|
||||
}
|
||||
|
||||
/** Char-marching responding indicator. 12-cell track; a 5-char wave
|
||||
* (▒▓█▓▒) shifts one cell per fast tick (120ms). Matches the design
|
||||
* HTML's `.thinking .marquee` exactly. */
|
||||
const MARQUEE_W = 12;
|
||||
const MARQUEE_WAVE = ["▒", "▓", "█", "▓", "▒"] as const;
|
||||
function Marquee() {
|
||||
const tick = useTick();
|
||||
const cells = new Array(MARQUEE_W).fill("░");
|
||||
for (let i = 0; i < MARQUEE_WAVE.length; i++) {
|
||||
cells[(tick + i) % MARQUEE_W] = MARQUEE_WAVE[i]!;
|
||||
}
|
||||
return <Text color={COLOR.primary}>{cells.join("")}</Text>;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -868,12 +934,6 @@ function formatReadyTail(tb: { readyCount?: number } | undefined): string {
|
||||
return ` · ${n} ready`;
|
||||
}
|
||||
|
||||
function lastLine(s: string, maxChars: number): string {
|
||||
const flat = s.replace(/\s+/g, " ").trim();
|
||||
if (!flat) return "";
|
||||
return flat.length <= maxChars ? flat : `…${flat.slice(-maxChars)}`;
|
||||
}
|
||||
|
||||
function StatsLine({ stats }: { stats: TurnStats }) {
|
||||
const hit = (stats.cacheHitRatio * 100).toFixed(1);
|
||||
const hitColor =
|
||||
|
||||
+45
-20
@@ -4,7 +4,8 @@ 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";
|
||||
import { CharBar } from "./char-bar.js";
|
||||
import { useElapsedSeconds, useSlowTick, useTick } from "./ticker.js";
|
||||
|
||||
export const SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
|
||||
|
||||
@@ -58,10 +59,12 @@ export function ModeStatusBar({
|
||||
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.
|
||||
// Subscribe to the slow tick so the jobs count stays live — the
|
||||
// registry is mutated outside React, so we need a periodic repaint
|
||||
// to catch it. 1Hz is enough for a count badge: a 1s lag for a job
|
||||
// appearing/disappearing is imperceptible vs how long jobs run.
|
||||
// No-op when there's no registry (chat mode / tests).
|
||||
useTick();
|
||||
useSlowTick();
|
||||
const running = jobs?.runningCount() ?? 0;
|
||||
const jobsTag =
|
||||
running > 0 ? (
|
||||
@@ -124,10 +127,16 @@ function ModeBarFrame({ children }: { children: React.ReactNode }) {
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* glance — bracket-text style matching the StatsPanel chrome at top
|
||||
* (one canonical pill style across the whole TUI). `flash` inverts
|
||||
* briefly after a mode flip so the user sees "yes, it changed"; once
|
||||
* the flash fades it returns to its quiet bracket form.
|
||||
*
|
||||
* Why bracket and not solid bg: the mode is already shown in the top
|
||||
* chrome's pill. Repeating the same info as a loud, padded block
|
||||
* directly above the prompt was visual repetition, not reinforcement.
|
||||
* Bracket here keeps the actionable hint readable while the flash
|
||||
* still does its acknowledgement job.
|
||||
*/
|
||||
function ModePill({
|
||||
label,
|
||||
@@ -139,8 +148,8 @@ function ModePill({
|
||||
flash: boolean;
|
||||
}) {
|
||||
return (
|
||||
<Text backgroundColor={bg} color="white" bold inverse={flash}>
|
||||
{` ${label} `}
|
||||
<Text color={bg} bold inverse={flash}>
|
||||
{`[${label}]`}
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
@@ -148,21 +157,29 @@ function ModePill({
|
||||
/**
|
||||
* "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.
|
||||
* The countdown ticks once per second — slow tick is the right
|
||||
* cadence here (faster re-renders just redraw the same digit).
|
||||
* State cleanup (the banner disappearing) happens in the parent's
|
||||
* setTimeout — the component is purely display.
|
||||
*/
|
||||
export function UndoBanner({
|
||||
banner,
|
||||
}: {
|
||||
banner: { results: ApplyResult[]; expiresAt: number };
|
||||
}) {
|
||||
// Fast tick so the char bar shrinks one cell at a time rather than
|
||||
// jumping in 1s gulps. With FAST_TICK_MS=120 we get ~42 frames over
|
||||
// a 5s window — smooth enough that the bar reads as a continuous
|
||||
// countdown without looking like a stutter.
|
||||
useTick();
|
||||
const totalMs = 5000; // mirrors armUndoBanner's hard-coded window
|
||||
const remainingMs = Math.max(0, banner.expiresAt - Date.now());
|
||||
const remainingSec = Math.ceil(remainingMs / 1000);
|
||||
const ok = banner.results.filter((r) => r.status === "applied" || r.status === "created").length;
|
||||
const total = banner.results.length;
|
||||
const urgent = remainingSec <= 1;
|
||||
// 20-cell bar, 4 cells per second. Filled = remaining time.
|
||||
const pct = (remainingMs / totalMs) * 100;
|
||||
return (
|
||||
<Box marginY={1} paddingX={1}>
|
||||
<Text backgroundColor="#c4b5fd" color="black" bold>
|
||||
@@ -172,7 +189,9 @@ export function UndoBanner({
|
||||
<Text backgroundColor="#67e8f9" color="black" bold>
|
||||
{" u "}
|
||||
</Text>
|
||||
<Text dimColor>{" to undo "}</Text>
|
||||
<Text dimColor>{" to undo "}</Text>
|
||||
<CharBar pct={pct} width={20} color={urgent ? "#f87171" : "#c4b5fd"} showLabel={false} />
|
||||
<Text dimColor>{" "}</Text>
|
||||
<Text color={urgent ? "#f87171" : "#c4b5fd"} bold={urgent}>
|
||||
{`${remainingSec}s`}
|
||||
</Text>
|
||||
@@ -194,14 +213,18 @@ export function SubagentRow({
|
||||
}) {
|
||||
const tick = useTick();
|
||||
const seconds = (activity.elapsedMs / 1000).toFixed(1);
|
||||
// Bracket-text style — same vocabulary as the static ToolPill so a
|
||||
// turn that contains both finished tools and a live subagent reads
|
||||
// as a consistent column. The braille spinner + colored ⌬ + colored
|
||||
// name carry enough weight without a solid-bg block.
|
||||
return (
|
||||
<Box paddingLeft={3}>
|
||||
<Text color="#c4b5fd" bold>
|
||||
{SPINNER_FRAMES[tick % SPINNER_FRAMES.length]}
|
||||
</Text>
|
||||
<Text>{" "}</Text>
|
||||
<Text backgroundColor="#c4b5fd" color="black" bold>
|
||||
{" ⌬ subagent "}
|
||||
<Text color="#c4b5fd" bold>
|
||||
⌬ subagent
|
||||
</Text>
|
||||
<Text color="#c4b5fd">{` ${activity.task}`}</Text>
|
||||
<Text dimColor>{` iter ${activity.iter} · ${seconds}s`}</Text>
|
||||
@@ -234,6 +257,9 @@ export function OngoingToolRow({
|
||||
const tick = useTick();
|
||||
const elapsed = useElapsedSeconds();
|
||||
const summary = summarizeToolArgs(tool.name, tool.args);
|
||||
// Bracket-text style — matches the static ToolPill that lands once
|
||||
// the call resolves, so a row of in-flight + finished tools reads
|
||||
// as one continuous column instead of two visual languages.
|
||||
return (
|
||||
<Box marginY={1} flexDirection="column" paddingX={1}>
|
||||
<Box>
|
||||
@@ -241,11 +267,10 @@ export function OngoingToolRow({
|
||||
{SPINNER_FRAMES[tick % SPINNER_FRAMES.length]}
|
||||
</Text>
|
||||
<Text>{" "}</Text>
|
||||
<Text backgroundColor="#fcd34d" color="black" bold>
|
||||
{` ⏵ ${tool.name} `}
|
||||
<Text color="#fcd34d" bold>
|
||||
{`▣ ${tool.name}`}
|
||||
</Text>
|
||||
<Text color="#fcd34d">{" running"}</Text>
|
||||
<Text dimColor>{` · ${elapsed}s`}</Text>
|
||||
<Text dimColor>{` running · ${elapsed}s`}</Text>
|
||||
</Box>
|
||||
{progress ? (
|
||||
<Box paddingLeft={3}>
|
||||
|
||||
+73
-28
@@ -1,22 +1,31 @@
|
||||
/**
|
||||
* 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).
|
||||
* PlanReviseConfirm). Renders as a true bordered card matching the
|
||||
* design doc — full accent-colored Unicode box around header + body,
|
||||
* with a horizontal rule separating the title row from the content
|
||||
* area so the modal reads as a discrete interrupt, not just a few
|
||||
* spaced lines in the live region.
|
||||
*
|
||||
* Layout:
|
||||
*
|
||||
* ▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
|
||||
* [ ICON TITLE ] optional subtitle
|
||||
* ╭───────────────────────────────────────────────╮
|
||||
* │ ICON TITLE subtitle │
|
||||
* ├───────────────────────────────────────────────┤
|
||||
* │ │
|
||||
* │ <children — body of the modal> │
|
||||
* │ │
|
||||
* ╰───────────────────────────────────────────────╯
|
||||
*
|
||||
* <children — body of the modal>
|
||||
* Color drives the accent (border + icon + title) so the user learns
|
||||
* to recognize the modal type by glance: violet = choice, cyan = plan,
|
||||
* amber = shell, green = edit review, red = budget exhausted.
|
||||
*
|
||||
* ▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁
|
||||
*
|
||||
* 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.
|
||||
* Why Ink `borderStyle="round"` is fine here despite the historical
|
||||
* comment about eraseLines miscounts: the modals only render in
|
||||
* single-instance positions (they replace the prompt area, never the
|
||||
* scrollback), so the frame doesn't get re-painted every tick. The
|
||||
* earlier bug class was about animated wide rows wrapping mid-render.
|
||||
*/
|
||||
|
||||
import { Box, Text, useStdout } from "ink";
|
||||
@@ -24,14 +33,21 @@ import { Box, Text, useStdout } from "ink";
|
||||
import React from "react";
|
||||
|
||||
export interface ModalCardProps {
|
||||
/** Accent color — title pill bg + top/bottom rule color. */
|
||||
/** Accent color — border + icon + title text. */
|
||||
accent: string;
|
||||
/** Section title shown in the bg-pill header. */
|
||||
/** Section title — rendered bold in the accent color. */
|
||||
title: string;
|
||||
/** Optional dim subtitle next to the title. */
|
||||
subtitle?: string;
|
||||
/** Optional leading glyph inside the title pill (icon). */
|
||||
/** Optional leading glyph (icon). Rendered in the accent color. */
|
||||
icon?: string;
|
||||
/**
|
||||
* Optional footer slot — renders below a horizontal rule, after the
|
||||
* body. Used for action-button rows like `[apply] [discard]` so they
|
||||
* sit visually pinned to the bottom of the modal regardless of body
|
||||
* scroll height. When absent, the modal ends right after the body.
|
||||
*/
|
||||
footer?: React.ReactNode;
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
@@ -40,31 +56,60 @@ export function ModalCard({
|
||||
title,
|
||||
subtitle,
|
||||
icon,
|
||||
footer,
|
||||
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} `;
|
||||
// Subtract 4: 2 cells for the left+right border + 2 cells of paddingX.
|
||||
// Min 28 keeps the rule visible even on absurdly narrow terminals.
|
||||
const innerWidth = Math.min(76, Math.max(28, cols - 6));
|
||||
|
||||
return (
|
||||
<Box flexDirection="column" paddingX={1} marginY={1}>
|
||||
<Box flexDirection="column" borderStyle="round" borderColor={accent} paddingX={1} marginY={1}>
|
||||
{/* Header row — icon + bold title in accent color, dim subtitle
|
||||
right-aligned. The horizontal rule below it doubles as a
|
||||
separator and a visual weight that says "this is the thing
|
||||
to read". */}
|
||||
<Box>
|
||||
<Text color={accent}>{"▔".repeat(ruleWidth)}</Text>
|
||||
</Box>
|
||||
<Box marginTop={1}>
|
||||
<Text backgroundColor={accent} color="black" bold>
|
||||
{titleText}
|
||||
{icon ? (
|
||||
<>
|
||||
<Text color={accent} bold>
|
||||
{icon}
|
||||
</Text>
|
||||
<Text>{" "}</Text>
|
||||
</>
|
||||
) : null}
|
||||
<Text color={accent} bold>
|
||||
{title}
|
||||
</Text>
|
||||
{subtitle ? <Text dimColor>{` ${subtitle}`}</Text> : null}
|
||||
{subtitle ? (
|
||||
<>
|
||||
<Box flexGrow={1} />
|
||||
<Text dimColor>{subtitle}</Text>
|
||||
</>
|
||||
) : null}
|
||||
</Box>
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
{children}
|
||||
</Box>
|
||||
<Box marginTop={1}>
|
||||
<Box>
|
||||
<Text color={accent} dimColor>
|
||||
{"▁".repeat(ruleWidth)}
|
||||
{"─".repeat(innerWidth)}
|
||||
</Text>
|
||||
</Box>
|
||||
{/* Body — children render with no extra padding so the modal
|
||||
body looks like one continuous content area inside the border. */}
|
||||
<Box flexDirection="column">{children}</Box>
|
||||
{/* Optional footer — divider rule + slot. Lets modals separate
|
||||
actions from body without each one re-implementing the rule. */}
|
||||
{footer ? (
|
||||
<>
|
||||
<Box>
|
||||
<Text color={accent} dimColor>
|
||||
{"─".repeat(innerWidth)}
|
||||
</Text>
|
||||
</Box>
|
||||
<Box flexDirection="column">{footer}</Box>
|
||||
</>
|
||||
) : null}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -18,6 +18,7 @@ import { Box, Text } from "ink";
|
||||
import React, { useState } from "react";
|
||||
import { ModalCard } from "./ModalCard.js";
|
||||
import { useKeystroke } from "./keystroke-context.js";
|
||||
import { COLOR } from "./theme.js";
|
||||
import { useTick } from "./ticker.js";
|
||||
|
||||
export interface PlanRefineInputProps {
|
||||
@@ -74,25 +75,25 @@ export function PlanRefineInput({ mode, onSubmit, onCancel }: PlanRefineInputPro
|
||||
mode === "approve"
|
||||
? {
|
||||
title: "approving — any last instructions?",
|
||||
icon: "📋",
|
||||
accent: "#67e8f9",
|
||||
icon: "◇",
|
||||
accent: COLOR.primary,
|
||||
}
|
||||
: mode === "checkpoint-revise"
|
||||
? {
|
||||
title: "revising — what should change before the next step?",
|
||||
icon: "✏",
|
||||
accent: "#fbbf24",
|
||||
icon: "✎",
|
||||
accent: COLOR.warn,
|
||||
}
|
||||
: mode === "choice-custom"
|
||||
? {
|
||||
title: "custom answer — type whatever fits",
|
||||
icon: "🔀",
|
||||
accent: "#f0abfc",
|
||||
icon: "⌥",
|
||||
accent: COLOR.accent,
|
||||
}
|
||||
: {
|
||||
title: "refining — what should the model change?",
|
||||
icon: "✏",
|
||||
accent: "#fbbf24",
|
||||
icon: "✎",
|
||||
accent: COLOR.warn,
|
||||
};
|
||||
const hint =
|
||||
mode === "approve"
|
||||
|
||||
@@ -9,37 +9,43 @@
|
||||
* - uncertainties: yellow — attention required (like tool)
|
||||
* - rejected paths: red dim — ruled out (muted, like error-but-resolved)
|
||||
*
|
||||
* Only the label is colored + bold. The items themselves render in the
|
||||
* terminal's default foreground, so they stay readable on any background —
|
||||
* which is why the old single-magenta block was hard to see on dark themes.
|
||||
* Visual: colored bold label + count, then dim items. No solid-bg pill
|
||||
* — every assistant turn surfaces this block, so the bracket-text style
|
||||
* keeps it from shouting four colored bg blocks at the user every turn.
|
||||
* Color alone (the bold label) is enough to identify the field type.
|
||||
*/
|
||||
|
||||
import { Box, Text } from "ink";
|
||||
import React from "react";
|
||||
import type { TypedPlanState } from "../../harvest.js";
|
||||
import { COLOR } from "./theme.js";
|
||||
|
||||
type FieldColor = string;
|
||||
|
||||
export function PlanStateBlock({ planState }: { planState: TypedPlanState }) {
|
||||
const fields: Array<[string, string[], FieldColor, boolean]> = [];
|
||||
if (planState.subgoals.length) fields.push(["subgoals", planState.subgoals, "#67e8f9", false]);
|
||||
if (planState.subgoals.length)
|
||||
fields.push(["subgoals", planState.subgoals, COLOR.primary, false]);
|
||||
if (planState.hypotheses.length)
|
||||
fields.push(["hypotheses", planState.hypotheses, "#86efac", false]);
|
||||
fields.push(["hypotheses", planState.hypotheses, COLOR.assistant, false]);
|
||||
if (planState.uncertainties.length)
|
||||
fields.push(["uncertainties", planState.uncertainties, "#fcd34d", false]);
|
||||
fields.push(["uncertainties", planState.uncertainties, COLOR.warn, false]);
|
||||
if (planState.rejectedPaths.length)
|
||||
fields.push(["rejected", planState.rejectedPaths, "#94a3b8", true]);
|
||||
fields.push(["rejected", planState.rejectedPaths, COLOR.info, true]);
|
||||
if (fields.length === 0) return null;
|
||||
|
||||
return (
|
||||
<Box flexDirection="column" marginBottom={1}>
|
||||
{fields.map(([label, items, color, dim]) => (
|
||||
<Box key={label}>
|
||||
<Text backgroundColor={color} color="black" bold dimColor={dim}>
|
||||
{` ${label} ${items.length} `}
|
||||
<Text color={color} bold dimColor={dim}>
|
||||
{label}
|
||||
</Text>
|
||||
<Text dimColor>{` (${items.length})`}</Text>
|
||||
<Text dimColor>{" · "}</Text>
|
||||
<Text dimColor={dim} color={dim ? undefined : COLOR.info}>
|
||||
{items.join(" · ")}
|
||||
</Text>
|
||||
<Text>{" "}</Text>
|
||||
<Text dimColor={dim}>{items.join(" · ")}</Text>
|
||||
</Box>
|
||||
))}
|
||||
</Box>
|
||||
|
||||
+97
-97
@@ -1,22 +1,37 @@
|
||||
/**
|
||||
* 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.
|
||||
* Compact tree-style renderer for a plan's structured step list. Used
|
||||
* by PlanConfirm (on approval) and PlanCheckpointConfirm (mid-execution)
|
||||
* so the user always sees the same visual representation.
|
||||
*
|
||||
* Layout per step:
|
||||
*
|
||||
* ● ✓ step-1 · Extract tokens into a module
|
||||
* ●●▶ step-2 · Migrate session cookies
|
||||
* ●●● step-3 · Update tests
|
||||
* 2/5 done (40%) · est. 5 steps
|
||||
* ┣ ✓ step-1 · Extract tokens into a module
|
||||
* ┣ ✓ step-2 · Migrate session cookies ⚠ med
|
||||
* ┣ ▸ step-3 · Update tests ⚠ high
|
||||
* ┣ ○ step-4 · Run regression suite
|
||||
* ┗ ○ step-5 · Audit every callsite
|
||||
* ████████░░░░░░░░░░░░ 40%
|
||||
*
|
||||
* 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.
|
||||
* Why this shape:
|
||||
* - Status icons (✓ ▸ ○ ✗) read at a glance — color + glyph are
|
||||
* redundant signals, useful for color-blind users and for
|
||||
* terminals where a single bg-color cell is the only contrast.
|
||||
* - Tree branch lines (┣ ┗) visually bind the steps as one group
|
||||
* and mark "last step" with a corner — the eye finds the bottom
|
||||
* without counting.
|
||||
* - Risk only shown ≥medium. low risk on every line is noise (most
|
||||
* steps are low-risk — that's the default). med + high are the
|
||||
* ones that deserve attention before approve.
|
||||
* - Bottom progress bar (24 cells of █ / ░) makes "how far in are
|
||||
* we" answerable from the cursor's eye position alone.
|
||||
*/
|
||||
|
||||
import { Box, Text } from "ink";
|
||||
import React from "react";
|
||||
import type { PlanStep, PlanStepRisk } from "../../tools/plan.js";
|
||||
import { CharBar } from "./char-bar.js";
|
||||
import { COLOR, GLYPH } from "./theme.js";
|
||||
|
||||
export type StepStatus = "pending" | "running" | "done" | "skipped";
|
||||
|
||||
@@ -28,28 +43,14 @@ export interface PlanStepListProps {
|
||||
*/
|
||||
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.
|
||||
* Optional current step — rendered with the `cur` (▸) glyph in cyan
|
||||
* even when its status is still "pending", so the user sees which
|
||||
* one's about to run. If the step's status is "running" we always
|
||||
* use the cur glyph regardless of focusStepId.
|
||||
*/
|
||||
focusStepId?: string;
|
||||
}
|
||||
|
||||
function 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) {
|
||||
@@ -58,96 +59,95 @@ function getStatus(stepId: string, statuses: PlanStepListProps["statuses"]): Ste
|
||||
return statuses[stepId] ?? "pending";
|
||||
}
|
||||
|
||||
interface StatusGlyph {
|
||||
glyph: string;
|
||||
color: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Map (status, focus) → (glyph, color). Centralized so a future tweak
|
||||
* (e.g. add a "queued for retry" state) lands in one switch instead of
|
||||
* five render branches.
|
||||
*/
|
||||
function statusGlyph(status: StepStatus, isCur: boolean): StatusGlyph {
|
||||
if (status === "done") return { glyph: GLYPH.done, color: COLOR.ok };
|
||||
if (status === "running") return { glyph: GLYPH.cur, color: COLOR.primary };
|
||||
if (status === "skipped") return { glyph: GLYPH.fail, color: COLOR.info };
|
||||
// pending: focus override gets the cur glyph (▸) in primary color so
|
||||
// the active row pops without us needing a separate column.
|
||||
if (isCur) return { glyph: GLYPH.cur, color: COLOR.primary };
|
||||
return { glyph: GLYPH.pending, color: COLOR.info };
|
||||
}
|
||||
|
||||
function riskLabel(risk: PlanStepRisk | undefined): { text: string; color: string } | null {
|
||||
if (risk === "med") return { text: `${GLYPH.warn} med`, color: COLOR.warn };
|
||||
if (risk === "high") return { text: `${GLYPH.warn} high`, color: COLOR.err };
|
||||
// low + undefined: omitted entirely (the default reading should be
|
||||
// "low risk" — surfacing it on every line buries the med/high ones).
|
||||
return null;
|
||||
}
|
||||
|
||||
function PlanStepListInner({ steps, statuses, focusStepId }: PlanStepListProps) {
|
||||
if (steps.length === 0) return null;
|
||||
const 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);
|
||||
const statusList = steps.map((s) => getStatus(s.id, statuses));
|
||||
const total = steps.length;
|
||||
const doneCount = statusList.filter((s) => s === "done").length;
|
||||
const pct = Math.round((doneCount / total) * 100);
|
||||
// Show progress only when the plan has any motion. A freshly-submitted
|
||||
// plan with 0/N done renders without the bar to avoid an empty
|
||||
// "░░░░░░░░░░ 0%" rule that signals nothing.
|
||||
const showProgress = doneCount > 0;
|
||||
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
<Box>
|
||||
<Text dimColor>
|
||||
{`${steps.length} step${steps.length === 1 ? "" : "s"}`}
|
||||
{doneCount > 0 ? ` · ${doneCount}/${steps.length} done (${pct}%)` : ""}
|
||||
{hasAnyRisk ? " · risk: " : ""}
|
||||
{showProgress
|
||||
? `${doneCount}/${total} done (${pct}%) · ${total} step${total === 1 ? "" : "s"}`
|
||||
: `${total} step${total === 1 ? "" : "s"}`}
|
||||
</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);
|
||||
<Box flexDirection="column">
|
||||
{steps.map((step, i) => {
|
||||
const status = statusList[i]!;
|
||||
const isLast = i === total - 1;
|
||||
const isCur = focusStepId === step.id;
|
||||
const sg = statusGlyph(status, isCur);
|
||||
const risk = riskLabel(step.risk);
|
||||
const titleDim = status === "done" || status === "skipped";
|
||||
return (
|
||||
<Box key={step.id}>
|
||||
<Text color={focus ? "#67e8f9" : "gray"} bold={focus}>
|
||||
{focus ? "▸ " : " "}
|
||||
<Text color={COLOR.info} dimColor>
|
||||
{isLast ? GLYPH.branchEnd : GLYPH.branch}
|
||||
</Text>
|
||||
<Text color={risk.color} bold>
|
||||
{risk.dots}
|
||||
<Text>{" "}</Text>
|
||||
<Text color={sg.color} bold={status === "running" || isCur}>
|
||||
{sg.glyph}
|
||||
</Text>
|
||||
<Text> </Text>
|
||||
<StatusBadge status={status} />
|
||||
<Text> </Text>
|
||||
<Text dimColor={titleDim} bold={focus}>
|
||||
<Text>{" "}</Text>
|
||||
<Text
|
||||
dimColor={titleDim}
|
||||
bold={isCur || status === "running"}
|
||||
strikethrough={status === "done" || status === "skipped"}
|
||||
>
|
||||
{`${step.id} · ${step.title}`}
|
||||
</Text>
|
||||
{risk ? (
|
||||
<>
|
||||
<Text>{" "}</Text>
|
||||
<Text color={risk.color}>{risk.text}</Text>
|
||||
</>
|
||||
) : null}
|
||||
</Box>
|
||||
);
|
||||
})}
|
||||
</Box>
|
||||
</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>
|
||||
{showProgress ? (
|
||||
<Box>
|
||||
<Text>{" "}</Text>
|
||||
<CharBar pct={pct} width={24} />
|
||||
</Box>
|
||||
) : null}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -258,6 +258,16 @@ export function PromptInput({
|
||||
</Text>
|
||||
</Box>
|
||||
) : null}
|
||||
{!disabled && !narrow && value.length === 0 ? (
|
||||
<Box>
|
||||
<Text color={barColorAt(0)}>{BAR}</Text>
|
||||
<Text dimColor>{continuationIndent.slice(BAR.length)}</Text>
|
||||
<Text dimColor>
|
||||
[PgUp/PgDn] scroll log · [End] jump to latest · drag to select & copy · /mouse on for
|
||||
wheel
|
||||
</Text>
|
||||
</Box>
|
||||
) : null}
|
||||
{disabled ? (
|
||||
<Box>
|
||||
<Text color={barColorAt(0)}>{BAR}</Text>
|
||||
|
||||
@@ -75,11 +75,7 @@ export function ReplayApp({ meta, pages }: ReplayAppProps) {
|
||||
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
<StatsPanel
|
||||
summary={summary}
|
||||
model={cumStats.models[0] ?? meta?.model ?? "?"}
|
||||
prefixHash={prefixHash}
|
||||
/>
|
||||
<StatsPanel summary={summary} />
|
||||
|
||||
<Box flexDirection="column" marginTop={1} paddingX={1}>
|
||||
<Box justifyContent="space-between">
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
import { Box, Text } from "ink";
|
||||
import React, { useState } from "react";
|
||||
import { useKeystroke } from "./keystroke-context.js";
|
||||
import { COLOR } from "./theme.js";
|
||||
|
||||
export interface SelectItem<V extends string = string> {
|
||||
/** Stable identifier — returned to caller on submit. */
|
||||
@@ -166,11 +167,14 @@ function SelectRow<V extends string>({
|
||||
active: boolean;
|
||||
marker: string;
|
||||
}) {
|
||||
const color = item.disabled ? "gray" : active ? "cyan" : undefined;
|
||||
// Color: dim for disabled, primary cyan + bold for active, plain
|
||||
// default for inactive. Keeps the active-row affordance consistent
|
||||
// with the slash + at-mention pickers (▸ + colored text).
|
||||
const color = item.disabled ? COLOR.info : active ? COLOR.primary : undefined;
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
<Box>
|
||||
<Text color={color}>
|
||||
<Text color={color} bold={active} dimColor={item.disabled}>
|
||||
{marker} {item.label}
|
||||
</Text>
|
||||
</Box>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Box, Text } from "ink";
|
||||
import React from "react";
|
||||
import { SingleSelect } from "./Select.js";
|
||||
import { COLOR, GLYPH } from "./theme.js";
|
||||
|
||||
export type SessionChoice = "resume" | "new" | "delete";
|
||||
|
||||
@@ -12,6 +13,15 @@ export interface SessionPickerProps {
|
||||
onChoose: (choice: SessionChoice) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resume / new / delete picker shown at launch when a prior session
|
||||
* file exists. Three lines of header (brand mark · session summary)
|
||||
* then the selector, then a footer with key bindings.
|
||||
*
|
||||
* Visual grammar matches the design's session-resume modal: brand
|
||||
* glyph in primary color, session name highlighted, the rest dim.
|
||||
* No solid-bg pills — bracket-text style continues.
|
||||
*/
|
||||
export function SessionPicker({
|
||||
sessionName,
|
||||
messageCount,
|
||||
@@ -21,9 +31,14 @@ export function SessionPicker({
|
||||
return (
|
||||
<Box flexDirection="column" marginY={1}>
|
||||
<Box marginBottom={1}>
|
||||
<Text bold color="cyan">
|
||||
{`Session "${sessionName}" has ${messageCount} prior message${messageCount === 1 ? "" : "s"}`}
|
||||
<Text color={COLOR.brand} bold>
|
||||
{GLYPH.brand}
|
||||
</Text>
|
||||
<Text>{" "}</Text>
|
||||
<Text color={COLOR.primary} bold>
|
||||
{`"${sessionName}"`}
|
||||
</Text>
|
||||
<Text dimColor>{` has ${messageCount} prior message${messageCount === 1 ? "" : "s"}`}</Text>
|
||||
<Text dimColor>{` · last active ${relativeTime(lastActive)}`}</Text>
|
||||
</Box>
|
||||
<SingleSelect
|
||||
@@ -48,7 +63,7 @@ export function SessionPicker({
|
||||
onSubmit={(v) => onChoose(v as SessionChoice)}
|
||||
/>
|
||||
<Box marginTop={1}>
|
||||
<Text dimColor>[↑↓] navigate · [Enter] select</Text>
|
||||
<Text dimColor>{" ↑↓ navigate · ⏎ select"}</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
|
||||
+33
-13
@@ -2,6 +2,7 @@ import { Box, Text, useApp } from "ink";
|
||||
import TextInput from "ink-text-input";
|
||||
import React, { useState } from "react";
|
||||
import { defaultConfigPath, isPlausibleKey, redactKey, saveApiKey } from "../../config.js";
|
||||
import { COLOR, GLYPH, GRADIENT } from "./theme.js";
|
||||
|
||||
export interface SetupProps {
|
||||
onReady: (apiKey: string) => void;
|
||||
@@ -33,18 +34,34 @@ export function Setup({ onReady }: SetupProps) {
|
||||
};
|
||||
|
||||
return (
|
||||
<Box flexDirection="column" borderStyle="round" borderColor="cyan" paddingX={1}>
|
||||
<Text bold color="cyan">
|
||||
Welcome to Reasonix.
|
||||
</Text>
|
||||
<Box marginTop={1}>
|
||||
<Text>Paste your DeepSeek API key to get started.</Text>
|
||||
<Box flexDirection="column" paddingX={1} marginY={1}>
|
||||
<Box>
|
||||
<Text bold color={GRADIENT[0]}>
|
||||
{GLYPH.brand}
|
||||
</Text>
|
||||
<Text>{" "}</Text>
|
||||
<Text bold>Welcome to </Text>
|
||||
<Text bold color={GRADIENT[2]}>
|
||||
REASONIX
|
||||
</Text>
|
||||
</Box>
|
||||
<Text dimColor>Get one (free credit on signup): https://platform.deepseek.com/api_keys</Text>
|
||||
<Text dimColor>Saved locally to {defaultConfigPath()}</Text>
|
||||
<Box marginTop={1}>
|
||||
<Text bold color="cyan">
|
||||
{"key › "}
|
||||
<Text color={COLOR.info}>Paste your DeepSeek API key to get started.</Text>
|
||||
</Box>
|
||||
<Box>
|
||||
<Text dimColor>{" free credit on signup · "}</Text>
|
||||
<Text color={COLOR.primary}>https://platform.deepseek.com/api_keys</Text>
|
||||
</Box>
|
||||
<Box>
|
||||
<Text dimColor>{" saved to "}</Text>
|
||||
<Text dimColor>{defaultConfigPath()}</Text>
|
||||
</Box>
|
||||
<Box marginTop={1}>
|
||||
<Text bold color={COLOR.brand}>
|
||||
{GLYPH.bar}
|
||||
</Text>
|
||||
<Text bold color={COLOR.primary}>
|
||||
{" › "}
|
||||
</Text>
|
||||
<TextInput
|
||||
value={value}
|
||||
@@ -56,15 +73,18 @@ export function Setup({ onReady }: SetupProps) {
|
||||
</Box>
|
||||
{error ? (
|
||||
<Box marginTop={1}>
|
||||
<Text color="red">{error}</Text>
|
||||
<Text color={COLOR.err} bold>
|
||||
{GLYPH.err}
|
||||
</Text>
|
||||
<Text color={COLOR.err}>{` ${error}`}</Text>
|
||||
</Box>
|
||||
) : value ? (
|
||||
<Box marginTop={1}>
|
||||
<Text dimColor>preview: {redactKey(value)}</Text>
|
||||
<Text dimColor>{` preview · ${redactKey(value)}`}</Text>
|
||||
</Box>
|
||||
) : null}
|
||||
<Box marginTop={1}>
|
||||
<Text dimColor>(Type /exit to abort.)</Text>
|
||||
<Text dimColor>{" /exit to abort"}</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
|
||||
@@ -2,6 +2,7 @@ import { Box, Text } from "ink";
|
||||
import React from "react";
|
||||
import { ModalCard } from "./ModalCard.js";
|
||||
import { SingleSelect } from "./Select.js";
|
||||
import { COLOR } from "./theme.js";
|
||||
|
||||
export type ShellConfirmChoice = "run_once" | "always_allow" | "deny";
|
||||
|
||||
@@ -40,16 +41,16 @@ export function ShellConfirm({ command, allowPrefix, kind, onChoose }: ShellConf
|
||||
: "model wants to run a shell command";
|
||||
return (
|
||||
<ModalCard
|
||||
accent="#f87171"
|
||||
accent={COLOR.err}
|
||||
icon={isBackground ? "⏱" : "⚡"}
|
||||
title={isBackground ? "background process" : "shell command"}
|
||||
subtitle={subtitle}
|
||||
>
|
||||
<Box marginBottom={1}>
|
||||
<Text dimColor>{"$ "}</Text>
|
||||
<Text color="#67e8f9" bold>
|
||||
{command}
|
||||
<Text color={COLOR.primary} bold>
|
||||
{"$ "}
|
||||
</Text>
|
||||
<Text bold>{command}</Text>
|
||||
</Box>
|
||||
<SingleSelect
|
||||
initialValue="run_once"
|
||||
@@ -72,7 +73,7 @@ export function ShellConfirm({ command, allowPrefix, kind, onChoose }: ShellConf
|
||||
]}
|
||||
onSubmit={(v) => onChoose(v as ShellConfirmChoice)}
|
||||
onCancel={() => onChoose("deny")}
|
||||
footer="[↑↓] navigate · [Enter] select · [Esc] deny"
|
||||
footer="↑↓ navigate · ⏎ select · esc deny"
|
||||
/>
|
||||
</ModalCard>
|
||||
);
|
||||
|
||||
@@ -2,6 +2,7 @@ import { Box, Text } from "ink";
|
||||
// biome-ignore lint/style/useImportType: tsconfig.jsx = "react" needs React in value scope for JSX compilation
|
||||
import React from "react";
|
||||
import type { SlashCommandSpec } from "./slash.js";
|
||||
import { COLOR, GLYPH } from "./theme.js";
|
||||
|
||||
export interface SlashArgPickerProps {
|
||||
/**
|
||||
@@ -36,15 +37,28 @@ export function SlashArgPicker({
|
||||
kind,
|
||||
partial,
|
||||
}: SlashArgPickerProps): React.ReactElement | null {
|
||||
// Hint mode: a single dim row explaining the argsHint + summary.
|
||||
// Header row shared by both hint and picker modes — same shape so
|
||||
// the UI looks like the same affordance, just with or without rows
|
||||
// beneath. cmd in accent violet (matches SlashSuggestions), argsHint
|
||||
// in dim, summary in info.
|
||||
const headerRow = (
|
||||
<Box>
|
||||
<Text color={COLOR.accent} bold>
|
||||
{"/ "}
|
||||
</Text>
|
||||
<Text color={COLOR.accent} bold>
|
||||
{`/${spec.cmd}`}
|
||||
</Text>
|
||||
{spec.argsHint ? <Text dimColor>{` ${spec.argsHint}`}</Text> : null}
|
||||
<Text dimColor>{` ${spec.summary}`}</Text>
|
||||
</Box>
|
||||
);
|
||||
|
||||
// Hint mode: header only.
|
||||
if (kind === "hint") {
|
||||
return (
|
||||
<Box paddingX={1} marginTop={1}>
|
||||
<Text dimColor>
|
||||
{" "}
|
||||
<Text bold>/{spec.cmd}</Text>
|
||||
{spec.argsHint ? ` ${spec.argsHint}` : ""} — {spec.summary}
|
||||
</Text>
|
||||
{headerRow}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -53,12 +67,14 @@ export function SlashArgPicker({
|
||||
if (matches.length === 0) {
|
||||
return (
|
||||
<Box flexDirection="column" paddingX={1} marginTop={1}>
|
||||
<Text dimColor>
|
||||
{" "}
|
||||
<Text bold>/{spec.cmd}</Text>
|
||||
{spec.argsHint ? ` ${spec.argsHint}` : ""} — {spec.summary}
|
||||
</Text>
|
||||
<Text color="yellow"> no match for "{partial}" — keep typing, or Backspace to edit</Text>
|
||||
{headerRow}
|
||||
<Box>
|
||||
<Text color={COLOR.warn} bold>
|
||||
{GLYPH.warn}
|
||||
</Text>
|
||||
<Text color={COLOR.warn}>{` no match for "${partial}"`}</Text>
|
||||
<Text dimColor>{" — keep typing, or Backspace to edit"}</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -72,36 +88,27 @@ export function SlashArgPicker({
|
||||
const hiddenBelow = total - windowStart - shown.length;
|
||||
return (
|
||||
<Box flexDirection="column" paddingX={1} marginTop={1}>
|
||||
<Text dimColor>
|
||||
{" "}
|
||||
<Text bold>/{spec.cmd}</Text>
|
||||
{spec.argsHint ? ` ${spec.argsHint}` : ""} — {spec.summary}
|
||||
</Text>
|
||||
{hiddenAbove > 0 ? <Text dimColor> ↑ {hiddenAbove} more above</Text> : null}
|
||||
{headerRow}
|
||||
{hiddenAbove > 0 ? <Text dimColor>{` ↑ ${hiddenAbove} above`}</Text> : null}
|
||||
{shown.map((value, i) => (
|
||||
<ArgRow key={value} value={value} isSelected={windowStart + i === selectedIndex} />
|
||||
))}
|
||||
{hiddenBelow > 0 ? <Text dimColor> ↓ {hiddenBelow} more below</Text> : null}
|
||||
<Text dimColor> [↑↓] navigate · [Tab]/[Enter] pick</Text>
|
||||
{hiddenBelow > 0 ? <Text dimColor>{` ↓ ${hiddenBelow} below`}</Text> : null}
|
||||
<Box marginTop={0}>
|
||||
<Text dimColor>{" ↑↓ navigate · Tab / ⏎ pick · esc cancel"}</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
function ArgRow({ value, isSelected }: { value: string; isSelected: boolean }) {
|
||||
const marker = isSelected ? "▸" : " ";
|
||||
if (isSelected) {
|
||||
return (
|
||||
<Box>
|
||||
<Text bold color="cyan">
|
||||
{marker} {value}
|
||||
</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Box>
|
||||
<Text dimColor>
|
||||
{marker} {value}
|
||||
<Text color={isSelected ? COLOR.primary : COLOR.info} bold={isSelected}>
|
||||
{isSelected ? `${GLYPH.cur} ` : " "}
|
||||
</Text>
|
||||
<Text color={isSelected ? COLOR.user : COLOR.info} bold={isSelected} dimColor={!isSelected}>
|
||||
{value}
|
||||
</Text>
|
||||
</Box>
|
||||
);
|
||||
|
||||
@@ -2,6 +2,7 @@ import { Box, Text } from "ink";
|
||||
// biome-ignore lint/style/useImportType: tsconfig.jsx = "react" needs React in value scope for JSX compilation
|
||||
import React from "react";
|
||||
import type { SlashCommandSpec } from "./slash.js";
|
||||
import { COLOR, GLYPH } from "./theme.js";
|
||||
|
||||
export interface SlashSuggestionsProps {
|
||||
/**
|
||||
@@ -15,11 +16,21 @@ export interface SlashSuggestionsProps {
|
||||
}
|
||||
|
||||
/**
|
||||
* Floating slash-command panel. Rendered below the input box when
|
||||
* the user is typing a `/…` prefix. Navigation state lives in the
|
||||
* parent (App.tsx owns `slashSelected`) so ↑/↓/Tab/Enter stay
|
||||
* consistent with the useInput handler. This component is pure
|
||||
* display: `matches` and `selectedIndex` come in, rows go out.
|
||||
* Slash-command palette. Rendered below the input box while the user
|
||||
* is typing a `/…` prefix. Visual grammar matches the design doc's
|
||||
* picker style:
|
||||
*
|
||||
* / suggestions esc cancel
|
||||
* ▸ /checkpoint [name] snapshot the workspace
|
||||
* /restore <name> roll back files to a checkpoint
|
||||
* /diff cumulative diff vs session start
|
||||
* [↑↓] navigate · [Tab/⏎] pick
|
||||
*
|
||||
* Cmd tokens render in accent violet (one consistent color for "this
|
||||
* is a command"), descriptions in dim info color. The selected row
|
||||
* gets a leading ▸ + bold cmd; non-selected rows get a 2-space pad in
|
||||
* the same column so the cmd column stays aligned. No solid-bg pill —
|
||||
* the bracket-text pattern from the chrome carries through here.
|
||||
*/
|
||||
export function SlashSuggestions({
|
||||
matches,
|
||||
@@ -29,8 +40,12 @@ export function SlashSuggestions({
|
||||
if (matches.length === 0) {
|
||||
return (
|
||||
<Box paddingX={1} marginTop={1}>
|
||||
<Text color="yellow">no slash command matches that prefix</Text>
|
||||
<Text dimColor> — Backspace to edit, or /help for the full list</Text>
|
||||
<Text color={COLOR.warn} bold>
|
||||
{GLYPH.warn}
|
||||
</Text>
|
||||
<Text> </Text>
|
||||
<Text color={COLOR.warn}>no slash command matches that prefix</Text>
|
||||
<Text dimColor>{" — Backspace to edit, or /help for the full list"}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -46,34 +61,40 @@ export function SlashSuggestions({
|
||||
const hiddenBelow = total - windowStart - shown.length;
|
||||
return (
|
||||
<Box flexDirection="column" paddingX={1} marginTop={1}>
|
||||
{hiddenAbove > 0 ? <Text dimColor> ↑ {hiddenAbove} more above</Text> : null}
|
||||
<Box>
|
||||
<Text color={COLOR.accent} bold>
|
||||
{"/ "}
|
||||
</Text>
|
||||
<Text dimColor>{`${total} command${total === 1 ? "" : "s"}`}</Text>
|
||||
{hiddenAbove > 0 ? <Text dimColor>{` ↑ ${hiddenAbove} above`}</Text> : null}
|
||||
</Box>
|
||||
{shown.map((spec, i) => (
|
||||
<SuggestionRow key={spec.cmd} spec={spec} isSelected={windowStart + i === selectedIndex} />
|
||||
))}
|
||||
{hiddenBelow > 0 ? <Text dimColor> ↓ {hiddenBelow} more below</Text> : null}
|
||||
<Text dimColor> [↑↓] navigate · [Tab]/[Enter] pick</Text>
|
||||
{hiddenBelow > 0 ? <Text dimColor>{` ↓ ${hiddenBelow} below`}</Text> : null}
|
||||
<Box marginTop={0}>
|
||||
<Text dimColor>{" ↑↓ navigate · Tab / ⏎ pick · esc cancel"}</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
function SuggestionRow({ spec, isSelected }: { spec: SlashCommandSpec; isSelected: boolean }) {
|
||||
const name = `/${spec.cmd}`;
|
||||
const argsSuffix = spec.argsHint ? ` ${spec.argsHint}` : "";
|
||||
// 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 backgroundColor="#67e8f9" color="black" bold>
|
||||
{` ▸ ${name.padEnd(12)}${argsSuffix.padEnd(16)} ${spec.summary} `}
|
||||
</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
const argsSuffix = spec.argsHint ? spec.argsHint : "";
|
||||
return (
|
||||
<Box>
|
||||
<Text color="#94a3b8">{` ${name.padEnd(12)}${argsSuffix.padEnd(16)} ${spec.summary}`}</Text>
|
||||
<Text color={isSelected ? COLOR.primary : COLOR.info} bold={isSelected}>
|
||||
{isSelected ? `${GLYPH.cur} ` : " "}
|
||||
</Text>
|
||||
<Text color={COLOR.accent} bold={isSelected}>
|
||||
{name.padEnd(14)}
|
||||
</Text>
|
||||
<Text dimColor>{argsSuffix.padEnd(14)}</Text>
|
||||
<Text>{" "}</Text>
|
||||
<Text color={isSelected ? COLOR.user : COLOR.info} dimColor={!isSelected}>
|
||||
{spec.summary}
|
||||
</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
/**
|
||||
* Side-by-side diff renderer — git-difftool / delta-style "old | new"
|
||||
* layout. Each row shows the same logical position on both sides;
|
||||
* removed lines have content on the left only with a red wash, added
|
||||
* lines on the right with a green wash, common context appears on
|
||||
* both sides dim.
|
||||
*
|
||||
* Layout:
|
||||
*
|
||||
* 40 function loginUser(...) │ 40 function loginUser(...)
|
||||
* 41 - if (!email) throw new Error… │ 41 + if (!email || typeof email…
|
||||
* │ 42 + throw new TypeError(…)
|
||||
* │ 43 + }
|
||||
* 42 return verify(email, …) │ 44 return verify(email, …)
|
||||
*
|
||||
* Width is derived from the terminal — half each side minus a 3-cell
|
||||
* separator (` │ `). Long lines truncate with `…` rather than wrap,
|
||||
* so the row count stays predictable for the parent's height budget.
|
||||
*/
|
||||
|
||||
import { Box, Text, useStdout } from "ink";
|
||||
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React in value scope for React.Fragment
|
||||
import React from "react";
|
||||
import type { SplitDiffRow } from "../../code/diff-preview.js";
|
||||
import { COLOR } from "./theme.js";
|
||||
|
||||
export interface SplitDiffProps {
|
||||
rows: readonly SplitDiffRow[];
|
||||
/**
|
||||
* Total columns budget. Defaults to terminal width. Modal callers
|
||||
* pass a smaller number so the diff fits inside the modal frame.
|
||||
*/
|
||||
totalCols?: number;
|
||||
}
|
||||
|
||||
export function SplitDiff({ rows, totalCols }: SplitDiffProps): React.ReactElement {
|
||||
const { stdout } = useStdout();
|
||||
const cols = totalCols ?? stdout?.columns ?? 80;
|
||||
// Reserve ~6 cells for outer border + padding on the modal/log side,
|
||||
// 3 cells for the ` │ ` separator. Half the rest per column.
|
||||
const innerCols = Math.max(40, cols - 6);
|
||||
const halfCols = Math.floor((innerCols - 3) / 2);
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
{rows.map((row, i) => (
|
||||
<Box key={`r-${i}-${row.left.num ?? "p"}-${row.right.num ?? "p"}`}>
|
||||
<Cell side={row.left} width={halfCols} which="left" />
|
||||
<Text color={COLOR.info} dimColor>
|
||||
{" │ "}
|
||||
</Text>
|
||||
<Cell side={row.right} width={halfCols} which="right" />
|
||||
</Box>
|
||||
))}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
function Cell({
|
||||
side,
|
||||
width,
|
||||
which,
|
||||
}: {
|
||||
side: SplitDiffRow["left"] | SplitDiffRow["right"];
|
||||
width: number;
|
||||
which: "left" | "right";
|
||||
}) {
|
||||
const numPad = 4; // up to 9999 lines
|
||||
const sgnPad = 1; // single-char sign
|
||||
const inner = Math.max(8, width - numPad - sgnPad - 2 /* spaces */);
|
||||
|
||||
const numStr = side.num !== null ? String(side.num).padStart(numPad) : " ".repeat(numPad);
|
||||
const sign =
|
||||
side.kind === "del" ? "-" : side.kind === "add" ? "+" : side.kind === "pad" ? " " : " ";
|
||||
const raw = side.text;
|
||||
const truncated = raw.length > inner ? `${raw.slice(0, inner - 1)}…` : raw;
|
||||
// Pad to fixed width so the bg color stretches across the whole
|
||||
// column even when the text is short — without this the red/green
|
||||
// wash would only cover the actual chars and the rest of the row
|
||||
// would be terminal default, which looks broken.
|
||||
const padded = truncated.padEnd(inner);
|
||||
|
||||
if (side.kind === "del") {
|
||||
return (
|
||||
<Text color="#fbc8c8" backgroundColor="#2a1212">
|
||||
{`${numStr} ${sign} ${padded}`}
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
if (side.kind === "add") {
|
||||
return (
|
||||
<Text color="#bef0c8" backgroundColor="#0c2718">
|
||||
{`${numStr} ${sign} ${padded}`}
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
if (side.kind === "pad") {
|
||||
// Empty side — mute everything, no bg, no glyph. The "… more
|
||||
// lines" capRows marker also rides this kind on the left side
|
||||
// when present, so we render its text dim italic.
|
||||
return (
|
||||
<Text color={COLOR.info} dimColor italic={!!raw}>
|
||||
{`${numStr} ${sign} ${padded}`}
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
// ctx: same content both sides, dim
|
||||
return <Text dimColor>{`${numStr} ${sign} ${padded}`}</Text>;
|
||||
}
|
||||
+190
-518
@@ -1,582 +1,254 @@
|
||||
import { basename } from "node:path";
|
||||
import { Box, Text, useStdout } from "ink";
|
||||
import React from "react";
|
||||
import stringWidth from "string-width";
|
||||
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 { Bar, ChromeRule } from "./primitives.js";
|
||||
import { COLOR, GRADIENT } from "./theme.js";
|
||||
|
||||
const WORDMARK_LETTERS: ReadonlyArray<string> = ["R", "E", "A", "S", "O", "N", "I", "X"];
|
||||
|
||||
/**
|
||||
* Gradient-flowing wordmark. Every tick the gradient shifts one
|
||||
* position so the colors visibly travel across the letters — like
|
||||
* a neon sign. Brand mark `◈` rides the same flow but also pulses
|
||||
* bold on/off (slow when idle, fast when busy) so a glance at the
|
||||
* top of the screen tells you whether the app is thinking.
|
||||
*
|
||||
* Tick is ~120 ms. `rotateEvery=4` ticks → one shift every ~480 ms
|
||||
* idle, ~240 ms when busy. Slow enough to be ambient, fast enough
|
||||
* to feel alive. Truecolor terminals get the smooth flow; 8-color
|
||||
* fallbacks just see all-cyan, which is still legible.
|
||||
*/
|
||||
function Wordmark({
|
||||
busy: _busy,
|
||||
animate: _animate,
|
||||
}: {
|
||||
busy: boolean;
|
||||
animate: boolean;
|
||||
}) {
|
||||
// Static gradient. The brand sweep teal → fuchsia is precomputed
|
||||
// once per render — no useTick subscription, no per-tick
|
||||
// re-render. Earlier versions flowed the colors over time, but
|
||||
// the per-tick re-render interleaved badly with terminal resize
|
||||
// (Ink's eraseLines misjudges row count when bars / wide text
|
||||
// wrap, ghost frames stack). Keeping this static eliminates the
|
||||
// multiplier; resize artifacts at most leave a single stale
|
||||
// frame instead of N.
|
||||
return (
|
||||
<Text>
|
||||
<Text color={GRADIENT[0]} bold>
|
||||
◈
|
||||
</Text>
|
||||
<Text> </Text>
|
||||
{WORDMARK_LETTERS.map((letter, i) => (
|
||||
<Text key={letter} color={GRADIENT[i % GRADIENT.length]} bold>
|
||||
{letter}
|
||||
</Text>
|
||||
))}
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
const COLD_START_TURNS = 3;
|
||||
|
||||
export interface StatsPanelProps {
|
||||
summary: SessionSummary;
|
||||
model: string;
|
||||
prefixHash: string;
|
||||
harvestOn?: boolean;
|
||||
branchBudget?: number;
|
||||
/**
|
||||
* Current `reasoning_effort` cap. Shown as a green "· max" / yellow
|
||||
* "· high" tag in the header so the user always sees which tier the
|
||||
* next turn will use. Absent/undefined hides the tag (e.g. before
|
||||
* the loop is constructed).
|
||||
*/
|
||||
reasoningEffort?: "high" | "max";
|
||||
/**
|
||||
* True when `reasonix code` is currently running in read-only Plan
|
||||
* Mode. Surfaced as a red "PLAN" tag in the panel header so the user
|
||||
* can tell at a glance that edits are gated behind submit_plan +
|
||||
* approval.
|
||||
*/
|
||||
planMode?: boolean;
|
||||
/**
|
||||
* Edit-gate mode. Surfaced as a small pill in the header so the user
|
||||
* can see at a glance whether edits will be queued for review or
|
||||
* applied immediately. Omitted in chat (non-code) mode.
|
||||
*/
|
||||
editMode?: EditMode;
|
||||
/**
|
||||
* Account balance fetched once at launch (and optionally refreshed
|
||||
* per-turn by the TUI). `null` or absent hides the balance cell
|
||||
* entirely — /user/balance failed or the user ran with `--no-config`.
|
||||
* The top-up warning fires below 1.0 unit of whatever currency
|
||||
* the endpoint reports so a Chinese user with CNY and a U.S. user
|
||||
* with USD both see "getting low."
|
||||
*/
|
||||
balance?: { currency: string; total: number } | null;
|
||||
/**
|
||||
* Published npm version newer than VERSION. Rendered as a yellow
|
||||
* "· update: X" nudge in the panel header. `null` / `undefined`
|
||||
* hides the nudge (offline launch, already up to date, or check
|
||||
* still in flight).
|
||||
*/
|
||||
updateAvailable?: string | null;
|
||||
/**
|
||||
* True when the loop is currently mid-turn — drives the wordmark's
|
||||
* "busy breathing" animation. Visual signal that the app is thinking,
|
||||
* visible at a glance from anywhere on screen.
|
||||
*/
|
||||
busy?: boolean;
|
||||
/**
|
||||
* /pro is queued — the next turn will run on v4-pro regardless of
|
||||
* `model`. Rendered as a yellow `⇧ pro armed` pill in the header so
|
||||
* the user has a clear "this turn will be expensive" signal before
|
||||
* submitting their message.
|
||||
*/
|
||||
proArmed?: boolean;
|
||||
/**
|
||||
* The CURRENT turn is running on v4-pro because the failure-
|
||||
* escalation threshold fired mid-turn. Rendered as a red `⇧ pro
|
||||
* escalated` pill. Clears at turn end.
|
||||
*/
|
||||
escalated?: boolean;
|
||||
budgetUsd?: number | null;
|
||||
rootDir?: string;
|
||||
sessionName?: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Terminal width under which we switch from one-line metrics to a
|
||||
* stacked layout. Below 120 cols the wide version wraps mid-number
|
||||
* and the parens ("in $X · out $Y") get split across lines — which
|
||||
* looks broken. Stacking costs one row but stays readable on every
|
||||
* SSH / split-pane case we've hit.
|
||||
*/
|
||||
const NARROW_BREAKPOINT = 120;
|
||||
|
||||
/**
|
||||
* Cache-hit ratio is always zero on turn 1 (there's literally no cache
|
||||
* to hit yet). Showing that as red "0.0%" is a false alarm — new users
|
||||
* read it as "something is broken." We suppress the gradient until a
|
||||
* few turns have landed; by turn 4 the cache has had time to warm up.
|
||||
*/
|
||||
const COLD_START_TURNS = 3;
|
||||
|
||||
export function StatsPanel({
|
||||
summary,
|
||||
model,
|
||||
prefixHash,
|
||||
harvestOn,
|
||||
branchBudget,
|
||||
reasoningEffort,
|
||||
planMode,
|
||||
editMode,
|
||||
balance,
|
||||
updateAvailable,
|
||||
busy,
|
||||
proArmed,
|
||||
escalated,
|
||||
budgetUsd,
|
||||
rootDir,
|
||||
sessionName,
|
||||
}: StatsPanelProps) {
|
||||
const branchOn = (branchBudget ?? 1) > 1;
|
||||
const ctxMax = DEEPSEEK_CONTEXT_TOKENS[model] ?? DEFAULT_CONTEXT_TOKENS;
|
||||
const ctxRatio = summary.lastPromptTokens / ctxMax;
|
||||
const { stdout } = useStdout();
|
||||
const columns = stdout?.columns ?? 80;
|
||||
const narrow = columns < NARROW_BREAKPOINT;
|
||||
|
||||
// Cold-start: first few turns render cache+cost muted so a 0.0% hit
|
||||
// rate on turn 1 doesn't look like an error. Once the cache has
|
||||
// actually had a chance to build, we flip to the live gradient.
|
||||
const coldStart = summary.turns <= COLD_START_TURNS;
|
||||
|
||||
// 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 flexDirection="column" paddingX={1} marginBottom={1}>
|
||||
<Header
|
||||
model={model}
|
||||
prefixHash={prefixHash}
|
||||
harvestOn={harvestOn}
|
||||
branchOn={branchOn}
|
||||
branchBudget={branchBudget ?? 1}
|
||||
reasoningEffort={reasoningEffort}
|
||||
planMode={planMode}
|
||||
<Box flexDirection="column" paddingX={1}>
|
||||
<ChromeRow
|
||||
editMode={editMode}
|
||||
turns={summary.turns}
|
||||
updateAvailable={updateAvailable}
|
||||
narrow={narrow}
|
||||
busy={busy ?? false}
|
||||
planMode={planMode}
|
||||
proArmed={proArmed ?? false}
|
||||
escalated={escalated ?? false}
|
||||
animate={false}
|
||||
summary={summary}
|
||||
coldStart={coldStart}
|
||||
rootDir={rootDir}
|
||||
sessionName={sessionName ?? null}
|
||||
updateAvailable={updateAvailable}
|
||||
balance={balance ?? null}
|
||||
/>
|
||||
{narrow ? (
|
||||
<StackedMetrics
|
||||
summary={summary}
|
||||
ctxRatio={ctxRatio}
|
||||
ctxMax={ctxMax}
|
||||
balance={balance}
|
||||
coldStart={coldStart}
|
||||
/>
|
||||
) : (
|
||||
<InlineMetrics
|
||||
summary={summary}
|
||||
ctxRatio={ctxRatio}
|
||||
ctxMax={ctxMax}
|
||||
balance={balance}
|
||||
coldStart={coldStart}
|
||||
/>
|
||||
)}
|
||||
<ChromeRule />
|
||||
{budgetUsd !== null && budgetUsd !== undefined ? (
|
||||
<BudgetRow spent={summary.totalCostUsd} cap={budgetUsd} />
|
||||
) : null}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
function Header({
|
||||
model,
|
||||
prefixHash,
|
||||
harvestOn,
|
||||
branchOn,
|
||||
branchBudget,
|
||||
reasoningEffort,
|
||||
planMode,
|
||||
function ChromeRow({
|
||||
editMode,
|
||||
turns,
|
||||
updateAvailable,
|
||||
narrow,
|
||||
busy,
|
||||
planMode,
|
||||
proArmed,
|
||||
escalated,
|
||||
animate,
|
||||
summary,
|
||||
coldStart,
|
||||
rootDir,
|
||||
sessionName,
|
||||
updateAvailable,
|
||||
balance,
|
||||
}: {
|
||||
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;
|
||||
planMode?: boolean;
|
||||
proArmed: boolean;
|
||||
escalated: boolean;
|
||||
/** When false, suppress optional pills + animation to avoid wraps. */
|
||||
animate: boolean;
|
||||
summary: SessionSummary;
|
||||
coldStart: boolean;
|
||||
rootDir?: string;
|
||||
sessionName?: string | null;
|
||||
updateAvailable?: string | null;
|
||||
balance?: { currency: string; total: number } | null;
|
||||
}) {
|
||||
// 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 modePill = pickModePill(planMode, editMode);
|
||||
const proPill = escalated
|
||||
? { label: "⇧ PRO", bg: "red" as const }
|
||||
? { label: "⇧ pro", color: COLOR.err }
|
||||
: proArmed
|
||||
? { label: "⇧ PRO", bg: "yellow" as const }
|
||||
? { label: "⇧ pro", color: COLOR.warn }
|
||||
: 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;
|
||||
const projectName = rootDir ? basename(rootDir) : null;
|
||||
const cachePct = Math.round(summary.cacheHitRatio * 100);
|
||||
const cacheColor =
|
||||
summary.cacheHitRatio >= 0.7 ? COLOR.ok : summary.cacheHitRatio >= 0.4 ? COLOR.warn : COLOR.err;
|
||||
const balanceLabel = balance
|
||||
? `[w ${balance.currency === "USD" ? "$" : ""}${balance.total.toFixed(2)}${balance.currency !== "USD" ? ` ${balance.currency}` : ""}]`
|
||||
: "";
|
||||
const costLabel = `[$${summary.totalCostUsd.toFixed(4)}]`;
|
||||
const cacheLabel = "[c ▰▰▰▰▰▰ 100%]";
|
||||
const updateLabel = updateAvailable ? `↑ ${updateAvailable}` : "";
|
||||
|
||||
// Greedy width-aware fit. Layout (every gap = 2 cells, applied as suffix
|
||||
// to update/mode/pro and as prefix to balance/cache):
|
||||
// [brand][·project][›session]<spacer>[update][mode][pro][cost][balance][cache]
|
||||
// Always shown: brand, project (if rootDir), mode (if set), pro (if armed),
|
||||
// cost. These carve fixedLeft / fixedRight first.
|
||||
// Optional, dropped greedy by priority: balance > cache > session > update.
|
||||
// The flexbox spacer can shrink to 0, so no minimum reserve.
|
||||
const { stdout } = useStdout();
|
||||
const cols = (stdout?.columns ?? 80) - 2; // subtract paddingX={1} on both sides
|
||||
const SEP_DOT = stringWidth(" · ");
|
||||
const SEP_ARROW = stringWidth(" › ");
|
||||
const GAP = 2;
|
||||
|
||||
const fixedLeft =
|
||||
stringWidth("◈ reasonix") + (projectName ? SEP_DOT + stringWidth(projectName) : 0);
|
||||
const modeW = modePill ? GAP + stringWidth(`[${modePill.label}]`) : 0;
|
||||
const proW = proPill ? GAP + stringWidth(`[${proPill.label}]`) : 0;
|
||||
const fixedRight = modeW + proW + stringWidth(costLabel);
|
||||
let budget = cols - fixedLeft - fixedRight;
|
||||
|
||||
const balW = balance ? GAP + stringWidth(balanceLabel) : 0;
|
||||
const cacheW = GAP + stringWidth(cacheLabel);
|
||||
const sessionW = sessionName ? SEP_ARROW + stringWidth(sessionName) : 0;
|
||||
const updateW = updateLabel ? GAP + stringWidth(updateLabel) : 0;
|
||||
|
||||
const showBalance = balW > 0 && budget >= balW;
|
||||
if (showBalance) budget -= balW;
|
||||
const showCache = budget >= cacheW;
|
||||
if (showCache) budget -= cacheW;
|
||||
const showSession = sessionW > 0 && budget >= sessionW;
|
||||
if (showSession) budget -= sessionW;
|
||||
const showUpdate = updateW > 0 && budget >= updateW;
|
||||
if (showUpdate) budget -= updateW;
|
||||
|
||||
return (
|
||||
<Box justifyContent="space-between">
|
||||
<Box>
|
||||
<Wordmark busy={busy} animate={animate} />
|
||||
<Text dimColor>{` ${VERSION}`}</Text>
|
||||
<Text dimColor>{" "}</Text>
|
||||
<Text color="yellow" bold>
|
||||
{model.replace(/^deepseek-/, "")}
|
||||
</Text>
|
||||
{modePill ? (
|
||||
<>
|
||||
<Text>{" "}</Text>
|
||||
<Pill label={modePill.label} bg={modePill.bg} />
|
||||
</>
|
||||
) : null}
|
||||
{proPill ? (
|
||||
<>
|
||||
<Text>{" "}</Text>
|
||||
<Pill label={proPill.label} bg={proPill.bg} />
|
||||
</>
|
||||
) : null}
|
||||
{showSecondary && harvestOn ? (
|
||||
<Text dimColor>
|
||||
<Text>{" "}</Text>
|
||||
<Text color="magenta">harvest</Text>
|
||||
<Box>
|
||||
<Text bold color={GRADIENT[0]}>
|
||||
{"◈ "}
|
||||
</Text>
|
||||
<Text color={COLOR.brand} bold>
|
||||
reasonix
|
||||
</Text>
|
||||
{projectName ? (
|
||||
<>
|
||||
<Text color={COLOR.info} dimColor>
|
||||
{" · "}
|
||||
</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>{`↑ ${updateAvailable} `}</Text> : null}
|
||||
<Text dimColor>{narrow ? `t${turns}` : `turn ${turns} · /help`}</Text>
|
||||
</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
/** Solid-background tag, used for primary mode + pro indicators. */
|
||||
function Pill({ label, bg }: { label: string; bg: "red" | "magenta" | "cyan" | "yellow" }) {
|
||||
return (
|
||||
<Text backgroundColor={bg} color="white" bold>
|
||||
{` ${label} `}
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Wide-terminal layout (≥120 cols): single metrics row. Matches the
|
||||
* original panel, just with calmer spacing and the cold-start
|
||||
* treatment folded in.
|
||||
*/
|
||||
function InlineMetrics({
|
||||
summary,
|
||||
ctxRatio,
|
||||
ctxMax,
|
||||
balance,
|
||||
coldStart,
|
||||
}: {
|
||||
summary: SessionSummary;
|
||||
ctxRatio: number;
|
||||
ctxMax: number;
|
||||
balance?: { currency: string; total: number } | null;
|
||||
coldStart: boolean;
|
||||
}) {
|
||||
return (
|
||||
<Box marginTop={1} gap={3}>
|
||||
<ContextCell ratio={ctxRatio} promptTokens={summary.lastPromptTokens} ctxMax={ctxMax} />
|
||||
<CacheCell hitRatio={summary.cacheHitRatio} coldStart={coldStart} turns={summary.turns} />
|
||||
<CostCell summary={summary} coldStart={coldStart} />
|
||||
{balance ? <BalanceCell balance={balance} /> : null}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Narrow-terminal layout (<120 cols): one metric per line, in priority
|
||||
* order (ctx → balance → cache → cost). Order matters because users
|
||||
* scanning a cramped terminal want "am I about to hit a wall?" answered
|
||||
* first; dollars spent comes later.
|
||||
*/
|
||||
function StackedMetrics({
|
||||
summary,
|
||||
ctxRatio,
|
||||
ctxMax,
|
||||
balance,
|
||||
coldStart,
|
||||
}: {
|
||||
summary: SessionSummary;
|
||||
ctxRatio: number;
|
||||
ctxMax: number;
|
||||
balance?: { currency: string; total: number } | null;
|
||||
coldStart: boolean;
|
||||
}) {
|
||||
return (
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
<ContextCell
|
||||
ratio={ctxRatio}
|
||||
promptTokens={summary.lastPromptTokens}
|
||||
ctxMax={ctxMax}
|
||||
showBar
|
||||
/>
|
||||
{balance ? <BalanceCell balance={balance} /> : null}
|
||||
<CacheCell hitRatio={summary.cacheHitRatio} coldStart={coldStart} turns={summary.turns} />
|
||||
<CostCell summary={summary} coldStart={coldStart} />
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
function ContextCell({
|
||||
ratio,
|
||||
promptTokens,
|
||||
ctxMax,
|
||||
showBar,
|
||||
}: {
|
||||
ratio: number;
|
||||
promptTokens: number;
|
||||
ctxMax: number;
|
||||
showBar?: boolean;
|
||||
}) {
|
||||
if (promptTokens === 0) {
|
||||
return (
|
||||
<Text>
|
||||
<Text color={COLOR.info} dimColor>
|
||||
{"▣ ctx "}
|
||||
</Text>
|
||||
<Text dimColor>— (no turns yet)</Text>
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
const color = ratio >= 0.8 ? COLOR.err : ratio >= 0.6 ? COLOR.warn : COLOR.ok;
|
||||
const pct = Math.round(ratio * 100);
|
||||
return (
|
||||
<Text>
|
||||
<Text color={COLOR.info}>{"▣ ctx "}</Text>
|
||||
<Bar ratio={ratio} color={color} cells={showBar ? 14 : 10} />
|
||||
<Text> </Text>
|
||||
<Text color={color} bold>
|
||||
{formatTokens(promptTokens)}/{formatTokens(ctxMax)}
|
||||
</Text>
|
||||
<Text dimColor> ({pct}%)</Text>
|
||||
{ratio >= 0.8 ? (
|
||||
<Text color={COLOR.err} bold>
|
||||
{" · /compact"}
|
||||
</Text>
|
||||
<Text>{projectName}</Text>
|
||||
{showSession && sessionName ? (
|
||||
<>
|
||||
<Text color={COLOR.info} dimColor>
|
||||
{" › "}
|
||||
</Text>
|
||||
<Text color={COLOR.info}>{sessionName}</Text>
|
||||
</>
|
||||
) : null}
|
||||
</>
|
||||
) : null}
|
||||
</Text>
|
||||
|
||||
<Box flexGrow={1} />
|
||||
|
||||
{showUpdate ? (
|
||||
<>
|
||||
<Text color={COLOR.warn} bold>
|
||||
{updateLabel}
|
||||
</Text>
|
||||
<Text>{" "}</Text>
|
||||
</>
|
||||
) : null}
|
||||
{modePill ? (
|
||||
<>
|
||||
<Text color={modePill.color} bold>
|
||||
{`[${modePill.label}]`}
|
||||
</Text>
|
||||
<Text>{" "}</Text>
|
||||
</>
|
||||
) : null}
|
||||
{proPill ? (
|
||||
<>
|
||||
<Text color={proPill.color} bold>
|
||||
{`[${proPill.label}]`}
|
||||
</Text>
|
||||
<Text>{" "}</Text>
|
||||
</>
|
||||
) : null}
|
||||
<Text
|
||||
color={
|
||||
summary.turns === 0 || coldStart ? COLOR.info : sessionCostColor(summary.totalCostUsd)
|
||||
}
|
||||
bold={summary.turns > 0 && !coldStart}
|
||||
dimColor={summary.turns === 0 || coldStart}
|
||||
>
|
||||
{costLabel}
|
||||
</Text>
|
||||
{showBalance && balance ? (
|
||||
<>
|
||||
<Text>{" "}</Text>
|
||||
<Text color={balance.total < 1 ? COLOR.err : balance.total < 5 ? COLOR.warn : COLOR.ok}>
|
||||
{balanceLabel}
|
||||
</Text>
|
||||
</>
|
||||
) : null}
|
||||
{showCache ? (
|
||||
<>
|
||||
<Text>{" "}</Text>
|
||||
<Text dimColor>{"["}</Text>
|
||||
<Text dimColor>{"c "}</Text>
|
||||
<Bar
|
||||
ratio={summary.cacheHitRatio}
|
||||
color={coldStart ? COLOR.info : cacheColor}
|
||||
cells={6}
|
||||
dim={coldStart}
|
||||
/>
|
||||
<Text> </Text>
|
||||
<Text color={coldStart ? undefined : cacheColor} dimColor={coldStart}>
|
||||
{coldStart && summary.turns === 0 ? "—" : `${cachePct}%`}
|
||||
</Text>
|
||||
<Text dimColor>{"]"}</Text>
|
||||
</>
|
||||
) : null}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
function CacheCell({
|
||||
hitRatio,
|
||||
coldStart,
|
||||
turns,
|
||||
}: {
|
||||
hitRatio: number;
|
||||
coldStart: boolean;
|
||||
turns: number;
|
||||
}) {
|
||||
const pct = (hitRatio * 100).toFixed(1);
|
||||
if (turns === 0) {
|
||||
return (
|
||||
<Text>
|
||||
<Text color={COLOR.info} dimColor>
|
||||
{"⌬ cache "}
|
||||
</Text>
|
||||
<Text dimColor>—</Text>
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
if (coldStart) {
|
||||
return (
|
||||
<Text>
|
||||
<Text color={COLOR.info} dimColor>
|
||||
{"⌬ cache "}
|
||||
</Text>
|
||||
<Text dimColor>{pct}% </Text>
|
||||
<Text dimColor italic>
|
||||
(cold start)
|
||||
</Text>
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
const color = hitRatio >= 0.7 ? COLOR.ok : hitRatio >= 0.4 ? COLOR.warn : COLOR.err;
|
||||
function pickModePill(
|
||||
planMode: boolean | undefined,
|
||||
editMode: EditMode | undefined,
|
||||
): { label: string; color: string } | null {
|
||||
if (planMode) return { label: "PLAN", color: COLOR.err };
|
||||
if (editMode === "yolo") return { label: "yolo", color: COLOR.err };
|
||||
if (editMode === "auto") return { label: "auto", color: COLOR.primary };
|
||||
if (editMode === "review") return { label: "review", color: COLOR.info };
|
||||
return null;
|
||||
}
|
||||
|
||||
function BudgetRow({ spent, cap }: { spent: number; cap: number }) {
|
||||
const pct = Math.max(0, (spent / cap) * 100);
|
||||
const color = pct >= 100 ? "#f87171" : pct >= 80 ? "#fbbf24" : "#94a3b8";
|
||||
return (
|
||||
<Text>
|
||||
<Text color={COLOR.info}>{"⌬ cache "}</Text>
|
||||
<Text color={color} bold>
|
||||
{pct}%
|
||||
<Box>
|
||||
<Text dimColor>{" budget "}</Text>
|
||||
<Text color={color}>
|
||||
{`$${spent.toFixed(4)} / $${cap.toFixed(2)}`}
|
||||
<Text dimColor>{` (${pct.toFixed(0)}%)`}</Text>
|
||||
</Text>
|
||||
</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Color thresholds. Per-turn and session cumulative scale roughly 10×
|
||||
* apart — a $0.20 single turn should feel just as warn-worthy as a $2
|
||||
* session total. Values are rough "notice this" points, not hard caps.
|
||||
*/
|
||||
function turnCostColor(cost: number): string | undefined {
|
||||
if (cost <= 0) return undefined;
|
||||
if (cost >= 0.2) return COLOR.err;
|
||||
if (cost >= 0.05) return COLOR.warn;
|
||||
return COLOR.ok;
|
||||
}
|
||||
function sessionCostColor(cost: number): string | undefined {
|
||||
if (cost <= 0) return undefined;
|
||||
if (cost >= 5) return COLOR.err;
|
||||
if (cost >= 0.5) return COLOR.warn;
|
||||
return COLOR.ok;
|
||||
}
|
||||
|
||||
function CostCell({
|
||||
summary,
|
||||
coldStart,
|
||||
}: {
|
||||
summary: SessionSummary;
|
||||
coldStart: boolean;
|
||||
}) {
|
||||
if (summary.turns === 0) {
|
||||
return (
|
||||
<Text>
|
||||
<Text color={COLOR.info} dimColor>
|
||||
{"◴ cost "}
|
||||
</Text>
|
||||
<Text dimColor>—</Text>
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
// The first turn is unavoidably a cache-miss (nothing to hit),
|
||||
// so the dollar figure is front-loaded. Muting it during the
|
||||
// cold-start window keeps the "expensive first turn" from
|
||||
// reading as "something is wrong."
|
||||
const turnColor = coldStart ? undefined : turnCostColor(summary.lastTurnCostUsd);
|
||||
const sessionColor = coldStart ? undefined : sessionCostColor(summary.totalCostUsd);
|
||||
return (
|
||||
<Text>
|
||||
<Text color={COLOR.info}>{"◴ turn "}</Text>
|
||||
<Text color={turnColor} bold={!coldStart} dimColor={coldStart}>
|
||||
${summary.lastTurnCostUsd.toFixed(4)}
|
||||
</Text>
|
||||
<Text dimColor>{" · session "}</Text>
|
||||
<Text color={sessionColor} bold={!coldStart} dimColor={coldStart}>
|
||||
${summary.totalCostUsd.toFixed(4)}
|
||||
</Text>
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
|
||||
function BalanceCell({ balance }: { balance: { currency: string; total: number } }) {
|
||||
const color = balance.total < 1 ? COLOR.err : balance.total < 5 ? COLOR.warn : COLOR.ok;
|
||||
return (
|
||||
<Text>
|
||||
<Text color={COLOR.info}>{"◐ balance "}</Text>
|
||||
<Text color={color} bold>
|
||||
{balance.currency === "USD" ? "$" : ""}
|
||||
{balance.total.toFixed(2)}
|
||||
{balance.currency !== "USD" ? ` ${balance.currency}` : ""}
|
||||
</Text>
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Truecolor progress bar. Filled cells use the threshold color (green
|
||||
* → amber → rose) so the bar communicates pressure at a glance;
|
||||
* empty cells use a dim shade so the empty portion is visible
|
||||
* without dominating. ▰/▱ have distinct shapes (filled vs hollow)
|
||||
* so the boundary is clear even when colors snap to 8-color slots
|
||||
* on legacy terminals.
|
||||
*/
|
||||
function Bar({
|
||||
ratio,
|
||||
color,
|
||||
cells = 14,
|
||||
}: {
|
||||
ratio: number;
|
||||
color: string;
|
||||
cells?: number;
|
||||
}) {
|
||||
const filled = Math.max(0, Math.min(cells, Math.round(ratio * cells)));
|
||||
return (
|
||||
<Text>
|
||||
<Text color={color}>{"▰".repeat(filled)}</Text>
|
||||
<Text dimColor>{"▱".repeat(cells - filled)}</Text>
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Compact token formatter using binary K (÷1024): 1234 → "1.2K",
|
||||
* 131072 → "128K". Matches DeepSeek's marketing label of "128K context
|
||||
* length" — showing "131k" confused users (the actual limit is
|
||||
* 128×1024 = 131,072 tokens, but the doc consistently says "128K").
|
||||
* Uppercase K signals binary-K to anyone who notices.
|
||||
*/
|
||||
function formatTokens(n: number): string {
|
||||
if (n < 1024) return String(n);
|
||||
const k = n / 1024;
|
||||
return k >= 100 ? `${k.toFixed(0)}K` : `${k.toFixed(1)}K`;
|
||||
}
|
||||
+145
-93
@@ -1,113 +1,165 @@
|
||||
/**
|
||||
* 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.
|
||||
* Welcome card on the empty session. The FIRST thing every user sees
|
||||
* after launching `reasonix code` — must communicate brand identity,
|
||||
* what to type next, and how to escape, all in the ~5 seconds before
|
||||
* the user starts typing.
|
||||
*
|
||||
* Layout (matches design/tui-redesign-ink.html welcome state):
|
||||
*
|
||||
* ◈ R E A S O N I X
|
||||
*
|
||||
* DeepSeek-native coding agent · cache-first · flash-first
|
||||
*
|
||||
* /skill invoke a stored playbook by name
|
||||
* @file inline a file's contents in your message
|
||||
* /checkpoint snapshot the workspace before a risky turn
|
||||
* /help every slash command + keyboard shortcut
|
||||
*
|
||||
* tip · ctrl+j newline · trailing \ continues
|
||||
*
|
||||
* Why the redesign: the previous version was a left-aligned hint list
|
||||
* with a tiny `◈ welcome` row — functional but invisible as brand. The
|
||||
* gradient wordmark is the one chance per launch to plant identity, so
|
||||
* we make it large + centered + colored across all 8 brand-gradient
|
||||
* stops. The tagline below answers "what is this?" in one line. Cards
|
||||
* answer "what do I type?" — the only three things a new user actually
|
||||
* needs to know in the first 5 seconds.
|
||||
*
|
||||
* Why no animation: an animated gradient pan was tried, but Ink's
|
||||
* eraseLines miscounts on resize when wide rows reflow, leaving
|
||||
* stale frames stacked. Static gradient renders identically and
|
||||
* costs zero ticker subscriptions.
|
||||
*/
|
||||
|
||||
import { Box, Text, useStdout } from "ink";
|
||||
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React in value scope
|
||||
import React from "react";
|
||||
import { COLOR, gradientCells } from "./theme.js";
|
||||
import { COLOR, GRADIENT } from "./theme.js";
|
||||
|
||||
export interface WelcomeBannerProps {
|
||||
/** True when running `reasonix code`. Surfaces code-mode hints. */
|
||||
inCodeMode?: boolean;
|
||||
/**
|
||||
* Live URL of the embedded dashboard, or null when it isn't running.
|
||||
* Surfacing this in the welcome card is how users discover the web UI
|
||||
* — the chrome pill version was unreliable across terminals, so the
|
||||
* card became the canonical pointer.
|
||||
*/
|
||||
dashboardUrl?: string | null;
|
||||
}
|
||||
|
||||
export function WelcomeBanner({ inCodeMode }: WelcomeBannerProps): React.ReactElement {
|
||||
const WORDMARK = "REASONIX";
|
||||
const TAGLINE_CHAT = "DeepSeek-native agent · cache-first · flash-first";
|
||||
const TAGLINE_CODE = "DeepSeek-native coding agent · cache-first · flash-first";
|
||||
|
||||
interface QuickCard {
|
||||
cmd: string;
|
||||
desc: string;
|
||||
}
|
||||
|
||||
const CARDS_CHAT: QuickCard[] = [
|
||||
{ cmd: "/help", desc: "every slash command + keyboard shortcut" },
|
||||
{ cmd: "/skill", desc: "invoke a stored playbook by name" },
|
||||
{ cmd: "/dashboard", desc: "open the embedded web UI (chat · stats · settings)" },
|
||||
{ cmd: "/preset pro", desc: "switch to v4-pro for hard reasoning tasks" },
|
||||
{ cmd: "/exit", desc: "quit the TUI (Ctrl+C twice also works)" },
|
||||
];
|
||||
|
||||
const CARDS_CODE: QuickCard[] = [
|
||||
{ cmd: "@file", desc: "inline a file's contents in your message" },
|
||||
{ cmd: "!cmd", desc: "run shell — output is captured for context" },
|
||||
{ cmd: "/checkpoint", desc: "snapshot the workspace before a risky turn" },
|
||||
{ cmd: "/dashboard", desc: "open the embedded web UI (chat · files · stats · settings)" },
|
||||
{ cmd: "/help", desc: "every slash command + keyboard shortcut" },
|
||||
];
|
||||
|
||||
export function WelcomeBanner({
|
||||
inCodeMode,
|
||||
dashboardUrl,
|
||||
}: WelcomeBannerProps): React.ReactElement {
|
||||
const { stdout } = useStdout();
|
||||
const cols = stdout?.columns ?? 80;
|
||||
const ruleWidth = Math.min(60, Math.max(28, cols - 4));
|
||||
// Wordmark width: each letter + space between letters. With letter-
|
||||
// spacing of 1 cell, "R E A S O N I X" is 8*2-1 = 15 cells, plus the
|
||||
// brand mark "◈ " = 2 cells, total 17 cells. We center on the term
|
||||
// width, capped to a sane minimum so very narrow terminals don't
|
||||
// produce negative pad.
|
||||
const wordmarkText = `◈ ${WORDMARK.split("").join(" ")}`;
|
||||
const wordmarkWidth = wordmarkText.length;
|
||||
const tagline = inCodeMode ? TAGLINE_CODE : TAGLINE_CHAT;
|
||||
const cards = inCodeMode ? CARDS_CODE : CARDS_CHAT;
|
||||
|
||||
// Center column 1: pad-left to put wordmark at terminal center
|
||||
const wordmarkPad = Math.max(0, Math.floor((cols - wordmarkWidth) / 2));
|
||||
const taglinePad = Math.max(0, Math.floor((cols - tagline.length) / 2));
|
||||
// Cards left-margin: align to a comfortable indent rather than
|
||||
// center each row (keeps the cmd column aligned).
|
||||
const cardsIndent = Math.max(2, Math.floor((cols - 60) / 2));
|
||||
const tipText = "tip · ctrl+j newline · trailing \\ also continues";
|
||||
const tipPad = Math.max(0, Math.floor((cols - tipText.length) / 2));
|
||||
|
||||
return (
|
||||
<Box flexDirection="column" paddingX={1} marginY={1}>
|
||||
<GradientRule width={ruleWidth} />
|
||||
<BarRow>
|
||||
<Text bold color={COLOR.brand}>
|
||||
◈ welcome
|
||||
<Box flexDirection="column" marginY={1}>
|
||||
{/* Wordmark — gradient across the 8 letters of REASONIX. The
|
||||
brand mark `◈` sits in the brand teal as the first stop, then
|
||||
each letter steps through the gradient. Bold throughout for
|
||||
weight; spacing keeps it from reading as a single dense word. */}
|
||||
<Box>
|
||||
<Text>{" ".repeat(wordmarkPad)}</Text>
|
||||
<Text bold color={GRADIENT[0]}>
|
||||
{"◈ "}
|
||||
</Text>
|
||||
<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>
|
||||
{WORDMARK.split("").map((letter, i) => (
|
||||
// Wordmark is fixed-string ("REASONIX") — letters are unique
|
||||
// and the array never reorders, so per-letter key is stable.
|
||||
<React.Fragment key={letter}>
|
||||
<Text bold color={GRADIENT[i % GRADIENT.length]}>
|
||||
{letter}
|
||||
</Text>
|
||||
{i < WORDMARK.length - 1 ? <Text> </Text> : null}
|
||||
</React.Fragment>
|
||||
))}
|
||||
</Box>
|
||||
|
||||
<Box marginTop={1}>
|
||||
<GradientRule width={ruleWidth} thin />
|
||||
<Text>{" ".repeat(taglinePad)}</Text>
|
||||
<Text color={COLOR.info}>{tagline}</Text>
|
||||
</Box>
|
||||
|
||||
{/* Quick-start cards — cmd token in accent violet, desc dim.
|
||||
Aligned in two columns so the eye can scan command names
|
||||
without having to read each desc. */}
|
||||
<Box flexDirection="column" marginTop={2}>
|
||||
{cards.map((card) => (
|
||||
<Box key={card.cmd}>
|
||||
<Text>{" ".repeat(cardsIndent)}</Text>
|
||||
<Text bold color={COLOR.accent}>
|
||||
{card.cmd.padEnd(14)}
|
||||
</Text>
|
||||
<Text color={COLOR.info}>{card.desc}</Text>
|
||||
</Box>
|
||||
))}
|
||||
</Box>
|
||||
|
||||
{/* Live dashboard URL — printed once, centered, when the embedded
|
||||
server is up. This is the canonical pointer to the web UI; the
|
||||
chrome pill version was unreliable across terminals so we
|
||||
surface the URL here (one-shot at launch) and let the user
|
||||
re-fetch via `/dashboard` whenever the welcome card has
|
||||
scrolled away. */}
|
||||
{dashboardUrl ? (
|
||||
<Box marginTop={2}>
|
||||
<Text>{" ".repeat(Math.max(0, Math.floor((cols - (dashboardUrl.length + 9)) / 2)))}</Text>
|
||||
<Text color={COLOR.brand} bold>
|
||||
{"▸ web · "}
|
||||
</Text>
|
||||
<Text color={COLOR.accent}>{dashboardUrl}</Text>
|
||||
</Box>
|
||||
) : null}
|
||||
|
||||
<Box marginTop={dashboardUrl ? 1 : 2}>
|
||||
<Text>{" ".repeat(tipPad)}</Text>
|
||||
<Text dimColor>{tipText}</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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>
|
||||
);
|
||||
}
|
||||
@@ -59,7 +59,7 @@ export function Wizard({ onComplete, onCancel, existingApiKey, initial }: Wizard
|
||||
const [step, setStep] = useState<Step>(existingApiKey ? "preset" : "apiKey");
|
||||
const [data, setData] = useState<WizardData>({
|
||||
apiKey: existingApiKey ?? "",
|
||||
preset: initial?.preset ?? "fast",
|
||||
preset: initial?.preset ?? "auto",
|
||||
selectedCatalog: deriveInitialCatalog(initial?.mcp ?? []),
|
||||
catalogArgs: {},
|
||||
});
|
||||
@@ -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,
|
||||
}));
|
||||
|
||||
@@ -2,6 +2,7 @@ import { Box, Text } from "ink";
|
||||
import React from "react";
|
||||
import { ModalCard } from "./ModalCard.js";
|
||||
import { SingleSelect } from "./Select.js";
|
||||
import { COLOR } from "./theme.js";
|
||||
|
||||
export type WorkspaceConfirmChoice = "switch" | "deny";
|
||||
|
||||
@@ -33,15 +34,15 @@ export function WorkspaceConfirm({
|
||||
? `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}>
|
||||
<ModalCard accent={COLOR.warn} icon="⇄" title="switch workspace" subtitle={subtitle}>
|
||||
<Box flexDirection="column" marginBottom={1}>
|
||||
<Box>
|
||||
<Text dimColor>{"from "}</Text>
|
||||
<Text color="#a3a3a3">{currentRoot}</Text>
|
||||
<Text dimColor>{"from "}</Text>
|
||||
<Text color={COLOR.info}>{currentRoot}</Text>
|
||||
</Box>
|
||||
<Box>
|
||||
<Text dimColor>{"to "}</Text>
|
||||
<Text color="#67e8f9" bold>
|
||||
<Text dimColor>{"to "}</Text>
|
||||
<Text color={COLOR.primary} bold>
|
||||
{path}
|
||||
</Text>
|
||||
</Box>
|
||||
@@ -62,7 +63,7 @@ export function WorkspaceConfirm({
|
||||
]}
|
||||
onSubmit={(v) => onChoose(v as WorkspaceConfirmChoice)}
|
||||
onCancel={() => onChoose("deny")}
|
||||
footer="[↑↓] navigate · [Enter] select · [Esc] deny"
|
||||
footer="↑↓ navigate · ⏎ select · esc deny"
|
||||
/>
|
||||
</ModalCard>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
/**
|
||||
* Alternate screen buffer lifecycle for the TUI.
|
||||
*
|
||||
* Reasonix used to render to the main terminal buffer — every
|
||||
* historical event scrolled past in the user's normal scrollback.
|
||||
* That had nice properties (copy/paste from history, exit-and-still-
|
||||
* see-it) but made sticky chrome impossible: the StatsPanel pinned
|
||||
* to the top of the live region was always at the bottom of the
|
||||
* viewport, just above the prompt.
|
||||
*
|
||||
* The redesign requires a real "viewport-style" layout: chrome at
|
||||
* row 1, scrollable log in the middle, prompt at the bottom. That
|
||||
* needs the alternate screen buffer (`\x1b[?1049h`), which:
|
||||
*
|
||||
* · gives the app the entire terminal viewport to manage cell-by-cell
|
||||
* · saves the user's previous terminal state, restores on exit
|
||||
* · means session output is NOT in the user's scrollback after quit —
|
||||
* the transcript file is the durable record (Reasonix already writes
|
||||
* `~/.reasonix/sessions/<name>.jsonl` and optional `--transcript`)
|
||||
*
|
||||
* Trade-off accepted: lose post-exit scrollback access in exchange for
|
||||
* a real fixed header / scrollable middle / fixed footer layout.
|
||||
*
|
||||
* The escape sequences are the standard `xterm` private modes:
|
||||
* `\x1b[?1049h` → switch to alt buffer + save cursor
|
||||
* `\x1b[?1049l` → restore main buffer + cursor
|
||||
* `\x1b[H` → cursor to home (1,1) — start clean inside alt buffer
|
||||
*
|
||||
* Compatibility: every modern terminal (iTerm2, Windows Terminal,
|
||||
* WezTerm, gnome-terminal, kitty, alacritty, VS Code) supports 1049.
|
||||
* Plain `xterm` does too. Old conhost falls back to no-op (the codes
|
||||
* print as garbage characters, but that's a museum-piece risk).
|
||||
*/
|
||||
|
||||
import { useEffect } from "react";
|
||||
|
||||
/** True iff stdout looks like a real TTY we should write escapes to. */
|
||||
function isInteractiveTty(): boolean {
|
||||
return Boolean(process.stdout?.isTTY);
|
||||
}
|
||||
|
||||
/** Module-level mirror of "is mouse tracking active right now?". Mutated
|
||||
* by both `useAltScreen` (on mount) and `setMouseTracking` (slash command). */
|
||||
let mouseTrackingOn = false;
|
||||
|
||||
/**
|
||||
* Enter the alt screen on mount, restore on unmount. Mouse tracking
|
||||
* is ON by default in basic-button mode (1000 + 1006 SGR coords) so
|
||||
* the wheel can drive the log scroll — the most-asked-for thing after
|
||||
* the alt-screen switch. We deliberately use mode 1000 (press/release
|
||||
* only) instead of 1002 (button + drag) so drag events DON'T go to
|
||||
* the app: every modern terminal (Windows Terminal, iTerm2, WezTerm,
|
||||
* gnome-terminal, kitty, alacritty, VS Code) lets the user hold
|
||||
* **Shift while dragging** to bypass mouse tracking entirely and do
|
||||
* native cell selection. So the user gets:
|
||||
* · plain wheel → in-app log scroll (the regression we're fixing)
|
||||
* · shift + click+drag → native terminal selection (copy/paste)
|
||||
* · `/mouse off` → fully disable for terminals that don't bypass
|
||||
*
|
||||
* Restore is idempotent and runs on SIGINT / SIGTERM / exit, so the
|
||||
* user's terminal returns to a sane state regardless of how the
|
||||
* process dies.
|
||||
*/
|
||||
export function useAltScreen(): void {
|
||||
useEffect(() => {
|
||||
if (!isInteractiveTty()) return;
|
||||
// Enter alt buffer + clear + cursor home + basic mouse tracking
|
||||
// with SGR coordinates. Mode 1000 = press/release only (includes
|
||||
// wheel as buttons 64/65). 1006 = SGR-encoded coords. Together
|
||||
// they let us read the wheel without intercepting drag motion.
|
||||
//
|
||||
// Note on kitty keyboard protocol (\x1b[>1u): tried in 0.13.x but
|
||||
// rolled back — terminals without protocol support sometimes
|
||||
// displayed the escape as visible chars, distorting layout. To
|
||||
// re-enable safely we'd need terminal-feature detection (DA1 /
|
||||
// DA2 query response) before pushing the flag.
|
||||
process.stdout.write("\x1b[?1049h\x1b[2J\x1b[H\x1b[?1000h\x1b[?1006h");
|
||||
mouseTrackingOn = true;
|
||||
|
||||
// Belt-and-suspenders restore on every plausible exit path.
|
||||
let restored = false;
|
||||
const restore = () => {
|
||||
if (restored) return;
|
||||
restored = true;
|
||||
try {
|
||||
// Disable every mouse mode we might have turned on (1000 +
|
||||
// 1002 + 1006), then leave alt screen.
|
||||
process.stdout.write("\x1b[?1006l\x1b[?1002l\x1b[?1000l\x1b[?1049l");
|
||||
} catch {
|
||||
/* terminal closed, nothing to do */
|
||||
}
|
||||
};
|
||||
|
||||
process.once("exit", restore);
|
||||
process.once("SIGINT", () => {
|
||||
restore();
|
||||
// Re-emit so default exit-on-SIGINT can still fire.
|
||||
process.exit(130);
|
||||
});
|
||||
process.once("SIGTERM", () => {
|
||||
restore();
|
||||
process.exit(143);
|
||||
});
|
||||
|
||||
return restore;
|
||||
}, []);
|
||||
}
|
||||
|
||||
/**
|
||||
* Runtime toggle for mouse-event tracking (basic button + wheel).
|
||||
* Invoked by the `/mouse on|off` slash command. ON by default in
|
||||
* basic-button mode 1000 — see {@link useAltScreen} for the rationale
|
||||
* (wheel works, drag still does native shift+drag selection).
|
||||
*
|
||||
* `/mouse off` is the escape hatch for terminals that don't honor
|
||||
* shift+drag bypass — flipping it off restores fully-native mouse
|
||||
* behavior at the cost of in-app wheel scrolling (PgUp/PgDn still
|
||||
* work).
|
||||
*/
|
||||
export function setMouseTracking(on: boolean): void {
|
||||
if (!isInteractiveTty()) return;
|
||||
if (on === mouseTrackingOn) return;
|
||||
if (on) {
|
||||
process.stdout.write("\x1b[?1000h\x1b[?1006h");
|
||||
} else {
|
||||
// Disable both 1000 and 1002 modes (we may have inherited the
|
||||
// older 1002 default from a long-running session) plus SGR.
|
||||
process.stdout.write("\x1b[?1006l\x1b[?1002l\x1b[?1000l");
|
||||
}
|
||||
mouseTrackingOn = on;
|
||||
}
|
||||
export function isMouseTrackingOn(): boolean {
|
||||
return mouseTrackingOn;
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
/**
|
||||
* Character-cell progress bar — the visual primitive shared across:
|
||||
* · cache hit ratio in the status bar
|
||||
* · undo banner countdown
|
||||
* · /context token-usage breakdown (stacked variant)
|
||||
* · plan step progress
|
||||
* · MCP progress notifications
|
||||
* · walk-through "block N of M" position
|
||||
*
|
||||
* Why one helper: in a TUI you can only convey "fraction" by character
|
||||
* fill, not by gradient bg. Doing it ad-hoc per call site led to five
|
||||
* subtly different bar styles (some used `█/░`, some `■/-`, some
|
||||
* inverted bg). Centralizing here means the visual cue is one
|
||||
* consistent thing the user reads at-a-glance everywhere.
|
||||
*
|
||||
* All variants render in 1 row, 1 cell tall. Width defaults to 24
|
||||
* which is wide enough for "10% increments are visible to the eye"
|
||||
* but narrow enough to fit beside other status info.
|
||||
*/
|
||||
|
||||
import { Box, Text } from "ink";
|
||||
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React in value scope for JSX compilation
|
||||
import React from "react";
|
||||
import { COLOR, GLYPH } from "./theme.js";
|
||||
|
||||
export interface CharBarProps {
|
||||
/** 0–100 (clamped). Negative or NaN → 0; >100 → 100. */
|
||||
pct: number;
|
||||
/** Cell count. Default 24. Min 4 enforced so the bar is at least readable. */
|
||||
width?: number;
|
||||
/** Filled-cell color. Defaults to brand cyan. */
|
||||
color?: string;
|
||||
/** Empty-cell color. Defaults to dim slate. */
|
||||
emptyColor?: string;
|
||||
/**
|
||||
* Whether to render the percentage label after the bar. Off when the
|
||||
* caller wants to put its own meta after (e.g. "12 of 30 done").
|
||||
*/
|
||||
showLabel?: boolean;
|
||||
/** Optional label override (default: "{pct}%"). */
|
||||
label?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Single-color progress bar. Render shape:
|
||||
* `████████████░░░░░░░░░░░░ 50%`
|
||||
*
|
||||
* Filled section is `█` in `color`, empty section is `░` in
|
||||
* `emptyColor`. Label sits in the same row, dim by default.
|
||||
*/
|
||||
export function CharBar({
|
||||
pct,
|
||||
width = 24,
|
||||
color = COLOR.primary,
|
||||
emptyColor,
|
||||
showLabel = true,
|
||||
label,
|
||||
}: CharBarProps): React.ReactElement {
|
||||
const total = Math.max(4, width);
|
||||
const clamped = Math.max(0, Math.min(100, Number.isFinite(pct) ? pct : 0));
|
||||
const filled = Math.round((total * clamped) / 100);
|
||||
return (
|
||||
<Box>
|
||||
<Text color={color}>{GLYPH.block.repeat(filled)}</Text>
|
||||
<Text color={emptyColor ?? COLOR.info} dimColor>
|
||||
{GLYPH.shade1.repeat(total - filled)}
|
||||
</Text>
|
||||
{showLabel ? <Text dimColor>{` ${label ?? `${Math.round(clamped)}%`}`}</Text> : null}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
export interface StackedSegment {
|
||||
/** Percent of the total width this segment occupies. 0–100. */
|
||||
pct: number;
|
||||
color: string;
|
||||
/** Optional label (used by legend renderer; not rendered in the bar). */
|
||||
label?: string;
|
||||
}
|
||||
|
||||
export interface StackedCharBarProps {
|
||||
segments: readonly StackedSegment[];
|
||||
width?: number;
|
||||
/** Color of the trailing "free / unused" cells. */
|
||||
emptyColor?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stacked progress bar. Multiple colored segments + a trailing empty
|
||||
* region. Rendered left-to-right in segment order; if the segments'
|
||||
* pcts sum >100 the trailing empty just becomes 0.
|
||||
*
|
||||
* Used by `/context` to break down system / tools / log / input
|
||||
* occupancy across the prompt budget.
|
||||
*/
|
||||
export function StackedCharBar({
|
||||
segments,
|
||||
width = 32,
|
||||
emptyColor,
|
||||
}: StackedCharBarProps): React.ReactElement {
|
||||
const total = Math.max(4, width);
|
||||
const cells = segments.map((s) => Math.max(0, Math.round((total * s.pct) / 100)));
|
||||
const used = cells.reduce((acc, n) => acc + n, 0);
|
||||
const empty = Math.max(0, total - used);
|
||||
return (
|
||||
<Box>
|
||||
{segments.map((seg, i) => (
|
||||
// biome-ignore lint/suspicious/noArrayIndexKey: ordered, fixed-shape
|
||||
<Text key={`seg-${i}`} color={seg.color}>
|
||||
{GLYPH.block.repeat(cells[i] ?? 0)}
|
||||
</Text>
|
||||
))}
|
||||
<Text color={emptyColor ?? COLOR.info} dimColor>
|
||||
{GLYPH.shade1.repeat(empty)}
|
||||
</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
import { Box, Text } from "ink";
|
||||
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React in value scope for JSX compilation
|
||||
import React from "react";
|
||||
import type { CacheFirstLoop } from "../../loop.js";
|
||||
import { DEEPSEEK_CONTEXT_TOKENS, DEFAULT_CONTEXT_TOKENS } from "../../telemetry.js";
|
||||
import { countTokens } from "../../tokenizer.js";
|
||||
import { formatTokens } from "./primitives.js";
|
||||
import { COLOR } from "./theme.js";
|
||||
|
||||
export interface CtxBreakdownData {
|
||||
systemTokens: number;
|
||||
toolsTokens: number;
|
||||
logTokens: number;
|
||||
inputTokens: number;
|
||||
ctxMax: number;
|
||||
toolsCount: number;
|
||||
logMessages: number;
|
||||
topTools: Array<{ name: string; tokens: number; turn: number }>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Walk the loop's prefix + log and tally tokens per category. Cheap
|
||||
* after the tokenizer warm-up (~100 ms first call, sub-ms after).
|
||||
* Memoize at the call site if used inside a render path.
|
||||
*/
|
||||
export function computeCtxBreakdown(loop: CacheFirstLoop): CtxBreakdownData {
|
||||
const systemTokens = countTokens(loop.prefix.system);
|
||||
const toolsTokens = countTokens(JSON.stringify(loop.prefix.toolSpecs));
|
||||
const entries = loop.log.toMessages();
|
||||
let userTokens = 0;
|
||||
let assistantTokens = 0;
|
||||
let toolResultTokens = 0;
|
||||
let toolCallTokens = 0;
|
||||
const toolBreakdown: Array<{ name: string; tokens: number; turn: number }> = [];
|
||||
let logTurn = 0;
|
||||
for (const e of entries) {
|
||||
const content = typeof e.content === "string" ? e.content : "";
|
||||
if (e.role === "user") {
|
||||
userTokens += countTokens(content);
|
||||
logTurn += 1;
|
||||
} else if (e.role === "assistant") {
|
||||
assistantTokens += countTokens(content);
|
||||
if (Array.isArray(e.tool_calls) && e.tool_calls.length > 0) {
|
||||
toolCallTokens += countTokens(JSON.stringify(e.tool_calls));
|
||||
}
|
||||
} else if (e.role === "tool") {
|
||||
const n = countTokens(content);
|
||||
toolResultTokens += n;
|
||||
toolBreakdown.push({ name: e.name ?? "?", tokens: n, turn: logTurn });
|
||||
}
|
||||
}
|
||||
const logTokens = userTokens + assistantTokens + toolResultTokens + toolCallTokens;
|
||||
const ctxMax = DEEPSEEK_CONTEXT_TOKENS[loop.model] ?? DEFAULT_CONTEXT_TOKENS;
|
||||
const topTools = [...toolBreakdown].sort((a, b) => b.tokens - a.tokens).slice(0, 5);
|
||||
return {
|
||||
systemTokens,
|
||||
toolsTokens,
|
||||
logTokens,
|
||||
inputTokens: 0,
|
||||
ctxMax,
|
||||
toolsCount: loop.prefix.toolSpecs.length,
|
||||
logMessages: entries.length,
|
||||
topTools,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 4-segment stacked bar with legend + top-tools list. Pushed to
|
||||
* scrollback by the `/context` slash; the always-on bottom footer
|
||||
* uses its own slim 1-row layout in `CtxFooter`.
|
||||
*/
|
||||
export function CtxBreakdownBlock({ data }: { data: CtxBreakdownData }): React.ReactElement {
|
||||
const total = data.systemTokens + data.toolsTokens + data.logTokens + data.inputTokens;
|
||||
const winPct = data.ctxMax > 0 ? Math.round((total / data.ctxMax) * 100) : 0;
|
||||
const barWidth = 48;
|
||||
const cellOf = (n: number) => (data.ctxMax > 0 ? Math.round((n / data.ctxMax) * barWidth) : 0);
|
||||
const sysCells = cellOf(data.systemTokens);
|
||||
const toolsCells = cellOf(data.toolsTokens);
|
||||
const logCells = cellOf(data.logTokens);
|
||||
const inputCells = cellOf(data.inputTokens);
|
||||
const used = sysCells + toolsCells + logCells + inputCells;
|
||||
const freeCells = Math.max(0, barWidth - used);
|
||||
const sevColor = winPct >= 80 ? COLOR.err : winPct >= 60 ? COLOR.warn : COLOR.ok;
|
||||
|
||||
return (
|
||||
<Box
|
||||
flexDirection="column"
|
||||
marginY={1}
|
||||
borderStyle="single"
|
||||
borderTop={false}
|
||||
borderRight={false}
|
||||
borderBottom={false}
|
||||
borderColor={COLOR.brand}
|
||||
paddingLeft={1}
|
||||
>
|
||||
<Box>
|
||||
<Text color={COLOR.brand} bold>
|
||||
▣ context
|
||||
</Text>
|
||||
<Text dimColor>{` ${formatTokens(total)} of ${formatTokens(data.ctxMax)}`}</Text>
|
||||
<Text dimColor>{" · "}</Text>
|
||||
<Text color={sevColor} bold>
|
||||
{`${winPct}%`}
|
||||
</Text>
|
||||
{winPct >= 80 ? (
|
||||
<Text color={COLOR.err} bold>
|
||||
{" · /compact"}
|
||||
</Text>
|
||||
) : null}
|
||||
</Box>
|
||||
<Box>
|
||||
<Text color={COLOR.brand}>{"█".repeat(sysCells)}</Text>
|
||||
<Text color={COLOR.accent}>{"█".repeat(toolsCells)}</Text>
|
||||
<Text color={COLOR.primary}>{"█".repeat(logCells)}</Text>
|
||||
<Text color={COLOR.tool}>{"█".repeat(inputCells)}</Text>
|
||||
<Text color={COLOR.info} dimColor>
|
||||
{"░".repeat(freeCells)}
|
||||
</Text>
|
||||
</Box>
|
||||
<Box>
|
||||
<Text color={COLOR.brand}>■</Text>
|
||||
<Text dimColor>{` system ${formatTokens(data.systemTokens)}`}</Text>
|
||||
<Text>{" "}</Text>
|
||||
<Text color={COLOR.accent}>■</Text>
|
||||
<Text dimColor>{` tools ${formatTokens(data.toolsTokens)}`}</Text>
|
||||
<Text dimColor>{` (${data.toolsCount})`}</Text>
|
||||
<Text>{" "}</Text>
|
||||
<Text color={COLOR.primary}>■</Text>
|
||||
<Text dimColor>{` log ${formatTokens(data.logTokens)}`}</Text>
|
||||
<Text dimColor>{` (${data.logMessages} msg)`}</Text>
|
||||
<Text>{" "}</Text>
|
||||
<Text color={COLOR.tool}>■</Text>
|
||||
<Text dimColor>{` input ${formatTokens(data.inputTokens)}`}</Text>
|
||||
</Box>
|
||||
{data.topTools.length > 0 ? (
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
<Text dimColor>{` top tool results by cost (${data.topTools.length}):`}</Text>
|
||||
{data.topTools.map((t) => (
|
||||
<Box key={`${t.turn}-${t.name}`}>
|
||||
<Text dimColor>{` turn ${String(t.turn).padStart(3)} `}</Text>
|
||||
<Text color={COLOR.info}>{t.name.padEnd(22)}</Text>
|
||||
<Text dimColor>{` ${formatTokens(t.tokens).padStart(8)}`}</Text>
|
||||
</Box>
|
||||
))}
|
||||
</Box>
|
||||
) : null}
|
||||
<Box marginTop={1}>
|
||||
<Text dimColor>{" /compact shrinks oversized tool results · /new wipes log"}</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { Box, Text } from "ink";
|
||||
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React in value scope for JSX compilation
|
||||
import React from "react";
|
||||
import { type Frame, frameToAnsi } from "../../frame/index.js";
|
||||
|
||||
/** Frame → JSX. One Box per row. */
|
||||
export function renderFrame(f: Frame, keyPrefix: string): React.ReactElement {
|
||||
return (
|
||||
<>
|
||||
{f.rows.map((row, i) => (
|
||||
// biome-ignore lint/suspicious/noArrayIndexKey: row index is the row's identity
|
||||
<Box key={`${keyPrefix}/${i}`} height={1} flexShrink={0}>
|
||||
<Text>{frameToAnsi({ width: f.width, rows: [row] })}</Text>
|
||||
</Box>
|
||||
))}
|
||||
</>
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,613 @@
|
||||
/**
|
||||
* Row-granular log rendering pipeline. Each `DisplayEvent` is
|
||||
* decomposed into one or more {@link LogItem}s — either a 1-row
|
||||
* inline `LogRow` (most chat noise: info / warn / error /
|
||||
* step-progress) or a multi-row atomic `LogBlock` (complex
|
||||
* components like plan / ctx-breakdown that we haven't broken
|
||||
* down yet).
|
||||
*
|
||||
* Why this exists: Ink's `overflow="hidden"` does NOT reliably clip
|
||||
* children with negative `marginTop` — content bleeds upward into
|
||||
* sibling regions (the chrome pills disappeared at scroll=0 in 0.13.0
|
||||
* because of exactly this). Clipping IS reliable for positive
|
||||
* overflow at the BOTTOM of a fixed-height parent. So instead of
|
||||
* fighting layout, we pre-flatten events into terminal-row units,
|
||||
* slice the row list, and render the slice as a stack of `<Box
|
||||
* height={1}>` items. Each item maps 1:1 to a terminal line, the
|
||||
* parent's overflow=hidden naturally clips overflow at the bottom,
|
||||
* and `justifyContent="flex-end"` (when at scroll=0) clips overflow
|
||||
* at the top by the same mechanism.
|
||||
*
|
||||
* Migration plan:
|
||||
* · 0.13.x : info / warn / error / step-progress → rows.
|
||||
* Everything else falls back to a single `LogBlock`
|
||||
* wrapping the existing `<EventRow>` component, so
|
||||
* the pipeline works end-to-end while complex roles
|
||||
* keep their old rendering.
|
||||
* · later : user / assistant text bodies → rows (split on \n,
|
||||
* one row per visual line).
|
||||
* · later : tool / edit_file diff → rows.
|
||||
* · later : plan / plan-replay / ctx-breakdown → rows.
|
||||
*
|
||||
* The slicer (`sliceLogItems`) treats `LogBlock`s as snap-points:
|
||||
* a partially-visible block at the viewport's top edge gets either
|
||||
* fully included or fully excluded, the user briefly "sticks" on
|
||||
* boundaries when wheel-scrolling through one. Once everything is
|
||||
* migrated to rows, scrolling is uniformly smooth.
|
||||
*/
|
||||
|
||||
import { Box, Text } from "ink";
|
||||
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React in value scope for JSX compilation
|
||||
import React from "react";
|
||||
import { type DisplayEvent, EventRow } from "./EventLog.js";
|
||||
import { COLOR } from "./theme.js";
|
||||
|
||||
/**
|
||||
* Greedy character-count wrap. Accurate for ASCII / Latin; CJK
|
||||
* (where one char ≈ 2 cells) under-counts, but the parent's
|
||||
* overflow="hidden" still clips the bleed — at worst a visually-
|
||||
* tight row, not a layout break. Word-aware wrap is a future polish;
|
||||
* for now we just need the row count to be close enough that the
|
||||
* slicer's row arithmetic and the scrollbar thumb position aren't
|
||||
* obviously off.
|
||||
*/
|
||||
function wrapToWidth(text: string, width: number): string[] {
|
||||
if (width <= 0) return [text];
|
||||
const out: string[] = [];
|
||||
for (const line of text.split("\n")) {
|
||||
if (line.length === 0) {
|
||||
out.push("");
|
||||
continue;
|
||||
}
|
||||
if (line.length <= width) {
|
||||
out.push(line);
|
||||
continue;
|
||||
}
|
||||
let i = 0;
|
||||
while (i < line.length) {
|
||||
out.push(line.slice(i, i + width));
|
||||
i += width;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* One terminal line. Always renders inside an outer `<Box height={1}
|
||||
* flexShrink={0}>` so the slicer's row arithmetic stays exact —
|
||||
* overlong content soft-wraps in Ink unless we constrain row height,
|
||||
* which we don't here, but the parent's `overflow="hidden"` clips
|
||||
* any wrap-induced overflow.
|
||||
*/
|
||||
export interface LogRow {
|
||||
kind: "row";
|
||||
/** Stable React key. Must be unique within the rendered slice. */
|
||||
id: string;
|
||||
content: React.ReactElement;
|
||||
}
|
||||
|
||||
/**
|
||||
* A multi-row atomic component. Used as the fall-back when an event
|
||||
* role hasn't been broken down into individual rows yet. The slicer
|
||||
* snaps to block boundaries — partially-visible blocks at the viewport
|
||||
* top either render in full or get excluded.
|
||||
*/
|
||||
export interface LogBlock {
|
||||
kind: "block";
|
||||
id: string;
|
||||
/** Estimated terminal row count. Used by the slicer for cumulative
|
||||
* row arithmetic. Over-estimates are safer (reserve more rows
|
||||
* than needed) than under-estimates (block crowds the viewport
|
||||
* and content past the bottom clips silently). */
|
||||
rows: number;
|
||||
content: React.ReactElement;
|
||||
}
|
||||
|
||||
export type LogItem = LogRow | LogBlock;
|
||||
|
||||
/**
|
||||
* Row count for an item, used by the slicer.
|
||||
* `LogRow` is always 1; `LogBlock` carries its own estimate.
|
||||
*/
|
||||
export function itemRows(item: LogItem): number {
|
||||
return item.kind === "row" ? 1 : item.rows;
|
||||
}
|
||||
|
||||
/**
|
||||
* Detect the leading glyph in an info-row text and pick a color tone.
|
||||
* Mirrors the existing dispatch in `EventLog.tsx` so migrated rows
|
||||
* look identical to the legacy renderer for the same event payload.
|
||||
*/
|
||||
function detectInfoTone(text: string): { lead: string; color: string; body: string } {
|
||||
const m = text.match(/^([▸▶▲⚠✓✗✖↻ⓘ])\s*(.*)$/s);
|
||||
const lead = m?.[1] ?? "▸";
|
||||
const body = m?.[2] ?? text;
|
||||
let color: string = COLOR.info;
|
||||
if (lead === "▲" || lead === "⚠") color = COLOR.warn;
|
||||
else if (lead === "✓") color = COLOR.ok;
|
||||
else if (lead === "✗" || lead === "✖") color = COLOR.err;
|
||||
else if (lead === "↻") color = COLOR.primary;
|
||||
return { lead, color, body };
|
||||
}
|
||||
|
||||
/**
|
||||
* Render a single accent-bar row. The bar is the left vertical
|
||||
* border of the wrapper Box; subsequent rows of the same event share
|
||||
* the bar's color so vertically-adjacent rows visually merge into one
|
||||
* continuous bar (which is what users read as "this is one log entry").
|
||||
*
|
||||
* `prefix` is rendered inline before the line's body; pass `null` for
|
||||
* continuation lines that should align under the body, not the glyph.
|
||||
*/
|
||||
function AccentRow({
|
||||
color,
|
||||
prefix,
|
||||
body,
|
||||
bodyColor,
|
||||
bodyDim,
|
||||
}: {
|
||||
color: string;
|
||||
prefix: React.ReactNode | null;
|
||||
body: string;
|
||||
bodyColor?: string;
|
||||
bodyDim?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<Box
|
||||
borderStyle="single"
|
||||
borderTop={false}
|
||||
borderRight={false}
|
||||
borderBottom={false}
|
||||
borderColor={color}
|
||||
paddingLeft={1}
|
||||
>
|
||||
{prefix}
|
||||
<Text color={bodyColor} dimColor={bodyDim}>
|
||||
{body}
|
||||
</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Decompose a plain "accent-bar + glyph + multiline text" event into
|
||||
* one row per visual line, word-wrapping at `width`. The first line
|
||||
* carries the glyph; continuation lines align under the body so they
|
||||
* read as one entry.
|
||||
*/
|
||||
function accentRows(
|
||||
baseId: string,
|
||||
glyph: string,
|
||||
glyphColor: string,
|
||||
text: string,
|
||||
bodyColor: string | undefined,
|
||||
bodyDim: boolean,
|
||||
width: number,
|
||||
): LogRow[] {
|
||||
// Reserve cells for the border (1) + paddingLeft (1) + glyph + 2-space
|
||||
// gap so the wrap width matches the visual content column.
|
||||
const indentCells = 1 + 1 + glyph.length + 2;
|
||||
const inner = Math.max(8, width - indentCells);
|
||||
const lines = wrapToWidth(text, inner);
|
||||
return lines.map((line, i) => ({
|
||||
kind: "row" as const,
|
||||
id: `${baseId}/${i}`,
|
||||
content:
|
||||
i === 0 ? (
|
||||
<AccentRow
|
||||
color={glyphColor}
|
||||
prefix={
|
||||
<>
|
||||
<Text color={glyphColor} bold>
|
||||
{glyph}
|
||||
</Text>
|
||||
<Text>{" "}</Text>
|
||||
</>
|
||||
}
|
||||
body={line}
|
||||
bodyColor={bodyColor}
|
||||
bodyDim={bodyDim}
|
||||
/>
|
||||
) : (
|
||||
<AccentRow
|
||||
color={glyphColor}
|
||||
prefix={<Text>{" ".repeat(glyph.length + 2)}</Text>}
|
||||
body={line}
|
||||
bodyColor={bodyColor}
|
||||
bodyDim={bodyDim}
|
||||
/>
|
||||
),
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Decompose a finished `assistant` event into rows so a long summary
|
||||
* scrolls one terminal line at a time. Header (glyph + model badge)
|
||||
* is its own row; body becomes one row per wrapped line under the
|
||||
* assistant accent bar; stats / repair occupy dedicated trailing rows.
|
||||
*
|
||||
* **Fall-through:** events that carry branch / reasoning / non-empty
|
||||
* planState fall back to the legacy `LogBlock` because those
|
||||
* sub-components have their own internal layout we haven't row-split
|
||||
* yet. This keeps every advanced-feature event readable; the dominant
|
||||
* case (a plain summary turn) gets row-level scrolling.
|
||||
*
|
||||
* **Trade-off:** the row body bypasses the markdown renderer, so
|
||||
* inline formatting (bold / italic / code spans) is rendered as plain
|
||||
* text. Most assistant prose reads fine without it, and the original
|
||||
* formatted text is still in `~/.reasonix/sessions/<name>.jsonl`. If
|
||||
* code-block fidelity matters, users can /transcript or pipe the file
|
||||
* to `bat`. Worth it for the scrolling win.
|
||||
*/
|
||||
function assistantToRows(event: DisplayEvent, projectRoot?: string, width = 80): LogItem[] {
|
||||
// Skip row migration for events with branch / reasoning / planState —
|
||||
// those sub-blocks have nested layout we'd lose by flattening, and
|
||||
// they're uncommon enough that LogBlock fall-back is fine for v1.
|
||||
const hasComplexSub =
|
||||
event.branch || event.reasoning || (event.planState && Object.keys(event.planState).length > 0);
|
||||
if (hasComplexSub) {
|
||||
return [
|
||||
{
|
||||
kind: "block",
|
||||
id: event.id,
|
||||
rows: estimatedHeight(event),
|
||||
content: <EventRow event={event} projectRoot={projectRoot} />,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
const items: LogItem[] = [];
|
||||
// Top spacer matches the legacy renderer's `marginTop={1}`.
|
||||
items.push({
|
||||
kind: "row",
|
||||
id: `${event.id}/spacer-top`,
|
||||
content: <Text> </Text>,
|
||||
});
|
||||
// Header: assistant glyph + (optional) model badge.
|
||||
items.push({
|
||||
kind: "row",
|
||||
id: `${event.id}/head`,
|
||||
content: (
|
||||
<Box>
|
||||
<Text color={COLOR.assistant} bold>
|
||||
{"◆"}
|
||||
</Text>
|
||||
{event.stats ? (
|
||||
<>
|
||||
<Text>{" "}</Text>
|
||||
<Text backgroundColor={COLOR.assistant} color="black" bold>
|
||||
{` ${event.stats.model.replace(/^deepseek-/, "")} `}
|
||||
</Text>
|
||||
</>
|
||||
) : null}
|
||||
</Box>
|
||||
),
|
||||
});
|
||||
// Body rows — one per wrapped line, all sharing the assistant
|
||||
// accent bar on the left so they read as one entry visually even
|
||||
// though they're independent rows for scroll arithmetic.
|
||||
const body = event.text || "(empty body — likely tool-call only)";
|
||||
const dim = !event.text;
|
||||
items.push(...accentRows(event.id, "", COLOR.assistant, body, COLOR.assistant, dim, width));
|
||||
// Repair note: single line, accent violet, indented under the body.
|
||||
if (event.repair) {
|
||||
items.push({
|
||||
kind: "row",
|
||||
id: `${event.id}/repair`,
|
||||
content: (
|
||||
<Box paddingLeft={2}>
|
||||
<Text color={COLOR.accent}>{event.repair}</Text>
|
||||
</Box>
|
||||
),
|
||||
});
|
||||
}
|
||||
// Stats line — inlined here (kept as a 1-row LogRow rather than a
|
||||
// LogBlock) so the user can scroll past it cleanly.
|
||||
if (event.stats) {
|
||||
const hit = (event.stats.cacheHitRatio * 100).toFixed(1);
|
||||
const hitColor =
|
||||
event.stats.cacheHitRatio >= 0.7
|
||||
? "#4ade80"
|
||||
: event.stats.cacheHitRatio >= 0.4
|
||||
? "#fcd34d"
|
||||
: "#f87171";
|
||||
items.push({
|
||||
kind: "row",
|
||||
id: `${event.id}/stats`,
|
||||
content: (
|
||||
<Box paddingLeft={2}>
|
||||
<Text color={hitColor} bold>
|
||||
{`⌬ ${hit}%`}
|
||||
</Text>
|
||||
<Text dimColor>{" · "}</Text>
|
||||
<Text color="#94a3b8">{"in "}</Text>
|
||||
<Text color="#67e8f9" bold>
|
||||
{event.stats.usage.promptTokens}
|
||||
</Text>
|
||||
<Text color="#94a3b8">{" → out "}</Text>
|
||||
<Text color="#c4b5fd" bold>
|
||||
{event.stats.usage.completionTokens}
|
||||
</Text>
|
||||
<Text dimColor>{" · "}</Text>
|
||||
<Text color="#86efac" bold>{`$${event.stats.cost.toFixed(6)}`}</Text>
|
||||
</Box>
|
||||
),
|
||||
});
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a single `DisplayEvent` to its row-pipeline representation.
|
||||
* Migrated roles return `LogRow[]` (one item per visual terminal line,
|
||||
* word-wrapped to `width`); everything else falls back to a single
|
||||
* `LogBlock` wrapping the legacy `<EventRow>` component.
|
||||
*
|
||||
* `projectRoot` is forwarded to the legacy renderer for fall-back
|
||||
* blocks (used by the markdown renderer to resolve relative paths).
|
||||
*
|
||||
* `width` is the terminal column count. Used to word-wrap accent rows
|
||||
* so a single long line decomposes into the right number of rows —
|
||||
* this matters for the slicer's row arithmetic and for the scrollbar
|
||||
* thumb position, both of which assume row count == visual lines.
|
||||
*/
|
||||
export function eventToItems(event: DisplayEvent, projectRoot?: string, width = 80): LogItem[] {
|
||||
if (event.role === "info") {
|
||||
const { lead, color, body } = detectInfoTone(event.text);
|
||||
return accentRows(event.id, lead, color, body, undefined, true, width);
|
||||
}
|
||||
if (event.role === "warning") {
|
||||
return accentRows(event.id, "▲ warn", COLOR.warn, event.text, COLOR.warn, false, width);
|
||||
}
|
||||
if (event.role === "error") {
|
||||
return accentRows(event.id, "✦ error", COLOR.err, event.text, COLOR.err, false, width);
|
||||
}
|
||||
if (event.role === "assistant" && !event.streaming) {
|
||||
return assistantToRows(event, projectRoot, width);
|
||||
}
|
||||
if (event.role === "step-progress") {
|
||||
const sp = event.stepProgress;
|
||||
const counter = sp && sp.total > 0 ? `${sp.completed}/${sp.total}` : "";
|
||||
const label = sp?.title ? `${sp.stepId} · ${sp.title}` : (sp?.stepId ?? "");
|
||||
const rows: LogRow[] = [];
|
||||
// marginTop={1} in the legacy renderer — emit one blank spacer row.
|
||||
rows.push({
|
||||
kind: "row",
|
||||
id: `${event.id}/spacer`,
|
||||
content: <Text> </Text>,
|
||||
});
|
||||
// Header row: green-on-black STEP pill + counter + label.
|
||||
rows.push({
|
||||
kind: "row",
|
||||
id: `${event.id}/head`,
|
||||
content: (
|
||||
<Box>
|
||||
<Text backgroundColor="#4ade80" color="black" bold>
|
||||
{" ✓ STEP "}
|
||||
</Text>
|
||||
{counter ? (
|
||||
<>
|
||||
<Text>{" "}</Text>
|
||||
<Text color="#4ade80" bold>
|
||||
{counter}
|
||||
</Text>
|
||||
</>
|
||||
) : null}
|
||||
<Text>{" "}</Text>
|
||||
<Text color="#86efac">{label}</Text>
|
||||
</Box>
|
||||
),
|
||||
});
|
||||
// Optional body lines (one per \n-split line).
|
||||
if (event.text) {
|
||||
for (const [i, line] of event.text.split("\n").entries()) {
|
||||
rows.push({
|
||||
kind: "row",
|
||||
id: `${event.id}/body/${i}`,
|
||||
content: (
|
||||
<Box paddingLeft={2}>
|
||||
<Text dimColor>{line}</Text>
|
||||
</Box>
|
||||
),
|
||||
});
|
||||
}
|
||||
}
|
||||
if (sp?.notes) {
|
||||
rows.push({
|
||||
kind: "row",
|
||||
id: `${event.id}/notes`,
|
||||
content: (
|
||||
<Box paddingLeft={2}>
|
||||
<Text color="#fbbf24" dimColor>
|
||||
{`note: ${sp.notes}`}
|
||||
</Text>
|
||||
</Box>
|
||||
),
|
||||
});
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
// Fallback: render the whole event as one atomic block via the
|
||||
// legacy `EventRow`. Estimates row count via a copy of the slicer's
|
||||
// heightOf logic. Once a role is migrated above, this branch stops
|
||||
// running for that role.
|
||||
return [
|
||||
{
|
||||
kind: "block",
|
||||
id: event.id,
|
||||
rows: estimatedHeight(event),
|
||||
content: <EventRow event={event} projectRoot={projectRoot} />,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Mirror of the slicer's `heightOfEvent` from App.tsx — kept in sync
|
||||
* by hand. Used only for fall-back `LogBlock`s; migrated roles
|
||||
* compute their row count exactly via the row count itself.
|
||||
*/
|
||||
function estimatedHeight(e: DisplayEvent): number {
|
||||
const text = e.text ?? "";
|
||||
const wrapLines = Math.max(0, Math.floor(text.length / 80));
|
||||
if (e.role === "user") return 3 + wrapLines;
|
||||
if (e.role === "assistant") {
|
||||
let h = 4 + wrapLines;
|
||||
if (e.reasoning) h += 3;
|
||||
if (e.branch) h += 4;
|
||||
return h;
|
||||
}
|
||||
if (e.role === "tool") {
|
||||
const isEditFile = e.toolName === "edit_file" || e.toolName?.endsWith("_edit_file");
|
||||
if (isEditFile) {
|
||||
const diffLines = (text.match(/\n/g)?.length ?? 0) + 1;
|
||||
return 6 + Math.min(20, diffLines);
|
||||
}
|
||||
return 2;
|
||||
}
|
||||
if (e.role === "plan" || e.role === "plan-replay" || e.role === "plan-resumed") return 10;
|
||||
if (e.role === "ctx-breakdown") return 7;
|
||||
return 2;
|
||||
}
|
||||
|
||||
export interface RowSlice {
|
||||
items: LogItem[];
|
||||
/** Highest valid scroll offset (rows). Caller clamps with this. */
|
||||
maxScrollRows: number;
|
||||
/** Total rows across all events (informational, e.g. for "↑ N rows above" hints). */
|
||||
totalRows: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Slice the flat `LogItem` list to fit `available` viewport rows,
|
||||
* scrolled up by `scrollOffsetRows` from the bottom.
|
||||
*
|
||||
* Snap behavior: if the viewport top edge would fall *inside* a
|
||||
* `LogBlock`, the block is included in full (so it might extend
|
||||
* partially above the viewport — clipped by the parent's flex-end
|
||||
* + overflow=hidden). The same trick that makes the BOTTOM of a tall
|
||||
* latest event readable is what makes block snap-rendering safe.
|
||||
*/
|
||||
export function sliceLogItems(
|
||||
items: readonly LogItem[],
|
||||
available: number,
|
||||
scrollOffsetRows: number,
|
||||
): RowSlice {
|
||||
if (items.length === 0) {
|
||||
return { items: [], maxScrollRows: 0, totalRows: 0 };
|
||||
}
|
||||
const heights = items.map(itemRows);
|
||||
const totalRows = heights.reduce((a, b) => a + b, 0);
|
||||
// Cap the scroll so the OLDEST viewport-full of rows (oldest line at
|
||||
// the top of the viewport) is reachable but the user never scrolls
|
||||
// past it into empty space. With `totalRows - 1` the user could
|
||||
// scroll until only one row remained visible — scrollbar at the top
|
||||
// and viewport mostly empty, which feels broken. Leaving a viewport-
|
||||
// worth of rows below the absolute top means Home / max-scroll lands
|
||||
// on a fully-populated viewport showing the start of the log.
|
||||
const maxScrollRows = Math.max(0, totalRows - available);
|
||||
const offset = Math.max(0, Math.min(scrollOffsetRows, maxScrollRows));
|
||||
|
||||
const viewportBottom = totalRows - offset;
|
||||
const viewportTop = Math.max(0, viewportBottom - available);
|
||||
|
||||
// Walk forward, picking items whose row range overlaps the viewport.
|
||||
// Items entirely above viewport are dropped; entirely below ends the
|
||||
// walk early.
|
||||
let cursor = 0;
|
||||
let firstIdx = -1;
|
||||
let lastIdx = -1;
|
||||
for (let i = 0; i < items.length; i++) {
|
||||
const eStart = cursor;
|
||||
const eEnd = cursor + heights[i]!;
|
||||
cursor = eEnd;
|
||||
if (eEnd <= viewportTop) continue;
|
||||
if (eStart >= viewportBottom) break;
|
||||
if (firstIdx === -1) firstIdx = i;
|
||||
lastIdx = i;
|
||||
}
|
||||
if (firstIdx === -1) {
|
||||
// Should not happen with clamped offset + non-empty items, but
|
||||
// fall back to "render the last item" so the user never sees a
|
||||
// blank middle.
|
||||
return { items: [items[items.length - 1]!], maxScrollRows, totalRows };
|
||||
}
|
||||
return {
|
||||
items: items.slice(firstIdx, lastIdx + 1),
|
||||
maxScrollRows,
|
||||
totalRows,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrap a `LogItem` in the height-1 (or natural-height for blocks) Box
|
||||
* that keeps the slicer's row arithmetic exact. `flexShrink={0}`
|
||||
* prevents Ink from squashing rows when the parent's content overflows.
|
||||
*/
|
||||
export function renderLogItem(item: LogItem): React.ReactElement {
|
||||
if (item.kind === "row") {
|
||||
return (
|
||||
<Box key={item.id} height={1} flexShrink={0}>
|
||||
{item.content}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Box key={item.id} flexShrink={0}>
|
||||
{item.content}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* One-row hint pinned at the bottom of the log viewport when the user
|
||||
* has scrolled up. Tells them how many rows of newer content sit
|
||||
* below the visible window and how to jump back. Hidden when the user
|
||||
* is at the bottom (offset === 0) since there's nothing to point to.
|
||||
*
|
||||
* `rowsBelow` is the same as the active `logScrollOffset` (rows from
|
||||
* the bottom that aren't currently visible).
|
||||
*/
|
||||
export function BottomHint({
|
||||
rowsBelow,
|
||||
totalRows,
|
||||
viewportRows,
|
||||
}: {
|
||||
rowsBelow: number;
|
||||
totalRows: number;
|
||||
viewportRows: number;
|
||||
}) {
|
||||
if (rowsBelow <= 0) return null;
|
||||
const maxScroll = Math.max(1, totalRows - viewportRows);
|
||||
const ratioFromTop = Math.max(0, Math.min(1, (totalRows - rowsBelow - viewportRows) / maxScroll));
|
||||
const pct = Math.round((1 - ratioFromTop) * 100);
|
||||
const rowsAbove = Math.max(0, totalRows - viewportRows - rowsBelow);
|
||||
const barCells = 16;
|
||||
const markerAt = Math.max(0, Math.min(barCells - 1, Math.round(ratioFromTop * (barCells - 1))));
|
||||
const left = "─".repeat(markerAt);
|
||||
const right = "─".repeat(barCells - 1 - markerAt);
|
||||
return (
|
||||
<Box height={1} flexShrink={0}>
|
||||
<Text color={COLOR.primary} bold>
|
||||
{`↑ ${rowsAbove}`}
|
||||
</Text>
|
||||
<Text>{" "}</Text>
|
||||
<Text dimColor>▕</Text>
|
||||
<Text color={COLOR.info} dimColor>
|
||||
{left}
|
||||
</Text>
|
||||
<Text color={COLOR.brand} bold>
|
||||
●
|
||||
</Text>
|
||||
<Text color={COLOR.info} dimColor>
|
||||
{right}
|
||||
</Text>
|
||||
<Text dimColor>▏</Text>
|
||||
<Text>{" "}</Text>
|
||||
<Text color={COLOR.primary} bold>{`${pct}%`}</Text>
|
||||
<Text>{" "}</Text>
|
||||
<Text color={COLOR.primary}>{`↓ ${rowsBelow}`}</Text>
|
||||
<Text dimColor>{" · End to jump · wheel to scroll"}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,395 @@
|
||||
/**
|
||||
* Markdown → Frame compiler. Reuses the existing block parser from
|
||||
* `markdown.tsx` (`parseBlocks`) but produces `Frame`s instead of
|
||||
* Ink JSX, so markdown-rich event bodies (assistant turns, plan
|
||||
* proposals) can flow through the row-pipeline slicer like every
|
||||
* other migrated role.
|
||||
*
|
||||
* Coverage in this first pass — most common 90% of model output:
|
||||
* · paragraphs with inline markup (bold, italic, code, link, strike)
|
||||
* · headings (#-#####)
|
||||
* · bullet lists (`- ` / `* ` / `1. `) including GFM task items
|
||||
* · fenced code blocks with bg tint per line
|
||||
* · blockquotes (left-border + dim text)
|
||||
* · horizontal rule
|
||||
*
|
||||
* Deferred — fall back to plain text:
|
||||
* · tables (multi-column layout, edge cases)
|
||||
* · edit blocks (Aider-style SEARCH/REPLACE — render as code)
|
||||
* · citations (link validation hints)
|
||||
*
|
||||
* Visual fidelity is "close" rather than "pixel-perfect" with the
|
||||
* existing Ink renderer. The trade-off (lost: nested-list spacing
|
||||
* polish, code-block syntax highlighting; gained: row-precise scroll
|
||||
* across long markdown bodies) was deemed worthwhile for the
|
||||
* row-pipeline migration.
|
||||
*/
|
||||
|
||||
import {
|
||||
type Cell,
|
||||
type Frame,
|
||||
type TextOpts,
|
||||
borderLeft,
|
||||
empty,
|
||||
pad,
|
||||
text,
|
||||
vstack,
|
||||
} from "../../frame/index.js";
|
||||
import { type Block, parseBlocks } from "./markdown.js";
|
||||
import { COLOR } from "./theme.js";
|
||||
|
||||
/**
|
||||
* Inline markup regex — same as `markdown.tsx`'s INLINE_RE. Matches
|
||||
* link / bold-italic / bold / triple-backtick code / single-backtick
|
||||
* code / strikethrough / italic / backslash escape.
|
||||
*/
|
||||
const INLINE_RE =
|
||||
/(\[([^\]\n]+)\]\(([^)\n]+)\)|\*\*\*([^*\n]+?)\*\*\*|\*\*([^*\n]+?)\*\*|```([^\n]+?)```|`([^`\n]+?)`|~~([^~\n]+?)~~|(?<![*\w])\*([^*\n]+?)\*(?!\w)|\\([*_~`[\](){}#+\-.!\\]))/g;
|
||||
|
||||
/** One styled segment of an inline-parsed paragraph: a string + the
|
||||
* text-style options to apply to it as a single cell run. */
|
||||
interface InlineSegment {
|
||||
text: string;
|
||||
opts: Omit<TextOpts, "width">;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a single paragraph's inline markup into a list of styled
|
||||
* segments. The base style flows through unchanged-text segments;
|
||||
* each markup match overrides with its own style (bold, italic,
|
||||
* code = bg + cyan fg, link = underline + accent, strike = dim).
|
||||
*/
|
||||
function parseInline(input: string, baseOpts: Omit<TextOpts, "width">): InlineSegment[] {
|
||||
const out: InlineSegment[] = [];
|
||||
let lastEnd = 0;
|
||||
// The regex is /g so we must reset lastIndex when reusing it.
|
||||
INLINE_RE.lastIndex = 0;
|
||||
for (let m = INLINE_RE.exec(input); m !== null; m = INLINE_RE.exec(input)) {
|
||||
if (m.index > lastEnd) {
|
||||
out.push({ text: input.slice(lastEnd, m.index), opts: baseOpts });
|
||||
}
|
||||
const linkText = m[2];
|
||||
const linkUrl = m[3];
|
||||
const boldItalic = m[4];
|
||||
const bold = m[5];
|
||||
const code3 = m[6];
|
||||
const code1 = m[7];
|
||||
const strike = m[8];
|
||||
const italic = m[9];
|
||||
const escapeChar = m[10];
|
||||
if (linkText !== undefined) {
|
||||
out.push({
|
||||
text: linkText,
|
||||
opts: { ...baseOpts, fg: COLOR.accent, underline: true, href: linkUrl },
|
||||
});
|
||||
} else if (boldItalic !== undefined) {
|
||||
out.push({ text: boldItalic, opts: { ...baseOpts, bold: true, italic: true } });
|
||||
} else if (bold !== undefined) {
|
||||
out.push({ text: bold, opts: { ...baseOpts, bold: true } });
|
||||
} else if (code3 !== undefined) {
|
||||
// Strip leading "lang " prefix (consistent with the legacy renderer)
|
||||
const stripped = code3.replace(/^(\w+)\s+/, "");
|
||||
out.push({ text: stripped, opts: { ...baseOpts, fg: "#67e8f9", bg: "#0f172a" } });
|
||||
} else if (code1 !== undefined) {
|
||||
out.push({ text: code1, opts: { ...baseOpts, fg: "#67e8f9", bg: "#0f172a" } });
|
||||
} else if (strike !== undefined) {
|
||||
out.push({ text: strike, opts: { ...baseOpts, dim: true } });
|
||||
} else if (italic !== undefined) {
|
||||
out.push({ text: italic, opts: { ...baseOpts, italic: true } });
|
||||
} else if (escapeChar !== undefined) {
|
||||
out.push({ text: escapeChar, opts: baseOpts });
|
||||
}
|
||||
lastEnd = m.index + m[0]!.length;
|
||||
}
|
||||
if (lastEnd < input.length) {
|
||||
out.push({ text: input.slice(lastEnd), opts: baseOpts });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Render a list of styled segments as a Frame, wrapping at `width`.
|
||||
* Word-friendly wrap: prefers to break at whitespace; falls back to
|
||||
* mid-segment break when a single segment exceeds the line budget.
|
||||
*
|
||||
* Implementation: convert each segment to a list of (cell, style)
|
||||
* pairs accumulated linearly, then emit rows as the running column
|
||||
* total reaches `width`. This keeps the wrap logic in ONE place
|
||||
* rather than duplicating it per segment style.
|
||||
*/
|
||||
function segmentsToFrame(segs: readonly InlineSegment[], width: number): Frame {
|
||||
if (width <= 0) return empty(0);
|
||||
// Build a flat list of "atoms" — each atom is one grapheme + its
|
||||
// style. We reuse Frame's text() to handle grapheme width / 2-wide
|
||||
// chars correctly: rendering each segment to a 1-row Frame at a
|
||||
// very wide budget gives back its cell array, which we splice
|
||||
// together for the wrap.
|
||||
const atoms: Cell[] = [];
|
||||
for (const seg of segs) {
|
||||
if (!seg.text) continue;
|
||||
// Use a generous width so the segment doesn't pre-wrap inside text()
|
||||
const f = text(seg.text, { ...seg.opts, width: Math.max(width, seg.text.length * 2 + 4) });
|
||||
if (f.rows.length > 0) {
|
||||
// Strip trailing space-padding the text() helper adds; the
|
||||
// segment's actual cells are the leading non-space prefix.
|
||||
let stop = f.rows[0]!.length;
|
||||
while (
|
||||
stop > 0 &&
|
||||
f.rows[0]![stop - 1]!.char === " " &&
|
||||
f.rows[0]![stop - 1]!.fg === undefined &&
|
||||
f.rows[0]![stop - 1]!.bg === undefined
|
||||
) {
|
||||
stop--;
|
||||
}
|
||||
for (let i = 0; i < stop; i++) atoms.push(f.rows[0]![i]!);
|
||||
}
|
||||
// Multi-line segments (rare with inline markup, but possible if
|
||||
// text contained \n) — append blank cells then continue.
|
||||
for (let li = 1; li < f.rows.length; li++) {
|
||||
// Insert a newline marker via a sentinel cell? Simpler: emit
|
||||
// a hard-break row right now and continue with the next line.
|
||||
// To keep `atoms` 1-D, we encode \n as a special cell char and
|
||||
// handle in the wrap loop. Use a SOH sentinel char that won't
|
||||
// appear in real text.
|
||||
atoms.push({ char: "\n", width: 1 });
|
||||
let stop = f.rows[li]!.length;
|
||||
while (
|
||||
stop > 0 &&
|
||||
f.rows[li]![stop - 1]!.char === " " &&
|
||||
f.rows[li]![stop - 1]!.fg === undefined
|
||||
) {
|
||||
stop--;
|
||||
}
|
||||
for (let i = 0; i < stop; i++) atoms.push(f.rows[li]![i]!);
|
||||
}
|
||||
}
|
||||
// Greedy wrap: walk atoms, accumulate cells until current row width
|
||||
// would exceed `width` (skipping tail cells from the count); on a
|
||||
// newline atom, force a row break.
|
||||
const SPACE: Cell = { char: " ", width: 1 };
|
||||
const rows: Cell[][] = [];
|
||||
let cur: Cell[] = [];
|
||||
let curW = 0;
|
||||
let lastSpaceIdx = -1;
|
||||
const flushRow = (forceNewline = false): void => {
|
||||
while (curW < width) {
|
||||
cur.push(SPACE);
|
||||
curW += 1;
|
||||
}
|
||||
rows.push(cur);
|
||||
cur = [];
|
||||
curW = 0;
|
||||
lastSpaceIdx = -1;
|
||||
if (forceNewline) return;
|
||||
};
|
||||
for (const a of atoms) {
|
||||
if (a.char === "\n") {
|
||||
flushRow(true);
|
||||
continue;
|
||||
}
|
||||
const w = a.tail ? 0 : a.width;
|
||||
if (curW + w > width) {
|
||||
// Try to break at the last whitespace we saw — soft wrap.
|
||||
if (lastSpaceIdx >= 0 && lastSpaceIdx > 0) {
|
||||
// Cut the row at lastSpaceIdx; carry overflow atoms into the
|
||||
// next row.
|
||||
const overflow = cur.slice(lastSpaceIdx + 1);
|
||||
cur = cur.slice(0, lastSpaceIdx);
|
||||
let newW = 0;
|
||||
for (const c of cur) newW += c.tail ? 0 : c.width;
|
||||
// Pad current row to width
|
||||
while (newW < width) {
|
||||
cur.push(SPACE);
|
||||
newW += 1;
|
||||
}
|
||||
rows.push(cur);
|
||||
cur = overflow;
|
||||
curW = 0;
|
||||
for (const c of cur) curW += c.tail ? 0 : c.width;
|
||||
lastSpaceIdx = -1;
|
||||
} else {
|
||||
// No whitespace to break at — hard wrap.
|
||||
flushRow();
|
||||
}
|
||||
}
|
||||
if (a.char === " ") lastSpaceIdx = cur.length;
|
||||
cur.push(a);
|
||||
curW += w;
|
||||
}
|
||||
if (cur.length > 0 || rows.length === 0) {
|
||||
flushRow();
|
||||
}
|
||||
return { width, rows };
|
||||
}
|
||||
|
||||
/**
|
||||
* Render one paragraph as a Frame. Inline markup is parsed and the
|
||||
* resulting styled segments are wrapped to `width`.
|
||||
*/
|
||||
function paragraphFrame(p: { text: string }, width: number): Frame {
|
||||
const segs = parseInline(p.text, {});
|
||||
return segmentsToFrame(segs, width);
|
||||
}
|
||||
|
||||
/**
|
||||
* Render a heading as a Frame. Levels 1-3 render in bold + brand
|
||||
* color; levels 4-6 render in bold + dim accent. Followed by a
|
||||
* trailing blank row for spacing — mirrors the legacy renderer's
|
||||
* `marginBottom={1}`.
|
||||
*/
|
||||
function headingFrame(h: { level: number; text: string }, width: number): Frame {
|
||||
const isMajor = h.level <= 3;
|
||||
const fg = isMajor ? COLOR.brand : COLOR.accent;
|
||||
const segs = parseInline(h.text, { bold: true, fg, dim: !isMajor });
|
||||
return vstack(segmentsToFrame(segs, width), text("", { width }));
|
||||
}
|
||||
|
||||
/**
|
||||
* Render a bullet list as a Frame. Each item: bullet glyph (for
|
||||
* tasks: `[ ]` / `[x]`) + space + item text (with inline markup).
|
||||
* Continuation lines align under the body, not under the bullet.
|
||||
*/
|
||||
function bulletListFrame(
|
||||
b: { items: { text: string; task?: "done" | "todo" }[]; ordered?: boolean },
|
||||
width: number,
|
||||
): Frame {
|
||||
const rows: Frame[] = [];
|
||||
for (let i = 0; i < b.items.length; i++) {
|
||||
const item = b.items[i]!;
|
||||
let prefix: string;
|
||||
let prefixOpts: Omit<TextOpts, "width">;
|
||||
if (item.task === "done") {
|
||||
prefix = "[x] ";
|
||||
prefixOpts = { fg: COLOR.ok, bold: true };
|
||||
} else if (item.task === "todo") {
|
||||
prefix = "[ ] ";
|
||||
prefixOpts = { fg: COLOR.warn, bold: true };
|
||||
} else if (b.ordered) {
|
||||
prefix = `${i + 1}. `;
|
||||
prefixOpts = { fg: COLOR.info, bold: true };
|
||||
} else {
|
||||
prefix = "• ";
|
||||
prefixOpts = { fg: COLOR.info, bold: true };
|
||||
}
|
||||
const prefixWidth = prefix.length;
|
||||
const indentRow = " ".repeat(prefixWidth);
|
||||
const innerSegs = parseInline(item.text, {});
|
||||
const innerFrame = segmentsToFrame(innerSegs, Math.max(8, width - prefixWidth));
|
||||
// Decorate first line with prefix, subsequent lines with spaces.
|
||||
const decoratedRows: Frame[] = innerFrame.rows.map((r, li) => {
|
||||
const indent =
|
||||
li === 0
|
||||
? text(prefix, { width: prefixWidth, ...prefixOpts })
|
||||
: text(indentRow, { width: prefixWidth });
|
||||
return {
|
||||
width: prefixWidth + innerFrame.width,
|
||||
rows: [[...indent.rows[0]!, ...r]],
|
||||
};
|
||||
});
|
||||
rows.push(...decoratedRows);
|
||||
}
|
||||
return vstack(...rows);
|
||||
}
|
||||
|
||||
/**
|
||||
* Render a fenced code block as a Frame. Each line gets a uniform
|
||||
* dark bg + cyan fg styling; the optional language tag becomes a
|
||||
* dim caption on the first row above the code.
|
||||
*/
|
||||
function codeBlockFrame(c: { lang: string; text: string }, width: number): Frame {
|
||||
const lines = c.text.split("\n");
|
||||
const rows: Frame[] = [];
|
||||
if (c.lang) {
|
||||
rows.push(text(c.lang, { width, fg: COLOR.info, dim: true, italic: true }));
|
||||
}
|
||||
for (const line of lines) {
|
||||
rows.push(text(line || " ", { width, fg: "#67e8f9", bg: "#0f172a" }));
|
||||
}
|
||||
return vstack(...rows);
|
||||
}
|
||||
|
||||
/**
|
||||
* Render a blockquote: left-border + dim text, mirroring the
|
||||
* conversation column visual idiom. Children are rendered
|
||||
* recursively so nested quotes / lists / code render correctly.
|
||||
*/
|
||||
function blockquoteFrame(bq: { children: Block[] }, width: number): Frame {
|
||||
const inner = bq.children.map((child) => blockToFrame(child, Math.max(8, width - 2)));
|
||||
const stacked = inner.length === 0 ? empty(Math.max(8, width - 2)) : vstack(...inner);
|
||||
return borderLeft(pad(stacked, 0, 0, 0, 1), COLOR.info);
|
||||
}
|
||||
|
||||
/**
|
||||
* Render a horizontal rule: a single dim row of `─`.
|
||||
*/
|
||||
function hrFrame(width: number): Frame {
|
||||
return text("─".repeat(width), { width, fg: COLOR.info, dim: true });
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a parsed Block to a Frame. Falls back to plain-text for
|
||||
* the block kinds we haven't migrated yet (table, edit-block); the
|
||||
* trade-off is consistent — those are rare-but-rich shapes whose
|
||||
* existing Ink renderers we keep until the next migration phase.
|
||||
*/
|
||||
function blockToFrame(b: Block, width: number): Frame {
|
||||
switch (b.kind) {
|
||||
case "paragraph":
|
||||
return paragraphFrame(b, width);
|
||||
case "heading":
|
||||
return headingFrame(b, width);
|
||||
case "bullet":
|
||||
return bulletListFrame(b, width);
|
||||
case "code":
|
||||
return codeBlockFrame(b, width);
|
||||
case "quote":
|
||||
return blockquoteFrame(b, width);
|
||||
case "hr":
|
||||
return hrFrame(width);
|
||||
case "table":
|
||||
// Tables: render as plain-text rows for now; full table layout
|
||||
// is a future migration. Header gets bold, body rows dim.
|
||||
return vstack(
|
||||
text(b.header.join(" | "), { width, bold: true }),
|
||||
text(b.header.map(() => "─").join("─┼─"), { width, dim: true }),
|
||||
text(b.rows.map((r) => r.join(" | ")).join("\n"), { width, dim: true }),
|
||||
);
|
||||
case "edit-block":
|
||||
// Aider edit blocks: render filename + SEARCH/REPLACE summaries
|
||||
// as plain text. The full diff renderer lives in EditBlockRow
|
||||
// which we keep on the legacy Ink path until migration.
|
||||
return text(`${b.filename}\n<<< SEARCH\n${b.search}\n=======\n${b.replace}\n>>> REPLACE`, {
|
||||
width,
|
||||
dim: true,
|
||||
});
|
||||
default:
|
||||
// Unknown block kind — should never happen given the parser's
|
||||
// exhaustive Block union, but stay defensive.
|
||||
return empty(width);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Public entry point: parse `markdown` and return a Frame at the
|
||||
* given `width`. Each block becomes a Frame, separated by a blank
|
||||
* row except where the block already includes its own trailing
|
||||
* spacer (headings, bullet lists).
|
||||
*/
|
||||
export function markdownToFrame(markdown: string, width: number): Frame {
|
||||
if (!markdown) return empty(width);
|
||||
const blocks = parseBlocks(markdown);
|
||||
if (blocks.length === 0) return empty(width);
|
||||
const frames: Frame[] = [];
|
||||
for (let i = 0; i < blocks.length; i++) {
|
||||
const b = blocks[i]!;
|
||||
frames.push(blockToFrame(b, width));
|
||||
// Inter-block separator. Skip after blocks that already include
|
||||
// their own trailing spacer (headings) so we don't double-space.
|
||||
const isLast = i === blocks.length - 1;
|
||||
const carriesOwnSpacer = b.kind === "heading";
|
||||
if (!isLast && !carriesOwnSpacer) {
|
||||
frames.push(text("", { width }));
|
||||
}
|
||||
}
|
||||
return vstack(...frames);
|
||||
}
|
||||
+55
-6
@@ -439,6 +439,42 @@ function extOf(p: string): string {
|
||||
return m ? m[0] : "";
|
||||
}
|
||||
|
||||
/**
|
||||
* mtime-keyed line-count cache. The expensive part of validating a
|
||||
* citation with a line number is reading the entire file just to
|
||||
* count newlines — for a 5k-line source file, that's a real
|
||||
* synchronous read on every assistant_final commit that cites it.
|
||||
* Across a session, the model often cites the same file repeatedly
|
||||
* (the file it's currently editing), so the same read happens N
|
||||
* times for the same file content.
|
||||
*
|
||||
* We cache `lineCount` keyed by absolute path, and invalidate by
|
||||
* comparing `mtimeMs` against the latest `statSync` (which we're
|
||||
* already calling for the file-exists check, so the cache hit is
|
||||
* free). Cap entries to 256 to avoid unbounded growth across long
|
||||
* sessions; LRU-evict on overflow with a simple FIFO since hot
|
||||
* citations get re-inserted on use anyway.
|
||||
*/
|
||||
const lineCountCache = new Map<string, { mtimeMs: number; lineCount: number }>();
|
||||
const LINE_COUNT_CACHE_LIMIT = 256;
|
||||
|
||||
function getCachedLineCount(fullPath: string, mtimeMs: number): number | null {
|
||||
const hit = lineCountCache.get(fullPath);
|
||||
if (!hit || hit.mtimeMs !== mtimeMs) return null;
|
||||
// Refresh insertion order so this entry is "hot" for FIFO eviction.
|
||||
lineCountCache.delete(fullPath);
|
||||
lineCountCache.set(fullPath, hit);
|
||||
return hit.lineCount;
|
||||
}
|
||||
|
||||
function setCachedLineCount(fullPath: string, mtimeMs: number, lineCount: number): void {
|
||||
if (lineCountCache.size >= LINE_COUNT_CACHE_LIMIT) {
|
||||
const oldest = lineCountCache.keys().next().value;
|
||||
if (oldest !== undefined) lineCountCache.delete(oldest);
|
||||
}
|
||||
lineCountCache.set(fullPath, { mtimeMs, lineCount });
|
||||
}
|
||||
|
||||
export function validateCitation(url: string, projectRoot: string): CitationStatus {
|
||||
const parts = parseCitationUrl(url);
|
||||
if (!parts || !parts.path) return { ok: false, reason: "empty path" };
|
||||
@@ -476,11 +512,14 @@ export function validateCitation(url: string, projectRoot: string): CitationStat
|
||||
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;
|
||||
try {
|
||||
lineCount = readFileSync(fullPath, "utf8").split("\n").length;
|
||||
} catch {
|
||||
return { ok: false, reason: "unreadable" };
|
||||
let lineCount = getCachedLineCount(fullPath, stat.mtimeMs);
|
||||
if (lineCount === null) {
|
||||
try {
|
||||
lineCount = readFileSync(fullPath, "utf8").split("\n").length;
|
||||
} catch {
|
||||
return { ok: false, reason: "unreadable" };
|
||||
}
|
||||
setCachedLineCount(fullPath, stat.mtimeMs, lineCount);
|
||||
}
|
||||
if (parts.startLine < 1 || parts.startLine > lineCount) {
|
||||
return { ok: false, reason: `line ${parts.startLine} > ${lineCount}` };
|
||||
@@ -791,7 +830,7 @@ interface TableBlock {
|
||||
rows: string[][];
|
||||
}
|
||||
|
||||
type Block =
|
||||
export type Block =
|
||||
| ParagraphBlock
|
||||
| HeadingBlock
|
||||
| BulletBlock
|
||||
@@ -800,6 +839,16 @@ type Block =
|
||||
| HrBlock
|
||||
| EditBlockView
|
||||
| TableBlock;
|
||||
export type {
|
||||
ParagraphBlock,
|
||||
HeadingBlock,
|
||||
BulletBlock,
|
||||
BlockquoteBlock,
|
||||
CodeBlock,
|
||||
HrBlock,
|
||||
EditBlockView,
|
||||
TableBlock,
|
||||
};
|
||||
|
||||
export function parseBlocks(raw: string): Block[] {
|
||||
const lines = raw.split(/\r?\n/);
|
||||
|
||||
+83
-37
@@ -25,55 +25,101 @@ import type { PresetName } from "../../config.js";
|
||||
export interface PresetSettings {
|
||||
model: string;
|
||||
/**
|
||||
* Reasoning-effort cap sent per turn. `high` = shorter chain of
|
||||
* thought (cheaper, faster); `max` = agent-class default (deeper,
|
||||
* more output tokens). DeepSeek ignores this field on non-thinking
|
||||
* calls, so it's safe to pin across models.
|
||||
* 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";
|
||||
/**
|
||||
* Pillar-2 plan-state extraction. Every preset ships `false` (see
|
||||
* module header); kept in the shape so a user who later flips it on
|
||||
* at runtime still round-trips cleanly. `/harvest on` toggles it.
|
||||
* 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. Every preset ships `1` (off). `/branch N` with
|
||||
* N>=2 is the only way to enable self-consistency sampling.
|
||||
*/
|
||||
/** Branch budget. Always 1 in presets — opt-in via /branch. */
|
||||
branch: number;
|
||||
}
|
||||
|
||||
export const PRESETS: Record<PresetName, PresetSettings> = {
|
||||
// fast — flash + effort=high. Quick Q&A, one-line tweaks, anything
|
||||
// where shallow reasoning is enough. Cheapest turn possible.
|
||||
fast: { model: "deepseek-v4-flash", reasoningEffort: "high", harvest: false, branch: 1 },
|
||||
// smart — flash + effort=max. Full thinking budget on the cheap
|
||||
// model. The default: handles 90%+ of coding work at a fraction
|
||||
// of pro's cost.
|
||||
smart: { model: "deepseek-v4-flash", reasoningEffort: "max", harvest: false, branch: 1 },
|
||||
// max — pro + effort=max. Frontier model for hard tasks: cross-
|
||||
// file architecture, subtle bug hunts, anything where flash's
|
||||
// reasoning has measurably failed. ~12× per-token vs flash; save
|
||||
// for when you need it, or use `/pro` to escalate a single turn.
|
||||
max: { model: "deepseek-v4-pro", reasoningEffort: "max", harvest: false, branch: 1 },
|
||||
};
|
||||
|
||||
export const PRESET_DESCRIPTIONS: Record<PresetName, { headline: string; cost: string }> = {
|
||||
fast: {
|
||||
headline: "v4-flash · effort=high",
|
||||
cost: "cheapest · quick Q&A, one-line edits",
|
||||
/**
|
||||
* 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: "v4-flash · effort=max",
|
||||
cost: "~1.5× fast · default · day-to-day coding",
|
||||
// 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: "v4-pro · effort=max",
|
||||
cost: "~12× fast · hard single-shots · use /pro for a single-turn bump",
|
||||
// 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 legacy) to its settings.
|
||||
* Canonical names (`auto | flash | pro`) hit the PRESETS table.
|
||||
* Legacy names from the v0.5–v0.11 vocabulary still resolve to their
|
||||
* old behavior so a `~/.reasonix/config.json` written by an older
|
||||
* Reasonix doesn't suddenly start producing different model + effort
|
||||
* choices on upgrade:
|
||||
* - `fast` → flash with effort=high (cheaper, predictable)
|
||||
* - `smart` → auto (flash + max + auto-escalate; the old default)
|
||||
* - `max` → pro (pro + max)
|
||||
* Anything else collapses to `auto`.
|
||||
*/
|
||||
export function resolvePreset(name: PresetName | undefined): PresetSettings {
|
||||
return PRESETS[name ?? "smart"];
|
||||
if (name === "auto" || name === "flash" || name === "pro") return PRESETS[name];
|
||||
if (name === "fast") return { ...PRESETS.flash, reasoningEffort: "high" };
|
||||
if (name === "smart") return PRESETS.auto;
|
||||
if (name === "max") return PRESETS.pro;
|
||||
return PRESETS.auto;
|
||||
}
|
||||
|
||||
/** Canonical name for storage / display — unknown values become auto. */
|
||||
export function canonicalPresetName(name: PresetName | undefined): "auto" | "flash" | "pro" {
|
||||
if (name === "auto" || name === "flash" || name === "pro") return name;
|
||||
return "auto";
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
import { Text, useStdout } from "ink";
|
||||
// biome-ignore lint/style/useImportType: tsconfig jsx=react needs React in value scope for JSX compilation
|
||||
import React from "react";
|
||||
import { COLOR } from "./theme.js";
|
||||
|
||||
/**
|
||||
* Faint full-width horizontal rule. Width tracks the terminal columns
|
||||
* minus 2 cells so it lines up exactly under content rendered inside
|
||||
* a `paddingX={1}` parent — the standard chrome layout. Used by the
|
||||
* top chrome bar, the replay StatsPanel, and the bottom ctx footer.
|
||||
*/
|
||||
export function ChromeRule(): React.ReactElement {
|
||||
const { stdout } = useStdout();
|
||||
const cols = stdout?.columns ?? 80;
|
||||
const w = Math.max(20, cols - 2);
|
||||
return <Text dimColor>{"─".repeat(w)}</Text>;
|
||||
}
|
||||
|
||||
/** Compact binary-K formatter — `1234 → "1.2K"`, `131072 → "128K"`. */
|
||||
export function formatTokens(n: number): string {
|
||||
if (n < 1024) return String(n);
|
||||
const k = n / 1024;
|
||||
return k >= 100 ? `${k.toFixed(0)}K` : `${k.toFixed(1)}K`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Filled / empty progress bar. `▰▱` glyphs have distinct shapes so the
|
||||
* boundary stays visible even when the terminal collapses to 8-color slots.
|
||||
*/
|
||||
export function Bar({
|
||||
ratio,
|
||||
color,
|
||||
cells = 14,
|
||||
dim,
|
||||
}: {
|
||||
ratio: number;
|
||||
color: string;
|
||||
cells?: number;
|
||||
dim?: boolean;
|
||||
}): React.ReactElement {
|
||||
const filled = Math.max(0, Math.min(cells, Math.round(ratio * cells)));
|
||||
return (
|
||||
<Text>
|
||||
<Text color={color} dimColor={dim}>
|
||||
{"▰".repeat(filled)}
|
||||
</Text>
|
||||
<Text dimColor>{"▱".repeat(cells - filled)}</Text>
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* `▣ ctx ▰▰▱▱… 14K/128K (11%)` — the canonical context-pressure cell.
|
||||
* Used by the persistent footer (chat) and StatsPanel (replay). Color
|
||||
* thresholds match the `/compact` warning policy in the loop:
|
||||
* green <60% · amber 60-80% · red ≥80% (with `· /compact` hint).
|
||||
*/
|
||||
export function ContextCell({
|
||||
ratio,
|
||||
promptTokens,
|
||||
ctxMax,
|
||||
showBar,
|
||||
}: {
|
||||
ratio: number;
|
||||
promptTokens: number;
|
||||
ctxMax: number;
|
||||
showBar?: boolean;
|
||||
}): React.ReactElement {
|
||||
if (promptTokens === 0) {
|
||||
return (
|
||||
<Text>
|
||||
<Text color={COLOR.info} dimColor>
|
||||
{"▣ ctx "}
|
||||
</Text>
|
||||
<Text dimColor>— (no turns yet)</Text>
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
const color = ratio >= 0.8 ? COLOR.err : ratio >= 0.6 ? COLOR.warn : COLOR.ok;
|
||||
const pct = Math.round(ratio * 100);
|
||||
return (
|
||||
<Text>
|
||||
<Text color={COLOR.info}>{"▣ ctx "}</Text>
|
||||
<Bar ratio={ratio} color={color} cells={showBar ? 14 : 10} />
|
||||
<Text> </Text>
|
||||
<Text color={color} bold>
|
||||
{formatTokens(promptTokens)}/{formatTokens(ctxMax)}
|
||||
</Text>
|
||||
<Text dimColor> ({pct}%)</Text>
|
||||
{ratio >= 0.8 ? (
|
||||
<Text color={COLOR.err} bold>
|
||||
{" · /compact"}
|
||||
</Text>
|
||||
) : null}
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
@@ -5,9 +5,9 @@ export const SLASH_COMMANDS: readonly SlashCommandSpec[] = [
|
||||
{ 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"],
|
||||
argsHint: "<auto|flash|pro>",
|
||||
summary: "model bundle — auto escalates flash → pro, flash/pro lock",
|
||||
argCompleter: ["auto", "flash", "pro"],
|
||||
},
|
||||
{
|
||||
cmd: "model",
|
||||
@@ -40,6 +40,13 @@ export const SLASH_COMMANDS: readonly SlashCommandSpec[] = [
|
||||
summary: "arm v4-pro for the NEXT turn only (one-shot · auto-disarms after turn)",
|
||||
argCompleter: ["off"],
|
||||
},
|
||||
{
|
||||
cmd: "budget",
|
||||
argsHint: "[usd|off]",
|
||||
summary:
|
||||
"session USD cap — warns at 80%, refuses next turn at 100%. Off by default. /budget alone shows status",
|
||||
argCompleter: ["off", "1", "5", "10", "20", "50"],
|
||||
},
|
||||
{ cmd: "mcp", summary: "list MCP servers + tools attached to this session" },
|
||||
{
|
||||
cmd: "resource",
|
||||
@@ -76,6 +83,12 @@ export const SLASH_COMMANDS: readonly SlashCommandSpec[] = [
|
||||
"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>",
|
||||
@@ -91,10 +104,25 @@ export const SLASH_COMMANDS: readonly SlashCommandSpec[] = [
|
||||
summary:
|
||||
"cross-session cost dashboard (today / week / month / all-time · cache hit · vs Claude)",
|
||||
},
|
||||
{
|
||||
cmd: "mouse",
|
||||
argsHint: "[on|off]",
|
||||
summary:
|
||||
"toggle terminal mouse tracking · off by default (lets shift-drag copy work) · on enables wheel-scroll for log",
|
||||
argCompleter: ["on", "off"],
|
||||
},
|
||||
{
|
||||
cmd: "copy",
|
||||
summary:
|
||||
"freeze + dump the rendered log to main screen so terminal scrollback + drag-select can copy across viewports · any key returns",
|
||||
},
|
||||
{ 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",
|
||||
argsHint: "[on|off]",
|
||||
summary:
|
||||
"toggle the always-on context-breakdown footer (system / tools / log / input). no arg → flip; on/off → force",
|
||||
argCompleter: ["on", "off"],
|
||||
},
|
||||
{ cmd: "retry", summary: "truncate & resend your last message (fresh sample)" },
|
||||
{
|
||||
@@ -112,6 +140,11 @@ export const SLASH_COMMANDS: readonly SlashCommandSpec[] = [
|
||||
},
|
||||
{ cmd: "sessions", summary: "list saved sessions (current marked with ▸)" },
|
||||
{ cmd: "forget", summary: "delete the current session from disk" },
|
||||
{
|
||||
cmd: "prune-sessions",
|
||||
summary: "delete sessions idle ≥N days (default 90) — frees disk on long-time installs",
|
||||
argsHint: "[days]",
|
||||
},
|
||||
{ cmd: "setup", summary: "reminds you to exit and run `reasonix setup`" },
|
||||
{
|
||||
cmd: "semantic",
|
||||
@@ -171,6 +204,20 @@ export const SLASH_COMMANDS: readonly SlashCommandSpec[] = [
|
||||
summary: "git add -A && git commit -m ...",
|
||||
contextual: "code",
|
||||
},
|
||||
{
|
||||
cmd: "checkpoint",
|
||||
argsHint: "[name|list|forget <id>]",
|
||||
summary:
|
||||
"snapshot every file the session has touched (Cursor-style internal store, not git). /checkpoint alone lists.",
|
||||
contextual: "code",
|
||||
argCompleter: ["list", "forget"],
|
||||
},
|
||||
{
|
||||
cmd: "restore",
|
||||
argsHint: "<name|id>",
|
||||
summary: "roll back files to a named checkpoint (see /checkpoint list)",
|
||||
contextual: "code",
|
||||
},
|
||||
{
|
||||
cmd: "plan",
|
||||
argsHint: "[on|off]",
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
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";
|
||||
@@ -34,6 +35,7 @@ export type SlashHandler = (args: string[], loop: CacheFirstLoop, ctx: SlashCont
|
||||
const HANDLERS: Record<string, SlashHandler> = {
|
||||
...adminHandlers,
|
||||
...basicHandlers,
|
||||
...dashboardHandlers,
|
||||
...editsHandlers,
|
||||
...initHandlers,
|
||||
...jobsHandlers,
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
import { aggregateUsage, defaultUsageLogPath, readUsageLog } from "../../../../usage.js";
|
||||
import { VERSION, compareVersions, isNpxInstall } from "../../../../version.js";
|
||||
import { renderDashboard } from "../../../commands/stats.js";
|
||||
import { isMouseTrackingOn, setMouseTracking } from "../../alt-screen.js";
|
||||
import type { SlashHandler } from "../dispatch.js";
|
||||
|
||||
const hooks: SlashHandler = (args, loop, ctx) => {
|
||||
@@ -211,10 +212,50 @@ const cwd: SlashHandler = (args, _loop, ctx) => {
|
||||
return { info: lines.join("\n") };
|
||||
};
|
||||
|
||||
/**
|
||||
* `/mouse [on|off]` — toggle terminal mouse-event tracking. OFF by
|
||||
* default so the user can shift+drag to select & copy text from the
|
||||
* log. Turn ON for wheel-scroll-to-navigate-history. Bare `/mouse`
|
||||
* reports the current state.
|
||||
*/
|
||||
const copy: SlashHandler = (_args, _loop, ctx) => {
|
||||
if (!ctx.enterCopyMode) {
|
||||
return { info: "/copy is not available in this context (TUI-internal)." };
|
||||
}
|
||||
ctx.enterCopyMode();
|
||||
return {};
|
||||
};
|
||||
|
||||
const mouse: SlashHandler = (args) => {
|
||||
const arg = (args[0] ?? "").toLowerCase();
|
||||
if (arg === "") {
|
||||
return {
|
||||
info: isMouseTrackingOn()
|
||||
? "mouse tracking: ON — wheel scrolls log; copy needs Shift+drag to bypass tracking"
|
||||
: "mouse tracking: off (default) — text selection / copy works natively; PgUp/PgDn scroll the log",
|
||||
};
|
||||
}
|
||||
if (arg === "on" || arg === "true" || arg === "1" || arg === "yes") {
|
||||
setMouseTracking(true);
|
||||
return {
|
||||
info: "▸ mouse tracking ON — wheel-up / wheel-down now scroll the log. To copy text, hold Shift while dragging (bypasses tracking).",
|
||||
};
|
||||
}
|
||||
if (arg === "off" || arg === "false" || arg === "0" || arg === "no") {
|
||||
setMouseTracking(false);
|
||||
return {
|
||||
info: "▸ mouse tracking off — text selection works natively; use PgUp / PgDn / Home / End to scroll.",
|
||||
};
|
||||
}
|
||||
return { info: "usage: /mouse [on|off] (no arg → status)" };
|
||||
};
|
||||
|
||||
export const handlers: Record<string, SlashHandler> = {
|
||||
hook: hooks,
|
||||
hooks,
|
||||
cwd,
|
||||
update,
|
||||
stats,
|
||||
mouse,
|
||||
copy,
|
||||
};
|
||||
@@ -70,7 +70,7 @@ const help: SlashHandler = () => ({
|
||||
" /help this message",
|
||||
" /keys keyboard shortcuts + prompt prefixes (!, @, /)",
|
||||
" /status show current settings",
|
||||
" /preset <fast|smart|max> one-tap presets — see below",
|
||||
" /preset <auto|flash|pro> model bundle — 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)",
|
||||
@@ -132,9 +132,9 @@ const help: SlashHandler = () => ({
|
||||
" 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",
|
||||
" auto v4-flash → v4-pro on hard turns ← default · cheap when easy, smart when hard",
|
||||
" flash v4-flash always cheapest · predictable per-turn cost",
|
||||
" pro v4-pro always ~3× flash (5/31) · hard multi-turn work",
|
||||
"",
|
||||
"Sessions (auto-enabled by default, named 'default'):",
|
||||
" reasonix chat --session <name> use a different named session",
|
||||
|
||||
@@ -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 };
|
||||
@@ -1,3 +1,11 @@
|
||||
import {
|
||||
createCheckpoint,
|
||||
deleteCheckpoint,
|
||||
findCheckpoint,
|
||||
fmtAgo,
|
||||
listCheckpoints,
|
||||
restoreCheckpoint,
|
||||
} from "../../../../code/checkpoints.js";
|
||||
import type { EditMode } from "../../../../config.js";
|
||||
import { parseEditIndices } from "../../edit-history.js";
|
||||
import type { SlashHandler } from "../dispatch.js";
|
||||
@@ -167,6 +175,138 @@ const walk: SlashHandler = (_args, _loop, ctx) => {
|
||||
return { info: ctx.startWalkthrough() };
|
||||
};
|
||||
|
||||
/**
|
||||
* `/checkpoint [name]` — snapshot every file the session has touched
|
||||
* (or recently queued an edit against) to a Reasonix-internal store.
|
||||
* Survives `reasonix code` exiting; restore later with `/restore`.
|
||||
*
|
||||
* Sub-commands:
|
||||
* /checkpoint → list (same as /checkpoint list)
|
||||
* /checkpoint <name> → save a new checkpoint named <name>
|
||||
* /checkpoint list → enumerate stored snapshots
|
||||
* /checkpoint forget <id|name> → delete one
|
||||
*
|
||||
* Why this and not git auto-commit: doesn't pollute the user's git
|
||||
* history, works in non-git directories, doesn't fight with hooks /
|
||||
* branch state. See `feedback_internal_checkpoints_over_git.md` for
|
||||
* the full rationale.
|
||||
*/
|
||||
const checkpoint: SlashHandler = (args, _loop, ctx) => {
|
||||
if (!ctx.codeRoot || !ctx.touchedFiles) {
|
||||
return {
|
||||
info: "/checkpoint is only available inside `reasonix code` — chat mode doesn't apply edits.",
|
||||
};
|
||||
}
|
||||
const sub = (args[0] ?? "").toLowerCase();
|
||||
const rest = args.slice(1).join(" ").trim();
|
||||
|
||||
if (sub === "" || sub === "list") {
|
||||
const items = [...listCheckpoints(ctx.codeRoot)].reverse();
|
||||
if (items.length === 0) {
|
||||
return {
|
||||
info: "no checkpoints yet — `/checkpoint <name>` snapshots every file the session has touched. Restore later with `/restore <name>`.",
|
||||
};
|
||||
}
|
||||
const lines = [`◈ checkpoints · ${items.length} stored`, ""];
|
||||
for (const m of items) {
|
||||
const sizeKb = (m.bytes / 1024).toFixed(1);
|
||||
const tag = m.source === "manual" ? "" : ` (${m.source})`;
|
||||
lines.push(
|
||||
` ${m.id} ${fmtAgo(m.createdAt).padEnd(8)} ${m.name}${tag} · ${m.fileCount} file${m.fileCount === 1 ? "" : "s"}, ${sizeKb} KB`,
|
||||
);
|
||||
}
|
||||
lines.push("");
|
||||
lines.push(" /restore <name|id> · /checkpoint forget <id> · /checkpoint <name> to add");
|
||||
return { info: lines.join("\n") };
|
||||
}
|
||||
|
||||
if (sub === "forget" || sub === "rm" || sub === "delete") {
|
||||
if (!rest) return { info: "usage: /checkpoint forget <id|name>" };
|
||||
const found = findCheckpoint(ctx.codeRoot, rest);
|
||||
if (!found) return { info: `▸ no checkpoint matching "${rest}" — see /checkpoint list` };
|
||||
const ok = deleteCheckpoint(ctx.codeRoot, found.id);
|
||||
return {
|
||||
info: ok
|
||||
? `▸ deleted checkpoint ${found.id} (${found.name})`
|
||||
: `▸ failed to delete ${found.id} (already gone?)`,
|
||||
};
|
||||
}
|
||||
|
||||
// `/checkpoint <name>` (any free-form name) → save
|
||||
const name = args.join(" ").trim();
|
||||
if (!name) {
|
||||
return {
|
||||
info: "usage: /checkpoint <name> (or /checkpoint list to see existing)",
|
||||
};
|
||||
}
|
||||
const paths = ctx.touchedFiles();
|
||||
const meta = createCheckpoint({
|
||||
rootDir: ctx.codeRoot,
|
||||
name,
|
||||
paths,
|
||||
source: "manual",
|
||||
});
|
||||
if (paths.length === 0) {
|
||||
return {
|
||||
info: `▸ checkpoint "${name}" saved (${meta.id}) — but no files have been touched yet, so it's an empty baseline. Edits made after this point will be revertable.`,
|
||||
};
|
||||
}
|
||||
return {
|
||||
info: `▸ checkpoint "${name}" saved (${meta.id}) — ${meta.fileCount} file${meta.fileCount === 1 ? "" : "s"}, ${(meta.bytes / 1024).toFixed(1)} KB. Restore: /restore ${name}`,
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* `/restore <id|name>` — write a checkpoint's files back to disk.
|
||||
* Files that didn't exist at snapshot time get deleted. Files that
|
||||
* weren't in the snapshot are left untouched (the snapshot is
|
||||
* declarative for what it captured, not for the whole project).
|
||||
*
|
||||
* Doesn't touch the model's edit history or pending-edit queue —
|
||||
* `/undo` is for in-session reverts, `/restore` for cross-session.
|
||||
*/
|
||||
const restore: SlashHandler = (args, _loop, ctx) => {
|
||||
if (!ctx.codeRoot) {
|
||||
return {
|
||||
info: "/restore is only available inside `reasonix code`.",
|
||||
};
|
||||
}
|
||||
const target = args.join(" ").trim();
|
||||
if (!target) {
|
||||
return {
|
||||
info: "usage: /restore <name|id> (see /checkpoint list for ids)",
|
||||
};
|
||||
}
|
||||
const found = findCheckpoint(ctx.codeRoot, target);
|
||||
if (!found) {
|
||||
return { info: `▸ no checkpoint matching "${target}" — try /checkpoint list` };
|
||||
}
|
||||
const result = restoreCheckpoint(ctx.codeRoot, found.id);
|
||||
const lines = [`▸ restored "${found.name}" (${found.id}) from ${fmtAgo(found.createdAt)}`];
|
||||
if (result.restored.length > 0) {
|
||||
lines.push(
|
||||
` · wrote back ${result.restored.length} file${result.restored.length === 1 ? "" : "s"}`,
|
||||
);
|
||||
}
|
||||
if (result.removed.length > 0) {
|
||||
lines.push(
|
||||
` · removed ${result.removed.length} file${result.removed.length === 1 ? "" : "s"} (didn't exist at checkpoint time)`,
|
||||
);
|
||||
}
|
||||
if (result.skipped.length > 0) {
|
||||
lines.push(
|
||||
` ✗ ${result.skipped.length} file${result.skipped.length === 1 ? "" : "s"} skipped:`,
|
||||
);
|
||||
for (const s of result.skipped.slice(0, 5)) {
|
||||
lines.push(` ${s.path} — ${s.reason}`);
|
||||
}
|
||||
if (result.skipped.length > 5) {
|
||||
lines.push(` … ${result.skipped.length - 5} more`);
|
||||
}
|
||||
}
|
||||
return { info: lines.join("\n") };
|
||||
};
|
||||
|
||||
export const handlers: Record<string, SlashHandler> = {
|
||||
undo,
|
||||
history,
|
||||
@@ -179,4 +319,6 @@ export const handlers: Record<string, SlashHandler> = {
|
||||
mode,
|
||||
commit,
|
||||
walk,
|
||||
checkpoint,
|
||||
restore,
|
||||
};
|
||||
@@ -1,29 +1,115 @@
|
||||
import type { JobRecord } from "../../../../tools/jobs.js";
|
||||
import type { SlashHandler } from "../dispatch.js";
|
||||
|
||||
/**
|
||||
* Status icon per job state. ● for live (terminal renders bare colored
|
||||
* dot — combine with chalk fg color in the output for the cyan/green/red
|
||||
* cue), ✓ / ✗ for clean / failed exits, ○ for stopped-without-exit.
|
||||
*/
|
||||
function statusIcon(r: JobRecord): string {
|
||||
if (r.running) return "●";
|
||||
if (r.spawnError) return "✗";
|
||||
if (r.exitCode === 0) return "✓";
|
||||
if (r.exitCode !== null) return "✗";
|
||||
return "○";
|
||||
}
|
||||
|
||||
/**
|
||||
* Compact human age: "12s" / "4m" / "2h" / "3d". Tabular widths so a
|
||||
* column of ages still aligns under a fixed-width header.
|
||||
*/
|
||||
function fmtAge(ms: number): string {
|
||||
const s = Math.floor(ms / 1000);
|
||||
if (s < 60) return `${s}s`;
|
||||
const m = Math.floor(s / 60);
|
||||
if (m < 60) return `${m}m`;
|
||||
const h = Math.floor(m / 60);
|
||||
if (h < 24) return `${h}h`;
|
||||
return `${Math.floor(h / 24)}d`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Best-effort port detection from a running job's output. Most dev
|
||||
* servers print "Local: http://localhost:3000" or "Listening on :8080"
|
||||
* in their startup banner; surfacing those next to the row turns
|
||||
* `/jobs` into a "what's running on what port" dashboard. Returns up
|
||||
* to three unique ports because docker-compose-style multi-service
|
||||
* boots can legitimately bind several at once (postgres+redis).
|
||||
*
|
||||
* Fall through to no-ports if nothing matches; we don't want to invent
|
||||
* a port number from the command name (`npm run dev` → :3000) since
|
||||
* that's just a guess and being wrong is worse than being silent.
|
||||
*/
|
||||
function detectPorts(output: string): number[] {
|
||||
if (!output) return [];
|
||||
const found = new Set<number>();
|
||||
const patterns = [
|
||||
/(?:localhost|127\.0\.0\.1|0\.0\.0\.0):(\d{2,5})\b/g,
|
||||
/(?:listening|listening on|bound to|port|on port)[\s:=]+(\d{2,5})\b/gi,
|
||||
];
|
||||
for (const re of patterns) {
|
||||
let m: RegExpExecArray | null;
|
||||
// biome-ignore lint/suspicious/noAssignInExpressions: standard regex iteration pattern
|
||||
while ((m = re.exec(output)) !== null) {
|
||||
const port = Number.parseInt(m[1] ?? "", 10);
|
||||
if (port >= 80 && port <= 65535) found.add(port);
|
||||
if (found.size >= 3) break;
|
||||
}
|
||||
if (found.size >= 3) break;
|
||||
}
|
||||
return [...found];
|
||||
}
|
||||
|
||||
/**
|
||||
* Right-side metadata column. For running jobs show ports (brand-color
|
||||
* intent — caller can wrap in chalk); for terminated jobs show the
|
||||
* exit code with a "✓"/"✗" already in the status icon column, so the
|
||||
* meta is just a number.
|
||||
*/
|
||||
function fmtMeta(r: JobRecord): string {
|
||||
if (r.running) {
|
||||
const ports = detectPorts(r.output);
|
||||
if (ports.length > 0) return ports.map((p) => `:${p}`).join(" ");
|
||||
return r.pid !== null ? `pid ${r.pid}` : "";
|
||||
}
|
||||
if (r.spawnError) return r.spawnError;
|
||||
if (r.exitCode !== null) return `exit ${r.exitCode}`;
|
||||
return "stopped";
|
||||
}
|
||||
|
||||
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" };
|
||||
return {
|
||||
info: "◈ jobs · 0 running · 0 total\n (run_background spawns one — dev servers, watchers, long-running scripts)",
|
||||
};
|
||||
}
|
||||
const lines = ["Background jobs:"];
|
||||
const running = rows.filter((r) => r.running).length;
|
||||
// Layout: ICO (1) · ID (right-pad 4) · CMD (flex) · META (auto) · AGE (right-pad 5)
|
||||
// Plain text from a slash, so we can't apply per-cell color the way
|
||||
// the React tree could; the icons + indentation already give the eye
|
||||
// strong landmarks. The chrome layer (when this lands in the TUI
|
||||
// directly) will color the icons via chalk.
|
||||
const lines: string[] = [`◈ jobs · ${running} running · ${rows.length} total`, ""];
|
||||
// Compute the max command width so cmds line up; cap at 44 so a long
|
||||
// docker-compose invocation doesn't push the meta column off-screen.
|
||||
const cmdWidth = Math.min(44, Math.max(8, ...rows.map((r) => r.command.length)));
|
||||
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}`,
|
||||
);
|
||||
const ico = statusIcon(r);
|
||||
const id = `#${String(r.id).padEnd(3)}`;
|
||||
const cmd =
|
||||
r.command.length > cmdWidth
|
||||
? `${r.command.slice(0, cmdWidth - 1)}…`
|
||||
: r.command.padEnd(cmdWidth);
|
||||
const meta = fmtMeta(r).padEnd(20);
|
||||
const age = fmtAge(Date.now() - r.startedAt).padStart(4);
|
||||
lines.push(` ${ico} ${id} ${cmd} ${meta} ${age}`);
|
||||
}
|
||||
lines.push("");
|
||||
lines.push("/kill <id> to stop one · /logs <id> [lines] to tail output");
|
||||
lines.push(" /logs <id> tail · /kill <id> SIGTERM → SIGKILL");
|
||||
return { info: lines.join("\n") };
|
||||
};
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { saveReasoningEffort } from "../../../../config.js";
|
||||
import { PRESETS } from "../../presets.js";
|
||||
import type { SlashHandler } from "../dispatch.js";
|
||||
|
||||
const model: SlashHandler = (args, loop, ctx) => {
|
||||
@@ -73,39 +74,43 @@ const preset: SlashHandler = (args, loop) => {
|
||||
/* disk full / perms — runtime change still took effect */
|
||||
}
|
||||
};
|
||||
if (name === "fast" || name === "default") {
|
||||
if (name === "auto") {
|
||||
const p = PRESETS.auto;
|
||||
loop.configure({
|
||||
model: "deepseek-v4-flash",
|
||||
reasoningEffort: "high",
|
||||
harvest: false,
|
||||
branch: 1,
|
||||
model: p.model,
|
||||
autoEscalate: p.autoEscalate,
|
||||
reasoningEffort: p.reasoningEffort,
|
||||
harvest: p.harvest,
|
||||
branch: p.branch,
|
||||
});
|
||||
applyAndPersist("high");
|
||||
return { info: "preset → fast (v4-flash · effort=high · cheapest)" };
|
||||
applyAndPersist(p.reasoningEffort);
|
||||
return { info: "preset → auto (v4-flash → v4-pro on hard turns · default)" };
|
||||
}
|
||||
if (name === "smart") {
|
||||
if (name === "flash") {
|
||||
const p = PRESETS.flash;
|
||||
loop.configure({
|
||||
model: "deepseek-v4-flash",
|
||||
reasoningEffort: "max",
|
||||
harvest: false,
|
||||
branch: 1,
|
||||
model: p.model,
|
||||
autoEscalate: p.autoEscalate,
|
||||
reasoningEffort: p.reasoningEffort,
|
||||
harvest: p.harvest,
|
||||
branch: p.branch,
|
||||
});
|
||||
applyAndPersist("max");
|
||||
return { info: "preset → smart (v4-flash · effort=max · default · ~1.5× fast)" };
|
||||
applyAndPersist(p.reasoningEffort);
|
||||
return { info: "preset → flash (v4-flash always · cheapest · /pro still bumps one turn)" };
|
||||
}
|
||||
if (name === "max" || name === "best") {
|
||||
if (name === "pro") {
|
||||
const p = PRESETS.pro;
|
||||
loop.configure({
|
||||
model: "deepseek-v4-pro",
|
||||
reasoningEffort: "max",
|
||||
harvest: false,
|
||||
branch: 1,
|
||||
model: p.model,
|
||||
autoEscalate: p.autoEscalate,
|
||||
reasoningEffort: p.reasoningEffort,
|
||||
harvest: p.harvest,
|
||||
branch: p.branch,
|
||||
});
|
||||
applyAndPersist("max");
|
||||
return {
|
||||
info: "preset → max (v4-pro · effort=max · ~12× fast · save for hard tasks, or use /pro for a single-turn bump)",
|
||||
};
|
||||
applyAndPersist(p.reasoningEffort);
|
||||
return { info: "preset → pro (v4-pro always · ~3× flash · for hard multi-turn work)" };
|
||||
}
|
||||
return { info: "usage: /preset <fast|smart|max>" };
|
||||
return { info: "usage: /preset <auto|flash|pro>" };
|
||||
};
|
||||
|
||||
const branch: SlashHandler = (args, loop) => {
|
||||
@@ -176,6 +181,48 @@ const pro: SlashHandler = (args, loop, ctx) => {
|
||||
// internal constant renames).
|
||||
const ESCALATION_MODEL_ID = "deepseek-v4-pro";
|
||||
|
||||
const budget: SlashHandler = (args, loop) => {
|
||||
const arg = args[0]?.trim() ?? "";
|
||||
// Bare /budget → status. No-cap state is the default Reasonix ships
|
||||
// with, so the message stays calm rather than making it sound like
|
||||
// a missing config.
|
||||
if (arg === "") {
|
||||
if (loop.budgetUsd === null) {
|
||||
return {
|
||||
info: "no session budget set — Reasonix will keep going until you stop it. Set one with: /budget <usd> (e.g. /budget 5)",
|
||||
};
|
||||
}
|
||||
const spent = loop.stats.totalCost;
|
||||
const pct = (spent / loop.budgetUsd) * 100;
|
||||
return {
|
||||
info: `budget: $${spent.toFixed(4)} of $${loop.budgetUsd.toFixed(2)} (${pct.toFixed(1)}%) · /budget off to clear, /budget <usd> to change`,
|
||||
};
|
||||
}
|
||||
// Explicit clear.
|
||||
if (arg === "off" || arg === "none" || arg === "0") {
|
||||
loop.setBudget(null);
|
||||
return { info: "budget → off (no cap)" };
|
||||
}
|
||||
// Strip a leading $ since users will type it half the time.
|
||||
const cleaned = arg.replace(/^\$/, "");
|
||||
const usd = Number(cleaned);
|
||||
if (!Number.isFinite(usd) || usd <= 0) {
|
||||
return {
|
||||
info: `usage: /budget <usd> (got "${arg}" — must be a positive number, e.g. /budget 5 or /budget 12.50)`,
|
||||
};
|
||||
}
|
||||
loop.setBudget(usd);
|
||||
const spent = loop.stats.totalCost;
|
||||
if (spent >= usd) {
|
||||
return {
|
||||
info: `▲ budget → $${usd.toFixed(2)} but already spent $${spent.toFixed(4)}. Next turn will be refused — bump the cap higher to keep going, or end the session.`,
|
||||
};
|
||||
}
|
||||
return {
|
||||
info: `budget → $${usd.toFixed(2)} (so far: $${spent.toFixed(4)} · warns at 80%, refuses next turn at 100% · /budget off to clear)`,
|
||||
};
|
||||
};
|
||||
|
||||
export const handlers: Record<string, SlashHandler> = {
|
||||
model,
|
||||
models,
|
||||
@@ -184,4 +231,5 @@ export const handlers: Record<string, SlashHandler> = {
|
||||
branch,
|
||||
effort,
|
||||
pro,
|
||||
budget,
|
||||
};
|
||||
@@ -1,5 +1,5 @@
|
||||
import { DEEPSEEK_CONTEXT_TOKENS, DEFAULT_CONTEXT_TOKENS } from "../../../../telemetry.js";
|
||||
import { countTokens } from "../../../../tokenizer.js";
|
||||
import { computeCtxBreakdown } from "../../ctx-breakdown.js";
|
||||
import type { SlashHandler } from "../dispatch.js";
|
||||
import { compactNum, formatToolList } from "../helpers.js";
|
||||
|
||||
@@ -53,87 +53,61 @@ const tool: SlashHandler = (args, _loop, ctx) => {
|
||||
};
|
||||
};
|
||||
|
||||
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 context: SlashHandler = (args, loop, ctx) => {
|
||||
// Toggle the persistent footer when wired (TUI). Falls back to a
|
||||
// one-shot scrollback breakdown push for headless / replay surfaces
|
||||
// that don't carry the toggle callback.
|
||||
if (ctx.toggleCtxFooter) {
|
||||
const arg = (args[0] ?? "").toLowerCase();
|
||||
const force = arg === "on" ? true : arg === "off" ? false : undefined;
|
||||
const next = ctx.toggleCtxFooter(force);
|
||||
return { info: `▸ context footer: ${next ? "on" : "off"}` };
|
||||
}
|
||||
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 breakdown = computeCtxBreakdown(loop);
|
||||
const total =
|
||||
breakdown.systemTokens + breakdown.toolsTokens + breakdown.logTokens + breakdown.inputTokens;
|
||||
const winPct = breakdown.ctxMax > 0 ? Math.round((total / breakdown.ctxMax) * 100) : 0;
|
||||
const fallbackInfo = `context: ~${compactNum(total)} of ${compactNum(breakdown.ctxMax)} (${winPct}%) · system ${compactNum(breakdown.systemTokens)} · tools ${compactNum(breakdown.toolsTokens)} · log ${compactNum(breakdown.logTokens)}`;
|
||||
return { info: fallbackInfo, ctxBreakdown: breakdown };
|
||||
};
|
||||
|
||||
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 summary = loop.stats.summary();
|
||||
const lastPromptTokens = summary.lastPromptTokens;
|
||||
const ctxPct = ctxMax > 0 ? Math.round((lastPromptTokens / ctxMax) * 100) : 0;
|
||||
// 16-cell context bar — narrower than /context's 48 since /status is
|
||||
// a quick glance, not the deep dive. Same `█/░` characters so the
|
||||
// visual grammar stays consistent across slashes.
|
||||
const ctxBar = lastPromptTokens > 0 ? renderTinyBar(ctxPct, 16) : "";
|
||||
const ctxLine =
|
||||
lastPromptTokens > 0
|
||||
? ` ctx ${compactNum(lastPromptTokens)}/${compactNum(ctxMax)} (${ctxPct}%)`
|
||||
: " ctx no turns yet";
|
||||
? ` ctx ${ctxBar} ${compactNum(lastPromptTokens)}/${compactNum(ctxMax)} (${ctxPct}%)`
|
||||
: " ctx no turns yet";
|
||||
|
||||
// Cost / cache hit row — the high-signal numbers from StatsPanel.
|
||||
// Cache pct only shown after the cold-start window so a 0.0% on
|
||||
// turn 1 doesn't read as broken.
|
||||
const cost = summary.totalCostUsd;
|
||||
const cacheLine =
|
||||
summary.turns > 3
|
||||
? (() => {
|
||||
const cachePct = Math.round(summary.cacheHitRatio * 100);
|
||||
return ` cost $${cost.toFixed(4)} · cache ${renderTinyBar(cachePct, 12)} ${cachePct}% · turns ${summary.turns}`;
|
||||
})()
|
||||
: ` cost $${cost.toFixed(4)} · turns ${summary.turns} (cache warming up)`;
|
||||
|
||||
// Budget row — only when a cap is set
|
||||
const budgetLine =
|
||||
typeof loop.budgetUsd === "number"
|
||||
? (() => {
|
||||
const pct = Math.round((cost / loop.budgetUsd!) * 100);
|
||||
const tag = pct >= 100 ? " ▲ EXHAUSTED" : pct >= 80 ? " ▲ 80%+" : "";
|
||||
return ` budget $${cost.toFixed(4)} / $${loop.budgetUsd!.toFixed(2)} (${pct}%)${tag}`;
|
||||
})()
|
||||
: "";
|
||||
|
||||
const pending = ctx.pendingEditCount ?? 0;
|
||||
const sessionLine = loop.sessionName
|
||||
? ` session "${loop.sessionName}" · ${loop.log.length} messages in log (resumed ${loop.resumedMessageCount})`
|
||||
@@ -152,19 +126,38 @@ const status: SlashHandler = (_args, loop, ctx) => {
|
||||
: ctx.editMode === "review"
|
||||
? " mode review — edits queue for /apply or y (Shift+Tab to flip)"
|
||||
: "";
|
||||
const dashLine = ctx.getDashboardUrl?.()
|
||||
? ` dash ${ctx.getDashboardUrl?.()} (open in browser · /dashboard stop)`
|
||||
: "";
|
||||
const lines = [
|
||||
` model ${loop.model}`,
|
||||
` flags harvest=${loop.harvestEnabled ? "on" : "off"} · branch=${branchBudget > 1 ? branchBudget : "off"} · stream=${loop.stream ? "on" : "off"} · effort=${loop.reasoningEffort}`,
|
||||
cacheLine,
|
||||
ctxLine,
|
||||
mcpLine,
|
||||
sessionLine,
|
||||
];
|
||||
if (budgetLine) lines.push(budgetLine);
|
||||
if (pendingLine) lines.push(pendingLine);
|
||||
if (planLine) lines.push(planLine);
|
||||
if (modeLine) lines.push(modeLine);
|
||||
if (dashLine) lines.push(dashLine);
|
||||
return { info: lines.join("\n") };
|
||||
};
|
||||
|
||||
/**
|
||||
* Tiny `[██████░░░░] 60%`-style bar for use inside slash text output.
|
||||
* Char-only, no color (info text strings render dimColor in EventLog).
|
||||
* The visual is intentionally subtle — these slashes are scanned for
|
||||
* numbers, not stared at.
|
||||
*/
|
||||
function renderTinyBar(pct: number, width: number): string {
|
||||
const w = Math.max(4, width);
|
||||
const clamped = Math.max(0, Math.min(100, pct));
|
||||
const filled = Math.round((w * clamped) / 100);
|
||||
return `[${"█".repeat(filled)}${"░".repeat(w - filled)}]`;
|
||||
}
|
||||
|
||||
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
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { deleteSession, listSessions } from "../../../../session.js";
|
||||
import { deleteSession, listSessions, pruneStaleSessions } from "../../../../session.js";
|
||||
import type { SlashHandler } from "../dispatch.js";
|
||||
|
||||
const STALE_THRESHOLD_DAYS = 90;
|
||||
|
||||
const sessions: SlashHandler = (_args, loop) => {
|
||||
const items = listSessions();
|
||||
if (items.length === 0) {
|
||||
@@ -8,17 +10,28 @@ const sessions: SlashHandler = (_args, loop) => {
|
||||
info: "no saved sessions yet — chat normally and your messages will be saved automatically",
|
||||
};
|
||||
}
|
||||
const now = Date.now();
|
||||
const lines = ["Saved sessions:"];
|
||||
let staleCount = 0;
|
||||
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 ? "▸" : " ";
|
||||
const ageDays = Math.floor((now - s.mtime.getTime()) / (24 * 60 * 60 * 1000));
|
||||
const isStale = ageDays >= STALE_THRESHOLD_DAYS;
|
||||
const ageTag = isStale ? ` (${ageDays}d — stale)` : "";
|
||||
if (isStale) staleCount++;
|
||||
lines.push(
|
||||
` ${marker} ${s.name.padEnd(22)} ${String(s.messageCount).padStart(5)} msgs ${sizeKb.padStart(7)} KB ${when}`,
|
||||
` ${marker} ${s.name.padEnd(22)} ${String(s.messageCount).padStart(5)} msgs ${sizeKb.padStart(7)} KB ${when}${ageTag}`,
|
||||
);
|
||||
}
|
||||
lines.push("");
|
||||
lines.push("Resume with: reasonix chat --session <name>");
|
||||
if (staleCount > 0) {
|
||||
lines.push(
|
||||
`${staleCount} session${staleCount === 1 ? "" : "s"} idle ≥${STALE_THRESHOLD_DAYS} days — /prune-sessions to remove`,
|
||||
);
|
||||
}
|
||||
return { info: lines.join("\n") };
|
||||
};
|
||||
|
||||
@@ -35,7 +48,27 @@ const forget: SlashHandler = (_args, loop) => {
|
||||
};
|
||||
};
|
||||
|
||||
const pruneSessions: SlashHandler = (args) => {
|
||||
// Optional first arg: cutoff in days (default 90). Lets users
|
||||
// tighten the threshold for a one-off purge without editing code.
|
||||
const raw = args?.[0];
|
||||
const days = raw ? Number.parseInt(raw, 10) : STALE_THRESHOLD_DAYS;
|
||||
if (!Number.isFinite(days) || days < 1) {
|
||||
return {
|
||||
info: `▸ usage: /prune-sessions [days] — defaults to ${STALE_THRESHOLD_DAYS}, must be ≥1`,
|
||||
};
|
||||
}
|
||||
const removed = pruneStaleSessions(days);
|
||||
if (removed.length === 0) {
|
||||
return { info: `▸ nothing to prune — no sessions idle ≥${days} days` };
|
||||
}
|
||||
return {
|
||||
info: `▸ pruned ${removed.length} session${removed.length === 1 ? "" : "s"} idle ≥${days} days: ${removed.join(", ")}`,
|
||||
};
|
||||
};
|
||||
|
||||
export const handlers: Record<string, SlashHandler> = {
|
||||
sessions,
|
||||
forget,
|
||||
"prune-sessions": pruneSessions,
|
||||
};
|
||||
@@ -20,6 +20,22 @@ export interface SlashResult {
|
||||
* submit flow so a fresh turn runs.
|
||||
*/
|
||||
resubmit?: string;
|
||||
/**
|
||||
* Structured payload for `/context` — pushed as a `ctx-breakdown`
|
||||
* DisplayEvent so EventLog can render the 4-color stacked bar via
|
||||
* proper Box+Text segments. Plain `info` text can't carry per-segment
|
||||
* color, so this is the structured route.
|
||||
*/
|
||||
ctxBreakdown?: {
|
||||
systemTokens: number;
|
||||
toolsTokens: number;
|
||||
logTokens: number;
|
||||
inputTokens: number;
|
||||
ctxMax: number;
|
||||
toolsCount: number;
|
||||
logMessages: number;
|
||||
topTools: Array<{ name: string; tokens: number; turn: number }>;
|
||||
};
|
||||
/**
|
||||
* Render an archived plan as a read-only "Time Travel" block in
|
||||
* scrollback. Populated by `/replay [N]`. The TUI mounts it as a
|
||||
@@ -48,6 +64,21 @@ export interface SlashResult {
|
||||
* slots that apply to their session.
|
||||
*/
|
||||
export interface SlashContext {
|
||||
/**
|
||||
* `/copy` — exit alt-screen, dump the rendered log to main screen so
|
||||
* the user can use native terminal scrollback + drag-select to copy
|
||||
* across content that doesn't fit the viewport. Any keystroke
|
||||
* restores alt-screen and the live TUI. Absent → `/copy` replies "not
|
||||
* available here" (TUI-internal only).
|
||||
*/
|
||||
enterCopyMode?: () => void;
|
||||
/**
|
||||
* `/context` — toggle the always-on context-breakdown footer. Returns
|
||||
* the new visibility state so the handler can echo "context footer:
|
||||
* on/off". Optional `force` skips the toggle and sets directly.
|
||||
*/
|
||||
toggleCtxFooter?: (force?: boolean) => boolean;
|
||||
|
||||
/**
|
||||
* The exact `--mcp` / config-derived spec strings that were bridged
|
||||
* into this session (one entry per server). Used by `/mcp`. Empty or
|
||||
@@ -139,6 +170,14 @@ export interface SlashContext {
|
||||
* also persist the choice to config and echo the change in historical.
|
||||
*/
|
||||
setEditMode?: (mode: EditMode) => void;
|
||||
/**
|
||||
* Repo-relative paths the session has touched so far (edit history +
|
||||
* pending-edit blocks, deduped). Used by `/checkpoint` to capture
|
||||
* "the surface area I might want to roll back later" without snapshotting
|
||||
* the whole project. Absent in chat mode → `/checkpoint` replies "not
|
||||
* available outside code mode".
|
||||
*/
|
||||
touchedFiles?: () => string[];
|
||||
/**
|
||||
* Background-process registry backing /jobs / /kill / /logs. Present
|
||||
* iff the session is a `reasonix code` run. Slash handlers expect
|
||||
@@ -247,6 +286,19 @@ export interface SlashContext {
|
||||
* 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 {
|
||||
|
||||
@@ -69,6 +69,24 @@ export interface KeyEvent {
|
||||
* keystrokes (e.g. a `\n` in a paste shouldn't fire submit).
|
||||
*/
|
||||
paste?: boolean;
|
||||
/**
|
||||
* Mouse wheel up — fired when the user scrolls up on a terminal
|
||||
* with mouse tracking enabled (xterm SGR mode 1006). Consumers use
|
||||
* this to scroll the log region up by N events.
|
||||
*/
|
||||
mouseScrollUp?: boolean;
|
||||
/** Mouse wheel down — symmetric to `mouseScrollUp`. */
|
||||
mouseScrollDown?: boolean;
|
||||
/**
|
||||
* Mouse click (left button press). `mouseRow` / `mouseCol` give
|
||||
* the cell-grid position in 1-based coordinates the terminal
|
||||
* emitted. Consumers use this to detect clicks on inline UI like a
|
||||
* "↓ jump to latest" indicator row. Released-click events are
|
||||
* suppressed — only the press fires.
|
||||
*/
|
||||
mouseClick?: boolean;
|
||||
mouseRow?: number;
|
||||
mouseCol?: number;
|
||||
}
|
||||
|
||||
type Subscriber = (ev: KeyEvent) => void;
|
||||
@@ -177,6 +195,17 @@ export class StdinReader {
|
||||
/** Buffer for paste content. */
|
||||
private pasteBuf = "";
|
||||
private escTimer: NodeJS.Timeout | null = null;
|
||||
// Deferred-dispatch handle paired with `escTimer`. The timer
|
||||
// queues an Immediate that runs in the event loop's CHECK phase —
|
||||
// i.e. AFTER the POLL phase where stdin 'data' events fire — so
|
||||
// a multi-byte sequence whose chunks queued up while the loop was
|
||||
// blocked (heavy render, etc.) gets a chance to be processed
|
||||
// BEFORE we emit a bogus standalone-Esc. Fixes the "I didn't press
|
||||
// Esc but it aborted the turn" class of bug: previously the timer's
|
||||
// setTimeout callback ran in the timers phase ahead of poll, so a
|
||||
// split sequence like `\x1b` + `[A` would dispatch escape+upArrow
|
||||
// even though the user only pressed Up.
|
||||
private escImmediate: NodeJS.Immediate | 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;
|
||||
@@ -247,16 +276,29 @@ export class StdinReader {
|
||||
clearTimeout(this.escTimer);
|
||||
this.escTimer = null;
|
||||
}
|
||||
if (this.escImmediate) {
|
||||
clearImmediate(this.escImmediate);
|
||||
this.escImmediate = 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 });
|
||||
}
|
||||
this.escTimer = null;
|
||||
// Defer the actual dispatch to the CHECK phase so any pending
|
||||
// stdin 'data' events that queued up during a long render still
|
||||
// get a chance to consume the rest of a split sequence. The
|
||||
// chunk handler cancels this Immediate at its start, so a
|
||||
// sequence completing first wins; only a truly-orphaned `\x1b`
|
||||
// reaches the dispatch below.
|
||||
this.escImmediate = setImmediate(() => {
|
||||
this.escImmediate = null;
|
||||
if (this.state === "esc") {
|
||||
this.state = "idle";
|
||||
this.dispatch({ input: "", escape: true });
|
||||
}
|
||||
});
|
||||
}, ESC_TIMEOUT_MS);
|
||||
}
|
||||
|
||||
@@ -447,6 +489,43 @@ export class StdinReader {
|
||||
// but if we do, drop it silently.
|
||||
return;
|
||||
}
|
||||
// SGR mouse: `<button;col;rowM` (press) or `<button;col;rowm`
|
||||
// (release). Only fired when the App enabled SGR mode + button-
|
||||
// event tracking at startup. Buttons:
|
||||
// 0 = left, 1 = middle, 2 = right
|
||||
// 64 = scroll up, 65 = scroll down (no release event for wheel)
|
||||
// We surface scroll wheels and left-button presses; the rest are
|
||||
// dropped to avoid noisy events.
|
||||
if (seq.length > 1 && seq.charCodeAt(0) === 60 /* '<' */) {
|
||||
const tail = seq[seq.length - 1]!;
|
||||
if (tail === "M" || tail === "m") {
|
||||
const body = seq.slice(1, -1);
|
||||
const parts = body.split(";");
|
||||
if (parts.length === 3) {
|
||||
const btn = Number.parseInt(parts[0]!, 10);
|
||||
const col = Number.parseInt(parts[1]!, 10);
|
||||
const row = Number.parseInt(parts[2]!, 10);
|
||||
if (Number.isFinite(btn) && Number.isFinite(col) && Number.isFinite(row)) {
|
||||
// Wheel up/down come as press-only (uppercase M).
|
||||
if (tail === "M" && btn === 64) {
|
||||
this.dispatch({ input: "", mouseScrollUp: true, mouseRow: row, mouseCol: col });
|
||||
return;
|
||||
}
|
||||
if (tail === "M" && btn === 65) {
|
||||
this.dispatch({ input: "", mouseScrollDown: true, mouseRow: row, mouseCol: col });
|
||||
return;
|
||||
}
|
||||
// Left-click press only (button 0 with M; we ignore release `m`).
|
||||
if (tail === "M" && btn === 0) {
|
||||
this.dispatch({ input: "", mouseClick: true, mouseRow: row, mouseCol: col });
|
||||
return;
|
||||
}
|
||||
// Other buttons / drag / release → drop silently.
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
const ev = lookupCsi(seq);
|
||||
if (ev) this.dispatch(ev);
|
||||
// Unknown CSI → drop. Do NOT insert raw bytes as text.
|
||||
|
||||
@@ -67,6 +67,64 @@ export const GLYPH = {
|
||||
shade1: "░",
|
||||
shade2: "▒",
|
||||
shade3: "▓",
|
||||
|
||||
// Status icons — checkbox-style states used across plan steps,
|
||||
// job rows, history entries. Pair with the COLOR semantics:
|
||||
// done→ok, cur→primary, pending→info-faint, fail→err.
|
||||
done: "✓",
|
||||
cur: "▸",
|
||||
pending: "○",
|
||||
fail: "✗",
|
||||
running: "●",
|
||||
|
||||
// Tree-drawing chars for hierarchical lists (plan steps, sub-loops,
|
||||
// hook attachments). 1 cell each; render fine in every monospace
|
||||
// font we've tested.
|
||||
branch: "┣",
|
||||
branchEnd: "┗",
|
||||
branchStub: "┃",
|
||||
rule: "─",
|
||||
|
||||
// Spinner frames — 4-step rotation. Cycle every 200ms via setInterval
|
||||
// (Ink's useEffect setState pattern). Equivalent to ink-spinner but
|
||||
// with our own cadence + character set.
|
||||
spinFrames: ["◐", "◓", "◑", "◒"] as readonly string[],
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* Surface color ramp — 6 steps from canvas (deepest) to selected
|
||||
* (lightest). Use these for stacked layers like top chrome over log
|
||||
* over modal-backdrop. Lifted from the dashboard's app.css so the web
|
||||
* surface and TUI share an identical depth perception (within Ink's
|
||||
* ANSI limits).
|
||||
*
|
||||
* Note: terminals quantize to 256-color or 16-color when truecolor
|
||||
* isn't available, so steps that look distinct in a modern terminal
|
||||
* may collapse to two visible shades on basic xterm. The ordering
|
||||
* stays correct in both — bg-canvas is always darker than bg-sel.
|
||||
*/
|
||||
export const SURFACE = {
|
||||
canvas: "#070a10",
|
||||
shell: "#0b1019",
|
||||
card: "#101721",
|
||||
elev: "#161f2c",
|
||||
sel: "#1a2433",
|
||||
line: "#1c2433",
|
||||
lineSoft: "#141b27",
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* Foreground intensity ramp — 5 steps from boldest text to faintest
|
||||
* decoration. Match these against semantic content: `strong` for
|
||||
* headings + active selection labels; `default` for body; `dim` for
|
||||
* meta; `faint` for hints + foot bars; `ghost` for separators.
|
||||
*/
|
||||
export const FG = {
|
||||
strong: "#e6edf6",
|
||||
default: "#cbd5e1",
|
||||
dim: "#94a3b8",
|
||||
faint: "#64748b",
|
||||
ghost: "#475569",
|
||||
} as const;
|
||||
|
||||
/**
|
||||
|
||||
+63
-27
@@ -1,27 +1,39 @@
|
||||
import React, { type ReactNode, createContext, useContext, useEffect, useState } from "react";
|
||||
|
||||
/**
|
||||
* Global heartbeat for every animated component (braille spinners,
|
||||
* elapsed-seconds counters, cursor blink). A single setInterval feeds
|
||||
* all of them instead of each component owning one. Consolidating the
|
||||
* 5-6 independent timers that used to exist in App.tsx + EventLog.tsx +
|
||||
* PromptInput.tsx into one source dramatically cuts the number of
|
||||
* React re-renders per second on heavy turns and stops Ink from
|
||||
* patching the terminal 30+ times/sec — the main amplifier of redraw
|
||||
* artifacts on winpty/MINTTY-class Windows terminals.
|
||||
* Two-tier global heartbeat. Both timers are owned by one provider so
|
||||
* we still pay for a single setInterval per cadence, but components
|
||||
* subscribe to whichever tier matches what they actually need to
|
||||
* repaint:
|
||||
*
|
||||
* Resolution: `TICK_MS` (default 120). Components that want 500ms or
|
||||
* 1s cadence just modulo the tick counter.
|
||||
* - FAST_TICK_MS (120ms) — spinners, glyph pulses, anything that
|
||||
* visibly animates frame-by-frame.
|
||||
* - SLOW_TICK_MS (1000ms) — elapsed-seconds counters, expiry
|
||||
* countdowns, out-of-React mutation pollers (job registries, file
|
||||
* stat refresh). These don't NEED 8Hz re-renders — they update
|
||||
* once per visible-state change anyway, so subscribing them to
|
||||
* the fast tick was 7 wasted re-renders per second per consumer.
|
||||
*
|
||||
* Splitting the contexts means a slow consumer (Elapsed timer) no
|
||||
* longer reconciles when only the fast tick increments — React's
|
||||
* context-propagation only fires for subscribers of the changed
|
||||
* context. The streaming row's spinner and elapsed counter used to
|
||||
* re-render together every 120ms; now the elapsed re-renders at 1Hz
|
||||
* while the spinner keeps its 8Hz cadence.
|
||||
*/
|
||||
export const TICK_MS = 120;
|
||||
export const FAST_TICK_MS = 120;
|
||||
export const SLOW_TICK_MS = 1000;
|
||||
/** @deprecated kept for callers that import the old name. */
|
||||
export const TICK_MS = FAST_TICK_MS;
|
||||
|
||||
const TickContext = createContext(0);
|
||||
const FastTickContext = createContext(0);
|
||||
const SlowTickContext = createContext(0);
|
||||
|
||||
export interface TickerProviderProps {
|
||||
children: ReactNode;
|
||||
/**
|
||||
* When true, the provider skips the setInterval entirely — tick stays at
|
||||
* 0, all consumers render once and never re-render from the timer. Used
|
||||
* When true, the provider skips both setIntervals — ticks stay at 0,
|
||||
* all consumers render once and never re-render from the timer. Used
|
||||
* by PLAIN_UI mode so the cursor and any surviving spinners don't drive
|
||||
* repaints on fragile Windows terminals.
|
||||
*/
|
||||
@@ -29,27 +41,51 @@ export interface TickerProviderProps {
|
||||
}
|
||||
|
||||
export function TickerProvider({ children, disabled }: TickerProviderProps) {
|
||||
const [tick, setTick] = useState(0);
|
||||
const [fast, setFast] = useState(0);
|
||||
const [slow, setSlow] = useState(0);
|
||||
useEffect(() => {
|
||||
if (disabled) return;
|
||||
const id = setInterval(() => setTick((t) => t + 1), TICK_MS);
|
||||
return () => clearInterval(id);
|
||||
const fastId = setInterval(() => setFast((t) => t + 1), FAST_TICK_MS);
|
||||
const slowId = setInterval(() => setSlow((t) => t + 1), SLOW_TICK_MS);
|
||||
return () => {
|
||||
clearInterval(fastId);
|
||||
clearInterval(slowId);
|
||||
};
|
||||
}, [disabled]);
|
||||
return <TickContext.Provider value={tick}>{children}</TickContext.Provider>;
|
||||
}
|
||||
|
||||
/** Current global tick. Re-renders the calling component every `TICK_MS`. */
|
||||
export function useTick(): number {
|
||||
return useContext(TickContext);
|
||||
return (
|
||||
<FastTickContext.Provider value={fast}>
|
||||
<SlowTickContext.Provider value={slow}>{children}</SlowTickContext.Provider>
|
||||
</FastTickContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Seconds elapsed since the calling component mounted. Derived from
|
||||
* the shared tick + a fresh Date.now() read, so no dedicated timer
|
||||
* is needed.
|
||||
* Fast tick — re-renders the calling component every {@link FAST_TICK_MS}.
|
||||
* Use for spinner frames, glyph pulses, and anything else that
|
||||
* visibly animates. If your component just shows a counter that
|
||||
* updates once per second, prefer {@link useSlowTick}.
|
||||
*/
|
||||
export function useTick(): number {
|
||||
return useContext(FastTickContext);
|
||||
}
|
||||
|
||||
/**
|
||||
* Slow tick — re-renders the calling component every {@link SLOW_TICK_MS}.
|
||||
* Use for elapsed-seconds counters, expiry countdowns, or pollers
|
||||
* that just need a "what's the time NOW?" trigger once per second.
|
||||
*/
|
||||
export function useSlowTick(): number {
|
||||
return useContext(SlowTickContext);
|
||||
}
|
||||
|
||||
/**
|
||||
* Seconds elapsed since the calling component mounted. Subscribes to
|
||||
* the slow tick — re-renders at 1Hz, which is exactly what a
|
||||
* second-resolution counter needs. Earlier versions used the fast
|
||||
* tick and re-rendered 8x/sec just to display the same number.
|
||||
*/
|
||||
export function useElapsedSeconds(): number {
|
||||
const [start] = useState(() => Date.now());
|
||||
useTick(); // subscribe to the tick so we re-render
|
||||
useSlowTick();
|
||||
return Math.floor((Date.now() - start) / 1000);
|
||||
}
|
||||
@@ -2,7 +2,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import {
|
||||
type FileWithStats,
|
||||
detectAtPicker,
|
||||
listFilesWithStatsSync,
|
||||
listFilesWithStatsAsync,
|
||||
rankPickerCandidates,
|
||||
} from "../../at-mentions.js";
|
||||
import {
|
||||
@@ -84,17 +84,32 @@ export function useCompletionPickers({
|
||||
|
||||
// ── @-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 [];
|
||||
// Walk the code root asynchronously after first paint. Earlier
|
||||
// versions used `listFilesWithStatsSync` inside `useMemo`, which
|
||||
// blocked mount for 100-300ms on Windows monorepos (one statSync
|
||||
// per file × 500 files). Async + parallel-stat-per-directory
|
||||
// takes the cost off the critical path; the picker stays empty
|
||||
// for the brief window before the walk completes (typically
|
||||
// <200ms), and fills in atomically once Promise.all resolves.
|
||||
// Files created mid-session via tool edits still won't appear
|
||||
// until restart — rare; the user can type the full path.
|
||||
const [atFiles, setAtFiles] = useState<readonly FileWithStats[]>([]);
|
||||
useEffect(() => {
|
||||
if (!codeMode) {
|
||||
setAtFiles([]);
|
||||
return;
|
||||
}
|
||||
let cancelled = false;
|
||||
listFilesWithStatsAsync(rootDir, { maxResults: 500 })
|
||||
.then((files) => {
|
||||
if (!cancelled) setAtFiles(files);
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) setAtFiles([]);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [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
|
||||
|
||||
@@ -73,6 +73,14 @@ export interface UseEditHistoryResult {
|
||||
* Reads the ref fresh — callers must re-read each time.
|
||||
*/
|
||||
hasUndoable: () => boolean;
|
||||
/**
|
||||
* Repo-relative paths the session has edited so far, deduped. Used by
|
||||
* `/checkpoint` to capture "what's been touched in this run". Includes
|
||||
* paths from undone batches too — the snapshot value is "what files
|
||||
* could the user want to roll back later?", and an undone batch still
|
||||
* represents a file the user was thinking about.
|
||||
*/
|
||||
touchedPaths: () => string[];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -296,6 +304,14 @@ export function useEditHistory(codeMode: { rootDir: string } | undefined): UseEd
|
||||
[],
|
||||
);
|
||||
|
||||
const touchedPaths = useCallback<UseEditHistoryResult["touchedPaths"]>(() => {
|
||||
const seen = new Set<string>();
|
||||
for (const entry of editHistory.current) {
|
||||
for (const b of entry.blocks) seen.add(b.path);
|
||||
}
|
||||
return [...seen];
|
||||
}, []);
|
||||
|
||||
return {
|
||||
undoBanner,
|
||||
recordEdit,
|
||||
@@ -305,5 +321,6 @@ export function useEditHistory(codeMode: { rootDir: string } | undefined): UseEd
|
||||
codeShowEdit,
|
||||
sealCurrentEntry,
|
||||
hasUndoable,
|
||||
touchedPaths,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,305 @@
|
||||
/**
|
||||
* Per-workspace edit checkpoints — Cursor-style "snapshot the files,
|
||||
* restore later" mechanism. Replaces the auto-commit feature that was
|
||||
* proposed and rejected on git-pollution grounds: instead of writing
|
||||
* every edit batch to git, we write opt-in named snapshots to a
|
||||
* dot-folder that lives outside the user's repo entirely.
|
||||
*
|
||||
* Storage layout:
|
||||
* ~/.reasonix/sessions/<sanitized-root>/checkpoints/index.json
|
||||
* ~/.reasonix/sessions/<sanitized-root>/checkpoints/<id>.json
|
||||
*
|
||||
* Each `<id>.json` is a complete file-content snapshot:
|
||||
* { id, name, createdAt, files: [{ path, content }] }
|
||||
*
|
||||
* `index.json` is a small lookup so `/checkpoint list` doesn't have
|
||||
* to load every snapshot off disk to enumerate them.
|
||||
*
|
||||
* Why one file per checkpoint instead of jsonl: deletion + selective
|
||||
* restore are common operations; rewriting a 50MB jsonl every time the
|
||||
* user runs `/checkpoint forget bad-attempt` is wasteful. Per-file
|
||||
* also means a corrupt snapshot only loses ONE checkpoint, not the
|
||||
* whole history.
|
||||
*
|
||||
* Why NOT git: see `feedback_internal_checkpoints_over_git.md` in
|
||||
* memory. Three reasons in one line: pollutes user's history, fights
|
||||
* with hooks, fails in non-git dirs.
|
||||
*/
|
||||
|
||||
import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { dirname, join, relative, resolve, sep } from "node:path";
|
||||
|
||||
/** One file's state at the time of snapshot. `content === null` → didn't exist. */
|
||||
export interface CheckpointFile {
|
||||
path: string;
|
||||
content: string | null;
|
||||
}
|
||||
|
||||
export interface Checkpoint {
|
||||
id: string;
|
||||
/** User-given name, or `auto-<reason>` for system-created snapshots. */
|
||||
name: string;
|
||||
/** Absolute workspace root the snapshot belongs to. */
|
||||
rootDir: string;
|
||||
createdAt: number;
|
||||
source: "manual" | "auto-session-start" | "auto-pre-restore";
|
||||
files: CheckpointFile[];
|
||||
/** Total bytes of file content captured (sum of `content?.length`). */
|
||||
bytes: number;
|
||||
}
|
||||
|
||||
export interface CheckpointMeta {
|
||||
id: string;
|
||||
name: string;
|
||||
createdAt: number;
|
||||
source: Checkpoint["source"];
|
||||
fileCount: number;
|
||||
bytes: number;
|
||||
}
|
||||
|
||||
/** Sanitize a directory path into a safe filesystem name for the store. */
|
||||
function sanitizeRoot(rootDir: string): string {
|
||||
return resolve(rootDir)
|
||||
.replace(/[\\/:]+/g, "_")
|
||||
.replace(/^_+/, "");
|
||||
}
|
||||
|
||||
function storeRoot(rootDir: string): string {
|
||||
return join(homedir(), ".reasonix", "sessions", sanitizeRoot(rootDir), "checkpoints");
|
||||
}
|
||||
|
||||
function indexPath(rootDir: string): string {
|
||||
return join(storeRoot(rootDir), "index.json");
|
||||
}
|
||||
|
||||
function snapshotPath(rootDir: string, id: string): string {
|
||||
return join(storeRoot(rootDir), `${id}.json`);
|
||||
}
|
||||
|
||||
/** Load the index of checkpoint metadata for a workspace. Empty when missing. */
|
||||
export function listCheckpoints(rootDir: string): CheckpointMeta[] {
|
||||
const path = indexPath(rootDir);
|
||||
if (!existsSync(path)) return [];
|
||||
try {
|
||||
const raw = readFileSync(path, "utf8");
|
||||
const parsed = JSON.parse(raw);
|
||||
if (!Array.isArray(parsed)) return [];
|
||||
// Defensive: filter out malformed entries rather than throwing on
|
||||
// a single bad row. A stale entry is annoying; a thrown listCheckpoints
|
||||
// would break /checkpoint list entirely.
|
||||
return parsed.filter(
|
||||
(m): m is CheckpointMeta =>
|
||||
typeof m === "object" &&
|
||||
m !== null &&
|
||||
typeof m.id === "string" &&
|
||||
typeof m.name === "string" &&
|
||||
typeof m.createdAt === "number" &&
|
||||
typeof m.source === "string" &&
|
||||
typeof m.fileCount === "number" &&
|
||||
typeof m.bytes === "number",
|
||||
);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function writeIndex(rootDir: string, items: CheckpointMeta[]): void {
|
||||
const path = indexPath(rootDir);
|
||||
mkdirSync(dirname(path), { recursive: true });
|
||||
writeFileSync(path, JSON.stringify(items, null, 2), "utf8");
|
||||
}
|
||||
|
||||
/** Read a single checkpoint by id. Returns null when missing or corrupt. */
|
||||
export function loadCheckpoint(rootDir: string, id: string): Checkpoint | null {
|
||||
const path = snapshotPath(rootDir, id);
|
||||
if (!existsSync(path)) return null;
|
||||
try {
|
||||
const raw = readFileSync(path, "utf8");
|
||||
const parsed = JSON.parse(raw);
|
||||
if (parsed && typeof parsed === "object" && Array.isArray(parsed.files)) {
|
||||
return parsed as Checkpoint;
|
||||
}
|
||||
return null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export interface CreateCheckpointOptions {
|
||||
rootDir: string;
|
||||
name: string;
|
||||
source?: Checkpoint["source"];
|
||||
/**
|
||||
* Repo-relative paths to snapshot. Caller decides what's "interesting"
|
||||
* — typically the union of (touched-this-session ∪ pending-edits ∪
|
||||
* a user-supplied path list). Empty list → empty snapshot, which is
|
||||
* legal for "session-start baseline" use cases.
|
||||
*/
|
||||
paths: readonly string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a checkpoint by capturing each path's current on-disk content.
|
||||
* Files that don't exist are recorded with `content: null` so a
|
||||
* subsequent restore knows to delete them. Returns the saved metadata.
|
||||
*
|
||||
* IDs are timestamp-based + a 4-char suffix to keep them collision-free
|
||||
* even when the user fires `/checkpoint name1` and `/checkpoint name2`
|
||||
* within the same millisecond (rare in practice but cheap to handle).
|
||||
*/
|
||||
export function createCheckpoint(opts: CreateCheckpointOptions): CheckpointMeta {
|
||||
const absRoot = resolve(opts.rootDir);
|
||||
const id = `cp-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`;
|
||||
const files: CheckpointFile[] = [];
|
||||
let bytes = 0;
|
||||
const seen = new Set<string>();
|
||||
for (const p of opts.paths) {
|
||||
if (seen.has(p)) continue;
|
||||
seen.add(p);
|
||||
const abs = resolve(absRoot, p);
|
||||
// Path-escape guard. A snapshot of `../../../etc/passwd` is not
|
||||
// something we want — refuse silently rather than abort the whole
|
||||
// checkpoint.
|
||||
if (abs !== absRoot && !abs.startsWith(`${absRoot}${sep}`)) continue;
|
||||
const rel = relative(absRoot, abs).split(sep).join("/");
|
||||
if (existsSync(abs)) {
|
||||
try {
|
||||
const content = readFileSync(abs, "utf8");
|
||||
files.push({ path: rel, content });
|
||||
bytes += content.length;
|
||||
} catch {
|
||||
// Unreadable (binary, perms) — record as null so restore knows
|
||||
// to delete on revert. Wrong for binary files but consistent.
|
||||
files.push({ path: rel, content: null });
|
||||
}
|
||||
} else {
|
||||
files.push({ path: rel, content: null });
|
||||
}
|
||||
}
|
||||
|
||||
const checkpoint: Checkpoint = {
|
||||
id,
|
||||
name: opts.name,
|
||||
rootDir: absRoot,
|
||||
createdAt: Date.now(),
|
||||
source: opts.source ?? "manual",
|
||||
files,
|
||||
bytes,
|
||||
};
|
||||
const cpPath = snapshotPath(absRoot, id);
|
||||
mkdirSync(dirname(cpPath), { recursive: true });
|
||||
writeFileSync(cpPath, JSON.stringify(checkpoint), "utf8");
|
||||
|
||||
const meta: CheckpointMeta = {
|
||||
id,
|
||||
name: opts.name,
|
||||
createdAt: checkpoint.createdAt,
|
||||
source: checkpoint.source,
|
||||
fileCount: files.length,
|
||||
bytes,
|
||||
};
|
||||
const items = listCheckpoints(absRoot);
|
||||
items.push(meta);
|
||||
writeIndex(absRoot, items);
|
||||
return meta;
|
||||
}
|
||||
|
||||
/**
|
||||
* Look up a checkpoint by id, or by name (most-recent wins on
|
||||
* collision). Returns null when nothing matches.
|
||||
*/
|
||||
export function findCheckpoint(rootDir: string, idOrName: string): CheckpointMeta | null {
|
||||
const items = listCheckpoints(rootDir);
|
||||
// Prefer exact id match, then most-recent name match.
|
||||
const byId = items.find((m) => m.id === idOrName);
|
||||
if (byId) return byId;
|
||||
const byName = [...items].reverse().find((m) => m.name === idOrName);
|
||||
return byName ?? null;
|
||||
}
|
||||
|
||||
export interface RestoreResult {
|
||||
/** Files we wrote back to disk. */
|
||||
restored: string[];
|
||||
/** Files we removed (snapshot had `content: null`, file existed). */
|
||||
removed: string[];
|
||||
/** Files we couldn't touch (errors), with the reason. */
|
||||
skipped: Array<{ path: string; reason: string }>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Restore a checkpoint. Returns a per-file report so the caller can
|
||||
* surface what landed and what didn't. Path-escape is double-checked
|
||||
* against the live `rootDir`, which may differ from the snapshot's
|
||||
* (e.g. user moved the project).
|
||||
*/
|
||||
export function restoreCheckpoint(rootDir: string, id: string): RestoreResult {
|
||||
const cp = loadCheckpoint(rootDir, id);
|
||||
const absRoot = resolve(rootDir);
|
||||
const result: RestoreResult = { restored: [], removed: [], skipped: [] };
|
||||
if (!cp) {
|
||||
result.skipped.push({ path: "(checkpoint)", reason: `not found: ${id}` });
|
||||
return result;
|
||||
}
|
||||
for (const f of cp.files) {
|
||||
const abs = resolve(absRoot, f.path);
|
||||
if (abs !== absRoot && !abs.startsWith(`${absRoot}${sep}`)) {
|
||||
result.skipped.push({ path: f.path, reason: "path escapes rootDir" });
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
if (f.content === null) {
|
||||
if (existsSync(abs)) {
|
||||
rmSync(abs);
|
||||
result.removed.push(f.path);
|
||||
}
|
||||
} else {
|
||||
mkdirSync(dirname(abs), { recursive: true });
|
||||
writeFileSync(abs, f.content, "utf8");
|
||||
result.restored.push(f.path);
|
||||
}
|
||||
} catch (err) {
|
||||
result.skipped.push({ path: f.path, reason: (err as Error).message });
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a checkpoint by id. Returns true iff the snapshot file +
|
||||
* index entry were both removed (or already absent in the case of a
|
||||
* partial-write left behind from a crash).
|
||||
*/
|
||||
export function deleteCheckpoint(rootDir: string, id: string): boolean {
|
||||
const cpPath = snapshotPath(rootDir, id);
|
||||
let removed = false;
|
||||
if (existsSync(cpPath)) {
|
||||
try {
|
||||
rmSync(cpPath);
|
||||
removed = true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
const items = listCheckpoints(rootDir);
|
||||
const next = items.filter((m) => m.id !== id);
|
||||
if (next.length !== items.length) {
|
||||
writeIndex(rootDir, next);
|
||||
removed = true;
|
||||
}
|
||||
return removed;
|
||||
}
|
||||
|
||||
/** Format ms-timestamp diff as human-readable relative age. */
|
||||
export function fmtAgo(ms: number): string {
|
||||
const now = Date.now();
|
||||
const diff = Math.max(0, now - ms);
|
||||
const s = Math.floor(diff / 1000);
|
||||
if (s < 60) return `${s}s ago`;
|
||||
const m = Math.floor(s / 60);
|
||||
if (m < 60) return `${m}m ago`;
|
||||
const h = Math.floor(m / 60);
|
||||
if (h < 24) return `${h}h ago`;
|
||||
const d = Math.floor(h / 24);
|
||||
return `${d}d ago`;
|
||||
}
|
||||
@@ -121,6 +121,146 @@ function countLines(s: string): number {
|
||||
return (s.match(/\n/g)?.length ?? 0) + 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* One row of a side-by-side diff. `left` is the old/before column,
|
||||
* `right` is the new/after column. `kind` drives color + glyph in
|
||||
* the renderer.
|
||||
*/
|
||||
export interface SplitDiffRow {
|
||||
left: { num: number | null; text: string; kind: "ctx" | "del" | "pad" };
|
||||
right: { num: number | null; text: string; kind: "ctx" | "add" | "pad" };
|
||||
}
|
||||
|
||||
export interface SplitDiffOptions extends DiffPreviewOptions {
|
||||
/** Starting 1-based line number for the old side. Default 1. */
|
||||
startLine?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Side-by-side diff rows for an EditBlock — git-difftool / delta-style
|
||||
* "old | new" layout. Each removed line pairs with the corresponding
|
||||
* added line at the same offset; unpaired remainders pad with blanks
|
||||
* on the missing side. Common leading/trailing context shows the same
|
||||
* line on both sides.
|
||||
*
|
||||
* Why pair rather than fully Myers-aligned: Myers needs an O(N²) edit
|
||||
* graph to compute LCS for arbitrary text. The SEARCH/REPLACE shape
|
||||
* here is small (typically <30 lines per block) and the fix usually
|
||||
* REPLACES a contiguous span — pairing by index gets the visually-
|
||||
* correct result for the 95% case without the algorithm cost.
|
||||
*/
|
||||
export function formatEditBlockSplit(
|
||||
block: EditBlock,
|
||||
opts: SplitDiffOptions = {},
|
||||
): SplitDiffRow[] {
|
||||
const contextLines = Math.max(0, opts.contextLines ?? 2);
|
||||
const maxLines = Math.max(4, opts.maxLines ?? 40);
|
||||
const startLine = opts.startLine ?? 1;
|
||||
|
||||
const search = block.search === "" ? [] : block.search.split("\n");
|
||||
const replace = block.replace.split("\n");
|
||||
|
||||
// New-file case: empty old column, every replace line on the right.
|
||||
if (search.length === 0) {
|
||||
const rows: SplitDiffRow[] = [];
|
||||
let n = startLine;
|
||||
for (const l of replace) {
|
||||
rows.push({
|
||||
left: { num: null, text: "", kind: "pad" },
|
||||
right: { num: n++, text: l, kind: "add" },
|
||||
});
|
||||
}
|
||||
return capRows(rows, maxLines);
|
||||
}
|
||||
|
||||
// Trim shared leading + trailing context — same logic as the
|
||||
// unified diff renderer, kept in lockstep so both stay accurate.
|
||||
let leading = 0;
|
||||
while (
|
||||
leading < search.length &&
|
||||
leading < replace.length &&
|
||||
search[leading] === replace[leading]
|
||||
) {
|
||||
leading++;
|
||||
}
|
||||
let trailing = 0;
|
||||
while (
|
||||
trailing < search.length - leading &&
|
||||
trailing < replace.length - leading &&
|
||||
search[search.length - 1 - trailing] === replace[replace.length - 1 - trailing]
|
||||
) {
|
||||
trailing++;
|
||||
}
|
||||
|
||||
const searchMiddle = search.slice(leading, search.length - trailing);
|
||||
const replaceMiddle = replace.slice(leading, replace.length - trailing);
|
||||
const leadStartIdx = Math.max(0, leading - contextLines);
|
||||
const leadShown = search.slice(leadStartIdx, leading);
|
||||
const trailShown = search.slice(
|
||||
search.length - trailing,
|
||||
search.length - trailing + contextLines,
|
||||
);
|
||||
|
||||
const rows: SplitDiffRow[] = [];
|
||||
let leftNum = startLine + leadStartIdx;
|
||||
let rightNum = startLine + leadStartIdx;
|
||||
|
||||
// Leading context — identical on both sides.
|
||||
for (const l of leadShown) {
|
||||
rows.push({
|
||||
left: { num: leftNum++, text: l, kind: "ctx" },
|
||||
right: { num: rightNum++, text: l, kind: "ctx" },
|
||||
});
|
||||
}
|
||||
|
||||
// Paired removed/added rows (up to min length).
|
||||
const pairedCount = Math.min(searchMiddle.length, replaceMiddle.length);
|
||||
for (let i = 0; i < pairedCount; i++) {
|
||||
rows.push({
|
||||
left: { num: leftNum++, text: searchMiddle[i]!, kind: "del" },
|
||||
right: { num: rightNum++, text: replaceMiddle[i]!, kind: "add" },
|
||||
});
|
||||
}
|
||||
// Extra removed lines (more old than new) — left only.
|
||||
for (let i = pairedCount; i < searchMiddle.length; i++) {
|
||||
rows.push({
|
||||
left: { num: leftNum++, text: searchMiddle[i]!, kind: "del" },
|
||||
right: { num: null, text: "", kind: "pad" },
|
||||
});
|
||||
}
|
||||
// Extra added lines (more new than old) — right only.
|
||||
for (let i = pairedCount; i < replaceMiddle.length; i++) {
|
||||
rows.push({
|
||||
left: { num: null, text: "", kind: "pad" },
|
||||
right: { num: rightNum++, text: replaceMiddle[i]!, kind: "add" },
|
||||
});
|
||||
}
|
||||
|
||||
// Trailing context — identical on both sides.
|
||||
for (const l of trailShown) {
|
||||
rows.push({
|
||||
left: { num: leftNum++, text: l, kind: "ctx" },
|
||||
right: { num: rightNum++, text: l, kind: "ctx" },
|
||||
});
|
||||
}
|
||||
|
||||
return capRows(rows, maxLines);
|
||||
}
|
||||
|
||||
function capRows(rows: SplitDiffRow[], maxRows: number): SplitDiffRow[] {
|
||||
if (rows.length <= maxRows) return rows;
|
||||
const head = rows.slice(0, maxRows - 1);
|
||||
const hidden = rows.length - head.length;
|
||||
// Replace the trailing slot with a "more lines hidden" marker row,
|
||||
// rendered as a pad on both sides with a special text so the
|
||||
// renderer can pick it up.
|
||||
head.push({
|
||||
left: { num: null, text: `… (${hidden} more lines)`, kind: "pad" },
|
||||
right: { num: null, text: "", kind: "pad" },
|
||||
});
|
||||
return head;
|
||||
}
|
||||
|
||||
function renderAllPlus(lines: string[], indent: string, maxLines: number): string[] {
|
||||
const out = lines.map((l) => `${indent}+ ${l}`);
|
||||
return capLines(out, maxLines, indent);
|
||||
|
||||
+16
-3
@@ -18,8 +18,21 @@ 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
|
||||
@@ -57,7 +70,7 @@ export interface ReasonixConfig {
|
||||
baseUrl?: string;
|
||||
/**
|
||||
* Default preset for `reasonix chat` / `reasonix run` when no flags override.
|
||||
* Maps to model + harvest + branch combos (see presets.ts). Missing → "fast".
|
||||
* Maps to model + autoEscalate (see presets.ts). Missing → "auto".
|
||||
*/
|
||||
preset?: PresetName;
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,288 @@
|
||||
/**
|
||||
* Event-log kernel — types only.
|
||||
*
|
||||
* Single source of truth for session state: every transition appends
|
||||
* a typed Event; every view is a pure reducer projection.
|
||||
* Reducers MUST NOT perform I/O. The bodies live in core/projections/*.
|
||||
*/
|
||||
|
||||
import type { PlanStep, PlanStepRisk, StepCompletion } from "../tools/plan-types.js";
|
||||
import type { ChatMessage, RawUsage, ToolCall } from "../types.js";
|
||||
|
||||
export type EventId = number;
|
||||
|
||||
export interface EventBase {
|
||||
id: EventId;
|
||||
ts: string;
|
||||
turn: number;
|
||||
}
|
||||
|
||||
export interface UserMessageEvent extends EventBase {
|
||||
type: "user.message";
|
||||
text: string;
|
||||
attachments?: ReadonlyArray<{ kind: "file" | "url"; ref: string }>;
|
||||
}
|
||||
|
||||
export interface SlashInvokedEvent extends EventBase {
|
||||
type: "slash.invoked";
|
||||
name: string;
|
||||
args: string;
|
||||
}
|
||||
|
||||
export interface ModelTurnStartedEvent extends EventBase {
|
||||
type: "model.turn.started";
|
||||
model: string;
|
||||
reasoningEffort: "high" | "max";
|
||||
prefixHash: string;
|
||||
}
|
||||
|
||||
export interface ModelDeltaEvent extends EventBase {
|
||||
type: "model.delta";
|
||||
channel: "content" | "reasoning" | "tool_args";
|
||||
text: string;
|
||||
toolCallIndex?: number;
|
||||
}
|
||||
|
||||
export interface ModelFinalEvent extends EventBase {
|
||||
type: "model.final";
|
||||
content: string;
|
||||
reasoningContent?: string;
|
||||
toolCalls: ReadonlyArray<ToolCall>;
|
||||
usage: RawUsage;
|
||||
costUsd: number;
|
||||
/** True iff this was the no-tools wrap-up after budget / abort / context guard. */
|
||||
forcedSummary?: boolean;
|
||||
}
|
||||
|
||||
export interface ToolIntentEvent extends EventBase {
|
||||
type: "tool.intent";
|
||||
callId: string;
|
||||
name: string;
|
||||
/** JSON string exactly as the model emitted it. */
|
||||
args: string;
|
||||
}
|
||||
|
||||
export interface ToolDispatchedEvent extends EventBase {
|
||||
type: "tool.dispatched";
|
||||
callId: string;
|
||||
}
|
||||
|
||||
export interface ToolDeniedEvent extends EventBase {
|
||||
type: "tool.denied";
|
||||
callId: string;
|
||||
reason: "permission" | "budget" | "policy" | "hook";
|
||||
}
|
||||
|
||||
export interface ToolResultEvent extends EventBase {
|
||||
type: "tool.result";
|
||||
callId: string;
|
||||
ok: boolean;
|
||||
output: string;
|
||||
truncated?: boolean;
|
||||
durationMs: number;
|
||||
}
|
||||
|
||||
export interface FileTouchedEvent extends EventBase {
|
||||
type: "effect.file.touched";
|
||||
path: string;
|
||||
mode: "create" | "edit" | "delete";
|
||||
bytes: number;
|
||||
}
|
||||
|
||||
export interface MemoryWrittenEvent extends EventBase {
|
||||
type: "effect.memory.written";
|
||||
scope: "user" | "project" | "hash";
|
||||
key: string;
|
||||
}
|
||||
|
||||
export interface PlanSubmittedEvent extends EventBase {
|
||||
type: "plan.submitted";
|
||||
steps: ReadonlyArray<PlanStep>;
|
||||
body: string;
|
||||
}
|
||||
|
||||
export interface PlanStepCompletedEvent extends EventBase {
|
||||
type: "plan.step.completed";
|
||||
stepId: string;
|
||||
title?: string;
|
||||
notes?: string;
|
||||
/** Raw payload echoed for replay; mirrors what the tool returned. */
|
||||
completion: StepCompletion;
|
||||
}
|
||||
|
||||
export interface CheckpointCreatedEvent extends EventBase {
|
||||
type: "checkpoint.created";
|
||||
checkpointId: string;
|
||||
name: string;
|
||||
source: "manual" | "auto-session-start" | "auto-pre-restore";
|
||||
fileCount: number;
|
||||
bytes: number;
|
||||
}
|
||||
|
||||
export interface CheckpointRestoredEvent extends EventBase {
|
||||
type: "checkpoint.restored";
|
||||
checkpointId: string;
|
||||
restored: number;
|
||||
removed: number;
|
||||
skipped: number;
|
||||
}
|
||||
|
||||
export interface HookFiredEvent extends EventBase {
|
||||
type: "hook.fired";
|
||||
hookName: string;
|
||||
phase: "PreToolUse" | "PostToolUse" | "UserPromptSubmit" | "Stop";
|
||||
outcome: "ok" | "blocked" | "modified" | "error";
|
||||
}
|
||||
|
||||
export interface BudgetWarningEvent extends EventBase {
|
||||
type: "policy.budget.warning";
|
||||
spentUsd: number;
|
||||
capUsd: number;
|
||||
}
|
||||
|
||||
export interface BudgetBlockedEvent extends EventBase {
|
||||
type: "policy.budget.blocked";
|
||||
spentUsd: number;
|
||||
capUsd: number;
|
||||
}
|
||||
|
||||
export interface EscalatedEvent extends EventBase {
|
||||
type: "policy.escalated";
|
||||
fromModel: string;
|
||||
toModel: string;
|
||||
reason: "self-report" | "failure-threshold" | "user-request";
|
||||
/** Optional one-liner rationale from the `<<<NEEDS_PRO: ...>>>` form. */
|
||||
rationale?: string;
|
||||
}
|
||||
|
||||
export interface SessionOpenedEvent extends EventBase {
|
||||
type: "session.opened";
|
||||
name: string;
|
||||
resumedFromTurn: number;
|
||||
}
|
||||
|
||||
export interface SessionCompactedEvent extends EventBase {
|
||||
type: "session.compacted";
|
||||
beforeMessages: number;
|
||||
afterMessages: number;
|
||||
reason: "user" | "auto-context-pressure";
|
||||
/** Post-compact message list. Only event that REPLACES (not appends) the conversation view. */
|
||||
replacementMessages: ReadonlyArray<ChatMessage>;
|
||||
}
|
||||
|
||||
export interface CapabilityRegisteredEvent extends EventBase {
|
||||
type: "capability.registered";
|
||||
name: string;
|
||||
permission: "ask" | "allow" | "deny";
|
||||
}
|
||||
|
||||
export interface CapabilityRemovedEvent extends EventBase {
|
||||
type: "capability.removed";
|
||||
name: string;
|
||||
}
|
||||
|
||||
/** Transient — never persisted, drops on next primary event. */
|
||||
export interface StatusEvent extends EventBase {
|
||||
type: "status";
|
||||
text: string;
|
||||
}
|
||||
|
||||
export interface ErrorEvent extends EventBase {
|
||||
type: "error";
|
||||
message: string;
|
||||
recoverable: boolean;
|
||||
}
|
||||
|
||||
export type Event =
|
||||
| UserMessageEvent
|
||||
| SlashInvokedEvent
|
||||
| ModelTurnStartedEvent
|
||||
| ModelDeltaEvent
|
||||
| ModelFinalEvent
|
||||
| ToolIntentEvent
|
||||
| ToolDispatchedEvent
|
||||
| ToolDeniedEvent
|
||||
| ToolResultEvent
|
||||
| FileTouchedEvent
|
||||
| MemoryWrittenEvent
|
||||
| PlanSubmittedEvent
|
||||
| PlanStepCompletedEvent
|
||||
| CheckpointCreatedEvent
|
||||
| CheckpointRestoredEvent
|
||||
| HookFiredEvent
|
||||
| BudgetWarningEvent
|
||||
| BudgetBlockedEvent
|
||||
| EscalatedEvent
|
||||
| SessionOpenedEvent
|
||||
| SessionCompactedEvent
|
||||
| CapabilityRegisteredEvent
|
||||
| CapabilityRemovedEvent
|
||||
| StatusEvent
|
||||
| ErrorEvent;
|
||||
|
||||
export type EventOf<T extends Event["type"]> = Extract<Event, { type: T }>;
|
||||
|
||||
/** Pure projection: folds an event slice into a view. No I/O. */
|
||||
export type Reducer<TView> = (view: TView, ev: Event) => TView;
|
||||
|
||||
export interface ConversationView {
|
||||
messages: ReadonlyArray<ChatMessage>;
|
||||
pendingToolCalls: ReadonlyArray<{ callId: string; name: string }>;
|
||||
}
|
||||
|
||||
export interface BudgetView {
|
||||
spentUsd: number;
|
||||
capUsd: number | null;
|
||||
promptTokens: number;
|
||||
completionTokens: number;
|
||||
cacheHitTokens: number;
|
||||
cacheMissTokens: number;
|
||||
warned: boolean;
|
||||
blocked: boolean;
|
||||
}
|
||||
|
||||
export interface PlanStepView {
|
||||
id: string;
|
||||
title: string;
|
||||
action: string;
|
||||
risk?: PlanStepRisk;
|
||||
completed: boolean;
|
||||
notes?: string;
|
||||
}
|
||||
|
||||
export interface PlanView {
|
||||
steps: ReadonlyArray<PlanStepView>;
|
||||
body: string | null;
|
||||
submittedTurn: number | null;
|
||||
}
|
||||
|
||||
export interface WorkspaceView {
|
||||
filesTouched: ReadonlyMap<string, "create" | "edit" | "delete">;
|
||||
lastCheckpointId: string | null;
|
||||
}
|
||||
|
||||
export interface CapabilityView {
|
||||
tools: ReadonlyArray<{ name: string; permission: "ask" | "allow" | "deny" }>;
|
||||
}
|
||||
|
||||
export interface StatusView {
|
||||
current: string | null;
|
||||
}
|
||||
|
||||
export interface SessionMetaView {
|
||||
name: string | null;
|
||||
openedAt: string | null;
|
||||
resumedFromTurn: number | null;
|
||||
currentTurn: number;
|
||||
lastError: string | null;
|
||||
}
|
||||
|
||||
export interface ProjectionSet {
|
||||
conversation: ConversationView;
|
||||
budget: BudgetView;
|
||||
plan: PlanView;
|
||||
workspace: WorkspaceView;
|
||||
capabilities: CapabilityView;
|
||||
status: StatusView;
|
||||
session: SessionMetaView;
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
/**
|
||||
* Pure projection reducers over the Event log. No I/O. No mutation.
|
||||
* Each reducer must be deterministic: same (view, ev) → same view.
|
||||
*/
|
||||
|
||||
import type { ChatMessage } from "../types.js";
|
||||
import type {
|
||||
BudgetView,
|
||||
CapabilityView,
|
||||
ConversationView,
|
||||
Event,
|
||||
PlanStepView,
|
||||
PlanView,
|
||||
ProjectionSet,
|
||||
Reducer,
|
||||
SessionMetaView,
|
||||
StatusView,
|
||||
WorkspaceView,
|
||||
} from "./events.js";
|
||||
|
||||
export function emptyConversation(): ConversationView {
|
||||
return { messages: [], pendingToolCalls: [] };
|
||||
}
|
||||
|
||||
export function emptyBudget(capUsd: number | null = null): BudgetView {
|
||||
return {
|
||||
spentUsd: 0,
|
||||
capUsd,
|
||||
promptTokens: 0,
|
||||
completionTokens: 0,
|
||||
cacheHitTokens: 0,
|
||||
cacheMissTokens: 0,
|
||||
warned: false,
|
||||
blocked: false,
|
||||
};
|
||||
}
|
||||
|
||||
export function emptyPlan(): PlanView {
|
||||
return { steps: [], body: null, submittedTurn: null };
|
||||
}
|
||||
|
||||
export function emptyWorkspace(): WorkspaceView {
|
||||
return { filesTouched: new Map(), lastCheckpointId: null };
|
||||
}
|
||||
|
||||
export function emptyCapabilities(): CapabilityView {
|
||||
return { tools: [] };
|
||||
}
|
||||
|
||||
export function emptyStatus(): StatusView {
|
||||
return { current: null };
|
||||
}
|
||||
|
||||
export function emptySessionMeta(): SessionMetaView {
|
||||
return {
|
||||
name: null,
|
||||
openedAt: null,
|
||||
resumedFromTurn: null,
|
||||
currentTurn: 0,
|
||||
lastError: null,
|
||||
};
|
||||
}
|
||||
|
||||
export function emptyProjections(capUsd: number | null = null): ProjectionSet {
|
||||
return {
|
||||
conversation: emptyConversation(),
|
||||
budget: emptyBudget(capUsd),
|
||||
plan: emptyPlan(),
|
||||
workspace: emptyWorkspace(),
|
||||
capabilities: emptyCapabilities(),
|
||||
status: emptyStatus(),
|
||||
session: emptySessionMeta(),
|
||||
};
|
||||
}
|
||||
|
||||
export const conversation: Reducer<ConversationView> = (v, ev) => {
|
||||
switch (ev.type) {
|
||||
case "user.message": {
|
||||
const msg: ChatMessage = { role: "user", content: ev.text };
|
||||
return { ...v, messages: [...v.messages, msg] };
|
||||
}
|
||||
case "model.final": {
|
||||
const msg: ChatMessage = { role: "assistant", content: ev.content };
|
||||
if (ev.toolCalls.length > 0) msg.tool_calls = [...ev.toolCalls];
|
||||
if (ev.reasoningContent !== undefined) msg.reasoning_content = ev.reasoningContent;
|
||||
return { ...v, messages: [...v.messages, msg] };
|
||||
}
|
||||
case "tool.intent":
|
||||
return {
|
||||
...v,
|
||||
pendingToolCalls: [...v.pendingToolCalls, { callId: ev.callId, name: ev.name }],
|
||||
};
|
||||
case "tool.result": {
|
||||
const msg: ChatMessage = { role: "tool", content: ev.output, tool_call_id: ev.callId };
|
||||
return {
|
||||
messages: [...v.messages, msg],
|
||||
pendingToolCalls: v.pendingToolCalls.filter((c) => c.callId !== ev.callId),
|
||||
};
|
||||
}
|
||||
case "tool.denied": {
|
||||
const msg: ChatMessage = {
|
||||
role: "tool",
|
||||
content: `denied: ${ev.reason}`,
|
||||
tool_call_id: ev.callId,
|
||||
};
|
||||
return {
|
||||
messages: [...v.messages, msg],
|
||||
pendingToolCalls: v.pendingToolCalls.filter((c) => c.callId !== ev.callId),
|
||||
};
|
||||
}
|
||||
case "session.compacted":
|
||||
return { messages: [...ev.replacementMessages], pendingToolCalls: [] };
|
||||
default:
|
||||
return v;
|
||||
}
|
||||
};
|
||||
|
||||
export const budget: Reducer<BudgetView> = (v, ev) => {
|
||||
switch (ev.type) {
|
||||
case "model.final": {
|
||||
const u = ev.usage;
|
||||
return {
|
||||
...v,
|
||||
spentUsd: v.spentUsd + ev.costUsd,
|
||||
promptTokens: v.promptTokens + (u.prompt_tokens ?? 0),
|
||||
completionTokens: v.completionTokens + (u.completion_tokens ?? 0),
|
||||
cacheHitTokens: v.cacheHitTokens + (u.prompt_cache_hit_tokens ?? 0),
|
||||
cacheMissTokens: v.cacheMissTokens + (u.prompt_cache_miss_tokens ?? 0),
|
||||
};
|
||||
}
|
||||
case "policy.budget.warning":
|
||||
return { ...v, warned: true };
|
||||
case "policy.budget.blocked":
|
||||
return { ...v, blocked: true };
|
||||
default:
|
||||
return v;
|
||||
}
|
||||
};
|
||||
|
||||
export const plan: Reducer<PlanView> = (v, ev) => {
|
||||
switch (ev.type) {
|
||||
case "plan.submitted": {
|
||||
const steps: PlanStepView[] = ev.steps.map((s) => ({
|
||||
id: s.id,
|
||||
title: s.title,
|
||||
action: s.action,
|
||||
risk: s.risk,
|
||||
completed: false,
|
||||
}));
|
||||
return { steps, body: ev.body, submittedTurn: ev.turn };
|
||||
}
|
||||
case "plan.step.completed": {
|
||||
if (!v.steps.some((s) => s.id === ev.stepId)) return v;
|
||||
return {
|
||||
...v,
|
||||
steps: v.steps.map((s) =>
|
||||
s.id === ev.stepId ? { ...s, completed: true, notes: ev.notes } : s,
|
||||
),
|
||||
};
|
||||
}
|
||||
default:
|
||||
return v;
|
||||
}
|
||||
};
|
||||
|
||||
export const workspace: Reducer<WorkspaceView> = (v, ev) => {
|
||||
switch (ev.type) {
|
||||
case "effect.file.touched": {
|
||||
const next = new Map(v.filesTouched);
|
||||
next.set(ev.path, ev.mode);
|
||||
return { ...v, filesTouched: next };
|
||||
}
|
||||
case "checkpoint.created":
|
||||
return { ...v, lastCheckpointId: ev.checkpointId };
|
||||
default:
|
||||
return v;
|
||||
}
|
||||
};
|
||||
|
||||
export const capabilities: Reducer<CapabilityView> = (v, ev) => {
|
||||
switch (ev.type) {
|
||||
case "capability.registered": {
|
||||
const filtered = v.tools.filter((t) => t.name !== ev.name);
|
||||
return { tools: [...filtered, { name: ev.name, permission: ev.permission }] };
|
||||
}
|
||||
case "capability.removed":
|
||||
return { tools: v.tools.filter((t) => t.name !== ev.name) };
|
||||
default:
|
||||
return v;
|
||||
}
|
||||
};
|
||||
|
||||
const STATUS_CLEARING: ReadonlySet<Event["type"]> = new Set([
|
||||
"model.delta",
|
||||
"model.final",
|
||||
"tool.dispatched",
|
||||
"tool.result",
|
||||
"tool.denied",
|
||||
"error",
|
||||
]);
|
||||
|
||||
export const status: Reducer<StatusView> = (v, ev) => {
|
||||
if (ev.type === "status") return { current: ev.text };
|
||||
if (STATUS_CLEARING.has(ev.type) && v.current !== null) return { current: null };
|
||||
return v;
|
||||
};
|
||||
|
||||
export const sessionMeta: Reducer<SessionMetaView> = (v, ev) => {
|
||||
let next = v;
|
||||
if (ev.turn > next.currentTurn) next = { ...next, currentTurn: ev.turn };
|
||||
switch (ev.type) {
|
||||
case "session.opened":
|
||||
return {
|
||||
...next,
|
||||
name: ev.name,
|
||||
openedAt: ev.ts,
|
||||
resumedFromTurn: ev.resumedFromTurn,
|
||||
};
|
||||
case "error":
|
||||
return { ...next, lastError: ev.message };
|
||||
default:
|
||||
return next;
|
||||
}
|
||||
};
|
||||
|
||||
export function apply(state: ProjectionSet, ev: Event): ProjectionSet {
|
||||
return {
|
||||
conversation: conversation(state.conversation, ev),
|
||||
budget: budget(state.budget, ev),
|
||||
plan: plan(state.plan, ev),
|
||||
workspace: workspace(state.workspace, ev),
|
||||
capabilities: capabilities(state.capabilities, ev),
|
||||
status: status(state.status, ev),
|
||||
session: sessionMeta(state.session, ev),
|
||||
};
|
||||
}
|
||||
|
||||
export function replay(events: Iterable<Event>, capUsd: number | null = null): ProjectionSet {
|
||||
let s = emptyProjections(capUsd);
|
||||
for (const ev of events) s = apply(s, ev);
|
||||
return s;
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
/**
|
||||
* Frame → ANSI conversion. Used by:
|
||||
* · snapshot tests — serialise a Frame to a plaintext-or-ANSI
|
||||
* string for inspection / vitest snapshots
|
||||
* · the eventual Phase-4 paint layer — write output directly to
|
||||
* stdout, bypassing Ink's render tree
|
||||
*
|
||||
* The serializer batches consecutive cells with identical style
|
||||
* into one ANSI run so we don't emit a SGR escape per cell — that
|
||||
* would balloon a 200×50 frame to 50KB+ of escapes for a few KB of
|
||||
* actual text. For the snapshot use case we also support a
|
||||
* `plain: true` mode that drops all styling.
|
||||
*/
|
||||
|
||||
import type { Cell, Frame, FrameRow } from "./types.js";
|
||||
|
||||
const ESC = "\u001b";
|
||||
const RESET = `${ESC}[0m`;
|
||||
|
||||
interface Style {
|
||||
fg?: string;
|
||||
bg?: string;
|
||||
bold?: boolean;
|
||||
dim?: boolean;
|
||||
italic?: boolean;
|
||||
underline?: boolean;
|
||||
inverse?: boolean;
|
||||
href?: string;
|
||||
}
|
||||
|
||||
function sameStyle(a: Style, b: Style): boolean {
|
||||
return (
|
||||
a.fg === b.fg &&
|
||||
a.bg === b.bg &&
|
||||
!!a.bold === !!b.bold &&
|
||||
!!a.dim === !!b.dim &&
|
||||
!!a.italic === !!b.italic &&
|
||||
!!a.underline === !!b.underline &&
|
||||
!!a.inverse === !!b.inverse &&
|
||||
a.href === b.href
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert hex `#rrggbb` → ANSI 38;2;r;g;b. Accepts named ANSI colors
|
||||
* ("red", "cyan", etc.) by mapping to the standard 4-bit codes.
|
||||
* Returns null for unknown color names; caller skips emitting a
|
||||
* color escape for those.
|
||||
*/
|
||||
function fgEscape(color: string | undefined): string | null {
|
||||
if (!color) return null;
|
||||
const rgb = parseColor(color);
|
||||
if (rgb) return `38;2;${rgb[0]};${rgb[1]};${rgb[2]}`;
|
||||
const named = NAMED_FG[color.toLowerCase()];
|
||||
if (named !== undefined) return String(named);
|
||||
return null;
|
||||
}
|
||||
|
||||
function bgEscape(color: string | undefined): string | null {
|
||||
if (!color) return null;
|
||||
const rgb = parseColor(color);
|
||||
if (rgb) return `48;2;${rgb[0]};${rgb[1]};${rgb[2]}`;
|
||||
const named = NAMED_BG[color.toLowerCase()];
|
||||
if (named !== undefined) return String(named);
|
||||
return null;
|
||||
}
|
||||
|
||||
function parseColor(s: string): [number, number, number] | null {
|
||||
if (!s.startsWith("#")) return null;
|
||||
const hex = s.slice(1);
|
||||
if (hex.length !== 6) return null;
|
||||
const r = Number.parseInt(hex.slice(0, 2), 16);
|
||||
const g = Number.parseInt(hex.slice(2, 4), 16);
|
||||
const b = Number.parseInt(hex.slice(4, 6), 16);
|
||||
if (Number.isNaN(r) || Number.isNaN(g) || Number.isNaN(b)) return null;
|
||||
return [r, g, b];
|
||||
}
|
||||
|
||||
const NAMED_FG: Record<string, number> = {
|
||||
black: 30,
|
||||
red: 31,
|
||||
green: 32,
|
||||
yellow: 33,
|
||||
blue: 34,
|
||||
magenta: 35,
|
||||
cyan: 36,
|
||||
white: 37,
|
||||
gray: 90,
|
||||
grey: 90,
|
||||
brightred: 91,
|
||||
brightgreen: 92,
|
||||
brightyellow: 93,
|
||||
brightblue: 94,
|
||||
brightmagenta: 95,
|
||||
brightcyan: 96,
|
||||
brightwhite: 97,
|
||||
};
|
||||
|
||||
const NAMED_BG: Record<string, number> = {
|
||||
black: 40,
|
||||
red: 41,
|
||||
green: 42,
|
||||
yellow: 43,
|
||||
blue: 44,
|
||||
magenta: 45,
|
||||
cyan: 46,
|
||||
white: 47,
|
||||
gray: 100,
|
||||
grey: 100,
|
||||
};
|
||||
|
||||
function styleToAnsi(s: Style): string {
|
||||
const codes: string[] = [];
|
||||
if (s.bold) codes.push("1");
|
||||
if (s.dim) codes.push("2");
|
||||
if (s.italic) codes.push("3");
|
||||
if (s.underline) codes.push("4");
|
||||
if (s.inverse) codes.push("7");
|
||||
const fg = fgEscape(s.fg);
|
||||
if (fg) codes.push(fg);
|
||||
const bg = bgEscape(s.bg);
|
||||
if (bg) codes.push(bg);
|
||||
if (codes.length === 0) return "";
|
||||
return `${ESC}[${codes.join(";")}m`;
|
||||
}
|
||||
|
||||
const EMPTY_STYLE: Style = {};
|
||||
|
||||
/**
|
||||
* Serialize a Frame to an ANSI-encoded string. Rows are joined with
|
||||
* `\n`. Each row is a sequence of style runs followed by RESET at
|
||||
* end-of-row so styling never bleeds onto the next line.
|
||||
*
|
||||
* In `plain: true` mode, only the visible characters are emitted —
|
||||
* useful for snapshot tests that want a stable, diffable string.
|
||||
*/
|
||||
export function frameToAnsi(f: Frame, opts: { plain?: boolean } = {}): string {
|
||||
const out: string[] = [];
|
||||
for (let i = 0; i < f.rows.length; i++) {
|
||||
out.push(rowToAnsi(f.rows[i]!, opts));
|
||||
}
|
||||
return out.join("\n");
|
||||
}
|
||||
|
||||
function rowToAnsi(row: FrameRow, opts: { plain?: boolean }): string {
|
||||
if (opts.plain) {
|
||||
let s = "";
|
||||
for (const c of row) {
|
||||
if (c.tail) continue;
|
||||
s += c.char;
|
||||
}
|
||||
return s;
|
||||
}
|
||||
let result = "";
|
||||
let curStyle = EMPTY_STYLE;
|
||||
let inHref = false;
|
||||
let curHref: string | undefined;
|
||||
|
||||
for (const c of row) {
|
||||
if (c.tail) continue; // tail cells contribute no visible output
|
||||
const cellStyle: Style = {
|
||||
fg: c.fg,
|
||||
bg: c.bg,
|
||||
bold: c.bold,
|
||||
dim: c.dim,
|
||||
italic: c.italic,
|
||||
underline: c.underline,
|
||||
inverse: c.inverse,
|
||||
href: c.href,
|
||||
};
|
||||
// OSC-8 hyperlink open/close
|
||||
if (cellStyle.href !== curHref) {
|
||||
if (inHref) {
|
||||
// close prior link
|
||||
result += `${ESC}]8;;${ESC}\\`;
|
||||
inHref = false;
|
||||
}
|
||||
if (cellStyle.href !== undefined) {
|
||||
result += `${ESC}]8;;${cellStyle.href}${ESC}\\`;
|
||||
inHref = true;
|
||||
}
|
||||
curHref = cellStyle.href;
|
||||
}
|
||||
// SGR styling — emit only when changed
|
||||
if (!sameStyle(curStyle, cellStyle)) {
|
||||
// Reset before applying new style so e.g. bold→non-bold works
|
||||
// (some terminals don't have a "turn off bold" code reliably).
|
||||
result += RESET;
|
||||
result += styleToAnsi(cellStyle);
|
||||
curStyle = cellStyle;
|
||||
}
|
||||
result += c.char;
|
||||
}
|
||||
if (inHref) result += `${ESC}]8;;${ESC}\\`;
|
||||
result += RESET;
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute the visible (no-style) string for a row. Same as
|
||||
* `frameToAnsi(f, { plain: true })` for one row; convenient for
|
||||
* targeted assertions in tests without slicing the whole frame.
|
||||
*/
|
||||
export function rowText(row: FrameRow): string {
|
||||
let s = "";
|
||||
for (const c of row) {
|
||||
if (c.tail) continue;
|
||||
s += c.char;
|
||||
}
|
||||
return s;
|
||||
}
|
||||
@@ -0,0 +1,297 @@
|
||||
/**
|
||||
* Frame primitives. Pure functions on the `Frame` data type — no
|
||||
* Ink, no React, no side effects. Every primitive maintains the
|
||||
* row-width invariant: every `FrameRow` has cells whose total
|
||||
* visual width (counting `tail` cells for 2-wide chars) equals
|
||||
* `Frame.width`.
|
||||
*
|
||||
* Composition rules:
|
||||
* · `vstack(...frames)` — pad narrower frames on the right with
|
||||
* spaces to the widest, then concat row arrays
|
||||
* · `hstack(...frames)` — pad shorter frames on the bottom with
|
||||
* blank rows to the tallest, then concat each row
|
||||
* · `pad(f, t,r,b,l)` — add blank cells around the existing frame
|
||||
* · `borderLeft(f, color)` — prepend a 1-cell colored vertical bar
|
||||
* · `slice(f, top, height)` — pick consecutive rows; out-of-range
|
||||
* bounds clamp gracefully
|
||||
* · `overlay(base, top, x, y)` — paint `top` over `base` at (x, y),
|
||||
* clipping to base bounds
|
||||
*
|
||||
* These are the building blocks for Phase 2 (EventLog as Frame
|
||||
* compiler). Tests in `tests/frame.test.ts` lock the invariants.
|
||||
*/
|
||||
|
||||
import type { Cell, Frame, FrameRow, TextOpts } from "./types.js";
|
||||
import { graphemeWidth, graphemes } from "./width.js";
|
||||
|
||||
// ─── construction ────────────────────────────────────────────────
|
||||
|
||||
/** Single space cell with no styling — the universal padding atom. */
|
||||
const SPACE: Cell = { char: " ", width: 1 };
|
||||
/** Single space cell with `tail: true` — cell occupied by a 2-wide
|
||||
* char's tail half. Carries no visual weight, only alignment. */
|
||||
const TAIL: Cell = { char: "", width: 1, tail: true };
|
||||
|
||||
/** Empty frame (no rows) at the given width. Used as a base case
|
||||
* for vstack/hstack reductions. */
|
||||
export function empty(width = 0): Frame {
|
||||
return { width, rows: [] };
|
||||
}
|
||||
|
||||
/**
|
||||
* Frame full of spaces at the given dimensions. Useful as a base
|
||||
* for `overlay` or as a vertical spacer in `vstack`.
|
||||
*/
|
||||
export function blank(width: number, height: number): Frame {
|
||||
if (width <= 0 || height <= 0) return empty(Math.max(0, width));
|
||||
const row: FrameRow = Object.freeze(Array.from({ length: width }, () => SPACE));
|
||||
const rows: FrameRow[] = [];
|
||||
for (let i = 0; i < height; i++) rows.push(row);
|
||||
return { width, rows };
|
||||
}
|
||||
|
||||
/**
|
||||
* Render a string into a frame, wrapping at `opts.width`. Each
|
||||
* grapheme becomes one cell (width 1) or occupies two cells (width
|
||||
* 2 + tail). Newlines start a new row; lines longer than `width`
|
||||
* wrap at the grapheme boundary that overflows.
|
||||
*
|
||||
* Empty input → empty frame at the requested width (zero rows).
|
||||
* Single newline → one blank row.
|
||||
*/
|
||||
export function text(s: string, opts: TextOpts): Frame {
|
||||
const { width, fg, bg, bold, dim, italic, underline, inverse, href } = opts;
|
||||
if (width <= 0) return empty(0);
|
||||
|
||||
const styleOf = (g: string, w: 1 | 2): Cell => {
|
||||
const base: Cell = { char: g, width: w };
|
||||
if (fg !== undefined) base.fg = fg;
|
||||
if (bg !== undefined) base.bg = bg;
|
||||
if (bold) base.bold = true;
|
||||
if (dim) base.dim = true;
|
||||
if (italic) base.italic = true;
|
||||
if (underline) base.underline = true;
|
||||
if (inverse) base.inverse = true;
|
||||
if (href !== undefined) base.href = href;
|
||||
return base;
|
||||
};
|
||||
|
||||
const rows: FrameRow[] = [];
|
||||
const lines = s.split("\n");
|
||||
for (const line of lines) {
|
||||
if (line.length === 0) {
|
||||
rows.push(padRowRight([], width));
|
||||
continue;
|
||||
}
|
||||
let buf: Cell[] = [];
|
||||
let bufWidth = 0;
|
||||
for (const g of graphemes(line)) {
|
||||
const w = graphemeWidth(g);
|
||||
if (w === 0) continue; // combining mark / ZWJ — already part of prior cell
|
||||
if (bufWidth + w > width) {
|
||||
rows.push(padRowRight(buf, width - bufWidth));
|
||||
buf = [];
|
||||
bufWidth = 0;
|
||||
}
|
||||
buf.push(styleOf(g, w as 1 | 2));
|
||||
if (w === 2) buf.push(TAIL);
|
||||
bufWidth += w;
|
||||
}
|
||||
rows.push(padRowRight(buf, width - bufWidth));
|
||||
}
|
||||
return { width, rows };
|
||||
}
|
||||
|
||||
/**
|
||||
* Pad a partial row to the target width with trailing spaces.
|
||||
* Used internally by primitives that produce rows of varying
|
||||
* width; the public Frame always has uniform-width rows.
|
||||
*/
|
||||
function padRowRight(cells: Cell[], extraSpaces: number): FrameRow {
|
||||
if (extraSpaces <= 0) return cells.slice();
|
||||
const out = cells.slice();
|
||||
for (let i = 0; i < extraSpaces; i++) out.push(SPACE);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Generate a row of pure-space padding at the given width. */
|
||||
function spacerRow(width: number): FrameRow {
|
||||
if (width <= 0) return [];
|
||||
return Array.from({ length: width }, () => SPACE);
|
||||
}
|
||||
|
||||
// ─── composition ─────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Stack frames vertically. Result width is `max(f.width)` — narrower
|
||||
* frames are right-padded with spaces. Result height is `sum(f.rows.length)`.
|
||||
*/
|
||||
export function vstack(...frames: Frame[]): Frame {
|
||||
if (frames.length === 0) return empty(0);
|
||||
const w = Math.max(...frames.map((f) => f.width));
|
||||
const rows: FrameRow[] = [];
|
||||
for (const f of frames) {
|
||||
if (f.width === w) {
|
||||
rows.push(...f.rows);
|
||||
} else {
|
||||
const extra = w - f.width;
|
||||
for (const r of f.rows) rows.push(padRowRight(r as Cell[], extra));
|
||||
}
|
||||
}
|
||||
return { width: w, rows };
|
||||
}
|
||||
|
||||
/**
|
||||
* Stack frames horizontally. Result height is `max(f.rows.length)` —
|
||||
* shorter frames are bottom-padded with blank rows of their own
|
||||
* width. Result width is `sum(f.width)`.
|
||||
*/
|
||||
export function hstack(...frames: Frame[]): Frame {
|
||||
if (frames.length === 0) return empty(0);
|
||||
const h = Math.max(...frames.map((f) => f.rows.length));
|
||||
const w = frames.reduce((a, f) => a + f.width, 0);
|
||||
const rows: FrameRow[] = [];
|
||||
for (let i = 0; i < h; i++) {
|
||||
const cells: Cell[] = [];
|
||||
for (const f of frames) {
|
||||
const r = f.rows[i] ?? spacerRow(f.width);
|
||||
cells.push(...r);
|
||||
}
|
||||
rows.push(cells);
|
||||
}
|
||||
return { width: w, rows };
|
||||
}
|
||||
|
||||
/**
|
||||
* Add space padding around a frame. Padding is in CELLS (visual
|
||||
* columns), not graphemes — `pad(f, 1, 0, 1, 0)` adds one row above
|
||||
* and below, leaving width unchanged.
|
||||
*/
|
||||
export function pad(f: Frame, top: number, right: number, bottom: number, left: number): Frame {
|
||||
const newWidth = f.width + Math.max(0, left) + Math.max(0, right);
|
||||
const tPad = Math.max(0, top);
|
||||
const bPad = Math.max(0, bottom);
|
||||
const blank = spacerRow(newWidth);
|
||||
const rows: FrameRow[] = [];
|
||||
for (let i = 0; i < tPad; i++) rows.push(blank);
|
||||
if (left <= 0 && right <= 0) {
|
||||
rows.push(...f.rows);
|
||||
} else {
|
||||
const lPad = spacerRow(Math.max(0, left));
|
||||
const rPad = spacerRow(Math.max(0, right));
|
||||
for (const r of f.rows) rows.push([...lPad, ...r, ...rPad]);
|
||||
}
|
||||
for (let i = 0; i < bPad; i++) rows.push(blank);
|
||||
return { width: newWidth, rows };
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepend a 1-cell vertical bar to every row. This is the row-by-row
|
||||
* equivalent of Ink's `borderLeft` — used for the chat accent bar
|
||||
* (`▎`-style left rule indicating "this is one log entry").
|
||||
*/
|
||||
export function borderLeft(f: Frame, color: string, char = "│"): Frame {
|
||||
const bar: Cell = { char, width: 1, fg: color };
|
||||
const newWidth = f.width + 1;
|
||||
const rows: FrameRow[] = [];
|
||||
for (const r of f.rows) rows.push([bar, ...r]);
|
||||
return { width: newWidth, rows };
|
||||
}
|
||||
|
||||
// ─── slicing ─────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Pick `height` consecutive rows starting at index `top`. Out-of-range
|
||||
* bounds clamp to the available range — never throws. Returns an
|
||||
* empty-row frame at the same width when the request is entirely
|
||||
* beyond the source.
|
||||
*/
|
||||
export function slice(f: Frame, top: number, height: number): Frame {
|
||||
if (height <= 0 || f.rows.length === 0) return { width: f.width, rows: [] };
|
||||
const start = Math.max(0, Math.min(top, f.rows.length));
|
||||
const end = Math.max(start, Math.min(start + height, f.rows.length));
|
||||
return { width: f.width, rows: f.rows.slice(start, end) };
|
||||
}
|
||||
|
||||
/**
|
||||
* Take exactly `height` rows from the BOTTOM of a frame. Used by the
|
||||
* scroll viewport at offset=0 — "show the most recent N rows of the
|
||||
* stack". Equivalent to `slice(f, max(0, rows.length - height), height)`
|
||||
* but reads more clearly at call sites.
|
||||
*/
|
||||
export function bottom(f: Frame, height: number): Frame {
|
||||
if (height <= 0) return { width: f.width, rows: [] };
|
||||
return slice(f, Math.max(0, f.rows.length - height), height);
|
||||
}
|
||||
|
||||
/**
|
||||
* Take exactly `height` rows from a SCROLL OFFSET counted in rows
|
||||
* from the bottom. `offset === 0` is `bottom(f, height)`; positive
|
||||
* offset reveals older rows above. Caps `offset` so the result is
|
||||
* always a valid slice within `f`.
|
||||
*/
|
||||
export function viewport(f: Frame, offset: number, height: number): Frame {
|
||||
if (height <= 0) return { width: f.width, rows: [] };
|
||||
const maxOffset = Math.max(0, f.rows.length - height);
|
||||
const o = Math.max(0, Math.min(offset, maxOffset));
|
||||
const start = Math.max(0, f.rows.length - height - o);
|
||||
return slice(f, start, height);
|
||||
}
|
||||
|
||||
// ─── compositing ─────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Paint `top` over `base` at offset (x, y). Cells of `top` outside
|
||||
* `base`'s bounds are silently dropped. The result has the SAME
|
||||
* dimensions as `base` — overlay never grows the frame.
|
||||
*
|
||||
* Used for modals / popovers / ScrollBar that appear on top of the
|
||||
* scroll log. Cleaner than nested flex boxes; explicit positioning.
|
||||
*/
|
||||
export function overlay(base: Frame, top: Frame, x: number, y: number): Frame {
|
||||
const rows: FrameRow[] = base.rows.map((r) => r.slice());
|
||||
for (let i = 0; i < top.rows.length; i++) {
|
||||
const targetRow = rows[y + i] as Cell[] | undefined;
|
||||
if (!targetRow) continue;
|
||||
const src = top.rows[i]!;
|
||||
let col = x;
|
||||
for (const cell of src) {
|
||||
if (col >= 0 && col < base.width) targetRow[col] = cell;
|
||||
col += 1;
|
||||
}
|
||||
}
|
||||
return { width: base.width, rows };
|
||||
}
|
||||
|
||||
/**
|
||||
* Make a frame uniform-width by either truncating each row to
|
||||
* `width` cells or right-padding with spaces. Useful when an
|
||||
* upstream producer built rows at a different width and the caller
|
||||
* needs to constrain to a known viewport.
|
||||
*
|
||||
* Truncation respects 2-wide chars: if the cut would split a
|
||||
* 2-wide grapheme (the head is included but the tail is sliced off),
|
||||
* the head is replaced by a space so we don't render a half-grapheme
|
||||
* (which terminals draw as either a stretched glyph spilling past the
|
||||
* intended column or a question-mark, depending on the font).
|
||||
*/
|
||||
export function fitWidth(f: Frame, width: number): Frame {
|
||||
if (f.width === width) return f;
|
||||
const rows: FrameRow[] = [];
|
||||
for (const r of f.rows) {
|
||||
if (r.length >= width) {
|
||||
const cut = r.slice(0, width) as Cell[];
|
||||
const last = cut[cut.length - 1];
|
||||
if (last && last.width === 2 && !last.tail) {
|
||||
// Cut splits a 2-wide grapheme — head kept, tail dropped.
|
||||
// Replace the orphaned head with a space so the visual width
|
||||
// matches the row count.
|
||||
cut[cut.length - 1] = SPACE;
|
||||
}
|
||||
rows.push(cut);
|
||||
} else {
|
||||
rows.push(padRowRight(r as Cell[], width - r.length));
|
||||
}
|
||||
}
|
||||
return { width, rows };
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
/**
|
||||
* Public surface of the Frame compiler. Phase 1 of the long-term
|
||||
* Ink-replacement migration. Components compile to `Frame` data,
|
||||
* primitives compose them, the paint layer renders to terminal.
|
||||
*/
|
||||
|
||||
export type { Cell, Frame, FrameRow, TextOpts } from "./types.js";
|
||||
export {
|
||||
blank,
|
||||
borderLeft,
|
||||
bottom,
|
||||
empty,
|
||||
fitWidth,
|
||||
hstack,
|
||||
overlay,
|
||||
pad,
|
||||
slice,
|
||||
text,
|
||||
viewport,
|
||||
vstack,
|
||||
} from "./frame.js";
|
||||
export { frameToAnsi, rowText } from "./ansi.js";
|
||||
export { graphemeWidth, graphemes, stringWidth } from "./width.js";
|
||||
@@ -0,0 +1,97 @@
|
||||
/**
|
||||
* Canonical terminal-grid representation. A `Frame` is "what the
|
||||
* terminal will show" as pure data — every cell is addressable, every
|
||||
* row's visual width is known, no flex-engine quirks, no estimates.
|
||||
*
|
||||
* Phase 1 of the Frame-compiler architecture migration. This file
|
||||
* just defines the data shape; behavior lives in `frame.ts`.
|
||||
*
|
||||
* Why a custom type instead of leaning on Ink's tree:
|
||||
* · Ink's overflow=hidden does NOT reliably clip negative-margin
|
||||
* children (verified in 0.13.0; bled into chrome).
|
||||
* · Ink doesn't expose rendered cell positions, so our slicer had
|
||||
* to estimate event heights — wrong estimates → scroll into
|
||||
* emptiness.
|
||||
* · Ink renders the whole tree on every state change; for thousands
|
||||
* of log events, this blocks the event loop > 250ms and breaks
|
||||
* stdin parsing's ESC-ambiguity timer (0.13.2 bogus-Esc abort).
|
||||
*
|
||||
* Frames sidestep all three: layout is a deterministic function on
|
||||
* pure data, the slicer becomes `rows.slice(top, top+h)`, and a
|
||||
* future paint layer (Phase 4) can diff frames cell-by-cell instead
|
||||
* of repainting the whole viewport.
|
||||
*/
|
||||
|
||||
/**
|
||||
* One terminal cell. Most are 1 column wide; CJK / emoji / fullwidth
|
||||
* forms occupy 2 columns. The `width` field is the canonical source
|
||||
* of truth for visual width, used by every layout primitive — never
|
||||
* inferred from the character.
|
||||
*
|
||||
* Style fields mirror Ink's `<Text>` props so migration from Ink
|
||||
* Text → Frame is mechanical. ANSI escape sequences live ONLY in the
|
||||
* paint layer (`ansi.ts`); never inside Frame data.
|
||||
*/
|
||||
export interface Cell {
|
||||
/**
|
||||
* The grapheme rendered at this cell. For 2-wide chars, the cell
|
||||
* with `width: 2` carries the actual char and the immediately-next
|
||||
* cell is a "tail" with `tail: true` and `char: ""` so row arrays
|
||||
* always have `length === Frame.width` (invariant). The tail cell
|
||||
* is skipped during paint but counted in slicing/positioning.
|
||||
*/
|
||||
char: string;
|
||||
/** 1 for ASCII / Latin / most BMP. 2 for CJK / emoji / fullwidth. */
|
||||
width: 1 | 2;
|
||||
/** Sentinel for the second cell of a 2-wide grapheme. */
|
||||
tail?: boolean;
|
||||
/** Foreground color: hex `#rrggbb` or named ANSI ("red", "cyan"). */
|
||||
fg?: string;
|
||||
/** Background color: hex `#rrggbb` or named ANSI. */
|
||||
bg?: string;
|
||||
bold?: boolean;
|
||||
dim?: boolean;
|
||||
italic?: boolean;
|
||||
underline?: boolean;
|
||||
inverse?: boolean;
|
||||
/** OSC-8 hyperlink target (cell renders as a clickable link). */
|
||||
href?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* One terminal row. INVARIANT: `cells.reduce((a, c) => a + (c.tail ? 0 : c.width), 0) === Frame.width`.
|
||||
* Every layout primitive maintains this invariant; tests verify it.
|
||||
*/
|
||||
export type FrameRow = readonly Cell[];
|
||||
|
||||
/**
|
||||
* Immutable terminal grid. `width` is the column count (visual cells);
|
||||
* `rows.length` is the row count. Every row has exactly `width`
|
||||
* worth of cells (counting `tail` cells for 2-wide chars).
|
||||
*
|
||||
* Frames compose via primitives in `frame.ts`. They render to the
|
||||
* terminal via `ansi.ts`. They never mutate after construction.
|
||||
*/
|
||||
export interface Frame {
|
||||
readonly width: number;
|
||||
readonly rows: readonly FrameRow[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Style options for text rendering. Mirrors Ink's `<Text>` props
|
||||
* so call sites read the same. `width` is the wrap column —
|
||||
* graphemes that don't fit start a new row.
|
||||
*/
|
||||
export interface TextOpts {
|
||||
/** Wrap column. Mandatory — text without a wrap budget is a
|
||||
* rendering bug; either pass terminal columns or constrain. */
|
||||
width: number;
|
||||
fg?: string;
|
||||
bg?: string;
|
||||
bold?: boolean;
|
||||
dim?: boolean;
|
||||
italic?: boolean;
|
||||
underline?: boolean;
|
||||
inverse?: boolean;
|
||||
href?: string;
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* Visual cell-width calculations for the Frame compiler.
|
||||
*
|
||||
* Delegates to the `string-width` npm package — same library Ink uses
|
||||
* internally — so app-side measurements match the Unicode East Asian
|
||||
* Width tables `string-width` ships, instead of a hand-rolled subset
|
||||
* that drifts on niche scripts. Grapheme segmentation stays on
|
||||
* `Intl.Segmenter` (built-in, no dep) so ZWJ emoji and combining-mark
|
||||
* sequences count as one cell.
|
||||
*
|
||||
* Why not roll our own: maintaining the wide/zero-width tables
|
||||
* in-tree means every Unicode rev (yearly) leaves us behind, and
|
||||
* any one-cell drift corrupts every Frame layout downstream
|
||||
* (right-edge pills, scrollbar alignment, log row truncation). The
|
||||
* lib bumps a version; we get the new tables for free.
|
||||
*/
|
||||
|
||||
import stringWidthLib from "string-width";
|
||||
|
||||
const segmenter = new Intl.Segmenter("en", { granularity: "grapheme" });
|
||||
|
||||
/**
|
||||
* Split a string into grapheme clusters. A grapheme is what humans
|
||||
* read as "one character" — `é` (1), `👨👩👧` (1 emoji), `한` (1 syllable).
|
||||
* We layout cell-by-cell using graphemes so combining marks stay
|
||||
* attached to their base and ZWJ-emoji don't get torn at wrap
|
||||
* boundaries.
|
||||
*/
|
||||
export function graphemes(s: string): string[] {
|
||||
return Array.from(segmenter.segment(s), (seg) => seg.segment);
|
||||
}
|
||||
|
||||
/**
|
||||
* Visual cell width of one grapheme: 0 (zero-width / combining), 1
|
||||
* (narrow), or 2 (wide). Computed by asking `string-width` and
|
||||
* clamping into the {0,1,2} domain — anything wider than 2 collapses
|
||||
* to 2 (the Frame grid only knows narrow + wide cells).
|
||||
*/
|
||||
export function graphemeWidth(g: string): 0 | 1 | 2 {
|
||||
if (g.length === 0) return 0;
|
||||
const w = stringWidthLib(g);
|
||||
if (w <= 0) return 0;
|
||||
if (w >= 2) return 2;
|
||||
return 1;
|
||||
}
|
||||
|
||||
/** Total visual width of a string. Direct passthrough to `string-width`. */
|
||||
export function stringWidth(s: string): number {
|
||||
return stringWidthLib(s);
|
||||
}
|
||||
+64
-13
@@ -117,6 +117,13 @@ export interface HookOutcome {
|
||||
/** Captured stderr (trimmed). The block / warn message comes from here. */
|
||||
stderr: string;
|
||||
durationMs: number;
|
||||
/**
|
||||
* True when stdout or stderr crossed the per-stream byte cap and was
|
||||
* truncated. The hook still completed; the loop just sees a clipped
|
||||
* view of its output. Surfaced via `formatHookOutcomeMessage` so the
|
||||
* user knows their script wrote more than Reasonix kept.
|
||||
*/
|
||||
truncated?: boolean;
|
||||
}
|
||||
|
||||
/** Aggregate report for `runHooks`. */
|
||||
@@ -246,8 +253,27 @@ export interface HookSpawnResult {
|
||||
timedOut: boolean;
|
||||
/** True iff spawn() itself failed (ENOENT, EACCES, …). */
|
||||
spawnError?: Error;
|
||||
/**
|
||||
* True iff stdout or stderr was capped at the byte limit. The hook
|
||||
* still ran to completion / timeout, but downstream consumers see a
|
||||
* truncated view of its output. Surface this in the UI so a hook
|
||||
* author who relies on long output knows the loop didn't see all
|
||||
* of it.
|
||||
*/
|
||||
truncated?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Per-stream cap on hook output. 256KB matches the shape of what
|
||||
* hooks are actually for — short error messages, validator stderr,
|
||||
* a `git status --short` summary — not full build logs. A buggy or
|
||||
* runaway hook (`cat large.bin`, infinite `yes`) used to accumulate
|
||||
* unbounded into Reasonix's heap until the timeout fired; with the
|
||||
* cap the worst case is 256KB stdout + 256KB stderr per hook
|
||||
* regardless of how chatty the child gets.
|
||||
*/
|
||||
const HOOK_OUTPUT_CAP_BYTES = 256 * 1024;
|
||||
|
||||
export type HookSpawner = (input: HookSpawnInput) => Promise<HookSpawnResult>;
|
||||
|
||||
/**
|
||||
@@ -267,8 +293,14 @@ function defaultSpawner(input: HookSpawnInput): Promise<HookSpawnResult> {
|
||||
shell: true,
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
});
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
// Collect raw bytes per stream and decode once at close so a
|
||||
// multi-byte UTF-8 sequence split across data chunks doesn't
|
||||
// corrupt — same approach shell.ts uses for run_command output.
|
||||
const stdoutChunks: Buffer[] = [];
|
||||
const stderrChunks: Buffer[] = [];
|
||||
let stdoutBytes = 0;
|
||||
let stderrBytes = 0;
|
||||
let truncated = false;
|
||||
let timedOut = false;
|
||||
const timer = setTimeout(() => {
|
||||
timedOut = true;
|
||||
@@ -284,29 +316,46 @@ function defaultSpawner(input: HookSpawnInput): Promise<HookSpawnResult> {
|
||||
}, 500);
|
||||
}, input.timeoutMs);
|
||||
|
||||
child.stdout.on("data", (chunk: Buffer) => {
|
||||
stdout += chunk.toString("utf8");
|
||||
});
|
||||
child.stderr.on("data", (chunk: Buffer) => {
|
||||
stderr += chunk.toString("utf8");
|
||||
});
|
||||
const onChunk = (kind: "stdout" | "stderr", chunk: Buffer) => {
|
||||
const target = kind === "stdout" ? stdoutChunks : stderrChunks;
|
||||
const seen = kind === "stdout" ? stdoutBytes : stderrBytes;
|
||||
if (seen >= HOOK_OUTPUT_CAP_BYTES) {
|
||||
truncated = true;
|
||||
return;
|
||||
}
|
||||
const remaining = HOOK_OUTPUT_CAP_BYTES - seen;
|
||||
if (chunk.length > remaining) {
|
||||
target.push(chunk.subarray(0, remaining));
|
||||
if (kind === "stdout") stdoutBytes = HOOK_OUTPUT_CAP_BYTES;
|
||||
else stderrBytes = HOOK_OUTPUT_CAP_BYTES;
|
||||
truncated = true;
|
||||
} else {
|
||||
target.push(chunk);
|
||||
if (kind === "stdout") stdoutBytes += chunk.length;
|
||||
else stderrBytes += chunk.length;
|
||||
}
|
||||
};
|
||||
child.stdout.on("data", (chunk: Buffer) => onChunk("stdout", chunk));
|
||||
child.stderr.on("data", (chunk: Buffer) => onChunk("stderr", chunk));
|
||||
child.once("error", (err) => {
|
||||
clearTimeout(timer);
|
||||
resolve({
|
||||
exitCode: null,
|
||||
stdout,
|
||||
stderr,
|
||||
stdout: Buffer.concat(stdoutChunks).toString("utf8"),
|
||||
stderr: Buffer.concat(stderrChunks).toString("utf8"),
|
||||
timedOut: false,
|
||||
spawnError: err,
|
||||
truncated: truncated || undefined,
|
||||
});
|
||||
});
|
||||
child.once("close", (code) => {
|
||||
clearTimeout(timer);
|
||||
resolve({
|
||||
exitCode: code,
|
||||
stdout: stdout.trim(),
|
||||
stderr: stderr.trim(),
|
||||
stdout: Buffer.concat(stdoutChunks).toString("utf8").trim(),
|
||||
stderr: Buffer.concat(stderrChunks).toString("utf8").trim(),
|
||||
timedOut,
|
||||
truncated: truncated || undefined,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -334,7 +383,8 @@ export function formatHookOutcomeMessage(outcome: HookOutcome): string {
|
||||
outcome.hook.command.length > 60
|
||||
? `${outcome.hook.command.slice(0, 60)}…`
|
||||
: outcome.hook.command;
|
||||
const head = `hook ${tag} \`${cmd}\` ${outcome.decision}`;
|
||||
const truncTag = outcome.truncated ? " (output truncated at 256KB)" : "";
|
||||
const head = `hook ${tag} \`${cmd}\` ${outcome.decision}${truncTag}`;
|
||||
return detail ? `${head}: ${detail}` : head;
|
||||
}
|
||||
|
||||
@@ -393,6 +443,7 @@ export async function runHooks(opts: RunHooksOptions): Promise<HookReport> {
|
||||
(raw.spawnError ? raw.spawnError.message : "") ||
|
||||
(raw.timedOut ? `hook timed out after ${timeoutMs}ms` : ""),
|
||||
durationMs: Date.now() - start,
|
||||
truncated: raw.truncated,
|
||||
});
|
||||
if (decision === "block") {
|
||||
blocked = true;
|
||||
|
||||
@@ -19,6 +19,7 @@ export {
|
||||
detectAtPicker,
|
||||
expandAtMentions,
|
||||
listFilesSync,
|
||||
listFilesWithStatsAsync,
|
||||
listFilesWithStatsSync,
|
||||
rankPickerCandidates,
|
||||
} from "./at-mentions.js";
|
||||
|
||||
+153
-6
@@ -219,6 +219,24 @@ export interface CacheFirstLoopOptions {
|
||||
* `max` for Reasonix (agent-class use per DeepSeek V4 docs).
|
||||
*/
|
||||
reasoningEffort?: "high" | "max";
|
||||
/**
|
||||
* Master switch for auto-escalation paths. See ReconfigurableOptions
|
||||
* — defaults to `true` (current behavior); the `flash` and `pro`
|
||||
* presets pass `false` to lock the running session to one model.
|
||||
*/
|
||||
autoEscalate?: boolean;
|
||||
/**
|
||||
* Soft USD budget for the entire session. When set, the loop:
|
||||
* - Emits a one-shot warning event when cumulative cost crosses 80%
|
||||
* - Refuses to run the next turn once cumulative cost ≥ budget,
|
||||
* yielding an error that explains how to bump or clear the cap
|
||||
*
|
||||
* Default `undefined` — no cap, no warnings. Reasonix is the cost-
|
||||
* focused agent; the budget is opt-in so users new to the tool
|
||||
* don't get blocked at $0.50 wondering what happened, but heavy /
|
||||
* headless / CI users have a clean circuit breaker available.
|
||||
*/
|
||||
budgetUsd?: number;
|
||||
/**
|
||||
* Session name. When set, the loop pre-loads the session's prior messages
|
||||
* into its log on construction, and appends every new log entry to
|
||||
@@ -264,6 +282,15 @@ export interface ReconfigurableOptions {
|
||||
* mid-session for cheaper, faster turns on simple tasks.
|
||||
*/
|
||||
reasoningEffort?: "high" | "max";
|
||||
/**
|
||||
* Master switch for the auto-escalation paths — both the
|
||||
* `<<<NEEDS_PRO>>>` marker scavenge and the failure-count threshold.
|
||||
* `true` (default) preserves the original "flash baseline, jump to
|
||||
* pro when struggling" behavior. `false` locks the active turn to
|
||||
* whatever `model` is set to — used by the `flash` and `pro` presets
|
||||
* which want a hard model commitment.
|
||||
*/
|
||||
autoEscalate?: boolean;
|
||||
}
|
||||
|
||||
export class CacheFirstLoop {
|
||||
@@ -286,6 +313,26 @@ export class CacheFirstLoop {
|
||||
branchOptions: BranchOptions;
|
||||
/** See ReconfigurableOptions — mutable so `/effort` can flip mid-session. */
|
||||
reasoningEffort: "high" | "max";
|
||||
/**
|
||||
* Auto-escalation toggle. `true` lets the loop self-promote to pro
|
||||
* mid-turn (NEEDS_PRO marker / failure threshold); `false` keeps it
|
||||
* pinned to `model`. Mutable so the dashboard's preset switcher can
|
||||
* flip it live alongside `model`.
|
||||
*/
|
||||
autoEscalate = true;
|
||||
/**
|
||||
* Soft USD budget — see {@link CacheFirstLoopOptions.budgetUsd}.
|
||||
* Mutable so `/budget` slash can set / change / clear it mid-session.
|
||||
* `null` (the default) disables all budget checks.
|
||||
*/
|
||||
budgetUsd: number | null;
|
||||
/**
|
||||
* Set the first time a turn crosses 80% of the budget so the warning
|
||||
* doesn't repeat every turn afterwards. Cleared by `setBudget` (any
|
||||
* change re-arms the warning, including raising the cap above the
|
||||
* current spend).
|
||||
*/
|
||||
private _budgetWarned = false;
|
||||
sessionName: string | null;
|
||||
|
||||
/**
|
||||
@@ -358,6 +405,9 @@ export class CacheFirstLoop {
|
||||
// was ~12× more expensive than most deployments needed.
|
||||
this.model = opts.model ?? "deepseek-v4-flash";
|
||||
this.reasoningEffort = opts.reasoningEffort ?? "max";
|
||||
if (opts.autoEscalate !== undefined) this.autoEscalate = opts.autoEscalate;
|
||||
this.budgetUsd =
|
||||
typeof opts.budgetUsd === "number" && opts.budgetUsd > 0 ? opts.budgetUsd : null;
|
||||
// Iter cap is a safety net, not the primary stop condition. The
|
||||
// primary stop is the token-context guard inside step(): after
|
||||
// every model response we check whether the prompt is already past
|
||||
@@ -397,7 +447,34 @@ export class CacheFirstLoop {
|
||||
this.stream = this.branchEnabled ? false : this._streamPreference;
|
||||
|
||||
const allowedNames = new Set([...this.prefix.toolSpecs.map((s) => s.function.name)]);
|
||||
this.repair = new ToolCallRepair({ allowedToolNames: allowedNames });
|
||||
// Mutation predicate sourced from the ToolRegistry: a tool is
|
||||
// mutating unless it declares `readOnly: true` (or has a per-call
|
||||
// `readOnlyCheck` that returns true on the actual args). The storm
|
||||
// breaker uses this to clear its window after edit/write/shell, so
|
||||
// legitimate read → edit → verify cycles aren't mistaken for storms.
|
||||
const registry = this.tools;
|
||||
const isMutating = (call: ToolCall): boolean => {
|
||||
const name = call.function?.name;
|
||||
if (!name) return false;
|
||||
const def = registry.get(name);
|
||||
if (!def) return false;
|
||||
if (def.readOnlyCheck) {
|
||||
let args: Record<string, unknown> = {};
|
||||
try {
|
||||
args = JSON.parse(call.function?.arguments ?? "{}") ?? {};
|
||||
} catch {
|
||||
// Malformed args → fall through to the static flag below; the
|
||||
// dynamic check would've thrown anyway.
|
||||
}
|
||||
try {
|
||||
if (def.readOnlyCheck(args as never)) return false;
|
||||
} catch {
|
||||
/* ignore — fall through */
|
||||
}
|
||||
}
|
||||
return def.readOnly !== true;
|
||||
};
|
||||
this.repair = new ToolCallRepair({ allowedToolNames: allowedNames, isMutating });
|
||||
|
||||
// Session resume: pre-load prior messages into the log if a session name
|
||||
// is provided. New messages appended to the log are also persisted.
|
||||
@@ -628,6 +705,7 @@ export class CacheFirstLoop {
|
||||
if (opts.model !== undefined) this.model = opts.model;
|
||||
if (opts.stream !== undefined) this._streamPreference = opts.stream;
|
||||
if (opts.reasoningEffort !== undefined) this.reasoningEffort = opts.reasoningEffort;
|
||||
if (opts.autoEscalate !== undefined) this.autoEscalate = opts.autoEscalate;
|
||||
|
||||
if (opts.branch !== undefined) {
|
||||
if (typeof opts.branch === "number") {
|
||||
@@ -656,6 +734,17 @@ export class CacheFirstLoop {
|
||||
this.stream = this.branchEnabled ? false : this._streamPreference;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set / change / clear the soft USD budget. `null` (or any non-
|
||||
* positive number) disables the cap entirely. Re-arms the 80%
|
||||
* warning so a user who bumps the cap mid-session sees a fresh
|
||||
* threshold message at the new boundary.
|
||||
*/
|
||||
setBudget(usd: number | null): void {
|
||||
this.budgetUsd = typeof usd === "number" && usd > 0 ? usd : null;
|
||||
this._budgetWarned = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Arm pro for the next turn (consumed at turn start). Called by
|
||||
* `/pro`. Idempotent — repeated calls stay armed, `disarmPro()`
|
||||
@@ -767,6 +856,7 @@ export class CacheFirstLoop {
|
||||
if (
|
||||
bumped &&
|
||||
!this._escalateThisTurn &&
|
||||
this.autoEscalate &&
|
||||
this._turnFailureCount >= FAILURE_ESCALATION_THRESHOLD
|
||||
) {
|
||||
this._escalateThisTurn = true;
|
||||
@@ -854,6 +944,30 @@ export class CacheFirstLoop {
|
||||
}
|
||||
|
||||
async *step(userInput: string): AsyncGenerator<LoopEvent> {
|
||||
// Budget gate runs FIRST, before any per-turn state mutation, so a
|
||||
// refusal leaves the loop unchanged and the user can correct the
|
||||
// cap and re-issue. Default `null` short-circuits the whole check
|
||||
// so the no-budget path is one comparison, no behavior delta.
|
||||
if (this.budgetUsd !== null) {
|
||||
const spent = this.stats.totalCost;
|
||||
if (spent >= this.budgetUsd) {
|
||||
yield {
|
||||
turn: this._turn,
|
||||
role: "error",
|
||||
content: "",
|
||||
error: `session budget exhausted — spent $${spent.toFixed(4)} ≥ cap $${this.budgetUsd.toFixed(2)}. Bump the cap with /budget <usd>, clear it with /budget off, or end the session.`,
|
||||
};
|
||||
return;
|
||||
}
|
||||
if (!this._budgetWarned && spent >= this.budgetUsd * 0.8) {
|
||||
this._budgetWarned = true;
|
||||
yield {
|
||||
turn: this._turn,
|
||||
role: "warning",
|
||||
content: `▲ budget 80% used — $${spent.toFixed(4)} of $${this.budgetUsd.toFixed(2)}. Next turn or two likely trips the cap.`,
|
||||
};
|
||||
}
|
||||
}
|
||||
this._turn++;
|
||||
this.scratch.reset();
|
||||
// A fresh user turn is a new intent — don't let StormBreaker's
|
||||
@@ -1132,10 +1246,11 @@ export class CacheFirstLoop {
|
||||
const callModel = this.modelForCurrentCall();
|
||||
// Escalation-marker buffer: delay the first few assistant_delta
|
||||
// yields so a "<<<NEEDS_PRO>>>" lead-in never flashes on-screen
|
||||
// before we abort + retry. Only active on flash (pro never
|
||||
// requests its own escalation). Flushed as one delta once we've
|
||||
// seen enough to rule out the marker.
|
||||
const bufferForEscalation = callModel !== ESCALATION_MODEL;
|
||||
// before we abort + retry. Only active on flash AND when the
|
||||
// user hasn't disabled auto-escalation (the `flash` preset
|
||||
// turns this off — model output flows through verbatim, no
|
||||
// marker handling). pro never requests its own escalation.
|
||||
const bufferForEscalation = this.autoEscalate && callModel !== ESCALATION_MODEL;
|
||||
let escalationBuf = "";
|
||||
let escalationBufFlushed = false;
|
||||
for await (const chunk of this.client.stream({
|
||||
@@ -1270,6 +1385,13 @@ export class CacheFirstLoop {
|
||||
if (signal.aborted) {
|
||||
this.autoCompactToolResultsOnTurnEnd();
|
||||
yield { turn: this._turn, role: "done", content: "" };
|
||||
// Reset the controller so the carry-abort check at the top of
|
||||
// the NEXT step() doesn't inherit this turn's aborted state.
|
||||
// Without this, a queued-submit triggered by App.tsx (e.g.
|
||||
// ShellConfirm "run once" → loop.abort() + setQueuedSubmit)
|
||||
// produces a spurious "aborted at iter 0/64" the moment the
|
||||
// synthetic message starts processing, locking the session.
|
||||
this._turnAbort = new AbortController();
|
||||
return;
|
||||
}
|
||||
yield {
|
||||
@@ -1291,6 +1413,7 @@ export class CacheFirstLoop {
|
||||
// no-op content and passed through verbatim, so there's no
|
||||
// infinite-retry loop.
|
||||
if (
|
||||
this.autoEscalate &&
|
||||
this.modelForCurrentCall() !== ESCALATION_MODEL &&
|
||||
this.isEscalationRequest(assistantContent)
|
||||
) {
|
||||
@@ -1524,6 +1647,16 @@ export class CacheFirstLoop {
|
||||
}
|
||||
}
|
||||
|
||||
// When `change_workspace` fires its WorkspaceConfirmationError,
|
||||
// any subsequent calls in the same parallel batch would dispatch
|
||||
// against the OLD sandbox before the user has approved the switch
|
||||
// — a silent data-loss footgun (file lands in the old project).
|
||||
// Once we observe one of these in this batch, every remaining
|
||||
// call gets a synthetic "skipped" result instead of running.
|
||||
// Tool-call ↔ tool pairing stays intact so DeepSeek doesn't 400
|
||||
// on the next turn; the model sees the deferral and the user
|
||||
// gets the modal first.
|
||||
let workspaceSwitchPending = false;
|
||||
for (const call of repairedCalls) {
|
||||
const name = call.function?.name ?? "";
|
||||
const args = call.function?.arguments ?? "{}";
|
||||
@@ -1558,7 +1691,16 @@ export class CacheFirstLoop {
|
||||
for (const w of hookWarnings(preReport.outcomes, this._turn)) yield w;
|
||||
|
||||
let result: string;
|
||||
if (preReport.blocked) {
|
||||
if (workspaceSwitchPending) {
|
||||
// Tool fired in the same parallel batch as a change_workspace
|
||||
// that's awaiting user confirmation. Don't dispatch — the
|
||||
// sandbox root may flip under us. Surface a clear deferral
|
||||
// so the model retries on the next turn (where rootDir is
|
||||
// either the new path or unchanged after a deny).
|
||||
result = JSON.stringify({
|
||||
error: `${name}: deferred because change_workspace in the same batch is awaiting the user's approval. Re-issue this call on your next turn — the sandbox root may have changed.`,
|
||||
});
|
||||
} else if (preReport.blocked) {
|
||||
const blocking = preReport.outcomes[preReport.outcomes.length - 1];
|
||||
const reason = (
|
||||
blocking?.stderr ||
|
||||
@@ -1571,6 +1713,11 @@ export class CacheFirstLoop {
|
||||
signal,
|
||||
maxResultTokens: DEFAULT_MAX_RESULT_TOKENS,
|
||||
});
|
||||
// Detect a workspace-switch confirmation marker in this dispatch
|
||||
// result; flip the gate so the rest of the batch defers.
|
||||
if (name === "change_workspace" && result.includes('"WorkspaceConfirmationError:')) {
|
||||
workspaceSwitchPending = true;
|
||||
}
|
||||
|
||||
// PostToolUse hooks — block is meaningless after the fact, so
|
||||
// every non-pass outcome is a warning. Hooks here are the
|
||||
|
||||
+2
-1
@@ -4,6 +4,7 @@
|
||||
* logic works against a real stdio server or an in-process fake.
|
||||
*/
|
||||
|
||||
import { VERSION } from "../version.js";
|
||||
import type { McpTransport } from "./stdio.js";
|
||||
import {
|
||||
type CallToolParams,
|
||||
@@ -65,7 +66,7 @@ export class McpClient {
|
||||
|
||||
constructor(opts: McpClientOptions) {
|
||||
this.transport = opts.transport;
|
||||
this.clientInfo = opts.clientInfo ?? { name: "reasonix", version: "0.3.0-dev" };
|
||||
this.clientInfo = opts.clientInfo ?? { name: "reasonix", version: VERSION };
|
||||
this.requestTimeoutMs = opts.requestTimeoutMs ?? 60_000;
|
||||
}
|
||||
|
||||
|
||||
+74
-4
@@ -9,27 +9,97 @@ export interface ImmutablePrefixOptions {
|
||||
|
||||
export class ImmutablePrefix {
|
||||
readonly system: string;
|
||||
readonly toolSpecs: readonly ToolSpec[];
|
||||
/**
|
||||
* Backing array for `toolSpecs`. Originally `Object.freeze`d at
|
||||
* construction (hence the class name) — but `addTool` now lets the
|
||||
* dashboard register `semantic_search` after a mid-session
|
||||
* `reasonix index` build without forcing the user to restart. Each
|
||||
* add is documented to cost one cache-miss turn (the cached prefix
|
||||
* on DeepSeek's side is keyed by the full tool list); subsequent
|
||||
* turns re-cache against the new shape.
|
||||
*/
|
||||
private _toolSpecs: ToolSpec[];
|
||||
readonly fewShots: readonly ChatMessage[];
|
||||
/**
|
||||
* Cached SHA-256 of the prefix payload. Computed lazily on first
|
||||
* `fingerprint` access, invalidated only by mutations that go
|
||||
* through `addTool` (the one legitimate post-construction mutation
|
||||
* path). The TUI reads `fingerprint` on every render — without the
|
||||
* cache, that means a fresh `JSON.stringify` + sha256 over the
|
||||
* full prefix (system prompt + tools list + few-shots, typically
|
||||
* 5-10KB) on every keystroke.
|
||||
*
|
||||
* The lazy-init also acts as a cheap drift guard: if some future
|
||||
* code path mutates `_toolSpecs` directly without going through
|
||||
* `addTool`, `fingerprint` will return the stale cached value
|
||||
* while the actual prefix sent to DeepSeek diverges — the cache
|
||||
* miss would be the first symptom. {@link verifyFingerprint}
|
||||
* lets dev / test code assert the cache matches reality.
|
||||
*/
|
||||
private _fingerprintCache: string | null = null;
|
||||
|
||||
constructor(opts: ImmutablePrefixOptions) {
|
||||
this.system = opts.system;
|
||||
this.toolSpecs = Object.freeze([...(opts.toolSpecs ?? [])]);
|
||||
this._toolSpecs = [...(opts.toolSpecs ?? [])];
|
||||
this.fewShots = Object.freeze([...(opts.fewShots ?? [])]);
|
||||
}
|
||||
|
||||
get toolSpecs(): readonly ToolSpec[] {
|
||||
return this._toolSpecs;
|
||||
}
|
||||
|
||||
toMessages(): ChatMessage[] {
|
||||
return [{ role: "system", content: this.system }, ...this.fewShots.map((m) => ({ ...m }))];
|
||||
}
|
||||
|
||||
tools(): ToolSpec[] {
|
||||
return this.toolSpecs.map((t) => structuredClone(t) as ToolSpec);
|
||||
return this._toolSpecs.map((t) => structuredClone(t) as ToolSpec);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a tool spec to the prefix. Returns `true` if added, `false`
|
||||
* if a tool with the same name was already present (callers can
|
||||
* decide whether to ignore or surface the no-op). The model picks
|
||||
* up the new tool on the next turn after the cache busts once.
|
||||
*/
|
||||
addTool(spec: ToolSpec): boolean {
|
||||
const name = spec.function?.name;
|
||||
if (!name) return false;
|
||||
if (this._toolSpecs.some((t) => t.function?.name === name)) return false;
|
||||
this._toolSpecs.push(spec);
|
||||
this._fingerprintCache = null;
|
||||
return true;
|
||||
}
|
||||
|
||||
get fingerprint(): string {
|
||||
if (this._fingerprintCache !== null) return this._fingerprintCache;
|
||||
this._fingerprintCache = this.computeFingerprint();
|
||||
return this._fingerprintCache;
|
||||
}
|
||||
|
||||
/**
|
||||
* Recompute the fingerprint from scratch and assert it matches the
|
||||
* cached value. Returns the freshly-computed hash on success; throws
|
||||
* with a diff if the cache drifted, which always indicates a bug —
|
||||
* either a non-`addTool` mutation path was added, or `addTool`
|
||||
* forgot to invalidate the cache. Dev / test only; the live loop
|
||||
* doesn't call this on the hot path.
|
||||
*/
|
||||
verifyFingerprint(): string {
|
||||
const fresh = this.computeFingerprint();
|
||||
if (this._fingerprintCache !== null && this._fingerprintCache !== fresh) {
|
||||
throw new Error(
|
||||
`ImmutablePrefix fingerprint drift: cached=${this._fingerprintCache}, fresh=${fresh}. A mutation path bypassed addTool's cache invalidation — DeepSeek will see prefix churn that the TUI / transcript log don't know about.`,
|
||||
);
|
||||
}
|
||||
this._fingerprintCache = fresh;
|
||||
return fresh;
|
||||
}
|
||||
|
||||
private computeFingerprint(): string {
|
||||
const blob = JSON.stringify({
|
||||
system: this.system,
|
||||
tools: this.toolSpecs,
|
||||
tools: this._toolSpecs,
|
||||
shots: this.fewShots,
|
||||
});
|
||||
return createHash("sha256").update(blob).digest("hex").slice(0, 16);
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
/** Port: workspace file snapshots. Async-shaped for remote backends. */
|
||||
|
||||
import type {
|
||||
CheckpointMeta,
|
||||
CreateCheckpointOptions,
|
||||
RestoreResult,
|
||||
} from "../code/checkpoints.js";
|
||||
|
||||
export interface CheckpointStore {
|
||||
create(opts: CreateCheckpointOptions): Promise<CheckpointMeta>;
|
||||
restore(rootDir: string, id: string): Promise<RestoreResult>;
|
||||
list(rootDir: string): ReadonlyArray<CheckpointMeta>;
|
||||
remove(rootDir: string, id: string): Promise<boolean>;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
/** Port: append-only persistence of the kernel event log. */
|
||||
|
||||
import type { Event } from "../core/events.js";
|
||||
|
||||
export interface EventSink {
|
||||
append(ev: Event): void;
|
||||
flush(): Promise<void>;
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
export interface EventSource {
|
||||
read(sessionName: string): AsyncIterable<Event>;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
/** Port: hook dispatch (PreToolUse / PostToolUse / UserPromptSubmit / Stop). */
|
||||
|
||||
import type { HookEvent, HookOutcome, HookPayload, ResolvedHook } from "../hooks.js";
|
||||
|
||||
export interface HookRunner {
|
||||
fire(
|
||||
event: HookEvent,
|
||||
payload: HookPayload,
|
||||
hooks: ReadonlyArray<ResolvedHook>,
|
||||
signal?: AbortSignal,
|
||||
): Promise<ReadonlyArray<HookOutcome>>;
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
/** Port: memory pyramid. Today wraps user-memory + project-memory + hash-memory. */
|
||||
|
||||
import type { MemoryEntry, MemoryScope, MemoryType } from "../user-memory.js";
|
||||
|
||||
export interface MemoryWriteInput {
|
||||
name: string;
|
||||
type: MemoryType;
|
||||
scope: MemoryScope;
|
||||
description: string;
|
||||
body: string;
|
||||
}
|
||||
|
||||
export interface MemoryStore {
|
||||
query(scope: MemoryScope, name: string): Promise<MemoryEntry | null>;
|
||||
list(scope: MemoryScope): Promise<ReadonlyArray<MemoryEntry>>;
|
||||
write(input: MemoryWriteInput): Promise<void>;
|
||||
remove(scope: MemoryScope, name: string): Promise<boolean>;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
/** Port: streaming chat model. Adapters: DeepSeek today; pluggable later. */
|
||||
|
||||
import type { ChatRequestOptions, RawUsage } from "../types.js";
|
||||
|
||||
export interface ModelStreamChunk {
|
||||
contentDelta?: string;
|
||||
reasoningDelta?: string;
|
||||
toolCallDelta?: {
|
||||
index: number;
|
||||
id?: string;
|
||||
name?: string;
|
||||
argumentsDelta?: string;
|
||||
};
|
||||
usage?: RawUsage;
|
||||
finishReason?: string;
|
||||
}
|
||||
|
||||
export interface ModelClient {
|
||||
chatStream(opts: ChatRequestOptions, signal?: AbortSignal): AsyncIterable<ModelStreamChunk>;
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
/** Port: capability dispatch. Tools / MCP / skills all flow through here. */
|
||||
|
||||
export interface CapabilityDescriptor {
|
||||
name: string;
|
||||
description?: string;
|
||||
readOnly: boolean;
|
||||
permission: "ask" | "allow" | "deny";
|
||||
}
|
||||
|
||||
export interface ToolDispatchIntent {
|
||||
callId: string;
|
||||
name: string;
|
||||
/** JSON string exactly as the model emitted it. */
|
||||
args: string;
|
||||
}
|
||||
|
||||
export type ToolDispatchOutcome =
|
||||
| {
|
||||
kind: "result";
|
||||
callId: string;
|
||||
ok: boolean;
|
||||
output: string;
|
||||
truncated?: boolean;
|
||||
durationMs: number;
|
||||
}
|
||||
| {
|
||||
kind: "denied";
|
||||
callId: string;
|
||||
reason: "permission" | "budget" | "policy" | "hook";
|
||||
};
|
||||
|
||||
export interface ToolHost {
|
||||
list(): ReadonlyArray<CapabilityDescriptor>;
|
||||
dispatch(intent: ToolDispatchIntent, signal?: AbortSignal): Promise<ToolDispatchOutcome>;
|
||||
}
|
||||
+10
-2
@@ -12,7 +12,7 @@
|
||||
|
||||
import type { ToolCall } from "../types.js";
|
||||
import { scavengeToolCalls } from "./scavenge.js";
|
||||
import { StormBreaker } from "./storm.js";
|
||||
import { type IsMutating, StormBreaker } from "./storm.js";
|
||||
import { repairTruncatedJson } from "./truncation.js";
|
||||
|
||||
export { analyzeSchema, flattenSchema, nestArguments } from "./flatten.js";
|
||||
@@ -35,6 +35,14 @@ export interface ToolCallRepairOptions {
|
||||
stormWindow?: number;
|
||||
stormThreshold?: number;
|
||||
maxScavenge?: number;
|
||||
/**
|
||||
* Optional predicate the storm breaker consults to identify state-
|
||||
* changing calls — those clear the sliding window so a post-edit
|
||||
* verify-read isn't mistaken for a repeat. Production callers wire
|
||||
* this off the ToolRegistry's `readOnly` / `readOnlyCheck` flags;
|
||||
* tests that don't supply it keep the original behavior.
|
||||
*/
|
||||
isMutating?: IsMutating;
|
||||
}
|
||||
|
||||
export class ToolCallRepair {
|
||||
@@ -43,7 +51,7 @@ export class ToolCallRepair {
|
||||
|
||||
constructor(opts: ToolCallRepairOptions) {
|
||||
this.opts = opts;
|
||||
this.storm = new StormBreaker(opts.stormWindow ?? 6, opts.stormThreshold ?? 3);
|
||||
this.storm = new StormBreaker(opts.stormWindow ?? 6, opts.stormThreshold ?? 3, opts.isMutating);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+50
-16
@@ -1,36 +1,76 @@
|
||||
import type { ToolCall } from "../types.js";
|
||||
|
||||
/**
|
||||
* Predicate the breaker consults to decide whether a call mutates state.
|
||||
* Mutating calls clear the recent-args buffer: re-reading a file after
|
||||
* `edit_file` shouldn't count as "saw the same args before" — the file
|
||||
* legitimately changed. Wire this from the caller using whatever source
|
||||
* of truth is appropriate (e.g. the ToolRegistry's `readOnly` /
|
||||
* `readOnlyCheck` flags). When undefined, every call is tracked the
|
||||
* old way — preserves the original behavior for callers that don't
|
||||
* thread a registry through.
|
||||
*/
|
||||
export type IsMutating = (call: ToolCall) => boolean;
|
||||
|
||||
interface RecentEntry {
|
||||
name: string;
|
||||
args: string;
|
||||
readOnly: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Call-storm breaker.
|
||||
*
|
||||
* Detects (tool, args) tuples repeating within a sliding window and suppresses
|
||||
* the offending call. Surfaces a synthetic tool_result advising the model to
|
||||
* change strategy on its next turn.
|
||||
*
|
||||
* Buffer entries are tagged read-only vs mutating. When a mutating call
|
||||
* runs, the breaker drops prior read-only entries — a re-read of the
|
||||
* same path after `edit_file` is fresh, not a repeat. Mutating calls
|
||||
* still count among themselves, so a model looping on identical
|
||||
* `edit_file` invocations still trips on the threshold.
|
||||
*
|
||||
* Without an `isMutating` predicate everything is tracked the same way
|
||||
* (back-compat for callers that don't thread a registry through).
|
||||
*/
|
||||
export class StormBreaker {
|
||||
private readonly windowSize: number;
|
||||
private readonly threshold: number;
|
||||
private readonly recent: Array<readonly [string, string]> = [];
|
||||
private readonly isMutating: IsMutating | undefined;
|
||||
private readonly recent: RecentEntry[] = [];
|
||||
|
||||
constructor(windowSize = 6, threshold = 3) {
|
||||
constructor(windowSize = 6, threshold = 3, isMutating?: IsMutating) {
|
||||
this.windowSize = windowSize;
|
||||
this.threshold = threshold;
|
||||
this.isMutating = isMutating;
|
||||
}
|
||||
|
||||
inspect(call: ToolCall): { suppress: boolean; reason?: string } {
|
||||
const sig = signature(call);
|
||||
if (!sig) return { suppress: false };
|
||||
const count = this.recent.reduce(
|
||||
(n, [name, args]) => (name === sig[0] && args === sig[1] ? n + 1 : n),
|
||||
0,
|
||||
);
|
||||
const name = call.function?.name;
|
||||
if (!name) return { suppress: false };
|
||||
const args = call.function?.arguments ?? "";
|
||||
const mutating = this.isMutating ? this.isMutating(call) : false;
|
||||
const readOnly = !mutating;
|
||||
|
||||
if (mutating) {
|
||||
// Drop prior read-only entries — the file/shell state just
|
||||
// changed, so a verify-read after this should start with a
|
||||
// clean slate. Keep mutator entries: 3 identical edits in a row
|
||||
// is still a storm (model in a loop).
|
||||
for (let i = this.recent.length - 1; i >= 0; i--) {
|
||||
if (this.recent[i]!.readOnly) this.recent.splice(i, 1);
|
||||
}
|
||||
}
|
||||
|
||||
const count = this.recent.reduce((n, e) => (e.name === name && e.args === args ? n + 1 : n), 0);
|
||||
if (count >= this.threshold - 1) {
|
||||
return {
|
||||
suppress: true,
|
||||
reason: `call-storm suppressed: ${sig[0]} called with identical args ${count + 1} times within window=${this.windowSize}`,
|
||||
reason: `call-storm suppressed: ${name} called with identical args ${count + 1} times within window=${this.windowSize}`,
|
||||
};
|
||||
}
|
||||
this.recent.push(sig);
|
||||
this.recent.push({ name, args, readOnly });
|
||||
while (this.recent.length > this.windowSize) this.recent.shift();
|
||||
return { suppress: false };
|
||||
}
|
||||
@@ -39,9 +79,3 @@ export class StormBreaker {
|
||||
this.recent.length = 0;
|
||||
}
|
||||
}
|
||||
|
||||
function signature(call: ToolCall): readonly [string, string] | null {
|
||||
const name = call.function?.name;
|
||||
if (!name) return null;
|
||||
return [name, call.function?.arguments ?? ""] as const;
|
||||
}
|
||||
Loaded 100 of 145 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user