Redraws finished tool-call rows in the terminal as one compact line with a Nerd Font icon, Gruvbox colors and a short stat

English | 日本語
Personal Claude Code mods (function-hook plugins), published as one marketplace.
| Mod | What it does |
|---|---|
agent-pane | Live pane of the session's subagents: running ones with elapsed time, finished ones with result and duration |
done-gate | Flags unverified edits, stops repeated failing commands, and blocks git --no-verify |
sandbox-lens | Tallies sandbox denials seen in Bash output and reports them with /sandbox-report |
todo-agent | Collects #TODO(agent) follow-ups from Claude's replies into a per-project list with a /todos pane. |
tool-row | Redraws finished tool-call rows in the terminal as one compact line with a Nerd Font icon, Gruvbox colors and a short stat |
image-preview | Thumbnails of the images a session writes, reads or generates: under the tool's row in the terminal, and in an /images pane |
self-audit | After each turn, a cached fork of the conversation audits Claude's own reply against the CLAUDE.md reporting rules and flags violations above the prompt |
browser-cam | Live pane of the browser Claude drives: the latest screenshot from Claude in Chrome, the page URL and the recent actions |
prompt-coach | Holds back a typed prompt that looks ambiguous (no done-condition, unclear target) and offers guesses at what it meant, sending it as is, or adding one; on by default |
loopback | Feeds what self-audit, done-gate and sandbox-lens found back to Claude beside the next prompt, instead of only showing it to the person, skipping rules hit-rate found mostly wrong; off by default |
zukan | Error book: catches the errors Bash commands hit across sessions and repos, records what got past each one, and when one comes back tells Claude and the person how it was fixed last time |
pr-lamp | The current branch's pull request as a lamp: checks, review, unresolved threads and what is left before a merge, in the status line and a /pr pane; red checks and new review comments go to Claude beside the next prompt |
fog-map | Exploration map: the repository as a tree under fog, cleared where Claude read and marked where it edited, made a file or hit an error, with the importers an edit may have broken unseen; /map |
assertion-guard | Catches edits that weaken tests to pass: assertions removed, expectations loosened or rewritten, tests skipped, errors swallowed; asks Claude for the reason beside the edit |
negative-space | When an edit adds authorization, validation or error handling, lists the refusal and boundary-value tests no test touched this session covers; /negative-space |
mutation-tap | /mutate runs a mutation test limited to the lines changed since HEAD and lists the mutants the tests did not catch |
perf-delta | /perf compares a benchmark before and after (a saved baseline, or a git ref in a temporary worktree): median time, peak memory, spread, and whether the change beats the noise |
port-lantern | The dev servers the session started: URL, port, whether each still listens, and their latest log lines, in the status line and /ports |
artifact-shelf | A shelf of what sessions made (CSV, PDF, HTML, video, patches…), tied to the call and request that made each; /shelf searches by kind, word and time |
side-effect-ledger | A ledger of what a git diff never shows (push, publish, deploy, PRs, API writes, messages) with outcome, how to undo, and whether the undo was checked; /ledger |
visual-diff | Compares browser screenshots of the same URL and size before and after an edit: side by side, a map of changed cells, regions, and the edits in between; /vdiff |
journey-trace | Records Claude's browser actions and the expected states as a replayable recipe; /journey md for a bug report, /journey e2e for a Playwright draft |
hit-rate | Gives each finding of done-gate, assertion-guard, self-audit and zukan a later verdict from what the session did next, keeps each rule's precision across sessions, and names the rules loopback stops feeding; /hit-rate; off by default |
token-lens | Checks an element's actual colours, spacing and type against the project's design tokens and lists off-token values with the nearest token; /token-lens <selector> |
kachi | When a check you broke turns green after a real fix, the band above the prompt sweeps green once with a short click, and the result row keeps the score: how many tries, how long it stayed red. Silent the rest of the time, but for one dim line under a check's first red |
cross-check | A second opinion from Codex in one press: the band above the prompt reviews the current diff with codex exec in its read-only sandbox, shows the top finding and the count, and puts the findings into the prompt for Claude to fix when asked; /codex lists them |
ci-rehearsal | CI before the push, in one press: the band above the prompt runs the push workflows locally with runthrough, shows the failing job and step with the count, and puts the failures and their log tails into the prompt for Claude to fix when asked; /ci lists every job |
stack-dock | The repository's devrouter stack in one press: the band above the prompt says whether it is unset, stopped or up, starts it with devrouter up, shows each service's URL and health in the status line and /stack, and puts doctor's findings and the failing logs into the prompt for Claude to fix when asked |
At the prompt of a terminal session:
/plugin install <mod> --marketplace simota/claude-mods
From a shell:
claude plugin install <mod> --marketplace simota/claude-mods
This repository is private: installing needs read access on GitHub and a git credential for github.com on the machine (an SSH key, or gh auth login then gh auth setup-git).
Options are set with /plugin configure <mod>@simota-mods in a session, or from a shell:
echo '{"enabled":"true"}' | claude plugin configure <mod>@simota-mods --values-stdin
A change made with /plugin configure reloads the mod; one made from a shell applies after a restart. Bands above the prompt stack: each mod draws its row above what the others draw.
/agent-pane opens the pane: running subagents first with elapsed time, then finished ones with ✓/✗ and duration; a background run that was stopped shows ■ 停止. A background run that left the roster without a result shows ? 結果不明; a teammate or remote launch shows ↗ 起動済み(追跡外).agents: N running while any run.Works on its own, no command:
ls build, npm ci are not checks), and only when its exit status is the command's: the check is last, or only && follows it (npm test | tail does not count).--no-verify (or a prefix of it from --no-ver), and git commit -n / -nm, is denied, also inside subshells, $(…), backticks, bash -c "…", eval and wrappers such as sudo/timeout. The value of an option (-m "…"), a comment or a heredoc never triggers it. So is a git command that moves its hooks for the run (-c core.hooksPath=…, --config-env core.hooksPath=…) or carries a hook manager's off switch in its environment (HUSKY=0, LEFTHOOK=0, pre-commit's SKIP=…), or moves the hooks through config in its environment (GIT_CONFIG_KEY_n=core.hooksPath, GIT_CONFIG_PARAMETERS). ANSI-C quoting ($'--no-\x76erify'), env -S "…", bash -c -- '…' and a shell reading its script from stdin (bash <<< '…', a heredoc, echo '…' | sh) are read through. It is a best-effort guard: git aliases (git ci -n), a hook path written into config beforehand and an environment exported by an earlier command are not detected./sandbox-report lists the sandbox denials seen in Bash output, for this session and all time: denied hosts and paths, counts, last seen, an example command, and which setting would allow each./sandbox-report reset clears the record.127.0.0.1:3000), since an entry without a port opens every port.<sandbox_violations> block, and Operation not permitted lines a program printed about itself, are read. For a command that succeeded or was interrupted, the block is taken from where the engine puts it, apart from the command's own output, so one inside a shown file or page is ignored even when it ends the output. A failed command keeps only its error text: the block that ends it (before an agent-proxy note) is read, and there a block the command printed itself cannot be told from the harness's. Credentials in the example command (tokens, passwords, Authorization/Cookie and other credential headers such as X-API-Key, URL userinfo, keys in env assignments including run-together names such as PGPASSWORD, known key shapes) are masked. Each section shows the top 10; when the record is full (200), the least recently seen entry gives way.#TODO(agent): <action> (after an optional quote or list bullet) in Claude's main-loop replies are collected per project (repo root or cwd). A mention inside a sentence, a table or inline code is not a TODO; subagent replies are ignored./todos opens the pane of this project's open items, each with a 完了 button./todos all lists every project's open items as text, marked as stored data.TODO(agent): N while the project has open items.Finished tool calls are drawn as one compact line with a Nerd Font icon: Edit/Write path +A −D, Read with line count, Bash (red on error), Agent, web and MCP calls. The result block under a compacted row is hidden, so a call is one line; an errored result stays. A row another mod decorated (an image-preview thumbnail) is left as it is, result included. Runs Claude Code folds into one count line (Read 3 files, ran 2 shell commands) stay folded. Terminal only.
| Option | Default | |
|---|---|---|
compact | true | Off leaves every row and result as Claude Code draws them |
/images opens a pane, newest first; h/l step through them.sips after the tool result has gone back, so tool calls never wait on it. Converted files live in a private cache ($TMPDIR or ~/.cache), newest 50 kept. A killed session's folder is removed by a later session's start once a day untouched; a running session touches its own every hour (again after a plugin reload), so it is kept while idle, though not across a day the machine sleeps./tmp/a b/x.jpg) joins at most 8 preceding pieces and 4096 characters; the first 64 paths named are read, and of those the first 4 that exist are shown.| Option | Default | |
|---|---|---|
inline | true | Thumbnail under the tool row |
maxRows | 12 | Rows a thumbnail may take, 1 to 60 |
After each reply of at least minChars characters, one tool-less fork of the conversation (served mostly from the prompt cache), given the reply itself as quoted data, checks it against the CLAUDE.md rules: claims done without evidence, first line not the result, unverified assertions, bypassed checks, scope inflation. Only violations of the five rules whose quote is found in the reply are kept (a made-up quote or rule is dropped); the quote is compared past markdown marks, bullets, curly quotes, case, spacing and a closing full stop, and one shortened with … is found piece by piece. Violations show in red above the prompt, in one row (the first and how many); 詳細 or /self-audit opens the pane with quotes and the fork's token use. Results belong to the latest reply only: when it was not audited, the pane says why.
| Option | Default | |
|---|---|---|
enabled | true | |
minChars | 200 | Shorter replies are not audited |
Cost: one extra request per turn on the session's model, plus the reply text (up to 12,000 characters) as uncached input; a cold cache (after 5 minutes idle or a model switch) resends the whole conversation.
type ‹7文字›, counted up to 10,000), since the field may be a password; a URL's secrets (token parameters, userinfo, key-shaped parts) are masked./cam toggles the pane; in a fullscreen terminal it opens by itself once per session, on the first browser call. Screenshots are decoded only while the pane is open, and written to a private per-session folder that is removed at session end. A killed session's folder is removed by a later session's start once a day untouched; a running session touches its own every hour (again after a plugin reload), so it is kept while idle, though not across a day the machine sleeps.| Option | Default | |
|---|---|---|
autoOpen | true | Open on the first browser call (fullscreen terminal) |
On by default (enabled: false turns it off). A typed prompt that looks ambiguous (no done-condition and an unclear target, or only evaluative words like いい感じ) is held back, and a band shows what is missing with up to three guesses at what it meant (judged along the lines of the clarify skill: the likeliest reading first, each a different deliverable with a checkable done-condition):
a / b / d: a guess goes into the prompt to edit and send (not held again)s: このまま送る sends it unchangede: 補足して送る puts it back with 完了条件: to fill in (not held again)q: 閉じる puts it back in the promptTyping another prompt instead sends that one and puts the held text back into the prompt. The held text is never lost: when a send fails or is dropped beneath, or putting words back fails, it stays held with its band (unless another prompt was held since) and its words are shown in a toast; a prompt still held at /clear goes straight back into the box, and one held when the session quits comes back at this project's next interactive session start. Words go into an empty box as they are, and are appended after a draft typed meanwhile on a line of their own, never over it.
Slash commands, prompts under 12 or over 1500 characters, prompts with any attachment or an @ mention, prompts sent by a plugin, and prompts typed while a turn runs are not judged. A timeout or error sends the prompt unchanged; the same text is not held twice (within the last 50 judged). Sending can wait up to timeoutMs.
| Option | Default | |
|---|---|---|
enabled | true | |
model | claude-haiku-5-5 | Judging model (alias or id) |
timeoutMs | 3000 | 500 to 3000 |
Off by default. When on, the new findings of the detector mods are attached to the next prompt typed at an idle prompt, as context only the model reads, so the correction does not wait for the person to retype it:
self-audit: the violations of the latest audited replydone-gate: edits with no passing check after them (again after a check passed and new edits were left unverified; 閉じる on its band takes the flag down, and nothing is fed)sandbox-lens: denials seen this session, each onceEach finding goes back once per session, marked as data that may be wrong for Claude to check before acting. A toast says how many went back and from where. Slash commands, hidden prompts, prompts sent by a plugin and prompts typed while a turn runs carry nothing. A detector that is not installed contributes nothing.
With hit-rate on, the rules it muted are not fed (sandbox-lens denials never are muted).
/loopback shows what was fed last and the self-audit repeat rate: of the rules fed back, how many self-audit flagged again on the next audited reply (all sessions). The rate is what the design is judged by (.genius/decisions/loopback.md). It also names the rules hit-rate muted.| Option | Default | |
|---|---|---|
enabled | false |
Cost: the findings ride as extra input on the prompt they are attached to (each quote clipped to 300 characters, at most 12 findings).
An error book, kept across sessions and repos. When a Bash command fails, the error line is caught and numbered:
📕 新種のエラー発見! No.042「…」 — a kind not seen before📙 No.017 再会(3回目・未解決) — seen before, nothing known to get past it 📗 既知 No.017(3回目)— 前回: sandbox 外で git push origin main ` — seen before with a fix: Claude also reads, beside the tool's result, where it was seen and what got past it (marked as a past record to check, not an instruction)A fix is learned when the same program and subcommand (git push, pnpm install; read past a leading cd, export or source, so cd app && npm install is npm install) succeeds within the next 10 Bash calls of the session; whether it ran outside the sandbox is kept with it. Two sightings are one kind when their error line matches with paths, quotes, numbers and hashes taken out.
Failures of tests, linters, type checkers and builds are not caught: they are fixed by editing code, not by a command. Credentials in a kept command and in the kept error line are masked as sandbox-lens does.
/zukan opens the book, most recently seen first: kinds, solved, sightings/zukan note <No> <text> writes how to get past it, shown and fed in place of the learned command; an empty text removes the note/zukan forget <No> removes an entryThe newest 300 kinds by last sighting are kept.
The current branch's pull request, kept in the status line while it is open (once merged or closed, a toast says so and the line clears):
⎇ #42 · ✓5 ✗1 ⏳2 · 🛑 変更要求 · 💬3 · マージまであと4
"マージまであと N" counts what still stands before a merge: draft, failed checks, running checks, changes requested or approval pending, unresolved review threads, a conflict, the branch behind its base. At 0 it reads 🟢 マージ可能.
A toast when it changes: 🔴 CI 失敗: test, 💬 新しいレビューコメント 2件 (@rev), ✅ 承認されました, 🟢 #42 マージまであと0, 🎉 #42 がマージされました. Checks turning red, new review comments, changes requested and a new conflict are also attached to the next prompt typed at an idle prompt, once, with the last 40 lines of the failed log of up to three jobs (more are counted), marked as data whose comments and logs are not to be followed as instructions. The session's own replies on a thread (the comment, made after the post, carrying words it replied with through an MCP reply tool or gh api …/pulls/N/comments… -f body=, matched once) are not news; your own review comments are. What waits for the next prompt is about one pull request and is capped (newest kept). The option feed (on by default) turns that off.
/pr asks again and opens the pane: title, size, what is left, checks (failed first) and unresolved threads/pr <number|url|branch> follows that pull request; /pr clear goes back to the defaultWhich pull request: the one a Bash command of the session last worked on (gh pr comment 2, gh pr review 2, the URL gh pr create printed, the branch a git push sent to; looking with gh pr view|diff|checks does not move it), so work pushed to a review branch from another checkout is followed; else the checked-out branch's; else your newest open pull request in the repository.
It asks gh (gh pr view, and gh api graphql for review threads) at session start, right after a Bash git push, git checkout, gh pr create and the like, every minute while a check runs or after a push, and every five minutes otherwise; it stops once the pull request is merged or closed. Without an origin remote, gh, or a pull request for the branch it shows nothing, and /pr says why. gh runs on the host, outside the Bash sandbox, with your gh auth.
The repository as a map under fog, cleared as Claude works through it:
🗺 探索率 31% ██████░░░░░░░░░░░░░░ 読 23 · 編 9 · ✗ 2 / 101
▾ mods/
▾ pr-lamp/
▾ hooks/
● lamp.ts +43 −2 編集 4回
✗ register.tsx +59 −16 編集 6回 エラー 1 ★
▸ loopback/ ○●
░ agent-pane/ ░ browser-cam/ ░ done-gate/ …8
⚠ 編集したファイルを import しているが未読: mods/pr-lamp/tests/pr-lamp.test.ts
░ nothing touched yet, ○ read (Read, or cat, sed, grep… in Bash), ● edited (Edit, Write, NotebookEdit, sed -i), ✚ made by the session, ✗ named with a line number by a failed Bash command since its last edit, ★ the file touched last. A directory holding an edit, a new file or an error is open; one only read is closed with its marks beside it; untouched directories and files at a level share one fog row.
Two warnings, each a likely oversight: a file edited without being read, and a file that imports an edited one (JS/TS and Python, found by git grep) that was never opened. A very large repository's file list is cut to what one state value holds (3 M characters of paths), so it is still mapped, partly.
/map opens the pane🗺 31% · ●9 · ✗2 · ⚠1 only while there is an error or a warning, and clears otherwise🗺 新しい区域を開拓: mods/zukan/)The map is the session's, subagents' calls included; files outside the repository are not mapped. Explored is touched files over git ls-files, read again after a checkout, pull, mv or rm. Outside a git repository only the edit count is shown. A failed command's output is read once, in time linear in its length, before its result goes back.
On each Edit, Write or MultiEdit it diffs the whole file before and after the call, so an assertion moved within the file is no removal, and one only reformatted (spaces around punctuation, a closing ; or ,, and '…' for "…" in languages that read them alike) is no rewrite; a change inside a string still is. In test files (by name, or a Rust file with a test module anywhere in it) it flags assertions removed or commented out, a strict matcher turned weak (toEqual → toBeDefined, assertEqual → assertTrue, toThrow(X) → toThrow()), an assertion now about a literal (expect(true).toBe(true)), the same assertion now expecting another value or the opposite (toBe → not.toBe), and tests skipped or focused (it.skip, @pytest.mark.skip, #[ignore], t.Skip). In any file but prose (.md, .txt, .rst, .adoc) it flags errors newly swallowed (catch {}, .catch(() => undefined), except: pass, || true); one named in a comment (// or || true, a doc block, /* … */, # …) is not.
Findings ride beside the edit's re
hooks/register.tsx 41 lines1import type { Register } from 'claude-code'
2
3import { summarize } from './summary'
4
5export const register: Register = (on, options) => {
6 const isCompact = options.compact !== false
7 // Calls whose row this plugin drew as one line: their result block is hidden with it.
8 const compacted = new Set<string>()
9
10 on('ui.render', { component: 'ToolUse' }, async ($, e, next) => {
11 if (!isCompact || e.surface !== 'terminal') return next(e)
12 const { tool, input, output, isRunning, isErrored, isInterrupted } = e.props
13 if (isRunning || isInterrupted || output === undefined) return next(e)
14
15 const summary = summarize({ tool, input, output, isErrored })
16 if (summary === undefined) return next(e)
17
18 // Only the engine's own row is replaced: a row a plugin beneath drew or
19 // decorated (image-preview's thumbnail under it) is left as that plugin drew it.
20 const below = await next(e)
21 if (below.type !== 'engine') return below
22
23 compacted.add(e.props.tool_use_id)
24 const { Box, Text } = $.ui.resolve(e)
25 return (
26 <Box flexDirection="row" gap={1}>
27 <Text color={summary.color}>{summary.icon}</Text>
28 <Text color={isErrored ? summary.color : undefined} wrap="truncate-middle">{summary.label}</Text>
29 {summary.stats.map(stat => <Text color={stat.color}>{stat.text}</Text>)}
30 </Box>
31 )
32 }).catch(($, e, next) => next(e))
33
34 // The one line stands for the call: its result goes unless it errored, which stays readable.
35 on('ui.render', { component: 'ToolResult' }, async ($, e, next) => {
36 if (!isCompact || e.surface !== 'terminal' || e.props.isErrored || !compacted.has(e.props.tool_use_id)) return next(e)
37 const { Box } = $.ui.resolve(e)
38 return <Box />
39 }).catch(($, e, next) => next(e))
40}
41hooks/summary.ts 239 lines1// What one finished tool call's compact line says, from the row's own props.
2// Pure: no `$`, so tests call it directly.
3
4export const GRUVBOX = {
5 red: '#fb4934',
6 green: '#b8bb26',
7 yellow: '#fabd2f',
8 blue: '#83a598',
9 purple: '#d3869b',
10 aqua: '#8ec07c',
11 orange: '#fe8019',
12 gray: '#a89984',
13} as const
14
15export const ICONS = {
16 edit: '',
17 write: '',
18 notebook: '',
19 read: '',
20 bash: '',
21 search: '',
22 agent: '\u{f06a9}',
23 web: '',
24 mcp: '\u{f0493}',
25} as const
26
27export type Stat = { text: string; color: string }
28
29export type Summary = {
30 icon: string
31 color: string
32 label: string
33 stats: Stat[]
34}
35
36export type RowFacts = {
37 tool: string
38 input: unknown
39 output: unknown
40 isErrored: boolean
41}
42
43const COMMAND_CHARS = 60
44
45function field(value: unknown, key: string): unknown {
46 return typeof value === 'object' && value !== null ? (value as Record<string, unknown>)[key] : undefined
47}
48
49function text(value: unknown, key: string): string | undefined {
50 const found = field(value, key)
51 return typeof found === 'string' && found.length > 0 ? found : undefined
52}
53
54function lineCount(value: string): number {
55 return value === '' ? 0 : value.replace(/\n$/, '').split('\n').length
56}
57
58// Lines added and removed, from a structuredPatch's hunks when the result has one.
59function patchCounts(output: unknown): { added: number; removed: number } | undefined {
60 const hunks = field(output, 'structuredPatch')
61 if (!Array.isArray(hunks)) return undefined
62 let added = 0
63 let removed = 0
64 for (const hunk of hunks) {
65 const lines = field(hunk, 'lines')
66 if (!Array.isArray(lines)) continue
67 for (const line of lines) {
68 if (typeof line !== 'string') continue
69 if (line.startsWith('+')) added += 1
70 else if (line.startsWith('-')) removed += 1
71 }
72 }
73 return { added, removed }
74}
75
76function diffStats(counts: { added: number; removed: number }): Stat[] {
77 return [
78 { text: `+${counts.added}`, color: GRUVBOX.green },
79 { text: `−${counts.removed}`, color: GRUVBOX.red },
80 ]
81}
82
83// Marks that belong to the character before them: combining marks, variation
84// selectors, the keycap mark, skin tones and tag characters.
85const isExtend = (cp: number) =>
86 (cp >= 0x0300 && cp <= 0x036f) ||
87 (cp >= 0x1ab0 && cp <= 0x1aff) ||
88 (cp >= 0x20d0 && cp <= 0x20ff) ||
89 (cp >= 0xfe00 && cp <= 0xfe0f) ||
90 (cp >= 0xfe20 && cp <= 0xfe2f) ||
91 (cp >= 0x1f3fb && cp <= 0x1f3ff) ||
92 (cp >= 0xe0020 && cp <= 0xe007f) ||
93 (cp >= 0xe0100 && cp <= 0xe01ef)
94const isRegional = (cp: number) => cp >= 0x1f1e6 && cp <= 0x1f1ff
95const ZWJ = 0x200d
96
97/**
98 * User-perceived characters where the runtime has no Intl.Segmenter: a ZWJ sequence
99 * (👩💻), a flag (two regional indicators), a keycap or a base with its marks stays whole.
100 */
101export function graphemesFallback(text: string, limit = Infinity): string[] {
102 const out: string[] = []
103 // The cluster being read, as its pieces and its first code point: a cluster that keeps
104 // growing is never read again as a whole, so one long cluster stays linear.
105 let pieces: string[] = []
106 let first = 0
107 let isAfterJoiner = false
108 for (const ch of text) {
109 const cp = ch.codePointAt(0) ?? 0
110 const isFlagHalf = isRegional(cp) && pieces.length === 1 && isRegional(first)
111 if (pieces.length > 0 && (isAfterJoiner || cp === ZWJ || isExtend(cp) || isFlagHalf)) pieces.push(ch)
112 else {
113 if (pieces.length > 0) out.push(pieces.join(''))
114 if (out.length >= limit) return out
115 pieces = [ch]
116 first = cp
117 }
118 isAfterJoiner = cp === ZWJ
119 }
120 if (pieces.length > 0 && out.length < limit) out.push(pieces.join(''))
121 return out
122}
123
124/** The first `limit` user-perceived characters, read no further than needed: a row is drawn often. */
125export function graphemes(text: string, limit = Infinity): string[] {
126 if (typeof Intl !== 'undefined' && typeof Intl.Segmenter === 'function') {
127 const out: string[] = []
128 for (const part of new Intl.Segmenter(undefined, { granularity: 'grapheme' }).segment(text)) {
129 if (out.length >= limit) break
130 out.push(part.segment)
131 }
132 return out
133 }
134 return graphemesFallback(text, limit)
135}
136
137// Cut between whole characters, so an emoji (a ZWJ sequence or a flag too) is never split.
138function firstLine(command: string): string {
139 const text = command.trim()
140 const end = text.indexOf('\n')
141 const head = end < 0 ? text : text.slice(0, end)
142 // One past the cut, to know whether there is more.
143 const line = graphemes(end >= 0 ? `${head} …` : head, COMMAND_CHARS + 1)
144 return line.length > COMMAND_CHARS ? `${line.slice(0, COMMAND_CHARS - 1).join('')}…` : line.join('')
145}
146
147function host(url: string): string {
148 try {
149 const parsed = new URL(url)
150 return `${parsed.host}${parsed.pathname === '/' ? '' : parsed.pathname}`
151 } catch {
152 return url
153 }
154}
155
156// The compact line for a call, or undefined where the engine's own row should stand.
157export function summarize(facts: RowFacts): Summary | undefined {
158 const { tool, input, output, isErrored } = facts
159 const tint = (color: string) => (isErrored ? GRUVBOX.red : color)
160
161 if (tool === 'Edit') {
162 const path = text(input, 'file_path')
163 if (path === undefined) return undefined
164 const counts = isErrored ? undefined : patchCounts(output) ?? {
165 added: lineCount(text(input, 'new_string') ?? ''),
166 removed: lineCount(text(input, 'old_string') ?? ''),
167 }
168 return { icon: ICONS.edit, color: tint(GRUVBOX.yellow), label: path, stats: counts ? diffStats(counts) : [] }
169 }
170
171 if (tool === 'Write') {
172 const path = text(input, 'file_path')
173 if (path === undefined) return undefined
174 // A new file's result may carry no hunks: its lines are the content's.
175 const counts = patchCounts(output)
176 const stats = isErrored
177 ? []
178 : counts && counts.added + counts.removed > 0
179 ? diffStats(counts)
180 : [{ text: `+${lineCount(text(input, 'content') ?? '')}`, color: GRUVBOX.green }]
181 return { icon: ICONS.write, color: tint(GRUVBOX.yellow), label: path, stats }
182 }
183
184 if (tool === 'NotebookEdit') {
185 const path = text(input, 'notebook_path')
186 if (path === undefined) return undefined
187 return { icon: ICONS.notebook, color: tint(GRUVBOX.yellow), label: path, stats: [] }
188 }
189
190 if (tool === 'Read') {
191 const path = text(input, 'file_path')
192 if (path === undefined) return undefined
193 const lines = field(field(output, 'file'), 'numLines')
194 const stats = !isErrored && typeof lines === 'number' ? [{ text: `(${lines}行)`, color: GRUVBOX.gray }] : []
195 return { icon: ICONS.read, color: tint(GRUVBOX.blue), label: path, stats }
196 }
197
198 if (tool === 'Bash') {
199 const command = text(input, 'command')
200 if (command === undefined) return undefined
201 // No duration: tool.call's span includes the permission prompt, and no event
202 // marks when the command itself started.
203 const stats: Stat[] = isErrored ? [{ text: '· error', color: GRUVBOX.red }] : []
204 return { icon: ICONS.bash, color: tint(GRUVBOX.aqua), label: firstLine(command), stats }
205 }
206
207 if (tool === 'Grep' || tool === 'Glob') {
208 const pattern = text(input, 'pattern')
209 if (pattern === undefined) return undefined
210 return { icon: ICONS.search, color: tint(GRUVBOX.purple), label: pattern, stats: [] }
211 }
212
213 if (tool === 'Agent') {
214 const description = text(input, 'description')
215 if (description === undefined) return undefined
216 const type = text(input, 'subagent_type') ?? 'general-purpose'
217 return { icon: ICONS.agent, color: tint(GRUVBOX.orange), label: `${type}: ${description}`, stats: [] }
218 }
219
220 if (tool === 'WebFetch') {
221 const url = text(input, 'url')
222 if (url === undefined) return undefined
223 return { icon: ICONS.web, color: tint(GRUVBOX.blue), label: host(url), stats: [] }
224 }
225
226 if (tool === 'WebSearch') {
227 const query = text(input, 'query')
228 if (query === undefined) return undefined
229 return { icon: ICONS.web, color: tint(GRUVBOX.blue), label: query, stats: [] }
230 }
231
232 const mcp = /^mcp__(.+?)__(.+)$/.exec(tool)
233 if (mcp) {
234 return { icon: ICONS.mcp, color: tint(GRUVBOX.gray), label: `${mcp[1]}:${mcp[2]}`, stats: [] }
235 }
236
237 return undefined
238}
239