Compare commits

...
61 Commits
Author SHA1 Message Date
esengine f82f93559b chore(release): 0.6.0
Cost control promoted to Pillar 4. Breaking behavior: default model
flipped from v4-pro to v4-flash; smart (default) preset no longer
auto-enables harvest; max preset no longer auto-enables branch 3.
New: /pro one-shot arming, failure-triggered auto-escalate, model
self-report <<<NEEDS_PRO>>>, turn-end auto-compaction, per-turn cost
badges. UI refactor: App.tsx -33%, slash.ts split into slash/ with
13 focused modules. See CHANGELOG for the full matrix.
2026-04-24 07:26:40 -07:00
esengine 5a7d16c24f fix(ui,prompt): dedupe edit_file result display; teach run_command its shell limits upfront
Two small papercuts from a 70-turn live run surfaced:

1. Every edit_file tool call showed the apply result TWICE — once
   as a dim info row (pushed by applyNow in the edit-mode
   interceptor), then again as a full `▣ edit_file → …` tool row
   yielded by the loop. Both with identical text. Wasted rows, made
   long sessions harder to skim.

   Fix: drop the info-row push inside applyNow. The returned string
   still becomes the tool result AND the model sees it via the tool
   event; the user sees it once via the tool row with its
   identifying header. The auto-text branch at turn-end (for
   text-form SEARCH/REPLACE blocks parsed from assistant prose)
   still pushes its own info row — there's no tool event to back
   it up.

2. The model repeatedly tried `cd dir && cmd`, `cmd1 | cmd2`,
   `cmd 2>&1`, learning only from the error reply. run_command's
   top-level description didn't spell the constraints upfront.

   Fix: front-load a "Constraints (read these before the first
   call):" block in both run_command and run_background
   descriptions. Explicit list of rejected operators, cd-doesn't-
   persist, and concrete alternatives (`npm --prefix`, `cargo -C`,
   `git -C`, `pytest tests/…` instead of `cd && …`). Also warns
   against unbounded-output commands like `netstat -ano` /
   `find /` that balloon context for no reason, with filtered
   alternatives.

Both are tool/UI changes only; 1054 tests green, typecheck + biome
clean.
2026-04-24 07:12:14 -07:00
esengine 292e51f0c2 fix(plan): render full plan body in scrollback, shrink PlanConfirm to picker only
User bug: "submit_plan" proposals were being truncated inside the
PlanConfirm modal with "(25 more lines truncated — resize the terminal
to see more)". The whole point of a plan review gate is that the user
can read the full thing before approving; the old design cut it off
at roughly 11 source lines to keep the picker on-screen.

Root cause: PlanConfirm rendered both the plan body (via Markdown)
AND the 3-option picker inside one Ink modal, with a hard line clamp
so total height never exceeded the TTY. The clamp fired unavoidably
on any non-trivial plan.

Fix: push the plan body to Static scrollback as a new display role
"plan" the moment submit_plan fires. The Static component renders
once into the terminal's permanent buffer (users can scroll back
through the terminal itself), and the PlanConfirm modal below
shrinks to a tight picker header + choice list. No truncation ever.

Changes:
- EventLog.tsx: new DisplayRole "plan" renders the plan body through
  the full Markdown pipeline inside a cyan-bordered box with a 📋
  header. Goes into <Static> so it's render-once + scrollable.
- App.tsx: on submit_plan detection, setHistorical pushes a "plan"
  row BEFORE setPendingPlan so the body is in scrollback by the
  time the modal mounts.
- PlanConfirm.tsx: dropped the embedded Markdown render, the line-
  clamp helper (clampBodyByLines), maxRenderedChars / terminalRows
  props, and the two constants that drove them. The modal is now
  just a header + open-questions hint + SingleSelect.
- tests/plan-confirm.test.ts deleted — its 5 tests were all for
  the removed clampBodyByLines helper.

Everything else (approve/refine/cancel semantics, staged-input
handoff, hasOpenQuestions hint toggle) unchanged. 1054 tests green.
2026-04-24 07:05:40 -07:00
esengine c5b0906576 fix(skill): run_skill accepts decorated names; index uses trailing [🧬 subagent] tag
Users hit \`run_skill({"name":"🧬 explore"}) → {"error":"unknown skill: \"🧬 explore\""}\`.
The Skills index wrote entries like \`- 🧬 explore — …\`, with the marker
LEADING the name. Models copied the whole thing verbatim into the
\`name\` argument and the lookup failed (VALID_SKILL_NAME regex rejects
emoji + spaces).

Two fixes, defense in depth:

1. Prompt format (primary fix). Rewrite skillIndexLine so the
   subagent marker trails the name, bracketed and labeled:
     old: \`- 🧬 explore — …\`
     new: \`- explore [🧬 subagent] — …\`
   Name comes first, unambiguous. The index intro + tool descriptions
   + CODE_SYSTEM_PROMPT all explicitly spell out "the \`name\` is ONLY
   the identifier before the tag."

2. run_skill normalization (belt-and-suspenders). If the model still
   passes a decorated name, strip \`[...]\` bracketed tags and pick
   the first whitespace-delimited token that starts with a word
   character. Handles every shape observed in the wild:
     "🧬 explore", "[🧬 subagent] explore", "[🧬] explore",
     "explore [🧬 subagent]", "  explore  "  → all resolve to "explore"

Tests:
- tests/skills.test.ts: updated to expect the trailing-tag format,
  explicit regression assertion against the old \`- 🧬 name\` pattern.
- tests/tools-skills.test.ts: new "normalizes decorated names" case
  exercising each decoration shape through run_skill dispatch.

All 1059 tests green.
2026-04-24 06:55:07 -07:00
esengine 30ca814809 feat(cost): model self-report escalation — flash emits <<<NEEDS_PRO>>>, loop retries on pro
Reactive-only escalation (wait for flash to rack up 3+ errors before
bumping to pro) burns tokens and time on tasks flash itself could
recognize as too hard upfront. Add a prompt-level contract: on flash,
the model can output `<<<NEEDS_PRO>>>` as the FIRST line of its
response to abort the current call and retry this turn on v4-pro,
one shot. Pro never self-escalates (the check short-circuits when
modelForCurrentCall === ESCALATION_MODEL).

This matters because non-expert users can't reliably predict which
tasks need the frontier tier. Letting the model self-assess catches
hard tasks upfront — design tradeoffs, architecture refactors, subtle
invariants — without auto-upgrading every prompt (which would destroy
the cost savings from flash-first defaults).

Implementation:
- loop.ts: NEEDS_PRO_MARKER constant, isEscalationRequest() helper,
  post-call retry check that sets _escalateThisTurn and re-enters
  the iter with `iter--; continue` on match. Streaming path buffers
  the first 80 chars / first line before yielding assistant_delta
  events so the marker never flickers on-screen before retry fires.
  Guarded against infinite retries by checking modelForCurrentCall
  against ESCALATION_MODEL — users who already chose /preset max
  see the marker as normal content.

- prompt-fragments.ts: new ESCALATION_CONTRACT fragment spells out
  when to use the marker (cross-file refactors, subtle correctness
  invariants, design tradeoffs) and when NOT to (small edits, clear
  bug fixes). Embedded into CODE_SYSTEM_PROMPT, DEFAULT_SYSTEM, and
  DEFAULT_SUBAGENT_SYSTEM — subagents default to flash+high too,
  so they benefit from the same escape hatch.

Tests (3 new in loop.test.ts):
- flash emits marker → retry on pro, final content is pro's response
- marker mid-text (not lead-in) → no retry
- pro emits marker → no infinite-retry loop

All 1058 tests green.
2026-04-24 06:47:31 -07:00
esengine 000e7c3ac0 docs(architecture): rewrite for v0.6 — four pillars, flash-first, new module layout
The previous ARCHITECTURE.md stopped at v0.3 (MCP + session persistence)
and read three-pillar (cache loop, harvest, tool-call repair) with a
roadmap that predates everything from v0.4 onward. After six months
of cost and refactor work the codebase is fundamentally different:
file layout reorganized, defaults flipped flash-first, branch + harvest
removed from every preset, /pro arming and failure-triggered
auto-escalation added.

New sections:
- Pillar 4 — Cost Control as a first-class subsystem: tiered defaults,
  turn-end auto-compaction, /pro one-shot arming, failure-signal
  auto-escalation, cost transparency thresholds.
- Module layout refreshed — reflects the slash/ + handlers/ split,
  the six hooks under cli/ui/, prompt-fragments.ts, and actual LOC
  counts (App.tsx 2931 → 1984).
- Design evolution replaces the stale roadmap — covers v0.0 through
  v0.6 with a line each so readers orient without reading six months
  of CHANGELOG.
- Non-goals updated to call out "automatic cost escalation without
  user-visible announcement" as explicitly rejected.

Pillar 2 (harvest) and Pillar 3 (tool-call repair) content kept intact
and marked as before. Pillar 1 unchanged.

Pure docs change — no code touched.
2026-04-24 06:32:00 -07:00
esengine a22355a2ab feat(cost): per-turn cost badge in StatsPanel + pro armed/escalated pills
Cost transparency is the last piece of the cost-control design —
users can now see at a glance how much the current turn cost and
which model it ran on, without opening /stats.

StatsPanel header picks up two new pills:
- ⇧ pro armed (yellow) — /pro queued, next turn will run on v4-pro
- ⇧ pro escalated (red) — current turn is on v4-pro (either /pro
  armed was consumed at turn start, or the failure threshold
  tripped mid-turn auto-escalation)

The cost cell now splits into two readings:
- turn $0.0042 — last turn's cost, colored by threshold
  (green <$0.05, yellow $0.05-0.20, red ≥$0.20)
- session $0.1234 — cumulative, same color scale 10× up
  (green <$0.50, yellow $0.50-5, red ≥$5)

No hard circuit-breaker that blocks turns — a mid-session pop-up
gate would be annoying. The colored thresholds are the signal;
users who notice yellow/red can /preset fast or /compact before
shipping the next message.

Plumbing:
- telemetry.ts: SessionSummary.lastTurnCostUsd added. Populated by
  SessionStats.summary() from the most recent TurnStats.cost.
- replay.ts + ReplayApp.tsx: summary-shape call sites updated.
- StatsPanel.tsx: proArmed/escalated props; CostCell refactor;
  turnCostColor/sessionCostColor threshold helpers.
- slash types: armPro / disarmPro ctx callbacks so the /pro handler
  can update App's mirror state synchronously.
- App.tsx: proArmed + turnOnPro state mirrors, turn-start/end
  transitions, warning-event sniff for "⇧" prefix flips turnOnPro.

Tests: 1055 green, typecheck + biome clean.
2026-04-24 06:27:23 -07:00
esengine 39a4e137dc feat(cost): /pro single-turn arming + auto-escalate on repeated flash failures
Two cost-aware escalation paths join the loop, keeping flash-first
as the default but letting the system (or the user) bump to v4-pro
when flash is visibly struggling — without requiring a persistent
preset switch.

1. `/pro` slash command arms pro for the NEXT turn only. Consumed
   at turn start, auto-disarms after the turn ends. Use case: the
   user knows the upcoming ask is hard and wants one-shot strength
   without typing /preset max + remembering to revert. Separate from
   /preset max (persistent, changes this.model) — armed state is
   strictly single-turn.

2. Auto-escalation on failure. The loop tracks visible "flash is
   struggling" signals per turn:
     - edit_file / write_file SEARCH-not-found errors
     - ToolCallRepair fires: scavenge, truncation-fix, storm-break
   Once the count hits FAILURE_ESCALATION_THRESHOLD (3) in one
   turn, the remainder of that turn's model calls upgrade to
   v4-pro. Announced via a yellow warning row — no silent cost
   surprises. Counter + escalation flag reset at every turn start.

Wiring:
- loop.ts: `_proArmedForNextTurn`, `_escalateThisTurn`,
  `_turnFailureCount` private state. Public `armProForNextTurn`,
  `disarmPro`, `proArmed`, `escalatedThisTurn` getters for UI.
  `modelForCurrentCall()` returns the effective model (escalated
  or this.model). `noteToolFailureSignal()` centralizes the
  increment+threshold logic.
- All three chat call sites (branch path, streaming, non-streaming)
  use `modelForCurrentCall()` instead of `this.model` directly.
- stats.record uses the actual model for cost attribution.
- Library-mode default model: v4-pro → v4-flash (aligned with CLI).
- slash/handlers/model.ts: new `pro` handler with /pro, /pro off.
- slash/commands.ts: /pro registered in SLASH_COMMANDS + /help text.

Tests: 1055 green, typecheck + biome clean.
2026-04-24 05:51:24 -07:00
esengine 0383255de2 feat(cost): auto-compact tool results at turn end + lower proactive threshold
Context bloat was the real cost driver, not model tier. A single
read_file returning 12K tokens rides every subsequent turn's prompt
at the cache-hit rate; 10 reads accumulate to 100K+ carry-cost
that each turn pays until the 60% reactive threshold kicks in.
By then the user has already paid for 20-40 turns of inflated
context.

Two changes shift us from reactive to preventive:

1. autoCompactToolResultsOnTurnEnd — fires at every `done` event
   (normal completion, abort, forced summary). Shrinks every tool
   result in the log over 3000 tokens to a tight cap. The model
   can re-read the file if it needs fresh detail — one extra
   read_file call is far cheaper than dragging 12KB through every
   future turn.

2. Proactive in-turn threshold lowered from 60% → 40%. The turn-end
   compact already handles the common case; this threshold now
   only catches multi-iter turns where one tool returned a huge
   payload mid-turn, before the turn ends. 40% triggers earlier
   without waiting for context to get tight.

Net impact on long sessions: per-turn prompt tokens stop compounding.
Expected monthly cost reduction for active users: ~3-5× on long
projects where tool results accumulate.

Constants:
- TURN_END_RESULT_CAP_TOKENS = 3000 (new)
- ARGS_COMPACT_THRESHOLD_TOKENS = 800 (unchanged; per-response args shrink)

Tests: 1055 green, typecheck + biome clean.
2026-04-24 05:22:32 -07:00
esengine b2a50d50f5 feat(cost): cheap defaults everywhere — flash-first, pro opt-in, no auto-branch/harvest
Overhauls the cost model so `reasonix code` doesn't burn pro-tier
tokens by default. Three principles:

1. The default turn runs on v4-flash, not v4-pro. Pro is a ~12× tier
   and shouldn't be implicit. Users escalate with /preset max.
2. Branch and harvest are NEVER auto-enabled by any preset. Both
   multiply per-turn cost (N× and +1 flash call respectively); both
   now require explicit /branch N or /harvest on.
3. Non-user-facing model calls (forced summary on budget exhaustion,
   subagent runs, truncation repair) route through flash+high
   regardless of the user's main-turn tier. No reason to pay pro
   rates for a wrap-up paragraph or an explore subagent's grep chain.

Preset redefinition (branch=1, harvest=false for all three):
  fast   v4-flash + effort=high   cheapest · 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

Default preset is now `smart` (was `fast`) — flash+max is the best
price-per-quality point for coding work. `fast` is the "I just want
a quick answer" escape hatch.

Specific changes:
- cli/ui/presets.ts — new PresetSettings shape adds `reasoningEffort`;
  PRESETS values rewritten; PRESET_DESCRIPTIONS reflect cost story;
  `resolvePreset` default is now "smart".
- cli/resolve.ts — ResolvedDefaults gains `reasoningEffort`; default
  preset is "smart".
- cli/commands/code.tsx — default model v4-pro → v4-flash.
- tools/subagent.ts — DEFAULT_SUBAGENT_MODEL v4-pro → v4-flash;
  DEFAULT_SUBAGENT_EFFORT = "high" (down from parent's "max").
  Skill frontmatter `model:` / `effort:` remain the escape hatches.
- loop.ts — forceSummaryAfterIterLimit hard-codes flash+high for the
  wrap-up call; stats.record attributes the actual summaryModel so
  /stats reflects reality.
- slash handlers — /preset rewritten (persists effort now); /harvest
  and /branch print cost-warning suffixes; /help + /keys text updated
  to match new presets and warn harvest/branch are opt-in only.
- CLI --help strings for `reasonix chat` / `reasonix code` / `--preset`
  / `--harvest` / `--branch` updated.

Tests:
- resolve.test.ts: expectations updated to new defaults (flash+max,
  no branch in max preset).
- slash.test.ts: preset test expectations updated to new combos.
- subagent.test.ts: default-model fallback expectation updated.
All 1055 tests green; typecheck + biome clean.
2026-04-24 04:59:15 -07:00
esengine e486a8e23a refactor(prompt): share TUI formatting + negative-claim rules across prompts
The TUI formatting rules (GFM tables, no Unicode box-drawing, no
decorative ┌──┐ frames, flow charts as bullet lists) were
maintained as three near-identical copies across
DEFAULT_SUBAGENT_SYSTEM, BUILTIN_EXPLORE_BODY, and
BUILTIN_RESEARCH_BODY — and missing entirely from
CODE_SYSTEM_PROMPT, even though the main code reply goes through
the same markdown renderer.

Subagents also lacked the "negative claims are the #1
hallucination shape" guardrail that the main code prompt has.
When an explore/research subagent confidently reported "X is
missing", the parent swallowed it at face value.

Changes:
- New src/prompt-fragments.ts holds TUI_FORMATTING_RULES and
  NEGATIVE_CLAIM_RULE as shared constants — single source of
  truth, embedded literally so prefix-cache hashing stays stable.
- DEFAULT_SUBAGENT_SYSTEM, BUILTIN_EXPLORE_BODY, and
  BUILTIN_RESEARCH_BODY import and interpolate both fragments
  instead of open-coding their own copies.
- CODE_SYSTEM_PROMPT imports TUI_FORMATTING_RULES and appends it
  after the Style section.
- CODE_SYSTEM_PROMPT's intro tool list now names every
  filesystem tool (read_file, write_file, edit_file,
  list_directory, directory_tree, search_files, search_content,
  get_file_info) instead of trailing off at "etc." before the
  essential search_content / edit_file were listed.

Behavior change is small and aligned: fewer hallucinated absences
from subagents, fewer Unicode-box-drawing tables to patch around
in markdown.tsx. Typecheck + biome + 1055 tests green.
2026-04-24 04:38:56 -07:00
esengine a4c1e9b478 refactor(ui): split slash.ts into per-topic handler modules
slash.ts had 1786 lines: types + SLASH_COMMANDS spec + parse
helpers + a ~800-line handleSlash switch + five private feature
handlers + utility helpers. Adding a command meant editing a
monolith; tests had to load the whole thing just to call one
handler. Layout:

    slash.ts                   20-line barrel (re-exports only)
    slash/types.ts             SlashResult / SlashContext / ...
    slash/commands.ts          SLASH_COMMANDS + parse functions
    slash/helpers.ts           git/memory/token/MCP utilities
    slash/dispatch.ts          SlashHandler type + registry +
                               handleSlash lookup
    slash/handlers/
      basic.ts     exit/clear/new/keys/help/setup/retry
      mcp.ts       mcp
      memory.ts    memory family
      skill.ts     skill/skills
      admin.ts     hooks/update/stats
      observability.ts   think/tool/context/status/compact
      edits.ts     undo/history/show/apply/discard/plan/mode/commit
      jobs.ts      jobs/kill/logs
      sessions.ts  sessions/forget
      model.ts     model/models/harvest/preset/branch/effort

Each handler is a plain (args, loop, ctx) => SlashResult function;
aliases (exit/quit, new/reset, skill/skills, apply-plan/applyplan,
hook/hooks, think/reasoning, help/?) are just duplicate keys in
the per-module handlers bag. The public import surface is
preserved via the barrel so App.tsx, tests, and sibling
components keep their existing imports.

Result: slash.ts 1786 -> 20 lines, fanned out into 13 focused
files each under 265 lines. Typecheck + biome + 1055 tests green.
2026-04-24 04:28:52 -07:00
esengine 9fdbdf738b refactor(ui): extract hooks + live components from App.tsx
App.tsx had grown to 2931 lines: streaming state, edit history,
pending-edits, shell/plan/edit confirm, @-picker, slash pickers,
subagent sink, hooks live-reload and cursor tracking all in one
function body. Split the cohesive clusters into dedicated modules
with no behavior change:

- LiveRows.tsx      StatusRow / ModeStatusBar / UndoBanner /
                    SubagentRow / OngoingToolRow + summarizeToolArgs
- edit-history.ts   EditHistoryEntry type + isEntryFullyUndone /
                    entryStatus / format{EditResults,PendingPreview,
                    UndoRows} / describeRepair
- useEditHistory    session-scoped /undo /history /show machinery
- useCompletionPickers  slash-name, @-mention, slash-arg pickers
- useSessionInfo    mount-time fetch of balance / models /
                    latestVersion + refresh callbacks
- useSubagent       subagent sink ref + live activity row

Also drops two dead helpers (formatQueuedEditPreview,
formatUndoResults) that had no callers.

Result: App.tsx 2931 -> 1984 lines (-32%). Typecheck + biome +
1055 tests green.
2026-04-24 04:28:33 -07:00
esengine f3f844b3dc fix(lint): pass biome check for 0.5.24 (format + unused template + exhaustive deps + comma/assign)
- biome format pass on EditConfirm / edit-blocks / jobs / shell /
  filesystem / compact-tokens / App / slash (auto-fixes)
- drop backtick template on a plain-string literal ("failed",
  "(already reverted — …)")
- annotate interceptor useEffect with a useExhaustiveDependencies
  ignore — the closure captures are intentional; adding the refs as
  deps would tear down the interceptor on every mode flip
- add codeHistory / codeShowEdit to handleSubmit deps
- expand comma-operator tricks in tests/tools.test.ts into
  explicit statements (biome rejects `(x = 1, "y")` and comma
  operator under lint/style/noCommaOperator + noAssignInExpressions)

prepublishOnly (lint + typecheck + test + build) now passes clean.
1055 tests, dist built.
2026-04-24 02:23:37 -07:00
esengine d65ca4f67f feat(code): review/auto edit gate, background jobs, context hygiene (0.5.24)
- EditConfirm modal for per-edit review (scrollable diff); Shift+Tab
  cycles review/auto; 5s undo banner + `u` keybind; session edit
  history with /history, /show [id] [path], /undo [id] [path]
- run_background / job_output / stop_job / list_jobs tools with
  ready-signal detection; /jobs, /kill, /logs; tree-kill (Windows
  taskkill /T /F, POSIX process.kill(-pid)) so dev servers actually
  stop; cleanup on SIGINT / SIGTERM / exit
- Bottom mode status bar always above the prompt: mode, pending
  count, Shift+Tab hint, running-jobs tag; one-time onboarding tip
  on first launch after upgrade
- Context hygiene: read_file `range:"A-B"` + auto-preview for files
  >200 lines; directory_tree default depth 4→2 + skip deps
  (node_modules / .git / dist / …) + per-directory 50-child collapse;
  auto-compact tool-call args after each tool response (>800 tok);
  /compact now covers both tool results and tool-call args
- Persist reasoningEffort to config so /effort high survives restart
  (earlier: silently reverted to max); editMode already persisted
- Prompt: scope discipline on "run/start/launch" requests so the
  model stops after verifying instead of auto-refactoring; teach
  model that run_background is for dev servers and review-mode
  rejections should not be retried with the same SEARCH/REPLACE

tests: 1055 passing (+17 new)
2026-04-24 02:17:34 -07:00
esengine ee577995d0 fix(errors): actionable messages for 401/402/422 + V4 context-overflow hint (0.5.23)
Before: DeepSeek auth/balance/parameter errors surfaced as raw
"DeepSeek 401: {\"error\":{\"message\":\"...\"}}" JSON blobs. Users
saw a wall of JSON and had to know to parse it themselves to learn
their API key was bad or they were out of credit.

formatLoopError now recognizes the per-code cases:

  401 → "Authentication failed (DeepSeek 401): <inner msg>. Your API
         key is rejected. Fix with `reasonix setup` or
         `export DEEPSEEK_API_KEY=sk-...`. Get one at
         https://platform.deepseek.com/api_keys."
  402 → "Out of balance (DeepSeek 402): <inner msg>. Top up at
         https://platform.deepseek.com/top_up — the panel header
         shows your balance once it's non-zero."
  422 → "Invalid parameter (DeepSeek 422): <inner msg>"
  400 → "Bad request (DeepSeek 400): <inner msg>"

Each unwraps `{"error":{"message":"..."}}` so the reader sees prose,
not JSON. Fallback keeps the raw body if parsing fails.

Context-overflow text also refreshed: mentions V4's 1M window AND
the legacy 131k for the chat/reasoner aliases, and drops the stale
"v0.3.0-alpha.6+" reference that's long-since rolled into the 0.5
release line. The "8k tokens per tool result" cap is current
(src/mcp/registry.ts DEFAULT_MAX_RESULT_TOKENS).

429/500/502/503/504/408 retries unchanged — fully absorbed by
retry.ts before they reach formatLoopError.

1013 tests (+6). Lint / typecheck / build clean.
2026-04-23 21:22:14 -07:00
esengine e3d6fe3a86 fix(client): bump default timeout past DeepSeek's 10-min queue cap (0.5.22)
DeepSeek's 2026-04 docs spell out that when concurrency is saturated
but the request is accepted, the connection stays open for up to 10
minutes while the request waits in the queue — non-streaming bodies
fill with empty lines, streaming bodies fill with `:` SSE keep-alive
comments. Both are invisible to our parsers (JSON.parse tolerates
leading whitespace; eventsource-parser drops `:`-prefixed comment
lines per the SSE spec), so no separate handling is needed.

What WAS broken: `timeoutMs` defaulted to 120s. A request that sat
in the queue past 2 min triggered our AbortController, which burned
the queue slot and bounced through retryWithBackoff — potentially
looping through the whole queue repeatedly and never landing.

Fix: bump default to 660_000ms (11 min). Server's own 10-min cap
closes the connection first on genuine queue overflow (clean EOF
→ our retry is normal), while still catching truly hung sockets.

Callers that want a tighter budget (short-lived CI checks, smoke
tests) keep their explicit `timeoutMs` override. No API shape change.

1007 tests. Lint / typecheck / build clean.
2026-04-23 21:17:04 -07:00
esengine bfc4cd38ee docs(readme): update for V4 models, /effort, /resource, /prompt, 1M context, !/@ shortcuts
- Tagline + /preset max + /think: V3/R1 → V4 (flash + pro)
- /model row lists v4-flash/pro as primary, chat/reasoner as compat aliases
- Add /effort, /resource, /prompt, /models, /context, /stats, /keys rows
- Context window 131k → 1M; test count 648 → 1007
- New "Prompt prefixes — !cmd and @path" section documenting the bang-
  mode shell shortcut (0.5.8, now session-durable) and @-mentions
  picker (0.5.5-0.5.7) — both are daily-use features that had no home
  in the README until now.
- Panel header example bumped from 0.4.22 to the current 0.5.21 with
  the reasoning-effort `· max` badge visible.

No code changes.
2026-04-23 21:13:00 -07:00
esengine 0ccc419d0d feat(v4): integrate DeepSeek V4 — models, pricing, thinking toggle, effort control (0.5.21)
Models & pricing (src/telemetry.ts):
- Add deepseek-v4-flash (¥0.2 / ¥1 / ¥2 per 1M hit/miss/out) and
  deepseek-v4-pro (¥1 / ¥12 / ¥24), converted at 7.2 CNY/USD.
- deepseek-chat and deepseek-reasoner now priced identically to
  v4-flash — per the 2026-04 V4 launch they're compat aliases for
  flash non-thinking / thinking modes respectively.
- Context bumped to 1M tokens across all four entries.

Defaults shifted to v4-pro (agent-class flagship):
- `reasonix code` mode, subagent DEFAULT_SUBAGENT_MODEL, loop
  constructor fallback, `max` preset all point at deepseek-v4-pro.
- `fast` / `smart` presets stay on chat/reasoner — those aliases are
  currently our only way to pin thinking ON or OFF via model name,
  so the preset system still has a cheap/fast option.
- Subagent tool enum widened to [v4-flash, v4-pro, chat, reasoner];
  description flipped to treat flash as the "cheaper opt-out" path.

Thinking-mode toggle + reasoning_effort (new API params):
- src/types.ts ChatRequestOptions gains `thinking?: "enabled" | "disabled"`
  serialized as extra_body.thinking.type, and `reasoningEffort?:
  "high" | "max"` as the top-level reasoning_effort field.
- src/loop.ts exposes thinkingModeForModel(model) and pins the
  correct value per model name (chat=disabled, reasoner=enabled,
  v4-*=enabled, unknown=undefined/server-default). Every turn now
  sets thinking + reasoningEffort explicitly — no more relying on
  server defaults to match what reasoning_content round-trip expects.
- reasoning_effort defaults to "max" because Reasonix is exactly the
  agent-class use case DeepSeek's docs call out.

UI: /effort slash + StatsPanel badge:
- `/effort [high|max]` flips the loop's reasoningEffort mid-session.
- `/effort` no-arg reports the current value.
- StatsPanel header shows a green `· max` or yellow `· high` tag next
  to harvest/branch/PLAN so users always see which tier the next turn
  will use. `/status` flags line also reports it.

Harvest cost tuning (src/harvest.ts):
- Default model reverted to deepseek-chat — harvest is a micro-
  extraction (4 small arrays of strings), not agent work.
- chat() call explicitly pins thinking=disabled + effort=high so a
  future default-model swap can't accidentally promote this micro-
  call into a multi-thousand-reasoning-token request.

1007 tests (+9 new: thinking toggle, /effort slash, v4 pricing).
Lint / typecheck / build clean.
2026-04-23 21:10:13 -07:00
esengine 7542aca687 feat(ui): show "N ready · building call M" during multi-tool turns (0.5.19)
Long assistant responses with many tool_calls used to render as a
single static "building tool call <write_file> · 37 chars" spinner
for 10–30s — user could see tokens being consumed but had no sense of
how many files were coming or how far along the stream was.

Each tool_call's `arguments` blob is now tried as JSON at every delta.
Once it first parses, the index is marked "ready" and the count goes
into subsequent `tool_call_delta` events. The UI label becomes
"building tool call (call 3) <write_file> · 127 chars · 2 ready"
so the user sees progress accumulating.

Dispatch timing is UNCHANGED — this is purely a visibility upgrade.
Mid-stream eager dispatch was considered and punted because it would
interact awkwardly with the repair step (truncation fix, storm
breaker, scavenge) that runs post-stream.

+6 tests locking down looksLikeCompleteJson (the gate that decides
when a streaming call counts as "ready"). 991 tests.
2026-04-23 20:18:10 -07:00
esengine 1e906bb577 fix(r1): round-trip reasoning_content on EVERY reasoner assistant turn (0.5.18)
0.5.15 scoped the fix too narrowly — only attached reasoning_content
when `tool_calls.length > 0`. DeepSeek's "thinking mode must be
passed back" rule applies to ANY R1-generated assistant message.

Symptom: plan approved → synthetic user message "implement it now" →
next API call 400s. The intermediate "plan submitted — awaiting
approval" plain-text R1 turn was persisted without its reasoning,
and R1 rejected the entire history the next time around.

Changes:
- assistantMessage() drops the tool_calls guard; reasoning attaches
  whenever the model emitted any (even on plain-text turns).
- Forced-summary path (no-tools fallback) now captures reasoning from
  the summary response.
- New syntheticAssistantMessage() stamps an empty-string
  reasoning_content on synthetic turns (Esc-abort notices) when the
  model is a reasoner, so R1's validator is satisfied even when no
  real reasoning exists. V3 stays clean.
- Test updated: plain-text reasoner turn now asserts reasoning
  DOES round-trip (reversed from 0.5.15's assumption).

985 tests.
2026-04-23 20:03:06 -07:00
esengine a8c367ad0c fix(citation): leading / resolves to project root, not filesystem root (0.5.17)
Symptom: user wrote a game design doc to `F:/Reasonix/game-design-doc.md`,
the model cited it as `[...](/game-design-doc.md)`, and Reasonix rendered
"✗ /game-design-doc.md → file not found" even though the file was
right there on disk.

Cause: `validateCitation` ran `isAbsolute(path)` on the raw URL. A model
writing `/foo.md` means "project-root relative" (Aider / Claude-Code
convention), but Node's isAbsolute returns true, so the validator
stat'd the literal `/foo.md` under the filesystem root and got ENOENT.

Fix: strip leading `/` or `\` before the absoluteness test. Drive-letter
paths (`C:\...`) still pass isAbsolute and are respected; plain
leading-slash paths become project-relative. Unix absolute citations
like `/etc/hosts` lose precision but are vanishingly rare in code
citations — if we need them we'll add an explicit scheme.

+2 markdown tests for the new leading-slash behavior (both `/` and `\`).
985 tests.
2026-04-23 19:57:49 -07:00
esengine 2d35cab39e fix(plan): actually stop the flicker — pause ticker, tighten clamp, stabilize onChoose (0.5.16)
0.5.14's clamp was insufficient. Three root causes the earlier fix missed:

1. TickerProvider kept pumping 120ms re-renders even while the picker
   was up — the memo'd PlanConfirm still re-evaluated on every tick
   because `onChoose` identity changed (handlePlanConfirm has `busy` in
   its deps; busy toggles during model streaming). Fix: disable the
   ticker while `pendingPlan` or `pendingShell` is set. No ticker = no
   re-render cadence to drive Ink redraws.

2. `clampBodyByLines` clamped SOURCE lines, not rendered rows.
   Markdown expands ~2× (wrap, code fences, heading blanks, list
   indent), so `rows - 18` source lines still overflowed on a 40-row
   terminal. Fix: divide by MARKDOWN_EXPANSION before clamping so the
   rendered output actually fits.

3. `handlePlanConfirm` identity churns — wrapped in a ref-stable
   `stableHandlePlanConfirm` so `React.memo(PlanConfirm)`'s shallow
   compare actually skips re-renders when `plan` + `projectRoot`
   haven't changed.

Together these pin the picker's rendered height to a known budget AND
eliminate the re-render loop that caused Ink to clear+redraw each
frame. The overflow-can't-scroll symptom is inherent to Ink's live
mode; only remedy is to make content fit, which the tightened clamp
now guarantees.
2026-04-23 19:54:19 -07:00
esengine 874d7df2f7 fix(r1): round-trip reasoning_content through tool loop (0.5.15)
DeepSeek R1 thinking mode 400s with "The reasoning_content in the
thinking mode must be passed back to the API" when a tool-loop
continuation replays an assistant message that had tool_calls but
no reasoning. Root cause: assistantMessage() stripped the field.

Fix: ChatMessage gains optional reasoning_content. Loop passes the
captured reasoning into assistantMessage; we attach it only when
the turn has tool_calls AND reasoning is non-empty — plain-text
R1 turns stay lean, deepseek-chat is unaffected.

+2 tests (loop-r1-reasoning): turn-2 body asserts the echoed
assistant message carries reasoning_content on a tool-call turn,
and does NOT carry it on a plain-text turn.
2026-04-23 19:50:18 -07:00
esengine 4d39744d99 feat(0.5.14): visible/durable/reachable + plan-flicker + pending-edit persistence
- !cmd bang output now persists via loop.appendAndPersist, so session
  resume sees the shell history the model already reasoned against.
- Subagent runs (run_skill · runAs:subagent) now emit cost/model/usage
  on their end event. App.tsx writes one row to ~/.reasonix/usage.jsonl
  per run; the completion line also shows $X inline. `/stats` and
  `reasonix stats` render a new "subagent activity" section with
  per-skill breakdown.
- `/resource [uri]` + `/prompt [name]` slashes with argument-level
  pickers (reusing 0.5.13's SlashArgPicker). No arg lists what every
  connected MCP server exposes; with arg reads via live McpClient
  stored on McpServerSummary. Display-only v1 — no loop injection.
  `/mcp` now hints toward these when servers expose resources/prompts,
  `/keys` gets an "MCP exploration" section, `/help` lists both.
- Bug A — plan picker flicker on small terminals: PlanConfirm's
  markdown body is now line-clamped to (rows − 18), and the component
  is React.memoed so tick-driven parent re-renders skip the heavy
  Markdown subtree when props are unchanged.
- Bug B — pending-edit queue wiped on crash: new
  src/code/pending-edits.ts checkpoints the queue to
  ~/.reasonix/sessions/<name>.pending.json on every parse. /apply
  and /discard clear the file; session resume restores it with a
  visible banner. deleteSession removes the sidecar too.

981 tests (+31). lint / typecheck / build clean.
2026-04-23 19:44:28 -07:00
esengine 74da4f2a92 revert /edit slash + fix picker blocking Enter on exact match (still 0.5.13)
Two small course-corrections on the 0.5.13 work-in-progress. Version
stays at 0.5.13 — these land before publish.

### 1. Remove /edit

The one-shot `/edit <file> <instruction>` slash was 99% redundant
with `@path/file.ts <instruction>`: the 0.5.5 `@`-mention already
inlines the file, and code-mode's system prompt already teaches the
model to output SEARCH/REPLACE blocks. `/edit` added only the
"output ONLY a block, no prose" hint — not worth a whole slash.

Reverted:
- case "edit" handler (slash.ts)
- SLASH_COMMANDS registry entry
- /help line
- /edit test describe block + "/help mentions /edit" + required-list
- "file" from the argCompleter union type (no consumer left; the
  `@` picker remains the single file-picker surface, avoiding two
  competing file-autocompletes)
- "file" branch in App.tsx's slashArgMatches memo + the trailing-
  space special case in pickSlashArg

Users who want one-shot edits type `@src/foo.ts fix the typo` —
clearer to read in history and the model obliges by default.

### 2. Picker blocked Enter after exact match

Typing `/preset smart` left the picker visible with one match
("smart") → Enter was intercepted and re-substituted the same value
instead of submitting the command. Fix: slashArgMatches memo now
returns null when the partial is a case-insensitive EXACT match for
an enum value (or a model id). Picker hides; Enter submits.

- Test added documenting that the detector itself remains kind-
  only — the hide-on-exact-match logic lives in the App-side memo
  so the detector stays UI-agnostic.

### Tests

946 (was 952; dropped 6 /edit-specific tests, added 1 regression
for the exact-match fix, dropped the File-picker-for-/edit detector
test since that path is gone). Lint + typecheck + build clean.
2026-04-23 19:08:14 -07:00
esengine 36f6d245f9 feat(ui): argument-level pickers for slash commands (0.5.13)
User feedback: "after I type `/edit` there's no hint about what files
exist — same for other commands with args." Fixed.

### Mechanism

SlashCommandSpec gains an `argCompleter` field:

- `"file"`    → file picker (reuses atFiles + rankPickerCandidates
                with mtime + recently-used ranking from 0.5.12)
- `"models"`  → DeepSeek model-id list fetched at startup
- `string[]`  → small enum (e.g. `["fast", "smart", "max"]`)
- omitted     → no picker, just a dim usage hint below the prompt

Attached to: /edit → file, /preset → enum, /model → models,
/plan → on/off, /harvest → on/off, /branch → off + a few N values.

`detectSlashArgContext(input, codeMode)` in slash.ts classifies the
buffer once the user has typed `/<cmd> ` — returns `{spec, partial,
partialOffset, kind}`. `kind` is "picker" (completable first-arg
position) or "hint" (past the first arg / no completer).

`src/cli/ui/SlashArgPicker.tsx` — new component mirroring the
SlashSuggestions / AtMentionSuggestions layout. Header row always
shows `/<cmd> <argsHint>  — <summary>` so even when no matches,
the user sees what's expected. Hint-only mode is a single dim row.

App.tsx: `slashArgSelected` state, `slashArgContext` memo,
`slashArgMatches` memo (dispatches on completer type), useEffect
clamp, `pickSlashArg` callback (splices at partialOffset; adds
trailing space for file picker so user can keep typing the
instruction; no trailing space for enum picks since those commands
take no further args). Wired into useInput arrow/Tab and
handleSubmit Enter intercept. Renders after SlashSuggestions +
AtMentionSuggestions.

### Tests (+11, suite 941 → 952)

tests/slash.test.ts — `detectSlashArgContext` suite covers: null
before name commit, null on unknown cmd, file picker for /edit in
code mode, contextual-command gating outside code mode, enum picker
for /preset, models completer for /model, /plan gated to code mode,
hint kind once partial has internal whitespace, picker with empty
partial (just-typed space), hint kind for free-form arg commands
like /commit.

Lint + typecheck + build clean. 952 tests, 7.5s.
2026-04-23 19:02:38 -07:00
esengine a44c23c0a8 feat(ui): @-picker recency ranking + /keys cheatsheet (0.5.12)
Two UX polishers bundled, closing out the A-E batch.

### D. `@` picker ranking by mtime + recently-used

Alphabetical sort was arbitrary on large repos — 500 files deep, the
first page was almost never what the user wanted. New ranking:

- Empty query → recently-used paths first, then mtime descending,
  then path alpha. "Recently used" = files touched by `read_file` /
  `edit_file` / `write_file` / `search_content` / etc. tool calls
  this session (20-slot LRU; resets on session change).
- Non-empty query → existing substring/prefix scoring, tiebreak by
  recently-used membership then mtime.
- Back-compat: `string[]` input with no recency list still returns
  input order (old tests pass unchanged).

Implementation:

- `listFilesWithStatsSync(root, opts)` — same walk as listFilesSync
  plus a statSync per file. Stat failures don't throw; the entry
  keeps `mtimeMs: 0` and sinks to the bottom of the recency bucket.
- `FileWithStats` / `PickerCandidate` / `RankPickerOptions` types
  exported for library callers.
- `rankPickerCandidates(files, query, limitOrOpts)` — overloaded:
  bare number still works (back-compat), or pass
  `{ limit, recentlyUsed }`.
- App.tsx: `atFiles` memo switched to listFilesWithStatsSync;
  `recentFilesRef` (useRef<string[]>) + `recordRecentFile(p)` LRU
  callback; `tool_start` event handler inspects `toolArgs` for
  `path` / `file_path` / `file` fields and feeds the LRU.

### E. `/keys` cheatsheet slash

Discoverability gap: `!` bang, `@` picker, `/` slash, Shift+Enter,
Ctrl+J, Ctrl+A/E, Esc, y/n — the kit is extensive but undocumented
in one place. `/keys` dumps a formatted table:

    Keyboard & prompt shortcuts:
      Enter                  submit the current prompt
      Shift+Enter / Ctrl+J   insert a newline
      ...

    Prompt prefixes:
      /<name>    slash command
      @<path>    inline a file (code mode)
      !<cmd>     run <cmd> as shell

    Pickers (slash + @-mention):
      ↑ / ↓      navigate
      Tab        insert without submitting
      Enter      insert + run/keep-editing

Added to SLASH_COMMANDS registry + cross-linked from `/help`.

### Tests (+9, suite 932 → 941)

- tests/at-mentions.test.ts — 5 new for rankPickerCandidates:
  mtime sort on empty query with FileWithStats, recently-used boost
  trumps mtime, non-empty query tiebreak by recent+mtime, back-compat
  input-order preservation for bare strings, numeric-limit literal
  as third arg.
- tests/slash.test.ts — 4 new for /keys: shortcuts listed, prefixes
  listed, pickers mentioned, /help cross-reference.

### Note on release cadence

A (0.5.9) + B (0.5.10) + C (0.5.11) + D + E were split across five
commits but each dist is cumulative — publishing only the final one
gets users everything. Going forward I'll bundle closer unless the
user asks otherwise.

Lint + typecheck + build clean. 941 tests, 8.3s.
2026-04-23 18:54:04 -07:00
esengine 337ded3839 feat(code): unified-diff preview for pending edit blocks (0.5.11)
Before /apply, the UI used to show only
    ▸ 2 pending edit block(s) — /apply or /discard
          src/a.ts  (-3 +4 lines)
          src/b.ts  (-1 +1 lines)
— a count summary, nothing about what was actually changing. Common
mistake shape: press y, look at git diff afterwards, discover the
model edited the wrong block / wrong file.

Now each pending block is rendered as a compact diff with ±2 lines of
context and a hard cap at 20 lines per block:

    ▸ 2 pending edit block(s) — /apply (or y) to commit · /discard (or n) to drop
          src/foo.ts  (-1 +1 lines)
            function foo() {
        -   const x = 1;
        +   const x = 2;
            return x;

      NEW src/bar.ts  (-0 +3 lines)
        + export const bar = 1;
        + export const baz = 2;
        + export default { bar, baz };

### Mechanism

`src/code/diff-preview.ts`:

- `formatEditBlockDiff(block, opts)` — shared leading/trailing lines
  collapse to context (default 2 lines each side, `… N unchanged lines
  above/below` when truncated). Middle divergence is `-old` / `+new`.
  Whole block capped at 20 lines with `… (N more diff lines — full
  content applies on /apply)` footer when exceeded. Empty-search
  (new file) case shows all-`+` lines.
- `formatAllBlockDiffs(blocks, opts)` — stitches each block's header
  (path + ±line counts, `NEW` prefix for new files) + its diff body,
  separated by blank lines.

Zero new deps. Small hand-rolled helper using prefix/suffix-compare;
sufficient for the typical SEARCH/REPLACE shape (small change inside
a function body, wrapped in a few lines of surrounding context).
Myers-diff quality is not needed — the model's SEARCH block already
minimizes context.

`formatPendingPreview` in App.tsx dropped its own summary line list
(paths now come from the per-block diff header) and its local
`countLines` helper (moved to diff-preview.ts alongside its only
consumer).

### No colors yet

Plain text, `-` / `+` / ` ` prefixes. ANSI colorization would need
Ink component plumbing that isn't worth the complexity for v1 —
the prefix convention is clear and universal (git / hunks / etc.).

### Tests (+10, suite 922 → 932)

tests/diff-preview.test.ts — new-file all-`+`, context collapse for
shared prefix/suffix, maxLines truncation with footer, leading and
trailing hidden-context annotations, single-line edits, custom
indent, multi-block formatAllBlockDiffs (path+counts headers, blank
separators, empty-input).

Lint + typecheck + build clean. 932 tests.
2026-04-23 18:47:01 -07:00
esengine 8ec6c630bd feat(slash): /edit <file> <instruction> — one-shot surgical edit (0.5.10)
One-liner shortcut for "change this one thing in this one file" —
faster than the multi-turn code-mode dance of "explain the file",
"here's my plan", "apply", etc. Code mode only.

### Mechanism

Zero new code paths. The slash is sugar: it builds a resubmit text of

    @<file> <instruction>

    Output ONLY a SEARCH/REPLACE block for this one edit. No prose,
    no explanation.

and hands that back through the normal turn machinery:

- 0.5.5's `@`-mention expansion inlines `<file>` under
  `[Referenced files]` so the model sees the current content.
- Code-mode's SEARCH/REPLACE handling already catches the output
  into `pendingEdits` (0.4.0+).
- The existing y/n confirm gate fires on the next event.

So `/edit src/foo.ts fix the typo` becomes equivalent to the user
typing `@src/foo.ts fix the typo. Output ONLY a SEARCH/REPLACE
block…` — the value is (a) discoverability via /help and slash
autocomplete, (b) the guaranteed-good prompt format without the user
having to remember it.

### Validation

- Outside code mode (no `codeRoot` in SlashContext) → refusal with a
  pointer to `reasonix code <dir>`.
- Missing file arg → usage hint.
- Missing instruction → usage hint with the file name echoed back.

### /help + discovery

Added to the slash autocomplete registry (`contextual: "code"` so
it only surfaces in code mode) and to the /help code-mode block.

### Tests (+6, suite 916 → 922)

tests/slash.test.ts — /edit describe block covers: non-code-mode
refusal, missing file, missing instruction, resubmit shape
(contains `@file` + instruction + SEARCH/REPLACE + ONLY), multi-
word instruction preservation. Plus `/help mentions /edit` and
`edit` added to the `SLASH_COMMANDS registry contains every handler`
required-list.

Lint + typecheck + build clean. 922 tests.
2026-04-23 18:41:12 -07:00
esengine a787272ceb feat(ui): collapse large user pastes in Historical display (0.5.9)
Pasting a stack trace / log dump / sample file flooded the Historical
scrollback with a massive block, hiding prior turns. Now user input
that exceeds a threshold renders as:

    ▸ pasted 2.3 KB (84 lines) — first 10 shown, full text sent to model
    line 1
    …
    line 10
    … (74 more lines)

The MODEL still receives the full text. Only the displayed row
collapses — `loop.step(modelInput)` gets the original string
(including any `@`-mention expansion) unchanged.

### Mechanism

- `src/cli/ui/paste-collapse.ts` — `formatLongPaste(text, opts)` pure
  helper. Collapse triggers when line count > 40 OR char count > 2000
  (defaults, override via opts). Head shows 10 lines; remaining
  footer reads "… (N more lines)". Byte header formats B/KB/MB.
- App.tsx — wired at the user-row push site in handleSubmit
  (between the UserPromptSubmit hook gate and the loop.step dispatch).
  The `pasteDisplay.displayText` goes to the Historical row; the
  existing `modelInput` variable (raw or `@`-expanded) goes to the
  loop.

### Scope

Affects only the regular user-message row. Separate paths for
`!`-bang commands, `@` expansions, and slash outputs are untouched.
Skipped on short messages (pass-through, no allocation overhead
beyond a `split("\n")`).

### Tests (+10, suite 906 → 916)

tests/paste-collapse.test.ts covers: short pass-through, multi-line
pass-through, line-threshold collapse, char-threshold collapse,
KB/MB formatting, 1-vs-N-more-lines pluralization, custom
thresholds, custom headLines, zero remaining (head covers all),
exported defaults.

Lint + typecheck + build clean. 916 tests.
2026-04-23 18:37:26 -07:00
esengine 0ca16d6e2d feat(ui): !cmd bash-mode prefix — user-typed shell passthrough (0.5.8)
Claude-Code-style bash mode. User types `!ls src/` or `!git status`;
Reasonix runs the command in the sandbox root, shows both the command
and its output, and appends the combined text to the conversation log
so the next model turn has the context automatically.

Faster than round-tripping through the model just to cat a file or
check git state, and closes a common UX gap vs. Claude Code.

### Mechanism

- `src/cli/ui/bang.ts` — `detectBangCommand(text)` returns the command
  body (whitespace-trimmed) or null. Only a LEADING `!` counts; `!`
  alone / `!   ` returns null; `echo !hi` doesn't trigger (the `!`
  isn't at position 0).
- `formatBangUserMessage(cmd, output)` — prepends a `[!cmd]\n`
  header so the model can distinguish user-typed shell output from
  its own `run_command` tool results (which are `role: tool`,
  structurally different).
- App.tsx handleSubmit intercept — fires AFTER the y/n fast-path (so
  pending edits still resolve cleanly) and BEFORE slash parsing:
  - Push `role: "user"` Historical row with the raw `!cmd` text.
  - `await runCommand(cmd, { cwd: codeMode?.rootDir ?? cwd,
    timeoutSec: 60, maxOutputChars: 32_000 })`.
  - Push `role: "info"` Historical row with
    `formatCommandResult(cmd, result)`.
  - `loop.log.append({ role: "user", content: formatBangUserMessage
    (cmd, formatted) })` so the next step() includes it in
    buildMessages.
  - setBusy true/false around the run so PromptInput reflects the
    in-flight state.
  - Catch errors → warning row, don't log.

### No allowlist gate

User-typed `!` is explicit consent (consistent with Claude Code; the
allowlist exists to bound what the MODEL can do with `run_command`,
not what the user chooses by hand). If someone wants stricter gating
later a `REASONIX_BANG_CONFIRM=1` toggle could layer on — out of
scope here.

### Known limitation: session durability

`loop.log.append` updates in-memory only. On session resume, the bang
output is gone (the session file didn't see it). The next actual
step() does appendAndPersist for the next user turn, and the model
sees this bang output live within the same session either way.
Treating bang as ephemeral keeps the fast-path simple; durable
capture could land later if real usage surfaces demand.

### /help + discovery

/help gains a "Shell shortcut" section documenting `!cmd` with
example commands (`!git status   !ls src/   !npm test`), plus a
"File references" section covering the `@` picker from 0.5.5 / 0.5.7
that was undocumented there.

### Tests (+9, suite 897 → 906)

tests/bang.test.ts — detectBangCommand covers: body extraction,
whitespace trim, non-bang pass-through, `!`-alone / blank body,
mid-string `!` rejection, embedded-trailing-`!` preservation,
multi-word with flags/quotes. formatBangUserMessage covers header
prepending and verbatim body preservation.

Lint + typecheck + build clean. 906 tests, 8.6s.
2026-04-23 18:31:30 -07:00
esengine ecf2ea372b feat(ui): @mentions picker + post-build bundle smoke test (0.5.7)
Two shipped, both extending 0.5's foundation:

### 1. @mentions picker UI

0.5.5 shipped `@path/to/file` inline expansion but made the user type
the full path. 0.5.7 adds a picker that mirrors the existing
/slash autocomplete: type `@` (with optional partial) in code mode,
get a filtered file list with ↑/↓ navigation and Tab/Enter pick.

- `listFilesSync(root, opts)` — sync recursive walk, skips
  node_modules / .git / dist / build / .next / etc. + any dot-dirs.
  Caps at 500 results by default. Forward-slash paths on all
  platforms. 10-50ms on moderate repos — fits the TUI's single-turn-
  per-tick model cleanly.
- `detectAtPicker(input)` — returns `{query, atOffset}` when the
  buffer ends with an in-progress mention; `null` otherwise. Distinct
  from `AT_MENTION_PATTERN` which finds completed mentions anywhere
  for expandAtMentions.
- `rankPickerCandidates(files, query, limit)` — case-insensitive
  substring filter with a boost for basename-prefix matches. Empty
  query returns the first `limit` candidates alpha.
- `AtMentionSuggestions.tsx` — same shape as `SlashSuggestions`
  (matches null = hide, empty = "no matches", array = highlight
  selected cyan/bold). Shows basename bold + dir dimmed à la
  VS Code Quick Open.
- App.tsx wiring: `atFiles` memo (walk on rootDir change), `atPicker`
  / `atMatches` memos, `atSelected` state with useEffect clamp.
  Arrow keys + Tab in useInput (before slash so they don't conflict
  — mutually exclusive by construction). Enter in handleSubmit
  substitutes at the `@` offset and appends a space (space auto-
  dismisses the picker, next Enter submits).
- Limitation intentionally not fixed: files created mid-session by
  edit tools won't appear in the picker until next launch. User can
  always type the full path. Rebuilding the list on every turn would
  be wasteful for the 95% case.

### 2. Bundle smoke test

v0.5.4 shipped to npm with a tokenizer path resolution bug that
crashed on first API call. The unit tests were fine — they load
modules from src/, which doesn't exercise the post-bundle directory
layout. These two tests close that gap:

- `dist/index.js`: dynamic import (via file:// URL on Windows),
  invoke `truncateForModelByTokens` to force a tokenizer load. ENOENT
  ⇒ fail.
- `dist/cli/index.js`: spawn with `DEEPSEEK_BASE_URL=127.0.0.1:1` so
  fetch fails fast. Preflight's tokenizer load runs BEFORE fetch, so
  if the bundled layout can't find the data file we see the ENOENT
  in stderr. If tokenizer loads fine, we see connection-refused and
  the test passes.
- Both tests skip when the bundle is absent (dev runs that haven't
  built yet). CI runs `build` before `test` → always exercised.

Would have caught 0.5.4's regression pre-publish.

### Tests (+23, suite 874 → 897)

- tests/at-mentions.test.ts — 7 new for detectAtPicker, 2 for
  AT_PICKER_PREFIX vs AT_MENTION_PATTERN sanity, 6 for
  rankPickerCandidates (empty query, substring, basename-prefix
  boost, path-prefix, no-match, limit), 6 for listFilesSync (recurse,
  forward slashes, ignore dirs, dotfile inclusion, custom ignores,
  maxResults cap, unreadable root).
- tests/bundle-smoke.test.ts — 2 tests for lib + CLI bundle
  tokenizer resolution.

Library exports: `detectAtPicker`, `listFilesSync`,
`rankPickerCandidates`, `AT_PICKER_PREFIX`, `DEFAULT_PICKER_IGNORE_DIRS`,
`ListFilesOptions`.

Lint + typecheck + build clean. 897 tests, 8.1s.
2026-04-23 18:14:46 -07:00
esengine 335de43db5 fix(tokenizer): resolve data-file path in bundled builds (0.5.6)
**Critical production bug.** Since 0.5.0 introduced the tokenizer, any
bundled `reasonix run` / `code` / `chat` crashed with ENOENT on the
first API turn after 0.5.4 put the tokenizer on the hot path.

Root cause: `resolveDataPath()` used
`join(dirname(import.meta.url), "..", "data", "deepseek-tokenizer.json.gz")`.

- In dev (`src/tokenizer.ts`) → resolves to `data/` ✓
- In the bundled CLI (`dist/cli/index.js`) → `dist/cli/` + `..` +
  `data/` = `dist/data/` ✗ — the data file ships at PACKAGE ROOT per
  package.json `files` entry; `dist/data/` doesn't exist.

Why this slipped through: before 0.5.4, `countTokens()` was only
called from the opt-in `/context` slash. Casual smoke tests and unit
tests (which run tokenizer.ts directly from src/) never hit the
bundled resolution. 0.5.4's preflight put `countTokens()` on every
step() call — so the first user-facing turn after `npm publish 0.5.4`
would have crashed.

Fix: `resolveDataPath()` now tries multiple candidate paths and
returns the first one that `existsSync`:

1. `REASONIX_TOKENIZER_PATH` env override (unchanged).
2. `../data/...` — dev + bundled `dist/index.js`.
3. `../../data/...` — bundled CLI at `dist/cli/index.js`.
4. `require.resolve("reasonix/package.json")` root — fallback for
   unusual bundlers.

Also falls back to `process.cwd() + data/...` if all candidates
missed, so readFileSync surfaces a concrete path in the error rather
than silently missing.

Caught via live `DEEPSEEK_API_KEY=... node dist/cli/index.js run
"hi"` against the actual bundled output. Unit tests alone would not
have caught this (they load src/tokenizer.ts directly, bypassing
the bundle path). Follow-up consideration: an integration test that
runs the bundled CLI against a fake API response — out of scope here.

874 tests still pass. Lint + typecheck + build clean.
2026-04-23 17:58:35 -07:00
esengine af077ddb24 feat: @file mentions in code mode + session-load heal → tokens (0.5.5)
Two shipped in one release, both closing out the 0.5 arc:

### 1. Session-load heal migrated to tokens

0.5.2 and 0.5.3 made dispatch truncation, /compact, and auto-compact
token-aware. Session load was the last char-based truncation surface;
now closed. CJK tool results in a resumed session come back at the
same effective context footprint as English instead of slipping past
the old 32k-char cap at 2× the token cost.

- `healLoadedMessagesByTokens(messages, maxTokens)` — sibling of the
  existing char-based `healLoadedMessages`.
- `fixToolCallPairing(messages)` — pure helper extracted so both
  variants reuse the structural tool_calls ↔ tool pairing pass.
- Session-resume call in loop.ts constructor switched to the token
  variant with `DEFAULT_MAX_RESULT_TOKENS`. Stderr "healed" line now
  reads "shrunk N tokens of oversized tool output" instead of chars.
- buildMessages's per-turn heal (hot path) stays on the char variant
  — avoids a per-turn tokenizer pass on every tool message.

### 2. `@file` mentions in code mode

User types `@src/loop.ts` → the model sees the file content inlined
under a "Referenced files" block:

    look at @src/loop.ts and explain

    [Referenced files]
    <file path="src/loop.ts">
    ...
    </file>

The user's original text is preserved verbatim; expansion is append-
only so the display stays clean and the model can cite the file
unambiguously.

- Regex `(?<=^|\s)@([a-zA-Z0-9_./\-]+)` — requires word boundary so
  `[email protected]` and `foo@bar` don't trigger. Trailing sentence
  period (`@foo.ts.`) is stripped before lookup.
- Sandbox: relative paths only, resolved against `rootDir`, no `..`
  escape, no absolute paths. Violations get
  `<file path="..." skipped="escape"/>` so the model sees the refusal.
- `DEFAULT_AT_MENTION_MAX_BYTES = 64 KB` (matches tool-result cap
  ballpark). Larger → skipped="too-large" with byte count.
- Missing / not-a-regular-file → skipped with reason.
- De-dupe: same file referenced twice inlines once.
- UI feedback: an info row lists inlined/skipped files so the user
  sees what reached the model.
- Only active in code mode (codeMode.rootDir). Plain chat mode
  doesn't expand — file references there are ambiguous.

### Tests (+15, suite 859 → 874)

- tests/at-mentions.test.ts — regex: boundary matching, email
  rejection, multi-mention; expansion: inline content, de-dupe,
  multiple distinct files, missing/escape/absolute/too-large skips,
  trailing-dot stripping, directory rejection.

Library exports: `expandAtMentions`, `AT_MENTION_PATTERN`,
`DEFAULT_AT_MENTION_MAX_BYTES`, `AtMentionExpansion`,
`AtMentionOptions`. Plus `healLoadedMessagesByTokens` and
`fixToolCallPairing` from loop.ts.

Lint + typecheck + build clean. 874 tests, 5.2s.
2026-04-23 17:48:50 -07:00
esengine 84ea648c84 feat(loop): preflight context-size check before each request (0.5.4)
Reactive auto-compact (60%/80% on prior prompt_tokens) keys off the
PREVIOUS turn's server usage, so a fresh resumed session — or one new
oversized tool result — can push the current turn's buildMessages
straight past 131,072 tokens and make DeepSeek 400 with "maximum
context length" before we see any usage number. Preflight closes that
hole by estimating locally before sending.

Mechanism:

- `estimateRequestTokens(messages, toolSpecs)` in src/tokenizer.ts:
  `estimateConversationTokens(messages) + countTokens(JSON.stringify
  (toolSpecs))`. Mirrors the arithmetic `/context` slash already uses
  so the two numbers don't drift.

- loop.step() injection right after buildMessages(). If the estimate
  exceeds 95% of `DEEPSEEK_CONTEXT_TOKENS[model]` (fallback
  `DEFAULT_CONTEXT_TOKENS`), run `compact(1_000)` and rebuild
  messages from the shrunk log. Warning event names the preflight
  path + tokens saved.

- When there's nothing to compact (first-ever turn with a bulky
  system prompt, for example), still yield a warning naming the
  preflight estimate + "nothing to auto-compact — DeepSeek will likely
  400". User sees the reason before the crash, can /forget or /clear.
  We don't short-circuit the request — let DeepSeek decide; its 400
  catch path already surfaces a useful hint.

- Non-branching AND branching paths share the `messages` variable
  from the outer buildMessages call, so the one injection covers
  both. Forced-summary fallback keeps its own path (a preflight
  there would be too late; the summary is the recovery step).

Tests (+3, suite 856 → 859) in tests/preflight.test.ts:

- Fires when estimate > 95%: compact runs, "pre-compacted N tool
  result(s), saved M tokens" warning appears, loop still completes.
- Stays silent when estimate is comfortably under 95%.
- Warns (but does not block) when over 95% with nothing to compact.

Per-test context budgets are set by mutating `DEEPSEEK_CONTEXT_TOKENS
[TEST_MODEL]` — the table is `Record<string, number>` so the write
is well-typed; teardown deletes the key. Seeded tool results are
properly paired with a prior assistant.tool_calls so
healLoadedMessages doesn't strip them as orphans (which would make
preflight never fire).

Lint + typecheck + build clean. 859 tests, 5.0s.
2026-04-23 17:32:09 -07:00
esengine 2d95c5787d feat(loop): token-aware /compact + auto-compact (0.5.3)
0.5.2 put the DeepSeek V3 tokenizer on the dispatch hot path to cap
NEW tool results by real tokens. 0.5.3 extends that to the live log:
/compact and auto-compact now shrink existing tool results by tokens
too, closing the last surface where CJK text slipped past a char cap
at 2× the intended context cost.

Mechanism:

- `shrinkOversizedToolResultsByTokens(messages, maxTokens)` in
  src/loop.ts — sibling of the char-based `shrinkOversizedToolResults`.
  Fast-pathes tool entries whose length ≤ cap (tokens ≤ length
  guarantee); otherwise tokenizes each candidate twice (before +
  after `truncateForModelByTokens`) to report exact tokensSaved.
  Never tokenizes the full input (same 0.5.2 guard against BPE
  O(n²) on pathological repetitive content).

- `loop.compact(maxTokens = 4000)` now shrinks by tokens and returns
  `{ healedCount, tokensSaved, charsSaved }` (was `{ healedCount,
  charsSaved }`). Persists to the session file when present.

- Auto-compact thresholds in `step()`:
  · 60%-80% band: soft compact at 4000 tokens/result (was 16k chars,
    which was 4k tokens in English but 16k tokens in CJK).
  · >80% band: hard compact at 1000 tokens/result (was 4k chars).
  Warnings report exact tokensSaved instead of `charsSaved / 4`.

- `/compact [N]` slash cap semantic flipped from chars to tokens
  (default 4000). The `info` line now reads "saved N tokens
  (M chars)". Help text + suggestion hint updated.

- Session-load heal (`healLoadedMessages`) left on the char cap so
  stored session files keep loading under their existing semantics.
  Live compaction and dispatch-time truncation are the only two
  surfaces that went token-aware.

Tests (+6, suite 850 → 856):

- tests/compact-tokens.test.ts — small-tool no-op, oversize shrink,
  input non-mutation, user/assistant protection, CJK parity, fast
  path by length.
- tests/loop.test.ts — seeded log content in the two auto-compact
  tests reshaped from `"Z".repeat(N)` to realistic log lines (was
  hitting BPE pathological path; also the 60%-80% warning now
  reads "4k tokens" instead of "16k" chars).
- tests/slash.test.ts — /compact assertions updated for token-based
  output ("saved N tokens", "N tokens each"); test content reshaped
  to realistic log lines.

Breaking change: library callers that pass an explicit number to
`loop.compact(N)` expecting chars will now get a tighter cap (4000
tokens ≈ 16k chars English, ~4k chars CJK). Fail mode is "compaction
is more aggressive than expected," which is the safe direction.

Lint + typecheck + build clean. 856 tests, 5.1s.
2026-04-23 17:21:02 -07:00
esengine 19a2b8d2be feat(tools): token-aware tool-result truncation at dispatch (0.5.2)
Before: every tool result was char-capped at 32K chars (8K English
tokens, but 16K+ tokens for CJK — Chinese/Japanese/Korean tool output
slipped past the budget at 2× the intended context cost).

After: dispatch truncates by REAL DeepSeek V3 tokens, using the
tokenizer that shipped in 0.5.0. Default 8K tokens per result, same
effective footprint regardless of char density.

Mechanism (src/mcp/registry.ts:truncateForModelByTokens):

- Fast path `s.length <= maxTokens` — every token is ≥1 char, so
  length bounds tokens. Skip tokenize entirely for small results.
- Intermediate check for moderate strings (`length <= maxTokens * 4`)
  — tokenize once to confirm it really is over budget.
- For large strings: char-slice head + tail by budget, tokenize the
  slices (NOT the full input), shrink on overshoot. 1–2 iterations per
  slice, bounded at 6. We explicitly never tokenize the whole input —
  pathological repetitive content (`"A".repeat(50_000)`) costs 30s+
  in the pure-TS BPE and is bounded to small slices.
- Dropped-tokens count in the marker is estimated from the per-slice
  char/token ratio (marker reads "~N tokens") so we don't pay a full
  tokenize just for diagnostics.

Wire-up:

- src/tools.ts — `ToolRegistry.dispatch` accepts both `maxResultChars`
  (legacy) and `maxResultTokens` (new). Both apply if both set; the
  tighter one wins. Char-only callers keep their old behavior.
- src/loop.ts — hot-path dispatch switched from
  `maxResultChars: 32_000` to `maxResultTokens: DEFAULT_MAX_RESULT_TOKENS`
  (8_000). Session-healing paths still use chars (preserves backwards
  compat on loaded session files).
- `DEFAULT_MAX_RESULT_TOKENS` and `truncateForModelByTokens` exported
  via src/index.ts for library consumers.

Tests (+9, suite 841 → 850):

- tests/truncate-tokens.test.ts — fast-path, short-string verify,
  CJK cap parity with English, head+tail preservation, zero-budget,
  empty input, marker format.
- tests/loop.test.ts — existing "pre-clips at dispatch" test reshaped
  to use realistic log-line content (was `"A".repeat(50_000)` which
  hit the BPE O(n²) pathological path, 46s+ in the suite).

Lint + typecheck clean. Suite now 5.2s total.
2026-04-23 16:52:23 -07:00
esengine ca27ca50bf fix(shell): reject shell operators (|, >, <, &, &&, ||, 2>) with a clear error (0.5.1)
Before: model writes `dir | findstr foo` → tokenizer produced `["dir",
"/b", "|", "findstr", "foo"]` → quoteForCmdExe wrapped `|` as `"|"`
(literal) → cmd.exe passed `|` as an argument to dir → no pipe, no
error, silent wrong output. The 0.4.26 memory flagged this as a known
issue; encoding fix from that release made the failure visible but
didn't address the root confusion.

After: detectShellOperator() walks the raw command with quote-tracking
and returns the first unquoted operator token at a token boundary.
runCommand rejects before spawn with:

  run_command: shell operator "|" is not supported — this tool spawns
  one process, no shell expansion. Split into separate run_command
  calls and combine the output in your reasoning...

Quoted operators (`grep "a|b" file.txt`) and chars embedded in larger
tokens (`--flag=1&2`) pass through — those are literal argv bytes.
Matches the tool's stated "no shell expansion, no pipes, no redirects"
contract; turns the silent failure into a loud, actionable one.

Tool description updated to document the rejection + the quote-it-as-
a-literal workaround so the model learns the constraint from the spec.

Tests: 841 (+13 covering pipe, redirect, fd-redirect, &&/||, stuck-
redirect, quoted operators, embedded operators).
2026-04-23 16:38:27 -07:00
esengine d4615d6e76 chore(0.5.0): fix CI + add animated SVG logo
CI fix — biome lint surfaced 9 errors on the 0.5.0 commit:
- tokenizer.ts: Infinity → Number.POSITIVE_INFINITY (style/useNumberNamespace)
- tokenizer.ts: formatter wrap on the CJS fallback branch
- StatsPanel.tsx: noArrayIndexKey on the Wordmark map — restructured to a
  module-level WORDMARK_STYLES table keyed by char+color pair, dropped
  the `i` parameter entirely (previous biome-ignore comment only
  suppressed one of two sites the rule fires on)
- various whitespace / line-wrap fixes from `biome check --write`

Animated SVG logo at docs/logo.svg, embedded at the top of README:
- Concentric diamond brand mark (◈) with three layers of motion:
  slow rotation (18s), outer-stroke pulse (2.4s), inner-fill breathing
- REASONIX wordmark in the same cyan → fuchsia gradient the TUI uses,
  so the README and the running app share one visual identity
- Tagline underneath for SEO-style context
- Colors (~4.5:1 contrast on both GitHub dark and light) — no
  prefers-color-scheme switching needed

828 tests, lint + typecheck clean.
2026-04-23 09:34:25 -07:00
esengine 9eff2e2cfc feat(0.5.0): Reasonix visual identity + DeepSeek tokenizer + models/pricing/context
Visual redesign — drop the generic vertical bars for a Reasonix-native
design language. The UI should be recognizable as ours at a glance:

- ◈ REASONIX wordmark in truecolor gradient (cyan → violet), with
  breathing animation — slow when idle, faster when the model is
  thinking, so the app's state is readable from the edge of vision.
- Geometric role glyphs replace all text labels: ◇ user · ◆ assistant ·
  ▣ tool · ▥ tool-err · ▲ warn · ✦ error. Consistent geometric family,
  distinct per role, no overlap with Claude / Cursor / Cline.
- Streaming assistant glyph pulses ◆↔◇ at ~480ms — visible heartbeat
  during R1's long (20-90s) pre-first-byte silence.
- Turn separators render "─── ◆ ───" with the Reasonix mark centered.
- Responsive StatsPanel: stacks metrics vertically on <120-col
  terminals (SSH, split-pane); inline when there's room. Context
  cell gains a 10-cell progress bar in the stacked layout.
- Cold-start cache hit ratio (turn ≤ 3) renders dim gray with a
  "(cold start)" hint instead of red — new users stopped reading
  "0% cache on turn 1" as a configuration error.
- Tool results tail-truncate by default (useful signal is usually at
  the end). ERROR-prefixed results keep the first line + a tail.
- Modal footers gain "[↑↓] navigate · [Enter] select · [Esc] cancel"
  hints; Esc actually cancels now (ShellConfirm → deny, PlanConfirm →
  cancel); SingleSelect gained an optional footer slot.
- Wait-phase messaging (pre-first-byte, R1 reasoning, branching,
  tool-call streaming) gets visible yellow italic instead of dim —
  users had been misreading the dim variant as "frozen".

New features:

- Pure-TS port of DeepSeek's V3 tokenizer (vocab + merges + pre_tokenizer
  from the official tokenizer.json). Bundled as data/deepseek-
  tokenizer.json.gz (1.74MB, slimmed + gzipped from 7.5MB). Zero new
  deps — uses built-in zlib. Encodes ~12k tokens of mixed source in
  ~40ms. scripts/prepare-tokenizer.ts regenerates the bundle from
  upstream.
- /context slash — renders a breakdown of the next request's tokens:
  system prompt, tool specs, per-turn log, top 5 heaviest tool results.
  Answers "where is my context going?" directly; closes the gap where
  StatsPanel showed ctx % without saying why.
- /models slash — fetches DeepSeek's live model catalog via
  GET /models. Renders the list with the current model marked.
- /model <id> now soft-validates against the fetched catalog (warn
  but still switch — accommodates newly-released models we haven't
  indexed). DeepSeekClient gains a listModels() method.

Loop + billing correctness:

- Tool results pre-clipped at dispatch time (default 32k chars) via
  ToolRegistry.dispatch({ maxResultChars }). Oversized results no
  longer bloat the AppendOnlyLog or the persisted session file.
- New proactive-compact tier: when promptTokens / ctxMax crosses 60%
  (before the existing 80% reactive guard), shrink oversized tool
  results to 16k chars. Catches slow-growth patterns before they
  compound into a forced summary.
- DEEPSEEK_PRICING updated to the current unified rates (¥0.2 / ¥2 /
  ¥3 per 1M at cache-hit / cache-miss / output; USD 0.028 / 0.28 /
  0.42 at 7.2 CNY/USD). chat and reasoner are now priced identically
  at source. Stats dashboard figures were systematically high under
  the old tiered constants — new sessions bill correctly.
- Context display switches to binary-K (128K) to match DeepSeek's
  marketing label. DEEPSEEK_CONTEXT_TOKENS stays at 131072 — only
  the formatter divisor changed.

OSC 8 clickable hyperlinks in markdown were attempted and reverted:
Ink 5 strips \x1b / \x07 from Text output, so file:// links never
reach the terminal. Documented as a known limit; re-visit with a
future Ink release or raw-stdout approach.

828 tests (14 new: tokenizer golden cases + /context + /models +
listModels + pricing unification + proactive compact). Lint +
typecheck + build clean.
2026-04-23 09:28:40 -07:00
esengine c2f8e9b734 feat(0.4.28): reasonix code defaults harvest OFF — opt in via --harvest
Pillar 2 harvesting fires an extra V3 call per turn to extract a typed
plan state (subgoals/hypotheses/uncertainties/rejectedPaths) from R1's
reasoning_content. Cost ~10-15% per turn. Closer audit of who actually
consumes the output:

- subgoals / hypotheses / rejectedPaths — purely cosmetic, only rendered
  in PlanStateBlock. No programmatic consumer. Can mislead users by
  giving structured-looking output extra perceived authority (today's
  citation work was triggered by hallucinated "hypotheses" that looked
  thoughtful).
- uncertainties.length — single real downstream use, drives self-
  consistency branching when count exceeds threshold. Could be replaced
  with a cheap heuristic on the raw reasoning text.

For coding tasks specifically, branching is rarely on (default budget=1)
and the cosmetic display value doesn't justify the per-turn premium.
Flip the default off; users who genuinely want the plan state surfaced
can pass --harvest. `reasonix chat` is unchanged — preset behaviour
there still controls harvest.

799 tests, lint + build clean.
2026-04-23 05:13:20 -07:00
esengine d52599ec44 feat(0.4.27): citation-first answers — validated [text](path:line) links + broken-citation surface
Anti-hallucination intervention for evaluative tasks. Two real R1 sessions
where the model invented "Resources/Prompts/Progress not implemented" gaps
that had been shipped months ago (v0.4.5, v0.4.8) motivated this — same
hallucination shape both times, across independent prefixes. The fix is
structural: force the model to ground every codebase claim in a clickable
citation, validate them, render broken ones in red so the user sees
fabrications instantly.

- markdown.tsx: parse [text](url) links (was unsupported — rendered as
  literal). External URLs (https://, mailto:, //) → blue underline.
  Citation-shaped URLs (path / path:line / path:start-end / path#L42) →
  validated against projectRoot, valid = cyan underline, broken = red
  strikethrough + ❌. Bottom-of-message BrokenCitationsBlock lists each
  failure with reason ("file not found", "line 999 > 250") so the user
  can challenge the specific claim.
- code/prompt.ts + cli/index.ts: "Cite or shut up — non-negotiable"
  section moved to TOP of system prompt (was at the end and ignored).
  Concrete ✅/❌ examples. Negative-claim rule made imperative — "STOP.
  Call search_content FIRST" instead of "qualify it" — because asserting
  absence without checking is the #1 failure mode.
- App.tsx / EventLog.tsx / PlanConfirm.tsx: thread projectRoot through
  every <Markdown /> callsite (defaults to process.cwd() for safety).

Behavioural validation: same "analyze the project" prompt that produced
5/8 hallucinations pre-fix returned 3/3 verifiable specific claims +
1 auto-detected broken citation post-fix. Citation feature working in
production.

799 tests (17 new in markdown.test.ts: parseCitationUrl, isExternalUrl,
validateCitation, collectCitations dedup + external skip, parseBlocks
no-regression). Lint + typecheck + build clean.
2026-04-23 04:47:10 -07:00
esengine 3c8669577d feat(0.4.26): subagents-via-Skills + search_content + render/shell/sandbox fixes
- Subagents-via-Skills (replaces 0.4.25's spawn_subagent user-facing
  surface; library API kept). Skills frontmatter gains runAs:subagent +
  optional model:deepseek-*. Builtin explore + research skills ship in
  src/skills.ts as constants. spawnSubagent(opts) extracted from
  registerSubagentTool — both surfaces share it via formatSubagentResult.
  registerSkillTools moved into App.tsx with subagentRunner closure;
  reasonix code no longer registers spawn_subagent in the model tool list.
  Pinned Skills index marks subagent skills with a 🧬 prefix so the model
  pattern-matches "user says explore -> use 🧬 explore" instead of
  reasoning about whether a task is "big enough" to delegate.
- search_content: real content grep tool. Skips 18 dependency / build /
  VCS dirs by default + skips binaries by extension (30+ types) and
  by content sniff (NUL byte in first 8KB). Per-file 2 MB cap, output
  capped to maxListBytes. Regex + literal fallback, glob substring
  filter, case_sensitive + include_deps options. Closes the gap that
  made subagents waste their iter budget calling search_files (which
  is filename-only) for content-grep questions.
- markdown renderer: recognizes Unicode box-drawing tables (│ ─ ┼) +
  ┌─┐ │ └─┘ frames as code blocks. Table cells now render through
  InlineMd with padTo so backticks/bold inside cells parse and column
  widths align by visible (post-strip) width. Multi-line table cell
  continuation rows fold back into the previous row's last cell.
- shell on Windows: prepareSpawn injects chcp 65001 prefix into every
  cmd.exe /c payload + injects [Console]::OutputEncoding=UTF8 into
  PowerShell -Command invocations. Fixes mojibake on CJK Windows where
  cmd builtins (dir, findstr, where) and PowerShell emit text in CP936
  / CP932 / CP949 — previously poisoned the next turn's prompt with
  garbled bytes.
- sandbox: filesystem tools' safePath strips leading / and \ so
  POSIX-absolute paths (path: "/" or "/src/foo.ts") resolve to the
  sandbox root instead of the actual filesystem root. Models routinely
  pass these intending the project root; the old behavior failed the
  escape check with a confusing error.
- loop: aborted signal in the API-call catch yields a clean done
  instead of a red error event. The "This operation was aborted" row
  was always a self-inflicted UX bug — App.tsx calls loop.abort() to
  switch turns when the user picks ShellConfirm "always allow" or
  PlanConfirm approve, and the resulting AbortError got rendered as
  a real error. Subagent layer compensates by synthesizing an error
  result when no final answer was produced (so success!=true on abort).
- prompts: dropped the fictional `grep` tool reference from
  CODE_SYSTEM_PROMPT; explicit list of available exploration tools
  (read_file, list_directory, directory_tree, search_files,
  search_content, get_file_info). New "Path conventions" section
  distinguishes filesystem-tool sandbox-relative paths from
  run_command OS-shell paths (don't use leading / in shell args).

781 tests (+26 vs 0.4.24), lint + typecheck + build clean.
2026-04-23 02:30:15 -07:00
esengine 3fee4e6883 feat: reasonix stats — cross-session cost dashboard + /stats slash (0.4.24)
Every turn run through `reasonix chat|code|run` now appends one line
to ~/.reasonix/usage.jsonl carrying tokens + cost + the equivalent
Claude Sonnet 4.6 cost. `reasonix stats` (no arg) rolls that log up
into today / week / month / all-time windows with a "saved vs
Claude" column. Pillar 1's pitch (94–97% cost reduction) becomes a
fact users can check on their own machine.

Same dashboard is available in-session via the new /stats slash,
reading from the same file and rendering through a shared pure
renderer. reasonix stats <transcript> keeps the old per-file
summary (assistant turns + tool calls) for scripts.

Privacy: only tokens, costs, session name. No prompts, completions,
or tool args. Log append is best-effort — disk failure never blocks
a turn.

New files:
  src/usage.ts                 — appendUsage, readUsageLog, aggregateUsage,
                                  bucketCacheHitRatio / SavingsFraction
  tests/usage.test.ts          — 15 tests (round-trip, malformed line,
                                  rolling windows, renderer, zero denom)

Modified:
  src/cli/commands/stats.ts    — dashboard mode + extracted renderDashboard
  src/cli/commands/run.ts      — appendUsage on assistant_final (for CI)
  src/cli/ui/App.tsx           — appendUsage on assistant_final (TUI)
  src/cli/ui/slash.ts          — /stats slash (shared renderer)
  src/cli/index.ts             — `stats <transcript>` → `stats [transcript]`
  src/index.ts                 — re-export usage module

+17 tests (suite 708 → 725). Lint + typecheck + build clean.
2026-04-22 22:24:59 -07:00
esengine 41d21f7cea feat(slash): /update shows current vs latest + shell command (0.4.23)
Adds an in-session `/update` slash that reports the running version
and the last-resolved latest from the App's background npm-registry
check. Deliberately does NOT spawn `npm install` — stdio:inherit
into a running Ink renderer corrupts the display, and on Windows
the currently-running binary can be locked. Users exit and run
`reasonix update` in a fresh shell when they actually want to
install.

Also splits App state: we now track `latestVersion` regardless of
whether it's newer (so the slash can tell "on the latest" apart
from "still fetching") and derive the yellow header badge from
that. Before this, `updateAvailable` was only set on strictly-
newer, so `/update` saw null when the user was already on the
latest — the message misleadingly said "background check in
flight or offline".

`/update` also triggers a fresh `getLatestVersion({force:true})`
when latestVersion is null, so a retry a few seconds later sees
a concrete answer.

4 new tests (suite 704 → 708). All green; lint / typecheck / build
clean.
2026-04-22 22:13:32 -07:00
esengine 715d8b5950 feat: hooks — user-defined automation at PreToolUse / PostToolUse / UserPromptSubmit / Stop (0.4.23)
Same two-scope layout as memory and skills:
  - <project>/.reasonix/settings.json (committable per-project)
  - ~/.reasonix/settings.json         (per-user)

A hook is a shell command. Reasonix invokes it with stdin = a JSON
envelope carrying the event, tool name, tool args, etc. Exit code
drives the decision:
  - 0 = pass; loop continues normally
  - 2 = block (only on PreToolUse / UserPromptSubmit); hook's stderr
    becomes the synthetic tool result the model sees, or the prompt
    is dropped entirely
  - anything else = warn; loop continues, stderr renders inline as a
    yellow row

Project hooks fire before global hooks. `match` is anchored regex on
the tool name (ignored for prompt / Stop events). Default timeouts:
5s for blocking events, 30s for logging events; per-hook `timeout`
overrides. Settings malformed? loadHooks swallows it so a typo
doesn't bring down the whole CLI.

Deliberate non-goals: no workflow DSL, no conditional chaining, no
hook templates. Hooks are shell commands — the user already has a
programming language.

New files:
  - src/hooks.ts                      (loadHooks, runHooks, decideOutcome, matchesTool, formatHookOutcomeMessage)
  - tests/hooks.test.ts               (26 unit tests)
  - tests/loop-hooks.test.ts          (6 smoke tests — loop wiring)

Modified:
  - src/loop.ts          — PreToolUse + PostToolUse dispatch around tool.dispatch
  - src/cli/ui/App.tsx   — load settings on mount, UserPromptSubmit before handleSubmit, Stop after loop.step
  - src/cli/ui/slash.ts  — /hooks list + /hooks reload
  - src/index.ts         — re-exports

+32 tests (suite 672 → 704). Lint / typecheck / build clean.
2026-04-22 22:06:29 -07:00
esengine 911f043db8 feat: version display in TUI header + reasonix update self-upgrade (0.4.22)
Two small quality-of-life additions.

The stats panel now carries the running version (`Reasonix v0.4.22 ·
model …`) so users can tell at a glance whether they're on the latest
build. A 24-hour background check against the npm registry surfaces a
yellow `update: X.Y.Z` nudge on the right side of the same row when a
newer version has been published — 2s timeout, cache at
`~/.reasonix/version-cache.json`, silent on failure.

`reasonix update` is the command form: detects global install vs npx,
spawns `npm install -g reasonix@latest` for the former or prints a
cache-refresh hint for the latter. `--dry-run` prints the plan.

Also fixes a drifted VERSION constant: `src/index.ts` hard-coded
"0.4.20" while package.json was on 0.4.21. Now re-exports from
`src/version.ts`, which walks up from import.meta.url to the
manifest on first access. A regression test pins them together.

New files: `src/version.ts`, `src/cli/commands/update.ts`,
`tests/version.test.ts`, `tests/update-command.test.ts`. +24 tests
(suite 648 → 672). Lint/typecheck/build clean.
2026-04-22 21:34:11 -07:00
esengine ce85319c9b docs(readme): promote reasonix code to the hero section, document skills
- Quick start now leads with `reasonix code` and a real SEARCH/REPLACE
  walkthrough — nobody enters through plain chat.
- New Skills section covers the SKILL.md format, project vs global
  scopes, /skill slash family, autonomous run_skill invocation, and
  the 'not tied to .claude/' stance.
- chat mode demoted to a brief 'also works as' section pointing at MCP.
- Commands table grouped by category (Core / Model / Context & tools /
  Memory & skills / Sessions / Code-mode only) instead of one flat list.
- Benchmarks promoted into their own 'verify yourself' section.
- Non-goals now names workflow DSL / DAG engine and DeepSeek-only
  positioning explicitly.
- Test count 444 → 648, Node requirement 18 → 20.10, added
  REASONIX_UI=plain to the env-var list.
2026-04-22 19:07:44 -07:00
esengine 2a9a9b386b feat: skills — project/global SKILL.md packs pinned into the prefix + shell fixes (0.4.21)
Skills are user-authored prompt packs read from `<project>/.reasonix/skills/`
and `~/.reasonix/skills/`. Pinned index (names + one-liners) lives in
the immutable prefix; bodies load lazily via the new `run_skill` tool
or `/skill <name> [args]`. Project scope wins on name collisions.
Deliberately NOT tied to any other client's dir (.claude/, .glm/) —
Reasonix is model-agnostic at the conversation layer.

No workflow DSL or DAG engine: skills are prose, the model sequences
via the existing tool-use loop. Preserves single-loop + append-only +
cache-first invariants; "no multi-agent orchestration" non-goal stands.

Shell fixes bundled in:
- ShellConfirm "always allow" now takes effect mid-session.
  extraAllowed is re-read on every dispatch via a getter, so a prefix
  saved to ~/.reasonix/config.json applies to the running tool
  without needing /new or a relaunch.
- Windows cmd.exe built-ins (dir, echo, type, ver, ...) no longer
  crash with ENOENT. prepareSpawn routes bare unresolved Windows
  commands through `cmd.exe /d /s /c` with verbatim-args quoting,
  matching the wrapping strategy for .cmd/.bat files.
2026-04-22 18:58:48 -07:00
esengine e3cfbb58dd feat: user memory — ~/.reasonix/memory/ pinned into the immutable prefix · remember/forget/recall tools · prompt cleanup (0.4.20)
- MemoryStore + applyUserMemory + applyMemoryStack (src/user-memory.ts):
  two scopes — global (cross-project) and project (per sandbox-root sha1).
  Each scope keeps a MEMORY.md index pinned into ImmutablePrefix.system;
  detail files loaded on demand via recall_memory. Byte-stable rewrite
  so identical file sets produce identical prefix hashes.
- remember / forget / recall_memory tools (src/tools/memory.ts) — chat
  mode gets global-only; reasonix code gets both scopes. remember's
  return text is imperative so R1 treats the fact as authoritative on
  the same turn.
- /memory slash extended: list | show <name> | forget <name> |
  clear <scope> confirm. Bare /memory renders REASONIX.md + both
  MEMORY.md blocks together.
- Prompt cleanup: dropped hardcoded dir enumerations, bun/npm examples,
  "待确认" CJK fallback, DSML-hallucination historical note, and
  Linear/Slack type-hint specifics. Principle-only wording + reference
  to the pinned .gitignore block. Net -tokens on every turn.
- README: new "User memory" subsection under REASONIX.md.
- scripts/smoke-memory.mts: 30-assertion end-to-end regression script.
- REASONIX_MEMORY=off now disables every memory source (REASONIX.md +
  user memory) — previous semantics was REASONIX.md only.

Tests: 542 → 624 (+82 incl. 36 memory-layer unit tests). Lint / tsc /
build clean.
2026-04-22 17:30:26 -07:00
esengine becaf487e8 fix(shell): use path.win32.join so CI tests with platform:win32 pass on Linux
CI runs on Linux, where pathMod.join defaults to POSIX (`/`). The
PATHEXT resolver mocks its isFile predicate with back-slashed keys
(`C:\tools\npm.CMD`), so join with POSIX produced `C:\tools/npm.CMD`
and lookups missed, failing 8 tests at origin. The runtime call path
is unaffected either way since the win32 branch is only active when
platform === "win32" anyway — but making the join explicitly win32
also hardens against weird PATHs on Windows where forward slashes
have historically crept in.
2026-04-22 06:38:41 -07:00
esengine 6111d8f621 fix(loop): surface StormBreaker suppression as a visible warning + reset on user turn
A silent storm-break was indistinguishable from a stalled turn — the
model would look like it gave up when really we'd suppressed its
repeat tool call. Now `step()` emits a dedicated warning event when
`report.stormsBroken > 0`, with distinct messages for the two cases:

- All calls suppressed (stuck retry): tell the user the model is
  looping on the same (tool, args) and point them at /retry or
  rewording the instruction. This is the case that used to dead-end
  the turn with nothing on screen.
- Some calls suppressed (one redundant): the rest of the turn
  proceeds; the warning is informational.

Also reset the StormBreaker's sliding window at the top of every
`step()` so a new user message doesn't inherit last turn's repeat
patterns (false-positive blocks on legitimate "try again" flows).

Part of the 0.4.19 batch — tag will be moved to this commit.
2026-04-22 06:35:13 -07:00
esengine d8ba9f9669 fix(shell): Windows — PATHEXT resolution + cmd.exe wrapping for .cmd/.bat (0.4.19)
Two layered fixes so `run_command` actually runs npm/npx/tsc/yarn/
pnpm/bun/pytest and every other Node-ecosystem wrapper on Windows:

1. resolveExecutable() walks PATH × PATHEXT manually — spawn
   with shell:false uses CreateProcess, which ignores PATHEXT, so
   bare `npm` missed `npm.cmd` and ENOENT'd.

2. prepareSpawn() wraps .cmd/.bat via `cmd.exe /d /s /c` with
   windowsVerbatimArguments + per-arg quoteForCmdExe — Node 21.7.3+/
   24 (CVE-2024-27980) refuses direct spawn of .cmd/.bat even with
   shell:false, throwing EINVAL. cmd.exe wrapping with manual
   safe-quoting keeps shell metacharacters (&, |, <, >, etc.) in
   arguments literal so the previous security posture holds.

Unix path unchanged. Suite 566 → 587.
2026-04-22 06:09:11 -07:00
esengine e409e9d8d9 feat: Plan Mode — autonomous plan proposals + /plan gate + answer-questions flow (0.4.18)
submit_plan tool: model proposes a markdown plan for large tasks
(multi-file refactors, ambiguous requests, risky changes). Picker
shows Approve / Refine / Cancel with the plan rendered as live
Markdown, not raw text. Open-questions sections ("Open questions",
"待确认", "Risks", etc.) are detected; default selection flips to
Refine and a yellow hint surfaces.

Both Approve and Refine take an inline text input afterward so the
user can answer the model's open questions or attach last-minute
instructions before the loop resumes. Empty Enter on Approve skips
the extras; empty Enter on Refine tells the model to ask concrete
clarifying questions.

/plan slash flips a dispatch-level read-only gate on the
ToolRegistry — writes + non-allowlisted shell bounce with a refusal
the model reads. Read tools, web_search/fetch, and allowlisted shell
(git status / cargo check / npm test etc.) still work during
exploration. Tool specs stay pinned across the toggle so the DeepSeek
prefix cache doesn't break.

/apply-plan is a fallback that force-approves without the picker,
for cases where the model wrote the plan in assistant text instead
of calling submit_plan.

Suite 542 → 566.
2026-04-22 05:50:28 -07:00
esengine 4d21ca4c4c feat: project memory — REASONIX.md pinned into the immutable prefix (0.4.17)
Drop a REASONIX.md in the project root and its contents are pinned
into the system prompt every session that opens there. Cache-first:
read once, hashed into the prefix fingerprint, no per-turn budget.
/memory prints what's currently pinned; REASONIX_MEMORY=off opts out.

Suite 517 → 542. Re-exported applyProjectMemory / readProjectMemory /
memoryEnabled + PROJECT_MEMORY_FILE / PROJECT_MEMORY_MAX_CHARS for
library consumers that build their own system prompt.
2026-04-22 04:55:06 -07:00
esengine 1ccc1d7e67 feat: run_command shell tool · session picker · ShellConfirm picker · backspace/markdown fixes (0.4.16) 2026-04-22 04:43:17 -07:00
esengine fd344986e8 feat: web_search via Mojeek · cursor editing in prompt · REASONIX_UI=plain · ticker consolidation (0.4.15) 2026-04-22 04:05:25 -07:00
esengine 6ceb73d367 fix(ui): consolidate timers · patchConsole:false · REASONIX_UI=plain opt-out (0.4.14) 2026-04-22 02:35:02 -07:00
esengine dee96f66a2 fix(ui): tool_call_delta progress · reset streamRef per iter · expanded README (0.4.13) 2026-04-22 01:59:44 -07:00
esengine 6b4d8652e4 fix(loop): full tool_calls↔tool pairing validator + auto-compact on context-guard (0.4.12)
Two DeepSeek 400s users hit in succession:
- "insufficient tool messages following tool_calls" on forced
  summary: context-guard appended assistant.tool_calls then bailed
  before dispatching. Fix: strip the tail before forceSummary.
- "tool must be a response to a preceding tool_calls" on the next
  message: partial heals left stray tool messages in the log.

Root fix: healLoadedMessages now runs a full tool_calls↔tool pairing
validator. Any assistant.tool_calls with an incomplete response set
is dropped (with its partial responses); any stray tool message is
dropped. Runs on session load (rewrites the file so damage doesn't
re-surface) AND on every buildMessages call (defensive).

Context-guard now auto-compacts before forcing summary. Previously
80% context meant you lost a turn immediately. Now: try shrinking
oversized tool payloads first; only fall back to forced summary
when nothing's compactable.

Split shrinkOversizedToolResults from healLoadedMessages so
`/compact` (mid-turn) doesn't strip legitimate structural state.

443 tests (+5 new, 4 reshaped).
2026-04-22 01:07:07 -07:00
137 changed files with 26351 additions and 1946 deletions

No files matched your search

+1066
View File
File diff suppressed because it is too large. Load diff
+678 -219
View File
@@ -1,3 +1,11 @@
<p align="center">
<img src="docs/logo.svg" alt="Reasonix — DeepSeek-native agent framework" width="640"/>
</p>
<p align="center">
<em>Cache-first agent loop for DeepSeek V4 (flash + pro) — Ink TUI, MCP first-class, no LangChain.</em>
</p>
# Reasonix
[![npm version](https://img.shields.io/npm/v/reasonix.svg)](https://www.npmjs.com/package/reasonix)
@@ -6,230 +14,630 @@
[![downloads](https://img.shields.io/npm/dm/reasonix.svg)](https://www.npmjs.com/package/reasonix)
[![node](https://img.shields.io/node/v/reasonix.svg)](./package.json)
**A DeepSeek-native AI coding assistant in your terminal.** Ink TUI. MCP
first-class. No LangChain.
```bash
npx reasonix
```
One command. First run walks you through a 30-second wizard (API key →
preset → pick MCP servers from a checklist); every run after that drops
straight into chat with your tools wired up. Inside the chat, type `/help`.
Why bother with yet another agent framework? Because every abstraction
here earns its weight against a DeepSeek-specific property — dirt-cheap
tokens, R1 reasoning traces, automatic prefix caching, JSON mode.
Generic wrappers treat DeepSeek as "OpenAI with a different base URL"
and leave these advantages on the table. Reasonix leans into them:
on the same τ-bench-lite workload,
[**94.4% cache hit, ~40% cheaper tokens, 100% pass rate**](#validated-numbers)
vs. a cache-hostile baseline.
**A DeepSeek-native AI coding agent in your terminal.** Edits files as
reviewable SEARCH/REPLACE blocks. Ink TUI. MCP first-class. No
LangChain.
---
## What you get
## Quick start (60 seconds)
| Feature | How it works | Opt in |
|---|---|---|
| **Setup wizard** | First run of `npx reasonix`: pick preset, multi-select MCP servers from a curated catalog, saved to config so the next run just launches chat | always on (first run) |
| **MCP (stdio + SSE)** | Multi-server bridge — every MCP tool inherits Cache-First + repair + context-safety automatically. `reasonix mcp list` shows the catalog | always on |
| **Cache-First Loop** | Immutable prefix + append-only log = prefix byte-stable across turns → DeepSeek's automatic prefix cache hits at 70–95% | always on |
| **Context safety net** | Tool results capped at 32k chars · oversized sessions auto-heal on load · `/compact` to shrink further · ctx gauge in the status bar · Esc to abort exploration and get a forced summary | always on |
| **R1 Thought Harvesting** | Parses `reasoning_content` into typed `{ subgoals, hypotheses, uncertainties, rejectedPaths }` via a cheap V3 call | `/preset smart` |
| **Self-Consistency Branching** | Runs N parallel samples at spread temperatures; picks the one with the fewest flagged uncertainties | `/preset max` / `/branch N` |
| **Tool-Call Repair** | Auto-flattens deep/wide schemas, scavenges tool calls leaked into `<think>`, repairs truncated JSON, breaks call-storms | always on |
| **Retry layer** | Exponential backoff + jitter on 408/429/500/502/503/504 and network errors. 4xx auth errors don't retry | always on |
| **Ink TUI** | Live cache-hit / cost / context panel. Streams R1 thinking to a compact preview. Renders Markdown (bold / lists / code / stripped LaTeX) | always on |
**1. Get a DeepSeek API key.** Free credit on signup:
<https://platform.deepseek.com/api_keys>
---
## Why not just use LangChain?
Even on the default `fast` preset (no harvest, no branching), Reasonix bakes
in five DeepSeek-specific defences that generic agent frameworks leave to you:
| | Reasonix default | generic frameworks |
|---|---|---|
| Prefix-stable loop (→ 85–95% cache hit) | ✅ | ❌ prompts rebuilt each turn |
| Auto-flatten deep tool schemas | ✅ | ❌ DeepSeek drops args |
| Retry with jittered backoff (429/503) | ✅ | ❌ custom callbacks |
| Scavenge tool calls leaked into `<think>` | ✅ | ❌ |
| Call-storm breaker on identical-arg repeats | ✅ | ❌ |
| Live cache-hit / cost / vs-Claude panel | ✅ | ❌ |
| First-run config prompt + Markdown TUI | ✅ | ❌ |
Harvest and self-consistency branching are bonuses on top. The everyday
win is that **a plain chat with Reasonix already pays for ~40% less tokens
than the same chat through a naive LangChain setup**, because the prefix
actually stays byte-stable.
## Validated numbers
**τ-bench-lite** — 8 multi-turn tool-use tasks × 3 repeats = 48 runs per
side. Same tools / same prompt / same client on both sides, sole variable
is prefix stability. Measured on live DeepSeek `deepseek-chat`:
| metric | baseline (cache-hostile) | Reasonix | delta |
|---|---:|---:|---:|
| runs | 24 | 24 | — |
| **cache hit** | 46.6% | **94.4%** | **+47.7pp** |
| cost / task | $0.002599 | $0.001579 | **−39% (×0.61)** |
| vs Claude Sonnet 4.6 (token-count estimate) | — | — | **~96% cheaper** |
| pass rate | 96% (23/24) | **100% (24/24)** | Reasonix held the guardrail on every run |
**Verify it yourself — no API key, zero cost:**
```bash
git clone https://github.com/esengine/reasonix.git && cd reasonix && npm install
npx reasonix replay benchmarks/tau-bench/transcripts/t01_address_happy.reasonix.r1.jsonl
npx reasonix diff \
benchmarks/tau-bench/transcripts/t01_address_happy.baseline.r1.jsonl \
benchmarks/tau-bench/transcripts/t01_address_happy.reasonix.r1.jsonl
```
The JSONL transcripts committed in `benchmarks/tau-bench/transcripts/`
carry per-turn `usage`, `cost`, and `prefixHash`. Reasonix's prefix hash
stays byte-stable across every model call; baseline's prefix churns on
every turn. The cache delta is *mechanically* attributable to log
stability, not to a different system prompt.
Full 48-run report: [`benchmarks/tau-bench/report.md`][r]. Reproduce
with your own API key: `npx tsx benchmarks/tau-bench/runner.ts --repeats 3`.
[r]: ./benchmarks/tau-bench/report.md
### MCP — works out of the box
Any [MCP](https://spec.modelcontextprotocol.io/) server's tools inherit
Cache-First + repair + context-safety automatically. The wizard (`npx
reasonix`) lets you multi-select from a curated catalog — no flags, no
JSON-by-hand. Three live reference runs:
| server | turns | tool calls | cache hit | cost | vs Claude |
|---|---:|---:|---:|---:|---:|
| bundled demo (`add` / `echo` / `get_time`) | 2 | 1 | **96.6%** (turn 2) | $0.000254 | −94.0% |
| official `@modelcontextprotocol/server-filesystem` | 5 | 4 | **96.7%** overall | $0.001235 | −97.0% |
| **both concurrently** (`demo_add` + `fs_write_file`) | 5 | 4 | **81.1%** | $0.001852 | −95.9% |
The third row is the ecosystem proof: two MCP servers running as
separate subprocesses, tools from both exercised in one conversation.
**One single prefix hash across all 5 turns** — byte-stability survives
concurrent MCP subprocesses.
Reproduce without an API key (replay the committed transcripts):
```bash
npx reasonix replay benchmarks/tau-bench/transcripts/mcp-demo.add.jsonl
npx reasonix replay benchmarks/tau-bench/transcripts/mcp-filesystem.jsonl
```
Supported transports: **stdio** (local `npx` or binary) and **HTTP+SSE**
(remote / hosted servers, MCP 2024-11-05 spec). Pass an `http(s)://`
URL to `--mcp` and Reasonix opens the SSE stream and POSTs JSON-RPC
to the endpoint the server advertises.
[mcp]: ./benchmarks/tau-bench/transcripts/mcp-demo.add.jsonl
---
## Usage
### One command
```bash
npx reasonix
```
First run: a wizard asks for your API key, lets you pick a preset
(fast / smart / max), then offers a multi-select checklist of MCP
servers — filesystem, memory, github, puppeteer, everything. Everything
is saved to `~/.reasonix/config.json`. Subsequent runs drop straight
into chat.
### Inside the chat
A status bar at the top shows cache hit %, cost, Claude-equivalent, and
the **context gauge** (`ctx 42k/131k (32%)` — yellow at 50%, red + a
`/compact` nudge at 80%). A command strip under the input lists the
slash commands:
```
/help full list + hints
/preset <fast|smart|max> one-tap bundles (model + harvest + branch)
/mcp list attached MCP servers and tools
/compact [cap] shrink oversized tool results in history
/sessions · /forget list / delete saved sessions
/setup reconfigure (exits and tells you to run `reasonix setup`)
/clear · /exit
```
**Esc while thinking** — abort the current exploration and force the
model to summarize what it already found. No more "model ran 24 tool
calls and gave up" — you get an answer every time.
Sessions live as JSONL under `~/.reasonix/sessions/<name>.jsonl` —
every message appended atomically, so killing the CLI never loses
context. Oversized tool results auto-heal on load, so poisoning a
session with one giant `read_file` doesn't brick your history.
### Code mode — `npx reasonix code`
A thin opinionated layer on top of chat: filesystem MCP bridged at
`cwd`, coding system prompt, reasoner preset, per-directory session.
The model proposes edits as **SEARCH/REPLACE blocks**:
```
src/foo.ts
<<<<<<< SEARCH
const x = 1;
=======
const x = 2;
>>>>>>> REPLACE
```
Reasonix parses them out of each turn, applies them to disk, reports
`✓ applied src/foo.ts` in the TUI. SEARCH must match byte-for-byte;
we never fuzzy-match (silent wrong edits are worse than loud
rejections). Run `git diff` to review, `git checkout .` to undo.
**2. Point it at a project.** No install needed.
```bash
cd my-project
npx reasonix code # default: cwd, reasoner, per-dir session
npx reasonix code src/ # scope the filesystem sandbox tighter
npx reasonix code --no-session # ephemeral
npx reasonix code
```
First-run sandbox: because code mode uses the filesystem MCP from
`@modelcontextprotocol/server-filesystem`, the model can only read
and write inside the directory you pointed at. It literally can't
touch files above that root.
First run walks you through a 30-second wizard (paste API key → pick
preset → multi-select MCP servers). Every run after that drops you
straight in.
### Advanced — CLI subcommands and flags
**3. Ask it to edit.** The model proposes edits as SEARCH/REPLACE
blocks — nothing hits disk until you `/apply`.
```
reasonix code › users.ts 里 findByEmail 对大小写敏感导致登录失败,帮我改
assistant
▸ tool<search_files> → src/users.ts, src/users.test.ts
▸ tool<read_file> → (src/users.ts, 412 chars)
▸ 找到了。findByEmail 直接用 === 比对。改成小写规范化并补一条测试。
src/users.ts
<<<<<<< SEARCH
return users.find(u => u.email === email);
=======
const needle = email.toLowerCase();
return users.find(u => u.email.toLowerCase() === needle);
>>>>>>> REPLACE
▸ 1 pending edit across 1 file — /apply to write · /discard to drop
reasonix code › /apply
▸ ✓ applied src/users.ts
```
Requires Node ≥ 20.10. macOS, Linux, Windows (PowerShell / Git Bash /
Windows Terminal). Press `Esc` anytime to abort; `/help` for the full
command list.
---
## `reasonix code` — pair programmer in your terminal
Scoped to the directory you launch from. The model has native
`read_file` / `write_file` / `edit_file` / `list_directory` /
`search_files` / `directory_tree` / `get_file_info` /
`create_directory` / `move_file` tools, all sandboxed — any path that
resolves outside the launch root (including `..` and symlink escapes)
is refused. Plus `run_command` with a read-only allowlist; anything
state-mutating (`npm install`, `git commit`, …) is gated behind a
confirmation picker.
### Walkthrough: explore before editing
For "what does this code do?" questions the model uses the read-side
tools and replies in prose — no SEARCH/REPLACE blocks, no file
writes. Ask to change something only when you mean it:
```
reasonix code › 这个项目的路由是怎么组织的?
assistant
▸ tool<directory_tree> → (src/ tree, 47 entries)
▸ tool<read_file> → (src/router.ts, 1.2 KB)
▸ 路由分三层:顶层 AppRouter 注册 tab,每个 tab 用 React Router 的
nested routes 写子路径,最后 …
```
If an `edit_file` SEARCH block doesn't match the file byte-for-byte,
the edit is refused loudly rather than fuzzy-matched. The model sees
the error and retries — silent wrong edits are worse than visible
rejections.
### Plan mode — review before executing
For anything bigger than a typo, the model is encouraged to propose a
markdown plan first. You'll see a picker with **Approve / Refine /
Cancel**:
```
reasonix code › 把 auth 从 JWT 迁移到 session cookies
▸ plan submitted — awaiting your review
────────────────────────────────────────
## Summary
Swap JWT middleware for session cookies, keep user table intact.
## Files
- src/auth/middleware.ts — replace `verifyJwt` with `readSession`
- src/auth/session.ts — new file, in-memory store + signed cookie
- src/routes/login.ts — return Set-Cookie instead of a token
- tests/auth/*.test.ts — update fixtures
## Risks
- Existing logged-in users get logged out (no migration).
- Session store is in-memory; restart clears sessions.
────────────────────────────────────────
▸ Approve and implement
Refine — explore more
Cancel
```
**Force it** with `/plan` — enters an explicit read-only phase where
the model *must* submit a plan before any edit or non-allowlisted
shell call will execute. Use for high-stakes changes you want to
audit before the model touches disk. `/plan off` or picker
Approve/Cancel exits.
### Prompt prefixes — `!cmd` and `@path`
Two inline shortcuts that don't need a slash:
**`!<cmd>` — run a shell command in the sandbox and feed it to the
model.** Typed at the prompt, like bash. Output lands in the visible
log AND in the session so the model's next turn reasons about it:
```
reasonix code › !git status --short
▸ M src/users.ts
▸ M src/users.test.ts
reasonix code › 把这两个文件的改动说明一下
assistant
▸ tool<read_file> → src/users.ts, src/users.test.ts
▸ …
```
No allowlist gate — user-typed shell = explicit consent. 60s timeout,
32k char cap, survives session resume since 0.5.14.
**`@path/to/file` — inline a file under "Referenced files."** Start
typing `@` and a picker appears (↑/↓ navigate, Tab/Enter to insert).
Good for "what does @src/users.ts do?" without making the model
`read_file` it first. Sandboxed: relative paths only, no `..` escape,
64KB per-file cap. Recent files rank higher.
### `/commit` — stage + commit in one step
```
reasonix code › /commit "fix: findByEmail case-insensitive"
▸ git add -A && git commit -m "fix: findByEmail case-insensitive"
[main a1b2c3d] fix: findByEmail case-insensitive
```
### Things to try
- `/tool 1` — dump the last tool call's full output (when the 400-char
inline clip isn't enough).
- `/think` — see the model's full reasoning for the last turn
(thinking-mode models: v4-flash / v4-pro / reasoner alias).
- `/undo` — roll back the last applied edit batch.
- `/new` — start fresh in the same directory without losing the
session file.
- `/effort high` — step down from the default `max` agent-class
reasoning_effort for cheaper/faster turns on simple tasks.
- `npx reasonix code --preset max` — v4-pro + 3-way self-consistency
branching for gnarly refactors.
- `npx reasonix code src/` — narrower sandbox (only `src/` is
writable).
- `npx reasonix code --no-session` — ephemeral; nothing saved.
### `reasonix stats` — how much did you actually save?
Every turn `reasonix chat|code|run` runs appends a compact record
(tokens + cost + what Claude Sonnet 4.6 would have charged) to
`~/.reasonix/usage.jsonl`. `reasonix stats` with no args rolls that
log into today / week / month / all-time windows:
```
Reasonix usage — /Users/you/.reasonix/usage.jsonl
turns cache hit cost (USD) vs Claude saved
----------------------------------------------------------------------
today 8 95.1% $0.004821 $0.1348 96.4%
week 34 93.8% $0.023104 $0.6081 96.2%
month 127 94.2% $0.081530 $2.1452 96.2%
all-time 342 94.0% $0.210881 $5.8934 96.4%
```
Privacy: only tokens, costs, and the session name you chose land
in the file. No prompts, no completions, no tool arguments.
`reasonix stats <transcript>` keeps the old per-file summary
(assistant turns + tool calls) for scripts that already use it.
### Staying current
The panel header shows the running version next to `Reasonix` (e.g.
`Reasonix v0.5.21 · deepseek-v4-pro · harvest · max …`, the trailing
`max` is the reasoning-effort badge — `/effort high` to step down).
A quiet 24-hour background check against
the npm registry surfaces a yellow `update: X.Y.Z` on the right side
of the same row when a newer version has been published. No blocking,
no nagging — the check runs once per day max and is silent on failure
(offline, firewall, etc.).
```bash
npx reasonix setup # reconfigure any time
npx reasonix chat --session work # a different named session
npx reasonix chat --no-session # ephemeral — nothing persisted
reasonix update # print current vs latest, run `npm i -g reasonix@latest`
reasonix update --dry-run # print the plan without running anything
```
Running via `npx`? The command detects that and prints a
cache-refresh hint instead — npx picks up the newest version on
its next invocation automatically.
### Project conventions — `REASONIX.md`
Drop a `REASONIX.md` in the project root and its contents are pinned
into the system prompt every launch. Committable team memory — house
conventions, domain glossary, things the model keeps forgetting:
```bash
cat > REASONIX.md <<'EOF'
# Notes for Reasonix
- Use snake_case for new Python modules; legacy camelCase modules keep their style.
- `cargo check` is in the auto-run allowlist; full `cargo test` needs confirmation.
- The `api/` dir mirrors `backend/` — keep schemas in sync.
EOF
```
Re-launch (or `/new`) to pick it up; the prefix is hashed once per
session to keep the DeepSeek cache warm. `/memory` prints what's
currently pinned. `REASONIX_MEMORY=off` disables every memory source
for CI / offline repro.
### User memory — `~/.reasonix/memory/`
A second, **private per-user** memory layer lives under your home
directory. Unlike `REASONIX.md` it's never committed, and the model
can write to it itself via the `remember` tool. Two scopes:
- `~/.reasonix/memory/global/` — cross-project (your preferences,
tooling).
- `~/.reasonix/memory/<project-hash>/` — scoped to one sandbox root
in `reasonix code` (decisions, local facts, per-repo shortcuts).
Each scope keeps an always-loaded `MEMORY.md` index of one-liners
plus zero or more `<name>.md` detail files (loaded on demand via
`recall_memory`). Writes land immediately; pinning into the system
prompt takes effect on next `/new` or launch so the cache prefix
stays stable for the current session.
```
reasonix code › 我用 bun 而不是 npm,请以后都用 bun 跑构建
assistant
▸ tool<remember> → project/bun_build saved
"Build command on this machine is `bun run build`"
```
**Slash**: `/memory` · `/memory list` · `/memory show <name>` ·
`/memory forget <name>` · `/memory clear <scope> confirm`.
**Model tools**: `remember(type, scope, name, description, content)` ·
`forget(scope, name)` · `recall_memory(scope, name)`.
Project scope is only available inside `reasonix code` (needs a real
sandbox root to hash); plain `reasonix` gets the global scope only.
### Skills — user-authored prompt packs
Skills are prose instruction blocks you drop on disk. Reasonix pins
their names + one-line descriptions into the system prompt; the
model can call `run_skill({name: "..."})` on its own when a match
fits, or you can type `/skill <name> [args]` to run one manually.
Two scopes, same layout as user memory:
- `<project>/.reasonix/skills/` — per-project skills (commit them to
share with your team, or add to `.gitignore` for personal drafts).
- `~/.reasonix/skills/` — global skills available everywhere.
Either layout works: `<name>/SKILL.md` (preferred — can bundle
additional assets alongside) or flat `<name>.md`.
```markdown
---
name: review
description: Review uncommitted changes and flag risks
---
Run `git diff` on staged and unstaged changes. Summarize what each
hunk does, call out potential regressions, and list files that might
need additional tests. Don't propose edits unless I ask.
```
Use it:
```
reasonix code › /skill review
▸ running skill: review
assistant
▸ tool<run_command> → git diff --cached
▸ 3 改动,1 个需要回归测试 …
```
Or let the model pick autonomously — because the skill's name +
description are pinned in the prefix, asking "帮我看下未提交的改动有没
有风险" triggers `run_skill({name: "review"})` without you typing the
slash command.
**Slash**: `/skill` (list) · `/skill show <name>` · `/skill <name>
[args]` (inject body as user turn).
**Deliberately not tied** to any other client's directory convention
(`.claude/skills`, etc.) — Reasonix is model-agnostic at the
conversation layer. Any SKILL.md you author works; the body is
prose, so skills authored for other tools usually port over unchanged
(Reasonix's tool names differ — `filesystem` / `shell` / `web` — but
the model reads the instructions and picks our equivalents).
### Hooks — automate around tool calls and turns
Drop a `settings.json` under `.reasonix/` (project or `~/`) and
Reasonix will fire shell commands at four well-known points in
the loop: before a tool runs, after a tool returns, before your
prompt reaches the model, and after the turn ends.
```json
// <project>/.reasonix/settings.json ← committable
// ~/.reasonix/settings.json ← per-user
{
"hooks": {
"PreToolUse": [{ "match": "edit_file|write_file", "command": "bun scripts/guard.ts" }],
"PostToolUse": [{ "match": "edit_file", "command": "biome format --write" }],
"UserPromptSubmit": [{ "command": "echo $(date +%s) >> ~/.reasonix/prompts.log" }],
"Stop": [{ "command": "bun test --run", "timeout": 60000 }]
}
}
```
Each hook is a shell command. Reasonix invokes it with stdin = a
JSON envelope describing the event:
```json
{ "event": "PreToolUse", "cwd": "/path/to/project",
"toolName": "edit_file", "toolArgs": { "path": "src/x.ts", "..." } }
```
Exit code drives the decision:
- **0** — pass; loop continues normally
- **2** — block (only on `PreToolUse` / `UserPromptSubmit`); the
hook's stderr becomes the synthetic tool result the model sees,
or the prompt is dropped entirely
- **anything else** — warn; loop continues, stderr renders as a
yellow row inline
`match` is anchored regex on the tool name; `*` or omitted matches
every tool. Project hooks fire before global hooks. Default
timeouts: 5s for blocking events, 30s for logging events; per-hook
`timeout` overrides.
**Slash**: `/hooks` (list active hooks) · `/hooks reload` (re-read
`settings.json` from disk without losing your session).
### Staying current from inside the TUI
`/update` inside a running session shows your current version, the
last-resolved latest version (from the quiet 24h background check),
and the shell command to run. The slash does *not* spawn
`npm install` — stdio:inherit into a running Ink renderer corrupts
the display. Exit the session and run `reasonix update` in a
fresh shell when you actually want to install.
---
## `reasonix` — also works as general chat
Same TUI, no filesystem tools unless you opt in via MCP. Good for
drafting, Q&A, schema design, architecture discussions, or driving
your own MCP servers. Sessions persist per name under
`~/.reasonix/sessions/`.
```bash
npx reasonix # uses saved config + wizard-selected MCP
npx reasonix --preset smart # reasoner + R1 harvest for this run
npx reasonix --session design # named session — resume later with --session design
```
Bridge your own MCP servers on the fly:
```bash
npx reasonix \
--mcp "fs=npx -y @modelcontextprotocol/server-filesystem /tmp/safe" \
--mcp "kb=https://mcp.example.com/sse"
```
MCP tools go through the same Cache-First + repair + context-safety
plumbing as native tools — 32k result cap, live progress-notification
rendering, retries.
---
## Commands inside the session
**Core**
| command | what it does |
|---|---|
| `/help` · `/?` | full command reference with hints |
| `/status` | current model · flags · context · session |
| `/new` · `/reset` | fresh conversation in the same session |
| `/clear` | clear visible scrollback only (log kept) |
| `/retry` | truncate and resend your last message (fresh sample) |
| `/exit` · `/quit` | quit |
**Model**
| command | what it does |
|---|---|
| `/preset <fast\|smart\|max>` | one-tap bundle (model + harvest + branch) |
| `/model <id>` | switch DeepSeek model (`deepseek-v4-flash`, `deepseek-v4-pro`, plus `deepseek-chat` / `deepseek-reasoner` compat aliases) |
| `/models` | list live models from DeepSeek `/models` endpoint |
| `/harvest [on\|off]` | toggle R1 plan-state extraction |
| `/branch <N\|off>` | run N parallel samples per turn, pick best (N ≥ 2) |
| `/effort <high\|max>` | reasoning_effort cap — `max` is the agent default, `high` is cheaper/faster |
| `/think` | dump the last turn's full thinking-mode reasoning |
**Context & tools**
| command | what it does |
|---|---|
| `/mcp` | list attached MCP servers and their tools / resources / prompts |
| `/resource [uri]` | browse + read MCP resources (no arg → list URIs; `<uri>` → fetch) |
| `/prompt [name]` | browse + fetch MCP prompts |
| `/tool [N]` | dump the Nth tool call's full output (1 = latest) |
| `/compact [tokens]` | shrink oversized tool results in the log (default 4000 tokens/result) |
| `/context` | break down where context tokens are going (system / tools / log) |
| `/stats` | cross-session cost dashboard (today / week / month / all-time) |
| `/keys` | keyboard shortcuts + prompt prefixes (`!` / `@` / `/`) cheatsheet |
**Memory & skills**
| command | what it does |
|---|---|
| `/memory` | show pinned memory (REASONIX.md + ~/.reasonix/memory) |
| `/memory list` · `show <name>` · `forget <name>` · `clear <scope> confirm` | manage the store |
| `/skill` · `/skill list` | list discovered skills (project + global) |
| `/skill show <name>` | dump one skill's body |
| `/skill <name> [args]` | run a skill (inject body as user turn) |
**Sessions**
| command | what it does |
|---|---|
| `/sessions` | list saved sessions (current marked with `▸`) |
| `/forget` | delete the current session from disk |
| `/setup` | reconfigure (exit and run `reasonix setup`) |
**Code mode only** (`reasonix code`)
| command | what it does |
|---|---|
| `/apply` | commit the pending SEARCH/REPLACE blocks to disk |
| `/discard` | drop the pending edit blocks without writing |
| `/undo` | roll back the last applied edit batch |
| `/commit "msg"` | `git add -A && git commit -m "msg"` |
| `/plan [on\|off]` | toggle read-only plan mode |
| `/apply-plan` | force-approve a pending plan |
**Keyboard**
- `Enter` — submit
- `Shift+Enter` / `Ctrl+J` — newline (multi-line paste also supported;
`\` + Enter as a portable fallback)
- `↑` / `↓` — walk prompt history while idle; navigate slash-autocomplete
- `Tab` / `Enter` on a `/foo` prefix — accept the highlighted suggestion
- `Esc` — abort the current turn (stops the API call, cancels any
in-flight tool, rejects pending MCP requests)
- `y` / `n` on confirm prompts — hotkey accept / reject
---
## Sessions and safety nets
- Sessions live as JSONL under `~/.reasonix/sessions/<name>.jsonl`
(per directory for `reasonix code`). Every message appended
atomically; `Ctrl+C` never loses context.
- Tool results are capped at 32k chars per call. Oversized sessions
self-heal on load (shrinks + rewrites the file).
- Malformed `assistant.tool_calls` / `tool` pairing is validated on
every outgoing API call so a corrupted session can't keep 400ing.
- Context gauge turns yellow at 50%, red at 80% with a `/compact`
nudge. Approaching the 1M-token window (V4 flash + pro) triggers an
automatic compaction attempt before falling back to a forced summary.
- The `reasonix code` sandbox refuses any path that resolves outside
the launch directory, including symlink escape and `..` traversal.
### Troubleshooting: duplicate rows / ghost rendering
Some Windows terminals (Git Bash / MINTTY / winpty-wrapped shells)
don't fully implement the ANSI cursor-up escapes Ink uses to repaint
the live spinner region. Symptom: spinners, streaming previews, or
tool-result rows print multiple copies into scrollback instead of
overwriting in place.
If you hit this, run with plain mode:
```bash
REASONIX_UI=plain npx reasonix code
```
Plain mode suppresses live/animated rows and disables the internal
tick timer. You lose the streaming preview and spinners but gain
stable scrollback. Windows Terminal, PowerShell 7 in Windows
Terminal, and WezTerm don't need this opt-out.
---
## Web search — on by default
The model has two web tools the moment you launch: `web_search` and
`web_fetch`. No flag, no API key, no signup. When you ask about
something the model wasn't trained on (new releases, current events,
obscure APIs), it decides to call `web_search` on its own; if a
snippet isn't enough it follows up with `web_fetch`.
Backed by **Mojeek**'s public search page — an independent web
index, bot-friendly, no cookies/sessions. Coverage on niche or very
recent queries can be thinner than Google/Bing, but it's reliable
from scripts. (DDG was the original backend but started serving
anti-bot pages in 2026.)
**Turn it off** (offline mode / privacy / CI):
```json
// ~/.reasonix/config.json
{ "apiKey": "sk-…", "search": false }
```
```bash
REASONIX_SEARCH=off npx reasonix code
```
**Bring your own** (Kagi, SearXNG, internal caches): implement the
`WebSearchProvider` interface and call
`registerWebTools(registry, { provider })` yourself, or bridge an
existing MCP search server via `--mcp`.
---
## MCP — bring your own tools
Any [MCP](https://spec.modelcontextprotocol.io/) server works. The
wizard lets you pick from a catalog, or drive it by flag:
```bash
# stdio (local subprocess)
npx reasonix --mcp "fs=npx -y @modelcontextprotocol/server-filesystem /tmp/safe"
# multiple at once
npx reasonix \
--mcp "fs=npx -y @modelcontextprotocol/server-filesystem /tmp/safe" \
--mcp "demo=npx tsx examples/mcp-server-demo.ts"
# HTTP+SSE (remote / hosted)
npx reasonix --mcp "kb=https://mcp.example.com/sse"
```
`reasonix mcp list` shows the curated catalog. `reasonix mcp inspect
<spec>` connects once and dumps the server's tools / resources /
prompts without starting a chat. Progress notifications from
long-running tools (2025-03-26 spec) render live as a progress bar
in the spinner.
Supported transports: **stdio** (local command) and **HTTP+SSE**
(remote, MCP 2024-11-05 spec).
---
## CLI reference
```bash
npx reasonix code [path] # coding mode scoped to path (default: cwd)
npx reasonix # chat (uses saved config)
npx reasonix setup # reconfigure the wizard
npx reasonix chat --session work # named session
npx reasonix chat --no-session # ephemeral
npx reasonix run "ask anything" # one-shot, streams to stdout
npx reasonix stats session.jsonl # summarize a transcript
npx reasonix replay chat.jsonl # scrub a transcript + rebuild cost/cache
npx reasonix replay chat.jsonl # rebuild cost/cache from a transcript
npx reasonix diff a.jsonl b.jsonl --md # compare two transcripts
npx reasonix mcp list # curated MCP server catalog
npx reasonix mcp list # curated MCP catalog
npx reasonix mcp inspect <spec> # probe a single MCP server
npx reasonix sessions # list saved sessions
```
Power users can still bypass config and drive Reasonix with flags:
Common flags:
```bash
npx reasonix chat \
--preset max \
--mcp "filesystem=npx -y @modelcontextprotocol/server-filesystem /tmp/safe" \
--mcp "kb=https://mcp.example.com/sse" \
--transcript session.jsonl \
--no-config # ignore ~/.reasonix/config.json (for CI / reproducing issues)
--preset <fast|smart|max> # bundle (model + harvest + branch)
--model <id> # explicit model id
--harvest / --no-harvest # R1 plan-state extraction
--branch <N> # self-consistency budget
--mcp "name=cmd args…" # attach an MCP server (repeatable)
--transcript path.jsonl # write a JSONL transcript on the side
--session <name> # named session (default: per-dir for code mode)
--no-session # ephemeral
--no-config # ignore ~/.reasonix/config.json (CI-friendly)
```
### Library
Env vars (win over config):
```bash
export DEEPSEEK_API_KEY=sk-...
export DEEPSEEK_BASE_URL=https://... # optional alternate endpoint
export REASONIX_MEMORY=off # disable REASONIX.md + user memory
export REASONIX_SEARCH=off # disable web_search / web_fetch
export REASONIX_UI=plain # disable live rows (ghosting workaround)
```
---
## Library usage
```ts
import {
@@ -261,7 +669,7 @@ const loop = new CacheFirstLoop({
toolSpecs: tools.specs(),
}),
harvest: true,
branch: 3, // self-consistency budget
branch: 3,
});
for await (const ev of loop.step("What is 17 + 25?")) {
@@ -270,29 +678,82 @@ for await (const ev of loop.step("What is 17 + 25?")) {
console.log(loop.stats.summary());
```
### Configuration
`ChatOptions.seedTools` accepts a pre-built `ToolRegistry` for
callers who want the `reasonix code` loop wiring without the CLI
wrapper. See [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) for
internals.
The wizard handles everything on first run. If you'd rather use env vars
(CI, shared boxes, etc.):
---
## Benchmarks — verify the cache-hit claim yourself
Every abstraction here earns its weight against a DeepSeek-specific
property — dirt-cheap tokens, R1 reasoning traces, automatic prefix
caching, JSON mode. Generic wrappers leave these on the table.
| | Reasonix default | generic frameworks |
|---|---|---|
| Prefix-stable loop (→ 85–95% cache hit) | yes | no (prompts rebuilt each turn) |
| Auto-flatten deep tool schemas | yes | no (DeepSeek drops args) |
| Retry with jittered backoff (429/503) | yes | no (custom callbacks) |
| Scavenge tool calls leaked into `<think>` | yes | no |
| Call-storm breaker on identical-arg repeats | yes | no |
| Live cache-hit / cost / vs-Claude panel | yes | no |
On the same τ-bench-lite workload — 8 multi-turn tool-use tasks × 3
repeats = 48 runs per side, live DeepSeek `deepseek-chat`, sole
variable prefix stability:
| metric | baseline (cache-hostile) | Reasonix | delta |
|---|---:|---:|---:|
| cache hit | 46.6% | **94.4%** | +47.7 pp |
| cost / task | $0.002599 | $0.001579 | **−39%** |
| pass rate | 96% (23/24) | **100% (24/24)** | — |
**Reproduce without spending an API credit:**
```bash
export DEEPSEEK_API_KEY=sk-... # wins over ~/.reasonix/config.json
export DEEPSEEK_BASE_URL=https://... # optional alternate endpoint
git clone https://github.com/esengine/reasonix.git && cd reasonix && npm install
npx reasonix replay benchmarks/tau-bench/transcripts/t01_address_happy.reasonix.r1.jsonl
npx reasonix diff \
benchmarks/tau-bench/transcripts/t01_address_happy.baseline.r1.jsonl \
benchmarks/tau-bench/transcripts/t01_address_happy.reasonix.r1.jsonl
```
Get a key (free credit on signup): <https://platform.deepseek.com/api_keys>
The committed JSONL transcripts carry per-turn `usage`, `cost`, and
`prefixHash`. Reasonix's prefix hash stays byte-stable across every
model call; baseline's churns on every turn. The cache delta is
*mechanically* attributable to log stability, not to a different
system prompt.
Re-run `npx reasonix setup` any time to add/remove MCP servers or switch
preset — your existing selections are pre-checked.
Full 48-run report:
[`benchmarks/tau-bench/report.md`](./benchmarks/tau-bench/report.md).
Reproduce with your own API key: `npx tsx
benchmarks/tau-bench/runner.ts --repeats 3`.
MCP reference runs (one single prefix hash across all 5 turns even
with two concurrent MCP subprocesses):
| server | turns | cache hit | cost | vs Claude |
|---|---:|---:|---:|---:|
| bundled demo (`add` / `echo` / `get_time`) | 2 | **96.6%** (turn 2) | $0.000254 | −94.0% |
| official `server-filesystem` | 5 | **96.7%** | $0.001235 | −97.0% |
| **both concurrently** | 5 | **81.1%** | $0.001852 | −95.9% |
---
## Non-goals
- Multi-agent orchestration (use LangGraph).
- RAG / vector stores (use LlamaIndex or do it yourself).
- Multi-provider abstraction (use LiteLLM).
- Web UI / SaaS.
- **Multi-agent orchestration / sub-agents** (use LangGraph).
- **Workflow DSL / DAG scheduler / parallel-branch engine** — skills
are prose; the model sequences via the normal tool-use loop.
Keeps single-loop + append-only + cache-first invariants intact.
- **Multi-provider abstraction** (use LiteLLM). Reasonix is
DeepSeek-only on purpose — every pillar (cache-first loop, R1
harvesting, tool-call repair) is tuned against DeepSeek-specific
behavior and economics. Coupling to one backend is the feature.
- **RAG / vector stores** (use LlamaIndex).
- **Web UI / SaaS.**
Reasonix does DeepSeek, deeply.
@@ -304,15 +765,13 @@ Reasonix does DeepSeek, deeply.
git clone https://github.com/esengine/reasonix.git
cd reasonix
npm install
npm run dev chat # run CLI from source via tsx
npm run dev code # run CLI from source via tsx
npm run build # tsup to dist/
npm test # vitest (279 tests)
npm test # vitest (1007 tests)
npm run lint # biome
npm run typecheck # tsc --noEmit
```
See [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) for internals.
---
## License
Binary file not shown.
+166 -62
View File
@@ -6,7 +6,11 @@ Reasonix is **opinionated, not general**. Every abstraction is justified by a
DeepSeek-specific behavior or economic property. If it's generic, we don't
ship it.
## The three pillars
The product north star: **coding agent that stays cheap enough to leave on**.
A tool that quietly burns $200/month on a background project is one nobody
uses. Every subsystem below is answerable to that goal.
## The four pillars
### Pillar 1 — Cache-First Loop
@@ -37,49 +41,29 @@ timestamps each turn — cache hit rate in practice: <20%.
into the log.
**Metric.** `prompt_cache_hit_tokens / (hit + miss)` exposed per-turn and
aggregated per-session. This is the user-visible proof of Pillar 1's value.
aggregated per-session. Visible in the TUI's top-bar cache cell.
### Pillar 2 — R1 Thought Harvesting *(v0.0.3, opt-in)*
### Pillar 2 — R1 Thought Harvesting *(opt-in)*
**Problem.** R1 emits extensive `reasoning_content`. DeepSeek's own docs
recommend *not* feeding it back to the next turn. Most frameworks display it
to the user and discard. The planning signal inside is lost.
**Problem.** R1 / V4-thinking emits extensive `reasoning_content`. DeepSeek's
own docs recommend *not* feeding it back to the next turn. Most frameworks
display it to the user and discard. The planning signal inside is lost.
**Solution.** A two-stage process:
```
R1 output → Harvester (V3, cheap) → TypedPlanState
├─ subgoals: string[]
├─ hypotheses: string[]
├─ uncertainties: string[]
└─ rejectedPaths: string[]
R1 output → Harvester (v4-flash, thinking off) → TypedPlanState
├─ subgoals: string[]
├─ hypotheses: string[]
├─ uncertainties: string[]
└─ rejectedPaths: string[]
```
The harvester is a cheap V3 call with a strict JSON schema. Output is
validated at runtime. The typed state is queryable by the orchestrator — e.g.
"if `uncertainties.length > 2`, trigger branch sampling."
The harvester is a cheap flash call with a strict JSON schema. Output is
validated at runtime. **Not enabled in any preset** (see Pillar 4) — the
additional round-trip rarely pays back, so it's `/harvest on` opt-in.
### Branch-and-Select *(v0.0.5, opt-in, builds on Pillar 2)*
**Why now.** DeepSeek is cheap enough that running N=3 R1 samples is still
cheaper than a single Claude call. What was research luxury (self-consistency
sampling) becomes a practical default.
**How.** When `--branch N` (or `{ branch: N }` in code) is passed:
1. The turn is forced non-streaming (N samples must complete before we can
compare).
2. `runBranches` fires N `client.chat` calls in parallel, spreading
temperatures across `[0, 1]` to diversify reasoning paths.
3. Each sample's `reasoning_content` is piped through Pillar 2's harvest.
4. The default selector picks the sample with the fewest `uncertainties`;
ties are broken by shorter answer length (Occam).
5. The loop emits a `branch_summary` alongside the winning `assistant_final`.
**Cost.** 3× R1 on a hard math problem ≈ \$0.02 — still dominates Claude on
cost/quality for agentic work.
### Pillar 3 — Tool-Call Repair *(v0.0.1 ships complete)*
### Pillar 3 — Tool-Call Repair
**Problem.** Empirical DeepSeek failure modes:
- Tool-call JSON emitted inside `<think>`, missing from the final message.
@@ -92,7 +76,6 @@ cost/quality for agentic work.
1. **`flatten`** — schemas with >10 leaf params or depth >2 are auto-detected
on `ToolRegistry.register()` and presented to the model in dot-notation
form. `dispatch()` re-nests the args before calling the user's `fn`.
Opt out with `new ToolRegistry({ autoFlatten: false })`.
2. **`scavenge`** — regex + JSON parser sweeps `reasoning_content` for any tool
call the model forgot to emit in `tool_calls`.
3. **`truncation`** — detect unbalanced JSON and repair by closing braces or
@@ -100,48 +83,169 @@ cost/quality for agentic work.
4. **`storm`** — identical `(tool, args)` tuple within a sliding window →
suppress the call, inject a reflection turn.
### Pillar 4 — Cost Control *(v0.6)*
**Problem.** Coding agents that default to the frontier model (v4-pro, ~12×
flash cost) and accumulate full tool results in context are $150-$250/month
for active users. Most turns don't need frontier reasoning; most sessions
re-pay for tool results that were only useful once.
**Solution.** Four complementary mechanisms, none of which require manual
tuning in the common case:
#### 4.1 Tiered defaults (flash-first)
The three presets now trade only **model tier** and **reasoning effort**:
| Preset | Model | Effort | Harvest | Branch | Cost |
|---|---|---|---|---|---:|
| `fast` | `v4-flash` | `high` | off | 1 | 1× |
| `smart` (default) | `v4-flash` | `max` | off | 1 | ~1.5× |
| `max` | `v4-pro` | `max` | off | 1 | ~12× |
**Branching and harvest are never in a preset.** Both multiply cost and
rarely pay back; `/branch N` and `/harvest on` are pure opt-ins. A user can
run for weeks without ever touching them.
All auxiliary calls — `forceSummaryAfterIterLimit`, subagent spawns,
truncation repair retries — hard-code `v4-flash + effort=high` regardless
of the user's preset. There's no reason to pay pro rates for "paraphrase
these tool results into prose" or for an `explore` subagent's grep chain.
#### 4.2 Turn-end auto-compaction
Every tool result in the log exceeding `TURN_END_RESULT_CAP_TOKENS` (3000)
is shrunk to that cap when a turn ends. The model had the full text for
the turn that read it; subsequent turns see a compact summary and can
re-read if needed. One extra `read_file` call is vastly cheaper than
dragging 12KB through every future prompt.
A proactive 40% context-ratio threshold runs the same shrink pre-emptively
inside long multi-iter turns before the 80% emergency threshold fires.
#### 4.3 `/pro` single-turn arming
Users who predict a hard task type `/pro`; the **next** turn runs on
`v4-pro`, then auto-disarms. No preset churn, no forgotten revert. Armed
state is visible as a yellow `⇧ pro armed` pill in the header.
#### 4.4 Failure-signal auto-escalation
The loop counts visible "flash is struggling" events per turn:
- `edit_file` / `write_file` SEARCH-not-found errors
- ToolCallRepair fires (scavenge / truncation-fix / storm-break)
Once the count hits `FAILURE_ESCALATION_THRESHOLD` (3), the **remainder of
the current turn** runs on `v4-pro`. Announced via a yellow warning row —
no silent cost surprises. Counter + escalation flag reset at every turn
start.
Header shows a red `⇧ pro escalated` pill while the turn is on pro.
#### Cost transparency
Per-turn and session cost are colored in the StatsPanel:
- `turn $0.003` — green <$0.05, yellow $0.05–0.20, red ≥$0.20
- `session $0.12` — same scale ×10
## Module layout
```
src/
├── client.ts # httpx-equivalent DeepSeek client (fetch + SSE)
├── loop.ts # Pillar 1: Cache-First Loop (async iterator)
├── harvest.ts # Pillar 2 stub (v0.0.1 surface only)
├── repair/
│ ├── index.ts # Pillar 3 pipeline
├── client.ts # DeepSeek client (fetch + SSE)
├── loop.ts # Pillar 1 + 4 — CacheFirstLoop
├── harvest.ts # Pillar 2 — flash-backed plan-state extraction
├── repair/ # Pillar 3 pipeline
│ ├── index.ts
│ ├── scavenge.ts
│ ├── flatten.ts
│ ├── truncation.ts
│ └── storm.ts
├── tools.ts # Tool registry + dispatch
├── memory.ts # Prefix / Log / Scratch primitives
├── telemetry.ts # Cost & cache-hit accounting
├── types.ts # Shared type definitions
├── index.ts # Library barrel export
├── prompt-fragments.ts # TUI_FORMATTING_RULES, NEGATIVE_CLAIM_RULE —
│ # reused by main + subagent + skill prompts
├── code/prompt.ts # reasonix code main system prompt
├── tools/ # Tool implementations
│ ├── filesystem.ts # read / list / search / edit / write
│ ├── shell.ts # run_command + run_background (JobRegistry)
│ ├── jobs.ts # background-process registry
│ ├── memory.ts # remember / forget / list user memories
│ ├── skills.ts # list + invoke SKILL.md playbooks
│ ├── subagent.ts # spawn_subagent — flash+high by default
│ ├── plan.ts # submit_plan (review gate)
│ └── web.ts # web_search, web_fetch
├── mcp/ # MCP client + bridge (stdio + SSE)
├── memory.ts # ImmutablePrefix / AppendOnlyLog / VolatileScratch
├── project-memory.ts # REASONIX.md loader
├── user-memory.ts # ~/.reasonix/memory/ store (project + global)
├── skills.ts # built-in explore + research skills
├── session.ts # JSONL session persistence
├── telemetry.ts # cost + cache-hit accounting + SessionSummary
├── tokenizer.ts # DeepSeek V3 tokenizer (ported)
├── usage.ts # ~/.reasonix/usage.jsonl roll-up
├── types.ts # ChatMessage, ToolCall, ToolSpec
├── index.ts # library barrel
└── cli/
├── index.ts # commander entry
├── commands/ # chat, run, stats, version
└── ui/ # Ink React components (App, StatsPanel, EventLog, PromptInput)
├── index.ts # commander entry
├── resolve.ts # config + CLI flag precedence
├── commands/ # chat, code, run, stats, sessions, ...
└── ui/
├── App.tsx # root Ink component (~1984 LOC, was 2931)
├── LiveRows.tsx # spinner rows (OngoingTool / Status / ...)
├── EventLog.tsx # Historical row rendering
├── StatsPanel.tsx # top bar + cost badges
├── PromptInput.tsx # cursor-aware multi-line input
├── PlanConfirm.tsx # submit_plan review modal
├── ShellConfirm.tsx # run_command approval modal
├── EditConfirm.tsx # per-edit review modal
├── markdown.tsx # Ink-native markdown renderer
├── edit-history.ts # EditHistoryEntry + formatters
├── useEditHistory.ts # /undo, /history, /show state machine
├── useCompletionPickers.ts # slash, @, slash-arg pickers
├── useSessionInfo.ts # balance + models + updates fetch
├── useSubagent.ts # subagent sink wiring
└── slash/ # /-command implementation
├── types.ts # SlashContext, SlashResult, ...
├── commands.ts # SLASH_COMMANDS data + parse + suggest
├── helpers.ts # git, memory, token formatters
├── dispatch.ts # registry + handleSlash lookup
└── handlers/ # per-topic: basic, mcp, memory,
# skill, admin, observability, edits,
# jobs, sessions, model (/pro lives here)
```
## Roadmap
Files kept small by design: the largest module under `cli/ui/` is 2K
lines (App.tsx), every handler under `slash/handlers/` is ≤200 lines,
every hook under `cli/ui/` is ≤310 lines. Adding a new slash command
means editing one handler file and one registry line.
- **v0.0.1** — Pillar 1 end-to-end, Pillar 3 complete, Ink TUI, τ-bench scaffold.
- **v0.0.2** — First-run key prompt, saved to `~/.reasonix/config.json`.
- **v0.0.3** — Pillar 2 MVP (opt-in harvest), retry layer, TextInput fix.
- **v0.0.4** — Schema flatten auto-applied in ToolRegistry (closes Pillar 3).
- **v0.0.5** — Self-consistency branching (`--branch N`) driven by Pillar 2
plan-state uncertainty count.
- **v0.0.6** — Named session persistence (`--session <name>`), JSONL log
stored under `~/.reasonix/sessions/`, restored into the append-only log
on resume.
## Design evolution
- **v0.0.x** — Pillar 1 end-to-end, Pillar 3 complete, Ink TUI scaffold.
- **v0.1** — τ-bench numbers published, streaming polish, transcript replay.
- **v0.2** — Self-consistency / branch-budget sampling driven by plan state.
- **v0.3** — MCP client, session persistence.
- **v0.3** — MCP client (stdio + SSE), session persistence.
- **v0.4.x** — `reasonix code` with SEARCH/REPLACE edits, review/auto
gate, background jobs, hooks.
- **v0.5.x** — V4 model support, skills, memory, subagents, actionable
error messages.
- **v0.6** *(current)* —
- **Pillar 4 cost control** (flash-first defaults, auto-compaction,
`/pro` one-shot, failure-triggered escalation, cost badges).
- `deepseek-chat` / `deepseek-reasoner` scheduled for deprecation —
all user-facing surfaces updated to `v4-flash` / `v4-pro`.
- `branch` + `harvest` removed from every preset; manual opt-in only.
- Shared prompt fragments (`TUI_FORMATTING_RULES`, `NEGATIVE_CLAIM_RULE`).
- UI refactor: App.tsx split into 6 hooks/components, slash.ts split
into 13 per-topic modules.
## Explicit non-goals
- Multi-agent orchestration.
- Multi-agent orchestration as a first-class concept (subagents are a
cost-reduction mechanism, not a coordination primitive).
- RAG / vector retrieval.
- Support for non-DeepSeek backends.
- Support for non-DeepSeek backends (an OpenAI-compatible shim would
work today via `--model` override, but is not tested).
- Web UI / SaaS.
- Automatic cost escalation without user-visible announcement. Every
pro-tier model call is surfaced; silent escalation was considered
and rejected.
+95
View File
@@ -0,0 +1,95 @@
<svg xmlns="http://www.w3.org/2000/svg" width="760" height="170" viewBox="0 0 760 170" role="img" aria-label="Reasonix — DeepSeek-native agent framework">
<title>Reasonix</title>
<defs>
<!-- Signature cyan → violet → fuchsia gradient used across the TUI wordmark
and the brand mark. Renders well on both GitHub dark and light bg. -->
<linearGradient id="rx-grad" x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0%" stop-color="#5eead4"/>
<stop offset="15%" stop-color="#67e8f9"/>
<stop offset="30%" stop-color="#7dd3fc"/>
<stop offset="45%" stop-color="#93c5fd"/>
<stop offset="60%" stop-color="#a5b4fc"/>
<stop offset="75%" stop-color="#c4b5fd"/>
<stop offset="90%" stop-color="#d8b4fe"/>
<stop offset="100%" stop-color="#f0abfc"/>
</linearGradient>
<linearGradient id="rx-grad-mark" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" stop-color="#5eead4"/>
<stop offset="50%" stop-color="#93c5fd"/>
<stop offset="100%" stop-color="#c4b5fd"/>
</linearGradient>
<filter id="glow" x="-50%" y="-50%" width="200%" height="200%">
<feGaussianBlur stdDeviation="3" result="blur"/>
<feMerge>
<feMergeNode in="blur"/>
<feMergeNode in="SourceGraphic"/>
</feMerge>
</filter>
</defs>
<!-- ◈ brand mark: concentric diamonds. Outer stroke pulses,
inner fill breathes, whole group rotates slowly. The rotation
is subtle (12s / full turn) so it feels like a heartbeat, not a
spinner. -->
<g transform="translate(90, 85)" filter="url(#glow)">
<g>
<animateTransform attributeName="transform" type="rotate"
from="0" to="360" dur="18s" repeatCount="indefinite"/>
<!-- Outer hollow diamond -->
<path d="M 0,-46 L 46,0 L 0,46 L -46,0 Z"
fill="none"
stroke="url(#rx-grad-mark)"
stroke-width="3.5"
stroke-linejoin="round">
<animate attributeName="stroke-width"
values="3.5;5.5;3.5"
dur="2.4s"
repeatCount="indefinite"/>
</path>
<!-- Middle hollow diamond -->
<path d="M 0,-26 L 26,0 L 0,26 L -26,0 Z"
fill="none"
stroke="url(#rx-grad-mark)"
stroke-width="2"
stroke-linejoin="round"
opacity="0.7">
<animate attributeName="opacity"
values="0.4;0.9;0.4"
dur="2.4s"
begin="0.8s"
repeatCount="indefinite"/>
</path>
<!-- Inner solid diamond -->
<path d="M 0,-11 L 11,0 L 0,11 L -11,0 Z"
fill="url(#rx-grad-mark)">
<animate attributeName="opacity"
values="0.75;1;0.75"
dur="2.4s"
repeatCount="indefinite"/>
</path>
</g>
</g>
<!-- REASONIX wordmark with shifting gradient. The x1 offset animates
so the gradient crawls left-to-right across the letters — a
slow rainbow sweep that gives the logo life without being noisy. -->
<text x="170" y="102"
font-family="ui-monospace, SFMono-Regular, 'Cascadia Code', Menlo, Consolas, 'DejaVu Sans Mono', monospace"
font-size="68"
font-weight="800"
fill="url(#rx-grad)"
letter-spacing="6">REASONIX
<animate attributeName="opacity"
values="0.9;1;0.9"
dur="3.2s"
repeatCount="indefinite"/>
</text>
<!-- Tagline sits just below the wordmark. Slate-500 reads well on
both GitHub dark and light themes (~4.5:1 contrast either way). -->
<text x="172" y="136"
font-family="ui-monospace, SFMono-Regular, 'Cascadia Code', Menlo, Consolas, 'DejaVu Sans Mono', monospace"
font-size="15"
fill="#64748b"
letter-spacing="0.5">DeepSeek-native agent framework · cache-first loop · Ink TUI</text>
</svg>

After

Width:  |  Height:  |  Size: 3.8 KiB

+3 -2
View File
@@ -1,7 +1,7 @@
{
"name": "reasonix",
"version": "0.4.11",
"description": "DeepSeek-native agent framework: cache-first loop, R1 thought harvesting, tool-call repair.",
"version": "0.6.0",
"description": "DeepSeek-native coding agent: cache-first loop, flash-first cost control, tool-call repair.",
"type": "module",
"bin": {
"reasonix": "dist/cli/index.js"
@@ -17,6 +17,7 @@
},
"files": [
"dist",
"data/deepseek-tokenizer.json.gz",
"README.md",
"LICENSE"
],
+34
View File
@@ -0,0 +1,34 @@
#!/usr/bin/env node
/**
* Regenerate `data/deepseek-tokenizer.json.gz` from an upstream
* `tokenizer.json` (as shipped in DeepSeek's deepseek_v3_tokenizer.zip).
*
* Why slim+gz: the full tokenizer.json is 7.5MB; we only need four
* fields (vocab, merges, pre_tokenizer, added_tokens). Strip + gzip
* drops the committed artifact to ~1.7MB with no loss of fidelity
* for encode-side token counting.
*
* Usage: `node --experimental-strip-types scripts/prepare-tokenizer.ts <path/to/tokenizer.json>`
* (or via `tsx` / `ts-node`.)
*/
import { readFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { gzipSync } from "node:zlib";
const src = process.argv[2];
if (!src) {
process.stderr.write("usage: prepare-tokenizer.ts <tokenizer.json>\n");
process.exit(2);
}
const raw = JSON.parse(readFileSync(src, "utf8"));
const slim = {
added_tokens: raw.added_tokens,
pre_tokenizer: raw.pre_tokenizer,
model: { type: raw.model.type, vocab: raw.model.vocab, merges: raw.model.merges },
};
const gz = gzipSync(Buffer.from(JSON.stringify(slim)), { level: 9 });
const outPath = join(process.cwd(), "data", "deepseek-tokenizer.json.gz");
writeFileSync(outPath, gz);
process.stdout.write(`wrote ${outPath} (${(gz.length / 1024).toFixed(1)} KB)\n`);
+192
View File
@@ -0,0 +1,192 @@
/**
* End-to-end smoke test for the memory layer. Runs against a temp
* homeDir so the developer's real ~/.reasonix/memory/ is never touched.
* Exercises: write → index regeneration → prefix assembly →
* recall → delete → REASONIX_MEMORY=off short-circuit.
*
* Run: npx tsx scripts/smoke-memory.mts
* Exit code 0 on success, 1 on any assertion failure.
*/
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { ToolRegistry } from "../src/tools.js";
import { registerMemoryTools } from "../src/tools/memory.js";
import {
MemoryStore,
applyMemoryStack,
applyUserMemory,
projectHash,
} from "../src/user-memory.js";
let failures = 0;
function check(label: string, cond: unknown, detail?: string) {
if (cond) {
process.stdout.write(` ✓ ${label}\n`);
} else {
failures++;
process.stdout.write(` ✗ ${label}${detail ? ` — ${detail}` : ""}\n`);
}
}
async function main() {
const home = mkdtempSync(join(tmpdir(), "reasonix-smoke-home-"));
const projectRoot = mkdtempSync(join(tmpdir(), "reasonix-smoke-proj-"));
process.stdout.write(`home: ${home}\nproject: ${projectRoot}\n\n`);
try {
// ── 1. MemoryStore write + index regeneration ────────────────────
process.stdout.write("1. MemoryStore write → index regen\n");
const store = new MemoryStore({ homeDir: home, projectRoot });
store.write({
name: "bun_build",
type: "project",
scope: "project",
description: "Build command on this machine is `bun run build`",
body: "On this machine, no npm — always `bun run build` / `bun run test`.",
});
store.write({
name: "tabs_not_spaces",
type: "user",
scope: "global",
description: "Use tabs for indentation across all projects",
body: "Rule.\n\n**Why:** muscle memory, editor config across machines.\n\n**How to apply:** always tabs.",
});
const hash = projectHash(projectRoot);
const projectFile = join(home, "memory", hash, "bun_build.md");
const globalFile = join(home, "memory", "global", "tabs_not_spaces.md");
check("project-scoped file landed in <hash>/ dir", existsSync(projectFile));
check("global-scoped file landed in global/ dir", existsSync(globalFile));
check("no cross-contamination project ⇒ global", !existsSync(join(home, "memory", "global", "bun_build.md")));
const projectIndex = readFileSync(join(home, "memory", hash, "MEMORY.md"), "utf8");
check("project MEMORY.md points at bun_build.md", projectIndex.includes("[bun_build](bun_build.md)"));
const globalIndex = readFileSync(join(home, "memory", "global", "MEMORY.md"), "utf8");
check("global MEMORY.md points at tabs_not_spaces.md", globalIndex.includes("[tabs_not_spaces](tabs_not_spaces.md)"));
const raw = readFileSync(projectFile, "utf8");
check("frontmatter has name/type/scope/created", /^---\nname: bun_build\n/.test(raw) && /type: project/.test(raw) && /scope: project/.test(raw) && /created: \d{4}-\d{2}-\d{2}/.test(raw));
// ── 2. Prefix assembly via applyMemoryStack (+ REASONIX.md) ────────
process.stdout.write("\n2. Prefix assembly (REASONIX.md + user memory)\n");
writeFileSync(join(projectRoot, "REASONIX.md"), "# Project notes\nPrefer explicit types over inference.\n", "utf8");
const BASE = "You are a test assistant.";
const withProjOnly = applyUserMemory(BASE, { homeDir: home, projectRoot });
check("applyUserMemory contains global block", withProjOnly.includes("# User memory — global"));
check("applyUserMemory contains project block", withProjOnly.includes("# User memory — this project"));
check("bun_build description present in prefix", withProjOnly.includes("bun run build"));
check("tabs_not_spaces description present in prefix", withProjOnly.includes("Use tabs for indentation"));
// Order: base → (REASONIX.md would go first via applyMemoryStack) → global → project
const ordered = applyUserMemory(BASE, { homeDir: home, projectRoot });
const iGlobalBlock = ordered.indexOf("# User memory — global");
const iProjBlock = ordered.indexOf("# User memory — this project");
check("global block precedes project block (stable for cache)", iGlobalBlock > 0 && iGlobalBlock < iProjBlock);
// Determinism — two calls with same state produce byte-identical prompts.
const a = applyUserMemory(BASE, { homeDir: home, projectRoot });
const b = applyUserMemory(BASE, { homeDir: home, projectRoot });
check("applyUserMemory is deterministic (byte-stable)", a === b);
// ── 3. The `remember` / `recall_memory` / `forget` tools ───────────
process.stdout.write("\n3. Tool dispatch (remember / recall / forget)\n");
const reg = new ToolRegistry();
registerMemoryTools(reg, { homeDir: home, projectRoot });
check("remember tool registered", reg.has("remember"));
check("forget tool registered", reg.has("forget"));
check("recall_memory tool registered", reg.has("recall_memory"));
check("recall_memory is readOnly (plan-mode safe)", reg.get("recall_memory")?.readOnly === true);
check("remember is NOT readOnly (plan-mode blocked)", reg.get("remember")?.readOnly !== true);
const remOut = await reg.dispatch("remember", {
type: "feedback",
scope: "global",
name: "prefers_short_replies",
description: "User wants terse answers, no trailing summaries",
content: "Default to terse. If the user wants detail they'll ask.",
});
check("remember returns a confirmation (not an error)", remOut.includes("REMEMBERED (global/prefers_short_replies)"), remOut);
const recallOut = await reg.dispatch("recall_memory", {
scope: "global",
name: "prefers_short_replies",
});
check("recall_memory returns the body", recallOut.includes("Default to terse"));
const forgetOut = await reg.dispatch("forget", {
scope: "global",
name: "prefers_short_replies",
});
check("forget returns a confirmation", forgetOut.includes("forgot (global/prefers_short_replies)"));
check("recall_memory after forget returns an error", (await reg.dispatch("recall_memory", { scope: "global", name: "prefers_short_replies" })).includes("error"));
// ── 4. Project scope refused when projectRoot is absent ────────────
process.stdout.write("\n4. Chat-mode (no projectRoot) refuses project scope\n");
const chatReg = new ToolRegistry();
registerMemoryTools(chatReg, { homeDir: home });
const projInChat = await chatReg.dispatch("remember", {
type: "project",
scope: "project",
name: "should_fail",
description: "d",
content: "c",
});
check("scope='project' in chat mode → error payload", projInChat.includes("error") && projInChat.includes("project"));
const globalInChat = await chatReg.dispatch("remember", {
type: "user",
scope: "global",
name: "global_from_chat",
description: "works across projects",
content: "body",
});
check("scope='global' in chat mode → writes successfully", globalInChat.includes("REMEMBERED (global/"));
// ── 5. REASONIX_MEMORY=off short-circuit ───────────────────────────
process.stdout.write("\n5. REASONIX_MEMORY=off opt-out\n");
process.env.REASONIX_MEMORY = "off";
try {
const silenced = applyUserMemory(BASE, { homeDir: home, projectRoot });
check("applyUserMemory returns BASE unchanged when off", silenced === BASE);
const fullStack = applyMemoryStack(BASE, projectRoot);
check("applyMemoryStack returns BASE unchanged when off (REASONIX.md also skipped)", fullStack === BASE);
} finally {
delete process.env.REASONIX_MEMORY;
}
// ── 6. Delete regeneration: MEMORY.md matches current file set ─────
process.stdout.write("\n6. Delete + index regeneration\n");
store.delete("global", "tabs_not_spaces");
store.delete("global", "global_from_chat");
const globalIdxAfter = join(home, "memory", "global", "MEMORY.md");
check("global MEMORY.md removed when last file deleted", !existsSync(globalIdxAfter));
const projectIdxStill = readFileSync(join(home, "memory", hash, "MEMORY.md"), "utf8");
check("project MEMORY.md untouched (different scope)", projectIdxStill.includes("bun_build"));
// ── 7. Name-sanitization boundary ──────────────────────────────────
process.stdout.write("\n7. Name sanitization (path-traversal refused)\n");
const badOut = await reg.dispatch("remember", {
type: "user",
scope: "global",
name: "../../etc/passwd",
description: "d",
content: "c",
});
check("remember refuses path-traversal name", badOut.includes("invalid memory name"));
const outsideFile = join(home, "etc", "passwd.md");
check("no file written outside the memory dir", !existsSync(outsideFile));
process.stdout.write(`\n${failures === 0 ? "✅ all smoke checks passed" : `❌ ${failures} failure(s)`}\n`);
} finally {
rmSync(home, { recursive: true, force: true });
rmSync(projectRoot, { recursive: true, force: true });
}
process.exit(failures === 0 ? 0 : 1);
}
main().catch((err) => {
console.error(err);
process.exit(1);
});
+397
View File
@@ -0,0 +1,397 @@
/**
* Expand `@path/to/file` mentions in a user prompt to inline file
* content.
*
* Why: most interactive coding sessions start with "look at X, then
* change Y". Typing `@src/loop.ts` reads faster and cheaper than
* "look at src/loop.ts (and the model fires read_file, and we pay for
* the round trip)" — the model sees the file content from turn 1
* instead of round-tripping a tool call for it.
*
* Shape: the user's text is kept verbatim. Expanded file contents are
* appended in a "Referenced files" block at the end, each wrapped in
* `<file path="...">...</file>` so the model can cite them back
* unambiguously.
*
* Safety: paths must resolve inside `rootDir` (no `..` escape, no
* absolute paths), must exist as a regular file, and must be under
* `maxBytes`. Missing / too-large / escaping paths get a short note
* appended instead of content so the user sees why it was skipped.
*/
import { type Dirent, existsSync, readFileSync, readdirSync, statSync } from "node:fs";
import { isAbsolute, join, relative, resolve } from "node:path";
/** Caps match tool-result dispatch truncation (0.5.2). */
export const DEFAULT_AT_MENTION_MAX_BYTES = 64 * 1024;
/**
* Default directory names skipped when listing files for the picker.
* Matches what most repos gitignore AND keeps the picker off the
* hottest bloat — `node_modules` alone can be 100k+ entries.
*/
export const DEFAULT_PICKER_IGNORE_DIRS: readonly string[] = [
"node_modules",
".git",
"dist",
"build",
".next",
"out",
"coverage",
".cache",
".vscode",
".idea",
"target",
".venv",
"venv",
"__pycache__",
];
export interface ListFilesOptions {
/** Cap the walk once we've collected this many entries. Default 500. */
maxResults?: number;
/** Directory names to skip entirely. Defaults to {@link DEFAULT_PICKER_IGNORE_DIRS}. */
ignoreDirs?: readonly string[];
}
/**
* Walk `root` recursively and return relative file paths (forward-slash
* separator, regardless of platform) for the `@` picker.
*
* Synchronous on purpose: this runs once at App mount (and on each turn
* so newly-created files show up) and blocks the render thread for a
* predictable ~10-50ms on a moderate repo. An async variant would need
* to coordinate with the Ink render loop; sync fits the rest of the
* TUI's single-turn-per-tick model cleanly.
*
* Skips:
* - directories in `ignoreDirs` (default: DEFAULT_PICKER_IGNORE_DIRS)
* - any directory whose name starts with `.` (covers `.git`,
* `.vscode`, dotfile vendors). Dotfile REGULAR FILES (`.env`,
* `.gitignore`, `.prettierrc`) are kept — users reference them.
* - entries the walker can't read (permission errors, broken links).
*/
export function listFilesSync(root: string, opts: ListFilesOptions = {}): string[] {
return listFilesWithStatsSync(root, opts).map((e) => e.path);
}
export interface FileWithStats {
/** Relative path with forward-slash separator. */
path: string;
/** Modification time (Date.getTime() / ms since epoch). 0 when stat failed. */
mtimeMs: number;
}
/**
* Same walk as {@link listFilesSync} but also statS each file for
* modification time. Used by the `@` picker to surface recently-
* edited files first — matches VS Code Quick Open / similar UX.
*
* Stat failures don't throw: the entry is kept with `mtimeMs: 0` so
* it still appears in the picker (just sinks to the bottom of the
* recency sort).
*/
export function listFilesWithStatsSync(root: string, opts: ListFilesOptions = {}): FileWithStats[] {
const maxResults = Math.max(1, opts.maxResults ?? 500);
const ignore = new Set(opts.ignoreDirs ?? DEFAULT_PICKER_IGNORE_DIRS);
const rootAbs = resolve(root);
const out: FileWithStats[] = [];
const walk = (dirAbs: string, dirRel: string) => {
if (out.length >= maxResults) return;
let entries: Dirent[];
try {
entries = readdirSync(dirAbs, { withFileTypes: true });
} catch {
return;
}
entries.sort((a, b) => a.name.localeCompare(b.name));
for (const ent of entries) {
if (out.length >= maxResults) return;
const relPath = dirRel ? `${dirRel}/${ent.name}` : ent.name;
if (ent.isDirectory()) {
if (ent.name.startsWith(".") || ignore.has(ent.name)) continue;
walk(join(dirAbs, ent.name), relPath);
} else if (ent.isFile()) {
let mtimeMs = 0;
try {
mtimeMs = statSync(join(dirAbs, ent.name)).mtimeMs;
} catch {
/* stat failed (permission / EAGAIN) — keep the entry with mtime=0 */
}
out.push({ path: relPath, mtimeMs });
}
}
};
walk(rootAbs, "");
return out;
}
/**
* Prefix pattern used by the `@` picker to detect an IN-PROGRESS
* mention at the END of the input buffer. Captures the partial path
* (which may be empty — just `@`) so the picker can use it as a
* substring filter.
*
* Distinct from {@link AT_MENTION_PATTERN} (which finds completed
* mentions anywhere in the text for expansion-at-submit). This one
* fires on the trailing token only, anchored at end-of-input.
*/
export const AT_PICKER_PREFIX = /(?:^|\s)@([a-zA-Z0-9_./\\-]*)$/;
/**
* Return the picker state for a given input buffer: the partial query
* (may be empty string — just `@`) and the buffer offset of the `@`
* character. `null` when the buffer doesn't end in a mention-in-
* progress.
*/
export function detectAtPicker(input: string): { query: string; atOffset: number } | null {
const m = AT_PICKER_PREFIX.exec(input);
if (!m) return null;
const query = m[1] ?? "";
// `m.index` is the offset of the capture group's SURROUNDING match —
// which starts at either ^ or the preceding whitespace. The `@`
// itself is at `end-of-input - query.length - 1`.
const atOffset = input.length - query.length - 1;
return { query, atOffset };
}
/** A candidate accepted by the picker ranker — either a bare path or a path with mtime. */
export type PickerCandidate = string | FileWithStats;
export interface RankPickerOptions {
/** Upper bound on returned entries. Default 40. */
limit?: number;
/**
* Paths the user or model has touched recently (via tool calls like
* `read_file` / `edit_file`). Matching paths get a recency boost so
* the picker surfaces "stuff I just looked at" near the top.
*/
recentlyUsed?: readonly string[];
}
/**
* Filter and rank candidate files against the picker's partial query.
*
* Empty query:
* - Sort by "recently used" bucket first (if provided), then mtime
* descending (newer first), then path alpha.
* - Pure-string input (no mtime data) falls back to alpha since
* recency info isn't available.
*
* Non-empty query:
* - Case-insensitive substring match, with a basename-prefix boost
* so `lo` floats `loop.ts`-shaped paths to the top.
* - Ties broken first by recently-used membership, then mtime.
*
* Back-compat: passes `string[]` through the same logic (mtime = 0,
* recently-used still honored).
*/
export function rankPickerCandidates(
files: readonly PickerCandidate[],
query: string,
limitOrOpts?: number | RankPickerOptions,
): string[] {
const opts: RankPickerOptions =
typeof limitOrOpts === "number" ? { limit: limitOrOpts } : (limitOrOpts ?? {});
const limit = opts.limit ?? 40;
const recent = new Set(opts.recentlyUsed ?? []);
const entries: FileWithStats[] = files.map((f) =>
typeof f === "string" ? { path: f, mtimeMs: 0 } : f,
);
if (!query) {
// Only re-sort when we actually have signal to sort by. If input
// is bare strings (mtime = 0 everywhere) AND there's no recent-
// used list, preserve input order so callers keep their existing
// layout. Passing FileWithStats or a non-empty recentlyUsed opts
// you into mtime+recency ranking.
const anyMtime = entries.some((e) => e.mtimeMs > 0);
if (!anyMtime && recent.size === 0) {
return entries.slice(0, limit).map((e) => e.path);
}
const sorted = [...entries].sort((a, b) => {
const aRecent = recent.has(a.path) ? 1 : 0;
const bRecent = recent.has(b.path) ? 1 : 0;
if (aRecent !== bRecent) return bRecent - aRecent;
if (a.mtimeMs !== b.mtimeMs) return b.mtimeMs - a.mtimeMs;
return a.path.localeCompare(b.path);
});
return sorted.slice(0, limit).map((e) => e.path);
}
const needle = query.toLowerCase();
const scored: Array<{ path: string; score: number; mtimeMs: number; recent: boolean }> = [];
for (const e of entries) {
const lower = e.path.toLowerCase();
const hit = lower.indexOf(needle);
if (hit < 0) continue;
const slash = lower.lastIndexOf("/");
const base = slash >= 0 ? lower.slice(slash + 1) : lower;
let score = 2;
if (base.startsWith(needle)) score = 0;
else if (lower.startsWith(needle)) score = 1;
scored.push({
path: e.path,
score: score * 10_000 + hit,
mtimeMs: e.mtimeMs,
recent: recent.has(e.path),
});
}
scored.sort((a, b) => {
if (a.score !== b.score) return a.score - b.score;
// Tie-break: recently-used, then mtime (newer first).
if (a.recent !== b.recent) return a.recent ? -1 : 1;
return b.mtimeMs - a.mtimeMs;
});
return scored.slice(0, limit).map((s) => s.path);
}
/**
* Matches `@` at a word boundary (start-of-string or preceded by
* whitespace) followed by a path-like token. Deliberately rejects `@`
* embedded in longer words (email addresses, mentions on social sites)
* by requiring the word boundary.
*
* Path charset keeps it to the characters that appear in real repo
* paths — letters, digits, `_` `-` `.` `/` `\`. Trailing `.` (e.g.
* `@foo.ts.`) is stripped before lookup so a sentence-terminating
* period doesn't break the mention.
*/
export const AT_MENTION_PATTERN = /(?<=^|\s)@([a-zA-Z0-9_./\\-]+)/g;
export interface AtMentionExpansion {
/** The raw `@path` token as it appeared in the text. */
token: string;
/** The relative path, as resolved against rootDir. */
path: string;
/** True if the content was inlined. False = skipped (reason in `skip`). */
ok: boolean;
/** Bytes read (only for ok=true). */
bytes?: number;
/** Why the mention was skipped. Set when ok=false. */
skip?: "missing" | "not-file" | "too-large" | "escape" | "read-error";
}
export interface AtMentionOptions {
/** Max file size in bytes before a mention is skipped. */
maxBytes?: number;
/**
* Optional file-system overrides for tests. Real callers omit these;
* the helper falls through to `node:fs`.
*/
fs?: {
exists: (path: string) => boolean;
isFile: (path: string) => boolean;
size: (path: string) => number;
read: (path: string) => string;
};
}
/**
* Expand `@path` mentions in `text`. Returns the (possibly augmented)
* text plus a per-mention report so the caller can surface expansions
* in the UI.
*/
export function expandAtMentions(
text: string,
rootDir: string,
opts: AtMentionOptions = {},
): { text: string; expansions: AtMentionExpansion[] } {
const maxBytes = opts.maxBytes ?? DEFAULT_AT_MENTION_MAX_BYTES;
const fs = opts.fs ?? defaultFs;
const root = resolve(rootDir);
// De-dupe by token so `@file.ts` referenced twice inlines once.
const seen = new Map<string, AtMentionExpansion>();
const expansions: AtMentionExpansion[] = [];
for (const match of text.matchAll(AT_MENTION_PATTERN)) {
const rawPath = match[1] ?? "";
// Strip trailing dot (sentence terminator): `@foo.ts.` → `@foo.ts`.
// Keep internal dots intact.
const cleaned = rawPath.replace(/\.+$/, "");
if (!cleaned) continue;
const token = `@${cleaned}`;
if (seen.has(token)) continue;
const expansion = resolveMention(cleaned, root, maxBytes, fs);
seen.set(token, expansion);
expansions.push(expansion);
}
if (expansions.length === 0) return { text, expansions };
// Build the trailing "Referenced files" block. Keep successful
// inlines and skipped ones (with their reason) so the model sees
// both what's here and what's missing.
const blocks: string[] = [];
for (const ex of expansions) {
if (ex.ok) {
const content = readSafe(root, ex.path, fs);
blocks.push(`<file path="${ex.path}">\n${content}\n</file>`);
} else {
blocks.push(`<file path="${ex.path}" skipped="${ex.skip}" />`);
}
}
const augmented = `${text}\n\n[Referenced files]\n${blocks.join("\n\n")}`;
return { text: augmented, expansions };
}
function resolveMention(
rawPath: string,
root: string,
maxBytes: number,
fs: NonNullable<AtMentionOptions["fs"]>,
): AtMentionExpansion {
// Reject absolute paths — `@/etc/passwd` should not inline.
if (isAbsolute(rawPath)) {
return { token: `@${rawPath}`, path: rawPath, ok: false, skip: "escape" };
}
const resolved = resolve(root, rawPath);
// Sandbox escape: after resolution the path must still be inside root.
const rel = relative(root, resolved);
if (rel.startsWith("..") || isAbsolute(rel)) {
return { token: `@${rawPath}`, path: rawPath, ok: false, skip: "escape" };
}
if (!fs.exists(resolved)) {
return { token: `@${rawPath}`, path: rawPath, ok: false, skip: "missing" };
}
if (!fs.isFile(resolved)) {
return { token: `@${rawPath}`, path: rawPath, ok: false, skip: "not-file" };
}
const size = fs.size(resolved);
if (size > maxBytes) {
return { token: `@${rawPath}`, path: rawPath, ok: false, skip: "too-large", bytes: size };
}
return { token: `@${rawPath}`, path: rawPath, ok: true, bytes: size };
}
function readSafe(root: string, rawPath: string, fs: NonNullable<AtMentionOptions["fs"]>): string {
const resolved = resolve(root, rawPath);
try {
return fs.read(resolved);
} catch {
return "(read failed)";
}
}
const defaultFs: NonNullable<AtMentionOptions["fs"]> = {
exists: (p) => existsSync(p),
isFile: (p) => {
try {
return statSync(p).isFile();
} catch {
return false;
}
},
size: (p) => {
try {
return statSync(p).size;
} catch {
return 0;
}
},
read: (p) => readFileSync(p, "utf8"),
};
+92 -4
View File
@@ -1,6 +1,7 @@
import { existsSync, statSync } from "node:fs";
import { render } from "ink";
import React, { useState } from "react";
import { loadApiKey } from "../../config.js";
import { loadApiKey, searchEnabled } from "../../config.js";
import { loadDotenv } from "../../env.js";
import { McpClient } from "../../mcp/client.js";
import { type InspectionReport, inspectMcpServer } from "../../mcp/inspect.js";
@@ -8,8 +9,16 @@ import { bridgeMcpTools } from "../../mcp/registry.js";
import { parseMcpSpec } from "../../mcp/spec.js";
import { SseTransport } from "../../mcp/sse.js";
import { type McpTransport, StdioTransport } from "../../mcp/stdio.js";
import {
loadSessionMessages,
rewriteSession,
sessionPath as sessionPathOf,
} from "../../session.js";
import { ToolRegistry } from "../../tools.js";
import { registerMemoryTools } from "../../tools/memory.js";
import { registerWebTools } from "../../tools/web.js";
import { App } from "../ui/App.js";
import { SessionPicker } from "../ui/SessionPicker.js";
import { Setup } from "../ui/Setup.js";
import type { McpServerSummary } from "../ui/slash.js";
@@ -42,7 +51,11 @@ export interface ChatOptions {
* Enable SEARCH/REPLACE edit-block processing after each assistant turn.
* Set by `reasonix code`; plain `reasonix chat` leaves this off.
*/
codeMode?: { rootDir: string };
codeMode?: { rootDir: string; jobs?: import("../../tools/jobs.js").JobRegistry };
/** Skip the session picker — assume "Resume" (backwards-compatible auto-continue). */
forceResume?: boolean;
/** Skip the session picker — assume "New" (wipe the session file and start fresh). */
forceNew?: boolean;
}
interface RootProps extends ChatOptions {
@@ -58,10 +71,24 @@ interface RootProps extends ChatOptions {
* React reconciliation (no effect-timing surprises).
*/
progressSink: { current: ((info: ProgressInfo) => void) | null };
/** Present when the session has prior messages; drives the picker. */
sessionPreview?: { messageCount: number; lastActive: Date };
}
function Root({ initialKey, tools, mcpSpecs, mcpServers, progressSink, ...appProps }: RootProps) {
function Root({
initialKey,
tools,
mcpSpecs,
mcpServers,
progressSink,
sessionPreview,
...appProps
}: RootProps) {
const [key, setKey] = useState<string | undefined>(initialKey);
// `null` once the picker is resolved (or was never needed). Starts as
// the preview so we can render the picker once before mounting App.
const [pending, setPending] = useState<typeof sessionPreview>(sessionPreview);
if (!key) {
return (
<Setup
@@ -73,6 +100,26 @@ function Root({ initialKey, tools, mcpSpecs, mcpServers, progressSink, ...appPro
);
}
process.env.DEEPSEEK_API_KEY = key;
if (pending && appProps.session) {
return (
<SessionPicker
sessionName={appProps.session}
messageCount={pending.messageCount}
lastActive={pending.lastActive}
onChoose={(choice) => {
if (choice === "new" || choice === "delete") {
// Wipe the session file. "new" and "delete" do the same thing
// at this step — the distinction is only in the picker's
// wording. A future enhancement could archive on "new".
rewriteSession(appProps.session!, []);
}
setPending(undefined);
}}
/>
);
}
return (
<App
model={appProps.model}
@@ -164,6 +211,7 @@ export async function chatCommand(opts: ChatOptions): Promise<void> {
spec: raw,
toolCount: bridge.registeredNames.length,
report,
client: mcp,
});
} catch (err) {
// Per-server failure is non-fatal: one broken server shouldn't
@@ -189,6 +237,43 @@ export async function chatCommand(opts: ChatOptions): Promise<void> {
}
const mcpSpecs = successfulSpecs;
// Register web search/fetch tools unless explicitly disabled. DDG
// backs them with no key required; the model invokes them whenever
// a question needs info fresher than its training data.
if (searchEnabled()) {
if (!tools) tools = new ToolRegistry();
registerWebTools(tools);
}
// Memory tools — available in every session, not just code mode.
// Chat-mode callers get global scope only; project scope requires
// the seedTools path from `reasonix code` (which registers its own
// MemoryStore bound to rootDir before chatCommand runs).
// `run_skill` is registered later in App.tsx (where the client
// exists) so it can wire the subagent runner for runAs:subagent
// skills.
if (!opts.seedTools) {
if (!tools) tools = new ToolRegistry();
registerMemoryTools(tools, {});
}
// Decide whether to show the session picker. It's gated on: session
// persistence is on, the session file already has prior messages, and
// the caller didn't pre-commit to one of the choices via --resume /
// --new flags. `--new` wipes the file now (before the loop opens),
// so the App mounts against a fresh log.
let sessionPreview: { messageCount: number; lastActive: Date } | undefined;
if (opts.session && !opts.forceResume && !opts.forceNew) {
const prior = loadSessionMessages(opts.session);
if (prior.length > 0) {
const p = sessionPathOf(opts.session);
const mtime = existsSync(p) ? statSync(p).mtime : new Date();
sessionPreview = { messageCount: prior.length, lastActive: mtime };
}
} else if (opts.session && opts.forceNew) {
rewriteSession(opts.session, []);
}
const { waitUntilExit } = render(
<Root
initialKey={initialKey}
@@ -196,9 +281,12 @@ export async function chatCommand(opts: ChatOptions): Promise<void> {
mcpSpecs={mcpSpecs}
mcpServers={mcpServers}
progressSink={progressSink}
sessionPreview={sessionPreview}
{...opts}
/>,
{ exitOnCtrlC: true },
// patchConsole:false — we never log to console during the TUI, and the
// patch is a known redraw-glitch source on winpty/MINTTY terminals.
{ exitOnCtrlC: true, patchConsole: false },
);
try {
await waitUntilExit();
+65 -4
View File
@@ -19,9 +19,14 @@
*/
import { basename, resolve } from "node:path";
import { loadProjectShellAllowed } from "../../config.js";
import { sanitizeName } from "../../session.js";
import { ToolRegistry } from "../../tools.js";
import { registerFilesystemTools } from "../../tools/filesystem.js";
import { JobRegistry } from "../../tools/jobs.js";
import { registerMemoryTools } from "../../tools/memory.js";
import { registerPlanTool } from "../../tools/plan.js";
import { registerShellTools } from "../../tools/shell.js";
import { chatCommand } from "./chat.js";
export interface CodeOptions {
@@ -33,6 +38,19 @@ export interface CodeOptions {
noSession?: boolean;
/** Transcript file for replay/diff. */
transcript?: string;
/** Skip the session picker — always resume prior messages. */
forceResume?: boolean;
/** Skip the session picker — always wipe prior messages and start fresh. */
forceNew?: boolean;
/**
* Opt into Pillar 2 harvesting (extracts a typed plan state from R1
* reasoning via an extra V3 call). Default OFF in code mode — the
* displayed subgoals/hypotheses/rejectedPaths have no programmatic
* consumer, only `uncertainties.length` feeds branching, and the
* extra V3 call adds ~10-15% per-turn cost. Users who want the
* reasoning surfaced explicitly can pass `--harvest`.
*/
harvest?: boolean;
}
export async function codeCommand(opts: CodeOptions = {}): Promise<void> {
@@ -49,18 +67,61 @@ export async function codeCommand(opts: CodeOptions = {}): Promise<void> {
// triggered R1's DSML hallucinations all through 0.4.x.
const tools = new ToolRegistry();
registerFilesystemTools(tools, { rootDir });
// Background-process registry shared between the shell tools and the
// TUI's /jobs + /kill slashes + exit cleanup. One per `reasonix code`
// run — orphan prevention on SIGINT / process exit kills everything
// it owns, so dev servers don't outlive the Reasonix process.
const jobs = new JobRegistry();
registerShellTools(tools, {
rootDir,
// Per-project "always allow" list persisted from prior ShellConfirm
// choices; merged on top of the built-in allowlist in shell.ts.
// GETTER form — re-read every dispatch so a prefix the user adds
// via ShellConfirm mid-session takes effect on the next shell call
// instead of waiting for `/new` or a relaunch.
extraAllowed: () => loadProjectShellAllowed(rootDir),
jobs,
});
// `submit_plan` is always in the spec list so the prefix cache stays
// stable across plan-mode toggles (Pillar 1). The tool itself is a
// no-op outside plan mode and throws `PlanProposedError` when the
// user has `/plan`-enabled the session.
registerPlanTool(tools);
// `remember` / `forget` / `recall_memory` — cross-session user memory.
// Project scope hashes off rootDir so switching projects gets a fresh
// per-project memory store; the global scope is shared across runs.
registerMemoryTools(tools, { projectRoot: rootDir });
// `run_skill` is intentionally NOT registered here — App.tsx wires it
// up with the subagent runner attached, so `runAs: subagent` skills
// can spawn isolated child loops. Doing it here would mean the App's
// re-registration would shadow the no-runner version, which works
// (last write wins) but obscures the wiring.
process.stderr.write(
`▸ reasonix code: rooted at ${rootDir}, session "${session ?? "(ephemeral)"}" · ${tools.size} native fs tool(s)\n`,
`▸ reasonix code: rooted at ${rootDir}, session "${session ?? "(ephemeral)"}" · ${tools.size} native tool(s)\n`,
);
// Belt-and-suspenders cleanup: even though spawn(detached:false)
// should tie child processes to the parent's lifetime, Windows cmd.exe
// wrappers occasionally leak. Kill everything on both clean and
// signal-driven exits. 'exit' fires too late for async I/O but is our
// only guaranteed last word; the signal handlers do the heavy lifting.
const sigShutdown = () => {
void jobs.shutdown();
};
process.once("SIGINT", sigShutdown);
process.once("SIGTERM", sigShutdown);
process.once("exit", sigShutdown);
await chatCommand({
model: opts.model ?? "deepseek-reasoner",
harvest: true, // smart preset's harvest setting, always on for code
model: opts.model ?? "deepseek-v4-flash",
harvest: opts.harvest ?? false,
system: codeSystemPrompt(rootDir),
transcript: opts.transcript,
session,
seedTools: tools,
codeMode: { rootDir },
codeMode: { rootDir, jobs },
forceResume: opts.forceResume,
forceNew: opts.forceNew,
});
}
+1
View File
@@ -51,6 +51,7 @@ export async function diffCommand(opts: DiffOptions): Promise<void> {
if (wantTui) {
const { waitUntilExit } = render(React.createElement(DiffApp, { report }), {
exitOnCtrlC: true,
patchConsole: false,
});
await waitUntilExit();
return;
+1
View File
@@ -31,6 +31,7 @@ export async function replayCommand(opts: ReplayOptions): Promise<void> {
const pages = groupRecordsByTurn(parsed.records);
const { waitUntilExit } = render(React.createElement(ReplayApp, { meta: parsed.meta, pages }), {
exitOnCtrlC: true,
patchConsole: false,
});
await waitUntilExit();
}
+7
View File
@@ -11,6 +11,7 @@ import { SseTransport } from "../../mcp/sse.js";
import { type McpTransport, StdioTransport } from "../../mcp/stdio.js";
import { ToolRegistry } from "../../tools.js";
import { openTranscriptFile, recordFromLoopEvent, writeRecord } from "../../transcript.js";
import { appendUsage } from "../../usage.js";
export interface RunOptions {
task: string;
@@ -148,6 +149,12 @@ export async function runCommand(opts: RunOptions): Promise<void> {
if (ev.role === "tool") process.stdout.write(`\n[tool ${ev.toolName}] ${ev.content}\n`);
if (ev.role === "error") process.stderr.write(`\n[error] ${ev.error}\n`);
if (ev.role === "done") process.stdout.write("\n");
if (ev.role === "assistant_final" && ev.stats?.usage) {
// `reasonix run` is often used in CI / scripting — we want
// those turns to show up in `reasonix stats` too so the
// dashboard reflects all DeepSeek spend, not just TUI sessions.
appendUsage({ session: null, model: ev.stats.model, usage: ev.stats.usage });
}
// Persist every non-streaming event — deltas would flood the file and
// aren't useful for replay (replay renders final content, not keystrokes).
if (transcriptStream && ev.role !== "assistant_delta") {
+1 -1
View File
@@ -39,7 +39,7 @@ export async function setupCommand(_opts: SetupOptions = {}): Promise<void> {
unmount();
}}
/>,
{ exitOnCtrlC: true },
{ exitOnCtrlC: true, patchConsole: false },
);
await waitUntilExit();
}
+163 -5
View File
@@ -1,15 +1,60 @@
/**
* `reasonix stats` — two modes, decided by whether the user passed
* a transcript path.
*
* - `reasonix stats` → cross-session usage dashboard
* (reads `~/.reasonix/usage.jsonl`)
* - `reasonix stats <path>` → summary of a single JSONL transcript
* (original v0.1 behavior, kept so
* existing scripts don't break)
*
* The dashboard is the new story: for every turn `reasonix chat|code|run`
* has ever executed on this machine, we aggregate tokens + cost + the
* equivalent Claude spend, and print rolling-window totals (today /
* week / month / all-time). The savings column is the Pillar 1 pitch
* made concrete — "you paid $X; Claude would have charged $Y, a N%
* reduction."
*/
import { existsSync, readFileSync } from "node:fs";
import {
type UsageAggregate,
type UsageBucket,
aggregateUsage,
bucketCacheHitRatio,
bucketSavingsFraction,
defaultUsageLogPath,
formatLogSize,
readUsageLog,
} from "../../usage.js";
export interface StatsOptions {
transcript: string;
/** Optional transcript path. Absent → dashboard mode. */
transcript?: string;
/** Override usage log location (tests). */
logPath?: string;
/** Inject a fixed timestamp (tests) so rolling windows are deterministic. */
now?: number;
}
export function statsCommand(opts: StatsOptions): void {
if (!existsSync(opts.transcript)) {
console.error(`no such transcript: ${opts.transcript}`);
if (opts.transcript) {
transcriptSummary(opts.transcript);
return;
}
dashboard(opts);
}
// ---------------------------------------------------------------------
// Transcript summary — legacy v0.1 behavior, preserved verbatim.
// ---------------------------------------------------------------------
function transcriptSummary(path: string): void {
if (!existsSync(path)) {
console.error(`no such transcript: ${path}`);
process.exit(1);
}
const lines = readFileSync(opts.transcript, "utf8").split(/\r?\n/).filter(Boolean);
const lines = readFileSync(path, "utf8").split(/\r?\n/).filter(Boolean);
let assistantTurns = 0;
let toolCalls = 0;
let lastTurn = 0;
@@ -23,8 +68,121 @@ export function statsCommand(opts: StatsOptions): void {
/* skip */
}
}
console.log(`transcript: ${opts.transcript}`);
console.log(`transcript: ${path}`);
console.log(`assistant turns: ${assistantTurns}`);
console.log(`tool invocations: ${toolCalls}`);
console.log(`last turn index: ${lastTurn}`);
}
// ---------------------------------------------------------------------
// Dashboard — aggregates ~/.reasonix/usage.jsonl.
// ---------------------------------------------------------------------
function dashboard(opts: StatsOptions): void {
const path = opts.logPath ?? defaultUsageLogPath();
const records = readUsageLog(path);
if (records.length === 0) {
console.log("no usage data yet.");
console.log("");
console.log(` ${path}`);
console.log("");
console.log("run `reasonix chat`, `reasonix code`, or `reasonix run <task>` — every turn");
console.log("appends one line to the log and `reasonix stats` will roll it up.");
return;
}
const agg = aggregateUsage(records, { now: opts.now });
console.log(renderDashboard(agg, path));
}
/** Pure renderer — pulled out so tests can assert on the string directly. */
export function renderDashboard(agg: UsageAggregate, logPath: string): string {
const lines: string[] = [];
const size = formatLogSize(logPath);
lines.push(`Reasonix usage — ${logPath}${size ? ` (${size})` : ""}`);
lines.push("");
lines.push(header());
lines.push(divider());
for (const b of agg.buckets) {
lines.push(bucketRow(b));
}
lines.push("");
// Model + session breakdown — both trim to top 3 so a user with 20
// sessions doesn't drown the table.
if (agg.byModel.length > 0) {
const totalTurns = agg.buckets[agg.buckets.length - 1]?.turns ?? 0;
const top = agg.byModel[0];
if (top && totalTurns > 0) {
const pct = ((top.turns / totalTurns) * 100).toFixed(0);
lines.push(`most used model: ${top.model} (${pct}% of turns)`);
}
}
if (agg.bySession.length > 0) {
const top = agg.bySession[0];
if (top) lines.push(`top session: ${top.session} (${top.turns} turns)`);
}
if (agg.firstSeen) {
lines.push(`tracked since: ${new Date(agg.firstSeen).toISOString().slice(0, 10)}`);
}
if (agg.subagents) {
lines.push("");
lines.push(renderSubagentSection(agg.subagents));
}
return lines.join("\n");
}
function renderSubagentSection(sub: NonNullable<UsageAggregate["subagents"]>): string {
const lines: string[] = [];
const seconds = (sub.totalDurationMs / 1000).toFixed(1);
lines.push(
`subagent activity: ${sub.total} run(s) · $${sub.costUsd.toFixed(6)} · ${seconds}s total`,
);
// Show at most 5 skills so the section never dwarfs the main table.
const top = sub.bySkill.slice(0, 5);
for (const s of top) {
const sec = (s.durationMs / 1000).toFixed(1);
lines.push(
` ${pad(s.skillName, 18)} ${pad(`${s.count}`, 4, "right")} $${s.costUsd.toFixed(6)} ${sec}s`,
);
}
if (sub.bySkill.length > top.length) {
lines.push(` (+${sub.bySkill.length - top.length} more)`);
}
return lines.join("\n");
}
function header(): string {
// Fixed column widths so alignment works in any TTY.
return [
pad("", 10),
pad("turns", 8, "right"),
pad("cache hit", 10, "right"),
pad("cost (USD)", 14, "right"),
pad("vs Claude", 14, "right"),
pad("saved", 10, "right"),
].join(" ");
}
function divider(): string {
return "-".repeat(70);
}
function bucketRow(b: UsageBucket): string {
const hit = bucketCacheHitRatio(b);
const savings = bucketSavingsFraction(b);
return [
pad(b.label, 10),
pad(b.turns.toString(), 8, "right"),
pad(b.turns > 0 ? `${(hit * 100).toFixed(1)}%` : "—", 10, "right"),
pad(b.turns > 0 ? `$${b.costUsd.toFixed(6)}` : "—", 14, "right"),
pad(b.turns > 0 ? `$${b.claudeEquivUsd.toFixed(4)}` : "—", 14, "right"),
pad(b.turns > 0 && savings > 0 ? `${(savings * 100).toFixed(1)}%` : "—", 10, "right"),
].join(" ");
}
function pad(s: string, width: number, align: "left" | "right" = "left"): string {
if (s.length >= width) return s;
const fill = " ".repeat(width - s.length);
return align === "right" ? `${fill}${s}` : `${s}${fill}`;
}
+143
View File
@@ -0,0 +1,143 @@
/**
* `reasonix update` — self-upgrade command.
*
* Talks to the npm registry, compares against the running version,
* and either runs `npm install -g reasonix@latest` (global install)
* or advises how to refresh the npx cache (ephemeral install).
*
* The decision logic is factored into `planUpdate()` so it can be
* unit-tested without spawning child processes or hitting the
* network. `updateCommand()` is the thin CLI wrapper that calls
* `getLatestVersion`, passes the result into `planUpdate`, and
* executes any suggested command.
*/
import { spawn } from "node:child_process";
import { VERSION, compareVersions, getLatestVersion, isNpxInstall } from "../../version.js";
export type UpdateAction = "up-to-date" | "newer-local" | "npx-hint" | "run-npm-install";
export interface UpdatePlan {
action: UpdateAction;
/** Human-readable summary; the CLI prints this verbatim. */
message: string;
/**
* Argv for the install command when `action === "run-npm-install"`.
* Absent otherwise. Kept as array so the CLI can pass it straight
* to `spawn` without re-parsing shell syntax.
*/
command?: string[];
}
export interface PlanUpdateInput {
current: string;
latest: string;
/** Overrides `isNpxInstall()` (tests). */
npx?: boolean;
}
/**
* Pure decision function: given current + latest + install kind,
* decide what the CLI should do. No I/O.
*
* newer-local — current > latest (dev build, local publish)
* up-to-date — current === latest
* npx-hint — current < latest AND running under npx
* run-npm-install — current < latest AND running as a real install
*/
export function planUpdate(input: PlanUpdateInput): UpdatePlan {
const diff = compareVersions(input.current, input.latest);
if (diff > 0) {
return {
action: "newer-local",
message: `current (${input.current}) is newer than the published ${input.latest} — nothing to do.`,
};
}
if (diff === 0) {
return { action: "up-to-date", message: `reasonix ${input.current} is up to date.` };
}
if (input.npx) {
return {
action: "npx-hint",
message: [
`reasonix ${input.latest} is available.`,
"you're running via npx — the next `npx reasonix ...` launch will auto-fetch",
"the latest (npx caches packages for a short window). to force a refresh",
"sooner, clear the cache: `npm cache clean --force`.",
].join("\n"),
};
}
return {
action: "run-npm-install",
message: `upgrading reasonix ${input.current} → ${input.latest}`,
command: ["npm", "install", "-g", "reasonix@latest"],
};
}
export interface UpdateCommandOptions {
/** Skip spawning npm; print the decision only. */
dryRun?: boolean;
/** Test seam: override the registry lookup. Returns null = offline. */
fetchLatest?: () => Promise<string | null>;
/** Test seam: override the npx detector. */
isNpx?: () => boolean;
/** Test seam: override the spawner. Must return exit code. */
spawnInstall?: (argv: string[]) => Promise<number>;
/** Test seam: stdout writer. */
write?: (msg: string) => void;
/** Test seam: process exit — tests don't want to tear down vitest. */
exit?: (code: number) => void;
}
function defaultSpawn(argv: string[]): Promise<number> {
return new Promise((resolve, reject) => {
// `shell: true` on Windows is what lets `npm` resolve to `npm.cmd`
// without routing through our `prepareSpawn` helper. The args here
// are literal strings under our control — no user input flows in,
// so injection is not a concern. Avoiding `prepareSpawn` keeps
// this command free of a dep on the shell tools module.
const child = spawn(argv[0]!, argv.slice(1), {
stdio: "inherit",
shell: process.platform === "win32",
});
child.once("error", reject);
child.once("exit", (code) => resolve(code ?? 1));
});
}
/**
* Run the update command. Prints a banner, resolves the latest
* version, prints the plan, and (unless `--dry-run`) executes the
* install when applicable.
*/
export async function updateCommand(opts: UpdateCommandOptions = {}): Promise<void> {
const write = opts.write ?? ((m: string) => process.stdout.write(m));
const exit = opts.exit ?? ((c: number) => process.exit(c));
const fetchLatest = opts.fetchLatest ?? (() => getLatestVersion({ force: true }));
const isNpx = opts.isNpx ?? isNpxInstall;
const doSpawn = opts.spawnInstall ?? defaultSpawn;
write(`current: reasonix ${VERSION}\n`);
const latest = await fetchLatest();
if (!latest) {
write("could not reach registry.npmjs.org — check your network.\n");
exit(1);
return;
}
write(`latest: reasonix ${latest}\n`);
const plan = planUpdate({ current: VERSION, latest, npx: isNpx() });
write(`\n${plan.message}\n`);
if (plan.action !== "run-npm-install" || !plan.command) return;
if (opts.dryRun) {
write(`(dry run) would run: ${plan.command.join(" ")}\n`);
return;
}
write(`\nrunning: ${plan.command.join(" ")}\n`);
const code = await doSpawn(plan.command);
if (code !== 0) {
write(`\nnpm exited with code ${code}. upgrade did not complete.\n`);
exit(code);
}
}
+55 -13
View File
@@ -1,6 +1,8 @@
import { Command } from "commander";
import { readConfig } from "../config.js";
import { VERSION } from "../index.js";
import { ESCALATION_CONTRACT } from "../prompt-fragments.js";
import { applyMemoryStack } from "../user-memory.js";
import { chatCommand } from "./commands/chat.js";
import { codeCommand } from "./commands/code.js";
import { diffCommand } from "./commands/diff.js";
@@ -11,11 +13,25 @@ import { runCommand } from "./commands/run.js";
import { sessionsCommand } from "./commands/sessions.js";
import { setupCommand } from "./commands/setup.js";
import { statsCommand } from "./commands/stats.js";
import { updateCommand } from "./commands/update.js";
import { versionCommand } from "./commands/version.js";
import { resolveDefaults } from "./resolve.js";
const DEFAULT_SYSTEM =
"You are Reasonix, a helpful DeepSeek-powered assistant. Be concise and accurate. Use tools when available.";
const DEFAULT_SYSTEM = `You are Reasonix, a helpful DeepSeek-powered assistant. Be concise and accurate. Use tools when available.
# Cite or shut up — non-negotiable
Every factual claim about a codebase must be backed by evidence. Reasonix VALIDATES your citations — broken paths render in **red strikethrough with ❌** in front of the user.
**Positive claims** — append a markdown link:
- ✅ \`The MCP client supports listResources [listResources](src/mcp/client.ts:142).\`
- ❌ \`The MCP client supports listResources.\` ← unverifiable, do not write.
**Negative claims** ("X is missing", "Y isn't implemented", "lacks Z") are the #1 hallucination shape. STOP before writing them. If you have a search tool, call it first; if the search returns nothing, cite the search itself as evidence (\`No matches for "foo" in src/\`). If you have no tool, qualify hard: "I haven't verified — this is a guess."
Asserting absence without checking is how evaluative answers go wrong. Treat the urge to write "missing" as a red flag in your own reasoning.
${ESCALATION_CONTRACT}`;
const program = new Command();
program
@@ -37,7 +53,7 @@ program.action(async () => {
const defaults = resolveDefaults({});
await chatCommand({
model: defaults.model,
system: DEFAULT_SYSTEM,
system: applyMemoryStack(DEFAULT_SYSTEM, process.cwd()),
harvest: defaults.harvest,
branch: defaults.branch,
session: defaults.session,
@@ -55,17 +71,26 @@ program
program
.command("code [dir]")
.description(
"Code-editing chat — filesystem MCP auto-bridged at <dir> (default: cwd), coding system prompt, smart preset. Model proposes SEARCH/REPLACE blocks; Reasonix applies them to disk.",
"Code-editing chat — filesystem tools rooted at <dir> (default: cwd), coding system prompt, v4-flash. Model proposes SEARCH/REPLACE blocks; Reasonix applies them to disk. Use /preset max or /pro to escalate to v4-pro on hard tasks.",
)
.option("-m, --model <id>", "Override default reasoner model")
.option("-m, --model <id>", "Override default model (v4-flash)")
.option("--no-session", "Disable session persistence for this run")
.option("-r, --resume", "Skip the session picker — always continue prior messages")
.option("-n, --new", "Skip the session picker — always wipe prior messages and start fresh")
.option("--transcript <path>", "Write a JSONL transcript to this path")
.option(
"--harvest",
"Opt-in Pillar-2 plan-state extraction. Adds one flash call per turn; off by default (no preset enables it).",
)
.action(async (dir: string | undefined, opts) => {
await codeCommand({
dir,
model: opts.model,
noSession: opts.session === false,
transcript: opts.transcript,
forceResume: !!opts.resume,
forceNew: !!opts.new,
harvest: !!opts.harvest,
});
});
@@ -77,19 +102,21 @@ program
.option("--transcript <path>", "Write a JSONL transcript to this path")
.option(
"--preset <name>",
"Bundle of model + harvest + branch. One of: fast, smart, max. Overrides config.preset.",
"Model + effort bundle. One of: fast (flash·high), smart (flash·max, default), max (pro·max). Overrides config.preset.",
)
.option(
"--harvest",
"Extract typed plan state from R1 reasoning (Pillar 2). Overrides preset's harvest setting.",
"Opt-in Pillar-2 plan-state extraction. Off by default — no preset enables it.",
)
.option(
"--branch <n>",
"Self-consistency: run N parallel samples per turn and pick the most confident (disables streaming; enables harvest)",
"Self-consistency: run N parallel samples per turn (N× cost). Manual only — never auto-enabled.",
(v) => Number.parseInt(v, 10),
)
.option("--session <name>", "Use a named session (default: from config, usually 'default').")
.option("--no-session", "Disable session persistence for this run (ephemeral chat)")
.option("-r, --resume", "Skip the session picker — always continue prior messages")
.option("-n, --new", "Skip the session picker — always wipe prior messages and start fresh")
.option(
"--mcp <spec>",
'MCP server spec; repeatable. "name=cmd args...", "cmd args...", or a URL (http/https → SSE transport). Overrides config.mcp when provided.',
@@ -113,13 +140,15 @@ program
});
await chatCommand({
model: defaults.model,
system: opts.system,
system: applyMemoryStack(opts.system, process.cwd()),
transcript: opts.transcript,
harvest: defaults.harvest,
branch: defaults.branch,
session: defaults.session,
mcp: defaults.mcp,
mcpPrefix: opts.mcpPrefix,
forceResume: !!opts.resume,
forceNew: !!opts.new,
});
});
@@ -159,7 +188,7 @@ program
await runCommand({
task,
model: defaults.model,
system: opts.system,
system: applyMemoryStack(opts.system, process.cwd()),
harvest: defaults.harvest,
branch: defaults.branch,
transcript: opts.transcript,
@@ -169,9 +198,12 @@ program
});
program
.command("stats <transcript>")
.description("Summarize a JSONL transcript produced by `reasonix chat --transcript`.")
.action((transcript: string) => {
.command("stats [transcript]")
.description(
"Show usage dashboard (today / week / month / all-time · turns · cache hit · cost · savings vs Claude). " +
"Pass a transcript path to fall back to the per-file summary (assistant turns + tool calls).",
)
.action((transcript: string | undefined) => {
statsCommand({ transcript });
});
@@ -251,6 +283,16 @@ mcp
program.command("version").description("Print Reasonix version.").action(versionCommand);
program
.command("update")
.description(
"Check the npm registry for a newer Reasonix and install it. Detects npx vs global install; for npx users, prints a cache-refresh hint instead of running `npm i -g`.",
)
.option("--dry-run", "Print the plan without executing the install")
.action(async (opts: { dryRun?: boolean }) => {
await updateCommand({ dryRun: !!opts.dryRun });
});
program.parseAsync(process.argv).catch((err) => {
console.error(err);
process.exit(1);
+5 -3
View File
@@ -6,7 +6,7 @@
* 1. Explicit per-setting CLI flag (`--model`, `--harvest`, `--branch`, `--mcp`)
* 2. Explicit `--preset <name>` CLI flag
* 3. `config.preset` from `~/.reasonix/config.json` (set by `reasonix setup`)
* 4. Hardcoded "fast" preset defaults
* 4. Hardcoded "smart" preset defaults (flash + effort=max)
*
* Keeping this logic in one place — rather than duplicating across
* `chat` and `run` — means the precedence rule only lives in one unit
@@ -18,6 +18,7 @@ import { PRESETS } from "./ui/presets.js";
export interface ResolvedDefaults {
model: string;
reasoningEffort: "high" | "max";
harvest: boolean;
branch: number | undefined;
mcp: string[];
@@ -44,6 +45,7 @@ export function resolveDefaults(flags: RawCliFlags): ResolvedDefaults {
const presetSettings = PRESETS[preset];
const model = flags.model ?? presetSettings.model;
const reasoningEffort = presetSettings.reasoningEffort;
const harvest = flags.harvest === true ? true : presetSettings.harvest;
const branchFromFlag = normalizeBranch(flags.branch);
const branch = branchFromFlag ?? (presetSettings.branch > 1 ? presetSettings.branch : undefined);
@@ -55,7 +57,7 @@ export function resolveDefaults(flags: RawCliFlags): ResolvedDefaults {
const session = resolveSession(flags.session, cfg.session);
return { model, harvest, branch, mcp, session };
return { model, reasoningEffort, harvest, branch, mcp, session };
}
function pickPreset(
@@ -64,7 +66,7 @@ function pickPreset(
): PresetName {
if (flagPreset && isPresetName(flagPreset)) return flagPreset;
if (configPreset) return configPreset;
return "fast";
return "smart";
}
function isPresetName(s: string): s is PresetName {
+1482 -368
View File
File diff suppressed because it is too large. Load diff
+86
View File
@@ -0,0 +1,86 @@
import { Box, Text } from "ink";
// biome-ignore lint/style/useImportType: tsconfig.jsx = "react" needs React in value scope for JSX compilation
import React from "react";
export interface AtMentionSuggestionsProps {
/**
* Current matching file paths, ranked by the picker. `null` means
* "not in @-prefix mode" — render nothing. Empty array means "in @
* mode but no files match that partial" — render a hint.
*/
matches: readonly string[] | null;
/** Index (within `matches`) of the currently highlighted row. */
selectedIndex: number;
/** The partial query the user typed after `@`. Shown in the hint row. */
query: string;
}
/**
* Floating `@`-mention picker. Rendered below the input box when the
* user is typing an `@…` prefix in code mode. Navigation state lives
* in the parent (App.tsx owns `atSelected`) — this component is pure
* display. Mirrors {@link SlashSuggestions} shape so the keybindings
* and layout feel identical across the two pickers.
*/
export function AtMentionSuggestions({
matches,
selectedIndex,
query,
}: AtMentionSuggestionsProps): React.ReactElement | null {
if (matches === null) return null;
if (matches.length === 0) {
return (
<Box paddingX={1}>
<Text color="yellow">no files match "@{query}"</Text>
<Text dimColor>
{" "}
— keep typing, or Backspace to edit. Paths resolve from the code root.
</Text>
</Box>
);
}
const MAX = 8;
const total = matches.length;
const windowStart =
total <= MAX ? 0 : Math.max(0, Math.min(selectedIndex - Math.floor(MAX / 2), total - MAX));
const shown = matches.slice(windowStart, windowStart + MAX);
const hiddenAbove = windowStart;
const hiddenBelow = total - windowStart - shown.length;
return (
<Box flexDirection="column" paddingX={1}>
{hiddenAbove > 0 ? <Text dimColor> ↑ {hiddenAbove} more above</Text> : null}
{shown.map((path, i) => (
<FileRow key={path} path={path} isSelected={windowStart + i === selectedIndex} />
))}
{hiddenBelow > 0 ? <Text dimColor> ↓ {hiddenBelow} more below</Text> : null}
<Text dimColor> [↑↓] navigate · [Tab]/[Enter] pick · file content inlined on send</Text>
</Box>
);
}
function FileRow({ path, isSelected }: { path: string; isSelected: boolean }) {
const marker = isSelected ? "▸" : " ";
// Split the path so the basename visually pops — same dropdown
// affordance as VS Code's Quick Open.
const slash = path.lastIndexOf("/");
const dir = slash >= 0 ? `${path.slice(0, slash)}/` : "";
const base = slash >= 0 ? path.slice(slash + 1) : path;
if (isSelected) {
return (
<Box>
<Text bold color="cyan">
{marker} {base}
</Text>
<Text color="cyan">{dir ? ` ${dir}` : ""}</Text>
</Box>
);
}
return (
<Box>
<Text dimColor>
{marker} {base}
{dir ? ` ${dir}` : ""}
</Text>
</Box>
);
}
+220
View File
@@ -0,0 +1,220 @@
import { Box, Text, useInput, useStdout } from "ink";
import React, { useMemo, useState } from "react";
import { formatEditBlockDiff } from "../../code/diff-preview.js";
import type { EditBlock } from "../../code/edit-blocks.js";
/**
* Choice surfaced to the interceptor when the user resolves the modal:
* - `apply` → apply this edit, keep prompting on next.
* - `reject` → tell the model the user refused; do NOT
* retry the same edit.
* - `apply-rest-of-turn` → apply this edit AND every remaining edit
* this turn without further prompts. Resets
* at the next user turn.
* - `flip-to-auto` → apply this edit + persistently switch the
* session to AUTO mode (survives restart).
*/
export type EditReviewChoice = "apply" | "reject" | "apply-rest-of-turn" | "flip-to-auto";
export interface EditConfirmProps {
block: EditBlock;
onChoose: (choice: EditReviewChoice) => void;
}
/**
* Overhead reserved for non-diff UI inside the modal: border (2),
* title (1), separator (1), file-header (1), scroll-indicator rows
* (up to 2), footer + margin (3), plus breathing room for the host
* TUI's chrome above (stats panel ≈ 4, historical live rows, prompt
* input ≈ 2). 18 rows absorbed before the diff gets any budget.
*/
const MODAL_OVERHEAD_ROWS = 18;
/**
* Absolute floor on the diff viewport. If the terminal is absurdly
* short (< 26 rows total) we still show at least 8 diff lines so the
* modal is usable; the user scrolls more aggressively but can't end up
* with a zero-height viewport.
*/
const MIN_DIFF_ROWS = 8;
/**
* Modal-style approval for a single model-proposed file edit.
*
* Why per-edit instead of end-of-turn batch: users reported they can't
* tell if the model is about to make one small change or seven sprawling
* ones until the turn is over. Per-edit prompts let the user intervene
* early — reject a bad direction before the model builds on it, or
* approve the first few and hit `a` to let the rest land.
*
* Diff viewport: we compute the UNCAPPED diff once, then slice to a
* height budget derived from terminal rows. Large diffs (100+ lines)
* are scrollable via j/k/↑/↓/Space/PgUp/PgDn/g/G — the user can page
* through the whole change before deciding, and the action footer
* never scrolls off the bottom. Before the scroll support a 97-line
* scene.ts diff truncated at "… 67 more …" which was unreviewable.
*/
export function EditConfirm({ block, onChoose }: EditConfirmProps) {
const { stdout } = useStdout();
const rows = stdout?.rows ?? 40;
const budget = Math.max(MIN_DIFF_ROWS, rows - MODAL_OVERHEAD_ROWS);
// Full diff — maxLines pushed high enough that the diff-preview
// renderer never inserts its own truncation marker. Context trimming
// (contextLines) still applies for tight scan.
const allLines = useMemo(
() => formatEditBlockDiff(block, { contextLines: 2, maxLines: 100_000, indent: " " }),
[block],
);
const [scroll, setScroll] = useState(0);
const maxScroll = Math.max(0, allLines.length - budget);
// Clamp scroll if budget shrinks (terminal resized) after a previous
// keypress drove the offset past the new ceiling.
const effectiveScroll = Math.min(scroll, maxScroll);
useInput((input, key) => {
// Action keys first — decision wins over scroll so a user who
// hammered PgDn can still hit `y` at the end without a stray
// extra scroll.
if (key.return || input === "y") {
onChoose("apply");
return;
}
if (input === "n") {
onChoose("reject");
return;
}
if (input === "a") {
onChoose("apply-rest-of-turn");
return;
}
if (input === "A") {
onChoose("flip-to-auto");
return;
}
// Scroll navigation — vim-ish (j/k) and emacs-ish (arrows) both
// work. Space for "next page" is the pager convention.
if (key.downArrow || input === "j") {
setScroll((s) => Math.min(maxScroll, s + 1));
return;
}
if (key.upArrow || input === "k") {
setScroll((s) => Math.max(0, s - 1));
return;
}
if (key.pageDown || input === " " || input === "f") {
setScroll((s) => Math.min(maxScroll, s + Math.max(1, budget - 2)));
return;
}
if (key.pageUp || input === "b") {
setScroll((s) => Math.max(0, s - Math.max(1, budget - 2)));
return;
}
if (input === "g") {
setScroll(0);
return;
}
if (input === "G") {
setScroll(maxScroll);
return;
}
// Esc falls through to the parent abort handler.
});
const isNew = block.search === "";
const removed = isNew ? 0 : (block.search.match(/\n/g)?.length ?? 0) + 1;
const added = block.replace === "" ? 0 : (block.replace.match(/\n/g)?.length ?? 0) + 1;
const tag = isNew ? "NEW" : "EDIT";
const visibleLines = allLines.slice(effectiveScroll, effectiveScroll + budget);
const hiddenAbove = effectiveScroll;
const hiddenBelow = Math.max(0, allLines.length - effectiveScroll - budget);
const totalLines = allLines.length;
const showScrollHud = hiddenAbove + hiddenBelow > 0;
return (
<Box flexDirection="column" borderStyle="round" borderColor="cyan" paddingX={1} marginY={1}>
<Box>
<Text bold color="cyan">
{"▸ model wants to edit a file"}
</Text>
</Box>
<Box>
<Text color="cyan" dimColor>
{"──────────────────────────────────────────"}
</Text>
</Box>
<Box marginTop={1}>
<Text>
<Text color={isNew ? "green" : "yellow"} bold>{`[${tag}] `}</Text>
<Text color="cyan">{block.path}</Text>
<Text dimColor>{` (-${removed} +${added} lines)`}</Text>
{showScrollHud ? (
<Text dimColor>
{` · viewing ${effectiveScroll + 1}-${effectiveScroll + visibleLines.length}/${totalLines}`}
</Text>
) : null}
</Text>
</Box>
{hiddenAbove > 0 ? (
<Text
dimColor
>{` ↑ ${hiddenAbove} line${hiddenAbove === 1 ? "" : "s"} above (↑/k or PgUp)`}</Text>
) : null}
<Box marginTop={hiddenAbove > 0 ? 0 : 1} flexDirection="column">
{visibleLines.map((line, i) => {
const trimmed = line.trimStart();
const color = trimmed.startsWith("+")
? "green"
: trimmed.startsWith("-")
? "red"
: undefined;
const dim = !color;
return (
<Text
// Stable-enough: slice only shifts by scroll; React keys only
// need to be unique within the current render.
// biome-ignore lint/suspicious/noArrayIndexKey: list is static per render
key={`diff-${effectiveScroll}-${i}`}
color={color}
dimColor={dim}
>
{line}
</Text>
);
})}
</Box>
{hiddenBelow > 0 ? (
<Text
dimColor
>{` ↓ ${hiddenBelow} line${hiddenBelow === 1 ? "" : "s"} below (↓/j or Space/PgDn)`}</Text>
) : null}
<Box marginTop={1}>
<Text dimColor>
{"["}
<Text color="cyan" bold>
y
</Text>
{"/Enter] apply · ["}
<Text color="cyan" bold>
n
</Text>
{"] reject · ["}
<Text color="cyan" bold>
a
</Text>
{"] apply rest · ["}
<Text color="cyan" bold>
A
</Text>
{"] flip AUTO · ["}
<Text color="cyan" bold>
↑↓/Space
</Text>
{"] scroll · [Esc] abort"}
</Text>
</Box>
</Box>
);
}
+292 -91
View File
@@ -1,12 +1,27 @@
import { Box, Text } from "ink";
import React, { useEffect, useState } from "react";
import { Box, Text, useStdout } from "ink";
import React from "react";
import { type TypedPlanState, isPlanStateEmpty } from "../../harvest.js";
import type { BranchProgress, BranchSummary } from "../../loop.js";
import type { TurnStats } from "../../telemetry.js";
import { PlanStateBlock } from "./PlanStateBlock.js";
import { Markdown } from "./markdown.js";
import { useElapsedSeconds, useTick } from "./ticker.js";
export type DisplayRole = "user" | "assistant" | "tool" | "system" | "error" | "info" | "warning";
export type DisplayRole =
| "user"
| "assistant"
| "tool"
| "system"
| "error"
| "info"
| "warning"
/**
* A plan body pushed to scrollback when the model calls `submit_plan`.
* Rendered through the full markdown pipeline (not truncated), so the
* user reads the whole thing in the permanent Static log and the
* PlanConfirm modal below it stays a tight picker.
*/
| "plan";
export interface DisplayEvent {
id: string;
@@ -20,16 +35,63 @@ export interface DisplayEvent {
stats?: TurnStats;
repair?: string;
streaming?: boolean;
toolCallBuild?: { name: string; chars: number; index?: number; readyCount?: number };
/**
* Render a thin horizontal rule above this event. Used to mark
* "start of a new user turn" so long scrollbacks get visual
* pacing — without it, five-turn sessions read as one wall of
* text. Only the *first* user message in a session should leave
* this off; App.tsx sets it based on whether history is empty.
*/
leadSeparator?: boolean;
}
export const EventRow = React.memo(function EventRow({ event }: { event: DisplayEvent }) {
/**
* Reasonix visual language: every event is anchored by a geometric
* glyph in its role color. Together they form a consistent alphabet
* (◇ ◆ ▣ ▥ ▲ ✦) the eye learns fast — no text labels needed after
* the first couple of turns. `◈` is the brand mark, reserved for
* the app header.
*/
const ROLE_GLYPH = {
user: "◇",
assistant: "◆",
assistantPulse: "◇", // pulse alternate for streaming state
toolOk: "▣",
toolErr: "▥",
warning: "▲",
error: "✦",
} as const;
function RoleGlyph({
glyph,
color,
}: {
glyph: string;
color: "cyan" | "green" | "yellow" | "red" | "magenta" | "blue";
}) {
return (
<Text color={color} bold>
{glyph}
</Text>
);
}
export const EventRow = React.memo(function EventRow({
event,
projectRoot,
}: {
event: DisplayEvent;
projectRoot?: string;
}) {
if (event.role === "user") {
return (
<Box>
<Text bold color="cyan">
you ›{" "}
<Box marginTop={event.leadSeparator ? 1 : 0}>
<RoleGlyph glyph={ROLE_GLYPH.user} color="cyan" />
<Text>
{" "}
{event.text}
</Text>
<Text>{event.text}</Text>
</Box>
);
}
@@ -38,29 +100,34 @@ export const EventRow = React.memo(function EventRow({ event }: { event: Display
return (
<Box flexDirection="column" marginTop={1}>
<Box>
<Text bold color="green">
assistant
</Text>
<RoleGlyph glyph={ROLE_GLYPH.assistant} color="green" />
{event.stats ? <Text dimColor>{` ${event.stats.model}`}</Text> : null}
</Box>
<Box flexDirection="column" paddingLeft={2} marginTop={1}>
{event.branch ? <BranchBlock branch={event.branch} /> : null}
{event.reasoning ? <ReasoningBlock reasoning={event.reasoning} /> : null}
{!isPlanStateEmpty(event.planState) ? (
<PlanStateBlock planState={event.planState!} />
) : null}
{event.text ? (
<Markdown text={event.text} projectRoot={projectRoot} />
) : (
<Text dimColor>(no content)</Text>
)}
{event.stats ? <StatsLine stats={event.stats} /> : null}
{event.repair ? <Text color="magenta">{event.repair}</Text> : null}
</Box>
{event.branch ? <BranchBlock branch={event.branch} /> : null}
{event.reasoning ? <ReasoningBlock reasoning={event.reasoning} /> : null}
{!isPlanStateEmpty(event.planState) ? (
<PlanStateBlock planState={event.planState!} />
) : null}
{event.text ? <Markdown text={event.text} /> : <Text dimColor>(no content)</Text>}
{event.stats ? <StatsLine stats={event.stats} /> : null}
{event.repair ? <Text color="magenta">{event.repair}</Text> : null}
</Box>
);
}
if (event.role === "tool") {
// `flattenMcpResult` prefixes server-side errors with "ERROR: ".
// Render those in red with a ✗ marker so they don't blend into
// successful tool output (yellow) — the failure mode is what the
// model most likely needs to act on next, and the user needs to
// see at a glance.
// Render the tool glyph in red with a ✗ direction marker so the
// failure mode is unmissable — it's the signal the model needs
// most for its next decision.
const isError = event.text.startsWith("ERROR:");
const color = isError ? "red" : "yellow";
const glyph = isError ? ROLE_GLYPH.toolErr : ROLE_GLYPH.toolOk;
const marker = isError ? "✗" : "→";
// `edit_file` results get a dedicated diff renderer — colored
// line-by-line so `-` removals show red, `+` additions show
@@ -71,25 +138,31 @@ export const EventRow = React.memo(function EventRow({ event }: { event: Display
(event.toolName === "edit_file" || event.toolName?.endsWith("_edit_file")) && !isError;
return (
<Box flexDirection="column" marginTop={1}>
<Text color={color}>{`tool<${event.toolName ?? "?"}> ${marker}`}</Text>
{isEditFile ? (
<EditFileDiff text={event.text} />
) : (
<Text color={isError ? "red" : undefined} dimColor={!isError}>
{" "}
{truncate(event.text, 400)}
</Text>
)}
<Box>
<RoleGlyph glyph={glyph} color={color} />
<Text color={color} bold>{` ${event.toolName ?? "?"}`}</Text>
<Text color={color} dimColor>{` ${marker}`}</Text>
</Box>
<Box flexDirection="column" paddingLeft={2} marginTop={1}>
{isEditFile ? (
<EditFileDiff text={event.text} />
) : (
<Text color={isError ? "red" : undefined} dimColor={!isError}>
{truncate(event.text, 400)}
</Text>
)}
</Box>
</Box>
);
}
if (event.role === "error") {
return (
<Box marginTop={1}>
<Text color="red" bold>
error{" "}
<RoleGlyph glyph={ROLE_GLYPH.error} color="red" />
<Text color="red">
{" "}
{event.text}
</Text>
<Text color="red">{event.text}</Text>
</Box>
);
}
@@ -100,11 +173,28 @@ export const EventRow = React.memo(function EventRow({ event }: { event: Display
</Box>
);
}
if (event.role === "plan") {
return (
<Box flexDirection="column" borderStyle="round" borderColor="cyan" paddingX={1} marginY={1}>
<Box>
<Text bold color="cyan">
{"📋 plan proposed — pick a choice below"}
</Text>
</Box>
<Box marginTop={1} flexDirection="column">
<Markdown text={event.text} projectRoot={projectRoot} />
</Box>
</Box>
);
}
if (event.role === "warning") {
return (
<Box>
<Text color="yellow">▸ </Text>
<Text color="yellow">{event.text}</Text>
<RoleGlyph glyph={ROLE_GLYPH.warning} color="yellow" />
<Text color="yellow">
{" "}
{event.text}
</Text>
</Box>
);
}
@@ -115,6 +205,32 @@ export const EventRow = React.memo(function EventRow({ event }: { event: Display
);
});
/**
* Thin horizontal rule between turns with a cyan ◆ centered as the
* Reasonix mark. Past-turn separators live inside `<Static>` (Ink's
* render-once optimization), so animation here would freeze at
* tick=0 on every past turn — we keep it static by design. The
* animated heartbeat lives in PulsingAssistantGlyph (current turn)
* and the Wordmark (StatsPanel) where rerender is free.
*/
function TurnSeparator() {
const { stdout } = useStdout();
const cols = stdout?.columns ?? 80;
const width = Math.max(16, cols - 2);
const half = Math.floor((width - 3) / 2);
const left = "─".repeat(half);
const right = "─".repeat(width - half - 3);
return (
<Box marginTop={1} marginBottom={1}>
<Text dimColor>{left}</Text>
<Text color="cyan" bold>
{" ◆ "}
</Text>
<Text dimColor>{right}</Text>
</Box>
);
}
/**
* Render the payload of an `edit_file` tool result with proper
* diff coloring: first line is the header ("edited X (A→B chars)"),
@@ -181,7 +297,7 @@ function BranchBlock({ branch }: { branch: BranchSummary }) {
return (
<Box>
<Text color="blue">
{"🔀 branched "}
{"⎇ branched "}
<Text bold>{branch.budget}</Text>
{` samples → picked #${branch.chosenIndex} `}
<Text dimColor>{per}</Text>
@@ -200,11 +316,15 @@ function ReasoningBlock({ reasoning }: { reasoning: string }) {
// Users can dump the full reasoning with `/think` if needed.
const preview =
flat.length <= max ? flat : `… (+${flat.length - max} earlier chars) ${flat.slice(-max)}`;
// ▏ (LEFT ONE EIGHTH BLOCK) renders as a thin vertical rule at the
// cell edge — subtler than the role-level ▎ above, giving a
// visual hierarchy: thick bar = role, thin bar = nested detail
// under that role (thinking, stats, citations, etc).
return (
<Box marginBottom={1}>
<Text dimColor>▏ </Text>
<Text dimColor italic>
{"↳ thinking: "}
{preview}
thinking {preview}
</Text>
</Box>
);
@@ -216,17 +336,28 @@ function ReasoningBlock({ reasoning }: { reasoning: string }) {
* the terminal viewport and leaves artifacts in scrollback.
*/
function Elapsed() {
const [s, setS] = useState(0);
useEffect(() => {
const start = Date.now();
const id = setInterval(() => setS(Math.floor((Date.now() - start) / 1000)), 1000);
return () => clearInterval(id);
}, []);
const s = useElapsedSeconds();
const mm = String(Math.floor(s / 60)).padStart(2, "0");
const ss = String(s % 60).padStart(2, "0");
return <Text dimColor>{`${mm}:${ss}`}</Text>;
}
/**
* Animated role glyph for the actively-streaming assistant. Alternates
* ◆ ↔ ◇ every ~480ms so the user can see the model is alive even
* during R1's long pre-first-byte silence. Settles back to a static
* ◆ once the turn ends (StreamingAssistant is unmounted).
*/
function PulsingAssistantGlyph() {
const tick = useTick();
const on = Math.floor(tick / 4) % 2 === 0;
return (
<Text color="green" bold>
{on ? ROLE_GLYPH.assistant : ROLE_GLYPH.assistantPulse}
</Text>
);
}
function StreamingAssistant({ event }: { event: DisplayEvent }) {
if (event.branchProgress) {
const p = event.branchProgress;
@@ -235,15 +366,17 @@ function StreamingAssistant({ event }: { event: DisplayEvent }) {
return (
<Box flexDirection="column" marginTop={1}>
<Box>
<Text bold color="green">
assistant{" "}
</Text>
<PulsingAssistantGlyph />
<Text color="blue">
🔀 launching {p.total} parallel samples (R1 thinking in parallel)…{" "}
{" ⎇ launching "}
{p.total}
{" parallel samples (R1 thinking in parallel)… "}
</Text>
<Elapsed />
</Box>
<Text dimColor>{" "}spread across T=0.0/0.5/1.0 · typical wait 30-90s for reasoner</Text>
<Text color="yellow">
{" "}spread across T=0.0/0.5/1.0 · reasoner typically takes 30-90s — this is normal
</Text>
</Box>
);
}
@@ -251,11 +384,13 @@ function StreamingAssistant({ event }: { event: DisplayEvent }) {
return (
<Box flexDirection="column" marginTop={1}>
<Box>
<Text bold color="green">
assistant{" "}
</Text>
<PulsingAssistantGlyph />
<Text color="blue">
🔀 branching {p.completed}/{p.total} ({pct}%){" "}
{" ⎇ branching "}
{p.completed}/{p.total}
{" ("}
{pct}
{"%) "}
</Text>
<Elapsed />
</Box>
@@ -274,40 +409,48 @@ 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;
const reasoningOnly = !event.text && !!event.reasoning;
const preFirstByte = !event.text && !event.reasoning && !toolCallBuild;
const reasoningOnly = !event.text && !!event.reasoning && !toolCallBuild;
const toolCallOnly = !event.text && !event.reasoning && !!toolCallBuild;
let label: string;
let labelColor: "yellow" | "cyan" | "green" | undefined;
let labelColor: "yellow" | "cyan" | "green" | "magenta" | undefined;
if (preFirstByte) {
label = "request sent · waiting for server";
labelColor = "yellow";
} else if (reasoningOnly) {
label = `R1 reasoning · ${event.reasoning?.length ?? 0} chars of thought`;
labelColor = "cyan";
} else if (toolCallOnly) {
label = `assembling tool call${formatToolCallIndex(toolCallBuild)} <${toolCallBuild.name}> · ${toolCallBuild.chars} chars of arguments${formatReadyTail(toolCallBuild)}`;
labelColor = "magenta";
} else {
// Content phase. If reasoning is non-empty we include its size
// so the user knows R1 did a thinking pass before speaking.
label = event.reasoning
? `writing response · ${event.text.length} chars · after ${event.reasoning.length} chars of reasoning`
: `writing response · ${event.text.length} chars`;
const parts: string[] = [`writing response · ${event.text.length} chars`];
if (event.reasoning) parts.push(`after ${event.reasoning.length} chars of reasoning`);
if (toolCallBuild) {
parts.push(
`building tool call${formatToolCallIndex(toolCallBuild)} <${toolCallBuild.name}> · ${toolCallBuild.chars} chars${formatReadyTail(toolCallBuild)}`,
);
}
label = parts.join(" · ");
labelColor = "green";
}
return (
<Box flexDirection="column" marginTop={1}>
<Box>
<Text bold color="green">
assistant{" "}
</Text>
<PulsingAssistantGlyph />
<Text>{" "}</Text>
<Pulse />
<Text color={labelColor}>{` ${label} `}</Text>
<Elapsed />
@@ -319,34 +462,64 @@ function StreamingAssistant({ event }: { event: DisplayEvent }) {
) : null}
{tail ? (
<Text dimColor>▸ {tail}</Text>
) : preFirstByte ? (
// Non-dim yellow: first-time users misread the dim version as
// "app frozen". The reassurance has to be VISIBLE to do its job.
<Text color="yellow" italic>
{" waiting for first byte — this is normal, typically 5-60s depending on model + load"}
</Text>
) : reasoningOnly ? (
<Text color="yellow" dimColor>
<Text color="yellow" italic>
{
" R1 is thinking before it speaks — body text starts when reasoning completes (typically 20-90s)."
" R1 is thinking before it speaks — body text arrives when reasoning finishes (typically 20-90s, this is normal)"
}
</Text>
) : (
<Text dimColor italic>
{" connection open, first byte typically in 5-60s depending on model + load"}
) : toolCallOnly ? (
<Text color="magenta" italic>
{" tool-call arguments streaming — the model is about to dispatch a tool"}
</Text>
)}
) : event.reasoning ? (
<Text color="yellow" italic>
{" R1 still reasoning — body text or tool call arrives when thinking finishes"}
</Text>
) : null}
</Box>
);
}
/**
* Blinking indicator so the user can tell the stream is alive even
* when the reasoner hasn't produced body text yet. Ticks every 500 ms
* regardless of content flow — it's a heartbeat, not a progress bar.
* when the reasoner hasn't produced body text yet. Uses the shared
* tick (TICK_MS ≈ 120ms) scaled down 4× so the visible blink rate
* lands around 500ms — feels like a heartbeat, not a progress bar.
*/
function Pulse() {
const [tick, setTick] = useState(0);
useEffect(() => {
const id = setInterval(() => setTick((t) => t + 1), 500);
return () => clearInterval(id);
}, []);
const tick = useTick();
const frames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
return <Text color="cyan">{frames[tick % frames.length]}</Text>;
return <Text color="cyan">{frames[Math.floor(tick / 4) % frames.length]}</Text>;
}
/**
* "(call 3)" suffix for the tool-call label when we have the index.
* Hides when the turn only has one call so the common case stays tidy.
*/
function formatToolCallIndex(tb: { index?: number; readyCount?: number } | undefined): string {
if (!tb || tb.index === undefined) return "";
// Only show the index when this isn't obviously the first + only call.
if (tb.index === 0 && (tb.readyCount ?? 0) === 0) return "";
return ` (call ${tb.index + 1})`;
}
/**
* "· 2 ready" tail that answers "how many tool calls have finished
* streaming so far this turn?" — user feedback for multi-file turns
* where the response takes 10–30s to stream. Hidden until readyCount
* > 0 so single-call turns aren't cluttered.
*/
function formatReadyTail(tb: { readyCount?: number } | undefined): string {
const n = tb?.readyCount ?? 0;
if (n <= 0) return "";
return ` · ${n} ready`;
}
function lastLine(s: string, maxChars: number): string {
@@ -358,19 +531,47 @@ function lastLine(s: string, maxChars: number): string {
function StatsLine({ stats }: { stats: TurnStats }) {
const hit = (stats.cacheHitRatio * 100).toFixed(1);
return (
<Text dimColor>
{" ↳ cache "}
{hit}
{"% · tokens "}
{stats.usage.promptTokens}
{"→"}
{stats.usage.completionTokens}
{" · $"}
{stats.cost.toFixed(6)}
</Text>
<Box>
<Text dimColor>▏ </Text>
<Text dimColor>
{"cache "}
{hit}
{"% · tokens "}
{stats.usage.promptTokens}
{" → "}
{stats.usage.completionTokens}
{" · $"}
{stats.cost.toFixed(6)}
</Text>
</Box>
);
}
/**
* Show the *tail* of a long tool result by default — the useful signal
* (return value, summary, error line) usually lives at the end, not the
* top-of-file boilerplate. For `ERROR:`-prefixed results, keep the
* first line intact (that's the actual error message) AND include the
* tail, so stack-trace endings stay visible too.
*
* Rendered like: `(+N earlier chars) …<tail>` so users can tell at a
* glance that something was elided. `/tool N` still dumps the full
* content for cases where the middle matters.
*/
function truncate(s: string, max: number): string {
return s.length <= max ? s : `${s.slice(0, max)}… (+${s.length - max} chars)`;
if (s.length <= max) return s;
if (s.startsWith("ERROR:")) {
const firstNl = s.indexOf("\n");
const firstLine = firstNl === -1 ? s : s.slice(0, firstNl);
// If the first line alone is bigger than max, just show it truncated.
if (firstLine.length >= max) {
return `${firstLine.slice(0, max)}… (+${s.length - max} chars — /tool N for full)`;
}
const budget = max - firstLine.length - 10; // reserve space for separator + ellipsis
const tail = s.slice(-budget);
const skipped = s.length - firstLine.length - tail.length;
return `${firstLine}\n… (+${skipped} chars) …\n${tail}`;
}
const skipped = s.length - max;
return `… (+${skipped} earlier chars — /tool N for full) …\n${s.slice(-max)}`;
}
+275
View File
@@ -0,0 +1,275 @@
import { Box, Text } from "ink";
import React from "react";
import type { ApplyResult } from "../../code/edit-blocks.js";
import type { EditMode } from "../../config.js";
import type { JobRegistry } from "../../tools/jobs.js";
import { useElapsedSeconds, useTick } from "./ticker.js";
export const SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
/**
* Transient "what's happening now" row shown during silent phases
* between the primary events — harvest round-trip, R1 thinking
* about a tool result before the next streaming delta, forced
* summary. Matches OngoingToolRow's visual language (braille
* spinner + elapsed seconds) so the user's eyes track the same
* spot regardless of which kind of wait it is.
*/
export function StatusRow({ text }: { text: string }) {
const tick = useTick();
const elapsed = useElapsedSeconds();
return (
<Box marginY={1}>
<Text color="magenta">{SPINNER_FRAMES[tick % SPINNER_FRAMES.length]}</Text>
<Text color="magenta">{` ${text}`}</Text>
<Text dimColor>{` ${elapsed}s`}</Text>
</Box>
);
}
/**
* One-line bottom status bar showing the current edit mode, pending
* queue size (review only), an undo hint (auto only / after /apply),
* and the Shift+Tab nudge. Rendered immediately above PromptInput so
* the mode is always in peripheral vision when the user's eyes are at
* the prompt. Flashes briefly on mode change so Shift+Tab gives a
* visible acknowledgment without the user having to scan the header.
*
* The plan-mode pill takes precedence — when plan mode is on, writes
* are bounced regardless of edit mode, so surfacing it is more useful
* than the review/auto toggle.
*/
export function ModeStatusBar({
editMode,
pendingCount,
flash,
planMode,
undoArmed,
jobs,
}: {
editMode: EditMode;
pendingCount: number;
flash: boolean;
planMode: boolean;
undoArmed: boolean;
jobs?: JobRegistry;
}) {
// Subscribe to tick so the jobs count stays live — the registry is
// mutated outside React, so we need a periodic repaint to catch it.
// No-op when there's no registry (chat mode / tests).
useTick();
const running = jobs?.runningCount() ?? 0;
const jobsTag =
running > 0 ? (
<Text color="yellow" bold>{` · ⏵ ${running} job${running === 1 ? "" : "s"}`}</Text>
) : null;
if (planMode) {
return (
<Box paddingX={1}>
<Text color="red" bold inverse={flash}>
{"▸ PLAN"}
</Text>
<Text dimColor>
{" writes gated — submit_plan + approval required · /plan off to leave"}
</Text>
{jobsTag}
</Box>
);
}
const label = editMode === "auto" ? "AUTO" : "review";
const color = editMode === "auto" ? "magenta" : "cyan";
const mid =
editMode === "auto"
? undoArmed
? "edits apply immediately · u = undo last batch"
: "edits apply immediately · 5s undo window after each batch"
: pendingCount > 0
? `${pendingCount} queued · y = /apply · n = /discard`
: "edits queue for review · y = /apply · n = /discard";
const flip = editMode === "auto" ? "Shift+Tab → review" : "Shift+Tab → AUTO";
return (
<Box paddingX={1}>
<Text color={color} bold inverse={flash}>
{`▸ ${label}`}
</Text>
<Text dimColor>{` ${mid} · ${flip}`}</Text>
{jobsTag}
</Box>
);
}
/**
* "Just auto-applied N edits — press u to undo" banner. Rendered below
* the live rows after an auto-mode edit batch lands, visible for 5s.
* `useTick` drives a crude live countdown so the user sees the window
* shrinking. State cleanup (the banner disappearing) happens in the
* parent's setTimeout — the component is purely display.
*/
export function UndoBanner({
banner,
}: {
banner: { results: ApplyResult[]; expiresAt: number };
}) {
useTick();
const remainingMs = Math.max(0, banner.expiresAt - Date.now());
const remainingSec = Math.ceil(remainingMs / 1000);
const ok = banner.results.filter((r) => r.status === "applied" || r.status === "created").length;
const total = banner.results.length;
return (
<Box marginY={1} borderStyle="round" borderColor="magenta" paddingX={1}>
<Text color="magenta" bold>
{"✓ auto-applied "}
</Text>
<Text color="magenta">{`${ok}/${total} edit${total === 1 ? "" : "s"}`}</Text>
<Text dimColor>{" · press "}</Text>
<Text color="magenta" bold>
{"u"}
</Text>
<Text dimColor>{" to undo ("}</Text>
<Text color={remainingSec <= 1 ? "red" : "magenta"}>{`${remainingSec}s`}</Text>
<Text dimColor>{")"}</Text>
</Box>
);
}
/**
* Live one-line indicator for a running subagent. Sits below the
* OngoingToolRow (the parent's tool dispatch row for `spawn_subagent`)
* so the user sees both layers at once: outer "spawn_subagent
* running…" + inner "⌬ subagent: <task> · iter N · 12.3s". Cleared
* when the subagent ends; a one-line summary lands in historical.
*/
export function SubagentRow({
activity,
}: {
activity: { task: string; iter: number; elapsedMs: number };
}) {
const tick = useTick();
const seconds = (activity.elapsedMs / 1000).toFixed(1);
return (
<Box paddingLeft={2}>
<Text color="magenta">{SPINNER_FRAMES[tick % SPINNER_FRAMES.length]}</Text>
<Text color="magenta">{` ⌬ subagent: ${activity.task}`}</Text>
<Text dimColor>{` · iter ${activity.iter} · ${seconds}s`}</Text>
</Box>
);
}
/**
* Live spinner row while a tool call is in flight. Without this the
* window between the model's `tool_calls` decision and the tool's
* result (often seconds for a multi-KB `filesystem_edit_file`) looks
* like the app has frozen — the streaming assistant display is
* already cleared and the input is disabled, so there's nothing to
* look at.
*
* Shows three signals: a braille spinner (liveness), an elapsed
* timer in seconds (so "long" has a number attached), and a
* per-tool summary of the most informative argument fields (path,
* edits count, pattern, etc.). As of 0.4.8, MCP progress frames
* (`notifications/progress`) land here too — bar + "n/N" when the
* server reports a total, free-form message when not.
*/
export function OngoingToolRow({
tool,
progress,
}: {
tool: { name: string; args?: string };
progress: { progress: number; total?: number; message?: string } | null;
}) {
const tick = useTick();
const elapsed = useElapsedSeconds();
const summary = summarizeToolArgs(tool.name, tool.args);
return (
<Box marginY={1} flexDirection="column">
<Box>
<Text color="cyan">{SPINNER_FRAMES[tick % SPINNER_FRAMES.length]}</Text>
<Text color="yellow">{` tool<${tool.name}> running…`}</Text>
<Text dimColor>{` ${elapsed}s`}</Text>
</Box>
{progress ? (
<Box paddingLeft={2}>
<Text color="cyan">{renderProgressLine(progress)}</Text>
</Box>
) : null}
{summary ? (
<Box paddingLeft={2}>
<Text dimColor>{summary}</Text>
</Box>
) : null}
</Box>
);
}
/**
* Render an MCP progress frame as a single line. When the server
* reports `total`, show an ASCII progress bar + "n/total pct%";
* otherwise just "progress" + optional message. Width is modest
* so the line fits even in a narrow terminal.
*/
function renderProgressLine(p: { progress: number; total?: number; message?: string }): string {
const msg = p.message ? ` ${p.message}` : "";
if (p.total && p.total > 0) {
const ratio = Math.max(0, Math.min(1, p.progress / p.total));
const width = 20;
const filled = Math.round(ratio * width);
const bar = "█".repeat(filled) + "░".repeat(width - filled);
const pct = (ratio * 100).toFixed(0);
return `[${bar}] ${p.progress}/${p.total} ${pct}%${msg}`;
}
return `progress: ${p.progress}${msg}`;
}
/**
* Turn raw JSON tool arguments into a one-line human summary. For
* common filesystem MCP tools we pull the actually-useful fields; for
* anything else we fall back to a truncated raw string so the user
* still sees *something* beyond the tool name.
*
* Match on suffix (e.g. `_read_file`) rather than exact name because
* `bridgeMcpTools({ namePrefix: "filesystem_" })` prepends the server
* namespace — tools arrive as `filesystem_read_file` in practice but
* callers might wire up anonymous too.
*/
function summarizeToolArgs(name: string, args?: string): string {
if (!args || args === "{}") return "";
let parsed: Record<string, unknown>;
try {
parsed = JSON.parse(args) as Record<string, unknown>;
} catch {
// Unparseable JSON — show a head slice so user at least sees
// what the model tried.
return args.length > 80 ? `${args.slice(0, 80)}…` : args;
}
const hasSuffix = (s: string) => name === s || name.endsWith(`_${s}`);
const path = typeof parsed.path === "string" ? parsed.path : undefined;
if (hasSuffix("read_file")) {
const head = typeof parsed.head === "number" ? `, head=${parsed.head}` : "";
const tail = typeof parsed.tail === "number" ? `, tail=${parsed.tail}` : "";
return `path: ${path ?? "?"}${head}${tail}`;
}
if (hasSuffix("write_file")) {
const content = typeof parsed.content === "string" ? parsed.content : "";
return `path: ${path ?? "?"} (${content.length} chars)`;
}
if (hasSuffix("edit_file")) {
const edits = Array.isArray(parsed.edits) ? parsed.edits.length : 0;
return `path: ${path ?? "?"} (${edits} edit${edits === 1 ? "" : "s"})`;
}
if (hasSuffix("list_directory") || hasSuffix("directory_tree")) {
return `path: ${path ?? "?"}`;
}
if (hasSuffix("search_files")) {
const pattern = typeof parsed.pattern === "string" ? parsed.pattern : "?";
return `path: ${path ?? "?"} · pattern: ${pattern}`;
}
if (hasSuffix("move_file")) {
const src = typeof parsed.source === "string" ? parsed.source : "?";
const dst = typeof parsed.destination === "string" ? parsed.destination : "?";
return `${src} → ${dst}`;
}
if (hasSuffix("get_file_info")) {
return `path: ${path ?? "?"}`;
}
return args.length > 80 ? `${args.slice(0, 80)}…` : args;
}
+91
View File
@@ -0,0 +1,91 @@
/**
* Modal-style approval for a `submit_plan` proposal.
*
* Three choices:
* 1. Approve + implement — exits plan mode, pushes a synthetic user
* message telling the model to implement the plan now.
* 2. Refine — stays in plan mode; tells the model to explore more
* and submit an improved plan.
* 3. Cancel — exits plan mode, drops the plan, tells the model the
* user didn't want any of it.
*
* The plan BODY is NOT rendered inside this modal — App.tsx pushes it
* into the Static scrollback as a `role: "plan"` display event the
* moment submit_plan fires. That's a one-time markdown render into
* permanent history, so the user reads the full proposal above and
* the modal below stays a tight picker. The previous design (body
* rendered inside the modal with an aggressive line clamp) left users
* staring at "(25 more lines truncated)" and unable to approve safely.
*/
import { Box, Text } from "ink";
import React from "react";
import { SingleSelect } from "./Select.js";
export type PlanConfirmChoice = "approve" | "refine" | "cancel";
export interface PlanConfirmProps {
plan: string;
onChoose: (choice: PlanConfirmChoice) => void;
projectRoot?: string;
}
function PlanConfirmInner({ plan, onChoose }: PlanConfirmProps) {
// Crude signal for "the model left questions or risks for me" — the
// typical section headings. Triggers an extra hint toward the Refine
// option so users know where to answer them.
const hasOpenQuestions =
/^#{1,6}\s*(open[-\s]?questions?|risks?|unknowns?|assumptions?|unclear)/im.test(plan) ||
/^#{1,6}\s*(待确认|开放问题|风险|未知|假设|不确定)/im.test(plan);
return (
<Box flexDirection="column" borderStyle="round" borderColor="cyan" paddingX={1} marginY={1}>
<Box>
<Text bold color="cyan">
▸ plan proposed (full text above) — approve / refine / cancel
</Text>
</Box>
{hasOpenQuestions ? (
<Box marginTop={1}>
<Text color="yellow">
▲ the plan flags open questions or risks — pick{" "}
<Text bold>Refine / answer questions</Text> to write concrete answers before the model
moves on.
</Text>
</Box>
) : null}
<Box marginTop={1}>
<SingleSelect
initialValue={hasOpenQuestions ? "refine" : "approve"}
items={[
{
value: "approve",
label: "Approve and implement",
hint: "Exit plan mode. The model starts executing. You'll get a text input to add any last instructions (or just press Enter to skip).",
},
{
value: "refine",
label: "Refine / answer questions",
hint: "Stay in plan mode. Write answers, modifications, or critiques; the model revises and re-submits.",
},
{
value: "cancel",
label: "Cancel",
hint: "Exit plan mode. Drop the plan; the model won't implement it.",
},
]}
onSubmit={(v) => onChoose(v as PlanConfirmChoice)}
onCancel={() => onChoose("cancel")}
footer="[↑↓] navigate · [Enter] select · [Esc] cancel"
/>
</Box>
</Box>
);
}
// React.memo: parent App re-renders every 120ms while the global ticker
// is running (even with the live status rows hidden — context changes
// propagate). Unless props change, skip re-rendering the heavy Markdown
// subtree. Default shallow prop compare is fine — `plan` + `onChoose`
// identity + `projectRoot` are the only fields that change.
export const PlanConfirm = React.memo(PlanConfirmInner);
+91
View File
@@ -0,0 +1,91 @@
/**
* Inline text input shown after the user picks Approve or Refine in
* PlanConfirm. Collects free-form feedback before the loop resumes.
*
* Why both paths: the plan may contain open questions or risks the
* model asked the user to weigh in on. If the user just picks Approve
* with no chance to answer, the model implements against its own
* guesses. This input lets the user answer questions, pass last-minute
* constraints, or (on Refine) request concrete changes. Empty input is
* fine for Approve (skip straight to implement) and triggers a
* "ask the user clarifying questions" path for Refine.
*
* Kept minimal: single-line prompt, Enter to submit, Esc to return to
* the picker without resuming.
*/
import { Box, Text, useInput } from "ink";
import React, { useState } from "react";
export interface PlanRefineInputProps {
/**
* Which path the user is on. Approve = "implement with these last
* instructions"; refine = "revise the plan with this feedback".
* Drives the header + hint text so users know what kind of message
* they're writing.
*/
mode: "approve" | "refine";
/** Called with trimmed feedback. Empty string is allowed. */
onSubmit: (feedback: string) => void;
/** Called when the user presses Esc to return to the picker. */
onCancel: () => void;
}
export function PlanRefineInput({ mode, onSubmit, onCancel }: PlanRefineInputProps) {
const [value, setValue] = useState("");
useInput((input, key) => {
if (key.escape) {
onCancel();
return;
}
if (key.return) {
onSubmit(value.trim());
return;
}
if (key.backspace || key.delete) {
setValue((v) => v.slice(0, -1));
return;
}
// Filter out non-printable chars; accept ordinary text + CJK.
if (input && !key.ctrl && !key.meta) {
setValue((v) => v + input);
}
});
const title =
mode === "approve"
? "▸ approving — any last instructions or answers to open questions?"
: "▸ refining — what should the model change?";
const hint =
mode === "approve"
? "Answer questions the plan raised, add constraints, or just press Enter to approve as-is."
: "Describe what's wrong or missing, or answer questions the plan raised.";
const blankHint =
mode === "approve"
? " (Enter with blank = approve without extra instructions.)"
: " (Enter with blank = ask the model to list concrete questions.)";
return (
<Box flexDirection="column" borderStyle="round" borderColor="yellow" paddingX={1} marginY={1}>
<Box>
<Text bold color="yellow">
{title}
</Text>
</Box>
<Box marginTop={1}>
<Text dimColor>
{hint} Enter to send · Esc to return to the picker.
{value === "" ? blankHint : ""}
</Text>
</Box>
<Box marginTop={1}>
<Text>
<Text color="yellow">› </Text>
<Text>{value || " "}</Text>
<Text color="yellow">▍</Text>
</Text>
</Box>
</Box>
);
}
+93 -49
View File
@@ -1,6 +1,7 @@
import { Box, Text, useInput } from "ink";
import React, { useEffect, useState } from "react";
import { type MultilineKey, processMultilineKey } from "./multiline-keys.js";
import React, { useRef, useState } from "react";
import { type MultilineKey, lineAndColumn, processMultilineKey } from "./multiline-keys.js";
import { useTick } from "./ticker.js";
export interface PromptInputProps {
value: string;
@@ -11,19 +12,16 @@ export interface PromptInputProps {
}
/**
* Input box with multi-line composition support. Behaves like the
* old single-line prompt by default, but:
* - Ctrl+J inserts a newline (universal across terminals).
* - Shift+Enter inserts a newline (only on terminals that report
* the modifier via CSI-u — many don't).
* - `\<Enter>` at end of line acts as bash-style continuation —
* always works, even on terminals without modifier reporting.
* - Pasted multi-line text lands as-is instead of submitting on
* the first '\r'.
* Input box with real cursor support. ←/→ move one column, ↑/↓ move
* across lines in multi-line buffers, Ctrl+A / Ctrl+E jump to
* start/end of the current line. Backspace deletes before cursor,
* Delete deletes under cursor. Multi-line composition via Ctrl+J,
* Shift+Enter, or bash-style `\<Enter>`.
*
* No mid-string insertion cursor — edits happen at the end, like
* a readline prompt in raw mode. Simple, predictable, enough for
* 95% of prompts and any code paste.
* Cursor state lives locally. When the parent replaces `value` out
* of band (history recall, slash completion, setup wizard) the
* cursor jumps to end; the `lastLocalValueRef` guards distinguishes
* that case from our own edits.
*/
export function PromptInput({
value,
@@ -32,24 +30,29 @@ export function PromptInput({
disabled,
placeholder,
}: PromptInputProps) {
const [showCursor, setShowCursor] = useState(true);
// Blink the end-of-input cursor so it's visibly alive even when
// the user hasn't typed for a while. 500 ms matches a typical
// terminal cursor blink.
useEffect(() => {
if (disabled) {
setShowCursor(false);
return;
const [cursor, setCursor] = useState(value.length);
// Tracks the last `value` we ourselves produced via onChange. If the
// incoming `value` prop diverges from this, the parent (or some other
// source) replaced the buffer — we reset the cursor to end.
const lastLocalValueRef = useRef(value);
if (value !== lastLocalValueRef.current) {
lastLocalValueRef.current = value;
if (cursor !== value.length) {
// Conditional setState during render is the "derived state" pattern;
// React schedules the re-render and the else branch of the `if`
// prevents infinite loops.
setCursor(value.length);
}
setShowCursor(true);
const id = setInterval(() => setShowCursor((s) => !s), 500);
return () => clearInterval(id);
}, [disabled]);
}
// Shared ticker drives the cursor blink. Dividing the tick by 4 lands
// the visible on/off cycle around 480ms — standard cursor cadence.
const tick = useTick();
const showCursor = disabled ? false : Math.floor(tick / 4) % 2 === 0;
useInput(
(input, key) => {
const keyEvent: MultilineKey = {
const ke: MultilineKey = {
input,
return: key.return,
shift: key.shift,
@@ -66,30 +69,33 @@ export function PromptInput({
pageUp: key.pageUp,
pageDown: key.pageDown,
};
const action = processMultilineKey(value, keyEvent);
if (action.next !== null) onChange(action.next);
const action = processMultilineKey(value, cursor, ke);
if (action.next !== null) {
lastLocalValueRef.current = action.next;
onChange(action.next);
}
if (action.cursor !== null) {
setCursor(action.cursor);
}
if (action.submit) onSubmit(action.submitValue ?? value);
},
{ isActive: !disabled },
);
const effectivePlaceholder = disabled
? (placeholder ?? "…waiting for response…")
: (placeholder ?? "type a message, or /command · Ctrl+J for newline");
? (placeholder ?? "…waiting for response… · [Esc] to stop")
: (placeholder ?? "type a message, or /command · [Shift+Enter] / [Ctrl+J] newline");
const lines = value.length > 0 ? value.split("\n") : [""];
const borderColor = disabled ? "gray" : "cyan";
const { line: cursorLine, col: cursorCol } = lineAndColumn(value, cursor);
return (
<Box borderStyle="round" borderColor={borderColor} paddingX={1} flexDirection="column">
{lines.map((line, i) => {
const isLast = i === lines.length - 1;
const isFirst = i === 0;
const showPlaceholder = isFirst && value.length === 0;
// Line content never survives a re-keying here: the value buffer
// fully re-renders on every keystroke, so the array index IS the
// stable identity. Biome's rule targets list reordering, which
// doesn't apply to an append-only splits-by-newline view.
const isCursorLine = i === cursorLine;
return (
// biome-ignore lint/suspicious/noArrayIndexKey: stable by construction — lines are derived from `value.split("\n")` and never reordered
<Box key={i}>
@@ -100,21 +106,59 @@ export function PromptInput({
) : (
<Text dimColor>{" "}</Text>
)}
{/* When showing the placeholder, the cursor is at position 0 —
put it BEFORE the dimmed hint text so it visually matches
"you're about to type here," not "you typed the placeholder."
When showing real content, the cursor follows the last char
of the last line (append-only edit model). */}
{showPlaceholder && isLast && !disabled ? (
<Text color={borderColor}>{showCursor ? "▌" : " "}</Text>
) : null}
{showPlaceholder ? <Text dimColor>{effectivePlaceholder}</Text> : <Text>{line}</Text>}
{!showPlaceholder && isLast && !disabled ? (
<Text color={borderColor}>{showCursor ? "▌" : " "}</Text>
) : null}
{showPlaceholder ? (
<>
{isCursorLine && !disabled ? (
<Text color={borderColor}>{showCursor ? "▌" : " "}</Text>
) : null}
<Text dimColor>{effectivePlaceholder}</Text>
</>
) : isCursorLine && !disabled ? (
<LineWithCursor
line={line}
col={cursorCol}
showCursor={showCursor}
borderColor={borderColor}
/>
) : (
<Text>{line}</Text>
)}
</Box>
);
})}
</Box>
);
}
function LineWithCursor({
line,
col,
showCursor,
borderColor,
}: {
line: string;
col: number;
showCursor: boolean;
borderColor: "cyan" | "gray";
}) {
const before = line.slice(0, col);
const atCursor = line.slice(col, col + 1);
const after = line.slice(col + 1);
if (atCursor.length === 0) {
// Cursor sits past the last char of this line (end-of-line). Render
// a trailing block so the user sees where they're typing next.
return (
<>
<Text>{before}</Text>
<Text color={borderColor}>{showCursor ? "▌" : " "}</Text>
</>
);
}
return (
<>
<Text>{before}</Text>
<Text inverse={showCursor}>{atCursor}</Text>
<Text>{after}</Text>
</>
);
}
+1
View File
@@ -59,6 +59,7 @@ export function ReplayApp({ meta, pages }: ReplayAppProps) {
cacheHitRatio: cumStats.cacheHitRatio,
// Replay is read-only — no live last-turn prompt tokens to show.
lastPromptTokens: 0,
lastTurnCostUsd: 0,
};
const prefixHash =
+13
View File
@@ -28,6 +28,13 @@ export interface SingleSelectProps<V extends string> {
initialValue?: V;
onSubmit: (value: V) => void;
onCancel?: () => void;
/**
* Optional footer rendered dim beneath the list, e.g.
* `"↑/↓ navigate · Enter select · Esc cancel"`. Makes keyboard
* affordances discoverable — otherwise new users hit `y`/`n` and
* wonder why nothing happens.
*/
footer?: string;
}
export function SingleSelect<V extends string>({
@@ -35,6 +42,7 @@ export function SingleSelect<V extends string>({
initialValue,
onSubmit,
onCancel,
footer,
}: SingleSelectProps<V>) {
const initialIndex = Math.max(
0,
@@ -65,6 +73,11 @@ export function SingleSelect<V extends string>({
marker={i === index ? "▸" : " "}
/>
))}
{footer ? (
<Box marginTop={1}>
<Text dimColor>{footer}</Text>
</Box>
) : null}
</Box>
);
}
+72
View File
@@ -0,0 +1,72 @@
import { Box, Text } from "ink";
import React from "react";
import { SingleSelect } from "./Select.js";
export type SessionChoice = "resume" | "new" | "delete";
export interface SessionPickerProps {
sessionName: string;
messageCount: number;
/** mtime of the session file; used to render "last active Nh ago". */
lastActive: Date;
onChoose: (choice: SessionChoice) => void;
}
export function SessionPicker({
sessionName,
messageCount,
lastActive,
onChoose,
}: SessionPickerProps) {
return (
<Box flexDirection="column" marginY={1}>
<Box marginBottom={1}>
<Text bold color="cyan">
{`Session "${sessionName}" has ${messageCount} prior message${messageCount === 1 ? "" : "s"}`}
</Text>
<Text dimColor>{` · last active ${relativeTime(lastActive)}`}</Text>
</Box>
<SingleSelect
initialValue="new"
items={[
{
value: "new",
label: "Start new conversation",
hint: "Previous messages kept on disk; your turn starts fresh.",
},
{
value: "resume",
label: "Resume",
hint: `Continue where you left off (${messageCount} messages in context).`,
},
{
value: "delete",
label: "Delete and start new",
hint: "Wipes the session file irreversibly. Other sessions untouched.",
},
]}
onSubmit={(v) => onChoose(v as SessionChoice)}
/>
<Box marginTop={1}>
<Text dimColor>↑↓ to move · Enter to pick</Text>
</Box>
</Box>
);
}
/**
* "Nh ago" / "Nm ago" / "yesterday" style relative time. Deliberately
* coarse — the picker just needs a sense of "how stale is this session".
*/
function relativeTime(date: Date): string {
const ms = Date.now() - date.getTime();
const mins = Math.floor(ms / 60_000);
if (mins < 1) return "just now";
if (mins < 60) return `${mins}m ago`;
const hours = Math.floor(mins / 60);
if (hours < 24) return `${hours}h ago`;
const days = Math.floor(hours / 24);
if (days === 1) return "yesterday";
if (days < 7) return `${days}d ago`;
return date.toISOString().slice(0, 10);
}
+129
View File
@@ -0,0 +1,129 @@
import { Box, Text } from "ink";
import React from "react";
import { SingleSelect } from "./Select.js";
export type ShellConfirmChoice = "run_once" | "always_allow" | "deny";
export interface ShellConfirmProps {
command: string;
/**
* The prefix that would be persisted if the user picks
* "always allow". Typically the first 1-2 tokens of `command`.
*/
allowPrefix: string;
/**
* Which tool is asking. `run_background` spawns via JobRegistry and
* returns early; `run_command` (default) blocks until the process
* exits. Shown as a hint in the modal so the user knows whether
* approving will block the TUI or not.
*/
kind?: "run_command" | "run_background";
onChoose: (choice: ShellConfirmChoice) => void;
}
/**
* Modal-style approval for a shell command the model wants to run.
* Three choices:
* 1. Run once — execute this invocation, prefix NOT remembered.
* 2. Always allow — persist the prefix to `~/.reasonix/config.json`
* under this project so every future invocation with that prefix
* auto-runs.
* 3. Deny — tell the model the user refused.
* Arrow keys + Enter. No y/n hotkey — too easy to trigger by accident
* when the user was mid-typing a response.
*/
export function ShellConfirm({ command, allowPrefix, kind, onChoose }: ShellConfirmProps) {
const isBackground = kind === "run_background";
return (
<Box flexDirection="column" borderStyle="round" borderColor="yellow" paddingX={1} marginY={1}>
<Box>
<Text bold color="yellow">
{isBackground
? "▸ model wants to start a BACKGROUND process"
: "▸ model wants to run a shell command"}
</Text>
</Box>
{isBackground ? (
<Box>
<Text dimColor>
{" (long-running: dev server / watcher; keeps running after approval, /kill to stop)"}
</Text>
</Box>
) : null}
<Box>
<Text color="yellow" dimColor>
{"──────────────────────────────────────────"}
</Text>
</Box>
<Box marginTop={1}>
<Text>
<Text dimColor>{"$ "}</Text>
<Text color="cyan">{command}</Text>
</Text>
</Box>
<Box marginTop={1}>
<SingleSelect
initialValue="run_once"
items={[
{
value: "run_once",
label: "Run once",
hint: "Execute this command, don't remember it.",
},
{
value: "always_allow",
label: `Always allow "${allowPrefix}" in this project`,
hint: "Save the prefix to ~/.reasonix/config.json; future matches auto-run.",
},
{
value: "deny",
label: "Deny",
hint: "Tell the model the user refused; it will continue without this command.",
},
]}
onSubmit={(v) => onChoose(v as ShellConfirmChoice)}
onCancel={() => onChoose("deny")}
footer="[↑↓] navigate · [Enter] select · [Esc] deny"
/>
</Box>
</Box>
);
}
/**
* Pick the "always allow" prefix from a full command. Heuristic:
* - one-token commands ("ls", "pytest") → the token itself
* - multi-token → first two tokens for well-known wrappers
* (`npm install`, `git commit`, `cargo add`, `docker run` …)
* otherwise just the first token (covers `node <script>` where the
* second token is usually a file path specific to this invocation).
* Exported so tests can pin the heuristic.
*/
export function derivePrefix(command: string): string {
const tokens = command.trim().split(/\s+/).filter(Boolean);
if (tokens.length === 0) return "";
if (tokens.length === 1) return tokens[0]!;
const first = tokens[0]!;
const TWO_TOKEN_WRAPPERS = new Set([
"npm",
"npx",
"pnpm",
"yarn",
"bun",
"git",
"cargo",
"go",
"docker",
"kubectl",
"python",
"python3",
"deno",
"pip",
"pip3",
"make",
"rake",
"bundle",
"gem",
]);
return TWO_TOKEN_WRAPPERS.has(first) ? `${first} ${tokens[1]}` : first;
}
+108
View File
@@ -0,0 +1,108 @@
import { Box, Text } from "ink";
// biome-ignore lint/style/useImportType: tsconfig.jsx = "react" needs React in value scope for JSX compilation
import React from "react";
import type { SlashCommandSpec } from "./slash.js";
export interface SlashArgPickerProps {
/**
* When set, render a picker with these matches (filter already
* applied upstream). Null → not in picker mode; check `hintSpec`
* for a usage hint instead.
*/
matches: readonly string[] | null;
/** Highlighted row within `matches`. */
selectedIndex: number;
/**
* Spec of the command the user is typing args for. Used to render
* the header label ("/edit <file>") even when matches is empty or
* the caller wants a hint instead of a picker.
*/
spec: SlashCommandSpec;
/** What kind of arg guidance to render. */
kind: "picker" | "hint";
/** The user's partial input — shown in the "no matches" hint. */
partial: string;
}
/**
* Argument-level picker for a slash command. Mirrors the visual
* layout of SlashSuggestions / AtMentionSuggestions so the UI stays
* consistent across all three picker surfaces.
*/
export function SlashArgPicker({
matches,
selectedIndex,
spec,
kind,
partial,
}: SlashArgPickerProps): React.ReactElement | null {
// Hint mode: a single dim row explaining the argsHint + summary.
if (kind === "hint") {
return (
<Box paddingX={1}>
<Text dimColor>
{" "}
<Text bold>/{spec.cmd}</Text>
{spec.argsHint ? ` ${spec.argsHint}` : ""} — {spec.summary}
</Text>
</Box>
);
}
if (matches === null) return null;
if (matches.length === 0) {
return (
<Box flexDirection="column" paddingX={1}>
<Text dimColor>
{" "}
<Text bold>/{spec.cmd}</Text>
{spec.argsHint ? ` ${spec.argsHint}` : ""} — {spec.summary}
</Text>
<Text color="yellow"> no match for "{partial}" — keep typing, or Backspace to edit</Text>
</Box>
);
}
const MAX = 8;
const total = matches.length;
const windowStart =
total <= MAX ? 0 : Math.max(0, Math.min(selectedIndex - Math.floor(MAX / 2), total - MAX));
const shown = matches.slice(windowStart, windowStart + MAX);
const hiddenAbove = windowStart;
const hiddenBelow = total - windowStart - shown.length;
return (
<Box flexDirection="column" paddingX={1}>
<Text dimColor>
{" "}
<Text bold>/{spec.cmd}</Text>
{spec.argsHint ? ` ${spec.argsHint}` : ""} — {spec.summary}
</Text>
{hiddenAbove > 0 ? <Text dimColor> ↑ {hiddenAbove} more above</Text> : null}
{shown.map((value, i) => (
<ArgRow key={value} value={value} isSelected={windowStart + i === selectedIndex} />
))}
{hiddenBelow > 0 ? <Text dimColor> ↓ {hiddenBelow} more below</Text> : null}
<Text dimColor> [↑↓] navigate · [Tab]/[Enter] pick</Text>
</Box>
);
}
function ArgRow({ value, isSelected }: { value: string; isSelected: boolean }) {
const marker = isSelected ? "▸" : " ";
if (isSelected) {
return (
<Box>
<Text bold color="cyan">
{marker} {value}
</Text>
</Box>
);
}
return (
<Box>
<Text dimColor>
{marker} {value}
</Text>
</Box>
);
}
+1 -1
View File
@@ -51,7 +51,7 @@ export function SlashSuggestions({
<SuggestionRow key={spec.cmd} spec={spec} isSelected={windowStart + i === selectedIndex} />
))}
{hiddenBelow > 0 ? <Text dimColor> ↓ {hiddenBelow} more below</Text> : null}
<Text dimColor> ↑/↓ navigate · Tab or Enter to pick</Text>
<Text dimColor> [↑↓] navigate · [Tab]/[Enter] pick</Text>
</Box>
);
}
+461 -65
View File
@@ -1,7 +1,55 @@
import { Box, Text } from "ink";
import { Box, Text, useStdout } from "ink";
import React from "react";
import type { EditMode } from "../../config.js";
import { DEEPSEEK_CONTEXT_TOKENS, DEFAULT_CONTEXT_TOKENS } from "../../telemetry.js";
import type { SessionSummary } from "../../telemetry.js";
import { VERSION } from "../../version.js";
import { useTick } from "./ticker.js";
/**
* Cyan → blue → purple truecolor gradient for the REASONIX wordmark.
* Each char gets its own hex color — terminals that support 24-bit
* color (nearly all since 2016) render this as a smooth fade. Older
* 256-color terminals snap to nearest; 8-color fall all the way back
* to plain cyan via Ink's color pipeline, so the worst case is still
* legible.
*/
const WORDMARK_STYLES: ReadonlyArray<{ ch: string; color: string; isLogo: boolean }> = [
{ ch: "◈", color: "#5eead4", isLogo: true }, // teal — brand mark
{ ch: " ", color: "#5eead4", isLogo: false },
{ ch: "R", color: "#67e8f9", isLogo: false }, // cyan
{ ch: "E", color: "#7dd3fc", isLogo: false }, // sky
{ ch: "A", color: "#93c5fd", isLogo: false }, // blue
{ ch: "S", color: "#a5b4fc", isLogo: false }, // indigo
{ ch: "O", color: "#c4b5fd", isLogo: false }, // violet
{ ch: "N", color: "#d8b4fe", isLogo: false }, // purple
{ ch: "I", color: "#f0abfc", isLogo: false }, // fuchsia
{ ch: "X", color: "#f0abfc", isLogo: false }, // fuchsia
];
/**
* Gradient-filled, animated app wordmark. The `◈` brand mark breathes
* (bold on/off) once every ~1.6s when idle, ~600ms when the model is
* working, so a glance at the top of the screen tells you immediately
* whether the app is doing something. Letters' keys use the char+color
* pair (not an index) so React state attaches to the glyph itself;
* fine because WORDMARK_STYLES never reorders.
*/
function Wordmark({ busy }: { busy: boolean }) {
const tick = useTick();
// Slow pulse = 12 ticks (~1.4s). Busy pulse = 5 ticks (~600ms).
const period = busy ? 5 : 12;
const bright = Math.floor(tick / period) % 2 === 0;
return (
<Text>
{WORDMARK_STYLES.map((c) => (
<Text key={`${c.ch}-${c.color}`} color={c.color} bold={c.isLogo ? bright : true}>
{c.ch}
</Text>
))}
</Text>
);
}
export interface StatsPanelProps {
summary: SessionSummary;
@@ -9,6 +57,26 @@ export interface StatsPanelProps {
prefixHash: string;
harvestOn?: boolean;
branchBudget?: number;
/**
* Current `reasoning_effort` cap. Shown as a green "· max" / yellow
* "· high" tag in the header so the user always sees which tier the
* next turn will use. Absent/undefined hides the tag (e.g. before
* the loop is constructed).
*/
reasoningEffort?: "high" | "max";
/**
* True when `reasonix code` is currently running in read-only Plan
* Mode. Surfaced as a red "PLAN" tag in the panel header so the user
* can tell at a glance that edits are gated behind submit_plan +
* approval.
*/
planMode?: boolean;
/**
* Edit-gate mode. Surfaced as a small pill in the header so the user
* can see at a glance whether edits will be queued for review or
* applied immediately. Omitted in chat (non-code) mode.
*/
editMode?: EditMode;
/**
* Account balance fetched once at launch (and optionally refreshed
* per-turn by the TUI). `null` or absent hides the balance cell
@@ -18,96 +86,424 @@ export interface StatsPanelProps {
* with USD both see "getting low."
*/
balance?: { currency: string; total: number } | null;
/**
* Published npm version newer than VERSION. Rendered as a yellow
* "· update: X" nudge in the panel header. `null` / `undefined`
* hides the nudge (offline launch, already up to date, or check
* still in flight).
*/
updateAvailable?: string | null;
/**
* True when the loop is currently mid-turn — drives the wordmark's
* "busy breathing" animation. Visual signal that the app is thinking,
* visible at a glance from anywhere on screen.
*/
busy?: boolean;
/**
* /pro is queued — the next turn will run on v4-pro regardless of
* `model`. Rendered as a yellow `⇧ pro armed` pill in the header so
* the user has a clear "this turn will be expensive" signal before
* submitting their message.
*/
proArmed?: boolean;
/**
* The CURRENT turn is running on v4-pro because the failure-
* escalation threshold fired mid-turn. Rendered as a red `⇧ pro
* escalated` pill. Clears at turn end.
*/
escalated?: boolean;
}
/**
* Terminal width under which we switch from one-line metrics to a
* stacked layout. Below 120 cols the wide version wraps mid-number
* and the parens ("in $X · out $Y") get split across lines — which
* looks broken. Stacking costs one row but stays readable on every
* SSH / split-pane case we've hit.
*/
const NARROW_BREAKPOINT = 120;
/**
* Cache-hit ratio is always zero on turn 1 (there's literally no cache
* to hit yet). Showing that as red "0.0%" is a false alarm — new users
* read it as "something is broken." We suppress the gradient until a
* few turns have landed; by turn 4 the cache has had time to warm up.
*/
const COLD_START_TURNS = 3;
export function StatsPanel({
summary,
model,
prefixHash,
harvestOn,
branchBudget,
reasoningEffort,
planMode,
editMode,
balance,
updateAvailable,
busy,
proArmed,
escalated,
}: StatsPanelProps) {
const hitPct = (summary.cacheHitRatio * 100).toFixed(1);
const hitColor =
summary.cacheHitRatio >= 0.7 ? "green" : summary.cacheHitRatio >= 0.4 ? "yellow" : "red";
const branchOn = (branchBudget ?? 1) > 1;
const ctxMax = DEEPSEEK_CONTEXT_TOKENS[model] ?? DEFAULT_CONTEXT_TOKENS;
const ctxRatio = summary.lastPromptTokens / ctxMax;
const ctxColor = ctxRatio >= 0.8 ? "red" : ctxRatio >= 0.5 ? "yellow" : undefined;
const { stdout } = useStdout();
const columns = stdout?.columns ?? 80;
const narrow = columns < NARROW_BREAKPOINT;
// Cold-start: first few turns render cache+cost muted so a 0.0% hit
// rate on turn 1 doesn't look like an error. Once the cache has
// actually had a chance to build, we flip to the live gradient.
const coldStart = summary.turns <= COLD_START_TURNS;
return (
<Box borderStyle="round" borderColor="cyan" flexDirection="column" paddingX={1}>
<Box justifyContent="space-between">
<Text>
<Text color="cyan" bold>
Reasonix
</Text>
<Text dimColor> · model </Text>
<Text color="yellow">{model}</Text>
<Text dimColor> · prefix </Text>
<Text dimColor>{prefixHash}</Text>
{harvestOn ? <Text color="magenta"> · harvest</Text> : null}
{branchOn ? <Text color="blue"> · branch{branchBudget}</Text> : null}
</Text>
<Text dimColor>turns {summary.turns} · type /help</Text>
</Box>
<Box marginTop={1} gap={3}>
<Text>
<Text dimColor>cache hit </Text>
<Text color={hitColor} bold>
{hitPct}%
</Text>
</Text>
<Text>
<Text dimColor>cost </Text>
<Text color="green" bold>
${summary.totalCostUsd.toFixed(6)}
</Text>
<Text dimColor>
{" (in "}${summary.totalInputCostUsd.toFixed(6)}
{" · out "}${summary.totalOutputCostUsd.toFixed(6)}
{")"}
</Text>
</Text>
{summary.lastPromptTokens > 0 ? (
<Text>
<Text dimColor>ctx </Text>
<Text color={ctxColor} bold={ctxColor !== undefined}>
{formatTokens(summary.lastPromptTokens)}/{formatTokens(ctxMax)}
</Text>
<Text dimColor> ({(ctxRatio * 100).toFixed(0)}%)</Text>
{ctxRatio >= 0.8 ? (
<Text color="red" bold>
{" "}
· /compact
</Text>
) : null}
<Header
model={model}
prefixHash={prefixHash}
harvestOn={harvestOn}
branchOn={branchOn}
branchBudget={branchBudget ?? 1}
reasoningEffort={reasoningEffort}
planMode={planMode}
editMode={editMode}
turns={summary.turns}
updateAvailable={updateAvailable}
narrow={narrow}
busy={busy ?? false}
proArmed={proArmed ?? false}
escalated={escalated ?? false}
/>
{narrow ? (
<StackedMetrics
summary={summary}
ctxRatio={ctxRatio}
ctxMax={ctxMax}
balance={balance}
coldStart={coldStart}
/>
) : (
<InlineMetrics
summary={summary}
ctxRatio={ctxRatio}
ctxMax={ctxMax}
balance={balance}
coldStart={coldStart}
/>
)}
</Box>
);
}
function Header({
model,
prefixHash,
harvestOn,
branchOn,
branchBudget,
reasoningEffort,
planMode,
editMode,
turns,
updateAvailable,
narrow,
busy,
proArmed,
escalated,
}: {
model: string;
prefixHash: string;
harvestOn?: boolean;
branchOn: boolean;
branchBudget: number;
reasoningEffort?: "high" | "max";
planMode?: boolean;
editMode?: EditMode;
turns: number;
updateAvailable?: string | null;
narrow: boolean;
busy: boolean;
proArmed: boolean;
escalated: boolean;
}) {
return (
<Box justifyContent="space-between">
<Box>
<Wordmark busy={busy} />
<Text dimColor>{` v${VERSION}`}</Text>
<Text dimColor> · </Text>
<Text color="yellow">{model}</Text>
{narrow ? null : (
<>
<Text dimColor> · </Text>
<Text dimColor>{prefixHash}</Text>
</>
)}
{harvestOn ? <Text color="magenta"> · harvest</Text> : null}
{branchOn ? <Text color="blue"> · branch{branchBudget}</Text> : null}
{reasoningEffort === "max" ? <Text color="green"> · max</Text> : null}
{reasoningEffort === "high" ? <Text color="yellow"> · high</Text> : null}
{planMode ? (
<Text color="red" bold>
{" · PLAN"}
</Text>
) : null}
{balance ? (
<Text>
<Text dimColor>balance </Text>
<Text color={balance.total < 1 ? "red" : balance.total < 5 ? "yellow" : "green"} bold>
{balance.currency === "USD" ? "$" : ""}
{balance.total.toFixed(2)}
{balance.currency !== "USD" ? ` ${balance.currency}` : ""}
</Text>
{editMode ? (
<Text color={editMode === "auto" ? "magenta" : "cyan"} bold>
{editMode === "auto" ? " · AUTO" : " · review"}
</Text>
) : null}
{escalated ? (
<Text color="red" bold>
{" · ⇧ pro escalated"}
</Text>
) : proArmed ? (
<Text color="yellow" bold>
{" · ⇧ pro armed"}
</Text>
) : null}
</Box>
<Text>
{updateAvailable ? (
<Text color="yellow" bold>{`update: ${updateAvailable} · `}</Text>
) : null}
<Text dimColor>{narrow ? `turn ${turns}` : `turn ${turns} · /help`}</Text>
</Text>
</Box>
);
}
/**
* Compact integer formatter: 1234 → "1.2k", 131072 → "131k". Keeps the
* panel narrow enough to fit on 80-col terminals even when the context
* is near full.
* Wide-terminal layout (≥120 cols): single metrics row. Matches the
* original panel, just with calmer spacing and the cold-start
* treatment folded in.
*/
function InlineMetrics({
summary,
ctxRatio,
ctxMax,
balance,
coldStart,
}: {
summary: SessionSummary;
ctxRatio: number;
ctxMax: number;
balance?: { currency: string; total: number } | null;
coldStart: boolean;
}) {
return (
<Box marginTop={1} gap={3}>
<ContextCell ratio={ctxRatio} promptTokens={summary.lastPromptTokens} ctxMax={ctxMax} />
<CacheCell hitRatio={summary.cacheHitRatio} coldStart={coldStart} turns={summary.turns} />
<CostCell summary={summary} coldStart={coldStart} />
{balance ? <BalanceCell balance={balance} /> : null}
</Box>
);
}
/**
* Narrow-terminal layout (<120 cols): one metric per line, in priority
* order (ctx → balance → cache → cost). Order matters because users
* scanning a cramped terminal want "am I about to hit a wall?" answered
* first; dollars spent comes later.
*/
function StackedMetrics({
summary,
ctxRatio,
ctxMax,
balance,
coldStart,
}: {
summary: SessionSummary;
ctxRatio: number;
ctxMax: number;
balance?: { currency: string; total: number } | null;
coldStart: boolean;
}) {
return (
<Box marginTop={1} flexDirection="column">
<ContextCell
ratio={ctxRatio}
promptTokens={summary.lastPromptTokens}
ctxMax={ctxMax}
showBar
/>
{balance ? <BalanceCell balance={balance} /> : null}
<CacheCell hitRatio={summary.cacheHitRatio} coldStart={coldStart} turns={summary.turns} />
<CostCell summary={summary} coldStart={coldStart} />
</Box>
);
}
function ContextCell({
ratio,
promptTokens,
ctxMax,
showBar,
}: {
ratio: number;
promptTokens: number;
ctxMax: number;
showBar?: boolean;
}) {
if (promptTokens === 0) {
return (
<Text>
<Text dimColor>ctx </Text>
<Text dimColor>— (no turns yet)</Text>
</Text>
);
}
const color = ratio >= 0.8 ? "red" : ratio >= 0.6 ? "yellow" : "green";
const pct = Math.round(ratio * 100);
return (
<Text>
<Text dimColor>ctx </Text>
{showBar ? <Bar ratio={ratio} color={color} /> : null}
{showBar ? <Text> </Text> : null}
<Text color={color} bold>
{formatTokens(promptTokens)}/{formatTokens(ctxMax)}
</Text>
<Text dimColor> ({pct}%)</Text>
{ratio >= 0.8 ? (
<Text color="red" bold>
{" · /compact"}
</Text>
) : null}
</Text>
);
}
function CacheCell({
hitRatio,
coldStart,
turns,
}: {
hitRatio: number;
coldStart: boolean;
turns: number;
}) {
const pct = (hitRatio * 100).toFixed(1);
if (turns === 0) {
return (
<Text>
<Text dimColor>cache </Text>
<Text dimColor>—</Text>
</Text>
);
}
if (coldStart) {
return (
<Text>
<Text dimColor>cache </Text>
<Text dimColor>{pct}% </Text>
<Text dimColor italic>
(cold start)
</Text>
</Text>
);
}
const color = hitRatio >= 0.7 ? "green" : hitRatio >= 0.4 ? "yellow" : "red";
return (
<Text>
<Text dimColor>cache </Text>
<Text color={color} bold>
{pct}%
</Text>
</Text>
);
}
/**
* Color thresholds. Per-turn and session cumulative scale roughly 10×
* apart — a $0.20 single turn should feel just as warn-worthy as a $2
* session total. Values are rough "notice this" points, not hard caps.
*/
function turnCostColor(cost: number): "green" | "yellow" | "red" | undefined {
if (cost <= 0) return undefined;
if (cost >= 0.2) return "red";
if (cost >= 0.05) return "yellow";
return "green";
}
function sessionCostColor(cost: number): "green" | "yellow" | "red" | undefined {
if (cost <= 0) return undefined;
if (cost >= 5) return "red";
if (cost >= 0.5) return "yellow";
return "green";
}
function CostCell({
summary,
coldStart,
}: {
summary: SessionSummary;
coldStart: boolean;
}) {
if (summary.turns === 0) {
return (
<Text>
<Text dimColor>cost </Text>
<Text dimColor>—</Text>
</Text>
);
}
// The first turn is unavoidably a cache-miss (nothing to hit),
// so the dollar figure is front-loaded. Muting it during the
// cold-start window keeps the "expensive first turn" from
// reading as "something is wrong."
const turnColor = coldStart ? undefined : turnCostColor(summary.lastTurnCostUsd);
const sessionColor = coldStart ? undefined : sessionCostColor(summary.totalCostUsd);
return (
<Text>
<Text dimColor>turn </Text>
<Text color={turnColor} bold={!coldStart} dimColor={coldStart}>
${summary.lastTurnCostUsd.toFixed(4)}
</Text>
<Text dimColor>{" · session "}</Text>
<Text color={sessionColor} bold={!coldStart} dimColor={coldStart}>
${summary.totalCostUsd.toFixed(4)}
</Text>
</Text>
);
}
function BalanceCell({ balance }: { balance: { currency: string; total: number } }) {
const color = balance.total < 1 ? "red" : balance.total < 5 ? "yellow" : "green";
return (
<Text>
<Text dimColor>balance </Text>
<Text color={color} bold>
{balance.currency === "USD" ? "$" : ""}
{balance.total.toFixed(2)}
{balance.currency !== "USD" ? ` ${balance.currency}` : ""}
</Text>
</Text>
);
}
/**
* Unicode progress bar for the narrow layout's context cell. 10 cells
* wide — narrow terminals are already cramped, and the bar is just a
* visual cue for the percentage next to it, not the primary readout.
*/
function Bar({ ratio, color }: { ratio: number; color: "green" | "yellow" | "red" }) {
const cells = 10;
const filled = Math.max(0, Math.min(cells, Math.round(ratio * cells)));
const bar = "█".repeat(filled) + "░".repeat(cells - filled);
return <Text color={color}>{bar}</Text>;
}
/**
* Compact token formatter using binary K (÷1024): 1234 → "1.2K",
* 131072 → "128K". Matches DeepSeek's marketing label of "128K context
* length" — showing "131k" confused users (the actual limit is
* 128×1024 = 131,072 tokens, but the doc consistently says "128K").
* Uppercase K signals binary-K to anyone who notices.
*/
function formatTokens(n: number): string {
if (n < 1000) return String(n);
const k = n / 1000;
return k >= 100 ? `${k.toFixed(0)}k` : `${k.toFixed(1)}k`;
if (n < 1024) return String(n);
const k = n / 1024;
return k >= 100 ? `${k.toFixed(0)}K` : `${k.toFixed(1)}K`;
}
+39
View File
@@ -0,0 +1,39 @@
/**
* Bash-mode (`!cmd`) prefix parsing.
*
* A `!` at the start of the user's input means "run this as a shell
* command in the sandbox root, and put both the command and its output
* into the conversation so the model sees it next turn." Same idea as
* Claude Code's `!` prefix — faster than round-tripping through the
* model just to cat a file or check git status.
*
* Design choice: user-typed `!` commands skip the allowlist. The
* allowlist exists to bound what the MODEL can do with run_command;
* the user typing `!git push` by hand is explicit consent. If a user
* wants stricter gating they can set `REASONIX_BANG_CONFIRM=1` in a
* future iteration.
*/
/**
* Return the command portion of a `!`-prefixed input, or `null` if
* the text isn't a bang invocation. Trims leading/trailing whitespace
* from the command body. `!` alone (or `!` followed by only whitespace)
* returns `null` — no command to run.
*/
export function detectBangCommand(text: string): string | null {
if (!text.startsWith("!")) return null;
const body = text.slice(1).trim();
if (!body) return null;
return body;
}
/**
* Format a bang command + its output into a single user-role message
* body that the model will see on the next turn. The `[!cmd]` header
* marks the run explicitly so the model can distinguish
* user-typed shell output from its own `run_command` tool results
* (which are `role: tool`, different message shape entirely).
*/
export function formatBangUserMessage(cmd: string, output: string): string {
return `[!${cmd}]\n${output}`;
}
+109
View File
@@ -0,0 +1,109 @@
import { formatAllBlockDiffs } from "../../code/diff-preview.js";
import type { ApplyResult, EditBlock, EditSnapshot } from "../../code/edit-blocks.js";
/**
* One batch of edits that actually landed on disk — durable enough for
* `/undo`, `/history`, and `/show` within a session. Not persisted
* across restarts: restoring pre-apply content from a process that
* crashed last week is git's job, not ours.
*/
export interface EditHistoryEntry {
/** Sequence number within the session, stable for `/show <id>`. */
id: number;
/** Epoch ms when the entry was opened (first edit landed). */
at: number;
/**
* Short tag for what produced the batch — "auto" (auto-mode tool
* call), "auto-text" (auto-mode text SEARCH/REPLACE at turn end),
* "review-apply" (user-approved modal edit or /apply flush).
*/
source: string;
/** Edit blocks included in this batch, in arrival order. */
blocks: EditBlock[];
/** Per-block outcome — some may be "not-found" if SEARCH drifted. */
results: ApplyResult[];
/**
* First-snapshot-per-path wins: this is what `/undo` restores to.
* Deduped so multi-edit turns still roll back to pre-turn state.
*/
snapshots: EditSnapshot[];
/**
* Paths within this entry that have already been reverted (via
* `/undo <id>`, `/undo <id> <path>`, or the newest-non-undone /undo
* shortcut). Per-path instead of entry-level so a batch can be
* partially undone — user reverts src/foo.ts out of a 3-file batch
* without rolling back the other two.
*/
undoneFiles: Set<string>;
}
/** True when every path in the entry has been undone. */
export function isEntryFullyUndone(e: EditHistoryEntry): boolean {
return e.snapshots.length > 0 && e.snapshots.every((s) => e.undoneFiles.has(s.path));
}
/** Per-entry three-state status label for display. */
export function entryStatus(e: EditHistoryEntry): "applied" | "UNDONE" | "PARTIAL" {
if (e.undoneFiles.size === 0) return "applied";
if (isEntryFullyUndone(e)) return "UNDONE";
return "PARTIAL";
}
/**
* Render a batch of SEARCH/REPLACE application results as one
* human-scannable info line per edit. Prefixes denote status so the
* line reads well even without color (e.g. when piped to a log file
* or stripped for screenshots):
* ✓ applied src/foo.ts
* ✓ created src/new.ts
* ✗ not-found src/bar.ts (SEARCH text does not match…)
*/
export function formatEditResults(results: ApplyResult[]): string {
const lines = results.map((r) => {
const mark = r.status === "applied" || r.status === "created" ? "✓" : "✗";
const detail = r.message ? ` (${r.message})` : "";
return ` ${mark} ${r.status.padEnd(11)} ${r.path}${detail}`;
});
const ok = results.filter((r) => r.status === "applied" || r.status === "created").length;
const total = results.length;
const header = `▸ edit blocks: ${ok}/${total} applied — /undo to roll back, or \`git diff\` to review`;
return [header, ...lines].join("\n");
}
/**
* Pending-edits preview shown after each assistant turn that proposed
* changes. Per-block path header + ±line-count, then a unified-diff-
* style preview (context trimmed to 2 lines each side, total capped
* at 20 lines per block). Users can eyeball what's about to land
* BEFORE pressing `y` — the old summary-only view was a common
* mistake surface.
*/
export function formatPendingPreview(blocks: EditBlock[]): string {
const header = `▸ ${blocks.length} pending edit block(s) — /apply (or y) to commit · /discard (or n) to drop`;
const diffLines = formatAllBlockDiffs(blocks);
return [header, ...diffLines].join("\n");
}
/**
* Per-file rows for the multi-level `/undo` output, without the
* single-batch header (the caller prepends its own).
*/
export function formatUndoRows(results: ApplyResult[]): string[] {
return results.map((r) => {
const mark = r.status === "applied" ? "✓" : "✗";
const detail = r.message ? ` (${r.message})` : "";
return ` ${mark} ${r.path}${detail}`;
});
}
export function describeRepair(repair: {
scavenged: number;
truncationsFixed: number;
stormsBroken: number;
}): string {
const parts: string[] = [];
if (repair.scavenged) parts.push(`scavenged ${repair.scavenged}`);
if (repair.truncationsFixed) parts.push(`repaired ${repair.truncationsFixed} truncation`);
if (repair.stormsBroken) parts.push(`broke ${repair.stormsBroken} storm`);
return parts.length ? `[repair] ${parts.join(", ")}` : "";
}
+380 -57
View File
@@ -14,6 +14,8 @@
* show the expression verbatim; terminals don't do math fonts anyway.
*/
import { readFileSync, statSync } from "node:fs";
import { isAbsolute, join } from "node:path";
import { Box, Text } from "ink";
import React from "react";
@@ -144,10 +146,135 @@ export function stripMath(s: string): string {
);
}
/** Split a single line into styled segments for bold / italic / inline code. */
const INLINE_RE = /(\*\*([^*\n]+?)\*\*|`([^`\n]+?)`|(?<![*\w])\*([^*\n]+?)\*(?!\w))/g;
/**
* Citation links: `[text](url)` where url either points outside the repo
* (rendered as a plain external link) or resolves to a file/line in the
* project (rendered as a validated citation — broken citations turn
* red so the user can spot model hallucinations at a glance). The point
* is: the model is encouraged to ground every codebase claim in a
* link, and Reasonix surfaces broken links instead of silently letting
* fabrications past.
*/
export type CitationStatus = { ok: true } | { ok: false; reason: string };
export type CitationMap = Map<string, CitationStatus>;
function InlineMd({ text }: { text: string }) {
interface CitationParts {
path: string;
startLine?: number;
endLine?: number;
}
export function isExternalUrl(url: string): boolean {
return /^[a-z][a-z0-9+.-]*:\/\//i.test(url) || url.startsWith("mailto:") || url.startsWith("//");
}
export function parseCitationUrl(url: string): CitationParts | null {
const trimmed = url.trim();
if (!trimmed) return null;
// GitHub-style anchor: foo.ts#L42 or foo.ts#L42-L58
let m = trimmed.match(/^(.+?)#L(\d+)(?:-L?(\d+))?$/);
if (m) {
return {
path: m[1] ?? "",
startLine: Number(m[2]),
endLine: m[3] ? Number(m[3]) : undefined,
};
}
// Colon-style: foo.ts:42 or foo.ts:42-58
m = trimmed.match(/^(.+?):(\d+)(?:-(\d+))?$/);
if (m) {
return {
path: m[1] ?? "",
startLine: Number(m[2]),
endLine: m[3] ? Number(m[3]) : undefined,
};
}
return { path: trimmed };
}
export function validateCitation(url: string, projectRoot: string): CitationStatus {
const parts = parseCitationUrl(url);
if (!parts || !parts.path) return { ok: false, reason: "empty path" };
// Strip a leading `/` or `\\`. Models habitually write `/foo.ts`
// meaning "project-root relative" — Aider / Claude-Code convention —
// rather than POSIX root-absolute. A literal absolute path is still
// reachable as `C:\foo` on Windows or once the strip drops the slash
// and Node's `isAbsolute` correctly rejects what's left. Real unix
// absolute references like `/etc/hosts` in a code citation are vanishingly
// rare — if anyone needs one we can revisit.
const normalized = parts.path.replace(/^[/\\]+/, "");
const fullPath = isAbsolute(normalized) ? normalized : join(projectRoot, normalized);
let stat: ReturnType<typeof statSync>;
try {
stat = statSync(fullPath);
} catch {
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" };
}
if (parts.startLine < 1 || parts.startLine > lineCount) {
return { ok: false, reason: `line ${parts.startLine} > ${lineCount}` };
}
if (parts.endLine !== undefined) {
if (parts.endLine < parts.startLine || parts.endLine > lineCount) {
return { ok: false, reason: `range end ${parts.endLine} invalid` };
}
}
return { ok: true };
}
/**
* Pre-scan rendered text for every `[text](url)` link, validate the
* citation-shaped ones, and cache the result. Done once per Markdown
* mount so InlineMd doesn't re-stat the filesystem on every keystroke
* during streaming. External links short-circuit (no fs work).
*/
export function collectCitations(text: string, projectRoot: string): CitationMap {
const map: CitationMap = new Map();
const re = /\[([^\]\n]+)\]\(([^)\n]+)\)/g;
for (const m of text.matchAll(re)) {
const url = m[2] ?? "";
if (!url || isExternalUrl(url)) continue;
if (map.has(url)) continue;
map.set(url, validateCitation(url, projectRoot));
}
return map;
}
/**
* Split a single line into styled segments for bold / italic / inline
* code / links.
*
* Link group is FIRST so `[text](url)` with markup-looking URL chars
* doesn't get partially eaten by the bold/code branches.
*
* Triple-backtick (```…```) runs are matched BEFORE the single-backtick
* case so a one-line code span like `​``bash echo hi``​` is captured
* whole instead of the single-backtick regex greedily eating the
* middle and leaving two stray backticks on each side (what 0.4.15
* users saw when the model emitted `​``bash …``​` on the same line as
* prose). Content may contain single backticks but not newlines —
* multi-line fenced code is a block-level concern handled in
* `parseBlocks`.
*/
const INLINE_RE =
/(\[([^\]\n]+)\]\(([^)\n]+)\)|\*\*([^*\n]+?)\*\*|```([^\n]+?)```|`([^`\n]+?)`|(?<![*\w])\*([^*\n]+?)\*(?!\w))/g;
function InlineMd({
text,
padTo,
citations,
}: {
text: string;
padTo?: number;
citations?: CitationMap;
}) {
const parts: React.ReactNode[] = [];
let last = 0;
let idx = 0;
@@ -156,33 +283,106 @@ function InlineMd({ text }: { text: string }) {
if (start > last) {
parts.push(<Text key={`t${idx++}`}>{text.slice(last, start)}</Text>);
}
if (m[2] !== undefined) {
parts.push(
<Text key={`b${idx++}`} bold>
{m[2]}
</Text>,
);
} else if (m[3] !== undefined) {
parts.push(
<Text key={`c${idx++}`} color="yellow">
{m[3]}
</Text>,
);
// Groups, in the order they appear in INLINE_RE:
// m[2] = link text m[3] = link url
// m[4] = bold content (inside ** **)
// m[5] = triple-backtick content (strip leading lang tag)
// m[6] = single-backtick inline code
// m[7] = italic content (inside * *)
if (m[2] !== undefined && m[3] !== undefined) {
const linkText = m[2];
const url = m[3];
if (isExternalUrl(url)) {
parts.push(
<Text key={`l${idx++}`} color="blue" underline>
{linkText}
</Text>,
);
} else {
const status = citations?.get(url);
if (status && !status.ok) {
parts.push(
<Text key={`l${idx++}`} color="red" strikethrough>
{`${linkText} ✗`}
</Text>,
);
} else {
parts.push(
<Text key={`l${idx++}`} color="cyan" underline>
{linkText}
</Text>,
);
}
}
} else if (m[4] !== undefined) {
parts.push(
<Text key={`i${idx++}`} italic>
<Text key={`b${idx++}`} bold>
{m[4]}
</Text>,
);
} else if (m[5] !== undefined) {
// One-line fenced span: ```bash echo hi``` → drop the "bash "
// language tag so the user doesn't see it rendered in code color.
const stripped = m[5].replace(/^(\w+)\s+/, "");
parts.push(
<Text key={`c${idx++}`} color="yellow">
{stripped}
</Text>,
);
} else if (m[6] !== undefined) {
parts.push(
<Text key={`c${idx++}`} color="yellow">
{m[6]}
</Text>,
);
} else if (m[7] !== undefined) {
parts.push(
<Text key={`i${idx++}`} italic>
{m[7]}
</Text>,
);
}
last = start + m[0].length;
}
if (last < text.length) {
parts.push(<Text key={`t${idx++}`}>{text.slice(last)}</Text>);
}
// Trailing pad — used by table cells so column widths line up after
// the inline markup is rendered (markup chars like `**` and `` ` ``
// are invisible in output, so naive `pad(rawText, width)` over-pads
// styled cells and the columns drift out of alignment).
if (padTo !== undefined) {
const seen = visibleWidth(text);
if (seen < padTo) {
parts.push(<Text key={`pad${idx++}`}>{" ".repeat(padTo - seen)}</Text>);
}
}
return <Text>{parts}</Text>;
}
/**
* Strip inline markdown markers (**, _, single + triple backtick) so the
* remaining text reflects what the user actually SEES on screen. Used
* to compute correct column widths for table cells where the raw cell
* length includes invisible markup chars.
*/
export function stripInlineMarkup(s: string): string {
return s
.replace(/\[([^\]\n]+)\]\(([^)\n]+)\)/g, "$1")
.replace(/\*\*([^*\n]+?)\*\*/g, "$1")
.replace(/```([^\n]+?)```/g, (_m, c: string) => c.replace(/^(\w+)\s+/, ""))
.replace(/`([^`\n]+?)`/g, "$1")
.replace(/(?<![*\w])\*([^*\n]+?)\*(?!\w)/g, "$1");
}
/**
* Display width AFTER stripping inline markup. The visible-on-screen
* column width — what padding decisions should be based on.
*/
export function visibleWidth(s: string): number {
return displayWidth(stripInlineMarkup(s));
}
interface ParagraphBlock {
kind: "paragraph";
text: string;
@@ -250,6 +450,11 @@ export function parseBlocks(raw: string): Block[] {
let codeBuf: string[] = [];
let listBuf: BulletBlock | null = null;
// Fence length of the currently-open code block so a block opened
// with ````` closes only on `````, matching GFM. Empty when we're
// not in code mode.
let codeFence = "";
const flushPara = () => {
if (para.length) {
out.push({ kind: "paragraph", text: para.join(" ") });
@@ -307,22 +512,51 @@ export function parseBlocks(raw: string): Block[] {
}
}
const fence = line.match(/^```(\w*)/);
if (fence) {
if (inCode) {
out.push({ kind: "code", lang: codeLang, text: codeBuf.join("\n") });
codeBuf = [];
codeLang = "";
inCode = false;
} else {
// Fenced code block (GFM). The fence is 3+ backticks, may have up
// to 3 leading spaces, and carries an optional language tag. A
// closing fence must be the SAME backtick run length or longer.
//
// Two paths:
// a) Fence on its own line → multi-line block, accumulate until
// a matching close fence.
// b) Fence opens AND closes on the same line (e.g.
// `​``bash echo hi``​`) → emit as a one-line code block so
// the inline parser doesn't half-eat the backticks.
if (!inCode) {
const open = line.match(/^ {0,3}(`{3,})(\w*)\s*(.*)$/);
if (open) {
const fence = open[1]!;
const lang = open[2] ?? "";
const rest = open[3] ?? "";
const closeOnSame = rest.match(new RegExp(`^(.*?)${fence}\\s*$`));
if (closeOnSame) {
flushPara();
flushList();
out.push({ kind: "code", lang, text: (closeOnSame[1] ?? "").trim() });
continue;
}
flushPara();
flushList();
inCode = true;
codeLang = fence[1] ?? "";
codeLang = lang;
codeFence = fence;
// Anything after the opening fence on the SAME line is
// still body content (rare but legal).
if (rest.length > 0) codeBuf.push(rest);
continue;
}
} else {
// In code mode — check for closing fence. Same indent rules as
// opening, and the backtick run must be at least as long.
const close = line.match(/^ {0,3}(`{3,})\s*$/);
if (close && close[1]!.length >= codeFence.length) {
out.push({ kind: "code", lang: codeLang, text: codeBuf.join("\n") });
codeBuf = [];
codeLang = "";
codeFence = "";
inCode = false;
continue;
}
continue;
}
if (inCode) {
codeBuf.push(rawLine);
continue;
}
@@ -348,22 +582,79 @@ export function parseBlocks(raw: string): Block[] {
continue;
}
// Table detection: a line with at least one `|` where the NEXT
// line looks like a GFM separator (`| --- | --- |` or any mix of
// pipes + dashes + colons + spaces). Both the header row and the
// separator need to be present — a bare pipe in prose shouldn't
// trigger the table path.
if (line.includes("|")) {
// Box-drawing frame detection: top edge `┌────┐`, body lines that
// each begin and end with `│`, bottom edge `└────┘`. Models love to
// draw decorative frames around code snippets and flow charts using
// these characters; without this branch, every body line gets
// word-wrapped by Ink and the frame turns into garbage. Rendering
// the inner content as a code block preserves the fixed-width
// layout the model intended AND gives it a real border via the
// existing code-block renderer. Only triggers OUTSIDE code mode
// (where `inCode` is false) so a literal box-drawing character
// inside a real fenced block isn't grabbed.
if (/^\s*┌─+┐\s*$/.test(line)) {
let j = i + 1;
const bodyLines: string[] = [];
while (j < lines.length && !/^\s*└─+┘\s*$/.test(lines[j]!)) {
const inner = lines[j]!;
// Strip outer `│ ... │` so the content reads naturally.
const m = inner.match(/^\s*│\s?(.*?)\s?│\s*$/);
bodyLines.push(m ? (m[1] ?? "") : inner);
j++;
}
if (j < lines.length) {
flushPara();
flushList();
out.push({ kind: "code", lang: "", text: bodyLines.join("\n") });
i = j;
continue;
}
// No closing edge — fall through and let the line render as
// paragraph rather than eating to EOF.
}
// Table detection: a line with at least one column separator where
// the NEXT line looks like a separator row. Two flavors accepted:
//
// - Standard GFM: `|` columns + `---` / `:---:` separators.
// - Unicode box-drawing: `│` columns (U+2502) + `─` / `┼` (U+2500
// / U+253C) separators. Models trained on Chinese text routinely
// pick the box-drawing characters even when GFM was an option;
// accepting both keeps their output legible without forcing a
// re-prompt. `splitTableRow` normalizes `│` → `|` so the rest of
// the path stays uniform.
//
// Both the header row and the separator must be present — a bare
// pipe in prose shouldn't trigger the table path.
if (line.includes("|") || line.includes("│")) {
const next = (lines[i + 1] ?? "").trim();
if (/^\|?\s*:?-{2,}:?\s*(\|\s*:?-{2,}:?\s*)+\|?\s*$/.test(next)) {
const isGfmSep = /^\|?\s*:?-{2,}:?\s*(\|\s*:?-{2,}:?\s*)+\|?\s*$/.test(next);
const isBoxSep = /^[│─┼┬┴┌┐└┘├┤\s]+$/.test(next) && /─{2,}/.test(next);
if (isGfmSep || isBoxSep) {
flushPara();
flushList();
const header = splitTableRow(line);
const colCount = header.length;
const rows: string[][] = [];
let j = i + 2; // skip header + separator
while (j < lines.length) {
const r = lines[j]!.replace(/\s+$/g, "");
if (r.trim() === "" || !r.includes("|")) break;
if (r.trim() === "") break;
if (!r.includes("|") && !r.includes("│")) {
// Continuation row: model wrapped a long cell across lines
// without re-emitting the column separator. Fold this line
// back into the LAST cell of the previous row so its inline
// markup (backticks, bold) parses as one piece instead of
// bleeding into the paragraph stream below the table.
const prev = rows[rows.length - 1];
if (prev && prev.length === colCount) {
const lastIdx = prev.length - 1;
prev[lastIdx] = `${prev[lastIdx] ?? ""} ${r.trim()}`;
j++;
continue;
}
break;
}
rows.push(splitTableRow(r));
j++;
}
@@ -407,23 +698,23 @@ export function parseBlocks(raw: string): Block[] {
return out;
}
function BlockView({ block }: { block: Block }) {
function BlockView({ block, citations }: { block: Block; citations?: CitationMap }) {
switch (block.kind) {
case "heading":
return (
<Text bold color="cyan">
<InlineMd text={block.text} />
<InlineMd text={block.text} citations={citations} />
</Text>
);
case "paragraph":
return <InlineMd text={block.text} />;
return <InlineMd text={block.text} citations={citations} />;
case "bullet":
return (
<Box flexDirection="column">
{block.items.map((item, i) => (
<Box key={`${i}-${item.slice(0, 24)}`}>
<Text color="cyan">{block.ordered ? ` ${block.start + i}. ` : " • "}</Text>
<InlineMd text={item} />
<InlineMd text={item} citations={citations} />
</Box>
))}
</Box>
@@ -437,21 +728,23 @@ function BlockView({ block }: { block: Block }) {
case "edit-block":
return <EditBlockRow block={block} />;
case "table":
return <TableBlockRow block={block} />;
return <TableBlockRow block={block} citations={citations} />;
case "hr":
return <Text dimColor>{"────────────────────────"}</Text>;
}
}
/**
* Split one table row into trimmed cells. Leading/trailing pipes are
* optional (both `| a | b |` and `a | b` are accepted). Pipes escaped
* as `\|` stay in the cell content.
* Split one table row into trimmed cells. Leading/trailing column
* markers are optional (both `| a | b |` and `a | b` are accepted).
* Pipes escaped as `\|` stay in the cell content. Unicode `│`
* (U+2502 BOX DRAWINGS LIGHT VERTICAL) is normalized to `|` first so
* box-drawing tables and GFM tables share one code path.
*/
function splitTableRow(line: string): string[] {
// Temporarily replace escaped pipes so split() doesn't fire on them.
const SENTINEL = "\u0000";
const masked = line.replace(/\\\|/g, SENTINEL);
const masked = line.replace(/\\\|/g, SENTINEL).replace(/│/g, "|");
const trimmed = masked.trim().replace(/^\||\|$/g, "");
return trimmed.split("|").map((c) => c.trim().replace(new RegExp(SENTINEL, "g"), "|"));
}
@@ -462,19 +755,19 @@ function splitTableRow(line: string): string[] {
* doesn't wreck the layout. Header row is bold + cyan; body rows use
* the default text color. Separator is a dim row of dashes.
*/
function TableBlockRow({ block }: { block: TableBlock }) {
function TableBlockRow({ block, citations }: { block: TableBlock; citations?: CitationMap }) {
const colCount = Math.max(block.header.length, ...block.rows.map((r) => r.length));
const widths: number[] = [];
for (let c = 0; c < colCount; c++) {
const cellLengths = [displayWidth(block.header[c] ?? "")];
for (const r of block.rows) cellLengths.push(displayWidth(r[c] ?? ""));
// Use VISIBLE width (post-markup-strip) for column sizing —
// otherwise a cell like `**定义** \`dispatch\` 方法` would be
// measured with the ** and ` chars included, over-padding once
// the markers vanish at render time and shoving subsequent
// columns rightward.
const cellLengths = [visibleWidth(block.header[c] ?? "")];
for (const r of block.rows) cellLengths.push(visibleWidth(r[c] ?? ""));
widths.push(Math.min(40, Math.max(3, ...cellLengths)));
}
const pad = (s: string, w: number) => {
const dw = displayWidth(s);
if (dw >= w) return s;
return s + " ".repeat(w - dw);
};
const separator = widths.map((w) => "─".repeat(w)).join("─┼─");
return (
<Box flexDirection="column">
@@ -482,7 +775,7 @@ function TableBlockRow({ block }: { block: TableBlock }) {
{block.header.map((cell, ci) => (
// biome-ignore lint/suspicious/noArrayIndexKey: table columns never reorder — derived from a static header array
<Text key={`h-${ci}`} bold color="cyan">
{pad(cell, widths[ci] ?? 3)}
<InlineMd text={cell} padTo={widths[ci] ?? 3} citations={citations} />
{ci < colCount - 1 ? " │ " : ""}
</Text>
))}
@@ -494,7 +787,7 @@ function TableBlockRow({ block }: { block: TableBlock }) {
{Array.from({ length: colCount }).map((_, ci) => (
// biome-ignore lint/suspicious/noArrayIndexKey: same — column axis is fixed by the table shape
<Text key={`c-${ri}-${ci}`}>
{pad(row[ci] ?? "", widths[ci] ?? 3)}
<InlineMd text={row[ci] ?? ""} padTo={widths[ci] ?? 3} citations={citations} />
{ci < colCount - 1 ? " │ " : ""}
</Text>
))}
@@ -582,13 +875,43 @@ function EditBlockRow({ block }: { block: EditBlockView }) {
);
}
export function Markdown({ text }: { text: string }) {
export function Markdown({ text, projectRoot }: { text: string; projectRoot?: string }) {
const cleaned = stripMath(text);
const root = projectRoot ?? process.cwd();
const citations = React.useMemo(() => collectCitations(cleaned, root), [cleaned, root]);
const blocks = React.useMemo(() => parseBlocks(cleaned), [cleaned]);
// Collect broken citations into an ordered list so the user sees
// exactly which paths/lines failed and why. A bare count ("⚠ 1
// broken citation") tells the user something's wrong but leaves them
// to scan the wall of text for the red strikethrough — listing each
// one with its reason makes the failure actionable: the user can
// immediately push back on the specific claim, or decide it doesn't
// matter and move on.
const broken: Array<{ url: string; reason: string }> = [];
for (const [url, status] of citations) {
if (!status.ok) broken.push({ url, reason: status.reason });
}
return (
<Box flexDirection="column" gap={1}>
{blocks.map((b, i) => (
<BlockView key={`${i}-${b.kind}`} block={b} />
<BlockView key={`${i}-${b.kind}`} block={b} citations={citations} />
))}
{broken.length > 0 ? <BrokenCitationsBlock items={broken} /> : null}
</Box>
);
}
function BrokenCitationsBlock({ items }: { items: Array<{ url: string; reason: string }> }) {
return (
<Box flexDirection="column" borderStyle="round" borderColor="red" paddingX={1}>
<Text color="red" bold>
{`⚠ ${items.length} broken citation${items.length > 1 ? "s" : ""} — the model referenced paths or lines that don't exist`}
</Text>
{items.map((b, i) => (
// biome-ignore lint/suspicious/noArrayIndexKey: list is derived from a Map iteration order, stable per render
<Text key={`bc-${i}`} color="red">
{` ✗ ${b.url} → ${b.reason}`}
</Text>
))}
</Box>
);
+242
View File
@@ -0,0 +1,242 @@
/**
* `/resource` and `/prompt` slash handlers for the chat/code TUI.
*
* The slash-command registry (slash.ts) advertises both commands so the
* argument-level picker and /help surface them, but the actual read/fetch
* work is async — McpClient.readResource and getPrompt both round-trip to
* the server — so it doesn't fit the synchronous `handleSlash` shape used
* by every other slash command. App.tsx intercepts the commands directly
* and calls into the helpers below.
*
* Split by effect boundary:
* - formatters (resource list, contents, prompt list, messages) are
* pure over already-fetched data and unit-tested
* - find-server helpers are pure lookups against inspection reports
* - `handleMcpBrowseSlash` is the async orchestrator App.tsx calls
*
* v1 intentionally does NOT inject the fetched resource/prompt into the
* next model turn. It's a display-only browser so users can see what
* their MCP servers expose. A future version may add a Tab-to-inject
* hotkey once the UX is settled.
*/
import type { McpClient } from "../../mcp/client.js";
import type {
GetPromptResult,
McpPromptMessage,
McpResourceContents,
ReadResourceResult,
} from "../../mcp/types.js";
import type { DisplayEvent } from "./EventLog.js";
import type { McpServerSummary } from "./slash.js";
/**
* React setState for Historical — typed loose because the App state
* shape is App-internal. We only ever append, so `(prev) => prev.concat(row)`
* works against any array-of-DisplayEvent state.
*/
export type HistoricalSetter = (updater: (prev: DisplayEvent[]) => DisplayEvent[]) => void;
export function formatResourceList(servers: readonly McpServerSummary[]): string {
const lines: string[] = [];
let total = 0;
for (const s of servers) {
if (!s.report.resources.supported) continue;
const items = s.report.resources.items;
if (items.length === 0) continue;
lines.push(`[${s.label}] ${items.length} resource(s):`);
for (const r of items.slice(0, 20)) {
const name = r.name && r.name !== r.uri ? ` ${r.name}` : "";
const mime = r.mimeType ? ` · ${r.mimeType}` : "";
lines.push(` · ${r.uri}${name}${mime}`);
total++;
}
if (items.length > 20) lines.push(` (+${items.length - 20} more)`);
lines.push("");
}
if (total === 0) {
return "No resources on any connected MCP server (or no servers connected). `/mcp` shows the current set.";
}
lines.push("Read one: `/resource <uri>` — or use Tab in the picker.");
return lines.join("\n");
}
export function formatPromptList(servers: readonly McpServerSummary[]): string {
const lines: string[] = [];
let total = 0;
for (const s of servers) {
if (!s.report.prompts.supported) continue;
const items = s.report.prompts.items;
if (items.length === 0) continue;
lines.push(`[${s.label}] ${items.length} prompt(s):`);
for (const p of items.slice(0, 20)) {
const desc = p.description ? ` — ${p.description}` : "";
const argHint =
p.arguments && p.arguments.length > 0
? ` (args: ${p.arguments.map((a) => a.name + (a.required ? "*" : "?")).join(", ")})`
: "";
lines.push(` · ${p.name}${argHint}${desc}`);
total++;
}
if (items.length > 20) lines.push(` (+${items.length - 20} more)`);
lines.push("");
}
if (total === 0) {
return "No prompts on any connected MCP server (or no servers connected). `/mcp` shows the current set.";
}
lines.push(
"Fetch one: `/prompt <name>` — args are not supported yet; prompts with required args will surface an error from the server.",
);
return lines.join("\n");
}
export function findServerForResource(
servers: readonly McpServerSummary[],
uri: string,
): McpServerSummary | null {
for (const s of servers) {
if (!s.report.resources.supported) continue;
if (s.report.resources.items.some((r) => r.uri === uri)) return s;
}
return null;
}
export function findServerForPrompt(
servers: readonly McpServerSummary[],
name: string,
): McpServerSummary | null {
for (const s of servers) {
if (!s.report.prompts.supported) continue;
if (s.report.prompts.items.some((p) => p.name === name)) return s;
}
return null;
}
export function formatResourceContents(uri: string, result: ReadResourceResult): string {
const lines: string[] = [`Resource ${uri} (${result.contents.length} content block(s)):`, ""];
for (let i = 0; i < result.contents.length; i++) {
const c = result.contents[i]!;
const header = `— block ${i + 1}${c.mimeType ? ` · ${c.mimeType}` : ""}`;
lines.push(header);
lines.push(formatOneResourceContent(c));
lines.push("");
}
return lines.join("\n").trimEnd();
}
function formatOneResourceContent(c: McpResourceContents): string {
if ("text" in c) {
const MAX = 8_000;
if (c.text.length > MAX) {
return `${c.text.slice(0, MAX)}\n\n[…truncated ${c.text.length - MAX} chars; full contents available via McpClient.readResource in library mode.]`;
}
return c.text;
}
// blob — we can't render arbitrary binary in the TUI; give the size.
const bytes = typeof c.blob === "string" ? approximateBase64ByteSize(c.blob) : 0;
return `[binary · ~${bytes.toLocaleString()} bytes · base64]`;
}
function approximateBase64ByteSize(b64: string): number {
// 4 base64 chars encode 3 bytes; padding `=` trims the output.
const padding = b64.endsWith("==") ? 2 : b64.endsWith("=") ? 1 : 0;
return Math.floor((b64.length * 3) / 4) - padding;
}
export function formatPromptMessages(name: string, result: GetPromptResult): string {
const lines: string[] = [
`Prompt ${name}${result.description ? ` — ${result.description}` : ""}`,
`(${result.messages.length} message(s))`,
"",
];
for (let i = 0; i < result.messages.length; i++) {
const m = result.messages[i]!;
lines.push(`— ${i + 1}. ${m.role}`);
lines.push(formatOnePromptMessage(m));
lines.push("");
}
return lines.join("\n").trimEnd();
}
function formatOnePromptMessage(m: McpPromptMessage): string {
const block = m.content as { type?: string; text?: string; resource?: McpResourceContents };
if (block.type === "text" && typeof block.text === "string") return block.text;
if (block.type === "resource" && block.resource) {
return `[resource: ${block.resource.uri}]\n${formatOneResourceContent(block.resource)}`;
}
return `[non-text content: ${block.type ?? "unknown"}]`;
}
/**
* Orchestrator. Looks up the right server, calls readResource/getPrompt
* via its `client`, and pushes one info row into `Historical`. Errors
* (server missing, -32601, network) surface as a warning row; the user
* can always fall back to `reasonix mcp inspect <spec>` for diagnostics.
*/
export async function handleMcpBrowseSlash(
kind: "resource" | "prompt",
arg: string,
servers: readonly McpServerSummary[],
setHistorical: HistoricalSetter,
): Promise<void> {
const ts = Date.now();
const push = (role: DisplayEvent["role"], text: string) => {
setHistorical((prev) => [...prev, { id: `mcp-${role}-${ts}-${prev.length}`, role, text }]);
};
// No arg → list mode.
if (!arg) {
push("info", kind === "resource" ? formatResourceList(servers) : formatPromptList(servers));
return;
}
if (kind === "resource") {
const server = findServerForResource(servers, arg);
if (!server) {
push(
"warning",
`no server exposes resource "${arg}". \`/resource\` with no arg lists what's available.`,
);
return;
}
const client: McpClient | undefined = server.client;
if (!client) {
push(
"warning",
`server [${server.label}] is not connected (display-only). Resource read requires a live MCP client.`,
);
return;
}
try {
const result = await client.readResource(arg);
push("info", formatResourceContents(arg, result));
} catch (err) {
push("warning", `readResource failed: ${(err as Error).message}`);
}
return;
}
// prompt
const server = findServerForPrompt(servers, arg);
if (!server) {
push(
"warning",
`no server exposes prompt "${arg}". \`/prompt\` with no arg lists what's available.`,
);
return;
}
const client: McpClient | undefined = server.client;
if (!client) {
push(
"warning",
`server [${server.label}] is not connected (display-only). Prompt fetch requires a live MCP client.`,
);
return;
}
try {
const result = await client.getPrompt(arg);
push("info", formatPromptMessages(arg, result));
} catch (err) {
push("warning", `getPrompt failed: ${(err as Error).message}`);
}
}
+152 -75
View File
@@ -1,30 +1,34 @@
/**
* Pure keystroke → action reducer for MultilineInput.
* Pure keystroke → action reducer for PromptInput.
*
* Kept separate from the React component so the keyboard
* semantics are easy to unit-test. MultilineInput is otherwise
* a thin Ink wrapper that threads its `useInput` callback
* through this function and applies the result.
* Kept separate from the React component so the keyboard semantics
* are easy to unit-test. The component threads `useInput` through
* this function and applies the returned action.
*
* Terminal reality check: on most terminals, pressing Shift+Enter
* sends the exact same byte as plain Enter — the modifier is lost.
* That's why the reliable newline insertion path is Ctrl+J (which
* really is LF, distinct from CR), with Shift+Enter only working
* on terminals that opt into CSI-u modifier encoding. The `\<Enter>`
* bash-style continuation is the portable fallback.
* Edit model:
* - Full cursor support. ←/→ move one column. ↑/↓ move across
* lines in a multi-line buffer (column preserved when possible).
* Ctrl+A / Ctrl+E jump to start / end of the current line.
* - Backspace deletes the char before the cursor; Delete deletes
* the char under the cursor.
* - Printable chars (including multi-char paste bursts) insert
* at the cursor.
* - Enter submits unless Shift is held (newline), the line ends
* with '\' and cursor is at end (bash-style continuation), or
* the input is Ctrl+J (LF, terminal-universal newline).
* - Parent owns Tab, Esc, PageUp/Down (slash-complete, abort,
* unused). Arrow keys are split: empty buffer → parent (history
* recall); non-empty → child (cursor movement).
*/
export interface MultilineKey {
/** Printable character(s) delivered by the key event, may be empty. */
input: string;
/** Modifier + named-key flags as Ink reports them. */
return?: boolean;
shift?: boolean;
ctrl?: boolean;
meta?: boolean;
backspace?: boolean;
delete?: boolean;
/** Navigation/editing keys owned by the parent App (slash-nav, history). */
tab?: boolean;
upArrow?: boolean;
downArrow?: boolean;
@@ -36,87 +40,160 @@ export interface MultilineKey {
}
export interface MultilineAction {
/** New value to set on the text buffer. `null` = unchanged. */
/** New buffer value. `null` = unchanged. */
next: string | null;
/** When `true`, the caller should fire `onSubmit(next ?? value)`. */
/** New cursor position (0..value.length). `null` = unchanged. */
cursor: number | null;
/** When `true`, fire `onSubmit(submitValue ?? value)`. */
submit: boolean;
/** When submitting, which value to submit (after any final trims). */
submitValue?: string;
}
const BACKSLASH_SUFFIX = /\\$/;
/**
* Decide what to do with a single keystroke against the current buffer.
*
* Decisions:
* Ctrl+J → insert '\n' (terminal-universal newline)
* Shift+Return → insert '\n' (works where CSI-u is on)
* Enter with "\" end → replace trailing '\' with '\n' (bash continuation)
* Enter → submit the current buffer
* Backspace/Delete → drop one char from the end (cursor-at-end model)
* Printable char(s) → append at the end
*
* We don't model an insertion cursor inside the string: always-at-end
* keeps the reducer tiny and matches how readline-in-raw-mode feels. The
* user can still edit by backspacing — for deep edits, exit and compose
* in $EDITOR.
*/
export function processMultilineKey(value: string, key: MultilineKey): MultilineAction {
// Parent App owns these keys: Tab for slash auto-complete, arrows
// for slash-nav/history, Esc for abort. Bowing out here keeps the
// text buffer from eating a stray "\t" or arrow escape sequence
// when both the parent and child useInput fire on the same event.
if (
key.tab ||
key.upArrow ||
key.downArrow ||
key.leftArrow ||
key.rightArrow ||
key.escape ||
key.pageUp ||
key.pageDown
) {
return { next: null, submit: false };
const NOOP: MultilineAction = { next: null, cursor: null, submit: false };
export function processMultilineKey(
value: string,
cursor: number,
key: MultilineKey,
): MultilineAction {
// Parent-owned keys: Tab (slash-complete), Esc (abort), PageUp/Down.
if (key.tab || key.escape || key.pageUp || key.pageDown) {
return NOOP;
}
// Reliable newline: Ctrl+J arrives as literal '\n' in key.input on
// every terminal we've checked. We also accept key.ctrl && input=='j'
// as a belt-and-braces match against terminals that normalize the
// control-char into its ASCII letter form.
// Empty buffer + ↑/↓ → parent handles history recall.
if (value.length === 0 && (key.upArrow || key.downArrow)) {
return NOOP;
}
// Cursor motion.
if (key.leftArrow) {
return { next: null, cursor: Math.max(0, cursor - 1), submit: false };
}
if (key.rightArrow) {
return { next: null, cursor: Math.min(value.length, cursor + 1), submit: false };
}
if (key.upArrow) {
const moved = moveCursorUp(value, cursor);
return moved === cursor ? NOOP : { next: null, cursor: moved, submit: false };
}
if (key.downArrow) {
const moved = moveCursorDown(value, cursor);
return moved === cursor ? NOOP : { next: null, cursor: moved, submit: false };
}
// Emacs-style line jumps (universal across terminals; Home/End aren't
// reliably reported by Ink so we don't depend on them).
if (key.ctrl && key.input === "a") {
return { next: null, cursor: startOfLine(value, cursor), submit: false };
}
if (key.ctrl && key.input === "e") {
return { next: null, cursor: endOfLine(value, cursor), submit: false };
}
// Newline: Ctrl+J (LF literal) or ctrl+'j' normalized form.
if (key.input === "\n" || (key.ctrl && key.input === "j")) {
return { next: `${value}\n`, submit: false };
return insertAt(value, cursor, "\n");
}
if (key.return) {
// Shift+Return → newline (when terminal reports the modifier).
if (key.shift) {
return { next: `${value}\n`, submit: false };
if (key.shift) return insertAt(value, cursor, "\n");
// Bash-style line continuation: trailing '\' + Enter (only when the
// cursor sits at end-of-buffer, so a stray '\' mid-line doesn't
// trigger it).
if (cursor === value.length && BACKSLASH_SUFFIX.test(value)) {
const replaced = `${value.slice(0, -1)}\n`;
return { next: replaced, cursor: replaced.length, submit: false };
}
// Bash-style line continuation: trailing '\' + Enter.
if (BACKSLASH_SUFFIX.test(value)) {
return { next: `${value.slice(0, -1)}\n`, submit: false };
}
// Plain Enter → submit.
return { next: null, submit: true, submitValue: value };
return { next: null, cursor: null, submit: true, submitValue: value };
}
if (key.backspace || key.delete) {
if (value.length === 0) return { next: null, submit: false };
return { next: value.slice(0, -1), submit: false };
// Backspace = delete the char BEFORE the cursor. We also accept
// `key.delete` and the raw DEL (0x7f) / BS (0x08) bytes as backspace
// for the same purpose — some Windows terminals (cmd.exe, certain
// winpty configs) report plain Backspace without setting
// `key.backspace`, which used to leave the user typing into a prompt
// where the Backspace key did nothing. Reasonix doesn't offer a
// separate forward-delete operation, so collapsing them is safe.
if (key.backspace || key.delete || key.input === "\x7f" || key.input === "\b") {
if (cursor === 0) return NOOP;
return {
next: value.slice(0, cursor - 1) + value.slice(cursor),
cursor: cursor - 1,
submit: false,
};
}
// Ignore bare modifier keys (ctrl/meta without accompanying printable).
if ((key.ctrl || key.meta) && key.input.length === 0) {
return { next: null, submit: false };
// Bare modifier events (Ctrl/Meta with no printable) and unhandled
// Ctrl-<letter> chords are dropped so a stray Ctrl+L doesn't insert "l".
if ((key.ctrl || key.meta) && key.input.length === 0) return NOOP;
if (key.ctrl || key.meta) return NOOP;
// Printable input (may be a multi-char paste; pasted newlines land
// inside the buffer rather than triggering submit on the first line).
if (key.input.length > 0) {
return insertAt(value, cursor, key.input);
}
// Printable input (may be a multi-char paste burst — accept as-is;
// pasted newlines become part of the buffer rather than triggering
// submit on the first line).
if (key.input.length > 0 && !key.ctrl && !key.meta) {
return { next: value + key.input, submit: false };
return NOOP;
}
function insertAt(value: string, cursor: number, insert: string): MultilineAction {
return {
next: value.slice(0, cursor) + insert + value.slice(cursor),
cursor: cursor + insert.length,
submit: false,
};
}
/**
* Line + column of a cursor inside a buffer. Exported because the
* renderer needs the same mapping for drawing the cursor block on the
* right line.
*/
export function lineAndColumn(value: string, cursor: number): { line: number; col: number } {
let line = 0;
let col = 0;
const n = Math.min(cursor, value.length);
for (let i = 0; i < n; i++) {
if (value[i] === "\n") {
line++;
col = 0;
} else {
col++;
}
}
return { line, col };
}
function startOfLine(value: string, cursor: number): number {
return value.lastIndexOf("\n", cursor - 1) + 1;
}
function endOfLine(value: string, cursor: number): number {
const nl = value.indexOf("\n", cursor);
return nl === -1 ? value.length : nl;
}
function moveCursorUp(value: string, cursor: number): number {
const curStart = startOfLine(value, cursor);
if (curStart === 0) return cursor; // already on the first line
const col = cursor - curStart;
const prevEnd = curStart - 1; // the '\n' between the two lines
const prevStart = value.lastIndexOf("\n", prevEnd - 1) + 1;
const prevLen = prevEnd - prevStart;
return prevStart + Math.min(col, prevLen);
}
return { next: null, submit: false };
function moveCursorDown(value: string, cursor: number): number {
const nextNl = value.indexOf("\n", cursor);
if (nextNl === -1) return cursor; // already on the last line
const curStart = startOfLine(value, cursor);
const col = cursor - curStart;
const nextStart = nextNl + 1;
const followingNl = value.indexOf("\n", nextStart);
const nextLen = (followingNl === -1 ? value.length : followingNl) - nextStart;
return nextStart + Math.min(col, nextLen);
}
+81
View File
@@ -0,0 +1,81 @@
/**
* Collapse long user-typed input for display purposes.
*
* Problem: pasting a stack trace, log dump, or sample file into the
* prompt box floods the Historical scrollback with a huge block — the
* user can't see their previous turns, the assistant's replies, or
* where the cursor is. Terminal UIs have shipped this shape for
* years (iTerm's "pasted text" notation, Claude Code's preview).
*
* Split of concerns: the MODEL still gets the full text. This helper
* only rewrites what we render in the Historical row. `@` expansions
* and `!` bang outputs have their own display paths (unaffected).
*/
/** Defaults tuned to typical prose vs. typical code-paste shapes. */
export const DEFAULT_PASTE_LINE_THRESHOLD = 40;
export const DEFAULT_PASTE_CHAR_THRESHOLD = 2000;
/** Lines kept visible at the head of a collapsed paste. */
export const DEFAULT_PASTE_HEAD_LINES = 10;
export interface PasteCollapseOptions {
lineThreshold?: number;
charThreshold?: number;
headLines?: number;
}
export interface PasteCollapseResult {
/** Text to render in the Historical row (possibly collapsed). */
displayText: string;
/** True when collapsing happened. False = input passed through verbatim. */
collapsed: boolean;
/** Original char length — exposed so callers can log/annotate. */
originalChars: number;
/** Original line count. */
originalLines: number;
}
/**
* Collapse `input` when it exceeds either the line OR char threshold.
* Display shape:
*
* ▸ pasted 2.3 KB (84 lines) — first 10 shown, full text sent to model
* line 1
* line 2
* …
* line 10
* … (74 more lines)
*
* Short input passes through unchanged — collapsed = false.
*/
export function formatLongPaste(
input: string,
opts: PasteCollapseOptions = {},
): PasteCollapseResult {
const lineCap = opts.lineThreshold ?? DEFAULT_PASTE_LINE_THRESHOLD;
const charCap = opts.charThreshold ?? DEFAULT_PASTE_CHAR_THRESHOLD;
const headN = Math.max(1, opts.headLines ?? DEFAULT_PASTE_HEAD_LINES);
const originalChars = input.length;
const lines = input.split("\n");
const originalLines = lines.length;
if (originalChars <= charCap && originalLines <= lineCap) {
return { displayText: input, collapsed: false, originalChars, originalLines };
}
const header = `▸ pasted ${formatBytes(originalChars)} (${originalLines} lines) — first ${Math.min(headN, originalLines)} shown, full text sent to model`;
const head = lines.slice(0, headN).join("\n");
const remaining = originalLines - headN;
const footer = remaining > 0 ? `… (${remaining} more line${remaining === 1 ? "" : "s"})` : "";
const displayText = footer ? `${header}\n${head}\n${footer}` : `${header}\n${head}`;
return { displayText, collapsed: true, originalChars, originalLines };
}
function formatBytes(n: number): string {
if (n < 1024) return `${n} B`;
const kb = n / 1024;
if (kb < 1024) return `${kb.toFixed(kb >= 10 ? 0 : 1)} KB`;
const mb = kb / 1024;
return `${mb.toFixed(mb >= 10 ? 0 : 1)} MB`;
}
+50 -13
View File
@@ -3,40 +3,77 @@
* (in-chat `/preset`) and the wizard (first-run setup) read from here.
*
* Presets are the single vocabulary we teach new users: they don't need
* to know model IDs, Pillar 2, branch budgets, or cost tradeoffs
* independently — they pick "fast / smart / max" and we translate.
* to know model IDs, reasoning effort, or thinking mode independently
* — they pick "fast / smart / max" and we translate.
*
* Design rules (v0.6+):
* - Branching (`branch >= 2`) is NEVER in a preset. Self-consistency
* sampling is `N×` cost; auto-enabling it would ambush users into
* multi-dollar turns without asking. Opt-in only via `/branch N`.
* - Harvest (Pillar-2 plan-state extraction) is NEVER in a preset.
* In practice it's display sugar — the typed plan state hasn't
* fed back into orchestration decisions (branch trigger) often
* enough to pay for the extra round-trip. Opt-in only via
* `/harvest on`.
* - The three tiers differ on only TWO knobs: model (flash/pro) and
* reasoning effort (high/max). Same on-the-wire billing axis,
* easy to reason about, easy to budget.
*/
import type { PresetName } from "../../config.js";
export interface PresetSettings {
model: string;
/**
* Reasoning-effort cap sent per turn. `high` = shorter chain of
* thought (cheaper, faster); `max` = agent-class default (deeper,
* more output tokens). DeepSeek ignores this field on non-thinking
* calls, so it's safe to pin across models.
*/
reasoningEffort: "high" | "max";
/**
* Pillar-2 plan-state extraction. Every preset ships `false` (see
* module header); kept in the shape so a user who later flips it on
* at runtime still round-trips cleanly. `/harvest on` toggles it.
*/
harvest: boolean;
/** Branch budget. `1` means branching off. */
/**
* Branch budget. Every preset ships `1` (off). `/branch N` with
* N>=2 is the only way to enable self-consistency sampling.
*/
branch: number;
}
export const PRESETS: Record<PresetName, PresetSettings> = {
fast: { model: "deepseek-chat", harvest: false, branch: 1 },
smart: { model: "deepseek-reasoner", harvest: true, branch: 1 },
max: { model: "deepseek-reasoner", harvest: true, branch: 3 },
// fast — flash + effort=high. Quick Q&A, one-line tweaks, anything
// where shallow reasoning is enough. Cheapest turn possible.
fast: { model: "deepseek-v4-flash", reasoningEffort: "high", harvest: false, branch: 1 },
// smart — flash + effort=max. Full thinking budget on the cheap
// model. The default: handles 90%+ of coding work at a fraction
// of pro's cost.
smart: { model: "deepseek-v4-flash", reasoningEffort: "max", harvest: false, branch: 1 },
// max — pro + effort=max. Frontier model for hard tasks: cross-
// file architecture, subtle bug hunts, anything where flash's
// reasoning has measurably failed. ~12× per-token vs flash; save
// for when you need it, or use `/pro` to escalate a single turn.
max: { model: "deepseek-v4-pro", reasoningEffort: "max", harvest: false, branch: 1 },
};
export const PRESET_DESCRIPTIONS: Record<PresetName, { headline: string; cost: string }> = {
fast: {
headline: "deepseek-chat, no reasoning harvest, no branching",
cost: "~1¢ per 100 turns · default",
headline: "v4-flash · effort=high",
cost: "cheapest · quick Q&A, one-line edits",
},
smart: {
headline: "deepseek-reasoner + Pillar 2 harvest",
cost: "~10× cost vs fast · slower · better on multi-step tasks",
headline: "v4-flash · effort=max",
cost: "~1.5× fast · default · day-to-day coding",
},
max: {
headline: "reasoner + harvest + self-consistency (3 branches)",
cost: "~30× cost vs fast · slowest · for hard single-shots",
headline: "v4-pro · effort=max",
cost: "~12× fast · hard single-shots · use /pro for a single-turn bump",
},
};
export function resolvePreset(name: PresetName | undefined): PresetSettings {
return PRESETS[name ?? "fast"];
return PRESETS[name ?? "smart"];
}
+20 -642
View File
@@ -1,642 +1,20 @@
import { spawnSync } from "node:child_process";
import type { CacheFirstLoop } from "../../loop.js";
import type { InspectionReport } from "../../mcp/inspect.js";
import { deleteSession, listSessions } from "../../session.js";
import { DEEPSEEK_CONTEXT_TOKENS, DEFAULT_CONTEXT_TOKENS } from "../../telemetry.js";
export interface SlashResult {
/** Text to display back to the user as a system/info line. */
info?: string;
/** Exit the app. */
exit?: boolean;
/** Clear the visible history. */
clear?: boolean;
/** Unknown command — display usage hint. */
unknown?: boolean;
/**
* Re-submit this text as a user message after displaying `info`.
* Used by `/retry` — the slash command truncates the log, then
* asks the TUI to push the original text back through the normal
* submit flow so a fresh turn runs.
*/
resubmit?: string;
}
/**
* Extra runtime context a slash handler may care about but that isn't
* already on the loop. Kept as an optional object so tests that only
* need loop-scoped commands can skip it, and callers only populate the
* slots that apply to their session.
*/
export interface SlashContext {
/**
* The exact `--mcp` / config-derived spec strings that were bridged
* into this session (one entry per server). Used by `/mcp`. Empty or
* omitted → no MCP servers attached.
*/
mcpSpecs?: string[];
/**
* Callback for `/undo` — provided by the TUI when it's running in
* code mode. Returns a human-readable report of what was restored.
* Absent outside code mode → `/undo` replies "not available here".
*/
codeUndo?: () => string;
/**
* Callback for `/apply` — commits pending edit blocks to disk. Returns
* a report of what landed. Absent → `/apply` replies "nothing pending"
* or "not available outside code mode".
*/
codeApply?: () => string;
/**
* Callback for `/discard` — drops the pending edit blocks without
* touching disk.
*/
codeDiscard?: () => string;
/**
* Root directory passed by `reasonix code`. Enables `/commit`, which
* runs `git add -A && git commit` in this directory. Missing → `/commit`
* replies "only available in code mode".
*/
codeRoot?: string;
/**
* How many edit blocks are currently pending `/apply` or `/discard`.
* Surfaced by `/status`. TUI populates it live from its pending ref;
* omitted → treat as 0 (chat-only session).
*/
pendingEditCount?: number;
/**
* Callback returning every tool result seen this session in
* chronological order (oldest first). Powers `/tool [N]` for
* inspecting the full untruncated output that `EventLog` clips at
* 400 chars for display. Absent → `/tool` replies "not available".
*/
toolHistory?: () => Array<{ toolName: string; text: string }>;
/**
* Pre-captured inspection reports for each connected MCP server.
* Populated once at chat startup (chat.tsx) so `/mcp` can render
* tools + resources + prompts synchronously without needing async
* handler support.
*/
mcpServers?: McpServerSummary[];
}
export interface McpServerSummary {
/** Short label shown in the `/mcp` output (server namespace or "anon"). */
label: string;
/** Original --mcp spec string. */
spec: string;
/** Count of tools bridged into the Reasonix registry from this server. */
toolCount: number;
/** Full inspection snapshot — used for the resources + prompts sections. */
report: InspectionReport;
}
/**
* Slash command registry. Drives `/help`, the on-type suggestion
* popup (`SlashSuggestions`), and auto-complete. Kept as data rather
* than derived from the `handleSlash` switch so summaries can be
* user-facing rather than code comments.
*
* `contextual` gates commands that only make sense in certain modes:
* - `"code"` — only show when the TUI is running `reasonix code`
* - absent → always shown
*/
export interface SlashCommandSpec {
cmd: string;
summary: string;
contextual?: "code";
/** If the command takes args, hint text shown after the name. */
argsHint?: string;
}
export const SLASH_COMMANDS: readonly SlashCommandSpec[] = [
{ cmd: "help", summary: "show the full command reference" },
{ cmd: "status", summary: "current model, flags, context, session" },
{
cmd: "preset",
argsHint: "<fast|smart|max>",
summary: "one-tap model + harvest + branch bundle",
},
{ cmd: "model", argsHint: "<id>", summary: "switch DeepSeek model id" },
{ cmd: "harvest", argsHint: "[on|off]", summary: "toggle Pillar-2 plan-state extraction" },
{ cmd: "branch", argsHint: "<N|off>", summary: "run N parallel samples per turn (N>=2)" },
{ cmd: "mcp", summary: "list MCP servers + tools attached to this session" },
{ cmd: "tool", argsHint: "[N]", summary: "dump full output of the Nth tool call (1=latest)" },
{ cmd: "think", summary: "dump the last turn's full R1 reasoning (reasoner only)" },
{ cmd: "retry", summary: "truncate & resend your last message (fresh sample)" },
{ cmd: "compact", argsHint: "[cap]", summary: "shrink oversized tool results in the log" },
{ cmd: "sessions", summary: "list saved sessions (current marked with ▸)" },
{ cmd: "forget", summary: "delete the current session from disk" },
{ cmd: "setup", summary: "reminds you to exit and run `reasonix setup`" },
{ cmd: "clear", summary: "clear visible scrollback only (log/context kept)" },
{ cmd: "new", summary: "start a fresh conversation (clear context + scrollback)" },
{ cmd: "exit", summary: "quit the TUI" },
// Code-mode only
{ cmd: "apply", summary: "commit pending edit blocks to disk", contextual: "code" },
{ cmd: "discard", summary: "drop pending edit blocks without writing", contextual: "code" },
{ cmd: "undo", summary: "roll back the last applied edit batch", contextual: "code" },
{
cmd: "commit",
argsHint: '"msg"',
summary: "git add -A && git commit -m ...",
contextual: "code",
},
];
/**
* Filter the registry by a prefix string (without the leading `/`).
* Empty prefix returns the full non-contextual list (plus code-mode
* entries when `codeMode` is true). Case-insensitive.
*/
export function suggestSlashCommands(prefix: string, codeMode = false): SlashCommandSpec[] {
const p = prefix.toLowerCase();
return SLASH_COMMANDS.filter((c) => {
if (c.contextual === "code" && !codeMode) return false;
return c.cmd.startsWith(p);
});
}
export function parseSlash(text: string): { cmd: string; args: string[] } | null {
if (!text.startsWith("/")) return null;
const parts = text.slice(1).trim().split(/\s+/);
const cmd = parts[0]?.toLowerCase() ?? "";
if (!cmd) return null;
return { cmd, args: parts.slice(1) };
}
export function handleSlash(
cmd: string,
args: string[],
loop: CacheFirstLoop,
ctx: SlashContext = {},
): SlashResult {
switch (cmd) {
case "exit":
case "quit":
return { exit: true };
case "clear":
return {
clear: true,
info: "▸ cleared visible scrollback only. Context (message log) is intact — next turn still sees everything. Use /new to start fresh, or /forget to delete the session entirely.",
};
case "new":
case "reset": {
// Actually drop the in-memory log + rewrite the session file
// so the NEXT call has no prior context. Keeps session name,
// model, and other config — just the conversation is reset.
const { dropped } = loop.clearLog();
return {
clear: true,
info: `▸ new conversation — dropped ${dropped} message(s) from context. Same session, fresh slate.`,
};
}
case "help":
case "?":
return {
info: [
"Commands:",
" /help this message",
" /status show current settings",
" /preset <fast|smart|max> one-tap presets — see below",
" /model <id> deepseek-chat or deepseek-reasoner",
" /harvest [on|off] Pillar 2: structured plan-state extraction",
" /branch <N|off> run N parallel samples (N>=2), pick most confident",
" /mcp list MCP servers + tools attached to this session",
" /setup (exit + reconfigure) → run `reasonix setup`",
" /compact [cap] shrink large tool results in history (default 4k/result)",
" /think dump the most recent turn's full R1 reasoning (reasoner only)",
" /tool [N] list tool calls (or dump full output of #N, 1=most recent)",
" /retry truncate & resend your last message (fresh sample from the model)",
" /apply (code mode) commit the pending edit blocks to disk",
" /discard (code mode) drop pending edits without writing",
" /undo (code mode) roll back the last applied edit batch",
' /commit "msg" (code mode) git add -A && git commit -m "msg"',
" /sessions list saved sessions (current is marked with ▸)",
" /forget delete the current session from disk",
" /new start fresh: drop all context + clear scrollback",
" /clear clear displayed scrollback only (context kept — model still sees it)",
" /exit quit",
"",
"Presets:",
" fast deepseek-chat no harvest no branch ~1¢/100turns ← default",
" smart reasoner harvest ~10x cost, slower",
" max reasoner harvest branch 3 ~30x cost, slowest",
"",
"Sessions (auto-enabled by default, named 'default'):",
" reasonix chat --session <name> use a different named session",
" reasonix chat --no-session disable persistence for this run",
].join("\n"),
};
case "mcp": {
const servers = ctx.mcpServers ?? [];
const specs = ctx.mcpSpecs ?? [];
const toolSpecs = loop.prefix.toolSpecs ?? [];
if (servers.length === 0 && specs.length === 0 && toolSpecs.length === 0) {
return {
info:
"no MCP servers attached. Run `reasonix setup` to pick some, " +
'or launch with --mcp "<spec>". `reasonix mcp list` shows the catalog.',
};
}
// Rich path — we have full inspection reports, so show each
// server with its tools / resources / prompts grouped together.
if (servers.length > 0) {
const lines: string[] = [];
for (const s of servers) {
const { report } = s;
const serverName = report.serverInfo.name || "(unknown)";
const serverVer = report.serverInfo.version ? ` v${report.serverInfo.version}` : "";
lines.push(`[${s.label}] ${serverName}${serverVer} — ${s.spec}`);
lines.push(` tools ${s.toolCount}`);
appendSection(lines, "resources", report.resources);
appendSection(lines, "prompts ", report.prompts);
lines.push("");
}
lines.push(
"Chat mode consumes tools today; resources+prompts are surfaced here for awareness.",
);
lines.push(
"Full catalog: `reasonix mcp list` · deeper diagnosis: `reasonix mcp inspect <spec>`.",
);
return { info: lines.join("\n") };
}
// Fallback — older path when the TUI hasn't populated `mcpServers`.
const lines: string[] = [];
if (specs.length > 0) {
lines.push(`MCP servers (${specs.length}):`);
for (const spec of specs) lines.push(` · ${spec}`);
lines.push("");
}
if (toolSpecs.length > 0) {
lines.push(`Tools in registry (${toolSpecs.length}):`);
for (const t of toolSpecs) lines.push(` · ${t.function.name}`);
}
lines.push("");
lines.push("To change this set, exit and run `reasonix setup`.");
return { info: lines.join("\n") };
}
case "setup":
return {
info:
"To reconfigure (preset, MCP servers, API key), exit this chat and run " +
"`reasonix setup`. Changes take effect on next launch.",
};
case "retry": {
const prev = loop.retryLastUser();
if (!prev) {
return {
info: "nothing to retry — no prior user message in this session's log.",
};
}
const preview = prev.length > 80 ? `${prev.slice(0, 80)}…` : prev;
return {
info: `▸ retrying: "${preview}"`,
resubmit: prev,
};
}
case "think":
case "reasoning": {
const raw = loop.scratch.reasoning;
if (!raw || !raw.trim()) {
return {
info:
"no reasoning cached. `/think` shows the full R1 thought for the most recent turn — " +
"only `deepseek-reasoner` produces it, and only once the turn completes.",
};
}
return { info: `↳ full thinking (${raw.length} chars):\n\n${raw.trim()}` };
}
case "tool": {
// EventLog truncates tool results at 400 chars for display. When
// the user wants to check what the model actually read (e.g. to
// verify it isn't hallucinating a file's contents), they need
// the full text. `/tool` is the escape hatch.
const history = ctx.toolHistory?.() ?? [];
if (history.length === 0) {
return {
info:
"no tool calls yet in this session. `/tool` lists them once the model has actually " +
"used a tool; `/tool N` dumps the full (untruncated) output of the Nth-most-recent.",
};
}
const raw = (args[0] ?? "").toLowerCase();
if (raw === "" || raw === "list" || raw === "ls") {
return { info: formatToolList(history) };
}
const n = Number.parseInt(raw, 10);
if (!Number.isFinite(n) || n < 1) {
return {
info: "usage: /tool [N] (no arg → list; N=1 → most recent result in full, N=2 → previous, …)",
};
}
if (n > history.length) {
return {
info: `only ${history.length} tool call(s) in history — asked for #${n}. Try /tool with no arg to see the list.`,
};
}
const entry = history[history.length - n];
if (!entry) {
return { info: `could not read tool call #${n}` };
}
return {
info: `↳ tool<${entry.toolName}> #${n} (${entry.text.length} chars):\n\n${entry.text}`,
};
}
case "undo": {
if (!ctx.codeUndo) {
return {
info: "/undo is only available inside `reasonix code` — chat mode doesn't apply edits.",
};
}
return { info: ctx.codeUndo() };
}
case "apply": {
if (!ctx.codeApply) {
return {
info: "/apply is only available inside `reasonix code` (nothing to apply here).",
};
}
return { info: ctx.codeApply() };
}
case "discard": {
if (!ctx.codeDiscard) {
return {
info: "/discard is only available inside `reasonix code`.",
};
}
return { info: ctx.codeDiscard() };
}
case "commit": {
if (!ctx.codeRoot) {
return {
info: "/commit is only available inside `reasonix code` (needs a rooted git repo).",
};
}
// Reassemble the original argv. The parser lowercases cmd but
// leaves args alone, and the TUI splits on whitespace which
// mangles quoted messages — rejoin with spaces and strip a
// surrounding pair of double quotes if the user wrote them.
const raw = args.join(" ").trim();
const message = stripOuterQuotes(raw);
if (!message) {
return {
info: `usage: /commit "your commit message" — runs \`git add -A && git commit -m "…"\` in ${ctx.codeRoot}`,
};
}
return runGitCommit(ctx.codeRoot, message);
}
case "compact": {
// Manual companion to the automatic heal-on-load. Re-applies
// truncation with a tighter cap (4k chars per tool result) and
// rewrites the session file so the shrink persists. Useful when
// the ctx gauge in StatsPanel goes yellow/red mid-session and
// the user wants to keep chatting without /forget'ing everything.
const tight = Number.parseInt(args[0] ?? "", 10);
const cap = Number.isFinite(tight) && tight >= 500 ? tight : 4000;
const { healedCount, charsSaved } = loop.compact(cap);
if (healedCount === 0) {
return {
info: `▸ nothing to compact — no tool result in history exceeds ${cap.toLocaleString()} chars.`,
};
}
return {
info: `▸ compacted ${healedCount} tool result(s), saved ${charsSaved.toLocaleString()} chars (~${Math.round(charsSaved / 4).toLocaleString()} tokens). Session file rewritten.`,
};
}
case "sessions": {
const items = listSessions();
if (items.length === 0) {
return {
info: "no saved sessions yet — chat normally and your messages will be saved automatically",
};
}
const lines = ["Saved sessions:"];
for (const s of items) {
const sizeKb = (s.size / 1024).toFixed(1);
const when = s.mtime.toISOString().replace("T", " ").slice(0, 16);
const marker = s.name === loop.sessionName ? "▸" : " ";
lines.push(
` ${marker} ${s.name.padEnd(22)} ${String(s.messageCount).padStart(5)} msgs ${sizeKb.padStart(7)} KB ${when}`,
);
}
lines.push("");
lines.push("Resume with: reasonix chat --session <name>");
return { info: lines.join("\n") };
}
case "forget": {
if (!loop.sessionName) {
return { info: "not in a session — nothing to forget" };
}
const name = loop.sessionName;
const ok = deleteSession(name);
return {
info: ok
? `▸ deleted session "${name}" — current screen still shows the conversation, but next launch starts fresh`
: `could not delete session "${name}" (already gone?)`,
};
}
case "status": {
const branchBudget = loop.branchOptions.budget ?? 1;
const ctxMax = DEEPSEEK_CONTEXT_TOKENS[loop.model] ?? DEFAULT_CONTEXT_TOKENS;
const lastPromptTokens = loop.stats.summary().lastPromptTokens;
const ctxPct = ctxMax > 0 ? Math.round((lastPromptTokens / ctxMax) * 100) : 0;
const ctxLine =
lastPromptTokens > 0
? ` ctx ${compactNum(lastPromptTokens)}/${compactNum(ctxMax)} (${ctxPct}%)`
: " ctx no turns yet";
const pending = ctx.pendingEditCount ?? 0;
const sessionLine = loop.sessionName
? ` session "${loop.sessionName}" · ${loop.log.length} messages in log (resumed ${loop.resumedMessageCount})`
: " session (ephemeral — no persistence)";
const mcpCount = ctx.mcpSpecs?.length ?? 0;
const toolCount = loop.prefix.toolSpecs.length;
const mcpLine = ` mcp ${mcpCount} server(s), ${toolCount} tool(s) in registry`;
const pendingLine =
pending > 0 ? ` edits ${pending} pending (/apply to commit, /discard to drop)` : "";
const lines = [
` model ${loop.model}`,
` flags harvest=${loop.harvestEnabled ? "on" : "off"} · branch=${branchBudget > 1 ? branchBudget : "off"} · stream=${loop.stream ? "on" : "off"}`,
ctxLine,
mcpLine,
sessionLine,
];
if (pendingLine) lines.push(pendingLine);
return { info: lines.join("\n") };
}
case "model": {
const id = args[0];
if (!id) return { info: "usage: /model <id> (try deepseek-chat or deepseek-reasoner)" };
loop.configure({ model: id });
return { info: `model → ${id}` };
}
case "harvest": {
const arg = (args[0] ?? "").toLowerCase();
const on = arg === "" ? !loop.harvestEnabled : arg === "on" || arg === "true" || arg === "1";
loop.configure({ harvest: on });
return { info: `harvest → ${loop.harvestEnabled ? "on" : "off"}` };
}
case "preset": {
const name = (args[0] ?? "").toLowerCase();
if (name === "fast" || name === "default") {
loop.configure({ model: "deepseek-chat", harvest: false, branch: 1 });
return { info: "preset → fast (deepseek-chat, no harvest, no branch)" };
}
if (name === "smart") {
loop.configure({ model: "deepseek-reasoner", harvest: true, branch: 1 });
return { info: "preset → smart (reasoner + harvest, ~10x cost vs fast)" };
}
if (name === "max" || name === "best") {
loop.configure({ model: "deepseek-reasoner", harvest: true, branch: 3 });
return {
info: "preset → max (reasoner + harvest + branch3, ~30x cost vs fast, slowest)",
};
}
return { info: "usage: /preset <fast|smart|max>" };
}
case "branch": {
const raw = (args[0] ?? "").toLowerCase();
if (raw === "" || raw === "off" || raw === "0" || raw === "1") {
loop.configure({ branch: 1 });
return { info: "branch → off" };
}
const n = Number.parseInt(raw, 10);
if (!Number.isFinite(n) || n < 2) {
return { info: "usage: /branch <N> (N>=2, or 'off')" };
}
if (n > 8) {
return { info: "branch budget capped at 8 to prevent runaway cost" };
}
loop.configure({ branch: n });
return { info: `branch → ${n} (harvest auto-enabled; streaming disabled)` };
}
default:
return { unknown: true, info: `unknown command: /${cmd} (try /help)` };
}
}
/**
* Render a section (resources / prompts) of an MCP inspection into a
* compact "name count items" form, collapsing when unsupported.
* Names-only — descriptions and full metadata live in
* `reasonix mcp inspect`, which is purpose-built for the deep view.
*/
function appendSection(
lines: string[],
label: string,
section:
| { supported: true; items: Array<{ name: string }> }
| { supported: false; reason: string }
| undefined,
): void {
if (!section || !section.supported) {
lines.push(
` ${label.trim()} ${section?.supported === false ? "(not supported)" : "(none)"}`,
);
return;
}
const names = section.items.map((i) => i.name);
if (names.length === 0) {
lines.push(` ${label.trim()} (none)`);
return;
}
const head = names.slice(0, 5).join(", ");
const more = names.length > 5 ? ` +${names.length - 5} more` : "";
lines.push(` ${label.trim()} ${names.length} [${head}${more}]`);
}
function formatToolList(history: Array<{ toolName: string; text: string }>): string {
const total = history.length;
const header = `Tool calls in this session (${total}, most recent first):`;
// Show the 10 most recent. Older ones are rarely what the user
// wants — and the help footer tells them how to reach any entry
// by index if they do.
const shown = Math.min(total, 10);
const lines: string[] = [header];
for (let i = 0; i < shown; i++) {
const entry = history[total - 1 - i];
if (!entry) continue;
const idx = i + 1; // 1-based from most recent
const flat = entry.text.replace(/\s+/g, " ").trim();
const preview = flat.length > 80 ? `${flat.slice(0, 80)}…` : flat;
const name = entry.toolName.length > 24 ? `${entry.toolName.slice(0, 23)}…` : entry.toolName;
lines.push(
` #${String(idx).padStart(2)} ${name.padEnd(24)} ${String(entry.text.length).padStart(6)} chars ${preview}`,
);
}
if (total > shown) {
lines.push(` … (${total - shown} earlier, reach with /tool N)`);
}
lines.push("");
lines.push("View full output: /tool N (N=1 → most recent)");
return lines.join("\n");
}
function compactNum(n: number): string {
if (n < 1000) return String(n);
const k = n / 1000;
return k >= 100 ? `${Math.round(k)}k` : `${k.toFixed(1)}k`;
}
function stripOuterQuotes(s: string): string {
if (s.length >= 2 && s.startsWith('"') && s.endsWith('"')) {
return s.slice(1, -1);
}
return s;
}
/**
* Run `git add -A` then `git commit -m <message>` in `rootDir`. Returns
* a SlashResult with a human-scannable info line. We surface stderr on
* failure so the user sees exactly what git complained about (bad
* config, pre-commit hook rejection, nothing staged, etc.).
*/
function runGitCommit(rootDir: string, message: string): SlashResult {
const add = spawnSync("git", ["add", "-A"], { cwd: rootDir, encoding: "utf8" });
if (add.error || add.status !== 0) {
return { info: `git add failed (${add.status ?? "?"}):\n${gitTail(add)}` };
}
const commit = spawnSync("git", ["commit", "-m", message], {
cwd: rootDir,
encoding: "utf8",
});
if (commit.error || commit.status !== 0) {
return { info: `git commit failed (${commit.status ?? "?"}):\n${gitTail(commit)}` };
}
const firstLine = (commit.stdout || "").split(/\r?\n/)[0] ?? "";
return { info: `▸ committed: ${message}${firstLine ? `\n ${firstLine}` : ""}` };
}
/**
* Safely extract whatever diagnostic text is available from a spawnSync
* result — on Windows or when cwd doesn't exist, `stderr`/`stdout` can
* be `undefined` and the caller has only `error.message` to go on.
*/
function gitTail(res: ReturnType<typeof spawnSync>): string {
const stderr = (res.stderr as string | undefined) ?? "";
const stdout = (res.stdout as string | undefined) ?? "";
const body = stderr.trim() || stdout.trim();
if (body) return body;
if (res.error) return (res.error as Error).message;
return "(no output from git)";
}
// Slash-command barrel. Public surface is stable across the slash/
// split — App.tsx, tests, and sibling components continue to import
// { handleSlash, parseSlash, suggestSlashCommands, SLASH_COMMANDS, ... }
// from "./slash.js". Everything below is re-exported from the per-topic
// modules under ./slash/.
export {
SLASH_COMMANDS,
detectSlashArgContext,
parseSlash,
suggestSlashCommands,
} from "./slash/commands.js";
export { handleSlash } from "./slash/dispatch.js";
export type { SlashHandler } from "./slash/dispatch.js";
export type {
McpServerSummary,
SlashArgContext,
SlashCommandSpec,
SlashContext,
SlashResult,
} from "./slash/types.js";
+213
View File
@@ -0,0 +1,213 @@
import type { SlashArgContext, SlashCommandSpec } from "./types.js";
export const SLASH_COMMANDS: readonly SlashCommandSpec[] = [
{ cmd: "help", summary: "show the full command reference" },
{ cmd: "status", summary: "current model, flags, context, session" },
{
cmd: "preset",
argsHint: "<fast|smart|max>",
summary: "one-tap model + harvest + branch bundle",
argCompleter: ["fast", "smart", "max"],
},
{
cmd: "model",
argsHint: "<id>",
summary: "switch DeepSeek model id",
argCompleter: "models",
},
{ cmd: "models", summary: "list available models fetched from DeepSeek /models" },
{
cmd: "harvest",
argsHint: "[on|off]",
summary: "toggle Pillar-2 plan-state extraction",
argCompleter: ["on", "off"],
},
{
cmd: "branch",
argsHint: "<N|off>",
summary: "run N parallel samples per turn (N>=2)",
argCompleter: ["off", "2", "3", "4", "5"],
},
{
cmd: "effort",
argsHint: "<high|max>",
summary: "reasoning_effort cap — max is default (agent-class), high is cheaper/faster",
argCompleter: ["max", "high"],
},
{
cmd: "pro",
argsHint: "[off]",
summary: "arm v4-pro for the NEXT turn only (one-shot · auto-disarms after turn)",
argCompleter: ["off"],
},
{ cmd: "mcp", summary: "list MCP servers + tools attached to this session" },
{
cmd: "resource",
argsHint: "[uri]",
summary: "browse + read MCP resources (no arg → list URIs; <uri> → fetch contents)",
argCompleter: "mcp-resources",
},
{
cmd: "prompt",
argsHint: "[name]",
summary: "browse + fetch MCP prompts (no arg → list names; <name> → render prompt)",
argCompleter: "mcp-prompts",
},
{ cmd: "tool", argsHint: "[N]", summary: "dump full output of the Nth tool call (1=latest)" },
{
cmd: "memory",
argsHint: "[list|show <name>|forget <name>|clear <scope> confirm]",
summary: "show / manage pinned memory (REASONIX.md + ~/.reasonix/memory)",
},
{
cmd: "skill",
argsHint: "[list|show <name>|<name> [args]]",
summary: "list / run user skills (<project>/.reasonix/skills + ~/.reasonix/skills)",
},
{
cmd: "hooks",
argsHint: "[reload]",
summary: "list active hooks (settings.json under .reasonix/) · reload re-reads from disk",
},
{
cmd: "update",
summary: "show current vs latest version + the shell command to upgrade",
},
{
cmd: "stats",
summary:
"cross-session cost dashboard (today / week / month / all-time · cache hit · vs Claude)",
},
{ cmd: "think", summary: "dump the last turn's full R1 reasoning (reasoner only)" },
{
cmd: "context",
summary: "break down where context tokens are going: system / tools / per-turn log",
},
{ cmd: "retry", summary: "truncate & resend your last message (fresh sample)" },
{
cmd: "compact",
argsHint: "[tokens]",
summary:
"shrink oversized tool results AND tool-call args (edit_file search/replace) in the log; cap in tokens, default 4000",
},
{ cmd: "keys", summary: "show all keyboard shortcuts and prompt prefixes" },
{ cmd: "sessions", summary: "list saved sessions (current marked with ▸)" },
{ cmd: "forget", summary: "delete the current session from disk" },
{ cmd: "setup", summary: "reminds you to exit and run `reasonix setup`" },
{ cmd: "clear", summary: "clear visible scrollback only (log/context kept)" },
{ cmd: "new", summary: "start a fresh conversation (clear context + scrollback)" },
{ cmd: "exit", summary: "quit the TUI" },
// Code-mode only
{ cmd: "apply", summary: "commit pending edit blocks to disk", contextual: "code" },
{ cmd: "discard", summary: "drop pending edit blocks without writing", contextual: "code" },
{ cmd: "undo", summary: "roll back the last applied edit batch", contextual: "code" },
{
cmd: "history",
summary: "list every edit batch this session (ids for /show, undone markers)",
contextual: "code",
},
{
cmd: "show",
argsHint: "[id]",
summary: "dump a stored edit diff (omit id for newest non-undone)",
contextual: "code",
},
{
cmd: "commit",
argsHint: '"msg"',
summary: "git add -A && git commit -m ...",
contextual: "code",
},
{
cmd: "plan",
argsHint: "[on|off]",
summary: "toggle read-only plan mode (writes bounced until submit_plan + approval)",
contextual: "code",
argCompleter: ["on", "off"],
},
{
cmd: "apply-plan",
summary: "force-approve a pending / in-text plan (fallback if picker was missed)",
contextual: "code",
},
{
cmd: "mode",
argsHint: "[review|auto]",
summary: "edit-gate: review (queue for /apply) or auto (apply+undo banner). Shift+Tab cycles.",
contextual: "code",
argCompleter: ["review", "auto"],
},
{ cmd: "jobs", summary: "list background jobs started by run_background", contextual: "code" },
{
cmd: "kill",
argsHint: "<id>",
summary: "stop a background job by id (SIGTERM → SIGKILL after grace)",
contextual: "code",
},
{
cmd: "logs",
argsHint: "<id> [lines]",
summary: "tail a background job's output (default last 80 lines)",
contextual: "code",
},
];
/**
* Filter the registry by a prefix string (without the leading `/`).
* Empty prefix returns the full non-contextual list (plus code-mode
* entries when `codeMode` is true). Case-insensitive.
*/
export function suggestSlashCommands(prefix: string, codeMode = false): SlashCommandSpec[] {
const p = prefix.toLowerCase();
return SLASH_COMMANDS.filter((c) => {
if (c.contextual === "code" && !codeMode) return false;
return c.cmd.startsWith(p);
});
}
/**
* Classify the prompt buffer for argument completion. Returns `null`
* when the buffer isn't in a slash-with-args state.
*
* Firing shape: input must start with `/<cmd> ` (space after a known
* command). The character right after the space through end-of-buffer
* is the "arg tail"; if the tail has NO internal whitespace the
* picker is live (tail is the partial). If the tail has whitespace,
* the user has moved past the first argument position and we surface
* the usage hint only.
*/
export function detectSlashArgContext(input: string, codeMode = false): SlashArgContext | null {
// `/cmd <rest>` — one space, rest captured up to end-of-buffer.
const m = /^\/(\S+) ([\s\S]*)$/.exec(input);
if (!m) return null;
const cmdName = m[1]!.toLowerCase();
const tail = m[2] ?? "";
const spec = SLASH_COMMANDS.find(
(s) => s.cmd === cmdName && (s.contextual !== "code" || codeMode),
);
if (!spec) return null;
const hasInternalSpace = /\s/.test(tail);
const partialOffset = input.length - tail.length;
if (hasInternalSpace) {
// Past the first arg position (typing the second arg for e.g.
// `/edit <file> <instruction>`, or mid-sentence for free-form).
return { spec, partial: tail, partialOffset, kind: "hint" };
}
// No internal whitespace — we're still typing the first arg. Picker
// is live if the spec declares a completer; otherwise show a hint
// ("what goes here?") since the user's guessing.
return {
spec,
partial: tail,
partialOffset,
kind: spec.argCompleter ? "picker" : "hint",
};
}
export function parseSlash(text: string): { cmd: string; args: string[] } | null {
if (!text.startsWith("/")) return null;
const parts = text.slice(1).trim().split(/\s+/);
const cmd = parts[0]?.toLowerCase() ?? "";
if (!cmd) return null;
return { cmd, args: parts.slice(1) };
}
+52
View File
@@ -0,0 +1,52 @@
import type { CacheFirstLoop } from "../../../loop.js";
import { handlers as adminHandlers } from "./handlers/admin.js";
import { handlers as basicHandlers } from "./handlers/basic.js";
import { handlers as editsHandlers } from "./handlers/edits.js";
import { handlers as jobsHandlers } from "./handlers/jobs.js";
import { handlers as mcpHandlers } from "./handlers/mcp.js";
import { handlers as memoryHandlers } from "./handlers/memory.js";
import { handlers as modelHandlers } from "./handlers/model.js";
import { handlers as observabilityHandlers } from "./handlers/observability.js";
import { handlers as sessionsHandlers } from "./handlers/sessions.js";
import { handlers as skillHandlers } from "./handlers/skill.js";
import type { SlashContext, SlashResult } from "./types.js";
/**
* A slash handler receives the command's args + the loop + shared
* runtime context, and returns a synchronous SlashResult. Async work
* (balance fetches, stop_job) fires-and-forgets via `ctx.postInfo`
* instead — keeps the TUI input non-blocking.
*/
export type SlashHandler = (args: string[], loop: CacheFirstLoop, ctx: SlashContext) => SlashResult;
/**
* Flat map of cmd → handler. Composed from per-topic modules so each
* feature's logic stays local; aliases (e.g. `exit` / `quit`) are just
* extra keys in the per-module handlers bag pointing at the same fn.
*
* Ordering of the spread matters only for duplicate keys; there are
* none. Keep alphabetical for diff sanity when adding modules.
*/
const HANDLERS: Record<string, SlashHandler> = {
...adminHandlers,
...basicHandlers,
...editsHandlers,
...jobsHandlers,
...mcpHandlers,
...memoryHandlers,
...modelHandlers,
...observabilityHandlers,
...sessionsHandlers,
...skillHandlers,
};
export function handleSlash(
cmd: string,
args: string[],
loop: CacheFirstLoop,
ctx: SlashContext = {},
): SlashResult {
const h = HANDLERS[cmd];
if (h) return h(args, loop, ctx);
return { unknown: true, info: `unknown command: /${cmd} (try /help)` };
}
+158
View File
@@ -0,0 +1,158 @@
import {
HOOK_EVENTS,
type HookEvent,
type ResolvedHook,
globalSettingsPath,
projectSettingsPath,
} from "../../../../hooks.js";
import { aggregateUsage, defaultUsageLogPath, readUsageLog } from "../../../../usage.js";
import { VERSION, compareVersions, isNpxInstall } from "../../../../version.js";
import { renderDashboard } from "../../../commands/stats.js";
import type { SlashHandler } from "../dispatch.js";
const hooks: SlashHandler = (args, loop, ctx) => {
const sub = (args[0] ?? "").toLowerCase();
if (sub === "reload") {
if (!ctx.reloadHooks) {
return {
info: "/hooks reload is not available in this context (no reload callback wired).",
};
}
const count = ctx.reloadHooks();
return { info: `▸ reloaded hooks · ${count} active` };
}
if (sub !== "" && sub !== "list" && sub !== "ls") {
return {
info: "usage: /hooks list active hooks\n /hooks reload re-read settings.json files",
};
}
const all = loop.hooks;
const projPath = ctx.codeRoot ? projectSettingsPath(ctx.codeRoot) : undefined;
const globPath = globalSettingsPath();
if (all.length === 0) {
const lines = [
"no hooks configured.",
"",
"drop a settings.json with a `hooks` key into either of:",
ctx.codeRoot
? ` · ${projPath} (project)`
: " · <project>/.reasonix/settings.json (project)",
` · ${globPath} (global)`,
"",
"events: PreToolUse, PostToolUse, UserPromptSubmit, Stop",
"exit 0 = pass · exit 2 = block (Pre*) · other = warn",
];
return { info: lines.join("\n") };
}
const grouped = new Map<HookEvent, ResolvedHook[]>();
for (const event of HOOK_EVENTS) grouped.set(event, []);
for (const h of all) grouped.get(h.event)?.push(h);
const lines: string[] = [`▸ ${all.length} hook(s) loaded`];
for (const event of HOOK_EVENTS) {
const list = grouped.get(event) ?? [];
if (list.length === 0) continue;
lines.push("", `${event}:`);
for (const h of list) {
const match = h.match && h.match !== "*" ? ` match=${h.match}` : "";
const desc = h.description ? ` — ${h.description}` : "";
lines.push(` [${h.scope}]${match} ${h.command}${desc}`);
}
}
lines.push("", `sources: project=${projPath ?? "(none — chat mode)"} · global=${globPath}`);
return { info: lines.join("\n") };
};
/**
* `/update` — inside the TUI we deliberately do NOT spawn `npm install`.
* stdio:inherit into a running Ink renderer corrupts the display, and
* the process being upgraded is the same process that's still reading
* its own binaries (messy on Windows). Instead we surface what we
* already know from the App's background registry check and print the
* exact shell command the user should run after exiting.
*
* The `latestVersion` ctx field is populated by App.tsx's mount-time
* `getLatestVersion()` effect. When it's `null` we report the check
* as pending/offline — still a useful output (current version + how
* to force a fresh check from another terminal).
*/
const update: SlashHandler = (_args, _loop, ctx) => {
const latest = ctx.latestVersion ?? null;
const lines: string[] = [`current: reasonix ${VERSION}`];
if (latest === null) {
// Kick off a fresh fetch so a follow-up /update a few seconds
// later has a real answer instead of the same pending message.
ctx.refreshLatestVersion?.();
lines.push(
"latest: (not yet resolved — background check in flight or offline)",
"",
"triggered a fresh registry fetch — retry `/update` in a few seconds,",
"or run `reasonix update` in another terminal to force it synchronously.",
);
return { info: lines.join("\n") };
}
lines.push(`latest: reasonix ${latest}`);
const diff = compareVersions(VERSION, latest);
if (diff >= 0) {
lines.push("", "you're on the latest. nothing to do.");
return { info: lines.join("\n") };
}
if (isNpxInstall()) {
lines.push(
"",
"you're running via npx — the next `npx reasonix ...` launch will auto-fetch.",
"to force a refresh sooner: `npm cache clean --force`.",
);
} else {
lines.push(
"",
"to upgrade, exit this session and run:",
" reasonix update (interactive, dry-run supported via --dry-run)",
" npm install -g reasonix@latest (direct)",
"",
"in-session install is deliberately disabled — the npm spawn would",
"corrupt this TUI's rendering and Windows can lock the running binary.",
);
}
return { info: lines.join("\n") };
};
/**
* `/stats` — dashboard view of `~/.reasonix/usage.jsonl`, the same
* roll-up `reasonix stats` (no arg) prints at the shell. Synchronous
* disk read; cheap enough that we don't bother caching between slash
* invocations.
*
* No transcript-path variant in-TUI: the per-file summary is scripty
* and rarely wanted mid-session. If someone needs it they have the
* CLI form (`reasonix stats <path>`).
*/
const stats: SlashHandler = () => {
const path = defaultUsageLogPath();
const records = readUsageLog(path);
if (records.length === 0) {
return {
info: [
"no usage data yet.",
"",
` ${path}`,
"",
"every turn you run here appends one record — this session's turns",
"will show up in the dashboard once you send a message.",
].join("\n"),
};
}
const agg = aggregateUsage(records);
return { info: renderDashboard(agg, path) };
};
export const handlers: Record<string, SlashHandler> = {
hook: hooks,
hooks,
update,
stats,
};
+151
View File
@@ -0,0 +1,151 @@
import type { SlashHandler } from "../dispatch.js";
const exit: SlashHandler = () => ({ exit: true });
const clear: SlashHandler = () => ({
clear: true,
info: "▸ cleared visible scrollback only. Context (message log) is intact — next turn still sees everything. Use /new to start fresh, or /forget to delete the session entirely.",
});
const resetLog: SlashHandler = (_args, loop) => {
// Actually drop the in-memory log + rewrite the session file so the
// NEXT call has no prior context. Keeps session name, model, and
// other config — just the conversation is reset.
const { dropped } = loop.clearLog();
return {
clear: true,
info: `▸ new conversation — dropped ${dropped} message(s) from context. Same session, fresh slate.`,
};
};
const keys: SlashHandler = () => ({
info: [
"Keyboard & prompt shortcuts:",
"",
" Enter submit the current prompt",
" Shift+Enter / Ctrl+J insert a newline (multi-line prompt)",
" \\<Enter> bash-style line continuation",
" ← → ↑ ↓ move cursor / recall history when buffer empty",
" Ctrl+A / Ctrl+E jump to start / end of the current line",
" Backspace delete left; Delete delete under cursor",
" Esc abort the in-flight turn",
" y / n accept / reject pending edits (code mode)",
" Shift+Tab cycle edit gate: review ↔ AUTO (code mode, persists to config)",
" u undo the latest non-undone edit batch (session-wide, not just banner)",
"",
"Prompt prefixes:",
" /<name> slash command; Tab/Enter picks from the suggestion list",
" @<path> inline a file under [Referenced files] (code mode).",
" Trailing `@…` opens a file picker; ↑/↓ navigate, Tab/Enter pick.",
" !<cmd> run <cmd> as shell in the sandbox root; output goes into context",
" so the model sees it next turn. No allowlist gate.",
"",
"Pickers (slash + @-mention):",
" ↑ / ↓ navigate the suggestion list",
" Tab insert the highlighted item without submitting",
" Enter insert and (slash) run it, (@) keep editing",
"",
"MCP exploration:",
" /mcp servers + tool/resource/prompt counts",
" /resource [uri] browse & read resources exposed by your MCP servers",
" /prompt [name] browse & fetch prompts exposed by your MCP servers",
"",
"Useful slashes: /help · /context · /stats · /compact · /new · /exit",
].join("\n"),
});
const help: SlashHandler = () => ({
info: [
"Commands:",
" /help this message",
" /keys keyboard shortcuts + prompt prefixes (!, @, /)",
" /status show current settings",
" /preset <fast|smart|max> one-tap presets — see below",
" /model <id> deepseek-v4-flash or deepseek-v4-pro",
" /pro [off] arm v4-pro for NEXT turn only (one-shot, auto-disarms)",
" /harvest [on|off] Pillar 2: structured plan-state extraction (OPT-IN — costs extra)",
" /branch <N|off> run N parallel samples (N>=2) — MANUAL ONLY, N× cost",
" /effort <high|max> reasoning_effort cap (max=full thinking, high=cheaper/faster)",
" /mcp list MCP servers + tools attached to this session",
" /resource [uri] browse + read MCP resources (no arg → list URIs; <uri> → fetch)",
" /prompt [name] browse + fetch MCP prompts (no arg → list names; <name> → render)",
" /setup (exit + reconfigure) → run `reasonix setup`",
" /compact [tokens] shrink large tool results in history (default 4000 tokens/result)",
" /think dump the most recent turn's full R1 reasoning (reasoner only)",
" /tool [N] list tool calls (or dump full output of #N, 1=most recent)",
" /memory [sub] show pinned memory (REASONIX.md + ~/.reasonix/memory).",
" subs: list | show <name> | forget <name> | clear <scope> confirm",
" /skill [sub] list / run user skills (project/.reasonix/skills + ~/.reasonix/skills).",
" subs: list | show <name> | <name> [args] (injects skill body as user turn)",
" /retry truncate & resend your last message (fresh sample from the model)",
" /apply (code mode) commit the pending edit blocks to disk",
" /discard (code mode) drop pending edits without writing",
" /undo (code mode) roll back the latest non-undone edit batch",
" /history (code mode) list every edit batch this session",
" /show [id] (code mode) dump a stored edit diff (newest when id omitted)",
' /commit "msg" (code mode) git add -A && git commit -m "msg"',
" /plan [on|off] (code mode) toggle read-only plan mode; writes gated behind submit_plan + your approval",
" /apply-plan (code mode) force-approve pending/in-text plan (fallback)",
" /mode [review|auto] (code mode) edit-gate: queue edits for /apply or apply instantly (Shift+Tab cycles, u undoes within 5s)",
" /jobs (code mode) list background processes (run_background) — running and exited",
" /kill <id> (code mode) stop a background job by id (SIGTERM → SIGKILL)",
" /logs <id> [lines] (code mode) tail a background job's output (default 80 lines)",
" /sessions list saved sessions (current is marked with ▸)",
" /forget delete the current session from disk",
" /new start fresh: drop all context + clear scrollback",
" /clear clear displayed scrollback only (context kept — model still sees it)",
" /exit quit",
"",
"Shell shortcut:",
" !<cmd> run <cmd> in the sandbox root; output goes into",
" the conversation so the model sees it next turn.",
" No allowlist gate — user-typed = explicit consent.",
" Example: !git status !ls src/ !npm test",
"",
"File references (code mode):",
" @path/to/file inline file content under [Referenced files] on send.",
" Type `@` to open the picker (↑↓ navigate, Tab/Enter pick).",
"",
"Presets (branch + harvest are NEVER auto-enabled — opt-in only):",
" fast v4-flash · effort=high cheapest · quick Q&A, one-line edits",
" smart v4-flash · effort=max ← default · day-to-day coding",
" max v4-pro · effort=max ~12× fast · hard single-shots",
"",
"Sessions (auto-enabled by default, named 'default'):",
" reasonix chat --session <name> use a different named session",
" reasonix chat --no-session disable persistence for this run",
].join("\n"),
});
const setup: SlashHandler = () => ({
info:
"To reconfigure (preset, MCP servers, API key), exit this chat and run " +
"`reasonix setup`. Changes take effect on next launch.",
});
const retry: SlashHandler = (_args, loop) => {
const prev = loop.retryLastUser();
if (!prev) {
return {
info: "nothing to retry — no prior user message in this session's log.",
};
}
const preview = prev.length > 80 ? `${prev.slice(0, 80)}…` : prev;
return {
info: `▸ retrying: "${preview}"`,
resubmit: prev,
};
};
export const handlers: Record<string, SlashHandler> = {
exit,
quit: exit,
clear,
new: resetLog,
reset: resetLog,
keys,
help,
"?": help,
setup,
retry,
};
+142
View File
@@ -0,0 +1,142 @@
import type { EditMode } from "../../../../config.js";
import type { SlashHandler } from "../dispatch.js";
import { runGitCommit, stripOuterQuotes } from "../helpers.js";
const undo: SlashHandler = (args, _loop, ctx) => {
if (!ctx.codeUndo) {
return {
info: "/undo is only available inside `reasonix code` — chat mode doesn't apply edits.",
};
}
return { info: ctx.codeUndo(args) };
};
const history: SlashHandler = (_args, _loop, ctx) => {
if (!ctx.codeHistory) {
return { info: "/history is only available inside `reasonix code`." };
}
return { info: ctx.codeHistory() };
};
const show: SlashHandler = (args, _loop, ctx) => {
if (!ctx.codeShowEdit) {
return { info: "/show is only available inside `reasonix code`." };
}
return { info: ctx.codeShowEdit(args) };
};
const apply: SlashHandler = (_args, _loop, ctx) => {
if (!ctx.codeApply) {
return {
info: "/apply is only available inside `reasonix code` (nothing to apply here).",
};
}
return { info: ctx.codeApply() };
};
const discard: SlashHandler = (_args, _loop, ctx) => {
if (!ctx.codeDiscard) {
return {
info: "/discard is only available inside `reasonix code`.",
};
}
return { info: ctx.codeDiscard() };
};
const plan: SlashHandler = (args, _loop, ctx) => {
if (!ctx.setPlanMode) {
return {
info: "/plan is only available inside `reasonix code` — chat mode doesn't gate tool writes.",
};
}
const currentOn = Boolean(ctx.planMode);
const raw = (args[0] ?? "").toLowerCase();
let target: boolean;
if (raw === "on" || raw === "true" || raw === "1") target = true;
else if (raw === "off" || raw === "false" || raw === "0") target = false;
else target = !currentOn;
ctx.setPlanMode(target);
if (target) {
return {
info: "▸ plan mode ON — write tools are gated; the model MUST call `submit_plan` before anything executes. (The model can also call submit_plan on its own for big tasks even when plan mode is off — this toggle is the stronger, explicit constraint.) Type /plan off to leave.",
};
}
return {
info: "▸ plan mode OFF — write tools are live again. Model can still propose plans autonomously for large tasks.",
};
};
const applyPlan: SlashHandler = (_args, _loop, ctx) => {
if (!ctx.setPlanMode) {
return {
info: "/apply-plan is only available inside `reasonix code`.",
};
}
ctx.setPlanMode(false);
ctx.clearPendingPlan?.();
return {
info: "▸ plan approved — implementing",
resubmit:
"The plan above has been approved. Implement it now. You are out of plan mode — use edit_file / write_file / run_command as needed. Stick to the plan unless you discover a concrete reason to deviate; if you do, tell me and wait for a response before making that deviation.",
};
};
const mode: SlashHandler = (args, _loop, ctx) => {
if (!ctx.setEditMode) {
return {
info: "/mode is only available inside `reasonix code`.",
};
}
const raw = (args[0] ?? "").toLowerCase();
const current = ctx.editMode ?? "review";
let target: EditMode;
if (raw === "review") target = "review";
else if (raw === "auto") target = "auto";
else if (raw === "") {
// Bare /mode toggles, mirroring Shift+Tab. Users who just want to
// see current mode without flipping can read /status.
target = current === "auto" ? "review" : "auto";
} else {
return { info: "usage: /mode <review|auto> (Shift+Tab also cycles)" };
}
ctx.setEditMode(target);
return {
info:
target === "auto"
? "▸ edit mode: AUTO — edits apply immediately; press u within 5s to undo, or /undo later"
: "▸ edit mode: review — edits queue for /apply (or y) / /discard (or n)",
};
};
const commit: SlashHandler = (args, _loop, ctx) => {
if (!ctx.codeRoot) {
return {
info: "/commit is only available inside `reasonix code` (needs a rooted git repo).",
};
}
// Reassemble the original argv. The parser lowercases cmd but leaves
// args alone, and the TUI splits on whitespace which mangles quoted
// messages — rejoin with spaces and strip a surrounding pair of
// double quotes if the user wrote them.
const raw = args.join(" ").trim();
const message = stripOuterQuotes(raw);
if (!message) {
return {
info: `usage: /commit "your commit message" — runs \`git add -A && git commit -m "…"\` in ${ctx.codeRoot}`,
};
}
return runGitCommit(ctx.codeRoot, message);
};
export const handlers: Record<string, SlashHandler> = {
undo,
history,
show,
apply,
discard,
plan,
"apply-plan": applyPlan,
applyplan: applyPlan,
mode,
commit,
};
+84
View File
@@ -0,0 +1,84 @@
import type { SlashHandler } from "../dispatch.js";
const jobs: SlashHandler = (_args, _loop, ctx) => {
if (!ctx.jobs) {
return { info: "/jobs is only available inside `reasonix code`." };
}
const rows = ctx.jobs.list();
if (rows.length === 0) {
return { info: "no background jobs yet — use run_background to start one" };
}
const lines = ["Background jobs:"];
for (const r of rows) {
const age = ((Date.now() - r.startedAt) / 1000).toFixed(1);
const state = r.running
? `running · pid ${r.pid ?? "?"}`
: r.exitCode !== null
? `exit ${r.exitCode}`
: r.spawnError
? "failed"
: "stopped";
lines.push(
` ${String(r.id).padStart(3)} ${state.padEnd(20)} ${age.padStart(6)}s ago $ ${r.command}`,
);
}
lines.push("");
lines.push("/kill <id> to stop one · /logs <id> [lines] to tail output");
return { info: lines.join("\n") };
};
const kill: SlashHandler = (args, _loop, ctx) => {
if (!ctx.jobs) return { info: "/kill is only available inside `reasonix code`." };
const id = Number.parseInt(args[0] ?? "", 10);
if (!Number.isFinite(id)) return { info: "usage: /kill <id> (see /jobs for ids)" };
const rec = ctx.jobs.list().find((r) => r.id === id);
if (!rec) return { info: `job ${id}: not found` };
if (!rec.running) return { info: `job ${id} already exited (${rec.exitCode ?? "?"})` };
// Fire-and-forget: the registry waits for grace + SIGKILL internally;
// returning immediately keeps the slash synchronous so the user's
// prompt doesn't lock up for 2s on every /kill. The postInfo
// callback lands a follow-up row in historical when the kill
// actually completes, so the user sees "job N stopped" without
// polling /jobs.
const jobsRef = ctx.jobs;
void (async () => {
const final = await jobsRef.stop(id);
if (!final) return;
const status = final.running
? "still alive after SIGKILL (!) — report this as a bug"
: final.exitCode !== null
? `exit ${final.exitCode}`
: "stopped";
ctx.postInfo?.(`▸ job ${id} ${status}`);
})();
return {
info: `▸ stopping job ${id} (tree kill: SIGTERM → SIGKILL after 2s grace; Windows: taskkill /T /F)`,
};
};
const logs: SlashHandler = (args, _loop, ctx) => {
if (!ctx.jobs) return { info: "/logs is only available inside `reasonix code`." };
const id = Number.parseInt(args[0] ?? "", 10);
if (!Number.isFinite(id)) {
return { info: "usage: /logs <id> [lines] (default last 80 lines)" };
}
const requested = Number.parseInt(args[1] ?? "", 10);
const tail = Number.isFinite(requested) && requested > 0 ? requested : 80;
const out = ctx.jobs.read(id, { tailLines: tail });
if (!out) return { info: `job ${id}: not found` };
const status = out.running
? `running · pid ${out.pid ?? "?"}`
: out.exitCode !== null
? `exited ${out.exitCode}`
: out.spawnError
? `failed (${out.spawnError})`
: "stopped";
const header = `[job ${id} · ${status}]\n$ ${out.command}`;
return { info: out.output ? `${header}\n${out.output}` : header };
};
export const handlers: Record<string, SlashHandler> = {
jobs,
kill,
logs,
};
+64
View File
@@ -0,0 +1,64 @@
import type { SlashHandler } from "../dispatch.js";
import { appendSection } from "../helpers.js";
const mcp: SlashHandler = (_args, loop, ctx) => {
const servers = ctx.mcpServers ?? [];
const specs = ctx.mcpSpecs ?? [];
const toolSpecs = loop.prefix.toolSpecs ?? [];
if (servers.length === 0 && specs.length === 0 && toolSpecs.length === 0) {
return {
info:
"no MCP servers attached. Run `reasonix setup` to pick some, " +
'or launch with --mcp "<spec>". `reasonix mcp list` shows the catalog.',
};
}
// Rich path — we have full inspection reports, so show each server
// with its tools / resources / prompts grouped together.
if (servers.length > 0) {
const lines: string[] = [];
let anyResources = false;
let anyPrompts = false;
for (const s of servers) {
const { report } = s;
const serverName = report.serverInfo.name || "(unknown)";
const serverVer = report.serverInfo.version ? ` v${report.serverInfo.version}` : "";
lines.push(`[${s.label}] ${serverName}${serverVer} — ${s.spec}`);
lines.push(` tools ${s.toolCount}`);
appendSection(lines, "resources", report.resources);
appendSection(lines, "prompts ", report.prompts);
if (report.resources.supported && report.resources.items.length > 0) anyResources = true;
if (report.prompts.supported && report.prompts.items.length > 0) anyPrompts = true;
lines.push("");
}
if (anyResources || anyPrompts) {
const hints: string[] = [];
if (anyResources) hints.push("`/resource` to browse+read");
if (anyPrompts) hints.push("`/prompt` to browse+fetch");
lines.push(hints.join(" · "));
} else {
lines.push(
"Chat mode consumes tools today; resources+prompts are surfaced here for awareness.",
);
}
lines.push(
"Full catalog: `reasonix mcp list` · deeper diagnosis: `reasonix mcp inspect <spec>`.",
);
return { info: lines.join("\n") };
}
// Fallback — older path when the TUI hasn't populated `mcpServers`.
const lines: string[] = [];
if (specs.length > 0) {
lines.push(`MCP servers (${specs.length}):`);
for (const spec of specs) lines.push(` · ${spec}`);
lines.push("");
}
if (toolSpecs.length > 0) {
lines.push(`Tools in registry (${toolSpecs.length}):`);
for (const t of toolSpecs) lines.push(` · ${t.function.name}`);
}
lines.push("");
lines.push("To change this set, exit and run `reasonix setup`.");
return { info: lines.join("\n") };
};
export const handlers: Record<string, SlashHandler> = { mcp };
+169
View File
@@ -0,0 +1,169 @@
import {
PROJECT_MEMORY_FILE,
memoryEnabled,
readProjectMemory,
} from "../../../../project-memory.js";
import { type MemoryScope, MemoryStore } from "../../../../user-memory.js";
import type { SlashHandler } from "../dispatch.js";
import { resolveMemoryTarget } from "../helpers.js";
/**
* `/memory` family. Bare `/memory` shows what's pinned (REASONIX.md +
* both MEMORY.md blocks). Subcommands manage the user-memory store:
* list — every memory file, both scopes
* show <name> — dump one file's body
* show <scope>/<name> — disambiguate when name exists in both scopes
* forget <name> — delete (same scope resolution as show)
* clear <scope> confirm — wipe a scope (typed literal "confirm" required)
*/
const memory: SlashHandler = (args, _loop, ctx) => {
if (!memoryEnabled()) {
return {
info: "memory is disabled (REASONIX_MEMORY=off in env). Unset the var to re-enable — no REASONIX.md or ~/.reasonix/memory content will be pinned in the meantime.",
};
}
if (!ctx.memoryRoot) {
return {
info: "no working directory on this session — `/memory` needs a root to resolve REASONIX.md from. (Running in a test harness?)",
};
}
// `codeRoot` is set only when running `reasonix code`. Chat mode has
// `memoryRoot` = cwd (for REASONIX.md), but we don't treat cwd as a
// sandbox — project-scope user memory requires a real code-mode root.
const store = new MemoryStore({ projectRoot: ctx.codeRoot });
const sub = (args[0] ?? "").toLowerCase();
if (sub === "list" || sub === "ls") {
const entries = store.list();
if (entries.length === 0) {
return {
info: "no user memories yet. The model can call `remember` to save one, or you can create files by hand in ~/.reasonix/memory/global/ or the per-project subdir.",
};
}
const lines = [`User memories (${entries.length}):`];
for (const e of entries) {
const tag = `${e.scope}/${e.type}`.padEnd(18);
const name = e.name.padEnd(28);
const desc = e.description.length > 70 ? `${e.description.slice(0, 69)}…` : e.description;
lines.push(` ${tag} ${name} ${desc}`);
}
lines.push("");
lines.push("View body: /memory show <name> Delete: /memory forget <name>");
return { info: lines.join("\n") };
}
if (sub === "show" || sub === "cat") {
const target = args[1];
if (!target) return { info: "usage: /memory show <name> or /memory show <scope>/<name>" };
const resolved = resolveMemoryTarget(store, target);
if (!resolved) return { info: `no memory found: ${target}` };
try {
const entry = store.read(resolved.scope, resolved.name);
return {
info: [
`▸ ${entry.scope}/${entry.name} (${entry.type}, created ${entry.createdAt || "?"})`,
entry.description ? ` ${entry.description}` : "",
"",
entry.body,
]
.filter((l) => l !== "")
.concat("")
.join("\n"),
};
} catch (err) {
return { info: `show failed: ${(err as Error).message}` };
}
}
if (sub === "forget" || sub === "rm" || sub === "delete") {
const target = args[1];
if (!target) return { info: "usage: /memory forget <name> or /memory forget <scope>/<name>" };
const resolved = resolveMemoryTarget(store, target);
if (!resolved) return { info: `no memory found: ${target}` };
try {
const ok = store.delete(resolved.scope, resolved.name);
return {
info: ok
? `▸ forgot ${resolved.scope}/${resolved.name}. Next /new or launch won't see it.`
: `could not forget ${resolved.scope}/${resolved.name} (already gone?)`,
};
} catch (err) {
return { info: `forget failed: ${(err as Error).message}` };
}
}
if (sub === "clear") {
const rawScope = (args[1] ?? "").toLowerCase();
if (rawScope !== "global" && rawScope !== "project") {
return { info: "usage: /memory clear <global|project> confirm" };
}
if ((args[2] ?? "").toLowerCase() !== "confirm") {
return {
info: `about to delete every memory in scope=${rawScope}. Re-run with the word 'confirm' to proceed: /memory clear ${rawScope} confirm`,
};
}
const scope = rawScope as MemoryScope;
const entries = store.list().filter((e) => e.scope === scope);
let deleted = 0;
for (const e of entries) {
try {
if (store.delete(scope, e.name)) deleted++;
} catch {
/* skip */
}
}
return { info: `▸ cleared scope=${scope} — deleted ${deleted} memory file(s).` };
}
// Bare `/memory` — show REASONIX.md + both MEMORY.md blocks.
const parts: string[] = [];
const projMem = readProjectMemory(ctx.memoryRoot);
if (projMem) {
const hdr = projMem.truncated
? `▸ ${PROJECT_MEMORY_FILE}: ${projMem.path} (${projMem.originalChars.toLocaleString()} chars, truncated)`
: `▸ ${PROJECT_MEMORY_FILE}: ${projMem.path} (${projMem.originalChars.toLocaleString()} chars)`;
parts.push(hdr, "", projMem.content);
}
const globalIdx = store.loadIndex("global");
if (globalIdx) {
parts.push(
"",
`▸ global memory (${globalIdx.originalChars.toLocaleString()} chars${globalIdx.truncated ? ", truncated" : ""})`,
"",
globalIdx.content,
);
}
const projectIdx = store.loadIndex("project");
if (projectIdx) {
parts.push(
"",
`▸ project memory (${projectIdx.originalChars.toLocaleString()} chars${projectIdx.truncated ? ", truncated" : ""})`,
"",
projectIdx.content,
);
}
if (parts.length === 0) {
return {
info: [
`no memory pinned in ${ctx.memoryRoot}.`,
"",
"Three layers are available:",
` 1. ${PROJECT_MEMORY_FILE} — committable team memory (in the repo).`,
" 2. ~/.reasonix/memory/global/ — your cross-project private memory.",
` 3. ~/.reasonix/memory/<project-hash>/ — this project's private memory.`,
"",
"Ask the model to `remember` something, or hand-edit files directly.",
"Changes take effect on next /new or launch — the system prompt is hashed once per session to keep the prefix cache warm.",
"",
"Subcommands: /memory list | /memory show <name> | /memory forget <name> | /memory clear <scope> confirm",
].join("\n"),
};
}
parts.push(
"",
"Changes take effect on next /new or launch. Subcommands: /memory list | show | forget | clear",
);
return { info: parts.join("\n") };
};
export const handlers: Record<string, SlashHandler> = { memory };
+187
View File
@@ -0,0 +1,187 @@
import { saveReasoningEffort } from "../../../../config.js";
import type { SlashHandler } from "../dispatch.js";
const model: SlashHandler = (args, loop, ctx) => {
const id = args[0];
const known = ctx.models ?? null;
if (!id) {
const hint =
known && known.length > 0
? known.join(" | ")
: "try deepseek-chat or deepseek-reasoner — run /models to fetch the live list";
return { info: `usage: /model <id> (${hint})` };
}
loop.configure({ model: id });
// Soft validation: if we have the live list and the id isn't in
// it, flag a warning but still switch — DeepSeek may have just
// released something we haven't indexed yet, and refusing would
// be worse than a bad API error on the next call.
if (known && known.length > 0 && !known.includes(id)) {
return {
info: `model → ${id} (⚠ not in the fetched catalog: ${known.join(", ")}. If this is wrong the next call will 400 — run /models to refresh.)`,
};
}
return { info: `model → ${id}` };
};
const models: SlashHandler = (_args, loop, ctx) => {
const list = ctx.models ?? null;
if (list === null) {
ctx.refreshModels?.();
return {
info: "fetching /models from DeepSeek… run /models again in a moment. If it stays empty, your API key may lack permission or the network is blocked.",
};
}
if (list.length === 0) {
return {
info: "DeepSeek /models returned an empty list. Try /models again, or check your account status at api-docs.deepseek.com.",
};
}
const current = loop.model;
const lines = list.map((id) => (id === current ? `▸ ${id} (current)` : ` ${id}`));
return {
info: [
`Available models (DeepSeek /models · ${list.length} total):`,
"",
...lines,
"",
"Switch with: /model <id>",
].join("\n"),
};
};
const harvest: SlashHandler = (args, loop) => {
const arg = (args[0] ?? "").toLowerCase();
const on = arg === "" ? !loop.harvestEnabled : arg === "on" || arg === "true" || arg === "1";
loop.configure({ harvest: on });
if (loop.harvestEnabled) {
return {
info: "harvest → on (Pillar-2 plan-state extraction · +1 cheap flash call per turn · opt-in only; no preset turns it on)",
};
}
return { info: "harvest → off" };
};
const preset: SlashHandler = (args, loop) => {
const name = (args[0] ?? "").toLowerCase();
// Persist the effort along with the preset change so a relaunch
// doesn't revert to the previously-saved /effort value.
const applyAndPersist = (effort: "high" | "max") => {
try {
saveReasoningEffort(effort);
} catch {
/* disk full / perms — runtime change still took effect */
}
};
if (name === "fast" || name === "default") {
loop.configure({
model: "deepseek-v4-flash",
reasoningEffort: "high",
harvest: false,
branch: 1,
});
applyAndPersist("high");
return { info: "preset → fast (v4-flash · effort=high · cheapest)" };
}
if (name === "smart") {
loop.configure({
model: "deepseek-v4-flash",
reasoningEffort: "max",
harvest: false,
branch: 1,
});
applyAndPersist("max");
return { info: "preset → smart (v4-flash · effort=max · default · ~1.5× fast)" };
}
if (name === "max" || name === "best") {
loop.configure({
model: "deepseek-v4-pro",
reasoningEffort: "max",
harvest: false,
branch: 1,
});
applyAndPersist("max");
return {
info: "preset → max (v4-pro · effort=max · ~12× fast · save for hard tasks, or use /pro for a single-turn bump)",
};
}
return { info: "usage: /preset <fast|smart|max>" };
};
const branch: SlashHandler = (args, loop) => {
const raw = (args[0] ?? "").toLowerCase();
if (raw === "" || raw === "off" || raw === "0" || raw === "1") {
loop.configure({ branch: 1 });
return { info: "branch → off" };
}
const n = Number.parseInt(raw, 10);
if (!Number.isFinite(n) || n < 2) {
return { info: "usage: /branch <N> (N>=2, or 'off')" };
}
if (n > 8) {
return { info: "branch budget capped at 8 to prevent runaway cost" };
}
loop.configure({ branch: n });
return {
info: `branch → ${n} (runs ${n} parallel samples per turn · ${n}× per-turn cost · streaming disabled · manual only, no preset enables branching)`,
};
};
const effort: SlashHandler = (args, loop) => {
const raw = (args[0] ?? "").toLowerCase();
if (raw === "") {
return {
info: `reasoning_effort → ${loop.reasoningEffort} (use /effort high for cheaper/faster, /effort max for the agent-class default · persisted across relaunches)`,
};
}
if (raw !== "high" && raw !== "max") {
return { info: "usage: /effort <high|max>" };
}
loop.configure({ reasoningEffort: raw });
// Persist so the next launch starts with this value instead of
// reverting to the constructor default.
try {
saveReasoningEffort(raw);
} catch {
/* disk full / perms — runtime change still took effect */
}
return { info: `reasoning_effort → ${raw} (persisted)` };
};
const pro: SlashHandler = (args, loop, ctx) => {
const arg = (args[0] ?? "").toLowerCase();
if (arg === "off" || arg === "cancel" || arg === "disarm") {
if (!loop.proArmed) {
return { info: "nothing armed — /pro with no args will arm pro for your next turn" };
}
if (ctx.disarmPro) ctx.disarmPro();
else loop.disarmPro();
return { info: "▸ /pro disarmed — next turn falls back to the current preset" };
}
if (arg && arg !== "on" && arg !== "arm") {
return {
info: "usage: /pro arm pro for the next turn (one-shot, auto-disarms after)\n /pro off cancel armed state before the next turn",
};
}
if (ctx.armPro) ctx.armPro();
else loop.armProForNextTurn();
return {
info: `▸ /pro armed — your NEXT message runs on ${ESCALATION_MODEL_ID} regardless of preset. Auto-disarms after one turn. Use /preset max for a persistent switch.`,
};
};
// Kept in sync with loop.ts ESCALATION_MODEL — hard-coding rather than
// importing it because loop.ts already exports enough surface, and this
// string is user-facing (description strings stay verbatim even if the
// internal constant renames).
const ESCALATION_MODEL_ID = "deepseek-v4-pro";
export const handlers: Record<string, SlashHandler> = {
model,
models,
harvest,
preset,
branch,
effort,
pro,
};
+191
View File
@@ -0,0 +1,191 @@
import { DEEPSEEK_CONTEXT_TOKENS, DEFAULT_CONTEXT_TOKENS } from "../../../../telemetry.js";
import { countTokens } from "../../../../tokenizer.js";
import type { SlashHandler } from "../dispatch.js";
import { compactNum, formatToolList } from "../helpers.js";
const think: SlashHandler = (_args, loop) => {
const raw = loop.scratch.reasoning;
if (!raw || !raw.trim()) {
return {
info:
"no reasoning cached. `/think` shows the full R1 thought for the most recent turn — " +
"only `deepseek-reasoner` produces it, and only once the turn completes.",
};
}
return { info: `↳ full thinking (${raw.length} chars):\n\n${raw.trim()}` };
};
const tool: SlashHandler = (args, _loop, ctx) => {
// EventLog truncates tool results at 400 chars for display. When the
// user wants to check what the model actually read (e.g. to verify
// it isn't hallucinating a file's contents), they need the full
// text. `/tool` is the escape hatch.
const history = ctx.toolHistory?.() ?? [];
if (history.length === 0) {
return {
info:
"no tool calls yet in this session. `/tool` lists them once the model has actually " +
"used a tool; `/tool N` dumps the full (untruncated) output of the Nth-most-recent.",
};
}
const raw = (args[0] ?? "").toLowerCase();
if (raw === "" || raw === "list" || raw === "ls") {
return { info: formatToolList(history) };
}
const n = Number.parseInt(raw, 10);
if (!Number.isFinite(n) || n < 1) {
return {
info: "usage: /tool [N] (no arg → list; N=1 → most recent result in full, N=2 → previous, …)",
};
}
if (n > history.length) {
return {
info: `only ${history.length} tool call(s) in history — asked for #${n}. Try /tool with no arg to see the list.`,
};
}
const entry = history[history.length - n];
if (!entry) {
return { info: `could not read tool call #${n}` };
}
return {
info: `↳ tool<${entry.toolName}> #${n} (${entry.text.length} chars):\n\n${entry.text}`,
};
};
const context: SlashHandler = (_args, loop) => {
// Measure each slice of the next request locally so the user can see
// *where* context is being spent — a much more useful number than
// the "last turn's total" the gauge shows. Tokenization is lazy so
// the first /context call carries the data-file load cost (~100ms);
// subsequent calls are pure compute.
const systemTokens = countTokens(loop.prefix.system);
const toolsTokens = countTokens(JSON.stringify(loop.prefix.toolSpecs));
const entries = loop.log.toMessages();
let userTokens = 0;
let assistantTokens = 0;
let toolResultTokens = 0;
let toolCallTokens = 0;
const toolBreakdown: Array<{ name: string; tokens: number; turn: number }> = [];
let logTurn = 0;
for (const e of entries) {
const content = typeof e.content === "string" ? e.content : "";
if (e.role === "user") {
userTokens += countTokens(content);
logTurn += 1;
} else if (e.role === "assistant") {
assistantTokens += countTokens(content);
if (Array.isArray(e.tool_calls) && e.tool_calls.length > 0) {
toolCallTokens += countTokens(JSON.stringify(e.tool_calls));
}
} else if (e.role === "tool") {
const n = countTokens(content);
toolResultTokens += n;
toolBreakdown.push({ name: e.name ?? "?", tokens: n, turn: logTurn });
}
}
const logTokens = userTokens + assistantTokens + toolResultTokens + toolCallTokens;
const total = systemTokens + toolsTokens + logTokens;
const ctxMax = DEEPSEEK_CONTEXT_TOKENS[loop.model] ?? DEFAULT_CONTEXT_TOKENS;
const pct = (n: number) => (total > 0 ? `${Math.round((n / total) * 100)}%`.padStart(4) : " 0%");
const row = (label: string, n: number, note = "") =>
` ${label.padEnd(20)}${compactNum(n).padStart(8)} tokens ${pct(n)}${note ? ` ${note}` : ""}`;
const lines = [
`Next-request estimate: ~${compactNum(total)} tokens of ${compactNum(ctxMax)} (${Math.round(
(total / ctxMax) * 100,
)}% of window)`,
"",
row("system prompt", systemTokens),
row("tool specs", toolsTokens, `(${loop.prefix.toolSpecs.length} tools)`),
row("log (all turns)", logTokens, `(${entries.length} messages)`),
` user ${compactNum(userTokens).padStart(8)} tokens`,
` assistant ${compactNum(assistantTokens).padStart(8)} tokens`,
` tool-call args ${compactNum(toolCallTokens).padStart(8)} tokens`,
` tool results ${compactNum(toolResultTokens).padStart(8)} tokens`,
];
// Top 5 heaviest tool results — usually where unexpected bloat
// lives (a big read_file, an unfiltered search_content).
if (toolBreakdown.length > 0) {
const top = [...toolBreakdown].sort((a, b) => b.tokens - a.tokens).slice(0, 5);
lines.push("");
lines.push(`Top tool results by cost (of ${toolBreakdown.length} total):`);
for (const t of top) {
lines.push(
` turn ${String(t.turn).padStart(3)} ${t.name.padEnd(22)} ${compactNum(t.tokens).padStart(8)} tokens`,
);
}
}
lines.push("");
lines.push(
"Count is a local estimate (DeepSeek V3 tokenizer, pure-TS port); server prompt_tokens may add ~3-6% for chat-template role markers.",
);
return { info: lines.join("\n") };
};
const status: SlashHandler = (_args, loop, ctx) => {
const branchBudget = loop.branchOptions.budget ?? 1;
const ctxMax = DEEPSEEK_CONTEXT_TOKENS[loop.model] ?? DEFAULT_CONTEXT_TOKENS;
const lastPromptTokens = loop.stats.summary().lastPromptTokens;
const ctxPct = ctxMax > 0 ? Math.round((lastPromptTokens / ctxMax) * 100) : 0;
const ctxLine =
lastPromptTokens > 0
? ` ctx ${compactNum(lastPromptTokens)}/${compactNum(ctxMax)} (${ctxPct}%)`
: " ctx no turns yet";
const pending = ctx.pendingEditCount ?? 0;
const sessionLine = loop.sessionName
? ` session "${loop.sessionName}" · ${loop.log.length} messages in log (resumed ${loop.resumedMessageCount})`
: " session (ephemeral — no persistence)";
const mcpCount = ctx.mcpSpecs?.length ?? 0;
const toolCount = loop.prefix.toolSpecs.length;
const mcpLine = ` mcp ${mcpCount} server(s), ${toolCount} tool(s) in registry`;
const pendingLine =
pending > 0 ? ` edits ${pending} pending (/apply to commit, /discard to drop)` : "";
const planLine = ctx.planMode ? " plan ON — writes gated (submit_plan + approval)" : "";
const modeLine =
ctx.editMode === "auto"
? " mode AUTO — edits apply immediately (u to undo within 5s · Shift+Tab to flip)"
: ctx.editMode === "review"
? " mode review — edits queue for /apply or y (Shift+Tab to flip)"
: "";
const lines = [
` model ${loop.model}`,
` flags harvest=${loop.harvestEnabled ? "on" : "off"} · branch=${branchBudget > 1 ? branchBudget : "off"} · stream=${loop.stream ? "on" : "off"} · effort=${loop.reasoningEffort}`,
ctxLine,
mcpLine,
sessionLine,
];
if (pendingLine) lines.push(pendingLine);
if (planLine) lines.push(planLine);
if (modeLine) lines.push(modeLine);
return { info: lines.join("\n") };
};
const compact: SlashHandler = (args, loop) => {
// Manual companion to the automatic 60%/80% auto-compact. Re-applies
// token-aware truncation with a tighter cap (default 4000 tokens per
// tool result) and rewrites the session file so the shrink persists.
// Useful when the ctx gauge in StatsPanel goes yellow/red mid-session
// and the user wants to keep chatting without /forget'ing everything.
const tight = Number.parseInt(args[0] ?? "", 10);
const cap = Number.isFinite(tight) && tight >= 100 ? tight : 4000;
const { healedCount, tokensSaved, charsSaved } = loop.compact(cap);
if (healedCount === 0) {
return {
info: `▸ nothing to compact — no tool result or tool-call args in history exceed ${cap.toLocaleString()} tokens.`,
};
}
return {
info: `▸ compacted ${healedCount} payload(s) to ${cap.toLocaleString()} tokens each (tool results + tool-call args), saved ${tokensSaved.toLocaleString()} tokens (${charsSaved.toLocaleString()} chars). Session file rewritten.`,
};
};
export const handlers: Record<string, SlashHandler> = {
think,
reasoning: think,
tool,
context,
status,
compact,
};
+41
View File
@@ -0,0 +1,41 @@
import { deleteSession, listSessions } from "../../../../session.js";
import type { SlashHandler } from "../dispatch.js";
const sessions: SlashHandler = (_args, loop) => {
const items = listSessions();
if (items.length === 0) {
return {
info: "no saved sessions yet — chat normally and your messages will be saved automatically",
};
}
const lines = ["Saved sessions:"];
for (const s of items) {
const sizeKb = (s.size / 1024).toFixed(1);
const when = s.mtime.toISOString().replace("T", " ").slice(0, 16);
const marker = s.name === loop.sessionName ? "▸" : " ";
lines.push(
` ${marker} ${s.name.padEnd(22)} ${String(s.messageCount).padStart(5)} msgs ${sizeKb.padStart(7)} KB ${when}`,
);
}
lines.push("");
lines.push("Resume with: reasonix chat --session <name>");
return { info: lines.join("\n") };
};
const forget: SlashHandler = (_args, loop) => {
if (!loop.sessionName) {
return { info: "not in a session — nothing to forget" };
}
const name = loop.sessionName;
const ok = deleteSession(name);
return {
info: ok
? `▸ deleted session "${name}" — current screen still shows the conversation, but next launch starts fresh`
: `could not delete session "${name}" (already gone?)`,
};
};
export const handlers: Record<string, SlashHandler> = {
sessions,
forget,
};
+94
View File
@@ -0,0 +1,94 @@
import { SkillStore } from "../../../../skills.js";
import type { SlashHandler } from "../dispatch.js";
/**
* `/skill` family. Bare `/skill` (or `/skill list`) prints the
* discovered skills from `<projectRoot>/.reasonix/skills` (code mode
* only) + `~/.reasonix/skills`. `/skill show <name>` dumps one body
* inline for reading. `/skill <name> [args...]` injects the skill body
* as a user turn via `resubmit` — the same mechanism `/apply-plan`
* uses — so the next model turn runs with the skill's instructions
* fresh in the log.
*
* Project scope is only populated when the session has a `codeRoot`
* (set by `reasonix code`). In plain chat mode the store reads the
* global scope only, matching how user-memory behaves.
*/
const skill: SlashHandler = (args, _loop, ctx) => {
const store = new SkillStore({ projectRoot: ctx.codeRoot });
const sub = (args[0] ?? "").toLowerCase();
if (sub === "" || sub === "list" || sub === "ls") {
const skills = store.list();
if (skills.length === 0) {
const lines = ["no skills found. Reasonix reads skills from:"];
if (store.hasProjectScope()) {
lines.push(
" · <project>/.reasonix/skills/<name>/SKILL.md (or <name>.md) — project scope",
);
}
lines.push(" · ~/.reasonix/skills/<name>/SKILL.md (or <name>.md) — global scope");
if (!store.hasProjectScope()) {
lines.push(" (project scope is only active in `reasonix code`)");
}
lines.push(
"",
"Each file's frontmatter needs at least `name` and `description`.",
"Invoke a skill with `/skill <name> [args]` or by asking the model to call `run_skill`.",
);
return { info: lines.join("\n") };
}
const lines = [`User skills (${skills.length}):`];
for (const s of skills) {
const scope = `(${s.scope})`.padEnd(11);
const name = s.name.padEnd(24);
const desc = s.description.length > 70 ? `${s.description.slice(0, 69)}…` : s.description;
lines.push(` ${scope} ${name} ${desc}`);
}
lines.push("");
lines.push("View body: /skill show <name> Run: /skill <name> [args]");
return { info: lines.join("\n") };
}
if (sub === "show" || sub === "cat") {
const target = args[1];
if (!target) return { info: "usage: /skill show <name>" };
const found = store.read(target);
if (!found) return { info: `no skill found: ${target}` };
return {
info: [
`▸ ${found.name} (${found.scope})`,
found.description ? ` ${found.description}` : "",
` ${found.path}`,
"",
found.body,
]
.filter((l) => l !== "")
.join("\n"),
};
}
// Bare `/skill <name> [args...]` — inject the body as a user turn.
// The first arg is the skill name; remaining args are forwarded
// verbatim as the skill's "Arguments:" line.
const name = args[0] ?? "";
const found = store.read(name);
if (!found) {
return {
info: `no skill found: ${name} (try /skill list)`,
};
}
const extra = args.slice(1).join(" ").trim();
const header = `# Skill: ${found.name}${found.description ? `\n> ${found.description}` : ""}`;
const argsLine = extra ? `\n\nArguments: ${extra}` : "";
const payload = `${header}\n\n${found.body}${argsLine}`;
return {
info: `▸ running skill: ${found.name}${extra ? ` — ${extra}` : ""}`,
resubmit: payload,
};
};
export const handlers: Record<string, SlashHandler> = {
skill,
skills: skill,
};
+145
View File
@@ -0,0 +1,145 @@
import { spawnSync } from "node:child_process";
import type { MemoryScope, MemoryStore } from "../../../user-memory.js";
import type { SlashResult } from "./types.js";
/**
* Parse a `/memory show|forget` argument. Accepts bare `<name>` or
* `<scope>/<name>`. For bare names, tries project scope first (more
* specific, usually what the user means) then falls back to global.
*/
export function resolveMemoryTarget(
store: MemoryStore,
raw: string,
): { scope: MemoryScope; name: string } | null {
const slash = raw.indexOf("/");
if (slash > 0) {
const scopeRaw = raw.slice(0, slash).toLowerCase();
const name = raw.slice(slash + 1);
if (scopeRaw !== "global" && scopeRaw !== "project") return null;
const scope = scopeRaw as MemoryScope;
if (scope === "project" && !store.hasProjectScope()) return null;
return { scope, name };
}
for (const scope of ["project", "global"] as MemoryScope[]) {
if (scope === "project" && !store.hasProjectScope()) continue;
try {
store.read(scope, raw);
return { scope, name: raw };
} catch {
/* next scope */
}
}
return null;
}
/**
* Render a section (resources / prompts) of an MCP inspection into a
* compact "name count items" form, collapsing when unsupported.
* Names-only — descriptions and full metadata live in
* `reasonix mcp inspect`, which is purpose-built for the deep view.
*/
export function appendSection(
lines: string[],
label: string,
section:
| { supported: true; items: Array<{ name: string }> }
| { supported: false; reason: string }
| undefined,
): void {
if (!section || !section.supported) {
lines.push(
` ${label.trim()} ${section?.supported === false ? "(not supported)" : "(none)"}`,
);
return;
}
const names = section.items.map((i) => i.name);
if (names.length === 0) {
lines.push(` ${label.trim()} (none)`);
return;
}
const head = names.slice(0, 5).join(", ");
const more = names.length > 5 ? ` +${names.length - 5} more` : "";
lines.push(` ${label.trim()} ${names.length} [${head}${more}]`);
}
export function formatToolList(history: Array<{ toolName: string; text: string }>): string {
const total = history.length;
const header = `Tool calls in this session (${total}, most recent first):`;
// Show the 10 most recent. Older ones are rarely what the user
// wants — and the help footer tells them how to reach any entry
// by index if they do.
const shown = Math.min(total, 10);
const lines: string[] = [header];
for (let i = 0; i < shown; i++) {
const entry = history[total - 1 - i];
if (!entry) continue;
const idx = i + 1; // 1-based from most recent
const flat = entry.text.replace(/\s+/g, " ").trim();
const preview = flat.length > 80 ? `${flat.slice(0, 80)}…` : flat;
const name = entry.toolName.length > 24 ? `${entry.toolName.slice(0, 23)}…` : entry.toolName;
lines.push(
` #${String(idx).padStart(2)} ${name.padEnd(24)} ${String(entry.text.length).padStart(6)} chars ${preview}`,
);
}
if (total > shown) {
lines.push(` … (${total - shown} earlier, reach with /tool N)`);
}
lines.push("");
lines.push("View full output: /tool N (N=1 → most recent)");
return lines.join("\n");
}
/**
* Binary-K token formatter: 1234 → "1.2K", 131072 → "128K". Matches
* DeepSeek's doc ("128K context"). Every call site here is rendering
* token counts — if a future caller wants decimal-K for dollars or
* similar, add a separate formatter rather than reusing this one.
*/
export function compactNum(n: number): string {
if (n < 1024) return String(n);
const k = n / 1024;
return k >= 100 ? `${Math.round(k)}K` : `${k.toFixed(1)}K`;
}
export function stripOuterQuotes(s: string): string {
if (s.length >= 2 && s.startsWith('"') && s.endsWith('"')) {
return s.slice(1, -1);
}
return s;
}
/**
* Run `git add -A` then `git commit -m <message>` in `rootDir`. Returns
* a SlashResult with a human-scannable info line. We surface stderr on
* failure so the user sees exactly what git complained about (bad
* config, pre-commit hook rejection, nothing staged, etc.).
*/
export function runGitCommit(rootDir: string, message: string): SlashResult {
const add = spawnSync("git", ["add", "-A"], { cwd: rootDir, encoding: "utf8" });
if (add.error || add.status !== 0) {
return { info: `git add failed (${add.status ?? "?"}):\n${gitTail(add)}` };
}
const commit = spawnSync("git", ["commit", "-m", message], {
cwd: rootDir,
encoding: "utf8",
});
if (commit.error || commit.status !== 0) {
return { info: `git commit failed (${commit.status ?? "?"}):\n${gitTail(commit)}` };
}
const firstLine = (commit.stdout || "").split(/\r?\n/)[0] ?? "";
return { info: `▸ committed: ${message}${firstLine ? `\n ${firstLine}` : ""}` };
}
/**
* Safely extract whatever diagnostic text is available from a spawnSync
* result — on Windows or when cwd doesn't exist, `stderr`/`stdout` can
* be `undefined` and the caller has only `error.message` to go on.
*/
export function gitTail(res: ReturnType<typeof spawnSync>): string {
const stderr = (res.stderr as string | undefined) ?? "";
const stdout = (res.stdout as string | undefined) ?? "";
const body = stderr.trim() || stdout.trim();
if (body) return body;
if (res.error) return (res.error as Error).message;
return "(no output from git)";
}
+274
View File
@@ -0,0 +1,274 @@
import type { EditMode } from "../../../config.js";
import type { McpClient } from "../../../mcp/client.js";
import type { InspectionReport } from "../../../mcp/inspect.js";
import type { JobRegistry } from "../../../tools/jobs.js";
export interface SlashResult {
/** Text to display back to the user as a system/info line. */
info?: string;
/** Exit the app. */
exit?: boolean;
/** Clear the visible history. */
clear?: boolean;
/** Unknown command — display usage hint. */
unknown?: boolean;
/**
* Re-submit this text as a user message after displaying `info`.
* Used by `/retry` — the slash command truncates the log, then
* asks the TUI to push the original text back through the normal
* submit flow so a fresh turn runs.
*/
resubmit?: string;
}
/**
* Extra runtime context a slash handler may care about but that isn't
* already on the loop. Kept as an optional object so tests that only
* need loop-scoped commands can skip it, and callers only populate the
* slots that apply to their session.
*/
export interface SlashContext {
/**
* The exact `--mcp` / config-derived spec strings that were bridged
* into this session (one entry per server). Used by `/mcp`. Empty or
* omitted → no MCP servers attached.
*/
mcpSpecs?: string[];
/**
* Callback for `/undo` — provided by the TUI when it's running in
* code mode. Returns a human-readable report of what was restored.
* Absent outside code mode → `/undo` replies "not available here".
* Accepts slash args: `[id]`, `[id, path]`.
*/
codeUndo?: (args: readonly string[]) => string;
/**
* Callback for `/apply` — commits pending edit blocks to disk. Returns
* a report of what landed. Absent → `/apply` replies "nothing pending"
* or "not available outside code mode".
*/
codeApply?: () => string;
/**
* Callback for `/discard` — drops the pending edit blocks without
* touching disk.
*/
codeDiscard?: () => string;
/**
* Callback for `/history` — returns a human-readable list of every
* edit batch this session, newest last. Includes entry ids (for
* `/show`) and undone status.
*/
codeHistory?: () => string;
/**
* Callback for `/show [id] [path]` — with no args, shows a per-file
* summary of the newest non-undone entry. With id only, the entry's
* per-file summary. With id + path, the full diff of that single
* file in that entry.
*/
codeShowEdit?: (args: readonly string[]) => string;
/**
* Root directory passed by `reasonix code`. Enables `/commit`, which
* runs `git add -A && git commit` in this directory. Missing → `/commit`
* replies "only available in code mode".
*/
codeRoot?: string;
/**
* How many edit blocks are currently pending `/apply` or `/discard`.
* Surfaced by `/status`. TUI populates it live from its pending ref;
* omitted → treat as 0 (chat-only session).
*/
pendingEditCount?: number;
/**
* Callback returning every tool result seen this session in
* chronological order (oldest first). Powers `/tool [N]` for
* inspecting the full untruncated output that `EventLog` clips at
* 400 chars for display. Absent → `/tool` replies "not available".
*/
toolHistory?: () => Array<{ toolName: string; text: string }>;
/**
* Pre-captured inspection reports for each connected MCP server.
* Populated once at chat startup (chat.tsx) so `/mcp` can render
* tools + resources + prompts synchronously without needing async
* handler support.
*/
mcpServers?: McpServerSummary[];
/**
* Directory `/memory` should resolve `REASONIX.md` from. In code
* mode this is the rootDir the filesystem tools are pinned to; in
* plain chat this is `process.cwd()` at launch time. Absent → the
* TUI is running in some non-cwd context (tests) and `/memory`
* replies "root unknown" instead of silently reading a different dir.
*/
memoryRoot?: string;
/**
* Current plan-mode state, surfaced in `/status` and toggled by
* `/plan`. Present iff the session is a `reasonix code` run — chat
* mode doesn't have plan mode.
*/
planMode?: boolean;
/**
* Current edit-gate mode (`review` or `auto`). Surfaced in `/status`,
* toggled by `/mode`, also flipped by the Shift+Tab keybind in the
* TUI. Absent → not in `reasonix code`.
*/
editMode?: EditMode;
/**
* Set the edit-gate mode. Callback rather than raw state so App can
* also persist the choice to config and echo the change in historical.
*/
setEditMode?: (mode: EditMode) => void;
/**
* Background-process registry backing /jobs / /kill / /logs. Present
* iff the session is a `reasonix code` run. Slash handlers expect
* synchronous info strings, but stop_job is async — we return a
* "stopping, watch /jobs" info and let the registry do its thing.
*/
jobs?: JobRegistry;
/**
* Async-late append to the historical log. /kill uses this to
* surface "job N stopped" the moment stop() actually resolves,
* rather than leaving the user to poll /jobs themselves.
*/
postInfo?: (text: string) => void;
/**
* Callback the `/plan` slash uses to flip plan mode on/off. Also
* mirrors the state to the underlying ToolRegistry so dispatch
* enforcement follows. Absent → `/plan` replies "only available in
* code mode".
*/
setPlanMode?: (on: boolean) => void;
/**
* Callback that clears a pending-plan picker state. Called by
* `/apply-plan` so that when the user force-approves, the picker
* dismisses without also firing its own approval synthetic (the
* slash returns its own `resubmit` instead). Safe to call with no
* pending plan.
*/
clearPendingPlan?: () => void;
/**
* Re-load `~/.reasonix/settings.json` + `<project>/.reasonix/settings.json`
* and update both the App's hook state and the loop's mutable hook
* list. Returns the new hook count so the slash can echo a sane
* confirmation. Absent → `/hooks reload` replies "not available".
*/
reloadHooks?: () => number;
/**
* Latest published version if App's background registry check
* has completed, `null` otherwise (still in flight OR offline).
* Drives `/update` — the slash shows whatever the async check
* already resolved, so the command is fully synchronous.
*/
latestVersion?: string | null;
/**
* Fire-and-forget: kick off a fresh registry fetch. `/update`
* calls this whenever it encounters `latestVersion === null`
* so the user can rerun the slash a few seconds later and see
* a concrete answer. Absent → the slash just reports "pending"
* with no retry path.
*/
refreshLatestVersion?: () => void;
/**
* Model catalog fetched from DeepSeek's `/models` endpoint at App
* mount. `null` → still in flight or the call failed (auth / offline);
* `[]` → the API answered with zero entries. `/models` uses this to
* render the list, and `/model <id>` uses it for soft validation
* (warn-only — we still switch even on unknown ids since the list
* can lag a newly-released model).
*/
models?: string[] | null;
/**
* Fire-and-forget refresh for the models list. Lets `/models` retry
* after a flaky first fetch without needing async slash support.
*/
refreshModels?: () => void;
/**
* Arm pro for the next turn. Called by `/pro`. The TUI wires this
* to both `loop.armProForNextTurn()` and its React mirror state so
* the StatsPanel badge flips immediately. Absent → the handler
* calls `loop.armProForNextTurn()` directly and the badge updates
* on the next render tick (slightly laggy but still correct).
*/
armPro?: () => void;
/** Cancel a pending /pro arming. Mirrors `armPro` semantics. */
disarmPro?: () => void;
}
export interface McpServerSummary {
/** Short label shown in the `/mcp` output (server namespace or "anon"). */
label: string;
/** Original --mcp spec string. */
spec: string;
/** Count of tools bridged into the Reasonix registry from this server. */
toolCount: number;
/** Full inspection snapshot — used for the resources + prompts sections. */
report: InspectionReport;
/**
* Live MCP client, kept so `/resource` and `/prompt` can call
* `readResource` / `getPrompt` against this server. Omitted by
* callers that only build the summary for display; those slashes
* fall back to "not available" when the client is missing.
*/
client?: McpClient;
}
/**
* Slash command registry. Drives `/help`, the on-type suggestion
* popup (`SlashSuggestions`), and auto-complete. Kept as data rather
* than derived from the `handleSlash` switch so summaries can be
* user-facing rather than code comments.
*
* `contextual` gates commands that only make sense in certain modes:
* - `"code"` — only show when the TUI is running `reasonix code`
* - absent → always shown
*/
export interface SlashCommandSpec {
cmd: string;
summary: string;
contextual?: "code";
/** If the command takes args, hint text shown after the name. */
argsHint?: string;
/**
* How the first argument position should autocomplete. Shapes the
* picker that appears below the prompt once the user types `/<cmd>`
* + space:
* - `"models"` → DeepSeek model-id list fetched at startup.
* - `"mcp-resources"` → live URIs aggregated across connected MCP servers.
* - `"mcp-prompts"` → live prompt names aggregated across MCP servers.
* - `string[]` → small enum of literal values (e.g. `["on", "off"]`).
* - omitted → no picker; a persistent usage hint shows the
* argsHint + summary so the user knows what to type.
*
* File-path completion is deliberately NOT offered here. Users who
* want to reference a file in a prompt use `@path/to/file` (0.5.5);
* the `@` picker already surfaces files with mtime + recently-used
* ranking. Adding a second file-picker surface for slash commands
* would split the UX without adding leverage.
*/
argCompleter?: "models" | "mcp-resources" | "mcp-prompts" | readonly string[];
}
/**
* Shape describing what the prompt buffer is asking for AFTER the
* user has committed to a slash command (`/<cmd>`) and started
* typing its first argument. Consumed by the TUI to drive an
* argument-level picker.
*/
export interface SlashArgContext {
/** The command spec (looked up by name from SLASH_COMMANDS). */
spec: SlashCommandSpec;
/** The partial first-argument text, possibly empty. */
partial: string;
/**
* Buffer offset where `partial` begins. Used by the TUI to splice
* a picked completion back in at the right position.
*/
partialOffset: number;
/**
* Classification of what the caller should show:
* - `"picker"` → an interactive picker (file / enum / models). The
* caller uses `spec.argCompleter` to pick the data source and
* filters against `partial`.
* - `"hint"` → past the completable position (additional args or
* no completer declared). Caller shows a dim usage hint only.
*/
kind: "picker" | "hint";
}
+55
View File
@@ -0,0 +1,55 @@
import React, { type ReactNode, createContext, useContext, useEffect, useState } from "react";
/**
* Global heartbeat for every animated component (braille spinners,
* elapsed-seconds counters, cursor blink). A single setInterval feeds
* all of them instead of each component owning one. Consolidating the
* 5-6 independent timers that used to exist in App.tsx + EventLog.tsx +
* PromptInput.tsx into one source dramatically cuts the number of
* React re-renders per second on heavy turns and stops Ink from
* patching the terminal 30+ times/sec — the main amplifier of redraw
* artifacts on winpty/MINTTY-class Windows terminals.
*
* Resolution: `TICK_MS` (default 120). Components that want 500ms or
* 1s cadence just modulo the tick counter.
*/
export const TICK_MS = 120;
const TickContext = createContext(0);
export interface TickerProviderProps {
children: ReactNode;
/**
* When true, the provider skips the setInterval entirely — tick stays at
* 0, all consumers render once and never re-render from the timer. Used
* by PLAIN_UI mode so the cursor and any surviving spinners don't drive
* repaints on fragile Windows terminals.
*/
disabled?: boolean;
}
export function TickerProvider({ children, disabled }: TickerProviderProps) {
const [tick, setTick] = useState(0);
useEffect(() => {
if (disabled) return;
const id = setInterval(() => setTick((t) => t + 1), TICK_MS);
return () => clearInterval(id);
}, [disabled]);
return <TickContext.Provider value={tick}>{children}</TickContext.Provider>;
}
/** Current global tick. Re-renders the calling component every `TICK_MS`. */
export function useTick(): number {
return useContext(TickContext);
}
/**
* Seconds elapsed since the calling component mounted. Derived from
* the shared tick + a fresh Date.now() read, so no dedicated timer
* is needed.
*/
export function useElapsedSeconds(): number {
const [start] = useState(() => Date.now());
useTick(); // subscribe to the tick so we re-render
return Math.floor((Date.now() - start) / 1000);
}
+218
View File
@@ -0,0 +1,218 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
type FileWithStats,
detectAtPicker,
listFilesWithStatsSync,
rankPickerCandidates,
} from "../../at-mentions.js";
import {
type McpServerSummary,
type SlashArgContext,
type SlashCommandSpec,
detectSlashArgContext,
suggestSlashCommands,
} from "./slash.js";
export interface UseCompletionPickersParams {
input: string;
setInput: (v: string) => void;
codeMode: { rootDir: string } | undefined;
models: string[] | null;
mcpServers: McpServerSummary[] | undefined;
}
export interface UseCompletionPickersResult {
// ── slash-name picker ──
slashMatches: SlashCommandSpec[] | null;
slashSelected: number;
setSlashSelected: React.Dispatch<React.SetStateAction<number>>;
// ── @-mention picker ──
atPicker: ReturnType<typeof detectAtPicker>;
atMatches: readonly string[] | null;
atSelected: number;
setAtSelected: React.Dispatch<React.SetStateAction<number>>;
pickAtMention: (chosenPath: string) => void;
recordRecentFile: (path: string) => void;
// ── slash-arg picker ──
slashArgContext: SlashArgContext | null;
slashArgMatches: readonly string[] | null;
slashArgSelected: number;
setSlashArgSelected: React.Dispatch<React.SetStateAction<number>>;
pickSlashArg: (chosen: string) => void;
}
/**
* The three mutually-exclusive input-prefix pickers share enough
* structure (matches list + highlighted index + reset-on-shrink effect
* + commit-back-into-buffer callback) that they live together here.
* Priority in the parent useInput handler:
* atMatches > slashArgMatches > slashMatches > prompt history
* detection already disambiguates by construction — the slash-name
* picker fires only when the buffer has no space; the slash-arg picker
* only after a space; the @-picker only outside slash mode.
*/
export function useCompletionPickers({
input,
setInput,
codeMode,
models,
mcpServers,
}: UseCompletionPickersParams): UseCompletionPickersResult {
// ── slash-name picker ──
const [slashSelected, setSlashSelected] = useState(0);
const slashMatches = useMemo(() => {
if (!input.startsWith("/") || input.includes(" ")) return null;
return suggestSlashCommands(input.slice(1), !!codeMode);
}, [input, codeMode]);
useEffect(() => {
setSlashSelected((prev) => {
if (!slashMatches || slashMatches.length === 0) return 0;
if (prev >= slashMatches.length) return slashMatches.length - 1;
return prev;
});
}, [slashMatches]);
// ── @-mention picker ──
const [atSelected, setAtSelected] = useState(0);
// Walk the code root ONCE on mount, collecting mtime alongside path
// so the picker can surface recently-edited files first. Files
// created mid-session via tool edits won't appear until restart —
// rare, and the user can always type the full path.
const atFiles = useMemo<readonly FileWithStats[]>(() => {
if (!codeMode?.rootDir) return [];
try {
return listFilesWithStatsSync(codeMode.rootDir, { maxResults: 500 });
} catch {
return [];
}
}, [codeMode?.rootDir]);
// LRU of files touched by recent tool calls. Seeds the picker with
// "stuff I just looked at" at the top, so a user typing `@` in the
// same file they were just discussing gets it instantly.
const recentFilesRef = useRef<string[]>([]);
const recordRecentFile = useCallback((p: string) => {
const list = recentFilesRef.current;
const i = list.indexOf(p);
if (i >= 0) list.splice(i, 1);
list.unshift(p);
if (list.length > 20) list.length = 20;
}, []);
const atPicker = useMemo(() => {
if (!codeMode?.rootDir) return null;
// Slash prefix wins — avoids the picker confusingly surfacing on
// `/@wat`-style edge inputs.
if (slashMatches !== null) return null;
return detectAtPicker(input);
}, [codeMode?.rootDir, input, slashMatches]);
const atMatches = useMemo<readonly string[] | null>(() => {
if (!atPicker) return null;
return rankPickerCandidates(atFiles, atPicker.query, {
limit: 40,
recentlyUsed: recentFilesRef.current,
});
}, [atPicker, atFiles]);
useEffect(() => {
setAtSelected((prev) => {
if (!atMatches || atMatches.length === 0) return 0;
if (prev >= atMatches.length) return atMatches.length - 1;
return prev;
});
}, [atMatches]);
const pickAtMention = useCallback(
(chosenPath: string) => {
if (!atPicker) return;
const before = input.slice(0, atPicker.atOffset);
setInput(`${before}@${chosenPath} `);
},
[atPicker, input, setInput],
);
// ── slash-arg picker ──
const [slashArgSelected, setSlashArgSelected] = useState(0);
const slashArgContext = useMemo<SlashArgContext | null>(() => {
if (!input.startsWith("/")) return null;
if (slashMatches !== null) return null;
return detectSlashArgContext(input, !!codeMode);
}, [input, slashMatches, codeMode]);
const slashArgMatches = useMemo<readonly string[] | null>(() => {
if (!slashArgContext || slashArgContext.kind !== "picker") return null;
const completer = slashArgContext.spec.argCompleter;
const partial = slashArgContext.partial;
const needle = partial.toLowerCase();
// Once the partial is an EXACT match for a valid completion, hide
// the picker so Enter submits the command instead of re-picking
// the same value in an infinite loop. Case-insensitive — users
// may type `/preset FAST` and still mean the same thing.
if (Array.isArray(completer)) {
if (partial && completer.some((v) => v.toLowerCase() === needle)) return null;
if (!partial) return completer.slice();
return completer.filter((v) => v.toLowerCase().startsWith(needle));
}
if (completer === "models") {
const all = models ?? [];
if (partial && all.some((m) => m.toLowerCase() === needle)) return null;
if (!partial) return all.slice(0, 40);
return all.filter((m) => m.toLowerCase().includes(needle)).slice(0, 40);
}
if (completer === "mcp-resources") {
// Aggregate URIs across every server's cached inspection.
const uris: string[] = [];
const servers = mcpServers ?? [];
for (const s of servers) {
if (!s.report.resources.supported) continue;
for (const r of s.report.resources.items) uris.push(r.uri);
}
if (partial && uris.some((u) => u.toLowerCase() === needle)) return null;
if (!partial) return uris.slice(0, 40);
return uris.filter((u) => u.toLowerCase().includes(needle)).slice(0, 40);
}
if (completer === "mcp-prompts") {
const names: string[] = [];
const servers = mcpServers ?? [];
for (const s of servers) {
if (!s.report.prompts.supported) continue;
for (const p of s.report.prompts.items) names.push(p.name);
}
if (partial && names.some((n) => n.toLowerCase() === needle)) return null;
if (!partial) return names.slice(0, 40);
return names.filter((n) => n.toLowerCase().includes(needle)).slice(0, 40);
}
return null;
}, [slashArgContext, models, mcpServers]);
useEffect(() => {
setSlashArgSelected((prev) => {
if (!slashArgMatches || slashArgMatches.length === 0) return 0;
if (prev >= slashArgMatches.length) return slashArgMatches.length - 1;
return prev;
});
}, [slashArgMatches]);
const pickSlashArg = useCallback(
(chosen: string) => {
if (!slashArgContext) return;
const before = input.slice(0, slashArgContext.partialOffset);
// No trailing space — enum picks take no further args, so the
// user presses Enter once more to run the command.
setInput(`${before}${chosen}`);
},
[slashArgContext, input, setInput],
);
return {
slashMatches,
slashSelected,
setSlashSelected,
atPicker,
atMatches,
atSelected,
setAtSelected,
pickAtMention,
recordRecentFile,
slashArgContext,
slashArgMatches,
slashArgSelected,
setSlashArgSelected,
pickSlashArg,
};
}
+309
View File
@@ -0,0 +1,309 @@
import { useCallback, useRef, useState } from "react";
import { formatAllBlockDiffs } from "../../code/diff-preview.js";
import {
type ApplyResult,
type EditBlock,
type EditSnapshot,
restoreSnapshots,
} from "../../code/edit-blocks.js";
import {
type EditHistoryEntry,
entryStatus,
formatUndoRows,
isEntryFullyUndone,
} from "./edit-history.js";
export interface UndoBannerState {
results: ApplyResult[];
expiresAt: number;
}
export interface UseEditHistoryResult {
/** Post-auto-apply banner state — rendered at the bottom for 5s. */
undoBanner: UndoBannerState | null;
/**
* Append a batch of successfully-applied edits into the session's
* edit history. If the current turn already has an open entry,
* append into it (first-wins-per-path so `/undo` restores the
* pre-turn state, not an intermediate half-edit). Otherwise open a
* new entry.
*/
recordEdit: (
source: string,
blocks: readonly EditBlock[],
results: readonly ApplyResult[],
snaps: readonly EditSnapshot[],
) => void;
/**
* Show the post-auto-apply undo banner for 5 seconds. Overwrites any
* prior banner and replaces the auto-dismiss timer so multiple
* edits inside a single turn don't prematurely expire the window.
*/
armUndoBanner: (results: ApplyResult[]) => void;
/**
* `/undo` — revert applied edits.
* `/undo` → newest non-fully-undone entry, all its
* remaining (non-undone) files.
* `/undo <id>` → that specific entry's remaining files.
* `/undo <id> <path>` → just that one file in that entry.
* Works as long as the session is alive; no 5-second banner limit.
*/
codeUndo: (args?: readonly string[]) => string;
/**
* `/history` — list every edit batch this session. Each entry's id
* is the token for `/show <id>` and the target of per-batch undo.
*/
codeHistory: () => string;
/**
* `/show` — inspect a stored edit batch.
* `/show` → newest non-fully-undone entry, per-file summary.
* `/show <id>` → that entry's per-file summary.
* `/show <id> <path>` → full diff of one file in that entry.
*/
codeShowEdit: (args?: readonly string[]) => string;
/**
* Seal the in-progress entry so the next edit opens a fresh one.
* Called at handleSubmit start — prior turns stay intact for
* `/history` and `/undo` to walk through independently.
*/
sealCurrentEntry: () => void;
/**
* True when there's at least one history entry that isn't fully
* undone yet. Used by the `u` keybind and the bottom ModeStatusBar.
* Reads the ref fresh — callers must re-read each time.
*/
hasUndoable: () => boolean;
}
/**
* Session-scoped edit history and undo machinery for `reasonix code`.
* Keeps the history ref + snapshot bookkeeping out of App.tsx so the
* parent only sees a small API: append, banner, three slash handlers,
* a turn sealer, and an undoable probe.
*
* `codeMode` is optional because the hook is always mounted but its
* handlers turn into no-ops when code mode isn't active.
*/
export function useEditHistory(codeMode: { rootDir: string } | undefined): UseEditHistoryResult {
const editHistory = useRef<EditHistoryEntry[]>([]);
const nextHistoryId = useRef(1);
const currentTurnEntry = useRef<EditHistoryEntry | null>(null);
const [undoBanner, setUndoBanner] = useState<UndoBannerState | null>(null);
const undoTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const recordEdit = useCallback<UseEditHistoryResult["recordEdit"]>(
(source, blocks, results, snaps) => {
if (snaps.length === 0) return;
let entry = currentTurnEntry.current;
if (!entry) {
entry = {
id: nextHistoryId.current++,
at: Date.now(),
source,
blocks: [],
results: [],
snapshots: [],
undoneFiles: new Set<string>(),
};
currentTurnEntry.current = entry;
editHistory.current.push(entry);
}
entry.blocks.push(...blocks);
entry.results.push(...results);
const seen = new Set(entry.snapshots.map((s) => s.path));
for (const s of snaps) {
if (!seen.has(s.path)) entry.snapshots.push(s);
}
},
[],
);
const armUndoBanner = useCallback<UseEditHistoryResult["armUndoBanner"]>((results) => {
setUndoBanner({ results, expiresAt: Date.now() + 5000 });
if (undoTimeoutRef.current) clearTimeout(undoTimeoutRef.current);
undoTimeoutRef.current = setTimeout(() => {
setUndoBanner(null);
undoTimeoutRef.current = null;
}, 5000);
}, []);
const codeUndo = useCallback<UseEditHistoryResult["codeUndo"]>(
(args = []) => {
if (!codeMode) return "not in code mode";
const root = codeMode.rootDir;
const revert = (entry: EditHistoryEntry, paths: readonly string[]): string => {
const subset = entry.snapshots.filter((s) => paths.includes(s.path));
if (subset.length === 0) {
return `batch #${entry.id}: nothing to undo (already restored or path not in batch)`;
}
const results = restoreSnapshots(subset, root);
for (const s of subset) entry.undoneFiles.add(s.path);
if (currentTurnEntry.current === entry && isEntryFullyUndone(entry)) {
currentTurnEntry.current = null;
}
if (undoTimeoutRef.current) {
clearTimeout(undoTimeoutRef.current);
undoTimeoutRef.current = null;
}
setUndoBanner(null);
const when = new Date(entry.at).toISOString().replace("T", " ").slice(11, 19);
const scope = subset.length === 1 ? subset[0]!.path : `${subset.length} file(s)`;
const header = `▸ undo: reverted ${scope} from batch #${entry.id} (${when})`;
return [header, ...formatUndoRows(results)].join("\n");
};
const idArg = args[0];
const pathArg = args[1];
if (!idArg) {
for (let i = editHistory.current.length - 1; i >= 0; i--) {
const e = editHistory.current[i]!;
if (isEntryFullyUndone(e)) continue;
const remaining = e.snapshots.map((s) => s.path).filter((p) => !e.undoneFiles.has(p));
return revert(e, remaining);
}
return "nothing to undo — every batch in the session history is already undone";
}
const id = Number.parseInt(idArg, 10);
if (!Number.isFinite(id)) {
return "usage: /undo [id] [path] (omit id for newest; id from /history; path from /show <id>)";
}
const entry = editHistory.current.find((e) => e.id === id);
if (!entry) return `no edit #${id} — run /history to see valid ids`;
if (!pathArg) {
const remaining = entry.snapshots
.map((s) => s.path)
.filter((p) => !entry.undoneFiles.has(p));
if (remaining.length === 0) return `batch #${id} is already fully undone`;
return revert(entry, remaining);
}
const snap = entry.snapshots.find((s) => s.path === pathArg);
if (!snap) {
const files = [...new Set(entry.blocks.map((b) => b.path))];
return `batch #${id} doesn't include "${pathArg}" — files in this batch: ${files.join(", ")}`;
}
if (entry.undoneFiles.has(pathArg)) {
return `${pathArg} in batch #${id} is already undone`;
}
return revert(entry, [pathArg]);
},
[codeMode],
);
const codeHistory = useCallback<UseEditHistoryResult["codeHistory"]>(() => {
if (!codeMode) return "not in code mode";
const entries = editHistory.current;
if (entries.length === 0) return "no edits recorded this session yet";
const lines = ["Edit history (oldest first):"];
for (const e of entries) {
const when = new Date(e.at).toISOString().replace("T", " ").slice(11, 19);
const files = new Set(e.blocks.map((b) => b.path));
const fileList = [...files].join(", ");
const fileSummary = fileList.length > 60 ? `${fileList.slice(0, 60)}…` : fileList;
const status = entryStatus(e);
const statusText =
status === "applied" ? "applied" : status === "PARTIAL" ? "PARTIAL" : "UNDONE ";
lines.push(
` #${String(e.id).padStart(3)} ${when} ${statusText} ${e.source.padEnd(12)} ${files.size} file · ${e.blocks.length} block ${fileSummary}`,
);
}
lines.push("");
lines.push(
"/show <id> → per-file summary · /show <id> <path> → full diff of one file",
);
lines.push(
"/undo → newest non-undone · /undo <id> [path] → target a specific batch or file",
);
return lines.join("\n");
}, [codeMode]);
const codeShowEdit = useCallback<UseEditHistoryResult["codeShowEdit"]>(
(args = []) => {
if (!codeMode) return "not in code mode";
const entries = editHistory.current;
if (entries.length === 0) return "no edits recorded this session — /history is empty";
const idArg = args[0];
const pathArg = args[1];
let entry: EditHistoryEntry | undefined;
if (!idArg) {
entry =
[...entries].reverse().find((e) => !isEntryFullyUndone(e)) ?? entries[entries.length - 1];
} else {
const id = Number.parseInt(idArg, 10);
if (!Number.isFinite(id)) {
return "usage: /show [id] [path] (omit id for newest; path from the per-file summary)";
}
entry = entries.find((e) => e.id === id);
if (!entry) return `no edit #${id} — run /history to see valid ids`;
}
if (!entry) return "unexpected: history lookup failed";
if (pathArg) {
const fileBlocks = entry.blocks.filter((b) => b.path === pathArg);
if (fileBlocks.length === 0) {
const files = [...new Set(entry.blocks.map((b) => b.path))];
return `batch #${entry.id} doesn't include "${pathArg}" — files in this batch: ${files.join(", ")}`;
}
const when = new Date(entry.at).toISOString().replace("T", " ").slice(11, 19);
const state = entry.undoneFiles.has(pathArg) ? "UNDONE" : "applied";
const header = `▸ edit #${entry.id} · ${when} · ${pathArg} · ${state} · ${fileBlocks.length} block(s)`;
const diff = formatAllBlockDiffs(fileBlocks, { maxLines: 60, contextLines: 2 });
const footer = entry.undoneFiles.has(pathArg)
? "(already reverted — /history shows the batch-level status)"
: `/undo ${entry.id} ${pathArg} → revert just this file`;
return [header, ...diff, "", footer].join("\n");
}
const when = new Date(entry.at).toISOString().replace("T", " ").slice(11, 19);
const files = [...new Set(entry.blocks.map((b) => b.path))];
const status = entryStatus(entry);
const header = `▸ edit #${entry.id} · ${when} · ${entry.source} · ${status} · ${files.length} file(s)`;
const countLines = (s: string) => (s.length === 0 ? 0 : (s.match(/\n/g)?.length ?? 0) + 1);
const fileLines = files.map((path) => {
const fileBlocks = entry!.blocks.filter((b) => b.path === path);
let removed = 0;
let added = 0;
for (const b of fileBlocks) {
removed += countLines(b.search);
added += countLines(b.replace);
}
const state = entry!.undoneFiles.has(path) ? "UNDONE" : "applied";
return ` ${state.padEnd(7)} -${String(removed).padStart(3)}/+${String(added).padStart(3)} ${path} (${fileBlocks.length} block${fileBlocks.length === 1 ? "" : "s"})`;
});
return [
header,
...fileLines,
"",
`/show ${entry.id} <path> → full diff of one file`,
`/undo ${entry.id} <path> → revert just that file · /undo ${entry.id} → revert whole batch`,
].join("\n");
},
[codeMode],
);
const sealCurrentEntry = useCallback(() => {
currentTurnEntry.current = null;
}, []);
const hasUndoable = useCallback(
() => editHistory.current.some((e) => !isEntryFullyUndone(e)),
[],
);
return {
undoBanner,
recordEdit,
armUndoBanner,
codeUndo,
codeHistory,
codeShowEdit,
sealCurrentEntry,
hasUndoable,
};
}
+119
View File
@@ -0,0 +1,119 @@
import { useCallback, useEffect, useState } from "react";
import type { CacheFirstLoop } from "../../loop.js";
import { VERSION, compareVersions, getLatestVersion } from "../../version.js";
export interface Balance {
currency: string;
total: number;
}
export interface UseSessionInfoResult {
balance: Balance | null;
models: string[] | null;
latestVersion: string | null;
/** Strictly-newer version string (for the header badge) — else `null`. */
updateAvailable: string | null;
refreshBalance: () => void;
refreshModels: () => void;
refreshLatestVersion: () => void;
}
/**
* Ambient session-level data fetched from DeepSeek + the npm registry
* at mount, refreshed either implicitly (balance after each turn) or
* on demand (`/update`, `/models`).
*
* All three are best-effort — a `null` value means "not loaded yet or
* the endpoint failed." The StatsPanel hides the cell in that case.
*/
export function useSessionInfo(loop: CacheFirstLoop): UseSessionInfoResult {
const [balance, setBalance] = useState<Balance | null>(null);
const [models, setModels] = useState<string[] | null>(null);
const [latestVersion, setLatestVersion] = useState<string | null>(null);
// Fetch balance on mount. Non-blocking — the session works without
// it; `null` hides the cell. handleSubmit calls refreshBalance in
// its finally so the number tracks actual spend rather than
// freezing at mount-time.
useEffect(() => {
let cancelled = false;
void (async () => {
const bal = await loop.client.getBalance().catch(() => null);
if (cancelled || !bal || !bal.balance_infos.length) return;
const primary = bal.balance_infos[0]!;
setBalance({ currency: primary.currency, total: Number(primary.total_balance) });
})();
return () => {
cancelled = true;
};
}, [loop]);
// Fetch the model catalog from DeepSeek once. Silent degrade on
// failure (stays null), so `/models` can tell "still loading /
// offline" apart from "loaded, here's the list."
useEffect(() => {
let cancelled = false;
void (async () => {
const list = await loop.client.listModels().catch(() => null);
if (cancelled || !list) return;
setModels(list.data.map((m) => m.id));
})();
return () => {
cancelled = true;
};
}, [loop]);
// Background registry check — 24h disk cache absorbs repeated
// launches, timeout bounded so a flaky network doesn't delay the
// notification. `null` on failure (silent). We store the raw version
// regardless of whether it's newer; the header badge's newer-only
// check happens at the `updateAvailable` derivation below.
useEffect(() => {
let cancelled = false;
void (async () => {
const latest = await getLatestVersion();
if (cancelled || !latest) return;
setLatestVersion(latest);
})();
return () => {
cancelled = true;
};
}, []);
const updateAvailable =
latestVersion && compareVersions(VERSION, latestVersion) < 0 ? latestVersion : null;
const refreshBalance = useCallback(() => {
void (async () => {
const bal = await loop.client.getBalance().catch(() => null);
if (bal?.balance_infos.length) {
const p = bal.balance_infos[0]!;
setBalance({ currency: p.currency, total: Number(p.total_balance) });
}
})();
}, [loop]);
const refreshModels = useCallback(() => {
void (async () => {
const list = await loop.client.listModels().catch(() => null);
if (list) setModels(list.data.map((m) => m.id));
})();
}, [loop]);
const refreshLatestVersion = useCallback(() => {
void (async () => {
const fresh = await getLatestVersion({ force: true });
if (fresh) setLatestVersion(fresh);
})();
}, []);
return {
balance,
models,
latestVersion,
updateAvailable,
refreshBalance,
refreshModels,
refreshLatestVersion,
};
}
+99
View File
@@ -0,0 +1,99 @@
import { useEffect, useRef, useState } from "react";
import type { SubagentEvent, SubagentSink } from "../../tools/subagent.js";
import { appendUsage } from "../../usage.js";
import type { DisplayEvent } from "./EventLog.js";
export interface SubagentActivity {
task: string;
iter: number;
elapsedMs: number;
}
export interface UseSubagentParams {
session: string | undefined;
setHistorical: React.Dispatch<React.SetStateAction<DisplayEvent[]>>;
}
export interface UseSubagentResult {
/** Live state for an in-flight subagent, null when none is running. */
activity: SubagentActivity | null;
/**
* Ref captured by the loop's `subagentRunner` closure so even
* late-spawned subagents find the current handler. Consumers pass
* this to `spawnSubagent({ sink })`.
*/
sinkRef: React.MutableRefObject<SubagentSink>;
}
/**
* Subagent UI wiring. `start` opens the activity row; each `progress`
* updates iter + elapsed in place; `end` clears the row and posts a
* one-line summary (with inline cost) into Historical. Only one
* subagent is active at a time in the MVP — overlapping events just
* replace the prior activity.
*/
export function useSubagent({ session, setHistorical }: UseSubagentParams): UseSubagentResult {
const [activity, setActivity] = useState<SubagentActivity | null>(null);
const sinkRef = useRef<SubagentSink>({ current: null });
useEffect(() => {
sinkRef.current.current = (ev: SubagentEvent) => {
if (ev.kind === "start") {
setActivity({
task: ev.task,
iter: ev.iter ?? 0,
elapsedMs: ev.elapsedMs ?? 0,
});
return;
}
if (ev.kind === "progress") {
setActivity({
task: ev.task,
iter: ev.iter ?? 0,
elapsedMs: ev.elapsedMs ?? 0,
});
return;
}
// end
setActivity(null);
const seconds = ((ev.elapsedMs ?? 0) / 1000).toFixed(1);
// Inline cost: the one number most users look at. Shown in the
// Historical row so they don't have to run `/stats` to see it.
const costTail =
ev.costUsd !== undefined && ev.costUsd > 0 ? ` · $${ev.costUsd.toFixed(4)}` : "";
const summary = ev.error
? `⌬ subagent "${ev.task}" failed after ${seconds}s · ${ev.iter ?? 0} tool call(s) — ${ev.error}`
: `⌬ subagent "${ev.task}" done in ${seconds}s · ${ev.iter ?? 0} tool call(s) · ${ev.turns ?? 0} turn(s)${costTail}`;
setHistorical((prev) => [
...prev,
{
id: `subagent-end-${Date.now()}`,
role: "info",
text: summary,
},
]);
// Persist a subagent summary row to ~/.reasonix/usage.jsonl so
// `/stats` and `reasonix stats` surface it. Skipped on error —
// we only record what actually cost money and did work.
if (!ev.error && ev.usage && ev.model) {
appendUsage({
session: session ?? null,
model: ev.model,
usage: ev.usage,
kind: "subagent",
subagent: {
skillName: ev.skillName,
taskPreview: ev.task.slice(0, 60),
toolIters: ev.iter ?? 0,
durationMs: ev.elapsedMs ?? 0,
},
});
}
};
return () => {
sinkRef.current.current = null;
};
}, [session, setHistorical]);
return { activity, sinkRef };
}
+63 -1
View File
@@ -64,6 +64,23 @@ export interface UserBalance {
balance_infos: BalanceInfo[];
}
/**
* Response shape for DeepSeek's `/models` endpoint. Mirrors the OpenAI
* models list shape DeepSeek copied — `id` is the model name to pass to
* `/chat/completions`, `owned_by` is the provider string (always
* `"deepseek"` today).
*/
export interface ModelInfo {
id: string;
object: "model";
owned_by: string;
}
export interface ModelList {
object: "list";
data: ModelInfo[];
}
export interface DeepSeekClientOptions {
apiKey?: string;
baseUrl?: string;
@@ -93,7 +110,17 @@ export class DeepSeekClient {
process.env.DEEPSEEK_BASE_URL ??
"https://api.deepseek.com"
).replace(/\/+$/, "");
this.timeoutMs = opts.timeoutMs ?? 120_000;
// 11 min. DeepSeek's load-balancer may keep a connection open for
// up to 10 minutes while the request waits in queue (non-streaming
// sends empty lines, streaming sends `:` SSE keep-alive comments —
// both are invisible to our parsers, so neither surfaces until the
// real response starts). Timing out at the legacy 2-min default
// killed queued requests prematurely, burned the queue slot on
// retry, and could loop through the whole queue repeatedly.
// Setting 11 min lets the server's own 10-min cap close the
// connection first (clean EOF → natural retry), and our timer
// is a safety net for genuinely hung sockets.
this.timeoutMs = opts.timeoutMs ?? 660_000;
this._fetch = opts.fetch ?? globalThis.fetch.bind(globalThis);
this.retry = opts.retry ?? {};
}
@@ -108,6 +135,18 @@ export class DeepSeekClient {
if (opts.temperature !== undefined) payload.temperature = opts.temperature;
if (opts.maxTokens !== undefined) payload.max_tokens = opts.maxTokens;
if (opts.responseFormat) payload.response_format = opts.responseFormat;
// V4 thinking-mode toggle: lives under `extra_body.thinking.type` per
// DeepSeek's docs. Docs also note that in thinking mode `temperature`,
// `top_p`, `presence_penalty`, `frequency_penalty` are silently
// ignored — we don't strip them here because the server's explicit
// "setting won't report an error" contract means leaving them in is
// safe and keeps the request payload diffable against OpenAI tooling.
if (opts.thinking) {
payload.extra_body = { thinking: { type: opts.thinking } };
}
if (opts.reasoningEffort) {
payload.reasoning_effort = opts.reasoningEffort;
}
return payload;
}
@@ -133,6 +172,29 @@ export class DeepSeekClient {
}
}
/**
* Fetch the model catalog DeepSeek currently exposes. Today this is
* `deepseek-chat` (V3) and `deepseek-reasoner` (R1), but querying is
* the only way to learn about new ones without a Reasonix release.
* Returns null on any network/auth failure so callers can degrade
* gracefully — e.g. `/models` falls back to the hardcoded hint.
*/
async listModels(opts: { signal?: AbortSignal } = {}): Promise<ModelList | null> {
try {
const resp = await this._fetch(`${this.baseUrl}/models`, {
method: "GET",
headers: { Authorization: `Bearer ${this.apiKey}` },
signal: opts.signal,
});
if (!resp.ok) return null;
const data = (await resp.json()) as ModelList;
if (!data || !Array.isArray(data.data)) return null;
return data;
} catch {
return null;
}
}
async chat(opts: ChatRequestOptions): Promise<ChatResponse> {
const ctrl = new AbortController();
const timer = setTimeout(() => ctrl.abort(), this.timeoutMs);
+124
View File
@@ -0,0 +1,124 @@
/**
* Render a SEARCH/REPLACE edit block as a compact unified-diff-style
* preview for the code-mode confirm gate. Shows the user what's about
* to land on disk BEFORE they press `y` — catches "wrong file" and
* "wrong replacement" mistakes that the old path + line-count summary
* couldn't.
*
* Not a full Myers diff: we trim shared leading/trailing lines as
* context and render the middle divergence as `-old` / `+new`. That's
* enough for the common SEARCH/REPLACE shape (small change inside a
* function body, wrapped with a few lines of surrounding code for
* uniqueness) and avoids pulling in a diff library.
*/
import type { EditBlock } from "./edit-blocks.js";
export interface DiffPreviewOptions {
/** How many lines of unchanged context to show at each end. Default 2. */
contextLines?: number;
/** Hard cap on total rendered lines. Default 20 — beyond this the preview collapses. */
maxLines?: number;
/** Indent applied to every output line. Default 8 spaces — matches the pending-preview nesting. */
indent?: string;
}
/** Render one edit block's diff. Returns an array of formatted lines. */
export function formatEditBlockDiff(block: EditBlock, opts: DiffPreviewOptions = {}): string[] {
const contextLines = Math.max(0, opts.contextLines ?? 2);
const maxLines = Math.max(4, opts.maxLines ?? 20);
const indent = opts.indent ?? " ";
const search = block.search === "" ? [] : block.search.split("\n");
const replace = block.replace.split("\n");
// New-file case: no search to compare, show the full new content
// (capped). Mark every line `+` so the user knows it's all additions.
if (search.length === 0) {
return renderAllPlus(replace, indent, maxLines);
}
// Common leading / trailing lines — shared context we can collapse.
let leading = 0;
while (
leading < search.length &&
leading < replace.length &&
search[leading] === replace[leading]
) {
leading++;
}
let trailing = 0;
while (
trailing < search.length - leading &&
trailing < replace.length - leading &&
search[search.length - 1 - trailing] === replace[replace.length - 1 - trailing]
) {
trailing++;
}
const searchMiddle = search.slice(leading, search.length - trailing);
const replaceMiddle = replace.slice(leading, replace.length - trailing);
// Trim context to `contextLines` on each side.
const leadShown = search.slice(Math.max(0, leading - contextLines), leading);
const leadHidden = leading - leadShown.length;
const trailShown = search.slice(
search.length - trailing,
search.length - trailing + contextLines,
);
const trailHidden = trailing - trailShown.length;
const out: string[] = [];
if (leadHidden > 0) {
out.push(`${indent} … ${leadHidden} unchanged line${leadHidden === 1 ? "" : "s"} above`);
}
for (const l of leadShown) out.push(`${indent} ${l}`);
for (const l of searchMiddle) out.push(`${indent}- ${l}`);
for (const l of replaceMiddle) out.push(`${indent}+ ${l}`);
for (const l of trailShown) out.push(`${indent} ${l}`);
if (trailHidden > 0) {
out.push(`${indent} … ${trailHidden} unchanged line${trailHidden === 1 ? "" : "s"} below`);
}
return capLines(out, maxLines, indent);
}
/**
* Render the full set of blocks back-to-back, each preceded by a
* path-and-size header so the user can tell which file owns each
* diff chunk. Blocks are separated by a blank line for breathing room.
*/
export function formatAllBlockDiffs(
blocks: readonly EditBlock[],
opts: DiffPreviewOptions = {},
): string[] {
const out: string[] = [];
for (let i = 0; i < blocks.length; i++) {
const b = blocks[i]!;
const removed = b.search === "" ? 0 : countLines(b.search);
const added = countLines(b.replace);
const tag = b.search === "" ? "NEW " : " ";
if (i > 0) out.push("");
out.push(` ${tag}${b.path} (-${removed} +${added} lines)`);
out.push(...formatEditBlockDiff(b, opts));
}
return out;
}
function countLines(s: string): number {
if (s.length === 0) return 0;
return (s.match(/\n/g)?.length ?? 0) + 1;
}
function renderAllPlus(lines: string[], indent: string, maxLines: number): string[] {
const out = lines.map((l) => `${indent}+ ${l}`);
return capLines(out, maxLines, indent);
}
function capLines(lines: string[], maxLines: number, indent: string): string[] {
if (lines.length <= maxLines) return lines;
const head = lines.slice(0, maxLines - 1);
const hidden = lines.length - head.length;
head.push(`${indent}… (${hidden} more diff lines — full content applies on /apply)`);
return head;
}
+21
View File
@@ -153,6 +153,27 @@ export function applyEditBlocks(blocks: EditBlock[], rootDir: string): ApplyResu
return blocks.map((b) => applyEditBlock(b, rootDir));
}
/**
* Build an EditBlock that represents a whole-file overwrite. If the
* target exists, SEARCH = current content so applyEditBlock replaces
* the whole thing when committed; if it doesn't, SEARCH is empty (the
* create-new sentinel). Used by the edit-mode gate when routing a
* `write_file` tool call through the review queue without executing
* the write inline.
*/
export function toWholeFileEditBlock(path: string, content: string, rootDir: string): EditBlock {
const abs = resolve(rootDir, path);
let search = "";
if (existsSync(abs)) {
try {
search = readFileSync(abs, "utf8");
} catch {
search = "";
}
}
return { path, search, replace: content, offset: 0 };
}
// ---------- snapshot / restore (for /undo) ----------
export interface EditSnapshot {
+111
View File
@@ -0,0 +1,111 @@
/**
* Durable checkpoint for the pending-edits queue.
*
* Code mode holds parsed SEARCH/REPLACE blocks in an in-memory
* `useRef<EditBlock[]>` until the user runs `/apply` or `/discard`.
* Pre-0.5.14 that was ephemeral: a crash or accidental Ctrl+C after
* the model proposed seven edits discarded all seven — the session
* log had the assistant text, but the "please review this batch"
* state was gone.
*
* This module checkpoints the queue to
* `~/.reasonix/sessions/<name>.pending.json`
* after every mutation (parse → set / apply → clear / discard →
* clear). On session resume the App reads the file and re-populates
* the queue. If the file doesn't exist the session resumes as before.
*
* Format choices:
* - JSON (not JSONL) — the queue is a single array written at once,
* not a stream of records.
* - Overwrite-on-write — the queue is small (kilobytes) and atomicity
* is "last write wins"; partial-write on crash is fine since we'd
* rather lose the checkpoint than have a torn file block resume.
* - Best-effort I/O — disk full or permission denied must not break
* the session. Silent skip matches the rest of the durable logs
* (session.ts, usage.ts).
*
* Ephemeral sessions (sessionName === null) skip persistence entirely:
* there's no stable name to key the checkpoint to.
*/
import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { sanitizeName, sessionsDir } from "../session.js";
import type { EditBlock } from "./edit-blocks.js";
/** Absolute path for the checkpoint file that belongs to this session. */
export function pendingEditsPath(sessionName: string): string {
return join(sessionsDir(), `${sanitizeName(sessionName)}.pending.json`);
}
/**
* Write the queue to disk, or delete the checkpoint file when `blocks`
* is empty. Callers pass the full current queue every time; we don't
* attempt append-style deltas because the queue is tiny.
*
* No-op when `sessionName` is null (ephemeral session has nowhere to
* write), so call sites can pass the session name directly without a
* null guard.
*/
export function savePendingEdits(sessionName: string | null, blocks: EditBlock[]): void {
if (!sessionName) return;
const path = pendingEditsPath(sessionName);
try {
if (blocks.length === 0) {
if (existsSync(path)) unlinkSync(path);
return;
}
mkdirSync(dirname(path), { recursive: true });
writeFileSync(path, JSON.stringify(blocks, null, 2), "utf8");
} catch {
/* best-effort — disk full / perms should not break the session */
}
}
/**
* Load the queue from disk, returns `null` when there's no checkpoint.
* A malformed file (power-loss torn write, user hand-edit) also returns
* null — silent recovery beats failing to open the session.
*/
export function loadPendingEdits(sessionName: string | null): EditBlock[] | null {
if (!sessionName) return null;
const path = pendingEditsPath(sessionName);
if (!existsSync(path)) return null;
let raw: string;
try {
raw = readFileSync(path, "utf8");
} catch {
return null;
}
try {
const parsed = JSON.parse(raw);
if (!Array.isArray(parsed)) return null;
const out: EditBlock[] = [];
for (const item of parsed) {
if (
item &&
typeof item === "object" &&
typeof item.path === "string" &&
typeof item.search === "string" &&
typeof item.replace === "string" &&
typeof item.offset === "number"
) {
out.push(item as EditBlock);
}
}
return out;
} catch {
return null;
}
}
/** Delete the checkpoint file unconditionally — called by /apply and /discard. */
export function clearPendingEdits(sessionName: string | null): void {
if (!sessionName) return;
const path = pendingEditsPath(sessionName);
try {
if (existsSync(path)) unlinkSync(path);
} catch {
/* best-effort */
}
}
+132 -8
View File
@@ -15,8 +15,71 @@
import { existsSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { ESCALATION_CONTRACT, TUI_FORMATTING_RULES } from "../prompt-fragments.js";
import { applyMemoryStack } from "../user-memory.js";
export const CODE_SYSTEM_PROMPT = `You are Reasonix Code, a coding assistant. You have filesystem tools (read_file, write_file, list_directory, search_files, etc.) rooted at the user's working directory.
export const CODE_SYSTEM_PROMPT = `You are Reasonix Code, a coding assistant. You have filesystem tools (read_file, write_file, edit_file, list_directory, directory_tree, search_files, search_content, get_file_info) rooted at the user's working directory, plus run_command / run_background for shell.
# Cite or shut up — non-negotiable
Every factual claim you make about THIS codebase must be backed by evidence. Reasonix VALIDATES the citations you write — broken paths or out-of-range lines render in **red strikethrough with ❌** in front of the user.
**Positive claims** (a file exists, a function does X, a feature IS implemented) — append a markdown link to the source:
- ✅ Correct: \`The MCP client supports listResources [listResources](src/mcp/client.ts:142).\`
- ❌ Wrong: \`The MCP client supports listResources.\` ← no citation, looks authoritative but unverifiable.
**Negative claims** (X is missing, Y is not implemented, lacks Z, doesn't have W) are the **most common hallucination shape**. They feel safe to write because no citation seems possible — but that's exactly why you must NOT write them on instinct.
If you are about to write "X is missing" or "Y is not implemented" — **STOP**. Call \`search_content\` for the relevant symbol or term FIRST. Only then:
- If the search returns matches → you were wrong; correct yourself and cite the matches.
- If the search returns nothing → state the absence with the search query as your evidence: \`No callers of \\\`foo()\\\` found (search_content "foo").\`
Asserting absence without a search is the #1 way evaluative answers go wrong. Treat the urge to write "missing" as a red flag in your own reasoning.
# When to propose a plan (submit_plan)
You have a \`submit_plan\` tool that shows the user a markdown plan and lets them Approve / Refine / Cancel before you execute. Use it proactively when the task is large enough to deserve a review gate:
- Multi-file refactors or renames.
- Architecture changes (moving modules, splitting / merging files, new abstractions).
- Anything where "undo" after the fact would be expensive — migrations, destructive cleanups, API shape changes.
- When the user's request is ambiguous and multiple reasonable interpretations exist — propose your reading as a plan and let them confirm.
Skip submit_plan for small, obvious changes: one-line typo, clear bug with a clear fix, adding a missing import, renaming a local variable. Just do those.
Plan body: one-sentence summary, then a file-by-file breakdown of what you'll change and why, and any risks or open questions. If some decisions are genuinely up to the user (naming, tradeoffs, out-of-scope possibilities), list them in an "Open questions" section — the user sees the plan in a picker and has a text input to answer your questions before approving. Don't pretend certainty you don't have; flagged questions are how the user tells you what they care about. After calling submit_plan, STOP — don't call any more tools, wait for the user's verdict.
# Plan mode (/plan)
The user can ALSO enter "plan mode" via /plan, which is a stronger, explicit constraint:
- Write tools (edit_file, write_file, create_directory, move_file) and non-allowlisted run_command calls are BOUNCED at dispatch — you'll get a tool result like "unavailable in plan mode". Don't retry them.
- Read tools (read_file, list_directory, search_files, directory_tree, get_file_info) and allowlisted read-only / test shell commands still work — use them to investigate.
- You MUST call submit_plan before anything will execute. Approve exits plan mode; Refine stays in; Cancel exits without implementing.
# Delegating to subagents via Skills
The pinned Skills index below lists playbooks you can invoke with \`run_skill\`. Entries tagged \`[🧬 subagent]\` spawn an **isolated subagent** — a fresh child loop that runs the playbook in its own context and returns only the final answer. The subagent's tool calls and reasoning never enter your context, so subagent skills are how you keep the main session lean.
**When you call \`run_skill\`, the \`name\` is ONLY the identifier before the tag** — e.g. \`run_skill({ name: "explore", arguments: "..." })\`, NOT \`"[🧬 subagent] explore"\` and NOT \`"explore [🧬 subagent]"\`. The tag is display sugar; the name argument is just the bare identifier.
Two built-ins ship by default:
- **explore** \`[🧬 subagent]\` — read-only investigation across the codebase. Use when the user says things like "find all places that...", "how does X work across the project", "survey the code for Y". Pass \`arguments\` describing the concrete question.
- **research** \`[🧬 subagent]\` — combines web search + code reading. Use for "is X supported by lib Y", "what's the canonical way to Z", "compare our impl to the spec".
When to delegate (call \`run_skill\` with a subagent skill):
- The task would otherwise need >5 file reads or searches.
- You only need the conclusion, not the exploration trail.
- The work is self-contained (you can describe it in one paragraph).
When NOT to delegate:
- Direct, narrow questions answerable in 1-2 tool calls — just do them.
- Anything where you need to track intermediate results yourself (planning, multi-step edits).
- Anything that requires user interaction (subagents can't submit plans or ask you for clarification).
Always pass a clear, self-contained \`arguments\` — that text is the **only** context the subagent gets.
# When to edit vs. when to explore
@@ -29,6 +92,15 @@ In those cases, use tools to gather what you need, then reply in prose. No SEARC
When you do propose edits, the user will review them and decide whether to \`/apply\` or \`/discard\`. Don't assume they'll accept — write as if each edit will be audited, because it will.
Reasonix runs an **edit gate**. The user's current mode (\`review\` or \`auto\`) decides what happens to your writes; you DO NOT see which mode is active, and you SHOULD NOT ask. Write the same way in both cases.
- In \`auto\` mode \`edit_file\` / \`write_file\` calls land on disk immediately with an undo window — you'll get the normal "edit blocks: 1/1 applied" style response.
- In \`review\` mode EACH \`edit_file\` / \`write_file\` call pauses tool dispatch while the user decides. You'll get one of these responses:
- \`"edit blocks: 1/1 applied"\` — user approved it. Continue as normal.
- \`"User rejected this edit to <path>. Don't retry the same SEARCH/REPLACE…"\` — user said no to THIS specific edit. Do NOT re-emit the same block, do NOT switch tools to sneak it past the gate (write_file → edit_file, or text-form SEARCH/REPLACE). Either take a clearly different approach or stop and ask the user what they want instead.
- Text-form SEARCH/REPLACE blocks in your assistant reply queue for end-of-turn /apply — same "don't retry on rejection" rule.
- If the user presses Esc mid-prompt the whole turn is aborted; you won't get another tool response. Don't keep spamming tool calls after an abort.
# Editing files
When you've been asked to change a file, output one or more SEARCH/REPLACE blocks in this exact format:
@@ -52,16 +124,66 @@ Rules:
- Do NOT use write_file to change existing files — the user reviews your edits as SEARCH/REPLACE. write_file is only for files you explicitly want to overwrite wholesale (rare).
- Paths are relative to the working directory. Don't use absolute paths.
# Trust what you already know
Before exploring the filesystem to answer a factual question, check whether the answer is already in context: the user's current message, earlier turns in this conversation (including prior tool results from \`remember\`), and the pinned memory blocks at the top of this prompt. When the user has stated a fact or you have remembered one, it outranks what the files say — don't re-derive from code what the user already told you. Explore when you genuinely don't know.
# Exploration
- Avoid listing or reading inside these common dependency / build directories unless the user explicitly asks about them: node_modules, dist, build, out, .next, .nuxt, .svelte-kit, .git, .venv, venv, __pycache__, target, coverage, .turbo, .cache. They're expensive and usually irrelevant.
- Prefer search_files / grep over list_directory when you know roughly what you're looking for — it saves context and avoids enumerating huge trees.
- Skip dependency, build, and VCS directories unless the user explicitly asks. The pinned .gitignore block (if any, below) is your authoritative denylist.
- Prefer \`search_files\` over \`list_directory\` when you know roughly what you're looking for — it saves context and avoids enumerating huge trees. Note: \`search_files\` matches file NAMES; for searching file CONTENTS use \`search_content\`.
- Available exploration tools: \`read_file\`, \`list_directory\`, \`directory_tree\`, \`search_files\` (filename match), \`search_content\` (content grep — use for "where is X called", "find all references to Y"), \`get_file_info\`. Don't call \`grep\` or other tools that aren't in this list — they don't exist as functions.
# Path conventions
Two different rules depending on which tool:
- **Filesystem tools** (\`read_file\`, \`list_directory\`, \`search_files\`, \`edit_file\`, etc.): paths are sandbox-relative. \`/\` means the project root, \`/src/foo.ts\` means \`<project>/src/foo.ts\`. Both relative (\`src/foo.ts\`) and POSIX-absolute (\`/src/foo.ts\`) forms work.
- **\`run_command\`**: the command runs in a real OS shell with cwd pinned to the project root. Paths inside the shell command are interpreted by THAT shell, not by us. **Never use leading \`/\` in run_command arguments** — Windows treats \`/tests\` as drive-root \`F:\\tests\` (non-existent), POSIX shells treat it as filesystem root. Use plain relative paths (\`tests\`, \`./tests\`, \`src/loop.ts\`) instead.
# Foreground vs. background commands
You have TWO tools for running shell commands, and picking the right one is non-negotiable:
- \`run_command\` — blocks until the process exits. Use for: **tests, builds, lints, typechecks, git operations, one-shot scripts**. Anything that naturally returns in under a minute.
- \`run_background\` — spawns and detaches after a brief startup window. Use for: **dev servers, watchers, any command with "dev" / "serve" / "watch" / "start" in the name**. Examples: \`npm run dev\`, \`pnpm dev\`, \`yarn start\`, \`vite\`, \`next dev\`, \`uvicorn app:app --reload\`, \`flask run\`, \`python -m http.server\`, \`cargo watch\`, \`tsc --watch\`, \`webpack serve\`.
**Never use run_command for a dev server.** It will block for 60s, time out, and the user will see a frozen tool call while the server was actually running fine. Always \`run_background\`, then \`job_output\` to peek at the logs when you need to verify something.
After \`run_background\`, tools available to you:
- \`job_output(jobId, tailLines?)\` — read recent logs to verify startup / debug errors.
- \`list_jobs\` — see every job this session (running + exited).
- \`stop_job(jobId)\` — SIGTERM → SIGKILL after grace. Stop before switching port / config.
Don't re-start an already-running dev server — call \`list_jobs\` first when in doubt.
# Scope discipline on "run it" / "start it" requests
When the user's request is to **run / start / launch / serve / boot up** something, your job is ONLY:
1. Start it (\`run_background\` for dev servers, \`run_command\` for one-shots).
2. Verify it came up (read a ready signal via \`job_output\`, or fetch the URL with \`web_fetch\` if they want you to confirm).
3. Report what's running, where (URL / port / pid), and STOP.
Do NOT, in the same turn:
- Run \`tsc\` / type-checkers / linters unless the user asked for it.
- Scan for bugs to "proactively" fix. The page rendering is success.
- Clean up unused imports, dead code, or refactor "while you're here."
- Edit files to improve anything the user didn't mention.
If you notice an obvious issue, MENTION it in one sentence and wait for the user to say "fix it." The cost of over-eagerness is real: you burn tokens, make surprise edits the user didn't want, and chain into cascading "fix the new error I just introduced" loops. The storm-breaker will cut you off, but the user still sees the mess.
"It works" is the end state. Resist the urge to polish.
# Style
- Show edits; don't narrate them in prose. "Here's the fix:" is enough.
- One short paragraph explaining *why*, then the blocks.
- If you need to explore first (list / grep / read), do it with tool calls before writing any prose — silence while exploring is fine.
- If you need to explore first (list / read / search), do it with tool calls before writing any prose — silence while exploring is fine.
${ESCALATION_CONTRACT}
${TUI_FORMATTING_RULES}
`;
/**
@@ -70,23 +192,25 @@ Rules:
* the file — we hand it to the model as-is. Truncate long ones so we
* don't eat context budget on huge generated ignore lists.
*
* Missing or unreadable .gitignore → returns the base prompt unchanged.
* Stacking order (stable for cache prefix):
* base prompt → REASONIX.md → global MEMORY.md → project MEMORY.md → .gitignore
*/
export function codeSystemPrompt(rootDir: string): string {
const withMemory = applyMemoryStack(CODE_SYSTEM_PROMPT, rootDir);
const gitignorePath = join(rootDir, ".gitignore");
if (!existsSync(gitignorePath)) return CODE_SYSTEM_PROMPT;
if (!existsSync(gitignorePath)) return withMemory;
let content: string;
try {
content = readFileSync(gitignorePath, "utf8");
} catch {
return CODE_SYSTEM_PROMPT;
return withMemory;
}
const MAX = 2000;
const truncated =
content.length > MAX
? `${content.slice(0, MAX)}\n… (truncated ${content.length - MAX} chars)`
: content;
return `${CODE_SYSTEM_PROMPT}
return `${withMemory}
# Project .gitignore
+146
View File
@@ -21,6 +21,23 @@ import { dirname, join } from "node:path";
/** One of the preset bundles (model + harvest + branch combo). */
export type PresetName = "fast" | "smart" | "max";
/**
* How `reasonix code` handles model-issued edits:
* - "review" — queue the edit into pendingEdits; user /apply or `y` commits.
* - "auto" — apply immediately, snapshot for /undo, show a short undo
* banner so the user can roll back with one keystroke.
* Persisted so `/mode auto` survives a relaunch. Missing → "review".
*/
export type EditMode = "review" | "auto";
/**
* reasoning_effort cap for the model. "max" is the agent-class default;
* "high" is cheaper / faster. Persisted so `/effort high` survives a
* relaunch — earlier versions silently reverted to "max" on every new
* session, which burned budget unexpectedly.
*/
export type ReasoningEffort = "high" | "max";
export interface ReasonixConfig {
apiKey?: string;
baseUrl?: string;
@@ -29,6 +46,22 @@ export interface ReasonixConfig {
* Maps to model + harvest + branch combos (see presets.ts). Missing → "fast".
*/
preset?: PresetName;
/**
* Edit-gate mode for `reasonix code`. See EditMode doc. Absent → "review".
*/
editMode?: EditMode;
/**
* Set to `true` the first time we've shown the "Shift+Tab cycles
* review/AUTO" onboarding tip in `reasonix code`. Once seen, we stop
* posting the tip — the bottom status bar carries the knowledge
* forward without further nagging.
*/
editModeHintShown?: boolean;
/**
* Last reasoning_effort chosen via `/effort`. Loaded on launch so
* "high" stays "high" — default is "max" when unset.
*/
reasoningEffort?: ReasoningEffort;
/**
* Default MCP server specs to bridge on every `reasonix chat`, in the
* same `"name=cmd args..."` format that `--mcp` takes. Stored as strings
@@ -44,6 +77,23 @@ export interface ReasonixConfig {
session?: string | null;
/** Marks that `reasonix setup` has completed at least once. */
setupCompleted?: boolean;
/**
* Whether `web_search` + `web_fetch` tools are registered. Default:
* enabled (no key required — backed by DuckDuckGo's public HTML
* endpoint). Set to `false` to keep the session offline.
*/
search?: boolean;
/**
* Per-project state keyed by absolute directory path. Written by the
* "always allow" choice on a shell confirmation prompt; merged into
* `registerShellTools({ extraAllowed })` when `reasonix code` runs
* against that directory again.
*/
projects?: {
[absoluteRootDir: string]: {
shellAllowed?: string[];
};
};
}
export function defaultConfigPath(): string {
@@ -78,12 +128,108 @@ export function loadApiKey(path: string = defaultConfigPath()): string | undefin
return readConfig(path).apiKey;
}
/**
* Resolve whether web-search tools should be registered. Default: on.
* Env `REASONIX_SEARCH=off` or config `search: false` turns it off.
* Any other value falls through to enabled.
*/
export function searchEnabled(path: string = defaultConfigPath()): boolean {
const env = process.env.REASONIX_SEARCH;
if (env === "off" || env === "false" || env === "0") return false;
const cfg = readConfig(path).search;
if (cfg === false) return false;
return true;
}
export function saveApiKey(key: string, path: string = defaultConfigPath()): void {
const cfg = readConfig(path);
cfg.apiKey = key.trim();
writeConfig(cfg, path);
}
/**
* Read the persisted "always allow" shell-command prefixes for a
* given project root. Returns an empty array when nothing's stored.
*/
export function loadProjectShellAllowed(
rootDir: string,
path: string = defaultConfigPath(),
): string[] {
const cfg = readConfig(path);
return cfg.projects?.[rootDir]?.shellAllowed ?? [];
}
/**
* Append a prefix to the project's shell-allowed list, dedup and
* persist. No-op if the prefix is empty/whitespace or already stored.
*/
export function addProjectShellAllowed(
rootDir: string,
prefix: string,
path: string = defaultConfigPath(),
): void {
const trimmed = prefix.trim();
if (!trimmed) return;
const cfg = readConfig(path);
if (!cfg.projects) cfg.projects = {};
if (!cfg.projects[rootDir]) cfg.projects[rootDir] = {};
const existing = cfg.projects[rootDir].shellAllowed ?? [];
if (existing.includes(trimmed)) return;
cfg.projects[rootDir].shellAllowed = [...existing, trimmed];
writeConfig(cfg, path);
}
/**
* Read the persisted edit-mode. Unknown values fall back to "review" so
* a user who hand-edits the file into an invalid state still gets the
* safe default. `reasonix code` calls this at launch and the App lets
* `/mode` / Shift+Tab flip it.
*/
export function loadEditMode(path: string = defaultConfigPath()): EditMode {
const v = readConfig(path).editMode;
return v === "auto" ? "auto" : "review";
}
/** Persist the edit mode so `/mode auto` survives a relaunch. */
export function saveEditMode(mode: EditMode, path: string = defaultConfigPath()): void {
const cfg = readConfig(path);
cfg.editMode = mode;
writeConfig(cfg, path);
}
/** True when the onboarding tip for the review/AUTO gate has been shown. */
export function editModeHintShown(path: string = defaultConfigPath()): boolean {
return readConfig(path).editModeHintShown === true;
}
/**
* Read the persisted reasoning_effort. Unknown / missing values fall
* back to "max" so the agent-class default is never silently overridden
* by a hand-edited bad value in config.json.
*/
export function loadReasoningEffort(path: string = defaultConfigPath()): ReasoningEffort {
const v = readConfig(path).reasoningEffort;
return v === "high" ? "high" : "max";
}
/** Persist the reasoning_effort cap so `/effort high` survives a relaunch. */
export function saveReasoningEffort(
effort: ReasoningEffort,
path: string = defaultConfigPath(),
): void {
const cfg = readConfig(path);
cfg.reasoningEffort = effort;
writeConfig(cfg, path);
}
/** Mark the onboarding tip as shown so subsequent launches skip it. */
export function markEditModeHintShown(path: string = defaultConfigPath()): void {
const cfg = readConfig(path);
if (cfg.editModeHintShown === true) return;
cfg.editModeHintShown = true;
writeConfig(cfg, path);
}
export function isPlausibleKey(key: string): boolean {
const trimmed = key.trim();
return /^sk-[A-Za-z0-9_-]{16,}$/.test(trimmed);
+13
View File
@@ -78,6 +78,12 @@ export async function harvest(
const trimmed = reasoningContent.trim();
if (trimmed.length < minLen) return emptyPlanState();
// Harvest is schema-constrained JSON extraction, not agent reasoning.
// Default to `deepseek-chat` (= v4-flash non-thinking mode) — a few
// hundred output tokens fit easily in the non-thinking budget, the
// reply comes back ~10× faster than thinking mode, and the
// per-turn cost stays an asterisk next to the main loop's spend
// rather than a visible slice of it.
const model = options.model ?? "deepseek-chat";
const maxItems = options.maxItems ?? 5;
const maxItemLen = options.maxItemLen ?? 80;
@@ -96,6 +102,13 @@ export async function harvest(
responseFormat: { type: "json_object" },
temperature: 0,
maxTokens: 600,
// Pin mode + effort so a future default-model swap (e.g. someone
// sets `options.model = "deepseek-v4-pro"`) can't accidentally
// turn this micro-extraction into a multi-thousand-reasoning-
// token call. DeepSeek ignores these on non-thinking models, so
// the request stays valid regardless of the chosen model.
thinking: "disabled",
reasoningEffort: "high",
signal,
});
return parsePlanState(resp.content, maxItems, maxItemLen);
+404
View File
@@ -0,0 +1,404 @@
/**
* Hooks — user-defined automation that fires at well-known points in
* the agent loop. Mirrors the two-scope layout we use for memory and
* skills:
*
* - `<project>/.reasonix/settings.json` — committable per-project
* - `~/.reasonix/settings.json` — every session
*
* A hook is a shell command. We invoke it with stdin = a JSON
* payload describing the event, and interpret the exit code:
*
* - `0` — pass; loop continues normally
* - `2` — block; for `PreToolUse` / `UserPromptSubmit` the
* loop refuses to continue with that step and surfaces the
* hook's stderr as the reason. For `PostToolUse` / `Stop` block
* is meaningless (the action already happened) — treat as warn.
* - anything else — warn; loop continues but stderr is rendered
* to the user as an inline notice.
*
* stdin JSON shape (one envelope per event):
*
* {
* "event": "PreToolUse" | "PostToolUse" | "UserPromptSubmit" | "Stop",
* "cwd": "<absolute project root or process.cwd()>",
* "toolName": "<string>", // tool events only
* "toolArgs": <unknown>, // tool events only — already JSON-decoded
* "toolResult": "<string>", // PostToolUse only — same body the model sees
* "prompt": "<string>", // UserPromptSubmit only
* "lastAssistantText": "<string>", // Stop only
* "turn": <number>, // Stop only
* }
*
* Hooks are executed in order: project scope first, then global.
* `Pre*` events stop dispatching at the first block; non-block
* outcomes accumulate into a single report so the UI can render
* each warning inline.
*/
import { spawn } from "node:child_process";
import { existsSync, readFileSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
export type HookEvent = "PreToolUse" | "PostToolUse" | "UserPromptSubmit" | "Stop";
/** All four events as a const array — drives slash listing + validation. */
export const HOOK_EVENTS: readonly HookEvent[] = [
"PreToolUse",
"PostToolUse",
"UserPromptSubmit",
"Stop",
] as const;
/** Only the gating events can block the loop. */
const BLOCKING_EVENTS: ReadonlySet<HookEvent> = new Set(["PreToolUse", "UserPromptSubmit"]);
/** Per-event default timeout. Tool/prompt hooks gate progress, so they're tight. */
const DEFAULT_TIMEOUTS_MS: Record<HookEvent, number> = {
PreToolUse: 5_000,
UserPromptSubmit: 5_000,
PostToolUse: 30_000,
Stop: 30_000,
};
export type HookScope = "project" | "global";
export interface HookConfig {
/**
* Tool-name pattern (PreToolUse / PostToolUse only). Anchored regex.
* Omitted or `"*"` matches every tool. Ignored for prompt / Stop
* events (they have no tool name to match against).
*/
match?: string;
/** Shell command to run. Spawned through the platform shell. */
command: string;
/** Optional human description — surfaced in `/hooks`. */
description?: string;
/** Per-hook timeout override in ms. */
timeout?: number;
/**
* Working directory for the spawned process. Defaults to:
* - project scope → the project root
* - global scope → process.cwd()
*/
cwd?: string;
}
/** Shape of `<scope>/.reasonix/settings.json` — only `hooks` for now. */
export interface HookSettings {
hooks?: Partial<Record<HookEvent, HookConfig[]>>;
}
/** A loaded hook with its origin scope baked in (used for ordering and `/hooks`). */
export interface ResolvedHook extends HookConfig {
event: HookEvent;
scope: HookScope;
/** Absolute path to the settings.json the hook came from. */
source: string;
}
/** Outcome of a single hook invocation. */
export interface HookOutcome {
/** Which hook fired. */
hook: ResolvedHook;
/**
* Decision:
* - `pass` — exit 0
* - `block` — exit 2 on a blocking event (otherwise downgraded to `warn`)
* - `warn` — non-zero exit that is not a successful block
* - `timeout` — the spawn was killed past `timeout`
* - `error` — could not spawn at all (missing command, etc.)
*/
decision: "pass" | "block" | "warn" | "timeout" | "error";
exitCode: number | null;
/** Captured stdout (trimmed). May be empty. */
stdout: string;
/** Captured stderr (trimmed). The block / warn message comes from here. */
stderr: string;
durationMs: number;
}
/** Aggregate report for `runHooks`. */
export interface HookReport {
event: HookEvent;
outcomes: HookOutcome[];
/** True iff at least one outcome was a `block` — only meaningful for blocking events. */
blocked: boolean;
}
export const HOOK_SETTINGS_FILENAME = "settings.json";
export const HOOK_SETTINGS_DIRNAME = ".reasonix";
/** Where the global settings.json lives. Equivalent to `~/.reasonix/settings.json`. */
export function globalSettingsPath(homeDirOverride?: string): string {
return join(homeDirOverride ?? homedir(), HOOK_SETTINGS_DIRNAME, HOOK_SETTINGS_FILENAME);
}
/** Where the project settings.json lives for a given root. */
export function projectSettingsPath(projectRoot: string): string {
return join(projectRoot, HOOK_SETTINGS_DIRNAME, HOOK_SETTINGS_FILENAME);
}
function readSettingsFile(path: string): HookSettings | null {
if (!existsSync(path)) return null;
try {
const raw = readFileSync(path, "utf8");
const parsed = JSON.parse(raw);
if (parsed && typeof parsed === "object") return parsed as HookSettings;
} catch {
/* malformed JSON → treat as no hooks; do NOT throw, the user
* shouldn't lose the whole CLI to a typo in their settings */
}
return null;
}
/**
* Pull every configured hook out of the project + global settings
* files, in the order they should fire (project first, global second,
* within each scope: array order from the file).
*
* Returns a flat list — the dispatcher filters by event + match
* pattern at run time. Loading is cheap (one or two JSON files), so
* we don't memoize across processes; re-load is allowed via
* `/hooks reload` and on every fresh App mount.
*/
export interface LoadHookSettingsOptions {
/** Absolute project root, if any. Without it, only global hooks load. */
projectRoot?: string;
/** Override `~` for tests. */
homeDir?: string;
}
export function loadHooks(opts: LoadHookSettingsOptions = {}): ResolvedHook[] {
const out: ResolvedHook[] = [];
if (opts.projectRoot) {
const projPath = projectSettingsPath(opts.projectRoot);
const settings = readSettingsFile(projPath);
if (settings) appendResolved(out, settings, "project", projPath);
}
const globalPath = globalSettingsPath(opts.homeDir);
const settings = readSettingsFile(globalPath);
if (settings) appendResolved(out, settings, "global", globalPath);
return out;
}
function appendResolved(
out: ResolvedHook[],
settings: HookSettings,
scope: HookScope,
source: string,
): void {
if (!settings.hooks) return;
for (const event of HOOK_EVENTS) {
const list = settings.hooks[event];
if (!Array.isArray(list)) continue;
for (const cfg of list) {
if (!cfg || typeof cfg.command !== "string" || cfg.command.trim() === "") continue;
out.push({ ...cfg, event, scope, source });
}
}
}
/**
* True if `toolName` matches the hook's `match` field. `"*"` and
* undefined match everything. Otherwise we anchor the field as a
* regex — partial-name matches don't fire, so `"file"` would not
* trigger on `read_file` (use `".*file"` for that).
*/
export function matchesTool(hook: ResolvedHook, toolName: string): boolean {
if (hook.event !== "PreToolUse" && hook.event !== "PostToolUse") return true;
const m = hook.match;
if (!m || m === "*") return true;
try {
const re = new RegExp(`^(?:${m})$`);
return re.test(toolName);
} catch {
/* malformed regex → don't fire (safer than firing on every tool) */
return false;
}
}
/** Payload envelope passed to hook stdin. */
export interface HookPayload {
event: HookEvent;
cwd: string;
toolName?: string;
toolArgs?: unknown;
toolResult?: string;
prompt?: string;
lastAssistantText?: string;
turn?: number;
}
/** Test seam — same shape as Node's spawn but returns a Promise of the raw outcome bits. */
export interface HookSpawnInput {
command: string;
cwd: string;
stdin: string;
timeoutMs: number;
}
export interface HookSpawnResult {
exitCode: number | null;
stdout: string;
stderr: string;
timedOut: boolean;
/** True iff spawn() itself failed (ENOENT, EACCES, …). */
spawnError?: Error;
}
export type HookSpawner = (input: HookSpawnInput) => Promise<HookSpawnResult>;
/**
* Default spawner — runs `command` through the platform shell so
* `&&`, pipes, env-var expansion all work without a tokenizer.
* Stdin is the JSON payload, stdout / stderr are buffered.
*
* Why `shell: true`? A hook is intentionally a shell command — that's
* the contract. Treating it like an argv array would surprise users
* who write `bun run check && eslint .` and expect it to behave the
* way it does in their terminal.
*/
function defaultSpawner(input: HookSpawnInput): Promise<HookSpawnResult> {
return new Promise<HookSpawnResult>((resolve) => {
const child = spawn(input.command, {
cwd: input.cwd,
shell: true,
stdio: ["pipe", "pipe", "pipe"],
});
let stdout = "";
let stderr = "";
let timedOut = false;
const timer = setTimeout(() => {
timedOut = true;
child.kill("SIGTERM");
// SIGTERM may not land on Windows for shell children — followed
// by a hard kill a moment later if the process is still around.
setTimeout(() => {
try {
child.kill("SIGKILL");
} catch {
/* already gone */
}
}, 500);
}, input.timeoutMs);
child.stdout.on("data", (chunk: Buffer) => {
stdout += chunk.toString("utf8");
});
child.stderr.on("data", (chunk: Buffer) => {
stderr += chunk.toString("utf8");
});
child.once("error", (err) => {
clearTimeout(timer);
resolve({
exitCode: null,
stdout,
stderr,
timedOut: false,
spawnError: err,
});
});
child.once("close", (code) => {
clearTimeout(timer);
resolve({
exitCode: code,
stdout: stdout.trim(),
stderr: stderr.trim(),
timedOut,
});
});
try {
child.stdin.write(input.stdin);
child.stdin.end();
} catch {
/* stdin write can race with spawn errors; the close handler
* still fires with exit 0/null */
}
});
}
/**
* Format a hook outcome as a single-line UI string. Used by both the
* loop (for `warning` events) and the App (for UserPromptSubmit /
* Stop outcomes). Centralizing keeps the language consistent across
* scopes.
*/
export function formatHookOutcomeMessage(outcome: HookOutcome): string {
if (outcome.decision === "pass") return "";
const detail = (outcome.stderr || outcome.stdout || "").trim();
const tag = `${outcome.hook.scope}/${outcome.hook.event}`;
const cmd =
outcome.hook.command.length > 60
? `${outcome.hook.command.slice(0, 60)}…`
: outcome.hook.command;
const head = `hook ${tag} \`${cmd}\` ${outcome.decision}`;
return detail ? `${head}: ${detail}` : head;
}
/**
* Decide the hook's outcome decision from raw spawn results.
* Pulled out as a pure function so tests can pin the matrix.
*/
export function decideOutcome(
event: HookEvent,
raw: HookSpawnResult,
): "pass" | "block" | "warn" | "timeout" | "error" {
if (raw.spawnError) return "error";
if (raw.timedOut) return BLOCKING_EVENTS.has(event) ? "block" : "warn";
if (raw.exitCode === 0) return "pass";
if (raw.exitCode === 2 && BLOCKING_EVENTS.has(event)) return "block";
return "warn";
}
export interface RunHooksOptions {
payload: HookPayload;
hooks: ResolvedHook[];
/** Test seam — defaults to a real `spawn`. */
spawner?: HookSpawner;
}
/**
* Filter hooks down to the ones that match `payload.event` (and
* `payload.toolName`, for tool events), then run them in order.
* Stops at the first `block` outcome on a blocking event so a
* gating hook can prevent later hooks from incorrectly seeing a
* success that wasn't going to happen.
*/
export async function runHooks(opts: RunHooksOptions): Promise<HookReport> {
const spawner = opts.spawner ?? defaultSpawner;
const event = opts.payload.event;
const toolName = opts.payload.toolName ?? "";
const matching = opts.hooks.filter((h) => h.event === event && matchesTool(h, toolName));
const outcomes: HookOutcome[] = [];
let blocked = false;
const stdin = `${JSON.stringify(opts.payload)}\n`;
for (const hook of matching) {
const start = Date.now();
const timeoutMs = hook.timeout ?? DEFAULT_TIMEOUTS_MS[event];
const cwd = hook.cwd ?? opts.payload.cwd;
const raw = await spawner({ command: hook.command, cwd, stdin, timeoutMs });
const decision = decideOutcome(event, raw);
outcomes.push({
hook,
decision,
exitCode: raw.exitCode,
stdout: raw.stdout,
stderr:
raw.stderr ||
(raw.spawnError ? raw.spawnError.message : "") ||
(raw.timedOut ? `hook timed out after ${timeoutMs}ms` : ""),
durationMs: Date.now() - start,
});
if (decision === "block") {
blocked = true;
break;
}
}
return { event, outcomes, blocked };
}
+143 -1
View File
@@ -6,9 +6,30 @@ export type { ChatResponse, StreamChunk, DeepSeekClientOptions } from "./client.
export {
CacheFirstLoop,
formatLoopError,
fixToolCallPairing,
healLoadedMessages,
healLoadedMessagesByTokens,
stripHallucinatedToolMarkup,
} from "./loop.js";
export {
AT_MENTION_PATTERN,
AT_PICKER_PREFIX,
DEFAULT_AT_MENTION_MAX_BYTES,
DEFAULT_PICKER_IGNORE_DIRS,
detectAtPicker,
expandAtMentions,
listFilesSync,
listFilesWithStatsSync,
rankPickerCandidates,
} from "./at-mentions.js";
export type {
AtMentionExpansion,
AtMentionOptions,
FileWithStats,
ListFilesOptions,
PickerCandidate,
RankPickerOptions,
} from "./at-mentions.js";
export type {
CacheFirstLoopOptions,
LoopEvent,
@@ -29,10 +50,77 @@ export type {
export { ImmutablePrefix, AppendOnlyLog, VolatileScratch } from "./memory.js";
export type { ImmutablePrefixOptions } from "./memory.js";
export {
PROJECT_MEMORY_FILE,
PROJECT_MEMORY_MAX_CHARS,
applyProjectMemory,
memoryEnabled,
readProjectMemory,
} from "./project-memory.js";
export type { ProjectMemory } from "./project-memory.js";
export {
MEMORY_INDEX_FILE,
MEMORY_INDEX_MAX_CHARS,
MemoryStore,
USER_MEMORY_DIR,
applyMemoryStack,
applyUserMemory,
projectHash,
sanitizeMemoryName,
} from "./user-memory.js";
export type {
MemoryEntry,
MemoryScope,
MemoryStoreOptions,
MemoryType,
WriteInput as MemoryWriteInput,
} from "./user-memory.js";
export { ToolRegistry } from "./tools.js";
export type { ToolDefinition, ToolCallContext } from "./tools.js";
export { registerFilesystemTools } from "./tools/filesystem.js";
export type { FilesystemToolsOptions } from "./tools/filesystem.js";
export { registerMemoryTools } from "./tools/memory.js";
export type { MemoryToolsOptions } from "./tools/memory.js";
export { PlanProposedError, registerPlanTool } from "./tools/plan.js";
export type { PlanToolOptions } from "./tools/plan.js";
export { forkRegistryExcluding, registerSubagentTool } from "./tools/subagent.js";
export type {
SubagentEvent,
SubagentSink,
SubagentToolOptions,
} from "./tools/subagent.js";
export {
NeedsConfirmationError,
detectShellOperator,
formatCommandResult,
injectPowerShellUtf8,
isAllowed,
prepareSpawn,
quoteForCmdExe,
registerShellTools,
resolveExecutable,
runCommand,
tokenizeCommand,
withUtf8Codepage,
} from "./tools/shell.js";
export type { RunCommandResult, ShellToolsOptions } from "./tools/shell.js";
export {
formatSearchResults,
htmlToText,
parseMojeekResults,
registerWebTools,
webFetch,
webSearch,
} from "./tools/web.js";
export type {
PageContent,
SearchResult,
WebFetchOptions,
WebSearchOptions,
WebToolsOptions,
} from "./tools/web.js";
export {
SessionStats,
@@ -107,9 +195,11 @@ export { SseTransport } from "./mcp/sse.js";
export type { SseTransportOptions } from "./mcp/sse.js";
export {
DEFAULT_MAX_RESULT_CHARS,
DEFAULT_MAX_RESULT_TOKENS,
bridgeMcpTools,
flattenMcpResult,
truncateForModel,
truncateForModelByTokens,
} from "./mcp/registry.js";
export type { BridgeOptions, BridgeResult, FlattenOptions } from "./mcp/registry.js";
export { parseMcpSpec } from "./mcp/spec.js";
@@ -186,4 +276,56 @@ export type {
JSONSchema,
} from "./types.js";
export const VERSION = "0.4.3";
export {
LATEST_CACHE_TTL_MS,
LATEST_FETCH_TIMEOUT_MS,
VERSION,
compareVersions,
getLatestVersion,
isNpxInstall,
} from "./version.js";
export type { GetLatestVersionOptions } from "./version.js";
export {
HOOK_EVENTS,
HOOK_SETTINGS_DIRNAME,
HOOK_SETTINGS_FILENAME,
decideOutcome,
formatHookOutcomeMessage,
globalSettingsPath,
loadHooks,
matchesTool,
projectSettingsPath,
runHooks,
} from "./hooks.js";
export {
aggregateUsage,
appendUsage,
bucketCacheHitRatio,
bucketSavingsFraction,
defaultUsageLogPath,
formatLogSize,
readUsageLog,
} from "./usage.js";
export type {
AggregateOptions,
AppendUsageInput,
UsageAggregate,
UsageBucket,
UsageRecord,
} from "./usage.js";
export type {
HookConfig,
HookEvent,
HookOutcome,
HookPayload,
HookReport,
HookScope,
HookSettings,
HookSpawner,
HookSpawnInput,
HookSpawnResult,
LoadHookSettingsOptions,
ResolvedHook,
RunHooksOptions,
} from "./hooks.js";
+1232 -55
View File
File diff suppressed because it is too large. Load diff
+101
View File
@@ -7,6 +7,7 @@
* MCP ecosystem tool, wrapped in Reasonix's Pillar 1 + Pillar 3 benefits.
*/
import { countTokens } from "../tokenizer.js";
import { ToolRegistry } from "../tools.js";
import type { JSONSchema } from "../types.js";
import type { McpClient } from "./client.js";
@@ -58,6 +59,18 @@ export interface BridgeOptions {
*/
export const DEFAULT_MAX_RESULT_CHARS = 32_000;
/**
* Token-aware cap for tool results, in DeepSeek V3 tokens.
*
* 8,000 tokens ≈ 6% of DeepSeek V3's 131K context. One oversized tool
* result can't eat more than that no matter what character density the
* content has. The char cap (32K chars) only bounds tokens for English
* — CJK text at 1 char/token blows past 16K tokens under the same
* ceiling. With the tokenizer shipped in 0.5.0 we can cap the thing
* that actually matters.
*/
export const DEFAULT_MAX_RESULT_TOKENS = 8_000;
export interface BridgeResult {
registry: ToolRegistry;
/** Names actually registered (may differ from MCP names when a prefix is applied). */
@@ -159,6 +172,94 @@ export function truncateForModel(s: string, maxChars: number): string {
return `${head}\n\n[…truncated ${dropped} chars — raise BridgeOptions.maxResultChars, or call the tool with a narrower scope (filter, head, pagination)…]\n\n${tail}`;
}
/**
* Token-aware truncation. Same head+tail policy as `truncateForModel`,
* but sizes the slices against a DeepSeek V3 token budget instead of a
* raw character count — so CJK text (which previously survived at 2×
* the token cost per char) gets capped at the same effective context
* footprint as English.
*
* Strategy: fast path when `s.length <= maxTokens` (every token is ≥1
* char, so this bounds tokens ≤ maxTokens — skip tokenize entirely).
* Short-ish strings are confirmed against the real token count.
* Long strings go straight to char-sliced head+tail with one or two
* tokenize-verify-and-shrink rounds per slice — we deliberately never
* tokenize the full input, because pathological repetitive text
* (megabytes of `AAAA…`) can cost 30s+ on the pure-TS BPE port.
*/
export function truncateForModelByTokens(s: string, maxTokens: number): string {
if (maxTokens <= 0) return "";
// Every token is ≥1 char — if length ≤ budget, tokens ≤ budget.
if (s.length <= maxTokens) return s;
// Small enough to tokenize-check without pathological cost: confirm
// whether we're actually over budget. (Threshold is the char-bound
// worst case for English/code — ~4 chars/token.)
if (s.length <= maxTokens * 4) {
const tokens = countTokens(s);
if (tokens <= maxTokens) return s;
}
const markerOverhead = 48; // rough token cost of the truncation marker
const contentBudget = Math.max(0, maxTokens - markerOverhead);
const tailBudget = Math.min(256, Math.floor(contentBudget * 0.1));
const headBudget = Math.max(0, contentBudget - tailBudget);
const head = sizePrefixToTokens(s, headBudget);
const tail = sizeSuffixToTokens(s, tailBudget);
const droppedChars = s.length - head.length - tail.length;
// Estimate dropped tokens from the per-slice char/token ratio we
// already measured, rather than paying another full-string tokenize.
// The marker says "~N tokens" so the ≤10% slop is visible to readers.
const headTokens = head ? countTokens(head) : 0;
const tailTokens = tail ? countTokens(tail) : 0;
const sampleChars = head.length + tail.length;
const sampleTokens = headTokens + tailTokens;
const ratio = sampleChars > 0 ? sampleTokens / sampleChars : 0.3;
const estTotalTokens = Math.ceil(s.length * ratio);
const droppedTokens = Math.max(0, estTotalTokens - sampleTokens);
return `${head}\n\n[…truncated ~${droppedTokens} tokens (${droppedChars} chars) — raise BridgeOptions.maxResultTokens, or call the tool with a narrower scope (filter, head, pagination)…]\n\n${tail}`;
}
/**
* Slice `s` from the start to the largest prefix that fits `budget`
* tokens. Never tokenizes the full input: starts with a char-bound
* estimate, then verifies and shrinks. Converges in 1–2 iterations.
*/
function sizePrefixToTokens(s: string, budget: number): string {
if (budget <= 0 || s.length === 0) return "";
// Optimistic starting size: assume ~4 chars/token (English/code
// average). If the content is denser (CJK ~1 char/token), the first
// tokenize will show we're over and we shrink.
let size = Math.min(s.length, budget * 4);
for (let iter = 0; iter < 6; iter++) {
if (size <= 0) return "";
const slice = s.slice(0, size);
const count = countTokens(slice);
if (count <= budget) return slice;
// Shrink by the overshoot fraction plus a small safety margin.
const next = Math.floor(size * (budget / count) * 0.95);
if (next >= size) return s.slice(0, Math.max(0, size - 1));
size = next;
}
return s.slice(0, Math.max(0, size));
}
/** Slice `s` from the end to the largest suffix that fits `budget` tokens. */
function sizeSuffixToTokens(s: string, budget: number): string {
if (budget <= 0 || s.length === 0) return "";
let size = Math.min(s.length, budget * 4);
for (let iter = 0; iter < 6; iter++) {
if (size <= 0) return "";
const slice = s.slice(-size);
const count = countTokens(slice);
if (count <= budget) return slice;
const next = Math.floor(size * (budget / count) * 0.95);
if (next >= size) return s.slice(-Math.max(0, size - 1));
size = next;
}
return s.slice(-Math.max(0, size));
}
function blockToString(block: McpContentBlock): string {
if (block.type === "text") return block.text;
if (block.type === "image") return `[image ${block.mimeType}, ${block.data.length} chars base64]`;
+99
View File
@@ -0,0 +1,99 @@
/**
* Project memory — a user-authored `REASONIX.md` in the project root
* that gets pinned into the immutable-prefix system prompt.
*
* Design notes:
*
* - The file lands in `ImmutablePrefix.system`, so the whole memory
* block is hashed into the cache prefix fingerprint. Editing the
* file invalidates the prefix; unchanged memory across sessions
* keeps the DeepSeek prefix cache warm. That matches Pillar 1 —
* memory is a deliberate, stable prefix, not per-turn drift.
* - Only one source: the working-root `REASONIX.md`. No parent walk,
* no `~/.reasonix/REASONIX.md`, no CLAUDE.md fallback. User-global
* memory can come later; for v1 one file == one mental model.
* - Truncated at 8 000 chars (≈ 2k tokens). `.gitignore` gets 2 000
* because it's a constraint dump; memory gets more headroom because
* it's deliberate instructions.
* - Opt-out via `REASONIX_MEMORY=off|false|0`. No CLI flag — memory
* is a file, `rm REASONIX.md` is the other opt-out.
*/
import { existsSync, readFileSync } from "node:fs";
import { join } from "node:path";
export const PROJECT_MEMORY_FILE = "REASONIX.md";
export const PROJECT_MEMORY_MAX_CHARS = 8000;
export interface ProjectMemory {
/** Absolute path the memory was read from. */
path: string;
/** Post-truncation content (may include a "… (truncated N chars)" marker). */
content: string;
/** Original byte length before truncation. */
originalChars: number;
/** True iff `originalChars > PROJECT_MEMORY_MAX_CHARS`. */
truncated: boolean;
}
/**
* Read `REASONIX.md` from `rootDir`. Returns `null` when the file is
* missing, unreadable, or empty (whitespace-only counts as empty — an
* empty memory file shouldn't perturb the cache prefix).
*/
export function readProjectMemory(rootDir: string): ProjectMemory | null {
const path = join(rootDir, PROJECT_MEMORY_FILE);
if (!existsSync(path)) return null;
let raw: string;
try {
raw = readFileSync(path, "utf8");
} catch {
return null;
}
const trimmed = raw.trim();
if (!trimmed) return null;
const originalChars = trimmed.length;
const truncated = originalChars > PROJECT_MEMORY_MAX_CHARS;
const content = truncated
? `${trimmed.slice(0, PROJECT_MEMORY_MAX_CHARS)}\n… (truncated ${
originalChars - PROJECT_MEMORY_MAX_CHARS
} chars)`
: trimmed;
return { path, content, originalChars, truncated };
}
/**
* Resolve whether project memory should be read. Default: on.
* `REASONIX_MEMORY=off|false|0` turns it off (CI, reproducing issues,
* intentional offline runs).
*/
export function memoryEnabled(): boolean {
const env = process.env.REASONIX_MEMORY;
if (env === "off" || env === "false" || env === "0") return false;
return true;
}
/**
* Return `basePrompt` with the project's `REASONIX.md` appended as a
* "Project memory" section. No-op when the file is absent, empty, or
* memory is disabled via env.
*
* The appended block is deterministic — identical input ⇒ identical
* output — so every session that opens against the same memory file
* gets the same prefix hash.
*/
export function applyProjectMemory(basePrompt: string, rootDir: string): string {
if (!memoryEnabled()) return basePrompt;
const mem = readProjectMemory(rootDir);
if (!mem) return basePrompt;
return `${basePrompt}
# Project memory (REASONIX.md)
The user pinned these notes about this project — treat them as authoritative context for every turn:
\`\`\`
${mem.content}
\`\`\`
`;
}
+61
View File
@@ -0,0 +1,61 @@
/**
* Reusable prompt fragments. Every rule that applies across multiple
* prompt surfaces (main agent + subagents + built-in skills) lives
* here so one edit covers every place the model learns the house
* style. The 4-copy formatting-rule drift that motivated this was a
* real bug: Unicode box-drawing warnings diverged between subagent
* prompts, and the main code prompt lacked them entirely even though
* its reply goes through the same markdown renderer.
*/
/**
* How replies get rendered. Matches behaviors the TUI's markdown
* pipeline (src/cli/ui/markdown.tsx) actually handles best.
* Embedded literally into prompts — no string interpolation, so it
* survives Reasonix's prefix-cache hashing unchanged across sessions.
*/
export const TUI_FORMATTING_RULES = `Formatting (rendered in a TUI with a real markdown renderer):
- Tabular data → GitHub-Flavored Markdown tables with ASCII pipes (\`| col | col |\` header + \`| --- | --- |\` separator). Never use Unicode box-drawing characters (│ ─ ┼ ┌ ┐ └ ┘ ├ ┤) — they look intentional but break terminal word-wrap and render as garbled columns at narrow widths.
- Keep table cells short (one phrase each). If a cell needs a paragraph, use bullets below the table instead.
- Code, file paths with line ranges, and shell commands → fenced code blocks (\`\`\`).
- Do NOT draw decorative frames around content with \`┌──┐ │ └──┘\` characters. The renderer adds its own borders; extra ASCII art adds noise and shatters at narrow widths.
- For flow charts and diagrams: a plain bullet list with \`→\` or \`↓\` between steps. Don't try to draw boxes-and-arrows in ASCII; it never survives word-wrap.`;
/**
* Self-report escalation contract — teaches the model (running on
* flash by default) how to ask for a retry on v4-pro. When Reasonix
* sees "<<<NEEDS_PRO>>>" as the first line of assistant output on
* flash, it aborts the call, upgrades this turn to pro, and re-issues
* the same messages. One retry per turn; pro never re-escalates.
*
* Why this exists: non-expert users can't reliably predict which
* tasks need the frontier tier, and reactive-only escalation (wait
* for flash to fail N times) wastes tokens + time. Letting the model
* self-assess catches hard tasks upfront when flash recognizes the
* difficulty — without silently auto-upgrading every prompt (which
* would destroy cost savings).
*
* Use sparingly: most coding tasks stay on flash. The escape hatch
* is for tasks where flash would otherwise emit a mediocre / guessed
* answer.
*/
export const ESCALATION_CONTRACT = `Cost-aware escalation (when you're running on deepseek-v4-flash):
If a task CLEARLY exceeds what flash can do well — complex cross-file architecture refactors, subtle concurrency / security / correctness invariants you can't resolve with confidence, or a design trade-off you'd be guessing at — output the exact string \`<<<NEEDS_PRO>>>\` as the FIRST line of your response (nothing before it, not even whitespace on a separate line). This aborts the current call and retries this turn on deepseek-v4-pro, one shot. Do NOT emit any other content in the same response when you request escalation.
Use this sparingly. Normal tasks — reading files, small edits, clear bug fixes, straightforward feature additions — stay on flash. Request escalation ONLY when you would otherwise produce a guess or a visibly-mediocre answer. If in doubt, attempt the task on flash first; the system also escalates automatically if you hit 3+ repair / SEARCH-mismatch errors in a single turn.`;
/**
* "Don't assert absence without checking." Subagents that run without
* this rule will confidently report "X is missing" based on their
* partial exploration, and the parent agent swallows it as fact. The
* main code prompt has its own, longer version of this — kept separate
* because the code agent is in a richer conversational frame.
*/
export const NEGATIVE_CLAIM_RULE = `Negative claims ("X is missing", "Y isn't implemented", "there's no Z") are the #1 hallucination shape. They feel safe to write because no citation seems possible — but that's exactly why you must NOT write them on instinct.
If you have a search tool (\`search_content\`, \`grep\`, web search), call it FIRST before asserting absence:
- Returns matches → you were wrong; correct yourself and cite the matches.
- Returns nothing → state the absence WITH the search query as evidence: \`No callers of \\\`foo()\\\` found (search_content "foo").\`
If you have no search tool, qualify hard: "I haven't verified — this is a guess." Never assert absence with fake authority.`;
+11
View File
@@ -46,6 +46,17 @@ export class ToolCallRepair {
this.storm = new StormBreaker(opts.stormWindow ?? 6, opts.stormThreshold ?? 3);
}
/**
* Drop the StormBreaker's sliding window of recent (name, args)
* signatures. Called at the start of every user turn — a fresh user
* message is a new intent, so carrying old repetition state into it
* would turn a valid "try again with different input" flow into a
* false-positive block.
*/
resetStorm(): void {
this.storm.reset();
}
process(
declaredCalls: ToolCall[],
reasoningContent: string | null,
+1
View File
@@ -170,6 +170,7 @@ function summarizeTurns(turns: TurnStats[]): SessionSummary {
savingsVsClaudePct: round(savingsVsClaude * 100, 2),
cacheHitRatio: round(cacheHitRatio, 4),
lastPromptTokens: lastTurn?.usage.promptTokens ?? 0,
lastTurnCostUsd: round(lastTurn?.cost ?? 0, 6),
};
}
+9
View File
@@ -107,6 +107,15 @@ export function deleteSession(name: string): boolean {
const path = sessionPath(name);
try {
unlinkSync(path);
// Best-effort cleanup of side-car files that belong to this session
// so `/forget` doesn't leave orphans in `sessionsDir()`. Currently
// just the pending-edits checkpoint (src/code/pending-edits.ts).
const sidecar = path.replace(/\.jsonl$/, ".pending.json");
try {
unlinkSync(sidecar);
} catch {
/* no sidecar present — expected for sessions without pending edits */
}
return true;
} catch {
return false;
+399
View File
@@ -0,0 +1,399 @@
/**
* Skills — user-defined prompt packs pinned (by name) into the
* immutable prefix and loaded (by body) on demand.
*
* Two scopes mirror the user-memory layout:
* - `project` → `<projectRoot>/.reasonix/skills/` (this repo only)
* - `global` → `~/.reasonix/skills/` (every session)
*
* Project scope wins on a name collision. Deliberately NOT tied to
* any specific client's directory convention (`.claude/`, `.glm/`,
* etc.) — Reasonix is model-agnostic at the conversation layer, so
* coupling the skill filesystem to one vendor would break any user
* running a different backend.
*
* Accepted file layouts (both emit the same `Skill`):
* - `{dir}/<name>/SKILL.md` (preferred — lets a skill bundle
* additional assets alongside)
* - `{dir}/<name>.md` (flat, one-file shorthand)
*
* Frontmatter keys we read:
* - `name` — optional, defaults to the file / dir name
* - `description` — one-line index description (REQUIRED for listing)
* - `allowed-tools` — parsed but UNUSED in v1 (see tools/skills.ts)
*
* Cache-First contract (Pillar 1):
* - The PREFIX sees only names + descriptions (one line each).
* - Bodies enter the APPEND-ONLY LOG lazily, via `run_skill` or
* `/skill <name>` — never the prefix. That keeps the prefix hash
* stable across skill additions to the body store.
*/
import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
import { homedir } from "node:os";
import { join, resolve } from "node:path";
import { NEGATIVE_CLAIM_RULE, TUI_FORMATTING_RULES } from "./prompt-fragments.js";
export const SKILLS_DIRNAME = "skills";
export const SKILL_FILE = "SKILL.md";
/** Cap on the pinned skills-index block, mirrors memory-index cap. */
export const SKILLS_INDEX_MAX_CHARS = 4000;
/** Skill identifier shape — alnum + `_` + `-` + interior `.`, 1-64 chars. */
const VALID_SKILL_NAME = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/;
export type SkillScope = "project" | "global" | "builtin";
/**
* Execution mode for a skill. `inline` (default) returns the body as a
* tool result so the body enters the parent's append-only log — the
* model continues the loop using the loaded instructions. `subagent`
* spawns an isolated child loop with the body as the system prompt and
* the user-supplied `arguments` as the task; only the child's final
* answer comes back. Use `subagent` for big-context exploration / research
* playbooks where the parent doesn't need to see the trail.
*/
export type SkillRunAs = "inline" | "subagent";
export interface Skill {
/** Canonical name — sanitized, matches the directory / filename stem. */
name: string;
/** One-line description shown in the pinned index. */
description: string;
/** Full markdown body (post-frontmatter). Loaded on demand. */
body: string;
/** Which scope this skill was loaded from. */
scope: SkillScope;
/** Absolute path to the SKILL.md (or {name}.md) file, or "(builtin)" for shipped defaults. */
path: string;
/** Raw `allowed-tools` field from frontmatter, if any. Unused in v1. */
allowedTools?: string;
/**
* Execution mode (frontmatter `runAs`). Defaults to `inline` for
* backwards compatibility with skills written before this field
* existed.
*/
runAs: SkillRunAs;
/**
* Frontmatter `model` — when set, overrides the default model the
* subagent runs on. Only meaningful when `runAs === "subagent"`.
* Accept any DeepSeek model id; the subagent layer falls back to its
* own default if this is missing or invalid.
*/
model?: string;
}
export interface SkillStoreOptions {
/** Override `$HOME` — tests point this at a tmpdir. */
homeDir?: string;
/**
* Absolute project root. Required to surface project-scope skills;
* omit (e.g. in `reasonix chat` without `code`) and the store only
* reads the global scope.
*/
projectRoot?: string;
/**
* Suppress the bundled built-in skills (`explore`, `research`).
* Used by unit tests that want to assert exact list contents
* without the +2 builtins distorting counts. Production callers
* leave this off so users always get the bundled defaults.
*/
disableBuiltins?: boolean;
}
/**
* Parse a `---` frontmatter block. Same minimal shape as user-memory:
* `key: value` lines, no quoting, no nesting. Returns `{}` data and the
* full input as body when no frontmatter fence is present — so hand-
* written files without frontmatter still surface (with empty desc).
*/
function parseFrontmatter(raw: string): { data: Record<string, string>; body: string } {
const lines = raw.split(/\r?\n/);
if (lines[0] !== "---") return { data: {}, body: raw };
const end = lines.indexOf("---", 1);
if (end < 0) return { data: {}, body: raw };
const data: Record<string, string> = {};
for (let i = 1; i < end; i++) {
const line = lines[i];
if (!line) continue;
const m = line.match(/^([a-zA-Z_][a-zA-Z0-9_-]*):\s*(.*)$/);
if (m?.[1]) data[m[1]] = (m[2] ?? "").trim();
}
return {
data,
body: lines
.slice(end + 1)
.join("\n")
.replace(/^\n+/, ""),
};
}
function isValidSkillName(name: string): boolean {
return VALID_SKILL_NAME.test(name);
}
export class SkillStore {
private readonly homeDir: string;
private readonly projectRoot: string | undefined;
private readonly disableBuiltins: boolean;
constructor(opts: SkillStoreOptions = {}) {
this.homeDir = opts.homeDir ?? homedir();
this.projectRoot = opts.projectRoot ? resolve(opts.projectRoot) : undefined;
this.disableBuiltins = opts.disableBuiltins === true;
}
/** True iff this store was configured with a project root. */
hasProjectScope(): boolean {
return this.projectRoot !== undefined;
}
/**
* Root directories scanned, in priority order. Project scope first
* so a per-repo skill overrides a global one with the same name —
* users expect the local copy to win when both exist.
*/
roots(): Array<{ dir: string; scope: SkillScope }> {
const out: Array<{ dir: string; scope: SkillScope }> = [];
if (this.projectRoot) {
out.push({
dir: join(this.projectRoot, ".reasonix", SKILLS_DIRNAME),
scope: "project",
});
}
out.push({ dir: join(this.homeDir, ".reasonix", SKILLS_DIRNAME), scope: "global" });
return out;
}
/**
* List every skill visible to this store. On name collisions the
* higher-priority root (project over global over builtin) wins.
* Sorted by name for stable prefix hashing.
*/
list(): Skill[] {
const byName = new Map<string, Skill>();
for (const { dir, scope } of this.roots()) {
if (!existsSync(dir)) continue;
let entries: import("node:fs").Dirent[];
try {
entries = readdirSync(dir, { withFileTypes: true });
} catch {
continue;
}
for (const entry of entries) {
const skill = this.readEntry(dir, scope, entry);
if (!skill) continue;
if (!byName.has(skill.name)) byName.set(skill.name, skill);
}
}
// Builtins are appended last so user/project files take precedence
// when names collide. The same priority you'd expect: my-project's
// "explore" overrides the shipped one without forcing a different
// name.
if (!this.disableBuiltins) {
for (const skill of BUILTIN_SKILLS) {
if (!byName.has(skill.name)) byName.set(skill.name, skill);
}
}
return [...byName.values()].sort((a, b) => a.name.localeCompare(b.name));
}
/** Resolve one skill by name. Returns `null` if not found or malformed. */
read(name: string): Skill | null {
if (!isValidSkillName(name)) return null;
for (const { dir, scope } of this.roots()) {
if (!existsSync(dir)) continue;
const dirCandidate = join(dir, name, SKILL_FILE);
if (existsSync(dirCandidate) && statSync(dirCandidate).isFile()) {
return this.parse(dirCandidate, name, scope);
}
const flatCandidate = join(dir, `${name}.md`);
if (existsSync(flatCandidate) && statSync(flatCandidate).isFile()) {
return this.parse(flatCandidate, name, scope);
}
}
// Fall back to builtins. Same precedence as `list()` — user-authored
// wins, builtins are the floor.
if (!this.disableBuiltins) {
for (const skill of BUILTIN_SKILLS) {
if (skill.name === name) return skill;
}
}
return null;
}
private readEntry(dir: string, scope: SkillScope, entry: import("node:fs").Dirent): Skill | null {
if (entry.isDirectory()) {
if (!isValidSkillName(entry.name)) return null;
const file = join(dir, entry.name, SKILL_FILE);
if (!existsSync(file)) return null;
return this.parse(file, entry.name, scope);
}
if (entry.isFile() && entry.name.endsWith(".md")) {
const stem = entry.name.slice(0, -3);
if (!isValidSkillName(stem)) return null;
return this.parse(join(dir, entry.name), stem, scope);
}
return null;
}
private parse(path: string, stem: string, scope: SkillScope): Skill | null {
let raw: string;
try {
raw = readFileSync(path, "utf8");
} catch {
return null;
}
const { data, body } = parseFrontmatter(raw);
const name = data.name && isValidSkillName(data.name) ? data.name : stem;
return {
name,
description: (data.description ?? "").trim(),
body: body.trim(),
scope,
path,
allowedTools: data["allowed-tools"],
runAs: parseRunAs(data.runAs),
model: data.model?.startsWith("deepseek-") ? data.model : undefined,
};
}
}
/**
* Coerce a frontmatter `runAs` string to the discriminated union. Any
* value other than the literal "subagent" is treated as inline — typos
* and unknown values default to the safe (non-spawning) mode rather
* than failing the load.
*/
function parseRunAs(raw: string | undefined): SkillRunAs {
return raw?.trim() === "subagent" ? "subagent" : "inline";
}
/**
* Build a single index line for one skill. Shape mirrors memory's
* `indexLine` — a bullet suitable for a markdown fenced block in the
* system prompt. Description is truncated to keep the full line under
* ~150 chars.
*
* Subagent-runAs skills carry a `[🧬 subagent]` tag AFTER the name
* so the model can't confuse the marker for part of the skill name.
* (Historical bug: when the marker led the name — `- 🧬 explore` —
* models would call `run_skill({ name: "🧬 explore" })` verbatim
* and fail lookup. Wrapping the marker in brackets AFTER the name
* eliminates that confusion; `run_skill`'s name arg also strips any
* leading non-word chars as a belt-and-suspenders measure.)
*/
function skillIndexLine(s: Pick<Skill, "name" | "description" | "runAs">): string {
const safeDesc = s.description.replace(/\n/g, " ").trim();
const tag = s.runAs === "subagent" ? " [🧬 subagent]" : "";
const max = 130 - s.name.length - tag.length;
const clipped = safeDesc.length > max ? `${safeDesc.slice(0, Math.max(1, max - 1))}…` : safeDesc;
return clipped ? `- ${s.name}${tag} — ${clipped}` : `- ${s.name}${tag}`;
}
/**
* Append a `# Skills` block to `basePrompt` listing every discovered
* skill (name + description only). Bodies are NOT inlined — that's the
* whole point: the prefix stays short and cacheable; full content loads
* on demand via `run_skill` or `/skill <name>`.
*
* Emits nothing when no skills are discovered — keeps the prefix hash
* stable for users who don't use skills at all.
*/
export function applySkillsIndex(basePrompt: string, opts: SkillStoreOptions = {}): string {
const store = new SkillStore(opts);
const skills = store.list().filter((s) => s.description);
if (skills.length === 0) return basePrompt;
const lines = skills.map(skillIndexLine);
const joined = lines.join("\n");
const truncated =
joined.length > SKILLS_INDEX_MAX_CHARS
? `${joined.slice(0, SKILLS_INDEX_MAX_CHARS)}\n… (truncated ${
joined.length - SKILLS_INDEX_MAX_CHARS
} chars)`
: joined;
return [
basePrompt,
"",
"# Skills — playbooks you can invoke",
"",
'One-liner index. Each entry is either a built-in or a user-authored playbook. Call `run_skill({ name: "<skill-name>", arguments: "<task>" })` — the `name` is JUST the skill identifier (e.g. `"explore"`), NOT the `[🧬 subagent]` tag that appears after it. Entries tagged `[🧬 subagent]` spawn an **isolated subagent** — its tool calls and reasoning never enter your context, only its final answer does. Use subagent skills for tasks that would otherwise flood your context (deep exploration, multi-step research, anything where you only need the conclusion). Plain skills are inlined: their body becomes a tool result you read and act on directly. The user can also invoke a skill via `/skill <name>`.',
"",
"```",
truncated,
"```",
].join("\n");
}
/**
* Built-in skills shipped with Reasonix. These are always available
* (no install step) and live as constants rather than files because:
* - Zero filesystem coupling — no copy-on-first-run dance, nothing
* to migrate when we update them.
* - They participate in the same `byName` priority as user/project
* skills: write `~/.reasonix/skills/explore.md` to override.
*
* Keep this list small and high-leverage. The bar for adding one: it
* demonstrates a pattern users would otherwise have to invent
* themselves, and the body fits in a screen.
*/
const BUILTIN_EXPLORE_BODY = `You are running as an exploration subagent. Your job is to investigate the codebase the parent agent pointed you at, then return one focused, distilled answer.
How to operate:
- Use read_file, search_files, search_content, directory_tree, list_directory, get_file_info as your primary tools. Stay read-only.
- For "find all places that call / reference / use X" questions, use \`search_content\` (content grep) — NOT \`search_files\` (which only matches file names). This is the most common subagent mistake; using the wrong tool gives empty results and you waste your iter budget chasing a phantom.
- Cast a wide net first (search_content for symbol references, directory_tree for structure) to map the territory; then read the 3-10 most relevant files in full.
- Don't read every file — be selective. Aim for breadth on the first pass, depth only where the question demands it.
- Stop exploring as soon as you can answer the question. The parent doesn't see your tool calls, so over-exploration is pure waste.
Your final answer:
- One paragraph (or a few short bullets). Lead with the conclusion.
- Cite specific file paths + line ranges when they support the answer.
- If the question can't be answered from what you found, say so plainly and suggest where to look next.
- No follow-up offers, no "let me know if you need more." The parent will ask again if they need more.
${NEGATIVE_CLAIM_RULE}
${TUI_FORMATTING_RULES}
The 'task' the parent gave you is the question you must answer. Treat any other reading of it as scope creep.`;
const BUILTIN_RESEARCH_BODY = `You are running as a research subagent. Your job is to gather information from code AND the web, synthesize it, and return one focused conclusion.
How to operate:
- Combine code reading (read_file, search_files) with web tools (web_search, web_fetch) as appropriate to the question.
- For "how does X work" / "is Y supported" questions: web first to find the canonical reference, then verify against the local code.
- For "what's our policy on Z" / "where do we use Q": local code first, web only if you need to compare against external standards.
- Cap yourself at ~10 tool calls. If you can't converge in 10, return what you have plus a note about what's missing.
Your final answer:
- One paragraph (or short bullets). Lead with the conclusion.
- Cite both code (file:line) AND web sources (URL) when they back the answer.
- Distinguish "I verified this in code" from "I read this on a docs page" — the parent will trust the former more.
- If the answer is uncertain, say so. Don't invent confidence.
${NEGATIVE_CLAIM_RULE}
${TUI_FORMATTING_RULES}
The 'task' the parent gave you is the research question. Stay on it.`;
const BUILTIN_SKILLS: readonly Skill[] = Object.freeze([
Object.freeze<Skill>({
name: "explore",
description:
"Explore the codebase in an isolated subagent — wide-net read-only investigation that returns one distilled answer. Best for: 'find all places that...', 'how does X work across the project', 'survey the code for Y'.",
body: BUILTIN_EXPLORE_BODY,
scope: "builtin",
path: "(builtin)",
runAs: "subagent",
}),
Object.freeze<Skill>({
name: "research",
description:
"Research a question by combining web search + code reading in an isolated subagent. Best for: 'is X feature supported by lib Y', 'what's the canonical way to do Z', 'compare our impl against the spec'.",
body: BUILTIN_RESEARCH_BODY,
scope: "builtin",
path: "(builtin)",
runAs: "subagent",
}),
]);
+45 -8
View File
@@ -1,12 +1,33 @@
import type { Usage } from "./client.js";
/** USD per 1M tokens. Update as DeepSeek pricing changes. */
/**
* USD per 1M tokens. Source: DeepSeek's CNY price sheet
* (https://api-docs.deepseek.com/zh-cn/quick_start/pricing) converted
* at a fixed 7.2 CNY/USD rate so billing stays stable across daily FX
* drift; revisit if the rate moves more than ±5%.
*
* 2026-04 V4 launch:
* - deepseek-v4-flash ¥0.2 / ¥1 / ¥2 (hit / miss / out per 1M)
* - deepseek-v4-pro ¥1 / ¥12 / ¥24
*
* deepseek-chat and deepseek-reasoner are now thin compat aliases for
* v4-flash's non-thinking and thinking modes respectively — same
* underlying model, same bill. We keep them in the table so existing
* sessions (and configs that hard-code these names) keep pricing.
*
* Historical note: sessions logged before this file was updated remain
* as-is in `~/.reasonix/usage.jsonl` — USD is frozen at record time,
* we never retroactively rewrite billing history.
*/
export const DEEPSEEK_PRICING: Record<
string,
{ inputCacheHit: number; inputCacheMiss: number; output: number }
> = {
"deepseek-chat": { inputCacheHit: 0.07, inputCacheMiss: 0.27, output: 1.1 },
"deepseek-reasoner": { inputCacheHit: 0.14, inputCacheMiss: 0.55, output: 2.19 },
"deepseek-v4-flash": { inputCacheHit: 0.028, inputCacheMiss: 0.139, output: 0.278 },
"deepseek-v4-pro": { inputCacheHit: 0.139, inputCacheMiss: 1.667, output: 3.333 },
// Compat aliases — priced as v4-flash per the deprecation notice.
"deepseek-chat": { inputCacheHit: 0.028, inputCacheMiss: 0.139, output: 0.278 },
"deepseek-reasoner": { inputCacheHit: 0.028, inputCacheMiss: 0.139, output: 0.278 },
};
/** Reference Claude Sonnet 4.6 pricing (USD per 1M tokens). */
@@ -14,13 +35,21 @@ export const CLAUDE_SONNET_PRICING = { input: 3.0, output: 15.0 };
/**
* Maximum prompt-side context window per DeepSeek model, in tokens.
* Both V3 (`deepseek-chat`) and R1 (`deepseek-reasoner`) currently expose
* a 131,072-token prompt limit per the OpenAPI spec; completion caps
* differ but don't affect the prompt budget the StatsPanel shows.
* V4 (flash + pro) jumps to 1,000,000 tokens. The compat aliases
* (deepseek-chat / deepseek-reasoner) inherit that through the
* v4-flash route — we bump them so the StatsPanel gauge reflects
* what the API actually accepts.
*
* Completion caps (e.g. 384K for V4) are enforced by the server, not
* tracked here — they don't affect the prompt-side budget the panel
* shows. If a future feature surfaces output-cap warnings we'll add
* a sibling table.
*/
export const DEEPSEEK_CONTEXT_TOKENS: Record<string, number> = {
"deepseek-chat": 131_072,
"deepseek-reasoner": 131_072,
"deepseek-v4-flash": 1_000_000,
"deepseek-v4-pro": 1_000_000,
"deepseek-chat": 1_000_000,
"deepseek-reasoner": 1_000_000,
};
/** Fallback when the caller's model id isn't in the table — safe lower bound. */
@@ -94,6 +123,13 @@ export interface SessionSummary {
* prompt + user delta + any new tool outputs).
*/
lastPromptTokens: number;
/**
* Most recent turn's USD cost. Complements `totalCostUsd` so the TUI
* can render "this turn: $X · session: $Y" — users asked for a
* per-turn signal so a mid-session jump from flash to pro is
* immediately visible, not hidden inside the session aggregate.
*/
lastTurnCostUsd: number;
}
export class SessionStats {
@@ -155,6 +191,7 @@ export class SessionStats {
savingsVsClaudePct: round(this.savingsVsClaude * 100, 2),
cacheHitRatio: round(this.aggregateCacheHitRatio, 4),
lastPromptTokens: last?.usage.promptTokens ?? 0,
lastTurnCostUsd: round(last?.cost ?? 0, 6),
};
}
}
+375
View File
@@ -0,0 +1,375 @@
/**
* Pure-TS port of DeepSeek's V3 tokenizer. Reads the slimmed+gzipped
* HuggingFace-format tokenizer data shipped at
* `data/deepseek-tokenizer.json.gz` and implements enough of the HF
* pipeline (Split pre-tokenizers → ByteLevel → BPE) to count tokens
* offline without pulling the `@lenml/tokenizers` or native Rust deps.
*
* Accuracy target: within ~3% of the API-returned `usage.prompt_tokens`
* for mixed CJK+English+code input. Exact-to-API match would also
* require replaying the Jinja chat template (role markers / tool call
* framing); we intentionally skip that — for a gauge/UI estimate the
* raw-text count is the useful number.
*
* Scope: ENCODE-SIDE ONLY. We don't need decode for counting; adding
* it later is trivial via the inverse byte-level table.
*/
import { existsSync, readFileSync } from "node:fs";
import { createRequire } from "node:module";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { gunzipSync } from "node:zlib";
interface AddedToken {
id: number;
content: string;
special: boolean;
normalized: boolean;
}
interface SplitPretokenizer {
type: "Split";
pattern: { Regex: string };
behavior: "Isolated" | "Removed" | string;
invert: boolean;
}
interface ByteLevelPretokenizer {
type: "ByteLevel";
add_prefix_space: boolean;
trim_offsets: boolean;
use_regex: boolean;
}
type Pretokenizer = SplitPretokenizer | ByteLevelPretokenizer;
interface TokenizerData {
added_tokens: AddedToken[];
pre_tokenizer: {
type: "Sequence";
pretokenizers: Pretokenizer[];
};
model: {
type: "BPE";
vocab: Record<string, number>;
merges: string[];
};
}
interface LoadedTokenizer {
vocab: Record<string, number>;
mergeRank: Map<string, number>;
splitRegexes: RegExp[];
byteToChar: string[];
/**
* Non-special added tokens (e.g. `<think>`, `<|fim▁hole|>`) that the
* HF tokenizer recognizes as atomic units when they appear inline in
* the text. Special tokens like `<|begin▁of▁sentence|>` are NOT in
* this list — the model ignores them when they appear in user text
* (the default HF `split_special_tokens=False` behavior), so we do
* the same: they get tokenized byte-by-byte, not as the special ID.
*/
addedPattern: RegExp | null;
addedMap: Map<string, number>;
}
/**
* GPT-2 byte-to-unicode mapping. Covers every byte 0..255 with a
* deterministic visible-printable unicode char — this is what lets the
* byte-level BPE show up in JSON vocabs as readable strings (`Ġ` for
* space, `Ċ` for `\n`, etc). Identical across every byte-level BPE
* tokenizer DeepSeek ships.
*/
function buildByteToChar(): string[] {
const result: string[] = new Array(256);
const bs: number[] = [];
for (let b = 33; b <= 126; b++) bs.push(b);
for (let b = 161; b <= 172; b++) bs.push(b);
for (let b = 174; b <= 255; b++) bs.push(b);
const cs = bs.slice();
let n = 0;
for (let b = 0; b < 256; b++) {
if (!bs.includes(b)) {
bs.push(b);
cs.push(256 + n);
n++;
}
}
for (let i = 0; i < bs.length; i++) {
result[bs[i]!] = String.fromCodePoint(cs[i]!);
}
return result;
}
let cached: LoadedTokenizer | null = null;
/**
* Find the bundled tokenizer data file. Resolution order (first hit wins):
* 1. `REASONIX_TOKENIZER_PATH` env var (tests / custom builds).
* 2. `../data/deepseek-tokenizer.json.gz` relative to this module —
* covers dev (src/tokenizer.ts → data/) AND production bundled at
* dist/index.js → dist/../data = data/.
* 3. `../../data/deepseek-tokenizer.json.gz` — covers the CLI bundle
* at dist/cli/index.js → dist/cli/../../data = data/. Without this
* step 2 resolves to dist/data/ which doesn't exist (the data file
* is shipped at package root per package.json `files` entry), and
* every step() preflight crashes the loop with ENOENT.
* 4. `require.resolve("reasonix/package.json")` — last-resort package
* root lookup for unusual bundlers.
*/
function resolveDataPath(): string {
if (process.env.REASONIX_TOKENIZER_PATH) return process.env.REASONIX_TOKENIZER_PATH;
const candidates: string[] = [];
try {
const here = dirname(fileURLToPath(import.meta.url));
candidates.push(join(here, "..", "data", "deepseek-tokenizer.json.gz"));
candidates.push(join(here, "..", "..", "data", "deepseek-tokenizer.json.gz"));
} catch {
/* import.meta.url unavailable — skip to the package resolution step. */
}
try {
const req = createRequire(import.meta.url);
candidates.push(
join(dirname(req.resolve("reasonix/package.json")), "data", "deepseek-tokenizer.json.gz"),
);
} catch {
/* Not installed as `reasonix/` — the earlier candidates still may hit. */
}
for (const p of candidates) {
if (existsSync(p)) return p;
}
// Nothing exists — return the first candidate anyway so readFileSync
// surfaces a concrete path in the ENOENT message (better than silent miss).
return candidates[0] ?? join(process.cwd(), "data", "deepseek-tokenizer.json.gz");
}
function loadTokenizer(): LoadedTokenizer {
if (cached) return cached;
const buf = readFileSync(resolveDataPath());
const json = gunzipSync(buf).toString("utf8");
const data = JSON.parse(json) as TokenizerData;
const mergeRank = new Map<string, number>();
for (let i = 0; i < data.model.merges.length; i++) {
mergeRank.set(data.model.merges[i]!, i);
}
const splitRegexes: RegExp[] = [];
for (const p of data.pre_tokenizer.pretokenizers) {
if (p.type === "Split") {
// All three Split rules use Isolated — matches become their own
// pre-tokens and so do the in-between stretches. The ByteLevel
// stage in the Sequence does no extra splitting here
// (use_regex:false), so our 3 Split regexes are the whole story.
splitRegexes.push(new RegExp(p.pattern.Regex, "gu"));
}
}
const addedMap = new Map<string, number>();
const addedContents: string[] = [];
for (const t of data.added_tokens) {
if (!t.special) {
addedMap.set(t.content, t.id);
addedContents.push(t.content);
}
}
// Longest-first ensures greedy matching doesn't lose a longer token
// to a shorter prefix (e.g. `<think>` before `<`).
addedContents.sort((a, b) => b.length - a.length);
const addedPattern = addedContents.length
? new RegExp(addedContents.map(escapeRegex).join("|"), "g")
: null;
cached = {
vocab: data.model.vocab,
mergeRank,
splitRegexes,
byteToChar: buildByteToChar(),
addedPattern,
addedMap,
};
return cached;
}
function escapeRegex(s: string): string {
return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
/**
* Apply one "Isolated" Split: the matches become their own pre-tokens,
* stretches between matches pass through unchanged. Empty pre-tokens
* are dropped so downstream stages don't see them.
*/
function applySplit(chunks: string[], re: RegExp): string[] {
const out: string[] = [];
for (const chunk of chunks) {
if (!chunk) continue;
// Reset lastIndex — reusing a /g regex across matchAll iterations
// is safe (matchAll internally advances), but across different
// input strings we want a clean start.
re.lastIndex = 0;
let last = 0;
for (const m of chunk.matchAll(re)) {
const idx = m.index ?? 0;
if (idx > last) out.push(chunk.slice(last, idx));
if (m[0].length > 0) out.push(m[0]);
last = idx + m[0].length;
}
if (last < chunk.length) out.push(chunk.slice(last));
}
return out;
}
/** UTF-8 bytes of `s`, each mapped to its byte-level visible char. */
function byteLevelEncode(s: string, byteToChar: string[]): string {
const bytes = new TextEncoder().encode(s);
let out = "";
for (let i = 0; i < bytes.length; i++) out += byteToChar[bytes[i]!];
return out;
}
/**
* Standard BPE merge loop. Starts from single byte-level chars and
* repeatedly applies the lowest-rank merge until none remain. O(n²)
* in chunk length, which is fine because chunks are ≤ a few hundred
* byte-level chars after pre-tokenization (and most are <50).
*/
function bpeEncode(piece: string, mergeRank: Map<string, number>): string[] {
if (piece.length <= 1) return piece ? [piece] : [];
let word: string[] = Array.from(piece);
while (true) {
let bestIdx = -1;
let bestRank = Number.POSITIVE_INFINITY;
for (let i = 0; i < word.length - 1; i++) {
const pair = `${word[i]} ${word[i + 1]}`;
const rank = mergeRank.get(pair);
if (rank !== undefined && rank < bestRank) {
bestRank = rank;
bestIdx = i;
if (rank === 0) break; // 0 is already the best possible
}
}
if (bestIdx < 0) break;
word = [
...word.slice(0, bestIdx),
word[bestIdx]! + word[bestIdx + 1]!,
...word.slice(bestIdx + 2),
];
if (word.length === 1) break;
}
return word;
}
/**
* Tokenize a UTF-8 string into DeepSeek token IDs. Mirrors the HF
* pipeline: (1) isolate non-special added tokens so they stay atomic,
* (2) for each in-between segment run the three Split regexes, (3)
* byte-level encode, (4) BPE merge, (5) look up vocab IDs.
*
* Not reentrancy-hazardous: loads a module-level singleton on first
* call and reuses it. Subsequent calls are pure compute.
*/
export function encode(text: string): number[] {
if (!text) return [];
const t = loadTokenizer();
const ids: number[] = [];
const process = (segment: string) => {
if (!segment) return;
let chunks: string[] = [segment];
for (const re of t.splitRegexes) chunks = applySplit(chunks, re);
for (const chunk of chunks) {
if (!chunk) continue;
const byteLevel = byteLevelEncode(chunk, t.byteToChar);
const pieces = bpeEncode(byteLevel, t.mergeRank);
for (const p of pieces) {
const id = t.vocab[p];
// If not in vocab we silently skip: shouldn't happen for
// byte-level BPE (every single byte has its own vocab entry),
// but if a future tokenizer update breaks that invariant we'd
// rather under-count than throw from a UI gauge.
if (id !== undefined) ids.push(id);
}
}
};
if (t.addedPattern) {
t.addedPattern.lastIndex = 0;
let last = 0;
for (const m of text.matchAll(t.addedPattern)) {
const idx = m.index ?? 0;
if (idx > last) process(text.slice(last, idx));
const id = t.addedMap.get(m[0]);
if (id !== undefined) ids.push(id);
last = idx + m[0].length;
}
if (last < text.length) process(text.slice(last));
} else {
process(text);
}
return ids;
}
/**
* Fast path for UI: we only need the count, not the IDs. Saves a
* per-call array allocation and lets callers batch large logs
* without holding the full ID stream.
*/
export function countTokens(text: string): number {
return encode(text).length;
}
/**
* Estimate the tokens a full conversation would cost. Sums raw-text
* counts for every message's content; we do NOT add overhead for the
* chat template's role markers (`<|User|>`, `<|Assistant|>`) because
* the exact framing varies between the chat/reasoner templates and
* DeepSeek applies them server-side anyway. Empirically adds ~3-6%
* to the real `prompt_tokens` — callers who care can post-multiply.
*/
export function estimateConversationTokens(
messages: Array<{ content?: string | null; tool_calls?: unknown }>,
): number {
let total = 0;
for (const m of messages) {
if (typeof m.content === "string" && m.content) {
total += countTokens(m.content);
}
// Tool-call arguments are serialized as JSON in the prompt by the
// chat template; their bytes WILL count upstream, so we count
// them too. Stringify-once is cheap relative to the tokenize.
if (m.tool_calls && Array.isArray(m.tool_calls) && m.tool_calls.length > 0) {
total += countTokens(JSON.stringify(m.tool_calls));
}
}
return total;
}
/**
* Estimate the tokens a full DeepSeek request would cost: the
* conversation-side tokens (what `estimateConversationTokens` already
* counts) PLUS the serialized tool-spec payload. Tool specs ride in
* their own JSON blob in the request body, not folded into any
* message's `content`, so they need a separate count to land an
* accurate preflight estimate.
*
* Returned number matches what `/context` displays for "next request"
* — reuse this helper anywhere (preflight guard, diagnostics, UI) to
* keep the two values from drifting.
*/
export function estimateRequestTokens(
messages: Array<{ content?: string | null; tool_calls?: unknown }>,
toolSpecs?: ReadonlyArray<unknown> | null,
): number {
let total = estimateConversationTokens(messages);
if (toolSpecs && toolSpecs.length > 0) {
total += countTokens(JSON.stringify(toolSpecs));
}
return total;
}
/** Exposed for tests — resets the lazy-load singleton. */
export function _resetForTests(): void {
cached = null;
}
+138 -3
View File
@@ -1,3 +1,4 @@
import { truncateForModel, truncateForModelByTokens } from "./mcp/registry.js";
import { analyzeSchema, flattenSchema, nestArguments } from "./repair/flatten.js";
import type { JSONSchema, ToolSpec } from "./types.js";
@@ -17,6 +18,25 @@ export interface ToolDefinition<A = any, R = any> {
name: string;
description?: string;
parameters?: JSONSchema;
/**
* Marks a tool as read-only: safe to invoke during plan mode. `true`
* for tools that only observe (read_file, list_directory, search, web
* fetch/search). Leave undefined / `false` for anything that can write,
* execute, or mutate state.
*
* The registry enforces this at dispatch: non-readonly tools called
* while `planMode` is on return a refusal string the model can
* learn from, instead of actually running.
*/
readOnly?: boolean;
/**
* Dynamic read-only check for tools whose safety depends on arguments
* — `run_command` with an allowlisted argv is safe, `run_command
* rm -rf` isn't. Called with the parsed arguments; `true` means "treat
* as read-only for plan mode". Takes precedence over `readOnly` when
* both are set.
*/
readOnlyCheck?: (args: A) => boolean;
fn: (args: A, ctx?: ToolCallContext) => R | Promise<R>;
}
@@ -39,14 +59,63 @@ export interface ToolRegistryOptions {
autoFlatten?: boolean;
}
/**
* Callback form for `setToolInterceptor` — receives the tool name and
* already-parsed arguments; returns a string to short-circuit dispatch
* (the returned value becomes the tool result the model sees), or
* `null` / `undefined` to fall through to the registered tool fn.
*
* Used by `reasonix code`'s edit-mode gate: `edit_file` / `write_file`
* are intercepted in "review" mode (queued into pendingEdits, returning
* "queued for /apply") or handled inline in "auto" mode (snapshot +
* apply, then surface an undo banner). Other tools pass through.
*/
export type ToolInterceptor = (
name: string,
args: Record<string, unknown>,
) => string | null | undefined | Promise<string | null | undefined>;
export class ToolRegistry {
private readonly _tools = new Map<string, InternalTool>();
private readonly _autoFlatten: boolean;
/**
* When true, `dispatch` refuses any tool whose `readOnly` flag isn't
* set (and whose `readOnlyCheck` doesn't pass on the specific args).
* Drives `reasonix code`'s Plan Mode — the model can still explore
* via read tools but its writes and non-allowlisted shell calls are
* bounced until the user approves a submitted plan.
*/
private _planMode = false;
/**
* Optional hook run after arg parsing but before tool.fn. Lets the TUI
* reroute specific tool calls (e.g. edit_file in review mode) without
* modifying the tool definitions themselves.
*/
private _interceptor: ToolInterceptor | null = null;
constructor(opts: ToolRegistryOptions = {}) {
this._autoFlatten = opts.autoFlatten !== false;
}
/** Enable / disable plan-mode enforcement at dispatch. */
setPlanMode(on: boolean): void {
this._planMode = Boolean(on);
}
/** True when the registry is currently refusing non-readonly calls. */
get planMode(): boolean {
return this._planMode;
}
/**
* Install or clear the dispatch interceptor. At most one interceptor
* is active at a time — calling twice replaces the previous. Pass
* `null` to remove.
*/
setToolInterceptor(fn: ToolInterceptor | null): void {
this._interceptor = fn;
}
register<A, R>(def: ToolDefinition<A, R>): this {
if (!def.name) throw new Error("tool requires a name");
const internal: InternalTool = { ...(def as ToolDefinition) };
@@ -91,7 +160,7 @@ export class ToolRegistry {
async dispatch(
name: string,
argumentsRaw: string | Record<string, unknown>,
opts: { signal?: AbortSignal } = {},
opts: { signal?: AbortSignal; maxResultChars?: number; maxResultTokens?: number } = {},
): Promise<string> {
const tool = this._tools.get(name);
if (!tool) {
@@ -120,17 +189,83 @@ export class ToolRegistry {
args = nestArguments(args);
}
// Plan-mode enforcement — runs AFTER arg parsing so a tool with a
// runtime `readOnlyCheck` can inspect the actual args (e.g.
// `run_command` is read-only iff the command matches its allowlist).
if (this._planMode && !isReadOnlyCall(tool, args)) {
return JSON.stringify({
error: `${name}: unavailable in plan mode — this is a read-only exploration phase. Use read_file / list_directory / search_files / directory_tree / web_search / allowlisted shell commands to investigate. Call submit_plan with your proposed plan when you're ready for the user's review.`,
});
}
// Interceptor runs after plan-mode (so a plan-mode refusal still
// wins) but before the real tool fn. A string return is treated as
// the full tool result; null / undefined means "not my concern,
// fall through." Uncaught throws from the interceptor are surfaced
// through the same error path as a failed tool fn below.
if (this._interceptor) {
try {
const short = await this._interceptor(name, args);
if (typeof short === "string") return short;
} catch (err) {
return JSON.stringify({
error: `${name}: interceptor failed — ${(err as Error).message}`,
});
}
}
try {
const result = await tool.fn(args, { signal: opts.signal });
return typeof result === "string" ? result : JSON.stringify(result);
const str = typeof result === "string" ? result : JSON.stringify(result);
// Pre-clip at dispatch so a single fat result can't balloon the
// log (and disk session file) on its way in. Healing at load time
// still catches pre-existing oversize entries; this closes the
// door on new ones.
//
// Two caps available: `maxResultTokens` (preferred — bounds the
// real context footprint, so CJK doesn't slip past at 2× density)
// and `maxResultChars` (legacy). If both are set, apply both and
// the tighter one wins; char-only callers keep their old behavior.
let clipped = str;
if (opts.maxResultTokens !== undefined) {
clipped = truncateForModelByTokens(clipped, opts.maxResultTokens);
}
if (opts.maxResultChars !== undefined) {
clipped = truncateForModel(clipped, opts.maxResultChars);
}
return clipped;
} catch (err) {
const e = err as Error & { toToolResult?: () => unknown };
// Errors may opt into a richer tool-result shape by implementing
// `toToolResult()`. Used by `PlanProposedError` to smuggle the
// submitted plan text out to the UI without stuffing it into the
// error message (which the dispatcher truncates at no fixed limit,
// but keeping payloads structured is cleaner for UI parsing).
if (typeof e.toToolResult === "function") {
try {
return JSON.stringify(e.toToolResult());
} catch {
/* fall through to the default shape */
}
}
return JSON.stringify({
error: `${(err as Error).name}: ${(err as Error).message}`,
error: `${e.name}: ${e.message}`,
});
}
}
}
function isReadOnlyCall(tool: InternalTool, args: Record<string, unknown>): boolean {
if (tool.readOnlyCheck) {
try {
return Boolean(tool.readOnlyCheck(args as never));
} catch {
return false;
}
}
return tool.readOnly === true;
}
function hasDotKey(obj: Record<string, unknown>): boolean {
for (const k of Object.keys(obj)) {
if (k.includes(".")) return true;
+369 -23
View File
@@ -48,6 +48,110 @@ export interface FilesystemToolsOptions {
const DEFAULT_MAX_READ_BYTES = 2 * 1024 * 1024;
const DEFAULT_MAX_LIST_BYTES = 256 * 1024;
/**
* When `read_file` is called without `head` / `tail` / `range`, files
* above this line count auto-trim to a head-plus-tail preview instead
* of dumping everything into the turn's context. Observed: five
* `read_file` calls in one session accounted for ~18K tokens (6.5K +
* 3.9K + 3.2K + 2.4K + 1.6K), a sizable chunk of the 27K total in
* tool results. Most of those reads wanted ~20 lines near one edit —
* the other 480 lines were inventory the model never cites.
*
* 200 is a deliberate middle ground: typical CLI / config / test
* files fit entirely; sprawling service files force the model to say
* what it actually wants (`range:"120-180"` or `search_content`).
*/
const DEFAULT_AUTO_PREVIEW_LINES = 200;
/**
* When auto-preview triggers, show this many lines at the top
* (structure / imports / public API) plus `AUTO_PREVIEW_TAIL_LINES`
* at the bottom (often the recently-edited tail).
*/
const AUTO_PREVIEW_HEAD_LINES = 80;
const AUTO_PREVIEW_TAIL_LINES = 40;
/**
* Directory names skipped by `search_content` unless `include_deps:true`
* is passed. The intent is "user is asking about THEIR code, not the
* libraries they depend on" — vendored / generated trees would otherwise
* dominate every match list. Pass include_deps when you genuinely need
* to grep a dependency.
*/
const SKIP_DIR_NAMES: ReadonlySet<string> = new Set([
"node_modules",
".git",
".hg",
".svn",
"dist",
"build",
"out",
".next",
".nuxt",
"target", // Rust / Java
".venv",
"venv",
"__pycache__",
".pytest_cache",
".mypy_cache",
".cache",
"coverage",
]);
/**
* Cheap binary-by-extension check for `search_content`. We err on the
* side of skipping so a NUL-byte content sniff is the second line of
* defense (handles e.g. a `.txt` that's actually a binary dump).
*/
const BINARY_EXTENSIONS: ReadonlySet<string> = new Set([
".png",
".jpg",
".jpeg",
".gif",
".bmp",
".ico",
".webp",
".tiff",
".pdf",
".zip",
".tar",
".gz",
".bz2",
".xz",
".7z",
".rar",
".exe",
".dll",
".so",
".dylib",
".bin",
".class",
".jar",
".war",
".o",
".obj",
".lib",
".a",
".woff",
".woff2",
".ttf",
".otf",
".eot",
".mp3",
".mp4",
".mov",
".avi",
".webm",
".wasm",
".pyc",
".pyo",
]);
function isLikelyBinaryByName(name: string): boolean {
const dot = name.lastIndexOf(".");
if (dot < 0) return false;
return BINARY_EXTENSIONS.has(name.slice(dot).toLowerCase());
}
export function registerFilesystemTools(
registry: ToolRegistry,
opts: FilesystemToolsOptions,
@@ -62,8 +166,22 @@ export function registerFilesystemTools(
if (typeof raw !== "string" || raw.length === 0) {
throw new Error("path must be a non-empty string");
}
// Interpret relative paths against rootDir (the session's scope).
const resolved = pathMod.resolve(rootDir, raw);
// Sandbox-root semantics: a leading POSIX-style `/` (or `\` on
// Windows) means "from the project root", not "from the filesystem
// root". Models routinely write `path: "/"` or `path: "/src/foo.ts"`
// intending the sandbox root — without this normalization,
// path.resolve interprets `/` as the actual drive root (`F:\` on
// Windows, `/` on POSIX) and the escape check rightly rejects it,
// confusing the model. Strip leading separators so the rest of the
// resolution treats the input as relative to rootDir. Drive-letter
// absolutes (`C:\foo`) and Unix absolutes outside rootDir still
// get caught by the relative-escape check below.
let normalized = raw;
while (normalized.startsWith("/") || normalized.startsWith("\\")) {
normalized = normalized.slice(1);
}
if (normalized.length === 0) normalized = ".";
const resolved = pathMod.resolve(rootDir, normalized);
const normRoot = pathMod.resolve(rootDir);
// Use relative() to catch any `..` segments that escape.
const rel = pathMod.relative(normRoot, resolved);
@@ -75,18 +193,27 @@ export function registerFilesystemTools(
registry.register({
name: "read_file",
description:
"Read a file under the sandbox root. Returns the full contents (truncated with a notice if larger than the per-call cap). Paths may be relative to the root or absolute-under-root.",
description: `Read a file under the sandbox root. To save context, PREFER to scope the read instead of pulling the whole file:
- head: N → first N lines (imports, public API, small configs)
- tail: N → last N lines (recently-added code, log tails)
- range: "A-B" → inclusive line range A..B, 1-indexed (e.g. "120-180" around an edit site)
When none of these is given AND the file is longer than ${DEFAULT_AUTO_PREVIEW_LINES} lines, the tool auto-returns a head+tail preview with an "N lines omitted" marker rather than dumping everything. If you need the middle, re-call with a range. Prefer search_content to locate a symbol first, then read_file with a range around the hit — one scoped read beats three full-file reads.`,
readOnly: true,
parameters: {
type: "object",
properties: {
path: { type: "string", description: "Path to read (relative to rootDir or absolute)." },
head: { type: "integer", description: "If set, return only the first N lines." },
tail: { type: "integer", description: "If set, return only the last N lines." },
range: {
type: "string",
description:
'Inclusive line range like "50-100" or "50-50". 1-indexed. Takes precedence over head/tail when all three are set. Out-of-range requests clamp to file bounds.',
},
},
required: ["path"],
},
fn: async (args: { path: string; head?: number; tail?: number }) => {
fn: async (args: { path: string; head?: number; tail?: number; range?: string }) => {
const abs = safePath(args.path);
const stat = await fs.stat(abs);
if (stat.isDirectory()) {
@@ -94,22 +221,64 @@ export function registerFilesystemTools(
}
const raw = await fs.readFile(abs);
if (raw.length > maxReadBytes) {
const head = raw.slice(0, maxReadBytes).toString("utf8");
return `${head}\n\n[…truncated ${raw.length - maxReadBytes} bytes — file is ${raw.length} B, cap ${maxReadBytes} B. Retry with head/tail for targeted view.]`;
const headBytes = raw.slice(0, maxReadBytes).toString("utf8");
return `${headBytes}\n\n[…truncated ${raw.length - maxReadBytes} bytes — file is ${raw.length} B, cap ${maxReadBytes} B. Retry with head/tail/range for targeted view.]`;
}
const text = raw.toString("utf8");
let lines = text.split(/\r?\n/);
// Most files end with '\n' which splits into an empty trailing
// entry; drop it so head/tail/range counts match the user's
// visible line numbers in an editor.
if (lines.length > 0 && lines[lines.length - 1] === "") lines = lines.slice(0, -1);
const totalLines = lines.length;
// range wins over head/tail when set — the most precise ask
// should dominate. Parse "A-B" strictly; bad formats fall through
// to head/tail / auto-preview instead of erroring.
if (typeof args.range === "string" && /^\d+\s*-\s*\d+$/.test(args.range)) {
const [rawStart, rawEnd] = args.range.split("-").map((s) => Number.parseInt(s, 10));
const start = Math.max(1, rawStart ?? 1);
const end = Math.min(totalLines, Math.max(start, rawEnd ?? totalLines));
const slice = lines.slice(start - 1, end);
const label = `[range ${start}-${end} of ${totalLines} lines]`;
return `${label}\n${slice.join("\n")}`;
}
if (typeof args.head === "number" && args.head > 0) {
return text.split(/\r?\n/).slice(0, args.head).join("\n");
const count = Math.min(args.head, totalLines);
const slice = lines.slice(0, count);
const marker =
count < totalLines
? `\n\n[…head ${count} of ${totalLines} lines — call again with range / tail for more]`
: "";
return slice.join("\n") + marker;
}
if (typeof args.tail === "number" && args.tail > 0) {
let lines = text.split(/\r?\n/);
// Most files end with a final '\n', which splits into an empty
// trailing string. Drop it before slicing so tail=2 returns the
// last two *real* lines, not "last line + empty".
if (lines.length > 0 && lines[lines.length - 1] === "") lines = lines.slice(0, -1);
return lines.slice(Math.max(0, lines.length - args.tail)).join("\n");
const count = Math.min(args.tail, totalLines);
const slice = lines.slice(totalLines - count);
const marker =
count < totalLines
? `[…tail ${count} of ${totalLines} lines — call again with range / head for more]\n\n`
: "";
return marker + slice.join("\n");
}
return text;
// No explicit scope + file is small → full content.
if (totalLines <= DEFAULT_AUTO_PREVIEW_LINES) return lines.join("\n");
// No explicit scope + file is large → head + tail preview plus
// a marker telling the model how much it missed and how to get
// it. This is the single biggest lever on read_file token cost —
// historically a 500-line file dumped ~4K tokens into the turn
// even when the model only needed 20 of them.
const head = lines.slice(0, AUTO_PREVIEW_HEAD_LINES).join("\n");
const tail = lines.slice(totalLines - AUTO_PREVIEW_TAIL_LINES).join("\n");
const omitted = totalLines - AUTO_PREVIEW_HEAD_LINES - AUTO_PREVIEW_TAIL_LINES;
return [
`[auto-preview: head ${AUTO_PREVIEW_HEAD_LINES} + tail ${AUTO_PREVIEW_TAIL_LINES} of ${totalLines} lines]`,
head,
`\n[… ${omitted} lines omitted — call read_file again with range:"A-B" (1-indexed) or head / tail to get the middle]\n`,
tail,
].join("\n");
},
});
@@ -117,6 +286,7 @@ export function registerFilesystemTools(
name: "list_directory",
description:
"List entries in a directory under the sandbox root. Returns one line per entry, marking directories with a trailing slash. Not recursive — use directory_tree for that.",
readOnly: true,
parameters: {
type: "object",
properties: {
@@ -136,21 +306,40 @@ export function registerFilesystemTools(
registry.register({
name: "directory_tree",
description:
"Recursively list entries in a directory. Shows indented tree structure with directories marked '/'. Caps output so a huge tree doesn't drown the context.",
description: `Recursively list entries in a directory. Shows indented tree structure with directories marked '/'. Budget-aware by default:
- maxDepth defaults to 2 (root + one level). A depth-4 tree on a real repo blew ~5K tokens in one call. If you truly need deeper, pass maxDepth:N explicitly.
- Skips ${[...SKIP_DIR_NAMES].sort().join(", ")} unless include_deps:true. Traversing into node_modules / .git / dist is almost always token-waste.
- Large subtrees (>50 children) auto-collapse to "[N files, M dirs hidden — list_directory <path> to inspect]" so one huge folder can't dominate the output.
Prefer \`list_directory\` for a single-level view, \`search_files\` to find specific paths, and \`search_content\` to find code.`,
readOnly: true,
parameters: {
type: "object",
properties: {
path: { type: "string", description: "Root of the tree (default: sandbox root)." },
maxDepth: { type: "integer", description: "Max recursion depth (default 4)." },
maxDepth: {
type: "integer",
description:
"Max recursion depth (default 2). Depth 0 shows only the top-level entries; depth 2 is usually enough to see module structure.",
},
include_deps: {
type: "boolean",
description:
"When true, also traverse node_modules / .git / dist / build / etc. Off by default — most exploration questions are about the user's own code.",
},
},
},
fn: async (args: { path?: string; maxDepth?: number }) => {
fn: async (args: { path?: string; maxDepth?: number; include_deps?: boolean }) => {
const startAbs = safePath(args.path ?? ".");
const maxDepth = typeof args.maxDepth === "number" ? args.maxDepth : 4;
const maxDepth = typeof args.maxDepth === "number" ? args.maxDepth : 2;
const includeDeps = args.include_deps === true;
const lines: string[] = [];
let totalBytes = 0;
let truncated = false;
// Per-directory child cap — long fixture / asset folders (200+
// snapshots) would otherwise dominate; the collapse keeps the
// overall shape visible. Modest: normal source dirs have <50
// entries.
const PER_DIR_CHILD_CAP = 50;
const walk = async (dir: string, depth: number): Promise<void> => {
if (truncated) return;
if (depth > maxDepth) return;
@@ -161,10 +350,31 @@ export function registerFilesystemTools(
return;
}
entries.sort((a, b) => a.name.localeCompare(b.name));
let emitted = 0;
for (const e of entries) {
if (truncated) return;
// Dep-skip applies only to DIRECTORIES (a file named
// "node_modules" is fine to list). Anything in the skip set
// still shows up as a single node with a trailing " (skipped)"
// hint so the model knows the dir exists but wasn't walked.
const skip = e.isDirectory() && !includeDeps && SKIP_DIR_NAMES.has(e.name);
if (emitted >= PER_DIR_CHILD_CAP) {
const remaining = entries.length - emitted;
let restFiles = 0;
let restDirs = 0;
for (const r of entries.slice(emitted)) {
if (r.isDirectory()) restDirs++;
else restFiles++;
}
const indent = " ".repeat(depth);
lines.push(
`${indent}[… ${remaining} entries hidden (${restDirs} dirs, ${restFiles} files) — list_directory on this path to see all]`,
);
return;
}
const indent = " ".repeat(depth);
const line = e.isDirectory() ? `${indent}${e.name}/` : `${indent}${e.name}`;
const suffix = skip ? " (skipped — pass include_deps:true to traverse)" : "";
const line = e.isDirectory() ? `${indent}${e.name}/${suffix}` : `${indent}${e.name}`;
totalBytes += line.length + 1;
if (totalBytes > maxListBytes) {
lines.push(` [… tree truncated at ${maxListBytes} bytes …]`);
@@ -172,7 +382,8 @@ export function registerFilesystemTools(
return;
}
lines.push(line);
if (e.isDirectory()) {
emitted++;
if (e.isDirectory() && !skip) {
await walk(pathMod.join(dir, e.name), depth + 1);
}
}
@@ -186,6 +397,7 @@ export function registerFilesystemTools(
name: "search_files",
description:
"Find files whose NAME matches a substring or regex. Case-insensitive. Walks the directory recursively under the sandbox root. Returns one path per line.",
readOnly: true,
parameters: {
type: "object",
properties: {
@@ -239,10 +451,144 @@ export function registerFilesystemTools(
},
});
registry.register({
name: "search_content",
description:
"Recursively grep file CONTENTS for a substring or regex. This is the right tool for 'find all places that call X', 'where is Y referenced', 'what files contain Z'. Different from search_files (which matches FILE NAMES). Returns one match per line in 'path:line: text' format. Skips dependency / VCS / build directories (node_modules, .git, dist, build, .next, target, .venv) and binary files by default.",
readOnly: true,
parameters: {
type: "object",
properties: {
pattern: {
type: "string",
description: "Substring (or regex) to search file contents for.",
},
path: {
type: "string",
description: "Directory to start the search at (default: sandbox root).",
},
glob: {
type: "string",
description:
"Optional file-name suffix or substring filter. Examples: '.ts' (only TypeScript), 'test' (any file with 'test' in the name). Reduces noise when you know the file shape.",
},
case_sensitive: {
type: "boolean",
description: "When true, match case exactly. Default false (case-insensitive).",
},
include_deps: {
type: "boolean",
description:
"When true, also search inside node_modules / .git / dist / build / etc. Off by default — most exploration questions are about the user's own code.",
},
},
required: ["pattern"],
},
fn: async (args: {
pattern: string;
path?: string;
glob?: string;
case_sensitive?: boolean;
include_deps?: boolean;
}) => {
const startAbs = safePath(args.path ?? ".");
const caseSensitive = args.case_sensitive === true;
const includeDeps = args.include_deps === true;
const nameFilter = typeof args.glob === "string" ? args.glob.toLowerCase() : null;
// Try the pattern as a regex first (lets the model say `\bdispatch\(`
// for a word-bounded match); fall back to literal substring on
// invalid regex. No `g` flag — we test once per line, so global
// statefulness (lastIndex tracking) would just be noise.
let re: RegExp | null = null;
try {
re = new RegExp(args.pattern, caseSensitive ? "" : "i");
} catch {
re = null;
}
const needle = caseSensitive ? args.pattern : args.pattern.toLowerCase();
const matches: string[] = [];
let totalBytes = 0;
let scanned = 0;
let truncated = false;
const walk = async (dir: string): Promise<void> => {
if (truncated) return;
let entries: import("node:fs").Dirent[];
try {
entries = await fs.readdir(dir, { withFileTypes: true });
} catch {
return;
}
for (const e of entries) {
if (truncated) return;
if (e.isDirectory()) {
if (!includeDeps && SKIP_DIR_NAMES.has(e.name)) continue;
await walk(pathMod.join(dir, e.name));
continue;
}
if (!e.isFile()) continue;
if (nameFilter && !e.name.toLowerCase().includes(nameFilter)) continue;
if (isLikelyBinaryByName(e.name)) continue;
const full = pathMod.join(dir, e.name);
let stat: import("node:fs").Stats;
try {
stat = await fs.stat(full);
} catch {
continue;
}
// Per-file size cap so a 50MB log doesn't dominate the search.
// Anything legitimately interesting fits in 2 MB; bigger files
// are usually data dumps or generated bundles.
if (stat.size > 2 * 1024 * 1024) continue;
let raw: Buffer;
try {
raw = await fs.readFile(full);
} catch {
continue;
}
// Content-based binary sniff: a NUL byte in the first 8KB is
// a strong indicator. Catches binaries with .json or .txt
// extensions (yes, this happens).
const firstNul = raw.indexOf(0);
if (firstNul !== -1 && firstNul < 8 * 1024) continue;
const text = raw.toString("utf8");
const rel = pathMod.relative(rootDir, full);
const lines = text.split(/\r?\n/);
for (let li = 0; li < lines.length; li++) {
const line = lines[li]!;
const lineForCheck = caseSensitive ? line : line.toLowerCase();
const hit = re ? re.test(line) : lineForCheck.includes(needle);
if (!hit) continue;
// Truncate very long lines so one giant minified file
// doesn't blow the budget on a single match.
const display = line.length > 200 ? `${line.slice(0, 200)}…` : line;
const out = `${rel}:${li + 1}: ${display}`;
if (totalBytes + out.length + 1 > maxListBytes) {
matches.push(`[… truncated at ${maxListBytes} bytes — refine pattern or path …]`);
truncated = true;
return;
}
matches.push(out);
totalBytes += out.length + 1;
}
scanned++;
}
};
await walk(startAbs);
if (matches.length === 0) {
return scanned === 0
? "(no files scanned — path empty or all files filtered out)"
: `(no matches across ${scanned} file${scanned === 1 ? "" : "s"})`;
}
return matches.join("\n");
},
});
registry.register({
name: "get_file_info",
description:
"Stat a path under the sandbox root. Returns type (file|directory|symlink), size in bytes, mtime in ISO-8601.",
readOnly: true,
parameters: {
type: "object",
properties: {
@@ -287,7 +633,7 @@ export function registerFilesystemTools(
registry.register({
name: "edit_file",
description:
"Apply a SEARCH/REPLACE edit to an existing file. `search` must match exactly (whitespace sensitive) — no regex. The match must be unique in the file; otherwise the edit is refused to avoid surprise rewrites. This flat-string shape replaces the `{oldText, newText}[]` JSON array form that previously triggered R1 DSML hallucinations.",
"Apply a SEARCH/REPLACE edit to an existing file. `search` must match exactly (whitespace sensitive) — no regex. The match must be unique in the file; otherwise the edit is refused to avoid surprise rewrites.",
parameters: {
type: "object",
properties: {
+470
View File
@@ -0,0 +1,470 @@
/**
* Long-running process registry — the "background run" counterpart to
* `run_command`. `run_command` spawns a child, waits for it to exit,
* then returns combined output; perfect for tests / builds / one-shots
* but useless for `npm run dev` / `python -m http.server` / watchers,
* which never exit and just time the tool out.
*
* JobRegistry lets the model fire-and-almost-forget: we spawn the
* child, wait at most `waitSec` (default 3s) OR until output matches
* a readiness regex, then return the startup preview plus a job id.
* The child keeps running in the background; later tool calls tail
* its output, stop it, or list what's still alive.
*
* Shape-wise this is modeled on Claude Code's `BashOutput` / `KillBash`
* pair. We diverge on one point: ready-signal detection is on by default
* because dev servers almost universally print "Local:", "listening on",
* "ready in N ms", "compiled successfully" when they come up — short-
* circuiting the wait on those keeps the model's first tool-result
* useful ("server is up at http://localhost:5173") instead of spending
* the full 3s on a stabilization timer.
*/
import { type ChildProcess, type SpawnOptions, spawn } from "node:child_process";
import * as pathMod from "node:path";
import { detectShellOperator, prepareSpawn, tokenizeCommand } from "./shell.js";
/**
* Kill an entire process tree rooted at `pid`.
*
* Why plain `child.kill(signal)` isn't enough:
* - Windows: Node maps signals to `TerminateProcess(handle)`, which
* only targets the direct child. `npm.cmd` spawned via cmd.exe
* launches `node`, which spawns Vite / Webpack / etc. Killing the
* npm wrapper leaves the whole JS server orphaned and still bound
* to the port. `taskkill /T /F /PID` walks the tree and terminates
* every descendant.
* - POSIX: a normal signal goes to the child process only. If we
* spawn with `detached:true` the child becomes a process-group
* leader; `process.kill(-pid, signal)` then reaches every process
* in that group, including grandchildren spawned after startup.
*
* Graceful vs forceful: SIGTERM gives the app a chance to cleanup; if
* it ignores the signal we follow up with SIGKILL after a grace window
* (handled by the caller, not here).
*/
function killProcessTree(pid: number, signal: "SIGTERM" | "SIGKILL"): void {
if (process.platform === "win32") {
// taskkill: /T = tree, /F = force (TerminateProcess, no cleanup).
// Graceful path still uses /F on Windows because there's no signal
// in the POSIX sense — the closest equivalent is Ctrl+Break, which
// is unreliable from another console. /F with /T is what most
// process managers ship on Windows.
const args = ["/pid", String(pid), "/T"];
if (signal === "SIGKILL") args.push("/F");
try {
const killer = spawn("taskkill", args, {
stdio: "ignore",
windowsHide: true,
});
// Swallow ENOENT / EACCES — we did our best. Not awaiting is
// intentional: taskkill can take a few hundred ms and the caller
// already has its own deadline.
killer.on("error", () => {
/* ignore */
});
} catch {
/* ignore */
}
return;
}
// POSIX: negative pid signals the whole process group. Requires the
// spawn to have been detached (which `start()` does below).
try {
process.kill(-pid, signal);
return;
} catch {
/* group-kill failed — fall back to direct */
}
try {
process.kill(pid, signal);
} catch {
/* ignore — already dead */
}
}
/** Per-job output ring. Capped so a chatty dev server doesn't OOM. */
const DEFAULT_OUTPUT_CAP_BYTES = 64 * 1024; // 64 KB
/**
* Regexes that signal "the server is up / the watcher has stabilized."
* Case-insensitive. Matched against the accumulated stdout+stderr; first
* hit cuts the startup wait short. Patterns are conservative — false
* positives waste nothing (we'd have returned at waitSec anyway), but
* a false negative costs the model a real stall.
*/
const READY_SIGNALS: ReadonlyArray<RegExp> = [
// HTTP server banners
/\blistening on\b/i,
/\blocal:\s+https?:\/\//i,
/\bhttps?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0)(?::\d+)?\b/i,
/\b(?:ready|server started|started server|app listening)\b/i,
// Bundlers / compilers
/\bcompiled successfully\b/i,
/\bbuild complete(?:d)?\b/i,
/\bwatching for (?:file )?changes\b/i,
/\bready in \d+/i,
// Generic
/\bstartup (?:complete|finished)\b/i,
];
export interface JobStartOptions {
/** Absolute path to cwd for the spawned child. */
cwd: string;
/**
* Max seconds to wait for the initial burst before returning. Capped
* at 30. A ready-signal match short-circuits this. Default 3.
*/
waitSec?: number;
/** Signal plumbed through from the calling tool's AbortSignal. */
signal?: AbortSignal;
/** Total per-job output buffer cap (bytes). Default 64 KB. */
maxBufferBytes?: number;
}
export interface JobStartResult {
jobId: number;
pid: number | null;
/** True iff the child was still running at the point we returned. */
stillRunning: boolean;
/** True iff a READY_SIGNALS pattern matched during the wait window. */
readyMatched: boolean;
/** Preview of combined stdout+stderr accumulated during the wait. */
preview: string;
/** If the child exited during the wait, its exit code; else null. */
exitCode: number | null;
}
export interface JobRecord {
id: number;
command: string;
pid: number | null;
startedAt: number;
/** Exit code once the process terminates; null while running. */
exitCode: number | null;
/** Combined stdout+stderr, ring-trimmed. */
output: string;
/**
* Total bytes ever written by the child (not just what's in `output`).
* Useful for "how much got dropped" diagnostics.
*/
totalBytesWritten: number;
/** True iff the child is still alive. */
running: boolean;
/** Error from spawn() itself (ENOENT, etc.) once surfaced. */
spawnError?: string;
}
export class JobRegistry {
private readonly jobs = new Map<number, InternalJob>();
private nextId = 1;
/**
* Spawn a background child. Resolves after `waitSec` OR on ready
* signal OR on early exit, whichever comes first. The child continues
* to run (and buffer output) regardless of which path fires.
*/
async start(command: string, opts: JobStartOptions): Promise<JobStartResult> {
const trimmed = command.trim();
if (!trimmed) throw new Error("run_background: empty command");
const op = detectShellOperator(trimmed);
if (op !== null) {
throw new Error(
`run_background: shell operator "${op}" is not supported — spawn one process per background job. Compose via your orchestration, not the shell.`,
);
}
const argv = tokenizeCommand(trimmed);
if (argv.length === 0) throw new Error("run_background: empty command");
const waitMs = Math.max(0, Math.min(30, opts.waitSec ?? 3)) * 1000;
const maxBytes = opts.maxBufferBytes ?? DEFAULT_OUTPUT_CAP_BYTES;
const { bin, args, spawnOverrides } = prepareSpawn(argv);
const spawnOpts: SpawnOptions = {
cwd: pathMod.resolve(opts.cwd),
shell: false,
windowsHide: true,
env: process.env,
// POSIX: detach so the child becomes its own process-group leader.
// Required for `process.kill(-pid, …)` later — without it a group
// kill fails and we end up only signaling the wrapper, leaving
// grandchildren (node → vite → esbuild …) orphaned.
// Windows: detached would spawn a new console window; leave the
// default and use taskkill /T for tree termination.
detached: process.platform !== "win32",
...spawnOverrides,
};
let child: ChildProcess;
try {
child = spawn(bin, args, spawnOpts);
} catch (err) {
// Can't even spawn — record a dead job so the model sees the
// failure in list_jobs, and return a synthetic result.
const id = this.nextId++;
const job: InternalJob = {
id,
command: trimmed,
pid: null,
startedAt: Date.now(),
exitCode: null,
output: `[spawn failed] ${(err as Error).message}`,
totalBytesWritten: 0,
running: false,
spawnError: (err as Error).message,
child: null,
readyPromise: Promise.resolve(),
signalReady: () => {},
};
this.jobs.set(id, job);
return {
jobId: id,
pid: null,
stillRunning: false,
readyMatched: false,
preview: job.output,
exitCode: null,
};
}
const id = this.nextId++;
let readyResolve: () => void = () => {};
const readyPromise = new Promise<void>((res) => {
readyResolve = res;
});
const job: InternalJob = {
id,
command: trimmed,
pid: child.pid ?? null,
startedAt: Date.now(),
exitCode: null,
output: "",
totalBytesWritten: 0,
running: true,
child,
readyPromise,
signalReady: readyResolve,
};
this.jobs.set(id, job);
let readyMatched = false;
const onData = (chunk: Buffer | string) => {
const s = chunk.toString();
job.totalBytesWritten += s.length;
job.output += s;
if (job.output.length > maxBytes) {
// Drop the oldest bytes, but keep a marker so the model can see
// output was truncated. Trim on a rough line boundary to avoid
// chopping a line mid-sentence.
const overflow = job.output.length - maxBytes;
const cut = job.output.indexOf("\n", overflow);
const start = cut >= 0 ? cut + 1 : overflow;
job.output = `[… older output dropped …]\n${job.output.slice(start)}`;
}
if (!readyMatched) {
for (const re of READY_SIGNALS) {
if (re.test(s) || re.test(job.output)) {
readyMatched = true;
job.signalReady();
break;
}
}
}
};
child.stdout?.on("data", onData);
child.stderr?.on("data", onData);
child.on("error", (err) => {
job.running = false;
job.spawnError = err.message;
job.signalReady();
});
child.on("close", (code) => {
job.running = false;
job.exitCode = code;
job.signalReady();
});
const onAbort = () => this.stop(id, { graceMs: 100 });
opts.signal?.addEventListener("abort", onAbort, { once: true });
// Race: (a) ready signal, (b) child exit, (c) wait deadline.
let timer: ReturnType<typeof setTimeout> | null = null;
await Promise.race([
readyPromise,
new Promise<void>((res) => {
timer = setTimeout(res, waitMs);
}),
]);
if (timer) clearTimeout(timer);
return {
jobId: id,
pid: job.pid,
stillRunning: job.running,
readyMatched,
preview: job.output,
exitCode: job.exitCode,
};
}
/**
* Read a job's accumulated output. `since` lets a caller poll
* incrementally: pass the byte count returned from the last call to
* get only newly-written content. Returns both full output and a
* running snapshot so the caller can use whichever.
*/
read(id: number, opts: { since?: number; tailLines?: number } = {}): JobReadResult | null {
const job = this.jobs.get(id);
if (!job) return null;
const full = job.output;
let slice = full;
if (typeof opts.since === "number" && opts.since >= 0 && opts.since < full.length) {
slice = full.slice(opts.since);
}
if (typeof opts.tailLines === "number" && opts.tailLines > 0) {
const lines = slice.split("\n");
const keep = lines.slice(Math.max(0, lines.length - opts.tailLines));
slice = keep.join("\n");
}
return {
output: slice,
byteLength: full.length,
running: job.running,
exitCode: job.exitCode,
command: job.command,
pid: job.pid,
spawnError: job.spawnError,
};
}
/**
* Send SIGTERM, wait `graceMs`, then SIGKILL if still alive. Returns
* the final job record (or null when the job id is unknown). Safe to
* call on an already-exited job — returns the record unchanged.
*/
async stop(id: number, opts: { graceMs?: number } = {}): Promise<JobRecord | null> {
const job = this.jobs.get(id);
if (!job) return null;
if (!job.running || !job.child) return snapshot(job);
const graceMs = Math.max(0, opts.graceMs ?? 2000);
// Tree kill — reaches grandchildren (vite, esbuild, etc.) instead
// of just the npm/cmd.exe wrapper that our direct child represents.
// Falls back to child.kill() only when we somehow don't have a pid.
if (job.pid !== null) {
killProcessTree(job.pid, "SIGTERM");
} else {
try {
job.child.kill("SIGTERM");
} catch {
/* already dead — fall through */
}
}
// Wait for the close event or graceMs, then SIGKILL.
await Promise.race([job.readyPromise, new Promise<void>((res) => setTimeout(res, graceMs))]);
if (job.running) {
if (job.pid !== null) {
killProcessTree(job.pid, "SIGKILL");
} else {
try {
job.child.kill("SIGKILL");
} catch {
/* ignore */
}
}
// Give the OS a moment to reap the tree so our exitCode field
// catches it before we return. Windows taskkill can take up to
// ~700ms to propagate on a three-level tree (npm → node → vite).
await new Promise<void>((res) => setTimeout(res, 800));
}
return snapshot(job);
}
list(): JobRecord[] {
return [...this.jobs.values()].map(snapshot);
}
/**
* Best-effort kill of every still-running job. Called on TUI shutdown
* so dev servers don't outlive the Reasonix process. Resolves after
* every child has closed or a hard deadline passes (3s total).
*/
async shutdown(deadlineMs = 5000): Promise<void> {
const start = Date.now();
const runningJobs = [...this.jobs.values()].filter((j) => j.running && j.child);
if (runningJobs.length === 0) return;
for (const job of runningJobs) {
if (job.pid !== null) killProcessTree(job.pid, "SIGTERM");
else
try {
job.child?.kill("SIGTERM");
} catch {
/* ignore */
}
}
const allClose = Promise.all(runningJobs.map((j) => j.readyPromise));
const elapsed = () => Date.now() - start;
// Grace window: give well-behaved apps time to clean up, capped at
// half the deadline so we always leave room for a SIGKILL pass +
// reap confirmation.
const graceMs = Math.min(1500, Math.max(0, deadlineMs / 2));
await Promise.race([allClose, new Promise<void>((res) => setTimeout(res, graceMs))]);
// Force-kill everything still alive.
for (const job of runningJobs) {
if (!job.running) continue;
if (job.pid !== null) killProcessTree(job.pid, "SIGKILL");
else
try {
job.child?.kill("SIGKILL");
} catch {
/* ignore */
}
}
// Wait for close events post-SIGKILL. taskkill /T on Windows is
// async — without this final wait, shutdown() can return while
// grandchildren are still mid-teardown, which is what "runningCount
// non-zero after shutdown" looks like.
const remaining = Math.max(800, deadlineMs - elapsed());
await Promise.race([allClose, new Promise<void>((res) => setTimeout(res, remaining))]);
}
/** Count of still-running jobs — drives the TUI status-bar indicator. */
runningCount(): number {
let n = 0;
for (const job of this.jobs.values()) if (job.running) n++;
return n;
}
}
interface InternalJob extends JobRecord {
/** Underlying Node child process. Null only on spawn failure. */
child: ChildProcess | null;
/** Resolved when ready-signal fires OR the child exits. */
readyPromise: Promise<void>;
/** Fires readyPromise — called by ready-signal OR close/error handlers. */
signalReady: () => void;
}
export interface JobReadResult {
output: string;
/** Total bytes ever in the buffer (pre-slice). Caller passes back as `since`. */
byteLength: number;
running: boolean;
exitCode: number | null;
command: string;
pid: number | null;
spawnError?: string;
}
function snapshot(job: InternalJob): JobRecord {
return {
id: job.id,
command: job.command,
pid: job.pid,
startedAt: job.startedAt,
exitCode: job.exitCode,
output: job.output,
totalBytesWritten: job.totalBytesWritten,
running: job.running,
spawnError: job.spawnError,
};
}
+180
View File
@@ -0,0 +1,180 @@
/**
* `remember` / `forget` / `recall_memory` — tools that let the model
* read and write the user-memory store across sessions.
*
* Scope rules:
* - `global` — always available (no sandbox needed).
* - `project` — requires a `projectRoot` on MemoryStore. In chat mode
* (no sandbox), the tools still register but a `scope=project` call
* returns a structured refusal so the model can try `global` instead.
*
* Memory changes are written eagerly but NOT re-loaded into the prefix
* mid-session (cache invariant). The user notices at `/new` or the next
* launch — or they can read fresh content via `recall_memory` which
* always hits disk.
*/
import type { ToolRegistry } from "../tools.js";
import {
type MemoryScope,
MemoryStore,
type MemoryType,
sanitizeMemoryName,
} from "../user-memory.js";
export interface MemoryToolsOptions {
/** Sandbox root for the `project` scope. Omit for chat mode. */
projectRoot?: string;
/** Override `~/.reasonix` (tests). */
homeDir?: string;
}
export function registerMemoryTools(
registry: ToolRegistry,
opts: MemoryToolsOptions = {},
): ToolRegistry {
const store = new MemoryStore({ homeDir: opts.homeDir, projectRoot: opts.projectRoot });
const hasProject = store.hasProjectScope();
registry.register({
name: "remember",
description:
"Save a memory for future sessions. Use when the user states a preference, corrects your approach, shares a non-obvious fact about this project, or explicitly asks you to remember something. Don't remember transient task state — only things worth recalling next session. The memory is written now but won't re-load into the system prompt until the next `/new` or launch.",
parameters: {
type: "object",
properties: {
type: {
type: "string",
enum: ["user", "feedback", "project", "reference"],
description:
"'user' = role/skills/prefs; 'feedback' = corrections or confirmed approaches; 'project' = facts/decisions about the current work; 'reference' = pointers to external systems the user uses.",
},
scope: {
type: "string",
enum: ["global", "project"],
description:
"'global' = applies across every project (preferences, tooling); 'project' = scoped to the current sandbox (decisions, local facts). Only available in `reasonix code`.",
},
name: {
type: "string",
description:
"filename-safe identifier, 3-40 chars, alnum + _ - . (no path separators, no leading dot).",
},
description: {
type: "string",
description: "One-line summary shown in MEMORY.md (under ~150 chars).",
},
content: {
type: "string",
description:
"Full memory body in markdown. For feedback/project types, structure as: rule/fact, then **Why:** line, then **How to apply:** line.",
},
},
required: ["type", "scope", "name", "description", "content"],
},
fn: async (args: {
type: MemoryType;
scope: MemoryScope;
name: string;
description: string;
content: string;
}) => {
if (args.scope === "project" && !hasProject) {
return JSON.stringify({
error:
"scope='project' is unavailable in this session (no sandbox root). Retry with scope='global', or ask the user to switch to `reasonix code` for project-scoped memory.",
});
}
try {
const path = store.write({
name: args.name,
type: args.type,
scope: args.scope,
description: args.description,
body: args.content,
});
const key = sanitizeMemoryName(args.name);
// The return text is load-bearing: it's the ONLY thing keeping
// the fact visible within the current session, because the
// prefix isn't re-hashed mid-session (Pillar 1). R1 reads this
// on its next turn — the wording is deliberately imperative so
// it doesn't get ignored in favor of explore-first behavior.
return [
`✓ REMEMBERED (${args.scope}/${key}): ${args.description}`,
"",
"TREAT THIS AS ESTABLISHED FACT for the rest of this session.",
"The user just told you — don't re-explore the filesystem to re-derive it.",
`(Saved to ${path}; pins into the system prompt on next /new or launch.)`,
].join("\n");
} catch (err) {
return JSON.stringify({ error: `remember failed: ${(err as Error).message}` });
}
},
});
registry.register({
name: "forget",
description:
"Delete a memory file and remove it from MEMORY.md. Use when the user explicitly asks to forget something, or when a previously-remembered fact has become wrong. Irreversible — no tombstone.",
parameters: {
type: "object",
properties: {
name: { type: "string", description: "Memory name (the identifier used in `remember`)." },
scope: { type: "string", enum: ["global", "project"] },
},
required: ["name", "scope"],
},
fn: async (args: { name: string; scope: MemoryScope }) => {
if (args.scope === "project" && !hasProject) {
return JSON.stringify({
error: "scope='project' is unavailable in this session (no sandbox root).",
});
}
try {
const existed = store.delete(args.scope, args.name);
return existed
? `forgot (${args.scope}/${sanitizeMemoryName(args.name)}). Re-load on next /new or launch.`
: `no such memory: ${args.scope}/${args.name} (nothing to forget).`;
} catch (err) {
return JSON.stringify({ error: `forget failed: ${(err as Error).message}` });
}
},
});
registry.register({
name: "recall_memory",
description:
"Read the full body of a memory file when its MEMORY.md one-liner (already in the system prompt) isn't enough detail. Most of the time the index suffices — only call this when the user's question genuinely requires the full context.",
readOnly: true,
parameters: {
type: "object",
properties: {
name: { type: "string" },
scope: { type: "string", enum: ["global", "project"] },
},
required: ["name", "scope"],
},
fn: async (args: { name: string; scope: MemoryScope }) => {
if (args.scope === "project" && !hasProject) {
return JSON.stringify({
error: "scope='project' is unavailable in this session (no sandbox root).",
});
}
try {
const entry = store.read(args.scope, args.name);
return [
`# ${entry.name} (${entry.scope}/${entry.type}, created ${entry.createdAt || "?"})`,
entry.description ? `> ${entry.description}` : "",
"",
entry.body,
]
.filter(Boolean)
.join("\n");
} catch (err) {
return JSON.stringify({ error: `recall failed: ${(err as Error).message}` });
}
},
});
return registry;
}
+101
View File
@@ -0,0 +1,101 @@
/**
* Plan Mode — read-only exploration phase for `reasonix code`.
*
* Shape (mirrors claude-code's plan/act split, adapted for Reasonix):
*
* 1. User types `/plan` → registry switches to plan-mode enforcement
* (write tools refused at dispatch; reads + allowlisted shell
* still work).
* 2. Model explores, then calls `submit_plan` with a markdown plan.
* 3. `submit_plan` throws `PlanProposedError`, which the TUI renders
* as a picker: Approve / Refine / Cancel.
* 4. Approve → registry leaves plan mode, a synthetic user message
* "The plan has been approved. Implement it now." is pushed into
* the loop so the next turn executes.
*
* The read-only enforcement lives in `ToolRegistry.dispatch` via
* `readOnly` / `readOnlyCheck`; this file only ships the `submit_plan`
* escape hatch and the error type that carries the plan out of the
* registry without stuffing it into the message.
*
* We do not change `ImmutablePrefix.toolSpecs` when plan mode toggles —
* that would break Pillar 1's prefix cache. Instead the same full spec
* list stays pinned, and the registry enforces mode at dispatch time.
* The refusal string teaches the model the rule; cache hits stay
* intact.
*/
import type { ToolRegistry } from "../tools.js";
/**
* Thrown by `submit_plan` when plan mode is active, carrying the plan
* text the TUI will render for the user's approval.
*
* Implements the `toToolResult` protocol so `ToolRegistry.dispatch`
* serializes the full plan into the tool-result JSON (not just the
* error message). The TUI parses `{ error, plan }` from the tool event
* and mounts the `PlanConfirm` picker.
*/
export class PlanProposedError extends Error {
readonly plan: string;
constructor(plan: string) {
super(
"PlanProposedError: plan submitted. STOP calling tools now — the TUI has shown the plan to the user. Wait for their next message; it will either approve (you'll then implement the plan), request a refinement (you should explore more and submit an updated plan), or cancel (drop the plan and ask what they want instead). Don't call any tools in the meantime.",
);
this.name = "PlanProposedError";
this.plan = plan;
}
/**
* Structured tool-result shape. Consumed by the TUI to extract the
* plan without regex-scraping the error message.
*/
toToolResult(): { error: string; plan: string } {
return { error: `${this.name}: ${this.message}`, plan: this.plan };
}
}
export interface PlanToolOptions {
/**
* Optional side-channel callback fired when the model submits a plan.
* The TUI uses this to preview the plan in real time (the tool-result
* event is also emitted; this is just earlier and friendlier to
* test harnesses that don't want to parse JSON).
*/
onPlanSubmitted?: (plan: string) => void;
}
export function registerPlanTool(registry: ToolRegistry, opts: PlanToolOptions = {}): ToolRegistry {
registry.register({
name: "submit_plan",
description:
"Submit a concrete plan to the user for review before executing. Use this for tasks that warrant a review gate — multi-file refactors, architecture changes, anything that would be expensive or confusing to undo. Skip it for small fixes (one-line typo, obvious bug with a clear fix) — just make the change. The user will either approve (you then implement it), ask for refinement, or cancel. If the user has already enabled /plan mode, writes are blocked at dispatch and you MUST use this. Write the plan as markdown with a one-line summary, a bulleted list of files to touch and what will change, and any risks or open questions.",
readOnly: true,
parameters: {
type: "object",
properties: {
plan: {
type: "string",
description:
"Markdown-formatted plan. Lead with a one-sentence summary. Then a file-by-file breakdown of what you'll change and why. Flag any risks or open questions at the end so the user can weigh in before you start.",
},
},
required: ["plan"],
},
fn: async (args: { plan: string }) => {
const plan = (args?.plan ?? "").trim();
if (!plan) {
throw new Error("submit_plan: empty plan — write a markdown plan and try again.");
}
// Always fire the picker, not just inside plan mode. Plan mode's
// role is the *stronger* constraint — it forces you into read-only
// until you submit. Outside plan mode, submit_plan is your own
// call: use it when the task is large enough to deserve a review
// gate (multi-file refactors, architecture changes, anything
// that would be expensive to undo), skip it for small fixes.
opts.onPlanSubmitted?.(plan);
throw new PlanProposedError(plan);
},
});
return registry;
}
+802
View File
@@ -0,0 +1,802 @@
/**
* Native shell tool — lets the model run commands inside the sandbox
* root so it can actually verify its own work (run tests, check git
* status, inspect a lockfile, etc.). Without this the coding-mode
* loop is "write code, hope it works, ask the user to run it" —
* defeats the purpose.
*
* Safety model:
* - Commands run with `cwd` pinned to the registered root. No
* path traversal via the command itself is enforced (users can
* `cat ../outside.txt`); the trust boundary is the directory
* you opened Reasonix from.
* - Commands are matched against a read-only / testing allowlist.
* Allowlisted commands execute immediately and return stdout +
* stderr merged. Everything else throws with a clear message —
* the UI translates that into an `/apply`-style confirm gate so
* the user sees the exact command before it runs.
* - Default timeout: 60s. Output cap: matches tool-result budget.
* - Every command that DOES run is spawned with `shell: false` and
* a tokenized argv — no string-to-shell interpolation, so the
* model can't accidentally construct a chained `rm` via quoting.
*
* This is intentionally narrower than what Claude Code / Aider ship:
* we gate more commands behind confirmation by default. Users who
* trust the model can widen the allowlist by instantiating their
* own tool registry.
*/
import { type SpawnOptions, spawn } from "node:child_process";
import { existsSync, statSync } from "node:fs";
import * as pathMod from "node:path";
import type { ToolRegistry } from "../tools.js";
import { JobRegistry } from "./jobs.js";
export interface ShellToolsOptions {
/** Directory to run commands in. Must be an absolute path. */
rootDir: string;
/** Seconds before an individual command is killed. Default: 60. */
timeoutSec?: number;
/**
* Per-command stdout+stderr cap in characters. Default: 32_000 to
* match the tool-result budget.
*/
maxOutputChars?: number;
/**
* Extra command-name prefixes the user explicitly trusts. Added on
* top of the built-in allowlist. Examples: `["my-ci-script", "lint"]`.
*
* Accepts either a fixed array (captured once at registration) or a
* getter called on every dispatch. The getter form is load-bearing:
* when the TUI's `ShellConfirm` writes a new prefix to config mid-
* session, the running `run_command` must pick it up immediately —
* otherwise the same command gets re-prompted until the next launch.
*/
extraAllowed?: readonly string[] | (() => readonly string[]);
/**
* When true, skip the allowlist entirely and auto-run every command.
* Off by default — this is an escape hatch for non-interactive use
* (CI, benchmarks) where a human can't be in the loop to confirm.
*/
allowAll?: boolean;
/**
* Background-process registry shared between `run_background`,
* `job_output`, `stop_job`, `list_jobs`, and the /jobs /kill slashes.
* When omitted, the registrar builds its own — but the caller
* usually wants to provide one so the TUI can tail it too.
*/
jobs?: JobRegistry;
}
const DEFAULT_TIMEOUT_SEC = 60;
const DEFAULT_MAX_OUTPUT_CHARS = 32_000;
/**
* Command prefixes we consider safe to run without asking the user.
* Rule of thumb: read-only reports, or test runners whose failure mode
* is "exit 1 with output." Nothing that can rewrite state, escalate,
* or touch the network.
*/
const BUILTIN_ALLOWLIST: ReadonlyArray<string> = [
// Repo inspection
"git status",
"git diff",
"git log",
"git show",
"git blame",
"git branch",
"git remote",
"git rev-parse",
"git config --get",
// Filesystem inspection
"ls",
"pwd",
"cat",
"head",
"tail",
"wc",
"file",
"tree",
"find",
"grep",
"rg",
// Language version probes
"node --version",
"node -v",
"npm --version",
"npx --version",
"python --version",
"python3 --version",
"cargo --version",
"go version",
"rustc --version",
"deno --version",
"bun --version",
// Test runners (non-destructive by convention)
"npm test",
"npm run test",
"npx vitest run",
"npx vitest",
"npx jest",
"pytest",
"python -m pytest",
"cargo test",
"cargo check",
"cargo clippy",
"go test",
"go vet",
"deno test",
"bun test",
// Linters / typecheckers (read-only by convention)
"npm run lint",
"npm run typecheck",
"npx tsc --noEmit",
"npx biome check",
"npx eslint",
"npx prettier --check",
"ruff",
"mypy",
];
/**
* Tokenize a shell-ish command string into argv. Handles single/double
* quoting; rejects unclosed quotes. Does NOT expand env vars, globs,
* backticks, or `$(…)` — the goal is to prevent the model from
* accidentally (or not) sneaking arbitrary shells past the allowlist
* via concatenation. Exported for testing.
*/
export function tokenizeCommand(cmd: string): string[] {
const out: string[] = [];
let cur = "";
let quote: '"' | "'" | null = null;
for (let i = 0; i < cmd.length; i++) {
const ch = cmd[i]!;
if (quote) {
if (ch === quote) {
quote = null;
} else if (ch === "\\" && quote === '"' && i + 1 < cmd.length) {
cur += cmd[++i];
} else {
cur += ch;
}
continue;
}
if (ch === '"' || ch === "'") {
quote = ch;
continue;
}
if (ch === " " || ch === "\t") {
if (cur.length > 0) {
out.push(cur);
cur = "";
}
continue;
}
cur += ch;
}
if (quote) throw new Error(`unclosed ${quote} in command`);
if (cur.length > 0) out.push(cur);
return out;
}
/**
* Scan `cmd` for a shell operator (`|`, `||`, `>`, `>>`, `<`, `<<`,
* `&`, `&&`, `2>`, `2>>`, `2>&1`, `&>`) that appears unquoted at a
* token boundary. Returns the operator string, or null if none.
*
* Why this exists: `run_command` documents "no shell expansion, no
* pipes, no redirects" (the tool spawns argv directly, not through a
* shell), but when the model writes `dir | findstr foo` the `|`
* survives tokenization as a standalone token and gets quoted as the
* literal string `"|"` by `quoteForCmdExe` — cmd.exe sees it as an
* argument, not an operator, so the pipe silently fails. Detecting
* operators up front lets us throw a clear error ("split into separate
* calls") instead of letting the command run with surprising results.
*
* Quoted operators (`grep "a|b"`) and operator characters embedded in
* larger tokens (`--flag=1&2`) are NOT flagged — those are literal
* argv bytes and are safe to pass through.
*
* Exported for testing.
*/
export function detectShellOperator(cmd: string): string | null {
const opPrefix = /^(?:2>&1|&>|\|{1,2}|&{1,2}|2>{1,2}|>{1,2}|<{1,2})/;
let cur = "";
let curQuoted = false;
let quote: '"' | "'" | null = null;
const check = (): string | null => {
if (cur.length === 0 && !curQuoted) return null;
if (!curQuoted) {
const m = opPrefix.exec(cur);
if (m) return m[0] ?? null;
}
return null;
};
for (let i = 0; i < cmd.length; i++) {
const ch = cmd[i]!;
if (quote) {
if (ch === quote) {
quote = null;
} else if (ch === "\\" && quote === '"' && i + 1 < cmd.length) {
cur += cmd[++i];
curQuoted = true;
} else {
cur += ch;
curQuoted = true;
}
continue;
}
if (ch === '"' || ch === "'") {
quote = ch;
curQuoted = true;
continue;
}
if (ch === " " || ch === "\t") {
const op = check();
if (op) return op;
cur = "";
curQuoted = false;
continue;
}
cur += ch;
}
if (quote) return null; // let tokenizeCommand throw the unclosed-quote error
return check();
}
/**
* Return true when `cmd` matches an allowlisted prefix. Exported for
* testing. Match is on the space-normalized leading tokens so
* `git status -s ` and `git status` both match `git status`.
*/
export function isAllowed(cmd: string, extra: readonly string[] = []): boolean {
const normalized = cmd.trim().replace(/\s+/g, " ");
const allowlist = [...BUILTIN_ALLOWLIST, ...extra];
for (const prefix of allowlist) {
if (normalized === prefix) return true;
if (normalized.startsWith(`${prefix} `)) return true;
}
return false;
}
export interface RunCommandResult {
exitCode: number | null;
/** Combined stdout+stderr, truncated to `maxOutputChars` with a marker. */
output: string;
/** True when the process was killed for exceeding `timeoutSec`. */
timedOut: boolean;
}
export async function runCommand(
cmd: string,
opts: {
cwd: string;
timeoutSec?: number;
maxOutputChars?: number;
signal?: AbortSignal;
},
): Promise<RunCommandResult> {
const argv = tokenizeCommand(cmd);
if (argv.length === 0) throw new Error("run_command: empty command");
const operator = detectShellOperator(cmd);
if (operator !== null) {
throw new Error(
`run_command: shell operator "${operator}" is not supported — this tool spawns one process, no shell expansion. Split into separate run_command calls and combine the output in your reasoning (e.g. instead of \`grep foo *.ts | wc -l\`, call \`grep -c foo *.ts\` or two separate commands). To pass "${operator}" as a literal argument, wrap it in quotes.`,
);
}
const timeoutMs = (opts.timeoutSec ?? DEFAULT_TIMEOUT_SEC) * 1000;
const maxChars = opts.maxOutputChars ?? DEFAULT_MAX_OUTPUT_CHARS;
const spawnOpts: SpawnOptions = {
cwd: opts.cwd,
shell: false, // no shell-expansion — see header comment
windowsHide: true,
env: process.env,
};
// Windows: two layered fixes on top of shell:false —
// 1. Resolve bare command names via PATH × PATHEXT (CreateProcess
// ignores PATHEXT, so `npm` alone misses `npm.cmd`).
// 2. Node 21.7.3+ (CVE-2024-27980) refuses to spawn `.cmd`/`.bat`
// directly even with shell:false and safe args — throws
// EINVAL at invocation time. Wrap those via `cmd.exe /d /s /c`
// with verbatim args + manual quoting, so shell metacharacters
// in arguments stay literal.
// Unix path is unchanged.
const { bin, args, spawnOverrides } = prepareSpawn(argv);
const effectiveSpawnOpts = { ...spawnOpts, ...spawnOverrides };
return await new Promise<RunCommandResult>((resolve, reject) => {
let child: import("node:child_process").ChildProcess;
try {
child = spawn(bin, args, effectiveSpawnOpts);
} catch (err) {
reject(err);
return;
}
let buf = "";
let timedOut = false;
const killTimer = setTimeout(() => {
timedOut = true;
child.kill("SIGKILL");
}, timeoutMs);
const onAbort = () => child.kill("SIGKILL");
opts.signal?.addEventListener("abort", onAbort, { once: true });
const onData = (chunk: Buffer | string) => {
buf += chunk.toString();
// Soft cap: we let the process keep running (killing early could
// hide a real failure), but we stop growing the buffer past 2×
// the cap so a chatty test can't OOM us.
if (buf.length > maxChars * 2) buf = `${buf.slice(0, maxChars * 2)}`;
};
child.stdout?.on("data", onData);
child.stderr?.on("data", onData);
child.on("error", (err) => {
clearTimeout(killTimer);
opts.signal?.removeEventListener("abort", onAbort);
reject(err);
});
child.on("close", (code) => {
clearTimeout(killTimer);
opts.signal?.removeEventListener("abort", onAbort);
const output =
buf.length > maxChars
? `${buf.slice(0, maxChars)}\n\n[… truncated ${buf.length - maxChars} chars …]`
: buf;
resolve({ exitCode: code, output, timedOut });
});
});
}
/**
* Test/override hooks for {@link resolveExecutable}. Omitting any field
* falls through to the real process globals — the runtime call path
* uses defaults; tests inject `platform` + `env` + `isFile` to exercise
* Windows-specific lookup from a Linux CI runner without touching
* actual fs.
*/
export interface ResolveExecutableOptions {
platform?: NodeJS.Platform;
env?: { PATH?: string; PATHEXT?: string };
/** Predicate swapped in by tests to avoid creating real files. */
isFile?: (path: string) => boolean;
/** Path.join used for the lookup. Defaults to Windows semantics on Windows. */
pathDelimiter?: string;
}
/**
* Resolve a bare command name (e.g. `npm`) to its on-disk path via
* PATH × PATHEXT on Windows. Returns the input unchanged on non-Windows
* platforms, when the input is already a path (contains `/`, `\`, or is
* absolute), or when no match is found in PATH × PATHEXT (caller gets a
* natural ENOENT from spawn, which surfaces cleanly).
*
* Why this exists: `child_process.spawn` with `shell: false` invokes
* Windows `CreateProcess`, which does not honor `PATHEXT` and does not
* search for `.cmd` / `.bat` wrappers. Node-ecosystem tools ship as
* `npm.cmd`, `npx.cmd`, `yarn.cmd`, etc., so a bare `npm` fails with
* ENOENT under `shell: false`. Flipping to `shell: true` would work
* but reintroduces shell-expansion (pipes, redirects, chained cmds)
* that the tool was explicitly designed to forbid. This resolver
* threads the needle.
*/
export function resolveExecutable(cmd: string, opts: ResolveExecutableOptions = {}): string {
const platform = opts.platform ?? process.platform;
if (platform !== "win32") return cmd;
if (!cmd) return cmd;
// Already a path fragment — spawn handles these natively.
if (cmd.includes("/") || cmd.includes("\\") || pathMod.isAbsolute(cmd)) return cmd;
// If the model wrote `npm.cmd` explicitly, respect that verbatim.
if (pathMod.extname(cmd)) return cmd;
const env = opts.env ?? process.env;
const pathExt = (env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD")
.split(";")
.map((e) => e.trim())
.filter(Boolean);
const delimiter = opts.pathDelimiter ?? (platform === "win32" ? ";" : pathMod.delimiter);
const pathDirs = (env.PATH ?? "").split(delimiter).filter(Boolean);
const isFile = opts.isFile ?? defaultIsFile;
for (const dir of pathDirs) {
for (const ext of pathExt) {
// Force win32 join so CI tests that pass `platform: "win32"`
// from a Linux runner get backslash-joined paths; the real-
// Windows runtime path lands here too and gets the correct
// separator regardless of where pathMod defaults.
const full = pathMod.win32.join(dir, cmd + ext);
if (isFile(full)) return full;
}
}
return cmd;
}
function defaultIsFile(full: string): boolean {
try {
return existsSync(full) && statSync(full).isFile();
} catch {
return false;
}
}
/**
* Prepare `(bin, args, spawnOpts)` for the runCommand spawn call,
* applying Windows-specific workarounds for (a) PATHEXT lookup and
* (b) the CVE-2024-27980 prohibition on direct `.cmd`/`.bat` spawns.
*
* Exported so tests can assert the transformation without booting an
* actual child process.
*/
export function prepareSpawn(
argv: readonly string[],
opts: ResolveExecutableOptions = {},
): { bin: string; args: string[]; spawnOverrides: SpawnOptions } {
const head = argv[0] ?? "";
const tail = argv.slice(1);
const platform = opts.platform ?? process.platform;
const resolved = resolveExecutable(head, opts);
if (platform !== "win32") {
return { bin: resolved, args: [...tail], spawnOverrides: {} };
}
// `.cmd` / `.bat` wrappers require cmd.exe on post-CVE Node.
if (/\.(cmd|bat)$/i.test(resolved)) {
const cmdline = [resolved, ...tail].map(quoteForCmdExe).join(" ");
return {
bin: "cmd.exe",
args: ["/d", "/s", "/c", withUtf8Codepage(cmdline)],
// windowsVerbatimArguments prevents Node from re-quoting the /c
// payload — we've already composed an exact cmd.exe command
// line. Without this Node wraps our already-quoted string in
// another round of quotes and cmd.exe can't parse it.
spawnOverrides: { windowsVerbatimArguments: true },
};
}
// Bare command names that PATH × PATHEXT couldn't resolve to an
// on-disk file — these are almost always cmd.exe built-ins (`dir`,
// `echo`, `type`, `ver`, `vol`, `where`, `help`, …) which don't
// exist as standalone executables. Direct spawn crashes with ENOENT;
// routing through cmd.exe lets the built-in resolve, and if it's
// genuinely unknown the user gets the standard "'foo' is not
// recognized" message instead of a raw spawn failure.
if (isBareWindowsName(resolved) && resolved === head) {
const cmdline = [head, ...tail].map(quoteForCmdExe).join(" ");
return {
bin: "cmd.exe",
args: ["/d", "/s", "/c", withUtf8Codepage(cmdline)],
spawnOverrides: { windowsVerbatimArguments: true },
};
}
// PowerShell variants: chcp 65001 doesn't help here because PowerShell
// sets its own [Console]::OutputEncoding at startup — usually system
// codepage (CP936/CP932/CP949 on CJK Windows) or UTF-16. The result
// is mojibake when our `chunk.toString()` UTF-8-decodes its stdout.
// Inject a UTF-8 setup prelude into the `-Command` (or `-c`) arg so
// any output produced thereafter is UTF-8.
if (isPowerShellExe(resolved)) {
const patched = injectPowerShellUtf8(tail);
if (patched) {
return { bin: resolved, args: patched, spawnOverrides: {} };
}
}
return { bin: resolved, args: [...tail], spawnOverrides: {} };
}
/** Resolved bin path looks like Windows PowerShell or PowerShell Core. */
function isPowerShellExe(resolved: string): boolean {
return /(?:^|[\\/])(?:powershell|pwsh)(?:\.exe)?$/i.test(resolved);
}
/**
* Locate `-Command` / `-c` in `args` and prepend the UTF-8 setup prelude
* to its value. Returns the patched args, or `null` when no `-Command`
* arg is present (in which case we leave the invocation untouched —
* inline-expression and script-file modes have their own conventions
* we don't want to silently rewrite).
*
* Why not always wrap: PowerShell's quoting semantics are finicky enough
* that adding a prelude to a script file invocation could break it.
* `-Command` is the case the model actually uses, and where mojibake
* matters; targeting just it keeps the blast radius small.
*
* Exported for tests.
*/
export function injectPowerShellUtf8(args: readonly string[]): string[] | null {
const prelude =
"[Console]::OutputEncoding=[System.Text.Encoding]::UTF8;$OutputEncoding=[System.Text.Encoding]::UTF8;";
for (let i = 0; i < args.length; i++) {
const a = args[i] ?? "";
if (/^-(?:Command|c)$/i.test(a) && i + 1 < args.length) {
const out = [...args];
out[i + 1] = `${prelude}${args[i + 1] ?? ""}`;
return out;
}
}
return null;
}
/**
* Prefix a cmd.exe command line with `chcp 65001 >nul &` so output
* (from cmd.exe and any child it spawns) is UTF-8-encoded. Without
* this, on Chinese / Japanese / Korean Windows, `dir`, `findstr`,
* `where`, etc. emit text in the system codepage (CP936, CP932,
* CP949, …) and `chunk.toString()` — which decodes as UTF-8 — produces
* garbled mojibake the model then sees as poisoned input on the next
* turn.
*
* Scope: chcp affects ONLY this cmd.exe instance, which exits after
* `/c`. No global console state changes. Single `&` (not `&&`) so the
* command still runs even on the rare Windows builds where chcp
* itself returns a non-zero exit (Win7 quirks; harmless on Win10+).
*
* Exported so tests can verify the wrapping shape.
*/
export function withUtf8Codepage(cmdline: string): string {
return `chcp 65001 >nul & ${cmdline}`;
}
/**
* True when `s` looks like a bare executable name — no path separator,
* no drive letter, no extension. Such names on Windows, when absent
* from PATH × PATHEXT, are almost always cmd.exe built-ins.
*/
function isBareWindowsName(s: string): boolean {
if (!s) return false;
if (s.includes("/") || s.includes("\\")) return false;
if (pathMod.isAbsolute(s)) return false;
if (pathMod.extname(s)) return false;
return true;
}
/**
* Quote an argument so cmd.exe parses it back as a single token. We
* always wrap in double quotes when the arg contains whitespace or
* any cmd.exe metacharacter, doubling embedded quotes per cmd.exe's
* `""` escape rule. Bare alphanumeric args pass through unquoted for
* readability in logs.
*
* Exported for test coverage of the quoting semantics.
*/
export function quoteForCmdExe(arg: string): string {
if (arg === "") return '""';
if (!/[\s"&|<>^%(),;!]/.test(arg)) return arg;
return `"${arg.replace(/"/g, '""')}"`;
}
/** Error thrown by `run_command` when the command isn't allowlisted. */
export class NeedsConfirmationError extends Error {
readonly command: string;
constructor(command: string) {
super(
`run_command: "${command}" needs the user's approval before it runs. STOP calling tools now — the TUI has already prompted the user to press y (run) or n (deny). Wait for their next message; it will either be the command's output (if they approved) or an instruction to continue without it (if they denied). Don't retry the command or call other shell commands in the meantime.`,
);
this.name = "NeedsConfirmationError";
this.command = command;
}
}
export function registerShellTools(registry: ToolRegistry, opts: ShellToolsOptions): ToolRegistry {
const rootDir = pathMod.resolve(opts.rootDir);
const timeoutSec = opts.timeoutSec ?? DEFAULT_TIMEOUT_SEC;
const maxOutputChars = opts.maxOutputChars ?? DEFAULT_MAX_OUTPUT_CHARS;
const jobs = opts.jobs ?? new JobRegistry();
// Resolved on every dispatch so newly-persisted "always allow"
// prefixes take effect inside the session that added them, not just
// on the next launch. Static arrays are wrapped into a constant
// getter so the call site below is uniform.
const getExtraAllowed: () => readonly string[] =
typeof opts.extraAllowed === "function"
? opts.extraAllowed
: (() => {
const snapshot = opts.extraAllowed ?? [];
return () => snapshot;
})();
const allowAll = opts.allowAll ?? false;
registry.register({
name: "run_command",
description:
"Run a shell command in the project root and return its combined stdout+stderr.\n\nConstraints (read these before the first call):\n• ONE process per call, NO shell expansion. `&&`, `||`, `|`, `;`, `>`, `<`, `2>&1` are all rejected up-front — split into separate calls and combine results in reasoning. Example: instead of `grep foo *.ts | wc -l`, use `grep -c foo *.ts`; instead of `cd sub && npm test`, use `npm test --prefix sub` (or whatever --cwd flag the binary accepts).\n• `cd` DOES NOT PERSIST between calls — each call spawns a fresh process rooted at the project. If a tool needs a subdirectory, pass it via the tool's own flag (`npm --prefix`, `cargo -C`, `git -C`, `pytest tests/…`), NOT via a preceding `cd`.\n• Avoid commands with unbounded output (`netstat -ano`, `find /`, etc.) — they waste tokens. Filter at source: `netstat -ano -p TCP`, `find src -name '*.ts'`, `grep -c`, `wc -l`.\n\nCommon read-only inspection and test/lint/typecheck commands run immediately; anything that could mutate state, install dependencies, or touch the network is refused until the user confirms it in the TUI. Prefer this over asking the user to run a command manually — after edits, run the project's tests to verify.",
// Plan-mode gate: allow allowlisted commands through (git status,
// cargo check, ls, grep …) so the model can actually investigate
// during planning. Anything that would otherwise trigger a
// confirmation prompt is treated as "not read-only" and bounced.
readOnlyCheck: (args: { command?: unknown }) => {
if (allowAll) return true;
const cmd = typeof args?.command === "string" ? args.command.trim() : "";
if (!cmd) return false;
return isAllowed(cmd, getExtraAllowed());
},
parameters: {
type: "object",
properties: {
command: {
type: "string",
description:
'Full command line. Tokenized with POSIX-ish quoting; no shell expansion. Pipes (`|`), redirects (`>`, `<`, `2>`), and `&&`/`||` chaining are rejected with an error — split into separate calls instead. To pass an operator character as a literal argument (e.g. a regex), wrap it in quotes: `grep "a|b" file.txt`.',
},
timeoutSec: {
type: "integer",
description: `Override the default ${timeoutSec}s timeout for a single command.`,
},
},
required: ["command"],
},
fn: async (args: { command: string; timeoutSec?: number }, ctx) => {
const cmd = args.command.trim();
if (!cmd) throw new Error("run_command: empty command");
if (!allowAll && !isAllowed(cmd, getExtraAllowed())) {
throw new NeedsConfirmationError(cmd);
}
const effectiveTimeout = Math.max(1, Math.min(600, args.timeoutSec ?? timeoutSec));
const result = await runCommand(cmd, {
cwd: rootDir,
timeoutSec: effectiveTimeout,
maxOutputChars,
signal: ctx?.signal,
});
return formatCommandResult(cmd, result);
},
});
registry.register({
name: "run_background",
description:
"Spawn a long-running process (dev server, watcher, any command that doesn't naturally exit) and detach. Waits up to `waitSec` seconds for startup (or until the output matches a readiness signal like 'Local:', 'listening on', 'compiled successfully'), then returns the job id + startup preview. The process keeps running; call `job_output` to tail its logs, `stop_job` to kill it, `list_jobs` to see all running jobs.\n\nSame shell constraints as run_command: NO `&&` / `||` / `|` / `;` / `>` / `<` / `2>&1`, `cd` doesn't persist. Dev servers that need a subdirectory: use the tool's own --prefix / --cwd flag. For Vite specifically, `--prefix` on npm only tells npm where package.json is; vite's server root still defaults to process cwd, so pass `vite <project-dir>` or configure via `vite.config.ts` root.\n\nUSE THIS — not `run_command` — for: npm/yarn/pnpm run dev, uvicorn / flask run, go run, cargo watch, tsc --watch, webpack serve, anything with 'dev' / 'serve' / 'watch' in the name.",
parameters: {
type: "object",
properties: {
command: {
type: "string",
description:
"Full command line. Same quoting rules as run_command (no pipes / redirects / chaining).",
},
waitSec: {
type: "integer",
description:
"Max seconds to wait for startup before returning. 0..30, default 3. A ready-signal match short-circuits this.",
},
},
required: ["command"],
},
fn: async (args: { command: string; waitSec?: number }, ctx) => {
const cmd = args.command.trim();
if (!cmd) throw new Error("run_background: empty command");
if (!allowAll && !isAllowed(cmd, getExtraAllowed())) {
throw new NeedsConfirmationError(cmd);
}
const result = await jobs.start(cmd, {
cwd: rootDir,
waitSec: args.waitSec,
signal: ctx?.signal,
});
return formatJobStart(result);
},
});
registry.register({
name: "job_output",
description:
"Read the latest output of a background job started with `run_background`. By default returns the tail of the buffer (last 80 lines). Pass `since` (the `byteLength` from a previous call) to stream only new content incrementally. Tells you whether the job is still running, so you can stop polling when it's done.",
readOnly: true,
parameters: {
type: "object",
properties: {
jobId: { type: "integer", description: "Job id returned by run_background." },
since: {
type: "integer",
description:
"Return only output written past this byte offset (for incremental polling).",
},
tailLines: {
type: "integer",
description: "Cap the returned slice to the last N lines. Default 80, 0 = unlimited.",
},
},
required: ["jobId"],
},
fn: async (args: { jobId: number; since?: number; tailLines?: number }) => {
const out = jobs.read(args.jobId, {
since: args.since,
tailLines: args.tailLines ?? 80,
});
if (!out) return `job ${args.jobId}: not found (use list_jobs)`;
return formatJobRead(args.jobId, out);
},
});
registry.register({
name: "stop_job",
description:
"Stop a background job started with `run_background`. SIGTERM first; SIGKILL after a short grace period if it doesn't exit cleanly. Returns the final output + exit code. Safe to call on an already-exited job.",
parameters: {
type: "object",
properties: {
jobId: { type: "integer" },
},
required: ["jobId"],
},
fn: async (args: { jobId: number }) => {
const rec = await jobs.stop(args.jobId);
if (!rec) return `job ${args.jobId}: not found`;
return formatJobStop(rec);
},
});
registry.register({
name: "list_jobs",
description:
"List every background job started this session — running and exited — with id, command, pid, status. Use when you've lost track of which job_id corresponds to which process, or to see what's still alive.",
readOnly: true,
parameters: { type: "object", properties: {} },
fn: async () => {
const all = jobs.list();
if (all.length === 0) return "(no background jobs started this session)";
return all.map(formatJobRow).join("\n");
},
});
return registry;
}
function formatJobStart(r: import("./jobs.js").JobStartResult): string {
const header = r.stillRunning
? `[job ${r.jobId} started · pid ${r.pid ?? "?"} · ${r.readyMatched ? "READY signal matched" : "running (no ready signal yet)"}]`
: r.exitCode !== null
? `[job ${r.jobId} exited during startup · exit ${r.exitCode}]`
: `[job ${r.jobId} failed to start]`;
return r.preview ? `${header}\n${r.preview}` : header;
}
function formatJobRead(jobId: number, r: import("./jobs.js").JobReadResult): string {
const status = r.running
? `running · pid ${r.pid ?? "?"}`
: r.exitCode !== null
? `exited ${r.exitCode}`
: r.spawnError
? `failed (${r.spawnError})`
: "stopped";
const header = `[job ${jobId} · ${status} · byteLength=${r.byteLength}]\n$ ${r.command}`;
return r.output ? `${header}\n${r.output}` : header;
}
function formatJobStop(r: import("./jobs.js").JobRecord): string {
const running = r.running
? "still running (SIGKILL may be pending)"
: `exit ${r.exitCode ?? "?"}`;
const tail = tailLines(r.output, 40);
const header = `[job ${r.id} stopped · ${running}]\n$ ${r.command}`;
return tail ? `${header}\n${tail}` : header;
}
function formatJobRow(r: import("./jobs.js").JobRecord): string {
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";
return ` ${String(r.id).padStart(3)} ${state.padEnd(24)} ${age}s ago $ ${r.command}`;
}
function tailLines(s: string, n: number): string {
if (!s) return "";
const lines = s.split("\n");
if (lines.length <= n) return s;
const dropped = lines.length - n;
return [`[… ${dropped} earlier lines …]`, ...lines.slice(-n)].join("\n");
}
export function formatCommandResult(cmd: string, r: RunCommandResult): string {
const header = r.timedOut
? `$ ${cmd}\n[killed after timeout]`
: `$ ${cmd}\n[exit ${r.exitCode ?? "?"}]`;
return r.output ? `${header}\n${r.output}` : header;
}
+165
View File
@@ -0,0 +1,165 @@
/**
* `run_skill` — invoke a user-authored playbook from the Skills index.
*
* Two execution modes, picked at registration time per skill via
* frontmatter `runAs`:
*
* - `inline` (default) — the skill body becomes the tool result and
* enters the parent's append-only log. The model reads the
* instructions and continues the normal loop, calling whatever
* tools the skill prescribes. Cheap, no isolation. Best for
* "load a checklist" / "load a coding style" / "load review
* criteria" patterns.
*
* - `subagent` — the skill body becomes the *system prompt* of an
* isolated child loop; the user-supplied `arguments` becomes the
* `task`. Only the child's final answer comes back as the tool
* result. Best for big-context exploration or research playbooks
* where the parent doesn't need to see the trail.
*
* Subagent dispatch is opt-in: callers must supply a `subagentRunner`
* at registration. When omitted (chat mode without a configured
* client), invoking a subagent skill returns a structured error
* instead of silently downgrading to inline — that would surprise the
* skill author.
*
* v1 deliberately ignores each skill's `allowed-tools` frontmatter:
* Reasonix's tool namespace doesn't align with Claude Code's so a
* literal pass would give wrong answers.
*/
import { type Skill, SkillStore } from "../skills.js";
import type { ToolRegistry } from "../tools.js";
/**
* Caller-supplied closure that knows how to spawn a subagent for the
* given resolved skill + task. Decoupled from `registerSkillTools` so
* the skills tool doesn't need to know about DeepSeekClient or the
* parent ToolRegistry — the App / library wiring assembles those once
* and hands in this function.
*
* Returns the JSON tool-result string verbatim (already serialized via
* `formatSubagentResult`), so the dispatch path is pure pass-through.
*/
export type SubagentRunner = (skill: Skill, task: string) => Promise<string>;
export interface SkillToolsOptions {
/** Override `$HOME` — tests set this to a tmpdir. */
homeDir?: string;
/**
* Absolute project root — enables discovery of project-scope skills
* under `<projectRoot>/.reasonix/skills/`. Omit for chat mode (global
* scope only).
*/
projectRoot?: string;
/**
* Closure that spawns a subagent for `runAs: subagent` skills. When
* omitted, invoking a subagent skill returns an error directing the
* user to wire up the runner — silent fallback to inline would be
* worse, since the skill author wrote the body assuming isolation.
*/
subagentRunner?: SubagentRunner;
/** Hide built-in skills (test-only knob; production callers leave off). */
disableBuiltins?: boolean;
}
export function registerSkillTools(
registry: ToolRegistry,
opts: SkillToolsOptions = {},
): ToolRegistry {
const store = new SkillStore({
homeDir: opts.homeDir,
projectRoot: opts.projectRoot,
disableBuiltins: opts.disableBuiltins,
});
const subagentRunner = opts.subagentRunner;
registry.register({
name: "run_skill",
description:
"Invoke a playbook from the Skills index pinned in the system prompt. Each entry is a self-contained instruction block. Pass `name` as the BARE skill identifier (e.g. 'explore'), NOT the `[🧬 subagent]` tag that appears after it in the index. Entries tagged `[🧬 subagent]` spawn an isolated subagent — only the final distilled answer comes back, the model's tool calls + reasoning during the run never enter your context. Plain skills are inlined: the body becomes a tool result you read and follow. For subagent skills, supply 'arguments' describing the concrete task — they'll be the only context the subagent has.",
readOnly: true,
parameters: {
type: "object",
properties: {
name: {
type: "string",
description:
"Skill identifier as it appears in the pinned Skills index (e.g. 'explore', 'review', 'security-review'). Case-sensitive.",
},
arguments: {
type: "string",
description:
"Free-form arguments the skill should act on. For inline skills: appended to the body as an 'Arguments:' line; the skill's own instructions decide how to consume them. For `[🧬 subagent]` skills: REQUIRED — becomes the entire task description the subagent receives, since it has no other context.",
},
},
required: ["name"],
},
fn: async (args: { name?: unknown; arguments?: unknown }) => {
const raw = typeof args.name === "string" ? args.name.trim() : "";
if (!raw) {
return JSON.stringify({ error: "run_skill requires a 'name' argument" });
}
// Defensive: The Skills index writes entries like
// `explore [🧬 subagent]`, and models sometimes copy the
// decoration verbatim into the `name` argument instead of just
// the identifier. Rather than reject those calls:
// 1. Drop any `[...]` bracketed tag (possibly containing
// emoji + "subagent" label).
// 2. Find the first whitespace-delimited token whose first
// char is alphanumeric — that's the skill identifier,
// whether the tag came before or after the name.
const stripped = raw.replace(/\[[^\]]*\]/g, " ").trim();
const tokens = stripped.split(/\s+/).filter(Boolean);
const name = tokens.find((t) => /^[a-zA-Z0-9]/.test(t)) ?? "";
if (!name) {
return JSON.stringify({
error: "run_skill requires a 'name' argument",
hint: `'${raw}' is just a marker/tag, not a skill name`,
});
}
const skill = store.read(name);
if (!skill) {
const available = store
.list()
.map((s) => s.name)
.join(", ");
return JSON.stringify({
error: `unknown skill: ${JSON.stringify(name)}`,
available: available || "(none — user has not defined any skills)",
});
}
const rawArgs = typeof args.arguments === "string" ? args.arguments.trim() : "";
if (skill.runAs === "subagent") {
if (!subagentRunner) {
return JSON.stringify({
error: `run_skill: skill ${JSON.stringify(name)} is marked runAs=subagent but no subagent runner is configured for this session. Skill authors who need isolation should run inside reasonix code (or a library setup that passes subagentRunner to registerSkillTools).`,
});
}
if (!rawArgs) {
return JSON.stringify({
error: `run_skill: skill ${JSON.stringify(name)} is a subagent and requires 'arguments' — the subagent has no other context, so describe the concrete task in the arguments field.`,
});
}
return subagentRunner(skill, rawArgs);
}
// inline path — body becomes the tool result.
const header = [
`# Skill: ${skill.name}`,
skill.description ? `> ${skill.description}` : "",
`(scope: ${skill.scope} · ${skill.path})`,
]
.filter(Boolean)
.join("\n");
const argsBlock = rawArgs ? `\n\nArguments: ${rawArgs}` : "";
// The body is handed to the model verbatim. No truncation — the
// user authored it, we trust their length choice. The append-only
// log pays the token cost exactly once per invocation.
return `${header}\n\n${skill.body}${argsBlock}`;
},
});
return registry;
}
+508
View File
@@ -0,0 +1,508 @@
/**
* Subagent runtime — isolated child loops for offloading exploration or
* self-contained subtasks.
*
* Two surfaces sit on top of the same `spawnSubagent` core:
*
* 1. `registerSubagentTool` — exposes a low-level `spawn_subagent`
* function-call tool. Library API. NOT registered into the model
* tool list by `reasonix code` since 0.4.26 — Skills (with
* `runAs: subagent` frontmatter) became the user-facing surface.
* Kept exported because library callers and tests still want
* direct access to the primitive.
*
* 2. `run_skill` (in src/tools/skills.ts) — when the resolved skill
* has `runAs: subagent`, it calls `spawnSubagent` with the skill
* body as the system prompt and the user's `arguments` as the
* task. Subagent skills are listed in the pinned Skills index
* with a 🧬 marker, which gives the model a clear pattern-match
* trigger without forcing it to reason about "is this task big
* enough to delegate."
*
* Why R1 specifically benefits:
* - R1 reasoning tokens are expensive AND inflate the parent context.
* A subagent runs its own private loop, then surfaces only the
* distilled final answer back to the parent — the main session
* never sees the reasoning trail.
*
* Invariants common to both surfaces:
* - Serial only — no parallel spawn (MVP).
* - Inherits parent's tool registry MINUS `spawn_subagent` itself
* (no recursion via the tool API) and MINUS `submit_plan`
* (subagents don't propose plans to the user).
* - No hooks, no session — runs are ephemeral.
* - Lower default `maxToolIters` than the parent (16 vs 64).
* - Independent prefix cache (subagent's prefix has its own
* fingerprint).
* - Parent registry's plan-mode state propagates: subagents can't
* escape `/plan`.
* - Non-streaming child loop — the parent isn't watching deltas, so
* streaming would only add an SSE parser to the critical path.
* Cancellation still works via the AbortSignal.
*/
import { type DeepSeekClient, Usage } from "../client.js";
import { CacheFirstLoop } from "../loop.js";
import { ImmutablePrefix } from "../memory.js";
import { applyProjectMemory } from "../project-memory.js";
import {
ESCALATION_CONTRACT,
NEGATIVE_CLAIM_RULE,
TUI_FORMATTING_RULES,
} from "../prompt-fragments.js";
import { ToolRegistry } from "../tools.js";
/**
* Live event emitted by a running subagent. Surfaced via the optional
* `sink` ref the TUI attaches its handler to. Side-channel only — these
* events do NOT pass through the parent loop's `LoopEvent` stream
* because subagents run inside a tool-dispatch frame, after the parent's
* `step()` has already yielded `tool_start` and is awaiting the result.
*/
export interface SubagentEvent {
kind: "start" | "progress" | "end";
/** First ~30 chars of the task prompt — used for the TUI status row. */
task: string;
/** Skill that spawned this subagent, when applicable. Stamped on every event so the TUI/logger can attribute without extra plumbing. */
skillName?: string;
/** Model id the child loop ran on. Stamped alongside skillName. */
model?: string;
/** Iteration count inside the child loop (number of tool results so far). */
iter?: number;
/** Wall-clock ms since the subagent started. */
elapsedMs?: number;
/** First ~120 chars of the final assistant message. Set on `end`. */
summary?: string;
/** Error message if the subagent failed. Set on `end`. */
error?: string;
/** Total turns the subagent took. Set on `end`. */
turns?: number;
/** Total USD spent inside the child loop. Set on `end`. */
costUsd?: number;
/** Aggregated child-loop Usage (sum across turns). Set on `end`. */
usage?: Usage;
}
/**
* Mutable ref the registration writes through. The TUI sets `.current`
* to its own handler on mount; nothing receives events before that
* happens (and headless callers leave `.current = null`, which is the
* library-mode default — they read the final result from the helper's
* return value instead).
*/
export interface SubagentSink {
current: ((ev: SubagentEvent) => void) | null;
}
/**
* Per-spawn options for {@link spawnSubagent}. All but `parentRegistry`
* + `client` + `system` + `task` are tunables with sensible defaults.
*/
export interface SpawnSubagentOptions {
/** Shared DeepSeek client. The subagent reuses it (same auth, same retries). */
client: DeepSeekClient;
/**
* Parent registry — the subagent inherits a copy of its tools (minus
* the never-inherited set: `spawn_subagent`, `submit_plan`).
*/
parentRegistry: ToolRegistry;
/**
* System prompt for the child loop. Skills' subagent path passes
* the skill body here; the spawn_subagent tool passes its default
* (or the model's `system` argument override).
*/
system: string;
/** The task / question / instruction the subagent must address. */
task: string;
/** Model id for the child loop. Defaults to `deepseek-v4-pro`. */
model?: string;
/** Iteration ceiling for the child loop. Defaults to 16. */
maxToolIters?: number;
/**
* Maximum chars of the final assistant message returned. Long answers
* are truncated with a notice — the parent's prompt budget shouldn't
* be blown out by an over-eager subagent.
*/
maxResultChars?: number;
/** Optional sink for TUI live updates. */
sink?: SubagentSink;
/**
* Parent's per-tool-dispatch AbortSignal. When the parent aborts (Esc),
* we forward the cancel into the child loop. Omit for headless callers
* that don't care about cancellation.
*/
parentSignal?: AbortSignal;
/**
* Skill name when this spawn is driven by a `runAs: subagent` skill.
* Used purely for downstream attribution (TUI summary line, usage log).
* Omit for raw `spawn_subagent` tool calls.
*/
skillName?: string;
}
/**
* Structured result of a subagent run. The two convenience JSON wrappers
* (`spawn_subagent` tool, `run_skill` subagent path) serialize this for
* the model; library callers can read the typed object directly.
*/
export interface SubagentResult {
success: boolean;
/** Final assistant message (possibly truncated). Empty on error. */
output: string;
/** Set when the run failed (network, child-loop error, etc.). */
error?: string;
/** Turns the child loop took. */
turns: number;
/** Tool calls dispatched inside the child loop. */
toolIters: number;
/** Wall-clock ms. */
elapsedMs: number;
/** USD spent in the child loop, summed across its turns. */
costUsd: number;
/** Model id the child loop ran on. */
model: string;
/** Skill name if the spawn was driven by a `runAs: subagent` skill. */
skillName?: string;
/** Aggregated Usage across the child loop's turns. Zero-filled when no API calls landed. */
usage: Usage;
}
export interface SubagentToolOptions {
/** Shared DeepSeek client. */
client: DeepSeekClient;
/**
* Default system prompt used when the model doesn't pass one. Project
* memory (REASONIX.md) is appended automatically when `projectRoot` is
* set.
*/
defaultSystem?: string;
/** Project root for `applyProjectMemory` lookup. Omit in chat mode. */
projectRoot?: string;
/** Default model. `deepseek-v4-pro` by default. */
defaultModel?: string;
/** Iteration ceiling. Lower than the parent (16 by default). */
maxToolIters?: number;
/** Maximum chars returned in the tool result. */
maxResultChars?: number;
/** Optional sink the TUI attaches its handler to for live updates. */
sink?: SubagentSink;
}
const DEFAULT_SUBAGENT_SYSTEM = `You are a Reasonix subagent. The parent agent spawned you to handle one focused subtask, then return.
Rules:
- Stay on the task you were given. Do not expand scope.
- Use tools as needed. You share the parent's sandbox + safety rules.
- When you're done, your final assistant message is the only thing the parent will see — make it complete and self-contained. No follow-up offers, no questions, no "let me know if you need more."
- Prefer one clear, distilled answer over a long log of what you tried.
${NEGATIVE_CLAIM_RULE}
${ESCALATION_CONTRACT}
${TUI_FORMATTING_RULES}`;
const DEFAULT_MAX_RESULT_CHARS = 8000;
const DEFAULT_MAX_ITERS = 16;
// Subagents default to flash — their work is read-and-synthesize
// (explore, research), which doesn't need the 12× pro tier. Skill
// frontmatter `model: deepseek-v4-pro` is the opt-in override for
// skills that empirically benefit from the stronger model.
const DEFAULT_SUBAGENT_MODEL = "deepseek-v4-flash";
// Subagents default to effort=high — less thinking budget than a
// main turn (which defaults to `max` in the preset). The parent's
// task arg is already a distilled prompt; explore/research rarely
// need deep chains of thought, and `high` saves output tokens.
const DEFAULT_SUBAGENT_EFFORT: "high" | "max" = "high";
const SUBAGENT_TOOL_NAME = "spawn_subagent";
/**
* Tools the subagent never inherits from the parent registry:
* - spawn_subagent itself: would allow unbounded recursion via the
* tool API. Depth=1 hard cap by construction.
* - submit_plan: only the parent talks to the user about plan
* approval; a subagent submitting a plan would surface a picker
* midway through the parent's turn, which the user did not ask for.
*/
const NEVER_INHERITED_TOOLS = new Set<string>([SUBAGENT_TOOL_NAME, "submit_plan"]);
/**
* Run one subagent to completion. The unified primitive both
* `spawn_subagent` (function-call tool) and `run_skill` (subagent
* skills) call into.
*
* Headless: returns a `SubagentResult` regardless of success/failure.
* Errors are captured in the structured shape, never thrown — the
* caller decides how to surface them (tool result JSON, log line, etc.).
*/
export async function spawnSubagent(opts: SpawnSubagentOptions): Promise<SubagentResult> {
const model = opts.model ?? DEFAULT_SUBAGENT_MODEL;
const maxToolIters = opts.maxToolIters ?? DEFAULT_MAX_ITERS;
const maxResultChars = opts.maxResultChars ?? DEFAULT_MAX_RESULT_CHARS;
const sink = opts.sink;
const skillName = opts.skillName;
const startedAt = Date.now();
const taskPreview = opts.task.length > 30 ? `${opts.task.slice(0, 30)}…` : opts.task;
sink?.current?.({
kind: "start",
task: taskPreview,
skillName,
model,
iter: 0,
elapsedMs: 0,
});
const childTools = forkRegistryExcluding(opts.parentRegistry, NEVER_INHERITED_TOOLS);
const childPrefix = new ImmutablePrefix({
system: opts.system,
toolSpecs: childTools.specs(),
});
const childLoop = new CacheFirstLoop({
client: opts.client,
prefix: childPrefix,
tools: childTools,
model,
// Subagents run on a constrained thinking budget by default — the
// task is already narrow by construction, and `high` cuts output
// tokens substantially vs `max`.
reasoningEffort: DEFAULT_SUBAGENT_EFFORT,
maxToolIters,
hooks: [],
stream: false,
});
const onParentAbort = () => childLoop.abort();
opts.parentSignal?.addEventListener("abort", onParentAbort, { once: true });
let final = "";
let errorMessage: string | undefined;
let toolIter = 0;
try {
for await (const ev of childLoop.step(opts.task)) {
if (ev.role === "tool") {
toolIter++;
sink?.current?.({
kind: "progress",
task: taskPreview,
skillName,
model,
iter: toolIter,
elapsedMs: Date.now() - startedAt,
});
}
if (ev.role === "assistant_final") {
final = ev.content ?? "";
}
if (ev.role === "error") {
errorMessage = ev.error ?? "subagent error";
}
}
} catch (err) {
errorMessage = (err as Error).message;
} finally {
opts.parentSignal?.removeEventListener("abort", onParentAbort);
}
// The loop yields `done` without an `error` event when its API call
// is aborted mid-flight (intentional UX — see the matching catch in
// CacheFirstLoop.step). From a SUBAGENT consumer's perspective that
// still counts as a failure: no answer came back, the parent has
// nothing to render. Synthesize an error so `success: false` and the
// UI surfaces the abort instead of returning empty output.
if (!errorMessage && !final) {
errorMessage = opts.parentSignal?.aborted
? "subagent aborted before producing an answer"
: "subagent ended without producing an answer";
}
const elapsedMs = Date.now() - startedAt;
const turns = childLoop.stats.turns.length;
const costUsd = childLoop.stats.totalCost;
const usage = aggregateChildUsage(childLoop);
const truncated =
final.length > maxResultChars
? `${final.slice(0, maxResultChars)}\n\n[…truncated ${final.length - maxResultChars} chars; ask the subagent for a tighter summary if you need more.]`
: final;
sink?.current?.({
kind: "end",
task: taskPreview,
skillName,
model,
iter: toolIter,
elapsedMs,
summary: errorMessage ? undefined : truncated.slice(0, 120),
error: errorMessage,
turns,
costUsd,
usage,
});
return {
success: !errorMessage,
output: errorMessage ? "" : truncated,
error: errorMessage,
turns,
toolIters: toolIter,
elapsedMs,
costUsd,
model,
skillName,
usage,
};
}
/**
* Sum the child loop's per-turn `Usage` into one aggregate record.
* Zero-filled when the loop made no API calls (e.g. failed before the
* first request) so downstream consumers always see a valid shape.
*/
function aggregateChildUsage(loop: CacheFirstLoop): Usage {
const agg = new Usage();
for (const t of loop.stats.turns) {
agg.promptTokens += t.usage.promptTokens;
agg.completionTokens += t.usage.completionTokens;
agg.totalTokens += t.usage.totalTokens;
agg.promptCacheHitTokens += t.usage.promptCacheHitTokens;
agg.promptCacheMissTokens += t.usage.promptCacheMissTokens;
}
return agg;
}
/**
* Serialize a {@link SubagentResult} into the JSON tool-result shape
* the model consumes. Both the spawn_subagent tool and the run_skill
* subagent path return this string verbatim, so the schema stays
* stable across both surfaces.
*/
export function formatSubagentResult(r: SubagentResult): string {
if (!r.success) {
return JSON.stringify({
success: false,
error: r.error ?? "unknown subagent error",
turns: r.turns,
tool_iters: r.toolIters,
elapsed_ms: r.elapsedMs,
});
}
return JSON.stringify({
success: true,
output: r.output,
turns: r.turns,
tool_iters: r.toolIters,
elapsed_ms: r.elapsedMs,
cost_usd: r.costUsd,
});
}
/**
* Register the spawn_subagent tool into the parent registry. Library
* surface — `reasonix code` does NOT call this since 0.4.26 (Skills
* with `runAs: subagent` are the user-facing surface), but library
* consumers who want the low-level tool can opt in.
*/
export function registerSubagentTool(
parentRegistry: ToolRegistry,
opts: SubagentToolOptions,
): ToolRegistry {
const baseSystem = opts.defaultSystem ?? DEFAULT_SUBAGENT_SYSTEM;
// Bake project memory into the default once — re-reading on every
// spawn would (a) make the child prefix unstable when REASONIX.md
// changes mid-session, defeating cache reuse across multiple
// subagent calls, and (b) cost a stat() per call. The parent itself
// also reads memory once at startup; matching that semantics keeps
// subagent and parent on the same page.
const defaultSystem = opts.projectRoot
? applyProjectMemory(baseSystem, opts.projectRoot)
: baseSystem;
const defaultModel = opts.defaultModel ?? DEFAULT_SUBAGENT_MODEL;
const maxToolIters = opts.maxToolIters ?? DEFAULT_MAX_ITERS;
const maxResultChars = opts.maxResultChars ?? DEFAULT_MAX_RESULT_CHARS;
const sink = opts.sink;
parentRegistry.register({
name: SUBAGENT_TOOL_NAME,
description:
"Spawn an isolated subagent to handle a self-contained subtask in a fresh context, returning only its final answer. Use for: deep codebase exploration that would flood the main context, multi-step research where you only need the conclusion, or any focused subtask whose intermediate reasoning the user does not need to see. The subagent inherits all your tools (filesystem, shell, web, MCP, etc.) but runs in its own isolated message log — its tool calls and reasoning never enter your context. Only the final assistant message comes back as this tool's result. Keep tasks focused; the subagent has a stricter iter budget than you do.",
parameters: {
type: "object",
properties: {
task: {
type: "string",
description:
"The subtask the subagent should perform. Be specific and self-contained — the subagent has none of your conversation context, only what you write here.",
},
system: {
type: "string",
description:
"Optional override for the subagent's system prompt. The default tells it to stay focused and return a concise answer; override only when the subtask needs a specialized persona.",
},
model: {
type: "string",
enum: ["deepseek-v4-flash", "deepseek-v4-pro", "deepseek-chat", "deepseek-reasoner"],
description:
"Which DeepSeek model the subagent runs on. Default is 'deepseek-v4-pro' — the strongest model, best for complex subtasks. Override to 'deepseek-v4-flash' (or the legacy 'deepseek-chat' / 'deepseek-reasoner' aliases, which route to flash non-thinking / thinking modes) when the subtask is simple enough that flash's quality suffices — flash is roughly 12× cheaper.",
},
},
required: ["task"],
},
fn: async (args: { task?: unknown; system?: unknown; model?: unknown }, ctx) => {
const task = typeof args.task === "string" ? args.task.trim() : "";
if (!task) {
return JSON.stringify({
error: "spawn_subagent requires a non-empty 'task' argument.",
});
}
const system =
typeof args.system === "string" && args.system.trim().length > 0
? args.system.trim()
: defaultSystem;
const model =
typeof args.model === "string" && args.model.startsWith("deepseek-")
? args.model
: defaultModel;
const result = await spawnSubagent({
client: opts.client,
parentRegistry,
system,
task,
model,
maxToolIters,
maxResultChars,
sink,
parentSignal: ctx?.signal,
});
return formatSubagentResult(result);
},
});
return parentRegistry;
}
/**
* Build a child ToolRegistry that copies every tool from `parent` except
* those whose names are in `exclude`. Plan-mode state propagates so a
* subagent spawned while the parent is under `/plan` cannot escape it.
*
* Exported for tests + library callers who want the same fork behavior
* for their own nested-loop patterns.
*/
export function forkRegistryExcluding(
parent: ToolRegistry,
exclude: ReadonlySet<string>,
): ToolRegistry {
const child = new ToolRegistry();
for (const spec of parent.specs()) {
const name = spec.function.name;
if (exclude.has(name)) continue;
const def = parent.get(name);
if (!def) continue;
// Re-register copies the public ToolDefinition fields. The child
// re-runs auto-flatten analysis on its own, which produces an
// identical flatSchema for the same input — no surprise.
child.register(def);
}
if (parent.planMode) child.setPlanMode(true);
return child;
}
+301
View File
@@ -0,0 +1,301 @@
/**
* Built-in web search + fetch tools.
*
* - `web_search(query, topK?)` — Mojeek's public search page. No API
* key, no signup. We originally shipped this backed by DuckDuckGo's
* HTML endpoint, but DDG started serving anti-bot interstitials
* (HTTP 202 with a challenge page) for every unauthenticated POST.
* Mojeek runs its own independent index, is bot-friendly, and
* returns parseable HTML.
* - `web_fetch(url)` — HTTP GET + naïve HTML-to-text extraction.
*
* Both are registered by default on `reasonix chat` / `reasonix code`;
* set `search: false` in config (or `REASONIX_SEARCH=off`) to turn
* them off. The model decides when to call them based on the query —
* no slash command required.
*/
import type { ToolRegistry } from "../tools.js";
export interface SearchResult {
title: string;
url: string;
snippet: string;
}
export interface PageContent {
url: string;
title?: string;
text: string;
/** True when the extracted text was clipped to fit the cap. */
truncated: boolean;
}
export interface WebFetchOptions {
/** Max bytes of extracted text. Defaults to 32_000 to match tool-result cap. */
maxChars?: number;
/** Timeout in ms. Defaults to 15_000. */
timeoutMs?: number;
signal?: AbortSignal;
}
export interface WebSearchOptions {
topK?: number;
signal?: AbortSignal;
}
const DEFAULT_FETCH_MAX_CHARS = 32_000;
const DEFAULT_FETCH_TIMEOUT_MS = 15_000;
const DEFAULT_TOPK = 5;
// Real-browser UA. Servers like Mojeek are bot-friendly but still gate
// obvious scraper UAs; a stock Chrome string avoids the fast-path block.
const USER_AGENT =
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36";
const MOJEEK_ENDPOINT = "https://www.mojeek.com/search";
/**
* Search the public web via Mojeek. Returns up to `topK` ranked
* results with title, url, snippet.
*
* Mojeek is an independent index (not a Google/Bing front-end) which
* means coverage on niche or very recent topics can be thinner, but
* it's reliable from scripts and doesn't gate on cookies or sessions.
* If the response has 0 results we distinguish "truly empty" from
* "layout changed or blocked" so the caller isn't left guessing.
*/
export async function webSearch(
query: string,
opts: WebSearchOptions = {},
): Promise<SearchResult[]> {
const topK = Math.max(1, Math.min(10, opts.topK ?? DEFAULT_TOPK));
const resp = await fetch(`${MOJEEK_ENDPOINT}?q=${encodeURIComponent(query)}`, {
headers: {
"User-Agent": USER_AGENT,
Accept: "text/html,application/xhtml+xml,application/xml;q=0.9",
"Accept-Language": "en-US,en;q=0.9",
},
signal: opts.signal,
redirect: "follow",
});
if (!resp.ok) throw new Error(`web_search ${resp.status}`);
const html = await resp.text();
const results = parseMojeekResults(html).slice(0, topK);
if (results.length === 0) {
if (/no results found|did not match any documents/i.test(html)) return [];
if (/captcha|verify you are human|access denied|forbidden/i.test(html)) {
throw new Error("web_search: Mojeek anti-bot page — rate-limited or blocked");
}
throw new Error(
`web_search: 0 results but response doesn't look like a real empty page (${html.length} chars, first 120: ${html.slice(0, 120).replace(/\s+/g, " ")})`,
);
}
return results;
}
/**
* Extract results from a Mojeek search page.
*
* Mojeek's stable shape (as of April 2026):
* <a … class="ob" href="URL"> … breadcrumb … </a>
* <h2><a class="title" href="URL">Title</a></h2>
* <p class="s">snippet text …</p>
*
* We do two tolerant passes — title anchors, then snippet paragraphs —
* and pair them positionally. Attribute order inside a tag varies
* between versions, so each pass captures the whole element and we
* re-extract href / inner text with a second regex. Exported for
* unit testing against a fixture.
*/
export function parseMojeekResults(html: string): SearchResult[] {
const titles: string[] = [];
const titleAnchorRe = /<a\b[^>]*\bclass="title"[^>]*>[\s\S]*?<\/a>/g;
let m: RegExpExecArray | null;
while (true) {
m = titleAnchorRe.exec(html);
if (m === null) break;
titles.push(m[0]);
}
const snippets: string[] = [];
const snippetRe = /<p\b[^>]*\bclass="s"[^>]*>([\s\S]*?)<\/p>/g;
while (true) {
m = snippetRe.exec(html);
if (m === null) break;
snippets.push(m[1] ?? "");
}
const hrefRe = /href="([^"]+)"/;
const innerRe = /<a\b[^>]*>([\s\S]*?)<\/a>/;
const results: SearchResult[] = [];
for (let i = 0; i < titles.length; i++) {
const anchor = titles[i]!;
const hrefMatch = anchor.match(hrefRe);
const innerMatch = anchor.match(innerRe);
if (!hrefMatch?.[1]) continue;
results.push({
title: decodeHtmlEntities(stripHtml(innerMatch?.[1] ?? "")).trim(),
url: hrefMatch[1],
snippet: decodeHtmlEntities(stripHtml(snippets[i] ?? ""))
.replace(/\s+/g, " ")
.trim(),
});
}
return results;
}
/**
* Download a URL, strip HTML down to readable text, return it. Times
* out at 15s, caps extracted text at 32k chars to fit the tool-result
* budget.
*/
export async function webFetch(url: string, opts: WebFetchOptions = {}): Promise<PageContent> {
const maxChars = opts.maxChars ?? DEFAULT_FETCH_MAX_CHARS;
const timeoutMs = opts.timeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS;
const ctl = new AbortController();
const timer = setTimeout(() => ctl.abort(), timeoutMs);
// Forward the caller's abort too so an Esc during a long fetch is respected.
const cancel = () => ctl.abort();
opts.signal?.addEventListener("abort", cancel, { once: true });
let resp: Response;
try {
resp = await fetch(url, {
headers: { "User-Agent": USER_AGENT, Accept: "text/html,text/plain,*/*" },
signal: ctl.signal,
redirect: "follow",
});
} finally {
clearTimeout(timer);
opts.signal?.removeEventListener("abort", cancel);
}
if (!resp.ok) throw new Error(`web_fetch ${resp.status} for ${url}`);
const contentType = resp.headers.get("content-type") ?? "";
const raw = await resp.text();
const title = extractTitle(raw);
const text = contentType.includes("text/html") ? htmlToText(raw) : raw;
const truncated = text.length > maxChars;
const finalText = truncated
? `${text.slice(0, maxChars)}\n\n[… truncated ${text.length - maxChars} chars …]`
: text;
return { url, title, text: finalText, truncated };
}
/**
* Strip HTML to readable text. Removes scripts/styles/nav/footer/aside
* blocks first, then tags, then collapses whitespace. Not a Readability
* clone — purpose-built to keep the extracted text small enough for the
* tool-result budget while preserving paragraph breaks.
*/
export function htmlToText(html: string): string {
let s = html;
s = s.replace(/<script[\s\S]*?<\/script>/gi, "");
s = s.replace(/<style[\s\S]*?<\/style>/gi, "");
s = s.replace(/<noscript[\s\S]*?<\/noscript>/gi, "");
s = s.replace(/<nav[\s\S]*?<\/nav>/gi, "");
s = s.replace(/<footer[\s\S]*?<\/footer>/gi, "");
s = s.replace(/<aside[\s\S]*?<\/aside>/gi, "");
s = s.replace(/<svg[\s\S]*?<\/svg>/gi, "");
// Preserve paragraph breaks by turning common block tags into newlines.
s = s.replace(/<\/?(p|div|br|h[1-6]|li|tr|section|article)\b[^>]*>/gi, "\n");
s = s.replace(/<[^>]+>/g, "");
s = decodeHtmlEntities(s);
s = s.replace(/[ \t]+/g, " ");
s = s.replace(/\n[ \t]+/g, "\n");
s = s.replace(/\n{3,}/g, "\n\n");
return s.trim();
}
function stripHtml(s: string): string {
return s.replace(/<[^>]+>/g, "");
}
function decodeHtmlEntities(s: string): string {
return s
.replace(/&nbsp;/g, " ")
.replace(/&amp;/g, "&")
.replace(/&lt;/g, "<")
.replace(/&gt;/g, ">")
.replace(/&quot;/g, '"')
.replace(/&#39;/g, "'");
}
function extractTitle(html: string): string | undefined {
const m = html.match(/<title[^>]*>([\s\S]*?)<\/title>/i);
if (!m?.[1]) return undefined;
return m[1].replace(/\s+/g, " ").trim() || undefined;
}
export interface WebToolsOptions {
/** Default top-K for `web_search` when the model doesn't specify. */
defaultTopK?: number;
/** Byte cap for `web_fetch` extracted text. */
maxFetchChars?: number;
}
/**
* Register `web_search` + `web_fetch` on a ToolRegistry. The model
* invokes them automatically when a question needs current info —
* no slash command from the user is required.
*/
export function registerWebTools(registry: ToolRegistry, opts: WebToolsOptions = {}): ToolRegistry {
const defaultTopK = opts.defaultTopK ?? DEFAULT_TOPK;
const maxFetchChars = opts.maxFetchChars ?? DEFAULT_FETCH_MAX_CHARS;
registry.register({
name: "web_search",
description:
"Search the public web. Returns ranked results with title, url, and snippet. Use this when the question needs information more current than your training data, when you're unsure of a factual detail, or when the user asks about a specific webpage/library/release you haven't seen.",
readOnly: true,
parameters: {
type: "object",
properties: {
query: { type: "string", description: "Natural-language search query." },
topK: {
type: "integer",
description: `Number of results to return (1..10). Default ${defaultTopK}.`,
},
},
required: ["query"],
},
fn: async (args: { query: string; topK?: number }, ctx) => {
const results = await webSearch(args.query, {
topK: args.topK ?? defaultTopK,
signal: ctx?.signal,
});
return formatSearchResults(args.query, results);
},
});
registry.register({
name: "web_fetch",
description:
"Download a URL and return its visible text content (HTML pages get scripts/styles/nav stripped). Truncated at the tool-result cap. Use after web_search when a snippet isn't enough.",
readOnly: true,
parameters: {
type: "object",
properties: {
url: { type: "string", description: "Absolute http:// or https:// URL." },
},
required: ["url"],
},
fn: async (args: { url: string }, ctx) => {
if (!/^https?:\/\//i.test(args.url)) {
throw new Error("web_fetch: url must start with http:// or https://");
}
const page = await webFetch(args.url, { maxChars: maxFetchChars, signal: ctx?.signal });
const header = page.title ? `${page.title}\n${page.url}` : page.url;
return `${header}\n\n${page.text}`;
},
});
return registry;
}
export function formatSearchResults(query: string, results: SearchResult[]): string {
const lines: string[] = [`query: ${query}`, `\nresults (${results.length}):`];
results.forEach((r, i) => {
lines.push(`\n${i + 1}. ${r.title}`);
lines.push(` ${r.url}`);
if (r.snippet) lines.push(` ${r.snippet}`);
});
return lines.join("\n");
}
+23
View File
@@ -36,6 +36,14 @@ export interface ChatMessage {
name?: string;
tool_call_id?: string;
tool_calls?: ToolCall[];
/**
* R1 `reasoning_content` captured from the assistant's thinking turn.
* DeepSeek's thinking mode 400s with "reasoning_content in the
* thinking mode must be passed back" when a tool-loop continuation
* omits it from the preceding assistant message. Round-tripped for
* deepseek-reasoner turns with tool_calls; absent for deepseek-chat.
*/
reasoning_content?: string | null;
}
export interface RawUsage {
@@ -56,4 +64,19 @@ export interface ChatRequestOptions {
signal?: AbortSignal;
/** DeepSeek response_format — use { type: "json_object" } to force valid JSON. */
responseFormat?: { type: "json_object" | "text" };
/**
* Explicitly toggle V4 thinking mode. Serialized as
* `extra_body.thinking.type = enabled|disabled`. Omit to let the
* server default apply (thinking enabled). Mainly used so the loop
* can pin the mode per model: `deepseek-chat` → disabled (legacy
* non-thinking compat), everything else → enabled.
*/
thinking?: "enabled" | "disabled";
/**
* Per-request reasoning-effort cap. Serialized as the top-level
* `reasoning_effort` field. DeepSeek accepts `high` (standard) or
* `max` (Agent-class, auto-applied to Claude-Code-style flows per
* the V4 docs). Reasonix pins `max` because every turn is agent-like.
*/
reasoningEffort?: "high" | "max";
}
+347
View File
@@ -0,0 +1,347 @@
/**
* Persistent per-turn usage log at `~/.reasonix/usage.jsonl`.
*
* Each line is a single `UsageRecord` — one turn's tokens + cost
* snapshot — appended after every `assistant_final` event. This is
* what drives `reasonix stats` (the dashboard, no-arg form), so the
* user can see how much they've spent vs what the equivalent Claude
* spend would have been. The Pillar 1 pitch (94–97% cost reduction
* vs Claude, from the v0.3 hard-number table) becomes a fact users
* can verify on their own machine.
*
* Format choices:
* - **append-only JSONL** — one line per turn, durable, survives
* abrupt exits. A corrupted tail line loses at most one record.
* - **flat keys, no nesting** — readable with `jq` / `cut` / `awk`;
* the model doesn't need to parse this, humans do.
* - **best-effort writes** — disk errors never propagate into the
* turn. We log nothing (no `console.error`) because the TUI is
* rendering Ink; a silent skip is the least-worst failure mode.
* - **no PII, no prompts, no completions** — the log contains
* tokens and costs, that's it. Sessions are identified by the
* user-chosen name (never a prompt).
*
* This file is deliberately NOT wired through project memory or
* skills — those are content pins. Usage is pure telemetry.
*/
import { appendFileSync, existsSync, mkdirSync, readFileSync, statSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join } from "node:path";
import type { Usage } from "./client.js";
import {
CLAUDE_SONNET_PRICING,
DEEPSEEK_PRICING,
claudeEquivalentCost,
costUsd,
} from "./telemetry.js";
/** One turn's snapshot — serialized verbatim as a JSONL line. */
export interface UsageRecord {
/** Epoch millis when the record was written. */
ts: number;
/** Session name if the turn ran inside a persisted session, `null` for ephemeral. */
session: string | null;
/** Model id the turn ran against (drives the pricing lookup). */
model: string;
promptTokens: number;
completionTokens: number;
cacheHitTokens: number;
cacheMissTokens: number;
/** Total cost of the turn in USD. */
costUsd: number;
/** What the same turn would have cost at Claude Sonnet 4.6 rates. */
claudeEquivUsd: number;
/**
* Distinguishes ordinary parent-loop turns from subagent summary rows.
* Absent on pre-0.5.14 records — treat as "turn" when missing.
*/
kind?: "turn" | "subagent";
/** Present when `kind === "subagent"`. Attribution metadata for the /stats roll-up. */
subagent?: {
/** Skill that spawned it, when the spawn came from a `runAs: subagent` skill. */
skillName?: string;
/** First ~60 chars of the task prompt — enough context to recognize a run, never the full text. */
taskPreview: string;
/** Tool calls the child loop dispatched before returning. */
toolIters: number;
/** Wall-clock ms. */
durationMs: number;
};
}
/** Where the log lives. Tests override via `opts.path`. */
export function defaultUsageLogPath(homeDirOverride?: string): string {
return join(homeDirOverride ?? homedir(), ".reasonix", "usage.jsonl");
}
export interface AppendUsageInput {
session: string | null;
model: string;
usage: Usage;
/** Override the timestamp (tests). */
now?: number;
/** Override the log path (tests). */
path?: string;
/** When appending a subagent summary row, set `kind: "subagent"` and populate `subagent`. */
kind?: "turn" | "subagent";
subagent?: UsageRecord["subagent"];
}
/**
* Append one record and return it. Swallows disk errors — the TUI
* should keep working even if `~/.reasonix/` is read-only.
*
* Returns the record that was written (or would have been written
* if the disk had cooperated) so tests / callers can assert on the
* computed cost fields without a round trip through the log file.
*/
export function appendUsage(input: AppendUsageInput): UsageRecord {
const record: UsageRecord = {
ts: input.now ?? Date.now(),
session: input.session,
model: input.model,
promptTokens: input.usage.promptTokens,
completionTokens: input.usage.completionTokens,
cacheHitTokens: input.usage.promptCacheHitTokens,
cacheMissTokens: input.usage.promptCacheMissTokens,
costUsd: costUsd(input.model, input.usage),
claudeEquivUsd: claudeEquivalentCost(input.usage),
};
if (input.kind === "subagent") record.kind = "subagent";
if (input.subagent) record.subagent = input.subagent;
const path = input.path ?? defaultUsageLogPath();
try {
mkdirSync(dirname(path), { recursive: true });
appendFileSync(path, `${JSON.stringify(record)}\n`, "utf8");
} catch {
/* best-effort — disk failure shouldn't break the chat */
}
return record;
}
/**
* Read + parse the log. Malformed lines are silently skipped so a
* single corrupted write (half-flushed on power loss, user hand-edit)
* doesn't throw away the rest of the history.
*/
export function readUsageLog(path: string = defaultUsageLogPath()): UsageRecord[] {
if (!existsSync(path)) return [];
let raw: string;
try {
raw = readFileSync(path, "utf8");
} catch {
return [];
}
const out: UsageRecord[] = [];
for (const line of raw.split(/\r?\n/)) {
if (!line.trim()) continue;
try {
const rec = JSON.parse(line);
if (isValidRecord(rec)) out.push(rec);
} catch {
/* skip malformed */
}
}
return out;
}
function isValidRecord(rec: unknown): rec is UsageRecord {
if (!rec || typeof rec !== "object") return false;
const r = rec as Partial<UsageRecord>;
return (
typeof r.ts === "number" &&
typeof r.model === "string" &&
typeof r.promptTokens === "number" &&
typeof r.completionTokens === "number" &&
typeof r.cacheHitTokens === "number" &&
typeof r.cacheMissTokens === "number" &&
typeof r.costUsd === "number" &&
typeof r.claudeEquivUsd === "number"
);
}
/** One row of the `reasonix stats` dashboard — a rolled-up window. */
export interface UsageBucket {
label: string;
/** Start of the window as epoch millis. `0` = unbounded (all-time). */
since: number;
turns: number;
promptTokens: number;
completionTokens: number;
cacheHitTokens: number;
cacheMissTokens: number;
costUsd: number;
claudeEquivUsd: number;
}
/** Cache hit ratio for a bucket — zero denominator returns 0. */
export function bucketCacheHitRatio(b: UsageBucket): number {
const denom = b.cacheHitTokens + b.cacheMissTokens;
return denom > 0 ? b.cacheHitTokens / denom : 0;
}
/** Savings vs Claude as a fraction (0.94 = 94% savings). 0 if Claude cost is 0. */
export function bucketSavingsFraction(b: UsageBucket): number {
return b.claudeEquivUsd > 0 ? 1 - b.costUsd / b.claudeEquivUsd : 0;
}
function emptyBucket(label: string, since: number): UsageBucket {
return {
label,
since,
turns: 0,
promptTokens: 0,
completionTokens: 0,
cacheHitTokens: 0,
cacheMissTokens: 0,
costUsd: 0,
claudeEquivUsd: 0,
};
}
function addToBucket(b: UsageBucket, r: UsageRecord): void {
b.turns += 1;
b.promptTokens += r.promptTokens;
b.completionTokens += r.completionTokens;
b.cacheHitTokens += r.cacheHitTokens;
b.cacheMissTokens += r.cacheMissTokens;
b.costUsd += r.costUsd;
b.claudeEquivUsd += r.claudeEquivUsd;
}
export interface AggregateOptions {
/** Override `Date.now()` for deterministic tests. */
now?: number;
}
export interface UsageAggregate {
/** Fixed-order rolling windows: today, week, month, all-time. */
buckets: UsageBucket[];
/** Model id → turn count. Sorted descending; top entry is the "most used." */
byModel: Array<{ model: string; turns: number }>;
/** Session name → turn count. Sorted descending. Null sessions are grouped under `"(ephemeral)"`. */
bySession: Array<{ session: string; turns: number }>;
/** Earliest record's ts, or `null` when the log is empty. Drives "saved $X since <date>". */
firstSeen: number | null;
/** Latest record's ts, or `null` when the log is empty. */
lastSeen: number | null;
/**
* Subagent-specific rollup. Undefined when no subagent records exist
* in the log so consumers can cheaply skip the section. Counts reflect
* subagent SPAWNS (not internal child-loop turns) — one row per run.
*/
subagents?: SubagentAggregate;
}
/** Rolled-up view of all `kind: "subagent"` records. */
export interface SubagentAggregate {
total: number;
costUsd: number;
totalDurationMs: number;
/** Per-skill breakdown. Records without `skillName` (raw spawn_subagent calls) group under `"(adhoc)"`. */
bySkill: Array<{ skillName: string; count: number; costUsd: number; durationMs: number }>;
}
/**
* Fold a flat record list into the dashboard shape — rolling windows
* plus model / session histograms. Windows are INCLUSIVE of boundary:
* - today = last 24h (rolling, not calendar-day)
* - week = last 7d
* - month = last 30d
* - all = every record
* Rolling windows avoid "it's 00:03, 'today' is empty" surprises.
*/
export function aggregateUsage(
records: UsageRecord[],
opts: AggregateOptions = {},
): UsageAggregate {
const now = opts.now ?? Date.now();
const day = 24 * 60 * 60 * 1000;
const today = emptyBucket("today", now - day);
const week = emptyBucket("week", now - 7 * day);
const month = emptyBucket("month", now - 30 * day);
const all = emptyBucket("all-time", 0);
const modelCounts = new Map<string, number>();
const sessionCounts = new Map<string, number>();
let firstSeen: number | null = null;
let lastSeen: number | null = null;
const skillCounts = new Map<string, { count: number; costUsd: number; durationMs: number }>();
let subagentTotal = 0;
let subagentCost = 0;
let subagentDuration = 0;
for (const r of records) {
addToBucket(all, r);
if (r.ts >= today.since) addToBucket(today, r);
if (r.ts >= week.since) addToBucket(week, r);
if (r.ts >= month.since) addToBucket(month, r);
modelCounts.set(r.model, (modelCounts.get(r.model) ?? 0) + 1);
const sessKey = r.session ?? "(ephemeral)";
sessionCounts.set(sessKey, (sessionCounts.get(sessKey) ?? 0) + 1);
if (firstSeen === null || r.ts < firstSeen) firstSeen = r.ts;
if (lastSeen === null || r.ts > lastSeen) lastSeen = r.ts;
if (r.kind === "subagent") {
subagentTotal += 1;
subagentCost += r.costUsd;
const dur = r.subagent?.durationMs ?? 0;
subagentDuration += dur;
const key = r.subagent?.skillName?.trim() || "(adhoc)";
const prev = skillCounts.get(key) ?? { count: 0, costUsd: 0, durationMs: 0 };
prev.count += 1;
prev.costUsd += r.costUsd;
prev.durationMs += dur;
skillCounts.set(key, prev);
}
}
const byModel = Array.from(modelCounts.entries())
.map(([model, turns]) => ({ model, turns }))
.sort((a, b) => b.turns - a.turns);
const bySession = Array.from(sessionCounts.entries())
.map(([session, turns]) => ({ session, turns }))
.sort((a, b) => b.turns - a.turns);
const subagents: SubagentAggregate | undefined =
subagentTotal > 0
? {
total: subagentTotal,
costUsd: subagentCost,
totalDurationMs: subagentDuration,
bySkill: Array.from(skillCounts.entries())
.map(([skillName, v]) => ({ skillName, ...v }))
.sort((a, b) => b.count - a.count),
}
: undefined;
return {
buckets: [today, week, month, all],
byModel,
bySession,
firstSeen,
lastSeen,
subagents,
};
}
/** File-size helper for the stats header — "1.2 MB" etc. Returns "" if missing. */
export function formatLogSize(path: string = defaultUsageLogPath()): string {
if (!existsSync(path)) return "";
try {
const s = statSync(path);
const bytes = s.size;
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
} catch {
return "";
}
}
/** Re-exports for downstream consumers that also want the pricing constants. */
export { CLAUDE_SONNET_PRICING, DEEPSEEK_PRICING };
+395
View File
@@ -0,0 +1,395 @@
/**
* User memory — `~/.reasonix/memory/` markdown notes pinned into the
* immutable-prefix system prompt across sessions.
*
* Two scopes:
* - `global` → `~/.reasonix/memory/global/` (cross-project)
* - `project` → `~/.reasonix/memory/<hash>/` (per sandbox root)
*
* Each scope has an always-loaded `MEMORY.md` index plus zero-or-more
* `<name>.md` detail files loaded on demand via `recall_memory`.
*
* Distinct from `src/project-memory.ts` (REASONIX.md) in purpose:
* REASONIX.md is committable, team-shared project memory.
* ~/.reasonix/memory is user-private memory, never committed.
*/
import { createHash } from "node:crypto";
import {
existsSync,
mkdirSync,
readFileSync,
readdirSync,
unlinkSync,
writeFileSync,
} from "node:fs";
import { homedir } from "node:os";
import { join, resolve } from "node:path";
import { applyProjectMemory, memoryEnabled } from "./project-memory.js";
import { applySkillsIndex } from "./skills.js";
export const USER_MEMORY_DIR = "memory";
export const MEMORY_INDEX_FILE = "MEMORY.md";
/** Cap on the index file content loaded into the prefix, per scope. */
export const MEMORY_INDEX_MAX_CHARS = 4000;
export type MemoryType = "user" | "feedback" | "project" | "reference";
export type MemoryScope = "global" | "project";
export interface MemoryEntry {
name: string;
type: MemoryType;
scope: MemoryScope;
description: string;
body: string;
/** ISO date string (YYYY-MM-DD). */
createdAt: string;
}
export interface MemoryStoreOptions {
/** Override `~/.reasonix` — tests set this to a tmpdir. */
homeDir?: string;
/** Absolute sandbox root. Required to use `scope: "project"`. */
projectRoot?: string;
}
export interface WriteInput {
name: string;
type: MemoryType;
scope: MemoryScope;
description: string;
body: string;
}
const VALID_NAME = /^[a-zA-Z0-9_-][a-zA-Z0-9_.-]{1,38}[a-zA-Z0-9]$/;
/**
* Throws on filename injection attempts (`../foo`, `foo/bar`, leading
* dots, etc.). Allowed: 3-40 chars, alnum + `_` + `-` + interior `.`.
*/
export function sanitizeMemoryName(raw: string): string {
const trimmed = String(raw ?? "").trim();
if (!VALID_NAME.test(trimmed)) {
throw new Error(
`invalid memory name: ${JSON.stringify(raw)} — must be 3-40 chars, alnum/_/-, no path separators`,
);
}
return trimmed;
}
/** Stable 16-hex-char hash of an absolute sandbox root path. */
export function projectHash(rootDir: string): string {
const abs = resolve(rootDir);
return createHash("sha1").update(abs).digest("hex").slice(0, 16);
}
function scopeDir(opts: { homeDir: string; scope: MemoryScope; projectRoot?: string }): string {
if (opts.scope === "global") {
return join(opts.homeDir, USER_MEMORY_DIR, "global");
}
if (!opts.projectRoot) {
throw new Error("scope=project requires a projectRoot on MemoryStore");
}
return join(opts.homeDir, USER_MEMORY_DIR, projectHash(opts.projectRoot));
}
function ensureDir(p: string): void {
if (!existsSync(p)) mkdirSync(p, { recursive: true });
}
/**
* Parse a `---` frontmatter block off the top of a markdown string.
* Tolerates missing frontmatter, returning `{}` for data and the full
* string as body. Only recognizes the simple `key: value` shape — no
* quoting, no multi-line, no YAML features. Matches what we emit.
*/
function parseFrontmatter(raw: string): { data: Record<string, string>; body: string } {
const lines = raw.split(/\r?\n/);
if (lines[0] !== "---") return { data: {}, body: raw };
const end = lines.indexOf("---", 1);
if (end < 0) return { data: {}, body: raw };
const data: Record<string, string> = {};
for (let i = 1; i < end; i++) {
const line = lines[i];
if (!line) continue;
const m = line.match(/^([a-zA-Z_][a-zA-Z0-9_-]*):\s*(.*)$/);
if (m?.[1]) data[m[1]] = (m[2] ?? "").trim();
}
return {
data,
body: lines
.slice(end + 1)
.join("\n")
.replace(/^\n+/, ""),
};
}
function formatFrontmatter(e: WriteInput & { createdAt: string }): string {
return [
"---",
`name: ${e.name}`,
`description: ${e.description.replace(/\n/g, " ")}`,
`type: ${e.type}`,
`scope: ${e.scope}`,
`created: ${e.createdAt}`,
"---",
"",
].join("\n");
}
function todayIso(): string {
const d = new Date();
return d.toISOString().slice(0, 10);
}
/**
* A `MEMORY.md` index line for one entry. One-liner, under ~150 chars.
* `description` is truncated if it would push past the soft limit.
*/
function indexLine(e: Pick<MemoryEntry, "name" | "description">): string {
const safeDesc = e.description.replace(/\n/g, " ").trim();
const max = 130 - e.name.length;
const clipped = safeDesc.length > max ? `${safeDesc.slice(0, Math.max(1, max - 1))}…` : safeDesc;
return `- [${e.name}](${e.name}.md) — ${clipped}`;
}
export class MemoryStore {
private readonly homeDir: string;
private readonly projectRoot: string | undefined;
constructor(opts: MemoryStoreOptions = {}) {
this.homeDir = opts.homeDir ?? join(homedir(), ".reasonix");
this.projectRoot = opts.projectRoot ? resolve(opts.projectRoot) : undefined;
}
/** Directory this store writes `scope` files into, creating it if needed. */
dir(scope: MemoryScope): string {
const d = scopeDir({ homeDir: this.homeDir, scope, projectRoot: this.projectRoot });
ensureDir(d);
return d;
}
/** Absolute path to a memory file (no existence check). */
pathFor(scope: MemoryScope, name: string): string {
return join(this.dir(scope), `${sanitizeMemoryName(name)}.md`);
}
/** True iff this store is configured with a project scope available. */
hasProjectScope(): boolean {
return this.projectRoot !== undefined;
}
/**
* Read the `MEMORY.md` index for a scope. Returns post-cap content
* (with a truncation marker if clipped), or `null` when absent / empty.
*/
loadIndex(
scope: MemoryScope,
): { content: string; originalChars: number; truncated: boolean } | null {
if (scope === "project" && !this.projectRoot) return null;
const file = join(
scopeDir({ homeDir: this.homeDir, scope, projectRoot: this.projectRoot }),
MEMORY_INDEX_FILE,
);
if (!existsSync(file)) return null;
let raw: string;
try {
raw = readFileSync(file, "utf8");
} catch {
return null;
}
const trimmed = raw.trim();
if (!trimmed) return null;
const originalChars = trimmed.length;
const truncated = originalChars > MEMORY_INDEX_MAX_CHARS;
const content = truncated
? `${trimmed.slice(0, MEMORY_INDEX_MAX_CHARS)}\n… (truncated ${originalChars - MEMORY_INDEX_MAX_CHARS} chars)`
: trimmed;
return { content, originalChars, truncated };
}
/** Read one memory file's body (frontmatter stripped). Throws if missing. */
read(scope: MemoryScope, name: string): MemoryEntry {
const file = this.pathFor(scope, name);
if (!existsSync(file)) {
throw new Error(`memory not found: scope=${scope} name=${name}`);
}
const raw = readFileSync(file, "utf8");
const { data, body } = parseFrontmatter(raw);
return {
name: data.name ?? name,
type: (data.type as MemoryType) ?? "project",
scope: (data.scope as MemoryScope) ?? scope,
description: data.description ?? "",
body: body.trim(),
createdAt: data.created ?? "",
};
}
/**
* List every memory in this store. Scans both scopes (skips project
* scope if unconfigured). Silently skips malformed files; the index
* must stay queryable even if one file is hand-edited into nonsense.
*/
list(): MemoryEntry[] {
const out: MemoryEntry[] = [];
const scopes: MemoryScope[] = this.projectRoot ? ["global", "project"] : ["global"];
for (const scope of scopes) {
const dir = scopeDir({ homeDir: this.homeDir, scope, projectRoot: this.projectRoot });
if (!existsSync(dir)) continue;
let entries: string[];
try {
entries = readdirSync(dir);
} catch {
continue;
}
for (const entry of entries) {
if (entry === MEMORY_INDEX_FILE) continue;
if (!entry.endsWith(".md")) continue;
const name = entry.slice(0, -3);
try {
out.push(this.read(scope, name));
} catch {
// malformed file — skip rather than fail the whole list
}
}
}
return out;
}
/**
* Write a new memory (or overwrite existing). Creates the scope dir,
* writes the `.md` file, and regenerates `MEMORY.md`. Returns the
* absolute path written to.
*/
write(input: WriteInput): string {
if (input.scope === "project" && !this.projectRoot) {
throw new Error("cannot write project-scoped memory: no projectRoot configured");
}
const name = sanitizeMemoryName(input.name);
const desc = String(input.description ?? "").trim();
if (!desc) throw new Error("memory description cannot be empty");
const body = String(input.body ?? "").trim();
if (!body) throw new Error("memory body cannot be empty");
const entry: WriteInput & { createdAt: string } = {
...input,
name,
description: desc,
body,
createdAt: todayIso(),
};
const dir = this.dir(input.scope);
const file = join(dir, `${name}.md`);
const content = `${formatFrontmatter(entry)}${body}\n`;
writeFileSync(file, content, "utf8");
this.regenerateIndex(input.scope);
return file;
}
/** Delete one memory + its index line. No-op if the file is already gone. */
delete(scope: MemoryScope, rawName: string): boolean {
if (scope === "project" && !this.projectRoot) {
throw new Error("cannot delete project-scoped memory: no projectRoot configured");
}
const file = this.pathFor(scope, rawName);
if (!existsSync(file)) return false;
unlinkSync(file);
this.regenerateIndex(scope);
return true;
}
/**
* Rebuild `MEMORY.md` from the `.md` files currently in the scope dir.
* Called after every write/delete. Sorted by name for stable prefix
* hashing — two stores with the same set of files produce byte-identical
* MEMORY.md content, keeping the cache prefix reproducible.
*/
private regenerateIndex(scope: MemoryScope): void {
const dir = scopeDir({ homeDir: this.homeDir, scope, projectRoot: this.projectRoot });
if (!existsSync(dir)) return;
let files: string[];
try {
files = readdirSync(dir);
} catch {
return;
}
const mdFiles = files
.filter((f) => f !== MEMORY_INDEX_FILE && f.endsWith(".md"))
.sort((a, b) => a.localeCompare(b));
const indexPath = join(dir, MEMORY_INDEX_FILE);
if (mdFiles.length === 0) {
if (existsSync(indexPath)) unlinkSync(indexPath);
return;
}
const lines: string[] = [];
for (const f of mdFiles) {
const name = f.slice(0, -3);
try {
const entry = this.read(scope, name);
lines.push(indexLine({ name: entry.name || name, description: entry.description }));
} catch {
// Malformed: still surface it in the index so the user notices.
lines.push(`- [${name}](${name}.md) — (malformed, check frontmatter)`);
}
}
writeFileSync(indexPath, `${lines.join("\n")}\n`, "utf8");
}
}
/**
* Append `MEMORY_GLOBAL` and (optionally) `MEMORY_PROJECT` blocks to
* `basePrompt`. Omits a block entirely when its index is absent — an
* empty tag would add bytes to the prefix hash without content.
* Respects `REASONIX_MEMORY=off` via `memoryEnabled()` from
* `project-memory.ts`.
*/
export function applyUserMemory(
basePrompt: string,
opts: { homeDir?: string; projectRoot?: string } = {},
): string {
if (!memoryEnabled()) return basePrompt;
const store = new MemoryStore(opts);
const global = store.loadIndex("global");
const project = store.hasProjectScope() ? store.loadIndex("project") : null;
if (!global && !project) return basePrompt;
const parts: string[] = [basePrompt];
if (global) {
parts.push(
"",
"# User memory — global (~/.reasonix/memory/global/MEMORY.md)",
"",
"Cross-project facts and preferences the user has told you in prior sessions. TREAT AS AUTHORITATIVE — don't re-verify via filesystem or web. One-liners index detail files; call `recall_memory` for full bodies only when the one-liner isn't enough.",
"",
"```",
global.content,
"```",
);
}
if (project) {
parts.push(
"",
"# User memory — this project",
"",
"Per-project facts the user established in prior sessions (not committed to the repo). TREAT AS AUTHORITATIVE. Same recall pattern as global memory.",
"",
"```",
project.content,
"```",
);
}
return parts.join("\n");
}
/**
* Compose every lazy-loaded prefix block in one call: REASONIX.md,
* user memory (global + project), and the skills index. Drop-in
* replacement for `applyProjectMemory` at CLI entry points. Stacking
* order is stable — the prefix hash only changes when block *content*
* changes, not when this helper is called a second time with the same
* filesystem state.
*/
export function applyMemoryStack(basePrompt: string, rootDir: string): string {
const withProject = applyProjectMemory(basePrompt, rootDir);
const withMemory = applyUserMemory(withProject, { projectRoot: rootDir });
return applySkillsIndex(withMemory, { projectRoot: rootDir });
}
+209
View File
@@ -0,0 +1,209 @@
/**
* Version module.
*
* Two jobs:
*
* 1. Expose `VERSION` sourced from the real `package.json` so the
* constant never drifts from what npm publishes. Works in dev
* (`tsx src/...`) AND after `tsup` bundles to `dist/` — both
* layouts sit two levels below the manifest, so a short
* walk-up finds it.
*
* 2. Offer an opt-in `getLatestVersion()` that hits the npm
* registry with a bounded timeout and a 24-hour on-disk
* cache at `~/.reasonix/version-cache.json`. Returns `null`
* on any failure — offline / restricted-network launches
* should stay silent rather than nag the user.
*
* The CLI wires `getLatestVersion` asynchronously at App mount
* (never in a hot path) and renders the outcome in the stats
* panel when there's a newer published version.
*/
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
/** npm registry endpoint for the `latest` dist-tag of this package. */
const REGISTRY_URL = "https://registry.npmjs.org/reasonix/latest";
/** TTL for the on-disk cache entry. 24h keeps noise low; users who
* want a fresh check can run `reasonix update` which passes
* `force: true`. */
export const LATEST_CACHE_TTL_MS = 24 * 60 * 60 * 1000;
/** Network timeout. Short — we never block the UI waiting on this. */
export const LATEST_FETCH_TIMEOUT_MS = 2_000;
/**
* Walk up from the current source file looking for the `reasonix`
* package.json. Works for:
* - dev: `src/version.ts` → `F:/Reasonix/package.json` (2 levels up)
* - built: `dist/index.js` → `F:/Reasonix/package.json` (2 levels up)
* - global install: `.../node_modules/reasonix/dist/index.js` → `.../reasonix/package.json`
*
* The `name === "reasonix"` guard is a cheap safety net against
* picking up the nearest *other* package.json if we're ever loaded
* as a dependency and the layout is unusual.
*/
function readPackageVersion(): string {
try {
let dir = dirname(fileURLToPath(import.meta.url));
for (let i = 0; i < 6; i++) {
const p = join(dir, "package.json");
if (existsSync(p)) {
const pkg = JSON.parse(readFileSync(p, "utf8"));
if (pkg?.name === "reasonix" && typeof pkg.version === "string") {
return pkg.version;
}
}
const parent = dirname(dir);
if (parent === dir) break;
dir = parent;
}
} catch {
/* fall through to fallback */
}
return "0.0.0-dev";
}
export const VERSION: string = readPackageVersion();
interface VersionCacheEntry {
version: string;
/** Epoch millis the entry was written. Drives TTL comparisons. */
checkedAt: number;
}
function cachePath(homeDirOverride?: string): string {
return join(homeDirOverride ?? homedir(), ".reasonix", "version-cache.json");
}
function readCache(homeDirOverride?: string): VersionCacheEntry | null {
try {
const raw = readFileSync(cachePath(homeDirOverride), "utf8");
const parsed = JSON.parse(raw);
if (parsed && typeof parsed.version === "string" && typeof parsed.checkedAt === "number") {
return parsed;
}
} catch {
/* missing or malformed → no cached entry */
}
return null;
}
function writeCache(entry: VersionCacheEntry, homeDirOverride?: string): void {
try {
const p = cachePath(homeDirOverride);
mkdirSync(dirname(p), { recursive: true });
writeFileSync(p, JSON.stringify(entry), "utf8");
} catch {
/* cache is best-effort — a failed write just means we'll re-fetch
* next launch. No reason to surface this to the user. */
}
}
export interface GetLatestVersionOptions {
/** Ignore the cached entry and always fetch fresh. Used by `reasonix update`. */
force?: boolean;
/** Registry URL override (tests). */
registryUrl?: string;
/** Home-directory override (tests). */
homeDir?: string;
/** Fetch implementation override (tests). Defaults to `globalThis.fetch`. */
fetchImpl?: typeof fetch;
/** TTL override (tests). */
ttlMs?: number;
/** Network timeout override (tests). */
timeoutMs?: number;
}
/**
* Resolve the latest published `reasonix` version from the npm registry.
*
* Returns `null` on any network / parse failure. Callers treat `null`
* as "don't know, don't nag the user." The cache entry is only
* written on a successful fetch — a bad registry response won't
* poison the cache.
*/
export async function getLatestVersion(opts: GetLatestVersionOptions = {}): Promise<string | null> {
const ttl = opts.ttlMs ?? LATEST_CACHE_TTL_MS;
if (!opts.force) {
const cached = readCache(opts.homeDir);
if (cached && Date.now() - cached.checkedAt < ttl) return cached.version;
}
const fetchImpl = opts.fetchImpl ?? globalThis.fetch;
if (!fetchImpl) return null;
const url = opts.registryUrl ?? REGISTRY_URL;
const timeout = opts.timeoutMs ?? LATEST_FETCH_TIMEOUT_MS;
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeout);
try {
const res = await fetchImpl(url, {
signal: controller.signal,
headers: { accept: "application/json" },
});
if (!res.ok) return null;
const body = (await res.json()) as { version?: unknown };
if (typeof body.version !== "string") return null;
writeCache({ version: body.version, checkedAt: Date.now() }, opts.homeDir);
return body.version;
} catch {
return null;
} finally {
clearTimeout(timer);
}
}
/**
* Semver compare. Returns a negative number when `a < b`, positive
* when `a > b`, zero when equal.
*
* Minimal pre-release handling: when the CORE (`x.y.z`) parts match,
* any version WITH a suffix (`-rc.1`, `-alpha.4`) compares LOWER
* than the bare version. That matches npm's dist-tag semantics —
* `reasonix@latest` resolves to a real release, not a pre-release.
*
* We're deliberately not pulling in `semver` (~50KB). The three
* cases we care about are: current > latest (future build, no
* prompt), current < latest (prompt), current === latest (no prompt).
*/
export function compareVersions(a: string, b: string): number {
const [aCore = "0", aPre = ""] = a.split("-", 2);
const [bCore = "0", bPre = ""] = b.split("-", 2);
const aParts = aCore.split(".").map((p) => Number.parseInt(p, 10) || 0);
const bParts = bCore.split(".").map((p) => Number.parseInt(p, 10) || 0);
for (let i = 0; i < 3; i++) {
const diff = (aParts[i] ?? 0) - (bParts[i] ?? 0);
if (diff !== 0) return diff;
}
if (!aPre && !bPre) return 0;
if (!aPre) return 1;
if (!bPre) return -1;
return aPre < bPre ? -1 : aPre > bPre ? 1 : 0;
}
/**
* Heuristic: did this process launch via `npx` / `pnpm dlx` instead
* of a global install? The update command takes different advice in
* each case — a global install can `npm i -g reasonix@latest`, while
* npx just needs its cache to roll over on next launch.
*
* Signals checked, in order:
* - `process.argv[1]` contains `_npx` (npm's ephemeral dir name)
* - `process.argv[1]` contains `.pnpm` + `dlx`
* - `npm_config_user_agent` contains `npx/`
*
* Any one hit → npx. False negatives are safe (worst case we suggest
* `npm i -g` to an npx user, which is a valid way to upgrade too).
*/
export function isNpxInstall(): boolean {
const bin = process.argv[1] ?? "";
if (/[/\\]_npx[/\\]/.test(bin)) return true;
if (/[/\\]\.pnpm[/\\]/.test(bin) && /dlx/i.test(bin)) return true;
const ua = process.env.npm_config_user_agent ?? "";
if (ua.includes("npx/")) return true;
return false;
}
+372
View File
@@ -0,0 +1,372 @@
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import {
AT_MENTION_PATTERN,
AT_PICKER_PREFIX,
DEFAULT_AT_MENTION_MAX_BYTES,
DEFAULT_PICKER_IGNORE_DIRS,
detectAtPicker,
expandAtMentions,
listFilesSync,
rankPickerCandidates,
} from "../src/at-mentions.js";
describe("AT_MENTION_PATTERN", () => {
it("matches @path at start of string", () => {
const matches = [...".".matchAll(AT_MENTION_PATTERN)];
expect(matches).toHaveLength(0);
const m2 = [..."@src/loop.ts".matchAll(AT_MENTION_PATTERN)];
expect(m2).toHaveLength(1);
expect(m2[0]![1]).toBe("src/loop.ts");
});
it("matches @path after whitespace", () => {
const m = [..."look at @src/loop.ts please".matchAll(AT_MENTION_PATTERN)];
expect(m).toHaveLength(1);
expect(m[0]![1]).toBe("src/loop.ts");
});
it("does NOT match @ embedded in a word (email, social handle)", () => {
const m1 = [..."email [email protected]".matchAll(AT_MENTION_PATTERN)];
expect(m1).toHaveLength(0);
const m2 = [..."foo@bar".matchAll(AT_MENTION_PATTERN)];
expect(m2).toHaveLength(0);
});
it("matches multiple @paths in one string", () => {
const m = [..."compare @a.ts and @b.ts".matchAll(AT_MENTION_PATTERN)];
expect(m).toHaveLength(2);
expect(m[0]![1]).toBe("a.ts");
expect(m[1]![1]).toBe("b.ts");
});
});
describe("expandAtMentions", () => {
let root: string;
beforeEach(() => {
root = mkdtempSync(join(tmpdir(), "reasonix-at-mentions-"));
mkdirSync(join(root, "src"), { recursive: true });
writeFileSync(join(root, "src", "loop.ts"), "export const x = 1;\n");
writeFileSync(join(root, "notes.md"), "# Notes\nhello\n");
});
afterEach(() => {
rmSync(root, { recursive: true, force: true });
});
it("returns text unchanged when there are no mentions", () => {
const r = expandAtMentions("plain prompt with no mentions", root);
expect(r.text).toBe("plain prompt with no mentions");
expect(r.expansions).toEqual([]);
});
it("inlines an existing file under a `Referenced files` block", () => {
const r = expandAtMentions("look at @src/loop.ts", root);
expect(r.expansions).toHaveLength(1);
expect(r.expansions[0]!.ok).toBe(true);
expect(r.expansions[0]!.path).toBe("src/loop.ts");
expect(r.text).toContain("look at @src/loop.ts");
expect(r.text).toContain("[Referenced files]");
expect(r.text).toContain('<file path="src/loop.ts">');
expect(r.text).toContain("export const x = 1;");
expect(r.text).toContain("</file>");
});
it("de-duplicates repeated mentions of the same file", () => {
const r = expandAtMentions("compare @src/loop.ts with @src/loop.ts", root);
expect(r.expansions).toHaveLength(1);
// Only one file block in the output.
const fileBlocks = r.text.match(/<file path="/g) ?? [];
expect(fileBlocks).toHaveLength(1);
});
it("expands multiple different files in the same prompt", () => {
const r = expandAtMentions("read @src/loop.ts and @notes.md", root);
expect(r.expansions).toHaveLength(2);
expect(r.expansions.every((ex) => ex.ok)).toBe(true);
expect(r.text).toContain('<file path="src/loop.ts">');
expect(r.text).toContain('<file path="notes.md">');
});
it("marks missing files as skipped with a reason", () => {
const r = expandAtMentions("look at @src/does-not-exist.ts", root);
expect(r.expansions).toHaveLength(1);
expect(r.expansions[0]!.ok).toBe(false);
expect(r.expansions[0]!.skip).toBe("missing");
expect(r.text).toContain('skipped="missing"');
});
it("rejects paths that escape the root directory", () => {
const r = expandAtMentions("peek at @../../../etc/passwd", root);
expect(r.expansions).toHaveLength(1);
expect(r.expansions[0]!.skip).toBe("escape");
expect(r.text).not.toContain("passwd content");
});
it("rejects absolute paths", () => {
const r = expandAtMentions("look at @/etc/hosts", root);
expect(r.expansions).toHaveLength(1);
expect(r.expansions[0]!.skip).toBe("escape");
});
it("skips files larger than maxBytes", () => {
const big = join(root, "big.log");
writeFileSync(big, "x".repeat(1000));
const r = expandAtMentions("inspect @big.log", root, { maxBytes: 500 });
expect(r.expansions).toHaveLength(1);
expect(r.expansions[0]!.ok).toBe(false);
expect(r.expansions[0]!.skip).toBe("too-large");
expect(r.expansions[0]!.bytes).toBe(1000);
expect(r.text).toContain('skipped="too-large"');
});
it("strips a trailing sentence-terminator dot from the path", () => {
// `@src/loop.ts.` — the trailing `.` is a sentence period, not
// part of the filename. The mention should resolve src/loop.ts.
const r = expandAtMentions("look at @src/loop.ts.", root);
expect(r.expansions).toHaveLength(1);
expect(r.expansions[0]!.ok).toBe(true);
expect(r.expansions[0]!.path).toBe("src/loop.ts");
});
it("default max bytes is 64KB", () => {
expect(DEFAULT_AT_MENTION_MAX_BYTES).toBe(64 * 1024);
});
it("marks a directory mention as not-file", () => {
const r = expandAtMentions("look at @src", root);
expect(r.expansions).toHaveLength(1);
expect(r.expansions[0]!.ok).toBe(false);
expect(r.expansions[0]!.skip).toBe("not-file");
});
});
describe("detectAtPicker", () => {
it("fires when the buffer ends with `@`", () => {
const r = detectAtPicker("look at @");
expect(r).not.toBeNull();
expect(r!.query).toBe("");
// `@` is at offset 8 (after "look at ").
expect(r!.atOffset).toBe(8);
});
it("captures the partial query after `@`", () => {
const r = detectAtPicker("edit @src/lo");
expect(r).not.toBeNull();
expect(r!.query).toBe("src/lo");
expect(r!.atOffset).toBe(5);
});
it("does NOT fire when @ is embedded in a word", () => {
expect(detectAtPicker("[email protected]")).toBeNull();
});
it("does NOT fire when the buffer ends with a space after the mention", () => {
// Trailing space closes the picker — the user's done picking.
expect(detectAtPicker("@src/loop.ts ")).toBeNull();
});
it("does NOT fire when there's no @ at all", () => {
expect(detectAtPicker("just a normal message")).toBeNull();
});
it("fires at start of string", () => {
const r = detectAtPicker("@sr");
expect(r).not.toBeNull();
expect(r!.query).toBe("sr");
expect(r!.atOffset).toBe(0);
});
});
describe("AT_PICKER_PREFIX vs AT_MENTION_PATTERN (sanity)", () => {
it("picker captures empty partial", () => {
const m = AT_PICKER_PREFIX.exec("hi @");
expect(m).not.toBeNull();
expect(m![1]).toBe("");
});
it("expansion pattern requires a non-empty path", () => {
// Completed mentions for expandAtMentions need at least one char.
const m = [..."hi @".matchAll(AT_MENTION_PATTERN)];
expect(m).toHaveLength(0);
});
});
describe("rankPickerCandidates", () => {
const files = [
"src/loop.ts",
"src/at-mentions.ts",
"src/tokenizer.ts",
"src/cli/ui/App.tsx",
"src/cli/ui/PromptInput.tsx",
"tests/loop.test.ts",
"tests/at-mentions.test.ts",
"README.md",
];
it("returns the first `limit` entries when query is empty", () => {
const r = rankPickerCandidates(files, "", 3);
expect(r).toHaveLength(3);
expect(r).toEqual(files.slice(0, 3));
});
it("filters by substring match (case-insensitive)", () => {
const r = rankPickerCandidates(files, "LOOP");
expect(r).toContain("src/loop.ts");
expect(r).toContain("tests/loop.test.ts");
expect(r).not.toContain("README.md");
});
it("ranks basename-prefix matches above substring matches", () => {
// `ment` appears in "at-mentions" (both src and tests). Basenames
// are "at-mentions.ts" and "at-mentions.test.ts" — both start
// with `at-m` not `ment`. Not a basename-prefix hit; both should
// score the same (substring).
const r = rankPickerCandidates(files, "at-m");
// `at-m` is a basename prefix for both at-mentions files:
expect(r[0]).toMatch(/at-mentions/);
expect(r[1]).toMatch(/at-mentions/);
});
it("ranks path-prefix above substring when basename doesn't match", () => {
// `tests/` is a path prefix (not basename). Both tests/* hit.
const r = rankPickerCandidates(files, "tests/");
expect(r[0]).toMatch(/^tests\//);
});
it("returns empty array when nothing matches", () => {
const r = rankPickerCandidates(files, "zzznomatch");
expect(r).toEqual([]);
});
it("respects the limit parameter", () => {
const r = rankPickerCandidates(files, "s", 2);
expect(r).toHaveLength(2);
});
it("sorts by mtime descending when entries carry FileWithStats and query is empty", () => {
const entries = [
{ path: "a.ts", mtimeMs: 100 },
{ path: "b.ts", mtimeMs: 300 },
{ path: "c.ts", mtimeMs: 200 },
];
const r = rankPickerCandidates(entries, "", 5);
// Newest (b, mtime 300) → middle (c, 200) → oldest (a, 100).
expect(r).toEqual(["b.ts", "c.ts", "a.ts"]);
});
it("recently-used paths float to the top on empty query regardless of mtime", () => {
const entries = [
{ path: "a.ts", mtimeMs: 300 },
{ path: "b.ts", mtimeMs: 100 },
{ path: "c.ts", mtimeMs: 200 },
];
const r = rankPickerCandidates(entries, "", {
limit: 5,
recentlyUsed: ["c.ts"],
});
// Recently-used c.ts comes first even though a.ts has a newer mtime.
expect(r[0]).toBe("c.ts");
// Remaining sorted by mtime descending.
expect(r[1]).toBe("a.ts");
expect(r[2]).toBe("b.ts");
});
it("tie-breaks query matches by recently-used, then mtime", () => {
const entries = [
{ path: "src/alpha.ts", mtimeMs: 100 },
{ path: "src/alpha2.ts", mtimeMs: 500 }, // newer
];
const r = rankPickerCandidates(entries, "alpha", { limit: 5 });
// Both match with the same score (basename prefix, same hit
// position) — mtime tiebreak puts alpha2 first.
expect(r[0]).toBe("src/alpha2.ts");
expect(r[1]).toBe("src/alpha.ts");
// Now with recency: older alpha.ts boosted over newer alpha2.ts.
const r2 = rankPickerCandidates(entries, "alpha", {
limit: 5,
recentlyUsed: ["src/alpha.ts"],
});
expect(r2[0]).toBe("src/alpha.ts");
expect(r2[1]).toBe("src/alpha2.ts");
});
it("preserves input order on empty query when no mtime + no recency signal", () => {
// Back-compat: bare string input behaves as before.
const r = rankPickerCandidates(files, "", 3);
expect(r).toEqual(files.slice(0, 3));
});
it("accepts a number literal as the third arg for limit (back-compat)", () => {
const r = rankPickerCandidates(files, "loop", 1);
expect(r).toHaveLength(1);
});
});
describe("listFilesSync", () => {
let root: string;
beforeEach(() => {
root = mkdtempSync(join(tmpdir(), "reasonix-listfiles-"));
mkdirSync(join(root, "src"), { recursive: true });
mkdirSync(join(root, "src", "cli"), { recursive: true });
mkdirSync(join(root, "node_modules", "foo"), { recursive: true });
mkdirSync(join(root, ".git", "objects"), { recursive: true });
writeFileSync(join(root, "package.json"), "{}");
writeFileSync(join(root, "README.md"), "# hi");
writeFileSync(join(root, ".gitignore"), "dist/");
writeFileSync(join(root, "src", "index.ts"), "");
writeFileSync(join(root, "src", "cli", "app.ts"), "");
writeFileSync(join(root, "node_modules", "foo", "index.js"), "");
writeFileSync(join(root, ".git", "objects", "abc"), "");
});
afterEach(() => {
rmSync(root, { recursive: true, force: true });
});
it("returns files recursively, with forward-slash separators", () => {
const files = listFilesSync(root);
expect(files).toContain("package.json");
expect(files).toContain("README.md");
expect(files).toContain("src/index.ts");
expect(files).toContain("src/cli/app.ts");
// All entries use forward slashes even on Windows.
for (const f of files) {
expect(f).not.toContain("\\");
}
});
it("skips ignored directories by default", () => {
const files = listFilesSync(root);
expect(files.every((f) => !f.includes("node_modules"))).toBe(true);
expect(files.every((f) => !f.includes(".git/"))).toBe(true);
});
it("includes dotfiles at the top level (e.g. .gitignore)", () => {
const files = listFilesSync(root);
expect(files).toContain(".gitignore");
});
it("respects custom ignoreDirs", () => {
const files = listFilesSync(root, { ignoreDirs: ["src"] });
expect(files.every((f) => !f.startsWith("src/"))).toBe(true);
expect(files).toContain("package.json");
});
it("caps the result count at maxResults", () => {
const files = listFilesSync(root, { maxResults: 2 });
expect(files.length).toBeLessThanOrEqual(2);
});
it("returns an empty list for an unreadable root (falls through)", () => {
const files = listFilesSync(join(root, "does-not-exist"));
expect(files).toEqual([]);
});
it("exposes the default ignore list", () => {
expect(DEFAULT_PICKER_IGNORE_DIRS).toContain("node_modules");
expect(DEFAULT_PICKER_IGNORE_DIRS).toContain(".git");
expect(DEFAULT_PICKER_IGNORE_DIRS).toContain("dist");
});
});
+59
View File
@@ -0,0 +1,59 @@
import { describe, expect, it } from "vitest";
import { detectBangCommand, formatBangUserMessage } from "../src/cli/ui/bang.js";
describe("detectBangCommand", () => {
it("returns the command body for a `!`-prefixed input", () => {
expect(detectBangCommand("!ls src/")).toBe("ls src/");
expect(detectBangCommand("!git status")).toBe("git status");
});
it("trims whitespace after the bang", () => {
expect(detectBangCommand("! ls")).toBe("ls");
expect(detectBangCommand("!ls ")).toBe("ls");
});
it("returns null for non-bang input", () => {
expect(detectBangCommand("ls src/")).toBeNull();
expect(detectBangCommand("hello world")).toBeNull();
expect(detectBangCommand("/help")).toBeNull();
expect(detectBangCommand("")).toBeNull();
});
it("returns null for `!` alone (no command body)", () => {
expect(detectBangCommand("!")).toBeNull();
expect(detectBangCommand("! ")).toBeNull();
});
it("does NOT trigger when `!` appears mid-string", () => {
// Only leading `!` counts. Otherwise commands like `cat foo!bar`
// would be incorrectly intercepted.
expect(detectBangCommand("echo !hello")).toBeNull();
expect(detectBangCommand("what is ! for?")).toBeNull();
});
it("accepts a command with embedded `!` (not leading)", () => {
// The bang is at position 0; the trailing ! in `echo hi!` is
// part of the command body and passes through intact.
expect(detectBangCommand("!echo hi!")).toBe("echo hi!");
});
it("handles multi-word commands with flags and quotes", () => {
expect(detectBangCommand('!grep -R "foo bar" src/')).toBe('grep -R "foo bar" src/');
});
});
describe("formatBangUserMessage", () => {
it("prepends a `[!cmd]` header so the model can distinguish bang runs from its own tool output", () => {
const out = formatBangUserMessage("ls", "$ ls\n[exit 0]\nfile1 file2");
expect(out.startsWith("[!ls]\n")).toBe(true);
expect(out).toContain("$ ls");
expect(out).toContain("[exit 0]");
expect(out).toContain("file1 file2");
});
it("preserves the output verbatim after the header", () => {
const rawOutput = "line1\nline2\n\n[…truncated…]";
const formatted = formatBangUserMessage("cmd", rawOutput);
expect(formatted).toBe(`[!cmd]\n${rawOutput}`);
});
});
+92
View File
@@ -0,0 +1,92 @@
/**
* Post-build smoke test for the bundled `dist/`.
*
* Unit tests load modules from `src/`, which means path-resolution
* bugs that only appear AFTER tsup bundles everything into a different
* directory layout never surface in the regular test suite. v0.5.4
* shipped to npm with exactly such a bug — `src/tokenizer.ts` at
* `dist/cli/index.js` tried to read the tokenizer data file relative
* to the bundled entry, ended up at `dist/data/...` instead of the
* package-root `data/...`, and every `reasonix run` crashed on first
* turn with ENOENT.
*
* These tests spawn the bundled output and verify the two bundle
* layouts (`dist/index.js` library + `dist/cli/index.js` CLI) can
* both locate the tokenizer data file. They're skipped when the
* build hasn't run yet (CI always runs `npm run build` first).
*/
import { spawnSync } from "node:child_process";
import { existsSync } from "node:fs";
import { resolve } from "node:path";
import { pathToFileURL } from "node:url";
import { describe, expect, it } from "vitest";
const LIB_BUNDLE = resolve("dist/index.js");
const CLI_BUNDLE = resolve("dist/cli/index.js");
describe("bundled dist — tokenizer path resolution", () => {
const libExists = existsSync(LIB_BUNDLE);
const cliExists = existsSync(CLI_BUNDLE);
(libExists ? it : it.skip)(
"dist/index.js resolves the tokenizer data file at package-root data/",
() => {
// truncateForModelByTokens internally calls countTokens when the
// input exceeds the fast-path threshold, which forces the
// tokenizer's lazy data-file load. If resolveDataPath() lands on
// a non-existent path (the 0.5.4 regression) this crashes with
// ENOENT and the spawned process exits non-zero.
// ESM dynamic imports on Windows require `file://` URLs, not bare
// absolute paths (which Node's ESM loader rejects as an unknown
// protocol). pathToFileURL handles the cross-platform form.
const libUrl = pathToFileURL(LIB_BUNDLE).href;
const result = spawnSync(
"node",
[
"--input-type=module",
"-e",
`import { truncateForModelByTokens } from "${libUrl}";
const s = "hello world ".repeat(500);
const out = truncateForModelByTokens(s, 100);
console.log(JSON.stringify({ ok: true, len: out.length }));`,
],
{ encoding: "utf8", timeout: 30_000 },
);
expect(result.status).toBe(0);
expect(result.stderr).not.toMatch(/deepseek-tokenizer\.json\.gz/);
expect(result.stderr).not.toMatch(/ENOENT/);
expect(result.stdout).toMatch(/"ok":true/);
},
);
(cliExists ? it : it.skip)("dist/cli/index.js loads tokenizer before the first API fetch", () => {
// Spawn the CLI pointed at a bogus local address that fails fetch
// fast. In step(), preflight's estimateRequestTokens runs BEFORE
// client.chat — so if the bundled layout can't find the
// tokenizer data, we see ENOENT in stderr even though the fetch
// never happens. If tokenizer loads fine, we see a connection
// error instead (and that's OK — we're not testing the network
// path, only that the tokenizer path resolution works from
// dist/cli/).
const result = spawnSync("node", [CLI_BUNDLE, "run", "--no-config", "hi"], {
encoding: "utf8",
timeout: 10_000,
env: {
...process.env,
DEEPSEEK_API_KEY: "sk-smoke-test-bogus",
// Fail-fast fetch target: the :1 port is almost never open,
// so we get connection-refused within ~1ms instead of the
// client's 120s timeout waiting on api.deepseek.com.
DEEPSEEK_BASE_URL: "http://127.0.0.1:1",
},
});
const combined = `${result.stdout}\n${result.stderr}`;
// The crucial assertion: bundle must not crash on the tokenizer
// path. Connection errors to 127.0.0.1:1 are expected and fine.
expect(combined).not.toMatch(/deepseek-tokenizer\.json\.gz/);
// Also not a missing-module style ENOENT (network errors are
// ECONNREFUSED or fetch failure, never ENOENT).
expect(combined).not.toMatch(/ENOENT.*tokenizer/i);
});
});
+75
View File
@@ -0,0 +1,75 @@
import { describe, expect, it, vi } from "vitest";
import { DeepSeekClient } from "../src/client.js";
function makeFetch(status: number, body: unknown) {
return vi.fn(
async () =>
new Response(typeof body === "string" ? body : JSON.stringify(body), {
status,
headers: { "Content-Type": "application/json" },
}),
) as unknown as typeof fetch;
}
describe("DeepSeekClient.listModels", () => {
it("parses the OpenAI-style model list", async () => {
const client = new DeepSeekClient({
apiKey: "sk-test",
fetch: makeFetch(200, {
object: "list",
data: [
{ id: "deepseek-chat", object: "model", owned_by: "deepseek" },
{ id: "deepseek-reasoner", object: "model", owned_by: "deepseek" },
],
}),
});
const list = await client.listModels();
expect(list).not.toBeNull();
expect(list!.data.map((m) => m.id)).toEqual(["deepseek-chat", "deepseek-reasoner"]);
});
it("returns null on non-2xx (bad key / offline)", async () => {
const client = new DeepSeekClient({
apiKey: "sk-bad",
fetch: makeFetch(401, { error: "unauthorized" }),
});
expect(await client.listModels()).toBeNull();
});
it("returns null on malformed payload", async () => {
const client = new DeepSeekClient({
apiKey: "sk-test",
fetch: makeFetch(200, { whatever: "not a list" }),
});
expect(await client.listModels()).toBeNull();
});
it("returns null when fetch throws (network error)", async () => {
const client = new DeepSeekClient({
apiKey: "sk-test",
fetch: vi.fn(async () => {
throw new Error("ECONNREFUSED");
}) as unknown as typeof fetch,
});
expect(await client.listModels()).toBeNull();
});
it("sends the bearer token header", async () => {
const spy = vi.fn(
async () =>
new Response(JSON.stringify({ object: "list", data: [] }), {
status: 200,
headers: { "Content-Type": "application/json" },
}),
);
const client = new DeepSeekClient({
apiKey: "sk-xyz",
fetch: spy as unknown as typeof fetch,
});
await client.listModels();
const [, init] = spy.mock.calls[0]!;
expect((init as RequestInit).method).toBe("GET");
const headers = (init as RequestInit).headers as Record<string, string>;
expect(headers.Authorization).toBe("Bearer sk-xyz");
});
});
+17 -10
View File
@@ -18,8 +18,14 @@ describe("codeSystemPrompt", () => {
rmSync(root, { recursive: true, force: true });
});
it("returns the base prompt unchanged when no .gitignore exists", () => {
expect(codeSystemPrompt(root)).toBe(CODE_SYSTEM_PROMPT);
it("does not append a .gitignore section when none exists", () => {
// We can no longer assert raw equality with CODE_SYSTEM_PROMPT —
// the bundled builtin skills (`explore`, `research`) always inject
// a `# Skills` block via applySkillsIndex. Assert the absence of
// the .gitignore-specific section instead.
const out = codeSystemPrompt(root);
expect(out).not.toMatch(/# Project \.gitignore/);
expect(out).toContain(CODE_SYSTEM_PROMPT);
});
it("appends the .gitignore content as a fenced block", () => {
@@ -36,15 +42,16 @@ describe("codeSystemPrompt", () => {
writeFileSync(join(root, ".gitignore"), huge, "utf8");
const out = codeSystemPrompt(root);
expect(out).toMatch(/truncated \d+ chars/);
// The prompt (base + truncated + fences) is bounded, not 5000+.
expect(out.length).toBeLessThan(CODE_SYSTEM_PROMPT.length + 2300);
// The .gitignore block (base + truncated + fences) is bounded.
// Allow extra slack for the builtin Skills index that applyMemoryStack
// also injects — that's a fixed-size addition, not unbounded.
expect(out.length).toBeLessThan(CODE_SYSTEM_PROMPT.length + 4500);
});
it("still reminds the model about built-in ignores even without a .gitignore", () => {
// Base prompt mentions node_modules / dist / .git as "avoid listing"
// so new-repo users without .gitignore still get the hint.
expect(CODE_SYSTEM_PROMPT).toMatch(/node_modules/);
expect(CODE_SYSTEM_PROMPT).toMatch(/dist/);
expect(CODE_SYSTEM_PROMPT).toMatch(/\.git/);
it("reminds the model to skip dependency / build / VCS dirs", () => {
// We don't enumerate specific names in the prompt anymore (too
// ecosystem-biased); the principle is stated generically and the
// pinned .gitignore block is the authoritative denylist.
expect(CODE_SYSTEM_PROMPT).toMatch(/dependency.*build.*VCS|skip/i);
});
});
+179
View File
@@ -0,0 +1,179 @@
import { describe, expect, it } from "vitest";
import {
shrinkOversizedToolCallArgsByTokens,
shrinkOversizedToolResultsByTokens,
} from "../src/loop.js";
import { countTokens } from "../src/tokenizer.js";
import type { ChatMessage } from "../src/types.js";
describe("shrinkOversizedToolResultsByTokens", () => {
it("leaves small tool messages alone", () => {
const msgs: ChatMessage[] = [
{ role: "user", content: "hi" },
{ role: "tool", tool_call_id: "t1", content: "short" },
];
const r = shrinkOversizedToolResultsByTokens(msgs, 1000);
expect(r.healedCount).toBe(0);
expect(r.tokensSaved).toBe(0);
expect(r.messages).toEqual(msgs);
});
it("shrinks tool messages that exceed the token budget", () => {
const huge = "some event detail line with words\n".repeat(1000);
const msgs: ChatMessage[] = [
{ role: "user", content: "do stuff" },
{ role: "tool", tool_call_id: "t1", content: huge },
];
const r = shrinkOversizedToolResultsByTokens(msgs, 500);
expect(r.healedCount).toBe(1);
expect(r.tokensSaved).toBeGreaterThan(0);
expect(r.charsSaved).toBeGreaterThan(0);
const toolMsg = r.messages.find((m) => m.role === "tool");
const shrunk = typeof toolMsg?.content === "string" ? toolMsg.content : "";
// Final token count stays reasonably near the cap (plus marker
// overhead from truncateForModelByTokens).
expect(countTokens(shrunk)).toBeLessThanOrEqual(600);
});
it("never mutates the input array", () => {
const big = "line of text with content\n".repeat(800);
const msgs: ChatMessage[] = [{ role: "tool", tool_call_id: "t1", content: big }];
const original = msgs[0]!.content;
shrinkOversizedToolResultsByTokens(msgs, 200);
expect(msgs[0]!.content).toBe(original);
});
it("does not touch user or assistant messages even when long", () => {
const bigUser = "user-intent prose ".repeat(2000);
const msgs: ChatMessage[] = [
{ role: "user", content: bigUser },
{ role: "assistant", content: "ok" },
];
const r = shrinkOversizedToolResultsByTokens(msgs, 100);
expect(r.healedCount).toBe(0);
expect(r.messages[0]!.content).toBe(bigUser);
});
it("caps CJK tool results at the same token budget as English", () => {
// Under the old char cap, CJK text slipped through at ~2× the
// intended token cost. With a token cap, both must converge.
const cjk = "错误:步骤执行失败需要复查\n".repeat(1000);
const msgs: ChatMessage[] = [{ role: "tool", tool_call_id: "t1", content: cjk }];
const r = shrinkOversizedToolResultsByTokens(msgs, 500);
expect(r.healedCount).toBe(1);
const shrunk = typeof r.messages[0]!.content === "string" ? r.messages[0]!.content : "";
expect(countTokens(shrunk)).toBeLessThanOrEqual(600);
});
it("fast-pathes tool messages whose content length is already below the budget", () => {
// Every token is ≥1 char, so length <= maxTokens implies tokens
// <= maxTokens — no tokenize call needed, message untouched.
const content = "x".repeat(50);
const msgs: ChatMessage[] = [{ role: "tool", tool_call_id: "t1", content }];
const r = shrinkOversizedToolResultsByTokens(msgs, 100);
expect(r.healedCount).toBe(0);
expect(r.messages[0]!.content).toBe(content);
});
});
describe("shrinkOversizedToolCallArgsByTokens", () => {
it("leaves small tool-call args alone", () => {
const msgs: ChatMessage[] = [
{
role: "assistant",
content: null,
tool_calls: [
{
id: "c1",
type: "function",
function: { name: "read_file", arguments: '{"path":"src/foo.ts"}' },
},
],
},
];
const r = shrinkOversizedToolCallArgsByTokens(msgs, 1000);
expect(r.healedCount).toBe(0);
expect(r.messages).toEqual(msgs);
});
it("shrinks long edit_file search/replace payloads into markers", () => {
const longSearch = "old code line\n".repeat(200);
const longReplace = "new code line\n".repeat(300);
const argsJson = JSON.stringify({
path: "src/foo.ts",
search: longSearch,
replace: longReplace,
});
const msgs: ChatMessage[] = [
{
role: "assistant",
content: null,
tool_calls: [
{ id: "c1", type: "function", function: { name: "edit_file", arguments: argsJson } },
],
},
{ role: "tool", tool_call_id: "c1", content: "applied" },
];
const r = shrinkOversizedToolCallArgsByTokens(msgs, 500);
expect(r.healedCount).toBe(1);
expect(r.tokensSaved).toBeGreaterThan(0);
expect(r.charsSaved).toBeGreaterThan(0);
const a = r.messages[0];
if (a?.role !== "assistant" || !a.tool_calls) throw new Error("assistant missing");
const shrunkArgs = a.tool_calls[0]!.function.arguments;
const parsed = JSON.parse(shrunkArgs) as { path: string; search: string; replace: string };
expect(parsed.path).toBe("src/foo.ts");
expect(parsed.search).toMatch(/shrunk/);
expect(parsed.replace).toMatch(/shrunk/);
});
it("leaves tool results intact (only targets assistant.tool_calls args)", () => {
const hugeResult = "log line ".repeat(2000);
const msgs: ChatMessage[] = [{ role: "tool", tool_call_id: "c1", content: hugeResult }];
const r = shrinkOversizedToolCallArgsByTokens(msgs, 100);
expect(r.healedCount).toBe(0);
expect(r.messages[0]!.content).toBe(hugeResult);
});
it("preserves short string fields next to long ones", () => {
const longBody = "x".repeat(4000);
const argsJson = JSON.stringify({
path: "src/foo.ts",
content: longBody,
mode: "append",
});
const msgs: ChatMessage[] = [
{
role: "assistant",
content: null,
tool_calls: [
{ id: "c1", type: "function", function: { name: "write_file", arguments: argsJson } },
],
},
];
const r = shrinkOversizedToolCallArgsByTokens(msgs, 500);
expect(r.healedCount).toBe(1);
const a = r.messages[0];
if (a?.role !== "assistant" || !a.tool_calls) throw new Error("assistant missing");
const parsed = JSON.parse(a.tool_calls[0]!.function.arguments) as Record<string, unknown>;
expect(parsed.path).toBe("src/foo.ts");
expect(parsed.mode).toBe("append");
expect(String(parsed.content)).toMatch(/shrunk/);
});
it("never mutates the input array or its tool_calls", () => {
const bigArgs = JSON.stringify({ path: "a", search: "x".repeat(4000) });
const msgs: ChatMessage[] = [
{
role: "assistant",
content: null,
tool_calls: [
{ id: "c1", type: "function", function: { name: "edit_file", arguments: bigArgs } },
],
},
];
const originalArgs = (msgs[0] as any).tool_calls[0].function.arguments;
shrinkOversizedToolCallArgsByTokens(msgs, 100);
expect((msgs[0] as any).tool_calls[0].function.arguments).toBe(originalArgs);
});
});
+115
View File
@@ -3,11 +3,20 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import {
addProjectShellAllowed,
editModeHintShown,
isPlausibleKey,
loadApiKey,
loadEditMode,
loadProjectShellAllowed,
loadReasoningEffort,
markEditModeHintShown,
readConfig,
redactKey,
saveApiKey,
saveEditMode,
saveReasoningEffort,
searchEnabled,
writeConfig,
} from "../src/config.js";
@@ -15,12 +24,15 @@ describe("config", () => {
let dir: string;
let path: string;
const originalEnv = process.env.DEEPSEEK_API_KEY;
const originalSearch = process.env.REASONIX_SEARCH;
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), "reasonix-test-"));
path = join(dir, "config.json");
// biome-ignore lint/performance/noDelete: the string "undefined" leaks into process.env otherwise
delete process.env.DEEPSEEK_API_KEY;
// biome-ignore lint/performance/noDelete: same reason
delete process.env.REASONIX_SEARCH;
});
afterEach(() => {
@@ -31,6 +43,12 @@ describe("config", () => {
} else {
process.env.DEEPSEEK_API_KEY = originalEnv;
}
if (originalSearch === undefined) {
// biome-ignore lint/performance/noDelete: same reason
delete process.env.REASONIX_SEARCH;
} else {
process.env.REASONIX_SEARCH = originalSearch;
}
});
it("readConfig returns {} when file is missing", () => {
@@ -106,4 +124,101 @@ describe("config", () => {
const loaded = readConfig(path);
expect(loaded.session).toBeNull();
});
it("searchEnabled defaults to true with no config and no env", () => {
expect(searchEnabled(path)).toBe(true);
});
it("searchEnabled honours `search: false` in the config file", () => {
writeConfig({ apiKey: "sk-test123abcdefghijkl", search: false }, path);
expect(searchEnabled(path)).toBe(false);
});
it("searchEnabled honours REASONIX_SEARCH=off/false/0", () => {
process.env.REASONIX_SEARCH = "off";
expect(searchEnabled(path)).toBe(false);
process.env.REASONIX_SEARCH = "false";
expect(searchEnabled(path)).toBe(false);
process.env.REASONIX_SEARCH = "0";
expect(searchEnabled(path)).toBe(false);
});
it("searchEnabled stays true for unrelated env values", () => {
process.env.REASONIX_SEARCH = "on";
expect(searchEnabled(path)).toBe(true);
});
it("env off beats config true", () => {
writeConfig({ apiKey: "sk-test123abcdefghijkl", search: true }, path);
process.env.REASONIX_SEARCH = "off";
expect(searchEnabled(path)).toBe(false);
});
it("loadProjectShellAllowed returns [] when nothing stored", () => {
expect(loadProjectShellAllowed("/some/project", path)).toEqual([]);
});
it("addProjectShellAllowed persists and dedups per project", () => {
addProjectShellAllowed("/a", "npm install", path);
addProjectShellAllowed("/a", "git commit", path);
addProjectShellAllowed("/a", "npm install", path); // dedup
addProjectShellAllowed("/b", "cargo add", path);
expect(loadProjectShellAllowed("/a", path)).toEqual(["npm install", "git commit"]);
expect(loadProjectShellAllowed("/b", path)).toEqual(["cargo add"]);
});
it("addProjectShellAllowed ignores empty / whitespace prefixes", () => {
addProjectShellAllowed("/a", "", path);
addProjectShellAllowed("/a", " ", path);
expect(loadProjectShellAllowed("/a", path)).toEqual([]);
});
it("loadEditMode defaults to 'review' when unset", () => {
expect(loadEditMode(path)).toBe("review");
});
it("saveEditMode + loadEditMode round-trip 'auto'", () => {
saveEditMode("auto", path);
expect(loadEditMode(path)).toBe("auto");
// Doesn't clobber other fields in the config.
expect(readConfig(path).editMode).toBe("auto");
});
it("loadEditMode coerces unknown values back to 'review'", () => {
writeConfig({ editMode: "garbage" as any }, path);
expect(loadEditMode(path)).toBe("review");
});
it("loadReasoningEffort defaults to 'max' when unset", () => {
expect(loadReasoningEffort(path)).toBe("max");
});
it("saveReasoningEffort + loadReasoningEffort round-trip 'high'", () => {
saveReasoningEffort("high", path);
expect(loadReasoningEffort(path)).toBe("high");
expect(readConfig(path).reasoningEffort).toBe("high");
});
it("loadReasoningEffort coerces unknown values back to 'max'", () => {
writeConfig({ reasoningEffort: "turbo" as any }, path);
expect(loadReasoningEffort(path)).toBe("max");
});
it("saveReasoningEffort doesn't clobber other persisted fields", () => {
saveEditMode("auto", path);
saveReasoningEffort("high", path);
expect(loadEditMode(path)).toBe("auto");
expect(loadReasoningEffort(path)).toBe("high");
});
it("editModeHintShown defaults to false and toggles on markEditModeHintShown", () => {
expect(editModeHintShown(path)).toBe(false);
markEditModeHintShown(path);
expect(editModeHintShown(path)).toBe(true);
// Idempotent — calling again doesn't rewrite or clobber other fields.
saveEditMode("auto", path);
markEditModeHintShown(path);
expect(editModeHintShown(path)).toBe(true);
expect(loadEditMode(path)).toBe("auto");
});
});
Loaded 100 of 137 files, more files were not shown because too many files have changed in this diff. Show more