SLOPSHOPPER

Claude DevTools

A debugger for Claude Code tool calls: breakpoints, pause/continue/reject/step, a timeline, an inspector, Error Lens failure diagnosis, a Permissions view of…

panebandrowsguardcommandtoast
★ 2v0.2.1MITupdated 2026-10-12NMenzel/claude-devtools-mod
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · devtools
│ ┃ Claude DevTools ✕ › fix the failing auth test and add an audit log call │ ┃ CLAUDE DEVTOOLS · ● active · ○ not recording │ ┃ ■ ok ■ failed ■ denied ■ simulated ■ pau ● devtools: devtools: recording Read failed: undefined is not an obje │ ┃ d: Dashboard t: Timeline i: Inspector b: ● devtools: devtools: recording Grep failed: undefined is not an obje │ ┃ ⏺ Read(src/auth.ts) │ ┃ REFUSED CALLS · none this session ⎿ Read 6 lines │ ┃ RULES · 0 · default mode default (not set) · ⟨Claude Code's own drawing⟩ │ ┃ No allow, ask or deny rules in any setting break on ○ Edit ○ src/auth.ts │ ┃ ⏺ Bash(bun test) │ ┃ r: Reload rules c: Clear refused ✔ confirm ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /devtools │ ⎿ devtools: Claude DevTools is open. Keys: d t i b e a switch tabs │ ● devtools: devtools: recording Edit failed: undefined is not an obje │ ● devtools: devtools: recording Write failed: undefined is not an obj │ │ ⟨Claude Code's own drawing⟩ DevTools … Bash cat .env · break on t: ○ Bash c: ○ "cat" d: DevTools x: hide · /bp <rule> ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
⟨Claude Code's own drawing⟩ DevTools … Bash cat .env · break on t: ○ Bash c: ○ "cat" d: DevTools x: hide · /bp <rule>
Pane · Claude DevTools
CLAUDE DEVTOOLS · ● active · ○ not recording · 0 breakpoints ■ ok ■ failed ■ denied ■ simulated ■ paused d: Dashboard t: Timeline i: Inspector b: Breakpoints e: REFUSED CALLS · none this session RULES · 0 · default mode default (not set) · read 08:53… No allow, ask or deny rules in any settings file. r: Reload rules c: Clear refused ✔ confirmed · ? possible
Tool row
⟨Claude Code's own drawing⟩ break on ○ Edit ○ src/auth.ts
README

<img src="docs/media/banner.svg" alt="Claude DevTools: a paused git push at a breakpoint, and a failed Write with a why? link" width="720">

<h1 align="center">Claude DevTools</h1>

<strong>Breakpoints for your coding agent. Stop it before it runs <code>git push</code>. See why its last call failed.</strong>

<sub>A Claude Code mod that works like a debugger for tool calls: breakpoints on tools, commands, files and errors · Continue, Step and Reject · a live dashboard · Error Lens failure diagnosis. Everything stays on your machine.</sub>

<a href="https://github.com/NMenzel/claude-devtools-mod/stargazers"><img src="https://img.shields.io/github/stars/NMenzel/claude-devtools-mod?style=flat-square&color=yellow&label=stars" alt="GitHub stars"></a>&nbsp; <a href="https://github.com/NMenzel/claude-devtools-mod/releases/latest"><img src="https://img.shields.io/github/v/release/NMenzel/claude-devtools-mod?style=flat-square&label=version&color=blue" alt="Latest release"></a>&nbsp; <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-green?style=flat-square" alt="License: MIT"></a>&nbsp; <a href="https://claude.com/blog/claude-code-mods"><img src="https://img.shields.io/badge/Claude%20Code-2.1.294%2B%20mod-d97757?style=flat-square" alt="Claude Code 2.1.294+ mod"></a>&nbsp; <img src="https://img.shields.io/badge/surfaces-terminal%20%7C%20desktop-lightgrey?style=flat-square" alt="Surfaces: terminal and desktop">

<a href="#install">Install</a> · <a href="#use-it">Use it</a> · <a href="#error-lens-why-a-tool-call-failed">Error Lens</a> · <a href="#commands">Commands</a> · <a href="#options">Options</a> · <a href="docs/SECURITY.md">Security</a>

<img src="docs/media/demo.gif" alt="Claude DevTools in a live session: /devtools-break command git push sets a breakpoint, Claude's git push is held and rejected, and the Error Lens tab explains what happened" width="900">


The problem

Claude Code acts on its own, one tool call after another. Permission rules decide whether a call may run. They don't let you stop the agent at a point you choose, look at what it is about to do, and step through it.

  • No breakpoints. You can't say "stop before any npm publish", "stop whenever it touches src/auth/**" or "stop on the next call after a failure", then decide with the full call in front of you.
  • Failures are one line. EPERM: operation not permitted scrolls past. Was the file locked? Did the parent folder exist? Did the write land anyway? Claude retries, and you guess.
  • No record. What ran, in what order, which permission rule applied, and what failed is spread across the scrollback.

The solution

Claude DevTools is a debugger for the agent's tool level, built on Claude Code's native Mods API.

In Claude Code todayWith Claude DevTools
A permission prompt per call, allow or denyBreakpoints on tools, command patterns, path globs and failures. Continue, Step (pause on the next call too) or Reject with a note Claude reads
Bash(npm test) in the transcriptA "break on" gutter under every tool row, like clicking a line number in Chrome DevTools, plus a one-key bar above the prompt
Error: EPERM: operation not permittedError Lens: the kind of failure, what is ✔ confirmed, ? possible or · unknown, each with its evidence, read-only file checks, and fixes to try
The same error, again and againRepeats grouped and counted. A notification for the first, then every fifth
ScrollbackA timeline and inspector: status, duration, agent, permission verdict and breakpoint of every call
Copying from the terminalSanitized exports, versioned JSON and Markdown, with secrets redacted and file contents omitted

Native mod. No wrappers, no API keys, no network calls, no model calls. Two commands to install.

It works at the tool level only. It does not show hidden reasoning, model internals or token-level steps. It sees what the Mods API exposes: each tool call's name, arguments, agent, permission verdict and result. It never approves anything: Claude Code's permission rules still decide after you press Continue.

[!TIP] If Claude DevTools saves you a bad git push or an hour of guessing at an error, a ⭐ on the repo helps other developers find it.

Claude DevTools is a community project. It is not made or endorsed by Anthropic.

Requirements

  • Claude Code with Mods support. Built and tested on 2.1.294 (Windows 10). Mods need 2.1.287 or later, and builds older than 2.1.294 are untested.
  • The pane draws in the terminal and in the Code tab of Claude Desktop. In the VS Code chat panel and in claude -p the hooks run but nothing is drawn; use the /devtools-* commands there.

Install

Inside Claude Code:

/plugin marketplace add NMenzel/claude-devtools-mod
/plugin install devtools@claude-devtools-mod
/reload-plugins
/devtools

Or from a terminal, in one command (it adds the marketplace too):

claude plugin install devtools --marketplace NMenzel/claude-devtools-mod

Then run /reload-plugins in an open session, or start a new one, and run /devtools.

The installer may say config options aren't set. The defaults are fine, and /config changes them. Mods are an early-access Claude Code feature, and their API can change between releases.

Check that it loaded: run /plugin and look for devtools in the mods active line. You can also run /devtools-help.

To update: claude plugin update devtools@claude-devtools-mod. To remove: claude plugin uninstall devtools@claude-devtools-mod.

Install with Claude

Paste this into Claude Code:

Install the Claude DevTools mod for Claude Code from
https://github.com/NMenzel/claude-devtools-mod. Follow the
"Instructions for agents" in its README, then tell me what to run next.
Instructions for agents

If you are an AI agent installing Claude DevTools for a user, follow these steps.

  1. Check the version. Run claude --version. Claude Code 2.1.287 or later supports mods, and Claude DevTools is tested on 2.1.294. If the version is older, stop and tell the user to update Claude Code (claude update).
  2. Install, without prompts: ``sh claude plugin install devtools --marketplace NMenzel/claude-devtools-mod --json ` This adds the marketplace to the user's settings and installs at user scope. Exit code 0 means it is installed. To share it with everyone working in the current repository, add --scope project (it is then recorded in .claude/settings.json`). Ask the user before using a scope other than the default.
  3. Options are optional. The defaults suit most users. Set an option only if the user asked for it, with --config <option>=<value> on the install command. Examples: --config errorLens=classify (no file checks), --config openOnStart=false. All options are listed under Options.
  4. Verify: claude plugin list --json includes devtools@claude-devtools-mod.
  5. Hand over to the user. An agent cannot activate a mod inside the user's running session. Tell the user to run /reload-plugins, then /devtools. A newly started session loads the mod by itself.

Notes for agents:

  • Nothing needs to be built, and it needs no npm packages, global installs or sudo. Do not clone the repository to install it.
  • The mod makes no network or model calls, and it never approves a tool call. It does not change the user's permission settings.
  • To test it headlessly: claude -p "/devtools-help" prints the help without a model call. In Git Bash on Windows, prefix MSYS_NO_PATHCONV=1 so the shell does not turn /devtools-help into a path.

Use it

