SLOPSHOPPER

agent-watch

Shows who is doing the work this turn: the main chat, every helper agent, its model, task, status and the skills that ran, in a band above the prompt and a…

panebandguardcommandpromptagents
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · agent-watch
│ ┃ Agents ✕ › fix the failing auth test and add an audit log call │ ┃ Agents │ ┃ ⏺ Read(src/auth.ts) │ ┃ main ✓ ⎿ Read 6 lines │ ┃ model unknown · calls 9 · tokens 0 in / 0 ⏺ Update(src/auth.ts) │ ┃ out ⎿ Added 2 lines, removed 1 line │ ┃ skills: none ⏺ Bash(bun test) │ ┃ ⎿ 3 pass, 1 fail │ ┃ Totals per model │ ┃ unknown 0 steps · 9 calls · 0 in / 0 out ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ │ ┃ Timeline (0s) ✻ Worked for 42s · done 4:20 PM │ ┃ ██████████████████████████ main │ › /agent-watch │ ⎿ agent-watch: Agents pane opened. │ │ agents │ ● main ✓ ⟨Claude Code's own drawing⟩ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
agents │ ● main ✓ ⟨Claude Code's own drawing⟩
Pane · Agents
Agents main ✓ model unknown · calls 9 · tokens 0 in / 0 out skills: none Totals per model unknown 0 steps · 9 calls · 0 in / 0 out Timeline (0s) ██████████████████████████ main
README

lchase

Lawrence Chase's Claude Code marketplace: code review, diagram, test-evidence and software factory skills, plus a set of small Claude Code mods that add band lines and panes to the terminal UI.

/plugin marketplace add lchase/coding-agent-plugins
/plugin install smart-review@lchase
/plugin install tldraw@lchase
/plugin install test-drive@lchase
/plugin install cache-clock@lchase
/plugin install usage-gauge@lchase
/plugin install auto-handoff@lchase
/plugin install agent-watch@lchase
/plugin install recording-mode@lchase
/plugin install factory@lchase

Each plugin is independent; install only what you want. @lchase is the marketplace name (from .claude-plugin/marketplace.json), not the GitHub slug.

Updating

New versions ship whenever the version string in a plugin's manifest changes. Claude Code refreshes marketplaces in the background by default, so you normally pick up updates without doing anything. To pull them right now:

/plugin marketplace update lchase      # refresh this marketplace's manifest
/plugin update smart-review@lchase     # apply a pending update to one plugin
/plugin update tldraw@lchase

/plugin marketplace update (no name) refreshes every marketplace. From a shell: claude plugin marketplace update lchase and claude plugin update <plugin>@lchase.

Reinstalling

If a plugin gets into a bad state (stale cached script, half-applied update), do a clean reinstall:

/plugin uninstall tldraw
/plugin marketplace update lchase
/plugin install tldraw@lchase

Nuclear option, re-register the whole marketplace:

/plugin marketplace remove lchase
/plugin marketplace add lchase/coding-agent-plugins
/plugin install smart-review@lchase
/plugin install tldraw@lchase

Migrating from the old layout

Before this repo became a multi-plugin marketplace it published one plugin from the repo root under a marketplace named chase. If you installed it back then, clear the old registration first:

/plugin uninstall smart-review
/plugin uninstall tldraw            # only if you installed the short-lived tldraw@chase
/plugin marketplace remove chase
/plugin marketplace add lchase/coding-agent-plugins
/plugin install smart-review@lchase
/plugin install tldraw@lchase

The tldraw skill's command also changed: /tldraw:tldraw → /tldraw:diagram.

PluginWhat it doesSkills / commandsHarnesses
smart-reviewEnsemble code review: six specialized lenses over a diff, merged into one deduplicated, severity-ranked verdict/smart-review:{review,min,max,add-pr-review,review-pr-comments} + auto-triggerClaude Code, Cursor, Codex, Gemini CLI, any AGENTS.md agent
tldrawNatural-language description → editable tldraw document (.tldr) + rendered PNG/SVG/tldraw:diagram + auto-triggerClaude Code only (needs Node + npx)
test-driveBefore/after evidence of a UI or API change: record the app before you edit, replay the same scripted scenario after, with a deterministic verdict/test-drive:{baseline,compare} + auto-triggerClaude Code only (needs Node; UI also needs Playwright and ffmpeg)
cache-clockMod: band line showing whether the prompt cache is warm. TTL, expiry, hit ratio, and re-cache size come from Claude Code when the status-line bridge is installed; otherwise the countdown is a marked estimateCompact button (warm only), /cache-clockClaude Code only
usage-gaugeMod: band line with plan usage windows (5-hour, weekly, spend limit), reset times, pace warning, session cost on API billing, threshold toasts/usage-gauge (detail pane)Claude Code only
auto-handoffMod: band line showing how full the chat is; saves a HANDOFF.md at a threshold (auto or on request), then clear and continue or resume in a new session/auto-handoffClaude Code only
agent-watchMod: band line showing who is doing the work this turn (main chat, helper agents, models, tasks, status, skills), plus a pane with per-agent blocks, per-model totals, timeline/agent-watchClaude Code only
recording-modeMod: screen-record without leaking secrets; tells the model to keep keys, emails, private words off screen and masks them in the transcript display only, red REC chip/recClaude Code only
factorySoftware factory: a feature or bug goes through spec-writer, builder, four parallel reviewers and an approver on its own branch, then merges to main or waits for you; live dashboard/factory <input>, /factory {setup,next,approve,rework,serve}Claude Code only (dashboard needs Bun)

