SLOPSHOPPER

agent-cats

A dashboard of the session's agents as coloured cats: their tasks, skills and run time, their questions answered in place with a meow, and the skills each task…

panerowsguardcommandtoastprompt
v0.3.2MITupdated 2026-10-17anthonyzng/agent-cats
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · agent-cats
│ ┃ Agent Cats ✕ › fix the failing auth test and ╭──────────────────────────────────╮ │ ┃ 🐾 Agent Cats [ All 1 ] [ Working 0 ] [ Asle │ agent-cats │ │ ┃ ● agent-cats: agent-cats: skills:│ 🐱 "Main agent" finished its │ │ ┃ ╭─────────────────────────────────────────── ⏺ Read(src/auth.ts) │ task │ │ ┃ │ Skills for this task [ Mode: prefer the c ⎿ Read 6 lines ╰──────────────────────────────────╯ │ ┃ │ ⏺ Update(src/auth.ts) │ ┃ │ None chosen (every skill works as usual) ⎿ Added 2 lines, removed 1 line │ ┃ │ ⏺ Bash(bun test) │ ┃ │ No installed skills found. Try "Refresh ⎿ 3 pass, 1 fail │ ┃ │ list". │ ┃ │ ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ │ Find a new skill: say what you need, Enter │ ┃ ╰─────────────────────────────────────────── ✻ Worked for 42s · done 4:20 PM │ ┃ │ ┃ ╭──────────────────────────────────────────╮ › /cats │ ┃ │ ᓚᘏᗢᶻ Main agent ✎ Rename │ ⎿ agent-cats: Agent Cats dashboard opened. skills: 0 (context list │ ┃ │ Asleep (can be woken) ⏱ --:-- main │ │ ┃ │ Skills: none yet │ │ ┃ ╰──────────────────────────────────────────╯ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Agent Cats
🐾 Agent Cats [ All 1 ] [ Working 0 ] [ Asleep 1 ] [ Waiting ╭─────────────────────────────────────────────────────────── │ Skills for this task [ Mode: prefer the chosen ones ] Re │ │ None chosen (every skill works as usual) │ │ No installed skills found. Try "Refresh list". │ │ Find a new skill: say what you need, Enter asks the main a ╰─────────────────────────────────────────────────────────── ╭──────────────────────────────────────────────────────────╮ │ ᓚᘏᗢᶻ Main agent ✎ Rename │ │ Asleep (can be woken) ⏱ --:-- main │ │ Skills: none yet │ ╰──────────────────────────────────────────────────────────╯
README

Agent Cats

English | 繁體中文

A Claude Code mod that turns the agents of a session into a dashboard of cats.

  • One cat per agent. The main agent and every subagent each get their own colour: an SVG cat on the desktop app and VS Code, ᓚᘏᗢ in the terminal.
  • What each cat is doing. Every cat shows its task, its status, how long it has run, its agent type, the tool it is using now and the skills it has loaded.
  • Asleep or done. When a subagent finishes, its cat changes status:
  • Asleep if SendMessage can still reach it. Give it a new task in its field and the main agent wakes it.
  • Done if it failed, was stopped or cannot be addressed.
  • Close it when you no longer need to wake it.
  • Show only some cats. The counts at the top are buttons: All, Working, Asleep and Waiting for you list only those cats. Press the chosen one again to see all.
  • Stop a cat. A working cat has ■ Stop, which asks you to confirm first. The main agent's turn is aborted; a subagent is stopped with TaskStop. A stopped cat keeps its +Skill picker: hand it a skill and it reads the skill and resumes (a subagent is woken with SendMessage, so it needs a name).
  • Delete a cat. Every subagent's cat has 🗑 Delete. It leaves the dashboard and does not come back, even while Claude Code still lists the agent. A cat still working asks you to confirm first, and is stopped before it is removed. A subagent that Claude Code no longer lists is marked done, so it never stays stuck as working. The main agent cannot be deleted.
  • A sound when an agent finishes or needs you. sounds/Hachimi.mp3 plays when an agent finishes its task, asks you something, waits for a permission or a plan approval, or an MCP server waits for your input. The main agent sounds only when its work is really done: not while background work it waits for (a subagent, a shell, a monitor) still runs, not while a one-shot wakeup is set, and not when a Stop hook sends it back to work. A permission sounds only if it is still waiting after 1.5 s, so one that auto mode or a rule settles at once stays quiet. One clip plays at a time: while a cat sound plays, every other one is skipped, never queued or layered. On Windows this holds across every Claude Code session and window. A cat you stopped does not sound.
  • Questions answered in place. When an agent asks you something (AskUserQuestion), the question appears at the top of the dashboard with the sound.
  • Pick an option, or type your own answer.
  • The engine's own dialog is replaced by a pointer to the dashboard. Use the native dialog is a fallback.
  • Permission prompts appear too, with the same sound. Allow / Deny stays in the engine's own dialog: only the engine may grant a permission.
  • Rename cats. Give any cat a name of your own with ✎ Rename.
  • Skills:
  • +Skill on a cat hands it one of your installed skills. A running agent reads the request at its next step. A sleeping subagent is woken with it. An idle main agent gets it as a prompt.
  • Find a new skill asks the main agent to search the skill and plugin catalogs and show install cards. Nothing is installed until you approve a card.
  • Skills for this task picks the skills for the work at hand, in one of two modes:
  • Prefer: every prompt and new subagent is told to use them.
  • Only: every other skill is refused.
  • English or Traditional Chinese. The dashboard's language is a setting (see below).

Requirements

Claude Code 2.1.286 or later: the first release with mods (function hooks).

Install

In Claude Code:

/plugin marketplace add anthonyzng/agent-cats
/plugin install agent-cats@agent-cats

Then open the dashboard with /cats. The pane also opens by itself when a session starts on a wide enough window, and whenever an agent asks you something.

To update later:

/plugin marketplace update agent-cats

From a local copy

git clone https://github.com/anthonyzng/agent-cats.git
claude --plugin-dir ./agent-cats

Hosts that cannot take a flag, such as the desktop app, read the same folders from CLAUDE_CODE_PLUGIN_DIRS. Set it in the env block of ~/.claude/settings.json to an absolute path.

Language

The dashboard is in English by default. To switch it to Traditional Chinese (Cantonese), open /config, find the Language row of agent-cats and pick zh-Hant. Claude Code saves the choice under pluginConfigs in ~/.claude/settings.json, and the mod reloads with the new language at once. Text the agents read, such as the skill instructions, stays in English.

Things to know

  • Mods are not sandboxed. This one runs inside Claude Code with your permissions, like every mod. Read hooks/register.tsx before you install it. It makes no network calls and writes no files. The only external thing it touches is the bundled sound, sounds/Hachimi.mp3, and on Windows the one program it runs: powershell.exe, to play that sound.
  • "Only" mode applies to every agent of the session, the main one included.
  • The dashboard holds still while you use it. While you are in one of its dropdowns or text fields, its once-a-second updates wait, so an open dropdown does not jump back to its top.
  • This works in the terminal.
  • The desktop app does not say which element took focus, so there an open dropdown can still be redrawn while an agent is working.
  • When every agent is idle, the dashboard does not redraw at all.
  • /cats prints a diagnostic line: how many skills it found, how often the pane drew and the last focus moves.
  • Playing the sound. On macOS it uses Claude Code's own audio player. Claude Code has none on Windows, so there the mod plays the clip with PowerShell's MediaPlayer (powershell.exe, built into Windows). A Linux terminal has no player: there you still get the toast.

Development

claude plugin validate .   # what the module hooks and calls, and anything the engine would refuse
claude plugin test .       # tests/*.test.tsx against the engine itself
python scripts/make-meow.py  # regenerate sounds/meow.wav (stdlib only)

Claude Code writes the type declarations into .claude-plugin/types/ when it loads the mod. tsconfig.json extends them, so tsc -p . type-checks the module. The interface words live in hooks/strings.ts, one table per language.

License

MIT

Source 3 files
hooks/register.tsx 1129 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { CatAgent, CatPending, CatQuestion, CatStatus, CatView, SkillMode } from '../types'
5
6import { STRINGS, languageOf } from './strings'
7import type { Strings } from './strings'
8
9const PANE = 'agent-cats'
10// The words of the language the `language` option names; set by `register`
11// (a change of the option reloads the module).
12let t: Strings = STRINGS.en
13const MAIN = 'main'
14const MAIN_COLOR = '#F4A261'
15const PALETTE = ['#2B2D42', '#F5F5F5', '#E76F51', '#8E7DBE', '#2A9D8F', '#E9C46A', '#6C757D', '#F28482', '#4D96FF']
16
17const agents = atom({ plugin: 'agent-cats', key: 'agents' } as const, [])
18const pending = atom({ plugin: 'agent-cats', key: 'pending' } as const, [])
19const clockNow = atom({ plugin: 'agent-cats', key: 'now' } as const, 0)
20const native = atom({ plugin: 'agent-cats', key: 'native' } as const, [])
21const skills = atom({ plugin: 'agent-cats', key: 'skills' } as const, [])
22const activeSkills = atom({ plugin: 'agent-cats', key: 'activeSkills' } as const, [])
23const skillMode = atom({ plugin: 'agent-cats', key: 'skillMode' } as const, 'prefer')
24
25const skillFilter = atom({ plugin: 'agent-cats', key: 'skillFilter' } as const, '')
26
27const renaming = atom({ plugin: 'agent-cats', key: 'renaming' } as const, '')
28const view = atom({ plugin: 'agent-cats', key: 'view' } as const, 'all' as CatView)
29const confirmStop = atom({ plugin: 'agent-cats', key: 'confirmStop' } as const, '')
30const deleted = atom({ plugin: 'agent-cats', key: 'deleted' } as const, [])
31
32// The main loop's running turn, which Stop aborts; set by `turn.start`.
33let mainTurnId: string | undefined
34
35// While the person is in one of the dashboard's pickers or text fields, the
36// once-a-second clock redraw would redraw it under them (an open dropdown
37// jumps back to its top), so the clock holds until focus leaves, at most this long.
38const HOLD_MS = 60_000
39const HOLD_ELEMENT = /^(give-|active-add|skill-filter|skill-search|wake-|other-|rename-)/
40let holdUntil = 0
41// Diagnostics for /cats: how often the pane drew, and the last focus moves.
42let renders = 0
43const writes: Record<string, number> = {}
44const wrote = (key: string) => {
45  writes[key] = (writes[key] ?? 0) + 1
46}
47const focusSeen: string[] = []
48
49async function isHolding($: EngineInterface): Promise<boolean> {
50  return holdUntil > 0 && (await $.clock.now()) < holdUntil
51}
52
53const PICK_HINT = '__pick__'
54// A Select takes at most 64 options: the hint plus this many skills.
55const MAX_SKILL_OPTIONS = 63
56
57// The hint first, then the skills that match the filter, capped to what a
58// Select can hold; the hint says how many the filter is hiding.
59function skillOptions(names: readonly string[], filter: string, hint: string): { value: string; label?: string }[] {
60  const needle = filter.trim().toLowerCase()
61  const matches = needle ? names.filter(n => n.toLowerCase().includes(needle)) : [...names]
62  const shown = matches.slice(0, MAX_SKILL_OPTIONS)
63  const hidden = matches.length - shown.length
64  const label =
65    matches.length === 0
66      ? t.noMatch(filter.trim())
67      : hidden > 0
68        ? t.moreHidden(hint, hidden)
69        : hint
70
71  return [{ value: PICK_HINT, label }, ...shown.map(n => ({ value: n }))]
72}
73
74type Answers = Record<string, string>
75
76// Lives with this module: after a reload the old waits are gone, so their
77// questions fall back to the engine's own dialog.
78const resolvers = new Map<string, (answers: Answers) => void>()
79
80const STATUS_COLOR: Record<CatStatus, string> = {
81  working: '#2A9D8F',
82  sleeping: '#8E7DBE',
83  closed: '#888888',
84}
85
86function catStatusOf(info: { status: string; name?: string }): CatStatus {
87  if (info.status === 'running' || info.status === 'pending') {
88    return 'working'
89  }
90  // A finished agent that SendMessage can still address sleeps until woken;
91  // one that failed, was killed or cannot be addressed is done for good.
92  if ((info.status === 'completed' || info.status === 'idle') && info.name) {
93    return 'sleeping'
94  }
95
96  return 'closed'
97}
98
99function elapsed(from: number, to: number): string {
100  const total = Math.max(0, Math.floor((to - from) / 1000))
101  const h = Math.floor(total / 3600)
102  const m = Math.floor((total % 3600) / 60)
103  const s = total % 60
104  const two = (n: number) => String(n).padStart(2, '0')
105
106  return h > 0 ? `${h}:${two(m)}:${two(s)}` : `${two(m)}:${two(s)}`
107}
108
109function catSvg(color: string, isAsleep: boolean): string {
110  const eyes = isAsleep
111    ? '<path d="M9 17 q2 2 4 0 M19 17 q2 2 4 0" stroke="#333" stroke-width="1.2" fill="none"/>'
112    : '<circle cx="11" cy="17" r="1.8" fill="#333"/><circle cx="21" cy="17" r="1.8" fill="#333"/>'
113
114  return (
115    '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="28" height="28">' +
116    `<path d="M5 14 L7 3 L14 9 Z M27 14 L25 3 L18 9 Z" fill="${color}" stroke="#333" stroke-width="1"/>` +
117    `<ellipse cx="16" cy="19" rx="12" ry="10" fill="${color}" stroke="#333" stroke-width="1"/>` +
118    eyes +
119    '<path d="M15 21 L17 21 L16 22.4 Z" fill="#E88"/>' +
120    '<path d="M3 20 L10 21 M3 23 L10 22 M29 20 L22 21 M29 23 L22 22" stroke="#555" stroke-width="0.6"/>' +
121    '</svg>'
122  )
123}
124
125function toQuestions(raw: readonly unknown[]): CatQuestion[] {
126  return raw.map(item => {
127    const q = item as {
128      question?: string
129      header?: string
130      kind?: string
131      multiSelect?: boolean
132      options?: { label?: string }[]
133    }
134    const kind = q.kind === 'text' || q.kind === 'number' ? q.kind : 'choice'
135
136    return {
137      question: q.question ?? '',
138      header: q.header ?? '',
139      kind,
140      isMulti: q.multiSelect === true,
141      options: (q.options ?? []).map(o => o.label ?? '').filter(Boolean),
142    }
143  })
144}
145
146function answerOf(p: CatPending, index: number): string {
147  const picked = p.picks[index] ?? []
148  const other = (p.others[index] ?? '').trim()
149
150  return [...picked, ...(other ? [other] : [])].join(', ')
151}
152
153function describeInput(input: unknown): string {
154  if (input && typeof input === 'object') {
155    const o = input as Record<string, unknown>
156    for (const key of ['command', 'file_path', 'url', 'path', 'pattern', 'description', 'prompt']) {
157      if (typeof o[key] === 'string') {
158        return String(o[key]).slice(0, 300)
159      }
160    }
161  }
162
163  return ''
164}
165
166const CHIME = 'sounds/Hachimi.mp3'
167// One clip at a time for the whole module: while it plays, every other request
168// is dropped (never queued, never layered), so agents finishing or asking one
169// after another sound once until the clip has played through.
170let isChiming = false
171// How long a permission request must stay unanswered before it chimes.
172const PERMISSION_GRACE_MS = 1500
173
174// Claude Code's own player (`afplay`) exists on macOS only: on Windows
175// `$.audio.play` skips the clip without an error. There the clip is played by
176// PowerShell's MediaPlayer (WPF), which reads mp3; it waits until the clip has
177// played through, so the one-clip-at-a-time rule holds there too. The path
178// goes in through the environment, never spliced into the script.
179// `isChiming` covers one session; every session (and Claude Code process)
180// loads its own copy of this module, so the player also holds a named mutex
181// for the clip's whole length: a cat sound already playing anywhere makes it
182// skip. Windows releases the mutex when the process ends, whatever the cause.
183const WINDOWS_PLAYER = [
184  '$m = New-Object System.Threading.Mutex($false, "Local\\agent-cats-chime")',
185  'try { $isOwner = $m.WaitOne(0) } catch [System.Threading.AbandonedMutexException] { $isOwner = $true }',
186  'if (-not $isOwner) { exit 0 }',
187  'Add-Type -AssemblyName PresentationCore',
188  '$p = New-Object System.Windows.Media.MediaPlayer',
189  '$p.Open([uri]$env:AGENT_CATS_CLIP)',
190  '$t = 0',
191  'while (-not $p.NaturalDuration.HasTimeSpan -and $t -lt 40) { Start-Sleep -Milliseconds 50; $t++ }',
192  '$p.Play()',
193  '$ms = if ($p.NaturalDuration.HasTimeSpan) { $p.NaturalDuration.TimeSpan.TotalMilliseconds } else { 3000 }',
194  'Start-Sleep -Milliseconds ([int]$ms + 100)',
195  '$p.Close()',
196  '$m.ReleaseMutex()',
197].join('; ')
198
199async function playChime($: EngineInterface): Promise<void> {
200  if ((await $.env.get('OS')) !== 'Windows_NT') {
201    await $.audio.play({ asset: CHIME })
202    return
203  }
204  const { exitCode, stderr } = await $.process.run(
205    ['powershell.exe', '-NoProfile', '-NonInteractive', '-Command', WINDOWS_PLAYER],
206    { env: { AGENT_CATS_CLIP: `${$.plugin.root}/${CHIME}` }, timeoutMs: 20_000 },
207  )
208  if (exitCode !== 0) {
209    throw new Error(`powershell exited ${exitCode}: ${stderr.trim()}`)
210  }
211}
212
213async function chime($: EngineInterface, text: string): Promise<void> {
214  $.ui.toast(`🐱 ${text}`)
215  if (isChiming) {
216    return
217  }
218  isChiming = true
219  try {
220    await playChime($)
221  } catch (error) {
222    $.ui.log(`agent-cats: could not play the chime (${String(error)})`, { to: 'debug' })
223  } finally {
224    isChiming = false
225  }
226}
227
228// Every write redraws the pane (an open dropdown jumps back to its top), so
229// the agents are written only when the change actually changed something.
230async function changeAgents($: EngineInterface, change: (rows: CatAgent[]) => CatAgent[]): Promise<void> {
231  const ref = { plugin: 'agent-cats', key: 'agents' } as const
232  for (let attempt = 0; attempt < 5; attempt += 1) {
233    const { value = [], version } = await $.state.get(ref)
234    const next = change(value)
235    if (JSON.stringify(next) === JSON.stringify(value)) {
236      return
237    }
238    wrote('agents')
239    const { isSet } = await $.state.set(ref, next, { ifVersion: version })
240    if (isSet) {
241      return
242    }
243  }
244}
245
246async function setMain($: EngineInterface, change: (row: CatAgent) => CatAgent): Promise<void> {
247  await changeAgents($, rows => {
248    const list = rows ?? []
249    const main =
250      list.find(r => r.id === MAIN) ??
251      ({
252        id: MAIN,
253        // Empty until the first turn; drawn as the main agent's name meanwhile.
254        label: '',
255        type: 'main',
256        status: 'sleeping',
257        rawStatus: 'idle',
258        color: MAIN_COLOR,
259        startedAt: 0,
260        skills: [],
261      } satisfies CatAgent)
262
263    return [change(main), ...list.filter(r => r.id !== MAIN)]
264  })
265}
266
267async function patchAgent($: EngineInterface, id: string, change: (row: CatAgent) => CatAgent): Promise<void> {
268  if (id === MAIN) {
269    return setMain($, change)
270  }
271  await changeAgents($, rows => rows.map(r => (r.id === id ? change(r) : r)))
272}
273
274// The installed skills: the context listing (counted locally, no API call)
275// where the host computes it, plus the plugin and user slash commands, which
276// is where skills show up when it does not. Answers a line for diagnostics.
277async function loadSkills($: EngineInterface): Promise<string> {
278  let fromContext: string[] = []
279  let contextNote = 'ok'
280  try {
281    const usage = await $.session.usage({ breakdown: 'summary' })
282    const breakdown = usage.context.breakdown
283    fromContext = (breakdown?.skills?.skillFrontmatter ?? []).map(s => s.name)
284    if (!breakdown) {
285      contextNote = 'no breakdown'
286    } else if (!breakdown.skills) {
287      contextNote = 'no skills in breakdown'
288    }
289  } catch (error) {
290    contextNote = `error: ${String(error)}`
291  }
292  let fromCommands: string[] = []
293  let commandNote = 'ok'
294  try {
295    fromCommands = (await $.command.list())
296      .filter(c => (c.source === 'plugin' || c.source === 'user') && c.name !== 'cats')
297      .map(c => c.name)
298  } catch (error) {
299    commandNote = `error: ${String(error)}`
300  }
301  const names = [...new Set([...fromContext, ...fromCommands])].sort((a, b) => a.localeCompare(b))
302  if (JSON.stringify(names) !== JSON.stringify(await read($, skills))) {
303    await $.state.set({ plugin: 'agent-cats', key: 'skills' }, names)
304  }
305
306  return `skills: ${names.length} (context listing ${fromContext.length}, ${contextNote}; commands ${fromCommands.length}, ${commandNote})`
307}
308
309function skillNote(active: readonly string[], mode: SkillMode): string {
310  const list = active.join(', ')
311
312  return mode === 'only'
313    ? `The user chose the skills for this task in the Agent Cats dashboard: ${list}. Use only these skills (load each with the Skill tool when it applies); any other skill is refused.`
314    : `The user chose the skills for this task in the Agent Cats dashboard: ${list}. Prefer these skills and load each with the Skill tool when it applies.`
315}
316
317// Hands one installed skill to one cat: a running loop reads it at its next
318// step, a sleeping subagent is woken with it, an idle main agent gets a prompt.
319async function giveSkill($: EngineInterface, row: CatAgent, skill: string): Promise<void> {
320  const ask = `The user asks you, from the Agent Cats dashboard, to load the skill "${skill}" with the Skill tool now and use it for your current task.`
321  if (row.isStopped) {
322    await patchAgent($, row.id, r => ({ ...r, isStopped: undefined }))
323  }
324  if (row.status === 'working' && !row.isStopped) {
325    await $.session.append({
326      message: { type: 'user', content: [{ type: 'text', text: ask }] },
327      ...(row.id === MAIN ? {} : { agentId: row.id }),
328    })
329  } else if (row.id === MAIN) {
330    await $.prompt.submit({ text: ask })
331  } else if (row.name) {
332    await $.prompt.submit({
333      text: `Use SendMessage to wake the agent "${row.name}" (${row.label}) and tell it to load the skill "${skill}" with the Skill tool and use it to continue its task.`,
334    })
335  } else {
336    $.ui.toast(`🐱 ${t.skillNotGiven(row.nickname || row.label)}`)
337
338    return
339  }
340  $.ui.toast(`🐱 ${t.skillGiven(row.nickname || row.label || t.mainAgent, skill)}`)
341}
342
343function nameOf(row: CatAgent): string {
344  return row.nickname || row.label || t.mainAgent
345}
346
347// Stops one cat: the main loop's turn is aborted; a subagent is stopped with
348// TaskStop (it takes an agent id). Either way the cat is marked stopped, so
349// the end is not chimed as a finished task and a skill handed to it resumes it.
350async function stopAgent($: EngineInterface, row: CatAgent): Promise<void> {
351  const now = await $.clock.now()
352  try {
353    if (row.id === MAIN) {
354      if (mainTurnId) {
355        await $.turn.abort({ turnId: mainTurnId })
356      }
357    } else {
358      await $.tool.call({ tool: 'TaskStop', task_id: row.id } as never)
359    }
360  } catch (error) {
361    $.ui.toast(`🐱 ${t.stopFailed(nameOf(row), String(error))}`)
362
363    return
364  }
365  await patchAgent($, row.id, r => ({
366    ...r,
367    isStopped: true,
368    status: r.id === MAIN ? 'sleeping' : r.status,
369    endedAt: r.endedAt ?? now,
370    tool: undefined,
371  }))
372  $.ui.toast(`🐱 ${t.stoppedToast(nameOf(row))}`)
373}
374
375// Deletes a subagent's cat: removed now, and remembered so that the engine's
376// own list (which keeps an agent for a while) never brings it back. A cat
377// still marked working is stopped first; a stop that fails (the agent is
378// already gone, its cat left marked working) does not keep the cat.
379async function deleteAgent($: EngineInterface, row: CatAgent): Promise<void> {
380  if (row.id === MAIN) {
381    return
382  }
383  if (row.status === 'working' && !row.isStopped) {
384    try {
385      await $.tool.call({ tool: 'TaskStop', task_id: row.id } as never)
386    } catch (error) {
387      $.ui.log(`agent-cats: could not stop ${row.id} before deleting it (${String(error)})`, { to: 'debug' })
388    }
389  }
390  await update($, deleted, list => [...new Set([...(list ?? []), row.id])])
391  await changeAgents($, rows => rows.filter(r => r.id !== row.id))
392}
393
394async function sync($: EngineInterface): Promise<void> {
395  // The person is in a picker: nothing redraws under them; the next tick
396  // after the hold catches up (end times are then a second or so late).
397  if (await isHolding($)) {
398    return
399  }
400  const gone = new Set(await read($, deleted))
401  const list = (await $.agent.list()).filter(a => !gone.has(a.id))
402  const now = await $.clock.now()
403  let finished: string[] = []
404
405  await changeAgents($, current => {
406    finished = []
407    let changed = false
408    const next = current.map(row => {
409      const info = list.find(a => a.id === row.id)
410      if (!info) {
411        // A subagent the engine no longer lists has ended: a cat left
412        // working would show Stop forever and never Delete.
413        if (row.id === MAIN || row.status !== 'working') {
414          return row
415        }
416        changed = true
417
418        return { ...row, status: 'closed' as CatStatus, endedAt: row.endedAt ?? now, tool: undefined }
419      }
420      const status = catStatusOf(info)
421      if (status === row.status && info.status === row.rawStatus && info.name === row.name) {
422        return row
423      }
424      changed = true
425      const isWoken = status === 'working' && row.status !== 'working'
426      if (row.status === 'working' && status !== 'working' && info.status === 'completed' && !row.isStopped) {
427        finished.push(nameOf(row))
428      }
429
430      return {
431        ...row,
432        status,
433        rawStatus: info.status,
434        name: info.name,
435        label: info.description || row.label,
436        startedAt: isWoken ? now : row.startedAt,
437        endedAt: status === 'working' ? undefined : (row.endedAt ?? now),
438        tool: status === 'working' ? row.tool : undefined,
439        isHidden: isWoken ? false : row.isHidden,
440        isStopped: isWoken ? undefined : row.isStopped,
441      }
442    })
443    const known = new Set(current.map(r => r.id))
444    const added = list
445      .filter(a => !known.has(a.id))
446      .map((a, i): CatAgent => {
447        const status = catStatusOf(a)
448
449        return {
450          id: a.id,
451          label: a.description || a.type,
452          type: a.type,
453          name: a.name,
454          status,
455          rawStatus: a.status,
456          color: PALETTE[(current.length - 1 + i + PALETTE.length) % PALETTE.length] ?? MAIN_COLOR,
457          startedAt: now,
458          endedAt: status === 'working' ? undefined : now,
459          skills: [],
460        }
461      })
462
463    return changed || added.length > 0 ? [...next, ...added] : current
464  })
465
466  if (finished.length > 0) {
467    void chime($, finished.map(name => t.doneToast(name)).join(' · '))
468  }
469
470  const rows = await read($, agents)
471  const waits = await read($, pending)
472  if (rows.some(r => r.status === 'working') || waits.length > 0) {
473    wrote('now')
474    await $.state.set({ plugin: 'agent-cats', key: 'now' }, now)
475  }
476}
477
478export const register: Register = (on, options) => {
479  t = STRINGS[languageOf(options['language'])]
480
481  on('session.start', async ($, e, next) => {
482    await setMain($, row => row)
483    $.ui.log(`agent-cats: ${await loadSkills($)}`, { to: 'debug' })
484    await $.command.register({ name: 'cats', description: t.commandDescription })
485    void $.ui.open({ id: PANE, title: t.title })
486    $.clock.every(1000, () => {
487      void sync($)
488    })
489
490    return next(e)
491  })
492
493  on('ui.focus', { requestId: PANE }, async ($, e, next) => {
494    // The person's move names the element; a plugin's `$.ui.focus` call, its `key`.
495    const element = e.element ?? (e as { key?: string }).key
496    holdUntil = element && HOLD_ELEMENT.test(element) ? (await $.clock.now()) + HOLD_MS : 0
497    focusSeen.push(element ?? '(none)')
498    focusSeen.splice(0, Math.max(0, focusSeen.length - 3))
499
500    return next(e)
501  })
502
503  on('command.run', { command: 'cats' }, async $ => {
504    const found = await loadSkills($)
505    await $.ui.open({ id: PANE, title: t.title, focus: true })
506    const focus = focusSeen.length > 0 ? focusSeen.join(', ') : 'none'
507
508    return { text: `${t.opened} ${found}; draws ${renders}; writes ${JSON.stringify(writes)}; last focus ${focus}` }
509  })
510
511  // The skills chosen in the dashboard ride along with every prompt and spawn.
512  on('prompt.submit', async ($, e, next) => {
513    const active = await read($, activeSkills)
514    if (active.length === 0) {
515      return next(e)
516    }
517    const note = skillNote(active, await read($, skillMode))
518
519    return next({ ...e, context: [...(e.context ?? []), note] })
520  })
521
522  on('agent.spawn', async ($, e, next) => {
523    const active = await read($, activeSkills)
524    if (active.length === 0) {
525      return next(e)
526    }
527
528    return next({ ...e, prompt: `${skillNote(active, await read($, skillMode))}\n\n${e.prompt}` })
529  })
530
531  on('turn.start', async ($, e, next) => {
532    if (e.agentId === undefined) {
533      mainTurnId = e.turnId
534    }
535    const now = await $.clock.now()
536    const text = e.text.trim().replace(/\s+/g, ' ')
537    await setMain($, row => ({
538      ...row,
539      status: 'working',
540      rawStatus: 'running',
541      label: text ? text.slice(0, 60) : row.label,
542      startedAt: now,
543      endedAt: undefined,
544      skills: [],
545      isStopped: undefined,
546    }))
547
548    return next(e)
549  })
550
551  on('turn.complete', async ($, e, next) => {
552    if (e.agentId === undefined) {
553      mainTurnId = undefined
554      const now = await $.clock.now()
555      await setMain($, row => ({ ...row, status: 'sleeping', rawStatus: 'idle', endedAt: now, tool: undefined }))
556    }
557
558    return next(e)
559  })
560
561  // The main agent's chime: only when its work is really done. A turn also
562  // ends while background work it waits for still runs (a subagent, a shell, a
563  // monitor) or with a one-shot wakeup set: it is only paused then, and the
564  // work that wakes it chimes for itself. A settings Stop hook that blocks the
565  // stop (it re-prompts) means the turn goes on: the chime waits for the stop
566  // that holds. An interrupted turn raises no Stop.
567  on('classic.Stop', async ($, e, next) => {
568    const result = await next(e)
569    const isPaused =
570      (e.background_tasks ?? []).length > 0 || (e.session_crons ?? []).some(cron => !cron.recurring)
571    if (!result.block && !isPaused) {
572      const main = (await read($, agents)).find(r => r.id === MAIN)
573      if (main && !main.isStopped) {
574        void chime($, t.doneToast(nameOf(main)))
575      }
576    }
577
578    return result
579  })
580
581  // A plan waiting for the person's approval.
582  on('tool.call', { tool: 'ExitPlanMode' }, async ($, e, next) => {
583    void chime($, t.meowPlan)
584
585    return next(e)
586  })
587
588  // An MCP server's form or link waiting for the person.
589  on('classic.Notification', async ($, e, next) => {
590    if (e.notification_type === 'elicitation_dialog' || e.notification_type === 'elicitation_url_dialog') {
591      void chime($, t.meowQuestion)
592    }
593
594    return next(e)
595  })
596
597  // Every tool call: what each cat is doing now, the skills it used, and the
598  // permission questions it raised that the call has now settled.
599  on('tool.call', async ($, e, next) => {
600    const who = e.agentId ?? MAIN
601    // Read the arguments as untyped: how the engine types a built-in tool's
602    // input depends on the build that wrote the declarations.
603    const args = e as { skill?: unknown }
604    const skill = e.tool === 'Skill' && typeof args.skill === 'string' ? args.skill : undefined
605    if (skill !== undefined && (await read($, skillMode)) === 'only') {
606      const active = await read($, activeSkills)
607      if (active.length > 0 && !active.includes(skill)) {
608        return {
609          deny: `The user allowed only these skills in the Agent Cats dashboard: ${active.join(', ')}. "${skill}" is switched off.`,
610        }
611      }
612    }
613    // The "using X" line waits while the person is in a picker; a skill is kept.
614    const showsTool = !(await isHolding($))
615    await patchAgent($, who, row => ({
616      ...row,
617      tool: showsTool ? e.tool : row.tool,
618      skills: skill && !row.skills.includes(skill) ? [...row.skills, skill] : row.skills,
619    }))
620    try {
621      return await next(e)
622    } finally {
623      if (!(await isHolding($))) {
624        await patchAgent($, who, row => (row.tool === e.tool ? { ...row, tool: undefined } : row))
625      }
626      await update($, pending, list =>
627        (list ?? []).filter(p => !(p.kind === 'permission' && p.agentId === who && p.tool === e.tool)),
628      )
629    }
630  })
631
632  // A question to the person: answered in the dashboard. The engine's dialog
633  // waits beneath (its site drawn as a pointer here) and wins if used instead.
634  on('tool.call', { tool: 'AskUserQuestion' }, async ($, e, next) => {
635    const id = e.tool_use_id
636    const raw = (e as { questions?: unknown }).questions
637    const questions = toQuestions(Array.isArray(raw) ? raw : [])
638    const answered = new Promise<Answers>(resolve => {
639      resolvers.set(id, resolve)
640    })
641    const item: CatPending = {
642      id,
643      kind: 'question',
644      agentId: e.agentId ?? MAIN,
645      askedAt: await $.clock.now(),
646      questions,
647      picks: questions.map(() => []),
648      others: questions.map(() => ''),
649    }
650    await update($, pending, list => [...(list ?? []), item])
651    void $.ui.open({ id: PANE, title: t.title, focus: true })
652    void chime($, t.meowQuestion)
653
654    try {
655      const won = await Promise.race([
656        next(e).then(result => ({ result })),
657        answered.then(answers => ({ answers })),
658      ])
659      if ('result' in won) {
660        return won.result
661      }
662
663      return { result: { questions: raw, answers: won.answers } as never }
664    } finally {
665      resolvers.delete(id)
666      await update($, pending, list => (list ?? []).filter(p => p.id !== id))
667      await update($, native, list => (list ?? []).filter(n => n !== id))
668    }
669  })
670
671  // A permission prompt: shown with its meow; the engine's own dialog answers it.
672  on('classic.PermissionRequest', async ($, e, next) => {
673    const item: CatPending = {
674      id: `perm-${await $.clock.now()}-${e.tool_name}`,
675      kind: 'permission',
676      agentId: e.agent_id ?? MAIN,
677      askedAt: await $.clock.now(),
678      questions: [],
679      picks: [],
680      others: [],
681      tool: e.tool_name,
682      detail: describeInput(e.tool_input),
683    }
684    await update($, pending, list => [...(list ?? []), item])
685    void $.ui.open({ id: PANE, title: t.title })
686    // A request the person never sees (auto mode or a rule settles it at
687    // once) is gone from the list by then: only a prompt still waiting chimes.
688    $.clock.after(PERMISSION_GRACE_MS, () => {
689      void (async () => {
690        if ((await read($, pending)).some(p => p.id === item.id)) {
691          await chime($, t.meowPermission(e.tool_name))
692        }
693      })()
694    })
695
696    return next(e)
697  })
698
699  on('ui.render', { component: 'AskUserQuestion' }, async ($, e, next) => {
700    const useNative = (await read($, native)).includes(e.requestId)
701    if (useNative || !resolvers.has(e.requestId)) {
702      return next(e)
703    }
704    const { Box, Text, Button } = $.ui.resolve(e)
705
706    return (
707      <Box flexDirection="row" gap={1}>
708        <Text color={MAIN_COLOR}>ᓚᘏᗢ</Text>
709        <Text>{t.pointer(t.title)}</Text>
710        <Button
711          key={`native-${e.requestId}`}
712          label={t.answerHere}
713          plain
714          onPress={() => update($, native, list => [...(list ?? []), e.requestId])}
715        />
716      </Box>
717    )
718  })
719
720  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
721    renders += 1
722    const table = $.ui.resolve(e)
723    const { Box, Text, Button } = table
724    const Svg = 'Svg' in table ? table.Svg : undefined
725    const Input = 'Input' in table ? table.Input : undefined
726    const Select = 'Select' in table ? table.Select : undefined
727    const installed = await read($, skills)
728    const active = await read($, activeSkills)
729    const mode = await read($, skillMode)
730    const filter = await read($, skillFilter)
731    const editing = await read($, renaming)
732    const shown = await read($, view)
733    const stopping = await read($, confirmStop)
734    const rows = await read($, agents)
735    const waits = await read($, pending)
736    const now = Math.max(await read($, clockNow), ...rows.map(r => r.endedAt ?? r.startedAt))
737    const nativeIds = await read($, native)
738    const byId = (id: string) => rows.find(r => r.id === id)
739
740    const cat = (color: string, isAsleep: boolean, key: string) =>
741      Svg ? (
742        <Svg key={key} source={catSvg(color, isAsleep)} alt={isAsleep ? 'sleeping cat' : 'cat'} width={28} height={28} />
743      ) : (
744        <Text color={color}>{isAsleep ? 'ᓚᘏᗢᶻ' : 'ᓚᘏᗢ'}</Text>
745      )
746
747    const setPending = (id: string, change: (p: CatPending) => CatPending) =>
748      update($, pending, list => (list ?? []).map(p => (p.id === id ? change(p) : p)))
749
750    const pick = (p: CatPending, index: number, label: string) =>
751      setPending(p.id, cur => {
752        const q = cur.questions[index]
753        const had = cur.picks[index] ?? []
754        const chosen = q?.isMulti
755          ? had.includes(label)
756            ? had.filter(l => l !== label)
757            : [...had, label]
758          : [label]
759        const others = q?.isMulti ? cur.others : cur.others.map((o, i) => (i === index ? '' : o))
760
761        return { ...cur, picks: cur.picks.map((l, i) => (i === index ? chosen : l)), others }
762      })
763
764    const typeOther = (p: CatPending, index: number, text: string) =>
765      setPending(p.id, cur => {
766        const isMulti = cur.questions[index]?.isMulti
767        const picks = isMulti ? cur.picks : cur.picks.map((l, i) => (i === index ? [] : l))
768
769        return { ...cur, picks, others: cur.others.map((o, i) => (i === index ? text : o)) }
770      })
771
772    const send = (p: CatPending) => {
773      const answers: Answers = {}
774      p.questions.forEach((q, i) => {
775        answers[q.question] = answerOf(p, i)
776      })
777      resolvers.get(p.id)?.(answers)
778    }
779
780    const working = rows.filter(r => r.status === 'working').length
781    const sleeping = rows.filter(r => r.status === 'sleeping').length
782    const waitingIds = new Set(waits.map(p => p.agentId))
783    const inView = (r: CatAgent) =>
784      shown === 'working'
785        ? r.status === 'working'
786        : shown === 'sleeping'
787          ? r.status === 'sleeping'
788          : shown === 'waiting'
789            ? waitingIds.has(r.id)
790            : true
791    const visible = rows.filter(r => !r.isHidden && inView(r))
792    // Pressing the view already chosen goes back to all.
793    const viewButton = (which: CatView, label: string) => (
794      <Button
795        key={`view-${which}`}
796        label={label}
797        variant={shown === which ? 'primary' : 'secondary'}
798        onPress={() => update($, view, current => (current === which ? 'all' : which))}
799      />
800    )
801    const hiddenClosed = rows.some(r => r.status === 'closed' && !r.isHidden)
802
803    return (
804      <Box flexDirection="column" gap={1}>
805        <Box flexDirection="row" gap={1} alignItems="center" flexWrap="wrap">
806          <Text bold>🐾 {t.title}</Text>
807          {viewButton('all', `${t.counts.all} ${rows.filter(r => !r.isHidden).length}`)}
808          {viewButton('working', `${t.counts.working} ${working}`)}
809          {viewButton('sleeping', `${t.counts.sleeping} ${sleeping}`)}
810          {viewButton('waiting', `${t.counts.waiting} ${waits.length}`)}
811        </Box>
812
813        <Box flexDirection="column" gap={1} borderStyle="round" borderColor="#4D96FF" paddingX={1}>
814          <Box flexDirection="row" gap={2} alignItems="center" flexWrap="wrap">
815            <Text bold color="#4D96FF">{t.skillsHeading}</Text>
816            <Button
817              key="skill-mode"
818              label={mode === 'only' ? t.modeOnly : t.modePrefer}
819              variant={mode === 'only' ? 'primary' : 'secondary'}
820              onPress={() => update($, skillMode, m => (m === 'only' ? 'prefer' : 'only'))}
821            />
822            <Button
823              key="skills-reload"
824              label={t.reloadList}
825              plain
826              onPress={async () => {
827                $.ui.toast(`🐱 ${await loadSkills($)}`)
828              }}
829            />
830          </Box>
831          {active.length === 0 ? (
832            <Text dimColor>{t.noneChosen}</Text>
833          ) : (
834            <Box flexDirection="row" flexWrap="wrap" gap={1}>
835              {active.map(name => (
836                <Button
837                  key={`active-${name}`}
838                  label={`${name} ✕`}
839                  onPress={() => update($, activeSkills, list => (list ?? []).filter(n => n !== name))}
840                />
841              ))}
842              <Button key="active-clear" label={t.clearAll} plain onPress={() => update($, activeSkills, () => [])} />
843            </Box>
844          )}
845          {Input && installed.length > MAX_SKILL_OPTIONS && (
846            <Input
847              key="skill-filter"
848              placeholder={t.filterPlaceholder(installed.length)}
849              value={filter}
850              submitLabel={t.filterSubmit}
851              onSubmit={value => update($, skillFilter, () => value)}
852            />
853          )}
854          {Select && installed.length > 0 && (
855            <Select
856              key="active-add"
857              label={t.addSkill}
858              value={PICK_HINT}
859              options={skillOptions(
860                installed.filter(n => !active.includes(n)),
861                filter,
862                t.pickInstalled,
863              )}
864              onSelect={value => {
865                if (value !== PICK_HINT) {
866                  void update($, activeSkills, list => [...new Set([...(list ?? []), value])])
867                }
868              }}
869            />
870          )}
871          {installed.length === 0 && <Text dimColor>{t.noSkillsFound}</Text>}
872          {Input && (
873            <Input
874              key="skill-search"
875              placeholder={t.searchPlaceholder}
876              submitLabel={t.searchSubmit}
877              onSubmit={value => {
878                const need = value.trim()
879                if (need) {
880                  void $.prompt.submit({
881                    text:
882                      `From the Agent Cats dashboard, the user wants a new skill for: "${need}". ` +
883                      'Search the skill and plugin catalogs (SearchSkills, SearchPlugins), then show the fitting results ' +
884                      'as install cards (SuggestSkills, SuggestPluginInstall) so the user approves the install. Do not install anything yourself.',
885                  })
886                  $.ui.toast(`🐱 ${t.searchToast}`)
887                }
888              }}
889            />
890          )}
891        </Box>
892
893        {waits.length > 0 && (
894          <Box flexDirection="column" gap={1} borderStyle="round" borderColor="#E76F51" paddingX={1}>
895            <Text bold color="#E76F51">{t.needsYou}</Text>
896            {waits.map(p => {
897              const who = byId(p.agentId)
898              const color = who?.color ?? MAIN_COLOR
899              const name = who?.nickname || who?.label || (p.agentId === MAIN ? t.mainAgent : p.agentId)
900              const head = (
901                <Box flexDirection="row" gap={1} alignItems="center">
902                  {cat(color, false, `ask-cat-${p.id}`)}
903                  <Text bold>{name}</Text>
904                  <Text dimColor>{t.waited(elapsed(p.askedAt, now))}</Text>
905                </Box>
906              )
907
908              if (p.kind === 'permission') {
909                return (
910                  <Box key={`wait-${p.id}`} flexDirection="column">
911                    {head}
912                    <Text>{t.wantsTool(p.tool ?? '', p.detail ?? '')}</Text>
913                    <Text dimColor>{t.permissionNote}</Text>
914                  </Box>
915                )
916              }
917
918              const isOrphan = !resolvers.has(p.id)
919              const isNative = nativeIds.includes(p.id)
920              const isReady = p.questions.every((_, i) => answerOf(p, i) !== '')
921
922              return (
923                <Box key={`wait-${p.id}`} flexDirection="column" gap={1}>
924                  {head}
925                  {p.questions.map((q, i) => (
926                    <Box key={`q-${p.id}-${i}`} flexDirection="column">
927                      <Text>
928                        {q.header ? `[${q.header}] ` : ''}
929                        {q.question}
930                      </Text>
931                      {q.kind === 'choice' && (
932                        <Box flexDirection="row" flexWrap="wrap" gap={1}>
933                          {q.options.map((label, j) => (
934                            <Button
935                              key={`opt-${p.id}-${i}-${j}`}
936                              label={`${(p.picks[i] ?? []).includes(label) ? '✓ ' : ''}${label}`}
937                              variant={(p.picks[i] ?? []).includes(label) ? 'primary' : 'secondary'}
938                              onPress={() => pick(p, i, label)}
939                            />
940                          ))}
941                        </Box>
942                      )}
943                      {Input && (
944                        <Input
945                          key={`other-${p.id}-${i}`}
946                          placeholder={q.kind === 'choice' ? t.otherPlaceholder : t.answerPlaceholder}
947                          value={p.others[i] ?? ''}
948                          submitLabel={t.confirm}
949                          onSubmit={value => typeOther(p, i, value)}
950                        />
951                      )}
952                    </Box>
953                  ))}
954                  {isOrphan || isNative ? (
955                    <Text dimColor>{t.answerNatively}</Text>
956                  ) : (
957                    <Box flexDirection="row" gap={1}>
958                      <Button
959                        key={`send-${p.id}`}
960                        label={isReady ? t.send : t.sendIncomplete}
961                        variant="primary"
962                        dimColor={!isReady}
963                        onPress={() => {
964                          if (isReady) {
965                            send(p)
966                          }
967                        }}
968                      />
969                      <Button
970                        key={`use-native-${p.id}`}
971                        label={t.useNative}
972                        onPress={() => update($, native, list => [...(list ?? []), p.id])}
973                      />
974                    </Box>
975                  )}
976                </Box>
977              )
978            })}
979          </Box>
980        )}
981
982        {visible.length === 0 && <Text dimColor>{rows.length === 0 ? t.noAgents : t.noneInView}</Text>}
983        {visible.map(r => (
984          <Box key={`agent-${r.id}`} flexDirection="column" borderStyle="round" borderColor={r.color} paddingX={1}>
985            <Box flexDirection="row" gap={1} alignItems="center">
986              {cat(r.color, r.status !== 'working', `cat-${r.id}`)}
987              <Text bold wrap="truncate-end">
988                {r.nickname || r.label || t.mainAgent}
989              </Text>
990              {editing !== r.id && (
991                <Button key={`rename-btn-${r.id}`} label={t.rename} plain onPress={() => update($, renaming, () => r.id)} />
992              )}
993            </Box>
994            {r.nickname && r.label && (
995              <Text dimColor wrap="truncate-end">
996                {t.taskLabel(r.label)}
997              </Text>
998            )}
999            {Input && editing === r.id && (
1000              <Box flexDirection="row" gap={1}>
1001                <Input
1002                  key={`rename-${r.id}`}
1003                  placeholder={t.renamePlaceholder}
1004                  value={r.nickname ?? ''}
1005                  submitLabel={t.renameSubmit}
1006                  autoFocus
1007                  onSubmit={value => {
1008                    const nickname = value.trim().slice(0, 40)
1009                    void patchAgent($, r.id, row => ({ ...row, nickname: nickname || undefined }))
1010                    void update($, renaming, () => '')
1011                  }}
1012                />
1013                <Button key={`rename-cancel-${r.id}`} label={t.cancel} plain onPress={() => update($, renaming, () => '')} />
1014              </Box>
1015            )}
1016            <Box flexDirection="row" gap={2} flexWrap="wrap">
1017              <Text color={STATUS_COLOR[r.status]}>{t.status[r.status]}</Text>
1018              <Text dimColor>⏱ {r.startedAt ? elapsed(r.startedAt, r.endedAt ?? now) : '--:--'}</Text>
1019              <Text dimColor>{r.type}</Text>
1020              {r.tool && <Text color="#4D96FF">{t.usingTool(r.tool)}</Text>}
1021            </Box>
1022            {r.isStopped && <Text color="#E76F51">{t.stoppedNote}</Text>}
1023            {r.status === 'working' && !r.isStopped && stopping !== r.id && (
1024              <Box flexDirection="row" gap={1}>
1025                <Button key={`stop-${r.id}`} label={t.stop} onPress={() => update($, confirmStop, () => r.id)} />
1026              </Box>
1027            )}
1028            {r.status === 'working' && !r.isStopped && stopping === r.id && (
1029              <Box flexDirection="row" gap={1} alignItems="center" flexWrap="wrap">
1030                <Text color="#E76F51">{t.stopConfirm(nameOf(r))}</Text>
1031                <Button
1032                  key={`stop-yes-${r.id}`}
1033                  label={t.stopYes}
1034                  variant="primary"
1035                  onPress={async () => {
1036                    await update($, confirmStop, () => '')
1037                    await stopAgent($, r)
1038                  }}
1039                />
1040                <Button key={`stop-no-${r.id}`} label={t.cancel} plain onPress={() => update($, confirmStop, () => '')} />
1041              </Box>
1042            )}
1043            <Text dimColor={r.skills.length === 0}>
1044              {t.skillsUsed(r.skills.length > 0 ? r.skills.join(t.skillsSeparator) : t.skillsNone)}
1045            </Text>
1046            {Select && (r.status !== 'closed' || r.isStopped) && installed.length > 0 && (
1047              <Select
1048                key={`give-${r.id}`}
1049                label={t.giveSkill}
1050                value={PICK_HINT}
1051                options={skillOptions(installed, filter, t.giveSkillHint)}
1052                onSelect={value => {
1053                  if (value !== PICK_HINT) {
1054                    void giveSkill($, r, value)
1055                  }
1056                }}
1057              />
1058            )}
1059            {r.status === 'sleeping' && r.id !== MAIN && (
1060              <Box flexDirection="column">
1061                {Input && r.name && (
1062                  <Input
1063                    key={`wake-${r.id}`}
1064                    placeholder={t.wakePlaceholder}
1065                    submitLabel={t.wakeSubmit}
1066                    onSubmit={value => {
1067                      const task = value.trim()
1068                      if (task && r.name) {
1069                        void $.prompt.submit({
1070                          text: `Use SendMessage to wake the agent "${r.name}" (${r.label}) and give it this follow-up task: ${task}`,
1071                        })
1072                      }
1073                    }}
1074                  />
1075                )}
1076                <Button
1077                  key={`close-${r.id}`}
1078                  label={t.closeCat}
1079                  plain
1080                  onPress={() =>
1081                    patchAgent($, r.id, row => ({ ...row, status: 'closed', isHidden: true }))
1082                  }
1083                />
1084              </Box>
1085            )}
1086            {r.id !== MAIN && stopping !== `delete:${r.id}` && (
1087              <Button
1088                key={`delete-${r.id}`}
1089                label={t.deleteCat}
1090                plain
1091                onPress={() =>
1092                  r.status === 'working' && !r.isStopped
1093                    ? update($, confirmStop, () => `delete:${r.id}`)
1094                    : deleteAgent($, r)
1095                }
1096              />
1097            )}
1098            {r.id !== MAIN && stopping === `delete:${r.id}` && (
1099              <Box flexDirection="row" gap={1} alignItems="center" flexWrap="wrap">
1100                <Text color="#E76F51">{t.deleteConfirm(nameOf(r))}</Text>
1101                <Button
1102                  key={`delete-yes-${r.id}`}
1103                  label={t.deleteYes}
1104                  variant="primary"
1105                  onPress={async () => {
1106                    await update($, confirmStop, () => '')
1107                    await deleteAgent($, r)
1108                  }}
1109                />
1110                <Button key={`delete-no-${r.id}`} label={t.cancel} plain onPress={() => update($, confirmStop, () => '')} />
1111              </Box>
1112            )}
1113          </Box>
1114        ))}
1115        {hiddenClosed && (
1116          <Button
1117            key="clear-closed"
1118            label={t.hideClosed}
1119            plain
1120            onPress={() =>
1121              update($, agents, list => (list ?? []).map(r => (r.status === 'closed' ? { ...r, isHidden: true } : r)))
1122            }
1123          />
1124        )}
1125      </Box>
1126    )
1127  })
1128}
1129
hooks/strings.ts 220 lines
1// The dashboard's words, one table per language the `language` option offers.
2// Text the model reads (prompts, denials) stays English in both: it is for the model.
3
4export type Language = 'en' | 'zh-Hant'
5
6export type Strings = {
7  title: string
8  commandDescription: string
9  mainAgent: string
10  status: { working: string; sleeping: string; closed: string }
11  counts: { all: string; working: string; sleeping: string; waiting: string }
12  noneInView: string
13  stop: string
14  stopConfirm: (name: string) => string
15  stopYes: string
16  stopFailed: (name: string, reason: string) => string
17  stoppedToast: (name: string) => string
18  stoppedNote: string
19  deleteCat: string
20  deleteConfirm: (name: string) => string
21  deleteYes: string
22  doneToast: (name: string) => string
23  meowQuestion: string
24  meowPlan: string
25  meowPermission: (tool: string) => string
26  pointer: (title: string) => string
27  answerHere: string
28  skillsHeading: string
29  modeOnly: string
30  modePrefer: string
31  reloadList: string
32  noneChosen: string
33  clearAll: string
34  filterPlaceholder: (count: number) => string
35  filterSubmit: string
36  addSkill: string
37  pickInstalled: string
38  noMatch: (filter: string) => string
39  moreHidden: (hint: string, hidden: number) => string
40  noSkillsFound: string
41  searchPlaceholder: string
42  searchSubmit: string
43  searchToast: string
44  needsYou: string
45  waited: (time: string) => string
46  wantsTool: (tool: string, detail: string) => string
47  permissionNote: string
48  otherPlaceholder: string
49  answerPlaceholder: string
50  confirm: string
51  answerNatively: string
52  send: string
53  sendIncomplete: string
54  useNative: string
55  noAgents: string
56  rename: string
57  renamePlaceholder: string
58  renameSubmit: string
59  cancel: string
60  taskLabel: (task: string) => string
61  usingTool: (tool: string) => string
62  skillsUsed: (list: string) => string
63  skillsNone: string
64  skillsSeparator: string
65  giveSkill: string
66  giveSkillHint: string
67  wakePlaceholder: string
68  wakeSubmit: string
69  closeCat: string
70  hideClosed: string
71  skillGiven: (name: string, skill: string) => string
72  skillNotGiven: (name: string) => string
73  opened: string
74}
75
76export const STRINGS: Record<Language, Strings> = {
77  en: {
78    title: 'Agent Cats',
79    commandDescription: 'Open the Agent Cats dashboard',
80    mainAgent: 'Main agent',
81    status: { working: 'Working', sleeping: 'Asleep (can be woken)', closed: 'Done' },
82    counts: { all: 'All', working: 'Working', sleeping: 'Asleep', waiting: 'Waiting for you' },
83    noneInView: 'No cats in this view.',
84    stop: '■ Stop',
85    stopConfirm: name => `Stop "${name}"? Its current work ends now.`,
86    stopYes: 'Stop it',
87    stopFailed: (name, reason) => `Could not stop "${name}": ${reason}`,
88    stoppedToast: name => `Stopped "${name}". Hand it a skill to resume.`,
89    stoppedNote: 'Stopped: hand it a skill (+Skill) to resume',
90    deleteCat: '🗑 Delete',
91    deleteConfirm: name => `Delete "${name}"? It is still working: it is stopped first, then removed.`,
92    deleteYes: 'Stop and delete',
93    doneToast: name => `"${name}" finished its task`,
94    meowQuestion: 'An agent has a question for you: answer it in the Agent Cats dashboard',
95    meowPlan: 'A plan is waiting for your approval',
96    meowPermission: tool => `An agent wants to use ${tool} and is waiting for your approval`,
97    pointer: title => `Answer this question in the ${title} dashboard.`,
98    answerHere: 'Answer here',
99    skillsHeading: 'Skills for this task',
100    modeOnly: 'Mode: only the chosen ones',
101    modePrefer: 'Mode: prefer the chosen ones',
102    reloadList: 'Refresh list',
103    noneChosen: 'None chosen (every skill works as usual)',
104    clearAll: 'Clear all',
105    filterPlaceholder: count => `Filter skills (${count} in all): type a keyword, then Enter`,
106    filterSubmit: 'Filter',
107    addSkill: 'Add a skill: ',
108    pickInstalled: '— Pick an installed skill —',
109    noMatch: filter => `— No skill matches "${filter}" —`,
110    moreHidden: (hint, hidden) => `${hint} (${hidden} more: type above to filter)`,
111    noSkillsFound: 'No installed skills found. Try "Refresh list".',
112    searchPlaceholder: 'Find a new skill: say what you need, Enter asks the main agent to search',
113    searchSubmit: 'Search',
114    searchToast: 'Asked the main agent to look for a skill',
115    needsYou: 'Needs your reply',
116    waited: time => `waiting ${time}`,
117    wantsTool: (tool, detail) => `wants to use ${tool}${detail ? `: ${detail}` : ''}`,
118    permissionNote: 'Choose Allow / Deny in the permission dialog (only the native dialog can grant a permission).',
119    otherPlaceholder: 'Other (type your own, Enter to confirm)',
120    answerPlaceholder: 'Your answer (Enter to confirm)',
121    confirm: 'Confirm',
122    answerNatively: 'Answer in the native dialog.',
123    send: 'Send answers',
124    sendIncomplete: 'Send answers (not all answered)',
125    useNative: 'Use the native dialog',
126    noAgents: 'No agents yet.',
127    rename: '✎ Rename',
128    renamePlaceholder: 'New name (empty: back to the task name)',
129    renameSubmit: 'Rename',
130    cancel: 'Cancel',
131    taskLabel: task => `Task: ${task}`,
132    usingTool: tool => `using ${tool}`,
133    skillsUsed: list => `Skills: ${list}`,
134    skillsNone: 'none yet',
135    skillsSeparator: ', ',
136    giveSkill: '+Skill: ',
137    giveSkillHint: '— Hand it a skill —',
138    wakePlaceholder: 'Give it a new task, Enter wakes it',
139    wakeSubmit: 'Wake',
140    closeCat: 'No need to wake it again: close',
141    hideClosed: 'Hide the finished cats',
142    skillGiven: (name, skill) => `Asked "${name}" to use ${skill}`,
143    skillNotGiven: name => `${name} has finished: cannot hand it a skill`,
144    opened: 'Agent Cats dashboard opened.',
145  },
146  'zh-Hant': {
147    title: 'Agent 貓貓',
148    commandDescription: '打開 Agent 貓貓 dashboard',
149    mainAgent: '主 agent',
150    status: { working: '工作中', sleeping: '休眠(可喚醒)', closed: '已結束' },
151    counts: { all: '全部', working: '工作中', sleeping: '休眠', waiting: '等你回覆' },
152    noneInView: '呢個分類冇貓。',
153    stop: '■ 停止',
154    stopConfirm: name => `確定停止「${name}」?佢而家做緊嘅嘢會即刻停。`,
155    stopYes: '確定停止',
156    stopFailed: (name, reason) => `停唔到「${name}」:${reason}`,
157    stoppedToast: name => `已停止「${name}」,交個 skill 俾佢就會恢復工作。`,
158    stoppedNote: '已停止:用「+Skill」交個 skill 俾佢就會恢復工作',
159    deleteCat: '🗑 刪除',
160    deleteConfirm: name => `確定刪除「${name}」?佢仲做緊嘢:會先停咗佢,再清走。`,
161    deleteYes: '停止並刪除',
162    doneToast: name => `「${name}」完成咗任務`,
163    meowQuestion: '有 agent 問你問題,喺 Agent 貓貓 dashboard 答',
164    meowPlan: '有個計劃等緊你批准',
165    meowPermission: tool => `有 agent 想用 ${tool},等你批准`,
166    pointer: title => `呢條問題請喺「${title}」dashboard 回答。`,
167    answerHere: '喺呢度答',
168    skillsHeading: '今次任務用嘅 skills',
169    modeOnly: '模式:只准用揀咗嘅',
170    modePrefer: '模式:優先用揀咗嘅',
171    reloadList: '重新整理清單',
172    noneChosen: '未揀(全部 skills 照常可用)',
173    clearAll: '全部清除',
174    filterPlaceholder: count => `篩選 skill(共 ${count} 個),打關鍵字再 Enter`,
175    filterSubmit: '篩選',
176    addSkill: '加入 skill:',
177    pickInstalled: '— 揀一個已安裝嘅 skill —',
178    noMatch: filter => `— 冇 skill 符合「${filter}」—`,
179    moreHidden: (hint, hidden) => `${hint}(仲有 ${hidden} 個,喺上面打字篩選)`,
180    noSkillsFound: '搵唔到已安裝嘅 skills,試吓撳「重新整理清單」。',
181    searchPlaceholder: '搵新 skill:講你想做乜,Enter 叫主 agent 去搵',
182    searchSubmit: '搵',
183    searchToast: '已經叫主 agent 去搵 skill',
184    needsYou: '需要你回覆',
185    waited: time => `等咗 ${time}`,
186    wantsTool: (tool, detail) => `想用 ${tool}${detail ? `:${detail}` : ''}`,
187    permissionNote: '請喺權限對話框揀 Allow / Deny(權限只可以由原生對話框批准)。',
188    otherPlaceholder: '其他(自己打,Enter 確認)',
189    answerPlaceholder: '你嘅答案(Enter 確認)',
190    confirm: '確認',
191    answerNatively: '請喺原生對話框回答。',
192    send: '送出答案',
193    sendIncomplete: '送出答案(未答晒)',
194    useNative: '改用原生對話框',
195    noAgents: '未有 agent。',
196    rename: '✎ 改名',
197    renamePlaceholder: '新名(留空就用返原本嘅任務名)',
198    renameSubmit: '改名',
199    cancel: '取消',
200    taskLabel: task => `任務:${task}`,
201    usingTool: tool => `用緊 ${tool}`,
202    skillsUsed: list => `Skills:${list}`,
203    skillsNone: '未用',
204    skillsSeparator: '、',
205    giveSkill: '+Skill:',
206    giveSkillHint: '— 交一個 skill 俾佢 —',
207    wakePlaceholder: '交代新工作,Enter 喚醒佢',
208    wakeSubmit: '喚醒',
209    closeCat: '唔使再喚醒,關閉佢',
210    hideClosed: '收埋已結束嘅貓',
211    skillGiven: (name, skill) => `已經叫「${name}」用 ${skill}`,
212    skillNotGiven: name => `${name} 已經結束,交唔到 skill`,
213    opened: 'Agent 貓貓 dashboard 已打開。',
214  },
215}
216
217export function languageOf(value: unknown): Language {
218  return value === 'zh-Hant' ? 'zh-Hant' : 'en'
219}
220
types/index.d.ts 68 lines
1export type CatStatus = 'working' | 'sleeping' | 'closed'
2
3/** Which cats the dashboard lists: all, or only those working, asleep or waiting for the person. */
4export type CatView = 'all' | 'working' | 'sleeping' | 'waiting'
5
6/** `prefer`: the chosen skills are suggested; `only`: any other skill is refused. */
7export type SkillMode = 'prefer' | 'only'
8
9export type CatAgent = {
10  id: string
11  label: string
12  /** The name the person gave the cat in the dashboard; shown before `label`. */
13  nickname?: string
14  type: string
15  name?: string
16  status: CatStatus
17  rawStatus: string
18  color: string
19  startedAt: number
20  endedAt?: number
21  skills: string[]
22  tool?: string
23  isHidden?: boolean
24  /** Stopped from the dashboard: not a finished task (no chime); a skill handed to it resumes it. */
25  isStopped?: boolean
26}
27
28export type CatQuestion = {
29  question: string
30  header: string
31  kind: 'choice' | 'text' | 'number'
32  isMulti: boolean
33  options: string[]
34}
35
36export type CatPending = {
37  id: string
38  kind: 'question' | 'permission'
39  agentId: string
40  askedAt: number
41  questions: CatQuestion[]
42  picks: string[][]
43  others: string[]
44  tool?: string
45  detail?: string
46}
47
48declare module 'claude-code' {
49  interface PluginState {
50    'agent-cats': {
51      agents: CatAgent[]
52      pending: CatPending[]
53      now: number
54      native: string[]
55      skills: string[]
56      activeSkills: string[]
57      skillMode: SkillMode
58      skillFilter: string
59      renaming: string
60      view: CatView
61      /** The cat whose Stop waits for the person's confirmation (`delete:<id>` for a Delete of a working cat), or ''. */
62      confirmStop: string
63      /** Cats deleted from the dashboard: never listed again, even while the engine still lists them. */
64      deleted: string[]
65    }
66  }
67}
68