/devtools-break command npm install        # pause before any `npm install`
/bp command git push                       # the same, short: /bp is /devtools-break
/devtools-break file src/auth/**           # pause before reading/editing auth code
/devtools-break tool Write,Edit --action warn
/devtools-break error Bash --action pause   # after a failed Bash call, pause the next call
/devtools                                   # open the pane

When a call matches a pause breakpoint, Claude Code shows a DevTools question with:

| Choice | What happens | | - | - | | Continue | The call goes on through Claude Code's normal permission checks and runs. | | Step | Same as Continue. Then the next tool call pauses too, one tool call at a time. | | Reject | The tool does not run. Claude is told the developer rejected it and to choose another approach. | | Simulate | Only offered when the simulation option is on. The tool does not run. Claude gets a clearly labeled synthetic result (see below). | | typed text | Rejects the call and passes your text to Claude as a note ("use pnpm instead"). | | Esc / Chat about this | Rejects the call ("dismissed"). |

The question dialog is the control for a held call. It holds the call inside Claude Code's own dialog, so the wait never times out the hook.

Set breakpoints where the calls are (Chrome DevTools style)

There are three ways to set a breakpoint without typing a rule.

  • The transcript gutter. Under every tool row (Bash(npm test), Read(src/auth/login.ts), a folded "Read 3 files, searched 2 patterns" line) sits one dim line: break on ○ Bash ○ "npm test" ○ src/x.ts. Press one to set a pause breakpoint on that tool, that command (program and subcommand), or that path. Press it again to remove it. A row that a breakpoint covers gets a red ● breakpoint bp1 … line. Clicks need a pointer (the fullscreen terminal or Claude Desktop); the bar below works by keyboard everywhere. Set inlineControls to hover to show the controls only while the pointer is over a row, or off.
  • The bar above the prompt. It shows the latest call: DevTools ✓ Bash git push origin main · break on ○ Bash ○ "git push" · DevTools · hide. Press ctrl+x tab to focus it, then t for the tool, c for the command, f for the path, d to open the dashboard and x to hide it. When that call failed, e (✗ why?) opens its Error Lens. A dim hint at its end names /bp <rule> and /devtools-help. The bar never wraps: when the line is narrow, the hint, the call's summary, DevTools and hide give way in that order, and the breakpoint keys and why? stay. Before the first tool call the bar is the hint alone. This works on every terminal layout, keyboard only.
  • Category toggles, like Chrome's event-listener breakpoints: pause on ■ Shell □ Read □ Search □ Edit □ Web □ Agents. They are on the dashboard and the Breakpoints tab, and each one adds or removes a tool breakpoint for the whole family.

The Inspector has the same break on buttons for any recorded call, on keys 1 2 3.

The dashboard

/devtools opens the dashboard, a live pane of bordered panels. It also opens by itself when an interactive session starts in a terminal at least 144 columns wide (set openOnStart to false to stop that).

  • Header: CLAUDE DEVTOOLS · ● active · ⏺ recording · 3 breakpoints · ⏸ 1 paused, and a color legend (ok, failed, denied, simulated, paused).
  • PAUSED / ARMED: each held call with its tool, summary, breakpoint and time held. When pause-next or step is armed, a Disarm button.
  • BREAKPOINTS: the category toggles, every rule with its state, match, action and hit count (press a rule to enable or disable it), and the totals.
  • CALLS: one colored cell per call (green ok, red failed, amber denied, purple simulated), the totals, and counts per family (shell, read, search, edit, web, mcp).
  • ERRORS (only after a failure): the latest kinds of failure, repeats counted (✗ 3× Bash · exit-code · npm ERR! …). Press one to open its Error Lens.
  • REFUSED (only after a refusal): the latest three refused calls and who refused each (✗ Bash rm -rf build · by mod blast-radius (append tier)). Press one to open its detail.
  • TIMELINE: the newest calls. Press one to inspect it.
  • Actions: p pause next call, r recording, m cycle mode, s export.

Times are UTC, as a mod's environment has no time zone: a list says so once in its header, and a time on its own ends in UTC.

Docked from 110 columns it lays out two columns (rules and calls on the left, the timeline on the right). Narrower, it stacks. Inline above the prompt (main-screen terminal) it is a three-line summary.

The tabs (d t i b e a; ctrl+x tab focuses the pane, Tab walks its controls):

  • Dashboard: as above.
  • Timeline: newest-first tool calls with status, tool, duration and summary. A ● marks calls that matched a breakpoint. j/k page, x clear. Press a row to inspect it, or the why? beside a failed row to open its Error Lens.
  • Inspector: the selected call's id, session, agent, timestamps, risk, permission verdict, breakpoint and decision, synthetic flag, result, error, and redacted input (JSON). break on buttons on 1/2/3, h/l older/newer, and on a failed call w "Why it failed".
  • Breakpoints: the mode picker, the category toggles, each rule with Enable/Disable and Delete, and a field that adds a rule in the same language as /devtools-break.
  • Errors: Error Lens (below). The tab label counts the failures kept.
  • Permissions: each refused call with who refused it and why, then your permission rules by settings file (below). The tab label counts the refused calls.

Error Lens: why a tool call failed

Error Lens watches every tool call that fails (Bash, PowerShell, Read, Write, Edit, Grep, Glob, web and MCP tools) and explains the failure from evidence. It is passive: it never retries a call, changes a result, asks a model or interrupts you, and its file checks run after the result has gone back to Claude. It is on by default (errorLens).

For each failure it keeps:

  • the original error, as Claude read it (redacted, up to 3,000 characters), with its code (ENOENT, EACCES, EPERM, ...) or shell exit code;
  • the call: the arguments (sanitized, file contents omitted), the agent, the duration and the permission verdict;
  • a category: not-found, access-denied, not-permitted, busy, stale-read (the file changed since Claude read it), not-read-yet, edit-mismatch, timeout, command-not-found, exit-code, network, mcp, permission-denied, blocked-by-hook, input-invalid, too-large, unknown, and more;
  • causes, sorted by certainty:
  • ✔ CONFIRMED: the result text, a permission verdict or a file check shows it. The evidence (the quoted line, the verdict, the observed file) is shown under it.
  • ? POSSIBLE: a known explanation the evidence does not prove (another program holding the file, CRLF line endings, a sandbox).
  • · UNKNOWN: what cannot be determined from here (which hook refused, permission bits, which process changed a file). When no signature matches, it says the cause is unknown. It never guesses past the evidence.
  • read-only checks (the probe mode, the default): after the result has gone back to Claude, one stat per path. It checks the target file, its parent folder and paths the error names: whether each exists, what kind it is, its size, its modification time and whether it is a link. So it can say "the parent directory /work/new does not exist", or that a Write reported an error but the file changed during the call and has exactly the intended size, so the write may have landed. It never reads file contents.
  • fixes to try, as a numbered list.

Repeats of one failure (same tool, kind and message with paths and numbers masked) are grouped and counted. A one-line notification announces the first failure of each kind and then every fifth repeat: DevTools ✗ Read failed (not-found): ENOENT: no such file … · /devtools-errors to inspect. DevTools' own refusals, simulations and interrupted calls are kept but never announced.

Ways to reach it: the Errors tab (e), the dashboard's ERRORS panel, why? on a failed timeline row, w in the Inspector, e on the bar above the prompt, or /devtools-errors, which prints the same report as text and works headless too. /devtools-errors clear empties it. Exports include every Error Lens record and group, and the Markdown report has an Error Lens section.

An MCP tool that reports success but whose output begins like an error (Error: …; some servers answer errors as plain text) is kept as suspected, with its cause marked possible. Built-in tools flag their own errors, so they are never judged this way.

Permissions: who refused a call, and why

The Permissions tab (a) answers "why couldn't the agent run that?". For each refused call, newest first, it shows the call, who refused it and the exact reason Claude was given:

| Refused by | How DevTools knows | | - | - | | a permission rule, with its settings file (Bash(rm -rf:*) in .claude/settings.json) | the permission check's verdict names the rule | | the permission mode (plan, dontAsk, auto) | the verdict names no rule, and its reason names the mode | | you, at the permission prompt | the rejection Claude Code sends back | | a settings hook (PreToolUse) | the verdict names the hook | | another mod, by name and tier (blast-radius (user tier)) | Claude Code's call chain names the plugin that returned the refusal | | Claude DevTools itself (Reject, headless, guard) | its own record |

Each attribution is ✔ confirmed when the verdict or the call chain shows it. A mod seated before DevTools in the chain refuses before DevTools' hook runs. DevTools still catches that refusal, from the tool result Claude Code stores, shows the command it refused (read from Claude's request), and marks the mod ? possible, read from the refusal's own words (blast-radius: … or [blast-radius] …). Press a call to open its Error Lens, which names the mod too.

Which of two installed mods comes first is Claude Code's choice: both sit in the user tier, and a mod cannot move itself. So a mod you installed, such as Blast Radius, may well sit before DevTools, and its refusals are then named as possible, never confirmed. A mod that starts its refusals with its plugin name (blast-radius: …) is named by that name rather than a display name.

Below the calls are your permission rules as each settings file holds them (managed policy, --settings, local, project, user): deny, ask and allow, each with its file, managed ones marked 🔒, the default mode and extra directories. They are read when the session starts and each time you open the tab or press Reload (r). DevTools only reads them; it never changes a setting.

/devtools-permissions (or /bpp) prints the same as text, every rule and every refused call with its evidence, and works headless. /devtools-permissions clear empties the refused list.

Commands

| Command | Does | | - | - | | /devtools | Open the pane (in a headless session: print the status) | | /devtools-status | Debugger state and the last few events, as text | | /devtools-break <rule> | Add a breakpoint. /devtools-break delete <id>, toggle <id>, enable <id>, disable <id>, clear | | /devtools-list | List breakpoints with ids and hit counts | | /devtools-pause | Pause on the next tool call | | /devtools-continue | Disarm pause-next and stepping (a call already held is answered in its dialog) | | /devtools-disable [observe\|off] | observe (default): breakpoints record but never pause. off: no interception, no recording | | /devtools-enable | Back to active: breakpoints pause | | /devtools-record [on\|off] | Record every call, or only breakpoint matches | | /devtools-errors [clear] | Error Lens: the failure kinds this session and the latest failure's diagnosis. Opens the Errors tab when interactive | | /devtools-permissions [clear] | Your permission rules by settings file, and each refused call: who refused it, why, and the evidence. Opens the Permissions tab when interactive | | /devtools-export [path.json\|path.md] [--md] | Write a sanitized JSON trace (and a Markdown report). Default: .claude-devtools/trace-<time>.json in the working directory | | /devtools-help | Usage and the rule language | | /bp <rule> | Short for /devtools-break; /bp alone lists the breakpoints and the rule language | | /bpl · /bpn · /bpc · /bpe · /bpp | Short for /devtools-list, /devtools-pause (next call), /devtools-continue, /devtools-errors and /devtools-permissions |

All of these run immediately, even while Claude is working. They answer you alone: typed, from Remote Control, from the SDK host, your own Slack ping, or a follow-up to your own action in the UI. Started by another session, a channel, a schedule or another mod, every one of them is refused, so nothing else can switch off your breakpoints, open the pane under your typing, or read your rules and refused calls out. A run Claude Code cannot attribute to anyone (unclassified) is refused too, with a pointer to the prompt and the pane, which always work.

Rule language

tool <Name>[,<Name>...]            every call to these tools (MCP tools by full name: mcp__github__create_issue)
command <pattern>                  shell command contains the words, in order; * is a wildcard; re:<regex> for a regex
file <glob>                        a call names a matching path: src/auth/**, prisma/schema.prisma, .env*
error [<Tool>,...]                 after a failed call (default action warn; --action pause arms the next call)
when tool=A,B command=".." path=.. all given conditions must match

--action pause|record|warn   --scope all|main|subagents   --name "..."
--after <N>   act from the Nth hit (hit counts reset each session)
--simulate fail|stub  --text "..."   what Simulate answers at this breakpoint
--disabled

Path globs are case-insensitive whenever either side is a Windows path. A glob with no / matches any path segment. A relative glob matches below the working directory or at any directory boundary. A glob under your home folder matches however either side spells it: ~/.ssh/** matches /home/me/.ssh/id_rsa, /Users/me/.ssh/config, C:\Users\me\.ssh\id_rsa and cat ~/.ssh/id_rsa, as do $HOME/ and %USERPROFILE%\.

Simulation (opt-in)

Simulation is off by default. Turn on the simulation option first. Simulate then appears only for allowlisted tools (Bash, PowerShell, Read, Edit, Write, NotebookEdit, Glob, Grep, WebFetch, WebSearch, and MCP tools):

  • fail (default): the call is refused with [Claude DevTools · SIMULATED FAILURE] <text> The <tool> call was NOT executed, so nothing changed.
  • stub: only for shell commands classified read-only. It returns stdout starting with [Claude DevTools · SIMULATED OUTPUT: the command was NOT executed].

A simulated call never reaches the real tool. The timeline, inspector and exports mark it simulated.

Headless (claude -p, SDK)

Nobody can answer a question there, so nothing waits. A call that matches a pause breakpoint is rejected with an explanation, and calls that match nothing run normally. To record such calls and let them through instead, set headlessPause to record-only.

Options

Set them in /config, or at install time with claude plugin install ... --config <option>=<value>:

| Option | Default | Meaning | | - | - | - | | recording | true | Record every call (until a saved preference exists) | | maxTimelineEntries | 500 | Ring buffer size, 10 to 5000 | | maxSummaryChars | 160 | Longest input/result summary, 40 to 2000 | | defaultScope | all | Scope of new rules: all, main or subagents | | headlessPause | reject | `rej

Source 19 files
hooks/register.tsx 1486 lines
1// Claude DevTools: the native Mod layer. It connects the pure engine in src/
2// to Claude Code's events: it holds tool calls at breakpoints through the
3// engine's own question dialog, records what really ran, draws the pane and
4// answers the /devtools commands. Decisions live in src/core; this file acts.
5//
6// The engine requires `$` to be passed only to functions declared at the top
7// of this file, so every helper that touches the API lives here, and the
8// options `register` receives are kept in module variables.
9
10import { atom, read, update } from 'claude-code'
11import type { EngineInterface, PromptOrigin, Register, TraceEntry } from 'claude-code'
12
13import type {
14  ArmState,
15  Breakpoint,
16  Denial,
17  DevtoolsMode,
18  DevtoolsSettings,
19  DevtoolsStats,
20  ErrorCategory,
21  LensProbe,
22  PauseDecision,
23  PendingCall,
24  PermissionInfo,
25  PermissionsSnapshot,
26  Refusal,
27  SettingsSourceName,
28  TraceEvent,
29  TraceOutcome,
30  TraceStatus,
31  ViewState,
32} from '../types'
33import { DEFAULT_OPTIONS, defaultSettings, type DevtoolsOptions, parseOptions, parsePersisted, STORE_KEY, toPersisted } from '../src/config/schema.ts'
34import {
35  criteriaMatch,
36  describeBreakpoint,
37  evaluateCall,
38  evaluateError,
39  nextBreakpointId,
40  parseBreakpointSpec,
41  SPEC_HELP,
42  validateBreakpoint,
43} from '../src/core/breakpoints.ts'
44import {
45  classifyResult,
46  type Counted,
47  counted,
48  DISARMED,
49  interpretAnswer,
50  type Planned,
51  pauseQuestion,
52  planAfterError,
53  planCall,
54  refusalText,
55  wouldPause,
56} from '../src/core/controller.ts'
57import {
58  asRecord,
59  clock,
60  errorTextOf,
61  normalizeCall,
62  type NormalizedCall,
63  rawOf,
64  type ResultLike,
65  sanitizeInput,
66  type SummaryOptions,
67  summarizeInput,
68  summarizeResult,
69  type ToolCallLike,
70  truncate,
71} from '../src/core/events.ts'
72import {
73  addToGroups,
74  buildLensRecord,
75  errorTextOfResult,
76  lensReport,
77  looksLikeFailure,
78  MAX_LENS,
79  type ProbeTarget,
80  shouldNotify,
81  withProbes,
82} from '../src/core/lens.ts'
83import {
84  appendBounded,
85  buildExport,
86  closeStale,
87  exportPaths,
88  exportToMarkdown,
89  formatDuration,
90  patchEvent,
91  serializeExport,
92  statusIcon,
93} from '../src/core/recorder.ts'
94import {
95  addDenial,
96  callDenier,
97  checkVerdict,
98  explainRefusal,
99  isEngine,
100  permissionsReport,
101  readPermissions,
102  SOURCES,
103  UNREAD_PERMISSIONS,
104  unseenRefusals,
105} from '../src/core/permissions.ts'
106import { checkSimulation, synthesize } from '../src/core/simulation.ts'
107import { type Category, findCategoryRule, findRule, type Suggestion, suggestBreakpoints, withHits } from '../src/core/suggest.ts'
108import { redactString } from '../src/security/redaction.ts'
109import { type Offer, renderBar, renderGutter } from '../src/ui/inline.tsx'
110import type { Layout } from '../src/ui/model.ts'
111import { type PaneActions, renderPane } from '../src/ui/pane.tsx'
112
113const VERSION = '0.2.1'
114const PANE = 'devtools'
115
116// The $.state values kept for the session (declared in ../types/index.d.ts):
117// host-held, so they survive a hot reload of this module. Settings have no
118// static initial: never written means "load from the store first".
119const SETTINGS = { plugin: 'devtools', key: 'settings' } as const
120const ARM = { plugin: 'devtools', key: 'arm' } as const
121const ARM_ATOM = atom({ plugin: 'devtools', key: 'arm' } as const, DISARMED)
122const TRACE = atom({ plugin: 'devtools', key: 'trace' } as const, [])
123const PENDING = atom({ plugin: 'devtools', key: 'pending' } as const, [])
124const HITS = atom({ plugin: 'devtools', key: 'hits' } as const, {})
125const VIEW = atom({ plugin: 'devtools', key: 'view' } as const, { tab: 'dashboard', page: 0 })
126const SESSION = atom({ plugin: 'devtools', key: 'session' } as const, { sessionId: '', isInteractive: true, cwd: '', surface: null })
127const STATS = atom({ plugin: 'devtools', key: 'stats' } as const, {
128  observed: 0,
129  completed: 0,
130  failed: 0,
131  denied: 0,
132  simulated: 0,
133  paused: 0,
134})
135const LENS = atom({ plugin: 'devtools', key: 'lens' } as const, [])
136const GROUPS = atom({ plugin: 'devtools', key: 'errorGroups' } as const, [])
137const DENIALS = atom({ plugin: 'devtools', key: 'denials' } as const, [])
138const PERMISSIONS = atom({ plugin: 'devtools', key: 'permissions' } as const, UNREAD_PERMISSIONS)
139
140type Dollar = EngineInterface
141type ToolResult = { deny: string } | { result: unknown }
142type Held = { answer: ToolResult } | { decision: Extract<PauseDecision, 'continue' | 'step'>; permission?: PermissionInfo }
143
144const STATUS_COUNTER: Partial<Record<TraceStatus, keyof DevtoolsStats>> = {
145  completed: 'completed',
146  failed: 'failed',
147  denied: 'denied',
148  simulated: 'simulated',
149}
150
151// Set by `register`; a reload runs it again with the current options.
152let options: DevtoolsOptions = DEFAULT_OPTIONS
153let optionWarnings: string[] = []
154let summary: SummaryOptions = { maxChars: DEFAULT_OPTIONS.maxSummaryChars, redaction: true, captureRaw: false }
155// Snapshot for the .catch handler, which may not call $ on a re-entry and has
156// one second: the settings (hit counts as last counted), arm, cwd and whether
157// anyone can answer, as last read or written.
158const mirror: { settings?: DevtoolsSettings; arm?: ArmState; cwd?: string; isInteractive?: boolean } = {}
159
160/** What DevTools noted about a call its tool.call hook saw (or its guard refused). */
161type CallNote = {
162  /** The permission verdict tool.check reached, until the call finishes. */
163  verdict?: PermissionInfo
164  /** The rules with this call counted, until it is planned: the guard plans with them if the hook fails in between. */
165  counted?: Counted
166  /** Whether the call's own plan holds it: the guard's answer once the hook has planned. */
167  holds?: boolean
168  /** Refused by the .catch guard, which may not call $: recorded when its tool result is stored. */
169  isGuardRefused?: true
170}
171
172// Notes by tool_use_id, oldest first, at most 500: a refused tool result for a
173// call with no note was refused above DevTools.
174const notes = new Map<string, CallNote>()
175let localSeq = 0
176
177/** A call's note, made the first time it is needed; none without a tool_use_id. */
178function noteOf(toolUseId: string | undefined): CallNote | undefined {
179  if (toolUseId === undefined) return undefined
180  let found = notes.get(toolUseId)
181  if (found === undefined) {
182    for (const key of notes.keys()) {
183      if (notes.size < 500) break
184      notes.delete(key)
185    }
186    found = {}
187    notes.set(toolUseId, found)
188  }
189  return found
190}
191
192/** Keeps the verdict a real call reached, and the mod that set it if one changed it beneath this hook. */
193function noteVerdict(toolUseId: string | undefined, trace: readonly TraceEntry<'tool.check'>[]): void {
194  const verdict = checkVerdict(trace)
195  if (verdict === undefined) return
196  const note = noteOf(toolUseId)
197  if (note !== undefined) note.verdict = verdict
198}
199
200/** Whether a pause plan holds the call: headless with headlessPause record-only, it is recorded and let through. */
201function holds(isPause: boolean, isInteractive: boolean | undefined): boolean {
202  return isPause && (isInteractive !== false || options.headlessPause !== 'record-only')
203}
204
205/** Whether the guard holds a call whose hook failed: its own plan, else its counted rules, else the last snapshot. */
206function guardHolds(call: NormalizedCall): boolean {
207  const note = call.toolUseId === undefined ? undefined : notes.get(call.toolUseId)
208  if (note?.holds !== undefined) return note.holds
209  const isPause =
210    note?.counted !== undefined ? planCall(note.counted, mirror.arm ?? DISARMED, call, mirror.cwd).plan.kind === 'pause' : wouldPause(mirror.settings, mirror.arm, call, mirror.cwd)
211  return holds(isPause, mirror.isInteractive)
212}
213
214/** The .catch guard's refusal, noted so the call's tool result is recorded as DevTools' own. */
215function guardRefusal(call: ToolCallLike, reason: string): { deny: string } {
216  const note = noteOf(call.tool_use_id)
217  if (note !== undefined) note.isGuardRefused = true
218  return { deny: refusalText('guard', call.tool, reason) }
219}
220
221function message(error: unknown): string {
222  return error instanceof Error ? error.message : String(error)
223}
224
225function redactIf(text: string): string {
226  return options.redaction ? redactString(text) : text
227}
228
229function debug($: Dollar, text: string): void {
230  $.ui.log(`devtools: ${text}`, { to: 'debug' })
231}
232
233// ------------------------------------------------------------------ settings
234
235/**
236 * The session's rules (hit counts not merged); on first use (a new session,
237 * or after /clear) loaded from the store.
238 */
239async function loadSettings($: Dollar): Promise<DevtoolsSettings> {
240  const held = await $.state.get(SETTINGS)
241  if (held.value !== undefined) return held.value
242  let settings = defaultSettings(options)
243  if (options.persistBreakpoints) {
244    try {
245      const parsed = parsePersisted(await $.store.get(STORE_KEY), options)
246      settings = parsed.settings
247      for (const warning of parsed.warnings) debug($, warning)
248    } catch (error) {
249      debug($, `could not read saved settings: ${message(error)}`)
250    }
251  }
252  const written = await $.state.set(SETTINGS, settings, { ifVersion: held.version })
253  if (!written.isSet) settings = (await $.state.get(SETTINGS)).value ?? settings
254  return settings
255}
256
257/** The rules with this session's hit counts, as planning and display need them; also the guard's snapshot. */
258async function liveSettings($: Dollar): Promise<DevtoolsSettings> {
259  const [settings, hits] = await Promise.all([loadSettings($), read($, HITS)])
260  return (mirror.settings = withHits(settings, hits))
261}
262
263/** A person's change: written to the session and, when enabled, to the store. */
264async function changeSettings($: Dollar, change: (settings: DevtoolsSettings) => DevtoolsSettings): Promise<DevtoolsSettings> {
265  await loadSettings($)
266  const saved = await update($, SETTINGS, current => change(current ?? defaultSettings(options)))
267  mirror.settings = withHits(saved, await read($, HITS))
268  if (options.persistBreakpoints) {
269    try {
270      await $.store.set(STORE_KEY, toPersisted(saved))
271    } catch (error) {
272      debug($, `could not save settings: ${message(error)}`)
273    }
274  }
275  await refreshStatus($)
276  return saved
277}
278
279/**
280 * Counts a call's hits in their own state key (the rules, which transcript
281 * rows read, do not change) and returns the rules with the counts including
282 * this call, as planning takes them. One atomic update, so two parallel calls
283 * never plan with the same count. The guard's snapshot takes the counts too.
284 */
285async function bumpHits($: Dollar, settings: DevtoolsSettings, matched: readonly Breakpoint[]): Promise<Counted> {
286  if (matched.length === 0) return counted(settings)
287  const ids = matched.map(bp => bp.id)
288  const counts = await update($, HITS, hits => {
289    const next = { ...hits }
290    for (const id of ids) next[id] = (next[id] ?? 0) + 1
291    return next
292  })
293  const after = counted(settings, counts)
294  mirror.settings = after
295  return after
296}
297
298async function forgetHits($: Dollar, ids: readonly string[] | 'all'): Promise<void> {
299  await update($, HITS, hits => (ids === 'all' ? {} : Object.fromEntries(Object.entries(hits).filter(([id]) => !ids.includes(id)))))
300}
301
302/**
303 * Sets or removes the rule a suggestion or category stands for, as a click
304 * on a line's gutter does in Chrome DevTools. Returns what happened.
305 */
306async function toggleRule($: Dollar, kind: Breakpoint['kind'], match: Breakpoint['match'], name: string): Promise<string> {
307  const settings = await loadSettings($)
308  const existing = findRule(settings.breakpoints, kind, match)
309  if (existing !== undefined) {
310    await changeSettings($, current => ({ ...current, breakpoints: current.breakpoints.filter(bp => bp.id !== existing.id) }))
311    await forgetHits($, [existing.id])
312    return `Breakpoint removed: ${existing.name}`
313  }
314  const checked = validateBreakpoint({ id: nextBreakpointId(settings.breakpoints), name, enabled: true, kind, match, scope: options.defaultScope, action: 'pause', hitCount: 0 })
315  if (!checked.ok) return `Breakpoint not set: ${checked.error}`
316  let id = checked.breakpoint.id
317  await changeSettings($, current => {
318    id = nextBreakpointId(current.breakpoints)
319    return { ...current, breakpoints: [...current.breakpoints, { ...checked.breakpoint, id }] }
320  })
321  await forgetHits($, [id])
322  const mode = (await loadSettings($)).mode
323  return `Breakpoint set: ${name} → pause${mode === 'active' ? '' : ` (mode ${mode}: /devtools-enable to pause)`}`
324}
325
326async function toggleSuggestion($: Dollar, suggestion: Suggestion): Promise<void> {
327  const text = await toggleRule($, suggestion.kind, suggestion.match, suggestion.name)
328  $.ui.toast(`DevTools: ${text}`)
329  await setView($, { notice: text })
330}
331
332async function toggleCategory($: Dollar, category: Category): Promise<void> {
333  const settings = await loadSettings($)
334  const existing = findCategoryRule(settings.breakpoints, category)
335  // A category rule switched off by hand is switched back on, not deleted and re-added.
336  if (existing !== undefined && !existing.enabled) {
337    await setView($, { notice: await editBreakpoint($, 'enable', existing.id) })
338    return
339  }
340  await setView($, { notice: await toggleRule($, 'tool', { tools: [...category.tools] }, `Pause on ${category.label}`) })
341}
342
343async function hideBar($: Dollar): Promise<void> {
344  await setView($, { barHidden: true })
345}
346
347async function openPane($: Dollar, isAsked: boolean): Promise<string | undefined> {
348  const opened = await $.ui.open(isAsked ? { id: PANE, title: 'Claude DevTools', focus: true } : { id: PANE, title: 'Claude DevTools' })
349  return opened.isPlaced ? undefined : opened.reason
350}
351
352/** The bar's "why?": the pane, on this failure's Error Lens. */
353async function openLens($: Dollar, id: string): Promise<void> {
354  await setView($, { tab: 'errors', lensId: id })
355  await openPane($, true)
356}
357
358async function exportFromPane($: Dollar): Promise<void> {
359  try {
360    const text = await exportTrace($, '')
361    await setView($, { notice: text.replace(/\s*\n\s*/g, ' ') })
362  } catch (error) {
363    await setView($, { notice: `Export failed: ${message(error)}` })
364  }
365}
366
367async function setArm($: Dollar, arm: ArmState): Promise<void> {
368  await $.state.set(ARM, arm)
369  mirror.arm = arm
370  await refreshStatus($)
371}
372
373async function toggleArm($: Dollar): Promise<void> {
374  const current = await read($, ARM_ATOM)
375  await setArm($, current.pauseNext || current.step ? DISARMED : { pauseNext: true, step: false, reason: 'armed in the pane' })
376}
377
378/** Merges a view change and clears the last notice; a key set to undefined is removed (state holds JSON). */
379async function setView($: Dollar, change: Partial<ViewState>): Promise<void> {
380  await update($, VIEW, ({ notice: _cleared, ...view }) => {
381    const merged: Record<string, unknown> = { ...view, ...change }
382    for (const key of Object.keys(merged)) if (merged[key] === undefined) delete merged[key]
383    return merged as ViewState
384  })
385}
386
387async function movePage($: Dollar, delta: number): Promise<void> {
388  await update($, VIEW, ({ notice: _cleared, ...view }) => ({ ...view, page: Math.max(0, view.page + delta) }))
389}
390
391async function clearTimeline($: Dollar): Promise<void> {
392  await update($, TRACE, () => [])
393  await setView($, { page: 0, selectedId: undefined })
394}
395
396async function refreshStatus($: Dollar): Promise<void> {
397  const [arm, pending, held] = await Promise.all([read($, ARM_ATOM), read($, PENDING), $.state.get(SETTINGS)])
398  const mode = held.value?.mode ?? 'active'
399  if (pending.length > 0) $.ui.status(`⏸ DevTools: ${pending.length === 1 ? `${pending[0]?.tool} paused` : `${pending.length} calls paused`}`)
400  else if (mode === 'active' && (arm.pauseNext || arm.step)) $.ui.status('DevTools: the next tool call will pause')
401  else if (mode === 'observe') $.ui.status('DevTools: observing (breakpoints do not pause)')
402  else $.ui.status(undefined)
403}
404
405// ------------------------------------------------------------------ recording
406
407async function addEvent($: Dollar, event: TraceEvent): Promise<void> {
408  await update($, TRACE, list => appendBounded(list, event, options.maxTimelineEntries))
409}
410
411async function patch($: Dollar, id: string, change: Partial<TraceEvent>): Promise<void> {
412  await update($, TRACE, list => patchEvent(list, id, change))
413}
414
415async function count($: Dollar, status: TraceStatus): Promise<void> {
416  const key = STATUS_COUNTER[status]
417  if (key !== undefined) await update($, STATS, stats => ({ ...stats, [key]: stats[key] + 1 }))
418}
419
420/**
421 * Claims the plan for a call. A consumed arm (pause-next, step) is written
422 * back only if nobody consumed it first, so of two concurrent calls only one
423 * pauses for a single step.
424 */
425async function claimPlan($: Dollar, settings: Counted, call: NormalizedCall, cwd: string | undefined): Promise<Planned> {
426  for (let attempt = 0; attempt < 5; attempt += 1) {
427    const held = await $.state.get(ARM)
428    const arm = held.value ?? DISARMED
429    mirror.arm = arm
430    const planned = planCall(settings, arm, call, cwd)
431    if (planned.arm === arm) return planned
432    const written = await $.state.set(ARM, planned.arm, { ifVersion: held.version })
433    if (written.isSet) {
434      mirror.arm = planned.arm
435      return planned
436    }
437  }
438  return planCall(settings, DISARMED, call, cwd)
439}
440
441/** What the permission rules and mode would decide, asked without running anything. */
442async function previewPermission($: Dollar, call: NormalizedCall): Promise<PermissionInfo | undefined> {
443  try {
444    const verdict = await $.tool.check({ tool: call.tool, input: call.args })
445    return { decision: verdict.decision, rule: verdict.rule, reason: verdict.reason, source: 'preview' }
446  } catch {
447    return undefined
448  }
449}
450
451// ------------------------------------------------------------------ pausing
452
453async function refuse($: Dollar, event: TraceEvent, status: TraceStatus, outcome: TraceOutcome, deny: string, decision?: PauseDecision): Promise<Held> {
454  // The refusal is kept first, and with the call's start time if the clock fails: a guard may refuse the call next.
455  const now = await $.clock.now().catch(() => event.startedAtMs)
456  if (status === 'denied') {
457    const refusal = explainRefusal({ outcome, text: redactIf(deny), seen: true })
458    await recordDenial($, { id: event.id, tool: event.tool, ...(event.agentId !== undefined ? { agentId: event.agentId } : {}), atMs: now, inputSummary: event.inputSummary, outcome, refusal })
459  }
460  await patch($, event.id, {
461    status,
462    outcome,
463    ...(decision !== undefined ? { decision } : {}),
464    errorText: redactIf(deny),
465    durationMs: 0,
466    resultSummary: `not run: ${outcome}`,
467  })
468  await count($, status)
469  await captureFailure($, event, true, { startedMs: now, endedMs: now, status, outcome, text: deny })
470  return { answer: { deny } }
471}
472
473/**
474 * Holds a call until the person decides, inside the engine's own question
475 * dialog ($.ui.ask), whose wait does not count against the hook's budget.
476 * Headless, nobody can answer: the configured policy decides at once.
477 */
478async function hold(
479  $: Dollar,
480  signal: AbortSignal,
481  call: NormalizedCall,
482  event: TraceEvent,
483  reason: string,
484  at: Breakpoint | undefined,
485  isInteractive: boolean,
486): Promise<Held> {
487  const pending: PendingCall = { id: event.id, tool: call.tool, inputSummary: event.inputSummary, reason, sinceMs: event.startedAtMs }
488  await update($, PENDING, list => [...list, call.agentId === undefined ? pending : { ...pending, agentId: call.agentId }])
489  await update($, STATS, stats => ({ ...stats, paused: stats.paused + 1 }))
490  await refreshStatus($)
491  try {
492    if (!isInteractive) {
493      if (options.headlessPause === 'record-only') {
494        $.ui.log(`devtools: ${reason} matched ${call.tool} in a headless session; recorded and let through (headlessPause=record-only).`)
495        return { decision: 'continue' }
496      }
497      const deny = refusalText('headless', call.tool, reason)
498      $.ui.log(`devtools: ${deny}`)
499      return await refuse($, event, 'denied', 'headless-rejected', deny)
500    }
501    const permission = await previewPermission($, call)
502    const simulation = checkSimulation(options.simulation, at, call)
503    if (permission !== undefined) await patch($, event.id, { permission })
504    const question = pauseQuestion({
505      tool: call.tool,
506      summary: event.inputSummary,
507      reason,
508      risk: call.risk,
509      agentId: call.agentId,
510      permission,
511      canSimulate: simulation.ok,
512    })
513    let answer: string | undefined
514    try {
515      answer = await $.ui.ask(question.question, { options: question.options, header: question.header })
516    } catch {
517      // Dismissed, "Chat about this", or nobody to ask: the call does not run.
518      answer = undefined
519    }
520    if (signal.aborted) return await refuse($, event, 'failed', 'aborted', refusalText('aborted', call.tool, reason))
521    if (answer === undefined) return await refuse($, event, 'denied', 'user-cancelled', refusalText('cancelled', call.tool, reason))
522    const { decision, note } = interpretAnswer(answer, simulation.ok)
523    if (decision === 'reject') return await refuse($, event, 'denied', 'debugger-rejected', refusalText('debugger', call.tool, reason, note), 'reject')
524    if (decision === 'simulate' && simulation.ok) {
525      const synthetic = synthesize(simulation.kind, call, simulation.text)
526      const shown: ResultLike = 'deny' in synthetic ? { deny: synthetic.deny } : { result: synthetic.result }
527      await patch($, event.id, {
528        status: 'simulated',
529        outcome: 'simulated',
530        decision: 'simulate',
531        simulated: true,
532        durationMs: 0,
533        resultSummary: `SIMULATED ${simulation.kind === 'fail' ? 'failure' : 'output'}: ${summarizeResult(call.tool, shown, summary)}`,
534      })
535      await count($, 'simulated')
536      if ('deny' in synthetic) {
537        const now = await $.clock.now()
538        await captureFailure($, event, true, { startedMs: now, endedMs: now, status: 'simulated', outcome: 'simulated', text: synthetic.deny })
539      }
540      return { answer: synthetic }
541    }
542    if (decision === 'step') await setArm($, { pauseNext: false, step: true })
543    return { decision: decision === 'step' ? 'step' : 'continue', ...(permission !== undefined ? { permission } : {}) }
544  } finally {
545    // The answer stands: a failure to clear the pause is only logged, never put in place of a Reject and its note.
546    try {
547      await update($, PENDING, list => list.filter(item => item.id !== event.id))
548      await refreshStatus($)
549    } catch (error) {
550      debug($, `could not clear the pause of ${call.tool}: ${message(error)}`)
551    }
552  }
553}
554
555/** Records what the call really returned, then applies error breakpoints. */
556async function afterRun(
557  $: Dollar,
558  call: NormalizedCall,
559  event: TraceEvent,
560  isRecorded: boolean,
561  startedMs: number,
562  result: ResultLike,
563  preview: PermissionInfo | undefined,
564  cwd: string | undefined,
565  denier: { plugin: string; tier: string } | undefined,
566): Promise<void> {
567  const endedMs = await $.clock.now()
568  const note = call.toolUseId === undefined ? undefined : notes.get(call.toolUseId)
569  const observed = note?.verdict
570  if (note !== undefined) delete note.verdict
571  const permission = observed ?? preview
572  const { status, outcome } = classifyResult(result, permission, denier !== undefined && !isEngine(denier))
573  const errorText = errorTextOf(result, summary)
574  let refusal: Refusal | undefined
575  if (status === 'denied') {
576    refusal = explainRefusal({
577      outcome,
578      text: redactIf(errorTextOfResult(result)),
579      ...(permission !== undefined ? { permission } : {}),
580      ...(denier !== undefined ? { denier } : {}),
581      seen: true,
582    })
583    await recordDenial($, { id: event.id, tool: call.tool, ...(call.agentId !== undefined ? { agentId: call.agentId } : {}), atMs: endedMs, inputSummary: event.inputSummary, outcome, refusal })
584  }
585  const change: Partial<TraceEvent> = {
586    status,
587    outcome,
588    durationMs: Math.max(0, endedMs - startedMs),
589    resultSummary: summarizeResult(call.tool, result, summary),
590    ...(errorText !== undefined ? { errorText } : {}),
591    ...(permission !== undefined ? { permission } : {}),
592    ...(result.isReadOnly === true ? { isReadOnly: true } : {}),
593    ...(options.captureRaw ? { raw: rawOf(call, result, summary) } : {}),
594  }
595  if (isRecorded) await patch($, event.id, change)
596  await count($, status)
597  const suspected = status === 'completed' && looksLikeFailure(call.tool, result)
598  let errorCategory: ErrorCategory | undefined
599  if (status === 'failed' || status === 'denied' || suspected) {
600    const content = call.tool === 'Write' && typeof call.args.content === 'string' ? call.args.content : undefined
601    errorCategory = await captureFailure(
602      $,
603      event,
604      isRecorded,
605      {
606        startedMs,
607        endedMs,
608        status,
609        outcome,
610        text: errorTextOfResult(result),
611        ...(suspected ? { suspected: true } : {}),
612        ...(permission !== undefined ? { permission } : {}),
613        ...(refusal !== undefined ? { refusal } : {}),
614      },
615      content === undefined ? undefined : new TextEncoder().encode(content).length,
616    )
617  }
618  if (outcome !== 'tool-error') return
619
620  const [live, arm] = await Promise.all([liveSettings($), read($, ARM_ATOM)])
621  // The mode may have been turned off while the call ran.
622  if (live.mode === 'off') return
623  // Counted before planning: a hit below its threshold counts too.
624  const settings = await bumpHits($, live, evaluateError(live.breakpoints, call, cwd).hits)
625  const planned = planAfterError(settings, arm, call, cwd)
626  if (planned.triggered.length === 0) return
627  const ids = planned.triggered.map(bp => bp.id)
628  if (!isRecorded) await addEvent($, { ...event, ...change, breakpointIds: ids, ...(errorCategory !== undefined ? { errorCategory } : {}) })
629  else await patch($, event.id, { breakpointIds: [...(event.breakpointIds ?? []), ...ids] })
630  if (planned.arm !== arm) await setArm($, planned.arm)
631  const armedNote = planned.arm.pauseNext ? ' The next tool call will pause.' : ''
632  $.ui.toast(`DevTools: ${call.tool} failed (${planned.triggered.map(bp => bp.name).join(', ')}).${armedNote}`, { timeoutMs: 6000 })
633}
634
635// ------------------------------------------------------------------ error lens
636
637/** What the person did themselves: kept and shown, never announced. */
638const QUIET: readonly ErrorCategory[] = ['debugger', 'simulated', 'interrupted']
639
640type Failure = {
641  startedMs: number
642  endedMs: number
643  status: TraceStatus
644  outcome: TraceOutcome
645  /** The error as Claude read it, before redaction. */
646  text: string
647  suspected?: true
648  permission?: PermissionInfo
649  refusal?: Refusal
650}
651
652/**
653 * Error Lens: diagnoses a failed call from its result, keeps it, groups
654 * repeats, and in probe mode schedules read-only checks for after the result
655 * has gone back. It never retries or changes the call, and its own failure
656 * is only logged. Returns the category it recorded.
657 */
658async function captureFailure($: Dollar, event: TraceEvent, isRecorded: boolean, failure: Failure, contentBytes?: number): Promise<ErrorCategory | undefined> {
659  if (options.errorLens === 'off') return undefined
660  try {
661    const { record, plan } = buildLensRecord({
662      id: event.id,
663      seq: event.seq,
664      tool: event.tool,
665      ...(event.agentId !== undefined ? { agentId: event.agentId } : {}),
666      startedAtMs: failure.startedMs,
667      endedAtMs: failure.endedMs,
668      status: failure.status,
669      outcome: failure.outcome,
670      ...(failure.suspected === true ? { suspected: true } : {}),
671      text: redactIf(failure.text),
672      args: event.input ?? {},
673      paths: event.paths ?? [],
674      ...(failure.permission !== undefined ? { permission: failure.permission } : {}),
675      ...(failure.refusal !== undefined ? { refusal: failure.refusal } : {}),
676      ...(contentBytes !== undefined ? { contentBytes } : {}),
677      probing: options.errorLens,
678    })
679    await update($, LENS, list => [...list.filter(one => one.id !== record.id), record].slice(-MAX_LENS))
680    const groups = await update($, GROUPS, list => addToGroups(list, record).groups)
681    const group = groups.find(one => one.signature === record.signature)
682    if (isRecorded) await patch($, record.id, { errorCategory: record.category })
683    if (options.errorToasts && group !== undefined && shouldNotify(group) && !QUIET.includes(record.category)) {
684      const verb = record.suspected === true ? 'may have failed' : record.status === 'denied' ? 'denied' : 'failed'
685      const repeat = group.count > 1 ? ` · ${group.count}× this session` : ''
686      $.ui.toast(`DevTools ✗ ${record.tool} ${verb} (${record.category})${repeat}: ${truncate(record.headline, 90)} · /devtools-errors to inspect`, { timeoutMs: 6000 })
687    }
688    // Deferred: the checks run once the result is on its way back to Claude.
689    if (plan.length > 0) $.clock.after(0, () => settle($, runProbes($, record.id, plan)))
690    return record.category
691  } catch (error) {
692    debug($, `Error Lens could not record ${event.tool}: ${message(error)}`)
693    return undefined
694  }
695}
696
697/** One $.fs.stat per planned path: read-only, metadata only, never a file's contents. */
698async function runProbes($: Dollar, id: string, plan: readonly ProbeTarget[]): Promise<void> {
699  const probes = await Promise.all(
700    plan.map(async ({ path, role }): Promise<LensProbe> => {
701      try {
702        const stat = await $.fs.stat(path, { resolve: true })
703        return {
704          path,
705          role,
706          exists: true,
707          kind: stat.kind,
708          size: stat.size,
709          mtimeMs: stat.mtimeMs,
710          isLink: stat.isLink,
711          ...(stat.realPath !== undefined ? { realPath: redactIf(stat.realPath) } : {}),
712        }
713      } catch (error) {
714        const text = message(error)
715        return /\bENOENT\b|no such file/i.test(text) ? { path, role, exists: false } : { path, role, exists: null, error: truncate(redactIf(text), 160) }
716      }
717    }),
718  )
719  await update($, LENS, list => list.map(one => (one.id === id ? withProbes(one, probes) : one)))
720}
721
722async function clearErrors($: Dollar): Promise<void> {
723  await update($, LENS, () => [])
724  await update($, GROUPS, () => [])
725  await setView($, { lensId: undefined })
726}
727
728async function errorsText($: Dollar): Promise<string> {
729  if (options.errorLens === 'off') return 'Error Lens is off (the devtools option errorLens).'
730  const [lens, groups] = await Promise.all([read($, LENS), read($, GROUPS)])
731  const latest = lens.at(-1)
732  if (latest === undefined) return 'Error Lens: no failed tool calls this session.'
733  return [
734    `Error Lens: ${lens.length} failure${lens.length === 1 ? '' : 's'} kept, ${groups.length} kind${groups.length === 1 ? '' : 's'}`,
735    ...groups.slice(0, 8).map(group => `  ${group.count}× ${group.tool} · ${group.category} · ${truncate(group.headline, 100)}`),
736    '',
737    'Latest:',
738    ...lensReport(latest),
739  ].join('\n')
740}
741
742// ------------------------------------------------------------------ permissions
743
744/** Reads the permission settings from each settings file: read-only, nothing is ever written to them. */
745async function readPermissionSettings($: Dollar): Promise<PermissionsSnapshot> {
746  const bySource: Partial<Record<SettingsSourceName, unknown>> = {}
747  const errors: string[] = []
748  await Promise.all(
749    SOURCES.map(async source => {
750      try {
751        bySource[source] = await $.settings.read({ source })
752      } catch (error) {
753        errors.push(`${source}: ${message(error)}`)
754      }
755    }),
756  )
757  const snapshot = readPermissions(bySource, errors, await $.clock.now(), redactIf)
758  await update($, PERMISSIONS, () => snapshot)
759  return snapshot
760}
761
762/** Keeps a refused call for the Permissions tab, whether or not the timeline records. */
763async function recordDenial($: Dollar, denial: Denial): Promise<void> {
764  await update($, DENIALS, list => addDenial(list, denial))
765}
766
767/**
768 * Refused tool results for calls whose tool.call never reached DevTools' hook
769 * (refused above it), and for calls DevTools' own guard refused.
770 */
771async function noteUnseenRefusals($: Dollar, content: readonly unknown[], tool: string, agentId: string | undefined): Promise<void> {
772  const isGuard = (id: string): boolean => notes.get(id)?.isGuardRefused === true
773  const found = unseenRefusals(content, id => notes.has(id), isGuard)
774  if (found.length === 0) return
775  // Off records nothing but DevTools' own refusals, made while it was on.
776  const kept = (await liveSettings($)).mode === 'off' ? found.filter(one => isGuard(one.toolUseId)) : found
777  if (kept.length === 0) return
778  const [now, trace, denials] = await Promise.all([$.clock.now(), read($, TRACE), read($, DENIALS)])
779  // A reload empties the notes; a call the old module saw is still in the timeline.
780  const eventOf = (id: string): TraceEvent | undefined => trace.find(one => one.id === id)
781  const toRecord = kept.filter(one => (isGuard(one.toolUseId) || eventOf(one.toolUseId) === undefined) && !denials.some(d => d.id === one.toolUseId))
782  // Recorded already (rejected at its pause, then the hook failed): the guard's mark is done.
783  for (const one of kept) if (!toRecord.includes(one)) delete notes.get(one.toolUseId)?.isGuardRefused
784  const missing = toRecord.filter(one => eventOf(one.toolUseId) === undefined).map(one => one.toolUseId)
785  const inputs = missing.length === 0 ? new Map<string, string>() : await inputsOf($, missing, agentId)
786  for (const { toolUseId, text } of toRecord) {
787    // Each on its own: one that fails to record leaves the rest, and keeps its mark.
788    try {
789      const event = eventOf(toolUseId)
790      const isOwn = isGuard(toolUseId)
791      if (event !== undefined && (event.status === 'pending' || event.status === 'running')) await refuse($, event, 'denied', 'guard-failed', text)
792      else {
793        const outcome: TraceOutcome = isOwn ? 'guard-failed' : 'blocked-by-hook'
794        await recordDenial($, {
795          id: toolUseId,
796          tool,
797          ...(agentId !== undefined ? { agentId } : {}),
798          atMs: now,
799          inputSummary: event?.inputSummary ?? inputs.get(toolUseId) ?? '',
800          outcome,
801          refusal: explainRefusal({ outcome, text: redactIf(text), seen: isOwn }),
802        })
803      }
804      const note = noteOf(toolUseId)
805      if (note !== undefined) delete note.isGuardRefused
806    } catch (error) {
807      debug($, `could not record the refusal of ${toolUseId}: ${message(error)}`)
808    }
809  }
810}
811
812/**
813 * What calls DevTools has no event of asked for, read once from the
814 * conversation that made them, summarized as the timeline would; a call not
815 * found is left out.
816 */
817async function inputsOf($: Dollar, ids: readonly string[], agentId: string | undefined): Promise<Map<string, string>> {
818  const found = new Map<string, string>()
819  try {
820    const rows = agentId === undefined ? await $.session.messages() : await $.session.messages({ agentId })
821    if (!Array.isArray(rows)) return found
822    // Newest first: the calls were just made.
823    for (let i = rows.length - 1; i >= 0 && found.size < ids.length; i -= 1) {
824      for (const use of rows[i]?.toolUses ?? []) {
825        if (ids.includes(use.tool_use_id)) found.set(use.tool_use_id, summarizeInput(normalizeCall({ ...use.input, tool: use.tool, tool_use_id: use.tool_use_id }), summary))
826      }
827    }
828  } catch (error) {
829    debug($, `could not read the input of ${ids.join(', ')}: ${message(error)}`)
830  }
831  return found
832}
833
834async function clearDenials($: Dollar): Promise<void> {
835  await update($, DENIALS, () => [])
836}
837
838async function permissionsText($: Dollar): Promise<string> {
839  const snapshot = await readPermissionSettings($)
840  const denials = await read($, DENIALS)
841  return ['Claude DevTools · Permissions (rules as read now; refused calls from this session)', ...permissionsReport(snapshot, denials)].join('\n')
842}
843
844async function showPermissions($: Dollar): Promise<void> {
845  await setView($, { tab: 'permissions' })
846  await readPermissionSettings($)
847}
848
849/** A refused call, opened where its detail is: Error Lens, else the Inspector. */
850async function openDenial($: Dollar, id: string): Promise<void> {
851  const [lens, trace, denials] = await Promise.all([read($, LENS), read($, TRACE), read($, DENIALS)])
852  if (lens.some(one => one.id === id)) await setView($, { tab: 'errors', lensId: id })
853  else if (trace.some(one => one.id === id)) await setView($, { tab: 'inspector', selectedId: id })
854  else if (denials.some(one => one.id === id && one.outcome === 'guard-failed')) {
855    await setView($, { notice: "Claude DevTools' guard refused the call before it was recorded: its reason is all there is." })
856  } else await setView($, { notice: 'Refused before Claude DevTools saw the call: its reason is all there is.' })
857}
858
859// ------------------------------------------------------------------ commands
860
861async function statusText($: Dollar): Promise<string> {
862  const [settings, arm, stats, trace, pending, session] = await Promise.all([
863    liveSettings($),
864    read($, ARM_ATOM),
865    read($, STATS),
866    read($, TRACE),
867    read($, PENDING),
868    read($, SESSION),
869  ])
870  const enabled = settings.breakpoints.filter(bp => bp.enabled).length
871  const lines = [
872    `Claude DevTools — mode ${settings.mode} · recording ${settings.recording ? 'on' : 'off'} · simulation ${options.simulation ? 'on' : 'off'} · ${session.isInteractive ? 'interactive' : `headless (pause → ${options.headlessPause})`}`,
873    `Paused: ${pending.length === 0 ? 'none' : pending.map(p => `${p.tool} ${p.inputSummary} (${p.reason})`).join('; ')}`,
874    `Armed: ${arm.pauseNext || arm.step ? `the next call pauses${arm.step ? ' (step)' : ''}${arm.reason !== undefined ? ` (${arm.reason})` : ''}` : 'no'}`,
875    `Calls: ${stats.observed} observed · ${stats.completed} ok · ${stats.failed} failed · ${stats.denied} denied · ${stats.simulated} simulated · ${stats.paused} paused`,
876    `Breakpoints: ${enabled} enabled of ${settings.breakpoints.length} (/devtools-list)`,
877    `Timeline: ${trace.length} of ${options.maxTimelineEntries} events kept · redaction ${options.redaction ? 'on' : 'OFF'}${options.captureRaw ? ' · RAW CAPTURE ON' : ''}`,
878  ]
879  const recent = trace.slice(-5)
880  if (recent.length > 0) {
881    lines.push('Recent (UTC):')
882    for (const ev of recent) {
883      lines.push(`  ${clock(ev.startedAtMs)} ${statusIcon(ev.status)} ${ev.tool} ${formatDuration(ev.durationMs)} ${ev.simulated ? 'SIMULATED ' : ''}${ev.inputSummary}`)
884    }
885  }
886  return lines.join('\n')
887}
888
889function listText(settings: DevtoolsSettings): string {
890  if (settings.breakpoints.length === 0) return 'No breakpoints. Add one with /devtools-break, e.g. /devtools-break command npm install'
891  return [
892    `Breakpoints (mode ${settings.mode}):`,
893    ...settings.breakpoints.map(bp => `  ${bp.id} ${bp.enabled ? '●' : '○'} ${bp.name} — ${describeBreakpoint(bp)} · hits ${bp.hitCount}`),
894  ].join('\n')
895}
896
897function helpText(): string {
898  return [
899    'Claude DevTools: inspect, pause and control tool calls before they run.',
900    '',
901    '/devtools                 open the pane (Overview, Timeline, Inspector, Breakpoints, Errors, Permissions)',
902    '/devtools-status          debugger state as text',
903    '/devtools-break <rule>    add a breakpoint; /devtools-break delete|toggle <id>; /devtools-break clear',
904    '/devtools-list            list breakpoints',
905    '/devtools-pause           pause on the next tool call',
906    '/devtools-continue        disarm pause-next and stepping',
907    '/devtools-disable [observe|off]   stop pausing, or turn the debugger off',
908    '/devtools-enable          pause on breakpoints again',
909    '/devtools-record [on|off] timeline recording',
910    '/devtools-export [path] [--md]    write a sanitized JSON trace (and a Markdown report)',
911    '/devtools-errors [clear]  Error Lens: why recent calls failed (confirmed / possible / unknown), with fixes',
912    '/devtools-permissions [clear]  your permission rules, and each refused call: who refused it and why',
913    '',
914    'Short aliases: /bp <rule> (/bp alone lists) · /bpl list · /bpn pause next · /bpc continue · /bpe errors · /bpp permissions',
915    '',
916    'Rules:',
917    ...SPEC_HELP.map(line => `  ${line}`),
918    '',
919    'A paused call is answered in the question dialog: Continue (normal permission checks still run),',
920    'Step (run it, pause on the next call), Reject (Claude is told it did not run), Simulate (only with',
921    'the simulation option, labeled, never claiming side effects). Typed text rejects and is passed to Claude.',
922  ].join('\n')
923}
924
925async function addBreakpoint($: Dollar, spec: string): Promise<{ ok: true; breakpoint: Breakpoint } | { ok: false; error: string }> {
926  const settings = await loadSettings($)
927  const parsed = parseBreakpointSpec(spec, nextBreakpointId(settings.breakpoints), options.defaultScope)
928  if (!parsed.ok) return parsed
929  let added = parsed.breakpoint
930  await changeSettings($, current => {
931    added = { ...parsed.breakpoint, id: nextBreakpointId(current.breakpoints) }
932    return { ...current, breakpoints: [...current.breakpoints, added] }
933  })
934  return { ok: true, breakpoint: added }
935}
936
937async function addFromPane($: Dollar, spec: string): Promise<void> {
938  const added = await addBreakpoint($, spec)
939  await setView($, { notice: added.ok ? `Added ${added.breakpoint.id}: ${describeBreakpoint(added.breakpoint)}` : `Not added: ${added.error}` })
940}
941
942async function editBreakpoint($: Dollar, verb: string, id: string): Promise<string> {
943  const settings = await loadSettings($)
944  const found = settings.breakpoints.find(bp => bp.id === id)
945  if (found === undefined) return `No breakpoint ${id}. ${listText(settings)}`
946  if (verb === 'delete' || verb === 'rm' || verb === 'remove') {
947    await changeSettings($, current => ({ ...current, breakpoints: current.breakpoints.filter(bp => bp.id !== id) }))
948    await forgetHits($, [id])
949    return `Deleted ${id} (${found.name}).`
950  }
951  const enabled = verb === 'enable' ? true : verb === 'disable' ? false : !found.enabled
952  await changeSettings($, current => ({ ...current, breakpoints: current.breakpoints.map(bp => (bp.id === id ? { ...bp, enabled } : bp)) }))
953  return `${enabled ? 'Enabled' : 'Disabled'} ${id} (${found.name}).`
954}
955
956async function setMode($: Dollar, mode: DevtoolsMode): Promise<void> {
957  await changeSettings($, current => ({ ...current, mode }))
958}
959
960async function toggleRecording($: Dollar): Promise<void> {
961  await changeSettings($, current => ({ ...current, recording: !current.recording }))
962}
963
964async function exportTrace($: Dollar, args: string): Promise<string> {
965  const words = args.split(/\s+/).filter(word => word !== '')
966  const wantsMarkdown = words.includes('--md')
967  const target = words.find(word => word !== '--md')
968  const [cwd, now, settings, trace, stats, session, errors, errorGroups, denials, permissions] = await Promise.all([
969    $.session.cwd(),
970    $.clock.now(),
971    liveSettings($),
972    read($, TRACE),
973    read($, STATS),
974    read($, SESSION),
975    read($, LENS),
976    read($, GROUPS),
977    read($, DENIALS),
978    // Read now (after /clear nothing has read them yet); the last snapshot if that fails.
979    readPermissionSettings($).catch(() => read($, PERMISSIONS)),
980  ])
981  const stamp = new Date(now).toISOString().replace(/[:.]/g, '-')
982  const paths = exportPaths(target, cwd, stamp, wantsMarkdown)
983  if (!paths.ok) return `Export refused: ${paths.error}.`
984  if (!paths.mayReplace) {
985    for (const path of [paths.json, paths.markdown]) {
986      if (path !== undefined && (await $.fs.exists(path))) return `Export refused: ${path} already exists. Only files in .claude-devtools/ are replaced; choose a new name.`
987    }
988  }
989  const built = buildExport({
990    version: VERSION,
991    exportedAt: new Date(now).toISOString(),
992    sessionId: session.sessionId,
993    redaction: options.redaction,
994    rawCapture: options.captureRaw,
995    mode: settings.mode,
996    stats,
997    breakpoints: settings.breakpoints,
998    events: trace,
999    errors,
1000    errorGroups,
1001    denials,
1002    permissions,
1003  })
1004  const text = serializeExport(built)
1005  await $.fs.write(paths.json, text)
1006  const written = [paths.json]
1007  if (paths.markdown !== undefined) {
1008    await $.fs.write(paths.markdown, exportToMarkdown(JSON.parse(text)))
1009    written.push(paths.markdown)
1010  }
1011  const privacy = options.redaction ? 'secrets redacted' : 'REDACTION OFF'
1012  return `Exported ${trace.length} events, ${errors.length} Error Lens record${errors.length === 1 ? '' : 's'} and ${denials.length} refused call${denials.length === 1 ? '' : 's'} (${privacy}${options.captureRaw ? ', raw capture included' : ''}) to:\n${written.map(path => `  ${path}`).join('\n')}`
1013}
1014
1015/** Registers the slash commands, each by its literal name; registering again on a reload replaces them. */
1016async function registerCommands($: Dollar): Promise<void> {
1017  await $.command.register({ name: 'devtools', description: 'Claude DevTools: open the debugger pane (overview, timeline, inspector, breakpoints)', immediate: true })
1018  await $.command.register({ name: 'devtools-status', description: 'Claude DevTools: show the debugger state as text', immediate: true })
1019  await $.command.register({
1020    name: 'devtools-break',
1021    description: 'Claude DevTools: add a breakpoint, or delete/toggle one by id',
1022    argumentHint: 'tool Bash | command npm install | file .env* | error | when tool=Edit path=src/** | delete <id>',
1023    immediate: true,
1024  })
1025  await $.command.register({ name: 'devtools-list', description: 'Claude DevTools: list breakpoint rules', immediate: true })
1026  await $.command.register({ name: 'devtools-pause', description: 'Claude DevTools: pause on the next tool call', immediate: true })
1027  await $.command.register({ name: 'devtools-continue', description: 'Claude DevTools: disarm pause-next and stepping so calls run freely', immediate: true })
1028  await $.command.register({
1029    name: 'devtools-disable',
1030    description: 'Claude DevTools: stop pausing (observe), or turn the debugger off',
1031    argumentHint: '[observe|off]',
1032    immediate: true,
1033  })
1034  await $.command.register({ name: 'devtools-enable', description: 'Claude DevTools: pause on breakpoints again', immediate: true })
1035  await $.command.register({ name: 'devtools-record', description: 'Claude DevTools: turn timeline recording on or off', argumentHint: '[on|off]', immediate: true })
1036  await $.command.register({
1037    name: 'devtools-export',
1038    description: 'Claude DevTools: export a sanitized trace as JSON (and Markdown)',
1039    argumentHint: '[path.json|path.md] [--md]',
1040    immediate: true,
1041  })
1042  await $.command.register({
1043    name: 'devtools-errors',
1044    description: 'Claude DevTools Error Lens: why recent tool calls failed, with evidence and fixes',
1045    argumentHint: '[clear]',
1046    immediate: true,
1047  })
1048  await $.command.register({
1049    name: 'devtools-permissions',
1050    description: 'Claude DevTools: your permission rules, and who refused each refused tool call and why',
1051    argumentHint: '[clear]',
1052    immediate: true,
1053  })
1054  await $.command.register({ name: 'devtools-help', description: 'Claude DevTools: usage and the breakpoint rule language', immediate: true })
1055  // Short aliases.
1056  await $.command.register({
1057    name: 'bp',
1058    description: 'DevTools: add a breakpoint (= /devtools-break); no rule lists them',
1059    argumentHint: 'command npm install | file .env* | tool Bash | delete <id>',
1060    immediate: true,
1061  })
1062  await $.command.register({ name: 'bpl', description: 'DevTools: list breakpoints (= /devtools-list)', immediate: true })
1063  await $.command.register({ name: 'bpn', description: 'DevTools: pause on the next tool call (= /devtools-pause)', immediate: true })
1064  await $.command.register({ name: 'bpc', description: 'DevTools: continue, disarm pause-next and stepping (= /devtools-continue)', immediate: true })
1065  await $.command.register({ name: 'bpe', description: 'DevTools: Error Lens, why recent calls failed (= /devtools-errors)', argumentHint: '[clear]', immediate: true })
1066  await $.command.register({ name: 'bpp', description: 'DevTools: permissions, who refused each call and why (= /devtools-permissions)', argumentHint: '[clear]', immediate: true })
1067}
1068
1069const ALIASES: Readonly<Record<string, string>> = {
1070  bp: 'devtools-break',
1071  bpl: 'devtools-list',
1072  bpn: 'devtools-pause',
1073  bpc: 'devtools-continue',
1074  bpe: 'devtools-errors',
1075  bpp: 'devtools-permissions',
1076}
1077
1078/**
1079 * Where a run came from that is the person's own: their Enter, the Remote
1080 * Control bridge, the SDK host, their Slack ping, a follow-up to their own
1081 * action in the UI. `unclassified` is not: the engine could not say who sent it.
1082 */
1083const PERSON_ORIGINS: readonly PromptOrigin['kind'][] = ['composer', 'bridge', 'sdk', 'slack-ping', 'auto-continuation']
1084
1085async function runCommand($: Dollar, command: string, rawArgs: string): Promise<{ text: string }> {
1086  const args = rawArgs.trim()
1087  switch (ALIASES[command] ?? command) {
1088    case 'devtools': {
1089      const session = await read($, SESSION)
1090      if (!session.isInteractive) return { text: await statusText($) }
1091      const waiting = await openPane($, true)
1092      if (waiting !== undefined) return { text: `${await statusText($)}\n\nThe pane is waiting: ${waiting}` }
1093      return { text: 'Claude DevTools is open. Keys: d t i b e a switch tabs; Tab walks the controls; ctrl+x tab focuses it.' }
1094    }
1095    case 'devtools-status':
1096      return { text: await statusText($) }
1097    case 'devtools-list':
1098      return { text: listText(await liveSettings($)) }
1099    case 'devtools-break': {
1100      const [first = '', id = ''] = args.split(/\s+/)
1101      const verb = first.toLowerCase()
1102      if (['delete', 'rm', 'remove', 'toggle', 'enable', 'disable'].includes(verb) && id !== '') return { text: await editBreakpoint($, verb, id) }
1103      if (verb === 'clear') {
1104        await changeSettings($, current => ({ ...current, breakpoints: [] }))
1105        await forgetHits($, 'all')
1106        return { text: 'Deleted every breakpoint.' }
1107      }
1108      if (args === '') return { text: `${listText(await liveSettings($))}\n\nUsage: /bp <rule> (or /devtools-break <rule>)\n${SPEC_HELP.map(line => `  ${line}`).join('\n')}` }
1109      const added = await addBreakpoint($, args)
1110      if (!added.ok) return { text: `Breakpoint not added: ${added.error}.` }
1111      const settings = await loadSettings($)
1112      const note = settings.mode === 'active' ? '' : ` Mode is ${settings.mode}: run /devtools-enable for it to pause.`
1113      return { text: `Added ${added.breakpoint.id} ${added.breakpoint.name}: ${describeBreakpoint(added.breakpoint)}.${note}` }
1114    }
1115    case 'devtools-pause':
1116      await setArm($, { pauseNext: true, step: false, reason: 'armed by /devtools-pause' })
1117      return { text: 'The next tool call will pause.' }
1118    case 'devtools-continue':
1119      await setArm($, DISARMED)
1120      return { text: 'Disarmed: calls run freely until a breakpoint matches. A call already held is answered in its dialog.' }
1121    case 'devtools-disable': {
1122      const mode: DevtoolsMode = args === 'off' ? 'off' : 'observe'
1123      await setMode($, mode)
1124      return { text: mode === 'off' ? 'Claude DevTools is off: no interception, no recording.' : 'Breakpoints no longer pause; matches are still recorded (observe mode).' }
1125    }
1126    case 'devtools-enable':
1127      await setMode($, 'active')
1128      return { text: 'Breakpoints pause again (active mode).' }
1129    case 'devtools-record': {
1130      const settings = await loadSettings($)
1131      const recording = args === 'on' ? true : args === 'off' ? false : !settings.recording
1132      await changeSettings($, current => ({ ...current, recording }))
1133      return { text: recording ? 'Recording every tool call.' : 'Recording off: only breakpoint matches are kept.' }
1134    }
1135    case 'devtools-errors': {
1136      if (args === 'clear') {
1137        await clearErrors($)
1138        return { text: 'Error Lens cleared.' }
1139      }
1140      const text = await errorsText($)
1141      const session = await read($, SESSION)
1142      if (!session.isInteractive || options.errorLens === 'off') return { text }
1143      await setView($, { tab: 'errors', lensId: undefined })
1144      const waiting = await openPane($, true)
1145      return { text: waiting === undefined ? text : `${text}\n\nThe pane is waiting: ${waiting}` }
1146    }
1147    case 'devtools-permissions': {
1148      if (args === 'clear') {
1149        await clearDenials($)
1150        return { text: 'Refused calls cleared.' }
1151      }
1152      const text = await permissionsText($)
1153      const session = await read($, SESSION)
1154      if (!session.isInteractive) return { text }
1155      await setView($, { tab: 'permissions' })
1156      const waiting = await openPane($, true)
1157      return { text: waiting === undefined ? text : `${text}\n\nThe pane is waiting: ${waiting}` }
1158    }
1159    case 'devtools-export':
1160      try {
1161        return { text: await exportTrace($, args) }
1162      } catch (error) {
1163        return { text: `Export failed: ${message(error)}` }
1164      }
1165    default:
1166      return { text: helpText() }
1167  }
1168}
1169
1170function settle($: Dollar, work: Promise<unknown>): void {
1171  work.catch(error => debug($, `pane action failed: ${message(error)}`))
1172}
1173
1174// ------------------------------------------------------------------ register
1175
1176export const register: Register = (on, rawOptions) => {
1177  const parsed = parseOptions(rawOptions)
1178  options = parsed.options
1179  optionWarnings = parsed.warnings
1180  summary = { maxChars: options.maxSummaryChars, redaction: options.redaction, captureRaw: options.captureRaw }
1181
1182  on('tool.call', async ($, e, next) => {
1183    const note = noteOf((e as ToolCallLike).tool_use_id)
1184    const live = await liveSettings($)
1185    if (live.mode === 'off') return next(e)
1186    const session = await read($, SESSION)
1187    const cwd = session.cwd === '' ? undefined : session.cwd
1188    mirror.cwd = cwd
1189    mirror.isInteractive = session.isInteractive
1190    const call = normalizeCall(e as ToolCallLike)
1191    const settings = await bumpHits($, live, evaluateCall(live.breakpoints, call, cwd).hits)
1192    if (note !== undefined) note.counted = settings
1193    const { plan } = await claimPlan($, settings, call, cwd)
1194    if (note !== undefined) {
1195      note.holds = holds(plan.kind === 'pause', session.isInteractive)
1196      delete note.counted
1197    }
1198    const hits = plan.kind === 'pass' ? [] : plan.hits.map(bp => bp.id)
1199
1200    const startedMs = await $.clock.now()
src/config/schema.ts 144 lines
1// Configuration: the manifest's userConfig options, validated at load, and
2// the persisted settings (mode, recording, breakpoint rules) in $.store.
3
4import type { BreakpointScope, DevtoolsMode, DevtoolsSettings } from '../../types'
5import { SCOPES, validateBreakpoint } from '../core/breakpoints.ts'
6
7export type HeadlessPolicy = 'reject' | 'record-only'
8export type InlineControls = 'hover' | 'always' | 'off'
9/** Error Lens: diagnose failures with read-only file checks, from the result alone, or not at all. */
10export type ErrorLensMode = 'probe' | 'classify' | 'off'
11
12export type DevtoolsOptions = {
13  recording: boolean
14  maxTimelineEntries: number
15  maxSummaryChars: number
16  defaultScope: BreakpointScope
17  headlessPause: HeadlessPolicy
18  simulation: boolean
19  redaction: boolean
20  captureRaw: boolean
21  persistBreakpoints: boolean
22  inlineControls: InlineControls
23  openOnStart: boolean
24  errorLens: ErrorLensMode
25  errorToasts: boolean
26}
27
28export const DEFAULT_OPTIONS: DevtoolsOptions = {
29  recording: true,
30  maxTimelineEntries: 500,
31  maxSummaryChars: 160,
32  defaultScope: 'all',
33  headlessPause: 'reject',
34  simulation: false,
35  redaction: true,
36  captureRaw: false,
37  persistBreakpoints: true,
38  inlineControls: 'always',
39  openOnStart: true,
40  errorLens: 'probe',
41  errorToasts: true,
42}
43
44export type ParsedOptions = { options: DevtoolsOptions; warnings: string[] }
45
46/**
47 * The engine validates userConfig against the manifest before `register`
48 * runs; this second pass keeps the module safe when it is handed something
49 * else (a test, an older manifest) and reports what it replaced.
50 */
51export function parseOptions(raw: Readonly<Record<string, unknown>> | undefined): ParsedOptions {
52  const source = raw ?? {}
53  const warnings: string[] = []
54  const options: DevtoolsOptions = { ...DEFAULT_OPTIONS }
55  const bool = (key: keyof DevtoolsOptions & string): void => {
56    const value = source[key]
57    if (value === undefined) return
58    if (typeof value === 'boolean') (options as Record<string, unknown>)[key] = value
59    else warnings.push(`option ${key} must be true or false; using ${String(DEFAULT_OPTIONS[key])}`)
60  }
61  const number = (key: 'maxTimelineEntries' | 'maxSummaryChars', min: number, max: number): void => {
62    const value = source[key]
63    if (value === undefined) return
64    if (typeof value === 'number' && Number.isFinite(value)) options[key] = Math.min(max, Math.max(min, Math.round(value)))
65    else warnings.push(`option ${key} must be a number; using ${DEFAULT_OPTIONS[key]}`)
66    if (typeof value === 'number' && (value < min || value > max)) warnings.push(`option ${key} clamped to ${min}-${max}`)
67  }
68  bool('recording')
69  bool('simulation')
70  bool('redaction')
71  bool('captureRaw')
72  bool('persistBreakpoints')
73  bool('openOnStart')
74  bool('errorToasts')
75  number('maxTimelineEntries', 10, 5000)
76  number('maxSummaryChars', 40, 2000)
77  if (source.defaultScope !== undefined) {
78    if (SCOPES.includes(source.defaultScope as BreakpointScope)) options.defaultScope = source.defaultScope as BreakpointScope
79    else warnings.push(`option defaultScope must be all, main or subagents; using ${DEFAULT_OPTIONS.defaultScope}`)
80  }
81  if (source.headlessPause !== undefined) {
82    if (source.headlessPause === 'reject' || source.headlessPause === 'record-only') options.headlessPause = source.headlessPause
83    else warnings.push('option headlessPause must be reject or record-only; using reject')
84  }
85  if (source.inlineControls !== undefined) {
86    if (source.inlineControls === 'hover' || source.inlineControls === 'always' || source.inlineControls === 'off') options.inlineControls = source.inlineControls
87    else warnings.push('option inlineControls must be always, hover or off; using always')
88  }
89  if (source.errorLens !== undefined) {
90    if (source.errorLens === 'probe' || source.errorLens === 'classify' || source.errorLens === 'off') options.errorLens = source.errorLens
91    else warnings.push('option errorLens must be probe, classify or off; using probe')
92  }
93  return { options, warnings }
94}
95
96export const STORE_KEY = 'settings.v1'
97export const SETTINGS_SCHEMA_VERSION = 1
98const MODES: readonly DevtoolsMode[] = ['active', 'observe', 'off']
99const MAX_BREAKPOINTS = 200
100
101export type PersistedSettings = {
102  schemaVersion: typeof SETTINGS_SCHEMA_VERSION
103  mode: DevtoolsMode
104  recording: boolean
105  breakpoints: unknown[]
106}
107
108export function defaultSettings(options: DevtoolsOptions): DevtoolsSettings {
109  return { mode: 'active', recording: options.recording, breakpoints: [] }
110}
111
112/** Reads what the store held: anything invalid is dropped with a warning, never trusted. */
113export function parsePersisted(raw: unknown, options: DevtoolsOptions): { settings: DevtoolsSettings; warnings: string[] } {
114  const settings = defaultSettings(options)
115  if (raw === undefined || raw === null) return { settings, warnings: [] }
116  if (typeof raw !== 'object') return { settings, warnings: ['saved settings were not an object; starting fresh'] }
117  const r = raw as Record<string, unknown>
118  if (r.schemaVersion !== SETTINGS_SCHEMA_VERSION) return { settings, warnings: [`saved settings have schema ${String(r.schemaVersion)}; starting fresh`] }
119  const warnings: string[] = []
120  if (MODES.includes(r.mode as DevtoolsMode)) settings.mode = r.mode as DevtoolsMode
121  if (typeof r.recording === 'boolean') settings.recording = r.recording
122  const seen = new Set<string>()
123  for (const item of Array.isArray(r.breakpoints) ? r.breakpoints.slice(0, MAX_BREAKPOINTS) : []) {
124    const checked = validateBreakpoint(item)
125    if (!checked.ok) {
126      warnings.push(`dropped a saved breakpoint: ${checked.error}`)
127      continue
128    }
129    if (seen.has(checked.breakpoint.id)) continue
130    seen.add(checked.breakpoint.id)
131    settings.breakpoints.push({ ...checked.breakpoint, hitCount: 0 })
132  }
133  return { settings, warnings }
134}
135
136export function toPersisted(settings: DevtoolsSettings): PersistedSettings {
137  return {
138    schemaVersion: SETTINGS_SCHEMA_VERSION,
139    mode: settings.mode,
140    recording: settings.recording,
141    breakpoints: settings.breakpoints.map(({ hitCount: _hits, ...rest }) => rest),
142  }
143}
144
src/core/breakpoints.ts 445 lines
1// Breakpoint rules: parsing, validation and matching. Pure functions; the
2// pattern matchers are bounded so a rule cannot stall a tool call.
3
4import type { Breakpoint, BreakpointAction, BreakpointKind, BreakpointMatch, BreakpointScope, SimulationKind } from '../../types'
5import type { NormalizedCall } from './events.ts'
6
7export const KINDS: readonly BreakpointKind[] = ['tool', 'command', 'file', 'error', 'conditional']
8export const ACTIONS: readonly BreakpointAction[] = ['pause', 'record', 'warn']
9export const SCOPES: readonly BreakpointScope[] = ['all', 'main', 'subagents']
10const SIMULATION_KINDS: readonly SimulationKind[] = ['fail', 'stub']
11
12const MAX_PATTERN = 512
13const MAX_REGEX = 200
14const MAX_COMMAND_SCAN = 8192
15const MAX_REGEX_SCAN = 2048
16const MAX_PATH = 1024
17const MAX_GLOB_WILDCARDS = 12
18
19type Failed = { ok: false; error: string }
20type Compiled = { ok: true; test: (text: string) => boolean } | Failed
21type CompiledGlob = { ok: true; glob: NormalPath; sensitive: RegExp; insensitive: RegExp } | Failed
22
23// ponycave: plain Map memos, cleared past 256 entries; an LRU only if rule sets get large.
24const commandCache = new Map<string, Compiled>()
25const globCache = new Map<string, CompiledGlob>()
26function memo<T>(cache: Map<string, T>, key: string, build: () => T): T {
27  const hit = cache.get(key)
28  if (hit !== undefined) return hit
29  if (cache.size > 256) cache.clear()
30  const made = build()
31  cache.set(key, made)
32  return made
33}
34
35function squash(text: string): string {
36  return text.replace(/\s+/g, ' ').trim().toLowerCase()
37}
38
39/**
40 * A command pattern: words with `*` wildcards, matched case-insensitively
41 * anywhere in the command (`npm install` matches `cd web && npm install x`),
42 * or `re:<regex>` under limits that keep it from backtracking for long.
43 */
44export function compileCommandPattern(pattern: string): Compiled {
45  return memo(commandCache, pattern, () => {
46    if (pattern.trim() === '') return { ok: false, error: 'the command pattern is empty' }
47    if (pattern.length > MAX_PATTERN) return { ok: false, error: `the command pattern is longer than ${MAX_PATTERN} characters` }
48    if (pattern.startsWith('re:')) return compileGuardedRegex(pattern.slice(3))
49    const segments = squash(pattern).split('*').filter(segment => segment !== '')
50    if (segments.length === 0) return { ok: true, test: () => true }
51    return {
52      ok: true,
53      test: command => {
54        const text = squash(command.slice(0, MAX_COMMAND_SCAN))
55        let from = 0
56        for (const segment of segments) {
57          const at = text.indexOf(segment, from)
58          if (at < 0) return false
59          from = at + segment.length
60        }
61        return true
62      },
63    }
64  })
65}
66
67/** Rejects the regex features that make backtracking blow up; the input is capped too. */
68export function compileGuardedRegex(source: string): Compiled {
69  if (source.length === 0) return { ok: false, error: 'the regex is empty' }
70  if (source.length > MAX_REGEX) return { ok: false, error: `the regex is longer than ${MAX_REGEX} characters` }
71  if (/\\[1-9]|\\k</.test(source)) return { ok: false, error: 'backreferences are not allowed in breakpoint regexes' }
72  if (/\)[*+{]/.test(source)) return { ok: false, error: 'quantified groups such as (a+)+ are not allowed in breakpoint regexes' }
73  const unbounded = source.match(/(?<!\\)[*+]|\{\d+,\}/g)?.length ?? 0
74  if (unbounded > 3) return { ok: false, error: 'a breakpoint regex may hold at most 3 unbounded quantifiers' }
75  let regex: RegExp
76  try {
77    regex = new RegExp(source, 'i')
78  } catch (error) {
79    return { ok: false, error: `invalid regex: ${(error as Error).message}` }
80  }
81  return { ok: true, test: text => regex.test(text.slice(0, MAX_REGEX_SCAN)) }
82}
83
84type NormalPath = { path: string; isWindows: boolean }
85
86/** Forward slashes, a lowercase drive letter, no `./`, no repeated or trailing slash. */
87export function normalizePath(raw: string): NormalPath {
88  const isWindows = raw.includes('\\') || /^[a-zA-Z]:/.test(raw)
89  let path = raw.trim().replace(/\\/g, '/')
90  const isUnc = path.startsWith('//')
91  path = path.replace(/\/{2,}/g, '/').replace(/(^|\/)\.(?=\/|$)/g, '$1').replace(/\/{2,}/g, '/')
92  path = path.replace(/^([a-zA-Z]):/, (_, drive: string) => `${drive.toLowerCase()}:`)
93  if (path.length > 1 && path.endsWith('/') && !/^[a-z]:\/$/.test(path)) path = path.slice(0, -1)
94  if (path.startsWith('./')) path = path.slice(2)
95  return { path: isUnc ? `/${path}` : path, isWindows }
96}
97
98function isAbsolute(path: string): boolean {
99  return path.startsWith('/') || /^[a-z]:\//.test(path)
100}
101
102// Nothing expands `~` or `$HOME`, so a rule and a call can name the same home
103// folder differently. Each side under a home folder (`~/`, `$HOME/`,
104// `%USERPROFILE%\`, `/home/<user>/`, `/Users/<user>/`, `C:\Users\<user>\`)
105// then also matches by its part below home.
106const HOME_ALIAS = /^(?:~|\$home|\$\{home\}|%userprofile%|\$env:userprofile)(?=\/|$)/i
107const HOME = /^(?:~|\$home|\$\{home\}|%userprofile%|\$env:userprofile|\/home\/[^/]+|\/users\/[^/]+|\/root|\/var\/root|[a-z]:\/users\/[^/]+)(?:\/|$)/i
108
109function belowHome(path: string): string | undefined {
110  const found = HOME.exec(path)
111  return found === null ? undefined : path.slice(found[0].length)
112}
113
114function matchBelowHome(glob: string, path: string, insensitive: boolean, cwd?: string): boolean {
115  const full = isAbsolute(path) || HOME_ALIAS.test(path) || cwd === undefined ? path : normalizePath(`${cwd}/${path}`).path
116  const globRest = belowHome(glob)
117  const pathRest = belowHome(full)
118  if (globRest === undefined || pathRest === undefined) return false
119  if (globRest === '') return pathRest === ''
120  const compiled = compileGlob(globRest)
121  return compiled.ok && (insensitive ? compiled.insensitive : compiled.sensitive).test(pathRest)
122}
123
124function globSource(glob: string): string {
125  let out = ''
126  for (let i = 0; i < glob.length; i += 1) {
127    const char = glob[i] as string
128    if (char === '*') {
129      if (glob[i + 1] === '*') {
130        if (glob[i + 2] === '/') {
131          out += '(?:.*/)?'
132          i += 2
133        } else {
134          out += '.*'
135          i += 1
136        }
137      } else {
138        out += '[^/]*'
139      }
140    } else if (char === '?') {
141      out += '[^/]'
142    } else {
143      out += char.replace(/[.+^${}()|[\]\\]/g, '\\$&')
144    }
145  }
146  // `dir/**` also names `dir` itself, so a search rooted at it matches.
147  return out.endsWith('/.*') ? `${out.slice(0, -3)}(?:/.*)?` : out
148}
149
150/**
151 * Glob over a path: `**` any depth, `*` and `?` within one segment. A glob
152 * with no slash matches any segment (`.env*` matches `/repo/.env.local`); a
153 * relative glob matches below the working directory or at any segment
154 * boundary; an absolute one matches the whole path. Case-insensitive when
155 * either side is a Windows path.
156 */
157export function compileGlob(glob: string): CompiledGlob {
158  return memo(globCache, glob, () => {
159    if (glob.trim() === '') return { ok: false, error: 'the path glob is empty' }
160    if (glob.length > MAX_PATTERN) return { ok: false, error: `the path glob is longer than ${MAX_PATTERN} characters` }
161    if ((glob.match(/[*?]/g)?.length ?? 0) > MAX_GLOB_WILDCARDS) return { ok: false, error: `a path glob may hold at most ${MAX_GLOB_WILDCARDS} wildcards` }
162    const normal = normalizePath(glob)
163    const source = `^${globSource(normal.path)}$`
164    return { ok: true, glob: normal, sensitive: new RegExp(source), insensitive: new RegExp(source, 'i') }
165  })
166}
167
168export function matchPath(glob: string, rawPath: string, cwd?: string): boolean {
169  const compiled = compileGlob(glob)
170  if (!compiled.ok || rawPath.length > MAX_PATH) return false
171  const { glob: pattern, sensitive, insensitive } = compiled
172  const target = normalizePath(rawPath)
173  const regex = pattern.isWindows || target.isWindows ? insensitive : sensitive
174  if (HOME_ALIAS.test(pattern.path) || HOME_ALIAS.test(target.path)) {
175    const below = matchBelowHome(pattern.path, target.path, regex === insensitive, cwd)
176    if (below || HOME_ALIAS.test(pattern.path)) return below
177  }
178  const segments = target.path.split('/').filter(segment => segment !== '')
179
180  if (!pattern.path.includes('/')) return segments.some(segment => regex.test(segment))
181
182  if (isAbsolute(pattern.path)) {
183    if (isAbsolute(target.path)) return regex.test(target.path)
184    return cwd !== undefined && regex.test(normalizePath(`${cwd}/${target.path}`).path)
185  }
186
187  if (cwd !== undefined) {
188    const root = normalizePath(cwd).path
189    const fold = (text: string): string => (regex === insensitive ? text.toLowerCase() : text)
190    if (fold(target.path).startsWith(`${fold(root)}/`) && regex.test(target.path.slice(root.length + 1))) return true
191  }
192  for (let i = 0; i < segments.length; i += 1) if (regex.test(segments.slice(i).join('/'))) return true
193  return false
194}
195
196function scopeAdmits(scope: BreakpointScope, call: NormalizedCall): boolean {
197  return scope === 'all' || (scope === 'main') === (call.scope === 'main')
198}
199
200/** Whether a breakpoint's criteria match a call (ignores enabled, kind and threshold). */
201export function criteriaMatch(bp: Breakpoint, call: NormalizedCall, cwd?: string): boolean {
202  if (!scopeAdmits(bp.scope, call)) return false
203  const { tools, command, path } = bp.match
204  if (tools !== undefined && tools.length > 0 && !tools.includes(call.tool)) return false
205  if (command !== undefined) {
206    const compiled = compileCommandPattern(command)
207    if (call.command === undefined || !compiled.ok || !compiled.test(call.command)) return false
208  }
209  if (path !== undefined && !call.paths.some(one => matchPath(path, one, cwd))) return false
210  return true
211}
212
213export type Evaluation = {
214  /** Rules that matched. */
215  hits: Breakpoint[]
216  /** Hits whose threshold is reached: their action applies. */
217  effective: Breakpoint[]
218}
219
220/** The hit counts must already include this call: the caller counts it first (countHits). */
221function evaluate(breakpoints: readonly Breakpoint[], isCandidate: (bp: Breakpoint) => boolean): Evaluation {
222  const hits = breakpoints.filter(isCandidate)
223  const effective = hits.filter(bp => bp.hitThreshold === undefined || bp.hitCount >= bp.hitThreshold)
224  return { hits, effective }
225}
226
227/** The rules with one more hit on each of `ids`: a call counted. */
228export function countHits(breakpoints: readonly Breakpoint[], ids: readonly string[]): Breakpoint[] {
229  return breakpoints.map(bp => (ids.includes(bp.id) ? { ...bp, hitCount: bp.hitCount + 1 } : bp))
230}
231
232/** Before a call runs: every enabled rule other than error rules. */
233export function evaluateCall(breakpoints: readonly Breakpoint[], call: NormalizedCall, cwd?: string): Evaluation {
234  return evaluate(breakpoints, bp => bp.enabled && bp.kind !== 'error' && criteriaMatch(bp, call, cwd))
235}
236
237/** After a call failed: the enabled error rules. */
238export function evaluateError(breakpoints: readonly Breakpoint[], call: NormalizedCall, cwd?: string): Evaluation {
239  return evaluate(breakpoints, bp => bp.enabled && bp.kind === 'error' && criteriaMatch(bp, call, cwd))
240}
241
242export function nextBreakpointId(breakpoints: readonly Breakpoint[]): string {
243  const taken = breakpoints.map(bp => Number(/^bp(\d+)$/.exec(bp.id)?.[1] ?? 0))
244  return `bp${Math.max(0, ...taken) + 1}`
245}
246
247export type Validated = { ok: true; breakpoint: Breakpoint } | { ok: false; error: string }
248
249const isString = (value: unknown): value is string => typeof value === 'string'
250
251/** Validates a rule from the store, a command or the pane; the one gate every rule passes. */
252export function validateBreakpoint(raw: unknown): Validated {
253  if (raw === null || typeof raw !== 'object') return { ok: false, error: 'a breakpoint must be an object' }
254  const r = raw as Record<string, unknown>
255  if (!isString(r.id) || !/^[A-Za-z0-9_-]{1,32}$/.test(r.id)) return { ok: false, error: 'a breakpoint id is 1-32 letters, digits, _ or -' }
256  if (!KINDS.includes(r.kind as BreakpointKind)) return { ok: false, error: `kind must be one of ${KINDS.join(', ')}` }
257  if (!ACTIONS.includes(r.action as BreakpointAction)) return { ok: false, error: `action must be one of ${ACTIONS.join(', ')}` }
258  if (!SCOPES.includes(r.scope as BreakpointScope)) return { ok: false, error: `scope must be one of ${SCOPES.join(', ')}` }
259  const m = (r.match ?? {}) as Record<string, unknown>
260  if (typeof m !== 'object') return { ok: false, error: 'match must be an object' }
261  const match: BreakpointMatch = {}
262  if (m.tools !== undefined) {
263    if (!Array.isArray(m.tools) || !m.tools.every(tool => isString(tool) && /^[A-Za-z0-9_.:-]{1,128}$/.test(tool)) || m.tools.length > 32) {
264      return { ok: false, error: 'tools must be a list of tool names' }
265    }
266    if (m.tools.length > 0) match.tools = [...(m.tools as string[])]
267  }
268  if (m.command !== undefined) {
269    if (!isString(m.command)) return { ok: false, error: 'command must be a string' }
270    const compiled = compileCommandPattern(m.command)
271    if (!compiled.ok) return { ok: false, error: compiled.error }
272    match.command = m.command
273  }
274  if (m.path !== undefined) {
275    if (!isString(m.path)) return { ok: false, error: 'path must be a string' }
276    const compiled = compileGlob(m.path)
277    if (!compiled.ok) return { ok: false, error: compiled.error }
278    match.path = m.path
279  }
280  const kind = r.kind as BreakpointKind
281  if (kind === 'tool' && match.tools === undefined) return { ok: false, error: 'a tool breakpoint names at least one tool' }
282  if (kind === 'command' && match.command === undefined) return { ok: false, error: 'a command breakpoint needs a command pattern' }
283  if (kind === 'file' && match.path === undefined) return { ok: false, error: 'a file breakpoint needs a path glob' }
284  if (kind === 'conditional' && Object.keys(match).length === 0) return { ok: false, error: 'a conditional breakpoint needs at least one of tool, command or path' }
285  let hitThreshold: number | undefined
286  if (r.hitThreshold !== undefined) {
287    if (typeof r.hitThreshold !== 'number' || !Number.isInteger(r.hitThreshold) || r.hitThreshold < 1 || r.hitThreshold > 1_000_000) {
288      return { ok: false, error: 'the hit threshold is a whole number from 1' }
289    }
290    hitThreshold = r.hitThreshold
291  }
292  let simulate: Breakpoint['simulate']
293  if (r.simulate !== undefined) {
294    const s = r.simulate as Record<string, unknown>
295    if (s === null || typeof s !== 'object' || !SIMULATION_KINDS.includes(s.kind as SimulationKind)) return { ok: false, error: 'simulate.kind must be fail or stub' }
296    if (s.text !== undefined && (!isString(s.text) || s.text.length > 2000)) return { ok: false, error: 'simulate.text is a string of at most 2000 characters' }
297    simulate = { kind: s.kind as SimulationKind, ...(isString(s.text) ? { text: s.text } : {}) }
298  }
299  const name = isString(r.name) && r.name.trim() !== '' ? r.name.trim().slice(0, 80) : `${kind} ${r.id}`
300  const hitCount = typeof r.hitCount === 'number' && Number.isInteger(r.hitCount) && r.hitCount >= 0 ? r.hitCount : 0
301  return {
302    ok: true,
303    breakpoint: {
304      id: r.id,
305      name,
306      enabled: r.enabled !== false,
307      kind,
308      match,
309      scope: r.scope as BreakpointScope,
310      action: r.action as BreakpointAction,
311      hitCount,
312      ...(hitThreshold !== undefined ? { hitThreshold } : {}),
313      ...(simulate !== undefined ? { simulate } : {}),
314    },
315  }
316}
317
318/**
319 * Splits a command line into words, honoring "double" and 'single' quotes.
320 * Inside double quotes only \" is unescaped, so regexes (\s) and Windows
321 * paths (C:\repo) keep their backslashes.
322 */
323export function tokenize(input: string): string[] {
324  const out: string[] = []
325  const re = /"((?:[^"\\]|\\.)*)"|'([^']*)'|(\S+)/g
326  for (let m = re.exec(input); m !== null; m = re.exec(input)) {
327    out.push(m[1] !== undefined ? m[1].replace(/\\"/g, '"') : (m[2] ?? m[3] ?? ''))
328  }
329  return out
330}
331
332export const SPEC_HELP = [
333  'tool <Name>[,<Name>...]        pause on every call to these tools',
334  'command <pattern>              Bash command contains the words (* wildcard, re:<regex>)',
335  'file <glob>                    a call names a matching path (src/auth/**, .env*)',
336  'error [<Tool>,...]             after a failed call: surface it, arm a pause on the next call',
337  'when tool=A,B command=".." path=..   all given conditions must match',
338  'flags: --action pause|record|warn  --scope all|main|subagents  --name ".."',
339  '       --after <N> (act from the Nth hit)  --simulate fail|stub  --text ".."  --disabled',
340]
341
342export type Parsed = { ok: true; breakpoint: Breakpoint } | { ok: false; error: string }
343
344/** Parses the rule language `/devtools-break` and the pane's input share. */
345export function parseBreakpointSpec(input: string, id: string, defaultScope: BreakpointScope): Parsed {
346  const words = tokenize(input.trim())
347  const head = words.shift()?.toLowerCase()
348  if (head === undefined) return { ok: false, error: 'empty rule: start with tool, command, file, error or when' }
349  const positional: string[] = []
350  const flags: Record<string, string | true> = {}
351  for (let i = 0; i < words.length; i += 1) {
352    const word = words[i] as string
353    if (/^--[a-z]+$/.test(word)) {
354      const name = word.slice(2)
355      if (name === 'disabled') {
356        flags[name] = true
357        continue
358      }
359      const value = words[i + 1]
360      if (value === undefined) return { ok: false, error: `${word} needs a value` }
361      flags[name] = value
362      i += 1
363    } else {
364      positional.push(word)
365    }
366  }
367  const known = ['action', 'scope', 'name', 'after', 'simulate', 'text', 'disabled']
368  const unknown = Object.keys(flags).find(name => !known.includes(name))
369  if (unknown !== undefined) return { ok: false, error: `unknown flag --${unknown}` }
370
371  const list = (text: string): string[] => text.split(/[\s,]+/).filter(item => item !== '')
372  let kind: BreakpointKind
373  const match: BreakpointMatch = {}
374  switch (head) {
375    case 'tool':
376    case 'tools':
377      kind = 'tool'
378      match.tools = list(positional.join(','))
379      break
380    case 'command':
381    case 'cmd':
382    case 'bash':
383      kind = 'command'
384      match.command = positional.join(' ')
385      break
386    case 'file':
387    case 'path':
388      kind = 'file'
389      match.path = positional.join(' ')
390      break
391    case 'error':
392    case 'errors':
393      kind = 'error'
394      if (positional.length > 0) match.tools = list(positional.join(','))
395      break
396    case 'when':
397    case 'if':
398      kind = 'conditional'
399      for (const pair of positional) {
400        const at = pair.indexOf('=')
401        if (at < 1) return { ok: false, error: `expected key=value, got "${pair}"` }
402        const key = pair.slice(0, at).toLowerCase()
403        const value = pair.slice(at + 1)
404        if (key === 'tool' || key === 'tools') match.tools = list(value)
405        else if (key === 'command' || key === 'cmd') match.command = value
406        else if (key === 'path' || key === 'file') match.path = value
407        else return { ok: false, error: `unknown condition "${key}": use tool, command or path` }
408      }
409      break
410    default:
411      return { ok: false, error: `unknown rule "${head}": start with tool, command, file, error or when` }
412  }
413  const threshold = flags.after === undefined ? undefined : Number(flags.after)
414  const describe = (match.command ?? match.path ?? match.tools?.join(',') ?? 'any tool').slice(0, 48)
415  const draft: Record<string, unknown> = {
416    id,
417    name: typeof flags.name === 'string' ? flags.name : `${kind} ${describe}`,
418    enabled: flags.disabled !== true,
419    kind,
420    match,
421    scope: typeof flags.scope === 'string' ? flags.scope : defaultScope,
422    action: typeof flags.action === 'string' ? flags.action : kind === 'error' ? 'warn' : 'pause',
423    hitCount: 0,
424    ...(threshold !== undefined ? { hitThreshold: threshold } : {}),
425    ...(typeof flags.simulate === 'string'
426      ? { simulate: { kind: flags.simulate, ...(typeof flags.text === 'string' ? { text: flags.text } : {}) } }
427      : {}),
428  }
429  return validateBreakpoint(draft)
430}
431
432export function describeBreakpoint(bp: Breakpoint): string {
433  const parts: string[] = []
434  if (bp.match.tools !== undefined) parts.push(`tool=${bp.match.tools.join(',')}`)
435  if (bp.match.command !== undefined) parts.push(`command="${bp.match.command}"`)
436  if (bp.match.path !== undefined) parts.push(`path=${bp.match.path}`)
437  if (parts.length === 0) parts.push('any tool')
438  const extra = [
439    bp.scope === 'all' ? undefined : `scope ${bp.scope}`,
440    bp.hitThreshold === undefined ? undefined : `from hit ${bp.hitThreshold}`,
441    bp.simulate === undefined ? undefined : `simulate ${bp.simulate.kind}`,
442  ].filter(Boolean)
443  return `${bp.kind} ${parts.join(' ')} → ${bp.action}${extra.length > 0 ? ` (${extra.join(', ')})` : ''}`
444}
445
src/core/controller.ts 178 lines
1// The debugger's decisions as pure functions: whether a call pauses, what the
2// pause dialog offers, what an answer means, and how a finished call is
3// classified. The native layer executes these decisions; it decides nothing.
4
5import type { ArmState, Breakpoint, DevtoolsSettings, PauseDecision, PermissionInfo, RiskLevel, TraceOutcome, TraceStatus } from '../../types'
6import { countHits, evaluateCall, evaluateError } from './breakpoints.ts'
7import { asRecord, type NormalizedCall, type ResultLike } from './events.ts'
8import { withHits } from './suggest.ts'
9
10export const DISARMED: ArmState = { pauseNext: false, step: false }
11
12/** Calls stepping and pause-next never stop on: a question already holds the person. */
13const NOT_STEPPABLE: readonly string[] = ['AskUserQuestion']
14
15export type CallPlan =
16  | { kind: 'pass' }
17  | { kind: 'record'; hits: Breakpoint[] }
18  | { kind: 'warn'; hits: Breakpoint[]; warned: Breakpoint[] }
19  | { kind: 'pause'; hits: Breakpoint[]; at?: Breakpoint; reason: string }
20
21export type Planned = { plan: CallPlan; arm: ArmState }
22
23declare const COUNTED: unique symbol
24
25/**
26 * Rules whose hit counts include the call being planned: the only rules
27 * planning takes, so a call is never planned uncounted. Made by `counted`
28 * (counts the native layer wrote) or `countCall` (a snapshot, counted here).
29 */
30export type Counted = DevtoolsSettings & { readonly [COUNTED]: true }
31
32/** The rules with the counts an atomic count of this call returned; with none, nothing the call matches to count. */
33export function counted(settings: DevtoolsSettings, counts?: Readonly<Record<string, number>>): Counted {
34  return (counts === undefined ? settings : withHits(settings, counts)) as Counted
35}
36
37/** A snapshot that predates the call, with the call counted: one more hit on each rule it matches. */
38export function countCall(settings: DevtoolsSettings, call: NormalizedCall, cwd?: string): Counted {
39  const ids = evaluateCall(settings.breakpoints, call, cwd).hits.map(bp => bp.id)
40  return { ...settings, breakpoints: countHits(settings.breakpoints, ids) } as Counted
41}
42
43/**
44 * Decides what happens to a call before it runs. `active` pauses on pause
45 * rules and on an armed step; `observe` downgrades every pause to a record
46 * and leaves the arm alone; `off` passes everything untouched.
47 */
48export function planCall(settings: Counted, arm: ArmState, call: NormalizedCall, cwd?: string): Planned {
49  if (settings.mode === 'off') return { plan: { kind: 'pass' }, arm }
50  const evaluation = evaluateCall(settings.breakpoints, call, cwd)
51  const hits = evaluation.hits
52  if (settings.mode === 'active') {
53    const at = evaluation.effective.find(bp => bp.action === 'pause')
54    // A pause at a breakpoint also satisfies an armed step; an unarmed arm keeps its identity (no write).
55    if (at !== undefined) return { plan: { kind: 'pause', hits, at, reason: `breakpoint "${at.name}"` }, arm: arm.pauseNext || arm.step ? DISARMED : arm }
56    if ((arm.pauseNext || arm.step) && !NOT_STEPPABLE.includes(call.tool)) {
57      const reason = arm.step ? 'step' : arm.reason !== undefined ? `pause-next (${arm.reason})` : 'pause-next'
58      return { plan: { kind: 'pause', hits, reason }, arm: DISARMED }
59    }
60  }
61  const warned = evaluation.effective.filter(bp => bp.action === 'warn')
62  if (warned.length > 0) return { plan: { kind: 'warn', hits, warned }, arm }
63  if (hits.length > 0) return { plan: { kind: 'record', hits }, arm }
64  return { plan: { kind: 'pass' }, arm }
65}
66
67export type ErrorPlan = { arm: ArmState; triggered: Breakpoint[] }
68
69/**
70 * After a failed call: error rules surface the failure, and an error rule
71 * whose action is pause arms a pause on the next eligible call (a call that
72 * already ran is never paused after the fact).
73 */
74export function planAfterError(settings: Counted, arm: ArmState, call: NormalizedCall, cwd?: string): ErrorPlan {
75  if (settings.mode === 'off') return { arm, triggered: [] }
76  const evaluation = evaluateError(settings.breakpoints, call, cwd)
77  if (evaluation.hits.length === 0) return { arm, triggered: [] }
78  const pauses = settings.mode === 'active' && evaluation.effective.some(bp => bp.action === 'pause')
79  return {
80    arm: pauses ? { pauseNext: true, step: false, reason: `after ${call.tool} failed` } : arm,
81    triggered: evaluation.effective,
82  }
83}
84
85export const LABELS = { continue: 'Continue', step: 'Step', reject: 'Reject', simulate: 'Simulate' } as const
86
87export type PauseQuestion = { question: string; options: string[]; header: string }
88
89export function pauseQuestion(args: {
90  tool: string
91  summary: string
92  reason: string
93  risk: RiskLevel
94  agentId?: string
95  permission?: PermissionInfo
96  canSimulate: boolean
97}): PauseQuestion {
98  const permission = args.permission === undefined ? '' : `, permission ${args.permission.decision}${args.permission.rule !== undefined ? ` by ${args.permission.rule}` : ''}`
99  const agent = args.agentId === undefined ? '' : ` in subagent ${args.agentId}`
100  const options: string[] = [LABELS.continue, LABELS.step, LABELS.reject]
101  if (args.canSimulate) options.push(LABELS.simulate)
102  return {
103    header: 'DevTools',
104    options,
105    question: `Paused at ${args.reason}: ${args.tool}${agent} wants to run ${args.summary} (risk ${args.risk}${permission}). Continue runs it through the normal permission checks; Step runs it and pauses on the next call. What should happen?`,
106  }
107}
108
109export type Interpreted = { decision: PauseDecision; note?: string }
110
111/** Maps the dialog's answer to a decision. Anything unrecognized rejects, keeping the typed text as a note. */
112export function interpretAnswer(answer: string, simulateOffered: boolean): Interpreted {
113  const text = answer.trim()
114  if (text === LABELS.continue) return { decision: 'continue' }
115  if (text === LABELS.step) return { decision: 'step' }
116  if (text === LABELS.reject) return { decision: 'reject' }
117  if (text === LABELS.simulate && simulateOffered) return { decision: 'simulate' }
118  return { decision: 'reject', note: text.slice(0, 500) }
119}
120
121export type RefusalKind = 'debugger' | 'cancelled' | 'headless' | 'aborted' | 'guard'
122
123/** What Claude reads when the debugger keeps a call from running: what happened and what to do next. */
124export function refusalText(kind: RefusalKind, tool: string, reason: string, note?: string): string {
125  switch (kind) {
126    case 'debugger':
127      return `Claude DevTools: the developer rejected this ${tool} call at ${reason}, so it did not run.${note !== undefined && note !== '' ? ` Their note: "${note}".` : ''} Choose a different approach or ask the user how to proceed.`
128    case 'cancelled':
129      return `Claude DevTools: this ${tool} call was held at ${reason} and the question was dismissed, so it did not run. Ask the user how to proceed before retrying it.`
130    case 'headless':
131      return `Claude DevTools: ${reason} requires an interactive decision, but this session has nobody to ask (headless), so the ${tool} call did not run. To let such calls through in headless runs, set the devtools option headlessPause to "record-only" or disable the breakpoint.`
132    case 'aborted':
133      return `Claude DevTools: the turn was interrupted while this ${tool} call was paused at ${reason}; it did not run.`
134    case 'guard':
135      return `Claude DevTools: its breakpoint guard failed (${reason}), so this ${tool} call was not run to keep the breakpoint's promise. Retry, or turn the debugger off with /devtools-disable off.`
136  }
137}
138
139const INTERRUPTED = /\[Request interrupted|interrupted by (the )?user|was interrupted|operation was aborted/i
140const PERMISSION_REJECTED =
141  /doesn't want to proceed|tool use was rejected|permission to use .{1,120} (?:has been|was) denied|denied by (?:a |the )?(?:permission )?(?:rule|policy|settings)|blocked by (?:a |the )?(?:permission|policy)/i
142
143export type Classified = { status: TraceStatus; outcome: TraceOutcome }
144
145/**
146 * Tells a tool failure from a permission denial, a hook's refusal and an
147 * interrupted call. Permission verdicts come from tool.check when observed;
148 * the text patterns are a documented fallback. A deny the call chain shows a
149 * mod returned is that mod's, whatever its words.
150 */
151export function classifyResult(result: ResultLike, permission?: PermissionInfo, isDeniedByMod = false): Classified {
152  if (typeof result.deny === 'string') {
153    if (isDeniedByMod) return { status: 'denied', outcome: 'blocked-by-hook' }
154    return { status: 'denied', outcome: permission?.decision === 'deny' || PERMISSION_REJECTED.test(result.deny) ? 'permission-denied' : 'blocked-by-hook' }
155  }
156  if (result.isError === true) {
157    const text = typeof result.text === 'string' ? result.text : String(result.result ?? '')
158    const record = asRecord(result.result)
159    if (record.interrupted === true || INTERRUPTED.test(text)) return { status: 'failed', outcome: 'aborted' }
160    if (permission?.decision === 'deny' || PERMISSION_REJECTED.test(text)) return { status: 'denied', outcome: 'permission-denied' }
161    return { status: 'failed', outcome: 'tool-error' }
162  }
163  const record = asRecord(result.result)
164  if (record.interrupted === true) return { status: 'failed', outcome: 'aborted' }
165  return { status: 'completed', outcome: 'ok' }
166}
167
168/**
169 * Whether a call would have been held, judged from a settings snapshot alone
170 * (no state reads): the fail-closed check a `.catch` handler runs when the
171 * guard itself failed before deciding.
172 */
173export function wouldPause(settings: DevtoolsSettings | undefined, arm: ArmState | undefined, call: NormalizedCall, cwd?: string): boolean {
174  if (settings === undefined || settings.mode !== 'active') return false
175  // The snapshot's counts predate this call: count it, as the hook would have.
176  return planCall(countCall(settings, call, cwd), arm ?? DISARMED, call, cwd).plan.kind === 'pause'
177}
178
src/core/events.ts 348 lines
1// Event normalization: one shape for every tool call, whatever the tool's own
2// argument and result shapes, plus risk classification and the summaries the
3// timeline keeps. Pure: no Claude Code API here.
4
5import type { RiskLevel } from '../../types'
6import { redactString, redactValue } from '../security/redaction.ts'
7
8/** Tools whose `command` argument is a shell command line. */
9export const SHELL_TOOLS: readonly string[] = ['Bash', 'PowerShell']
10
11/** Arguments that carry file contents: never kept unless raw capture is on. */
12const CONTENT_FIELDS: Readonly<Record<string, readonly string[]>> = {
13  Write: ['content'],
14  Edit: ['old_string', 'new_string'],
15  MultiEdit: ['edits'],
16  NotebookEdit: ['new_source'],
17}
18
19/** Argument names that hold a path, across built-in and MCP tools. */
20const PATH_FIELDS: readonly string[] = ['file_path', 'notebook_path', 'path', 'filePath', 'filepath', 'directory', 'dir']
21
22const RESERVED_KEYS = new Set(['tool', 'tool_use_id', 'agentId', 'consent'])
23
24export type ToolCallLike = {
25  tool: string
26  tool_use_id?: string
27  agentId?: string
28  [argument: string]: unknown
29}
30
31export type NormalizedCall = {
32  tool: string
33  toolUseId?: string
34  agentId?: string
35  scope: 'main' | 'subagent'
36  /** The tool's own arguments, without the envelope keys. */
37  args: Readonly<Record<string, unknown>>
38  /** The shell command line, for shell tools only. */
39  command?: string
40  /** Every path the call names (best effort for shell commands). */
41  paths: string[]
42  risk: RiskLevel
43}
44
45export type SummaryOptions = {
46  maxChars: number
47  redaction: boolean
48  captureRaw: boolean
49}
50
51export function normalizeCall(e: ToolCallLike): NormalizedCall {
52  const args: Record<string, unknown> = {}
53  for (const [key, value] of Object.entries(e)) if (!RESERVED_KEYS.has(key)) args[key] = value
54  const command = SHELL_TOOLS.includes(e.tool) && typeof args.command === 'string' ? args.command : undefined
55  const paths = collectPaths(args, command)
56  return {
57    tool: e.tool,
58    toolUseId: e.tool_use_id,
59    agentId: e.agentId,
60    scope: e.agentId === undefined ? 'main' : 'subagent',
61    args,
62    command,
63    paths,
64    risk: classifyRisk(e.tool, command),
65  }
66}
67
68function collectPaths(args: Record<string, unknown>, command: string | undefined): string[] {
69  const found: string[] = []
70  for (const field of PATH_FIELDS) {
71    const value = args[field]
72    if (typeof value === 'string' && value !== '') found.push(value)
73  }
74  if (Array.isArray(args.paths)) for (const value of args.paths) if (typeof value === 'string') found.push(value)
75  if (command !== undefined) found.push(...shellPathTokens(command))
76  return [...new Set(found)].slice(0, 32)
77}
78
79/** Words of a command line that look like paths: best effort, no full shell parsing. */
80export function shellPathTokens(command: string): string[] {
81  const tokens = command.slice(0, 4096).match(/"[^"]*"|'[^']*'|[^\s;&|<>()]+/g) ?? []
82  return tokens
83    .map(token => token.replace(/^["']|["']$/g, ''))
84    .filter(token => !token.startsWith('-') && /[\\/.]/.test(token) && !/^[a-z]+:\/\//i.test(token) && !token.includes('='))
85}
86
87const DESTRUCTIVE_COMMAND = new RegExp(
88  [
89    String.raw`\brm\s+(-[a-zA-Z]*[rf][a-zA-Z]*\s+)`,
90    String.raw`\bRemove-Item\b.*-Recurse`,
91    String.raw`\bgit\s+push\b.*(\s--force\b|\s-f\b|\s--force-with-lease\b|\s\+)`,
92    String.raw`\bgit\s+reset\s+--hard\b`,
93    String.raw`\bgit\s+clean\s+-[a-zA-Z]*f`,
94    String.raw`\bgit\s+(checkout|restore)\s+(--\s+)?\.(\s|$)`,
95    String.raw`\b(drop|truncate)\s+(table|database|schema)\b`,
96    String.raw`\bdelete\s+from\b`,
97    String.raw`\b(prisma\s+migrate|db:migrate|alembic\s+upgrade|manage\.py\s+migrate|knex\s+migrate|sequelize\s+db:migrate|flyway\s+migrate)\b`,
98    String.raw`\b(npm|pnpm|yarn)\s+publish\b`,
99    String.raw`\bterraform\s+(apply|destroy)\b`,
100    String.raw`\bkubectl\s+(delete|apply|replace)\b`,
101    String.raw`\b(mkfs|fdisk|diskpart)\b`,
102    String.raw`\bdd\s+.*\bof=`,
103    String.raw`\bchmod\s+-R\b`,
104    String.raw`\b(deploy|vercel\s+--prod|fly\s+deploy|heroku\s+releases)\b`,
105  ].join('|'),
106  'i',
107)
108
109// One program (or program and subcommands) per entry, as DESTRUCTIVE_COMMAND lists them.
110const NETWORK_COMMAND = new RegExp(
111  String.raw`\b(${[
112    'curl',
113    'wget',
114    'ssh',
115    'scp',
116    'rsync',
117    'ftp',
118    'nc',
119    'Invoke-WebRequest',
120    'iwr',
121    String.raw`git\s+(push|pull|fetch|clone)`,
122    String.raw`(npm|pnpm|yarn|bun)\s+(install|add|i|ci)`,
123    String.raw`pip3?\s+install`,
124    String.raw`cargo\s+(install|add)`,
125    String.raw`go\s+get`,
126    String.raw`docker\s+(pull|push)`,
127  ].join('|')})\b`,
128  'i',
129)
130
131const READ_ONLY_COMMAND =
132  /^\s*(ls|dir|pwd|cat|head|tail|less|wc|echo|which|where|type|file|stat|du|df|tree|grep|rg|find|git\s+(status|diff|log|show|branch|rev-parse|remote\s+-v|blame)|node\s+(-v|--version)|npm\s+(ls|list|view|-v|--version)|Get-ChildItem|Get-Content|Get-Location)\b/i
133
134const COMMAND_SEPARATOR = /&&|\|\||;|\|/
135
136/** A coarse label for how consequential a call can be. Not a security boundary. */
137export function classifyRisk(tool: string, command?: string): RiskLevel {
138  if (command !== undefined) {
139    if (DESTRUCTIVE_COMMAND.test(command)) return 'destructive'
140    if (NETWORK_COMMAND.test(command)) return 'network'
141    const parts = command.split(COMMAND_SEPARATOR)
142    const isReadOnly =
143      !/[^2]>|>>|\bsudo\b|-delete\b|-exec\b/.test(command) && parts.every(part => READ_ONLY_COMMAND.test(part))
144    return isReadOnly ? 'read' : 'exec'
145  }
146  switch (tool) {
147    case 'Read':
148    case 'Glob':
149    case 'Grep':
150    case 'LS':
151    case 'NotebookRead':
152    case 'LSP':
153      return 'read'
154    case 'Edit':
155    case 'Write':
156    case 'MultiEdit':
157    case 'NotebookEdit':
158      return 'write'
159    case 'WebFetch':
160    case 'WebSearch':
161      return 'network'
162    case 'Agent':
163    case 'Task':
164      return 'exec'
165    default:
166      return 'unknown'
167  }
168}
169
170/** An object's fields, or none for anything else (null, a string, a number). */
171export function asRecord(value: unknown): Record<string, unknown> {
172  return value !== null && typeof value === 'object' ? (value as Record<string, unknown>) : {}
173}
174
175export function truncate(text: string, max: number): string {
176  return text.length <= max ? text : `${text.slice(0, Math.max(0, max - 1))}…`
177}
178
179/** A time of day in UTC (the mod's environment has no time zone), for rows under a header that says UTC. */
180export function clock(ms: number): string {
181  return new Date(ms).toISOString().slice(11, 19)
182}
183
184/** A time of day that stands alone, its zone named. */
185export function clockUtc(ms: number): string {
186  return `${clock(ms)} UTC`
187}
188
189/** The lines joined with ⏎, each trimmed, blank ones dropped. Linear: a regex over long whitespace runs backtracks. */
190export function oneLine(text: string): string {
191  return text
192    .split('\n')
193    .map(line => line.trim())
194    .filter(line => line !== '')
195    .join(' ⏎ ')
196}
197
198function clean(text: string, options: SummaryOptions): string {
199  return options.redaction ? redactString(text) : text
200}
201
202/** The tool's arguments as the inspector shows them: redacted, truncated, file contents omitted. */
203export function sanitizeInput(call: NormalizedCall, options: SummaryOptions): Record<string, unknown> {
204  const omitted = options.captureRaw ? [] : (CONTENT_FIELDS[call.tool] ?? [])
205  const out: Record<string, unknown> = {}
206  for (const [key, value] of Object.entries(call.args)) {
207    if (omitted.includes(key)) {
208      out[key] = `<${describeSize(value)} omitted>`
209      continue
210    }
211    out[key] = shrink(value, options.maxChars * 4, 0)
212  }
213  return (options.redaction ? redactValue(out) : out) as Record<string, unknown>
214}
215
216function describeSize(value: unknown): string {
217  if (typeof value === 'string') return `${value.length} chars`
218  if (Array.isArray(value)) return `${value.length} items`
219  return 'value'
220}
221
222function shrink(value: unknown, max: number, depth: number): unknown {
223  if (typeof value === 'string') return truncate(value, max)
224  if (value === null || typeof value !== 'object') return value
225  if (depth >= 4) return '[…]'
226  if (Array.isArray(value)) {
227    const items = value.slice(0, 20).map(item => shrink(item, max, depth + 1))
228    return value.length > 20 ? [...items, `… ${value.length - 20} more`] : items
229  }
230  const out: Record<string, unknown> = {}
231  for (const [key, item] of Object.entries(value).slice(0, 40)) out[key] = shrink(item, max, depth + 1)
232  return out
233}
234
235/** One line describing the call for the timeline. */
236export function summarizeInput(call: NormalizedCall, options: SummaryOptions): string {
237  const a = call.args
238  const str = (key: string): string => (typeof a[key] === 'string' ? (a[key] as string) : '')
239  let text: string
240  if (call.command !== undefined) {
241    text = call.command + (a.run_in_background === true ? '  (background)' : '')
242  } else {
243    switch (call.tool) {
244      case 'Read':
245        text = str('file_path') + (a.offset !== undefined || a.limit !== undefined ? `  [${String(a.offset ?? 0)}+${String(a.limit ?? '')}]` : '')
246        break
247      case 'Edit':
248        text = `${str('file_path')}  (${str('old_string').length} → ${str('new_string').length} chars${a.replace_all === true ? ', all' : ''})`
249        break
250      case 'Write':
251        text = `${str('file_path')}  (${str('content').length} chars)`
252        break
253      case 'NotebookEdit':
254        text = `${str('notebook_path')}  (${str('edit_mode') || 'replace'})`
255        break
256      case 'Glob':
257        text = str('pattern') + (str('path') ? `  in ${str('path')}` : '')
258        break
259      case 'Grep':
260        text = `/${str('pattern')}/` + (str('path') ? `  in ${str('path')}` : '') + (str('glob') ? `  glob ${str('glob')}` : '')
261        break
262      case 'WebFetch':
263        text = str('url')
264        break
265      case 'WebSearch':
266        text = str('query')
267        break
268      case 'Agent':
269      case 'Task':
270        text = `${str('subagent_type') || 'agent'}: ${str('description')}`
271        break
272      default:
273        // Redacted by key too: a `password` or `token` argument has no secret shape to match.
274        text = JSON.stringify(sanitizeInput(call, options)) ?? ''
275    }
276  }
277  return truncate(oneLine(clean(capped(text), options)), options.maxChars)
278}
279
280/** How much of a summary's text is redacted: far past what any summary shows. */
281const REDACT_CAP = 65_536
282
283/**
284 * Cuts a huge text (a heredoc, a quoted file) before it is redacted, so it is
285 * not scanned whole. The word the cut splits is dropped: a secret cut short
286 * could slip past the patterns. A text that is one long word is cut as is.
287 */
288export function capped(text: string, max = REDACT_CAP): string {
289  if (text.length <= max) return text
290  const cut = text.slice(0, max)
291  const end = Math.max(cut.lastIndexOf(' '), cut.lastIndexOf('\n'), cut.lastIndexOf('\t'), cut.lastIndexOf('\r'))
292  return end < 0 ? cut : cut.slice(0, end)
293}
294
295/** A loose view of `next(e)`'s answer: the ToolCallResult arms, read without trusting shapes. */
296export type ResultLike = {
297  deny?: string
298  result?: unknown
299  text?: string
300  isError?: true
301  isReadOnly?: true
302}
303
304function lineCount(text: string): number {
305  return text === '' ? 0 : text.replace(/\n$/, '').split('\n').length
306}
307
308/** One line describing what came back, with no file contents. */
309export function summarizeResult(tool: string, result: ResultLike, options: SummaryOptions): string {
310  if (typeof result.deny === 'string') return truncate(oneLine(`denied: ${clean(capped(result.deny), options)}`), options.maxChars)
311  if (result.isError === true) {
312    const text = typeof result.text === 'string' ? result.text : String(result.result ?? '')
313    return truncate(oneLine(`error: ${clean(capped(text), options)}`), options.maxChars)
314  }
315  const record = asRecord(result.result)
316  const parts: string[] = []
317  if (SHELL_TOOLS.includes(tool) && typeof record.stdout === 'string') {
318    parts.push(`stdout ${lineCount(record.stdout)} lines`, `stderr ${lineCount(String(record.stderr ?? ''))} lines`)
319    if (record.interrupted === true) parts.push('interrupted')
320    if (typeof record.backgroundTaskId === 'string') parts.push(`background ${record.backgroundTaskId}`)
321  } else if (typeof record.numFiles === 'number') {
322    parts.push(`${record.numFiles} files`)
323    if (typeof record.numLines === 'number') parts.push(`${record.numLines} lines`)
324  } else if (typeof result.text === 'string') {
325    parts.push(`${lineCount(result.text)} lines`, `${result.text.length} chars`)
326  } else if (typeof result.result === 'string') {
327    parts.push(`${result.result.length} chars`)
328  } else {
329    parts.push('ok')
330  }
331  if (result.isReadOnly === true) parts.push('read-only')
332  return truncate(parts.join(', '), options.maxChars)
333}
334
335/** The error text the inspector shows: redacted, longer than a summary. */
336export function errorTextOf(result: ResultLike, options: SummaryOptions): string | undefined {
337  const text = typeof result.deny === 'string' ? result.deny : result.isError === true ? (result.text ?? String(result.result ?? '')) : undefined
338  return text === undefined ? undefined : truncate(clean(text, options), options.maxChars * 4)
339}
340
341/** Raw capture (opt-in): the input and the result text, redacted unless redaction is off. */
342export function rawOf(call: NormalizedCall, result: ResultLike | undefined, options: SummaryOptions): { input: string; result?: string } {
343  const limit = 20_000
344  const input = truncate(clean(JSON.stringify(call.args) ?? '', options), limit)
345  const text = result === undefined ? undefined : (result.deny ?? result.text ?? (typeof result.result === 'string' ? result.result : JSON.stringify(result.result)))
346  return { input, result: text === undefined ? undefined : truncate(clean(text, options), limit) }
347}
348
src/core/lens.ts 732 lines
1// Error Lens: why a tool call failed, from evidence. Deterministic and pure.
2// Every cause carries a certainty: `confirmed` when the result itself, a
3// permission verdict or a file system fact shows it; `possible` when it is a
4// known explanation the evidence does not prove; `unknown` for what no
5// observation here can settle. Nothing is guessed beyond the matched evidence.
6
7import type {
8  Certainty,
9  ErrorCategory,
10  ErrorGroup,
11  LensCause,
12  LensProbe,
13  LensRecord,
14  PermissionInfo,
15  Refusal,
16  TraceOutcome,
17  TraceStatus,
18} from '../../types'
19import { clockUtc, SHELL_TOOLS, truncate } from './events.ts'
20
21export const MAX_MESSAGE = 3000
22export const MAX_LENS = 80
23export const MAX_GROUPS = 50
24const MAX_GROUP_IDS = 20
25
26type Advice = { category: ErrorCategory; meaning: string; possible?: string[]; unknown?: string[]; fixes: string[] }
27
28const LOCKS_UNKNOWN = 'Permission bits, ownership, attributes and file locks are not visible to mods ($.fs.stat reports none), so they could not be checked.'
29
30/** errno-style codes: what the OS said, and what usually explains it. */
31const CODES: Readonly<Record<string, Advice>> = {
32  ENOENT: {
33    category: 'not-found',
34    meaning: 'a path does not exist',
35    possible: ['The path is misspelled, or relative to a different working directory than expected.', 'A parent directory has not been created yet.'],
36    fixes: ['Check the path and the working directory (pwd).', 'Create missing parent directories first (mkdir -p).'],
37  },
38  EACCES: {
39    category: 'access-denied',
40    meaning: 'access was refused',
41    possible: ['This user lacks permission on the file or a parent directory.', 'On Windows: the file is read-only, or another program (editor, antivirus, sync client) holds it.'],
42    unknown: [LOCKS_UNKNOWN],
43    fixes: ['Check permissions (ls -l, or icacls on Windows).', 'Close programs that may hold the file, then retry.', 'Clear a read-only attribute (chmod u+w, or attrib -r on Windows).'],
44  },
45  EPERM: {
46    category: 'not-permitted',
47    meaning: 'the operation is not permitted',
48    possible: ['The file is read-only, locked, or owned by another user.', 'On Windows: another program holds the file, or the location is protected.', "Claude Code's sandbox restricts this operation (sandboxed Bash only)."],
49    unknown: [LOCKS_UNKNOWN],
50    fixes: ['Check permissions and attributes; close programs holding the file.', 'For sandboxed Bash, allow the path in the sandbox settings or run outside the sandbox.'],
51  },
52  EISDIR: { category: 'is-directory', meaning: 'the path is a directory where a file was expected', fixes: ['Use a path to a file inside the directory.'] },
53  ENOTDIR: { category: 'not-directory', meaning: 'a component of the path is not a directory', fixes: ['Check each part of the path: one of them is a file.'] },
54  EEXIST: { category: 'already-exists', meaning: 'the path already exists', fixes: ['Use another name, or remove the existing path if that is intended.'] },
55  EBUSY: {
56    category: 'busy',
57    meaning: 'the file or resource is busy or locked',
58    possible: ['Another process holds it open (an editor, a dev server, antivirus, a sync client).'],
59    unknown: [LOCKS_UNKNOWN],
60    fixes: ['Close the program holding it, then retry.'],
61  },
62  ENOSPC: { category: 'no-space', meaning: 'the device has no space left', fixes: ['Free disk space, then retry.'] },
63  EROFS: { category: 'read-only-fs', meaning: 'the file system is read-only', fixes: ['Write somewhere writable, or remount the volume read-write.'] },
64  EMFILE: { category: 'too-many-files', meaning: 'the process has too many open files', fixes: ['Close file handles or raise the open-file limit (ulimit -n).'] },
65  ENFILE: { category: 'too-many-files', meaning: 'the system has too many open files', fixes: ['Close programs, or raise the system file limit.'] },
66  ENAMETOOLONG: { category: 'name-too-long', meaning: 'the path or a name in it is too long', fixes: ['Shorten the path; on Windows, enable long paths or move the project higher up.'] },
67  ETIMEDOUT: { category: 'timeout', meaning: 'an operation timed out', possible: ['A slow or unreachable network, or a host that does not answer.'], fixes: ['Check connectivity, then retry.'] },
68  ECONNREFUSED: { category: 'network', meaning: 'the connection was refused', possible: ['Nothing listens on that host and port (a server not started?).'], fixes: ['Start the server, or check the host and port.'] },
69  ECONNRESET: { category: 'network', meaning: 'the connection was reset by the other side', fixes: ['Retry; check proxies and the remote service.'] },
70  ENOTFOUND: { category: 'network', meaning: 'a host name did not resolve', fixes: ['Check the host name, DNS and connectivity.'] },
71  EAI_AGAIN: { category: 'network', meaning: 'a host name lookup failed temporarily', fixes: ['Check DNS and connectivity, then retry.'] },
72  EHOSTUNREACH: { category: 'network', meaning: 'the host is unreachable', fixes: ['Check the network route, VPN or firewall.'] },
73  ENETUNREACH: { category: 'network', meaning: 'the network is unreachable', fixes: ['Check the network connection, VPN or firewall.'] },
74}
75
76type TextRule = Advice & { pattern: RegExp; cause: string; mcpOnly?: boolean }
77
78/** Messages of Claude Code's tools and of common programs, most specific first. */
79const TEXT_RULES: readonly TextRule[] = [
80  {
81    category: 'stale-read',
82    pattern: /modified since (?:it was )?(?:last )?read/i,
83    meaning: '',
84    cause: 'The file changed on disk after Claude last read it, so Claude Code refused to overwrite it.',
85    possible: ['You, an editor, a formatter or linter, a file watcher, or another tool call changed the file in between.'],
86    unknown: ['Which process changed the file: mods cannot see other processes.'],
87    fixes: ['Read the file again, then retry the change.', 'If a formatter or watcher rewrites the file, wait for it or pause it while Claude edits.'],
88  },
89  {
90    category: 'not-read-yet',
91    pattern: /has not been read yet|read it first/i,
92    meaning: '',
93    cause: 'Claude Code requires a file to be read in this conversation before it is changed, and it had not been.',
94    fixes: ['Read the file first, then retry.'],
95  },
96  {
97    category: 'edit-mismatch',
98    pattern: /found \d+ matches of the string to replace|replace_all is false/i,
99    meaning: '',
100    cause: 'The text to replace occurs more than once, and replace_all was not set.',
101    fixes: ['Include more surrounding context so the text is unique, or set replace_all.'],
102  },
103  {
104    category: 'edit-mismatch',
105    pattern: /string to replace (?:was )?not found|old_string .{0,40}not found|could not find .{0,60}to replace/i,
106    meaning: '',
107    cause: 'The exact text to replace was not found in the file.',
108    possible: ['The file changed since it was read.', 'Whitespace, indentation or line endings differ from what Claude expected.'],
109    fixes: ['Read the file again and copy the exact text, including whitespace.'],
110  },
111  {
112    category: 'input-invalid',
113    pattern: /no changes to make|old_string and new_string are (?:exactly )?the same/i,
114    meaning: '',
115    cause: 'The edit would change nothing: the old and new text are the same.',
116    fixes: ['Nothing to fix in the file: the edit was a no-op.'],
117  },
118  {
119    category: 'too-large',
120    pattern: /exceeds? (?:the )?maximum (?:allowed )?(?:tokens|size|length)|too large to (?:read|process)|file (?:content|is) too (?:large|big)/i,
121    meaning: '',
122    cause: 'The file or input exceeds a size limit of the tool.',
123    fixes: ['Read it in parts (offset and limit), or search it with Grep.'],
124  },
125  {
126    category: 'input-invalid',
127    pattern: /InputValidationError|invalid (?:input|parameters?|arguments?)|required (?:parameter|property)|is not a valid|expected .{1,40} (?:but )?received/i,
128    meaning: '',
129    cause: 'The tool rejected its arguments as invalid.',
130    fixes: ["Check the arguments against the tool's schema."],
131  },
132  {
133    category: 'timeout',
134    pattern: /timed out|time ?out (?:after|exceeded)|deadline exceeded/i,
135    meaning: '',
136    cause: 'The operation ran longer than its time limit.',
137    possible: ['The command waited for input, a lock or a slow network, or the job is simply long.'],
138    fixes: ['Raise the timeout or run it in the background (run_in_background).', 'Make the command non-interactive (--yes, CI=1).'],
139  },
140  {
141    category: 'command-not-found',
142    pattern: /: command not found|is not recognized as an internal or external command|not recognized as the name of a cmdlet/i,
143    meaning: '',
144    cause: 'The shell could not find the program to run.',
145    possible: ['It is not installed, or not on PATH in the shell Claude Code uses.'],
146    fixes: ['Install the program, or call it by its full path.', 'Check PATH in the shell Claude Code runs (echo $PATH).'],
147  },
148  {
149    category: 'not-found',
150    pattern: /file does not exist|no such file or directory|cannot find the (?:file|path) specified|path not found|directory does not exist/i,
151    meaning: '',
152    cause: 'The tool reported that a path does not exist.',
153    possible: ['The path is misspelled, or relative to a different working directory than expected.'],
154    fixes: ['Check the path; Glob for the file name to find where it is.'],
155  },
156  {
157    category: 'access-denied',
158    pattern: /permission denied|access is denied|access denied/i,
159    meaning: '',
160    cause: 'The operating system or the program refused access.',
161    possible: ['This user lacks permission, or the file is read-only or held by another program.'],
162    unknown: [LOCKS_UNKNOWN],
163    fixes: ['Check permissions; close programs holding the file; retry.'],
164  },
165  {
166    category: 'not-permitted',
167    pattern: /operation not permitted/i,
168    meaning: '',
169    cause: 'The operating system did not permit the operation.',
170    possible: ["The file is read-only or locked, or Claude Code's sandbox restricts it."],
171    unknown: [LOCKS_UNKNOWN],
172    fixes: ['Check permissions and the sandbox settings.'],
173  },
174  {
175    category: 'busy',
176    pattern: /resource busy or locked|being used by another process|file is locked/i,
177    meaning: '',
178    cause: 'The file is in use by another process.',
179    unknown: [LOCKS_UNKNOWN],
180    fixes: ['Close the program holding it, then retry.'],
181  },
182  { category: 'no-space', pattern: /no space left on device|disk (?:is )?full/i, meaning: '', cause: 'The disk is full.', fixes: ['Free disk space, then retry.'] },
183  { category: 'read-only-fs', pattern: /read-only file system/i, meaning: '', cause: 'The file system is read-only.', fixes: ['Write somewhere writable.'] },
184  {
185    category: 'network',
186    pattern: /could not resolve host|connection refused|network is unreachable|getaddrinfo|socket hang up|fetch failed|\bssl\b|certificate (?:has expired|verify failed|is not trusted)|self[- ]signed certificate/i,
187    meaning: '',
188    cause: 'A network request failed.',
189    possible: ['No connectivity, a proxy or firewall, a wrong host, or a server that is down.'],
190    fixes: ['Check connectivity and the URL, then retry.'],
191  },
192  {
193    category: 'mcp',
194    pattern: /MCP error|MCP server|not connected|disconnected|server .{0,40}(?:unavailable|failed to start|not running)/i,
195    meaning: '',
196    cause: 'The MCP server behind this tool reported an error or is not connected.',
197    possible: ['The server crashed, failed to start, or lost its authentication.'],
198    fixes: ['Check the server in /mcp; reconnect or re-authenticate it.'],
199    mcpOnly: true,
200  },
201]
202
203const EXIT_MEANING: Readonly<Record<number, string>> = {
204  124: 'Exit code 124 usually means a `timeout` wrapper stopped the command.',
205  126: 'Exit code 126 usually means the program was found but is not executable.',
206  127: 'Exit code 127 usually means the shell could not find the program.',
207  130: 'Exit code 130 usually means the command was interrupted (Ctrl+C, SIGINT).',
208  137: 'Exit code 137 usually means the process was killed (SIGKILL), often for running out of memory.',
209  143: 'Exit code 143 usually means the process was terminated (SIGTERM).',
210}
211
212const USER_REJECTED = /doesn't want to proceed|tool use was rejected|user (?:rejected|denied|declined)/i
213
214export type DiagnoseInput = {
215  tool: string
216  outcome: TraceOutcome
217  /** The error text as Claude read it, already redacted. */
218  text: string
219  /** The tool's own result record, when there is one (Bash: interrupted). */
220  result?: unknown
221  args: Readonly<Record<string, unknown>>
222  permission?: PermissionInfo
223  /** Who refused the call, when the call chain or the verdict shows it. */
224  refusal?: Refusal
225  durationMs?: number
226  suspected?: boolean
227}
228
229export type Diagnosis = {
230  category: ErrorCategory
231  code?: string
232  exitCode?: number
233  headline: string
234  causes: LensCause[]
235  fixes: string[]
236  mentionedPaths: string[]
237}
238
239/** The text a result carries as its error, whatever its shape. */
240export function errorTextOfResult(result: { deny?: string; text?: string; result?: unknown }): string {
241  if (typeof result.deny === 'string') return result.deny
242  if (typeof result.text === 'string' && result.text !== '') return result.text
243  if (typeof result.result === 'string') return result.result
244  try {
245    return JSON.stringify(result.result) ?? ''
246  } catch {
247    return ''
248  }
249}
250
251function lines(text: string): string[] {
252  return text
253    .replace(/<\/?tool_use_error>/g, '')
254    .split(/\r?\n/)
255    .map(line => line.trim())
256    .filter(line => line !== '')
257}
258
259/** The first meaningful line: not an `Exit code N` line, not a tag. */
260export function headlineOf(text: string): string {
261  const all = lines(text)
262  const line = all.find(one => !/^exit code:? \d+$/i.test(one)) ?? all[0] ?? '(no error text)'
263  return truncate(line, 160)
264}
265
266/** The line of `text` that matched, as a quoted excerpt. */
267function excerpt(text: string, pattern: RegExp): string | undefined {
268  const line = lines(text).find(one => pattern.test(one))
269  return line === undefined ? undefined : `"${truncate(line, 180)}"`
270}
271
272const PATH_QUOTED = /'([^'\n]{2,300})'|"([^"\n]{2,300})"/g
273const PATH_BARE = /(?:^|[\s(=])((?:[A-Za-z]:)?[\\/][^\s:'"(),]{1,300}|\.{1,2}[\\/][^\s:'"(),]{1,300})/g
274
275/** Paths an error names (quoted, absolute or ./relative), at most three. */
276export function pathsInText(text: string): string[] {
277  const found: string[] = []
278  const add = (candidate: string | undefined): void => {
279    if (candidate === undefined) return
280    const value = candidate.trim().replace(/[.,;:]+$/, '')
281    if (value.length < 2 || value.length > 1024 || /^[a-z][a-z0-9+.-]*:\/\//i.test(value) || value.includes('[REDACTED]')) return
282    if (!/[\\/]/.test(value) && !/\.[a-z0-9]{1,8}$/i.test(value)) return
283    if (!found.includes(value)) found.push(value)
284  }
285  for (const match of text.matchAll(PATH_QUOTED)) add(match[1] ?? match[2])
286  for (const match of text.matchAll(PATH_BARE)) add(match[1])
287  return found.slice(0, 3)
288}
289
290function cause(certainty: Certainty, text: string, evidence: Array<string | undefined> = []): LensCause {
291  return { certainty, text, evidence: evidence.filter((item): item is string => item !== undefined && item !== '') }
292}
293
294function fromAdvice(advice: Advice, first: LensCause, out: { causes: LensCause[]; fixes: string[] }): void {
295  out.causes.push(first)
296  for (const text of advice.possible ?? []) out.causes.push(cause('possible', text))
297  for (const text of advice.unknown ?? []) out.causes.push(cause('unknown', text))
298  out.fixes.push(...advice.fixes)
299}
300
301function exitCodeOf(text: string): number | undefined {
302  const match = /(?:^|\n)\s*exit code:? (\d{1,3})\b|exited with (?:code|status) (\d{1,3})\b/i.exec(text)
303  const value = match?.[1] ?? match?.[2]
304  return value === undefined ? undefined : Number(value)
305}
306
307// A path from `/` is POSIX, where a backslash is an ordinary filename character.
308function isWindowsPath(value: unknown): boolean {
309  return typeof value === 'string' && (/^[a-zA-Z]:[\\/]/.test(value) || (value.includes('\\') && !value.startsWith('/')))
310}
311
312/**
313 * Classifies one failure. Order: what DevTools itself or the permission
314 * system decided (known for certain), errno codes in the text, the tools'
315 * own messages, shell exit codes, then unknown.
316 */
317export function diagnose(input: DiagnoseInput): Diagnosis {
318  const { text, tool, outcome } = input
319  const headline = headlineOf(text)
320  const mentionedPaths = pathsInText(text)
321  const quoted = text.trim() === '' ? undefined : `"${truncate(headline, 180)}"`
322  const out: { causes: LensCause[]; fixes: string[] } = { causes: [], fixes: [] }
323  const done = (category: ErrorCategory, extra: Partial<Diagnosis> = {}): Diagnosis => ({
324    category,
325    headline,
326    causes: out.causes,
327    fixes: [...new Set(out.fixes)],
328    mentionedPaths,
329    ...extra,
330  })
331
332  switch (outcome) {
333    case 'debugger-rejected':
334      out.causes.push(cause('confirmed', 'You rejected this call at a Claude DevTools breakpoint, so it never ran.', [quoted]))
335      out.fixes.push('Nothing failed: Claude was told the call was rejected. Disable the breakpoint if it should run.')
336      return done('debugger')
337    case 'user-cancelled':
338      out.causes.push(cause('confirmed', 'The Claude DevTools pause question was dismissed, so the call never ran.', [quoted]))
339      out.fixes.push('Answer the question with Continue to let such a call run.')
340      return done('debugger')
341    case 'headless-rejected':
342      out.causes.push(cause('confirmed', 'A Claude DevTools pause breakpoint matched in a headless session, where nobody can answer, so the call was refused.', [quoted]))
343      out.fixes.push('Set the devtools option headlessPause to "record-only", or disable the breakpoint for headless runs.')
344      return done('debugger')
345    case 'guard-failed':
346      out.causes.push(cause('confirmed', "Claude DevTools' own breakpoint guard failed, so it refused the call to keep the breakpoint's promise.", [quoted]))
347      out.fixes.push('Retry; if it repeats, run claude --debug and look for devtools lines.')
348      return done('debugger')
349    case 'simulated':
350      out.causes.push(cause('confirmed', 'Claude DevTools answered with a simulated failure; the real tool never ran.', [quoted]))
351      out.fixes.push('Nothing to fix: this failure was injected on purpose.')
352      return done('simulated')
353    case 'aborted':
354      out.causes.push(cause('confirmed', 'The call was interrupted (Esc, or an abort) before it finished.', [quoted]))
355      out.fixes.push('Rerun it if it is still needed.')
356      return done('interrupted')
357    case 'permission-denied': {
358      const p = input.permission
359      if (p?.decision === 'deny' && p.decidedBy !== undefined) {
360        out.causes.push(cause('confirmed', `The mod ${p.decidedBy.plugin} (${p.decidedBy.tier} tier) changed the permission verdict to deny.`, [`tool.check verdict: deny (${p.source})`, p.reason]))
361        out.fixes.push(`If it should run, check what ${p.decidedBy.plugin} allows (/plugin).`)
362      } else if (p?.decision === 'deny' && p.hook !== undefined) {
363        out.causes.push(cause('confirmed', `A ${p.hook} settings hook denied this call.`, [`tool.check verdict: deny by the ${p.hook} hook (${p.source})`, p.reason]))
364        out.fixes.push('Review the hook in /hooks if the call should run.')
365      } else if (p?.decision === 'deny') {
366        out.causes.push(
367          cause('confirmed', `Claude Code's permission check denied this call${p.rule !== undefined ? ` by the rule ${p.rule}` : ''}.`, [
368            `tool.check verdict: deny (${p.source})`,
369            p.reason,
370          ]),
371        )
372        out.fixes.push(`If it should run, change the rule${p.rule !== undefined ? ` ${p.rule}` : ''} in your settings (/permissions).`)
373      } else if (USER_REJECTED.test(text)) {
374        out.causes.push(cause('confirmed', 'The permission prompt for this call was answered with a rejection.', [excerpt(text, USER_REJECTED)]))
375        out.fixes.push('Approve the call when prompted, or add an allow rule in /permissions.')
376      } else {
377        out.causes.push(cause('possible', 'A permission rule or the permission prompt refused the call; the message reads like a permission denial.', [quoted]))
378        out.causes.push(cause('unknown', 'Which rule refused it: no deny verdict was observed for this call.'))
379        out.fixes.push('Check /permissions for a deny or ask rule matching this tool.')
380      }
381      return done('permission-denied')
382    }
383    case 'blocked-by-hook': {
384      const r = input.refusal
385      if (r?.by === 'mod' && r.certainty === 'confirmed' && r.plugin !== undefined) {
386        out.causes.push(cause('confirmed', `The mod ${r.plugin}${r.tier !== undefined ? ` (${r.tier} tier)` : ''} refused the call before it ran.`, [quoted, r.evidence]))
387        out.fixes.push(`Read its refusal; what ${r.plugin} holds or refuses is set in that mod (/plugin).`)
388        return done('blocked-by-hook')
389      }
390      out.causes.push(cause('confirmed', 'A settings hook or another mod beneath Claude DevTools refused the call before it ran.', [quoted]))
391      if (r?.by === 'settings-hook') out.causes.push(cause('possible', 'Claude Code itself refused it, not a mod: a PreToolUse settings hook is the usual cause.', [r.evidence]))
392      else out.causes.push(cause('unknown', 'Which hook or mod refused it: the result does not name it (claude --debug logs the plugin that denied).'))
393      out.fixes.push('Read the refusal text; review /hooks and the mods in /plugin.')
394      return done('blocked-by-hook')
395    }
396    default:
397      break
398  }
399
400  const exitCode = SHELL_TOOLS.includes(tool) ? exitCodeOf(text) : undefined
401  const exitEvidence = exitCode === undefined ? undefined : `exit code ${exitCode}`
402
403  if (input.suspected === true) {
404    out.causes.push(cause('possible', 'The tool reported success, but its output begins like an error message.', [quoted]))
405    out.causes.push(cause('unknown', 'Whether the call really failed: the tool did not flag it as an error.'))
406    out.fixes.push('Read the output to decide whether the call did what was intended.')
407    return done('suspected')
408  }
409
410  const code = /\b(E[A-Z_]{2,14})\b/g
411  for (const match of text.matchAll(code)) {
412    const name = match[1] as string
413    const advice = CODES[name]
414    if (advice === undefined) continue
415    // The sandbox restricts Bash alone: the hint does not apply to the file tools.
416    const applicable = SHELL_TOOLS.includes(tool) ? advice : { ...advice, possible: (advice.possible ?? []).filter(text => !text.includes('sandbox')) }
417    fromAdvice(applicable, cause('confirmed', `The operating system reported ${name}: ${advice.meaning}.`, [excerpt(text, new RegExp(`\\b${name}\\b`)), exitEvidence]), out)
418    return done(advice.category, { code: name, ...(exitCode !== undefined ? { exitCode } : {}) })
419  }
420
421  for (const rule of TEXT_RULES) {
422    if (rule.mcpOnly === true && !tool.startsWith('mcp__')) continue
423    if (!rule.pattern.test(text)) continue
424    const possible = [...(rule.possible ?? [])]
425    if (rule.category === 'edit-mismatch' && isWindowsPath(input.args.file_path)) possible.push('The file uses Windows line endings (CRLF) where the text to replace has LF.')
426    fromAdvice({ ...rule, possible }, cause('confirmed', rule.cause, [excerpt(text, rule.pattern), exitEvidence]), out)
427    return done(rule.category, exitCode !== undefined ? { exitCode } : {})
428  }
429
430  if (exitCode !== undefined) {
431    out.causes.push(cause('confirmed', `The command exited with code ${exitCode}.`, [excerpt(text, /exit code|exited with/i)]))
432    const meaning = EXIT_MEANING[exitCode]
433    if (meaning !== undefined) out.causes.push(cause('possible', meaning))
434    else out.causes.push(cause('unknown', "Why: no known signature matched; the command's own output (below) is the evidence."))
435    addTimeoutHint(input, out)
436    out.fixes.push('Read the command output below; run the command yourself to reproduce it.')
437    return done('exit-code', { exitCode })
438  }
439
440  if (tool.startsWith('mcp__')) {
441    out.causes.push(cause('confirmed', 'The MCP server returned an error for this tool.', [quoted]))
442    out.causes.push(cause('unknown', 'Why: the message matches no known signature; it is the server\'s own.'))
443    out.fixes.push('Read the server\'s message below; check the server in /mcp.')
444    return done('mcp')
445  }
446
447  out.causes.push(cause('unknown', 'No known error signature matched, so the cause cannot be determined from the result alone.', [quoted]))
448  addTimeoutHint(input, out)
449  out.fixes.push('Read the original error below.', 'Reproduce the call by hand to see more detail.')
450  return done('unknown')
451}
452
453/** A shell call that failed after running about as long as its limit. */
454function addTimeoutHint(input: DiagnoseInput, out: { causes: LensCause[]; fixes: string[] }): void {
455  if (!SHELL_TOOLS.includes(input.tool) || input.durationMs === undefined) return
456  const limit = typeof input.args.timeout === 'number' ? input.args.timeout : 120_000
457  if (input.durationMs >= limit - 1000) {
458    out.causes.push(cause('possible', `It ran for ${Math.round(input.durationMs / 1000)}s, about its time limit of ${Math.round(limit / 1000)}s, so it may have been stopped for time.`))
459  }
460}
461
462/** Masks paths, quoted text and numbers so repeats of one failure share a signature. */
463export function signatureOf(tool: string, category: ErrorCategory, headline: string): string {
464  const masked = headline
465    .replace(/'[^']*'|"[^"]*"/g, '…')
466    .replace(/(?:[A-Za-z]:)?[\\/][^\s:]+|\S+[\\/]\S+/g, '<path>')
467    .replace(/\d+/g, '#')
468    .toLowerCase()
469  return truncate(`${tool}|${category}|${masked}`, 140)
470}
471
472/**
473 * Whether an MCP call the server reported as successful reads like a failure.
474 * Built-in tools flag their own errors, so only MCP servers, which sometimes
475 * answer an error as plain text, are judged this way.
476 */
477export function looksLikeFailure(tool: string, result: { deny?: string; isError?: true; text?: string; result?: unknown }): boolean {
478  if (typeof result.deny === 'string' || result.isError === true || !tool.startsWith('mcp__')) return false
479  const text = typeof result.text === 'string' ? result.text : typeof result.result === 'string' ? result.result : ''
480  return /^\s*(?:error|failed|failure|exception|traceback|fatal)\b[\s:!]/i.test(text.slice(0, 200))
481}
482
483const FILE_TOOLS: readonly string[] = ['Write', 'Edit', 'MultiEdit', 'Read', 'NotebookEdit']
484const DIR_TOOLS: readonly string[] = ['Grep', 'Glob']
485const NO_PROBE: readonly ErrorCategory[] = ['debugger', 'simulated', 'interrupted', 'permission-denied', 'blocked-by-hook', 'network', 'mcp', 'input-invalid', 'timeout']
486
487export type ProbeTarget = { path: string; role: LensProbe['role'] }
488
489export function parentOf(path: string): string | undefined {
490  const cut = isWindowsPath(path) ? Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\')) : path.lastIndexOf('/')
491  if (cut <= 0) return undefined
492  const parent = path.slice(0, cut)
493  return /^[A-Za-z]:$/.test(parent) ? `${parent}\\` : parent
494}
495
496/** The read-only checks worth making for a failure: its target, the target's parent, paths the error names. */
497export function probePlan(tool: string, category: ErrorCategory, args: Readonly<Record<string, unknown>>, mentioned: readonly string[]): ProbeTarget[] {
498  if (NO_PROBE.includes(category)) return []
499  const out: ProbeTarget[] = []
500  const add = (path: string | undefined, role: ProbeTarget['role']): boolean => {
501    // Skipped: network paths (a stat could reach out), globs, and spellings redaction or truncation changed (a stat would report a path nobody named).
502    if (path === undefined || path === '' || path.length > 1024 || /^[\\/]{2}/.test(path) || /[*?]/.test(path) || path.includes('[REDACTED]') || path.endsWith('…')) return false
503    if (!out.some(one => one.path === path)) out.push({ path, role })
504    return true
505  }
506  const field = (name: string): string | undefined => (typeof args[name] === 'string' ? (args[name] as string) : undefined)
507  const target = FILE_TOOLS.includes(tool) ? (field('file_path') ?? field('notebook_path')) : DIR_TOOLS.includes(tool) ? field('path') : undefined
508  // The parent of a path that could not be checked would be a guess.
509  if (add(target, 'target') && FILE_TOOLS.includes(tool)) add(parentOf(target as string), 'parent')
510  for (const path of mentioned) add(path, 'mentioned')
511  return out.slice(0, 5)
512}
513
514function size(bytes: number): string {
515  return bytes < 1024 ? `${bytes} B` : bytes < 1024 * 1024 ? `${(bytes / 1024).toFixed(1)} KB` : `${(bytes / 1024 / 1024).toFixed(1)} MB`
516}
517
518/** One line describing a probe, for the view and reports. */
519export function describeProbe(probe: LensProbe): string {
520  if (probe.exists === null) return `${probe.role} ${probe.path}: could not be checked (${probe.error ?? 'error'})`
521  if (!probe.exists) return `${probe.role} ${probe.path}: does not exist`
522  const parts = [probe.kind === 'dir' ? 'directory' : probe.kind ?? 'exists']
523  if (probe.kind === 'file' && probe.size !== undefined) parts.push(size(probe.size))
524  if (probe.mtimeMs !== undefined) parts.push(`modified ${clockUtc(probe.mtimeMs)}`)
525  if (probe.isLink === true) parts.push(`link → ${probe.realPath ?? '?'}`)
526  return `${probe.role} ${probe.path}: ${parts.join(' · ')}`
527}
528
529/** Grace for file system clocks (FAT's 2 s granularity, a skew between the host clock and the file system's). */
530const MTIME_GRACE_MS = 2000
531
532/**
533 * What the read-only checks show. Facts about the files are `confirmed`
534 * (they were observed after the failure, and say so); what they suggest
535 * about the failure is `possible`.
536 */
537export function interpretProbes(
538  record: Pick<LensRecord, 'tool' | 'category' | 'startedAtMs' | 'endedAtMs' | 'contentBytes'>,
539  probes: readonly LensProbe[],
540): { causes: LensCause[]; fixes: string[] } {
541  const causes: LensCause[] = []
542  const fixes: string[] = []
543  const isWrite = record.tool === 'Write' || record.tool === 'NotebookEdit'
544  for (const probe of probes) {
545    const fact = describeProbe(probe)
546    if (probe.exists === null) {
547      causes.push(cause('confirmed', `Checking ${probe.path} after the failure also failed: ${probe.error ?? 'unknown error'}.`, [fact]))
548      continue
549    }
550    if (probe.role === 'target') {
551      if (!probe.exists) {
552        causes.push(cause('confirmed', isWrite ? `${probe.path} does not exist after the call: the write did not land.` : `${probe.path} does not exist.`, [fact]))
553        if (!isWrite) fixes.push('Check the path; Glob for the file name to find where it is.')
554      } else if (probe.kind === 'dir' && record.tool !== 'Grep' && record.tool !== 'Glob') {
555        causes.push(cause('confirmed', `${probe.path} is a directory, not a file.`, [fact]))
556        fixes.push('Use a path to a file.')
557      } else if (probe.kind === 'file' && probe.mtimeMs !== undefined) {
558        const changedDuring = probe.mtimeMs >= record.startedAtMs - MTIME_GRACE_MS
559        if (isWrite && changedDuring) {
560          causes.push(cause('confirmed', `${probe.path} exists and was modified at ${clockUtc(probe.mtimeMs)}, during or right after this call.`, [fact]))
561          if (record.contentBytes !== undefined && probe.size === record.contentBytes) {
562            causes.push(cause('possible', `The write may have landed despite the reported error: the file's size (${probe.size} bytes) equals what Claude meant to write.`, [fact]))
563            fixes.push('Read the file to check its content before retrying the write.')
564          }
565        } else if (isWrite) {
566          causes.push(cause('confirmed', `${probe.path} exists but was last modified at ${clockUtc(probe.mtimeMs)}, before this call: the call did not change it.`, [fact]))
567        } else if (record.category === 'stale-read') {
568          causes.push(cause('confirmed', `${probe.path} was last modified at ${clockUtc(probe.mtimeMs)}${changedDuring ? ', during or after this call' : ''}.`, [fact]))
569        }
570      }
571      if (probe.isLink === true) causes.push(cause('possible', `${probe.path} is a symbolic link to ${probe.realPath ?? 'an unresolved target'}; the tool may have followed it somewhere unexpected.`, [fact]))
572      if (isWindowsPath(probe.path) && probe.path.length >= 260) {
573        causes.push(cause('possible', `The path is ${probe.path.length} characters, past Windows' classic 260-character limit (MAX_PATH).`, [fact]))
574        fixes.push('Enable long paths on Windows, or shorten the path.')
575      }
576    } else if (probe.role === 'parent') {
577      if (!probe.exists) {
578        causes.push(cause('confirmed', `The parent directory ${probe.path} does not exist.`, [fact]))
579        fixes.push(`Create it first: mkdir -p "${probe.path}"`)
580      } else if (probe.kind !== 'dir') {
581        causes.push(cause('confirmed', `${probe.path} is a file, so nothing can be created inside it.`, [fact]))
582      } else if (record.category === 'not-found') {
583        causes.push(cause('confirmed', 'The parent directory exists, so only the file itself is missing.', [fact]))
584      }
585    } else if (!probe.exists) {
586      causes.push(cause('confirmed', `${probe.path}, named in the error, does not exist now.`, [fact]))
587    } else {
588      causes.push(cause('possible', `${probe.path}, named in the error, exists now: it may have been created after the failure, or the error meant another location.`, [fact]))
589    }
590  }
591  return { causes, fixes }
592}
593
594/** Orders causes confirmed first, keeping each group's order, and drops exact repeats. */
595export function orderCauses(causes: readonly LensCause[]): LensCause[] {
596  const rank: Record<Certainty, number> = { confirmed: 0, possible: 1, unknown: 2 }
597  const seen = new Set<string>()
598  return causes
599    .filter(one => (seen.has(one.text) ? false : (seen.add(one.text), true)))
600    .map((one, index) => ({ one, index }))
601    .sort((a, b) => rank[a.one.certainty] - rank[b.one.certainty] || a.index - b.index)
602    .map(({ one }) => one)
603}
604
605const ANSI = /\u001b\[[0-9;?]*[ -/]*[@-~]|\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)/g
606
607export type CaptureInput = {
608  id: string
609  seq: number
610  tool: string
611  agentId?: string
612  startedAtMs: number
613  endedAtMs: number
614  status: TraceStatus
615  outcome: TraceOutcome
616  suspected?: boolean
617  /** The error text, already redacted. */
618  text: string
619  result?: unknown
620  /** Sanitized arguments, as the timeline keeps them. */
621  args: Record<string, unknown>
622  paths: string[]
623  permission?: PermissionInfo
624  refusal?: Refusal
625  contentBytes?: number
626  probing: 'probe' | 'classify'
627}
628
629/** A diagnosed failure, ready to keep; its probes still to run when the plan has any. */
630export function buildLensRecord(input: CaptureInput): { record: LensRecord; plan: ProbeTarget[] } {
631  const durationMs = Math.max(0, input.endedAtMs - input.startedAtMs)
632  // Terminal color and cursor codes from shell output would garble the pane.
633  const text = input.text.replace(ANSI, '')
634  const diagnosis = diagnose({
635    tool: input.tool,
636    outcome: input.outcome,
637    text,
638    result: input.result,
639    args: input.args,
640    ...(input.permission !== undefined ? { permission: input.permission } : {}),
641    ...(input.refusal !== undefined ? { refusal: input.refusal } : {}),
642    durationMs,
643    ...(input.suspected === true ? { suspected: true } : {}),
644  })
645  const plan = input.probing === 'probe' ? probePlan(input.tool, diagnosis.category, input.args, diagnosis.mentionedPaths) : []
646  const record: LensRecord = {
647    id: input.id,
648    seq: input.seq,
649    tool: input.tool,
650    ...(input.agentId !== undefined ? { agentId: input.agentId } : {}),
651    startedAtMs: input.startedAtMs,
652    endedAtMs: input.endedAtMs,
653    durationMs,
654    status: input.status,
655    outcome: input.outcome,
656    ...(input.suspected === true ? { suspected: true } : {}),
657    category: diagnosis.category,
658    ...(diagnosis.code !== undefined ? { code: diagnosis.code } : {}),
659    ...(diagnosis.exitCode !== undefined ? { exitCode: diagnosis.exitCode } : {}),
660    headline: diagnosis.headline,
661    message: truncate(text, MAX_MESSAGE),
662    signature: signatureOf(input.tool, diagnosis.category, diagnosis.headline),
663    args: input.args,
664    paths: input.paths,
665    ...(input.permission !== undefined ? { permission: input.permission } : {}),
666    ...(input.contentBytes !== undefined ? { contentBytes: input.contentBytes } : {}),
667    causes: orderCauses(diagnosis.causes),
668    fixes: diagnosis.fixes,
669    probes: [],
670    probeState: input.probing === 'classify' ? 'off' : plan.length === 0 ? 'none' : 'pending',
671  }
672  return { record, plan }
673}
674
675/** Folds probe results into a record: facts and what they suggest, causes reordered. */
676export function withProbes(record: LensRecord, probes: readonly LensProbe[]): LensRecord {
677  const found = interpretProbes(record, probes)
678  return {
679    ...record,
680    probes: [...probes],
681    probeState: 'done',
682    causes: orderCauses([...found.causes.filter(one => one.certainty === 'confirmed'), ...record.causes, ...found.causes.filter(one => one.certainty !== 'confirmed')]),
683    fixes: [...new Set([...found.fixes, ...record.fixes])],
684  }
685}
686
687/** Adds a failure to its group (by signature), newest group first; bounded. */
688export function addToGroups(groups: readonly ErrorGroup[], record: LensRecord, max = MAX_GROUPS): { groups: ErrorGroup[]; group: ErrorGroup } {
689  const existing = groups.find(group => group.signature === record.signature)
690  const group: ErrorGroup =
691    existing === undefined
692      ? { signature: record.signature, tool: record.tool, category: record.category, headline: record.headline, count: 1, firstMs: record.endedAtMs, lastMs: record.endedAtMs, ids: [record.id] }
693      : { ...existing, headline: record.headline, count: existing.count + 1, lastMs: record.endedAtMs, ids: [...existing.ids, record.id].slice(-MAX_GROUP_IDS) }
694  return { groups: [group, ...groups.filter(one => one.signature !== record.signature)].slice(0, max), group }
695}
696
697/** Whether a failure is worth a toast: the first of its group, then every fifth. */
698export function shouldNotify(group: ErrorGroup): boolean {
699  return group.count === 1 || group.count % 5 === 0
700}
701
702const CERTAINTY_LABEL: Record<Certainty, string> = { confirmed: 'CONFIRMED', possible: 'POSSIBLE', unknown: 'UNKNOWN' }
703
704/** A plain-text report of one failure: the commands' output and the Markdown export share it. */
705export function lensReport(record: LensRecord): string[] {
706  const out = [
707    `✗ ${record.tool} · ${record.category}${record.code !== undefined ? ` (${record.code})` : ''}${record.exitCode !== undefined ? ` · exit ${record.exitCode}` : ''} · ${new Date(record.endedAtMs).toISOString()}`,
708    `  error: ${record.headline}`,
709  ]
710  if (record.permission !== undefined) out.push(`  permission: ${record.permission.decision}${record.permission.rule !== undefined ? ` by ${record.permission.rule}` : ''} (${record.permission.source})`)
711  for (const certainty of ['confirmed', 'possible', 'unknown'] as const) {
712    const items = record.causes.filter(one => one.certainty === certainty)
713    if (items.length === 0) continue
714    out.push(`  ${CERTAINTY_LABEL[certainty]}`)
715    for (const item of items) {
716      out.push(`    - ${item.text}`)
717      for (const evidence of item.evidence) out.push(`      evidence: ${evidence}`)
718    }
719  }
720  if (record.probes.length > 0) {
721    out.push('  checks (read-only, after the failure)')
722    for (const probe of record.probes) out.push(`    - ${describeProbe(probe)}`)
723  } else if (record.probeState === 'pending') {
724    out.push('  checks: running')
725  }
726  if (record.fixes.length > 0) {
727    out.push('  try')
728    record.fixes.forEach((fix, index) => out.push(`    ${index + 1}. ${fix}`))
729  }
730  return out
731}
732
src/core/recorder.ts 323 lines
1// The bounded timeline and its exports: a ring buffer of trace events, a
2// versioned JSON export with a validator, and a readable Markdown report.
3
4import type { Breakpoint, Certainty, Denial, DevtoolsMode, DevtoolsStats, ErrorGroup, LensRecord, PermissionsSnapshot, TraceEvent, TraceOutcome, TraceStatus } from '../../types'
5import { describeBreakpoint } from './breakpoints.ts'
6import { asRecord } from './events.ts'
7import { lensReport } from './lens.ts'
8import { permissionsReport, UNREAD_PERMISSIONS } from './permissions.ts'
9
10export const TRACE_SCHEMA = 'claude-devtools.trace'
11/** 2: adds Error Lens (`errors`, `errorGroups`). 3: adds refused calls (`denials`) and the permission rules (`permissions`). */
12export const TRACE_SCHEMA_VERSION = 3
13/** Kept under $.fs.write's 4 MiB per file. */
14export const MAX_EXPORT_BYTES = 3_500_000
15
16/** Appends, dropping the oldest past `max`. */
17export function appendBounded<T>(list: readonly T[], item: T, max: number): T[] {
18  const next = [...list, item]
19  return next.length > max ? next.slice(next.length - max) : next
20}
21
22/** Applies a patch to one event by id; an id no longer in the ring is ignored. */
23export function patchEvent(list: readonly TraceEvent[], id: string, patch: Partial<TraceEvent>): TraceEvent[] {
24  return list.map(event => (event.id === id ? { ...event, ...patch } : event))
25}
26
27/** After a reload no hook still holds a call: what was pending or running is closed as aborted. */
28export function closeStale(list: readonly TraceEvent[]): TraceEvent[] {
29  return list.map(event =>
30    event.status === 'pending' || event.status === 'running'
31      ? { ...event, status: 'failed', outcome: 'aborted', errorText: 'Closed by Claude DevTools: the mod reloaded while this call was in flight.' }
32      : event,
33  )
34}
35
36export type TraceExport = {
37  schema: typeof TRACE_SCHEMA
38  schemaVersion: typeof TRACE_SCHEMA_VERSION
39  generator: { name: string; version: string }
40  exportedAt: string
41  sessionId: string
42  redaction: boolean
43  rawCapture: boolean
44  mode: DevtoolsMode
45  /** Events dropped to keep the file under the size limit, oldest first. */
46  droppedEvents: number
47  stats: DevtoolsStats
48  breakpoints: Array<Pick<Breakpoint, 'id' | 'name' | 'kind' | 'enabled' | 'action' | 'scope' | 'match' | 'hitCount'>>
49  events: TraceEvent[]
50  /** Error Lens: the diagnosed failures, oldest first. */
51  errors: LensRecord[]
52  /** Error Lens: repeated failures grouped by signature, most recent first. */
53  errorGroups: ErrorGroup[]
54  /** Refused calls with who refused them, oldest first; also those refused before DevTools saw them, which have no event. */
55  denials: Denial[]
56  /** The permission rules, as last read from the settings files. */
57  permissions: PermissionsSnapshot
58}
59
60export function buildExport(args: {
61  version: string
62  exportedAt: string
63  sessionId: string
64  redaction: boolean
65  rawCapture: boolean
66  mode: DevtoolsMode
67  stats: DevtoolsStats
68  breakpoints: readonly Breakpoint[]
69  events: readonly TraceEvent[]
70  errors?: readonly LensRecord[]
71  errorGroups?: readonly ErrorGroup[]
72  denials?: readonly Denial[]
73  permissions?: PermissionsSnapshot
74}): TraceExport {
75  return {
76    schema: TRACE_SCHEMA,
77    schemaVersion: TRACE_SCHEMA_VERSION,
78    generator: { name: 'devtools', version: args.version },
79    exportedAt: args.exportedAt,
80    sessionId: args.sessionId,
81    redaction: args.redaction,
82    rawCapture: args.rawCapture,
83    mode: args.mode,
84    droppedEvents: 0,
85    stats: args.stats,
86    breakpoints: args.breakpoints.map(({ id, name, kind, enabled, action, scope, match, hitCount }) => ({ id, name, kind, enabled, action, scope, match, hitCount })),
87    events: [...args.events],
88    errors: [...(args.errors ?? [])],
89    errorGroups: [...(args.errorGroups ?? [])],
90    denials: [...(args.denials ?? [])],
91    permissions: args.permissions ?? UNREAD_PERMISSIONS,
92  }
93}
94
95/** `mayReplace`: the target is in the export folder, the only place an existing file may be replaced. */
96export type ExportPaths = { ok: true; json: string; markdown?: string; mayReplace: boolean } | { ok: false; error: string }
97
98const EXPORT_FOLDER = '.claude-devtools'
99
100/** Files coding agents read as instructions; an export never writes one. */
101const INSTRUCTIONS_FILE = /(^|[\\/])(claude|claude\.local|agents|gemini)\.md$/i
102
103/**
104 * Where `/devtools-export [path] [--md]` writes. A path is the person's own
105 * input, so it is checked: a .json or .md name, no `..` segment, no control
106 * characters, no unexpanded `~` or environment variable, no hidden file or folder (where settings and tool configuration
107 * live) but the export folder, no instructions file; a relative path lands
108 * under the session's working directory. Outside the export folder the
109 * caller refuses to replace an existing file, so no build, settings or
110 * instructions file is ever overwritten.
111 */
112export function exportPaths(arg: string | undefined, cwd: string, stamp: string, wantsMarkdown: boolean): ExportPaths {
113  const root = cwd.replace(/[\\/]+$/, '')
114  const target = arg === undefined || arg === '' ? `${EXPORT_FOLDER}/trace-${stamp}.json` : arg
115  if (/[\u0000-\u001f]/.test(target)) return { ok: false, error: 'the export path holds a control character' }
116  // Nothing expands these here, so `~/t.json` would land in a folder named `~` under the working directory.
117  if (/^~|\$[A-Za-z_{(]|%[A-Za-z_][A-Za-z0-9_]*%/.test(target)) {
118    return { ok: false, error: 'the export path uses ~ or an environment variable, which are not expanded: give the full path' }
119  }
120  const segments = target.split(/[\\/]/).filter(part => part !== '' && part !== '.')
121  if (segments.includes('..')) return { ok: false, error: 'the export path may not contain ".." segments' }
122  if (segments.some(part => part.startsWith('.') && part !== EXPORT_FOLDER)) {
123    return { ok: false, error: `the export path may not name a hidden file or folder other than ${EXPORT_FOLDER}/` }
124  }
125  const isAbsolutePath = /^([a-zA-Z]:[\\/]|[\\/])/.test(target)
126  const full = isAbsolutePath ? target : `${root}/${target}`
127  const lower = full.toLowerCase()
128  let paths: { json: string; markdown?: string }
129  if (lower.endsWith('.json')) paths = { json: full, ...(wantsMarkdown ? { markdown: `${full.slice(0, -5)}.md` } : {}) }
130  else if (lower.endsWith('.md')) paths = { json: `${full.slice(0, -3)}.json`, markdown: full }
131  else return { ok: false, error: 'the export path must end in .json or .md' }
132  if (paths.markdown !== undefined && INSTRUCTIONS_FILE.test(paths.markdown)) {
133    return { ok: false, error: 'the export path names an instructions file (CLAUDE.md, AGENTS.md, GEMINI.md)' }
134  }
135  return { ok: true, ...paths, mayReplace: !isAbsolutePath && segments[0] === EXPORT_FOLDER }
136}
137
138function byteLength(text: string): number {
139  return new TextEncoder().encode(text).length
140}
141
142/** Serializes, dropping the oldest events until the text fits `maxBytes`. */
143export function serializeExport(trace: TraceExport, maxBytes = MAX_EXPORT_BYTES): string {
144  let current = trace
145  let text = JSON.stringify(current, null, 2)
146  while (byteLength(text) > maxBytes && current.events.length > 0) {
147    const drop = Math.max(1, Math.ceil(current.events.length / 10))
148    current = { ...current, events: current.events.slice(drop), droppedEvents: current.droppedEvents + drop }
149    text = JSON.stringify(current, null, 2)
150  }
151  return text
152}
153
154const CERTAINTIES: readonly Certainty[] = ['confirmed', 'possible', 'unknown']
155const STATUSES: readonly TraceStatus[] = ['pending', 'running', 'completed', 'failed', 'denied', 'simulated']
156const OUTCOMES: readonly TraceOutcome[] = [
157  'ok',
158  'tool-error',
159  'permission-denied',
160  'blocked-by-hook',
161  'debugger-rejected',
162  'user-cancelled',
163  'headless-rejected',
164  'simulated',
165  'timeout',
166  'aborted',
167  'guard-failed',
168]
169
170/** A time Date can show: a finite number of milliseconds within its range. */
171function isTime(value: unknown): boolean {
172  return typeof value === 'number' && Math.abs(value) <= 8.64e15
173}
174
175/** Checks a parsed export against the schema; returns the problems, empty when valid. */
176export function validateExport(value: unknown): string[] {
177  const problems: string[] = []
178  if (value === null || typeof value !== 'object') return ['the export is not an object']
179  const x = value as Record<string, unknown>
180  if (x.schema !== TRACE_SCHEMA) problems.push(`schema must be "${TRACE_SCHEMA}"`)
181  if (x.schemaVersion !== TRACE_SCHEMA_VERSION) problems.push(`schemaVersion must be ${TRACE_SCHEMA_VERSION}`)
182  if (typeof x.exportedAt !== 'string' || Number.isNaN(Date.parse(x.exportedAt))) problems.push('exportedAt must be an ISO time')
183  if (typeof x.sessionId !== 'string') problems.push('sessionId must be a string')
184  if (typeof x.redaction !== 'boolean') problems.push('redaction must be a boolean')
185  if (!Array.isArray(x.breakpoints)) problems.push('breakpoints must be an array')
186  if (!Array.isArray(x.errorGroups)) problems.push('errorGroups must be an array')
187  const permissions = asRecord(x.permissions)
188  const isRule = (row: unknown): boolean => ['behavior', 'rule', 'source'].every(key => typeof asRecord(row)[key] === 'string')
189  const isDirectory = (row: unknown): boolean => ['path', 'source'].every(key => typeof asRecord(row)[key] === 'string')
190  const mode = permissions.defaultMode
191  const isMode = mode === undefined || ['mode', 'source'].every(key => typeof asRecord(mode)[key] === 'string')
192  if (
193    typeof permissions.readAtMs !== 'number' ||
194    !isMode ||
195    !Array.isArray(permissions.rules) ||
196    !permissions.rules.every(isRule) ||
197    !Array.isArray(permissions.directories) ||
198    !permissions.directories.every(isDirectory) ||
199    !Array.isArray(permissions.errors) ||
200    !permissions.errors.every(error => typeof error === 'string')
201  ) {
202    problems.push('permissions must be an object with readAtMs, an optional defaultMode, and rules, directories and errors arrays')
203  }
204  if (!Array.isArray(x.denials)) problems.push('denials must be an array')
205  else
206    x.denials.forEach((raw, i) => {
207      const d = asRecord(raw)
208      const refusal = asRecord(d.refusal)
209      if (typeof d.id !== 'string' || d.id === '' || typeof d.tool !== 'string' || !isTime(d.atMs) || typeof d.inputSummary !== 'string') {
210        problems.push(`denials[${i}] needs an id, tool, a valid atMs and inputSummary`)
211      }
212      if (['by', 'reason', 'evidence'].some(key => typeof refusal[key] !== 'string') || !CERTAINTIES.includes(refusal.certainty as Certainty)) {
213        problems.push(`denials[${i}].refusal needs by, reason, evidence and a known certainty`)
214      }
215    })
216  if (!Array.isArray(x.errors)) problems.push('errors must be an array')
217  else
218    x.errors.forEach((raw, i) => {
219      const r = asRecord(raw)
220      const at = `errors[${i}]`
221      if (typeof r.id !== 'string' || r.id === '') problems.push(`${at}.id must be a non-empty string`)
222      if (typeof r.tool !== 'string' || r.tool === '') problems.push(`${at}.tool must be a non-empty string`)
223      if (typeof r.category !== 'string' || r.category === '') problems.push(`${at}.category must be a non-empty string`)
224      if (typeof r.message !== 'string') problems.push(`${at}.message must be a string`)
225      if (!Array.isArray(r.causes) || r.causes.some(c => !CERTAINTIES.includes(asRecord(c).certainty as Certainty))) {
226        problems.push(`${at}.causes must be an array of causes with a known certainty`)
227      }
228      if (!Array.isArray(r.probes)) problems.push(`${at}.probes must be an array`)
229    })
230  if (!Array.isArray(x.events)) return [...problems, 'events must be an array']
231  x.events.forEach((raw, i) => {
232    const e = asRecord(raw)
233    const at = `events[${i}]`
234    if (typeof e.id !== 'string' || e.id === '') problems.push(`${at}.id must be a non-empty string`)
235    if (typeof e.tool !== 'string' || e.tool === '') problems.push(`${at}.tool must be a non-empty string`)
236    if (!STATUSES.includes(e.status as TraceStatus)) problems.push(`${at}.status is not a known status`)
237    if (e.outcome !== undefined && !OUTCOMES.includes(e.outcome as TraceOutcome)) problems.push(`${at}.outcome is not a known outcome`)
238    if (typeof e.startedAt !== 'string' || Number.isNaN(Date.parse(e.startedAt))) problems.push(`${at}.startedAt must be an ISO time`)
239    if (typeof e.simulated !== 'boolean') problems.push(`${at}.simulated must be a boolean`)
240    if (e.simulated === true && e.status !== 'simulated') problems.push(`${at} is simulated but its status is ${String(e.status)}`)
241    if (e.durationMs !== undefined && (typeof e.durationMs !== 'number' || e.durationMs < 0)) problems.push(`${at}.durationMs must be a non-negative number`)
242  })
243  return problems
244}
245
246const ICON: Record<TraceStatus, string> = {
247  pending: '⏸',
248  running: '…',
249  completed: '✓',
250  failed: '✗',
251  denied: '⊘',
252  simulated: '◇',
253}
254
255export function statusIcon(status: TraceStatus): string {
256  return ICON[status]
257}
258
259export function formatDuration(ms: number | undefined): string {
260  if (ms === undefined) return '—'
261  if (ms < 1000) return `${Math.round(ms)}ms`
262  if (ms < 60_000) return `${(ms / 1000).toFixed(1)}s`
263  return `${Math.floor(ms / 60_000)}m${Math.round((ms % 60_000) / 1000)}s`
264}
265
266function cell(text: string): string {
267  return text.replace(/\|/g, '\\|').replace(/\n/g, ' ')
268}
269
270/** A readable report of an export. */
271export function exportToMarkdown(trace: TraceExport): string {
272  const lines = [
273    '# Claude DevTools trace',
274    '',
275    `- Session: \`${trace.sessionId || 'unknown'}\``,
276    `- Exported: ${trace.exportedAt}`,
277    `- Mode: ${trace.mode} · redaction ${trace.redaction ? 'on' : 'OFF'} · raw capture ${trace.rawCapture ? 'ON' : 'off'}`,
278    `- Calls observed: ${trace.stats.observed} · failed ${trace.stats.failed} · denied ${trace.stats.denied} · simulated ${trace.stats.simulated} · paused ${trace.stats.paused}`,
279    ...(trace.droppedEvents > 0 ? [`- ${trace.droppedEvents} oldest events dropped to fit the file size limit`] : []),
280    '',
281    '## Breakpoints',
282    '',
283    ...(trace.breakpoints.length === 0
284      ? ['None.']
285      : trace.breakpoints.map(bp => `- \`${bp.id}\` ${bp.enabled ? '●' : '○'} **${cell(bp.name)}**: ${cell(describeBreakpoint(bp))} · hits ${bp.hitCount}`)),
286    '',
287    '## Timeline',
288    '',
289    '| # | Time | Status | Tool | Agent | Duration | Input | Result |',
290    '| - | - | - | - | - | - | - | - |',
291    ...trace.events.map(e =>
292      [
293        '',
294        String(e.seq),
295        e.startedAt,
296        `${ICON[e.status]} ${e.status}${e.outcome !== undefined && e.outcome !== 'ok' ? ` (${e.outcome})` : ''}${e.simulated ? ' **SIMULATED**' : ''}`,
297        cell(e.tool),
298        e.agentId ?? 'main',
299        formatDuration(e.durationMs),
300        `\`${cell(e.inputSummary)}\``,
301        cell(e.errorText ?? e.resultSummary ?? ''),
302        '',
303      ].join(' | ').trim(),
304    ),
305    '',
306    '## Error Lens',
307    '',
308    ...(trace.errors.length === 0 ? ['No failed tool calls.', ''] : []),
309    ...(trace.errorGroups.some(group => group.count > 1)
310      ? ['| Count | Tool | Kind | Error |', '| - | - | - | - |', ...trace.errorGroups.map(g => `| ${g.count} | ${cell(g.tool)} | ${g.category} | ${cell(g.headline)} |`), '']
311      : []),
312    // A fence inside quoted error text would end the block early.
313    ...trace.errors.flatMap(record => ['```text', ...lensReport(record).map(line => line.replace(/`{3,}/g, "'''")), '```', '']),
314    '## Permissions',
315    '',
316    '```text',
317    ...permissionsReport(trace.permissions, trace.denials).map(line => line.replace(/`{3,}/g, "'''")),
318    '```',
319    '',
320  ]
321  return lines.join('\n')
322}
323
src/core/permissions.ts 262 lines
1// Permissions: who refused a tool call and why, from the evidence the engine
2// gives (the permission check's verdict, the call chain's trace, the refusal
3// text), and the permission rules as the settings files hold them. Pure.
4// An attribution is `confirmed` only when the verdict or the trace names it;
5// one read from the refusal's own words is `possible`.
6
7import type { Denial, PermissionInfo, PermissionRuleRow, PermissionsSnapshot, Refusal, SettingsSourceName, TraceOutcome } from '../../types'
8import { capped, clock, truncate } from './events.ts'
9
10/** The snapshot before the settings files are read. */
11export const UNREAD_PERMISSIONS: PermissionsSnapshot = { readAtMs: 0, rules: [], directories: [], errors: [] }
12
13/** A refused call in a few words: the tool and what it was asked to do. */
14export function denialLabel(denial: Pick<Denial, 'tool' | 'inputSummary'>): string {
15  return denial.inputSummary === '' ? denial.tool : `${denial.tool} ${denial.inputSummary}`
16}
17
18/** The settings files, the one that wins first (managed policy, then --settings, local, project, user). */
19export const SOURCES: readonly SettingsSourceName[] = ['policy', 'flag', 'local', 'project', 'user']
20const BEHAVIORS = ['deny', 'ask', 'allow'] as const
21export const MAX_DENIALS = 80
22const MAX_REASON = 600
23const MAX_RULES_PER_LIST = 200
24const MAX_RULE = 500
25const MAX_READ_ERROR = 200
26
27export const SOURCE_LABEL: Readonly<Record<SettingsSourceName, string>> = {
28  policy: 'managed policy',
29  flag: '--settings',
30  local: '.claude/settings.local.json',
31  project: '.claude/settings.json',
32  user: '~/.claude/settings.json',
33}
34
35/** One link of a chain as `next.trace` lists it, reduced to what attribution reads. */
36export type Link = { index: number; plugin: string; tier: string; returned?: unknown }
37
38type Verdict = { decision: 'allow' | 'ask' | 'deny'; rule?: string; reason?: string; hook?: string }
39
40function isVerdict(value: unknown): value is Verdict {
41  const decision = (value as { decision?: unknown } | undefined)?.decision
42  return decision === 'allow' || decision === 'ask' || decision === 'deny'
43}
44
45/** Claude Code's own link (its rules, mode and settings hooks), not a mod. */
46export const isEngine = (link: { plugin: string; tier: string }): boolean => link.plugin === 'engine' || link.tier === 'core'
47
48/**
49 * The verdict a call reached beneath DevTools' tool.check hook, and the mod
50 * that set it when a mod's hook changed what was beneath it. The innermost
51 * link is the baseline (Claude Code's rules, mode and settings hooks).
52 */
53export function checkVerdict(trace: readonly Link[]): PermissionInfo | undefined {
54  const settled = trace.filter(link => isVerdict(link.returned)).sort((a, b) => a.index - b.index)
55  const top = settled[0]
56  if (top === undefined) return undefined
57  let decider: Link | undefined
58  for (let i = settled.length - 2; i >= 0; i -= 1) {
59    const link = settled[i] as Link
60    if ((link.returned as Verdict).decision !== ((settled[i + 1] as Link).returned as Verdict).decision) decider = link
61  }
62  const verdict = top.returned as Verdict
63  return {
64    decision: verdict.decision,
65    ...(verdict.rule !== undefined ? { rule: verdict.rule } : {}),
66    ...(verdict.reason !== undefined ? { reason: verdict.reason } : {}),
67    ...(verdict.hook !== undefined ? { hook: verdict.hook } : {}),
68    ...(decider !== undefined && !isEngine(decider) ? { decidedBy: { plugin: decider.plugin, tier: decider.tier } } : {}),
69    source: 'observed',
70  }
71}
72
73/** The link that refused a call: the innermost one that returned a deny (those above it passed it on). */
74export function callDenier(trace: readonly Link[]): { plugin: string; tier: string } | undefined {
75  const denied = trace
76    .filter(link => typeof (link.returned as { deny?: unknown } | null | undefined)?.deny === 'string')
77    .sort((a, b) => b.index - a.index)[0]
78  return denied === undefined ? undefined : { plugin: denied.plugin, tier: denied.tier }
79}
80
81const DEVTOOLS_OUTCOMES: readonly TraceOutcome[] = ['debugger-rejected', 'user-cancelled', 'headless-rejected', 'guard-failed']
82const USER_REJECTED = /doesn't want to proceed|tool use was rejected|user (?:rejected|denied|declined)/i
83const MODE = /\bmode\b/i
84
85export type RefusalInput = {
86  outcome: TraceOutcome
87  /** The refusal as Claude read it, already redacted. */
88  text: string
89  permission?: PermissionInfo
90  /** Who returned the deny in the tool.call chain beneath DevTools. */
91  denier?: { plugin: string; tier: string }
92  /** False when the call was refused before DevTools' tool.call hook ran. */
93  seen: boolean
94}
95
96/** Who refused a call, most certain evidence first: DevTools' own record, the chain's trace, the verdict, the text. */
97export function explainRefusal(input: RefusalInput): Refusal {
98  const reason = truncate(input.text.trim(), MAX_REASON)
99  const made = (by: Refusal['by'], certainty: Refusal['certainty'], evidence: string, extra: Partial<Refusal> = {}): Refusal => ({ by, ...extra, reason, certainty, evidence })
100  const { permission: p, denier } = input
101
102  if (DEVTOOLS_OUTCOMES.includes(input.outcome)) return made('devtools', 'confirmed', 'Claude DevTools recorded its own decision')
103  if (denier !== undefined && !isEngine(denier)) {
104    return made('mod', 'confirmed', `call chain: ${denier.plugin} (${denier.tier} tier) returned the refusal`, { plugin: denier.plugin, tier: denier.tier })
105  }
106  if (p?.decision === 'deny') {
107    if (p.decidedBy !== undefined) {
108      return made('mod', 'confirmed', `permission check: ${p.decidedBy.plugin} (${p.decidedBy.tier} tier) changed the verdict to deny`, { ...p.decidedBy })
109    }
110    if (p.hook !== undefined) return made('settings-hook', 'confirmed', `permission check: deny from the ${p.hook} hook`, { hook: p.hook })
111    if (p.rule !== undefined) return made('rule', 'confirmed', `permission check: deny by the rule ${p.rule}`, { rule: p.rule })
112    const said = p.reason ?? ''
113    return made('mode', MODE.test(said) ? 'confirmed' : 'possible', `permission check: deny with no rule${said !== '' ? `: ${truncate(said, 160)}` : ''}`)
114  }
115  if (USER_REJECTED.test(input.text)) return made('prompt', 'confirmed', 'the refusal says the permission prompt was answered no')
116  if (input.outcome === 'permission-denied' && p?.decision === 'ask') return made('prompt', 'possible', 'permission check: ask, and the call was refused after it')
117  if (!input.seen) {
118    const plugin = guessPlugin(input.text)
119    if (plugin !== undefined) return made('mod', 'possible', `refused before Claude DevTools' hook ran; the refusal starts with "${plugin}"`, { plugin })
120    return made('unknown', 'possible', "refused before Claude DevTools saw the call: a mod seated above it, a managed hook or Claude Code itself")
121  }
122  if (denier !== undefined) return made('settings-hook', 'possible', 'Claude Code itself refused it, not a mod; a PreToolUse settings hook is the usual cause')
123  if (input.outcome === 'permission-denied') return made('unknown', 'possible', 'the refusal reads like a permission denial; no verdict was observed for this call')
124  return made('unknown', 'possible', 'nothing observed names who refused it')
125}
126
127const NOT_A_NAME = /^(?:error|warning|fatal|note|hint|info|exception|failed|denied)$/i
128
129/** A mod's name as its refusal starts: `name: ...`, `[name] ...`, or `Two Words held|blocked|refused ...`. */
130export function guessPlugin(text: string): string | undefined {
131  const found = /^\s*(?:\[([a-z0-9][\w.-]{1,40})\]|([a-z0-9][a-z0-9._-]{1,40}):\s)/.exec(text) ?? /^\s*([A-Z][\w-]*(?: [A-Z][\w-]*){1,3}) (?:held|blocked|refused|denied|stopped|rejected)\b/.exec(text)
132  const name = found?.[1] ?? found?.[2] ?? found?.[3]
133  return name === undefined || NOT_A_NAME.test(name) ? undefined : name
134}
135
136const NOT_A_REFUSAL = /InputValidationError|No such tool|is not available|\[Request interrupted|interrupted by (?:the )?user/i
137
138function resultText(content: unknown): string {
139  if (typeof content === 'string') return content
140  if (!Array.isArray(content)) return ''
141  return content
142    .map(block => (block !== null && typeof block === 'object' && (block as { type?: unknown }).type === 'text' ? String((block as { text?: unknown }).text ?? '') : ''))
143    .join('\n')
144}
145
146/**
147 * Error results, in a tool-result row, for calls DevTools' hook never saw
148 * (refused above it), and for DevTools' own refusals (`isOwn`), whatever
149 * words the engine's error put in them.
150 */
151export function unseenRefusals(
152  content: readonly unknown[],
153  isSeen: (toolUseId: string) => boolean,
154  isOwn: (toolUseId: string) => boolean = () => false,
155): Array<{ toolUseId: string; text: string }> {
156  const out: Array<{ toolUseId: string; text: string }> = []
157  for (const block of content) {
158    if (block === null || typeof block !== 'object') continue
159    const b = block as { type?: unknown; tool_use_id?: unknown; content?: unknown; is_error?: unknown }
160    if (b.type !== 'tool_result' || b.is_error !== true || typeof b.tool_use_id !== 'string') continue
161    const isMine = isOwn(b.tool_use_id)
162    if (!isMine && isSeen(b.tool_use_id)) continue
163    const text = resultText(b.content).replace(/<\/?tool_use_error>/g, '').trim()
164    if (text === '' || (!isMine && NOT_A_REFUSAL.test(text))) continue
165    out.push({ toolUseId: b.tool_use_id, text })
166  }
167  return out
168}
169
170function strings(value: unknown, redact: (text: string) => string): string[] {
171  if (!Array.isArray(value)) return []
172  return value.filter((item): item is string => typeof item === 'string' && item.trim() !== '').slice(0, MAX_RULES_PER_LIST).map(item => truncate(redact(item.trim()), MAX_RULE))
173}
174
175/** The permission settings from each file, as `$.settings.read({ source })` answered; malformed values are skipped. */
176export function readPermissions(
177  bySource: Partial<Record<SettingsSourceName, unknown>>,
178  errors: readonly string[],
179  readAtMs: number,
180  redact: (text: string) => string = text => text,
181): PermissionsSnapshot {
182  const rules: PermissionRuleRow[] = []
183  const directories: PermissionsSnapshot['directories'] = []
184  let defaultMode: PermissionsSnapshot['defaultMode']
185  for (const behavior of BEHAVIORS) {
186    for (const source of SOURCES) {
187      const permissions = (bySource[source] as { permissions?: Record<string, unknown> } | undefined)?.permissions
188      if (permissions === null || typeof permissions !== 'object') continue
189      for (const rule of new Set(strings(permissions[behavior], redact))) rules.push({ behavior, rule, source })
190    }
191  }
192  for (const source of SOURCES) {
193    const permissions = (bySource[source] as { permissions?: Record<string, unknown> } | undefined)?.permissions
194    if (permissions === null || typeof permissions !== 'object') continue
195    if (defaultMode === undefined && typeof permissions.defaultMode === 'string') defaultMode = { mode: permissions.defaultMode, source }
196    for (const path of strings(permissions.additionalDirectories, redact)) directories.push({ path, source })
197  }
198  // Redacted before cut: a parse error can quote the file, and a secret cut short could slip past the patterns.
199  const read = errors.map(error => truncate(redact(capped(error, 4096)), MAX_READ_ERROR))
200  return { readAtMs, ...(defaultMode !== undefined ? { defaultMode } : {}), rules, directories, errors: read }
201}
202
203/** The file that holds a rule, the one that wins first. */
204export function ruleSource(snapshot: PermissionsSnapshot, rule: string, behavior?: PermissionRuleRow['behavior']): SettingsSourceName | undefined {
205  return snapshot.rules.find(row => row.rule === rule && (behavior === undefined || row.behavior === behavior))?.source
206}
207
208/** Who refused, in a few words. */
209export function describeRefusal(refusal: Refusal, snapshot: PermissionsSnapshot): string {
210  const maybe = refusal.certainty === 'confirmed' ? '' : 'probably '
211  switch (refusal.by) {
212    case 'rule': {
213      const source = refusal.rule === undefined ? undefined : ruleSource(snapshot, refusal.rule, 'deny') ?? ruleSource(snapshot, refusal.rule)
214      return `rule ${refusal.rule ?? '?'}${source !== undefined ? ` in ${SOURCE_LABEL[source]}` : ''}`
215    }
216    case 'mode':
217      return refusal.certainty === 'confirmed' ? 'the permission mode' : "the permission mode or the tool's own check"
218    case 'prompt':
219      return `${maybe}you, at the permission prompt`
220    case 'settings-hook':
221      return `${maybe}a ${refusal.hook ?? 'PreToolUse'} settings hook`
222    case 'mod':
223      return refusal.plugin === undefined ? `${maybe}a mod` : `${maybe}mod ${refusal.plugin}${refusal.tier !== undefined ? ` (${refusal.tier} tier)` : ''}`
224    case 'devtools':
225      return 'Claude DevTools (your breakpoint)'
226    default:
227      return 'not determinable'
228  }
229}
230
231/** Keeps the newest refusals, one per call. */
232export function addDenial(list: readonly Denial[], denial: Denial): Denial[] {
233  return [...list.filter(one => one.id !== denial.id), denial].slice(-MAX_DENIALS)
234}
235
236const BEHAVIOR_MARK = { deny: '✗', ask: '?', allow: '✓' } as const
237
238/** The rules and the refused calls as text: the command's output. */
239export function permissionsReport(snapshot: PermissionsSnapshot, denials: readonly Denial[]): string[] {
240  const out = snapshot.readAtMs === 0 ? ['Rules: not read this session.'] : rulesReport(snapshot)
241  out.push('', denials.length === 0 ? 'Refused calls: none this session.' : `Refused calls (${denials.length}), newest first, times in UTC:`)
242  for (const denial of [...denials].reverse()) {
243    out.push(`  ✗ ${clock(denial.atMs)} ${denialLabel(denial)}`)
244    out.push(`    refused by ${describeRefusal(denial.refusal, snapshot)} (${denial.refusal.certainty})`)
245    out.push(`    reason: ${denial.refusal.reason}`)
246    out.push(`    evidence: ${denial.refusal.evidence}`)
247  }
248  return out
249}
250
251function rulesReport(snapshot: PermissionsSnapshot): string[] {
252  const out = [`Default mode: ${snapshot.defaultMode === undefined ? 'default (not set)' : `${snapshot.defaultMode.mode} (${SOURCE_LABEL[snapshot.defaultMode.source]})`}`]
253  for (const behavior of BEHAVIORS) {
254    const rows = snapshot.rules.filter(row => row.behavior === behavior)
255    out.push(`${behavior[0]?.toUpperCase()}${behavior.slice(1)} rules: ${rows.length === 0 ? 'none' : rows.length}`)
256    for (const row of rows) out.push(`  ${BEHAVIOR_MARK[behavior]} ${behavior.padEnd(5)} ${row.rule}  · ${SOURCE_LABEL[row.source]}${row.source === 'policy' ? ' 🔒' : ''}`)
257  }
258  if (snapshot.directories.length > 0) out.push(`Extra directories: ${snapshot.directories.map(dir => `${dir.path} (${SOURCE_LABEL[dir.source]})`).join(', ')}`)
259  for (const error of snapshot.errors) out.push(`Not read: ${error}`)
260  return out
261}
262
src/core/simulation.ts 56 lines
1// Synthetic results: opt-in, allowlisted, always labeled, and never claiming
2// that a side effect happened. A simulated call never reaches the real tool.
3
4import type { Breakpoint, SimulationKind } from '../../types'
5import { SHELL_TOOLS, type NormalizedCall } from './events.ts'
6
7/** Tools whose calls may be answered with a simulated failure. */
8export const SIMULATION_TOOLS: readonly string[] = [
9  'Bash',
10  'PowerShell',
11  'Read',
12  'Edit',
13  'Write',
14  'NotebookEdit',
15  'Glob',
16  'Grep',
17  'WebFetch',
18  'WebSearch',
19]
20
21export const SIMULATED_FAILURE_TAG = '[Claude DevTools · SIMULATED FAILURE]'
22export const SIMULATED_OUTPUT_TAG = '[Claude DevTools · SIMULATED OUTPUT: the command was NOT executed]'
23
24export type SimulationCheck = { ok: true; kind: SimulationKind; text?: string } | { ok: false; reason: string }
25
26/**
27 * Whether 'Simulate' may be offered for this call: simulation switched on,
28 * an allowlisted tool, and for a stubbed output a shell command classified
29 * read-only, so a canned output can never stand in for a write, migration,
30 * deployment or other consequential operation.
31 */
32export function checkSimulation(isEnabled: boolean, bp: Breakpoint | undefined, call: NormalizedCall): SimulationCheck {
33  if (!isEnabled) return { ok: false, reason: 'simulation is off (devtools option "simulation")' }
34  const kind = bp?.simulate?.kind ?? 'fail'
35  if (!SIMULATION_TOOLS.includes(call.tool) && !call.tool.startsWith('mcp__')) {
36    return { ok: false, reason: `${call.tool} is not on the simulation allowlist` }
37  }
38  if (kind === 'stub' && !(SHELL_TOOLS.includes(call.tool) && call.risk === 'read')) {
39    return { ok: false, reason: 'a stubbed output is allowed only for read-only shell commands' }
40  }
41  return { ok: true, kind, ...(bp?.simulate?.text !== undefined ? { text: bp.simulate.text } : {}) }
42}
43
44export type SyntheticResult =
45  | { deny: string }
46  | { result: { stdout: string; stderr: string; interrupted: false } }
47
48/** The answer a simulated call returns in place of running the tool. */
49export function synthesize(kind: SimulationKind, call: NormalizedCall, text?: string): SyntheticResult {
50  if (kind === 'stub') {
51    return { result: { stdout: `${SIMULATED_OUTPUT_TAG}\n${text ?? ''}`.trimEnd(), stderr: '', interrupted: false } }
52  }
53  const detail = text ?? 'A tool failure was injected by the developer to test recovery.'
54  return { deny: `${SIMULATED_FAILURE_TAG} ${detail} The ${call.tool} call was NOT executed, so nothing changed.` }
55}
56
src/core/suggest.ts 103 lines
1// One-press breakpoints, Chrome DevTools style: the rules a tool call suggests
2// (its tool, its command, its path) and the tool categories that can be ticked
3// like event-listener breakpoints. Pure.
4
5import type { Breakpoint, BreakpointKind, BreakpointMatch } from '../../types'
6import { normalizePath } from './breakpoints.ts'
7import { asRecord, SHELL_TOOLS } from './events.ts'
8
9export type Category = { id: string; label: string; tools: readonly string[] }
10
11/** Tool families a person ticks to pause on, like Chrome's event-listener breakpoints. */
12export const CATEGORIES: readonly Category[] = [
13  { id: 'shell', label: 'Shell', tools: ['Bash', 'PowerShell'] },
14  { id: 'read', label: 'Read', tools: ['Read'] },
15  { id: 'search', label: 'Search', tools: ['Grep', 'Glob'] },
16  { id: 'edit', label: 'Edit', tools: ['Edit', 'Write', 'NotebookEdit'] },
17  { id: 'web', label: 'Web', tools: ['WebFetch', 'WebSearch'] },
18  { id: 'agent', label: 'Agents', tools: ['Agent'] },
19]
20
21/** The family a tool belongs to, for counts; MCP and unknown tools have their own. */
22export function familyOf(tool: string): string {
23  if (tool.startsWith('mcp__')) return 'mcp'
24  return CATEGORIES.find(category => category.tools.includes(tool))?.id ?? 'other'
25}
26
27export type Suggestion = {
28  id: 'tool' | 'command' | 'path'
29  /** What the button says. */
30  label: string
31  kind: BreakpointKind
32  match: BreakpointMatch
33  name: string
34}
35
36const PATH_FIELDS = ['file_path', 'notebook_path', 'path'] as const
37/** Tools whose `path` names a directory searched below. */
38const DIRECTORY_TOOLS: readonly string[] = ['Grep', 'Glob']
39
40/**
41 * The program and its subcommand (`npm install`, `git push`), skipping
42 * leading environment assignments and `sudo`; the part of a command that
43 * stays the same when its arguments change.
44 */
45export function commandHead(command: string): string | undefined {
46  const first = command.split(/&&|\|\||[;|\n]/)[0] ?? ''
47  const words = first.trim().split(/\s+/).filter(word => word !== '')
48  while (words.length > 0 && (/^[A-Za-z_][A-Za-z0-9_]*=/.test(words[0] as string) || words[0] === 'sudo')) words.shift()
49  const program = words[0]
50  if (program === undefined || program === '') return undefined
51  const sub = words[1]
52  return sub !== undefined && /^[a-z][\w:.-]*$/i.test(sub) ? `${program} ${sub}` : program
53}
54
55/** A path shown and matched relative to the working directory when it lies below it. */
56export function relativePath(path: string, cwd?: string): string {
57  const target = normalizePath(path)
58  if (cwd === undefined || cwd === '') return target.path
59  const root = normalizePath(cwd).path
60  const fold = (text: string): string => (target.isWindows ? text.toLowerCase() : text)
61  return fold(target.path).startsWith(`${fold(root)}/`) ? target.path.slice(root.length + 1) : target.path
62}
63
64function shorten(text: string, max = 32): string {
65  return text.length <= max ? text : `…${text.slice(text.length - max + 1)}`
66}
67
68/** The breakpoints one tool call suggests: its tool, its command (shell), its path. */
69export function suggestBreakpoints(tool: string, input: unknown, cwd?: string): Suggestion[] {
70  const args = asRecord(input)
71  const out: Suggestion[] = [{ id: 'tool', label: tool, kind: 'tool', match: { tools: [tool] }, name: `${tool} calls` }]
72  if (SHELL_TOOLS.includes(tool) && typeof args.command === 'string') {
73    const head = commandHead(args.command)
74    if (head !== undefined) out.push({ id: 'command', label: `"${shorten(head, 24)}"`, kind: 'command', match: { command: head }, name: head })
75  }
76  const raw = PATH_FIELDS.map(field => args[field]).find((value): value is string => typeof value === 'string' && value !== '')
77  if (raw !== undefined) {
78    const relative = relativePath(raw, cwd)
79    const glob = DIRECTORY_TOOLS.includes(tool) ? `${relative.replace(/\/$/, '')}/**` : relative
80    if (!/[*?]/.test(raw)) out.push({ id: 'path', label: shorten(glob), kind: 'file', match: { path: glob }, name: shorten(glob, 48) })
81  }
82  return out
83}
84
85function canonical(match: BreakpointMatch): string {
86  return JSON.stringify({ tools: match.tools === undefined ? undefined : [...match.tools].sort(), command: match.command, path: match.path })
87}
88
89/** The existing rule that a suggestion or category stands for, if any. */
90export function findRule(breakpoints: readonly Breakpoint[], kind: BreakpointKind, match: BreakpointMatch): Breakpoint | undefined {
91  const wanted = canonical(match)
92  return breakpoints.find(bp => bp.kind === kind && canonical(bp.match) === wanted)
93}
94
95export function findCategoryRule(breakpoints: readonly Breakpoint[], category: Category): Breakpoint | undefined {
96  return findRule(breakpoints, 'tool', { tools: [...category.tools] })
97}
98
99/** Merges the session's hit counts into the rules. */
100export function withHits<T extends { breakpoints: readonly Breakpoint[] }>(settings: T, hits: Readonly<Record<string, number>>): T {
101  return { ...settings, breakpoints: settings.breakpoints.map(bp => ({ ...bp, hitCount: hits[bp.id] ?? 0 })) }
102}
103
src/security/redaction.ts 72 lines
1// Secret redaction for everything the timeline keeps and every export writes.
2// Pattern-based and best effort: it catches the common credential shapes and
3// every inline environment assignment, it cannot prove a string holds no secret.
4
5export const REDACTED = '[REDACTED]'
6
7/** Object keys whose values are dropped whole, matched per word (`apiKey` is `api_key`). */
8const SENSITIVE_KEY =
9  /(^|_)(password|passwd|passphrase|pass|pwd|secret|token|api_?key|auth|authorization|cookie|credentials?|private_?key|session_?(id|key)|bearer|access_?key)(_|$)/
10
11/** Credential shapes replaced wherever they appear in a string. */
12const SECRET_PATTERNS: readonly RegExp[] = [
13  /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g,
14  /\b(?:Bearer|Basic)\s+[A-Za-z0-9._~+/=-]{8,}/gi,
15  /\bsk-(?:ant-)?[A-Za-z0-9_-]{16,}/g,
16  /\b(?:sk|rk|pk)_(?:live|test)_[A-Za-z0-9]{16,}/g,
17  /\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{20,}/g,
18  /\bgithub_pat_[A-Za-z0-9_]{20,}/g,
19  /\bglpat-[A-Za-z0-9_-]{20,}/g,
20  /\bxox[abeprs][.-][A-Za-z0-9.-]{10,}/g,
21  /\bSK[0-9a-fA-F]{32}\b/g,
22  /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g,
23  /\bAIza[0-9A-Za-z_-]{35}\b/g,
24  /\bnpm_[A-Za-z0-9]{36}\b/g,
25  /\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g,
26]
27
28/** `scheme://user:password@host` keeps the user, drops the password. */
29const URL_CREDENTIALS = /\b([a-z][a-z0-9+.-]*:\/\/[^\s:/@]+):[^\s@/]+@/gi
30
31/** `KEY=value` (shell env assignment, `export`, `set`, `env`): the value goes. */
32const ENV_ASSIGNMENT = /(^|[\s;&|(`])((?:export\s+|set\s+)?[A-Za-z_][A-Za-z0-9_]*)=("[^"]*"|'[^']*'|[^\s;&|)`]+)/g
33
34/** PowerShell `$env:NAME = value`. */
35const PS_ENV_ASSIGNMENT = /(\$env:[A-Za-z_][A-Za-z0-9_]*\s*=\s*)("[^"]*"|'[^']*'|\S+)/gi
36
37/** `--password x`, `--token=x`, `-p:x` style secret flags. */
38const SECRET_FLAG =
39  /(--?(?:password|passwd|pass|token|secret|api[-_]?key|auth(?:-token)?|access[-_]?key|client[-_]?secret)(?:=|\s+))("[^"]*"|'[^']*'|\S+)/gi
40
41/** Header-style `Authorization: x`, `X-Api-Key: x`. */
42const SECRET_HEADER = /\b((?:authorization|x-api-key|api-key|cookie|set-cookie)\s*:\s*)([^\s"',;]+(?:\s+[^\s"',;]+)?)/gi
43
44export function redactString(text: string): string {
45  let out = text
46  for (const pattern of SECRET_PATTERNS) out = out.replace(pattern, REDACTED)
47  return out
48    .replace(URL_CREDENTIALS, `$1:${REDACTED}@`)
49    .replace(ENV_ASSIGNMENT, `$1$2=${REDACTED}`)
50    .replace(PS_ENV_ASSIGNMENT, `$1${REDACTED}`)
51    .replace(SECRET_FLAG, `$1${REDACTED}`)
52    .replace(SECRET_HEADER, `$1${REDACTED}`)
53}
54
55export function isSensitiveKey(key: string): boolean {
56  const words = key.replace(/([a-z0-9])([A-Z])/g, '$1_$2').replace(/[-\s.]+/g, '_').toLowerCase()
57  return SENSITIVE_KEY.test(words)
58}
59
60/** Deep copy of plain JSON data with sensitive keys and secret shapes redacted. */
61export function redactValue(value: unknown, depth = 0): unknown {
62  if (typeof value === 'string') return redactString(value)
63  if (value === null || typeof value !== 'object') return value
64  if (depth > 8) return '[…]'
65  if (Array.isArray(value)) return value.map(item => redactValue(item, depth + 1))
66  const out: Record<string, unknown> = {}
67  for (const [key, item] of Object.entries(value)) {
68    out[key] = isSensitiveKey(key) && item !== null && item !== undefined ? REDACTED : redactValue(item, depth + 1)
69  }
70  return out
71}
72
src/ui/inline.tsx 153 lines
1// Breakpoints set where the calls are, Chrome DevTools style: a gutter on
2// each tool row in the transcript (hover it, press "break on"), a red mark on
3// rows a breakpoint covers, and a bar above the prompt for the latest call
4// that the keyboard reaches (ctrl+x tab, then its hotkeys).
5
6import type { RenderElement } from 'claude-code'
7
8import type { Breakpoint, TraceEvent } from '../../types'
9import { truncate } from '../core/events.ts'
10import { statusIcon } from '../core/recorder.ts'
11import type { Suggestion } from '../core/suggest.ts'
12import type { Table } from './model.ts'
13import { C, STATUS_COLOR } from './theme.ts'
14
15/** A suggestion as drawn: its element key, and the rule it stands for when one is set. */
16export type Offer = Suggestion & { key: string; rule?: Breakpoint }
17
18export type InlineMode = 'hover' | 'always'
19
20function offerLabel(offer: Offer): string {
21  return `${offer.rule !== undefined ? '●' : '○'} ${offer.label}`
22}
23
24/**
25 * The transcript row with a gutter: the engine's own drawing first, a red
26 * line naming the breakpoints that cover the call, then the "break on"
27 * controls. `hover` lays them over the row's top right, shown only while the
28 * pointer is over the row, so nothing moves; `always` gives them a line.
29 */
30export function renderGutter(els: Table, drawn: RenderElement, matched: readonly Breakpoint[], offers: readonly Offer[], mode: InlineMode, onToggle: (offer: Offer) => void): RenderElement {
31  const { Box, Text, Button } = els
32  const buttons = offers.map(offer => <Button key={offer.key} plain dimColor={offer.rule === undefined} label={offerLabel(offer)} onPress={() => onToggle(offer)} />)
33  return (
34    <Box key="devtools-row" flexDirection="column">
35      {drawn}
36      {matched.length > 0 && (
37        <Text key="devtools-mark" color={C.breakpoints} wrap="truncate-end">
38          {`  ● breakpoint ${matched.map(bp => `${bp.id} ${bp.name} → ${bp.action}`).join(' · ')}`}
39        </Text>
40      )}
41      {mode === 'hover' ? (
42        <Box position="absolute" top={0} right={0} flexDirection="row" columnGap={1} display="none" hover={{ display: 'flex' }}>
43          <Text color={C.breakpoints}>break on</Text>
44          {buttons}
45        </Box>
46      ) : (
47        <Box key="devtools-gutter" flexDirection="row" columnGap={1} marginLeft={2}>
48          <Text dimColor>break on</Text>
49          {buttons}
50        </Box>
51      )}
52    </Box>
53  )
54}
55
56const BAR_HOTKEY: Record<Suggestion['id'], string> = { tool: 't', command: 'c', path: 'f' }
57
58export const BAR_HINT = '/bp <rule> · /devtools-help'
59/** Longest first: the bar shows the longest that still fits on its line. */
60const HINTS = [BAR_HINT, '/bp <rule>']
61/** A plain Button with a hotkey draws `t: label`. */
62const BUTTON_EXTRA = 3
63/** Cells the engine keeps at the band's right edge (its `[−]` fold control). */
64const EDGE = 4
65const BREAK_ON = '· break on'
66
67/** What the bar shows, so that it always fits one line. */
68export type BarFit = { summary?: string; offers: number; lens: boolean; hide: boolean; open: boolean; hint?: string }
69
70/**
71 * Lays the bar out on one line, never wrapping: the brand and status first,
72 * then each part in order of importance (the breakpoint keys, the Error Lens
73 * key, hide, open, the call's summary, the hint), each only if the rest of the
74 * line still has room for it.
75 */
76export function fitBar(width: number, summary: string, offerLabels: readonly string[], lens: string | undefined): BarFit {
77  let room = width - EDGE - 'DevTools'.length - 2
78  const take = (cells: number): boolean => (cells <= room ? ((room -= cells), true) : false)
79  const button = (label: string): number => 1 + BUTTON_EXTRA + label.length
80  let offers = 0
81  if (offerLabels.length > 0 && take(1 + BREAK_ON.length)) {
82    for (const label of offerLabels) {
83      if (!take(button(label))) break
84      offers += 1
85    }
86    // "break on" with no key after it says nothing.
87    if (offers === 0) room += 1 + BREAK_ON.length
88  }
89  const showLens = lens !== undefined && take(button(lens))
90  const hide = take(button('hide'))
91  const open = take(button('DevTools'))
92  // The summary gets what is left, at most a third of the line; cut below 12 cells it tells nothing.
93  const cells = Math.min(summary.length, Math.floor(width / 3), room - 1)
94  const shown = cells > 0 && cells >= Math.min(12, summary.length) ? truncate(summary, cells) : undefined
95  if (shown !== undefined) room -= 1 + shown.length
96  const hint = HINTS.find(text => take(3 + text.length))
97  return { offers, lens: showLens, hide, open, ...(shown !== undefined ? { summary: shown } : {}), ...(hint !== undefined ? { hint } : {}) }
98}
99
100/**
101 * The bar above the prompt: the latest call, one-key breakpoints for it, its
102 * Error Lens when it failed, and a dim hint. Before the first call, the hint alone.
103 */
104export function renderBar(
105  els: Table,
106  below: RenderElement,
107  event: TraceEvent | undefined,
108  offers: readonly Offer[],
109  width: number,
110  on: { toggle: (offer: Offer) => void; open: () => void; hide: () => void; lens: () => void },
111): RenderElement {
112  const { Box, Text, Button } = els
113  const cells = Math.max(24, width)
114  if (event === undefined) {
115    return (
116      <Box flexDirection="column">
117        {below}
118        <Box key="devtools-bar" flexDirection="row" columnGap={1} width={cells}>
119          <Text color={C.brand} dimColor>
120            DevTools
121          </Text>
122          <Text dimColor wrap="truncate-end">
123            {truncate(`· press "break on" under any tool call, or ${BAR_HINT}`, cells - EDGE - 9)}
124          </Text>
125        </Box>
126      </Box>
127    )
128  }
129  const lens = event.errorCategory !== undefined ? `✗ why? (${event.errorCategory})` : undefined
130  const fit = fitBar(cells, `${event.tool} ${event.inputSummary}`, offers.map(offerLabel), lens)
131  const keys = offers.slice(0, fit.offers)
132  return (
133    <Box flexDirection="column">
134      {below}
135      <Box key="devtools-bar" flexDirection="row" columnGap={1} width={cells}>
136        <Text color={C.brand} bold>
137          DevTools
138        </Text>
139        <Text color={STATUS_COLOR[event.status]}>{statusIcon(event.status)}</Text>
140        {fit.summary !== undefined && <Text dimColor>{fit.summary}</Text>}
141        {keys.length > 0 && <Text dimColor>{BREAK_ON}</Text>}
142        {keys.map(offer => (
143          <Button key={`bar-${offer.id}`} hotkey={BAR_HOTKEY[offer.id]} plain dimColor={offer.rule === undefined} label={offerLabel(offer)} onPress={() => on.toggle(offer)} />
144        ))}
145        {fit.lens && lens !== undefined && <Button key="bar-lens" hotkey="e" plain label={lens} onPress={() => on.lens()} />}
146        {fit.open && <Button key="bar-open" hotkey="d" plain dimColor label="DevTools" onPress={() => on.open()} />}
147        {fit.hide && <Button key="bar-hide" hotkey="x" plain dimColor label="hide" onPress={() => on.hide()} />}
148        {fit.hint !== undefined && <Text dimColor>{`· ${fit.hint}`}</Text>}
149      </Box>
150    </Box>
151  )
152}
153