SLOPSHOPPER

delegate-watch

Live pane that watches agy, Claude Code, cursor-agent and opencode delegate runs while they work

panecommandtoaststatusprocesstimer
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · delegate-watch
│ ┃ Delegates ✕ › fix the failing auth test and add an audit log call │ ┃ ● Watching delegates starting… [ Pause ] │ ┃ ⏺ Read(src/auth.ts) │ ┃ ╭──────────────────────────────────────────╮ ⎿ Read 6 lines │ ┃ │ │ ⏺ Update(src/auth.ts) │ ┃ │ No delegate runs yet │ ⎿ Added 2 lines, removed 1 line │ ┃ │ Dispatch one with /agy-delegate, │ ⏺ Bash(bun test) │ ┃ │ /claude-delegate, /cursor-delegate or │ ⎿ 3 pass, 1 fail │ ┃ │ /opencode-delegate and it shows up │ │ ┃ │ here. │ ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ │ │ │ ┃ ╰──────────────────────────────────────────╯ ✻ Worked for 42s · done 4:20 PM │ ┃ │ ┃ › /delegate-watch │ ┃ [ All ] [ Tools ] [ Thoughts ] [ ↑ ] [ ↓ ] [ ⎿ delegate-watch: Delegates pane opened. │ ┃ │ ┃ TIMELINE · no events yet │ ┃ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Delegates
● Watching delegates starting… [ Pause ] ╭──────────────────────────────────────────────────────────╮ │ │ │ No delegate runs yet │ │ Dispatch one with /agy-delegate, /claude-delegate, │ │ /cursor-delegate or /opencode-delegate and it shows up │ │ here. │ │ │ ╰──────────────────────────────────────────────────────────╯ [ All ] [ Tools ] [ Thoughts ] [ ↑ ] [ ↓ ] [ ● Live ] [ − ] TIMELINE · no events yet
README

delegate-watch

A live pane for Claude Code that shows what your delegated coding agents are doing while they work, instead of leaving you blind until they finish.

It watches runs started by relay-style delegate scripts for agy (Google Antigravity), Claude Code (claude -p), cursor-agent and opencode, and works in both the terminal CLI and the desktop app.

It is built around the run folders written by the delegate-skills relay scripts (/agy-delegate, /claude-delegate, /cursor-delegate, /opencode-delegate). Install those skills to get runs to watch; this plugin only reads what they write.

What you see

The delegate-watch pane showing a running agent

  • A chip per recent run (● running, ✓ done, ✗ failed), newest first.
  • A status card: agent badge, model, elapsed time, tool calls or model turns, files edited, cost.
  • A tool-mix bar and a 30-minute activity strip.
  • A timeline of every event: clock time, time since the run started (01:38), a typed badge (READ, EDIT, SHELL, GREP, TURN, THINK...), and the file or command (folder dimmed, name bold).
  • Filters (All / Tools / Thoughts, or Turns / Edits for agy), scroll buttons and a Live toggle.
  • A toast when a run finishes and a status-line count of running delegates.

Per agent

AgentSourceWhat is shown
Claude Codeevents.jsonl (stream-json)every tool call, message, visible thought, failed tool result, and the run's cost
cursor-agentevents.jsonl (stream-json)every tool call, message and thought
opencodeevents.jsonlevery tool call, message, error, and cost
agyagy.log, stderr.txt, git, psmodel turns, files it edited since start, idle/blocked state, commands running under agy

agy writes no event stream, so for agy the pane infers progress from the outside: each streamGenerateContent request in its log is a model turn, files changed in the working tree since the run started are its edits, and ps shows what it is waiting on. It cannot show agy's tool calls or reasoning.

Install

/plugin install delegate-watch --marketplace EslamHanafy/delegate-watch

Or from a shell:

claude plugin marketplace add EslamHanafy/delegate-watch
claude plugin install delegate-watch@delegate-watch --scope user

Use

  • The pane opens by itself when a new run starts. Reopen it with /delegate-watch.
  • /delegate-watch pause and /delegate-watch resume stop and restart all polling. The choice is remembered across sessions. The Pause / Resume button in the pane does the same.
  • Closing the pane only hides it; polling continues until you pause.

Configure where it looks

Run folders live in different places depending on how you dispatch delegates, so the search folders are settings, not hard-coded. The defaults match the delegate relay scripts:

SettingDefaultMeaning
watchPaths$TMPDIR/delegate-relay, .orchestrator, .superpowersFolders to search for run folders. Absolute, or relative to the folder Claude Code was started in. $TMPDIR and ~ are expanded.
searchDepth6How many folder levels below each watched folder to search.
maxAgeHours6Only runs whose log changed within this many hours are shown.
maxSessions3How many of the most recent runs get a chip at the top of the pane (1 to 12).
timelineRows8How many timeline events show at once. 0 fits the pane height. The − / + buttons in the pane change it live and remember the choice. More rows cost a little more drawing per refresh, nothing else.

In the pane itself, the − / + buttons next to the timeline filters change the number of timeline rows by 5 (down to auto, which fits the pane height). That choice is remembered across sessions and takes priority over timelineRows. Long thinking and message rows end in ▸; press it to read the full text, ▾ to fold it again. The tool-mix bar always spans the full pane width, with bar widths square-root scaled so small groups stay visible (the legend shows exact counts and percentages).

Change them any of these ways:

  • The /config menu in Claude Code (each setting is a row under delegate-watch), or the prompt shown when you install the plugin.
  • claude plugin configure delegate-watch@delegate-watch.
  • Directly in ~/.claude/settings.json:
{
  "pluginConfigs": {
    "delegate-watch": {
      "watchPaths": ["$TMPDIR/delegate-relay", ".my-runs", "~/agent-runs"],
      "searchDepth": 4,
      "maxAgeHours": 24,
      "timelineRows": 30
    }
  }
}

Changes apply on the next /reload-plugins (or new session).

What counts as a run

Any folder under a watched path that contains events.jsonl (Claude Code, cursor-agent, opencode) or agy.log (agy). The pane also reads result.json, final.txt, brief.txt and stderr.txt in that folder when present. If your delegate scripts write somewhere else, point watchPaths at it. Start Claude Code in the project whose delegates you want to watch, so relative paths resolve there.

Cost and performance

No model calls and no tokens. It polls every 2 seconds (10 seconds when nothing is running), reads only the bytes added since the last poll of the selected run, and caps memory at 4,000 events per run. The find, git and ps calls run every 6 to 8 seconds, git and ps only for a running agy run.

Safety and privacy

Everything is local. It reads log files and runs find, tail, head, stat, git ls-files, pgrep and ps. It makes no network requests and sends nothing anywhere. The only thing it stores is the pause flag. The pane shows your delegates' output, which can contain code, paths and prompts, so treat screenshots accordingly. As with any plugin, read the code before installing; it is delegate-watch/hooks/.

Platforms

macOS and Linux. Windows is not supported (it relies on sh, find, xargs, ps).

Development

claude plugin validate delegate-watch
claude plugin test delegate-watch

After editing, run /reload-plugins. Bump the version in delegate-watch/.claude-plugin/plugin.json and .claude-plugin/marketplace.json for each release so installed copies update.

License

MIT

Source 5 files
hooks/register.tsx 642 lines
1import { atom, read, update } from 'claude-code'
2import type { Register } from 'claude-code'
3
4import type { Beat, Ev, Filter, Run } from '../types'
5import { FRESH_BEAT, nextBeat, orElse, withTimeout } from './guard'
6import {
7  MAX_EVENTS, agentOf, ago, beatLabel, blockedOf, childrenOf, clock, editsSince, glyph, mixOf, parseAgyLines, parseLines, parseStat, rel, expandCap, fitRows, fitText, spark, splitPath, startOf, tintOf, topLines, weightOf,
8} from './summarize'
9import type { Proc, Snap, Totals } from './summarize'
10import { anchorsOf, mergeCands, resolveRoots, searchedHint } from './roots'
11import type { Cand } from './roots'
12
13const PANE = 'delegate-watch'
14const POLL_MS = 2000
15const SLOW_EVERY = 4
16const FIND_EVERY = 3
17const IDLE_EVERY = 5
18const ROWS_STEP = 5
19const ROWS_MAX = 200
20const CALL_MS = 10_000
21const PROC_GUARD_MS = 3_000
22const REDRAW_MS = 5_000
23const MAX_READ = 8 * 1024 * 1024
24const STALE_MS = 15 * 60 * 1000
25const STAT = "if [ \"$(uname)\" = Darwin ]; then xargs -0 stat -f '%m %N'; else xargs -0 stat -c '%Y %n'; fi"
26const GOOD = ['success', 'completed', 'done', 'finished']
27
28const runs = atom({ plugin: 'delegate-watch', key: 'runs' } as const, [] as Run[])
29const selected = atom({ plugin: 'delegate-watch', key: 'selected' } as const, null as string | null)
30const events = atom({ plugin: 'delegate-watch', key: 'events' } as const, [] as Ev[])
31// scroll: 0 follows the newest event (live); n > 0 pins the view to end at event n, so new events cannot move it
32const scroll = atom({ plugin: 'delegate-watch', key: 'scroll' } as const, 0)
33const paused = atom({ plugin: 'delegate-watch', key: 'paused' } as const, false)
34const filter = atom({ plugin: 'delegate-watch', key: 'filter' } as const, 'all' as Filter)
35const expanded = atom({ plugin: 'delegate-watch', key: 'expanded' } as const, [] as string[])
36const rowsPref = atom({ plugin: 'delegate-watch', key: 'rowsPref' } as const, -1)
37const beat = atom({ plugin: 'delegate-watch', key: 'beat' } as const, FRESH_BEAT as Beat)
38// the cwd the session started in: kept in session state so a reload (which runs session.start again) does not move it
39const startCwd = atom({ plugin: 'delegate-watch', key: 'startCwd' } as const, '')
40// the absolute folders the last search looked in, shown when it found nothing
41const searched = atom({ plugin: 'delegate-watch', key: 'searched' } as const, [] as string[])
42
43type Data = {
44  offset: number
45  carry: string
46  evs: Ev[]
47  totals: Totals
48  snap: Snap | null
49  note: string
50  blocked: string
51  procs: Proc[]
52}
53
54export const register: Register = (on, options) => {
55  const asList = (v: unknown): string[] => (Array.isArray(v) ? v.map(String) : typeof v === 'string' ? v.split(/[\n,]/) : [])
56  const watch = asList(options.watchPaths).map(x => x.trim()).filter(Boolean)
57  const depth = Math.min(12, Math.max(1, Math.floor(Number(options.searchDepth) || 6)))
58  const clampRows = (n: number) => Math.min(ROWS_MAX, Math.max(0, Math.floor(n) || 0))
59  const configRows = clampRows(Number(options.timelineRows ?? 8))
60  const maxRuns = Math.min(12, Math.max(1, Math.floor(Number(options.maxSessions) || 3)))
61  const maxMin = Math.max(1, Math.floor((Number(options.maxAgeHours) || 6) * 60))
62  const data = new Map<string, Data>()
63  const agents = new Map<string, Run['agent']>()
64  const results = new Map<string, { status: string; touched: number | null; model: string; started: number; finishedAt: number }>()
65  const finished = new Set<string>()
66  const announced = new Set<string>()
67  let isPolling = false
68  let hasOpened = false
69  let isPaneOpen = false
70  let tick = 0
71  let lastSig = ''
72  let cands: Cand[] = []
73  // run folders whose log is no longer there; a search that finds one again brings it back
74  const gone = new Set<string>()
75  // repository root per folder (null when the folder is not in a git work tree)
76  const gitTops = new Map<string, string | null>()
77
78  on('session.start', async ($, e, next) => {
79    await $.command.register({
80      name: 'delegate-watch',
81      description: 'Open the live delegate pane, or pause / resume the watcher',
82      argumentHint: 'pause | resume',
83    })
84    await update($, runs, () => [])
85    await update($, events, () => [])
86    await update($, selected, () => null)
87    await update($, scroll, () => 0)
88    await update($, paused, () => false)
89    await update($, expanded, () => [])
90    await update($, beat, () => FRESH_BEAT)
91    await update($, searched, () => [])
92    const firstCwd = await $.session.cwd()
93    await update($, startCwd, prev => prev || firstCwd)
94    if ((await $.store.get('paused')) === true) await update($, paused, () => true)
95    const savedRows = await $.store.get('timelineRows')
96    await update($, rowsPref, () => (typeof savedRows === 'number' ? clampRows(savedRows) : configRows))
97
98    // every host call goes through here: one that never answers rejects after `ms` instead of holding the poll forever
99    const call = <T,>(label: string, work: Promise<T>, ms = CALL_MS): Promise<T> => withTimeout((n, fn) => $.clock.after(n, fn), work, ms, label)
100    // a process gets its own timeout first, the guard only catches a call that does not even honour that
101    const exec = (label: string, argv: string[], init: { cwd?: string; timeoutMs: number }) =>
102      call(label, $.process.run(argv, init), init.timeoutMs + PROC_GUARD_MS)
103    // the repository root of a folder, asked once per folder; null outside a work tree or when git fails
104    const topOf = async (dir: string): Promise<string | null> => {
105      if (gitTops.has(dir)) return gitTops.get(dir) ?? null
106      const ran = await exec('git root', ['git', '-C', dir, 'rev-parse', '--show-toplevel'], { timeoutMs: 3000 }).catch(() => null)
107      const top = ran?.stdout.trim() || null
108      gitTops.set(dir, top)
109      return top
110    }
111
112    // records how a poll ended; best effort, it must never throw or it would defeat the point of a heartbeat
113    const recordBeat = async (failure: unknown): Promise<void> => {
114      try {
115        const at = await call('clock', $.clock.now()).catch(() => Date.now())
116        await call('heartbeat', update($, beat, prev => nextBeat({ ...FRESH_BEAT, ...prev }, failure, at)))
117      } catch {
118        // nothing left to report to
119      }
120    }
121
122    // while the pane is open its age label has to keep counting even if the poll is the thing that stopped
123    $.clock.every(REDRAW_MS, () => {
124      if (isPaneOpen) $.ui.invalidate('ui.render')
125    })
126
127    $.clock.every(POLL_MS, async () => {
128      if (isPolling) return
129      isPolling = true
130      tick += 1
131      let failure: unknown = null
132      let isCounted = true
133      try {
134        if (await call('paused', read($, paused))) {
135          isCounted = false
136          return
137        }
138        const cwd = await call('cwd', $.session.cwd())
139        const tmp = ((await call('env', $.env.get('TMPDIR'))) ?? '/tmp').replace(/\/$/, '')
140        const wasLive = (await call('runs', read($, runs))).some(x => !x.isDone)
141        if (!wasLive && tick % IDLE_EVERY !== 0) return
142        const now = await call('clock', $.clock.now())
143        const isSlow = tick % SLOW_EVERY === 0
144
145        // discovery: one `find` for every run folder touched in the last 6 hours, refreshed every few ticks
146        if (cands.length === 0 || tick % FIND_EVERY === 0 || tick <= 1) {
147          const home = (await call('env', $.env.get('HOME'))) ?? ''
148          // relative paths are resolved against the repository root and the start cwd too: the live cwd moves
149          const anchors = anchorsOf(await call('start cwd', read($, startCwd)), cwd, await topOf(cwd))
150          const roots = resolveRoots(watch.length > 0 ? watch : ['$TMPDIR/delegate-relay', '.orchestrator', '.superpowers'], anchors, tmp, home)
151          await call('searched', update($, searched, () => roots))
152          // a failing `find` is not "nothing running": it throws so the heartbeat shows it
153          const ran = await exec(
154            'find',
155            ['sh', '-c', `find ${roots.map(x => `'${x.replace(/'/g, '')}'`).join(' ')} -maxdepth ${depth} \\( -name events.jsonl -o -name agy.log \\) -mmin -${maxMin} -print0 2>/dev/null | ${STAT} 2>/dev/null`],
156            { timeoutMs: 8000 },
157          )
158          const seenDirs = new Set<string>()
159          const fresh: Cand[] = []
160          for (const l of ran.stdout.split('\n')) {
161            const sp = l.indexOf(' ')
162            const path = l.slice(sp + 1)
163            const dir = path.slice(0, path.lastIndexOf('/'))
164            if (sp < 1 || dir === '' || seenDirs.has(dir)) continue
165            seenDirs.add(dir)
166            fresh.push({ dir, name: dir.slice(dir.lastIndexOf('/') + 1), mtime: Number(l.slice(0, sp)) * 1000 })
167          }
168          for (const c of fresh) gone.delete(c.dir)
169          cands = mergeCands(cands, fresh, gone, now - maxMin * 60_000)
170        }
171
172        const found: Run[] = []
173        for (const c of cands.slice(0, maxRuns)) {
174          const files = await orElse(call('list', $.fs.list(c.dir)), [])
175          const names = files.map(f => f.name)
176          const logName = names.includes('agy.log') ? 'agy.log' : names.includes('events.jsonl') ? 'events.jsonl' : null
177          if (logName === null) {
178            // the folder or its log went away: stop keeping it until a search finds it again
179            gone.add(c.dir)
180            continue
181          }
182          const log = files.find(f => f.name === logName)!
183          c.mtime = log.mtimeMs
184          const brief = files.find(f => f.name === 'brief.txt')
185          let agent: Run['agent'] = agents.get(c.dir) ?? (logName === 'agy.log' ? 'agy' : 'unknown')
186          if (agent === 'unknown' && log.size > 0) {
187            const head = await exec('head', ['head', '-c', '1500', `${c.dir}/events.jsonl`], { timeoutMs: 3000 }).catch(() => null)
188            agent = agentOf(names, head?.stdout ?? '')
189            if (agent !== 'unknown') agents.set(c.dir, agent)
190          }
191          let status = 'running'
192          let model = ''
193          let started = 0
194          let finishedAt = 0
195          let touched: number | null = null
196          let isDone = false
197          if (names.includes('result.json')) {
198            isDone = true
199            let hit = results.get(c.dir)
200            if (!hit) {
201              try {
202                const result = JSON.parse(await call('read result', $.fs.read(`${c.dir}/result.json`)))
203                hit = {
204                  status: String(result.status ?? 'done'),
205                  touched: Array.isArray(result.touchedFiles) ? result.touchedFiles.length : null,
206                  model: String(result.resolvedModel ?? result.model ?? ''),
207                  started: Date.parse(result.startedAt ?? '') || 0,
208                  finishedAt: Date.parse(result.finishedAt ?? '') || 0,
209                }
210                results.set(c.dir, hit)
211              } catch {
212                hit = { status: 'done', touched: null, model: '', started: 0, finishedAt: 0 }
213              }
214            }
215            status = hit.status
216            touched = hit.touched
217            model = hit.model
218            started = hit.started
219            finishedAt = hit.finishedAt
220          } else if (names.includes('final.txt') && agent !== 'claude' && !names.includes('profile.json')) {
221            // the Claude relay (its folder alone has profile.json) creates an empty final.txt when the run starts,
222            // so only result.json ends a Claude run, also before its first event names the agent
223            isDone = true
224            status = 'finished'
225          } else if (now - log.mtimeMs > STALE_MS && agent !== 'agy') {
226            status = `stalled ${ago(now - log.mtimeMs)}`
227          }
228          const d = data.get(c.dir) ?? {
229            offset: 0, carry: '', evs: [], totals: { tools: 0, cost: 0, turns: 0, lastTurn: 0, think: '' }, snap: null, note: '', blocked: '', procs: [],
230          }
231          data.set(c.dir, d)
232          found.push({
233            dir: c.dir,
234            name: c.name,
235            agent,
236            model,
237            finishedAt,
238            startedAt: started || (brief?.mtimeMs ?? startOf(c.name) ?? log.mtimeMs),
239            updatedAt: log.mtimeMs,
240            status,
241            isDone,
242            touched,
243            tools: d.totals.tools,
244            cost: d.totals.cost,
245            note: d.note,
246            turns: d.totals.turns,
247            lastTurn: d.totals.lastTurn,
248            blocked: d.blocked,
249            procs: d.procs,
250          })
251        }
252
253        if (gone.size > 0) cands = cands.filter(c => !gone.has(c.dir))
254
255        // pick the run to show: the user's choice, else the newest running, else the newest
256        let sel = await call('selected', read($, selected))
257        if (!found.some(r => r.dir === sel)) {
258          sel = (found.find(r => !r.isDone) ?? found[0])?.dir ?? null
259          await call('selected', update($, selected, () => sel))
260          await call('scroll', update($, scroll, () => 0))
261        }
262
263        // only the shown run is read, and only the bytes added since the last tick
264        const run = found.find(r => r.dir === sel)
265        if (run) {
266          const d = data.get(run.dir)!
267          const logFile = run.agent === 'agy' ? 'agy.log' : 'events.jsonl'
268          const files = await orElse(call('list', $.fs.list(run.dir)), [])
269          const size = files.find(f => f.name === logFile)?.size ?? 0
270          if (size > d.offset) {
271            const from = Math.max(d.offset, size - MAX_READ)
272            try {
273              const ran = await exec('tail', ['tail', '-c', `+${from + 1}`, `${run.dir}/${logFile}`], { timeoutMs: 8000 })
274              let text = d.carry + ran.stdout
275              if (d.offset === 0 && from > 0) text = text.slice(text.indexOf('\n') + 1)
276              const cut = text.lastIndexOf('\n')
277              d.carry = cut >= 0 ? text.slice(cut + 1) : text
278              const lines = cut >= 0 ? text.slice(0, cut).split('\n') : []
279              if (run.agent === 'agy') parseAgyLines(lines, d.evs, d.totals, new Date(now).getFullYear())
280              else parseLines(lines, d.evs, d.totals, now)
281              d.offset = size
282              d.note = ''
283            } catch {
284              d.note = 'cannot read the log here'
285            }
286          }
287          if (run.agent === 'agy' && (isSlow || d.snap === null)) {
288            // the run's own repository, not the live cwd (which may be a subfolder or another checkout)
289            const repo = (await topOf(run.dir)) ?? cwd
290            try {
291              if (d.snap === null || !run.isDone) {
292                const ran = await exec(
293                  'git',
294                  ['sh', '-c', `git ls-files -m -o --exclude-standard -z | ${STAT} 2>/dev/null`],
295                  { cwd: repo, timeoutMs: 8000 },
296                )
297                const snap = parseStat(ran.stdout)
298                d.evs.push(...editsSince(d.snap, snap, run.startedAt, ''))
299                d.snap = snap
300              }
301              if (!run.isDone && !run.dir.includes("'")) {
302                const ps = await exec(
303                  'ps',
304                  ['sh', '-c', `pgrep -f '${run.dir}/[a]gy.log'; echo @@; ps -axo pid=,ppid=,etime=,command=`],
305                  { timeoutMs: 5000 },
306                )
307                d.procs = childrenOf(ps.stdout)
308                d.blocked = blockedOf(await orElse(call('read stderr', $.fs.read(`${run.dir}/stderr.txt`)), ''))
309              } else {
310                d.procs = []
311                d.blocked = ''
312              }
313            } catch {
314              d.note = 'git or ps unavailable here'
315            }
316          }
317          if (d.evs.length > MAX_EVENTS) d.evs.splice(0, d.evs.length - MAX_EVENTS)
318          run.tools = run.agent === 'agy' ? new Set(d.evs.filter(x => x.kind === 'file').map(x => x.text)).size : d.totals.tools
319          run.cost = d.totals.cost
320          run.note = d.note
321          run.turns = d.totals.turns
322          run.lastTurn = d.totals.lastTurn
323          run.blocked = d.blocked
324          run.procs = d.procs
325        }
326
327        const sig = `${sel}|${run ? data.get(run.dir)!.evs.length : 0}|${run?.blocked}|${run?.procs.map(x => x.age + x.cmd).join(',')}|${found.map(r => r.dir + r.status + r.updatedAt).join(',')}`
328        if (sig !== lastSig) {
329          await call('write runs', update($, runs, () => found))
330          // no run shown: clear the timeline too, so an empty run list never sits above an old timeline
331          const list = run ? data.get(run.dir)!.evs.slice().sort((a, b) => a.t - b.t) : []
332          await call('write events', update($, events, () => list))
333          // remembered only once both writes landed, so a failed write is retried on the next tick
334          lastSig = sig
335        }
336
337        for (const r of found) {
338          if (!r.isDone && !finished.has(r.dir) && !announced.has(r.dir)) {
339            announced.add(r.dir)
340            hasOpened = true
341            isPaneOpen = true
342            void $.ui.open({ id: PANE, title: 'Delegates' }).then(o => {
343              if (!o.isPlaced) $.ui.toast(`delegate-watch: run started, type /delegate-watch to open the pane (${o.reason})`)
344            })
345          }
346          if (r.isDone && !finished.has(r.dir)) {
347            finished.add(r.dir)
348            if (hasOpened) $.ui.toast(`${r.agent} ${r.name}: ${r.status}`)
349          }
350        }
351        const live = found.filter(r => !r.isDone).length
352        $.ui.status(live > 0 ? `${live} delegate${live > 1 ? 's' : ''} running` : undefined)
353      } catch (err) {
354        // whatever broke (a hung host call, a bad read) ends this poll only; the next tick starts clean
355        failure = err
356      } finally {
357        isPolling = false
358        if (isCounted) await recordBeat(failure)
359      }
360    })
361    return next(e)
362  })
363
364  on('command.run', { command: 'delegate-watch' }, async ($, e) => {
365    const arg = e.args.trim().toLowerCase()
366    if (arg === 'pause' || arg === 'stop') {
367      await update($, paused, () => true)
368      await $.store.set('paused', true)
369      $.ui.status(undefined)
370      return { text: 'Delegate watcher paused. It reads no files until you run /delegate-watch resume.' }
371    }
372    if (arg === 'resume' || arg === 'start') {
373      await update($, paused, () => false)
374      await $.store.set('paused', false)
375      lastSig = ''
376      cands = []
377      gone.clear()
378      gitTops.clear()
379      isPaneOpen = true
380      await $.ui.open({ id: PANE, title: 'Delegates' })
381      return { text: 'Delegate watcher resumed.' }
382    }
383    isPaneOpen = true
384    const opened = await $.ui.open({ id: PANE, title: 'Delegates' })
385    return { text: opened.isPlaced ? 'Delegates pane opened.' : `Delegates pane is open but not drawn: ${opened.reason}` }
386  })
387
388  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
389    const { Box, Text, Button } = $.ui.resolve(e)
390    const list: Run[] = (await read($, runs)).map((x: Partial<Run>) => ({
391      dir: String(x.dir ?? ''), name: String(x.name ?? ''), agent: x.agent ?? 'unknown', model: x.model ?? '',
392      startedAt: x.startedAt ?? 0, finishedAt: x.finishedAt ?? 0, updatedAt: x.updatedAt ?? 0,
393      status: String(x.status ?? 'running'), isDone: x.isDone ?? false, touched: x.touched ?? null,
394      tools: x.tools ?? 0, cost: x.cost ?? 0, note: x.note ?? '', turns: x.turns ?? 0, lastTurn: x.lastTurn ?? 0,
395      blocked: x.blocked ?? '',
396      procs: (Array.isArray(x.procs) ? x.procs : []).filter(
397        (q): q is Proc => typeof q === 'object' && q !== null && typeof q.age === 'string' && typeof q.cmd === 'string',
398      ),
399    }))
400    const sel = await read($, selected)
401    const all: Ev[] = (await read($, events))
402      .filter((x: Partial<Ev>) => typeof x === 'object' && x !== null && typeof x.text === 'string')
403      .map((x: Ev) => ({ ...x, tag: typeof x.tag === 'string' ? x.tag : x.kind }))
404    const back = await read($, scroll)
405    const f = await read($, filter)
406    const isPaused = await read($, paused)
407    const hint = searchedHint(await read($, searched))
408    const now = await $.clock.now()
409    const pulse = beatLabel({ ...FRESH_BEAT, ...(await read($, beat)) }, now)
410    const run = list.find(r => r.dir === sel)
411    const isAgy = run?.agent === 'agy'
412    const open = new Set(await read($, expanded))
413    const flip = (id: string) => update($, expanded, l => (l.includes(id) ? [] : [id]))
414    const stored = await read($, rowsPref)
415    const timelineRows = stored < 0 ? configRows : stored
416    const setRows = (n: number) => {
417      const v = clampRows(n)
418      void update($, rowsPref, () => v)
419      void $.store.set('timelineRows', v)
420    }
421    const keep = (x: Ev) =>
422      f === 'all' || (f === 'tools' ? x.kind === 'tool' || x.kind === 'file' || x.kind === 'err' : f === 'say' ? x.kind === 'say' || x.kind === 'think' : x.kind === 'turn')
423    const shown = all.filter(keep)
424    const isLive = back === 0
425    const end = isLive ? shown.length : Math.min(back, shown.length)
426    const mix = mixOf(all)
427    const idOf = (x: Ev) => `${x.t}|${x.kind}|${x.text.slice(0, 48)}`
428    const used = topLines({
429      hasRuns: list.length > 0, hasRun: run !== undefined, isDone: run?.isDone ?? true, isAgy, hasBlocked: Boolean(run?.blocked),
430      activeProcs: run?.procs.filter(x => !x.isHelper).length ?? 0, helperProcs: run?.procs.filter(x => x.isHelper).length ?? 0,
431      hasNote: Boolean(run?.note), mixTags: mix.length, hasSpark: all.length > 1,
432    })
433    const cols = e.viewport?.columns ?? 60
434    const budget = (e.viewport?.rows ?? 40) - used - 1
435    const textCols = cols - 44
436    const rows = timelineRows > 0 ? timelineRows : fitRows(shown, end, budget, open, idOf, textCols)
437    const view = shown.slice(Math.max(0, end - rows), end)
438    const step = Math.max(1, Math.floor(rows / 2))
439    const brand = { agy: '#60a5fa', claude: '#d97757', cursor: '#94a3b8', opencode: '#34d399', unknown: 'gray' }
440    const tone = !run
441      ? 'gray'
442      : run.status === 'running' || run.status.startsWith('stalled')
443        ? 'yellow'
444        : GOOD.includes(run.status)
445          ? 'green'
446          : 'red'
447    const mark = (r: Run) => (!r.isDone ? '●' : GOOD.includes(r.status) ? '✓' : '✗')
448    const pick = (r: Run) => {
449      void update($, selected, () => r.dir)
450      void update($, scroll, () => 0)
451      void update($, events, () => [])
452      void update($, expanded, () => [])
453    }
454    const tab = (label: string, value: Filter) => (
455      <Button key={value} variant={f === value ? 'primary' : 'secondary'} onPress={() => {
456        void update($, scroll, () => 0)
457        void update($, filter, () => value)
458      }}>
459        {label}
460      </Button>
461    )
462    const tile = (label: string, value: string, color?: string) => (
463      <Box key={label} flexDirection="column" borderStyle="round" borderColor="gray" borderDimColor paddingX={1} minWidth={11}>
464        <Text dimColor>{label}</Text>
465        <Text bold color={color}>{value}</Text>
466      </Box>
467    )
468    const badge = (tag: string, color: string) => (
469      <Text bold inverse color={color}>{` ${tag.toUpperCase().slice(0, 6).padEnd(6)} `}</Text>
470    )
471    const toggle = async () => {
472      const next = !isPaused
473      await update($, paused, () => next)
474      await $.store.set('paused', next)
475      if (next) $.ui.status(undefined)
476      else {
477        lastSig = ''
478        cands = []
479        gone.clear()
480        gitTops.clear()
481      }
482    }
483    const mixTotal = mix.reduce((n, [, c]) => n + c, 0)
484    const idleFor = run && run.lastTurn > 0 ? ago(now - run.lastTurn) : null
485    const span = (run ? (run.isDone && run.finishedAt > 0 ? run.finishedAt : run.isDone ? run.updatedAt : now) : now) - (run?.startedAt ?? now)
486
487    return (
488      <Box flexDirection="column" gap={1}>
489        <Box justifyContent="space-between">
490          <Text bold color={isPaused ? 'yellow' : 'green'}>{isPaused ? '⏸ Watcher paused, not reading any files' : '● Watching delegates'}</Text>
491          <Box gap={1} flexShrink={1} minWidth={0}>
492            {isPaused ? null : <Text color={pulse.color} bold={pulse.isWarn} wrap="truncate-end">{pulse.text}</Text>}
493            <Button key="pause" variant={isPaused ? 'primary' : 'secondary'} onPress={toggle}>{isPaused ? 'Resume' : 'Pause'}</Button>
494          </Box>
495        </Box>
496
497        {list.length === 0 && (
498          <Box flexDirection="column" borderStyle="round" borderColor="gray" paddingX={2} paddingY={1}>
499            <Text bold>No delegate runs yet</Text>
500            <Text dimColor>Dispatch one with /agy-delegate, /claude-delegate, /cursor-delegate or /opencode-delegate and it shows up here.</Text>
501            {hint === null ? null : <Text dimColor>{hint}</Text>}
502          </Box>
503        )}
504
505        <Box gap={1} flexWrap="wrap">
506          {list.map(r => (
507            <Button key={r.dir} variant={r.dir === sel ? 'primary' : 'secondary'} onPress={() => pick(r)}>
508              {`${mark(r)} ${r.agent} · ${r.name}`}
509            </Button>
510          ))}
511        </Box>
512
513        {run && (
514          <Box flexDirection="column" borderStyle="round" borderColor={tone} paddingX={2} paddingY={1} gap={1}>
515            <Box justifyContent="space-between">
516              <Box gap={1}>
517                {badge(run.agent, brand[run.agent])}
518                <Text bold>{run.name}</Text>
519                {run.model ? <Text dimColor>{run.model}</Text> : null}
520              </Box>
521              <Text bold inverse color={tone}>{` ${mark(run)} ${run.status.toUpperCase()} `}</Text>
522            </Box>
523
524            <Box gap={1} flexWrap="wrap">
525              {tile('ELAPSED', ago(span))}
526              {isAgy ? tile('MODEL TURNS', String(run.turns)) : tile('TOOL CALLS', String(run.tools))}
527              {isAgy ? tile('FILES EDITED', String(run.tools)) : tile('COST', run.cost > 0 ? `$${run.cost.toFixed(2)}` : '—')}
528              {run.touched !== null ? tile('IN DIFF', String(run.touched)) : null}
529            </Box>
530
531            {!run.isDone && isAgy && (
532              <Box flexDirection="column">
533                {run.blocked ? (
534                  <Text color="yellow" bold>⏸ Idle · blocked on a background command</Text>
535                ) : (
536                  <Text color="green" bold>{idleFor ? `● Model active ${idleFor} ago` : '○ Waiting for the first model turn'}</Text>
537                )}
538                {run.blocked ? <Text dimColor>{run.blocked}</Text> : null}
539                {run.procs.filter(x => !x.isHelper).length === 0 && !run.blocked ? (
540                  <Text dimColor>{'  '}no command running, the model is thinking</Text>
541                ) : null}
542                {run.procs.filter(x => !x.isHelper).map((p, i) => (
543                  <Box key={`p${i}`} gap={1}>
544                    <Text color="green">{'  ▸'}</Text>
545                    <Text dimColor>{p.age.padStart(6)}</Text>
546                    <Text wrap="truncate-end">{p.cmd}</Text>
547                  </Box>
548                ))}
549                {run.procs.filter(x => x.isHelper).map((p, i) => (
550                  <Box key={`h${i}`} gap={1}>
551                    <Text dimColor>{'  ·'}</Text>
552                    <Text dimColor>{p.age.padStart(6)}</Text>
553                    <Text dimColor wrap="truncate-end">{p.cmd} (helper)</Text>
554                  </Box>
555                ))}
556              </Box>
557            )}
558            {!run.isDone && !isAgy && <Text color="green" bold>● Log updated {ago(now - run.updatedAt)} ago</Text>}
559            {run.note ? <Text color="red">{run.note}</Text> : null}
560
561            {mixTotal > 0 && (
562              <Box flexDirection="column">
563                <Box width="100%" height={1} overflow="hidden">
564                  {mix.map(([tag, n]) => (
565                    <Box key={tag} flexGrow={weightOf(n)} minWidth={1} height={1} backgroundColor={tintOf(tag)} />
566                  ))}
567                </Box>
568                <Box gap={2} flexWrap="wrap">
569                  {mix.map(([tag, n]) => (
570                    <Text key={tag}><Text color={tintOf(tag)}>■</Text> {tag} <Text dimColor>{n} · {Math.round((n / mixTotal) * 100)}%</Text></Text>
571                  ))}
572                </Box>
573              </Box>
574            )}
575            {all.length > 1 && (
576              <Box gap={1}>
577                <Text dimColor>activity, last 30 min</Text>
578                <Text color={tone}>{spark(all, now, 30)}</Text>
579              </Box>
580            )}
581          </Box>
582        )}
583
584        <Box gap={1} flexWrap="wrap">
585          {tab('All', 'all')}
586          {isAgy ? tab('Turns', 'turns') : tab('Tools', 'tools')}
587          {isAgy ? tab('Edits', 'tools') : tab('Thoughts', 'say')}
588          <Button key="older" onPress={() => update($, scroll, () => Math.max(Math.min(rows, shown.length), end - step))}>↑</Button>
589          <Button key="newer" onPress={() => update($, scroll, () => (isLive || end + step >= shown.length ? 0 : end + step))}>↓</Button>
590          <Button key="live" variant={isLive ? 'primary' : 'secondary'} onPress={() => update($, scroll, () => 0)}>
591            {isLive ? '● Live' : shown.length > end ? `Jump to live (+${shown.length - end})` : 'Jump to live'}
592          </Button>
593          <Box gap={1}>
594            <Button key="rows-less" onPress={() => setRows(timelineRows - ROWS_STEP)}>−</Button>
595            <Text dimColor>{timelineRows > 0 ? `${timelineRows} rows` : 'auto rows'}</Text>
596            <Button key="rows-more" onPress={() => setRows(timelineRows + ROWS_STEP)}>+</Button>
597          </Box>
598        </Box>
599
600        <Box flexDirection="column">
601          <Box marginBottom={1}>
602          <Text bold dimColor>
603            TIMELINE{shown.length === 0 ? '  ·  no events yet' : `  ·  ${Math.max(1, end - view.length + 1)}–${end} of ${shown.length}`}
604          </Text>
605          </Box>
606          {view.map((x, i) => {
607            const isPath = x.kind === 'tool' || x.kind === 'file'
608            const { dir, name } = isPath ? splitPath(x.text) : { dir: '', name: x.text }
609            const color = x.kind === 'err' ? 'red' : tintOf(x.tag)
610            const isProse = x.kind === 'say' || x.kind === 'think' || x.kind === 'turn'
611            const id = idOf(x)
612            const isOpen = open.has(id)
613            const isLong = isProse && (x.text.length > 90 || x.text.includes('\n'))
614            return (
615              <Box key={`e${i}`} gap={1} marginTop={i === 0 ? 0 : 0}>
616                <Box width={e.surface === 'terminal' ? 18 : 13} flexShrink={0}>
617                  <Text dimColor>{x.t > 0 ? clock(x.t) : '--:--:--'}{' '}</Text>
618                  <Text color={color}>({run && x.t > 0 ? rel(x.t - run.startedAt) : '--:--'})</Text>
619                </Box>
620                <Text color={color} bold>▌</Text>
621                <Box width={10} flexShrink={0}>
622                  <Text color={color} bold>{glyph(x.kind)} </Text>
623                  <Text bold inverse color={color}>{` ${x.tag.toUpperCase().slice(0, 6).padEnd(6)} `}</Text>
624                </Box>
625                <Box width={3} flexShrink={0}>
626                  {isLong ? <Button key={`x${i}`} onPress={() => flip(id)}>{isOpen ? '▾' : '▸'}</Button> : null}
627                </Box>
628                <Box flexDirection="column" flexGrow={1} flexShrink={1} minWidth={0}>
629                  <Text wrap={isProse && (isOpen || !isLong) ? 'wrap' : 'truncate-end'} bold={isPath} italic={x.kind === 'think'} dimColor={isProse} color={x.kind === 'err' ? 'red' : undefined}>
630                    {isOpen && timelineRows === 0 ? fitText(name, expandCap(budget), textCols) : name}
631                  </Text>
632                  {dir ? <Text dimColor wrap="truncate-middle">{dir}</Text> : null}
633                </Box>
634              </Box>
635            )
636          })}
637        </Box>
638      </Box>
639    )
640  })
641}
642
hooks/guard.ts 52 lines
1import type { Beat } from '../types'
2
3// the one timer shape the guard needs, so it can be tested without the engine (`$.clock.after` fits)
4export type After = (ms: number, fn: () => void) => { cancel: () => void }
5
6const TIMEOUT = 'TimeoutError'
7const ERROR_WIDTH = 120
8
9// settles like `work`, but rejects with a TimeoutError once `ms` pass first, so one host call that never answers cannot hold the poll
10export const withTimeout = <T>(after: After, work: Promise<T>, ms: number, label: string): Promise<T> =>
11  new Promise<T>((resolve, reject) => {
12    const timer = after(ms, () => {
13      const err = new Error(`${label} timed out after ${Math.round(ms / 1000)}s`)
14      err.name = TIMEOUT
15      reject(err)
16    })
17    work.then(
18      v => {
19        timer.cancel()
20        resolve(v)
21      },
22      err => {
23        timer.cancel()
24        reject(err)
25      },
26    )
27  })
28
29export const isTimeout = (err: unknown): boolean => err instanceof Error && err.name === TIMEOUT
30
31// a fallback for a call that may fail (a missing file, a folder that vanished), but never for a call that hung: that must reach the heartbeat
32export const orElse = <T>(work: Promise<T>, fallback: T): Promise<T> =>
33  work.catch(err => {
34    if (isTimeout(err)) throw err
35    return fallback
36  })
37
38// one line of text for any thrown value
39export const errorText = (err: unknown): string => {
40  const raw = err instanceof Error ? err.message : String(err)
41  const one = raw.replace(/\s+/g, ' ').trim()
42  return one.length > ERROR_WIDTH ? `${one.slice(0, ERROR_WIDTH - 1)}…` : one
43}
44
45export const FRESH_BEAT: Beat = { okAt: 0, ticks: 0, errors: 0, error: '', errorAt: 0 }
46
47// the heartbeat after one poll ended at `at`: `failure` is what it threw, or null when it completed
48export const nextBeat = (prev: Beat, failure: unknown, at: number): Beat =>
49  failure === null
50    ? { ...prev, ticks: prev.ticks + 1, okAt: at }
51    : { ...prev, ticks: prev.ticks + 1, errors: prev.errors + 1, errorAt: at, error: errorText(failure) }
52
hooks/summarize.ts 361 lines
1import type { Beat, Ev, Run } from '../types'
2
3const WIDTH = 200
4export const MAX_EVENTS = 4000
5
6const clip = (text: string): string => {
7  const one = text.replace(/\s+/g, ' ').trim()
8  return one.length > WIDTH ? `${one.slice(0, WIDTH - 1)}…` : one
9}
10
11// messages keep their full text (bounded) so the pane can expand them; the row itself truncates
12const clipLong = (text: string): string => {
13  const one = text.replace(/\s+/g, ' ').trim()
14  return one.length > 2000 ? `${one.slice(0, 1999)}…` : one
15}
16
17const detailOf = (input: unknown): string => {
18  if (typeof input !== 'object' || input === null) return ''
19  const o = input as Record<string, any>
20  const pick = o.filePath ?? o.path ?? o.file_path ?? o.command ?? o.pattern ?? o.query ?? o.description ?? o.taskId
21  return typeof pick === 'string' ? pick : ''
22}
23
24// `names` maps a Claude tool_use id to its tool name, so a failed tool_result can name the tool; created on first use
25export type Totals = { tools: number; cost: number; turns: number; lastTurn: number; think: string; names?: Record<string, string> }
26
27const shorten = (p: string): string => {
28  const rel = p.replace(/^\/Users\/[^/]+\/(?:[^/]+\/)*?(?=(?:lib|test|src|backend|frontend|docs|app|packages|assets|scripts|tests)\/)/, '')
29  if (rel !== p) return rel
30  const parts = p.split('/')
31  return parts.length > 4 ? `…/${parts.slice(-3).join('/')}` : p
32}
33
34const firstLine = (text: string): string => clip((text.split('\n')[0] ?? '').trim())
35
36// one Claude Code stream-json `assistant` message: every text, non-empty thought and tool call becomes a row
37const parseClaudeAssistant = (content: any[], t: number, out: Ev[], totals: Totals): void => {
38  for (const p of content) {
39    if (p?.type === 'text' && typeof p.text === 'string' && p.text.trim()) {
40      out.push({ t, kind: 'say', tag: 'say', text: clipLong(p.text) })
41    } else if (p?.type === 'thinking' && typeof p.thinking === 'string' && p.thinking.trim()) {
42      out.push({ t, kind: 'think', tag: 'think', text: clipLong(p.thinking) })
43    } else if (p?.type === 'tool_use' && typeof p.name === 'string') {
44      if (typeof p.id === 'string') (totals.names ??= {})[p.id] = p.name
45      totals.tools += 1
46      out.push({ t, kind: 'tool', tag: p.name, text: shorten(firstLine(detailOf(p.input))) })
47    }
48  }
49}
50
51// one Claude Code stream-json `user` message: a failed tool result becomes an error row named after its tool
52const parseClaudeUser = (content: any[], t: number, out: Ev[], totals: Totals): void => {
53  for (const p of content) {
54    if (p?.type !== 'tool_result' || p.is_error !== true) continue
55    const body = typeof p.content === 'string' ? p.content : Array.isArray(p.content) ? String(p.content.find((c: any) => c?.type === 'text')?.text ?? '') : ''
56    out.push({ t, kind: 'err', tag: totals.names?.[p.tool_use_id] ?? 'tool', text: firstLine(body) })
57  }
58}
59
60// `fallbackT` stamps events whose log line carries no time (Claude Code stream-json has none): the caller passes the read time
61export const parseLines = (lines: string[], out: Ev[], totals: Totals, fallbackT = 0): void => {
62  for (const raw of lines) {
63    if (!raw.startsWith('{')) continue
64    let ev: any
65    try {
66      ev = JSON.parse(raw)
67    } catch {
68      continue
69    }
70    const t = Number(ev.timestamp_ms ?? ev.timestamp ?? 0) || fallbackT
71    if (ev.type === 'step_finish' && typeof ev.part?.cost === 'number') {
72      totals.cost += ev.part.cost
73    } else if (ev.type === 'tool_use' && ev.part) {
74      const st = ev.part.state
75      const detail = detailOf(st?.input)
76      if (st?.status === 'error') {
77        out.push({ t, kind: 'err', tag: String(ev.part.tool), text: clip(`${shorten(detail)} ${String(st.error ?? '')}`) })
78      } else if (st?.status === 'completed') {
79        totals.tools += 1
80        out.push({ t, kind: 'tool', tag: String(ev.part.tool), text: shorten(firstLine(detail)) })
81      }
82    } else if (ev.type === 'text' && typeof ev.part?.text === 'string' && ev.part.text.trim()) {
83      out.push({ t, kind: 'say', tag: 'say', text: clipLong(ev.part.text) })
84    } else if (ev.type === 'assistant' && Array.isArray(ev.message?.content)) {
85      // cursor-agent sends text parts only; Claude Code also sends its tool calls and thoughts here
86      parseClaudeAssistant(ev.message.content, t, out, totals)
87    } else if (ev.type === 'user' && Array.isArray(ev.message?.content)) {
88      parseClaudeUser(ev.message.content, t, out, totals)
89    } else if (ev.type === 'result' && typeof ev.total_cost_usd === 'number') {
90      // Claude Code's final event carries the whole run's cost, not an increment
91      totals.cost = ev.total_cost_usd
92    } else if (ev.type === 'thinking') {
93      if (ev.subtype === 'delta' && typeof ev.text === 'string') totals.think += ev.text
94      if (ev.subtype === 'completed') {
95        if (totals.think.trim()) out.push({ t, kind: 'think', tag: 'think', text: clipLong(totals.think) })
96        totals.think = ''
97      }
98    } else if (ev.type === 'tool_call' && ev.subtype === 'started' && ev.tool_call) {
99      const key = Object.keys(ev.tool_call)[0] ?? 'tool'
100      const args = ev.tool_call[key]?.args
101      const detail = detailOf(args) || (typeof args?.description === 'string' ? args.description : '')
102      totals.tools += 1
103      out.push({ t, kind: 'tool', tag: key.replace(/ToolCall$/, ''), text: shorten(firstLine(detail)) })
104    }
105  }
106}
107
108export const agentOf = (names: string[], head: string): Run['agent'] => {
109  if (names.includes('agy.log')) return 'agy'
110  // Claude Code's stream opens with hook events or its init line; both are checked before cursor's `session_id`
111  if (head.includes('"claude_code_version"') || head.includes('"hook_event"')) return 'claude'
112  if (head.includes('"session_id"')) return 'cursor'
113  if (head.includes('"sessionID"')) return 'opencode'
114  return 'unknown'
115}
116
117const START = /-(\d{4}-\d{2}-\d{2})T(\d{2})-(\d{2})-(\d{2})-(\d{3})Z$/
118
119export const startOf = (name: string): number | null => {
120  const m = START.exec(name)
121  return m ? Date.parse(`${m[1]}T${m[2]}:${m[3]}:${m[4]}.${m[5]}Z`) : null
122}
123
124export const ago = (ms: number): string => {
125  const s = Math.max(0, Math.round(ms / 1000))
126  if (s < 60) return `${s}s`
127  const m = Math.floor(s / 60)
128  return m < 60 ? `${m}m${String(s % 60).padStart(2, '0')}s` : `${Math.floor(m / 60)}h${String(m % 60).padStart(2, '0')}m`
129}
130
131// longer than this since the last completed poll and the watcher looks stalled (a poll normally ends every 2s, every 10s when idle)
132export const STALL_MS = 30_000
133
134export type BeatLabel = { text: string; color: string; isWarn: boolean }
135
136// the watcher's pulse as one line for the pane header
137export const beatLabel = (b: Beat, now: number): BeatLabel => {
138  if (b.errorAt > b.okAt) return { text: `⚠ poll failed ${ago(now - b.errorAt)} ago: ${b.error}`, color: 'red', isWarn: true }
139  if (b.ticks === 0 || b.okAt === 0) return { text: 'starting…', color: 'gray', isWarn: false }
140  const age = now - b.okAt
141  return age > STALL_MS ? { text: `⚠ stalled, last refresh ${ago(age)} ago`, color: 'yellow', isWarn: true } : { text: `refreshed ${ago(age)} ago`, color: 'gray', isWarn: false }
142}
143
144export const clock = (ms: number): string => (ms > 0 ? new Date(ms).toTimeString().slice(0, 8) : '        ')
145
146export type Snap = Map<string, string>
147
148// `mtime path` lines (seconds since the epoch) of the files git reports modified or untracked
149export const parseStat = (out: string): Snap => {
150  const snap: Snap = new Map()
151  for (const l of out.split('\n')) {
152    const sp = l.indexOf(' ')
153    if (sp > 0) snap.set(l.slice(sp + 1), l.slice(0, sp))
154  }
155  return snap
156}
157
158export const editsSince = (prev: Snap | null, next: Snap, since: number, root: string): Ev[] => {
159  const out: Ev[] = []
160  for (const [p, m] of next) {
161    const t = Number(m) * 1000
162    if (t >= since && prev?.get(p) !== m) out.push({ t, kind: 'file', tag: 'edit', text: p.startsWith(root) ? p.slice(root.length + 1) : p })
163  }
164  return out.sort((a, b) => a.t - b.t)
165}
166
167const GLOG = /^[IWEF](\d{2})(\d{2}) (\d{2}):(\d{2}):(\d{2})\.(\d{3})/
168
169// agy's own log: each model turn is one streamGenerateContent request
170export const parseAgyLines = (lines: string[], out: Ev[], totals: Totals, year: number): void => {
171  for (const l of lines) {
172    if (!l.includes('streamGenerateContent')) continue
173    const m = GLOG.exec(l)
174    if (!m) continue
175    const t = new Date(year, Number(m[1]) - 1, Number(m[2]), Number(m[3]), Number(m[4]), Number(m[5]), Number(m[6])).getTime()
176    totals.turns += 1
177    totals.lastTurn = t
178    out.push({ t, kind: 'turn', tag: 'turn', text: `model turn ${totals.turns}` })
179  }
180}
181
182const WAITING = /(idle; waiting.*|waiting up to.*background task.*)$/
183
184export const blockedOf = (stderr: string): string => {
185  const lines = stderr.split('\n').filter(l => l.trim())
186  const last = lines[lines.length - 1] ?? ''
187  const m = WAITING.exec(last)
188  return m ? clip(m[1] ?? '') : ''
189}
190
191export type Proc = { age: string; cmd: string; isHelper: boolean }
192
193const HELPER = /(mcp-server|language[-_]server|analysis[_-]server|VBCSCompiler|dartaotruntime|kotlin-daemon|gradle.*daemon|nodeReuse)/i
194const SHELL = /^(?:\S*\/)?(?:bash|sh|zsh|dash)(?=\s|$)/
195const PREAMBLE = [
196  /^source\s+\S+(?:\s+2>\/dev\/null)?(?:\s*\|\|\s*true)?\s*&&\s*/,
197  /^setopt\s[^&;]*?(?:\|\|\s*true)?\s*&&\s*/,
198  /^\{[^}]*\}\s*(?:>\/dev\/null\s*2>&1)?\s*(?:\|\|\s*true)?\s*&&\s*/,
199  /^eval\s+'?/,
200  /^set\s+-[a-z]+(?:\s+pipefail)?\s*[;&]+\s*/,
201  /^cd\s+\S+\s*&&\s*/,
202  /^export\s+\S+\s*[;&]+\s*/,
203]
204
205const etimeSec = (e: string): number => {
206  const [d, rest] = e.includes('-') ? e.split('-') : ['0', e]
207  const t = (rest ?? '').split(':').map(Number)
208  while (t.length < 3) t.unshift(0)
209  return Number(d) * 86400 + t[0]! * 3600 + t[1]! * 60 + t[2]!
210}
211
212const tidy = (raw: string): string => {
213  let c = raw.trim()
214  const sh = SHELL.exec(c)
215  if (sh) {
216    const rest = c.slice(sh[0].length).trim()
217    const dash = /^(?:-\w+\s+)*-c\s+([\s\S]*)$/.exec(rest)
218    if (dash) {
219      c = dash[1]!
220      for (let i = 0, prev = ''; prev !== c && i < 12; i++) {
221        prev = c
222        for (const re of PREAMBLE) c = c.replace(re, '')
223      }
224    } else if (rest) {
225      const file = rest.split(/\s+/)[0]!
226      c = `script ${file.slice(file.lastIndexOf('/') + 1)}`
227    }
228  }
229  c = c.replace(/^\/\S*\/(?=[^\s/]+(?:\s|$))/, '').replace(/\/Users\/[^/\s]+\//g, '~/')
230  return clip(c).slice(0, 110)
231}
232
233// what is running beneath the agy process, from `pgrep` pids and a `ps` listing: real commands first, long-lived helpers last
234export const childrenOf = (out: string): Proc[] => {
235  const [pidPart = '', psPart = ''] = out.split('@@\n')
236  const roots = new Set(pidPart.split('\n').map(x => x.trim()).filter(Boolean))
237  const rows = psPart.split('\n').map(l => /^\s*(\d+)\s+(\d+)\s+(\S+)\s+(.*)$/.exec(l)).filter((m): m is RegExpExecArray => m !== null)
238  const keep = new Set(roots)
239  for (let grew = true; grew; ) {
240    grew = false
241    for (const m of rows) {
242      if (keep.has(m[2]!) && !keep.has(m[1]!)) {
243        keep.add(m[1]!)
244        grew = true
245      }
246    }
247  }
248  const found = rows
249    .filter(m => keep.has(m[1]!) && !roots.has(m[1]!) && !/^\(.*\)$/.test(m[4]!.trim()))
250    .map(m => ({ sec: etimeSec(m[3]!), raw: m[4]! }))
251    .map(x => ({ ...x, cmd: tidy(x.raw) }))
252    .filter(x => x.cmd !== '' && !/^(ps|pgrep|find|sleep)\b/.test(x.cmd) && !x.raw.includes('pgrep -f'))
253    .map(x => ({ sec: x.sec, cmd: x.cmd, isHelper: HELPER.test(x.raw) }))
254  const act = found.filter(x => !x.isHelper).sort((a, b) => b.sec - a.sec).slice(0, 5)
255  const help = found.filter(x => x.isHelper).sort((a, b) => b.sec - a.sec).slice(0, 3)
256  return [...act, ...help].map(x => ({ age: ago(x.sec * 1000), cmd: x.cmd, isHelper: x.isHelper }))
257}
258
259const BARS = '▁▂▃▄▅▆▇█'
260
261// events per minute over the last `minutes`, as block characters
262export const spark = (evs: Ev[], now: number, minutes: number): string => {
263  const b = new Array<number>(minutes).fill(0)
264  for (const e of evs) {
265    const i = minutes - 1 - Math.floor((now - e.t) / 60000)
266    if (e.t > 0 && i >= 0 && i < minutes) b[i]! += 1
267  }
268  const max = Math.max(1, ...b)
269  return b.map(n => (n === 0 ? '·' : BARS[Math.min(7, Math.ceil((n / max) * 7))]!)).join('')
270}
271
272export const rel = (ms: number): string => {
273  const s = Math.max(0, Math.round(ms / 1000))
274  const mm = String(Math.floor(s / 60) % 60).padStart(2, '0')
275  const ss = String(s % 60).padStart(2, '0')
276  return s >= 3600 ? `${Math.floor(s / 3600)}:${mm}:${ss}` : `${mm}:${ss}`
277}
278
279export const glyph = (kind: string): string => ({ tool: '▸', file: '✎', turn: '◆', say: '”', think: '✦', err: '✗' })[kind] ?? '·'
280
281export const splitPath = (text: string): { dir: string; name: string } => {
282  const cut = text.lastIndexOf('/')
283  return cut > 0 ? { dir: text.slice(0, cut + 1), name: text.slice(cut + 1) } : { dir: '', name: text }
284}
285
286export const mixOf = (evs: Ev[]): [string, number][] => {
287  const c = new Map<string, number>()
288  for (const e of evs) if (e.kind === 'tool' || e.kind === 'file' || e.kind === 'turn') c.set(e.tag, (c.get(e.tag) ?? 0) + 1)
289  return [...c.entries()].sort((a, b) => b[1] - a[1]).slice(0, 6)
290}
291
292const TINT: Record<string, string> = {
293  read: 'cyan', grep: '#60a5fa', glob: '#a78bfa', ls: '#38bdf8', edit: 'yellow', write: 'yellow', patch: 'yellow', apply_patch: 'yellow',
294  shell: '#fb923c', bash: '#fb923c', turn: '#60a5fa', think: 'gray', say: 'green', await: 'gray',
295}
296export const tintOf = (tag: string): string => TINT[tag.toLowerCase()] ?? 'white'
297
298// bar weights: square-root scaled so a few huge groups do not squeeze the small ones to nothing
299export const weightOf = (n: number): number => Math.sqrt(Math.max(0, n))
300
301export type Layout = {
302  hasRuns: boolean
303  hasRun: boolean
304  isDone: boolean
305  isAgy: boolean
306  hasBlocked: boolean
307  activeProcs: number
308  helperProcs: number
309  hasNote: boolean
310  mixTags: number
311  hasSpark: boolean
312}
313
314// lines the views above the timeline occupy (root gap 1 between children), so auto rows can use exactly what is left
315export const topLines = (l: Layout): number => {
316  const parts: number[] = [1]
317  if (!l.hasRuns) parts.push(4)
318  parts.push(1)
319  if (l.hasRun) {
320    const inner: number[] = [1, 4]
321    if (!l.isDone && l.isAgy) inner.push(1 + (l.hasBlocked ? 1 : 0) + Math.max(l.activeProcs, l.hasBlocked || l.activeProcs > 0 ? 0 : 1) + l.helperProcs)
322    if (!l.isDone && !l.isAgy) inner.push(1)
323    if (l.hasNote) inner.push(1)
324    if (l.mixTags > 0) inner.push(1 + (l.mixTags > 4 ? 2 : 1))
325    if (l.hasSpark) inner.push(1)
326    parts.push(4 + inner.reduce((n, x) => n + x, 0) + inner.length - 1)
327  }
328  parts.push(1, 2)
329  return parts.reduce((n, x) => n + x, 0) + parts.length - 1 - 1
330}
331
332// an expanded message never takes more than this share of the timeline lines, so the other rows keep their place
333export const expandCap = (budget: number): number => Math.max(3, Math.floor(budget * 0.6))
334
335// the text an expanded row shows: all of it unless it would not fit in `maxLines`, then cut with a marker
336export const fitText = (text: string, maxLines: number, textCols: number): string => {
337  const room = Math.max(10, textCols) * maxLines
338  return text.length > room ? `${text.slice(0, room - 2)} …` : text
339}
340
341// terminal lines one timeline row takes: path rows have a folder line, prose wraps only when expanded
342export const rowLines = (x: Ev, isOpen: boolean, textCols: number, maxLines: number): number => {
343  if (x.kind === 'tool' || x.kind === 'file') return splitPath(x.text).dir ? 2 : 1
344  if (!isOpen) return 1
345  return Math.min(maxLines, Math.max(1, Math.ceil(x.text.length / Math.max(10, textCols))))
346}
347
348// how many of the newest rows (ending at `end`) fit in `budget` lines, at least 3
349export const fitRows = (shown: Ev[], end: number, budget: number, open: Set<string>, idOf: (x: Ev) => string, textCols: number): number => {
350  const maxLines = expandCap(budget)
351  let used = open.size > 0 ? 1 : 0
352  let n = 0
353  for (let i = end - 1; i >= 0; i--) {
354    const h = rowLines(shown[i]!, open.has(idOf(shown[i]!)), textCols, maxLines)
355    if (used + h > budget) break
356    used += h
357    n += 1
358  }
359  return Math.max(3, n)
360}
361
hooks/roots.ts 48 lines
1// Where to look for run folders, and which run folders to keep between searches.
2// The session's working directory moves (every `cd` in a Bash call moves it in the desktop app), so a relative
3// watch path is resolved against stable anchors, never against the live cwd alone.
4
5export type Cand = { dir: string; name: string; mtime: number }
6
7const trimSlash = (p: string): string => (p.length > 1 ? p.replace(/\/+$/, '') : p)
8
9// The folders a relative watch path is resolved against, most stable first, without duplicates:
10// the repository root of the current cwd, the cwd the session started in, and the current cwd.
11export const anchorsOf = (startCwd: string, cwd: string, gitTop: string | null): string[] => {
12  const out: string[] = []
13  for (const p of [gitTop, startCwd, cwd]) {
14    const v = trimSlash((p ?? '').trim())
15    if (v.startsWith('/') && !out.includes(v)) out.push(v)
16  }
17  return out
18}
19
20// Every watch path as an absolute root: `$TMPDIR` and `~` expanded, an absolute path kept once,
21// a relative one joined to each anchor. Duplicates are dropped and the order is kept.
22export const resolveRoots = (watch: string[], anchors: string[], tmp: string, home: string): string[] => {
23  const out: string[] = []
24  const add = (p: string) => {
25    const v = trimSlash(p)
26    if (!out.includes(v)) out.push(v)
27  }
28  for (const raw of watch) {
29    const abs = raw.trim().replace(/^\$TMPDIR/, trimSlash(tmp)).replace(/^~(?=\/|$)/, trimSlash(home))
30    if (abs === '') continue
31    if (abs.startsWith('/')) add(abs)
32    else for (const a of anchors) add(`${a}/${abs.replace(/^\.\//, '')}`)
33  }
34  return out
35}
36
37// The run folders after a search: what the search found, plus every folder found earlier that the search
38// missed, that is not known to be gone and whose log was written after `minMtime` (a search from a different
39// cwd must not make a live run vanish, but an old run still ages out). Newest first.
40export const mergeCands = (prev: Cand[], fresh: Cand[], gone: Set<string>, minMtime: number): Cand[] => {
41  const seen = new Set(fresh.map(c => c.dir))
42  const kept = prev.filter(c => !seen.has(c.dir) && !gone.has(c.dir) && c.mtime >= minMtime)
43  return [...fresh, ...kept].sort((x, y) => y.mtime - x.mtime)
44}
45
46// The line under "No delegate runs yet" naming where the last search looked, or null before the first search.
47export const searchedHint = (roots: string[]): string | null => (roots.length > 0 ? `Searched: ${roots.join(', ')}` : null)
48
types/index.d.ts 56 lines
1export type Ev = {
2  t: number
3  kind: 'tool' | 'say' | 'think' | 'err' | 'file' | 'turn'
4  tag: string
5  text: string
6}
7
8export type Run = {
9  dir: string
10  name: string
11  agent: 'agy' | 'claude' | 'cursor' | 'opencode' | 'unknown'
12  model: string
13  startedAt: number
14  finishedAt: number
15  updatedAt: number
16  status: string
17  isDone: boolean
18  touched: number | null
19  tools: number
20  cost: number
21  note: string
22  turns: number
23  lastTurn: number
24  blocked: string
25  procs: { age: string; cmd: string; isHelper: boolean }[]
26}
27
28// the poll loop's pulse: when it last completed, how often it has run, and the last failure
29export type Beat = {
30  okAt: number
31  ticks: number
32  errors: number
33  error: string
34  errorAt: number
35}
36
37export type Filter = 'all' | 'tools' | 'say' | 'turns'
38
39declare module 'claude-code' {
40  interface PluginState {
41    'delegate-watch': {
42      runs: Run[]
43      selected: string | null
44      events: Ev[]
45      scroll: number
46      paused: boolean
47      filter: Filter
48      rowsPref: number
49      expanded: string[]
50      beat: Beat
51      startCwd: string
52      searched: string[]
53    }
54  }
55}
56