smart-review

An ensemble code review: several specialized lenses, one merged verdict, not another pile of comments.

Most code review, human or AI, is one reviewer making a single pass and leaving a list of comments. This runs six specialized lenses instead (spec-conformance, correctness, security, performance, design, and tests), then merges the results into one verdict: duplicates collapsed, findings that several lenses independently raise weighted up, conflicting advice reconciled, severity rolled up, structural problems first, nits capped. The merge is the point. An ensemble without it is just louder, and a longer checklist handed to one reviewer only dilutes its attention and repeats its own misses.

Two modes: a fast single pass (min) for tight loops, and an orchestrated ensemble (max) for pre-merge review. Auto-routing picks between them by change size and sensitivity.

The skill lives in plugins/smart-review/skills/smart-review/ as harness-neutral markdown. Each harness gets a thin manifest pointing at that same directory, so no skill content is copied or forked.

HarnessInstallminmaxSlash commands / auto-trigger
Claude Code/plugin marketplace add lchase/coding-agent-plugins then /plugin install smart-review@lchase✅✅ isolated parallel subagents✅
Cursorpoint Cursor at plugins/smart-review/.cursor-plugin/✅✅ sequential ensemblevia session-start hook
Codexplugins/smart-review/.codex-plugin/ manifest✅✅ sequential ensembleno
Gemini CLIgemini extensions install https://github.com/lchase/coding-agent-plugins (reads root gemini-extension.json)✅✅ sequential ensemblevia GEMINI.md
Any AGENTS.md agentreads root AGENTS.md✅✅ sequential ensembleno

max's isolated parallel subagents are a Claude Code capability. A model panel (plugins/smart-review/skills/smart-review/references/ensemble.md, off by default) rides on top when the harness can route more than one model. Otherwise max is single-model. Elsewhere max runs the same spec-gate, six lenses, and merge as a disciplined sequential walk. Design and internals: plugins/smart-review/SMART-REVIEW.md.

Claude Code slash commands:

  • /smart-review:review: auto (routes to min or max by size + sensitivity)
  • /smart-review:min: fast single-pass review
  • /smart-review:max: orchestrated ensemble review
  • /smart-review:add-pr-review <PR number or URL>: reviews a GitHub PR and, after you confirm what to publish, posts the findings as PR comments
  • /smart-review:review-pr-comments <PR number or URL>: triages a PR's existing unresolved review comments, fixes or explains each after your approval, replies, and resolves the thread

The skill also triggers automatically when you ask Claude to review a diff, PR, or branch.


tldraw

Turn a described diagram (flowchart, architecture / system diagram, process map, decision tree, state machine) into two artifacts: an editable .tldr document (opens at tldraw.com or in the tldraw editor) and a rendered PNG/SVG for docs and PRs.

Claude writes a {nodes, edges} spec from your description; a bundled Node script does a simple layered auto-layout, emits the .tldr, and renders images by loading it into a headless-Chromium tldraw instance via @kitschpatrol/tldraw-cli (first run downloads Chromium, ~1 min, cached).

/plugin install tldraw@lchase

Claude Code only. Skill: /tldraw:diagram (also auto-triggers on "draw this diagram", "diagram this flow", "make a tldraw of…"). Details: plugins/tldraw/skills/diagram/SKILL.md.


test-drive

A test drive is an e2e test that happens to produce video, and the "before" is part of the process rather than something reconstructed later. Run /test-drive:baseline before you edit: it writes a short browser scenario and records the app as it stands. Make the change, then run /test-drive:compare: it replays the identical scenario with Playwright and composes a labeled side-by-side MP4. The pass/warn/fail verdict comes from the scenario's assertions, not from reading the video.

Backend changes work the same way with "kind": "api": the scenario is a list of HTTP steps (method, path, body, expected status, JSON fields, and server-log lines to expect or avoid). There is nothing to screen-record, so each step captures the request, the response, and the server log lines it produced, and compare writes a before/after report.md instead of a video. Secrets are redacted from the stored transcript (best effort, extendable per scenario with redact), and the finished report is scanned and flagged if anything still looks secret.

/plugin install test-drive@lchase

Claude Code only. UI scenarios need ffmpeg and Playwright in the repo under test; API scenarios need only Node 18+. Only the working tree is ever run, so there is no second checkout to boot. Details: baseline and compare.


Claude Code mods

Five small plugins that change Claude Code's own interface instead of adding a task skill. Each draws a band line above the prompt (some add a side pane or slash command), is independent of the others, and works on Claude Code only.

  • cache-clock: is the prompt cache still warm? After /cache-clock setup, the countdown, TTL, hit ratio, re-cache size, and last miss cause come from Claude Code's own prompt_cache (v2.1.251+). Without that, the band uses your promptCacheTtl or cache environment variables, and only then a fallback (cacheMinutes, default 5) marked with ?. Compact is offered only while the cache is warm. Dollar figures stay hand-kept list-price estimates.
  • usage-gauge: plan usage windows (5-hour, weekly, spend limit) with reset times and a pace warning; session cost on API billing; threshold toasts. /usage-gauge opens a detail pane.
  • auto-handoff: watches context fill and saves a HANDOFF.md at a threshold (automatically or on request), then clears and continues, or resumes in a new session. /auto-handoff.
  • agent-watch: who is doing the work this turn: main chat, helper agents, models, tasks, status, skills. /agent-watch opens a pane with per-agent blocks, per-model totals, and a timeline.
  • recording-mode: for screen recordings. Tells the model to keep keys, emails, and private words off screen and masks them in the transcript display only (the underlying transcript is untouched). Red REC chip, /rec to toggle.
/plugin install cache-clock@lchase    # or usage-gauge, auto-handoff, agent-watch, recording-mode

cache-clock and the status line

Claude Code tells a status-line script whether the prompt cache is warm, when it expires, and the session hit ratio (prompt_cache on the status-line JSON, v2.1.251 or later). A plugin cannot register a status line, and the mods API does not include those fields, so cache-clock reads them through a small bridge.

In Claude Code, run:

/cache-clock setup

That edits your user settings (~/.claude/settings.json, or $CLAUDE_CONFIG_DIR/settings.json when that variable is set). It saves whatever statusLine was there and points statusLine at cache-clock/bridge.mjs, which still runs your previous status line and writes Claude Code's prompt_cache for the band to read. /cache-clock remove puts the previous value back. node must be on PATH. Setup refuses to edit a status line that comes from managed settings, --settings, or a project or local settings file.

The same edit by hand, when you have no status line yet:

{
  "statusLine": {
    "type": "command",
    "command": "node ~/.claude/cache-clock/bridge.mjs"
  }
}

Run /cache-clock setup once so the script is copied into that folder. After the next reply the band's TTL and expiry are Claude Code's figures, not a guess. The band redraws every 30 seconds from the last expires_at. Claude Code also re-runs the status line on its own events, and when a warm cache reaches expires_at.

Until the bridge is installed, the band still works. It follows this order: prompt_cache if the bridge has written it, then FORCE_PROMPT_CACHING_5M, CLAUDE_CODE_PROMPT_CACHE_TTL, the promptCacheTtl setting, ENABLE_PROMPT_CACHING_1H, then the cacheMinutes option (5 or 60, default 5). Only that last step is marked with ?. A subscription within plan usage is often 60 minutes and an API key, cloud provider, or usage-credit session is often

  1. The option cannot see a mid-session change; the bridge can.

/cache-clock status names which of those sources the band is using.


factory

A small, visual software factory. /factory <input> takes a feature or bug as text, a path to a requirements .md, an issue key or URL, or a GitHub issue, and runs it through a fixed loop: spec-writer writes a spec with testable acceptance criteria, builder implements it in its own git worktree (via the Orca CLI when present, so .env and setup hooks come along, else plain git worktree), four reviewers (security, ux, ui, code) run in parallel and each writes a VERDICT: PASS | CHANGES file, the builder is resumed while any review says CHANGES (max two rounds), then an approver writes APPROVE or ESCALATE. APPROVE merges to main locally; ESCALATE parks the job as needs-human.

/plugin install factory@lchase

Then, in a repo:

/factory setup                          # once per repo: profiles it into .factory/repo.md, review that file
/factory <text | path.md | KEY-123 | #123>
/factory next                           # first unchecked item in .factory/backlog.md
/factory approve <job-id>               # merge a needs-human job
/factory rework <job-id> <note>         # send it back to the builder with your note
/factory serve                          # live board at http://localhost:8765 (needs Bun)

Nothing repo-specific is baked in: commands, conventions, commit rules, issue tracker and the approver's never-auto-merge list all come from .factory/repo.md, which /factory setup drafts and you edit. Job state is .factory/jobs/<id>/ (gitignored), one folder of markdown per job, so several sessions can run jobs at once and the dashboard shows them all.

Claude Code only. Dashboard needs Bun. Full guide, including what happens when a job stops for you: plugins/factory/README.md.


Token-savings benchmark

benchmarks/token-savings/ compares stock Claude Code with plugins and settings that claim to cut tokens or cost. It is not a marketplace plugin. Click 8.5.0 is fetched at a pinned commit when you run it. The full matrix calls the Anthropic API and has a hard ceiling of $600 at the default per-session cap. Read the benchmark README before you run it. ./benchmarks/token-savings/check.sh is the offline check and does not spend API money.

Repo layout

.claude-plugin/marketplace.json   # the "lchase" marketplace: 9 plugin entries
AGENTS.md                         # repo-level agent pointer (→ smart-review)
gemini-extension.json + GEMINI.md # Gemini CLI installs the repo as an extension (→ smart-review)

plugins/smart-review/             # plugin 1, multi-harness code review
  .claude-plugin/plugin.json
  skills/smart-review/            # the harness-neutral core (SKILL.md + references/)
  agents/ commands/ hooks/        # Claude Code packaging
  .cursor-plugin/ .codex-plugin/  # thin per-harness manifests
  scripts/                        # validate-adapters.sh, bump-version.sh
  evals/                          # dev-only eval kit (not shipped to installers)
  SMART-REVIEW.md                 # design writeup

plugins/tldraw/                   # plugin 2, Claude Code only
  .claude-plugin/plugin.json
  skills/diagram/                 # SKILL.md + scripts/build-tldr.mjs + references/

plugins/test-drive/               # plugin 3, Claude Code only
  .claude-plugin/plugin.json
  skills/{baseline,compare}/      # SKILL.md each
  scripts/{lib.mjs,record.mjs,record-api.mjs,redact.mjs,verdict.mjs,compose.sh,report.mjs}   # shared by both skills
  references/                     # UI and API scenario schemas + examples

plugins/factory/                  # plugin 4, Claude Code only
  .claude-plugin/plugin.json
  skills/factory/SKILL.md         # the orchestrator loop, commands, setup, job.json and repo.md schemas
  agents/                         # spec-writer, builder, review-{security,ux,ui,code}, approver, repo-profiler
  dashboard/                      # dashboard.html + serve.ts (Bun) + example/ dummy jobs

plugins/{cache-clock,usage-gauge,auto-handoff,agent-watch,recording-mode}/   # plugins 5-9, Claude Code mods
  .claude-plugin/plugin.json      # each with its own version
  hooks/                          # register.tsx (the mod) + hooks.json, tests where present
  types/                          # mod API typings

benchmarks/token-savings/         # paired Claude Code cost benchmark (not a plugin)

Developing

claude plugin validate .                                # marketplace + all plugins
./plugins/smart-review/scripts/validate-adapters.sh      # smart-review's per-harness manifests
./benchmarks/token-savings/check.sh                      # benchmark lint and graders; no API spend
claude plugin test plugins/cache-clock                   # mod tests, including the native prompt_cache path
node --test plugins/cache-clock/statusline/bridge.test.mjs

Releasing: users only get an update when a plugin's version string changes, so bump it on every user-facing change and push to main.

  • smart-review: version is pinned across all its manifests; bump them together with ./plugins/smart-review/scripts/bump-version.sh <version>.
  • tldraw, test-drive, factory, and each mod: version independently; edit that plugin's .claude-plugin/plugin.json.

Once pushed, installed clients pick it up on their next background marketplace refresh, or immediately with /plugin marketplace update lchase.

Source 3 files
hooks/register.tsx 298 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { AgentRow, Run, Settings } from '../types'
5import type { Seg } from './lib'
6import {
7  HELP,
8  MAIN,
9  SEP,
10  addCall,
11  addSkill,
12  addUsage,
13  bandSegs,
14  emptyRun,
15  modelColor,
16  seconds,
17  statusColor,
18  statusMark,
19  text,
20  timelineBar,
21  tokens,
22  touch,
23  tree,
24} from './lib'
25
26const PANE = 'agent-watch'
27const DEFAULTS: Settings = { isOn: true }
28
29const run = atom({ plugin: 'agent-watch', key: 'run' } as const, null)
30const settings = atom({ plugin: 'agent-watch', key: 'settings' } as const, DEFAULTS)
31
32const isSettings = (v: unknown): v is Settings =>
33  typeof v === 'object' && v !== null && typeof (v as Settings).isOn === 'boolean'
34
35const agentOf = (e: { agentId?: string }): string => e.agentId ?? MAIN
36
37/** Applies `fn` to the current turn's run, starting one when none is open. */
38async function change($: EngineInterface, fn: (r: Run, now: number) => Run) {
39  try {
40    const now: number = await $.clock.now()
41    await update($, run, cur => fn(cur ?? touch(emptyRun(now), MAIN, now, () => ({})), now))
42  } catch {
43    // Watching must never break a tool call or a turn.
44  }
45}
46
47
48export const register: Register = on => {
49  on('session.start', async ($, e, next) => {
50    const saved = await $.store.get('settings')
51    if (isSettings(saved)) await update($, settings, () => saved)
52    await $.command.register({
53      name: 'agent-watch',
54      description: 'Who is doing the work this turn: agents, models, tasks, skills',
55      argumentHint: 'on | off | clear | help',
56    })
57
58    return next(e)
59  })
60
61  on('turn.start', async ($, e, next) => {
62    if (!e.turnId) return next(e)
63    const now: number = await $.clock.now()
64    await update($, run, () => touch(emptyRun(now), MAIN, now, () => ({ status: 'running' })))
65
66    return next(e)
67  })
68
69  on('agent.spawn', async ($, e, next) => {
70    const started = await next(e)
71    if ('agentId' in started && started.agentId) {
72      const id = started.agentId
73      await change($, (r, now) =>
74        touch(r, id, now, a => ({
75          type: e.name ?? e.subagentType,
76          task: e.description || e.prompt,
77          model: a.model || started.model,
78          parent: e.parentAgentId ?? MAIN,
79        })),
80      )
81    }
82
83    return started
84  })
85
86  on('tool.call', async ($, e, next) => {
87    const id = agentOf(e)
88    await change($, (r, now) => {
89      const counted = addCall(r, id, now)
90      // Remember who called the Skill tool, so its skill.prompt lands on that agent.
91      return e.tool === 'Skill'
92        ? { ...counted, pending: [...counted.pending, { skill: String(e.skill), agentId: id }] }
93        : counted
94    })
95
96    return next(e)
97  })
98
99  on('skill.prompt', async ($, e, next) => {
100    await change($, (r, now) => {
101      const at = r.pending.findIndex(p => p.skill === e.skill)
102      const owner = at >= 0 ? (r.pending[at]?.agentId ?? MAIN) : MAIN
103      const rest = at >= 0 ? r.pending.filter((_, i) => i !== at) : r.pending
104
105      return addSkill({ ...r, pending: rest }, owner, e.skill, now)
106    })
107
108    return next(e)
109  })
110
111  on('turn.step', async function* ($, e, next) {
112    const result = yield* next(e)
113    const used = result?.usage
114    await change($, (r, now) =>
115      addUsage(
116        r,
117        agentOf(e),
118        used?.model ?? e.model,
119        used ? used.input_tokens + used.cache_read_input_tokens + used.cache_creation_input_tokens : 0,
120        used ? used.output_tokens : 0,
121        now,
122      ),
123    )
124
125    return result
126  })
127
128  on('turn.complete', async ($, e, next) => {
129    const id = agentOf(e)
130    await change($, (r, now) => {
131      const done = touch(r, id, now, () => ({
132        status: e.reason === 'answer' ? 'done' : 'failed',
133        endedAt: now,
134      }))
135
136      return id === MAIN ? { ...done, endedAt: now } : done
137    })
138
139    return next(e)
140  })
141
142  on('command.run', { command: 'agent-watch' }, async ($, e) => {
143    const word = (e.args.trim().split(/\s+/)[0] ?? '').toLowerCase()
144    const cfg: Settings = ((await read($, settings)) as Settings | undefined) ?? DEFAULTS
145
146    if (word === '') {
147      await $.ui.open({ id: PANE, title: 'Agents' })
148
149      return { text: 'Agents pane opened.' }
150    }
151    if (word === 'on' || word === 'off') {
152      const next: Settings = { ...cfg, isOn: word === 'on' }
153      await update($, settings, () => next)
154      await $.store.set('settings', next)
155
156      return { text: `agent-watch band ${word}.` }
157    }
158    if (word === 'clear') {
159      await update($, run, () => null)
160
161      return { text: 'agent-watch cleared.' }
162    }
163
164    return { text: HELP }
165  })
166
167  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
168    const cfg: Settings = ((await read($, settings)) as Settings | undefined) ?? DEFAULTS
169    const r = await read($, run)
170    if (e.props.hasSurvey || !cfg.isOn || r === null) return next(e)
171
172    const { Box, Text } = $.ui.resolve(e)
173    const segs = bandSegs(r, e.props.bodyColumns)
174    const draw = (s: Seg) => (
175      <Text bold={s.bold} dimColor={s.dim} color={s.color} backgroundColor={s.bg}>
176        {s.t}
177      </Text>
178    )
179    // proportional fonts collapse the padded label and │ columns: the groups between them, spaced by gap
180    const groups: Seg[][] = [[]]
181    for (const s of segs) {
182      if (s === SEP) groups.push([])
183      else groups[groups.length - 1]?.push(s)
184    }
185    const line = e.surface !== 'terminal' ? (
186      // one label column and one fixed gap on every band, so all rows start their content at the same x
187      <Box flexDirection="row" alignItems="center">
188        <Box width={9} flexShrink={0}><Text dimColor bold>{text(groups[0] ?? []).trim()}</Text></Box>
189        <Box flexDirection="row" alignItems="center" flexWrap="wrap" flexGrow={1} columnGap={2}>
190          {groups.slice(1).map(g => (
191            <Text>{g.map(draw)}</Text>
192          ))}
193        </Box>
194      </Box>
195    ) : (
196      <Text wrap="truncate-end">
197        {segs.map(s => (
198          <Text bold={s.bold} dimColor={s.dim} color={s.color} backgroundColor={s.bg}>
199            {s.t}
200          </Text>
201        ))}
202      </Text>
203    )
204    const below = await next(e)
205
206    return below ? (
207      <Box flexDirection="column">
208        {line}
209        {below}
210      </Box>
211    ) : (
212      line
213    )
214  })
215
216  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
217    const { Box, Text } = $.ui.resolve(e)
218    const r = await read($, run)
219    if (r === null) {
220      return (
221        <Box flexDirection="column">
222          <Text bold>Agents</Text>
223          <Text dimColor>No turn yet.</Text>
224        </Box>
225      )
226    }
227
228    const now: number = await $.clock.now()
229    const total = Math.max(1, (r.endedAt ?? now) - r.startedAt)
230    const rows = tree(r)
231    const barWidth = Math.max(10, Math.min(40, (e.props.bodyColumns ?? 60) - 30))
232    const models = Object.entries(r.byModel)
233    // the terminal's █ and · cells; elsewhere one Svg span on a 240px track
234    const Span = (start: number, end: number, row: AgentRow) => {
235      if (e.surface === 'terminal') {
236        return (
237          <Text>
238            <Text color={statusColor(row.status)}>{timelineBar(start, end, total, barWidth)}</Text>
239            <Text dimColor> {row.type}</Text>
240          </Text>
241        )
242      }
243      const { Svg } = $.ui.resolve(e)
244      const x = Math.round(Math.min(1, Math.max(0, start / total)) * 240)
245      const w = Math.max(3, Math.round(Math.min(1, Math.max(0, end / total)) * 240) - x)
246      return (
247        <Box flexDirection="row" alignItems="center" gap={1}>
248          <Svg
249            source={`<svg xmlns="http://www.w3.org/2000/svg" width="240" height="8" viewBox="0 0 240 8"><rect width="240" height="8" rx="4" fill="#8080804d"/><rect x="${x}" width="${w}" height="8" rx="4" fill="${statusColor(row.status)}"/></svg>`}
250            alt={`${row.type} ${seconds(end - start)}`}
251            width={240}
252            height={8}
253          />
254          <Text dimColor>{row.type}</Text>
255        </Box>
256      )
257    }
258
259    return (
260      <Box flexDirection="column">
261        <Text bold>Agents</Text>
262        {rows.map(({ row, depth }) => (
263          <Box flexDirection="column" marginTop={1} marginLeft={depth * 2}>
264            <Text>
265              <Text bold>{row.type}</Text>
266              {row.task ? <Text bold> — {row.task}</Text> : null}{' '}
267              <Text color={statusColor(row.status)}>{statusMark(row.status)}</Text>
268            </Text>
269            <Text dimColor>
270              model <Text color={modelColor(row.model)}>{row.model || 'unknown'}</Text>
271              {' · '}calls {row.calls}
272              {' · '}tokens {tokens(row.tokensIn)} in / {tokens(row.tokensOut)} out
273            </Text>
274            <Text dimColor>skills: {row.skills.length > 0 ? row.skills.join(', ') : 'none'}</Text>
275          </Box>
276        ))}
277        <Box flexDirection="column" marginTop={1}>
278          <Text bold>Totals per model</Text>
279          {models.length === 0 && <Text dimColor>No model steps yet.</Text>}
280          {models.map(([label, m]) => (
281            <Text>
282              <Text color={modelColor(label)}>{label}</Text>
283              <Text dimColor>
284                {' '}
285                {m.steps} steps · {m.calls} calls · {tokens(m.tokensIn)} in / {tokens(m.tokensOut)} out
286              </Text>
287            </Text>
288          ))}
289        </Box>
290        <Box flexDirection="column" marginTop={1}>
291          <Text bold>Timeline ({seconds(total)})</Text>
292          {rows.map(({ row }) => Span(row.startedAt - r.startedAt, (row.endedAt ?? now) - r.startedAt, row))}
293        </Box>
294      </Box>
295    )
296  })
297}
298
hooks/lib.ts 214 lines
1import type { AgentRow, Run, Status } from '../types'
2
3// label column width, the length of 'handoff', so stacked bands line up
4export const LABEL_W = 7
5export const SKILL_COLOR = '#a3e635'
6export const TASK_MAX = 22
7export const MAIN = 'main'
8
9// same purple as auto-handoff's branch name
10const MODEL_COLOR = '#b794f4'
11const STATUS_COLOR: Record<Status, string> = {
12  running: '#f59e0b',
13  done: '#22c55e',
14  failed: '#ef4444',
15}
16const STATUS_MARK: Record<Status, string> = { running: '⟳', done: '✓', failed: '✗' }
17
18export const statusColor = (s: Status): string => STATUS_COLOR[s]
19export const statusMark = (s: Status): string => STATUS_MARK[s]
20
21const FAMILY_RE = /(fable|opus|sonnet|haiku)/
22
23/** `claude-opus-5-5` -> `opus·5.5`, `claude-3-5-sonnet-20241022` -> `sonnet·3.5`, `haiku` -> `haiku`. */
24export function modelLabel(raw: string | undefined): string {
25  if (!raw) return ''
26  const id = raw.toLowerCase().replace(/\[.*\]$/, '').replace(/-\d{8}$/, '')
27  const m = FAMILY_RE.exec(id)
28  if (!m) return raw
29  const family = m[1] as string
30  const after = id.slice(m.index + family.length)
31  const before = id.slice(0, m.index)
32  const a = /^-(\d+)(?:-(\d+))?$/.exec(after)
33  if (a) return `${family}·${a[1]}${a[2] ? `.${a[2]}` : ''}`
34  const b = /(\d+)(?:-(\d+))?-$/.exec(before)
35  if (b) return `${family}·${b[1]}${b[2] ? `.${b[2]}` : ''}`
36  return family
37}
38
39export function modelColor(label: string): string | undefined {
40  const m = FAMILY_RE.exec(label)
41  return m ? MODEL_COLOR : undefined
42}
43
44/** Task text cut to `max` characters, ending in an ellipsis when it was longer. */
45export function cut(text: string, max = TASK_MAX): string {
46  const t = text.replace(/\s+/g, ' ').trim()
47  return t.length > max ? `${t.slice(0, max - 1).trimEnd()}…` : t
48}
49
50export type Seg = { t: string; color?: string; bg?: string; bold?: boolean; dim?: boolean }
51
52export const text = (segs: readonly Seg[]): string => segs.map(s => s.t).join('')
53
54export function emptyRun(now: number): Run {
55  return { startedAt: now, order: [], agents: {}, skills: [], pending: [], byModel: {} }
56}
57
58export function blankAgent(id: string, now: number): AgentRow {
59  return {
60    id,
61    type: id === MAIN ? MAIN : 'agent',
62    task: '',
63    model: '',
64    status: 'running',
65    parent: MAIN,
66    calls: 0,
67    tokensIn: 0,
68    tokensOut: 0,
69    skills: [],
70    startedAt: now,
71  }
72}
73
74/** Reducer helper: the run with agent `id` present (created when unseen) and patched. */
75export function touch(run: Run, id: string, now: number, patch: (a: AgentRow) => Partial<AgentRow>): Run {
76  const existing = run.agents[id]
77  const base = existing ?? blankAgent(id, now)
78  const order = existing || run.order.includes(id) ? run.order : [...run.order, id]
79  return { ...run, order, agents: { ...run.agents, [id]: { ...base, ...patch(base) } } }
80}
81
82export function addSkill(run: Run, agentId: string, skill: string, now: number): Run {
83  const named = touch(run, agentId, now, a => (a.skills.includes(skill) ? {} : { skills: [...a.skills, skill] }))
84  return named.skills.includes(skill) ? named : { ...named, skills: [...named.skills, skill] }
85}
86
87export function addUsage(run: Run, agentId: string, model: string, tokensIn: number, tokensOut: number, now: number): Run {
88  const label = modelLabel(model)
89  const next = touch(run, agentId, now, a => ({
90    model: label || a.model,
91    tokensIn: a.tokensIn + tokensIn,
92    tokensOut: a.tokensOut + tokensOut,
93  }))
94  const key = label || 'unknown'
95  const m = next.byModel[key] ?? { steps: 0, calls: 0, tokensIn: 0, tokensOut: 0 }
96  return {
97    ...next,
98    byModel: { ...next.byModel, [key]: { ...m, steps: m.steps + 1, tokensIn: m.tokensIn + tokensIn, tokensOut: m.tokensOut + tokensOut } },
99  }
100}
101
102export function addCall(run: Run, agentId: string, now: number): Run {
103  const next = touch(run, agentId, now, a => ({ calls: a.calls + 1 }))
104  const label = next.agents[agentId]?.model || 'unknown'
105  const m = next.byModel[label] ?? { steps: 0, calls: 0, tokensIn: 0, tokensOut: 0 }
106  return { ...next, byModel: { ...next.byModel, [label]: { ...m, calls: m.calls + 1 } } }
107}
108
109/** Helpers in spawn order, main excluded. */
110export const helpers = (run: Run): AgentRow[] =>
111  run.order.filter(id => id !== MAIN).map(id => run.agents[id] as AgentRow)
112
113function agentSegs(a: AgentRow, withTask: boolean): Seg[] {
114  const out: Seg[] = [{ t: '● ', color: modelColor(a.model) }, { t: a.type, bold: a.id === MAIN }]
115  if (a.model) out.push({ t: ' ' }, { t: a.model, color: modelColor(a.model) })
116  if (withTask && a.id !== MAIN && a.task) out.push({ t: ` "${cut(a.task)}"` })
117  out.push({ t: ' ' }, { t: statusMark(a.status), color: statusColor(a.status) })
118  return out
119}
120
121export const SEP: Seg = { t: ' │ ', dim: true }
122const DOT: Seg = { t: ' · ', dim: true }
123
124/**
125 * The band line as segments, fitted to `columns`. Task text goes first, oldest
126 * helper first, except the first helper's. Then newest helpers collapse to
127 * "+N more", then skills shrink to the first one plus "+N".
128 */
129export function bandSegs(run: Run, columns: number): Seg[] {
130  const all = helpers(run)
131  const main = run.agents[MAIN] ?? { ...blankAgent(MAIN, run.startedAt) }
132  const showTask = all.map(() => true)
133  let hidden = 0
134  let skillsShown = run.skills.length
135
136  const build = (): Seg[] => {
137    const segs: Seg[] = [{ t: 'agents'.padStart(LABEL_W), dim: true }, SEP, ...agentSegs(main, false)]
138    const visible = all.slice(0, all.length - hidden)
139    if (visible.length > 0 || hidden > 0) {
140      segs.push(SEP)
141      visible.forEach((a, i) => {
142        if (i > 0) segs.push(DOT)
143        segs.push(...agentSegs(a, showTask[i] as boolean))
144      })
145      if (hidden > 0) segs.push(...(visible.length > 0 ? [DOT] : []), { t: `+${hidden} more`, dim: true })
146    }
147    if (run.skills.length > 0) {
148      segs.push(SEP, { t: 'skills: ', dim: true })
149      run.skills.slice(0, skillsShown).forEach((s, i) => {
150        if (i > 0) segs.push({ t: ', ', dim: true })
151        segs.push({ t: s, color: SKILL_COLOR })
152      })
153      const more = run.skills.length - skillsShown
154      if (more > 0) segs.push({ t: ` +${more}`, dim: true })
155    }
156    return segs
157  }
158  const fits = (): boolean => text(build()).length <= columns
159
160  for (let i = 1; i < all.length && !fits(); i++) showTask[i] = false
161  while (!fits() && all.length - hidden > 1) hidden++
162  while (!fits() && skillsShown > 1) skillsShown--
163
164  return build()
165}
166
167export function tokens(n: number): string {
168  if (n < 1000) return String(n)
169  if (n < 1_000_000) return `${(n / 1000).toFixed(n < 10_000 ? 1 : 0)}k`
170  return `${(n / 1_000_000).toFixed(1)}M`
171}
172
173export function seconds(ms: number): string {
174  const s = Math.max(0, Math.round(ms / 1000))
175  return s < 60 ? `${s}s` : `${Math.floor(s / 60)}m${String(s % 60).padStart(2, '0')}s`
176}
177
178/** A bar of `width` cells placing [start, end] inside [0, total]. */
179export function timelineBar(start: number, end: number, total: number, width: number): string {
180  if (width < 1) return ''
181  const span = Math.max(1, total)
182  const from = Math.min(width - 1, Math.max(0, Math.floor((start / span) * width)))
183  const to = Math.min(width, Math.max(from + 1, Math.ceil((end / span) * width)))
184  return '·'.repeat(from) + '█'.repeat(to - from) + '·'.repeat(width - to)
185}
186
187/** Agents depth-first: each helper right after its parent, spawn order among siblings. */
188export function tree(run: Run): { row: AgentRow; depth: number }[] {
189  const out: { row: AgentRow; depth: number }[] = []
190  const seen = new Set<string>()
191  const walk = (id: string, depth: number) => {
192    const row = run.agents[id]
193    if (!row || seen.has(id)) return
194    seen.add(id)
195    out.push({ row, depth })
196    for (const k of run.order) {
197      const child = run.agents[k]
198      const p = child && child.parent !== k && run.agents[child.parent] ? child.parent : MAIN
199      if (k !== MAIN && p === id) walk(k, depth + 1)
200    }
201  }
202  walk(MAIN, 0)
203  return out
204}
205
206export const HELP = [
207  'agent-watch: who is doing the work this turn.',
208  '/agent-watch          open the Agents pane',
209  '/agent-watch on       show the band above the prompt',
210  '/agent-watch off      hide the band (the pane still works)',
211  '/agent-watch clear    forget this turn',
212  '/agent-watch help     this text',
213].join('\n')
214
types/index.d.ts 41 lines
1export type Status = 'running' | 'done' | 'failed'
2
3export type AgentRow = {
4  id: string
5  /** Agent type or given name; `main` for the chat itself. */
6  type: string
7  task: string
8  /** Model label already shortened, e.g. `opus·5.5`; empty until known. */
9  model: string
10  status: Status
11  /** `main` or the id of the agent that spawned this one. */
12  parent: string
13  calls: number
14  tokensIn: number
15  tokensOut: number
16  skills: string[]
17  startedAt: number
18  endedAt?: number
19}
20
21export type Run = {
22  startedAt: number
23  endedAt?: number
24  /** Spawn order; `main` first. */
25  order: string[]
26  agents: Record<string, AgentRow>
27  /** Every skill that ran this turn, once each. */
28  skills: string[]
29  /** Skill tool calls waiting for their skill.prompt, to attribute it. */
30  pending: { skill: string; agentId: string }[]
31  byModel: Record<string, { steps: number; calls: number; tokensIn: number; tokensOut: number }>
32}
33
34export type Settings = { isOn: boolean }
35
36declare module 'claude-code' {
37  interface PluginState {
38    'agent-watch': { run: Run | null; settings: Settings }
39  }
40}
41